diff --git a/.eslintrc.json b/.eslintrc.json index 37a0caeb2..b86a14dbf 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,62 +1,69 @@ { - "plugins": ["jest", "@typescript-eslint"], - "extends": ["plugin:github/recommended", "prettier"], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 9, - "sourceType": "module", - "project": "./tsconfig.eslint.json" - }, - "rules": { - "eslint-comments/no-use": "off", - "import/no-namespace": "off", - "no-unused-vars": "off", - "camelcase": "off", - "@typescript-eslint/no-unused-vars": "error", - "@typescript-eslint/explicit-member-accessibility": ["error", {"accessibility": "no-public"}], - "@typescript-eslint/no-require-imports": "error", - "@typescript-eslint/array-type": "error", - "@typescript-eslint/await-thenable": "error", - "@typescript-eslint/ban-ts-comment": "error", - "@typescript-eslint/consistent-type-assertions": "error", - "@typescript-eslint/explicit-function-return-type": ["error", {"allowExpressions": true}], - "@typescript-eslint/func-call-spacing": ["error", "never"], - "@typescript-eslint/no-array-constructor": "error", - "@typescript-eslint/no-empty-interface": "error", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-extraneous-class": "error", - "@typescript-eslint/no-for-in-array": "error", - "@typescript-eslint/no-inferrable-types": "error", - "@typescript-eslint/no-misused-new": "error", - "@typescript-eslint/no-namespace": "error", - "@typescript-eslint/no-non-null-assertion": "warn", - "@typescript-eslint/no-unnecessary-qualifier": "error", - "@typescript-eslint/no-unnecessary-type-assertion": "error", - "@typescript-eslint/no-useless-constructor": "error", - "@typescript-eslint/no-var-requires": "error", - "@typescript-eslint/prefer-for-of": "warn", - "@typescript-eslint/prefer-function-type": "warn", - "@typescript-eslint/prefer-includes": "error", - "@typescript-eslint/prefer-string-starts-ends-with": "error", - "@typescript-eslint/promise-function-async": "error", - "@typescript-eslint/require-array-sort-compare": "error", - "@typescript-eslint/restrict-plus-operands": "error", - "@typescript-eslint/type-annotation-spacing": "error", - "@typescript-eslint/unbound-method": "error", - "@typescript-eslint/no-shadow": "error", - "no-shadow": "off" - }, - "overrides": [ - { - "files": ["*.ts"], - "rules": { - "no-undef": "off" - } + "plugins": ["github", "jest", "@typescript-eslint"], + "extends": ["plugin:github/recommended", "plugin:github/typescript", "prettier"], + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaVersion": 9, + "sourceType": "module", + "project": "./tsconfig.eslint.json" + }, + "settings": { + "import/resolver": { + "typescript": {} + } + }, + "rules": { + "eslint-comments/no-use": "off", + "import/no-namespace": "off", + "no-unused-vars": "off", + "camelcase": "off", + "@typescript-eslint/no-unused-vars": "error", + "@typescript-eslint/explicit-member-accessibility": ["error", {"accessibility": "no-public"}], + "@typescript-eslint/no-require-imports": "error", + "@typescript-eslint/array-type": "error", + "@typescript-eslint/await-thenable": "error", + "@typescript-eslint/ban-ts-comment": "error", + "@typescript-eslint/consistent-type-assertions": "error", + "@typescript-eslint/explicit-function-return-type": ["error", {"allowExpressions": true}], + "@typescript-eslint/func-call-spacing": ["error", "never"], + "@typescript-eslint/no-array-constructor": "error", + "@typescript-eslint/no-empty-interface": "error", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-extraneous-class": "error", + "@typescript-eslint/no-for-in-array": "error", + "@typescript-eslint/no-inferrable-types": "error", + "@typescript-eslint/no-misused-new": "error", + "@typescript-eslint/no-namespace": "error", + "@typescript-eslint/no-non-null-assertion": "warn", + "@typescript-eslint/no-unnecessary-qualifier": "error", + "@typescript-eslint/no-unnecessary-type-assertion": "error", + "@typescript-eslint/no-useless-constructor": "error", + "@typescript-eslint/no-var-requires": "error", + "@typescript-eslint/prefer-for-of": "warn", + "@typescript-eslint/prefer-function-type": "warn", + "@typescript-eslint/prefer-includes": "error", + "@typescript-eslint/prefer-string-starts-ends-with": "error", + "@typescript-eslint/promise-function-async": "error", + "@typescript-eslint/require-array-sort-compare": "error", + "@typescript-eslint/restrict-plus-operands": "error", + "@typescript-eslint/type-annotation-spacing": "error", + "@typescript-eslint/unbound-method": "error", + "@typescript-eslint/no-shadow": "error", + "no-shadow": "off", + "i18n-text/no-en": "off", + "filenames/match-regex": "off" + }, + "overrides": [ + { + "files": ["*.ts"], + "rules": { + "no-undef": "off" } - ], - "env": { - "node": true, - "es6": true, - "jest/globals": true } + ], + "env": { + "node": true, + "es6": true, + "jest/globals": true } +} diff --git a/.github/dependabot.yml b/.github/dependabot.yml index cb6c35881..5e4435771 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,21 +1,54 @@ version: 2 updates: - - package-ecosystem: 'docker' - directory: '/docker' + - package-ecosystem: "docker" + directory: "/docker" + open-pull-requests-limit: 20 schedule: - interval: 'daily' + interval: "weekly" + day: "sunday" + time: "22:00" registries: - ghcr + labels: + - dependencies + - docker + - Fanout + groups: + dependabot-core-images: + patterns: + - dependabot/* - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "monthly" - - package-ecosystem: 'npm' - directory: '/' + interval: "weekly" + day: "sunday" + time: "22:00" + labels: + - dependencies + - github_actions + - Fanout + - package-ecosystem: "npm" + directory: "/" open-pull-requests-limit: 20 schedule: - interval: 'monthly' - + interval: "weekly" + day: "sunday" + time: "22:00" + labels: + - dependencies + - javascript + - Fanout + groups: + dev-dependencies: + dependency-type: "development" + update-types: + - "patch" + - "minor" + prod-dependencies: + dependency-type: "production" + update-types: + - "patch" + - "minor" registries: ghcr: type: docker-registry diff --git a/.github/workflows/check-dist.yml b/.github/workflows/check-dist.yml index 802610a3a..5692b830f 100644 --- a/.github/workflows/check-dist.yml +++ b/.github/workflows/check-dist.yml @@ -12,18 +12,14 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} - - name: Read .nvmrc - id: nvm - run: echo ::set-output name=NVMRC::$(cat .nvmrc) - - name: Setup Node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: - node-version: ${{ steps.nvm.outputs.NVMRC }} + node-version-file: .nvmrc - name: Install npm dependencies run: npm clean-install @@ -36,7 +32,7 @@ jobs: verify-index-js: # make sure the entrypoint js files run on a clean machine without compiling first runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 4213e56f0..1cf9d5a73 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -23,14 +23,14 @@ jobs: language: [ 'javascript' ] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml index 0fa8de4d8..5f729f57d 100644 --- a/.github/workflows/dependabot-auto-merge.yml +++ b/.github/workflows/dependabot-auto-merge.yml @@ -9,7 +9,7 @@ jobs: if: ${{ github.event.pull_request.user.login == 'dependabot[bot]' }} steps: - name: Fetch metadata - uses: dependabot/fetch-metadata@v1.3.4 + uses: dependabot/fetch-metadata@dbb049abf0d677abbd7f7eee0375145b417fdd34 # v2.2.0 # Enable the automerge using a PAT so the merge commits trigger workflows - name: Auto-merge diff --git a/.github/workflows/dependabot-build.yml b/.github/workflows/dependabot-build.yml index bbd36cade..e4d5a3d25 100644 --- a/.github/workflows/dependabot-build.yml +++ b/.github/workflows/dependabot-build.yml @@ -20,7 +20,7 @@ jobs: steps: - name: Fetch dependabot metadata id: dependabot-metadata - uses: dependabot/fetch-metadata@v1.3.4 + uses: dependabot/fetch-metadata@dbb049abf0d677abbd7f7eee0375145b417fdd34 # v2.2.0 with: github-token: "${{ secrets.GITHUB_TOKEN }}" build-dependabot-changes: @@ -30,19 +30,15 @@ jobs: if: needs.fetch-dependabot-metadata.outputs.package-ecosystem == 'docker' || needs.fetch-dependabot-metadata.outputs.package-ecosystem == 'npm_and_yarn' steps: # Check out using a PAT so any pushed changes will trigger checkruns - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.ref }} token: ${{ secrets.DEPENDABOT_AUTOBUILD }} - - name: Read .nvmrc - id: nvm - run: echo ::set-output name=NVMRC::$(cat .nvmrc) - - name: Setup Node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: - node-version: ${{ steps.nvm.outputs.NVMRC }} + node-version-file: .nvmrc - name: Install npm dependencies run: npm clean-install @@ -61,7 +57,8 @@ jobs: - name: Check in any change to dist/ run: | git add dist/ - git config user.name github-actions - git config user.email github-actions@github.com + # Specifying the full email allows the avatar to show up: https://github.com/orgs/community/discussions/26560 + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git commit -m "[dependabot skip] Update dist/ with build changes" || exit 0 git push diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index e9c6fafd3..965265e5c 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -13,24 +13,22 @@ jobs: integration: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} - - name: Read .nvmrc - id: nvm - run: echo ::set-output name=NVMRC::$(cat .nvmrc) - - name: Setup Node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: - node-version: ${{ steps.nvm.outputs.NVMRC }} + node-version-file: .nvmrc - name: Install npm dependencies run: npm clean-install - name: Pre-fetch the pinned images - run: npm run fetch-images + run: npm run fetch-images -- bundler - name: Run integration tests run: npm run test-integration + env: + GITHUB_TOKEN: ${{ github.token }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9a7b3d23c..aaa5d8360 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,18 +11,14 @@ jobs: test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} - - name: Read .nvmrc - id: nvm - run: echo ::set-output name=NVMRC::$(cat .nvmrc) - - name: Setup Node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: - node-version: ${{ steps.nvm.outputs.NVMRC }} + node-version-file: .nvmrc - name: Install npm dependencies run: npm clean-install diff --git a/.node-version b/.node-version new file mode 120000 index 000000000..56976b9a7 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +.nvmrc \ No newline at end of file diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000..09b35cdd0 --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +audit=false +fund=false diff --git a/.nvmrc b/.nvmrc index 3027af39c..f3f52b42d 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -16.10.0 +20.9.0 diff --git a/.vscode/settings.json b/.vscode/settings.json index 5c7149e49..d75764eb0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,6 @@ { "editor.codeActionsOnSave": { - "source.fixAll.eslint": true + "source.fixAll.eslint": "explicit" }, "eslint.validate": ["javascript", "typescript"], "eslint.alwaysShowStatus": true, diff --git a/CODEOWNERS b/CODEOWNERS index 429be33f1..9c414e335 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1 +1 @@ -* @github/dsp-dependabot-reviewers +* @github/dependabot-updates-reviewers diff --git a/__tests__/api_client.test.ts b/__tests__/api_client.test.ts index d37b09c9e..9b4e3b420 100644 --- a/__tests__/api_client.test.ts +++ b/__tests__/api_client.test.ts @@ -1,20 +1,41 @@ import * as core from '@actions/core' -import {ApiClient, CredentialFetchingError} from '../src/api-client' +import { + ApiClient, + CredentialFetchingError, + JobDetailsFetchingError +} from '../src/api-client' +import {HttpClientError} from '@actions/http-client' describe('ApiClient', () => { - const mockAxios: any = { - get: jest.fn() + const mockHttpClient: any = { + getJson: jest.fn() } - const api = new ApiClient(mockAxios, { - jobId: 1, - jobToken: 'xxx', - credentialsToken: 'yyy', - dependabotApiUrl: 'https://localhost', - dependabotApiDockerUrl: 'https://localhost', - workingDirectory: './job-directory' - }) + + // Define jobToken and credentialsToken + const jobToken = 'xxx' + const credentialsToken = 'yyy' + + const api = new ApiClient( + mockHttpClient, + { + jobId: 1, + jobToken, + credentialsToken, + dependabotApiUrl: 'https://localhost', + dependabotApiDockerUrl: 'https://localhost', + updaterImage: '', // irrelevant for this test + workingDirectory: './job-directory' + }, + jobToken, + credentialsToken + ) beforeEach(jest.clearAllMocks) + test('getJobToken returns the correct job token', async () => { + const actualJobToken = api.getJobToken() + expect(actualJobToken).toBe(jobToken) + }) + test('get job details', async () => { const apiResponse = { data: { @@ -32,13 +53,92 @@ describe('ApiClient', () => { } } } - mockAxios.get.mockResolvedValue({status: 200, data: apiResponse}) + mockHttpClient.getJson.mockResolvedValue({ + statusCode: 200, + result: apiResponse + }) const jobDetails = await api.getJobDetails() expect(jobDetails['allowed-updates'].length).toBe(1) expect(jobDetails['package-manager']).toBe('npm_and_yarn') }) + test('job details errors', async () => { + const apiResponse = { + errors: [ + { + status: 400, + title: 'Bad Request', + detail: 'Update job has already been processed' + } + ] + } + mockHttpClient.getJson.mockRejectedValue( + new HttpClientError(JSON.stringify(apiResponse), 400) + ) + + await expect(api.getJobDetails()).rejects.toThrowError( + new JobDetailsFetchingError( + 'fetching job details: unexpected status code: 400: {"errors":[{"status":400,"title":"Bad Request","detail":"Update job has already been processed"}]}' + ) + ) + }) + + test('job details with certificate error', async () => { + mockHttpClient.getJson.mockRejectedValue( + new Error('unable to get local issuer certificate') + ) + + await expect(api.getJobDetails()).rejects.toThrowError( + new JobDetailsFetchingError( + 'fetching job details: Error: unable to get local issuer certificate' + ) + ) + }) + + test('job details retries on 500', async () => { + mockHttpClient.getJson.mockRejectedValueOnce( + new HttpClientError('retryable failure', 500) + ) + + const apiResponse = { + data: { + id: '1001', + type: 'update-jobs', + attributes: { + 'allowed-updates': [ + { + 'dependency-type': 'direct', + 'update-type': 'all' + } + ], + dependencies: null, + 'package-manager': 'npm_and_yarn' + } + } + } + mockHttpClient.getJson.mockResolvedValue({ + statusCode: 200, + result: apiResponse + }) + + const jobDetails = await api.getJobDetails() + expect(jobDetails['allowed-updates'].length).toBe(1) + expect(jobDetails['package-manager']).toBe('npm_and_yarn') + }) + + test('job details gives up on too many 500s', async () => { + mockHttpClient.getJson.mockRejectedValue( + new HttpClientError('retryable failure', 500) + ) + + await expect(api.getJobDetails()).rejects.toThrowError( + new JobDetailsFetchingError( + 'fetching job details: unexpected status code: 500: retryable failure' + ) + ) + }, 10000) + test('get job credentials', async () => { const apiResponse = { data: { @@ -76,7 +176,10 @@ describe('ApiClient', () => { } } } - mockAxios.get.mockResolvedValue({status: 200, data: apiResponse}) + mockHttpClient.getJson.mockResolvedValue({ + statusCode: 200, + result: apiResponse + }) jest.spyOn(core, 'setSecret').mockImplementation(jest.fn()) const jobCredentials = await api.getCredentials() @@ -100,13 +203,12 @@ describe('ApiClient', () => { ] } - mockAxios.get.mockRejectedValue({ - isAxiosError: true, - response: {status: 422, data: apiResponse} - }) + mockHttpClient.getJson.mockRejectedValue( + new HttpClientError(JSON.stringify(apiResponse), 422) + ) await expect(api.getCredentials()).rejects.toThrowError( new CredentialFetchingError( - 'fetching credentials: received code 422: {"errors":[{"status":422,"title":"Secret Not Found","detail":"MISSING_SECRET_NAME"}]}' + 'fetching credentials: unexpected status code: 422: {"errors":[{"status":422,"title":"Secret Not Found","detail":"MISSING_SECRET_NAME"}]}' ) ) }) diff --git a/__tests__/cleanup-integration.test.ts b/__tests__/cleanup-integration.test.ts index d20116aff..64684f014 100644 --- a/__tests__/cleanup-integration.test.ts +++ b/__tests__/cleanup-integration.test.ts @@ -3,6 +3,7 @@ import Docker from 'dockerode' import {ImageService} from '../src/image-service' import {integration, delay} from './helpers' import {run, cleanupOldImageVersions} from '../src/cleanup' +import {PROXY_IMAGE_NAME, digestName} from '../src/docker-tags' integration('run', () => { beforeEach(async () => { @@ -17,19 +18,13 @@ integration('run', () => { }) integration('cleanupOldImageVersions', () => { - // We use this GitHub-hosted hello world example as a small stand-in for this test - // in order to avoid hitting the rate limit on pulling containers from docker.io - // since this test needs to remove and pull containers per run. - const testImage = 'ghcr.io/github/hello-docker' const docker = new Docker() const imageOptions = { - filters: { - reference: [testImage] - } + filters: `{"reference":["ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy"]}` } - const currentImage = `${testImage}@sha256:f32f4412fa4b6c7ece72cb85ae652751f11ac0d075c1131df09bb24f46b2f4e3` - const oldImage = `${testImage}@sha256:8cfee63309567569d3d7d0edc05fcf8be8f9f5130f0564dacea4cfe82a9db4b7` + const currentImage = PROXY_IMAGE_NAME + const oldImage = `ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy:v2.0.20221204234507@sha256:c4d68b711d260099f5cfa06651910a613617d1c2b585361ac7139904e42a1f59` async function clearTestImages(): Promise { const testImages = await docker.listImages(imageOptions) @@ -54,8 +49,8 @@ integration('cleanupOldImageVersions', () => { }, 10000) test('it removes unused versions of the given image', async () => { - const imageCount = (await docker.listImages(imageOptions)).length - expect(imageCount).toEqual(2) + const initialImages = await docker.listImages(imageOptions) + expect(initialImages.length).toEqual(2) await cleanupOldImageVersions(docker, currentImage) // The Docker API seems to ack the removal before it is carried out, so let's wait briefly to ensure @@ -64,6 +59,23 @@ integration('cleanupOldImageVersions', () => { const remainingImages = await docker.listImages(imageOptions) expect(remainingImages.length).toEqual(1) - expect(remainingImages[0].RepoDigests?.includes(currentImage)) + expect( + remainingImages[0].RepoDigests?.includes(digestName(currentImage)) + ).toEqual(true) + }) + + test('it no-ops when disabled', async () => { + process.env.DEPENDABOT_DISABLE_CLEANUP = '1' + + const imageCount = (await docker.listImages(imageOptions)).length + expect(imageCount).toEqual(2) + + await run() + // The Docker API seems to ack the removal before it is carried out, so let's wait briefly to ensure + // the verification query doesn't race the deletion + await delay(200) + + const remainingImages = await docker.listImages(imageOptions) + expect(remainingImages.length).toEqual(2) }) }) diff --git a/__tests__/container-service.test.ts b/__tests__/container-service.test.ts index aefe4f190..da62dc683 100644 --- a/__tests__/container-service.test.ts +++ b/__tests__/container-service.test.ts @@ -23,6 +23,7 @@ describe('ContainerService', () => { }) }) + jest.setTimeout(5000) test('it returns true', async () => { expect(await ContainerService.run(container)).toBe(true) }) @@ -38,6 +39,7 @@ describe('ContainerService', () => { }) }) + jest.setTimeout(5000) test('raises an exception', async () => { await expect(ContainerService.run(container)).rejects.toThrow( /The updater encountered one or more errors/ diff --git a/__tests__/docker-tags.test.ts b/__tests__/docker-tags.test.ts index afcc7a32b..355aa7c0f 100644 --- a/__tests__/docker-tags.test.ts +++ b/__tests__/docker-tags.test.ts @@ -1,31 +1,41 @@ import { - UPDATER_IMAGE_NAME, + updaterImages, PROXY_IMAGE_NAME, + digestName, + hasDigest, repositoryName } from '../src/docker-tags' import {getImageName} from '../src/update-containers' describe('Docker tags', () => { - test('UPDATER_IMAGE_NAME uses a pinned version and matches the config Dockerfile', () => { - expect(UPDATER_IMAGE_NAME).toMatch( - /^ghcr\.io\/dependabot\/dependabot-updater@sha256:[a-zA-Z0-9]{64}$/ - ) + test('updater images use a pinned version and matches the config Dockerfile', () => { + for (const image of updaterImages()) { + expect(image).toMatch( + /^ghcr\.io\/dependabot\/dependabot-updater-[-\w]+:v\d.\d.\d{14}@sha256:[a-zA-Z0-9]{64}$/ + ) - expect(UPDATER_IMAGE_NAME).toEqual(getImageName('Dockerfile.updater')) + expect(image).toEqual( + getImageName( + `Dockerfile.${image.match(/dependabot-updater-([-\w]+)/)?.[1]}` + ) + ) + } }) test('PROXY_IMAGE_NAME uses a pinned version and matches the config Dockerfile', () => { expect(PROXY_IMAGE_NAME).toMatch( - /^ghcr\.io\/github\/dependabot-update-job-proxy\/dependabot-update-job-proxy@sha256:[a-zA-Z0-9]{64}$/ + /^ghcr\.io\/github\/dependabot-update-job-proxy\/dependabot-update-job-proxy:v\d.\d.\d{14}@sha256:[a-zA-Z0-9]{64}$/ ) expect(PROXY_IMAGE_NAME).toEqual(getImageName('Dockerfile.proxy')) }) - test('repositoryName returns the image name minus the tagged version or reference for our real values', () => { - expect(repositoryName(UPDATER_IMAGE_NAME)).toMatch( - 'ghcr.io/dependabot/dependabot-updater' - ) + test('repositoryName returns the image name minus the tagged version and reference for our real values', () => { + for (const image of updaterImages()) { + expect(repositoryName(image)).toMatch( + /^ghcr.io\/dependabot\/dependabot-updater-[-\w]+$/ + ) + } expect(repositoryName(PROXY_IMAGE_NAME)).toMatch( 'ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy' @@ -33,7 +43,7 @@ describe('Docker tags', () => { }) test('repositoryName handles named tags', () => { - // We currently use pinned SHA references instead of tags, but we should account for both notations + // We currently use pinned SHA references in addition to tags, but we should account for both notations // to avoid any surprises expect( repositoryName('docker.pkg.github.com/dependabot/dependabot-updater:v1') @@ -92,4 +102,36 @@ describe('Docker tags', () => { repositoryName('this-is-just-some-random-nonsense-with-a:in-it') ).toMatch('this-is-just-some-random-nonsense-with-a') }) + + test('digestName returns the image name and digest minus the tagged version or reference', () => { + expect( + digestName( + 'ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy:v2.0.20221206155623@sha256:1942aea0f57a3652d7694390dd4d8e6d08abca84b89383ee7ef9c6b57e00d247' + ) + ).toMatch( + 'ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy@sha256:1942aea0f57a3652d7694390dd4d8e6d08abca84b89383ee7ef9c6b57e00d247' + ) + + expect( + digestName( + 'ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy@sha256:1942aea0f57a3652d7694390dd4d8e6d08abca84b89383ee7ef9c6b57e00d247' + ) + ).toMatch( + 'ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy@sha256:1942aea0f57a3652d7694390dd4d8e6d08abca84b89383ee7ef9c6b57e00d247' + ) + }) + + test('hasDigest identifies when a digest is present', () => { + expect( + hasDigest( + 'ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy:v2.0.20221206155623@sha256:1942aea0f57a3652d7694390dd4d8e6d08abca84b89383ee7ef9c6b57e00d247' + ) + ).toEqual(true) + + expect( + hasDigest( + 'ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy:v1' + ) + ).toEqual(false) + }) }) diff --git a/__tests__/helpers.ts b/__tests__/helpers.ts index 6b76716d6..33713ca26 100644 --- a/__tests__/helpers.ts +++ b/__tests__/helpers.ts @@ -1,5 +1,5 @@ import Docker from 'dockerode' -import {UPDATER_IMAGE_NAME, PROXY_IMAGE_NAME} from '../src/docker-tags' +import {updaterImages, PROXY_IMAGE_NAME} from '../src/docker-tags' import waitPort from 'wait-port' import path from 'path' import {spawn} from 'child_process' @@ -10,7 +10,7 @@ export const removeDanglingUpdaterContainers = async (): Promise => { for (const container of containers) { if ( - container.Image.includes(UPDATER_IMAGE_NAME) || + updaterImages().includes(container.Image) || container.Image.includes(PROXY_IMAGE_NAME) ) { try { @@ -25,11 +25,15 @@ export const removeDanglingUpdaterContainers = async (): Promise => { await docker.pruneContainers() } -export const runFakeDependabotApi = async (port = 9000): Promise => { - const server = spawn('node', [ - `${path.join(__dirname, 'server/server.js')}`, - `${port}` - ]) +export const runFakeDependabotApi = async ( + port = 9000, + testRetry = false +): Promise<() => void> => { + const server = spawn( + 'node', + [`${path.join(__dirname, 'server/server.js')}`, `${port}`], + {env: {...process.env, TEST_RETRY: `${testRetry}`}} + ) server.stdout.on('data', (data: any) => { console.log(`json-server log: ${data}`) // eslint-disable-line no-console diff --git a/__tests__/inputs.test.ts b/__tests__/inputs.test.ts index 85d09c5a5..4f80837da 100644 --- a/__tests__/inputs.test.ts +++ b/__tests__/inputs.test.ts @@ -24,6 +24,7 @@ describe('when there is a fully configured Actions environment', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace context = new Context() @@ -51,6 +52,7 @@ describe('when there is no GITHUB_EVENT_NAME defined', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') delete process.env.GITHUB_EVENT_NAME process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace context = new Context() @@ -67,7 +69,7 @@ describe('when the GITHUB_EVENT_NAME is not "dynamic"', () => { beforeEach(() => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'issue_comment' - process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace context = new Context() @@ -85,6 +87,7 @@ describe('when there is no GITHUB_ACTOR defined', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' delete process.env.GITHUB_ACTOR + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace context = new Context() @@ -102,6 +105,43 @@ describe('when the GITHUB_ACTOR is not "dependabot[bot]"', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'classic-rando' + process.env.GITHUB_TRIGGERING_ACTOR = 'classic-rando' + process.env.GITHUB_WORKSPACE = workspace + + context = new Context() + }) + + test('it returns null', () => { + const params = getJobParameters(context) + + expect(params).toEqual(null) + }) +}) + +describe('when there is no GITHUB_TRIGGERING_ACTOR defined', () => { + beforeEach(() => { + process.env.GITHUB_EVENT_PATH = eventFixturePath('default') + process.env.GITHUB_EVENT_NAME = 'dynamic' + process.env.GITHUB_ACTOR = 'dependabot[bot]' + delete process.env.GITHUB_TRIGGERING_ACTOR + process.env.GITHUB_WORKSPACE = workspace + + context = new Context() + }) + + test('it returns a result', () => { + expect(() => { + getJobParameters(context) + }).toBeTruthy() + }) +}) + +describe('when the GITHUB_TRIGGERING_ACTOR is not "dependabot[bot]"', () => { + beforeEach(() => { + process.env.GITHUB_EVENT_PATH = eventFixturePath('default') + process.env.GITHUB_EVENT_NAME = 'dynamic' + process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'classic-rando' process.env.GITHUB_WORKSPACE = workspace context = new Context() @@ -119,6 +159,7 @@ describe('when there is no GITHUB_WORKSPACE defined', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' delete process.env.GITHUB_WORKSPACE context = new Context() @@ -138,6 +179,7 @@ describe('when the GITHUB_WORKSPACE path does not exist', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = path.join(workspace, randomFolderName) context = new Context() @@ -160,6 +202,7 @@ describe('when the GITHUB_WORKSPACE exists, but is a file', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = randomFileName fs.closeSync(fs.openSync(randomFileName, 'w')) @@ -183,6 +226,7 @@ describe('when the workingDirectory is a blank value', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('blank_working_directory') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace context = new Context() @@ -207,6 +251,7 @@ describe('when the workingDirectory does not exist', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace context = new Context() @@ -228,6 +273,7 @@ describe('when the workingDirectory exists, but is a file', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace context = new Context() @@ -254,6 +300,7 @@ describe('when the event inputs are empty', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('no_inputs') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace context = new Context() diff --git a/__tests__/main.test.ts b/__tests__/main.test.ts index 5582bf913..37a26f9a4 100644 --- a/__tests__/main.test.ts +++ b/__tests__/main.test.ts @@ -2,17 +2,22 @@ import fs from 'fs' import path from 'path' import * as core from '@actions/core' import {Context} from '@actions/github/lib/context' -import {ApiClient} from '../src/api-client' +import { + ApiClient, + JobDetails, + CredentialFetchingError, + JobDetailsFetchingError +} from '../src/api-client' import {ContainerRuntimeError} from '../src/container-service' -import {Updater, UpdaterFetchError} from '../src/updater' +import {Updater} from '../src/updater' import {ImageService} from '../src/image-service' +import {updaterImageName} from '../src/docker-tags' import * as inputs from '../src/inputs' import {run} from '../src/main' import {eventFixturePath} from './helpers' // We do not need to build actual containers or run updates for this test. -jest.mock('../src/api-client') jest.mock('../src/image-service') jest.mock('../src/updater') @@ -28,16 +33,28 @@ describe('run', () => { process.env.GITHUB_EVENT_PATH = eventFixturePath('default') process.env.GITHUB_EVENT_NAME = 'dynamic' process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'dependabot[bot]' process.env.GITHUB_WORKSPACE = workspace process.env.GITHUB_SERVER_URL = 'https://test.dev' process.env.GITHUB_REPOSITORY = 'foo/bar' + process.env.GITHUB_DEPENDABOT_JOB_TOKEN = 'xxx' + process.env.GITHUB_DEPENDABOT_CRED_TOKEN = 'yyy' + markJobAsProcessedSpy = jest.spyOn( ApiClient.prototype, 'markJobAsProcessed' ) + markJobAsProcessedSpy.mockImplementation(jest.fn()) reportJobErrorSpy = jest.spyOn(ApiClient.prototype, 'reportJobError') + reportJobErrorSpy.mockImplementation(jest.fn()) + jest + .spyOn(ApiClient.prototype, 'getCredentials') + .mockImplementation(jest.fn()) + jest + .spyOn(ApiClient.prototype, 'getJobDetails') + .mockImplementation(jest.fn()) jest.spyOn(core, 'info').mockImplementation(jest.fn()) jest.spyOn(core, 'warning').mockImplementation(jest.fn()) @@ -53,6 +70,11 @@ describe('run', () => { describe('when the run follows the happy path', () => { beforeEach(() => { + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) context = new Context() }) @@ -73,9 +95,60 @@ describe('run', () => { }) }) + describe('when an updaterImage is not specified', () => { + beforeEach(() => { + context = new Context() + context.payload = { + ...context.payload, + inputs: { + ...context.payload.inputs, + updaterImage: null + } + } + jest.spyOn(ImageService, 'pull') + + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) + }) + + test('it runs with the pinned image', async () => { + await run(context) + + // eslint-disable-next-line @typescript-eslint/unbound-method + expect(ImageService.pull).toHaveBeenCalledWith( + updaterImageName('npm_and_yarn') + ) + }) + }) + + describe('when an updaterImage is specified', () => { + beforeEach(() => { + context = new Context() + context.payload = { + ...context.payload, + inputs: { + ...context.payload.inputs, + updaterImage: 'alpine' + } + } + jest.spyOn(ImageService, 'pull') + }) + + test('it runs with the specified image', async () => { + await run(context) + + // eslint-disable-next-line @typescript-eslint/unbound-method + expect(ImageService.pull).toHaveBeenCalledWith('alpine') + }) + }) + describe('when the action is triggered by a different actor', () => { beforeEach(() => { process.env.GITHUB_ACTOR = 'classic-rando' + process.env.GITHUB_TRIGGERING_ACTOR = 'classic-rando' context = new Context() }) @@ -84,7 +157,31 @@ describe('run', () => { expect(core.setFailed).not.toHaveBeenCalled() expect(core.warning).toHaveBeenCalledWith( - 'This workflow can only be triggered by Dependabot.' + "This workflow can only be triggered by Dependabot. Actor was 'classic-rando'." + ) + }) + + test('it does not report this failed run to dependabot-api', async () => { + await run(context) + + expect(markJobAsProcessedSpy).not.toHaveBeenCalled() + expect(reportJobErrorSpy).not.toHaveBeenCalled() + }) + }) + + describe('when the action is retriggered by a different actor', () => { + beforeEach(() => { + process.env.GITHUB_ACTOR = 'dependabot[bot]' + process.env.GITHUB_TRIGGERING_ACTOR = 'classic-rando' + context = new Context() + }) + + test('it skips the rest of the job', async () => { + await run(context) + + expect(core.setFailed).not.toHaveBeenCalled() + expect(core.warning).toHaveBeenCalledWith( + 'Dependabot workflows cannot be re-run. Retrigger this update via Dependabot instead.' ) }) @@ -134,7 +231,7 @@ describe('run', () => { await run(context) expect(core.setFailed).toHaveBeenCalledWith( - `Dependabot encountered an unexpected problem\n\nError: unexpected error retrieving job params\n\nFor more information see: https://test.dev/foo/bar/network/updates/1 (write access required)` + `Dependabot encountered an unexpected problem\n\nError: unexpected error retrieving job params\n\nFor more information see: https://test.dev/foo/bar/network/updates/1 (write access to the repository is required to view the log)` ) }) @@ -152,7 +249,11 @@ describe('run', () => { .spyOn(ApiClient.prototype, 'getJobDetails') .mockImplementationOnce( jest.fn(async () => - Promise.reject(new Error('error getting job details')) + Promise.reject( + new JobDetailsFetchingError( + 'fetching job details: received code 400: more details' + ) + ) ) ) @@ -163,7 +264,7 @@ describe('run', () => { await run(context) expect(core.setFailed).toHaveBeenCalledWith( - `Dependabot encountered an unexpected problem\n\nError: error getting job details\n\nFor more information see: https://test.dev/foo/bar/network/updates/1 (write access required)` + `Dependabot encountered an unexpected problem\n\nError: fetching job details: received code 400: more details\n\nFor more information see: https://test.dev/foo/bar/network/updates/1 (write access to the repository is required to view the log)` ) }) @@ -175,16 +276,26 @@ describe('run', () => { }) }) - describe('when there is an error retrieving job credentials from DependabotAPI', () => { + describe('when there is an API error retrieving job credentials from DependabotAPI', () => { beforeEach(() => { jest .spyOn(ApiClient.prototype, 'getCredentials') .mockImplementationOnce( jest.fn(async () => - Promise.reject(new Error('error getting credentials')) + Promise.reject( + new CredentialFetchingError( + 'fetching credentials: received code 422: more details' + ) + ) ) ) + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) + context = new Context() }) @@ -192,7 +303,48 @@ describe('run', () => { await run(context) expect(core.setFailed).toHaveBeenCalledWith( - expect.stringContaining('error getting credentials') + expect.stringContaining( + 'fetching credentials: received code 422: more details' + ) + ) + }) + + test('it relays a failure message to the dependabot service', async () => { + await run(context) + + expect(reportJobErrorSpy).toHaveBeenCalledWith({ + 'error-type': 'actions_workflow_updater', + 'error-details': { + 'action-error': + 'fetching credentials: received code 422: more details' + } + }) + expect(markJobAsProcessedSpy).toHaveBeenCalled() + }) + }) + + describe('when there is an unexpected error retrieving job credentials from DependabotAPI', () => { + beforeEach(() => { + jest + .spyOn(ApiClient.prototype, 'getCredentials') + .mockImplementationOnce( + jest.fn(async () => Promise.reject(new Error('something went wrong'))) + ) + + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) + + context = new Context() + }) + + test('it fails the workflow', async () => { + await run(context) + + expect(core.setFailed).toHaveBeenCalledWith( + expect.stringContaining('something went wrong') ) }) @@ -202,7 +354,7 @@ describe('run', () => { expect(reportJobErrorSpy).toHaveBeenCalledWith({ 'error-type': 'actions_workflow_unknown', 'error-details': { - 'action-error': 'error getting credentials' + 'action-error': 'something went wrong' } }) expect(markJobAsProcessedSpy).toHaveBeenCalled() @@ -218,7 +370,11 @@ describe('run', () => { Promise.reject(new Error('error pulling an image')) ) ) - + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) context = new Context() }) @@ -252,7 +408,11 @@ describe('run', () => { Promise.reject(new ContainerRuntimeError('the container melted')) ) ) - + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) context = new Context() }) @@ -260,7 +420,7 @@ describe('run', () => { await run(context) expect(core.setFailed).toHaveBeenCalledWith( - `Dependabot encountered an error performing the update\n\nError: the container melted\n\nFor more information see: https://test.dev/foo/bar/network/updates/1 (write access required)` + `Dependabot encountered an error performing the update\n\nError: the container melted\n\nFor more information see: https://test.dev/foo/bar/network/updates/1 (write access to the repository is required to view the log)` ) }) @@ -286,7 +446,11 @@ describe('run', () => { Promise.reject(new Error('error running the update')) ) ) - + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) context = new Context() }) @@ -294,7 +458,7 @@ describe('run', () => { await run(context) expect(core.setFailed).toHaveBeenCalledWith( - `Dependabot encountered an error performing the update\n\nError: error running the update\n\nFor more information see: https://test.dev/foo/bar/network/updates/1 (write access required)` + `Dependabot encountered an error performing the update\n\nError: error running the update\n\nFor more information see: https://test.dev/foo/bar/network/updates/1 (write access to the repository is required to view the log)` ) }) @@ -311,34 +475,257 @@ describe('run', () => { }) }) - describe('when the file fetch step fails', () => { + describe('when the there is no job token', () => { + beforeEach(() => { + jest.spyOn(inputs, 'getJobParameters').mockReturnValueOnce( + new inputs.JobParameters( + 1, + '', // jobToken set as empty + 'cred-token', + 'https://example.com', + '172.17.0.1', + 'image/name:tag', + './' + ) + ) + + process.env.GITHUB_DEPENDABOT_JOB_TOKEN = '' + process.env.GITHUB_DEPENDABOT_CRED_TOKEN = 'yyy' + context = new Context() + }) + + test('it fails the workflow with the specific error message for missing job token', async () => { + await run(context) + + expect(core.setFailed).toHaveBeenCalledWith( + `Github Dependabot job token is not set` + ) + }) + + test('it does not report this failed run to dependabot-api', async () => { + await run(context) + + expect(markJobAsProcessedSpy).not.toHaveBeenCalled() + expect(reportJobErrorSpy).not.toHaveBeenCalled() + }) + + test('it does not inform dependabot-api as it cannot instantiate a client without the params', async () => { + await run(context) + + expect(markJobAsProcessedSpy).not.toHaveBeenCalled() + expect(reportJobErrorSpy).not.toHaveBeenCalled() + }) + }) + + describe('when the there is no cred token', () => { + beforeEach(() => { + jest.spyOn(inputs, 'getJobParameters').mockReturnValueOnce( + new inputs.JobParameters( + 1, + 'job-token', + '', // credToken set as empty + 'https://example.com', + '172.17.0.1', + 'image/name:tag', + './' + ) + ) + + process.env.GITHUB_DEPENDABOT_JOB_TOKEN = 'xxx' + process.env.GITHUB_DEPENDABOT_CRED_TOKEN = '' + context = new Context() + }) + + test('it fails the workflow with the specific error message for missing credentials token', async () => { + await run(context) + + expect(core.setFailed).toHaveBeenCalledWith( + `Github Dependabot credentials token is not set` + ) + }) + + test('it does not report this failed run to dependabot-api', async () => { + await run(context) + + expect(markJobAsProcessedSpy).not.toHaveBeenCalled() + expect(reportJobErrorSpy).not.toHaveBeenCalled() + }) + + test('it does not inform dependabot-api as it cannot instantiate a client without the params', async () => { + await run(context) + + expect(markJobAsProcessedSpy).not.toHaveBeenCalled() + expect(reportJobErrorSpy).not.toHaveBeenCalled() + }) + }) + + describe('when only the job token is provided through the Action environment', () => { beforeEach(() => { jest - .spyOn(Updater.prototype, 'runUpdater') - .mockImplementationOnce( - jest.fn(async () => - Promise.reject( - new UpdaterFetchError( - 'No output.json created by the fetcher container' - ) - ) + .spyOn(inputs, 'getJobParameters') + .mockReturnValueOnce( + new inputs.JobParameters( + 1, + '', + '', + 'https://example.com', + '172.17.0.1', + 'image/name:tag', + './' ) ) + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) + process.env.GITHUB_DEPENDABOT_JOB_TOKEN = 'xxx' + process.env.GITHUB_DEPENDABOT_CRED_TOKEN = 'yyy' context = new Context() }) - test('it fails the workflow', async () => { + test('it signs off at completion without any errors', async () => { await run(context) - expect(core.setFailed).toHaveBeenCalledWith( - expect.stringContaining( - 'Dependabot was unable to retrieve the files required to perform the update' + expect(core.setFailed).not.toHaveBeenCalled() + expect(core.info).toHaveBeenCalledWith( + expect.stringContaining('🤖 ~ finished ~') + ) + }) + + test('it defers reporting back to dependabot-api to the updater itself', async () => { + await run(context) + + expect(markJobAsProcessedSpy).not.toHaveBeenCalled() + expect(reportJobErrorSpy).not.toHaveBeenCalled() + }) + }) + + describe('when only the cred token is provided through the Action environment', () => { + beforeEach(() => { + jest + .spyOn(inputs, 'getJobParameters') + .mockReturnValueOnce( + new inputs.JobParameters( + 1, + '', + '', + 'https://example.com', + '172.17.0.1', + 'image/name:tag', + './' + ) ) + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) ) + + process.env.GITHUB_DEPENDABOT_JOB_TOKEN = 'xxx' + process.env.GITHUB_DEPENDABOT_CRED_TOKEN = 'yyy' + context = new Context() }) - test('it does not inform dependabot-api as the failed fetch step will have already reported in', async () => { + test('it signs off at completion without any errors', async () => { + await run(context) + + expect(core.setFailed).not.toHaveBeenCalled() + expect(core.info).toHaveBeenCalledWith( + expect.stringContaining('🤖 ~ finished ~') + ) + }) + + test('it defers reporting back to dependabot-api to the updater itself', async () => { + await run(context) + + expect(markJobAsProcessedSpy).not.toHaveBeenCalled() + expect(reportJobErrorSpy).not.toHaveBeenCalled() + }) + }) + + // The below tests are to support backward compatibility when the job token and cred token + // are not provided through the Action environment + describe('when only the job token is provided through the jobParmeters', () => { + beforeEach(() => { + jest + .spyOn(inputs, 'getJobParameters') + .mockReturnValueOnce( + new inputs.JobParameters( + 1, + 'xxx', + 'yyy', + 'https://example.com', + '172.17.0.1', + 'image/name:tag', + './' + ) + ) + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) + + process.env.GITHUB_DEPENDABOT_JOB_TOKEN = '' + process.env.GITHUB_DEPENDABOT_CRED_TOKEN = '' + context = new Context() + }) + + test('it signs off at completion without any errors', async () => { + await run(context) + + expect(core.setFailed).not.toHaveBeenCalled() + expect(core.info).toHaveBeenCalledWith( + expect.stringContaining('🤖 ~ finished ~') + ) + }) + + test('it defers reporting back to dependabot-api to the updater itself', async () => { + await run(context) + + expect(markJobAsProcessedSpy).not.toHaveBeenCalled() + expect(reportJobErrorSpy).not.toHaveBeenCalled() + }) + }) + + describe('when only the cred token is provided through the jobParmeters', () => { + beforeEach(() => { + jest + .spyOn(inputs, 'getJobParameters') + .mockReturnValueOnce( + new inputs.JobParameters( + 1, + 'xxx', + 'yyy', + 'https://example.com', + '172.17.0.1', + 'image/name:tag', + './' + ) + ) + jest.spyOn(ApiClient.prototype, 'getJobDetails').mockImplementationOnce( + jest.fn(async () => { + return {'package-manager': 'npm_and_yarn'} as JobDetails + }) + ) + + process.env.GITHUB_DEPENDABOT_JOB_TOKEN = '' + process.env.GITHUB_DEPENDABOT_CRED_TOKEN = '' + context = new Context() + }) + + test('it signs off at completion without any errors', async () => { + await run(context) + + expect(core.setFailed).not.toHaveBeenCalled() + expect(core.info).toHaveBeenCalledWith( + expect.stringContaining('🤖 ~ finished ~') + ) + }) + + test('it defers reporting back to dependabot-api to the updater itself', async () => { await run(context) expect(markJobAsProcessedSpy).not.toHaveBeenCalled() diff --git a/__tests__/proxy-integration.test.ts b/__tests__/proxy-integration.test.ts index 79d448eb3..6a42edf08 100644 --- a/__tests__/proxy-integration.test.ts +++ b/__tests__/proxy-integration.test.ts @@ -11,6 +11,8 @@ import path from 'path' integration('ProxyBuilder', () => { const docker = new Docker() const jobId = 1 + const jobToken = 'xxxyyyzzzz' + const dependabotApiUrl = 'http://localhost:9000' const credentials: Credential[] = [ { type: 'git_source', @@ -20,7 +22,8 @@ integration('ProxyBuilder', () => { } ] - const builder = new ProxyBuilder(docker, PROXY_IMAGE_NAME) + const cachedMode = true + const builder = new ProxyBuilder(docker, PROXY_IMAGE_NAME, cachedMode) beforeAll(async () => { await ImageService.pull(PROXY_IMAGE_NAME) @@ -32,7 +35,12 @@ integration('ProxyBuilder', () => { jest.setTimeout(20000) it('should create a proxy container with the right details', async () => { - const proxy = await builder.run(jobId, credentials) + const proxy = await builder.run( + jobId, + jobToken, + dependabotApiUrl, + credentials + ) await proxy.container.start() const containerInfo = await proxy.container.inspect() @@ -46,7 +54,7 @@ integration('ProxyBuilder', () => { expect(proxy.networkName).toBe('dependabot-job-1-internal-network') const proxyUrl = await proxy.url() - expect(proxyUrl).toMatch(/^http:\/\/1:.+:1080$/) + expect(proxyUrl).toMatch(/^http:\/\/.+:1080$/) const proxyIPAddress = containerInfo.NetworkSettings.Networks[proxy.networkName].IPAddress @@ -84,7 +92,12 @@ integration('ProxyBuilder', () => { fs.writeFileSync(certPath, 'ca-pem-contents') process.env.CUSTOM_CA_PATH = certPath - const proxy = await builder.run(jobId, credentials) + const proxy = await builder.run( + jobId, + jobToken, + dependabotApiUrl, + credentials + ) await proxy.container.start() const id = proxy.container.id @@ -111,7 +124,12 @@ integration('ProxyBuilder', () => { fs.writeFileSync(certPath, 'ca-pem-contents') process.env.NODE_EXTRA_CA_CERTS = certPath - const proxy = await builder.run(jobId, credentials) + const proxy = await builder.run( + jobId, + jobToken, + dependabotApiUrl, + credentials + ) await proxy.container.start() const id = proxy.container.id @@ -132,7 +150,12 @@ integration('ProxyBuilder', () => { const url = 'http://example.com' process.env.HTTP_PROXY = url - const proxy = await builder.run(jobId, credentials) + const proxy = await builder.run( + jobId, + jobToken, + dependabotApiUrl, + credentials + ) await proxy.container.start() const id = proxy.container.id @@ -146,7 +169,12 @@ integration('ProxyBuilder', () => { const url = 'https://example.com' process.env.https_proxy = url - const proxy = await builder.run(jobId, credentials) + const proxy = await builder.run( + jobId, + jobToken, + dependabotApiUrl, + credentials + ) await proxy.container.start() const id = proxy.container.id diff --git a/__tests__/server/server.js b/__tests__/server/server.js index 155200b55..e182c3794 100755 --- a/__tests__/server/server.js +++ b/__tests__/server/server.js @@ -6,6 +6,7 @@ const db = JSON.parse(fs.readFileSync(path.join(__dirname, 'db.json'))) const router = jsonServer.router(db) const middlewares = jsonServer.defaults() const SERVER_PORT = process.argv.slice(2)[0] || 9000 +var failOneRequest = process.env.TEST_RETRY == 'true' // Sets up a fake dependabot-api using json-server // @@ -32,6 +33,12 @@ server.get('/update_jobs/:id/details', (req, res) => { if (!updateJob) { return res.status(404).end() } + if (failOneRequest) { + failOneRequest = false + return res.status(500).jsonp({ + errors: [{ status: 500, title: 'Server error', detail: 'Test error to trigger retry' }] + }) + } res.jsonp({ data: { @@ -60,7 +67,7 @@ server.post( '/update_jobs/:id/create_pull_request', jsonServer.bodyParser, (req, res) => { - const data = {...req.body.data, id: req.params.id} + const data = { ...req.body.data, id: req.params.id } db.pull_requests.push(data) router.db.write() diff --git a/__tests__/updater-builder-integration.test.ts b/__tests__/updater-builder-integration.test.ts index 4560c3017..3b198c4da 100644 --- a/__tests__/updater-builder-integration.test.ts +++ b/__tests__/updater-builder-integration.test.ts @@ -1,4 +1,4 @@ -import {UPDATER_IMAGE_NAME, PROXY_IMAGE_NAME} from '../src/docker-tags' +import {updaterImageName, PROXY_IMAGE_NAME} from '../src/docker-tags' import {ImageService} from '../src/image-service' import {removeDanglingUpdaterContainers, integration} from './helpers' import Docker from 'dockerode' @@ -11,6 +11,8 @@ import {UpdaterBuilder} from '../src/updater-builder' integration('UpdaterBuilder', () => { const docker = new Docker() + const dependabotApiUrl = `http://localhost:9000` + const jobToken = 'xxxyyyzzzz' const credentials: Credential[] = [ { type: 'git_source', @@ -23,7 +25,8 @@ integration('UpdaterBuilder', () => { const details: JobDetails = { 'allowed-updates': [], id: '1', - 'package-manager': 'npm_and_yarn' + 'package-manager': 'npm_and_yarn', + experiments: {} } const workingDirectory = path.join( @@ -35,14 +38,14 @@ integration('UpdaterBuilder', () => { beforeAll(async () => { await ImageService.pull(PROXY_IMAGE_NAME) - await ImageService.pull(UPDATER_IMAGE_NAME) + await ImageService.pull(updaterImageName('bundler')) fs.mkdirSync(workingDirectory) }) afterEach(async () => { await removeDanglingUpdaterContainers() - fs.rmdirSync(workingDirectory, {recursive: true}) + fs.rmSync(workingDirectory, {recursive: true}) }) it('createUpdaterContainer returns a container only connected to the internal network', async () => { @@ -51,10 +54,12 @@ integration('UpdaterBuilder', () => { fs.mkdirSync(outputPath) fs.mkdirSync(repoPath) - const proxy = await new ProxyBuilder(docker, PROXY_IMAGE_NAME).run( - 1, - credentials - ) + const cachedMode = true + const proxy = await new ProxyBuilder( + docker, + PROXY_IMAGE_NAME, + cachedMode + ).run(1, dependabotApiUrl, jobToken, credentials) await proxy.container.start() const input = {job: details} const params = new JobParameters( @@ -63,6 +68,7 @@ integration('UpdaterBuilder', () => { 'cred-token', 'https://example.com', '172.17.0.1', + updaterImageName('bundler'), workingDirectory ) const container = await new UpdaterBuilder( @@ -71,9 +77,8 @@ integration('UpdaterBuilder', () => { input, outputPath, proxy, - repoPath, - UPDATER_IMAGE_NAME - ).run('updater-image-test', 'fetch_files') + updaterImageName('bundler') + ).run('updater-image-test') const containerInfo = await container.inspect() diff --git a/__tests__/updater-integration.test.ts b/__tests__/updater-integration.test.ts index 434e121f1..33574e646 100644 --- a/__tests__/updater-integration.test.ts +++ b/__tests__/updater-integration.test.ts @@ -1,10 +1,10 @@ -import axios from 'axios' +import * as httpClient from '@actions/http-client' import fs from 'fs' import path from 'path' import {ApiClient} from '../src/api-client' import {ImageService} from '../src/image-service' import {JobParameters} from '../src/inputs' -import {UPDATER_IMAGE_NAME, PROXY_IMAGE_NAME} from '../src/docker-tags' +import {updaterImageName, PROXY_IMAGE_NAME} from '../src/docker-tags' import {Updater} from '../src/updater' import { @@ -24,6 +24,7 @@ integration('Updater', () => { const internalDockerHost = process.platform === 'darwin' ? 'host.docker.internal' : '172.17.0.1' const dependabotApiDockerUrl = `http://${internalDockerHost}:${FAKE_SERVER_PORT}` + const updaterImage = updaterImageName('npm_and_yarn') const workingDirectory = path.join( __dirname, '..', @@ -31,23 +32,31 @@ integration('Updater', () => { './integration_working_directory' ) + // Define jobToken and credentialsToken + const jobToken = 'xxx' + const credentialsToken = 'yyy' + const params = new JobParameters( 1, - 'job-token', - 'cred-token', + jobToken, + credentialsToken, dependabotApiUrl, dependabotApiDockerUrl, + updaterImage, workingDirectory ) - const client = axios.create({baseURL: dependabotApiUrl}) - const apiClient = new ApiClient(client, params) + const client = new httpClient.HttpClient( + 'github/dependabot-action integration' + ) + const apiClient = new ApiClient(client, params, jobToken, credentialsToken) beforeAll(async () => { - await ImageService.pull(UPDATER_IMAGE_NAME) + await ImageService.pull(updaterImageName('npm_and_yarn')) await ImageService.pull(PROXY_IMAGE_NAME) - server = await runFakeDependabotApi(FAKE_SERVER_PORT) + const testRetry = true + server = await runFakeDependabotApi(FAKE_SERVER_PORT, testRetry) fs.mkdirSync(workingDirectory) }) @@ -55,16 +64,16 @@ integration('Updater', () => { afterEach(async () => { server && server() // teardown server process await removeDanglingUpdaterContainers() - fs.rmdirSync(workingDirectory, {recursive: true}) + fs.rmSync(workingDirectory, {recursive: true}) }) jest.setTimeout(120000) - it('should run the updater and create a pull request', async () => { + it('should run the updater, retry on apiClient failure, and create a pull request', async () => { const details = await apiClient.getJobDetails() const credentials = await apiClient.getCredentials() const updater = new Updater( - UPDATER_IMAGE_NAME, + updaterImageName('npm_and_yarn'), PROXY_IMAGE_NAME, apiClient, details, @@ -76,10 +85,10 @@ integration('Updater', () => { // NOTE: This will not work when running against the actual dependabot-api // Checks if the pr was persisted in the fake json-server - const res: any = await client.get('/pull_requests/1') + const res = await client.getJson(`${dependabotApiUrl}/pull_requests/1`) - expect(res.status).toEqual(200) - expect(res.data['pr-title']).toEqual( + expect(res.statusCode).toEqual(200) + expect(res.result['pr-title']).toEqual( 'Bump fetch-factory from 0.0.1 to 0.2.1' ) }) diff --git a/__tests__/updater.test.ts b/__tests__/updater.test.ts index 938486349..6f3a96f9f 100644 --- a/__tests__/updater.test.ts +++ b/__tests__/updater.test.ts @@ -1,6 +1,6 @@ import fs from 'fs' import path from 'path' -import {Updater, UpdaterFetchError} from '../src/updater' +import {Updater} from '../src/updater' import Docker from 'dockerode' import {ContainerService} from '../src/container-service' import {ProxyBuilder} from '../src/proxy' @@ -25,12 +25,13 @@ describe('Updater', () => { const mockApiClient: any = { getJobDetails: jest.fn(), getCredentials: jest.fn(), + getJobToken: jest.fn(), params: { jobId: 1, - jobToken: 'job-token', - credentialsToken: 'job-credentials-token', dependabotApiUrl: 'http://localhost:3001' - } + }, + jobToken: 'job-token', + credentialsToken: 'job-credentials-token' } const mockJobDetails: any = { @@ -75,7 +76,7 @@ describe('Updater', () => { afterEach(async () => { jest.clearAllMocks() // Reset any mocked classes - fs.rmdirSync(workingDirectory, {recursive: true}) + fs.rmSync(workingDirectory, {recursive: true}) }) describe('when there is a happy path update', () => { @@ -96,21 +97,12 @@ describe('Updater', () => { .mockResolvedValue(mockContainer) jest.spyOn(ProxyBuilder.prototype, 'run').mockResolvedValue(mockProxy) - jest - .spyOn(ContainerService, 'run') - .mockImplementationOnce( - jest.fn(async () => { - fs.copyFileSync(outputFixture, outputFilePath) - return true - }) - ) - .mockImplementationOnce( - jest.fn( - jest.fn(async () => { - return true - }) - ) - ) + jest.spyOn(ContainerService, 'run').mockImplementationOnce( + jest.fn(async () => { + fs.copyFileSync(outputFixture, outputFilePath) + return true + }) + ) }) it('should be successful', async () => { @@ -118,7 +110,7 @@ describe('Updater', () => { }) }) - describe('when the file fetch container fails', () => { + describe('when the updater container fails', () => { const updater = new Updater( 'MOCK_UPDATER_IMAGE_NAME', 'MOCK_PROXY_IMAGE_NAME', @@ -139,117 +131,15 @@ describe('Updater', () => { .spyOn(ContainerService, 'run') .mockImplementationOnce( jest.fn(async () => - Promise.reject(new Error('First call to container service errored')) + Promise.reject(new Error('Call to container service errored')) ) ) }) it('should raise an error', async () => { await expect(updater.runUpdater()).rejects.toThrow( - 'First call to container service errored' - ) - }) - }) - - describe('when file updater container fails', () => { - const updater = new Updater( - 'MOCK_UPDATER_IMAGE_NAME', - 'MOCK_PROXY_IMAGE_NAME', - mockApiClient, - mockJobDetails, - [], - workingDirectory - ) - - const outputFixture = outputFixturePath('happy_path') - - beforeEach(async () => { - jest - .spyOn(Docker.prototype, 'createContainer') - .mockResolvedValue(mockContainer) - - jest.spyOn(ProxyBuilder.prototype, 'run').mockResolvedValue(mockProxy) - - jest - .spyOn(ContainerService, 'run') - .mockImplementationOnce( - jest.fn(async () => { - fs.copyFileSync(outputFixture, outputFilePath) - return true - }) - ) - .mockImplementationOnce( - jest.fn(async () => - Promise.reject( - new Error('Second call to container service errored') - ) - ) - ) - }) - - it('should raise an error', async () => { - await expect(updater.runUpdater()).rejects.toThrow( - 'Second call to container service errored' - ) - }) - }) - - describe('when the file fetch step results in empty output', () => { - const updater = new Updater( - 'MOCK_UPDATER_IMAGE_NAME', - 'MOCK_PROXY_IMAGE_NAME', - mockApiClient, - mockJobDetails, - [], - workingDirectory - ) - - beforeEach(async () => { - jest - .spyOn(Docker.prototype, 'createContainer') - .mockResolvedValue(mockContainer) - - jest.spyOn(ProxyBuilder.prototype, 'run').mockResolvedValue(mockProxy) - - jest.spyOn(ContainerService, 'run').mockImplementation(jest.fn()) - }) - - it('should raise a UpdaterFetchError', async () => { - await expect(updater.runUpdater()).rejects.toThrow( - new UpdaterFetchError('No output.json created by the fetcher container') + 'Call to container service errored' ) }) }) - - describe('when the file fetch step results in malformed output', () => { - const updater = new Updater( - 'MOCK_UPDATER_IMAGE_NAME', - 'MOCK_PROXY_IMAGE_NAME', - mockApiClient, - mockJobDetails, - [], - workingDirectory - ) - - const outputFixture = outputFixturePath('malformed') - - beforeEach(async () => { - jest - .spyOn(Docker.prototype, 'createContainer') - .mockResolvedValue(mockContainer) - - jest.spyOn(ProxyBuilder.prototype, 'run').mockResolvedValue(mockProxy) - - jest.spyOn(ContainerService, 'run').mockImplementation( - jest.fn(async () => { - fs.copyFileSync(outputFixture, outputFilePath) - return true - }) - ) - }) - - it('should raise an error', async () => { - await expect(updater.runUpdater()).rejects.toThrow(/Unexpected token/) - }) - }) }) diff --git a/action.yml b/action.yml index fe8496e09..8b718e19d 100644 --- a/action.yml +++ b/action.yml @@ -2,6 +2,6 @@ name: 'Updater Action' description: 'Runs dependabot-updater in Actions' author: 'GitHub' runs: - using: 'node12' + using: 'node20' main: 'dist/main/index.js' post: 'dist/cleanup/index.js' diff --git a/dist/cleanup/index.js b/dist/cleanup/index.js index 406f707fb..087774c96 100644 --- a/dist/cleanup/index.js +++ b/dist/cleanup/index.js @@ -140,7 +140,6 @@ const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); const os = __importStar(__nccwpck_require__(2037)); const path = __importStar(__nccwpck_require__(1017)); -const uuid_1 = __nccwpck_require__(5840); const oidc_utils_1 = __nccwpck_require__(8041); /** * The code to exit an action @@ -170,20 +169,9 @@ function exportVariable(name, val) { process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - // These should realistically never happen, but just in case someone finds a way to exploit uuid generation let's not allow keys or values that contain the delimiter. - if (name.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedVal.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); + return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); } + command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -201,7 +189,7 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueCommand('PATH', inputPath); + file_command_1.issueFileCommand('PATH', inputPath); } else { command_1.issueCommand('add-path', {}, inputPath); @@ -241,7 +229,10 @@ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); - return inputs; + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** @@ -274,8 +265,12 @@ exports.getBooleanInput = getBooleanInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); + command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); } exports.setOutput = setOutput; /** @@ -404,7 +399,11 @@ exports.group = group; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); + } + command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); } exports.saveState = saveState; /** @@ -470,13 +469,14 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = void 0; +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__nccwpck_require__(7147)); const os = __importStar(__nccwpck_require__(2037)); +const uuid_1 = __nccwpck_require__(5840); const utils_1 = __nccwpck_require__(5278); -function issueCommand(command, message) { +function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); @@ -488,7 +488,22 @@ function issueCommand(command, message) { encoding: 'utf8' }); } -exports.issueCommand = issueCommand; +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + const convertedValue = utils_1.toCommandValue(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map /***/ }), @@ -509,8 +524,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(1404); -const auth_1 = __nccwpck_require__(6758); +const http_client_1 = __nccwpck_require__(6255); +const auth_1 = __nccwpck_require__(5526); const core_1 = __nccwpck_require__(2186); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { @@ -543,7 +558,7 @@ class OidcClient { .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); + Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { @@ -979,7 +994,7 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 6758: +/***/ 5526: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -1067,7 +1082,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 1404: +/***/ 6255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1075,7 +1090,11 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + 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]; @@ -1088,7 +1107,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + 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; }; @@ -1105,8 +1124,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(3685)); const https = __importStar(__nccwpck_require__(5687)); -const pm = __importStar(__nccwpck_require__(2843)); +const pm = __importStar(__nccwpck_require__(9835)); const tunnel = __importStar(__nccwpck_require__(4294)); +const undici_1 = __nccwpck_require__(1773); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -1136,16 +1156,16 @@ var HttpCodes; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); +})(Headers || (exports.Headers = Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com @@ -1196,6 +1216,19 @@ class HttpClientResponse { })); }); } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { @@ -1501,6 +1534,15 @@ class HttpClient { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; @@ -1548,7 +1590,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -1580,16 +1622,12 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { + // if tunneling agent isn't assigned create a new agent + if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options @@ -1600,6 +1638,30 @@ class HttpClient { } return agent; } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `${proxyUrl.username}:${proxyUrl.password}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); @@ -1679,7 +1741,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 2843: +/***/ 9835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1700,7 +1762,13 @@ function getProxyUrl(reqUrl) { } })(); if (proxyVar) { - return new URL(proxyVar); + try { + return new URL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new URL(`http://${proxyVar}`); + } } else { return undefined; @@ -1711,6 +1779,10 @@ function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; @@ -1736,2022 +1808,3333 @@ function checkBypass(reqUrl) { .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} //# sourceMappingURL=proxy.js.map /***/ }), -/***/ 9348: -/***/ ((module) => { +/***/ 3358: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2011 Mark Cavage All rights reserved. +"use strict"; +/** + * @license + * Copyright 2020 Balena Ltd. + * + * 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. + * + * ------------------------------------------------------------------------ + * + * Copyright 2018 Zeit, Inc. + * Licensed under the MIT License. See file LICENSE.md for a full copy. + * + * ------------------------------------------------------------------------ + */ -module.exports = { +/** + * This module implements the [dockerignore + * spec](https://docs.docker.com/engine/reference/builder/#dockerignore-file), + * closely following Docker's (Moby) Golang implementation: + * https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go + * https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go + * https://github.com/moby/moby/blob/v19.03.8/pkg/archive/archive.go#L825 + * + * Something the spec is not clear about, but we discovered by reading source code + * and testing against the "docker build" command, is the handling of backslashes and + * forward slashes as path separators and escape characters in the .dockerignore file + * across platforms including Windows, Linux and macOS: + * + * * On Linux and macOS, only forward slashes can be used as path separators in the + * .dockerignore file, and the backslash works as an escape character. + * * On Windows, both forward slashes and backslashes are allowed as path separators + * in the .dockerignore file, and the backslash is not used as an escape character. + * + * This is consistent with how Windows works generally: both forward slashes and + * backslashes are accepted as path separators by the cmd.exe Command Prompt or + * PowerShell, and by library functions like the Golang filepath.Clean or the + * Node.js path.normalize. + * + * Similarly, path strings provided to the IgnoreBase.ignores() and IgnoreBase.filter() + * methods can use either forward slashes or backslashes as path separators on Windows, + * but only forward slashes are accepted as path separators on Linux and macOS. + */ - newInvalidAsn1Error: function (msg) { - var e = new Error(); - e.name = 'InvalidAsn1Error'; - e.message = msg || ''; - return e; - } +const path = __nccwpck_require__(1017); -}; +const factory = options => new IgnoreBase(options); // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L538-L539 +// Fixes typescript module import -/***/ }), +factory.default = factory; +module.exports = factory; -/***/ 194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function make_array(subject) { + return Array.isArray(subject) ? subject : [subject]; +} -// Copyright 2011 Mark Cavage All rights reserved. +const REGEX_TRAILING_SLASH = /(?<=.)\/$/; +const REGEX_TRAILING_BACKSLASH = /(?<=.)\\$/; +const REGEX_TRAILING_PATH_SEP = path.sep === '\\' ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH; +const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('dockerignore') : 'dockerignore'; // An implementation of Go's filepath.Clean +// https://golang.org/pkg/path/filepath/#Clean +// https://github.com/golang/go/blob/master/src/path/filepath/path.go +// Note that, like Go, on Windows this function converts forward slashes +// to backslashes. -var errors = __nccwpck_require__(9348); -var types = __nccwpck_require__(2473); +function cleanPath(file) { + return path.normalize(file).replace(REGEX_TRAILING_PATH_SEP, ''); +} // Javascript port of Golang's filepath.ToSlash +// https://golang.org/pkg/path/filepath/#ToSlash +// https://github.com/golang/go/blob/master/src/path/filepath/path.go +// Convert any OS-specific path separator to '/'. Backslash is converted +// to forward slash on Windows, but not on Linux/macOS. +// Note that both forward slashes and backslashes are valid path separators on +// Windows. As a result, code such as `pattern.split(path.sep).join('/')` fails +// on Windows when forward slashes are used as path separators. -var Reader = __nccwpck_require__(290); -var Writer = __nccwpck_require__(3200); +function toSlash(file) { + if (path.sep === '/') { + return file; + } -// --- Exports + return file.replace(/\\/g, '/'); +} // Javascript port of Golang's filepath.FromSlash +// https://github.com/golang/go/blob/master/src/path/filepath/path.go -module.exports = { - Reader: Reader, +function fromSlash(file) { + if (path.sep === '/') { + return file; + } - Writer: Writer + return file.replace(/\//g, path.sep); +} -}; +class IgnoreBase { + constructor({ + // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L372 + ignorecase = true + } = {}) { + this._rules = []; + this._ignorecase = ignorecase; + this[KEY_IGNORE] = true; -for (var t in types) { - if (types.hasOwnProperty(t)) - module.exports[t] = types[t]; -} -for (var e in errors) { - if (errors.hasOwnProperty(e)) - module.exports[e] = errors[e]; -} + this._initCache(); + } + _initCache() { + this._cache = {}; + } // @param {Array.|string|Ignore} pattern -/***/ }), -/***/ 290: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + add(pattern) { + this._added = false; -// Copyright 2011 Mark Cavage All rights reserved. + if (typeof pattern === 'string') { + pattern = pattern.split(/\r?\n/g); + } -var assert = __nccwpck_require__(9491); -var Buffer = (__nccwpck_require__(5118).Buffer); + make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore, + // making the behavior changed. -var ASN1 = __nccwpck_require__(2473); -var errors = __nccwpck_require__(9348); + if (this._added) { + this._initCache(); + } + return this; + } // legacy -// --- Globals -var newInvalidAsn1Error = errors.newInvalidAsn1Error; + addPattern(pattern) { + return this.add(pattern); + } + _addPattern(pattern) { + // https://github.com/kaelzhang/node-ignore/issues/32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + if (this._checkPattern(pattern)) { + const rule = this._createRule(pattern.trim()); -// --- API + if (rule !== null) { + this._added = true; -function Reader(data) { - if (!data || !Buffer.isBuffer(data)) - throw new TypeError('data must be a node Buffer'); + this._rules.push(rule); + } + } + } - this._buf = data; - this._size = data.length; + _checkPattern(pattern) { + // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L34-L40 + return pattern && typeof pattern === 'string' && pattern.indexOf('#') !== 0 && pattern.trim() !== ""; + } - // These hold the "current" state - this._len = 0; - this._offset = 0; -} + filter(paths) { + return make_array(paths).filter(path => this._filter(path)); + } -Object.defineProperty(Reader.prototype, 'length', { - enumerable: true, - get: function () { return (this._len); } -}); + createFilter() { + return path => this._filter(path); + } -Object.defineProperty(Reader.prototype, 'offset', { - enumerable: true, - get: function () { return (this._offset); } -}); + ignores(path) { + return !this._filter(path); + } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L41-L53 + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L29-L55 -Object.defineProperty(Reader.prototype, 'remain', { - get: function () { return (this._size - this._offset); } -}); -Object.defineProperty(Reader.prototype, 'buffer', { - get: function () { return (this._buf.slice(this._offset)); } -}); + _createRule(pattern) { + const origin = pattern; + let negative = false; // > An optional prefix "!" which negates the pattern; + // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L43-L46 + if (pattern[0] === '!') { + negative = true; + pattern = pattern.substring(1).trim(); + } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L47-L53 -/** - * Reads a single byte and advances offset; you can pass in `true` to make this - * a "peek" operation (i.e., get the byte, but don't advance the offset). - * - * @param {Boolean} peek true means don't move offset. - * @return {Number} the next byte, null if not enough data. - */ -Reader.prototype.readByte = function (peek) { - if (this._size - this._offset < 1) - return null; - var b = this._buf[this._offset] & 0xff; + if (pattern.length > 0) { + pattern = cleanPath(pattern); + pattern = toSlash(pattern); - if (!peek) - this._offset += 1; + if (pattern.length > 1 && pattern[0] === '/') { + pattern = pattern.slice(1); + } + } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L54-L55 - return b; -}; + if (negative) { + pattern = '!' + pattern; + } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L30 -Reader.prototype.peek = function () { - return this.readByte(true); -}; + pattern = pattern.trim(); -/** - * Reads a (potentially) variable length off the BER buffer. This call is - * not really meant to be called directly, as callers have to manipulate - * the internal buffer afterwards. - * - * As a result of this call, you can call `Reader.length`, until the - * next thing called that does a readLength. - * - * @return {Number} the amount of offset to advance the buffer. - * @throws {InvalidAsn1Error} on bad ASN.1 - */ -Reader.prototype.readLength = function (offset) { - if (offset === undefined) - offset = this._offset; + if (pattern === "") { + return null; + } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L34 + // convert forward slashes to backslashes on Windows - if (offset >= this._size) - return null; - var lenB = this._buf[offset++] & 0xff; - if (lenB === null) - return null; + pattern = cleanPath(pattern); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L36-L42 - if ((lenB & 0x80) === 0x80) { - lenB &= 0x7f; + if (pattern[0] === '!') { + if (pattern.length === 1) { + return null; + } - if (lenB === 0) - throw newInvalidAsn1Error('Indefinite length not supported'); + negative = true; + pattern = pattern.substring(1); + } else { + negative = false; + } - if (lenB > 4) - throw newInvalidAsn1Error('encoding too long'); + return { + origin, + pattern, + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L54 + dirs: pattern.split(path.sep), + negative + }; + } // @returns `Boolean` true if the `path` is NOT ignored - if (this._size - offset < lenB) - return null; - this._len = 0; - for (var i = 0; i < lenB; i++) - this._len = (this._len << 8) + (this._buf[offset++] & 0xff); + _filter(path) { + if (!path) { + return false; + } - } else { - // Wasn't a variable length - this._len = lenB; - } + if (path in this._cache) { + return this._cache[path]; + } - return offset; -}; + return this._cache[path] = this._test(path); + } // @returns {Boolean} true if a file is NOT ignored + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L62 -/** - * Parses the next sequence in this BER buffer. - * - * To get the length of the sequence, call `Reader.length`. - * - * @return {Number} the sequence's tag. - */ -Reader.prototype.readSequence = function (tag) { - var seq = this.peek(); - if (seq === null) - return null; - if (tag !== undefined && tag !== seq) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + seq.toString(16)); + _test(file) { + file = fromSlash(file); // equivalent to golang filepath.Dir() https://golang.org/src/path/filepath/path.go - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; + const parentPath = cleanPath(path.dirname(file)); + const parentPathDirs = parentPath.split(path.sep); + let matched = false; - this._offset = o; - return seq; -}; + this._rules.forEach(rule => { + let match = this._match(file, rule); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L80 -Reader.prototype.readInt = function () { - return this._readTag(ASN1.Integer); -}; + if (!match && parentPath !== ".") { + // Check to see if the pattern matches one of our parent dirs. + if (rule.dirs.includes('**')) { + // Ah shucks! We have to test every possible parent path that has + // a number of dirs _n_ where + // `rule.dirs.filter(doubleStar).length <= _n_ <= parentPathDirs.length` + // since the ** can imply any number of directories including 0 + for (let i = rule.dirs.filter(x => x !== '**').length; i <= parentPathDirs.length; i++) { + match = match || this._match(parentPathDirs.slice(0, i).join(path.sep), rule); + } + } else if (rule.dirs.length <= parentPathDirs.length) { + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L83 + match = this._match(parentPathDirs.slice(0, rule.dirs.length).join(path.sep), rule); + } + } + if (match) { + matched = !rule.negative; + } + }); -Reader.prototype.readBoolean = function () { - return (this._readTag(ASN1.Boolean) === 0 ? false : true); -}; + return !matched; + } // @returns {Boolean} true if a file is matched by a rule -Reader.prototype.readEnumeration = function () { - return this._readTag(ASN1.Enumeration); -}; + _match(file, rule) { + return this._compile(rule).regexp.test(file); + } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L139 -Reader.prototype.readString = function (tag, retbuf) { - if (!tag) - tag = ASN1.OctetString; + _compile(rule) { + if (rule.regexp) { + return rule; + } - var b = this.peek(); - if (b === null) - return null; + let regStr = '^'; // Go through the pattern and convert it to a regexp. - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); + let escapedSlash = path.sep === '\\' ? '\\\\' : path.sep; - var o = this.readLength(this._offset + 1); // stored in `length` + for (let i = 0; i < rule.pattern.length; i++) { + const ch = rule.pattern[i]; - if (o === null) - return null; + if (ch === '*') { + if (rule.pattern[i + 1] === '*') { + // is some flavor of "**" + i++; // Treat **/ as ** so eat the "/" - if (this.length > this._size - o) - return null; + if (rule.pattern[i + 1] === path.sep) { + i++; + } - this._offset = o; + if (rule.pattern[i + 1] === undefined) { + // is "**EOF" - to align with .gitignore just accept all + regStr += ".*"; + } else { + // is "**" + // Note that this allows for any # of /'s (even 0) because + // the .* will eat everything, even /'s + regStr += `(.*${escapedSlash})?`; + } + } else { + // is "*" so map it to anything but "/" + regStr += `[^${escapedSlash}]*`; + } + } else if (ch === '?') { + // "?" is any char except "/" + regStr += `[^${escapedSlash}]`; + } else if (ch === '.' || ch === '$') { + // Escape some regexp special chars that have no meaning + // in golang's filepath.Match + regStr += `\\${ch}`; + } else if (ch === '\\') { + // escape next char. Note that a trailing \ in the pattern + // will be left alone (but need to escape it) + if (path.sep === '\\') { + // On windows map "\" to "\\", meaning an escaped backslash, + // and then just continue because filepath.Match on + // Windows doesn't allow escaping at all + regStr += escapedSlash; + continue; + } - if (this.length === 0) - return retbuf ? Buffer.alloc(0) : ''; + if (rule.pattern[i + 1] !== undefined) { + regStr += '\\' + rule.pattern[i + 1]; + i++; + } else { + regStr += '\\'; + } + } else { + regStr += ch; + } + } - var str = this._buf.slice(this._offset, this._offset + this.length); - this._offset += this.length; + regStr += "$"; + rule.regexp = new RegExp(regStr, this._ignorecase ? 'i' : ''); + return rule; + } - return retbuf ? str : str.toString('utf8'); -}; +} -Reader.prototype.readOID = function (tag) { - if (!tag) - tag = ASN1.OID; - var b = this.readString(tag, true); - if (b === null) - return null; +/***/ }), - var values = []; - var value = 0; +/***/ 2856: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (var i = 0; i < b.length; i++) { - var byte = b[i] & 0xff; +"use strict"; - value <<= 7; - value += byte & 0x7f; - if ((byte & 0x80) === 0) { - values.push(value); - value = 0; - } - } - value = values.shift(); - values.unshift(value % 40); - values.unshift((value / 40) >> 0); +const WritableStream = (__nccwpck_require__(4492).Writable) +const inherits = (__nccwpck_require__(7261).inherits) - return values.join('.'); -}; +const StreamSearch = __nccwpck_require__(8534) +const PartStream = __nccwpck_require__(8710) +const HeaderParser = __nccwpck_require__(333) -Reader.prototype._readTag = function (tag) { - assert.ok(tag !== undefined); +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} - var b = this.peek(); +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) - if (b === null) - return null; + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; + this._headerFirst = cfg.headerFirst - if (this.length > 4) - throw newInvalidAsn1Error('Integer too long: ' + this.length); + 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 (this.length > this._size - o) - return null; - this._offset = o; + 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) + +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) } +} - var fb = this._buf[this._offset]; - var value = 0; +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } - for (var i = 0; i < this.length; i++) { - value <<= 8; - value |= (this._buf[this._offset++] & 0xff); + 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 ((fb & 0x80) === 0x80 && i !== 4) - value -= (1 << (i * 8)); - - return value >> 0; -}; + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + this._bparser.push(data) + if (this._pause) { this._cb = cb } else { cb() } +} -// --- Exported API +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} -module.exports = Reader; +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) + }) +} +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() + } +} -/***/ }), +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true -/***/ 2473: -/***/ ((module) => { + 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 + } + } + 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 } + } + 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 (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) } + } + } + 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() + } + } + }) + } + } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } +} -// Copyright 2011 Mark Cavage All rights reserved. +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} -module.exports = { - EOC: 0, - Boolean: 1, - Integer: 2, - BitString: 3, - OctetString: 4, - Null: 5, - OID: 6, - ObjectDescriptor: 7, - External: 8, - Real: 9, // float - Enumeration: 10, - PDV: 11, - Utf8String: 12, - RelativeOID: 13, - Sequence: 16, - Set: 17, - NumericString: 18, - PrintableString: 19, - T61String: 20, - VideotexString: 21, - IA5String: 22, - UTCTime: 23, - GeneralizedTime: 24, - GraphicString: 25, - VisibleString: 26, - GeneralString: 28, - UniversalString: 29, - CharacterString: 30, - BMPString: 31, - Constructor: 32, - Context: 128 -}; +module.exports = Dicer /***/ }), -/***/ 3200: +/***/ 333: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2011 Mark Cavage All rights reserved. +"use strict"; -var assert = __nccwpck_require__(9491); -var Buffer = (__nccwpck_require__(5118).Buffer); -var ASN1 = __nccwpck_require__(2473); -var errors = __nccwpck_require__(9348); +const EventEmitter = (__nccwpck_require__(5673).EventEmitter) +const inherits = (__nccwpck_require__(7261).inherits) +const getLimit = __nccwpck_require__(9692) + +const StreamSearch = __nccwpck_require__(8534) + +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 HeaderParser (cfg) { + EventEmitter.call(this) + + 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) } + + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) -// --- Globals +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} -var newInvalidAsn1Error = errors.newInvalidAsn1Error; +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} -var DEFAULT_OPTS = { - size: 1024, - growthFactor: 8 -}; +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) +} +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } -// --- Helpers + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h -function merge(from, to) { - assert.ok(from); - assert.equal(typeof (from), 'object'); - assert.ok(to); - assert.equal(typeof (to), 'object'); + 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 + } + } - var keys = Object.getOwnPropertyNames(from); - keys.forEach(function (key) { - if (to[key]) - return; + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return + } + 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 } + } +} - var value = Object.getOwnPropertyDescriptor(from, key); - Object.defineProperty(to, key, value); - }); +module.exports = HeaderParser - return to; -} +/***/ }), +/***/ 8710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// --- API +"use strict"; -function Writer(options) { - options = merge(DEFAULT_OPTS, options || {}); - this._buf = Buffer.alloc(options.size || 1024); - this._size = this._buf.length; - this._offset = 0; - this._options = options; +const inherits = (__nccwpck_require__(7261).inherits) +const ReadableStream = (__nccwpck_require__(4492).Readable) - // A list of offsets in the buffer where we need to insert - // sequence tag/len pairs. - this._seq = []; +function PartStream (opts) { + ReadableStream.call(this, opts) } +inherits(PartStream, ReadableStream) -Object.defineProperty(Writer.prototype, 'buffer', { - get: function () { - if (this._seq.length) - throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); +PartStream.prototype._read = function (n) {} - return (this._buf.slice(0, this._offset)); - } -}); +module.exports = PartStream -Writer.prototype.writeByte = function (b) { - if (typeof (b) !== 'number') - throw new TypeError('argument must be a Number'); - this._ensure(1); - this._buf[this._offset++] = b; -}; +/***/ }), +/***/ 8534: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Writer.prototype.writeInt = function (i, tag) { - if (typeof (i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof (tag) !== 'number') - tag = ASN1.Integer; +"use strict"; - var sz = 4; - while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && - (sz > 1)) { - sz--; - i <<= 8; +/** + * 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__(5673).EventEmitter) +const inherits = (__nccwpck_require__(7261).inherits) + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) } - if (sz > 4) - throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } - this._ensure(2 + sz); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = sz; + const needleLength = needle.length - while (sz-- > 0) { - this._buf[this._offset++] = ((i & 0xff000000) >>> 24); - i <<= 8; + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') } -}; + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + this.maxMatches = Infinity + this.matches = 0 -Writer.prototype.writeNull = function () { - this.writeByte(ASN1.Null); - this.writeByte(0x00); -}; + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + this._lookbehind = Buffer.alloc(needleLength) -Writer.prototype.writeEnumeration = function (i, tag) { - if (typeof (i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof (tag) !== 'number') - tag = ASN1.Enumeration; + // 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) - return this.writeInt(i, tag); -}; +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} +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 +} -Writer.prototype.writeBoolean = function (b, tag) { - if (typeof (b) !== 'boolean') - throw new TypeError('argument must be a Boolean'); - if (typeof (tag) !== 'number') - tag = ASN1.Boolean; +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] - this._ensure(3); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = 0x01; - this._buf[this._offset++] = b ? 0xff : 0x00; -}; + // 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 + 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) -Writer.prototype.writeString = function (s, tag) { - if (typeof (s) !== 'string') - throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); - if (typeof (tag) !== 'number') - tag = ASN1.OctetString; + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) - var len = Buffer.byteLength(s); - this.writeByte(tag); - this.writeLength(len); - if (len) { - this._ensure(len); - this._buf.write(s, this._offset); - this._offset += len; + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] + } + + // No match. + + 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 } + } + + 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) + } + + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len + + this._bufpos = len + return len + } } -}; + pos += (pos >= 0) * this._bufpos -Writer.prototype.writeBuffer = function (buf, tag) { - if (typeof (tag) !== 'number') - throw new TypeError('tag must be a number'); - if (!Buffer.isBuffer(buf)) - throw new TypeError('argument must be a buffer'); + // 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) } - this.writeByte(tag); - this.writeLength(buf.length); - this._ensure(buf.length); - buf.copy(this._buf, this._offset, 0, buf.length); - this._offset += buf.length; -}; + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + + // 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 + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } -Writer.prototype.writeStringArray = function (strings) { - if ((!strings instanceof Array)) - throw new TypeError('argument must be an Array[String]'); + this._bufpos = len + return len +} - var self = this; - strings.forEach(function (s) { - self.writeString(s); - }); -}; +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} -// This is really to solve DER cases, but whatever for now -Writer.prototype.writeOID = function (s, tag) { - if (typeof (s) !== 'string') - throw new TypeError('argument must be a string'); - if (typeof (tag) !== 'number') - tag = ASN1.OID; +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 } + } + return true +} - if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) - throw new Error('argument is not a valid OID string'); +module.exports = SBMH - function encodeOctet(bytes, octet) { - if (octet < 128) { - bytes.push(octet); - } else if (octet < 16384) { - bytes.push((octet >>> 7) | 0x80); - bytes.push(octet & 0x7F); - } else if (octet < 2097152) { - bytes.push((octet >>> 14) | 0x80); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else if (octet < 268435456) { - bytes.push((octet >>> 21) | 0x80); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else { - bytes.push(((octet >>> 28) | 0x80) & 0xFF); - bytes.push(((octet >>> 21) | 0x80) & 0xFF); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); + +/***/ }), + +/***/ 3438: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const WritableStream = (__nccwpck_require__(4492).Writable) +const { inherits } = __nccwpck_require__(7261) +const Dicer = __nccwpck_require__(2856) + +const MultipartParser = __nccwpck_require__(415) +const UrlencodedParser = __nccwpck_require__(6780) +const parseParams = __nccwpck_require__(4426) + +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts + + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) + + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) + +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) +} + +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) + + 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 } - var tmp = s.split('.'); - var bytes = []; - bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); - tmp.slice(2).forEach(function (b) { - encodeOctet(bytes, parseInt(b, 10)); - }); + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} - var self = this; - this._ensure(2 + bytes.length); - this.writeByte(tag); - this.writeLength(bytes.length); - bytes.forEach(function (b) { - self.writeByte(b); - }); -}; +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} +module.exports = Busboy +module.exports["default"] = Busboy +module.exports.Busboy = Busboy -Writer.prototype.writeLength = function (len) { - if (typeof (len) !== 'number') - throw new TypeError('argument must be a Number'); +module.exports.Dicer = Dicer - this._ensure(4); - if (len <= 0x7f) { - this._buf[this._offset++] = len; - } else if (len <= 0xff) { - this._buf[this._offset++] = 0x81; - this._buf[this._offset++] = len; - } else if (len <= 0xffff) { - this._buf[this._offset++] = 0x82; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else if (len <= 0xffffff) { - this._buf[this._offset++] = 0x83; - this._buf[this._offset++] = len >> 16; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else { - throw newInvalidAsn1Error('Length too long (> 4 bytes)'); +/***/ }), + +/***/ 415: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +// 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 + +const { Readable } = __nccwpck_require__(4492) +const { inherits } = __nccwpck_require__(7261) + +const Dicer = __nccwpck_require__(2856) + +const parseParams = __nccwpck_require__(4426) +const decodeText = __nccwpck_require__(9136) +const basename = __nccwpck_require__(496) +const getLimit = __nccwpck_require__(9692) + +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 + +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 } + + 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 + } } -}; -Writer.prototype.startSequence = function (tag) { - if (typeof (tag) !== 'number') - tag = ASN1.Sequence | ASN1.Constructor; + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + 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) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + 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) + } + + // 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') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + 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 + } + } + } + } - this.writeByte(tag); - this._seq.push(this._offset); - this._ensure(3); - this._offset += 3; -}; + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + + 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) } + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } -Writer.prototype.endSequence = function () { - var seq = this._seq.pop(); - var start = seq + 3; - var len = this._offset - start; + let onData, + onEnd - if (len <= 0x7f) { - this._shift(start, len, -2); - this._buf[seq] = len; - } else if (len <= 0xff) { - this._shift(start, len, -1); - this._buf[seq] = 0x81; - this._buf[seq + 1] = len; - } else if (len <= 0xffff) { - this._buf[seq] = 0x82; - this._buf[seq + 1] = len >> 8; - this._buf[seq + 2] = len; - } else if (len <= 0xffffff) { - this._shift(start, len, 1); - this._buf[seq] = 0x83; - this._buf[seq + 1] = len >> 16; - this._buf[seq + 2] = len >> 8; - this._buf[seq + 3] = len; + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } + + ++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) + + 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 } + + file.bytesRead = nsize + } + + 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) + } + + ++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() + } + } + + /* 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 + + 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 { - throw newInvalidAsn1Error('Sequence too long'); + this._needDrain = !r + this._cb = cb } -}; +} +Multipart.prototype.end = function () { + const self = this -Writer.prototype._shift = function (start, len, shift) { - assert.ok(start !== undefined); - assert.ok(len !== undefined); - assert.ok(shift); + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } +} - this._buf.copy(this._buf, start + shift, start, start + len); - this._offset += shift; -}; +function skipPart (part) { + part.resume() +} -Writer.prototype._ensure = function (len) { - assert.ok(len); +function FileStream (opts) { + Readable.call(this, opts) - if (this._size - this._offset < len) { - var sz = this._size * this._options.growthFactor; - if (sz - this._offset < len) - sz += len; + this.bytesRead = 0 - var buf = Buffer.alloc(sz); + this.truncated = false +} - this._buf.copy(buf, 0, 0, this._offset); - this._buf = buf; - this._size = sz; +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart + + +/***/ }), + +/***/ 6780: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Decoder = __nccwpck_require__(9730) +const decodeText = __nccwpck_require__(9136) +const getLimit = __nccwpck_require__(9692) + +const RE_CHARSET = /^charset$/i + +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy + + 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 + } } -}; + 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 +} -// --- Exported API +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() + } -module.exports = Writer; + 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 } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + 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 } + + 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() +} + +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') +} + +module.exports = UrlEncoded /***/ }), -/***/ 970: +/***/ 9730: +/***/ ((module) => { + +"use strict"; + + +const RE_PLUS = /\+/g + +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 +] + +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 +} + +module.exports = Decoder + + +/***/ }), + +/***/ 496: +/***/ ((module) => { + +"use strict"; + + +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) + } + } + return (path === '..' || path === '.' ? '' : path) +} + + +/***/ }), + +/***/ 9136: +/***/ ((module) => { + +"use strict"; + + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function decodeText (text, textEncoding, destEncoding) { + if (text) { + if (textDecoders.has(destEncoding)) { + try { + return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding)) + } catch (e) { } + } else { + try { + textDecoders.set(destEncoding, new TextDecoder(destEncoding)) + return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding)) + } catch (e) { } + } + } + return text +} + +module.exports = decodeText + + +/***/ }), + +/***/ 9692: +/***/ ((module) => { + +"use strict"; + + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} + + +/***/ }), + +/***/ 4426: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2011 Mark Cavage All rights reserved. +"use strict"; -// If you have no idea what ASN.1 or BER is, see this: -// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc -var Ber = __nccwpck_require__(194); +const decodeText = __nccwpck_require__(9136) +const RE_ENCODED = /%([a-fA-F0-9]{2})/g +function encodedReplacer (match, byte) { + return String.fromCharCode(parseInt(byte, 16)) +} -// --- Exported API +function parseParams (str) { + const res = [] + let state = 'key' + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' -module.exports = { + 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 + } + } 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) + } + 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 (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } - Ber: Ber, + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } - BerReader: Ber.Reader, + return res +} - BerWriter: Ber.Writer +module.exports = parseParams + + +/***/ }), + +/***/ 9348: +/***/ ((module) => { + +// Copyright 2011 Mark Cavage All rights reserved. + + +module.exports = { + + newInvalidAsn1Error: function (msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } }; /***/ }), -/***/ 5447: +/***/ 194: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +// Copyright 2011 Mark Cavage All rights reserved. +var errors = __nccwpck_require__(9348); +var types = __nccwpck_require__(2473); -var crypto_hash_sha512 = (__nccwpck_require__(8729).lowlevel.crypto_hash); +var Reader = __nccwpck_require__(290); +var Writer = __nccwpck_require__(3200); -/* - * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a - * result, it retains the original copyright and license. The two files are - * under slightly different (but compatible) licenses, and are here combined in - * one file. - * - * Credit for the actual porting work goes to: - * Devi Mandiri - */ -/* - * The Blowfish portions are under the following license: - * - * Blowfish block cipher for OpenBSD - * Copyright 1997 Niels Provos - * All rights reserved. - * - * Implementation advice by David Mazieres . - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ +// --- Exports -/* - * The bcrypt_pbkdf portions are under the following license: - * - * Copyright (c) 2013 Ted Unangst - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ +module.exports = { -/* - * Performance improvements (Javascript-specific): - * - * Copyright 2016, Joyent Inc - * Author: Alex Wilson - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ + Reader: Reader, -// Ported from OpenBSD bcrypt_pbkdf.c v1.9 + Writer: Writer -var BLF_J = 0; +}; -var Blowfish = function() { - this.S = [ - new Uint32Array([ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, - 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, - 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, - 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, - 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, - 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, - 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, - 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, - 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, - 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, - 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, - 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, - 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, - 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, - 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, - 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, - 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, - 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, - 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, - 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, - 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, - 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, - 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, - 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, - 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, - 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, - 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, - 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, - 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, - 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, - 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, - 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, - 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, - 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, - 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, - 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, - 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, - 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, - 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, - 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, - 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, - 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, - 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), - new Uint32Array([ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, - 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, - 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, - 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, - 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, - 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, - 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, - 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, - 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, - 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, - 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, - 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, - 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, - 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, - 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, - 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, - 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, - 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, - 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, - 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, - 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, - 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, - 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, - 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, - 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, - 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, - 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, - 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, - 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, - 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, - 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, - 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, - 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, - 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, - 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, - 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, - 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, - 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, - 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, - 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, - 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, - 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, - 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), - new Uint32Array([ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, - 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, - 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, - 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, - 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, - 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, - 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, - 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, - 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, - 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, - 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, - 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, - 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, - 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, - 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, - 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, - 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, - 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, - 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, - 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, - 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, - 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, - 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, - 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, - 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, - 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, - 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, - 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, - 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, - 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, - 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, - 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, - 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, - 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, - 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, - 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, - 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, - 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, - 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, - 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, - 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, - 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, - 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), - new Uint32Array([ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, - 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, - 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, - 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, - 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, - 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, - 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, - 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, - 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, - 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, - 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, - 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, - 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, - 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, - 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, - 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, - 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, - 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, - 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, - 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, - 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, - 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, - 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, - 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, - 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, - 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, - 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, - 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, - 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, - 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, - 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, - 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, - 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, - 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, - 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, - 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, - 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, - 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, - 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, - 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, - 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, - 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, - 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) - ]; - this.P = new Uint32Array([ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, - 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, - 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, - 0x9216d5d9, 0x8979fb1b]); -}; - -function F(S, x8, i) { - return (((S[0][x8[i+3]] + - S[1][x8[i+2]]) ^ - S[2][x8[i+1]]) + - S[3][x8[i]]); -}; - -Blowfish.prototype.encipher = function(x, x8) { - if (x8 === undefined) { - x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - } - x[0] ^= this.P[0]; - for (var i = 1; i < 16; i += 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[17]; - x[1] = t; -}; - -Blowfish.prototype.decipher = function(x) { - var x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - x[0] ^= this.P[17]; - for (var i = 16; i > 0; i -= 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[0]; - x[1] = t; -}; - -function stream2word(data, databytes){ - var i, temp = 0; - for (i = 0; i < 4; i++, BLF_J++) { - if (BLF_J >= databytes) BLF_J = 0; - temp = (temp << 8) | data[BLF_J]; - } - return temp; -}; - -Blowfish.prototype.expand0state = function(key, keybytes) { - var d = new Uint32Array(2), i, k; - var d8 = new Uint8Array(d.buffer); +for (var t in types) { + if (types.hasOwnProperty(t)) + module.exports[t] = types[t]; +} +for (var e in errors) { + if (errors.hasOwnProperty(e)) + module.exports[e] = errors[e]; +} - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - BLF_J = 0; - for (i = 0; i < 18; i += 2) { - this.encipher(d, d8); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } +/***/ }), - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - this.encipher(d, d8); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } -}; +/***/ 290: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { - var d = new Uint32Array(2), i, k; +// Copyright 2011 Mark Cavage All rights reserved. - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } +var assert = __nccwpck_require__(9491); +var Buffer = (__nccwpck_require__(5118).Buffer); - for (i = 0, BLF_J = 0; i < 18; i += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } +var ASN1 = __nccwpck_require__(2473); +var errors = __nccwpck_require__(9348); - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } - BLF_J = 0; -}; -Blowfish.prototype.enc = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.encipher(data.subarray(i*2)); - } -}; +// --- Globals -Blowfish.prototype.dec = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.decipher(data.subarray(i*2)); - } -}; +var newInvalidAsn1Error = errors.newInvalidAsn1Error; -var BCRYPT_BLOCKS = 8, - BCRYPT_HASHSIZE = 32; -function bcrypt_hash(sha2pass, sha2salt, out) { - var state = new Blowfish(), - cdata = new Uint32Array(BCRYPT_BLOCKS), i, - ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, - 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, - 105,116,101]); //"OxychromaticBlowfishSwatDynamite" - state.expandstate(sha2salt, 64, sha2pass, 64); - for (i = 0; i < 64; i++) { - state.expand0state(sha2salt, 64); - state.expand0state(sha2pass, 64); - } +// --- API - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = stream2word(ciphertext, ciphertext.byteLength); - for (i = 0; i < 64; i++) - state.enc(cdata, cdata.byteLength / 8); +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) + throw new TypeError('data must be a node Buffer'); - for (i = 0; i < BCRYPT_BLOCKS; i++) { - out[4*i+3] = cdata[i] >>> 24; - out[4*i+2] = cdata[i] >>> 16; - out[4*i+1] = cdata[i] >>> 8; - out[4*i+0] = cdata[i]; - } -}; + this._buf = data; + this._size = data.length; -function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { - var sha2pass = new Uint8Array(64), - sha2salt = new Uint8Array(64), - out = new Uint8Array(BCRYPT_HASHSIZE), - tmpout = new Uint8Array(BCRYPT_HASHSIZE), - countsalt = new Uint8Array(saltlen+4), - i, j, amt, stride, dest, count, - origkeylen = keylen; + // These hold the "current" state + this._len = 0; + this._offset = 0; +} - if (rounds < 1) - return -1; - if (passlen === 0 || saltlen === 0 || keylen === 0 || - keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) - return -1; +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function () { return (this._len); } +}); - stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); - amt = Math.floor((keylen + stride - 1) / stride); +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function () { return (this._offset); } +}); - for (i = 0; i < saltlen; i++) - countsalt[i] = salt[i]; +Object.defineProperty(Reader.prototype, 'remain', { + get: function () { return (this._size - this._offset); } +}); - crypto_hash_sha512(sha2pass, pass, passlen); +Object.defineProperty(Reader.prototype, 'buffer', { + get: function () { return (this._buf.slice(this._offset)); } +}); - for (count = 1; keylen > 0; count++) { - countsalt[saltlen+0] = count >>> 24; - countsalt[saltlen+1] = count >>> 16; - countsalt[saltlen+2] = count >>> 8; - countsalt[saltlen+3] = count; - crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (i = out.byteLength; i--;) - out[i] = tmpout[i]; +/** + * Reads a single byte and advances offset; you can pass in `true` to make this + * a "peek" operation (i.e., get the byte, but don't advance the offset). + * + * @param {Boolean} peek true means don't move offset. + * @return {Number} the next byte, null if not enough data. + */ +Reader.prototype.readByte = function (peek) { + if (this._size - this._offset < 1) + return null; - for (i = 1; i < rounds; i++) { - crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (j = 0; j < out.byteLength; j++) - out[j] ^= tmpout[j]; - } + var b = this._buf[this._offset] & 0xff; - amt = Math.min(amt, keylen); - for (i = 0; i < amt; i++) { - dest = i * stride + (count - 1); - if (dest >= origkeylen) - break; - key[dest] = out[i]; - } - keylen -= i; - } + if (!peek) + this._offset += 1; - return 0; + return b; }; -module.exports = { - BLOCKS: BCRYPT_BLOCKS, - HASHSIZE: BCRYPT_HASHSIZE, - hash: bcrypt_hash, - pbkdf: bcrypt_pbkdf + +Reader.prototype.peek = function () { + return this.readByte(true); }; -/***/ }), +/** + * Reads a (potentially) variable length off the BER buffer. This call is + * not really meant to be called directly, as callers have to manipulate + * the internal buffer afterwards. + * + * As a result of this call, you can call `Reader.length`, until the + * next thing called that does a readLength. + * + * @return {Number} the amount of offset to advance the buffer. + * @throws {InvalidAsn1Error} on bad ASN.1 + */ +Reader.prototype.readLength = function (offset) { + if (offset === undefined) + offset = this._offset; -/***/ 3664: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + if (offset >= this._size) + return null; + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) + return null; -const { Buffer } = __nccwpck_require__(4300) -const symbol = Symbol.for('BufferList') + if ((lenB & 0x80) === 0x80) { + lenB &= 0x7f; -function BufferList (buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf) - } + if (lenB === 0) + throw newInvalidAsn1Error('Indefinite length not supported'); - BufferList._init.call(this, buf) -} + if (lenB > 4) + throw newInvalidAsn1Error('encoding too long'); -BufferList._init = function _init (buf) { - Object.defineProperty(this, symbol, { value: true }) + if (this._size - offset < lenB) + return null; - this._bufs = [] - this.length = 0 + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); - if (buf) { - this.append(buf) + } else { + // Wasn't a variable length + this._len = lenB; } -} -BufferList.prototype._new = function _new (buf) { - return new BufferList(buf) -} + return offset; +}; -BufferList.prototype._offset = function _offset (offset) { - if (offset === 0) { - return [0, 0] - } - let tot = 0 +/** + * Parses the next sequence in this BER buffer. + * + * To get the length of the sequence, call `Reader.length`. + * + * @return {Number} the sequence's tag. + */ +Reader.prototype.readSequence = function (tag) { + var seq = this.peek(); + if (seq === null) + return null; + if (tag !== undefined && tag !== seq) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + seq.toString(16)); - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot] - } - tot = _t - } -} + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; -BufferList.prototype._reverseOffset = function (blOffset) { - const bufferId = blOffset[0] - let offset = blOffset[1] + this._offset = o; + return seq; +}; - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } - return offset -} +Reader.prototype.readInt = function () { + return this._readTag(ASN1.Integer); +}; -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - const offset = this._offset(index) +Reader.prototype.readBoolean = function () { + return (this._readTag(ASN1.Boolean) === 0 ? false : true); +}; - return this._bufs[offset[0]][offset[1]] -} -BufferList.prototype.slice = function slice (start, end) { - if (typeof start === 'number' && start < 0) { - start += this.length - } +Reader.prototype.readEnumeration = function () { + return this._readTag(ASN1.Enumeration); +}; - if (typeof end === 'number' && end < 0) { - end += this.length - } - return this.copy(null, 0, start, end) -} +Reader.prototype.readString = function (tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== 'number' || srcStart < 0) { - srcStart = 0 - } + var b = this.peek(); + if (b === null) + return null; - if (typeof srcEnd !== 'number' || srcEnd > this.length) { - srcEnd = this.length - } + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - if (srcStart >= this.length) { - return dst || Buffer.alloc(0) - } + var o = this.readLength(this._offset + 1); // stored in `length` - if (srcEnd <= 0) { - return dst || Buffer.alloc(0) - } + if (o === null) + return null; - const copy = !!dst - const off = this._offset(srcStart) - const len = srcEnd - srcStart - let bytes = len - let bufoff = (copy && dstStart) || 0 - let start = off[1] + if (this.length > this._size - o) + return null; - // copy/slice everything - if (srcStart === 0 && srcEnd === this.length) { - if (!copy) { - // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } + this._offset = o; - // copy, need to copy individual buffers - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } + if (this.length === 0) + return retbuf ? Buffer.alloc(0) : ''; - return dst - } + var str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } + return retbuf ? str : str.toString('utf8'); +}; - if (!copy) { - // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - } +Reader.prototype.readOID = function (tag) { + if (!tag) + tag = ASN1.OID; - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start + var b = this.readString(tag, true); + if (b === null) + return null; - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break - } + var values = []; + var value = 0; - bytes -= l + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 0xff; - if (start) { - start = 0 + value <<= 7; + value += byte & 0x7f; + if ((byte & 0x80) === 0) { + values.push(value); + value = 0; } } - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) - - return dst -} + value = values.shift(); + values.unshift(value % 40); + values.unshift((value / 40) >> 0); -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end + return values.join('.'); +}; - if (start < 0) { - start += this.length - } - if (end < 0) { - end += this.length - } +Reader.prototype._readTag = function (tag) { + assert.ok(tag !== undefined); - if (start === end) { - return this._new() - } + var b = this.peek(); - const startOffset = this._offset(start) - const endOffset = this._offset(end) - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) + if (b === null) + return null; - if (endOffset[1] === 0) { - buffers.pop() - } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) - } + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]) - } + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; - return this._new(buffers) -} + if (this.length > 4) + throw newInvalidAsn1Error('Integer too long: ' + this.length); -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} + if (this.length > this._size - o) + return null; + this._offset = o; -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this + var fb = this._buf[this._offset]; + var value = 0; - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= (this._buf[this._offset++] & 0xff); } - return this -} + if ((fb & 0x80) === 0x80 && i !== 4) + value -= (1 << (i * 8)); -BufferList.prototype.duplicate = function duplicate () { - const copy = this._new() + return value >> 0; +}; - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]) - } - return copy -} -BufferList.prototype.append = function append (buf) { - if (buf == null) { - return this - } +// --- Exported API - if (buf.buffer) { - // append a view of the underlying ArrayBuffer - this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]) - } - } else if (this._isBufferList(buf)) { - // unwrap argument into individual BufferLists - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]) - } - } else { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf === 'number') { - buf = buf.toString() - } +module.exports = Reader; - this._appendBuffer(Buffer.from(buf)) - } - return this -} +/***/ }), -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} +/***/ 2473: +/***/ ((module) => { -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } +// Copyright 2011 Mark Cavage All rights reserved. - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (this._isBufferList(search)) { - search = search.slice() - } else if (Array.isArray(search.buffer)) { - search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } - offset = Number(offset || 0) +module.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 +}; - if (isNaN(offset)) { - offset = 0 - } - if (offset < 0) { - offset = this.length + offset - } +/***/ }), - if (offset < 0) { - offset = 0 - } +/***/ 3200: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (search.length === 0) { - return offset > this.length ? this.length : offset - } +// Copyright 2011 Mark Cavage All rights reserved. - const blOffset = this._offset(offset) - let blIndex = blOffset[0] // index of which internal buffer we're working on - let buffOffset = blOffset[1] // offset of the internal buffer we're working on +var assert = __nccwpck_require__(9491); +var Buffer = (__nccwpck_require__(5118).Buffer); +var ASN1 = __nccwpck_require__(2473); +var errors = __nccwpck_require__(9348); - // scan over each buffer - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex] - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset +// --- Globals - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset) +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) - } +var DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 +}; - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]) - if (this._match(revOffset, search)) { - return revOffset - } +// --- Helpers - buffOffset++ - } - } +function merge(from, to) { + assert.ok(from); + assert.equal(typeof (from), 'object'); + assert.ok(to); + assert.equal(typeof (to), 'object'); - buffOffset = 0 - } + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function (key) { + if (to[key]) + return; - return -1 + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); + }); + + return to; } -BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false - } - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false - } - } - return true -} -;(function () { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null - } +// --- API - for (const m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } else { - BufferList.prototype[m] = function (offset = 0) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) +function Writer(options) { + options = merge(DEFAULT_OPTS, options || {}); -// Used internally by the class and also as an indicator of this object being -// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser -// environment because there could be multiple different copies of the -// BufferList class and some `BufferList`s might be `BufferList`s. -BufferList.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferList || BufferList.isBufferList(b) -} + this._buf = Buffer.alloc(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; -BufferList.isBufferList = function isBufferList (b) { - return b != null && b[symbol] + // A list of offsets in the buffer where we need to insert + // sequence tag/len pairs. + this._seq = []; } -module.exports = BufferList +Object.defineProperty(Writer.prototype, 'buffer', { + get: function () { + if (this._seq.length) + throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); + return (this._buf.slice(0, this._offset)); + } +}); -/***/ }), +Writer.prototype.writeByte = function (b) { + if (typeof (b) !== 'number') + throw new TypeError('argument must be a Number'); -/***/ 336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._ensure(1); + this._buf[this._offset++] = b; +}; -"use strict"; +Writer.prototype.writeInt = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Integer; -const DuplexStream = (__nccwpck_require__(1642).Duplex) -const inherits = __nccwpck_require__(4124) -const BufferList = __nccwpck_require__(3664) + var sz = 4; -function BufferListStream (callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback) + while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && + (sz > 1)) { + sz--; + i <<= 8; } - if (typeof callback === 'function') { - this._callback = callback - - const piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) + if (sz > 4) + throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; - callback = null + while (sz-- > 0) { + this._buf[this._offset++] = ((i & 0xff000000) >>> 24); + i <<= 8; } - BufferList._init.call(this, callback) - DuplexStream.call(this) -} - -inherits(BufferListStream, DuplexStream) -Object.assign(BufferListStream.prototype, BufferList.prototype) +}; -BufferListStream.prototype._new = function _new (callback) { - return new BufferListStream(callback) -} -BufferListStream.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) +Writer.prototype.writeNull = function () { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; - if (typeof callback === 'function') { - callback() - } -} -BufferListStream.prototype._read = function _read (size) { - if (!this.length) { - return this.push(null) - } +Writer.prototype.writeEnumeration = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Enumeration; - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} + return this.writeInt(i, tag); +}; -BufferListStream.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} +Writer.prototype.writeBoolean = function (b, tag) { + if (typeof (b) !== 'boolean') + throw new TypeError('argument must be a Boolean'); + if (typeof (tag) !== 'number') + tag = ASN1.Boolean; -BufferListStream.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) -} + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; -BufferListStream.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) -} -BufferListStream.isBufferList = BufferList.isBufferList +Writer.prototype.writeString = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); + if (typeof (tag) !== 'number') + tag = ASN1.OctetString; -module.exports = BufferListStream -module.exports.BufferListStream = BufferListStream -module.exports.BufferList = BufferList + var len = Buffer.byteLength(s); + this.writeByte(tag); + this.writeLength(len); + if (len) { + this._ensure(len); + this._buf.write(s, this._offset); + this._offset += len; + } +}; -/***/ }), +Writer.prototype.writeBuffer = function (buf, tag) { + if (typeof (tag) !== 'number') + throw new TypeError('tag must be a number'); + if (!Buffer.isBuffer(buf)) + throw new TypeError('argument must be a buffer'); -/***/ 9051: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; -"use strict"; -const fs = __nccwpck_require__(7147) -const path = __nccwpck_require__(1017) +Writer.prototype.writeStringArray = function (strings) { + if ((!strings instanceof Array)) + throw new TypeError('argument must be an Array[String]'); -/* istanbul ignore next */ -const LCHOWN = fs.lchown ? 'lchown' : 'chown' -/* istanbul ignore next */ -const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' + var self = this; + strings.forEach(function (s) { + self.writeString(s); + }); +}; -/* istanbul ignore next */ -const needEISDIRHandled = fs.lchown && - !process.version.match(/v1[1-9]+\./) && - !process.version.match(/v10\.[6-9]/) +// This is really to solve DER cases, but whatever for now +Writer.prototype.writeOID = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string'); + if (typeof (tag) !== 'number') + tag = ASN1.OID; -const lchownSync = (path, uid, gid) => { - try { - return fs[LCHOWNSYNC](path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } -} + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error('argument is not a valid OID string'); -/* istanbul ignore next */ -const chownSync = (path, uid, gid) => { - try { - return fs.chownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er + function encodeOctet(bytes, octet) { + if (octet < 128) { + bytes.push(octet); + } else if (octet < 16384) { + bytes.push((octet >>> 7) | 0x80); + bytes.push(octet & 0x7F); + } else if (octet < 2097152) { + bytes.push((octet >>> 14) | 0x80); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else if (octet < 268435456) { + bytes.push((octet >>> 21) | 0x80); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else { + bytes.push(((octet >>> 28) | 0x80) & 0xFF); + bytes.push(((octet >>> 21) | 0x80) & 0xFF); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } } -} -/* istanbul ignore next */ -const handleEISDIR = - needEISDIRHandled ? (path, uid, gid, cb) => er => { - // Node prior to v10 had a very questionable implementation of - // fs.lchown, which would always try to call fs.open on a directory - // Fall back to fs.chown in those cases. - if (!er || er.code !== 'EISDIR') - cb(er) - else - fs.chown(path, uid, gid, cb) - } - : (_, __, ___, cb) => cb + var tmp = s.split('.'); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function (b) { + encodeOctet(bytes, parseInt(b, 10)); + }); -/* istanbul ignore next */ -const handleEISDirSync = - needEISDIRHandled ? (path, uid, gid) => { - try { - return lchownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'EISDIR') - throw er - chownSync(path, uid, gid) - } - } - : (path, uid, gid) => lchownSync(path, uid, gid) + var self = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function (b) { + self.writeByte(b); + }); +}; -// fs.readdir could only accept an options object as of node v6 -const nodeVersion = process.version -let readdir = (path, options, cb) => fs.readdir(path, options, cb) -let readdirSync = (path, options) => fs.readdirSync(path, options) -/* istanbul ignore next */ -if (/^v4\./.test(nodeVersion)) - readdir = (path, options, cb) => fs.readdir(path, cb) -const chown = (cpath, uid, gid, cb) => { - fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { - // Skip ENOENT error - cb(er && er.code !== 'ENOENT' ? er : null) - })) -} +Writer.prototype.writeLength = function (len) { + if (typeof (len) !== 'number') + throw new TypeError('argument must be a Number'); -const chownrKid = (p, child, uid, gid, cb) => { - if (typeof child === 'string') - return fs.lstat(path.resolve(p, child), (er, stats) => { - // Skip ENOENT error - if (er) - return cb(er.code !== 'ENOENT' ? er : null) - stats.name = child - chownrKid(p, stats, uid, gid, cb) - }) + this._ensure(4); - if (child.isDirectory()) { - chownr(path.resolve(p, child.name), uid, gid, er => { - if (er) - return cb(er) - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - }) + if (len <= 0x7f) { + this._buf[this._offset++] = len; + } else if (len <= 0xff) { + this._buf[this._offset++] = 0x81; + this._buf[this._offset++] = len; + } else if (len <= 0xffff) { + this._buf[this._offset++] = 0x82; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 0xffffff) { + this._buf[this._offset++] = 0x83; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; } else { - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) + throw newInvalidAsn1Error('Length too long (> 4 bytes)'); } -} +}; +Writer.prototype.startSequence = function (tag) { + if (typeof (tag) !== 'number') + tag = ASN1.Sequence | ASN1.Constructor; -const chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { - // any error other than ENOTDIR or ENOTSUP means it's not readable, - // or doesn't exist. give up. - if (er) { - if (er.code === 'ENOENT') - return cb() - else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') - return cb(er) - } - if (er || !children.length) - return chown(p, uid, gid, cb) + this.writeByte(tag); + this._seq.push(this._offset); + this._ensure(3); + this._offset += 3; +}; - let len = children.length - let errState = null - const then = er => { - if (errState) - return - if (er) - return cb(errState = er) - if (-- len === 0) - return chown(p, uid, gid, cb) - } - children.forEach(child => chownrKid(p, child, uid, gid, then)) - }) -} +Writer.prototype.endSequence = function () { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; -const chownrKidSync = (p, child, uid, gid) => { - if (typeof child === 'string') { - try { - const stats = fs.lstatSync(path.resolve(p, child)) - stats.name = child - child = stats - } catch (er) { - if (er.code === 'ENOENT') - return - else - throw er - } + if (len <= 0x7f) { + this._shift(start, len, -2); + this._buf[seq] = len; + } else if (len <= 0xff) { + this._shift(start, len, -1); + this._buf[seq] = 0x81; + this._buf[seq + 1] = len; + } else if (len <= 0xffff) { + this._buf[seq] = 0x82; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 0xffffff) { + this._shift(start, len, 1); + this._buf[seq] = 0x83; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw newInvalidAsn1Error('Sequence too long'); } +}; - if (child.isDirectory()) - chownrSync(path.resolve(p, child.name), uid, gid) - handleEISDirSync(path.resolve(p, child.name), uid, gid) -} +Writer.prototype._shift = function (start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); -const chownrSync = (p, uid, gid) => { - let children - try { - children = readdirSync(p, { withFileTypes: true }) - } catch (er) { - if (er.code === 'ENOENT') - return - else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') - return handleEISDirSync(p, uid, gid) - else - throw er + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; +}; + +Writer.prototype._ensure = function (len) { + assert.ok(len); + + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) + sz += len; + + var buf = Buffer.alloc(sz); + + this._buf.copy(buf, 0, 0, this._offset); + this._buf = buf; + this._size = sz; } +}; - if (children && children.length) - children.forEach(child => chownrKidSync(p, child, uid, gid)) - return handleEISDirSync(p, uid, gid) -} -module.exports = chownr -chownr.sync = chownrSync +// --- Exported API + +module.exports = Writer; /***/ }), -/***/ 4137: +/***/ 970: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const binding = __nccwpck_require__(4240); +// Copyright 2011 Mark Cavage All rights reserved. -module.exports = binding.getCPUInfo; +// If you have no idea what ASN.1 or BER is, see this: +// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc + +var Ber = __nccwpck_require__(194); + + + +// --- Exported API + +module.exports = { + + Ber: Ber, + + BerReader: Ber.Reader, + + BerWriter: Ber.Writer + +}; /***/ }), -/***/ 8222: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 5447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* eslint-env browser */ +"use strict"; -/** - * This is the web browser implementation of `debug()`. - */ -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; +var crypto_hash_sha512 = (__nccwpck_require__(8729).lowlevel.crypto_hash); - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. + * + * Credit for the actual porting work goes to: + * Devi Mandiri + */ -/** - * Colors. +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 + +var BLF_J = 0; + +var Blowfish = function() { + this.S = [ + new Uint32Array([ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), + new Uint32Array([ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), + new Uint32Array([ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), + new Uint32Array([ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) + ]; + this.P = new Uint32Array([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b]); +}; + +function F(S, x8, i) { + return (((S[0][x8[i+3]] + + S[1][x8[i+2]]) ^ + S[2][x8[i+1]]) + + S[3][x8[i]]); +}; + +Blowfish.prototype.encipher = function(x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + } + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; +}; + +Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; + +function stream2word(data, databytes){ + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +}; + +Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; + + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; + } + } +}; + +Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; + } + } + BLF_J = 0; +}; + +Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i*2)); + } +}; + +Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i*2)); + } +}; + +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; + +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), i, + ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, + 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, + 105,116,101]); //"OxychromaticBlowfishSwatDynamite" + + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } + + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); + + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4*i+3] = cdata[i] >>> 24; + out[4*i+2] = cdata[i] >>> 16; + out[4*i+1] = cdata[i] >>> 8; + out[4*i+0] = cdata[i]; + } +}; + +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen+4), + i, j, amt, stride, dest, count, + origkeylen = keylen; + + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || + keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) + return -1; + + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); + + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; + + crypto_hash_sha512(sha2pass, pass, passlen); + + for (count = 1; keylen > 0; count++) { + countsalt[saltlen+0] = count >>> 24; + countsalt[saltlen+1] = count >>> 16; + countsalt[saltlen+2] = count >>> 8; + countsalt[saltlen+3] = count; + + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--;) + out[i] = tmpout[i]; + + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; + } + + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; + } + keylen -= i; + } + + return 0; +}; + +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf +}; + + +/***/ }), + +/***/ 9051: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const fs = __nccwpck_require__(7147) +const path = __nccwpck_require__(1017) + +/* istanbul ignore next */ +const LCHOWN = fs.lchown ? 'lchown' : 'chown' +/* istanbul ignore next */ +const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' + +/* istanbul ignore next */ +const needEISDIRHandled = fs.lchown && + !process.version.match(/v1[1-9]+\./) && + !process.version.match(/v10\.[6-9]/) + +const lchownSync = (path, uid, gid) => { + try { + return fs[LCHOWNSYNC](path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } +} + +/* istanbul ignore next */ +const chownSync = (path, uid, gid) => { + try { + return fs.chownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } +} + +/* istanbul ignore next */ +const handleEISDIR = + needEISDIRHandled ? (path, uid, gid, cb) => er => { + // Node prior to v10 had a very questionable implementation of + // fs.lchown, which would always try to call fs.open on a directory + // Fall back to fs.chown in those cases. + if (!er || er.code !== 'EISDIR') + cb(er) + else + fs.chown(path, uid, gid, cb) + } + : (_, __, ___, cb) => cb + +/* istanbul ignore next */ +const handleEISDirSync = + needEISDIRHandled ? (path, uid, gid) => { + try { + return lchownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'EISDIR') + throw er + chownSync(path, uid, gid) + } + } + : (path, uid, gid) => lchownSync(path, uid, gid) + +// fs.readdir could only accept an options object as of node v6 +const nodeVersion = process.version +let readdir = (path, options, cb) => fs.readdir(path, options, cb) +let readdirSync = (path, options) => fs.readdirSync(path, options) +/* istanbul ignore next */ +if (/^v4\./.test(nodeVersion)) + readdir = (path, options, cb) => fs.readdir(path, cb) + +const chown = (cpath, uid, gid, cb) => { + fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { + // Skip ENOENT error + cb(er && er.code !== 'ENOENT' ? er : null) + })) +} + +const chownrKid = (p, child, uid, gid, cb) => { + if (typeof child === 'string') + return fs.lstat(path.resolve(p, child), (er, stats) => { + // Skip ENOENT error + if (er) + return cb(er.code !== 'ENOENT' ? er : null) + stats.name = child + chownrKid(p, stats, uid, gid, cb) + }) + + if (child.isDirectory()) { + chownr(path.resolve(p, child.name), uid, gid, er => { + if (er) + return cb(er) + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + }) + } else { + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + } +} + + +const chownr = (p, uid, gid, cb) => { + readdir(p, { withFileTypes: true }, (er, children) => { + // any error other than ENOTDIR or ENOTSUP means it's not readable, + // or doesn't exist. give up. + if (er) { + if (er.code === 'ENOENT') + return cb() + else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') + return cb(er) + } + if (er || !children.length) + return chown(p, uid, gid, cb) + + let len = children.length + let errState = null + const then = er => { + if (errState) + return + if (er) + return cb(errState = er) + if (-- len === 0) + return chown(p, uid, gid, cb) + } + + children.forEach(child => chownrKid(p, child, uid, gid, then)) + }) +} + +const chownrKidSync = (p, child, uid, gid) => { + if (typeof child === 'string') { + try { + const stats = fs.lstatSync(path.resolve(p, child)) + stats.name = child + child = stats + } catch (er) { + if (er.code === 'ENOENT') + return + else + throw er + } + } + + if (child.isDirectory()) + chownrSync(path.resolve(p, child.name), uid, gid) + + handleEISDirSync(path.resolve(p, child.name), uid, gid) +} + +const chownrSync = (p, uid, gid) => { + let children + try { + children = readdirSync(p, { withFileTypes: true }) + } catch (er) { + if (er.code === 'ENOENT') + return + else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') + return handleEISDirSync(p, uid, gid) + else + throw er + } + + if (children && children.length) + children.forEach(child => chownrKidSync(p, child, uid, gid)) + + return handleEISDirSync(p, uid, gid) +} + +module.exports = chownr +chownr.sync = chownrSync + + +/***/ }), + +/***/ 4137: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const binding = __nccwpck_require__(4240); + +module.exports = binding.getCPUInfo; + + +/***/ }), + +/***/ 8222: +/***/ ((module, exports, __nccwpck_require__) => { + +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', @@ -3817,33104 +5200,57127 @@ exports.colors = [ '#FFCC33' ]; -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = __nccwpck_require__(6243)(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; + + +/***/ }), + +/***/ 6243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(900); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; + + +/***/ }), + +/***/ 8237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(8222); +} else { + module.exports = __nccwpck_require__(4874); +} + + +/***/ }), + +/***/ 4874: +/***/ ((module, exports, __nccwpck_require__) => { + +/** + * Module dependencies. + */ + +const tty = __nccwpck_require__(6224); +const util = __nccwpck_require__(3837); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(9318); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = __nccwpck_require__(6243)(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + + +/***/ }), + +/***/ 4305: +/***/ ((module, exports, __nccwpck_require__) => { + +//Based on follow-redirects v0.0.x + +var nativeHttps = __nccwpck_require__(5687), + nativeHttp = __nccwpck_require__(3685), + url = __nccwpck_require__(7310), + utils = __nccwpck_require__(4967); + +var maxRedirects = module.exports.maxRedirects = 5; + +var protocols = { + https: nativeHttps, + http: nativeHttp +}; + +for (var protocol in protocols) { + var h = function() {}; + h.prototype = protocols[protocol]; + h = new h(); + + h.request = function(h) { + return function(options, callback, redirectOptions) { + + redirectOptions = redirectOptions || {}; + + var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects; + + var redirect = utils.extend({ + count: 0, + max: max, + clientRequest: null, + userCallback: callback + }, redirectOptions); + + if (redirect.count > redirect.max) { + var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.'); + redirect.clientRequest.emit('error', err); + return redirect.clientRequest; + } + + redirect.count++; + + var reqUrl; + if (typeof options === 'string') { + reqUrl = options; + } else { + reqUrl = url.format(utils.extend({ + protocol: protocol + }, options)); + } + + var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect)); + + if (!redirect.clientRequest) redirect.clientRequest = clientRequest; + + function redirectCallback(reqUrl, redirect) { + return function(res) { + if (res.statusCode < 300 || res.statusCode > 399) { + return redirect.userCallback(res); + } + + if (!('location' in res.headers)) { + return redirect.userCallback(res); + } + + var redirectUrl = url.resolve(reqUrl, res.headers.location); + + var proto = url.parse(redirectUrl).protocol; + proto = proto.substr(0, proto.length - 1); + return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect); + }; + } + + return clientRequest; + }; + }(h); + + // see https://github.com/joyent/node/blob/master/lib/http.js#L1623 + h.get = function(h) { + return function(options, cb, redirectOptions) { + var req = h.request(options, cb, redirectOptions); + req.end(); + return req; + }; + }(h); + + module.exports[protocol] = h; +} + + +/***/ }), + +/***/ 3855: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = HttpDuplex; + +var util = __nccwpck_require__(3837), + stream = __nccwpck_require__(1642); + +util.inherits(HttpDuplex, stream.Duplex); + +function HttpDuplex(req, res, options) { + var self = this; + + if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options); + + stream.Duplex.call(self, options); + self._output = null; + + self.connect(req, res); +} + +HttpDuplex.prototype.connect = function(req, res) { + var self = this; + self.req = req; + self._output = res; + self.emit('response', res); + + res.on('data', function(c) { + if (!self.push(c)) self._output.pause(); + }); + res.on('end', function() { + self.push(null); + }); +}; + +HttpDuplex.prototype._read = function(n) { + if (this._output) this._output.resume(); +}; + +HttpDuplex.prototype._write = function(chunk, encoding, cb) { + this.req.write(chunk, encoding); + cb(); +}; + +HttpDuplex.prototype.end = function(chunk, encoding, cb) { + this._output.socket.destroySoon(); + return this.req.end(chunk, encoding, cb); +}; + +HttpDuplex.prototype.destroy = function() { + this.req.destroy(); + this._output.socket.destroy(); +}; + +HttpDuplex.prototype.destroySoon = function() { + this.req.destroy(); + this._output.socket.destroy(); +}; + + +/***/ }), + +/***/ 6042: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var querystring = __nccwpck_require__(3477), + http = __nccwpck_require__(4305), + fs = __nccwpck_require__(7147), + path = __nccwpck_require__(1017), + url = __nccwpck_require__(7310), + ssh = __nccwpck_require__(7964), + HttpDuplex = __nccwpck_require__(3855), + debug = __nccwpck_require__(8237)('modem'), + utils = __nccwpck_require__(4967), + util = __nccwpck_require__(3837), + splitca = __nccwpck_require__(9798), + os = __nccwpck_require__(2037), + isWin = os.type() === 'Windows_NT', + stream = __nccwpck_require__(2781); + +var defaultOpts = function () { + var host; + var opts = {}; + + if (!process.env.DOCKER_HOST) { + // Windows socket path: //./pipe/docker_engine ( Windows 10 ) + // Linux & Darwin socket path is /var/run/docker.sock when running system-wide, + // or $HOME/.docker/run/docker.sock in new Docker Desktop installs. + opts.socketPath = isWin ? '//./pipe/docker_engine' : findDefaultUnixSocket; + } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) { + // Strip off unix://, fall back to default if unix:// was passed without a path + opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket; + } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) { + // Strip off npipe://, fall back to default of //./pipe/docker_engine if + // npipe:// was passed without a path + opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine'; + } else { + var hostStr = process.env.DOCKER_HOST; + if (hostStr.indexOf('\/\/') < 0) { + hostStr = 'tcp://' + hostStr; + } + try { + host = new url.URL(hostStr); + } catch (err) { + throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234'); + } + + opts.port = host.port; + + if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') { + opts.protocol = 'https'; + } else if (host.protocol === 'ssh:') { + opts.protocol = 'ssh'; + opts.username = host.username; + opts.sshOptions = { + agent: process.env.SSH_AUTH_SOCK, + } + } else { + opts.protocol = 'http'; + } + + if (process.env.DOCKER_PATH_PREFIX) { + opts.pathPrefix = process.env.DOCKER_PATH_PREFIX; + } + else { + opts.pathPrefix = '/'; + } + + opts.host = host.hostname; + + if (process.env.DOCKER_CERT_PATH) { + opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem')); + opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem')); + opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem')); + } + + if (process.env.DOCKER_CLIENT_TIMEOUT) { + opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); + } + } + + return opts; +}; + +var findDefaultUnixSocket = function () { + return new Promise(function (resolve) { + var userDockerSocket = path.join(os.homedir(), '.docker', 'run', 'docker.sock'); + fs.access(userDockerSocket, function (err) { + if (err) resolve('/var/run/docker.sock'); + else resolve(userDockerSocket); + }) + }); +} + + +var Modem = function (options) { + var optDefaults = defaultOpts(); + var opts = Object.assign({}, optDefaults, options); + + this.host = opts.host; + + if (!this.host) { + this.socketPath = opts.socketPath; + } + + this.port = opts.port; + this.pathPrefix = opts.pathPrefix; + this.username = opts.username; + this.password = opts.password; + this.version = opts.version; + this.key = opts.key; + this.cert = opts.cert; + this.ca = opts.ca; + this.timeout = opts.timeout; + this.connectionTimeout = opts.connectionTimeout; + this.checkServerIdentity = opts.checkServerIdentity; + this.agent = opts.agent; + this.headers = opts.headers || {}; + this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); + //retrocompabitlity + if (this.sshOptions.agentForward === undefined) { + this.sshOptions.agentForward = opts.agentForward; + } + + if (this.key && this.cert && this.ca) { + this.protocol = 'https'; + } + this.protocol = opts.protocol || this.protocol || 'http'; +}; + +Modem.prototype.dial = function (options, callback) { + var opts, address, data; + + if (options.options) { + opts = options.options; + } + + // Prevent credentials from showing up in URL + if (opts && opts.authconfig) { + delete opts.authconfig; + } + + // Prevent abortsignal from showing up in the URL + if (opts && opts.abortSignal) { + delete opts.abortSignal; + } + + if (this.version) { + options.path = '/' + this.version + options.path; + } + + if (this.host) { + var parsed = url.parse(this.host); + address = url.format({ + protocol: parsed.protocol || this.protocol, + hostname: parsed.hostname || this.host, + port: this.port, + pathname: parsed.pathname || this.pathPrefix, + }); + address = url.resolve(address, options.path); + } else { + address = options.path; + } + + if (options.path.indexOf('?') !== -1) { + if (opts && Object.keys(opts).length > 0) { + address += this.buildQuerystring(opts._query || opts); + } else { + address = address.substring(0, address.length - 1); + } + } + + var optionsf = { + path: address, + method: options.method, + headers: options.headers || Object.assign({}, this.headers), + key: this.key, + cert: this.cert, + ca: this.ca + }; + + + if (this.checkServerIdentity) { + optionsf.checkServerIdentity = this.checkServerIdentity; + } + + if (this.agent) { + optionsf.agent = this.agent; + } + + if (options.authconfig) { + optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 || + Buffer.from(JSON.stringify(options.authconfig)).toString('base64').replace(/\+/g, "-").replace(/\//g, "_"); + } + + if (options.registryconfig) { + optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 || + Buffer.from(JSON.stringify(options.registryconfig)).toString('base64'); + } + + if (options.abortSignal) { + optionsf.signal = options.abortSignal; + } + + if (options.file) { + if (typeof options.file === 'string') { + data = fs.createReadStream(path.resolve(options.file)); + } else { + data = options.file; + } + optionsf.headers['Content-Type'] = 'application/tar'; + } else if (opts && options.method === 'POST') { + data = JSON.stringify(opts._body || opts); + if (options.allowEmpty) { + optionsf.headers['Content-Type'] = 'application/json'; + } else { + if (data !== '{}' && data !== '""') { + optionsf.headers['Content-Type'] = 'application/json'; + } else { + data = undefined; + } + } + } + + if (typeof data === 'string') { + optionsf.headers['Content-Length'] = Buffer.byteLength(data); + } else if (Buffer.isBuffer(data) === true) { + optionsf.headers['Content-Length'] = data.length; + } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) { + optionsf.headers['Transfer-Encoding'] = 'chunked'; + } + + if (options.hijack) { + optionsf.headers.Connection = 'Upgrade'; + optionsf.headers.Upgrade = 'tcp'; + } + + if (this.socketPath) { + // SocketPath may be a function that can return a promise: + this.getSocketPath().then((socketPath) => { + optionsf.socketPath = socketPath; + this.buildRequest(optionsf, options, data, callback); + }); + } else { + var urlp = url.parse(address); + optionsf.hostname = urlp.hostname; + optionsf.port = urlp.port; + optionsf.path = urlp.path; + + this.buildRequest(optionsf, options, data, callback); + } +}; + +Modem.prototype.getSocketPath = function () { + if (!this.socketPath) return; + if (this.socketPathCache) return Promise.resolve(this.socketPathCache); + + var socketPathValue = typeof this.socketPath === 'function' + ? this.socketPath() : this.socketPath; + + this.socketPathCache = socketPathValue; + + return Promise.resolve(socketPathValue); +} + +Modem.prototype.buildRequest = function (options, context, data, callback) { + var self = this; + var connectionTimeoutTimer; + var finished = false; + + var opts = self.protocol === 'ssh' ? Object.assign(options, { + agent: ssh(Object.assign({}, self.sshOptions, { + 'host': self.host, + 'port': self.port, + 'username': self.username, + 'password': self.password, + })), + protocol: 'http:', + }) : options; + + var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { }); + + debug('Sending: %s', util.inspect(options, { + showHidden: true, + depth: null + })); + + if (self.connectionTimeout) { + connectionTimeoutTimer = setTimeout(function () { + debug('Connection Timeout of %s ms exceeded', self.connectionTimeout); + req.abort(); + }, self.connectionTimeout); + } + + if (self.timeout) { + req.on('socket', function (socket) { + socket.setTimeout(self.timeout); + socket.on('timeout', function () { + debug('Timeout of %s ms exceeded', self.timeout); + req.abort(); + }); + }); + } + + if (context.hijack === true) { + clearTimeout(connectionTimeoutTimer); + req.on('upgrade', function (res, sock, head) { + if (finished === false) { + finished = true; + return callback(null, sock); + } + }); + } + + req.on('connect', function () { + clearTimeout(connectionTimeoutTimer); + }); + + req.on('disconnect', function () { + clearTimeout(connectionTimeoutTimer); + }); + + req.on('response', function (res) { + clearTimeout(connectionTimeoutTimer); + if (context.isStream === true) { + if (finished === false) { + finished = true; + self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback); + } + } else { + // The native 'request' method only handles aborting during the request lifecycle not the response lifecycle. + // We need to make the response stream abortable so that it's destroyed with an error on abort and then + // it triggers the request 'error' event + if (options.signal != null) { + stream.addAbortSignal(options.signal, res) + } + var chunks = []; + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + var buffer = Buffer.concat(chunks); + var result = buffer.toString(); + + debug('Received: %s', result); + + var json = utils.parseJSON(result) || buffer; + if (finished === false) { + finished = true; + self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback); + } + }); + } + }); + + req.on('error', function (error) { + clearTimeout(connectionTimeoutTimer); + if (finished === false) { + finished = true; + self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback); + } + }); + + if (typeof data === 'string' || Buffer.isBuffer(data)) { + req.write(data); + } else if (data) { + data.on('error', function (error) { + req.destroy(error); + }); + data.pipe(req); + } + + if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) { + req.end(); + } +}; + +Modem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) { + if (err) return cb(err, null); + + if (statusCodes[res.statusCode] !== true) { + getCause(isStream, res, json, function (err, cause) { + if (err) { + return cb(err, null); + } + var msg = new Error( + '(HTTP code ' + res.statusCode + ') ' + + (statusCodes[res.statusCode] || 'unexpected') + ' - ' + + (cause.message || cause) + ' ' + ); + msg.reason = statusCodes[res.statusCode]; + msg.statusCode = res.statusCode; + msg.json = json; + cb(msg, null); + }); + } else { + if (openStdin) { + cb(null, new HttpDuplex(req, res)); + } else if (isStream) { + cb(null, res); + } else { + cb(null, json); + } + } + + function getCause(isStream, res, json, callback) { + var chunks = ''; + var done = false; + + if (isStream) { + res.on('data', function (chunk) { + chunks += chunk; + }); + res.on('error', function (err) { + handler(err, null); + }); + res.on('end', function () { + handler(null, utils.parseJSON(chunks) || chunks) + }); + } else { + callback(null, json); + } + + function handler(err, data) { + if (done === false) { + if (err) { + callback(err); + } else { + callback(null, data); + } + } + done = true; + } + } +}; + +Modem.prototype.demuxStream = function (streama, stdout, stderr) { + var nextDataType = null; + var nextDataLength = null; + var buffer = Buffer.from(''); + function processData(data) { + if (data) { + buffer = Buffer.concat([buffer, data]); + } + if (!nextDataType) { + if (buffer.length >= 8) { + var header = bufferSlice(8); + nextDataType = header.readUInt8(0); + nextDataLength = header.readUInt32BE(4); + // It's possible we got a "data" that contains multiple messages + // Process the next one + processData(); + } + } else { + if (buffer.length >= nextDataLength) { + var content = bufferSlice(nextDataLength); + if (nextDataType === 1) { + stdout.write(content); + } else { + stderr.write(content); + } + nextDataType = null; + // It's possible we got a "data" that contains multiple messages + // Process the next one + processData(); + } + } + } + + function bufferSlice(end) { + var out = buffer.subarray(0, end); + buffer = Buffer.from(buffer.subarray(end, buffer.length)); + return out; + } + + streama.on('data', processData); +}; + +Modem.prototype.followProgress = function (streama, onFinished, onProgress) { + var buf = ''; + var output = []; + var finished = false; + + streama.on('data', onStreamEvent); + streama.on('error', onStreamError); + streama.on('end', onStreamEnd); + streama.on('close', onStreamEnd); + + function onStreamEvent(data) { + buf += data.toString(); + pump(); + + function pump() { + var pos; + while ((pos = buf.indexOf('\n')) >= 0) { + if (pos == 0) { + buf = buf.slice(1); + continue; + } + processLine(buf.slice(0, pos)); + buf = buf.slice(pos + 1); + } + } + + function processLine(line) { + if (line[line.length - 1] == '\r') line = line.substr(0, line.length - 1); + if (line.length > 0) { + var obj = JSON.parse(line); + output.push(obj); + if (onProgress) { + onProgress(obj); + } + } + } + }; + + function onStreamError(err) { + finished = true; + streama.removeListener('data', onStreamEvent); + streama.removeListener('error', onStreamError); + streama.removeListener('end', onStreamEnd); + streama.removeListener('close', onStreamEnd); + onFinished(err, output); + } + + function onStreamEnd() { + if (!finished) onFinished(null, output); + finished = true; + } +}; + +Modem.prototype.buildQuerystring = function (opts) { + var clone = {}; + + // serialize map and array values as JSON strings, else querystring truncates. + // 't' and 'extrahosts' can be arrays but need special treatment so that they're + // passed as multiple qs parameters instead of JSON values. + Object.keys(opts).map(function (key, i) { + if (opts[key] + && typeof opts[key] === 'object' + && !['t', 'extrahosts'].includes(key) + ) { + clone[key] = JSON.stringify(opts[key]); + } else { + clone[key] = opts[key]; + } + }); + + return querystring.stringify(clone); +}; + +module.exports = Modem; + + +/***/ }), + +/***/ 7964: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Client = (__nccwpck_require__(5869).Client), + http = __nccwpck_require__(3685); + +module.exports = function (opt) { + var conn = new Client(); + var agent = new http.Agent(); + + agent.createConnection = function (options, fn) { + try { + conn.once('ready', function () { + conn.exec('docker system dial-stdio', function (err, stream) { + if (err) { + handleError(err); + } + + fn(null, stream); + + stream.addListener('error', (err) => { + handleError(err); + }); + stream.once('close', () => { + conn.end(); + agent.destroy(); + }); + }); + }).on('error', (err) => { + handleError(err); + }) + .connect(opt); + conn.once('end', () => agent.destroy()); + + } catch (err) { + handleError(err); + } + }; + + function handleError(err) { + conn.end(); + agent.destroy(); + throw err; + } + + return agent; +}; + + +/***/ }), + +/***/ 4967: +/***/ ((module) => { + +// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js + +var arr = []; +var each = arr.forEach; +var slice = arr.slice; + +module.exports.extend = function(obj) { + each.call(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }); + return obj; +}; + +module.exports.parseJSON = function(s) { + try { + return JSON.parse(s); + } catch (e) { + return null; + } +}; + + +/***/ }), + +/***/ 5004: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents a config + * @param {Object} modem docker-modem + * @param {String} id Config's id + */ +var Config = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Config.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Config.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/configs/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'config not found', + 500: 'server error', + 503: 'node is not part of a swarm' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update a config. + * + * @param {object} opts + * @param {function} callback + */ +Config.prototype.update = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/configs/' + this.id + '/update?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'config not found', + 500: 'server error', + 503: 'node is not part of a swarm' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Removes the config + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Config.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/configs/' + this.id, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'config not found', + 500: 'server error', + 503: 'node is not part of a swarm' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + + +module.exports = Config; + + +/***/ }), + +/***/ 5815: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var extend = (__nccwpck_require__(1604).extend), + Exec = __nccwpck_require__(3149), + util = __nccwpck_require__(1604); + +/** + * Represents a Container + * @param {Object} modem docker-modem + * @param {String} id Container's ID + */ +var Container = function(modem, id) { + this.modem = modem; + this.id = id; + + this.defaultOptions = { + top: {}, + start: {}, + commit: {}, + stop: {}, + pause: {}, + unpause: {}, + restart: {}, + resize: {}, + attach: {}, + remove: {}, + copy: {}, + kill: {}, + exec: {}, + rename: {}, + log: {}, + stats: {}, + getArchive: {}, + infoArchive: {}, + putArchive: {}, + update: {}, + wait: {} + }; +}; + +Container.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if supplied will query Docker. + * @return {Object} ID only and only if callback isn't supplied. + */ +Container.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/json?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Rename + * @param {Object} opts Rename options + * @param {Function} callback Callback + */ +Container.prototype.rename = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.rename); + + var optsf = { + path: '/containers/' + this.id + '/rename?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update + * @param {Object} opts Update options + * @param {Function} callback Callback + */ +Container.prototype.update = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.update); + + var optsf = { + path: '/containers/' + this.id + '/update', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 400: 'bad parameter', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Top + * @param {Object} opts like 'ps_args' (optional) + * @param {Function} callback Callback + */ +Container.prototype.top = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.top); + + var optsf = { + path: '/containers/' + this.id + '/top?', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Containers changes + * @param {Object} Options + * @param {Function} callback Callback + */ +Container.prototype.changes = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/changes', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Checkpoints list + * @param {Object} opts List checkpoints options (optional) + * @param {Function} callback Callback + */ +Container.prototype.listCheckpoint = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/checkpoints?', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Delete checkpoint + * @param {Object} opts Delete checkpoint options (optional) + * @param {Function} callback Callback + */ +Container.prototype.deleteCheckpoint = function(checkpoint, opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Create checkpoint + * @param {Object} opts Create checkpoint options (optional) + * @param {Function} callback Callback + */ +Container.prototype.createCheckpoint = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/checkpoints', + method: 'POST', + abortSignal: args.opts.abortSignal, + allowEmpty: true, + statusCodes: { + 200: true, //unofficial, but proxies may return it + 201: true, + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Export + * @param {Object} opts Options (optional) + * @param {Function} callback Callback with the octet-stream. + */ +Container.prototype.export = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/export', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Start + * @param {Object} opts Container start options (optional) + * @param {Function} callback Callback + */ +Container.prototype.start = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.start); + + var optsf = { + path: '/containers/' + this.id + '/start?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 304: 'container already started', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Pause + * @param {Object} opts Pause options (optional) + * @param {Function} callback Callback + */ +Container.prototype.pause = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.pause); + + var optsf = { + path: '/containers/' + this.id + '/pause', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Unpause + * @param {Object} opts Unpause options (optional) + * @param {Function} callback Callback + */ +Container.prototype.unpause = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.unpause); + + var optsf = { + path: '/containers/' + this.id + '/unpause', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Setup an exec call to a running container + * + * @param {object} opts + * @param {function} callback + */ +Container.prototype.exec = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.exec); + + var optsf = { + path: '/containers/' + this.id + '/exec', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 404: 'no such container', + 409: 'container stopped/paused', + 500: 'server error' + }, + options: args.opts + }; + + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(new Exec(self.modem, data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, new Exec(self.modem, data.Id)); + }); + } +}; + +/** + * Commit + * @param {Object} opts Commit options like 'Hostname' (optional) + * @param {Function} callback Callback + */ +Container.prototype.commit = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.commit); + + args.opts.container = this.id; + + var optsf = { + path: '/commit?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Stop + * @param {Object} opts Container stop options, like 't' (optional) + * @param {Function} callback Callback + */ +Container.prototype.stop = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.stop); + + var optsf = { + path: '/containers/' + this.id + '/stop?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 304: 'container already stopped', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Restart + * @param {Object} opts Container restart options, like 't' (optional) + * @param {Function} callback Callback + */ +Container.prototype.restart = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.restart); + + var optsf = { + path: '/containers/' + this.id + '/restart?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Kill + * @param {Object} opts Container kill options, like 'signal' (optional) + * @param {Function} callback Callback + */ +Container.prototype.kill = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.kill); + + var optsf = { + path: '/containers/' + this.id + '/kill?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Container resize + * @param {[type]} opts Resize options. (optional) + * @param {Function} callback Callback + */ +Container.prototype.resize = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.resize); + + var optsf = { + path: '/containers/' + this.id + '/resize?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Attach + * @param {Object} opts Attach options, like 'logs' (optional) + * @param {Function} callback Callback with stream. + */ +Container.prototype.attach = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.attach); + + var optsf = { + path: '/containers/' + this.id + '/attach?', + method: 'POST', + abortSignal: args.opts.abortSignal, + isStream: true, + hijack: args.opts.hijack, + openStdin: args.opts.stdin, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, stream) { + if (err) { + return reject(err); + } + resolve(stream); + }); + }); + } else { + this.modem.dial(optsf, function(err, stream) { + args.callback(err, stream); + }); + } +}; + +/** + * Waits for a container to end. + * @param {[type]} opts Container wait options, like condition. (optional) + * @param {Function} callback Callback + */ +Container.prototype.wait = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.wait); + + var optsf = { + path: '/containers/' + this.id + '/wait?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Removes a container + * @param {Object} opts Remove options, like 'force' (optional) + * @param {Function} callback Callback + */ +Container.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.remove); + + var optsf = { + path: '/containers/' + this.id + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 400: 'bad parameter', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Copy (WARNING: DEPRECATED since RAPI v1.20) + * @param {Object} opts Copy options, like 'Resource' (optional) + * @param {Function} callback Callback with stream. + */ +Container.prototype.copy = function(opts, callback) { + var self = this; + console.log('container.copy is deprecated since Docker v1.8.x'); + var args = util.processArgs(opts, callback, this.defaultOptions.copy); + + var optsf = { + path: '/containers/' + this.id + '/copy', + method: 'POST', + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * getArchive + * @param {Object} opts Archive options, like 'path' + * @param {Function} callback Callback with stream. + */ +Container.prototype.getArchive = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.getArchive); + + var optsf = { + path: '/containers/' + this.id + '/archive?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: 'client error, bad parameters', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * infoArchive + * @param {Object} opts Archive options, like 'path' + * @param {Function} callback Callback with stream. + */ +Container.prototype.infoArchive = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive); + + var optsf = { + path: '/containers/' + this.id + '/archive?', + method: 'HEAD', + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: 'client error, bad parameters', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * putArchive + * @param {Object} opts Archive options, like 'path' + * @param {Function} callback Callback with stream. + */ +Container.prototype.putArchive = function(file, opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.putArchive); + + var optsf = { + path: '/containers/' + this.id + '/archive?', + method: 'PUT', + file: file, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'client error, bad parameters', + 403: 'client error, permission denied', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Container logs + * @param {Object} opts Logs options. (optional) + * @param {Function} callback Callback with data + */ +Container.prototype.logs = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.log); + + var optsf = { + path: '/containers/' + this.id + '/logs?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Container stats + * @param {Object} opts Stats options. (optional) + * @param {Function} callback Callback with data + */ +Container.prototype.stats = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.stats); + var isStream = true; + if (args.opts.stream === false) { + isStream = false; + } + var optsf = { + path: '/containers/' + this.id + '/stats?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: isStream, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +module.exports = Container; + + +/***/ }), + +/***/ 4571: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var EventEmitter = (__nccwpck_require__(2361).EventEmitter), + Modem = __nccwpck_require__(6042), + Container = __nccwpck_require__(5815), + Image = __nccwpck_require__(6689), + Volume = __nccwpck_require__(4877), + Network = __nccwpck_require__(9780), + Service = __nccwpck_require__(8866), + Plugin = __nccwpck_require__(6606), + Secret = __nccwpck_require__(9934), + Config = __nccwpck_require__(5004), + Task = __nccwpck_require__(1385), + Node = __nccwpck_require__(2297), + Exec = __nccwpck_require__(3149), + util = __nccwpck_require__(1604), + extend = util.extend; + +var Docker = function(opts) { + if (!(this instanceof Docker)) return new Docker(opts); + + var plibrary = global.Promise; + + if (opts && opts.Promise) { + plibrary = opts.Promise; + + if (Object.keys(opts).length === 1) { + opts = undefined; + } + } + + if (opts && opts.modem) { + this.modem = opts.modem; + } else { + this.modem = new Modem(opts); + } + this.modem.Promise = plibrary; +}; + +/** + * Creates a new container + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createContainer = function(opts, callback) { + var self = this; + var optsf = { + path: '/containers/create?', + method: 'POST', + options: opts, + authconfig: opts.authconfig, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 400: 'bad parameter', + 404: 'no such container', + 406: 'impossible to attach', + 500: 'server error' + } + }; + + delete opts.authconfig; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getContainer(data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return callback(err, data); + callback(err, self.getContainer(data.Id)); + }); + } +}; + +/** + * Creates a new image + * @param {Object} auth Authentication (optional) + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createImage = function(auth, opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + opts = auth; + auth = opts.authconfig || undefined; + } else if (!callback && !opts) { + opts = auth; + auth = opts.authconfig; + } + + var optsf = { + path: '/images/create?', + method: 'POST', + options: opts, + authconfig: auth, + abortSignal: opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Load image + * @param {String} file File + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.loadImage = function(file, opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + opts = null; + } + + var optsf = { + path: '/images/load?', + method: 'POST', + options: opts, + file: file, + abortSignal: opts && opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Import image from a tar archive + * @param {String} file File + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.importImage = function(file, opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + opts = undefined; + } + + if (!opts) + opts = {}; + + opts.fromSrc = '-'; + + var optsf = { + path: '/images/create?', + method: 'POST', + options: opts, + file: file, + abortSignal: opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Verifies auth + * @param {Object} opts Options + * @param {Function} callback Callback + */ +Docker.prototype.checkAuth = function(opts, callback) { + var self = this; + var optsf = { + path: '/auth', + method: 'POST', + options: opts, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Builds an image + * @param {String} file File + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.buildImage = function(file, opts, callback) { + var self = this; + + if (!callback && typeof opts === 'function') { + callback = opts; + opts = null; + } + + var optsf = { + path: '/build?', + method: 'POST', + file: undefined, + options: opts, + abortSignal: opts && opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (opts) { + if (opts.registryconfig) { + optsf.registryconfig = optsf.options.registryconfig; + delete optsf.options.registryconfig; + } + + //undocumented? + if (opts.authconfig) { + optsf.authconfig = optsf.options.authconfig; + delete optsf.options.authconfig; + } + } + + if (callback === undefined) { + return new self.modem.Promise(function(resolve, reject) { + util.prepareBuildContext(file, (ctx) => { + optsf.file = ctx; + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + }); + } else { + util.prepareBuildContext(file, (ctx) => { + optsf.file = ctx; + self.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + }) + } +}; + +/** + * Fetches a Container by ID + * @param {String} id Container's ID + */ +Docker.prototype.getContainer = function(id) { + return new Container(this.modem, id); +}; + +/** + * Fetches an Image by name + * @param {String} name Image's name + */ +Docker.prototype.getImage = function(name) { + return new Image(this.modem, name); +}; + +/** + * Fetches a Volume by name + * @param {String} name Volume's name + */ +Docker.prototype.getVolume = function(name) { + return new Volume(this.modem, name); +}; + +/** + * Fetches a Plugin by name + * @param {String} name Volume's name + */ +Docker.prototype.getPlugin = function(name, remote) { + return new Plugin(this.modem, name, remote); +}; + +/** + * Fetches a Service by id + * @param {String} id Services's id + */ +Docker.prototype.getService = function(id) { + return new Service(this.modem, id); +}; + +/** + * Fetches a Task by id + * @param {String} id Task's id + */ +Docker.prototype.getTask = function(id) { + return new Task(this.modem, id); +}; + +/** + * Fetches Node by id + * @param {String} id Node's id + */ +Docker.prototype.getNode = function(id) { + return new Node(this.modem, id); +}; + +/** + * Fetches a Network by id + * @param {String} id network's id + */ +Docker.prototype.getNetwork = function(id) { + return new Network(this.modem, id); +}; + +/** + * Fetches a Secret by id + * @param {String} id network's id + */ +Docker.prototype.getSecret = function(id) { + return new Secret(this.modem, id); +}; + +/** + * Fetches a Config by id + * @param {String} id network's id + */ +Docker.prototype.getConfig = function(id) { + return new Config(this.modem, id); +}; + +/** + * Fetches an Exec instance by ID + * @param {String} id Exec instance's ID + */ +Docker.prototype.getExec = function(id) { + return new Exec(this.modem, id); +}; + +/** + * Lists containers + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.listContainers = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/json?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists images + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.listImages = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/images/json?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Get images + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.getImages = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/images/get?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists Services + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listServices = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/services?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists Nodes + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listNodes = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/nodes?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 404: 'no such node', + 500: 'server error', + 503: 'node is not part of a swarm', + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists Tasks + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listTasks = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/tasks?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Creates a new secret + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createSecret = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self = this; + var optsf = { + path: '/secrets/create?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 406: 'server error or node is not part of a swarm', + 409: 'name conflicts with an existing object', + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getSecret(data.ID)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getSecret(data.ID)); + }); + } +}; + + +/** + * Creates a new config + * @param {Object} opts Config options + * @param {Function} callback Callback + */ +Docker.prototype.createConfig = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self = this; + var optsf = { + path: '/configs/create?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 406: 'server error or node is not part of a swarm', + 409: 'name conflicts with an existing object', + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getConfig(data.ID)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getConfig(data.ID)); + }); + } +}; + + +/** + * Lists secrets + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listSecrets = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/secrets?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists configs + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listConfigs = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/configs?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Creates a new plugin + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createPlugin = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: '/plugins/create?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getPlugin(args.opts.name)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getPlugin(args.opts.name)); + }); + } +}; + + +/** + * Lists plugins + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listPlugins = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune images + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneImages = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/images/prune?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune builder + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneBuilder = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/build/prune', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune containers + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneContainers = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/prune?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune volumes + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneVolumes = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/volumes/prune?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune networks + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneNetworks = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks/prune?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Creates a new volume + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createVolume = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: '/volumes/create?', + method: 'POST', + allowEmpty: true, + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getVolume(data.Name)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getVolume(data.Name)); + }); + } +}; + +/** + * Creates a new service + * @param {Object} auth + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createService = function(auth, opts, callback) { + if (!callback && typeof opts === 'function') { + callback = opts; + opts = auth; + auth = opts.authconfig || undefined; + } else if (!opts && !callback) { + opts = auth; + } + + + var self = this; + var optsf = { + path: '/services/create', + method: 'POST', + options: opts, + authconfig: auth, + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 500: 'server error' + } + }; + + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getService(data.ID || data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return callback(err, data); + callback(err, self.getService(data.ID || data.Id)); + }); + } +}; + +/** + * Lists volumes + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.listVolumes = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/volumes?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Creates a new network + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createNetwork = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: '/networks/create?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 404: 'driver not found', + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getNetwork(data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getNetwork(data.Id)); + }); + } +}; + +/** + * Lists networks + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.listNetworks = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Search images + * @param {Object} opts Options + * @param {Function} callback Callback + */ +Docker.prototype.searchImages = function(opts, callback) { + var self = this; + var optsf = { + path: '/images/search?', + method: 'GET', + options: opts, + authconfig: opts.authconfig, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Info + * @param {Object} opts Options (optional) + * @param {Function} callback Callback with info + */ +Docker.prototype.info = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var opts = { + path: '/info', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Version + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.version = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var opts = { + path: '/version', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Ping + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.ping = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/_ping', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * SystemDf equivalent to system/df API Engine + * get usage data information + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.df = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/system/df', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Events + * @param {Object} opts Events options, like 'since' (optional) + * @param {Function} callback Callback + */ +Docker.prototype.getEvents = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/events?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Pull is a wrapper around createImage, parsing image's tags. + * @param {String} repoTag Repository tag + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + * @param {Object} auth Authentication (optional) + * @return {Object} Image + */ +Docker.prototype.pull = function(repoTag, opts, callback, auth) { + var args = util.processArgs(opts, callback); + + var imageSrc = util.parseRepositoryTag(repoTag); + args.opts.fromImage = imageSrc.repository; + args.opts.tag = imageSrc.tag || 'latest'; + + var argsf = [args.opts, args.callback]; + if (auth) { + argsf = [auth, args.opts, args.callback]; + } + return this.createImage.apply(this, argsf); +}; + +/** + * Like run command from Docker's CLI + * @param {String} image Image name to be used. + * @param {Array} cmd Command to run in array format. + * @param {Object} streamo Output stream + * @param {Object} createOptions Container create options (optional) + * @param {Object} startOptions Container start options (optional) + * @param {Function} callback Callback + * @return {Object} EventEmitter + */ +Docker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) { + if (typeof arguments[arguments.length - 1] === 'function') { + return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback); + } else { + return this.runPromise(image, cmd, streamo, createOptions, startOptions); + } +}; + + +Docker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) { + if (!callback && typeof createOptions === 'function') { + callback = createOptions; + createOptions = {}; + startOptions = {}; + } else if (!callback && typeof startOptions === 'function') { + callback = startOptions; + startOptions = {}; + } + + var hub = new EventEmitter(); + + function handler(err, container) { + if (err) return callback(err, null, container); + + hub.emit('container', container); + + container.attach({ + stream: true, + stdout: true, + stderr: true + }, function handler(err, stream) { + if (err) return callback(err, null, container); + + hub.emit('stream', stream); + + if (streamo) { + if (streamo instanceof Array) { + stream.on('end', function() { + try { + streamo[0].end(); + } catch (e) {} + try { + streamo[1].end(); + } catch (e) {} + }); + container.modem.demuxStream(stream, streamo[0], streamo[1]); + } else { + stream.setEncoding('utf8'); + stream.pipe(streamo, { + end: true + }); + } + } + + container.start(startOptions, function(err, data) { + if (err) return callback(err, data, container); + hub.emit('start', container); + + container.wait(function(err, data) { + hub.emit('data', data); + callback(err, data, container); + }); + }); + }); + } + + var optsc = { + 'Hostname': '', + 'User': '', + 'AttachStdin': false, + 'AttachStdout': true, + 'AttachStderr': true, + 'Tty': true, + 'OpenStdin': false, + 'StdinOnce': false, + 'Env': null, + 'Cmd': cmd, + 'Image': image, + 'Volumes': {}, + 'VolumesFrom': [] + }; + + extend(optsc, createOptions); + + this.createContainer(optsc, handler); + + return hub; +}; + +Docker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) { + var self = this; + + createOptions = createOptions || {}; + startOptions = startOptions || {}; + + var optsc = { + 'Hostname': '', + 'User': '', + 'AttachStdin': false, + 'AttachStdout': true, + 'AttachStderr': true, + 'Tty': true, + 'OpenStdin': false, + 'StdinOnce': false, + 'Env': null, + 'Cmd': cmd, + 'Image': image, + 'Volumes': {}, + 'VolumesFrom': [] + }; + + extend(optsc, createOptions); + + var containero; + + return new this.modem.Promise(function(resolve, reject) { + self.createContainer(optsc).then(function(container) { + containero = container; + return container.attach({ + stream: true, + stdout: true, + stderr: true + }); + }).then(function(stream) { + if (streamo) { + if (streamo instanceof Array) { + stream.on('end', function() { + try { + streamo[0].end(); + } catch (e) {} + try { + streamo[1].end(); + } catch (e) {} + }); + containero.modem.demuxStream(stream, streamo[0], streamo[1]); + } else { + stream.setEncoding('utf8'); + stream.pipe(streamo, { + end: true + }); + } + } + return containero.start(startOptions); + }).then(function(data) { + return containero.wait(); + }).then(function(data) { + resolve([data, containero]); + }).catch(function(err) { + reject(err); + }); + }); +}; + +/** + * Init swarm. + * + * @param {object} opts + * @param {function} callback + */ +Docker.prototype.swarmInit = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm/init', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 406: 'node is already part of a Swarm' + }, + options: args.opts + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Join swarm. + * + * @param {object} opts + * @param {function} callback + */ +Docker.prototype.swarmJoin = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm/join', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 406: 'node is already part of a Swarm' + }, + options: args.opts + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Leave swarm. + * + * @param {object} opts + * @param {function} callback + */ +Docker.prototype.swarmLeave = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm/leave?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 406: 'node is not part of a Swarm' + }, + options: args.opts + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update swarm. + * + * @param {object} opts + * @param {function} callback + */ +Docker.prototype.swarmUpdate = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm/update?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 406: 'node is already part of a Swarm' + }, + options: args.opts + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Inspect a Swarm. + * Warning: This method is not documented in the API + * + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.swarmInspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 406: 'This node is not a swarm manager', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +Docker.Container = Container; +Docker.Image = Image; +Docker.Volume = Volume; +Docker.Network = Network; +Docker.Service = Service; +Docker.Plugin = Plugin; +Docker.Secret = Secret; +Docker.Task = Task; +Docker.Node = Node; +Docker.Exec = Exec; + +module.exports = Docker; + + +/***/ }), + +/***/ 3149: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an Exec + * @param {Object} modem docker-modem + * @param {String} id Exec's ID + */ +var Exec = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Exec.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Start the exec call that was setup. + * + * @param {object} opts + * @param {function} callback + */ +Exec.prototype.start = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/exec/' + this.id + '/start', + method: 'POST', + abortSignal: args.opts.abortSignal, + isStream: true, + allowEmpty: true, + hijack: args.opts.hijack, + openStdin: args.opts.stdin, + statusCodes: { + 200: true, + 204: true, + 404: 'no such exec', + 409: 'container stopped/paused', + 500: 'container not running' + }, + options: args.opts + }; + + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + +/** + * Resize the exec call that was setup. + * + * @param {object} opts + * @param {function} callback + */ +Exec.prototype.resize = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/exec/' + this.id + '/resize?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such exec', + 500: 'container not running' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + +/** + * Get low-level information about the exec call. + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Exec.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/exec/' + this.id + '/json', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such exec', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + + +module.exports = Exec; + + +/***/ }), + +/***/ 6689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an image + * @param {Object} modem docker-modem + * @param {String} name Image's name + */ +var Image = function(modem, name) { + this.modem = modem; + this.name = name; +}; + +Image.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Image.prototype.inspect = function(callback) { + var self = this; + + var opts = { + path: '/images/' + this.name + '/json', + method: 'GET', + statusCodes: { + 200: true, + 404: 'no such image', + 500: 'server error' + } + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return callback(err, data); + callback(err, data); + }); + } +}; + +/** + * Distribution + * @param {Object} opts + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Image.prototype.distribution = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self = this; + + var fopts = { + path: '/distribution/' + this.name + '/json', + method: 'GET', + statusCodes: { + 200: true, + 401: 'no such image', + 500: 'server error' + }, + authconfig: (args.opts) ? args.opts.authconfig : undefined + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(fopts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(fopts, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + +/** + * History + * @param {Function} callback Callback + */ +Image.prototype.history = function(callback) { + var self = this; + var opts = { + path: '/images/' + this.name + '/history', + method: 'GET', + statusCodes: { + 200: true, + 404: 'no such image', + 500: 'server error' + } + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return callback(err, data); + callback(err, data); + }); + } +}; + +/** + * Get + * @param {Function} callback Callback with data stream. + */ +Image.prototype.get = function(callback) { + var self = this; + var opts = { + path: '/images/' + this.name + '/get', + method: 'GET', + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return callback(err, data); + callback(err, data); + }); + } +}; + +/** + * Push + * @param {Object} opts Push options, like 'registry' (optional) + * @param {Function} callback Callback with stream. + * @param {Object} auth Registry authentication + */ +Image.prototype.push = function(opts, callback, auth) { + var self = this; + var args = util.processArgs(opts, callback); + var isStream = true; + if (args.opts.stream === false) { + isStream = false; + } + var optsf = { + path: '/images/' + this.name + '/push?', + method: 'POST', + options: args.opts, + authconfig: args.opts.authconfig || auth, + abortSignal: args.opts.abortSignal, + isStream: isStream, + statusCodes: { + 200: true, + 404: 'no such image', + 500: 'server error' + } + }; + + delete optsf.options.authconfig; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Tag + * @param {Object} opts Tag options, like 'repo' (optional) + * @param {Function} callback Callback + */ +Image.prototype.tag = function(opts, callback) { + var self = this; + var optsf = { + path: '/images/' + this.name + '/tag?', + method: 'POST', + options: opts, + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 400: 'bad parameter', + 404: 'no such image', + 409: 'conflict', + 500: 'server error' + } + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Removes the image + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Image.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/images/' + this.name + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such image', + 409: 'conflict', + 500: 'server error' + }, + options: args.opts + }; + + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +module.exports = Image; + + +/***/ }), + +/***/ 9780: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an network + * @param {Object} modem docker-modem + * @param {String} id Network's id + */ +var Network = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Network.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Id only if callback isn't specified. + */ +Network.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var opts = { + path: '/networks/' + this.id + '?', + method: 'GET', + statusCodes: { + 200: true, + 404: 'no such network', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Removes the network + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Network.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks/' + this.id, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'no such network', + 409: 'conflict', + 500: 'server error' + }, + options: args.opts + }; + + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Connects a container to a network + * @param {[Object]} opts Connect options (optional) + * @param {Function} callback Callback + */ +Network.prototype.connect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks/' + this.id + '/connect', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 404: 'network or container is not found', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Disconnects a container from a network + * @param {[Object]} opts Disconnect options (optional) + * @param {Function} callback Callback + */ +Network.prototype.disconnect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks/' + this.id + '/disconnect', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 404: 'network or container is not found', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + + + +module.exports = Network; + + +/***/ }), + +/***/ 2297: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an Node + * @param {Object} modem docker-modem + * @param {String} id Node's ID + */ +var Node = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Node.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Query Docker for Node details. + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Node.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/nodes/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such node', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Update a node. + * + * @param {object} opts + * @param {function} callback + */ +Node.prototype.update = function(opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + } + + var optsf = { + path: '/nodes/' + this.id + '/update?', + method: 'POST', + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such node', + 406: 'node is not part of a swarm', + 500: 'server error' + }, + options: opts + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + + +/** + * Remove a Node. + * Warning: This method is not documented in the API. + * + * @param {object} opts + * @param {function} callback + */ +Node.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/nodes/' + this.id + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such node', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +module.exports = Node; + + +/***/ }), + +/***/ 6606: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents a plugin + * @param {Object} modem docker-modem + * @param {String} name Plugin's name + */ +var Plugin = function(modem, name, remote) { + this.modem = modem; + this.name = name; + this.remote = remote || name; +}; + +Plugin.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Plugin.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'plugin is not installed', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Removes the plugin + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'plugin is not installed', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + +/** + * get privileges + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + * @return {Object} Name only if callback isn't specified. + */ +Plugin.prototype.privileges = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/privileges?', + method: 'GET', + options: { + 'remote': this.remote + }, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Installs a new plugin + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Plugin.prototype.pull = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + if(args.opts._query && !args.opts._query.name) { + args.opts._query.name = this.name; + } + if(args.opts._query && !args.opts._query.remote) { + args.opts._query.remote = this.remote; + } + + var optsf = { + path: '/plugins/pull?', + method: 'POST', + abortSignal: args.opts.abortSignal, + isStream: true, + options: args.opts, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Enable + * @param {Object} opts Plugin enable options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.enable = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '/enable?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Disable + * @param {Object} opts Plugin disable options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.disable = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '/disable', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Push + * @param {Object} opts Plugin push options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.push = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '/push', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'plugin not installed', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * COnfigure + * @param {Object} opts Plugin configure options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.configure = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '/set', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'plugin not installed', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Upgrade plugin + * + * @param {object} auth + * @param {object} opts + * @param {function} callback + */ +Plugin.prototype.upgrade = function(auth, opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + opts = auth; + auth = opts.authconfig || undefined; + } + + var optsf = { + path: '/plugins/' + this.name + '/upgrade?', + method: 'POST', + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'plugin not installed', + 500: 'server error' + }, + authconfig: auth, + options: opts + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + + +module.exports = Plugin; + + +/***/ }), + +/***/ 9934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents a secret + * @param {Object} modem docker-modem + * @param {String} id Secret's id + */ +var Secret = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Secret.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Secret.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/secrets/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'secret not found', + 406: 'node is not part of a swarm', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update a secret. + * + * @param {object} opts + * @param {function} callback + */ +Secret.prototype.update = function(opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + } + + var optsf = { + path: '/secrets/' + this.id + '/update?', + method: 'POST', + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: 'secret not found', + 500: 'server error' + }, + options: opts + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + + +/** + * Removes the secret + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Secret.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/secrets/' + this.id, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'secret not found', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + + +module.exports = Secret; + + +/***/ }), + +/***/ 8866: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an Service + * @param {Object} modem docker-modem + * @param {String} id Service's ID + */ +var Service = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Service.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Query Docker for service details. + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Service.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/services/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such service', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Delete Service + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Service.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/services/' + this.id, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'no such service', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update service + * + * @param {object} auth + * @param {object} opts + * @param {function} callback + */ +Service.prototype.update = function(auth, opts, callback) { + var self = this; + if (!callback) { + var t = typeof opts; + if(t === 'function'){ + callback = opts; + opts = auth; + auth = opts.authconfig || undefined; + } else if (t === 'undefined'){ + opts = auth; + auth = opts.authconfig || undefined; + } + } + + var optsf = { + path: '/services/' + this.id + '/update?', + method: 'POST', + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such service', + 500: 'server error' + }, + authconfig: auth, + options: opts + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + + + +/** + * Service logs + * @param {Object} opts Logs options. (optional) + * @param {Function} callback Callback with data + */ +Service.prototype.logs = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, {}); + + var optsf = { + path: '/services/' + this.id + '/logs?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 200: true, + 404: 'no such service', + 500: 'server error', + 503: 'node is not part of a swarm' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + + +module.exports = Service; + + +/***/ }), + +/***/ 1385: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an Task + * @param {Object} modem docker-modem + * @param {String} id Task's ID + */ +var Task = function(modem, id) { + this.modem = modem; + this.id = id; + + this.defaultOptions = { + log: {} + }; +}; + +Task.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Query Docker for Task details. + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Task.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/tasks/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'unknown task', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Task logs + * @param {Object} opts Logs options. (optional) + * @param {Function} callback Callback with data + */ +Task.prototype.logs = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.log); + + var optsf = { + path: '/tasks/' + this.id + '/logs?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 101: true, + 200: true, + 404: 'no such container', + 500: 'server error', + 503: 'node is not part of a swarm' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +module.exports = Task; + + +/***/ }), + +/***/ 1604: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var DockerIgnore = __nccwpck_require__(3358); +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); +var tar = __nccwpck_require__(366); +var zlib = __nccwpck_require__(9796); + +// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js + +var arr = []; +var each = arr.forEach; +var slice = arr.slice; + +module.exports.extend = function(obj) { + each.call(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }); + return obj; +}; + +module.exports.processArgs = function(opts, callback, defaultOpts) { + if (!callback && typeof opts === 'function') { + callback = opts; + opts = null; + } + return { + callback: callback, + opts: module.exports.extend({}, defaultOpts, opts) + }; +}; + + +/** + * Parse the given repo tag name (as a string) and break it out into repo/tag pair. + * // if given the input http://localhost:8080/woot:latest + * { + * repository: 'http://localhost:8080/woot', + * tag: 'latest' + * } + * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest' + * @return {Object} input parsed into the repo and tag. + */ +module.exports.parseRepositoryTag = function(input) { + var separatorPos; + var digestPos = input.indexOf('@'); + var colonPos = input.lastIndexOf(':'); + // @ symbol is more important + if (digestPos >= 0) { + separatorPos = digestPos; + } else if (colonPos >= 0) { + separatorPos = colonPos; + } else { + // no colon nor @ + return { + repository: input + }; + } + + // last colon is either the tag (or part of a port designation) + var tag = input.slice(separatorPos + 1); + + // if it contains a / its not a tag and is part of the url + if (tag.indexOf('/') === -1) { + return { + repository: input.slice(0, separatorPos), + tag: tag + }; + } + + return { + repository: input + }; +}; + + +module.exports.prepareBuildContext = function(file, next) { + if (file && file.context) { + fs.readFile(path.join(file.context, '.dockerignore'), (err, data) => { + let ignoreFn; + let filterFn; + + if (!err) { + const dockerIgnore = DockerIgnore({ ignorecase: false }).add(data.toString()); + + filterFn = dockerIgnore.createFilter(); + ignoreFn = (path) => { + return !filterFn(path); + } + } + + const entries = file.src.slice() || [] + + const pack = tar.pack(file.context, { + entries: filterFn ? entries.filter(filterFn) : entries, + ignore: ignoreFn // Only works on directories + }); + + next(pack.pipe(zlib.createGzip())); + }) + } else { + next(file); + } +} + + +/***/ }), + +/***/ 4877: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents a volume + * @param {Object} modem docker-modem + * @param {String} name Volume's name + */ +var Volume = function(modem, name) { + this.modem = modem; + this.name = name; +}; + +Volume.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Volume.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/volumes/' + this.name, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such volume', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Removes the volume + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Volume.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/volumes/' + this.name, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 204: true, + 404: 'no such volume', + 409: 'conflict', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +module.exports = Volume; + + +/***/ }), + +/***/ 1205: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var once = __nccwpck_require__(1223); + +var noop = function() {}; + +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; + +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; + +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + + callback = once(callback || noop); + + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var cancelled = false; + + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; + + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; + + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; + + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; + + var onerror = function(err) { + callback.call(stream, err); + }; + + var onclose = function() { + process.nextTick(onclosenexttick); + }; + + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + }; + + var onrequest = function() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + cancelled = true; + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +}; + +module.exports = eos; + + +/***/ }), + +/***/ 3186: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = (__nccwpck_require__(7147).constants) || __nccwpck_require__(2057) + + +/***/ }), + +/***/ 1621: +/***/ ((module) => { + +"use strict"; + + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; + + +/***/ }), + +/***/ 4124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +try { + var util = __nccwpck_require__(3837); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(8544); +} + + +/***/ }), + +/***/ 8544: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 7614: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var path = __nccwpck_require__(1017); +var fs = __nccwpck_require__(7147); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; + + +/***/ }), + +/***/ 900: +/***/ ((module) => { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + + +/***/ }), + +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var wrappy = __nccwpck_require__(2940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} + + +/***/ }), + +/***/ 8341: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var once = __nccwpck_require__(1223) +var eos = __nccwpck_require__(1205) +var fs = __nccwpck_require__(7147) // 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 + + +/***/ }), + +/***/ 7214: +/***/ ((module) => { + +"use strict"; + + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.q = codes; + + +/***/ }), + +/***/ 1359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; +}; +/**/ + + +module.exports = Duplex; + +var Readable = __nccwpck_require__(1433); + +var Writable = __nccwpck_require__(6993); + +__nccwpck_require__(4124)(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer + +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + process.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +/***/ }), + +/***/ 1542: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + +module.exports = PassThrough; + +var Transform = __nccwpck_require__(4415); + +__nccwpck_require__(4124)(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 1433: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + + +module.exports = Readable; +/**/ + +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; +/**/ + +var EE = (__nccwpck_require__(2361).EventEmitter); + +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ + + +var Stream = __nccwpck_require__(2387); +/**/ + + +var Buffer = (__nccwpck_require__(4300).Buffer); + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + + +var debugUtil = __nccwpck_require__(3837); + +var debug; + +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + + +var BufferList = __nccwpck_require__(6522); + +var destroyImpl = __nccwpck_require__(7049); + +var _require = __nccwpck_require__(9948), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; + +__nccwpck_require__(4124)(Readable, Stream); + +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(1359); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __nccwpck_require__(1359); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; + +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. + + +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() + + +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. + + +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB + + +var MAX_HWM = 0x40000000; + +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. + + +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; +} // you can override either this method, or the async _read(n) below. + + +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; +}; + +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} // Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. + + +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} + +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. + + +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. + + +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; // set up data events if they are asked for +// Ensure readable listeners eventually get something + + +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + + return res; +}; + +Readable.prototype.addListener = Readable.prototype.on; + +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. + + +Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. + + +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __nccwpck_require__(3306); + } + + return createReadableStreamAsyncIterator(this); + }; +} + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); // exposed for testing purposes only. + +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. + +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} + +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __nccwpck_require__(9082); + } + + return from(Readable, iterable, opts); + }; +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; +} + +/***/ }), + +/***/ 4415: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + +module.exports = Transform; + +var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + +var Duplex = __nccwpck_require__(1359); + +__nccwpck_require__(4124)(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. + + +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. + + +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} + +/***/ }), + +/***/ 6993: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + +module.exports = Writable; +/* */ + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream + + +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ + + +var Duplex; +/**/ + +Writable.WritableState = WritableState; +/**/ + +var internalUtil = { + deprecate: __nccwpck_require__(7127) +}; +/**/ + +/**/ + +var Stream = __nccwpck_require__(2387); +/**/ + + +var Buffer = (__nccwpck_require__(4300).Buffer); + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +var destroyImpl = __nccwpck_require__(7049); + +var _require = __nccwpck_require__(9948), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + +var errorOrDestroy = destroyImpl.errorOrDestroy; + +__nccwpck_require__(4124)(Writable, Stream); + +function nop() {} + +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(1359); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. + + +var realHasInstance; + +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __nccwpck_require__(1359); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. + + +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; + +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. + + +function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + + return true; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; + +Writable.prototype.cork = function () { + this._writableState.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. + +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. + + +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it + + +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} + +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; + +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; + +/***/ }), + +/***/ 3306: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var _Object$setPrototypeO; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var finished = __nccwpck_require__(6080); + +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); + +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} + +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} + +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} + +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} + +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); + +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; + +module.exports = createReadableStreamAsyncIterator; + +/***/ }), + +/***/ 6522: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = __nccwpck_require__(4300), + Buffer = _require.Buffer; + +var _require2 = __nccwpck_require__(3837), + inspect = _require2.inspect; + +var custom = inspect && inspect.custom || 'inspect'; + +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} + +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; +}(); + +/***/ }), + +/***/ 7049: +/***/ ((module) => { + +"use strict"; + // undocumented cb() API, needed for core, not for public API + +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + + return this; +} + +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} + +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; + +/***/ }), + +/***/ 6080: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + + +var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(7214)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; +} + +function noop() {} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} + +module.exports = eos; + +/***/ }), + +/***/ 9082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(7214)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE); + +function from(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; +} + +module.exports = from; + +/***/ }), + +/***/ 6989: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + + +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} + +var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __nccwpck_require__(6080); + 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; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + 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 = pipeline; + +/***/ }), + +/***/ 9948: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(7214)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); + +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; +} + +module.exports = { + getHighWaterMark: getHighWaterMark +}; + +/***/ }), + +/***/ 2387: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(2781); + + +/***/ }), + +/***/ 1642: +/***/ ((module, exports, __nccwpck_require__) => { + +var Stream = __nccwpck_require__(2781); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = __nccwpck_require__(1433); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(6993); + exports.Duplex = __nccwpck_require__(1359); + exports.Transform = __nccwpck_require__(4415); + exports.PassThrough = __nccwpck_require__(1542); + exports.finished = __nccwpck_require__(6080); + exports.pipeline = __nccwpck_require__(6989); +} + + +/***/ }), + +/***/ 5118: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* eslint-disable node/no-deprecated-api */ + + + +var buffer = __nccwpck_require__(4300) +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 + + +/***/ }), + +/***/ 9798: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var fs = __nccwpck_require__(7147); + +module.exports = function (filepath, split, encoding) { + split = typeof split !== 'undefined' ? split : "\n"; + encoding = typeof encoding !== 'undefined' ? encoding : "utf8"; + + var ca = []; + var chain = fs.readFileSync(filepath, encoding); + if(chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0){ + throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); + } + chain = chain.split(split); + var cert = []; + var _i, _len; + for (_i = 0, _len = chain.length; _i < _len; _i++) { + var line = chain[_i]; + if (!(line.length !== 0)) { + continue; + } + cert.push(line); + if (line.match(/-END CERTIFICATE-/)) { + ca.push(cert.join(split)); + cert = []; + } + } + return ca; +} + + +/***/ }), + +/***/ 3204: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + Duplex: DuplexStream, + Readable: ReadableStream, + Writable: WritableStream, +} = __nccwpck_require__(2781); + +const { + CHANNEL_EXTENDED_DATATYPE: { STDERR }, +} = __nccwpck_require__(6832); +const { bufferSlice } = __nccwpck_require__(9475); + +const PACKET_SIZE = 32 * 1024; +const MAX_WINDOW = 2 * 1024 * 1024; +const WINDOW_THRESHOLD = MAX_WINDOW / 2; + +class ClientStderr extends ReadableStream { + constructor(channel, streamOpts) { + super(streamOpts); + + this._channel = channel; + } + _read(n) { + if (this._channel._waitChanDrain) { + this._channel._waitChanDrain = false; + if (this._channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(this._channel); + } + } +} + +class ServerStderr extends WritableStream { + constructor(channel) { + super({ highWaterMark: MAX_WINDOW }); + + this._channel = channel; + } + + _write(data, encoding, cb) { + const channel = this._channel; + const protocol = channel._client._protocol; + const outgoing = channel.outgoing; + const packetSize = outgoing.packetSize; + const id = outgoing.id; + let window = outgoing.window; + const len = data.length; + let p = 0; + + if (outgoing.state !== 'open') + return; + + while (len - p > 0 && window > 0) { + let sliceLen = len - p; + if (sliceLen > window) + sliceLen = window; + if (sliceLen > packetSize) + sliceLen = packetSize; + + if (p === 0 && sliceLen === len) + protocol.channelExtData(id, data, STDERR); + else + protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); + + p += sliceLen; + window -= sliceLen; + } + + outgoing.window = window; + + if (len - p > 0) { + if (window === 0) + channel._waitWindow = true; + if (p > 0) + channel._chunkErr = bufferSlice(data, p, len); + else + channel._chunkErr = data; + channel._chunkcbErr = cb; + return; + } + + cb(); + } +} + +class Channel extends DuplexStream { + constructor(client, info, opts) { + const streamOpts = { + highWaterMark: MAX_WINDOW, + allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), + emitClose: false, + }; + super(streamOpts); + this.allowHalfOpen = streamOpts.allowHalfOpen; + + const server = !!(opts && opts.server); + + this.server = server; + this.type = info.type; + this.subtype = undefined; + + /* + incoming and outgoing contain these properties: + { + id: undefined, + window: undefined, + packetSize: undefined, + state: 'closed' + } + */ + this.incoming = info.incoming; + this.outgoing = info.outgoing; + this._callbacks = []; + + this._client = client; + this._hasX11 = false; + this._exit = { + code: undefined, + signal: undefined, + dump: undefined, + desc: undefined, + }; + + this.stdin = this.stdout = this; + + if (server) + this.stderr = new ServerStderr(this); + else + this.stderr = new ClientStderr(this, streamOpts); + + // Outgoing data + this._waitWindow = false; // SSH-level backpressure + + // Incoming data + this._waitChanDrain = false; // Channel Readable side backpressure + + this._chunk = undefined; + this._chunkcb = undefined; + this._chunkErr = undefined; + this._chunkcbErr = undefined; + + this.on('finish', onFinish) + .on('prefinish', onFinish); // For node v0.11+ + + this.on('end', onEnd).on('close', onEnd); + } + + _read(n) { + if (this._waitChanDrain) { + this._waitChanDrain = false; + if (this.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(this); + } + } + + _write(data, encoding, cb) { + const protocol = this._client._protocol; + const outgoing = this.outgoing; + const packetSize = outgoing.packetSize; + const id = outgoing.id; + let window = outgoing.window; + const len = data.length; + let p = 0; + + if (outgoing.state !== 'open') + return; + + while (len - p > 0 && window > 0) { + let sliceLen = len - p; + if (sliceLen > window) + sliceLen = window; + if (sliceLen > packetSize) + sliceLen = packetSize; + + if (p === 0 && sliceLen === len) + protocol.channelData(id, data); + else + protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); + + p += sliceLen; + window -= sliceLen; + } + + outgoing.window = window; + + if (len - p > 0) { + if (window === 0) + this._waitWindow = true; + if (p > 0) + this._chunk = bufferSlice(data, p, len); + else + this._chunk = data; + this._chunkcb = cb; + return; + } + + cb(); + } + + eof() { + if (this.outgoing.state === 'open') { + this.outgoing.state = 'eof'; + this._client._protocol.channelEOF(this.outgoing.id); + } + } + + close() { + if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { + this.outgoing.state = 'closing'; + this._client._protocol.channelClose(this.outgoing.id); + } + } + + destroy() { + this.end(); + this.close(); + return this; + } + + // Session type-specific methods ============================================= + setWindow(rows, cols, height, width) { + if (this.server) + throw new Error('Client-only method called in server mode'); + + if (this.type === 'session' + && (this.subtype === 'shell' || this.subtype === 'exec') + && this.writable + && this.outgoing.state === 'open') { + this._client._protocol.windowChange(this.outgoing.id, + rows, + cols, + height, + width); + } + } + + signal(signalName) { + if (this.server) + throw new Error('Client-only method called in server mode'); + + if (this.type === 'session' + && this.writable + && this.outgoing.state === 'open') { + this._client._protocol.signal(this.outgoing.id, signalName); + } + } + + exit(statusOrSignal, coreDumped, msg) { + if (!this.server) + throw new Error('Server-only method called in client mode'); + + if (this.type === 'session' + && this.writable + && this.outgoing.state === 'open') { + if (typeof statusOrSignal === 'number') { + this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); + } else { + this._client._protocol.exitSignal(this.outgoing.id, + statusOrSignal, + coreDumped, + msg); + } + } + } + +} + +function onFinish() { + this.eof(); + if (this.server || !this.allowHalfOpen) + this.close(); + this.writable = false; +} + +function onEnd() { + this.readable = false; +} + +function windowAdjust(self) { + if (self.outgoing.state === 'closed') + return; + const amt = MAX_WINDOW - self.incoming.window; + if (amt <= 0) + return; + self.incoming.window += amt; + self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); +} + +module.exports = { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD, +}; + + +/***/ }), + +/***/ 6119: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { Socket } = __nccwpck_require__(1808); +const { Duplex } = __nccwpck_require__(2781); +const { resolve } = __nccwpck_require__(1017); +const { readFile } = __nccwpck_require__(7147); +const { execFile, spawn } = __nccwpck_require__(2081); + +const { isParsedKey, parseKey } = __nccwpck_require__(2218); + +const { + makeBufferParser, + readUInt32BE, + writeUInt32BE, + writeUInt32LE, +} = __nccwpck_require__(9475); + +function once(cb) { + let called = false; + return (...args) => { + if (called) + return; + called = true; + cb(...args); + }; +} + +function concat(buf1, buf2) { + const combined = Buffer.allocUnsafe(buf1.length + buf2.length); + buf1.copy(combined, 0); + buf2.copy(combined, buf1.length); + return combined; +} + +function noop() {} + +const EMPTY_BUF = Buffer.alloc(0); + +const binaryParser = makeBufferParser(); + +class BaseAgent { + getIdentities(cb) { + cb(new Error('Missing getIdentities() implementation')); + } + sign(pubKey, data, options, cb) { + if (typeof options === 'function') + cb = options; + cb(new Error('Missing sign() implementation')); + } +} + +class OpenSSHAgent extends BaseAgent { + constructor(socketPath) { + super(); + this.socketPath = socketPath; + } + + getStream(cb) { + cb = once(cb); + const sock = new Socket(); + sock.on('connect', () => { + cb(null, sock); + }); + sock.on('close', onFail) + .on('end', onFail) + .on('error', onFail); + sock.connect(this.socketPath); + + function onFail() { + try { + sock.destroy(); + } catch {} + + cb(new Error('Failed to connect to agent')); + } + } + + getIdentities(cb) { + cb = once(cb); + this.getStream((err, stream) => { + function onFail(err) { + if (stream) { + try { + stream.destroy(); + } catch {} + } + if (!err) + err = new Error('Failed to retrieve identities from agent'); + cb(err); + } + + if (err) + return onFail(err); + + const protocol = new AgentProtocol(true); + protocol.on('error', onFail); + protocol.pipe(stream).pipe(protocol); + + stream.on('close', onFail) + .on('end', onFail) + .on('error', onFail); + + protocol.getIdentities((err, keys) => { + if (err) + return onFail(err); + try { + stream.destroy(); + } catch {} + cb(null, keys); + }); + }); + } + + sign(pubKey, data, options, cb) { + if (typeof options === 'function') { + cb = options; + options = undefined; + } else if (typeof options !== 'object' || options === null) { + options = undefined; + } + + cb = once(cb); + this.getStream((err, stream) => { + function onFail(err) { + if (stream) { + try { + stream.destroy(); + } catch {} + } + if (!err) + err = new Error('Failed to sign data with agent'); + cb(err); + } + + if (err) + return onFail(err); + + const protocol = new AgentProtocol(true); + protocol.on('error', onFail); + protocol.pipe(stream).pipe(protocol); + + stream.on('close', onFail) + .on('end', onFail) + .on('error', onFail); + + protocol.sign(pubKey, data, options, (err, sig) => { + if (err) + return onFail(err); + + try { + stream.destroy(); + } catch {} + + cb(null, sig); + }); + }); + } +} + +const PageantAgent = (() => { + const RET_ERR_BADARGS = 10; + const RET_ERR_UNAVAILABLE = 11; + const RET_ERR_NOMAP = 12; + const RET_ERR_BINSTDIN = 13; + const RET_ERR_BINSTDOUT = 14; + const RET_ERR_BADLEN = 15; + + const EXEPATH = __nccwpck_require__.ab + "pagent.exe"; + const ERROR = { + [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), + [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), + [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), + [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), + [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), + [RET_ERR_BADLEN]: + new Error('pagent.exe did not get expected input payload'), + }; + + function destroy(stream) { + stream.buffer = null; + if (stream.proc) { + stream.proc.kill(); + stream.proc = undefined; + } + } + + class PageantSocket extends Duplex { + constructor() { + super(); + this.proc = undefined; + this.buffer = null; + } + _read(n) {} + _write(data, encoding, cb) { + if (this.buffer === null) { + this.buffer = data; + } else { + const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); + this.buffer.copy(newBuffer, 0); + data.copy(newBuffer, this.buffer.length); + this.buffer = newBuffer; + } + // Wait for at least all length bytes + if (this.buffer.length < 4) + return cb(); + + const len = readUInt32BE(this.buffer, 0); + // Make sure we have a full message before querying pageant + if ((this.buffer.length - 4) < len) + return cb(); + + data = this.buffer.slice(0, 4 + len); + if (this.buffer.length > (4 + len)) + return cb(new Error('Unexpected multiple agent requests')); + this.buffer = null; + + let error; + const proc = this.proc = spawn(__nccwpck_require__.ab + "pagent.exe", [ data.length ]); + proc.stdout.on('data', (data) => { + this.push(data); + }); + proc.on('error', (err) => { + error = err; + cb(error); + }); + proc.on('close', (code) => { + this.proc = undefined; + if (!error) { + if (error = ERROR[code]) + return cb(error); + cb(); + } + }); + proc.stdin.end(data); + } + _final(cb) { + destroy(this); + cb(); + } + _destroy(err, cb) { + destroy(this); + cb(); + } + } + + return class PageantAgent extends OpenSSHAgent { + getStream(cb) { + cb(null, new PageantSocket()); + } + }; +})(); + +const CygwinAgent = (() => { + const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; + + return class CygwinAgent extends OpenSSHAgent { + getStream(cb) { + cb = once(cb); + + // The cygwin ssh-agent connection process looks like this: + // 1. Read the "socket" as a file to get the underlying TCP port and a + // special "secret" that must be sent to the TCP server. + // 2. Connect to the server listening on localhost at the TCP port. + // 3. Send the "secret" to the server. + // 4. The server sends back the same "secret". + // 5. Send three 32-bit integer values of zero. This is ordinarily the + // pid, uid, and gid of this process, but cygwin will actually + // send us the correct values as a response. + // 6. The server sends back the pid, uid, gid. + // 7. Disconnect. + // 8. Repeat steps 2-6, except send the received pid, uid, and gid in + // step 5 instead of zeroes. + // 9. Connection is ready to be used. + + let socketPath = this.socketPath; + let triedCygpath = false; + readFile(socketPath, function readCygsocket(err, data) { + if (err) { + if (triedCygpath) + return cb(new Error('Invalid cygwin unix socket path')); + + // Try using `cygpath` to convert a possible *nix-style path to the + // real Windows path before giving up ... + execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { + if (err || stdout.length === 0) + return cb(new Error('Invalid cygwin unix socket path')); + + triedCygpath = true; + socketPath = stdout.toString().replace(/[\r\n]/g, ''); + readFile(socketPath, readCygsocket); + }); + return; + } + + const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); + if (!m) + return cb(new Error('Malformed cygwin unix socket file')); + + let state; + let bc = 0; + let isRetrying = false; + const inBuf = []; + let sock; + + // Use 0 for pid, uid, and gid to ensure we get an error and also + // a valid uid and gid from cygwin so that we don't have to figure it + // out ourselves + let credsBuf = Buffer.alloc(12); + + // Parse cygwin unix socket file contents + const port = parseInt(m[1], 10); + const secret = m[2].replace(/-/g, ''); + const secretBuf = Buffer.allocUnsafe(16); + for (let i = 0, j = 0; j < 32; ++i, j += 2) + secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); + + // Convert to host order (always LE for Windows) + for (let i = 0; i < 16; i += 4) + writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); + + tryConnect(); + + function _onconnect() { + bc = 0; + state = 'secret'; + sock.write(secretBuf); + } + + function _ondata(data) { + bc += data.length; + + if (state === 'secret') { + // The secret we sent is echoed back to us by cygwin, not sure of + // the reason for that, but we ignore it nonetheless ... + if (bc === 16) { + bc = 0; + state = 'creds'; + sock.write(credsBuf); + } + return; + } + + if (state === 'creds') { + // If this is the first attempt, make sure to gather the valid + // uid and gid for our next attempt + if (!isRetrying) + inBuf.push(data); + + if (bc === 12) { + sock.removeListener('connect', _onconnect); + sock.removeListener('data', _ondata); + sock.removeListener('error', onFail); + sock.removeListener('end', onFail); + sock.removeListener('close', onFail); + + if (isRetrying) + return cb(null, sock); + + isRetrying = true; + credsBuf = Buffer.concat(inBuf); + writeUInt32LE(credsBuf, process.pid, 0); + sock.on('error', () => {}); + sock.destroy(); + + tryConnect(); + } + } + } + + function onFail() { + cb(new Error('Problem negotiating cygwin unix socket security')); + } + + function tryConnect() { + sock = new Socket(); + sock.on('connect', _onconnect); + sock.on('data', _ondata); + sock.on('error', onFail); + sock.on('end', onFail); + sock.on('close', onFail); + sock.connect(port); + } + }); + } + }; +})(); + +// Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes +// being interchangeable +const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; +function createAgent(path) { + if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { + return (path === 'pageant' + ? new PageantAgent() + : new CygwinAgent(path)); + } + return new OpenSSHAgent(path); +} + +const AgentProtocol = (() => { + // Client->Server messages + const SSH_AGENTC_REQUEST_IDENTITIES = 11; + const SSH_AGENTC_SIGN_REQUEST = 13; + // const SSH_AGENTC_ADD_IDENTITY = 17; + // const SSH_AGENTC_REMOVE_IDENTITY = 18; + // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; + // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; + // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; + // const SSH_AGENTC_LOCK = 22; + // const SSH_AGENTC_UNLOCK = 23; + // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; + // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; + // const SSH_AGENTC_EXTENSION = 27; + // Server->Client messages + const SSH_AGENT_FAILURE = 5; + // const SSH_AGENT_SUCCESS = 6; + const SSH_AGENT_IDENTITIES_ANSWER = 12; + const SSH_AGENT_SIGN_RESPONSE = 14; + // const SSH_AGENT_EXTENSION_FAILURE = 28; + + // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; + // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; + // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; + + const SSH_AGENT_RSA_SHA2_256 = (1 << 1); + const SSH_AGENT_RSA_SHA2_512 = (1 << 2); + + const ROLE_CLIENT = 0; + const ROLE_SERVER = 1; + + // Ensures that responses get sent back in the same order the requests were + // received + function processResponses(protocol) { + let ret; + while (protocol[SYM_REQS].length) { + const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; + if (nextResponse === undefined) + break; + + protocol[SYM_REQS].shift(); + ret = protocol.push(nextResponse); + } + return ret; + } + + const SYM_TYPE = Symbol('Inbound Request Type'); + const SYM_RESP = Symbol('Inbound Request Response'); + const SYM_CTX = Symbol('Inbound Request Context'); + class AgentInboundRequest { + constructor(type, ctx) { + this[SYM_TYPE] = type; + this[SYM_RESP] = undefined; + this[SYM_CTX] = ctx; + } + hasResponded() { + return (this[SYM_RESP] !== undefined); + } + getType() { + return this[SYM_TYPE]; + } + getContext() { + return this[SYM_CTX]; + } + } + function respond(protocol, req, data) { + req[SYM_RESP] = data; + return processResponses(protocol); + } + + function cleanup(protocol) { + protocol[SYM_BUFFER] = null; + if (protocol[SYM_MODE] === ROLE_CLIENT) { + const reqs = protocol[SYM_REQS]; + if (reqs && reqs.length) { + protocol[SYM_REQS] = []; + for (const req of reqs) + req.cb(new Error('No reply from server')); + } + } + + // Node streams hackery to make streams do the "right thing" + try { + protocol.end(); + } catch {} + setImmediate(() => { + if (!protocol[SYM_ENDED]) + protocol.emit('end'); + if (!protocol[SYM_CLOSED]) + protocol.emit('close'); + }); + } + + function onClose() { + this[SYM_CLOSED] = true; + } + + function onEnd() { + this[SYM_ENDED] = true; + } + + const SYM_REQS = Symbol('Requests'); + const SYM_MODE = Symbol('Agent Protocol Role'); + const SYM_BUFFER = Symbol('Agent Protocol Buffer'); + const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); + const SYM_CLOSED = Symbol('Agent Protocol Closed'); + const SYM_ENDED = Symbol('Agent Protocol Ended'); + // Implementation based on: + // https://tools.ietf.org/html/draft-miller-ssh-agent-04 + return class AgentProtocol extends Duplex { + /* + Notes: + - `constraint` type consists of: + byte constraint_type + byte[] constraint_data + where `constraint_type` is one of: + * SSH_AGENT_CONSTRAIN_LIFETIME + - `constraint_data` consists of: + uint32 seconds + * SSH_AGENT_CONSTRAIN_CONFIRM + - `constraint_data` N/A + * SSH_AGENT_CONSTRAIN_EXTENSION + - `constraint_data` consists of: + string extension name + byte[] extension-specific details + */ + + constructor(isClient) { + super({ autoDestroy: true, emitClose: false }); + this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); + this[SYM_REQS] = []; + this[SYM_BUFFER] = null; + this[SYM_MSGLEN] = -1; + this.once('end', onEnd); + this.once('close', onClose); + } + + _read(n) {} + + _write(data, encoding, cb) { + /* + Messages are of the format: + uint32 message length + byte message type + byte[message length - 1] message contents + */ + if (this[SYM_BUFFER] === null) + this[SYM_BUFFER] = data; + else + this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); + + let buffer = this[SYM_BUFFER]; + let bufferLen = buffer.length; + + let p = 0; + while (p < bufferLen) { + // Wait for length + type + if (bufferLen < 5) + break; + + if (this[SYM_MSGLEN] === -1) + this[SYM_MSGLEN] = readUInt32BE(buffer, p); + + // Check if we have the entire message + if (bufferLen < (4 + this[SYM_MSGLEN])) + break; + + const msgType = buffer[p += 4]; + ++p; + + if (this[SYM_MODE] === ROLE_CLIENT) { + if (this[SYM_REQS].length === 0) + return cb(new Error('Received unexpected message from server')); + + const req = this[SYM_REQS].shift(); + + switch (msgType) { + case SSH_AGENT_FAILURE: + req.cb(new Error('Agent responded with failure')); + break; + case SSH_AGENT_IDENTITIES_ANSWER: { + if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) + return cb(new Error('Agent responded with wrong message type')); + + /* + byte SSH_AGENT_IDENTITIES_ANSWER + uint32 nkeys + + where `nkeys` is 0 or more of: + string key blob + string comment + */ + + binaryParser.init(buffer, p); + + const numKeys = binaryParser.readUInt32BE(); + + if (numKeys === undefined) { + binaryParser.clear(); + return cb(new Error('Malformed agent response')); + } + + const keys = []; + for (let i = 0; i < numKeys; ++i) { + let pubKey = binaryParser.readString(); + if (pubKey === undefined) { + binaryParser.clear(); + return cb(new Error('Malformed agent response')); + } + + const comment = binaryParser.readString(true); + if (comment === undefined) { + binaryParser.clear(); + return cb(new Error('Malformed agent response')); + } + + pubKey = parseKey(pubKey); + // We continue parsing the packet if we encounter an error + // in case the error is due to the key being an unsupported + // type + if (pubKey instanceof Error) + continue; + + pubKey.comment = pubKey.comment || comment; + + keys.push(pubKey); + } + p = binaryParser.pos(); + binaryParser.clear(); + + req.cb(null, keys); + break; + } + case SSH_AGENT_SIGN_RESPONSE: { + if (req.type !== SSH_AGENTC_SIGN_REQUEST) + return cb(new Error('Agent responded with wrong message type')); + + /* + byte SSH_AGENT_SIGN_RESPONSE + string signature + */ + + binaryParser.init(buffer, p); + let signature = binaryParser.readString(); + p = binaryParser.pos(); + binaryParser.clear(); + + if (signature === undefined) + return cb(new Error('Malformed agent response')); + + // We strip the algorithm from OpenSSH's output and assume it's + // using the algorithm we specified. This makes it easier on + // custom Agent implementations so they don't have to construct + // the correct binary format for a (OpenSSH-style) signature. + + // TODO: verify signature type based on key and options used + // during initial sign request + binaryParser.init(signature, 0); + binaryParser.readString(true); + signature = binaryParser.readString(); + binaryParser.clear(); + + if (signature === undefined) + return cb(new Error('Malformed OpenSSH signature format')); + + req.cb(null, signature); + break; + } + default: + return cb( + new Error('Agent responded with unsupported message type') + ); + } + } else { + switch (msgType) { + case SSH_AGENTC_REQUEST_IDENTITIES: { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + /* + byte SSH_AGENTC_REQUEST_IDENTITIES + */ + this.emit('identities', req); + break; + } + case SSH_AGENTC_SIGN_REQUEST: { + /* + byte SSH_AGENTC_SIGN_REQUEST + string key_blob + string data + uint32 flags + */ + binaryParser.init(buffer, p); + let pubKey = binaryParser.readString(); + const data = binaryParser.readString(); + const flagsVal = binaryParser.readUInt32BE(); + p = binaryParser.pos(); + binaryParser.clear(); + if (flagsVal === undefined) { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + return this.failureReply(req); + } + + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + return this.failureReply(req); + } + + const flags = { + hash: undefined, + }; + let ctx; + if (pubKey.type === 'ssh-rsa') { + if (flagsVal & SSH_AGENT_RSA_SHA2_256) { + ctx = 'rsa-sha2-256'; + flags.hash = 'sha256'; + } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { + ctx = 'rsa-sha2-512'; + flags.hash = 'sha512'; + } + } + if (ctx === undefined) + ctx = pubKey.type; + + const req = new AgentInboundRequest(msgType, ctx); + this[SYM_REQS].push(req); + + this.emit('sign', req, pubKey, data, flags); + break; + } + default: { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + this.failureReply(req); + } + } + } + + // Get ready for next message + this[SYM_MSGLEN] = -1; + if (p === bufferLen) { + // Nothing left to process for now + this[SYM_BUFFER] = null; + break; + } else { + this[SYM_BUFFER] = buffer = buffer.slice(p); + bufferLen = buffer.length; + p = 0; + } + } + + cb(); + } + + _destroy(err, cb) { + cleanup(this); + cb(); + } + + _final(cb) { + cleanup(this); + cb(); + } + + // Client->Server messages ================================================= + sign(pubKey, data, options, cb) { + if (this[SYM_MODE] !== ROLE_CLIENT) + throw new Error('Client-only method called with server role'); + + if (typeof options === 'function') { + cb = options; + options = undefined; + } else if (typeof options !== 'object' || options === null) { + options = undefined; + } + + let flags = 0; + + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error('Invalid public key argument'); + + if (pubKey.type === 'ssh-rsa' && options) { + switch (options.hash) { + case 'sha256': + flags = SSH_AGENT_RSA_SHA2_256; + break; + case 'sha512': + flags = SSH_AGENT_RSA_SHA2_512; + break; + } + } + pubKey = pubKey.getPublicSSH(); + + /* + byte SSH_AGENTC_SIGN_REQUEST + string key_blob + string data + uint32 flags + */ + const type = SSH_AGENTC_SIGN_REQUEST; + const keyLen = pubKey.length; + const dataLen = data.length; + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); + + writeUInt32BE(buf, buf.length - 4, p); + + buf[p += 4] = type; + + writeUInt32BE(buf, keyLen, ++p); + pubKey.copy(buf, p += 4); + + writeUInt32BE(buf, dataLen, p += keyLen); + data.copy(buf, p += 4); + + writeUInt32BE(buf, flags, p += dataLen); + + if (typeof cb !== 'function') + cb = noop; + + this[SYM_REQS].push({ type, cb }); + + return this.push(buf); + } + getIdentities(cb) { + if (this[SYM_MODE] !== ROLE_CLIENT) + throw new Error('Client-only method called with server role'); + + /* + byte SSH_AGENTC_REQUEST_IDENTITIES + */ + const type = SSH_AGENTC_REQUEST_IDENTITIES; + + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1); + + writeUInt32BE(buf, buf.length - 4, p); + + buf[p += 4] = type; + + if (typeof cb !== 'function') + cb = noop; + + this[SYM_REQS].push({ type, cb }); + + return this.push(buf); + } + + // Server->Client messages ================================================= + failureReply(req) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error('Server-only method called with client role'); + + if (!(req instanceof AgentInboundRequest)) + throw new Error('Wrong request argument'); + + if (req.hasResponded()) + return true; + + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1); + + writeUInt32BE(buf, buf.length - 4, p); + + buf[p += 4] = SSH_AGENT_FAILURE; + + return respond(this, req, buf); + } + getIdentitiesReply(req, keys) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error('Server-only method called with client role'); + + if (!(req instanceof AgentInboundRequest)) + throw new Error('Wrong request argument'); + + if (req.hasResponded()) + return true; + + /* + byte SSH_AGENT_IDENTITIES_ANSWER + uint32 nkeys + + where `nkeys` is 0 or more of: + string key blob + string comment + */ + + if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) + throw new Error('Invalid response to request'); + + if (!Array.isArray(keys)) + throw new Error('Keys argument must be an array'); + + let totalKeysLen = 4; // Include `nkeys` size + + const newKeys = []; + for (let i = 0; i < keys.length; ++i) { + const entry = keys[i]; + if (typeof entry !== 'object' || entry === null) + throw new Error(`Invalid key entry: ${entry}`); + + let pubKey; + let comment; + if (isParsedKey(entry)) { + pubKey = entry; + } else if (isParsedKey(entry.pubKey)) { + pubKey = entry.pubKey; + } else { + if (typeof entry.pubKey !== 'object' || entry.pubKey === null) + continue; + ({ pubKey, comment } = entry.pubKey); + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + continue; // TODO: add debug output + } + comment = pubKey.comment || comment; + pubKey = pubKey.getPublicSSH(); + + totalKeysLen += 4 + pubKey.length; + + if (comment && typeof comment === 'string') + comment = Buffer.from(comment); + else if (!Buffer.isBuffer(comment)) + comment = EMPTY_BUF; + + totalKeysLen += 4 + comment.length; + + newKeys.push({ pubKey, comment }); + } + + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); + + writeUInt32BE(buf, buf.length - 4, p); + + buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; + + writeUInt32BE(buf, newKeys.length, ++p); + p += 4; + for (let i = 0; i < newKeys.length; ++i) { + const { pubKey, comment } = newKeys[i]; + + writeUInt32BE(buf, pubKey.length, p); + pubKey.copy(buf, p += 4); + + writeUInt32BE(buf, comment.length, p += pubKey.length); + p += 4; + if (comment.length) { + comment.copy(buf, p); + p += comment.length; + } + } + + return respond(this, req, buf); + } + signReply(req, signature) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error('Server-only method called with client role'); + + if (!(req instanceof AgentInboundRequest)) + throw new Error('Wrong request argument'); + + if (req.hasResponded()) + return true; + + /* + byte SSH_AGENT_SIGN_RESPONSE + string signature + */ + + if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) + throw new Error('Invalid response to request'); + + if (!Buffer.isBuffer(signature)) + throw new Error('Signature argument must be a Buffer'); + + if (signature.length === 0) + throw new Error('Signature argument must be non-empty'); + + /* + OpenSSH agent signatures are encoded as: + + string signature format identifier (as specified by the + public key/certificate format) + byte[n] signature blob in format specific encoding. + - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 + types + */ + + let p = 0; + const sigFormat = req.getContext(); + const sigFormatLen = Buffer.byteLength(sigFormat); + const buf = Buffer.allocUnsafe( + 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length + ); + + writeUInt32BE(buf, buf.length - 4, p); + + buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; + + writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); + writeUInt32BE(buf, sigFormatLen, p += 4); + buf.utf8Write(sigFormat, p += 4, sigFormatLen); + writeUInt32BE(buf, signature.length, p += sigFormatLen); + signature.copy(buf, p += 4); + + return respond(this, req, buf); + } + }; +})(); + +const SYM_AGENT = Symbol('Agent'); +const SYM_AGENT_KEYS = Symbol('Agent Keys'); +const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); +const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); +class AgentContext { + constructor(agent) { + if (typeof agent === 'string') + agent = createAgent(agent); + else if (!isAgent(agent)) + throw new Error('Invalid agent argument'); + this[SYM_AGENT] = agent; + this[SYM_AGENT_KEYS] = null; + this[SYM_AGENT_KEYS_IDX] = -1; + this[SYM_AGENT_CBS] = null; + } + init(cb) { + if (typeof cb !== 'function') + cb = noop; + + if (this[SYM_AGENT_KEYS] === null) { + if (this[SYM_AGENT_CBS] === null) { + this[SYM_AGENT_CBS] = [cb]; + + const doCbs = (...args) => { + process.nextTick(() => { + const cbs = this[SYM_AGENT_CBS]; + this[SYM_AGENT_CBS] = null; + for (const cb of cbs) + cb(...args); + }); + }; + + this[SYM_AGENT].getIdentities(once((err, keys) => { + if (err) + return doCbs(err); + + if (!Array.isArray(keys)) { + return doCbs(new Error( + 'Agent implementation failed to provide keys' + )); + } + + const newKeys = []; + for (let key of keys) { + key = parseKey(key); + if (key instanceof Error) { + // TODO: add debug output + continue; + } + newKeys.push(key); + } + + this[SYM_AGENT_KEYS] = newKeys; + this[SYM_AGENT_KEYS_IDX] = -1; + doCbs(); + })); + } else { + this[SYM_AGENT_CBS].push(cb); + } + } else { + process.nextTick(cb); + } + } + nextKey() { + if (this[SYM_AGENT_KEYS] === null + || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return false; + } + + return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; + } + currentKey() { + if (this[SYM_AGENT_KEYS] === null + || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return null; + } + + return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; + } + pos() { + if (this[SYM_AGENT_KEYS] === null + || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return -1; + } + + return this[SYM_AGENT_KEYS_IDX]; + } + reset() { + this[SYM_AGENT_KEYS_IDX] = -1; + } + + sign(...args) { + this[SYM_AGENT].sign(...args); + } +} + +function isAgent(val) { + return (val instanceof BaseAgent); +} + +module.exports = { + AgentContext, + AgentProtocol, + BaseAgent, + createAgent, + CygwinAgent, + isAgent, + OpenSSHAgent, + PageantAgent, +}; + + +/***/ }), + +/***/ 6063: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// TODO: +// * add `.connected` or similar property to allow immediate connection +// status checking +// * add/improve debug output during user authentication phase + + +const { + createHash, + getHashes, + randomFillSync, +} = __nccwpck_require__(6113); +const { Socket } = __nccwpck_require__(1808); +const { lookup: dnsLookup } = __nccwpck_require__(9523); +const EventEmitter = __nccwpck_require__(2361); +const HASHES = getHashes(); + +const { + COMPAT, + CHANNEL_EXTENDED_DATATYPE: { STDERR }, + CHANNEL_OPEN_FAILURE, + DEFAULT_CIPHER, + DEFAULT_COMPRESSION, + DEFAULT_KEX, + DEFAULT_MAC, + DEFAULT_SERVER_HOST_KEY, + DISCONNECT_REASON, + DISCONNECT_REASON_BY_VALUE, + SUPPORTED_CIPHER, + SUPPORTED_COMPRESSION, + SUPPORTED_KEX, + SUPPORTED_MAC, + SUPPORTED_SERVER_HOST_KEY, +} = __nccwpck_require__(6832); +const { init: cryptoInit } = __nccwpck_require__(5708); +const Protocol = __nccwpck_require__(9031); +const { parseKey } = __nccwpck_require__(2218); +const { SFTP } = __nccwpck_require__(2026); +const { + bufferCopy, + makeBufferParser, + makeError, + readUInt32BE, + sigSSHToASN1, + writeUInt32BE, +} = __nccwpck_require__(9475); + +const { AgentContext, createAgent, isAgent } = __nccwpck_require__(6119); +const { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD, +} = __nccwpck_require__(3204); +const { + ChannelManager, + generateAlgorithmList, + isWritable, + onChannelOpenFailure, + onCHANNEL_CLOSE, +} = __nccwpck_require__(834); + +const bufferParser = makeBufferParser(); +const sigParser = makeBufferParser(); +const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; +const noop = (err) => {}; + +class Client extends EventEmitter { + constructor() { + super(); + + this.config = { + host: undefined, + port: undefined, + localAddress: undefined, + localPort: undefined, + forceIPv4: undefined, + forceIPv6: undefined, + keepaliveCountMax: undefined, + keepaliveInterval: undefined, + readyTimeout: undefined, + ident: undefined, + + username: undefined, + password: undefined, + privateKey: undefined, + tryKeyboard: undefined, + agent: undefined, + allowAgentFwd: undefined, + authHandler: undefined, + + hostHashAlgo: undefined, + hostHashCb: undefined, + strictVendor: undefined, + debug: undefined + }; + + this._agent = undefined; + this._readyTimeout = undefined; + this._chanMgr = undefined; + this._callbacks = undefined; + this._forwarding = undefined; + this._forwardingUnix = undefined; + this._acceptX11 = undefined; + this._agentFwdEnabled = undefined; + this._remoteVer = undefined; + + this._protocol = undefined; + this._sock = undefined; + this._resetKA = undefined; + } + + connect(cfg) { + if (this._sock && isWritable(this._sock)) { + this.once('close', () => { + this.connect(cfg); + }); + this.end(); + return this; + } + + this.config.host = cfg.hostname || cfg.host || 'localhost'; + this.config.port = cfg.port || 22; + this.config.localAddress = (typeof cfg.localAddress === 'string' + ? cfg.localAddress + : undefined); + this.config.localPort = (typeof cfg.localPort === 'string' + || typeof cfg.localPort === 'number' + ? cfg.localPort + : undefined); + this.config.forceIPv4 = cfg.forceIPv4 || false; + this.config.forceIPv6 = cfg.forceIPv6 || false; + this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' + && cfg.keepaliveCountMax >= 0 + ? cfg.keepaliveCountMax + : 3); + this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' + && cfg.keepaliveInterval > 0 + ? cfg.keepaliveInterval + : 0); + this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' + && cfg.readyTimeout >= 0 + ? cfg.readyTimeout + : 20000); + this.config.ident = (typeof cfg.ident === 'string' + || Buffer.isBuffer(cfg.ident) + ? cfg.ident + : undefined); + + const algorithms = { + kex: undefined, + serverHostKey: undefined, + cs: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: [], + }, + sc: undefined, + }; + let allOfferDefaults = true; + if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { + algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, + DEFAULT_KEX, + SUPPORTED_KEX); + if (algorithms.kex !== DEFAULT_KEX) + allOfferDefaults = false; + + algorithms.serverHostKey = + generateAlgorithmList(cfg.algorithms.serverHostKey, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY); + if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) + allOfferDefaults = false; + + algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, + DEFAULT_CIPHER, + SUPPORTED_CIPHER); + if (algorithms.cs.cipher !== DEFAULT_CIPHER) + allOfferDefaults = false; + + algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, + DEFAULT_MAC, + SUPPORTED_MAC); + if (algorithms.cs.mac !== DEFAULT_MAC) + allOfferDefaults = false; + + algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION); + if (algorithms.cs.compress !== DEFAULT_COMPRESSION) + allOfferDefaults = false; + + if (!allOfferDefaults) + algorithms.sc = algorithms.cs; + } + + if (typeof cfg.username === 'string') + this.config.username = cfg.username; + else if (typeof cfg.user === 'string') + this.config.username = cfg.user; + else + throw new Error('Invalid username'); + + this.config.password = (typeof cfg.password === 'string' + ? cfg.password + : undefined); + this.config.privateKey = (typeof cfg.privateKey === 'string' + || Buffer.isBuffer(cfg.privateKey) + ? cfg.privateKey + : undefined); + this.config.localHostname = (typeof cfg.localHostname === 'string' + ? cfg.localHostname + : undefined); + this.config.localUsername = (typeof cfg.localUsername === 'string' + ? cfg.localUsername + : undefined); + this.config.tryKeyboard = (cfg.tryKeyboard === true); + if (typeof cfg.agent === 'string' && cfg.agent.length) + this.config.agent = createAgent(cfg.agent); + else if (isAgent(cfg.agent)) + this.config.agent = cfg.agent; + else + this.config.agent = undefined; + this.config.allowAgentFwd = (cfg.agentForward === true + && this.config.agent !== undefined); + let authHandler = this.config.authHandler = ( + typeof cfg.authHandler === 'function' + || Array.isArray(cfg.authHandler) + ? cfg.authHandler + : undefined + ); + + this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' + ? cfg.strictVendor + : true); + + const debug = this.config.debug = (typeof cfg.debug === 'function' + ? cfg.debug + : undefined); + + if (cfg.agentForward === true && !this.config.allowAgentFwd) { + throw new Error( + 'You must set a valid agent path to allow agent forwarding' + ); + } + + let callbacks = this._callbacks = []; + this._chanMgr = new ChannelManager(this); + this._forwarding = {}; + this._forwardingUnix = {}; + this._acceptX11 = 0; + this._agentFwdEnabled = false; + this._agent = (this.config.agent ? this.config.agent : undefined); + this._remoteVer = undefined; + let privateKey; + + if (this.config.privateKey) { + privateKey = parseKey(this.config.privateKey, cfg.passphrase); + if (privateKey instanceof Error) + throw new Error(`Cannot parse privateKey: ${privateKey.message}`); + if (Array.isArray(privateKey)) { + // OpenSSH's newer format only stores 1 key for now + privateKey = privateKey[0]; + } + if (privateKey.getPrivatePEM() === null) { + throw new Error( + 'privateKey value does not contain a (valid) private key' + ); + } + } + + let hostVerifier; + if (typeof cfg.hostVerifier === 'function') { + const hashCb = cfg.hostVerifier; + let hasher; + if (HASHES.indexOf(cfg.hostHash) !== -1) { + // Default to old behavior of hashing on user's behalf + hasher = createHash(cfg.hostHash); + } + hostVerifier = (key, verify) => { + if (hasher) { + hasher.update(key); + key = hasher.digest('hex'); + } + const ret = hashCb(key, verify); + if (ret !== undefined) + verify(ret); + }; + } + + const sock = this._sock = (cfg.sock || new Socket()); + let ready = false; + let sawHeader = false; + if (this._protocol) + this._protocol.cleanup(); + const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { + debug(`Debug output from server: ${JSON.stringify(msg)}`); + }); + let serverSigAlgs; + const proto = this._protocol = new Protocol({ + ident: this.config.ident, + offer: (allOfferDefaults ? undefined : algorithms), + onWrite: (data) => { + if (isWritable(sock)) + sock.write(data); + }, + onError: (err) => { + if (err.level === 'handshake') + clearTimeout(this._readyTimeout); + if (!proto._destruct) + sock.removeAllListeners('data'); + this.emit('error', err); + try { + sock.end(); + } catch {} + }, + onHeader: (header) => { + sawHeader = true; + this._remoteVer = header.versions.software; + if (header.greeting) + this.emit('greeting', header.greeting); + }, + onHandshakeComplete: (negotiated) => { + this.emit('handshake', negotiated); + if (!ready) { + ready = true; + proto.service('ssh-userauth'); + } + }, + debug, + hostVerifier, + messageHandlers: { + DEBUG: DEBUG_HANDLER, + DISCONNECT: (p, reason, desc) => { + if (reason !== DISCONNECT_REASON.BY_APPLICATION) { + if (!desc) { + desc = DISCONNECT_REASON_BY_VALUE[reason]; + if (desc === undefined) + desc = `Unexpected disconnection reason: ${reason}`; + } + const err = new Error(desc); + err.code = reason; + this.emit('error', err); + } + sock.end(); + }, + SERVICE_ACCEPT: (p, name) => { + if (name === 'ssh-userauth') + tryNextAuth(); + }, + EXT_INFO: (p, exts) => { + if (serverSigAlgs === undefined) { + for (const ext of exts) { + if (ext.name === 'server-sig-algs') { + serverSigAlgs = ext.algs; + return; + } + } + serverSigAlgs = null; + } + }, + USERAUTH_BANNER: (p, msg) => { + this.emit('banner', msg); + }, + USERAUTH_SUCCESS: (p) => { + // Start keepalive mechanism + resetKA(); + + clearTimeout(this._readyTimeout); + + this.emit('ready'); + }, + USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { + // For key-based authentication, check if we should retry the current + // key with a different algorithm first + if (curAuth.keyAlgos) { + const oldKeyAlgo = curAuth.keyAlgos[0][0]; + if (debug) + debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); + curAuth.keyAlgos.shift(); + if (curAuth.keyAlgos.length) { + const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + switch (curAuth.type) { + case 'agent': + proto.authPK( + curAuth.username, + curAuth.agentCtx.currentKey(), + keyAlgo + ); + return; + case 'publickey': + proto.authPK(curAuth.username, curAuth.key, keyAlgo); + return; + case 'hostbased': + proto.authHostbased(curAuth.username, + curAuth.key, + curAuth.localHostname, + curAuth.localUsername, + keyAlgo, + (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = + `Error while signing with key: ${signature.message}`; + signature.level = 'client-authentication'; + this.emit('error', signature); + return tryNextAuth(); + } + + cb(signature); + }); + return; + } + } else { + curAuth.keyAlgos = undefined; + } + } + + if (curAuth.type === 'agent') { + const pos = curAuth.agentCtx.pos(); + debug && debug(`Client: Agent key #${pos + 1} failed`); + return tryNextAgentKey(); + } + + debug && debug(`Client: ${curAuth.type} auth failed`); + + curPartial = partialSuccess; + curAuthsLeft = authMethods; + tryNextAuth(); + }, + USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { + if (curAuth.type === 'password') { + // TODO: support a `changePrompt()` on `curAuth` that defaults to + // emitting 'change password' as before + this.emit('change password', prompt, (newPassword) => { + proto.authPassword( + this.config.username, + this.config.password, + newPassword + ); + }); + } + }, + USERAUTH_PK_OK: (p) => { + let keyAlgo; + let hashAlgo; + if (curAuth.keyAlgos) + [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + if (curAuth.type === 'agent') { + const key = curAuth.agentCtx.currentKey(); + proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => { + const opts = { hash: hashAlgo }; + curAuth.agentCtx.sign(key, buf, opts, (err, signed) => { + if (err) { + err.level = 'agent'; + this.emit('error', err); + } else { + return cb(signed); + } + + tryNextAgentKey(); + }); + }); + } else if (curAuth.type === 'publickey') { + proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = + `Error signing data with key: ${signature.message}`; + signature.level = 'client-authentication'; + this.emit('error', signature); + return tryNextAuth(); + } + cb(signature); + }); + } + }, + USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { + if (curAuth.type === 'keyboard-interactive') { + const nprompts = (Array.isArray(prompts) ? prompts.length : 0); + if (nprompts === 0) { + debug && debug( + 'Client: Sending automatic USERAUTH_INFO_RESPONSE' + ); + proto.authInfoRes(); + return; + } + // We sent a keyboard-interactive user authentication request and + // now the server is sending us the prompts we need to present to + // the user + curAuth.prompt( + name, + instructions, + '', + prompts, + (answers) => { + proto.authInfoRes(answers); + } + ); + } + }, + REQUEST_SUCCESS: (p, data) => { + if (callbacks.length) + callbacks.shift()(false, data); + }, + REQUEST_FAILURE: (p) => { + if (callbacks.length) + callbacks.shift()(true); + }, + GLOBAL_REQUEST: (p, name, wantReply, data) => { + switch (name) { + case 'hostkeys-00@openssh.com': + // Automatically verify keys before passing to end user + hostKeysProve(this, data, (err, keys) => { + if (err) + return; + this.emit('hostkeys', keys); + }); + if (wantReply) + proto.requestSuccess(); + break; + default: + // Auto-reject all other global requests, this can be especially + // useful if the server is sending us dummy keepalive global + // requests + if (wantReply) + proto.requestFailure(); + } + }, + CHANNEL_OPEN: (p, info) => { + // Handle incoming requests from server, typically a forwarded TCP or + // X11 connection + onCHANNEL_OPEN(this, info); + }, + CHANNEL_OPEN_CONFIRMATION: (p, info) => { + const channel = this._chanMgr.get(info.recipient); + if (typeof channel !== 'function') + return; + + const isSFTP = (channel.type === 'sftp'); + const type = (isSFTP ? 'session' : channel.type); + const chanInfo = { + type, + incoming: { + id: info.recipient, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; + const instance = ( + isSFTP + ? new SFTP(this, chanInfo, { debug }) + : new Channel(this, chanInfo) + ); + this._chanMgr.update(info.recipient, instance); + channel(undefined, instance); + }, + CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'function') + return; + + const info = { reason, description }; + onChannelOpenFailure(this, recipient, info, channel); + }, + CHANNEL_DATA: (p, recipient, data) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + + // The remote party should not be sending us data if there is no + // window space available ... + // TODO: raise error on data with not enough window? + if (channel.incoming.window === 0) + return; + + channel.incoming.window -= data.length; + + if (channel.push(data) === false) { + channel._waitChanDrain = true; + return; + } + + if (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { + if (type !== STDERR) + return; + + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + + // The remote party should not be sending us data if there is no + // window space available ... + // TODO: raise error on data with not enough window? + if (channel.incoming.window === 0) + return; + + channel.incoming.window -= data.length; + + if (!channel.stderr.push(data)) { + channel._waitChanDrain = true; + return; + } + + if (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + + // The other side is allowing us to send `amount` more bytes of data + channel.outgoing.window += amount; + + if (channel._waitWindow) { + channel._waitWindow = false; + + if (channel._chunk) { + channel._write(channel._chunk, null, channel._chunkcb); + } else if (channel._chunkcb) { + channel._chunkcb(); + } else if (channel._chunkErr) { + channel.stderr._write(channel._chunkErr, + null, + channel._chunkcbErr); + } else if (channel._chunkcbErr) { + channel._chunkcbErr(); + } + } + }, + CHANNEL_SUCCESS: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + + this._resetKA(); + + if (channel._callbacks.length) + channel._callbacks.shift()(false); + }, + CHANNEL_FAILURE: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + + this._resetKA(); + + if (channel._callbacks.length) + channel._callbacks.shift()(true); + }, + CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + + const exit = channel._exit; + if (exit.code !== undefined) + return; + switch (type) { + case 'exit-status': + channel.emit('exit', exit.code = data); + return; + case 'exit-signal': + channel.emit('exit', + exit.code = null, + exit.signal = `SIG${data.signal}`, + exit.dump = data.coreDumped, + exit.desc = data.errorMessage); + return; + } + + // Keepalive request? OpenSSH will send one as a channel request if + // there is a channel open + + if (wantReply) + p.channelFailure(channel.outgoing.id); + }, + CHANNEL_EOF: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + + if (channel.incoming.state !== 'open') + return; + channel.incoming.state = 'eof'; + + if (channel.readable) + channel.push(null); + if (channel.stderr.readable) + channel.stderr.push(null); + }, + CHANNEL_CLOSE: (p, recipient) => { + onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); + }, + }, + }); + + sock.pause(); + + // TODO: check keepalive implementation + // Keepalive-related + const kainterval = this.config.keepaliveInterval; + const kacountmax = this.config.keepaliveCountMax; + let kacount = 0; + let katimer; + const sendKA = () => { + if (++kacount > kacountmax) { + clearInterval(katimer); + if (sock.readable) { + const err = new Error('Keepalive timeout'); + err.level = 'client-timeout'; + this.emit('error', err); + sock.destroy(); + } + return; + } + if (isWritable(sock)) { + // Append dummy callback to keep correct callback order + callbacks.push(resetKA); + proto.ping(); + } else { + clearInterval(katimer); + } + }; + function resetKA() { + if (kainterval > 0) { + kacount = 0; + clearInterval(katimer); + if (isWritable(sock)) + katimer = setInterval(sendKA, kainterval); + } + } + this._resetKA = resetKA; + + const onDone = (() => { + let called = false; + return () => { + if (called) + return; + called = true; + if (wasConnected && !sawHeader) { + const err = + makeError('Connection lost before handshake', 'protocol', true); + this.emit('error', err); + } + }; + })(); + const onConnect = (() => { + let called = false; + return () => { + if (called) + return; + called = true; + + wasConnected = true; + debug && debug('Socket connected'); + this.emit('connect'); + + cryptoInit.then(() => { + proto.start(); + sock.on('data', (data) => { + try { + proto.parse(data, 0, data.length); + } catch (ex) { + this.emit('error', ex); + try { + if (isWritable(sock)) + sock.end(); + } catch {} + } + }); + + // Drain stderr if we are connection hopping using an exec stream + if (sock.stderr && typeof sock.stderr.resume === 'function') + sock.stderr.resume(); + + sock.resume(); + }).catch((err) => { + this.emit('error', err); + try { + if (isWritable(sock)) + sock.end(); + } catch {} + }); + }; + })(); + let wasConnected = false; + sock.on('connect', onConnect) + .on('timeout', () => { + this.emit('timeout'); + }).on('error', (err) => { + debug && debug(`Socket error: ${err.message}`); + clearTimeout(this._readyTimeout); + err.level = 'client-socket'; + this.emit('error', err); + }).on('end', () => { + debug && debug('Socket ended'); + onDone(); + proto.cleanup(); + clearTimeout(this._readyTimeout); + clearInterval(katimer); + this.emit('end'); + }).on('close', () => { + debug && debug('Socket closed'); + onDone(); + proto.cleanup(); + clearTimeout(this._readyTimeout); + clearInterval(katimer); + this.emit('close'); + + // Notify outstanding channel requests of disconnection ... + const callbacks_ = callbacks; + callbacks = this._callbacks = []; + const err = new Error('No response from server'); + for (let i = 0; i < callbacks_.length; ++i) + callbacks_[i](err); + + // Simulate error for any channels waiting to be opened + this._chanMgr.cleanup(err); + }); + + // Begin authentication handling =========================================== + let curAuth; + let curPartial = null; + let curAuthsLeft = null; + const authsAllowed = ['none']; + if (this.config.password !== undefined) + authsAllowed.push('password'); + if (privateKey !== undefined) + authsAllowed.push('publickey'); + if (this._agent !== undefined) + authsAllowed.push('agent'); + if (this.config.tryKeyboard) + authsAllowed.push('keyboard-interactive'); + if (privateKey !== undefined + && this.config.localHostname !== undefined + && this.config.localUsername !== undefined) { + authsAllowed.push('hostbased'); + } + + if (Array.isArray(authHandler)) + authHandler = makeSimpleAuthHandler(authHandler); + else if (typeof authHandler !== 'function') + authHandler = makeSimpleAuthHandler(authsAllowed); + + let hasSentAuth = false; + const doNextAuth = (nextAuth) => { + if (hasSentAuth) + return; + hasSentAuth = true; + + if (nextAuth === false) { + const err = new Error('All configured authentication methods failed'); + err.level = 'client-authentication'; + this.emit('error', err); + this.end(); + return; + } + + if (typeof nextAuth === 'string') { + // Remain backwards compatible with original `authHandler()` usage, + // which only supported passing names of next method to try using data + // from the `connect()` config object + + const type = nextAuth; + if (authsAllowed.indexOf(type) === -1) + return skipAuth(`Authentication method not allowed: ${type}`); + + const username = this.config.username; + switch (type) { + case 'password': + nextAuth = { type, username, password: this.config.password }; + break; + case 'publickey': + nextAuth = { type, username, key: privateKey }; + break; + case 'hostbased': + nextAuth = { + type, + username, + key: privateKey, + localHostname: this.config.localHostname, + localUsername: this.config.localUsername, + }; + break; + case 'agent': + nextAuth = { + type, + username, + agentCtx: new AgentContext(this._agent), + }; + break; + case 'keyboard-interactive': + nextAuth = { + type, + username, + prompt: (...args) => this.emit('keyboard-interactive', ...args), + }; + break; + case 'none': + nextAuth = { type, username }; + break; + default: + return skipAuth( + `Skipping unsupported authentication method: ${nextAuth}` + ); + } + } else if (typeof nextAuth !== 'object' || nextAuth === null) { + return skipAuth( + `Skipping invalid authentication attempt: ${nextAuth}` + ); + } else { + const username = nextAuth.username; + if (typeof username !== 'string') { + return skipAuth( + `Skipping invalid authentication attempt: ${nextAuth}` + ); + } + const type = nextAuth.type; + switch (type) { + case 'password': { + const { password } = nextAuth; + if (typeof password !== 'string' && !Buffer.isBuffer(password)) + return skipAuth('Skipping invalid password auth attempt'); + nextAuth = { type, username, password }; + break; + } + case 'publickey': { + const key = parseKey(nextAuth.key, nextAuth.passphrase); + if (key instanceof Error) + return skipAuth('Skipping invalid key auth attempt'); + if (!key.isPrivateKey()) + return skipAuth('Skipping non-private key'); + nextAuth = { type, username, key }; + break; + } + case 'hostbased': { + const { localHostname, localUsername } = nextAuth; + const key = parseKey(nextAuth.key, nextAuth.passphrase); + if (key instanceof Error + || typeof localHostname !== 'string' + || typeof localUsername !== 'string') { + return skipAuth('Skipping invalid hostbased auth attempt'); + } + if (!key.isPrivateKey()) + return skipAuth('Skipping non-private key'); + nextAuth = { type, username, key, localHostname, localUsername }; + break; + } + case 'agent': { + let agent = nextAuth.agent; + if (typeof agent === 'string' && agent.length) { + agent = createAgent(agent); + } else if (!isAgent(agent)) { + return skipAuth( + `Skipping invalid agent: ${nextAuth.agent}` + ); + } + nextAuth = { type, username, agentCtx: new AgentContext(agent) }; + break; + } + case 'keyboard-interactive': { + const { prompt } = nextAuth; + if (typeof prompt !== 'function') { + return skipAuth( + 'Skipping invalid keyboard-interactive auth attempt' + ); + } + nextAuth = { type, username, prompt }; + break; + } + case 'none': + nextAuth = { type, username }; + break; + default: + return skipAuth( + `Skipping unsupported authentication method: ${nextAuth}` + ); + } + } + curAuth = nextAuth; + + // Begin authentication method's process + try { + const username = curAuth.username; + switch (curAuth.type) { + case 'password': + proto.authPassword(username, curAuth.password); + break; + case 'publickey': { + let keyAlgo; + curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + keyAlgo = curAuth.keyAlgos[0][0]; + } else { + return skipAuth( + 'Skipping key authentication (no mutual hash algorithm)' + ); + } + } + proto.authPK(username, curAuth.key, keyAlgo); + break; + } + case 'hostbased': { + let keyAlgo; + let hashAlgo; + curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + } else { + return skipAuth( + 'Skipping hostbased authentication (no mutual hash algorithm)' + ); + } + } + + proto.authHostbased(username, + curAuth.key, + curAuth.localHostname, + curAuth.localUsername, + keyAlgo, + (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = + `Error while signing with key: ${signature.message}`; + signature.level = 'client-authentication'; + this.emit('error', signature); + return tryNextAuth(); + } + + cb(signature); + }); + break; + } + case 'agent': + curAuth.agentCtx.init((err) => { + if (err) { + err.level = 'agent'; + this.emit('error', err); + return tryNextAuth(); + } + tryNextAgentKey(); + }); + break; + case 'keyboard-interactive': + proto.authKeyboard(username); + break; + case 'none': + proto.authNone(username); + break; + } + } finally { + hasSentAuth = false; + } + }; + + function skipAuth(msg) { + debug && debug(msg); + process.nextTick(tryNextAuth); + } + + function tryNextAuth() { + hasSentAuth = false; + const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); + if (hasSentAuth || auth === undefined) + return; + doNextAuth(auth); + } + + const tryNextAgentKey = () => { + if (curAuth.type === 'agent') { + const key = curAuth.agentCtx.nextKey(); + if (key === false) { + debug && debug('Agent: No more keys left to try'); + debug && debug('Client: agent auth failed'); + tryNextAuth(); + } else { + const pos = curAuth.agentCtx.pos(); + let keyAlgo; + curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + keyAlgo = curAuth.keyAlgos[0][0]; + } else { + debug && debug( + `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` + ); + tryNextAgentKey(); + return; + } + } + debug && debug(`Agent: Trying key #${pos + 1}`); + proto.authPK(curAuth.username, key, keyAlgo); + } + } + }; + + const startTimeout = () => { + if (this.config.readyTimeout > 0) { + this._readyTimeout = setTimeout(() => { + const err = new Error('Timed out while waiting for handshake'); + err.level = 'client-timeout'; + this.emit('error', err); + sock.destroy(); + }, this.config.readyTimeout); + } + }; + + if (!cfg.sock) { + let host = this.config.host; + const forceIPv4 = this.config.forceIPv4; + const forceIPv6 = this.config.forceIPv6; + + debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); + + const doConnect = () => { + startTimeout(); + sock.connect({ + host, + port: this.config.port, + localAddress: this.config.localAddress, + localPort: this.config.localPort + }); + sock.setMaxListeners(0); + sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); + }; + + if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { + doConnect(); + } else { + dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { + if (err) { + const type = (forceIPv4 ? 'IPv4' : 'IPv6'); + const error = new Error( + `Error while looking up ${type} address for '${host}': ${err}` + ); + clearTimeout(this._readyTimeout); + error.level = 'client-dns'; + this.emit('error', error); + this.emit('close'); + return; + } + host = address; + doConnect(); + }); + } + } else { + // Custom socket passed in + startTimeout(); + if (typeof sock.connecting === 'boolean') { + // net.Socket + + if (!sock.connecting) { + // Already connected + onConnect(); + } + } else { + // Assume socket/stream is already "connected" + onConnect(); + } + } + + return this; + } + + end() { + if (this._sock && isWritable(this._sock)) { + this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); + this._sock.end(); + } + return this; + } + + destroy() { + this._sock && isWritable(this._sock) && this._sock.destroy(); + return this; + } + + exec(cmd, opts, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + + const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; + + openChannel(this, 'session', extraOpts, (err, chan) => { + if (err) { + cb(err); + return; + } + + const todo = []; + + function reqCb(err) { + if (err) { + chan.close(); + cb(err); + return; + } + if (todo.length) + todo.shift()(); + } + + if (this.config.allowAgentFwd === true + || (opts + && opts.agentForward === true + && this._agent !== undefined)) { + todo.push(() => reqAgentFwd(chan, reqCb)); + } + + if (typeof opts === 'object' && opts !== null) { + if (typeof opts.env === 'object' && opts.env !== null) + reqEnv(chan, opts.env); + if ((typeof opts.pty === 'object' && opts.pty !== null) + || opts.pty === true) { + todo.push(() => reqPty(chan, opts.pty, reqCb)); + } + if ((typeof opts.x11 === 'object' && opts.x11 !== null) + || opts.x11 === 'number' + || opts.x11 === true) { + todo.push(() => reqX11(chan, opts.x11, reqCb)); + } + } + + todo.push(() => reqExec(chan, cmd, opts, cb)); + todo.shift()(); + }); + + return this; + } + + shell(wndopts, opts, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + if (typeof wndopts === 'function') { + cb = wndopts; + wndopts = opts = undefined; + } else if (typeof opts === 'function') { + cb = opts; + opts = undefined; + } + if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { + opts = wndopts; + wndopts = undefined; + } + + openChannel(this, 'session', (err, chan) => { + if (err) { + cb(err); + return; + } + + const todo = []; + + function reqCb(err) { + if (err) { + chan.close(); + cb(err); + return; + } + if (todo.length) + todo.shift()(); + } + + if (this.config.allowAgentFwd === true + || (opts + && opts.agentForward === true + && this._agent !== undefined)) { + todo.push(() => reqAgentFwd(chan, reqCb)); + } + + if (wndopts !== false) + todo.push(() => reqPty(chan, wndopts, reqCb)); + + if (typeof opts === 'object' && opts !== null) { + if (typeof opts.env === 'object' && opts.env !== null) + reqEnv(chan, opts.env); + if ((typeof opts.x11 === 'object' && opts.x11 !== null) + || opts.x11 === 'number' + || opts.x11 === true) { + todo.push(() => reqX11(chan, opts.x11, reqCb)); + } + } + + todo.push(() => reqShell(chan, cb)); + todo.shift()(); + }); + + return this; + } + + subsys(name, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + openChannel(this, 'session', (err, chan) => { + if (err) { + cb(err); + return; + } + + reqSubsystem(chan, name, (err, stream) => { + if (err) { + cb(err); + return; + } + + cb(undefined, stream); + }); + }); + + return this; + } + + forwardIn(bindAddr, bindPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + // Send a request for the server to start forwarding TCP connections to us + // on a particular address and port + + const wantReply = (typeof cb === 'function'); + + if (wantReply) { + this._callbacks.push((had_err, data) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); + return; + } + + let realPort = bindPort; + if (bindPort === 0 && data && data.length >= 4) { + realPort = readUInt32BE(data, 0); + if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) + bindPort = realPort; + } + + this._forwarding[`${bindAddr}:${bindPort}`] = realPort; + + cb(undefined, realPort); + }); + } + + this._protocol.tcpipForward(bindAddr, bindPort, wantReply); + + return this; + } + + unforwardIn(bindAddr, bindPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + // Send a request to stop forwarding us new connections for a particular + // address and port + + const wantReply = (typeof cb === 'function'); + + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); + return; + } + + delete this._forwarding[`${bindAddr}:${bindPort}`]; + + cb(); + }); + } + + this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); + + return this; + } + + forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + // Send a request to forward a TCP connection to the server + + const cfg = { + srcIP: srcIP, + srcPort: srcPort, + dstIP: dstIP, + dstPort: dstPort + }; + + if (typeof cb !== 'function') + cb = noop; + + openChannel(this, 'direct-tcpip', cfg, cb); + + return this; + } + + openssh_noMoreSessions(cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + const wantReply = (typeof cb === 'function'); + + if (!this.config.strictVendor + || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error('Unable to disable future sessions')); + return; + } + + cb(); + }); + } + + this._protocol.openssh_noMoreSessions(wantReply); + return this; + } + + if (!wantReply) + return this; + + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); + + return this; + } + + openssh_forwardInStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + const wantReply = (typeof cb === 'function'); + + if (!this.config.strictVendor + || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to bind to ${socketPath}`)); + return; + } + this._forwardingUnix[socketPath] = true; + cb(); + }); + } + + this._protocol.openssh_streamLocalForward(socketPath, wantReply); + return this; + } + + if (!wantReply) + return this; + + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); + + return this; + } + + openssh_unforwardInStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + const wantReply = (typeof cb === 'function'); + + if (!this.config.strictVendor + || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to unbind from ${socketPath}`)); + return; + } + delete this._forwardingUnix[socketPath]; + cb(); + }); + } + + this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); + return this; + } + + if (!wantReply) + return this; + + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); + + return this; + } + + openssh_forwardOutStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + if (typeof cb !== 'function') + cb = noop; + + if (!this.config.strictVendor + || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { + openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); + return this; + } + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); + + return this; + } + + sftp(cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + openChannel(this, 'sftp', (err, sftp) => { + if (err) { + cb(err); + return; + } + + reqSubsystem(sftp, 'sftp', (err, sftp_) => { + if (err) { + cb(err); + return; + } + + function removeListeners() { + sftp.removeListener('ready', onReady); + sftp.removeListener('error', onError); + sftp.removeListener('exit', onExit); + sftp.removeListener('close', onExit); + } + + function onReady() { + // TODO: do not remove exit/close in case remote end closes the + // channel abruptly and we need to notify outstanding callbacks + removeListeners(); + cb(undefined, sftp); + } + + function onError(err) { + removeListeners(); + cb(err); + } + + function onExit(code, signal) { + removeListeners(); + let msg; + if (typeof code === 'number') + msg = `Received exit code ${code} while establishing SFTP session`; + else if (signal !== undefined) + msg = `Received signal ${signal} while establishing SFTP session`; + else + msg = 'Received unexpected SFTP session termination'; + const err = new Error(msg); + err.code = code; + err.signal = signal; + cb(err); + } + + sftp.on('ready', onReady) + .on('error', onError) + .on('exit', onExit) + .on('close', onExit); + + sftp._init(); + }); + }); + + return this; + } + + setNoDelay(noDelay) { + if (this._sock && typeof this._sock.setNoDelay === 'function') + this._sock.setNoDelay(noDelay); + + return this; + } +} + +function openChannel(self, type, opts, cb) { + // Ask the server to open a channel for some purpose + // (e.g. session (sftp, exec, shell), or forwarding a TCP connection + const initWindow = MAX_WINDOW; + const maxPacket = PACKET_SIZE; + + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + + const wrapper = (err, stream) => { + cb(err, stream); + }; + wrapper.type = type; + + const localChan = self._chanMgr.add(wrapper); + + if (localChan === -1) { + cb(new Error('No free channels available')); + return; + } + + switch (type) { + case 'session': + case 'sftp': + self._protocol.session(localChan, initWindow, maxPacket); + break; + case 'direct-tcpip': + self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); + break; + case 'direct-streamlocal@openssh.com': + self._protocol.openssh_directStreamLocal( + localChan, initWindow, maxPacket, opts + ); + break; + default: + throw new Error(`Unsupported channel type: ${type}`); + } +} + +function reqX11(chan, screen, cb) { + // Asks server to start sending us X11 connections + const cfg = { + single: false, + protocol: 'MIT-MAGIC-COOKIE-1', + cookie: undefined, + screen: 0 + }; + + if (typeof screen === 'function') { + cb = screen; + } else if (typeof screen === 'object' && screen !== null) { + if (typeof screen.single === 'boolean') + cfg.single = screen.single; + if (typeof screen.screen === 'number') + cfg.screen = screen.screen; + if (typeof screen.protocol === 'string') + cfg.protocol = screen.protocol; + if (typeof screen.cookie === 'string') + cfg.cookie = screen.cookie; + else if (Buffer.isBuffer(screen.cookie)) + cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); + } + if (cfg.cookie === undefined) + cfg.cookie = randomCookie(); + + const wantReply = (typeof cb === 'function'); + + if (chan.outgoing.state !== 'open') { + if (wantReply) + cb(new Error('Channel is not open')); + return; + } + + if (wantReply) { + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error('Unable to request X11')); + return; + } + + chan._hasX11 = true; + ++chan._client._acceptX11; + chan.once('close', () => { + if (chan._client._acceptX11) + --chan._client._acceptX11; + }); + + cb(); + }); + } + + chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); +} + +function reqPty(chan, opts, cb) { + let rows = 24; + let cols = 80; + let width = 640; + let height = 480; + let term = 'vt100'; + let modes = null; + + if (typeof opts === 'function') { + cb = opts; + } else if (typeof opts === 'object' && opts !== null) { + if (typeof opts.rows === 'number') + rows = opts.rows; + if (typeof opts.cols === 'number') + cols = opts.cols; + if (typeof opts.width === 'number') + width = opts.width; + if (typeof opts.height === 'number') + height = opts.height; + if (typeof opts.term === 'string') + term = opts.term; + if (typeof opts.modes === 'object') + modes = opts.modes; + } + + const wantReply = (typeof cb === 'function'); + + if (chan.outgoing.state !== 'open') { + if (wantReply) + cb(new Error('Channel is not open')); + return; + } + + if (wantReply) { + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error('Unable to request a pseudo-terminal')); + return; + } + cb(); + }); + } + + chan._client._protocol.pty(chan.outgoing.id, + rows, + cols, + height, + width, + term, + modes, + wantReply); +} + +function reqAgentFwd(chan, cb) { + const wantReply = (typeof cb === 'function'); + + if (chan.outgoing.state !== 'open') { + wantReply && cb(new Error('Channel is not open')); + return; + } + if (chan._client._agentFwdEnabled) { + wantReply && cb(false); + return; + } + + chan._client._agentFwdEnabled = true; + + chan._callbacks.push((had_err) => { + if (had_err) { + chan._client._agentFwdEnabled = false; + if (wantReply) { + cb(had_err !== true + ? had_err + : new Error('Unable to request agent forwarding')); + } + return; + } + + if (wantReply) + cb(); + }); + + chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); +} + +function reqShell(chan, cb) { + if (chan.outgoing.state !== 'open') { + cb(new Error('Channel is not open')); + return; + } + + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error('Unable to open shell')); + return; + } + chan.subtype = 'shell'; + cb(undefined, chan); + }); + + chan._client._protocol.shell(chan.outgoing.id, true); +} + +function reqExec(chan, cmd, opts, cb) { + if (chan.outgoing.state !== 'open') { + cb(new Error('Channel is not open')); + return; + } + + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error('Unable to exec')); + return; + } + chan.subtype = 'exec'; + chan.allowHalfOpen = (opts.allowHalfOpen !== false); + cb(undefined, chan); + }); + + chan._client._protocol.exec(chan.outgoing.id, cmd, true); +} + +function reqEnv(chan, env) { + if (chan.outgoing.state !== 'open') + return; + + const keys = Object.keys(env || {}); + + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + const val = env[key]; + chan._client._protocol.env(chan.outgoing.id, key, val, false); + } +} + +function reqSubsystem(chan, name, cb) { + if (chan.outgoing.state !== 'open') { + cb(new Error('Channel is not open')); + return; + } + + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to start subsystem: ${name}`)); + return; + } + chan.subtype = 'subsystem'; + cb(undefined, chan); + }); + + chan._client._protocol.subsystem(chan.outgoing.id, name, true); +} + +// TODO: inline implementation into single call site +function onCHANNEL_OPEN(self, info) { + // The server is trying to open a channel with us, this is usually when + // we asked the server to forward us connections on some port and now they + // are asking us to accept/deny an incoming connection on their side + + let localChan = -1; + let reason; + + const accept = () => { + const chanInfo = { + type: info.type, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; + const stream = new Channel(self, chanInfo); + self._chanMgr.update(localChan, stream); + + self._protocol.channelOpenConfirm(info.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE); + return stream; + }; + const reject = () => { + if (reason === undefined) { + if (localChan === -1) + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + else + reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; + } + + if (localChan !== -1) + self._chanMgr.remove(localChan); + + self._protocol.channelOpenFail(info.sender, reason, ''); + }; + const reserveChannel = () => { + localChan = self._chanMgr.add(); + + if (localChan === -1) { + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + if (self.config.debug) { + self.config.debug( + 'Client: Automatic rejection of incoming channel open: ' + + 'no channels available' + ); + } + } + + return (localChan !== -1); + }; + + const data = info.data; + switch (info.type) { + case 'forwarded-tcpip': { + const val = self._forwarding[`${data.destIP}:${data.destPort}`]; + if (val !== undefined && reserveChannel()) { + if (data.destPort === 0) + data.destPort = val; + self.emit('tcp connection', data, accept, reject); + return; + } + break; + } + case 'forwarded-streamlocal@openssh.com': + if (self._forwardingUnix[data.socketPath] !== undefined + && reserveChannel()) { + self.emit('unix connection', data, accept, reject); + return; + } + break; + case 'auth-agent@openssh.com': + if (self._agentFwdEnabled + && typeof self._agent.getStream === 'function' + && reserveChannel()) { + self._agent.getStream((err, stream) => { + if (err) + return reject(); + + const upstream = accept(); + upstream.pipe(stream).pipe(upstream); + }); + return; + } + break; + case 'x11': + if (self._acceptX11 !== 0 && reserveChannel()) { + self.emit('x11', data, accept, reject); + return; + } + break; + default: + // Automatically reject any unsupported channel open requests + reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; + if (self.config.debug) { + self.config.debug( + 'Client: Automatic rejection of unsupported incoming channel open ' + + `type: ${info.type}` + ); + } + } + + if (reason === undefined) { + reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + if (self.config.debug) { + self.config.debug( + 'Client: Automatic rejection of unexpected incoming channel open for: ' + + info.type + ); + } + } + + reject(); +} + +const randomCookie = (() => { + const buffer = Buffer.allocUnsafe(16); + return () => { + randomFillSync(buffer, 0, 16); + return buffer.hexSlice(0, 16); + }; +})(); + +function makeSimpleAuthHandler(authList) { + if (!Array.isArray(authList)) + throw new Error('authList must be an array'); + + let a = 0; + return (authsLeft, partialSuccess, cb) => { + if (a === authList.length) + return false; + return authList[a++]; + }; +} + +function hostKeysProve(client, keys_, cb) { + if (!client._sock || !isWritable(client._sock)) + return; + + if (typeof cb !== 'function') + cb = noop; + + if (!Array.isArray(keys_)) + throw new TypeError('Invalid keys argument type'); + + const keys = []; + for (const key of keys_) { + const parsed = parseKey(key); + if (parsed instanceof Error) + throw parsed; + keys.push(parsed); + } + + if (!client.config.strictVendor + || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { + client._callbacks.push((had_err, data) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error('Server failed to prove supplied keys')); + return; + } + + // TODO: move all of this parsing/verifying logic out of the client? + const ret = []; + let keyIdx = 0; + bufferParser.init(data, 0); + while (bufferParser.avail()) { + if (keyIdx === keys.length) + break; + const key = keys[keyIdx++]; + const keyPublic = key.getPublicSSH(); + + const sigEntry = bufferParser.readString(); + sigParser.init(sigEntry, 0); + const type = sigParser.readString(true); + let value = sigParser.readString(); + + let algo; + if (type !== key.type) { + if (key.type === 'ssh-rsa') { + switch (type) { + case 'rsa-sha2-256': + algo = 'sha256'; + break; + case 'rsa-sha2-512': + algo = 'sha512'; + break; + default: + continue; + } + } else { + continue; + } + } + + const sessionID = client._protocol._kex.sessionID; + const verifyData = Buffer.allocUnsafe( + 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length + ); + let p = 0; + writeUInt32BE(verifyData, 29, p); + verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); + writeUInt32BE(verifyData, sessionID.length, p += 29); + bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); + writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); + bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); + + if (!(value = sigSSHToASN1(value, type))) + continue; + if (key.verify(verifyData, value, algo) === true) + ret.push(key); + } + sigParser.clear(); + bufferParser.clear(); + + cb(null, ret); + }); + + client._protocol.openssh_hostKeysProve(keys); + return; + } + + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); +} + +function getKeyAlgos(client, key, serverSigAlgs) { + switch (key.type) { + case 'ssh-rsa': + if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) { + if (!Array.isArray(serverSigAlgs)) + serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512']; + else + serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512', ...serverSigAlgs]; + } + if (Array.isArray(serverSigAlgs)) { + if (serverSigAlgs.indexOf('rsa-sha2-256') !== -1) + return [['rsa-sha2-256', 'sha256']]; + if (serverSigAlgs.indexOf('rsa-sha2-512') !== -1) + return [['rsa-sha2-512', 'sha512']]; + if (serverSigAlgs.indexOf('ssh-rsa') === -1) + return []; + } + return [['ssh-rsa', 'sha1']]; + } +} + +module.exports = Client; + + +/***/ }), + +/***/ 2994: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const { Agent: HttpAgent } = __nccwpck_require__(3685); +const { Agent: HttpsAgent } = __nccwpck_require__(5687); +const { connect: tlsConnect } = __nccwpck_require__(4404); + +let Client; + +for (const ctor of [HttpAgent, HttpsAgent]) { + class SSHAgent extends ctor { + constructor(connectCfg, agentOptions) { + super(agentOptions); + + this._connectCfg = connectCfg; + this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; + } + + createConnection(options, cb) { + const srcIP = (options && options.localAddress) || this._defaultSrcIP; + const srcPort = (options && options.localPort) || 0; + const dstIP = options.host; + const dstPort = options.port; + + if (Client === undefined) + Client = __nccwpck_require__(6063); + + const client = new Client(); + let triedForward = false; + client.on('ready', () => { + client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { + triedForward = true; + if (err) { + client.end(); + return cb(err); + } + stream.once('close', () => client.end()); + cb(null, decorateStream(stream, ctor, options)); + }); + }).on('error', cb).on('close', () => { + if (!triedForward) + cb(new Error('Unexpected connection close')); + }).connect(this._connectCfg); + } + } + + exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; +} + +function noop() {} + +function decorateStream(stream, ctor, options) { + if (ctor === HttpAgent) { + // HTTP + stream.setKeepAlive = noop; + stream.setNoDelay = noop; + stream.setTimeout = noop; + stream.ref = noop; + stream.unref = noop; + stream.destroySoon = stream.destroy; + return stream; + } + + // HTTPS + options.socket = stream; + const wrapped = tlsConnect(options); + + // This is a workaround for a regression in node v12.16.3+ + // https://github.com/nodejs/node/issues/35904 + const onClose = (() => { + let called = false; + return () => { + if (called) + return; + called = true; + if (stream.isPaused()) + stream.resume(); + }; + })(); + // 'end' listener is needed because 'close' is not emitted in some scenarios + // in node v12.x for some unknown reason + wrapped.on('end', onClose).on('close', onClose); + + return wrapped; +} + + +/***/ }), + +/***/ 5869: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + AgentProtocol, + BaseAgent, + createAgent, + CygwinAgent, + OpenSSHAgent, + PageantAgent, +} = __nccwpck_require__(6119); +const { + SSHTTPAgent: HTTPAgent, + SSHTTPSAgent: HTTPSAgent, +} = __nccwpck_require__(2994); +const { parseKey } = __nccwpck_require__(2218); +const { + flagsToString, + OPEN_MODE, + STATUS_CODE, + stringToFlags, +} = __nccwpck_require__(2026); + +module.exports = { + AgentProtocol, + BaseAgent, + createAgent, + Client: __nccwpck_require__(6063), + CygwinAgent, + HTTPAgent, + HTTPSAgent, + OpenSSHAgent, + PageantAgent, + Server: __nccwpck_require__(2986), + utils: { + parseKey, + ...__nccwpck_require__(3823), + sftp: { + flagsToString, + OPEN_MODE, + STATUS_CODE, + stringToFlags, + }, + }, +}; + + +/***/ }), + +/***/ 3823: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + createCipheriv, + generateKeyPair: generateKeyPair_, + generateKeyPairSync: generateKeyPairSync_, + getCurves, + randomBytes, +} = __nccwpck_require__(6113); + +const { Ber } = __nccwpck_require__(970); +const bcrypt_pbkdf = (__nccwpck_require__(5447).pbkdf); + +const { CIPHER_INFO } = __nccwpck_require__(5708); + +const SALT_LEN = 16; +const DEFAULT_ROUNDS = 16; + +const curves = getCurves(); +const ciphers = new Map(Object.entries(CIPHER_INFO)); + +function makeArgs(type, opts) { + if (typeof type !== 'string') + throw new TypeError('Key type must be a string'); + + const publicKeyEncoding = { type: 'spki', format: 'der' }; + const privateKeyEncoding = { type: 'pkcs8', format: 'der' }; + + switch (type.toLowerCase()) { + case 'rsa': { + if (typeof opts !== 'object' || opts === null) + throw new TypeError('Missing options object for RSA key'); + const modulusLength = opts.bits; + if (!Number.isInteger(modulusLength)) + throw new TypeError('RSA bits must be an integer'); + if (modulusLength <= 0 || modulusLength > 16384) + throw new RangeError('RSA bits must be non-zero and <= 16384'); + return ['rsa', { modulusLength, publicKeyEncoding, privateKeyEncoding }]; + } + case 'ecdsa': { + if (typeof opts !== 'object' || opts === null) + throw new TypeError('Missing options object for ECDSA key'); + if (!Number.isInteger(opts.bits)) + throw new TypeError('ECDSA bits must be an integer'); + let namedCurve; + switch (opts.bits) { + case 256: + namedCurve = 'prime256v1'; + break; + case 384: + namedCurve = 'secp384r1'; + break; + case 521: + namedCurve = 'secp521r1'; + break; + default: + throw new Error('ECDSA bits must be 256, 384, or 521'); + } + if (!curves.includes(namedCurve)) + throw new Error('Unsupported ECDSA bits value'); + return ['ec', { namedCurve, publicKeyEncoding, privateKeyEncoding }]; + } + case 'ed25519': + return ['ed25519', { publicKeyEncoding, privateKeyEncoding }]; + default: + throw new Error(`Unsupported key type: ${type}`); + } +} + +function parseDERs(keyType, pub, priv) { + switch (keyType) { + case 'rsa': { + // Note: we don't need to parse the public key since the PKCS8 private key + // already includes the public key parameters + + // Parse private key + let reader = new Ber.Reader(priv); + reader.readSequence(); + + // - Version + if (reader.readInt() !== 0) + throw new Error('Unsupported version in RSA private key'); + + // - Algorithm + reader.readSequence(); + if (reader.readOID() !== '1.2.840.113549.1.1.1') + throw new Error('Bad RSA private OID'); + // - Algorithm parameters (RSA has none) + if (reader.readByte() !== Ber.Null) + throw new Error('Malformed RSA private key (expected null)'); + if (reader.readByte() !== 0x00) { + throw new Error( + 'Malformed RSA private key (expected zero-length null)' + ); + } + + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + reader.readSequence(); + if (reader.readInt() !== 0) + throw new Error('Unsupported version in RSA private key'); + const n = reader.readString(Ber.Integer, true); + const e = reader.readString(Ber.Integer, true); + const d = reader.readString(Ber.Integer, true); + const p = reader.readString(Ber.Integer, true); + const q = reader.readString(Ber.Integer, true); + reader.readString(Ber.Integer, true); // dmp1 + reader.readString(Ber.Integer, true); // dmq1 + const iqmp = reader.readString(Ber.Integer, true); + + /* + OpenSSH RSA private key: + string "ssh-rsa" + string n -- public + string e -- public + string d -- private + string iqmp -- private + string p -- private + string q -- private + */ + const keyName = Buffer.from('ssh-rsa'); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + n.length + + 4 + e.length + + 4 + d.length + + 4 + iqmp.length + + 4 + p.length + + 4 + q.length + ); + let pos = 0; + + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(n.length, pos += keyName.length); + privBuf.set(n, pos += 4); + privBuf.writeUInt32BE(e.length, pos += n.length); + privBuf.set(e, pos += 4); + privBuf.writeUInt32BE(d.length, pos += e.length); + privBuf.set(d, pos += 4); + privBuf.writeUInt32BE(iqmp.length, pos += d.length); + privBuf.set(iqmp, pos += 4); + privBuf.writeUInt32BE(p.length, pos += iqmp.length); + privBuf.set(p, pos += 4); + privBuf.writeUInt32BE(q.length, pos += p.length); + privBuf.set(q, pos += 4); + + /* + OpenSSH RSA public key: + string "ssh-rsa" + string e -- public + string n -- public + */ + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + e.length + + 4 + n.length + ); + pos = 0; + + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(e.length, pos += keyName.length); + pubBuf.set(e, pos += 4); + pubBuf.writeUInt32BE(n.length, pos += e.length); + pubBuf.set(n, pos += 4); + + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; + } + case 'ec': { + // Parse public key + let reader = new Ber.Reader(pub); + reader.readSequence(); + + reader.readSequence(); + if (reader.readOID() !== '1.2.840.10045.2.1') + throw new Error('Bad ECDSA public OID'); + // Skip curve OID, we'll get it from the private key + reader.readOID(); + let pubBin = reader.readString(Ber.BitString, true); + { + // Remove leading zero bytes + let i = 0; + for (; i < pubBin.length && pubBin[i] === 0x00; ++i); + if (i > 0) + pubBin = pubBin.slice(i); + } + + // Parse private key + reader = new Ber.Reader(priv); + reader.readSequence(); + + // - Version + if (reader.readInt() !== 0) + throw new Error('Unsupported version in ECDSA private key'); + + reader.readSequence(); + if (reader.readOID() !== '1.2.840.10045.2.1') + throw new Error('Bad ECDSA private OID'); + const curveOID = reader.readOID(); + let sshCurveName; + switch (curveOID) { + case '1.2.840.10045.3.1.7': + // prime256v1/secp256r1 + sshCurveName = 'nistp256'; + break; + case '1.3.132.0.34': + // secp384r1 + sshCurveName = 'nistp384'; + break; + case '1.3.132.0.35': + // secp521r1 + sshCurveName = 'nistp521'; + break; + default: + throw new Error('Unsupported curve in ECDSA private key'); + } + + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + reader.readSequence(); + + // - Version + if (reader.readInt() !== 1) + throw new Error('Unsupported version in ECDSA private key'); + + // Add leading zero byte to prevent negative bignum in private key + const privBin = Buffer.concat([ + Buffer.from([0x00]), + reader.readString(Ber.OctetString, true) + ]); + + /* + OpenSSH ECDSA private key: + string "ecdsa-sha2-" + string curve name + string Q -- public + string d -- private + */ + const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`); + sshCurveName = Buffer.from(sshCurveName); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + sshCurveName.length + + 4 + pubBin.length + + 4 + privBin.length + ); + let pos = 0; + + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); + privBuf.set(sshCurveName, pos += 4); + privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); + privBuf.set(pubBin, pos += 4); + privBuf.writeUInt32BE(privBin.length, pos += pubBin.length); + privBuf.set(privBin, pos += 4); + + /* + OpenSSH ECDSA public key: + string "ecdsa-sha2-" + string curve name + string Q -- public + */ + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + sshCurveName.length + + 4 + pubBin.length + ); + pos = 0; + + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); + pubBuf.set(sshCurveName, pos += 4); + pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); + pubBuf.set(pubBin, pos += 4); + + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; + } + case 'ed25519': { + // Parse public key + let reader = new Ber.Reader(pub); + reader.readSequence(); + + // - Algorithm + reader.readSequence(); + if (reader.readOID() !== '1.3.101.112') + throw new Error('Bad ED25519 public OID'); + // - Attributes (absent for ED25519) + + let pubBin = reader.readString(Ber.BitString, true); + { + // Remove leading zero bytes + let i = 0; + for (; i < pubBin.length && pubBin[i] === 0x00; ++i); + if (i > 0) + pubBin = pubBin.slice(i); + } + + // Parse private key + reader = new Ber.Reader(priv); + reader.readSequence(); + + // - Version + if (reader.readInt() !== 0) + throw new Error('Unsupported version in ED25519 private key'); + + // - Algorithm + reader.readSequence(); + if (reader.readOID() !== '1.3.101.112') + throw new Error('Bad ED25519 private OID'); + // - Attributes (absent) + + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + const privBin = reader.readString(Ber.OctetString, true); + + /* + OpenSSH ed25519 private key: + string "ssh-ed25519" + string public key + string private key + public key + */ + const keyName = Buffer.from('ssh-ed25519'); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + pubBin.length + + 4 + (privBin.length + pubBin.length) + ); + let pos = 0; + + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(pubBin.length, pos += keyName.length); + privBuf.set(pubBin, pos += 4); + privBuf.writeUInt32BE( + privBin.length + pubBin.length, + pos += pubBin.length + ); + privBuf.set(privBin, pos += 4); + privBuf.set(pubBin, pos += privBin.length); + + /* + OpenSSH ed25519 public key: + string "ssh-ed25519" + string public key + */ + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + pubBin.length + ); + pos = 0; + + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length); + pubBuf.set(pubBin, pos += 4); + + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; + } + } +} + +function convertKeys(keyType, pub, priv, opts) { + let format = 'new'; + let encrypted; + let comment = ''; + if (typeof opts === 'object' && opts !== null) { + if (typeof opts.comment === 'string' && opts.comment) + comment = opts.comment; + if (typeof opts.format === 'string' && opts.format) + format = opts.format; + if (opts.passphrase) { + let passphrase; + if (typeof opts.passphrase === 'string') + passphrase = Buffer.from(opts.passphrase); + else if (Buffer.isBuffer(opts.passphrase)) + passphrase = opts.passphrase; + else + throw new Error('Invalid passphrase'); + + if (opts.cipher === undefined) + throw new Error('Missing cipher name'); + const cipher = ciphers.get(opts.cipher); + if (cipher === undefined) + throw new Error('Invalid cipher name'); + + if (format === 'new') { + let rounds = DEFAULT_ROUNDS; + if (opts.rounds !== undefined) { + if (!Number.isInteger(opts.rounds)) + throw new TypeError('rounds must be an integer'); + if (opts.rounds > 0) + rounds = opts.rounds; + } + + const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen); + const salt = randomBytes(SALT_LEN); + const r = bcrypt_pbkdf( + passphrase, + passphrase.length, + salt, + salt.length, + gen, + gen.length, + rounds + ); + if (r !== 0) + return new Error('Failed to generate information to encrypt key'); + + /* + string salt + uint32 rounds + */ + const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4); + { + let pos = 0; + kdfOptions.writeUInt32BE(salt.length, pos += 0); + kdfOptions.set(salt, pos += 4); + kdfOptions.writeUInt32BE(rounds, pos += salt.length); + } + + encrypted = { + cipher, + cipherName: opts.cipher, + kdfName: 'bcrypt', + kdfOptions, + key: gen.slice(0, cipher.keyLen), + iv: gen.slice(cipher.keyLen), + }; + } + } + } + + switch (format) { + case 'new': { + let privateB64 = '-----BEGIN OPENSSH PRIVATE KEY-----\n'; + let publicB64; + /* + byte[] "openssh-key-v1\0" + string ciphername + string kdfname + string kdfoptions + uint32 number of keys N + string publickey1 + string encrypted, padded list of private keys + uint32 checkint + uint32 checkint + byte[] privatekey1 + string comment1 + byte 1 + byte 2 + byte 3 + ... + byte padlen % 255 + */ + const cipherName = Buffer.from(encrypted ? encrypted.cipherName : 'none'); + const kdfName = Buffer.from(encrypted ? encrypted.kdfName : 'none'); + const kdfOptions = (encrypted ? encrypted.kdfOptions : Buffer.alloc(0)); + const blockLen = (encrypted ? encrypted.cipher.blockLen : 8); + + const parsed = parseDERs(keyType, pub, priv); + + const checkInt = randomBytes(4); + const commentBin = Buffer.from(comment); + const privBlobLen = (4 + 4 + parsed.priv.length + 4 + commentBin.length); + let padding = []; + for (let i = 1; ((privBlobLen + padding.length) % blockLen); ++i) + padding.push(i & 0xFF); + padding = Buffer.from(padding); + + let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length); + let extra; + { + let pos = 0; + privBlob.set(checkInt, pos += 0); + privBlob.set(checkInt, pos += 4); + privBlob.set(parsed.priv, pos += 4); + privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length); + privBlob.set(commentBin, pos += 4); + privBlob.set(padding, pos += commentBin.length); + } + + if (encrypted) { + const options = { authTagLength: encrypted.cipher.authLen }; + const cipher = createCipheriv( + encrypted.cipher.sslName, + encrypted.key, + encrypted.iv, + options + ); + cipher.setAutoPadding(false); + privBlob = Buffer.concat([ cipher.update(privBlob), cipher.final() ]); + if (encrypted.cipher.authLen > 0) + extra = cipher.getAuthTag(); + else + extra = Buffer.alloc(0); + encrypted.key.fill(0); + encrypted.iv.fill(0); + } else { + extra = Buffer.alloc(0); + } + + const magicBytes = Buffer.from('openssh-key-v1\0'); + const privBin = Buffer.allocUnsafe( + magicBytes.length + + 4 + cipherName.length + + 4 + kdfName.length + + 4 + kdfOptions.length + + 4 + + 4 + parsed.pub.length + + 4 + privBlob.length + + extra.length + ); + { + let pos = 0; + privBin.set(magicBytes, pos += 0); + privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length); + privBin.set(cipherName, pos += 4); + privBin.writeUInt32BE(kdfName.length, pos += cipherName.length); + privBin.set(kdfName, pos += 4); + privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length); + privBin.set(kdfOptions, pos += 4); + privBin.writeUInt32BE(1, pos += kdfOptions.length); + privBin.writeUInt32BE(parsed.pub.length, pos += 4); + privBin.set(parsed.pub, pos += 4); + privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length); + privBin.set(privBlob, pos += 4); + privBin.set(extra, pos += privBlob.length); + } + + { + const b64 = privBin.base64Slice(0, privBin.length); + let formatted = b64.replace(/.{64}/g, '$&\n'); + if (b64.length & 63) + formatted += '\n'; + privateB64 += formatted; + } + + { + const b64 = parsed.pub.base64Slice(0, parsed.pub.length); + publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ''}`; + } + + privateB64 += '-----END OPENSSH PRIVATE KEY-----\n'; + return { + private: privateB64, + public: publicB64, + }; + } + default: + throw new Error('Invalid output key format'); + } +} + +function noop() {} + +module.exports = { + generateKeyPair: (keyType, opts, cb) => { + if (typeof opts === 'function') { + cb = opts; + opts = undefined; + } + if (typeof cb !== 'function') + cb = noop; + const args = makeArgs(keyType, opts); + generateKeyPair_(...args, (err, pub, priv) => { + if (err) + return cb(err); + let ret; + try { + ret = convertKeys(args[0], pub, priv, opts); + } catch (ex) { + return cb(ex); + } + cb(null, ret); + }); + }, + generateKeyPairSync: (keyType, opts) => { + const args = makeArgs(keyType, opts); + const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args); + return convertKeys(args[0], pub, priv, opts); + } +}; + + +/***/ }), + +/***/ 9031: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* + TODO: + * Replace `buffer._pos` usage in keyParser.js and elsewhere + * Utilize optional "writev" support when writing packets from + cipher.encrypt() + * Built-in support for automatic re-keying, on by default + * Revisit receiving unexpected/unknown packets + * Error (fatal or otherwise) or ignore or pass on to user (in some or all + cases)? + * Including server/client check for single directional packet types? + * Check packets for validity or bail as early as possible? + * Automatic re-key every 2**31 packets after the last key exchange (sent or + received), as suggested by RFC4344. OpenSSH currently does this. + * Automatic re-key every so many blocks depending on cipher. RFC4344: + Because of a birthday property of block ciphers and some modes of + operation, implementations must be careful not to encrypt too many + blocks with the same encryption key. + + Let L be the block length (in bits) of an SSH encryption method's + block cipher (e.g., 128 for AES). If L is at least 128, then, after + rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) + blocks before rekeying again. If L is at least 128, then SSH + implementations should also attempt to force a rekey before receiving + more than 2**(L/4) blocks. If L is less than 128 (which is the case + for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, + although it may be too expensive to rekey every 2**(L/4) blocks, it + is still advisable for SSH implementations to follow the original + recommendation in [RFC4253]: rekey at least once for every gigabyte + of transmitted data. + + Note that if L is less than or equal to 128, then the recommendation + in this subsection supersedes the recommendation in Section 3.1. If + an SSH implementation uses a block cipher with a larger block size + (e.g., Rijndael with 256-bit blocks), then the recommendations in + Section 3.1 may supersede the recommendations in this subsection + (depending on the lengths of the packets). +*/ + + + +const { inspect } = __nccwpck_require__(3837); + +const { bindingAvailable, NullCipher, NullDecipher } = __nccwpck_require__(5708); +const { + COMPAT_CHECKS, + DISCONNECT_REASON, + eddsaSupported, + MESSAGE, + SIGNALS, + TERMINAL_MODE, +} = __nccwpck_require__(6832); +const { + DEFAULT_KEXINIT_CLIENT, + DEFAULT_KEXINIT_SERVER, + KexInit, + kexinit, + onKEXPayload, +} = __nccwpck_require__(4126); +const { + parseKey, +} = __nccwpck_require__(2218); +const MESSAGE_HANDLERS = __nccwpck_require__(172); +const { + bufferCopy, + bufferFill, + bufferSlice, + convertSignature, + sendPacket, + writeUInt32BE, +} = __nccwpck_require__(9475); +const { + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter, +} = __nccwpck_require__(6715); + +const MODULE_VER = (__nccwpck_require__(6674)/* .version */ .i8); + +const VALID_DISCONNECT_REASONS = new Map( + Object.values(DISCONNECT_REASON).map((n) => [n, 1]) +); +const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); +const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); +const MAX_LINE_LEN = 8192; +const MAX_LINES = 1024; +const PING_PAYLOAD = Buffer.from([ + MESSAGE.GLOBAL_REQUEST, + // "keepalive@openssh.com" + 0, 0, 0, 21, + 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, + 115, 104, 46, 99, 111, 109, + // Request a reply + 1, +]); +const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); + +function noop() {} + +/* + Inbound: + * kexinit payload (needed only until exchange hash is generated) + * raw ident + * rekey packet queue + * expected packet (implemented as separate _parse() function?) + Outbound: + * kexinit payload (needed only until exchange hash is generated) + * rekey packet queue + * kex secret (needed only until NEWKEYS) + * exchange hash (needed only until NEWKEYS) + * session ID (set to exchange hash from initial handshake) +*/ +class Protocol { + constructor(config) { + const onWrite = config.onWrite; + if (typeof onWrite !== 'function') + throw new Error('Missing onWrite function'); + this._onWrite = (data) => { onWrite(data); }; + + const onError = config.onError; + if (typeof onError !== 'function') + throw new Error('Missing onError function'); + this._onError = (err) => { onError(err); }; + + const debug = config.debug; + this._debug = (typeof debug === 'function' + ? (msg) => { debug(msg); } + : undefined); + + const onHeader = config.onHeader; + this._onHeader = (typeof onHeader === 'function' + ? (...args) => { onHeader(...args); } + : noop); + + const onPacket = config.onPacket; + this._onPacket = (typeof onPacket === 'function' + ? () => { onPacket(); } + : noop); + + let onHandshakeComplete = config.onHandshakeComplete; + if (typeof onHandshakeComplete !== 'function') + onHandshakeComplete = noop; + let firstHandshake; + this._onHandshakeComplete = (...args) => { + this._debug && this._debug('Handshake completed'); + if (firstHandshake === undefined) + firstHandshake = true; + else + firstHandshake = false; + + // Process packets queued during a rekey where necessary + const oldQueue = this._queue; + if (oldQueue) { + this._queue = undefined; + this._debug && this._debug( + `Draining outbound queue (${oldQueue.length}) ...` + ); + for (let i = 0; i < oldQueue.length; ++i) { + const data = oldQueue[i]; + // data === payload only + + // XXX: hacky + let finalized = this._packetRW.write.finalize(data); + if (finalized === data) { + const packet = this._cipher.allocPacket(data.length); + packet.set(data, 5); + finalized = packet; + } + + sendPacket(this, finalized); + } + this._debug && this._debug('... finished draining outbound queue'); + } + + if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled) + sendExtInfo(this); + + onHandshakeComplete(...args); + }; + this._queue = undefined; + + const messageHandlers = config.messageHandlers; + if (typeof messageHandlers === 'object' && messageHandlers !== null) + this._handlers = messageHandlers; + else + this._handlers = {}; + + this._onPayload = onPayload.bind(this); + + this._server = !!config.server; + this._banner = undefined; + let greeting; + if (this._server) { + if (typeof config.hostKeys !== 'object' || config.hostKeys === null) + throw new Error('Missing server host key(s)'); + this._hostKeys = config.hostKeys; + + // Greeting displayed before the ssh identification string is sent, this + // is usually ignored by most clients + if (typeof config.greeting === 'string' && config.greeting.length) { + greeting = (config.greeting.slice(-2) === '\r\n' + ? config.greeting + : `${config.greeting}\r\n`); + } + + // Banner shown after the handshake completes, but before user + // authentication begins + if (typeof config.banner === 'string' && config.banner.length) { + this._banner = (config.banner.slice(-2) === '\r\n' + ? config.banner + : `${config.banner}\r\n`); + } + } else { + this._hostKeys = undefined; + } + + let offer = config.offer; + if (typeof offer !== 'object' || offer === null) { + offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT); + } else if (offer.constructor !== KexInit) { + if (this._server) { + offer.kex = offer.kex.concat(['kex-strict-s-v00@openssh.com']); + } else { + offer.kex = offer.kex.concat([ + 'ext-info-c', + 'kex-strict-c-v00@openssh.com', + ]); + } + offer = new KexInit(offer); + } + this._kex = undefined; + this._strictMode = undefined; + this._kexinit = undefined; + this._offer = offer; + this._cipher = new NullCipher(0, this._onWrite); + this._decipher = undefined; + this._skipNextInboundPacket = false; + this._packetRW = { + read: new PacketReader(), + write: new PacketWriter(this), + }; + this._hostVerifier = (!this._server + && typeof config.hostVerifier === 'function' + ? config.hostVerifier + : undefined); + + this._parse = parseHeader; + this._buffer = undefined; + this._authsQueue = []; + this._authenticated = false; + this._remoteIdentRaw = undefined; + let sentIdent; + if (typeof config.ident === 'string') { + this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); + + sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); + sentIdent.set(this._identRaw, 0); + sentIdent[sentIdent.length - 2] = 13; // '\r' + sentIdent[sentIdent.length - 1] = 10; // '\n' + } else if (Buffer.isBuffer(config.ident)) { + const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); + fullIdent.latin1Write('SSH-2.0-', 0, 8); + fullIdent.set(config.ident, 8); + this._identRaw = fullIdent; + + sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); + sentIdent.set(fullIdent, 0); + sentIdent[sentIdent.length - 2] = 13; // '\r' + sentIdent[sentIdent.length - 1] = 10; // '\n' + } else { + this._identRaw = IDENT_RAW; + sentIdent = IDENT; + } + this._compatFlags = 0; + + if (this._debug) { + if (bindingAvailable) + this._debug('Custom crypto binding available'); + else + this._debug('Custom crypto binding not available'); + } + + this._debug && this._debug( + `Local ident: ${inspect(this._identRaw.toString())}` + ); + this.start = () => { + this.start = undefined; + if (greeting) + this._onWrite(greeting); + this._onWrite(sentIdent); + }; + } + _destruct(reason) { + this._packetRW.read.cleanup(); + this._packetRW.write.cleanup(); + this._cipher && this._cipher.free(); + this._decipher && this._decipher.free(); + if (typeof reason !== 'string' || reason.length === 0) + reason = 'fatal error'; + this.parse = () => { + throw new Error(`Instance unusable after ${reason}`); + }; + this._onWrite = () => { + throw new Error(`Instance unusable after ${reason}`); + }; + this._destruct = undefined; + } + cleanup() { + this._destruct && this._destruct(); + } + parse(chunk, i, len) { + while (i < len) + i = this._parse(chunk, i, len); + } + + // Protocol message API + + // =========================================================================== + // Common/Shared ============================================================= + // =========================================================================== + + // Global + // ------ + disconnect(reason) { + const pktLen = 1 + 4 + 4 + 4; + // We don't use _packetRW.write.* here because we need to make sure that + // we always get a full packet allocated because this message can be sent + // at any time -- even during a key exchange + let p = this._packetRW.write.allocStartKEX; + const packet = this._packetRW.write.alloc(pktLen, true); + const end = p + pktLen; + + if (!VALID_DISCONNECT_REASONS.has(reason)) + reason = DISCONNECT_REASON.PROTOCOL_ERROR; + + packet[p] = MESSAGE.DISCONNECT; + writeUInt32BE(packet, reason, ++p); + packet.fill(0, p += 4, end); + + this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); + sendPacket(this, this._packetRW.write.finalize(packet, true), true); + } + ping() { + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); + + packet.set(PING_PAYLOAD, p); + + this._debug && this._debug( + 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + rekey() { + if (this._kexinit === undefined) { + this._debug && this._debug('Outbound: Initiated explicit rekey'); + this._queue = []; + kexinit(this); + } else { + this._debug && this._debug('Outbound: Ignoring rekey during handshake'); + } + } + + // 'ssh-connection' service-specific + // --------------------------------- + requestSuccess(data) { + let p = this._packetRW.write.allocStart; + let packet; + if (Buffer.isBuffer(data)) { + packet = this._packetRW.write.alloc(1 + data.length); + + packet[p] = MESSAGE.REQUEST_SUCCESS; + + packet.set(data, ++p); + } else { + packet = this._packetRW.write.alloc(1); + + packet[p] = MESSAGE.REQUEST_SUCCESS; + } + + this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + requestFailure() { + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1); + + packet[p] = MESSAGE.REQUEST_FAILURE; + + this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelSuccess(chan) { + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); + + packet[p] = MESSAGE.CHANNEL_SUCCESS; + + writeUInt32BE(packet, chan, ++p); + + this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelFailure(chan) { + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); + + packet[p] = MESSAGE.CHANNEL_FAILURE; + + writeUInt32BE(packet, chan, ++p); + + this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelEOF(chan) { + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); + + packet[p] = MESSAGE.CHANNEL_EOF; + + writeUInt32BE(packet, chan, ++p); + + this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelClose(chan) { + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); + + packet[p] = MESSAGE.CHANNEL_CLOSE; + + writeUInt32BE(packet, chan, ++p); + + this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelWindowAdjust(chan, amount) { + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4); + + packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, amount, p += 4); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelData(chan, data) { + const isBuffer = Buffer.isBuffer(data); + const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); + + packet[p] = MESSAGE.CHANNEL_DATA; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, dataLen, p += 4); + + if (isBuffer) + packet.set(data, p += 4); + else + packet.utf8Write(data, p += 4, dataLen); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelExtData(chan, data, type) { + const isBuffer = Buffer.isBuffer(data); + const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); + + packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, type, p += 4); + + writeUInt32BE(packet, dataLen, p += 4); + + if (isBuffer) + packet.set(data, p += 4); + else + packet.utf8Write(data, p += 4, dataLen); + + this._debug + && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelOpenConfirm(remote, local, initWindow, maxPacket) { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); + + packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; + + writeUInt32BE(packet, remote, ++p); + + writeUInt32BE(packet, local, p += 4); + + writeUInt32BE(packet, initWindow, p += 4); + + writeUInt32BE(packet, maxPacket, p += 4); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelOpenFail(remote, reason, desc) { + if (typeof desc !== 'string') + desc = ''; + + const descLen = Buffer.byteLength(desc); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); + + packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; + + writeUInt32BE(packet, remote, ++p); + + writeUInt32BE(packet, reason, p += 4); + + writeUInt32BE(packet, descLen, p += 4); + + p += 4; + if (descLen) { + packet.utf8Write(desc, p, descLen); + p += descLen; + } + + writeUInt32BE(packet, 0, p); // Empty language tag + + this._debug + && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + + // =========================================================================== + // Client-specific =========================================================== + // =========================================================================== + + // Global + // ------ + service(name) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const nameLen = Buffer.byteLength(name); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + nameLen); + + packet[p] = MESSAGE.SERVICE_REQUEST; + + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(name, p += 4, nameLen); + + this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + + // 'ssh-userauth' service-specific + // ------------------------------- + authPassword(username, password, newPassword) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const userLen = Buffer.byteLength(username); + const passLen = Buffer.byteLength(password); + const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen + + (newPassword ? 4 + newPassLen : 0) + ); + + packet[p] = MESSAGE.USERAUTH_REQUEST; + + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); + + writeUInt32BE(packet, 8, p += 14); + packet.utf8Write('password', p += 4, 8); + + packet[p += 8] = (newPassword ? 1 : 0); + + writeUInt32BE(packet, passLen, ++p); + if (Buffer.isBuffer(password)) + bufferCopy(password, packet, 0, passLen, p += 4); + else + packet.utf8Write(password, p += 4, passLen); + + if (newPassword) { + writeUInt32BE(packet, newPassLen, p += passLen); + if (Buffer.isBuffer(newPassword)) + bufferCopy(newPassword, packet, 0, newPassLen, p += 4); + else + packet.utf8Write(newPassword, p += 4, newPassLen); + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (changed password)' + ); + } else { + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (password)' + ); + } + + this._authsQueue.push('password'); + + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authPK(username, pubKey, keyAlgo, cbSign) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error('Invalid key'); + + const keyType = pubKey.type; + pubKey = pubKey.getPublicSSH(); + + if (typeof keyAlgo === 'function') { + cbSign = keyAlgo; + keyAlgo = undefined; + } + if (!keyAlgo) + keyAlgo = keyType; + + const userLen = Buffer.byteLength(username); + const algoLen = Buffer.byteLength(keyAlgo); + const pubKeyLen = pubKey.length; + const sessionID = this._kex.sessionID; + const sesLen = sessionID.length; + const payloadLen = + (cbSign ? 4 + sesLen : 0) + + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; + let packet; + let p; + if (cbSign) { + packet = Buffer.allocUnsafe(payloadLen); + p = 0; + writeUInt32BE(packet, sesLen, p); + packet.set(sessionID, p += 4); + p += sesLen; + } else { + packet = this._packetRW.write.alloc(payloadLen); + p = this._packetRW.write.allocStart; + } + + packet[p] = MESSAGE.USERAUTH_REQUEST; + + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); + + writeUInt32BE(packet, 9, p += 14); + packet.utf8Write('publickey', p += 4, 9); + + packet[p += 9] = (cbSign ? 1 : 0); + + writeUInt32BE(packet, algoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, algoLen); + + writeUInt32BE(packet, pubKeyLen, p += algoLen); + packet.set(pubKey, p += 4); + + if (!cbSign) { + this._authsQueue.push('publickey'); + + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + return; + } + + cbSign(packet, (signature) => { + signature = convertSignature(signature, keyType); + if (signature === false) + throw new Error('Error while converting handshake signature'); + + const sigLen = signature.length; + p = this._packetRW.write.allocStart; + packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 + + 4 + algoLen + 4 + sigLen + ); + + // TODO: simply copy from original "packet" to new `packet` to avoid + // having to write each individual field a second time? + packet[p] = MESSAGE.USERAUTH_REQUEST; + + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); + + writeUInt32BE(packet, 9, p += 14); + packet.utf8Write('publickey', p += 4, 9); + + packet[p += 9] = 1; + + writeUInt32BE(packet, algoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, algoLen); + + writeUInt32BE(packet, pubKeyLen, p += algoLen); + packet.set(pubKey, p += 4); + + writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); + + writeUInt32BE(packet, algoLen, p += 4); + packet.utf8Write(keyAlgo, p += 4, algoLen); + + writeUInt32BE(packet, sigLen, p += algoLen); + packet.set(signature, p += 4); + + // Servers shouldn't send packet type 60 in response to signed publickey + // attempts, but if they do, interpret as type 60. + this._authsQueue.push('publickey'); + + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (publickey)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + }); + } + authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) { + // TODO: Make DRY by sharing similar code with authPK() + if (this._server) + throw new Error('Client-only method called in server mode'); + + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error('Invalid key'); + + const keyType = pubKey.type; + pubKey = pubKey.getPublicSSH(); + + if (typeof keyAlgo === 'function') { + cbSign = keyAlgo; + keyAlgo = undefined; + } + if (!keyAlgo) + keyAlgo = keyType; + + const userLen = Buffer.byteLength(username); + const algoLen = Buffer.byteLength(keyAlgo); + const pubKeyLen = pubKey.length; + const sessionID = this._kex.sessionID; + const sesLen = sessionID.length; + const hostnameLen = Buffer.byteLength(hostname); + const userlocalLen = Buffer.byteLength(userlocal); + const data = Buffer.allocUnsafe( + 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen + + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen + ); + let p = 0; + + writeUInt32BE(data, sesLen, p); + data.set(sessionID, p += 4); + + data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; + + writeUInt32BE(data, userLen, ++p); + data.utf8Write(username, p += 4, userLen); + + writeUInt32BE(data, 14, p += userLen); + data.utf8Write('ssh-connection', p += 4, 14); + + writeUInt32BE(data, 9, p += 14); + data.utf8Write('hostbased', p += 4, 9); + + writeUInt32BE(data, algoLen, p += 9); + data.utf8Write(keyAlgo, p += 4, algoLen); + + writeUInt32BE(data, pubKeyLen, p += algoLen); + data.set(pubKey, p += 4); + + writeUInt32BE(data, hostnameLen, p += pubKeyLen); + data.utf8Write(hostname, p += 4, hostnameLen); + + writeUInt32BE(data, userlocalLen, p += hostnameLen); + data.utf8Write(userlocal, p += 4, userlocalLen); + + cbSign(data, (signature) => { + signature = convertSignature(signature, keyType); + if (!signature) + throw new Error('Error while converting handshake signature'); + + const sigLen = signature.length; + const reqDataLen = (data.length - sesLen - 4); + p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + reqDataLen + 4 + 4 + algoLen + 4 + sigLen + ); + + bufferCopy(data, packet, 4 + sesLen, data.length, p); + + writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); + writeUInt32BE(packet, algoLen, p += 4); + packet.utf8Write(keyAlgo, p += 4, algoLen); + writeUInt32BE(packet, sigLen, p += algoLen); + packet.set(signature, p += 4); + + this._authsQueue.push('hostbased'); + + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (hostbased)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + }); + } + authKeyboard(username) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const userLen = Buffer.byteLength(username); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 + ); + + packet[p] = MESSAGE.USERAUTH_REQUEST; + + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); + + writeUInt32BE(packet, 20, p += 14); + packet.utf8Write('keyboard-interactive', p += 4, 20); + + writeUInt32BE(packet, 0, p += 20); + + writeUInt32BE(packet, 0, p += 4); + + this._authsQueue.push('keyboard-interactive'); + + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authNone(username) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const userLen = Buffer.byteLength(username); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); + + packet[p] = MESSAGE.USERAUTH_REQUEST; + + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); + + writeUInt32BE(packet, 4, p += 14); + packet.utf8Write('none', p += 4, 4); + + this._authsQueue.push('none'); + + this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authInfoRes(responses) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + let responsesTotalLen = 0; + let responseLens; + + if (responses) { + responseLens = new Array(responses.length); + for (let i = 0; i < responses.length; ++i) { + const len = Buffer.byteLength(responses[i]); + responseLens[i] = len; + responsesTotalLen += 4 + len; + } + } + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); + + packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; + + if (responses) { + writeUInt32BE(packet, responses.length, ++p); + p += 4; + for (let i = 0; i < responses.length; ++i) { + const len = responseLens[i]; + writeUInt32BE(packet, len, p); + p += 4; + if (len) { + packet.utf8Write(responses[i], p, len); + p += len; + } + } + } else { + writeUInt32BE(packet, 0, ++p); + } + + this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + + // 'ssh-connection' service-specific + // --------------------------------- + tcpipForward(bindAddr, bindPort, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const addrLen = Buffer.byteLength(bindAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); + + packet[p] = MESSAGE.GLOBAL_REQUEST; + + writeUInt32BE(packet, 13, ++p); + packet.utf8Write('tcpip-forward', p += 4, 13); + + packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, addrLen, ++p); + packet.utf8Write(bindAddr, p += 4, addrLen); + + writeUInt32BE(packet, bindPort, p += addrLen); + + this._debug + && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + cancelTcpipForward(bindAddr, bindPort, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const addrLen = Buffer.byteLength(bindAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); + + packet[p] = MESSAGE.GLOBAL_REQUEST; + + writeUInt32BE(packet, 20, ++p); + packet.utf8Write('cancel-tcpip-forward', p += 4, 20); + + packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, addrLen, ++p); + packet.utf8Write(bindAddr, p += 4, addrLen); + + writeUInt32BE(packet, bindPort, p += addrLen); + + this._debug + && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_streamLocalForward(socketPath, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const socketPathLen = Buffer.byteLength(socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 31 + 1 + 4 + socketPathLen + ); + + packet[p] = MESSAGE.GLOBAL_REQUEST; + + writeUInt32BE(packet, 31, ++p); + packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); + + packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, socketPathLen, ++p); + packet.utf8Write(socketPath, p += 4, socketPathLen); + + this._debug && this._debug( + 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_cancelStreamLocalForward(socketPath, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const socketPathLen = Buffer.byteLength(socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 38 + 1 + 4 + socketPathLen + ); + + packet[p] = MESSAGE.GLOBAL_REQUEST; + + writeUInt32BE(packet, 38, ++p); + packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); + + packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, socketPathLen, ++p); + packet.utf8Write(socketPath, p += 4, socketPathLen); + + if (this._debug) { + this._debug( + 'Outbound: Sending GLOBAL_REQUEST ' + + '(cancel-streamlocal-forward@openssh.com)' + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + directTcpip(chan, initWindow, maxPacket, cfg) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const srcLen = Buffer.byteLength(cfg.srcIP); + const dstLen = Buffer.byteLength(cfg.dstIP); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 + ); + + packet[p] = MESSAGE.CHANNEL_OPEN; + + writeUInt32BE(packet, 12, ++p); + packet.utf8Write('direct-tcpip', p += 4, 12); + + writeUInt32BE(packet, chan, p += 12); + + writeUInt32BE(packet, initWindow, p += 4); + + writeUInt32BE(packet, maxPacket, p += 4); + + writeUInt32BE(packet, dstLen, p += 4); + packet.utf8Write(cfg.dstIP, p += 4, dstLen); + + writeUInt32BE(packet, cfg.dstPort, p += dstLen); + + writeUInt32BE(packet, srcLen, p += 4); + packet.utf8Write(cfg.srcIP, p += 4, srcLen); + + writeUInt32BE(packet, cfg.srcPort, p += srcLen); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + const pathLen = Buffer.byteLength(cfg.socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 + ); + + packet[p] = MESSAGE.CHANNEL_OPEN; + + writeUInt32BE(packet, 30, ++p); + packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); + + writeUInt32BE(packet, chan, p += 30); + + writeUInt32BE(packet, initWindow, p += 4); + + writeUInt32BE(packet, maxPacket, p += 4); + + writeUInt32BE(packet, pathLen, p += 4); + packet.utf8Write(cfg.socketPath, p += 4, pathLen); + + // zero-fill reserved fields (string and uint32) + bufferFill(packet, 0, p += pathLen, p + 8); + + if (this._debug) { + this._debug( + 'Outbound: Sending CHANNEL_OPEN ' + + `(r:${chan}, direct-streamlocal@openssh.com)` + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_noMoreSessions(wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); + + packet[p] = MESSAGE.GLOBAL_REQUEST; + + writeUInt32BE(packet, 28, ++p); + packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); + + packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); + + this._debug && this._debug( + 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + session(chan, initWindow, maxPacket) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); + + packet[p] = MESSAGE.CHANNEL_OPEN; + + writeUInt32BE(packet, 7, ++p); + packet.utf8Write('session', p += 4, 7); + + writeUInt32BE(packet, chan, p += 7); + + writeUInt32BE(packet, initWindow, p += 4); + + writeUInt32BE(packet, maxPacket, p += 4); + + this._debug + && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + windowChange(chan, rows, cols, height, width) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 + ); + + packet[p] = MESSAGE.CHANNEL_REQUEST; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, 13, p += 4); + packet.utf8Write('window-change', p += 4, 13); + + packet[p += 13] = 0; + + writeUInt32BE(packet, cols, ++p); + + writeUInt32BE(packet, rows, p += 4); + + writeUInt32BE(packet, width, p += 4); + + writeUInt32BE(packet, height, p += 4); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + pty(chan, rows, cols, height, width, term, modes, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + // Does not consume window space + + if (!term || !term.length) + term = 'vt100'; + if (modes + && !Buffer.isBuffer(modes) + && !Array.isArray(modes) + && typeof modes === 'object' + && modes !== null) { + modes = modesToBytes(modes); + } + if (!modes || !modes.length) + modes = NO_TERMINAL_MODES_BUFFER; + + const termLen = term.length; + const modesLen = modes.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen + ); + + packet[p] = MESSAGE.CHANNEL_REQUEST; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, 7, p += 4); + packet.utf8Write('pty-req', p += 4, 7); + + packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, termLen, ++p); + packet.utf8Write(term, p += 4, termLen); + + writeUInt32BE(packet, cols, p += termLen); + + writeUInt32BE(packet, rows, p += 4); + + writeUInt32BE(packet, width, p += 4); + + writeUInt32BE(packet, height, p += 4); + + writeUInt32BE(packet, modesLen, p += 4); + p += 4; + if (Array.isArray(modes)) { + for (let i = 0; i < modesLen; ++i) + packet[p++] = modes[i]; + } else if (Buffer.isBuffer(modes)) { + packet.set(modes, p); + } + + this._debug + && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + shell(chan, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); + + packet[p] = MESSAGE.CHANNEL_REQUEST; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, 5, p += 4); + packet.utf8Write('shell', p += 4, 5); + + packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); + + this._debug + && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + exec(chan, cmd, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + // Does not consume window space + + const isBuf = Buffer.isBuffer(cmd); + const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); + + packet[p] = MESSAGE.CHANNEL_REQUEST; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, 4, p += 4); + packet.utf8Write('exec', p += 4, 4); + + packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, cmdLen, ++p); + if (isBuf) + packet.set(cmd, p += 4); + else + packet.utf8Write(cmd, p += 4, cmdLen); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + signal(chan, signal) { + if (this._server) + throw new Error('Client-only method called in server mode'); -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } + // Does not consume window space - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + const origSignal = signal; - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + signal = signal.toUpperCase(); + if (signal.slice(0, 3) === 'SIG') + signal = signal.slice(3); -/** - * Colorize log arguments if enabled. - * - * @api public - */ + if (SIGNALS[signal] !== 1) + throw new Error(`Invalid signal: ${origSignal}`); -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); + const signalLen = signal.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 6 + 1 + 4 + signalLen + ); - if (!this.useColors) { - return; - } + packet[p] = MESSAGE.CHANNEL_REQUEST; - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); + writeUInt32BE(packet, chan, ++p); - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + writeUInt32BE(packet, 6, p += 4); + packet.utf8Write('signal', p += 4, 6); - args.splice(lastC, 0, c); -} + packet[p += 6] = 0; -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); + writeUInt32BE(packet, signalLen, ++p); + packet.utf8Write(signal, p += 4, signalLen); -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + env(chan, key, val, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } + // Does not consume window space - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + const keyLen = Buffer.byteLength(key); + const isBuf = Buffer.isBuffer(val); + const valLen = (isBuf ? val.length : Buffer.byteLength(val)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen + ); - return r; -} + packet[p] = MESSAGE.CHANNEL_REQUEST; -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + writeUInt32BE(packet, chan, ++p); -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} + writeUInt32BE(packet, 3, p += 4); + packet.utf8Write('env', p += 4, 3); -module.exports = __nccwpck_require__(6243)(exports); + packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); -const {formatters} = module.exports; + writeUInt32BE(packet, keyLen, ++p); + packet.utf8Write(key, p += 4, keyLen); -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + writeUInt32BE(packet, valLen, p += keyLen); + if (isBuf) + packet.set(val, p += 4); + else + packet.utf8Write(val, p += 4, valLen); -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + x11Forward(chan, cfg, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + // Does not consume window space -/***/ }), + const protocol = cfg.protocol; + const cookie = cfg.cookie; + const isBufProto = Buffer.isBuffer(protocol); + const protoLen = (isBufProto + ? protocol.length + : Buffer.byteLength(protocol)); + const isBufCookie = Buffer.isBuffer(cookie); + const cookieLen = (isBufCookie + ? cookie.length + : Buffer.byteLength(cookie)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 + ); -/***/ 6243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ + writeUInt32BE(packet, 7, p += 4); + packet.utf8Write('x11-req', p += 4, 7); -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(900); - createDebug.destroy = destroy; + packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); + packet[++p] = (cfg.single ? 1 : 0); - /** - * The currently active debug mode names, and names to skip. - */ + writeUInt32BE(packet, protoLen, ++p); + if (isBufProto) + packet.set(protocol, p += 4); + else + packet.utf8Write(protocol, p += 4, protoLen); - createDebug.names = []; - createDebug.skips = []; + writeUInt32BE(packet, cookieLen, p += protoLen); + if (isBufCookie) + packet.set(cookie, p += 4); + else + packet.latin1Write(cookie, p += 4, cookieLen); - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; + writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; + this._debug + && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + subsystem(chan, name, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + // Does not consume window space + const nameLen = Buffer.byteLength(name); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + packet[p] = MESSAGE.CHANNEL_REQUEST; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; + writeUInt32BE(packet, chan, ++p); - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + writeUInt32BE(packet, 9, p += 4); + packet.utf8Write('subsystem', p += 4, 9); + + packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(name, p += 4, nameLen); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_agentForward(chan, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + // Does not consume window space + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); + + packet[p] = MESSAGE.CHANNEL_REQUEST; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, 26, p += 4); + packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); + + packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); + + if (this._debug) { + this._debug( + 'Outbound: Sending CHANNEL_REQUEST ' + + `(r:${chan}, auth-agent-req@openssh.com)` + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_hostKeysProve(keys) { + if (this._server) + throw new Error('Client-only method called in server mode'); + + let keysTotal = 0; + const publicKeys = []; + for (const key of keys) { + const publicKey = key.getPublicSSH(); + keysTotal += 4 + publicKey.length; + publicKeys.push(publicKey); + } + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); + + packet[p] = MESSAGE.GLOBAL_REQUEST; + + writeUInt32BE(packet, 29, ++p); + packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); + + packet[p += 29] = 1; // want reply + + ++p; + for (const buf of publicKeys) { + writeUInt32BE(packet, buf.length, p); + bufferCopy(buf, packet, 0, buf.length, p += 4); + p += buf.length; + } + + if (this._debug) { + this._debug( + 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + + // =========================================================================== + // Server-specific =========================================================== + // =========================================================================== + + // Global + // ------ + serviceAccept(svcName) { + if (!this._server) + throw new Error('Server-only method called in client mode'); + + const svcNameLen = Buffer.byteLength(svcName); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); + + packet[p] = MESSAGE.SERVICE_ACCEPT; + + writeUInt32BE(packet, svcNameLen, ++p); + packet.utf8Write(svcName, p += 4, svcNameLen); + + this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + + if (this._server && this._banner && svcName === 'ssh-userauth') { + const banner = this._banner; + this._banner = undefined; // Prevent banner from being displayed again + const bannerLen = Buffer.byteLength(banner); + p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); + + packet[p] = MESSAGE.USERAUTH_BANNER; + + writeUInt32BE(packet, bannerLen, ++p); + packet.utf8Write(banner, p += 4, bannerLen); + + writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag + + this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + } + // 'ssh-connection' service-specific + forwardedTcpip(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error('Server-only method called in client mode'); + + const boundAddrLen = Buffer.byteLength(cfg.boundAddr); + const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 + ); + + packet[p] = MESSAGE.CHANNEL_OPEN; + + writeUInt32BE(packet, 15, ++p); + packet.utf8Write('forwarded-tcpip', p += 4, 15); + + writeUInt32BE(packet, chan, p += 15); + + writeUInt32BE(packet, initWindow, p += 4); + + writeUInt32BE(packet, maxPacket, p += 4); + + writeUInt32BE(packet, boundAddrLen, p += 4); + packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); + + writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); + + writeUInt32BE(packet, remoteAddrLen, p += 4); + packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); + + writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + x11(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error('Server-only method called in client mode'); + + const addrLen = Buffer.byteLength(cfg.originAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 + ); + + packet[p] = MESSAGE.CHANNEL_OPEN; + + writeUInt32BE(packet, 3, ++p); + packet.utf8Write('x11', p += 4, 3); + + writeUInt32BE(packet, chan, p += 3); + + writeUInt32BE(packet, initWindow, p += 4); + + writeUInt32BE(packet, maxPacket, p += 4); + + writeUInt32BE(packet, addrLen, p += 4); + packet.utf8Write(cfg.originAddr, p += 4, addrLen); + + writeUInt32BE(packet, cfg.originPort, p += addrLen); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_authAgent(chan, initWindow, maxPacket) { + if (!this._server) + throw new Error('Server-only method called in client mode'); + + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); + + packet[p] = MESSAGE.CHANNEL_OPEN; + + writeUInt32BE(packet, 22, ++p); + packet.utf8Write('auth-agent@openssh.com', p += 4, 22); + + writeUInt32BE(packet, chan, p += 22); - const self = debug; + writeUInt32BE(packet, initWindow, p += 4); - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + writeUInt32BE(packet, maxPacket, p += 4); - args[0] = createDebug.coerce(args[0]); + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } + const pathLen = Buffer.byteLength(cfg.socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 + ); - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); + packet[p] = MESSAGE.CHANNEL_OPEN; - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + writeUInt32BE(packet, 33, ++p); + packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + writeUInt32BE(packet, chan, p += 33); - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } + writeUInt32BE(packet, initWindow, p += 4); - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + writeUInt32BE(packet, maxPacket, p += 4); - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, - set: v => { - enableOverride = v; - } - }); + writeUInt32BE(packet, pathLen, p += 4); + packet.utf8Write(cfg.socketPath, p += 4, pathLen); - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + writeUInt32BE(packet, 0, p += pathLen); - return debug; - } + if (this._debug) { + this._debug( + 'Outbound: Sending CHANNEL_OPEN ' + + `(r:${chan}, forwarded-streamlocal@openssh.com)` + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + exitStatus(chan, status) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + // Does not consume window space + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); + packet[p] = MESSAGE.CHANNEL_REQUEST; - createDebug.names = []; - createDebug.skips = []; + writeUInt32BE(packet, chan, ++p); - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; + writeUInt32BE(packet, 11, p += 4); + packet.utf8Write('exit-status', p += 4, 11); - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } + packet[p += 11] = 0; - namespaces = split[i].replace(/\*/g, '.*?'); + writeUInt32BE(packet, status, ++p); - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + exitSignal(chan, name, coreDumped, msg) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } + // Does not consume window space - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + const origSignal = name; - let i; - let len; + if (typeof origSignal !== 'string' || !origSignal) + throw new Error(`Invalid signal: ${origSignal}`); - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } + let signal = name.toUpperCase(); + if (signal.slice(0, 3) === 'SIG') + signal = signal.slice(3); - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } + if (SIGNALS[signal] !== 1) + throw new Error(`Invalid signal: ${origSignal}`); - return false; - } + const nameLen = Buffer.byteLength(signal); + const msgLen = (msg ? Buffer.byteLength(msg) : 0); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 + ); - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } + packet[p] = MESSAGE.CHANNEL_REQUEST; - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + writeUInt32BE(packet, chan, ++p); - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + writeUInt32BE(packet, 11, p += 4); + packet.utf8Write('exit-signal', p += 4, 11); - createDebug.enable(createDebug.load()); + packet[p += 11] = 0; - return createDebug; -} + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(signal, p += 4, nameLen); -module.exports = setup; + packet[p += nameLen] = (coreDumped ? 1 : 0); + writeUInt32BE(packet, msgLen, ++p); -/***/ }), + p += 4; + if (msgLen) { + packet.utf8Write(msg, p, msgLen); + p += msgLen; + } -/***/ 8237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + writeUInt32BE(packet, 0, p); -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + // 'ssh-userauth' service-specific + authFailure(authMethods, isPartial) { + if (!this._server) + throw new Error('Server-only method called in client mode'); -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(8222); -} else { - module.exports = __nccwpck_require__(4874); -} + if (this._authsQueue.length === 0) + throw new Error('No auth in progress'); + let methods; -/***/ }), + if (typeof authMethods === 'boolean') { + isPartial = authMethods; + authMethods = undefined; + } -/***/ 4874: -/***/ ((module, exports, __nccwpck_require__) => { + if (authMethods) { + methods = []; + for (let i = 0; i < authMethods.length; ++i) { + if (authMethods[i].toLowerCase() === 'none') + continue; + methods.push(authMethods[i]); + } + methods = methods.join(','); + } else { + methods = ''; + } -/** - * Module dependencies. - */ + const methodsLen = methods.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); -const tty = __nccwpck_require__(6224); -const util = __nccwpck_require__(3837); + packet[p] = MESSAGE.USERAUTH_FAILURE; -/** - * This is the Node.js implementation of `debug()`. - */ + writeUInt32BE(packet, methodsLen, ++p); + packet.utf8Write(methods, p += 4, methodsLen); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); + packet[p += methodsLen] = (isPartial === true ? 1 : 0); -/** - * Colors. - */ + this._authsQueue.shift(); -exports.colors = [6, 2, 3, 4, 5, 1]; + this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authSuccess() { + if (!this._server) + throw new Error('Server-only method called in client mode'); -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(9318); + if (this._authsQueue.length === 0) + throw new Error('No auth in progress'); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1); -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + packet[p] = MESSAGE.USERAUTH_SUCCESS; -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); + this._authsQueue.shift(); + this._authenticated = true; - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } + this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); + sendPacket(this, this._packetRW.write.finalize(packet)); - obj[prop] = val; - return obj; -}, {}); + if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') + this._packetRW.read = new ZlibPacketReader(); + if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') + this._packetRW.write = new ZlibPacketWriter(this); + } + authPKOK(keyAlgo, key) { + if (!this._server) + throw new Error('Server-only method called in client mode'); -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') + throw new Error('"publickey" auth not in progress'); -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} + // TODO: support parsed key for `key` -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + const keyAlgoLen = Buffer.byteLength(keyAlgo); + const keyLen = key.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); -function formatArgs(args) { - const {namespace: name, useColors} = this; + packet[p] = MESSAGE.USERAUTH_PK_OK; - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + writeUInt32BE(packet, keyAlgoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} + writeUInt32BE(packet, keyLen, p += keyAlgoLen); + packet.set(key, p += 4); -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} + this._authsQueue.shift(); -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ + this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authPasswdChg(prompt) { + if (!this._server) + throw new Error('Server-only method called in client mode'); -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} + const promptLen = Buffer.byteLength(prompt); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} + packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + writeUInt32BE(packet, promptLen, ++p); + packet.utf8Write(prompt, p += 4, promptLen); -function load() { - return process.env.DEBUG; -} + writeUInt32BE(packet, 0, p += promptLen); // Empty language tag -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authInfoReq(name, instructions, prompts) { + if (!this._server) + throw new Error('Server-only method called in client mode'); -function init(debug) { - debug.inspectOpts = {}; + let promptsLen = 0; + const nameLen = name ? Buffer.byteLength(name) : 0; + const instrLen = instructions ? Buffer.byteLength(instructions) : 0; - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + for (let i = 0; i < prompts.length; ++i) + promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; -module.exports = __nccwpck_require__(6243)(exports); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen + ); -const {formatters} = module.exports; + packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; -/** - * Map %o to `util.inspect()`, all on a single line. - */ + writeUInt32BE(packet, nameLen, ++p); + p += 4; + if (name) { + packet.utf8Write(name, p, nameLen); + p += nameLen; + } -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; + writeUInt32BE(packet, instrLen, p); + p += 4; + if (instructions) { + packet.utf8Write(instructions, p, instrLen); + p += instrLen; + } -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ + writeUInt32BE(packet, 0, p); -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + writeUInt32BE(packet, prompts.length, p += 4); + p += 4; + for (let i = 0; i < prompts.length; ++i) { + const prompt = prompts[i]; + const promptLen = Buffer.byteLength(prompt.prompt); + writeUInt32BE(packet, promptLen, p); + p += 4; + if (promptLen) { + packet.utf8Write(prompt.prompt, p, promptLen); + p += promptLen; + } + packet[p++] = (prompt.echo ? 1 : 0); + } -/***/ }), + this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } +} -/***/ 4305: -/***/ ((module, exports, __nccwpck_require__) => { +// SSH-protoversion-softwareversion (SP comments) CR LF +const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; -//Based on follow-redirects v0.0.x +// TODO: optimize this by starting n bytes from the end of this._buffer instead +// of the beginning +function parseHeader(chunk, p, len) { + let data; + let chunkOffset; + if (this._buffer) { + data = Buffer.allocUnsafe(this._buffer.length + (len - p)); + data.set(this._buffer, 0); + if (p === 0) { + data.set(chunk, this._buffer.length); + } else { + data.set(new Uint8Array(chunk.buffer, + chunk.byteOffset + p, + (len - p)), + this._buffer.length); + } + chunkOffset = this._buffer.length; + p = 0; + } else { + data = chunk; + chunkOffset = 0; + } + const op = p; + let start = p; + let end = p; + let needNL = false; + let lineLen = 0; + let lines = 0; + for (; p < data.length; ++p) { + const ch = data[p]; -var nativeHttps = __nccwpck_require__(5687), - nativeHttp = __nccwpck_require__(3685), - url = __nccwpck_require__(7310), - utils = __nccwpck_require__(4967); + if (ch === 13 /* '\r' */) { + needNL = true; + continue; + } -var maxRedirects = module.exports.maxRedirects = 5; + if (ch === 10 /* '\n' */) { + if (end > start + && end - start > 4 + && data[start] === 83 /* 'S' */ + && data[start + 1] === 83 /* 'S' */ + && data[start + 2] === 72 /* 'H' */ + && data[start + 3] === 45 /* '-' */) { -var protocols = { - https: nativeHttps, - http: nativeHttp -}; + const full = data.latin1Slice(op, end + 1); + const identRaw = (start === op ? full : full.slice(start - op)); + const m = RE_IDENT.exec(identRaw); + if (!m) + throw new Error('Invalid identification string'); -for (var protocol in protocols) { - var h = function() {}; - h.prototype = protocols[protocol]; - h = new h(); + const header = { + greeting: (start === op ? '' : full.slice(0, start - op)), + identRaw, + versions: { + protocol: m[1], + software: m[2], + }, + comments: m[3] + }; - h.request = function(h) { - return function(options, callback, redirectOptions) { + // Needed during handshake + this._remoteIdentRaw = Buffer.from(identRaw); - redirectOptions = redirectOptions || {}; + this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); + this._compatFlags = getCompatFlags(header); - var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects; + this._buffer = undefined; + this._decipher = + new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); + this._parse = parsePacket; - var redirect = utils.extend({ - count: 0, - max: max, - clientRequest: null, - userCallback: callback - }, redirectOptions); + this._onHeader(header); + if (!this._destruct) { + // We disconnected inside _onHeader + return len; + } - if (redirect.count > redirect.max) { - var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.'); - redirect.clientRequest.emit('error', err); - return redirect.clientRequest; + kexinit(this); + + return p + 1 - chunkOffset; } - redirect.count++; + // Only allow pre-ident greetings when we're a client + if (this._server) + throw new Error('Greetings from clients not permitted'); - var reqUrl; - if (typeof options === 'string') { - reqUrl = options; - } else { - reqUrl = url.format(utils.extend({ - protocol: protocol - }, options)); - } + if (++lines > MAX_LINES) + throw new Error('Max greeting lines exceeded'); - var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect)); + needNL = false; + start = p + 1; + lineLen = 0; + } else if (needNL) { + throw new Error('Invalid header: expected newline'); + } else if (++lineLen >= MAX_LINE_LEN) { + throw new Error('Header line too long'); + } - if (!redirect.clientRequest) redirect.clientRequest = clientRequest; + end = p; + } + if (!this._buffer) + this._buffer = bufferSlice(data, op); - function redirectCallback(reqUrl, redirect) { - return function(res) { - if (res.statusCode < 300 || res.statusCode > 399) { - return redirect.userCallback(res); - } + return p - chunkOffset; +} - if (!('location' in res.headers)) { - return redirect.userCallback(res); - } +function parsePacket(chunk, p, len) { + return this._decipher.decrypt(chunk, p, len); +} - var redirectUrl = url.resolve(reqUrl, res.headers.location); +function onPayload(payload) { + // XXX: move this to the Decipher implementations? - var proto = url.parse(redirectUrl).protocol; - proto = proto.substr(0, proto.length - 1); - return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect); - }; - } + this._onPacket(); - return clientRequest; - }; - }(h); + if (payload.length === 0) { + this._debug && this._debug('Inbound: Skipping empty packet payload'); + return; + } - // see https://github.com/joyent/node/blob/master/lib/http.js#L1623 - h.get = function(h) { - return function(options, cb, redirectOptions) { - var req = h.request(options, cb, redirectOptions); - req.end(); - return req; - }; - }(h); + payload = this._packetRW.read.read(payload); - module.exports[protocol] = h; + const type = payload[0]; + if (type === MESSAGE.USERAUTH_SUCCESS + && !this._server + && !this._authenticated) { + this._authenticated = true; + if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') + this._packetRW.write = new ZlibPacketWriter(this); + if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') + this._packetRW.read = new ZlibPacketReader(); + } + const handler = MESSAGE_HANDLERS[type]; + if (handler === undefined) { + this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); + return; + } + + return handler(this, payload); } +function getCompatFlags(header) { + const software = header.versions.software; -/***/ }), + let flags = 0; -/***/ 3855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (const rule of COMPAT_CHECKS) { + if (typeof rule[0] === 'string') { + if (software === rule[0]) + flags |= rule[1]; + } else if (rule[0].test(software)) { + flags |= rule[1]; + } + } -module.exports = HttpDuplex; + return flags; +} -var util = __nccwpck_require__(3837), - stream = __nccwpck_require__(1642); +function modesToBytes(modes) { + const keys = Object.keys(modes); + const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); + let b = 0; -util.inherits(HttpDuplex, stream.Duplex); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (key === 'TTY_OP_END') + continue; -function HttpDuplex(req, res, options) { - var self = this; + const opcode = TERMINAL_MODE[key]; + if (opcode === undefined) + continue; - if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options); + const val = modes[key]; + if (typeof val === 'number' && isFinite(val)) { + bytes[b++] = opcode; + bytes[b++] = val >>> 24; + bytes[b++] = val >>> 16; + bytes[b++] = val >>> 8; + bytes[b++] = val; + } + } - stream.Duplex.call(self, options); - self._output = null; + bytes[b++] = TERMINAL_MODE.TTY_OP_END; - self.connect(req, res); + if (b < bytes.length) + return bufferSlice(bytes, 0, b); + + return bytes; } -HttpDuplex.prototype.connect = function(req, res) { - var self = this; - self.req = req; - self._output = res; - self.emit('response', res); +function sendExtInfo(proto) { + let serverSigAlgs = + 'ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521' + + 'rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss'; + if (eddsaSupported) + serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`; + const algsLen = Buffer.byteLength(serverSigAlgs); - res.on('data', function(c) { - if (!self.push(c)) self._output.pause(); - }); - res.on('end', function() { - self.push(null); - }); -}; + let p = proto._packetRW.write.allocStart; + const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen); -HttpDuplex.prototype._read = function(n) { - if (this._output) this._output.resume(); -}; + packet[p] = MESSAGE.EXT_INFO; -HttpDuplex.prototype._write = function(chunk, encoding, cb) { - this.req.write(chunk, encoding); - cb(); -}; + writeUInt32BE(packet, 1, ++p); -HttpDuplex.prototype.end = function(chunk, encoding, cb) { - this._output.socket.destroy(); - return this.req.end(chunk, encoding, cb); -}; + writeUInt32BE(packet, 15, p += 4); + packet.utf8Write('server-sig-algs', p += 4, 15); -HttpDuplex.prototype.destroy = function() { - this.req.destroy(); - this._output.socket.destroy(); -}; + writeUInt32BE(packet, algsLen, p += 15); + packet.utf8Write(serverSigAlgs, p += 4, algsLen); + + proto._debug && proto._debug('Outbound: Sending EXT_INFO'); + sendPacket(proto, proto._packetRW.write.finalize(packet)); +} + +module.exports = Protocol; /***/ }), -/***/ 6042: +/***/ 2026: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var querystring = __nccwpck_require__(3477), - http = __nccwpck_require__(4305), - fs = __nccwpck_require__(7147), - path = __nccwpck_require__(1017), - url = __nccwpck_require__(7310), - ssh = __nccwpck_require__(7964), - HttpDuplex = __nccwpck_require__(3855), - debug = __nccwpck_require__(8237)('modem'), - utils = __nccwpck_require__(4967), - util = __nccwpck_require__(3837), - url = __nccwpck_require__(7310), - splitca = __nccwpck_require__(9798), - isWin = (__nccwpck_require__(2037).type)() === 'Windows_NT'; +"use strict"; -var defaultOpts = function () { - var host; - var opts = {}; - if (!process.env.DOCKER_HOST) { - // Windows socket path: //./pipe/docker_engine ( Windows 10 ) - // Linux & Darwin socket path: /var/run/docker.sock - opts.socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock'; - } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) { - // Strip off unix://, fall back to default of /var/run/docker.sock if - // unix:// was passed without a path - opts.socketPath = process.env.DOCKER_HOST.substring(7) || '/var/run/docker.sock'; - } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) { - // Strip off npipe://, fall back to default of //./pipe/docker_engine if - // npipe:// was passed without a path - opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine'; - } else { - var hostStr = process.env.DOCKER_HOST; - if (hostStr.indexOf('\/\/') < 0) { - hostStr = 'tcp://' + hostStr; - } - try { - host = new url.URL(hostStr); - } catch (err) { - throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234'); - } +const EventEmitter = __nccwpck_require__(2361); +const fs = __nccwpck_require__(7147); +const { constants } = fs; +const { + Readable: ReadableStream, + Writable: WritableStream +} = __nccwpck_require__(2781); +const { inherits, isDate } = __nccwpck_require__(3837); - opts.port = host.port; +const FastBuffer = Buffer[Symbol.species]; - if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') { - opts.protocol = 'https'; - } else if (host.protocol === 'ssh:') { - opts.protocol = 'ssh'; - opts.username = host.username; - opts.sshOptions = { - agent: process.env.SSH_AUTH_SOCK, - } - } else { - opts.protocol = 'http'; - } +const { + bufferCopy, + bufferSlice, + makeBufferParser, + writeUInt32BE, +} = __nccwpck_require__(9475); - opts.host = host.hostname; +const ATTR = { + SIZE: 0x00000001, + UIDGID: 0x00000002, + PERMISSIONS: 0x00000004, + ACMODTIME: 0x00000008, + EXTENDED: 0x80000000, +}; - if (process.env.DOCKER_CERT_PATH) { - opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem')); - opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem')); - opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem')); - } +// Large enough to store all possible attributes +const ATTRS_BUF = Buffer.alloc(28); - if (process.env.DOCKER_CLIENT_TIMEOUT) { - opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); - } - } +const STATUS_CODE = { + OK: 0, + EOF: 1, + NO_SUCH_FILE: 2, + PERMISSION_DENIED: 3, + FAILURE: 4, + BAD_MESSAGE: 5, + NO_CONNECTION: 6, + CONNECTION_LOST: 7, + OP_UNSUPPORTED: 8 +}; + +const VALID_STATUS_CODES = new Map( + Object.values(STATUS_CODE).map((n) => [n, 1]) +); + +const STATUS_CODE_STR = { + [STATUS_CODE.OK]: 'No error', + [STATUS_CODE.EOF]: 'End of file', + [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', + [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', + [STATUS_CODE.FAILURE]: 'Failure', + [STATUS_CODE.BAD_MESSAGE]: 'Bad message', + [STATUS_CODE.NO_CONNECTION]: 'No connection', + [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', + [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', +}; + +const REQUEST = { + INIT: 1, + OPEN: 3, + CLOSE: 4, + READ: 5, + WRITE: 6, + LSTAT: 7, + FSTAT: 8, + SETSTAT: 9, + FSETSTAT: 10, + OPENDIR: 11, + READDIR: 12, + REMOVE: 13, + MKDIR: 14, + RMDIR: 15, + REALPATH: 16, + STAT: 17, + RENAME: 18, + READLINK: 19, + SYMLINK: 20, + EXTENDED: 200 +}; + +const RESPONSE = { + VERSION: 2, + STATUS: 101, + HANDLE: 102, + DATA: 103, + NAME: 104, + ATTRS: 105, + EXTENDED: 201 +}; - return opts; +const OPEN_MODE = { + READ: 0x00000001, + WRITE: 0x00000002, + APPEND: 0x00000004, + CREAT: 0x00000008, + TRUNC: 0x00000010, + EXCL: 0x00000020 }; +const PKT_RW_OVERHEAD = 2 * 1024; +const MAX_REQID = 2 ** 32 - 1; +const CLIENT_VERSION_BUFFER = Buffer.from([ + 0, 0, 0, 5 /* length */, + REQUEST.INIT, + 0, 0, 0, 3 /* version */ +]); +const SERVER_VERSION_BUFFER = Buffer.from([ + 0, 0, 0, 5 /* length */, + RESPONSE.VERSION, + 0, 0, 0, 3 /* version */ +]); -var Modem = function (options) { - var optDefaults = defaultOpts(); - var opts = Object.assign({}, optDefaults, options); +const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; +const OPENSSH_MAX_PKT_LEN = 256 * 1024; - this.host = opts.host; +const bufferParser = makeBufferParser(); - if(!this.host) { - this.socketPath = opts.socketPath; - } +const fakeStderr = { + readable: false, + writable: false, + push: (data) => {}, + once: () => {}, + on: () => {}, + emit: () => {}, + end: () => {}, +}; - this.port = opts.port; - this.username = opts.username; - this.password = opts.password; - this.version = opts.version; - this.key = opts.key; - this.cert = opts.cert; - this.ca = opts.ca; - this.timeout = opts.timeout; - this.connectionTimeout = opts.connectionTimeout; - this.checkServerIdentity = opts.checkServerIdentity; - this.agent = opts.agent; - this.headers = opts.headers || {}; - this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); - //retrocompabitlity - if(this.sshOptions.agentForward === undefined) { - this.sshOptions.agentForward = opts.agentForward; - } +function noop() {} - if (this.key && this.cert && this.ca) { - this.protocol = 'https'; - } - this.protocol = opts.protocol || this.protocol || 'http'; -}; +// Emulates enough of `Channel` to be able to be used as a drop-in replacement +// in order to process incoming data with as little overhead as possible +class SFTP extends EventEmitter { + constructor(client, chanInfo, cfg) { + super(); -Modem.prototype.dial = function (options, callback) { - var opts, address, data; - var self = this; + if (typeof cfg !== 'object' || !cfg) + cfg = {}; - if (options.options) { - opts = options.options; - } + const remoteIdentRaw = client._protocol._remoteIdentRaw; - // Prevent credentials from showing up in URL - if (opts && opts.authconfig) { - delete opts.authconfig; - } + this.server = !!cfg.server; + this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); + this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); - // Prevent abortsignal from showing up in the URL - if (opts && opts.abortSignal) { - delete opts.abortSignal; - } + this._version = -1; + this._extensions = {}; + this._biOpt = cfg.biOpt; + this._pktLenBytes = 0; + this._pktLen = 0; + this._pktPos = 0; + this._pktType = 0; + this._pktData = undefined; + this._writeReqid = -1; + this._requests = {}; + this._maxInPktLen = OPENSSH_MAX_PKT_LEN; + this._maxOutPktLen = 34000; + this._maxReadLen = + (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; + this._maxWriteLen = + (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - if (this.version) { - options.path = '/' + this.version + options.path; - } + this.maxOpenHandles = undefined; - if (this.host) { - var parsed = url.parse(self.host); - address = url.format({ - 'protocol': parsed.protocol || self.protocol, - 'hostname': parsed.hostname || self.host, - 'port': self.port - }); - address = url.resolve(address, options.path); - } else { - address = options.path; + // Channel compatibility + this._client = client; + this._protocol = client._protocol; + this._callbacks = []; + this._hasX11 = false; + this._exit = { + code: undefined, + signal: undefined, + dump: undefined, + desc: undefined, + }; + this._waitWindow = false; // SSH-level backpressure + this._chunkcb = undefined; + this._buffer = []; + this.type = chanInfo.type; + this.subtype = undefined; + this.incoming = chanInfo.incoming; + this.outgoing = chanInfo.outgoing; + this.stderr = fakeStderr; + this.readable = true; } - if (options.path.indexOf('?') !== -1) { - if (opts && Object.keys(opts).length > 0) { - address += this.buildQuerystring(opts._query || opts); - } else { - address = address.substring(0, address.length - 1); + // This handles incoming data to parse + push(data) { + if (data === null) { + cleanupRequests(this); + if (!this.readable) + return; + // No more incoming data from the remote side + this.readable = false; + this.emit('end'); + return; } - } + /* + uint32 length + byte type + byte[length - 1] data payload + */ + let p = 0; - var optionsf = { - path: address, - method: options.method, - headers: options.headers || Object.assign({}, self.headers), - key: self.key, - cert: self.cert, - ca: self.ca - }; + while (p < data.length) { + if (this._pktLenBytes < 4) { + let nb = Math.min(4 - this._pktLenBytes, data.length - p); + this._pktLenBytes += nb; - if (this.checkServerIdentity) { - optionsf.checkServerIdentity = this.checkServerIdentity; - } + while (nb--) + this._pktLen = (this._pktLen << 8) + data[p++]; - if (this.agent) { - optionsf.agent = this.agent; - } + if (this._pktLenBytes < 4) + return; + if (this._pktLen === 0) + return doFatalSFTPError(this, 'Invalid packet length'); + if (this._pktLen > this._maxInPktLen) { + const max = this._maxInPktLen; + return doFatalSFTPError( + this, + `Packet length ${this._pktLen} exceeds max length of ${max}` + ); + } + if (p >= data.length) + return; + } + if (this._pktPos < this._pktLen) { + const nb = Math.min(this._pktLen - this._pktPos, data.length - p); + if (p !== 0 || nb !== data.length) { + if (nb === this._pktLen) { + this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); + } else { + if (!this._pkt) + this._pkt = Buffer.allocUnsafe(this._pktLen); + this._pkt.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._pktPos + ); + } + } else if (nb === this._pktLen) { + this._pkt = data; + } else { + if (!this._pkt) + this._pkt = Buffer.allocUnsafe(this._pktLen); + this._pkt.set(data, this._pktPos); + } + p += nb; + this._pktPos += nb; + if (this._pktPos < this._pktLen) + return; + } - if (options.authconfig) { - optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 || - Buffer.from(JSON.stringify(options.authconfig)).toString('base64'); - } + const type = this._pkt[0]; + const payload = this._pkt; - if (options.registryconfig) { - optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 || - Buffer.from(JSON.stringify(options.registryconfig)).toString('base64'); - } + // Prepare for next packet + this._pktLen = 0; + this._pktLenBytes = 0; + this._pkt = undefined; + this._pktPos = 0; - if (options.abortSignal) { - optionsf.signal = options.abortSignal; - } + const handler = (this.server + ? SERVER_HANDLERS[type] + : CLIENT_HANDLERS[type]); + if (!handler) + return doFatalSFTPError(this, `Unknown packet type ${type}`); - if (options.file) { - if (typeof options.file === 'string') { - data = fs.createReadStream(path.resolve(options.file)); - } else { - data = options.file; - } - optionsf.headers['Content-Type'] = 'application/tar'; - } else if (opts && options.method === 'POST') { - data = JSON.stringify(opts._body || opts); - if (options.allowEmpty) { - optionsf.headers['Content-Type'] = 'application/json'; - } else { - if (data !== '{}' && data !== '""') { - optionsf.headers['Content-Type'] = 'application/json'; - } else { - data = undefined; + if (this._version === -1) { + if (this.server) { + if (type !== REQUEST.INIT) + return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); + } else if (type !== RESPONSE.VERSION) { + return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); + } } + + if (handler(this, payload) === false) + return; } } - if (typeof data === 'string') { - optionsf.headers['Content-Length'] = Buffer.byteLength(data); - } else if (Buffer.isBuffer(data) === true) { - optionsf.headers['Content-Length'] = data.length; - } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) { - optionsf.headers['Transfer-Encoding'] = 'chunked'; + end() { + this.destroy(); } - - if (options.hijack) { - optionsf.headers.Connection = 'Upgrade'; - optionsf.headers.Upgrade = 'tcp'; + destroy() { + if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { + this.outgoing.state = 'closing'; + this._protocol.channelClose(this.outgoing.id); + } } - - if (this.socketPath) { - optionsf.socketPath = this.socketPath; - } else { - var urlp = url.parse(address); - optionsf.hostname = urlp.hostname; - optionsf.port = urlp.port; - optionsf.path = urlp.path; + _init() { + this._init = noop; + if (!this.server) + sendOrBuffer(this, CLIENT_VERSION_BUFFER); } - this.buildRequest(optionsf, options, data, callback); -}; - -Modem.prototype.buildRequest = function (options, context, data, callback) { - var self = this; - var connectionTimeoutTimer; - - var opts = self.protocol === 'ssh' ? Object.assign(options, { - agent: ssh(Object.assign({}, self.sshOptions, { - 'host': self.host, - 'port': self.port, - 'username': self.username, - 'password': self.password, - })), - protocol: 'http:', - }) : options; - - var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { }); - - debug('Sending: %s', util.inspect(options, { - showHidden: true, - depth: null - })); + // =========================================================================== + // Client-specific =========================================================== + // =========================================================================== + createReadStream(path, options) { + if (this.server) + throw new Error('Client-only method called in server mode'); - if (self.connectionTimeout) { - connectionTimeoutTimer = setTimeout(function () { - debug('Connection Timeout of %s ms exceeded', self.connectionTimeout); - req.abort(); - }, self.connectionTimeout); + return new ReadStream(this, path, options); } + createWriteStream(path, options) { + if (this.server) + throw new Error('Client-only method called in server mode'); - if (self.timeout) { - req.on('socket', function (socket) { - socket.setTimeout(self.timeout); - socket.on('timeout', function () { - debug('Timeout of %s ms exceeded', self.timeout); - req.abort(); - }); - }); + return new WriteStream(this, path, options); } + open(path, flags_, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - if (context.hijack === true) { - clearTimeout(connectionTimeoutTimer); - req.on('upgrade', function (res, sock, head) { - return callback(null, sock); - }); - } + if (typeof attrs === 'function') { + cb = attrs; + attrs = undefined; + } - req.on('connect', function () { - clearTimeout(connectionTimeoutTimer); - }); + const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); + if (flags === null) + throw new Error(`Unknown flags string: ${flags_}`); - req.on('disconnect', function () { - clearTimeout(connectionTimeoutTimer); - }); + let attrsFlags = 0; + let attrsLen = 0; + if (typeof attrs === 'string' || typeof attrs === 'number') + attrs = { mode: attrs }; + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + attrsFlags = attrs.flags; + attrsLen = attrs.nb; + } - req.on('response', function (res) { - clearTimeout(connectionTimeoutTimer); - if (context.isStream === true) { - self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback); - } else { - var chunks = []; - res.on('data', function (chunk) { - chunks.push(chunk); - }); + /* + uint32 id + string filename + uint32 pflags + ATTRS attrs + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); - res.on('end', function () { - var buffer = Buffer.concat(chunks); - var result = buffer.toString(); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.OPEN; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - debug('Received: %s', result); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + writeUInt32BE(buf, attrsFlags, p += 4); + if (attrsLen) { + p += 4; - var json = utils.parseJSON(result) || buffer; - self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback); - }); - } - }); + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - req.on('error', function (error) { - clearTimeout(connectionTimeoutTimer); - self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback); - }); + p += attrsLen; + } + this._requests[reqid] = { cb }; - if (typeof data === 'string' || Buffer.isBuffer(data)) { - req.write(data); - } else if (data) { - data.on('error', function (error) { - req.destroy(error); - }); - data.pipe(req); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` + ); } + close(handle, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) { - req.end(); - } -}; + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); -Modem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) { - if (err) return cb(err, null); + /* + uint32 id + string handle + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - if (statusCodes[res.statusCode] !== true) { - getCause(isStream, res, json, function (err, cause) { - var msg = new Error( - '(HTTP code ' + res.statusCode + ') ' + - (statusCodes[res.statusCode] || 'unexpected') + ' - ' + - (cause.message || cause) + ' ' - ); - msg.reason = statusCodes[res.statusCode]; - msg.statusCode = res.statusCode; - msg.json = json; - cb(msg, null); - }); - } else { - if (openStdin) { - cb(null, new HttpDuplex(req, res)); - } else if (isStream) { - cb(null, res); - } else { - cb(null, json); - } - } + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.CLOSE; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - function getCause(isStream, res, json, callback) { - var chunks = ''; - if (isStream) { - res.on('data', function (chunk) { - chunks += chunk; - }); - res.on('end', function () { - callback(null, utils.parseJSON(chunks) || chunks); - }); - } else { - callback(null, json); - } - } -}; + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); -Modem.prototype.demuxStream = function (stream, stdout, stderr) { - var nextDataType = null; - var nextDataLength = null; - var buffer = Buffer.from(''); - function processData(data) { - if (data) { - buffer = Buffer.concat([buffer, data]); - } - if (!nextDataType) { - if (buffer.length >= 8) { - var header = bufferSlice(8); - nextDataType = header.readUInt8(0); - nextDataLength = header.readUInt32BE(4); - // It's possible we got a "data" that contains multiple messages - // Process the next one - processData(); - } - } else { - if (buffer.length >= nextDataLength) { - var content = bufferSlice(nextDataLength); - if (nextDataType === 1) { - stdout.write(content); - } else { - stderr.write(content); - } - nextDataType = null; - // It's possible we got a "data" that contains multiple messages - // Process the next one - processData(); - } - } + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` + ); } + read(handle, buf, off, len, position, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); + if (!Buffer.isBuffer(buf)) + throw new Error('buffer is not a Buffer'); + if (off >= buf.length) + throw new Error('offset is out of bounds'); + if (off + len > buf.length) + throw new Error('length extends beyond buffer'); + if (position === null) + throw new Error('null position currently unsupported'); - function bufferSlice(end) { - var out = buffer.slice(0, end); - buffer = Buffer.from(buffer.slice(end, buffer.length)); - return out; + read_(this, handle, buf, off, len, position, cb); + } + readData(handle, buf, off, len, position, cb) { + // Backwards compatibility + this.read(handle, buf, off, len, position, cb); } + write(handle, buf, off, len, position, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - stream.on('data', processData); -}; + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); + if (!Buffer.isBuffer(buf)) + throw new Error('buffer is not a Buffer'); + if (off > buf.length) + throw new Error('offset is out of bounds'); + if (off + len > buf.length) + throw new Error('length extends beyond buffer'); + if (position === null) + throw new Error('null position currently unsupported'); -Modem.prototype.followProgress = function (stream, onFinished, onProgress) { - var buf = ''; - var output = []; - var finished = false; + if (!len) { + cb && process.nextTick(cb, undefined, 0); + return; + } - stream.on('data', onStreamEvent); - stream.on('error', onStreamError); - stream.on('end', onStreamEnd); - stream.on('close', onStreamEnd); + const maxDataLen = this._maxWriteLen; + const overflow = Math.max(len - maxDataLen, 0); + const origPosition = position; - function onStreamEvent(data) { - buf += data.toString(); - pump(); + if (overflow) + len = maxDataLen; - function pump() { - var pos; - while ((pos = buf.indexOf('\n')) >= 0) { - if (pos == 0) { - buf = buf.slice(1); - continue; - } - processLine(buf.slice(0, pos)); - buf = buf.slice(pos + 1); - } + /* + uint32 id + string handle + uint64 offset + string data + */ + const handleLen = handle.length; + let p = 9; + const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); + + writeUInt32BE(out, out.length - 4, 0); + out[4] = REQUEST.WRITE; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(out, reqid, 5); + + writeUInt32BE(out, handleLen, p); + out.set(handle, p += 4); + p += handleLen; + for (let i = 7; i >= 0; --i) { + out[p + i] = position & 0xFF; + position /= 256; } + writeUInt32BE(out, len, p += 8); + bufferCopy(buf, out, off, off + len, p += 4); - function processLine(line) { - if (line[line.length - 1] == '\r') line = line.substr(0, line.length - 1); - if (line.length > 0) { - var obj = JSON.parse(line); - output.push(obj); - if (onProgress) { - onProgress(obj); + this._requests[reqid] = { + cb: (err) => { + if (err) { + if (typeof cb === 'function') + cb(err); + } else if (overflow) { + this.write(handle, + buf, + off + len, + overflow, + origPosition + len, + cb); + } else if (typeof cb === 'function') { + cb(undefined, off + len); } } - } - }; + }; - function onStreamError(err) { - finished = true; - stream.removeListener('data', onStreamEvent); - stream.removeListener('error', onStreamError); - stream.removeListener('end', onStreamEnd); - stream.removeListener('close', onStreamEnd); - onFinished(err, output); + const isSent = sendOrBuffer(this, out); + if (this._debug) { + const how = (isSent ? 'Sent' : 'Buffered'); + this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); + } + } + writeData(handle, buf, off, len, position, cb) { + // Backwards compatibility + this.write(handle, buf, off, len, position, cb); } + fastGet(remotePath, localPath, opts, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - function onStreamEnd() { - if(!finished) onFinished(null, output); - finished = true; + fastXfer(this, fs, remotePath, localPath, opts, cb); } -}; + fastPut(localPath, remotePath, opts, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -Modem.prototype.buildQuerystring = function (opts) { - var clone = {}; + fastXfer(fs, this, localPath, remotePath, opts, cb); + } + readFile(path, options, callback_) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // serialize map values as JSON strings, else querystring truncates. - Object.keys(opts).map(function (key, i) { - if (opts[key] - && typeof opts[key] === 'object' - && !Array.isArray(opts[key]) - // Ref: https://docs.docker.com/engine/api/v1.40/#operation/ImageBuild - // > cachefrom (string) JSON array of images used for build cache resolution. - || key === 'cachefrom' - ) { - clone[key] = JSON.stringify(opts[key]); - } else { - clone[key] = opts[key]; + let callback; + if (typeof callback_ === 'function') { + callback = callback_; + } else if (typeof options === 'function') { + callback = options; + options = undefined; } - }); - - return querystring.stringify(clone); -}; -module.exports = Modem; + if (typeof options === 'string') + options = { encoding: options, flag: 'r' }; + else if (!options) + options = { encoding: null, flag: 'r' }; + else if (typeof options !== 'object') + throw new TypeError('Bad arguments'); + const encoding = options.encoding; + if (encoding && !Buffer.isEncoding(encoding)) + throw new Error(`Unknown encoding: ${encoding}`); -/***/ }), + // First stat the file, so we know the size. + let size; + let buffer; // Single buffer with file data + let buffers; // List for when size is unknown + let pos = 0; + let handle; -/***/ 7964: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // SFTPv3 does not support using -1 for read position, so we have to track + // read position manually + let bytesRead = 0; -var Client = (__nccwpck_require__(5869).Client), - http = __nccwpck_require__(3685); + const flag = options.flag || 'r'; -module.exports = function(opt) { - var conn = new Client(); - var agent = new http.Agent(); + const read = () => { + if (size === 0) { + buffer = Buffer.allocUnsafe(8192); + this.read(handle, buffer, 0, 8192, bytesRead, afterRead); + } else { + this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); + } + }; - agent.createConnection = function(options, fn) { - conn.once('ready', function() { - conn.exec('docker system dial-stdio', function(err, stream) { - if (err) { - conn.end(); - agent.destroy(); - return; + const afterRead = (er, nbytes) => { + let eof; + if (er) { + eof = (er.code === STATUS_CODE.EOF); + if (!eof) { + return this.close(handle, () => { + return callback && callback(er); + }); } + } else { + eof = false; + } - fn(null, stream); - - stream.once('close', () => { - conn.end(); - agent.destroy(); - }); - }); - }).connect(opt); - - conn.once('end', () => agent.destroy()); - }; - - return agent; -}; + if (eof || (size === 0 && nbytes === 0)) + return close(); + bytesRead += nbytes; + pos += nbytes; + if (size !== 0) { + if (pos === size) + close(); + else + read(); + } else { + // Unknown size, just read until we don't get bytes. + buffers.push(bufferSlice(buffer, 0, nbytes)); + read(); + } + }; + afterRead._wantEOFError = true; -/***/ }), + const close = () => { + this.close(handle, (er) => { + if (size === 0) { + // Collect the data into the buffers list. + buffer = Buffer.concat(buffers, pos); + } else if (pos < size) { + buffer = bufferSlice(buffer, 0, pos); + } -/***/ 4967: -/***/ ((module) => { + if (encoding) + buffer = buffer.toString(encoding); + return callback && callback(er, buffer); + }); + }; -// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js + this.open(path, flag, 0o666, (er, handle_) => { + if (er) + return callback && callback(er); + handle = handle_; -var arr = []; -var each = arr.forEach; -var slice = arr.slice; + const tryStat = (er, st) => { + if (er) { + // Try stat() for sftp servers that may not support fstat() for + // whatever reason + this.stat(path, (er_, st_) => { + if (er_) { + return this.close(handle, () => { + callback && callback(er); + }); + } + tryStat(null, st_); + }); + return; + } -module.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; -}; + size = st.size || 0; + if (size === 0) { + // The kernel lies about many files. + // Go ahead and try to read some bytes. + buffers = []; + return read(); + } -module.exports.parseJSON = function(s) { - try { - return JSON.parse(s); - } catch (e) { - return null; + buffer = Buffer.allocUnsafe(size); + read(); + }; + this.fstat(handle, tryStat); + }); } -}; - - -/***/ }), - -/***/ 5004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(1604); + writeFile(path, data, options, callback_) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Represents a config - * @param {Object} modem docker-modem - * @param {String} id Config's id - */ -var Config = function(modem, id) { - this.modem = modem; - this.id = id; -}; + let callback; + if (typeof callback_ === 'function') { + callback = callback_; + } else if (typeof options === 'function') { + callback = options; + options = undefined; + } -Config.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + if (typeof options === 'string') + options = { encoding: options, mode: 0o666, flag: 'w' }; + else if (!options) + options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; + else if (typeof options !== 'object') + throw new TypeError('Bad arguments'); -/** - * Inspect - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Config.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (options.encoding && !Buffer.isEncoding(options.encoding)) + throw new Error(`Unknown encoding: ${options.encoding}`); - var optsf = { - path: '/configs/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - } - }; + const flag = options.flag || 'w'; + this.open(path, flag, options.mode, (openErr, handle) => { + if (openErr) { + callback && callback(openErr); + } else { + const buffer = (Buffer.isBuffer(data) + ? data + : Buffer.from('' + data, options.encoding || 'utf8')); + const position = (/a/.test(flag) ? null : 0); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + // SFTPv3 does not support the notion of 'current position' + // (null position), so we just attempt to append to the end of the file + // instead + if (position === null) { + const tryStat = (er, st) => { + if (er) { + // Try stat() for sftp servers that may not support fstat() for + // whatever reason + this.stat(path, (er_, st_) => { + if (er_) { + return this.close(handle, () => { + callback && callback(er); + }); + } + tryStat(null, st_); + }); + return; + } + writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); + }; + this.fstat(handle, tryStat); + return; } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); + writeAll(this, handle, buffer, 0, buffer.length, position, callback); + } }); } -}; + appendFile(path, data, options, callback_) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Update a config. - * - * @param {object} opts - * @param {function} callback - */ -Config.prototype.update = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + let callback; + if (typeof callback_ === 'function') { + callback = callback_; + } else if (typeof options === 'function') { + callback = options; + options = undefined; + } - var optsf = { - path: '/configs/' + this.id + '/update?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; + if (typeof options === 'string') + options = { encoding: options, mode: 0o666, flag: 'a' }; + else if (!options) + options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; + else if (typeof options !== 'object') + throw new TypeError('Bad arguments'); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); + if (!options.flag) + options = Object.assign({ flag: 'a' }, options); + this.writeFile(path, data, options, callback); + } + exists(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); + + this.stat(path, (err) => { + cb && cb(err ? false : true); }); } -}; + unlink(filename, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); + /* + uint32 id + string filename + */ + const fnameLen = Buffer.byteLength(filename); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); -/** - * Removes the config - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Config.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.REMOVE; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - var optsf = { - path: '/configs/' + this.id, - method: 'DELETE', - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; + writeUInt32BE(buf, fnameLen, p); + buf.utf8Write(filename, p += 4, fnameLen); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` + ); } -}; + rename(oldPath, newPath, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); + /* + uint32 id + string oldpath + string newpath + */ + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.RENAME; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -module.exports = Config; + writeUInt32BE(buf, oldLen, p); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); + this._requests[reqid] = { cb }; -/***/ }), + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` + ); + } + mkdir(path, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/***/ 5815: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let flags = 0; + let attrsLen = 0; -var extend = (__nccwpck_require__(1604).extend), - Exec = __nccwpck_require__(3149), - util = __nccwpck_require__(1604); + if (typeof attrs === 'function') { + cb = attrs; + attrs = undefined; + } + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } -/** - * Represents a Container - * @param {Object} modem docker-modem - * @param {String} id Container's ID - */ -var Container = function(modem, id) { - this.modem = modem; - this.id = id; + /* + uint32 id + string path + ATTRS attrs + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - this.defaultOptions = { - top: {}, - start: {}, - commit: {}, - stop: {}, - pause: {}, - unpause: {}, - restart: {}, - resize: {}, - attach: {}, - remove: {}, - copy: {}, - kill: {}, - exec: {}, - rename: {}, - log: {}, - stats: {}, - getArchive: {}, - infoArchive: {}, - putArchive: {}, - update: {}, - wait: {} - }; -}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.MKDIR; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -Container.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if supplied will query Docker. - * @return {Object} ID only and only if callback isn't supplied. - */ -Container.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - var optsf = { - path: '/containers/' + this.id + '/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' + p += attrsLen; } - }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` + ); } -}; + rmdir(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Rename - * @param {Object} opts Rename options - * @param {Function} callback Callback - */ -Container.prototype.rename = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.rename); + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - var optsf = { - path: '/containers/' + this.id + '/rename?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.RMDIR; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` + ); } -}; + readdir(where, opts, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Update - * @param {Object} opts Update options - * @param {Function} callback Callback - */ -Container.prototype.update = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.update); + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (typeof opts !== 'object' || opts === null) + opts = {}; - var optsf = { - path: '/containers/' + this.id + '/update', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + const doFilter = (opts && opts.full ? false : true); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + if (!Buffer.isBuffer(where) && typeof where !== 'string') + throw new Error('missing directory handle or path'); -/** - * Top - * @param {Object} opts like 'ps_args' (optional) - * @param {Function} callback Callback - */ -Container.prototype.top = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.top); + if (typeof where === 'string') { + const entries = []; + let e = 0; - var optsf = { - path: '/containers/' + this.id + '/top?', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + const reread = (err, handle) => { + if (err) + return cb(err); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + this.readdir(handle, opts, (err, list) => { + const eof = (err && err.code === STATUS_CODE.EOF); -/** - * Containers changes - * @param {Object} Options - * @param {Function} callback Callback - */ -Container.prototype.changes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (err && !eof) + return this.close(handle, () => cb(err)); - var optsf = { - path: '/containers/' + this.id + '/changes', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - } - }; + if (eof) { + return this.close(handle, (err) => { + if (err) + return cb(err); + cb(undefined, entries); + }); + } - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + for (let i = 0; i < list.length; ++i, ++e) + entries[e] = list[i]; -/** - * Checkpoints list - * @param {Object} opts List checkpoints options (optional) - * @param {Function} callback Callback - */ -Container.prototype.listCheckpoint = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + reread(undefined, handle); + }); + }; + return this.opendir(where, reread); + } - var optsf = { - path: '/containers/' + this.id + '/checkpoints?', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + /* + uint32 id + string handle + */ + const handleLen = where.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.READDIR; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + + writeUInt32BE(buf, handleLen, p); + buf.set(where, p += 4); + this._requests[reqid] = { + cb: (doFilter + ? (err, list) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); -/** - * Delete checkpoint - * @param {Object} opts Delete checkpoint options (optional) - * @param {Function} callback Callback - */ -Container.prototype.deleteCheckpoint = function(checkpoint, opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + for (let i = list.length - 1; i >= 0; --i) { + if (list[i].filename === '.' || list[i].filename === '..') + list.splice(i, 1); + } - var optsf = { - path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + cb(undefined, list); + } + : cb) + }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` + ); } -}; + fstat(handle, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Create checkpoint - * @param {Object} opts Create checkpoint options (optional) - * @param {Function} callback Callback - */ -Container.prototype.createCheckpoint = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - var optsf = { - path: '/containers/' + this.id + '/checkpoints', - method: 'POST', - abortSignal: args.opts.abortSignal, - allowEmpty: true, - statusCodes: { - 200: true, //unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + /* + uint32 id + string handle + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.FSTAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); + + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` + ); } -}; + stat(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); + + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.STAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/** - * Export - * @param {Object} opts Options (optional) - * @param {Function} callback Callback with the octet-stream. - */ -Container.prototype.export = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); - var optsf = { - path: '/containers/' + this.id + '/export', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - } - }; + this._requests[reqid] = { cb }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` + ); } -}; + lstat(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Start - * @param {Object} opts Container start options (optional) - * @param {Function} callback Callback - */ -Container.prototype.start = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.start); + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - var optsf = { - path: '/containers/' + this.id + '/start?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 304: 'container already started', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.LSTAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` + ); } -}; + opendir(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Pause - * @param {Object} opts Pause options (optional) - * @param {Function} callback Callback - */ -Container.prototype.pause = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.pause); + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - var optsf = { - path: '/containers/' + this.id + '/pause', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - }, - options: args.opts - }; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.OPENDIR; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` + ); } -}; + setstat(path, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Unpause - * @param {Object} opts Unpause options (optional) - * @param {Function} callback Callback - */ -Container.prototype.unpause = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.unpause); + let flags = 0; + let attrsLen = 0; - var optsf = { - path: '/containers/' + this.id + '/unpause', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === 'function') { + cb = attrs; + } - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + /* + uint32 id + string path + ATTRS attrs + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); -/** - * Setup an exec call to a running container - * - * @param {object} opts - * @param {function} callback - */ -Container.prototype.exec = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.exec); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.SETSTAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - var optsf = { - path: '/containers/' + this.id + '/exec', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 409: 'container stopped/paused', - 500: 'server error' - }, - options: args.opts - }; + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(new Exec(self.modem, data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, new Exec(self.modem, data.Id)); - }); + p += attrsLen; + } + + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` + ); } -}; + fsetstat(handle, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Commit - * @param {Object} opts Commit options like 'Hostname' (optional) - * @param {Function} callback Callback - */ -Container.prototype.commit = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.commit); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - args.opts.container = this.id; + let flags = 0; + let attrsLen = 0; - var optsf = { - path: '/commit?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === 'function') { + cb = attrs; + } - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + /* + uint32 id + string handle + ATTRS attrs + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); -/** - * Stop - * @param {Object} opts Container stop options, like 't' (optional) - * @param {Function} callback Callback - */ -Container.prototype.stop = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stop); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.FSETSTAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - var optsf = { - path: '/containers/' + this.id + '/stop?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 304: 'container already stopped', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); + writeUInt32BE(buf, flags, p += handleLen); + if (attrsLen) { + p += 4; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); -/** - * Restart - * @param {Object} opts Container restart options, like 't' (optional) - * @param {Function} callback Callback - */ -Container.prototype.restart = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.restart); + p += attrsLen; + } - var optsf = { - path: '/containers/' + this.id + '/restart?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + this._requests[reqid] = { cb }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` + ); } -}; + futimes(handle, atime, mtime, cb) { + return this.fsetstat(handle, { + atime: toUnixTimestamp(atime), + mtime: toUnixTimestamp(mtime) + }, cb); + } + utimes(path, atime, mtime, cb) { + return this.setstat(path, { + atime: toUnixTimestamp(atime), + mtime: toUnixTimestamp(mtime) + }, cb); + } + fchown(handle, uid, gid, cb) { + return this.fsetstat(handle, { + uid: uid, + gid: gid + }, cb); + } + chown(path, uid, gid, cb) { + return this.setstat(path, { + uid: uid, + gid: gid + }, cb); + } + fchmod(handle, mode, cb) { + return this.fsetstat(handle, { + mode: mode + }, cb); + } + chmod(path, mode, cb) { + return this.setstat(path, { + mode: mode + }, cb); + } + readlink(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Kill - * @param {Object} opts Container kill options, like 'signal' (optional) - * @param {Function} callback Callback - */ -Container.prototype.kill = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.kill); + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - var optsf = { - path: '/containers/' + this.id + '/kill?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.READLINK; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error('Response missing link info')); + cb(undefined, names[0].filename); + } + }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` + ); } -}; + symlink(targetPath, linkPath, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Container resize - * @param {[type]} opts Resize options. (optional) - * @param {Function} callback Callback - */ -Container.prototype.resize = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.resize); + /* + uint32 id + string linkpath + string targetpath + */ + const linkLen = Buffer.byteLength(linkPath); + const targetLen = Buffer.byteLength(targetPath); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); - var optsf = { - path: '/containers/' + this.id + '/resize?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.SYMLINK; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + if (this._isOpenSSH) { + // OpenSSH has linkpath and targetpath positions switched + writeUInt32BE(buf, targetLen, p); + buf.utf8Write(targetPath, p += 4, targetLen); + writeUInt32BE(buf, linkLen, p += targetLen); + buf.utf8Write(linkPath, p += 4, linkLen); + } else { + writeUInt32BE(buf, linkLen, p); + buf.utf8Write(linkPath, p += 4, linkLen); + writeUInt32BE(buf, targetLen, p += linkLen); + buf.utf8Write(targetPath, p += 4, targetLen); + } + + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` + ); } -}; + realpath(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Attach - * @param {Object} opts Attach options, like 'logs' (optional) - * @param {Function} callback Callback with stream. - */ -Container.prototype.attach = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.attach); + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - var optsf = { - path: '/containers/' + this.id + '/attach?', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.REALPATH; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, stream) { - if (err) { - return reject(err); - } - resolve(stream); - }); - }); - } else { - this.modem.dial(optsf, function(err, stream) { - args.callback(err, stream); - }); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error('Response missing path info')); + cb(undefined, names[0].filename); + } + }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` + ); } -}; + // extended requests + ext_openssh_rename(oldPath, newPath, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Waits for a container to end. - * @param {[type]} opts Container wait options, like condition. (optional) - * @param {Function} callback Callback - */ -Container.prototype.wait = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.wait); + const ext = this._extensions['posix-rename@openssh.com']; + if (!ext || ext !== '1') + throw new Error('Server does not support this extended request'); - var optsf = { - path: '/containers/' + this.id + '/wait?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + /* + uint32 id + string "posix-rename@openssh.com" + string oldpath + string newpath + */ + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = + Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/** - * Removes a container - * @param {Object} opts Remove options, like 'force' (optional) - * @param {Function} callback Callback - */ -Container.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.remove); + writeUInt32BE(buf, 24, p); + buf.utf8Write('posix-rename@openssh.com', p += 4, 24); + writeUInt32BE(buf, oldLen, p += 24); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); - var optsf = { - path: '/containers/' + this.id + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + this._requests[reqid] = { cb }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); + } } -}; + ext_openssh_statvfs(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Copy (WARNING: DEPRECATED since RAPI v1.20) - * @param {Object} opts Copy options, like 'Resource' (optional) - * @param {Function} callback Callback with stream. - */ -Container.prototype.copy = function(opts, callback) { - var self = this; - console.log('container.copy is deprecated since Docker v1.8.x'); - var args = util.processArgs(opts, callback, this.defaultOptions.copy); + const ext = this._extensions['statvfs@openssh.com']; + if (!ext || ext !== '2') + throw new Error('Server does not support this extended request'); - var optsf = { - path: '/containers/' + this.id + '/copy', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + /* + uint32 id + string "statvfs@openssh.com" + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/** - * getArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.getArchive = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.getArchive); + writeUInt32BE(buf, 19, p); + buf.utf8Write('statvfs@openssh.com', p += 4, 19); + writeUInt32BE(buf, pathLen, p += 19); + buf.utf8Write(path, p += 4, pathLen); - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); + } } -}; + ext_openssh_fstatvfs(handle, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * infoArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.infoArchive = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive); + const ext = this._extensions['fstatvfs@openssh.com']; + if (!ext || ext !== '2') + throw new Error('Server does not support this extended request'); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'HEAD', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + /* + uint32 id + string "fstatvfs@openssh.com" + string handle + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/** - * putArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.putArchive = function(file, opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.putArchive); + writeUInt32BE(buf, 20, p); + buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); + writeUInt32BE(buf, handleLen, p += 20); + buf.set(handle, p += 4); - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'PUT', - file: file, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 403: 'client error, permission denied', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); + } } -}; + ext_openssh_hardlink(oldPath, newPath, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Container logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Container.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); + const ext = this._extensions['hardlink@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - var optsf = { - path: '/containers/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + /* + uint32 id + string "hardlink@openssh.com" + string oldpath + string newpath + */ + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = + Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + + writeUInt32BE(buf, 20, p); + buf.utf8Write('hardlink@openssh.com', p += 4, 20); + writeUInt32BE(buf, oldLen, p += 20); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); -/** - * Container stats - * @param {Object} opts Stats options. (optional) - * @param {Function} callback Callback with data - */ -Container.prototype.stats = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stats); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: '/containers/' + this.id + '/stats?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: isStream, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + this._requests[reqid] = { cb }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); + } } -}; + ext_openssh_fsync(handle, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -module.exports = Container; + const ext = this._extensions['fsync@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); + /* + uint32 id + string "fsync@openssh.com" + string handle + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); -/***/ }), + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/***/ 4571: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + writeUInt32BE(buf, 17, p); + buf.utf8Write('fsync@openssh.com', p += 4, 17); + writeUInt32BE(buf, handleLen, p += 17); + buf.set(handle, p += 4); -var EventEmitter = (__nccwpck_require__(2361).EventEmitter), - Modem = __nccwpck_require__(6042), - tar = __nccwpck_require__(366), - zlib = __nccwpck_require__(9796), - Container = __nccwpck_require__(5815), - Image = __nccwpck_require__(6689), - Volume = __nccwpck_require__(4877), - Network = __nccwpck_require__(9780), - Service = __nccwpck_require__(8866), - Plugin = __nccwpck_require__(6606), - Secret = __nccwpck_require__(9934), - Config = __nccwpck_require__(5004), - Task = __nccwpck_require__(1385), - Node = __nccwpck_require__(2297), - Exec = __nccwpck_require__(3149), - util = __nccwpck_require__(1604), - extend = util.extend; + this._requests[reqid] = { cb }; -var Docker = function(opts) { - if (!(this instanceof Docker)) return new Docker(opts); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` + ); + } + ext_openssh_lsetstat(path, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - var plibrary = global.Promise; + const ext = this._extensions['lsetstat@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - if (opts && opts.Promise) { - plibrary = opts.Promise; + let flags = 0; + let attrsLen = 0; - if (Object.keys(opts).length === 1) { - opts = undefined; + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === 'function') { + cb = attrs; } - } - this.modem = new Modem(opts); - this.modem.Promise = plibrary; -}; + /* + uint32 id + string "lsetstat@openssh.com" + string path + ATTRS attrs + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = + Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); -/** - * Creates a new container - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createContainer = function(opts, callback) { - var self = this; - var optsf = { - path: '/containers/create?', - method: 'POST', - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 406: 'impossible to attach', - 500: 'server error' - } - }; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - delete opts.authconfig; + writeUInt32BE(buf, 20, p); + buf.utf8Write('lsetstat@openssh.com', p += 4, 20); - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getContainer(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self.getContainer(data.Id)); - }); - } -}; + writeUInt32BE(buf, pathLen, p += 20); + buf.utf8Write(path, p += 4, pathLen); -/** - * Creates a new image - * @param {Object} auth Authentication (optional) - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createImage = function(auth, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (!callback && !opts) { - opts = auth; - auth = opts.authconfig; - } + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; - var optsf = { - path: '/images/create?', - method: 'POST', - options: opts, - authconfig: auth, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + + p += attrsLen; } - }; - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; + this._requests[reqid] = { cb }; -/** - * Load image - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.loadImage = function(file, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); + } } + ext_openssh_expandPath(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - var optsf = { - path: '/images/load?', - method: 'POST', - options: opts, - file: file, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + const ext = this._extensions['expand-path@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; + /* + uint32 id + string "expand-path@openssh.com" + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); -/** - * Import image from a tar archive - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.importImage = function(file, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = undefined; - } + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if (!opts) - opts = {}; + writeUInt32BE(buf, 23, p); + buf.utf8Write('expand-path@openssh.com', p += 4, 23); - opts.fromSrc = '-'; + writeUInt32BE(buf, pathLen, p += 20); + buf.utf8Write(path, p += 4, pathLen); - var optsf = { - path: '/images/create?', - method: 'POST', - options: opts, - file: file, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error('Response missing expanded path')); + cb(undefined, names[0].filename); + } + }; - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); + } } -}; + ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Verifies auth - * @param {Object} opts Options - * @param {Function} callback Callback - */ -Docker.prototype.checkAuth = function(opts, callback) { - var self = this; - var optsf = { - path: '/auth', - method: 'POST', - options: opts, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 500: 'server error' - } - }; + const ext = this._extensions['copy-data']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; + if (!Buffer.isBuffer(srcHandle)) + throw new Error('Source handle is not a Buffer'); -/** - * Builds an image - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.buildImage = function(file, opts, callback) { - var self = this; + if (!Buffer.isBuffer(dstHandle)) + throw new Error('Destination handle is not a Buffer'); - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } + /* + uint32 id + string "copy-data" + string read-from-handle + uint64 read-from-offset + uint64 read-data-length + string write-to-handle + uint64 write-to-offset + */ + let p = 0; + const buf = Buffer.allocUnsafe( + 4 + 1 + + 4 + + 4 + 9 + + 4 + srcHandle.length + + 8 + + 8 + + 4 + dstHandle.length + + 8 + ); - function build(file) { - var optsf = { - path: '/build?', - method: 'POST', - file: file, - options: opts, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + writeUInt32BE(buf, buf.length - 4, p); + p += 4; - if (opts) { - if (opts.registryconfig) { - optsf.registryconfig = optsf.options.registryconfig; - delete optsf.options.registryconfig; - } + buf[p] = REQUEST.EXTENDED; + ++p; - //undocumented? - if (opts.authconfig) { - optsf.authconfig = optsf.options.authconfig; - delete optsf.options.authconfig; - } - } + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; - if (callback === undefined) { - return new self.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - self.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + writeUInt32BE(buf, 9, p); + p += 4; + buf.utf8Write('copy-data', p, 9); + p += 9; + + writeUInt32BE(buf, srcHandle.length, p); + p += 4; + buf.set(srcHandle, p); + p += srcHandle.length; + + for (let i = 7; i >= 0; --i) { + buf[p + i] = srcOffset & 0xFF; + srcOffset /= 256; } - } + p += 8; - if (file && file.context) { - var pack = tar.pack(file.context, { - entries: file.src - }); - return build(pack.pipe(zlib.createGzip())); - } else { - return build(file); - } -}; + for (let i = 7; i >= 0; --i) { + buf[p + i] = len & 0xFF; + len /= 256; + } + p += 8; -/** - * Fetches a Container by ID - * @param {String} id Container's ID - */ -Docker.prototype.getContainer = function(id) { - return new Container(this.modem, id); -}; + writeUInt32BE(buf, dstHandle.length, p); + p += 4; + buf.set(dstHandle, p); + p += dstHandle.length; -/** - * Fetches an Image by name - * @param {String} name Image's name - */ -Docker.prototype.getImage = function(name) { - return new Image(this.modem, name); -}; + for (let i = 7; i >= 0; --i) { + buf[p + i] = dstOffset & 0xFF; + dstOffset /= 256; + } -/** - * Fetches a Volume by name - * @param {String} name Volume's name - */ -Docker.prototype.getVolume = function(name) { - return new Volume(this.modem, name); -}; + this._requests[reqid] = { cb }; -/** - * Fetches a Plugin by name - * @param {String} name Volume's name - */ -Docker.prototype.getPlugin = function(name, remote) { - return new Plugin(this.modem, name, remote); -}; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} copy-data`); + } + } + ext_home_dir(username, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Fetches a Service by id - * @param {String} id Services's id - */ -Docker.prototype.getService = function(id) { - return new Service(this.modem, id); -}; + const ext = this._extensions['home-directory']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); -/** - * Fetches a Task by id - * @param {String} id Task's id - */ -Docker.prototype.getTask = function(id) { - return new Task(this.modem, id); -}; + if (typeof username !== 'string') + throw new TypeError('username is not a string'); -/** - * Fetches Node by id - * @param {String} id Node's id - */ -Docker.prototype.getNode = function(id) { - return new Node(this.modem, id); -}; + /* + uint32 id + string "home-directory" + string username + */ + let p = 0; + const usernameLen = Buffer.byteLength(username); + const buf = Buffer.allocUnsafe( + 4 + 1 + + 4 + + 4 + 14 + + 4 + usernameLen + ); -/** - * Fetches a Network by id - * @param {String} id network's id - */ -Docker.prototype.getNetwork = function(id) { - return new Network(this.modem, id); -}; + writeUInt32BE(buf, buf.length - 4, p); + p += 4; -/** - * Fetches a Secret by id - * @param {String} id network's id - */ -Docker.prototype.getSecret = function(id) { - return new Secret(this.modem, id); -}; + buf[p] = REQUEST.EXTENDED; + ++p; -/** - * Fetches a Config by id - * @param {String} id network's id - */ -Docker.prototype.getConfig = function(id) { - return new Config(this.modem, id); -}; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; -/** - * Fetches an Exec instance by ID - * @param {String} id Exec instance's ID - */ -Docker.prototype.getExec = function(id) { - return new Exec(this.modem, id); -}; + writeUInt32BE(buf, 14, p); + p += 4; + buf.utf8Write('home-directory', p, 14); + p += 14; -/** - * Lists containers - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listContainers = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + writeUInt32BE(buf, usernameLen, p); + p += 4; + buf.utf8Write(username, p, usernameLen); + p += usernameLen; - var optsf = { - path: '/containers/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error('Response missing home directory')); + cb(undefined, names[0].filename); + } + }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} home-directory`); + } } -}; + ext_users_groups(uids, gids, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Lists images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + const ext = this._extensions['users-groups-by-id@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - var optsf = { - path: '/images/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' + if (!Array.isArray(uids)) + throw new TypeError('uids is not an array'); + for (const val of uids) { + if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) + throw new Error('uid values must all be 32-bit unsigned integers'); + } + if (!Array.isArray(gids)) + throw new TypeError('gids is not an array'); + for (const val of gids) { + if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) + throw new Error('gid values must all be 32-bit unsigned integers'); } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + /* + uint32 id + string "users-groups-by-id@openssh.com" + string uids + uint32 uid1 + ... + string gids + uint32 gid1 + ... + */ + let p = 0; + const buf = Buffer.allocUnsafe( + 4 + 1 + + 4 + + 4 + 30 + + 4 + (4 * uids.length) + + 4 + (4 * gids.length) + ); -/** - * Get images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.getImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + writeUInt32BE(buf, buf.length - 4, p); + p += 4; - var optsf = { - path: '/images/get?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; + buf[p] = REQUEST.EXTENDED; + ++p; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; -/** - * Lists Services - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listServices = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + writeUInt32BE(buf, 30, p); + p += 4; + buf.utf8Write('users-groups-by-id@openssh.com', p, 30); + p += 30; - var optsf = { - path: '/services?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + writeUInt32BE(buf, 4 * uids.length, p); + p += 4; + for (const val of uids) { + writeUInt32BE(buf, val, p); + p += 4; } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + writeUInt32BE(buf, 4 * gids.length, p); + p += 4; + for (const val of gids) { + writeUInt32BE(buf, val, p); + p += 4; + } -/** - * Lists Nodes - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listNodes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + this._requests[reqid] = { extended: 'users-groups-by-id@openssh.com', cb }; - var optsf = { - path: '/nodes?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such node', - 500: 'server error', - 503: 'node is not part of a swarm', + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`); } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); } -}; + // =========================================================================== + // Server-specific =========================================================== + // =========================================================================== + handle(reqid, handle) { + if (!this.server) + throw new Error('Server-only method called in client mode'); -/** - * Lists Tasks - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listTasks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - var optsf = { - path: '/tasks?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + const handleLen = handle.length; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + if (handleLen > 256) + throw new Error('handle too large (> 256 bytes)'); -/** - * Creates a new secret - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createSecret = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - var optsf = { - path: '/secrets/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 406: 'server error or node is not part of a swarm', - 409: 'name conflicts with an existing object', - 500: 'server error' - } - }; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.HANDLE; + writeUInt32BE(buf, reqid, 5); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getSecret(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getSecret(data.ID)); - }); + writeUInt32BE(buf, handleLen, p); + if (handleLen) + buf.set(handle, p += 4); + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` + ); } -}; + status(reqid, code, message) { + if (!this.server) + throw new Error('Server-only method called in client mode'); + if (!VALID_STATUS_CODES.has(code)) + throw new Error(`Bad status code: ${code}`); -/** - * Creates a new config - * @param {Object} opts Config options - * @param {Function} callback Callback - */ -Docker.prototype.createConfig = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - var optsf = { - path: '/configs/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 406: 'server error or node is not part of a swarm', - 409: 'name conflicts with an existing object', - 500: 'server error' + message || (message = ''); + + const msgLen = Buffer.byteLength(message); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); + + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.STATUS; + writeUInt32BE(buf, reqid, 5); + + writeUInt32BE(buf, code, p); + + writeUInt32BE(buf, msgLen, p += 4); + p += 4; + if (msgLen) { + buf.utf8Write(message, p, msgLen); + p += msgLen; } - }; + writeUInt32BE(buf, 0, p); // Empty language tag - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getConfig(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getConfig(data.ID)); - }); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` + ); } -}; + data(reqid, data, encoding) { + if (!this.server) + throw new Error('Server-only method called in client mode'); + const isBuffer = Buffer.isBuffer(data); -/** - * Lists secrets - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listSecrets = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (!isBuffer && typeof data !== 'string') + throw new Error('data is not a Buffer or string'); - var optsf = { - path: '/secrets?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + let isUTF8; + if (!isBuffer && !encoding) { + encoding = undefined; + isUTF8 = true; } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + const dataLen = ( + isBuffer + ? data.length + : Buffer.byteLength(data, encoding) + ); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); -/** - * Lists configs - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listConfigs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.DATA; + writeUInt32BE(buf, reqid, 5); - var optsf = { - path: '/configs?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + writeUInt32BE(buf, dataLen, p); + if (dataLen) { + if (isBuffer) + buf.set(data, p += 4); + else if (isUTF8) + buf.utf8Write(data, p += 4, dataLen); + else + buf.write(data, p += 4, dataLen, encoding); } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` + ); + } + name(reqid, names) { + if (!this.server) + throw new Error('Server-only method called in client mode'); + + if (!Array.isArray(names)) { + if (typeof names !== 'object' || names === null) + throw new Error('names is not an object or array'); + names = [ names ]; + } + + const count = names.length; + let namesLen = 0; + let nameAttrs; + const attrs = []; + + for (let i = 0; i < count; ++i) { + const name = names[i]; + const filename = ( + !name || !name.filename || typeof name.filename !== 'string' + ? '' + : name.filename + ); + namesLen += 4 + Buffer.byteLength(filename); + const longname = ( + !name || !name.longname || typeof name.longname !== 'string' + ? '' + : name.longname + ); + namesLen += 4 + Buffer.byteLength(longname); + + if (typeof name.attrs === 'object' && name.attrs !== null) { + nameAttrs = attrsToBytes(name.attrs); + namesLen += 4 + nameAttrs.nb; + + if (nameAttrs.nb) { + let bytes; + + if (nameAttrs.nb === ATTRS_BUF.length) { + bytes = new Uint8Array(ATTRS_BUF); + } else { + bytes = new Uint8Array(nameAttrs.nb); + bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); + } + + nameAttrs.bytes = bytes; } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; -/** - * Creates a new plugin - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createPlugin = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/plugins/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' + attrs.push(nameAttrs); + } else { + namesLen += 4; + attrs.push(null); + } } - }; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getPlugin(args.opts.name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getPlugin(args.opts.name)); - }); - } -}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.NAME; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, count, p); -/** - * Lists plugins - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listPlugins = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + p += 4; - var optsf = { - path: '/plugins?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + for (let i = 0; i < count; ++i) { + const name = names[i]; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + { + const filename = ( + !name || !name.filename || typeof name.filename !== 'string' + ? '' + : name.filename + ); + const len = Buffer.byteLength(filename); + writeUInt32BE(buf, len, p); + p += 4; + if (len) { + buf.utf8Write(filename, p, len); + p += len; } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + } -/** - * Prune images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + { + const longname = ( + !name || !name.longname || typeof name.longname !== 'string' + ? '' + : name.longname + ); + const len = Buffer.byteLength(longname); + writeUInt32BE(buf, len, p); + p += 4; + if (len) { + buf.utf8Write(longname, p, len); + p += len; + } + } - var optsf = { - path: '/images/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + const attr = attrs[i]; + if (attr) { + writeUInt32BE(buf, attr.flags, p); + p += 4; + if (attr.flags && attr.bytes) { + buf.set(attr.bytes, p); + p += attr.nb; + } + } else { + writeUInt32BE(buf, 0, p); + p += 4; + } } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` + ); } -}; + attrs(reqid, attrs) { + if (!this.server) + throw new Error('Server-only method called in client mode'); -/** - * Prune builder - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneBuilder = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (typeof attrs !== 'object' || attrs === null) + throw new Error('attrs is not an object'); - var optsf = { - path: '/build/prune', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + attrs = attrsToBytes(attrs); + const flags = attrs.flags; + const attrsLen = attrs.nb; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.ATTRS; + writeUInt32BE(buf, reqid, 5); -/** - * Prune containers - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneContainers = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + writeUInt32BE(buf, flags, p); + if (attrsLen) { + p += 4; - var optsf = { - path: '/containers/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + + p += attrsLen; } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` + ); } -}; +} -/** - * Prune volumes - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneVolumes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +function tryCreateBuffer(size) { + try { + return Buffer.allocUnsafe(size); + } catch (ex) { + return ex; + } +} - var optsf = { - path: '/volumes/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; +function read_(self, handle, buf, off, len, position, cb, req_) { + const maxDataLen = self._maxReadLen; + const overflow = Math.max(len - maxDataLen, 0); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + if (overflow) + len = maxDataLen; + + /* + uint32 id + string handle + uint64 offset + uint32 len + */ + const handleLen = handle.length; + let p = 9; + let pos = position; + const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); + + writeUInt32BE(out, out.length - 4, 0); + out[4] = REQUEST.READ; + const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; + writeUInt32BE(out, reqid, 5); + + writeUInt32BE(out, handleLen, p); + out.set(handle, p += 4); + p += handleLen; + for (let i = 7; i >= 0; --i) { + out[p + i] = pos & 0xFF; + pos /= 256; } -}; + writeUInt32BE(out, len, p += 8); -/** - * Prune networks - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneNetworks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (typeof cb !== 'function') + cb = noop; - var optsf = { - path: '/networks/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + const req = (req_ || { + nb: 0, + position, + off, + origOff: off, + len: undefined, + overflow: undefined, + cb: (err, data, nb) => { + const len = req.len; + const overflow = req.overflow; + + if (err) { + if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) + return cb(err); + } else if (nb > len) { + return cb(new Error('Received more data than requested')); + } else if (nb === len && overflow) { + req.nb += nb; + req.position += nb; + req.off += nb; + read_(self, handle, buf, req.off, overflow, req.position, cb, req); + return; + } + + nb = (nb || 0); + if (req.origOff === 0 && buf.length === req.nb) + data = buf; + else + data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb); + cb(undefined, req.nb + nb, data, req.position); + }, + buffer: undefined, + }); + + req.len = len; + req.overflow = overflow; + + // TODO: avoid creating multiple buffer slices when we need to re-call read_() + // because of overflow + req.buffer = bufferSlice(buf, off, off + len); + + self._requests[reqid] = req; + + const isBuffered = sendOrBuffer(self, out); + self._debug && self._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` + ); +} + +function fastXfer(src, dst, srcPath, dstPath, opts, cb) { + let concurrency = 64; + let chunkSize = 32768; + let onstep; + let mode; + let fileSize; + + if (typeof opts === 'function') { + cb = opts; + } else if (typeof opts === 'object' && opts !== null) { + if (typeof opts.concurrency === 'number' + && opts.concurrency > 0 + && !isNaN(opts.concurrency)) { + concurrency = opts.concurrency; } - }; + if (typeof opts.chunkSize === 'number' + && opts.chunkSize > 0 + && !isNaN(opts.chunkSize)) { + chunkSize = opts.chunkSize; + } + if (typeof opts.fileSize === 'number' + && opts.fileSize > 0 + && !isNaN(opts.fileSize)) { + fileSize = opts.fileSize; + } + if (typeof opts.step === 'function') + onstep = opts.step; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + if (typeof opts.mode === 'string' || typeof opts.mode === 'number') + mode = modeNum(opts.mode); } -}; + // Internal state variables + let fsize; + let pdst = 0; + let total = 0; + let hadError = false; + let srcHandle; + let dstHandle; + let readbuf; + let bufsize = chunkSize * concurrency; -/** - * Creates a new volume - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createVolume = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/volumes/create?', - method: 'POST', - allowEmpty: true, - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 500: 'server error' - } - }; + function onerror(err) { + if (hadError) + return; + hadError = true; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getVolume(data.Name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getVolume(data.Name)); - }); - } -}; + let left = 0; + let cbfinal; -/** - * Creates a new service - * @param {Object} auth - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createService = function(auth, opts, callback) { - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (!opts && !callback) { - opts = auth; + if (srcHandle || dstHandle) { + cbfinal = () => { + if (--left === 0) + cb(err); + }; + if (srcHandle && (src === fs || src.outgoing.state === 'open')) + ++left; + if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) + ++left; + if (srcHandle && (src === fs || src.outgoing.state === 'open')) + src.close(srcHandle, cbfinal); + if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) + dst.close(dstHandle, cbfinal); + } else { + cb(err); + } } + src.open(srcPath, 'r', (err, sourceHandle) => { + if (err) + return onerror(err); - var self = this; - var optsf = { - path: '/services/create', - method: 'POST', - options: opts, - authconfig: auth, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 500: 'server error' - } - }; + srcHandle = sourceHandle; + if (fileSize === undefined) + src.fstat(srcHandle, tryStat); + else + tryStat(null, { size: fileSize }); - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + function tryStat(err, attrs) { + if (err) { + if (src !== fs) { + // Try stat() for sftp servers that may not support fstat() for + // whatever reason + src.stat(srcPath, (err_, attrs_) => { + if (err_) + return onerror(err); + tryStat(null, attrs_); + }); + return; } - resolve(self.getService(data.ID || data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self.getService(data.ID || data.Id)); - }); - } -}; + return onerror(err); + } + fsize = attrs.size; -/** - * Lists volumes - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listVolumes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + dst.open(dstPath, 'w', (err, destHandle) => { + if (err) + return onerror(err); - var optsf = { - path: '/volumes?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; + dstHandle = destHandle; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + if (fsize <= 0) + return onerror(); -/** - * Creates a new network - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createNetwork = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/networks/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'driver not found', - 500: 'server error' - } - }; + // Use less memory where possible + while (bufsize > fsize) { + if (concurrency === 1) { + bufsize = fsize; + break; + } + bufsize -= chunkSize; + --concurrency; + } + readbuf = tryCreateBuffer(bufsize); + if (readbuf instanceof Error) + return onerror(readbuf); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + if (mode !== undefined) { + dst.fchmod(dstHandle, mode, function tryAgain(err) { + if (err) { + // Try chmod() for sftp servers that may not support fchmod() + // for whatever reason + dst.chmod(dstPath, mode, (err_) => tryAgain()); + return; + } + startReads(); + }); + } else { + startReads(); } - resolve(self.getNetwork(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getNetwork(data.Id)); - }); - } -}; -/** - * Lists networks - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listNetworks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + function onread(err, nb, data, dstpos, datapos, origChunkLen) { + if (err) + return onerror(err); - var optsf = { - path: '/networks?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; + datapos = datapos || 0; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); -/** - * Search images - * @param {Object} opts Options - * @param {Function} callback Callback - */ -Docker.prototype.searchImages = function(opts, callback) { - var self = this; - var optsf = { - path: '/images/search?', - method: 'GET', - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + function writeCb(err) { + if (err) + return onerror(err); - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; + total += nb; + onstep && onstep(total, nb, fsize); -/** - * Info - * @param {Object} opts Options (optional) - * @param {Function} callback Callback with info - */ -Docker.prototype.info = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (nb < origChunkLen) + return singleRead(datapos, dstpos + nb, origChunkLen - nb); - var opts = { - path: '/info', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + if (total === fsize) { + dst.close(dstHandle, (err) => { + dstHandle = undefined; + if (err) + return onerror(err); + src.close(srcHandle, (err) => { + srcHandle = undefined; + if (err) + return onerror(err); + cb(); + }); + }); + return; + } + if (pdst >= fsize) + return; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); + const chunk = + (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); + singleRead(datapos, pdst, chunk); + pdst += chunk; + } } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } -}; -/** - * Version - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.version = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + function makeCb(psrc, pdst, chunk) { + return (err, nb, data) => { + onread(err, nb, data, pdst, psrc, chunk); + }; + } - var opts = { - path: '/version', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + function singleRead(psrc, pdst, chunk) { + src.read(srcHandle, + readbuf, + psrc, + chunk, + pdst, + makeCb(psrc, pdst, chunk)); + } - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); + function startReads() { + let reads = 0; + let psrc = 0; + while (pdst < fsize && reads < concurrency) { + const chunk = + (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); + singleRead(psrc, pdst, chunk); + psrc += chunk; + pdst += chunk; + ++reads; + } } - resolve(data); }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); + } + }); +} + +function writeAll(sftp, handle, buffer, offset, length, position, callback_) { + const callback = (typeof callback_ === 'function' ? callback_ : undefined); + + sftp.write(handle, + buffer, + offset, + length, + position, + (writeErr, written) => { + if (writeErr) { + return sftp.close(handle, () => { + callback && callback(writeErr); + }); + } + if (written === length) { + sftp.close(handle, callback); + } else { + offset += written; + length -= written; + position += written; + writeAll(sftp, handle, buffer, offset, length, position, callback); + } + }); +} + +class Stats { + constructor(initial) { + this.mode = (initial && initial.mode); + this.uid = (initial && initial.uid); + this.gid = (initial && initial.gid); + this.size = (initial && initial.size); + this.atime = (initial && initial.atime); + this.mtime = (initial && initial.mtime); + this.extended = (initial && initial.extended); } -}; + isDirectory() { + return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); + } + isFile() { + return ((this.mode & constants.S_IFMT) === constants.S_IFREG); + } + isBlockDevice() { + return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); + } + isCharacterDevice() { + return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); + } + isSymbolicLink() { + return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); + } + isFIFO() { + return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); + } + isSocket() { + return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); + } +} -/** - * Ping - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.ping = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +function attrsToBytes(attrs) { + let flags = 0; + let nb = 0; - var optsf = { - path: '/_ping', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + if (typeof attrs === 'object' && attrs !== null) { + if (typeof attrs.size === 'number') { + flags |= ATTR.SIZE; + const val = attrs.size; + // Big Endian + ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 + ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 + ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 + ATTRS_BUF[nb++] = val / 4294967296; // 2**32 + ATTRS_BUF[nb++] = val / 16777216; // 2**24 + ATTRS_BUF[nb++] = val / 65536; // 2**16 + ATTRS_BUF[nb++] = val / 256; // 2**8 + ATTRS_BUF[nb++] = val; } - }; + if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { + flags |= ATTR.UIDGID; + const uid = attrs.uid; + const gid = attrs.gid; + // Big Endian + ATTRS_BUF[nb++] = uid >>> 24; + ATTRS_BUF[nb++] = uid >>> 16; + ATTRS_BUF[nb++] = uid >>> 8; + ATTRS_BUF[nb++] = uid; + ATTRS_BUF[nb++] = gid >>> 24; + ATTRS_BUF[nb++] = gid >>> 16; + ATTRS_BUF[nb++] = gid >>> 8; + ATTRS_BUF[nb++] = gid; + } + if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { + const mode = modeNum(attrs.mode); + flags |= ATTR.PERMISSIONS; + // Big Endian + ATTRS_BUF[nb++] = mode >>> 24; + ATTRS_BUF[nb++] = mode >>> 16; + ATTRS_BUF[nb++] = mode >>> 8; + ATTRS_BUF[nb++] = mode; + } + if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) + && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { + const atime = toUnixTimestamp(attrs.atime); + const mtime = toUnixTimestamp(attrs.mtime); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + flags |= ATTR.ACMODTIME; + // Big Endian + ATTRS_BUF[nb++] = atime >>> 24; + ATTRS_BUF[nb++] = atime >>> 16; + ATTRS_BUF[nb++] = atime >>> 8; + ATTRS_BUF[nb++] = atime; + ATTRS_BUF[nb++] = mtime >>> 24; + ATTRS_BUF[nb++] = mtime >>> 16; + ATTRS_BUF[nb++] = mtime >>> 8; + ATTRS_BUF[nb++] = mtime; + } + // TODO: extended attributes } + + return { flags, nb }; +} + +function toUnixTimestamp(time) { + // eslint-disable-next-line no-self-compare + if (typeof time === 'number' && time === time) // Valid, non-NaN number + return time; + if (isDate(time)) + return parseInt(time.getTime() / 1000, 10); + throw new Error(`Cannot parse time: ${time}`); +} + +function modeNum(mode) { + // eslint-disable-next-line no-self-compare + if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number + return mode; + if (typeof mode === 'string') + return modeNum(parseInt(mode, 8)); + throw new Error(`Cannot parse mode: ${mode}`); +} + +const stringFlagMap = { + 'r': OPEN_MODE.READ, + 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, + 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, + 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, + 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE + | OPEN_MODE.EXCL, + 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE + | OPEN_MODE.EXCL, + 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, + 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, + 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE + | OPEN_MODE.EXCL, + 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE + | OPEN_MODE.EXCL }; -/** - * SystemDf equivalent to system/df API Engine - * get usage data information - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.df = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +function stringToFlags(str) { + const flags = stringFlagMap[str]; + return (flags !== undefined ? flags : null); +} - var optsf = { - path: '/system/df', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' +const flagsToString = (() => { + const stringFlagMapKeys = Object.keys(stringFlagMap); + return (flags) => { + for (let i = 0; i < stringFlagMapKeys.length; ++i) { + const key = stringFlagMapKeys[i]; + if (stringFlagMap[key] === flags) + return key; } + return null; }; +})(); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +function readAttrs(biOpt) { + /* + uint32 flags + uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE + uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID + uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID + uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS + uint32 atime present only if flag SSH_FILEXFER_ACMODTIME + uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME + uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED + string extended_type + string extended_data + ... more extended data (extended_type - extended_data pairs), + so that number of pairs equals extended_count + */ + const flags = bufferParser.readUInt32BE(); + if (flags === undefined) + return; + + const attrs = new Stats(); + if (flags & ATTR.SIZE) { + const size = bufferParser.readUInt64BE(biOpt); + if (size === undefined) + return; + attrs.size = size; } -}; -/** - * Events - * @param {Object} opts Events options, like 'since' (optional) - * @param {Function} callback Callback - */ -Docker.prototype.getEvents = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (flags & ATTR.UIDGID) { + const uid = bufferParser.readUInt32BE(); + const gid = bufferParser.readUInt32BE(); + if (gid === undefined) + return; + attrs.uid = uid; + attrs.gid = gid; + } - var optsf = { - path: '/events?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' + if (flags & ATTR.PERMISSIONS) { + const mode = bufferParser.readUInt32BE(); + if (mode === undefined) + return; + attrs.mode = mode; + } + + if (flags & ATTR.ACMODTIME) { + const atime = bufferParser.readUInt32BE(); + const mtime = bufferParser.readUInt32BE(); + if (mtime === undefined) + return; + attrs.atime = atime; + attrs.mtime = mtime; + } + + if (flags & ATTR.EXTENDED) { + const count = bufferParser.readUInt32BE(); + if (count === undefined) + return; + const extended = {}; + for (let i = 0; i < count; ++i) { + const type = bufferParser.readString(true); + const data = bufferParser.readString(); + if (data === undefined) + return; + extended[type] = data; } - }; + attrs.extended = extended; + } - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + return attrs; +} + +function sendOrBuffer(sftp, payload) { + const ret = tryWritePayload(sftp, payload); + if (ret !== undefined) { + sftp._buffer.push(ret); + return false; } -}; + return true; +} -/** - * Pull is a wrapper around createImage, parsing image's tags. - * @param {String} repoTag Repository tag - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @param {Object} auth Authentication (optional) - * @return {Object} Image - */ -Docker.prototype.pull = function(repoTag, opts, callback, auth) { - var args = util.processArgs(opts, callback); +function tryWritePayload(sftp, payload) { + const outgoing = sftp.outgoing; + if (outgoing.state !== 'open') + return; - var imageSrc = util.parseRepositoryTag(repoTag); - args.opts.fromImage = imageSrc.repository; - args.opts.tag = imageSrc.tag || 'latest'; + if (outgoing.window === 0) { + sftp._waitWindow = true; + sftp._chunkcb = drainBuffer; + return payload; + } - var argsf = [args.opts, args.callback]; - if (auth) { - argsf = [auth, args.opts, args.callback]; + let ret; + const len = payload.length; + let p = 0; + + while (len - p > 0 && outgoing.window > 0) { + const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); + outgoing.window -= actualLen; + if (outgoing.window === 0) { + sftp._waitWindow = true; + sftp._chunkcb = drainBuffer; + } + + if (p === 0 && actualLen === len) { + sftp._protocol.channelData(sftp.outgoing.id, payload); + } else { + sftp._protocol.channelData(sftp.outgoing.id, + bufferSlice(payload, p, p + actualLen)); + } + + p += actualLen; } - return this.createImage.apply(this, argsf); -}; -/** - * Like run command from Docker's CLI - * @param {String} image Image name to be used. - * @param {Array} cmd Command to run in array format. - * @param {Object} streamo Output stream - * @param {Object} createOptions Container create options (optional) - * @param {Object} startOptions Container start options (optional) - * @param {Function} callback Callback - * @return {Object} EventEmitter - */ -Docker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (typeof arguments[arguments.length - 1] === 'function') { - return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback); - } else { - return this.runPromise(image, cmd, streamo, createOptions, startOptions); + if (len - p > 0) { + if (p > 0) + ret = bufferSlice(payload, p, len); + else + ret = payload; // XXX: should never get here? } -}; + return ret; +} -Docker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (!callback && typeof createOptions === 'function') { - callback = createOptions; - createOptions = {}; - startOptions = {}; - } else if (!callback && typeof startOptions === 'function') { - callback = startOptions; - startOptions = {}; +function drainBuffer() { + this._chunkcb = undefined; + const buffer = this._buffer; + let i = 0; + while (i < buffer.length) { + const payload = buffer[i]; + const ret = tryWritePayload(this, payload); + if (ret !== undefined) { + if (ret !== payload) + buffer[i] = ret; + if (i > 0) + this._buffer = buffer.slice(i); + return; + } + ++i; } + if (i > 0) + this._buffer = []; +} - var hub = new EventEmitter(); +function doFatalSFTPError(sftp, msg, noDebug) { + const err = new Error(msg); + err.level = 'sftp-protocol'; + if (!noDebug && sftp._debug) + sftp._debug(`SFTP: Inbound: ${msg}`); + sftp.emit('error', err); + sftp.destroy(); + cleanupRequests(sftp); + return false; +} - function handler(err, container) { - if (err) return callback(err, null, container); +function cleanupRequests(sftp) { + const keys = Object.keys(sftp._requests); + if (keys.length === 0) + return; - hub.emit('container', container); + const reqs = sftp._requests; + sftp._requests = {}; + const err = new Error('No response from server'); + for (let i = 0; i < keys.length; ++i) { + const req = reqs[keys[i]]; + if (typeof req.cb === 'function') + req.cb(err); + } +} - container.attach({ - stream: true, - stdout: true, - stderr: true - }, function handler(err, stream) { - if (err) return callback(err, null, container); +function requestLimits(sftp, cb) { + /* + uint32 id + string "limits@openssh.com" + */ + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); - hub.emit('stream', stream); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if (streamo) { - if (streamo instanceof Array) { - stream.on('end', function() { - try { - streamo[0].end(); - } catch (e) {} - try { - streamo[1].end(); - } catch (e) {} - }); - container.modem.demuxStream(stream, streamo[0], streamo[1]); - } else { - stream.setEncoding('utf8'); - stream.pipe(streamo, { - end: true - }); - } - } + writeUInt32BE(buf, 18, p); + buf.utf8Write('limits@openssh.com', p += 4, 18); - container.start(startOptions, function(err, data) { - if (err) return callback(err, data, container); - hub.emit('start', container); + sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; - container.wait(function(err, data) { - hub.emit('data', data); - callback(err, data, container); - }); - }); - }); + const isBuffered = sendOrBuffer(sftp, buf); + if (sftp._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); } +} - var optsc = { - 'Hostname': '', - 'User': '', - 'AttachStdin': false, - 'AttachStdout': true, - 'AttachStderr': true, - 'Tty': true, - 'OpenStdin': false, - 'StdinOnce': false, - 'Env': null, - 'Cmd': cmd, - 'Image': image, - 'Volumes': {}, - 'VolumesFrom': [] - }; +const CLIENT_HANDLERS = { + [RESPONSE.VERSION]: (sftp, payload) => { + if (sftp._version !== -1) + return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); - extend(optsc, createOptions); + const extensions = {}; - this.createContainer(optsc, handler); + /* + uint32 version + + */ + bufferParser.init(payload, 1); + let version = bufferParser.readUInt32BE(); + while (bufferParser.avail()) { + const extName = bufferParser.readString(true); + const extData = bufferParser.readString(true); + if (extData === undefined) { + version = undefined; + break; + } + extensions[extName] = extData; + } + bufferParser.clear(); - return hub; -}; + if (version === undefined) + return doFatalSFTPError(sftp, 'Malformed VERSION packet'); -Docker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) { - var self = this; + if (sftp._debug) { + const names = Object.keys(extensions); + if (names.length) { + sftp._debug( + `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` + ); + } else { + sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); + } + } - createOptions = createOptions || {}; - startOptions = startOptions || {}; + sftp._version = version; + sftp._extensions = extensions; - var optsc = { - 'Hostname': '', - 'User': '', - 'AttachStdin': false, - 'AttachStdout': true, - 'AttachStderr': true, - 'Tty': true, - 'OpenStdin': false, - 'StdinOnce': false, - 'Env': null, - 'Cmd': cmd, - 'Image': image, - 'Volumes': {}, - 'VolumesFrom': [] - }; + if (extensions['limits@openssh.com'] === '1') { + return requestLimits(sftp, (err, limits) => { + if (!err) { + if (limits.maxPktLen > 0) + sftp._maxOutPktLen = limits.maxPktLen; + if (limits.maxReadLen > 0) + sftp._maxReadLen = limits.maxReadLen; + if (limits.maxWriteLen > 0) + sftp._maxWriteLen = limits.maxWriteLen; + sftp.maxOpenHandles = ( + limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity + ); + } + sftp.emit('ready'); + }); + } - extend(optsc, createOptions); + sftp.emit('ready'); + }, + [RESPONSE.STATUS]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + uint32 error/status code + string error message (ISO-10646 UTF-8) + string language tag + */ + const errorCode = bufferParser.readUInt32BE(); + const errorMsg = bufferParser.readString(true); + bufferParser.clear(); - var containero; + // Note: we avoid checking that the error message and language tag are in + // the packet because there are some broken implementations that incorrectly + // omit them. The language tag in general was never really used amongst ssh + // implementations, so in the case of a missing error message we just + // default to something sensible. - return new this.modem.Promise(function(resolve, reject) { - self.createContainer(optsc).then(function(container) { - containero = container; - return container.attach({ - stream: true, - stdout: true, - stderr: true - }); - }).then(function(stream) { - if (streamo) { - if (streamo instanceof Array) { - stream.on('end', function() { - try { - streamo[0].end(); - } catch (e) {} - try { - streamo[1].end(); - } catch (e) {} - }); - containero.modem.demuxStream(stream, streamo[0], streamo[1]); - } else { - stream.setEncoding('utf8'); - stream.pipe(streamo, { - end: true - }); - } + if (sftp._debug) { + const jsonMsg = JSON.stringify(errorMsg); + sftp._debug( + `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` + ); + } + const req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + if (req && typeof req.cb === 'function') { + if (errorCode === STATUS_CODE.OK) { + req.cb(); + return; } - return containero.start(startOptions); - }).then(function(data) { - return containero.wait(); - }).then(function(data) { - resolve([data, containero]); - }).catch(function(err) { - reject(err); - }); - }); -}; + const err = new Error(errorMsg + || STATUS_CODE_STR[errorCode] + || 'Unknown status'); + err.code = errorCode; + req.cb(err); + } + }, + [RESPONSE.HANDLE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + */ + const handle = bufferParser.readString(); + bufferParser.clear(); -/** - * Init swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmInit = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (handle === undefined) { + if (reqID !== undefined) + delete sftp._requests[reqID]; + return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); + } - var optsf = { - path: '/swarm/init', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; + sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + const req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + if (req && typeof req.cb === 'function') + req.cb(undefined, handle); + }, + [RESPONSE.DATA]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== undefined) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + /* + string data + */ + if (req && typeof req.cb === 'function') { + if (req.buffer) { + // We have already pre-allocated space to store the data -/** - * Join swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmJoin = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + const nb = bufferParser.readString(req.buffer); + bufferParser.clear(); - var optsf = { - path: '/swarm/join', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; + if (nb !== undefined) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` + ); + req.cb(undefined, req.buffer, nb); + return; + } + } else { + const data = bufferParser.readString(); + bufferParser.clear(); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + if (data !== undefined) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` + ); + req.cb(undefined, data); + return; } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + } + } else { + const nb = bufferParser.skipString(); + bufferParser.clear(); + if (nb !== undefined) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` + ); + return; + } + } -/** - * Leave swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmLeave = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + return doFatalSFTPError(sftp, 'Malformed DATA packet'); + }, + [RESPONSE.NAME]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== undefined) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + /* + uint32 count + repeats count times: + string filename + string longname + ATTRS attrs + */ + const count = bufferParser.readUInt32BE(); + if (count !== undefined) { + let names = []; + for (let i = 0; i < count; ++i) { + // We are going to assume UTF-8 for filenames despite the SFTPv3 + // spec not specifying an encoding because the specs for newer + // versions of the protocol all explicitly specify UTF-8 for + // filenames + const filename = bufferParser.readString(true); - var optsf = { - path: '/swarm/leave?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: 'node is not part of a Swarm' - }, - options: args.opts - }; + // `longname` only exists in SFTPv3 and since it typically will + // contain the filename, we assume it is also UTF-8 + const longname = bufferParser.readString(true); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + const attrs = readAttrs(sftp._biOpt); + if (attrs === undefined) { + names = undefined; + break; } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + names.push({ filename, longname, attrs }); + } + if (names !== undefined) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` + ); + bufferParser.clear(); + if (req && typeof req.cb === 'function') + req.cb(undefined, names); + return; + } + } -/** - * Update swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmUpdate = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + bufferParser.clear(); + return doFatalSFTPError(sftp, 'Malformed NAME packet'); + }, + [RESPONSE.ATTRS]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== undefined) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + /* + ATTRS attrs + */ + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); + if (attrs !== undefined) { + sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); + if (req && typeof req.cb === 'function') + req.cb(undefined, attrs); + return; + } - var optsf = { - path: '/swarm/update?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; + return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); + }, + [RESPONSE.EXTENDED]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + if (reqID !== undefined) { + const req = sftp._requests[reqID]; + if (req) { + delete sftp._requests[reqID]; + switch (req.extended) { + case 'statvfs@openssh.com': + case 'fstatvfs@openssh.com': { + /* + uint64 f_bsize // file system block size + uint64 f_frsize // fundamental fs block size + uint64 f_blocks // number of blocks (unit f_frsize) + uint64 f_bfree // free blocks in file system + uint64 f_bavail // free blocks for non-root + uint64 f_files // total file inodes + uint64 f_ffree // free file inodes + uint64 f_favail // free file inodes for to non-root + uint64 f_fsid // file system id + uint64 f_flag // bit mask of f_flag values + uint64 f_namemax // maximum filename length + */ + const biOpt = sftp._biOpt; + const stats = { + f_bsize: bufferParser.readUInt64BE(biOpt), + f_frsize: bufferParser.readUInt64BE(biOpt), + f_blocks: bufferParser.readUInt64BE(biOpt), + f_bfree: bufferParser.readUInt64BE(biOpt), + f_bavail: bufferParser.readUInt64BE(biOpt), + f_files: bufferParser.readUInt64BE(biOpt), + f_ffree: bufferParser.readUInt64BE(biOpt), + f_favail: bufferParser.readUInt64BE(biOpt), + f_sid: bufferParser.readUInt64BE(biOpt), + f_flag: bufferParser.readUInt64BE(biOpt), + f_namemax: bufferParser.readUInt64BE(biOpt), + }; + if (stats.f_namemax === undefined) + break; + if (sftp._debug) { + sftp._debug( + 'SFTP: Inbound: Received EXTENDED_REPLY ' + + `(id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === 'function') + req.cb(undefined, stats); + return; + } + case 'limits@openssh.com': { + /* + uint64 max-packet-length + uint64 max-read-length + uint64 max-write-length + uint64 max-open-handles + */ + const limits = { + maxPktLen: bufferParser.readUInt64BE(), + maxReadLen: bufferParser.readUInt64BE(), + maxWriteLen: bufferParser.readUInt64BE(), + maxOpenHandles: bufferParser.readUInt64BE(), + }; + if (limits.maxOpenHandles === undefined) + break; + if (sftp._debug) { + sftp._debug( + 'SFTP: Inbound: Received EXTENDED_REPLY ' + + `(id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === 'function') + req.cb(undefined, limits); + return; + } + case 'users-groups-by-id@openssh.com': { + /* + string usernames + string username1 + ... + string groupnames + string groupname1 + ... + */ + const usernameCount = bufferParser.readUInt32BE(); + if (usernameCount === undefined) + break; + const usernames = new Array(usernameCount); + for (let i = 0; i < usernames.length; ++i) + usernames[i] = bufferParser.readString(true); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + const groupnameCount = bufferParser.readUInt32BE(); + if (groupnameCount === undefined) + break; + const groupnames = new Array(groupnameCount); + for (let i = 0; i < groupnames.length; ++i) + groupnames[i] = bufferParser.readString(true); + if (groupnames.length > 0 + && groupnames[groupnames.length - 1] === undefined) { + break; + } + + if (sftp._debug) { + sftp._debug( + 'SFTP: Inbound: Received EXTENDED_REPLY ' + + `(id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === 'function') + req.cb(undefined, usernames, groupnames); + return; + } + default: + // Unknown extended request + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` + ); + bufferParser.clear(); + if (typeof req.cb === 'function') + req.cb(); + return; } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + } else { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` + ); + bufferParser.clear(); + return; + } + } + bufferParser.clear(); + return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); + }, +}; +const SERVER_HANDLERS = { + [REQUEST.INIT]: (sftp, payload) => { + if (sftp._version !== -1) + return doFatalSFTPError(sftp, 'Duplicate INIT packet'); -/** - * Inspect a Swarm. - * Warning: This method is not documented in the API - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.swarmInspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + const extensions = {}; - var optsf = { - path: '/swarm', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: 'This node is not a swarm manager', - 500: 'server error' + /* + uint32 version + + */ + bufferParser.init(payload, 1); + let version = bufferParser.readUInt32BE(); + while (bufferParser.avail()) { + const extName = bufferParser.readString(true); + const extData = bufferParser.readString(true); + if (extData === undefined) { + version = undefined; + break; + } + extensions[extName] = extData; } - }; + bufferParser.clear(); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + if (version === undefined) + return doFatalSFTPError(sftp, 'Malformed INIT packet'); -Docker.Container = Container; -Docker.Image = Image; -Docker.Volume = Volume; -Docker.Network = Network; -Docker.Service = Service; -Docker.Plugin = Plugin; -Docker.Secret = Secret; -Docker.Task = Task; -Docker.Node = Node; -Docker.Exec = Exec; + if (sftp._debug) { + const names = Object.keys(extensions); + if (names.length) { + sftp._debug( + `SFTP: Inbound: Received INIT (v${version}, exts:${names})` + ); + } else { + sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); + } + } -module.exports = Docker; + sendOrBuffer(sftp, SERVER_VERSION_BUFFER); + sftp._version = version; + sftp._extensions = extensions; + sftp.emit('ready'); + }, + [REQUEST.OPEN]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string filename + uint32 pflags + ATTRS attrs + */ + const filename = bufferParser.readString(true); + const pflags = bufferParser.readUInt32BE(); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); -/***/ }), + if (attrs === undefined) + return doFatalSFTPError(sftp, 'Malformed OPEN packet'); -/***/ 3149: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); -var util = __nccwpck_require__(1604); + if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.CLOSE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + */ + const handle = bufferParser.readString(); + bufferParser.clear(); -/** - * Represents an Exec - * @param {Object} modem docker-modem - * @param {String} id Exec's ID - */ -var Exec = function(modem, id) { - this.modem = modem; - this.id = id; -}; + if (handle === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); -Exec.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); -/** - * Start the exec call that was setup. - * - * @param {object} opts - * @param {function} callback - */ -Exec.prototype.start = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (!sftp.emit('CLOSE', reqID, handle)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.READ]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + uint64 offset + uint32 len + */ + const handle = bufferParser.readString(); + const offset = bufferParser.readUInt64BE(sftp._biOpt); + const len = bufferParser.readUInt32BE(); + bufferParser.clear(); - var optsf = { - path: '/exec/' + this.id + '/start', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - allowEmpty: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 204: true, - 404: 'no such exec', - 409: 'container stopped/paused', - 500: 'container not running' - }, - options: args.opts - }; + if (len === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed READ packet'); + sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; + if (!sftp.emit('READ', reqID, handle, offset, len)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.WRITE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + uint64 offset + string data + */ + const handle = bufferParser.readString(); + const offset = bufferParser.readUInt64BE(sftp._biOpt); + const data = bufferParser.readString(); + bufferParser.clear(); -/** - * Resize the exec call that was setup. - * - * @param {object} opts - * @param {function} callback - */ -Exec.prototype.resize = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (data === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed WRITE packet'); - var optsf = { - path: '/exec/' + this.id + '/resize?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such exec', - 500: 'container not running' - }, - options: args.opts - }; + sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; + if (!sftp.emit('WRITE', reqID, handle, offset, data)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.LSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); -/** - * Get low-level information about the exec call. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Exec.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); - var optsf = { - path: '/exec/' + this.id + '/json', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such exec', - 500: 'server error' + sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); + + if (!sftp.emit('LSTAT', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } - }; + }, + [REQUEST.FSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + */ + const handle = bufferParser.readString(); + bufferParser.clear(); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - args.callback(err, data); - }); - } -}; + if (handle === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); + sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); -module.exports = Exec; + if (!sftp.emit('FSTAT', reqID, handle)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.SETSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + ATTRS attrs + */ + const path = bufferParser.readString(true); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); + if (attrs === undefined) + return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); -/***/ }), + sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); -/***/ 6689: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!sftp.emit('SETSTAT', reqID, path, attrs)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.FSETSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + ATTRS attrs + */ + const handle = bufferParser.readString(); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); -var util = __nccwpck_require__(1604); + if (attrs === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); -/** - * Represents an image - * @param {Object} modem docker-modem - * @param {String} name Image's name - */ -var Image = function(modem, name) { - this.modem = modem; - this.name = name; -}; + sftp._debug && sftp._debug( + `SFTP: Inbound: Received FSETSTAT (id:${reqID})` + ); -Image.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.OPENDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); -/** - * Inspect - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Image.prototype.inspect = function(callback) { - var self = this; + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); - var opts = { - path: '/images/' + this.name + '/json', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' + sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); + + if (!sftp.emit('OPENDIR', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } - }; + }, + [REQUEST.READDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + */ + const handle = bufferParser.readString(); + bufferParser.clear(); - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } -}; + if (handle === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed READDIR packet'); -/** - * Distribution - * @param {Object} opts - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Image.prototype.distribution = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; + sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); - var fopts = { - path: '/distribution/' + this.name + '/json', - method: 'GET', - statusCodes: { - 200: true, - 401: 'no such image', - 500: 'server error' - }, - authconfig: (args.opts) ? args.opts.authconfig : undefined - }; + if (!sftp.emit('READDIR', reqID, handle)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.REMOVE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(fopts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(fopts, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); -/** - * History - * @param {Function} callback Callback - */ -Image.prototype.history = function(callback) { - var self = this; - var opts = { - path: '/images/' + this.name + '/history', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' + sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); + + if (!sftp.emit('REMOVE', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } - }; + }, + [REQUEST.MKDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + ATTRS attrs + */ + const path = bufferParser.readString(true); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } -}; + if (attrs === undefined) + return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); -/** - * Get - * @param {Function} callback Callback with data stream. - */ -Image.prototype.get = function(callback) { - var self = this; - var opts = { - path: '/images/' + this.name + '/get', - method: 'GET', - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' + sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); + + if (!sftp.emit('MKDIR', reqID, path, attrs)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } - }; + }, + [REQUEST.RMDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } -}; + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); -/** - * Push - * @param {Object} opts Push options, like 'registry' (optional) - * @param {Function} callback Callback with stream. - * @param {Object} auth Registry authentication - */ -Image.prototype.push = function(opts, callback, auth) { - var self = this; - var args = util.processArgs(opts, callback); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: '/images/' + this.name + '/push?', - method: 'POST', - options: args.opts, - authconfig: args.opts.authconfig || auth, - abortSignal: args.opts.abortSignal, - isStream: isStream, - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' + sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); + + if (!sftp.emit('RMDIR', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } - }; + }, + [REQUEST.REALPATH]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - delete optsf.options.authconfig; + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; + sftp._debug && sftp._debug( + `SFTP: Inbound: Received REALPATH (id:${reqID})` + ); -/** - * Tag - * @param {Object} opts Tag options, like 'repo' (optional) - * @param {Function} callback Callback - */ -Image.prototype.tag = function(opts, callback) { - var self = this; - var optsf = { - path: '/images/' + this.name + '/tag?', - method: 'POST', - options: opts, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 400: 'bad parameter', - 404: 'no such image', - 409: 'conflict', - 500: 'server error' + if (!sftp.emit('REALPATH', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } - }; + }, + [REQUEST.STAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed STAT packet'); -/** - * Removes the image - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Image.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); - var optsf = { - path: '/images/' + this.name + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such image', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; + if (!sftp.emit('STAT', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.RENAME]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string oldpath + string newpath + */ + const oldPath = bufferParser.readString(true); + const newPath = bufferParser.readString(true); + bufferParser.clear(); + if (newPath === undefined) + return doFatalSFTPError(sftp, 'Malformed RENAME packet'); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); -module.exports = Image; + if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.READLINK]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed READLINK packet'); -/***/ }), + sftp._debug && sftp._debug( + `SFTP: Inbound: Received READLINK (id:${reqID})` + ); -/***/ 9780: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!sftp.emit('READLINK', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.SYMLINK]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string linkpath + string targetpath + */ + const linkPath = bufferParser.readString(true); + const targetPath = bufferParser.readString(true); + bufferParser.clear(); -var util = __nccwpck_require__(1604); + if (targetPath === undefined) + return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); -/** - * Represents an network - * @param {Object} modem docker-modem - * @param {String} id Network's id - */ -var Network = function(modem, id) { - this.modem = modem; - this.id = id; -}; + sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); -Network.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + let handled; + if (sftp._isOpenSSH) { + // OpenSSH has linkpath and targetpath positions switched + handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); + } else { + handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); + } + if (!handled) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.EXTENDED]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string extended-request + ... any request-specific data ... + */ + const extName = bufferParser.readString(true); + if (extName === undefined) { + bufferParser.clear(); + return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); + } -/** - * Inspect - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Id only if callback isn't specified. - */ -Network.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + let extData; + if (bufferParser.avail()) + extData = bufferParser.readRaw(); + bufferParser.clear(); - var opts = { - path: '/networks/' + this.id + '?', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such network', - 500: 'server error' - }, - options: args.opts - }; + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED (id:${reqID})` + ); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } + if (!sftp.emit('EXTENDED', reqID, extName, extData)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, }; -/** - * Removes the network - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Network.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +// ============================================================================= +// ReadStream/WriteStream-related ============================================== +// ============================================================================= +const { + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE, + validateNumber +} = __nccwpck_require__(7609); - var optsf = { - path: '/networks/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such network', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; +const kMinPoolSpace = 128; +let pool; +// It can happen that we expect to read a large chunk of data, and reserve +// a large chunk of the pool accordingly, but the read() call only filled +// a portion of it. If a concurrently executing read() then uses the same pool, +// the "reserved" portion cannot be used, so we allow it to be re-used as a +// new pool later. +const poolFragments = []; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; +function allocNewPool(poolSize) { + if (poolFragments.length > 0) + pool = poolFragments.pop(); + else + pool = Buffer.allocUnsafe(poolSize); + pool.used = 0; +} -/** - * Connects a container to a network - * @param {[Object]} opts Connect options (optional) - * @param {Function} callback Callback - */ -Network.prototype.connect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +// Check the `this.start` and `this.end` of stream. +function checkPosition(pos, name) { + if (!Number.isSafeInteger(pos)) { + validateNumber(pos, name); + if (!Number.isInteger(pos)) + throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); + throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); + } + if (pos < 0) + throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); +} - var optsf = { - path: '/networks/' + this.id + '/connect', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: 'network or container is not found', - 500: 'server error' - }, - options: args.opts - }; +function roundUpToMultipleOf8(n) { + return (n + 7) & ~7; // Align to 8 byte boundary. +} - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; +function ReadStream(sftp, path, options) { + if (options === undefined) + options = {}; + else if (typeof options === 'string') + options = { encoding: options }; + else if (options === null || typeof options !== 'object') + throw new TypeError('"options" argument must be a string or an object'); + else + options = Object.create(options); + // A little bit bigger buffer and water marks by default + if (options.highWaterMark === undefined) + options.highWaterMark = 64 * 1024; -/** - * Disconnects a container from a network - * @param {[Object]} opts Disconnect options (optional) - * @param {Function} callback Callback - */ -Network.prototype.disconnect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // For backwards compat do not emit close on destroy. + options.emitClose = false; + options.autoDestroy = false; // Node 14 major change. - var optsf = { - path: '/networks/' + this.id + '/disconnect', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: 'network or container is not found', - 500: 'server error' - }, - options: args.opts - }; + ReadableStream.call(this, options); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + this.path = path; + this.flags = options.flags === undefined ? 'r' : options.flags; + this.mode = options.mode === undefined ? 0o666 : options.mode; + this.start = options.start; + this.end = options.end; + this.autoClose = options.autoClose === undefined ? true : options.autoClose; + this.pos = 0; + this.bytesRead = 0; + this.isClosed = false; + this.handle = options.handle === undefined ? null : options.handle; + this.sftp = sftp; + this._opening = false; + if (this.start !== undefined) { + checkPosition(this.start, 'start'); -module.exports = Network; + this.pos = this.start; + } + if (this.end === undefined) { + this.end = Infinity; + } else if (this.end !== Infinity) { + checkPosition(this.end, 'end'); -/***/ }), + if (this.start !== undefined && this.start > this.end) { + throw new ERR_OUT_OF_RANGE( + 'start', + `<= "end" (here: ${this.end})`, + this.start + ); + } + } -/***/ 2297: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.on('end', function() { + if (this.autoClose) + this.destroy(); + }); -var util = __nccwpck_require__(1604); + if (!Buffer.isBuffer(this.handle)) + this.open(); +} +inherits(ReadStream, ReadableStream); -/** - * Represents an Node - * @param {Object} modem docker-modem - * @param {String} id Node's ID - */ -var Node = function(modem, id) { - this.modem = modem; - this.id = id; -}; +ReadStream.prototype.open = function() { + if (this._opening) + return; -Node.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + this._opening = true; -/** - * Query Docker for Node details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Node.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { + this._opening = false; - var optsf = { - path: '/nodes/' + this.id, - method: 'GET', - abortSignal: args.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 500: 'server error' + if (er) { + this.emit('error', er); + if (this.autoClose) + this.destroy(); + return; } - }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + this.handle = handle; + this.emit('open', handle); + this.emit('ready'); + // Start the flow of data. + this.read(); + }); }; +ReadStream.prototype._read = function(n) { + if (!Buffer.isBuffer(this.handle)) + return this.once('open', () => this._read(n)); -/** - * Update a node. - * - * @param {object} opts - * @param {function} callback - */ -Node.prototype.update = function(opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; + // XXX: safe to remove this? + if (this.destroyed) + return; + + if (!pool || pool.length - pool.used < kMinPoolSpace) { + // Discard the old pool. + allocNewPool(this.readableHighWaterMark + || this._readableState.highWaterMark); } - var optsf = { - path: '/nodes/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 406: 'node is not part of a swarm', - 500: 'server error' - }, - options: opts - }; + // Grab another reference to the pool in the case that while we're + // in the thread pool another read() finishes up the pool, and + // allocates a new one. + const thisPool = pool; + let toRead = Math.min(pool.length - pool.used, n); + const start = pool.used; + + if (this.end !== undefined) + toRead = Math.min(this.end - this.pos + 1, toRead); + + // Already read everything we were supposed to read! + // treat as EOF. + if (toRead <= 0) + return this.push(null); + + // the actual read. + this.sftp.read(this.handle, + pool, + pool.used, + toRead, + this.pos, + (er, bytesRead) => { + if (er) { + this.emit('error', er); + if (this.autoClose) + this.destroy(); + return; + } + let b = null; + + // Now that we know how much data we have actually read, re-wind the + // 'used' field if we can, and otherwise allow the remainder of our + // reservation to be used as a new pool later. + if (start + toRead === thisPool.used && thisPool === pool) { + thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); + } else { + // Round down to the next lowest multiple of 8 to ensure the new pool + // fragment start and end positions are aligned to an 8 byte boundary. + const alignedEnd = (start + toRead) & ~7; + const alignedStart = roundUpToMultipleOf8(start + bytesRead); + if (alignedEnd - alignedStart >= kMinPoolSpace) + poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); + } - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; + if (bytesRead > 0) { + this.bytesRead += bytesRead; + b = thisPool.slice(start, start + bytesRead); + } + // Move the pool positions, and internal position for reading. + this.pos += bytesRead; -/** - * Remove a Node. - * Warning: This method is not documented in the API. - * - * @param {object} opts - * @param {function} callback - */ -Node.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + this.push(b); + }); - var optsf = { - path: '/nodes/' + this.id + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 500: 'server error' - }, - options: args.opts - }; + pool.used = roundUpToMultipleOf8(pool.used + toRead); +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +ReadStream.prototype._destroy = function(err, cb) { + if (this._opening && !Buffer.isBuffer(this.handle)) { + this.once('open', closeStream.bind(null, this, cb, err)); + return; } -}; + closeStream(this, cb, err); + this.handle = null; + this._opening = false; +}; -module.exports = Node; +function closeStream(stream, cb, err) { + if (!stream.handle) + return onclose(); + stream.sftp.close(stream.handle, onclose); -/***/ }), + function onclose(er) { + er = er || err; + cb(er); + stream.isClosed = true; + if (!er) + stream.emit('close'); + } +} -/***/ 6606: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +ReadStream.prototype.close = function(cb) { + this.destroy(null, cb); +}; -var util = __nccwpck_require__(1604); +Object.defineProperty(ReadStream.prototype, 'pending', { + get() { + return this.handle === null; + }, + configurable: true +}); -/** - * Represents a plugin - * @param {Object} modem docker-modem - * @param {String} name Plugin's name - */ -var Plugin = function(modem, name, remote) { - this.modem = modem; - this.name = name; - this.remote = remote || name; -}; +// TODO: add `concurrency` setting to allow more than one in-flight WRITE +// request to server to improve throughput +function WriteStream(sftp, path, options) { + if (options === undefined) + options = {}; + else if (typeof options === 'string') + options = { encoding: options }; + else if (options === null || typeof options !== 'object') + throw new TypeError('"options" argument must be a string or an object'); + else + options = Object.create(options); -Plugin.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + // For backwards compat do not emit close on destroy. + options.emitClose = false; + options.autoDestroy = false; // Node 14 major change. -/** - * Inspect - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Plugin.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + WritableStream.call(this, options); - var optsf = { - path: '/plugins/' + this.name, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin is not installed', - 500: 'server error' - } - }; + this.path = path; + this.flags = options.flags === undefined ? 'w' : options.flags; + this.mode = options.mode === undefined ? 0o666 : options.mode; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + this.start = options.start; + this.autoClose = options.autoClose === undefined ? true : options.autoClose; + this.pos = 0; + this.bytesWritten = 0; + this.isClosed = false; -/** - * Removes the plugin - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + this.handle = options.handle === undefined ? null : options.handle; + this.sftp = sftp; + this._opening = false; - var optsf = { - path: '/plugins/' + this.name + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin is not installed', - 500: 'server error' - }, - options: args.opts - }; + if (this.start !== undefined) { + checkPosition(this.start, 'start'); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); + this.pos = this.start; } -}; -/** - * get privileges - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @return {Object} Name only if callback isn't specified. - */ -Plugin.prototype.privileges = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + if (options.encoding) + this.setDefaultEncoding(options.encoding); - var optsf = { - path: '/plugins/privileges?', - method: 'GET', - options: { - 'remote': this.remote - }, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + // Node v6.x only + this.on('finish', function() { + if (this._writableState.finalCalled) + return; + if (this.autoClose) + this.destroy(); + }); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + if (!Buffer.isBuffer(this.handle)) + this.open(); +} +inherits(WriteStream, WritableStream); + +WriteStream.prototype._final = function(cb) { + if (this.autoClose) + this.destroy(); + cb(); }; +WriteStream.prototype.open = function() { + if (this._opening) + return; -/** - * Installs a new plugin - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Plugin.prototype.pull = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + this._opening = true; - if(args.opts._query && !args.opts._query.name) { - args.opts._query.name = this.name; - } - if(args.opts._query && !args.opts._query.remote) { - args.opts._query.remote = this.remote; - } + this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { + this._opening = false; - var optsf = { - path: '/plugins/pull?', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - options: args.opts, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' + if (er) { + this.emit('error', er); + if (this.autoClose) + this.destroy(); + return; } - }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + this.handle = handle; + const tryAgain = (err) => { + if (err) { + // Try chmod() for sftp servers that may not support fchmod() for + // whatever reason + this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); + return; + } -/** - * Enable - * @param {Object} opts Plugin enable options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.enable = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // SFTPv3 requires absolute offsets, no matter the open flag used + if (this.flags[0] === 'a') { + const tryStat = (err, st) => { + if (err) { + // Try stat() for sftp servers that may not support fstat() for + // whatever reason + this.sftp.stat(this.path, (err_, st_) => { + if (err_) { + this.destroy(); + this.emit('error', err); + return; + } + tryStat(null, st_); + }); + return; + } - var optsf = { - path: '/plugins/' + this.name + '/enable?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - }, - options: args.opts - }; + this.pos = st.size; + this.emit('open', handle); + this.emit('ready'); + }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + this.sftp.fstat(handle, tryStat); + return; + } -/** - * Disable - * @param {Object} opts Plugin disable options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.disable = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + this.emit('open', handle); + this.emit('ready'); + }; - var optsf = { - path: '/plugins/' + this.name + '/disable', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - }, - options: args.opts - }; + this.sftp.fchmod(handle, this.mode, tryAgain); + }); +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); +WriteStream.prototype._write = function(data, encoding, cb) { + if (!Buffer.isBuffer(data)) { + const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); + return this.emit('error', err); + } + + if (!Buffer.isBuffer(this.handle)) { + return this.once('open', function() { + this._write(data, encoding, cb); }); } -}; -/** - * Push - * @param {Object} opts Plugin push options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.push = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + this.sftp.write(this.handle, + data, + 0, + data.length, + this.pos, + (er, bytes) => { + if (er) { + if (this.autoClose) + this.destroy(); + return cb(er); + } + this.bytesWritten += bytes; + cb(); + }); - var optsf = { - path: '/plugins/' + this.name + '/push', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin not installed', - 500: 'server error' - }, - options: args.opts - }; + this.pos += data.length; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); +WriteStream.prototype._writev = function(data, cb) { + if (!Buffer.isBuffer(this.handle)) { + return this.once('open', function() { + this._writev(data, cb); }); } -}; -/** - * COnfigure - * @param {Object} opts Plugin configure options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.configure = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + const sftp = this.sftp; + const handle = this.handle; + let writesLeft = data.length; - var optsf = { - path: '/plugins/' + this.name + '/set', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin not installed', - 500: 'server error' - }, - options: args.opts + const onwrite = (er, bytes) => { + if (er) { + this.destroy(); + return cb(er); + } + this.bytesWritten += bytes; + if (--writesLeft === 0) + cb(); }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // TODO: try to combine chunks to reduce number of requests to the server? + for (let i = 0; i < data.length; ++i) { + const chunk = data[i].chunk; + + sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); + this.pos += chunk.length; } }; +if (typeof WritableStream.prototype.destroy !== 'function') + WriteStream.prototype.destroy = ReadStream.prototype.destroy; -/** - * Upgrade plugin - * - * @param {object} auth - * @param {object} opts - * @param {function} callback - */ -Plugin.prototype.upgrade = function(auth, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; +WriteStream.prototype._destroy = ReadStream.prototype._destroy; +WriteStream.prototype.close = function(cb) { + if (cb) { + if (this.isClosed) { + process.nextTick(cb); + return; + } + this.on('close', cb); } - var optsf = { - path: '/plugins/' + this.name + '/upgrade?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'plugin not installed', - 500: 'server error' - }, - authconfig: auth, - options: opts - }; + // If we are not autoClosing, we should call + // destroy on 'finish'. + if (!this.autoClose) + this.on('finish', this.destroy.bind(this)); - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } + this.end(); }; +// There is no shutdown() for files. +WriteStream.prototype.destroySoon = WriteStream.prototype.end; -module.exports = Plugin; +Object.defineProperty(WriteStream.prototype, 'pending', { + get() { + return this.handle === null; + }, + configurable: true +}); +// ============================================================================= + +module.exports = { + flagsToString, + OPEN_MODE, + SFTP, + Stats, + STATUS_CODE, + stringToFlags, +}; /***/ }), -/***/ 9934: +/***/ 6832: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(1604); +"use strict"; -/** - * Represents a secret - * @param {Object} modem docker-modem - * @param {String} id Secret's id - */ -var Secret = function(modem, id) { - this.modem = modem; - this.id = id; -}; -Secret.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; +const crypto = __nccwpck_require__(6113); -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Secret.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +let cpuInfo; +try { + cpuInfo = __nccwpck_require__(4137)(); +} catch {} - var optsf = { - path: '/secrets/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'secret not found', - 406: 'node is not part of a swarm', - 500: 'server error' - } - }; +const { bindingAvailable, CIPHER_INFO, MAC_INFO } = __nccwpck_require__(5708); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +const eddsaSupported = (() => { + if (typeof crypto.sign === 'function' + && typeof crypto.verify === 'function') { + const key = + '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' + + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; + const data = Buffer.from('a'); + let sig; + let verified; + try { + sig = crypto.sign(null, data, key); + verified = crypto.verify(null, data, key, sig); + } catch {} + return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); } -}; -/** - * Update a secret. - * - * @param {object} opts - * @param {function} callback - */ -Secret.prototype.update = function(opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - } + return false; +})(); - var optsf = { - path: '/secrets/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'secret not found', - 500: 'server error' - }, - options: opts - }; +const curve25519Supported = (typeof crypto.diffieHellman === 'function' + && typeof crypto.generateKeyPairSync === 'function' + && typeof crypto.createPublicKey === 'function'); - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; +const DEFAULT_KEX = [ + // https://tools.ietf.org/html/rfc5656#section-10.1 + 'ecdh-sha2-nistp256', + 'ecdh-sha2-nistp384', + 'ecdh-sha2-nistp521', + // https://tools.ietf.org/html/rfc4419#section-4 + 'diffie-hellman-group-exchange-sha256', -/** - * Removes the secret - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Secret.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // https://tools.ietf.org/html/rfc8268 + 'diffie-hellman-group14-sha256', + 'diffie-hellman-group15-sha512', + 'diffie-hellman-group16-sha512', + 'diffie-hellman-group17-sha512', + 'diffie-hellman-group18-sha512', +]; +if (curve25519Supported) { + DEFAULT_KEX.unshift('curve25519-sha256'); + DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); +} +const SUPPORTED_KEX = DEFAULT_KEX.concat([ + // https://tools.ietf.org/html/rfc4419#section-4 + 'diffie-hellman-group-exchange-sha1', - var optsf = { - path: '/secrets/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'secret not found', - 500: 'server error' - }, - options: args.opts - }; + 'diffie-hellman-group14-sha1', // REQUIRED + 'diffie-hellman-group1-sha1', // REQUIRED +]); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + +const DEFAULT_SERVER_HOST_KEY = [ + 'ecdsa-sha2-nistp256', + 'ecdsa-sha2-nistp384', + 'ecdsa-sha2-nistp521', + 'rsa-sha2-512', // RFC 8332 + 'rsa-sha2-256', // RFC 8332 + 'ssh-rsa', +]; +if (eddsaSupported) + DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); +const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ + 'ssh-dss', +]); + + +const canUseCipher = (() => { + const ciphers = crypto.getCiphers(); + return (name) => ciphers.includes(CIPHER_INFO[name].sslName); +})(); +let DEFAULT_CIPHER = [ + // http://tools.ietf.org/html/rfc5647 + 'aes128-gcm@openssh.com', + 'aes256-gcm@openssh.com', + + // http://tools.ietf.org/html/rfc4344#section-4 + 'aes128-ctr', + 'aes192-ctr', + 'aes256-ctr', +]; +if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { + // We know for sure the CPU does not support AES acceleration + if (bindingAvailable) + DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); + else + DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); +} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { + // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers + // seem to outperform it on x86, but it seems to be faster than CTR ciphers + DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); +} else { + DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); +} +DEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher); +const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ + 'aes256-cbc', + 'aes192-cbc', + 'aes128-cbc', + 'blowfish-cbc', + '3des-cbc', + 'aes128-gcm', + 'aes256-gcm', + + // http://tools.ietf.org/html/rfc4345#section-4: + 'arcfour256', + 'arcfour128', + + 'cast128-cbc', + 'arcfour', +].filter(canUseCipher)); + + +const canUseMAC = (() => { + const hashes = crypto.getHashes(); + return (name) => hashes.includes(MAC_INFO[name].sslName); +})(); +const DEFAULT_MAC = [ + 'hmac-sha2-256-etm@openssh.com', + 'hmac-sha2-512-etm@openssh.com', + 'hmac-sha1-etm@openssh.com', + 'hmac-sha2-256', + 'hmac-sha2-512', + 'hmac-sha1', +].filter(canUseMAC); +const SUPPORTED_MAC = DEFAULT_MAC.concat([ + 'hmac-md5', + 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 + 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 + 'hmac-ripemd160', + 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 + 'hmac-md5-96', // first 96 bits of HMAC-MD5 +].filter(canUseMAC)); + +const DEFAULT_COMPRESSION = [ + 'none', + 'zlib@openssh.com', // ZLIB (LZ77) compression, except + // compression/decompression does not start until after + // successful user authentication + 'zlib', // ZLIB (LZ77) compression +]; +const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ +]); + + +const COMPAT = { + BAD_DHGEX: 1 << 0, + OLD_EXIT: 1 << 1, + DYN_RPORT_BUG: 1 << 2, + BUG_DHGEX_LARGE: 1 << 3, + IMPLY_RSA_SHA2_SIGALGS: 1 << 4, }; +module.exports = { + MESSAGE: { + // Transport layer protocol -- generic (1-19) + DISCONNECT: 1, + IGNORE: 2, + UNIMPLEMENTED: 3, + DEBUG: 4, + SERVICE_REQUEST: 5, + SERVICE_ACCEPT: 6, + EXT_INFO: 7, // RFC 8308 + + // Transport layer protocol -- algorithm negotiation (20-29) + KEXINIT: 20, + NEWKEYS: 21, + + // Transport layer protocol -- key exchange method-specific (30-49) + KEXDH_INIT: 30, + KEXDH_REPLY: 31, + + KEXDH_GEX_GROUP: 31, + KEXDH_GEX_INIT: 32, + KEXDH_GEX_REPLY: 33, + KEXDH_GEX_REQUEST: 34, + + KEXECDH_INIT: 30, + KEXECDH_REPLY: 31, + + // User auth protocol -- generic (50-59) + USERAUTH_REQUEST: 50, + USERAUTH_FAILURE: 51, + USERAUTH_SUCCESS: 52, + USERAUTH_BANNER: 53, + + // User auth protocol -- user auth method-specific (60-79) + USERAUTH_PASSWD_CHANGEREQ: 60, + + USERAUTH_PK_OK: 60, + + USERAUTH_INFO_REQUEST: 60, + USERAUTH_INFO_RESPONSE: 61, + + // Connection protocol -- generic (80-89) + GLOBAL_REQUEST: 80, + REQUEST_SUCCESS: 81, + REQUEST_FAILURE: 82, + + // Connection protocol -- channel-related (90-127) + CHANNEL_OPEN: 90, + CHANNEL_OPEN_CONFIRMATION: 91, + CHANNEL_OPEN_FAILURE: 92, + CHANNEL_WINDOW_ADJUST: 93, + CHANNEL_DATA: 94, + CHANNEL_EXTENDED_DATA: 95, + CHANNEL_EOF: 96, + CHANNEL_CLOSE: 97, + CHANNEL_REQUEST: 98, + CHANNEL_SUCCESS: 99, + CHANNEL_FAILURE: 100 + + // Reserved for client protocols (128-191) + + // Local extensions (192-155) + }, + DISCONNECT_REASON: { + HOST_NOT_ALLOWED_TO_CONNECT: 1, + PROTOCOL_ERROR: 2, + KEY_EXCHANGE_FAILED: 3, + RESERVED: 4, + MAC_ERROR: 5, + COMPRESSION_ERROR: 6, + SERVICE_NOT_AVAILABLE: 7, + PROTOCOL_VERSION_NOT_SUPPORTED: 8, + HOST_KEY_NOT_VERIFIABLE: 9, + CONNECTION_LOST: 10, + BY_APPLICATION: 11, + TOO_MANY_CONNECTIONS: 12, + AUTH_CANCELED_BY_USER: 13, + NO_MORE_AUTH_METHODS_AVAILABLE: 14, + ILLEGAL_USER_NAME: 15, + }, + DISCONNECT_REASON_STR: undefined, + CHANNEL_OPEN_FAILURE: { + ADMINISTRATIVELY_PROHIBITED: 1, + CONNECT_FAILED: 2, + UNKNOWN_CHANNEL_TYPE: 3, + RESOURCE_SHORTAGE: 4 + }, + TERMINAL_MODE: { + TTY_OP_END: 0, // Indicates end of options. + VINTR: 1, // Interrupt character; 255 if none. Similarly for the + // other characters. Not all of these characters are + // supported on all systems. + VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX + // systems). + VERASE: 3, // Erase the character to left of the cursor. + VKILL: 4, // Kill the current input line. + VEOF: 5, // End-of-file character (sends EOF from the + // terminal). + VEOL: 6, // End-of-line character in addition to carriage + // return and/or linefeed. + VEOL2: 7, // Additional end-of-line character. + VSTART: 8, // Continues paused output (normally control-Q). + VSTOP: 9, // Pauses output (normally control-S). + VSUSP: 10, // Suspends the current program. + VDSUSP: 11, // Another suspend character. + VREPRINT: 12, // Reprints the current input line. + VWERASE: 13, // Erases a word left of cursor. + VLNEXT: 14, // Enter the next character typed literally, even if + // it is a special character + VFLUSH: 15, // Character to flush output. + VSWTCH: 16, // Switch to a different shell layer. + VSTATUS: 17, // Prints system status line (load, command, pid, + // etc). + VDISCARD: 18, // Toggles the flushing of terminal output. + IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 + // if this flag is FALSE, and 1 if it is TRUE. + PARMRK: 31, // Mark parity and framing errors. + INPCK: 32, // Enable checking of parity errors. + ISTRIP: 33, // Strip 8th bit off characters. + INLCR: 34, // Map NL into CR on input. + IGNCR: 35, // Ignore CR on input. + ICRNL: 36, // Map CR to NL on input. + IUCLC: 37, // Translate uppercase characters to lowercase. + IXON: 38, // Enable output flow control. + IXANY: 39, // Any char will restart after stop. + IXOFF: 40, // Enable input flow control. + IMAXBEL: 41, // Ring bell on input queue full. + ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. + ICANON: 51, // Canonicalize input lines. + XCASE: 52, // Enable input and output of uppercase characters by + // preceding their lowercase equivalents with "\". + ECHO: 53, // Enable echoing. + ECHOE: 54, // Visually erase chars. + ECHOK: 55, // Kill character discards current line. + ECHONL: 56, // Echo NL even if ECHO is off. + NOFLSH: 57, // Don't flush after interrupt. + TOSTOP: 58, // Stop background jobs from output. + IEXTEN: 59, // Enable extensions. + ECHOCTL: 60, // Echo control characters as ^(Char). + ECHOKE: 61, // Visual erase for line kill. + PENDIN: 62, // Retype pending input. + OPOST: 70, // Enable output processing. + OLCUC: 71, // Convert lowercase to uppercase. + ONLCR: 72, // Map NL to CR-NL. + OCRNL: 73, // Translate carriage return to newline (output). + ONOCR: 74, // Translate newline to carriage return-newline + // (output). + ONLRET: 75, // Newline performs a carriage return (output). + CS7: 90, // 7 bit mode. + CS8: 91, // 8 bit mode. + PARENB: 92, // Parity enable. + PARODD: 93, // Odd parity, else even. + TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. + TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. + }, + CHANNEL_EXTENDED_DATATYPE: { + STDERR: 1, + }, + + SIGNALS: [ + 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', + 'USR2', 'KILL', 'PIPE' + ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), + + COMPAT, + COMPAT_CHECKS: [ + [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], + [ /^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE ], + [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations + [ /^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG ], + [ /^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS ], + ], + + // KEX proposal-related + DEFAULT_KEX, + SUPPORTED_KEX, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY, + DEFAULT_CIPHER, + SUPPORTED_CIPHER, + DEFAULT_MAC, + SUPPORTED_MAC, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION, + curve25519Supported, + eddsaSupported, +}; -module.exports = Secret; +module.exports.DISCONNECT_REASON_BY_VALUE = + Array.from(Object.entries(module.exports.DISCONNECT_REASON)) + .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); /***/ }), -/***/ 8866: +/***/ 5708: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(1604); +"use strict"; +// TODO: +// * make max packet size configurable +// * if decompression is enabled, use `._packet` in decipher instances as +// input to (sync) zlib inflater with appropriate offset and length to +// avoid an additional copy of payload data before inflation +// * factor decompression status into packet length checks -/** - * Represents an Service - * @param {Object} modem docker-modem - * @param {String} id Service's ID - */ -var Service = function(modem, id) { - this.modem = modem; - this.id = id; -}; -Service.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; +const { + createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual +} = __nccwpck_require__(6113); -/** - * Query Docker for service details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Service.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +const { readUInt32BE, writeUInt32BE } = __nccwpck_require__(9475); - var optsf = { - path: '/services/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error' - } - }; +const FastBuffer = Buffer[Symbol.species]; +const MAX_SEQNO = 2 ** 32 - 1; +const EMPTY_BUFFER = Buffer.alloc(0); +const BUF_INT = Buffer.alloc(4); +const DISCARD_CACHE = new Map(); +const MAX_PACKET_SIZE = 35000; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +let binding; +let AESGCMCipher; +let ChaChaPolyCipher; +let GenericCipher; +let AESGCMDecipher; +let ChaChaPolyDecipher; +let GenericDecipher; +try { + binding = __nccwpck_require__(9041); + ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, + AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); +} catch {} + +const CIPHER_STREAM = 1 << 0; +const CIPHER_INFO = (() => { + function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { + return { + sslName, + blockLen, + keyLen, + ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) + ? ivLen + : blockLen), + authLen, + discardLen, + stream: !!(flags & CIPHER_STREAM), + }; } -}; -/** - * Delete Service - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Service.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + return { + 'chacha20-poly1305@openssh.com': + info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), - var optsf = { - path: '/services/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such service', - 500: 'server error' - } + 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), + 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), + 'aes128-gcm@openssh.com': + info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), + 'aes256-gcm@openssh.com': + info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), + + 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), + 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), + 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), + 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), + '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), + 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), + 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), + 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), + + 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), + 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), + 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), + '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), + 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), + 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), + + /* The "arcfour128" algorithm is the RC4 cipher, as described in + [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream + generated by the cipher MUST be discarded, and the first byte of the + first encrypted packet MUST be encrypted using the 1537th byte of + keystream. + + -- http://tools.ietf.org/html/rfc4345#section-4 */ + 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), + 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), + 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), + 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), }; +})(); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +const MAC_INFO = (() => { + function info(sslName, len, actualLen, isETM) { + return { + sslName, + len, + actualLen, + isETM, + }; } -}; -/** - * Update service - * - * @param {object} auth - * @param {object} opts - * @param {function} callback - */ -Service.prototype.update = function(auth, opts, callback) { - var self = this; - if (!callback) { - var t = typeof opts; - if(t === 'function'){ - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (t === 'undefined'){ - opts = auth; - auth = opts.authconfig || undefined; - } + return { + 'hmac-md5': info('md5', 16, 16, false), + 'hmac-md5-96': info('md5', 16, 12, false), + 'hmac-ripemd160': info('ripemd160', 20, 20, false), + 'hmac-sha1': info('sha1', 20, 20, false), + 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), + 'hmac-sha1-96': info('sha1', 20, 12, false), + 'hmac-sha2-256': info('sha256', 32, 32, false), + 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), + 'hmac-sha2-256-96': info('sha256', 32, 12, false), + 'hmac-sha2-512': info('sha512', 64, 64, false), + 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), + 'hmac-sha2-512-96': info('sha512', 64, 12, false), + }; +})(); + + +// Should only_be used during the initial handshake +class NullCipher { + constructor(seqno, onWrite) { + this.outSeqno = seqno; + this._onWrite = onWrite; + this._dead = false; + } + free() { + this._dead = true; } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - (pktLen & (8 - 1)); + if (padLen < 4) + padLen += 8; + pktLen += padLen; - var optsf = { - path: '/services/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error' - }, - authconfig: auth, - options: opts - }; + const packet = Buffer.allocUnsafe(pktLen); - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + + randomFillSync(packet, 5 + payloadLen, padLen); + + return packet; } -}; + encrypt(packet) { + // `packet` === unencrypted packet + if (this._dead) + return; + this._onWrite(packet); -/** - * Service logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Service.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, {}); + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} - var optsf = { - path: '/services/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +const POLY1305_ZEROS = Buffer.alloc(32); +const POLY1305_OUT_COMPUTE = Buffer.alloc(16); +let POLY1305_WASM_MODULE; +let POLY1305_RESULT_MALLOC; +let poly1305_auth; +class ChaChaPolyCipherNative { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encKeyMain = enc.cipherKey.slice(0, 32); + this._encKeyPktLen = enc.cipherKey.slice(32); + this._dead = false; } -}; + free() { + this._dead = true; + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - ((pktLen - 4) & (8 - 1)); + if (padLen < 4) + padLen += 8; + pktLen += padLen; + const packet = Buffer.allocUnsafe(pktLen); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; -module.exports = Service; + randomFillSync(packet, 5 + payloadLen, padLen); + return packet; + } + encrypt(packet) { + // `packet` === unencrypted packet -/***/ }), + if (this._dead) + return; -/***/ 1385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Generate Poly1305 key + POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) + writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); + const polyKey = + createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) + .update(POLY1305_ZEROS); -var util = __nccwpck_require__(1604); + // Encrypt packet length + const pktLenEnc = + createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) + .update(packet.slice(0, 4)); + this._onWrite(pktLenEnc); -/** - * Represents an Task - * @param {Object} modem docker-modem - * @param {String} id Task's ID - */ -var Task = function(modem, id) { - this.modem = modem; - this.id = id; + // Encrypt rest of packet + POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) + const payloadEnc = + createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) + .update(packet.slice(4)); + this._onWrite(payloadEnc); - this.defaultOptions = { - log: {} - }; -}; + // Calculate Poly1305 MAC + poly1305_auth(POLY1305_RESULT_MALLOC, + pktLenEnc, + pktLenEnc.length, + payloadEnc, + payloadEnc.length, + polyKey); + const mac = Buffer.allocUnsafe(16); + mac.set( + new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, + POLY1305_RESULT_MALLOC, + 16), + 0 + ); + this._onWrite(mac); -Task.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} -/** - * Query Docker for Task details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Task.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +class ChaChaPolyCipherBinding { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._instance = new ChaChaPolyCipher(enc.cipherKey); + this._dead = false; + } + free() { + this._dead = true; + this._instance.free(); + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - ((pktLen - 4) & (8 - 1)); + if (padLen < 4) + padLen += 8; + pktLen += padLen; - var optsf = { - path: '/tasks/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'unknown task', - 500: 'server error' - } - }; + const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + + randomFillSync(packet, 5 + payloadLen, padLen); + + return packet; } -}; + encrypt(packet) { + // `packet` === unencrypted packet -/** - * Task logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Task.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); + if (this._dead) + return; - var optsf = { - path: '/tasks/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 101: true, - 200: true, - 404: 'no such container', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; + // Encrypts in-place + this._instance.encrypt(packet, this.outSeqno); + + this._onWrite(packet); + + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} + + +class AESGCMCipherNative { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encSSLName = enc.cipherInfo.sslName; + this._encKey = enc.cipherKey; + this._encIV = enc.cipherIV; + this._dead = false; + } + free() { + this._dead = true; + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 16 - ((pktLen - 4) & (16 - 1)); + if (padLen < 4) + padLen += 16; + pktLen += padLen; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + const packet = Buffer.allocUnsafe(pktLen); + + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + + randomFillSync(packet, 5 + payloadLen, padLen); + + return packet; } -}; + encrypt(packet) { + // `packet` === unencrypted packet + if (this._dead) + return; -module.exports = Task; + const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); + cipher.setAutoPadding(false); + const lenData = packet.slice(0, 4); + cipher.setAAD(lenData); + this._onWrite(lenData); -/***/ }), + // Encrypt pad length, payload, and padding + const encrypted = cipher.update(packet.slice(4)); + this._onWrite(encrypted); + const final = cipher.final(); + // XXX: final.length === 0 always? + if (final.length) + this._onWrite(final); -/***/ 1604: -/***/ ((module) => { + // Generate MAC + const tag = cipher.getAuthTag(); + this._onWrite(tag); -// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js + // Increment counter in IV by 1 for next packet + ivIncrement(this._encIV); -var arr = []; -var each = arr.forEach; -var slice = arr.slice; + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} -module.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; -}; +class AESGCMCipherBinding { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._instance = new AESGCMCipher(enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV); + this._dead = false; + } + free() { + this._dead = true; + this._instance.free(); + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 16 - ((pktLen - 4) & (16 - 1)); + if (padLen < 4) + padLen += 16; + pktLen += padLen; -module.exports.processArgs = function(opts, callback, defaultOpts) { - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; + const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); + + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + + randomFillSync(packet, 5 + payloadLen, padLen); + + return packet; } - return { - callback: callback, - opts: module.exports.extend({}, defaultOpts, opts) - }; -}; + encrypt(packet) { + // `packet` === unencrypted packet + if (this._dead) + return; -/** - * Parse the given repo tag name (as a string) and break it out into repo/tag pair. - * // if given the input http://localhost:8080/woot:latest - * { - * repository: 'http://localhost:8080/woot', - * tag: 'latest' - * } - * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest' - * @return {Object} input parsed into the repo and tag. - */ -module.exports.parseRepositoryTag = function(input) { - var separatorPos; - var digestPos = input.indexOf('@'); - var colonPos = input.lastIndexOf(':'); - // @ symbol is more important - if (digestPos >= 0) { - separatorPos = digestPos; - } else if (colonPos >= 0) { - separatorPos = colonPos; - } else { - // no colon nor @ - return { - repository: input - }; + // Encrypts in-place + this._instance.encrypt(packet); + + this._onWrite(packet); + + this.outSeqno = (this.outSeqno + 1) >>> 0; } +} - // last colon is either the tag (or part of a port designation) - var tag = input.slice(separatorPos + 1); - // if it contains a / its not a tag and is part of the url - if (tag.indexOf('/') === -1) { - return { - repository: input.slice(0, separatorPos), - tag: tag - }; +class GenericCipherNative { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encBlockLen = enc.cipherInfo.blockLen; + this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV); + this._macSSLName = enc.macInfo.sslName; + this._macKey = enc.macKey; + this._macActualLen = enc.macInfo.actualLen; + this._macETM = enc.macInfo.isETM; + this._aadLen = (this._macETM ? 4 : 0); + this._dead = false; + + const discardLen = enc.cipherInfo.discardLen; + if (discardLen) { + let discard = DISCARD_CACHE.get(discardLen); + if (discard === undefined) { + discard = Buffer.alloc(discardLen); + DISCARD_CACHE.set(discardLen, discard); + } + this._cipherInstance.update(discard); + } + } + free() { + this._dead = true; } + allocPacket(payloadLen) { + const blockLen = this._encBlockLen; - return { - repository: input - }; -}; + let pktLen = 4 + 1 + payloadLen; + let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); + if (padLen < 4) + padLen += blockLen; + pktLen += padLen; + const packet = Buffer.allocUnsafe(pktLen); -/***/ }), + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; -/***/ 4877: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + randomFillSync(packet, 5 + payloadLen, padLen); -var util = __nccwpck_require__(1604); + return packet; + } + encrypt(packet) { + // `packet` === unencrypted packet -/** - * Represents a volume - * @param {Object} modem docker-modem - * @param {String} name Volume's name - */ -var Volume = function(modem, name) { - this.modem = modem; - this.name = name; -}; + if (this._dead) + return; -Volume.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + let mac; + if (this._macETM) { + // Encrypt pad length, payload, and padding + const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); + const encrypted = this._cipherInstance.update( + new Uint8Array(packet.buffer, + packet.byteOffset + 4, + packet.length - 4) + ); -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Volume.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + this._onWrite(lenBytes); + this._onWrite(encrypted); - var optsf = { - path: '/volumes/' + this.name, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such volume', - 500: 'server error' - } - }; + // TODO: look into storing seqno as 4-byte buffer and incrementing like we + // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time + mac = createHmac(this._macSSLName, this._macKey); + writeUInt32BE(BUF_INT, this.outSeqno, 0); + mac.update(BUF_INT); + mac.update(lenBytes); + mac.update(encrypted); + } else { + // Encrypt length field, pad length, payload, and padding + const encrypted = this._cipherInstance.update(packet); + this._onWrite(encrypted); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + // TODO: look into storing seqno as 4-byte buffer and incrementing like we + // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time + mac = createHmac(this._macSSLName, this._macKey); + writeUInt32BE(BUF_INT, this.outSeqno, 0); + mac.update(BUF_INT); + mac.update(packet); + } -/** - * Removes the volume - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Volume.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + let digest = mac.digest(); + if (digest.length > this._macActualLen) + digest = digest.slice(0, this._macActualLen); + this._onWrite(digest); - var optsf = { - path: '/volumes/' + this.name, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 204: true, - 404: 'no such volume', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +class GenericCipherBinding { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encBlockLen = enc.cipherInfo.blockLen; + this._macLen = enc.macInfo.len; + this._macActualLen = enc.macInfo.actualLen; + this._aadLen = (enc.macInfo.isETM ? 4 : 0); + this._instance = new GenericCipher(enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV, + enc.macInfo.sslName, + enc.macKey, + enc.macInfo.isETM); + this._dead = false; } -}; + free() { + this._dead = true; + this._instance.free(); + } + allocPacket(payloadLen) { + const blockLen = this._encBlockLen; -module.exports = Volume; + let pktLen = 4 + 1 + payloadLen; + let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); + if (padLen < 4) + padLen += blockLen; + pktLen += padLen; + const packet = Buffer.allocUnsafe(pktLen + this._macLen); -/***/ }), + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; -/***/ 1205: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + randomFillSync(packet, 5 + payloadLen, padLen); -var once = __nccwpck_require__(1223); + return packet; + } + encrypt(packet) { + // `packet` === unencrypted packet -var noop = function() {}; + if (this._dead) + return; -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; + // Encrypts in-place + this._instance.encrypt(packet, this.outSeqno); -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; + if (this._macActualLen < this._macLen) { + packet = new FastBuffer(packet.buffer, + packet.byteOffset, + (packet.length + - (this._macLen - this._macActualLen))); + } + this._onWrite(packet); -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} - callback = once(callback || noop); - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; +class NullDecipher { + constructor(seqno, onPayload) { + this.inSeqno = seqno; + this._onPayload = onPayload; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + } + free() {} + decrypt(data, p, dataLen) { + while (p < dataLen) { + // Read packet length + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; + if (this._lenBytes < 4) + return; - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; + if (this._len > MAX_PACKET_SIZE + || this._len < 8 + || (4 + this._len & 7) !== 0) { + throw new Error('Bad packet length'); + } + if (p >= dataLen) + return; + } - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; + // Read padding length, payload, and padding + if (this._packetPos < this._len) { + const nb = Math.min(this._len - this._packetPos, dataLen - p); + let chunk; + if (p !== 0 || nb !== dataLen) + chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + chunk = data; + if (nb === this._len) { + this._packet = chunk; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(chunk, this._packetPos); + } + p += nb; + this._packetPos += nb; + if (this._packetPos < this._len) + return; + } - var onerror = function(err) { - callback.call(stream, err); - }; + const payload = (!this._packet + ? EMPTY_BUFFER + : new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length + - this._packet[0] - 1)); - var onclose = function() { - process.nextTick(onclosenexttick); - }; + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); - }; + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } + } + } +} - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +class ChaChaPolyDecipherNative { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decKeyMain = dec.decipherKey.slice(0, 32); + this._decKeyPktLen = dec.decipherKey.slice(32); + this._len = 0; + this._lenBuf = Buffer.alloc(4); + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(16); + this._calcMac = Buffer.allocUnsafe(16); + this._macPos = 0; + } + free() {} + decrypt(data, p, dataLen) { + // `data` === encrypted data - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } + while (p < dataLen) { + // Read packet length + if (this._lenPos < 4) { + let nb = Math.min(4 - this._lenPos, dataLen - p); + while (nb--) + this._lenBuf[this._lenPos++] = data[p++]; + if (this._lenPos < 4) + return; - if (isChildProcess(stream)) stream.on('exit', onexit); + POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) + writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); + const decLenBytes = + createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) + .update(this._lenBuf); + this._len = readUInt32BE(decLenBytes, 0); - return function() { - cancelled = true; - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -}; + if (this._len > MAX_PACKET_SIZE + || this._len < 8 + || (this._len & 7) !== 0) { + throw new Error('Bad packet length'); + } + } -module.exports = eos; + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } + + // Read Poly1305 MAC + { + const nb = Math.min(16 - this._macPos, dataLen - p); + // TODO: avoid copying if entire MAC is in current chunk + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < 16) + return; + } + // Generate Poly1305 key + POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) + writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); + const polyKey = + createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) + .update(POLY1305_ZEROS); -/***/ }), + // Calculate and compare Poly1305 MACs + poly1305_auth(POLY1305_RESULT_MALLOC, + this._lenBuf, + 4, + this._packet, + this._packet.length, + polyKey); -/***/ 3186: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._calcMac.set( + new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, + POLY1305_RESULT_MALLOC, + 16), + 0 + ); + if (!timingSafeEqual(this._calcMac, this._mac)) + throw new Error('Invalid MAC'); -module.exports = (__nccwpck_require__(7147).constants) || __nccwpck_require__(2057) + // Decrypt packet + POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) + const packet = + createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) + .update(this._packet); + const payload = new FastBuffer(packet.buffer, + packet.byteOffset + 1, + packet.length - packet[0] - 1); -/***/ }), + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._len = 0; + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; -/***/ 1621: -/***/ ((module) => { + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } + } + } +} -"use strict"; +class ChaChaPolyDecipherBinding { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new ChaChaPolyDecipher(dec.decipherKey); + this._len = 0; + this._lenBuf = Buffer.alloc(4); + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(16); + this._macPos = 0; + } + free() { + this._instance.free(); + } + decrypt(data, p, dataLen) { + // `data` === encrypted data + while (p < dataLen) { + // Read packet length + if (this._lenPos < 4) { + let nb = Math.min(4 - this._lenPos, dataLen - p); + while (nb--) + this._lenBuf[this._lenPos++] = data[p++]; + if (this._lenPos < 4) + return; -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; + this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); + if (this._len > MAX_PACKET_SIZE + || this._len < 8 + || (this._len & 7) !== 0) { + throw new Error('Bad packet length'); + } -/***/ }), + if (p >= dataLen) + return; + } -/***/ 4124: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } -try { - var util = __nccwpck_require__(3837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(8544); -} + // Read Poly1305 MAC + { + const nb = Math.min(16 - this._macPos, dataLen - p); + // TODO: avoid copying if entire MAC is in current chunk + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < 16) + return; + } + this._instance.decrypt(this._packet, this._mac, this.inSeqno); -/***/ }), + const payload = new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1); -/***/ 8544: -/***/ ((module) => { + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._len = 0; + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } } } } +class AESGCMDecipherNative { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decipherInstance = null; + this._decipherSSLName = dec.decipherInfo.sslName; + this._decipherKey = dec.decipherKey; + this._decipherIV = dec.decipherIV; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._tag = Buffer.allocUnsafe(16); + this._tagPos = 0; + } + free() {} + decrypt(data, p, dataLen) { + // `data` === encrypted data -/***/ }), + while (p < dataLen) { + // Read packet length (unencrypted, but AAD) + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; + if (this._lenBytes < 4) + return; -/***/ 7614: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if ((this._len + 20) > MAX_PACKET_SIZE + || this._len < 16 + || (this._len & 15) !== 0) { + throw new Error('Bad packet length'); + } -var path = __nccwpck_require__(1017); -var fs = __nccwpck_require__(7147); -var _0777 = parseInt('0777', 8); + this._decipherInstance = createDecipheriv( + this._decipherSSLName, + this._decipherKey, + this._decipherIV + ); + this._decipherInstance.setAutoPadding(false); + this._decipherInstance.setAAD(intToBytes(this._len)); + } -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let decrypted; + if (p !== 0 || nb !== dataLen) { + decrypted = this._decipherInstance.update( + new Uint8Array(data.buffer, data.byteOffset + p, nb) + ); + } else { + decrypted = this._decipherInstance.update(data); + } + if (decrypted.length) { + if (nb === this._len) { + this._packet = decrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(decrypted, this._packetPos); + } + this._packetPos += decrypted.length; + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); + // Read authentication tag + { + const nb = Math.min(16 - this._tagPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._tag.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._tagPos + ); + } else { + this._tag.set(data, this._tagPos); } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; + p += nb; + this._tagPos += nb; + if (this._tagPos < 16) + return; + } - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; + { + // Verify authentication tag + this._decipherInstance.setAuthTag(this._tag); + + const decrypted = this._decipherInstance.final(); + + // XXX: this should never output any data since stream ciphers always + // return data from .update() and block ciphers must end on a multiple + // of the block length, which would have caused an exception to be + // thrown if the total input was not... + if (decrypted.length) { + if (this._packet) + this._packet.set(decrypted, this._packetPos); + else + this._packet = decrypted; } - }); -} + } -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; + const payload = (!this._packet + ? EMPTY_BUFFER + : new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length + - this._packet[0] - 1)); - p = path.resolve(p); + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + ivIncrement(this._decipherIV); + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._tagPos = 0; - try { - xfs.mkdirSync(p, mode); - made = made || p; + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; + } +} - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; +class AESGCMDecipherBinding { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV); + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._pktLen = 0; + this._tag = Buffer.allocUnsafe(16); + this._tagPos = 0; + } + free() {} + decrypt(data, p, dataLen) { + // `data` === encrypted data + + while (p < dataLen) { + // Read packet length (unencrypted, but AAD) + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; + if (this._lenBytes < 4) + return; + + if ((this._len + 20) > MAX_PACKET_SIZE + || this._len < 16 + || (this._len & 15) !== 0) { + throw new Error(`Bad packet length: ${this._len}`); + } + } + + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); } - } - - return made; -}; - - -/***/ }), + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } -/***/ 900: -/***/ ((module) => { + // Read authentication tag + { + const nb = Math.min(16 - this._tagPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._tag.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._tagPos + ); + } else { + this._tag.set(data, this._tagPos); + } + p += nb; + this._tagPos += nb; + if (this._tagPos < 16) + return; + } -/** - * Helpers. - */ + this._instance.decrypt(this._packet, this._len, this._tag); -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; + const payload = new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1); -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._pktLen = 0; + this._tagPos = 0; -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } + } } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +} -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ +// TODO: test incremental .update()s vs. copying to _packet and doing a single +// .update() after entire packet read -- a single .update() would allow +// verifying MAC before decrypting for ETM MACs +class GenericDecipherNative { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV); + this._decipherInstance.setAutoPadding(false); + this._block = Buffer.allocUnsafe( + dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen + ); + this._blockSize = dec.decipherInfo.blockLen; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); + this._macPos = 0; + this._macSSLName = dec.macInfo.sslName; + this._macKey = dec.macKey; + this._macActualLen = dec.macInfo.actualLen; + this._macETM = dec.macInfo.isETM; + this._macInstance = null; -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; + const discardLen = dec.decipherInfo.discardLen; + if (discardLen) { + let discard = DISCARD_CACHE.get(discardLen); + if (discard === undefined) { + discard = Buffer.alloc(discardLen); + DISCARD_CACHE.set(discardLen, discard); + } + this._decipherInstance.update(discard); + } } -} + free() {} + decrypt(data, p, dataLen) { + // `data` === encrypted data -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + while (p < dataLen) { + // Read first encrypted block + if (this._blockPos < this._block.length) { + const nb = Math.min(this._block.length - this._blockPos, dataLen - p); + if (p !== 0 || nb !== dataLen || nb < data.length) { + this._block.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._blockPos + ); + } else { + this._block.set(data, this._blockPos); + } -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} + p += nb; + this._blockPos += nb; + if (this._blockPos < this._block.length) + return; -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + let decrypted; + let need; + if (this._macETM) { + this._len = need = readUInt32BE(this._block, 0); + } else { + // Decrypt first block to get packet length + decrypted = this._decipherInstance.update(this._block); + this._len = readUInt32BE(decrypted, 0); + need = 4 + this._len - this._blockSize; + } -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} + if (this._len > MAX_PACKET_SIZE + || this._len < 5 + || (need & (this._blockSize - 1)) !== 0) { + throw new Error('Bad packet length'); + } -/** - * Pluralization helper. - */ + // Create MAC up front to calculate in parallel with decryption + this._macInstance = createHmac(this._macSSLName, this._macKey); -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} + writeUInt32BE(BUF_INT, this.inSeqno, 0); + this._macInstance.update(BUF_INT); + if (this._macETM) { + this._macInstance.update(this._block); + } else { + this._macInstance.update(new Uint8Array(decrypted.buffer, + decrypted.byteOffset, + 4)); + this._pktLen = decrypted.length - 4; + this._packetPos = this._pktLen; + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set( + new Uint8Array(decrypted.buffer, + decrypted.byteOffset + 4, + this._packetPos), + 0 + ); + } + if (p >= dataLen) + return; + } -/***/ }), + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (this._macETM) + this._macInstance.update(encrypted); + const decrypted = this._decipherInstance.update(encrypted); + if (decrypted.length) { + if (nb === this._len) { + this._packet = decrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(decrypted, this._packetPos); + } + this._packetPos += decrypted.length; + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } -/***/ 1223: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Read MAC + { + const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < this._macActualLen) + return; + } -var wrappy = __nccwpck_require__(2940) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + // Verify MAC + if (!this._macETM) + this._macInstance.update(this._packet); + let calculated = this._macInstance.digest(); + if (this._macActualLen < calculated.length) { + calculated = new Uint8Array(calculated.buffer, + calculated.byteOffset, + this._macActualLen); + } + if (!timingSafeEquals(calculated, this._mac)) + throw new Error('Invalid MAC'); -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) + const payload = new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1); - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._macPos = 0; + this._macInstance = null; -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } + } } - f.called = false - return f } -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) +class GenericDecipherBinding { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new GenericDecipher(dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV, + dec.macInfo.sslName, + dec.macKey, + dec.macInfo.isETM, + dec.macInfo.actualLen); + this._block = Buffer.allocUnsafe( + dec.macInfo.isETM || dec.decipherInfo.stream + ? 4 + : dec.decipherInfo.blockLen + ); + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); + this._macPos = 0; + this._macActualLen = dec.macInfo.actualLen; + this._macETM = dec.macInfo.isETM; } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), - -/***/ 8341: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(1223) -var eos = __nccwpck_require__(1205) -var fs = __nccwpck_require__(7147) // we only need fs to get the ReadStream and WriteStream prototypes + free() { + this._instance.free(); + } + decrypt(data, p, dataLen) { + // `data` === encrypted data -var noop = function () {} -var ancient = /^v?\.0/.test(process.version) + while (p < dataLen) { + // Read first encrypted block + if (this._blockPos < this._block.length) { + const nb = Math.min(this._block.length - this._blockPos, dataLen - p); + if (p !== 0 || nb !== dataLen || nb < data.length) { + this._block.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._blockPos + ); + } else { + this._block.set(data, this._blockPos); + } -var isFn = function (fn) { - return typeof fn === 'function' -} + p += nb; + this._blockPos += nb; + if (this._blockPos < this._block.length) + return; -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) -} + let need; + if (this._macETM) { + this._len = need = readUInt32BE(this._block, 0); + } else { + // Decrypt first block to get packet length + this._instance.decryptBlock(this._block); + this._len = readUInt32BE(this._block, 0); + need = 4 + this._len - this._block.length; + } -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) -} + if (this._len > MAX_PACKET_SIZE + || this._len < 5 + || (need & (this._block.length - 1)) !== 0) { + throw new Error('Bad packet length'); + } -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) + if (!this._macETM) { + this._pktLen = (this._block.length - 4); + if (this._pktLen) { + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set( + new Uint8Array(this._block.buffer, + this._block.byteOffset + 4, + this._pktLen), + 0 + ); + } + } - var closed = false - stream.on('close', function () { - closed = true - }) + if (p >= dataLen) + return; + } - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true + // Read MAC + { + const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < this._macActualLen) + return; + } - 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 + // Decrypt and verify MAC + this._instance.decrypt(this._packet, + this.inSeqno, + this._block, + this._mac); - if (isFn(stream.destroy)) return stream.destroy() + const payload = new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1); - callback(err || new Error('stream was destroyed')) - } -} + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; + this._macInstance = null; -var call = function (fn) { - fn() + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } + } + } } -var pipe = function (from, to) { - return from.pipe(to) +// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV +function ivIncrement(iv) { + // eslint-disable-next-line no-unused-expressions + ++iv[11] >>> 8 + && ++iv[10] >>> 8 + && ++iv[9] >>> 8 + && ++iv[8] >>> 8 + && ++iv[7] >>> 8 + && ++iv[6] >>> 8 + && ++iv[5] >>> 8 + && ++iv[4] >>> 8; } -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) - }) - }) +const intToBytes = (() => { + const ret = Buffer.alloc(4); + return (n) => { + ret[0] = (n >>> 24); + ret[1] = (n >>> 16); + ret[2] = (n >>> 8); + ret[3] = n; + return ret; + }; +})(); - return streams.reduce(pipe) +function timingSafeEquals(a, b) { + if (a.length !== b.length) { + timingSafeEqual(a, a); + return false; + } + return timingSafeEqual(a, b); } -module.exports = pump - - -/***/ }), +function createCipher(config) { + if (typeof config !== 'object' || config === null) + throw new Error('Invalid config'); -/***/ 7214: -/***/ ((module) => { + if (typeof config.outbound !== 'object' || config.outbound === null) + throw new Error('Invalid outbound'); -"use strict"; + const outbound = config.outbound; + if (typeof outbound.onWrite !== 'function') + throw new Error('Invalid outbound.onWrite'); -const codes = {}; + if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) + throw new Error('Invalid outbound.cipherInfo'); -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error + if (!Buffer.isBuffer(outbound.cipherKey) + || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { + throw new Error('Invalid outbound.cipherKey'); } - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) - } + if (outbound.cipherInfo.ivLen + && (!Buffer.isBuffer(outbound.cipherIV) + || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { + throw new Error('Invalid outbound.cipherIV'); } - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } + if (typeof outbound.seqno !== 'number' + || outbound.seqno < 0 + || outbound.seqno > MAX_SEQNO) { + throw new Error('Invalid outbound.seqno'); } - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - - codes[code] = NodeError; -} + const forceNative = !!outbound.forceNative; -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; + switch (outbound.cipherInfo.sslName) { + case 'aes-128-gcm': + case 'aes-256-gcm': + return (AESGCMCipher && !forceNative + ? new AESGCMCipherBinding(config) + : new AESGCMCipherNative(config)); + case 'chacha20': + return (ChaChaPolyCipher && !forceNative + ? new ChaChaPolyCipherBinding(config) + : new ChaChaPolyCipherNative(config)); + default: { + if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) + throw new Error('Invalid outbound.macInfo'); + if (!Buffer.isBuffer(outbound.macKey) + || outbound.macKey.length !== outbound.macInfo.len) { + throw new Error('Invalid outbound.macKey'); + } + return (GenericCipher && !forceNative + ? new GenericCipherBinding(config) + : new GenericCipherNative(config)); } - } else { - return `of ${thing} ${String(expected)}`; } } -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} +function createDecipher(config) { + if (typeof config !== 'object' || config === null) + throw new Error('Invalid config'); -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} + if (typeof config.inbound !== 'object' || config.inbound === null) + throw new Error('Invalid inbound'); -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } + const inbound = config.inbound; - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} + if (typeof inbound.onPayload !== 'function') + throw new Error('Invalid inbound.onPayload'); -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; + if (typeof inbound.decipherInfo !== 'object' + || inbound.decipherInfo === null) { + throw new Error('Invalid inbound.decipherInfo'); } - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + if (!Buffer.isBuffer(inbound.decipherKey) + || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { + throw new Error('Invalid inbound.decipherKey'); } - msg += `. Received type ${typeof actual}`; - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - -module.exports.q = codes; - - -/***/ }), - -/***/ 1359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. + if (inbound.decipherInfo.ivLen + && (!Buffer.isBuffer(inbound.decipherIV) + || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { + throw new Error('Invalid inbound.decipherIV'); + } -/**/ + if (typeof inbound.seqno !== 'number' + || inbound.seqno < 0 + || inbound.seqno > MAX_SEQNO) { + throw new Error('Invalid inbound.seqno'); + } -var objectKeys = Object.keys || function (obj) { - var keys = []; + const forceNative = !!inbound.forceNative; - for (var key in obj) { - keys.push(key); + switch (inbound.decipherInfo.sslName) { + case 'aes-128-gcm': + case 'aes-256-gcm': + return (AESGCMDecipher && !forceNative + ? new AESGCMDecipherBinding(config) + : new AESGCMDecipherNative(config)); + case 'chacha20': + return (ChaChaPolyDecipher && !forceNative + ? new ChaChaPolyDecipherBinding(config) + : new ChaChaPolyDecipherNative(config)); + default: { + if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) + throw new Error('Invalid inbound.macInfo'); + if (!Buffer.isBuffer(inbound.macKey) + || inbound.macKey.length !== inbound.macInfo.len) { + throw new Error('Invalid inbound.macKey'); + } + return (GenericDecipher && !forceNative + ? new GenericDecipherBinding(config) + : new GenericDecipherNative(config)); + } } +} - return keys; -}; -/**/ +module.exports = { + CIPHER_INFO, + MAC_INFO, + bindingAvailable: !!binding, + init: (() => { + // eslint-disable-next-line no-async-promise-executor + return new Promise(async (resolve, reject) => { + try { + POLY1305_WASM_MODULE = await __nccwpck_require__(4989)(); + POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); + poly1305_auth = POLY1305_WASM_MODULE.cwrap( + 'poly1305_auth', + null, + ['number', 'array', 'number', 'array', 'number', 'array'] + ); + } catch (ex) { + return reject(ex); + } + resolve(); + }); + })(), + NullCipher, + createCipher, + NullDecipher, + createDecipher, +}; -module.exports = Duplex; -var Readable = __nccwpck_require__(1433); +/***/ }), -var Writable = __nccwpck_require__(6993); +/***/ 4989: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -__nccwpck_require__(4124)(Duplex, Readable); -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); +var createPoly1305 = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(createPoly1305) { + createPoly1305 = createPoly1305 || {}; - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; +var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; +if(z)B=y?(__nccwpck_require__(1017).dirname)(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=__nccwpck_require__(7147));G||(G=__nccwpck_require__(1017));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=__nccwpck_require__(7147));G||(G=__nccwpck_require__(1017));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= +0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; +function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; +function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} +function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} +function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; +(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, +a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); +b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; +b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; +function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 { - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed +"use strict"; - this._readableState.destroyed = value; - this._writableState.destroyed = value; +const MESSAGE_HANDLERS = new Array(256); +[ + (__nccwpck_require__(4126).HANDLERS), + __nccwpck_require__(6475), +].forEach((handlers) => { + // eslint-disable-next-line prefer-const + for (let [type, handler] of Object.entries(handlers)) { + type = +type; + if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) + MESSAGE_HANDLERS[type] = handler; } }); +module.exports = MESSAGE_HANDLERS; + + /***/ }), -/***/ 1542: +/***/ 6475: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - - -module.exports = PassThrough; - -var Transform = __nccwpck_require__(4415); - -__nccwpck_require__(4124)(PassThrough, Transform); -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; +const { + bufferSlice, + bufferParser, + doFatalError, + sigSSHToASN1, + writeUInt32BE, +} = __nccwpck_require__(9475); -/***/ }), +const { + CHANNEL_OPEN_FAILURE, + COMPAT, + MESSAGE, + TERMINAL_MODE, +} = __nccwpck_require__(6832); -/***/ 1433: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const { + parseKey, +} = __nccwpck_require__(2218); -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. +const TERMINAL_MODE_BY_VALUE = + Array.from(Object.entries(TERMINAL_MODE)) + .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); +module.exports = { + // Transport layer protocol ================================================== + [MESSAGE.DISCONNECT]: (self, payload) => { + /* + byte SSH_MSG_DISCONNECT + uint32 reason code + string description in ISO-10646 UTF-8 encoding + string language tag + */ + bufferParser.init(payload, 1); + const reason = bufferParser.readUInt32BE(); + const desc = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); -module.exports = Readable; -/**/ + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed DISCONNECT packet' + ); + } -var Duplex; -/**/ + self._debug && self._debug( + `Inbound: Received DISCONNECT (${reason}, "${desc}")` + ); -Readable.ReadableState = ReadableState; -/**/ + const handler = self._handlers.DISCONNECT; + handler && handler(self, reason, desc); + }, + [MESSAGE.IGNORE]: (self, payload) => { + /* + byte SSH_MSG_IGNORE + string data + */ + self._debug && self._debug('Inbound: Received IGNORE'); + }, + [MESSAGE.UNIMPLEMENTED]: (self, payload) => { + /* + byte SSH_MSG_UNIMPLEMENTED + uint32 packet sequence number of rejected message + */ + bufferParser.init(payload, 1); + const seqno = bufferParser.readUInt32BE(); + bufferParser.clear(); -var EE = (__nccwpck_require__(2361).EventEmitter); + if (seqno === undefined) { + return doFatalError( + self, + 'Inbound: Malformed UNIMPLEMENTED packet' + ); + } -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + self._debug + && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); + }, + [MESSAGE.DEBUG]: (self, payload) => { + /* + byte SSH_MSG_DEBUG + boolean always_display + string message in ISO-10646 UTF-8 encoding [RFC3629] + string language tag [RFC3066] + */ + bufferParser.init(payload, 1); + const display = bufferParser.readBool(); + const msg = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); -/**/ + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed DEBUG packet' + ); + } + self._debug && self._debug('Inbound: Received DEBUG'); -var Stream = __nccwpck_require__(2387); -/**/ + const handler = self._handlers.DEBUG; + handler && handler(self, display, msg); + }, + [MESSAGE.SERVICE_REQUEST]: (self, payload) => { + /* + byte SSH_MSG_SERVICE_REQUEST + string service name + */ + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + bufferParser.clear(); + if (name === undefined) { + return doFatalError( + self, + 'Inbound: Malformed SERVICE_REQUEST packet' + ); + } -var Buffer = (__nccwpck_require__(4300).Buffer); + self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); -var OurUint8Array = global.Uint8Array || function () {}; + const handler = self._handlers.SERVICE_REQUEST; + handler && handler(self, name); + }, + [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { + // S->C + /* + byte SSH_MSG_SERVICE_ACCEPT + string service name + */ + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + bufferParser.clear(); -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} + if (name === undefined) { + return doFatalError( + self, + 'Inbound: Malformed SERVICE_ACCEPT packet' + ); + } -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ + self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); + const handler = self._handlers.SERVICE_ACCEPT; + handler && handler(self, name); + }, + [MESSAGE.EXT_INFO]: (self, payload) => { + /* + byte SSH_MSG_EXT_INFO + uint32 nr-extensions + repeat the following 2 fields "nr-extensions" times: + string extension-name + string extension-value (binary) + */ + bufferParser.init(payload, 1); + const numExts = bufferParser.readUInt32BE(); + let exts; + if (numExts !== undefined) { + exts = []; + for (let i = 0; i < numExts; ++i) { + const name = bufferParser.readString(true); + const data = bufferParser.readString(); + if (data !== undefined) { + switch (name) { + case 'server-sig-algs': { + const algs = data.latin1Slice(0, data.length).split(','); + exts.push({ name, algs }); + continue; + } + default: + continue; + } + } + // Malformed + exts = undefined; + break; + } + } + bufferParser.clear(); -var debugUtil = __nccwpck_require__(3837); + if (exts === undefined) + return doFatalError(self, 'Inbound: Malformed EXT_INFO packet'); -var debug; + self._debug && self._debug('Inbound: Received EXT_INFO'); -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ + const handler = self._handlers.EXT_INFO; + handler && handler(self, exts); + }, + // User auth protocol -- generic ============================================= + [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { + /* + byte SSH_MSG_USERAUTH_REQUEST + string user name in ISO-10646 UTF-8 encoding [RFC3629] + string service name in US-ASCII + string method name in US-ASCII + .... method specific fields + */ + bufferParser.init(payload, 1); + const user = bufferParser.readString(true); + const service = bufferParser.readString(true); + const method = bufferParser.readString(true); + let methodData; + let methodDesc; + switch (method) { + case 'none': + methodData = null; + break; + case 'password': { + /* + boolean + string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] + [string new password] + */ + const isChange = bufferParser.readBool(); + if (isChange !== undefined) { + methodData = bufferParser.readString(true); + if (methodData !== undefined && isChange) { + const newPassword = bufferParser.readString(true); + if (newPassword !== undefined) + methodData = { oldPassword: methodData, newPassword }; + else + methodData = undefined; + } + } + break; + } + case 'publickey': { + /* + boolean + string public key algorithm name + string public key blob + [string signature] + */ + const hasSig = bufferParser.readBool(); + if (hasSig !== undefined) { + const keyAlgo = bufferParser.readString(true); + let realKeyAlgo = keyAlgo; + const key = bufferParser.readString(); -var BufferList = __nccwpck_require__(6522); + let hashAlgo; + switch (keyAlgo) { + case 'rsa-sha2-256': + realKeyAlgo = 'ssh-rsa'; + hashAlgo = 'sha256'; + break; + case 'rsa-sha2-512': + realKeyAlgo = 'ssh-rsa'; + hashAlgo = 'sha512'; + break; + } -var destroyImpl = __nccwpck_require__(7049); + if (hasSig) { + const blobEnd = bufferParser.pos(); + let signature = bufferParser.readString(); + if (signature !== undefined) { + if (signature.length > (4 + keyAlgo.length + 4) + && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { + // Skip algoLen + algo + sigLen + signature = bufferSlice(signature, 4 + keyAlgo.length + 4); + } -var _require = __nccwpck_require__(9948), - getHighWaterMark = _require.getHighWaterMark; + signature = sigSSHToASN1(signature, realKeyAlgo); + if (signature) { + const sessionID = self._kex.sessionID; + const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); + writeUInt32BE(blob, sessionID.length, 0); + blob.set(sessionID, 4); + blob.set( + new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), + 4 + sessionID.length + ); + methodData = { + keyAlgo: realKeyAlgo, + key, + signature, + blob, + hashAlgo, + }; + } + } + } else { + methodData = { keyAlgo: realKeyAlgo, key, hashAlgo }; + methodDesc = 'publickey -- check'; + } + } + break; + } + case 'hostbased': { + /* + string public key algorithm for host key + string public host key and certificates for client host + string client host name expressed as the FQDN in US-ASCII + string user name on the client host in ISO-10646 UTF-8 encoding + [RFC3629] + string signature + */ + const keyAlgo = bufferParser.readString(true); + let realKeyAlgo = keyAlgo; + const key = bufferParser.readString(); + const localHostname = bufferParser.readString(true); + const localUsername = bufferParser.readString(true); -var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + let hashAlgo; + switch (keyAlgo) { + case 'rsa-sha2-256': + realKeyAlgo = 'ssh-rsa'; + hashAlgo = 'sha256'; + break; + case 'rsa-sha2-512': + realKeyAlgo = 'ssh-rsa'; + hashAlgo = 'sha512'; + break; + } + const blobEnd = bufferParser.pos(); + let signature = bufferParser.readString(); + if (signature !== undefined) { + if (signature.length > (4 + keyAlgo.length + 4) + && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { + // Skip algoLen + algo + sigLen + signature = bufferSlice(signature, 4 + keyAlgo.length + 4); + } -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; + signature = sigSSHToASN1(signature, realKeyAlgo); + if (signature !== undefined) { + const sessionID = self._kex.sessionID; + const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); + writeUInt32BE(blob, sessionID.length, 0); + blob.set(sessionID, 4); + blob.set( + new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), + 4 + sessionID.length + ); + methodData = { + keyAlgo: realKeyAlgo, + key, + signature, + blob, + localHostname, + localUsername, + hashAlgo + }; + } + } + break; + } + case 'keyboard-interactive': + /* + string language tag (as defined in [RFC-3066]) + string submethods (ISO-10646 UTF-8) + */ + // Skip/ignore language field -- it's deprecated in RFC 4256 + bufferParser.skipString(); -__nccwpck_require__(4124)(Readable, Stream); + methodData = bufferParser.readList(); + break; + default: + if (method !== undefined) + methodData = bufferParser.readRaw(); + } + bufferParser.clear(); -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + if (methodData === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_REQUEST packet' + ); + } -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. + if (methodDesc === undefined) + methodDesc = method; - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} + self._authsQueue.push(method); -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(1359); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. + self._debug + && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away + const handler = self._handlers.USERAUTH_REQUEST; + handler && handler(self, user, service, method, methodData); + }, + [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { + // S->C + /* + byte SSH_MSG_USERAUTH_FAILURE + name-list authentications that can continue + boolean partial success + */ + bufferParser.init(payload, 1); + const authMethods = bufferParser.readList(); + const partialSuccess = bufferParser.readBool(); + bufferParser.clear(); - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" + if (partialSuccess === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_FAILURE packet' + ); + } - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() + self._debug + && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. + self._authsQueue.shift(); + const handler = self._handlers.USERAUTH_FAILURE; + handler && handler(self, authMethods, partialSuccess); + }, + [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { + // S->C + /* + byte SSH_MSG_USERAUTH_SUCCESS + */ + self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. + self._authsQueue.shift(); + const handler = self._handlers.USERAUTH_SUCCESS; + handler && handler(self); + }, + [MESSAGE.USERAUTH_BANNER]: (self, payload) => { + // S->C + /* + byte SSH_MSG_USERAUTH_BANNER + string message in ISO-10646 UTF-8 encoding [RFC3629] + string language tag [RFC3066] + */ + bufferParser.init(payload, 1); + const msg = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_BANNER packet' + ); + } - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); - this.autoDestroy = !!options.autoDestroy; // has it been destroyed + const handler = self._handlers.USERAUTH_BANNER; + handler && handler(self, msg); + }, - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + // User auth protocol -- method-specific ===================================== + 60: (self, payload) => { + if (!self._authsQueue.length) { + self._debug + && self._debug('Inbound: Received payload type 60 without auth'); + return; + } - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + switch (self._authsQueue[0]) { + case 'password': { + // S->C + /* + byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ + string prompt in ISO-10646 UTF-8 encoding [RFC3629] + string language tag [RFC3066] + */ + bufferParser.init(payload, 1); + const prompt = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' + ); + } - this.readingMore = false; - this.decoder = null; - this.encoding = null; + self._debug + && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} + const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; + handler && handler(self, prompt); + break; + } + case 'publickey': { + // S->C + /* + byte SSH_MSG_USERAUTH_PK_OK + string public key algorithm name from the request + string public key blob from the request + */ + bufferParser.init(payload, 1); + const keyAlgo = bufferParser.readString(true); + const key = bufferParser.readString(); + bufferParser.clear(); -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(1359); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 + if (key === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_PK_OK packet' + ); + } - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy + self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); - this.readable = true; + self._authsQueue.shift(); + const handler = self._handlers.USERAUTH_PK_OK; + handler && handler(self, keyAlgo, key); + break; + } + case 'keyboard-interactive': { + // S->C + /* + byte SSH_MSG_USERAUTH_INFO_REQUEST + string name (ISO-10646 UTF-8) + string instruction (ISO-10646 UTF-8) + string language tag (as defined in [RFC-3066]) + int num-prompts + string prompt[1] (ISO-10646 UTF-8) + boolean echo[1] + ... + string prompt[num-prompts] (ISO-10646 UTF-8) + boolean echo[num-prompts] + */ + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + const instructions = bufferParser.readString(true); + bufferParser.readString(); // skip lang + const numPrompts = bufferParser.readUInt32BE(); + let prompts; + if (numPrompts !== undefined) { + prompts = new Array(numPrompts); + let i; + for (i = 0; i < numPrompts; ++i) { + const prompt = bufferParser.readString(true); + const echo = bufferParser.readBool(); + if (echo === undefined) + break; + prompts[i] = { prompt, echo }; + } + if (i !== numPrompts) + prompts = undefined; + } + bufferParser.clear(); - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } + if (prompts === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' + ); + } - Stream.call(this); -} + self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; + const handler = self._handlers.USERAUTH_INFO_REQUEST; + handler && handler(self, name, instructions, prompts); + break; + } + default: + self._debug + && self._debug('Inbound: Received unexpected payload type 60'); } - - return this._readableState.destroyed; }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { + 61: (self, payload) => { + if (!self._authsQueue.length) { + self._debug + && self._debug('Inbound: Received payload type 61 without auth'); return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. + } + /* + byte SSH_MSG_USERAUTH_INFO_RESPONSE + int num-responses + string response[1] (ISO-10646 UTF-8) + ... + string response[num-responses] (ISO-10646 UTF-8) + */ + if (self._authsQueue[0] !== 'keyboard-interactive') { + return doFatalError( + self, + 'Inbound: Received unexpected payload type 61' + ); + } + bufferParser.init(payload, 1); + const numResponses = bufferParser.readUInt32BE(); + let responses; + if (numResponses !== undefined) { + responses = new Array(numResponses); + let i; + for (i = 0; i < numResponses; ++i) { + const response = bufferParser.readString(true); + if (response === undefined) + break; + responses[i] = response; + } + if (i !== numResponses) + responses = undefined; + } + bufferParser.clear(); + if (responses === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' + ); + } -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + const handler = self._handlers.USERAUTH_INFO_RESPONSE; + handler && handler(self, responses); + }, - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; + // Connection protocol -- generic ============================================ + [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { + /* + byte SSH_MSG_GLOBAL_REQUEST + string request name in US-ASCII only + boolean want reply + .... request-specific data follows + */ + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + const wantReply = bufferParser.readBool(); + let data; + if (wantReply !== undefined) { + switch (name) { + case 'tcpip-forward': + case 'cancel-tcpip-forward': { + /* + string address to bind (e.g., "0.0.0.0") + uint32 port number to bind + */ + const bindAddr = bufferParser.readString(true); + const bindPort = bufferParser.readUInt32BE(); + if (bindPort !== undefined) + data = { bindAddr, bindPort }; + break; + } + case 'streamlocal-forward@openssh.com': + case 'cancel-streamlocal-forward@openssh.com': { + /* + string socket path + */ + const socketPath = bufferParser.readString(true); + if (socketPath !== undefined) + data = { socketPath }; + break; + } + case 'no-more-sessions@openssh.com': + data = null; + break; + case 'hostkeys-00@openssh.com': { + data = []; + while (bufferParser.avail() > 0) { + const keyRaw = bufferParser.readString(); + if (keyRaw === undefined) { + data = undefined; + break; + } + const key = parseKey(keyRaw); + if (!(key instanceof Error)) + data.push(key); + } + break; + } + default: + data = bufferParser.readRaw(); } + } + bufferParser.clear(); - skipChunkCheck = true; + if (data === undefined) { + return doFatalError( + self, + 'Inbound: Malformed GLOBAL_REQUEST packet' + ); } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() + self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); + const handler = self._handlers.GLOBAL_REQUEST; + if (handler) + handler(self, name, wantReply, data); + else + self.requestFailure(); // Auto reject + }, + [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { + /* + byte SSH_MSG_REQUEST_SUCCESS + .... response specific data + */ + const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; + self._debug && self._debug('Inbound: REQUEST_SUCCESS'); -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; + const handler = self._handlers.REQUEST_SUCCESS; + handler && handler(self, data); + }, + [MESSAGE.REQUEST_FAILURE]: (self, payload) => { + /* + byte SSH_MSG_REQUEST_FAILURE + */ + self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); + const handler = self._handlers.REQUEST_FAILURE; + handler && handler(self); + }, - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + // Connection protocol -- channel-related ==================================== + [MESSAGE.CHANNEL_OPEN]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_OPEN + string channel type in US-ASCII only + uint32 sender channel + uint32 initial window size + uint32 maximum packet size + .... channel type specific data follows + */ + bufferParser.init(payload, 1); + const type = bufferParser.readString(true); + const sender = bufferParser.readUInt32BE(); + const window = bufferParser.readUInt32BE(); + const packetSize = bufferParser.readUInt32BE(); + let channelInfo; - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; + switch (type) { + case 'forwarded-tcpip': // S->C + case 'direct-tcpip': { // C->S + /* + string address that was connected / host to connect + uint32 port that was connected / port to connect + string originator IP address + uint32 originator port + */ + const destIP = bufferParser.readString(true); + const destPort = bufferParser.readUInt32BE(); + const srcIP = bufferParser.readString(true); + const srcPort = bufferParser.readUInt32BE(); + if (srcPort !== undefined) { + channelInfo = { + type, + sender, + window, + packetSize, + data: { destIP, destPort, srcIP, srcPort } + }; + } + break; + } + case 'forwarded-streamlocal@openssh.com': // S->C + case 'direct-streamlocal@openssh.com': { // C->S + /* + string socket path + string reserved for future use - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); + (direct-streamlocal@openssh.com additionally has:) + uint32 reserved + */ + const socketPath = bufferParser.readString(true); + if (socketPath !== undefined) { + channelInfo = { + type, + sender, + window, + packetSize, + data: { socketPath } + }; } + break; } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); + case 'x11': { // S->C + /* + string originator address (e.g., "192.168.7.38") + uint32 originator port + */ + const srcIP = bufferParser.readString(true); + const srcPort = bufferParser.readUInt32BE(); + if (srcPort !== undefined) { + channelInfo = { + type, + sender, + window, + packetSize, + data: { srcIP, srcPort } + }; + } + break; + } + default: + // Includes: + // 'session' (C->S) + // 'auth-agent@openssh.com' (S->C) + channelInfo = { + type, + sender, + window, + packetSize, + data: {} + }; + } + bufferParser.clear(); + + if (channelInfo === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_OPEN packet' + ); + } + + self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); + + const handler = self._handlers.CHANNEL_OPEN; + if (handler) { + handler(self, channelInfo); + } else { + self.channelOpenFail( + channelInfo.sender, + CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, + '', + '' + ); + } + }, + [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION + uint32 recipient channel + uint32 sender channel + uint32 initial window size + uint32 maximum packet size + .... channel type specific data follows + */ + // "The 'recipient channel' is the channel number given in the + // original open request, and 'sender channel' is the channel number + // allocated by the other side." + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const sender = bufferParser.readUInt32BE(); + const window = bufferParser.readUInt32BE(); + const packetSize = bufferParser.readUInt32BE(); + const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); + bufferParser.clear(); + + if (packetSize === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' + ); + } + + self._debug && self._debug( + `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` + ); + + const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; + if (handler) + handler(self, { recipient, sender, window, packetSize, data }); + }, + [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_OPEN_FAILURE + uint32 recipient channel + uint32 reason code + string description in ISO-10646 UTF-8 encoding [RFC3629] + string language tag [RFC3066] + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const reason = bufferParser.readUInt32BE(); + const description = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); + + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' + ); } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. + self._debug + && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} + const handler = self._handlers.CHANNEL_OPEN_FAILURE; + handler && handler(self, recipient, reason, description); + }, + [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_WINDOW_ADJUST + uint32 recipient channel + uint32 bytes to add + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const bytesToAdd = bufferParser.readUInt32BE(); + bufferParser.clear(); -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } + if (bytesToAdd === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' + ); + } - maybeReadMore(stream, state); -} + self._debug && self._debug( + `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` + ); -function chunkInvalid(state, chunk) { - var er; + const handler = self._handlers.CHANNEL_WINDOW_ADJUST; + handler && handler(self, recipient, bytesToAdd); + }, + [MESSAGE.CHANNEL_DATA]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_DATA + uint32 recipient channel + string data + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const data = bufferParser.readString(); + bufferParser.clear(); - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } + if (data === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_DATA packet' + ); + } - return er; -} + self._debug + && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. + const handler = self._handlers.CHANNEL_DATA; + handler && handler(self, recipient, data); + }, + [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_EXTENDED_DATA + uint32 recipient channel + uint32 data_type_code + string data + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const type = bufferParser.readUInt32BE(); + const data = bufferParser.readString(); + bufferParser.clear(); + if (data === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' + ); + } -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + self._debug && self._debug( + `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` + ); - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + const handler = self._handlers.CHANNEL_EXTENDED_DATA; + handler && handler(self, recipient, data, type); + }, + [MESSAGE.CHANNEL_EOF]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_EOF + uint32 recipient channel + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); - var p = this._readableState.buffer.head; - var content = ''; + if (recipient === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_EOF packet' + ); + } - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } + self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); - this._readableState.buffer.clear(); + const handler = self._handlers.CHANNEL_EOF; + handler && handler(self, recipient); + }, + [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_CLOSE + uint32 recipient channel + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB + if (recipient === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_CLOSE packet' + ); + } + self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); -var MAX_HWM = 0x40000000; + const handler = self._handlers.CHANNEL_CLOSE; + handler && handler(self, recipient); + }, + [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_REQUEST + uint32 recipient channel + string request type in US-ASCII characters only + boolean want reply + .... type-specific data follows + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const type = bufferParser.readString(true); + const wantReply = bufferParser.readBool(); + let data; + if (wantReply !== undefined) { + switch (type) { + case 'exit-status': // S->C + /* + uint32 exit_status + */ + data = bufferParser.readUInt32BE(); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'exit-signal': { // S->C + /* + string signal name (without the "SIG" prefix) + boolean core dumped + string error message in ISO-10646 UTF-8 encoding + string language tag + */ + let signal; + let coreDumped; + if (self._compatFlags & COMPAT.OLD_EXIT) { + /* + Instead of `signal name` and `core dumped`, we have just: + uint32 signal number + */ + const num = bufferParser.readUInt32BE(); + switch (num) { + case 1: + signal = 'HUP'; + break; + case 2: + signal = 'INT'; + break; + case 3: + signal = 'QUIT'; + break; + case 6: + signal = 'ABRT'; + break; + case 9: + signal = 'KILL'; + break; + case 14: + signal = 'ALRM'; + break; + case 15: + signal = 'TERM'; + break; + default: + if (num !== undefined) { + // Unknown or OS-specific + signal = `UNKNOWN (${num})`; + } + } + coreDumped = false; + } else { + signal = bufferParser.readString(true); + coreDumped = bufferParser.readBool(); + if (coreDumped === undefined) + signal = undefined; + } + const errorMessage = bufferParser.readString(true); + if (bufferParser.skipString() !== undefined) + data = { signal, coreDumped, errorMessage }; + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` + ); + break; + } + case 'pty-req': { // C->S + /* + string TERM environment variable value (e.g., vt100) + uint32 terminal width, characters (e.g., 80) + uint32 terminal height, rows (e.g., 24) + uint32 terminal width, pixels (e.g., 640) + uint32 terminal height, pixels (e.g., 480) + string encoded terminal modes + */ + const term = bufferParser.readString(true); + const cols = bufferParser.readUInt32BE(); + const rows = bufferParser.readUInt32BE(); + const width = bufferParser.readUInt32BE(); + const height = bufferParser.readUInt32BE(); + const modesBinary = bufferParser.readString(); + if (modesBinary !== undefined) { + bufferParser.init(modesBinary, 1); + let modes = {}; + while (bufferParser.avail()) { + const opcode = bufferParser.readByte(); + if (opcode === TERMINAL_MODE.TTY_OP_END) + break; + const name = TERMINAL_MODE_BY_VALUE[opcode]; + const value = bufferParser.readUInt32BE(); + if (opcode === undefined + || name === undefined + || value === undefined) { + modes = undefined; + break; + } + modes[name] = value; + } + if (modes !== undefined) + data = { term, cols, rows, width, height, modes }; + } + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case 'window-change': { // C->S + /* + uint32 terminal width, columns + uint32 terminal height, rows + uint32 terminal width, pixels + uint32 terminal height, pixels + */ + const cols = bufferParser.readUInt32BE(); + const rows = bufferParser.readUInt32BE(); + const width = bufferParser.readUInt32BE(); + const height = bufferParser.readUInt32BE(); + if (height !== undefined) + data = { cols, rows, width, height }; + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case 'x11-req': { // C->S + /* + boolean single connection + string x11 authentication protocol + string x11 authentication cookie + uint32 x11 screen number + */ + const single = bufferParser.readBool(); + const protocol = bufferParser.readString(true); + const cookie = bufferParser.readString(); + const screen = bufferParser.readUInt32BE(); + if (screen !== undefined) + data = { single, protocol, cookie, screen }; + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case 'env': { // C->S + /* + string variable name + string variable value + */ + const name = bufferParser.readString(true); + const value = bufferParser.readString(true); + if (value !== undefined) + data = { name, value }; + if (self._debug) { + self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` + + `${name}=${value})` + ); + } + break; + } + case 'shell': // C->S + data = null; // No extra data + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + case 'exec': // C->S + /* + string command + */ + data = bufferParser.readString(true); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'subsystem': // C->S + /* + string subsystem name + */ + data = bufferParser.readString(true); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'signal': // C->S + /* + string signal name (without the "SIG" prefix) + */ + data = bufferParser.readString(true); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'xon-xoff': // C->S + /* + boolean client can do + */ + data = bufferParser.readBool(); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'auth-agent-req@openssh.com': // C-S + data = null; // No extra data + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + default: + data = (bufferParser.avail() ? bufferParser.readRaw() : null); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + } + } + bufferParser.clear(); -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } + if (data === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_REQUEST packet' + ); + } - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. + const handler = self._handlers.CHANNEL_REQUEST; + handler && handler(self, recipient, type, wantReply, data); + }, + [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_SUCCESS + uint32 recipient channel + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (recipient === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_SUCCESS packet' + ); + } -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; + self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. + const handler = self._handlers.CHANNEL_SUCCESS; + handler && handler(self, recipient); + }, + [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_FAILURE + uint32 recipient channel + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (recipient === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_FAILURE packet' + ); + } - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough + self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); - if (!state.ended) { - state.needReadable = true; - return 0; - } + const handler = self._handlers.CHANNEL_FAILURE; + handler && handler(self, recipient); + }, +}; - return state.length; -} // you can override either this method, or the async _read(n) below. +/***/ }), -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. +/***/ 4126: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } +"use strict"; - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. +const { + createDiffieHellman, + createDiffieHellmanGroup, + createECDH, + createHash, + createPublicKey, + diffieHellman, + generateKeyPairSync, + randomFillSync, +} = __nccwpck_require__(6113); +const { Ber } = __nccwpck_require__(970); - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some +const { + COMPAT, + curve25519Supported, + DEFAULT_KEX, + DEFAULT_SERVER_HOST_KEY, + DEFAULT_CIPHER, + DEFAULT_MAC, + DEFAULT_COMPRESSION, + DISCONNECT_REASON, + MESSAGE, +} = __nccwpck_require__(6832); +const { + CIPHER_INFO, + createCipher, + createDecipher, + MAC_INFO, +} = __nccwpck_require__(5708); +const { parseDERKey } = __nccwpck_require__(2218); +const { + bufferFill, + bufferParser, + convertSignature, + doFatalError, + FastBuffer, + sigSSHToASN1, + writeUInt32BE, +} = __nccwpck_require__(9475); +const { + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter, +} = __nccwpck_require__(6715); - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. +let MESSAGE_HANDLERS; +const GEX_MIN_BITS = 2048; // RFC 8270 +const GEX_MAX_BITS = 8192; // RFC 8270 - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. +const EMPTY_BUFFER = Buffer.alloc(0); - if (state.length === 0) state.needReadable = true; // call internal read method +// Client/Server +function kexinit(self) { + /* + byte SSH_MSG_KEXINIT + byte[16] cookie (random bytes) + name-list kex_algorithms + name-list server_host_key_algorithms + name-list encryption_algorithms_client_to_server + name-list encryption_algorithms_server_to_client + name-list mac_algorithms_client_to_server + name-list mac_algorithms_server_to_client + name-list compression_algorithms_client_to_server + name-list compression_algorithms_server_to_client + name-list languages_client_to_server + name-list languages_server_to_client + boolean first_kex_packet_follows + uint32 0 (reserved for future extension) + */ - this._read(state.highWaterMark); + let payload; + if (self._compatFlags & COMPAT.BAD_DHGEX) { + const entry = self._offer.lists.kex; + let kex = entry.array; + let found = false; + for (let i = 0; i < kex.length; ++i) { + if (kex[i].includes('group-exchange')) { + if (!found) { + found = true; + // Copy array lazily + kex = kex.slice(); + } + kex.splice(i--, 1); + } + } + if (found) { + let len = 1 + 16 + self._offer.totalSize + 1 + 4; + const newKexBuf = Buffer.from(kex.join(',')); + len -= (entry.buffer.length - newKexBuf.length); - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. + const all = self._offer.lists.all; + const rest = new Uint8Array( + all.buffer, + all.byteOffset + 4 + entry.buffer.length, + all.length - (4 + entry.buffer.length) + ); - if (!state.reading) n = howMuchToRead(nOrig, state); + payload = Buffer.allocUnsafe(len); + writeUInt32BE(payload, newKexBuf.length, 17); + payload.set(newKexBuf, 17 + 4); + payload.set(rest, 17 + 4 + newKexBuf.length); + } } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; + if (payload === undefined) { + payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); + self._offer.copyAllTo(payload, 17); } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + self._debug && self._debug('Outbound: Sending KEXINIT'); - if (nOrig !== n && state.ended) endReadable(this); - } + payload[0] = MESSAGE.KEXINIT; + randomFillSync(payload, 1, 16); - if (ret !== null) this.emit('data', ret); - return ret; -}; + // Zero-fill first_kex_packet_follows and reserved bytes + bufferFill(payload, 0, payload.length - 5); -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; + self._kexinit = payload; - if (state.decoder) { - var chunk = state.decoder.end(); + // Needed to correct the starting position in allocated "packets" when packets + // will be buffered due to active key exchange + self._packetRW.write.allocStart = 0; - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } + // TODO: only create single buffer and set _kexinit as slice of packet instead + { + const p = self._packetRW.write.allocStartKEX; + const packet = self._packetRW.write.alloc(payload.length, true); + packet.set(payload, p); + self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); } +} - state.ended = true; +function handleKexInit(self, payload) { + /* + byte SSH_MSG_KEXINIT + byte[16] cookie (random bytes) + name-list kex_algorithms + name-list server_host_key_algorithms + name-list encryption_algorithms_client_to_server + name-list encryption_algorithms_server_to_client + name-list mac_algorithms_client_to_server + name-list mac_algorithms_server_to_client + name-list compression_algorithms_client_to_server + name-list compression_algorithms_server_to_client + name-list languages_client_to_server + name-list languages_server_to_client + boolean first_kex_packet_follows + uint32 0 (reserved for future extension) + */ + const init = { + kex: undefined, + serverHostKey: undefined, + cs: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: undefined, + }, + sc: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: undefined, + }, + }; - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; + bufferParser.init(payload, 17); - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } + if ((init.kex = bufferParser.readList()) === undefined + || (init.serverHostKey = bufferParser.readList()) === undefined + || (init.cs.cipher = bufferParser.readList()) === undefined + || (init.sc.cipher = bufferParser.readList()) === undefined + || (init.cs.mac = bufferParser.readList()) === undefined + || (init.sc.mac = bufferParser.readList()) === undefined + || (init.cs.compress = bufferParser.readList()) === undefined + || (init.sc.compress = bufferParser.readList()) === undefined + || (init.cs.lang = bufferParser.readList()) === undefined + || (init.sc.lang = bufferParser.readList()) === undefined) { + bufferParser.clear(); + return doFatalError( + self, + 'Received malformed KEXINIT', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. + const pos = bufferParser.pos(); + const firstFollows = (pos < payload.length && payload[pos] === 1); + bufferParser.clear(); -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; + const local = self._offer; + const remote = init; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); + let localKex = local.lists.kex.array; + if (self._compatFlags & COMPAT.BAD_DHGEX) { + let found = false; + for (let i = 0; i < localKex.length; ++i) { + if (localKex[i].indexOf('group-exchange') !== -1) { + if (!found) { + found = true; + // Copy array lazily + localKex = localKex.slice(); + } + localKex.splice(i--, 1); + } + } } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. + let clientList; + let serverList; + let i; + const debug = self._debug; + debug && debug('Inbound: Handshake in progress'); - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. + // Key exchange method ======================================================= + debug && debug(`Handshake: (local) KEX method: ${localKex}`); + debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); + let remoteExtInfoEnabled; + if (self._server) { + serverList = localKex; + clientList = remote.kex; + remoteExtInfoEnabled = (clientList.indexOf('ext-info-c') !== -1); + } else { + serverList = remote.kex; + clientList = localKex; + remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1); + } + if (self._strictMode === undefined) { + if (self._server) { + self._strictMode = + (clientList.indexOf('kex-strict-c-v00@openssh.com') !== -1); + } else { + self._strictMode = + (serverList.indexOf('kex-strict-s-v00@openssh.com') !== -1); + } + // Note: We check for seqno of 1 instead of 0 since we increment before + // calling the packet handler + if (self._strictMode) { + debug && debug('Handshake: strict KEX mode enabled'); + if (self._decipher.inSeqno !== 1) { + if (debug) + debug('Handshake: KEXINIT not first packet in strict KEX mode'); + return doFatalError( + self, + 'Handshake failed: KEXINIT not first packet in strict KEX mode', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } + } + // Check for agreeable key exchange algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: no matching key exchange algorithm'); + return doFatalError( + self, + 'Handshake failed: no matching key exchange algorithm', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.kex = clientList[i]; + debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); + if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { + // Ignore next inbound packet, it was a wrong first guess at KEX algorithm + self._skipNextInboundPacket = true; + } -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); + // Server host key format ==================================================== + const localSrvHostKey = local.lists.serverHostKey.array; + debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); + debug && debug( + `Handshake: (remote) Host key format: ${remote.serverHostKey}` + ); + if (self._server) { + serverList = localSrvHostKey; + clientList = remote.serverHostKey; + } else { + serverList = remote.serverHostKey; + clientList = localSrvHostKey; } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; + // Check for agreeable server host key format + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching host key format'); + return doFatalError( + self, + 'Handshake failed: no matching host key format', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. + init.serverHostKey = clientList[i]; + debug && debug(`Handshake: Host key format: ${clientList[i]}`); -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; + // Client->Server cipher ===================================================== + const localCSCipher = local.lists.cs.cipher.array; + debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); + debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); + if (self._server) { + serverList = localCSCipher; + clientList = remote.cs.cipher; + } else { + serverList = remote.cs.cipher; + clientList = localCSCipher; + } + // Check for agreeable client->server cipher + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching C->S cipher'); + return doFatalError( + self, + 'Handshake failed: no matching C->S cipher', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.cs.cipher = clientList[i]; + debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; + // Server->Client cipher ===================================================== + const localSCCipher = local.lists.sc.cipher.array; + debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); + debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); + if (self._server) { + serverList = localSCCipher; + clientList = remote.sc.cipher; + } else { + serverList = remote.sc.cipher; + clientList = localSCCipher; + } + // Check for agreeable server->client cipher + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching S->C cipher'); + return doFatalError( + self, + 'Handshake failed: no matching S->C cipher', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.sc.cipher = clientList[i]; + debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; + // Client->Server MAC ======================================================== + const localCSMAC = local.lists.cs.mac.array; + debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); + debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); + if (CIPHER_INFO[init.cs.cipher].authLen > 0) { + init.cs.mac = ''; + debug && debug('Handshake: C->S MAC: '); + } else { + if (self._server) { + serverList = localCSMAC; + clientList = remote.cs.mac; + } else { + serverList = remote.cs.mac; + clientList = localCSMAC; + } + // Check for agreeable client->server hmac algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching C->S MAC'); + return doFatalError( + self, + 'Handshake failed: no matching C->S MAC', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.cs.mac = clientList[i]; + debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } + // Server->Client MAC ======================================================== + const localSCMAC = local.lists.sc.mac.array; + debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); + debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); + if (CIPHER_INFO[init.sc.cipher].authLen > 0) { + init.sc.mac = ''; + debug && debug('Handshake: S->C MAC: '); + } else { + if (self._server) { + serverList = localSCMAC; + clientList = remote.sc.mac; + } else { + serverList = remote.sc.mac; + clientList = localSCMAC; + } + // Check for agreeable server->client hmac algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching S->C MAC'); + return doFatalError( + self, + 'Handshake failed: no matching S->C MAC', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } + init.sc.mac = clientList[i]; + debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); } - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + // Client->Server compression ================================================ + const localCSCompress = local.lists.cs.compress.array; + debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); + debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); + if (self._server) { + serverList = localCSCompress; + clientList = remote.cs.compress; + } else { + serverList = remote.cs.compress; + clientList = localCSCompress; + } + // Check for agreeable client->server compression algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching C->S compression'); + return doFatalError( + self, + 'Handshake failed: no matching C->S compression', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } + init.cs.compress = clientList[i]; + debug && debug(`Handshake: C->S compression: ${clientList[i]}`); - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); + // Server->Client compression ================================================ + const localSCCompress = local.lists.sc.compress.array; + debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); + debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); + if (self._server) { + serverList = localSCCompress; + clientList = remote.sc.compress; + } else { + serverList = remote.sc.compress; + clientList = localSCCompress; + } + // Check for agreeable server->client compression algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching S->C compression'); + return doFatalError( + self, + 'Handshake failed: no matching S->C compression', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.sc.compress = clientList[i]; + debug && debug(`Handshake: S->C compression: ${clientList[i]}`); - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } + init.cs.lang = ''; + init.sc.lang = ''; - src.pause(); + // XXX: hack -- find a better way to do this + if (self._kex) { + if (!self._kexinit) { + // We received a rekey request, but we haven't sent a KEXINIT in response + // yet + kexinit(self); } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); + self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); } - dest.once('close', onclose); + self._kex = createKeyExchange(init, self, payload); + self._kex.remoteExtInfoEnabled = remoteExtInfoEnabled; + self._kex.start(); +} - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); +const createKeyExchange = (() => { + function convertToMpint(buf) { + let idx = 0; + let length = buf.length; + while (buf[idx] === 0x00) { + ++idx; + --length; + } + let newBuf; + if (buf[idx] & 0x80) { + newBuf = Buffer.allocUnsafe(1 + length); + newBuf[0] = 0; + buf.copy(newBuf, 1, idx); + buf = newBuf; + } else if (length !== buf.length) { + newBuf = Buffer.allocUnsafe(length); + buf.copy(newBuf, 0, idx); + buf = newBuf; + } + return buf; } - dest.once('finish', onfinish); + class KeyExchange { + constructor(negotiated, protocol, remoteKexinit) { + this._protocol = protocol; - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to + this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); + this.negotiated = negotiated; + this.remoteExtInfoEnabled = false; + this._step = 1; + this._public = null; + this._dh = null; + this._sentNEWKEYS = false; + this._receivedNEWKEYS = false; + this._finished = false; + this._hostVerified = false; + // Data needed for initializing cipher/decipher/etc. + this._kexinit = protocol._kexinit; + this._remoteKexinit = remoteKexinit; + this._identRaw = protocol._identRaw; + this._remoteIdentRaw = protocol._remoteIdentRaw; + this._hostKey = undefined; + this._dhData = undefined; + this._sig = undefined; + } + finish(scOnly) { + if (this._finished) + return false; + this._finished = true; - dest.emit('pipe', src); // start the flow if it hasn't been started already. + const isServer = this._protocol._server; + const negotiated = this.negotiated; - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } + const pubKey = this.convertPublicKey(this._dhData); + let secret = this.computeSecret(this._dhData); + if (secret instanceof Error) { + secret.message = + `Error while computing DH secret (${this.type}): ${secret.message}`; + secret.level = 'handshake'; + return doFatalError( + this._protocol, + secret, + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } - return dest; -}; + const hash = createHash(this.hashName); + // V_C + hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); + // "V_S" + hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); + // "I_C" + hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); + // "I_S" + hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); + // "K_S" + const serverPublicHostKey = (isServer + ? this._hostKey.getPublicSSH() + : this._hostKey); + hashString(hash, serverPublicHostKey); -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; + if (this.type === 'groupex') { + // Group exchange-specific + const params = this.getDHParams(); + const num = Buffer.allocUnsafe(4); + // min (uint32) + writeUInt32BE(num, this._minBits, 0); + hash.update(num); + // preferred (uint32) + writeUInt32BE(num, this._prefBits, 0); + hash.update(num); + // max (uint32) + writeUInt32BE(num, this._maxBits, 0); + hash.update(num); + // prime + hashString(hash, params.prime); + // generator + hashString(hash, params.generator); + } - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} + // method-specific data sent by client + hashString(hash, (isServer ? pubKey : this.getPublicKey())); + // method-specific data sent by server + const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); + hashString(hash, serverPublicKey); + // shared secret ("K") + hashString(hash, secret); -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + // "H" + const exchangeHash = hash.digest(); - if (state.pipesCount === 0) return this; // just one destination. most common case. + if (!isServer) { + bufferParser.init(this._sig, 0); + const sigType = bufferParser.readString(true); - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + if (!sigType) { + return doFatalError( + this._protocol, + 'Malformed packet while reading signature', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + if (sigType !== negotiated.serverHostKey) { + return doFatalError( + this._protocol, + `Wrong signature type: ${sigType}, ` + + `expected: ${negotiated.serverHostKey}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + // "s" + let sigValue = bufferParser.readString(); - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + bufferParser.clear(); - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } + if (sigValue === undefined) { + return doFatalError( + this._protocol, + 'Malformed packet while reading signature', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } - return this; - } // try to find the right one. + if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { + return doFatalError( + this._protocol, + 'Malformed signature', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + let parsedHostKey; + { + bufferParser.init(this._hostKey, 0); + const name = bufferParser.readString(true); + const hostKey = this._hostKey.slice(bufferParser.pos()); + bufferParser.clear(); + parsedHostKey = parseDERKey(hostKey, name); + if (parsedHostKey instanceof Error) { + parsedHostKey.level = 'handshake'; + return doFatalError( + this._protocol, + parsedHostKey, + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something + let hashAlgo; + // Check if we need to override the default hash algorithm + switch (this.negotiated.serverHostKey) { + case 'rsa-sha2-256': hashAlgo = 'sha256'; break; + case 'rsa-sha2-512': hashAlgo = 'sha512'; break; + } + this._protocol._debug + && this._protocol._debug('Verifying signature ...'); -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; + const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); + if (verified !== true) { + if (verified instanceof Error) { + this._protocol._debug && this._protocol._debug( + `Signature verification failed: ${verified.stack}` + ); + } else { + this._protocol._debug && this._protocol._debug( + 'Signature verification failed' + ); + } + return doFatalError( + this._protocol, + 'Handshake failed: signature verification failed', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug('Verified signature'); + } else { + // Server - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + let hashAlgo; + // Check if we need to override the default hash algorithm + switch (this.negotiated.serverHostKey) { + case 'rsa-sha2-256': hashAlgo = 'sha256'; break; + case 'rsa-sha2-512': hashAlgo = 'sha512'; break; + } - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); + this._protocol._debug && this._protocol._debug( + 'Generating signature ...' + ); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } + let signature = this._hostKey.sign(exchangeHash, hashAlgo); + if (signature instanceof Error) { + return doFatalError( + this._protocol, + 'Handshake failed: signature generation failed for ' + + `${this._hostKey.type} host key: ${signature.message}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } - return res; -}; + signature = convertSignature(signature, this._hostKey.type); + if (signature === false) { + return doFatalError( + this._protocol, + 'Handshake failed: signature conversion failed for ' + + `${this._hostKey.type} host key`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -Readable.prototype.addListener = Readable.prototype.on; + // Send KEX reply + /* + byte SSH_MSG_KEXDH_REPLY + / SSH_MSG_KEX_DH_GEX_REPLY + / SSH_MSG_KEX_ECDH_REPLY + string server public host key and certificates (K_S) + string + string signature of H + */ + const sigType = this.negotiated.serverHostKey; + const sigTypeLen = Buffer.byteLength(sigType); + const sigLen = 4 + sigTypeLen + 4 + signature.length; + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + + 4 + serverPublicHostKey.length + + 4 + serverPublicKey.length + + 4 + sigLen, + true + ); -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); + packet[p] = MESSAGE.KEXDH_REPLY; - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } + writeUInt32BE(packet, serverPublicHostKey.length, ++p); + packet.set(serverPublicHostKey, p += 4); - return res; -}; + writeUInt32BE(packet, + serverPublicKey.length, + p += serverPublicHostKey.length); + packet.set(serverPublicKey, p += 4); -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); + writeUInt32BE(packet, sigLen, p += serverPublicKey.length); - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } + writeUInt32BE(packet, sigTypeLen, p += 4); + packet.utf8Write(sigType, p += 4, sigTypeLen); - return res; -}; + writeUInt32BE(packet, signature.length, p += sigTypeLen); + packet.set(signature, p += 4); -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; + if (this._protocol._debug) { + let type; + switch (this.type) { + case 'group': + type = 'KEXDH_REPLY'; + break; + case 'groupex': + type = 'KEXDH_GEX_REPLY'; + break; + default: + type = 'KEXECDH_REPLY'; + } + this._protocol._debug(`Outbound: Sending ${type}`); + } + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} + if (isServer || !scOnly) + trySendNEWKEYS(this); + + let hsCipherConfig; + let hsWrite; + const completeHandshake = (partial) => { + if (hsCipherConfig) { + trySendNEWKEYS(this); + hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno; + this._protocol._cipher.free(); + this._protocol._cipher = createCipher(hsCipherConfig); + this._protocol._packetRW.write = hsWrite; + hsCipherConfig = undefined; + hsWrite = undefined; + this._protocol._onHandshakeComplete(negotiated); -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. + return false; + } + if (!this.sessionID) + this.sessionID = exchangeHash; -Readable.prototype.resume = function () { - var state = this._readableState; + { + const newSecret = Buffer.allocUnsafe(4 + secret.length); + writeUInt32BE(newSecret, secret.length, 0); + newSecret.set(secret, 4); + secret = newSecret; + } - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + // Initialize new ciphers, deciphers, etc. - state.flowing = !state.readableListening; - resume(this, state); - } + const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; + const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; - state.paused = false; - return this; -}; + const csIV = generateKEXVal(csCipherInfo.ivLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'A'); + const scIV = generateKEXVal(scCipherInfo.ivLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'B'); + const csKey = generateKEXVal(csCipherInfo.keyLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'C'); + const scKey = generateKEXVal(scCipherInfo.keyLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'D'); + let csMacInfo; + let csMacKey; + if (!csCipherInfo.authLen) { + csMacInfo = MAC_INFO[negotiated.cs.mac]; + csMacKey = generateKEXVal(csMacInfo.len, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'E'); + } + let scMacInfo; + let scMacKey; + if (!scCipherInfo.authLen) { + scMacInfo = MAC_INFO[negotiated.sc.mac]; + scMacKey = generateKEXVal(scMacInfo.len, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'F'); + } -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} + const config = { + inbound: { + onPayload: this._protocol._onPayload, + seqno: this._protocol._decipher.inSeqno, + decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), + decipherIV: (!isServer ? scIV : csIV), + decipherKey: (!isServer ? scKey : csKey), + macInfo: (!isServer ? scMacInfo : csMacInfo), + macKey: (!isServer ? scMacKey : csMacKey), + }, + outbound: { + onWrite: this._protocol._onWrite, + seqno: this._protocol._cipher.outSeqno, + cipherInfo: (isServer ? scCipherInfo : csCipherInfo), + cipherIV: (isServer ? scIV : csIV), + cipherKey: (isServer ? scKey : csKey), + macInfo: (isServer ? scMacInfo : csMacInfo), + macKey: (isServer ? scMacKey : csMacKey), + }, + }; + this._protocol._decipher.free(); + hsCipherConfig = config; + this._protocol._decipher = createDecipher(config); -function resume_(stream, state) { - debug('resume', state.reading); + const rw = { + read: undefined, + write: undefined, + }; + switch (negotiated.cs.compress) { + case 'zlib': // starts immediately + if (isServer) + rw.read = new ZlibPacketReader(); + else + rw.write = new ZlibPacketWriter(this._protocol); + break; + case 'zlib@openssh.com': + // Starts after successful user authentication - if (!state.reading) { - stream.read(0); - } + if (this._protocol._authenticated) { + // If a rekey happens and this compression method is selected and + // we already authenticated successfully, we need to start + // immediately instead + if (isServer) + rw.read = new ZlibPacketReader(); + else + rw.write = new ZlibPacketWriter(this._protocol); + break; + } + // FALLTHROUGH + default: + // none -- never any compression/decompression - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} + if (isServer) + rw.read = new PacketReader(); + else + rw.write = new PacketWriter(this._protocol); + } + switch (negotiated.sc.compress) { + case 'zlib': // starts immediately + if (isServer) + rw.write = new ZlibPacketWriter(this._protocol); + else + rw.read = new ZlibPacketReader(); + break; + case 'zlib@openssh.com': + // Starts after successful user authentication -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); + if (this._protocol._authenticated) { + // If a rekey happens and this compression method is selected and + // we already authenticated successfully, we need to start + // immediately instead + if (isServer) + rw.write = new ZlibPacketWriter(this._protocol); + else + rw.read = new ZlibPacketReader(); + break; + } + // FALLTHROUGH + default: + // none -- never any compression/decompression - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } + if (isServer) + rw.write = new PacketWriter(this._protocol); + else + rw.read = new PacketReader(); + } + this._protocol._packetRW.read.cleanup(); + this._protocol._packetRW.write.cleanup(); + this._protocol._packetRW.read = rw.read; + hsWrite = rw.write; - this._readableState.paused = true; - return this; -}; + // Cleanup/reset various state + this._public = null; + this._dh = null; + this._kexinit = this._protocol._kexinit = undefined; + this._remoteKexinit = undefined; + this._identRaw = undefined; + this._remoteIdentRaw = undefined; + this._hostKey = undefined; + this._dhData = undefined; + this._sig = undefined; -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); + if (!partial) + return completeHandshake(); + return false; + }; - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. + if (isServer || scOnly) + this.finish = completeHandshake; + if (!isServer) + return completeHandshake(scOnly); + } -Readable.prototype.wrap = function (stream) { - var _this = this; + start() { + if (!this._protocol._server) { + if (this._protocol._debug) { + let type; + switch (this.type) { + case 'group': + type = 'KEXDH_INIT'; + break; + default: + type = 'KEXECDH_INIT'; + } + this._protocol._debug(`Outbound: Sending ${type}`); + } - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); + const pubKey = this.getPublicKey(); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + 4 + pubKey.length, + true + ); + packet[p] = MESSAGE.KEXDH_INIT; + writeUInt32BE(packet, pubKey.length, ++p); + packet.set(pubKey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } } + getPublicKey() { + this.generateKeys(); - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + const key = this._public; - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + if (key) + return this.convertPublicKey(key); + } + convertPublicKey(key) { + let newKey; + let idx = 0; + let len = key.length; + while (key[idx] === 0x00) { + ++idx; + --len; + } - var ret = _this.push(chunk); + if (key[idx] & 0x80) { + newKey = Buffer.allocUnsafe(1 + len); + newKey[0] = 0; + key.copy(newKey, 1, idx); + return newKey; + } - if (!ret) { - paused = true; - stream.pause(); + if (len !== key.length) { + newKey = Buffer.allocUnsafe(len); + key.copy(newKey, 0, idx); + key = newKey; + } + return key; } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. + computeSecret(otherPublicKey) { + this.generateKeys(); - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); + try { + return convertToMpint(this._dh.computeSecret(otherPublicKey)); + } catch (ex) { + return ex; + } } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. + parse(payload) { + const type = payload[0]; + switch (this._step) { + case 1: + if (this._protocol._server) { + // Server + if (type !== MESSAGE.KEXDH_INIT) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Received DH Init' + ); + /* + byte SSH_MSG_KEXDH_INIT + / SSH_MSG_KEX_ECDH_INIT + string + */ + bufferParser.init(payload, 1); + const dhData = bufferParser.readString(); + bufferParser.clear(); + if (dhData === undefined) { + return doFatalError( + this._protocol, + 'Received malformed KEX*_INIT', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + // Client public key + this._dhData = dhData; - this._read = function (n) { - debug('wrapped _read', n); + let hostKey = + this._protocol._hostKeys[this.negotiated.serverHostKey]; + if (Array.isArray(hostKey)) + hostKey = hostKey[0]; + this._hostKey = hostKey; - if (paused) { - paused = false; - stream.resume(); - } - }; + this.finish(); + } else { + // Client + if (type !== MESSAGE.KEXDH_REPLY) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Received DH Reply' + ); + /* + byte SSH_MSG_KEXDH_REPLY + / SSH_MSG_KEX_DH_GEX_REPLY + / SSH_MSG_KEX_ECDH_REPLY + string server public host key and certificates (K_S) + string + string signature of H + */ + bufferParser.init(payload, 1); + let hostPubKey; + let dhData; + let sig; + if ((hostPubKey = bufferParser.readString()) === undefined + || (dhData = bufferParser.readString()) === undefined + || (sig = bufferParser.readString()) === undefined) { + bufferParser.clear(); + return doFatalError( + this._protocol, + 'Received malformed KEX*_REPLY', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + bufferParser.clear(); - return this; -}; + // Check that the host public key type matches what was negotiated + // during KEXINIT swap + bufferParser.init(hostPubKey, 0); + const hostPubKeyType = bufferParser.readString(true); + bufferParser.clear(); + if (hostPubKeyType === undefined) { + return doFatalError( + this._protocol, + 'Received malformed host public key', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + if (hostPubKeyType !== this.negotiated.serverHostKey) { + // Check if we need to make an exception + switch (this.negotiated.serverHostKey) { + case 'rsa-sha2-256': + case 'rsa-sha2-512': + if (hostPubKeyType === 'ssh-rsa') + break; + // FALLTHROUGH + default: + return doFatalError( + this._protocol, + 'Host key does not match negotiated type', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = __nccwpck_require__(3306); - } + this._hostKey = hostPubKey; + this._dhData = dhData; + this._sig = sig; - return createReadableStreamAsyncIterator(this); - }; -} + let checked = false; + let ret; + if (this._protocol._hostVerifier === undefined) { + ret = true; + this._protocol._debug && this._protocol._debug( + 'Host accepted by default (no verification)' + ); + } else { + ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { + if (checked) + return; + checked = true; + if (permitted === false) { + this._protocol._debug && this._protocol._debug( + 'Host denied (verification failed)' + ); + return doFatalError( + this._protocol, + 'Host denied (verification failed)', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Host accepted (verified)' + ); + this._hostVerified = true; + if (this._receivedNEWKEYS) + this.finish(); + else + trySendNEWKEYS(this); + }); + } + if (ret === undefined) { + // Async host verification + ++this._step; + return; + } + checked = true; + if (ret === false) { + this._protocol._debug && this._protocol._debug( + 'Host denied (verification failed)' + ); + return doFatalError( + this._protocol, + 'Host denied (verification failed)', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Host accepted (verified)' + ); + this._hostVerified = true; + trySendNEWKEYS(this); + } + ++this._step; + break; + case 2: + if (type !== MESSAGE.NEWKEYS) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Inbound: NEWKEYS' + ); + this._receivedNEWKEYS = true; + if (this._protocol._strictMode) + this._protocol._decipher.inSeqno = 0; + ++this._step; -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; + return this.finish(!this._protocol._server && !this._hostVerified); + default: + return doFatalError( + this._protocol, + `Received unexpected packet ${type} after NEWKEYS`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } } } -}); // exposed for testing purposes only. -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. + class Curve25519Exchange extends KeyExchange { + constructor(hashName, ...args) { + super(...args); -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} + this.type = '25519'; + this.hashName = hashName; + this._keys = null; + } + generateKeys() { + if (!this._keys) + this._keys = generateKeyPairSync('x25519'); + } + getPublicKey() { + this.generateKeys(); -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); + const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); + return key.slice(-32); // HACK: avoids parsing DER/BER header + } + convertPublicKey(key) { + let newKey; + let idx = 0; + let len = key.length; + while (key[idx] === 0x00) { + ++idx; + --len; + } - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} + if (key.length === 32) + return key; -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + if (len !== key.length) { + newKey = Buffer.allocUnsafe(len); + key.copy(newKey, 0, idx); + key = newKey; + } + return key; + } + computeSecret(otherPublicKey) { + this.generateKeys(); - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + try { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.3.101.110'); // id-X25519 + asnWriter.endSequence(); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; + // PublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + // XXX: hack to write a raw buffer without a tag -- yuck + asnWriter._ensure(otherPublicKey.length); + otherPublicKey.copy(asnWriter._buf, + asnWriter._offset, + 0, + otherPublicKey.length); + asnWriter._offset += otherPublicKey.length; + asnWriter.endSequence(); + asnWriter.endSequence(); - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); + return convertToMpint(diffieHellman({ + privateKey: this._keys.privateKey, + publicKey: createPublicKey({ + key: asnWriter.buffer, + type: 'spki', + format: 'der', + }), + })); + } catch (ex) { + return ex; } } } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = __nccwpck_require__(9082); - } - return from(Readable, iterable, opts); - }; -} + class ECDHExchange extends KeyExchange { + constructor(curveName, hashName, ...args) { + super(...args); -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + this.type = 'ecdh'; + this.curveName = curveName; + this.hashName = hashName; + } + generateKeys() { + if (!this._dh) { + this._dh = createECDH(this.curveName); + this._public = this._dh.generateKeys(); + } + } } - return -1; -} + class DHGroupExchange extends KeyExchange { + constructor(hashName, ...args) { + super(...args); -/***/ }), + this.type = 'groupex'; + this.hashName = hashName; + this._prime = null; + this._generator = null; + this._minBits = GEX_MIN_BITS; + this._prefBits = dhEstimate(this.negotiated); + if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) + this._prefBits = Math.min(this._prefBits, 4096); + this._maxBits = GEX_MAX_BITS; + } + start() { + if (this._protocol._server) + return; + this._protocol._debug && this._protocol._debug( + 'Outbound: Sending KEXDH_GEX_REQUEST' + ); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + 4 + 4 + 4, + true + ); + packet[p] = MESSAGE.KEXDH_GEX_REQUEST; + writeUInt32BE(packet, this._minBits, ++p); + writeUInt32BE(packet, this._prefBits, p += 4); + writeUInt32BE(packet, this._maxBits, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + generateKeys() { + if (!this._dh && this._prime && this._generator) { + this._dh = createDiffieHellman(this._prime, this._generator); + this._public = this._dh.generateKeys(); + } + } + setDHParams(prime, generator) { + if (!Buffer.isBuffer(prime)) + throw new Error('Invalid prime value'); + if (!Buffer.isBuffer(generator)) + throw new Error('Invalid generator value'); + this._prime = prime; + this._generator = generator; + } + getDHParams() { + if (this._dh) { + return { + prime: convertToMpint(this._dh.getPrime()), + generator: convertToMpint(this._dh.getGenerator()), + }; + } + } + parse(payload) { + const type = payload[0]; + switch (this._step) { + case 1: { + if (this._protocol._server) { + if (type !== MESSAGE.KEXDH_GEX_REQUEST) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ` + + MESSAGE.KEXDH_GEX_REQUEST, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + // TODO: allow user implementation to provide safe prime and + // generator on demand to support group exchange on server side + return doFatalError( + this._protocol, + 'Group exchange not implemented for server', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -/***/ 4415: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (type !== MESSAGE.KEXDH_GEX_GROUP) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. + this._protocol._debug && this._protocol._debug( + 'Received DH GEX Group' + ); + /* + byte SSH_MSG_KEX_DH_GEX_GROUP + mpint p, safe prime + mpint g, generator for subgroup in GF(p) + */ + bufferParser.init(payload, 1); + let prime; + let gen; + if ((prime = bufferParser.readString()) === undefined + || (gen = bufferParser.readString()) === undefined) { + bufferParser.clear(); + return doFatalError( + this._protocol, + 'Received malformed KEXDH_GEX_GROUP', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + bufferParser.clear(); -module.exports = Transform; + // TODO: validate prime + this.setDHParams(prime, gen); + this.generateKeys(); + const pubkey = this.getPublicKey(); -var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + this._protocol._debug && this._protocol._debug( + 'Outbound: Sending KEXDH_GEX_INIT' + ); -var Duplex = __nccwpck_require__(1359); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = + this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); + packet[p] = MESSAGE.KEXDH_GEX_INIT; + writeUInt32BE(packet, pubkey.length, ++p); + packet.set(pubkey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); -__nccwpck_require__(4124)(Transform, Duplex); + ++this._step; + break; + } + case 2: + if (this._protocol._server) { + if (type !== MESSAGE.KEXDH_GEX_INIT) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Received DH GEX Init' + ); + return doFatalError( + this._protocol, + 'Group exchange not implemented for server', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Received DH GEX Reply' + ); + this._step = 1; + payload[0] = MESSAGE.KEXDH_REPLY; + this.parse = KeyExchange.prototype.parse; + this.parse(payload); + } + } + } -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; + class DHExchange extends KeyExchange { + constructor(groupName, hashName, ...args) { + super(...args); - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + this.type = 'group'; + this.groupName = groupName; + this.hashName = hashName; + } + start() { + if (!this._protocol._server) { + this._protocol._debug && this._protocol._debug( + 'Outbound: Sending KEXDH_INIT' + ); + const pubKey = this.getPublicKey(); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = + this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); + packet[p] = MESSAGE.KEXDH_INIT; + writeUInt32BE(packet, pubKey.length, ++p); + packet.set(pubKey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + } + generateKeys() { + if (!this._dh) { + this._dh = createDiffieHellmanGroup(this.groupName); + this._public = this._dh.generateKeys(); + } + } + getDHParams() { + if (this._dh) { + return { + prime: convertToMpint(this._dh.getPrime()), + generator: convertToMpint(this._dh.getGenerator()), + }; + } + } } - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; + return (negotiated, ...args) => { + if (typeof negotiated !== 'object' || negotiated === null) + throw new Error('Invalid negotiated argument'); + const kexType = negotiated.kex; + if (typeof kexType === 'string') { + args = [negotiated, ...args]; + switch (kexType) { + case 'curve25519-sha256': + case 'curve25519-sha256@libssh.org': + if (!curve25519Supported) + break; + return new Curve25519Exchange('sha256', ...args); - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} + case 'ecdh-sha2-nistp256': + return new ECDHExchange('prime256v1', 'sha256', ...args); + case 'ecdh-sha2-nistp384': + return new ECDHExchange('secp384r1', 'sha384', ...args); + case 'ecdh-sha2-nistp521': + return new ECDHExchange('secp521r1', 'sha512', ...args); + + case 'diffie-hellman-group1-sha1': + return new DHExchange('modp2', 'sha1', ...args); + case 'diffie-hellman-group14-sha1': + return new DHExchange('modp14', 'sha1', ...args); + case 'diffie-hellman-group14-sha256': + return new DHExchange('modp14', 'sha256', ...args); + case 'diffie-hellman-group15-sha512': + return new DHExchange('modp15', 'sha512', ...args); + case 'diffie-hellman-group16-sha512': + return new DHExchange('modp16', 'sha512', ...args); + case 'diffie-hellman-group17-sha512': + return new DHExchange('modp17', 'sha512', ...args); + case 'diffie-hellman-group18-sha512': + return new DHExchange('modp18', 'sha512', ...args); + + case 'diffie-hellman-group-exchange-sha1': + return new DHGroupExchange('sha1', ...args); + case 'diffie-hellman-group-exchange-sha256': + return new DHGroupExchange('sha256', ...args); + } + throw new Error(`Unsupported key exchange algorithm: ${kexType}`); + } + throw new Error(`Invalid key exchange type: ${kexType}`); + }; +})(); -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. +const KexInit = (() => { + const KEX_PROPERTY_NAMES = [ + 'kex', + 'serverHostKey', + ['cs', 'cipher' ], + ['sc', 'cipher' ], + ['cs', 'mac' ], + ['sc', 'mac' ], + ['cs', 'compress' ], + ['sc', 'compress' ], + ['cs', 'lang' ], + ['sc', 'lang' ], + ]; + return class KexInit { + constructor(obj) { + if (typeof obj !== 'object' || obj === null) + throw new TypeError('Argument must be an object'); - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. + const lists = { + kex: undefined, + serverHostKey: undefined, + cs: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: undefined, + }, + sc: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: undefined, + }, - this._readableState.sync = false; + all: undefined, + }; + let totalSize = 0; + for (const prop of KEX_PROPERTY_NAMES) { + let base; + let val; + let desc; + let key; + if (typeof prop === 'string') { + base = lists; + val = obj[prop]; + desc = key = prop; + } else { + const parent = prop[0]; + base = lists[parent]; + key = prop[1]; + val = obj[parent][key]; + desc = `${parent}.${key}`; + } + const entry = { array: undefined, buffer: undefined }; + if (Buffer.isBuffer(val)) { + entry.array = ('' + val).split(','); + entry.buffer = val; + totalSize += 4 + val.length; + } else { + if (typeof val === 'string') + val = val.split(','); + if (Array.isArray(val)) { + entry.array = val; + entry.buffer = Buffer.from(val.join(',')); + } else { + throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); + } + totalSize += 4 + entry.buffer.length; + } + base[key] = entry; + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. + const all = Buffer.allocUnsafe(totalSize); + lists.all = all; + let allPos = 0; + for (const prop of KEX_PROPERTY_NAMES) { + let data; + if (typeof prop === 'string') + data = lists[prop].buffer; + else + data = lists[prop[0]][prop[1]].buffer; + allPos = writeUInt32BE(all, data.length, allPos); + all.set(data, allPos); + allPos += data.length; + } - this.on('prefinish', prefinish); -} + this.totalSize = totalSize; + this.lists = lists; + } + copyAllTo(buf, offset) { + const src = this.lists.all; + if (typeof offset !== 'number') + throw new TypeError(`Invalid offset value: ${typeof offset}`); + if (buf.length - offset < src.length) + throw new Error('Insufficient space to copy list'); + buf.set(src, offset); + return src.length; + } + }; +})(); -function prefinish() { - var _this = this; +const hashString = (() => { + const LEN = Buffer.allocUnsafe(4); + return (hash, buf) => { + writeUInt32BE(LEN, buf.length, 0); + hash.update(LEN); + hash.update(buf); + }; +})(); - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); +function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { + let ret; + if (len) { + let digest = createHash(hashName) + .update(secret) + .update(exchangeHash) + .update(char) + .update(sessionID) + .digest(); + while (digest.length < len) { + const chunk = createHash(hashName) + .update(secret) + .update(exchangeHash) + .update(digest) + .digest(); + const extended = Buffer.allocUnsafe(digest.length + chunk.length); + extended.set(digest, 0); + extended.set(chunk, digest.length); + digest = extended; + } + if (digest.length === len) + ret = digest; + else + ret = new FastBuffer(digest.buffer, digest.byteOffset, len); } else { - done(this, null, null); + ret = EMPTY_BUFFER; } + return ret; } -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. +function onKEXPayload(state, payload) { + // XXX: move this to the Decipher implementations? + if (payload.length === 0) { + this._debug && this._debug('Inbound: Skipping empty packet payload'); + return; + } + if (this._skipNextInboundPacket) { + this._skipNextInboundPacket = false; + return; + } -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; + payload = this._packetRW.read.read(payload); -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; + const type = payload[0]; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + if (!this._strictMode) { + switch (type) { + case MESSAGE.IGNORE: + case MESSAGE.UNIMPLEMENTED: + case MESSAGE.DEBUG: + if (!MESSAGE_HANDLERS) + MESSAGE_HANDLERS = __nccwpck_require__(172); + return MESSAGE_HANDLERS[type](this, payload); + } } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. + switch (type) { + case MESSAGE.DISCONNECT: + if (!MESSAGE_HANDLERS) + MESSAGE_HANDLERS = __nccwpck_require__(172); + return MESSAGE_HANDLERS[type](this, payload); + case MESSAGE.KEXINIT: + if (!state.firstPacket) { + return doFatalError( + this, + 'Received extra KEXINIT during handshake', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + state.firstPacket = false; + return handleKexInit(this, payload); + default: + // Ensure packet is either an algorithm negotiation or KEX + // algorithm-specific packet + if (type < 20 || type > 49) { + return doFatalError( + this, + `Received unexpected packet type ${type}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } -Transform.prototype._read = function (n) { - var ts = this._transformState; + return this._kex.parse(payload); +} - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; +function dhEstimate(neg) { + const csCipher = CIPHER_INFO[neg.cs.cipher]; + const scCipher = CIPHER_INFO[neg.sc.cipher]; + // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will + // also need to be considered when calculating `bits` + const bits = Math.max( + 0, + (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), + csCipher.blockLen, + csCipher.ivLen, + (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), + scCipher.blockLen, + scCipher.ivLen + ) * 8; + if (bits <= 112) + return 2048; + if (bits <= 128) + return 3072; + if (bits <= 192) + return 7680; + return 8192; +} - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; +function trySendNEWKEYS(kex) { + if (!kex._sentNEWKEYS) { + kex._protocol._debug && kex._protocol._debug( + 'Outbound: Sending NEWKEYS' + ); + const p = kex._protocol._packetRW.write.allocStartKEX; + const packet = kex._protocol._packetRW.write.alloc(1, true); + packet[p] = MESSAGE.NEWKEYS; + kex._protocol._cipher.encrypt( + kex._protocol._packetRW.write.finalize(packet, true) + ); + kex._sentNEWKEYS = true; + if (kex._protocol._strictMode) + kex._protocol._cipher.outSeqno = 0; } -}; +} -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); +module.exports = { + KexInit, + kexinit, + onKEXPayload, + DEFAULT_KEXINIT_CLIENT: new KexInit({ + kex: DEFAULT_KEX.concat(['ext-info-c', 'kex-strict-c-v00@openssh.com']), + serverHostKey: DEFAULT_SERVER_HOST_KEY, + cs: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [], + }, + sc: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [], + }, + }), + DEFAULT_KEXINIT_SERVER: new KexInit({ + kex: DEFAULT_KEX.concat(['kex-strict-s-v00@openssh.com']), + serverHostKey: DEFAULT_SERVER_HOST_KEY, + cs: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [], + }, + sc: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [], + }, + }), + HANDLERS: { + [MESSAGE.KEXINIT]: handleKexInit, + }, }; -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} /***/ }), -/***/ 6993: +/***/ 2218: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +// TODO: +// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` +// * handle multi-line header values (OpenSSH)? +// * more thorough validation? -module.exports = Writable; -/* */ +const { + createDecipheriv, + createECDH, + createHash, + createHmac, + createSign, + createVerify, + getCiphers, + sign: sign_, + verify: verify_, +} = __nccwpck_require__(6113); +const supportedOpenSSLCiphers = getCiphers(); -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream +const { Ber } = __nccwpck_require__(970); +const bcrypt_pbkdf = (__nccwpck_require__(5447).pbkdf); + +const { CIPHER_INFO } = __nccwpck_require__(5708); +const { eddsaSupported, SUPPORTED_CIPHER } = __nccwpck_require__(6832); +const { + bufferSlice, + makeBufferParser, + readString, + readUInt32BE, + writeUInt32BE, +} = __nccwpck_require__(9475); +const SYM_HASH_ALGO = Symbol('Hash Algorithm'); +const SYM_PRIV_PEM = Symbol('Private key PEM'); +const SYM_PUB_PEM = Symbol('Public key PEM'); +const SYM_PUB_SSH = Symbol('Public key SSH'); +const SYM_DECRYPTED = Symbol('Decrypted Key'); -function CorkedRequest(state) { - var _this = this; +// Create OpenSSL cipher name -> SSH cipher name conversion table +const CIPHER_INFO_OPENSSL = Object.create(null); +{ + const keys = Object.keys(CIPHER_INFO); + for (let i = 0; i < keys.length; ++i) { + const cipherName = CIPHER_INFO[keys[i]].sslName; + if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) + continue; + CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; + } +} - this.next = null; - this.entry = null; +const binaryKeyParser = makeBufferParser(); - this.finish = function () { - onCorkedFinish(_this, state); - }; +function makePEM(type, data) { + data = data.base64Slice(0, data.length); + let formatted = data.replace(/.{64}/g, '$&\n'); + if (data.length & 63) + formatted += '\n'; + return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; } -/* */ -/**/ +function combineBuffers(buf1, buf2) { + const result = Buffer.allocUnsafe(buf1.length + buf2.length); + result.set(buf1, 0); + result.set(buf2, buf1.length); + return result; +} +function skipFields(buf, nfields) { + const bufLen = buf.length; + let pos = (buf._pos || 0); + for (let i = 0; i < nfields; ++i) { + const left = (bufLen - pos); + if (pos >= bufLen || left < 4) + return false; + const len = readUInt32BE(buf, pos); + if (left < 4 + len) + return false; + pos += 4 + len; + } + buf._pos = pos; + return true; +} -var Duplex; -/**/ +function genOpenSSLRSAPub(n, e) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption + // algorithm parameters (RSA has none) + asnWriter.writeNull(); + asnWriter.endSequence(); -Writable.WritableState = WritableState; -/**/ + // subjectPublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + asnWriter.startSequence(); + asnWriter.writeBuffer(n, Ber.Integer); + asnWriter.writeBuffer(e, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PUBLIC', asnWriter.buffer); +} -var internalUtil = { - deprecate: __nccwpck_require__(7127) -}; -/**/ +function genOpenSSHRSAPub(n, e) { + const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); -/**/ + writeUInt32BE(publicKey, 7, 0); + publicKey.utf8Write('ssh-rsa', 4, 7); -var Stream = __nccwpck_require__(2387); -/**/ + let i = 4 + 7; + writeUInt32BE(publicKey, e.length, i); + publicKey.set(e, i += 4); + + writeUInt32BE(publicKey, n.length, i += e.length); + publicKey.set(n, i + 4); + return publicKey; +} -var Buffer = (__nccwpck_require__(4300).Buffer); +const genOpenSSLRSAPriv = (() => { + function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeInt(0x00, Ber.Integer); + asnWriter.writeBuffer(n, Ber.Integer); + asnWriter.writeBuffer(e, Ber.Integer); + asnWriter.writeBuffer(d, Ber.Integer); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(dmp1, Ber.Integer); + asnWriter.writeBuffer(dmq1, Ber.Integer); + asnWriter.writeBuffer(iqmp, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; + } + + function bigIntFromBuffer(buf) { + return BigInt(`0x${buf.hexSlice(0, buf.length)}`); + } + + function bigIntToBuffer(bn) { + let hex = bn.toString(16); + if ((hex.length & 1) !== 0) { + hex = `0${hex}`; + } else { + const sigbit = hex.charCodeAt(0); + // BER/DER integers require leading zero byte to denote a positive value + // when first byte >= 0x80 + if (sigbit === 56/* '8' */ + || sigbit === 57/* '9' */ + || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { + hex = `00${hex}`; + } + } + return Buffer.from(hex, 'hex'); + } -var OurUint8Array = global.Uint8Array || function () {}; + return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { + const bn_d = bigIntFromBuffer(d); + const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); + const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); + return makePEM('RSA PRIVATE', + genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); + }; +})(); -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} +function genOpenSSLDSAPub(p, q, g, y) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa + // algorithm parameters + asnWriter.startSequence(); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(g, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + // subjectPublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + asnWriter.writeBuffer(y, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PUBLIC', asnWriter.buffer); } -var destroyImpl = __nccwpck_require__(7049); - -var _require = __nccwpck_require__(9948), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +function genOpenSSHDSAPub(p, q, g, y) { + const publicKey = Buffer.allocUnsafe( + 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length + ); -var errorOrDestroy = destroyImpl.errorOrDestroy; + writeUInt32BE(publicKey, 7, 0); + publicKey.utf8Write('ssh-dss', 4, 7); -__nccwpck_require__(4124)(Writable, Stream); + let i = 4 + 7; + writeUInt32BE(publicKey, p.length, i); + publicKey.set(p, i += 4); -function nop() {} + writeUInt32BE(publicKey, q.length, i += p.length); + publicKey.set(q, i += 4); -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(1359); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + writeUInt32BE(publicKey, g.length, i += q.length); + publicKey.set(g, i += 4); - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. + writeUInt32BE(publicKey, y.length, i += g.length); + publicKey.set(y, i + 4); - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() + return publicKey; +} - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called +function genOpenSSLDSAPriv(p, q, g, y, x) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeInt(0x00, Ber.Integer); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(g, Ber.Integer); + asnWriter.writeBuffer(y, Ber.Integer); + asnWriter.writeBuffer(x, Ber.Integer); + asnWriter.endSequence(); + return makePEM('DSA PRIVATE', asnWriter.buffer); +} - this.finalCalled = false; // drain event flag. +function genOpenSSLEdPub(pub) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.3.101.112'); // id-Ed25519 + asnWriter.endSequence(); - this.needDrain = false; // at the start of calling end() + // PublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + // XXX: hack to write a raw buffer without a tag -- yuck + asnWriter._ensure(pub.length); + asnWriter._buf.set(pub, asnWriter._offset); + asnWriter._offset += pub.length; + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PUBLIC', asnWriter.buffer); +} - this.ending = false; // when end() has been called, and returned +function genOpenSSHEdPub(pub) { + const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); - this.ended = false; // when 'finish' is emitted + writeUInt32BE(publicKey, 11, 0); + publicKey.utf8Write('ssh-ed25519', 4, 11); - this.finished = false; // has it been destroyed + writeUInt32BE(publicKey, pub.length, 15); + publicKey.set(pub, 19); - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. + return publicKey; +} - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. +function genOpenSSLEdPriv(priv) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // version + asnWriter.writeInt(0x00, Ber.Integer); - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.3.101.112'); // id-Ed25519 + asnWriter.endSequence(); - this.length = 0; // a flag to see when we're in the middle of a write. + // PrivateKey + asnWriter.startSequence(Ber.OctetString); + asnWriter.writeBuffer(priv, Ber.OctetString); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PRIVATE', asnWriter.buffer); +} - this.writing = false; // when true all writes will be buffered until .uncork() call +function genOpenSSLECDSAPub(oid, Q) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey + // algorithm parameters (namedCurve) + asnWriter.writeOID(oid); + asnWriter.endSequence(); - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. + // subjectPublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + // XXX: hack to write a raw buffer without a tag -- yuck + asnWriter._ensure(Q.length); + asnWriter._buf.set(Q, asnWriter._offset); + asnWriter._offset += Q.length; + // end hack + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PUBLIC', asnWriter.buffer); +} - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. +function genOpenSSHECDSAPub(oid, Q) { + let curveName; + switch (oid) { + case '1.2.840.10045.3.1.7': + // prime256v1/secp256r1 + curveName = 'nistp256'; + break; + case '1.3.132.0.34': + // secp384r1 + curveName = 'nistp384'; + break; + case '1.3.132.0.35': + // secp521r1 + curveName = 'nistp521'; + break; + default: + return; + } - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) + writeUInt32BE(publicKey, 19, 0); + publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); + writeUInt32BE(publicKey, 8, 23); + publicKey.utf8Write(curveName, 27, 8); - this.writecb = null; // the amount that is being written when _write is called. + writeUInt32BE(publicKey, Q.length, 35); + publicKey.set(Q, 39); - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted + return publicKey; +} - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams +function genOpenSSLECDSAPriv(oid, pub, priv) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // version + asnWriter.writeInt(0x01, Ber.Integer); + // privateKey + asnWriter.writeBuffer(priv, Ber.OctetString); + // parameters (optional) + asnWriter.startSequence(0xA0); + asnWriter.writeOID(oid); + asnWriter.endSequence(); + // publicKey (optional) + asnWriter.startSequence(0xA1); + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + // XXX: hack to write a raw buffer without a tag -- yuck + asnWriter._ensure(pub.length); + asnWriter._buf.set(pub, asnWriter._offset); + asnWriter._offset += pub.length; + // end hack + asnWriter.endSequence(); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('EC PRIVATE', asnWriter.buffer); +} - this.prefinished = false; // True if the error was already emitted and should not be thrown again +function genOpenSSLECDSAPubFromPriv(curveName, priv) { + const tempECDH = createECDH(curveName); + tempECDH.setPrivateKey(priv); + return tempECDH.getPublicKey(); +} - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. +const BaseKey = { + sign: (() => { + if (typeof sign_ === 'function') { + return function sign(data, algo) { + const pem = this[SYM_PRIV_PEM]; + if (pem === null) + return new Error('No private key available'); + if (!algo || typeof algo !== 'string') + algo = this[SYM_HASH_ALGO]; + try { + return sign_(algo, data, pem); + } catch (ex) { + return ex; + } + }; + } + return function sign(data, algo) { + const pem = this[SYM_PRIV_PEM]; + if (pem === null) + return new Error('No private key available'); + if (!algo || typeof algo !== 'string') + algo = this[SYM_HASH_ALGO]; + const signature = createSign(algo); + signature.update(data); + try { + return signature.sign(pem); + } catch (ex) { + return ex; + } + }; + })(), + verify: (() => { + if (typeof verify_ === 'function') { + return function verify(data, signature, algo) { + const pem = this[SYM_PUB_PEM]; + if (pem === null) + return new Error('No public key available'); + if (!algo || typeof algo !== 'string') + algo = this[SYM_HASH_ALGO]; + try { + return verify_(algo, data, pem, signature); + } catch (ex) { + return ex; + } + }; + } + return function verify(data, signature, algo) { + const pem = this[SYM_PUB_PEM]; + if (pem === null) + return new Error('No public key available'); + if (!algo || typeof algo !== 'string') + algo = this[SYM_HASH_ALGO]; + const verifier = createVerify(algo); + verifier.update(data); + try { + return verifier.verify(pem, signature); + } catch (ex) { + return ex; + } + }; + })(), + isPrivateKey: function isPrivateKey() { + return (this[SYM_PRIV_PEM] !== null); + }, + getPrivatePEM: function getPrivatePEM() { + return this[SYM_PRIV_PEM]; + }, + getPublicPEM: function getPublicPEM() { + return this[SYM_PUB_PEM]; + }, + getPublicSSH: function getPublicSSH() { + return this[SYM_PUB_SSH]; + }, + equals: function equals(key) { + const parsed = parseKey(key); + if (parsed instanceof Error) + return false; + return ( + this.type === parsed.type + && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] + && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] + && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH] + ); + }, +}; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - this.autoDestroy = !!options.autoDestroy; // count buffered requests +function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, + decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; +} +OpenSSH_Private.prototype = BaseKey; +{ + const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; + OpenSSH_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + let ret; + const data = Buffer.from(m[1], 'base64'); + if (data.length < 31) // magic (+ magic null term.) + minimum field lengths + return new Error('Malformed OpenSSH private key'); + const magic = data.utf8Slice(0, 15); + if (magic !== 'openssh-key-v1\0') + return new Error(`Unsupported OpenSSH key magic: ${magic}`); - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two + const cipherName = readString(data, 15, true); + if (cipherName === undefined) + return new Error('Malformed OpenSSH private key'); + if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) + return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); - this.corkedRequestsFree = new CorkedRequest(this); -} + const kdfName = readString(data, data._pos, true); + if (kdfName === undefined) + return new Error('Malformed OpenSSH private key'); + if (kdfName !== 'none') { + if (cipherName === 'none') + return new Error('Malformed OpenSSH private key'); + if (kdfName !== 'bcrypt') + return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); + if (!passphrase) { + return new Error( + 'Encrypted private OpenSSH key detected, but no passphrase given' + ); + } + } else if (cipherName !== 'none') { + return new Error('Malformed OpenSSH private key'); + } -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; + let encInfo; + let cipherKey; + let cipherIV; + if (cipherName !== 'none') + encInfo = CIPHER_INFO[cipherName]; + const kdfOptions = readString(data, data._pos); + if (kdfOptions === undefined) + return new Error('Malformed OpenSSH private key'); + if (kdfOptions.length) { + switch (kdfName) { + case 'none': + return new Error('Malformed OpenSSH private key'); + case 'bcrypt': { + /* + string salt + uint32 rounds + */ + const salt = readString(kdfOptions, 0); + if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) + return new Error('Malformed OpenSSH private key'); + const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); + const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); + const r = bcrypt_pbkdf(passphrase, + passphrase.length, + salt, + salt.length, + gen, + gen.length, + rounds); + if (r !== 0) + return new Error('Failed to generate information to decrypt key'); + cipherKey = bufferSlice(gen, 0, encInfo.keyLen); + cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); + break; + } + } + } else if (kdfName !== 'none') { + return new Error('Malformed OpenSSH private key'); + } - while (current) { - out.push(current); - current = current.next; - } + if (data._pos + 3 >= data.length) + return new Error('Malformed OpenSSH private key'); + const keyCount = readUInt32BE(data, data._pos); + data._pos += 4; - return out; -}; + if (keyCount > 0) { + // TODO: place sensible limit on max `keyCount` -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. + // Read public keys first + for (let i = 0; i < keyCount; ++i) { + const pubData = readString(data, data._pos); + if (pubData === undefined) + return new Error('Malformed OpenSSH private key'); + const type = readString(pubData, 0, true); + if (type === undefined) + return new Error('Malformed OpenSSH private key'); + } + let privBlob = readString(data, data._pos); + if (privBlob === undefined) + return new Error('Malformed OpenSSH private key'); -var realHasInstance; + if (cipherKey !== undefined) { + // Encrypted private key(s) + if (privBlob.length < encInfo.blockLen + || (privBlob.length % encInfo.blockLen) !== 0) { + return new Error('Malformed OpenSSH private key'); + } + try { + const options = { authTagLength: encInfo.authLen }; + const decipher = createDecipheriv(encInfo.sslName, + cipherKey, + cipherIV, + options); + decipher.setAutoPadding(false); + if (encInfo.authLen > 0) { + if (data.length - data._pos < encInfo.authLen) + return new Error('Malformed OpenSSH private key'); + decipher.setAuthTag( + bufferSlice(data, data._pos, data._pos += encInfo.authLen) + ); + } + privBlob = combineBuffers(decipher.update(privBlob), + decipher.final()); + } catch (ex) { + return ex; + } + } + // Nothing should we follow the private key(s), except a possible + // authentication tag for relevant ciphers + if (data._pos !== data.length) + return new Error('Malformed OpenSSH private key'); -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; + ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); + } else { + ret = []; } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; + if (ret instanceof Error) + return ret; + // This will need to change if/when OpenSSH ever starts storing multiple + // keys in their key files + return ret[0]; }; -} - -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(1359); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. + function parseOpenSSHPrivKeys(data, nkeys, decrypted) { + const keys = []; + /* + uint32 checkint + uint32 checkint + string privatekey1 + string comment1 + string privatekey2 + string comment2 + ... + string privatekeyN + string commentN + char 1 + char 2 + char 3 + ... + char padlen % 255 + */ + if (data.length < 8) + return new Error('Malformed OpenSSH private key'); + const check1 = readUInt32BE(data, 0); + const check2 = readUInt32BE(data, 4); + if (check1 !== check2) { + if (decrypted) { + return new Error( + 'OpenSSH key integrity check failed -- bad passphrase?' + ); + } + return new Error('OpenSSH key integrity check failed'); + } + data._pos = 8; + let i; + let oid; + for (i = 0; i < nkeys; ++i) { + let algo; + let privPEM; + let pubPEM; + let pubSSH; + // The OpenSSH documentation for the key format actually lies, the + // entirety of the private key content is not contained with a string + // field, it's actually the literal contents of the private key, so to be + // able to find the end of the key data you need to know the layout/format + // of each key type ... + const type = readString(data, data._pos, true); + if (type === undefined) + return new Error('Malformed OpenSSH private key'); + switch (type) { + case 'ssh-rsa': { + /* + string n -- public + string e -- public + string d -- private + string iqmp -- private + string p -- private + string q -- private + */ + const n = readString(data, data._pos); + if (n === undefined) + return new Error('Malformed OpenSSH private key'); + const e = readString(data, data._pos); + if (e === undefined) + return new Error('Malformed OpenSSH private key'); + const d = readString(data, data._pos); + if (d === undefined) + return new Error('Malformed OpenSSH private key'); + const iqmp = readString(data, data._pos); + if (iqmp === undefined) + return new Error('Malformed OpenSSH private key'); + const p = readString(data, data._pos); + if (p === undefined) + return new Error('Malformed OpenSSH private key'); + const q = readString(data, data._pos); + if (q === undefined) + return new Error('Malformed OpenSSH private key'); -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); + algo = 'sha1'; + break; + } + case 'ssh-dss': { + /* + string p -- public + string q -- public + string g -- public + string y -- public + string x -- private + */ + const p = readString(data, data._pos); + if (p === undefined) + return new Error('Malformed OpenSSH private key'); + const q = readString(data, data._pos); + if (q === undefined) + return new Error('Malformed OpenSSH private key'); + const g = readString(data, data._pos); + if (g === undefined) + return new Error('Malformed OpenSSH private key'); + const y = readString(data, data._pos); + if (y === undefined) + return new Error('Malformed OpenSSH private key'); + const x = readString(data, data._pos); + if (x === undefined) + return new Error('Malformed OpenSSH private key'); -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + privPEM = genOpenSSLDSAPriv(p, q, g, y, x); + algo = 'sha1'; + break; + } + case 'ssh-ed25519': { + if (!eddsaSupported) + return new Error(`Unsupported OpenSSH private key type: ${type}`); + /* + * string public key + * string private key + public key + */ + const edpub = readString(data, data._pos); + if (edpub === undefined || edpub.length !== 32) + return new Error('Malformed OpenSSH private key'); + const edpriv = readString(data, data._pos); + if (edpriv === undefined || edpriv.length !== 64) + return new Error('Malformed OpenSSH private key'); - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. + pubPEM = genOpenSSLEdPub(edpub); + pubSSH = genOpenSSHEdPub(edpub); + privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); + algo = null; + break; + } + case 'ecdsa-sha2-nistp256': + algo = 'sha256'; + oid = '1.2.840.10045.3.1.7'; + // FALLTHROUGH + case 'ecdsa-sha2-nistp384': + if (algo === undefined) { + algo = 'sha384'; + oid = '1.3.132.0.34'; + } + // FALLTHROUGH + case 'ecdsa-sha2-nistp521': { + if (algo === undefined) { + algo = 'sha512'; + oid = '1.3.132.0.35'; + } + /* + string curve name + string Q -- public + string d -- private + */ + // TODO: validate curve name against type + if (!skipFields(data, 1)) // Skip curve name + return new Error('Malformed OpenSSH private key'); + const ecpub = readString(data, data._pos); + if (ecpub === undefined) + return new Error('Malformed OpenSSH private key'); + const ecpriv = readString(data, data._pos); + if (ecpriv === undefined) + return new Error('Malformed OpenSSH private key'); + pubPEM = genOpenSSLECDSAPub(oid, ecpub); + pubSSH = genOpenSSHECDSAPub(oid, ecpub); + privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); + break; + } + default: + return new Error(`Unsupported OpenSSH private key type: ${type}`); + } -function validChunk(stream, state, chunk, cb) { - var er; + const privComment = readString(data, data._pos, true); + if (privComment === undefined) + return new Error('Malformed OpenSSH private key'); - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } + keys.push( + new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, + decrypted) + ); + } + let cnt = 0; + for (i = data._pos; i < data.length; ++i) { + if (data[i] !== (++cnt % 255)) + return new Error('Malformed OpenSSH private key'); + } - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; + return keys; } - - return true; } -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; +function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, + decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; +} +OpenSSH_Old_Private.prototype = BaseKey; +{ + const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; + OpenSSH_Old_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + let privBlob = Buffer.from(m[3], 'base64'); + let headers = m[2]; + let decrypted = false; + if (headers !== undefined) { + // encrypted key + headers = headers.split(/\r\n|\n/g); + for (let i = 0; i < headers.length; ++i) { + const header = headers[i]; + let sepIdx = header.indexOf(':'); + if (header.slice(0, sepIdx) === 'DEK-Info') { + const val = header.slice(sepIdx + 2); + sepIdx = val.indexOf(','); + if (sepIdx === -1) + continue; + const cipherName = val.slice(0, sepIdx).toLowerCase(); + if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { + return new Error( + `Cipher (${cipherName}) not supported ` + + 'for encrypted OpenSSH private key' + ); + } + const encInfo = CIPHER_INFO_OPENSSL[cipherName]; + if (!encInfo) { + return new Error( + `Cipher (${cipherName}) not supported ` + + 'for encrypted OpenSSH private key' + ); + } + const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); + if (cipherIV.length !== encInfo.ivLen) + return new Error('Malformed encrypted OpenSSH private key'); + if (!passphrase) { + return new Error( + 'Encrypted OpenSSH private key detected, but no passphrase given' + ); + } + const ivSlice = bufferSlice(cipherIV, 0, 8); + let cipherKey = createHash('md5') + .update(passphrase) + .update(ivSlice) + .digest(); + while (cipherKey.length < encInfo.keyLen) { + cipherKey = combineBuffers( + cipherKey, + createHash('md5') + .update(cipherKey) + .update(passphrase) + .update(ivSlice) + .digest() + ); + } + if (cipherKey.length > encInfo.keyLen) + cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); + try { + const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); + decipher.setAutoPadding(false); + privBlob = combineBuffers(decipher.update(privBlob), + decipher.final()); + decrypted = true; + } catch (ex) { + return ex; + } + } + } + } -Writable.prototype.cork = function () { - this._writableState.corked++; -}; + let type; + let privPEM; + let pubPEM; + let pubSSH; + let algo; + let reader; + let errMsg = 'Malformed OpenSSH private key'; + if (decrypted) + errMsg += '. Bad passphrase?'; + switch (m[1]) { + case 'RSA': + type = 'ssh-rsa'; + privPEM = makePEM('RSA PRIVATE', privBlob); + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); // skip version + const n = reader.readString(Ber.Integer, true); + if (n === null) + return new Error(errMsg); + const e = reader.readString(Ber.Integer, true); + if (e === null) + return new Error(errMsg); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + } catch { + return new Error(errMsg); + } + algo = 'sha1'; + break; + case 'DSA': + type = 'ssh-dss'; + privPEM = makePEM('DSA PRIVATE', privBlob); + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); // skip version + const p = reader.readString(Ber.Integer, true); + if (p === null) + return new Error(errMsg); + const q = reader.readString(Ber.Integer, true); + if (q === null) + return new Error(errMsg); + const g = reader.readString(Ber.Integer, true); + if (g === null) + return new Error(errMsg); + const y = reader.readString(Ber.Integer, true); + if (y === null) + return new Error(errMsg); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + } catch { + return new Error(errMsg); + } + algo = 'sha1'; + break; + case 'EC': { + let ecSSLName; + let ecPriv; + let ecOID; + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); // skip version + ecPriv = reader.readString(Ber.OctetString, true); + reader.readByte(); // Skip "complex" context type byte + const offset = reader.readLength(); // Skip context length + if (offset !== null) { + reader._offset = offset; + ecOID = reader.readOID(); + if (ecOID === null) + return new Error(errMsg); + switch (ecOID) { + case '1.2.840.10045.3.1.7': + // prime256v1/secp256r1 + ecSSLName = 'prime256v1'; + type = 'ecdsa-sha2-nistp256'; + algo = 'sha256'; + break; + case '1.3.132.0.34': + // secp384r1 + ecSSLName = 'secp384r1'; + type = 'ecdsa-sha2-nistp384'; + algo = 'sha384'; + break; + case '1.3.132.0.35': + // secp521r1 + ecSSLName = 'secp521r1'; + type = 'ecdsa-sha2-nistp521'; + algo = 'sha512'; + break; + default: + return new Error(`Unsupported private key EC OID: ${ecOID}`); + } + } else { + return new Error(errMsg); + } + } catch { + return new Error(errMsg); + } + privPEM = makePEM('EC PRIVATE', privBlob); + const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); + pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); + pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); + break; + } + } -Writable.prototype.uncork = function () { - var state = this._writableState; + return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, + decrypted); + }; +} - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; +function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; +} +PPK_Private.prototype = BaseKey; +{ + const EMPTY_PASSPHRASE = Buffer.alloc(0); + const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + const PPK_PP1 = Buffer.from([0, 0, 0, 0]); + const PPK_PP2 = Buffer.from([0, 0, 0, 1]); + const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; + PPK_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + // m[1] = key type + // m[2] = encryption type + // m[3] = comment + // m[4] = base64-encoded public key data: + // for "ssh-rsa": + // string "ssh-rsa" + // mpint e (public exponent) + // mpint n (modulus) + // for "ssh-dss": + // string "ssh-dss" + // mpint p (modulus) + // mpint q (prime) + // mpint g (base number) + // mpint y (public key parameter: g^x mod p) + // m[5] = base64-encoded private key data: + // for "ssh-rsa": + // mpint d (private exponent) + // mpint p (prime 1) + // mpint q (prime 2) + // mpint iqmp ([inverse of q] mod p) + // for "ssh-dss": + // mpint x (private key parameter) + // m[6] = SHA1 HMAC over: + // string name of algorithm ("ssh-dss", "ssh-rsa") + // string encryption type + // string comment + // string public key data + // string private-plaintext (including the final padding) + const cipherName = m[2]; + const encrypted = (cipherName !== 'none'); + if (encrypted && !passphrase) { + return new Error( + 'Encrypted PPK private key detected, but no passphrase given' + ); + } -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); + let privBlob = Buffer.from(m[5], 'base64'); -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } + if (encrypted) { + const encInfo = CIPHER_INFO[cipherName]; + let cipherKey = combineBuffers( + createHash('sha1').update(PPK_PP1).update(passphrase).digest(), + createHash('sha1').update(PPK_PP2).update(passphrase).digest() + ); + if (cipherKey.length > encInfo.keyLen) + cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); + try { + const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV); + decipher.setAutoPadding(false); + privBlob = combineBuffers(decipher.update(privBlob), + decipher.final()); + } catch (ex) { + return ex; + } + } - return chunk; -} + const type = m[1]; + const comment = m[3]; + const pubBlob = Buffer.from(m[4], 'base64'); -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. + const mac = m[6]; + const typeLen = type.length; + const cipherNameLen = cipherName.length; + const commentLen = Buffer.byteLength(comment); + const pubLen = pubBlob.length; + const privLen = privBlob.length; + const macData = Buffer.allocUnsafe(4 + typeLen + + 4 + cipherNameLen + + 4 + commentLen + + 4 + pubLen + + 4 + privLen); + let p = 0; -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); + writeUInt32BE(macData, typeLen, p); + macData.utf8Write(type, p += 4, typeLen); + writeUInt32BE(macData, cipherNameLen, p += typeLen); + macData.utf8Write(cipherName, p += 4, cipherNameLen); + writeUInt32BE(macData, commentLen, p += cipherNameLen); + macData.utf8Write(comment, p += 4, commentLen); + writeUInt32BE(macData, pubLen, p += commentLen); + macData.set(pubBlob, p += 4); + writeUInt32BE(macData, privLen, p += pubLen); + macData.set(privBlob, p + 4); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } + if (!passphrase) + passphrase = EMPTY_PASSPHRASE; - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + const calcMAC = createHmac( + 'sha1', + createHash('sha1') + .update('putty-private-key-file-mac-key') + .update(passphrase) + .digest() + ).update(macData).digest('hex'); - if (!ret) state.needDrain = true; + if (calcMAC !== mac) { + if (encrypted) { + return new Error( + 'PPK private key integrity check failed -- bad passphrase?' + ); + } + return new Error('PPK private key integrity check failed'); + } - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; + let pubPEM; + let pubSSH; + let privPEM; + pubBlob._pos = 0; + skipFields(pubBlob, 1); // skip (duplicate) key type + switch (type) { + case 'ssh-rsa': { + const e = readString(pubBlob, pubBlob._pos); + if (e === undefined) + return new Error('Malformed PPK public key'); + const n = readString(pubBlob, pubBlob._pos); + if (n === undefined) + return new Error('Malformed PPK public key'); + const d = readString(privBlob, 0); + if (d === undefined) + return new Error('Malformed PPK private key'); + const p = readString(privBlob, privBlob._pos); + if (p === undefined) + return new Error('Malformed PPK private key'); + const q = readString(privBlob, privBlob._pos); + if (q === undefined) + return new Error('Malformed PPK private key'); + const iqmp = readString(privBlob, privBlob._pos); + if (iqmp === undefined) + return new Error('Malformed PPK private key'); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); + break; + } + case 'ssh-dss': { + const p = readString(pubBlob, pubBlob._pos); + if (p === undefined) + return new Error('Malformed PPK public key'); + const q = readString(pubBlob, pubBlob._pos); + if (q === undefined) + return new Error('Malformed PPK public key'); + const g = readString(pubBlob, pubBlob._pos); + if (g === undefined) + return new Error('Malformed PPK public key'); + const y = readString(pubBlob, pubBlob._pos); + if (y === undefined) + return new Error('Malformed PPK public key'); + const x = readString(privBlob, 0); + if (x === undefined) + return new Error('Malformed PPK private key'); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + privPEM = genOpenSSLDSAPriv(p, q, g, y, x); + break; + } } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; + return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', + encrypted); + }; } -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; +function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = null; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = false; +} +OpenSSH_Public.prototype = BaseKey; +{ + let regexp; + if (eddsaSupported) + regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; + else + regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; + OpenSSH_Public.parse = (str) => { + const m = regexp.exec(str); + if (m === null) + return null; + // m[1] = full type + // m[2] = base type + // m[3] = base64-encoded public key + // m[4] = comment - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error + const fullType = m[1]; + const baseType = m[2]; + const data = Buffer.from(m[3], 'base64'); + const comment = (m[4] || ''); - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error + const type = readString(data, data._pos, true); + if (type === undefined || type.indexOf(baseType) !== 0) + return new Error('Malformed OpenSSH public key'); - finishMaybe(stream, state); - } + return parseDER(data, baseType, comment, fullType); + }; } -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; + +function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = null; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = false; } +RFC4716_Public.prototype = BaseKey; +{ + const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; + const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; + const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; + const RE_HEADER_ENDS = /\\\r?\n/g; + RFC4716_Public.parse = (str) => { + let m = regexp.exec(str); + if (m === null) + return null; -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; + const body = m[1]; + let dataStart = 0; + let comment = ''; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + while (m = RE_HEADER.exec(body)) { + const headerName = m[1]; + const headerValue = m[2].replace(RE_HEADER_ENDS, ''); + if (headerValue.length > 1024) { + RE_HEADER.lastIndex = 0; + return new Error('Malformed RFC4716 public key'); + } - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); + dataStart = RE_HEADER.lastIndex; + + if (headerName.toLowerCase() === 'comment') { + comment = headerValue; + if (comment.length > 1 + && comment.charCodeAt(0) === 34/* '"' */ + && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { + comment = comment.slice(1, -1); + } + } } - } -} -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. + let data = body.slice(dataStart); + if (!RE_DATA.test(data)) + return new Error('Malformed RFC4716 public key'); + data = Buffer.from(data, 'base64'); -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it + const type = readString(data, 0, true); + if (type === undefined) + return new Error('Malformed RFC4716 public key'); + + let pubPEM = null; + let pubSSH = null; + switch (type) { + case 'ssh-rsa': { + const e = readString(data, data._pos); + if (e === undefined) + return new Error('Malformed RFC4716 public key'); + const n = readString(data, data._pos); + if (n === undefined) + return new Error('Malformed RFC4716 public key'); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + break; + } + case 'ssh-dss': { + const p = readString(data, data._pos); + if (p === undefined) + return new Error('Malformed RFC4716 public key'); + const q = readString(data, data._pos); + if (q === undefined) + return new Error('Malformed RFC4716 public key'); + const g = readString(data, data._pos); + if (g === undefined) + return new Error('Malformed RFC4716 public key'); + const y = readString(data, data._pos); + if (y === undefined) + return new Error('Malformed RFC4716 public key'); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + break; + } + default: + return new Error('Malformed RFC4716 public key'); + } + return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); + }; +} -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; +function parseDER(data, baseType, comment, fullType) { + if (!isSupportedKeyType(baseType)) + return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; + let algo; + let oid; + let pubPEM = null; + let pubSSH = null; + + switch (baseType) { + case 'ssh-rsa': { + const e = readString(data, data._pos || 0); + if (e === undefined) + return new Error('Malformed OpenSSH public key'); + const n = readString(data, data._pos); + if (n === undefined) + return new Error('Malformed OpenSSH public key'); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + algo = 'sha1'; + break; + } + case 'ssh-dss': { + const p = readString(data, data._pos || 0); + if (p === undefined) + return new Error('Malformed OpenSSH public key'); + const q = readString(data, data._pos); + if (q === undefined) + return new Error('Malformed OpenSSH public key'); + const g = readString(data, data._pos); + if (g === undefined) + return new Error('Malformed OpenSSH public key'); + const y = readString(data, data._pos); + if (y === undefined) + return new Error('Malformed OpenSSH public key'); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + algo = 'sha1'; + break; + } + case 'ssh-ed25519': { + const edpub = readString(data, data._pos || 0); + if (edpub === undefined || edpub.length !== 32) + return new Error('Malformed OpenSSH public key'); + pubPEM = genOpenSSLEdPub(edpub); + pubSSH = genOpenSSHEdPub(edpub); + algo = null; + break; + } + case 'ecdsa-sha2-nistp256': + algo = 'sha256'; + oid = '1.2.840.10045.3.1.7'; + // FALLTHROUGH + case 'ecdsa-sha2-nistp384': + if (algo === undefined) { + algo = 'sha384'; + oid = '1.3.132.0.34'; + } + // FALLTHROUGH + case 'ecdsa-sha2-nistp521': { + if (algo === undefined) { + algo = 'sha512'; + oid = '1.3.132.0.35'; + } + // TODO: validate curve name against type + if (!skipFields(data, 1)) // Skip curve name + return new Error('Malformed OpenSSH public key'); + const ecpub = readString(data, data._pos || 0); + if (ecpub === undefined) + return new Error('Malformed OpenSSH public key'); + pubPEM = genOpenSSLECDSAPub(oid, ecpub); + pubSSH = genOpenSSHECDSAPub(oid, ecpub); + break; } + default: + return new Error(`Unsupported OpenSSH public key type: ${baseType}`); + } - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite + return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); +} - state.pendingcb++; - state.lastBufferedRequest = null; +function isSupportedKeyType(type) { + switch (type) { + case 'ssh-rsa': + case 'ssh-dss': + case 'ecdsa-sha2-nistp256': + case 'ecdsa-sha2-nistp384': + case 'ecdsa-sha2-nistp521': + return true; + case 'ssh-ed25519': + if (eddsaSupported) + return true; + // FALLTHROUGH + default: + return false; + } +} - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } +function isParsedKey(val) { + if (!val) + return false; + return (typeof val[SYM_DECRYPTED] === 'boolean'); +} - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. +function parseKey(data, passphrase) { + if (isParsedKey(data)) + return data; - if (state.writing) { - break; - } - } + let origBuffer; + if (Buffer.isBuffer(data)) { + origBuffer = data; + data = data.utf8Slice(0, data.length).trim(); + } else if (typeof data === 'string') { + data = data.trim(); + } else { + return new Error('Key data must be a Buffer or string'); + } - if (entry === null) state.lastBufferedRequest = null; + // eslint-disable-next-line eqeqeq + if (passphrase != undefined) { + if (typeof passphrase === 'string') + passphrase = Buffer.from(passphrase); + else if (!Buffer.isBuffer(passphrase)) + return new Error('Passphrase must be a string or Buffer when supplied'); } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + let ret; -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; + // First try as printable string format (e.g. PEM) -Writable.prototype._writev = null; + // Private keys + if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) + return ret; + if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) + return ret; + if ((ret = PPK_Private.parse(data, passphrase)) !== null) + return ret; -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + // Public keys + if ((ret = OpenSSH_Public.parse(data)) !== null) + return ret; + if ((ret = RFC4716_Public.parse(data)) !== null) + return ret; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + // Finally try as a binary format if we were originally passed binary data + if (origBuffer) { + binaryKeyParser.init(origBuffer, 0); + const type = binaryKeyParser.readString(true); + if (type !== undefined) { + data = binaryKeyParser.readRaw(); + if (data !== undefined) { + ret = parseDER(data, type, '', type); + // Ignore potentially useless errors in case the data was not actually + // in the binary format + if (ret instanceof Error) + ret = null; + } + } + binaryKeyParser.clear(); } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. + if (ret) + return ret; + return new Error('Unsupported key format'); +} - if (!state.ending) endWritable(this, state, cb); - return this; +module.exports = { + isParsedKey, + isSupportedKeyType, + parseDERKey: (data, type) => parseDER(data, type, '', type), + parseKey, }; -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} +/***/ }), -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; +/***/ 7609: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (err) { - errorOrDestroy(stream, err); - } +"use strict"; - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); + +const assert = __nccwpck_require__(9491); +const { inspect } = __nccwpck_require__(3837); + +// Only use this for integers! Decimal numbers do not work with this function. +function addNumericalSeparator(val) { + let res = ''; + let i = val.length; + const start = val[0] === '-' ? 1 : 0; + for (; i >= start + 4; i -= 3) + res = `_${val.slice(i - 3, i)}${res}`; + return `${val.slice(0, i)}${res}`; } -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); +function oneOf(expected, thing) { + assert(typeof thing === 'string', '`thing` has to be of type string'); + if (Array.isArray(expected)) { + const len = expected.length; + assert(len > 0, 'At least one expected value needs to be specified'); + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; } + return `of ${thing} ${expected[0]}`; } + return `of ${thing} ${String(expected)}`; } -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); +exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { + constructor(message) { + super(); + Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; + const suffix = 'This is caused by either a bug in ssh2 ' + + 'or incorrect usage of ssh2 internals.\n' + + 'Please open an issue with this stack trace at ' + + 'https://github.com/mscdex/ssh2/issues\n'; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } + this.message = (message === undefined ? suffix : `${message}\n${suffix}`); } +}; - return need; -} +const MAX_32BIT_INT = 2 ** 32; +const MAX_32BIT_BIGINT = (() => { + try { + return new Function('return 2n ** 32n')(); + } catch {} +})(); +exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { + constructor(str, range, input, replaceDefaultBoolean) { + super(); + Error.captureStackTrace(this, ERR_OUT_OF_RANGE); -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); + assert(range, 'Missing "range" argument'); + let msg = (replaceDefaultBoolean + ? str + : `The value of "${str}" is out of range.`); + let received; + if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === 'bigint') { + received = String(input); + if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) + received = addNumericalSeparator(received); + received += 'n'; + } else { + received = inspect(input); + } + msg += ` It must be ${range}. Received ${received}`; - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + this.message = msg; } +}; - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - +class ERR_INVALID_ARG_TYPE extends TypeError { + constructor(name, expected, actual) { + super(); + Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); - state.corkedRequestsFree.next = corkReq; -} + assert(typeof name === 'string', `'name' must be a string`); -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && expected.startsWith('not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; } - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + let msg; + if (name.endsWith(' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = (name.includes('.') ? 'property' : 'argument'); + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + msg += `. Received type ${typeof actual}`; - this._writableState.destroyed = value; + this.message = msg; } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; +} +exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; -Writable.prototype._destroy = function (err, cb) { - cb(err); +exports.validateNumber = function validateNumber(value, name) { + if (typeof value !== 'number') + throw new ERR_INVALID_ARG_TYPE(name, 'number', value); }; + /***/ }), -/***/ 3306: +/***/ 9475: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var _Object$setPrototypeO; +const Ber = (__nccwpck_require__(970).Ber); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +let DISCONNECT_REASON; -var finished = __nccwpck_require__(6080); +const FastBuffer = Buffer[Symbol.species]; +const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); +function readUInt32BE(buf, offset) { + return (buf[offset++] * 16777216) + + (buf[offset++] * 65536) + + (buf[offset++] * 256) + + buf[offset]; +} -function createIterResult(value, done) { - return { - value: value, - done: done - }; +function bufferCopy(src, dest, srcStart, srcEnd, destStart) { + if (!destStart) + destStart = 0; + if (srcEnd > src.length) + srcEnd = src.length; + let nb = srcEnd - srcStart; + const destLeft = (dest.length - destStart); + if (nb > destLeft) + nb = destLeft; + dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), + destStart); + return nb; } -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; +function bufferSlice(buf, start, end) { + if (end === undefined) + end = buf.length; + return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); +} - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' +function makeBufferParser() { + let pos = 0; + let buffer; - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} + const self = { + init: (buf, start) => { + buffer = buf; + pos = (typeof start === 'number' ? start : 0); + }, + pos: () => pos, + length: () => (buffer ? buffer.length : 0), + avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), + clear: () => { + buffer = undefined; + }, + readUInt32BE: () => { + if (!buffer || pos + 3 >= buffer.length) + return; + return (buffer[pos++] * 16777216) + + (buffer[pos++] * 65536) + + (buffer[pos++] * 256) + + buffer[pos++]; + }, + readUInt64BE: (behavior) => { + if (!buffer || pos + 7 >= buffer.length) + return; + switch (behavior) { + case 'always': + return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); + case 'maybe': + if (buffer[pos] > 0x1F) + return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); + // FALLTHROUGH + default: + return (buffer[pos++] * 72057594037927940) + + (buffer[pos++] * 281474976710656) + + (buffer[pos++] * 1099511627776) + + (buffer[pos++] * 4294967296) + + (buffer[pos++] * 16777216) + + (buffer[pos++] * 65536) + + (buffer[pos++] * 256) + + buffer[pos++]; + } + }, + skip: (n) => { + if (buffer && n > 0) + pos += n; + }, + skipString: () => { + const len = self.readUInt32BE(); + if (len === undefined) + return; + pos += len; + return (pos <= buffer.length ? len : undefined); + }, + readByte: () => { + if (buffer && pos < buffer.length) + return buffer[pos++]; + }, + readBool: () => { + if (buffer && pos < buffer.length) + return !!buffer[pos++]; + }, + readList: () => { + const list = self.readString(true); + if (list === undefined) + return; + return (list ? list.split(',') : []); + }, + readString: (dest, maxLen) => { + if (typeof dest === 'number') { + maxLen = dest; + dest = undefined; + } -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} + const len = self.readUInt32BE(); + if (len === undefined) + return; -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); + if ((buffer.length - pos) < len + || (typeof maxLen === 'number' && len > maxLen)) { return; } - iter[kHandlePromise](resolve, reject); - }, reject); + if (dest) { + if (Buffer.isBuffer(dest)) + return bufferCopy(buffer, dest, pos, pos += len); + return buffer.utf8Slice(pos, pos += len); + } + return bufferSlice(buffer, pos, pos += len); + }, + readRaw: (len) => { + if (!buffer) + return; + if (typeof len !== 'number') + return bufferSlice(buffer, pos, pos += (buffer.length - pos)); + if ((buffer.length - pos) >= len) + return bufferSlice(buffer, pos, pos += len); + }, }; -} -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, + return self; +} - next: function next() { - var _this = this; +function makeError(msg, level, fatal) { + const err = new Error(msg); + if (typeof level === 'boolean') { + fatal = level; + err.level = 'protocol'; + } else { + err.level = level || 'protocol'; + } + err.fatal = !!fatal; + return err; +} - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; +function writeUInt32BE(buf, value, offset) { + buf[offset++] = (value >>> 24); + buf[offset++] = (value >>> 16); + buf[offset++] = (value >>> 8); + buf[offset++] = value; + return offset; +} - if (error !== null) { - return Promise.reject(error); - } +const utilBufferParser = makeBufferParser(); - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); +module.exports = { + bufferCopy, + bufferSlice, + FastBuffer, + bufferFill: (buf, value, start, end) => { + return TypedArrayFill.call(buf, value, start, end); + }, + makeError, + doFatalError: (protocol, msg, level, reason) => { + let err; + if (DISCONNECT_REASON === undefined) + ({ DISCONNECT_REASON } = __nccwpck_require__(6832)); + if (msg instanceof Error) { + // doFatalError(protocol, err[, reason]) + err = msg; + if (typeof level !== 'number') + reason = DISCONNECT_REASON.PROTOCOL_ERROR; + else + reason = level; + } else { + // doFatalError(protocol, msg[, level[, reason]]) + err = makeError(msg, level, true); + } + if (typeof reason !== 'number') + reason = DISCONNECT_REASON.PROTOCOL_ERROR; + protocol.disconnect(reason); + protocol._destruct(); + protocol._onError(err); + return Infinity; + }, + readUInt32BE, + writeUInt32BE, + writeUInt32LE: (buf, value, offset) => { + buf[offset++] = value; + buf[offset++] = (value >>> 8); + buf[offset++] = (value >>> 16); + buf[offset++] = (value >>> 24); + return offset; + }, + makeBufferParser, + bufferParser: makeBufferParser(), + readString: (buffer, start, dest, maxLen) => { + if (typeof dest === 'number') { + maxLen = dest; + dest = undefined; } - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - + if (start === undefined) + start = 0; - var lastPromise = this[kLastPromise]; - var promise; + const left = (buffer.length - start); + if (start < 0 || start >= buffer.length || left < 4) + return; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); + const len = readUInt32BE(buffer, start); + if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) + return; - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } + start += 4; + const end = start + len; + buffer._pos = end; - promise = new Promise(this[kHandlePromise]); + if (dest) { + if (Buffer.isBuffer(dest)) + return bufferCopy(buffer, dest, start, end); + return buffer.utf8Slice(start, end); } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; + return bufferSlice(buffer, start, end); + }, + sigSSHToASN1: (sig, type) => { + switch (type) { + case 'ssh-dss': { + if (sig.length > 40) + return sig; + // Change bare signature r and s values to ASN.1 BER values for OpenSSL + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + let r = sig.slice(0, 20); + let s = sig.slice(20); + if (r[0] & 0x80) { + const rNew = Buffer.allocUnsafe(21); + rNew[0] = 0x00; + r.copy(rNew, 1); + r = rNew; + } else if (r[0] === 0x00 && !(r[1] & 0x80)) { + r = r.slice(1); + } + if (s[0] & 0x80) { + const sNew = Buffer.allocUnsafe(21); + sNew[0] = 0x00; + s.copy(sNew, 1); + s = sNew; + } else if (s[0] === 0x00 && !(s[1] & 0x80)) { + s = s.slice(1); + } + asnWriter.writeBuffer(r, Ber.Integer); + asnWriter.writeBuffer(s, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; } + case 'ecdsa-sha2-nistp256': + case 'ecdsa-sha2-nistp384': + case 'ecdsa-sha2-nistp521': { + utilBufferParser.init(sig, 0); + const r = utilBufferParser.readString(); + const s = utilBufferParser.readString(); + utilBufferParser.clear(); + if (r === undefined || s === undefined) + return; - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeBuffer(r, Ber.Integer); + asnWriter.writeBuffer(s, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); + default: + return sig; + } + }, + convertSignature: (signature, keyType) => { + switch (keyType) { + case 'ssh-dss': { + if (signature.length <= 40) + return signature; + // This is a quick and dirty way to get from BER encoded r and s that + // OpenSSL gives us, to just the bare values back to back (40 bytes + // total) like OpenSSH (and possibly others) are expecting + const asnReader = new Ber.Reader(signature); + asnReader.readSequence(); + let r = asnReader.readString(Ber.Integer, true); + let s = asnReader.readString(Ber.Integer, true); + let rOffset = 0; + let sOffset = 0; + if (r.length < 20) { + const rNew = Buffer.allocUnsafe(20); + rNew.set(r, 1); + r = rNew; + r[0] = 0; + } + if (s.length < 20) { + const sNew = Buffer.allocUnsafe(20); + sNew.set(s, 1); + s = sNew; + s[0] = 0; + } + if (r.length > 20 && r[0] === 0) + rOffset = 1; + if (s.length > 20 && s[0] === 0) + sOffset = 1; + const newSig = + Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); + bufferCopy(r, newSig, rOffset, r.length, 0); + bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); + return newSig; + } + case 'ecdsa-sha2-nistp256': + case 'ecdsa-sha2-nistp384': + case 'ecdsa-sha2-nistp521': { + if (signature[0] === 0) + return signature; + // Convert SSH signature parameters to ASN.1 BER values for OpenSSL + const asnReader = new Ber.Reader(signature); + asnReader.readSequence(); + const r = asnReader.readString(Ber.Integer, true); + const s = asnReader.readString(Ber.Integer, true); + if (r === null || s === null) + return; + const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); + writeUInt32BE(newSig, r.length, 0); + newSig.set(r, 4); + writeUInt32BE(newSig, s.length, 4 + r.length); + newSig.set(s, 4 + 4 + r.length); + return newSig; } - - iterator[kError] = err; - return; } - var resolve = iterator[kLastResolve]; + return signature; + }, + sendPacket: (proto, packet, bypass) => { + if (!bypass && proto._kexinit !== undefined) { + // We're currently in the middle of a handshake - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); + if (proto._queue === undefined) + proto._queue = []; + proto._queue.push(packet); + proto._debug && proto._debug('Outbound: ... packet queued'); + return false; } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; + proto._cipher.encrypt(packet); + return true; + }, }; -module.exports = createReadableStreamAsyncIterator; /***/ }), -/***/ 6522: +/***/ 6715: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = __nccwpck_require__(4300), - Buffer = _require.Buffer; - -var _require2 = __nccwpck_require__(3837), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; +const { kMaxLength } = __nccwpck_require__(4300); +const { + createInflate, + constants: { + DEFLATE, + INFLATE, + Z_DEFAULT_CHUNK, + Z_DEFAULT_COMPRESSION, + Z_DEFAULT_MEMLEVEL, + Z_DEFAULT_STRATEGY, + Z_DEFAULT_WINDOWBITS, + Z_PARTIAL_FLUSH, } +} = __nccwpck_require__(9796); +const ZlibHandle = createInflate()._handle.constructor; - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } +function processCallback() { + throw new Error('Should not get here'); +} - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. +function zlibOnError(message, errno, code) { + const self = this._owner; + // There is no way to cleanly recover. + // Continuing only obscures problems. - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; + const error = new Error(message); + error.errno = errno; + error.code = code; + self._err = error; +} - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } +function _close(engine) { + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) + return; - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. + engine._handle.close(); + engine._handle = null; +} - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; +class Zlib { + constructor(mode) { + const windowBits = Z_DEFAULT_WINDOWBITS; + const level = Z_DEFAULT_COMPRESSION; + const memLevel = Z_DEFAULT_MEMLEVEL; + const strategy = Z_DEFAULT_STRATEGY; + const dictionary = undefined; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; + this._err = undefined; + this._writeState = new Uint32Array(2); + this._chunkSize = Z_DEFAULT_CHUNK; + this._maxOutputLength = kMaxLength; + this._outBuffer = Buffer.allocUnsafe(this._chunkSize); + this._outOffset = 0; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } + this._handle = new ZlibHandle(mode); + this._handle._owner = this; + this._handle.onerror = zlibOnError; + this._handle.init(windowBits, + level, + memLevel, + strategy, + this._writeState, + processCallback, + dictionary); + } - break; - } + writeSync(chunk, retChunks) { + const handle = this._handle; + if (!handle) + throw new Error('Invalid Zlib instance'); - ++c; - } + let availInBefore = chunk.length; + let availOutBefore = this._chunkSize - this._outOffset; + let inOff = 0; + let availOutAfter; + let availInAfter; - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. + let buffers; + let nread = 0; + const state = this._writeState; + let buffer = this._outBuffer; + let offset = this._outOffset; + const chunkSize = this._chunkSize; - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; + while (true) { + handle.writeSync(Z_PARTIAL_FLUSH, + chunk, // in + inOff, // in_off + availInBefore, // in_len + buffer, // out + offset, // out_off + availOutBefore); // out_len + if (this._err) + throw this._err; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; + availOutAfter = state[0]; + availInAfter = state[1]; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } + const inDelta = availInBefore - availInAfter; + const have = availOutBefore - availOutAfter; - break; - } + if (have > 0) { + const out = (offset === 0 && have === buffer.length + ? buffer + : buffer.slice(offset, offset + have)); + offset += have; + if (!buffers) + buffers = out; + else if (buffers.push === undefined) + buffers = [buffers, out]; + else + buffers.push(out); + nread += out.byteLength; - ++c; + if (nread > this._maxOutputLength) { + _close(this); + throw new Error( + `Output length exceeded maximum of ${this._maxOutputLength}` + ); + } + } else if (have !== 0) { + throw new Error('have should not go down'); } - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. + // Exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || offset >= chunkSize) { + availOutBefore = chunkSize; + offset = 0; + buffer = Buffer.allocUnsafe(chunkSize); + } - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += inDelta; + availInBefore = availInAfter; + } else { + break; + } } - }]); - - return BufferList; -}(); - -/***/ }), - -/***/ 7049: -/***/ ((module) => { - -"use strict"; - // undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; + this._outBuffer = buffer; + this._outOffset = offset; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; + if (nread === 0) + buffers = Buffer.alloc(0); - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } + if (retChunks) { + buffers.totalLen = nread; + return buffers; } - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks + if (buffers.push === undefined) + return buffers; + const output = Buffer.allocUnsafe(nread); + for (let i = 0, p = 0; i < buffers.length; ++i) { + const buf = buffers[i]; + output.set(buf, p); + p += buf.length; + } + return output; + } +} - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well +class ZlibPacketWriter { + constructor(protocol) { + this.allocStart = 0; + this.allocStartKEX = 0; + this._protocol = protocol; + this._zlib = new Zlib(DEFLATE); + } + cleanup() { + if (this._zlib) + _close(this._zlib); + } - if (this._writableState) { - this._writableState.destroyed = true; + alloc(payloadSize, force) { + return Buffer.allocUnsafe(payloadSize); } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); + finalize(payload, force) { + if (this._protocol._kexinit === undefined || force) { + const output = this._zlib.writeSync(payload, true); + const packet = this._protocol._cipher.allocPacket(output.totalLen); + if (output.push === undefined) { + packet.set(output, 5); } else { - process.nextTick(emitCloseNT, _this); + for (let i = 0, p = 5; i < output.length; ++i) { + const chunk = output[i]; + packet.set(chunk, p); + p += chunk.length; + } } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); + return packet; } - }); - - return this; + return payload; + } } -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} +class PacketWriter { + constructor(protocol) { + this.allocStart = 5; + this.allocStartKEX = 5; + this._protocol = protocol; + } -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} + cleanup() {} -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; + alloc(payloadSize, force) { + if (this._protocol._kexinit === undefined || force) + return this._protocol._cipher.allocPacket(payloadSize); + return Buffer.allocUnsafe(payloadSize); } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; + finalize(packet, force) { + return packet; } } -function emitErrorNT(self, err) { - self.emit('error', err); +class ZlibPacketReader { + constructor() { + this._zlib = new Zlib(INFLATE); + } + + cleanup() { + if (this._zlib) + _close(this._zlib); + } + + read(data) { + return this._zlib.writeSync(data, false); + } } -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +class PacketReader { + cleanup() {} + + read(data) { + return data; + } } module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter, }; + /***/ }), -/***/ 6080: +/***/ 2986: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). - +// TODO: +// * convert listenerCount() usage to emit() return value checking? +// * emit error when connection severed early (e.g. before handshake) +// * add '.connected' or similar property to connection objects to allow +// immediate connection status checking -var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(7214)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; +const { Server: netServer } = __nccwpck_require__(1808); +const EventEmitter = __nccwpck_require__(2361); +const { listenerCount } = EventEmitter; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } +const { + CHANNEL_OPEN_FAILURE, + DEFAULT_CIPHER, + DEFAULT_COMPRESSION, + DEFAULT_KEX, + DEFAULT_MAC, + DEFAULT_SERVER_HOST_KEY, + DISCONNECT_REASON, + DISCONNECT_REASON_BY_VALUE, + SUPPORTED_CIPHER, + SUPPORTED_COMPRESSION, + SUPPORTED_KEX, + SUPPORTED_MAC, + SUPPORTED_SERVER_HOST_KEY, +} = __nccwpck_require__(6832); +const { init: cryptoInit } = __nccwpck_require__(5708); +const { KexInit } = __nccwpck_require__(4126); +const { parseKey } = __nccwpck_require__(2218); +const Protocol = __nccwpck_require__(9031); +const { SFTP } = __nccwpck_require__(2026); +const { writeUInt32BE } = __nccwpck_require__(9475); - callback.apply(this, args); - }; -} +const { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD, +} = __nccwpck_require__(3204); -function noop() {} +const { + ChannelManager, + generateAlgorithmList, + isWritable, + onChannelOpenFailure, + onCHANNEL_CLOSE, +} = __nccwpck_require__(834); -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} +const MAX_PENDING_AUTHS = 10; -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; +class AuthContext extends EventEmitter { + constructor(protocol, username, service, method, cb) { + super(); - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; + this.username = this.user = username; + this.service = service; + this.method = method; + this._initialResponse = false; + this._finalResponse = false; + this._multistep = false; + this._cbfinal = (allowed, methodsLeft, isPartial) => { + if (!this._finalResponse) { + this._finalResponse = true; + cb(this, allowed, methodsLeft, isPartial); + } + }; + this._protocol = protocol; + } - var writableEnded = stream._writableState && stream._writableState.finished; + accept() { + this._cleanup && this._cleanup(); + this._initialResponse = true; + this._cbfinal(true); + } + reject(methodsLeft, isPartial) { + this._cleanup && this._cleanup(); + this._initialResponse = true; + this._cbfinal(false, methodsLeft, isPartial); + } +} - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; +class KeyboardAuthContext extends AuthContext { + constructor(protocol, username, service, method, submethods, cb) { + super(protocol, username, service, method, cb); - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; + this._multistep = true; - var onerror = function onerror(err) { - callback.call(stream, err); - }; + this._cb = undefined; + this._onInfoResponse = (responses) => { + const callback = this._cb; + if (callback) { + this._cb = undefined; + callback(responses); + } + }; + this.submethods = submethods; + this.on('abort', () => { + this._cb && this._cb(new Error('Authentication request aborted')); + }); + } - var onclose = function onclose() { - var err; + prompt(prompts, title, instructions, cb) { + if (!Array.isArray(prompts)) + prompts = [ prompts ]; - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + if (typeof title === 'function') { + cb = title; + title = instructions = undefined; + } else if (typeof instructions === 'function') { + cb = instructions; + instructions = undefined; + } else if (typeof cb !== 'function') { + cb = undefined; } - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + for (let i = 0; i < prompts.length; ++i) { + if (typeof prompts[i] === 'string') { + prompts[i] = { + prompt: prompts[i], + echo: true + }; + } } - }; - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; + this._cb = cb; + this._initialResponse = true; - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); + this._protocol.authInfoReq(title, instructions, prompts); } +} - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; +class PKAuthContext extends AuthContext { + constructor(protocol, username, service, method, pkInfo, cb) { + super(protocol, username, service, method, cb); + + this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; + this.hashAlgo = pkInfo.hashAlgo; + this.signature = pkInfo.signature; + this.blob = pkInfo.blob; + } + + accept() { + if (!this.signature) { + this._initialResponse = true; + this._protocol.authPKOK(this.key.algo, this.key.data); + } else { + AuthContext.prototype.accept.call(this); + } + } } -module.exports = eos; +class HostbasedAuthContext extends AuthContext { + constructor(protocol, username, service, method, pkInfo, cb) { + super(protocol, username, service, method, cb); -/***/ }), + this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; + this.hashAlgo = pkInfo.hashAlgo; + this.signature = pkInfo.signature; + this.blob = pkInfo.blob; + this.localHostname = pkInfo.localHostname; + this.localUsername = pkInfo.localUsername; + } +} -/***/ 9082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +class PwdAuthContext extends AuthContext { + constructor(protocol, username, service, method, password, cb) { + super(protocol, username, service, method, cb); -"use strict"; + this.password = password; + this._changeCb = undefined; + } + requestChange(prompt, cb) { + if (this._changeCb) + throw new Error('Change request already in progress'); + if (typeof prompt !== 'string') + throw new Error('prompt argument must be a string'); + if (typeof cb !== 'function') + throw new Error('Callback argument must be a function'); + this._changeCb = cb; + this._protocol.authPasswdChg(prompt); + } +} -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +class Session extends EventEmitter { + constructor(client, info, localChan) { + super(); -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + this.type = 'session'; + this.subtype = undefined; + this.server = true; + this._ending = false; + this._channel = undefined; + this._chanInfo = { + type: 'session', + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; + } +} -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +class Server extends EventEmitter { + constructor(cfg, listener) { + super(); -var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(7214)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE); + if (typeof cfg !== 'object' || cfg === null) + throw new Error('Missing configuration object'); -function from(Readable, iterable, opts) { - var iterator; + const hostKeys = Object.create(null); + const hostKeyAlgoOrder = []; - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + const hostKeys_ = cfg.hostKeys; + if (!Array.isArray(hostKeys_)) + throw new Error('hostKeys must be an array'); - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); // Reading boolean to protect against _read - // being called before last iteration completion. + const cfgAlgos = ( + typeof cfg.algorithms === 'object' && cfg.algorithms !== null + ? cfg.algorithms + : {} + ); + + const hostKeyAlgos = generateAlgorithmList( + cfgAlgos.serverHostKey, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY + ); + for (let i = 0; i < hostKeys_.length; ++i) { + let privateKey; + if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') + privateKey = parseKey(hostKeys_[i]); + else + privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); - var reading = false; + if (privateKey instanceof Error) + throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - readable._read = function () { - if (!reading) { - reading = true; - next(); - } - }; + if (Array.isArray(privateKey)) { + // OpenSSH's newer format only stores 1 key for now + privateKey = privateKey[0]; + } - function next() { - return _next2.apply(this, arguments); - } + if (privateKey.getPrivatePEM() === null) + throw new Error('privateKey value contains an invalid private key'); - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _ref = yield iterator.next(), - value = _ref.value, - done = _ref.done; + // Discard key if we already found a key of the same type + if (hostKeyAlgoOrder.includes(privateKey.type)) + continue; - if (done) { - readable.push(null); - } else if (readable.push((yield value))) { - next(); - } else { - reading = false; + if (privateKey.type === 'ssh-rsa') { + // SSH supports multiple signature hashing algorithms for RSA, so we add + // the algorithms in the desired order + let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); + const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); + const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); + if (sha1Pos === -1) { + // Fall back to giving SHA1 the lowest priority + sha1Pos = Infinity; } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } + [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { + if (pos === -1) + return; - return readable; -} + let type; + switch (pos) { + case sha1Pos: type = 'ssh-rsa'; break; + case sha256Pos: type = 'rsa-sha2-256'; break; + case sha512Pos: type = 'rsa-sha2-512'; break; + default: return; + } -module.exports = from; + // Store same RSA key under each hash algorithm name for convenience + hostKeys[type] = privateKey; -/***/ }), + hostKeyAlgoOrder.push(type); + }); + } else { + hostKeys[privateKey.type] = privateKey; + hostKeyAlgoOrder.push(privateKey.type); + } + } -/***/ 6989: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const algorithms = { + kex: generateAlgorithmList( + cfgAlgos.kex, + DEFAULT_KEX, + SUPPORTED_KEX + ).concat(['kex-strict-s-v00@openssh.com']), + serverHostKey: hostKeyAlgoOrder, + cs: { + cipher: generateAlgorithmList( + cfgAlgos.cipher, + DEFAULT_CIPHER, + SUPPORTED_CIPHER + ), + mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), + compress: generateAlgorithmList( + cfgAlgos.compress, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION + ), + lang: [], + }, + sc: undefined, + }; + algorithms.sc = algorithms.cs; -"use strict"; -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). + if (typeof listener === 'function') + this.on('connection', listener); + const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); + const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); + const offer = new KexInit(algorithms); -var eos; + this._srv = new netServer((socket) => { + if (this._connections >= this.maxConnections) { + socket.destroy(); + return; + } + ++this._connections; + socket.once('close', () => { + --this._connections; + }); -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} + let debug; + if (origDebug) { + // Prepend debug output with a unique identifier in case there are + // multiple clients connected at the same time + const debugPrefix = `[${process.hrtime().join('.')}] `; + debug = (msg) => { + origDebug(`${debugPrefix}${msg}`); + }; + } -var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + // eslint-disable-next-line no-use-before-define + new Client(socket, hostKeys, ident, offer, debug, this, cfg); + }).on('error', (err) => { + this.emit('error', err); + }).on('listening', () => { + this.emit('listening'); + }).on('close', () => { + this.emit('close'); + }); + this._connections = 0; + this.maxConnections = Infinity; + } -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} + injectSocket(socket) { + this._srv.emit('connection', socket); + } -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} + listen(...args) { + this._srv.listen(...args); + return this; + } -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = __nccwpck_require__(6080); - 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; // request.destroy just do .end - .abort is what we want + address() { + return this._srv.address(); + } - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} + getConnections(cb) { + this._srv.getConnections(cb); + return this; + } -function call(fn) { - fn(); -} + close(cb) { + this._srv.close(cb); + return this; + } -function pipe(from, to) { - return from.pipe(to); -} + ref() { + this._srv.ref(); + return this; + } -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); + unref() { + this._srv.unref(); + return this; + } } +Server.KEEPALIVE_CLIENT_INTERVAL = 15000; +Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; +class Client extends EventEmitter { + constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { + super(); - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } + let exchanges = 0; + let acceptedAuthSvc = false; + let pendingAuths = []; + let authCtx; + let kaTimer; + let onPacket; + const unsentGlobalRequestsReplies = []; + this._sock = socket; + this._chanMgr = new ChannelManager(this); + this._debug = debug; + this.noMoreSessions = false; + this.authenticated = false; - 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); + // Silence pre-header errors + function onClientPreHeaderError(err) {} + this.on('error', onClientPreHeaderError); + + const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { + debug(`Debug output from client: ${JSON.stringify(msg)}`); }); - }); - return streams.reduce(pipe); -} -module.exports = pipeline; + const kaIntvl = ( + typeof srvCfg.keepaliveInterval === 'number' + && isFinite(srvCfg.keepaliveInterval) + && srvCfg.keepaliveInterval > 0 + ? srvCfg.keepaliveInterval + : ( + typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' + && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) + && Server.KEEPALIVE_CLIENT_INTERVAL > 0 + ? Server.KEEPALIVE_CLIENT_INTERVAL + : -1 + ) + ); + const kaCountMax = ( + typeof srvCfg.keepaliveCountMax === 'number' + && isFinite(srvCfg.keepaliveCountMax) + && srvCfg.keepaliveCountMax >= 0 + ? srvCfg.keepaliveCountMax + : ( + typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' + && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) + && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 + ? Server.KEEPALIVE_CLIENT_COUNT_MAX + : -1 + ) + ); + let kaCurCount = 0; + if (kaIntvl !== -1 && kaCountMax !== -1) { + this.once('ready', () => { + const onClose = () => { + clearInterval(kaTimer); + }; + this.on('close', onClose).on('end', onClose); + kaTimer = setInterval(() => { + if (++kaCurCount > kaCountMax) { + clearInterval(kaTimer); + const err = new Error('Keepalive timeout'); + err.level = 'client-timeout'; + this.emit('error', err); + this.end(); + } else { + // XXX: if the server ever starts sending real global requests to + // the client, we will need to add a dummy callback here to + // keep the correct reply order + proto.ping(); + } + }, kaIntvl); + }); + // TODO: re-verify keepalive behavior with OpenSSH + onPacket = () => { + kaTimer && kaTimer.refresh(); + kaCurCount = 0; + }; + } -/***/ }), + const proto = this._protocol = new Protocol({ + server: true, + hostKeys, + ident, + offer, + onPacket, + greeting: srvCfg.greeting, + banner: srvCfg.banner, + onWrite: (data) => { + if (isWritable(socket)) + socket.write(data); + }, + onError: (err) => { + if (!proto._destruct) + socket.removeAllListeners('data'); + this.emit('error', err); + try { + socket.end(); + } catch {} + }, + onHeader: (header) => { + this.removeListener('error', onClientPreHeaderError); -/***/ 9948: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const info = { + ip: socket.remoteAddress, + family: socket.remoteFamily, + port: socket.remotePort, + header, + }; + if (!server.emit('connection', this, info)) { + // auto reject + proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); + socket.end(); + return; + } -"use strict"; + if (header.greeting) + this.emit('greeting', header.greeting); + }, + onHandshakeComplete: (negotiated) => { + if (++exchanges > 1) + this.emit('rekey'); + this.emit('handshake', negotiated); + }, + debug, + messageHandlers: { + DEBUG: DEBUG_HANDLER, + DISCONNECT: (p, reason, desc) => { + if (reason !== DISCONNECT_REASON.BY_APPLICATION) { + if (!desc) { + desc = DISCONNECT_REASON_BY_VALUE[reason]; + if (desc === undefined) + desc = `Unexpected disconnection reason: ${reason}`; + } + const err = new Error(desc); + err.code = reason; + this.emit('error', err); + } + socket.end(); + }, + CHANNEL_OPEN: (p, info) => { + // Handle incoming requests from client + // Do early reject in some cases to prevent wasteful channel + // allocation + if ((info.type === 'session' && this.noMoreSessions) + || !this.authenticated) { + const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + return proto.channelOpenFail(info.sender, reasonCode); + } -var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(7214)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); + let localChan = -1; + let reason; + let replied = false; -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} + let accept; + const reject = () => { + if (replied) + return; + replied = true; -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (reason === undefined) { + if (localChan === -1) + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + else + reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; + } - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } + if (localChan !== -1) + this._chanMgr.remove(localChan); + proto.channelOpenFail(info.sender, reason, ''); + }; + const reserveChannel = () => { + localChan = this._chanMgr.add(); - return Math.floor(hwm); - } // Default value + if (localChan === -1) { + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + if (debug) { + debug('Automatic rejection of incoming channel open: ' + + 'no channels available'); + } + } + return (localChan !== -1); + }; - return state.objectMode ? 16 : 16 * 1024; -} + const data = info.data; + switch (info.type) { + case 'session': + if (listenerCount(this, 'session') && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; -module.exports = { - getHighWaterMark: getHighWaterMark -}; + const instance = new Session(this, info, localChan); + this._chanMgr.update(localChan, instance); -/***/ }), + proto.channelOpenConfirm(info.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE); -/***/ 2387: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return instance; + }; -module.exports = __nccwpck_require__(2781); + this.emit('session', accept, reject); + return; + } + break; + case 'direct-tcpip': + if (listenerCount(this, 'tcpip') && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; + const chanInfo = { + type: undefined, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; -/***/ }), + const stream = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(localChan, stream); -/***/ 1642: -/***/ ((module, exports, __nccwpck_require__) => { + proto.channelOpenConfirm(info.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE); -var Stream = __nccwpck_require__(2781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream.Readable; - Object.assign(module.exports, Stream); - module.exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(1433); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(6993); - exports.Duplex = __nccwpck_require__(1359); - exports.Transform = __nccwpck_require__(4415); - exports.PassThrough = __nccwpck_require__(1542); - exports.finished = __nccwpck_require__(6080); - exports.pipeline = __nccwpck_require__(6989); -} + return stream; + }; + + this.emit('tcpip', accept, reject, data); + return; + } + break; + case 'direct-streamlocal@openssh.com': + if (listenerCount(this, 'openssh.streamlocal') + && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; + const chanInfo = { + type: undefined, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; -/***/ }), + const stream = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(localChan, stream); -/***/ 5118: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + proto.channelOpenConfirm(info.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE); -"use strict"; -/* eslint-disable node/no-deprecated-api */ + return stream; + }; + this.emit('openssh.streamlocal', accept, reject, data); + return; + } + break; + default: + // Automatically reject any unsupported channel open requests + reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; + if (debug) { + debug('Automatic rejection of unsupported incoming channel open' + + ` type: ${info.type}`); + } + } + if (reason === undefined) { + reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + if (debug) { + debug('Automatic rejection of unexpected incoming channel open' + + ` for: ${info.type}`); + } + } -var buffer = __nccwpck_require__(4300) -var Buffer = buffer.Buffer + reject(); + }, + CHANNEL_OPEN_CONFIRMATION: (p, info) => { + const channel = this._chanMgr.get(info.recipient); + if (typeof channel !== 'function') + return; -var safer = {} + const chanInfo = { + type: channel.type, + incoming: { + id: info.recipient, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; -var key + const instance = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(info.recipient, instance); + channel(undefined, instance); + }, + CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'function') + return; -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} + const info = { reason, description }; + onChannelOpenFailure(this, recipient, info, channel); + }, + CHANNEL_DATA: (p, recipient, data) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } -safer.Buffer.prototype = Buffer.prototype + // The remote party should not be sending us data if there is no + // window space available ... + // TODO: raise error on data with not enough window? + if (channel.incoming.window === 0) + return; -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) - } -} + channel.incoming.window -= data.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 (channel.push(data) === false) { + channel._waitChanDrain = true; + return; + } -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 (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { + // NOOP -- should not be sent by client + }, + CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } -module.exports = safer + // The other side is allowing us to send `amount` more bytes of data + channel.outgoing.window += amount; + if (channel._waitWindow) { + channel._waitWindow = false; -/***/ }), + if (channel._chunk) { + channel._write(channel._chunk, null, channel._chunkcb); + } else if (channel._chunkcb) { + channel._chunkcb(); + } else if (channel._chunkErr) { + channel.stderr._write(channel._chunkErr, + null, + channel._chunkcbErr); + } else if (channel._chunkcbErr) { + channel._chunkcbErr(); + } + } + }, + CHANNEL_SUCCESS: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -/***/ 9798: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } -var fs = __nccwpck_require__(7147); + if (channel._callbacks.length) + channel._callbacks.shift()(false); + }, + CHANNEL_FAILURE: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -module.exports = function (filepath, split, encoding) { - split = typeof split !== 'undefined' ? split : "\n"; - encoding = typeof encoding !== 'undefined' ? encoding : "utf8"; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } - var ca = []; - var chain = fs.readFileSync(filepath, encoding); - if(chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0){ - throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); - } - chain = chain.split(split); - var cert = []; - var _i, _len; - for (_i = 0, _len = chain.length; _i < _len; _i++) { - var line = chain[_i]; - if (!(line.length !== 0)) { - continue; - } - cert.push(line); - if (line.match(/-END CERTIFICATE-/)) { - ca.push(cert.join(split)); - cert = []; - } - } - return ca; -} + if (channel._callbacks.length) + channel._callbacks.shift()(true); + }, + CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { + const session = this._chanMgr.get(recipient); + if (typeof session !== 'object' || session === null) + return; + let replied = false; + let accept; + let reject; -/***/ }), + if (session.constructor !== Session) { + // normal Channel instance + if (wantReply) + proto.channelFailure(session.outgoing.id); + return; + } -/***/ 3204: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (wantReply) { + // "real session" requests will have custom accept behaviors + if (type !== 'shell' + && type !== 'exec' + && type !== 'subsystem') { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; -"use strict"; + proto.channelSuccess(session._chanInfo.outgoing.id); + }; + } + reject = () => { + if (replied || session._ending || session._channel) + return; + replied = true; -const { - Duplex: DuplexStream, - Readable: ReadableStream, - Writable: WritableStream, -} = __nccwpck_require__(2781); + proto.channelFailure(session._chanInfo.outgoing.id); + }; + } -const { - CHANNEL_EXTENDED_DATATYPE: { STDERR }, -} = __nccwpck_require__(6832); -const { bufferSlice } = __nccwpck_require__(9475); + if (session._ending) { + reject && reject(); + return; + } -const PACKET_SIZE = 32 * 1024; -const MAX_WINDOW = 2 * 1024 * 1024; -const WINDOW_THRESHOLD = MAX_WINDOW / 2; + switch (type) { + // "pre-real session start" requests + case 'env': + if (listenerCount(session, 'env')) { + session.emit('env', accept, reject, { + key: data.name, + val: data.value + }); + return; + } + break; + case 'pty-req': + if (listenerCount(session, 'pty')) { + session.emit('pty', accept, reject, data); + return; + } + break; + case 'window-change': + if (listenerCount(session, 'window-change')) + session.emit('window-change', accept, reject, data); + else + reject && reject(); + break; + case 'x11-req': + if (listenerCount(session, 'x11')) { + session.emit('x11', accept, reject, data); + return; + } + break; + // "post-real session start" requests + case 'signal': + if (listenerCount(session, 'signal')) { + session.emit('signal', accept, reject, { + name: data + }); + return; + } + break; + // XXX: is `auth-agent-req@openssh.com` really "post-real session + // start"? + case 'auth-agent-req@openssh.com': + if (listenerCount(session, 'auth-agent')) { + session.emit('auth-agent', accept, reject); + return; + } + break; + // "real session start" requests + case 'shell': + if (listenerCount(session, 'shell')) { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; -class ClientStderr extends ReadableStream { - constructor(channel, streamOpts) { - super(streamOpts); + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); - this._channel = channel; - } - _read(n) { - if (this._channel._waitChanDrain) { - this._channel._waitChanDrain = false; - if (this._channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this._channel); - } - } -} + const channel = new Channel( + this, session._chanInfo, { server: true } + ); -class ServerStderr extends WritableStream { - constructor(channel) { - super({ highWaterMark: MAX_WINDOW }); + channel.subtype = session.subtype = type; + session._channel = channel; - this._channel = channel; - } + return channel; + }; - _write(data, encoding, cb) { - const channel = this._channel; - const protocol = channel._client._protocol; - const outgoing = channel.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; + session.emit('shell', accept, reject); + return; + } + break; + case 'exec': + if (listenerCount(session, 'exec')) { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; - if (outgoing.state !== 'open') - return; + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; + const channel = new Channel( + this, session._chanInfo, { server: true } + ); - if (p === 0 && sliceLen === len) - protocol.channelExtData(id, data, STDERR); - else - protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); + channel.subtype = session.subtype = type; + session._channel = channel; - p += sliceLen; - window -= sliceLen; - } + return channel; + }; - outgoing.window = window; + session.emit('exec', accept, reject, { + command: data + }); + return; + } + break; + case 'subsystem': { + let useSFTP = (data === 'sftp'); + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; - if (len - p > 0) { - if (window === 0) - channel._waitWindow = true; - if (p > 0) - channel._chunkErr = bufferSlice(data, p, len); - else - channel._chunkErr = data; - channel._chunkcbErr = cb; - return; - } + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); - cb(); - } -} + let instance; + if (useSFTP) { + instance = new SFTP(this, session._chanInfo, { + server: true, + debug, + }); + } else { + instance = new Channel( + this, session._chanInfo, { server: true } + ); + instance.subtype = + session.subtype = `${type}:${data}`; + } + session._channel = instance; -class Channel extends DuplexStream { - constructor(client, info, opts) { - const streamOpts = { - highWaterMark: MAX_WINDOW, - allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), - emitClose: false, - }; - super(streamOpts); - this.allowHalfOpen = streamOpts.allowHalfOpen; + return instance; + }; - const server = !!(opts && opts.server); + if (data === 'sftp') { + if (listenerCount(session, 'sftp')) { + session.emit('sftp', accept, reject); + return; + } + useSFTP = false; + } + if (listenerCount(session, 'subsystem')) { + session.emit('subsystem', accept, reject, { + name: data + }); + return; + } + break; + } + } + debug && debug( + `Automatic rejection of incoming channel request: ${type}` + ); + reject && reject(); + }, + CHANNEL_EOF: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + + if (channel.constructor === Session) { + if (!channel._ending) { + channel._ending = true; + channel.emit('eof'); + channel.emit('end'); + } + channel = channel._channel; + if (!channel) + return; + } - this.server = server; - this.type = info.type; - this.subtype = undefined; + if (channel.incoming.state !== 'open') + return; + channel.incoming.state = 'eof'; - /* - incoming and outgoing contain these properties: - { - id: undefined, - window: undefined, - packetSize: undefined, - state: 'closed' - } - */ - this.incoming = info.incoming; - this.outgoing = info.outgoing; - this._callbacks = []; + if (channel.readable) + channel.push(null); + }, + CHANNEL_CLOSE: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; - this._client = client; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; + if (channel.constructor === Session) { + channel._ending = true; + channel.emit('close'); + channel = channel._channel; + if (!channel) + return; + } - this.stdin = this.stdout = this; + onCHANNEL_CLOSE(this, recipient, channel); + }, + // Begin service/auth-related ========================================== + SERVICE_REQUEST: (p, service) => { + if (exchanges === 0 + || acceptedAuthSvc + || this.authenticated + || service !== 'ssh-userauth') { + proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); + socket.end(); + return; + } - if (server) - this.stderr = new ServerStderr(this); - else - this.stderr = new ClientStderr(this, streamOpts); + acceptedAuthSvc = true; + proto.serviceAccept(service); + }, + USERAUTH_REQUEST: (p, username, service, method, methodData) => { + if (exchanges === 0 + || this.authenticated + || (authCtx + && (authCtx.username !== username + || authCtx.service !== service)) + // TODO: support hostbased auth + || (method !== 'password' + && method !== 'publickey' + && method !== 'hostbased' + && method !== 'keyboard-interactive' + && method !== 'none') + || pendingAuths.length === MAX_PENDING_AUTHS) { + proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); + socket.end(); + return; + } else if (service !== 'ssh-connection') { + proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); + socket.end(); + return; + } - // Outgoing data - this._waitWindow = false; // SSH-level backpressure + let ctx; + switch (method) { + case 'keyboard-interactive': + ctx = new KeyboardAuthContext(proto, username, service, method, + methodData, onAuthDecide); + break; + case 'publickey': + ctx = new PKAuthContext(proto, username, service, method, + methodData, onAuthDecide); + break; + case 'hostbased': + ctx = new HostbasedAuthContext(proto, username, service, method, + methodData, onAuthDecide); + break; + case 'password': + if (authCtx + && authCtx instanceof PwdAuthContext + && authCtx._changeCb) { + const cb = authCtx._changeCb; + authCtx._changeCb = undefined; + cb(methodData.newPassword); + return; + } + ctx = new PwdAuthContext(proto, username, service, method, + methodData, onAuthDecide); + break; + case 'none': + ctx = new AuthContext(proto, username, service, method, + onAuthDecide); + break; + } - // Incoming data - this._waitChanDrain = false; // Channel Readable side backpressure + if (authCtx) { + if (!authCtx._initialResponse) { + return pendingAuths.push(ctx); + } else if (authCtx._multistep && !authCtx._finalResponse) { + // RFC 4252 says to silently abort the current auth request if a + // new auth request comes in before the final response from an + // auth method that requires additional request/response exchanges + // -- this means keyboard-interactive for now ... + authCtx._cleanup && authCtx._cleanup(); + authCtx.emit('abort'); + } + } - this._chunk = undefined; - this._chunkcb = undefined; - this._chunkErr = undefined; - this._chunkcbErr = undefined; + authCtx = ctx; - this.on('finish', onFinish) - .on('prefinish', onFinish); // For node v0.11+ + if (listenerCount(this, 'authentication')) + this.emit('authentication', authCtx); + else + authCtx.reject(); + }, + USERAUTH_INFO_RESPONSE: (p, responses) => { + if (authCtx && authCtx instanceof KeyboardAuthContext) + authCtx._onInfoResponse(responses); + }, + // End service/auth-related ============================================ + GLOBAL_REQUEST: (p, name, wantReply, data) => { + const reply = { + type: null, + buf: null + }; - this.on('end', onEnd).on('close', onEnd); - } + function setReply(type, buf) { + reply.type = type; + reply.buf = buf; + sendReplies(); + } - _read(n) { - if (this._waitChanDrain) { - this._waitChanDrain = false; - if (this.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this); - } - } + if (wantReply) + unsentGlobalRequestsReplies.push(reply); - _write(data, encoding, cb) { - const protocol = this._client._protocol; - const outgoing = this.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; + if ((name === 'tcpip-forward' + || name === 'cancel-tcpip-forward' + || name === 'no-more-sessions@openssh.com' + || name === 'streamlocal-forward@openssh.com' + || name === 'cancel-streamlocal-forward@openssh.com') + && listenerCount(this, 'request') + && this.authenticated) { + let accept; + let reject; - if (outgoing.state !== 'open') - return; + if (wantReply) { + let replied = false; + accept = (chosenPort) => { + if (replied) + return; + replied = true; + let bufPort; + if (name === 'tcpip-forward' + && data.bindPort === 0 + && typeof chosenPort === 'number') { + bufPort = Buffer.allocUnsafe(4); + writeUInt32BE(bufPort, chosenPort, 0); + } + setReply('SUCCESS', bufPort); + }; + reject = () => { + if (replied) + return; + replied = true; + setReply('FAILURE'); + }; + } - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; + if (name === 'no-more-sessions@openssh.com') { + this.noMoreSessions = true; + accept && accept(); + return; + } - if (p === 0 && sliceLen === len) - protocol.channelData(id, data); - else - protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); + this.emit('request', accept, reject, name, data); + } else if (wantReply) { + setReply('FAILURE'); + } + }, + }, + }); - p += sliceLen; - window -= sliceLen; - } + socket.pause(); + cryptoInit.then(() => { + proto.start(); + socket.on('data', (data) => { + try { + proto.parse(data, 0, data.length); + } catch (ex) { + this.emit('error', ex); + try { + if (isWritable(socket)) + socket.end(); + } catch {} + } + }); + socket.resume(); + }).catch((err) => { + this.emit('error', err); + try { + if (isWritable(socket)) + socket.end(); + } catch {} + }); + socket.on('error', (err) => { + err.level = 'socket'; + this.emit('error', err); + }).once('end', () => { + debug && debug('Socket ended'); + proto.cleanup(); + this.emit('end'); + }).once('close', () => { + debug && debug('Socket closed'); + proto.cleanup(); + this.emit('close'); - outgoing.window = window; + const err = new Error('No response from server'); - if (len - p > 0) { - if (window === 0) - this._waitWindow = true; - if (p > 0) - this._chunk = bufferSlice(data, p, len); - else - this._chunk = data; - this._chunkcb = cb; - return; - } + // Simulate error for pending channels and close any open channels + this._chanMgr.cleanup(err); + }); - cb(); - } + const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { + if (authCtx === ctx && !this.authenticated) { + if (allowed) { + authCtx = undefined; + this.authenticated = true; + proto.authSuccess(); + pendingAuths = []; + this.emit('ready'); + } else { + proto.authFailure(methodsLeft, isPartial); + if (pendingAuths.length) { + authCtx = pendingAuths.pop(); + if (listenerCount(this, 'authentication')) + this.emit('authentication', authCtx); + else + authCtx.reject(); + } + } + } + }; - eof() { - if (this.outgoing.state === 'open') { - this.outgoing.state = 'eof'; - this._client._protocol.channelEOF(this.outgoing.id); + function sendReplies() { + while (unsentGlobalRequestsReplies.length > 0 + && unsentGlobalRequestsReplies[0].type) { + const reply = unsentGlobalRequestsReplies.shift(); + if (reply.type === 'SUCCESS') + proto.requestSuccess(reply.buf); + if (reply.type === 'FAILURE') + proto.requestFailure(); + } } } - close() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._client._protocol.channelClose(this.outgoing.id); + end() { + if (this._sock && isWritable(this._sock)) { + this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); + this._sock.end(); } + return this; } - destroy() { - this.end(); - this.close(); + x11(originAddr, originPort, cb) { + const opts = { originAddr, originPort }; + openChannel(this, 'x11', opts, cb); return this; } - // Session type-specific methods ============================================= - setWindow(rows, cols, height, width) { - if (this.server) - throw new Error('Client-only method called in server mode'); + forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { + const opts = { boundAddr, boundPort, remoteAddr, remotePort }; + openChannel(this, 'forwarded-tcpip', opts, cb); + return this; + } - if (this.type === 'session' - && (this.subtype === 'shell' || this.subtype === 'exec') - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.windowChange(this.outgoing.id, - rows, - cols, - height, - width); - } + openssh_forwardOutStreamLocal(socketPath, cb) { + const opts = { socketPath }; + openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); + return this; } - signal(signalName) { - if (this.server) - throw new Error('Client-only method called in server mode'); + rekey(cb) { + let error; - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.signal(this.outgoing.id, signalName); + try { + this._protocol.rekey(); + } catch (ex) { + error = ex; } - } - exit(statusOrSignal, coreDumped, msg) { - if (!this.server) - throw new Error('Server-only method called in client mode'); + // TODO: re-throw error if no callback? - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - if (typeof statusOrSignal === 'number') { - this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); - } else { - this._client._protocol.exitSignal(this.outgoing.id, - statusOrSignal, - coreDumped, - msg); - } + if (typeof cb === 'function') { + if (error) + process.nextTick(cb, error); + else + this.once('rekey', cb); } } -} - -function onFinish() { - this.eof(); - if (this.server || !this.allowHalfOpen) - this.close(); - this.writable = false; -} - -function onEnd() { - this.readable = false; -} + setNoDelay(noDelay) { + if (this._sock && typeof this._sock.setNoDelay === 'function') + this._sock.setNoDelay(noDelay); -function windowAdjust(self) { - if (self.outgoing.state === 'closed') - return; - const amt = MAX_WINDOW - self.incoming.window; - if (amt <= 0) - return; - self.incoming.window += amt; - self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); + return this; + } } -module.exports = { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -}; - - -/***/ }), - -/***/ 9054: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { Socket } = __nccwpck_require__(1808); -const { Duplex } = __nccwpck_require__(2781); -const { resolve } = __nccwpck_require__(1017); -const { readFile } = __nccwpck_require__(7147); -const { execFile, spawn } = __nccwpck_require__(2081); -const { isParsedKey, parseKey } = __nccwpck_require__(2218); +function openChannel(self, type, opts, cb) { + // Ask the client to open a channel for some purpose (e.g. a forwarded TCP + // connection) + const initWindow = MAX_WINDOW; + const maxPacket = PACKET_SIZE; -const { - makeBufferParser, - readUInt32BE, - writeUInt32BE, - writeUInt32LE, -} = __nccwpck_require__(9475); + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } -function once(cb) { - let called = false; - return (...args) => { - if (called) - return; - called = true; - cb(...args); + const wrapper = (err, stream) => { + cb(err, stream); }; -} - -function concat(buf1, buf2) { - const combined = Buffer.allocUnsafe(buf1.length + buf2.length); - buf1.copy(combined, 0); - buf2.copy(combined, buf1.length); - return combined; -} - -function noop() {} - -const EMPTY_BUF = Buffer.alloc(0); - -const binaryParser = makeBufferParser(); + wrapper.type = type; -class BaseAgent { - getIdentities(cb) { - cb(new Error('Missing getIdentities() implementation')); - } - sign(pubKey, data, options, cb) { - if (typeof options === 'function') - cb = options; - cb(new Error('Missing sign() implementation')); - } -} + const localChan = self._chanMgr.add(wrapper); -class OpenSSHAgent extends BaseAgent { - constructor(socketPath) { - super(); - this.socketPath = socketPath; + if (localChan === -1) { + cb(new Error('No free channels available')); + return; } - getStream(cb) { - cb = once(cb); - const sock = new Socket(); - sock.on('connect', () => { - cb(null, sock); - }); - sock.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - sock.connect(this.socketPath); - - function onFail() { - try { - sock.destroy(); - } catch {} - - cb(new Error('Failed to connect to agent')); - } + switch (type) { + case 'forwarded-tcpip': + self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); + break; + case 'x11': + self._protocol.x11(localChan, initWindow, maxPacket, opts); + break; + case 'forwarded-streamlocal@openssh.com': + self._protocol.openssh_forwardedStreamLocal( + localChan, initWindow, maxPacket, opts + ); + break; + default: + throw new Error(`Unsupported channel type: ${type}`); } +} - getIdentities(cb) { - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to retrieve identities from agent'); - cb(err); - } +function compareNumbers(a, b) { + return a - b; +} - if (err) - return onFail(err); +module.exports = Server; +module.exports.IncomingClient = Client; - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); +/***/ }), - protocol.getIdentities((err, keys) => { - if (err) - return onFail(err); - try { - stream.destroy(); - } catch {} - cb(null, keys); - }); - }); - } +/***/ 834: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - sign(pubKey, data, options, cb) { - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } +"use strict"; - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to sign data with agent'); - cb(err); - } - if (err) - return onFail(err); +const { SFTP } = __nccwpck_require__(2026); - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); +const MAX_CHANNEL = 2 ** 32 - 1; - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); +function onChannelOpenFailure(self, recipient, info, cb) { + self._chanMgr.remove(recipient); + if (typeof cb !== 'function') + return; - protocol.sign(pubKey, data, options, (err, sig) => { - if (err) - return onFail(err); + let err; + if (info instanceof Error) { + err = info; + } else if (typeof info === 'object' && info !== null) { + err = new Error(`(SSH) Channel open failure: ${info.description}`); + err.reason = info.reason; + } else { + err = new Error( + '(SSH) Channel open failure: server closed channel unexpectedly' + ); + err.reason = ''; + } - try { - stream.destroy(); - } catch {} + cb(err); +} - cb(null, sig); - }); - }); +function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { + if (typeof channel === 'function') { + // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when + // requesting to open a channel + onChannelOpenFailure(self, recipient, err, channel); + return; } -} -const PageantAgent = (() => { - const RET_ERR_BADARGS = 10; - const RET_ERR_UNAVAILABLE = 11; - const RET_ERR_NOMAP = 12; - const RET_ERR_BINSTDIN = 13; - const RET_ERR_BINSTDOUT = 14; - const RET_ERR_BADLEN = 15; + if (typeof channel !== 'object' || channel === null) + return; - const EXEPATH = __nccwpck_require__.ab + "pagent.exe"; - const ERROR = { - [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), - [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), - [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), - [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), - [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), - [RET_ERR_BADLEN]: - new Error('pagent.exe did not get expected input payload'), - }; + if (channel.incoming && channel.incoming.state === 'closed') + return; - function destroy(stream) { - stream.buffer = null; - if (stream.proc) { - stream.proc.kill(); - stream.proc = undefined; - } + self._chanMgr.remove(recipient); + + if (channel.server && channel.constructor.name === 'Session') + return; + + channel.incoming.state = 'closed'; + + if (channel.readable) + channel.push(null); + if (channel.server) { + if (channel.stderr.writable) + channel.stderr.end(); + } else if (channel.stderr.readable) { + channel.stderr.push(null); } - class PageantSocket extends Duplex { - constructor() { - super(); - this.proc = undefined; - this.buffer = null; - } - _read(n) {} - _write(data, encoding, cb) { - if (this.buffer === null) { - this.buffer = data; - } else { - const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); - this.buffer.copy(newBuffer, 0); - data.copy(newBuffer, this.buffer.length); - this.buffer = newBuffer; - } - // Wait for at least all length bytes - if (this.buffer.length < 4) - return cb(); + if (channel.constructor !== SFTP + && (channel.outgoing.state === 'open' + || channel.outgoing.state === 'eof') + && !dead) { + channel.close(); + } + if (channel.outgoing.state === 'closing') + channel.outgoing.state = 'closed'; - const len = readUInt32BE(this.buffer, 0); - // Make sure we have a full message before querying pageant - if ((this.buffer.length - 4) < len) - return cb(); + const readState = channel._readableState; + const writeState = channel._writableState; + if (writeState && !writeState.ending && !writeState.finished && !dead) + channel.end(); - data = this.buffer.slice(0, 4 + len); - if (this.buffer.length > (4 + len)) - return cb(new Error('Unexpected multiple agent requests')); - this.buffer = null; + // Take care of any outstanding channel requests + const chanCallbacks = channel._callbacks; + channel._callbacks = []; + for (let i = 0; i < chanCallbacks.length; ++i) + chanCallbacks[i](true); - let error; - const proc = this.proc = spawn(__nccwpck_require__.ab + "pagent.exe", [ data.length ]); - proc.stdout.on('data', (data) => { - this.push(data); - }); - proc.on('error', (err) => { - error = err; - cb(error); - }); - proc.on('close', (code) => { - this.proc = undefined; - if (!error) { - if (error = ERROR[code]) - return cb(error); - cb(); - } - }); - proc.stdin.end(data); + if (channel.server) { + if (!channel.readable + || channel.destroyed + || (readState && readState.endEmitted)) { + channel.emit('close'); + } else { + channel.once('end', () => channel.emit('close')); } - _final(cb) { - destroy(this); - cb(); + } else { + let doClose; + switch (channel.type) { + case 'direct-streamlocal@openssh.com': + case 'direct-tcpip': + doClose = () => channel.emit('close'); + break; + default: { + // Align more with node child processes, where the close event gets + // the same arguments as the exit event + const exit = channel._exit; + doClose = () => { + if (exit.code === null) + channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); + else + channel.emit('close', exit.code); + }; + } } - _destroy(err, cb) { - destroy(this); - cb(); + if (!channel.readable + || channel.destroyed + || (readState && readState.endEmitted)) { + doClose(); + } else { + channel.once('end', doClose); } - } - return class PageantAgent extends OpenSSHAgent { - getStream(cb) { - cb(null, new PageantSocket()); + const errReadState = channel.stderr._readableState; + if (!channel.stderr.readable + || channel.stderr.destroyed + || (errReadState && errReadState.endEmitted)) { + channel.stderr.emit('close'); + } else { + channel.stderr.once('end', () => channel.stderr.emit('close')); } - }; -})(); - -const CygwinAgent = (() => { - const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; - - return class CygwinAgent extends OpenSSHAgent { - getStream(cb) { - cb = once(cb); - - // The cygwin ssh-agent connection process looks like this: - // 1. Read the "socket" as a file to get the underlying TCP port and a - // special "secret" that must be sent to the TCP server. - // 2. Connect to the server listening on localhost at the TCP port. - // 3. Send the "secret" to the server. - // 4. The server sends back the same "secret". - // 5. Send three 32-bit integer values of zero. This is ordinarily the - // pid, uid, and gid of this process, but cygwin will actually - // send us the correct values as a response. - // 6. The server sends back the pid, uid, gid. - // 7. Disconnect. - // 8. Repeat steps 2-6, except send the received pid, uid, and gid in - // step 5 instead of zeroes. - // 9. Connection is ready to be used. + } +} - let socketPath = this.socketPath; - let triedCygpath = false; - readFile(socketPath, function readCygsocket(err, data) { - if (err) { - if (triedCygpath) - return cb(new Error('Invalid cygwin unix socket path')); +class ChannelManager { + constructor(client) { + this._client = client; + this._channels = {}; + this._cur = -1; + this._count = 0; + } + add(val) { + // Attempt to reserve an id - // Try using `cygpath` to convert a possible *nix-style path to the - // real Windows path before giving up ... - execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { - if (err || stdout.length === 0) - return cb(new Error('Invalid cygwin unix socket path')); + let id; + // Optimized paths + if (this._cur < MAX_CHANNEL) { + id = ++this._cur; + } else if (this._count === 0) { + // Revert and reset back to fast path once we no longer have any channels + // open + this._cur = 0; + id = 0; + } else { + // Slower lookup path - triedCygpath = true; - socketPath = stdout.toString().replace(/[\r\n]/g, ''); - readFile(socketPath, readCygsocket); - }); - return; + // This path is triggered we have opened at least MAX_CHANNEL channels + // while having at least one channel open at any given time, so we have + // to search for a free id. + const channels = this._channels; + for (let i = 0; i < MAX_CHANNEL; ++i) { + if (channels[i] === undefined) { + id = i; + break; } + } + } - const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); - if (!m) - return cb(new Error('Malformed cygwin unix socket file')); + if (id === undefined) + return -1; - let state; - let bc = 0; - let isRetrying = false; - const inBuf = []; - let sock; + this._channels[id] = (val || true); + ++this._count; - // Use 0 for pid, uid, and gid to ensure we get an error and also - // a valid uid and gid from cygwin so that we don't have to figure it - // out ourselves - let credsBuf = Buffer.alloc(12); + return id; + } + update(id, val) { + if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); - // Parse cygwin unix socket file contents - const port = parseInt(m[1], 10); - const secret = m[2].replace(/-/g, ''); - const secretBuf = Buffer.allocUnsafe(16); - for (let i = 0, j = 0; j < 32; ++i, j += 2) - secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); + if (val && this._channels[id]) + this._channels[id] = val; + } + get(id) { + if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); - // Convert to host order (always LE for Windows) - for (let i = 0; i < 16; i += 4) - writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); + return this._channels[id]; + } + remove(id) { + if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); - tryConnect(); + if (this._channels[id]) { + delete this._channels[id]; + if (this._count) + --this._count; + } + } + cleanup(err) { + const channels = this._channels; + this._channels = {}; + this._cur = -1; + this._count = 0; - function _onconnect() { - bc = 0; - state = 'secret'; - sock.write(secretBuf); - } + const chanIDs = Object.keys(channels); + const client = this._client; + for (let i = 0; i < chanIDs.length; ++i) { + const id = +chanIDs[i]; + const channel = channels[id]; + onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); + } + } +} - function _ondata(data) { - bc += data.length; +const isRegExp = (() => { + const toString = Object.prototype.toString; + return (val) => toString.call(val) === '[object RegExp]'; +})(); - if (state === 'secret') { - // The secret we sent is echoed back to us by cygwin, not sure of - // the reason for that, but we ignore it nonetheless ... - if (bc === 16) { - bc = 0; - state = 'creds'; - sock.write(credsBuf); +function generateAlgorithmList(algoList, defaultList, supportedList) { + if (Array.isArray(algoList) && algoList.length > 0) { + // Exact list + for (let i = 0; i < algoList.length; ++i) { + if (supportedList.indexOf(algoList[i]) === -1) + throw new Error(`Unsupported algorithm: ${algoList[i]}`); + } + return algoList; + } + + if (typeof algoList === 'object' && algoList !== null) { + // Operations based on the default list + const keys = Object.keys(algoList); + let list = defaultList; + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + let val = algoList[key]; + switch (key) { + case 'append': + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = 0; j < val.length; ++j) { + const append = val[j]; + if (typeof append === 'string') { + if (!append || list.indexOf(append) !== -1) + continue; + if (supportedList.indexOf(append) === -1) + throw new Error(`Unsupported algorithm: ${append}`); + if (list === defaultList) + list = list.slice(); + list.push(append); + } else if (isRegExp(append)) { + for (let k = 0; k < supportedList.length; ++k) { + const algo = supportedList[k]; + if (append.test(algo)) { + if (list.indexOf(algo) !== -1) + continue; + if (list === defaultList) + list = list.slice(); + list.push(algo); + } + } + } + } + } + break; + case 'prepend': + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = val.length; j >= 0; --j) { + const prepend = val[j]; + if (typeof prepend === 'string') { + if (!prepend || list.indexOf(prepend) !== -1) + continue; + if (supportedList.indexOf(prepend) === -1) + throw new Error(`Unsupported algorithm: ${prepend}`); + if (list === defaultList) + list = list.slice(); + list.unshift(prepend); + } else if (isRegExp(prepend)) { + for (let k = supportedList.length; k >= 0; --k) { + const algo = supportedList[k]; + if (prepend.test(algo)) { + if (list.indexOf(algo) !== -1) + continue; + if (list === defaultList) + list = list.slice(); + list.unshift(algo); + } + } + } + } + } + break; + case 'remove': + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = 0; j < val.length; ++j) { + const search = val[j]; + if (typeof search === 'string') { + if (!search) + continue; + const idx = list.indexOf(search); + if (idx === -1) + continue; + if (list === defaultList) + list = list.slice(); + list.splice(idx, 1); + } else if (isRegExp(search)) { + for (let k = 0; k < list.length; ++k) { + if (search.test(list[k])) { + if (list === defaultList) + list = list.slice(); + list.splice(k, 1); + --k; + } + } + } } - return; } + break; + } + } - if (state === 'creds') { - // If this is the first attempt, make sure to gather the valid - // uid and gid for our next attempt - if (!isRetrying) - inBuf.push(data); - - if (bc === 12) { - sock.removeListener('connect', _onconnect); - sock.removeListener('data', _ondata); - sock.removeListener('error', onFail); - sock.removeListener('end', onFail); - sock.removeListener('close', onFail); - - if (isRetrying) - return cb(null, sock); + return list; + } - isRetrying = true; - credsBuf = Buffer.concat(inBuf); - writeUInt32LE(credsBuf, process.pid, 0); - sock.on('error', () => {}); - sock.destroy(); + return defaultList; +} - tryConnect(); - } - } - } +module.exports = { + ChannelManager, + generateAlgorithmList, + onChannelOpenFailure, + onCHANNEL_CLOSE, + isWritable: (stream) => { + // XXX: hack to workaround regression in node + // See: https://github.com/nodejs/node/issues/36029 + return (stream + && stream.writable + && stream._readableState + && stream._readableState.ended === false); + }, +}; - function onFail() { - cb(new Error('Problem negotiating cygwin unix socket security')); - } - function tryConnect() { - sock = new Socket(); - sock.on('connect', _onconnect); - sock.on('data', _ondata); - sock.on('error', onFail); - sock.on('end', onFail); - sock.on('close', onFail); - sock.connect(port); - } - }); - } - }; -})(); +/***/ }), -// Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes -// being interchangeable -const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; -function createAgent(path) { - if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { - return (path === 'pageant' - ? new PageantAgent() - : new CygwinAgent(path)); - } - return new OpenSSHAgent(path); -} +/***/ 4841: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const AgentProtocol = (() => { - // Client->Server messages - const SSH_AGENTC_REQUEST_IDENTITIES = 11; - const SSH_AGENTC_SIGN_REQUEST = 13; - // const SSH_AGENTC_ADD_IDENTITY = 17; - // const SSH_AGENTC_REMOVE_IDENTITY = 18; - // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; - // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; - // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; - // const SSH_AGENTC_LOCK = 22; - // const SSH_AGENTC_UNLOCK = 23; - // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; - // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; - // const SSH_AGENTC_EXTENSION = 27; - // Server->Client messages - const SSH_AGENT_FAILURE = 5; - // const SSH_AGENT_SUCCESS = 6; - const SSH_AGENT_IDENTITIES_ANSWER = 12; - const SSH_AGENT_SIGN_RESPONSE = 14; - // const SSH_AGENT_EXTENSION_FAILURE = 28; +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. - // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; - // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; - // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; - const SSH_AGENT_RSA_SHA2_256 = (1 << 1); - const SSH_AGENT_RSA_SHA2_512 = (1 << 2); - const ROLE_CLIENT = 0; - const ROLE_SERVER = 1; +/**/ - // Ensures that responses get sent back in the same order the requests were - // received - function processResponses(protocol) { - let ret; - while (protocol[SYM_REQS].length) { - const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; - if (nextResponse === undefined) - break; +var Buffer = (__nccwpck_require__(2279).Buffer); +/**/ - protocol[SYM_REQS].shift(); - ret = protocol.push(nextResponse); - } - return ret; +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; } +}; - const SYM_TYPE = Symbol('Inbound Request Type'); - const SYM_RESP = Symbol('Inbound Request Response'); - const SYM_CTX = Symbol('Inbound Request Context'); - class AgentInboundRequest { - constructor(type, ctx) { - this[SYM_TYPE] = type; - this[SYM_RESP] = undefined; - this[SYM_CTX] = ctx; - } - hasResponded() { - return (this[SYM_RESP] !== undefined); - } - getType() { - return this[SYM_TYPE]; - } - getContext() { - return this[SYM_CTX]; +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; } } - function respond(protocol, req, data) { - req[SYM_RESP] = data; - return processResponses(protocol); - } +}; - function cleanup(protocol) { - protocol[SYM_BUFFER] = null; - if (protocol[SYM_MODE] === ROLE_CLIENT) { - const reqs = protocol[SYM_REQS]; - if (reqs && reqs.length) { - protocol[SYM_REQS] = []; - for (const req of reqs) - req.cb(new Error('No reply from server')); - } - } +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} - // Node streams hackery to make streams do the "right thing" - try { - protocol.end(); - } catch {} - setImmediate(() => { - if (!protocol[SYM_ENDED]) - protocol.emit('end'); - if (!protocol[SYM_CLOSED]) - protocol.emit('close'); - }); +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} - function onClose() { - this[SYM_CLOSED] = true; +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; - function onEnd() { - this[SYM_ENDED] = true; - } +StringDecoder.prototype.end = utf8End; - const SYM_REQS = Symbol('Requests'); - const SYM_MODE = Symbol('Agent Protocol Role'); - const SYM_BUFFER = Symbol('Agent Protocol Buffer'); - const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); - const SYM_CLOSED = Symbol('Agent Protocol Closed'); - const SYM_ENDED = Symbol('Agent Protocol Ended'); - // Implementation based on: - // https://tools.ietf.org/html/draft-miller-ssh-agent-04 - return class AgentProtocol extends Duplex { - /* - Notes: - - `constraint` type consists of: - byte constraint_type - byte[] constraint_data - where `constraint_type` is one of: - * SSH_AGENT_CONSTRAIN_LIFETIME - - `constraint_data` consists of: - uint32 seconds - * SSH_AGENT_CONSTRAIN_CONFIRM - - `constraint_data` N/A - * SSH_AGENT_CONSTRAIN_EXTENSION - - `constraint_data` consists of: - string extension name - byte[] extension-specific details - */ +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; - constructor(isClient) { - super({ autoDestroy: true, emitClose: false }); - this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); - this[SYM_REQS] = []; - this[SYM_BUFFER] = null; - this[SYM_MSGLEN] = -1; - this.once('end', onEnd); - this.once('close', onClose); - } +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; - _read(n) {} +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} - _write(data, encoding, cb) { - /* - Messages are of the format: - uint32 message length - byte message type - byte[message length - 1] message contents - */ - if (this[SYM_BUFFER] === null) - this[SYM_BUFFER] = data; - else - this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} - let buffer = this[SYM_BUFFER]; - let bufferLen = buffer.length; +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} - let p = 0; - while (p < bufferLen) { - // Wait for length + type - if (bufferLen < 5) - break; +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} - if (this[SYM_MSGLEN] === -1) - this[SYM_MSGLEN] = readUInt32BE(buffer, p); +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} - // Check if we have the entire message - if (bufferLen < (4 + this[SYM_MSGLEN])) - break; +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} - const msgType = buffer[p += 4]; - ++p; +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} - if (this[SYM_MODE] === ROLE_CLIENT) { - if (this[SYM_REQS].length === 0) - return cb(new Error('Received unexpected message from server')); +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} - const req = this[SYM_REQS].shift(); +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} - switch (msgType) { - case SSH_AGENT_FAILURE: - req.cb(new Error('Agent responded with failure')); - break; - case SSH_AGENT_IDENTITIES_ANSWER: { - if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) - return cb(new Error('Agent responded with wrong message type')); +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} - where `nkeys` is 0 or more of: - string key blob - string comment - */ +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} - binaryParser.init(buffer, p); +/***/ }), - const numKeys = binaryParser.readUInt32BE(); +/***/ 2279: +/***/ ((module, exports, __nccwpck_require__) => { - if (numKeys === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(4300) +var Buffer = buffer.Buffer - const keys = []; - for (let i = 0; i < numKeys; ++i) { - let pubKey = binaryParser.readString(); - if (pubKey === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } +// 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 +} - const comment = binaryParser.readString(true); - if (comment === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} - pubKey = parseKey(pubKey); - // We continue parsing the packet if we encounter an error - // in case the error is due to the key being an unsupported - // type - if (pubKey instanceof Error) - continue; +SafeBuffer.prototype = Object.create(Buffer.prototype) - pubKey.comment = pubKey.comment || comment; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) - keys.push(pubKey); - } - p = binaryParser.pos(); - binaryParser.clear(); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} - req.cb(null, keys); - break; - } - case SSH_AGENT_SIGN_RESPONSE: { - if (req.type !== SSH_AGENTC_SIGN_REQUEST) - return cb(new Error('Agent responded with wrong message type')); +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 +} - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} - binaryParser.init(buffer, p); - let signature = binaryParser.readString(); - p = binaryParser.pos(); - binaryParser.clear(); +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} - if (signature === undefined) - return cb(new Error('Malformed agent response')); - // We strip the algorithm from OpenSSH's output and assume it's - // using the algorithm we specified. This makes it easier on - // custom Agent implementations so they don't have to construct - // the correct binary format for a (OpenSSH-style) signature. +/***/ }), - // TODO: verify signature type based on key and options used - // during initial sign request - binaryParser.init(signature, 0); - binaryParser.readString(true); - signature = binaryParser.readString(); - binaryParser.clear(); +/***/ 9318: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (signature === undefined) - return cb(new Error('Malformed OpenSSH signature format')); +"use strict"; - req.cb(null, signature); - break; - } - default: - return cb( - new Error('Agent responded with unsupported message type') - ); - } - } else { - switch (msgType) { - case SSH_AGENTC_REQUEST_IDENTITIES: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - this.emit('identities', req); - break; - } - case SSH_AGENTC_SIGN_REQUEST: { - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - binaryParser.init(buffer, p); - let pubKey = binaryParser.readString(); - const data = binaryParser.readString(); - const flagsVal = binaryParser.readUInt32BE(); - p = binaryParser.pos(); - binaryParser.clear(); - if (flagsVal === undefined) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } +const os = __nccwpck_require__(2037); +const tty = __nccwpck_require__(6224); +const hasFlag = __nccwpck_require__(1621); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } +const {env} = process; - const flags = { - hash: undefined, - }; - let ctx; - if (pubKey.type === 'ssh-rsa') { - if (flagsVal & SSH_AGENT_RSA_SHA2_256) { - ctx = 'rsa-sha2-256'; - flags.hash = 'sha256'; - } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { - ctx = 'rsa-sha2-512'; - flags.hash = 'sha512'; - } - } - if (ctx === undefined) - ctx = pubKey.type; +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; +} - const req = new AgentInboundRequest(msgType, ctx); - this[SYM_REQS].push(req); +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} - this.emit('sign', req, pubKey, data, flags); - break; - } - default: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - this.failureReply(req); - } - } - } +function translateLevel(level) { + if (level === 0) { + return false; + } - // Get ready for next message - this[SYM_MSGLEN] = -1; - if (p === bufferLen) { - // Nothing left to process for now - this[SYM_BUFFER] = null; - break; - } else { - this[SYM_BUFFER] = buffer = buffer.slice(p); - bufferLen = buffer.length; - p = 0; - } - } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} - cb(); - } +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } - _destroy(err, cb) { - cleanup(this); - cb(); - } + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } - _final(cb) { - cleanup(this); - cb(); - } + if (hasFlag('color=256')) { + return 2; + } - // Client->Server messages ================================================= - sign(pubKey, data, options, cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } + const min = forceColor || 0; - let flags = 0; + if (env.TERM === 'dumb') { + return min; + } - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid public key argument'); + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } - if (pubKey.type === 'ssh-rsa' && options) { - switch (options.hash) { - case 'sha256': - flags = SSH_AGENT_RSA_SHA2_256; - break; - case 'sha512': - flags = SSH_AGENT_RSA_SHA2_512; - break; - } - } - pubKey = pubKey.getPublicSSH(); + return 1; + } - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - const type = SSH_AGENTC_SIGN_REQUEST; - const keyLen = pubKey.length; - const dataLen = data.length; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } - writeUInt32BE(buf, buf.length - 4, p); + return min; + } - buf[p += 4] = type; + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } - writeUInt32BE(buf, keyLen, ++p); - pubKey.copy(buf, p += 4); + if (env.COLORTERM === 'truecolor') { + return 3; + } - writeUInt32BE(buf, dataLen, p += keyLen); - data.copy(buf, p += 4); + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - writeUInt32BE(buf, flags, p += dataLen); + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } - if (typeof cb !== 'function') - cb = noop; + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } - this[SYM_REQS].push({ type, cb }); + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } - return this.push(buf); - } - getIdentities(cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); + if ('COLORTERM' in env) { + return 1; + } - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - const type = SSH_AGENTC_REQUEST_IDENTITIES; + return min; +} - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} - writeUInt32BE(buf, buf.length - 4, p); +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; - buf[p += 4] = type; - if (typeof cb !== 'function') - cb = noop; +/***/ }), - this[SYM_REQS].push({ type, cb }); +/***/ 366: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this.push(buf); - } +var chownr = __nccwpck_require__(9051) +var tar = __nccwpck_require__(1260) +var pump = __nccwpck_require__(8341) +var mkdirp = __nccwpck_require__(7614) +var fs = __nccwpck_require__(7147) +var path = __nccwpck_require__(1017) +var os = __nccwpck_require__(2037) - // Server->Client messages ================================================= - failureReply(req) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); +var win32 = os.platform() === 'win32' - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); +var noop = function () {} - if (req.hasResponded()) - return true; +var echo = function (name) { + return name +} - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); +var normalize = !win32 ? echo : function (name) { + return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_') +} - writeUInt32BE(buf, buf.length - 4, p); +var statAll = function (fs, stat, cwd, ignore, entries, sort) { + var queue = entries || ['.'] - buf[p += 4] = SSH_AGENT_FAILURE; + return function loop (callback) { + if (!queue.length) return callback() + var next = queue.shift() + var nextAbs = path.join(cwd, next) - return respond(this, req, buf); - } - getIdentitiesReply(req, keys) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); + stat(nextAbs, function (err, stat) { + if (err) return callback(err) - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); + if (!stat.isDirectory()) return callback(null, next, stat) - if (req.hasResponded()) - return true; + fs.readdir(nextAbs, function (err, files) { + if (err) return callback(err) - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys + if (sort) files.sort() + for (var i = 0; i < files.length; i++) { + if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) + } - where `nkeys` is 0 or more of: - string key blob - string comment - */ + callback(null, next, stat) + }) + }) + } +} - if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) - throw new Error('Invalid response to request'); +var strip = function (map, level) { + return function (header) { + header.name = header.name.split('/').slice(level).join('/') - if (!Array.isArray(keys)) - throw new Error('Keys argument must be an array'); + var linkname = header.linkname + if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { + header.linkname = linkname.split('/').slice(level).join('/') + } - let totalKeysLen = 4; // Include `nkeys` size + return map(header) + } +} - const newKeys = []; - for (let i = 0; i < keys.length; ++i) { - const entry = keys[i]; - if (typeof entry !== 'object' || entry === null) - throw new Error(`Invalid key entry: ${entry}`); +exports.pack = function (cwd, opts) { + if (!cwd) cwd = '.' + if (!opts) opts = {} - let pubKey; - let comment; - if (isParsedKey(entry)) { - pubKey = entry; - } else if (isParsedKey(entry.pubKey)) { - pubKey = entry.pubKey; - } else { - if (typeof entry.pubKey !== 'object' || entry.pubKey === null) - continue; - ({ pubKey, comment } = entry.pubKey); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - continue; // TODO: add debug output - } - comment = pubKey.comment || comment; - pubKey = pubKey.getPublicSSH(); + var xfs = opts.fs || fs + var ignore = opts.ignore || opts.filter || noop + var map = opts.map || noop + var mapStream = opts.mapStream || echo + var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) + var strict = opts.strict !== false + var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() + var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 + var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 + var pack = opts.pack || tar.pack() + var finish = opts.finish || noop - totalKeysLen += 4 + pubKey.length; + if (opts.strip) map = strip(map, opts.strip) - if (comment && typeof comment === 'string') - comment = Buffer.from(comment); - else if (!Buffer.isBuffer(comment)) - comment = EMPTY_BUF; + if (opts.readable) { + dmode |= parseInt(555, 8) + fmode |= parseInt(444, 8) + } + if (opts.writable) { + dmode |= parseInt(333, 8) + fmode |= parseInt(222, 8) + } - totalKeysLen += 4 + comment.length; + var onsymlink = function (filename, header) { + xfs.readlink(path.join(cwd, filename), function (err, linkname) { + if (err) return pack.destroy(err) + header.linkname = normalize(linkname) + pack.entry(header, onnextentry) + }) + } - newKeys.push({ pubKey, comment }); - } + var onstat = function (err, filename, stat) { + if (err) return pack.destroy(err) + if (!filename) { + if (opts.finalize !== false) pack.finalize() + return finish(pack) + } - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); + if (stat.isSocket()) return onnextentry() // tar does not support sockets... - writeUInt32BE(buf, buf.length - 4, p); + var header = { + name: normalize(filename), + mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, + mtime: stat.mtime, + size: stat.size, + type: 'file', + uid: stat.uid, + gid: stat.gid + } - buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; + if (stat.isDirectory()) { + header.size = 0 + header.type = 'directory' + header = map(header) || header + return pack.entry(header, onnextentry) + } - writeUInt32BE(buf, newKeys.length, ++p); - p += 4; - for (let i = 0; i < newKeys.length; ++i) { - const { pubKey, comment } = newKeys[i]; + if (stat.isSymbolicLink()) { + header.size = 0 + header.type = 'symlink' + header = map(header) || header + return onsymlink(filename, header) + } - writeUInt32BE(buf, pubKey.length, p); - pubKey.copy(buf, p += 4); + // TODO: add fifo etc... - writeUInt32BE(buf, comment.length, p += pubKey.length); - p += 4; - if (comment.length) { - comment.copy(buf, p); - p += comment.length; - } - } + header = map(header) || header - return respond(this, req, buf); + if (!stat.isFile()) { + if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) + return onnextentry() } - signReply(req, signature) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); + var entry = pack.entry(header, onnextentry) + if (!entry) return - if (req.hasResponded()) - return true; + var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header) - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ + rs.on('error', function (err) { // always forward errors on destroy + entry.destroy(err) + }) - if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) - throw new Error('Invalid response to request'); + pump(rs, entry) + } - if (!Buffer.isBuffer(signature)) - throw new Error('Signature argument must be a Buffer'); + var onnextentry = function (err) { + if (err) return pack.destroy(err) + statNext(onstat) + } - if (signature.length === 0) - throw new Error('Signature argument must be non-empty'); + onnextentry() - /* - OpenSSH agent signatures are encoded as: + return pack +} - string signature format identifier (as specified by the - public key/certificate format) - byte[n] signature blob in format specific encoding. - - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 - types - */ +var head = function (list) { + return list.length ? list[list.length - 1] : null +} - let p = 0; - const sigFormat = req.getContext(); - const sigFormatLen = Buffer.byteLength(sigFormat); - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length - ); +var processGetuid = function () { + return process.getuid ? process.getuid() : -1 +} - writeUInt32BE(buf, buf.length - 4, p); +var processUmask = function () { + return process.umask ? process.umask() : 0 +} - buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; +exports.extract = function (cwd, opts) { + if (!cwd) cwd = '.' + if (!opts) opts = {} - writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); - writeUInt32BE(buf, sigFormatLen, p += 4); - buf.utf8Write(sigFormat, p += 4, sigFormatLen); - writeUInt32BE(buf, signature.length, p += sigFormatLen); - signature.copy(buf, p += 4); + var xfs = opts.fs || fs + var ignore = opts.ignore || opts.filter || noop + var map = opts.map || noop + var mapStream = opts.mapStream || echo + var own = opts.chown !== false && !win32 && processGetuid() === 0 + var extract = opts.extract || tar.extract() + var stack = [] + var now = new Date() + var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() + var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 + var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 + var strict = opts.strict !== false - return respond(this, req, buf); - } - }; -})(); + if (opts.strip) map = strip(map, opts.strip) -const SYM_AGENT = Symbol('Agent'); -const SYM_AGENT_KEYS = Symbol('Agent Keys'); -const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); -const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); -class AgentContext { - constructor(agent) { - if (typeof agent === 'string') - agent = createAgent(agent); - else if (!isAgent(agent)) - throw new Error('Invalid agent argument'); - this[SYM_AGENT] = agent; - this[SYM_AGENT_KEYS] = null; - this[SYM_AGENT_KEYS_IDX] = -1; - this[SYM_AGENT_CBS] = null; + if (opts.readable) { + dmode |= parseInt(555, 8) + fmode |= parseInt(444, 8) + } + if (opts.writable) { + dmode |= parseInt(333, 8) + fmode |= parseInt(222, 8) } - init(cb) { - if (typeof cb !== 'function') - cb = noop; - if (this[SYM_AGENT_KEYS] === null) { - if (this[SYM_AGENT_CBS] === null) { - this[SYM_AGENT_CBS] = [cb]; + var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry + var top + while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() + if (!top) return cb() + xfs.utimes(top[0], now, top[1], cb) + } - const doCbs = (...args) => { - process.nextTick(() => { - const cbs = this[SYM_AGENT_CBS]; - this[SYM_AGENT_CBS] = null; - for (const cb of cbs) - cb(...args); - }); - }; + var utimes = function (name, header, cb) { + if (opts.utimes === false) return cb() - this[SYM_AGENT].getIdentities(once((err, keys) => { - if (err) - return doCbs(err); + if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) + if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? - if (!Array.isArray(keys)) { - return doCbs(new Error( - 'Agent implementation failed to provide keys' - )); - } + xfs.utimes(name, now, header.mtime, function (err) { + if (err) return cb(err) + utimesParent(name, cb) + }) + } - const newKeys = []; - for (let key of keys) { - key = parseKey(key); - if (key instanceof Error) { - // TODO: add debug output - continue; - } - newKeys.push(key); - } + var chperm = function (name, header, cb) { + var link = header.type === 'symlink' - this[SYM_AGENT_KEYS] = newKeys; - this[SYM_AGENT_KEYS_IDX] = -1; - doCbs(); - })); - } else { - this[SYM_AGENT_CBS].push(cb); - } - } else { - process.nextTick(cb); - } + /* eslint-disable node/no-deprecated-api */ + var chmod = link ? xfs.lchmod : xfs.chmod + var chown = link ? xfs.lchown : xfs.chown + /* eslint-enable node/no-deprecated-api */ + + if (!chmod) return cb() + + var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask + chmod(name, mode, function (err) { + if (err) return cb(err) + if (!own) return cb() + if (!chown) return cb() + chown(name, header.uid, header.gid, cb) + }) } - nextKey() { - if (this[SYM_AGENT_KEYS] === null - || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return false; + + extract.on('entry', function (header, stream, next) { + header = map(header) || header + header.name = normalize(header.name) + var name = path.join(cwd, path.join('/', header.name)) + + if (ignore(name, header)) { + stream.resume() + return next() } - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - currentKey() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return null; + var stat = function (err) { + if (err) return next(err) + utimes(name, header, function (err) { + if (err) return next(err) + if (win32) return next() + chperm(name, header, next) + }) } - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - pos() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return -1; + var onsymlink = function () { + if (win32) return next() // skip symlinks on win for now before it can be tested + xfs.unlink(name, function () { + xfs.symlink(header.linkname, name, stat) + }) } - return this[SYM_AGENT_KEYS_IDX]; - } - reset() { - this[SYM_AGENT_KEYS_IDX] = -1; - } + var onlink = function () { + if (win32) return next() // skip links on win for now before it can be tested + xfs.unlink(name, function () { + var srcpath = path.join(cwd, path.join('/', header.linkname)) - sign(...args) { - this[SYM_AGENT].sign(...args); - } -} + xfs.link(srcpath, name, function (err) { + if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { + stream = xfs.createReadStream(srcpath) + return onfile() + } -function isAgent(val) { - return (val instanceof BaseAgent); -} + stat(err) + }) + }) + } -module.exports = { - AgentContext, - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - isAgent, - OpenSSHAgent, - PageantAgent, -}; + var onfile = function () { + var ws = xfs.createWriteStream(name) + var rs = mapStream(stream, header) + ws.on('error', function (err) { // always forward errors on destroy + rs.destroy(err) + }) -/***/ }), + pump(rs, ws, function (err) { + if (err) return next(err) + ws.on('close', stat) + }) + } -/***/ 6063: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (header.type === 'directory') { + stack.push([name, header.mtime]) + return mkdirfix(name, { + fs: xfs, own: own, uid: header.uid, gid: header.gid + }, stat) + } -"use strict"; -// TODO: -// * add `.connected` or similar property to allow immediate connection -// status checking -// * add/improve debug output during user authentication phase + var dir = path.dirname(name) + validate(xfs, dir, path.join(cwd, '.'), function (err, valid) { + if (err) return next(err) + if (!valid) return next(new Error(dir + ' is not a valid path')) -const { - createHash, - getHashes, - randomFillSync, -} = __nccwpck_require__(6113); -const { Socket } = __nccwpck_require__(1808); -const { lookup: dnsLookup } = __nccwpck_require__(9523); -const EventEmitter = __nccwpck_require__(2361); -const HASHES = getHashes(); + mkdirfix(dir, { + fs: xfs, own: own, uid: header.uid, gid: header.gid + }, function (err) { + if (err) return next(err) -const { - COMPAT, - CHANNEL_EXTENDED_DATATYPE: { STDERR }, - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = __nccwpck_require__(6832); -const { init: cryptoInit } = __nccwpck_require__(5708); -const Protocol = __nccwpck_require__(9031); -const { parseKey } = __nccwpck_require__(2218); -const { SFTP } = __nccwpck_require__(2026); -const { - bufferCopy, - makeBufferParser, - makeError, - readUInt32BE, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(9475); + switch (header.type) { + case 'file': return onfile() + case 'link': return onlink() + case 'symlink': return onsymlink() + } -const { AgentContext, createAgent, isAgent } = __nccwpck_require__(9054); -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = __nccwpck_require__(3204); -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = __nccwpck_require__(834); + if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) -const bufferParser = makeBufferParser(); -const sigParser = makeBufferParser(); -const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; -const noop = (err) => {}; + stream.resume() + next() + }) + }) + }) -class Client extends EventEmitter { - constructor() { - super(); + if (opts.finish) extract.on('finish', opts.finish) - this.config = { - host: undefined, - port: undefined, - localAddress: undefined, - localPort: undefined, - forceIPv4: undefined, - forceIPv6: undefined, - keepaliveCountMax: undefined, - keepaliveInterval: undefined, - readyTimeout: undefined, - ident: undefined, + return extract +} - username: undefined, - password: undefined, - privateKey: undefined, - tryKeyboard: undefined, - agent: undefined, - allowAgentFwd: undefined, - authHandler: undefined, +function validate (fs, name, root, cb) { + if (name === root) return cb(null, true) + fs.lstat(name, function (err, st) { + if (err && err.code !== 'ENOENT') return cb(err) + if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb) + cb(null, false) + }) +} - hostHashAlgo: undefined, - hostHashCb: undefined, - strictVendor: undefined, - debug: undefined - }; +function mkdirfix (name, opts, cb) { + mkdirp(name, { fs: opts.fs }, function (err, made) { + if (!err && made && opts.own) { + chownr(made, opts.uid, opts.gid, cb) + } else { + cb(err) + } + }) +} - this._agent = undefined; - this._readyTimeout = undefined; - this._chanMgr = undefined; - this._callbacks = undefined; - this._forwarding = undefined; - this._forwardingUnix = undefined; - this._acceptX11 = undefined; - this._agentFwdEnabled = undefined; - this._remoteVer = undefined; - this._protocol = undefined; - this._sock = undefined; - this._resetKA = undefined; - } +/***/ }), - connect(cfg) { - if (this._sock && isWritable(this._sock)) { - this.once('close', () => { - this.connect(cfg); - }); - this.end(); - return this; - } +/***/ 1515: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.config.host = cfg.hostname || cfg.host || 'localhost'; - this.config.port = cfg.port || 22; - this.config.localAddress = (typeof cfg.localAddress === 'string' - ? cfg.localAddress - : undefined); - this.config.localPort = (typeof cfg.localPort === 'string' - || typeof cfg.localPort === 'number' - ? cfg.localPort - : undefined); - this.config.forceIPv4 = cfg.forceIPv4 || false; - this.config.forceIPv6 = cfg.forceIPv6 || false; - this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' - && cfg.keepaliveCountMax >= 0 - ? cfg.keepaliveCountMax - : 3); - this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' - && cfg.keepaliveInterval > 0 - ? cfg.keepaliveInterval - : 0); - this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' - && cfg.readyTimeout >= 0 - ? cfg.readyTimeout - : 20000); - this.config.ident = (typeof cfg.ident === 'string' - || Buffer.isBuffer(cfg.ident) - ? cfg.ident - : undefined); +"use strict"; + + +const { Buffer } = __nccwpck_require__(4300) +const symbol = Symbol.for('BufferList') - const algorithms = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: [], - }, - sc: undefined, - }; - let allOfferDefaults = true; - if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { - algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, - DEFAULT_KEX, - SUPPORTED_KEX); - if (algorithms.kex !== DEFAULT_KEX) - allOfferDefaults = false; +function BufferList (buf) { + if (!(this instanceof BufferList)) { + return new BufferList(buf) + } - algorithms.serverHostKey = - generateAlgorithmList(cfg.algorithms.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY); - if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) - allOfferDefaults = false; + BufferList._init.call(this, buf) +} - algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER); - if (algorithms.cs.cipher !== DEFAULT_CIPHER) - allOfferDefaults = false; +BufferList._init = function _init (buf) { + Object.defineProperty(this, symbol, { value: true }) - algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, - DEFAULT_MAC, - SUPPORTED_MAC); - if (algorithms.cs.mac !== DEFAULT_MAC) - allOfferDefaults = false; + this._bufs = [] + this.length = 0 - algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION); - if (algorithms.cs.compress !== DEFAULT_COMPRESSION) - allOfferDefaults = false; + if (buf) { + this.append(buf) + } +} - if (!allOfferDefaults) - algorithms.sc = algorithms.cs; +BufferList.prototype._new = function _new (buf) { + return new BufferList(buf) +} + +BufferList.prototype._offset = function _offset (offset) { + if (offset === 0) { + return [0, 0] + } + + let tot = 0 + + for (let i = 0; i < this._bufs.length; i++) { + const _t = tot + this._bufs[i].length + if (offset < _t || i === this._bufs.length - 1) { + return [i, offset - tot] } + tot = _t + } +} - if (typeof cfg.username === 'string') - this.config.username = cfg.username; - else if (typeof cfg.user === 'string') - this.config.username = cfg.user; - else - throw new Error('Invalid username'); +BufferList.prototype._reverseOffset = function (blOffset) { + const bufferId = blOffset[0] + let offset = blOffset[1] - this.config.password = (typeof cfg.password === 'string' - ? cfg.password - : undefined); - this.config.privateKey = (typeof cfg.privateKey === 'string' - || Buffer.isBuffer(cfg.privateKey) - ? cfg.privateKey - : undefined); - this.config.localHostname = (typeof cfg.localHostname === 'string' - ? cfg.localHostname - : undefined); - this.config.localUsername = (typeof cfg.localUsername === 'string' - ? cfg.localUsername - : undefined); - this.config.tryKeyboard = (cfg.tryKeyboard === true); - if (typeof cfg.agent === 'string' && cfg.agent.length) - this.config.agent = createAgent(cfg.agent); - else if (isAgent(cfg.agent)) - this.config.agent = cfg.agent; - else - this.config.agent = undefined; - this.config.allowAgentFwd = (cfg.agentForward === true - && this.config.agent !== undefined); - let authHandler = this.config.authHandler = ( - typeof cfg.authHandler === 'function' - || Array.isArray(cfg.authHandler) - ? cfg.authHandler - : undefined - ); + for (let i = 0; i < bufferId; i++) { + offset += this._bufs[i].length + } - this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' - ? cfg.strictVendor - : true); + return offset +} - const debug = this.config.debug = (typeof cfg.debug === 'function' - ? cfg.debug - : undefined); +BufferList.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined + } - if (cfg.agentForward === true && !this.config.allowAgentFwd) { - throw new Error( - 'You must set a valid agent path to allow agent forwarding' - ); - } + const offset = this._offset(index) - let callbacks = this._callbacks = []; - this._chanMgr = new ChannelManager(this); - this._forwarding = {}; - this._forwardingUnix = {}; - this._acceptX11 = 0; - this._agentFwdEnabled = false; - this._agent = (this.config.agent ? this.config.agent : undefined); - this._remoteVer = undefined; - let privateKey; + return this._bufs[offset[0]][offset[1]] +} - if (this.config.privateKey) { - privateKey = parseKey(this.config.privateKey, cfg.passphrase); - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - if (privateKey.getPrivatePEM() === null) { - throw new Error( - 'privateKey value does not contain a (valid) private key' - ); - } - } +BufferList.prototype.slice = function slice (start, end) { + if (typeof start === 'number' && start < 0) { + start += this.length + } - let hostVerifier; - if (typeof cfg.hostVerifier === 'function') { - const hashCb = cfg.hostVerifier; - let hasher; - if (HASHES.indexOf(cfg.hostHash) !== -1) { - // Default to old behavior of hashing on user's behalf - hasher = createHash(cfg.hostHash); - } - hostVerifier = (key, verify) => { - if (hasher) { - hasher.update(key); - key = hasher.digest('hex'); - } - const ret = hashCb(key, verify); - if (ret !== undefined) - verify(ret); - }; - } + if (typeof end === 'number' && end < 0) { + end += this.length + } - const sock = this._sock = (cfg.sock || new Socket()); - let ready = false; - let sawHeader = false; - if (this._protocol) - this._protocol.cleanup(); - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from server: ${JSON.stringify(msg)}`); - }); - const proto = this._protocol = new Protocol({ - ident: this.config.ident, - offer: (allOfferDefaults ? undefined : algorithms), - onWrite: (data) => { - if (isWritable(sock)) - sock.write(data); - }, - onError: (err) => { - if (err.level === 'handshake') - clearTimeout(this._readyTimeout); - if (!proto._destruct) - sock.removeAllListeners('data'); - this.emit('error', err); - try { - sock.end(); - } catch {} - }, - onHeader: (header) => { - sawHeader = true; - this._remoteVer = header.versions.software; - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - this.emit('handshake', negotiated); - if (!ready) { - ready = true; - proto.service('ssh-userauth'); - } - }, - debug, - hostVerifier, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - sock.end(); - }, - SERVICE_ACCEPT: (p, name) => { - if (name === 'ssh-userauth') - tryNextAuth(); - }, - USERAUTH_BANNER: (p, msg) => { - this.emit('banner', msg); - }, - USERAUTH_SUCCESS: (p) => { - // Start keepalive mechanism - resetKA(); + return this.copy(null, 0, start, end) +} - clearTimeout(this._readyTimeout); +BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart !== 'number' || srcStart < 0) { + srcStart = 0 + } - this.emit('ready'); - }, - USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { - if (curAuth.type === 'agent') { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Client: Agent key #${pos + 1} failed`); - return tryNextAgentKey(); - } + if (typeof srcEnd !== 'number' || srcEnd > this.length) { + srcEnd = this.length + } - debug && debug(`Client: ${curAuth.type} auth failed`); + if (srcStart >= this.length) { + return dst || Buffer.alloc(0) + } - curPartial = partialSuccess; - curAuthsLeft = authMethods; - tryNextAuth(); - }, - USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { - if (curAuth.type === 'password') { - // TODO: support a `changePrompt()` on `curAuth` that defaults to - // emitting 'change password' as before - this.emit('change password', prompt, (newPassword) => { - proto.authPassword( - this.config.username, - this.config.password, - newPassword - ); - }); - } - }, - USERAUTH_PK_OK: (p) => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.currentKey(); - proto.authPK(curAuth.username, key, (buf, cb) => { - curAuth.agentCtx.sign(key, buf, {}, (err, signed) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - } else { - return cb(signed); - } + if (srcEnd <= 0) { + return dst || Buffer.alloc(0) + } - tryNextAgentKey(); - }); - }); - } else if (curAuth.type === 'publickey') { - proto.authPK(curAuth.username, curAuth.key, (buf, cb) => { - const signature = curAuth.key.sign(buf); - if (signature instanceof Error) { - signature.message = - `Error signing data with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - cb(signature); - }); - } - }, - USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { - if (curAuth.type === 'keyboard-interactive') { - const nprompts = (Array.isArray(prompts) ? prompts.length : 0); - if (nprompts === 0) { - debug && debug( - 'Client: Sending automatic USERAUTH_INFO_RESPONSE' - ); - proto.authInfoRes(); - return; - } - // We sent a keyboard-interactive user authentication request and - // now the server is sending us the prompts we need to present to - // the user - curAuth.prompt( - name, - instructions, - '', - prompts, - (answers) => { - proto.authInfoRes(answers); - } - ); - } - }, - REQUEST_SUCCESS: (p, data) => { - if (callbacks.length) - callbacks.shift()(false, data); - }, - REQUEST_FAILURE: (p) => { - if (callbacks.length) - callbacks.shift()(true); - }, - GLOBAL_REQUEST: (p, name, wantReply, data) => { - switch (name) { - case 'hostkeys-00@openssh.com': - // Automatically verify keys before passing to end user - hostKeysProve(this, data, (err, keys) => { - if (err) - return; - this.emit('hostkeys', keys); - }); - if (wantReply) - proto.requestSuccess(); - break; - default: - // Auto-reject all other global requests, this can be especially - // useful if the server is sending us dummy keepalive global - // requests - if (wantReply) - proto.requestFailure(); - } - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from server, typically a forwarded TCP or - // X11 connection - onCHANNEL_OPEN(this, info); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; + const copy = !!dst + const off = this._offset(srcStart) + const len = srcEnd - srcStart + let bytes = len + let bufoff = (copy && dstStart) || 0 + let start = off[1] - const isSFTP = (channel.type === 'sftp'); - const type = (isSFTP ? 'session' : channel.type); - const chanInfo = { - type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const instance = ( - isSFTP - ? new SFTP(this, chanInfo, { debug }) - : new Channel(this, chanInfo) - ); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; + // copy/slice everything + if (srcStart === 0 && srcEnd === this.length) { + if (!copy) { + // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer.concat(this._bufs, this.length) + } - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + // copy, need to copy individual buffers + for (let i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; + return dst + } - channel.incoming.window -= data.length; + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } + if (!copy) { + // a slice, we need something to copy in to + dst = Buffer.allocUnsafe(len) + } - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - if (type !== STDERR) - return; + for (let i = off[0]; i < this._bufs.length; i++) { + const l = this._bufs[i].length - start - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + bufoff += l + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l + break + } - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; + bytes -= l - channel.incoming.window -= data.length; + if (start) { + start = 0 + } + } - if (!channel.stderr.push(data)) { - channel._waitChanDrain = true; - return; - } + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + return dst +} - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = typeof end !== 'number' ? this.length : end + + if (start < 0) { + start += this.length + } + + if (end < 0) { + end += this.length + } + + if (start === end) { + return this._new() + } - if (channel._waitWindow) { - channel._waitWindow = false; + const startOffset = this._offset(start) + const endOffset = this._offset(end) + const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + if (endOffset[1] === 0) { + buffers.pop() + } else { + buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) + } - this._resetKA(); + if (startOffset[1] !== 0) { + buffers[0] = buffers[0].slice(startOffset[1]) + } - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + return this._new(buffers) +} - this._resetKA(); +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this - const exit = channel._exit; - if (exit.code !== undefined) - return; - switch (type) { - case 'exit-status': - channel.emit('exit', exit.code = data); - return; - case 'exit-signal': - channel.emit('exit', - exit.code = null, - exit.signal = `SIG${data.signal}`, - exit.dump = data.coreDumped, - exit.desc = data.errorMessage); - return; - } + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() + } else { + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break + } + } - // Keepalive request? OpenSSH will send one as a channel request if - // there is a channel open + return this +} - if (wantReply) - p.channelFailure(channel.outgoing.id); - }, - CHANNEL_EOF: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +BufferList.prototype.duplicate = function duplicate () { + const copy = this._new() - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; + for (let i = 0; i < this._bufs.length; i++) { + copy.append(this._bufs[i]) + } - if (channel.readable) - channel.push(null); - if (channel.stderr.readable) - channel.stderr.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); - }, - }, - }); + return copy +} - sock.pause(); +BufferList.prototype.append = function append (buf) { + if (buf == null) { + return this + } - // TODO: check keepalive implementation - // Keepalive-related - const kainterval = this.config.keepaliveInterval; - const kacountmax = this.config.keepaliveCountMax; - let kacount = 0; - let katimer; - const sendKA = () => { - if (++kacount > kacountmax) { - clearInterval(katimer); - if (sock.readable) { - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - } - return; - } - if (isWritable(sock)) { - // Append dummy callback to keep correct callback order - callbacks.push(resetKA); - proto.ping(); - } else { - clearInterval(katimer); - } - }; - function resetKA() { - if (kainterval > 0) { - kacount = 0; - clearInterval(katimer); - if (isWritable(sock)) - katimer = setInterval(sendKA, kainterval); - } + if (buf.buffer) { + // append a view of the underlying ArrayBuffer + this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) + } else if (Array.isArray(buf)) { + for (let i = 0; i < buf.length; i++) { + this.append(buf[i]) + } + } else if (this._isBufferList(buf)) { + // unwrap argument into individual BufferLists + for (let i = 0; i < buf._bufs.length; i++) { + this.append(buf._bufs[i]) + } + } else { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf === 'number') { + buf = buf.toString() } - this._resetKA = resetKA; - const onDone = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (wasConnected && !sawHeader) { - const err = - makeError('Connection lost before handshake', 'protocol', true); - this.emit('error', err); - } - }; - })(); - const onConnect = (() => { - let called = false; - return () => { - if (called) - return; - called = true; + this._appendBuffer(Buffer.from(buf)) + } - wasConnected = true; - debug && debug('Socket connected'); - this.emit('connect'); + return this +} - cryptoInit.then(() => { - proto.start(); - sock.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - } - }); +BufferList.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf) + this.length += buf.length +} - // Drain stderr if we are connection hopping using an exec stream - if (sock.stderr && typeof sock.stderr.resume === 'function') - sock.stderr.resume(); +BufferList.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + } - sock.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - }); - }; - })(); - let wasConnected = false; - sock.on('connect', onConnect) - .on('timeout', () => { - this.emit('timeout'); - }).on('error', (err) => { - debug && debug(`Socket error: ${err.message}`); - clearTimeout(this._readyTimeout); - err.level = 'client-socket'; - this.emit('error', err); - }).on('end', () => { - debug && debug('Socket ended'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('end'); - }).on('close', () => { - debug && debug('Socket closed'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('close'); + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer.from([search]) + } else if (typeof search === 'string') { + search = Buffer.from(search, encoding) + } else if (this._isBufferList(search)) { + search = search.slice() + } else if (Array.isArray(search.buffer)) { + search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) + } else if (!Buffer.isBuffer(search)) { + search = Buffer.from(search) + } - // Notify outstanding channel requests of disconnection ... - const callbacks_ = callbacks; - callbacks = this._callbacks = []; - const err = new Error('No response from server'); - for (let i = 0; i < callbacks_.length; ++i) - callbacks_[i](err); + offset = Number(offset || 0) - // Simulate error for any channels waiting to be opened - this._chanMgr.cleanup(err); - }); + if (isNaN(offset)) { + offset = 0 + } - // Begin authentication handling =========================================== - let curAuth; - let curPartial = null; - let curAuthsLeft = null; - const authsAllowed = ['none']; - if (this.config.password !== undefined) - authsAllowed.push('password'); - if (privateKey !== undefined) - authsAllowed.push('publickey'); - if (this._agent !== undefined) - authsAllowed.push('agent'); - if (this.config.tryKeyboard) - authsAllowed.push('keyboard-interactive'); - if (privateKey !== undefined - && this.config.localHostname !== undefined - && this.config.localUsername !== undefined) { - authsAllowed.push('hostbased'); - } + if (offset < 0) { + offset = this.length + offset + } - if (Array.isArray(authHandler)) - authHandler = makeSimpleAuthHandler(authHandler); - else if (typeof authHandler !== 'function') - authHandler = makeSimpleAuthHandler(authsAllowed); + if (offset < 0) { + offset = 0 + } - let hasSentAuth = false; - const doNextAuth = (nextAuth) => { - if (hasSentAuth) - return; - hasSentAuth = true; + if (search.length === 0) { + return offset > this.length ? this.length : offset + } - if (nextAuth === false) { - const err = new Error('All configured authentication methods failed'); - err.level = 'client-authentication'; - this.emit('error', err); - this.end(); - return; - } + const blOffset = this._offset(offset) + let blIndex = blOffset[0] // index of which internal buffer we're working on + let buffOffset = blOffset[1] // offset of the internal buffer we're working on - if (typeof nextAuth === 'string') { - // Remain backwards compatible with original `authHandler()` usage, - // which only supported passing names of next method to try using data - // from the `connect()` config object + // scan over each buffer + for (; blIndex < this._bufs.length; blIndex++) { + const buff = this._bufs[blIndex] - const type = nextAuth; - if (authsAllowed.indexOf(type) === -1) - return skipAuth(`Authentication method not allowed: ${type}`); + while (buffOffset < buff.length) { + const availableWindow = buff.length - buffOffset - const username = this.config.username; - switch (type) { - case 'password': - nextAuth = { type, username, password: this.config.password }; - break; - case 'publickey': - nextAuth = { type, username, key: privateKey }; - break; - case 'hostbased': - nextAuth = { - type, - username, - key: privateKey, - localHostname: this.config.localHostname, - localUsername: this.config.localUsername, - }; - break; - case 'agent': - nextAuth = { - type, - username, - agentCtx: new AgentContext(this._agent), - }; - break; - case 'keyboard-interactive': - nextAuth = { - type, - username, - prompt: (...args) => this.emit('keyboard-interactive', ...args), - }; - break; - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); + if (availableWindow >= search.length) { + const nativeSearchResult = buff.indexOf(search, buffOffset) + + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) } - } else if (typeof nextAuth !== 'object' || nextAuth === null) { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); + + buffOffset = buff.length - search.length + 1 // end of native search window } else { - const username = nextAuth.username; - if (typeof username !== 'string') { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } - const type = nextAuth.type; - switch (type) { - case 'password': { - const { password } = nextAuth; - if (typeof password !== 'string' && !Buffer.isBuffer(password)) - return skipAuth('Skipping invalid password auth attempt'); - nextAuth = { type, username, password }; - break; - } - case 'publickey': { - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error) - return skipAuth('Skipping invalid key auth attempt'); - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key }; - break; - } - case 'hostbased': { - const { localHostname, localUsername } = nextAuth; - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error - || typeof localHostname !== 'string' - || typeof localUsername !== 'string') { - return skipAuth('Skipping invalid hostbased auth attempt'); - } - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key, localHostname, localUsername }; - break; - } - case 'agent': { - let agent = nextAuth.agent; - if (typeof agent === 'string' && agent.length) { - agent = createAgent(agent); - } else if (!isAgent(agent)) { - return skipAuth( - `Skipping invalid agent: ${nextAuth.agent}` - ); - } - nextAuth = { type, username, agentCtx: new AgentContext(agent) }; - break; - } - case 'keyboard-interactive': { - const { prompt } = nextAuth; - if (typeof prompt !== 'function') { - return skipAuth( - 'Skipping invalid keyboard-interactive auth attempt' - ); - } - nextAuth = { type, username, prompt }; - break; - } - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); + const revOffset = this._reverseOffset([blIndex, buffOffset]) + + if (this._match(revOffset, search)) { + return revOffset } + + buffOffset++ } - curAuth = nextAuth; + } - // Begin authentication method's process - try { - const username = curAuth.username; - switch (curAuth.type) { - case 'password': - proto.authPassword(username, curAuth.password); - break; - case 'publickey': - proto.authPK(username, curAuth.key); - break; - case 'hostbased': - proto.authHostbased(username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - (buf, cb) => { - const signature = curAuth.key.sign(buf); - if (signature instanceof Error) { - signature.message = - `Error while signing with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } + buffOffset = 0 + } - cb(signature); - }); - break; - case 'agent': - curAuth.agentCtx.init((err) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - return tryNextAuth(); - } - tryNextAgentKey(); - }); - break; - case 'keyboard-interactive': - proto.authKeyboard(username); - break; - case 'none': - proto.authNone(username); - break; - } - } finally { - hasSentAuth = false; - } - }; + return -1 +} + +BufferList.prototype._match = function (offset, search) { + if (this.length - offset < search.length) { + return false + } - function skipAuth(msg) { - debug && debug(msg); - process.nextTick(tryNextAuth); + for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { + if (this.get(offset + searchOffset) !== search[searchOffset]) { + return false } + } + return true +} - function tryNextAuth() { - hasSentAuth = false; - const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); - if (hasSentAuth || auth === undefined) - return; - doNextAuth(auth); - } +;(function () { + const methods = { + readDoubleBE: 8, + readDoubleLE: 8, + readFloatBE: 4, + readFloatLE: 4, + readInt32BE: 4, + readInt32LE: 4, + readUInt32BE: 4, + readUInt32LE: 4, + readInt16BE: 2, + readInt16LE: 2, + readUInt16BE: 2, + readUInt16LE: 2, + readInt8: 1, + readUInt8: 1, + readIntBE: null, + readIntLE: null, + readUIntBE: null, + readUIntLE: null + } - const tryNextAgentKey = () => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.nextKey(); - if (key === false) { - debug && debug('Agent: No more keys left to try'); - debug && debug('Client: agent auth failed'); - tryNextAuth(); - } else { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Agent: Trying key #${pos + 1}`); - proto.authPK(curAuth.username, key); + for (const m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) + } + } else { + BufferList.prototype[m] = function (offset = 0) { + return this.slice(offset, offset + methods[m])[m](0) } } - }; + }(m)) + } +}()) - const startTimeout = () => { - if (this.config.readyTimeout > 0) { - this._readyTimeout = setTimeout(() => { - const err = new Error('Timed out while waiting for handshake'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - }, this.config.readyTimeout); - } - }; +// Used internally by the class and also as an indicator of this object being +// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser +// environment because there could be multiple different copies of the +// BufferList class and some `BufferList`s might be `BufferList`s. +BufferList.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferList || BufferList.isBufferList(b) +} - if (!cfg.sock) { - let host = this.config.host; - const forceIPv4 = this.config.forceIPv4; - const forceIPv6 = this.config.forceIPv6; +BufferList.isBufferList = function isBufferList (b) { + return b != null && b[symbol] +} - debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); +module.exports = BufferList - const doConnect = () => { - startTimeout(); - sock.connect({ - host, - port: this.config.port, - localAddress: this.config.localAddress, - localPort: this.config.localPort - }); - sock.setNoDelay(true); - sock.setMaxListeners(0); - sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); - }; - if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { - doConnect(); - } else { - dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { - if (err) { - const type = (forceIPv4 ? 'IPv4' : 'IPv6'); - const error = new Error( - `Error while looking up ${type} address for '${host}': ${err}` - ); - clearTimeout(this._readyTimeout); - error.level = 'client-dns'; - this.emit('error', error); - this.emit('close'); - return; - } - host = address; - doConnect(); - }); - } - } else { - // Custom socket passed in - startTimeout(); - if (typeof sock.connecting === 'boolean') { - // net.Socket +/***/ }), - if (!sock.connecting) { - // Already connected - onConnect(); - } - } else { - // Assume socket/stream is already "connected" - onConnect(); +/***/ 6136: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const DuplexStream = (__nccwpck_require__(1642).Duplex) +const inherits = __nccwpck_require__(4124) +const BufferList = __nccwpck_require__(1515) + +function BufferListStream (callback) { + if (!(this instanceof BufferListStream)) { + return new BufferListStream(callback) + } + + if (typeof callback === 'function') { + this._callback = callback + + const piper = function piper (err) { + if (this._callback) { + this._callback(err) + this._callback = null } - } + }.bind(this) - return this; + this.on('pipe', function onPipe (src) { + src.on('error', piper) + }) + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper) + }) + + callback = null } - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; + BufferList._init.call(this, callback) + DuplexStream.call(this) +} + +inherits(BufferListStream, DuplexStream) +Object.assign(BufferListStream.prototype, BufferList.prototype) + +BufferListStream.prototype._new = function _new (callback) { + return new BufferListStream(callback) +} + +BufferListStream.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf) + + if (typeof callback === 'function') { + callback() } +} - destroy() { - this._sock && isWritable(this._sock) && this._sock.destroy(); - return this; +BufferListStream.prototype._read = function _read (size) { + if (!this.length) { + return this.push(null) } - exec(cmd, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } +BufferListStream.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk) - const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null + } +} - openChannel(this, 'session', extraOpts, (err, chan) => { - if (err) { - cb(err); - return; - } +BufferListStream.prototype._destroy = function _destroy (err, cb) { + this._bufs.length = 0 + this.length = 0 + cb(err) +} - const todo = []; +BufferListStream.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) +} - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } +BufferListStream.isBufferList = BufferList.isBufferList - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } +module.exports = BufferListStream +module.exports.BufferListStream = BufferListStream +module.exports.BufferList = BufferList - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.pty === 'object' && opts.pty !== null) - || opts.pty === true) { - todo.push(() => reqPty(chan, opts.pty, reqCb)); - } - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - todo.push(() => reqExec(chan, cmd, opts, cb)); - todo.shift()(); - }); +/***/ }), - return this; - } +/***/ 9545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - shell(wndopts, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); +var util = __nccwpck_require__(3837) +var bl = __nccwpck_require__(6136) +var headers = __nccwpck_require__(6834) - if (typeof wndopts === 'function') { - cb = wndopts; - wndopts = opts = undefined; - } else if (typeof opts === 'function') { - cb = opts; - opts = undefined; - } - if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { - opts = wndopts; - wndopts = undefined; - } +var Writable = (__nccwpck_require__(1642).Writable) +var PassThrough = (__nccwpck_require__(1642).PassThrough) - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } +var noop = function () {} - const todo = []; +var overflow = function (size) { + size &= 511 + return size && 512 - size +} - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } +var emptyStream = function (self, offset) { + var s = new Source(self, offset) + s.end() + return s +} - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } +var mixinPax = function (header, pax) { + if (pax.path) header.name = pax.path + if (pax.linkpath) header.linkname = pax.linkpath + if (pax.size) header.size = parseInt(pax.size, 10) + header.pax = pax + return header +} - if (wndopts !== false) - todo.push(() => reqPty(chan, wndopts, reqCb)); +var Source = function (self, offset) { + this._parent = self + this.offset = offset + PassThrough.call(this, { autoDestroy: false }) +} - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } +util.inherits(Source, PassThrough) - todo.push(() => reqShell(chan, cb)); - todo.shift()(); - }); +Source.prototype.destroy = function (err) { + this._parent.destroy(err) +} - return this; +var Extract = function (opts) { + if (!(this instanceof Extract)) return new Extract(opts) + Writable.call(this, opts) + + opts = opts || {} + + this._offset = 0 + this._buffer = bl() + this._missing = 0 + this._partial = false + this._onparse = noop + this._header = null + this._stream = null + this._overflow = null + this._cb = null + this._locked = false + this._destroyed = false + this._pax = null + this._paxGlobal = null + this._gnuLongPath = null + this._gnuLongLinkPath = null + + var self = this + var b = self._buffer + + var oncontinue = function () { + self._continue() } - subsys(name, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + var onunlock = function (err) { + self._locked = false + if (err) return self.destroy(err) + if (!self._stream) oncontinue() + } - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } + var onstreamend = function () { + self._stream = null + var drain = overflow(self._header.size) + if (drain) self._parse(drain, ondrain) + else self._parse(512, onheader) + if (!self._locked) oncontinue() + } - reqSubsystem(chan, name, (err, stream) => { - if (err) { - cb(err); - return; - } + var ondrain = function () { + self._buffer.consume(overflow(self._header.size)) + self._parse(512, onheader) + oncontinue() + } - cb(undefined, stream); - }); - }); + var onpaxglobalheader = function () { + var size = self._header.size + self._paxGlobal = headers.decodePax(b.slice(0, size)) + b.consume(size) + onstreamend() + } - return this; + var onpaxheader = function () { + var size = self._header.size + self._pax = headers.decodePax(b.slice(0, size)) + if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax) + b.consume(size) + onstreamend() } - forwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + var ongnulongpath = function () { + var size = self._header.size + this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) + b.consume(size) + onstreamend() + } - // Send a request for the server to start forwarding TCP connections to us - // on a particular address and port + var ongnulonglinkpath = function () { + var size = self._header.size + this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) + b.consume(size) + onstreamend() + } - const wantReply = (typeof cb === 'function'); + var onheader = function () { + var offset = self._offset + var header + try { + header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat) + } catch (err) { + self.emit('error', err) + } + b.consume(512) + + if (!header) { + self._parse(512, onheader) + oncontinue() + return + } + if (header.type === 'gnu-long-path') { + self._parse(header.size, ongnulongpath) + oncontinue() + return + } + if (header.type === 'gnu-long-link-path') { + self._parse(header.size, ongnulonglinkpath) + oncontinue() + return + } + if (header.type === 'pax-global-header') { + self._parse(header.size, onpaxglobalheader) + oncontinue() + return + } + if (header.type === 'pax-header') { + self._parse(header.size, onpaxheader) + oncontinue() + return + } + + if (self._gnuLongPath) { + header.name = self._gnuLongPath + self._gnuLongPath = null + } + + if (self._gnuLongLinkPath) { + header.linkname = self._gnuLongLinkPath + self._gnuLongLinkPath = null + } + + if (self._pax) { + self._header = header = mixinPax(header, self._pax) + self._pax = null + } + + self._locked = true + + if (!header.size || header.type === 'directory') { + self._parse(512, onheader) + self.emit('entry', header, emptyStream(self, offset), onunlock) + return + } + + self._stream = new Source(self, offset) + + self.emit('entry', header, self._stream, onunlock) + self._parse(header.size, onstreamend) + oncontinue() + } + + this._onheader = onheader + this._parse(512, onheader) +} + +util.inherits(Extract, Writable) + +Extract.prototype.destroy = function (err) { + if (this._destroyed) return + this._destroyed = true + + if (err) this.emit('error', err) + this.emit('close') + if (this._stream) this._stream.emit('close') +} - if (wantReply) { - this._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); - return; - } +Extract.prototype._parse = function (size, onparse) { + if (this._destroyed) return + this._offset += size + this._missing = size + if (onparse === this._onheader) this._partial = false + this._onparse = onparse +} - let realPort = bindPort; - if (bindPort === 0 && data && data.length >= 4) { - realPort = readUInt32BE(data, 0); - if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) - bindPort = realPort; - } +Extract.prototype._continue = function () { + if (this._destroyed) return + var cb = this._cb + this._cb = noop + if (this._overflow) this._write(this._overflow, undefined, cb) + else cb() +} - this._forwarding[`${bindAddr}:${bindPort}`] = realPort; +Extract.prototype._write = function (data, enc, cb) { + if (this._destroyed) return - cb(undefined, realPort); - }); - } + var s = this._stream + var b = this._buffer + var missing = this._missing + if (data.length) this._partial = true - this._protocol.tcpipForward(bindAddr, bindPort, wantReply); + // we do not reach end-of-chunk now. just forward it - return this; + if (data.length < missing) { + this._missing -= data.length + this._overflow = null + if (s) return s.write(data, cb) + b.append(data) + return cb() } - unforwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + // end-of-chunk. the parser should call cb. - // Send a request to stop forwarding us new connections for a particular - // address and port + this._cb = cb + this._missing = 0 - const wantReply = (typeof cb === 'function'); + var overflow = null + if (data.length > missing) { + overflow = data.slice(missing) + data = data.slice(0, missing) + } - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); - return; - } + if (s) s.end(data) + else b.append(data) - delete this._forwarding[`${bindAddr}:${bindPort}`]; + this._overflow = overflow + this._onparse() +} - cb(); - }); - } +Extract.prototype._final = function (cb) { + if (this._partial) return this.destroy(new Error('Unexpected end of data')) + cb() +} - this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); +module.exports = Extract - return this; - } - forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); +/***/ }), - // Send a request to forward a TCP connection to the server +/***/ 6834: +/***/ ((__unused_webpack_module, exports) => { - const cfg = { - srcIP: srcIP, - srcPort: srcPort, - dstIP: dstIP, - dstPort: dstPort - }; +var alloc = Buffer.alloc - if (typeof cb !== 'function') - cb = noop; +var ZEROS = '0000000000000000000' +var SEVENS = '7777777777777777777' +var ZERO_OFFSET = '0'.charCodeAt(0) +var USTAR_MAGIC = Buffer.from('ustar\x00', 'binary') +var USTAR_VER = Buffer.from('00', 'binary') +var GNU_MAGIC = Buffer.from('ustar\x20', 'binary') +var GNU_VER = Buffer.from('\x20\x00', 'binary') +var MASK = parseInt('7777', 8) +var MAGIC_OFFSET = 257 +var VERSION_OFFSET = 263 - openChannel(this, 'direct-tcpip', cfg, cb); +var clamp = function (index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue + index = ~~index // Coerce to integer. + if (index >= len) return len + if (index >= 0) return index + index += len + if (index >= 0) return index + return 0 +} - return this; +var toType = function (flag) { + switch (flag) { + case 0: + return 'file' + case 1: + return 'link' + case 2: + return 'symlink' + case 3: + return 'character-device' + case 4: + return 'block-device' + case 5: + return 'directory' + case 6: + return 'fifo' + case 7: + return 'contiguous-file' + case 72: + return 'pax-header' + case 55: + return 'pax-global-header' + case 27: + return 'gnu-long-link-path' + case 28: + case 30: + return 'gnu-long-path' } - openssh_noMoreSessions(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + return null +} - const wantReply = (typeof cb === 'function'); +var toTypeflag = function (flag) { + switch (flag) { + case 'file': + return 0 + case 'link': + return 1 + case 'symlink': + return 2 + case 'character-device': + return 3 + case 'block-device': + return 4 + case 'directory': + return 5 + case 'fifo': + return 6 + case 'contiguous-file': + return 7 + case 'pax-header': + return 72 + } - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to disable future sessions')); - return; - } + return 0 +} - cb(); - }); - } +var indexOf = function (block, num, offset, end) { + for (; offset < end; offset++) { + if (block[offset] === num) return offset + } + return end +} - this._protocol.openssh_noMoreSessions(wantReply); - return this; - } +var cksum = function (block) { + var sum = 8 * 32 + for (var i = 0; i < 148; i++) sum += block[i] + for (var j = 156; j < 512; j++) sum += block[j] + return sum +} - if (!wantReply) - return this; +var encodeOct = function (val, n) { + val = val.toString(8) + if (val.length > n) return SEVENS.slice(0, n) + ' ' + else return ZEROS.slice(0, n - val.length) + val + ' ' +} - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); +/* Copied from the node-tar repo and modified to meet + * tar-stream coding standard. + * + * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 + */ +function parse256 (buf) { + // first byte MUST be either 80 or FF + // 80 for positive, FF for 2's comp + var positive + if (buf[0] === 0x80) positive = true + else if (buf[0] === 0xFF) positive = false + else return null - return this; + // build up a base-256 tuple from the least sig to the highest + var tuple = [] + for (var i = buf.length - 1; i > 0; i--) { + var byte = buf[i] + if (positive) tuple.push(byte) + else tuple.push(0xFF - byte) } - openssh_forwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + var sum = 0 + var l = tuple.length + for (i = 0; i < l; i++) { + sum += tuple[i] * Math.pow(256, i) + } - const wantReply = (typeof cb === 'function'); + return positive ? sum : -1 * sum +} - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${socketPath}`)); - return; - } - this._forwardingUnix[socketPath] = true; - cb(); - }); - } +var decodeOct = function (val, offset, length) { + val = val.slice(offset, offset + length) + offset = 0 - this._protocol.openssh_streamLocalForward(socketPath, wantReply); - return this; - } + // If prefixed with 0x80 then parse as a base-256 integer + if (val[offset] & 0x80) { + return parse256(val) + } else { + // Older versions of tar can prefix with spaces + while (offset < val.length && val[offset] === 32) offset++ + var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) + while (offset < end && val[offset] === 0) offset++ + if (end === offset) return 0 + return parseInt(val.slice(offset, end).toString(), 8) + } +} - if (!wantReply) - return this; +var decodeStr = function (val, offset, length, encoding) { + return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding) +} - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); +var addLength = function (str) { + var len = Buffer.byteLength(str) + var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 + if (len + digits >= Math.pow(10, digits)) digits++ - return this; + return (len + digits) + str +} + +exports.decodeLongPath = function (buf, encoding) { + return decodeStr(buf, 0, buf.length, encoding) +} + +exports.encodePax = function (opts) { // TODO: encode more stuff in pax + var result = '' + if (opts.name) result += addLength(' path=' + opts.name + '\n') + if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') + var pax = opts.pax + if (pax) { + for (var key in pax) { + result += addLength(' ' + key + '=' + pax[key] + '\n') + } } + return Buffer.from(result) +} - openssh_unforwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); +exports.decodePax = function (buf) { + var result = {} - const wantReply = (typeof cb === 'function'); + while (buf.length) { + var i = 0 + while (i < buf.length && buf[i] !== 32) i++ + var len = parseInt(buf.slice(0, i).toString(), 10) + if (!len) return result - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${socketPath}`)); - return; - } - delete this._forwardingUnix[socketPath]; - cb(); - }); - } + var b = buf.slice(i + 1, len - 1).toString() + var keyIndex = b.indexOf('=') + if (keyIndex === -1) return result + result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) - this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); - return this; - } + buf = buf.slice(len) + } - if (!wantReply) - return this; + return result +} - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); +exports.encode = function (opts) { + var buf = alloc(512) + var name = opts.name + var prefix = '' - return this; + if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' + if (Buffer.byteLength(name) !== name.length) return null // utf-8 + + while (Buffer.byteLength(name) > 100) { + var i = name.indexOf('/') + if (i === -1) return null + prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) + name = name.slice(i + 1) } - openssh_forwardOutStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null + if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null - if (typeof cb !== 'function') - cb = noop; + buf.write(name) + buf.write(encodeOct(opts.mode & MASK, 6), 100) + buf.write(encodeOct(opts.uid, 6), 108) + buf.write(encodeOct(opts.gid, 6), 116) + buf.write(encodeOct(opts.size, 11), 124) + buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); - return this; - } - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); + buf[156] = ZERO_OFFSET + toTypeflag(opts.type) - return this; - } + if (opts.linkname) buf.write(opts.linkname, 157) - sftp(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + USTAR_MAGIC.copy(buf, MAGIC_OFFSET) + USTAR_VER.copy(buf, VERSION_OFFSET) + if (opts.uname) buf.write(opts.uname, 265) + if (opts.gname) buf.write(opts.gname, 297) + buf.write(encodeOct(opts.devmajor || 0, 6), 329) + buf.write(encodeOct(opts.devminor || 0, 6), 337) - openChannel(this, 'sftp', (err, sftp) => { - if (err) { - cb(err); - return; - } + if (prefix) buf.write(prefix, 345) - reqSubsystem(sftp, 'sftp', (err, sftp_) => { - if (err) { - cb(err); - return; - } + buf.write(encodeOct(cksum(buf), 6), 148) - function removeListeners() { - sftp.removeListener('ready', onReady); - sftp.removeListener('error', onError); - sftp.removeListener('exit', onExit); - sftp.removeListener('close', onExit); - } + return buf +} - function onReady() { - // TODO: do not remove exit/close in case remote end closes the - // channel abruptly and we need to notify outstanding callbacks - removeListeners(); - cb(undefined, sftp); - } +exports.decode = function (buf, filenameEncoding, allowUnknownFormat) { + var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET - function onError(err) { - removeListeners(); - cb(err); - } + var name = decodeStr(buf, 0, 100, filenameEncoding) + var mode = decodeOct(buf, 100, 8) + var uid = decodeOct(buf, 108, 8) + var gid = decodeOct(buf, 116, 8) + var size = decodeOct(buf, 124, 12) + var mtime = decodeOct(buf, 136, 12) + var type = toType(typeflag) + var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) + var uname = decodeStr(buf, 265, 32) + var gname = decodeStr(buf, 297, 32) + var devmajor = decodeOct(buf, 329, 8) + var devminor = decodeOct(buf, 337, 8) - function onExit(code, signal) { - removeListeners(); - let msg; - if (typeof code === 'number') - msg = `Received exit code ${code} while establishing SFTP session`; - else if (signal !== undefined) - msg = `Received signal ${signal} while establishing SFTP session`; - else - msg = 'Received unexpected SFTP session termination'; - const err = new Error(msg); - err.code = code; - err.signal = signal; - cb(err); - } + var c = cksum(buf) - sftp.on('ready', onReady) - .on('error', onError) - .on('exit', onExit) - .on('close', onExit); + // checksum is still initial value if header was null. + if (c === 8 * 32) return null - sftp._init(); - }); - }); + // valid checksum + if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') - return this; + if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { + // ustar (posix) format. + // prepend prefix, if present. + if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name + } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && + GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { + // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and + // multi-volume tarballs. + } else { + if (!allowUnknownFormat) { + throw new Error('Invalid tar header: unknown format.') + } } -} -function openChannel(self, type, opts, cb) { - // Ask the server to open a channel for some purpose - // (e.g. session (sftp, exec, shell), or forwarding a TCP connection - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; + // to support old tar versions that use trailing / to indicate dirs + if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 - if (typeof opts === 'function') { - cb = opts; - opts = {}; + return { + name, + mode, + uid, + gid, + size, + mtime: new Date(1000 * mtime), + type, + linkname, + uname, + gname, + devmajor, + devminor } +} - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } +/***/ }), - switch (type) { - case 'session': - case 'sftp': - self._protocol.session(localChan, initWindow, maxPacket); - break; - case 'direct-tcpip': - self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'direct-streamlocal@openssh.com': - self._protocol.openssh_directStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} +/***/ 1260: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function reqX11(chan, screen, cb) { - // Asks server to start sending us X11 connections - const cfg = { - single: false, - protocol: 'MIT-MAGIC-COOKIE-1', - cookie: undefined, - screen: 0 - }; +exports.extract = __nccwpck_require__(9545) +exports.pack = __nccwpck_require__(2456) - if (typeof screen === 'function') { - cb = screen; - } else if (typeof screen === 'object' && screen !== null) { - if (typeof screen.single === 'boolean') - cfg.single = screen.single; - if (typeof screen.screen === 'number') - cfg.screen = screen.screen; - if (typeof screen.protocol === 'string') - cfg.protocol = screen.protocol; - if (typeof screen.cookie === 'string') - cfg.cookie = screen.cookie; - else if (Buffer.isBuffer(screen.cookie)) - cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); - } - if (cfg.cookie === undefined) - cfg.cookie = randomCookie(); - const wantReply = (typeof cb === 'function'); +/***/ }), - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } +/***/ 2456: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to request X11')); - return; - } +var constants = __nccwpck_require__(3186) +var eos = __nccwpck_require__(1205) +var inherits = __nccwpck_require__(4124) +var alloc = Buffer.alloc - chan._hasX11 = true; - ++chan._client._acceptX11; - chan.once('close', () => { - if (chan._client._acceptX11) - --chan._client._acceptX11; - }); +var Readable = (__nccwpck_require__(1642).Readable) +var Writable = (__nccwpck_require__(1642).Writable) +var StringDecoder = (__nccwpck_require__(1576).StringDecoder) - cb(); - }); - } +var headers = __nccwpck_require__(6834) - chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); -} +var DMODE = parseInt('755', 8) +var FMODE = parseInt('644', 8) -function reqPty(chan, opts, cb) { - let rows = 24; - let cols = 80; - let width = 640; - let height = 480; - let term = 'vt100'; - let modes = null; +var END_OF_TAR = alloc(1024) - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.rows === 'number') - rows = opts.rows; - if (typeof opts.cols === 'number') - cols = opts.cols; - if (typeof opts.width === 'number') - width = opts.width; - if (typeof opts.height === 'number') - height = opts.height; - if (typeof opts.term === 'string') - term = opts.term; - if (typeof opts.modes === 'object') - modes = opts.modes; - } +var noop = function () {} - const wantReply = (typeof cb === 'function'); +var overflow = function (self, size) { + size &= 511 + if (size) self.push(END_OF_TAR.slice(0, 512 - size)) +} - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; +function modeToType (mode) { + switch (mode & constants.S_IFMT) { + case constants.S_IFBLK: return 'block-device' + case constants.S_IFCHR: return 'character-device' + case constants.S_IFDIR: return 'directory' + case constants.S_IFIFO: return 'fifo' + case constants.S_IFLNK: return 'symlink' } - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to request a pseudo-terminal')); - return; - } - cb(); - }); - } + return 'file' +} - chan._client._protocol.pty(chan.outgoing.id, - rows, - cols, - height, - width, - term, - modes, - wantReply); +var Sink = function (to) { + Writable.call(this) + this.written = 0 + this._to = to + this._destroyed = false } -function reqAgentFwd(chan, cb) { - const wantReply = (typeof cb === 'function'); +inherits(Sink, Writable) - if (chan.outgoing.state !== 'open') { - wantReply && cb(new Error('Channel is not open')); - return; - } - if (chan._client._agentFwdEnabled) { - wantReply && cb(false); - return; - } +Sink.prototype._write = function (data, enc, cb) { + this.written += data.length + if (this._to.push(data)) return cb() + this._to._drain = cb +} - chan._client._agentFwdEnabled = true; +Sink.prototype.destroy = function () { + if (this._destroyed) return + this._destroyed = true + this.emit('close') +} - chan._callbacks.push((had_err) => { - if (had_err) { - chan._client._agentFwdEnabled = false; - if (wantReply) { - cb(had_err !== true - ? had_err - : new Error('Unable to request agent forwarding')); - } - return; - } +var LinkSink = function () { + Writable.call(this) + this.linkname = '' + this._decoder = new StringDecoder('utf-8') + this._destroyed = false +} - if (wantReply) - cb(); - }); +inherits(LinkSink, Writable) - chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); +LinkSink.prototype._write = function (data, enc, cb) { + this.linkname += this._decoder.write(data) + cb() } -function reqShell(chan, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } +LinkSink.prototype.destroy = function () { + if (this._destroyed) return + this._destroyed = true + this.emit('close') +} - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to open shell')); - return; - } - chan.subtype = 'shell'; - cb(undefined, chan); - }); +var Void = function () { + Writable.call(this) + this._destroyed = false +} - chan._client._protocol.shell(chan.outgoing.id, true); +inherits(Void, Writable) + +Void.prototype._write = function (data, enc, cb) { + cb(new Error('No body allowed for this entry')) } -function reqExec(chan, cmd, opts, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } +Void.prototype.destroy = function () { + if (this._destroyed) return + this._destroyed = true + this.emit('close') +} - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to exec')); - return; - } - chan.subtype = 'exec'; - chan.allowHalfOpen = (opts.allowHalfOpen !== false); - cb(undefined, chan); - }); +var Pack = function (opts) { + if (!(this instanceof Pack)) return new Pack(opts) + Readable.call(this, opts) - chan._client._protocol.exec(chan.outgoing.id, cmd, true); + this._drain = noop + this._finalized = false + this._finalizing = false + this._destroyed = false + this._stream = null } -function reqEnv(chan, env) { - if (chan.outgoing.state !== 'open') - return; +inherits(Pack, Readable) - const keys = Object.keys(env || {}); +Pack.prototype.entry = function (header, buffer, callback) { + if (this._stream) throw new Error('already piping an entry') + if (this._finalized || this._destroyed) return - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const val = env[key]; - chan._client._protocol.env(chan.outgoing.id, key, val, false); + if (typeof buffer === 'function') { + callback = buffer + buffer = null } -} -function reqSubsystem(chan, name, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; + if (!callback) callback = noop + + var self = this + + if (!header.size || header.type === 'symlink') header.size = 0 + if (!header.type) header.type = modeToType(header.mode) + if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE + if (!header.uid) header.uid = 0 + if (!header.gid) header.gid = 0 + if (!header.mtime) header.mtime = new Date() + + if (typeof buffer === 'string') buffer = Buffer.from(buffer) + if (Buffer.isBuffer(buffer)) { + header.size = buffer.length + this._encode(header) + var ok = this.push(buffer) + overflow(self, header.size) + if (ok) process.nextTick(callback) + else this._drain = callback + return new Void() } - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to start subsystem: ${name}`)); - return; - } - chan.subtype = 'subsystem'; - cb(undefined, chan); - }); + if (header.type === 'symlink' && !header.linkname) { + var linkSink = new LinkSink() + eos(linkSink, function (err) { + if (err) { // stream was closed + self.destroy() + return callback(err) + } - chan._client._protocol.subsystem(chan.outgoing.id, name, true); -} + header.linkname = linkSink.linkname + self._encode(header) + callback() + }) -// TODO: inline implementation into single call site -function onCHANNEL_OPEN(self, info) { - // The server is trying to open a channel with us, this is usually when - // we asked the server to forward us connections on some port and now they - // are asking us to accept/deny an incoming connection on their side + return linkSink + } - let localChan = -1; - let reason; + this._encode(header) - const accept = () => { - const chanInfo = { - type: info.type, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const stream = new Channel(self, chanInfo); - self._chanMgr.update(localChan, stream); + if (header.type !== 'file' && header.type !== 'contiguous-file') { + process.nextTick(callback) + return new Void() + } - self._protocol.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - return stream; - }; - const reject = () => { - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } + var sink = new Sink(this) - if (localChan !== -1) - self._chanMgr.remove(localChan); + this._stream = sink - self._protocol.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = self._chanMgr.add(); + eos(sink, function (err) { + self._stream = null - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of incoming channel open: ' - + 'no channels available' - ); - } + if (err) { // stream was closed + self.destroy() + return callback(err) } - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'forwarded-tcpip': { - const val = self._forwarding[`${data.destIP}:${data.destPort}`]; - if (val !== undefined && reserveChannel()) { - if (data.destPort === 0) - data.destPort = val; - self.emit('tcp connection', data, accept, reject); - return; - } - break; + if (sink.written !== header.size) { // corrupting tar + self.destroy() + return callback(new Error('size mismatch')) } - case 'forwarded-streamlocal@openssh.com': - if (self._forwardingUnix[data.socketPath] !== undefined - && reserveChannel()) { - self.emit('unix connection', data, accept, reject); - return; - } - break; - case 'auth-agent@openssh.com': - if (self._agentFwdEnabled - && typeof self._agent.getStream === 'function' - && reserveChannel()) { - self._agent.getStream((err, stream) => { - if (err) - return reject(); - const upstream = accept(); - upstream.pipe(stream).pipe(upstream); - }); - return; - } - break; - case 'x11': - if (self._acceptX11 !== 0 && reserveChannel()) { - self.emit('x11', data, accept, reject); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unsupported incoming channel open ' - + `type: ${info.type}` - ); - } + overflow(self, header.size) + if (self._finalizing) self.finalize() + callback() + }) + + return sink +} + +Pack.prototype.finalize = function () { + if (this._stream) { + this._finalizing = true + return } - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unexpected incoming channel open for: ' - + info.type - ); + if (this._finalized) return + this._finalized = true + this.push(END_OF_TAR) + this.push(null) +} + +Pack.prototype.destroy = function (err) { + if (this._destroyed) return + this._destroyed = true + + if (err) this.emit('error', err) + this.emit('close') + if (this._stream && this._stream.destroy) this._stream.destroy() +} + +Pack.prototype._encode = function (header) { + if (!header.pax) { + var buf = headers.encode(header) + if (buf) { + this.push(buf) + return } } + this._encodePax(header) +} + +Pack.prototype._encodePax = function (header) { + var paxHeader = headers.encodePax({ + name: header.name, + linkname: header.linkname, + pax: header.pax + }) + + var newHeader = { + name: 'PaxHeader', + mode: header.mode, + uid: header.uid, + gid: header.gid, + size: paxHeader.length, + mtime: header.mtime, + type: 'pax-header', + linkname: header.linkname && 'PaxHeader', + uname: header.uname, + gname: header.gname, + devmajor: header.devmajor, + devminor: header.devminor + } + + this.push(headers.encode(newHeader)) + this.push(paxHeader) + overflow(this, paxHeader.length) + + newHeader.size = header.size + newHeader.type = header.type + this.push(headers.encode(newHeader)) +} - reject(); +Pack.prototype._read = function (n) { + var drain = this._drain + this._drain = noop + drain() } -const randomCookie = (() => { - const buffer = Buffer.allocUnsafe(16); - return () => { - randomFillSync(buffer, 0, 16); - return buffer.hexSlice(0, 16); - }; -})(); +module.exports = Pack -function makeSimpleAuthHandler(authList) { - if (!Array.isArray(authList)) - throw new Error('authList must be an array'); - let a = 0; - return (authsLeft, partialSuccess, cb) => { - if (a === authList.length) - return false; - return authList[a++]; - }; -} +/***/ }), -function hostKeysProve(client, keys_, cb) { - if (!client._sock || !isWritable(client._sock)) - return; +/***/ 4294: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof cb !== 'function') - cb = noop; +module.exports = __nccwpck_require__(4219); - if (!Array.isArray(keys_)) - throw new TypeError('Invalid keys argument type'); - const keys = []; - for (const key of keys_) { - const parsed = parseKey(key); - if (parsed instanceof Error) - throw parsed; - keys.push(parsed); - } +/***/ }), - if (!client.config.strictVendor - || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { - client._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Server failed to prove supplied keys')); - return; - } +/***/ 4219: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // TODO: move all of this parsing/verifying logic out of the client? - const ret = []; - let keyIdx = 0; - bufferParser.init(data, 0); - while (bufferParser.avail()) { - if (keyIdx === keys.length) - break; - const key = keys[keyIdx++]; - const keyPublic = key.getPublicSSH(); +"use strict"; - const sigEntry = bufferParser.readString(); - sigParser.init(sigEntry, 0); - const type = sigParser.readString(true); - let value = sigParser.readString(); - let algo; - if (type !== key.type) { - if (key.type === 'ssh-rsa') { - switch (type) { - case 'rsa-sha2-256': - algo = 'sha256'; - break; - case 'rsa-sha2-512': - algo = 'sha512'; - break; - default: - continue; - } - } else { - continue; - } - } +var net = __nccwpck_require__(1808); +var tls = __nccwpck_require__(4404); +var http = __nccwpck_require__(3685); +var https = __nccwpck_require__(5687); +var events = __nccwpck_require__(2361); +var assert = __nccwpck_require__(9491); +var util = __nccwpck_require__(3837); - const sessionID = client._protocol._kex.sessionID; - const verifyData = Buffer.allocUnsafe( - 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length - ); - let p = 0; - writeUInt32BE(verifyData, 29, p); - verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - writeUInt32BE(verifyData, sessionID.length, p += 29); - bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); - writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); - bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); - if (!(value = sigSSHToASN1(value, type))) - continue; - if (key.verify(verifyData, value, algo) === true) - ret.push(key); - } - sigParser.clear(); - bufferParser.clear(); +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; - cb(null, ret); - }); - client._protocol.openssh_hostKeysProve(keys); - return; - } +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; } -module.exports = Client; +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} -/***/ }), -/***/ 2994: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; -"use strict"; + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; + } + } + socket.destroy(); + self.removeSocket(socket); + }); +} +util.inherits(TunnelingAgent, events.EventEmitter); +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); -const { Agent: HttpAgent } = __nccwpck_require__(3685); -const { Agent: HttpsAgent } = __nccwpck_require__(5687); -const { connect: tlsConnect } = __nccwpck_require__(4404); + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } -let Client; + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); -for (const ctor of [HttpAgent, HttpsAgent]) { - class SSHAgent extends ctor { - constructor(connectCfg, agentOptions) { - super(agentOptions); + function onFree() { + self.emit('free', socket, options); + } - this._connectCfg = connectCfg; - this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); } + }); +}; - createConnection(options, cb) { - const srcIP = (options && options.localAddress) || this._defaultSrcIP; - const srcPort = (options && options.localPort) || 0; - const dstIP = options.host; - const dstPort = options.port; +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); - if (Client === undefined) - Client = __nccwpck_require__(6063); + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port + } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } - const client = new Client(); - let triedForward = false; - client.on('ready', () => { - client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { - triedForward = true; - if (err) { - client.end(); - return cb(err); - } - stream.once('close', () => client.end()); - cb(null, decorateStream(stream, ctor, options)); - }); - }).on('error', cb).on('close', () => { - if (!triedForward) - cb(new Error('Unexpected connection close')); - }).connect(this._connectCfg); + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); + + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); } - exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; -} + function onError(cause) { + connectReq.removeAllListeners(); -function noop() {} + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; -function decorateStream(stream, ctor, options) { - if (ctor === HttpAgent) { - // HTTP - stream.setKeepAlive = noop; - stream.setNoDelay = noop; - stream.setTimeout = noop; - stream.ref = noop; - stream.unref = noop; - stream.destroySoon = stream.destroy; - return stream; +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; } + this.sockets.splice(pos, 1); - // HTTPS - options.socket = stream; - const wrapped = tlsConnect(options); + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); + } +}; - // This is a workaround for a regression in node v12.16.3+ - // https://github.com/nodejs/node/issues/35904 - const onClose = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (stream.isPaused()) - stream.resume(); +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); + + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} + + +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress }; - })(); - // 'end' listener is needed because 'close' is not emitted in some scenarios - // in node v12.x for some unknown reason - wrapped.on('end', onClose).on('close', onClose); + } + return host; // for v0.11 or later +} - return wrapped; +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } + } + } + } + return target; +} + + +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); + } + console.error.apply(console, args); + } +} else { + debug = function() {}; } +exports.debug = debug; // for test /***/ }), -/***/ 5869: +/***/ 8729: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +(function(nacl) { +'use strict'; -const { - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - OpenSSHAgent, - PageantAgent, -} = __nccwpck_require__(9054); -const { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent, -} = __nccwpck_require__(2994); -const { parseKey } = __nccwpck_require__(2218); -const { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, -} = __nccwpck_require__(2026); +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ -module.exports = { - AgentProtocol, - BaseAgent, - createAgent, - Client: __nccwpck_require__(6063), - CygwinAgent, - HTTPAgent, - HTTPSAgent, - OpenSSHAgent, - PageantAgent, - Server: __nccwpck_require__(2986), - utils: { - parseKey, - sftp: { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, - }, - }, +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; }; +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; -/***/ }), + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); -/***/ 9031: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); -"use strict"; -/* - TODO: - * Replace `buffer._pos` usage in keyParser.js and elsewhere - * Utilize optional "writev" support when writing packets from - cipher.encrypt() - * Built-in support for automatic re-keying, on by default - * Revisit receiving unexpected/unknown packets - * Error (fatal or otherwise) or ignore or pass on to user (in some or all - cases)? - * Including server/client check for single directional packet types? - * Check packets for validity or bail as early as possible? - * Automatic re-key every 2**31 packets after the last key exchange (sent or - received), as suggested by RFC4344. OpenSSH currently does this. - * Automatic re-key every so many blocks depending on cipher. RFC4344: - Because of a birthday property of block ciphers and some modes of - operation, implementations must be careful not to encrypt too many - blocks with the same encryption key. + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); - Let L be the block length (in bits) of an SSH encryption method's - block cipher (e.g., 128 for AES). If L is at least 128, then, after - rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) - blocks before rekeying again. If L is at least 128, then SSH - implementations should also attempt to force a rekey before receiving - more than 2**(L/4) blocks. If L is less than 128 (which is the case - for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, - although it may be too expensive to rekey every 2**(L/4) blocks, it - is still advisable for SSH implementations to follow the original - recommendation in [RFC4253]: rekey at least once for every gigabyte - of transmitted data. + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); - Note that if L is less than or equal to 128, then the recommendation - in this subsection supersedes the recommendation in Section 3.1. If - an SSH implementation uses a block cipher with a larger block size - (e.g., Rijndael with 256-bit blocks), then the recommendations in - Section 3.1 may supersede the recommendations in this subsection - (depending on the lengths of the packets). -*/ + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); -const { inspect } = __nccwpck_require__(3837); + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; -const { bindingAvailable, NullCipher, NullDecipher } = __nccwpck_require__(5708); -const { - COMPAT_CHECKS, - DISCONNECT_REASON, - MESSAGE, - SIGNALS, - TERMINAL_MODE, -} = __nccwpck_require__(6832); -const { - DEFAULT_KEXINIT, - KexInit, - kexinit, - onKEXPayload, -} = __nccwpck_require__(4126); -const { - parseKey, -} = __nccwpck_require__(2218); -const MESSAGE_HANDLERS = __nccwpck_require__(172); -const { - bufferCopy, - bufferFill, - bufferSlice, - convertSignature, - sendPacket, - writeUInt32BE, -} = __nccwpck_require__(9475); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = __nccwpck_require__(6715); + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; -const MODULE_VER = (__nccwpck_require__(6674)/* .version */ .i8); + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; -const VALID_DISCONNECT_REASONS = new Map( - Object.values(DISCONNECT_REASON).map((n) => [n, 1]) -); -const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); -const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); -const MAX_LINE_LEN = 8192; -const MAX_LINES = 1024; -const PING_PAYLOAD = Buffer.from([ - MESSAGE.GLOBAL_REQUEST, - // "keepalive@openssh.com" - 0, 0, 0, 21, - 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, - 115, 104, 46, 99, 111, 109, - // Request a reply - 1, -]); -const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; -function noop() {} + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; -/* - Inbound: - * kexinit payload (needed only until exchange hash is generated) - * raw ident - * rekey packet queue - * expected packet (implemented as separate _parse() function?) - Outbound: - * kexinit payload (needed only until exchange hash is generated) - * rekey packet queue - * kex secret (needed only until NEWKEYS) - * exchange hash (needed only until NEWKEYS) - * session ID (set to exchange hash from initial handshake) -*/ -class Protocol { - constructor(config) { - const onWrite = config.onWrite; - if (typeof onWrite !== 'function') - throw new Error('Missing onWrite function'); - this._onWrite = (data) => { onWrite(data); }; + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; - const onError = config.onError; - if (typeof onError !== 'function') - throw new Error('Missing onError function'); - this._onError = (err) => { onError(err); }; + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; - const debug = config.debug; - this._debug = (typeof debug === 'function' - ? (msg) => { debug(msg); } - : undefined); + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; - const onHeader = config.onHeader; - this._onHeader = (typeof onHeader === 'function' - ? (...args) => { onHeader(...args); } - : noop); + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; - const onPacket = config.onPacket; - this._onPacket = (typeof onPacket === 'function' - ? () => { onPacket(); } - : noop); + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; - let onHandshakeComplete = config.onHandshakeComplete; - if (typeof onHandshakeComplete !== 'function') - onHandshakeComplete = noop; - this._onHandshakeComplete = (...args) => { - this._debug && this._debug('Handshake completed'); + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; - // Process packets queued during a rekey where necessary - const oldQueue = this._queue; - if (oldQueue) { - this._queue = undefined; - this._debug && this._debug( - `Draining outbound queue (${oldQueue.length}) ...` - ); - for (let i = 0; i < oldQueue.length; ++i) { - const data = oldQueue[i]; - // data === payload only + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; - // XXX: hacky - let finalized = this._packetRW.write.finalize(data); - if (finalized === data) { - const packet = this._cipher.allocPacket(data.length); - packet.set(data, 5); - finalized = packet; - } + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; - sendPacket(this, finalized); - } - this._debug && this._debug('... finished draining outbound queue'); - } + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; - onHandshakeComplete(...args); - }; - this._queue = undefined; + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; - const messageHandlers = config.messageHandlers; - if (typeof messageHandlers === 'object' && messageHandlers !== null) - this._handlers = messageHandlers; - else - this._handlers = {}; + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; - this._onPayload = onPayload.bind(this); + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} - this._server = !!config.server; - this._banner = undefined; - let greeting; - if (this._server) { - if (typeof config.hostKeys !== 'object' || config.hostKeys === null) - throw new Error('Missing server host key(s)'); - this._hostKeys = config.hostKeys; +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; - // Greeting displayed before the ssh identification string is sent, this - // is usually ignored by most clients - if (typeof config.greeting === 'string' && config.greeting.length) { - greeting = (config.greeting.slice(-2) === '\r\n' - ? config.greeting - : `${config.greeting}\r\n`); - } + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; - // Banner shown after the handshake completes, but before user - // authentication begins - if (typeof config.banner === 'string' && config.banner.length) { - this._banner = (config.banner.slice(-2) === '\r\n' - ? config.banner - : `${config.banner}\r\n`); - } - } else { - this._hostKeys = undefined; - } + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); - let offer = config.offer; - if (typeof offer !== 'object' || offer === null) - offer = DEFAULT_KEXINIT; - else if (offer.constructor !== KexInit) - offer = new KexInit(offer); - this._kex = undefined; - this._kexinit = undefined; - this._offer = offer; - this._cipher = new NullCipher(0, this._onWrite); - this._decipher = undefined; - this._skipNextInboundPacket = false; - this._packetRW = { - read: new PacketReader(), - write: new PacketWriter(this), - }; - this._hostVerifier = (!this._server - && typeof config.hostVerifier === 'function' - ? config.hostVerifier - : undefined); + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); - this._parse = parseHeader; - this._buffer = undefined; - this._authsQueue = []; - this._authenticated = false; - this._remoteIdentRaw = undefined; - let sentIdent; - if (typeof config.ident === 'string') { - this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); - sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); - sentIdent.set(this._identRaw, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else if (Buffer.isBuffer(config.ident)) { - const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); - fullIdent.latin1Write('SSH-2.0-', 0, 8); - fullIdent.set(config.ident, 8); - this._identRaw = fullIdent; + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); - sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); - sentIdent.set(fullIdent, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else { - this._identRaw = IDENT_RAW; - sentIdent = IDENT; - } - this._compatFlags = 0; + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); - if (this._debug) { - if (bindingAvailable) - this._debug('Custom crypto binding available'); - else - this._debug('Custom crypto binding not available'); - } + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); - this._debug && this._debug( - `Local ident: ${inspect(this._identRaw.toString())}` - ); - this.start = () => { - this.start = undefined; - if (greeting) - this._onWrite(greeting); - this._onWrite(sentIdent); - }; - } - _destruct(reason) { - this._packetRW.read.cleanup(); - this._packetRW.write.cleanup(); - this._cipher && this._cipher.free(); - this._decipher && this._decipher.free(); - if (typeof reason !== 'string' || reason.length === 0) - reason = 'fatal error'; - this.parse = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._onWrite = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._destruct = undefined; - } - cleanup() { - this._destruct && this._destruct(); - } - parse(chunk, i, len) { - while (i < len) - i = this._parse(chunk, i, len); + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); } - // Protocol message API + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; - // =========================================================================== - // Common/Shared ============================================================= - // =========================================================================== + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; - // Global - // ------ - disconnect(reason) { - const pktLen = 1 + 4 + 4 + 4; - // We don't use _packetRW.write.* here because we need to make sure that - // we always get a full packet allocated because this message can be sent - // at any time -- even during a key exchange - let p = this._packetRW.write.allocStartKEX; - const packet = this._packetRW.write.alloc(pktLen, true); - const end = p + pktLen; + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; - if (!VALID_DISCONNECT_REASONS.has(reason)) - reason = DISCONNECT_REASON.PROTOCOL_ERROR; + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; - packet[p] = MESSAGE.DISCONNECT; - writeUInt32BE(packet, reason, ++p); - packet.fill(0, p += 4, end); + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; - this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); - sendPacket(this, this._packetRW.write.finalize(packet, true), true); - } - ping() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; - packet.set(PING_PAYLOAD, p); + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; - this._debug && this._debug( - 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} + +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; } - rekey() { - if (this._kexinit === undefined) { - this._debug && this._debug('Outbound: Initiated explicit rekey'); - this._queue = []; - kexinit(this); - } else { - this._debug && this._debug('Outbound: Ignoring rekey during handshake'); + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; } + return 0; +} - // 'ssh-connection' service-specific - // --------------------------------- - requestSuccess(data) { - let p = this._packetRW.write.allocStart; - let packet; - if (Buffer.isBuffer(data)) { - packet = this._packetRW.write.alloc(1 + data.length); +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} - packet[p] = MESSAGE.REQUEST_SUCCESS; +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} - packet.set(data, ++p); - } else { - packet = this._packetRW.write.alloc(1); +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ - packet[p] = MESSAGE.REQUEST_SUCCESS; - } +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; - this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - requestFailure() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); + var t0, t1, t2, t3, t4, t5, t6, t7; - packet[p] = MESSAGE.REQUEST_FAILURE; + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; - this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelSuccess(chan) { - // Does not consume window space + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - packet[p] = MESSAGE.CHANNEL_SUCCESS; + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; - writeUInt32BE(packet, chan, ++p); + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; - this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelFailure(chan) { - // Does not consume window space + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); + c = 0; - packet[p] = MESSAGE.CHANNEL_FAILURE; + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; - writeUInt32BE(packet, chan, ++p); + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; - this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelEOF(chan) { - // Does not consume window space + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; - packet[p] = MESSAGE.CHANNEL_EOF; + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; - writeUInt32BE(packet, chan, ++p); + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; - this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelClose(chan) { - // Does not consume window space + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; - packet[p] = MESSAGE.CHANNEL_CLOSE; + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; - writeUInt32BE(packet, chan, ++p); + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; - this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; } - channelWindowAdjust(chan, amount) { - // Does not consume window space + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4); +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; - packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } - writeUInt32BE(packet, chan, ++p); + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; - writeUInt32BE(packet, amount, p += 4); + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); - this._debug && this._debug( - `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; } - channelData(chan, data) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); - packet[p] = MESSAGE.CHANNEL_DATA; + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; - writeUInt32BE(packet, chan, ++p); +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; - writeUInt32BE(packet, dataLen, p += 4); + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } - this._debug && this._debug( - `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; } - channelExtData(chan, data, type) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); +}; - packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} - writeUInt32BE(packet, chan, ++p); +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} - writeUInt32BE(packet, type, p += 4); +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} - writeUInt32BE(packet, dataLen, p += 4); +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} - this._debug - && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; } - channelOpenConfirm(remote, local, initWindow, maxPacket) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); + o[0] += c-1 + 37 * (c-1); +} - packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} - writeUInt32BE(packet, remote, ++p); +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} - writeUInt32BE(packet, local, p += 4); +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} - writeUInt32BE(packet, initWindow, p += 4); +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} - writeUInt32BE(packet, maxPacket, p += 4); +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenFail(remote, reason, desc) { - if (typeof desc !== 'string') - desc = ''; +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} - const descLen = Buffer.byteLength(desc); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} - packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; - writeUInt32BE(packet, remote, ++p); + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - writeUInt32BE(packet, reason, p += 4); + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} - writeUInt32BE(packet, descLen, p += 4); +function S(o, a) { + M(o, a, a); +} - p += 4; - if (descLen) { - packet.utf8Write(desc, p, descLen); - p += descLen; - } +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} - writeUInt32BE(packet, 0, p); // Empty language tag +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); - sendPacket(this, this._packetRW.write.finalize(packet)); +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} - // Global - // ------ - service(name) { - if (this._server) - throw new Error('Client-only method called in server mode'); +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + nameLen); +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} - packet[p] = MESSAGE.SERVICE_REQUEST; +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} - this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} - // 'ssh-userauth' service-specific - // ------------------------------- - authPassword(username, password, newPassword) { - if (this._server) - throw new Error('Client-only method called in server mode'); +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; - const userLen = Buffer.byteLength(username); - const passLen = Buffer.byteLength(password); - const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen - + (newPassword ? 4 + newPassLen : 0) - ); +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; - packet[p] = MESSAGE.USERAUTH_REQUEST; + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; - writeUInt32BE(packet, 8, p += 14); - packet.utf8Write('password', p += 4, 8); + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; - packet[p += 8] = (newPassword ? 1 : 0); + // add + h = ah7; + l = al7; - writeUInt32BE(packet, passLen, ++p); - if (Buffer.isBuffer(password)) - bufferCopy(password, packet, 0, passLen, p += 4); - else - packet.utf8Write(password, p += 4, passLen); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (newPassword) { - writeUInt32BE(packet, newPassLen, p += passLen); - if (Buffer.isBuffer(newPassword)) - bufferCopy(newPassword, packet, 0, newPassLen, p += 4); - else - packet.utf8Write(newPassword, p += 4, newPassLen); - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (changed password)' - ); - } else { - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (password)' - ); - } + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); - this._authsQueue.push('password'); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPK(username, pubKey, cbSign) { - if (this._server) - throw new Error('Client-only method called in server mode'); + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); + // K + h = K[i*2]; + l = K[i*2+1]; - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyType); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const payloadLen = - (cbSign ? 4 + sesLen : 0) - + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; - let packet; - let p; - if (cbSign) { - packet = Buffer.allocUnsafe(payloadLen); - p = 0; - writeUInt32BE(packet, sesLen, p); - packet.set(sessionID, p += 4); - p += sesLen; - } else { - packet = this._packetRW.write.alloc(payloadLen); - p = this._packetRW.write.allocStart; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - packet[p] = MESSAGE.USERAUTH_REQUEST; + // w + h = wh[i%16]; + l = wl[i%16]; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; - packet[p += 9] = (cbSign ? 1 : 0); + // add + h = th; + l = tl; - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyType, p += 4, algoLen); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); - if (!cbSign) { - this._authsQueue.push('publickey'); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - return; - } + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); - cbSign(packet, (signature) => { - signature = convertSignature(signature, keyType); - if (signature === false) - throw new Error('Error while converting handshake signature'); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - const sigLen = signature.length; - p = this._packetRW.write.allocStart; - packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 - + 4 + algoLen + 4 + sigLen - ); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - // TODO: simply copy from original "packet" to new `packet` to avoid - // having to write each individual field a second time? - packet[p] = MESSAGE.USERAUTH_REQUEST; + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); + // add + h = bh3; + l = bl3; - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); + h = th; + l = tl; - packet[p += 9] = 1; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyType, p += 4, algoLen); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyType, p += 4, algoLen); + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; - // Servers shouldn't send packet type 60 in response to signed publickey - // attempts, but if they do, interpret as type 60. - this._authsQueue.push('publickey'); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authHostbased(username, pubKey, hostname, userlocal, cbSign) { - // TODO: Make DRY by sharing similar code with authPK() - if (this._server) - throw new Error('Client-only method called in server mode'); + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyType); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const hostnameLen = Buffer.byteLength(hostname); - const userlocalLen = Buffer.byteLength(userlocal); - const data = Buffer.allocUnsafe( - 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen - + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen - ); - let p = 0; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - writeUInt32BE(data, sesLen, p); - data.set(sessionID, p += 4); + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); - data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - writeUInt32BE(data, userLen, ++p); - data.utf8Write(username, p += 4, userLen); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - writeUInt32BE(data, 14, p += userLen); - data.utf8Write('ssh-connection', p += 4, 14); + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } - writeUInt32BE(data, 9, p += 14); - data.utf8Write('hostbased', p += 4, 9); + // add + h = ah0; + l = al0; - writeUInt32BE(data, algoLen, p += 9); - data.utf8Write(keyType, p += 4, algoLen); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; - writeUInt32BE(data, pubKeyLen, p += algoLen); - data.set(pubKey, p += 4); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - writeUInt32BE(data, hostnameLen, p += pubKeyLen); - data.utf8Write(hostname, p += 4, hostnameLen); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - writeUInt32BE(data, userlocalLen, p += hostnameLen); - data.utf8Write(userlocal, p += 4, userlocalLen); + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); - cbSign(data, (signature) => { - signature = convertSignature(signature, keyType); - if (!signature) - throw new Error('Error while converting handshake signature'); + h = ah1; + l = al1; - const sigLen = signature.length; - const reqDataLen = (data.length - sesLen - 4); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - reqDataLen + 4 + 4 + algoLen + 4 + sigLen - ); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - bufferCopy(data, packet, 4 + sesLen, data.length, p); + h = hh[1]; + l = hl[1]; - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyType, p += 4, algoLen); - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - this._authsQueue.push('hostbased'); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (hostbased)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authKeyboard(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 - ); + h = ah2; + l = al2; - packet[p] = MESSAGE.USERAUTH_REQUEST; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); + h = hh[2]; + l = hl[2]; - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - writeUInt32BE(packet, 20, p += 14); - packet.utf8Write('keyboard-interactive', p += 4, 20); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - writeUInt32BE(packet, 0, p += 20); + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); - writeUInt32BE(packet, 0, p += 4); + h = ah3; + l = al3; - this._authsQueue.push('keyboard-interactive'); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authNone(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); + h = hh[3]; + l = hl[3]; - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - packet[p] = MESSAGE.USERAUTH_REQUEST; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); + h = ah4; + l = al4; - writeUInt32BE(packet, 4, p += 14); - packet.utf8Write('none', p += 4, 4); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - this._authsQueue.push('none'); + h = hh[4]; + l = hl[4]; - this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoRes(responses) { - if (this._server) - throw new Error('Client-only method called in server mode'); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - let responsesTotalLen = 0; - let responseLens; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - if (responses) { - responseLens = new Array(responses.length); - for (let i = 0; i < responses.length; ++i) { - const len = Buffer.byteLength(responses[i]); - responseLens[i] = len; - responsesTotalLen += 4 + len; - } - } + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); + h = ah5; + l = al5; - packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (responses) { - writeUInt32BE(packet, responses.length, ++p); - p += 4; - for (let i = 0; i < responses.length; ++i) { - const len = responseLens[i]; - writeUInt32BE(packet, len, p); - p += 4; - if (len) { - packet.utf8Write(responses[i], p, len); - p += len; - } - } - } else { - writeUInt32BE(packet, 0, ++p); - } + h = hh[5]; + l = hl[5]; - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // 'ssh-connection' service-specific - // --------------------------------- - tcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); - packet[p] = MESSAGE.GLOBAL_REQUEST; + h = ah6; + l = al6; - writeUInt32BE(packet, 13, ++p); - packet.utf8Write('tcpip-forward', p += 4, 13); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); + h = hh[6]; + l = hl[6]; - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - writeUInt32BE(packet, bindPort, p += addrLen); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - cancelTcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); + h = ah7; + l = al7; - packet[p] = MESSAGE.GLOBAL_REQUEST; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - writeUInt32BE(packet, 20, ++p); - packet.utf8Write('cancel-tcpip-forward', p += 4, 20); + h = hh[7]; + l = hl[7]; - packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - writeUInt32BE(packet, bindPort, p += addrLen); + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); + pos += 128; + n -= 128; } - openssh_streamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 31 + 1 + 4 + socketPathLen - ); - packet[p] = MESSAGE.GLOBAL_REQUEST; + return n; +} - writeUInt32BE(packet, 31, ++p); - packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; - packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_cancelStreamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 38 + 1 + 4 + socketPathLen - ); + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; - packet[p] = MESSAGE.GLOBAL_REQUEST; + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); - writeUInt32BE(packet, 38, ++p); - packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); - packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); + return 0; +} - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST ' - + '(cancel-streamlocal-forward@openssh.com)' - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - directTcpip(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); - const srcLen = Buffer.byteLength(cfg.srcIP); - const dstLen = Buffer.byteLength(cfg.dstIP); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 - ); + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} - packet[p] = MESSAGE.CHANNEL_OPEN; +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} - writeUInt32BE(packet, 12, ++p); - packet.utf8Write('direct-tcpip', p += 4, 12); +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} - writeUInt32BE(packet, chan, p += 12); +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} - writeUInt32BE(packet, initWindow, p += 4); +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} - writeUInt32BE(packet, maxPacket, p += 4); +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; - writeUInt32BE(packet, dstLen, p += 4); - packet.utf8Write(cfg.dstIP, p += 4, dstLen); + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - writeUInt32BE(packet, cfg.dstPort, p += dstLen); + scalarbase(p, d); + pack(pk, p); - writeUInt32BE(packet, srcLen, p += 4); - packet.utf8Write(cfg.srcIP, p += 4, srcLen); + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} - writeUInt32BE(packet, cfg.srcPort, p += srcLen); +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; } - openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} - writeUInt32BE(packet, 30, ++p); - packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} - writeUInt32BE(packet, chan, p += 30); +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; - writeUInt32BE(packet, initWindow, p += 4); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - writeUInt32BE(packet, maxPacket, p += 4); + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - // zero-fill reserved fields (string and uint32) - bufferFill(packet, 0, p += pathLen, p + 8); + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, direct-streamlocal@openssh.com)` - ); + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; } - sendPacket(this, this._packetRW.write.finalize(packet)); } - openssh_noMoreSessions(wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); - packet[p] = MESSAGE.GLOBAL_REQUEST; + modL(sm.subarray(32), x); + return smlen; +} - writeUInt32BE(packet, 28, ++p); - packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); - packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - session(chan, initWindow, maxPacket) { - if (this._server) - throw new Error('Client-only method called in server mode'); + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); - // Does not consume window space + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); - packet[p] = MESSAGE.CHANNEL_OPEN; + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; - writeUInt32BE(packet, 7, ++p); - packet.utf8Write('session', p += 4, 7); + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - writeUInt32BE(packet, chan, p += 7); + M(r[3], r[0], r[1]); + return 0; +} - writeUInt32BE(packet, initWindow, p += 4); +function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; - writeUInt32BE(packet, maxPacket, p += 4); + mlen = -1; + if (n < 64) return -1; - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - windowChange(chan, rows, cols, height, width) { - if (this._server) - throw new Error('Client-only method called in server mode'); + if (unpackneg(q, pk)) return -1; - // Does not consume window space + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 - ); + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); - packet[p] = MESSAGE.CHANNEL_REQUEST; + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } - writeUInt32BE(packet, chan, ++p); + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + mlen = n; + return mlen; +} - writeUInt32BE(packet, 13, p += 4); - packet.utf8Write('window-change', p += 4, 13); +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; - packet[p += 13] = 0; +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, - writeUInt32BE(packet, cols, ++p); + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES +}; - writeUInt32BE(packet, rows, p += 4); +/* High-level API */ - writeUInt32BE(packet, width, p += 4); +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} - writeUInt32BE(packet, height, p += 4); +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +function checkArrayTypes() { + var t, i; + for (i = 0; i < arguments.length; i++) { + if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') + throw new TypeError('unexpected type ' + t + ', use Uint8Array'); } - pty(chan, rows, cols, height, width, term, modes, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +} - // Does not consume window space +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} - if (!term || !term.length) - term = 'vt100'; - if (modes - && !Buffer.isBuffer(modes) - && !Array.isArray(modes) - && typeof modes === 'object' - && modes !== null) { - modes = modesToBytes(modes); - } - if (!modes || !modes.length) - modes = NO_TERMINAL_MODES_BUFFER; +// TODO: Completely remove this in v0.15. +if (!nacl.util) { + nacl.util = {}; + nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { + throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); + }; +} - const termLen = term.length; - const modesLen = modes.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen - ); +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; - packet[p] = MESSAGE.CHANNEL_REQUEST; +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; - writeUInt32BE(packet, chan, ++p); +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return false; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('pty-req', p += 4, 7); +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; - writeUInt32BE(packet, termLen, ++p); - packet.utf8Write(term, p += 4, termLen); +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; - writeUInt32BE(packet, cols, p += termLen); +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - writeUInt32BE(packet, rows, p += 4); +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; - writeUInt32BE(packet, width, p += 4); +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; - writeUInt32BE(packet, height, p += 4); +nacl.box.after = nacl.secretbox; - writeUInt32BE(packet, modesLen, p += 4); - p += 4; - if (Array.isArray(modes)) { - for (let i = 0; i < modesLen; ++i) - packet[p++] = modes[i]; - } else if (Buffer.isBuffer(modes)) { - packet.set(modes, p); - } +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - shell(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +nacl.box.open.after = nacl.secretbox.open; - // Does not consume window space +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; - packet[p] = MESSAGE.CHANNEL_REQUEST; +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; - writeUInt32BE(packet, chan, ++p); +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; - writeUInt32BE(packet, 5, p += 4); - packet.utf8Write('shell', p += 4, 5); +nacl.sign.open = function(signedMsg, publicKey) { + if (arguments.length !== 2) + throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; - packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exec(chan, cmd, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; - // Does not consume window space +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; - const isBuf = Buffer.isBuffer(cmd); - const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; - packet[p] = MESSAGE.CHANNEL_REQUEST; +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; - writeUInt32BE(packet, chan, ++p); +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; - writeUInt32BE(packet, 4, p += 4); - packet.utf8Write('exec', p += 4, 4); +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; - packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); +nacl.hash.hashLength = crypto_hash_BYTES; - writeUInt32BE(packet, cmdLen, ++p); - if (isBuf) - packet.set(cmd, p += 4); - else - packet.utf8Write(cmd, p += 4, cmdLen); +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (true) { + // Node.js. + crypto = __nccwpck_require__(6113); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } } - signal(chan, signal) { - if (this._server) - throw new Error('Client-only method called in server mode'); +})(); - // Does not consume window space +})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); - const origSignal = signal; - signal = signal.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); +/***/ }), - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); +/***/ 1773: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const signalLen = signal.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 6 + 1 + 4 + signalLen - ); +"use strict"; - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); +const Client = __nccwpck_require__(3598) +const Dispatcher = __nccwpck_require__(412) +const errors = __nccwpck_require__(8045) +const Pool = __nccwpck_require__(4634) +const BalancedPool = __nccwpck_require__(7931) +const Agent = __nccwpck_require__(7890) +const util = __nccwpck_require__(3983) +const { InvalidArgumentError } = errors +const api = __nccwpck_require__(4059) +const buildConnector = __nccwpck_require__(2067) +const MockClient = __nccwpck_require__(8687) +const MockAgent = __nccwpck_require__(6771) +const MockPool = __nccwpck_require__(6193) +const mockErrors = __nccwpck_require__(888) +const ProxyAgent = __nccwpck_require__(7858) +const RetryHandler = __nccwpck_require__(2286) +const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(1892) +const DecoratorHandler = __nccwpck_require__(6930) +const RedirectHandler = __nccwpck_require__(2860) +const createRedirectInterceptor = __nccwpck_require__(8861) + +let hasCrypto +try { + __nccwpck_require__(6113) + hasCrypto = true +} catch { + hasCrypto = false +} - writeUInt32BE(packet, 6, p += 4); - packet.utf8Write('signal', p += 4, 6); +Object.assign(Dispatcher.prototype, api) - packet[p += 6] = 0; +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent +module.exports.RetryHandler = RetryHandler - writeUInt32BE(packet, signalLen, ++p); - packet.utf8Write(signal, p += 4, signalLen); +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - env(chan, key, val, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +module.exports.buildConnector = buildConnector +module.exports.errors = errors - // Does not consume window space +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } - const keyLen = Buffer.byteLength(key); - const isBuf = Buffer.isBuffer(val); - const valLen = (isBuf ? val.length : Buffer.byteLength(val)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen - ); + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } - packet[p] = MESSAGE.CHANNEL_REQUEST; + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - writeUInt32BE(packet, chan, ++p); + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } - writeUInt32BE(packet, 3, p += 4); - packet.utf8Write('env', p += 4, 3); + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } - packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } - writeUInt32BE(packet, keyLen, ++p); - packet.utf8Write(key, p += 4, keyLen); + url = util.parseURL(url) + } - writeUInt32BE(packet, valLen, p += keyLen); - if (isBuf) - packet.set(val, p += 4); - else - packet.utf8Write(val, p += 4, valLen); + const { agent, dispatcher = getGlobalDispatcher() } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) } - x11Forward(chan, cfg, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +} - // Does not consume window space +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher - const protocol = cfg.protocol; - const cookie = cfg.cookie; - const isBufProto = Buffer.isBuffer(protocol); - const protoLen = (isBufProto - ? protocol.length - : Buffer.byteLength(protocol)); - const isBufCookie = Buffer.isBuffer(cookie); - const cookieLen = (isBufCookie - ? cookie.length - : Buffer.byteLength(cookie)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 - ); +if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { + let fetchImpl = null + module.exports.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = (__nccwpck_require__(4881).fetch) + } - packet[p] = MESSAGE.CHANNEL_REQUEST; + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) + } - writeUInt32BE(packet, chan, ++p); + throw err + } + } + module.exports.Headers = __nccwpck_require__(554).Headers + module.exports.Response = __nccwpck_require__(7823).Response + module.exports.Request = __nccwpck_require__(8359).Request + module.exports.FormData = __nccwpck_require__(2015).FormData + module.exports.File = __nccwpck_require__(8511).File + module.exports.FileReader = __nccwpck_require__(1446).FileReader - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('x11-req', p += 4, 7); + const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1246) - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin - packet[++p] = (cfg.single ? 1 : 0); + const { CacheStorage } = __nccwpck_require__(7907) + const { kConstruct } = __nccwpck_require__(9174) - writeUInt32BE(packet, protoLen, ++p); - if (isBufProto) - packet.set(protocol, p += 4); - else - packet.utf8Write(protocol, p += 4, protoLen); + // Cache & CacheStorage are tightly coupled with fetch. Even if it may run + // in an older version of Node, it doesn't have any use without fetch. + module.exports.caches = new CacheStorage(kConstruct) +} - writeUInt32BE(packet, cookieLen, p += protoLen); - if (isBufCookie) - packet.set(cookie, p += 4); - else - packet.latin1Write(cookie, p += 4, cookieLen); +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(1724) - writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - subsystem(chan, name, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); + const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) - // Does not consume window space - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType +} - packet[p] = MESSAGE.CHANNEL_REQUEST; +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = __nccwpck_require__(4284) - writeUInt32BE(packet, chan, ++p); + module.exports.WebSocket = WebSocket +} - writeUInt32BE(packet, 9, p += 4); - packet.utf8Write('subsystem', p += 4, 9); +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) - packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_agentForward(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +/***/ }), - // Does not consume window space +/***/ 7890: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); +"use strict"; - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(2785) +const DispatcherBase = __nccwpck_require__(4839) +const Pool = __nccwpck_require__(4634) +const Client = __nccwpck_require__(3598) +const util = __nccwpck_require__(3983) +const createRedirectInterceptor = __nccwpck_require__(8861) +const { WeakRef, FinalizationRegistry } = __nccwpck_require__(6436)() - writeUInt32BE(packet, 26, p += 4); - packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kMaxRedirections = Symbol('maxRedirections') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kFinalizer = Symbol('finalizer') +const kOptions = Symbol('options') - packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_REQUEST ' - + `(r:${chan}, auth-agent-req@openssh.com)` - ); +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super() + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_hostKeysProve(keys) { - if (this._server) - throw new Error('Client-only method called in server mode'); - let keysTotal = 0; - const publicKeys = []; - for (const key of keys) { - const publicKey = key.getPublicSSH(); - keysTotal += 4 + publicKey.length; - publicKeys.push(publicKey); + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') } - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } - packet[p] = MESSAGE.GLOBAL_REQUEST; + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } - writeUInt32BE(packet, 29, ++p); - packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); + this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] - packet[p += 29] = 1; // want reply + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kMaxRedirections] = maxRedirections + this[kFactory] = factory + this[kClients] = new Map() + this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { + const ref = this[kClients].get(key) + if (ref !== undefined && ref.deref() === undefined) { + this[kClients].delete(key) + } + }) - ++p; - for (const buf of publicKeys) { - writeUInt32BE(packet, buf.length, p); - bufferCopy(buf, packet, 0, buf.length, p += 4); - p += buf.length; + const agent = this + + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) } - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' - ); + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } - // Global - // ------ - serviceAccept(svcName) { - if (!this._server) - throw new Error('Server-only method called in client mode'); + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } + } - const svcNameLen = Buffer.byteLength(svcName); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); + get [kRunning] () { + let ret = 0 + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore next: gc is undeterministic */ + if (client) { + ret += client[kRunning] + } + } + return ret + } - packet[p] = MESSAGE.SERVICE_ACCEPT; + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } - writeUInt32BE(packet, svcNameLen, ++p); - packet.utf8Write(svcName, p += 4, svcNameLen); + const ref = this[kClients].get(key) - this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); - sendPacket(this, this._packetRW.write.finalize(packet)); + let dispatcher = ref ? ref.deref() : null + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) - if (this._server && this._banner && svcName === 'ssh-userauth') { - const banner = this._banner; - this._banner = undefined; // Prevent banner from being displayed again - const bannerLen = Buffer.byteLength(banner); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) + } - packet[p] = MESSAGE.USERAUTH_BANNER; + return dispatcher.dispatch(opts, handler) + } - writeUInt32BE(packet, bannerLen, ++p); - packet.utf8Write(banner, p += 4, bannerLen); + async [kClose] () { + const closePromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + closePromises.push(client.close()) + } + } - writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag + await Promise.all(closePromises) + } - this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); - sendPacket(this, this._packetRW.write.finalize(packet)); + async [kDestroy] (err) { + const destroyPromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + destroyPromises.push(client.destroy(err)) + } } + + await Promise.all(destroyPromises) } - // 'ssh-connection' service-specific - forwardedTcpip(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); +} - const boundAddrLen = Buffer.byteLength(cfg.boundAddr); - const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 - ); +module.exports = Agent - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 15, ++p); - packet.utf8Write('forwarded-tcpip', p += 4, 15); +/***/ }), - writeUInt32BE(packet, chan, p += 15); +/***/ 7032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(packet, initWindow, p += 4); +const { addAbortListener } = __nccwpck_require__(3983) +const { RequestAbortedError } = __nccwpck_require__(8045) - writeUInt32BE(packet, maxPacket, p += 4); +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') - writeUInt32BE(packet, boundAddrLen, p += 4); - packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) + } +} - writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null - writeUInt32BE(packet, remoteAddrLen, p += 4); - packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); + if (!signal) { + return + } - writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); + if (signal.aborted) { + abort(self) + return + } - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + self[kSignal] = signal + self[kListener] = () => { + abort(self) } - x11(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - const addrLen = Buffer.byteLength(cfg.originAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 - ); + addAbortListener(self[kSignal], self[kListener]) +} - packet[p] = MESSAGE.CHANNEL_OPEN; +function removeSignal (self) { + if (!self[kSignal]) { + return + } - writeUInt32BE(packet, 3, ++p); - packet.utf8Write('x11', p += 4, 3); + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } - writeUInt32BE(packet, chan, p += 3); + self[kSignal] = null + self[kListener] = null +} - writeUInt32BE(packet, initWindow, p += 4); +module.exports = { + addSignal, + removeSignal +} - writeUInt32BE(packet, maxPacket, p += 4); - writeUInt32BE(packet, addrLen, p += 4); - packet.utf8Write(cfg.originAddr, p += 4, addrLen); +/***/ }), - writeUInt32BE(packet, cfg.originPort, p += addrLen); +/***/ 9744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_authAgent(chan, initWindow, maxPacket) { - if (!this._server) - throw new Error('Server-only method called in client mode'); +"use strict"; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); - packet[p] = MESSAGE.CHANNEL_OPEN; +const { AsyncResource } = __nccwpck_require__(852) +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { addSignal, removeSignal } = __nccwpck_require__(7032) - writeUInt32BE(packet, 22, ++p); - packet.utf8Write('auth-agent@openssh.com', p += 4, 22); +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - writeUInt32BE(packet, chan, p += 22); + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - writeUInt32BE(packet, initWindow, p += 4); + const { signal, opaque, responseHeaders } = opts - writeUInt32BE(packet, maxPacket, p += 4); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); + super('UNDICI_CONNECT') - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 - ); + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null - packet[p] = MESSAGE.CHANNEL_OPEN; + addSignal(this, signal) + } - writeUInt32BE(packet, 33, ++p); - packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - writeUInt32BE(packet, chan, p += 33); + this.abort = abort + this.context = context + } - writeUInt32BE(packet, initWindow, p += 4); + onHeaders () { + throw new SocketError('bad connect', null) + } - writeUInt32BE(packet, maxPacket, p += 4); + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); + removeSignal(this) - writeUInt32BE(packet, 0, p += pathLen); + this.callback = null - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, forwarded-streamlocal@openssh.com)` - ); + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitStatus(chan, status) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-status', p += 4, 11); + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } - packet[p += 11] = 0; + onError (err) { + const { callback, opaque } = this - writeUInt32BE(packet, status, ++p); + removeSignal(this) - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } } - exitSignal(chan, name, coreDumped, msg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); +} - // Does not consume window space +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - const origSignal = name; + try { + const connectHandler = new ConnectHandler(opts, callback) + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} - if (typeof origSignal !== 'string' || !origSignal) - throw new Error(`Invalid signal: ${origSignal}`); +module.exports = connect - let signal = name.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); +/***/ }), - const nameLen = Buffer.byteLength(signal); - const msgLen = (msg ? Buffer.byteLength(msg) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 - ); +/***/ 8752: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - packet[p] = MESSAGE.CHANNEL_REQUEST; +"use strict"; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-signal', p += 4, 11); +const { + Readable, + Duplex, + PassThrough +} = __nccwpck_require__(2781) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) +const assert = __nccwpck_require__(9491) - packet[p += 11] = 0; +const kResume = Symbol('resume') - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(signal, p += 4, nameLen); +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) - packet[p += nameLen] = (coreDumped ? 1 : 0); + this[kResume] = null + } - writeUInt32BE(packet, msgLen, ++p); + _read () { + const { [kResume]: resume } = this - p += 4; - if (msgLen) { - packet.utf8Write(msg, p, msgLen); - p += msgLen; + if (resume) { + this[kResume] = null + resume() } + } - writeUInt32BE(packet, 0, p); + _destroy (err, callback) { + this._read() - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + callback(err) } - // 'ssh-userauth' service-specific - authFailure(authMethods, isPartial) { - if (!this._server) - throw new Error('Server-only method called in client mode'); +} - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } - let methods; + _read () { + this[kResume]() + } - if (typeof authMethods === 'boolean') { - isPartial = authMethods; - authMethods = undefined; + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() } - if (authMethods) { - methods = []; - for (let i = 0; i < authMethods.length; ++i) { - if (authMethods[i].toLowerCase() === 'none') - continue; - methods.push(authMethods[i]); - } - methods = methods.join(','); - } else { - methods = ''; - } + callback(err) + } +} - const methodsLen = methods.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - packet[p] = MESSAGE.USERAUTH_FAILURE; + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } - writeUInt32BE(packet, methodsLen, ++p); - packet.utf8Write(methods, p += 4, methodsLen); + const { signal, method, opaque, onInfo, responseHeaders } = opts - packet[p += methodsLen] = (isPartial === true ? 1 : 0); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - this._authsQueue.shift(); + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authSuccess() { - if (!this._server) - throw new Error('Server-only method called in client mode'); + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); + super('UNDICI_PIPELINE') - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null - packet[p] = MESSAGE.USERAUTH_SUCCESS; + this.req = new PipelineRequest().on('error', util.nop) - this._authsQueue.shift(); - this._authenticated = true; + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this - this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); + if (body && body.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - } - authPKOK(keyAlgo, key) { - if (!this._server) - throw new Error('Server-only method called in client mode'); + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this - if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') - throw new Error('"publickey" auth not in progress'); + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } - // TODO: support parsed key for `key` + if (abort && err) { + abort() + } - const keyAlgoLen = Buffer.byteLength(keyAlgo); - const keyLen = key.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) - packet[p] = MESSAGE.USERAUTH_PK_OK; + removeSignal(this) - writeUInt32BE(packet, keyAlgoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); + callback(err) + } + }).on('prefinish', () => { + const { req } = this - writeUInt32BE(packet, keyLen, p += keyAlgoLen); - packet.set(key, p += 4); + // Node < 15 does not call _final in same tick. + req.push(null) + }) - this._authsQueue.shift(); + this.res = null - this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); - sendPacket(this, this._packetRW.write.finalize(packet)); + addSignal(this, signal) } - authPasswdChg(prompt) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const promptLen = Buffer.byteLength(prompt); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); - packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; + onConnect (abort, context) { + const { ret, res } = this - writeUInt32BE(packet, promptLen, ++p); - packet.utf8Write(prompt, p += 4, promptLen); + assert(!res, 'pipeline cannot be retried') - writeUInt32BE(packet, 0, p += promptLen); // Empty language tag + if (ret.destroyed) { + throw new RequestAbortedError() + } - this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); - sendPacket(this, this._packetRW.write.finalize(packet)); + this.abort = abort + this.context = context } - authInfoReq(name, instructions, prompts) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let promptsLen = 0; - const nameLen = name ? Buffer.byteLength(name) : 0; - const instrLen = instructions ? Buffer.byteLength(instructions) : 0; - for (let i = 0; i < prompts.length; ++i) - promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen - ); + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } - packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; + this.res = new PipelineResponse(resume) - writeUInt32BE(packet, nameLen, ++p); - p += 4; - if (name) { - packet.utf8Write(name, p, nameLen); - p += nameLen; + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', util.nop) + throw err } - writeUInt32BE(packet, instrLen, p); - p += 4; - if (instructions) { - packet.utf8Write(instructions, p, instrLen); - p += instrLen; + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') } - writeUInt32BE(packet, 0, p); + body + .on('data', (chunk) => { + const { ret, body } = this - writeUInt32BE(packet, prompts.length, p += 4); - p += 4; - for (let i = 0; i < prompts.length; ++i) { - const prompt = prompts[i]; - const promptLen = Buffer.byteLength(prompt.prompt); + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } - writeUInt32BE(packet, promptLen, p); - p += 4; - if (promptLen) { - packet.utf8Write(prompt.prompt, p, promptLen); - p += promptLen; - } - packet[p++] = (prompt.echo ? 1 : 0); - } + onData (chunk) { + const { res } = this + return res.push(chunk) + } - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); - sendPacket(this, this._packetRW.write.finalize(packet)); + onComplete (trailers) { + const { res } = this + res.push(null) } -} -// SSH-protoversion-softwareversion (SP comments) CR LF -const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} -// TODO: optimize this by starting n bytes from the end of this._buffer instead -// of the beginning -function parseHeader(chunk, p, len) { - let data; - let chunkOffset; - if (this._buffer) { - data = Buffer.allocUnsafe(this._buffer.length + (len - p)); - data.set(this._buffer, 0); - if (p === 0) { - data.set(chunk, this._buffer.length); - } else { - data.set(new Uint8Array(chunk.buffer, - chunk.byteOffset + p, - (len - p)), - this._buffer.length); - } - chunkOffset = this._buffer.length; - p = 0; - } else { - data = chunk; - chunkOffset = 0; +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) } - const op = p; - let start = p; - let end = p; - let needNL = false; - let lineLen = 0; - let lines = 0; - for (; p < data.length; ++p) { - const ch = data[p]; +} - if (ch === 13 /* '\r' */) { - needNL = true; - continue; - } +module.exports = pipeline - if (ch === 10 /* '\n' */) { - if (end > start - && end - start > 4 - && data[start] === 83 /* 'S' */ - && data[start + 1] === 83 /* 'S' */ - && data[start + 2] === 72 /* 'H' */ - && data[start + 3] === 45 /* '-' */) { - const full = data.latin1Slice(op, end + 1); - const identRaw = (start === op ? full : full.slice(start - op)); - const m = RE_IDENT.exec(identRaw); - if (!m) - throw new Error('Invalid identification string'); +/***/ }), - const header = { - greeting: (start === op ? '' : full.slice(0, start - op)), - identRaw, - versions: { - protocol: m[1], - software: m[2], - }, - comments: m[3] - }; +/***/ 5448: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Needed during handshake - this._remoteIdentRaw = Buffer.from(identRaw); +"use strict"; - this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); - this._compatFlags = getCompatFlags(header); - this._buffer = undefined; - this._decipher = - new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); - this._parse = parsePacket; +const Readable = __nccwpck_require__(3858) +const { + InvalidArgumentError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - this._onHeader(header); - if (!this._destruct) { - // We disconnected inside _onHeader - return len; - } + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts - kexinit(this); + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - return p + 1 - chunkOffset; + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') } - // Only allow pre-ident greetings when we're a client - if (this._server) - throw new Error('Greetings from clients not permitted'); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - if (++lines > MAX_LINES) - throw new Error('Max greeting lines exceeded'); + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - needNL = false; - start = p + 1; - lineLen = 0; - } else if (needNL) { - throw new Error('Invalid header: expected newline'); - } else if (++lineLen >= MAX_LINE_LEN) { - throw new Error('Header line too long'); + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.throwOnError = throwOnError + this.highWaterMark = highWaterMark + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) } - end = p; + addSignal(this, signal) } - if (!this._buffer) - this._buffer = bufferSlice(data, op); - return p - chunkOffset; -} + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } -function parsePacket(chunk, p, len) { - return this._decipher.decrypt(chunk, p, len); -} + this.abort = abort + this.context = context + } -function onPayload(payload) { - // XXX: move this to the Decipher implementations? + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this - this._onPacket(); + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } - payload = this._packetRW.read.read(payload); + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const body = new Readable({ resume, abort, contentType, highWaterMark }) - const type = payload[0]; - if (type === MESSAGE.USERAUTH_SUCCESS - && !this._server - && !this._authenticated) { - this._authenticated = true; - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); + this.callback = null + this.res = body + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body, contentType, statusCode, statusMessage, headers } + ) + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body, + context + }) + } + } } - const handler = MESSAGE_HANDLERS[type]; - if (handler === undefined) { - this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); - return; + + onData (chunk) { + const { res } = this + return res.push(chunk) } - return handler(this, payload); -} + onComplete (trailers) { + const { res } = this -function getCompatFlags(header) { - const software = header.versions.software; + removeSignal(this) - let flags = 0; + util.parseHeaders(trailers, this.trailers) - for (const rule of COMPAT_CHECKS) { - if (typeof rule[0] === 'string') { - if (software === rule[0]) - flags |= rule[1]; - } else if (rule[0].test(software)) { - flags |= rule[1]; - } + res.push(null) } - return flags; -} + onError (err) { + const { res, callback, body, opaque } = this -function modesToBytes(modes) { - const keys = Object.keys(modes); - const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); - let b = 0; + removeSignal(this) - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === 'TTY_OP_END') - continue; + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } - const opcode = TERMINAL_MODE[key]; - if (opcode === undefined) - continue; + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } - const val = modes[key]; - if (typeof val === 'number' && isFinite(val)) { - bytes[b++] = opcode; - bytes[b++] = val >>> 24; - bytes[b++] = val >>> 16; - bytes[b++] = val >>> 8; - bytes[b++] = val; + if (body) { + this.body = null + util.destroy(body, err) } } +} - bytes[b++] = TERMINAL_MODE.TTY_OP_END; - - if (b < bytes.length) - return bufferSlice(bytes, 0, b); +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - return bytes; + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } } -module.exports = Protocol; +module.exports = request +module.exports.RequestHandler = RequestHandler /***/ }), -/***/ 2026: +/***/ 5395: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const EventEmitter = __nccwpck_require__(2361); -const fs = __nccwpck_require__(7147); -const { constants } = fs; +const { finished, PassThrough } = __nccwpck_require__(2781) const { - Readable: ReadableStream, - Writable: WritableStream -} = __nccwpck_require__(2781); -const { inherits, isDate } = __nccwpck_require__(3837); + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } -const FastBuffer = Buffer[Symbol.species]; + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts -const { - bufferCopy, - bufferSlice, - makeBufferParser, - writeUInt32BE, -} = __nccwpck_require__(9475); + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } -const ATTR = { - SIZE: 0x00000001, - UIDGID: 0x00000002, - PERMISSIONS: 0x00000004, - ACMODTIME: 0x00000008, - EXTENDED: 0x80000000, -}; + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } -// Large enough to store all possible attributes -const ATTRS_BUF = Buffer.alloc(28); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } -const STATUS_CODE = { - OK: 0, - EOF: 1, - NO_SUCH_FILE: 2, - PERMISSION_DENIED: 3, - FAILURE: 4, - BAD_MESSAGE: 5, - NO_CONNECTION: 6, - CONNECTION_LOST: 7, - OP_UNSUPPORTED: 8 -}; + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } -const VALID_STATUS_CODES = new Map( - Object.values(STATUS_CODE).map((n) => [n, 1]) -); + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } -const STATUS_CODE_STR = { - [STATUS_CODE.OK]: 'No error', - [STATUS_CODE.EOF]: 'End of file', - [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', - [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', - [STATUS_CODE.FAILURE]: 'Failure', - [STATUS_CODE.BAD_MESSAGE]: 'Bad message', - [STATUS_CODE.NO_CONNECTION]: 'No connection', - [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', - [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', -}; + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + this.throwOnError = throwOnError || false + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } -const REQUEST = { - INIT: 1, - OPEN: 3, - CLOSE: 4, - READ: 5, - WRITE: 6, - LSTAT: 7, - FSTAT: 8, - SETSTAT: 9, - FSETSTAT: 10, - OPENDIR: 11, - READDIR: 12, - REMOVE: 13, - MKDIR: 14, - RMDIR: 15, - REALPATH: 16, - STAT: 17, - RENAME: 18, - READLINK: 19, - SYMLINK: 20, - EXTENDED: 200 -}; + addSignal(this, signal) + } -const RESPONSE = { - VERSION: 2, - STATUS: 101, - HANDLE: 102, - DATA: 103, - NAME: 104, - ATTRS: 105, - EXTENDED: 201 -}; + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } -const OPEN_MODE = { - READ: 0x00000001, - WRITE: 0x00000002, - APPEND: 0x00000004, - CREAT: 0x00000008, - TRUNC: 0x00000010, - EXCL: 0x00000020 -}; + this.abort = abort + this.context = context + } -const PKT_RW_OVERHEAD = 2 * 1024; -const MAX_REQID = 2 ** 32 - 1; -const CLIENT_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - REQUEST.INIT, - 0, 0, 0, 3 /* version */ -]); -const SERVER_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - RESPONSE.VERSION, - 0, 0, 0, 3 /* version */ -]); + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this -const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; -const OPENSSH_MAX_PKT_LEN = 256 * 1024; + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) -const bufferParser = makeBufferParser(); + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } -const fakeStderr = { - readable: false, - writable: false, - push: (data) => {}, - once: () => {}, - on: () => {}, - emit: () => {}, - end: () => {}, -}; + this.factory = null -function noop() {} + let res -// Emulates enough of `Channel` to be able to be used as a drop-in replacement -// in order to process incoming data with as little overhead as possible -class SFTP extends EventEmitter { - constructor(client, chanInfo, cfg) { - super(); + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() - if (typeof cfg !== 'object' || !cfg) - cfg = {}; + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + if (factory === null) { + return + } - const remoteIdentRaw = client._protocol._remoteIdentRaw; + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) - this.server = !!cfg.server; - this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } - this._version = -1; - this._extensions = {}; - this._biOpt = cfg.biOpt; - this._pktLenBytes = 0; - this._pktLen = 0; - this._pktPos = 0; - this._pktType = 0; - this._pktData = undefined; - this._writeReqid = -1; - this._requests = {}; - this._maxInPktLen = OPENSSH_MAX_PKT_LEN; - this._maxOutPktLen = 34000; - this._maxReadLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - this._maxWriteLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this - this.maxOpenHandles = undefined; + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } - // Channel compatibility - this._client = client; - this._protocol = client._protocol; - this._callbacks = []; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - this._waitWindow = false; // SSH-level backpressure - this._chunkcb = undefined; - this._buffer = []; - this.type = chanInfo.type; - this.subtype = undefined; - this.incoming = chanInfo.incoming; - this.outgoing = chanInfo.outgoing; - this.stderr = fakeStderr; - this.readable = true; + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + } + + res.on('drain', resume) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain + + return needDrain !== true } - // This handles incoming data to parse - push(data) { - if (data === null) { - cleanupRequests(this); - if (!this.readable) - return; - // No more incoming data from the remote side - this.readable = false; - this.emit('end'); - return; + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + if (!res) { + return } - /* - uint32 length - byte type - byte[length - 1] data payload - */ - let p = 0; - while (p < data.length) { - if (this._pktLenBytes < 4) { - let nb = Math.min(4 - this._pktLenBytes, data.length - p); - this._pktLenBytes += nb; + this.trailers = util.parseHeaders(trailers) - while (nb--) - this._pktLen = (this._pktLen << 8) + data[p++]; + res.end() + } - if (this._pktLenBytes < 4) - return; - if (this._pktLen === 0) - return doFatalSFTPError(this, 'Invalid packet length'); - if (this._pktLen > this._maxInPktLen) { - const max = this._maxInPktLen; - return doFatalSFTPError( - this, - `Packet length ${this._pktLen} exceeds max length of ${max}` - ); - } - if (p >= data.length) - return; - } - if (this._pktPos < this._pktLen) { - const nb = Math.min(this._pktLen - this._pktPos, data.length - p); - if (p !== 0 || nb !== data.length) { - if (nb === this._pktLen) { - this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._pktPos - ); - } - } else if (nb === this._pktLen) { - this._pkt = data; - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set(data, this._pktPos); - } - p += nb; - this._pktPos += nb; - if (this._pktPos < this._pktLen) - return; - } + onError (err) { + const { res, callback, opaque, body } = this - const type = this._pkt[0]; - const payload = this._pkt; + removeSignal(this) - // Prepare for next packet - this._pktLen = 0; - this._pktLenBytes = 0; - this._pkt = undefined; - this._pktPos = 0; + this.factory = null - const handler = (this.server - ? SERVER_HANDLERS[type] - : CLIENT_HANDLERS[type]); - if (!handler) - return doFatalSFTPError(this, `Unknown packet type ${type}`); + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } - if (this._version === -1) { - if (this.server) { - if (type !== REQUEST.INIT) - return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); - } else if (type !== RESPONSE.VERSION) { - return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); - } - } + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream + + +/***/ }), + +/***/ 6923: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) +const { AsyncResource } = __nccwpck_require__(852) +const util = __nccwpck_require__(3983) +const { addSignal, removeSignal } = __nccwpck_require__(7032) +const assert = __nccwpck_require__(9491) + +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - if (handler(this, payload) === false) - return; + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - } - end() { - this.destroy(); + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) } - destroy() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._protocol.channelClose(this.outgoing.id); + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() } + + this.abort = abort + this.context = null } - _init() { - this._init = noop; - if (!this.server) - sendOrBuffer(this, CLIENT_VERSION_BUFFER); + + onHeaders () { + throw new SocketError('bad upgrade', null) } - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - createReadStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this - return new ReadStream(this, path, options); - } - createWriteStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); + assert.strictEqual(statusCode, 101) - return new WriteStream(this, path, options); + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) } - open(path, flags_, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } + } +} - const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); - if (flags === null) - throw new Error(`Unknown flags string: ${flags_}`); +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - let attrsFlags = 0; - let attrsLen = 0; - if (typeof attrs === 'string' || typeof attrs === 'number') - attrs = { mode: attrs }; - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - attrsFlags = attrs.flags; - attrsLen = attrs.nb; + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} - /* - uint32 id - string filename - uint32 pflags - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); +module.exports = upgrade - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPEN; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - writeUInt32BE(buf, attrsFlags, p += 4); - if (attrsLen) { - p += 4; +/***/ }), - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); +/***/ 4059: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - p += attrsLen; - } - this._requests[reqid] = { cb }; +"use strict"; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` - ); - } - close(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); +module.exports.request = __nccwpck_require__(5448) +module.exports.stream = __nccwpck_require__(5395) +module.exports.pipeline = __nccwpck_require__(8752) +module.exports.upgrade = __nccwpck_require__(6923) +module.exports.connect = __nccwpck_require__(9744) - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.CLOSE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +/***/ }), - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); +/***/ 3858: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._requests[reqid] = { cb }; +"use strict"; +// Ported from https://github.com/nodejs/undici/pull/907 - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` - ); - } - read(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off >= buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - read_(this, handle, buf, off, len, position, cb); - } - readData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.read(handle, buf, off, len, position, cb); - } - write(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off > buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); +const assert = __nccwpck_require__(9491) +const { Readable } = __nccwpck_require__(2781) +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3983) - if (!len) { - cb && process.nextTick(cb, undefined, 0); - return; - } +let Blob - const maxDataLen = this._maxWriteLen; - const overflow = Math.max(len - maxDataLen, 0); - const origPosition = position; +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') - if (overflow) - len = maxDataLen; +const noop = () => {} - /* - uint32 id - string handle - uint64 offset - string data - */ - const handleLen = handle.length; - let p = 9; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.WRITE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); + this._readableState.dataEmitted = false - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = position & 0xFF; - position /= 256; + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false + } + + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this } - writeUInt32BE(out, len, p += 8); - bufferCopy(buf, out, off, off + len, p += 4); - this._requests[reqid] = { - cb: (err) => { - if (err) { - if (typeof cb === 'function') - cb(err); - } else if (overflow) { - this.write(handle, - buf, - off + len, - overflow, - origPosition + len, - cb); - } else if (typeof cb === 'function') { - cb(undefined, off + len); - } - } - }; + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } - const isSent = sendOrBuffer(this, out); - if (this._debug) { - const how = (isSent ? 'Sent' : 'Buffered'); - this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); + if (err) { + this[kAbort]() } + + return super.destroy(err) } - writeData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.write(handle, buf, off, len, position, cb); + + emit (ev, ...args) { + if (ev === 'data') { + // Node < 16.7 + this._readableState.dataEmitted = true + } else if (ev === 'error') { + // Node < 16 + this._readableState.errorEmitted = true + } + return super.emit(ev, ...args) } - fastGet(remotePath, localPath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - fastXfer(this, fs, remotePath, localPath, opts, cb); + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true + } + return super.on(ev, ...args) } - fastPut(localPath, remotePath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - fastXfer(fs, this, localPath, remotePath, opts, cb); + addListener (ev, ...args) { + return this.on(ev, ...args) } - readFile(path, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; + off (ev, ...args) { + const ret = super.off(ev, ...args) + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) } + return ret + } - if (typeof options === 'string') - options = { encoding: options, flag: 'r' }; - else if (!options) - options = { encoding: null, flag: 'r' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); + removeListener (ev, ...args) { + return this.off(ev, ...args) + } - const encoding = options.encoding; - if (encoding && !Buffer.isEncoding(encoding)) - throw new Error(`Unknown encoding: ${encoding}`); + push (chunk) { + if (this[kConsume] && chunk !== null && this.readableLength === 0) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } - // First stat the file, so we know the size. - let size; - let buffer; // Single buffer with file data - let buffers; // List for when size is unknown - let pos = 0; - let handle; + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } - // SFTPv3 does not support using -1 for read position, so we have to track - // read position manually - let bytesRead = 0; + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } - const flag = options.flag || 'r'; + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } - const read = () => { - if (size === 0) { - buffer = Buffer.allocUnsafe(8192); - this.read(handle, buffer, 0, 8192, bytesRead, afterRead); - } else { - this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } + + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) } - }; + } + return this[kBody] + } - const afterRead = (er, nbytes) => { - let eof; - if (er) { - eof = (er.code === STATUS_CODE.EOF); - if (!eof) { - return this.close(handle, () => { - return callback && callback(er); - }); + dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal + + if (signal) { + try { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') } - } else { - eof = false; + util.throwIfAborted(signal) + } catch (err) { + return Promise.reject(err) } + } - if (eof || (size === 0 && nbytes === 0)) - return close(); + if (this.closed) { + return Promise.resolve(null) + } - bytesRead += nbytes; - pos += nbytes; - if (size !== 0) { - if (pos === size) - close(); - else - read(); - } else { - // Unknown size, just read until we don't get bytes. - buffers.push(bufferSlice(buffer, 0, nbytes)); - read(); - } - }; - afterRead._wantEOFError = true; + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal + ? util.addAbortListener(signal, () => { + this.destroy() + }) + : noop - const close = () => { - this.close(handle, (er) => { - if (size === 0) { - // Collect the data into the buffers list. - buffer = Buffer.concat(buffers, pos); - } else if (pos < size) { - buffer = bufferSlice(buffer, 0, pos); - } + this + .on('close', function () { + signalListenerCleanup() + if (signal && signal.aborted) { + reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) + } else { + resolve(null) + } + }) + .on('error', noop) + .on('data', function (chunk) { + limit -= chunk.length + if (limit <= 0) { + this.destroy() + } + }) + .resume() + }) + } +} - if (encoding) - buffer = buffer.toString(encoding); - return callback && callback(er, buffer); - }); - }; +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] +} - this.open(path, flag, 0o666, (er, handle_) => { - if (er) - return callback && callback(er); - handle = handle_; +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') + } - size = st.size || 0; - if (size === 0) { - // The kernel lies about many files. - // Go ahead and try to read some bytes. - buffers = []; - return read(); + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) } + }) - buffer = Buffer.allocUnsafe(size); - read(); - }; - this.fstat(handle, tryStat); - }); + process.nextTick(consumeStart, stream[kConsume]) + }) +} + +function consumeStart (consume) { + if (consume.body === null) { + return } - writeFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } + const { _readableState: state } = consume.stream - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'w' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } - if (options.encoding && !Buffer.isEncoding(options.encoding)) - throw new Error(`Unknown encoding: ${options.encoding}`); + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } - const flag = options.flag || 'w'; - this.open(path, flag, options.mode, (openErr, handle) => { - if (openErr) { - callback && callback(openErr); - } else { - const buffer = (Buffer.isBuffer(data) - ? data - : Buffer.from('' + data, options.encoding || 'utf8')); - const position = (/a/.test(flag) ? null : 0); + consume.stream.resume() - // SFTPv3 does not support the notion of 'current position' - // (null position), so we just attempt to append to the end of the file - // instead - if (position === null) { - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); - }; - this.fstat(handle, tryStat); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, position, callback); - } - }); + while (consume.stream.read() != null) { + // Loop } - appendFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); +} - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume + + try { + if (type === 'text') { + resolve(toUSVString(Buffer.concat(body))) + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))) + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length) + + let pos = 0 + for (const buf of body) { + dst.set(buf, pos) + pos += buf.byteLength + } + + resolve(dst.buffer) + } else if (type === 'blob') { + if (!Blob) { + Blob = (__nccwpck_require__(4300).Blob) + } + resolve(new Blob(body, { type: stream[kContentType] })) } - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'a' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); + consumeFinish(consume) + } catch (err) { + stream.destroy(err) + } +} - if (!options.flag) - options = Object.assign({ flag: 'a' }, options); - this.writeFile(path, data, options, callback); +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} + +function consumeFinish (consume, err) { + if (consume.body === null) { + return } - exists(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - this.stat(path, (err) => { - cb && cb(err ? false : true); - }); + if (err) { + consume.reject(err) + } else { + consume.resolve() } - unlink(filename, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - /* - uint32 id - string filename - */ - const fnameLen = Buffer.byteLength(filename); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} + + +/***/ }), + +/***/ 7474: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const assert = __nccwpck_require__(9491) +const { + ResponseStatusCodeError +} = __nccwpck_require__(8045) +const { toUSVString } = __nccwpck_require__(3983) + +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) + + let chunks = [] + let limit = 0 + + for await (const chunk of body) { + chunks.push(chunk) + limit += chunk.length + if (limit > 128 * 1024) { + chunks = null + break + } + } + + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return + } + + try { + if (contentType.startsWith('application/json')) { + const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + + if (contentType.startsWith('text/')) { + const payload = toUSVString(Buffer.concat(chunks)) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + } catch (err) { + // Process in a fallback if error + } + + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) +} + +module.exports = { getResolveErrorBodyCallback } + + +/***/ }), - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REMOVE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +/***/ 7931: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(buf, fnameLen, p); - buf.utf8Write(filename, p += 4, fnameLen); +"use strict"; - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` - ); - } - rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = __nccwpck_require__(8045) +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = __nccwpck_require__(3198) +const Pool = __nccwpck_require__(4634) +const { kUrl, kInterceptors } = __nccwpck_require__(2785) +const { parseOrigin } = __nccwpck_require__(3983) +const kFactory = Symbol('factory') - /* - uint32 id - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RENAME; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} - writeUInt32BE(buf, oldLen, p); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} - this._requests[reqid] = { cb }; +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` - ); - } - mkdir(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 - let flags = 0; - let attrsLen = 0; + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; - } - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] } - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.MKDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - p += attrsLen; + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) - this._requests[reqid] = { cb }; + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` - ); - } - rmdir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RMDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + this._updateBalancedPoolStats() - this._requests[reqid] = { cb }; + return this + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` - ); + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) } - readdir(where, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - if (typeof opts !== 'object' || opts === null) - opts = {}; + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - const doFilter = (opts && opts.full ? false : true); + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) - if (!Buffer.isBuffer(where) && typeof where !== 'string') - throw new Error('missing directory handle or path'); + if (pool) { + this[kRemoveClient](pool) + } - if (typeof where === 'string') { - const entries = []; - let e = 0; + return this + } - const reread = (err, handle) => { - if (err) - return cb(err); + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } - this.readdir(handle, opts, (err, list) => { - const eof = (err && err.code === STATUS_CODE.EOF); + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } - if (err && !eof) - return this.close(handle, () => cb(err)); + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) - if (eof) { - return this.close(handle, (err) => { - if (err) - return cb(err); - cb(undefined, entries); - }); - } + if (!dispatcher) { + return + } - for (let i = 0; i < list.length; ++i, ++e) - entries[e] = list[i]; + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) - reread(undefined, handle); - }); - }; - return this.opendir(where, reread); + if (allClientsBusy) { + return } - /* - uint32 id - string handle - */ - const handleLen = where.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + let counter = 0 - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) - writeUInt32BE(buf, handleLen, p); - buf.set(where, p += 4); + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] - this._requests[reqid] = { - cb: (doFilter - ? (err, list) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } - for (let i = list.length - 1; i >= 0; --i) { - if (list[i].filename === '.' || list[i].filename === '..') - list.splice(i, 1); - } + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] - cb(undefined, list); - } - : cb) - }; + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` - ); + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] } - fstat(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +} - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); +module.exports = BalancedPool - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +/***/ }), - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); +/***/ 6101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._requests[reqid] = { cb }; +"use strict"; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` - ); - } - stat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); +const { kConstruct } = __nccwpck_require__(9174) +const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(2396) +const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3983) +const { kHeadersList } = __nccwpck_require__(2785) +const { webidl } = __nccwpck_require__(1744) +const { Response, cloneResponse } = __nccwpck_require__(7823) +const { Request } = __nccwpck_require__(8359) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const { fetching } = __nccwpck_require__(4881) +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(2538) +const assert = __nccwpck_require__(9491) +const { getGlobalDispatcher } = __nccwpck_require__(1892) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.STAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../types/cache').CacheQueryOptions} options + */ - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ - this._requests[reqid] = { cb }; +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` - ); + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() + } + + this.#relevantRequestResponseList = arguments[1] } - lstat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.LSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + const p = await this.matchAll(request, options) - this._requests[reqid] = { cb }; + if (p.length === 0) { + return + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` - ); + return p[0] } - opendir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPENDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + // 1. + let r = null - this._requests[reqid] = { cb }; + // 2. + if (request !== undefined) { + if (request instanceof Request) { + // 2.1.1 + r = request[kState] - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` - ); - } - setstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = new Request(request)[kState] + } + } - let flags = 0; - let attrsLen = 0; + // 5. + // 5.1 + const responses = [] - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; + // 5.5.1 + const responseList = [] - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = new Response(response.body?.source ?? null) + const body = responseObject[kState].body + responseObject[kState] = response + responseObject[kState].body = body + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' - p += attrsLen; + responseList.push(responseObject) } - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` - ); + // 6. + return Object.freeze(responseList) } - fsetstat(handle, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); + async add (request) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) - let flags = 0; - let attrsLen = 0; + request = webidl.converters.RequestInfo(request) - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } + // 1. + const requests = [request] - /* - uint32 id - string handle - ATTRS attrs - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); + // 2. + const responseArrayPromise = this.addAll(requests) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 3. + return await responseArrayPromise + } - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - writeUInt32BE(buf, flags, p += handleLen); - if (attrsLen) { - p += 4; + async addAll (requests) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + requests = webidl.converters['sequence'](requests) - p += attrsLen; - } + // 1. + const responsePromises = [] - this._requests[reqid] = { cb }; + // 2. + const requestList = [] - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` - ); - } - futimes(handle, atime, mtime, cb) { - return this.fsetstat(handle, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - utimes(path, atime, mtime, cb) { - return this.setstat(path, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - fchown(handle, uid, gid, cb) { - return this.fsetstat(handle, { - uid: uid, - gid: gid - }, cb); - } - chown(path, uid, gid, cb) { - return this.setstat(path, { - uid: uid, - gid: gid - }, cb); - } - fchmod(handle, mode, cb) { - return this.fsetstat(handle, { - mode: mode - }, cb); - } - chmod(path, mode, cb) { - return this.setstat(path, { - mode: mode - }, cb); - } - readlink(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + // 3.1 + const r = request[kState] - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme when method is not GET.' + }) + } + } - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing link info')); - cb(undefined, names[0].filename); + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme.' + }) } - }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` - ); - } - symlink(targetPath, linkPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' + + // 5.5 + requestList.push(r) + + // 5.6 + const responsePromise = createDeferredPromise() + + // 5.7 + fetchControllers.push(fetching({ + request: r, + dispatcher: getGlobalDispatcher(), + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })) + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')) + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })) + + for (const controller of fetchControllers) { + controller.abort() + } - /* - uint32 id - string linkpath - string targetpath - */ - const linkLen = Buffer.byteLength(linkPath); - const targetLen = Buffer.byteLength(targetPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SYMLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 2. + responsePromise.resolve(response) + } + })) - if (this._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - writeUInt32BE(buf, targetLen, p); - buf.utf8Write(targetPath, p += 4, targetLen); - writeUInt32BE(buf, linkLen, p += targetLen); - buf.utf8Write(linkPath, p += 4, linkLen); - } else { - writeUInt32BE(buf, linkLen, p); - buf.utf8Write(linkPath, p += 4, linkLen); - writeUInt32BE(buf, targetLen, p += linkLen); - buf.utf8Write(targetPath, p += 4, targetLen); + // 5.8 + responsePromises.push(responsePromise.promise) } - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` - ); - } - realpath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 6. + const p = Promise.all(responsePromises) - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + // 7. + const responses = await p - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REALPATH; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 7.1 + const operations = [] - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + // 7.2 + let index = 0 - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing path info')); - cb(undefined, names[0].filename); + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 } - }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` - ); - } - // extended requests - ext_openssh_rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + operations.push(operation) // 7.3.5 - const ext = this._extensions['posix-rename@openssh.com']; - if (!ext || ext !== '1') - throw new Error('Server does not support this extended request'); + index++ // 7.3.6 + } - /* - uint32 id - string "posix-rename@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); + // 7.5 + const cacheJobPromise = createDeferredPromise() - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 7.6.1 + let errorData = null - writeUInt32BE(buf, 24, p); - buf.utf8Write('posix-rename@openssh.com', p += 4, 24); - writeUInt32BE(buf, oldLen, p += 24); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } - this._requests[reqid] = { cb }; + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); - } + // 7.7 + return cacheJobPromise.promise } - ext_openssh_statvfs(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - const ext = this._extensions['statvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); + async put (request, response) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) - /* - uint32 id - string "statvfs@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); + request = webidl.converters.RequestInfo(request) + response = webidl.converters.Response(response) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 1. + let innerRequest = null - writeUInt32BE(buf, 19, p); - buf.utf8Write('statvfs@openssh.com', p += 4, 19); - writeUInt32BE(buf, pathLen, p += 19); - buf.utf8Write(path, p += 4, pathLen); + // 2. + if (request instanceof Request) { + innerRequest = request[kState] + } else { // 3. + innerRequest = new Request(request)[kState] + } - this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Expected an http/s scheme when method is not GET' + }) + } - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); + // 5. + const innerResponse = response[kState] + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) } - } - ext_openssh_fstatvfs(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - const ext = this._extensions['fstatvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) - /* - uint32 id - string "fstatvfs@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Response body is locked or disturbed' + }) + } - writeUInt32BE(buf, 20, p); - buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); - writeUInt32BE(buf, handleLen, p += 20); - buf.set(handle, p += 4); + // 9. + const clonedResponse = cloneResponse(innerResponse) - this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; + // 10. + const bodyReadPromise = createDeferredPromise() - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); - } - } - ext_openssh_hardlink(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream - const ext = this._extensions['hardlink@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); + // 11.2 + const reader = stream.getReader() - /* - uint32 id - string "hardlink@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] - writeUInt32BE(buf, 20, p); - buf.utf8Write('hardlink@openssh.com', p += 4, 20); - writeUInt32BE(buf, oldLen, p += 20); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + } - this._requests[reqid] = { cb }; + // 17. + operations.push(operation) - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); + // 19. + const bytes = await bodyReadPromise.promise + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes } + + // 19.1 + const cacheJobPromise = createDeferredPromise() + + // 19.2.1 + let errorData = null + + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise } - ext_openssh_fsync(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - const ext = this._extensions['fsync@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) - /* - uint32 id - string "fsync@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + /** + * @type {Request} + */ + let r = null - writeUInt32BE(buf, 17, p); - buf.utf8Write('fsync@openssh.com', p += 4, 17); - writeUInt32BE(buf, handleLen, p += 17); - buf.set(handle, p += 4); + if (request instanceof Request) { + r = request[kState] - this._requests[reqid] = { cb }; + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string') - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` - ); - } - ext_openssh_lsetstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + r = new Request(request)[kState] + } - const ext = this._extensions['lsetstat@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); + /** @type {CacheBatchOperation[]} */ + const operations = [] - let flags = 0; - let attrsLen = 0; + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; + operations.push(operation) + + const cacheJobPromise = createDeferredPromise() + + let errorData = null + let requestResponses + + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e } - /* - uint32 id - string "lsetstat@openssh.com" - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + return cacheJobPromise.promise + } - writeUInt32BE(buf, 20, p); - buf.utf8Write('lsetstat@openssh.com', p += 4, 20); + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../types/cache').CacheQueryOptions} options + * @returns {readonly Request[]} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; + // 1. + let r = null - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] - p += attrsLen; + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } } - this._requests[reqid] = { cb }; + // 4. + const promise = createDeferredPromise() - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); + // 5. + // 5.1 + const requests = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] + + // 5.4.2 + for (const request of requests) { + const requestObject = new Request('https://a') + requestObject[kState] = request + requestObject[kHeaders][kHeadersList] = request.headersList + requestObject[kHeaders][kGuard] = 'immutable' + requestObject[kRealm] = request.client + + // 5.4.2.1 + requestList.push(requestObject) + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) + + return promise.promise } - ext_openssh_expandPath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - const ext = this._extensions['expand-path@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList - /* - uint32 id - string "expand-path@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); + // 2. + const backupCache = [...cache] - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 3. + const addedItems = [] - writeUInt32BE(buf, 23, p); - buf.utf8Write('expand-path@openssh.com', p += 4, 23); + // 4.1 + const resultList = [] - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } - this._requests[reqid] = { cb }; + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); - } - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - handle(reqid, handle) { - if (!this.server) - throw new Error('Server-only method called in client mode'); + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); + // 4.2.4 + let requestResponses - const handleLen = handle.length; + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) - if (handleLen > 256) - throw new Error('handle too large (> 256 bytes)'); + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.HANDLE; - writeUInt32BE(buf, reqid, 5); + // 4.2.5.2.1 + cache.splice(idx, 1) + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } - writeUInt32BE(buf, handleLen, p); - if (handleLen) - buf.set(handle, p += 4); + // 4.2.6.2 + const r = operation.request - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` - ); - } - status(reqid, code, message) { - if (!this.server) - throw new Error('Server-only method called in client mode'); + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } - if (!VALID_STATUS_CODES.has(code)) - throw new Error(`Bad status code: ${code}`); + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } - message || (message = ''); + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } - const msgLen = Buffer.byteLength(message); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.STATUS; - writeUInt32BE(buf, reqid, 5); + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) - writeUInt32BE(buf, code, p); + // 4.2.6.7.1 + cache.splice(idx, 1) + } - writeUInt32BE(buf, msgLen, p += 4); - p += 4; - if (msgLen) { - buf.utf8Write(message, p, msgLen); - p += msgLen; - } + // 4.2.6.8 + cache.push([operation.request, operation.response]) - writeUInt32BE(buf, 0, p); // Empty language tag + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` - ); - } - data(reqid, data, encoding) { - if (!this.server) - throw new Error('Server-only method called in client mode'); + // 4.2.7 + resultList.push([operation.request, operation.response]) + } - const isBuffer = Buffer.isBuffer(data); + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 - if (!isBuffer && typeof data !== 'string') - throw new Error('data is not a Buffer or string'); + // 5.2 + this.#relevantRequestResponseList = backupCache - let isUTF8; - if (!isBuffer && !encoding) { - encoding = undefined; - isUTF8 = true; + // 5.3 + throw e } + } - const dataLen = ( - isBuffer - ? data.length - : Buffer.byteLength(data, encoding) - ); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = [] - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.DATA; - writeUInt32BE(buf, reqid, 5); + const storage = targetStorage ?? this.#relevantRequestResponseList - writeUInt32BE(buf, dataLen, p); - if (dataLen) { - if (isBuffer) - buf.set(data, p += 4); - else if (isUTF8) - buf.utf8Write(data, p += 4, dataLen); - else - buf.write(data, p += 4, dataLen, encoding); + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` - ); + return resultList } - name(reqid, names) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - if (!Array.isArray(names)) { - if (typeof names !== 'object' || names === null) - throw new Error('names is not an object or array'); - names = [ names ]; - } + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } - const count = names.length; - let namesLen = 0; - let nameAttrs; - const attrs = []; + const queryURL = new URL(requestQuery.url) - for (let i = 0; i < count; ++i) { - const name = names[i]; - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - namesLen += 4 + Buffer.byteLength(filename); - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - namesLen += 4 + Buffer.byteLength(longname); + const cachedURL = new URL(request.url) - if (typeof name.attrs === 'object' && name.attrs !== null) { - nameAttrs = attrsToBytes(name.attrs); - namesLen += 4 + nameAttrs.nb; + if (options?.ignoreSearch) { + cachedURL.search = '' - if (nameAttrs.nb) { - let bytes; + queryURL.search = '' + } - if (nameAttrs.nb === ATTRS_BUF.length) { - bytes = new Uint8Array(ATTRS_BUF); - } else { - bytes = new Uint8Array(nameAttrs.nb); - bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); - } + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } - nameAttrs.bytes = bytes; - } + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } - attrs.push(nameAttrs); - } else { - namesLen += 4; - attrs.push(null); + const fieldValues = getFieldValues(response.headersList.get('vary')) + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false } } - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); + return true + } +} - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.NAME; - writeUInt32BE(buf, reqid, 5); +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) - writeUInt32BE(buf, count, p); +const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: false + } +] - p += 4; +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) - for (let i = 0; i < count; ++i) { - const name = names[i]; +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } +]) - { - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - const len = Buffer.byteLength(filename); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(filename, p, len); - p += len; - } - } +webidl.converters.Response = webidl.interfaceConverter(Response) - { - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - const len = Buffer.byteLength(longname); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(longname, p, len); - p += len; - } +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) + +module.exports = { + Cache +} + + +/***/ }), + +/***/ 7907: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { kConstruct } = __nccwpck_require__(9174) +const { Cache } = __nccwpck_require__(6101) +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) + +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) - attrs = attrsToBytes(attrs); - const flags = attrs.flags; - const attrsLen = attrs.nb; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); + cacheName = webidl.converters.DOMString(cacheName) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.ATTRS; - writeUInt32BE(buf, reqid, 5); + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } - writeUInt32BE(buf, flags, p); - if (attrsLen) { - p += 4; + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + cacheName = webidl.converters.DOMString(cacheName) - p += attrsLen; + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` - ); - } -} + // 2.2 + const cache = [] -function tryCreateBuffer(size) { - try { - return Buffer.allocUnsafe(size); - } catch (ex) { - return ex; + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) } -} -function read_(self, handle, buf, off, len, position, cb, req_) { - const maxDataLen = self._maxReadLen; - const overflow = Math.max(len - maxDataLen, 0); + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) - if (overflow) - len = maxDataLen; + cacheName = webidl.converters.DOMString(cacheName) - /* - uint32 id - string handle - uint64 offset - uint32 len - */ - const handleLen = handle.length; - let p = 9; - let pos = position; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); + return this.#caches.delete(cacheName) + } - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.READ; - const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = pos & 0xFF; - pos /= 256; + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] } - writeUInt32BE(out, len, p += 8); +} - if (typeof cb !== 'function') - cb = noop; +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) - const req = (req_ || { - nb: 0, - position, - off, - origOff: off, - len: undefined, - overflow: undefined, - cb: (err, data, nb) => { - const len = req.len; - const overflow = req.overflow; +module.exports = { + CacheStorage +} - if (err) { - if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) - return cb(err); - } else if (nb > len) { - return cb(new Error('Received more data than requested')); - } else if (nb === len && overflow) { - req.nb += nb; - req.position += nb; - req.off += nb; - read_(self, handle, buf, req.off, overflow, req.position, cb, req); - return; - } - if (req.origOff === 0 && buf.length === req.nb) - data = buf; - else - data = bufferSlice(buf, req.origOff, req.origOff + req.nb); - cb(undefined, req.nb + (nb || 0), data, req.position); - }, - buffer: undefined, - }); +/***/ }), - req.len = len; - req.overflow = overflow; +/***/ 9174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // TODO: avoid creating multiple buffer slices when we need to re-call read_() - // because of overflow - req.buffer = bufferSlice(buf, off, off + len); +"use strict"; - self._requests[reqid] = req; - const isBuffered = sendOrBuffer(self, out); - self._debug && self._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` - ); +module.exports = { + kConstruct: (__nccwpck_require__(2785).kConstruct) } -function fastXfer(src, dst, srcPath, dstPath, opts, cb) { - let concurrency = 64; - let chunkSize = 32768; - let onstep; - let mode; - let fileSize; - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.concurrency === 'number' - && opts.concurrency > 0 - && !isNaN(opts.concurrency)) { - concurrency = opts.concurrency; - } - if (typeof opts.chunkSize === 'number' - && opts.chunkSize > 0 - && !isNaN(opts.chunkSize)) { - chunkSize = opts.chunkSize; - } - if (typeof opts.fileSize === 'number' - && opts.fileSize > 0 - && !isNaN(opts.fileSize)) { - fileSize = opts.fileSize; - } - if (typeof opts.step === 'function') - onstep = opts.step; +/***/ }), - if (typeof opts.mode === 'string' || typeof opts.mode === 'number') - mode = modeNum(opts.mode); - } +/***/ 2396: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Internal state variables - let fsize; - let pdst = 0; - let total = 0; - let hadError = false; - let srcHandle; - let dstHandle; - let readbuf; - let bufsize = chunkSize * concurrency; +"use strict"; - function onerror(err) { - if (hadError) - return; - hadError = true; +const assert = __nccwpck_require__(9491) +const { URLSerializer } = __nccwpck_require__(685) +const { isValidHeaderName } = __nccwpck_require__(2538) - let left = 0; - let cbfinal; +/** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ +function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment) - if (srcHandle || dstHandle) { - cbfinal = () => { - if (--left === 0) - cb(err); - }; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - ++left; - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - ++left; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - src.close(srcHandle, cbfinal); - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - dst.close(dstHandle, cbfinal); - } else { - cb(err); + const serializedB = URLSerializer(B, excludeFragment) + + return serializedA === serializedB +} + +/** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ +function fieldValues (header) { + assert(header !== null) + + const values = [] + + for (let value of header.split(',')) { + value = value.trim() + + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue } + + values.push(value) } - src.open(srcPath, 'r', (err, sourceHandle) => { - if (err) - return onerror(err); + return values +} - srcHandle = sourceHandle; +module.exports = { + urlEquals, + fieldValues +} - if (fileSize === undefined) - src.fstat(srcHandle, tryStat); - else - tryStat(null, { size: fileSize }); - function tryStat(err, attrs) { - if (err) { - if (src !== fs) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - src.stat(srcPath, (err_, attrs_) => { - if (err_) - return onerror(err); - tryStat(null, attrs_); - }); - return; - } - return onerror(err); - } - fsize = attrs.size; +/***/ }), - dst.open(dstPath, 'w', (err, destHandle) => { - if (err) - return onerror(err); +/***/ 3598: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - dstHandle = destHandle; +"use strict"; +// @ts-check - if (fsize <= 0) - return onerror(); - // Use less memory where possible - while (bufsize > fsize) { - if (concurrency === 1) { - bufsize = fsize; - break; - } - bufsize -= chunkSize; - --concurrency; - } - readbuf = tryCreateBuffer(bufsize); - if (readbuf instanceof Error) - return onerror(readbuf); +/* global WebAssembly */ - if (mode !== undefined) { - dst.fchmod(dstHandle, mode, function tryAgain(err) { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() - // for whatever reason - dst.chmod(dstPath, mode, (err_) => tryAgain()); - return; - } - startReads(); - }); - } else { - startReads(); - } +const assert = __nccwpck_require__(9491) +const net = __nccwpck_require__(1808) +const http = __nccwpck_require__(3685) +const { pipeline } = __nccwpck_require__(2781) +const util = __nccwpck_require__(3983) +const timers = __nccwpck_require__(9459) +const Request = __nccwpck_require__(2905) +const DispatcherBase = __nccwpck_require__(4839) +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError +} = __nccwpck_require__(8045) +const buildConnector = __nccwpck_require__(2067) +const { + kUrl, + kReset, + kServerName, + kClient, + kBusy, + kParser, + kConnect, + kBlocking, + kResuming, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize, + kHTTPConnVersion, + // HTTP2 + kHost, + kHTTP2Session, + kHTTP2SessionState, + kHTTP2BuildRequest, + kHTTP2CopyHeaders, + kHTTP1BuildRequest +} = __nccwpck_require__(2785) + +/** @type {import('http2')} */ +let http2 +try { + http2 = __nccwpck_require__(5158) +} catch { + // @ts-ignore + http2 = { constants: {} } +} - function onread(err, nb, data, dstpos, datapos, origChunkLen) { - if (err) - return onerror(err); +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS + } +} = http2 - datapos = datapos || 0; +// Experimental +let h2ExperimentalWarned = false - dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); +const FastBuffer = Buffer[Symbol.species] - function writeCb(err) { - if (err) - return onerror(err); +const kClosedResolve = Symbol('kClosedResolve') - total += nb; - onstep && onstep(total, nb, fsize); +const channels = {} - if (nb < origChunkLen) - return singleRead(datapos, dstpos + nb, origChunkLen - nb); +try { + const diagnosticsChannel = __nccwpck_require__(7643) + channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') + channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') + channels.connectError = diagnosticsChannel.channel('undici:client:connectError') + channels.connected = diagnosticsChannel.channel('undici:client:connected') +} catch { + channels.sendHeaders = { hasSubscribers: false } + channels.beforeConnect = { hasSubscribers: false } + channels.connectError = { hasSubscribers: false } + channels.connected = { hasSubscribers: false } +} - if (total === fsize) { - dst.close(dstHandle, (err) => { - dstHandle = undefined; - if (err) - return onerror(err); - src.close(srcHandle, (err) => { - srcHandle = undefined; - if (err) - return onerror(err); - cb(); - }); - }); - return; - } +/** + * @type {import('../types/client').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../types/client').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + allowH2, + maxConcurrentStreams + } = {}) { + super() - if (pdst >= fsize) - return; + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(datapos, pdst, chunk); - pdst += chunk; - } - } + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } - function makeCb(psrc, pdst, chunk) { - return (err, nb, data) => { - onread(err, nb, data, pdst, psrc, chunk); - }; - } + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } - function singleRead(psrc, pdst, chunk) { - src.read(srcHandle, - readbuf, - psrc, - chunk, - pdst, - makeCb(psrc, pdst, chunk)); - } + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } - function startReads() { - let reads = 0; - let psrc = 0; - while (pdst < fsize && reads < concurrency) { - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(psrc, pdst, chunk); - psrc += chunk; - pdst += chunk; - ++reads; - } - } - }); + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') } - }); -} -function writeAll(sftp, handle, buffer, offset, length, position, callback_) { - const callback = (typeof callback_ === 'function' ? callback_ : undefined); + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } - sftp.write(handle, - buffer, - offset, - length, - position, - (writeErr, written) => { - if (writeErr) { - return sftp.close(handle, () => { - callback && callback(writeErr); - }); + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') } - if (written === length) { - sftp.close(handle, callback); - } else { - offset += written; - length -= written; - position += written; - writeAll(sftp, handle, buffer, offset, length, position, callback); + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') } - }); -} -class Stats { - constructor(initial) { - this.mode = (initial && initial.mode); - this.uid = (initial && initial.uid); - this.gid = (initial && initial.gid); - this.size = (initial && initial.size); - this.atime = (initial && initial.atime); - this.mtime = (initial && initial.mtime); - this.extended = (initial && initial.extended); - } - isDirectory() { - return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); - } - isFile() { - return ((this.mode & constants.S_IFMT) === constants.S_IFREG); - } - isBlockDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); - } - isCharacterDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); - } - isSymbolicLink() { - return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); - } - isFIFO() { - return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); - } - isSocket() { - return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); - } -} + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } -function attrsToBytes(attrs) { - let flags = 0; - let nb = 0; + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } - if (typeof attrs === 'object' && attrs !== null) { - if (typeof attrs.size === 'number') { - flags |= ATTR.SIZE; - const val = attrs.size; - // Big Endian - ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 - ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 - ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 - ATTRS_BUF[nb++] = val / 4294967296; // 2**32 - ATTRS_BUF[nb++] = val / 16777216; // 2**24 - ATTRS_BUF[nb++] = val / 65536; // 2**16 - ATTRS_BUF[nb++] = val / 256; // 2**8 - ATTRS_BUF[nb++] = val; + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') } - if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { - flags |= ATTR.UIDGID; - const uid = attrs.uid; - const gid = attrs.gid; - // Big Endian - ATTRS_BUF[nb++] = uid >>> 24; - ATTRS_BUF[nb++] = uid >>> 16; - ATTRS_BUF[nb++] = uid >>> 8; - ATTRS_BUF[nb++] = uid; - ATTRS_BUF[nb++] = gid >>> 24; - ATTRS_BUF[nb++] = gid >>> 16; - ATTRS_BUF[nb++] = gid >>> 8; - ATTRS_BUF[nb++] = gid; + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') } - if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { - const mode = modeNum(attrs.mode); - flags |= ATTR.PERMISSIONS; - // Big Endian - ATTRS_BUF[nb++] = mode >>> 24; - ATTRS_BUF[nb++] = mode >>> 16; - ATTRS_BUF[nb++] = mode >>> 8; - ATTRS_BUF[nb++] = mode; + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') } - if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) - && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { - const atime = toUnixTimestamp(attrs.atime); - const mtime = toUnixTimestamp(attrs.mtime); - flags |= ATTR.ACMODTIME; - // Big Endian - ATTRS_BUF[nb++] = atime >>> 24; - ATTRS_BUF[nb++] = atime >>> 16; - ATTRS_BUF[nb++] = atime >>> 8; - ATTRS_BUF[nb++] = atime; - ATTRS_BUF[nb++] = mtime >>> 24; - ATTRS_BUF[nb++] = mtime >>> 16; - ATTRS_BUF[nb++] = mtime >>> 8; - ATTRS_BUF[nb++] = mtime; + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') } - // TODO: extended attributes - } - return { flags, nb }; -} + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } -function toUnixTimestamp(time) { - // eslint-disable-next-line no-self-compare - if (typeof time === 'number' && time === time) // Valid, non-NaN number - return time; - if (isDate(time)) - return parseInt(time.getTime() / 1000, 10); - throw new Error(`Cannot parse time: ${time}`); -} + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } -function modeNum(mode) { - // eslint-disable-next-line no-self-compare - if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number - return mode; - if (typeof mode === 'string') - return modeNum(parseInt(mode, 8)); - throw new Error(`Cannot parse mode: ${mode}`); -} + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } -const stringFlagMap = { - 'r': OPEN_MODE.READ, - 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, - 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL -}; + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } -function stringToFlags(str) { - const flags = stringFlagMap[str]; - return (flags !== undefined ? flags : null); -} + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') + } -const flagsToString = (() => { - const stringFlagMapKeys = Object.keys(stringFlagMap); - return (flags) => { - for (let i = 0; i < stringFlagMapKeys.length; ++i) { - const key = stringFlagMapKeys[i]; - if (stringFlagMap[key] === flags) - return key; + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) } - return null; - }; -})(); -function readAttrs(biOpt) { - /* - uint32 flags - uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE - uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS - uint32 atime present only if flag SSH_FILEXFER_ACMODTIME - uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME - uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED - string extended_type - string extended_data - ... more extended data (extended_type - extended_data pairs), - so that number of pairs equals extended_count - */ - const flags = bufferParser.readUInt32BE(); - if (flags === undefined) - return; + this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) + ? interceptors.Client + : [createRedirectInterceptor({ maxRedirections })] + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kSocket] = null + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRedirections] = maxRedirections + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + this[kHTTPConnVersion] = 'h1' - const attrs = new Stats(); - if (flags & ATTR.SIZE) { - const size = bufferParser.readUInt64BE(biOpt); - if (size === undefined) - return; - attrs.size = size; + // HTTP/2 + this[kHTTP2Session] = null + this[kHTTP2SessionState] = !allowH2 + ? null + : { + // streams: null, // Fixed queue of streams - For future support of `push` + openStreams: 0, // Keep track of them to decide wether or not unref the session + maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + } + this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 } - if (flags & ATTR.UIDGID) { - const uid = bufferParser.readUInt32BE(); - const gid = bufferParser.readUInt32BE(); - if (gid === undefined) - return; - attrs.uid = uid; - attrs.gid = gid; + get pipelining () { + return this[kPipelining] } - if (flags & ATTR.PERMISSIONS) { - const mode = bufferParser.readUInt32BE(); - if (mode === undefined) - return; - attrs.mode = mode; + set pipelining (value) { + this[kPipelining] = value + resume(this, true) } - if (flags & ATTR.ACMODTIME) { - const atime = bufferParser.readUInt32BE(); - const mtime = bufferParser.readUInt32BE(); - if (mtime === undefined) - return; - attrs.atime = atime; - attrs.mtime = mtime; + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] } - if (flags & ATTR.EXTENDED) { - const count = bufferParser.readUInt32BE(); - if (count === undefined) - return; - const extended = {}; - for (let i = 0; i < count; ++i) { - const type = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data === undefined) - return; - extended[type] = data; - } - attrs.extended = extended; + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] } - return attrs; -} + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } -function sendOrBuffer(sftp, payload) { - const ret = tryWritePayload(sftp, payload); - if (ret !== undefined) { - sftp._buffer.push(ret); - return false; + get [kConnected] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed } - return true; -} -function tryWritePayload(sftp, payload) { - const outgoing = sftp.outgoing; - if (outgoing.state !== 'open') - return; + get [kBusy] () { + const socket = this[kSocket] + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize] >= (this[kPipelining] || 1)) || + this[kPending] > 0 + ) + } - if (outgoing.window === 0) { - sftp._waitWindow = true; // XXX: Unnecessary? - return payload; + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) } - let ret; - const len = payload.length; - let p = 0; + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin - while (len - p > 0 && outgoing.window > 0) { - const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); - outgoing.window -= actualLen; - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; - } + const request = this[kHTTPConnVersion] === 'h2' + ? Request[kHTTP2BuildRequest](origin, opts, handler) + : Request[kHTTP1BuildRequest](origin, opts, handler) - if (p === 0 && actualLen === len) { - sftp._protocol.channelData(sftp.outgoing.id, payload); + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + process.nextTick(resume, this) } else { - sftp._protocol.channelData(sftp.outgoing.id, - bufferSlice(payload, p, p + actualLen)); + resume(this, true) } - p += actualLen; + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } + + return this[kNeedDrain] < 2 } - if (len - p > 0) { - if (p > 0) - ret = bufferSlice(payload, p, len); - else - ret = payload; // XXX: should never get here? + async [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (!this[kSize]) { + resolve(null) + } else { + this[kClosedResolve] = resolve + } + }) } - return ret; -} + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) + } -function drainBuffer() { - this._chunkcb = undefined; - const buffer = this._buffer; - let i = 0; - while (i < buffer.length) { - const payload = buffer[i]; - const ret = tryWritePayload(this, payload); - if (ret !== undefined) { - if (ret !== payload) - buffer[i] = ret; - if (i > 0) - this._buffer = buffer.slice(i); - return; - } - ++i; - } - if (i > 0) - this._buffer = []; -} + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve() + } -function doFatalSFTPError(sftp, msg, noDebug) { - const err = new Error(msg); - err.level = 'sftp-protocol'; - if (!noDebug && sftp._debug) - sftp._debug(`SFTP: Inbound: ${msg}`); - sftp.emit('error', err); - sftp.destroy(); - cleanupRequests(sftp); - return false; -} + if (this[kHTTP2Session] != null) { + util.destroy(this[kHTTP2Session], err) + this[kHTTP2Session] = null + this[kHTTP2SessionState] = null + } -function cleanupRequests(sftp) { - const keys = Object.keys(sftp._requests); - if (keys.length === 0) - return; + if (!this[kSocket]) { + queueMicrotask(callback) + } else { + util.destroy(this[kSocket].on('close', callback), err) + } - const reqs = sftp._requests; - sftp._requests = {}; - const err = new Error('No response from server'); - for (let i = 0; i < keys.length; ++i) { - const req = reqs[keys[i]]; - if (typeof req.cb === 'function') - req.cb(err); + resume(this) + }) } } -function requestLimits(sftp, cb) { - /* - uint32 id - string "limits@openssh.com" - */ - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + this[kSocket][kError] = err - writeUInt32BE(buf, 18, p); - buf.utf8Write('limits@openssh.com', p += 4, 18); + onError(this[kClient], err) +} - sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; +function onHttp2FrameError (type, code, id) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - const isBuffered = sendOrBuffer(sftp, buf); - if (sftp._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); + if (id === 0) { + this[kSocket][kError] = err + onError(this[kClient], err) } } -const CLIENT_HANDLERS = { - [RESPONSE.VERSION]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); - - const extensions = {}; +function onHttp2SessionEnd () { + util.destroy(this, new SocketError('other side closed')) + util.destroy(this[kSocket], new SocketError('other side closed')) +} - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); +function onHTTP2GoAway (code) { + const client = this[kClient] + const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) + client[kSocket] = null + client[kHTTP2Session] = null - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed VERSION packet'); + if (client.destroyed) { + assert(this[kPending] === 0) - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); - } + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) } + } else if (client[kRunning] > 0) { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null - sftp._version = version; - sftp._extensions = extensions; + errorRequest(client, request, err) + } - if (extensions['limits@openssh.com'] === '1') { - return requestLimits(sftp, (err, limits) => { - if (!err) { - if (limits.maxPktLen > 0) - sftp._maxOutPktLen = limits.maxPktLen; - if (limits.maxReadLen > 0) - sftp._maxReadLen = limits.maxReadLen; - if (limits.maxWriteLen > 0) - sftp._maxWriteLen = limits.maxWriteLen; - sftp.maxOpenHandles = ( - limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity - ); - } - sftp.emit('ready'); - }); - } + client[kPendingIdx] = client[kRunningIdx] - sftp.emit('ready'); - }, - [RESPONSE.STATUS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - uint32 error/status code - string error message (ISO-10646 UTF-8) - string language tag - */ - const errorCode = bufferParser.readUInt32BE(); - const errorMsg = bufferParser.readString(true); - bufferParser.clear(); + assert(client[kRunning] === 0) - // Note: we avoid checking that the error message and language tag are in - // the packet because there are some broken implementations that incorrectly - // omit them. The language tag in general was never really used amongst ssh - // implementations, so in the case of a missing error message we just - // default to something sensible. + client.emit('disconnect', + client[kUrl], + [client], + err + ) - if (sftp._debug) { - const jsonMsg = JSON.stringify(errorMsg); - sftp._debug( - `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` - ); - } - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') { - if (errorCode === STATUS_CODE.OK) { - req.cb(); - return; - } - const err = new Error(errorMsg - || STATUS_CODE_STR[errorCode] - || 'Unknown status'); - err.code = errorCode; - req.cb(err); - } - }, - [RESPONSE.HANDLE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); + resume(client) +} - if (handle === undefined) { - if (reqID !== undefined) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); - } +const constants = __nccwpck_require__(953) +const createRedirectInterceptor = __nccwpck_require__(8861) +const EMPTY_BUF = Buffer.alloc(0) - sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(1145) : undefined - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') - req.cb(undefined, handle); - }, - [RESPONSE.DATA]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - string data - */ - if (req && typeof req.cb === 'function') { - if (req.buffer) { - // We have already pre-allocated space to store the data + let mod + try { + mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(5627), 'base64')) + } catch (e) { + /* istanbul ignore next */ - const nb = bufferParser.readString(req.buffer); - bufferParser.clear(); + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(1145), 'base64')) + } - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - req.cb(undefined, req.buffer, nb); - return; - } - } else { - const data = bufferParser.readString(); - bufferParser.clear(); + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ - if (data !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` - ); - req.cb(undefined, data); - return; - } - } - } else { - const nb = bufferParser.skipString(); - bufferParser.clear(); - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - return; + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageComplete() || 0 } - } - return doFatalSFTPError(sftp, 'Malformed DATA packet'); - }, - [RESPONSE.NAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; + /* eslint-enable camelcase */ } - /* - uint32 count - repeats count times: - string filename - string longname - ATTRS attrs - */ - const count = bufferParser.readUInt32BE(); - if (count !== undefined) { - let names = []; - for (let i = 0; i < count; ++i) { - // We are going to assume UTF-8 for filenames despite the SFTPv3 - // spec not specifying an encoding because the specs for newer - // versions of the protocol all explicitly specify UTF-8 for - // filenames - const filename = bufferParser.readString(true); - - // `longname` only exists in SFTPv3 and since it typically will - // contain the filename, we assume it is also UTF-8 - const longname = bufferParser.readString(true); + }) +} - const attrs = readAttrs(sftp._biOpt); - if (attrs === undefined) { - names = undefined; - break; +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() + +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null + +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 + +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) + + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = null + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (value, type) { + this.timeoutType = type + if (value !== this.timeoutValue) { + timers.clearTimeout(this.timeout) + if (value) { + this.timeout = timers.setTimeout(onParserTimeout, value, this) + // istanbul ignore else: only for jest + if (this.timeout.unref) { + this.timeout.unref() } - names.push({ filename, longname, attrs }); + } else { + this.timeout = null } - if (names !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` - ); - bufferParser.clear(); - if (req && typeof req.cb === 'function') - req.cb(undefined, names); - return; + this.timeoutValue = value + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() } } + } - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed NAME packet'); - }, - [RESPONSE.ATTRS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; + resume () { + if (this.socket.destroyed || !this.paused) { + return } - /* - ATTRS attrs - */ - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs !== undefined) { - sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); - if (req && typeof req.cb === 'function') - req.cb(undefined, attrs); - return; + + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_resume(this.ptr) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } } - return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); - }, - [RESPONSE.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - if (reqID !== undefined) { - const req = sftp._requests[reqID]; - if (req) { - delete sftp._requests[reqID]; - switch (req.extended) { - case 'statvfs@openssh.com': - case 'fstatvfs@openssh.com': { - /* - uint64 f_bsize // file system block size - uint64 f_frsize // fundamental fs block size - uint64 f_blocks // number of blocks (unit f_frsize) - uint64 f_bfree // free blocks in file system - uint64 f_bavail // free blocks for non-root - uint64 f_files // total file inodes - uint64 f_ffree // free file inodes - uint64 f_favail // free file inodes for to non-root - uint64 f_fsid // file system id - uint64 f_flag // bit mask of f_flag values - uint64 f_namemax // maximum filename length - */ - const biOpt = sftp._biOpt; - const stats = { - f_bsize: bufferParser.readUInt64BE(biOpt), - f_frsize: bufferParser.readUInt64BE(biOpt), - f_blocks: bufferParser.readUInt64BE(biOpt), - f_bfree: bufferParser.readUInt64BE(biOpt), - f_bavail: bufferParser.readUInt64BE(biOpt), - f_files: bufferParser.readUInt64BE(biOpt), - f_ffree: bufferParser.readUInt64BE(biOpt), - f_favail: bufferParser.readUInt64BE(biOpt), - f_sid: bufferParser.readUInt64BE(biOpt), - f_flag: bufferParser.readUInt64BE(biOpt), - f_namemax: bufferParser.readUInt64BE(biOpt), - }; - if (stats.f_namemax === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, stats); - return; - } - case 'limits@openssh.com': { - /* - uint64 max-packet-length - uint64 max-read-length - uint64 max-write-length - uint64 max-open-handles - */ - const limits = { - maxPktLen: bufferParser.readUInt64BE(), - maxReadLen: bufferParser.readUInt64BE(), - maxWriteLen: bufferParser.readUInt64BE(), - maxOpenHandles: bufferParser.readUInt64BE(), - }; - if (limits.maxOpenHandles === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, limits); - return; - } - default: - // Unknown extended request - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(); - return; - } - } else { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - return; + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break } + this.execute(chunk) } + } - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); - }, -}; -const SERVER_HANDLERS = { - [REQUEST.INIT]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate INIT packet'); + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) - const extensions = {}; + const { socket, llhttp } = this - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) } - extensions[extName] = extData; + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) } - bufferParser.clear(); - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed INIT packet'); + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received INIT (v${version}, exts:${names})` - ); + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret + + try { + currentBufferRef = data + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(data.slice(offset)) + } else if (ret !== constants.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + /* istanbul ignore else: difficult to make a test case for */ + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')' + } + throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) + } + } catch (err) { + util.destroy(socket, err) + } + } + + destroy () { + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_free(this.ptr) + this.ptr = null + + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + + this.paused = false + } + + onStatus (buf) { + this.statusText = buf.toString() + } + + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 + } + } + + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + this.trackHeader(buf.length) + } + + onHeaderValue (buf) { + let len = this.headers.length + + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + const key = this.headers[len - 2] + if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { + this.connection += buf.toString() + } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { + this.contentLength += buf.toString() + } + + this.trackHeader(buf.length) + } + + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } + + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this + + assert(upgrade) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') + + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + socket.unshift(head) + + socket[kParser].destroy() + socket[kParser] = null + + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) + + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } + + resume(client) + } + + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert(!this.upgrade) + assert(this.statusCode < 200) + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } + + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) + + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout + } } else { - sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true } - sendOrBuffer(sftp, SERVER_VERSION_BUFFER); + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false - sftp._version = version; - sftp._extensions = extensions; - sftp.emit('ready'); - }, - [REQUEST.OPEN]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string filename - uint32 pflags - ATTRS attrs - */ - const filename = bufferParser.readString(true); - const pflags = bufferParser.readUInt32BE(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); + if (request.aborted) { + return -1 + } - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed OPEN packet'); + if (request.method === 'HEAD') { + return 1 + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); + if (statusCode < 200) { + return 1 + } - if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) } - }, - [REQUEST.CLOSE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); + return pause ? constants.ERROR.PAUSED : 0 + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this - if (!sftp.emit('CLOSE', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + if (socket.destroyed) { + return -1 } - }, - [REQUEST.READ]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - uint32 len - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const len = bufferParser.readUInt32BE(); - bufferParser.clear(); - if (len === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READ packet'); + const request = client[kQueue][client[kRunningIdx]] + assert(request) - sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); + assert.strictEqual(this.timeoutType, TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } - if (!sftp.emit('READ', reqID, handle, offset, len)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 } - }, - [REQUEST.WRITE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - string data - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const data = bufferParser.readString(); - bufferParser.clear(); - if (data === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed WRITE packet'); + this.bytesRead += buf.length - sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } - if (!sftp.emit('WRITE', reqID, handle, offset, data)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 } - }, - [REQUEST.LSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); + if (upgrade) { + return + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); + const request = client[kQueue][client[kRunningIdx]] + assert(request) - if (!sftp.emit('LSTAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + assert(statusCode >= 100) + + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (statusCode < 200) { + return } - }, - [REQUEST.FSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + request.onComplete(headers) + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert.strictEqual(client[kRunning], 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(resume, client) + } else { + resume(client) + } + } +} - sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); +function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser - if (!sftp.emit('FSTAT', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!parser.paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) } - }, - [REQUEST.SETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); + } else if (timeoutType === TIMEOUT_BODY) { + if (!parser.paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_IDLE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) + } +} - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); +function onSocketReadable () { + const { [kParser]: parser } = this + if (parser) { + parser.readMore() + } +} - sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); +function onSocketError (err) { + const { [kClient]: client, [kParser]: parser } = this - if (!sftp.emit('SETSTAT', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + if (client[kHTTPConnVersion] !== 'h2') { + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete() + return } - }, - [REQUEST.FSETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - ATTRS attrs - */ - const handle = bufferParser.readString(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); + } - if (attrs === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); + this[kError] = err - sftp._debug && sftp._debug( - `SFTP: Inbound: Received FSETSTAT (id:${reqID})` - ); + onError(this[kClient], err) +} - if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) } - }, - [REQUEST.OPENDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); + assert(client[kSize] === 0) + } +} - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); +function onSocketEnd () { + const { [kParser]: parser, [kClient]: client } = this - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); + if (client[kHTTPConnVersion] !== 'h2') { + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return + } + } - if (!sftp.emit('OPENDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onSocketClose () { + const { [kClient]: client, [kParser]: parser } = this + + if (client[kHTTPConnVersion] === 'h1' && parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() } - }, - [REQUEST.READDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READDIR packet'); + this[kParser].destroy() + this[kParser] = null + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) - if (!sftp.emit('READDIR', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + client[kSocket] = null + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) } - }, - [REQUEST.REMOVE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); + errorRequest(client, request, err) + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); + client[kPendingIdx] = client[kRunningIdx] - if (!sftp.emit('REMOVE', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + resume(client) +} + +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) + + let { host, hostname, protocol, port } = client[kUrl] + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') + + assert(idx !== -1) + const ip = hostname.substring(1, idx) + + assert(net.isIP(ip)) + hostname = ip + } + + client[kConnecting] = true + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err) + } else { + resolve(socket) + } + }) + }) + + if (client.destroyed) { + util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) + return } - }, - [REQUEST.MKDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); + client[kConnecting] = false - sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); + assert(socket) - if (!sftp.emit('MKDIR', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + const isH2 = socket.alpnProtocol === 'h2' + if (isH2) { + if (!h2ExperimentalWarned) { + h2ExperimentalWarned = true + process.emitWarning('H2 support is experimental, expect them to change at any time.', { + code: 'UNDICI-H2' + }) + } + + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }) + + client[kHTTPConnVersion] = 'h2' + session[kClient] = client + session[kSocket] = socket + session.on('error', onHttp2SessionError) + session.on('frameError', onHttp2FrameError) + session.on('end', onHttp2SessionEnd) + session.on('goaway', onHTTP2GoAway) + session.on('close', onSocketClose) + session.unref() + + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + } else { + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = null + } + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) } - }, - [REQUEST.RMDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null - sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) - if (!sftp.emit('RMDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + client[kSocket] = socket + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) + } + client.emit('connect', client[kUrl], [client]) + } catch (err) { + if (client.destroyed) { + return } - }, - [REQUEST.REALPATH]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); + client[kConnecting] = false - sftp._debug && sftp._debug( - `SFTP: Inbound: Received REALPATH (id:${reqID})` - ); + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } - if (!sftp.emit('REALPATH', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + errorRequest(client, request, err) + } + } else { + onError(client, err) } - }, - [REQUEST.STAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed STAT packet'); + client.emit('connectionError', client[kUrl], [client], err) + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); + resume(client) +} - if (!sftp.emit('STAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return } - }, - [REQUEST.RENAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string oldpath - string newpath - */ - const oldPath = bufferParser.readString(true); - const newPath = bufferParser.readString(true); - bufferParser.clear(); - if (newPath === undefined) - return doFatalSFTPError(sftp, 'Malformed RENAME packet'); + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); + const socket = client[kSocket] - if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) + } + } } - }, - [REQUEST.READLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed READLINK packet'); + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) + } else { + emitDrain(client) + } + continue + } - sftp._debug && sftp._debug( - `SFTP: Inbound: Received READLINK (id:${reqID})` - ); + if (client[kPending] === 0) { + return + } - if (!sftp.emit('READLINK', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + if (client[kRunning] >= (client[kPipelining] || 1)) { + return } - }, - [REQUEST.SYMLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string linkpath - string targetpath - */ - const linkPath = bufferParser.readString(true); - const targetPath = bufferParser.readString(true); - bufferParser.clear(); - if (targetPath === undefined) - return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); + const request = client[kQueue][client[kPendingIdx]] - sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } - let handled; - if (sftp._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); - } else { - handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); - } - if (!handled) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string extended-request - ... any request-specific data ... - */ - const extName = bufferParser.readString(true); - if (extName === undefined) { - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); + client[kServerName] = request.servername + + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return + } } - let extData; - if (bufferParser.avail()) - extData = bufferParser.readRaw(); - bufferParser.clear(); + if (client[kConnecting]) { + return + } - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED (id:${reqID})` - ); + if (!socket && !client[kHTTP2Session]) { + connect(client) + return + } - if (!sftp.emit('EXTENDED', reqID, extName, extData)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return } - }, -}; -// ============================================================================= -// ReadStream/WriteStream-related ============================================== -// ============================================================================= -const { - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE, - validateNumber -} = __nccwpck_require__(7609); + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } -const kMinPoolSpace = 128; + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return + } -let pool; -// It can happen that we expect to read a large chunk of data, and reserve -// a large chunk of the pool accordingly, but the read() call only filled -// a portion of it. If a concurrently executing read() then uses the same pool, -// the "reserved" portion cannot be used, so we allow it to be re-used as a -// new pool later. -const poolFragments = []; + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. -function allocNewPool(poolSize) { - if (poolFragments.length > 0) - pool = poolFragments.pop(); - else - pool = Buffer.allocUnsafe(poolSize); - pool.used = 0; -} + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } -// Check the `this.start` and `this.end` of stream. -function checkPosition(pos, name) { - if (!Number.isSafeInteger(pos)) { - validateNumber(pos, name); - if (!Number.isInteger(pos)) - throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } } - if (pos < 0) - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); } -function roundUpToMultipleOf8(n) { - return (n + 7) & ~7; // Align to 8 byte boundary. +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' } -function ReadStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); +function write (client, request) { + if (client[kHTTPConnVersion] === 'h2') { + writeH2(client, client[kHTTP2Session], request) + return + } - // A little bit bigger buffer and water marks by default - if (options.highWaterMark === undefined) - options.highWaterMark = 64 * 1024; + const { body, method, path, host, upgrade, headers, blocking, reset } = request - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 - ReadableStream.call(this, options); + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. - this.path = path; - this.flags = options.flags === undefined ? 'r' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) - this.start = options.start; - this.end = options.end; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesRead = 0; - this.closed = false; + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; + const bodyLength = util.bodyLength(body) - if (this.start !== undefined) { - checkPosition(this.start, 'start'); + let contentLength = bodyLength - this.pos = this.start; + if (contentLength === null) { + contentLength = request.contentLength } - if (this.end === undefined) { - this.end = Infinity; - } else if (this.end !== Infinity) { - checkPosition(this.end, 'end'); + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. - if (this.start !== undefined && this.start > this.end) { - throw new ERR_OUT_OF_RANGE( - 'start', - `<= "end" (here: ${this.end})`, - this.start - ); + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false } + + process.emitWarning(new RequestContentLengthMismatchError()) } - this.on('end', function() { - if (this.autoClose) - this.destroy(); - }); + const socket = client[kSocket] - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(ReadStream, ReadableStream); + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } -ReadStream.prototype.open = function() { - if (this._opening) - return; + errorRequest(client, request, err || new RequestAbortedError()) - this._opening = true; + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) + } - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; + if (request.aborted) { + return false + } - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; - } + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. - this.handle = handle; - this.emit('open', handle); - this.emit('ready'); - // Start the flow of data. - this.read(); - }); -}; + socket[kReset] = true + } -ReadStream.prototype._read = function(n) { - if (!Buffer.isBuffer(this.handle)) - return this.once('open', () => this._read(n)); + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. - // XXX: safe to remove this? - if (this.destroyed) - return; + socket[kReset] = true + } - if (!pool || pool.length - pool.used < kMinPoolSpace) { - // Discard the old pool. - allocNewPool(this.readableHighWaterMark - || this._readableState.highWaterMark); + if (reset != null) { + socket[kReset] = reset } - // Grab another reference to the pool in the case that while we're - // in the thread pool another read() finishes up the pool, and - // allocates a new one. - const thisPool = pool; - let toRead = Math.min(pool.length - pool.used, n); - const start = pool.used; + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } - if (this.end !== undefined) - toRead = Math.min(this.end - this.pos + 1, toRead); + if (blocking) { + socket[kBlocking] = true + } - // Already read everything we were supposed to read! - // treat as EOF. - if (toRead <= 0) - return this.push(null); + let header = `${method} ${path} HTTP/1.1\r\n` - // the actual read. - this.sftp.read(this.handle, - pool, - pool.used, - toRead, - this.pos, - (er, bytesRead) => { - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; - } - let b = null; + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } - // Now that we know how much data we have actually read, re-wind the - // 'used' field if we can, and otherwise allow the remainder of our - // reservation to be used as a new pool later. - if (start + toRead === thisPool.used && thisPool === pool) { - thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } + + if (headers) { + header += headers + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + /* istanbul ignore else: assertion */ + if (!body || bodyLength === 0) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { - // Round down to the next lowest multiple of 8 to ensure the new pool - // fragment start and end positions are aligned to an 8 byte boundary. - const alignedEnd = (start + toRead) & ~7; - const alignedStart = roundUpToMultipleOf8(start + bytesRead); - if (alignedEnd - alignedStart >= kMinPoolSpace) - poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'latin1') + } + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(body) + socket.uncork() + request.onBodySent(body) + request.onRequestSent() + if (!expectsPayload) { + socket[kReset] = true + } + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) + } else { + writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) } + } else if (util.isStream(body)) { + writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) + } else if (util.isIterable(body)) { + writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) + } else { + assert(false) + } - if (bytesRead > 0) { - this.bytesRead += bytesRead; - b = thisPool.slice(start, start + bytesRead); - } + return true +} - // Move the pool positions, and internal position for reading. - this.pos += bytesRead; +function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request - this.push(b); - }); + let headers + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) + else headers = reqHeaders - pool.used = roundUpToMultipleOf8(pool.used + toRead); -}; + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } -ReadStream.prototype._destroy = function(err, cb) { - if (this._opening && !Buffer.isBuffer(this.handle)) { - this.once('open', closeStream.bind(null, this, cb, err)); - return; + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError()) + }) + } catch (err) { + errorRequest(client, request, err) } - closeStream(this, cb, err); - this.handle = null; - this._opening = false; -}; + if (request.aborted) { + return false + } -function closeStream(stream, cb, err) { - if (!stream.handle) - return onclose(); + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream + const h2State = client[kHTTP2SessionState] - stream.sftp.close(stream.handle, onclose); + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] + headers[HTTP2_HEADER_METHOD] = method - function onclose(er) { - er = er || err; - cb(er); - stream.closed = true; - if (!er) - stream.emit('close'); + if (method === 'CONNECT') { + session.ref() + // we are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }) + + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + }) + } + + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref() + }) + + return true } -} -ReadStream.prototype.close = function(cb) { - this.destroy(null, cb); -}; + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT -Object.defineProperty(ReadStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' -// TODO: add `concurrency` setting to allow more than one in-flight WRITE -// request to server to improve throughput -function WriteStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. - WritableStream.call(this, options); + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) - this.path = path; - this.flags = options.flags === undefined ? 'w' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } - this.start = options.start; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesWritten = 0; - this.closed = false; + let contentLength = util.bodyLength(body) - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; + if (contentLength == null) { + contentLength = request.contentLength + } - if (this.start !== undefined) { - checkPosition(this.start, 'start'); + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. - this.pos = this.start; + contentLength = null } - if (options.encoding) - this.setDefaultEncoding(options.encoding); + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } - // Node v6.x only - this.on('finish', function() { - if (this._writableState.finalCalled) - return; - if (this.autoClose) - this.destroy(); - }); + process.emitWarning(new RequestContentLengthMismatchError()) + } - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(WriteStream, WritableStream); + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } -WriteStream.prototype._final = function(cb) { - if (this.autoClose) - this.destroy(); - cb(); -}; + session.ref() -WriteStream.prototype.open = function() { - if (this._opening) - return; + const shouldEndStream = method === 'GET' || method === 'HEAD' + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + stream = session.request(headers, { endStream: shouldEndStream, signal }) - this._opening = true; + stream.once('continue', writeBodyH2) + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + writeBodyH2() + } - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; + // Increment counter as we have new several streams open + ++h2State.openStreams - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + + if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { + stream.pause() } + }) - this.handle = handle; + stream.once('end', () => { + request.onComplete([]) + }) - const tryAgain = (err) => { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() for - // whatever reason - this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); - return; - } + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause() + } + }) - // SFTPv3 requires absolute offsets, no matter the open flag used - if (this.flags[0] === 'a') { - const tryStat = (err, st) => { - if (err) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.sftp.stat(this.path, (err_, st_) => { - if (err_) { - this.destroy(); - this.emit('error', err); - return; - } - tryStat(null, st_); - }); - return; - } + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) { + session.unref() + } + }) - this.pos = st.size; - this.emit('open', handle); - this.emit('ready'); - }; + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) - this.sftp.fstat(handle, tryStat); - return; - } + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + errorRequest(client, request, err) - this.emit('open', handle); - this.emit('ready'); - }; + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) - this.sftp.fchmod(handle, this.mode, tryAgain); - }); -}; + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) -WriteStream.prototype._write = function(data, encoding, cb) { - if (!Buffer.isBuffer(data)) { - const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); - return this.emit('error', err); - } + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._write(data, encoding, cb); - }); - } + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) - this.sftp.write(this.handle, - data, - 0, - data.length, - this.pos, - (er, bytes) => { - if (er) { - if (this.autoClose) - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - cb(); - }); + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) - this.pos += data.length; -}; + return true -WriteStream.prototype._writev = function(data, cb) { - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._writev(data, cb); - }); + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body) { + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + stream.cork() + stream.write(body) + stream.uncork() + stream.end() + request.onBodySent(body) + request.onRequestSent() + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ + client, + request, + contentLength, + h2stream: stream, + expectsPayload, + body: body.stream(), + socket: client[kSocket], + header: '' + }) + } else { + writeBlob({ + body, + client, + request, + contentLength, + expectsPayload, + h2stream: stream, + header: '', + socket: client[kSocket] + }) + } + } else if (util.isStream(body)) { + writeStream({ + body, + client, + request, + contentLength, + expectsPayload, + socket: client[kSocket], + h2stream: stream, + header: '' + }) + } else if (util.isIterable(body)) { + writeIterable({ + body, + client, + request, + contentLength, + expectsPayload, + header: '', + h2stream: stream, + socket: client[kSocket] + }) + } else { + assert(false) + } } +} - const sftp = this.sftp; - const handle = this.handle; - let writesLeft = data.length; +function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') - const onwrite = (er, bytes) => { - if (er) { - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - if (--writesLeft === 0) - cb(); - }; + if (client[kHTTPConnVersion] === 'h2') { + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(body, err) + util.destroy(h2stream, err) + } else { + request.onRequestSent() + } + } + ) - // TODO: try to combine chunks to reduce number of requests to the server? - for (let i = 0; i < data.length; ++i) { - const chunk = data[i].chunk; + pipe.on('data', onPipeData) + pipe.once('end', () => { + pipe.removeListener('data', onPipeData) + util.destroy(pipe) + }) - sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); - this.pos += chunk.length; + function onPipeData (chunk) { + request.onBodySent(chunk) + } + + return } -}; -if (typeof WritableStream.prototype.destroy !== 'function') - WriteStream.prototype.destroy = ReadStream.prototype.destroy; + let finished = false -WriteStream.prototype._destroy = ReadStream.prototype._destroy; -WriteStream.prototype.close = function(cb) { - if (cb) { - if (this.closed) { - process.nextTick(cb); - return; + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } + } + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume() } - this.on('close', cb); } + const onAbort = function () { + if (finished) { + return + } + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) + } + const onFinished = function (err) { + if (finished) { + return + } - // If we are not autoClosing, we should call - // destroy on 'finish'. - if (!this.autoClose) - this.on('finish', this.destroy.bind(this)); + finished = true - this.end(); -}; + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) -// There is no shutdown() for files. -WriteStream.prototype.destroySoon = WriteStream.prototype.end; + socket + .off('drain', onDrain) + .off('error', onFinished) -Object.defineProperty(WriteStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); -// ============================================================================= + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) -module.exports = { - flagsToString, - OPEN_MODE, - SFTP, - Stats, - STATUS_CODE, - stringToFlags, -}; + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } + writer.destroy(err) -/***/ }), + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } -/***/ 6832: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) -"use strict"; + if (body.resume) { + body.resume() + } + socket + .on('drain', onDrain) + .on('error', onFinished) +} -const crypto = __nccwpck_require__(6113); +async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') -let cpuInfo; -try { - cpuInfo = __nccwpck_require__(4137)(); -} catch {} + const isH2 = client[kHTTPConnVersion] === 'h2' + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } -const { bindingAvailable } = __nccwpck_require__(5708); + const buffer = Buffer.from(await body.arrayBuffer()) -const eddsaSupported = (() => { - if (typeof crypto.sign === 'function' - && typeof crypto.verify === 'function') { - const key = - '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' - + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; - const data = Buffer.from('a'); - let sig; - let verified; - try { - sig = crypto.sign(null, data, key); - verified = crypto.verify(null, data, key, sig); - } catch {} - return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); - } + if (isH2) { + h2stream.cork() + h2stream.write(buffer) + h2stream.uncork() + } else { + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(buffer) + socket.uncork() + } - return false; -})(); + request.onBodySent(buffer) + request.onRequestSent() -const curve25519Supported = (typeof crypto.diffieHellman === 'function' - && typeof crypto.generateKeyPairSync === 'function' - && typeof crypto.createPublicKey === 'function'); + if (!expectsPayload) { + socket[kReset] = true + } -const DEFAULT_KEX = [ - // https://tools.ietf.org/html/rfc5656#section-10.1 - 'ecdh-sha2-nistp256', - 'ecdh-sha2-nistp384', - 'ecdh-sha2-nistp521', + resume(client) + } catch (err) { + util.destroy(isH2 ? h2stream : socket, err) + } +} - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha256', +async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') - // https://tools.ietf.org/html/rfc8268 - 'diffie-hellman-group14-sha256', - 'diffie-hellman-group15-sha512', - 'diffie-hellman-group16-sha512', - 'diffie-hellman-group17-sha512', - 'diffie-hellman-group18-sha512', -]; -if (curve25519Supported) { - DEFAULT_KEX.unshift('curve25519-sha256'); - DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); -} -const SUPPORTED_KEX = DEFAULT_KEX.concat([ - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha1', + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } - 'diffie-hellman-group14-sha1', // REQUIRED - 'diffie-hellman-group1-sha1', // REQUIRED -]); + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) -const DEFAULT_SERVER_HOST_KEY = [ - 'ecdsa-sha2-nistp256', - 'ecdsa-sha2-nistp384', - 'ecdsa-sha2-nistp521', - 'rsa-sha2-512', // RFC 8332 - 'rsa-sha2-256', // RFC 8332 - 'ssh-rsa', -]; -if (eddsaSupported) - DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); -const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ - 'ssh-dss', -]); + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } -const DEFAULT_CIPHER = [ - // http://tools.ietf.org/html/rfc5647 - 'aes128-gcm@openssh.com', - 'aes256-gcm@openssh.com', + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { + await waitForDrain() + } + } + } catch (err) { + h2stream.destroy(err) + } finally { + request.onRequestSent() + h2stream.end() + h2stream + .off('close', onDrain) + .off('drain', onDrain) + } - // http://tools.ietf.org/html/rfc4344#section-4 - 'aes128-ctr', - 'aes192-ctr', - 'aes256-ctr', -]; -if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { - // We know for sure the CPU does not support AES acceleration - if (bindingAvailable) - DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); - else - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { - // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers - // seem to outperform it on x86, but it seems to be faster than CTR ciphers - DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); -} else { - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} -const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ - 'aes256-cbc', - 'aes192-cbc', - 'aes128-cbc', - 'blowfish-cbc', - '3des-cbc', - 'aes128-gcm', - 'aes256-gcm', + return + } - // http://tools.ietf.org/html/rfc4345#section-4: - 'arcfour256', - 'arcfour128', + socket + .on('close', onDrain) + .on('drain', onDrain) - 'cast128-cbc', - 'arcfour', -]); + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + if (!writer.write(chunk)) { + await waitForDrain() + } + } -const DEFAULT_MAC = [ - 'hmac-sha2-256-etm@openssh.com', - 'hmac-sha2-512-etm@openssh.com', - 'hmac-sha1-etm@openssh.com', - 'hmac-sha2-256', - 'hmac-sha2-512', - 'hmac-sha1', -]; -const SUPPORTED_MAC = DEFAULT_MAC.concat([ - 'hmac-md5', - 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 - 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 - 'hmac-ripemd160', - 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 - 'hmac-md5-96', // first 96 bits of HMAC-MD5 -]); + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} -const DEFAULT_COMPRESSION = [ - 'none', - 'zlib@openssh.com', // ZLIB (LZ77) compression, except - // compression/decompression does not start until after - // successful user authentication - 'zlib', // ZLIB (LZ77) compression -]; -const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ -]); +class AsyncWriter { + constructor ({ socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header + socket[kWriting] = true + } -const COMPAT = { - BAD_DHGEX: 1 << 0, - OLD_EXIT: 1 << 1, - DYN_RPORT_BUG: 1 << 2, - BUG_DHGEX_LARGE: 1 << 3, -}; + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this -module.exports = { - MESSAGE: { - // Transport layer protocol -- generic (1-19) - DISCONNECT: 1, - IGNORE: 2, - UNIMPLEMENTED: 3, - DEBUG: 4, - SERVICE_REQUEST: 5, - SERVICE_ACCEPT: 6, + if (socket[kError]) { + throw socket[kError] + } - // Transport layer protocol -- algorithm negotiation (20-29) - KEXINIT: 20, - NEWKEYS: 21, + if (socket.destroyed) { + return false + } - // Transport layer protocol -- key exchange method-specific (30-49) - KEXDH_INIT: 30, - KEXDH_REPLY: 31, + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } - KEXDH_GEX_GROUP: 31, - KEXDH_GEX_INIT: 32, - KEXDH_GEX_REPLY: 33, - KEXDH_GEX_REQUEST: 34, + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } - KEXECDH_INIT: 30, - KEXECDH_REPLY: 31, + process.emitWarning(new RequestContentLengthMismatchError()) + } - // User auth protocol -- generic (50-59) - USERAUTH_REQUEST: 50, - USERAUTH_FAILURE: 51, - USERAUTH_SUCCESS: 52, - USERAUTH_BANNER: 53, + socket.cork() - // User auth protocol -- user auth method-specific (60-79) - USERAUTH_PASSWD_CHANGEREQ: 60, + if (bytesWritten === 0) { + if (!expectsPayload) { + socket[kReset] = true + } - USERAUTH_PK_OK: 60, + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + } + } - USERAUTH_INFO_REQUEST: 60, - USERAUTH_INFO_RESPONSE: 61, + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } - // Connection protocol -- generic (80-89) - GLOBAL_REQUEST: 80, - REQUEST_SUCCESS: 81, - REQUEST_FAILURE: 82, + this.bytesWritten += len - // Connection protocol -- channel-related (90-127) - CHANNEL_OPEN: 90, - CHANNEL_OPEN_CONFIRMATION: 91, - CHANNEL_OPEN_FAILURE: 92, - CHANNEL_WINDOW_ADJUST: 93, - CHANNEL_DATA: 94, - CHANNEL_EXTENDED_DATA: 95, - CHANNEL_EOF: 96, - CHANNEL_CLOSE: 97, - CHANNEL_REQUEST: 98, - CHANNEL_SUCCESS: 99, - CHANNEL_FAILURE: 100 + const ret = socket.write(chunk) - // Reserved for client protocols (128-191) + socket.uncork() - // Local extensions (192-155) - }, - DISCONNECT_REASON: { - HOST_NOT_ALLOWED_TO_CONNECT: 1, - PROTOCOL_ERROR: 2, - KEY_EXCHANGE_FAILED: 3, - RESERVED: 4, - MAC_ERROR: 5, - COMPRESSION_ERROR: 6, - SERVICE_NOT_AVAILABLE: 7, - PROTOCOL_VERSION_NOT_SUPPORTED: 8, - HOST_KEY_NOT_VERIFIABLE: 9, - CONNECTION_LOST: 10, - BY_APPLICATION: 11, - TOO_MANY_CONNECTIONS: 12, - AUTH_CANCELED_BY_USER: 13, - NO_MORE_AUTH_METHODS_AVAILABLE: 14, - ILLEGAL_USER_NAME: 15, - }, - DISCONNECT_REASON_STR: undefined, - CHANNEL_OPEN_FAILURE: { - ADMINISTRATIVELY_PROHIBITED: 1, - CONNECT_FAILED: 2, - UNKNOWN_CHANNEL_TYPE: 3, - RESOURCE_SHORTAGE: 4 - }, - TERMINAL_MODE: { - TTY_OP_END: 0, // Indicates end of options. - VINTR: 1, // Interrupt character; 255 if none. Similarly for the - // other characters. Not all of these characters are - // supported on all systems. - VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX - // systems). - VERASE: 3, // Erase the character to left of the cursor. - VKILL: 4, // Kill the current input line. - VEOF: 5, // End-of-file character (sends EOF from the - // terminal). - VEOL: 6, // End-of-line character in addition to carriage - // return and/or linefeed. - VEOL2: 7, // Additional end-of-line character. - VSTART: 8, // Continues paused output (normally control-Q). - VSTOP: 9, // Pauses output (normally control-S). - VSUSP: 10, // Suspends the current program. - VDSUSP: 11, // Another suspend character. - VREPRINT: 12, // Reprints the current input line. - VWERASE: 13, // Erases a word left of cursor. - VLNEXT: 14, // Enter the next character typed literally, even if - // it is a special character - VFLUSH: 15, // Character to flush output. - VSWTCH: 16, // Switch to a different shell layer. - VSTATUS: 17, // Prints system status line (load, command, pid, - // etc). - VDISCARD: 18, // Toggles the flushing of terminal output. - IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 - // if this flag is FALSE, and 1 if it is TRUE. - PARMRK: 31, // Mark parity and framing errors. - INPCK: 32, // Enable checking of parity errors. - ISTRIP: 33, // Strip 8th bit off characters. - INLCR: 34, // Map NL into CR on input. - IGNCR: 35, // Ignore CR on input. - ICRNL: 36, // Map CR to NL on input. - IUCLC: 37, // Translate uppercase characters to lowercase. - IXON: 38, // Enable output flow control. - IXANY: 39, // Any char will restart after stop. - IXOFF: 40, // Enable input flow control. - IMAXBEL: 41, // Ring bell on input queue full. - ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. - ICANON: 51, // Canonicalize input lines. - XCASE: 52, // Enable input and output of uppercase characters by - // preceding their lowercase equivalents with "\". - ECHO: 53, // Enable echoing. - ECHOE: 54, // Visually erase chars. - ECHOK: 55, // Kill character discards current line. - ECHONL: 56, // Echo NL even if ECHO is off. - NOFLSH: 57, // Don't flush after interrupt. - TOSTOP: 58, // Stop background jobs from output. - IEXTEN: 59, // Enable extensions. - ECHOCTL: 60, // Echo control characters as ^(Char). - ECHOKE: 61, // Visual erase for line kill. - PENDIN: 62, // Retype pending input. - OPOST: 70, // Enable output processing. - OLCUC: 71, // Convert lowercase to uppercase. - ONLCR: 72, // Map NL to CR-NL. - OCRNL: 73, // Translate carriage return to newline (output). - ONOCR: 74, // Translate newline to carriage return-newline - // (output). - ONLRET: 75, // Newline performs a carriage return (output). - CS7: 90, // 7 bit mode. - CS8: 91, // 8 bit mode. - PARENB: 92, // Parity enable. - PARODD: 93, // Odd parity, else even. - TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. - TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. - }, - CHANNEL_EXTENDED_DATATYPE: { - STDERR: 1, - }, + request.onBodySent(chunk) - SIGNALS: [ - 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', - 'USR2', 'KILL', 'PIPE' - ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + } - COMPAT, - COMPAT_CHECKS: [ - [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], - [ /^Cisco-1\./, COMPAT.BUG_DHGEX_LARGE ], - [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations - [ /^OpenSSH_5\.\d+/, COMPAT.DYN_RPORT_BUG ], - ], + return ret + } - // KEX proposal-related - DEFAULT_KEX, - SUPPORTED_KEX, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY, - DEFAULT_CIPHER, - SUPPORTED_CIPHER, - DEFAULT_MAC, - SUPPORTED_MAC, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION, + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() - curve25519Supported, - eddsaSupported, -}; + socket[kWriting] = false -module.exports.DISCONNECT_REASON_BY_VALUE = - Array.from(Object.entries(module.exports.DISCONNECT_REASON)) - .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); + if (socket[kError]) { + throw socket[kError] + } + if (socket.destroyed) { + return + } -/***/ }), + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. -/***/ 5708: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + socket.write(`${header}\r\n`, 'latin1') + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1') + } -"use strict"; -// TODO: -// * make max packet size configurable -// * if decompression is enabled, use `._packet` in decipher instances as -// input to (sync) zlib inflater with appropriate offset and length to -// avoid an additional copy of payload data before inflation -// * factor decompression status into packet length checks + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } -const { - createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual -} = __nccwpck_require__(6113); + resume(client) + } -const { readUInt32BE, writeUInt32BE } = __nccwpck_require__(9475); + destroy (err) { + const { socket, client } = this -const FastBuffer = Buffer[Symbol.species]; -const MAX_SEQNO = 2 ** 32 - 1; -const EMPTY_BUFFER = Buffer.alloc(0); -const BUF_INT = Buffer.alloc(4); -const DISCARD_CACHE = new Map(); -const MAX_PACKET_SIZE = 35000; + socket[kWriting] = false -let binding; -let AESGCMCipher; -let ChaChaPolyCipher; -let GenericCipher; -let AESGCMDecipher; -let ChaChaPolyDecipher; -let GenericDecipher; -try { - binding = __nccwpck_require__(9041); - ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, - AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); -} catch {} + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + util.destroy(socket, err) + } + } +} -const CIPHER_STREAM = 1 << 0; -const CIPHER_INFO = (() => { - function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { - return { - sslName, - blockLen, - keyLen, - ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) - ? ivLen - : blockLen), - authLen, - discardLen, - stream: !!(flags & CIPHER_STREAM), - }; +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) } +} - return { - 'chacha20-poly1305@openssh.com': - info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), +module.exports = Client - 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - 'aes128-gcm@openssh.com': - info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm@openssh.com': - info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), - 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), - 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), - 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), - 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), - 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), +/***/ }), - 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), - 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), - 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), - '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), - 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), +/***/ 6436: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. +"use strict"; - -- http://tools.ietf.org/html/rfc4345#section-4 */ - 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), - 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), - }; -})(); -const MAC_INFO = (() => { - function info(sslName, len, actualLen, isETM) { - return { - sslName, - len, - actualLen, - isETM, - }; - } +/* istanbul ignore file: only for Node 12 */ - return { - 'hmac-md5': info('md5', 16, 16, false), - 'hmac-md5-96': info('md5', 16, 12, false), - 'hmac-ripemd160': info('ripemd160', 20, 20, false), - 'hmac-sha1': info('sha1', 20, 20, false), - 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), - 'hmac-sha1-96': info('sha1', 20, 12, false), - 'hmac-sha2-256': info('sha256', 32, 32, false), - 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), - 'hmac-sha2-256-96': info('sha256', 32, 12, false), - 'hmac-sha2-512': info('sha512', 64, 64, false), - 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), - 'hmac-sha2-512-96': info('sha512', 64, 12, false), - }; -})(); +const { kConnected, kSize } = __nccwpck_require__(2785) + +class CompatWeakRef { + constructor (value) { + this.value = value + } + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} -// Should only_be used during the initial handshake -class NullCipher { - constructor(seqno, onWrite) { - this.outSeqno = seqno; - this._onWrite = onWrite; - this._dead = false; +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer } - free() { - this._dead = true; + + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; +} - const packet = Buffer.allocUnsafe(pktLen); +module.exports = function () { + // FIXME: remove workaround when the Node bug is fixed + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (process.env.NODE_V8_COVERAGE) { + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + } + } + return { + WeakRef: global.WeakRef || CompatWeakRef, + FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer + } +} - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); +/***/ }), - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet +/***/ 663: +/***/ ((module) => { - if (this._dead) - return; +"use strict"; - this._onWrite(packet); - this.outSeqno = (this.outSeqno + 1) >>> 0; - } +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 + +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize } -const POLY1305_ZEROS = Buffer.alloc(32); -const POLY1305_OUT_COMPUTE = Buffer.alloc(16); -let POLY1305_WASM_MODULE; -let POLY1305_RESULT_MALLOC; -let poly1305_auth; -class ChaChaPolyCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encKeyMain = enc.cipherKey.slice(0, 32); - this._encKeyPktLen = enc.cipherKey.slice(32); - this._dead = false; +/***/ }), + +/***/ 1724: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { parseSetCookie } = __nccwpck_require__(4408) +const { stringify, getHeadersList } = __nccwpck_require__(3121) +const { webidl } = __nccwpck_require__(1744) +const { Headers } = __nccwpck_require__(554) + +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ + +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookie = headers.get('cookie') + const out = {} + + if (!cookie) { + return out } - free() { - this._dead = true; + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') + + out[name.trim()] = value.join('=') } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); + return out +} - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) - randomFillSync(packet, 5 + payloadLen, padLen); + webidl.brandCheck(headers, Headers, { strict: false }) - return packet; + name = webidl.converters.DOMString(name) + attributes = webidl.converters.DeleteCookieAttributes(attributes) + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} + +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookies = getHeadersList(headers).cookies + + if (!cookies) { + return [] } - encrypt(packet) { - // `packet` === unencrypted packet - if (this._dead) - return; + // In older versions of undici, cookies is a list of name:value. + return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair)) +} - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) - // Encrypt packet length - const pktLenEnc = - createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) - .update(packet.slice(0, 4)); - this._onWrite(pktLenEnc); + webidl.brandCheck(headers, Headers, { strict: false }) - // Encrypt rest of packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const payloadEnc = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(packet.slice(4)); - this._onWrite(payloadEnc); + cookie = webidl.converters.Cookie(cookie) - // Calculate Poly1305 MAC - poly1305_auth(POLY1305_RESULT_MALLOC, - pktLenEnc, - pktLenEnc.length, - payloadEnc, - payloadEnc.length, - polyKey); - const mac = Buffer.allocUnsafe(16); - mac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - this._onWrite(mac); + const str = stringify(cookie) - this.outSeqno = (this.outSeqno + 1) >>> 0; + if (str) { + headers.append('Set-Cookie', stringify(cookie)) } } -class ChaChaPolyCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new ChaChaPolyCipher(enc.cipherKey); - this._dead = false; +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null } - free() { - this._dead = true; - this._instance.free(); +]) + +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: [] } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; +]) - const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie +} - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); +/***/ }), - return packet; +/***/ 4408: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(663) +const { isCTLExcludingHtab } = __nccwpck_require__(3121) +const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685) +const assert = __nccwpck_require__(9491) + +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header } - encrypt(packet) { - // `packet` === unencrypted packet - if (this._dead) - return; + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() - this._onWrite(packet); + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } - this.outSeqno = (this.outSeqno + 1) >>> 0; + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) } } +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: -class AESGCMCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encSSLName = enc.cipherInfo.sslName; - this._encKey = enc.cipherKey; - this._encIV = enc.cipherIV; - this._dead = false; - } - free() { - this._dead = true; + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); + // Let the cookie-av string be the characters consumed in this step. - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; + let attributeName = '' + let attributeValue = '' - randomFillSync(packet, 5 + payloadLen, padLen); + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } - return packet; + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) } - encrypt(packet) { - // `packet` === unencrypted packet - if (this._dead) - return; + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} - const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); - cipher.setAutoPadding(false); +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} - const lenData = packet.slice(0, 4); - cipher.setAAD(lenData); - this._onWrite(lenData); - // Encrypt pad length, payload, and padding - const encrypted = cipher.update(packet.slice(4)); - this._onWrite(encrypted); - const final = cipher.final(); - // XXX: final.length === 0 always? - if (final.length) - this._onWrite(final); +/***/ }), - // Generate MAC - const tag = cipher.getAuthTag(); - this._onWrite(tag); +/***/ 3121: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Increment counter in IV by 1 for next packet - ivIncrement(this._encIV); +"use strict"; - this.outSeqno = (this.outSeqno + 1) >>> 0; + +const assert = __nccwpck_require__(9491) +const { kHeadersList } = __nccwpck_require__(2785) + +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } + + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false + } } } -class AESGCMCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new AESGCMCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._dead = false; +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) + + if ( + (code <= 0x20 || code > 0x7F) || + char === '(' || + char === ')' || + char === '>' || + char === '<' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' + ) { + throw new Error('Invalid cookie name') + } } - free() { - this._dead = true; - this._instance.free(); +} + +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || // exclude CTLs (0-31) + code === 0x22 || + code === 0x2C || + code === 0x3B || + code === 0x5C || + code > 0x7E // non-ascii + ) { + throw new Error('Invalid header value') + } } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; +} - const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') + } + } +} - randomFillSync(packet, 5 + payloadLen, padLen); +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} - return packet; +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) } - encrypt(packet) { - // `packet` === unencrypted packet - if (this._dead) - return; + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ] - // Encrypts in-place - this._instance.encrypt(packet); + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ] - this._onWrite(packet); + const dayName = days[date.getUTCDay()] + const day = date.getUTCDate().toString().padStart(2, '0') + const month = months[date.getUTCMonth()] + const year = date.getUTCFullYear() + const hour = date.getUTCHours().toString().padStart(2, '0') + const minute = date.getUTCMinutes().toString().padStart(2, '0') + const second = date.getUTCSeconds().toString().padStart(2, '0') - this.outSeqno = (this.outSeqno + 1) >>> 0; + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') } } +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } -class GenericCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._macSSLName = enc.macInfo.sslName; - this._macKey = enc.macKey; - this._macActualLen = enc.macInfo.actualLen; - this._macETM = enc.macInfo.isETM; - this._aadLen = (this._macETM ? 4 : 0); - this._dead = false; + validateCookieName(cookie.name) + validateCookieValue(cookie.value) - const discardLen = enc.cipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._cipherInstance.update(discard); - } - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; + const out = [`${cookie.name}=${cookie.value}`] - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } - const packet = Buffer.allocUnsafe(pktLen); + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; + if (cookie.secure) { + out.push('Secure') + } - randomFillSync(packet, 5 + payloadLen, padLen); + if (cookie.httpOnly) { + out.push('HttpOnly') + } - return packet; + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) } - encrypt(packet) { - // `packet` === unencrypted packet - if (this._dead) - return; + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } - let mac; - if (this._macETM) { - // Encrypt pad length, payload, and padding - const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); - const encrypted = this._cipherInstance.update( - new Uint8Array(packet.buffer, - packet.byteOffset + 4, - packet.length - 4) - ); + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } - this._onWrite(lenBytes); - this._onWrite(encrypted); + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(lenBytes); - mac.update(encrypted); - } else { - // Encrypt length field, pad length, payload, and padding - const encrypted = this._cipherInstance.update(packet); - this._onWrite(encrypted); + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(packet); + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') } - let digest = mac.digest(); - if (digest.length > this._macActualLen) - digest = digest.slice(0, this._macActualLen); - this._onWrite(digest); + const [key, ...value] = part.split('=') - this.outSeqno = (this.outSeqno + 1) >>> 0; + out.push(`${key.trim()}=${value.join('=')}`) } + + return out.join('; ') } -class GenericCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._macLen = enc.macInfo.len; - this._macActualLen = enc.macInfo.actualLen; - this._aadLen = (enc.macInfo.isETM ? 4 : 0); - this._instance = new GenericCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV, - enc.macInfo.sslName, - enc.macKey, - enc.macInfo.isETM); - this._dead = false; +let kHeadersListNode + +function getHeadersList (headers) { + if (headers[kHeadersList]) { + return headers[kHeadersList] } - free() { - this._dead = true; - this._instance.free(); + + if (!kHeadersListNode) { + kHeadersListNode = Object.getOwnPropertySymbols(headers).find( + (symbol) => symbol.description === 'headers list' + ) + + assert(kHeadersListNode, 'Headers cannot be parsed') } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; + const headersList = headers[kHeadersListNode] + assert(headersList) - const packet = Buffer.allocUnsafe(pktLen + this._macLen); + return headersList +} - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; +module.exports = { + isCTLExcludingHtab, + stringify, + getHeadersList +} - randomFillSync(packet, 5 + payloadLen, padLen); - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet +/***/ }), - if (this._dead) - return; +/***/ 2067: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); +"use strict"; + + +const net = __nccwpck_require__(1808) +const assert = __nccwpck_require__(9491) +const util = __nccwpck_require__(3983) +const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8045) + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +let SessionCache +// FIXME: remove workaround when the Node bug is fixed +// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 +if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new global.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } + } +} else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + } - if (this._macActualLen < this._macLen) { - packet = new FastBuffer(packet.buffer, - packet.byteOffset, - (packet.length - - (this._macLen - this._macActualLen))); + get (sessionKey) { + return this._sessionCache.get(sessionKey) } - this._onWrite(packet); - this.outSeqno = (this.outSeqno + 1) >>> 0; + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } + + this._sessionCache.set(sessionKey, session) + } } } - -class NullDecipher { - constructor(seqno, onPayload) { - this.inSeqno = seqno; - this._onPayload = onPayload; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; +function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') } - free() {} - decrypt(data, p, dataLen) { - while (p < dataLen) { - // Read packet length - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = __nccwpck_require__(4404) + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null + + assert(sessionKey) + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + // TODO(HTTP/2): Add support for h2c + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port: port || 443, + host: hostname + }) - if (this._lenBytes < 4) - return; + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port: port || 80, + host: hostname + }) + } - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (4 + this._len & 7) !== 0) { - throw new Error('Bad packet length'); + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(null, this) } - if (p >= dataLen) - return; - } + }) + .on('error', function (err) { + cancelTimeout() - // Read padding length, payload, and padding - if (this._packetPos < this._len) { - const nb = Math.min(this._len - this._packetPos, dataLen - p); - let chunk; - if (p !== 0 || nb !== dataLen) - chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - chunk = data; - if (nb === this._len) { - this._packet = chunk; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(chunk, this._packetPos); + if (callback) { + const cb = callback + callback = null + cb(err) } - p += nb; - this._packetPos += nb; - if (this._packetPos < this._len) - return; - } + }) - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); + return socket + } +} - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} + } - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); + let s1 = null + let s2 = null + const timeoutId = setTimeout(() => { + // setImmediate is added to make sure that we priotorise socket error events over timeouts + s1 = setImmediate(() => { + if (process.platform === 'win32') { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout()) + } else { + onConnectTimeout() } - } + }) + }, timeout) + return () => { + clearTimeout(timeoutId) + clearImmediate(s1) + clearImmediate(s2) } } -class ChaChaPolyDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decKeyMain = dec.decipherKey.slice(0, 32); - this._decKeyPktLen = dec.decipherKey.slice(32); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._calcMac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) +} - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; +module.exports = buildConnector - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const decLenBytes = - createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) - .update(this._lenBuf); - this._len = readUInt32BE(decLenBytes, 0); +/***/ }), - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - } +/***/ 4462: +/***/ ((module) => { - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } +"use strict"; - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); +/** @type {Record} */ +const headerNameLowerCasedRecord = {} + +// https://developer.mozilla.org/docs/Web/HTTP/Headers +const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +] + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) - // Calculate and compare Poly1305 MACs - poly1305_auth(POLY1305_RESULT_MALLOC, - this._lenBuf, - 4, - this._packet, - this._packet.length, - polyKey); +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord +} - this._calcMac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - if (!timingSafeEqual(this._calcMac, this._mac)) - throw new Error('Invalid MAC'); - // Decrypt packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const packet = - createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(this._packet); +/***/ }), - const payload = new FastBuffer(packet.buffer, - packet.byteOffset + 1, - packet.length - packet[0] - 1); +/***/ 8045: +/***/ ((module) => { - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; +"use strict"; - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } + +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' } } -class ChaChaPolyDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new ChaChaPolyDecipher(dec.decipherKey); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._macPos = 0; +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ConnectTimeoutError) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' } - free() { - this._instance.free(); +} + +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersTimeoutError) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' } - decrypt(data, p, dataLen) { - // `data` === encrypted data +} - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersOverflowError) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } +} - this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, BodyTimeoutError) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } +} - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } +class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message) + Error.captureStackTrace(this, ResponseStatusCodeError) + this.name = 'ResponseStatusCodeError' + this.message = message || 'Response Status Code Error' + this.code = 'UND_ERR_RESPONSE_STATUS_CODE' + this.body = body + this.status = statusCode + this.statusCode = statusCode + this.headers = headers + } +} - if (p >= dataLen) - return; - } +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidArgumentError) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } +} - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidReturnValueError) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } +} - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } +class RequestAbortedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestAbortedError) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } +} - this._instance.decrypt(this._packet, this._mac, this.inSeqno); +class InformationalError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InformationalError) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } +} - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestContentLengthMismatchError) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } +} - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseContentLengthMismatchError) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } +} - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientDestroyedError) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' } } -class AESGCMDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = null; - this._decipherSSLName = dec.decipherInfo.sslName; - this._decipherKey = dec.decipherKey; - this._decipherIV = dec.decipherIV; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientClosedError) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data +} - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + Error.captureStackTrace(this, SocketError) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } +} - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error('Bad packet length'); - } +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } +} - this._decipherInstance = createDecipheriv( - this._decipherSSLName, - this._decipherKey, - this._decipherIV - ); - this._decipherInstance.setAutoPadding(false); - this._decipherInstance.setAAD(intToBytes(this._len)); - } +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } +} - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let decrypted; - if (p !== 0 || nb !== dataLen) { - decrypted = this._decipherInstance.update( - new Uint8Array(data.buffer, data.byteOffset + p, nb) - ); - } else { - decrypted = this._decipherInstance.update(data); - } - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + Error.captureStackTrace(this, HTTPParserError) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } +} - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseExceededMaxSizeError) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } +} - { - // Verify authentication tag - this._decipherInstance.setAuthTag(this._tag); +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + Error.captureStackTrace(this, RequestRetryError) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers + } +} - const decrypted = this._decipherInstance.final(); +module.exports = { + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError +} - // XXX: this should never output any data since stream ciphers always - // return data from .update() and block ciphers must end on a multiple - // of the block length, which would have caused an exception to be - // thrown if the total input was not... - if (decrypted.length) { - if (this._packet) - this._packet.set(decrypted, this._packetPos); - else - this._packet = decrypted; - } - } - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); +/***/ }), - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - ivIncrement(this._decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tagPos = 0; +/***/ 2905: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } +"use strict"; + + +const { + InvalidArgumentError, + NotSupportedError +} = __nccwpck_require__(8045) +const assert = __nccwpck_require__(9491) +const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(2785) +const util = __nccwpck_require__(3983) + +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js + +/** + * Verifies that the given val is a valid HTTP token + * per the rules defined in RFC 7230 + * See https://tools.ietf.org/html/rfc7230#section-3.2.6 + */ +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ + +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ + +const kHandler = Symbol('handler') + +const channels = {} + +let extractBody + +try { + const diagnosticsChannel = __nccwpck_require__(7643) + channels.create = diagnosticsChannel.channel('undici:request:create') + channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') + channels.headers = diagnosticsChannel.channel('undici:request:headers') + channels.trailers = diagnosticsChannel.channel('undici:request:trailers') + channels.error = diagnosticsChannel.channel('undici:request:error') +} catch { + channels.create = { hasSubscribers: false } + channels.bodySent = { hasSubscribers: false } + channels.headers = { hasSubscribers: false } + channels.trailers = { hasSubscribers: false } + channels.error = { hasSubscribers: false } +} + +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError, + expectContinue + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.exec(path) !== null) { + throw new InvalidArgumentError('invalid request path') } - } -} -class AESGCMDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error(`Bad packet length: ${this._len}`); + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + + this.headersTimeout = headersTimeout + + this.bodyTimeout = bodyTimeout + + this.throwOnError = throwOnError === true + + this.method = method + + this.abort = null + + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body + + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + util.destroy(this) } + this.body.on('end', this.endHandler) } - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; + this.errorHandler = err => { + if (this.abort) { + this.abort(err) } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); + this.error = err } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; } + this.body.on('error', this.errorHandler) + } else if (util.isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; + this.completed = false + + this.aborted = false + + this.upgrade = upgrade || null + + this.path = query ? util.buildURL(path, query) : path + + this.origin = origin + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent + + this.blocking = blocking == null ? false : blocking + + this.reset = reset == null ? null : reset + + this.host = null + + this.contentLength = null + + this.contentType = null + + this.headers = '' + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(this, key, headers[key]) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } - this._instance.decrypt(this._packet, this._len, this._tag); + if (util.isFormDataLike(this.body)) { + if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { + throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') + } - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); + if (!extractBody) { + extractBody = (__nccwpck_require__(1472).extractBody) + } - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tagPos = 0; + const [bodyStream, contentType] = extractBody(body) + if (this.contentType == null) { + this.contentType = contentType + this.headers += `content-type: ${contentType}\r\n` + } + this.body = bodyStream.stream + this.contentLength = bodyStream.length + } else if (util.isBlobLike(body) && this.contentType == null && body.type) { + this.contentType = body.type + this.headers += `content-type: ${body.type}\r\n` + } - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); + util.validateHandler(handler, method, upgrade) + + this.servername = util.getServerName(this.host) + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } + + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) } } } -} -// TODO: test incremental .update()s vs. copying to _packet and doing a single -// .update() after entire packet read -- a single .update() would allow -// verifying MAC before decrypting for ETM MACs -class GenericDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._decipherInstance.setAutoPadding(false); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen - ); - this._blockSize = dec.decipherInfo.blockLen; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macSSLName = dec.macInfo.sslName; - this._macKey = dec.macKey; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - this._macInstance = null; + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } - const discardLen = dec.decipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) } - this._decipherInstance.update(discard); } } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } + } - let decrypted; - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - decrypted = this._decipherInstance.update(this._block); - this._len = readUInt32BE(decrypted, 0); - need = 4 + this._len - this._blockSize; - } + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._blockSize - 1)) !== 0) { - throw new Error('Bad packet length'); - } + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } - // Create MAC up front to calculate in parallel with decryption - this._macInstance = createHmac(this._macSSLName, this._macKey); + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) + } + } - writeUInt32BE(BUF_INT, this.inSeqno, 0); - this._macInstance.update(BUF_INT); - if (this._macETM) { - this._macInstance.update(this._block); - } else { - this._macInstance.update(new Uint8Array(decrypted.buffer, - decrypted.byteOffset, - 4)); - this._pktLen = decrypted.length - 4; - this._packetPos = this._pktLen; - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(decrypted.buffer, - decrypted.byteOffset + 4, - this._packetPos), - 0 - ); - } + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) - if (p >= dataLen) - return; - } + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } + } - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (this._macETM) - this._macInstance.update(encrypted); - const decrypted = this._decipherInstance.update(encrypted); - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } + return this[kHandler].onUpgrade(statusCode, headers, socket) + } - // Verify MAC - if (!this._macETM) - this._macInstance.update(this._packet); - let calculated = this._macInstance.digest(); - if (this._macActualLen < calculated.length) { - calculated = new Uint8Array(calculated.buffer, - calculated.byteOffset, - this._macActualLen); - } - if (!timingSafeEquals(calculated, this._mac)) - throw new Error('Invalid MAC'); + onComplete (trailers) { + this.onFinally() - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); + assert(!this.aborted) - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) } } -} -class GenericDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new GenericDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV, - dec.macInfo.sslName, - dec.macKey, - dec.macInfo.isETM, - dec.macInfo.actualLen); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM || dec.decipherInfo.stream - ? 4 - : dec.decipherInfo.blockLen - ); - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; + onError (error) { + this.onFinally() + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + + if (this.aborted) { + return + } + this.aborted = true + + return this[kHandler].onError(error) } - free() { - this._instance.free(); + + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } + + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } } - decrypt(data, p, dataLen) { - // `data` === encrypted data - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value) + return this + } - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; + static [kHTTP1BuildRequest] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - this._instance.decryptBlock(this._block); - this._len = readUInt32BE(this._block, 0); - need = 4 + this._len - this._block.length; - } + static [kHTTP2BuildRequest] (origin, opts, handler) { + const headers = opts.headers + opts = { ...opts, headers: null } - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._block.length - 1)) !== 0) { - throw new Error('Bad packet length'); - } + const request = new Request(origin, opts, handler) - if (!this._macETM) { - this._pktLen = (this._block.length - 4); - if (this._pktLen) { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(this._block.buffer, - this._block.byteOffset + 4, - this._pktLen), - 0 - ); - } - } + request.headers = {} - if (p >= dataLen) - return; + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; + for (let i = 0; i < headers.length; i += 2) { + processHeader(request, headers[i], headers[i + 1], true) } - - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(request, key, headers[key], true) } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } - // Decrypt and verify MAC - this._instance.decrypt(this._packet, - this.inSeqno, - this._block, - this._mac); + return request + } - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); + static [kHTTP2CopyHeaders] (raw) { + const rawHeaders = raw.split('\r\n') + const headers = {} - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; + for (const header of rawHeaders) { + const [key, value] = header.split(': ') - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + if (value == null || value.length === 0) continue + + if (headers[key]) headers[key] += `,${value}` + else headers[key] = value } + + return headers } } -// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV -function ivIncrement(iv) { - // eslint-disable-next-line no-unused-expressions - ++iv[11] >>> 8 - && ++iv[10] >>> 8 - && ++iv[9] >>> 8 - && ++iv[8] >>> 8 - && ++iv[7] >>> 8 - && ++iv[6] >>> 8 - && ++iv[5] >>> 8 - && ++iv[4] >>> 8; +function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + val = val != null ? `${val}` : '' + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + return skipAppend ? val : `${key}: ${val}\r\n` } -const intToBytes = (() => { - const ret = Buffer.alloc(4); - return (n) => { - ret[0] = (n >>> 24); - ret[1] = (n >>> 16); - ret[2] = (n >>> 8); - ret[3] = n; - return ret; - }; -})(); +function processHeader (request, key, val, skipAppend = false) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } -function timingSafeEquals(a, b) { - if (a.length !== b.length) { - timingSafeEqual(a, a); - return false; + if ( + request.host === null && + key.length === 4 && + key.toLowerCase() === 'host' + ) { + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + // Consumed by Client + request.host = val + } else if ( + request.contentLength === null && + key.length === 14 && + key.toLowerCase() === 'content-length' + ) { + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if ( + request.contentType === null && + key.length === 12 && + key.toLowerCase() === 'content-type' + ) { + request.contentType = val + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } else if ( + key.length === 17 && + key.toLowerCase() === 'transfer-encoding' + ) { + throw new InvalidArgumentError('invalid transfer-encoding header') + } else if ( + key.length === 10 && + key.toLowerCase() === 'connection' + ) { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } else if (value === 'close') { + request.reset = true + } + } else if ( + key.length === 10 && + key.toLowerCase() === 'keep-alive' + ) { + throw new InvalidArgumentError('invalid keep-alive header') + } else if ( + key.length === 7 && + key.toLowerCase() === 'upgrade' + ) { + throw new InvalidArgumentError('invalid upgrade header') + } else if ( + key.length === 6 && + key.toLowerCase() === 'expect' + ) { + throw new NotSupportedError('expect header not supported') + } else if (tokenRegExp.exec(key) === null) { + throw new InvalidArgumentError('invalid header key') + } else { + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (skipAppend) { + if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` + else request.headers[key] = processHeaderValue(key, val[i], skipAppend) + } else { + request.headers += processHeaderValue(key, val[i]) + } + } + } else { + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } } - return timingSafeEqual(a, b); } -function createCipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); +module.exports = Request - if (typeof config.outbound !== 'object' || config.outbound === null) - throw new Error('Invalid outbound'); - const outbound = config.outbound; +/***/ }), - if (typeof outbound.onWrite !== 'function') - throw new Error('Invalid outbound.onWrite'); +/***/ 2785: +/***/ ((module) => { - if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) - throw new Error('Invalid outbound.cipherInfo'); +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kHeadersList: Symbol('headers list'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kHTTP2BuildRequest: Symbol('http2 build request'), + kHTTP1BuildRequest: Symbol('http1 build request'), + kHTTP2CopyHeaders: Symbol('http2 copy headers'), + kHTTPConnVersion: Symbol('http connection version'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable') +} + + +/***/ }), + +/***/ 3983: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const assert = __nccwpck_require__(9491) +const { kDestroyed, kBodyUsed } = __nccwpck_require__(2785) +const { IncomingMessage } = __nccwpck_require__(3685) +const stream = __nccwpck_require__(2781) +const net = __nccwpck_require__(1808) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { Blob } = __nccwpck_require__(4300) +const nodeUtil = __nccwpck_require__(3837) +const { stringify } = __nccwpck_require__(3477) +const { headerNameLowerCasedRecord } = __nccwpck_require__(4462) + +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + +function nop () {} + +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} + +// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) +function isBlobLike (object) { + return (Blob && object instanceof Blob) || ( + object && + typeof object === 'object' && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) +} + +function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified + } + + return url +} + +function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url) - if (!Buffer.isBuffer(outbound.cipherKey) - || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { - throw new Error('Invalid outbound.cipherKey'); + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url } - if (outbound.cipherInfo.ivLen - && (!Buffer.isBuffer(outbound.cipherIV) - || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { - throw new Error('Invalid outbound.cipherIV'); + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') } - if (typeof outbound.seqno !== 'number' - || outbound.seqno < 0 - || outbound.seqno > MAX_SEQNO) { - throw new Error('Invalid outbound.seqno'); + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } - const forceNative = !!outbound.forceNative; + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } - switch (outbound.cipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMCipher && !forceNative - ? new AESGCMCipherBinding(config) - : new AESGCMCipherNative(config)); - case 'chacha20': - return (ChaChaPolyCipher && !forceNative - ? new ChaChaPolyCipherBinding(config) - : new ChaChaPolyCipherNative(config)); - default: { - if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) - throw new Error('Invalid outbound.macInfo'); - if (!Buffer.isBuffer(outbound.macKey) - || outbound.macKey.length !== outbound.macInfo.len) { - throw new Error('Invalid outbound.macKey'); - } - return (GenericCipher && !forceNative - ? new GenericCipherBinding(config) - : new GenericCipherNative(config)); + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') } - } -} -function createDecipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } - if (typeof config.inbound !== 'object' || config.inbound === null) - throw new Error('Invalid inbound'); + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } - const inbound = config.inbound; + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } - if (typeof inbound.onPayload !== 'function') - throw new Error('Invalid inbound.onPayload'); + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol}//${url.hostname}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` - if (typeof inbound.decipherInfo !== 'object' - || inbound.decipherInfo === null) { - throw new Error('Invalid inbound.decipherInfo'); + if (origin.endsWith('/')) { + origin = origin.substring(0, origin.length - 1) + } + + if (path && !path.startsWith('/')) { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + url = new URL(origin + path) } - if (!Buffer.isBuffer(inbound.decipherKey) - || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { - throw new Error('Invalid inbound.decipherKey'); + return url +} + +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') } - if (inbound.decipherInfo.ivLen - && (!Buffer.isBuffer(inbound.decipherIV) - || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { - throw new Error('Invalid inbound.decipherIV'); + return url +} + +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substring(1, idx) } - if (typeof inbound.seqno !== 'number' - || inbound.seqno < 0 - || inbound.seqno > MAX_SEQNO) { - throw new Error('Invalid inbound.seqno'); + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substring(0, idx) +} + +// IP addresses are not valid server names per RFC6066 +// > Currently, the only server names supported are DNS hostnames +function getServerName (host) { + if (!host) { + return null } - const forceNative = !!inbound.forceNative; + assert.strictEqual(typeof host, 'string') - switch (inbound.decipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMDecipher && !forceNative - ? new AESGCMDecipherBinding(config) - : new AESGCMDecipherNative(config)); - case 'chacha20': - return (ChaChaPolyDecipher && !forceNative - ? new ChaChaPolyDecipherBinding(config) - : new ChaChaPolyDecipherNative(config)); - default: { - if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) - throw new Error('Invalid inbound.macInfo'); - if (!Buffer.isBuffer(inbound.macKey) - || inbound.macKey.length !== inbound.macInfo.len) { - throw new Error('Invalid inbound.macKey'); - } - return (GenericDecipher && !forceNative - ? new GenericDecipherBinding(config) - : new GenericDecipherNative(config)); - } + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' } + + return servername } -module.exports = { - CIPHER_INFO, - MAC_INFO, - bindingAvailable: !!binding, - init: (() => { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - try { - POLY1305_WASM_MODULE = await __nccwpck_require__(4989)(); - POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); - poly1305_auth = POLY1305_WASM_MODULE.cwrap( - 'poly1305_auth', - null, - ['number', 'array', 'number', 'array', 'number', 'array'] - ); - } catch (ex) { - return reject(ex); - } - resolve(); - }); - })(), +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} - NullCipher, - createCipher, - NullDecipher, - createDecipher, -}; +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} -/***/ }), +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } -/***/ 4989: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return null +} +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) +} -var createPoly1305 = (function() { - var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; - if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; - return ( -function(createPoly1305) { - createPoly1305 = createPoly1305 || {}; +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted +} +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return + } -var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; -if(z)B=y?(__nccwpck_require__(1017).dirname)(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=__nccwpck_require__(7147));G||(G=__nccwpck_require__(1017));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=__nccwpck_require__(7147));G||(G=__nccwpck_require__(1017));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= -0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; -function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; -function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} -function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} -function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; -(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, -a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); -b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; -b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; -function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 { + stream.emit('error', err) + }, stream, err) + } - return createPoly1305.ready + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } } -); -})(); -if (true) - module.exports = createPoly1305; -else {} +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} -/***/ }), +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return headerNameLowerCasedRecord[value] || value.toLowerCase() +} -/***/ 172: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function parseHeaders (headers, obj = {}) { + // For H2 support + if (!Array.isArray(headers)) return headers -"use strict"; + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase() + let val = obj[key] + if (!val) { + if (Array.isArray(headers[i + 1])) { + obj[key] = headers[i + 1].map(x => x.toString('utf8')) + } else { + obj[key] = headers[i + 1].toString('utf8') + } + } else { + if (!Array.isArray(val)) { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) + } + } -const MESSAGE_HANDLERS = new Array(256); -[ - (__nccwpck_require__(4126).HANDLERS), - __nccwpck_require__(6475), -].forEach((handlers) => { - // eslint-disable-next-line prefer-const - for (let [type, handler] of Object.entries(handlers)) { - type = +type; - if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) - MESSAGE_HANDLERS[type] = handler; + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') } -}); -module.exports = MESSAGE_HANDLERS; + return obj +} +function parseRawHeaders (headers) { + const ret = [] + let hasContentLength = false + let contentDispositionIdx = -1 -/***/ }), + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString() + const val = headers[n + 1].toString('utf8') -/***/ 6475: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + ret.push(key, val) + hasContentLength = true + } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = ret.push(key, val) - 1 + } else { + ret.push(key, val) + } + } -"use strict"; + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } + return ret +} -const { - bufferSlice, - bufferParser, - doFatalError, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(9475); +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} -const { - CHANNEL_OPEN_FAILURE, - COMPAT, - MESSAGE, - TERMINAL_MODE, -} = __nccwpck_require__(6832); +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } -const { - parseKey, -} = __nccwpck_require__(2218); + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } -const TERMINAL_MODE_BY_VALUE = - Array.from(Object.entries(TERMINAL_MODE)) - .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } -module.exports = { - // Transport layer protocol ================================================== - [MESSAGE.DISCONNECT]: (self, payload) => { - /* - byte SSH_MSG_DISCONNECT - uint32 reason code - string description in ISO-10646 UTF-8 encoding - string language tag - */ - bufferParser.init(payload, 1); - const reason = bufferParser.readUInt32BE(); - const desc = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DISCONNECT packet' - ); + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') } - self._debug && self._debug( - `Inbound: Received DISCONNECT (${reason}, "${desc}")` - ); - - const handler = self._handlers.DISCONNECT; - handler && handler(self, reason, desc); - }, - [MESSAGE.IGNORE]: (self, payload) => { - /* - byte SSH_MSG_IGNORE - string data - */ - self._debug && self._debug('Inbound: Received IGNORE'); - }, - [MESSAGE.UNIMPLEMENTED]: (self, payload) => { - /* - byte SSH_MSG_UNIMPLEMENTED - uint32 packet sequence number of rejected message - */ - bufferParser.init(payload, 1); - const seqno = bufferParser.readUInt32BE(); - bufferParser.clear(); + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } - if (seqno === undefined) { - return doFatalError( - self, - 'Inbound: Malformed UNIMPLEMENTED packet' - ); + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') } + } +} - self._debug - && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); - }, - [MESSAGE.DEBUG]: (self, payload) => { - /* - byte SSH_MSG_DEBUG - boolean always_display - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const display = bufferParser.readBool(); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); +// A body is disturbed if it has been read from and it cannot +// be re-used without losing state or data. +function isDisturbed (body) { + return !!(body && ( + stream.isDisturbed + ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? + : body[kBodyUsed] || + body.readableDidRead || + (body._readableState && body._readableState.dataEmitted) || + isReadableAborted(body) + )) +} - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DEBUG packet' - ); - } +function isErrored (body) { + return !!(body && ( + stream.isErrored + ? stream.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) +} - self._debug && self._debug('Inbound: Received DEBUG'); +function isReadable (body) { + return !!(body && ( + stream.isReadable + ? stream.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) +} - const handler = self._handlers.DEBUG; - handler && handler(self, display, msg); - }, - [MESSAGE.SERVICE_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_SERVICE_REQUEST - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_REQUEST packet' - ); - } +async function * convertIterableToBuffer (iterable) { + for await (const chunk of iterable) { + yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + } +} - self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); +let ReadableStream +function ReadableStreamFrom (iterable) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } - const handler = self._handlers.SERVICE_REQUEST; - handler && handler(self, name); - }, - [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { - // S->C - /* - byte SSH_MSG_SERVICE_ACCEPT - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); + if (ReadableStream.from) { + return ReadableStream.from(convertIterableToBuffer(iterable)) + } - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_ACCEPT packet' - ); + let iterator + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator]() + }, + async pull (controller) { + const { done, value } = await iterator.next() + if (done) { + queueMicrotask(() => { + controller.close() + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + controller.enqueue(new Uint8Array(buf)) + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + } + }, + 0 + ) +} + +// The chunk should be a FormData instance and contains +// all the required methods. +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function throwIfAborted (signal) { + if (!signal) { return } + if (typeof signal.throwIfAborted === 'function') { + signal.throwIfAborted() + } else { + if (signal.aborted) { + // DOMException not available < v17.0.0 + const err = new Error('The operation was aborted') + err.name = 'AbortError' + throw err } + } +} - self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); +function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener) + return () => signal.removeListener('abort', listener) +} - const handler = self._handlers.SERVICE_ACCEPT; - handler && handler(self, name); - }, +const hasToWellFormed = !!String.prototype.toWellFormed - // User auth protocol -- generic ============================================= - [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_USERAUTH_REQUEST - string user name in ISO-10646 UTF-8 encoding [RFC3629] - string service name in US-ASCII - string method name in US-ASCII - .... method specific fields - */ - bufferParser.init(payload, 1); - const user = bufferParser.readString(true); - const service = bufferParser.readString(true); - const method = bufferParser.readString(true); - let methodData; - let methodDesc; - switch (method) { - case 'none': - methodData = null; - break; - case 'password': { - /* - boolean - string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] - [string new password] - */ - const isChange = bufferParser.readBool(); - if (isChange !== undefined) { - methodData = bufferParser.readString(true); - if (methodData !== undefined && isChange) { - const newPassword = bufferParser.readString(true); - if (newPassword !== undefined) - methodData = { oldPassword: methodData, newPassword }; - else - methodData = undefined; - } - } - break; - } - case 'publickey': { - /* - boolean - string public key algorithm name - string public key blob - [string signature] - */ - const hasSig = bufferParser.readBool(); - if (hasSig !== undefined) { - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - if (hasSig) { - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } +/** + * @param {string} val + */ +function toUSVString (val) { + if (hasToWellFormed) { + return `${val}`.toWellFormed() + } else if (nodeUtil.toUSVString) { + return nodeUtil.toUSVString(val) + } - signature = sigSSHToASN1(signature, keyAlgo); - if (signature) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo, - key, - signature, - blob, - }; - } - } - } else { - methodData = { keyAlgo, key }; - methodDesc = 'publickey -- check'; - } - } - break; - } - case 'hostbased': { - /* - string public key algorithm for host key - string public host key and certificates for client host - string client host name expressed as the FQDN in US-ASCII - string user name on the client host in ISO-10646 UTF-8 encoding - [RFC3629] - string signature - */ - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - const localHostname = bufferParser.readString(true); - const localUsername = bufferParser.readString(true); + return `${val}` +} - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } +// Parsed accordingly to RFC 9110 +// https://www.rfc-editor.org/rfc/rfc9110#field.content-range +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } - signature = sigSSHToASN1(signature, keyAlgo); - if (signature !== undefined) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo, - key, - signature, - blob, - localHostname, - localUsername, - }; - } - } - break; + const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null } - case 'keyboard-interactive': - /* - string language tag (as defined in [RFC-3066]) - string submethods (ISO-10646 UTF-8) - */ - // Skip/ignore language field -- it's deprecated in RFC 4256 - bufferParser.skipString(); + : null +} - methodData = bufferParser.readList(); - break; - default: - if (method !== undefined) - methodData = bufferParser.readRaw(); - } - bufferParser.clear(); +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true + +module.exports = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString, + isReadableAborted, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + throwIfAborted, + addAbortListener, + parseRangeHeader, + nodeMajor, + nodeMinor, + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), + safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +} - if (methodData === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_REQUEST packet' - ); - } - if (methodDesc === undefined) - methodDesc = method; +/***/ }), - self._authsQueue.push(method); +/***/ 4839: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - self._debug - && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); +"use strict"; - const handler = self._handlers.USERAUTH_REQUEST; - handler && handler(self, user, service, method, methodData); - }, - [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_FAILURE - name-list authentications that can continue - boolean partial success - */ - bufferParser.init(payload, 1); - const authMethods = bufferParser.readList(); - const partialSuccess = bufferParser.readBool(); - bufferParser.clear(); - if (partialSuccess === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_FAILURE packet' - ); - } +const Dispatcher = __nccwpck_require__(412) +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = __nccwpck_require__(8045) +const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(2785) - self._debug - && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_FAILURE; - handler && handler(self, authMethods, partialSuccess); - }, - [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_SUCCESS - */ - self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); +class DispatcherBase extends Dispatcher { + constructor () { + super() - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_SUCCESS; - handler && handler(self); - }, - [MESSAGE.USERAUTH_BANNER]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_BANNER - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] + } - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_BANNER packet' - ); + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + get interceptors () { + return this[kInterceptors] + } + + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors][i] + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError('interceptor must be an function') + } + } } - self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); + this[kInterceptors] = newInterceptors + } - const handler = self._handlers.USERAUTH_BANNER; - handler && handler(self, msg); - }, + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - // User auth protocol -- method-specific ===================================== - 60: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 60 without auth'); - return; + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - switch (self._authsQueue[0]) { - case 'password': { - // S->C - /* - byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ - string prompt in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const prompt = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return + } - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' - ); - } + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } - self._debug - && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); + this[kClosed] = true + this[kOnClosed].push(callback) - const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; - handler && handler(self, prompt); - break; + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) } - case 'publickey': { - // S->C - /* - byte SSH_MSG_USERAUTH_PK_OK - string public key algorithm name from the request - string public key blob from the request - */ - bufferParser.init(payload, 1); - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - bufferParser.clear(); + } - if (key === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PK_OK packet' - ); - } + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) + } - self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_PK_OK; - handler && handler(self, keyAlgo, key); - break; + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) } - case 'keyboard-interactive': { - // S->C - /* - byte SSH_MSG_USERAUTH_INFO_REQUEST - string name (ISO-10646 UTF-8) - string instruction (ISO-10646 UTF-8) - string language tag (as defined in [RFC-3066]) - int num-prompts - string prompt[1] (ISO-10646 UTF-8) - boolean echo[1] - ... - string prompt[num-prompts] (ISO-10646 UTF-8) - boolean echo[num-prompts] - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const instructions = bufferParser.readString(true); - bufferParser.readString(); // skip lang - const numPrompts = bufferParser.readUInt32BE(); - let prompts; - if (numPrompts !== undefined) { - prompts = new Array(numPrompts); - let i; - for (i = 0; i < numPrompts; ++i) { - const prompt = bufferParser.readString(true); - const echo = bufferParser.readBool(); - if (echo === undefined) - break; - prompts[i] = { prompt, echo }; - } - if (i !== numPrompts) - prompts = undefined; - } - bufferParser.clear(); + return + } - if (prompts === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' - ); - } + if (!err) { + err = new ClientDestroyedError() + } - self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) - const handler = self._handlers.USERAUTH_INFO_REQUEST; - handler && handler(self, name, instructions, prompts); - break; + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) } - default: - self._debug - && self._debug('Inbound: Received unexpected payload type 60'); - } - }, - 61: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 61 without auth'); - return; } - /* - byte SSH_MSG_USERAUTH_INFO_RESPONSE - int num-responses - string response[1] (ISO-10646 UTF-8) - ... - string response[num-responses] (ISO-10646 UTF-8) - */ - if (self._authsQueue[0] !== 'keyboard-interactive') { - return doFatalError( - self, - 'Inbound: Received unexpected payload type 61' - ); + + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) + } + + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) } - bufferParser.init(payload, 1); - const numResponses = bufferParser.readUInt32BE(); - let responses; - if (numResponses !== undefined) { - responses = new Array(numResponses); - let i; - for (i = 0; i < numResponses; ++i) { - const response = bufferParser.readString(true); - if (response === undefined) - break; - responses[i] = response; - } - if (i !== numResponses) - responses = undefined; + + let dispatch = this[kDispatch].bind(this) + for (let i = this[kInterceptors].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors][i](dispatch) } - bufferParser.clear(); + this[kInterceptedDispatch] = dispatch + return dispatch(opts, handler) + } - if (responses === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' - ); + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') } - self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } - const handler = self._handlers.USERAUTH_INFO_RESPONSE; - handler && handler(self, responses); - }, + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } - // Connection protocol -- generic ============================================ - [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_GLOBAL_REQUEST - string request name in US-ASCII only - boolean want reply - .... request-specific data follows - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (name) { - case 'tcpip-forward': - case 'cancel-tcpip-forward': { - /* - string address to bind (e.g., "0.0.0.0") - uint32 port number to bind - */ - const bindAddr = bufferParser.readString(true); - const bindPort = bufferParser.readUInt32BE(); - if (bindPort !== undefined) - data = { bindAddr, bindPort }; - break; - } - case 'streamlocal-forward@openssh.com': - case 'cancel-streamlocal-forward@openssh.com': { - /* - string socket path - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) - data = { socketPath }; - break; - } - case 'no-more-sessions@openssh.com': - data = null; - break; - case 'hostkeys-00@openssh.com': { - data = []; - while (bufferParser.avail() > 0) { - const keyRaw = bufferParser.readString(); - if (keyRaw === undefined) { - data = undefined; - break; - } - const key = parseKey(keyRaw); - if (!(key instanceof Error)) - data.push(key); - } - break; - } - default: - data = bufferParser.readRaw(); + if (this[kClosed]) { + throw new ClientClosedError() } - } - bufferParser.clear(); - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed GLOBAL_REQUEST packet' - ); + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err) + + return false } + } +} - self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); +module.exports = DispatcherBase - const handler = self._handlers.GLOBAL_REQUEST; - if (handler) - handler(self, name, wantReply, data); - else - self.requestFailure(); // Auto reject - }, - [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_SUCCESS - .... response specific data - */ - const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); - self._debug && self._debug('Inbound: REQUEST_SUCCESS'); +/***/ }), - const handler = self._handlers.REQUEST_SUCCESS; - handler && handler(self, data); - }, - [MESSAGE.REQUEST_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_FAILURE - */ - self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); +/***/ 412: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const handler = self._handlers.REQUEST_FAILURE; - handler && handler(self); - }, +"use strict"; - // Connection protocol -- channel-related ==================================== - [MESSAGE.CHANNEL_OPEN]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN - string channel type in US-ASCII only - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - bufferParser.init(payload, 1); - const type = bufferParser.readString(true); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - let channelInfo; - switch (type) { - case 'forwarded-tcpip': // S->C - case 'direct-tcpip': { // C->S - /* - string address that was connected / host to connect - uint32 port that was connected / port to connect - string originator IP address - uint32 originator port - */ - const destIP = bufferParser.readString(true); - const destPort = bufferParser.readUInt32BE(); - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { destIP, destPort, srcIP, srcPort } - }; - } - break; - } - case 'forwarded-streamlocal@openssh.com': // S->C - case 'direct-streamlocal@openssh.com': { // C->S - /* - string socket path - string reserved for future use +const EventEmitter = __nccwpck_require__(2361) - (direct-streamlocal@openssh.com additionally has:) - uint32 reserved - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { socketPath } - }; +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } +} + +module.exports = Dispatcher + + +/***/ }), + +/***/ 1472: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Busboy = __nccwpck_require__(3438) +const util = __nccwpck_require__(3983) +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = __nccwpck_require__(2538) +const { FormData } = __nccwpck_require__(2015) +const { kState } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { DOMException, structuredClone } = __nccwpck_require__(1037) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) +const { kBodyUsed } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { isErrored } = __nccwpck_require__(3983) +const { isUint8Array, isArrayBuffer } = __nccwpck_require__(9830) +const { File: UndiciFile } = __nccwpck_require__(8511) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) + +let ReadableStream = globalThis.ReadableStream + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() + +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } + + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream. + stream = new ReadableStream({ + async pull (controller) { + controller.enqueue( + typeof source === 'string' ? textEncoder.encode(source) : source + ) + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: undefined + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength + } else { + hasUnknownSizeValue = true } - break; } - case 'x11': { // S->C - /* - string originator address (e.g., "192.168.7.38") - uint32 originator port - */ - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { srcIP, srcPort } - }; + } + + const chunk = textEncoder.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part } - break; } - default: - // Includes: - // 'session' (C->S) - // 'auth-agent@openssh.com' (S->C) - channelInfo = { - type, - sender, - window, - packetSize, - data: {} - }; } - bufferParser.clear(); - if (channelInfo === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN packet' - ); + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = 'multipart/form-data; boundary=' + boundary + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') } - self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + async pull (controller) { + const { value, done } = await iterator.next() + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + controller.enqueue(new Uint8Array(value)) + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: undefined + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } + + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.') + // istanbul ignore next + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee() + const out2Clone = structuredClone(out2, { transfer: [out2] }) + // This, for whatever reasons, unrefs out2Clone which allows + // the process to exit by itself. + const [, finalClone] = out2Clone.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } +} - const handler = self._handlers.CHANNEL_OPEN; - if (handler) { - handler(self, channelInfo); +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body } else { - self.channelOpenFail( - channelInfo.sender, - CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, - '', - '' - ); - } - }, - [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION - uint32 recipient channel - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - // "The 'recipient channel' is the channel number given in the - // original open request, and 'sender channel' is the channel number - // allocated by the other side." - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); - bufferParser.clear(); + const stream = body.stream - if (packetSize === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' - ); - } + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } - self._debug && self._debug( - `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` - ); + if (stream.locked) { + throw new TypeError('The stream is locked.') + } - const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; - if (handler) - handler(self, { recipient, sender, window, packetSize, data }); - }, - [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_FAILURE - uint32 recipient channel - uint32 reason code - string description in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const reason = bufferParser.readUInt32BE(); - const description = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); + // Compat. + stream[kBodyUsed] = true - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' - ); + yield * stream } + } +} - self._debug - && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } +} - const handler = self._handlers.CHANNEL_OPEN_FAILURE; - handler && handler(self, recipient, reason, description); - }, - [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_WINDOW_ADJUST - uint32 recipient channel - uint32 bytes to add - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const bytesToAdd = bufferParser.readUInt32BE(); - bufferParser.clear(); +function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return specConsumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this) + + if (mimeType === 'failure') { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, - if (bytesToAdd === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' - ); - } + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return specConsumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, - self._debug && self._debug( - `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` - ); + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return specConsumeBody(this, utf8DecodeBytes, instance) + }, - const handler = self._handlers.CHANNEL_WINDOW_ADJUST; - handler && handler(self, recipient, bytesToAdd); - }, - [MESSAGE.CHANNEL_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_DATA - uint32 recipient channel - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return specConsumeBody(this, parseJSONFromBytes, instance) + }, - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_DATA packet' - ); - } + async formData () { + webidl.brandCheck(this, instance) - self._debug - && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); + throwIfAborted(this[kState]) - const handler = self._handlers.CHANNEL_DATA; - handler && handler(self, recipient, data); - }, - [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EXTENDED_DATA - uint32 recipient channel - uint32 data_type_code - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); + const contentType = this.headers.get('Content-Type') - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' - ); - } + // If mimeType’s essence is "multipart/form-data", then: + if (/multipart\/form-data/.test(contentType)) { + const headers = {} + for (const [key, value] of this.headers) headers[key.toLowerCase()] = value - self._debug && self._debug( - `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` - ); + const responseFormData = new FormData() - const handler = self._handlers.CHANNEL_EXTENDED_DATA; - handler && handler(self, recipient, data, type); - }, - [MESSAGE.CHANNEL_EOF]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EOF - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); + let busboy - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EOF packet' - ); - } + try { + busboy = new Busboy({ + headers, + preservePath: true + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') + } - self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = [] - const handler = self._handlers.CHANNEL_EOF; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_CLOSE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_CLOSE packet' - ); - } + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') - self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); + const end = base64chunk.length - base64chunk.length % 4 + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) - const handler = self._handlers.CHANNEL_CLOSE; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_REQUEST - uint32 recipient channel - string request type in US-ASCII characters only - boolean want reply - .... type-specific data follows - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (type) { - case 'exit-status': // S->C - /* - uint32 exit_status - */ - data = bufferParser.readUInt32BE(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'exit-signal': { // S->C - /* - string signal name (without the "SIG" prefix) - boolean core dumped - string error message in ISO-10646 UTF-8 encoding - string language tag - */ - let signal; - let coreDumped; - if (self._compatFlags & COMPAT.OLD_EXIT) { - /* - Instead of `signal name` and `core dumped`, we have just: - uint32 signal number - */ - const num = bufferParser.readUInt32BE(); - switch (num) { - case 1: - signal = 'HUP'; - break; - case 2: - signal = 'INT'; - break; - case 3: - signal = 'QUIT'; - break; - case 6: - signal = 'ABRT'; - break; - case 9: - signal = 'KILL'; - break; - case 14: - signal = 'ALRM'; - break; - case 15: - signal = 'TERM'; - break; - default: - if (num !== undefined) { - // Unknown or OS-specific - signal = `UNKNOWN (${num})`; - } - } - coreDumped = false; + base64chunk = base64chunk.slice(end) + }) + value.on('end', () => { + chunks.push(Buffer.from(base64chunk, 'base64')) + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) } else { - signal = bufferParser.readString(true); - coreDumped = bufferParser.readBool(); - if (coreDumped === undefined) - signal = undefined; + value.on('data', (chunk) => { + chunks.push(chunk) + }) + value.on('end', () => { + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) } - const errorMessage = bufferParser.readString(true); - if (bufferParser.skipString() !== undefined) - data = { signal, coreDumped, errorMessage }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` - ); - break; - } - case 'pty-req': { // C->S - /* - string TERM environment variable value (e.g., vt100) - uint32 terminal width, characters (e.g., 80) - uint32 terminal height, rows (e.g., 24) - uint32 terminal width, pixels (e.g., 640) - uint32 terminal height, pixels (e.g., 480) - string encoded terminal modes - */ - const term = bufferParser.readString(true); - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - const modesBinary = bufferParser.readString(); - if (modesBinary !== undefined) { - bufferParser.init(modesBinary, 1); - let modes = {}; - while (bufferParser.avail()) { - const opcode = bufferParser.readByte(); - if (opcode === TERMINAL_MODE.TTY_OP_END) - break; - const name = TERMINAL_MODE_BY_VALUE[opcode]; - const value = bufferParser.readUInt32BE(); - if (opcode === undefined - || name === undefined - || value === undefined) { - modes = undefined; - break; - } - modes[name] = value; + }) + + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve) + busboy.on('error', (err) => reject(new TypeError(err))) + }) + + if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) + busboy.end() + await busboyResolve + + return responseFormData + } else if (/application\/x-www-form-urlencoded/.test(contentType)) { + // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: + + // 1. Let entries be the result of parsing bytes. + let entries + try { + let text = '' + // application/x-www-form-urlencoded parser will keep the BOM. + // https://url.spec.whatwg.org/#concept-urlencoded-parser + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) + + for await (const chunk of consumeBody(this[kState].body)) { + if (!isUint8Array(chunk)) { + throw new TypeError('Expected Uint8Array chunk') } - if (modes !== undefined) - data = { term, cols, rows, width, height, modes }; + text += streamingDecoder.decode(chunk, { stream: true }) } - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'window-change': { // C->S - /* - uint32 terminal width, columns - uint32 terminal height, rows - uint32 terminal width, pixels - uint32 terminal height, pixels - */ - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - if (height !== undefined) - data = { cols, rows, width, height }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'x11-req': { // C->S - /* - boolean single connection - string x11 authentication protocol - string x11 authentication cookie - uint32 x11 screen number - */ - const single = bufferParser.readBool(); - const protocol = bufferParser.readString(true); - const cookie = bufferParser.readString(); - const screen = bufferParser.readUInt32BE(); - if (screen !== undefined) - data = { single, protocol, cookie, screen }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; + text += streamingDecoder.decode() + entries = new URLSearchParams(text) + } catch (err) { + // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. + // 2. If entries is failure, then throw a TypeError. + throw Object.assign(new TypeError(), { cause: err }) } - case 'env': { // C->S - /* - string variable name - string variable value - */ - const name = bufferParser.readString(true); - const value = bufferParser.readString(true); - if (value !== undefined) - data = { name, value }; - if (self._debug) { - self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` - + `${name}=${value})` - ); - } - break; + + // 3. Return a new FormData object whose entries are entries. + const formData = new FormData() + for (const [name, value] of entries) { + formData.append(name, value) } - case 'shell': // C->S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - case 'exec': // C->S - /* - string command - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'subsystem': // C->S - /* - string subsystem name - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'signal': // C->S - /* - string signal name (without the "SIG" prefix) - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'xon-xoff': // C->S - /* - boolean client can do - */ - data = bufferParser.readBool(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'auth-agent-req@openssh.com': // C-S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - default: - data = (bufferParser.avail() ? bufferParser.readRaw() : null); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); + return formData + } else { + // Wait a tick before checking if the request has been aborted. + // Otherwise, a TypeError can be thrown when an AbortError should. + await Promise.resolve() + + throwIfAborted(this[kState]) + + // Otherwise, throw a TypeError. + throw webidl.errors.exception({ + header: `${instance.name}.formData`, + message: 'Could not parse content as FormData.' + }) } } - bufferParser.clear(); + } - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_REQUEST packet' - ); - } + return methods +} - const handler = self._handlers.CHANNEL_REQUEST; - handler && handler(self, recipient, type, wantReply, data); - }, - [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_SUCCESS - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) +} - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_SUCCESS packet' - ); +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ +async function specConsumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance) + + throwIfAborted(object[kState]) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') + } + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error) + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) } + } - self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(new Uint8Array()) + return promise.promise + } - const handler = self._handlers.CHANNEL_SUCCESS; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_FAILURE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +// https://fetch.spec.whatwg.org/#body-unusable +function bodyUnusable (body) { + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) + + // 4. Return output. + return output +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} object + */ +function bodyMimeType (object) { + const { headersList } = object[kState] + const contentType = headersList.get('content-type') + + if (contentType === null) { + return 'failure' + } + + return parseMIMEType(contentType) +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody +} + + +/***/ }), + +/***/ 1037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(1267) + +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + +const nullBodyStatus = [101, 204, 205, 304] + +const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) + +// https://fetch.spec.whatwg.org/#block-bad-port +const badPorts = [ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', + '10080' +] + +const badPortsSet = new Set(badPorts) + +// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies +const referrerPolicy = [ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +] +const referrerPolicySet = new Set(referrerPolicy) + +const requestRedirect = ['follow', 'manual', 'error'] + +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) + +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + +const requestCredentials = ['omit', 'same-origin', 'include'] + +const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +] + +// https://fetch.spec.whatwg.org/#request-body-header-name +const requestBodyHeader = [ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' +] + +// https://fetch.spec.whatwg.org/#enumdef-requestduplex +const requestDuplex = [ + 'half' +] + +// http://fetch.spec.whatwg.org/#forbidden-method +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) + +const subresource = [ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +] +const subresourceSet = new Set(subresource) + +/** @type {globalThis['DOMException']} */ +const DOMException = globalThis.DOMException ?? (() => { + // DOMException was only made a global in Node v17.0.0, + // but fetch supports >= v16.8. + try { + atob('~') + } catch (err) { + return Object.getPrototypeOf(err).constructor + } +})() + +let channel - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_FAILURE packet' - ); +/** @type {globalThis['structuredClone']} */ +const structuredClone = + globalThis.structuredClone ?? + // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js + // structuredClone was added in v17.0.0, but fetch supports v16.8 + function structuredClone (value, options = undefined) { + if (arguments.length === 0) { + throw new TypeError('missing argument') } - self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); + if (!channel) { + channel = new MessageChannel() + } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message + } - const handler = self._handlers.CHANNEL_FAILURE; - handler && handler(self, recipient); - }, -}; +module.exports = { + DOMException, + structuredClone, + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet +} /***/ }), -/***/ 4126: +/***/ 685: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const assert = __nccwpck_require__(9491) +const { atob } = __nccwpck_require__(4300) +const { isomorphicDecode } = __nccwpck_require__(2538) +const encoder = new TextEncoder() -const { - createDiffieHellman, - createDiffieHellmanGroup, - createECDH, - createHash, - createPublicKey, - diffieHellman, - generateKeyPairSync, - randomFillSync, -} = __nccwpck_require__(6113); +/** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ +const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ +const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line +/** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ +const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line -const { Ber } = __nccwpck_require__(970); +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') -const { - COMPAT, - curve25519Supported, - DEFAULT_KEX, - DEFAULT_SERVER_HOST_KEY, - DEFAULT_CIPHER, - DEFAULT_MAC, - DEFAULT_COMPRESSION, - DISCONNECT_REASON, - MESSAGE, -} = __nccwpck_require__(6832); -const { - CIPHER_INFO, - createCipher, - createDecipher, - MAC_INFO, -} = __nccwpck_require__(5708); -const { parseDERKey } = __nccwpck_require__(2218); -const { - bufferFill, - bufferParser, - convertSignature, - doFatalError, - FastBuffer, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(9475); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = __nccwpck_require__(6715); + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) -let MESSAGE_HANDLERS; + // 3. Remove the leading "data:" string from input. + input = input.slice(5) -const GEX_MIN_BITS = 2048; // RFC 8270 -const GEX_MAX_BITS = 8192; // RFC 8270 + // 4. Let position point at the start of input. + const position = { position: 0 } -const EMPTY_BUFFER = Buffer.alloc(0); + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) -// Client/Server -function kexinit(self) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = removeASCIIWhitespace(mimeType, true, true) - let payload; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - const entry = self._offer.lists.kex; - let kex = entry.array; - let found = false; - for (let i = 0; i < kex.length; ++i) { - if (kex[i].includes('group-exchange')) { - if (!found) { - found = true; - // Copy array lazily - kex = kex.slice(); - } - kex.splice(i--, 1); - } - } - if (found) { - let len = 1 + 16 + self._offer.totalSize + 1 + 4; - const newKexBuf = Buffer.from(kex.join(',')); - len -= (entry.buffer.length - newKexBuf.length); + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } - const all = self._offer.lists.all; - const rest = new Uint8Array( - all.buffer, - all.byteOffset + 4 + entry.buffer.length, - all.length - (4 + entry.buffer.length) - ); + // 8. Advance position by 1. + position.position++ - payload = Buffer.allocUnsafe(len); - writeUInt32BE(payload, newKexBuf.length, 17); - payload.set(newKexBuf, 17 + 4); - payload.set(rest, 17 + 4 + newKexBuf.length); + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) } - if (payload === undefined) { - payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); - self._offer.copyAllTo(payload, 17); + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType } - self._debug && self._debug('Outbound: Sending KEXINIT'); + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) - payload[0] = MESSAGE.KEXINIT; - randomFillSync(payload, 1, 16); + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } - // Zero-fill first_kex_packet_follows and reserved bytes - bufferFill(payload, 0, payload.length - 5); + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} - self._kexinit = payload; +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } - // Needed to correct the starting position in allocated "packets" when packets - // will be buffered due to active key exchange - self._packetRW.write.allocStart = 0; + const href = url.href + const hashLength = url.hash.length - // TODO: only create single buffer and set _kexinit as slice of packet instead - { - const p = self._packetRW.write.allocStartKEX; - const packet = self._packetRW.write.alloc(payload.length, true); - packet.set(payload, p); - self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); - } + return hashLength === 0 ? href : href.substring(0, href.length - hashLength) } -function handleKexInit(self, payload) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - const init = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - }; +// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' - bufferParser.init(payload, 17); + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] - if ((init.kex = bufferParser.readList()) === undefined - || (init.serverHostKey = bufferParser.readList()) === undefined - || (init.cs.cipher = bufferParser.readList()) === undefined - || (init.sc.cipher = bufferParser.readList()) === undefined - || (init.cs.mac = bufferParser.readList()) === undefined - || (init.sc.mac = bufferParser.readList()) === undefined - || (init.cs.compress = bufferParser.readList()) === undefined - || (init.sc.compress = bufferParser.readList()) === undefined - || (init.cs.lang = bufferParser.readList()) === undefined - || (init.sc.lang = bufferParser.readList()) === undefined) { - bufferParser.clear(); - return doFatalError( - self, - 'Received malformed KEXINIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + // 2. Advance position by 1. + position.position++ } - const pos = bufferParser.pos(); - const firstFollows = (pos < payload.length && payload[pos] === 1); - bufferParser.clear(); + // 3. Return result. + return result +} - const local = self._offer; - const remote = init; +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position - let localKex = local.lists.kex.array; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - let found = false; - for (let i = 0; i < localKex.length; ++i) { - if (localKex[i].indexOf('group-exchange') !== -1) { - if (!found) { - found = true; - // Copy array lazily - localKex = localKex.slice(); - } - localKex.splice(i--, 1); + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + // 1. Let output be an empty byte sequence. + /** @type {number[]} */ + const output = [] + + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) + ) { + output.push(0x25) + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) + const bytePoint = Number.parseInt(nextTwoBytes, 16) + + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) + + // 3. Skip the next two bytes in input. + i += 2 + } + } + + // 3. Return output. + return Uint8Array.from(output) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true) + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue } } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } } - let clientList; - let serverList; - let i; - const debug = self._debug; + // 12. Return mimeType. + return mimeType +} - debug && debug('Inbound: Handshake in progress'); +// https://infra.spec.whatwg.org/#forgiving-base64-decode +/** @param {string} data */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line - // Key exchange method ======================================================= - debug && debug(`Handshake: (local) KEX method: ${localKex}`); - debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); - if (self._server) { - serverList = localKex; - clientList = remote.kex; - } else { - serverList = remote.kex; - clientList = localKex; + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (data.length % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + data = data.replace(/=?=$/, '') } - // Check for agreeable key exchange algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching key exchange algorithm'); - return doFatalError( - self, - 'Handshake failed: no matching key exchange algorithm', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (data.length % 4 === 1) { + return 'failure' } - init.kex = clientList[i]; - debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); - if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { - // Ignore next inbound packet, it was a wrong first guess at KEX algorithm - self._skipNextInboundPacket = true; + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data)) { + return 'failure' } + const binary = atob(data) + const bytes = new Uint8Array(binary.length) - // Server host key format ==================================================== - const localSrvHostKey = local.lists.serverHostKey.array; - debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); - debug && debug( - `Handshake: (remote) Host key format: ${remote.serverHostKey}` - ); - if (self._server) { - serverList = localSrvHostKey; - clientList = remote.serverHostKey; - } else { - serverList = remote.serverHostKey; - clientList = localSrvHostKey; - } - // Check for agreeable server host key format - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching host key format'); - return doFatalError( - self, - 'Handshake failed: no matching host key format', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) } - init.serverHostKey = clientList[i]; - debug && debug(`Handshake: Host key format: ${clientList[i]}`); + return bytes +} - // Client->Server cipher ===================================================== - const localCSCipher = local.lists.cs.cipher.array; - debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); - debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); - if (self._server) { - serverList = localCSCipher; - clientList = remote.cs.cipher; - } else { - serverList = remote.cs.cipher; - clientList = localCSCipher; - } - // Check for agreeable client->server cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S cipher'); - return doFatalError( - self, - 'Handshake failed: no matching C->S cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.cipher = clientList[i]; - debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ +function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position + // 2. Let value be the empty string. + let value = '' - // Server->Client cipher ===================================================== - const localSCCipher = local.lists.sc.cipher.array; - debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); - debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); - if (self._server) { - serverList = localSCCipher; - clientList = remote.sc.cipher; - } else { - serverList = remote.sc.cipher; - clientList = localSCCipher; - } - // Check for agreeable server->client cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C cipher'); - return doFatalError( - self, - 'Handshake failed: no matching S->C cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.cipher = clientList[i]; - debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + // 4. Advance position by 1. + position.position++ - // Client->Server MAC ======================================================== - const localCSMAC = local.lists.cs.mac.array; - debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); - debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); - if (CIPHER_INFO[init.cs.cipher].authLen > 0) { - init.cs.mac = ''; - debug && debug('Handshake: C->S MAC: '); - } else { - if (self._server) { - serverList = localCSMAC; - clientList = remote.cs.mac; - } else { - serverList = remote.cs.mac; - clientList = localCSMAC; - } - // Check for agreeable client->server hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S MAC'); - return doFatalError( - self, - 'Handshake failed: no matching C->S MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break } - init.cs.mac = clientList[i]; - debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); - } + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] - // Server->Client MAC ======================================================== - const localSCMAC = local.lists.sc.mac.array; - debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); - debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); - if (CIPHER_INFO[init.sc.cipher].authLen > 0) { - init.sc.mac = ''; - debug && debug('Handshake: S->C MAC: '); - } else { - if (self._server) { - serverList = localSCMAC; - clientList = remote.sc.mac; + // 4. Advance position by 1. + position.position++ + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position] + + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: } else { - serverList = remote.sc.mac; - clientList = localSCMAC; - } - // Check for agreeable server->client hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C MAC'); - return doFatalError( - self, - 'Handshake failed: no matching S->C MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break } - init.sc.mac = clientList[i]; - debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); } - - // Client->Server compression ================================================ - const localCSCompress = local.lists.cs.compress.array; - debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); - debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); - if (self._server) { - serverList = localCSCompress; - clientList = remote.cs.compress; - } else { - serverList = remote.cs.compress; - clientList = localCSCompress; - } - // Check for agreeable client->server compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S compression'); - return doFatalError( - self, - 'Handshake failed: no matching C->S compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value } - init.cs.compress = clientList[i]; - debug && debug(`Handshake: C->S compression: ${clientList[i]}`); + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} - // Server->Client compression ================================================ - const localSCCompress = local.lists.sc.compress.array; - debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); - debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); - if (self._server) { - serverList = localSCCompress; - clientList = remote.sc.compress; - } else { - serverList = remote.sc.compress; - clientList = localSCCompress; +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' + + // 2. Append name to serialization. + serialization += name + + // 3. Append U+003D (=) to serialization. + serialization += '=' + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value } - // Check for agreeable server->client compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C compression'); - return doFatalError( - self, - 'Handshake failed: no matching S->C compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + // 3. Return serialization. + return serialization +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} char + */ +function isHTTPWhiteSpace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === ' ' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + */ +function removeHTTPWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); } - init.sc.compress = clientList[i]; - debug && debug(`Handshake: S->C compression: ${clientList[i]}`); - init.cs.lang = ''; - init.sc.lang = ''; + if (trailing) { + for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + } - // XXX: hack -- find a better way to do this - if (self._kex) { - if (!self._kexinit) { - // We received a rekey request, but we haven't sent a KEXINIT in response - // yet - kexinit(self); - } - self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); + return str.slice(lead, trail + 1) +} + +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {string} char + */ +function isASCIIWhitespace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' +} + +/** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + */ +function removeASCIIWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); } - self._kex = createKeyExchange(init, self, payload); - self._kex.start(); + if (trailing) { + for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) } -const createKeyExchange = (() => { - function convertToMpint(buf) { - let idx = 0; - let length = buf.length; - while (buf[idx] === 0x00) { - ++idx; - --length; +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} + + +/***/ }), + +/***/ 8511: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { Blob, File: NativeFile } = __nccwpck_require__(4300) +const { types } = __nccwpck_require__(3837) +const { kState } = __nccwpck_require__(5861) +const { isBlobLike } = __nccwpck_require__(2538) +const { webidl } = __nccwpck_require__(1744) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const encoder = new TextEncoder() + +class File extends Blob { + constructor (fileBits, fileName, options = {}) { + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) + + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // 2. Convert every character in t to ASCII lowercase. + let t = options.type + let d + + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) + + if (t === 'failure') { + t = '' + // eslint-disable-next-line no-labels + break substep + } + + t = serializeAMimeType(t).toLowerCase() + } + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + d = options.lastModified } - let newBuf; - if (buf[idx] & 0x80) { - newBuf = Buffer.allocUnsafe(1 + length); - newBuf[0] = 0; - buf.copy(newBuf, 1, idx); - buf = newBuf; - } else if (length !== buf.length) { - newBuf = Buffer.allocUnsafe(length); - buf.copy(newBuf, 0, idx); - buf = newBuf; + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t } - return buf; } - class KeyExchange { - constructor(negotiated, protocol, remoteKexinit) { - this._protocol = protocol; + get name () { + webidl.brandCheck(this, File) - this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); - this.negotiated = negotiated; - this._step = 1; - this._public = null; - this._dh = null; - this._sentNEWKEYS = false; - this._receivedNEWKEYS = false; - this._finished = false; - this._hostVerified = false; + return this[kState].name + } - // Data needed for initializing cipher/decipher/etc. - this._kexinit = protocol._kexinit; - this._remoteKexinit = remoteKexinit; - this._identRaw = protocol._identRaw; - this._remoteIdentRaw = protocol._remoteIdentRaw; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - } - finish() { - if (this._finished) - return false; - this._finished = true; + get lastModified () { + webidl.brandCheck(this, File) - const isServer = this._protocol._server; - const negotiated = this.negotiated; + return this[kState].lastModified + } - const pubKey = this.convertPublicKey(this._dhData); - let secret = this.computeSecret(this._dhData); - if (secret instanceof Error) { - secret.message = - `Error while computing DH secret (${this.type}): ${secret.message}`; - secret.level = 'handshake'; - return doFatalError( - this._protocol, - secret, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + get type () { + webidl.brandCheck(this, File) - const hash = createHash(this.hashName); - // V_C - hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); - // "V_S" - hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); - // "I_C" - hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); - // "I_S" - hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); - // "K_S" - const serverPublicHostKey = (isServer - ? this._hostKey.getPublicSSH() - : this._hostKey); - hashString(hash, serverPublicHostKey); + return this[kState].type + } +} - if (this.type === 'groupex') { - // Group exchange-specific - const params = this.getDHParams(); - const num = Buffer.allocUnsafe(4); - // min (uint32) - writeUInt32BE(num, this._minBits, 0); - hash.update(num); - // preferred (uint32) - writeUInt32BE(num, this._prefBits, 0); - hash.update(num); - // max (uint32) - writeUInt32BE(num, this._maxBits, 0); - hash.update(num); - // prime - hashString(hash, params.prime); - // generator - hashString(hash, params.generator); - } +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check - // method-specific data sent by client - hashString(hash, (isServer ? pubKey : this.getPublicKey())); - // method-specific data sent by server - const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); - hashString(hash, serverPublicKey); - // shared secret ("K") - hashString(hash, secret); + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: - // "H" - const exchangeHash = hash.digest(); + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. - if (!isServer) { - bufferParser.init(this._sig, 0); - const sigType = bufferParser.readString(true); + // 2. Let n be the fileName argument to the constructor. + const n = fileName - if (!sigType) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: - if (sigType !== negotiated.serverHostKey) { - return doFatalError( - this._protocol, - `Wrong signature type: ${sigType}, ` - + `expected: ${negotiated.serverHostKey}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type - // "s" - let sigValue = bufferParser.readString(); + // 2. Convert every character in t to ASCII lowercase. + // TODO - bufferParser.clear(); + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now() - if (sigValue === undefined) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. - if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { - return doFatalError( - this._protocol, - 'Malformed signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } - let parsedHostKey; - { - bufferParser.init(this._hostKey, 0); - const name = bufferParser.readString(true); - const hostKey = this._hostKey.slice(bufferParser.pos()); - bufferParser.clear(); - parsedHostKey = parseDERKey(hostKey, name); - if (parsedHostKey instanceof Error) { - parsedHostKey.level = 'handshake'; - return doFatalError( - this._protocol, - parsedHostKey, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } + stream (...args) { + webidl.brandCheck(this, FileLike) - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } + return this[kState].blobLike.stream(...args) + } - this._protocol._debug - && this._protocol._debug('Verifying signature ...'); + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) - const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); - if (verified !== true) { - if (verified instanceof Error) { - this._protocol._debug && this._protocol._debug( - `Signature verification failed: ${verified.stack}` - ); - } else { - this._protocol._debug && this._protocol._debug( - 'Signature verification failed' - ); - } - return doFatalError( - this._protocol, - 'Handshake failed: signature verification failed', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug('Verified signature'); - } else { - // Server + return this[kState].blobLike.arrayBuffer(...args) + } - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } + slice (...args) { + webidl.brandCheck(this, FileLike) - this._protocol._debug && this._protocol._debug( - 'Generating signature ...' - ); + return this[kState].blobLike.slice(...args) + } - let signature = this._hostKey.sign(exchangeHash, hashAlgo); - if (signature instanceof Error) { - return doFatalError( - this._protocol, - 'Handshake failed: signature generation failed for ' - + `${this._hostKey.type} host key: ${signature.message}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + text (...args) { + webidl.brandCheck(this, FileLike) - signature = convertSignature(signature, this._hostKey.type); - if (signature === false) { - return doFatalError( - this._protocol, - 'Handshake failed: signature conversion failed for ' - + `${this._hostKey.type} host key`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + return this[kState].blobLike.text(...args) + } - // Send KEX reply - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - const sigType = this.negotiated.serverHostKey; - const sigTypeLen = Buffer.byteLength(sigType); - const sigLen = 4 + sigTypeLen + 4 + signature.length; - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 - + 4 + serverPublicHostKey.length - + 4 + serverPublicKey.length - + 4 + sigLen, - true - ); + get size () { + webidl.brandCheck(this, FileLike) - packet[p] = MESSAGE.KEXDH_REPLY; + return this[kState].blobLike.size + } - writeUInt32BE(packet, serverPublicHostKey.length, ++p); - packet.set(serverPublicHostKey, p += 4); + get type () { + webidl.brandCheck(this, FileLike) - writeUInt32BE(packet, - serverPublicKey.length, - p += serverPublicHostKey.length); - packet.set(serverPublicKey, p += 4); + return this[kState].blobLike.type + } - writeUInt32BE(packet, sigLen, p += serverPublicKey.length); + get name () { + webidl.brandCheck(this, FileLike) - writeUInt32BE(packet, sigTypeLen, p += 4); - packet.utf8Write(sigType, p += 4, sigTypeLen); + return this[kState].name + } - writeUInt32BE(packet, signature.length, p += sigTypeLen); - packet.set(signature, p += 4); + get lastModified () { + webidl.brandCheck(this, FileLike) - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_REPLY'; - break; - case 'groupex': - type = 'KEXDH_GEX_REPLY'; - break; - default: - type = 'KEXECDH_REPLY'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } +} + +Object.defineProperties(File.prototype, { + [Symbol.toStringTag]: { + value: 'File', + configurable: true + }, + name: kEnumerableProperty, + lastModified: kEnumerableProperty +}) + +webidl.converters.Blob = webidl.interfaceConverter(Blob) + +webidl.converters.BlobPart = function (V, opts) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) + ) { + return webidl.converters.BufferSource(V, opts) + } + } + + return webidl.converters.USVString(V, opts) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.BlobPart +) + +// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag +webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ + { + key: 'lastModified', + converter: webidl.converters['long long'], + get defaultValue () { + return Date.now() + } + }, + { + key: 'type', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'endings', + converter: (value) => { + value = webidl.converters.DOMString(value) + value = value.toLowerCase() + + if (value !== 'native') { + value = 'transparent' } - trySendNEWKEYS(this); - const completeHandshake = () => { - if (!this.sessionID) - this.sessionID = exchangeHash; + return value + }, + defaultValue: 'transparent' + } +]) - { - const newSecret = Buffer.allocUnsafe(4 + secret.length); - writeUInt32BE(newSecret, secret.length, 0); - newSecret.set(secret, 4); - secret = newSecret; - } +/** + * @see https://www.w3.org/TR/FileAPI/#process-blob-parts + * @param {(NodeJS.TypedArray|Blob|string)[]} parts + * @param {{ type: string, endings: string }} options + */ +function processBlobParts (parts, options) { + // 1. Let bytes be an empty sequence of bytes. + /** @type {NodeJS.TypedArray[]} */ + const bytes = [] + + // 2. For each element in parts: + for (const element of parts) { + // 1. If element is a USVString, run the following substeps: + if (typeof element === 'string') { + // 1. Let s be element. + let s = element + + // 2. If the endings member of options is "native", set s + // to the result of converting line endings to native + // of element. + if (options.endings === 'native') { + s = convertLineEndingsNative(s) + } - // Initialize new ciphers, deciphers, etc. + // 3. Append the result of UTF-8 encoding s to bytes. + bytes.push(encoder.encode(s)) + } else if ( + types.isAnyArrayBuffer(element) || + types.isTypedArray(element) + ) { + // 2. If element is a BufferSource, get a copy of the + // bytes held by the buffer source, and append those + // bytes to bytes. + if (!element.buffer) { // ArrayBuffer + bytes.push(new Uint8Array(element)) + } else { + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ) + } + } else if (isBlobLike(element)) { + // 3. If element is a Blob, append the bytes it represents + // to bytes. + bytes.push(element) + } + } - const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; - const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; + // 3. Return bytes. + return bytes +} - const csIV = generateKEXVal(csCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'A'); - const scIV = generateKEXVal(scCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'B'); - const csKey = generateKEXVal(csCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'C'); - const scKey = generateKEXVal(scCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'D'); - let csMacInfo; - let csMacKey; - if (!csCipherInfo.authLen) { - csMacInfo = MAC_INFO[negotiated.cs.mac]; - csMacKey = generateKEXVal(csMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'E'); - } - let scMacInfo; - let scMacKey; - if (!scCipherInfo.authLen) { - scMacInfo = MAC_INFO[negotiated.sc.mac]; - scMacKey = generateKEXVal(scMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'F'); - } +/** + * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native + * @param {string} s + */ +function convertLineEndingsNative (s) { + // 1. Let native line ending be be the code point U+000A LF. + let nativeLineEnding = '\n' - const config = { - inbound: { - onPayload: this._protocol._onPayload, - seqno: this._protocol._decipher.inSeqno, - decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), - decipherIV: (!isServer ? scIV : csIV), - decipherKey: (!isServer ? scKey : csKey), - macInfo: (!isServer ? scMacInfo : csMacInfo), - macKey: (!isServer ? scMacKey : csMacKey), - }, - outbound: { - onWrite: this._protocol._onWrite, - seqno: this._protocol._cipher.outSeqno, - cipherInfo: (isServer ? scCipherInfo : csCipherInfo), - cipherIV: (isServer ? scIV : csIV), - cipherKey: (isServer ? scKey : csKey), - macInfo: (isServer ? scMacInfo : csMacInfo), - macKey: (isServer ? scMacKey : csMacKey), - }, - }; - this._protocol._cipher && this._protocol._cipher.free(); - this._protocol._decipher && this._protocol._decipher.free(); - this._protocol._cipher = createCipher(config); - this._protocol._decipher = createDecipher(config); + // 2. If the underlying platform’s conventions are to + // represent newlines as a carriage return and line feed + // sequence, set native line ending to the code point + // U+000D CR followed by the code point U+000A LF. + if (process.platform === 'win32') { + nativeLineEnding = '\r\n' + } - const rw = { - read: undefined, - write: undefined, - }; - switch (negotiated.cs.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication + return s.replace(/\r?\n/g, nativeLineEnding) +} - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression +// If this function is moved to ./util.js, some tools (such as +// rollup) will warn about circular dependencies. See: +// https://github.com/nodejs/undici/issues/1629 +function isFileLike (object) { + return ( + (NativeFile && object instanceof NativeFile) || + object instanceof File || ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) +} - if (isServer) - rw.read = new PacketReader(); - else - rw.write = new PacketWriter(this._protocol); - } - switch (negotiated.sc.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication +module.exports = { File, FileLike, isFileLike } - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - if (isServer) - rw.write = new PacketWriter(this._protocol); - else - rw.read = new PacketReader(); - } - this._protocol._packetRW.read.cleanup(); - this._protocol._packetRW.write.cleanup(); - this._protocol._packetRW = rw; +/***/ }), - // Cleanup/reset various state - this._public = null; - this._dh = null; - this._kexinit = this._protocol._kexinit = undefined; - this._remoteKexinit = undefined; - this._identRaw = undefined; - this._remoteIdentRaw = undefined; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; +/***/ 2015: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._protocol._onHandshakeComplete(negotiated); +"use strict"; - return false; - }; - if (!isServer) - return completeHandshake(); - this.finish = completeHandshake; - } - start() { - if (!this._protocol._server) { - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_INIT'; - break; - default: - type = 'KEXECDH_INIT'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } +const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(2538) +const { kState } = __nccwpck_require__(5861) +const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(8511) +const { webidl } = __nccwpck_require__(1744) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) - const pubKey = this.getPublicKey(); +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + pubKey.length, - true - ); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } +// https://xhr.spec.whatwg.org/#formdata +class FormData { + constructor (form) { + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) } - getPublicKey() { - this.generateKeys(); - const key = this._public; + this[kState] = [] + } - if (key) - return this.convertPublicKey(key); - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) - if (key[idx] & 0x80) { - newKey = Buffer.allocUnsafe(1 + len); - newKey[0] = 0; - key.copy(newKey, 1, idx); - return newKey; - } + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) } - computeSecret(otherPublicKey) { - this.generateKeys(); - try { - return convertToMpint(this._dh.computeSecret(otherPublicKey)); - } catch (ex) { - return ex; - } - } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - // Server - if (type !== MESSAGE.KEXDH_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Init' - ); - /* - byte SSH_MSG_KEXDH_INIT - / SSH_MSG_KEX_ECDH_INIT - string - */ - bufferParser.init(payload, 1); - const dhData = bufferParser.readString(); - bufferParser.clear(); - if (dhData === undefined) { - return doFatalError( - this._protocol, - 'Received malformed KEX*_INIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // 1. Let value be value if given; otherwise blobValue. - // Client public key - this._dhData = dhData; + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? webidl.converters.USVString(filename) + : undefined - let hostKey = - this._protocol._hostKeys[this.negotiated.serverHostKey]; - if (Array.isArray(hostKey)) - hostKey = hostKey[0]; - this._hostKey = hostKey; + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) - this.finish(); - } else { - // Client - if (type !== MESSAGE.KEXDH_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Reply' - ); - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - bufferParser.init(payload, 1); - let hostPubKey; - let dhData; - let sig; - if ((hostPubKey = bufferParser.readString()) === undefined - || (dhData = bufferParser.readString()) === undefined - || (sig = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEX*_REPLY', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); + // 3. Append entry to this’s entry list. + this[kState].push(entry) + } - // Check that the host public key type matches what was negotiated - // during KEXINIT swap - bufferParser.init(hostPubKey, 0); - const hostPubKeyType = bufferParser.readString(true); - bufferParser.clear(); - if (hostPubKeyType === undefined) { - return doFatalError( - this._protocol, - 'Received malformed host public key', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (hostPubKeyType !== this.negotiated.serverHostKey) { - // Check if we need to make an exception - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': - case 'rsa-sha2-512': - if (hostPubKeyType === 'ssh-rsa') - break; - // FALLTHROUGH - default: - return doFatalError( - this._protocol, - 'Host key does not match negotiated type', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } + delete (name) { + webidl.brandCheck(this, FormData) - this._hostKey = hostPubKey; - this._dhData = dhData; - this._sig = sig; + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) - let checked = false; - let ret; - if (this._protocol._hostVerifier === undefined) { - ret = true; - this._protocol._debug && this._protocol._debug( - 'Host accepted by default (no verification)' - ); - } else { - ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { - if (checked) - return; - checked = true; - if (permitted === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - if (this._receivedNEWKEYS) - this.finish(); - else - trySendNEWKEYS(this); - }); - } - if (ret === undefined) { - // Async host verification - ++this._step; - return; - } - checked = true; - if (ret === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - trySendNEWKEYS(this); - } - ++this._step; - break; - case 2: - if (type !== MESSAGE.NEWKEYS) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Inbound: NEWKEYS' - ); - this._receivedNEWKEYS = true; - ++this._step; - if (this._protocol._server || this._hostVerified) - return this.finish(); + name = webidl.converters.USVString(name) - // Signal to current decipher that we need to change to a new decipher - // for the next packet - return false; - default: - return doFatalError( - this._protocol, - `Received unexpected packet ${type} after NEWKEYS`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this[kState] = this[kState].filter(entry => entry.name !== name) } - class Curve25519Exchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); + get (name) { + webidl.brandCheck(this, FormData) - this.type = '25519'; - this.hashName = hashName; - this._keys = null; - } - generateKeys() { - if (!this._keys) - this._keys = generateKeyPairSync('x25519'); - } - getPublicKey() { - this.generateKeys(); + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) - const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); - return key.slice(-32); // HACK: avoids parsing DER/BER header + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx === -1) { + return null } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - if (key.length === 32) - return key; + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; - } - computeSecret(otherPublicKey) { - this.generateKeys(); + getAll (name) { + webidl.brandCheck(this, FormData) - try { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.110'); // id-X25519 - asnWriter.endSequence(); + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(otherPublicKey.length); - otherPublicKey.copy(asnWriter._buf, - asnWriter._offset, - 0, - otherPublicKey.length); - asnWriter._offset += otherPublicKey.length; - asnWriter.endSequence(); - asnWriter.endSequence(); + name = webidl.converters.USVString(name) - return convertToMpint(diffieHellman({ - privateKey: this._keys.privateKey, - publicKey: createPublicKey({ - key: asnWriter.buffer, - type: 'spki', - format: 'der', - }), - })); - } catch (ex) { - return ex; - } - } + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) } - class ECDHExchange extends KeyExchange { - constructor(curveName, hashName, ...args) { - super(...args); + has (name) { + webidl.brandCheck(this, FormData) - this.type = 'ecdh'; - this.curveName = curveName; - this.hashName = hashName; + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) + + name = webidl.converters.USVString(name) + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) } - generateKeys() { - if (!this._dh) { - this._dh = createECDH(this.curveName); - this._public = this._dh.generateKeys(); - } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? toUSVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry) } } - class DHGroupExchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); + entries () { + webidl.brandCheck(this, FormData) - this.type = 'groupex'; - this.hashName = hashName; - this._prime = null; - this._generator = null; - this._minBits = GEX_MIN_BITS; - this._prefBits = dhEstimate(this.negotiated); - if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) - this._prefBits = Math.min(this._prefBits, 4096); - this._maxBits = GEX_MAX_BITS; + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) + } + + keys () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key' + ) + } + + values () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' + ) + } + + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) } - start() { - if (this._protocol._server) - return; - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_REQUEST' - ); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + 4 + 4, - true - ); - packet[p] = MESSAGE.KEXDH_GEX_REQUEST; - writeUInt32BE(packet, this._minBits, ++p); - writeUInt32BE(packet, this._prefBits, p += 4); - writeUInt32BE(packet, this._maxBits, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) } - generateKeys() { - if (!this._dh && this._prime && this._generator) { - this._dh = createDiffieHellman(this._prime, this._generator); - this._public = this._dh.generateKeys(); + } +} + +FormData.prototype[Symbol.iterator] = FormData.prototype.entries + +Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // "To convert a string into a scalar value string, replace any surrogates + // with U+FFFD." + // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end + name = Buffer.from(name).toString('utf8') + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + value = Buffer.from(value).toString('utf8') + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }) + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified } + + value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile + ? new File([value], filename, options) + : new FileLike(value, filename, options) } - setDHParams(prime, generator) { - if (!Buffer.isBuffer(prime)) - throw new Error('Invalid prime value'); - if (!Buffer.isBuffer(generator)) - throw new Error('Invalid generator value'); - this._prime = prime; - this._generator = generator; - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} + +module.exports = { FormData } + + +/***/ }), + +/***/ 1246: +/***/ ((module) => { + +"use strict"; + + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return + } + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} + +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} + + +/***/ }), + +/***/ 554: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// https://github.com/Ethan-Arrowood/undici-fetch + + + +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const { kGuard } = __nccwpck_require__(5861) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const { + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = __nccwpck_require__(2538) +const { webidl } = __nccwpck_require__(1744) +const assert = __nccwpck_require__(9491) + +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') + +/** + * @param {number} code + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length + + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +} + +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i] + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) } + + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]) } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_REQUEST) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ` - + MESSAGE.KEXDH_GEX_REQUEST, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - // TODO: allow user implementation to provide safe prime and - // generator on demand to support group exchange on server side - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object) + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + */ +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } - if (type !== MESSAGE.KEXDH_GEX_GROUP) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (headers[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (headers[kGuard] === 'request-no-cors') { + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Group' - ); + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. - /* - byte SSH_MSG_KEX_DH_GEX_GROUP - mpint p, safe prime - mpint g, generator for subgroup in GF(p) - */ - bufferParser.init(payload, 1); - let prime; - let gen; - if ((prime = bufferParser.readString()) === undefined - || (gen = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEXDH_GEX_GROUP', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); + // 7. Append (name, value) to headers’s header list. + return headers[kHeadersList].append(name, value) - // TODO: validate prime - this.setDHParams(prime, gen); - this.generateKeys(); - const pubkey = this.getPublicKey(); + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers +} - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_INIT' - ); +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); - packet[p] = MESSAGE.KEXDH_GEX_INIT; - writeUInt32BE(packet, pubkey.length, ++p); - packet.set(pubkey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]) + this[kHeadersSortedMap] = init[kHeadersSortedMap] + this.cookies = init.cookies === null ? null : [...init.cookies] + } else { + this[kHeadersMap] = new Map(init) + this[kHeadersSortedMap] = null + } + } - ++this._step; - break; - case 2: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Init' - ); - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Reply' - ); - this._step = 1; - payload[0] = MESSAGE.KEXDH_REPLY; - this.parse = KeyExchange.prototype.parse; - this.parse(payload); - } + // https://fetch.spec.whatwg.org/#header-list-contains + contains (name) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + name = name.toLowerCase() + + return this[kHeadersMap].has(name) + } + + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null + } + + // https://fetch.spec.whatwg.org/#concept-header-list-append + append (name, value) { + this[kHeadersSortedMap] = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = name.toLowerCase() + const exists = this[kHeadersMap].get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + this.cookies ??= [] + this.cookies.push(value) } } - class DHExchange extends KeyExchange { - constructor(groupName, hashName, ...args) { - super(...args); + // https://fetch.spec.whatwg.org/#concept-header-list-set + set (name, value) { + this[kHeadersSortedMap] = null + const lowercaseName = name.toLowerCase() - this.type = 'group'; - this.groupName = groupName; - this.hashName = hashName; + if (lowercaseName === 'set-cookie') { + this.cookies = [value] } - start() { - if (!this._protocol._server) { - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_INIT' - ); - const pubKey = this.getPublicKey(); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-delete + delete (name) { + this[kHeadersSortedMap] = null + + name = name.toLowerCase() + + if (name === 'set-cookie') { + this.cookies = null } - generateKeys() { - if (!this._dh) { - this._dh = createDiffieHellmanGroup(this.groupName); - this._public = this._dh.generateKeys(); - } + + this[kHeadersMap].delete(name) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-get + get (name) { + const value = this[kHeadersMap].get(name.toLowerCase()) + + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return value === undefined ? null : value.value + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; + } + + get entries () { + const headers = {} + + if (this[kHeadersMap].size) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value } } + + return headers } +} - return (negotiated, ...args) => { - if (typeof negotiated !== 'object' || negotiated === null) - throw new Error('Invalid negotiated argument'); - const kexType = negotiated.kex; - if (typeof kexType === 'string') { - args = [negotiated, ...args]; - switch (kexType) { - case 'curve25519-sha256': - case 'curve25519-sha256@libssh.org': - if (!curve25519Supported) - break; - return new Curve25519Exchange('sha256', ...args); +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + constructor (init = undefined) { + if (init === kConstruct) { + return + } + this[kHeadersList] = new HeadersList() - case 'ecdh-sha2-nistp256': - return new ECDHExchange('prime256v1', 'sha256', ...args); - case 'ecdh-sha2-nistp384': - return new ECDHExchange('secp384r1', 'sha384', ...args); - case 'ecdh-sha2-nistp521': - return new ECDHExchange('secp521r1', 'sha512', ...args); + // The new Headers(init) constructor steps are: - case 'diffie-hellman-group1-sha1': - return new DHExchange('modp2', 'sha1', ...args); - case 'diffie-hellman-group14-sha1': - return new DHExchange('modp14', 'sha1', ...args); - case 'diffie-hellman-group14-sha256': - return new DHExchange('modp14', 'sha256', ...args); - case 'diffie-hellman-group15-sha512': - return new DHExchange('modp15', 'sha512', ...args); - case 'diffie-hellman-group16-sha512': - return new DHExchange('modp16', 'sha512', ...args); - case 'diffie-hellman-group17-sha512': - return new DHExchange('modp17', 'sha512', ...args); - case 'diffie-hellman-group18-sha512': - return new DHExchange('modp18', 'sha512', ...args); + // 1. Set this’s guard to "none". + this[kGuard] = 'none' - case 'diffie-hellman-group-exchange-sha1': - return new DHGroupExchange('sha1', ...args); - case 'diffie-hellman-group-exchange-sha256': - return new DHGroupExchange('sha256', ...args); - } - throw new Error(`Unsupported key exchange algorithm: ${kexType}`); + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init) + fill(this, init) } - throw new Error(`Invalid key exchange type: ${kexType}`); - }; -})(); + } -const KexInit = (() => { - const KEX_PROPERTY_NAMES = [ - 'kex', - 'serverHostKey', - ['cs', 'cipher' ], - ['sc', 'cipher' ], - ['cs', 'mac' ], - ['sc', 'mac' ], - ['cs', 'compress' ], - ['sc', 'compress' ], - ['cs', 'lang' ], - ['sc', 'lang' ], - ]; - return class KexInit { - constructor(obj) { - if (typeof obj !== 'object' || obj === null) - throw new TypeError('Argument must be an object'); + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) - const lists = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) - all: undefined, - }; - let totalSize = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let base; - let val; - let desc; - let key; - if (typeof prop === 'string') { - base = lists; - val = obj[prop]; - desc = key = prop; - } else { - const parent = prop[0]; - base = lists[parent]; - key = prop[1]; - val = obj[parent][key]; - desc = `${parent}.${key}`; - } - const entry = { array: undefined, buffer: undefined }; - if (Buffer.isBuffer(val)) { - entry.array = ('' + val).split(','); - entry.buffer = val; - totalSize += 4 + val.length; - } else { - if (typeof val === 'string') - val = val.split(','); - if (Array.isArray(val)) { - entry.array = val; - entry.buffer = Buffer.from(val.join(',')); - } else { - throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); - } - totalSize += 4 + entry.buffer.length; - } - base[key] = entry; - } + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) - const all = Buffer.allocUnsafe(totalSize); - lists.all = all; + return appendHeader(this, name, value) + } - let allPos = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let data; - if (typeof prop === 'string') - data = lists[prop].buffer; - else - data = lists[prop[0]][prop[1]].buffer; - allPos = writeUInt32BE(all, data.length, allPos); - all.set(data, allPos); - allPos += data.length; - } + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) - this.totalSize = totalSize; - this.lists = lists; + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) } - copyAllTo(buf, offset) { - const src = this.lists.all; - if (typeof offset !== 'number') - throw new TypeError(`Invalid offset value: ${typeof offset}`); - if (buf.length - offset < src.length) - throw new Error('Insufficient space to copy list'); - buf.set(src, offset); - return src.length; + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return } - }; -})(); -const hashString = (() => { - const LEN = Buffer.allocUnsafe(4); - return (hash, buf) => { - writeUInt32BE(LEN, buf.length, 0); - hash.update(LEN); - hash.update(buf); - }; -})(); + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this[kHeadersList].delete(name) + } -function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { - let ret; - if (len) { - let digest = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(char) - .update(sessionID) - .digest(); - while (digest.length < len) { - const chunk = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(digest) - .digest(); - const extended = Buffer.allocUnsafe(digest.length + chunk.length); - extended.set(digest, 0); - extended.set(chunk, digest.length); - digest = extended; + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.get', + value: name, + type: 'header name' + }) } - if (digest.length === len) - ret = digest; - else - ret = new FastBuffer(digest.buffer, digest.byteOffset, len); - } else { - ret = EMPTY_BUFFER; + + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) } - return ret; -} -function onKEXPayload(state, payload) { - // XXX: move this to the Decipher implementations? - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.has', + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this[kHeadersList].contains(name) } - if (this._skipNextInboundPacket) { - this._skipNextInboundPacket = false; - return; + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this[kHeadersList].set(name, value) } - payload = this._packetRW.read.read(payload); + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) - const type = payload[0]; - switch (type) { - case MESSAGE.DISCONNECT: - case MESSAGE.IGNORE: - case MESSAGE.UNIMPLEMENTED: - case MESSAGE.DEBUG: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = __nccwpck_require__(172); - return MESSAGE_HANDLERS[type](this, payload); - case MESSAGE.KEXINIT: - if (!state.firstPacket) { - return doFatalError( - this, - 'Received extra KEXINIT during handshake', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - state.firstPacket = false; - return handleKexInit(this, payload); - default: - if (type < 20 || type > 49) { - return doFatalError( - this, - `Received unexpected packet type ${type}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this[kHeadersList].cookies + + if (list) { + return [...list] + } + + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) + const cookies = this[kHeadersList].cookies + + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const [name, value] = names[i] + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]) + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + assert(value !== null) + + // 3. Append (name, value) to headers. + headers.push([name, value]) } + } + + this[kHeadersList][kHeadersSortedMap] = headers + + // 4. Return headers. + return headers } - return this._kex.parse(payload); -} + keys () { + webidl.brandCheck(this, Headers) -function dhEstimate(neg) { - const csCipher = CIPHER_INFO[neg.cs.cipher]; - const scCipher = CIPHER_INFO[neg.sc.cipher]; - // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will - // also need to be considered when calculating `bits` - const bits = Math.max( - 0, - (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), - csCipher.blockLen, - csCipher.ivLen, - (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), - scCipher.blockLen, - scCipher.ivLen - ) * 8; - if (bits <= 112) - return 2048; - if (bits <= 128) - return 3072; - if (bits <= 192) - return 7680; - return 8192; -} + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key') + } -function trySendNEWKEYS(kex) { - if (!kex._sentNEWKEYS) { - kex._protocol._debug && kex._protocol._debug( - 'Outbound: Sending NEWKEYS' - ); - const p = kex._protocol._packetRW.write.allocStartKEX; - const packet = kex._protocol._packetRW.write.alloc(1, true); - packet[p] = MESSAGE.NEWKEYS; - kex._protocol._cipher.encrypt( - kex._protocol._packetRW.write.finalize(packet, true) - ); - kex._sentNEWKEYS = true; + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) } -} -module.exports = { - KexInit, - kexinit, - onKEXPayload, - DEFAULT_KEXINIT: new KexInit({ - kex: DEFAULT_KEX, - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - }), - HANDLERS: { - [MESSAGE.KEXINIT]: handleKexInit, - }, -}; + values () { + webidl.brandCheck(this, Headers) + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'value') + } -/***/ }), + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } -/***/ 2218: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + entries () { + webidl.brandCheck(this, Headers) -"use strict"; -// TODO: -// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` -// * handle multi-line header values (OpenSSH)? -// * more thorough validation? + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key+value') + } + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) + } -const { - createDecipheriv, - createECDH, - createHash, - createHmac, - createSign, - createVerify, - getCiphers, - sign: sign_, - verify: verify_, -} = __nccwpck_require__(6113); -const supportedOpenSSLCiphers = getCiphers(); + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers) -const { Ber } = __nccwpck_require__(970); -const bcrypt_pbkdf = (__nccwpck_require__(5447).pbkdf); + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) -const { CIPHER_INFO } = __nccwpck_require__(5708); -const { eddsaSupported, SUPPORTED_CIPHER } = __nccwpck_require__(6832); -const { - bufferSlice, - makeBufferParser, - readString, - readUInt32BE, - writeUInt32BE, -} = __nccwpck_require__(9475); + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." + ) + } -const SYM_HASH_ALGO = Symbol('Hash Algorithm'); -const SYM_PRIV_PEM = Symbol('Private key PEM'); -const SYM_PUB_PEM = Symbol('Public key PEM'); -const SYM_PUB_SSH = Symbol('Public key SSH'); -const SYM_DECRYPTED = Symbol('Decrypted Key'); + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } -// Create OpenSSL cipher name -> SSH cipher name conversion table -const CIPHER_INFO_OPENSSL = Object.create(null); -{ - const keys = Object.keys(CIPHER_INFO); - for (let i = 0; i < keys.length; ++i) { - const cipherName = CIPHER_INFO[keys[i]].sslName; - if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) - continue; - CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) + + return this[kHeadersList] } } -const binaryKeyParser = makeBufferParser(); +Headers.prototype[Symbol.iterator] = Headers.prototype.entries -function makePEM(type, data) { - data = data.base64Slice(0, data.length); - let formatted = data.replace(/.{64}/g, '$&\n'); - if (data.length & 63) - formatted += '\n'; - return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; -} +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + keys: kEnumerableProperty, + values: kEnumerableProperty, + entries: kEnumerableProperty, + forEach: kEnumerableProperty, + [Symbol.iterator]: { enumerable: false }, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + } +}) -function combineBuffers(buf1, buf2) { - const result = Buffer.allocUnsafe(buf1.length + buf2.length); - result.set(buf1, 0); - result.set(buf2, buf1.length); - return result; -} +webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) + } -function skipFields(buf, nfields) { - const bufLen = buf.length; - let pos = (buf._pos || 0); - for (let i = 0; i < nfields; ++i) { - const left = (bufLen - pos); - if (pos >= bufLen || left < 4) - return false; - const len = readUInt32BE(buf, pos); - if (left < 4 + len) - return false; - pos += 4 + len; + return webidl.converters['record'](V) } - buf._pos = pos; - return true; -} -function genOpenSSLRSAPub(n, e) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption - // algorithm parameters (RSA has none) - asnWriter.writeNull(); - asnWriter.endSequence(); + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.startSequence(); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); +module.exports = { + fill, + Headers, + HeadersList } -function genOpenSSHRSAPub(n, e) { - const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-rsa', 4, 7); +/***/ }), - let i = 4 + 7; - writeUInt32BE(publicKey, e.length, i); - publicKey.set(e, i += 4); +/***/ 4881: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(publicKey, n.length, i += e.length); - publicKey.set(n, i + 4); +"use strict"; +// https://github.com/Ethan-Arrowood/undici-fetch - return publicKey; -} -const genOpenSSLRSAPriv = (() => { - function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.writeBuffer(d, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(dmp1, Ber.Integer); - asnWriter.writeBuffer(dmq1, Ber.Integer); - asnWriter.writeBuffer(iqmp, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - function bigIntFromBuffer(buf) { - return BigInt(`0x${buf.hexSlice(0, buf.length)}`); +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = __nccwpck_require__(7823) +const { Headers } = __nccwpck_require__(554) +const { Request, makeRequest } = __nccwpck_require__(8359) +const zlib = __nccwpck_require__(9796) +const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme +} = __nccwpck_require__(2538) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const assert = __nccwpck_require__(9491) +const { safelyExtractBody } = __nccwpck_require__(1472) +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet, + DOMException +} = __nccwpck_require__(1037) +const { kHeadersList } = __nccwpck_require__(2785) +const EE = __nccwpck_require__(2361) +const { Readable, pipeline } = __nccwpck_require__(2781) +const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3983) +const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(685) +const { TransformStream } = __nccwpck_require__(5356) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { webidl } = __nccwpck_require__(1744) +const { STATUS_CODES } = __nccwpck_require__(3685) +const GET_OR_HEAD = ['GET', 'HEAD'] + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + // 2 terminated listeners get added per request, + // but only 1 gets removed. If there are 20 redirects, + // 21 listeners will be added. + // See https://github.com/nodejs/undici/issues/1711 + // TODO (fix): Find and fix root cause for leaked listener. + this.setMaxListeners(21) + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) } - function bigIntToBuffer(bn) { - let hex = bn.toString(16); - if ((hex.length & 1) !== 0) { - hex = `0${hex}`; - } else { - const sigbit = hex.charCodeAt(0); - // BER/DER integers require leading zero byte to denote a positive value - // when first byte >= 0x80 - if (sigbit === 56/* '8' */ - || sigbit === 57/* '9' */ - || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { - hex = `00${hex}`; - } + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return } - return Buffer.from(hex, 'hex'); - } - return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { - const bn_d = bigIntFromBuffer(d); - const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); - const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); - return makePEM('RSA PRIVATE', - genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); - }; -})(); + // 1. Set controller’s state to "aborted". + this.state = 'aborted' -function genOpenSSLDSAPub(p, q, g, y) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa - // algorithm parameters - asnWriter.startSequence(); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error + + this.connection?.destroy(error) + this.emit('terminated', error) + } } -function genOpenSSHDSAPub(p, q, g, y) { - const publicKey = Buffer.allocUnsafe( - 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length - ); +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-dss', 4, 7); + // 1. Let p be a new promise. + const p = createDeferredPromise() - let i = 4 + 7; - writeUInt32BE(publicKey, p.length, i); - publicKey.set(p, i += 4); + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject - writeUInt32BE(publicKey, q.length, i += p.length); - publicKey.set(q, i += 4); + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise + } - writeUInt32BE(publicKey, g.length, i += q.length); - publicKey.set(g, i += 4); + // 3. Let request be requestObject’s request. + const request = requestObject[kState] - writeUInt32BE(publicKey, y.length, i += g.length); - publicKey.set(y, i + 4); + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) - return publicKey; -} + // 2. Return p. + return p.promise + } -function genOpenSSLDSAPriv(p, q, g, y, x) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.writeBuffer(x, Ber.Integer); - asnWriter.endSequence(); - return makePEM('DSA PRIVATE', asnWriter.buffer); -} + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject -function genOpenSSLEdPub(pub) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} + // 7. Let responseObject be null. + let responseObject = null -function genOpenSSHEdPub(pub) { - const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null - writeUInt32BE(publicKey, 11, 0); - publicKey.utf8Write('ssh-ed25519', 4, 11); + // 9. Let locallyAborted be false. + let locallyAborted = false - writeUInt32BE(publicKey, pub.length, 15); - publicKey.set(pub, 19); + // 10. Let controller be null. + let controller = null - return publicKey; -} + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true -function genOpenSSLEdPriv(priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x00, Ber.Integer); + // 2. Assert: controller is non-null. + assert(controller != null) - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) - // PrivateKey - asnWriter.startSequence(Ber.OctetString); - asnWriter.writeBuffer(priv, Ber.OctetString); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PRIVATE', asnWriter.buffer); -} + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason) + } + ) -function genOpenSSLECDSAPub(oid, Q) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey - // algorithm parameters (namedCurve) - asnWriter.writeOID(oid); - asnWriter.endSequence(); + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch') - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(Q.length); - asnWriter._buf.set(Q, asnWriter._offset); - asnWriter._offset += Q.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: -function genOpenSSHECDSAPub(oid, Q) { - let curveName; - switch (oid) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - curveName = 'nistp256'; - break; - case '1.3.132.0.34': - // secp384r1 - curveName = 'nistp384'; - break; - case '1.3.132.0.35': - // secp521r1 - curveName = 'nistp521'; - break; - default: - return; - } + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() + } - const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. - writeUInt32BE(publicKey, 19, 0); - publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. - writeUInt32BE(publicKey, 8, 23); - publicKey.utf8Write(curveName, 27, 8); + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return Promise.resolve() + } - writeUInt32BE(publicKey, Q.length, 35); - publicKey.set(Q, 39); + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject( + Object.assign(new TypeError('fetch failed'), { cause: response.error }) + ) + return Promise.resolve() + } - return publicKey; -} + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new Response() + responseObject[kState] = response + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm -function genOpenSSLECDSAPriv(oid, pub, priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x01, Ber.Integer); - // privateKey - asnWriter.writeBuffer(priv, Ber.OctetString); - // parameters (optional) - asnWriter.startSequence(0xA0); - asnWriter.writeOID(oid); - asnWriter.endSequence(); - // publicKey (optional) - asnWriter.startSequence(0xA1); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('EC PRIVATE', asnWriter.buffer); -} + // 5. Resolve p with responseObject. + p.resolve(responseObject) + } -function genOpenSSLECDSAPubFromPriv(curveName, priv) { - const tempECDH = createECDH(curveName); - tempECDH.setPrivateKey(priv); - return tempECDH.getPublicKey(); + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) + + // 14. Return p. + return p.promise } -const BaseKey = { - sign: (() => { - if (typeof sign_ === 'function') { - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return sign_(algo, data, pem); - } catch (ex) { - return ex; - } - }; - } - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const signature = createSign(algo); - signature.update(data); - try { - return signature.sign(pem); - } catch (ex) { - return ex; - } - }; - })(), - verify: (() => { - if (typeof verify_ === 'function') { - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return verify_(algo, data, pem, signature); - } catch (ex) { - return ex; - } - }; - } - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const verifier = createVerify(algo); - verifier.update(data); - try { - return verifier.verify(pem, signature); - } catch (ex) { - return ex; - } - }; - })(), - isPrivateKey: function isPrivateKey() { - return (this[SYM_PRIV_PEM] !== null); - }, - getPrivatePEM: function getPrivatePEM() { - return this[SYM_PRIV_PEM]; - }, - getPublicPEM: function getPublicPEM() { - return this[SYM_PUB_PEM]; - }, - getPublicSSH: function getPublicSSH() { - return this[SYM_PUB_SSH]; - }, - equals: function equals(key) { - const parsed = parseKey(key); - if (parsed instanceof Error) - return false; - return ( - this.type === parsed.type - && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] - && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] - && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH] - ); - }, -}; +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } -function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; - OpenSSH_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let ret; - const data = Buffer.from(m[1], 'base64'); - if (data.length < 31) // magic (+ magic null term.) + minimum field lengths - return new Error('Malformed OpenSSH private key'); - const magic = data.utf8Slice(0, 15); - if (magic !== 'openssh-key-v1\0') - return new Error(`Unsupported OpenSSH key magic: ${magic}`); + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] - const cipherName = readString(data, 15, true); - if (cipherName === undefined) - return new Error('Malformed OpenSSH private key'); - if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) - return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo - const kdfName = readString(data, data._pos, true); - if (kdfName === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'none') { - if (cipherName === 'none') - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'bcrypt') - return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); - if (!passphrase) { - return new Error( - 'Encrypted private OpenSSH key detected, but no passphrase given' - ); - } - } else if (cipherName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState - let encInfo; - let cipherKey; - let cipherIV; - if (cipherName !== 'none') - encInfo = CIPHER_INFO[cipherName]; - const kdfOptions = readString(data, data._pos); - if (kdfOptions === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfOptions.length) { - switch (kdfName) { - case 'none': - return new Error('Malformed OpenSSH private key'); - case 'bcrypt': - /* - string salt - uint32 rounds - */ - const salt = readString(kdfOptions, 0); - if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) - return new Error('Malformed OpenSSH private key'); - const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); - const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); - const r = bcrypt_pbkdf(passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds); - if (r !== 0) - return new Error('Failed to generate information to decrypt key'); - cipherKey = bufferSlice(gen, 0, encInfo.keyLen); - cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); - break; - } - } else if (kdfName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } - if (data._pos + 3 >= data.length) - return new Error('Malformed OpenSSH private key'); - const keyCount = readUInt32BE(data, data._pos); - data._pos += 4; + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } - if (keyCount > 0) { - // TODO: place sensible limit on max `keyCount` + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) - // Read public keys first - for (let i = 0; i < keyCount; ++i) { - const pubData = readString(data, data._pos); - if (pubData === undefined) - return new Error('Malformed OpenSSH private key'); - const type = readString(pubData, 0, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { + if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { + performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) + } +} + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // Note: AbortSignal.reason was added in node v17.2.0 + // which would give us an undefined error to reject with. + // Remove this once node v16 is no longer supported. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 1. Reject promise with error. + p.reject(error) + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return } + throw err + }) + } - let privBlob = readString(data, data._pos); - if (privBlob === undefined) - return new Error('Malformed OpenSSH private key'); + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } - if (cipherKey !== undefined) { - // Encrypted private key(s) - if (privBlob.length < encInfo.blockLen - || (privBlob.length % encInfo.blockLen) !== 0) { - return new Error('Malformed OpenSSH private key'); - } - try { - const options = { authTagLength: encInfo.authLen }; - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - cipherIV, - options); - if (encInfo.authLen > 0) { - if (data.length - data._pos < encInfo.authLen) - return new Error('Malformed OpenSSH private key'); - decipher.setAuthTag( - bufferSlice(data, data._pos, data._pos += encInfo.authLen) - ); - } - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } + // 4. Let response be responseObject’s response. + const response = responseObject[kState] + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return } - // Nothing should we follow the private key(s), except a possible - // authentication tag for relevant ciphers - if (data._pos !== data.length) - return new Error('Malformed OpenSSH private key'); + throw err + }) + } +} - ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher // undici +}) { + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currenTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + // TODO: What if request.client is null? + request.origin = request.client?.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) } else { - ret = []; + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() } - if (ret instanceof Error) - return ret; - // This will need to change if/when OpenSSH ever starts storing multiple - // keys in their key files - return ret[0]; - }; + } - function parseOpenSSHPrivKeys(data, nkeys, decrypted) { - const keys = []; - /* - uint32 checkint - uint32 checkint - string privatekey1 - string comment1 - string privatekey2 - string comment2 - ... - string privatekeyN - string commentN - char 1 - char 2 - char 3 - ... - char padlen % 255 - */ - if (data.length < 8) - return new Error('Malformed OpenSSH private key'); - const check1 = readUInt32BE(data, 0); - const check2 = readUInt32BE(data, 4); - if (check1 !== check2) { - if (decrypted) { - return new Error( - 'OpenSSH key integrity check failed -- bad passphrase?' - ); - } - return new Error('OpenSSH key integrity check failed'); - } - data._pos = 8; - let i; - let oid; - for (i = 0; i < nkeys; ++i) { - let algo; - let privPEM; - let pubPEM; - let pubSSH; - // The OpenSSH documentation for the key format actually lies, the - // entirety of the private key content is not contained with a string - // field, it's actually the literal contents of the private key, so to be - // able to find the end of the key data you need to know the layout/format - // of each key type ... - const type = readString(data, data._pos, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' - switch (type) { - case 'ssh-rsa': { - /* - string n -- public - string e -- public - string d -- private - string iqmp -- private - string p -- private - string q -- private - */ - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH private key'); - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed OpenSSH private key'); - const d = readString(data, data._pos); - if (d === undefined) - return new Error('Malformed OpenSSH private key'); - const iqmp = readString(data, data._pos); - if (iqmp === undefined) - return new Error('Malformed OpenSSH private key'); - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - /* - string p -- public - string q -- public - string g -- public - string y -- public - string x -- private - */ - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH private key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH private key'); - const x = readString(data, data._pos); - if (x === undefined) - return new Error('Malformed OpenSSH private key'); + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value) + } - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - if (!eddsaSupported) - return new Error(`Unsupported OpenSSH private key type: ${type}`); - /* - * string public key - * string private key + public key - */ - const edpub = readString(data, data._pos); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH private key'); - const edpriv = readString(data, data._pos); - if (edpriv === undefined || edpriv.length !== 64) - return new Error('Malformed OpenSSH private key'); + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language')) { + request.headersList.append('accept-language', '*') + } - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - /* - string curve name - string Q -- public - string d -- private - */ - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH private key'); - const ecpub = readString(data, data._pos); - if (ecpub === undefined) - return new Error('Malformed OpenSSH private key'); - const ecpriv = readString(data, data._pos); - if (ecpriv === undefined) - return new Error('Malformed OpenSSH private key'); + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); - break; - } - default: - return new Error(`Unsupported OpenSSH private key type: ${type}`); - } + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO + } - const privComment = readString(data, data._pos, true); - if (privComment === undefined) - return new Error('Malformed OpenSSH private key'); + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) - keys.push( - new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, - decrypted) - ); - } - let cnt = 0; - for (i = data._pos; i < data.length; ++i) { - if (data[i] !== (++cnt % 255)) - return new Error('Malformed OpenSSH private key'); - } + // 17. Return fetchParam's controller + return fetchParams.controller +} - return keys; +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only') } -} + // 4. Run report Content Security Policy violations for request. + // TODO -function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Old_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; - OpenSSH_Old_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let privBlob = Buffer.from(m[3], 'base64'); - let headers = m[2]; - let decrypted = false; - if (headers !== undefined) { - // encrypted key - headers = headers.split(/\r\n|\n/g); - for (let i = 0; i < headers.length; ++i) { - const header = headers[i]; - let sepIdx = header.indexOf(':'); - if (header.slice(0, sepIdx) === 'DEK-Info') { - const val = header.slice(sepIdx + 2); - sepIdx = val.indexOf(','); - if (sepIdx === -1) - continue; - const cipherName = val.slice(0, sepIdx).toLowerCase(); - if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const encInfo = CIPHER_INFO_OPENSSL[cipherName]; - if (!encInfo) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); - if (cipherIV.length !== encInfo.ivLen) - return new Error('Malformed encrypted OpenSSH private key'); - if (!passphrase) { - return new Error( - 'Encrypted OpenSSH private key detected, but no passphrase given' - ); - } - const ivSlice = bufferSlice(cipherIV, 0, 8); - let cipherKey = createHash('md5') - .update(passphrase) - .update(ivSlice) - .digest(); - while (cipherKey.length < encInfo.keyLen) { - cipherKey = combineBuffers( - cipherKey, - createHash('md5') - .update(cipherKey) - .update(passphrase) - .update(ivSlice) - .digest() - ); - } - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - decrypted = true; - } catch (ex) { - return ex; - } - } + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request) + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) } - } - let type; - let privPEM; - let pubPEM; - let pubSSH; - let algo; - let reader; - let errMsg = 'Malformed OpenSSH private key'; - if (decrypted) - errMsg += '. Bad passphrase?'; - switch (m[1]) { - case 'RSA': - type = 'ssh-rsa'; - privPEM = makePEM('RSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const n = reader.readString(Ber.Integer, true); - if (n === null) - return new Error(errMsg); - const e = reader.readString(Ber.Integer, true); - if (e === null) - return new Error(errMsg); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'DSA': - type = 'ssh-dss'; - privPEM = makePEM('DSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const p = reader.readString(Ber.Integer, true); - if (p === null) - return new Error(errMsg); - const q = reader.readString(Ber.Integer, true); - if (q === null) - return new Error(errMsg); - const g = reader.readString(Ber.Integer, true); - if (g === null) - return new Error(errMsg); - const y = reader.readString(Ber.Integer, true); - if (y === null) - return new Error(errMsg); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'EC': - let ecSSLName; - let ecPriv; - let ecOID; - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - ecPriv = reader.readString(Ber.OctetString, true); - reader.readByte(); // Skip "complex" context type byte - const offset = reader.readLength(); // Skip context length - if (offset !== null) { - reader._offset = offset; - ecOID = reader.readOID(); - if (ecOID === null) - return new Error(errMsg); - switch (ecOID) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - ecSSLName = 'prime256v1'; - type = 'ecdsa-sha2-nistp256'; - algo = 'sha256'; - break; - case '1.3.132.0.34': - // secp384r1 - ecSSLName = 'secp384r1'; - type = 'ecdsa-sha2-nistp384'; - algo = 'sha384'; - break; - case '1.3.132.0.35': - // secp521r1 - ecSSLName = 'secp521r1'; - type = 'ecdsa-sha2-nistp521'; - algo = 'sha512'; - break; - default: - return new Error(`Unsupported private key EC OID: ${ecOID}`); - } - } else { - return new Error(errMsg); - } - } catch { - return new Error(errMsg); + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } + + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) } - privPEM = makePEM('EC PRIVATE', privBlob); - const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); - pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); - pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); - break; + + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' + + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' + + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range') + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return } - return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, - decrypted); - }; -} + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return + } + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] -function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } } -PPK_Private.prototype = BaseKey; -{ - const EMPTY_PASSPHRASE = Buffer.alloc(0); - const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - const PPK_PP1 = Buffer.from([0, 0, 0, 0]); - const PPK_PP2 = Buffer.from([0, 0, 0, 1]); - const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; - PPK_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = key type - // m[2] = encryption type - // m[3] = comment - // m[4] = base64-encoded public key data: - // for "ssh-rsa": - // string "ssh-rsa" - // mpint e (public exponent) - // mpint n (modulus) - // for "ssh-dss": - // string "ssh-dss" - // mpint p (modulus) - // mpint q (prime) - // mpint g (base number) - // mpint y (public key parameter: g^x mod p) - // m[5] = base64-encoded private key data: - // for "ssh-rsa": - // mpint d (private exponent) - // mpint p (prime 1) - // mpint q (prime 2) - // mpint iqmp ([inverse of q] mod p) - // for "ssh-dss": - // mpint x (private key parameter) - // m[6] = SHA1 HMAC over: - // string name of algorithm ("ssh-dss", "ssh-rsa") - // string encryption type - // string comment - // string public key data - // string private-plaintext (including the final padding) - const cipherName = m[2]; - const encrypted = (cipherName !== 'none'); - if (encrypted && !passphrase) { - return new Error( - 'Encrypted PPK private key detected, but no passphrase given' - ); + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = (__nccwpck_require__(4300).resolveObjectURL) + } - let privBlob = Buffer.from(m[5], 'base64'); + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) - if (encrypted) { - const encInfo = CIPHER_INFO[cipherName]; - let cipherKey = combineBuffers( - createHash('sha1').update(PPK_PP1).update(passphrase).digest(), - createHash('sha1').update(PPK_PP2).update(passphrase).digest() - ); - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - PPK_IV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } - } - const type = m[1]; - const comment = m[3]; - const pubBlob = Buffer.from(m[4], 'base64'); + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) - const mac = m[6]; - const typeLen = type.length; - const cipherNameLen = cipherName.length; - const commentLen = Buffer.byteLength(comment); - const pubLen = pubBlob.length; - const privLen = privBlob.length; - const macData = Buffer.allocUnsafe(4 + typeLen - + 4 + cipherNameLen - + 4 + commentLen - + 4 + pubLen - + 4 + privLen); - let p = 0; + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { + return Promise.resolve(makeNetworkError('invalid method')) + } - writeUInt32BE(macData, typeLen, p); - macData.utf8Write(type, p += 4, typeLen); - writeUInt32BE(macData, cipherNameLen, p += typeLen); - macData.utf8Write(cipherName, p += 4, cipherNameLen); - writeUInt32BE(macData, commentLen, p += cipherNameLen); - macData.utf8Write(comment, p += 4, commentLen); - writeUInt32BE(macData, pubLen, p += commentLen); - macData.set(pubBlob, p += 4); - writeUInt32BE(macData, privLen, p += pubLen); - macData.set(privBlob, p + 4); + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) - if (!passphrase) - passphrase = EMPTY_PASSPHRASE; + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] - const calcMAC = createHmac( - 'sha1', - createHash('sha1') - .update('putty-private-key-file-mac-key') - .update(passphrase) - .digest() - ).update(macData).digest('hex'); + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) - if (calcMAC !== mac) { - if (encrypted) { - return new Error( - 'PPK private key integrity check failed -- bad passphrase?' - ); - } - return new Error('PPK private key integrity check failed'); + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' + + // 7. Return a new response whose status message is `OK`, header list is + // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. + const response = makeResponse({ + statusText: 'OK', + headersList: [ + ['content-length', { name: 'Content-Length', value: length }], + ['content-type', { name: 'Content-Type', value: type }] + ] + }) + + response.body = body + + return Promise.resolve(response) } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) - let pubPEM; - let pubSSH; - let privPEM; - pubBlob._pos = 0; - skipFields(pubBlob, 1); // skip (duplicate) key type - switch (type) { - case 'ssh-rsa': { - const e = readString(pubBlob, pubBlob._pos); - if (e === undefined) - return new Error('Malformed PPK public key'); - const n = readString(pubBlob, pubBlob._pos); - if (n === undefined) - return new Error('Malformed PPK public key'); - const d = readString(privBlob, 0); - if (d === undefined) - return new Error('Malformed PPK private key'); - const p = readString(privBlob, privBlob._pos); - if (p === undefined) - return new Error('Malformed PPK private key'); - const q = readString(privBlob, privBlob._pos); - if (q === undefined) - return new Error('Malformed PPK private key'); - const iqmp = readString(privBlob, privBlob._pos); - if (iqmp === undefined) - return new Error('Malformed PPK private key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - break; + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } - case 'ssh-dss': { - const p = readString(pubBlob, pubBlob._pos); - if (p === undefined) - return new Error('Malformed PPK public key'); - const q = readString(pubBlob, pubBlob._pos); - if (q === undefined) - return new Error('Malformed PPK public key'); - const g = readString(pubBlob, pubBlob._pos); - if (g === undefined) - return new Error('Malformed PPK public key'); - const y = readString(pubBlob, pubBlob._pos); - if (y === undefined) - return new Error('Malformed PPK public key'); - const x = readString(privBlob, 0); - if (x === undefined) - return new Error('Malformed PPK private key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - break; - } + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. - return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', - encrypted); - }; + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } } +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true -function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) + } } -OpenSSH_Public.prototype = BaseKey; -{ - let regexp; - if (eddsaSupported) - regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - else - regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - OpenSSH_Public.parse = (str) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = full type - // m[2] = base type - // m[3] = base64-encoded public key - // m[4] = comment - const fullType = m[1]; - const baseType = m[2]; - const data = Buffer.from(m[3], 'base64'); - const comment = (m[4] || ''); +// https://fetch.spec.whatwg.org/#fetch-finale +function fetchFinale (fetchParams, response) { + // 1. If response is a network error, then: + if (response.type === 'error') { + // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». + response.urlList = [fetchParams.request.urlList[0]] - const type = readString(data, data._pos, true); - if (type === undefined || type.indexOf(baseType) !== 0) - return new Error('Malformed OpenSSH public key'); + // 2. Set response’s timing info to the result of creating an opaque timing + // info for fetchParams’s timing info. + response.timingInfo = createOpaqueTimingInfo({ + startTime: fetchParams.timingInfo.startTime + }) + } - return parseDER(data, baseType, comment, fullType); - }; -} + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + // If fetchParams’s process response end-of-body is not null, + // then queue a fetch task to run fetchParams’s process response + // end-of-body given response with fetchParams’s task destination. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + } -function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -RFC4716_Public.prototype = BaseKey; -{ - const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; - const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; - const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; - const RE_HEADER_ENDS = /\\\r?\n/g; - RFC4716_Public.parse = (str) => { - let m = regexp.exec(str); - if (m === null) - return null; + // 3. If fetchParams’s process response is non-null, then queue a fetch task + // to run fetchParams’s process response given response, with fetchParams’s + // task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => fetchParams.processResponse(response)) + } - const body = m[1]; - let dataStart = 0; - let comment = ''; + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: - while (m = RE_HEADER.exec(body)) { - const headerName = m[1]; - const headerValue = m[2].replace(RE_HEADER_ENDS, ''); - if (headerValue.length > 1024) { - RE_HEADER.lastIndex = 0; - return new Error('Malformed RFC4716 public key'); - } + // 1. Let transformStream be a new a TransformStream. - dataStart = RE_HEADER.lastIndex; + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) + } - if (headerName.toLowerCase() === 'comment') { - comment = headerValue; - if (comment.length > 1 - && comment.charCodeAt(0) === 34/* '"' */ - && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { - comment = comment.slice(1, -1); - } + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm + // and flushAlgorithm set to processResponseEndOfBody. + const transformStream = new TransformStream({ + start () {}, + transform: identityTransformAlgorithm, + flush: processResponseEndOfBody + }, { + size () { + return 1 + } + }, { + size () { + return 1 } + }) + + // 4. Set response’s body to the result of piping response’s body through transformStream. + response.body = { stream: response.body.stream.pipeThrough(transformStream) } + } + + // 6. If fetchParams’s process response consume body is non-null, then: + if (fetchParams.processResponseConsumeBody != null) { + // 1. Let processBody given nullOrBytes be this step: run fetchParams’s + // process response consume body given response and nullOrBytes. + const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) + + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) + + // 3. If response’s body is null, then queue a fetch task to run processBody + // given null, with fetchParams’s task destination. + if (response.body == null) { + queueMicrotask(() => processBody(null)) + } else { + // 4. Otherwise, fully read response’s body given processBody, processBodyError, + // and fetchParams’s task destination. + return fullyReadBody(response.body, processBody, processBodyError) } + return Promise.resolve() + } +} - let data = body.slice(dataStart); - if (!RE_DATA.test(data)) - return new Error('Malformed RFC4716 public key'); +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request - data = Buffer.from(data, 'base64'); + // 2. Let response be null. + let response = null - const type = readString(data, 0, true); - if (type === undefined) - return new Error('Malformed RFC4716 public key'); + // 3. Let actualResponse be null. + let actualResponse = null - let pubPEM = null; - let pubSSH = null; - switch (type) { - case 'ssh-rsa': { - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed RFC4716 public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed RFC4716 public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed RFC4716 public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed RFC4716 public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - break; - } - default: - return new Error('Malformed RFC4716 public key'); + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' } - return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); - }; + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy() + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response } +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request -function parseDER(data, baseType, comment, fullType) { - if (!isSupportedKeyType(baseType)) - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response - let algo; - let oid; - let pubPEM = null; - let pubSSH = null; + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL - switch (baseType) { - case 'ssh-rsa': { - const e = readString(data, data._pos || 0); - if (e === undefined) - return new Error('Malformed OpenSSH public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - algo = 'sha1'; - break; + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response } - case 'ssh-dss': { - const p = readString(data, data._pos || 0); - if (p === undefined) - return new Error('Malformed OpenSSH public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - algo = 'sha1'; - break; + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) } - case 'ssh-ed25519': { - const edpub = readString(data, data._pos || 0); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - algo = null; - break; + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization') + + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null) + request.body = safelyExtractBody(request.body.source)[0] + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent')) { + httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since') || + httpRequest.headersList.contains('if-none-match') || + httpRequest.headersList.contains('if-unmodified-since') || + httpRequest.headersList.contains('if-match') || + httpRequest.headersList.contains('if-range')) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control') + ) { + httpRequest.headersList.append('cache-control', 'max-age=0') + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma')) { + httpRequest.headersList.append('pragma', 'no-cache') } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control')) { + httpRequest.headersList.append('cache-control', 'no-cache') + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range')) { + httpRequest.headersList.append('accept-encoding', 'identity') + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding')) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate') + } + } + + httpRequest.headersList.delete('host') + + // 20. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + // 2. If httpRequest’s header list does not contain `Authorization`, then: + // TODO: credentials + } + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache + } + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.mode === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } + + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err) { + if (!this.destroyed) { + this.destroyed = true + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; + } + } + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } + + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO + + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO + } + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return } - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH public key'); - const ecpub = readString(data, data._pos || 0); - if (ecpub === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - break; + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) } - default: - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) + } + processEndOfBody() + } catch (err) { + processBodyError(err) + } + })() } - return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); -} + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) -function isSupportedKeyType(type) { - switch (type) { - case 'ssh-rsa': - case 'ssh-dss': - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': - return true; - case 'ssh-ed25519': - if (eddsaSupported) - return true; - // FALLTHROUGH - default: - return false; - } -} + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() -function isParsedKey(val) { - if (!val) - return false; - return (typeof val[SYM_DECRYPTED] === 'boolean'); -} + response = makeResponse({ status, statusText, headersList }) + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() -function parseKey(data, passphrase) { - if (isParsedKey(data)) - return data; + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } - let origBuffer; - if (Buffer.isBuffer(data)) { - origBuffer = data; - data = data.utf8Slice(0, data.length).trim(); - } else if (typeof data === 'string') { - data = data.trim(); - } else { - return new Error('Key data must be a Buffer or string'); + return makeNetworkError(err) } - // eslint-disable-next-line eqeqeq - if (passphrase != undefined) { - if (typeof passphrase === 'string') - passphrase = Buffer.from(passphrase); - else if (!Buffer.isBuffer(passphrase)) - return new Error('Passphrase must be a string or Buffer when supplied'); + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() } - let ret; + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason) + } - // First try as printable string format (e.g. PEM) + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO - // Private keys - if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = PPK_Private.parse(data, passphrase)) !== null) - return ret; + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO - // Public keys - if ((ret = OpenSSH_Public.parse(data)) !== null) - return ret; - if ((ret = RFC4716_Public.parse(data)) !== null) - return ret; + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to + // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } - // Finally try as a binary format if we were originally passed binary data - if (origBuffer) { - binaryKeyParser.init(origBuffer, 0); - const type = binaryKeyParser.readString(true); - if (type !== undefined) { - data = binaryKeyParser.readRaw(); - if (data !== undefined) { - ret = parseDER(data, type, '', type); - // Ignore potentially useless errors in case the data was not actually - // in the binary format - if (ret instanceof Error) - ret = null; + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller + }, + async pull (controller) { + await pullAlgorithm(controller) + }, + async cancel (reason) { + await cancelAlgorithm(reason) + } + }, + { + highWaterMark: 0, + size () { + return 1 } } - binaryKeyParser.clear(); - } + ) - if (ret) - return ret; + // 17. Run these steps, but abort when the ongoing fetch is terminated: - return new Error('Unsupported key format'); -} + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream } -module.exports = { - isParsedKey, - isSupportedKeyType, - parseDERKey: (data, type) => parseDER(data, type, '', type), - parseKey, -}; + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO -/***/ }), + // 18. If aborted, then: + // TODO -/***/ 7609: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 19. Run these steps in parallel: -"use strict"; + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.on('terminated', onAborted) + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + let isFailure + try { + const { done, value } = await fetchParams.controller.next() -const assert = __nccwpck_require__(9491); -const { inspect } = __nccwpck_require__(3837); + if (isAborted(fetchParams)) { + break + } -// Only use this for integers! Decimal numbers do not work with this function. -function addNumericalSeparator(val) { - let res = ''; - let i = val.length; - const start = val[0] === '-' ? 1 : 0; - for (; i >= start + 4; i -= 3) - res = `_${val.slice(i - 3, i)}${res}`; - return `${val.slice(0, i)}${res}`; -} + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err -function oneOf(expected, thing) { - assert(typeof thing === 'string', '`thing` has to be of type string'); - if (Array.isArray(expected)) { - const len = expected.length; - assert(len > 0, 'At least one expected value needs to be specified'); - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` - + expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } - return `of ${thing} ${expected[0]}`; - } - return `of ${thing} ${String(expected)}`; -} + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true + } + } + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) -exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { - constructor(message) { - super(); - Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); + finalizeResponse(fetchParams, response) - const suffix = 'This is caused by either a bug in ssh2 ' - + 'or incorrect usage of ssh2 internals.\n' - + 'Please open an issue with this stack trace at ' - + 'https://github.com/mscdex/ssh2/issues\n'; + return + } - this.message = (message === undefined ? suffix : `${message}\n${suffix}`); + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } + } } -}; -const MAX_32BIT_INT = 2 ** 32; -const MAX_32BIT_BIGINT = (() => { - try { - return new Function('return 2n ** 32n')(); - } catch {} -})(); -exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { - constructor(str, range, input, replaceDefaultBoolean) { - super(); - Error.captureStackTrace(this, ERR_OUT_OF_RANGE); + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true - assert(range, 'Missing "range" argument'); - let msg = (replaceDefaultBoolean - ? str - : `The value of "${str}" is out of range.`); - let received; - if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === 'bigint') { - received = String(input); - if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) - received = addNumericalSeparator(received); - received += 'n'; + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } } else { - received = inspect(input); + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } } - msg += ` It must be ${range}. Received ${received}`; - this.message = msg; + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() } -}; -class ERR_INVALID_ARG_TYPE extends TypeError { - constructor(name, expected, actual) { - super(); - Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); + // 20. Return response. + return response - assert(typeof name === 'string', `'name' must be a string`); + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && expected.startsWith('not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, - let msg; - if (name.endsWith(' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = (name.includes('.') ? 'property' : 'argument'); - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller - msg += `. Received type ${typeof actual}`; + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + }, - this.message = msg; - } -} -exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } -exports.validateNumber = function validateNumber(value, name) { - if (typeof value !== 'number') - throw new ERR_INVALID_ARG_TYPE(name, 'number', value); -}; + let codings = [] + let location = '' + + const headers = new Headers() + + // For H2, the headers are a plain JS object + // We distinguish between them and iterate accordingly + if (Array.isArray(headersList)) { + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()) + } else if (key.toLowerCase() === 'location') { + location = val + } + headers[kHeadersList].append(key, val) + } + } else { + const keys = Object.keys(headersList) + for (const key of keys) { + const val = headersList[key] + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() + } else if (key.toLowerCase() === 'location') { + location = val + } -/***/ }), + headers[kHeadersList].append(key, val) + } + } -/***/ 9475: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.body = new Readable({ read: resume }) + + const decoders = [] + + const willFollow = request.redirect === 'follow' && + location && + redirectStatusSet.has(status) + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + for (const coding of codings) { + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'deflate') { + decoders.push(zlib.createInflate()) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress()) + } else { + decoders.length = 0 + break + } + } + } -"use strict"; + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) + return true + }, -const Ber = (__nccwpck_require__(970).Ber); + onData (chunk) { + if (fetchParams.controller.dump) { + return + } -let DISCONNECT_REASON; + // 1. If one or more bytes have been transmitted from response’s + // message body, then: -const FastBuffer = Buffer[Symbol.species]; -const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; + // 1. Let bytes be the transmitted bytes. + const bytes = chunk -function readUInt32BE(buf, offset) { - return (buf[offset++] * 16777216) - + (buf[offset++] * 65536) - + (buf[offset++] * 256) - + buf[offset]; -} + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. -function bufferCopy(src, dest, srcStart, srcEnd, destStart) { - if (!destStart) - destStart = 0; - if (srcEnd > src.length) - srcEnd = src.length; - let nb = srcEnd - srcStart; - const destLeft = (dest.length - destStart); - if (nb > destLeft) - nb = destLeft; - dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), - destStart); - return nb; -} + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength -function bufferSlice(buf, start, end) { - if (end === undefined) - end = buf.length; - return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); -} + // 4. See pullAlgorithm... -function makeBufferParser() { - let pos = 0; - let buffer; + return this.body.push(bytes) + }, - const self = { - init: (buf, start) => { - buffer = buf; - pos = (typeof start === 'number' ? start : 0); - }, - pos: () => pos, - length: () => (buffer ? buffer.length : 0), - avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), - clear: () => { - buffer = undefined; - }, - readUInt32BE: () => { - if (!buffer || pos + 3 >= buffer.length) - return; - return (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - }, - readUInt64BE: (behavior) => { - if (!buffer || pos + 7 >= buffer.length) - return; - switch (behavior) { - case 'always': - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - case 'maybe': - if (buffer[pos] > 0x1F) - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - // FALLTHROUGH - default: - return (buffer[pos++] * 72057594037927940) - + (buffer[pos++] * 281474976710656) - + (buffer[pos++] * 1099511627776) - + (buffer[pos++] * 4294967296) - + (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - } - }, - skip: (n) => { - if (buffer && n > 0) - pos += n; - }, - skipString: () => { - const len = self.readUInt32BE(); - if (len === undefined) - return; - pos += len; - return (pos <= buffer.length ? len : undefined); - }, - readByte: () => { - if (buffer && pos < buffer.length) - return buffer[pos++]; - }, - readBool: () => { - if (buffer && pos < buffer.length) - return !!buffer[pos++]; - }, - readList: () => { - const list = self.readString(true); - if (list === undefined) - return; - return (list ? list.split(',') : []); - }, - readString: (dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } - const len = self.readUInt32BE(); - if (len === undefined) - return; + fetchParams.controller.ended = true - if ((buffer.length - pos) < len - || (typeof maxLen === 'number' && len > maxLen)) { - return; - } + this.body.push(null) + }, - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, pos, pos += len); - return buffer.utf8Slice(pos, pos += len); - } - return bufferSlice(buffer, pos, pos += len); - }, - readRaw: (len) => { - if (!buffer) - return; - if (typeof len !== 'number') - return bufferSlice(buffer, pos, pos += (buffer.length - pos)); - if ((buffer.length - pos) >= len) - return bufferSlice(buffer, pos, pos += len); - }, - }; + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } - return self; -} + this.body?.destroy(error) -function makeError(msg, level, fatal) { - const err = new Error(msg); - if (typeof level === 'boolean') { - fatal = level; - err.level = 'protocol'; - } else { - err.level = level || 'protocol'; + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } + + const headers = new Headers() + + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + + headers[kHeadersList].append(key, val) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }) + + return true + } + } + )) } - err.fatal = !!fatal; - return err; } -function writeUInt32BE(buf, value, offset) { - buf[offset++] = (value >>> 24); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 8); - buf[offset++] = value; - return offset; +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming } -const utilBufferParser = makeBufferParser(); -module.exports = { - bufferCopy, - bufferSlice, - FastBuffer, - bufferFill: (buf, value, start, end) => { - return TypedArrayFill.call(buf, value, start, end); - }, - makeError, - doFatalError: (protocol, msg, level, reason) => { - let err; - if (DISCONNECT_REASON === undefined) - ({ DISCONNECT_REASON } = __nccwpck_require__(9475)); - if (msg instanceof Error) { - // doFatalError(protocol, err[, reason]) - err = msg; - if (typeof level !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - else - reason = level; - } else { - // doFatalError(protocol, msg[, level[, reason]]) - err = makeError(msg, level, true); +/***/ }), + +/***/ 8359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* globals AbortController */ + + + +const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(1472) +const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(554) +const { FinalizationRegistry } = __nccwpck_require__(6436)() +const util = __nccwpck_require__(3983) +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer, + normalizeMethodRecord +} = __nccwpck_require__(2538) +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = __nccwpck_require__(1037) +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { URLSerializer } = __nccwpck_require__(685) +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(2361) + +let TransformStream = globalThis.TransformStream + +const kAbortController = Symbol('abortController') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) + +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kConstruct) { + return } - if (typeof reason !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - protocol.disconnect(reason); - protocol._destruct(); - protocol._onError(err); - return Infinity; - }, - readUInt32BE, - writeUInt32BE, - writeUInt32LE: (buf, value, offset) => { - buf[offset++] = value; - buf[offset++] = (value >>> 8); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 24); - return offset; - }, - makeBufferParser, - bufferParser: makeBufferParser(), - readString: (buffer, start, dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; + + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) + + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) + + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() + } } - if (start === undefined) - start = 0; + // 1. Let request be null. + let request = null - const left = (buffer.length - start); - if (start < 0 || start >= buffer.length || left < 4) - return; + // 2. Let fallbackMode be null. + let fallbackMode = null - const len = readUInt32BE(buffer, start); - if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) - return; + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl - start += 4; - const end = start + len; - buffer._pos = end; + // 4. Let signal be null. + let signal = null - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, start, end); - return buffer.utf8Slice(start, end); - } - return bufferSlice(buffer, start, end); - }, - sigSSHToASN1: (sig, type) => { - switch (type) { - case 'ssh-dss': { - if (sig.length > 40) - return sig; - // Change bare signature r and s values to ASN.1 BER values for OpenSSL - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - let r = sig.slice(0, 20); - let s = sig.slice(20); - if (r[0] & 0x80) { - const rNew = Buffer.allocUnsafe(21); - rNew[0] = 0x00; - r.copy(rNew, 1); - r = rNew; - } else if (r[0] === 0x00 && !(r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] & 0x80) { - const sNew = Buffer.allocUnsafe(21); - sNew[0] = 0x00; - s.copy(sNew, 1); - s = sNew; - } else if (s[0] === 0x00 && !(s[1] & 0x80)) { - s = s.slice(1); - } - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; + // 5. If input is a string, then: + if (typeof input === 'string') { + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - utilBufferParser.init(sig, 0); - const r = utilBufferParser.readString(); - const s = utilBufferParser.readString(); - utilBufferParser.clear(); - if (r === undefined || s === undefined) - return; - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request) + + // 8. Set request to input’s request. + request = input[kState] + + // 9. Set signal to input’s signal. + signal = input[kSignal] + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin + + // 8. Let window be "client". + let window = 'client' + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: this[kRealm].settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) + + const initHasKey = Object.keys(init).length !== 0 + + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' } - default: - return sig; + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false + + // 4. Set request’s origin to "client". + request.origin = 'client' + + // 5. Set request’s referrer to "client" + request.referrer = 'client' + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] } - }, - convertSignature: (signature, keyType) => { - switch (keyType) { - case 'ssh-dss': { - if (signature.length <= 40) - return signature; - // This is a quick and dirty way to get from BER encoded r and s that - // OpenSSL gives us, to just the bare values back to back (40 bytes - // total) like OpenSSH (and possibly others) are expecting - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - let r = asnReader.readString(Ber.Integer, true); - let s = asnReader.readString(Ber.Integer, true); - let rOffset = 0; - let sOffset = 0; - if (r.length < 20) { - const rNew = Buffer.allocUnsafe(20); - rNew.set(r, 1); - r = rNew; - r[0] = 0; - } - if (s.length < 20) { - const sNew = Buffer.allocUnsafe(20); - sNew.set(s, 1); - s = sNew; - s[0] = 0; + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) + ) { + request.referrer = 'client' + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer } - if (r.length > 20 && r[0] === 0) - rOffset = 1; - if (s.length > 20 && s[0] === 0) - sOffset = 1; - const newSig = - Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); - bufferCopy(r, newSig, rOffset, r.length, 0); - bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); - return newSig; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - if (signature[0] === 0) - return signature; - // Convert SSH signature parameters to ASN.1 BER values for OpenSSL - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - const r = asnReader.readString(Ber.Integer, true); - const s = asnReader.readString(Ber.Integer, true); - if (r === null || s === null) - return; - const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); - writeUInt32BE(newSig, r.length, 0); - newSig.set(r, 4); - writeUInt32BE(newSig, s.length, 4 + r.length); - newSig.set(s, 4 + 4 + r.length); - return newSig; } } - return signature; - }, - sendPacket: (proto, packet, bypass) => { - if (!bypass && proto._kexinit !== undefined) { - // We're currently in the middle of a handshake + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } - if (proto._queue === undefined) - proto._queue = []; - proto._queue.push(packet); - proto._debug && proto._debug('Outbound: ... packet queued'); - return false; + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode } - proto._cipher.encrypt(packet); - return true; - }, -}; + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } -/***/ }), + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } -/***/ 6715: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } -"use strict"; + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } -const { kMaxLength } = __nccwpck_require__(4300); -const { - createInflate, - constants: { - DEFLATE, - INFLATE, - Z_DEFAULT_CHUNK, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_MEMLEVEL, - Z_DEFAULT_STRATEGY, - Z_DEFAULT_WINDOWBITS, - Z_PARTIAL_FLUSH, - } -} = __nccwpck_require__(9796); -const ZlibHandle = createInflate()._handle.constructor; + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } -function processCallback() { - throw new Error('Should not get here'); -} + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) + } -function zlibOnError(message, errno, code) { - const self = this._owner; - // There is no way to cleanly recover. - // Continuing only obscures problems. + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } - const error = new Error(message); - error.errno = errno; - error.code = code; - self._err = error; -} + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method -function _close(engine) { - // Caller may invoke .close after a zlib error (which will null _handle). - if (!engine._handle) - return; + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) + } - engine._handle.close(); - engine._handle = null; -} + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } -class Zlib { - constructor(mode) { - const windowBits = Z_DEFAULT_WINDOWBITS; - const level = Z_DEFAULT_COMPRESSION; - const memLevel = Z_DEFAULT_MEMLEVEL; - const strategy = Z_DEFAULT_STRATEGY; - const dictionary = undefined; + // 3. Normalize method. + method = normalizeMethodRecord[method] ?? normalizeMethod(method) - this._err = undefined; - this._writeState = new Uint32Array(2); - this._chunkSize = Z_DEFAULT_CHUNK; - this._maxOutputLength = kMaxLength; - this._outBuffer = Buffer.allocUnsafe(this._chunkSize); - this._outOffset = 0; + // 4. Set request’s method to method. + request.method = method + } - this._handle = new ZlibHandle(mode); - this._handle._owner = this; - this._handle.onerror = zlibOnError; - this._handle.init(windowBits, - level, - memLevel, - strategy, - this._writeState, - processCallback, - dictionary); - } + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } - writeSync(chunk, retChunks) { - const handle = this._handle; - if (!handle) - throw new Error('Invalid Zlib instance'); + // 27. Set this’s request to request. + this[kState] = request - let availInBefore = chunk.length; - let availOutBefore = this._chunkSize - this._outOffset; - let inOff = 0; - let availOutAfter; - let availInAfter; + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController() + this[kSignal] = ac.signal + this[kSignal][kRealm] = this[kRealm] - let buffers; - let nread = 0; - const state = this._writeState; - let buffer = this._outBuffer; - let offset = this._outOffset; - const chunkSize = this._chunkSize; + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } - while (true) { - handle.writeSync(Z_PARTIAL_FLUSH, - chunk, // in - inOff, // in_off - availInBefore, // in_len - buffer, // out - offset, // out_off - availOutBefore); // out_len - if (this._err) - throw this._err; + if (signal.aborted) { + ac.abort(signal.reason) + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac + + const acRef = new WeakRef(ac) + const abort = function () { + const ac = acRef.deref() + if (ac !== undefined) { + ac.abort(this.reason) + } + } - availOutAfter = state[0]; - availInAfter = state[1]; + // Third-party AbortControllers may not work with these. + // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. + try { + // If the max amount of listeners is equal to the default, increase it + // This is only available in node >= v19.9.0 + if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(100, signal) + } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(100, signal) + } + } catch {} - const inDelta = availInBefore - availInAfter; - const have = availOutBefore - availOutAfter; + util.addAbortListener(signal, abort) + requestFinalizer.register(ac, { signal, abort }) + } + } - if (have > 0) { - const out = (offset === 0 && have === buffer.length - ? buffer - : buffer.slice(offset, offset + have)); - offset += have; - if (!buffers) - buffers = out; - else if (buffers.push === undefined) - buffers = [buffers, out]; - else - buffers.push(out); - nread += out.byteLength; + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kHeadersList] = request.headersList + this[kHeaders][kGuard] = 'request' + this[kHeaders][kRealm] = this[kRealm] + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } - if (nread > this._maxOutputLength) { - _close(this); - throw new Error( - `Output length exceeded maximum of ${this._maxOutputLength}` - ); + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' + } + + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = this[kHeaders][kHeadersList] + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) + + // 3. Empty this’s headers’s header list. + headersList.clear() + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const [key, val] of headers) { + headersList.append(key, val) } - } else if (have !== 0) { - throw new Error('have should not go down'); + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers) } + } - // Exhausted the output buffer, or used all the input create a new one. - if (availOutAfter === 0 || offset >= chunkSize) { - availOutBefore = chunkSize; - offset = 0; - buffer = Buffer.allocUnsafe(chunkSize); - } + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null - if (availOutAfter === 0) { - // Not actually done. Need to reprocess. - // Also, update the availInBefore to the availInAfter value, - // so that if we have to hit it a third (fourth, etc.) time, - // it'll have the correct byte counts. - inOff += inDelta; - availInBefore = availInAfter; - } else { - break; + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { + this[kHeaders].append('content-type', contentType) } } - this._outBuffer = buffer; - this._outOffset = offset; + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody - if (nread === 0) - buffers = Buffer.alloc(0); + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } - if (retChunks) { - buffers.totalLen = nread; - return buffers; + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true } - if (buffers.push === undefined) - return buffers; + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody - const output = Buffer.allocUnsafe(nread); - for (let i = 0, p = 0; i < buffers.length; ++i) { - const buf = buffers[i]; - output.set(buf, p); - p += buf.length; + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = (__nccwpck_require__(5356).TransformStream) + } + + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } } - return output; + + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody } -} -class ZlibPacketWriter { - constructor(protocol) { - this.allocStart = 0; - this.allocStartKEX = 0; - this._protocol = protocol; - this._zlib = new Zlib(DEFLATE); + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) + + // The method getter steps are to return this’s request’s method. + return this[kState].method } - cleanup() { - if (this._zlib) - _close(this._zlib); + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) } - alloc(payloadSize, force) { - return Buffer.allocUnsafe(payloadSize); + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] } - finalize(payload, force) { - if (this._protocol._kexinit === undefined || force) { - const output = this._zlib.writeSync(payload, true); - const packet = this._protocol._cipher.allocPacket(output.totalLen); - if (output.push === undefined) { - packet.set(output, 5); - } else { - for (let i = 0, p = 5; i < output.length; ++i) { - const chunk = output[i]; - packet.set(chunk, p); - p += chunk.length; - } - } - return packet; + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) + + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' } - return payload; + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() } -} -class PacketWriter { - constructor(protocol) { - this.allocStart = 5; - this.allocStartKEX = 5; - this._protocol = protocol; + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy } - cleanup() {} + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) - alloc(payloadSize, force) { - if (this._protocol._kexinit === undefined || force) - return this._protocol._cipher.allocPacket(payloadSize); - return Buffer.allocUnsafe(payloadSize); + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode } - finalize(packet, force) { - return packet; + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials } -} -class ZlibPacketReader { - constructor() { - this._zlib = new Zlib(INFLATE); + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) + + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache } - cleanup() { - if (this._zlib) - _close(this._zlib); + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) + + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect } - read(data) { - return this._zlib.writeSync(data, false); + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity } -} -class PacketReader { - cleanup() {} + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) - read(data) { - return data; + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive } -} -module.exports = { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -}; + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } -/***/ }), + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-foward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) -/***/ 2986: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } -"use strict"; -// TODO: -// * convert listenerCount() usage to emit() return value checking? -// * emit error when connection severed early (e.g. before handshake) -// * add '.connected' or similar property to connection objects to allow -// immediate connection status checking + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) + // The signal getter steps are to return this’s signal. + return this[kSignal] + } -const { Server: netServer } = __nccwpck_require__(1808); -const EventEmitter = __nccwpck_require__(2361); -const { listenerCount } = EventEmitter; + get body () { + webidl.brandCheck(this, Request) -const { - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = __nccwpck_require__(6832); -const { init: cryptoInit } = __nccwpck_require__(5708); -const { KexInit } = __nccwpck_require__(4126); -const { parseKey } = __nccwpck_require__(2218); -const Protocol = __nccwpck_require__(9031); -const { SFTP } = __nccwpck_require__(2026); -const { writeUInt32BE } = __nccwpck_require__(9475); + return this[kState].body ? this[kState].body.stream : null + } -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = __nccwpck_require__(3204); + get bodyUsed () { + webidl.brandCheck(this, Request) -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = __nccwpck_require__(834); + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } -const MAX_PENDING_AUTHS = 10; + get duplex () { + webidl.brandCheck(this, Request) -class AuthContext extends EventEmitter { - constructor(protocol, username, service, method, cb) { - super(); + return 'half' + } - this.username = this.user = username; - this.service = service; - this.method = method; - this._initialResponse = false; - this._finalResponse = false; - this._multistep = false; - this._cbfinal = (allowed, methodsLeft, isPartial) => { - if (!this._finalResponse) { - this._finalResponse = true; - cb(this, allowed, methodsLeft, isPartial); - } - }; - this._protocol = protocol; + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + const clonedRequestObject = new Request(kConstruct) + clonedRequestObject[kState] = clonedRequest + clonedRequestObject[kRealm] = this[kRealm] + clonedRequestObject[kHeaders] = new Headers(kConstruct) + clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList + clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + util.addAbortListener( + this.signal, + () => { + ac.abort(this.signal.reason) + } + ) + } + clonedRequestObject[kSignal] = ac.signal + + // 4. Return clonedRequestObject. + return clonedRequestObject } +} - accept() { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(true); +mixinBody(Request) + +function makeRequest (init) { + // https://fetch.spec.whatwg.org/#requests + const request = { + method: 'GET', + localURLsOnly: false, + unsafeRequest: false, + body: null, + client: null, + reservedClient: null, + replacesClientId: '', + window: 'client', + keepalive: false, + serviceWorkers: 'all', + initiator: '', + destination: '', + priority: null, + origin: 'client', + policyContainer: 'client', + referrer: 'client', + referrerPolicy: '', + mode: 'no-cors', + useCORSPreflightFlag: false, + credentials: 'same-origin', + useCredentials: false, + cache: 'default', + redirect: 'follow', + integrity: '', + cryptoGraphicsNonceMetadata: '', + parserMetadata: '', + reloadNavigation: false, + historyNavigation: false, + userActivation: false, + taintedOrigin: false, + redirectCount: 0, + responseTainting: 'basic', + preventNoCacheCacheControlHeaderModification: false, + done: false, + timingAllowFailed: false, + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } + request.url = request.urlList[0] + return request +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body) + } + + // 3. Return newRequest. + return newRequest +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true } - reject(methodsLeft, isPartial) { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(false, methodsLeft, isPartial); +}) + +webidl.converters.Request = webidl.interfaceConverter( + Request +) + +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) } + + if (V instanceof Request) { + return webidl.converters.Request(V) + } + + return webidl.converters.USVString(V) } +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) -class KeyboardAuthContext extends AuthContext { - constructor(protocol, username, service, method, submethods, cb) { - super(protocol, username, service, method, cb); +// https://fetch.spec.whatwg.org/#requestinit +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + } +]) - this._multistep = true; +module.exports = { Request, makeRequest } - this._cb = undefined; - this._onInfoResponse = (responses) => { - const callback = this._cb; - if (callback) { - this._cb = undefined; - callback(responses); - } - }; - this.submethods = submethods; - this.on('abort', () => { - this._cb && this._cb(new Error('Authentication request aborted')); - }); + +/***/ }), + +/***/ 7823: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { Headers, HeadersList, fill } = __nccwpck_require__(554) +const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(1472) +const util = __nccwpck_require__(3983) +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode +} = __nccwpck_require__(2538) +const { + redirectStatusSet, + nullBodyStatus, + DOMException +} = __nccwpck_require__(1037) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { FormData } = __nccwpck_require__(2015) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { URLSerializer } = __nccwpck_require__(685) +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { types } = __nccwpck_require__(3837) + +const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(5356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') + +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} } + + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = new Response() + responseObject[kState] = makeNetworkError() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const relevantRealm = { settingsObject: {} } + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'response' + responseObject[kHeaders][kRealm] = relevantRealm + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject } - prompt(prompts, title, instructions, cb) { - if (!Array.isArray(prompts)) - prompts = [ prompts ]; + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + const relevantRealm = { settingsObject: {} } - if (typeof title === 'function') { - cb = title; - title = instructions = undefined; - } else if (typeof instructions === 'function') { - cb = instructions; - instructions = undefined; - } else if (typeof cb !== 'function') { - cb = undefined; + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) + + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, getGlobalOrigin()) + } catch (err) { + throw Object.assign(new TypeError('Failed to parse URL from ' + url), { + cause: err + }) } - for (let i = 0; i < prompts.length; ++i) { - if (typeof prompts[i] === 'string') { - prompts[i] = { - prompt: prompts[i], - echo: true - }; - } + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError('Invalid status code ' + status) } - this._cb = cb; - this._initialResponse = true; + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm - this._protocol.authInfoReq(title, instructions, prompts); - } -} + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status -class PKAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) + + // 8. Return responseObject. + return responseObject } - accept() { - if (!this.signature) { - this._initialResponse = true; - this._protocol.authPKOK(this.key.algo, this.key.data); - } else { - AuthContext.prototype.accept.call(this); + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) } - } -} -class HostbasedAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); + init = webidl.converters.ResponseInit(init) - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - this.localHostname = pkInfo.localHostname; - this.localUsername = pkInfo.localUsername; - } -} + // TODO + this[kRealm] = { settingsObject: {} } -class PwdAuthContext extends AuthContext { - constructor(protocol, username, service, method, password, cb) { - super(protocol, username, service, method, cb); + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) - this.password = password; - this._changeCb = undefined; + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kGuard] = 'response' + this[kHeaders][kHeadersList] = this[kState].headersList + this[kHeaders][kRealm] = this[kRealm] + + // 3. Let bodyWithType be null. + let bodyWithType = null + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) } - requestChange(prompt, cb) { - if (this._changeCb) - throw new Error('Change request already in progress'); - if (typeof prompt !== 'string') - throw new Error('prompt argument must be a string'); - if (typeof cb !== 'function') - throw new Error('Callback argument must be a function'); - this._changeCb = cb; - this._protocol.authPasswdChg(prompt); + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) + + // The type getter steps are to return this’s response’s type. + return this[kState].type } -} + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) -class Session extends EventEmitter { - constructor(client, info, localChan) { - super(); + const urlList = this[kState].urlList - this.type = 'session'; - this.subtype = undefined; - this.server = true; - this._ending = false; - this._channel = undefined; - this._chanInfo = { - type: 'session', - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - } -} + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + if (url === null) { + return '' + } -class Server extends EventEmitter { - constructor(cfg, listener) { - super(); + return URLSerializer(url, true) + } - if (typeof cfg !== 'object' || cfg === null) - throw new Error('Missing configuration object'); + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) - const hostKeys = Object.create(null); - const hostKeyAlgoOrder = []; + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } - const hostKeys_ = cfg.hostKeys; - if (!Array.isArray(hostKeys_)) - throw new Error('hostKeys must be an array'); + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) - const cfgAlgos = ( - typeof cfg.algorithms === 'object' && cfg.algorithms !== null - ? cfg.algorithms - : {} - ); + // The status getter steps are to return this’s response’s status. + return this[kState].status + } - const hostKeyAlgos = generateAlgorithmList( - cfgAlgos.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY - ); - for (let i = 0; i < hostKeys_.length; ++i) { - let privateKey; - if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') - privateKey = parseKey(hostKeys_[i]); - else - privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) - if (privateKey.getPrivatePEM() === null) - throw new Error('privateKey value contains an invalid private key'); + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } - // Discard key if we already found a key of the same type - if (hostKeyAlgoOrder.includes(privateKey.type)) - continue; + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) - if (privateKey.type === 'ssh-rsa') { - // SSH supports multiple signature hashing algorithms for RSA, so we add - // the algorithms in the desired order - let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); - const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); - const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); - if (sha1Pos === -1) { - // Fall back to giving SHA1 the lowest priority - sha1Pos = Infinity; - } - [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { - if (pos === -1) - return; + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } - let type; - switch (pos) { - case sha1Pos: type = 'ssh-rsa'; break; - case sha256Pos: type = 'rsa-sha2-256'; break; - case sha512Pos: type = 'rsa-sha2-512'; break; - default: return; - } + get body () { + webidl.brandCheck(this, Response) - // Store same RSA key under each hash algorithm name for convenience - hostKeys[type] = privateKey; + return this[kState].body ? this[kState].body.stream : null + } - hostKeyAlgoOrder.push(type); - }); - } else { - hostKeys[privateKey.type] = privateKey; - hostKeyAlgoOrder.push(privateKey.type); - } - } + get bodyUsed () { + webidl.brandCheck(this, Response) - const algorithms = { - kex: generateAlgorithmList(cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX), - serverHostKey: hostKeyAlgoOrder, - cs: { - cipher: generateAlgorithmList( - cfgAlgos.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER - ), - mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), - compress: generateAlgorithmList( - cfgAlgos.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION - ), - lang: [], - }, - sc: undefined, - }; - algorithms.sc = algorithms.cs; + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } - if (typeof listener === 'function') - this.on('connection', listener); + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) - const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); - const offer = new KexInit(algorithms); + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || (this.body && this.body.locked)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } - this._srv = new netServer((socket) => { - if (this._connections >= this.maxConnections) { - socket.destroy(); - return; - } - ++this._connections; - socket.once('close', () => { - --this._connections; - }); + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) - let debug; - if (origDebug) { - // Prepend debug output with a unique identifier in case there are - // multiple clients connected at the same time - const debugPrefix = `[${process.hrtime().join('.')}] `; - debug = (msg) => { - origDebug(`${debugPrefix}${msg}`); - }; - } + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + const clonedResponseObject = new Response() + clonedResponseObject[kState] = clonedResponse + clonedResponseObject[kRealm] = this[kRealm] + clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList + clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] - // eslint-disable-next-line no-use-before-define - new Client(socket, hostKeys, ident, offer, debug, this, cfg); - }).on('error', (err) => { - this.emit('error', err); - }).on('listening', () => { - this.emit('listening'); - }).on('close', () => { - this.emit('close'); - }); - this._connections = 0; - this.maxConnections = Infinity; + return clonedResponseObject } +} - injectSocket(socket) { - this._srv.emit('connection', socket); - } +mixinBody(Response) - listen(...args) { - this._srv.listen(...args); - return this; +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true } +}) - address() { - return this._srv.address(); - } +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) - getConnections(cb) { - this._srv.getConnections(cb); - return this; +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) } - close(cb) { - this._srv.close(cb); - return this; - } + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) - ref() { - this._srv.ref(); - return this; + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body) } - unref() { - this._srv.unref(); - return this; - } + // 4. Return newResponse. + return newResponse } -Server.KEEPALIVE_CLIENT_INTERVAL = 15000; -Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList(), + urlList: init.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) +} -class Client extends EventEmitter { - constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { - super(); +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } - let exchanges = 0; - let acceptedAuthSvc = false; - let pendingAuths = []; - let authCtx; - let kaTimer; - let onPacket; - const unsentGlobalRequestsReplies = []; - this._sock = socket; - this._chanMgr = new ChannelManager(this); - this._debug = debug; - this.noMoreSessions = false; - this.authenticated = false; + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} - // Silence pre-header errors - function onClientPreHeaderError(err) {} - this.on('error', onClientPreHeaderError); +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from client: ${JSON.stringify(msg)}`); - }); + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} - const kaIntvl = ( - typeof srvCfg.keepaliveInterval === 'number' - && isFinite(srvCfg.keepaliveInterval) - && srvCfg.keepaliveInterval > 0 - ? srvCfg.keepaliveInterval - : ( - typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) - && Server.KEEPALIVE_CLIENT_INTERVAL > 0 - ? Server.KEEPALIVE_CLIENT_INTERVAL - : -1 - ) - ); - const kaCountMax = ( - typeof srvCfg.keepaliveCountMax === 'number' - && isFinite(srvCfg.keepaliveCountMax) - && srvCfg.keepaliveCountMax >= 0 - ? srvCfg.keepaliveCountMax - : ( - typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) - && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 - ? Server.KEEPALIVE_CLIENT_COUNT_MAX - : -1 - ) - ); - let kaCurCount = 0; - if (kaIntvl !== -1 && kaCountMax !== -1) { - this.once('ready', () => { - const onClose = () => { - clearInterval(kaTimer); - }; - this.on('close', onClose).on('end', onClose); - kaTimer = setInterval(() => { - if (++kaCurCount > kaCountMax) { - clearInterval(kaTimer); - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - this.end(); - } else { - // XXX: if the server ever starts sending real global requests to - // the client, we will need to add a dummy callback here to - // keep the correct reply order - proto.ping(); - } - }, kaIntvl); - }); - // TODO: re-verify keepalive behavior with OpenSSH - onPacket = () => { - kaTimer && kaTimer.refresh(); - kaCurCount = 0; - }; - } +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) - const proto = this._protocol = new Protocol({ - server: true, - hostKeys, - ident, - offer, - onPacket, - greeting: srvCfg.greeting, - banner: srvCfg.banner, - onWrite: (data) => { - if (isWritable(socket)) - socket.write(data); - }, - onError: (err) => { - if (!proto._destruct) - socket.removeAllListeners('data'); - this.emit('error', err); - try { - socket.end(); - } catch {} - }, - onHeader: (header) => { - this.removeListener('error', onClientPreHeaderError); + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) +} - const info = { - ip: socket.remoteAddress, - family: socket.remoteFamily, - port: socket.remotePort, - header, - }; - if (!server.emit('connection', this, info)) { - // auto reject - proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); - socket.end(); - return; - } +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - if (++exchanges > 1) - this.emit('rekey'); - this.emit('handshake', negotiated); - }, - debug, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - socket.end(); - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from client + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } - // Do early reject in some cases to prevent wasteful channel - // allocation - if ((info.type === 'session' && this.noMoreSessions) - || !this.authenticated) { - const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - return proto.channelOpenFail(info.sender, reasonCode); - } + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status + } - let localChan = -1; - let reason; - let replied = false; + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText + } - let accept; - const reject = () => { - if (replied) - return; - replied = true; + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kHeaders], init.headers) + } - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: 'Invalid response status code ' + response.status + }) + } - if (localChan !== -1) - this._chanMgr.remove(localChan); - proto.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = this._chanMgr.add(); + // 2. Set response's body to body's body. + response[kState].body = body.body - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (debug) { - debug('Automatic rejection of incoming channel open: ' - + 'no channels available'); - } - } + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('Content-Type')) { + response[kState].headersList.append('content-type', body.type) + } + } +} - return (localChan !== -1); - }; +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) - const data = info.data; - switch (info.type) { - case 'session': - if (listenerCount(this, 'session') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) - const instance = new Session(this, info, localChan); - this._chanMgr.update(localChan, instance); +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } - return instance; - }; + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } - this.emit('session', accept, reject); - return; - } - break; - case 'direct-tcpip': - if (listenerCount(this, 'tcpip') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; + if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { + return webidl.converters.BufferSource(V) + } - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) + } + + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) + } - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); + return webidl.converters.DOMString(V) +} - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) + } - return stream; - }; + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } - this.emit('tcpip', accept, reject, data); - return; - } - break; - case 'direct-streamlocal@openssh.com': - if (listenerCount(this, 'openssh.streamlocal') - && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; + return webidl.converters.XMLHttpRequestBodyInit(V) +} - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); +module.exports = { + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse +} - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - return stream; - }; +/***/ }), - this.emit('openssh.streamlocal', accept, reject, data); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (debug) { - debug('Automatic rejection of unsupported incoming channel open' - + ` type: ${info.type}`); - } - } +/***/ 5861: +/***/ ((module) => { - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (debug) { - debug('Automatic rejection of unexpected incoming channel open' - + ` for: ${info.type}`); - } - } +"use strict"; - reject(); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - const chanInfo = { - type: channel.type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') +} - const instance = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +/***/ }), - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } +/***/ 2538: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; +"use strict"; - channel.incoming.window -= data.length; - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(1037) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { performance } = __nccwpck_require__(4074) +const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3983) +const assert = __nccwpck_require__(9491) +const { isUint8Array } = __nccwpck_require__(9830) - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - // NOOP -- should not be sent by client - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +let supportedHashes = [] - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; +try { + crypto = __nccwpck_require__(6113) + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) +/* c8 ignore next 3 */ +} catch { +} - if (channel._waitWindow) { - channel._waitWindow = false; +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null + } - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location') - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + location = new URL(location, responseURL(response)) + } - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const session = this._chanMgr.get(recipient); - if (typeof session !== 'object' || session === null) - return; + // 5. Return location. + return location +} - let replied = false; - let accept; - let reject; +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} - if (session.constructor !== Session) { - // normal Channel instance - if (wantReply) - proto.channelFailure(session.outgoing.id); - return; - } +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) - if (wantReply) { - // "real session" requests will have custom accept behaviors - if (type !== 'shell' - && type !== 'exec' - && type !== 'subsystem') { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' + } - proto.channelSuccess(session._chanInfo.outgoing.id); - }; - } + // 3. Return allowed. + return 'allowed' +} - reject = () => { - if (replied || session._ending || session._channel) - return; - replied = true; +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} - proto.channelFailure(session._chanInfo.outgoing.id); - }; - } +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true +} - if (session._ending) { - reject && reject(); - return; - } +/** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + */ +function isTokenCharCode (c) { + switch (c) { + case 0x22: + case 0x28: + case 0x29: + case 0x2c: + case 0x2f: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x7b: + case 0x7d: + // DQUOTE and "(),/:;<=>?@[\]{}" + return false + default: + // VCHAR %x21-7E + return c >= 0x21 && c <= 0x7e + } +} - switch (type) { - // "pre-real session start" requests - case 'env': - if (listenerCount(session, 'env')) { - session.emit('env', accept, reject, { - key: data.name, - val: data.value - }); - return; - } - break; - case 'pty-req': - if (listenerCount(session, 'pty')) { - session.emit('pty', accept, reject, data); - return; - } - break; - case 'window-change': - if (listenerCount(session, 'window-change')) - session.emit('window-change', accept, reject, data); - else - reject && reject(); - break; - case 'x11-req': - if (listenerCount(session, 'x11')) { - session.emit('x11', accept, reject, data); - return; - } - break; - // "post-real session start" requests - case 'signal': - if (listenerCount(session, 'signal')) { - session.emit('signal', accept, reject, { - name: data - }); - return; - } - break; - // XXX: is `auth-agent-req@openssh.com` really "post-real session - // start"? - case 'auth-agent-req@openssh.com': - if (listenerCount(session, 'auth-agent')) { - session.emit('auth-agent', accept, reject); - return; - } - break; - // "real session start" requests - case 'shell': - if (listenerCount(session, 'shell')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; +/** + * @param {string} characters + */ +function isValidHTTPToken (characters) { + if (characters.length === 0) { + return false + } + for (let i = 0; i < characters.length; ++i) { + if (!isTokenCharCode(characters.charCodeAt(i))) { + return false + } + } + return true +} - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); +/** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ +function isValidHeaderName (potentialValue) { + return isValidHTTPToken(potentialValue) +} - const channel = new Channel( - this, session._chanInfo, { server: true } - ); +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + if ( + potentialValue.startsWith('\t') || + potentialValue.startsWith(' ') || + potentialValue.endsWith('\t') || + potentialValue.endsWith(' ') + ) { + return false + } - channel.subtype = session.subtype = type; - session._channel = channel; + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false + } - return channel; - }; + return true +} - session.emit('shell', accept, reject); - return; - } - break; - case 'exec': - if (listenerCount(session, 'exec')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; +// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = '' + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.has(token)) { + policy = token + break + } + } + } - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} - const channel = new Channel( - this, session._chanInfo, { server: true } - ); +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} - channel.subtype = session.subtype = type; - session._channel = channel; +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} - return channel; - }; +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} - session.emit('exec', accept, reject, { - command: data - }); - return; - } - break; - case 'subsystem': { - let useSFTP = (data === 'sftp'); - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header - let instance; - if (useSFTP) { - instance = new SFTP(this, session._chanInfo, { - server: true, - debug, - }); - } else { - instance = new Channel( - this, session._chanInfo, { server: true } - ); - instance.subtype = - session.subtype = `${type}:${data}`; - } - session._channel = instance; + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO - return instance; - }; + // 2. Let header be a Structured Header whose value is a token. + let header = null - if (data === 'sftp') { - if (listenerCount(session, 'sftp')) { - session.emit('sftp', accept, reject); - return; - } - useSFTP = false; - } - if (listenerCount(session, 'subsystem')) { - session.emit('subsystem', accept, reject, { - name: data - }); - return; - } - break; - } - } - debug && debug( - `Automatic rejection of incoming channel request: ${type}` - ); - reject && reject(); - }, - CHANNEL_EOF: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + // 3. Set header’s value to r’s mode. + header = httpRequest.mode - if (channel.constructor === Session) { - if (!channel._ending) { - channel._ending = true; - channel.emit('eof'); - channel.emit('end'); - } - channel = channel._channel; - if (!channel) - return; - } + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header) - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO - if (channel.readable) - channel.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} - if (channel.constructor === Session) { - channel._ending = true; - channel.emit('close'); - channel = channel._channel; - if (!channel) - return; - } +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. + let serializedOrigin = request.origin - onCHANNEL_CLOSE(this, recipient, channel); - }, - // Begin service/auth-related ========================================== - SERVICE_REQUEST: (p, service) => { - if (exchanges === 0 - || acceptedAuthSvc - || this.authenticated - || service !== 'ssh-userauth') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + if (serializedOrigin) { + request.headersList.append('origin', serializedOrigin) + } - acceptedAuthSvc = true; - proto.serviceAccept(service); - }, - USERAUTH_REQUEST: (p, username, service, method, methodData) => { - if (exchanges === 0 - || this.authenticated - || (authCtx - && (authCtx.username !== username - || authCtx.service !== service)) - // TODO: support hostbased auth - || (method !== 'password' - && method !== 'publickey' - && method !== 'hostbased' - && method !== 'keyboard-interactive' - && method !== 'none') - || pendingAuths.length === MAX_PENDING_AUTHS) { - proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); - socket.end(); - return; - } else if (service !== 'ssh-connection') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } - let ctx; - switch (method) { - case 'keyboard-interactive': - ctx = new KeyboardAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'publickey': - ctx = new PKAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'hostbased': - ctx = new HostbasedAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'password': - if (authCtx - && authCtx instanceof PwdAuthContext - && authCtx._changeCb) { - const cb = authCtx._changeCb; - authCtx._changeCb = undefined; - cb(methodData.newPassword); - return; - } - ctx = new PwdAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'none': - ctx = new AuthContext(proto, username, service, method, - onAuthDecide); - break; - } + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin) + } + } +} - if (authCtx) { - if (!authCtx._initialResponse) { - return pendingAuths.push(ctx); - } else if (authCtx._multistep && !authCtx._finalResponse) { - // RFC 4252 says to silently abort the current auth request if a - // new auth request comes in before the final response from an - // auth method that requires additional request/response exchanges - // -- this means keyboard-interactive for now ... - authCtx._cleanup && authCtx._cleanup(); - authCtx.emit('abort'); - } - } +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} - authCtx = ctx; +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } +} - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - }, - USERAUTH_INFO_RESPONSE: (p, responses) => { - if (authCtx && authCtx instanceof KeyboardAuthContext) - authCtx._onInfoResponse(responses); - }, - // End service/auth-related ============================================ - GLOBAL_REQUEST: (p, name, wantReply, data) => { - const reply = { - type: null, - buf: null - }; +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} - function setReply(type, buf) { - reply.type = type; - reply.buf = buf; - sendReplies(); - } +// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer +function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy - if (wantReply) - unsentGlobalRequestsReplies.push(reply); + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) - if ((name === 'tcpip-forward' - || name === 'cancel-tcpip-forward' - || name === 'no-more-sessions@openssh.com' - || name === 'streamlocal-forward@openssh.com' - || name === 'cancel-streamlocal-forward@openssh.com') - && listenerCount(this, 'request') - && this.authenticated) { - let accept; - let reject; + // 2. Let environment be request’s client. - if (wantReply) { - let replied = false; - accept = (chosenPort) => { - if (replied) - return; - replied = true; - let bufPort; - if (name === 'tcpip-forward' - && data.bindPort === 0 - && typeof chosenPort === 'number') { - bufPort = Buffer.allocUnsafe(4); - writeUInt32BE(bufPort, chosenPort, 0); - } - setReply('SUCCESS', bufPort); - }; - reject = () => { - if (replied) - return; - replied = true; - setReply('FAILURE'); - }; - } + let referrerSource = null - if (name === 'no-more-sessions@openssh.com') { - this.noMoreSessions = true; - accept && accept(); - return; - } + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. - this.emit('request', accept, reject, name, data); - } else if (wantReply) { - setReply('FAILURE'); - } - }, - }, - }); + const globalOrigin = getGlobalOrigin() - socket.pause(); - cryptoInit.then(() => { - proto.start(); - socket.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - } - }); - socket.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - }); - socket.on('error', (err) => { - err.level = 'socket'; - this.emit('error', err); - }).once('end', () => { - debug && debug('Socket ended'); - proto.cleanup(); - this.emit('end'); - }).once('close', () => { - debug && debug('Socket closed'); - proto.cleanup(); - this.emit('close'); + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } - const err = new Error('No response from server'); + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } - // Simulate error for pending channels and close any open channels - this._chanMgr.cleanup(err); - }); + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) - const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { - if (authCtx === ctx && !this.authenticated) { - if (allowed) { - authCtx = undefined; - this.authenticated = true; - proto.authSuccess(); - pendingAuths = []; - this.emit('ready'); - } else { - proto.authFailure(methodsLeft, isPartial); - if (pendingAuths.length) { - authCtx = pendingAuths.pop(); - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - } - } + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL } - }; - function sendReplies() { - while (unsentGlobalRequestsReplies.length > 0 - && unsentGlobalRequestsReplies[0].type) { - const reply = unsentGlobalRequestsReplies.shift(); - if (reply.type === 'SUCCESS') - proto.requestSuccess(reply.buf); - if (reply.type === 'FAILURE') - proto.requestFailure(); + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' } + + // 3. Return referrerOrigin. + return referrerOrigin } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin } +} - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ +function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL) + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' } - x11(originAddr, originPort, cb) { - const opts = { originAddr, originPort }; - openChannel(this, 'x11', opts, cb); - return this; + // 3. Set url’s username to the empty string. + url.username = '' + + // 4. Set url’s password to the empty string. + url.password = '' + + // 5. Set url’s fragment to null. + url.hash = '' + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' + + // 2. Set url’s query to null. + url.search = '' } - forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { - const opts = { boundAddr, boundPort, remoteAddr, remotePort }; - openChannel(this, 'forwarded-tcpip', opts, cb); - return this; + // 7. Return url. + return url +} + +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false } - openssh_forwardOutStreamLocal(socketPath, cb) { - const opts = { socketPath }; - openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); - return this; + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true } - rekey(cb) { - let error; + // If scheme is data, return true + if (url.protocol === 'data:') return true - try { - this._protocol.rekey(); - } catch (ex) { - error = ex; - } + // If file, return true + if (url.protocol === 'file:') return true - // TODO: re-throw error if no callback? + return isOriginPotentiallyTrustworthy(url.origin) - if (typeof cb === 'function') { - if (error) - process.nextTick(cb, error); - else - this.once('rekey', cb); + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false + + const originAsURL = new URL(origin) + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false } } +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ +function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } -function openChannel(self, type, opts, cb) { - // Ask the client to open a channel for some purpose (e.g. a forwarded TCP - // connection) - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) - if (typeof opts === 'function') { - cb = opts; - opts = {}; + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true } - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); + // 3. If response is not eligible for integrity validation, return false. + // TODO - if (localChan === -1) { - cb(new Error('No free channels available')); - return; + // 4. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true } - switch (type) { - case 'forwarded-tcpip': - self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'x11': - self._protocol.x11(localChan, initWindow, maxPacket, opts); - break; - case 'forwarded-streamlocal@openssh.com': - self._protocol.openssh_forwardedStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata) + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) + + // 6. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo + + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2) + } else { + actualValue = actualValue.slice(0, -1) + } + } + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { + return true + } } -} -function compareNumbers(a, b) { - return a - b; + // 7. Return false. + return false } -module.exports = Server; -module.exports.IncomingClient = Client; +// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options +// https://www.w3.org/TR/CSP2/#source-list-syntax +// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 +const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = [] + + // 2. Let empty be equal to true. + let empty = true + + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) + + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === undefined + ) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } -/***/ }), + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase() -/***/ 834: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups) + } + } -"use strict"; + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + return result +} -const { SFTP } = __nccwpck_require__(2026); +/** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ +function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm + } + + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i] + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512' + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384' + } + } + return algorithm +} -const MAX_CHANNEL = 2 ** 32 - 1; +function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList + } -function onChannelOpenFailure(self, recipient, info, cb) { - self._chanMgr.remove(recipient); - if (typeof cb !== 'function') - return; + let pos = 0 + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i] + } + } - let err; - if (info instanceof Error) { - err = info; - } else if (typeof info === 'object' && info !== null) { - err = new Error(`(SSH) Channel open failure: ${info.description}`); - err.reason = info.reason; - } else { - err = new Error( - '(SSH) Channel open failure: server closed channel unexpectedly' - ); - err.reason = ''; + metadataList.length = pos + + return metadataList +} + +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * +* @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ +function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false + } + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } } - cb(err); + return true } -function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { - if (typeof channel === 'function') { - // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when - // requesting to open a channel - onChannelOpenFailure(self, recipient, err, channel); - return; +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true } - if (typeof channel !== 'object' || channel === null) - return; + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } - if (channel.incoming && channel.incoming.state === 'closed') - return; + // 3. Return false. + return false +} - self._chanMgr.remove(recipient); +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) - if (channel.server && channel.constructor.name === 'Session') - return; + return { promise, resolve: res, reject: rej } +} - channel.incoming.state = 'closed'; +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} - if (channel.readable) - channel.push(null); - if (channel.server) { - if (channel.stderr.writable) - channel.stderr.end(); - } else if (channel.stderr.readable) { - channel.stderr.push(null); +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +const normalizeMethodRecord = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizeMethodRecord, null) + +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizeMethodRecord[method.toLowerCase()] ?? method +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') } - if (channel.constructor !== SFTP - && (channel.outgoing.state === 'open' - || channel.outgoing.state === 'eof') - && !dead) { - channel.close(); + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result +} + +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {() => unknown[]} iterator + * @param {string} name name of the instance + * @param {'key'|'value'|'key+value'} kind + */ +function makeIterator (iterator, name, kind) { + const object = { + index: 0, + kind, + target: iterator } - if (channel.outgoing.state === 'closing') - channel.outgoing.state = 'closed'; - const readState = channel._readableState; - const writeState = channel._writableState; - if (writeState && !writeState.ending && !writeState.finished && !dead) - channel.end(); + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. - // Take care of any outstanding channel requests - const chanCallbacks = channel._callbacks; - channel._callbacks = []; - for (let i = 0; i < chanCallbacks.length; ++i) - chanCallbacks[i](true); + // 2. Let thisValue be the this value. - if (channel.server) { - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - channel.emit('close'); - } else { - channel.once('end', () => channel.emit('close')); - } - } else { - let doClose; - switch (channel.type) { - case 'direct-streamlocal@openssh.com': - case 'direct-tcpip': - doClose = () => channel.emit('close'); - break; - default: { - // Align more with node child processes, where the close event gets - // the same arguments as the exit event - const exit = channel._exit; - doClose = () => { - if (exit.code === null) - channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); - else - channel.emit('close', exit.code); - }; + // 3. Let object be ? ToObject(thisValue). + + // 4. If object is a platform object, then perform a security + // check, passing: + + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const { index, kind, target } = object + const values = target() + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { value: undefined, done: true } } + + // 11. Let pair be the entry in values at index index. + const pair = values[index] + + // 12. Set object’s index to index + 1. + object.index = index + 1 + + // 13. Return the iterator result for pair and kind. + return iteratorResult(pair, kind) + }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". + [Symbol.toStringTag]: `${name} Iterator` + } + + // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. + Object.setPrototypeOf(i, esIteratorPrototype) + // esIteratorPrototype needs to be the prototype of i + // which is the prototype of an empty object. Yes, it's confusing. + return Object.setPrototypeOf({}, i) +} + +// https://webidl.spec.whatwg.org/#iterator-result +function iteratorResult (pair, kind) { + let result + + // 1. Let result be a value determined by the value of kind: + switch (kind) { + case 'key': { + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = pair[0] + break } - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - doClose(); - } else { - channel.once('end', doClose); + case 'value': { + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = pair[1] + break } - - const errReadState = channel.stderr._readableState; - if (!channel.stderr.readable - || channel.stderr.destroyed - || (errReadState && errReadState.endEmitted)) { - channel.stderr.emit('close'); - } else { - channel.stderr.once('end', () => channel.stderr.emit('close')); + case 'key+value': { + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = pair + break } } -} -class ChannelManager { - constructor(client) { - this._client = client; - this._channels = {}; - this._cur = -1; - this._count = 0; - } - add(val) { - // Attempt to reserve an id + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } +} - let id; - // Optimized paths - if (this._cur < MAX_CHANNEL) { - id = ++this._cur; - } else if (this._count === 0) { - // Revert and reset back to fast path once we no longer have any channels - // open - this._cur = 0; - id = 0; - } else { - // Slower lookup path +/** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +async function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. - // This path is triggered we have opened at least MAX_CHANNEL channels - // while having at least one channel open at any given time, so we have - // to search for a free id. - const channels = this._channels; - for (let i = 0; i < MAX_CHANNEL; ++i) { - if (channels[i] === undefined) { - id = i; - break; - } - } - } + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody - if (id === undefined) - return -1; + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError - this._channels[id] = (val || true); - ++this._count; + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader - return id; + try { + reader = body.stream.getReader() + } catch (e) { + errorSteps(e) + return } - update(id, val) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - if (val && this._channels[id]) - this._channels[id] = val; + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + const result = await readAllBytes(reader) + successSteps(result) + } catch (e) { + errorSteps(e) } - get(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); +} - return this._channels[id]; +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream + +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) } - remove(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - if (this._channels[id]) { - delete this._channels[id]; - if (this._count) - --this._count; - } + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} + +const MAXIMUM_ARGUMENT_LENGTH = 65535 + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {number[]|Uint8Array} input + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + + if (input.length < MAXIMUM_ARGUMENT_LENGTH) { + return String.fromCharCode(...input) } - cleanup(err) { - const channels = this._channels; - this._channels = {}; - this._cur = -1; - this._count = 0; - const chanIDs = Object.keys(channels); - const client = this._client; - for (let i = 0; i < chanIDs.length; ++i) { - const id = +chanIDs[i]; - const channel = channels[id]; - onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); + return input.reduce((previous, current) => previous + String.fromCharCode(current), '') +} + +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed')) { + throw err } } } -const isRegExp = (() => { - const toString = Object.prototype.toString; - return (val) => toString.call(val) === '[object RegExp]'; -})(); +/** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + for (let i = 0; i < input.length; i++) { + assert(input.charCodeAt(i) <= 0xFF) + } -function generateAlgorithmList(algoList, defaultList, supportedList) { - if (Array.isArray(algoList) && algoList.length > 0) { - // Exact list - for (let i = 0; i < algoList.length; ++i) { - if (supportedList.indexOf(algoList[i]) === -1) - throw new Error(`Unsupported algorithm: ${algoList[i]}`); + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} + +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + */ +async function readAllBytes (reader) { + const bytes = [] + let byteLength = 0 + + while (true) { + const { done, value: chunk } = await reader.read() + + if (done) { + // 1. Call successSteps with bytes. + return Buffer.concat(bytes, byteLength) } - return algoList; - } - if (typeof algoList === 'object' && algoList !== null) { - // Operations based on the default list - const keys = Object.keys(algoList); - let list = defaultList; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - let val = algoList[key]; - switch (key) { - case 'append': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const append = val[j]; - if (typeof append === 'string') { - if (!append || list.indexOf(append) !== -1) - continue; - if (supportedList.indexOf(append) === -1) - throw new Error(`Unsupported algorithm: ${append}`); - if (list === defaultList) - list = list.slice(); - list.push(append); - } else if (isRegExp(append)) { - for (let k = 0; k < supportedList.length; ++k) { - const algo = supportedList[k]; - if (append.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.push(algo); - } - } - } - } - } - break; - case 'prepend': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = val.length; j >= 0; --j) { - const prepend = val[j]; - if (typeof prepend === 'string') { - if (!prepend || list.indexOf(prepend) !== -1) - continue; - if (supportedList.indexOf(prepend) === -1) - throw new Error(`Unsupported algorithm: ${prepend}`); - if (list === defaultList) - list = list.slice(); - list.unshift(prepend); - } else if (isRegExp(prepend)) { - for (let k = supportedList.length; k >= 0; --k) { - const algo = supportedList[k]; - if (prepend.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.unshift(algo); - } - } - } - } - } - break; - case 'remove': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const search = val[j]; - if (typeof search === 'string') { - if (!search) - continue; - const idx = list.indexOf(search); - if (idx === -1) - continue; - if (list === defaultList) - list = list.slice(); - list.splice(idx, 1); - } else if (isRegExp(search)) { - for (let k = 0; k < list.length; ++k) { - if (search.test(list[k])) { - if (list === defaultList) - list = list.slice(); - list.splice(k, 1); - --k; - } - } - } - } - } - break; - } + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + throw new TypeError('Received non-Uint8Array chunk') } - return list; + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. } +} - return defaultList; +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} + +/** + * @param {string|URL} url + */ +function urlHasHttpsScheme (url) { + if (typeof url === 'string') { + return url.startsWith('https:') + } + + return url.protocol === 'https:' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'http:' || protocol === 'https:' } +/** + * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. + */ +const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) + module.exports = { - ChannelManager, - generateAlgorithmList, - onChannelOpenFailure, - onCHANNEL_CLOSE, - isWritable: (stream) => { - // XXX: hack to workaround regression in node - // See: https://github.com/nodejs/node/issues/36029 - return (stream - && stream.writable - && stream._readableState - && stream._readableState.ended === false); - }, -}; + isAborted, + isCancelled, + createDeferredPromise, + ReadableStreamFrom, + toUSVString, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + makeIterator, + isValidHeaderName, + isValidHeaderValue, + hasOwn, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + isomorphicDecode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + normalizeMethodRecord, + parseMetadata +} /***/ }), -/***/ 4841: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. +const { types } = __nccwpck_require__(3837) +const { hasOwn, toUSVString } = __nccwpck_require__(2538) -/**/ +/** @type {import('../../types/webidl').Webidl} */ +const webidl = {} +webidl.converters = {} +webidl.util = {} +webidl.errors = {} -var Buffer = (__nccwpck_require__(2279).Buffer); -/**/ +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; +webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of' + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.` + + return webidl.errors.exception({ + header: context.prefix, + message + }) +} + +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I, opts = undefined) { + if (opts?.strict !== false && !(V instanceof I)) { + throw new TypeError('Illegal invocation') + } else { + return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] } -}; +} -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + ...ctx + }) } -}; +} -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) } -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } + + return 'Object' + } } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); } -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { + let upperBound + let lowerBound + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0 + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 } else { - i = 0; + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; -StringDecoder.prototype.end = utf8End; + // 4. Let x be ? ToNumber(V). + let x = Number(V) -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${V} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } + + // 3. Return x. + return x } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) } - return 0; + + // 12. Otherwise, return x. + return x } -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; + + // 3. Otherwise, return r. + return r +} + +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: 'Sequence', + message: `Value of type ${webidl.util.Type(V)} is not an Object.` + }) } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = V?.[Symbol.iterator]?.() + const seq = [] + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: 'Sequence', + message: 'Object is not an iterator.' + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break } + + seq.push(converter(value)) } + + return seq } } -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: 'Record', + message: `Value of type ${webidl.util.Type(O)} is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {} + + if (!types.isProxy(O)) { + // Object.keys only returns enumerable properties + const keys = Object.keys(O) + + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + } + + // 5. Return result. + return result } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; } -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} +webidl.interfaceConverter = function (i) { + return (V, opts = {}) => { + if (opts.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: i.name, + message: `Expected ${V} to be an instance of ${i.name}.` + }) + } -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; + return V + } } -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); +webidl.dictionaryConverter = function (converters) { + return (dictionary) => { + const type = webidl.util.Type(dictionary) + const dict = {} + + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options + + if (required === true) { + if (!hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key] + const hasDefault = hasOwn(options, 'defaultValue') + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value = value ?? defaultValue + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value) + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value } } - return r; + + return dict } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); } -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V + } + + return converter(V) } - return r; } -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, opts = {}) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts.legacyNullToEmptyString) { + return '' } - return buf.toString('base64', i, buf.length - n); + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw new TypeError('Could not convert argument of type symbol to string.') + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) } -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x } -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); +// https://webidl.spec.whatwg.org/#es-USVString +webidl.converters.USVString = toUSVString + +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V) + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x } -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V } -/***/ }), +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed') -/***/ 2279: -/***/ ((module, exports, __nccwpck_require__) => { + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(4300) -var Buffer = buffer.Buffer +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned') -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x } -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer + +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned') + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x } -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x } -SafeBuffer.prototype = Object.create(Buffer.prototype) +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix: `${V}`, + argument: `${V}`, + types: ['ArrayBuffer'] + }) + } -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + // Note: resizable ArrayBuffers are currently a proposal. + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +webidl.converters.TypedArray = function (V, T, opts = {}) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix: `${T.name}`, + argument: `${V}`, + types: [T.name] + }) } - return Buffer(arg, encodingOrOffset, length) + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable array buffers are currently a proposal + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V } -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +webidl.converters.DataView = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: 'DataView', + message: 'Object is not a DataView.' + }) } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) } - return buf + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable ArrayBuffers are currently a proposal + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, opts = {}) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, opts) } - return Buffer(size) -} -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor) } - return buffer.SlowBuffer(size) + + if (types.isDataView(V)) { + return webidl.converters.DataView(V, opts) + } + + throw new TypeError(`Could not convert ${V} to a BufferSource.`) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) + +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) + +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) + +module.exports = { + webidl } /***/ }), -/***/ 9318: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4854: +/***/ ((module) => { "use strict"; -const os = __nccwpck_require__(2037); -const tty = __nccwpck_require__(6224); -const hasFlag = __nccwpck_require__(1621); - -const {env} = process; -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; +/** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ +function getEncoding (label) { + if (!label) { + return 'failure' + } + + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' + } } -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } +module.exports = { + getEncoding } -function translateLevel(level) { - if (level === 0) { - return false; - } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} +/***/ }), -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } +/***/ 1446: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } +"use strict"; - if (hasFlag('color=256')) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = __nccwpck_require__(7530) +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = __nccwpck_require__(9054) +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) - const min = forceColor || 0; +class FileReader extends EventTarget { + constructor () { + super() - if (env.TERM === 'dumb') { - return min; - } + this[kState] = 'empty' + this[kResult] = null + this[kError] = null + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + } + } - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader) - return 1; - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } + blob = webidl.converters.Blob(blob, { strict: false }) - return min; - } + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer') + } - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader) - if (env.COLORTERM === 'truecolor') { - return 3; - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + blob = webidl.converters.Blob(blob, { strict: false }) - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString') + } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader) - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) - if ('COLORTERM' in env) { - return 1; - } + blob = webidl.converters.Blob(blob, { strict: false }) - return min; -} + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding) + } -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); -} + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding) + } -module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader) + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) -/***/ }), + blob = webidl.converters.Blob(blob, { strict: false }) -/***/ 366: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL') + } -var chownr = __nccwpck_require__(9051) -var tar = __nccwpck_require__(2283) -var pump = __nccwpck_require__(8341) -var mkdirp = __nccwpck_require__(7614) -var fs = __nccwpck_require__(7147) -var path = __nccwpck_require__(1017) -var os = __nccwpck_require__(2037) + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null + return + } -var win32 = os.platform() === 'win32' + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done' + this[kResult] = null + } -var noop = function () {} + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true -var echo = function (name) { - return name -} + // 4. Terminate the algorithm for the read method being processed. + // TODO -var normalize = !win32 ? echo : function (name) { - return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_') -} + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) -var statAll = function (fs, stat, cwd, ignore, entries, sort) { - var queue = entries || ['.'] + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) + } + } - return function loop (callback) { - if (!queue.length) return callback() - var next = queue.shift() - var nextAbs = path.join(cwd, next) + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader) - stat(nextAbs, function (err, stat) { - if (err) return callback(err) + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } - if (!stat.isDirectory()) return callback(null, next, stat) + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader) - fs.readdir(nextAbs, function (err, files) { - if (err) return callback(err) + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] + } - if (sort) files.sort() - for (var i = 0; i < files.length; i++) { - if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) - } + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader) - callback(null, next, stat) - }) - }) + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] } -} -var strip = function (map, level) { - return function (header) { - header.name = header.name.split('/').slice(level).join('/') + get onloadend () { + webidl.brandCheck(this, FileReader) - var linkname = header.linkname - if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { - header.linkname = linkname.split('/').slice(level).join('/') + return this[kEvents].loadend + } + + set onloadend (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend) } - return map(header) + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null + } } -} -exports.pack = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} + get onerror () { + webidl.brandCheck(this, FileReader) - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) - var strict = opts.strict !== false - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var pack = opts.pack || tar.pack() - var finish = opts.finish || noop + return this[kEvents].error + } - if (opts.strip) map = strip(map, opts.strip) + set onerror (fn) { + webidl.brandCheck(this, FileReader) - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error) + } + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null + } } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) + + get onloadstart () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadstart } - var onsymlink = function (filename, header) { - xfs.readlink(path.join(cwd, filename), function (err, linkname) { - if (err) return pack.destroy(err) - header.linkname = normalize(linkname) - pack.entry(header, onnextentry) - }) + set onloadstart (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart) + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null + } } - var onstat = function (err, filename, stat) { - if (err) return pack.destroy(err) - if (!filename) { - if (opts.finalize !== false) pack.finalize() - return finish(pack) + get onprogress () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].progress + } + + set onprogress (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) } - if (stat.isSocket()) return onnextentry() // tar does not support sockets... + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null + } + } - var header = { - name: normalize(filename), - mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, - mtime: stat.mtime, - size: stat.size, - type: 'file', - uid: stat.uid, - gid: stat.gid + get onload () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].load + } + + set onload (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) } - if (stat.isDirectory()) { - header.size = 0 - header.type = 'directory' - header = map(header) || header - return pack.entry(header, onnextentry) + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null } + } - if (stat.isSymbolicLink()) { - header.size = 0 - header.type = 'symlink' - header = map(header) || header - return onsymlink(filename, header) + get onabort () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].abort + } + + set onabort (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort) } - // TODO: add fifo etc... + if (typeof fn === 'function') { + this[kEvents].abort = fn + this.addEventListener('abort', fn) + } else { + this[kEvents].abort = null + } + } +} + +// https://w3c.github.io/FileAPI/#dom-filereader-empty +FileReader.EMPTY = FileReader.prototype.EMPTY = 0 +// https://w3c.github.io/FileAPI/#dom-filereader-loading +FileReader.LOADING = FileReader.prototype.LOADING = 1 +// https://w3c.github.io/FileAPI/#dom-filereader-done +FileReader.DONE = FileReader.prototype.DONE = 2 + +Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true + } +}) - header = map(header) || header +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) - if (!stat.isFile()) { - if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) - return onnextentry() +module.exports = { + FileReader +} + + +/***/ }), + +/***/ 5504: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { webidl } = __nccwpck_require__(1744) + +const kState = Symbol('ProgressEvent state') + +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) + + super(type, eventInitDict) + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total } + } - var entry = pack.entry(header, onnextentry) - if (!entry) return + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) - var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header) + return this[kState].lengthComputable + } - rs.on('error', function (err) { // always forward errors on destroy - entry.destroy(err) - }) + get loaded () { + webidl.brandCheck(this, ProgressEvent) - pump(rs, entry) + return this[kState].loaded } - var onnextentry = function (err) { - if (err) return pack.destroy(err) - statNext(onstat) + get total () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].total } +} - onnextentry() +webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +]) - return pack +module.exports = { + ProgressEvent } -var head = function (list) { - return list.length ? list[list.length - 1] : null + +/***/ }), + +/***/ 9054: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') } -var processGetuid = function () { - return process.getuid ? process.getuid() : -1 + +/***/ }), + +/***/ 7530: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = __nccwpck_require__(9054) +const { ProgressEvent } = __nccwpck_require__(5504) +const { getEncoding } = __nccwpck_require__(4854) +const { DOMException } = __nccwpck_require__(1037) +const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(685) +const { types } = __nccwpck_require__(3837) +const { StringDecoder } = __nccwpck_require__(1576) +const { btoa } = __nccwpck_require__(4300) + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false } -var processUmask = function () { - return process.umask ? process.umask() : 0 +/** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ +function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading' + + // 3. Set fr’s result to null. + fr[kResult] = null + + // 4. Set fr’s error to null. + fr[kError] = null + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream() + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader() + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = [] + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr) + }) + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value) + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now() + queueMicrotask(() => { + fireAProgressEvent('progress', fr) + }) + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read() + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName) + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr) + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Set fr’s error to error. + fr[kError] = error + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } + })() } -exports.extract = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} +/** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ +function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }) - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var own = opts.chown !== false && !win32 && processGetuid() === 0 - var extract = opts.extract || tar.extract() - var stack = [] - var now = new Date() - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var strict = opts.strict !== false + reader.dispatchEvent(event) +} - if (opts.strip) map = strip(map, opts.strip) +/** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ +function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) - } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) - } + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:' + + const parsed = parseMIMEType(mimeType || 'application/octet-stream') + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed) + } - var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry - var top - while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() - if (!top) return cb() - xfs.utimes(top[0], now, top[1], cb) - } + dataURL += ';base64,' - var utimes = function (name, header, cb) { - if (opts.utimes === false) return cb() + const decoder = new StringDecoder('latin1') - if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) - if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)) + } - xfs.utimes(name, now, header.mtime, function (err) { - if (err) return cb(err) - utimesParent(name, cb) - }) - } + dataURL += btoa(decoder.end()) - var chperm = function (name, header, cb) { - var link = header.type === 'symlink' + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure' - /* eslint-disable node/no-deprecated-api */ - var chmod = link ? xfs.lchmod : xfs.chmod - var chown = link ? xfs.lchown : xfs.chown - /* eslint-enable node/no-deprecated-api */ + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName) + } - if (!chmod) return cb() + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType) - var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask - chmod(name, mode, function (err) { - if (err) return cb(err) - if (!own) return cb() - if (!chown) return cb() - chown(name, header.uid, header.gid, cb) - }) - } + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')) + } + } - extract.on('entry', function (header, stream, next) { - header = map(header) || header - header.name = normalize(header.name) - var name = path.join(cwd, path.join('/', header.name)) + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8' + } - if (ignore(name, header)) { - stream.resume() - return next() + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes) - var stat = function (err) { - if (err) return next(err) - utimes(name, header, function (err) { - if (err) return next(err) - if (win32) return next() - chperm(name, header, next) - }) + return sequence.buffer } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = '' - var onsymlink = function () { - if (win32) return next() // skip symlinks on win for now before it can be tested - xfs.unlink(name, function () { - xfs.symlink(header.linkname, name, stat) - }) - } + const decoder = new StringDecoder('latin1') - var onlink = function () { - if (win32) return next() // skip links on win for now before it can be tested - xfs.unlink(name, function () { - var srcpath = path.join(cwd, path.join('/', header.linkname)) + for (const chunk of bytes) { + binaryString += decoder.write(chunk) + } - xfs.link(srcpath, name, function (err) { - if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { - stream = xfs.createReadStream(srcpath) - return onfile() - } + binaryString += decoder.end() - stat(err) - }) - }) + return binaryString } + } +} - var onfile = function () { - var ws = xfs.createWriteStream(name) - var rs = mapStream(stream, header) +/** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ +function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue) - ws.on('error', function (err) { // always forward errors on destroy - rs.destroy(err) - }) + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes) - pump(rs, ws, function (err) { - if (err) return next(err) - ws.on('close', stat) - }) - } + let slice = 0 - if (header.type === 'directory') { - stack.push([name, header.mtime]) - return mkdirfix(name, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, stat) - } + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding - var dir = path.dirname(name) + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2 + } - validate(xfs, dir, path.join(cwd, '.'), function (err, valid) { - if (err) return next(err) - if (!valid) return next(new Error(dir + ' is not a valid path')) + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". - mkdirfix(dir, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, function (err) { - if (err) return next(err) + // 4. Return output. - switch (header.type) { - case 'file': return onfile() - case 'link': return onlink() - case 'symlink': return onsymlink() - } + const sliced = bytes.slice(slice) + return new TextDecoder(encoding).decode(sliced) +} - if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) +/** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ +function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue + + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } - stream.resume() - next() - }) - }) - }) + return null +} - if (opts.finish) extract.on('finish', opts.finish) +/** + * @param {Uint8Array[]} sequences + */ +function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0) - return extract -} + let offset = 0 -function validate (fs, name, root, cb) { - if (name === root) return cb(null, true) - fs.lstat(name, function (err, st) { - if (err && err.code !== 'ENOENT') return cb(err) - if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb) - cb(null, false) - }) + return sequences.reduce((a, b) => { + a.set(b, offset) + offset += b.byteLength + return a + }, new Uint8Array(size)) } -function mkdirfix (name, opts, cb) { - mkdirp(name, { fs: opts.fs }, function (err, made) { - if (!err && made && opts.own) { - chownr(made, opts.uid, opts.gid, cb) - } else { - cb(err) - } - }) +module.exports = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent } /***/ }), -/***/ 7882: +/***/ 1892: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(3837) -var bl = __nccwpck_require__(336) -var headers = __nccwpck_require__(8860) +"use strict"; -var Writable = (__nccwpck_require__(1642).Writable) -var PassThrough = (__nccwpck_require__(1642).PassThrough) -var noop = function () {} +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = __nccwpck_require__(8045) +const Agent = __nccwpck_require__(7890) -var overflow = function (size) { - size &= 511 - return size && 512 - size +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) } -var emptyStream = function (self, offset) { - var s = new Source(self, offset) - s.end() - return s +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) } -var mixinPax = function (header, pax) { - if (pax.path) header.name = pax.path - if (pax.linkpath) header.linkname = pax.linkpath - if (pax.size) header.size = parseInt(pax.size, 10) - header.pax = pax - return header +function getGlobalDispatcher () { + return globalThis[globalDispatcher] } -var Source = function (self, offset) { - this._parent = self - this.offset = offset - PassThrough.call(this, { autoDestroy: false }) +module.exports = { + setGlobalDispatcher, + getGlobalDispatcher } -util.inherits(Source, PassThrough) -Source.prototype.destroy = function (err) { - this._parent.destroy(err) -} +/***/ }), -var Extract = function (opts) { - if (!(this instanceof Extract)) return new Extract(opts) - Writable.call(this, opts) +/***/ 6930: +/***/ ((module) => { - opts = opts || {} +"use strict"; - this._offset = 0 - this._buffer = bl() - this._missing = 0 - this._partial = false - this._onparse = noop - this._header = null - this._stream = null - this._overflow = null - this._cb = null - this._locked = false - this._destroyed = false - this._pax = null - this._paxGlobal = null - this._gnuLongPath = null - this._gnuLongLinkPath = null - var self = this - var b = self._buffer +module.exports = class DecoratorHandler { + constructor (handler) { + this.handler = handler + } - var oncontinue = function () { - self._continue() + onConnect (...args) { + return this.handler.onConnect(...args) } - var onunlock = function (err) { - self._locked = false - if (err) return self.destroy(err) - if (!self._stream) oncontinue() + onError (...args) { + return this.handler.onError(...args) } - var onstreamend = function () { - self._stream = null - var drain = overflow(self._header.size) - if (drain) self._parse(drain, ondrain) - else self._parse(512, onheader) - if (!self._locked) oncontinue() + onUpgrade (...args) { + return this.handler.onUpgrade(...args) } - var ondrain = function () { - self._buffer.consume(overflow(self._header.size)) - self._parse(512, onheader) - oncontinue() + onHeaders (...args) { + return this.handler.onHeaders(...args) } - var onpaxglobalheader = function () { - var size = self._header.size - self._paxGlobal = headers.decodePax(b.slice(0, size)) - b.consume(size) - onstreamend() + onData (...args) { + return this.handler.onData(...args) } - var onpaxheader = function () { - var size = self._header.size - self._pax = headers.decodePax(b.slice(0, size)) - if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax) - b.consume(size) - onstreamend() + onComplete (...args) { + return this.handler.onComplete(...args) } - var ongnulongpath = function () { - var size = self._header.size - this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) - b.consume(size) - onstreamend() + onBodySent (...args) { + return this.handler.onBodySent(...args) } +} - var ongnulonglinkpath = function () { - var size = self._header.size - this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) - b.consume(size) - onstreamend() + +/***/ }), + +/***/ 2860: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const util = __nccwpck_require__(3983) +const { kBodyUsed } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const EE = __nccwpck_require__(2361) + +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] + +const kBody = Symbol('body') + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false } - var onheader = function () { - var offset = self._offset - var header - try { - header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat) - } catch (err) { - self.emit('error', err) - } - b.consume(512) + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} - if (!header) { - self._parse(512, onheader) - oncontinue() - return - } - if (header.type === 'gnu-long-path') { - self._parse(header.size, ongnulongpath) - oncontinue() - return - } - if (header.type === 'gnu-long-link-path') { - self._parse(header.size, ongnulonglinkpath) - oncontinue() - return - } - if (header.type === 'pax-global-header') { - self._parse(header.size, onpaxglobalheader) - oncontinue() - return - } - if (header.type === 'pax-header') { - self._parse(header.size, onpaxheader) - oncontinue() - return +class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') } - if (self._gnuLongPath) { - header.name = self._gnuLongPath - self._gnuLongPath = null - } + util.validateHandler(handler, opts.method, opts.upgrade) - if (self._gnuLongLinkPath) { - header.linkname = self._gnuLongLinkPath - self._gnuLongLinkPath = null - } + this.dispatch = dispatch + this.location = null + this.abort = null + this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] - if (self._pax) { - self._header = header = mixinPax(header, self._pax) - self._pax = null + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) } + } - self._locked = true + onConnect (abort) { + this.abort = abort + this.handler.onConnect(abort, { history: this.history }) + } - if (!header.size || header.type === 'directory') { - self._parse(512, onheader) - self.emit('entry', header, emptyStream(self, offset), onunlock) - return + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket) + } + + onError (error) { + this.handler.onError(error) + } + + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers) + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) } - self._stream = new Source(self, offset) + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) + } - self.emit('entry', header, self._stream, onunlock) - self._parse(header.size, onstreamend) - oncontinue() + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.maxRedirections = 0 + this.opts.query = null + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + this.opts.body = null + } } - this._onheader = onheader - this._parse(512, onheader) -} + onData (chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 -util.inherits(Extract, Writable) + TLDR: undici always ignores 3xx response bodies. -Extract.prototype.destroy = function (err) { - if (this._destroyed) return - this._destroyed = true + Redirection is used to serve the requested resource from another URL, so it is assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. - if (err) this.emit('error', err) - this.emit('close') - if (this._stream) this._stream.emit('close') -} + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. -Extract.prototype._parse = function (size, onparse) { - if (this._destroyed) return - this._offset += size - this._missing = size - if (onparse === this._onheader) this._partial = false - this._onparse = onparse -} + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitily chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + return this.handler.onData(chunk) + } + } -Extract.prototype._continue = function () { - if (this._destroyed) return - var cb = this._cb - this._cb = noop - if (this._overflow) this._write(this._overflow, undefined, cb) - else cb() -} + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 -Extract.prototype._write = function (data, enc, cb) { - if (this._destroyed) return + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. - var s = this._stream - var b = this._buffer - var missing = this._missing - if (data.length) this._partial = true + See comment on onData method above for more detailed informations. + */ - // we do not reach end-of-chunk now. just forward it + this.location = null + this.abort = null - if (data.length < missing) { - this._missing -= data.length - this._overflow = null - if (s) return s.write(data, cb) - b.append(data) - return cb() + this.dispatch(this.opts, this) + } else { + this.handler.onComplete(trailers) + } } - // end-of-chunk. the parser should call cb. - - this._cb = cb - this._missing = 0 + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk) + } + } +} - var overflow = null - if (data.length > missing) { - overflow = data.slice(missing) - data = data.slice(0, missing) +function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null } - if (s) s.end(data) - else b.append(data) + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toString().toLowerCase() === 'location') { + return headers[i + 1] + } + } +} - this._overflow = overflow - this._onparse() +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false } -Extract.prototype._final = function (cb) { - if (this._partial) return this.destroy(new Error('Unexpected end of data')) - cb() +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret } -module.exports = Extract +module.exports = RedirectHandler /***/ }), -/***/ 8860: -/***/ ((__unused_webpack_module, exports) => { - -var alloc = Buffer.alloc +/***/ 2286: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var ZEROS = '0000000000000000000' -var SEVENS = '7777777777777777777' -var ZERO_OFFSET = '0'.charCodeAt(0) -var USTAR_MAGIC = Buffer.from('ustar\x00', 'binary') -var USTAR_VER = Buffer.from('00', 'binary') -var GNU_MAGIC = Buffer.from('ustar\x20', 'binary') -var GNU_VER = Buffer.from('\x20\x00', 'binary') -var MASK = parseInt('7777', 8) -var MAGIC_OFFSET = 257 -var VERSION_OFFSET = 263 +const assert = __nccwpck_require__(9491) + +const { kRetryHandlerDefaultRetry } = __nccwpck_require__(2785) +const { RequestRetryError } = __nccwpck_require__(8045) +const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3983) + +function calculateRetryAfterHeader (retryAfter) { + const current = Date.now() + const diff = new Date(retryAfter).getTime() - current + + return diff +} + +class RetryHandler { + constructor (opts, handlers) { + const { retryOptions, ...dispatchOpts } = opts + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes + } = retryOptions ?? {} + + this.dispatch = handlers.dispatch + this.handler = handlers.handler + this.opts = dispatchOpts + this.abort = null + this.aborted = false + this.retryOpts = { + retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1000, // 30s, + timeout: minTimeout ?? 500, // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + 'ECONNRESET', + 'ECONNREFUSED', + 'ENOTFOUND', + 'ENETDOWN', + 'ENETUNREACH', + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'EPIPE' + ] + } + + this.retryCount = 0 + this.start = 0 + this.end = null + this.etag = null + this.resume = null + + // Handle possible onConnect duplication + this.handler.onConnect(reason => { + this.aborted = true + if (this.abort) { + this.abort(reason) + } else { + this.reason = reason + } + }) + } -var clamp = function (index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue - index = ~~index // Coerce to integer. - if (index >= len) return len - if (index >= 0) return index - index += len - if (index >= 0) return index - return 0 -} + onRequestSent () { + if (this.handler.onRequestSent) { + this.handler.onRequestSent() + } + } -var toType = function (flag) { - switch (flag) { - case 0: - return 'file' - case 1: - return 'link' - case 2: - return 'symlink' - case 3: - return 'character-device' - case 4: - return 'block-device' - case 5: - return 'directory' - case 6: - return 'fifo' - case 7: - return 'contiguous-file' - case 72: - return 'pax-header' - case 55: - return 'pax-global-header' - case 27: - return 'gnu-long-link-path' - case 28: - case 30: - return 'gnu-long-path' + onUpgrade (statusCode, headers, socket) { + if (this.handler.onUpgrade) { + this.handler.onUpgrade(statusCode, headers, socket) + } } - return null -} + onConnect (abort) { + if (this.aborted) { + abort(this.reason) + } else { + this.abort = abort + } + } -var toTypeflag = function (flag) { - switch (flag) { - case 'file': - return 0 - case 'link': - return 1 - case 'symlink': - return 2 - case 'character-device': - return 3 - case 'block-device': - return 4 - case 'directory': - return 5 - case 'fifo': - return 6 - case 'contiguous-file': - return 7 - case 'pax-header': - return 72 + onBodySent (chunk) { + if (this.handler.onBodySent) return this.handler.onBodySent(chunk) } - return 0 -} + static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { + const { statusCode, code, headers } = err + const { method, retryOptions } = opts + const { + maxRetries, + timeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions + let { counter, currentTimeout } = state -var indexOf = function (block, num, offset, end) { - for (; offset < end; offset++) { - if (block[offset] === num) return offset - } - return end -} + currentTimeout = + currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout -var cksum = function (block) { - var sum = 8 * 32 - for (var i = 0; i < 148; i++) sum += block[i] - for (var j = 156; j < 512; j++) sum += block[j] - return sum -} + // Any code that is not a Undici's originated and allowed to retry + if ( + code && + code !== 'UND_ERR_REQ_RETRY' && + code !== 'UND_ERR_SOCKET' && + !errorCodes.includes(code) + ) { + cb(err) + return + } -var encodeOct = function (val, n) { - val = val.toString(8) - if (val.length > n) return SEVENS.slice(0, n) + ' ' - else return ZEROS.slice(0, n - val.length) + val + ' ' -} + // If a set of method are provided and the current method is not in the list + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err) + return + } -/* Copied from the node-tar repo and modified to meet - * tar-stream coding standard. - * - * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 - */ -function parse256 (buf) { - // first byte MUST be either 80 or FF - // 80 for positive, FF for 2's comp - var positive - if (buf[0] === 0x80) positive = true - else if (buf[0] === 0xFF) positive = false - else return null + // If a set of status code are provided and the current status code is not in the list + if ( + statusCode != null && + Array.isArray(statusCodes) && + !statusCodes.includes(statusCode) + ) { + cb(err) + return + } - // build up a base-256 tuple from the least sig to the highest - var tuple = [] - for (var i = buf.length - 1; i > 0; i--) { - var byte = buf[i] - if (positive) tuple.push(byte) - else tuple.push(0xFF - byte) + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err) + return + } + + let retryAfterHeader = headers != null && headers['retry-after'] + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader) + retryAfterHeader = isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(retryAfterHeader) + : retryAfterHeader * 1e3 // Retry-After is in seconds + } + + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) + + state.currentTimeout = retryTimeout + + setTimeout(() => cb(null), retryTimeout) } - var sum = 0 - var l = tuple.length - for (i = 0; i < l; i++) { - sum += tuple[i] * Math.pow(256, i) - } + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = parseHeaders(rawHeaders) + + this.retryCount += 1 + + if (statusCode >= 300) { + this.abort( + new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } + + // Checkpoint for resume from where we left it + if (this.resume != null) { + this.resume = null + + if (statusCode !== 206) { + return true + } + + const contentRange = parseRangeHeader(headers['content-range']) + // If no content range + if (!contentRange) { + this.abort( + new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } - return positive ? sum : -1 * sum -} + // Let's start with a weak etag check + if (this.etag != null && this.etag !== headers.etag) { + this.abort( + new RequestRetryError('ETag mismatch', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } -var decodeOct = function (val, offset, length) { - val = val.slice(offset, offset + length) - offset = 0 + const { start, size, end = size } = contentRange - // If prefixed with 0x80 then parse as a base-256 integer - if (val[offset] & 0x80) { - return parse256(val) - } else { - // Older versions of tar can prefix with spaces - while (offset < val.length && val[offset] === 32) offset++ - var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) - while (offset < end && val[offset] === 0) offset++ - if (end === offset) return 0 - return parseInt(val.slice(offset, end).toString(), 8) - } -} + assert(this.start === start, 'content-range mismatch') + assert(this.end == null || this.end === end, 'content-range mismatch') -var decodeStr = function (val, offset, length, encoding) { - return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding) -} + this.resume = resume + return true + } -var addLength = function (str) { - var len = Buffer.byteLength(str) - var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 - if (len + digits >= Math.pow(10, digits)) digits++ + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']) - return (len + digits) + str -} + if (range == null) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } -exports.decodeLongPath = function (buf, encoding) { - return decodeStr(buf, 0, buf.length, encoding) -} + const { start, size, end = size } = range -exports.encodePax = function (opts) { // TODO: encode more stuff in pax - var result = '' - if (opts.name) result += addLength(' path=' + opts.name + '\n') - if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') - var pax = opts.pax - if (pax) { - for (var key in pax) { - result += addLength(' ' + key + '=' + pax[key] + '\n') - } - } - return Buffer.from(result) -} + assert( + start != null && Number.isFinite(start) && this.start !== start, + 'content-range mismatch' + ) + assert(Number.isFinite(start)) + assert( + end != null && Number.isFinite(end) && this.end !== end, + 'invalid content-length' + ) -exports.decodePax = function (buf) { - var result = {} + this.start = start + this.end = end + } - while (buf.length) { - var i = 0 - while (i < buf.length && buf[i] !== 32) i++ - var len = parseInt(buf.slice(0, i).toString(), 10) - if (!len) return result + // We make our best to checkpoint the body for further range headers + if (this.end == null) { + const contentLength = headers['content-length'] + this.end = contentLength != null ? Number(contentLength) : null + } - var b = buf.slice(i + 1, len - 1).toString() - var keyIndex = b.indexOf('=') - if (keyIndex === -1) return result - result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) + assert(Number.isFinite(this.start)) + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) - buf = buf.slice(len) - } + this.resume = resume + this.etag = headers.etag != null ? headers.etag : null - return result -} + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } -exports.encode = function (opts) { - var buf = alloc(512) - var name = opts.name - var prefix = '' + const err = new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount + }) - if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' - if (Buffer.byteLength(name) !== name.length) return null // utf-8 + this.abort(err) - while (Buffer.byteLength(name) > 100) { - var i = name.indexOf('/') - if (i === -1) return null - prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) - name = name.slice(i + 1) + return false } - if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null - if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null + onData (chunk) { + this.start += chunk.length - buf.write(name) - buf.write(encodeOct(opts.mode & MASK, 6), 100) - buf.write(encodeOct(opts.uid, 6), 108) - buf.write(encodeOct(opts.gid, 6), 116) - buf.write(encodeOct(opts.size, 11), 124) - buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) + return this.handler.onData(chunk) + } - buf[156] = ZERO_OFFSET + toTypeflag(opts.type) + onComplete (rawTrailers) { + this.retryCount = 0 + return this.handler.onComplete(rawTrailers) + } - if (opts.linkname) buf.write(opts.linkname, 157) + onError (err) { + if (this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } - USTAR_MAGIC.copy(buf, MAGIC_OFFSET) - USTAR_VER.copy(buf, VERSION_OFFSET) - if (opts.uname) buf.write(opts.uname, 265) - if (opts.gname) buf.write(opts.gname, 297) - buf.write(encodeOct(opts.devmajor || 0, 6), 329) - buf.write(encodeOct(opts.devminor || 0, 6), 337) + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + onRetry.bind(this) + ) - if (prefix) buf.write(prefix, 345) + function onRetry (err) { + if (err != null || this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } - buf.write(encodeOct(cksum(buf), 6), 148) + if (this.start !== 0) { + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + range: `bytes=${this.start}-${this.end ?? ''}` + } + } + } - return buf + try { + this.dispatch(this.opts, this) + } catch (err) { + this.handler.onError(err) + } + } + } } -exports.decode = function (buf, filenameEncoding, allowUnknownFormat) { - var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET +module.exports = RetryHandler - var name = decodeStr(buf, 0, 100, filenameEncoding) - var mode = decodeOct(buf, 100, 8) - var uid = decodeOct(buf, 108, 8) - var gid = decodeOct(buf, 116, 8) - var size = decodeOct(buf, 124, 12) - var mtime = decodeOct(buf, 136, 12) - var type = toType(typeflag) - var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) - var uname = decodeStr(buf, 265, 32) - var gname = decodeStr(buf, 297, 32) - var devmajor = decodeOct(buf, 329, 8) - var devminor = decodeOct(buf, 337, 8) - var c = cksum(buf) +/***/ }), - // checksum is still initial value if header was null. - if (c === 8 * 32) return null +/***/ 8861: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // valid checksum - if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') +"use strict"; - if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { - // ustar (posix) format. - // prepend prefix, if present. - if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name - } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && - GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { - // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and - // multi-volume tarballs. - } else { - if (!allowUnknownFormat) { - throw new Error('Invalid tar header: unknown format.') - } - } - // to support old tar versions that use trailing / to indicate dirs - if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 +const RedirectHandler = __nccwpck_require__(2860) - return { - name, - mode, - uid, - gid, - size, - mtime: new Date(1000 * mtime), - type, - linkname, - uname, - gname, - devmajor, - devminor +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } } } +module.exports = createRedirectInterceptor + /***/ }), -/***/ 2283: +/***/ 953: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.extract = __nccwpck_require__(7882) -exports.pack = __nccwpck_require__(4930) +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = __nccwpck_require__(1891); +// C headers +var ERROR; +(function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; +})(ERROR = exports.ERROR || (exports.ERROR = {})); +var TYPE; +(function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; +})(TYPE = exports.TYPE || (exports.TYPE = {})); +var FLAGS; +(function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; +})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); +var LENIENT_FLAGS; +(function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; +})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); +var METHODS; +(function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; +})(METHODS = exports.METHODS || (exports.METHODS = {})); +exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, +]; +exports.METHODS_ICE = [ + METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, +]; +exports.METHOD_MAP = utils_1.enumToMap(METHODS); +exports.H_METHOD_MAP = {}; +Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } +}); +var FINISH; +(function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; +})(FINISH = exports.FINISH || (exports.FINISH = {})); +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); +// All characters with 0x80 bit set to 1 +for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); +} +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +var HEADER_STATE; +(function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; +})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); +exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, +}; +//# sourceMappingURL=constants.js.map /***/ }), -/***/ 4930: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1145: +/***/ ((module) => { -var constants = __nccwpck_require__(3186) -var eos = __nccwpck_require__(1205) -var inherits = __nccwpck_require__(4124) -var alloc = Buffer.alloc +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkBigGLAYwBjQGOAY8BkAGRAZIBkwGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwHLAcoBuAHJAbkByAG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAQDcAQtBACEQDMYBC0EOIRAMxQELQQ0hEAzEAQtBDyEQDMMBC0EQIRAMwgELQRMhEAzBAQtBFCEQDMABC0EVIRAMvwELQRYhEAy+AQtBFyEQDL0BC0EYIRAMvAELQRkhEAy7AQtBGiEQDLoBC0EbIRAMuQELQRwhEAy4AQtBCCEQDLcBC0EdIRAMtgELQSAhEAy1AQtBHyEQDLQBC0EHIRAMswELQSEhEAyyAQtBIiEQDLEBC0EeIRAMsAELQSMhEAyvAQtBEiEQDK4BC0ERIRAMrQELQSQhEAysAQtBJSEQDKsBC0EmIRAMqgELQSchEAypAQtBwwEhEAyoAQtBKSEQDKcBC0ErIRAMpgELQSwhEAylAQtBLSEQDKQBC0EuIRAMowELQS8hEAyiAQtBxAEhEAyhAQtBMCEQDKABC0E0IRAMnwELQQwhEAyeAQtBMSEQDJ0BC0EyIRAMnAELQTMhEAybAQtBOSEQDJoBC0E1IRAMmQELQcUBIRAMmAELQQshEAyXAQtBOiEQDJYBC0E2IRAMlQELQQohEAyUAQtBNyEQDJMBC0E4IRAMkgELQTwhEAyRAQtBOyEQDJABC0E9IRAMjwELQQkhEAyOAQtBKCEQDI0BC0E+IRAMjAELQT8hEAyLAQtBwAAhEAyKAQtBwQAhEAyJAQtBwgAhEAyIAQtBwwAhEAyHAQtBxAAhEAyGAQtBxQAhEAyFAQtBxgAhEAyEAQtBKiEQDIMBC0HHACEQDIIBC0HIACEQDIEBC0HJACEQDIABC0HKACEQDH8LQcsAIRAMfgtBzQAhEAx9C0HMACEQDHwLQc4AIRAMewtBzwAhEAx6C0HQACEQDHkLQdEAIRAMeAtB0gAhEAx3C0HTACEQDHYLQdQAIRAMdQtB1gAhEAx0C0HVACEQDHMLQQYhEAxyC0HXACEQDHELQQUhEAxwC0HYACEQDG8LQQQhEAxuC0HZACEQDG0LQdoAIRAMbAtB2wAhEAxrC0HcACEQDGoLQQMhEAxpC0HdACEQDGgLQd4AIRAMZwtB3wAhEAxmC0HhACEQDGULQeAAIRAMZAtB4gAhEAxjC0HjACEQDGILQQIhEAxhC0HkACEQDGALQeUAIRAMXwtB5gAhEAxeC0HnACEQDF0LQegAIRAMXAtB6QAhEAxbC0HqACEQDFoLQesAIRAMWQtB7AAhEAxYC0HtACEQDFcLQe4AIRAMVgtB7wAhEAxVC0HwACEQDFQLQfEAIRAMUwtB8gAhEAxSC0HzACEQDFELQfQAIRAMUAtB9QAhEAxPC0H2ACEQDE4LQfcAIRAMTQtB+AAhEAxMC0H5ACEQDEsLQfoAIRAMSgtB+wAhEAxJC0H8ACEQDEgLQf0AIRAMRwtB/gAhEAxGC0H/ACEQDEULQYABIRAMRAtBgQEhEAxDC0GCASEQDEILQYMBIRAMQQtBhAEhEAxAC0GFASEQDD8LQYYBIRAMPgtBhwEhEAw9C0GIASEQDDwLQYkBIRAMOwtBigEhEAw6C0GLASEQDDkLQYwBIRAMOAtBjQEhEAw3C0GOASEQDDYLQY8BIRAMNQtBkAEhEAw0C0GRASEQDDMLQZIBIRAMMgtBkwEhEAwxC0GUASEQDDALQZUBIRAMLwtBlgEhEAwuC0GXASEQDC0LQZgBIRAMLAtBmQEhEAwrC0GaASEQDCoLQZsBIRAMKQtBnAEhEAwoC0GdASEQDCcLQZ4BIRAMJgtBnwEhEAwlC0GgASEQDCQLQaEBIRAMIwtBogEhEAwiC0GjASEQDCELQaQBIRAMIAtBpQEhEAwfC0GmASEQDB4LQacBIRAMHQtBqAEhEAwcC0GpASEQDBsLQaoBIRAMGgtBqwEhEAwZC0GsASEQDBgLQa0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAdUB1gHXAdgB2QHaAdsB3AHdAd4B4AHhAeIB4wHkAeUB5gHnAegB6QHqAesB7AHtAe4B7wHwAfEB8gHzAZkCpAKwAv4C/gILIAEiBCACRw3zAUHdASEQDP8DCyABIhAgAkcN3QFBwwEhEAz+AwsgASIBIAJHDZABQfcAIRAM/QMLIAEiASACRw2GAUHvACEQDPwDCyABIgEgAkcNf0HqACEQDPsDCyABIgEgAkcNe0HoACEQDPoDCyABIgEgAkcNeEHmACEQDPkDCyABIgEgAkcNGkEYIRAM+AMLIAEiASACRw0UQRIhEAz3AwsgASIBIAJHDVlBxQAhEAz2AwsgASIBIAJHDUpBPyEQDPUDCyABIgEgAkcNSEE8IRAM9AMLIAEiASACRw1BQTEhEAzzAwsgAC0ALkEBRg3rAwyHAgsgACABIgEgAhDAgICAAEEBRw3mASAAQgA3AyAM5wELIAAgASIBIAIQtICAgAAiEA3nASABIQEM9QILAkAgASIBIAJHDQBBBiEQDPADCyAAIAFBAWoiASACELuAgIAAIhAN6AEgASEBDDELIABCADcDIEESIRAM1QMLIAEiECACRw0rQR0hEAztAwsCQCABIgEgAkYNACABQQFqIQFBECEQDNQDC0EHIRAM7AMLIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN5QFBCCEQDOsDCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEUIRAM0gMLQQkhEAzqAwsgASEBIAApAyBQDeQBIAEhAQzyAgsCQCABIgEgAkcNAEELIRAM6QMLIAAgAUEBaiIBIAIQtoCAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3mASABIQEMDQsgACABIgEgAhC6gICAACIQDecBIAEhAQzwAgsCQCABIgEgAkcNAEEPIRAM5QMLIAEtAAAiEEE7Rg0IIBBBDUcN6AEgAUEBaiEBDO8CCyAAIAEiASACELqAgIAAIhAN6AEgASEBDPICCwNAAkAgAS0AAEHwtYCAAGotAAAiEEEBRg0AIBBBAkcN6wEgACgCBCEQIABBADYCBCAAIBAgAUEBaiIBELmAgIAAIhAN6gEgASEBDPQCCyABQQFqIgEgAkcNAAtBEiEQDOIDCyAAIAEiASACELqAgIAAIhAN6QEgASEBDAoLIAEiASACRw0GQRshEAzgAwsCQCABIgEgAkcNAEEWIRAM4AMLIABBioCAgAA2AgggACABNgIEIAAgASACELiAgIAAIhAN6gEgASEBQSAhEAzGAwsCQCABIgEgAkYNAANAAkAgAS0AAEHwt4CAAGotAAAiEEECRg0AAkAgEEF/ag4E5QHsAQDrAewBCyABQQFqIQFBCCEQDMgDCyABQQFqIgEgAkcNAAtBFSEQDN8DC0EVIRAM3gMLA0ACQCABLQAAQfC5gIAAai0AACIQQQJGDQAgEEF/ag4E3gHsAeAB6wHsAQsgAUEBaiIBIAJHDQALQRghEAzdAwsCQCABIgEgAkYNACAAQYuAgIAANgIIIAAgATYCBCABIQFBByEQDMQDC0EZIRAM3AMLIAFBAWohAQwCCwJAIAEiFCACRw0AQRohEAzbAwsgFCEBAkAgFC0AAEFzag4U3QLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gIA7gILQQAhECAAQQA2AhwgAEGvi4CAADYCECAAQQI2AgwgACAUQQFqNgIUDNoDCwJAIAEtAAAiEEE7Rg0AIBBBDUcN6AEgAUEBaiEBDOUCCyABQQFqIQELQSIhEAy/AwsCQCABIhAgAkcNAEEcIRAM2AMLQgAhESAQIQEgEC0AAEFQag435wHmAQECAwQFBgcIAAAAAAAAAAkKCwwNDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADxAREhMUAAtBHiEQDL0DC0ICIREM5QELQgMhEQzkAQtCBCERDOMBC0IFIREM4gELQgYhEQzhAQtCByERDOABC0IIIREM3wELQgkhEQzeAQtCCiERDN0BC0ILIREM3AELQgwhEQzbAQtCDSERDNoBC0IOIREM2QELQg8hEQzYAQtCCiERDNcBC0ILIREM1gELQgwhEQzVAQtCDSERDNQBC0IOIREM0wELQg8hEQzSAQtCACERAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQLQAAQVBqDjflAeQBAAECAwQFBgfmAeYB5gHmAeYB5gHmAQgJCgsMDeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gEODxAREhPmAQtCAiERDOQBC0IDIREM4wELQgQhEQziAQtCBSERDOEBC0IGIREM4AELQgchEQzfAQtCCCERDN4BC0IJIREM3QELQgohEQzcAQtCCyERDNsBC0IMIREM2gELQg0hEQzZAQtCDiERDNgBC0IPIREM1wELQgohEQzWAQtCCyERDNUBC0IMIREM1AELQg0hEQzTAQtCDiERDNIBC0IPIREM0QELIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN0gFBHyEQDMADCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEkIRAMpwMLQSAhEAy/AwsgACABIhAgAhC+gICAAEF/ag4FtgEAxQIB0QHSAQtBESEQDKQDCyAAQQE6AC8gECEBDLsDCyABIgEgAkcN0gFBJCEQDLsDCyABIg0gAkcNHkHGACEQDLoDCyAAIAEiASACELKAgIAAIhAN1AEgASEBDLUBCyABIhAgAkcNJkHQACEQDLgDCwJAIAEiASACRw0AQSghEAy4AwsgAEEANgIEIABBjICAgAA2AgggACABIAEQsYCAgAAiEA3TASABIQEM2AELAkAgASIQIAJHDQBBKSEQDLcDCyAQLQAAIgFBIEYNFCABQQlHDdMBIBBBAWohAQwVCwJAIAEiASACRg0AIAFBAWohAQwXC0EqIRAMtQMLAkAgASIQIAJHDQBBKyEQDLUDCwJAIBAtAAAiAUEJRg0AIAFBIEcN1QELIAAtACxBCEYN0wEgECEBDJEDCwJAIAEiASACRw0AQSwhEAy0AwsgAS0AAEEKRw3VASABQQFqIQEMyQILIAEiDiACRw3VAUEvIRAMsgMLA0ACQCABLQAAIhBBIEYNAAJAIBBBdmoOBADcAdwBANoBCyABIQEM4AELIAFBAWoiASACRw0AC0ExIRAMsQMLQTIhECABIhQgAkYNsAMgAiAUayAAKAIAIgFqIRUgFCABa0EDaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfC7gIAAai0AAEcNAQJAIAFBA0cNAEEGIQEMlgMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLEDCyAAQQA2AgAgFCEBDNkBC0EzIRAgASIUIAJGDa8DIAIgFGsgACgCACIBaiEVIBQgAWtBCGohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUH0u4CAAGotAABHDQECQCABQQhHDQBBBSEBDJUDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAywAwsgAEEANgIAIBQhAQzYAQtBNCEQIAEiFCACRg2uAyACIBRrIAAoAgAiAWohFSAUIAFrQQVqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw0BAkAgAUEFRw0AQQchAQyUAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMrwMLIABBADYCACAUIQEM1wELAkAgASIBIAJGDQADQAJAIAEtAABBgL6AgABqLQAAIhBBAUYNACAQQQJGDQogASEBDN0BCyABQQFqIgEgAkcNAAtBMCEQDK4DC0EwIRAMrQMLAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AIBBBdmoOBNkB2gHaAdkB2gELIAFBAWoiASACRw0AC0E4IRAMrQMLQTghEAysAwsDQAJAIAEtAAAiEEEgRg0AIBBBCUcNAwsgAUEBaiIBIAJHDQALQTwhEAyrAwsDQAJAIAEtAAAiEEEgRg0AAkACQCAQQXZqDgTaAQEB2gEACyAQQSxGDdsBCyABIQEMBAsgAUEBaiIBIAJHDQALQT8hEAyqAwsgASEBDNsBC0HAACEQIAEiFCACRg2oAyACIBRrIAAoAgAiAWohFiAUIAFrQQZqIRcCQANAIBQtAABBIHIgAUGAwICAAGotAABHDQEgAUEGRg2OAyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAypAwsgAEEANgIAIBQhAQtBNiEQDI4DCwJAIAEiDyACRw0AQcEAIRAMpwMLIABBjICAgAA2AgggACAPNgIEIA8hASAALQAsQX9qDgTNAdUB1wHZAYcDCyABQQFqIQEMzAELAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgciAQIBBBv39qQf8BcUEaSRtB/wFxIhBBCUYNACAQQSBGDQACQAJAAkACQCAQQZ1/ag4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIRAMkQMLIAFBAWohAUEyIRAMkAMLIAFBAWohAUEzIRAMjwMLIAEhAQzQAQsgAUEBaiIBIAJHDQALQTUhEAylAwtBNSEQDKQDCwJAIAEiASACRg0AA0ACQCABLQAAQYC8gIAAai0AAEEBRg0AIAEhAQzTAQsgAUEBaiIBIAJHDQALQT0hEAykAwtBPSEQDKMDCyAAIAEiASACELCAgIAAIhAN1gEgASEBDAELIBBBAWohAQtBPCEQDIcDCwJAIAEiASACRw0AQcIAIRAMoAMLAkADQAJAIAEtAABBd2oOGAAC/gL+AoQD/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4CAP4CCyABQQFqIgEgAkcNAAtBwgAhEAygAwsgAUEBaiEBIAAtAC1BAXFFDb0BIAEhAQtBLCEQDIUDCyABIgEgAkcN0wFBxAAhEAydAwsDQAJAIAEtAABBkMCAgABqLQAAQQFGDQAgASEBDLcCCyABQQFqIgEgAkcNAAtBxQAhEAycAwsgDS0AACIQQSBGDbMBIBBBOkcNgQMgACgCBCEBIABBADYCBCAAIAEgDRCvgICAACIBDdABIA1BAWohAQyzAgtBxwAhECABIg0gAkYNmgMgAiANayAAKAIAIgFqIRYgDSABa0EFaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGQwoCAAGotAABHDYADIAFBBUYN9AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmgMLQcgAIRAgASINIAJGDZkDIAIgDWsgACgCACIBaiEWIA0gAWtBCWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBlsKAgABqLQAARw3/AgJAIAFBCUcNAEECIQEM9QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJkDCwJAIAEiDSACRw0AQckAIRAMmQMLAkACQCANLQAAIgFBIHIgASABQb9/akH/AXFBGkkbQf8BcUGSf2oOBwCAA4ADgAOAA4ADAYADCyANQQFqIQFBPiEQDIADCyANQQFqIQFBPyEQDP8CC0HKACEQIAEiDSACRg2XAyACIA1rIAAoAgAiAWohFiANIAFrQQFqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaDCgIAAai0AAEcN/QIgAUEBRg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyXAwtBywAhECABIg0gAkYNlgMgAiANayAAKAIAIgFqIRYgDSABa0EOaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGiwoCAAGotAABHDfwCIAFBDkYN8AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlgMLQcwAIRAgASINIAJGDZUDIAIgDWsgACgCACIBaiEWIA0gAWtBD2ohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBwMKAgABqLQAARw37AgJAIAFBD0cNAEEDIQEM8QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJUDC0HNACEQIAEiDSACRg2UAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQdDCgIAAai0AAEcN+gICQCABQQVHDQBBBCEBDPACCyABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyUAwsCQCABIg0gAkcNAEHOACEQDJQDCwJAAkACQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZ1/ag4TAP0C/QL9Av0C/QL9Av0C/QL9Av0C/QL9AgH9Av0C/QICA/0CCyANQQFqIQFBwQAhEAz9AgsgDUEBaiEBQcIAIRAM/AILIA1BAWohAUHDACEQDPsCCyANQQFqIQFBxAAhEAz6AgsCQCABIgEgAkYNACAAQY2AgIAANgIIIAAgATYCBCABIQFBxQAhEAz6AgtBzwAhEAySAwsgECEBAkACQCAQLQAAQXZqDgQBqAKoAgCoAgsgEEEBaiEBC0EnIRAM+AILAkAgASIBIAJHDQBB0QAhEAyRAwsCQCABLQAAQSBGDQAgASEBDI0BCyABQQFqIQEgAC0ALUEBcUUNxwEgASEBDIwBCyABIhcgAkcNyAFB0gAhEAyPAwtB0wAhECABIhQgAkYNjgMgAiAUayAAKAIAIgFqIRYgFCABa0EBaiEXA0AgFC0AACABQdbCgIAAai0AAEcNzAEgAUEBRg3HASABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAyOAwsCQCABIgEgAkcNAEHVACEQDI4DCyABLQAAQQpHDcwBIAFBAWohAQzHAQsCQCABIgEgAkcNAEHWACEQDI0DCwJAAkAgAS0AAEF2ag4EAM0BzQEBzQELIAFBAWohAQzHAQsgAUEBaiEBQcoAIRAM8wILIAAgASIBIAIQroCAgAAiEA3LASABIQFBzQAhEAzyAgsgAC0AKUEiRg2FAwymAgsCQCABIgEgAkcNAEHbACEQDIoDC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgAS0AAEFQag4K1AHTAQABAgMEBQYI1QELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMzAELQQkhEEEBIRRBACEXQQAhFgzLAQsCQCABIgEgAkcNAEHdACEQDIkDCyABLQAAQS5HDcwBIAFBAWohAQymAgsgASIBIAJHDcwBQd8AIRAMhwMLAkAgASIBIAJGDQAgAEGOgICAADYCCCAAIAE2AgQgASEBQdAAIRAM7gILQeAAIRAMhgMLQeEAIRAgASIBIAJGDYUDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHiwoCAAGotAABHDc0BIBRBA0YNzAEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhQMLQeIAIRAgASIBIAJGDYQDIAIgAWsgACgCACIUaiEWIAEgFGtBAmohFwNAIAEtAAAgFEHmwoCAAGotAABHDcwBIBRBAkYNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhAMLQeMAIRAgASIBIAJGDYMDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHpwoCAAGotAABHDcsBIBRBA0YNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMgwMLAkAgASIBIAJHDQBB5QAhEAyDAwsgACABQQFqIgEgAhCogICAACIQDc0BIAEhAUHWACEQDOkCCwJAIAEiASACRg0AA0ACQCABLQAAIhBBIEYNAAJAAkACQCAQQbh/ag4LAAHPAc8BzwHPAc8BzwHPAc8BAs8BCyABQQFqIQFB0gAhEAztAgsgAUEBaiEBQdMAIRAM7AILIAFBAWohAUHUACEQDOsCCyABQQFqIgEgAkcNAAtB5AAhEAyCAwtB5AAhEAyBAwsDQAJAIAEtAABB8MKAgABqLQAAIhBBAUYNACAQQX5qDgPPAdAB0QHSAQsgAUEBaiIBIAJHDQALQeYAIRAMgAMLAkAgASIBIAJGDQAgAUEBaiEBDAMLQecAIRAM/wILA0ACQCABLQAAQfDEgIAAai0AACIQQQFGDQACQCAQQX5qDgTSAdMB1AEA1QELIAEhAUHXACEQDOcCCyABQQFqIgEgAkcNAAtB6AAhEAz+AgsCQCABIgEgAkcNAEHpACEQDP4CCwJAIAEtAAAiEEF2ag4augHVAdUBvAHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHKAdUB1QEA0wELIAFBAWohAQtBBiEQDOMCCwNAAkAgAS0AAEHwxoCAAGotAABBAUYNACABIQEMngILIAFBAWoiASACRw0AC0HqACEQDPsCCwJAIAEiASACRg0AIAFBAWohAQwDC0HrACEQDPoCCwJAIAEiASACRw0AQewAIRAM+gILIAFBAWohAQwBCwJAIAEiASACRw0AQe0AIRAM+QILIAFBAWohAQtBBCEQDN4CCwJAIAEiFCACRw0AQe4AIRAM9wILIBQhAQJAAkACQCAULQAAQfDIgIAAai0AAEF/ag4H1AHVAdYBAJwCAQLXAQsgFEEBaiEBDAoLIBRBAWohAQzNAQtBACEQIABBADYCHCAAQZuSgIAANgIQIABBBzYCDCAAIBRBAWo2AhQM9gILAkADQAJAIAEtAABB8MiAgABqLQAAIhBBBEYNAAJAAkAgEEF/ag4H0gHTAdQB2QEABAHZAQsgASEBQdoAIRAM4AILIAFBAWohAUHcACEQDN8CCyABQQFqIgEgAkcNAAtB7wAhEAz2AgsgAUEBaiEBDMsBCwJAIAEiFCACRw0AQfAAIRAM9QILIBQtAABBL0cN1AEgFEEBaiEBDAYLAkAgASIUIAJHDQBB8QAhEAz0AgsCQCAULQAAIgFBL0cNACAUQQFqIQFB3QAhEAzbAgsgAUF2aiIEQRZLDdMBQQEgBHRBiYCAAnFFDdMBDMoCCwJAIAEiASACRg0AIAFBAWohAUHeACEQDNoCC0HyACEQDPICCwJAIAEiFCACRw0AQfQAIRAM8gILIBQhAQJAIBQtAABB8MyAgABqLQAAQX9qDgPJApQCANQBC0HhACEQDNgCCwJAIAEiFCACRg0AA0ACQCAULQAAQfDKgIAAai0AACIBQQNGDQACQCABQX9qDgLLAgDVAQsgFCEBQd8AIRAM2gILIBRBAWoiFCACRw0AC0HzACEQDPECC0HzACEQDPACCwJAIAEiASACRg0AIABBj4CAgAA2AgggACABNgIEIAEhAUHgACEQDNcCC0H1ACEQDO8CCwJAIAEiASACRw0AQfYAIRAM7wILIABBj4CAgAA2AgggACABNgIEIAEhAQtBAyEQDNQCCwNAIAEtAABBIEcNwwIgAUEBaiIBIAJHDQALQfcAIRAM7AILAkAgASIBIAJHDQBB+AAhEAzsAgsgAS0AAEEgRw3OASABQQFqIQEM7wELIAAgASIBIAIQrICAgAAiEA3OASABIQEMjgILAkAgASIEIAJHDQBB+gAhEAzqAgsgBC0AAEHMAEcN0QEgBEEBaiEBQRMhEAzPAQsCQCABIgQgAkcNAEH7ACEQDOkCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRADQCAELQAAIAFB8M6AgABqLQAARw3QASABQQVGDc4BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQfsAIRAM6AILAkAgASIEIAJHDQBB/AAhEAzoAgsCQAJAIAQtAABBvX9qDgwA0QHRAdEB0QHRAdEB0QHRAdEB0QEB0QELIARBAWohAUHmACEQDM8CCyAEQQFqIQFB5wAhEAzOAgsCQCABIgQgAkcNAEH9ACEQDOcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDc8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH9ACEQDOcCCyAAQQA2AgAgEEEBaiEBQRAhEAzMAQsCQCABIgQgAkcNAEH+ACEQDOYCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUH2zoCAAGotAABHDc4BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH+ACEQDOYCCyAAQQA2AgAgEEEBaiEBQRYhEAzLAQsCQCABIgQgAkcNAEH/ACEQDOUCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUH8zoCAAGotAABHDc0BIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH/ACEQDOUCCyAAQQA2AgAgEEEBaiEBQQUhEAzKAQsCQCABIgQgAkcNAEGAASEQDOQCCyAELQAAQdkARw3LASAEQQFqIQFBCCEQDMkBCwJAIAEiBCACRw0AQYEBIRAM4wILAkACQCAELQAAQbJ/ag4DAMwBAcwBCyAEQQFqIQFB6wAhEAzKAgsgBEEBaiEBQewAIRAMyQILAkAgASIEIAJHDQBBggEhEAziAgsCQAJAIAQtAABBuH9qDggAywHLAcsBywHLAcsBAcsBCyAEQQFqIQFB6gAhEAzJAgsgBEEBaiEBQe0AIRAMyAILAkAgASIEIAJHDQBBgwEhEAzhAgsgAiAEayAAKAIAIgFqIRAgBCABa0ECaiEUAkADQCAELQAAIAFBgM+AgABqLQAARw3JASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBA2AgBBgwEhEAzhAgtBACEQIABBADYCACAUQQFqIQEMxgELAkAgASIEIAJHDQBBhAEhEAzgAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBg8+AgABqLQAARw3IASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhAEhEAzgAgsgAEEANgIAIBBBAWohAUEjIRAMxQELAkAgASIEIAJHDQBBhQEhEAzfAgsCQAJAIAQtAABBtH9qDggAyAHIAcgByAHIAcgBAcgBCyAEQQFqIQFB7wAhEAzGAgsgBEEBaiEBQfAAIRAMxQILAkAgASIEIAJHDQBBhgEhEAzeAgsgBC0AAEHFAEcNxQEgBEEBaiEBDIMCCwJAIAEiBCACRw0AQYcBIRAM3QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQYjPgIAAai0AAEcNxQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYcBIRAM3QILIABBADYCACAQQQFqIQFBLSEQDMIBCwJAIAEiBCACRw0AQYgBIRAM3AILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNxAEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYgBIRAM3AILIABBADYCACAQQQFqIQFBKSEQDMEBCwJAIAEiASACRw0AQYkBIRAM2wILQQEhECABLQAAQd8ARw3AASABQQFqIQEMgQILAkAgASIEIAJHDQBBigEhEAzaAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQA0AgBC0AACABQYzPgIAAai0AAEcNwQEgAUEBRg2vAiABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGKASEQDNkCCwJAIAEiBCACRw0AQYsBIRAM2QILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQY7PgIAAai0AAEcNwQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYsBIRAM2QILIABBADYCACAQQQFqIQFBAiEQDL4BCwJAIAEiBCACRw0AQYwBIRAM2AILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNwAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYwBIRAM2AILIABBADYCACAQQQFqIQFBHyEQDL0BCwJAIAEiBCACRw0AQY0BIRAM1wILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNvwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY0BIRAM1wILIABBADYCACAQQQFqIQFBCSEQDLwBCwJAIAEiBCACRw0AQY4BIRAM1gILAkACQCAELQAAQbd/ag4HAL8BvwG/Ab8BvwEBvwELIARBAWohAUH4ACEQDL0CCyAEQQFqIQFB+QAhEAy8AgsCQCABIgQgAkcNAEGPASEQDNUCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGRz4CAAGotAABHDb0BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGPASEQDNUCCyAAQQA2AgAgEEEBaiEBQRghEAy6AQsCQCABIgQgAkcNAEGQASEQDNQCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUGXz4CAAGotAABHDbwBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGQASEQDNQCCyAAQQA2AgAgEEEBaiEBQRchEAy5AQsCQCABIgQgAkcNAEGRASEQDNMCCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUGaz4CAAGotAABHDbsBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGRASEQDNMCCyAAQQA2AgAgEEEBaiEBQRUhEAy4AQsCQCABIgQgAkcNAEGSASEQDNICCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGhz4CAAGotAABHDboBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGSASEQDNICCyAAQQA2AgAgEEEBaiEBQR4hEAy3AQsCQCABIgQgAkcNAEGTASEQDNECCyAELQAAQcwARw24ASAEQQFqIQFBCiEQDLYBCwJAIAQgAkcNAEGUASEQDNACCwJAAkAgBC0AAEG/f2oODwC5AbkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AQG5AQsgBEEBaiEBQf4AIRAMtwILIARBAWohAUH/ACEQDLYCCwJAIAQgAkcNAEGVASEQDM8CCwJAAkAgBC0AAEG/f2oOAwC4AQG4AQsgBEEBaiEBQf0AIRAMtgILIARBAWohBEGAASEQDLUCCwJAIAQgAkcNAEGWASEQDM4CCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUGnz4CAAGotAABHDbYBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGWASEQDM4CCyAAQQA2AgAgEEEBaiEBQQshEAyzAQsCQCAEIAJHDQBBlwEhEAzNAgsCQAJAAkACQCAELQAAQVNqDiMAuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AQG4AbgBuAG4AbgBArgBuAG4AQO4AQsgBEEBaiEBQfsAIRAMtgILIARBAWohAUH8ACEQDLUCCyAEQQFqIQRBgQEhEAy0AgsgBEEBaiEEQYIBIRAMswILAkAgBCACRw0AQZgBIRAMzAILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQanPgIAAai0AAEcNtAEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZgBIRAMzAILIABBADYCACAQQQFqIQFBGSEQDLEBCwJAIAQgAkcNAEGZASEQDMsCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGuz4CAAGotAABHDbMBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGZASEQDMsCCyAAQQA2AgAgEEEBaiEBQQYhEAywAQsCQCAEIAJHDQBBmgEhEAzKAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBtM+AgABqLQAARw2yASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmgEhEAzKAgsgAEEANgIAIBBBAWohAUEcIRAMrwELAkAgBCACRw0AQZsBIRAMyQILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbbPgIAAai0AAEcNsQEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZsBIRAMyQILIABBADYCACAQQQFqIQFBJyEQDK4BCwJAIAQgAkcNAEGcASEQDMgCCwJAAkAgBC0AAEGsf2oOAgABsQELIARBAWohBEGGASEQDK8CCyAEQQFqIQRBhwEhEAyuAgsCQCAEIAJHDQBBnQEhEAzHAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBuM+AgABqLQAARw2vASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBnQEhEAzHAgsgAEEANgIAIBBBAWohAUEmIRAMrAELAkAgBCACRw0AQZ4BIRAMxgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbrPgIAAai0AAEcNrgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ4BIRAMxgILIABBADYCACAQQQFqIQFBAyEQDKsBCwJAIAQgAkcNAEGfASEQDMUCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDa0BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGfASEQDMUCCyAAQQA2AgAgEEEBaiEBQQwhEAyqAQsCQCAEIAJHDQBBoAEhEAzEAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBvM+AgABqLQAARw2sASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBoAEhEAzEAgsgAEEANgIAIBBBAWohAUENIRAMqQELAkAgBCACRw0AQaEBIRAMwwILAkACQCAELQAAQbp/ag4LAKwBrAGsAawBrAGsAawBrAGsAQGsAQsgBEEBaiEEQYsBIRAMqgILIARBAWohBEGMASEQDKkCCwJAIAQgAkcNAEGiASEQDMICCyAELQAAQdAARw2pASAEQQFqIQQM6QELAkAgBCACRw0AQaMBIRAMwQILAkACQCAELQAAQbd/ag4HAaoBqgGqAaoBqgEAqgELIARBAWohBEGOASEQDKgCCyAEQQFqIQFBIiEQDKYBCwJAIAQgAkcNAEGkASEQDMACCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHAz4CAAGotAABHDagBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGkASEQDMACCyAAQQA2AgAgEEEBaiEBQR0hEAylAQsCQCAEIAJHDQBBpQEhEAy/AgsCQAJAIAQtAABBrn9qDgMAqAEBqAELIARBAWohBEGQASEQDKYCCyAEQQFqIQFBBCEQDKQBCwJAIAQgAkcNAEGmASEQDL4CCwJAAkACQAJAAkAgBC0AAEG/f2oOFQCqAaoBqgGqAaoBqgGqAaoBqgGqAQGqAaoBAqoBqgEDqgGqAQSqAQsgBEEBaiEEQYgBIRAMqAILIARBAWohBEGJASEQDKcCCyAEQQFqIQRBigEhEAymAgsgBEEBaiEEQY8BIRAMpQILIARBAWohBEGRASEQDKQCCwJAIAQgAkcNAEGnASEQDL0CCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDaUBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGnASEQDL0CCyAAQQA2AgAgEEEBaiEBQREhEAyiAQsCQCAEIAJHDQBBqAEhEAy8AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBws+AgABqLQAARw2kASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqAEhEAy8AgsgAEEANgIAIBBBAWohAUEsIRAMoQELAkAgBCACRw0AQakBIRAMuwILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQcXPgIAAai0AAEcNowEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQakBIRAMuwILIABBADYCACAQQQFqIQFBKyEQDKABCwJAIAQgAkcNAEGqASEQDLoCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHKz4CAAGotAABHDaIBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGqASEQDLoCCyAAQQA2AgAgEEEBaiEBQRQhEAyfAQsCQCAEIAJHDQBBqwEhEAy5AgsCQAJAAkACQCAELQAAQb5/ag4PAAECpAGkAaQBpAGkAaQBpAGkAaQBpAGkAQOkAQsgBEEBaiEEQZMBIRAMogILIARBAWohBEGUASEQDKECCyAEQQFqIQRBlQEhEAygAgsgBEEBaiEEQZYBIRAMnwILAkAgBCACRw0AQawBIRAMuAILIAQtAABBxQBHDZ8BIARBAWohBAzgAQsCQCAEIAJHDQBBrQEhEAy3AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBzc+AgABqLQAARw2fASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrQEhEAy3AgsgAEEANgIAIBBBAWohAUEOIRAMnAELAkAgBCACRw0AQa4BIRAMtgILIAQtAABB0ABHDZ0BIARBAWohAUElIRAMmwELAkAgBCACRw0AQa8BIRAMtQILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNnQEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQa8BIRAMtQILIABBADYCACAQQQFqIQFBKiEQDJoBCwJAIAQgAkcNAEGwASEQDLQCCwJAAkAgBC0AAEGrf2oOCwCdAZ0BnQGdAZ0BnQGdAZ0BnQEBnQELIARBAWohBEGaASEQDJsCCyAEQQFqIQRBmwEhEAyaAgsCQCAEIAJHDQBBsQEhEAyzAgsCQAJAIAQtAABBv39qDhQAnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBAZwBCyAEQQFqIQRBmQEhEAyaAgsgBEEBaiEEQZwBIRAMmQILAkAgBCACRw0AQbIBIRAMsgILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQdnPgIAAai0AAEcNmgEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbIBIRAMsgILIABBADYCACAQQQFqIQFBISEQDJcBCwJAIAQgAkcNAEGzASEQDLECCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUHdz4CAAGotAABHDZkBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGzASEQDLECCyAAQQA2AgAgEEEBaiEBQRohEAyWAQsCQCAEIAJHDQBBtAEhEAywAgsCQAJAAkAgBC0AAEG7f2oOEQCaAZoBmgGaAZoBmgGaAZoBmgEBmgGaAZoBmgGaAQKaAQsgBEEBaiEEQZ0BIRAMmAILIARBAWohBEGeASEQDJcCCyAEQQFqIQRBnwEhEAyWAgsCQCAEIAJHDQBBtQEhEAyvAgsgAiAEayAAKAIAIgFqIRQgBCABa0EFaiEQAkADQCAELQAAIAFB5M+AgABqLQAARw2XASABQQVGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtQEhEAyvAgsgAEEANgIAIBBBAWohAUEoIRAMlAELAkAgBCACRw0AQbYBIRAMrgILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQerPgIAAai0AAEcNlgEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbYBIRAMrgILIABBADYCACAQQQFqIQFBByEQDJMBCwJAIAQgAkcNAEG3ASEQDK0CCwJAAkAgBC0AAEG7f2oODgCWAZYBlgGWAZYBlgGWAZYBlgGWAZYBlgEBlgELIARBAWohBEGhASEQDJQCCyAEQQFqIQRBogEhEAyTAgsCQCAEIAJHDQBBuAEhEAysAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB7c+AgABqLQAARw2UASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuAEhEAysAgsgAEEANgIAIBBBAWohAUESIRAMkQELAkAgBCACRw0AQbkBIRAMqwILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNkwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbkBIRAMqwILIABBADYCACAQQQFqIQFBICEQDJABCwJAIAQgAkcNAEG6ASEQDKoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHyz4CAAGotAABHDZIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG6ASEQDKoCCyAAQQA2AgAgEEEBaiEBQQ8hEAyPAQsCQCAEIAJHDQBBuwEhEAypAgsCQAJAIAQtAABBt39qDgcAkgGSAZIBkgGSAQGSAQsgBEEBaiEEQaUBIRAMkAILIARBAWohBEGmASEQDI8CCwJAIAQgAkcNAEG8ASEQDKgCCyACIARrIAAoAgAiAWohFCAEIAFrQQdqIRACQANAIAQtAAAgAUH0z4CAAGotAABHDZABIAFBB0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG8ASEQDKgCCyAAQQA2AgAgEEEBaiEBQRshEAyNAQsCQCAEIAJHDQBBvQEhEAynAgsCQAJAAkAgBC0AAEG+f2oOEgCRAZEBkQGRAZEBkQGRAZEBkQEBkQGRAZEBkQGRAZEBApEBCyAEQQFqIQRBpAEhEAyPAgsgBEEBaiEEQacBIRAMjgILIARBAWohBEGoASEQDI0CCwJAIAQgAkcNAEG+ASEQDKYCCyAELQAAQc4ARw2NASAEQQFqIQQMzwELAkAgBCACRw0AQb8BIRAMpQILAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgBC0AAEG/f2oOFQABAgOcAQQFBpwBnAGcAQcICQoLnAEMDQ4PnAELIARBAWohAUHoACEQDJoCCyAEQQFqIQFB6QAhEAyZAgsgBEEBaiEBQe4AIRAMmAILIARBAWohAUHyACEQDJcCCyAEQQFqIQFB8wAhEAyWAgsgBEEBaiEBQfYAIRAMlQILIARBAWohAUH3ACEQDJQCCyAEQQFqIQFB+gAhEAyTAgsgBEEBaiEEQYMBIRAMkgILIARBAWohBEGEASEQDJECCyAEQQFqIQRBhQEhEAyQAgsgBEEBaiEEQZIBIRAMjwILIARBAWohBEGYASEQDI4CCyAEQQFqIQRBoAEhEAyNAgsgBEEBaiEEQaMBIRAMjAILIARBAWohBEGqASEQDIsCCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEGrASEQDIsCC0HAASEQDKMCCyAAIAUgAhCqgICAACIBDYsBIAUhAQxcCwJAIAYgAkYNACAGQQFqIQUMjQELQcIBIRAMoQILA0ACQCAQLQAAQXZqDgSMAQAAjwEACyAQQQFqIhAgAkcNAAtBwwEhEAygAgsCQCAHIAJGDQAgAEGRgICAADYCCCAAIAc2AgQgByEBQQEhEAyHAgtBxAEhEAyfAgsCQCAHIAJHDQBBxQEhEAyfAgsCQAJAIActAABBdmoOBAHOAc4BAM4BCyAHQQFqIQYMjQELIAdBAWohBQyJAQsCQCAHIAJHDQBBxgEhEAyeAgsCQAJAIActAABBdmoOFwGPAY8BAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAQCPAQsgB0EBaiEHC0GwASEQDIQCCwJAIAggAkcNAEHIASEQDJ0CCyAILQAAQSBHDY0BIABBADsBMiAIQQFqIQFBswEhEAyDAgsgASEXAkADQCAXIgcgAkYNASAHLQAAQVBqQf8BcSIQQQpPDcwBAkAgAC8BMiIUQZkzSw0AIAAgFEEKbCIUOwEyIBBB//8DcyAUQf7/A3FJDQAgB0EBaiEXIAAgFCAQaiIQOwEyIBBB//8DcUHoB0kNAQsLQQAhECAAQQA2AhwgAEHBiYCAADYCECAAQQ02AgwgACAHQQFqNgIUDJwCC0HHASEQDJsCCyAAIAggAhCugICAACIQRQ3KASAQQRVHDYwBIABByAE2AhwgACAINgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAyaAgsCQCAJIAJHDQBBzAEhEAyaAgtBACEUQQEhF0EBIRZBACEQAkACQAJAAkACQAJAAkACQAJAIAktAABBUGoOCpYBlQEAAQIDBAUGCJcBC0ECIRAMBgtBAyEQDAULQQQhEAwEC0EFIRAMAwtBBiEQDAILQQchEAwBC0EIIRALQQAhF0EAIRZBACEUDI4BC0EJIRBBASEUQQAhF0EAIRYMjQELAkAgCiACRw0AQc4BIRAMmQILIAotAABBLkcNjgEgCkEBaiEJDMoBCyALIAJHDY4BQdABIRAMlwILAkAgCyACRg0AIABBjoCAgAA2AgggACALNgIEQbcBIRAM/gELQdEBIRAMlgILAkAgBCACRw0AQdIBIRAMlgILIAIgBGsgACgCACIQaiEUIAQgEGtBBGohCwNAIAQtAAAgEEH8z4CAAGotAABHDY4BIBBBBEYN6QEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB0gEhEAyVAgsgACAMIAIQrICAgAAiAQ2NASAMIQEMuAELAkAgBCACRw0AQdQBIRAMlAILIAIgBGsgACgCACIQaiEUIAQgEGtBAWohDANAIAQtAAAgEEGB0ICAAGotAABHDY8BIBBBAUYNjgEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB1AEhEAyTAgsCQCAEIAJHDQBB1gEhEAyTAgsgAiAEayAAKAIAIhBqIRQgBCAQa0ECaiELA0AgBC0AACAQQYPQgIAAai0AAEcNjgEgEEECRg2QASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHWASEQDJICCwJAIAQgAkcNAEHXASEQDJICCwJAAkAgBC0AAEG7f2oOEACPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAY8BCyAEQQFqIQRBuwEhEAz5AQsgBEEBaiEEQbwBIRAM+AELAkAgBCACRw0AQdgBIRAMkQILIAQtAABByABHDYwBIARBAWohBAzEAQsCQCAEIAJGDQAgAEGQgICAADYCCCAAIAQ2AgRBvgEhEAz3AQtB2QEhEAyPAgsCQCAEIAJHDQBB2gEhEAyPAgsgBC0AAEHIAEYNwwEgAEEBOgAoDLkBCyAAQQI6AC8gACAEIAIQpoCAgAAiEA2NAUHCASEQDPQBCyAALQAoQX9qDgK3AbkBuAELA0ACQCAELQAAQXZqDgQAjgGOAQCOAQsgBEEBaiIEIAJHDQALQd0BIRAMiwILIABBADoALyAALQAtQQRxRQ2EAgsgAEEAOgAvIABBAToANCABIQEMjAELIBBBFUYN2gEgAEEANgIcIAAgATYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMiAILAkAgACAQIAIQtICAgAAiBA0AIBAhAQyBAgsCQCAEQRVHDQAgAEEDNgIcIAAgEDYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMiAILIABBADYCHCAAIBA2AhQgAEGnjoCAADYCECAAQRI2AgxBACEQDIcCCyAQQRVGDdYBIABBADYCHCAAIAE2AhQgAEHajYCAADYCECAAQRQ2AgxBACEQDIYCCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNjQEgAEEHNgIcIAAgEDYCFCAAIBQ2AgxBACEQDIUCCyAAIAAvATBBgAFyOwEwIAEhAQtBKiEQDOoBCyAQQRVGDdEBIABBADYCHCAAIAE2AhQgAEGDjICAADYCECAAQRM2AgxBACEQDIICCyAQQRVGDc8BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDIECCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyNAQsgAEEMNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDIACCyAQQRVGDcwBIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDP8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyMAQsgAEENNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDP4BCyAQQRVGDckBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDP0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyLAQsgAEEONgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPwBCyAAQQA2AhwgACABNgIUIABBwJWAgAA2AhAgAEECNgIMQQAhEAz7AQsgEEEVRg3FASAAQQA2AhwgACABNgIUIABBxoyAgAA2AhAgAEEjNgIMQQAhEAz6AQsgAEEQNgIcIAAgATYCFCAAIBA2AgxBACEQDPkBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQzxAQsgAEERNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPgBCyAQQRVGDcEBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPcBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyIAQsgAEETNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPYBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQztAQsgAEEUNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPUBCyAQQRVGDb0BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDPQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyGAQsgAEEWNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPMBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQt4CAgAAiBA0AIAFBAWohAQzpAQsgAEEXNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPIBCyAAQQA2AhwgACABNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzxAQtCASERCyAQQQFqIQECQCAAKQMgIhJC//////////8PVg0AIAAgEkIEhiARhDcDICABIQEMhAELIABBADYCHCAAIAE2AhQgAEGtiYCAADYCECAAQQw2AgxBACEQDO8BCyAAQQA2AhwgACAQNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzuAQsgACgCBCEXIABBADYCBCAQIBGnaiIWIQEgACAXIBAgFiAUGyIQELWAgIAAIhRFDXMgAEEFNgIcIAAgEDYCFCAAIBQ2AgxBACEQDO0BCyAAQQA2AhwgACAQNgIUIABBqpyAgAA2AhAgAEEPNgIMQQAhEAzsAQsgACAQIAIQtICAgAAiAQ0BIBAhAQtBDiEQDNEBCwJAIAFBFUcNACAAQQI2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAzqAQsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAM6QELIAFBAWohEAJAIAAvATAiAUGAAXFFDQACQCAAIBAgAhC7gICAACIBDQAgECEBDHALIAFBFUcNugEgAEEFNgIcIAAgEDYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAM6QELAkAgAUGgBHFBoARHDQAgAC0ALUECcQ0AIABBADYCHCAAIBA2AhQgAEGWk4CAADYCECAAQQQ2AgxBACEQDOkBCyAAIBAgAhC9gICAABogECEBAkACQAJAAkACQCAAIBAgAhCzgICAAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIABBAToALgsgACAALwEwQcAAcjsBMCAQIQELQSYhEAzRAQsgAEEjNgIcIAAgEDYCFCAAQaWWgIAANgIQIABBFTYCDEEAIRAM6QELIABBADYCHCAAIBA2AhQgAEHVi4CAADYCECAAQRE2AgxBACEQDOgBCyAALQAtQQFxRQ0BQcMBIRAMzgELAkAgDSACRg0AA0ACQCANLQAAQSBGDQAgDSEBDMQBCyANQQFqIg0gAkcNAAtBJSEQDOcBC0ElIRAM5gELIAAoAgQhBCAAQQA2AgQgACAEIA0Qr4CAgAAiBEUNrQEgAEEmNgIcIAAgBDYCDCAAIA1BAWo2AhRBACEQDOUBCyAQQRVGDasBIABBADYCHCAAIAE2AhQgAEH9jYCAADYCECAAQR02AgxBACEQDOQBCyAAQSc2AhwgACABNgIUIAAgEDYCDEEAIRAM4wELIBAhAUEBIRQCQAJAAkACQAJAAkACQCAALQAsQX5qDgcGBQUDAQIABQsgACAALwEwQQhyOwEwDAMLQQIhFAwBC0EEIRQLIABBAToALCAAIAAvATAgFHI7ATALIBAhAQtBKyEQDMoBCyAAQQA2AhwgACAQNgIUIABBq5KAgAA2AhAgAEELNgIMQQAhEAziAQsgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDEEAIRAM4QELIABBADoALCAQIQEMvQELIBAhAUEBIRQCQAJAAkACQAJAIAAtACxBe2oOBAMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0EpIRAMxQELIABBADYCHCAAIAE2AhQgAEHwlICAADYCECAAQQM2AgxBACEQDN0BCwJAIA4tAABBDUcNACAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA5BAWohAQx1CyAAQSw2AhwgACABNgIMIAAgDkEBajYCFEEAIRAM3QELIAAtAC1BAXFFDQFBxAEhEAzDAQsCQCAOIAJHDQBBLSEQDNwBCwJAAkADQAJAIA4tAABBdmoOBAIAAAMACyAOQQFqIg4gAkcNAAtBLSEQDN0BCyAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA4hAQx0CyAAQSw2AhwgACAONgIUIAAgATYCDEEAIRAM3AELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHMLIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzbAQsgACgCBCEEIABBADYCBCAAIAQgDhCxgICAACIEDaABIA4hAQzOAQsgEEEsRw0BIAFBAWohEEEBIQECQAJAAkACQAJAIAAtACxBe2oOBAMBAgQACyAQIQEMBAtBAiEBDAELQQQhAQsgAEEBOgAsIAAgAC8BMCABcjsBMCAQIQEMAQsgACAALwEwQQhyOwEwIBAhAQtBOSEQDL8BCyAAQQA6ACwgASEBC0E0IRAMvQELIAAgAC8BMEEgcjsBMCABIQEMAgsgACgCBCEEIABBADYCBAJAIAAgBCABELGAgIAAIgQNACABIQEMxwELIABBNzYCHCAAIAE2AhQgACAENgIMQQAhEAzUAQsgAEEIOgAsIAEhAQtBMCEQDLkBCwJAIAAtAChBAUYNACABIQEMBAsgAC0ALUEIcUUNkwEgASEBDAMLIAAtADBBIHENlAFBxQEhEAy3AQsCQCAPIAJGDQACQANAAkAgDy0AAEFQaiIBQf8BcUEKSQ0AIA8hAUE1IRAMugELIAApAyAiEUKZs+bMmbPmzBlWDQEgACARQgp+IhE3AyAgESABrUL/AYMiEkJ/hVYNASAAIBEgEnw3AyAgD0EBaiIPIAJHDQALQTkhEAzRAQsgACgCBCECIABBADYCBCAAIAIgD0EBaiIEELGAgIAAIgINlQEgBCEBDMMBC0E5IRAMzwELAkAgAC8BMCIBQQhxRQ0AIAAtAChBAUcNACAALQAtQQhxRQ2QAQsgACABQff7A3FBgARyOwEwIA8hAQtBNyEQDLQBCyAAIAAvATBBEHI7ATAMqwELIBBBFUYNiwEgAEEANgIcIAAgATYCFCAAQfCOgIAANgIQIABBHDYCDEEAIRAMywELIABBwwA2AhwgACABNgIMIAAgDUEBajYCFEEAIRAMygELAkAgAS0AAEE6Rw0AIAAoAgQhECAAQQA2AgQCQCAAIBAgARCvgICAACIQDQAgAUEBaiEBDGMLIABBwwA2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMygELIABBADYCHCAAIAE2AhQgAEGxkYCAADYCECAAQQo2AgxBACEQDMkBCyAAQQA2AhwgACABNgIUIABBoJmAgAA2AhAgAEEeNgIMQQAhEAzIAQsgAEEANgIACyAAQYASOwEqIAAgF0EBaiIBIAIQqICAgAAiEA0BIAEhAQtBxwAhEAysAQsgEEEVRw2DASAAQdEANgIcIAAgATYCFCAAQeOXgIAANgIQIABBFTYCDEEAIRAMxAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDF4LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMwwELIABBADYCHCAAIBQ2AhQgAEHBqICAADYCECAAQQc2AgwgAEEANgIAQQAhEAzCAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAzBAQtBACEQIABBADYCHCAAIAE2AhQgAEGAkYCAADYCECAAQQk2AgwMwAELIBBBFUYNfSAAQQA2AhwgACABNgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAy/AQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgAUEBaiEBAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBAJAIAAgECABEK2AgIAAIhANACABIQEMXAsgAEHYADYCHCAAIAE2AhQgACAQNgIMQQAhEAy+AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMrQELIABB2QA2AhwgACABNgIUIAAgBDYCDEEAIRAMvQELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKsBCyAAQdoANgIcIAAgATYCFCAAIAQ2AgxBACEQDLwBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQypAQsgAEHcADYCHCAAIAE2AhQgACAENgIMQQAhEAy7AQsCQCABLQAAQVBqIhBB/wFxQQpPDQAgACAQOgAqIAFBAWohAUHPACEQDKIBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQynAQsgAEHeADYCHCAAIAE2AhQgACAENgIMQQAhEAy6AQsgAEEANgIAIBdBAWohAQJAIAAtAClBI08NACABIQEMWQsgAEEANgIcIAAgATYCFCAAQdOJgIAANgIQIABBCDYCDEEAIRAMuQELIABBADYCAAtBACEQIABBADYCHCAAIAE2AhQgAEGQs4CAADYCECAAQQg2AgwMtwELIABBADYCACAXQQFqIQECQCAALQApQSFHDQAgASEBDFYLIABBADYCHCAAIAE2AhQgAEGbioCAADYCECAAQQg2AgxBACEQDLYBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKSIQQV1qQQtPDQAgASEBDFULAkAgEEEGSw0AQQEgEHRBygBxRQ0AIAEhAQxVC0EAIRAgAEEANgIcIAAgATYCFCAAQfeJgIAANgIQIABBCDYCDAy1AQsgEEEVRg1xIABBADYCHCAAIAE2AhQgAEG5jYCAADYCECAAQRo2AgxBACEQDLQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxUCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLMBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAAgEDoAKSAAKAIEIRAgAEEANgIEIAAgECABEKuAgIAAIhANVCABIQEMPgsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQfGbgIAANgIQIABBBjYCDAyXAQsgAUEVRg1QIABBADYCHCAAIAU2AhQgAEHwjICAADYCECAAQRs2AgxBACEQDJYBCyAAKAIEIQUgAEEANgIEIAAgBSAQEKmAgIAAIgUNASAQQQFqIQULQa0BIRAMewsgAEHBATYCHCAAIAU2AgwgACAQQQFqNgIUQQAhEAyTAQsgACgCBCEGIABBADYCBCAAIAYgEBCpgICAACIGDQEgEEEBaiEGC0GuASEQDHgLIABBwgE2AhwgACAGNgIMIAAgEEEBajYCFEEAIRAMkAELIABBADYCHCAAIAc2AhQgAEGXi4CAADYCECAAQQ02AgxBACEQDI8BCyAAQQA2AhwgACAINgIUIABB45CAgAA2AhAgAEEJNgIMQQAhEAyOAQsgAEEANgIcIAAgCDYCFCAAQZSNgIAANgIQIABBITYCDEEAIRAMjQELQQEhFkEAIRdBACEUQQEhEAsgACAQOgArIAlBAWohCAJAAkAgAC0ALUEQcQ0AAkACQAJAIAAtACoOAwEAAgQLIBZFDQMMAgsgFA0BDAILIBdFDQELIAAoAgQhECAAQQA2AgQgACAQIAgQrYCAgAAiEEUNPSAAQckBNgIcIAAgCDYCFCAAIBA2AgxBACEQDIwBCyAAKAIEIQQgAEEANgIEIAAgBCAIEK2AgIAAIgRFDXYgAEHKATYCHCAAIAg2AhQgACAENgIMQQAhEAyLAQsgACgCBCEEIABBADYCBCAAIAQgCRCtgICAACIERQ10IABBywE2AhwgACAJNgIUIAAgBDYCDEEAIRAMigELIAAoAgQhBCAAQQA2AgQgACAEIAoQrYCAgAAiBEUNciAAQc0BNgIcIAAgCjYCFCAAIAQ2AgxBACEQDIkBCwJAIAstAABBUGoiEEH/AXFBCk8NACAAIBA6ACogC0EBaiEKQbYBIRAMcAsgACgCBCEEIABBADYCBCAAIAQgCxCtgICAACIERQ1wIABBzwE2AhwgACALNgIUIAAgBDYCDEEAIRAMiAELIABBADYCHCAAIAQ2AhQgAEGQs4CAADYCECAAQQg2AgwgAEEANgIAQQAhEAyHAQsgAUEVRg0/IABBADYCHCAAIAw2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDIYBCyAAQYEEOwEoIAAoAgQhECAAQgA3AwAgACAQIAxBAWoiDBCrgICAACIQRQ04IABB0wE2AhwgACAMNgIUIAAgEDYCDEEAIRAMhQELIABBADYCAAtBACEQIABBADYCHCAAIAQ2AhQgAEHYm4CAADYCECAAQQg2AgwMgwELIAAoAgQhECAAQgA3AwAgACAQIAtBAWoiCxCrgICAACIQDQFBxgEhEAxpCyAAQQI6ACgMVQsgAEHVATYCHCAAIAs2AhQgACAQNgIMQQAhEAyAAQsgEEEVRg03IABBADYCHCAAIAQ2AhQgAEGkjICAADYCECAAQRA2AgxBACEQDH8LIAAtADRBAUcNNCAAIAQgAhC8gICAACIQRQ00IBBBFUcNNSAAQdwBNgIcIAAgBDYCFCAAQdWWgIAANgIQIABBFTYCDEEAIRAMfgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQMfQtBACEQDGMLQQIhEAxiC0ENIRAMYQtBDyEQDGALQSUhEAxfC0ETIRAMXgtBFSEQDF0LQRYhEAxcC0EXIRAMWwtBGCEQDFoLQRkhEAxZC0EaIRAMWAtBGyEQDFcLQRwhEAxWC0EdIRAMVQtBHyEQDFQLQSEhEAxTC0EjIRAMUgtBxgAhEAxRC0EuIRAMUAtBLyEQDE8LQTshEAxOC0E9IRAMTQtByAAhEAxMC0HJACEQDEsLQcsAIRAMSgtBzAAhEAxJC0HOACEQDEgLQdEAIRAMRwtB1QAhEAxGC0HYACEQDEULQdkAIRAMRAtB2wAhEAxDC0HkACEQDEILQeUAIRAMQQtB8QAhEAxAC0H0ACEQDD8LQY0BIRAMPgtBlwEhEAw9C0GpASEQDDwLQawBIRAMOwtBwAEhEAw6C0G5ASEQDDkLQa8BIRAMOAtBsQEhEAw3C0GyASEQDDYLQbQBIRAMNQtBtQEhEAw0C0G6ASEQDDMLQb0BIRAMMgtBvwEhEAwxC0HBASEQDDALIABBADYCHCAAIAQ2AhQgAEHpi4CAADYCECAAQR82AgxBACEQDEgLIABB2wE2AhwgACAENgIUIABB+paAgAA2AhAgAEEVNgIMQQAhEAxHCyAAQfgANgIcIAAgDDYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMRgsgAEHRADYCHCAAIAU2AhQgAEGwl4CAADYCECAAQRU2AgxBACEQDEULIABB+QA2AhwgACABNgIUIAAgEDYCDEEAIRAMRAsgAEH4ADYCHCAAIAE2AhQgAEHKmICAADYCECAAQRU2AgxBACEQDEMLIABB5AA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAxCCyAAQdcANgIcIAAgATYCFCAAQcmXgIAANgIQIABBFTYCDEEAIRAMQQsgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMQAsgAEHCADYCHCAAIAE2AhQgAEHjmICAADYCECAAQRU2AgxBACEQDD8LIABBADYCBCAAIA8gDxCxgICAACIERQ0BIABBOjYCHCAAIAQ2AgwgACAPQQFqNgIUQQAhEAw+CyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBEUNACAAQTs2AhwgACAENgIMIAAgAUEBajYCFEEAIRAMPgsgAUEBaiEBDC0LIA9BAWohAQwtCyAAQQA2AhwgACAPNgIUIABB5JKAgAA2AhAgAEEENgIMQQAhEAw7CyAAQTY2AhwgACAENgIUIAAgAjYCDEEAIRAMOgsgAEEuNgIcIAAgDjYCFCAAIAQ2AgxBACEQDDkLIABB0AA2AhwgACABNgIUIABBkZiAgAA2AhAgAEEVNgIMQQAhEAw4CyANQQFqIQEMLAsgAEEVNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMNgsgAEEbNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNQsgAEEPNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNAsgAEELNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMMwsgAEEaNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMgsgAEELNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMQsgAEEKNgIcIAAgATYCFCAAQeSWgIAANgIQIABBFTYCDEEAIRAMMAsgAEEeNgIcIAAgATYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAMLwsgAEEANgIcIAAgEDYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMLgsgAEEENgIcIAAgATYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMLQsgAEEANgIAIAtBAWohCwtBuAEhEAwSCyAAQQA2AgAgEEEBaiEBQfUAIRAMEQsgASEBAkAgAC0AKUEFRw0AQeMAIRAMEQtB4gAhEAwQC0EAIRAgAEEANgIcIABB5JGAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAwoCyAAQQA2AgAgF0EBaiEBQcAAIRAMDgtBASEBCyAAIAE6ACwgAEEANgIAIBdBAWohAQtBKCEQDAsLIAEhAQtBOCEQDAkLAkAgASIPIAJGDQADQAJAIA8tAABBgL6AgABqLQAAIgFBAUYNACABQQJHDQMgD0EBaiEBDAQLIA9BAWoiDyACRw0AC0E+IRAMIgtBPiEQDCELIABBADoALCAPIQEMAQtBCyEQDAYLQTohEAwFCyABQQFqIQFBLSEQDAQLIAAgAToALCAAQQA2AgAgFkEBaiEBQQwhEAwDCyAAQQA2AgAgF0EBaiEBQQohEAwCCyAAQQA2AgALIABBADoALCANIQFBCSEQDAALC0EAIRAgAEEANgIcIAAgCzYCFCAAQc2QgIAANgIQIABBCTYCDAwXC0EAIRAgAEEANgIcIAAgCjYCFCAAQemKgIAANgIQIABBCTYCDAwWC0EAIRAgAEEANgIcIAAgCTYCFCAAQbeQgIAANgIQIABBCTYCDAwVC0EAIRAgAEEANgIcIAAgCDYCFCAAQZyRgIAANgIQIABBCTYCDAwUC0EAIRAgAEEANgIcIAAgATYCFCAAQc2QgIAANgIQIABBCTYCDAwTC0EAIRAgAEEANgIcIAAgATYCFCAAQemKgIAANgIQIABBCTYCDAwSC0EAIRAgAEEANgIcIAAgATYCFCAAQbeQgIAANgIQIABBCTYCDAwRC0EAIRAgAEEANgIcIAAgATYCFCAAQZyRgIAANgIQIABBCTYCDAwQC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwPC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwOC0EAIRAgAEEANgIcIAAgATYCFCAAQcCSgIAANgIQIABBCzYCDAwNC0EAIRAgAEEANgIcIAAgATYCFCAAQZWJgIAANgIQIABBCzYCDAwMC0EAIRAgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDAwLC0EAIRAgAEEANgIcIAAgATYCFCAAQfuPgIAANgIQIABBCjYCDAwKC0EAIRAgAEEANgIcIAAgATYCFCAAQfGZgIAANgIQIABBAjYCDAwJC0EAIRAgAEEANgIcIAAgATYCFCAAQcSUgIAANgIQIABBAjYCDAwIC0EAIRAgAEEANgIcIAAgATYCFCAAQfKVgIAANgIQIABBAjYCDAwHCyAAQQI2AhwgACABNgIUIABBnJqAgAA2AhAgAEEWNgIMQQAhEAwGC0EBIRAMBQtB1AAhECABIgQgAkYNBCADQQhqIAAgBCACQdjCgIAAQQoQxYCAgAAgAygCDCEEIAMoAggOAwEEAgALEMqAgIAAAAsgAEEANgIcIABBtZqAgAA2AhAgAEEXNgIMIAAgBEEBajYCFEEAIRAMAgsgAEEANgIcIAAgBDYCFCAAQcqagIAANgIQIABBCTYCDEEAIRAMAQsCQCABIgQgAkcNAEEiIRAMAQsgAEGJgICAADYCCCAAIAQ2AgRBISEQCyADQRBqJICAgIAAIBALrwEBAn8gASgCACEGAkACQCACIANGDQAgBCAGaiEEIAYgA2ogAmshByACIAZBf3MgBWoiBmohBQNAAkAgAi0AACAELQAARg0AQQIhBAwDCwJAIAYNAEEAIQQgBSECDAMLIAZBf2ohBiAEQQFqIQQgAkEBaiICIANHDQALIAchBiADIQILIABBATYCACABIAY2AgAgACACNgIEDwsgAUEANgIAIAAgBDYCACAAIAI2AgQLCgAgABDHgICAAAvyNgELfyOAgICAAEEQayIBJICAgIAAAkBBACgCoNCAgAANAEEAEMuAgIAAQYDUhIAAayICQdkASQ0AQQAhAwJAQQAoAuDTgIAAIgQNAEEAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEIakFwcUHYqtWqBXMiBDYC4NOAgABBAEEANgL004CAAEEAQQA2AsTTgIAAC0EAIAI2AszTgIAAQQBBgNSEgAA2AsjTgIAAQQBBgNSEgAA2ApjQgIAAQQAgBDYCrNCAgABBAEF/NgKo0ICAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALQYDUhIAAQXhBgNSEgABrQQ9xQQBBgNSEgABBCGpBD3EbIgNqIgRBBGogAkFIaiIFIANrIgNBAXI2AgBBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAQYDUhIAAIAVqQTg2AgQLAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFLDQACQEEAKAKI0ICAACIGQRAgAEETakFwcSAAQQtJGyICQQN2IgR2IgNBA3FFDQACQAJAIANBAXEgBHJBAXMiBUEDdCIEQbDQgIAAaiIDIARBuNCAgABqKAIAIgQoAggiAkcNAEEAIAZBfiAFd3E2AojQgIAADAELIAMgAjYCCCACIAM2AgwLIARBCGohAyAEIAVBA3QiBUEDcjYCBCAEIAVqIgQgBCgCBEEBcjYCBAwMCyACQQAoApDQgIAAIgdNDQECQCADRQ0AAkACQCADIAR0QQIgBHQiA0EAIANrcnEiA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqIgRBA3QiA0Gw0ICAAGoiBSADQbjQgIAAaigCACIDKAIIIgBHDQBBACAGQX4gBHdxIgY2AojQgIAADAELIAUgADYCCCAAIAU2AgwLIAMgAkEDcjYCBCADIARBA3QiBGogBCACayIFNgIAIAMgAmoiACAFQQFyNgIEAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQQCQAJAIAZBASAHQQN2dCIIcQ0AQQAgBiAIcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCAENgIMIAIgBDYCCCAEIAI2AgwgBCAINgIICyADQQhqIQNBACAANgKc0ICAAEEAIAU2ApDQgIAADAwLQQAoAozQgIAAIglFDQEgCUEAIAlrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqQQJ0QbjSgIAAaigCACIAKAIEQXhxIAJrIQQgACEFAkADQAJAIAUoAhAiAw0AIAVBFGooAgAiA0UNAgsgAygCBEF4cSACayIFIAQgBSAESSIFGyEEIAMgACAFGyEAIAMhBQwACwsgACgCGCEKAkAgACgCDCIIIABGDQAgACgCCCIDQQAoApjQgIAASRogCCADNgIIIAMgCDYCDAwLCwJAIABBFGoiBSgCACIDDQAgACgCECIDRQ0DIABBEGohBQsDQCAFIQsgAyIIQRRqIgUoAgAiAw0AIAhBEGohBSAIKAIQIgMNAAsgC0EANgIADAoLQX8hAiAAQb9/Sw0AIABBE2oiA0FwcSECQQAoAozQgIAAIgdFDQBBACELAkAgAkGAAkkNAEEfIQsgAkH///8HSw0AIANBCHYiAyADQYD+P2pBEHZBCHEiA3QiBCAEQYDgH2pBEHZBBHEiBHQiBSAFQYCAD2pBEHZBAnEiBXRBD3YgAyAEciAFcmsiA0EBdCACIANBFWp2QQFxckEcaiELC0EAIAJrIQQCQAJAAkACQCALQQJ0QbjSgIAAaigCACIFDQBBACEDQQAhCAwBC0EAIQMgAkEAQRkgC0EBdmsgC0EfRht0IQBBACEIA0ACQCAFKAIEQXhxIAJrIgYgBE8NACAGIQQgBSEIIAYNAEEAIQQgBSEIIAUhAwwDCyADIAVBFGooAgAiBiAGIAUgAEEddkEEcWpBEGooAgAiBUYbIAMgBhshAyAAQQF0IQAgBQ0ACwsCQCADIAhyDQBBACEIQQIgC3QiA0EAIANrciAHcSIDRQ0DIANBACADa3FBf2oiAyADQQx2QRBxIgN2IgVBBXZBCHEiACADciAFIAB2IgNBAnZBBHEiBXIgAyAFdiIDQQF2QQJxIgVyIAMgBXYiA0EBdkEBcSIFciADIAV2akECdEG40oCAAGooAgAhAwsgA0UNAQsDQCADKAIEQXhxIAJrIgYgBEkhAAJAIAMoAhAiBQ0AIANBFGooAgAhBQsgBiAEIAAbIQQgAyAIIAAbIQggBSEDIAUNAAsLIAhFDQAgBEEAKAKQ0ICAACACa08NACAIKAIYIQsCQCAIKAIMIgAgCEYNACAIKAIIIgNBACgCmNCAgABJGiAAIAM2AgggAyAANgIMDAkLAkAgCEEUaiIFKAIAIgMNACAIKAIQIgNFDQMgCEEQaiEFCwNAIAUhBiADIgBBFGoiBSgCACIDDQAgAEEQaiEFIAAoAhAiAw0ACyAGQQA2AgAMCAsCQEEAKAKQ0ICAACIDIAJJDQBBACgCnNCAgAAhBAJAAkAgAyACayIFQRBJDQAgBCACaiIAIAVBAXI2AgRBACAFNgKQ0ICAAEEAIAA2ApzQgIAAIAQgA2ogBTYCACAEIAJBA3I2AgQMAQsgBCADQQNyNgIEIAQgA2oiAyADKAIEQQFyNgIEQQBBADYCnNCAgABBAEEANgKQ0ICAAAsgBEEIaiEDDAoLAkBBACgClNCAgAAiACACTQ0AQQAoAqDQgIAAIgMgAmoiBCAAIAJrIgVBAXI2AgRBACAFNgKU0ICAAEEAIAQ2AqDQgIAAIAMgAkEDcjYCBCADQQhqIQMMCgsCQAJAQQAoAuDTgIAARQ0AQQAoAujTgIAAIQQMAQtBAEJ/NwLs04CAAEEAQoCAhICAgMAANwLk04CAAEEAIAFBDGpBcHFB2KrVqgVzNgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgABBgIAEIQQLQQAhAwJAIAQgAkHHAGoiB2oiBkEAIARrIgtxIgggAksNAEEAQTA2AvjTgIAADAoLAkBBACgCwNOAgAAiA0UNAAJAQQAoArjTgIAAIgQgCGoiBSAETQ0AIAUgA00NAQtBACEDQQBBMDYC+NOAgAAMCgtBAC0AxNOAgABBBHENBAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQAJAIAMoAgAiBSAESw0AIAUgAygCBGogBEsNAwsgAygCCCIDDQALC0EAEMuAgIAAIgBBf0YNBSAIIQYCQEEAKALk04CAACIDQX9qIgQgAHFFDQAgCCAAayAEIABqQQAgA2txaiEGCyAGIAJNDQUgBkH+////B0sNBQJAQQAoAsDTgIAAIgNFDQBBACgCuNOAgAAiBCAGaiIFIARNDQYgBSADSw0GCyAGEMuAgIAAIgMgAEcNAQwHCyAGIABrIAtxIgZB/v///wdLDQQgBhDLgICAACIAIAMoAgAgAygCBGpGDQMgACEDCwJAIANBf0YNACACQcgAaiAGTQ0AAkAgByAGa0EAKALo04CAACIEakEAIARrcSIEQf7///8HTQ0AIAMhAAwHCwJAIAQQy4CAgABBf0YNACAEIAZqIQYgAyEADAcLQQAgBmsQy4CAgAAaDAQLIAMhACADQX9HDQUMAwtBACEIDAcLQQAhAAwFCyAAQX9HDQILQQBBACgCxNOAgABBBHI2AsTTgIAACyAIQf7///8HSw0BIAgQy4CAgAAhAEEAEMuAgIAAIQMgAEF/Rg0BIANBf0YNASAAIANPDQEgAyAAayIGIAJBOGpNDQELQQBBACgCuNOAgAAgBmoiAzYCuNOAgAACQCADQQAoArzTgIAATQ0AQQAgAzYCvNOAgAALAkACQAJAAkBBACgCoNCAgAAiBEUNAEHI04CAACEDA0AgACADKAIAIgUgAygCBCIIakYNAiADKAIIIgMNAAwDCwsCQAJAQQAoApjQgIAAIgNFDQAgACADTw0BC0EAIAA2ApjQgIAAC0EAIQNBACAGNgLM04CAAEEAIAA2AsjTgIAAQQBBfzYCqNCAgABBAEEAKALg04CAADYCrNCAgABBAEEANgLU04CAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgQgBkFIaiIFIANrIgNBAXI2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAIAAgBWpBODYCBAwCCyADLQAMQQhxDQAgBCAFSQ0AIAQgAE8NACAEQXggBGtBD3FBACAEQQhqQQ9xGyIFaiIAQQAoApTQgIAAIAZqIgsgBWsiBUEBcjYCBCADIAggBmo2AgRBAEEAKALw04CAADYCpNCAgABBACAFNgKU0ICAAEEAIAA2AqDQgIAAIAQgC2pBODYCBAwBCwJAIABBACgCmNCAgAAiCE8NAEEAIAA2ApjQgIAAIAAhCAsgACAGaiEFQcjTgIAAIQMCQAJAAkACQAJAAkACQANAIAMoAgAgBUYNASADKAIIIgMNAAwCCwsgAy0ADEEIcUUNAQtByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiIFIARLDQMLIAMoAgghAwwACwsgAyAANgIAIAMgAygCBCAGajYCBCAAQXggAGtBD3FBACAAQQhqQQ9xG2oiCyACQQNyNgIEIAVBeCAFa0EPcUEAIAVBCGpBD3EbaiIGIAsgAmoiAmshAwJAIAYgBEcNAEEAIAI2AqDQgIAAQQBBACgClNCAgAAgA2oiAzYClNCAgAAgAiADQQFyNgIEDAMLAkAgBkEAKAKc0ICAAEcNAEEAIAI2ApzQgIAAQQBBACgCkNCAgAAgA2oiAzYCkNCAgAAgAiADQQFyNgIEIAIgA2ogAzYCAAwDCwJAIAYoAgQiBEEDcUEBRw0AIARBeHEhBwJAAkAgBEH/AUsNACAGKAIIIgUgBEEDdiIIQQN0QbDQgIAAaiIARhoCQCAGKAIMIgQgBUcNAEEAQQAoAojQgIAAQX4gCHdxNgKI0ICAAAwCCyAEIABGGiAEIAU2AgggBSAENgIMDAELIAYoAhghCQJAAkAgBigCDCIAIAZGDQAgBigCCCIEIAhJGiAAIAQ2AgggBCAANgIMDAELAkAgBkEUaiIEKAIAIgUNACAGQRBqIgQoAgAiBQ0AQQAhAAwBCwNAIAQhCCAFIgBBFGoiBCgCACIFDQAgAEEQaiEEIAAoAhAiBQ0ACyAIQQA2AgALIAlFDQACQAJAIAYgBigCHCIFQQJ0QbjSgIAAaiIEKAIARw0AIAQgADYCACAADQFBAEEAKAKM0ICAAEF+IAV3cTYCjNCAgAAMAgsgCUEQQRQgCSgCECAGRhtqIAA2AgAgAEUNAQsgACAJNgIYAkAgBigCECIERQ0AIAAgBDYCECAEIAA2AhgLIAYoAhQiBEUNACAAQRRqIAQ2AgAgBCAANgIYCyAHIANqIQMgBiAHaiIGKAIEIQQLIAYgBEF+cTYCBCACIANqIAM2AgAgAiADQQFyNgIEAkAgA0H/AUsNACADQXhxQbDQgIAAaiEEAkACQEEAKAKI0ICAACIFQQEgA0EDdnQiA3ENAEEAIAUgA3I2AojQgIAAIAQhAwwBCyAEKAIIIQMLIAMgAjYCDCAEIAI2AgggAiAENgIMIAIgAzYCCAwDC0EfIQQCQCADQf///wdLDQAgA0EIdiIEIARBgP4/akEQdkEIcSIEdCIFIAVBgOAfakEQdkEEcSIFdCIAIABBgIAPakEQdkECcSIAdEEPdiAEIAVyIAByayIEQQF0IAMgBEEVanZBAXFyQRxqIQQLIAIgBDYCHCACQgA3AhAgBEECdEG40oCAAGohBQJAQQAoAozQgIAAIgBBASAEdCIIcQ0AIAUgAjYCAEEAIAAgCHI2AozQgIAAIAIgBTYCGCACIAI2AgggAiACNgIMDAMLIANBAEEZIARBAXZrIARBH0YbdCEEIAUoAgAhAANAIAAiBSgCBEF4cSADRg0CIARBHXYhACAEQQF0IQQgBSAAQQRxakEQaiIIKAIAIgANAAsgCCACNgIAIAIgBTYCGCACIAI2AgwgAiACNgIIDAILIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgsgBkFIaiIIIANrIgNBAXI2AgQgACAIakE4NgIEIAQgBUE3IAVrQQ9xQQAgBUFJakEPcRtqQUFqIgggCCAEQRBqSRsiCEEjNgIEQQBBACgC8NOAgAA2AqTQgIAAQQAgAzYClNCAgABBACALNgKg0ICAACAIQRBqQQApAtDTgIAANwIAIAhBACkCyNOAgAA3AghBACAIQQhqNgLQ04CAAEEAIAY2AszTgIAAQQAgADYCyNOAgABBAEEANgLU04CAACAIQSRqIQMDQCADQQc2AgAgA0EEaiIDIAVJDQALIAggBEYNAyAIIAgoAgRBfnE2AgQgCCAIIARrIgA2AgAgBCAAQQFyNgIEAkAgAEH/AUsNACAAQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgAEEDdnQiAHENAEEAIAUgAHI2AojQgIAAIAMhBQwBCyADKAIIIQULIAUgBDYCDCADIAQ2AgggBCADNgIMIAQgBTYCCAwEC0EfIQMCQCAAQf///wdLDQAgAEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCIIIAhBgIAPakEQdkECcSIIdEEPdiADIAVyIAhyayIDQQF0IAAgA0EVanZBAXFyQRxqIQMLIAQgAzYCHCAEQgA3AhAgA0ECdEG40oCAAGohBQJAQQAoAozQgIAAIghBASADdCIGcQ0AIAUgBDYCAEEAIAggBnI2AozQgIAAIAQgBTYCGCAEIAQ2AgggBCAENgIMDAQLIABBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhCANAIAgiBSgCBEF4cSAARg0DIANBHXYhCCADQQF0IQMgBSAIQQRxakEQaiIGKAIAIggNAAsgBiAENgIAIAQgBTYCGCAEIAQ2AgwgBCAENgIIDAMLIAUoAggiAyACNgIMIAUgAjYCCCACQQA2AhggAiAFNgIMIAIgAzYCCAsgC0EIaiEDDAULIAUoAggiAyAENgIMIAUgBDYCCCAEQQA2AhggBCAFNgIMIAQgAzYCCAtBACgClNCAgAAiAyACTQ0AQQAoAqDQgIAAIgQgAmoiBSADIAJrIgNBAXI2AgRBACADNgKU0ICAAEEAIAU2AqDQgIAAIAQgAkEDcjYCBCAEQQhqIQMMAwtBACEDQQBBMDYC+NOAgAAMAgsCQCALRQ0AAkACQCAIIAgoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAA2AgAgAA0BQQAgB0F+IAV3cSIHNgKM0ICAAAwCCyALQRBBFCALKAIQIAhGG2ogADYCACAARQ0BCyAAIAs2AhgCQCAIKAIQIgNFDQAgACADNgIQIAMgADYCGAsgCEEUaigCACIDRQ0AIABBFGogAzYCACADIAA2AhgLAkACQCAEQQ9LDQAgCCAEIAJqIgNBA3I2AgQgCCADaiIDIAMoAgRBAXI2AgQMAQsgCCACaiIAIARBAXI2AgQgCCACQQNyNgIEIAAgBGogBDYCAAJAIARB/wFLDQAgBEF4cUGw0ICAAGohAwJAAkBBACgCiNCAgAAiBUEBIARBA3Z0IgRxDQBBACAFIARyNgKI0ICAACADIQQMAQsgAygCCCEECyAEIAA2AgwgAyAANgIIIAAgAzYCDCAAIAQ2AggMAQtBHyEDAkAgBEH///8HSw0AIARBCHYiAyADQYD+P2pBEHZBCHEiA3QiBSAFQYDgH2pBEHZBBHEiBXQiAiACQYCAD2pBEHZBAnEiAnRBD3YgAyAFciACcmsiA0EBdCAEIANBFWp2QQFxckEcaiEDCyAAIAM2AhwgAEIANwIQIANBAnRBuNKAgABqIQUCQCAHQQEgA3QiAnENACAFIAA2AgBBACAHIAJyNgKM0ICAACAAIAU2AhggACAANgIIIAAgADYCDAwBCyAEQQBBGSADQQF2ayADQR9GG3QhAyAFKAIAIQICQANAIAIiBSgCBEF4cSAERg0BIANBHXYhAiADQQF0IQMgBSACQQRxakEQaiIGKAIAIgINAAsgBiAANgIAIAAgBTYCGCAAIAA2AgwgACAANgIIDAELIAUoAggiAyAANgIMIAUgADYCCCAAQQA2AhggACAFNgIMIAAgAzYCCAsgCEEIaiEDDAELAkAgCkUNAAJAAkAgACAAKAIcIgVBAnRBuNKAgABqIgMoAgBHDQAgAyAINgIAIAgNAUEAIAlBfiAFd3E2AozQgIAADAILIApBEEEUIAooAhAgAEYbaiAINgIAIAhFDQELIAggCjYCGAJAIAAoAhAiA0UNACAIIAM2AhAgAyAINgIYCyAAQRRqKAIAIgNFDQAgCEEUaiADNgIAIAMgCDYCGAsCQAJAIARBD0sNACAAIAQgAmoiA0EDcjYCBCAAIANqIgMgAygCBEEBcjYCBAwBCyAAIAJqIgUgBEEBcjYCBCAAIAJBA3I2AgQgBSAEaiAENgIAAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQMCQAJAQQEgB0EDdnQiCCAGcQ0AQQAgCCAGcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCADNgIMIAIgAzYCCCADIAI2AgwgAyAINgIIC0EAIAU2ApzQgIAAQQAgBDYCkNCAgAALIABBCGohAwsgAUEQaiSAgICAACADCwoAIAAQyYCAgAAL4g0BB38CQCAARQ0AIABBeGoiASAAQXxqKAIAIgJBeHEiAGohAwJAIAJBAXENACACQQNxRQ0BIAEgASgCACICayIBQQAoApjQgIAAIgRJDQEgAiAAaiEAAkAgAUEAKAKc0ICAAEYNAAJAIAJB/wFLDQAgASgCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgASgCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAwsgAiAGRhogAiAENgIIIAQgAjYCDAwCCyABKAIYIQcCQAJAIAEoAgwiBiABRg0AIAEoAggiAiAESRogBiACNgIIIAIgBjYCDAwBCwJAIAFBFGoiAigCACIEDQAgAUEQaiICKAIAIgQNAEEAIQYMAQsDQCACIQUgBCIGQRRqIgIoAgAiBA0AIAZBEGohAiAGKAIQIgQNAAsgBUEANgIACyAHRQ0BAkACQCABIAEoAhwiBEECdEG40oCAAGoiAigCAEcNACACIAY2AgAgBg0BQQBBACgCjNCAgABBfiAEd3E2AozQgIAADAMLIAdBEEEUIAcoAhAgAUYbaiAGNgIAIAZFDQILIAYgBzYCGAJAIAEoAhAiAkUNACAGIAI2AhAgAiAGNgIYCyABKAIUIgJFDQEgBkEUaiACNgIAIAIgBjYCGAwBCyADKAIEIgJBA3FBA0cNACADIAJBfnE2AgRBACAANgKQ0ICAACABIABqIAA2AgAgASAAQQFyNgIEDwsgASADTw0AIAMoAgQiAkEBcUUNAAJAAkAgAkECcQ0AAkAgA0EAKAKg0ICAAEcNAEEAIAE2AqDQgIAAQQBBACgClNCAgAAgAGoiADYClNCAgAAgASAAQQFyNgIEIAFBACgCnNCAgABHDQNBAEEANgKQ0ICAAEEAQQA2ApzQgIAADwsCQCADQQAoApzQgIAARw0AQQAgATYCnNCAgABBAEEAKAKQ0ICAACAAaiIANgKQ0ICAACABIABBAXI2AgQgASAAaiAANgIADwsgAkF4cSAAaiEAAkACQCACQf8BSw0AIAMoAggiBCACQQN2IgVBA3RBsNCAgABqIgZGGgJAIAMoAgwiAiAERw0AQQBBACgCiNCAgABBfiAFd3E2AojQgIAADAILIAIgBkYaIAIgBDYCCCAEIAI2AgwMAQsgAygCGCEHAkACQCADKAIMIgYgA0YNACADKAIIIgJBACgCmNCAgABJGiAGIAI2AgggAiAGNgIMDAELAkAgA0EUaiICKAIAIgQNACADQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQACQAJAIAMgAygCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAgsgB0EQQRQgBygCECADRhtqIAY2AgAgBkUNAQsgBiAHNgIYAkAgAygCECICRQ0AIAYgAjYCECACIAY2AhgLIAMoAhQiAkUNACAGQRRqIAI2AgAgAiAGNgIYCyABIABqIAA2AgAgASAAQQFyNgIEIAFBACgCnNCAgABHDQFBACAANgKQ0ICAAA8LIAMgAkF+cTYCBCABIABqIAA2AgAgASAAQQFyNgIECwJAIABB/wFLDQAgAEF4cUGw0ICAAGohAgJAAkBBACgCiNCAgAAiBEEBIABBA3Z0IgBxDQBBACAEIAByNgKI0ICAACACIQAMAQsgAigCCCEACyAAIAE2AgwgAiABNgIIIAEgAjYCDCABIAA2AggPC0EfIQICQCAAQf///wdLDQAgAEEIdiICIAJBgP4/akEQdkEIcSICdCIEIARBgOAfakEQdkEEcSIEdCIGIAZBgIAPakEQdkECcSIGdEEPdiACIARyIAZyayICQQF0IAAgAkEVanZBAXFyQRxqIQILIAEgAjYCHCABQgA3AhAgAkECdEG40oCAAGohBAJAAkBBACgCjNCAgAAiBkEBIAJ0IgNxDQAgBCABNgIAQQAgBiADcjYCjNCAgAAgASAENgIYIAEgATYCCCABIAE2AgwMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgBCgCACEGAkADQCAGIgQoAgRBeHEgAEYNASACQR12IQYgAkEBdCECIAQgBkEEcWpBEGoiAygCACIGDQALIAMgATYCACABIAQ2AhggASABNgIMIAEgATYCCAwBCyAEKAIIIgAgATYCDCAEIAE2AgggAUEANgIYIAEgBDYCDCABIAA2AggLQQBBACgCqNCAgABBf2oiAUF/IAEbNgKo0ICAAAsLBAAAAAtOAAJAIAANAD8AQRB0DwsCQCAAQf//A3ENACAAQX9MDQACQCAAQRB2QAAiAEF/Rw0AQQBBMDYC+NOAgABBfw8LIABBEHQPCxDKgICAAAAL8gICA38BfgJAIAJFDQAgACABOgAAIAIgAGoiA0F/aiABOgAAIAJBA0kNACAAIAE6AAIgACABOgABIANBfWogAToAACADQX5qIAE6AAAgAkEHSQ0AIAAgAToAAyADQXxqIAE6AAAgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIFayICQSBJDQAgAa1CgYCAgBB+IQYgAyAFaiEBA0AgASAGNwMYIAEgBjcDECABIAY3AwggASAGNwMAIAFBIGohASACQWBqIgJBH0sNAAsLIAALC45IAQBBgAgLhkgBAAAAAgAAAAMAAAAAAAAAAAAAAAQAAAAFAAAAAAAAAAAAAAAGAAAABwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEludmFsaWQgY2hhciBpbiB1cmwgcXVlcnkAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9ib2R5AENvbnRlbnQtTGVuZ3RoIG92ZXJmbG93AENodW5rIHNpemUgb3ZlcmZsb3cAUmVzcG9uc2Ugb3ZlcmZsb3cASW52YWxpZCBtZXRob2QgZm9yIEhUVFAveC54IHJlcXVlc3QASW52YWxpZCBtZXRob2QgZm9yIFJUU1AveC54IHJlcXVlc3QARXhwZWN0ZWQgU09VUkNFIG1ldGhvZCBmb3IgSUNFL3gueCByZXF1ZXN0AEludmFsaWQgY2hhciBpbiB1cmwgZnJhZ21lbnQgc3RhcnQARXhwZWN0ZWQgZG90AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fc3RhdHVzAEludmFsaWQgcmVzcG9uc2Ugc3RhdHVzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABEdXBsaWNhdGUgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyIGluIHVybCBwYXRoAENvbnRlbnQtTGVuZ3RoIGNhbid0IGJlIHByZXNlbnQgd2l0aCBUcmFuc2Zlci1FbmNvZGluZwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBzaXplAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX3ZhbHVlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgdmFsdWUATWlzc2luZyBleHBlY3RlZCBMRiBhZnRlciBoZWFkZXIgdmFsdWUASW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fbmFtZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIG5hbWUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAXhMAACYTAAAwEAAA8BcAAJ0TAAAVEgAAORcAAPASAAAKEAAAdRIAAK0SAACCEwAATxQAAH8QAACgFQAAIxQAAIkSAACLFAAATRUAANQRAADPFAAAEBgAAMkWAADcFgAAwREAAOAXAAC7FAAAdBQAAHwVAADlFAAACBcAAB8QAABlFQAAoxQAACgVAAACFQAAmRUAACwQAACLGQAATw8AANQOAABqEAAAzhAAAAIXAACJDgAAbhMAABwTAABmFAAAVhcAAMETAADNEwAAbBMAAGgXAABmFwAAXxcAACITAADODwAAaQ4AANgOAABjFgAAyxMAAKoOAAAoFwAAJhcAAMUTAABdFgAA6BEAAGcTAABlEwAA8hYAAHMTAAAdFwAA+RYAAPMRAADPDgAAzhUAAAwSAACzEQAApREAAGEQAAAyFwAAuxMAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIDAgICAgIAAAICAAICAAICAgICAgICAgIABAAAAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAACAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbG9zZWVlcC1hbGl2ZQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AAAAAAAAAAAAAAAAAAAByYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AAAAAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQIAAQMAAAAAAAAAAAAAAAAAAAAAAAAEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAQAAAgAAAAAAAAAAAAAAAAAAAAAAAAMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=' -var Readable = (__nccwpck_require__(1642).Readable) -var Writable = (__nccwpck_require__(1642).Writable) -var StringDecoder = (__nccwpck_require__(1576).StringDecoder) -var headers = __nccwpck_require__(8860) +/***/ }), -var DMODE = parseInt('755', 8) -var FMODE = parseInt('644', 8) +/***/ 5627: +/***/ ((module) => { -var END_OF_TAR = alloc(1024) +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCrLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AcsBygG4AckBuQHIAboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBANwBC0EAIRAMxgELQQ4hEAzFAQtBDSEQDMQBC0EPIRAMwwELQRAhEAzCAQtBEyEQDMEBC0EUIRAMwAELQRUhEAy/AQtBFiEQDL4BC0EXIRAMvQELQRghEAy8AQtBGSEQDLsBC0EaIRAMugELQRshEAy5AQtBHCEQDLgBC0EIIRAMtwELQR0hEAy2AQtBICEQDLUBC0EfIRAMtAELQQchEAyzAQtBISEQDLIBC0EiIRAMsQELQR4hEAywAQtBIyEQDK8BC0ESIRAMrgELQREhEAytAQtBJCEQDKwBC0ElIRAMqwELQSYhEAyqAQtBJyEQDKkBC0HDASEQDKgBC0EpIRAMpwELQSshEAymAQtBLCEQDKUBC0EtIRAMpAELQS4hEAyjAQtBLyEQDKIBC0HEASEQDKEBC0EwIRAMoAELQTQhEAyfAQtBDCEQDJ4BC0ExIRAMnQELQTIhEAycAQtBMyEQDJsBC0E5IRAMmgELQTUhEAyZAQtBxQEhEAyYAQtBCyEQDJcBC0E6IRAMlgELQTYhEAyVAQtBCiEQDJQBC0E3IRAMkwELQTghEAySAQtBPCEQDJEBC0E7IRAMkAELQT0hEAyPAQtBCSEQDI4BC0EoIRAMjQELQT4hEAyMAQtBPyEQDIsBC0HAACEQDIoBC0HBACEQDIkBC0HCACEQDIgBC0HDACEQDIcBC0HEACEQDIYBC0HFACEQDIUBC0HGACEQDIQBC0EqIRAMgwELQccAIRAMggELQcgAIRAMgQELQckAIRAMgAELQcoAIRAMfwtBywAhEAx+C0HNACEQDH0LQcwAIRAMfAtBzgAhEAx7C0HPACEQDHoLQdAAIRAMeQtB0QAhEAx4C0HSACEQDHcLQdMAIRAMdgtB1AAhEAx1C0HWACEQDHQLQdUAIRAMcwtBBiEQDHILQdcAIRAMcQtBBSEQDHALQdgAIRAMbwtBBCEQDG4LQdkAIRAMbQtB2gAhEAxsC0HbACEQDGsLQdwAIRAMagtBAyEQDGkLQd0AIRAMaAtB3gAhEAxnC0HfACEQDGYLQeEAIRAMZQtB4AAhEAxkC0HiACEQDGMLQeMAIRAMYgtBAiEQDGELQeQAIRAMYAtB5QAhEAxfC0HmACEQDF4LQecAIRAMXQtB6AAhEAxcC0HpACEQDFsLQeoAIRAMWgtB6wAhEAxZC0HsACEQDFgLQe0AIRAMVwtB7gAhEAxWC0HvACEQDFULQfAAIRAMVAtB8QAhEAxTC0HyACEQDFILQfMAIRAMUQtB9AAhEAxQC0H1ACEQDE8LQfYAIRAMTgtB9wAhEAxNC0H4ACEQDEwLQfkAIRAMSwtB+gAhEAxKC0H7ACEQDEkLQfwAIRAMSAtB/QAhEAxHC0H+ACEQDEYLQf8AIRAMRQtBgAEhEAxEC0GBASEQDEMLQYIBIRAMQgtBgwEhEAxBC0GEASEQDEALQYUBIRAMPwtBhgEhEAw+C0GHASEQDD0LQYgBIRAMPAtBiQEhEAw7C0GKASEQDDoLQYsBIRAMOQtBjAEhEAw4C0GNASEQDDcLQY4BIRAMNgtBjwEhEAw1C0GQASEQDDQLQZEBIRAMMwtBkgEhEAwyC0GTASEQDDELQZQBIRAMMAtBlQEhEAwvC0GWASEQDC4LQZcBIRAMLQtBmAEhEAwsC0GZASEQDCsLQZoBIRAMKgtBmwEhEAwpC0GcASEQDCgLQZ0BIRAMJwtBngEhEAwmC0GfASEQDCULQaABIRAMJAtBoQEhEAwjC0GiASEQDCILQaMBIRAMIQtBpAEhEAwgC0GlASEQDB8LQaYBIRAMHgtBpwEhEAwdC0GoASEQDBwLQakBIRAMGwtBqgEhEAwaC0GrASEQDBkLQawBIRAMGAtBrQEhEAwXC0GuASEQDBYLQQEhEAwVC0GvASEQDBQLQbABIRAMEwtBsQEhEAwSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB4fICEjJSg/QEFERUZHSElKS0xNT1BRUlPeA1dZW1xdYGJlZmdoaWprbG1vcHFyc3R1dnd4eXp7fH1+gAGCAYUBhgGHAYkBiwGMAY0BjgGPAZABkQGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwG4AbkBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgHHAcgByQHKAcsBzAHNAc4BzwHQAdEB0gHTAdQB1QHWAdcB2AHZAdoB2wHcAd0B3gHgAeEB4gHjAeQB5QHmAecB6AHpAeoB6wHsAe0B7gHvAfAB8QHyAfMBmQKkArAC/gL+AgsgASIEIAJHDfMBQd0BIRAM/wMLIAEiECACRw3dAUHDASEQDP4DCyABIgEgAkcNkAFB9wAhEAz9AwsgASIBIAJHDYYBQe8AIRAM/AMLIAEiASACRw1/QeoAIRAM+wMLIAEiASACRw17QegAIRAM+gMLIAEiASACRw14QeYAIRAM+QMLIAEiASACRw0aQRghEAz4AwsgASIBIAJHDRRBEiEQDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg0AIABBi4CAgAA2AgggACABNgIEIAEhAUEHIRAMxAMLQRkhEAzcAwsgAUEBaiEBDAILAkAgASIUIAJHDQBBGiEQDNsDCyAUIQECQCAULQAAQXNqDhTdAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAgDuAgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQM2gMLAkAgAS0AACIQQTtGDQAgEEENRw3oASABQQFqIQEM5QILIAFBAWohAQtBIiEQDL8DCwJAIAEiECACRw0AQRwhEAzYAwtCACERIBAhASAQLQAAQVBqDjfnAeYBAQIDBAUGBwgAAAAAAAAACQoLDA0OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPEBESExQAC0EeIRAMvQMLQgIhEQzlAQtCAyERDOQBC0IEIREM4wELQgUhEQziAQtCBiERDOEBC0IHIREM4AELQgghEQzfAQtCCSERDN4BC0IKIREM3QELQgshEQzcAQtCDCERDNsBC0INIREM2gELQg4hEQzZAQtCDyERDNgBC0IKIREM1wELQgshEQzWAQtCDCERDNUBC0INIREM1AELQg4hEQzTAQtCDyERDNIBC0IAIRECQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAtAABBUGoON+UB5AEAAQIDBAUGB+YB5gHmAeYB5gHmAeYBCAkKCwwN5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAQ4PEBESE+YBC0ICIREM5AELQgMhEQzjAQtCBCERDOIBC0IFIREM4QELQgYhEQzgAQtCByERDN8BC0IIIREM3gELQgkhEQzdAQtCCiERDNwBC0ILIREM2wELQgwhEQzaAQtCDSERDNkBC0IOIREM2AELQg8hEQzXAQtCCiERDNYBC0ILIREM1QELQgwhEQzUAQtCDSERDNMBC0IOIREM0gELQg8hEQzRAQsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3SAUEfIRAMwAMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQSQhEAynAwtBICEQDL8DCyAAIAEiECACEL6AgIAAQX9qDgW2AQDFAgHRAdIBC0ERIRAMpAMLIABBAToALyAQIQEMuwMLIAEiASACRw3SAUEkIRAMuwMLIAEiDSACRw0eQcYAIRAMugMLIAAgASIBIAIQsoCAgAAiEA3UASABIQEMtQELIAEiECACRw0mQdAAIRAMuAMLAkAgASIBIAJHDQBBKCEQDLgDCyAAQQA2AgQgAEGMgICAADYCCCAAIAEgARCxgICAACIQDdMBIAEhAQzYAQsCQCABIhAgAkcNAEEpIRAMtwMLIBAtAAAiAUEgRg0UIAFBCUcN0wEgEEEBaiEBDBULAkAgASIBIAJGDQAgAUEBaiEBDBcLQSohEAy1AwsCQCABIhAgAkcNAEErIRAMtQMLAkAgEC0AACIBQQlGDQAgAUEgRw3VAQsgAC0ALEEIRg3TASAQIQEMkQMLAkAgASIBIAJHDQBBLCEQDLQDCyABLQAAQQpHDdUBIAFBAWohAQzJAgsgASIOIAJHDdUBQS8hEAyyAwsDQAJAIAEtAAAiEEEgRg0AAkAgEEF2ag4EANwB3AEA2gELIAEhAQzgAQsgAUEBaiIBIAJHDQALQTEhEAyxAwtBMiEQIAEiFCACRg2wAyACIBRrIAAoAgAiAWohFSAUIAFrQQNqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB8LuAgABqLQAARw0BAkAgAUEDRw0AQQYhAQyWAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMsQMLIABBADYCACAUIQEM2QELQTMhECABIhQgAkYNrwMgAiAUayAAKAIAIgFqIRUgFCABa0EIaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfS7gIAAai0AAEcNAQJAIAFBCEcNAEEFIQEMlQMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLADCyAAQQA2AgAgFCEBDNgBC0E0IRAgASIUIAJGDa4DIAIgFGsgACgCACIBaiEVIBQgAWtBBWohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUHQwoCAAGotAABHDQECQCABQQVHDQBBByEBDJQDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAyvAwsgAEEANgIAIBQhAQzXAQsCQCABIgEgAkYNAANAAkAgAS0AAEGAvoCAAGotAAAiEEEBRg0AIBBBAkYNCiABIQEM3QELIAFBAWoiASACRw0AC0EwIRAMrgMLQTAhEAytAwsCQCABIgEgAkYNAANAAkAgAS0AACIQQSBGDQAgEEF2ag4E2QHaAdoB2QHaAQsgAUEBaiIBIAJHDQALQTghEAytAwtBOCEQDKwDCwNAAkAgAS0AACIQQSBGDQAgEEEJRw0DCyABQQFqIgEgAkcNAAtBPCEQDKsDCwNAAkAgAS0AACIQQSBGDQACQAJAIBBBdmoOBNoBAQHaAQALIBBBLEYN2wELIAEhAQwECyABQQFqIgEgAkcNAAtBPyEQDKoDCyABIQEM2wELQcAAIRAgASIUIAJGDagDIAIgFGsgACgCACIBaiEWIBQgAWtBBmohFwJAA0AgFC0AAEEgciABQYDAgIAAai0AAEcNASABQQZGDY4DIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADKkDCyAAQQA2AgAgFCEBC0E2IRAMjgMLAkAgASIPIAJHDQBBwQAhEAynAwsgAEGMgICAADYCCCAAIA82AgQgDyEBIAAtACxBf2oOBM0B1QHXAdkBhwMLIAFBAWohAQzMAQsCQCABIgEgAkYNAANAAkAgAS0AACIQQSByIBAgEEG/f2pB/wFxQRpJG0H/AXEiEEEJRg0AIBBBIEYNAAJAAkACQAJAIBBBnX9qDhMAAwMDAwMDAwEDAwMDAwMDAwMCAwsgAUEBaiEBQTEhEAyRAwsgAUEBaiEBQTIhEAyQAwsgAUEBaiEBQTMhEAyPAwsgASEBDNABCyABQQFqIgEgAkcNAAtBNSEQDKUDC0E1IRAMpAMLAkAgASIBIAJGDQADQAJAIAEtAABBgLyAgABqLQAAQQFGDQAgASEBDNMBCyABQQFqIgEgAkcNAAtBPSEQDKQDC0E9IRAMowMLIAAgASIBIAIQsICAgAAiEA3WASABIQEMAQsgEEEBaiEBC0E8IRAMhwMLAkAgASIBIAJHDQBBwgAhEAygAwsCQANAAkAgAS0AAEF3ag4YAAL+Av4ChAP+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gIA/gILIAFBAWoiASACRw0AC0HCACEQDKADCyABQQFqIQEgAC0ALUEBcUUNvQEgASEBC0EsIRAMhQMLIAEiASACRw3TAUHEACEQDJ0DCwNAAkAgAS0AAEGQwICAAGotAABBAUYNACABIQEMtwILIAFBAWoiASACRw0AC0HFACEQDJwDCyANLQAAIhBBIEYNswEgEEE6Rw2BAyAAKAIEIQEgAEEANgIEIAAgASANEK+AgIAAIgEN0AEgDUEBaiEBDLMCC0HHACEQIAEiDSACRg2aAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQZDCgIAAai0AAEcNgAMgAUEFRg30AiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyaAwtByAAhECABIg0gAkYNmQMgAiANayAAKAIAIgFqIRYgDSABa0EJaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGWwoCAAGotAABHDf8CAkAgAUEJRw0AQQIhAQz1AgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmQMLAkAgASINIAJHDQBByQAhEAyZAwsCQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZJ/ag4HAIADgAOAA4ADgAMBgAMLIA1BAWohAUE+IRAMgAMLIA1BAWohAUE/IRAM/wILQcoAIRAgASINIAJGDZcDIAIgDWsgACgCACIBaiEWIA0gAWtBAWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBoMKAgABqLQAARw39AiABQQFGDfACIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJcDC0HLACEQIAEiDSACRg2WAyACIA1rIAAoAgAiAWohFiANIAFrQQ5qIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaLCgIAAai0AAEcN/AIgAUEORg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyWAwtBzAAhECABIg0gAkYNlQMgAiANayAAKAIAIgFqIRYgDSABa0EPaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUHAwoCAAGotAABHDfsCAkAgAUEPRw0AQQMhAQzxAgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlQMLQc0AIRAgASINIAJGDZQDIAIgDWsgACgCACIBaiEWIA0gAWtBBWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw36AgJAIAFBBUcNAEEEIQEM8AILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJQDCwJAIAEiDSACRw0AQc4AIRAMlAMLAkACQAJAAkAgDS0AACIBQSByIAEgAUG/f2pB/wFxQRpJG0H/AXFBnX9qDhMA/QL9Av0C/QL9Av0C/QL9Av0C/QL9Av0CAf0C/QL9AgID/QILIA1BAWohAUHBACEQDP0CCyANQQFqIQFBwgAhEAz8AgsgDUEBaiEBQcMAIRAM+wILIA1BAWohAUHEACEQDPoCCwJAIAEiASACRg0AIABBjYCAgAA2AgggACABNgIEIAEhAUHFACEQDPoCC0HPACEQDJIDCyAQIQECQAJAIBAtAABBdmoOBAGoAqgCAKgCCyAQQQFqIQELQSchEAz4AgsCQCABIgEgAkcNAEHRACEQDJEDCwJAIAEtAABBIEYNACABIQEMjQELIAFBAWohASAALQAtQQFxRQ3HASABIQEMjAELIAEiFyACRw3IAUHSACEQDI8DC0HTACEQIAEiFCACRg2OAyACIBRrIAAoAgAiAWohFiAUIAFrQQFqIRcDQCAULQAAIAFB1sKAgABqLQAARw3MASABQQFGDccBIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADI4DCwJAIAEiASACRw0AQdUAIRAMjgMLIAEtAABBCkcNzAEgAUEBaiEBDMcBCwJAIAEiASACRw0AQdYAIRAMjQMLAkACQCABLQAAQXZqDgQAzQHNAQHNAQsgAUEBaiEBDMcBCyABQQFqIQFBygAhEAzzAgsgACABIgEgAhCugICAACIQDcsBIAEhAUHNACEQDPICCyAALQApQSJGDYUDDKYCCwJAIAEiASACRw0AQdsAIRAMigMLQQAhFEEBIRdBASEWQQAhEAJAAkACQAJAAkACQAJAAkACQCABLQAAQVBqDgrUAdMBAAECAwQFBgjVAQtBAiEQDAYLQQMhEAwFC0EEIRAMBAtBBSEQDAMLQQYhEAwCC0EHIRAMAQtBCCEQC0EAIRdBACEWQQAhFAzMAQtBCSEQQQEhFEEAIRdBACEWDMsBCwJAIAEiASACRw0AQd0AIRAMiQMLIAEtAABBLkcNzAEgAUEBaiEBDKYCCyABIgEgAkcNzAFB3wAhEAyHAwsCQCABIgEgAkYNACAAQY6AgIAANgIIIAAgATYCBCABIQFB0AAhEAzuAgtB4AAhEAyGAwtB4QAhECABIgEgAkYNhQMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQeLCgIAAai0AAEcNzQEgFEEDRg3MASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyFAwtB4gAhECABIgEgAkYNhAMgAiABayAAKAIAIhRqIRYgASAUa0ECaiEXA0AgAS0AACAUQebCgIAAai0AAEcNzAEgFEECRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyEAwtB4wAhECABIgEgAkYNgwMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQenCgIAAai0AAEcNywEgFEEDRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyDAwsCQCABIgEgAkcNAEHlACEQDIMDCyAAIAFBAWoiASACEKiAgIAAIhANzQEgASEBQdYAIRAM6QILAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AAkACQAJAIBBBuH9qDgsAAc8BzwHPAc8BzwHPAc8BzwECzwELIAFBAWohAUHSACEQDO0CCyABQQFqIQFB0wAhEAzsAgsgAUEBaiEBQdQAIRAM6wILIAFBAWoiASACRw0AC0HkACEQDIIDC0HkACEQDIEDCwNAAkAgAS0AAEHwwoCAAGotAAAiEEEBRg0AIBBBfmoOA88B0AHRAdIBCyABQQFqIgEgAkcNAAtB5gAhEAyAAwsCQCABIgEgAkYNACABQQFqIQEMAwtB5wAhEAz/AgsDQAJAIAEtAABB8MSAgABqLQAAIhBBAUYNAAJAIBBBfmoOBNIB0wHUAQDVAQsgASEBQdcAIRAM5wILIAFBAWoiASACRw0AC0HoACEQDP4CCwJAIAEiASACRw0AQekAIRAM/gILAkAgAS0AACIQQXZqDhq6AdUB1QG8AdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAcoB1QHVAQDTAQsgAUEBaiEBC0EGIRAM4wILA0ACQCABLQAAQfDGgIAAai0AAEEBRg0AIAEhAQyeAgsgAUEBaiIBIAJHDQALQeoAIRAM+wILAkAgASIBIAJGDQAgAUEBaiEBDAMLQesAIRAM+gILAkAgASIBIAJHDQBB7AAhEAz6AgsgAUEBaiEBDAELAkAgASIBIAJHDQBB7QAhEAz5AgsgAUEBaiEBC0EEIRAM3gILAkAgASIUIAJHDQBB7gAhEAz3AgsgFCEBAkACQAJAIBQtAABB8MiAgABqLQAAQX9qDgfUAdUB1gEAnAIBAtcBCyAUQQFqIQEMCgsgFEEBaiEBDM0BC0EAIRAgAEEANgIcIABBm5KAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAz2AgsCQANAAkAgAS0AAEHwyICAAGotAAAiEEEERg0AAkACQCAQQX9qDgfSAdMB1AHZAQAEAdkBCyABIQFB2gAhEAzgAgsgAUEBaiEBQdwAIRAM3wILIAFBAWoiASACRw0AC0HvACEQDPYCCyABQQFqIQEMywELAkAgASIUIAJHDQBB8AAhEAz1AgsgFC0AAEEvRw3UASAUQQFqIQEMBgsCQCABIhQgAkcNAEHxACEQDPQCCwJAIBQtAAAiAUEvRw0AIBRBAWohAUHdACEQDNsCCyABQXZqIgRBFksN0wFBASAEdEGJgIACcUUN0wEMygILAkAgASIBIAJGDQAgAUEBaiEBQd4AIRAM2gILQfIAIRAM8gILAkAgASIUIAJHDQBB9AAhEAzyAgsgFCEBAkAgFC0AAEHwzICAAGotAABBf2oOA8kClAIA1AELQeEAIRAM2AILAkAgASIUIAJGDQADQAJAIBQtAABB8MqAgABqLQAAIgFBA0YNAAJAIAFBf2oOAssCANUBCyAUIQFB3wAhEAzaAgsgFEEBaiIUIAJHDQALQfMAIRAM8QILQfMAIRAM8AILAkAgASIBIAJGDQAgAEGPgICAADYCCCAAIAE2AgQgASEBQeAAIRAM1wILQfUAIRAM7wILAkAgASIBIAJHDQBB9gAhEAzvAgsgAEGPgICAADYCCCAAIAE2AgQgASEBC0EDIRAM1AILA0AgAS0AAEEgRw3DAiABQQFqIgEgAkcNAAtB9wAhEAzsAgsCQCABIgEgAkcNAEH4ACEQDOwCCyABLQAAQSBHDc4BIAFBAWohAQzvAQsgACABIgEgAhCsgICAACIQDc4BIAEhAQyOAgsCQCABIgQgAkcNAEH6ACEQDOoCCyAELQAAQcwARw3RASAEQQFqIQFBEyEQDM8BCwJAIAEiBCACRw0AQfsAIRAM6QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEANAIAQtAAAgAUHwzoCAAGotAABHDdABIAFBBUYNzgEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBB+wAhEAzoAgsCQCABIgQgAkcNAEH8ACEQDOgCCwJAAkAgBC0AAEG9f2oODADRAdEB0QHRAdEB0QHRAdEB0QHRAQHRAQsgBEEBaiEBQeYAIRAMzwILIARBAWohAUHnACEQDM4CCwJAIAEiBCACRw0AQf0AIRAM5wILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNzwEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf0AIRAM5wILIABBADYCACAQQQFqIQFBECEQDMwBCwJAIAEiBCACRw0AQf4AIRAM5gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQfbOgIAAai0AAEcNzgEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf4AIRAM5gILIABBADYCACAQQQFqIQFBFiEQDMsBCwJAIAEiBCACRw0AQf8AIRAM5QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQfzOgIAAai0AAEcNzQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf8AIRAM5QILIABBADYCACAQQQFqIQFBBSEQDMoBCwJAIAEiBCACRw0AQYABIRAM5AILIAQtAABB2QBHDcsBIARBAWohAUEIIRAMyQELAkAgASIEIAJHDQBBgQEhEAzjAgsCQAJAIAQtAABBsn9qDgMAzAEBzAELIARBAWohAUHrACEQDMoCCyAEQQFqIQFB7AAhEAzJAgsCQCABIgQgAkcNAEGCASEQDOICCwJAAkAgBC0AAEG4f2oOCADLAcsBywHLAcsBywEBywELIARBAWohAUHqACEQDMkCCyAEQQFqIQFB7QAhEAzIAgsCQCABIgQgAkcNAEGDASEQDOECCyACIARrIAAoAgAiAWohECAEIAFrQQJqIRQCQANAIAQtAAAgAUGAz4CAAGotAABHDckBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgEDYCAEGDASEQDOECC0EAIRAgAEEANgIAIBRBAWohAQzGAQsCQCABIgQgAkcNAEGEASEQDOACCyACIARrIAAoAgAiAWohFCAEIAFrQQRqIRACQANAIAQtAAAgAUGDz4CAAGotAABHDcgBIAFBBEYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGEASEQDOACCyAAQQA2AgAgEEEBaiEBQSMhEAzFAQsCQCABIgQgAkcNAEGFASEQDN8CCwJAAkAgBC0AAEG0f2oOCADIAcgByAHIAcgByAEByAELIARBAWohAUHvACEQDMYCCyAEQQFqIQFB8AAhEAzFAgsCQCABIgQgAkcNAEGGASEQDN4CCyAELQAAQcUARw3FASAEQQFqIQEMgwILAkAgASIEIAJHDQBBhwEhEAzdAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBiM+AgABqLQAARw3FASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhwEhEAzdAgsgAEEANgIAIBBBAWohAUEtIRAMwgELAkAgASIEIAJHDQBBiAEhEAzcAgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw3EASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiAEhEAzcAgsgAEEANgIAIBBBAWohAUEpIRAMwQELAkAgASIBIAJHDQBBiQEhEAzbAgtBASEQIAEtAABB3wBHDcABIAFBAWohAQyBAgsCQCABIgQgAkcNAEGKASEQDNoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRADQCAELQAAIAFBjM+AgABqLQAARw3BASABQQFGDa8CIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYoBIRAM2QILAkAgASIEIAJHDQBBiwEhEAzZAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBjs+AgABqLQAARw3BASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiwEhEAzZAgsgAEEANgIAIBBBAWohAUECIRAMvgELAkAgASIEIAJHDQBBjAEhEAzYAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw3AASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjAEhEAzYAgsgAEEANgIAIBBBAWohAUEfIRAMvQELAkAgASIEIAJHDQBBjQEhEAzXAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8s+AgABqLQAARw2/ASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjQEhEAzXAgsgAEEANgIAIBBBAWohAUEJIRAMvAELAkAgASIEIAJHDQBBjgEhEAzWAgsCQAJAIAQtAABBt39qDgcAvwG/Ab8BvwG/AQG/AQsgBEEBaiEBQfgAIRAMvQILIARBAWohAUH5ACEQDLwCCwJAIAEiBCACRw0AQY8BIRAM1QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQZHPgIAAai0AAEcNvQEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY8BIRAM1QILIABBADYCACAQQQFqIQFBGCEQDLoBCwJAIAEiBCACRw0AQZABIRAM1AILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQZfPgIAAai0AAEcNvAEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZABIRAM1AILIABBADYCACAQQQFqIQFBFyEQDLkBCwJAIAEiBCACRw0AQZEBIRAM0wILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQZrPgIAAai0AAEcNuwEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZEBIRAM0wILIABBADYCACAQQQFqIQFBFSEQDLgBCwJAIAEiBCACRw0AQZIBIRAM0gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQaHPgIAAai0AAEcNugEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZIBIRAM0gILIABBADYCACAQQQFqIQFBHiEQDLcBCwJAIAEiBCACRw0AQZMBIRAM0QILIAQtAABBzABHDbgBIARBAWohAUEKIRAMtgELAkAgBCACRw0AQZQBIRAM0AILAkACQCAELQAAQb9/ag4PALkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AbkBAbkBCyAEQQFqIQFB/gAhEAy3AgsgBEEBaiEBQf8AIRAMtgILAkAgBCACRw0AQZUBIRAMzwILAkACQCAELQAAQb9/ag4DALgBAbgBCyAEQQFqIQFB/QAhEAy2AgsgBEEBaiEEQYABIRAMtQILAkAgBCACRw0AQZYBIRAMzgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQafPgIAAai0AAEcNtgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZYBIRAMzgILIABBADYCACAQQQFqIQFBCyEQDLMBCwJAIAQgAkcNAEGXASEQDM0CCwJAAkACQAJAIAQtAABBU2oOIwC4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBAbgBuAG4AbgBuAECuAG4AbgBA7gBCyAEQQFqIQFB+wAhEAy2AgsgBEEBaiEBQfwAIRAMtQILIARBAWohBEGBASEQDLQCCyAEQQFqIQRBggEhEAyzAgsCQCAEIAJHDQBBmAEhEAzMAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBqc+AgABqLQAARw20ASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmAEhEAzMAgsgAEEANgIAIBBBAWohAUEZIRAMsQELAkAgBCACRw0AQZkBIRAMywILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQa7PgIAAai0AAEcNswEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZkBIRAMywILIABBADYCACAQQQFqIQFBBiEQDLABCwJAIAQgAkcNAEGaASEQDMoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG0z4CAAGotAABHDbIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGaASEQDMoCCyAAQQA2AgAgEEEBaiEBQRwhEAyvAQsCQCAEIAJHDQBBmwEhEAzJAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBts+AgABqLQAARw2xASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmwEhEAzJAgsgAEEANgIAIBBBAWohAUEnIRAMrgELAkAgBCACRw0AQZwBIRAMyAILAkACQCAELQAAQax/ag4CAAGxAQsgBEEBaiEEQYYBIRAMrwILIARBAWohBEGHASEQDK4CCwJAIAQgAkcNAEGdASEQDMcCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG4z4CAAGotAABHDa8BIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGdASEQDMcCCyAAQQA2AgAgEEEBaiEBQSYhEAysAQsCQCAEIAJHDQBBngEhEAzGAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBus+AgABqLQAARw2uASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBngEhEAzGAgsgAEEANgIAIBBBAWohAUEDIRAMqwELAkAgBCACRw0AQZ8BIRAMxQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNrQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ8BIRAMxQILIABBADYCACAQQQFqIQFBDCEQDKoBCwJAIAQgAkcNAEGgASEQDMQCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUG8z4CAAGotAABHDawBIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGgASEQDMQCCyAAQQA2AgAgEEEBaiEBQQ0hEAypAQsCQCAEIAJHDQBBoQEhEAzDAgsCQAJAIAQtAABBun9qDgsArAGsAawBrAGsAawBrAGsAawBAawBCyAEQQFqIQRBiwEhEAyqAgsgBEEBaiEEQYwBIRAMqQILAkAgBCACRw0AQaIBIRAMwgILIAQtAABB0ABHDakBIARBAWohBAzpAQsCQCAEIAJHDQBBowEhEAzBAgsCQAJAIAQtAABBt39qDgcBqgGqAaoBqgGqAQCqAQsgBEEBaiEEQY4BIRAMqAILIARBAWohAUEiIRAMpgELAkAgBCACRw0AQaQBIRAMwAILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQcDPgIAAai0AAEcNqAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaQBIRAMwAILIABBADYCACAQQQFqIQFBHSEQDKUBCwJAIAQgAkcNAEGlASEQDL8CCwJAAkAgBC0AAEGuf2oOAwCoAQGoAQsgBEEBaiEEQZABIRAMpgILIARBAWohAUEEIRAMpAELAkAgBCACRw0AQaYBIRAMvgILAkACQAJAAkACQCAELQAAQb9/ag4VAKoBqgGqAaoBqgGqAaoBqgGqAaoBAaoBqgECqgGqAQOqAaoBBKoBCyAEQQFqIQRBiAEhEAyoAgsgBEEBaiEEQYkBIRAMpwILIARBAWohBEGKASEQDKYCCyAEQQFqIQRBjwEhEAylAgsgBEEBaiEEQZEBIRAMpAILAkAgBCACRw0AQacBIRAMvQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNpQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQacBIRAMvQILIABBADYCACAQQQFqIQFBESEQDKIBCwJAIAQgAkcNAEGoASEQDLwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHCz4CAAGotAABHDaQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGoASEQDLwCCyAAQQA2AgAgEEEBaiEBQSwhEAyhAQsCQCAEIAJHDQBBqQEhEAy7AgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBxc+AgABqLQAARw2jASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqQEhEAy7AgsgAEEANgIAIBBBAWohAUErIRAMoAELAkAgBCACRw0AQaoBIRAMugILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQcrPgIAAai0AAEcNogEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaoBIRAMugILIABBADYCACAQQQFqIQFBFCEQDJ8BCwJAIAQgAkcNAEGrASEQDLkCCwJAAkACQAJAIAQtAABBvn9qDg8AAQKkAaQBpAGkAaQBpAGkAaQBpAGkAaQBA6QBCyAEQQFqIQRBkwEhEAyiAgsgBEEBaiEEQZQBIRAMoQILIARBAWohBEGVASEQDKACCyAEQQFqIQRBlgEhEAyfAgsCQCAEIAJHDQBBrAEhEAy4AgsgBC0AAEHFAEcNnwEgBEEBaiEEDOABCwJAIAQgAkcNAEGtASEQDLcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHNz4CAAGotAABHDZ8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGtASEQDLcCCyAAQQA2AgAgEEEBaiEBQQ4hEAycAQsCQCAEIAJHDQBBrgEhEAy2AgsgBC0AAEHQAEcNnQEgBEEBaiEBQSUhEAybAQsCQCAEIAJHDQBBrwEhEAy1AgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw2dASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrwEhEAy1AgsgAEEANgIAIBBBAWohAUEqIRAMmgELAkAgBCACRw0AQbABIRAMtAILAkACQCAELQAAQat/ag4LAJ0BnQGdAZ0BnQGdAZ0BnQGdAQGdAQsgBEEBaiEEQZoBIRAMmwILIARBAWohBEGbASEQDJoCCwJAIAQgAkcNAEGxASEQDLMCCwJAAkAgBC0AAEG/f2oOFACcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAEBnAELIARBAWohBEGZASEQDJoCCyAEQQFqIQRBnAEhEAyZAgsCQCAEIAJHDQBBsgEhEAyyAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFB2c+AgABqLQAARw2aASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBsgEhEAyyAgsgAEEANgIAIBBBAWohAUEhIRAMlwELAkAgBCACRw0AQbMBIRAMsQILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQd3PgIAAai0AAEcNmQEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbMBIRAMsQILIABBADYCACAQQQFqIQFBGiEQDJYBCwJAIAQgAkcNAEG0ASEQDLACCwJAAkACQCAELQAAQbt/ag4RAJoBmgGaAZoBmgGaAZoBmgGaAQGaAZoBmgGaAZoBApoBCyAEQQFqIQRBnQEhEAyYAgsgBEEBaiEEQZ4BIRAMlwILIARBAWohBEGfASEQDJYCCwJAIAQgAkcNAEG1ASEQDK8CCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUHkz4CAAGotAABHDZcBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG1ASEQDK8CCyAAQQA2AgAgEEEBaiEBQSghEAyUAQsCQCAEIAJHDQBBtgEhEAyuAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB6s+AgABqLQAARw2WASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtgEhEAyuAgsgAEEANgIAIBBBAWohAUEHIRAMkwELAkAgBCACRw0AQbcBIRAMrQILAkACQCAELQAAQbt/ag4OAJYBlgGWAZYBlgGWAZYBlgGWAZYBlgGWAQGWAQsgBEEBaiEEQaEBIRAMlAILIARBAWohBEGiASEQDJMCCwJAIAQgAkcNAEG4ASEQDKwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDZQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG4ASEQDKwCCyAAQQA2AgAgEEEBaiEBQRIhEAyRAQsCQCAEIAJHDQBBuQEhEAyrAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw2TASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuQEhEAyrAgsgAEEANgIAIBBBAWohAUEgIRAMkAELAkAgBCACRw0AQboBIRAMqgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNkgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQboBIRAMqgILIABBADYCACAQQQFqIQFBDyEQDI8BCwJAIAQgAkcNAEG7ASEQDKkCCwJAAkAgBC0AAEG3f2oOBwCSAZIBkgGSAZIBAZIBCyAEQQFqIQRBpQEhEAyQAgsgBEEBaiEEQaYBIRAMjwILAkAgBCACRw0AQbwBIRAMqAILIAIgBGsgACgCACIBaiEUIAQgAWtBB2ohEAJAA0AgBC0AACABQfTPgIAAai0AAEcNkAEgAUEHRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbwBIRAMqAILIABBADYCACAQQQFqIQFBGyEQDI0BCwJAIAQgAkcNAEG9ASEQDKcCCwJAAkACQCAELQAAQb5/ag4SAJEBkQGRAZEBkQGRAZEBkQGRAQGRAZEBkQGRAZEBkQECkQELIARBAWohBEGkASEQDI8CCyAEQQFqIQRBpwEhEAyOAgsgBEEBaiEEQagBIRAMjQILAkAgBCACRw0AQb4BIRAMpgILIAQtAABBzgBHDY0BIARBAWohBAzPAQsCQCAEIAJHDQBBvwEhEAylAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAELQAAQb9/ag4VAAECA5wBBAUGnAGcAZwBBwgJCgucAQwNDg+cAQsgBEEBaiEBQegAIRAMmgILIARBAWohAUHpACEQDJkCCyAEQQFqIQFB7gAhEAyYAgsgBEEBaiEBQfIAIRAMlwILIARBAWohAUHzACEQDJYCCyAEQQFqIQFB9gAhEAyVAgsgBEEBaiEBQfcAIRAMlAILIARBAWohAUH6ACEQDJMCCyAEQQFqIQRBgwEhEAySAgsgBEEBaiEEQYQBIRAMkQILIARBAWohBEGFASEQDJACCyAEQQFqIQRBkgEhEAyPAgsgBEEBaiEEQZgBIRAMjgILIARBAWohBEGgASEQDI0CCyAEQQFqIQRBowEhEAyMAgsgBEEBaiEEQaoBIRAMiwILAkAgBCACRg0AIABBkICAgAA2AgggACAENgIEQasBIRAMiwILQcABIRAMowILIAAgBSACEKqAgIAAIgENiwEgBSEBDFwLAkAgBiACRg0AIAZBAWohBQyNAQtBwgEhEAyhAgsDQAJAIBAtAABBdmoOBIwBAACPAQALIBBBAWoiECACRw0AC0HDASEQDKACCwJAIAcgAkYNACAAQZGAgIAANgIIIAAgBzYCBCAHIQFBASEQDIcCC0HEASEQDJ8CCwJAIAcgAkcNAEHFASEQDJ8CCwJAAkAgBy0AAEF2ag4EAc4BzgEAzgELIAdBAWohBgyNAQsgB0EBaiEFDIkBCwJAIAcgAkcNAEHGASEQDJ4CCwJAAkAgBy0AAEF2ag4XAY8BjwEBjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAI8BCyAHQQFqIQcLQbABIRAMhAILAkAgCCACRw0AQcgBIRAMnQILIAgtAABBIEcNjQEgAEEAOwEyIAhBAWohAUGzASEQDIMCCyABIRcCQANAIBciByACRg0BIActAABBUGpB/wFxIhBBCk8NzAECQCAALwEyIhRBmTNLDQAgACAUQQpsIhQ7ATIgEEH//wNzIBRB/v8DcUkNACAHQQFqIRcgACAUIBBqIhA7ATIgEEH//wNxQegHSQ0BCwtBACEQIABBADYCHCAAQcGJgIAANgIQIABBDTYCDCAAIAdBAWo2AhQMnAILQccBIRAMmwILIAAgCCACEK6AgIAAIhBFDcoBIBBBFUcNjAEgAEHIATYCHCAAIAg2AhQgAEHJl4CAADYCECAAQRU2AgxBACEQDJoCCwJAIAkgAkcNAEHMASEQDJoCC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgCS0AAEFQag4KlgGVAQABAgMEBQYIlwELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMjgELQQkhEEEBIRRBACEXQQAhFgyNAQsCQCAKIAJHDQBBzgEhEAyZAgsgCi0AAEEuRw2OASAKQQFqIQkMygELIAsgAkcNjgFB0AEhEAyXAgsCQCALIAJGDQAgAEGOgICAADYCCCAAIAs2AgRBtwEhEAz+AQtB0QEhEAyWAgsCQCAEIAJHDQBB0gEhEAyWAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EEaiELA0AgBC0AACAQQfzPgIAAai0AAEcNjgEgEEEERg3pASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHSASEQDJUCCyAAIAwgAhCsgICAACIBDY0BIAwhAQy4AQsCQCAEIAJHDQBB1AEhEAyUAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EBaiEMA0AgBC0AACAQQYHQgIAAai0AAEcNjwEgEEEBRg2OASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHUASEQDJMCCwJAIAQgAkcNAEHWASEQDJMCCyACIARrIAAoAgAiEGohFCAEIBBrQQJqIQsDQCAELQAAIBBBg9CAgABqLQAARw2OASAQQQJGDZABIBBBAWohECAEQQFqIgQgAkcNAAsgACAUNgIAQdYBIRAMkgILAkAgBCACRw0AQdcBIRAMkgILAkACQCAELQAAQbt/ag4QAI8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwEBjwELIARBAWohBEG7ASEQDPkBCyAEQQFqIQRBvAEhEAz4AQsCQCAEIAJHDQBB2AEhEAyRAgsgBC0AAEHIAEcNjAEgBEEBaiEEDMQBCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEG+ASEQDPcBC0HZASEQDI8CCwJAIAQgAkcNAEHaASEQDI8CCyAELQAAQcgARg3DASAAQQE6ACgMuQELIABBAjoALyAAIAQgAhCmgICAACIQDY0BQcIBIRAM9AELIAAtAChBf2oOArcBuQG4AQsDQAJAIAQtAABBdmoOBACOAY4BAI4BCyAEQQFqIgQgAkcNAAtB3QEhEAyLAgsgAEEAOgAvIAAtAC1BBHFFDYQCCyAAQQA6AC8gAEEBOgA0IAEhAQyMAQsgEEEVRg3aASAAQQA2AhwgACABNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAyIAgsCQCAAIBAgAhC0gICAACIEDQAgECEBDIECCwJAIARBFUcNACAAQQM2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAyIAgsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMhwILIBBBFUYN1gEgAEEANgIcIAAgATYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMhgILIAAoAgQhFyAAQQA2AgQgECARp2oiFiEBIAAgFyAQIBYgFBsiEBC1gICAACIURQ2NASAAQQc2AhwgACAQNgIUIAAgFDYCDEEAIRAMhQILIAAgAC8BMEGAAXI7ATAgASEBC0EqIRAM6gELIBBBFUYN0QEgAEEANgIcIAAgATYCFCAAQYOMgIAANgIQIABBEzYCDEEAIRAMggILIBBBFUYNzwEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAMgQILIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDI0BCyAAQQw2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMgAILIBBBFUYNzAEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM/wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIwBCyAAQQ02AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/gELIBBBFUYNyQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM/QELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIsBCyAAQQ42AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/AELIABBADYCHCAAIAE2AhQgAEHAlYCAADYCECAAQQI2AgxBACEQDPsBCyAQQRVGDcUBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPoBCyAAQRA2AhwgACABNgIUIAAgEDYCDEEAIRAM+QELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDPEBCyAAQRE2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM+AELIBBBFUYNwQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM9wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIgBCyAAQRM2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM9gELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDO0BCyAAQRQ2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM9QELIBBBFUYNvQEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM9AELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIYBCyAAQRY2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM8wELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC3gICAACIEDQAgAUEBaiEBDOkBCyAAQRc2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM8gELIABBADYCHCAAIAE2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDPEBC0IBIRELIBBBAWohAQJAIAApAyAiEkL//////////w9WDQAgACASQgSGIBGENwMgIAEhAQyEAQsgAEEANgIcIAAgATYCFCAAQa2JgIAANgIQIABBDDYCDEEAIRAM7wELIABBADYCHCAAIBA2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDO4BCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNcyAAQQU2AhwgACAQNgIUIAAgFDYCDEEAIRAM7QELIABBADYCHCAAIBA2AhQgAEGqnICAADYCECAAQQ82AgxBACEQDOwBCyAAIBAgAhC0gICAACIBDQEgECEBC0EOIRAM0QELAkAgAUEVRw0AIABBAjYCHCAAIBA2AhQgAEGwmICAADYCECAAQRU2AgxBACEQDOoBCyAAQQA2AhwgACAQNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAzpAQsgAUEBaiEQAkAgAC8BMCIBQYABcUUNAAJAIAAgECACELuAgIAAIgENACAQIQEMcAsgAUEVRw26ASAAQQU2AhwgACAQNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAzpAQsCQCABQaAEcUGgBEcNACAALQAtQQJxDQAgAEEANgIcIAAgEDYCFCAAQZaTgIAANgIQIABBBDYCDEEAIRAM6QELIAAgECACEL2AgIAAGiAQIQECQAJAAkACQAJAIAAgECACELOAgIAADhYCAQAEBAQEBAQEBAQEBAQEBAQEBAQDBAsgAEEBOgAuCyAAIAAvATBBwAByOwEwIBAhAQtBJiEQDNEBCyAAQSM2AhwgACAQNgIUIABBpZaAgAA2AhAgAEEVNgIMQQAhEAzpAQsgAEEANgIcIAAgEDYCFCAAQdWLgIAANgIQIABBETYCDEEAIRAM6AELIAAtAC1BAXFFDQFBwwEhEAzOAQsCQCANIAJGDQADQAJAIA0tAABBIEYNACANIQEMxAELIA1BAWoiDSACRw0AC0ElIRAM5wELQSUhEAzmAQsgACgCBCEEIABBADYCBCAAIAQgDRCvgICAACIERQ2tASAAQSY2AhwgACAENgIMIAAgDUEBajYCFEEAIRAM5QELIBBBFUYNqwEgAEEANgIcIAAgATYCFCAAQf2NgIAANgIQIABBHTYCDEEAIRAM5AELIABBJzYCHCAAIAE2AhQgACAQNgIMQQAhEAzjAQsgECEBQQEhFAJAAkACQAJAAkACQAJAIAAtACxBfmoOBwYFBQMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0ErIRAMygELIABBADYCHCAAIBA2AhQgAEGrkoCAADYCECAAQQs2AgxBACEQDOIBCyAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMQQAhEAzhAQsgAEEAOgAsIBAhAQy9AQsgECEBQQEhFAJAAkACQAJAAkAgAC0ALEF7ag4EAwECAAULIAAgAC8BMEEIcjsBMAwDC0ECIRQMAQtBBCEUCyAAQQE6ACwgACAALwEwIBRyOwEwCyAQIQELQSkhEAzFAQsgAEEANgIcIAAgATYCFCAAQfCUgIAANgIQIABBAzYCDEEAIRAM3QELAkAgDi0AAEENRw0AIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHULIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzdAQsgAC0ALUEBcUUNAUHEASEQDMMBCwJAIA4gAkcNAEEtIRAM3AELAkACQANAAkAgDi0AAEF2ag4EAgAAAwALIA5BAWoiDiACRw0AC0EtIRAM3QELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDiEBDHQLIABBLDYCHCAAIA42AhQgACABNgIMQQAhEAzcAQsgACgCBCEBIABBADYCBAJAIAAgASAOELGAgIAAIgENACAOQQFqIQEMcwsgAEEsNgIcIAAgATYCDCAAIA5BAWo2AhRBACEQDNsBCyAAKAIEIQQgAEEANgIEIAAgBCAOELGAgIAAIgQNoAEgDiEBDM4BCyAQQSxHDQEgAUEBaiEQQQEhAQJAAkACQAJAAkAgAC0ALEF7ag4EAwECBAALIBAhAQwEC0ECIQEMAQtBBCEBCyAAQQE6ACwgACAALwEwIAFyOwEwIBAhAQwBCyAAIAAvATBBCHI7ATAgECEBC0E5IRAMvwELIABBADoALCABIQELQTQhEAy9AQsgACAALwEwQSByOwEwIAEhAQwCCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBA0AIAEhAQzHAQsgAEE3NgIcIAAgATYCFCAAIAQ2AgxBACEQDNQBCyAAQQg6ACwgASEBC0EwIRAMuQELAkAgAC0AKEEBRg0AIAEhAQwECyAALQAtQQhxRQ2TASABIQEMAwsgAC0AMEEgcQ2UAUHFASEQDLcBCwJAIA8gAkYNAAJAA0ACQCAPLQAAQVBqIgFB/wFxQQpJDQAgDyEBQTUhEAy6AQsgACkDICIRQpmz5syZs+bMGVYNASAAIBFCCn4iETcDICARIAGtQv8BgyISQn+FVg0BIAAgESASfDcDICAPQQFqIg8gAkcNAAtBOSEQDNEBCyAAKAIEIQIgAEEANgIEIAAgAiAPQQFqIgQQsYCAgAAiAg2VASAEIQEMwwELQTkhEAzPAQsCQCAALwEwIgFBCHFFDQAgAC0AKEEBRw0AIAAtAC1BCHFFDZABCyAAIAFB9/sDcUGABHI7ATAgDyEBC0E3IRAMtAELIAAgAC8BMEEQcjsBMAyrAQsgEEEVRg2LASAAQQA2AhwgACABNgIUIABB8I6AgAA2AhAgAEEcNgIMQQAhEAzLAQsgAEHDADYCHCAAIAE2AgwgACANQQFqNgIUQQAhEAzKAQsCQCABLQAAQTpHDQAgACgCBCEQIABBADYCBAJAIAAgECABEK+AgIAAIhANACABQQFqIQEMYwsgAEHDADYCHCAAIBA2AgwgACABQQFqNgIUQQAhEAzKAQsgAEEANgIcIAAgATYCFCAAQbGRgIAANgIQIABBCjYCDEEAIRAMyQELIABBADYCHCAAIAE2AhQgAEGgmYCAADYCECAAQR42AgxBACEQDMgBCyAAQQA2AgALIABBgBI7ASogACAXQQFqIgEgAhCogICAACIQDQEgASEBC0HHACEQDKwBCyAQQRVHDYMBIABB0QA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAzEAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAzDAQsgAEEANgIcIAAgFDYCFCAAQcGogIAANgIQIABBBzYCDCAAQQA2AgBBACEQDMIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxdCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDMEBC0EAIRAgAEEANgIcIAAgATYCFCAAQYCRgIAANgIQIABBCTYCDAzAAQsgEEEVRg19IABBADYCHCAAIAE2AhQgAEGUjYCAADYCECAAQSE2AgxBACEQDL8BC0EBIRZBACEXQQAhFEEBIRALIAAgEDoAKyABQQFqIQECQAJAIAAtAC1BEHENAAJAAkACQCAALQAqDgMBAAIECyAWRQ0DDAILIBQNAQwCCyAXRQ0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQrYCAgAAiEA0AIAEhAQxcCyAAQdgANgIcIAAgATYCFCAAIBA2AgxBACEQDL4BCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQytAQsgAEHZADYCHCAAIAE2AhQgACAENgIMQQAhEAy9AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMqwELIABB2gA2AhwgACABNgIUIAAgBDYCDEEAIRAMvAELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKkBCyAAQdwANgIcIAAgATYCFCAAIAQ2AgxBACEQDLsBCwJAIAEtAABBUGoiEEH/AXFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHSADYCHCAAIBQ2AhQgACABNgIMQQAhEAykAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHTADYCHCAAIBQ2AhQgACABNgIMQQAhEAyjAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMQwsgAEHlADYCHCAAIBQ2AhQgACABNgIMQQAhEAyiAQsgAEEANgIcIAAgFDYCFCAAQcOPgIAANgIQIABBBzYCDEEAIRAMoQELIABBADYCHCAAIAE2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKABC0EAIRAgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDAyfAQsgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDEEAIRAMngELIABBADYCHCAAIBQ2AhQgAEH+kYCAADYCECAAQQc2AgxBACEQDJ0BCyAAQQA2AhwgACABNgIUIABBjpuAgAA2AhAgAEEGNgIMQQAhEAycAQsgEEEVRg1XIABBADYCHCAAIAE2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDJsBCyAAQQA2AgAgEEEBaiEBQSQhEAsgACAQOgApIAAoAgQhECAAQQA2AgQgACAQIAEQq4CAgAAiEA1UIAEhAQw+CyAAQQA2AgALQQAhECAAQQA2AhwgACAENgIUIABB8ZuAgAA2AhAgAEEGNgIMDJcBCyABQRVGDVAgAEEANgIcIAAgBTYCFCAAQfCMgIAANgIQIABBGzYCDEEAIRAMlgELIAAoAgQhBSAAQQA2AgQgACAFIBAQqYCAgAAiBQ0BIBBBAWohBQtBrQEhEAx7CyAAQcEBNgIcIAAgBTYCDCAAIBBBAWo2AhRBACEQDJMBCyAAKAIEIQYgAEEANgIEIAAgBiAQEKmAgIAAIgYNASAQQQFqIQYLQa4BIRAMeAsgAEHCATYCHCAAIAY2AgwgACAQQQFqNgIUQQAhEAyQAQsgAEEANgIcIAAgBzYCFCAAQZeLgIAANgIQIABBDTYCDEEAIRAMjwELIABBADYCHCAAIAg2AhQgAEHjkICAADYCECAAQQk2AgxBACEQDI4BCyAAQQA2AhwgACAINgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAyNAQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgCUEBaiEIAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBCAAIBAgCBCtgICAACIQRQ09IABByQE2AhwgACAINgIUIAAgEDYCDEEAIRAMjAELIAAoAgQhBCAAQQA2AgQgACAEIAgQrYCAgAAiBEUNdiAAQcoBNgIcIAAgCDYCFCAAIAQ2AgxBACEQDIsBCyAAKAIEIQQgAEEANgIEIAAgBCAJEK2AgIAAIgRFDXQgAEHLATYCHCAAIAk2AhQgACAENgIMQQAhEAyKAQsgACgCBCEEIABBADYCBCAAIAQgChCtgICAACIERQ1yIABBzQE2AhwgACAKNgIUIAAgBDYCDEEAIRAMiQELAkAgCy0AAEFQaiIQQf8BcUEKTw0AIAAgEDoAKiALQQFqIQpBtgEhEAxwCyAAKAIEIQQgAEEANgIEIAAgBCALEK2AgIAAIgRFDXAgAEHPATYCHCAAIAs2AhQgACAENgIMQQAhEAyIAQsgAEEANgIcIAAgBDYCFCAAQZCzgIAANgIQIABBCDYCDCAAQQA2AgBBACEQDIcBCyABQRVGDT8gAEEANgIcIAAgDDYCFCAAQcyOgIAANgIQIABBIDYCDEEAIRAMhgELIABBgQQ7ASggACgCBCEQIABCADcDACAAIBAgDEEBaiIMEKuAgIAAIhBFDTggAEHTATYCHCAAIAw2AhQgACAQNgIMQQAhEAyFAQsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQdibgIAANgIQIABBCDYCDAyDAQsgACgCBCEQIABCADcDACAAIBAgC0EBaiILEKuAgIAAIhANAUHGASEQDGkLIABBAjoAKAxVCyAAQdUBNgIcIAAgCzYCFCAAIBA2AgxBACEQDIABCyAQQRVGDTcgAEEANgIcIAAgBDYCFCAAQaSMgIAANgIQIABBEDYCDEEAIRAMfwsgAC0ANEEBRw00IAAgBCACELyAgIAAIhBFDTQgEEEVRw01IABB3AE2AhwgACAENgIUIABB1ZaAgAA2AhAgAEEVNgIMQQAhEAx+C0EAIRAgAEEANgIcIABBr4uAgAA2AhAgAEECNgIMIAAgFEEBajYCFAx9C0EAIRAMYwtBAiEQDGILQQ0hEAxhC0EPIRAMYAtBJSEQDF8LQRMhEAxeC0EVIRAMXQtBFiEQDFwLQRchEAxbC0EYIRAMWgtBGSEQDFkLQRohEAxYC0EbIRAMVwtBHCEQDFYLQR0hEAxVC0EfIRAMVAtBISEQDFMLQSMhEAxSC0HGACEQDFELQS4hEAxQC0EvIRAMTwtBOyEQDE4LQT0hEAxNC0HIACEQDEwLQckAIRAMSwtBywAhEAxKC0HMACEQDEkLQc4AIRAMSAtB0QAhEAxHC0HVACEQDEYLQdgAIRAMRQtB2QAhEAxEC0HbACEQDEMLQeQAIRAMQgtB5QAhEAxBC0HxACEQDEALQfQAIRAMPwtBjQEhEAw+C0GXASEQDD0LQakBIRAMPAtBrAEhEAw7C0HAASEQDDoLQbkBIRAMOQtBrwEhEAw4C0GxASEQDDcLQbIBIRAMNgtBtAEhEAw1C0G1ASEQDDQLQboBIRAMMwtBvQEhEAwyC0G/ASEQDDELQcEBIRAMMAsgAEEANgIcIAAgBDYCFCAAQemLgIAANgIQIABBHzYCDEEAIRAMSAsgAEHbATYCHCAAIAQ2AhQgAEH6loCAADYCECAAQRU2AgxBACEQDEcLIABB+AA2AhwgACAMNgIUIABBypiAgAA2AhAgAEEVNgIMQQAhEAxGCyAAQdEANgIcIAAgBTYCFCAAQbCXgIAANgIQIABBFTYCDEEAIRAMRQsgAEH5ADYCHCAAIAE2AhQgACAQNgIMQQAhEAxECyAAQfgANgIcIAAgATYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMQwsgAEHkADYCHCAAIAE2AhQgAEHjl4CAADYCECAAQRU2AgxBACEQDEILIABB1wA2AhwgACABNgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAxBCyAAQQA2AhwgACABNgIUIABBuY2AgAA2AhAgAEEaNgIMQQAhEAxACyAAQcIANgIcIAAgATYCFCAAQeOYgIAANgIQIABBFTYCDEEAIRAMPwsgAEEANgIEIAAgDyAPELGAgIAAIgRFDQEgAEE6NgIcIAAgBDYCDCAAIA9BAWo2AhRBACEQDD4LIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCxgICAACIERQ0AIABBOzYCHCAAIAQ2AgwgACABQQFqNgIUQQAhEAw+CyABQQFqIQEMLQsgD0EBaiEBDC0LIABBADYCHCAAIA82AhQgAEHkkoCAADYCECAAQQQ2AgxBACEQDDsLIABBNjYCHCAAIAQ2AhQgACACNgIMQQAhEAw6CyAAQS42AhwgACAONgIUIAAgBDYCDEEAIRAMOQsgAEHQADYCHCAAIAE2AhQgAEGRmICAADYCECAAQRU2AgxBACEQDDgLIA1BAWohAQwsCyAAQRU2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAw2CyAAQRs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw1CyAAQQ82AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw0CyAAQQs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAwzCyAAQRo2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwyCyAAQQs2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwxCyAAQQo2AhwgACABNgIUIABB5JaAgAA2AhAgAEEVNgIMQQAhEAwwCyAAQR42AhwgACABNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAwvCyAAQQA2AhwgACAQNgIUIABB2o2AgAA2AhAgAEEUNgIMQQAhEAwuCyAAQQQ2AhwgACABNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAwtCyAAQQA2AgAgC0EBaiELC0G4ASEQDBILIABBADYCACAQQQFqIQFB9QAhEAwRCyABIQECQCAALQApQQVHDQBB4wAhEAwRC0HiACEQDBALQQAhECAAQQA2AhwgAEHkkYCAADYCECAAQQc2AgwgACAUQQFqNgIUDCgLIABBADYCACAXQQFqIQFBwAAhEAwOC0EBIQELIAAgAToALCAAQQA2AgAgF0EBaiEBC0EoIRAMCwsgASEBC0E4IRAMCQsCQCABIg8gAkYNAANAAkAgDy0AAEGAvoCAAGotAAAiAUEBRg0AIAFBAkcNAyAPQQFqIQEMBAsgD0EBaiIPIAJHDQALQT4hEAwiC0E+IRAMIQsgAEEAOgAsIA8hAQwBC0ELIRAMBgtBOiEQDAULIAFBAWohAUEtIRAMBAsgACABOgAsIABBADYCACAWQQFqIQFBDCEQDAMLIABBADYCACAXQQFqIQFBCiEQDAILIABBADYCAAsgAEEAOgAsIA0hAUEJIRAMAAsLQQAhECAAQQA2AhwgACALNgIUIABBzZCAgAA2AhAgAEEJNgIMDBcLQQAhECAAQQA2AhwgACAKNgIUIABB6YqAgAA2AhAgAEEJNgIMDBYLQQAhECAAQQA2AhwgACAJNgIUIABBt5CAgAA2AhAgAEEJNgIMDBULQQAhECAAQQA2AhwgACAINgIUIABBnJGAgAA2AhAgAEEJNgIMDBQLQQAhECAAQQA2AhwgACABNgIUIABBzZCAgAA2AhAgAEEJNgIMDBMLQQAhECAAQQA2AhwgACABNgIUIABB6YqAgAA2AhAgAEEJNgIMDBILQQAhECAAQQA2AhwgACABNgIUIABBt5CAgAA2AhAgAEEJNgIMDBELQQAhECAAQQA2AhwgACABNgIUIABBnJGAgAA2AhAgAEEJNgIMDBALQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA8LQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA4LQQAhECAAQQA2AhwgACABNgIUIABBwJKAgAA2AhAgAEELNgIMDA0LQQAhECAAQQA2AhwgACABNgIUIABBlYmAgAA2AhAgAEELNgIMDAwLQQAhECAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMDAsLQQAhECAAQQA2AhwgACABNgIUIABB+4+AgAA2AhAgAEEKNgIMDAoLQQAhECAAQQA2AhwgACABNgIUIABB8ZmAgAA2AhAgAEECNgIMDAkLQQAhECAAQQA2AhwgACABNgIUIABBxJSAgAA2AhAgAEECNgIMDAgLQQAhECAAQQA2AhwgACABNgIUIABB8pWAgAA2AhAgAEECNgIMDAcLIABBAjYCHCAAIAE2AhQgAEGcmoCAADYCECAAQRY2AgxBACEQDAYLQQEhEAwFC0HUACEQIAEiBCACRg0EIANBCGogACAEIAJB2MKAgABBChDFgICAACADKAIMIQQgAygCCA4DAQQCAAsQyoCAgAAACyAAQQA2AhwgAEG1moCAADYCECAAQRc2AgwgACAEQQFqNgIUQQAhEAwCCyAAQQA2AhwgACAENgIUIABBypqAgAA2AhAgAEEJNgIMQQAhEAwBCwJAIAEiBCACRw0AQSIhEAwBCyAAQYmAgIAANgIIIAAgBDYCBEEhIRALIANBEGokgICAgAAgEAuvAQECfyABKAIAIQYCQAJAIAIgA0YNACAEIAZqIQQgBiADaiACayEHIAIgBkF/cyAFaiIGaiEFA0ACQCACLQAAIAQtAABGDQBBAiEEDAMLAkAgBg0AQQAhBCAFIQIMAwsgBkF/aiEGIARBAWohBCACQQFqIgIgA0cNAAsgByEGIAMhAgsgAEEBNgIAIAEgBjYCACAAIAI2AgQPCyABQQA2AgAgACAENgIAIAAgAjYCBAsKACAAEMeAgIAAC/I2AQt/I4CAgIAAQRBrIgEkgICAgAACQEEAKAKg0ICAAA0AQQAQy4CAgABBgNSEgABrIgJB2QBJDQBBACEDAkBBACgC4NOAgAAiBA0AQQBCfzcC7NOAgABBAEKAgISAgIDAADcC5NOAgABBACABQQhqQXBxQdiq1aoFcyIENgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgAALQQAgAjYCzNOAgABBAEGA1ISAADYCyNOAgABBAEGA1ISAADYCmNCAgABBACAENgKs0ICAAEEAQX82AqjQgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAtBgNSEgABBeEGA1ISAAGtBD3FBAEGA1ISAAEEIakEPcRsiA2oiBEEEaiACQUhqIgUgA2siA0EBcjYCAEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgABBgNSEgAAgBWpBODYCBAsCQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHsAUsNAAJAQQAoAojQgIAAIgZBECAAQRNqQXBxIABBC0kbIgJBA3YiBHYiA0EDcUUNAAJAAkAgA0EBcSAEckEBcyIFQQN0IgRBsNCAgABqIgMgBEG40ICAAGooAgAiBCgCCCICRw0AQQAgBkF+IAV3cTYCiNCAgAAMAQsgAyACNgIIIAIgAzYCDAsgBEEIaiEDIAQgBUEDdCIFQQNyNgIEIAQgBWoiBCAEKAIEQQFyNgIEDAwLIAJBACgCkNCAgAAiB00NAQJAIANFDQACQAJAIAMgBHRBAiAEdCIDQQAgA2tycSIDQQAgA2txQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmoiBEEDdCIDQbDQgIAAaiIFIANBuNCAgABqKAIAIgMoAggiAEcNAEEAIAZBfiAEd3EiBjYCiNCAgAAMAQsgBSAANgIIIAAgBTYCDAsgAyACQQNyNgIEIAMgBEEDdCIEaiAEIAJrIgU2AgAgAyACaiIAIAVBAXI2AgQCQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhBAJAAkAgBkEBIAdBA3Z0IghxDQBBACAGIAhyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAQ2AgwgAiAENgIIIAQgAjYCDCAEIAg2AggLIANBCGohA0EAIAA2ApzQgIAAQQAgBTYCkNCAgAAMDAtBACgCjNCAgAAiCUUNASAJQQAgCWtxQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmpBAnRBuNKAgABqKAIAIgAoAgRBeHEgAmshBCAAIQUCQANAAkAgBSgCECIDDQAgBUEUaigCACIDRQ0CCyADKAIEQXhxIAJrIgUgBCAFIARJIgUbIQQgAyAAIAUbIQAgAyEFDAALCyAAKAIYIQoCQCAAKAIMIgggAEYNACAAKAIIIgNBACgCmNCAgABJGiAIIAM2AgggAyAINgIMDAsLAkAgAEEUaiIFKAIAIgMNACAAKAIQIgNFDQMgAEEQaiEFCwNAIAUhCyADIghBFGoiBSgCACIDDQAgCEEQaiEFIAgoAhAiAw0ACyALQQA2AgAMCgtBfyECIABBv39LDQAgAEETaiIDQXBxIQJBACgCjNCAgAAiB0UNAEEAIQsCQCACQYACSQ0AQR8hCyACQf///wdLDQAgA0EIdiIDIANBgP4/akEQdkEIcSIDdCIEIARBgOAfakEQdkEEcSIEdCIFIAVBgIAPakEQdkECcSIFdEEPdiADIARyIAVyayIDQQF0IAIgA0EVanZBAXFyQRxqIQsLQQAgAmshBAJAAkACQAJAIAtBAnRBuNKAgABqKAIAIgUNAEEAIQNBACEIDAELQQAhAyACQQBBGSALQQF2ayALQR9GG3QhAEEAIQgDQAJAIAUoAgRBeHEgAmsiBiAETw0AIAYhBCAFIQggBg0AQQAhBCAFIQggBSEDDAMLIAMgBUEUaigCACIGIAYgBSAAQR12QQRxakEQaigCACIFRhsgAyAGGyEDIABBAXQhACAFDQALCwJAIAMgCHINAEEAIQhBAiALdCIDQQAgA2tyIAdxIgNFDQMgA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBUEFdkEIcSIAIANyIAUgAHYiA0ECdkEEcSIFciADIAV2IgNBAXZBAnEiBXIgAyAFdiIDQQF2QQFxIgVyIAMgBXZqQQJ0QbjSgIAAaigCACEDCyADRQ0BCwNAIAMoAgRBeHEgAmsiBiAESSEAAkAgAygCECIFDQAgA0EUaigCACEFCyAGIAQgABshBCADIAggABshCCAFIQMgBQ0ACwsgCEUNACAEQQAoApDQgIAAIAJrTw0AIAgoAhghCwJAIAgoAgwiACAIRg0AIAgoAggiA0EAKAKY0ICAAEkaIAAgAzYCCCADIAA2AgwMCQsCQCAIQRRqIgUoAgAiAw0AIAgoAhAiA0UNAyAIQRBqIQULA0AgBSEGIAMiAEEUaiIFKAIAIgMNACAAQRBqIQUgACgCECIDDQALIAZBADYCAAwICwJAQQAoApDQgIAAIgMgAkkNAEEAKAKc0ICAACEEAkACQCADIAJrIgVBEEkNACAEIAJqIgAgBUEBcjYCBEEAIAU2ApDQgIAAQQAgADYCnNCAgAAgBCADaiAFNgIAIAQgAkEDcjYCBAwBCyAEIANBA3I2AgQgBCADaiIDIAMoAgRBAXI2AgRBAEEANgKc0ICAAEEAQQA2ApDQgIAACyAEQQhqIQMMCgsCQEEAKAKU0ICAACIAIAJNDQBBACgCoNCAgAAiAyACaiIEIAAgAmsiBUEBcjYCBEEAIAU2ApTQgIAAQQAgBDYCoNCAgAAgAyACQQNyNgIEIANBCGohAwwKCwJAAkBBACgC4NOAgABFDQBBACgC6NOAgAAhBAwBC0EAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEMakFwcUHYqtWqBXM2AuDTgIAAQQBBADYC9NOAgABBAEEANgLE04CAAEGAgAQhBAtBACEDAkAgBCACQccAaiIHaiIGQQAgBGsiC3EiCCACSw0AQQBBMDYC+NOAgAAMCgsCQEEAKALA04CAACIDRQ0AAkBBACgCuNOAgAAiBCAIaiIFIARNDQAgBSADTQ0BC0EAIQNBAEEwNgL404CAAAwKC0EALQDE04CAAEEEcQ0EAkACQAJAQQAoAqDQgIAAIgRFDQBByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiAESw0DCyADKAIIIgMNAAsLQQAQy4CAgAAiAEF/Rg0FIAghBgJAQQAoAuTTgIAAIgNBf2oiBCAAcUUNACAIIABrIAQgAGpBACADa3FqIQYLIAYgAk0NBSAGQf7///8HSw0FAkBBACgCwNOAgAAiA0UNAEEAKAK404CAACIEIAZqIgUgBE0NBiAFIANLDQYLIAYQy4CAgAAiAyAARw0BDAcLIAYgAGsgC3EiBkH+////B0sNBCAGEMuAgIAAIgAgAygCACADKAIEakYNAyAAIQMLAkAgA0F/Rg0AIAJByABqIAZNDQACQCAHIAZrQQAoAujTgIAAIgRqQQAgBGtxIgRB/v///wdNDQAgAyEADAcLAkAgBBDLgICAAEF/Rg0AIAQgBmohBiADIQAMBwtBACAGaxDLgICAABoMBAsgAyEAIANBf0cNBQwDC0EAIQgMBwtBACEADAULIABBf0cNAgtBAEEAKALE04CAAEEEcjYCxNOAgAALIAhB/v///wdLDQEgCBDLgICAACEAQQAQy4CAgAAhAyAAQX9GDQEgA0F/Rg0BIAAgA08NASADIABrIgYgAkE4ak0NAQtBAEEAKAK404CAACAGaiIDNgK404CAAAJAIANBACgCvNOAgABNDQBBACADNgK804CAAAsCQAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQCAAIAMoAgAiBSADKAIEIghqRg0CIAMoAggiAw0ADAMLCwJAAkBBACgCmNCAgAAiA0UNACAAIANPDQELQQAgADYCmNCAgAALQQAhA0EAIAY2AszTgIAAQQAgADYCyNOAgABBAEF/NgKo0ICAAEEAQQAoAuDTgIAANgKs0ICAAEEAQQA2AtTTgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiBCAGQUhqIgUgA2siA0EBcjYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgAAgACAFakE4NgIEDAILIAMtAAxBCHENACAEIAVJDQAgBCAATw0AIARBeCAEa0EPcUEAIARBCGpBD3EbIgVqIgBBACgClNCAgAAgBmoiCyAFayIFQQFyNgIEIAMgCCAGajYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAU2ApTQgIAAQQAgADYCoNCAgAAgBCALakE4NgIEDAELAkAgAEEAKAKY0ICAACIITw0AQQAgADYCmNCAgAAgACEICyAAIAZqIQVByNOAgAAhAwJAAkACQAJAAkACQAJAA0AgAygCACAFRg0BIAMoAggiAw0ADAILCyADLQAMQQhxRQ0BC0HI04CAACEDA0ACQCADKAIAIgUgBEsNACAFIAMoAgRqIgUgBEsNAwsgAygCCCEDDAALCyADIAA2AgAgAyADKAIEIAZqNgIEIABBeCAAa0EPcUEAIABBCGpBD3EbaiILIAJBA3I2AgQgBUF4IAVrQQ9xQQAgBUEIakEPcRtqIgYgCyACaiICayEDAkAgBiAERw0AQQAgAjYCoNCAgABBAEEAKAKU0ICAACADaiIDNgKU0ICAACACIANBAXI2AgQMAwsCQCAGQQAoApzQgIAARw0AQQAgAjYCnNCAgABBAEEAKAKQ0ICAACADaiIDNgKQ0ICAACACIANBAXI2AgQgAiADaiADNgIADAMLAkAgBigCBCIEQQNxQQFHDQAgBEF4cSEHAkACQCAEQf8BSw0AIAYoAggiBSAEQQN2IghBA3RBsNCAgABqIgBGGgJAIAYoAgwiBCAFRw0AQQBBACgCiNCAgABBfiAId3E2AojQgIAADAILIAQgAEYaIAQgBTYCCCAFIAQ2AgwMAQsgBigCGCEJAkACQCAGKAIMIgAgBkYNACAGKAIIIgQgCEkaIAAgBDYCCCAEIAA2AgwMAQsCQCAGQRRqIgQoAgAiBQ0AIAZBEGoiBCgCACIFDQBBACEADAELA0AgBCEIIAUiAEEUaiIEKAIAIgUNACAAQRBqIQQgACgCECIFDQALIAhBADYCAAsgCUUNAAJAAkAgBiAGKAIcIgVBAnRBuNKAgABqIgQoAgBHDQAgBCAANgIAIAANAUEAQQAoAozQgIAAQX4gBXdxNgKM0ICAAAwCCyAJQRBBFCAJKAIQIAZGG2ogADYCACAARQ0BCyAAIAk2AhgCQCAGKAIQIgRFDQAgACAENgIQIAQgADYCGAsgBigCFCIERQ0AIABBFGogBDYCACAEIAA2AhgLIAcgA2ohAyAGIAdqIgYoAgQhBAsgBiAEQX5xNgIEIAIgA2ogAzYCACACIANBAXI2AgQCQCADQf8BSw0AIANBeHFBsNCAgABqIQQCQAJAQQAoAojQgIAAIgVBASADQQN2dCIDcQ0AQQAgBSADcjYCiNCAgAAgBCEDDAELIAQoAgghAwsgAyACNgIMIAQgAjYCCCACIAQ2AgwgAiADNgIIDAMLQR8hBAJAIANB////B0sNACADQQh2IgQgBEGA/j9qQRB2QQhxIgR0IgUgBUGA4B9qQRB2QQRxIgV0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAQgBXIgAHJrIgRBAXQgAyAEQRVqdkEBcXJBHGohBAsgAiAENgIcIAJCADcCECAEQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiAEEBIAR0IghxDQAgBSACNgIAQQAgACAIcjYCjNCAgAAgAiAFNgIYIAIgAjYCCCACIAI2AgwMAwsgA0EAQRkgBEEBdmsgBEEfRht0IQQgBSgCACEAA0AgACIFKAIEQXhxIANGDQIgBEEddiEAIARBAXQhBCAFIABBBHFqQRBqIggoAgAiAA0ACyAIIAI2AgAgAiAFNgIYIAIgAjYCDCACIAI2AggMAgsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiCyAGQUhqIgggA2siA0EBcjYCBCAAIAhqQTg2AgQgBCAFQTcgBWtBD3FBACAFQUlqQQ9xG2pBQWoiCCAIIARBEGpJGyIIQSM2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAs2AqDQgIAAIAhBEGpBACkC0NOAgAA3AgAgCEEAKQLI04CAADcCCEEAIAhBCGo2AtDTgIAAQQAgBjYCzNOAgABBACAANgLI04CAAEEAQQA2AtTTgIAAIAhBJGohAwNAIANBBzYCACADQQRqIgMgBUkNAAsgCCAERg0DIAggCCgCBEF+cTYCBCAIIAggBGsiADYCACAEIABBAXI2AgQCQCAAQf8BSw0AIABBeHFBsNCAgABqIQMCQAJAQQAoAojQgIAAIgVBASAAQQN2dCIAcQ0AQQAgBSAAcjYCiNCAgAAgAyEFDAELIAMoAgghBQsgBSAENgIMIAMgBDYCCCAEIAM2AgwgBCAFNgIIDAQLQR8hAwJAIABB////B0sNACAAQQh2IgMgA0GA/j9qQRB2QQhxIgN0IgUgBUGA4B9qQRB2QQRxIgV0IgggCEGAgA9qQRB2QQJxIgh0QQ92IAMgBXIgCHJrIgNBAXQgACADQRVqdkEBcXJBHGohAwsgBCADNgIcIARCADcCECADQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiCEEBIAN0IgZxDQAgBSAENgIAQQAgCCAGcjYCjNCAgAAgBCAFNgIYIAQgBDYCCCAEIAQ2AgwMBAsgAEEAQRkgA0EBdmsgA0EfRht0IQMgBSgCACEIA0AgCCIFKAIEQXhxIABGDQMgA0EddiEIIANBAXQhAyAFIAhBBHFqQRBqIgYoAgAiCA0ACyAGIAQ2AgAgBCAFNgIYIAQgBDYCDCAEIAQ2AggMAwsgBSgCCCIDIAI2AgwgBSACNgIIIAJBADYCGCACIAU2AgwgAiADNgIICyALQQhqIQMMBQsgBSgCCCIDIAQ2AgwgBSAENgIIIARBADYCGCAEIAU2AgwgBCADNgIIC0EAKAKU0ICAACIDIAJNDQBBACgCoNCAgAAiBCACaiIFIAMgAmsiA0EBcjYCBEEAIAM2ApTQgIAAQQAgBTYCoNCAgAAgBCACQQNyNgIEIARBCGohAwwDC0EAIQNBAEEwNgL404CAAAwCCwJAIAtFDQACQAJAIAggCCgCHCIFQQJ0QbjSgIAAaiIDKAIARw0AIAMgADYCACAADQFBACAHQX4gBXdxIgc2AozQgIAADAILIAtBEEEUIAsoAhAgCEYbaiAANgIAIABFDQELIAAgCzYCGAJAIAgoAhAiA0UNACAAIAM2AhAgAyAANgIYCyAIQRRqKAIAIgNFDQAgAEEUaiADNgIAIAMgADYCGAsCQAJAIARBD0sNACAIIAQgAmoiA0EDcjYCBCAIIANqIgMgAygCBEEBcjYCBAwBCyAIIAJqIgAgBEEBcjYCBCAIIAJBA3I2AgQgACAEaiAENgIAAkAgBEH/AUsNACAEQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgBEEDdnQiBHENAEEAIAUgBHI2AojQgIAAIAMhBAwBCyADKAIIIQQLIAQgADYCDCADIAA2AgggACADNgIMIAAgBDYCCAwBC0EfIQMCQCAEQf///wdLDQAgBEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCICIAJBgIAPakEQdkECcSICdEEPdiADIAVyIAJyayIDQQF0IAQgA0EVanZBAXFyQRxqIQMLIAAgAzYCHCAAQgA3AhAgA0ECdEG40oCAAGohBQJAIAdBASADdCICcQ0AIAUgADYCAEEAIAcgAnI2AozQgIAAIAAgBTYCGCAAIAA2AgggACAANgIMDAELIARBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhAgJAA0AgAiIFKAIEQXhxIARGDQEgA0EddiECIANBAXQhAyAFIAJBBHFqQRBqIgYoAgAiAg0ACyAGIAA2AgAgACAFNgIYIAAgADYCDCAAIAA2AggMAQsgBSgCCCIDIAA2AgwgBSAANgIIIABBADYCGCAAIAU2AgwgACADNgIICyAIQQhqIQMMAQsCQCAKRQ0AAkACQCAAIAAoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAg2AgAgCA0BQQAgCUF+IAV3cTYCjNCAgAAMAgsgCkEQQRQgCigCECAARhtqIAg2AgAgCEUNAQsgCCAKNgIYAkAgACgCECIDRQ0AIAggAzYCECADIAg2AhgLIABBFGooAgAiA0UNACAIQRRqIAM2AgAgAyAINgIYCwJAAkAgBEEPSw0AIAAgBCACaiIDQQNyNgIEIAAgA2oiAyADKAIEQQFyNgIEDAELIAAgAmoiBSAEQQFyNgIEIAAgAkEDcjYCBCAFIARqIAQ2AgACQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhAwJAAkBBASAHQQN2dCIIIAZxDQBBACAIIAZyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAM2AgwgAiADNgIIIAMgAjYCDCADIAg2AggLQQAgBTYCnNCAgABBACAENgKQ0ICAAAsgAEEIaiEDCyABQRBqJICAgIAAIAMLCgAgABDJgICAAAviDQEHfwJAIABFDQAgAEF4aiIBIABBfGooAgAiAkF4cSIAaiEDAkAgAkEBcQ0AIAJBA3FFDQEgASABKAIAIgJrIgFBACgCmNCAgAAiBEkNASACIABqIQACQCABQQAoApzQgIAARg0AAkAgAkH/AUsNACABKAIIIgQgAkEDdiIFQQN0QbDQgIAAaiIGRhoCQCABKAIMIgIgBEcNAEEAQQAoAojQgIAAQX4gBXdxNgKI0ICAAAwDCyACIAZGGiACIAQ2AgggBCACNgIMDAILIAEoAhghBwJAAkAgASgCDCIGIAFGDQAgASgCCCICIARJGiAGIAI2AgggAiAGNgIMDAELAkAgAUEUaiICKAIAIgQNACABQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQECQAJAIAEgASgCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAwsgB0EQQRQgBygCECABRhtqIAY2AgAgBkUNAgsgBiAHNgIYAkAgASgCECICRQ0AIAYgAjYCECACIAY2AhgLIAEoAhQiAkUNASAGQRRqIAI2AgAgAiAGNgIYDAELIAMoAgQiAkEDcUEDRw0AIAMgAkF+cTYCBEEAIAA2ApDQgIAAIAEgAGogADYCACABIABBAXI2AgQPCyABIANPDQAgAygCBCICQQFxRQ0AAkACQCACQQJxDQACQCADQQAoAqDQgIAARw0AQQAgATYCoNCAgABBAEEAKAKU0ICAACAAaiIANgKU0ICAACABIABBAXI2AgQgAUEAKAKc0ICAAEcNA0EAQQA2ApDQgIAAQQBBADYCnNCAgAAPCwJAIANBACgCnNCAgABHDQBBACABNgKc0ICAAEEAQQAoApDQgIAAIABqIgA2ApDQgIAAIAEgAEEBcjYCBCABIABqIAA2AgAPCyACQXhxIABqIQACQAJAIAJB/wFLDQAgAygCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgAygCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAgsgAiAGRhogAiAENgIIIAQgAjYCDAwBCyADKAIYIQcCQAJAIAMoAgwiBiADRg0AIAMoAggiAkEAKAKY0ICAAEkaIAYgAjYCCCACIAY2AgwMAQsCQCADQRRqIgIoAgAiBA0AIANBEGoiAigCACIEDQBBACEGDAELA0AgAiEFIAQiBkEUaiICKAIAIgQNACAGQRBqIQIgBigCECIEDQALIAVBADYCAAsgB0UNAAJAAkAgAyADKAIcIgRBAnRBuNKAgABqIgIoAgBHDQAgAiAGNgIAIAYNAUEAQQAoAozQgIAAQX4gBHdxNgKM0ICAAAwCCyAHQRBBFCAHKAIQIANGG2ogBjYCACAGRQ0BCyAGIAc2AhgCQCADKAIQIgJFDQAgBiACNgIQIAIgBjYCGAsgAygCFCICRQ0AIAZBFGogAjYCACACIAY2AhgLIAEgAGogADYCACABIABBAXI2AgQgAUEAKAKc0ICAAEcNAUEAIAA2ApDQgIAADwsgAyACQX5xNgIEIAEgAGogADYCACABIABBAXI2AgQLAkAgAEH/AUsNACAAQXhxQbDQgIAAaiECAkACQEEAKAKI0ICAACIEQQEgAEEDdnQiAHENAEEAIAQgAHI2AojQgIAAIAIhAAwBCyACKAIIIQALIAAgATYCDCACIAE2AgggASACNgIMIAEgADYCCA8LQR8hAgJAIABB////B0sNACAAQQh2IgIgAkGA/j9qQRB2QQhxIgJ0IgQgBEGA4B9qQRB2QQRxIgR0IgYgBkGAgA9qQRB2QQJxIgZ0QQ92IAIgBHIgBnJrIgJBAXQgACACQRVqdkEBcXJBHGohAgsgASACNgIcIAFCADcCECACQQJ0QbjSgIAAaiEEAkACQEEAKAKM0ICAACIGQQEgAnQiA3ENACAEIAE2AgBBACAGIANyNgKM0ICAACABIAQ2AhggASABNgIIIAEgATYCDAwBCyAAQQBBGSACQQF2ayACQR9GG3QhAiAEKAIAIQYCQANAIAYiBCgCBEF4cSAARg0BIAJBHXYhBiACQQF0IQIgBCAGQQRxakEQaiIDKAIAIgYNAAsgAyABNgIAIAEgBDYCGCABIAE2AgwgASABNgIIDAELIAQoAggiACABNgIMIAQgATYCCCABQQA2AhggASAENgIMIAEgADYCCAtBAEEAKAKo0ICAAEF/aiIBQX8gARs2AqjQgIAACwsEAAAAC04AAkAgAA0APwBBEHQPCwJAIABB//8DcQ0AIABBf0wNAAJAIABBEHZAACIAQX9HDQBBAEEwNgL404CAAEF/DwsgAEEQdA8LEMqAgIAAAAvyAgIDfwF+AkAgAkUNACAAIAE6AAAgAiAAaiIDQX9qIAE6AAAgAkEDSQ0AIAAgAToAAiAAIAE6AAEgA0F9aiABOgAAIANBfmogAToAACACQQdJDQAgACABOgADIANBfGogAToAACACQQlJDQAgAEEAIABrQQNxIgRqIgMgAUH/AXFBgYKECGwiATYCACADIAIgBGtBfHEiBGoiAkF8aiABNgIAIARBCUkNACADIAE2AgggAyABNgIEIAJBeGogATYCACACQXRqIAE2AgAgBEEZSQ0AIAMgATYCGCADIAE2AhQgAyABNgIQIAMgATYCDCACQXBqIAE2AgAgAkFsaiABNgIAIAJBaGogATYCACACQWRqIAE2AgAgBCADQQRxQRhyIgVrIgJBIEkNACABrUKBgICAEH4hBiADIAVqIQEDQCABIAY3AxggASAGNwMQIAEgBjcDCCABIAY3AwAgAUEgaiEBIAJBYGoiAkEfSw0ACwsgAAsLjkgBAEGACAuGSAEAAAACAAAAAwAAAAAAAAAAAAAABAAAAAUAAAAAAAAAAAAAAAYAAAAHAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsb3NlZWVwLWFsaXZlAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgAAAAAAAAAAAAAAAAAAAHJhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KDQpTTQ0KDQpUVFAvQ0UvVFNQLwAAAAAAAAAAAAAAAAECAAEDAAAAAAAAAAAAAAAAAAAAAAAABAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQUBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAABAAACAAAAAAAAAAAAAAAAAAAAAAAAAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' -var noop = function () {} -var overflow = function (self, size) { - size &= 511 - if (size) self.push(END_OF_TAR.slice(0, 512 - size)) -} +/***/ }), -function modeToType (mode) { - switch (mode & constants.S_IFMT) { - case constants.S_IFBLK: return 'block-device' - case constants.S_IFCHR: return 'character-device' - case constants.S_IFDIR: return 'directory' - case constants.S_IFIFO: return 'fifo' - case constants.S_IFLNK: return 'symlink' - } +/***/ 1891: +/***/ ((__unused_webpack_module, exports) => { - return 'file' -} +"use strict"; -var Sink = function (to) { - Writable.call(this) - this.written = 0 - this._to = to - this._destroyed = false +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.enumToMap = void 0; +function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; } +exports.enumToMap = enumToMap; +//# sourceMappingURL=utils.js.map -inherits(Sink, Writable) - -Sink.prototype._write = function (data, enc, cb) { - this.written += data.length - if (this._to.push(data)) return cb() - this._to._drain = cb -} +/***/ }), -Sink.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} +/***/ 6771: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var LinkSink = function () { - Writable.call(this) - this.linkname = '' - this._decoder = new StringDecoder('utf-8') - this._destroyed = false -} +"use strict"; -inherits(LinkSink, Writable) -LinkSink.prototype._write = function (data, enc, cb) { - this.linkname += this._decoder.write(data) - cb() -} +const { kClients } = __nccwpck_require__(2785) +const Agent = __nccwpck_require__(7890) +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = __nccwpck_require__(4347) +const MockClient = __nccwpck_require__(8687) +const MockPool = __nccwpck_require__(6193) +const { matchValue, buildMockOptions } = __nccwpck_require__(9323) +const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8045) +const Dispatcher = __nccwpck_require__(412) +const Pluralizer = __nccwpck_require__(8891) +const PendingInterceptorsFormatter = __nccwpck_require__(6823) -LinkSink.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} +class FakeWeakRef { + constructor (value) { + this.value = value + } -var Void = function () { - Writable.call(this) - this._destroyed = false + deref () { + return this.value + } } -inherits(Void, Writable) +class MockAgent extends Dispatcher { + constructor (opts) { + super(opts) -Void.prototype._write = function (data, enc, cb) { - cb(new Error('No body allowed for this entry')) -} + this[kNetConnect] = true + this[kIsMockActive] = true -Void.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} + // Instantiate Agent and encapsulate + if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts && opts.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent -var Pack = function (opts) { - if (!(this instanceof Pack)) return new Pack(opts) - Readable.call(this, opts) + this[kClients] = agent[kClients] + this[kOptions] = buildMockOptions(opts) + } - this._drain = noop - this._finalized = false - this._finalizing = false - this._destroyed = false - this._stream = null -} + get (origin) { + let dispatcher = this[kMockAgentGet](origin) -inherits(Pack, Readable) + if (!dispatcher) { + dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + } + return dispatcher + } -Pack.prototype.entry = function (header, buffer, callback) { - if (this._stream) throw new Error('already piping an entry') - if (this._finalized || this._destroyed) return + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + return this[kAgent].dispatch(opts, handler) + } - if (typeof buffer === 'function') { - callback = buffer - buffer = null + async close () { + await this[kAgent].close() + this[kClients].clear() } - if (!callback) callback = noop + deactivate () { + this[kIsMockActive] = false + } - var self = this + activate () { + this[kIsMockActive] = true + } - if (!header.size || header.type === 'symlink') header.size = 0 - if (!header.type) header.type = modeToType(header.mode) - if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE - if (!header.uid) header.uid = 0 - if (!header.gid) header.gid = 0 - if (!header.mtime) header.mtime = new Date() + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } - if (typeof buffer === 'string') buffer = Buffer.from(buffer) - if (Buffer.isBuffer(buffer)) { - header.size = buffer.length - this._encode(header) - var ok = this.push(buffer) - overflow(self, header.size) - if (ok) process.nextTick(callback) - else this._drain = callback - return new Void() + disableNetConnect () { + this[kNetConnect] = false } - if (header.type === 'symlink' && !header.linkname) { - var linkSink = new LinkSink() - eos(linkSink, function (err) { - if (err) { // stream was closed - self.destroy() - return callback(err) - } + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } - header.linkname = linkSink.linkname - self._encode(header) - callback() - }) + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, new FakeWeakRef(dispatcher)) + } - return linkSink + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) } - this._encode(header) + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const ref = this[kClients].get(origin) + if (ref) { + return ref.deref() + } - if (header.type !== 'file' && header.type !== 'contiguous-file') { - process.nextTick(callback) - return new Void() + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { + const nonExplicitDispatcher = nonExplicitRef.deref() + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] + return dispatcher + } + } } - var sink = new Sink(this) + [kGetNetConnect] () { + return this[kNetConnect] + } - this._stream = sink + pendingInterceptors () { + const mockAgentClients = this[kClients] - eos(sink, function (err) { - self._stream = null + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } - if (err) { // stream was closed - self.destroy() - return callback(err) - } + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() - if (sink.written !== header.size) { // corrupting tar - self.destroy() - return callback(new Error('size mismatch')) + if (pending.length === 0) { + return } - overflow(self, header.size) - if (self._finalizing) self.finalize() - callback() - }) + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) - return sink -} + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: -Pack.prototype.finalize = function () { - if (this._stream) { - this._finalizing = true - return +${pendingInterceptorsFormatter.format(pending)} +`.trim()) } - - if (this._finalized) return - this._finalized = true - this.push(END_OF_TAR) - this.push(null) } -Pack.prototype.destroy = function (err) { - if (this._destroyed) return - this._destroyed = true +module.exports = MockAgent - if (err) this.emit('error', err) - this.emit('close') - if (this._stream && this._stream.destroy) this._stream.destroy() -} -Pack.prototype._encode = function (header) { - if (!header.pax) { - var buf = headers.encode(header) - if (buf) { - this.push(buf) - return +/***/ }), + +/***/ 8687: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { promisify } = __nccwpck_require__(3837) +const Client = __nccwpck_require__(3598) +const { buildMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(4347) +const { MockInterceptor } = __nccwpck_require__(410) +const Symbols = __nccwpck_require__(2785) +const { InvalidArgumentError } = __nccwpck_require__(8045) + +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') } - } - this._encodePax(header) -} -Pack.prototype._encodePax = function (header) { - var paxHeader = headers.encodePax({ - name: header.name, - linkname: header.linkname, - pax: header.pax - }) + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) - var newHeader = { - name: 'PaxHeader', - mode: header.mode, - uid: header.uid, - gid: header.gid, - size: paxHeader.length, - mtime: header.mtime, - type: 'pax-header', - linkname: header.linkname && 'PaxHeader', - uname: header.uname, - gname: header.gname, - devmajor: header.devmajor, - devminor: header.devminor + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] } - this.push(headers.encode(newHeader)) - this.push(paxHeader) - overflow(this, paxHeader.length) + get [Symbols.kConnected] () { + return this[kConnected] + } - newHeader.size = header.size - newHeader.type = header.type - this.push(headers.encode(newHeader)) -} + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } -Pack.prototype._read = function (n) { - var drain = this._drain - this._drain = noop - drain() + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } } -module.exports = Pack +module.exports = MockClient /***/ }), -/***/ 4294: +/***/ 888: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(4219); - +"use strict"; -/***/ }), -/***/ 4219: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const { UndiciError } = __nccwpck_require__(8045) -"use strict"; +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, MockNotMatchedError) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} +module.exports = { + MockNotMatchedError +} -var net = __nccwpck_require__(1808); -var tls = __nccwpck_require__(4404); -var http = __nccwpck_require__(3685); -var https = __nccwpck_require__(5687); -var events = __nccwpck_require__(2361); -var assert = __nccwpck_require__(9491); -var util = __nccwpck_require__(3837); +/***/ }), -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; +/***/ 410: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} +const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = __nccwpck_require__(4347) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { buildURL } = __nccwpck_require__(3983) -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch + } -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + this[kMockDispatch].delay = waitInMs + return this + } -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') } - socket.destroy(); - self.removeSocket(socket); - }); + + this[kMockDispatch].times = repeatTimes + return this + } } -util.inherits(TunnelingAgent, events.EventEmitter); -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); +/** + * Defines an interceptor for a Mock + */ +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false } - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); + createMockScopeDispatchData (statusCode, data, responseOptions = {}) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } - function onFree() { - self.emit('free', socket, options); + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (statusCode, data, responseOptions) { + if (typeof statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof data === 'undefined') { + throw new InvalidArgumentError('data must be defined') } + if (typeof responseOptions !== 'object') { + throw new InvalidArgumentError('responseOptions must be an object') + } + } - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); + /** + * Mock an undici request with a defined reply. + */ + reply (replyData) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyData === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyData(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object') { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const { statusCode, data = '', responseOptions = {} } = resolvedData + this.validateReplyParameters(statusCode, data, responseOptions) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(statusCode, data, responseOptions) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) + return new MockScope(newMockDispatch) } - }); -}; -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const [statusCode, data = '', responseOptions = {}] = [...arguments] + this.validateReplyParameters(statusCode, data, responseOptions) - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) + return new MockScope(newMockDispatch) } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers + return this } - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; + this[kDefaultTrailers] = trailers + return this } - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this } +} - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; + +/***/ }), + +/***/ 6193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { promisify } = __nccwpck_require__(3837) +const Pool = __nccwpck_require__(4634) +const { buildMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(4347) +const { MockInterceptor } = __nccwpck_require__(410) +const Symbols = __nccwpck_require__(2785) +const { InvalidArgumentError } = __nccwpck_require__(8045) + +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } - function onError(cause) { - connectReq.removeAllListeners(); + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] } -}; -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; + get [Symbols.kConnected] () { + return this[kConnected] } - this.sockets.splice(pos, 1); - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) } -}; - -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } } +module.exports = MockPool -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; - } - return host; // for v0.11 or later -} -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } - } - } - return target; -} +/***/ }), +/***/ 4347: +/***/ ((module) => { -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); - } - console.error.apply(console, args); - } -} else { - debug = function() {}; +"use strict"; + + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') } -exports.debug = debug; // for test /***/ }), -/***/ 8729: +/***/ 9323: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -(function(nacl) { -'use strict'; +"use strict"; -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; +const { MockNotMatchedError } = __nccwpck_require__(888) +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = __nccwpck_require__(4347) +const { buildURL, nop } = __nccwpck_require__(3983) +const { STATUS_CODES } = __nccwpck_require__(3685) +const { + types: { + isPromise + } +} = __nccwpck_require__(3837) -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} -var _0 = new Uint8Array(16); -var _9 = new Uint8Array(32); _9[0] = 9; +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } -function ts64(x, i, h, l) { - x[i] = (h >> 24) & 0xff; - x[i+1] = (h >> 16) & 0xff; - x[i+2] = (h >> 8) & 0xff; - x[i+3] = h & 0xff; - x[i+4] = (l >> 24) & 0xff; - x[i+5] = (l >> 16) & 0xff; - x[i+6] = (l >> 8) & 0xff; - x[i+7] = l & 0xff; + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } } -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) } -function crypto_verify_16(x, xi, y, yi) { - return vn(x,xi,y,yi,16); -} +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true } -function core_salsa20(o, p, k, c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; + const pathSegments = path.split('?') - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); + if (pathSegments.length !== 2) { + return path + } - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } +} - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) + } - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) } - x0 = x0 + j0 | 0; - x1 = x1 + j1 | 0; - x2 = x2 + j2 | 0; - x3 = x3 + j3 | 0; - x4 = x4 + j4 | 0; - x5 = x5 + j5 | 0; - x6 = x6 + j6 | 0; - x7 = x7 + j7 | 0; - x8 = x8 + j8 | 0; - x9 = x9 + j9 | 0; - x10 = x10 + j10 | 0; - x11 = x11 + j11 | 0; - x12 = x12 + j12 | 0; - x13 = x13 + j13 | 0; - x14 = x14 + j14 | 0; - x15 = x15 + j15 | 0; - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) + } - o[ 4] = x1 >>> 0 & 0xff; - o[ 5] = x1 >>> 8 & 0xff; - o[ 6] = x1 >>> 16 & 0xff; - o[ 7] = x1 >>> 24 & 0xff; + return matchedMockDispatches[0] +} - o[ 8] = x2 >>> 0 & 0xff; - o[ 9] = x2 >>> 8 & 0xff; - o[10] = x2 >>> 16 & 0xff; - o[11] = x2 >>> 24 & 0xff; +function addMockDispatch (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch +} - o[12] = x3 >>> 0 & 0xff; - o[13] = x3 >>> 8 & 0xff; - o[14] = x3 >>> 16 & 0xff; - o[15] = x3 >>> 24 & 0xff; +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) + } +} - o[16] = x4 >>> 0 & 0xff; - o[17] = x4 >>> 8 & 0xff; - o[18] = x4 >>> 16 & 0xff; - o[19] = x4 >>> 24 & 0xff; +function buildKey (opts) { + const { path, method, body, headers, query } = opts + return { + path, + method, + body, + headers, + query + } +} - o[20] = x5 >>> 0 & 0xff; - o[21] = x5 >>> 8 & 0xff; - o[22] = x5 >>> 16 & 0xff; - o[23] = x5 >>> 24 & 0xff; +function generateKeyValues (data) { + return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ + ...keyValuePairs, + Buffer.from(`${key}`), + Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) + ], []) +} - o[24] = x6 >>> 0 & 0xff; - o[25] = x6 >>> 8 & 0xff; - o[26] = x6 >>> 16 & 0xff; - o[27] = x6 >>> 24 & 0xff; +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' +} - o[28] = x7 >>> 0 & 0xff; - o[29] = x7 >>> 8 & 0xff; - o[30] = x7 >>> 16 & 0xff; - o[31] = x7 >>> 24 & 0xff; +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') +} - o[32] = x8 >>> 0 & 0xff; - o[33] = x8 >>> 8 & 0xff; - o[34] = x8 >>> 16 & 0xff; - o[35] = x8 >>> 24 & 0xff; +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) - o[36] = x9 >>> 0 & 0xff; - o[37] = x9 >>> 8 & 0xff; - o[38] = x9 >>> 16 & 0xff; - o[39] = x9 >>> 24 & 0xff; + mockDispatch.timesInvoked++ - o[40] = x10 >>> 0 & 0xff; - o[41] = x10 >>> 8 & 0xff; - o[42] = x10 >>> 16 & 0xff; - o[43] = x10 >>> 24 & 0xff; + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } - o[44] = x11 >>> 0 & 0xff; - o[45] = x11 >>> 8 & 0xff; - o[46] = x11 >>> 16 & 0xff; - o[47] = x11 >>> 24 & 0xff; + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch - o[48] = x12 >>> 0 & 0xff; - o[49] = x12 >>> 8 & 0xff; - o[50] = x12 >>> 16 & 0xff; - o[51] = x12 >>> 24 & 0xff; + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times - o[52] = x13 >>> 0 & 0xff; - o[53] = x13 >>> 8 & 0xff; - o[54] = x13 >>> 16 & 0xff; - o[55] = x13 >>> 24 & 0xff; + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } - o[56] = x14 >>> 0 & 0xff; - o[57] = x14 >>> 8 & 0xff; - o[58] = x14 >>> 16 & 0xff; - o[59] = x14 >>> 24 & 0xff; + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)) + return + } - o[60] = x15 >>> 0 & 0xff; - o[61] = x15 >>> 8 & 0xff; - o[62] = x15 >>> 16 & 0xff; - o[63] = x15 >>> 24 & 0xff; + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.abort = nop + handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData(Buffer.from(responseData)) + handler.onComplete(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true } -function core_hsalsa20(o,p,k,c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } +} - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); +function buildMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts + return mockOptions + } +} - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildMockOptions, + getHeaderByName +} - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); +/***/ }), - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); +/***/ 6823: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); +"use strict"; - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); +const { Transform } = __nccwpck_require__(2781) +const { Console } = __nccwpck_require__(6206) + +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) + } + }) + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) } - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? '✅' : '❌', + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) - o[ 4] = x5 >>> 0 & 0xff; - o[ 5] = x5 >>> 8 & 0xff; - o[ 6] = x5 >>> 16 & 0xff; - o[ 7] = x5 >>> 24 & 0xff; + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() + } +} - o[ 8] = x10 >>> 0 & 0xff; - o[ 9] = x10 >>> 8 & 0xff; - o[10] = x10 >>> 16 & 0xff; - o[11] = x10 >>> 24 & 0xff; - o[12] = x15 >>> 0 & 0xff; - o[13] = x15 >>> 8 & 0xff; - o[14] = x15 >>> 16 & 0xff; - o[15] = x15 >>> 24 & 0xff; +/***/ }), - o[16] = x6 >>> 0 & 0xff; - o[17] = x6 >>> 8 & 0xff; - o[18] = x6 >>> 16 & 0xff; - o[19] = x6 >>> 24 & 0xff; +/***/ 8891: +/***/ ((module) => { - o[20] = x7 >>> 0 & 0xff; - o[21] = x7 >>> 8 & 0xff; - o[22] = x7 >>> 16 & 0xff; - o[23] = x7 >>> 24 & 0xff; +"use strict"; - o[24] = x8 >>> 0 & 0xff; - o[25] = x8 >>> 8 & 0xff; - o[26] = x8 >>> 16 & 0xff; - o[27] = x8 >>> 24 & 0xff; - o[28] = x9 >>> 0 & 0xff; - o[29] = x9 >>> 8 & 0xff; - o[30] = x9 >>> 16 & 0xff; - o[31] = x9 >>> 24 & 0xff; +const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' } -function crypto_core_salsa20(out,inp,k,c) { - core_salsa20(out,inp,k,c); +const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' } -function crypto_core_hsalsa20(out,inp,k,c) { - core_hsalsa20(out,inp,k,c); +module.exports = class Pluralizer { + constructor (singular, plural) { + this.singular = singular + this.plural = plural + } + + pluralize (count) { + const one = count === 1 + const keys = one ? singulars : plurals + const noun = one ? this.singular : this.plural + return { ...keys, count, noun } + } } -var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - // "expand 32-byte k" -function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - mpos += 64; +/***/ }), + +/***/ 8266: +/***/ ((module) => { + +"use strict"; +/* eslint-disable */ + + + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048; +const kMask = kSize - 1; + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | [empty] | <-- top | item | | item | +// | [empty] | | item | | item | +// | [empty] | | [empty] | <-- top top --> | [empty] | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | [empty] | | item | +// | [empty] | | item | +// | item | <-- bottom top --> | [empty] | +// | item | | [empty] | +// | [empty] | <-- top bottom --> | item | +// | [empty] | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; } - return 0; } -function crypto_stream_salsa20(c,cpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; +module.exports = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); } - b -= 64; - cpos += 64; + this.head.push(data); } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = x[i]; + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; } - return 0; -} +}; -function crypto_stream(c,cpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20(c,cpos,d,sn,s); -} -function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); -} +/***/ }), -/* -* Port of Andrew Moon's Poly1305-donna-16. Public domain. -* https://github.com/floodyberry/poly1305-donna -*/ +/***/ 3198: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var poly1305 = function(key) { - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.leftover = 0; - this.fin = 0; +"use strict"; - var t0, t1, t2, t3, t4, t5, t6, t7; - t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; - t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; - t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; - this.r[5] = ((t4 >>> 1)) & 0x1ffe; - t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; - t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - this.r[9] = ((t7 >>> 5)) & 0x007f; +const DispatcherBase = __nccwpck_require__(4839) +const FixedQueue = __nccwpck_require__(8266) +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(2785) +const PoolStats = __nccwpck_require__(9689) - this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; - this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; - this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; - this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; - this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; - this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; - this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; - this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; -}; +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') +const kStats = Symbol('stats') -poly1305.prototype.blocks = function(m, mpos, bytes) { - var hibit = this.fin ? 0 : (1 << 11); - var t0, t1, t2, t3, t4, t5, t6, t7, c; - var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; +class PoolBase extends DispatcherBase { + constructor () { + super() - var h0 = this.h[0], - h1 = this.h[1], - h2 = this.h[2], - h3 = this.h[3], - h4 = this.h[4], - h5 = this.h[5], - h6 = this.h[6], - h7 = this.h[7], - h8 = this.h[8], - h9 = this.h[9]; + this[kQueue] = new FixedQueue() + this[kClients] = [] + this[kQueued] = 0 - var r0 = this.r[0], - r1 = this.r[1], - r2 = this.r[2], - r3 = this.r[3], - r4 = this.r[4], - r5 = this.r[5], - r6 = this.r[6], - r7 = this.r[7], - r8 = this.r[8], - r9 = this.r[9]; + const pool = this - while (bytes >= 16) { - t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; - t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; - t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; - h5 += ((t4 >>> 1)) & 0x1fff; - t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; - t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - h9 += ((t7 >>> 5)) | hibit; + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue] - c = 0; + let needDrain = false - d0 = c; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h2 * (5 * r8); - d0 += h3 * (5 * r7); - d0 += h4 * (5 * r6); - c = (d0 >>> 13); d0 &= 0x1fff; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c += (d0 >>> 13); d0 &= 0x1fff; + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + pool[kQueued]-- + needDrain = !this.dispatch(item.opts, item.handler) + } - d1 = c; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h2 * (5 * r9); - d1 += h3 * (5 * r8); - d1 += h4 * (5 * r7); - c = (d1 >>> 13); d1 &= 0x1fff; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c += (d1 >>> 13); d1 &= 0x1fff; + this[kNeedDrain] = needDrain - d2 = c; - d2 += h0 * r2; - d2 += h1 * r1; - d2 += h2 * r0; - d2 += h3 * (5 * r9); - d2 += h4 * (5 * r8); - c = (d2 >>> 13); d2 &= 0x1fff; - d2 += h5 * (5 * r7); - d2 += h6 * (5 * r6); - d2 += h7 * (5 * r5); - d2 += h8 * (5 * r4); - d2 += h9 * (5 * r3); - c += (d2 >>> 13); d2 &= 0x1fff; + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false + pool.emit('drain', origin, [pool, ...targets]) + } - d3 = c; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h2 * r1; - d3 += h3 * r0; - d3 += h4 * (5 * r9); - c = (d3 >>> 13); d3 &= 0x1fff; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c += (d3 >>> 13); d3 &= 0x1fff; + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]) + } + } - d4 = c; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h2 * r2; - d4 += h3 * r1; - d4 += h4 * r0; - c = (d4 >>> 13); d4 &= 0x1fff; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c += (d4 >>> 13); d4 &= 0x1fff; + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]) + } - d5 = c; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h2 * r3; - d5 += h3 * r2; - d5 += h4 * r1; - c = (d5 >>> 13); d5 &= 0x1fff; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c += (d5 >>> 13); d5 &= 0x1fff; + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err) + } - d6 = c; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h2 * r4; - d6 += h3 * r3; - d6 += h4 * r2; - c = (d6 >>> 13); d6 &= 0x1fff; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c += (d6 >>> 13); d6 &= 0x1fff; + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err) + } - d7 = c; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h2 * r5; - d7 += h3 * r4; - d7 += h4 * r3; - c = (d7 >>> 13); d7 &= 0x1fff; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c += (d7 >>> 13); d7 &= 0x1fff; + this[kStats] = new PoolStats(this) + } - d8 = c; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h2 * r6; - d8 += h3 * r5; - d8 += h4 * r4; - c = (d8 >>> 13); d8 &= 0x1fff; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c += (d8 >>> 13); d8 &= 0x1fff; + get [kBusy] () { + return this[kNeedDrain] + } - d9 = c; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h2 * r7; - d9 += h3 * r6; - d9 += h4 * r5; - c = (d9 >>> 13); d9 &= 0x1fff; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c += (d9 >>> 13); d9 &= 0x1fff; + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } - c = (((c << 2) + c)) | 0; - c = (c + d0) | 0; - d0 = c & 0x1fff; - c = (c >>> 13); - d1 += c; + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } - h0 = d0; - h1 = d1; - h2 = d2; - h3 = d3; - h4 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending + } + return ret + } - mpos += 16; - bytes -= 16; + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret } - this.h[0] = h0; - this.h[1] = h1; - this.h[2] = h2; - this.h[3] = h3; - this.h[4] = h4; - this.h[5] = h5; - this.h[6] = h6; - this.h[7] = h7; - this.h[8] = h8; - this.h[9] = h9; -}; -poly1305.prototype.finish = function(mac, macpos) { - var g = new Uint16Array(10); - var c, mask, f, i; + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret + } - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); + get stats () { + return this[kStats] } - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - for (i = 2; i < 10; i++) { - this.h[i] += c; - c = this.h[i] >>> 13; - this.h[i] &= 0x1fff; + async [kClose] () { + if (this[kQueue].isEmpty()) { + return Promise.all(this[kClients].map(c => c.close())) + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve + }) + } + } + + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) + } + + return Promise.all(this[kClients].map(c => c.destroy(err))) + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + process.nextTick(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]) + } + }) + } + + return this } - this.h[0] += (c * 5); - c = this.h[0] >>> 13; - this.h[0] &= 0x1fff; - this.h[1] += c; - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - this.h[2] += c; - g[0] = this.h[0] + 5; - c = g[0] >>> 13; - g[0] &= 0x1fff; - for (i = 1; i < 10; i++) { - g[i] = this.h[i] + c; - c = g[i] >>> 13; - g[i] &= 0x1fff; + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) } - g[9] -= (1 << 13); +} - mask = (c ^ 1) - 1; - for (i = 0; i < 10; i++) g[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} - this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; - this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; - this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; - this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; - this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; - this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; - this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; - this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; - f = this.h[0] + this.pad[0]; - this.h[0] = f & 0xffff; - for (i = 1; i < 8; i++) { - f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; - this.h[i] = f & 0xffff; +/***/ }), + +/***/ 9689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(2785) +const kPool = Symbol('pool') + +class PoolStats { + constructor (pool) { + this[kPool] = pool } - mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; - mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; - mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; - mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; - mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; - mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; - mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; - mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; - mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; - mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; - mac[macpos+10] = (this.h[5] >>> 0) & 0xff; - mac[macpos+11] = (this.h[5] >>> 8) & 0xff; - mac[macpos+12] = (this.h[6] >>> 0) & 0xff; - mac[macpos+13] = (this.h[6] >>> 8) & 0xff; - mac[macpos+14] = (this.h[7] >>> 0) & 0xff; - mac[macpos+15] = (this.h[7] >>> 8) & 0xff; -}; + get connected () { + return this[kPool][kConnected] + } -poly1305.prototype.update = function(m, mpos, bytes) { - var i, want; + get free () { + return this[kPool][kFree] + } - if (this.leftover) { - want = (16 - this.leftover); - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; + get pending () { + return this[kPool][kPending] } - if (bytes >= 16) { - want = bytes - (bytes % 16); - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; + get queued () { + return this[kPool][kQueued] } - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; + get running () { + return this[kPool][kRunning] } -}; -function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s = new poly1305(k); - s.update(m, mpos, n); - s.finish(out, outpos); - return 0; + get size () { + return this[kPool][kSize] + } } -function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x,0,m,mpos,n,k); - return crypto_verify_16(h,hpos,x,0); -} +module.exports = PoolStats -function crypto_secretbox(c,m,d,n,k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c,0,m,0,d,n,k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; -} -function crypto_secretbox_open(m,c,d,n,k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x,0,32,n,k); - if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; - crypto_stream_xor(m,0,c,0,d,n,k); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; -} +/***/ }), -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} +/***/ 4634: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} +"use strict"; -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher +} = __nccwpck_require__(3198) +const Client = __nccwpck_require__(3598) +const { + InvalidArgumentError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { kUrl, kInterceptors } = __nccwpck_require__(2785) +const buildConnector = __nccwpck_require__(2067) + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + ...options + } = {}) { + super() + + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); + + this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : [] + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2 } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; + + [kGetDispatcher] () { + let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + + if (dispatcher) { + return dispatcher + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + } + + return dispatcher } } -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} +module.exports = Pool -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; +/***/ }), + +/***/ 7858: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(2785) +const { URL } = __nccwpck_require__(7310) +const Agent = __nccwpck_require__(7890) +const Pool = __nccwpck_require__(4634) +const DispatcherBase = __nccwpck_require__(4839) +const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8045) +const buildConnector = __nccwpck_require__(2067) + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 } -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +function buildProxyOptions (opts) { + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + return { + uri: opts.uri, + protocol: opts.protocol || 'https' + } } -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +function defaultFactory (origin, opts) { + return new Pool(origin, opts) } -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; +class ProxyAgent extends DispatcherBase { + constructor (opts) { + super(opts) + this[kProxy] = buildProxyOptions(opts) + this[kAgent] = new Agent(opts) + this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : [] - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + + const resolvedUrl = new URL(opts.uri) + const { origin, port, host, username, password } = resolvedUrl + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } else if (username && password) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` + } + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + this[kClient] = clientFactory(resolvedUrl, { connect }) + this[kAgent] = new Agent({ + ...opts, + connect: async (opts, callback) => { + let requestedHost = opts.host + if (!opts.port) { + requestedHost += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedHost, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host + } + }) + if (statusCode !== 200) { + socket.on('error', () => {}).destroy() + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) + } + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + callback(err) + } + } + }) + } - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is + dispatch (opts, handler) { + const { host } = new URL(opts.origin) + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + return this[kAgent].dispatch( + { + ...opts, + headers: { + ...headers, + host + } + }, + handler + ) + } - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + async [kClose] () { + await this[kAgent].close() + await this[kClient].close() + } - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + async [kDestroy] () { + await this[kAgent].destroy() + await this[kClient].destroy() + } +} - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] + } + + return headersPair + } + + return headers } -function S(o, a) { - M(o, a, a); +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } } -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); +module.exports = ProxyAgent + + +/***/ }), + +/***/ 9459: +/***/ ((module) => { + +"use strict"; + + +let fastNow = Date.now() +let fastNowTimeout + +const fastTimers = [] + +function onTimeout () { + fastNow = Date.now() + + let len = fastTimers.length + let idx = 0 + while (idx < len) { + const timer = fastTimers[idx] + + if (timer.state === 0) { + timer.state = fastNow + timer.delay + } else if (timer.state > 0 && fastNow >= timer.state) { + timer.state = -1 + timer.callback(timer.opaque) + } + + if (timer.state === -1) { + timer.state = -2 + if (idx !== len - 1) { + fastTimers[idx] = fastTimers.pop() + } else { + fastTimers.pop() + } + len -= 1 + } else { + idx += 1 + } + } + + if (fastTimers.length > 0) { + refreshTimeout() } - for (a = 0; a < 16; a++) o[a] = c[a]; } -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); +function refreshTimeout () { + if (fastNowTimeout && fastNowTimeout.refresh) { + fastNowTimeout.refresh() + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTimeout, 1e3) + if (fastNowTimeout.unref) { + fastNowTimeout.unref() + } } - for (a = 0; a < 16; a++) o[a] = c[a]; } -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; +class Timeout { + constructor (callback, delay, opaque) { + this.callback = callback + this.delay = delay + this.opaque = opaque + + // -2 not in timer list + // -1 in timer list but inactive + // 0 in timer list waiting for time + // > 0 in timer list waiting for time to expire + this.state = -2 + + this.refresh() } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); + + refresh () { + if (this.state === -2) { + fastTimers.push(this) + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + } + + this.state = 0 } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; + + clear () { + this.state = -1 } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; } -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); +module.exports = { + setTimeout (callback, delay, opaque) { + return delay < 1e3 + ? setTimeout(callback, delay, opaque) + : new Timeout(callback, delay, opaque) + }, + clearTimeout (timeout) { + if (timeout instanceof Timeout) { + timeout.clear() + } else { + clearTimeout(timeout) + } + } } -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); + +/***/ }), + +/***/ 5354: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const diagnosticsChannel = __nccwpck_require__(7643) +const { uid, states } = __nccwpck_require__(9188) +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose +} = __nccwpck_require__(7578) +const { fireEvent, failWebsocketConnection } = __nccwpck_require__(5515) +const { CloseEvent } = __nccwpck_require__(2611) +const { makeRequest } = __nccwpck_require__(8359) +const { fetching } = __nccwpck_require__(4881) +const { Headers } = __nccwpck_require__(554) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { kHeadersList } = __nccwpck_require__(2785) + +const channels = {} +channels.open = diagnosticsChannel.channel('undici:websocket:open') +channels.close = diagnosticsChannel.channel('undici:websocket:close') +channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = __nccwpck_require__(6113) +} catch { + } -function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any) => void} onEstablish + * @param {Partial} options + */ +function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }) + + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = new Headers(options.headers)[kHeadersList] + + request.headersList = headersList + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13') + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + // TODO: enable once permessage-deflate is supported + const permessageDeflate = '' // 'permessage-deflate; 15' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + // request.headersList.append('sec-websocket-extensions', permessageDeflate) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher ?? getGlobalDispatcher(), + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.') + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.') + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') + + if (secExtension !== null && secExtension !== permessageDeflate) { + failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') + return + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') + + if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') + return + } + + response.socket.on('data', onSocketData) + response.socket.on('close', onSocketClose) + response.socket.on('error', onSocketError) + + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }) + } + + onEstablish(response) + } + }) + + return controller } -var crypto_box_afternm = crypto_secretbox; -var crypto_box_open_afternm = crypto_secretbox_open; +/** + * @param {Buffer} chunk + */ +function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause() + } +} -function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ +function onSocketClose () { + const { ws } = this + + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] && ws[kReceivedClose] + + let code = 1005 + let reason = '' + + const result = ws[kByteParser].closingInfo + + if (result) { + code = result.code ?? 1005 + reason = result.reason + } else if (!ws[kSentClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + } + + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + fireEvent('close', ws, CloseEvent, { + wasClean, code, reason + }) + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }) + } } -function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); +function onSocketError (error) { + const { ws } = this + + ws[kReadyState] = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error) + } + + this.destroy() } -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; +module.exports = { + establishWebSocketConnection +} -function crypto_hashblocks_hl(hh, hl, m, n) { - var wh = new Int32Array(16), wl = new Int32Array(16), - bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, - bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, - th, tl, i, j, h, l, a, b, c, d; - var ah0 = hh[0], - ah1 = hh[1], - ah2 = hh[2], - ah3 = hh[3], - ah4 = hh[4], - ah5 = hh[5], - ah6 = hh[6], - ah7 = hh[7], +/***/ }), - al0 = hl[0], - al1 = hl[1], - al2 = hl[2], - al3 = hl[3], - al4 = hl[4], - al5 = hl[5], - al6 = hl[6], - al7 = hl[7]; +/***/ 9188: +/***/ ((module) => { - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) { - j = 8 * i + pos; - wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; - wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; +"use strict"; + + +// This is a Globally Unique Identifier unique used +// to validate that the endpoint accepts websocket +// connections. +// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 +} + +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA +} + +const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 + +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 +} + +const emptyBuffer = Buffer.allocUnsafe(0) + +module.exports = { + uid, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer +} + + +/***/ }), + +/***/ 2611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const { MessagePort } = __nccwpck_require__(1267) + +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.MessageEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get data () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent) + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) } - for (i = 0; i < 80; i++) { - bh0 = ah0; - bh1 = ah1; - bh2 = ah2; - bh3 = ah3; - bh4 = ah4; - bh5 = ah5; - bh6 = ah6; - bh7 = ah7; - bl0 = al0; - bl1 = al1; - bl2 = al2; - bl3 = al3; - bl4 = al4; - bl5 = al5; - bl6 = al6; - bl7 = al7; + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } +} + +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason + } +} + +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) + + super(type, eventInitDict) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict + } + + get message () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.error + } +} + +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) + +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) + +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) + +webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +] + +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + get defaultValue () { + return [] + } + } +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'error', + converter: webidl.converters.any + } +]) + +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent +} + + +/***/ }), - // add - h = ah7; - l = al7; +/***/ 5444: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +"use strict"; - // Sigma1 - h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); - l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +const { maxUnsigned16Bit } = __nccwpck_require__(9188) - // Ch - h = (ah4 & ah5) ^ (~ah4 & ah6); - l = (al4 & al5) ^ (~al4 & al6); +/** @type {import('crypto')} */ +let crypto +try { + crypto = __nccwpck_require__(6113) +} catch { - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +} - // K - h = K[i*2]; - l = K[i*2+1]; +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + this.maskKey = crypto.randomBytes(4) + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + createFrame (opcode) { + const bodyLength = this.frameData?.byteLength ?? 0 - // w - h = wh[i%16]; - l = wl[i%16]; + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + const buffer = Buffer.allocUnsafe(bodyLength + offset) - th = c & 0xffff | d << 16; - tl = a & 0xffff | b << 16; + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode - // add - h = th; - l = tl; + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = this.maskKey[0] + buffer[offset - 3] = this.maskKey[1] + buffer[offset - 2] = this.maskKey[2] + buffer[offset - 1] = this.maskKey[3] - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + buffer[1] = payloadLength - // Sigma0 - h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); - l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + buffer[1] |= 0x80 // MASK - // Maj - h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); - l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + // mask body + for (let i = 0; i < bodyLength; i++) { + buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + return buffer + } +} - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; +module.exports = { + WebsocketFrameSend +} - bh7 = (c & 0xffff) | (d << 16); - bl7 = (a & 0xffff) | (b << 16); - // add - h = bh3; - l = bl3; +/***/ }), - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +/***/ 1688: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - h = th; - l = tl; +"use strict"; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; +const { Writable } = __nccwpck_require__(2781) +const diagnosticsChannel = __nccwpck_require__(7643) +const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(9188) +const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(7578) +const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(5515) +const { WebsocketFrameSend } = __nccwpck_require__(5444) - bh3 = (c & 0xffff) | (d << 16); - bl3 = (a & 0xffff) | (b << 16); +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; +const channels = {} +channels.ping = diagnosticsChannel.channel('undici:websocket:ping') +channels.pong = diagnosticsChannel.channel('undici:websocket:pong') - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; +class ByteParser extends Writable { + #buffers = [] + #byteOffset = 0 - if (i%16 === 15) { - for (j = 0; j < 16; j++) { - // add - h = wh[j]; - l = wl[j]; + #state = parserStates.INFO - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + #info = {} + #fragments = [] - h = wh[(j+9)%16]; - l = wl[(j+9)%16]; + constructor (ws) { + super() - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + this.ws = ws + } - // sigma0 - th = wh[(j+1)%16]; - tl = wl[(j+1)%16]; - h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); - l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + this.run(callback) + } - // sigma1 - th = wh[(j+14)%16]; - tl = wl[(j+14)%16]; - h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); - l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (true) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.fin = (buffer[0] & 0x80) !== 0 + this.#info.opcode = buffer[0] & 0x0F + + // If we receive a fragmented message, we use the type of the first + // frame to parse the full message as binary/text, when it's terminated + this.#info.originalOpcode ??= this.#info.opcode + + this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION + + if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') + return + } + + const payloadLength = buffer[1] & 0x7F + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } + + if (this.#info.fragmented && payloadLength > 125) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') + return + } else if ( + (this.#info.opcode === opcodes.PING || + this.#info.opcode === opcodes.PONG || + this.#info.opcode === opcodes.CLOSE) && + payloadLength > 125 + ) { + // Control frames can have a payload length of 125 bytes MAX + failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') + return + } else if (this.#info.opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') + return + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + const body = this.consume(payloadLength) - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + this.#info.closeInfo = this.parseCloseBody(false, body) - wh[j] = (c & 0xffff) | (d << 16); - wl[j] = (a & 0xffff) | (b << 16); - } - } - } + if (!this.ws[kSentClose]) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + const body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + const closeFrame = new WebsocketFrameSend(body) - // add - h = ah0; - l = al0; + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true + } + } + ) + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING + this.ws[kReceivedClose] = true - h = hh[0]; - l = hl[0]; + this.end() - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + return + } else if (this.#info.opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + const body = this.consume(payloadLength) - hh[0] = ah0 = (c & 0xffff) | (d << 16); - hl[0] = al0 = (a & 0xffff) | (b << 16); + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body) - h = ah1; - l = al1; + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }) + } + } - h = hh[1]; - l = hl[1]; + this.#state = parserStates.INFO - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } else if (this.#info.opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + const body = this.consume(payloadLength) - hh[1] = ah1 = (c & 0xffff) | (d << 16); - hl[1] = al1 = (a & 0xffff) | (b << 16); + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }) + } - h = ah2; - l = al2; + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + const buffer = this.consume(2) - h = hh[2]; - l = hl[2]; + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + // 2^31 is the maxinimum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') + return + } - hh[2] = ah2 = (c & 0xffff) | (d << 16); - hl[2] = al2 = (a & 0xffff) | (b << 16); + const lower = buffer.readUInt32BE(4) - h = ah3; - l = al3; + this.#info.payloadLength = (upper << 8) + lower + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + // If there is still more data in this chunk that needs to be read + return callback() + } else if (this.#byteOffset >= this.#info.payloadLength) { + // If the server sent multiple frames in a single chunk - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + const body = this.consume(this.#info.payloadLength) - h = hh[3]; - l = hl[3]; + this.#fragments.push(body) - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + // If the frame is unfragmented, or a fragmented frame was terminated, + // a message was received + if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { + const fullMessage = Buffer.concat(this.#fragments) - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) - hh[3] = ah3 = (c & 0xffff) | (d << 16); - hl[3] = al3 = (a & 0xffff) | (b << 16); + this.#info = {} + this.#fragments.length = 0 + } - h = ah4; - l = al4; + this.#state = parserStates.INFO + } + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + if (this.#byteOffset > 0) { + continue + } else { + callback() + break + } + } + } - h = hh[4]; - l = hl[4]; + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer|null} + */ + consume (n) { + if (n > this.#byteOffset) { + return null + } else if (n === 0) { + return emptyBuffer + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length + return this.#buffers.shift() + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + const buffer = Buffer.allocUnsafe(n) + let offset = 0 - hh[4] = ah4 = (c & 0xffff) | (d << 16); - hl[4] = al4 = (a & 0xffff) | (b << 16); + while (offset !== n) { + const next = this.#buffers[0] + const { length } = next - h = ah5; - l = al5; + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += next.length + } + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + this.#byteOffset -= n - h = hh[5]; - l = hl[5]; + return buffer + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } - hh[5] = ah5 = (c & 0xffff) | (d << 16); - hl[5] = al5 = (a & 0xffff) | (b << 16); + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } - h = ah6; - l = al6; + return { code } + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) - h = hh[6]; - l = hl[6]; + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (code !== undefined && !isValidStatusCode(code)) { + return null + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + try { + // TODO: optimize this + reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) + } catch { + return null + } - hh[6] = ah6 = (c & 0xffff) | (d << 16); - hl[6] = al6 = (a & 0xffff) | (b << 16); + return { code, reason } + } - h = ah7; - l = al7; + get closingInfo () { + return this.#info.closeInfo + } +} - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +module.exports = { + ByteParser +} - h = hh[7]; - l = hl[7]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +/***/ }), - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; +/***/ 7578: +/***/ ((module) => { - hh[7] = ah7 = (c & 0xffff) | (d << 16); - hl[7] = al7 = (a & 0xffff) | (b << 16); +"use strict"; - pos += 128; - n -= 128; - } - return n; +module.exports = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') } -function crypto_hash(out, m, n) { - var hh = new Int32Array(8), - hl = new Int32Array(8), - x = new Uint8Array(256), - i, b = n; - hh[0] = 0x6a09e667; - hh[1] = 0xbb67ae85; - hh[2] = 0x3c6ef372; - hh[3] = 0xa54ff53a; - hh[4] = 0x510e527f; - hh[5] = 0x9b05688c; - hh[6] = 0x1f83d9ab; - hh[7] = 0x5be0cd19; +/***/ }), - hl[0] = 0xf3bcc908; - hl[1] = 0x84caa73b; - hl[2] = 0xfe94f82b; - hl[3] = 0x5f1d36f1; - hl[4] = 0xade682d1; - hl[5] = 0x2b3e6c1f; - hl[6] = 0xfb41bd6b; - hl[7] = 0x137e2179; +/***/ 5515: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - crypto_hashblocks_hl(hh, hl, m, n); - n %= 128; +"use strict"; - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; - n = 256-128*(n<112?1:0); - x[n-9] = 0; - ts64(x, n-8, (b / 0x20000000) | 0, b << 3); - crypto_hashblocks_hl(hh, hl, x, n); +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(7578) +const { states, opcodes } = __nccwpck_require__(9188) +const { MessageEvent, ErrorEvent } = __nccwpck_require__(2611) - for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); +/* globals Blob */ - return 0; +/** + * @param {import('./websocket').WebSocket} ws + */ +function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN } -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING +} - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosed (ws) { + return ws[kReadyState] === states.CLOSED +} - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {EventInit | undefined} eventInitDict + */ +function fireEvent (e, target, eventConstructor = Event, eventInitDict) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) } -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ +function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return } -} -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = new Uint8Array(data).buffer + } } -} -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, MessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }) } -function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; + for (const char of protocol) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || + code > 0x7E || + char === '(' || + char === ')' || + char === '<' || + char === '>' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' || + code === 32 || // SP + code === 9 // HT + ) { + return false + } + } - scalarbase(p, d); - pack(pk, p); + return true +} - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 } -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; + controller.abort() + + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; + + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }) } } -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); +module.exports = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived } -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; +/***/ }), + +/***/ 4284: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { webidl } = __nccwpck_require__(1744) +const { DOMException } = __nccwpck_require__(1037) +const { URLSerializer } = __nccwpck_require__(685) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(9188) +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = __nccwpck_require__(7578) +const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(5515) +const { establishWebSocketConnection } = __nccwpck_require__(5354) +const { WebsocketFrameSend } = __nccwpck_require__(5444) +const { ByteParser } = __nccwpck_require__(1688) +const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3983) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { types } = __nccwpck_require__(3837) + +let experimentalWarned = false + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('WebSockets are experimental, expect them to change at any time.', { + code: 'UNDICI-WS' + }) + } + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) + + url = webidl.converters.USVString(url) + protocols = options.protocols + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = getGlobalOrigin() + + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". + urlRecord.protocol = 'wss:' + } + + // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 9. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href) + + // 11. Let client be this's relevant settings object. + + // 12. Run this step in parallel: + + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob' + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, { clamp: true }) + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason) + } + + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + let reasonByteLength = 0 - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason) - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); + // 3. Run the first matching steps from the following list: + if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { + // If this's ready state is CLOSING (2) or CLOSED (3) + // Do nothing. + } else if (!isEstablished(this)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(this, 'Connection was closed before it was established.') + this[kReadyState] = WebSocket.CLOSING + } else if (!isClosing(this)) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + socket.write(frame.createFrame(opcodes.CLOSE), (err) => { + if (!err) { + this[kSentClose] = true + } + }) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this[kReadyState] = states.CLOSING + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + this[kReadyState] = WebSocket.CLOSING } } - modL(sm.subarray(32), x); - return smlen; -} + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); + data = webidl.converters.WebSocketSendData(data) - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (this[kReadyState] === WebSocket.CONNECTING) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); + if (!isEstablished(this) || isClosing(this)) { + return + } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.TEXT) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + const ab = Buffer.from(data, data.byteOffset, data.byteLength) + + const frame = new WebsocketFrameSend(ab) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += ab.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= ab.byteLength + }) + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + const frame = new WebsocketFrameSend() + + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab) + frame.frameData = value + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + }) + } + } - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + get readyState () { + webidl.brandCheck(this, WebSocket) - M(r[3], r[0], r[1]); - return 0; -} + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) - mlen = -1; - if (n < 64) return -1; + return this.#bufferedAmount + } - if (unpackneg(q, pk)) return -1; + get url () { + webidl.brandCheck(this, WebSocket) - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); + get extensions () { + webidl.brandCheck(this, WebSocket) - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; + return this.#extensions } - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; -} - -var crypto_secretbox_KEYBYTES = 32, - crypto_secretbox_NONCEBYTES = 24, - crypto_secretbox_ZEROBYTES = 32, - crypto_secretbox_BOXZEROBYTES = 16, - crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_box_BEFORENMBYTES = 32, - crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, - crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, - crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32, - crypto_hash_BYTES = 64; + get protocol () { + webidl.brandCheck(this, WebSocket) -nacl.lowlevel = { - crypto_core_hsalsa20: crypto_core_hsalsa20, - crypto_stream_xor: crypto_stream_xor, - crypto_stream: crypto_stream, - crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, - crypto_stream_salsa20: crypto_stream_salsa20, - crypto_onetimeauth: crypto_onetimeauth, - crypto_onetimeauth_verify: crypto_onetimeauth_verify, - crypto_verify_16: crypto_verify_16, - crypto_verify_32: crypto_verify_32, - crypto_secretbox: crypto_secretbox, - crypto_secretbox_open: crypto_secretbox_open, - crypto_scalarmult: crypto_scalarmult, - crypto_scalarmult_base: crypto_scalarmult_base, - crypto_box_beforenm: crypto_box_beforenm, - crypto_box_afternm: crypto_box_afternm, - crypto_box: crypto_box, - crypto_box_open: crypto_box_open, - crypto_box_keypair: crypto_box_keypair, - crypto_hash: crypto_hash, - crypto_sign: crypto_sign, - crypto_sign_keypair: crypto_sign_keypair, - crypto_sign_open: crypto_sign_open, + return this.#protocol + } - crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, - crypto_sign_BYTES: crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, - crypto_hash_BYTES: crypto_hash_BYTES -}; + get onopen () { + webidl.brandCheck(this, WebSocket) -/* High-level API */ + return this.#events.open + } -function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); -} + set onopen (fn) { + webidl.brandCheck(this, WebSocket) -function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); -} + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } -function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') - throw new TypeError('unexpected type ' + t + ', use Uint8Array'); + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } } -} -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} + get onerror () { + webidl.brandCheck(this, WebSocket) -// TODO: Completely remove this in v0.15. -if (!nacl.util) { - nacl.util = {}; - nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { - throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); - }; -} + return this.#events.error + } -nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; -}; + set onerror (fn) { + webidl.brandCheck(this, WebSocket) -nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); -}; + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } -nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); -}; + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } -nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; -nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; -nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + get onclose () { + webidl.brandCheck(this, WebSocket) -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; + return this.#events.close + } -nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; -}; + set onclose (fn) { + webidl.brandCheck(this, WebSocket) -nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; -nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); -}; + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } -nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; -}; + get onmessage () { + webidl.brandCheck(this, WebSocket) -nacl.box.after = nacl.secretbox; + return this.#events.message + } -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); -}; + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) -nacl.box.open.after = nacl.secretbox.open; + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; + get binaryType () { + webidl.brandCheck(this, WebSocket) -nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; -nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; -nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; -nacl.box.nonceLength = crypto_box_NONCEBYTES; -nacl.box.overheadLength = nacl.secretbox.overheadLength; + return this[kBinaryType] + } -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; + set binaryType (type) { + webidl.brandCheck(this, WebSocket) -nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; -}; + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob' + } else { + this[kBinaryType] = type + } + } -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; + const parser = new ByteParser(this) + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume() + }) -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; + response.socket.ws = this + this[kByteParser] = parser + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + } +} + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; +webidl.converters['DOMString or sequence'] = function (V) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; -}; + return webidl.converters.DOMString(V) +} -nacl.hash.hashLength = crypto_hash_BYTES; +// This implements the propsal made in https://github.com/whatwg/websockets/issues/42 +webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + get defaultValue () { + return [] + } + }, + { + key: 'dispatcher', + converter: (V) => V, + get defaultValue () { + return getGlobalDispatcher() + } + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } +]) -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return (vn(x, 0, y, 0, x.length) === 0) ? true : false; -}; +webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } -nacl.setPRNG = function(fn) { - randombytes = fn; -}; + return { protocols: webidl.converters['DOMString or sequence'](V) } +} -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (true) { - // Node.js. - crypto = __nccwpck_require__(6113); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { + return webidl.converters.BufferSource(V) } } -})(); -})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket +} /***/ }), @@ -37668,8 +63074,11 @@ const docker_tags_1 = __nccwpck_require__(4665); // which may have crashed before deleting their own containers or networks // // cutoff - a Go duration string to pass to the Docker API's 'until' argument, default '24h' -function run(cutoff = '24h') { - return __awaiter(this, void 0, void 0, function* () { +function run() { + return __awaiter(this, arguments, void 0, function* (cutoff = '24h') { + if (process.env.DEPENDABOT_DISABLE_CLEANUP === '1') { + return; + } try { const docker = new dockerode_1.default(); const untilFilter = { until: [cutoff] }; @@ -37677,7 +63086,9 @@ function run(cutoff = '24h') { yield docker.pruneNetworks({ filters: untilFilter }); core.info(`Pruning containers older than ${cutoff}`); yield docker.pruneContainers({ filters: untilFilter }); - yield cleanupOldImageVersions(docker, docker_tags_1.UPDATER_IMAGE_NAME); + yield Promise.all((0, docker_tags_1.updaterImages)().map((image) => __awaiter(this, void 0, void 0, function* () { + return cleanupOldImageVersions(docker, image); + }))); yield cleanupOldImageVersions(docker, docker_tags_1.PROXY_IMAGE_NAME); } catch (error) { @@ -37692,27 +63103,23 @@ function cleanupOldImageVersions(docker, imageName) { return __awaiter(this, void 0, void 0, function* () { const repo = (0, docker_tags_1.repositoryName)(imageName); const options = { - filters: { - reference: [repo] - } + filters: `{"reference":["${repo}"]}` }; core.info(`Cleaning up images for ${repo}`); docker.listImages(options, function (err, imageInfoList) { - var _a, _b; return __awaiter(this, void 0, void 0, function* () { if (imageInfoList && imageInfoList.length > 0) { for (const imageInfo of imageInfoList) { - // The given imageName is expected to be a digest, however to avoid any surprises in future - // we fail over to check for a match on tags as well. + // The given imageName is expected to be a tag + digest, however to avoid any surprises in future + // we fail over to check for a match on just tags as well. // // This means we won't remove any image which matches an imageName of either of these notations: - // - dependabot/image@sha256:$REF (current implementation) + // - dependabot/image:$TAG@sha256:$REF (current implementation) // - dependabot/image:v1 // // Without checking imageInfo.RepoTags for a match, we would actually remove the latter even if // this was the active version. - if (((_a = imageInfo.RepoDigests) === null || _a === void 0 ? void 0 : _a.includes(imageName)) || - ((_b = imageInfo.RepoTags) === null || _b === void 0 ? void 0 : _b.includes(imageName))) { + if (imageMatches(imageInfo, imageName)) { core.info(`Skipping current image ${imageInfo.Id}`); continue; } @@ -37732,6 +63139,14 @@ function cleanupOldImageVersions(docker, imageName) { }); } exports.cleanupOldImageVersions = cleanupOldImageVersions; +function imageMatches(imageInfo, imageName) { + if ((0, docker_tags_1.hasDigest)(imageName)) { + return imageInfo.RepoDigests + ? imageInfo.RepoDigests.includes((0, docker_tags_1.digestName)(imageName)) + : false; + } + return imageInfo.RepoTags ? imageInfo.RepoTags.includes(imageName) : false; +} run(); @@ -37746,11 +63161,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.repositoryName = exports.PROXY_IMAGE_NAME = exports.UPDATER_IMAGE_NAME = void 0; +exports.digestName = exports.hasDigest = exports.repositoryName = exports.updaterImages = exports.updaterImageName = exports.PROXY_IMAGE_NAME = void 0; +// eslint-disable-next-line import/extensions const containers_json_1 = __importDefault(__nccwpck_require__(8708)); -exports.UPDATER_IMAGE_NAME = containers_json_1.default.updater; exports.PROXY_IMAGE_NAME = containers_json_1.default.proxy; -const imageNamePattern = '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))((:[a-zA-Z0-9._/-]+)|(@sha256:[a-zA-Z0-9]{64}))?$'; +function updaterImageName(packageManager) { + return containers_json_1.default[packageManager]; +} +exports.updaterImageName = updaterImageName; +const updaterRegex = /ghcr.io\/dependabot\/dependabot-updater-([\w+])/; +function updaterImages() { + return Object.values(containers_json_1.default).filter(image => image.match(updaterRegex)); +} +exports.updaterImages = updaterImages; +const imageNamePattern = '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))(:[a-zA-Z0-9._/-]+)?(?@sha256:[a-zA-Z0-9]{64})?$'; function repositoryName(imageName) { const match = imageName.match(imageNamePattern); if (match === null || match === void 0 ? void 0 : match.groups) { @@ -37761,6 +63185,29 @@ function repositoryName(imageName) { } } exports.repositoryName = repositoryName; +function hasDigest(imageName) { + const match = imageName.match(imageNamePattern); + if (match === null || match === void 0 ? void 0 : match.groups) { + if (match === null || match === void 0 ? void 0 : match.groups['digest']) { + return true; + } + return false; + } + else { + throw Error('invalid image name'); + } +} +exports.hasDigest = hasDigest; +function digestName(imageName) { + const match = imageName.match(imageNamePattern); + if (match === null || match === void 0 ? void 0 : match.groups) { + return match.groups['repository'] + match.groups['digest']; + } + else { + throw Error('invalid image name'); + } +} +exports.digestName = digestName; /***/ }), @@ -37787,6 +63234,14 @@ module.exports = require("assert"); /***/ }), +/***/ 852: +/***/ ((module) => { + +"use strict"; +module.exports = require("async_hooks"); + +/***/ }), + /***/ 4300: /***/ ((module) => { @@ -37803,6 +63258,14 @@ module.exports = require("child_process"); /***/ }), +/***/ 6206: +/***/ ((module) => { + +"use strict"; +module.exports = require("console"); + +/***/ }), + /***/ 2057: /***/ ((module) => { @@ -37819,6 +63282,14 @@ module.exports = require("crypto"); /***/ }), +/***/ 7643: +/***/ ((module) => { + +"use strict"; +module.exports = require("diagnostics_channel"); + +/***/ }), + /***/ 9523: /***/ ((module) => { @@ -37851,6 +63322,14 @@ module.exports = require("http"); /***/ }), +/***/ 5158: +/***/ ((module) => { + +"use strict"; +module.exports = require("http2"); + +/***/ }), + /***/ 5687: /***/ ((module) => { @@ -37867,6 +63346,30 @@ module.exports = require("net"); /***/ }), +/***/ 5673: +/***/ ((module) => { + +"use strict"; +module.exports = require("node:events"); + +/***/ }), + +/***/ 4492: +/***/ ((module) => { + +"use strict"; +module.exports = require("node:stream"); + +/***/ }), + +/***/ 7261: +/***/ ((module) => { + +"use strict"; +module.exports = require("node:util"); + +/***/ }), + /***/ 2037: /***/ ((module) => { @@ -37883,6 +63386,14 @@ module.exports = require("path"); /***/ }), +/***/ 4074: +/***/ ((module) => { + +"use strict"; +module.exports = require("perf_hooks"); + +/***/ }), + /***/ 3477: /***/ ((module) => { @@ -37899,6 +63410,14 @@ module.exports = require("stream"); /***/ }), +/***/ 5356: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream/web"); + +/***/ }), + /***/ 1576: /***/ ((module) => { @@ -37939,6 +63458,22 @@ module.exports = require("util"); /***/ }), +/***/ 9830: +/***/ ((module) => { + +"use strict"; +module.exports = require("util/types"); + +/***/ }), + +/***/ 1267: +/***/ ((module) => { + +"use strict"; +module.exports = require("worker_threads"); + +/***/ }), + /***/ 9796: /***/ ((module) => { @@ -37951,7 +63486,7 @@ module.exports = require("zlib"); /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"proxy":"ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy@sha256:4714e9c495d7af0a83347517703cf524e2793f58625e4285e323d5d890a7cfa4","updater":"ghcr.io/dependabot/dependabot-updater@sha256:85108a36530c8ee66027eb798b62aabe0b31d2972a902375ff9baf862777cb38"}'); +module.exports = JSON.parse('{"proxy":"ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy:v2.0.20241004183849@sha256:5e895b5edfaba72e99d0a19b43f386b18b65fc08a2d43af5aedd6360cda56842","bundler":"ghcr.io/dependabot/dependabot-updater-bundler:v2.0.20241107222650@sha256:3cf4cafa6016c78e372fb29cac35472ed261c57b084b326747429afee2199c1b","cargo":"ghcr.io/dependabot/dependabot-updater-cargo:v2.0.20241107222650@sha256:91f64f9e49c36fc5b683756997060565dff67c5e30a1d5588ade386d2a79c8ec","composer":"ghcr.io/dependabot/dependabot-updater-composer:v2.0.20241107222650@sha256:0fbb307c6e249c08498527b9c3ceb23b761dd9d55bcca2f74cd0ca81a8914740","pub":"ghcr.io/dependabot/dependabot-updater-pub:v2.0.20241107222650@sha256:ce2b994ba59765b847251036a7a66f7d32e6a7076ae455f80bb6bf8cad2f16fc","docker":"ghcr.io/dependabot/dependabot-updater-docker:v2.0.20241107222650@sha256:3d44776d7a87cc5fc4c9d61678b03d6efc388901702697e514ed70823b440aba","elm":"ghcr.io/dependabot/dependabot-updater-elm:v2.0.20241107222650@sha256:16e94bdb0144ef7398b66d81388d7eb437dd8f5b514171d13cb858cc171efa05","github_actions":"ghcr.io/dependabot/dependabot-updater-github-actions:v2.0.20241107222650@sha256:c58910178f005aecfbdc41e0610f76ded7a4c5dc333521a33b3d6985c2eb9dc0","submodules":"ghcr.io/dependabot/dependabot-updater-gitsubmodule:v2.0.20241107222650@sha256:2a6bc87850734c8e3116c7020d6681b49151e201c43a0b590288e812a0336023","go_modules":"ghcr.io/dependabot/dependabot-updater-gomod:v2.0.20241107222650@sha256:77980075afb1a74eae6f63764f1cb26fcd6e146c90ac91a9ed77db25da55a008","gradle":"ghcr.io/dependabot/dependabot-updater-gradle:v2.0.20241107222650@sha256:8108e23b0d3a76dacea69f3756c89a3d6d35bcca3c2f975a61c1bfde815d7ee9","maven":"ghcr.io/dependabot/dependabot-updater-maven:v2.0.20241107222650@sha256:eadf9c29977e411420ca3fa9bb89e79f0a49872a87c3cd718721714782144a0b","hex":"ghcr.io/dependabot/dependabot-updater-mix:v2.0.20241107222650@sha256:0460f703a613ff38dd2ad61ef7d079070f37cbbb14f57e764c9427a4ee46b831","nuget":"ghcr.io/dependabot/dependabot-updater-nuget:v2.0.20241107222650@sha256:d2f293e19cd21467c73d0d967febb865184f5059c8b40fa9d73cd05810267b10","npm_and_yarn":"ghcr.io/dependabot/dependabot-updater-npm:v2.0.20241107222650@sha256:f187a18dbf871c71124d59c970e551d76196384e8d266da70a9c8c6417cb88fc","pip":"ghcr.io/dependabot/dependabot-updater-pip:v2.0.20241107222650@sha256:3dc06304cabaa7839388fb7c87b2cfa7d3cddf6c648e810415b025f3498b084c","swift":"ghcr.io/dependabot/dependabot-updater-swift:v2.0.20241107141918@sha256:4935ce7bd14b783e4838a38e59c6e2eae25e0ca7b0a11cd779d04a064ba8b654","terraform":"ghcr.io/dependabot/dependabot-updater-terraform:v2.0.20241107222650@sha256:d28f3845ae8cf4cbf1ae0f8ea0622da31cd1035a0eda18a3229e125fba0d224c","devcontainers":"ghcr.io/dependabot/dependabot-updater-devcontainers:v2.0.20241107222650@sha256:5273198c7c9d2490c6c1147b0e79a7d5351a8fa6f4ad37fdfffe434b7b569c32"}'); /***/ }), @@ -37959,7 +63494,7 @@ module.exports = JSON.parse('{"proxy":"ghcr.io/github/dependabot-update-job-prox /***/ ((module) => { "use strict"; -module.exports = {"i8":"1.6.0"}; +module.exports = {"i8":"1.15.0"}; /***/ }) diff --git a/dist/cleanup/index.js.map b/dist/cleanup/index.js.map index 3680a1147..770ad8d36 100644 --- a/dist/cleanup/index.js.map +++ b/dist/cleanup/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5lBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC5DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3iBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3YA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtKA;AACA;AACA;;;;;;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1dA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5jCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzyDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7FA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnmCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1BA;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtSA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC79DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5hEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChsHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjkDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7rCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtyDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC18CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACt1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtSA;AACA;;;;;;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9PA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACn1EA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnBA;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC7BA;AACA;;;;AEDA;AACA;AACA;AACA","sources":["../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/command.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/core.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/file-command.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/oidc-utils.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/path-utils.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/summary.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/errors.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/index.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/reader.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/types.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/writer.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/index.js","../webpack://dependabot-updater-action/./node_modules/bcrypt-pbkdf/index.js","../webpack://dependabot-updater-action/./node_modules/bl/BufferList.js","../webpack://dependabot-updater-action/./node_modules/bl/bl.js","../webpack://dependabot-updater-action/./node_modules/chownr/chownr.js","../webpack://dependabot-updater-action/./node_modules/cpu-features/lib/index.js","../webpack://dependabot-updater-action/./node_modules/debug/src/browser.js","../webpack://dependabot-updater-action/./node_modules/debug/src/common.js","../webpack://dependabot-updater-action/./node_modules/debug/src/index.js","../webpack://dependabot-updater-action/./node_modules/debug/src/node.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/http.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/http_duplex.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/modem.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/ssh.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/config.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/container.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/docker.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/exec.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/image.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/network.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/node.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/plugin.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/secret.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/service.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/task.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/util.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/volume.js","../webpack://dependabot-updater-action/./node_modules/end-of-stream/index.js","../webpack://dependabot-updater-action/./node_modules/fs-constants/index.js","../webpack://dependabot-updater-action/./node_modules/has-flag/index.js","../webpack://dependabot-updater-action/./node_modules/inherits/inherits.js","../webpack://dependabot-updater-action/./node_modules/inherits/inherits_browser.js","../webpack://dependabot-updater-action/./node_modules/mkdirp-classic/index.js","../webpack://dependabot-updater-action/./node_modules/ms/index.js","../webpack://dependabot-updater-action/./node_modules/once/once.js","../webpack://dependabot-updater-action/./node_modules/pump/index.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/errors.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_duplex.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_passthrough.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_readable.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_transform.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_writable.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/async_iterator.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/buffer_list.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/destroy.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/from.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/pipeline.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/state.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/stream.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/readable.js","../webpack://dependabot-updater-action/./node_modules/safer-buffer/safer.js","../webpack://dependabot-updater-action/./node_modules/split-ca/index.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/Channel.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/agent.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/client.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/http-agents.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/index.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/Protocol.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/SFTP.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/constants.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/crypto.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/crypto/poly1305.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/handlers.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/handlers.misc.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/kex.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/keyParser.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/node-fs-compat.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/utils.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/zlib.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/server.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/string_decoder/lib/string_decoder.js","../webpack://dependabot-updater-action/./node_modules/string_decoder/node_modules/safe-buffer/index.js","../webpack://dependabot-updater-action/./node_modules/supports-color/index.js","../webpack://dependabot-updater-action/./node_modules/tar-fs/index.js","../webpack://dependabot-updater-action/./node_modules/tar-stream/extract.js","../webpack://dependabot-updater-action/./node_modules/tar-stream/headers.js","../webpack://dependabot-updater-action/./node_modules/tar-stream/index.js","../webpack://dependabot-updater-action/./node_modules/tar-stream/pack.js","../webpack://dependabot-updater-action/./node_modules/tunnel/index.js","../webpack://dependabot-updater-action/./node_modules/tunnel/lib/tunnel.js","../webpack://dependabot-updater-action/./node_modules/tweetnacl/nacl-fast.js","../webpack://dependabot-updater-action/./node_modules/util-deprecate/node.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/index.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/md5.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/nil.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/parse.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/regex.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/rng.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/sha1.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/stringify.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v1.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v3.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v35.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v4.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v5.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/validate.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/version.js","../webpack://dependabot-updater-action/./node_modules/wrappy/wrappy.js","../webpack://dependabot-updater-action/./src/cleanup.ts","../webpack://dependabot-updater-action/./src/docker-tags.ts","../webpack://dependabot-updater-action/./node_modules/cpu-features/build/Release/cpufeatures.node","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node","../webpack://dependabot-updater-action/external node-commonjs \"assert\"","../webpack://dependabot-updater-action/external node-commonjs \"buffer\"","../webpack://dependabot-updater-action/external node-commonjs \"child_process\"","../webpack://dependabot-updater-action/external node-commonjs \"constants\"","../webpack://dependabot-updater-action/external node-commonjs \"crypto\"","../webpack://dependabot-updater-action/external node-commonjs \"dns\"","../webpack://dependabot-updater-action/external node-commonjs \"events\"","../webpack://dependabot-updater-action/external node-commonjs \"fs\"","../webpack://dependabot-updater-action/external node-commonjs \"http\"","../webpack://dependabot-updater-action/external node-commonjs \"https\"","../webpack://dependabot-updater-action/external node-commonjs \"net\"","../webpack://dependabot-updater-action/external node-commonjs \"os\"","../webpack://dependabot-updater-action/external node-commonjs \"path\"","../webpack://dependabot-updater-action/external node-commonjs \"querystring\"","../webpack://dependabot-updater-action/external node-commonjs \"stream\"","../webpack://dependabot-updater-action/external node-commonjs \"string_decoder\"","../webpack://dependabot-updater-action/external node-commonjs \"tls\"","../webpack://dependabot-updater-action/external node-commonjs \"tty\"","../webpack://dependabot-updater-action/external node-commonjs \"url\"","../webpack://dependabot-updater-action/external node-commonjs \"util\"","../webpack://dependabot-updater-action/external node-commonjs \"zlib\"","../webpack://dependabot-updater-action/webpack/bootstrap","../webpack://dependabot-updater-action/webpack/runtime/compat","../webpack://dependabot-updater-action/webpack/before-startup","../webpack://dependabot-updater-action/webpack/startup","../webpack://dependabot-updater-action/webpack/after-startup"],"sourcesContent":["\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issue = exports.issueCommand = void 0;\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\n/**\n * Commands\n *\n * Command Format:\n * ::name key=value,key=value::message\n *\n * Examples:\n * ::warning::This is the message\n * ::set-env name=MY_VAR::some value\n */\nfunction issueCommand(command, properties, message) {\n const cmd = new Command(command, properties, message);\n process.stdout.write(cmd.toString() + os.EOL);\n}\nexports.issueCommand = issueCommand;\nfunction issue(name, message = '') {\n issueCommand(name, {}, message);\n}\nexports.issue = issue;\nconst CMD_STRING = '::';\nclass Command {\n constructor(command, properties, message) {\n if (!command) {\n command = 'missing.command';\n }\n this.command = command;\n this.properties = properties;\n this.message = message;\n }\n toString() {\n let cmdStr = CMD_STRING + this.command;\n if (this.properties && Object.keys(this.properties).length > 0) {\n cmdStr += ' ';\n let first = true;\n for (const key in this.properties) {\n if (this.properties.hasOwnProperty(key)) {\n const val = this.properties[key];\n if (val) {\n if (first) {\n first = false;\n }\n else {\n cmdStr += ',';\n }\n cmdStr += `${key}=${escapeProperty(val)}`;\n }\n }\n }\n }\n cmdStr += `${CMD_STRING}${escapeData(this.message)}`;\n return cmdStr;\n }\n}\nfunction escapeData(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A');\n}\nfunction escapeProperty(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n}\n//# sourceMappingURL=command.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;\nconst command_1 = require(\"./command\");\nconst file_command_1 = require(\"./file-command\");\nconst utils_1 = require(\"./utils\");\nconst os = __importStar(require(\"os\"));\nconst path = __importStar(require(\"path\"));\nconst uuid_1 = require(\"uuid\");\nconst oidc_utils_1 = require(\"./oidc-utils\");\n/**\n * The code to exit an action\n */\nvar ExitCode;\n(function (ExitCode) {\n /**\n * A code indicating that the action was successful\n */\n ExitCode[ExitCode[\"Success\"] = 0] = \"Success\";\n /**\n * A code indicating that the action was a failure\n */\n ExitCode[ExitCode[\"Failure\"] = 1] = \"Failure\";\n})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));\n//-----------------------------------------------------------------------\n// Variables\n//-----------------------------------------------------------------------\n/**\n * Sets env variable for this action and future actions in the job\n * @param name the name of the variable to set\n * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction exportVariable(name, val) {\n const convertedVal = utils_1.toCommandValue(val);\n process.env[name] = convertedVal;\n const filePath = process.env['GITHUB_ENV'] || '';\n if (filePath) {\n const delimiter = `ghadelimiter_${uuid_1.v4()}`;\n // These should realistically never happen, but just in case someone finds a way to exploit uuid generation let's not allow keys or values that contain the delimiter.\n if (name.includes(delimiter)) {\n throw new Error(`Unexpected input: name should not contain the delimiter \"${delimiter}\"`);\n }\n if (convertedVal.includes(delimiter)) {\n throw new Error(`Unexpected input: value should not contain the delimiter \"${delimiter}\"`);\n }\n const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;\n file_command_1.issueCommand('ENV', commandValue);\n }\n else {\n command_1.issueCommand('set-env', { name }, convertedVal);\n }\n}\nexports.exportVariable = exportVariable;\n/**\n * Registers a secret which will get masked from logs\n * @param secret value of the secret\n */\nfunction setSecret(secret) {\n command_1.issueCommand('add-mask', {}, secret);\n}\nexports.setSecret = setSecret;\n/**\n * Prepends inputPath to the PATH (for this action and future actions)\n * @param inputPath\n */\nfunction addPath(inputPath) {\n const filePath = process.env['GITHUB_PATH'] || '';\n if (filePath) {\n file_command_1.issueCommand('PATH', inputPath);\n }\n else {\n command_1.issueCommand('add-path', {}, inputPath);\n }\n process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;\n}\nexports.addPath = addPath;\n/**\n * Gets the value of an input.\n * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.\n * Returns an empty string if the value is not defined.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string\n */\nfunction getInput(name, options) {\n const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';\n if (options && options.required && !val) {\n throw new Error(`Input required and not supplied: ${name}`);\n }\n if (options && options.trimWhitespace === false) {\n return val;\n }\n return val.trim();\n}\nexports.getInput = getInput;\n/**\n * Gets the values of an multiline input. Each value is also trimmed.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string[]\n *\n */\nfunction getMultilineInput(name, options) {\n const inputs = getInput(name, options)\n .split('\\n')\n .filter(x => x !== '');\n return inputs;\n}\nexports.getMultilineInput = getMultilineInput;\n/**\n * Gets the input value of the boolean type in the YAML 1.2 \"core schema\" specification.\n * Support boolean input list: `true | True | TRUE | false | False | FALSE` .\n * The return value is also in boolean type.\n * ref: https://yaml.org/spec/1.2/spec.html#id2804923\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns boolean\n */\nfunction getBooleanInput(name, options) {\n const trueValue = ['true', 'True', 'TRUE'];\n const falseValue = ['false', 'False', 'FALSE'];\n const val = getInput(name, options);\n if (trueValue.includes(val))\n return true;\n if (falseValue.includes(val))\n return false;\n throw new TypeError(`Input does not meet YAML 1.2 \"Core Schema\" specification: ${name}\\n` +\n `Support boolean input list: \\`true | True | TRUE | false | False | FALSE\\``);\n}\nexports.getBooleanInput = getBooleanInput;\n/**\n * Sets the value of an output.\n *\n * @param name name of the output to set\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setOutput(name, value) {\n process.stdout.write(os.EOL);\n command_1.issueCommand('set-output', { name }, value);\n}\nexports.setOutput = setOutput;\n/**\n * Enables or disables the echoing of commands into stdout for the rest of the step.\n * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.\n *\n */\nfunction setCommandEcho(enabled) {\n command_1.issue('echo', enabled ? 'on' : 'off');\n}\nexports.setCommandEcho = setCommandEcho;\n//-----------------------------------------------------------------------\n// Results\n//-----------------------------------------------------------------------\n/**\n * Sets the action status to failed.\n * When the action exits it will be with an exit code of 1\n * @param message add error issue message\n */\nfunction setFailed(message) {\n process.exitCode = ExitCode.Failure;\n error(message);\n}\nexports.setFailed = setFailed;\n//-----------------------------------------------------------------------\n// Logging Commands\n//-----------------------------------------------------------------------\n/**\n * Gets whether Actions Step Debug is on or not\n */\nfunction isDebug() {\n return process.env['RUNNER_DEBUG'] === '1';\n}\nexports.isDebug = isDebug;\n/**\n * Writes debug message to user log\n * @param message debug message\n */\nfunction debug(message) {\n command_1.issueCommand('debug', {}, message);\n}\nexports.debug = debug;\n/**\n * Adds an error issue\n * @param message error issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction error(message, properties = {}) {\n command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.error = error;\n/**\n * Adds a warning issue\n * @param message warning issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction warning(message, properties = {}) {\n command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.warning = warning;\n/**\n * Adds a notice issue\n * @param message notice issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction notice(message, properties = {}) {\n command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.notice = notice;\n/**\n * Writes info to log with console.log.\n * @param message info message\n */\nfunction info(message) {\n process.stdout.write(message + os.EOL);\n}\nexports.info = info;\n/**\n * Begin an output group.\n *\n * Output until the next `groupEnd` will be foldable in this group\n *\n * @param name The name of the output group\n */\nfunction startGroup(name) {\n command_1.issue('group', name);\n}\nexports.startGroup = startGroup;\n/**\n * End an output group.\n */\nfunction endGroup() {\n command_1.issue('endgroup');\n}\nexports.endGroup = endGroup;\n/**\n * Wrap an asynchronous function call in a group.\n *\n * Returns the same type as the function itself.\n *\n * @param name The name of the group\n * @param fn The function to wrap in the group\n */\nfunction group(name, fn) {\n return __awaiter(this, void 0, void 0, function* () {\n startGroup(name);\n let result;\n try {\n result = yield fn();\n }\n finally {\n endGroup();\n }\n return result;\n });\n}\nexports.group = group;\n//-----------------------------------------------------------------------\n// Wrapper action state\n//-----------------------------------------------------------------------\n/**\n * Saves state for current action, the state can only be retrieved by this action's post job execution.\n *\n * @param name name of the state to store\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction saveState(name, value) {\n command_1.issueCommand('save-state', { name }, value);\n}\nexports.saveState = saveState;\n/**\n * Gets the value of an state set by this action's main execution.\n *\n * @param name name of the state to get\n * @returns string\n */\nfunction getState(name) {\n return process.env[`STATE_${name}`] || '';\n}\nexports.getState = getState;\nfunction getIDToken(aud) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield oidc_utils_1.OidcClient.getIDToken(aud);\n });\n}\nexports.getIDToken = getIDToken;\n/**\n * Summary exports\n */\nvar summary_1 = require(\"./summary\");\nObject.defineProperty(exports, \"summary\", { enumerable: true, get: function () { return summary_1.summary; } });\n/**\n * @deprecated use core.summary\n */\nvar summary_2 = require(\"./summary\");\nObject.defineProperty(exports, \"markdownSummary\", { enumerable: true, get: function () { return summary_2.markdownSummary; } });\n/**\n * Path exports\n */\nvar path_utils_1 = require(\"./path-utils\");\nObject.defineProperty(exports, \"toPosixPath\", { enumerable: true, get: function () { return path_utils_1.toPosixPath; } });\nObject.defineProperty(exports, \"toWin32Path\", { enumerable: true, get: function () { return path_utils_1.toWin32Path; } });\nObject.defineProperty(exports, \"toPlatformPath\", { enumerable: true, get: function () { return path_utils_1.toPlatformPath; } });\n//# sourceMappingURL=core.js.map","\"use strict\";\n// For internal use, subject to change.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issueCommand = void 0;\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst fs = __importStar(require(\"fs\"));\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\nfunction issueCommand(command, message) {\n const filePath = process.env[`GITHUB_${command}`];\n if (!filePath) {\n throw new Error(`Unable to find environment variable for file command ${command}`);\n }\n if (!fs.existsSync(filePath)) {\n throw new Error(`Missing file at path: ${filePath}`);\n }\n fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {\n encoding: 'utf8'\n });\n}\nexports.issueCommand = issueCommand;\n//# sourceMappingURL=file-command.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OidcClient = void 0;\nconst http_client_1 = require(\"@actions/http-client\");\nconst auth_1 = require(\"@actions/http-client/lib/auth\");\nconst core_1 = require(\"./core\");\nclass OidcClient {\n static createHttpClient(allowRetry = true, maxRetry = 10) {\n const requestOptions = {\n allowRetries: allowRetry,\n maxRetries: maxRetry\n };\n return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);\n }\n static getRequestToken() {\n const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];\n if (!token) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');\n }\n return token;\n }\n static getIDTokenUrl() {\n const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];\n if (!runtimeUrl) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');\n }\n return runtimeUrl;\n }\n static getCall(id_token_url) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const httpclient = OidcClient.createHttpClient();\n const res = yield httpclient\n .getJson(id_token_url)\n .catch(error => {\n throw new Error(`Failed to get ID Token. \\n \n Error Code : ${error.statusCode}\\n \n Error Message: ${error.result.message}`);\n });\n const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;\n if (!id_token) {\n throw new Error('Response json body do not have ID Token field');\n }\n return id_token;\n });\n }\n static getIDToken(audience) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // New ID Token is requested from action service\n let id_token_url = OidcClient.getIDTokenUrl();\n if (audience) {\n const encodedAudience = encodeURIComponent(audience);\n id_token_url = `${id_token_url}&audience=${encodedAudience}`;\n }\n core_1.debug(`ID token url is ${id_token_url}`);\n const id_token = yield OidcClient.getCall(id_token_url);\n core_1.setSecret(id_token);\n return id_token;\n }\n catch (error) {\n throw new Error(`Error message: ${error.message}`);\n }\n });\n }\n}\nexports.OidcClient = OidcClient;\n//# sourceMappingURL=oidc-utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;\nconst path = __importStar(require(\"path\"));\n/**\n * toPosixPath converts the given path to the posix form. On Windows, \\\\ will be\n * replaced with /.\n *\n * @param pth. Path to transform.\n * @return string Posix path.\n */\nfunction toPosixPath(pth) {\n return pth.replace(/[\\\\]/g, '/');\n}\nexports.toPosixPath = toPosixPath;\n/**\n * toWin32Path converts the given path to the win32 form. On Linux, / will be\n * replaced with \\\\.\n *\n * @param pth. Path to transform.\n * @return string Win32 path.\n */\nfunction toWin32Path(pth) {\n return pth.replace(/[/]/g, '\\\\');\n}\nexports.toWin32Path = toWin32Path;\n/**\n * toPlatformPath converts the given path to a platform-specific path. It does\n * this by replacing instances of / and \\ with the platform-specific path\n * separator.\n *\n * @param pth The path to platformize.\n * @return string The platform-specific path.\n */\nfunction toPlatformPath(pth) {\n return pth.replace(/[/\\\\]/g, path.sep);\n}\nexports.toPlatformPath = toPlatformPath;\n//# sourceMappingURL=path-utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;\nconst os_1 = require(\"os\");\nconst fs_1 = require(\"fs\");\nconst { access, appendFile, writeFile } = fs_1.promises;\nexports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';\nexports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';\nclass Summary {\n constructor() {\n this._buffer = '';\n }\n /**\n * Finds the summary file path from the environment, rejects if env var is not found or file does not exist\n * Also checks r/w permissions.\n *\n * @returns step summary file path\n */\n filePath() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._filePath) {\n return this._filePath;\n }\n const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];\n if (!pathFromEnv) {\n throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);\n }\n try {\n yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);\n }\n catch (_a) {\n throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);\n }\n this._filePath = pathFromEnv;\n return this._filePath;\n });\n }\n /**\n * Wraps content in an HTML tag, adding any HTML attributes\n *\n * @param {string} tag HTML tag to wrap\n * @param {string | null} content content within the tag\n * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add\n *\n * @returns {string} content wrapped in HTML element\n */\n wrap(tag, content, attrs = {}) {\n const htmlAttrs = Object.entries(attrs)\n .map(([key, value]) => ` ${key}=\"${value}\"`)\n .join('');\n if (!content) {\n return `<${tag}${htmlAttrs}>`;\n }\n return `<${tag}${htmlAttrs}>${content}`;\n }\n /**\n * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.\n *\n * @param {SummaryWriteOptions} [options] (optional) options for write operation\n *\n * @returns {Promise} summary instance\n */\n write(options) {\n return __awaiter(this, void 0, void 0, function* () {\n const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);\n const filePath = yield this.filePath();\n const writeFunc = overwrite ? writeFile : appendFile;\n yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });\n return this.emptyBuffer();\n });\n }\n /**\n * Clears the summary buffer and wipes the summary file\n *\n * @returns {Summary} summary instance\n */\n clear() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.emptyBuffer().write({ overwrite: true });\n });\n }\n /**\n * Returns the current summary buffer as a string\n *\n * @returns {string} string of summary buffer\n */\n stringify() {\n return this._buffer;\n }\n /**\n * If the summary buffer is empty\n *\n * @returns {boolen} true if the buffer is empty\n */\n isEmptyBuffer() {\n return this._buffer.length === 0;\n }\n /**\n * Resets the summary buffer without writing to summary file\n *\n * @returns {Summary} summary instance\n */\n emptyBuffer() {\n this._buffer = '';\n return this;\n }\n /**\n * Adds raw text to the summary buffer\n *\n * @param {string} text content to add\n * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)\n *\n * @returns {Summary} summary instance\n */\n addRaw(text, addEOL = false) {\n this._buffer += text;\n return addEOL ? this.addEOL() : this;\n }\n /**\n * Adds the operating system-specific end-of-line marker to the buffer\n *\n * @returns {Summary} summary instance\n */\n addEOL() {\n return this.addRaw(os_1.EOL);\n }\n /**\n * Adds an HTML codeblock to the summary buffer\n *\n * @param {string} code content to render within fenced code block\n * @param {string} lang (optional) language to syntax highlight code\n *\n * @returns {Summary} summary instance\n */\n addCodeBlock(code, lang) {\n const attrs = Object.assign({}, (lang && { lang }));\n const element = this.wrap('pre', this.wrap('code', code), attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML list to the summary buffer\n *\n * @param {string[]} items list of items to render\n * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)\n *\n * @returns {Summary} summary instance\n */\n addList(items, ordered = false) {\n const tag = ordered ? 'ol' : 'ul';\n const listItems = items.map(item => this.wrap('li', item)).join('');\n const element = this.wrap(tag, listItems);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML table to the summary buffer\n *\n * @param {SummaryTableCell[]} rows table rows\n *\n * @returns {Summary} summary instance\n */\n addTable(rows) {\n const tableBody = rows\n .map(row => {\n const cells = row\n .map(cell => {\n if (typeof cell === 'string') {\n return this.wrap('td', cell);\n }\n const { header, data, colspan, rowspan } = cell;\n const tag = header ? 'th' : 'td';\n const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));\n return this.wrap(tag, data, attrs);\n })\n .join('');\n return this.wrap('tr', cells);\n })\n .join('');\n const element = this.wrap('table', tableBody);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds a collapsable HTML details element to the summary buffer\n *\n * @param {string} label text for the closed state\n * @param {string} content collapsable content\n *\n * @returns {Summary} summary instance\n */\n addDetails(label, content) {\n const element = this.wrap('details', this.wrap('summary', label) + content);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML image tag to the summary buffer\n *\n * @param {string} src path to the image you to embed\n * @param {string} alt text description of the image\n * @param {SummaryImageOptions} options (optional) addition image attributes\n *\n * @returns {Summary} summary instance\n */\n addImage(src, alt, options) {\n const { width, height } = options || {};\n const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));\n const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML section heading element\n *\n * @param {string} text heading text\n * @param {number | string} [level=1] (optional) the heading level, default: 1\n *\n * @returns {Summary} summary instance\n */\n addHeading(text, level) {\n const tag = `h${level}`;\n const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)\n ? tag\n : 'h1';\n const element = this.wrap(allowedTag, text);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML thematic break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addSeparator() {\n const element = this.wrap('hr', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML line break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addBreak() {\n const element = this.wrap('br', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML blockquote to the summary buffer\n *\n * @param {string} text quote text\n * @param {string} cite (optional) citation url\n *\n * @returns {Summary} summary instance\n */\n addQuote(text, cite) {\n const attrs = Object.assign({}, (cite && { cite }));\n const element = this.wrap('blockquote', text, attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML anchor tag to the summary buffer\n *\n * @param {string} text link text/content\n * @param {string} href hyperlink\n *\n * @returns {Summary} summary instance\n */\n addLink(text, href) {\n const element = this.wrap('a', text, { href });\n return this.addRaw(element).addEOL();\n }\n}\nconst _summary = new Summary();\n/**\n * @deprecated use `core.summary`\n */\nexports.markdownSummary = _summary;\nexports.summary = _summary;\n//# sourceMappingURL=summary.js.map","\"use strict\";\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toCommandProperties = exports.toCommandValue = void 0;\n/**\n * Sanitizes an input into a string so it can be passed into issueCommand safely\n * @param input input to sanitize into a string\n */\nfunction toCommandValue(input) {\n if (input === null || input === undefined) {\n return '';\n }\n else if (typeof input === 'string' || input instanceof String) {\n return input;\n }\n return JSON.stringify(input);\n}\nexports.toCommandValue = toCommandValue;\n/**\n *\n * @param annotationProperties\n * @returns The command properties to send with the actual annotation command\n * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646\n */\nfunction toCommandProperties(annotationProperties) {\n if (!Object.keys(annotationProperties).length) {\n return {};\n }\n return {\n title: annotationProperties.title,\n file: annotationProperties.file,\n line: annotationProperties.startLine,\n endLine: annotationProperties.endLine,\n col: annotationProperties.startColumn,\n endColumn: annotationProperties.endColumn\n };\n}\nexports.toCommandProperties = toCommandProperties;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;\nclass BasicCredentialHandler {\n constructor(username, password) {\n this.username = username;\n this.password = password;\n }\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BasicCredentialHandler = BasicCredentialHandler;\nclass BearerCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Bearer ${this.token}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BearerCredentialHandler = BearerCredentialHandler;\nclass PersonalAccessTokenCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;\n//# sourceMappingURL=auth.js.map","\"use strict\";\n/* eslint-disable @typescript-eslint/no-explicit-any */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;\nconst http = __importStar(require(\"http\"));\nconst https = __importStar(require(\"https\"));\nconst pm = __importStar(require(\"./proxy\"));\nconst tunnel = __importStar(require(\"tunnel\"));\nvar HttpCodes;\n(function (HttpCodes) {\n HttpCodes[HttpCodes[\"OK\"] = 200] = \"OK\";\n HttpCodes[HttpCodes[\"MultipleChoices\"] = 300] = \"MultipleChoices\";\n HttpCodes[HttpCodes[\"MovedPermanently\"] = 301] = \"MovedPermanently\";\n HttpCodes[HttpCodes[\"ResourceMoved\"] = 302] = \"ResourceMoved\";\n HttpCodes[HttpCodes[\"SeeOther\"] = 303] = \"SeeOther\";\n HttpCodes[HttpCodes[\"NotModified\"] = 304] = \"NotModified\";\n HttpCodes[HttpCodes[\"UseProxy\"] = 305] = \"UseProxy\";\n HttpCodes[HttpCodes[\"SwitchProxy\"] = 306] = \"SwitchProxy\";\n HttpCodes[HttpCodes[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n HttpCodes[HttpCodes[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n HttpCodes[HttpCodes[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpCodes[HttpCodes[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpCodes[HttpCodes[\"PaymentRequired\"] = 402] = \"PaymentRequired\";\n HttpCodes[HttpCodes[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpCodes[HttpCodes[\"NotFound\"] = 404] = \"NotFound\";\n HttpCodes[HttpCodes[\"MethodNotAllowed\"] = 405] = \"MethodNotAllowed\";\n HttpCodes[HttpCodes[\"NotAcceptable\"] = 406] = \"NotAcceptable\";\n HttpCodes[HttpCodes[\"ProxyAuthenticationRequired\"] = 407] = \"ProxyAuthenticationRequired\";\n HttpCodes[HttpCodes[\"RequestTimeout\"] = 408] = \"RequestTimeout\";\n HttpCodes[HttpCodes[\"Conflict\"] = 409] = \"Conflict\";\n HttpCodes[HttpCodes[\"Gone\"] = 410] = \"Gone\";\n HttpCodes[HttpCodes[\"TooManyRequests\"] = 429] = \"TooManyRequests\";\n HttpCodes[HttpCodes[\"InternalServerError\"] = 500] = \"InternalServerError\";\n HttpCodes[HttpCodes[\"NotImplemented\"] = 501] = \"NotImplemented\";\n HttpCodes[HttpCodes[\"BadGateway\"] = 502] = \"BadGateway\";\n HttpCodes[HttpCodes[\"ServiceUnavailable\"] = 503] = \"ServiceUnavailable\";\n HttpCodes[HttpCodes[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));\nvar Headers;\n(function (Headers) {\n Headers[\"Accept\"] = \"accept\";\n Headers[\"ContentType\"] = \"content-type\";\n})(Headers = exports.Headers || (exports.Headers = {}));\nvar MediaTypes;\n(function (MediaTypes) {\n MediaTypes[\"ApplicationJson\"] = \"application/json\";\n})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));\n/**\n * Returns the proxy URL, depending upon the supplied url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\nfunction getProxyUrl(serverUrl) {\n const proxyUrl = pm.getProxyUrl(new URL(serverUrl));\n return proxyUrl ? proxyUrl.href : '';\n}\nexports.getProxyUrl = getProxyUrl;\nconst HttpRedirectCodes = [\n HttpCodes.MovedPermanently,\n HttpCodes.ResourceMoved,\n HttpCodes.SeeOther,\n HttpCodes.TemporaryRedirect,\n HttpCodes.PermanentRedirect\n];\nconst HttpResponseRetryCodes = [\n HttpCodes.BadGateway,\n HttpCodes.ServiceUnavailable,\n HttpCodes.GatewayTimeout\n];\nconst RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];\nconst ExponentialBackoffCeiling = 10;\nconst ExponentialBackoffTimeSlice = 5;\nclass HttpClientError extends Error {\n constructor(message, statusCode) {\n super(message);\n this.name = 'HttpClientError';\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, HttpClientError.prototype);\n }\n}\nexports.HttpClientError = HttpClientError;\nclass HttpClientResponse {\n constructor(message) {\n this.message = message;\n }\n readBody() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n let output = Buffer.alloc(0);\n this.message.on('data', (chunk) => {\n output = Buffer.concat([output, chunk]);\n });\n this.message.on('end', () => {\n resolve(output.toString());\n });\n }));\n });\n }\n}\nexports.HttpClientResponse = HttpClientResponse;\nfunction isHttps(requestUrl) {\n const parsedUrl = new URL(requestUrl);\n return parsedUrl.protocol === 'https:';\n}\nexports.isHttps = isHttps;\nclass HttpClient {\n constructor(userAgent, handlers, requestOptions) {\n this._ignoreSslError = false;\n this._allowRedirects = true;\n this._allowRedirectDowngrade = false;\n this._maxRedirects = 50;\n this._allowRetries = false;\n this._maxRetries = 1;\n this._keepAlive = false;\n this._disposed = false;\n this.userAgent = userAgent;\n this.handlers = handlers || [];\n this.requestOptions = requestOptions;\n if (requestOptions) {\n if (requestOptions.ignoreSslError != null) {\n this._ignoreSslError = requestOptions.ignoreSslError;\n }\n this._socketTimeout = requestOptions.socketTimeout;\n if (requestOptions.allowRedirects != null) {\n this._allowRedirects = requestOptions.allowRedirects;\n }\n if (requestOptions.allowRedirectDowngrade != null) {\n this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;\n }\n if (requestOptions.maxRedirects != null) {\n this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);\n }\n if (requestOptions.keepAlive != null) {\n this._keepAlive = requestOptions.keepAlive;\n }\n if (requestOptions.allowRetries != null) {\n this._allowRetries = requestOptions.allowRetries;\n }\n if (requestOptions.maxRetries != null) {\n this._maxRetries = requestOptions.maxRetries;\n }\n }\n }\n options(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});\n });\n }\n get(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('GET', requestUrl, null, additionalHeaders || {});\n });\n }\n del(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('DELETE', requestUrl, null, additionalHeaders || {});\n });\n }\n post(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('POST', requestUrl, data, additionalHeaders || {});\n });\n }\n patch(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PATCH', requestUrl, data, additionalHeaders || {});\n });\n }\n put(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PUT', requestUrl, data, additionalHeaders || {});\n });\n }\n head(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('HEAD', requestUrl, null, additionalHeaders || {});\n });\n }\n sendStream(verb, requestUrl, stream, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request(verb, requestUrl, stream, additionalHeaders);\n });\n }\n /**\n * Gets a typed object from an endpoint\n * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise\n */\n getJson(requestUrl, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n const res = yield this.get(requestUrl, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n postJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.post(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n putJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.put(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n patchJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.patch(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n /**\n * Makes a raw http request.\n * All other methods such as get, post, patch, and request ultimately call this.\n * Prefer get, del, post and patch\n */\n request(verb, requestUrl, data, headers) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._disposed) {\n throw new Error('Client has already been disposed.');\n }\n const parsedUrl = new URL(requestUrl);\n let info = this._prepareRequest(verb, parsedUrl, headers);\n // Only perform retries on reads since writes may not be idempotent.\n const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)\n ? this._maxRetries + 1\n : 1;\n let numTries = 0;\n let response;\n do {\n response = yield this.requestRaw(info, data);\n // Check if it's an authentication challenge\n if (response &&\n response.message &&\n response.message.statusCode === HttpCodes.Unauthorized) {\n let authenticationHandler;\n for (const handler of this.handlers) {\n if (handler.canHandleAuthentication(response)) {\n authenticationHandler = handler;\n break;\n }\n }\n if (authenticationHandler) {\n return authenticationHandler.handleAuthentication(this, info, data);\n }\n else {\n // We have received an unauthorized response but have no handlers to handle it.\n // Let the response return to the caller.\n return response;\n }\n }\n let redirectsRemaining = this._maxRedirects;\n while (response.message.statusCode &&\n HttpRedirectCodes.includes(response.message.statusCode) &&\n this._allowRedirects &&\n redirectsRemaining > 0) {\n const redirectUrl = response.message.headers['location'];\n if (!redirectUrl) {\n // if there's no location to redirect to, we won't\n break;\n }\n const parsedRedirectUrl = new URL(redirectUrl);\n if (parsedUrl.protocol === 'https:' &&\n parsedUrl.protocol !== parsedRedirectUrl.protocol &&\n !this._allowRedirectDowngrade) {\n throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');\n }\n // we need to finish reading the response before reassigning response\n // which will leak the open socket.\n yield response.readBody();\n // strip authorization header if redirected to a different hostname\n if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {\n for (const header in headers) {\n // header names are case insensitive\n if (header.toLowerCase() === 'authorization') {\n delete headers[header];\n }\n }\n }\n // let's make the request with the new redirectUrl\n info = this._prepareRequest(verb, parsedRedirectUrl, headers);\n response = yield this.requestRaw(info, data);\n redirectsRemaining--;\n }\n if (!response.message.statusCode ||\n !HttpResponseRetryCodes.includes(response.message.statusCode)) {\n // If not a retry code, return immediately instead of retrying\n return response;\n }\n numTries += 1;\n if (numTries < maxTries) {\n yield response.readBody();\n yield this._performExponentialBackoff(numTries);\n }\n } while (numTries < maxTries);\n return response;\n });\n }\n /**\n * Needs to be called if keepAlive is set to true in request options.\n */\n dispose() {\n if (this._agent) {\n this._agent.destroy();\n }\n this._disposed = true;\n }\n /**\n * Raw request.\n * @param info\n * @param data\n */\n requestRaw(info, data) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n function callbackForResult(err, res) {\n if (err) {\n reject(err);\n }\n else if (!res) {\n // If `err` is not passed, then `res` must be passed.\n reject(new Error('Unknown error'));\n }\n else {\n resolve(res);\n }\n }\n this.requestRawWithCallback(info, data, callbackForResult);\n });\n });\n }\n /**\n * Raw request with callback.\n * @param info\n * @param data\n * @param onResult\n */\n requestRawWithCallback(info, data, onResult) {\n if (typeof data === 'string') {\n if (!info.options.headers) {\n info.options.headers = {};\n }\n info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');\n }\n let callbackCalled = false;\n function handleResult(err, res) {\n if (!callbackCalled) {\n callbackCalled = true;\n onResult(err, res);\n }\n }\n const req = info.httpModule.request(info.options, (msg) => {\n const res = new HttpClientResponse(msg);\n handleResult(undefined, res);\n });\n let socket;\n req.on('socket', sock => {\n socket = sock;\n });\n // If we ever get disconnected, we want the socket to timeout eventually\n req.setTimeout(this._socketTimeout || 3 * 60000, () => {\n if (socket) {\n socket.end();\n }\n handleResult(new Error(`Request timeout: ${info.options.path}`));\n });\n req.on('error', function (err) {\n // err has statusCode property\n // res should have headers\n handleResult(err);\n });\n if (data && typeof data === 'string') {\n req.write(data, 'utf8');\n }\n if (data && typeof data !== 'string') {\n data.on('close', function () {\n req.end();\n });\n data.pipe(req);\n }\n else {\n req.end();\n }\n }\n /**\n * Gets an http agent. This function is useful when you need an http agent that handles\n * routing through a proxy server - depending upon the url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\n getAgent(serverUrl) {\n const parsedUrl = new URL(serverUrl);\n return this._getAgent(parsedUrl);\n }\n _prepareRequest(method, requestUrl, headers) {\n const info = {};\n info.parsedUrl = requestUrl;\n const usingSsl = info.parsedUrl.protocol === 'https:';\n info.httpModule = usingSsl ? https : http;\n const defaultPort = usingSsl ? 443 : 80;\n info.options = {};\n info.options.host = info.parsedUrl.hostname;\n info.options.port = info.parsedUrl.port\n ? parseInt(info.parsedUrl.port)\n : defaultPort;\n info.options.path =\n (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');\n info.options.method = method;\n info.options.headers = this._mergeHeaders(headers);\n if (this.userAgent != null) {\n info.options.headers['user-agent'] = this.userAgent;\n }\n info.options.agent = this._getAgent(info.parsedUrl);\n // gives handlers an opportunity to participate\n if (this.handlers) {\n for (const handler of this.handlers) {\n handler.prepareRequest(info.options);\n }\n }\n return info;\n }\n _mergeHeaders(headers) {\n if (this.requestOptions && this.requestOptions.headers) {\n return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));\n }\n return lowercaseKeys(headers || {});\n }\n _getExistingOrDefaultHeader(additionalHeaders, header, _default) {\n let clientHeader;\n if (this.requestOptions && this.requestOptions.headers) {\n clientHeader = lowercaseKeys(this.requestOptions.headers)[header];\n }\n return additionalHeaders[header] || clientHeader || _default;\n }\n _getAgent(parsedUrl) {\n let agent;\n const proxyUrl = pm.getProxyUrl(parsedUrl);\n const useProxy = proxyUrl && proxyUrl.hostname;\n if (this._keepAlive && useProxy) {\n agent = this._proxyAgent;\n }\n if (this._keepAlive && !useProxy) {\n agent = this._agent;\n }\n // if agent is already assigned use that agent.\n if (agent) {\n return agent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n let maxSockets = 100;\n if (this.requestOptions) {\n maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;\n }\n // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.\n if (proxyUrl && proxyUrl.hostname) {\n const agentOptions = {\n maxSockets,\n keepAlive: this._keepAlive,\n proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {\n proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`\n })), { host: proxyUrl.hostname, port: proxyUrl.port })\n };\n let tunnelAgent;\n const overHttps = proxyUrl.protocol === 'https:';\n if (usingSsl) {\n tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;\n }\n else {\n tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;\n }\n agent = tunnelAgent(agentOptions);\n this._proxyAgent = agent;\n }\n // if reusing agent across request and tunneling agent isn't assigned create a new agent\n if (this._keepAlive && !agent) {\n const options = { keepAlive: this._keepAlive, maxSockets };\n agent = usingSsl ? new https.Agent(options) : new http.Agent(options);\n this._agent = agent;\n }\n // if not using private agent and tunnel agent isn't setup then use global agent\n if (!agent) {\n agent = usingSsl ? https.globalAgent : http.globalAgent;\n }\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n agent.options = Object.assign(agent.options || {}, {\n rejectUnauthorized: false\n });\n }\n return agent;\n }\n _performExponentialBackoff(retryNumber) {\n return __awaiter(this, void 0, void 0, function* () {\n retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);\n const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);\n return new Promise(resolve => setTimeout(() => resolve(), ms));\n });\n }\n _processResponse(res, options) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n const statusCode = res.message.statusCode || 0;\n const response = {\n statusCode,\n result: null,\n headers: {}\n };\n // not found leads to null obj returned\n if (statusCode === HttpCodes.NotFound) {\n resolve(response);\n }\n // get the result from the body\n function dateTimeDeserializer(key, value) {\n if (typeof value === 'string') {\n const a = new Date(value);\n if (!isNaN(a.valueOf())) {\n return a;\n }\n }\n return value;\n }\n let obj;\n let contents;\n try {\n contents = yield res.readBody();\n if (contents && contents.length > 0) {\n if (options && options.deserializeDates) {\n obj = JSON.parse(contents, dateTimeDeserializer);\n }\n else {\n obj = JSON.parse(contents);\n }\n response.result = obj;\n }\n response.headers = res.message.headers;\n }\n catch (err) {\n // Invalid resource (contents not json); leaving result obj null\n }\n // note that 3xx redirects are handled by the http layer.\n if (statusCode > 299) {\n let msg;\n // if exception/error in body, attempt to get better error\n if (obj && obj.message) {\n msg = obj.message;\n }\n else if (contents && contents.length > 0) {\n // it may be the case that the exception is in the body message as string\n msg = contents;\n }\n else {\n msg = `Failed request: (${statusCode})`;\n }\n const err = new HttpClientError(msg, statusCode);\n err.result = response.result;\n reject(err);\n }\n else {\n resolve(response);\n }\n }));\n });\n }\n}\nexports.HttpClient = HttpClient;\nconst lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.checkBypass = exports.getProxyUrl = void 0;\nfunction getProxyUrl(reqUrl) {\n const usingSsl = reqUrl.protocol === 'https:';\n if (checkBypass(reqUrl)) {\n return undefined;\n }\n const proxyVar = (() => {\n if (usingSsl) {\n return process.env['https_proxy'] || process.env['HTTPS_PROXY'];\n }\n else {\n return process.env['http_proxy'] || process.env['HTTP_PROXY'];\n }\n })();\n if (proxyVar) {\n return new URL(proxyVar);\n }\n else {\n return undefined;\n }\n}\nexports.getProxyUrl = getProxyUrl;\nfunction checkBypass(reqUrl) {\n if (!reqUrl.hostname) {\n return false;\n }\n const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';\n if (!noProxy) {\n return false;\n }\n // Determine the request port\n let reqPort;\n if (reqUrl.port) {\n reqPort = Number(reqUrl.port);\n }\n else if (reqUrl.protocol === 'http:') {\n reqPort = 80;\n }\n else if (reqUrl.protocol === 'https:') {\n reqPort = 443;\n }\n // Format the request hostname and hostname with port\n const upperReqHosts = [reqUrl.hostname.toUpperCase()];\n if (typeof reqPort === 'number') {\n upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);\n }\n // Compare request host against noproxy\n for (const upperNoProxyItem of noProxy\n .split(',')\n .map(x => x.trim().toUpperCase())\n .filter(x => x)) {\n if (upperReqHosts.some(x => x === upperNoProxyItem)) {\n return true;\n }\n }\n return false;\n}\nexports.checkBypass = checkBypass;\n//# sourceMappingURL=proxy.js.map","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n\n newInvalidAsn1Error: function (msg) {\n var e = new Error();\n e.name = 'InvalidAsn1Error';\n e.message = msg || '';\n return e;\n }\n\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar errors = require('./errors');\nvar types = require('./types');\n\nvar Reader = require('./reader');\nvar Writer = require('./writer');\n\n\n// --- Exports\n\nmodule.exports = {\n\n Reader: Reader,\n\n Writer: Writer\n\n};\n\nfor (var t in types) {\n if (types.hasOwnProperty(t))\n module.exports[t] = types[t];\n}\nfor (var e in errors) {\n if (errors.hasOwnProperty(e))\n module.exports[e] = errors[e];\n}\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\n\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\n\n\n// --- API\n\nfunction Reader(data) {\n if (!data || !Buffer.isBuffer(data))\n throw new TypeError('data must be a node Buffer');\n\n this._buf = data;\n this._size = data.length;\n\n // These hold the \"current\" state\n this._len = 0;\n this._offset = 0;\n}\n\nObject.defineProperty(Reader.prototype, 'length', {\n enumerable: true,\n get: function () { return (this._len); }\n});\n\nObject.defineProperty(Reader.prototype, 'offset', {\n enumerable: true,\n get: function () { return (this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'remain', {\n get: function () { return (this._size - this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'buffer', {\n get: function () { return (this._buf.slice(this._offset)); }\n});\n\n\n/**\n * Reads a single byte and advances offset; you can pass in `true` to make this\n * a \"peek\" operation (i.e., get the byte, but don't advance the offset).\n *\n * @param {Boolean} peek true means don't move offset.\n * @return {Number} the next byte, null if not enough data.\n */\nReader.prototype.readByte = function (peek) {\n if (this._size - this._offset < 1)\n return null;\n\n var b = this._buf[this._offset] & 0xff;\n\n if (!peek)\n this._offset += 1;\n\n return b;\n};\n\n\nReader.prototype.peek = function () {\n return this.readByte(true);\n};\n\n\n/**\n * Reads a (potentially) variable length off the BER buffer. This call is\n * not really meant to be called directly, as callers have to manipulate\n * the internal buffer afterwards.\n *\n * As a result of this call, you can call `Reader.length`, until the\n * next thing called that does a readLength.\n *\n * @return {Number} the amount of offset to advance the buffer.\n * @throws {InvalidAsn1Error} on bad ASN.1\n */\nReader.prototype.readLength = function (offset) {\n if (offset === undefined)\n offset = this._offset;\n\n if (offset >= this._size)\n return null;\n\n var lenB = this._buf[offset++] & 0xff;\n if (lenB === null)\n return null;\n\n if ((lenB & 0x80) === 0x80) {\n lenB &= 0x7f;\n\n if (lenB === 0)\n throw newInvalidAsn1Error('Indefinite length not supported');\n\n if (lenB > 4)\n throw newInvalidAsn1Error('encoding too long');\n\n if (this._size - offset < lenB)\n return null;\n\n this._len = 0;\n for (var i = 0; i < lenB; i++)\n this._len = (this._len << 8) + (this._buf[offset++] & 0xff);\n\n } else {\n // Wasn't a variable length\n this._len = lenB;\n }\n\n return offset;\n};\n\n\n/**\n * Parses the next sequence in this BER buffer.\n *\n * To get the length of the sequence, call `Reader.length`.\n *\n * @return {Number} the sequence's tag.\n */\nReader.prototype.readSequence = function (tag) {\n var seq = this.peek();\n if (seq === null)\n return null;\n if (tag !== undefined && tag !== seq)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + seq.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n this._offset = o;\n return seq;\n};\n\n\nReader.prototype.readInt = function () {\n return this._readTag(ASN1.Integer);\n};\n\n\nReader.prototype.readBoolean = function () {\n return (this._readTag(ASN1.Boolean) === 0 ? false : true);\n};\n\n\nReader.prototype.readEnumeration = function () {\n return this._readTag(ASN1.Enumeration);\n};\n\n\nReader.prototype.readString = function (tag, retbuf) {\n if (!tag)\n tag = ASN1.OctetString;\n\n var b = this.peek();\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n\n if (o === null)\n return null;\n\n if (this.length > this._size - o)\n return null;\n\n this._offset = o;\n\n if (this.length === 0)\n return retbuf ? Buffer.alloc(0) : '';\n\n var str = this._buf.slice(this._offset, this._offset + this.length);\n this._offset += this.length;\n\n return retbuf ? str : str.toString('utf8');\n};\n\nReader.prototype.readOID = function (tag) {\n if (!tag)\n tag = ASN1.OID;\n\n var b = this.readString(tag, true);\n if (b === null)\n return null;\n\n var values = [];\n var value = 0;\n\n for (var i = 0; i < b.length; i++) {\n var byte = b[i] & 0xff;\n\n value <<= 7;\n value += byte & 0x7f;\n if ((byte & 0x80) === 0) {\n values.push(value);\n value = 0;\n }\n }\n\n value = values.shift();\n values.unshift(value % 40);\n values.unshift((value / 40) >> 0);\n\n return values.join('.');\n};\n\n\nReader.prototype._readTag = function (tag) {\n assert.ok(tag !== undefined);\n\n var b = this.peek();\n\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n if (this.length > 4)\n throw newInvalidAsn1Error('Integer too long: ' + this.length);\n\n if (this.length > this._size - o)\n return null;\n this._offset = o;\n\n var fb = this._buf[this._offset];\n var value = 0;\n\n for (var i = 0; i < this.length; i++) {\n value <<= 8;\n value |= (this._buf[this._offset++] & 0xff);\n }\n\n if ((fb & 0x80) === 0x80 && i !== 4)\n value -= (1 << (i * 8));\n\n return value >> 0;\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Reader;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n EOC: 0,\n Boolean: 1,\n Integer: 2,\n BitString: 3,\n OctetString: 4,\n Null: 5,\n OID: 6,\n ObjectDescriptor: 7,\n External: 8,\n Real: 9, // float\n Enumeration: 10,\n PDV: 11,\n Utf8String: 12,\n RelativeOID: 13,\n Sequence: 16,\n Set: 17,\n NumericString: 18,\n PrintableString: 19,\n T61String: 20,\n VideotexString: 21,\n IA5String: 22,\n UTCTime: 23,\n GeneralizedTime: 24,\n GraphicString: 25,\n VisibleString: 26,\n GeneralString: 28,\n UniversalString: 29,\n CharacterString: 30,\n BMPString: 31,\n Constructor: 32,\n Context: 128\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\nvar DEFAULT_OPTS = {\n size: 1024,\n growthFactor: 8\n};\n\n\n// --- Helpers\n\nfunction merge(from, to) {\n assert.ok(from);\n assert.equal(typeof (from), 'object');\n assert.ok(to);\n assert.equal(typeof (to), 'object');\n\n var keys = Object.getOwnPropertyNames(from);\n keys.forEach(function (key) {\n if (to[key])\n return;\n\n var value = Object.getOwnPropertyDescriptor(from, key);\n Object.defineProperty(to, key, value);\n });\n\n return to;\n}\n\n\n\n// --- API\n\nfunction Writer(options) {\n options = merge(DEFAULT_OPTS, options || {});\n\n this._buf = Buffer.alloc(options.size || 1024);\n this._size = this._buf.length;\n this._offset = 0;\n this._options = options;\n\n // A list of offsets in the buffer where we need to insert\n // sequence tag/len pairs.\n this._seq = [];\n}\n\nObject.defineProperty(Writer.prototype, 'buffer', {\n get: function () {\n if (this._seq.length)\n throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');\n\n return (this._buf.slice(0, this._offset));\n }\n});\n\nWriter.prototype.writeByte = function (b) {\n if (typeof (b) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(1);\n this._buf[this._offset++] = b;\n};\n\n\nWriter.prototype.writeInt = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Integer;\n\n var sz = 4;\n\n while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&\n (sz > 1)) {\n sz--;\n i <<= 8;\n }\n\n if (sz > 4)\n throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');\n\n this._ensure(2 + sz);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = sz;\n\n while (sz-- > 0) {\n this._buf[this._offset++] = ((i & 0xff000000) >>> 24);\n i <<= 8;\n }\n\n};\n\n\nWriter.prototype.writeNull = function () {\n this.writeByte(ASN1.Null);\n this.writeByte(0x00);\n};\n\n\nWriter.prototype.writeEnumeration = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Enumeration;\n\n return this.writeInt(i, tag);\n};\n\n\nWriter.prototype.writeBoolean = function (b, tag) {\n if (typeof (b) !== 'boolean')\n throw new TypeError('argument must be a Boolean');\n if (typeof (tag) !== 'number')\n tag = ASN1.Boolean;\n\n this._ensure(3);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = 0x01;\n this._buf[this._offset++] = b ? 0xff : 0x00;\n};\n\n\nWriter.prototype.writeString = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');\n if (typeof (tag) !== 'number')\n tag = ASN1.OctetString;\n\n var len = Buffer.byteLength(s);\n this.writeByte(tag);\n this.writeLength(len);\n if (len) {\n this._ensure(len);\n this._buf.write(s, this._offset);\n this._offset += len;\n }\n};\n\n\nWriter.prototype.writeBuffer = function (buf, tag) {\n if (typeof (tag) !== 'number')\n throw new TypeError('tag must be a number');\n if (!Buffer.isBuffer(buf))\n throw new TypeError('argument must be a buffer');\n\n this.writeByte(tag);\n this.writeLength(buf.length);\n this._ensure(buf.length);\n buf.copy(this._buf, this._offset, 0, buf.length);\n this._offset += buf.length;\n};\n\n\nWriter.prototype.writeStringArray = function (strings) {\n if ((!strings instanceof Array))\n throw new TypeError('argument must be an Array[String]');\n\n var self = this;\n strings.forEach(function (s) {\n self.writeString(s);\n });\n};\n\n// This is really to solve DER cases, but whatever for now\nWriter.prototype.writeOID = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string');\n if (typeof (tag) !== 'number')\n tag = ASN1.OID;\n\n if (!/^([0-9]+\\.){3,}[0-9]+$/.test(s))\n throw new Error('argument is not a valid OID string');\n\n function encodeOctet(bytes, octet) {\n if (octet < 128) {\n bytes.push(octet);\n } else if (octet < 16384) {\n bytes.push((octet >>> 7) | 0x80);\n bytes.push(octet & 0x7F);\n } else if (octet < 2097152) {\n bytes.push((octet >>> 14) | 0x80);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else if (octet < 268435456) {\n bytes.push((octet >>> 21) | 0x80);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else {\n bytes.push(((octet >>> 28) | 0x80) & 0xFF);\n bytes.push(((octet >>> 21) | 0x80) & 0xFF);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n }\n }\n\n var tmp = s.split('.');\n var bytes = [];\n bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));\n tmp.slice(2).forEach(function (b) {\n encodeOctet(bytes, parseInt(b, 10));\n });\n\n var self = this;\n this._ensure(2 + bytes.length);\n this.writeByte(tag);\n this.writeLength(bytes.length);\n bytes.forEach(function (b) {\n self.writeByte(b);\n });\n};\n\n\nWriter.prototype.writeLength = function (len) {\n if (typeof (len) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(4);\n\n if (len <= 0x7f) {\n this._buf[this._offset++] = len;\n } else if (len <= 0xff) {\n this._buf[this._offset++] = 0x81;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffff) {\n this._buf[this._offset++] = 0x82;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffffff) {\n this._buf[this._offset++] = 0x83;\n this._buf[this._offset++] = len >> 16;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else {\n throw newInvalidAsn1Error('Length too long (> 4 bytes)');\n }\n};\n\nWriter.prototype.startSequence = function (tag) {\n if (typeof (tag) !== 'number')\n tag = ASN1.Sequence | ASN1.Constructor;\n\n this.writeByte(tag);\n this._seq.push(this._offset);\n this._ensure(3);\n this._offset += 3;\n};\n\n\nWriter.prototype.endSequence = function () {\n var seq = this._seq.pop();\n var start = seq + 3;\n var len = this._offset - start;\n\n if (len <= 0x7f) {\n this._shift(start, len, -2);\n this._buf[seq] = len;\n } else if (len <= 0xff) {\n this._shift(start, len, -1);\n this._buf[seq] = 0x81;\n this._buf[seq + 1] = len;\n } else if (len <= 0xffff) {\n this._buf[seq] = 0x82;\n this._buf[seq + 1] = len >> 8;\n this._buf[seq + 2] = len;\n } else if (len <= 0xffffff) {\n this._shift(start, len, 1);\n this._buf[seq] = 0x83;\n this._buf[seq + 1] = len >> 16;\n this._buf[seq + 2] = len >> 8;\n this._buf[seq + 3] = len;\n } else {\n throw newInvalidAsn1Error('Sequence too long');\n }\n};\n\n\nWriter.prototype._shift = function (start, len, shift) {\n assert.ok(start !== undefined);\n assert.ok(len !== undefined);\n assert.ok(shift);\n\n this._buf.copy(this._buf, start + shift, start, start + len);\n this._offset += shift;\n};\n\nWriter.prototype._ensure = function (len) {\n assert.ok(len);\n\n if (this._size - this._offset < len) {\n var sz = this._size * this._options.growthFactor;\n if (sz - this._offset < len)\n sz += len;\n\n var buf = Buffer.alloc(sz);\n\n this._buf.copy(buf, 0, 0, this._offset);\n this._buf = buf;\n this._size = sz;\n }\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Writer;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n// If you have no idea what ASN.1 or BER is, see this:\n// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc\n\nvar Ber = require('./ber/index');\n\n\n\n// --- Exported API\n\nmodule.exports = {\n\n Ber: Ber,\n\n BerReader: Ber.Reader,\n\n BerWriter: Ber.Writer\n\n};\n","'use strict';\n\nvar crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;\n\n/*\n * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a\n * result, it retains the original copyright and license. The two files are\n * under slightly different (but compatible) licenses, and are here combined in\n * one file.\n *\n * Credit for the actual porting work goes to:\n * Devi Mandiri \n */\n\n/*\n * The Blowfish portions are under the following license:\n *\n * Blowfish block cipher for OpenBSD\n * Copyright 1997 Niels Provos \n * All rights reserved.\n *\n * Implementation advice by David Mazieres .\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * The bcrypt_pbkdf portions are under the following license:\n *\n * Copyright (c) 2013 Ted Unangst \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n/*\n * Performance improvements (Javascript-specific):\n *\n * Copyright 2016, Joyent Inc\n * Author: Alex Wilson \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n// Ported from OpenBSD bcrypt_pbkdf.c v1.9\n\nvar BLF_J = 0;\n\nvar Blowfish = function() {\n this.S = [\n new Uint32Array([\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,\n 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,\n 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,\n 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,\n 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,\n 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,\n 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,\n 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,\n 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,\n 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,\n 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,\n 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,\n 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,\n 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,\n 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,\n 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,\n 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,\n 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,\n 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,\n 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,\n 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,\n 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,\n 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,\n 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,\n 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,\n 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,\n 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,\n 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,\n 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,\n 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,\n 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,\n 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,\n 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,\n 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,\n 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,\n 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,\n 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,\n 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,\n 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,\n 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,\n 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,\n 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,\n 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),\n new Uint32Array([\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,\n 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,\n 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,\n 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,\n 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,\n 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,\n 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,\n 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,\n 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,\n 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,\n 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,\n 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,\n 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,\n 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,\n 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,\n 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,\n 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,\n 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,\n 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,\n 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,\n 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,\n 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,\n 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,\n 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,\n 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,\n 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,\n 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,\n 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,\n 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,\n 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,\n 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,\n 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,\n 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,\n 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,\n 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,\n 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,\n 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,\n 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,\n 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,\n 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,\n 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,\n 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,\n 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),\n new Uint32Array([\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,\n 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,\n 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,\n 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,\n 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,\n 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,\n 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,\n 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,\n 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,\n 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,\n 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,\n 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,\n 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,\n 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,\n 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,\n 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,\n 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,\n 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,\n 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,\n 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,\n 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,\n 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,\n 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,\n 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,\n 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,\n 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,\n 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,\n 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,\n 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,\n 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,\n 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,\n 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,\n 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,\n 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,\n 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,\n 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,\n 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,\n 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,\n 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,\n 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,\n 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,\n 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,\n 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),\n new Uint32Array([\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,\n 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,\n 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,\n 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,\n 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,\n 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,\n 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,\n 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,\n 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,\n 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,\n 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,\n 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,\n 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,\n 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,\n 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,\n 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,\n 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,\n 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,\n 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,\n 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,\n 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,\n 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,\n 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,\n 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,\n 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,\n 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,\n 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,\n 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,\n 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,\n 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,\n 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,\n 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,\n 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,\n 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,\n 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,\n 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,\n 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,\n 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,\n 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,\n 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,\n 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,\n 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,\n 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])\n ];\n this.P = new Uint32Array([\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,\n 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,\n 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,\n 0x9216d5d9, 0x8979fb1b]);\n};\n\nfunction F(S, x8, i) {\n return (((S[0][x8[i+3]] +\n S[1][x8[i+2]]) ^\n S[2][x8[i+1]]) +\n S[3][x8[i]]);\n};\n\nBlowfish.prototype.encipher = function(x, x8) {\n if (x8 === undefined) {\n x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n }\n x[0] ^= this.P[0];\n for (var i = 1; i < 16; i += 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[17];\n x[1] = t;\n};\n\nBlowfish.prototype.decipher = function(x) {\n var x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n x[0] ^= this.P[17];\n for (var i = 16; i > 0; i -= 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[0];\n x[1] = t;\n};\n\nfunction stream2word(data, databytes){\n var i, temp = 0;\n for (i = 0; i < 4; i++, BLF_J++) {\n if (BLF_J >= databytes) BLF_J = 0;\n temp = (temp << 8) | data[BLF_J];\n }\n return temp;\n};\n\nBlowfish.prototype.expand0state = function(key, keybytes) {\n var d = new Uint32Array(2), i, k;\n var d8 = new Uint8Array(d.buffer);\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n BLF_J = 0;\n\n for (i = 0; i < 18; i += 2) {\n this.encipher(d, d8);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n this.encipher(d, d8);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n};\n\nBlowfish.prototype.expandstate = function(data, databytes, key, keybytes) {\n var d = new Uint32Array(2), i, k;\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n\n for (i = 0, BLF_J = 0; i < 18; i += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n BLF_J = 0;\n};\n\nBlowfish.prototype.enc = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.encipher(data.subarray(i*2));\n }\n};\n\nBlowfish.prototype.dec = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.decipher(data.subarray(i*2));\n }\n};\n\nvar BCRYPT_BLOCKS = 8,\n BCRYPT_HASHSIZE = 32;\n\nfunction bcrypt_hash(sha2pass, sha2salt, out) {\n var state = new Blowfish(),\n cdata = new Uint32Array(BCRYPT_BLOCKS), i,\n ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,\n 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,\n 105,116,101]); //\"OxychromaticBlowfishSwatDynamite\"\n\n state.expandstate(sha2salt, 64, sha2pass, 64);\n for (i = 0; i < 64; i++) {\n state.expand0state(sha2salt, 64);\n state.expand0state(sha2pass, 64);\n }\n\n for (i = 0; i < BCRYPT_BLOCKS; i++)\n cdata[i] = stream2word(ciphertext, ciphertext.byteLength);\n for (i = 0; i < 64; i++)\n state.enc(cdata, cdata.byteLength / 8);\n\n for (i = 0; i < BCRYPT_BLOCKS; i++) {\n out[4*i+3] = cdata[i] >>> 24;\n out[4*i+2] = cdata[i] >>> 16;\n out[4*i+1] = cdata[i] >>> 8;\n out[4*i+0] = cdata[i];\n }\n};\n\nfunction bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {\n var sha2pass = new Uint8Array(64),\n sha2salt = new Uint8Array(64),\n out = new Uint8Array(BCRYPT_HASHSIZE),\n tmpout = new Uint8Array(BCRYPT_HASHSIZE),\n countsalt = new Uint8Array(saltlen+4),\n i, j, amt, stride, dest, count,\n origkeylen = keylen;\n\n if (rounds < 1)\n return -1;\n if (passlen === 0 || saltlen === 0 || keylen === 0 ||\n keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))\n return -1;\n\n stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);\n amt = Math.floor((keylen + stride - 1) / stride);\n\n for (i = 0; i < saltlen; i++)\n countsalt[i] = salt[i];\n\n crypto_hash_sha512(sha2pass, pass, passlen);\n\n for (count = 1; keylen > 0; count++) {\n countsalt[saltlen+0] = count >>> 24;\n countsalt[saltlen+1] = count >>> 16;\n countsalt[saltlen+2] = count >>> 8;\n countsalt[saltlen+3] = count;\n\n crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (i = out.byteLength; i--;)\n out[i] = tmpout[i];\n\n for (i = 1; i < rounds; i++) {\n crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (j = 0; j < out.byteLength; j++)\n out[j] ^= tmpout[j];\n }\n\n amt = Math.min(amt, keylen);\n for (i = 0; i < amt; i++) {\n dest = i * stride + (count - 1);\n if (dest >= origkeylen)\n break;\n key[dest] = out[i];\n }\n keylen -= i;\n }\n\n return 0;\n};\n\nmodule.exports = {\n BLOCKS: BCRYPT_BLOCKS,\n HASHSIZE: BCRYPT_HASHSIZE,\n hash: bcrypt_hash,\n pbkdf: bcrypt_pbkdf\n};\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst symbol = Symbol.for('BufferList')\n\nfunction BufferList (buf) {\n if (!(this instanceof BufferList)) {\n return new BufferList(buf)\n }\n\n BufferList._init.call(this, buf)\n}\n\nBufferList._init = function _init (buf) {\n Object.defineProperty(this, symbol, { value: true })\n\n this._bufs = []\n this.length = 0\n\n if (buf) {\n this.append(buf)\n }\n}\n\nBufferList.prototype._new = function _new (buf) {\n return new BufferList(buf)\n}\n\nBufferList.prototype._offset = function _offset (offset) {\n if (offset === 0) {\n return [0, 0]\n }\n\n let tot = 0\n\n for (let i = 0; i < this._bufs.length; i++) {\n const _t = tot + this._bufs[i].length\n if (offset < _t || i === this._bufs.length - 1) {\n return [i, offset - tot]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n const bufferId = blOffset[0]\n let offset = blOffset[1]\n\n for (let i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n\n return offset\n}\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n\n const offset = this._offset(index)\n\n return this._bufs[offset[0]][offset[1]]\n}\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start === 'number' && start < 0) {\n start += this.length\n }\n\n if (typeof end === 'number' && end < 0) {\n end += this.length\n }\n\n return this.copy(null, 0, start, end)\n}\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart !== 'number' || srcStart < 0) {\n srcStart = 0\n }\n\n if (typeof srcEnd !== 'number' || srcEnd > this.length) {\n srcEnd = this.length\n }\n\n if (srcStart >= this.length) {\n return dst || Buffer.alloc(0)\n }\n\n if (srcEnd <= 0) {\n return dst || Buffer.alloc(0)\n }\n\n const copy = !!dst\n const off = this._offset(srcStart)\n const len = srcEnd - srcStart\n let bytes = len\n let bufoff = (copy && dstStart) || 0\n let start = off[1]\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd === this.length) {\n if (!copy) {\n // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (let i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) {\n // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n }\n\n for (let i = off[0]; i < this._bufs.length; i++) {\n const l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start) {\n start = 0\n }\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0) {\n start += this.length\n }\n\n if (end < 0) {\n end += this.length\n }\n\n if (start === end) {\n return this._new()\n }\n\n const startOffset = this._offset(start)\n const endOffset = this._offset(end)\n const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] === 0) {\n buffers.pop()\n } else {\n buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])\n }\n\n if (startOffset[1] !== 0) {\n buffers[0] = buffers[0].slice(startOffset[1])\n }\n\n return this._new(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n\n return this\n}\n\nBufferList.prototype.duplicate = function duplicate () {\n const copy = this._new()\n\n for (let i = 0; i < this._bufs.length; i++) {\n copy.append(this._bufs[i])\n }\n\n return copy\n}\n\nBufferList.prototype.append = function append (buf) {\n if (buf == null) {\n return this\n }\n\n if (buf.buffer) {\n // append a view of the underlying ArrayBuffer\n this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))\n } else if (Array.isArray(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.append(buf[i])\n }\n } else if (this._isBufferList(buf)) {\n // unwrap argument into individual BufferLists\n for (let i = 0; i < buf._bufs.length; i++) {\n this.append(buf._bufs[i])\n }\n } else {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf === 'number') {\n buf = buf.toString()\n }\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (this._isBufferList(search)) {\n search = search.slice()\n } else if (Array.isArray(search.buffer)) {\n search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n const blOffset = this._offset(offset)\n let blIndex = blOffset[0] // index of which internal buffer we're working on\n let buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (; blIndex < this._bufs.length; blIndex++) {\n const buff = this._bufs[blIndex]\n\n while (buffOffset < buff.length) {\n const availableWindow = buff.length - buffOffset\n\n if (availableWindow >= search.length) {\n const nativeSearchResult = buff.indexOf(search, buffOffset)\n\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n const revOffset = this._reverseOffset([blIndex, buffOffset])\n\n if (this._match(revOffset, search)) {\n return revOffset\n }\n\n buffOffset++\n }\n }\n\n buffOffset = 0\n }\n\n return -1\n}\n\nBufferList.prototype._match = function (offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n\n for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {\n if (this.get(offset + searchOffset) !== search[searchOffset]) {\n return false\n }\n }\n return true\n}\n\n;(function () {\n const methods = {\n readDoubleBE: 8,\n readDoubleLE: 8,\n readFloatBE: 4,\n readFloatLE: 4,\n readInt32BE: 4,\n readInt32LE: 4,\n readUInt32BE: 4,\n readUInt32LE: 4,\n readInt16BE: 2,\n readInt16LE: 2,\n readUInt16BE: 2,\n readUInt16LE: 2,\n readInt8: 1,\n readUInt8: 1,\n readIntBE: null,\n readIntLE: null,\n readUIntBE: null,\n readUIntLE: null\n }\n\n for (const m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n } else {\n BufferList.prototype[m] = function (offset = 0) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n// Used internally by the class and also as an indicator of this object being\n// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser\n// environment because there could be multiple different copies of the\n// BufferList class and some `BufferList`s might be `BufferList`s.\nBufferList.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferList || BufferList.isBufferList(b)\n}\n\nBufferList.isBufferList = function isBufferList (b) {\n return b != null && b[symbol]\n}\n\nmodule.exports = BufferList\n","'use strict'\n\nconst DuplexStream = require('readable-stream').Duplex\nconst inherits = require('inherits')\nconst BufferList = require('./BufferList')\n\nfunction BufferListStream (callback) {\n if (!(this instanceof BufferListStream)) {\n return new BufferListStream(callback)\n }\n\n if (typeof callback === 'function') {\n this._callback = callback\n\n const piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n\n callback = null\n }\n\n BufferList._init.call(this, callback)\n DuplexStream.call(this)\n}\n\ninherits(BufferListStream, DuplexStream)\nObject.assign(BufferListStream.prototype, BufferList.prototype)\n\nBufferListStream.prototype._new = function _new (callback) {\n return new BufferListStream(callback)\n}\n\nBufferListStream.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback === 'function') {\n callback()\n }\n}\n\nBufferListStream.prototype._read = function _read (size) {\n if (!this.length) {\n return this.push(null)\n }\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\nBufferListStream.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\nBufferListStream.prototype._destroy = function _destroy (err, cb) {\n this._bufs.length = 0\n this.length = 0\n cb(err)\n}\n\nBufferListStream.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)\n}\n\nBufferListStream.isBufferList = BufferList.isBufferList\n\nmodule.exports = BufferListStream\nmodule.exports.BufferListStream = BufferListStream\nmodule.exports.BufferList = BufferList\n","'use strict'\nconst fs = require('fs')\nconst path = require('path')\n\n/* istanbul ignore next */\nconst LCHOWN = fs.lchown ? 'lchown' : 'chown'\n/* istanbul ignore next */\nconst LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync'\n\n/* istanbul ignore next */\nconst needEISDIRHandled = fs.lchown &&\n !process.version.match(/v1[1-9]+\\./) &&\n !process.version.match(/v10\\.[6-9]/)\n\nconst lchownSync = (path, uid, gid) => {\n try {\n return fs[LCHOWNSYNC](path, uid, gid)\n } catch (er) {\n if (er.code !== 'ENOENT')\n throw er\n }\n}\n\n/* istanbul ignore next */\nconst chownSync = (path, uid, gid) => {\n try {\n return fs.chownSync(path, uid, gid)\n } catch (er) {\n if (er.code !== 'ENOENT')\n throw er\n }\n}\n\n/* istanbul ignore next */\nconst handleEISDIR =\n needEISDIRHandled ? (path, uid, gid, cb) => er => {\n // Node prior to v10 had a very questionable implementation of\n // fs.lchown, which would always try to call fs.open on a directory\n // Fall back to fs.chown in those cases.\n if (!er || er.code !== 'EISDIR')\n cb(er)\n else\n fs.chown(path, uid, gid, cb)\n }\n : (_, __, ___, cb) => cb\n\n/* istanbul ignore next */\nconst handleEISDirSync =\n needEISDIRHandled ? (path, uid, gid) => {\n try {\n return lchownSync(path, uid, gid)\n } catch (er) {\n if (er.code !== 'EISDIR')\n throw er\n chownSync(path, uid, gid)\n }\n }\n : (path, uid, gid) => lchownSync(path, uid, gid)\n\n// fs.readdir could only accept an options object as of node v6\nconst nodeVersion = process.version\nlet readdir = (path, options, cb) => fs.readdir(path, options, cb)\nlet readdirSync = (path, options) => fs.readdirSync(path, options)\n/* istanbul ignore next */\nif (/^v4\\./.test(nodeVersion))\n readdir = (path, options, cb) => fs.readdir(path, cb)\n\nconst chown = (cpath, uid, gid, cb) => {\n fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => {\n // Skip ENOENT error\n cb(er && er.code !== 'ENOENT' ? er : null)\n }))\n}\n\nconst chownrKid = (p, child, uid, gid, cb) => {\n if (typeof child === 'string')\n return fs.lstat(path.resolve(p, child), (er, stats) => {\n // Skip ENOENT error\n if (er)\n return cb(er.code !== 'ENOENT' ? er : null)\n stats.name = child\n chownrKid(p, stats, uid, gid, cb)\n })\n\n if (child.isDirectory()) {\n chownr(path.resolve(p, child.name), uid, gid, er => {\n if (er)\n return cb(er)\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n })\n } else {\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n }\n}\n\n\nconst chownr = (p, uid, gid, cb) => {\n readdir(p, { withFileTypes: true }, (er, children) => {\n // any error other than ENOTDIR or ENOTSUP means it's not readable,\n // or doesn't exist. give up.\n if (er) {\n if (er.code === 'ENOENT')\n return cb()\n else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')\n return cb(er)\n }\n if (er || !children.length)\n return chown(p, uid, gid, cb)\n\n let len = children.length\n let errState = null\n const then = er => {\n if (errState)\n return\n if (er)\n return cb(errState = er)\n if (-- len === 0)\n return chown(p, uid, gid, cb)\n }\n\n children.forEach(child => chownrKid(p, child, uid, gid, then))\n })\n}\n\nconst chownrKidSync = (p, child, uid, gid) => {\n if (typeof child === 'string') {\n try {\n const stats = fs.lstatSync(path.resolve(p, child))\n stats.name = child\n child = stats\n } catch (er) {\n if (er.code === 'ENOENT')\n return\n else\n throw er\n }\n }\n\n if (child.isDirectory())\n chownrSync(path.resolve(p, child.name), uid, gid)\n\n handleEISDirSync(path.resolve(p, child.name), uid, gid)\n}\n\nconst chownrSync = (p, uid, gid) => {\n let children\n try {\n children = readdirSync(p, { withFileTypes: true })\n } catch (er) {\n if (er.code === 'ENOENT')\n return\n else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP')\n return handleEISDirSync(p, uid, gid)\n else\n throw er\n }\n\n if (children && children.length)\n children.forEach(child => chownrKidSync(p, child, uid, gid))\n\n return handleEISDirSync(p, uid, gid)\n}\n\nmodule.exports = chownr\nchownr.sync = chownrSync\n","const binding = require('../build/Release/cpufeatures.node');\n\nmodule.exports = binding.getCPUInfo;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","//Based on follow-redirects v0.0.x\n\nvar nativeHttps = require('https'),\n nativeHttp = require('http'),\n url = require('url'),\n utils = require('./utils');\n\nvar maxRedirects = module.exports.maxRedirects = 5;\n\nvar protocols = {\n https: nativeHttps,\n http: nativeHttp\n};\n\nfor (var protocol in protocols) {\n var h = function() {};\n h.prototype = protocols[protocol];\n h = new h();\n\n h.request = function(h) {\n return function(options, callback, redirectOptions) {\n\n redirectOptions = redirectOptions || {};\n\n var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects;\n\n var redirect = utils.extend({\n count: 0,\n max: max,\n clientRequest: null,\n userCallback: callback\n }, redirectOptions);\n\n if (redirect.count > redirect.max) {\n var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.');\n redirect.clientRequest.emit('error', err);\n return redirect.clientRequest;\n }\n\n redirect.count++;\n\n var reqUrl;\n if (typeof options === 'string') {\n reqUrl = options;\n } else {\n reqUrl = url.format(utils.extend({\n protocol: protocol\n }, options));\n }\n\n var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect));\n\n if (!redirect.clientRequest) redirect.clientRequest = clientRequest;\n\n function redirectCallback(reqUrl, redirect) {\n return function(res) {\n if (res.statusCode < 300 || res.statusCode > 399) {\n return redirect.userCallback(res);\n }\n\n if (!('location' in res.headers)) {\n return redirect.userCallback(res);\n }\n\n var redirectUrl = url.resolve(reqUrl, res.headers.location);\n\n var proto = url.parse(redirectUrl).protocol;\n proto = proto.substr(0, proto.length - 1);\n return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect);\n };\n }\n\n return clientRequest;\n };\n }(h);\n\n // see https://github.com/joyent/node/blob/master/lib/http.js#L1623\n h.get = function(h) {\n return function(options, cb, redirectOptions) {\n var req = h.request(options, cb, redirectOptions);\n req.end();\n return req;\n };\n }(h);\n\n module.exports[protocol] = h;\n}\n","module.exports = HttpDuplex;\n\nvar util = require('util'),\n stream = require('readable-stream');\n\nutil.inherits(HttpDuplex, stream.Duplex);\n\nfunction HttpDuplex(req, res, options) {\n var self = this;\n\n if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options);\n\n stream.Duplex.call(self, options);\n self._output = null;\n\n self.connect(req, res);\n}\n\nHttpDuplex.prototype.connect = function(req, res) {\n var self = this;\n self.req = req;\n self._output = res;\n self.emit('response', res);\n\n res.on('data', function(c) {\n if (!self.push(c)) self._output.pause();\n });\n res.on('end', function() {\n self.push(null);\n });\n};\n\nHttpDuplex.prototype._read = function(n) {\n if (this._output) this._output.resume();\n};\n\nHttpDuplex.prototype._write = function(chunk, encoding, cb) {\n this.req.write(chunk, encoding);\n cb();\n};\n\nHttpDuplex.prototype.end = function(chunk, encoding, cb) {\n this._output.socket.destroy();\n return this.req.end(chunk, encoding, cb);\n};\n\nHttpDuplex.prototype.destroy = function() {\n this.req.destroy();\n this._output.socket.destroy();\n};\n","var querystring = require('querystring'),\n http = require('./http'),\n fs = require('fs'),\n path = require('path'),\n url = require('url'),\n ssh = require('./ssh'),\n HttpDuplex = require('./http_duplex'),\n debug = require('debug')('modem'),\n utils = require('./utils'),\n util = require('util'),\n url = require('url'),\n splitca = require('split-ca'),\n isWin = require('os').type() === 'Windows_NT';\n\nvar defaultOpts = function () {\n var host;\n var opts = {};\n\n if (!process.env.DOCKER_HOST) {\n // Windows socket path: //./pipe/docker_engine ( Windows 10 )\n // Linux & Darwin socket path: /var/run/docker.sock\n opts.socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock';\n } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) {\n // Strip off unix://, fall back to default of /var/run/docker.sock if\n // unix:// was passed without a path\n opts.socketPath = process.env.DOCKER_HOST.substring(7) || '/var/run/docker.sock';\n } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) {\n // Strip off npipe://, fall back to default of //./pipe/docker_engine if\n // npipe:// was passed without a path\n opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine';\n } else {\n var hostStr = process.env.DOCKER_HOST;\n if (hostStr.indexOf('\\/\\/') < 0) {\n hostStr = 'tcp://' + hostStr;\n }\n try {\n host = new url.URL(hostStr);\n } catch (err) {\n throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234');\n }\n\n opts.port = host.port;\n\n if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') {\n opts.protocol = 'https';\n } else if (host.protocol === 'ssh:') {\n opts.protocol = 'ssh';\n opts.username = host.username;\n opts.sshOptions = {\n agent: process.env.SSH_AUTH_SOCK,\n }\n } else {\n opts.protocol = 'http';\n }\n\n opts.host = host.hostname;\n\n if (process.env.DOCKER_CERT_PATH) {\n opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem'));\n opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem'));\n opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem'));\n }\n\n if (process.env.DOCKER_CLIENT_TIMEOUT) {\n opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10);\n }\n }\n\n return opts;\n};\n\n\nvar Modem = function (options) {\n var optDefaults = defaultOpts();\n var opts = Object.assign({}, optDefaults, options);\n\n this.host = opts.host;\n\n if(!this.host) {\n this.socketPath = opts.socketPath;\n }\n\n this.port = opts.port;\n this.username = opts.username;\n this.password = opts.password;\n this.version = opts.version;\n this.key = opts.key;\n this.cert = opts.cert;\n this.ca = opts.ca;\n this.timeout = opts.timeout;\n this.connectionTimeout = opts.connectionTimeout;\n this.checkServerIdentity = opts.checkServerIdentity;\n this.agent = opts.agent;\n this.headers = opts.headers || {};\n this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions);\n //retrocompabitlity\n if(this.sshOptions.agentForward === undefined) {\n this.sshOptions.agentForward = opts.agentForward;\n }\n\n if (this.key && this.cert && this.ca) {\n this.protocol = 'https';\n }\n this.protocol = opts.protocol || this.protocol || 'http';\n};\n\nModem.prototype.dial = function (options, callback) {\n var opts, address, data;\n var self = this;\n\n if (options.options) {\n opts = options.options;\n }\n\n // Prevent credentials from showing up in URL\n if (opts && opts.authconfig) {\n delete opts.authconfig;\n }\n\n // Prevent abortsignal from showing up in the URL\n if (opts && opts.abortSignal) {\n delete opts.abortSignal;\n }\n\n if (this.version) {\n options.path = '/' + this.version + options.path;\n }\n\n if (this.host) {\n var parsed = url.parse(self.host);\n address = url.format({\n 'protocol': parsed.protocol || self.protocol,\n 'hostname': parsed.hostname || self.host,\n 'port': self.port\n });\n address = url.resolve(address, options.path);\n } else {\n address = options.path;\n }\n\n if (options.path.indexOf('?') !== -1) {\n if (opts && Object.keys(opts).length > 0) {\n address += this.buildQuerystring(opts._query || opts);\n } else {\n address = address.substring(0, address.length - 1);\n }\n }\n\n var optionsf = {\n path: address,\n method: options.method,\n headers: options.headers || Object.assign({}, self.headers),\n key: self.key,\n cert: self.cert,\n ca: self.ca\n };\n\n if (this.checkServerIdentity) {\n optionsf.checkServerIdentity = this.checkServerIdentity;\n }\n\n if (this.agent) {\n optionsf.agent = this.agent;\n }\n\n if (options.authconfig) {\n optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 ||\n Buffer.from(JSON.stringify(options.authconfig)).toString('base64');\n }\n\n if (options.registryconfig) {\n optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 ||\n Buffer.from(JSON.stringify(options.registryconfig)).toString('base64');\n }\n\n if (options.abortSignal) {\n optionsf.signal = options.abortSignal;\n }\n\n if (options.file) {\n if (typeof options.file === 'string') {\n data = fs.createReadStream(path.resolve(options.file));\n } else {\n data = options.file;\n }\n optionsf.headers['Content-Type'] = 'application/tar';\n } else if (opts && options.method === 'POST') {\n data = JSON.stringify(opts._body || opts);\n if (options.allowEmpty) {\n optionsf.headers['Content-Type'] = 'application/json';\n } else {\n if (data !== '{}' && data !== '\"\"') {\n optionsf.headers['Content-Type'] = 'application/json';\n } else {\n data = undefined;\n }\n }\n }\n\n if (typeof data === 'string') {\n optionsf.headers['Content-Length'] = Buffer.byteLength(data);\n } else if (Buffer.isBuffer(data) === true) {\n optionsf.headers['Content-Length'] = data.length;\n } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) {\n optionsf.headers['Transfer-Encoding'] = 'chunked';\n }\n\n if (options.hijack) {\n optionsf.headers.Connection = 'Upgrade';\n optionsf.headers.Upgrade = 'tcp';\n }\n\n if (this.socketPath) {\n optionsf.socketPath = this.socketPath;\n } else {\n var urlp = url.parse(address);\n optionsf.hostname = urlp.hostname;\n optionsf.port = urlp.port;\n optionsf.path = urlp.path;\n }\n\n this.buildRequest(optionsf, options, data, callback);\n};\n\nModem.prototype.buildRequest = function (options, context, data, callback) {\n var self = this;\n var connectionTimeoutTimer;\n\n var opts = self.protocol === 'ssh' ? Object.assign(options, {\n agent: ssh(Object.assign({}, self.sshOptions, {\n 'host': self.host,\n 'port': self.port,\n 'username': self.username,\n 'password': self.password,\n })),\n protocol: 'http:',\n }) : options;\n\n var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { });\n\n debug('Sending: %s', util.inspect(options, {\n showHidden: true,\n depth: null\n }));\n\n if (self.connectionTimeout) {\n connectionTimeoutTimer = setTimeout(function () {\n debug('Connection Timeout of %s ms exceeded', self.connectionTimeout);\n req.abort();\n }, self.connectionTimeout);\n }\n\n if (self.timeout) {\n req.on('socket', function (socket) {\n socket.setTimeout(self.timeout);\n socket.on('timeout', function () {\n debug('Timeout of %s ms exceeded', self.timeout);\n req.abort();\n });\n });\n }\n\n if (context.hijack === true) {\n clearTimeout(connectionTimeoutTimer);\n req.on('upgrade', function (res, sock, head) {\n return callback(null, sock);\n });\n }\n\n req.on('connect', function () {\n clearTimeout(connectionTimeoutTimer);\n });\n\n req.on('disconnect', function () {\n clearTimeout(connectionTimeoutTimer);\n });\n\n req.on('response', function (res) {\n clearTimeout(connectionTimeoutTimer);\n if (context.isStream === true) {\n self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback);\n } else {\n var chunks = [];\n res.on('data', function (chunk) {\n chunks.push(chunk);\n });\n\n res.on('end', function () {\n var buffer = Buffer.concat(chunks);\n var result = buffer.toString();\n\n debug('Received: %s', result);\n\n var json = utils.parseJSON(result) || buffer;\n self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback);\n });\n }\n });\n\n req.on('error', function (error) {\n clearTimeout(connectionTimeoutTimer);\n self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback);\n });\n\n if (typeof data === 'string' || Buffer.isBuffer(data)) {\n req.write(data);\n } else if (data) {\n data.on('error', function (error) {\n req.destroy(error);\n });\n data.pipe(req);\n }\n\n if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) {\n req.end();\n }\n};\n\nModem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) {\n if (err) return cb(err, null);\n\n if (statusCodes[res.statusCode] !== true) {\n getCause(isStream, res, json, function (err, cause) {\n var msg = new Error(\n '(HTTP code ' + res.statusCode + ') ' +\n (statusCodes[res.statusCode] || 'unexpected') + ' - ' +\n (cause.message || cause) + ' '\n );\n msg.reason = statusCodes[res.statusCode];\n msg.statusCode = res.statusCode;\n msg.json = json;\n cb(msg, null);\n });\n } else {\n if (openStdin) {\n cb(null, new HttpDuplex(req, res));\n } else if (isStream) {\n cb(null, res);\n } else {\n cb(null, json);\n }\n }\n\n function getCause(isStream, res, json, callback) {\n var chunks = '';\n if (isStream) {\n res.on('data', function (chunk) {\n chunks += chunk;\n });\n res.on('end', function () {\n callback(null, utils.parseJSON(chunks) || chunks);\n });\n } else {\n callback(null, json);\n }\n }\n};\n\nModem.prototype.demuxStream = function (stream, stdout, stderr) {\n var nextDataType = null;\n var nextDataLength = null;\n var buffer = Buffer.from('');\n function processData(data) {\n if (data) {\n buffer = Buffer.concat([buffer, data]);\n }\n if (!nextDataType) {\n if (buffer.length >= 8) {\n var header = bufferSlice(8);\n nextDataType = header.readUInt8(0);\n nextDataLength = header.readUInt32BE(4);\n // It's possible we got a \"data\" that contains multiple messages\n // Process the next one\n processData();\n }\n } else {\n if (buffer.length >= nextDataLength) {\n var content = bufferSlice(nextDataLength);\n if (nextDataType === 1) {\n stdout.write(content);\n } else {\n stderr.write(content);\n }\n nextDataType = null;\n // It's possible we got a \"data\" that contains multiple messages\n // Process the next one\n processData();\n }\n }\n }\n\n function bufferSlice(end) {\n var out = buffer.slice(0, end);\n buffer = Buffer.from(buffer.slice(end, buffer.length));\n return out;\n }\n\n stream.on('data', processData);\n};\n\nModem.prototype.followProgress = function (stream, onFinished, onProgress) {\n var buf = '';\n var output = [];\n var finished = false;\n\n stream.on('data', onStreamEvent);\n stream.on('error', onStreamError);\n stream.on('end', onStreamEnd);\n stream.on('close', onStreamEnd);\n\n function onStreamEvent(data) {\n buf += data.toString();\n pump();\n\n function pump() {\n var pos;\n while ((pos = buf.indexOf('\\n')) >= 0) {\n if (pos == 0) {\n buf = buf.slice(1);\n continue;\n }\n processLine(buf.slice(0, pos));\n buf = buf.slice(pos + 1);\n }\n }\n\n function processLine(line) {\n if (line[line.length - 1] == '\\r') line = line.substr(0, line.length - 1);\n if (line.length > 0) {\n var obj = JSON.parse(line);\n output.push(obj);\n if (onProgress) {\n onProgress(obj);\n }\n }\n }\n };\n\n function onStreamError(err) {\n finished = true;\n stream.removeListener('data', onStreamEvent);\n stream.removeListener('error', onStreamError);\n stream.removeListener('end', onStreamEnd);\n stream.removeListener('close', onStreamEnd);\n onFinished(err, output);\n }\n\n function onStreamEnd() {\n if(!finished) onFinished(null, output);\n finished = true;\n }\n};\n\nModem.prototype.buildQuerystring = function (opts) {\n var clone = {};\n\n // serialize map values as JSON strings, else querystring truncates.\n Object.keys(opts).map(function (key, i) {\n if (opts[key]\n && typeof opts[key] === 'object'\n && !Array.isArray(opts[key])\n // Ref: https://docs.docker.com/engine/api/v1.40/#operation/ImageBuild\n // > cachefrom (string) JSON array of images used for build cache resolution.\n || key === 'cachefrom'\n ) {\n clone[key] = JSON.stringify(opts[key]);\n } else {\n clone[key] = opts[key];\n }\n });\n\n return querystring.stringify(clone);\n};\n\nmodule.exports = Modem;\n","var Client = require('ssh2').Client,\n http = require('http');\n\nmodule.exports = function(opt) {\n var conn = new Client();\n var agent = new http.Agent();\n\n agent.createConnection = function(options, fn) {\n conn.once('ready', function() {\n conn.exec('docker system dial-stdio', function(err, stream) {\n if (err) {\n conn.end();\n agent.destroy();\n return;\n }\n\n fn(null, stream);\n\n stream.once('close', () => {\n conn.end();\n agent.destroy();\n });\n });\n }).connect(opt);\n\n conn.once('end', () => agent.destroy());\n };\n\n return agent;\n};\n","// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js\n\nvar arr = [];\nvar each = arr.forEach;\nvar slice = arr.slice;\n\nmodule.exports.extend = function(obj) {\n each.call(slice.call(arguments, 1), function(source) {\n if (source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\nmodule.exports.parseJSON = function(s) {\n try {\n return JSON.parse(s);\n } catch (e) {\n return null;\n }\n};\n","var util = require('./util');\n\n/**\n * Represents a config\n * @param {Object} modem docker-modem\n * @param {String} id Config's id\n */\nvar Config = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nConfig.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nConfig.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update a config.\n *\n * @param {object} opts\n * @param {function} callback\n */\nConfig.prototype.update = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id + '/update?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Removes the config\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nConfig.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id,\n method: 'DELETE',\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Config;\n","var extend = require('./util').extend,\n Exec = require('./exec'),\n util = require('./util');\n\n/**\n * Represents a Container\n * @param {Object} modem docker-modem\n * @param {String} id Container's ID\n */\nvar Container = function(modem, id) {\n this.modem = modem;\n this.id = id;\n\n this.defaultOptions = {\n top: {},\n start: {},\n commit: {},\n stop: {},\n pause: {},\n unpause: {},\n restart: {},\n resize: {},\n attach: {},\n remove: {},\n copy: {},\n kill: {},\n exec: {},\n rename: {},\n log: {},\n stats: {},\n getArchive: {},\n infoArchive: {},\n putArchive: {},\n update: {},\n wait: {}\n };\n};\n\nContainer.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if supplied will query Docker.\n * @return {Object} ID only and only if callback isn't supplied.\n */\nContainer.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Rename\n * @param {Object} opts Rename options\n * @param {Function} callback Callback\n */\nContainer.prototype.rename = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.rename);\n\n var optsf = {\n path: '/containers/' + this.id + '/rename?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update\n * @param {Object} opts Update options\n * @param {Function} callback Callback\n */\nContainer.prototype.update = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.update);\n\n var optsf = {\n path: '/containers/' + this.id + '/update',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Top\n * @param {Object} opts like 'ps_args' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.top = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.top);\n\n var optsf = {\n path: '/containers/' + this.id + '/top?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Containers changes\n * @param {Object} Options\n * @param {Function} callback Callback\n */\nContainer.prototype.changes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/changes',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Checkpoints list\n * @param {Object} opts List checkpoints options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.listCheckpoint = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Delete checkpoint\n * @param {Object} opts Delete checkpoint options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.deleteCheckpoint = function(checkpoint, opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Create checkpoint\n * @param {Object} opts Create checkpoint options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.createCheckpoint = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n allowEmpty: true,\n statusCodes: {\n 200: true, //unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Export\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback with the octet-stream.\n */\nContainer.prototype.export = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/export',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Start\n * @param {Object} opts Container start options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.start = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.start);\n\n var optsf = {\n path: '/containers/' + this.id + '/start?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 304: 'container already started',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Pause\n * @param {Object} opts Pause options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.pause = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.pause);\n\n var optsf = {\n path: '/containers/' + this.id + '/pause',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Unpause\n * @param {Object} opts Unpause options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.unpause = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.unpause);\n\n var optsf = {\n path: '/containers/' + this.id + '/unpause',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Setup an exec call to a running container\n *\n * @param {object} opts\n * @param {function} callback\n */\nContainer.prototype.exec = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.exec);\n\n var optsf = {\n path: '/containers/' + this.id + '/exec',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 409: 'container stopped/paused',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(new Exec(self.modem, data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, new Exec(self.modem, data.Id));\n });\n }\n};\n\n/**\n * Commit\n * @param {Object} opts Commit options like 'Hostname' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.commit = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.commit);\n\n args.opts.container = this.id;\n\n var optsf = {\n path: '/commit?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Stop\n * @param {Object} opts Container stop options, like 't' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.stop = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.stop);\n\n var optsf = {\n path: '/containers/' + this.id + '/stop?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 304: 'container already stopped',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Restart\n * @param {Object} opts Container restart options, like 't' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.restart = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.restart);\n\n var optsf = {\n path: '/containers/' + this.id + '/restart?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Kill\n * @param {Object} opts Container kill options, like 'signal' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.kill = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.kill);\n\n var optsf = {\n path: '/containers/' + this.id + '/kill?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container resize\n * @param {[type]} opts Resize options. (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.resize = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.resize);\n\n var optsf = {\n path: '/containers/' + this.id + '/resize?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Attach\n * @param {Object} opts Attach options, like 'logs' (optional)\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.attach = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.attach);\n\n var optsf = {\n path: '/containers/' + this.id + '/attach?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n hijack: args.opts.hijack,\n openStdin: args.opts.stdin,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, stream) {\n if (err) {\n return reject(err);\n }\n resolve(stream);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, stream) {\n args.callback(err, stream);\n });\n }\n};\n\n/**\n * Waits for a container to end.\n * @param {[type]} opts Container wait options, like condition. (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.wait = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.wait);\n\n var optsf = {\n path: '/containers/' + this.id + '/wait?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes a container\n * @param {Object} opts Remove options, like 'force' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.remove);\n\n var optsf = {\n path: '/containers/' + this.id + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Copy (WARNING: DEPRECATED since RAPI v1.20)\n * @param {Object} opts Copy options, like 'Resource' (optional)\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.copy = function(opts, callback) {\n var self = this;\n console.log('container.copy is deprecated since Docker v1.8.x');\n var args = util.processArgs(opts, callback, this.defaultOptions.copy);\n\n var optsf = {\n path: '/containers/' + this.id + '/copy',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * getArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.getArchive = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.getArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * infoArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.infoArchive = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'HEAD',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * putArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.putArchive = function(file, opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.putArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'PUT',\n file: file,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 403: 'client error, permission denied',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nContainer.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.log);\n\n var optsf = {\n path: '/containers/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container stats\n * @param {Object} opts Stats options. (optional)\n * @param {Function} callback Callback with data\n */\nContainer.prototype.stats = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.stats);\n var isStream = true;\n if (args.opts.stream === false) {\n isStream = false;\n }\n var optsf = {\n path: '/containers/' + this.id + '/stats?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: isStream,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Container;\n","var EventEmitter = require('events').EventEmitter,\n Modem = require('docker-modem'),\n tar = require('tar-fs'),\n zlib = require('zlib'),\n Container = require('./container'),\n Image = require('./image'),\n Volume = require('./volume'),\n Network = require('./network'),\n Service = require('./service'),\n Plugin = require('./plugin'),\n Secret = require('./secret'),\n Config = require('./config'),\n Task = require('./task'),\n Node = require('./node'),\n Exec = require('./exec'),\n util = require('./util'),\n extend = util.extend;\n\nvar Docker = function(opts) {\n if (!(this instanceof Docker)) return new Docker(opts);\n\n var plibrary = global.Promise;\n\n if (opts && opts.Promise) {\n plibrary = opts.Promise;\n\n if (Object.keys(opts).length === 1) {\n opts = undefined;\n }\n }\n\n this.modem = new Modem(opts);\n this.modem.Promise = plibrary;\n};\n\n/**\n * Creates a new container\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createContainer = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/containers/create?',\n method: 'POST',\n options: opts,\n authconfig: opts.authconfig,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 406: 'impossible to attach',\n 500: 'server error'\n }\n };\n\n delete opts.authconfig;\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getContainer(data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n callback(err, self.getContainer(data.Id));\n });\n }\n};\n\n/**\n * Creates a new image\n * @param {Object} auth Authentication (optional)\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createImage = function(auth, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (!callback && !opts) {\n opts = auth;\n auth = opts.authconfig;\n }\n\n var optsf = {\n path: '/images/create?',\n method: 'POST',\n options: opts,\n authconfig: auth,\n abortSignal: opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Load image\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.loadImage = function(file, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n\n var optsf = {\n path: '/images/load?',\n method: 'POST',\n options: opts,\n file: file,\n abortSignal: opts && opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Import image from a tar archive\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.importImage = function(file, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = undefined;\n }\n\n if (!opts)\n opts = {};\n\n opts.fromSrc = '-';\n\n var optsf = {\n path: '/images/create?',\n method: 'POST',\n options: opts,\n file: file,\n abortSignal: opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Verifies auth\n * @param {Object} opts Options\n * @param {Function} callback Callback\n */\nDocker.prototype.checkAuth = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/auth',\n method: 'POST',\n options: opts,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Builds an image\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.buildImage = function(file, opts, callback) {\n var self = this;\n\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n\n function build(file) {\n var optsf = {\n path: '/build?',\n method: 'POST',\n file: file,\n options: opts,\n abortSignal: opts && opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (opts) {\n if (opts.registryconfig) {\n optsf.registryconfig = optsf.options.registryconfig;\n delete optsf.options.registryconfig;\n }\n\n //undocumented?\n if (opts.authconfig) {\n optsf.authconfig = optsf.options.authconfig;\n delete optsf.options.authconfig;\n }\n }\n\n if (callback === undefined) {\n return new self.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n self.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n }\n\n if (file && file.context) {\n var pack = tar.pack(file.context, {\n entries: file.src\n });\n return build(pack.pipe(zlib.createGzip()));\n } else {\n return build(file);\n }\n};\n\n/**\n * Fetches a Container by ID\n * @param {String} id Container's ID\n */\nDocker.prototype.getContainer = function(id) {\n return new Container(this.modem, id);\n};\n\n/**\n * Fetches an Image by name\n * @param {String} name Image's name\n */\nDocker.prototype.getImage = function(name) {\n return new Image(this.modem, name);\n};\n\n/**\n * Fetches a Volume by name\n * @param {String} name Volume's name\n */\nDocker.prototype.getVolume = function(name) {\n return new Volume(this.modem, name);\n};\n\n/**\n * Fetches a Plugin by name\n * @param {String} name Volume's name\n */\nDocker.prototype.getPlugin = function(name, remote) {\n return new Plugin(this.modem, name, remote);\n};\n\n/**\n * Fetches a Service by id\n * @param {String} id Services's id\n */\nDocker.prototype.getService = function(id) {\n return new Service(this.modem, id);\n};\n\n/**\n * Fetches a Task by id\n * @param {String} id Task's id\n */\nDocker.prototype.getTask = function(id) {\n return new Task(this.modem, id);\n};\n\n/**\n * Fetches Node by id\n * @param {String} id Node's id\n */\nDocker.prototype.getNode = function(id) {\n return new Node(this.modem, id);\n};\n\n/**\n * Fetches a Network by id\n * @param {String} id network's id\n */\nDocker.prototype.getNetwork = function(id) {\n return new Network(this.modem, id);\n};\n\n/**\n * Fetches a Secret by id\n * @param {String} id network's id\n */\nDocker.prototype.getSecret = function(id) {\n return new Secret(this.modem, id);\n};\n\n/**\n * Fetches a Config by id\n * @param {String} id network's id\n */\nDocker.prototype.getConfig = function(id) {\n return new Config(this.modem, id);\n};\n\n/**\n * Fetches an Exec instance by ID\n * @param {String} id Exec instance's ID\n */\nDocker.prototype.getExec = function(id) {\n return new Exec(this.modem, id);\n};\n\n/**\n * Lists containers\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listContainers = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Get images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.getImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/get?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Services\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listServices = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Nodes\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listNodes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such node',\n 500: 'server error',\n 503: 'node is not part of a swarm',\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Tasks\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listTasks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/tasks?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new secret\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createSecret = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n var optsf = {\n path: '/secrets/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 406: 'server error or node is not part of a swarm',\n 409: 'name conflicts with an existing object',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getSecret(data.ID));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getSecret(data.ID));\n });\n }\n};\n\n\n/**\n * Creates a new config\n * @param {Object} opts Config options\n * @param {Function} callback Callback\n */\nDocker.prototype.createConfig = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n var optsf = {\n path: '/configs/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 406: 'server error or node is not part of a swarm',\n 409: 'name conflicts with an existing object',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getConfig(data.ID));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getConfig(data.ID));\n });\n }\n};\n\n\n/**\n * Lists secrets\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listSecrets = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists configs\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listConfigs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new plugin\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createPlugin = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/plugins/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getPlugin(args.opts.name));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getPlugin(args.opts.name));\n });\n }\n};\n\n\n/**\n * Lists plugins\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listPlugins = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune builder\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneBuilder = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/build/prune',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune containers\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneContainers = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune volumes\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneVolumes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune networks\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneNetworks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Creates a new volume\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createVolume = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/volumes/create?',\n method: 'POST',\n allowEmpty: true,\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getVolume(data.Name));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getVolume(data.Name));\n });\n }\n};\n\n/**\n * Creates a new service\n * @param {Object} auth\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createService = function(auth, opts, callback) {\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (!opts && !callback) {\n opts = auth;\n }\n\n\n var self = this;\n var optsf = {\n path: '/services/create',\n method: 'POST',\n options: opts,\n authconfig: auth,\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 500: 'server error'\n }\n };\n\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getService(data.ID || data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n callback(err, self.getService(data.ID || data.Id));\n });\n }\n};\n\n/**\n * Lists volumes\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listVolumes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new network\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createNetwork = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/networks/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'driver not found',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getNetwork(data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getNetwork(data.Id));\n });\n }\n};\n\n/**\n * Lists networks\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listNetworks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Search images\n * @param {Object} opts Options\n * @param {Function} callback Callback\n */\nDocker.prototype.searchImages = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/images/search?',\n method: 'GET',\n options: opts,\n authconfig: opts.authconfig,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Info\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback with info\n */\nDocker.prototype.info = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/info',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Version\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.version = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/version',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Ping\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.ping = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/_ping',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * SystemDf \tequivalent to system/df API Engine\n *\t\tget usage data information\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.df = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/system/df',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Events\n * @param {Object} opts Events options, like 'since' (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.getEvents = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/events?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Pull is a wrapper around createImage, parsing image's tags.\n * @param {String} repoTag Repository tag\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n * @param {Object} auth Authentication (optional)\n * @return {Object} Image\n */\nDocker.prototype.pull = function(repoTag, opts, callback, auth) {\n var args = util.processArgs(opts, callback);\n\n var imageSrc = util.parseRepositoryTag(repoTag);\n args.opts.fromImage = imageSrc.repository;\n args.opts.tag = imageSrc.tag || 'latest';\n\n var argsf = [args.opts, args.callback];\n if (auth) {\n argsf = [auth, args.opts, args.callback];\n }\n return this.createImage.apply(this, argsf);\n};\n\n/**\n * Like run command from Docker's CLI\n * @param {String} image Image name to be used.\n * @param {Array} cmd Command to run in array format.\n * @param {Object} streamo Output stream\n * @param {Object} createOptions Container create options (optional)\n * @param {Object} startOptions Container start options (optional)\n * @param {Function} callback Callback\n * @return {Object} EventEmitter\n */\nDocker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) {\n if (typeof arguments[arguments.length - 1] === 'function') {\n return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback);\n } else {\n return this.runPromise(image, cmd, streamo, createOptions, startOptions);\n }\n};\n\n\nDocker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) {\n if (!callback && typeof createOptions === 'function') {\n callback = createOptions;\n createOptions = {};\n startOptions = {};\n } else if (!callback && typeof startOptions === 'function') {\n callback = startOptions;\n startOptions = {};\n }\n\n var hub = new EventEmitter();\n\n function handler(err, container) {\n if (err) return callback(err, null, container);\n\n hub.emit('container', container);\n\n container.attach({\n stream: true,\n stdout: true,\n stderr: true\n }, function handler(err, stream) {\n if (err) return callback(err, null, container);\n\n hub.emit('stream', stream);\n\n if (streamo) {\n if (streamo instanceof Array) {\n stream.on('end', function() {\n try {\n streamo[0].end();\n } catch (e) {}\n try {\n streamo[1].end();\n } catch (e) {}\n });\n container.modem.demuxStream(stream, streamo[0], streamo[1]);\n } else {\n stream.setEncoding('utf8');\n stream.pipe(streamo, {\n end: true\n });\n }\n }\n\n container.start(startOptions, function(err, data) {\n if (err) return callback(err, data, container);\n hub.emit('start', container);\n\n container.wait(function(err, data) {\n hub.emit('data', data);\n callback(err, data, container);\n });\n });\n });\n }\n\n var optsc = {\n 'Hostname': '',\n 'User': '',\n 'AttachStdin': false,\n 'AttachStdout': true,\n 'AttachStderr': true,\n 'Tty': true,\n 'OpenStdin': false,\n 'StdinOnce': false,\n 'Env': null,\n 'Cmd': cmd,\n 'Image': image,\n 'Volumes': {},\n 'VolumesFrom': []\n };\n\n extend(optsc, createOptions);\n\n this.createContainer(optsc, handler);\n\n return hub;\n};\n\nDocker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) {\n var self = this;\n\n createOptions = createOptions || {};\n startOptions = startOptions || {};\n\n var optsc = {\n 'Hostname': '',\n 'User': '',\n 'AttachStdin': false,\n 'AttachStdout': true,\n 'AttachStderr': true,\n 'Tty': true,\n 'OpenStdin': false,\n 'StdinOnce': false,\n 'Env': null,\n 'Cmd': cmd,\n 'Image': image,\n 'Volumes': {},\n 'VolumesFrom': []\n };\n\n extend(optsc, createOptions);\n\n var containero;\n\n return new this.modem.Promise(function(resolve, reject) {\n self.createContainer(optsc).then(function(container) {\n containero = container;\n return container.attach({\n stream: true,\n stdout: true,\n stderr: true\n });\n }).then(function(stream) {\n if (streamo) {\n if (streamo instanceof Array) {\n stream.on('end', function() {\n try {\n streamo[0].end();\n } catch (e) {}\n try {\n streamo[1].end();\n } catch (e) {}\n });\n containero.modem.demuxStream(stream, streamo[0], streamo[1]);\n } else {\n stream.setEncoding('utf8');\n stream.pipe(streamo, {\n end: true\n });\n }\n }\n return containero.start(startOptions);\n }).then(function(data) {\n return containero.wait();\n }).then(function(data) {\n resolve([data, containero]);\n }).catch(function(err) {\n reject(err);\n });\n });\n};\n\n/**\n * Init swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmInit = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/init',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Join swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmJoin = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/join',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Leave swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmLeave = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/leave?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 406: 'node is not part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmUpdate = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/update?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Inspect a Swarm.\n * Warning: This method is not documented in the API\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.swarmInspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 406: 'This node is not a swarm manager',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nDocker.Container = Container;\nDocker.Image = Image;\nDocker.Volume = Volume;\nDocker.Network = Network;\nDocker.Service = Service;\nDocker.Plugin = Plugin;\nDocker.Secret = Secret;\nDocker.Task = Task;\nDocker.Node = Node;\nDocker.Exec = Exec;\n\nmodule.exports = Docker;\n","var util = require('./util');\n\n/**\n * Represents an Exec\n * @param {Object} modem docker-modem\n * @param {String} id Exec's ID\n */\nvar Exec = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nExec.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Start the exec call that was setup.\n *\n * @param {object} opts\n * @param {function} callback\n */\nExec.prototype.start = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/start',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n allowEmpty: true,\n hijack: args.opts.hijack,\n openStdin: args.opts.stdin,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such exec',\n 409: 'container stopped/paused',\n 500: 'container not running'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Resize the exec call that was setup.\n *\n * @param {object} opts\n * @param {function} callback\n */\nExec.prototype.resize = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/resize?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such exec',\n 500: 'container not running'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Get low-level information about the exec call.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nExec.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/json',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such exec',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Exec;\n","var util = require('./util');\n\n/**\n * Represents an image\n * @param {Object} modem docker-modem\n * @param {String} name Image's name\n */\nvar Image = function(modem, name) {\n this.modem = modem;\n this.name = name;\n};\n\nImage.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nImage.prototype.inspect = function(callback) {\n var self = this;\n\n var opts = {\n path: '/images/' + this.name + '/json',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Distribution\n * @param {Object} opts\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nImage.prototype.distribution = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n\n var fopts = {\n path: '/distribution/' + this.name + '/json',\n method: 'GET',\n statusCodes: {\n 200: true,\n 401: 'no such image',\n 500: 'server error'\n },\n authconfig: (args.opts) ? args.opts.authconfig : undefined\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(fopts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(fopts, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * History\n * @param {Function} callback Callback\n */\nImage.prototype.history = function(callback) {\n var self = this;\n var opts = {\n path: '/images/' + this.name + '/history',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Get\n * @param {Function} callback Callback with data stream.\n */\nImage.prototype.get = function(callback) {\n var self = this;\n var opts = {\n path: '/images/' + this.name + '/get',\n method: 'GET',\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Push\n * @param {Object} opts Push options, like 'registry' (optional)\n * @param {Function} callback Callback with stream.\n * @param {Object} auth Registry authentication\n */\nImage.prototype.push = function(opts, callback, auth) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var isStream = true;\n if (args.opts.stream === false) {\n isStream = false;\n }\n var optsf = {\n path: '/images/' + this.name + '/push?',\n method: 'POST',\n options: args.opts,\n authconfig: args.opts.authconfig || auth,\n abortSignal: args.opts.abortSignal,\n isStream: isStream,\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n delete optsf.options.authconfig;\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Tag\n * @param {Object} opts Tag options, like 'repo' (optional)\n * @param {Function} callback Callback\n */\nImage.prototype.tag = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/images/' + this.name + '/tag?',\n method: 'POST',\n options: opts,\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 400: 'bad parameter',\n 404: 'no such image',\n 409: 'conflict',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Removes the image\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nImage.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/' + this.name + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Image;\n","var util = require('./util');\n\n/**\n * Represents an network\n * @param {Object} modem docker-modem\n * @param {String} id Network's id\n */\nvar Network = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nNetwork.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Id only if callback isn't specified.\n */\nNetwork.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/networks/' + this.id + '?',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such network',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the network\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such network',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Connects a container to a network\n * @param {[Object]} opts Connect options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.connect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id + '/connect',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 404: 'network or container is not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Disconnects a container from a network\n * @param {[Object]} opts Disconnect options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.disconnect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id + '/disconnect',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 404: 'network or container is not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\n\nmodule.exports = Network;\n","var util = require('./util');\n\n/**\n * Represents an Node\n * @param {Object} modem docker-modem\n * @param {String} id Node's ID\n */\nvar Node = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nNode.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for Node details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nNode.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes/' + this.id,\n method: 'GET',\n abortSignal: args.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Update a node.\n *\n * @param {object} opts\n * @param {function} callback\n */\nNode.prototype.update = function(opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n }\n\n var optsf = {\n path: '/nodes/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 406: 'node is not part of a swarm',\n 500: 'server error'\n },\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n/**\n * Remove a Node.\n * Warning: This method is not documented in the API.\n *\n * @param {object} opts\n * @param {function} callback\n */\nNode.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes/' + this.id + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Node;\n","var util = require('./util');\n\n/**\n * Represents a plugin\n * @param {Object} modem docker-modem\n * @param {String} name Plugin's name\n */\nvar Plugin = function(modem, name, remote) {\n this.modem = modem;\n this.name = name;\n this.remote = remote || name;\n};\n\nPlugin.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nPlugin.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin is not installed',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the plugin\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin is not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * get privileges\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n * @return {Object} Name only if callback isn't specified.\n */\nPlugin.prototype.privileges = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/privileges?',\n method: 'GET',\n options: {\n 'remote': this.remote\n },\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Installs a new plugin\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nPlugin.prototype.pull = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n if(args.opts._query && !args.opts._query.name) {\n args.opts._query.name = this.name;\n }\n if(args.opts._query && !args.opts._query.remote) {\n args.opts._query.remote = this.remote;\n }\n\n var optsf = {\n path: '/plugins/pull?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n options: args.opts,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Enable\n * @param {Object} opts Plugin enable options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.enable = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/enable?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Disable\n * @param {Object} opts Plugin disable options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.disable = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/disable',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Push\n * @param {Object} opts Plugin push options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.push = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/push',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * COnfigure\n * @param {Object} opts Plugin configure options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.configure = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/set',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Upgrade plugin\n *\n * @param {object} auth\n * @param {object} opts\n * @param {function} callback\n */\nPlugin.prototype.upgrade = function(auth, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n }\n\n var optsf = {\n path: '/plugins/' + this.name + '/upgrade?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n authconfig: auth,\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Plugin;\n","var util = require('./util');\n\n/**\n * Represents a secret\n * @param {Object} modem docker-modem\n * @param {String} id Secret's id\n */\nvar Secret = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nSecret.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nSecret.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'secret not found',\n 406: 'node is not part of a swarm',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update a secret.\n *\n * @param {object} opts\n * @param {function} callback\n */\nSecret.prototype.update = function(opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n }\n\n var optsf = {\n path: '/secrets/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'secret not found',\n 500: 'server error'\n },\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n/**\n * Removes the secret\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nSecret.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'secret not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Secret;\n","var util = require('./util');\n\n/**\n * Represents an Service\n * @param {Object} modem docker-modem\n * @param {String} id Service's ID\n */\nvar Service = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nService.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for service details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nService.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Delete Service\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nService.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such service',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update service\n *\n * @param {object} auth\n * @param {object} opts\n * @param {function} callback\n */\nService.prototype.update = function(auth, opts, callback) {\n var self = this;\n if (!callback) {\n var t = typeof opts;\n if(t === 'function'){\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (t === 'undefined'){\n opts = auth;\n auth = opts.authconfig || undefined;\n }\n }\n\n var optsf = {\n path: '/services/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error'\n },\n authconfig: auth,\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n\n/**\n * Service logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nService.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, {});\n\n var optsf = {\n path: '/services/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Service;\n","var util = require('./util');\n\n/**\n * Represents an Task\n * @param {Object} modem docker-modem\n * @param {String} id Task's ID\n */\nvar Task = function(modem, id) {\n this.modem = modem;\n this.id = id;\n\n this.defaultOptions = {\n log: {}\n };\n};\n\nTask.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for Task details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nTask.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/tasks/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'unknown task',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Task logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nTask.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.log);\n\n var optsf = {\n path: '/tasks/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 101: true,\n 200: true,\n 404: 'no such container',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Task;\n","// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js\n\nvar arr = [];\nvar each = arr.forEach;\nvar slice = arr.slice;\n\nmodule.exports.extend = function(obj) {\n each.call(slice.call(arguments, 1), function(source) {\n if (source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\nmodule.exports.processArgs = function(opts, callback, defaultOpts) {\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n return {\n callback: callback,\n opts: module.exports.extend({}, defaultOpts, opts)\n };\n};\n\n\n/**\n * Parse the given repo tag name (as a string) and break it out into repo/tag pair.\n * // if given the input http://localhost:8080/woot:latest\n * {\n * repository: 'http://localhost:8080/woot',\n * tag: 'latest'\n * }\n * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest'\n * @return {Object} input parsed into the repo and tag.\n */\nmodule.exports.parseRepositoryTag = function(input) {\n var separatorPos;\n var digestPos = input.indexOf('@');\n var colonPos = input.lastIndexOf(':');\n // @ symbol is more important\n if (digestPos >= 0) {\n separatorPos = digestPos;\n } else if (colonPos >= 0) {\n separatorPos = colonPos;\n } else {\n // no colon nor @\n return {\n repository: input\n };\n }\n\n // last colon is either the tag (or part of a port designation)\n var tag = input.slice(separatorPos + 1);\n\n // if it contains a / its not a tag and is part of the url\n if (tag.indexOf('/') === -1) {\n return {\n repository: input.slice(0, separatorPos),\n tag: tag\n };\n }\n\n return {\n repository: input\n };\n};\n","var util = require('./util');\n\n/**\n * Represents a volume\n * @param {Object} modem docker-modem\n * @param {String} name Volume's name\n */\nvar Volume = function(modem, name) {\n this.modem = modem;\n this.name = name;\n};\n\nVolume.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nVolume.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/' + this.name,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such volume',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the volume\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nVolume.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/' + this.name,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 204: true,\n 404: 'no such volume',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Volume;\n","var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n","module.exports = require('fs').constants || require('constants')\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","var path = require('path');\nvar fs = require('fs');\nvar _0777 = parseInt('0777', 8);\n\nmodule.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;\n\nfunction mkdirP (p, opts, f, made) {\n if (typeof opts === 'function') {\n f = opts;\n opts = {};\n }\n else if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n \n var mode = opts.mode;\n var xfs = opts.fs || fs;\n \n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made) made = null;\n \n var cb = f || function () {};\n p = path.resolve(p);\n \n xfs.mkdir(p, mode, function (er) {\n if (!er) {\n made = made || p;\n return cb(null, made);\n }\n switch (er.code) {\n case 'ENOENT':\n mkdirP(path.dirname(p), opts, function (er, made) {\n if (er) cb(er, made);\n else mkdirP(p, opts, cb, made);\n });\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n xfs.stat(p, function (er2, stat) {\n // if the stat fails, then that's super weird.\n // let the original error be the failure reason.\n if (er2 || !stat.isDirectory()) cb(er, made)\n else cb(null, made);\n });\n break;\n }\n });\n}\n\nmkdirP.sync = function sync (p, opts, made) {\n if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n \n var mode = opts.mode;\n var xfs = opts.fs || fs;\n \n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made) made = null;\n\n p = path.resolve(p);\n\n try {\n xfs.mkdirSync(p, mode);\n made = made || p;\n }\n catch (err0) {\n switch (err0.code) {\n case 'ENOENT' :\n made = sync(path.dirname(p), opts, made);\n sync(p, opts, made);\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n var stat;\n try {\n stat = xfs.statSync(p);\n }\n catch (err1) {\n throw err0;\n }\n if (!stat.isDirectory()) throw err0;\n break;\n }\n }\n\n return made;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n","var once = require('once')\nvar eos = require('end-of-stream')\nvar fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes\n\nvar noop = function () {}\nvar ancient = /^v?\\.0/.test(process.version)\n\nvar isFn = function (fn) {\n return typeof fn === 'function'\n}\n\nvar isFS = function (stream) {\n if (!ancient) return false // newer node version do not need to care about fs is a special way\n if (!fs) return false // browser\n return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)\n}\n\nvar isRequest = function (stream) {\n return stream.setHeader && isFn(stream.abort)\n}\n\nvar destroyer = function (stream, reading, writing, callback) {\n callback = once(callback)\n\n var closed = false\n stream.on('close', function () {\n closed = true\n })\n\n eos(stream, {readable: reading, writable: writing}, function (err) {\n if (err) return callback(err)\n closed = true\n callback()\n })\n\n var destroyed = false\n return function (err) {\n if (closed) return\n if (destroyed) return\n destroyed = true\n\n if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks\n if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want\n\n if (isFn(stream.destroy)) return stream.destroy()\n\n callback(err || new Error('stream was destroyed'))\n }\n}\n\nvar call = function (fn) {\n fn()\n}\n\nvar pipe = function (from, to) {\n return from.pipe(to)\n}\n\nvar pump = function () {\n var streams = Array.prototype.slice.call(arguments)\n var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop\n\n if (Array.isArray(streams[0])) streams = streams[0]\n if (streams.length < 2) throw new Error('pump requires two streams per minimum')\n\n var error\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1\n var writing = i > 0\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err\n if (err) destroys.forEach(call)\n if (reading) return\n destroys.forEach(call)\n callback(error)\n })\n })\n\n return streams.reduce(pipe)\n}\n\nmodule.exports = pump\n","'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};","'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;","'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();","'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;","'use strict';\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;\n\nfunction from(Readable, iterable, opts) {\n var iterator;\n\n if (iterable && typeof iterable.next === 'function') {\n iterator = iterable;\n } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);\n\n var readable = new Readable(_objectSpread({\n objectMode: true\n }, opts)); // Reading boolean to protect against _read\n // being called before last iteration completion.\n\n var reading = false;\n\n readable._read = function () {\n if (!reading) {\n reading = true;\n next();\n }\n };\n\n function next() {\n return _next2.apply(this, arguments);\n }\n\n function _next2() {\n _next2 = _asyncToGenerator(function* () {\n try {\n var _ref = yield iterator.next(),\n value = _ref.value,\n done = _ref.done;\n\n if (done) {\n readable.push(null);\n } else if (readable.push((yield value))) {\n next();\n } else {\n reading = false;\n }\n } catch (err) {\n readable.destroy(err);\n }\n });\n return _next2.apply(this, arguments);\n }\n\n return readable;\n}\n\nmodule.exports = from;","// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\n\n var error;\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1;\n var writing = i > 0;\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err;\n if (err) destroys.forEach(call);\n if (reading) return;\n destroys.forEach(call);\n callback(error);\n });\n });\n return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;","'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};","module.exports = require('stream');\n","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n","/* eslint-disable node/no-deprecated-api */\n\n'use strict'\n\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\nvar safer = {}\n\nvar key\n\nfor (key in buffer) {\n if (!buffer.hasOwnProperty(key)) continue\n if (key === 'SlowBuffer' || key === 'Buffer') continue\n safer[key] = buffer[key]\n}\n\nvar Safer = safer.Buffer = {}\nfor (key in Buffer) {\n if (!Buffer.hasOwnProperty(key)) continue\n if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue\n Safer[key] = Buffer[key]\n}\n\nsafer.Buffer.prototype = Buffer.prototype\n\nif (!Safer.from || Safer.from === Uint8Array.from) {\n Safer.from = function (value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('The \"value\" argument must not be of type number. Received type ' + typeof value)\n }\n if (value && typeof value.length === 'undefined') {\n throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)\n }\n return Buffer(value, encodingOrOffset, length)\n }\n}\n\nif (!Safer.alloc) {\n Safer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('The \"size\" argument must be of type number. Received type ' + typeof size)\n }\n if (size < 0 || size >= 2 * (1 << 30)) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n var buf = Buffer(size)\n if (!fill || fill.length === 0) {\n buf.fill(0)\n } else if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n return buf\n }\n}\n\nif (!safer.kStringMaxLength) {\n try {\n safer.kStringMaxLength = process.binding('buffer').kStringMaxLength\n } catch (e) {\n // we can't determine kStringMaxLength in environments where process.binding\n // is unsupported, so let's not set it\n }\n}\n\nif (!safer.constants) {\n safer.constants = {\n MAX_LENGTH: safer.kMaxLength\n }\n if (safer.kStringMaxLength) {\n safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength\n }\n}\n\nmodule.exports = safer\n","var fs = require('fs');\n\nmodule.exports = function (filepath, split, encoding) {\n split = typeof split !== 'undefined' ? split : \"\\n\";\n encoding = typeof encoding !== 'undefined' ? encoding : \"utf8\";\n\n var ca = [];\n var chain = fs.readFileSync(filepath, encoding);\n if(chain.indexOf(\"-END CERTIFICATE-\") < 0 || chain.indexOf(\"-BEGIN CERTIFICATE-\") < 0){\n throw Error(\"File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'\");\n }\n chain = chain.split(split);\n var cert = [];\n var _i, _len;\n for (_i = 0, _len = chain.length; _i < _len; _i++) {\n var line = chain[_i];\n if (!(line.length !== 0)) {\n continue;\n }\n cert.push(line);\n if (line.match(/-END CERTIFICATE-/)) {\n ca.push(cert.join(split));\n cert = [];\n }\n }\n return ca;\n}\n","'use strict';\n\nconst {\n Duplex: DuplexStream,\n Readable: ReadableStream,\n Writable: WritableStream,\n} = require('stream');\n\nconst {\n CHANNEL_EXTENDED_DATATYPE: { STDERR },\n} = require('./protocol/constants.js');\nconst { bufferSlice } = require('./protocol/utils.js');\n\nconst PACKET_SIZE = 32 * 1024;\nconst MAX_WINDOW = 2 * 1024 * 1024;\nconst WINDOW_THRESHOLD = MAX_WINDOW / 2;\n\nclass ClientStderr extends ReadableStream {\n constructor(channel, streamOpts) {\n super(streamOpts);\n\n this._channel = channel;\n }\n _read(n) {\n if (this._channel._waitChanDrain) {\n this._channel._waitChanDrain = false;\n if (this._channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(this._channel);\n }\n }\n}\n\nclass ServerStderr extends WritableStream {\n constructor(channel) {\n super({ highWaterMark: MAX_WINDOW });\n\n this._channel = channel;\n }\n\n _write(data, encoding, cb) {\n const channel = this._channel;\n const protocol = channel._client._protocol;\n const outgoing = channel.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelExtData(id, data, STDERR);\n else\n protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR);\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n channel._waitWindow = true;\n if (p > 0)\n channel._chunkErr = bufferSlice(data, p, len);\n else\n channel._chunkErr = data;\n channel._chunkcbErr = cb;\n return;\n }\n\n cb();\n }\n}\n\nclass Channel extends DuplexStream {\n constructor(client, info, opts) {\n const streamOpts = {\n highWaterMark: MAX_WINDOW,\n allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)),\n emitClose: false,\n };\n super(streamOpts);\n this.allowHalfOpen = streamOpts.allowHalfOpen;\n\n const server = !!(opts && opts.server);\n\n this.server = server;\n this.type = info.type;\n this.subtype = undefined;\n\n /*\n incoming and outgoing contain these properties:\n {\n id: undefined,\n window: undefined,\n packetSize: undefined,\n state: 'closed'\n }\n */\n this.incoming = info.incoming;\n this.outgoing = info.outgoing;\n this._callbacks = [];\n\n this._client = client;\n this._hasX11 = false;\n this._exit = {\n code: undefined,\n signal: undefined,\n dump: undefined,\n desc: undefined,\n };\n\n this.stdin = this.stdout = this;\n\n if (server)\n this.stderr = new ServerStderr(this);\n else\n this.stderr = new ClientStderr(this, streamOpts);\n\n // Outgoing data\n this._waitWindow = false; // SSH-level backpressure\n\n // Incoming data\n this._waitChanDrain = false; // Channel Readable side backpressure\n\n this._chunk = undefined;\n this._chunkcb = undefined;\n this._chunkErr = undefined;\n this._chunkcbErr = undefined;\n\n this.on('finish', onFinish)\n .on('prefinish', onFinish); // For node v0.11+\n\n this.on('end', onEnd).on('close', onEnd);\n }\n\n _read(n) {\n if (this._waitChanDrain) {\n this._waitChanDrain = false;\n if (this.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(this);\n }\n }\n\n _write(data, encoding, cb) {\n const protocol = this._client._protocol;\n const outgoing = this.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelData(id, data);\n else\n protocol.channelData(id, bufferSlice(data, p, p + sliceLen));\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n this._waitWindow = true;\n if (p > 0)\n this._chunk = bufferSlice(data, p, len);\n else\n this._chunk = data;\n this._chunkcb = cb;\n return;\n }\n\n cb();\n }\n\n eof() {\n if (this.outgoing.state === 'open') {\n this.outgoing.state = 'eof';\n this._client._protocol.channelEOF(this.outgoing.id);\n }\n }\n\n close() {\n if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {\n this.outgoing.state = 'closing';\n this._client._protocol.channelClose(this.outgoing.id);\n }\n }\n\n destroy() {\n this.end();\n this.close();\n return this;\n }\n\n // Session type-specific methods =============================================\n setWindow(rows, cols, height, width) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && (this.subtype === 'shell' || this.subtype === 'exec')\n && this.writable\n && this.outgoing.state === 'open') {\n this._client._protocol.windowChange(this.outgoing.id,\n rows,\n cols,\n height,\n width);\n }\n }\n\n signal(signalName) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open') {\n this._client._protocol.signal(this.outgoing.id, signalName);\n }\n }\n\n exit(statusOrSignal, coreDumped, msg) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open') {\n if (typeof statusOrSignal === 'number') {\n this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal);\n } else {\n this._client._protocol.exitSignal(this.outgoing.id,\n statusOrSignal,\n coreDumped,\n msg);\n }\n }\n }\n\n}\n\nfunction onFinish() {\n this.eof();\n if (this.server || !this.allowHalfOpen)\n this.close();\n this.writable = false;\n}\n\nfunction onEnd() {\n this.readable = false;\n}\n\nfunction windowAdjust(self) {\n if (self.outgoing.state === 'closed')\n return;\n const amt = MAX_WINDOW - self.incoming.window;\n if (amt <= 0)\n return;\n self.incoming.window += amt;\n self._client._protocol.channelWindowAdjust(self.outgoing.id, amt);\n}\n\nmodule.exports = {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n};\n",null,"// TODO:\n// * add `.connected` or similar property to allow immediate connection\n// status checking\n// * add/improve debug output during user authentication phase\n'use strict';\n\nconst {\n createHash,\n getHashes,\n randomFillSync,\n} = require('crypto');\nconst { Socket } = require('net');\nconst { lookup: dnsLookup } = require('dns');\nconst EventEmitter = require('events');\nconst HASHES = getHashes();\n\nconst {\n COMPAT,\n CHANNEL_EXTENDED_DATATYPE: { STDERR },\n CHANNEL_OPEN_FAILURE,\n DEFAULT_CIPHER,\n DEFAULT_COMPRESSION,\n DEFAULT_KEX,\n DEFAULT_MAC,\n DEFAULT_SERVER_HOST_KEY,\n DISCONNECT_REASON,\n DISCONNECT_REASON_BY_VALUE,\n SUPPORTED_CIPHER,\n SUPPORTED_COMPRESSION,\n SUPPORTED_KEX,\n SUPPORTED_MAC,\n SUPPORTED_SERVER_HOST_KEY,\n} = require('./protocol/constants.js');\nconst { init: cryptoInit } = require('./protocol/crypto.js');\nconst Protocol = require('./protocol/Protocol.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst { SFTP } = require('./protocol/SFTP.js');\nconst {\n bufferCopy,\n makeBufferParser,\n makeError,\n readUInt32BE,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./protocol/utils.js');\n\nconst { AgentContext, createAgent, isAgent } = require('./agent.js');\nconst {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n} = require('./Channel.js');\nconst {\n ChannelManager,\n generateAlgorithmList,\n isWritable,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n} = require('./utils.js');\n\nconst bufferParser = makeBufferParser();\nconst sigParser = makeBufferParser();\nconst RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\\d)|(?:\\d{2,})/;\nconst noop = (err) => {};\n\nclass Client extends EventEmitter {\n constructor() {\n super();\n\n this.config = {\n host: undefined,\n port: undefined,\n localAddress: undefined,\n localPort: undefined,\n forceIPv4: undefined,\n forceIPv6: undefined,\n keepaliveCountMax: undefined,\n keepaliveInterval: undefined,\n readyTimeout: undefined,\n ident: undefined,\n\n username: undefined,\n password: undefined,\n privateKey: undefined,\n tryKeyboard: undefined,\n agent: undefined,\n allowAgentFwd: undefined,\n authHandler: undefined,\n\n hostHashAlgo: undefined,\n hostHashCb: undefined,\n strictVendor: undefined,\n debug: undefined\n };\n\n this._agent = undefined;\n this._readyTimeout = undefined;\n this._chanMgr = undefined;\n this._callbacks = undefined;\n this._forwarding = undefined;\n this._forwardingUnix = undefined;\n this._acceptX11 = undefined;\n this._agentFwdEnabled = undefined;\n this._remoteVer = undefined;\n\n this._protocol = undefined;\n this._sock = undefined;\n this._resetKA = undefined;\n }\n\n connect(cfg) {\n if (this._sock && isWritable(this._sock)) {\n this.once('close', () => {\n this.connect(cfg);\n });\n this.end();\n return this;\n }\n\n this.config.host = cfg.hostname || cfg.host || 'localhost';\n this.config.port = cfg.port || 22;\n this.config.localAddress = (typeof cfg.localAddress === 'string'\n ? cfg.localAddress\n : undefined);\n this.config.localPort = (typeof cfg.localPort === 'string'\n || typeof cfg.localPort === 'number'\n ? cfg.localPort\n : undefined);\n this.config.forceIPv4 = cfg.forceIPv4 || false;\n this.config.forceIPv6 = cfg.forceIPv6 || false;\n this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number'\n && cfg.keepaliveCountMax >= 0\n ? cfg.keepaliveCountMax\n : 3);\n this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number'\n && cfg.keepaliveInterval > 0\n ? cfg.keepaliveInterval\n : 0);\n this.config.readyTimeout = (typeof cfg.readyTimeout === 'number'\n && cfg.readyTimeout >= 0\n ? cfg.readyTimeout\n : 20000);\n this.config.ident = (typeof cfg.ident === 'string'\n || Buffer.isBuffer(cfg.ident)\n ? cfg.ident\n : undefined);\n\n const algorithms = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: [],\n },\n sc: undefined,\n };\n let allOfferDefaults = true;\n if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) {\n algorithms.kex = generateAlgorithmList(cfg.algorithms.kex,\n DEFAULT_KEX,\n SUPPORTED_KEX);\n if (algorithms.kex !== DEFAULT_KEX)\n allOfferDefaults = false;\n\n algorithms.serverHostKey =\n generateAlgorithmList(cfg.algorithms.serverHostKey,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY);\n if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY)\n allOfferDefaults = false;\n\n algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER);\n if (algorithms.cs.cipher !== DEFAULT_CIPHER)\n allOfferDefaults = false;\n\n algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac,\n DEFAULT_MAC,\n SUPPORTED_MAC);\n if (algorithms.cs.mac !== DEFAULT_MAC)\n allOfferDefaults = false;\n\n algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION);\n if (algorithms.cs.compress !== DEFAULT_COMPRESSION)\n allOfferDefaults = false;\n\n if (!allOfferDefaults)\n algorithms.sc = algorithms.cs;\n }\n\n if (typeof cfg.username === 'string')\n this.config.username = cfg.username;\n else if (typeof cfg.user === 'string')\n this.config.username = cfg.user;\n else\n throw new Error('Invalid username');\n\n this.config.password = (typeof cfg.password === 'string'\n ? cfg.password\n : undefined);\n this.config.privateKey = (typeof cfg.privateKey === 'string'\n || Buffer.isBuffer(cfg.privateKey)\n ? cfg.privateKey\n : undefined);\n this.config.localHostname = (typeof cfg.localHostname === 'string'\n ? cfg.localHostname\n : undefined);\n this.config.localUsername = (typeof cfg.localUsername === 'string'\n ? cfg.localUsername\n : undefined);\n this.config.tryKeyboard = (cfg.tryKeyboard === true);\n if (typeof cfg.agent === 'string' && cfg.agent.length)\n this.config.agent = createAgent(cfg.agent);\n else if (isAgent(cfg.agent))\n this.config.agent = cfg.agent;\n else\n this.config.agent = undefined;\n this.config.allowAgentFwd = (cfg.agentForward === true\n && this.config.agent !== undefined);\n let authHandler = this.config.authHandler = (\n typeof cfg.authHandler === 'function'\n || Array.isArray(cfg.authHandler)\n ? cfg.authHandler\n : undefined\n );\n\n this.config.strictVendor = (typeof cfg.strictVendor === 'boolean'\n ? cfg.strictVendor\n : true);\n\n const debug = this.config.debug = (typeof cfg.debug === 'function'\n ? cfg.debug\n : undefined);\n\n if (cfg.agentForward === true && !this.config.allowAgentFwd) {\n throw new Error(\n 'You must set a valid agent path to allow agent forwarding'\n );\n }\n\n let callbacks = this._callbacks = [];\n this._chanMgr = new ChannelManager(this);\n this._forwarding = {};\n this._forwardingUnix = {};\n this._acceptX11 = 0;\n this._agentFwdEnabled = false;\n this._agent = (this.config.agent ? this.config.agent : undefined);\n this._remoteVer = undefined;\n let privateKey;\n\n if (this.config.privateKey) {\n privateKey = parseKey(this.config.privateKey, cfg.passphrase);\n if (privateKey instanceof Error)\n throw new Error(`Cannot parse privateKey: ${privateKey.message}`);\n if (Array.isArray(privateKey)) {\n // OpenSSH's newer format only stores 1 key for now\n privateKey = privateKey[0];\n }\n if (privateKey.getPrivatePEM() === null) {\n throw new Error(\n 'privateKey value does not contain a (valid) private key'\n );\n }\n }\n\n let hostVerifier;\n if (typeof cfg.hostVerifier === 'function') {\n const hashCb = cfg.hostVerifier;\n let hasher;\n if (HASHES.indexOf(cfg.hostHash) !== -1) {\n // Default to old behavior of hashing on user's behalf\n hasher = createHash(cfg.hostHash);\n }\n hostVerifier = (key, verify) => {\n if (hasher) {\n hasher.update(key);\n key = hasher.digest('hex');\n }\n const ret = hashCb(key, verify);\n if (ret !== undefined)\n verify(ret);\n };\n }\n\n const sock = this._sock = (cfg.sock || new Socket());\n let ready = false;\n let sawHeader = false;\n if (this._protocol)\n this._protocol.cleanup();\n const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {\n debug(`Debug output from server: ${JSON.stringify(msg)}`);\n });\n const proto = this._protocol = new Protocol({\n ident: this.config.ident,\n offer: (allOfferDefaults ? undefined : algorithms),\n onWrite: (data) => {\n if (isWritable(sock))\n sock.write(data);\n },\n onError: (err) => {\n if (err.level === 'handshake')\n clearTimeout(this._readyTimeout);\n if (!proto._destruct)\n sock.removeAllListeners('data');\n this.emit('error', err);\n try {\n sock.end();\n } catch {}\n },\n onHeader: (header) => {\n sawHeader = true;\n this._remoteVer = header.versions.software;\n if (header.greeting)\n this.emit('greeting', header.greeting);\n },\n onHandshakeComplete: (negotiated) => {\n this.emit('handshake', negotiated);\n if (!ready) {\n ready = true;\n proto.service('ssh-userauth');\n }\n },\n debug,\n hostVerifier,\n messageHandlers: {\n DEBUG: DEBUG_HANDLER,\n DISCONNECT: (p, reason, desc) => {\n if (reason !== DISCONNECT_REASON.BY_APPLICATION) {\n if (!desc) {\n desc = DISCONNECT_REASON_BY_VALUE[reason];\n if (desc === undefined)\n desc = `Unexpected disconnection reason: ${reason}`;\n }\n const err = new Error(desc);\n err.code = reason;\n this.emit('error', err);\n }\n sock.end();\n },\n SERVICE_ACCEPT: (p, name) => {\n if (name === 'ssh-userauth')\n tryNextAuth();\n },\n USERAUTH_BANNER: (p, msg) => {\n this.emit('banner', msg);\n },\n USERAUTH_SUCCESS: (p) => {\n // Start keepalive mechanism\n resetKA();\n\n clearTimeout(this._readyTimeout);\n\n this.emit('ready');\n },\n USERAUTH_FAILURE: (p, authMethods, partialSuccess) => {\n if (curAuth.type === 'agent') {\n const pos = curAuth.agentCtx.pos();\n debug && debug(`Client: Agent key #${pos + 1} failed`);\n return tryNextAgentKey();\n }\n\n debug && debug(`Client: ${curAuth.type} auth failed`);\n\n curPartial = partialSuccess;\n curAuthsLeft = authMethods;\n tryNextAuth();\n },\n USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => {\n if (curAuth.type === 'password') {\n // TODO: support a `changePrompt()` on `curAuth` that defaults to\n // emitting 'change password' as before\n this.emit('change password', prompt, (newPassword) => {\n proto.authPassword(\n this.config.username,\n this.config.password,\n newPassword\n );\n });\n }\n },\n USERAUTH_PK_OK: (p) => {\n if (curAuth.type === 'agent') {\n const key = curAuth.agentCtx.currentKey();\n proto.authPK(curAuth.username, key, (buf, cb) => {\n curAuth.agentCtx.sign(key, buf, {}, (err, signed) => {\n if (err) {\n err.level = 'agent';\n this.emit('error', err);\n } else {\n return cb(signed);\n }\n\n tryNextAgentKey();\n });\n });\n } else if (curAuth.type === 'publickey') {\n proto.authPK(curAuth.username, curAuth.key, (buf, cb) => {\n const signature = curAuth.key.sign(buf);\n if (signature instanceof Error) {\n signature.message =\n `Error signing data with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n cb(signature);\n });\n }\n },\n USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => {\n if (curAuth.type === 'keyboard-interactive') {\n const nprompts = (Array.isArray(prompts) ? prompts.length : 0);\n if (nprompts === 0) {\n debug && debug(\n 'Client: Sending automatic USERAUTH_INFO_RESPONSE'\n );\n proto.authInfoRes();\n return;\n }\n // We sent a keyboard-interactive user authentication request and\n // now the server is sending us the prompts we need to present to\n // the user\n curAuth.prompt(\n name,\n instructions,\n '',\n prompts,\n (answers) => {\n proto.authInfoRes(answers);\n }\n );\n }\n },\n REQUEST_SUCCESS: (p, data) => {\n if (callbacks.length)\n callbacks.shift()(false, data);\n },\n REQUEST_FAILURE: (p) => {\n if (callbacks.length)\n callbacks.shift()(true);\n },\n GLOBAL_REQUEST: (p, name, wantReply, data) => {\n switch (name) {\n case 'hostkeys-00@openssh.com':\n // Automatically verify keys before passing to end user\n hostKeysProve(this, data, (err, keys) => {\n if (err)\n return;\n this.emit('hostkeys', keys);\n });\n if (wantReply)\n proto.requestSuccess();\n break;\n default:\n // Auto-reject all other global requests, this can be especially\n // useful if the server is sending us dummy keepalive global\n // requests\n if (wantReply)\n proto.requestFailure();\n }\n },\n CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from server, typically a forwarded TCP or\n // X11 connection\n onCHANNEL_OPEN(this, info);\n },\n CHANNEL_OPEN_CONFIRMATION: (p, info) => {\n const channel = this._chanMgr.get(info.recipient);\n if (typeof channel !== 'function')\n return;\n\n const isSFTP = (channel.type === 'sftp');\n const type = (isSFTP ? 'session' : channel.type);\n const chanInfo = {\n type,\n incoming: {\n id: info.recipient,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const instance = (\n isSFTP\n ? new SFTP(this, chanInfo, { debug })\n : new Channel(this, chanInfo)\n );\n this._chanMgr.update(info.recipient, instance);\n channel(undefined, instance);\n },\n CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },\n CHANNEL_DATA: (p, recipient, data) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n if (type !== STDERR)\n return;\n\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (!channel.stderr.push(data)) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },\n CHANNEL_SUCCESS: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n this._resetKA();\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(false);\n },\n CHANNEL_FAILURE: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n this._resetKA();\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },\n CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n const exit = channel._exit;\n if (exit.code !== undefined)\n return;\n switch (type) {\n case 'exit-status':\n channel.emit('exit', exit.code = data);\n return;\n case 'exit-signal':\n channel.emit('exit',\n exit.code = null,\n exit.signal = `SIG${data.signal}`,\n exit.dump = data.coreDumped,\n exit.desc = data.errorMessage);\n return;\n }\n\n // Keepalive request? OpenSSH will send one as a channel request if\n // there is a channel open\n\n if (wantReply)\n p.channelFailure(channel.outgoing.id);\n },\n CHANNEL_EOF: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.incoming.state !== 'open')\n return;\n channel.incoming.state = 'eof';\n\n if (channel.readable)\n channel.push(null);\n if (channel.stderr.readable)\n channel.stderr.push(null);\n },\n CHANNEL_CLOSE: (p, recipient) => {\n onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient));\n },\n },\n });\n\n sock.pause();\n\n // TODO: check keepalive implementation\n // Keepalive-related\n const kainterval = this.config.keepaliveInterval;\n const kacountmax = this.config.keepaliveCountMax;\n let kacount = 0;\n let katimer;\n const sendKA = () => {\n if (++kacount > kacountmax) {\n clearInterval(katimer);\n if (sock.readable) {\n const err = new Error('Keepalive timeout');\n err.level = 'client-timeout';\n this.emit('error', err);\n sock.destroy();\n }\n return;\n }\n if (isWritable(sock)) {\n // Append dummy callback to keep correct callback order\n callbacks.push(resetKA);\n proto.ping();\n } else {\n clearInterval(katimer);\n }\n };\n function resetKA() {\n if (kainterval > 0) {\n kacount = 0;\n clearInterval(katimer);\n if (isWritable(sock))\n katimer = setInterval(sendKA, kainterval);\n }\n }\n this._resetKA = resetKA;\n\n const onDone = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n if (wasConnected && !sawHeader) {\n const err =\n makeError('Connection lost before handshake', 'protocol', true);\n this.emit('error', err);\n }\n };\n })();\n const onConnect = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n\n wasConnected = true;\n debug && debug('Socket connected');\n this.emit('connect');\n\n cryptoInit.then(() => {\n proto.start();\n sock.on('data', (data) => {\n try {\n proto.parse(data, 0, data.length);\n } catch (ex) {\n this.emit('error', ex);\n try {\n if (isWritable(sock))\n sock.end();\n } catch {}\n }\n });\n\n // Drain stderr if we are connection hopping using an exec stream\n if (sock.stderr && typeof sock.stderr.resume === 'function')\n sock.stderr.resume();\n\n sock.resume();\n }).catch((err) => {\n this.emit('error', err);\n try {\n if (isWritable(sock))\n sock.end();\n } catch {}\n });\n };\n })();\n let wasConnected = false;\n sock.on('connect', onConnect)\n .on('timeout', () => {\n this.emit('timeout');\n }).on('error', (err) => {\n debug && debug(`Socket error: ${err.message}`);\n clearTimeout(this._readyTimeout);\n err.level = 'client-socket';\n this.emit('error', err);\n }).on('end', () => {\n debug && debug('Socket ended');\n onDone();\n proto.cleanup();\n clearTimeout(this._readyTimeout);\n clearInterval(katimer);\n this.emit('end');\n }).on('close', () => {\n debug && debug('Socket closed');\n onDone();\n proto.cleanup();\n clearTimeout(this._readyTimeout);\n clearInterval(katimer);\n this.emit('close');\n\n // Notify outstanding channel requests of disconnection ...\n const callbacks_ = callbacks;\n callbacks = this._callbacks = [];\n const err = new Error('No response from server');\n for (let i = 0; i < callbacks_.length; ++i)\n callbacks_[i](err);\n\n // Simulate error for any channels waiting to be opened\n this._chanMgr.cleanup(err);\n });\n\n // Begin authentication handling ===========================================\n let curAuth;\n let curPartial = null;\n let curAuthsLeft = null;\n const authsAllowed = ['none'];\n if (this.config.password !== undefined)\n authsAllowed.push('password');\n if (privateKey !== undefined)\n authsAllowed.push('publickey');\n if (this._agent !== undefined)\n authsAllowed.push('agent');\n if (this.config.tryKeyboard)\n authsAllowed.push('keyboard-interactive');\n if (privateKey !== undefined\n && this.config.localHostname !== undefined\n && this.config.localUsername !== undefined) {\n authsAllowed.push('hostbased');\n }\n\n if (Array.isArray(authHandler))\n authHandler = makeSimpleAuthHandler(authHandler);\n else if (typeof authHandler !== 'function')\n authHandler = makeSimpleAuthHandler(authsAllowed);\n\n let hasSentAuth = false;\n const doNextAuth = (nextAuth) => {\n if (hasSentAuth)\n return;\n hasSentAuth = true;\n\n if (nextAuth === false) {\n const err = new Error('All configured authentication methods failed');\n err.level = 'client-authentication';\n this.emit('error', err);\n this.end();\n return;\n }\n\n if (typeof nextAuth === 'string') {\n // Remain backwards compatible with original `authHandler()` usage,\n // which only supported passing names of next method to try using data\n // from the `connect()` config object\n\n const type = nextAuth;\n if (authsAllowed.indexOf(type) === -1)\n return skipAuth(`Authentication method not allowed: ${type}`);\n\n const username = this.config.username;\n switch (type) {\n case 'password':\n nextAuth = { type, username, password: this.config.password };\n break;\n case 'publickey':\n nextAuth = { type, username, key: privateKey };\n break;\n case 'hostbased':\n nextAuth = {\n type,\n username,\n key: privateKey,\n localHostname: this.config.localHostname,\n localUsername: this.config.localUsername,\n };\n break;\n case 'agent':\n nextAuth = {\n type,\n username,\n agentCtx: new AgentContext(this._agent),\n };\n break;\n case 'keyboard-interactive':\n nextAuth = {\n type,\n username,\n prompt: (...args) => this.emit('keyboard-interactive', ...args),\n };\n break;\n case 'none':\n nextAuth = { type, username };\n break;\n default:\n return skipAuth(\n `Skipping unsupported authentication method: ${nextAuth}`\n );\n }\n } else if (typeof nextAuth !== 'object' || nextAuth === null) {\n return skipAuth(\n `Skipping invalid authentication attempt: ${nextAuth}`\n );\n } else {\n const username = nextAuth.username;\n if (typeof username !== 'string') {\n return skipAuth(\n `Skipping invalid authentication attempt: ${nextAuth}`\n );\n }\n const type = nextAuth.type;\n switch (type) {\n case 'password': {\n const { password } = nextAuth;\n if (typeof password !== 'string' && !Buffer.isBuffer(password))\n return skipAuth('Skipping invalid password auth attempt');\n nextAuth = { type, username, password };\n break;\n }\n case 'publickey': {\n const key = parseKey(nextAuth.key, nextAuth.passphrase);\n if (key instanceof Error)\n return skipAuth('Skipping invalid key auth attempt');\n if (!key.isPrivateKey())\n return skipAuth('Skipping non-private key');\n nextAuth = { type, username, key };\n break;\n }\n case 'hostbased': {\n const { localHostname, localUsername } = nextAuth;\n const key = parseKey(nextAuth.key, nextAuth.passphrase);\n if (key instanceof Error\n || typeof localHostname !== 'string'\n || typeof localUsername !== 'string') {\n return skipAuth('Skipping invalid hostbased auth attempt');\n }\n if (!key.isPrivateKey())\n return skipAuth('Skipping non-private key');\n nextAuth = { type, username, key, localHostname, localUsername };\n break;\n }\n case 'agent': {\n let agent = nextAuth.agent;\n if (typeof agent === 'string' && agent.length) {\n agent = createAgent(agent);\n } else if (!isAgent(agent)) {\n return skipAuth(\n `Skipping invalid agent: ${nextAuth.agent}`\n );\n }\n nextAuth = { type, username, agentCtx: new AgentContext(agent) };\n break;\n }\n case 'keyboard-interactive': {\n const { prompt } = nextAuth;\n if (typeof prompt !== 'function') {\n return skipAuth(\n 'Skipping invalid keyboard-interactive auth attempt'\n );\n }\n nextAuth = { type, username, prompt };\n break;\n }\n case 'none':\n nextAuth = { type, username };\n break;\n default:\n return skipAuth(\n `Skipping unsupported authentication method: ${nextAuth}`\n );\n }\n }\n curAuth = nextAuth;\n\n // Begin authentication method's process\n try {\n const username = curAuth.username;\n switch (curAuth.type) {\n case 'password':\n proto.authPassword(username, curAuth.password);\n break;\n case 'publickey':\n proto.authPK(username, curAuth.key);\n break;\n case 'hostbased':\n proto.authHostbased(username,\n curAuth.key,\n curAuth.localHostname,\n curAuth.localUsername,\n (buf, cb) => {\n const signature = curAuth.key.sign(buf);\n if (signature instanceof Error) {\n signature.message =\n `Error while signing with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n\n cb(signature);\n });\n break;\n case 'agent':\n curAuth.agentCtx.init((err) => {\n if (err) {\n err.level = 'agent';\n this.emit('error', err);\n return tryNextAuth();\n }\n tryNextAgentKey();\n });\n break;\n case 'keyboard-interactive':\n proto.authKeyboard(username);\n break;\n case 'none':\n proto.authNone(username);\n break;\n }\n } finally {\n hasSentAuth = false;\n }\n };\n\n function skipAuth(msg) {\n debug && debug(msg);\n process.nextTick(tryNextAuth);\n }\n\n function tryNextAuth() {\n hasSentAuth = false;\n const auth = authHandler(curAuthsLeft, curPartial, doNextAuth);\n if (hasSentAuth || auth === undefined)\n return;\n doNextAuth(auth);\n }\n\n const tryNextAgentKey = () => {\n if (curAuth.type === 'agent') {\n const key = curAuth.agentCtx.nextKey();\n if (key === false) {\n debug && debug('Agent: No more keys left to try');\n debug && debug('Client: agent auth failed');\n tryNextAuth();\n } else {\n const pos = curAuth.agentCtx.pos();\n debug && debug(`Agent: Trying key #${pos + 1}`);\n proto.authPK(curAuth.username, key);\n }\n }\n };\n\n const startTimeout = () => {\n if (this.config.readyTimeout > 0) {\n this._readyTimeout = setTimeout(() => {\n const err = new Error('Timed out while waiting for handshake');\n err.level = 'client-timeout';\n this.emit('error', err);\n sock.destroy();\n }, this.config.readyTimeout);\n }\n };\n\n if (!cfg.sock) {\n let host = this.config.host;\n const forceIPv4 = this.config.forceIPv4;\n const forceIPv6 = this.config.forceIPv6;\n\n debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`);\n\n const doConnect = () => {\n startTimeout();\n sock.connect({\n host,\n port: this.config.port,\n localAddress: this.config.localAddress,\n localPort: this.config.localPort\n });\n sock.setNoDelay(true);\n sock.setMaxListeners(0);\n sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0);\n };\n\n if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) {\n doConnect();\n } else {\n dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => {\n if (err) {\n const type = (forceIPv4 ? 'IPv4' : 'IPv6');\n const error = new Error(\n `Error while looking up ${type} address for '${host}': ${err}`\n );\n clearTimeout(this._readyTimeout);\n error.level = 'client-dns';\n this.emit('error', error);\n this.emit('close');\n return;\n }\n host = address;\n doConnect();\n });\n }\n } else {\n // Custom socket passed in\n startTimeout();\n if (typeof sock.connecting === 'boolean') {\n // net.Socket\n\n if (!sock.connecting) {\n // Already connected\n onConnect();\n }\n } else {\n // Assume socket/stream is already \"connected\"\n onConnect();\n }\n }\n\n return this;\n }\n\n end() {\n if (this._sock && isWritable(this._sock)) {\n this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n this._sock.end();\n }\n return this;\n }\n\n destroy() {\n this._sock && isWritable(this._sock) && this._sock.destroy();\n return this;\n }\n\n exec(cmd, opts, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) };\n\n openChannel(this, 'session', extraOpts, (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n const todo = [];\n\n function reqCb(err) {\n if (err) {\n chan.close();\n cb(err);\n return;\n }\n if (todo.length)\n todo.shift()();\n }\n\n if (this.config.allowAgentFwd === true\n || (opts\n && opts.agentForward === true\n && this._agent !== undefined)) {\n todo.push(() => reqAgentFwd(chan, reqCb));\n }\n\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.env === 'object' && opts.env !== null)\n reqEnv(chan, opts.env);\n if ((typeof opts.pty === 'object' && opts.pty !== null)\n || opts.pty === true) {\n todo.push(() => reqPty(chan, opts.pty, reqCb));\n }\n if ((typeof opts.x11 === 'object' && opts.x11 !== null)\n || opts.x11 === 'number'\n || opts.x11 === true) {\n todo.push(() => reqX11(chan, opts.x11, reqCb));\n }\n }\n\n todo.push(() => reqExec(chan, cmd, opts, cb));\n todo.shift()();\n });\n\n return this;\n }\n\n shell(wndopts, opts, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof wndopts === 'function') {\n cb = wndopts;\n wndopts = opts = undefined;\n } else if (typeof opts === 'function') {\n cb = opts;\n opts = undefined;\n }\n if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) {\n opts = wndopts;\n wndopts = undefined;\n }\n\n openChannel(this, 'session', (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n const todo = [];\n\n function reqCb(err) {\n if (err) {\n chan.close();\n cb(err);\n return;\n }\n if (todo.length)\n todo.shift()();\n }\n\n if (this.config.allowAgentFwd === true\n || (opts\n && opts.agentForward === true\n && this._agent !== undefined)) {\n todo.push(() => reqAgentFwd(chan, reqCb));\n }\n\n if (wndopts !== false)\n todo.push(() => reqPty(chan, wndopts, reqCb));\n\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.env === 'object' && opts.env !== null)\n reqEnv(chan, opts.env);\n if ((typeof opts.x11 === 'object' && opts.x11 !== null)\n || opts.x11 === 'number'\n || opts.x11 === true) {\n todo.push(() => reqX11(chan, opts.x11, reqCb));\n }\n }\n\n todo.push(() => reqShell(chan, cb));\n todo.shift()();\n });\n\n return this;\n }\n\n subsys(name, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n openChannel(this, 'session', (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n reqSubsystem(chan, name, (err, stream) => {\n if (err) {\n cb(err);\n return;\n }\n\n cb(undefined, stream);\n });\n });\n\n return this;\n }\n\n forwardIn(bindAddr, bindPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request for the server to start forwarding TCP connections to us\n // on a particular address and port\n\n const wantReply = (typeof cb === 'function');\n\n if (wantReply) {\n this._callbacks.push((had_err, data) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${bindAddr}:${bindPort}`));\n return;\n }\n\n let realPort = bindPort;\n if (bindPort === 0 && data && data.length >= 4) {\n realPort = readUInt32BE(data, 0);\n if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG))\n bindPort = realPort;\n }\n\n this._forwarding[`${bindAddr}:${bindPort}`] = realPort;\n\n cb(undefined, realPort);\n });\n }\n\n this._protocol.tcpipForward(bindAddr, bindPort, wantReply);\n\n return this;\n }\n\n unforwardIn(bindAddr, bindPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request to stop forwarding us new connections for a particular\n // address and port\n\n const wantReply = (typeof cb === 'function');\n\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`));\n return;\n }\n\n delete this._forwarding[`${bindAddr}:${bindPort}`];\n\n cb();\n });\n }\n\n this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply);\n\n return this;\n }\n\n forwardOut(srcIP, srcPort, dstIP, dstPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request to forward a TCP connection to the server\n\n const cfg = {\n srcIP: srcIP,\n srcPort: srcPort,\n dstIP: dstIP,\n dstPort: dstPort\n };\n\n if (typeof cb !== 'function')\n cb = noop;\n\n openChannel(this, 'direct-tcpip', cfg, cb);\n\n return this;\n }\n\n openssh_noMoreSessions(cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to disable future sessions'));\n return;\n }\n\n cb();\n });\n }\n\n this._protocol.openssh_noMoreSessions(wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_forwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${socketPath}`));\n return;\n }\n this._forwardingUnix[socketPath] = true;\n cb();\n });\n }\n\n this._protocol.openssh_streamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_unforwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to unbind from ${socketPath}`));\n return;\n }\n delete this._forwardingUnix[socketPath];\n cb();\n });\n }\n\n this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_forwardOutStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof cb !== 'function')\n cb = noop;\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb);\n return this;\n }\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n sftp(cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n openChannel(this, 'sftp', (err, sftp) => {\n if (err) {\n cb(err);\n return;\n }\n\n reqSubsystem(sftp, 'sftp', (err, sftp_) => {\n if (err) {\n cb(err);\n return;\n }\n\n function removeListeners() {\n sftp.removeListener('ready', onReady);\n sftp.removeListener('error', onError);\n sftp.removeListener('exit', onExit);\n sftp.removeListener('close', onExit);\n }\n\n function onReady() {\n // TODO: do not remove exit/close in case remote end closes the\n // channel abruptly and we need to notify outstanding callbacks\n removeListeners();\n cb(undefined, sftp);\n }\n\n function onError(err) {\n removeListeners();\n cb(err);\n }\n\n function onExit(code, signal) {\n removeListeners();\n let msg;\n if (typeof code === 'number')\n msg = `Received exit code ${code} while establishing SFTP session`;\n else if (signal !== undefined)\n msg = `Received signal ${signal} while establishing SFTP session`;\n else\n msg = 'Received unexpected SFTP session termination';\n const err = new Error(msg);\n err.code = code;\n err.signal = signal;\n cb(err);\n }\n\n sftp.on('ready', onReady)\n .on('error', onError)\n .on('exit', onExit)\n .on('close', onExit);\n\n sftp._init();\n });\n });\n\n return this;\n }\n}\n\nfunction openChannel(self, type, opts, cb) {\n // Ask the server to open a channel for some purpose\n // (e.g. session (sftp, exec, shell), or forwarding a TCP connection\n const initWindow = MAX_WINDOW;\n const maxPacket = PACKET_SIZE;\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const wrapper = (err, stream) => {\n cb(err, stream);\n };\n wrapper.type = type;\n\n const localChan = self._chanMgr.add(wrapper);\n\n if (localChan === -1) {\n cb(new Error('No free channels available'));\n return;\n }\n\n switch (type) {\n case 'session':\n case 'sftp':\n self._protocol.session(localChan, initWindow, maxPacket);\n break;\n case 'direct-tcpip':\n self._protocol.directTcpip(localChan, initWindow, maxPacket, opts);\n break;\n case 'direct-streamlocal@openssh.com':\n self._protocol.openssh_directStreamLocal(\n localChan, initWindow, maxPacket, opts\n );\n break;\n default:\n throw new Error(`Unsupported channel type: ${type}`);\n }\n}\n\nfunction reqX11(chan, screen, cb) {\n // Asks server to start sending us X11 connections\n const cfg = {\n single: false,\n protocol: 'MIT-MAGIC-COOKIE-1',\n cookie: undefined,\n screen: 0\n };\n\n if (typeof screen === 'function') {\n cb = screen;\n } else if (typeof screen === 'object' && screen !== null) {\n if (typeof screen.single === 'boolean')\n cfg.single = screen.single;\n if (typeof screen.screen === 'number')\n cfg.screen = screen.screen;\n if (typeof screen.protocol === 'string')\n cfg.protocol = screen.protocol;\n if (typeof screen.cookie === 'string')\n cfg.cookie = screen.cookie;\n else if (Buffer.isBuffer(screen.cookie))\n cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length);\n }\n if (cfg.cookie === undefined)\n cfg.cookie = randomCookie();\n\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n if (wantReply)\n cb(new Error('Channel is not open'));\n return;\n }\n\n if (wantReply) {\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to request X11'));\n return;\n }\n\n chan._hasX11 = true;\n ++chan._client._acceptX11;\n chan.once('close', () => {\n if (chan._client._acceptX11)\n --chan._client._acceptX11;\n });\n\n cb();\n });\n }\n\n chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply);\n}\n\nfunction reqPty(chan, opts, cb) {\n let rows = 24;\n let cols = 80;\n let width = 640;\n let height = 480;\n let term = 'vt100';\n let modes = null;\n\n if (typeof opts === 'function') {\n cb = opts;\n } else if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.rows === 'number')\n rows = opts.rows;\n if (typeof opts.cols === 'number')\n cols = opts.cols;\n if (typeof opts.width === 'number')\n width = opts.width;\n if (typeof opts.height === 'number')\n height = opts.height;\n if (typeof opts.term === 'string')\n term = opts.term;\n if (typeof opts.modes === 'object')\n modes = opts.modes;\n }\n\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n if (wantReply)\n cb(new Error('Channel is not open'));\n return;\n }\n\n if (wantReply) {\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to request a pseudo-terminal'));\n return;\n }\n cb();\n });\n }\n\n chan._client._protocol.pty(chan.outgoing.id,\n rows,\n cols,\n height,\n width,\n term,\n modes,\n wantReply);\n}\n\nfunction reqAgentFwd(chan, cb) {\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n wantReply && cb(new Error('Channel is not open'));\n return;\n }\n if (chan._client._agentFwdEnabled) {\n wantReply && cb(false);\n return;\n }\n\n chan._client._agentFwdEnabled = true;\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n chan._client._agentFwdEnabled = false;\n if (wantReply) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to request agent forwarding'));\n }\n return;\n }\n\n if (wantReply)\n cb();\n });\n\n chan._client._protocol.openssh_agentForward(chan.outgoing.id, true);\n}\n\nfunction reqShell(chan, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to open shell'));\n return;\n }\n chan.subtype = 'shell';\n cb(undefined, chan);\n });\n\n chan._client._protocol.shell(chan.outgoing.id, true);\n}\n\nfunction reqExec(chan, cmd, opts, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to exec'));\n return;\n }\n chan.subtype = 'exec';\n chan.allowHalfOpen = (opts.allowHalfOpen !== false);\n cb(undefined, chan);\n });\n\n chan._client._protocol.exec(chan.outgoing.id, cmd, true);\n}\n\nfunction reqEnv(chan, env) {\n if (chan.outgoing.state !== 'open')\n return;\n\n const keys = Object.keys(env || {});\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n const val = env[key];\n chan._client._protocol.env(chan.outgoing.id, key, val, false);\n }\n}\n\nfunction reqSubsystem(chan, name, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to start subsystem: ${name}`));\n return;\n }\n chan.subtype = 'subsystem';\n cb(undefined, chan);\n });\n\n chan._client._protocol.subsystem(chan.outgoing.id, name, true);\n}\n\n// TODO: inline implementation into single call site\nfunction onCHANNEL_OPEN(self, info) {\n // The server is trying to open a channel with us, this is usually when\n // we asked the server to forward us connections on some port and now they\n // are asking us to accept/deny an incoming connection on their side\n\n let localChan = -1;\n let reason;\n\n const accept = () => {\n const chanInfo = {\n type: info.type,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const stream = new Channel(self, chanInfo);\n self._chanMgr.update(localChan, stream);\n\n self._protocol.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n return stream;\n };\n const reject = () => {\n if (reason === undefined) {\n if (localChan === -1)\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n else\n reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;\n }\n\n if (localChan !== -1)\n self._chanMgr.remove(localChan);\n\n self._protocol.channelOpenFail(info.sender, reason, '');\n };\n const reserveChannel = () => {\n localChan = self._chanMgr.add();\n\n if (localChan === -1) {\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of incoming channel open: '\n + 'no channels available'\n );\n }\n }\n\n return (localChan !== -1);\n };\n\n const data = info.data;\n switch (info.type) {\n case 'forwarded-tcpip': {\n const val = self._forwarding[`${data.destIP}:${data.destPort}`];\n if (val !== undefined && reserveChannel()) {\n if (data.destPort === 0)\n data.destPort = val;\n self.emit('tcp connection', data, accept, reject);\n return;\n }\n break;\n }\n case 'forwarded-streamlocal@openssh.com':\n if (self._forwardingUnix[data.socketPath] !== undefined\n && reserveChannel()) {\n self.emit('unix connection', data, accept, reject);\n return;\n }\n break;\n case 'auth-agent@openssh.com':\n if (self._agentFwdEnabled\n && typeof self._agent.getStream === 'function'\n && reserveChannel()) {\n self._agent.getStream((err, stream) => {\n if (err)\n return reject();\n\n const upstream = accept();\n upstream.pipe(stream).pipe(upstream);\n });\n return;\n }\n break;\n case 'x11':\n if (self._acceptX11 !== 0 && reserveChannel()) {\n self.emit('x11', data, accept, reject);\n return;\n }\n break;\n default:\n // Automatically reject any unsupported channel open requests\n reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of unsupported incoming channel open '\n + `type: ${info.type}`\n );\n }\n }\n\n if (reason === undefined) {\n reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of unexpected incoming channel open for: '\n + info.type\n );\n }\n }\n\n reject();\n}\n\nconst randomCookie = (() => {\n const buffer = Buffer.allocUnsafe(16);\n return () => {\n randomFillSync(buffer, 0, 16);\n return buffer.hexSlice(0, 16);\n };\n})();\n\nfunction makeSimpleAuthHandler(authList) {\n if (!Array.isArray(authList))\n throw new Error('authList must be an array');\n\n let a = 0;\n return (authsLeft, partialSuccess, cb) => {\n if (a === authList.length)\n return false;\n return authList[a++];\n };\n}\n\nfunction hostKeysProve(client, keys_, cb) {\n if (!client._sock || !isWritable(client._sock))\n return;\n\n if (typeof cb !== 'function')\n cb = noop;\n\n if (!Array.isArray(keys_))\n throw new TypeError('Invalid keys argument type');\n\n const keys = [];\n for (const key of keys_) {\n const parsed = parseKey(key);\n if (parsed instanceof Error)\n throw parsed;\n keys.push(parsed);\n }\n\n if (!client.config.strictVendor\n || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) {\n client._callbacks.push((had_err, data) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Server failed to prove supplied keys'));\n return;\n }\n\n // TODO: move all of this parsing/verifying logic out of the client?\n const ret = [];\n let keyIdx = 0;\n bufferParser.init(data, 0);\n while (bufferParser.avail()) {\n if (keyIdx === keys.length)\n break;\n const key = keys[keyIdx++];\n const keyPublic = key.getPublicSSH();\n\n const sigEntry = bufferParser.readString();\n sigParser.init(sigEntry, 0);\n const type = sigParser.readString(true);\n let value = sigParser.readString();\n\n let algo;\n if (type !== key.type) {\n if (key.type === 'ssh-rsa') {\n switch (type) {\n case 'rsa-sha2-256':\n algo = 'sha256';\n break;\n case 'rsa-sha2-512':\n algo = 'sha512';\n break;\n default:\n continue;\n }\n } else {\n continue;\n }\n }\n\n const sessionID = client._protocol._kex.sessionID;\n const verifyData = Buffer.allocUnsafe(\n 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length\n );\n let p = 0;\n writeUInt32BE(verifyData, 29, p);\n verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);\n writeUInt32BE(verifyData, sessionID.length, p += 29);\n bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4);\n writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length);\n bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4);\n\n if (!(value = sigSSHToASN1(value, type)))\n continue;\n if (key.verify(verifyData, value, algo) === true)\n ret.push(key);\n }\n sigParser.clear();\n bufferParser.clear();\n\n cb(null, ret);\n });\n\n client._protocol.openssh_hostKeysProve(keys);\n return;\n }\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n}\n\nmodule.exports = Client;\n","'use strict';\n\nconst { Agent: HttpAgent } = require('http');\nconst { Agent: HttpsAgent } = require('https');\nconst { connect: tlsConnect } = require('tls');\n\nlet Client;\n\nfor (const ctor of [HttpAgent, HttpsAgent]) {\n class SSHAgent extends ctor {\n constructor(connectCfg, agentOptions) {\n super(agentOptions);\n\n this._connectCfg = connectCfg;\n this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost';\n }\n\n createConnection(options, cb) {\n const srcIP = (options && options.localAddress) || this._defaultSrcIP;\n const srcPort = (options && options.localPort) || 0;\n const dstIP = options.host;\n const dstPort = options.port;\n\n if (Client === undefined)\n Client = require('./client.js');\n\n const client = new Client();\n let triedForward = false;\n client.on('ready', () => {\n client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => {\n triedForward = true;\n if (err) {\n client.end();\n return cb(err);\n }\n stream.once('close', () => client.end());\n cb(null, decorateStream(stream, ctor, options));\n });\n }).on('error', cb).on('close', () => {\n if (!triedForward)\n cb(new Error('Unexpected connection close'));\n }).connect(this._connectCfg);\n }\n }\n\n exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent;\n}\n\nfunction noop() {}\n\nfunction decorateStream(stream, ctor, options) {\n if (ctor === HttpAgent) {\n // HTTP\n stream.setKeepAlive = noop;\n stream.setNoDelay = noop;\n stream.setTimeout = noop;\n stream.ref = noop;\n stream.unref = noop;\n stream.destroySoon = stream.destroy;\n return stream;\n }\n\n // HTTPS\n options.socket = stream;\n const wrapped = tlsConnect(options);\n\n // This is a workaround for a regression in node v12.16.3+\n // https://github.com/nodejs/node/issues/35904\n const onClose = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n if (stream.isPaused())\n stream.resume();\n };\n })();\n // 'end' listener is needed because 'close' is not emitted in some scenarios\n // in node v12.x for some unknown reason\n wrapped.on('end', onClose).on('close', onClose);\n\n return wrapped;\n}\n","'use strict';\n\nconst {\n AgentProtocol,\n BaseAgent,\n createAgent,\n CygwinAgent,\n OpenSSHAgent,\n PageantAgent,\n} = require('./agent.js');\nconst {\n SSHTTPAgent: HTTPAgent,\n SSHTTPSAgent: HTTPSAgent,\n} = require('./http-agents.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst {\n flagsToString,\n OPEN_MODE,\n STATUS_CODE,\n stringToFlags,\n} = require('./protocol/SFTP.js');\n\nmodule.exports = {\n AgentProtocol,\n BaseAgent,\n createAgent,\n Client: require('./client.js'),\n CygwinAgent,\n HTTPAgent,\n HTTPSAgent,\n OpenSSHAgent,\n PageantAgent,\n Server: require('./server.js'),\n utils: {\n parseKey,\n sftp: {\n flagsToString,\n OPEN_MODE,\n STATUS_CODE,\n stringToFlags,\n },\n },\n};\n","/*\n TODO:\n * Replace `buffer._pos` usage in keyParser.js and elsewhere\n * Utilize optional \"writev\" support when writing packets from\n cipher.encrypt()\n * Built-in support for automatic re-keying, on by default\n * Revisit receiving unexpected/unknown packets\n * Error (fatal or otherwise) or ignore or pass on to user (in some or all\n cases)?\n * Including server/client check for single directional packet types?\n * Check packets for validity or bail as early as possible?\n * Automatic re-key every 2**31 packets after the last key exchange (sent or\n received), as suggested by RFC4344. OpenSSH currently does this.\n * Automatic re-key every so many blocks depending on cipher. RFC4344:\n Because of a birthday property of block ciphers and some modes of\n operation, implementations must be careful not to encrypt too many\n blocks with the same encryption key.\n\n Let L be the block length (in bits) of an SSH encryption method's\n block cipher (e.g., 128 for AES). If L is at least 128, then, after\n rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4)\n blocks before rekeying again. If L is at least 128, then SSH\n implementations should also attempt to force a rekey before receiving\n more than 2**(L/4) blocks. If L is less than 128 (which is the case\n for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then,\n although it may be too expensive to rekey every 2**(L/4) blocks, it\n is still advisable for SSH implementations to follow the original\n recommendation in [RFC4253]: rekey at least once for every gigabyte\n of transmitted data.\n\n Note that if L is less than or equal to 128, then the recommendation\n in this subsection supersedes the recommendation in Section 3.1. If\n an SSH implementation uses a block cipher with a larger block size\n (e.g., Rijndael with 256-bit blocks), then the recommendations in\n Section 3.1 may supersede the recommendations in this subsection\n (depending on the lengths of the packets).\n*/\n\n'use strict';\n\nconst { inspect } = require('util');\n\nconst { bindingAvailable, NullCipher, NullDecipher } = require('./crypto.js');\nconst {\n COMPAT_CHECKS,\n DISCONNECT_REASON,\n MESSAGE,\n SIGNALS,\n TERMINAL_MODE,\n} = require('./constants.js');\nconst {\n DEFAULT_KEXINIT,\n KexInit,\n kexinit,\n onKEXPayload,\n} = require('./kex.js');\nconst {\n parseKey,\n} = require('./keyParser.js');\nconst MESSAGE_HANDLERS = require('./handlers.js');\nconst {\n bufferCopy,\n bufferFill,\n bufferSlice,\n convertSignature,\n sendPacket,\n writeUInt32BE,\n} = require('./utils.js');\nconst {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n} = require('./zlib.js');\n\nconst MODULE_VER = require('../../package.json').version;\n\nconst VALID_DISCONNECT_REASONS = new Map(\n Object.values(DISCONNECT_REASON).map((n) => [n, 1])\n);\nconst IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`);\nconst IDENT = Buffer.from(`${IDENT_RAW}\\r\\n`);\nconst MAX_LINE_LEN = 8192;\nconst MAX_LINES = 1024;\nconst PING_PAYLOAD = Buffer.from([\n MESSAGE.GLOBAL_REQUEST,\n // \"keepalive@openssh.com\"\n 0, 0, 0, 21,\n 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115,\n 115, 104, 46, 99, 111, 109,\n // Request a reply\n 1,\n]);\nconst NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]);\n\nfunction noop() {}\n\n/*\n Inbound:\n * kexinit payload (needed only until exchange hash is generated)\n * raw ident\n * rekey packet queue\n * expected packet (implemented as separate _parse() function?)\n Outbound:\n * kexinit payload (needed only until exchange hash is generated)\n * rekey packet queue\n * kex secret (needed only until NEWKEYS)\n * exchange hash (needed only until NEWKEYS)\n * session ID (set to exchange hash from initial handshake)\n*/\nclass Protocol {\n constructor(config) {\n const onWrite = config.onWrite;\n if (typeof onWrite !== 'function')\n throw new Error('Missing onWrite function');\n this._onWrite = (data) => { onWrite(data); };\n\n const onError = config.onError;\n if (typeof onError !== 'function')\n throw new Error('Missing onError function');\n this._onError = (err) => { onError(err); };\n\n const debug = config.debug;\n this._debug = (typeof debug === 'function'\n ? (msg) => { debug(msg); }\n : undefined);\n\n const onHeader = config.onHeader;\n this._onHeader = (typeof onHeader === 'function'\n ? (...args) => { onHeader(...args); }\n : noop);\n\n const onPacket = config.onPacket;\n this._onPacket = (typeof onPacket === 'function'\n ? () => { onPacket(); }\n : noop);\n\n let onHandshakeComplete = config.onHandshakeComplete;\n if (typeof onHandshakeComplete !== 'function')\n onHandshakeComplete = noop;\n this._onHandshakeComplete = (...args) => {\n this._debug && this._debug('Handshake completed');\n\n // Process packets queued during a rekey where necessary\n const oldQueue = this._queue;\n if (oldQueue) {\n this._queue = undefined;\n this._debug && this._debug(\n `Draining outbound queue (${oldQueue.length}) ...`\n );\n for (let i = 0; i < oldQueue.length; ++i) {\n const data = oldQueue[i];\n // data === payload only\n\n // XXX: hacky\n let finalized = this._packetRW.write.finalize(data);\n if (finalized === data) {\n const packet = this._cipher.allocPacket(data.length);\n packet.set(data, 5);\n finalized = packet;\n }\n\n sendPacket(this, finalized);\n }\n this._debug && this._debug('... finished draining outbound queue');\n }\n\n onHandshakeComplete(...args);\n };\n this._queue = undefined;\n\n const messageHandlers = config.messageHandlers;\n if (typeof messageHandlers === 'object' && messageHandlers !== null)\n this._handlers = messageHandlers;\n else\n this._handlers = {};\n\n this._onPayload = onPayload.bind(this);\n\n this._server = !!config.server;\n this._banner = undefined;\n let greeting;\n if (this._server) {\n if (typeof config.hostKeys !== 'object' || config.hostKeys === null)\n throw new Error('Missing server host key(s)');\n this._hostKeys = config.hostKeys;\n\n // Greeting displayed before the ssh identification string is sent, this\n // is usually ignored by most clients\n if (typeof config.greeting === 'string' && config.greeting.length) {\n greeting = (config.greeting.slice(-2) === '\\r\\n'\n ? config.greeting\n : `${config.greeting}\\r\\n`);\n }\n\n // Banner shown after the handshake completes, but before user\n // authentication begins\n if (typeof config.banner === 'string' && config.banner.length) {\n this._banner = (config.banner.slice(-2) === '\\r\\n'\n ? config.banner\n : `${config.banner}\\r\\n`);\n }\n } else {\n this._hostKeys = undefined;\n }\n\n let offer = config.offer;\n if (typeof offer !== 'object' || offer === null)\n offer = DEFAULT_KEXINIT;\n else if (offer.constructor !== KexInit)\n offer = new KexInit(offer);\n this._kex = undefined;\n this._kexinit = undefined;\n this._offer = offer;\n this._cipher = new NullCipher(0, this._onWrite);\n this._decipher = undefined;\n this._skipNextInboundPacket = false;\n this._packetRW = {\n read: new PacketReader(),\n write: new PacketWriter(this),\n };\n this._hostVerifier = (!this._server\n && typeof config.hostVerifier === 'function'\n ? config.hostVerifier\n : undefined);\n\n this._parse = parseHeader;\n this._buffer = undefined;\n this._authsQueue = [];\n this._authenticated = false;\n this._remoteIdentRaw = undefined;\n let sentIdent;\n if (typeof config.ident === 'string') {\n this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`);\n\n sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2);\n sentIdent.set(this._identRaw, 0);\n sentIdent[sentIdent.length - 2] = 13; // '\\r'\n sentIdent[sentIdent.length - 1] = 10; // '\\n'\n } else if (Buffer.isBuffer(config.ident)) {\n const fullIdent = Buffer.allocUnsafe(8 + config.ident.length);\n fullIdent.latin1Write('SSH-2.0-', 0, 8);\n fullIdent.set(config.ident, 8);\n this._identRaw = fullIdent;\n\n sentIdent = Buffer.allocUnsafe(fullIdent.length + 2);\n sentIdent.set(fullIdent, 0);\n sentIdent[sentIdent.length - 2] = 13; // '\\r'\n sentIdent[sentIdent.length - 1] = 10; // '\\n'\n } else {\n this._identRaw = IDENT_RAW;\n sentIdent = IDENT;\n }\n this._compatFlags = 0;\n\n if (this._debug) {\n if (bindingAvailable)\n this._debug('Custom crypto binding available');\n else\n this._debug('Custom crypto binding not available');\n }\n\n this._debug && this._debug(\n `Local ident: ${inspect(this._identRaw.toString())}`\n );\n this.start = () => {\n this.start = undefined;\n if (greeting)\n this._onWrite(greeting);\n this._onWrite(sentIdent);\n };\n }\n _destruct(reason) {\n this._packetRW.read.cleanup();\n this._packetRW.write.cleanup();\n this._cipher && this._cipher.free();\n this._decipher && this._decipher.free();\n if (typeof reason !== 'string' || reason.length === 0)\n reason = 'fatal error';\n this.parse = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };\n this._onWrite = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };\n this._destruct = undefined;\n }\n cleanup() {\n this._destruct && this._destruct();\n }\n parse(chunk, i, len) {\n while (i < len)\n i = this._parse(chunk, i, len);\n }\n\n // Protocol message API\n\n // ===========================================================================\n // Common/Shared =============================================================\n // ===========================================================================\n\n // Global\n // ------\n disconnect(reason) {\n const pktLen = 1 + 4 + 4 + 4;\n // We don't use _packetRW.write.* here because we need to make sure that\n // we always get a full packet allocated because this message can be sent\n // at any time -- even during a key exchange\n let p = this._packetRW.write.allocStartKEX;\n const packet = this._packetRW.write.alloc(pktLen, true);\n const end = p + pktLen;\n\n if (!VALID_DISCONNECT_REASONS.has(reason))\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n\n packet[p] = MESSAGE.DISCONNECT;\n writeUInt32BE(packet, reason, ++p);\n packet.fill(0, p += 4, end);\n\n this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`);\n sendPacket(this, this._packetRW.write.finalize(packet, true), true);\n }\n ping() {\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(PING_PAYLOAD.length);\n\n packet.set(PING_PAYLOAD, p);\n\n this._debug && this._debug(\n 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n rekey() {\n if (this._kexinit === undefined) {\n this._debug && this._debug('Outbound: Initiated explicit rekey');\n this._queue = [];\n kexinit(this);\n } else {\n this._debug && this._debug('Outbound: Ignoring rekey during handshake');\n }\n }\n\n // 'ssh-connection' service-specific\n // ---------------------------------\n requestSuccess(data) {\n let p = this._packetRW.write.allocStart;\n let packet;\n if (Buffer.isBuffer(data)) {\n packet = this._packetRW.write.alloc(1 + data.length);\n\n packet[p] = MESSAGE.REQUEST_SUCCESS;\n\n packet.set(data, ++p);\n } else {\n packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.REQUEST_SUCCESS;\n }\n\n this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n requestFailure() {\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.REQUEST_FAILURE;\n\n this._debug && this._debug('Outbound: Sending REQUEST_FAILURE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelSuccess(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_SUCCESS;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelFailure(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_FAILURE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelEOF(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_EOF;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelClose(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_CLOSE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelWindowAdjust(chan, amount) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, amount, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelData(chan, data) {\n const isBuffer = Buffer.isBuffer(data);\n const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen);\n\n packet[p] = MESSAGE.CHANNEL_DATA;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, dataLen, p += 4);\n\n if (isBuffer)\n packet.set(data, p += 4);\n else\n packet.utf8Write(data, p += 4, dataLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelExtData(chan, data, type) {\n const isBuffer = Buffer.isBuffer(data);\n const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen);\n\n packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, type, p += 4);\n\n writeUInt32BE(packet, dataLen, p += 4);\n\n if (isBuffer)\n packet.set(data, p += 4);\n else\n packet.utf8Write(data, p += 4, dataLen);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelOpenConfirm(remote, local, initWindow, maxPacket) {\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION;\n\n writeUInt32BE(packet, remote, ++p);\n\n writeUInt32BE(packet, local, p += 4);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelOpenFail(remote, reason, desc) {\n if (typeof desc !== 'string')\n desc = '';\n\n const descLen = Buffer.byteLength(desc);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE;\n\n writeUInt32BE(packet, remote, ++p);\n\n writeUInt32BE(packet, reason, p += 4);\n\n writeUInt32BE(packet, descLen, p += 4);\n\n p += 4;\n if (descLen) {\n packet.utf8Write(desc, p, descLen);\n p += descLen;\n }\n\n writeUInt32BE(packet, 0, p); // Empty language tag\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // ===========================================================================\n // Client-specific ===========================================================\n // ===========================================================================\n\n // Global\n // ------\n service(name) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + nameLen);\n\n packet[p] = MESSAGE.SERVICE_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // 'ssh-userauth' service-specific\n // -------------------------------\n authPassword(username, password, newPassword) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n const passLen = Buffer.byteLength(password);\n const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen\n + (newPassword ? 4 + newPassLen : 0)\n );\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 8, p += 14);\n packet.utf8Write('password', p += 4, 8);\n\n packet[p += 8] = (newPassword ? 1 : 0);\n\n writeUInt32BE(packet, passLen, ++p);\n if (Buffer.isBuffer(password))\n bufferCopy(password, packet, 0, passLen, p += 4);\n else\n packet.utf8Write(password, p += 4, passLen);\n\n if (newPassword) {\n writeUInt32BE(packet, newPassLen, p += passLen);\n if (Buffer.isBuffer(newPassword))\n bufferCopy(newPassword, packet, 0, newPassLen, p += 4);\n else\n packet.utf8Write(newPassword, p += 4, newPassLen);\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (changed password)'\n );\n } else {\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (password)'\n );\n }\n\n this._authsQueue.push('password');\n\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authPK(username, pubKey, cbSign) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n pubKey = parseKey(pubKey);\n if (pubKey instanceof Error)\n throw new Error('Invalid key');\n\n const keyType = pubKey.type;\n pubKey = pubKey.getPublicSSH();\n\n const userLen = Buffer.byteLength(username);\n const algoLen = Buffer.byteLength(keyType);\n const pubKeyLen = pubKey.length;\n const sessionID = this._kex.sessionID;\n const sesLen = sessionID.length;\n const payloadLen =\n (cbSign ? 4 + sesLen : 0)\n + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen;\n let packet;\n let p;\n if (cbSign) {\n packet = Buffer.allocUnsafe(payloadLen);\n p = 0;\n writeUInt32BE(packet, sesLen, p);\n packet.set(sessionID, p += 4);\n p += sesLen;\n } else {\n packet = this._packetRW.write.alloc(payloadLen);\n p = this._packetRW.write.allocStart;\n }\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 9, p += 14);\n packet.utf8Write('publickey', p += 4, 9);\n\n packet[p += 9] = (cbSign ? 1 : 0);\n\n writeUInt32BE(packet, algoLen, ++p);\n packet.utf8Write(keyType, p += 4, algoLen);\n\n writeUInt32BE(packet, pubKeyLen, p += algoLen);\n packet.set(pubKey, p += 4);\n\n if (!cbSign) {\n this._authsQueue.push('publickey');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n return;\n }\n\n cbSign(packet, (signature) => {\n signature = convertSignature(signature, keyType);\n if (signature === false)\n throw new Error('Error while converting handshake signature');\n\n const sigLen = signature.length;\n p = this._packetRW.write.allocStart;\n packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4\n + 4 + algoLen + 4 + sigLen\n );\n\n // TODO: simply copy from original \"packet\" to new `packet` to avoid\n // having to write each individual field a second time?\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 9, p += 14);\n packet.utf8Write('publickey', p += 4, 9);\n\n packet[p += 9] = 1;\n\n writeUInt32BE(packet, algoLen, ++p);\n packet.utf8Write(keyType, p += 4, algoLen);\n\n writeUInt32BE(packet, pubKeyLen, p += algoLen);\n packet.set(pubKey, p += 4);\n\n writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen);\n\n writeUInt32BE(packet, algoLen, p += 4);\n packet.utf8Write(keyType, p += 4, algoLen);\n\n writeUInt32BE(packet, sigLen, p += algoLen);\n packet.set(signature, p += 4);\n\n // Servers shouldn't send packet type 60 in response to signed publickey\n // attempts, but if they do, interpret as type 60.\n this._authsQueue.push('publickey');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (publickey)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n });\n }\n authHostbased(username, pubKey, hostname, userlocal, cbSign) {\n // TODO: Make DRY by sharing similar code with authPK()\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n pubKey = parseKey(pubKey);\n if (pubKey instanceof Error)\n throw new Error('Invalid key');\n\n const keyType = pubKey.type;\n pubKey = pubKey.getPublicSSH();\n\n const userLen = Buffer.byteLength(username);\n const algoLen = Buffer.byteLength(keyType);\n const pubKeyLen = pubKey.length;\n const sessionID = this._kex.sessionID;\n const sesLen = sessionID.length;\n const hostnameLen = Buffer.byteLength(hostname);\n const userlocalLen = Buffer.byteLength(userlocal);\n const data = Buffer.allocUnsafe(\n 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen\n + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen\n );\n let p = 0;\n\n writeUInt32BE(data, sesLen, p);\n data.set(sessionID, p += 4);\n\n data[p += sesLen] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(data, userLen, ++p);\n data.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(data, 14, p += userLen);\n data.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(data, 9, p += 14);\n data.utf8Write('hostbased', p += 4, 9);\n\n writeUInt32BE(data, algoLen, p += 9);\n data.utf8Write(keyType, p += 4, algoLen);\n\n writeUInt32BE(data, pubKeyLen, p += algoLen);\n data.set(pubKey, p += 4);\n\n writeUInt32BE(data, hostnameLen, p += pubKeyLen);\n data.utf8Write(hostname, p += 4, hostnameLen);\n\n writeUInt32BE(data, userlocalLen, p += hostnameLen);\n data.utf8Write(userlocal, p += 4, userlocalLen);\n\n cbSign(data, (signature) => {\n signature = convertSignature(signature, keyType);\n if (!signature)\n throw new Error('Error while converting handshake signature');\n\n const sigLen = signature.length;\n const reqDataLen = (data.length - sesLen - 4);\n p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n reqDataLen + 4 + 4 + algoLen + 4 + sigLen\n );\n\n bufferCopy(data, packet, 4 + sesLen, data.length, p);\n\n writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen);\n writeUInt32BE(packet, algoLen, p += 4);\n packet.utf8Write(keyType, p += 4, algoLen);\n writeUInt32BE(packet, sigLen, p += algoLen);\n packet.set(signature, p += 4);\n\n this._authsQueue.push('hostbased');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (hostbased)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n });\n }\n authKeyboard(username) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4\n );\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 20, p += 14);\n packet.utf8Write('keyboard-interactive', p += 4, 20);\n\n writeUInt32BE(packet, 0, p += 20);\n\n writeUInt32BE(packet, 0, p += 4);\n\n this._authsQueue.push('keyboard-interactive');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authNone(username) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4);\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 4, p += 14);\n packet.utf8Write('none', p += 4, 4);\n\n this._authsQueue.push('none');\n\n this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authInfoRes(responses) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let responsesTotalLen = 0;\n let responseLens;\n\n if (responses) {\n responseLens = new Array(responses.length);\n for (let i = 0; i < responses.length; ++i) {\n const len = Buffer.byteLength(responses[i]);\n responseLens[i] = len;\n responsesTotalLen += 4 + len;\n }\n }\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen);\n\n packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE;\n\n if (responses) {\n writeUInt32BE(packet, responses.length, ++p);\n p += 4;\n for (let i = 0; i < responses.length; ++i) {\n const len = responseLens[i];\n writeUInt32BE(packet, len, p);\n p += 4;\n if (len) {\n packet.utf8Write(responses[i], p, len);\n p += len;\n }\n }\n } else {\n writeUInt32BE(packet, 0, ++p);\n }\n\n this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // 'ssh-connection' service-specific\n // ---------------------------------\n tcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 13, ++p);\n packet.utf8Write('tcpip-forward', p += 4, 13);\n\n packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n cancelTcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 20, ++p);\n packet.utf8Write('cancel-tcpip-forward', p += 4, 20);\n\n packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_streamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 31 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 31, ++p);\n packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31);\n\n packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_cancelStreamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 38 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 38, ++p);\n packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38);\n\n packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending GLOBAL_REQUEST '\n + '(cancel-streamlocal-forward@openssh.com)'\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n directTcpip(chan, initWindow, maxPacket, cfg) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const srcLen = Buffer.byteLength(cfg.srcIP);\n const dstLen = Buffer.byteLength(cfg.dstIP);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 12, ++p);\n packet.utf8Write('direct-tcpip', p += 4, 12);\n\n writeUInt32BE(packet, chan, p += 12);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, dstLen, p += 4);\n packet.utf8Write(cfg.dstIP, p += 4, dstLen);\n\n writeUInt32BE(packet, cfg.dstPort, p += dstLen);\n\n writeUInt32BE(packet, srcLen, p += 4);\n packet.utf8Write(cfg.srcIP, p += 4, srcLen);\n\n writeUInt32BE(packet, cfg.srcPort, p += srcLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const pathLen = Buffer.byteLength(cfg.socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 30, ++p);\n packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30);\n\n writeUInt32BE(packet, chan, p += 30);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, pathLen, p += 4);\n packet.utf8Write(cfg.socketPath, p += 4, pathLen);\n\n // zero-fill reserved fields (string and uint32)\n bufferFill(packet, 0, p += pathLen, p + 8);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_OPEN '\n + `(r:${chan}, direct-streamlocal@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_noMoreSessions(wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 28, ++p);\n packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28);\n\n packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n session(chan, initWindow, maxPacket) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 7, ++p);\n packet.utf8Write('session', p += 4, 7);\n\n writeUInt32BE(packet, chan, p += 7);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n windowChange(chan, rows, cols, height, width) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 13, p += 4);\n packet.utf8Write('window-change', p += 4, 13);\n\n packet[p += 13] = 0;\n\n writeUInt32BE(packet, cols, ++p);\n\n writeUInt32BE(packet, rows, p += 4);\n\n writeUInt32BE(packet, width, p += 4);\n\n writeUInt32BE(packet, height, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n pty(chan, rows, cols, height, width, term, modes, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n if (!term || !term.length)\n term = 'vt100';\n if (modes\n && !Buffer.isBuffer(modes)\n && !Array.isArray(modes)\n && typeof modes === 'object'\n && modes !== null) {\n modes = modesToBytes(modes);\n }\n if (!modes || !modes.length)\n modes = NO_TERMINAL_MODES_BUFFER;\n\n const termLen = term.length;\n const modesLen = modes.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 7, p += 4);\n packet.utf8Write('pty-req', p += 4, 7);\n\n packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, termLen, ++p);\n packet.utf8Write(term, p += 4, termLen);\n\n writeUInt32BE(packet, cols, p += termLen);\n\n writeUInt32BE(packet, rows, p += 4);\n\n writeUInt32BE(packet, width, p += 4);\n\n writeUInt32BE(packet, height, p += 4);\n\n writeUInt32BE(packet, modesLen, p += 4);\n p += 4;\n if (Array.isArray(modes)) {\n for (let i = 0; i < modesLen; ++i)\n packet[p++] = modes[i];\n } else if (Buffer.isBuffer(modes)) {\n packet.set(modes, p);\n }\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n shell(chan, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 5, p += 4);\n packet.utf8Write('shell', p += 4, 5);\n\n packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exec(chan, cmd, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const isBuf = Buffer.isBuffer(cmd);\n const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 4, p += 4);\n packet.utf8Write('exec', p += 4, 4);\n\n packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, cmdLen, ++p);\n if (isBuf)\n packet.set(cmd, p += 4);\n else\n packet.utf8Write(cmd, p += 4, cmdLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n signal(chan, signal) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const origSignal = signal;\n\n signal = signal.toUpperCase();\n if (signal.slice(0, 3) === 'SIG')\n signal = signal.slice(3);\n\n if (SIGNALS[signal] !== 1)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n const signalLen = signal.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 6 + 1 + 4 + signalLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 6, p += 4);\n packet.utf8Write('signal', p += 4, 6);\n\n packet[p += 6] = 0;\n\n writeUInt32BE(packet, signalLen, ++p);\n packet.utf8Write(signal, p += 4, signalLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n env(chan, key, val, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const keyLen = Buffer.byteLength(key);\n const isBuf = Buffer.isBuffer(val);\n const valLen = (isBuf ? val.length : Buffer.byteLength(val));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 3, p += 4);\n packet.utf8Write('env', p += 4, 3);\n\n packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, keyLen, ++p);\n packet.utf8Write(key, p += 4, keyLen);\n\n writeUInt32BE(packet, valLen, p += keyLen);\n if (isBuf)\n packet.set(val, p += 4);\n else\n packet.utf8Write(val, p += 4, valLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n x11Forward(chan, cfg, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const protocol = cfg.protocol;\n const cookie = cfg.cookie;\n const isBufProto = Buffer.isBuffer(protocol);\n const protoLen = (isBufProto\n ? protocol.length\n : Buffer.byteLength(protocol));\n const isBufCookie = Buffer.isBuffer(cookie);\n const cookieLen = (isBufCookie\n ? cookie.length\n : Buffer.byteLength(cookie));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 7, p += 4);\n packet.utf8Write('x11-req', p += 4, 7);\n\n packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n packet[++p] = (cfg.single ? 1 : 0);\n\n writeUInt32BE(packet, protoLen, ++p);\n if (isBufProto)\n packet.set(protocol, p += 4);\n else\n packet.utf8Write(protocol, p += 4, protoLen);\n\n writeUInt32BE(packet, cookieLen, p += protoLen);\n if (isBufCookie)\n packet.set(cookie, p += 4);\n else\n packet.latin1Write(cookie, p += 4, cookieLen);\n\n writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n subsystem(chan, name, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 9, p += 4);\n packet.utf8Write('subsystem', p += 4, 9);\n\n packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_agentForward(chan, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 26, p += 4);\n packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26);\n\n packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_REQUEST '\n + `(r:${chan}, auth-agent-req@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_hostKeysProve(keys) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let keysTotal = 0;\n const publicKeys = [];\n for (const key of keys) {\n const publicKey = key.getPublicSSH();\n keysTotal += 4 + publicKey.length;\n publicKeys.push(publicKey);\n }\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 29, ++p);\n packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);\n\n packet[p += 29] = 1; // want reply\n\n ++p;\n for (const buf of publicKeys) {\n writeUInt32BE(packet, buf.length, p);\n bufferCopy(buf, packet, 0, buf.length, p += 4);\n p += buf.length;\n }\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)'\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // ===========================================================================\n // Server-specific ===========================================================\n // ===========================================================================\n\n // Global\n // ------\n serviceAccept(svcName) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const svcNameLen = Buffer.byteLength(svcName);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen);\n\n packet[p] = MESSAGE.SERVICE_ACCEPT;\n\n writeUInt32BE(packet, svcNameLen, ++p);\n packet.utf8Write(svcName, p += 4, svcNameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n\n if (this._server && this._banner && svcName === 'ssh-userauth') {\n const banner = this._banner;\n this._banner = undefined; // Prevent banner from being displayed again\n const bannerLen = Buffer.byteLength(banner);\n p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4);\n\n packet[p] = MESSAGE.USERAUTH_BANNER;\n\n writeUInt32BE(packet, bannerLen, ++p);\n packet.utf8Write(banner, p += 4, bannerLen);\n\n writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag\n\n this._debug && this._debug('Outbound: Sending USERAUTH_BANNER');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n }\n // 'ssh-connection' service-specific\n forwardedTcpip(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const boundAddrLen = Buffer.byteLength(cfg.boundAddr);\n const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 15, ++p);\n packet.utf8Write('forwarded-tcpip', p += 4, 15);\n\n writeUInt32BE(packet, chan, p += 15);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, boundAddrLen, p += 4);\n packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen);\n\n writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen);\n\n writeUInt32BE(packet, remoteAddrLen, p += 4);\n packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen);\n\n writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n x11(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const addrLen = Buffer.byteLength(cfg.originAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 3, ++p);\n packet.utf8Write('x11', p += 4, 3);\n\n writeUInt32BE(packet, chan, p += 3);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, addrLen, p += 4);\n packet.utf8Write(cfg.originAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, cfg.originPort, p += addrLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_authAgent(chan, initWindow, maxPacket) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 22, ++p);\n packet.utf8Write('auth-agent@openssh.com', p += 4, 22);\n\n writeUInt32BE(packet, chan, p += 22);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const pathLen = Buffer.byteLength(cfg.socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 33, ++p);\n packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33);\n\n writeUInt32BE(packet, chan, p += 33);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, pathLen, p += 4);\n packet.utf8Write(cfg.socketPath, p += 4, pathLen);\n\n writeUInt32BE(packet, 0, p += pathLen);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_OPEN '\n + `(r:${chan}, forwarded-streamlocal@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exitStatus(chan, status) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n // Does not consume window space\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 11, p += 4);\n packet.utf8Write('exit-status', p += 4, 11);\n\n packet[p += 11] = 0;\n\n writeUInt32BE(packet, status, ++p);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exitSignal(chan, name, coreDumped, msg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n // Does not consume window space\n\n const origSignal = name;\n\n if (typeof origSignal !== 'string' || !origSignal)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n let signal = name.toUpperCase();\n if (signal.slice(0, 3) === 'SIG')\n signal = signal.slice(3);\n\n if (SIGNALS[signal] !== 1)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n const nameLen = Buffer.byteLength(signal);\n const msgLen = (msg ? Buffer.byteLength(msg) : 0);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 11, p += 4);\n packet.utf8Write('exit-signal', p += 4, 11);\n\n packet[p += 11] = 0;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(signal, p += 4, nameLen);\n\n packet[p += nameLen] = (coreDumped ? 1 : 0);\n\n writeUInt32BE(packet, msgLen, ++p);\n\n p += 4;\n if (msgLen) {\n packet.utf8Write(msg, p, msgLen);\n p += msgLen;\n }\n\n writeUInt32BE(packet, 0, p);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n // 'ssh-userauth' service-specific\n authFailure(authMethods, isPartial) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0)\n throw new Error('No auth in progress');\n\n let methods;\n\n if (typeof authMethods === 'boolean') {\n isPartial = authMethods;\n authMethods = undefined;\n }\n\n if (authMethods) {\n methods = [];\n for (let i = 0; i < authMethods.length; ++i) {\n if (authMethods[i].toLowerCase() === 'none')\n continue;\n methods.push(authMethods[i]);\n }\n methods = methods.join(',');\n } else {\n methods = '';\n }\n\n const methodsLen = methods.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1);\n\n packet[p] = MESSAGE.USERAUTH_FAILURE;\n\n writeUInt32BE(packet, methodsLen, ++p);\n packet.utf8Write(methods, p += 4, methodsLen);\n\n packet[p += methodsLen] = (isPartial === true ? 1 : 0);\n\n this._authsQueue.shift();\n\n this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authSuccess() {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0)\n throw new Error('No auth in progress');\n\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.USERAUTH_SUCCESS;\n\n this._authsQueue.shift();\n this._authenticated = true;\n\n this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS');\n sendPacket(this, this._packetRW.write.finalize(packet));\n\n if (this._kex.negotiated.cs.compress === 'zlib@openssh.com')\n this._packetRW.read = new ZlibPacketReader();\n if (this._kex.negotiated.sc.compress === 'zlib@openssh.com')\n this._packetRW.write = new ZlibPacketWriter(this);\n }\n authPKOK(keyAlgo, key) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey')\n throw new Error('\"publickey\" auth not in progress');\n\n // TODO: support parsed key for `key`\n\n const keyAlgoLen = Buffer.byteLength(keyAlgo);\n const keyLen = key.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen);\n\n packet[p] = MESSAGE.USERAUTH_PK_OK;\n\n writeUInt32BE(packet, keyAlgoLen, ++p);\n packet.utf8Write(keyAlgo, p += 4, keyAlgoLen);\n\n writeUInt32BE(packet, keyLen, p += keyAlgoLen);\n packet.set(key, p += 4);\n\n this._authsQueue.shift();\n\n this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authPasswdChg(prompt) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const promptLen = Buffer.byteLength(prompt);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4);\n\n packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ;\n\n writeUInt32BE(packet, promptLen, ++p);\n packet.utf8Write(prompt, p += 4, promptLen);\n\n writeUInt32BE(packet, 0, p += promptLen); // Empty language tag\n\n this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authInfoReq(name, instructions, prompts) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n let promptsLen = 0;\n const nameLen = name ? Buffer.byteLength(name) : 0;\n const instrLen = instructions ? Buffer.byteLength(instructions) : 0;\n\n for (let i = 0; i < prompts.length; ++i)\n promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1;\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen\n );\n\n packet[p] = MESSAGE.USERAUTH_INFO_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n p += 4;\n if (name) {\n packet.utf8Write(name, p, nameLen);\n p += nameLen;\n }\n\n writeUInt32BE(packet, instrLen, p);\n p += 4;\n if (instructions) {\n packet.utf8Write(instructions, p, instrLen);\n p += instrLen;\n }\n\n writeUInt32BE(packet, 0, p);\n\n writeUInt32BE(packet, prompts.length, p += 4);\n p += 4;\n for (let i = 0; i < prompts.length; ++i) {\n const prompt = prompts[i];\n const promptLen = Buffer.byteLength(prompt.prompt);\n\n writeUInt32BE(packet, promptLen, p);\n p += 4;\n if (promptLen) {\n packet.utf8Write(prompt.prompt, p, promptLen);\n p += promptLen;\n }\n packet[p++] = (prompt.echo ? 1 : 0);\n }\n\n this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n}\n\n// SSH-protoversion-softwareversion (SP comments) CR LF\nconst RE_IDENT = /^SSH-(2\\.0|1\\.99)-([^ ]+)(?: (.*))?$/;\n\n// TODO: optimize this by starting n bytes from the end of this._buffer instead\n// of the beginning\nfunction parseHeader(chunk, p, len) {\n let data;\n let chunkOffset;\n if (this._buffer) {\n data = Buffer.allocUnsafe(this._buffer.length + (len - p));\n data.set(this._buffer, 0);\n if (p === 0) {\n data.set(chunk, this._buffer.length);\n } else {\n data.set(new Uint8Array(chunk.buffer,\n chunk.byteOffset + p,\n (len - p)),\n this._buffer.length);\n }\n chunkOffset = this._buffer.length;\n p = 0;\n } else {\n data = chunk;\n chunkOffset = 0;\n }\n const op = p;\n let start = p;\n let end = p;\n let needNL = false;\n let lineLen = 0;\n let lines = 0;\n for (; p < data.length; ++p) {\n const ch = data[p];\n\n if (ch === 13 /* '\\r' */) {\n needNL = true;\n continue;\n }\n\n if (ch === 10 /* '\\n' */) {\n if (end > start\n && end - start > 4\n && data[start] === 83 /* 'S' */\n && data[start + 1] === 83 /* 'S' */\n && data[start + 2] === 72 /* 'H' */\n && data[start + 3] === 45 /* '-' */) {\n\n const full = data.latin1Slice(op, end + 1);\n const identRaw = (start === op ? full : full.slice(start - op));\n const m = RE_IDENT.exec(identRaw);\n if (!m)\n throw new Error('Invalid identification string');\n\n const header = {\n greeting: (start === op ? '' : full.slice(0, start - op)),\n identRaw,\n versions: {\n protocol: m[1],\n software: m[2],\n },\n comments: m[3]\n };\n\n // Needed during handshake\n this._remoteIdentRaw = Buffer.from(identRaw);\n\n this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`);\n this._compatFlags = getCompatFlags(header);\n\n this._buffer = undefined;\n this._decipher =\n new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true }));\n this._parse = parsePacket;\n\n this._onHeader(header);\n if (!this._destruct) {\n // We disconnected inside _onHeader\n return len;\n }\n\n kexinit(this);\n\n return p + 1 - chunkOffset;\n }\n\n // Only allow pre-ident greetings when we're a client\n if (this._server)\n throw new Error('Greetings from clients not permitted');\n\n if (++lines > MAX_LINES)\n throw new Error('Max greeting lines exceeded');\n\n needNL = false;\n start = p + 1;\n lineLen = 0;\n } else if (needNL) {\n throw new Error('Invalid header: expected newline');\n } else if (++lineLen >= MAX_LINE_LEN) {\n throw new Error('Header line too long');\n }\n\n end = p;\n }\n if (!this._buffer)\n this._buffer = bufferSlice(data, op);\n\n return p - chunkOffset;\n}\n\nfunction parsePacket(chunk, p, len) {\n return this._decipher.decrypt(chunk, p, len);\n}\n\nfunction onPayload(payload) {\n // XXX: move this to the Decipher implementations?\n\n this._onPacket();\n\n if (payload.length === 0) {\n this._debug && this._debug('Inbound: Skipping empty packet payload');\n return;\n }\n\n payload = this._packetRW.read.read(payload);\n\n const type = payload[0];\n if (type === MESSAGE.USERAUTH_SUCCESS\n && !this._server\n && !this._authenticated) {\n this._authenticated = true;\n if (this._kex.negotiated.cs.compress === 'zlib@openssh.com')\n this._packetRW.write = new ZlibPacketWriter(this);\n if (this._kex.negotiated.sc.compress === 'zlib@openssh.com')\n this._packetRW.read = new ZlibPacketReader();\n }\n const handler = MESSAGE_HANDLERS[type];\n if (handler === undefined) {\n this._debug && this._debug(`Inbound: Unsupported message type: ${type}`);\n return;\n }\n\n return handler(this, payload);\n}\n\nfunction getCompatFlags(header) {\n const software = header.versions.software;\n\n let flags = 0;\n\n for (const rule of COMPAT_CHECKS) {\n if (typeof rule[0] === 'string') {\n if (software === rule[0])\n flags |= rule[1];\n } else if (rule[0].test(software)) {\n flags |= rule[1];\n }\n }\n\n return flags;\n}\n\nfunction modesToBytes(modes) {\n const keys = Object.keys(modes);\n const bytes = Buffer.allocUnsafe((5 * keys.length) + 1);\n let b = 0;\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (key === 'TTY_OP_END')\n continue;\n\n const opcode = TERMINAL_MODE[key];\n if (opcode === undefined)\n continue;\n\n const val = modes[key];\n if (typeof val === 'number' && isFinite(val)) {\n bytes[b++] = opcode;\n bytes[b++] = val >>> 24;\n bytes[b++] = val >>> 16;\n bytes[b++] = val >>> 8;\n bytes[b++] = val;\n }\n }\n\n bytes[b++] = TERMINAL_MODE.TTY_OP_END;\n\n if (b < bytes.length)\n return bufferSlice(bytes, 0, b);\n\n return bytes;\n}\n\nmodule.exports = Protocol;\n","'use strict';\n\nconst EventEmitter = require('events');\nconst fs = require('fs');\nconst { constants } = fs;\nconst {\n Readable: ReadableStream,\n Writable: WritableStream\n} = require('stream');\nconst { inherits, isDate } = require('util');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst {\n bufferCopy,\n bufferSlice,\n makeBufferParser,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst ATTR = {\n SIZE: 0x00000001,\n UIDGID: 0x00000002,\n PERMISSIONS: 0x00000004,\n ACMODTIME: 0x00000008,\n EXTENDED: 0x80000000,\n};\n\n// Large enough to store all possible attributes\nconst ATTRS_BUF = Buffer.alloc(28);\n\nconst STATUS_CODE = {\n OK: 0,\n EOF: 1,\n NO_SUCH_FILE: 2,\n PERMISSION_DENIED: 3,\n FAILURE: 4,\n BAD_MESSAGE: 5,\n NO_CONNECTION: 6,\n CONNECTION_LOST: 7,\n OP_UNSUPPORTED: 8\n};\n\nconst VALID_STATUS_CODES = new Map(\n Object.values(STATUS_CODE).map((n) => [n, 1])\n);\n\nconst STATUS_CODE_STR = {\n [STATUS_CODE.OK]: 'No error',\n [STATUS_CODE.EOF]: 'End of file',\n [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory',\n [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied',\n [STATUS_CODE.FAILURE]: 'Failure',\n [STATUS_CODE.BAD_MESSAGE]: 'Bad message',\n [STATUS_CODE.NO_CONNECTION]: 'No connection',\n [STATUS_CODE.CONNECTION_LOST]: 'Connection lost',\n [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported',\n};\n\nconst REQUEST = {\n INIT: 1,\n OPEN: 3,\n CLOSE: 4,\n READ: 5,\n WRITE: 6,\n LSTAT: 7,\n FSTAT: 8,\n SETSTAT: 9,\n FSETSTAT: 10,\n OPENDIR: 11,\n READDIR: 12,\n REMOVE: 13,\n MKDIR: 14,\n RMDIR: 15,\n REALPATH: 16,\n STAT: 17,\n RENAME: 18,\n READLINK: 19,\n SYMLINK: 20,\n EXTENDED: 200\n};\n\nconst RESPONSE = {\n VERSION: 2,\n STATUS: 101,\n HANDLE: 102,\n DATA: 103,\n NAME: 104,\n ATTRS: 105,\n EXTENDED: 201\n};\n\nconst OPEN_MODE = {\n READ: 0x00000001,\n WRITE: 0x00000002,\n APPEND: 0x00000004,\n CREAT: 0x00000008,\n TRUNC: 0x00000010,\n EXCL: 0x00000020\n};\n\nconst PKT_RW_OVERHEAD = 2 * 1024;\nconst MAX_REQID = 2 ** 32 - 1;\nconst CLIENT_VERSION_BUFFER = Buffer.from([\n 0, 0, 0, 5 /* length */,\n REQUEST.INIT,\n 0, 0, 0, 3 /* version */\n]);\nconst SERVER_VERSION_BUFFER = Buffer.from([\n 0, 0, 0, 5 /* length */,\n RESPONSE.VERSION,\n 0, 0, 0, 3 /* version */\n]);\n\nconst RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/;\nconst OPENSSH_MAX_PKT_LEN = 256 * 1024;\n\nconst bufferParser = makeBufferParser();\n\nconst fakeStderr = {\n readable: false,\n writable: false,\n push: (data) => {},\n once: () => {},\n on: () => {},\n emit: () => {},\n end: () => {},\n};\n\nfunction noop() {}\n\n// Emulates enough of `Channel` to be able to be used as a drop-in replacement\n// in order to process incoming data with as little overhead as possible\nclass SFTP extends EventEmitter {\n constructor(client, chanInfo, cfg) {\n super();\n\n if (typeof cfg !== 'object' || !cfg)\n cfg = {};\n\n const remoteIdentRaw = client._protocol._remoteIdentRaw;\n\n this.server = !!cfg.server;\n this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);\n this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw));\n\n this._version = -1;\n this._extensions = {};\n this._biOpt = cfg.biOpt;\n this._pktLenBytes = 0;\n this._pktLen = 0;\n this._pktPos = 0;\n this._pktType = 0;\n this._pktData = undefined;\n this._writeReqid = -1;\n this._requests = {};\n this._maxInPktLen = OPENSSH_MAX_PKT_LEN;\n this._maxOutPktLen = 34000;\n this._maxReadLen =\n (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;\n this._maxWriteLen =\n (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;\n\n this.maxOpenHandles = undefined;\n\n // Channel compatibility\n this._client = client;\n this._protocol = client._protocol;\n this._callbacks = [];\n this._hasX11 = false;\n this._exit = {\n code: undefined,\n signal: undefined,\n dump: undefined,\n desc: undefined,\n };\n this._waitWindow = false; // SSH-level backpressure\n this._chunkcb = undefined;\n this._buffer = [];\n this.type = chanInfo.type;\n this.subtype = undefined;\n this.incoming = chanInfo.incoming;\n this.outgoing = chanInfo.outgoing;\n this.stderr = fakeStderr;\n this.readable = true;\n }\n\n // This handles incoming data to parse\n push(data) {\n if (data === null) {\n cleanupRequests(this);\n if (!this.readable)\n return;\n // No more incoming data from the remote side\n this.readable = false;\n this.emit('end');\n return;\n }\n /*\n uint32 length\n byte type\n byte[length - 1] data payload\n */\n let p = 0;\n\n while (p < data.length) {\n if (this._pktLenBytes < 4) {\n let nb = Math.min(4 - this._pktLenBytes, data.length - p);\n this._pktLenBytes += nb;\n\n while (nb--)\n this._pktLen = (this._pktLen << 8) + data[p++];\n\n if (this._pktLenBytes < 4)\n return;\n if (this._pktLen === 0)\n return doFatalSFTPError(this, 'Invalid packet length');\n if (this._pktLen > this._maxInPktLen) {\n const max = this._maxInPktLen;\n return doFatalSFTPError(\n this,\n `Packet length ${this._pktLen} exceeds max length of ${max}`\n );\n }\n if (p >= data.length)\n return;\n }\n if (this._pktPos < this._pktLen) {\n const nb = Math.min(this._pktLen - this._pktPos, data.length - p);\n if (p !== 0 || nb !== data.length) {\n if (nb === this._pktLen) {\n this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb);\n } else {\n if (!this._pkt)\n this._pkt = Buffer.allocUnsafe(this._pktLen);\n this._pkt.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._pktPos\n );\n }\n } else if (nb === this._pktLen) {\n this._pkt = data;\n } else {\n if (!this._pkt)\n this._pkt = Buffer.allocUnsafe(this._pktLen);\n this._pkt.set(data, this._pktPos);\n }\n p += nb;\n this._pktPos += nb;\n if (this._pktPos < this._pktLen)\n return;\n }\n\n const type = this._pkt[0];\n const payload = this._pkt;\n\n // Prepare for next packet\n this._pktLen = 0;\n this._pktLenBytes = 0;\n this._pkt = undefined;\n this._pktPos = 0;\n\n const handler = (this.server\n ? SERVER_HANDLERS[type]\n : CLIENT_HANDLERS[type]);\n if (!handler)\n return doFatalSFTPError(this, `Unknown packet type ${type}`);\n\n if (this._version === -1) {\n if (this.server) {\n if (type !== REQUEST.INIT)\n return doFatalSFTPError(this, `Expected INIT packet, got ${type}`);\n } else if (type !== RESPONSE.VERSION) {\n return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`);\n }\n }\n\n if (handler(this, payload) === false)\n return;\n }\n }\n\n end() {\n this.destroy();\n }\n destroy() {\n if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {\n this.outgoing.state = 'closing';\n this._protocol.channelClose(this.outgoing.id);\n }\n }\n _init() {\n this._init = noop;\n if (!this.server)\n sendOrBuffer(this, CLIENT_VERSION_BUFFER);\n }\n\n // ===========================================================================\n // Client-specific ===========================================================\n // ===========================================================================\n createReadStream(path, options) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n return new ReadStream(this, path, options);\n }\n createWriteStream(path, options) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n return new WriteStream(this, path, options);\n }\n open(path, flags_, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (typeof attrs === 'function') {\n cb = attrs;\n attrs = undefined;\n }\n\n const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_));\n if (flags === null)\n throw new Error(`Unknown flags string: ${flags_}`);\n\n let attrsFlags = 0;\n let attrsLen = 0;\n if (typeof attrs === 'string' || typeof attrs === 'number')\n attrs = { mode: attrs };\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n attrsFlags = attrs.flags;\n attrsLen = attrs.nb;\n }\n\n /*\n uint32 id\n string filename\n uint32 pflags\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.OPEN;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n writeUInt32BE(buf, attrsFlags, p += 4);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN`\n );\n }\n close(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.CLOSE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE`\n );\n }\n read(handle, buf, off, len, position, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n if (!Buffer.isBuffer(buf))\n throw new Error('buffer is not a Buffer');\n if (off >= buf.length)\n throw new Error('offset is out of bounds');\n if (off + len > buf.length)\n throw new Error('length extends beyond buffer');\n if (position === null)\n throw new Error('null position currently unsupported');\n\n read_(this, handle, buf, off, len, position, cb);\n }\n readData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.read(handle, buf, off, len, position, cb);\n }\n write(handle, buf, off, len, position, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n if (!Buffer.isBuffer(buf))\n throw new Error('buffer is not a Buffer');\n if (off > buf.length)\n throw new Error('offset is out of bounds');\n if (off + len > buf.length)\n throw new Error('length extends beyond buffer');\n if (position === null)\n throw new Error('null position currently unsupported');\n\n if (!len) {\n cb && process.nextTick(cb, undefined, 0);\n return;\n }\n\n const maxDataLen = this._maxWriteLen;\n const overflow = Math.max(len - maxDataLen, 0);\n const origPosition = position;\n\n if (overflow)\n len = maxDataLen;\n\n /*\n uint32 id\n string handle\n uint64 offset\n string data\n */\n const handleLen = handle.length;\n let p = 9;\n const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len);\n\n writeUInt32BE(out, out.length - 4, 0);\n out[4] = REQUEST.WRITE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(out, reqid, 5);\n\n writeUInt32BE(out, handleLen, p);\n out.set(handle, p += 4);\n p += handleLen;\n for (let i = 7; i >= 0; --i) {\n out[p + i] = position & 0xFF;\n position /= 256;\n }\n writeUInt32BE(out, len, p += 8);\n bufferCopy(buf, out, off, off + len, p += 4);\n\n this._requests[reqid] = {\n cb: (err) => {\n if (err) {\n if (typeof cb === 'function')\n cb(err);\n } else if (overflow) {\n this.write(handle,\n buf,\n off + len,\n overflow,\n origPosition + len,\n cb);\n } else if (typeof cb === 'function') {\n cb(undefined, off + len);\n }\n }\n };\n\n const isSent = sendOrBuffer(this, out);\n if (this._debug) {\n const how = (isSent ? 'Sent' : 'Buffered');\n this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`);\n }\n }\n writeData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.write(handle, buf, off, len, position, cb);\n }\n fastGet(remotePath, localPath, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n fastXfer(this, fs, remotePath, localPath, opts, cb);\n }\n fastPut(localPath, remotePath, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n fastXfer(fs, this, localPath, remotePath, opts, cb);\n }\n readFile(path, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, flag: 'r' };\n else if (!options)\n options = { encoding: null, flag: 'r' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n const encoding = options.encoding;\n if (encoding && !Buffer.isEncoding(encoding))\n throw new Error(`Unknown encoding: ${encoding}`);\n\n // First stat the file, so we know the size.\n let size;\n let buffer; // Single buffer with file data\n let buffers; // List for when size is unknown\n let pos = 0;\n let handle;\n\n // SFTPv3 does not support using -1 for read position, so we have to track\n // read position manually\n let bytesRead = 0;\n\n const flag = options.flag || 'r';\n\n const read = () => {\n if (size === 0) {\n buffer = Buffer.allocUnsafe(8192);\n this.read(handle, buffer, 0, 8192, bytesRead, afterRead);\n } else {\n this.read(handle, buffer, pos, size - pos, bytesRead, afterRead);\n }\n };\n\n const afterRead = (er, nbytes) => {\n let eof;\n if (er) {\n eof = (er.code === STATUS_CODE.EOF);\n if (!eof) {\n return this.close(handle, () => {\n return callback && callback(er);\n });\n }\n } else {\n eof = false;\n }\n\n if (eof || (size === 0 && nbytes === 0))\n return close();\n\n bytesRead += nbytes;\n pos += nbytes;\n if (size !== 0) {\n if (pos === size)\n close();\n else\n read();\n } else {\n // Unknown size, just read until we don't get bytes.\n buffers.push(bufferSlice(buffer, 0, nbytes));\n read();\n }\n };\n afterRead._wantEOFError = true;\n\n const close = () => {\n this.close(handle, (er) => {\n if (size === 0) {\n // Collect the data into the buffers list.\n buffer = Buffer.concat(buffers, pos);\n } else if (pos < size) {\n buffer = bufferSlice(buffer, 0, pos);\n }\n\n if (encoding)\n buffer = buffer.toString(encoding);\n return callback && callback(er, buffer);\n });\n };\n\n this.open(path, flag, 0o666, (er, handle_) => {\n if (er)\n return callback && callback(er);\n handle = handle_;\n\n const tryStat = (er, st) => {\n if (er) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.stat(path, (er_, st_) => {\n if (er_) {\n return this.close(handle, () => {\n callback && callback(er);\n });\n }\n tryStat(null, st_);\n });\n return;\n }\n\n size = st.size || 0;\n if (size === 0) {\n // The kernel lies about many files.\n // Go ahead and try to read some bytes.\n buffers = [];\n return read();\n }\n\n buffer = Buffer.allocUnsafe(size);\n read();\n };\n this.fstat(handle, tryStat);\n });\n }\n writeFile(path, data, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, mode: 0o666, flag: 'w' };\n else if (!options)\n options = { encoding: 'utf8', mode: 0o666, flag: 'w' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n if (options.encoding && !Buffer.isEncoding(options.encoding))\n throw new Error(`Unknown encoding: ${options.encoding}`);\n\n const flag = options.flag || 'w';\n this.open(path, flag, options.mode, (openErr, handle) => {\n if (openErr) {\n callback && callback(openErr);\n } else {\n const buffer = (Buffer.isBuffer(data)\n ? data\n : Buffer.from('' + data, options.encoding || 'utf8'));\n const position = (/a/.test(flag) ? null : 0);\n\n // SFTPv3 does not support the notion of 'current position'\n // (null position), so we just attempt to append to the end of the file\n // instead\n if (position === null) {\n const tryStat = (er, st) => {\n if (er) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.stat(path, (er_, st_) => {\n if (er_) {\n return this.close(handle, () => {\n callback && callback(er);\n });\n }\n tryStat(null, st_);\n });\n return;\n }\n writeAll(this, handle, buffer, 0, buffer.length, st.size, callback);\n };\n this.fstat(handle, tryStat);\n return;\n }\n writeAll(this, handle, buffer, 0, buffer.length, position, callback);\n }\n });\n }\n appendFile(path, data, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, mode: 0o666, flag: 'a' };\n else if (!options)\n options = { encoding: 'utf8', mode: 0o666, flag: 'a' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n if (!options.flag)\n options = Object.assign({ flag: 'a' }, options);\n this.writeFile(path, data, options, callback);\n }\n exists(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n this.stat(path, (err) => {\n cb && cb(err ? false : true);\n });\n }\n unlink(filename, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string filename\n */\n const fnameLen = Buffer.byteLength(filename);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.REMOVE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, fnameLen, p);\n buf.utf8Write(filename, p += 4, fnameLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE`\n );\n }\n rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RENAME;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, oldLen, p);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME`\n );\n }\n mkdir(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'function') {\n cb = attrs;\n attrs = undefined;\n }\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n }\n\n /*\n uint32 id\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.MKDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR`\n );\n }\n rmdir(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RMDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR`\n );\n }\n readdir(where, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof opts !== 'object' || opts === null)\n opts = {};\n\n const doFilter = (opts && opts.full ? false : true);\n\n if (!Buffer.isBuffer(where) && typeof where !== 'string')\n throw new Error('missing directory handle or path');\n\n if (typeof where === 'string') {\n const entries = [];\n let e = 0;\n\n const reread = (err, handle) => {\n if (err)\n return cb(err);\n\n this.readdir(handle, opts, (err, list) => {\n const eof = (err && err.code === STATUS_CODE.EOF);\n\n if (err && !eof)\n return this.close(handle, () => cb(err));\n\n if (eof) {\n return this.close(handle, (err) => {\n if (err)\n return cb(err);\n cb(undefined, entries);\n });\n }\n\n for (let i = 0; i < list.length; ++i, ++e)\n entries[e] = list[i];\n\n reread(undefined, handle);\n });\n };\n return this.opendir(where, reread);\n }\n\n /*\n uint32 id\n string handle\n */\n const handleLen = where.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.READDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(where, p += 4);\n\n this._requests[reqid] = {\n cb: (doFilter\n ? (err, list) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n\n for (let i = list.length - 1; i >= 0; --i) {\n if (list[i].filename === '.' || list[i].filename === '..')\n list.splice(i, 1);\n }\n\n cb(undefined, list);\n }\n : cb)\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR`\n );\n }\n fstat(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.FSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT`\n );\n }\n stat(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.STAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT`\n );\n }\n lstat(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.LSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT`\n );\n }\n opendir(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.OPENDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR`\n );\n }\n setstat(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.SETSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT`\n );\n }\n fsetstat(handle, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string handle\n ATTRS attrs\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.FSETSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n writeUInt32BE(buf, flags, p += handleLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT`\n );\n }\n futimes(handle, atime, mtime, cb) {\n return this.fsetstat(handle, {\n atime: toUnixTimestamp(atime),\n mtime: toUnixTimestamp(mtime)\n }, cb);\n }\n utimes(path, atime, mtime, cb) {\n return this.setstat(path, {\n atime: toUnixTimestamp(atime),\n mtime: toUnixTimestamp(mtime)\n }, cb);\n }\n fchown(handle, uid, gid, cb) {\n return this.fsetstat(handle, {\n uid: uid,\n gid: gid\n }, cb);\n }\n chown(path, uid, gid, cb) {\n return this.setstat(path, {\n uid: uid,\n gid: gid\n }, cb);\n }\n fchmod(handle, mode, cb) {\n return this.fsetstat(handle, {\n mode: mode\n }, cb);\n }\n chmod(path, mode, cb) {\n return this.setstat(path, {\n mode: mode\n }, cb);\n }\n readlink(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.READLINK;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing link info'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK`\n );\n }\n symlink(targetPath, linkPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string linkpath\n string targetpath\n */\n const linkLen = Buffer.byteLength(linkPath);\n const targetLen = Buffer.byteLength(targetPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.SYMLINK;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n if (this._isOpenSSH) {\n // OpenSSH has linkpath and targetpath positions switched\n writeUInt32BE(buf, targetLen, p);\n buf.utf8Write(targetPath, p += 4, targetLen);\n writeUInt32BE(buf, linkLen, p += targetLen);\n buf.utf8Write(linkPath, p += 4, linkLen);\n } else {\n writeUInt32BE(buf, linkLen, p);\n buf.utf8Write(linkPath, p += 4, linkLen);\n writeUInt32BE(buf, targetLen, p += linkLen);\n buf.utf8Write(targetPath, p += 4, targetLen);\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK`\n );\n }\n realpath(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.REALPATH;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing path info'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH`\n );\n }\n // extended requests\n ext_openssh_rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['posix-rename@openssh.com'];\n if (!ext || ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"posix-rename@openssh.com\"\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 24, p);\n buf.utf8Write('posix-rename@openssh.com', p += 4, 24);\n writeUInt32BE(buf, oldLen, p += 24);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`);\n }\n }\n ext_openssh_statvfs(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['statvfs@openssh.com'];\n if (!ext || ext !== '2')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"statvfs@openssh.com\"\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 19, p);\n buf.utf8Write('statvfs@openssh.com', p += 4, 19);\n writeUInt32BE(buf, pathLen, p += 19);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { extended: 'statvfs@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`);\n }\n }\n ext_openssh_fstatvfs(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['fstatvfs@openssh.com'];\n if (!ext || ext !== '2')\n throw new Error('Server does not support this extended request');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string \"fstatvfs@openssh.com\"\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('fstatvfs@openssh.com', p += 4, 20);\n writeUInt32BE(buf, handleLen, p += 20);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`);\n }\n }\n ext_openssh_hardlink(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['hardlink@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"hardlink@openssh.com\"\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('hardlink@openssh.com', p += 4, 20);\n writeUInt32BE(buf, oldLen, p += 20);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`);\n }\n }\n ext_openssh_fsync(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['fsync@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string \"fsync@openssh.com\"\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 17, p);\n buf.utf8Write('fsync@openssh.com', p += 4, 17);\n writeUInt32BE(buf, handleLen, p += 17);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com`\n );\n }\n ext_openssh_lsetstat(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['lsetstat@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string \"lsetstat@openssh.com\"\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('lsetstat@openssh.com', p += 4, 20);\n\n writeUInt32BE(buf, pathLen, p += 20);\n buf.utf8Write(path, p += 4, pathLen);\n\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`);\n }\n }\n ext_openssh_expandPath(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['expand-path@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"expand-path@openssh.com\"\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 23, p);\n buf.utf8Write('expand-path@openssh.com', p += 4, 23);\n\n writeUInt32BE(buf, pathLen, p += 20);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`);\n }\n }\n // ===========================================================================\n // Server-specific ===========================================================\n // ===========================================================================\n handle(reqid, handle) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n const handleLen = handle.length;\n\n if (handleLen > 256)\n throw new Error('handle too large (> 256 bytes)');\n\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.HANDLE;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n if (handleLen)\n buf.set(handle, p += 4);\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE`\n );\n }\n status(reqid, code, message) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!VALID_STATUS_CODES.has(code))\n throw new Error(`Bad status code: ${code}`);\n\n message || (message = '');\n\n const msgLen = Buffer.byteLength(message);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.STATUS;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, code, p);\n\n writeUInt32BE(buf, msgLen, p += 4);\n p += 4;\n if (msgLen) {\n buf.utf8Write(message, p, msgLen);\n p += msgLen;\n }\n\n writeUInt32BE(buf, 0, p); // Empty language tag\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS`\n );\n }\n data(reqid, data, encoding) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n const isBuffer = Buffer.isBuffer(data);\n\n if (!isBuffer && typeof data !== 'string')\n throw new Error('data is not a Buffer or string');\n\n let isUTF8;\n if (!isBuffer && !encoding) {\n encoding = undefined;\n isUTF8 = true;\n }\n\n const dataLen = (\n isBuffer\n ? data.length\n : Buffer.byteLength(data, encoding)\n );\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.DATA;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, dataLen, p);\n if (dataLen) {\n if (isBuffer)\n buf.set(data, p += 4);\n else if (isUTF8)\n buf.utf8Write(data, p += 4, dataLen);\n else\n buf.write(data, p += 4, dataLen, encoding);\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA`\n );\n }\n name(reqid, names) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!Array.isArray(names)) {\n if (typeof names !== 'object' || names === null)\n throw new Error('names is not an object or array');\n names = [ names ];\n }\n\n const count = names.length;\n let namesLen = 0;\n let nameAttrs;\n const attrs = [];\n\n for (let i = 0; i < count; ++i) {\n const name = names[i];\n const filename = (\n !name || !name.filename || typeof name.filename !== 'string'\n ? ''\n : name.filename\n );\n namesLen += 4 + Buffer.byteLength(filename);\n const longname = (\n !name || !name.longname || typeof name.longname !== 'string'\n ? ''\n : name.longname\n );\n namesLen += 4 + Buffer.byteLength(longname);\n\n if (typeof name.attrs === 'object' && name.attrs !== null) {\n nameAttrs = attrsToBytes(name.attrs);\n namesLen += 4 + nameAttrs.nb;\n\n if (nameAttrs.nb) {\n let bytes;\n\n if (nameAttrs.nb === ATTRS_BUF.length) {\n bytes = new Uint8Array(ATTRS_BUF);\n } else {\n bytes = new Uint8Array(nameAttrs.nb);\n bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0);\n }\n\n nameAttrs.bytes = bytes;\n }\n\n attrs.push(nameAttrs);\n } else {\n namesLen += 4;\n attrs.push(null);\n }\n }\n\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.NAME;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, count, p);\n\n p += 4;\n\n for (let i = 0; i < count; ++i) {\n const name = names[i];\n\n {\n const filename = (\n !name || !name.filename || typeof name.filename !== 'string'\n ? ''\n : name.filename\n );\n const len = Buffer.byteLength(filename);\n writeUInt32BE(buf, len, p);\n p += 4;\n if (len) {\n buf.utf8Write(filename, p, len);\n p += len;\n }\n }\n\n {\n const longname = (\n !name || !name.longname || typeof name.longname !== 'string'\n ? ''\n : name.longname\n );\n const len = Buffer.byteLength(longname);\n writeUInt32BE(buf, len, p);\n p += 4;\n if (len) {\n buf.utf8Write(longname, p, len);\n p += len;\n }\n }\n\n const attr = attrs[i];\n if (attr) {\n writeUInt32BE(buf, attr.flags, p);\n p += 4;\n if (attr.flags && attr.bytes) {\n buf.set(attr.bytes, p);\n p += attr.nb;\n }\n } else {\n writeUInt32BE(buf, 0, p);\n p += 4;\n }\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME`\n );\n }\n attrs(reqid, attrs) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (typeof attrs !== 'object' || attrs === null)\n throw new Error('attrs is not an object');\n\n attrs = attrsToBytes(attrs);\n const flags = attrs.flags;\n const attrsLen = attrs.nb;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.ATTRS;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, flags, p);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS`\n );\n }\n}\n\nfunction tryCreateBuffer(size) {\n try {\n return Buffer.allocUnsafe(size);\n } catch (ex) {\n return ex;\n }\n}\n\nfunction read_(self, handle, buf, off, len, position, cb, req_) {\n const maxDataLen = self._maxReadLen;\n const overflow = Math.max(len - maxDataLen, 0);\n\n if (overflow)\n len = maxDataLen;\n\n /*\n uint32 id\n string handle\n uint64 offset\n uint32 len\n */\n const handleLen = handle.length;\n let p = 9;\n let pos = position;\n const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4);\n\n writeUInt32BE(out, out.length - 4, 0);\n out[4] = REQUEST.READ;\n const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(out, reqid, 5);\n\n writeUInt32BE(out, handleLen, p);\n out.set(handle, p += 4);\n p += handleLen;\n for (let i = 7; i >= 0; --i) {\n out[p + i] = pos & 0xFF;\n pos /= 256;\n }\n writeUInt32BE(out, len, p += 8);\n\n if (typeof cb !== 'function')\n cb = noop;\n\n const req = (req_ || {\n nb: 0,\n position,\n off,\n origOff: off,\n len: undefined,\n overflow: undefined,\n cb: (err, data, nb) => {\n const len = req.len;\n const overflow = req.overflow;\n\n if (err) {\n if (cb._wantEOFError || err.code !== STATUS_CODE.EOF)\n return cb(err);\n } else if (nb > len) {\n return cb(new Error('Received more data than requested'));\n } else if (nb === len && overflow) {\n req.nb += nb;\n req.position += nb;\n req.off += nb;\n read_(self, handle, buf, req.off, overflow, req.position, cb, req);\n return;\n }\n\n if (req.origOff === 0 && buf.length === req.nb)\n data = buf;\n else\n data = bufferSlice(buf, req.origOff, req.origOff + req.nb);\n cb(undefined, req.nb + (nb || 0), data, req.position);\n },\n buffer: undefined,\n });\n\n req.len = len;\n req.overflow = overflow;\n\n // TODO: avoid creating multiple buffer slices when we need to re-call read_()\n // because of overflow\n req.buffer = bufferSlice(buf, off, off + len);\n\n self._requests[reqid] = req;\n\n const isBuffered = sendOrBuffer(self, out);\n self._debug && self._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ`\n );\n}\n\nfunction fastXfer(src, dst, srcPath, dstPath, opts, cb) {\n let concurrency = 64;\n let chunkSize = 32768;\n let onstep;\n let mode;\n let fileSize;\n\n if (typeof opts === 'function') {\n cb = opts;\n } else if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.concurrency === 'number'\n && opts.concurrency > 0\n && !isNaN(opts.concurrency)) {\n concurrency = opts.concurrency;\n }\n if (typeof opts.chunkSize === 'number'\n && opts.chunkSize > 0\n && !isNaN(opts.chunkSize)) {\n chunkSize = opts.chunkSize;\n }\n if (typeof opts.fileSize === 'number'\n && opts.fileSize > 0\n && !isNaN(opts.fileSize)) {\n fileSize = opts.fileSize;\n }\n if (typeof opts.step === 'function')\n onstep = opts.step;\n\n if (typeof opts.mode === 'string' || typeof opts.mode === 'number')\n mode = modeNum(opts.mode);\n }\n\n // Internal state variables\n let fsize;\n let pdst = 0;\n let total = 0;\n let hadError = false;\n let srcHandle;\n let dstHandle;\n let readbuf;\n let bufsize = chunkSize * concurrency;\n\n function onerror(err) {\n if (hadError)\n return;\n\n hadError = true;\n\n let left = 0;\n let cbfinal;\n\n if (srcHandle || dstHandle) {\n cbfinal = () => {\n if (--left === 0)\n cb(err);\n };\n if (srcHandle && (src === fs || src.outgoing.state === 'open'))\n ++left;\n if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))\n ++left;\n if (srcHandle && (src === fs || src.outgoing.state === 'open'))\n src.close(srcHandle, cbfinal);\n if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))\n dst.close(dstHandle, cbfinal);\n } else {\n cb(err);\n }\n }\n\n src.open(srcPath, 'r', (err, sourceHandle) => {\n if (err)\n return onerror(err);\n\n srcHandle = sourceHandle;\n\n if (fileSize === undefined)\n src.fstat(srcHandle, tryStat);\n else\n tryStat(null, { size: fileSize });\n\n function tryStat(err, attrs) {\n if (err) {\n if (src !== fs) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n src.stat(srcPath, (err_, attrs_) => {\n if (err_)\n return onerror(err);\n tryStat(null, attrs_);\n });\n return;\n }\n return onerror(err);\n }\n fsize = attrs.size;\n\n dst.open(dstPath, 'w', (err, destHandle) => {\n if (err)\n return onerror(err);\n\n dstHandle = destHandle;\n\n if (fsize <= 0)\n return onerror();\n\n // Use less memory where possible\n while (bufsize > fsize) {\n if (concurrency === 1) {\n bufsize = fsize;\n break;\n }\n bufsize -= chunkSize;\n --concurrency;\n }\n\n readbuf = tryCreateBuffer(bufsize);\n if (readbuf instanceof Error)\n return onerror(readbuf);\n\n if (mode !== undefined) {\n dst.fchmod(dstHandle, mode, function tryAgain(err) {\n if (err) {\n // Try chmod() for sftp servers that may not support fchmod()\n // for whatever reason\n dst.chmod(dstPath, mode, (err_) => tryAgain());\n return;\n }\n startReads();\n });\n } else {\n startReads();\n }\n\n function onread(err, nb, data, dstpos, datapos, origChunkLen) {\n if (err)\n return onerror(err);\n\n datapos = datapos || 0;\n\n dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb);\n\n function writeCb(err) {\n if (err)\n return onerror(err);\n\n total += nb;\n onstep && onstep(total, nb, fsize);\n\n if (nb < origChunkLen)\n return singleRead(datapos, dstpos + nb, origChunkLen - nb);\n\n if (total === fsize) {\n dst.close(dstHandle, (err) => {\n dstHandle = undefined;\n if (err)\n return onerror(err);\n src.close(srcHandle, (err) => {\n srcHandle = undefined;\n if (err)\n return onerror(err);\n cb();\n });\n });\n return;\n }\n\n if (pdst >= fsize)\n return;\n\n const chunk =\n (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);\n singleRead(datapos, pdst, chunk);\n pdst += chunk;\n }\n }\n\n function makeCb(psrc, pdst, chunk) {\n return (err, nb, data) => {\n onread(err, nb, data, pdst, psrc, chunk);\n };\n }\n\n function singleRead(psrc, pdst, chunk) {\n src.read(srcHandle,\n readbuf,\n psrc,\n chunk,\n pdst,\n makeCb(psrc, pdst, chunk));\n }\n\n function startReads() {\n let reads = 0;\n let psrc = 0;\n while (pdst < fsize && reads < concurrency) {\n const chunk =\n (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);\n singleRead(psrc, pdst, chunk);\n psrc += chunk;\n pdst += chunk;\n ++reads;\n }\n }\n });\n }\n });\n}\n\nfunction writeAll(sftp, handle, buffer, offset, length, position, callback_) {\n const callback = (typeof callback_ === 'function' ? callback_ : undefined);\n\n sftp.write(handle,\n buffer,\n offset,\n length,\n position,\n (writeErr, written) => {\n if (writeErr) {\n return sftp.close(handle, () => {\n callback && callback(writeErr);\n });\n }\n if (written === length) {\n sftp.close(handle, callback);\n } else {\n offset += written;\n length -= written;\n position += written;\n writeAll(sftp, handle, buffer, offset, length, position, callback);\n }\n });\n}\n\nclass Stats {\n constructor(initial) {\n this.mode = (initial && initial.mode);\n this.uid = (initial && initial.uid);\n this.gid = (initial && initial.gid);\n this.size = (initial && initial.size);\n this.atime = (initial && initial.atime);\n this.mtime = (initial && initial.mtime);\n this.extended = (initial && initial.extended);\n }\n isDirectory() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFDIR);\n }\n isFile() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFREG);\n }\n isBlockDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFBLK);\n }\n isCharacterDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFCHR);\n }\n isSymbolicLink() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFLNK);\n }\n isFIFO() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFIFO);\n }\n isSocket() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK);\n }\n}\n\nfunction attrsToBytes(attrs) {\n let flags = 0;\n let nb = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n if (typeof attrs.size === 'number') {\n flags |= ATTR.SIZE;\n const val = attrs.size;\n // Big Endian\n ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56\n ATTRS_BUF[nb++] = val / 281474976710656; // 2**48\n ATTRS_BUF[nb++] = val / 1099511627776; // 2**40\n ATTRS_BUF[nb++] = val / 4294967296; // 2**32\n ATTRS_BUF[nb++] = val / 16777216; // 2**24\n ATTRS_BUF[nb++] = val / 65536; // 2**16\n ATTRS_BUF[nb++] = val / 256; // 2**8\n ATTRS_BUF[nb++] = val;\n }\n if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') {\n flags |= ATTR.UIDGID;\n const uid = attrs.uid;\n const gid = attrs.gid;\n // Big Endian\n ATTRS_BUF[nb++] = uid >>> 24;\n ATTRS_BUF[nb++] = uid >>> 16;\n ATTRS_BUF[nb++] = uid >>> 8;\n ATTRS_BUF[nb++] = uid;\n ATTRS_BUF[nb++] = gid >>> 24;\n ATTRS_BUF[nb++] = gid >>> 16;\n ATTRS_BUF[nb++] = gid >>> 8;\n ATTRS_BUF[nb++] = gid;\n }\n if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') {\n const mode = modeNum(attrs.mode);\n flags |= ATTR.PERMISSIONS;\n // Big Endian\n ATTRS_BUF[nb++] = mode >>> 24;\n ATTRS_BUF[nb++] = mode >>> 16;\n ATTRS_BUF[nb++] = mode >>> 8;\n ATTRS_BUF[nb++] = mode;\n }\n if ((typeof attrs.atime === 'number' || isDate(attrs.atime))\n && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) {\n const atime = toUnixTimestamp(attrs.atime);\n const mtime = toUnixTimestamp(attrs.mtime);\n\n flags |= ATTR.ACMODTIME;\n // Big Endian\n ATTRS_BUF[nb++] = atime >>> 24;\n ATTRS_BUF[nb++] = atime >>> 16;\n ATTRS_BUF[nb++] = atime >>> 8;\n ATTRS_BUF[nb++] = atime;\n ATTRS_BUF[nb++] = mtime >>> 24;\n ATTRS_BUF[nb++] = mtime >>> 16;\n ATTRS_BUF[nb++] = mtime >>> 8;\n ATTRS_BUF[nb++] = mtime;\n }\n // TODO: extended attributes\n }\n\n return { flags, nb };\n}\n\nfunction toUnixTimestamp(time) {\n // eslint-disable-next-line no-self-compare\n if (typeof time === 'number' && time === time) // Valid, non-NaN number\n return time;\n if (isDate(time))\n return parseInt(time.getTime() / 1000, 10);\n throw new Error(`Cannot parse time: ${time}`);\n}\n\nfunction modeNum(mode) {\n // eslint-disable-next-line no-self-compare\n if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number\n return mode;\n if (typeof mode === 'string')\n return modeNum(parseInt(mode, 8));\n throw new Error(`Cannot parse mode: ${mode}`);\n}\n\nconst stringFlagMap = {\n 'r': OPEN_MODE.READ,\n 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE,\n 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE,\n 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL\n};\n\nfunction stringToFlags(str) {\n const flags = stringFlagMap[str];\n return (flags !== undefined ? flags : null);\n}\n\nconst flagsToString = (() => {\n const stringFlagMapKeys = Object.keys(stringFlagMap);\n return (flags) => {\n for (let i = 0; i < stringFlagMapKeys.length; ++i) {\n const key = stringFlagMapKeys[i];\n if (stringFlagMap[key] === flags)\n return key;\n }\n return null;\n };\n})();\n\nfunction readAttrs(biOpt) {\n /*\n uint32 flags\n uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE\n uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID\n uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID\n uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS\n uint32 atime present only if flag SSH_FILEXFER_ACMODTIME\n uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME\n uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED\n string extended_type\n string extended_data\n ... more extended data (extended_type - extended_data pairs),\n so that number of pairs equals extended_count\n */\n const flags = bufferParser.readUInt32BE();\n if (flags === undefined)\n return;\n\n const attrs = new Stats();\n if (flags & ATTR.SIZE) {\n const size = bufferParser.readUInt64BE(biOpt);\n if (size === undefined)\n return;\n attrs.size = size;\n }\n\n if (flags & ATTR.UIDGID) {\n const uid = bufferParser.readUInt32BE();\n const gid = bufferParser.readUInt32BE();\n if (gid === undefined)\n return;\n attrs.uid = uid;\n attrs.gid = gid;\n }\n\n if (flags & ATTR.PERMISSIONS) {\n const mode = bufferParser.readUInt32BE();\n if (mode === undefined)\n return;\n attrs.mode = mode;\n }\n\n if (flags & ATTR.ACMODTIME) {\n const atime = bufferParser.readUInt32BE();\n const mtime = bufferParser.readUInt32BE();\n if (mtime === undefined)\n return;\n attrs.atime = atime;\n attrs.mtime = mtime;\n }\n\n if (flags & ATTR.EXTENDED) {\n const count = bufferParser.readUInt32BE();\n if (count === undefined)\n return;\n const extended = {};\n for (let i = 0; i < count; ++i) {\n const type = bufferParser.readString(true);\n const data = bufferParser.readString();\n if (data === undefined)\n return;\n extended[type] = data;\n }\n attrs.extended = extended;\n }\n\n return attrs;\n}\n\nfunction sendOrBuffer(sftp, payload) {\n const ret = tryWritePayload(sftp, payload);\n if (ret !== undefined) {\n sftp._buffer.push(ret);\n return false;\n }\n return true;\n}\n\nfunction tryWritePayload(sftp, payload) {\n const outgoing = sftp.outgoing;\n if (outgoing.state !== 'open')\n return;\n\n if (outgoing.window === 0) {\n sftp._waitWindow = true; // XXX: Unnecessary?\n return payload;\n }\n\n let ret;\n const len = payload.length;\n let p = 0;\n\n while (len - p > 0 && outgoing.window > 0) {\n const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize);\n outgoing.window -= actualLen;\n if (outgoing.window === 0) {\n sftp._waitWindow = true;\n sftp._chunkcb = drainBuffer;\n }\n\n if (p === 0 && actualLen === len) {\n sftp._protocol.channelData(sftp.outgoing.id, payload);\n } else {\n sftp._protocol.channelData(sftp.outgoing.id,\n bufferSlice(payload, p, p + actualLen));\n }\n\n p += actualLen;\n }\n\n if (len - p > 0) {\n if (p > 0)\n ret = bufferSlice(payload, p, len);\n else\n ret = payload; // XXX: should never get here?\n }\n\n return ret;\n}\n\nfunction drainBuffer() {\n this._chunkcb = undefined;\n const buffer = this._buffer;\n let i = 0;\n while (i < buffer.length) {\n const payload = buffer[i];\n const ret = tryWritePayload(this, payload);\n if (ret !== undefined) {\n if (ret !== payload)\n buffer[i] = ret;\n if (i > 0)\n this._buffer = buffer.slice(i);\n return;\n }\n ++i;\n }\n if (i > 0)\n this._buffer = [];\n}\n\nfunction doFatalSFTPError(sftp, msg, noDebug) {\n const err = new Error(msg);\n err.level = 'sftp-protocol';\n if (!noDebug && sftp._debug)\n sftp._debug(`SFTP: Inbound: ${msg}`);\n sftp.emit('error', err);\n sftp.destroy();\n cleanupRequests(sftp);\n return false;\n}\n\nfunction cleanupRequests(sftp) {\n const keys = Object.keys(sftp._requests);\n if (keys.length === 0)\n return;\n\n const reqs = sftp._requests;\n sftp._requests = {};\n const err = new Error('No response from server');\n for (let i = 0; i < keys.length; ++i) {\n const req = reqs[keys[i]];\n if (typeof req.cb === 'function')\n req.cb(err);\n }\n}\n\nfunction requestLimits(sftp, cb) {\n /*\n uint32 id\n string \"limits@openssh.com\"\n */\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 18, p);\n buf.utf8Write('limits@openssh.com', p += 4, 18);\n\n sftp._requests[reqid] = { extended: 'limits@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(sftp, buf);\n if (sftp._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`);\n }\n}\n\nconst CLIENT_HANDLERS = {\n [RESPONSE.VERSION]: (sftp, payload) => {\n if (sftp._version !== -1)\n return doFatalSFTPError(sftp, 'Duplicate VERSION packet');\n\n const extensions = {};\n\n /*\n uint32 version\n \n */\n bufferParser.init(payload, 1);\n let version = bufferParser.readUInt32BE();\n while (bufferParser.avail()) {\n const extName = bufferParser.readString(true);\n const extData = bufferParser.readString(true);\n if (extData === undefined) {\n version = undefined;\n break;\n }\n extensions[extName] = extData;\n }\n bufferParser.clear();\n\n if (version === undefined)\n return doFatalSFTPError(sftp, 'Malformed VERSION packet');\n\n if (sftp._debug) {\n const names = Object.keys(extensions);\n if (names.length) {\n sftp._debug(\n `SFTP: Inbound: Received VERSION (v${version}, exts:${names})`\n );\n } else {\n sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`);\n }\n }\n\n sftp._version = version;\n sftp._extensions = extensions;\n\n if (extensions['limits@openssh.com'] === '1') {\n return requestLimits(sftp, (err, limits) => {\n if (!err) {\n if (limits.maxPktLen > 0)\n sftp._maxOutPktLen = limits.maxPktLen;\n if (limits.maxReadLen > 0)\n sftp._maxReadLen = limits.maxReadLen;\n if (limits.maxWriteLen > 0)\n sftp._maxWriteLen = limits.maxWriteLen;\n sftp.maxOpenHandles = (\n limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity\n );\n }\n sftp.emit('ready');\n });\n }\n\n sftp.emit('ready');\n },\n [RESPONSE.STATUS]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n uint32 error/status code\n string error message (ISO-10646 UTF-8)\n string language tag\n */\n const errorCode = bufferParser.readUInt32BE();\n const errorMsg = bufferParser.readString(true);\n bufferParser.clear();\n\n // Note: we avoid checking that the error message and language tag are in\n // the packet because there are some broken implementations that incorrectly\n // omit them. The language tag in general was never really used amongst ssh\n // implementations, so in the case of a missing error message we just\n // default to something sensible.\n\n if (sftp._debug) {\n const jsonMsg = JSON.stringify(errorMsg);\n sftp._debug(\n `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})`\n );\n }\n const req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n if (req && typeof req.cb === 'function') {\n if (errorCode === STATUS_CODE.OK) {\n req.cb();\n return;\n }\n const err = new Error(errorMsg\n || STATUS_CODE_STR[errorCode]\n || 'Unknown status');\n err.code = errorCode;\n req.cb(err);\n }\n },\n [RESPONSE.HANDLE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined) {\n if (reqID !== undefined)\n delete sftp._requests[reqID];\n return doFatalSFTPError(sftp, 'Malformed HANDLE packet');\n }\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`);\n\n const req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n if (req && typeof req.cb === 'function')\n req.cb(undefined, handle);\n },\n [RESPONSE.DATA]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n string data\n */\n if (req && typeof req.cb === 'function') {\n if (req.buffer) {\n // We have already pre-allocated space to store the data\n\n const nb = bufferParser.readString(req.buffer);\n bufferParser.clear();\n\n if (nb !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`\n );\n req.cb(undefined, req.buffer, nb);\n return;\n }\n } else {\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})`\n );\n req.cb(undefined, data);\n return;\n }\n }\n } else {\n const nb = bufferParser.skipString();\n bufferParser.clear();\n if (nb !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`\n );\n return;\n }\n }\n\n return doFatalSFTPError(sftp, 'Malformed DATA packet');\n },\n [RESPONSE.NAME]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n uint32 count\n repeats count times:\n string filename\n string longname\n ATTRS attrs\n */\n const count = bufferParser.readUInt32BE();\n if (count !== undefined) {\n let names = [];\n for (let i = 0; i < count; ++i) {\n // We are going to assume UTF-8 for filenames despite the SFTPv3\n // spec not specifying an encoding because the specs for newer\n // versions of the protocol all explicitly specify UTF-8 for\n // filenames\n const filename = bufferParser.readString(true);\n\n // `longname` only exists in SFTPv3 and since it typically will\n // contain the filename, we assume it is also UTF-8\n const longname = bufferParser.readString(true);\n\n const attrs = readAttrs(sftp._biOpt);\n if (attrs === undefined) {\n names = undefined;\n break;\n }\n names.push({ filename, longname, attrs });\n }\n if (names !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})`\n );\n bufferParser.clear();\n if (req && typeof req.cb === 'function')\n req.cb(undefined, names);\n return;\n }\n }\n\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed NAME packet');\n },\n [RESPONSE.ATTRS]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n ATTRS attrs\n */\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n if (attrs !== undefined) {\n sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`);\n if (req && typeof req.cb === 'function')\n req.cb(undefined, attrs);\n return;\n }\n\n return doFatalSFTPError(sftp, 'Malformed ATTRS packet');\n },\n [RESPONSE.EXTENDED]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n if (reqID !== undefined) {\n const req = sftp._requests[reqID];\n if (req) {\n delete sftp._requests[reqID];\n switch (req.extended) {\n case 'statvfs@openssh.com':\n case 'fstatvfs@openssh.com': {\n /*\n uint64 f_bsize // file system block size\n uint64 f_frsize // fundamental fs block size\n uint64 f_blocks // number of blocks (unit f_frsize)\n uint64 f_bfree // free blocks in file system\n uint64 f_bavail // free blocks for non-root\n uint64 f_files // total file inodes\n uint64 f_ffree // free file inodes\n uint64 f_favail // free file inodes for to non-root\n uint64 f_fsid // file system id\n uint64 f_flag // bit mask of f_flag values\n uint64 f_namemax // maximum filename length\n */\n const biOpt = sftp._biOpt;\n const stats = {\n f_bsize: bufferParser.readUInt64BE(biOpt),\n f_frsize: bufferParser.readUInt64BE(biOpt),\n f_blocks: bufferParser.readUInt64BE(biOpt),\n f_bfree: bufferParser.readUInt64BE(biOpt),\n f_bavail: bufferParser.readUInt64BE(biOpt),\n f_files: bufferParser.readUInt64BE(biOpt),\n f_ffree: bufferParser.readUInt64BE(biOpt),\n f_favail: bufferParser.readUInt64BE(biOpt),\n f_sid: bufferParser.readUInt64BE(biOpt),\n f_flag: bufferParser.readUInt64BE(biOpt),\n f_namemax: bufferParser.readUInt64BE(biOpt),\n };\n if (stats.f_namemax === undefined)\n break;\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, stats);\n return;\n }\n case 'limits@openssh.com': {\n /*\n uint64 max-packet-length\n uint64 max-read-length\n uint64 max-write-length\n uint64 max-open-handles\n */\n const limits = {\n maxPktLen: bufferParser.readUInt64BE(),\n maxReadLen: bufferParser.readUInt64BE(),\n maxWriteLen: bufferParser.readUInt64BE(),\n maxOpenHandles: bufferParser.readUInt64BE(),\n };\n if (limits.maxOpenHandles === undefined)\n break;\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, limits);\n return;\n }\n default:\n // Unknown extended request\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`\n );\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb();\n return;\n }\n } else {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`\n );\n bufferParser.clear();\n return;\n }\n }\n\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet');\n },\n};\nconst SERVER_HANDLERS = {\n [REQUEST.INIT]: (sftp, payload) => {\n if (sftp._version !== -1)\n return doFatalSFTPError(sftp, 'Duplicate INIT packet');\n\n const extensions = {};\n\n /*\n uint32 version\n \n */\n bufferParser.init(payload, 1);\n let version = bufferParser.readUInt32BE();\n while (bufferParser.avail()) {\n const extName = bufferParser.readString(true);\n const extData = bufferParser.readString(true);\n if (extData === undefined) {\n version = undefined;\n break;\n }\n extensions[extName] = extData;\n }\n bufferParser.clear();\n\n if (version === undefined)\n return doFatalSFTPError(sftp, 'Malformed INIT packet');\n\n if (sftp._debug) {\n const names = Object.keys(extensions);\n if (names.length) {\n sftp._debug(\n `SFTP: Inbound: Received INIT (v${version}, exts:${names})`\n );\n } else {\n sftp._debug(`SFTP: Inbound: Received INIT (v${version})`);\n }\n }\n\n sendOrBuffer(sftp, SERVER_VERSION_BUFFER);\n\n sftp._version = version;\n sftp._extensions = extensions;\n sftp.emit('ready');\n },\n [REQUEST.OPEN]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string filename\n uint32 pflags\n ATTRS attrs\n */\n const filename = bufferParser.readString(true);\n const pflags = bufferParser.readUInt32BE();\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed OPEN packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`);\n\n if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.CLOSE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed CLOSE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`);\n\n if (!sftp.emit('CLOSE', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READ]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n uint64 offset\n uint32 len\n */\n const handle = bufferParser.readString();\n const offset = bufferParser.readUInt64BE(sftp._biOpt);\n const len = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (len === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed READ packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`);\n\n if (!sftp.emit('READ', reqID, handle, offset, len)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.WRITE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n uint64 offset\n string data\n */\n const handle = bufferParser.readString();\n const offset = bufferParser.readUInt64BE(sftp._biOpt);\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed WRITE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`);\n\n if (!sftp.emit('WRITE', reqID, handle, offset, data)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.LSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed LSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`);\n\n if (!sftp.emit('LSTAT', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.FSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed FSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`);\n\n if (!sftp.emit('FSTAT', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.SETSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n ATTRS attrs\n */\n const path = bufferParser.readString(true);\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed SETSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`);\n\n if (!sftp.emit('SETSTAT', reqID, path, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.FSETSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n ATTRS attrs\n */\n const handle = bufferParser.readString();\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received FSETSTAT (id:${reqID})`\n );\n\n if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.OPENDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed OPENDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`);\n\n if (!sftp.emit('OPENDIR', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed READDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`);\n\n if (!sftp.emit('READDIR', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.REMOVE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed REMOVE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`);\n\n if (!sftp.emit('REMOVE', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.MKDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n ATTRS attrs\n */\n const path = bufferParser.readString(true);\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed MKDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`);\n\n if (!sftp.emit('MKDIR', reqID, path, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.RMDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed RMDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`);\n\n if (!sftp.emit('RMDIR', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.REALPATH]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed REALPATH packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received REALPATH (id:${reqID})`\n );\n\n if (!sftp.emit('REALPATH', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.STAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed STAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`);\n\n if (!sftp.emit('STAT', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.RENAME]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string oldpath\n string newpath\n */\n const oldPath = bufferParser.readString(true);\n const newPath = bufferParser.readString(true);\n bufferParser.clear();\n\n if (newPath === undefined)\n return doFatalSFTPError(sftp, 'Malformed RENAME packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`);\n\n if (!sftp.emit('RENAME', reqID, oldPath, newPath)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READLINK]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed READLINK packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received READLINK (id:${reqID})`\n );\n\n if (!sftp.emit('READLINK', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.SYMLINK]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string linkpath\n string targetpath\n */\n const linkPath = bufferParser.readString(true);\n const targetPath = bufferParser.readString(true);\n bufferParser.clear();\n\n if (targetPath === undefined)\n return doFatalSFTPError(sftp, 'Malformed SYMLINK packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`);\n\n let handled;\n if (sftp._isOpenSSH) {\n // OpenSSH has linkpath and targetpath positions switched\n handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath);\n } else {\n handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath);\n }\n if (!handled) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.EXTENDED]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string extended-request\n ... any request-specific data ...\n */\n const extName = bufferParser.readString(true);\n if (extName === undefined) {\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed EXTENDED packet');\n }\n\n let extData;\n if (bufferParser.avail())\n extData = bufferParser.readRaw();\n bufferParser.clear();\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED (id:${reqID})`\n );\n\n if (!sftp.emit('EXTENDED', reqID, extName, extData)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n};\n\n// =============================================================================\n// ReadStream/WriteStream-related ==============================================\n// =============================================================================\nconst {\n ERR_INVALID_ARG_TYPE,\n ERR_OUT_OF_RANGE,\n validateNumber\n} = require('./node-fs-compat');\n\nconst kMinPoolSpace = 128;\n\nlet pool;\n// It can happen that we expect to read a large chunk of data, and reserve\n// a large chunk of the pool accordingly, but the read() call only filled\n// a portion of it. If a concurrently executing read() then uses the same pool,\n// the \"reserved\" portion cannot be used, so we allow it to be re-used as a\n// new pool later.\nconst poolFragments = [];\n\nfunction allocNewPool(poolSize) {\n if (poolFragments.length > 0)\n pool = poolFragments.pop();\n else\n pool = Buffer.allocUnsafe(poolSize);\n pool.used = 0;\n}\n\n// Check the `this.start` and `this.end` of stream.\nfunction checkPosition(pos, name) {\n if (!Number.isSafeInteger(pos)) {\n validateNumber(pos, name);\n if (!Number.isInteger(pos))\n throw new ERR_OUT_OF_RANGE(name, 'an integer', pos);\n throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);\n }\n if (pos < 0)\n throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);\n}\n\nfunction roundUpToMultipleOf8(n) {\n return (n + 7) & ~7; // Align to 8 byte boundary.\n}\n\nfunction ReadStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // A little bit bigger buffer and water marks by default\n if (options.highWaterMark === undefined)\n options.highWaterMark = 64 * 1024;\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n options.autoDestroy = false; // Node 14 major change.\n\n ReadableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'r' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.end = options.end;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesRead = 0;\n this.closed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (this.end === undefined) {\n this.end = Infinity;\n } else if (this.end !== Infinity) {\n checkPosition(this.end, 'end');\n\n if (this.start !== undefined && this.start > this.end) {\n throw new ERR_OUT_OF_RANGE(\n 'start',\n `<= \"end\" (here: ${this.end})`,\n this.start\n );\n }\n }\n\n this.on('end', function() {\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}\ninherits(ReadStream, ReadableStream);\n\nReadStream.prototype.open = function() {\n if (this._opening)\n return;\n\n this._opening = true;\n\n this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {\n this._opening = false;\n\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n\n this.handle = handle;\n this.emit('open', handle);\n this.emit('ready');\n // Start the flow of data.\n this.read();\n });\n};\n\nReadStream.prototype._read = function(n) {\n if (!Buffer.isBuffer(this.handle))\n return this.once('open', () => this._read(n));\n\n // XXX: safe to remove this?\n if (this.destroyed)\n return;\n\n if (!pool || pool.length - pool.used < kMinPoolSpace) {\n // Discard the old pool.\n allocNewPool(this.readableHighWaterMark\n || this._readableState.highWaterMark);\n }\n\n // Grab another reference to the pool in the case that while we're\n // in the thread pool another read() finishes up the pool, and\n // allocates a new one.\n const thisPool = pool;\n let toRead = Math.min(pool.length - pool.used, n);\n const start = pool.used;\n\n if (this.end !== undefined)\n toRead = Math.min(this.end - this.pos + 1, toRead);\n\n // Already read everything we were supposed to read!\n // treat as EOF.\n if (toRead <= 0)\n return this.push(null);\n\n // the actual read.\n this.sftp.read(this.handle,\n pool,\n pool.used,\n toRead,\n this.pos,\n (er, bytesRead) => {\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n let b = null;\n\n // Now that we know how much data we have actually read, re-wind the\n // 'used' field if we can, and otherwise allow the remainder of our\n // reservation to be used as a new pool later.\n if (start + toRead === thisPool.used && thisPool === pool) {\n thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead);\n } else {\n // Round down to the next lowest multiple of 8 to ensure the new pool\n // fragment start and end positions are aligned to an 8 byte boundary.\n const alignedEnd = (start + toRead) & ~7;\n const alignedStart = roundUpToMultipleOf8(start + bytesRead);\n if (alignedEnd - alignedStart >= kMinPoolSpace)\n poolFragments.push(thisPool.slice(alignedStart, alignedEnd));\n }\n\n if (bytesRead > 0) {\n this.bytesRead += bytesRead;\n b = thisPool.slice(start, start + bytesRead);\n }\n\n // Move the pool positions, and internal position for reading.\n this.pos += bytesRead;\n\n this.push(b);\n });\n\n pool.used = roundUpToMultipleOf8(pool.used + toRead);\n};\n\nReadStream.prototype._destroy = function(err, cb) {\n if (this._opening && !Buffer.isBuffer(this.handle)) {\n this.once('open', closeStream.bind(null, this, cb, err));\n return;\n }\n\n closeStream(this, cb, err);\n this.handle = null;\n this._opening = false;\n};\n\nfunction closeStream(stream, cb, err) {\n if (!stream.handle)\n return onclose();\n\n stream.sftp.close(stream.handle, onclose);\n\n function onclose(er) {\n er = er || err;\n cb(er);\n stream.closed = true;\n if (!er)\n stream.emit('close');\n }\n}\n\nReadStream.prototype.close = function(cb) {\n this.destroy(null, cb);\n};\n\nObject.defineProperty(ReadStream.prototype, 'pending', {\n get() {\n return this.handle === null;\n },\n configurable: true\n});\n\n// TODO: add `concurrency` setting to allow more than one in-flight WRITE\n// request to server to improve throughput\nfunction WriteStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n options.autoDestroy = false; // Node 14 major change.\n\n WritableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'w' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesWritten = 0;\n this.closed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (options.encoding)\n this.setDefaultEncoding(options.encoding);\n\n // Node v6.x only\n this.on('finish', function() {\n if (this._writableState.finalCalled)\n return;\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}\ninherits(WriteStream, WritableStream);\n\nWriteStream.prototype._final = function(cb) {\n if (this.autoClose)\n this.destroy();\n cb();\n};\n\nWriteStream.prototype.open = function() {\n if (this._opening)\n return;\n\n this._opening = true;\n\n this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {\n this._opening = false;\n\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n\n this.handle = handle;\n\n const tryAgain = (err) => {\n if (err) {\n // Try chmod() for sftp servers that may not support fchmod() for\n // whatever reason\n this.sftp.chmod(this.path, this.mode, (err_) => tryAgain());\n return;\n }\n\n // SFTPv3 requires absolute offsets, no matter the open flag used\n if (this.flags[0] === 'a') {\n const tryStat = (err, st) => {\n if (err) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.sftp.stat(this.path, (err_, st_) => {\n if (err_) {\n this.destroy();\n this.emit('error', err);\n return;\n }\n tryStat(null, st_);\n });\n return;\n }\n\n this.pos = st.size;\n this.emit('open', handle);\n this.emit('ready');\n };\n\n this.sftp.fstat(handle, tryStat);\n return;\n }\n\n this.emit('open', handle);\n this.emit('ready');\n };\n\n this.sftp.fchmod(handle, this.mode, tryAgain);\n });\n};\n\nWriteStream.prototype._write = function(data, encoding, cb) {\n if (!Buffer.isBuffer(data)) {\n const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data);\n return this.emit('error', err);\n }\n\n if (!Buffer.isBuffer(this.handle)) {\n return this.once('open', function() {\n this._write(data, encoding, cb);\n });\n }\n\n this.sftp.write(this.handle,\n data,\n 0,\n data.length,\n this.pos,\n (er, bytes) => {\n if (er) {\n if (this.autoClose)\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n cb();\n });\n\n this.pos += data.length;\n};\n\nWriteStream.prototype._writev = function(data, cb) {\n if (!Buffer.isBuffer(this.handle)) {\n return this.once('open', function() {\n this._writev(data, cb);\n });\n }\n\n const sftp = this.sftp;\n const handle = this.handle;\n let writesLeft = data.length;\n\n const onwrite = (er, bytes) => {\n if (er) {\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n if (--writesLeft === 0)\n cb();\n };\n\n // TODO: try to combine chunks to reduce number of requests to the server?\n for (let i = 0; i < data.length; ++i) {\n const chunk = data[i].chunk;\n\n sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite);\n this.pos += chunk.length;\n }\n};\n\nif (typeof WritableStream.prototype.destroy !== 'function')\n WriteStream.prototype.destroy = ReadStream.prototype.destroy;\n\nWriteStream.prototype._destroy = ReadStream.prototype._destroy;\nWriteStream.prototype.close = function(cb) {\n if (cb) {\n if (this.closed) {\n process.nextTick(cb);\n return;\n }\n this.on('close', cb);\n }\n\n // If we are not autoClosing, we should call\n // destroy on 'finish'.\n if (!this.autoClose)\n this.on('finish', this.destroy.bind(this));\n\n this.end();\n};\n\n// There is no shutdown() for files.\nWriteStream.prototype.destroySoon = WriteStream.prototype.end;\n\nObject.defineProperty(WriteStream.prototype, 'pending', {\n get() {\n return this.handle === null;\n },\n configurable: true\n});\n// =============================================================================\n\nmodule.exports = {\n flagsToString,\n OPEN_MODE,\n SFTP,\n Stats,\n STATUS_CODE,\n stringToFlags,\n};\n","'use strict';\n\nconst crypto = require('crypto');\n\nlet cpuInfo;\ntry {\n cpuInfo = require('cpu-features')();\n} catch {}\n\nconst { bindingAvailable } = require('./crypto.js');\n\nconst eddsaSupported = (() => {\n if (typeof crypto.sign === 'function'\n && typeof crypto.verify === 'function') {\n const key =\n '-----BEGIN PRIVATE KEY-----\\r\\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD'\n + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\\r\\n-----END PRIVATE KEY-----';\n const data = Buffer.from('a');\n let sig;\n let verified;\n try {\n sig = crypto.sign(null, data, key);\n verified = crypto.verify(null, data, key, sig);\n } catch {}\n return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true);\n }\n\n return false;\n})();\n\nconst curve25519Supported = (typeof crypto.diffieHellman === 'function'\n && typeof crypto.generateKeyPairSync === 'function'\n && typeof crypto.createPublicKey === 'function');\n\nconst DEFAULT_KEX = [\n // https://tools.ietf.org/html/rfc5656#section-10.1\n 'ecdh-sha2-nistp256',\n 'ecdh-sha2-nistp384',\n 'ecdh-sha2-nistp521',\n\n // https://tools.ietf.org/html/rfc4419#section-4\n 'diffie-hellman-group-exchange-sha256',\n\n // https://tools.ietf.org/html/rfc8268\n 'diffie-hellman-group14-sha256',\n 'diffie-hellman-group15-sha512',\n 'diffie-hellman-group16-sha512',\n 'diffie-hellman-group17-sha512',\n 'diffie-hellman-group18-sha512',\n];\nif (curve25519Supported) {\n DEFAULT_KEX.unshift('curve25519-sha256');\n DEFAULT_KEX.unshift('curve25519-sha256@libssh.org');\n}\nconst SUPPORTED_KEX = DEFAULT_KEX.concat([\n // https://tools.ietf.org/html/rfc4419#section-4\n 'diffie-hellman-group-exchange-sha1',\n\n 'diffie-hellman-group14-sha1', // REQUIRED\n 'diffie-hellman-group1-sha1', // REQUIRED\n]);\n\n\nconst DEFAULT_SERVER_HOST_KEY = [\n 'ecdsa-sha2-nistp256',\n 'ecdsa-sha2-nistp384',\n 'ecdsa-sha2-nistp521',\n 'rsa-sha2-512', // RFC 8332\n 'rsa-sha2-256', // RFC 8332\n 'ssh-rsa',\n];\nif (eddsaSupported)\n DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519');\nconst SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([\n 'ssh-dss',\n]);\n\n\nconst DEFAULT_CIPHER = [\n // http://tools.ietf.org/html/rfc5647\n 'aes128-gcm@openssh.com',\n 'aes256-gcm@openssh.com',\n\n // http://tools.ietf.org/html/rfc4344#section-4\n 'aes128-ctr',\n 'aes192-ctr',\n 'aes256-ctr',\n];\nif (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) {\n // We know for sure the CPU does not support AES acceleration\n if (bindingAvailable)\n DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com');\n else\n DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com');\n} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') {\n // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers\n // seem to outperform it on x86, but it seems to be faster than CTR ciphers\n DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com');\n} else {\n DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com');\n}\nconst SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([\n 'aes256-cbc',\n 'aes192-cbc',\n 'aes128-cbc',\n 'blowfish-cbc',\n '3des-cbc',\n 'aes128-gcm',\n 'aes256-gcm',\n\n // http://tools.ietf.org/html/rfc4345#section-4:\n 'arcfour256',\n 'arcfour128',\n\n 'cast128-cbc',\n 'arcfour',\n]);\n\n\nconst DEFAULT_MAC = [\n 'hmac-sha2-256-etm@openssh.com',\n 'hmac-sha2-512-etm@openssh.com',\n 'hmac-sha1-etm@openssh.com',\n 'hmac-sha2-256',\n 'hmac-sha2-512',\n 'hmac-sha1',\n];\nconst SUPPORTED_MAC = DEFAULT_MAC.concat([\n 'hmac-md5',\n 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256\n 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512\n 'hmac-ripemd160',\n 'hmac-sha1-96', // first 96 bits of HMAC-SHA1\n 'hmac-md5-96', // first 96 bits of HMAC-MD5\n]);\n\nconst DEFAULT_COMPRESSION = [\n 'none',\n 'zlib@openssh.com', // ZLIB (LZ77) compression, except\n // compression/decompression does not start until after\n // successful user authentication\n 'zlib', // ZLIB (LZ77) compression\n];\nconst SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([\n]);\n\n\nconst COMPAT = {\n BAD_DHGEX: 1 << 0,\n OLD_EXIT: 1 << 1,\n DYN_RPORT_BUG: 1 << 2,\n BUG_DHGEX_LARGE: 1 << 3,\n};\n\nmodule.exports = {\n MESSAGE: {\n // Transport layer protocol -- generic (1-19)\n DISCONNECT: 1,\n IGNORE: 2,\n UNIMPLEMENTED: 3,\n DEBUG: 4,\n SERVICE_REQUEST: 5,\n SERVICE_ACCEPT: 6,\n\n // Transport layer protocol -- algorithm negotiation (20-29)\n KEXINIT: 20,\n NEWKEYS: 21,\n\n // Transport layer protocol -- key exchange method-specific (30-49)\n KEXDH_INIT: 30,\n KEXDH_REPLY: 31,\n\n KEXDH_GEX_GROUP: 31,\n KEXDH_GEX_INIT: 32,\n KEXDH_GEX_REPLY: 33,\n KEXDH_GEX_REQUEST: 34,\n\n KEXECDH_INIT: 30,\n KEXECDH_REPLY: 31,\n\n // User auth protocol -- generic (50-59)\n USERAUTH_REQUEST: 50,\n USERAUTH_FAILURE: 51,\n USERAUTH_SUCCESS: 52,\n USERAUTH_BANNER: 53,\n\n // User auth protocol -- user auth method-specific (60-79)\n USERAUTH_PASSWD_CHANGEREQ: 60,\n\n USERAUTH_PK_OK: 60,\n\n USERAUTH_INFO_REQUEST: 60,\n USERAUTH_INFO_RESPONSE: 61,\n\n // Connection protocol -- generic (80-89)\n GLOBAL_REQUEST: 80,\n REQUEST_SUCCESS: 81,\n REQUEST_FAILURE: 82,\n\n // Connection protocol -- channel-related (90-127)\n CHANNEL_OPEN: 90,\n CHANNEL_OPEN_CONFIRMATION: 91,\n CHANNEL_OPEN_FAILURE: 92,\n CHANNEL_WINDOW_ADJUST: 93,\n CHANNEL_DATA: 94,\n CHANNEL_EXTENDED_DATA: 95,\n CHANNEL_EOF: 96,\n CHANNEL_CLOSE: 97,\n CHANNEL_REQUEST: 98,\n CHANNEL_SUCCESS: 99,\n CHANNEL_FAILURE: 100\n\n // Reserved for client protocols (128-191)\n\n // Local extensions (192-155)\n },\n DISCONNECT_REASON: {\n HOST_NOT_ALLOWED_TO_CONNECT: 1,\n PROTOCOL_ERROR: 2,\n KEY_EXCHANGE_FAILED: 3,\n RESERVED: 4,\n MAC_ERROR: 5,\n COMPRESSION_ERROR: 6,\n SERVICE_NOT_AVAILABLE: 7,\n PROTOCOL_VERSION_NOT_SUPPORTED: 8,\n HOST_KEY_NOT_VERIFIABLE: 9,\n CONNECTION_LOST: 10,\n BY_APPLICATION: 11,\n TOO_MANY_CONNECTIONS: 12,\n AUTH_CANCELED_BY_USER: 13,\n NO_MORE_AUTH_METHODS_AVAILABLE: 14,\n ILLEGAL_USER_NAME: 15,\n },\n DISCONNECT_REASON_STR: undefined,\n CHANNEL_OPEN_FAILURE: {\n ADMINISTRATIVELY_PROHIBITED: 1,\n CONNECT_FAILED: 2,\n UNKNOWN_CHANNEL_TYPE: 3,\n RESOURCE_SHORTAGE: 4\n },\n TERMINAL_MODE: {\n TTY_OP_END: 0, // Indicates end of options.\n VINTR: 1, // Interrupt character; 255 if none. Similarly for the\n // other characters. Not all of these characters are\n // supported on all systems.\n VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX\n // systems).\n VERASE: 3, // Erase the character to left of the cursor.\n VKILL: 4, // Kill the current input line.\n VEOF: 5, // End-of-file character (sends EOF from the\n // terminal).\n VEOL: 6, // End-of-line character in addition to carriage\n // return and/or linefeed.\n VEOL2: 7, // Additional end-of-line character.\n VSTART: 8, // Continues paused output (normally control-Q).\n VSTOP: 9, // Pauses output (normally control-S).\n VSUSP: 10, // Suspends the current program.\n VDSUSP: 11, // Another suspend character.\n VREPRINT: 12, // Reprints the current input line.\n VWERASE: 13, // Erases a word left of cursor.\n VLNEXT: 14, // Enter the next character typed literally, even if\n // it is a special character\n VFLUSH: 15, // Character to flush output.\n VSWTCH: 16, // Switch to a different shell layer.\n VSTATUS: 17, // Prints system status line (load, command, pid,\n // etc).\n VDISCARD: 18, // Toggles the flushing of terminal output.\n IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0\n // if this flag is FALSE, and 1 if it is TRUE.\n PARMRK: 31, // Mark parity and framing errors.\n INPCK: 32, // Enable checking of parity errors.\n ISTRIP: 33, // Strip 8th bit off characters.\n INLCR: 34, // Map NL into CR on input.\n IGNCR: 35, // Ignore CR on input.\n ICRNL: 36, // Map CR to NL on input.\n IUCLC: 37, // Translate uppercase characters to lowercase.\n IXON: 38, // Enable output flow control.\n IXANY: 39, // Any char will restart after stop.\n IXOFF: 40, // Enable input flow control.\n IMAXBEL: 41, // Ring bell on input queue full.\n ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP.\n ICANON: 51, // Canonicalize input lines.\n XCASE: 52, // Enable input and output of uppercase characters by\n // preceding their lowercase equivalents with \"\\\".\n ECHO: 53, // Enable echoing.\n ECHOE: 54, // Visually erase chars.\n ECHOK: 55, // Kill character discards current line.\n ECHONL: 56, // Echo NL even if ECHO is off.\n NOFLSH: 57, // Don't flush after interrupt.\n TOSTOP: 58, // Stop background jobs from output.\n IEXTEN: 59, // Enable extensions.\n ECHOCTL: 60, // Echo control characters as ^(Char).\n ECHOKE: 61, // Visual erase for line kill.\n PENDIN: 62, // Retype pending input.\n OPOST: 70, // Enable output processing.\n OLCUC: 71, // Convert lowercase to uppercase.\n ONLCR: 72, // Map NL to CR-NL.\n OCRNL: 73, // Translate carriage return to newline (output).\n ONOCR: 74, // Translate newline to carriage return-newline\n // (output).\n ONLRET: 75, // Newline performs a carriage return (output).\n CS7: 90, // 7 bit mode.\n CS8: 91, // 8 bit mode.\n PARENB: 92, // Parity enable.\n PARODD: 93, // Odd parity, else even.\n TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second.\n TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second.\n },\n CHANNEL_EXTENDED_DATATYPE: {\n STDERR: 1,\n },\n\n SIGNALS: [\n 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1',\n 'USR2', 'KILL', 'PIPE'\n ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}),\n\n COMPAT,\n COMPAT_CHECKS: [\n [ 'Cisco-1.25', COMPAT.BAD_DHGEX ],\n [ /^Cisco-1\\./, COMPAT.BUG_DHGEX_LARGE ],\n [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations\n [ /^OpenSSH_5\\.\\d+/, COMPAT.DYN_RPORT_BUG ],\n ],\n\n // KEX proposal-related\n DEFAULT_KEX,\n SUPPORTED_KEX,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER,\n DEFAULT_MAC,\n SUPPORTED_MAC,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION,\n\n curve25519Supported,\n eddsaSupported,\n};\n\nmodule.exports.DISCONNECT_REASON_BY_VALUE =\n Array.from(Object.entries(module.exports.DISCONNECT_REASON))\n .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {});\n","// TODO:\n// * make max packet size configurable\n// * if decompression is enabled, use `._packet` in decipher instances as\n// input to (sync) zlib inflater with appropriate offset and length to\n// avoid an additional copy of payload data before inflation\n// * factor decompression status into packet length checks\n'use strict';\n\nconst {\n createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual\n} = require('crypto');\n\nconst { readUInt32BE, writeUInt32BE } = require('./utils.js');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst MAX_SEQNO = 2 ** 32 - 1;\nconst EMPTY_BUFFER = Buffer.alloc(0);\nconst BUF_INT = Buffer.alloc(4);\nconst DISCARD_CACHE = new Map();\nconst MAX_PACKET_SIZE = 35000;\n\nlet binding;\nlet AESGCMCipher;\nlet ChaChaPolyCipher;\nlet GenericCipher;\nlet AESGCMDecipher;\nlet ChaChaPolyDecipher;\nlet GenericDecipher;\ntry {\n binding = require('./crypto/build/Release/sshcrypto.node');\n ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher,\n AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding);\n} catch {}\n\nconst CIPHER_STREAM = 1 << 0;\nconst CIPHER_INFO = (() => {\n function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) {\n return {\n sslName,\n blockLen,\n keyLen,\n ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM)\n ? ivLen\n : blockLen),\n authLen,\n discardLen,\n stream: !!(flags & CIPHER_STREAM),\n };\n }\n\n return {\n 'chacha20-poly1305@openssh.com':\n info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM),\n\n 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM),\n 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM),\n 'aes128-gcm@openssh.com':\n info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM),\n 'aes256-gcm@openssh.com':\n info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM),\n\n 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0),\n 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0),\n 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0),\n 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0),\n '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0),\n 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0),\n 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0),\n 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0),\n\n 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM),\n 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM),\n 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM),\n '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM),\n 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM),\n 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM),\n\n /* The \"arcfour128\" algorithm is the RC4 cipher, as described in\n [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream\n generated by the cipher MUST be discarded, and the first byte of the\n first encrypted packet MUST be encrypted using the 1537th byte of\n keystream.\n\n -- http://tools.ietf.org/html/rfc4345#section-4 */\n 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM),\n };\n})();\n\nconst MAC_INFO = (() => {\n function info(sslName, len, actualLen, isETM) {\n return {\n sslName,\n len,\n actualLen,\n isETM,\n };\n }\n\n return {\n 'hmac-md5': info('md5', 16, 16, false),\n 'hmac-md5-96': info('md5', 16, 12, false),\n 'hmac-ripemd160': info('ripemd160', 20, 20, false),\n 'hmac-sha1': info('sha1', 20, 20, false),\n 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true),\n 'hmac-sha1-96': info('sha1', 20, 12, false),\n 'hmac-sha2-256': info('sha256', 32, 32, false),\n 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true),\n 'hmac-sha2-256-96': info('sha256', 32, 12, false),\n 'hmac-sha2-512': info('sha512', 64, 64, false),\n 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true),\n 'hmac-sha2-512-96': info('sha512', 64, 12, false),\n };\n})();\n\n\n// Should only_be used during the initial handshake\nclass NullCipher {\n constructor(seqno, onWrite) {\n this.outSeqno = seqno;\n this._onWrite = onWrite;\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - (pktLen & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nconst POLY1305_ZEROS = Buffer.alloc(32);\nconst POLY1305_OUT_COMPUTE = Buffer.alloc(16);\nlet POLY1305_WASM_MODULE;\nlet POLY1305_RESULT_MALLOC;\nlet poly1305_auth;\nclass ChaChaPolyCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encKeyMain = enc.cipherKey.slice(0, 32);\n this._encKeyPktLen = enc.cipherKey.slice(32);\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - ((pktLen - 4) & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Generate Poly1305 key\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12);\n const polyKey =\n createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE)\n .update(POLY1305_ZEROS);\n\n // Encrypt packet length\n const pktLenEnc =\n createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE)\n .update(packet.slice(0, 4));\n this._onWrite(pktLenEnc);\n\n // Encrypt rest of packet\n POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian)\n const payloadEnc =\n createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE)\n .update(packet.slice(4));\n this._onWrite(payloadEnc);\n\n // Calculate Poly1305 MAC\n poly1305_auth(POLY1305_RESULT_MALLOC,\n pktLenEnc,\n pktLenEnc.length,\n payloadEnc,\n payloadEnc.length,\n polyKey);\n const mac = Buffer.allocUnsafe(16);\n mac.set(\n new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer,\n POLY1305_RESULT_MALLOC,\n 16),\n 0\n );\n this._onWrite(mac);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass ChaChaPolyCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._instance = new ChaChaPolyCipher(enc.cipherKey);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - ((pktLen - 4) & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet, this.outSeqno);\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass AESGCMCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encSSLName = enc.cipherInfo.sslName;\n this._encKey = enc.cipherKey;\n this._encIV = enc.cipherIV;\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 16 - ((pktLen - 4) & (16 - 1));\n if (padLen < 4)\n padLen += 16;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV);\n cipher.setAutoPadding(false);\n\n const lenData = packet.slice(0, 4);\n cipher.setAAD(lenData);\n this._onWrite(lenData);\n\n // Encrypt pad length, payload, and padding\n const encrypted = cipher.update(packet.slice(4));\n this._onWrite(encrypted);\n const final = cipher.final();\n // XXX: final.length === 0 always?\n if (final.length)\n this._onWrite(final);\n\n // Generate MAC\n const tag = cipher.getAuthTag();\n this._onWrite(tag);\n\n // Increment counter in IV by 1 for next packet\n ivIncrement(this._encIV);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass AESGCMCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._instance = new AESGCMCipher(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 16 - ((pktLen - 4) & (16 - 1));\n if (padLen < 4)\n padLen += 16;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet);\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass GenericCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encBlockLen = enc.cipherInfo.blockLen;\n this._cipherInstance = createCipheriv(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV);\n this._macSSLName = enc.macInfo.sslName;\n this._macKey = enc.macKey;\n this._macActualLen = enc.macInfo.actualLen;\n this._macETM = enc.macInfo.isETM;\n this._aadLen = (this._macETM ? 4 : 0);\n this._dead = false;\n\n const discardLen = enc.cipherInfo.discardLen;\n if (discardLen) {\n let discard = DISCARD_CACHE.get(discardLen);\n if (discard === undefined) {\n discard = Buffer.alloc(discardLen);\n DISCARD_CACHE.set(discardLen, discard);\n }\n this._cipherInstance.update(discard);\n }\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n const blockLen = this._encBlockLen;\n\n let pktLen = 4 + 1 + payloadLen;\n let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1));\n if (padLen < 4)\n padLen += blockLen;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n let mac;\n if (this._macETM) {\n // Encrypt pad length, payload, and padding\n const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4);\n const encrypted = this._cipherInstance.update(\n new Uint8Array(packet.buffer,\n packet.byteOffset + 4,\n packet.length - 4)\n );\n\n this._onWrite(lenBytes);\n this._onWrite(encrypted);\n\n // TODO: look into storing seqno as 4-byte buffer and incrementing like we\n // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time\n mac = createHmac(this._macSSLName, this._macKey);\n writeUInt32BE(BUF_INT, this.outSeqno, 0);\n mac.update(BUF_INT);\n mac.update(lenBytes);\n mac.update(encrypted);\n } else {\n // Encrypt length field, pad length, payload, and padding\n const encrypted = this._cipherInstance.update(packet);\n this._onWrite(encrypted);\n\n // TODO: look into storing seqno as 4-byte buffer and incrementing like we\n // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time\n mac = createHmac(this._macSSLName, this._macKey);\n writeUInt32BE(BUF_INT, this.outSeqno, 0);\n mac.update(BUF_INT);\n mac.update(packet);\n }\n\n let digest = mac.digest();\n if (digest.length > this._macActualLen)\n digest = digest.slice(0, this._macActualLen);\n this._onWrite(digest);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass GenericCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encBlockLen = enc.cipherInfo.blockLen;\n this._macLen = enc.macInfo.len;\n this._macActualLen = enc.macInfo.actualLen;\n this._aadLen = (enc.macInfo.isETM ? 4 : 0);\n this._instance = new GenericCipher(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV,\n enc.macInfo.sslName,\n enc.macKey,\n enc.macInfo.isETM);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n const blockLen = this._encBlockLen;\n\n let pktLen = 4 + 1 + payloadLen;\n let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1));\n if (padLen < 4)\n padLen += blockLen;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + this._macLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet, this.outSeqno);\n\n if (this._macActualLen < this._macLen) {\n packet = new FastBuffer(packet.buffer,\n packet.byteOffset,\n (packet.length\n - (this._macLen - this._macActualLen)));\n }\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass NullDecipher {\n constructor(seqno, onPayload) {\n this.inSeqno = seqno;\n this._onPayload = onPayload;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n while (p < dataLen) {\n // Read packet length\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n\n if (this._lenBytes < 4)\n return;\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (4 + this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._packetPos < this._len) {\n const nb = Math.min(this._len - this._packetPos, dataLen - p);\n let chunk;\n if (p !== 0 || nb !== dataLen)\n chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n chunk = data;\n if (nb === this._len) {\n this._packet = chunk;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(chunk, this._packetPos);\n }\n p += nb;\n this._packetPos += nb;\n if (this._packetPos < this._len)\n return;\n }\n\n const payload = (!this._packet\n ? EMPTY_BUFFER\n : new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length\n - this._packet[0] - 1));\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass ChaChaPolyDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decKeyMain = dec.decipherKey.slice(0, 32);\n this._decKeyPktLen = dec.decipherKey.slice(32);\n this._len = 0;\n this._lenBuf = Buffer.alloc(4);\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(16);\n this._calcMac = Buffer.allocUnsafe(16);\n this._macPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length\n if (this._lenPos < 4) {\n let nb = Math.min(4 - this._lenPos, dataLen - p);\n while (nb--)\n this._lenBuf[this._lenPos++] = data[p++];\n if (this._lenPos < 4)\n return;\n\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);\n\n const decLenBytes =\n createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE)\n .update(this._lenBuf);\n this._len = readUInt32BE(decLenBytes, 0);\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read Poly1305 MAC\n {\n const nb = Math.min(16 - this._macPos, dataLen - p);\n // TODO: avoid copying if entire MAC is in current chunk\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < 16)\n return;\n }\n\n // Generate Poly1305 key\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);\n const polyKey =\n createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE)\n .update(POLY1305_ZEROS);\n\n // Calculate and compare Poly1305 MACs\n poly1305_auth(POLY1305_RESULT_MALLOC,\n this._lenBuf,\n 4,\n this._packet,\n this._packet.length,\n polyKey);\n\n this._calcMac.set(\n new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer,\n POLY1305_RESULT_MALLOC,\n 16),\n 0\n );\n if (!timingSafeEqual(this._calcMac, this._mac))\n throw new Error('Invalid MAC');\n\n // Decrypt packet\n POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian)\n const packet =\n createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE)\n .update(this._packet);\n\n const payload = new FastBuffer(packet.buffer,\n packet.byteOffset + 1,\n packet.length - packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass ChaChaPolyDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new ChaChaPolyDecipher(dec.decipherKey);\n this._len = 0;\n this._lenBuf = Buffer.alloc(4);\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(16);\n this._macPos = 0;\n }\n free() {\n this._instance.free();\n }\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length\n if (this._lenPos < 4) {\n let nb = Math.min(4 - this._lenPos, dataLen - p);\n while (nb--)\n this._lenBuf[this._lenPos++] = data[p++];\n if (this._lenPos < 4)\n return;\n\n this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno);\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read Poly1305 MAC\n {\n const nb = Math.min(16 - this._macPos, dataLen - p);\n // TODO: avoid copying if entire MAC is in current chunk\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < 16)\n return;\n }\n\n this._instance.decrypt(this._packet, this._mac, this.inSeqno);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass AESGCMDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decipherInstance = null;\n this._decipherSSLName = dec.decipherInfo.sslName;\n this._decipherKey = dec.decipherKey;\n this._decipherIV = dec.decipherIV;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._tag = Buffer.allocUnsafe(16);\n this._tagPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length (unencrypted, but AAD)\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n if (this._lenBytes < 4)\n return;\n\n if ((this._len + 20) > MAX_PACKET_SIZE\n || this._len < 16\n || (this._len & 15) !== 0) {\n throw new Error('Bad packet length');\n }\n\n this._decipherInstance = createDecipheriv(\n this._decipherSSLName,\n this._decipherKey,\n this._decipherIV\n );\n this._decipherInstance.setAutoPadding(false);\n this._decipherInstance.setAAD(intToBytes(this._len));\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let decrypted;\n if (p !== 0 || nb !== dataLen) {\n decrypted = this._decipherInstance.update(\n new Uint8Array(data.buffer, data.byteOffset + p, nb)\n );\n } else {\n decrypted = this._decipherInstance.update(data);\n }\n if (decrypted.length) {\n if (nb === this._len) {\n this._packet = decrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(decrypted, this._packetPos);\n }\n this._packetPos += decrypted.length;\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read authentication tag\n {\n const nb = Math.min(16 - this._tagPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._tag.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._tagPos\n );\n } else {\n this._tag.set(data, this._tagPos);\n }\n p += nb;\n this._tagPos += nb;\n if (this._tagPos < 16)\n return;\n }\n\n {\n // Verify authentication tag\n this._decipherInstance.setAuthTag(this._tag);\n\n const decrypted = this._decipherInstance.final();\n\n // XXX: this should never output any data since stream ciphers always\n // return data from .update() and block ciphers must end on a multiple\n // of the block length, which would have caused an exception to be\n // thrown if the total input was not...\n if (decrypted.length) {\n if (this._packet)\n this._packet.set(decrypted, this._packetPos);\n else\n this._packet = decrypted;\n }\n }\n\n const payload = (!this._packet\n ? EMPTY_BUFFER\n : new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length\n - this._packet[0] - 1));\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n ivIncrement(this._decipherIV);\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._tagPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass AESGCMDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new AESGCMDecipher(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV);\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._pktLen = 0;\n this._tag = Buffer.allocUnsafe(16);\n this._tagPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length (unencrypted, but AAD)\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n if (this._lenBytes < 4)\n return;\n\n if ((this._len + 20) > MAX_PACKET_SIZE\n || this._len < 16\n || (this._len & 15) !== 0) {\n throw new Error(`Bad packet length: ${this._len}`);\n }\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read authentication tag\n {\n const nb = Math.min(16 - this._tagPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._tag.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._tagPos\n );\n } else {\n this._tag.set(data, this._tagPos);\n }\n p += nb;\n this._tagPos += nb;\n if (this._tagPos < 16)\n return;\n }\n\n this._instance.decrypt(this._packet, this._len, this._tag);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._pktLen = 0;\n this._tagPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\n// TODO: test incremental .update()s vs. copying to _packet and doing a single\n// .update() after entire packet read -- a single .update() would allow\n// verifying MAC before decrypting for ETM MACs\nclass GenericDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV);\n this._decipherInstance.setAutoPadding(false);\n this._block = Buffer.allocUnsafe(\n dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen\n );\n this._blockSize = dec.decipherInfo.blockLen;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen);\n this._macPos = 0;\n this._macSSLName = dec.macInfo.sslName;\n this._macKey = dec.macKey;\n this._macActualLen = dec.macInfo.actualLen;\n this._macETM = dec.macInfo.isETM;\n this._macInstance = null;\n\n const discardLen = dec.decipherInfo.discardLen;\n if (discardLen) {\n let discard = DISCARD_CACHE.get(discardLen);\n if (discard === undefined) {\n discard = Buffer.alloc(discardLen);\n DISCARD_CACHE.set(discardLen, discard);\n }\n this._decipherInstance.update(discard);\n }\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read first encrypted block\n if (this._blockPos < this._block.length) {\n const nb = Math.min(this._block.length - this._blockPos, dataLen - p);\n if (p !== 0 || nb !== dataLen || nb < data.length) {\n this._block.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._blockPos\n );\n } else {\n this._block.set(data, this._blockPos);\n }\n\n p += nb;\n this._blockPos += nb;\n if (this._blockPos < this._block.length)\n return;\n\n let decrypted;\n let need;\n if (this._macETM) {\n this._len = need = readUInt32BE(this._block, 0);\n } else {\n // Decrypt first block to get packet length\n decrypted = this._decipherInstance.update(this._block);\n this._len = readUInt32BE(decrypted, 0);\n need = 4 + this._len - this._blockSize;\n }\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 5\n || (need & (this._blockSize - 1)) !== 0) {\n throw new Error('Bad packet length');\n }\n\n // Create MAC up front to calculate in parallel with decryption\n this._macInstance = createHmac(this._macSSLName, this._macKey);\n\n writeUInt32BE(BUF_INT, this.inSeqno, 0);\n this._macInstance.update(BUF_INT);\n if (this._macETM) {\n this._macInstance.update(this._block);\n } else {\n this._macInstance.update(new Uint8Array(decrypted.buffer,\n decrypted.byteOffset,\n 4));\n this._pktLen = decrypted.length - 4;\n this._packetPos = this._pktLen;\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(\n new Uint8Array(decrypted.buffer,\n decrypted.byteOffset + 4,\n this._packetPos),\n 0\n );\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (this._macETM)\n this._macInstance.update(encrypted);\n const decrypted = this._decipherInstance.update(encrypted);\n if (decrypted.length) {\n if (nb === this._len) {\n this._packet = decrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(decrypted, this._packetPos);\n }\n this._packetPos += decrypted.length;\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read MAC\n {\n const nb = Math.min(this._macActualLen - this._macPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < this._macActualLen)\n return;\n }\n\n // Verify MAC\n if (!this._macETM)\n this._macInstance.update(this._packet);\n let calculated = this._macInstance.digest();\n if (this._macActualLen < calculated.length) {\n calculated = new Uint8Array(calculated.buffer,\n calculated.byteOffset,\n this._macActualLen);\n }\n if (!timingSafeEquals(calculated, this._mac))\n throw new Error('Invalid MAC');\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._macPos = 0;\n this._macInstance = null;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass GenericDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new GenericDecipher(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV,\n dec.macInfo.sslName,\n dec.macKey,\n dec.macInfo.isETM,\n dec.macInfo.actualLen);\n this._block = Buffer.allocUnsafe(\n dec.macInfo.isETM || dec.decipherInfo.stream\n ? 4\n : dec.decipherInfo.blockLen\n );\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen);\n this._macPos = 0;\n this._macActualLen = dec.macInfo.actualLen;\n this._macETM = dec.macInfo.isETM;\n }\n free() {\n this._instance.free();\n }\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read first encrypted block\n if (this._blockPos < this._block.length) {\n const nb = Math.min(this._block.length - this._blockPos, dataLen - p);\n if (p !== 0 || nb !== dataLen || nb < data.length) {\n this._block.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._blockPos\n );\n } else {\n this._block.set(data, this._blockPos);\n }\n\n p += nb;\n this._blockPos += nb;\n if (this._blockPos < this._block.length)\n return;\n\n let need;\n if (this._macETM) {\n this._len = need = readUInt32BE(this._block, 0);\n } else {\n // Decrypt first block to get packet length\n this._instance.decryptBlock(this._block);\n this._len = readUInt32BE(this._block, 0);\n need = 4 + this._len - this._block.length;\n }\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 5\n || (need & (this._block.length - 1)) !== 0) {\n throw new Error('Bad packet length');\n }\n\n if (!this._macETM) {\n this._pktLen = (this._block.length - 4);\n if (this._pktLen) {\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(\n new Uint8Array(this._block.buffer,\n this._block.byteOffset + 4,\n this._pktLen),\n 0\n );\n }\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read MAC\n {\n const nb = Math.min(this._macActualLen - this._macPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < this._macActualLen)\n return;\n }\n\n // Decrypt and verify MAC\n this._instance.decrypt(this._packet,\n this.inSeqno,\n this._block,\n this._mac);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n this._macInstance = null;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\n// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV\nfunction ivIncrement(iv) {\n // eslint-disable-next-line no-unused-expressions\n ++iv[11] >>> 8\n && ++iv[10] >>> 8\n && ++iv[9] >>> 8\n && ++iv[8] >>> 8\n && ++iv[7] >>> 8\n && ++iv[6] >>> 8\n && ++iv[5] >>> 8\n && ++iv[4] >>> 8;\n}\n\nconst intToBytes = (() => {\n const ret = Buffer.alloc(4);\n return (n) => {\n ret[0] = (n >>> 24);\n ret[1] = (n >>> 16);\n ret[2] = (n >>> 8);\n ret[3] = n;\n return ret;\n };\n})();\n\nfunction timingSafeEquals(a, b) {\n if (a.length !== b.length) {\n timingSafeEqual(a, a);\n return false;\n }\n return timingSafeEqual(a, b);\n}\n\nfunction createCipher(config) {\n if (typeof config !== 'object' || config === null)\n throw new Error('Invalid config');\n\n if (typeof config.outbound !== 'object' || config.outbound === null)\n throw new Error('Invalid outbound');\n\n const outbound = config.outbound;\n\n if (typeof outbound.onWrite !== 'function')\n throw new Error('Invalid outbound.onWrite');\n\n if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null)\n throw new Error('Invalid outbound.cipherInfo');\n\n if (!Buffer.isBuffer(outbound.cipherKey)\n || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) {\n throw new Error('Invalid outbound.cipherKey');\n }\n\n if (outbound.cipherInfo.ivLen\n && (!Buffer.isBuffer(outbound.cipherIV)\n || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) {\n throw new Error('Invalid outbound.cipherIV');\n }\n\n if (typeof outbound.seqno !== 'number'\n || outbound.seqno < 0\n || outbound.seqno > MAX_SEQNO) {\n throw new Error('Invalid outbound.seqno');\n }\n\n const forceNative = !!outbound.forceNative;\n\n switch (outbound.cipherInfo.sslName) {\n case 'aes-128-gcm':\n case 'aes-256-gcm':\n return (AESGCMCipher && !forceNative\n ? new AESGCMCipherBinding(config)\n : new AESGCMCipherNative(config));\n case 'chacha20':\n return (ChaChaPolyCipher && !forceNative\n ? new ChaChaPolyCipherBinding(config)\n : new ChaChaPolyCipherNative(config));\n default: {\n if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null)\n throw new Error('Invalid outbound.macInfo');\n if (!Buffer.isBuffer(outbound.macKey)\n || outbound.macKey.length !== outbound.macInfo.len) {\n throw new Error('Invalid outbound.macKey');\n }\n return (GenericCipher && !forceNative\n ? new GenericCipherBinding(config)\n : new GenericCipherNative(config));\n }\n }\n}\n\nfunction createDecipher(config) {\n if (typeof config !== 'object' || config === null)\n throw new Error('Invalid config');\n\n if (typeof config.inbound !== 'object' || config.inbound === null)\n throw new Error('Invalid inbound');\n\n const inbound = config.inbound;\n\n if (typeof inbound.onPayload !== 'function')\n throw new Error('Invalid inbound.onPayload');\n\n if (typeof inbound.decipherInfo !== 'object'\n || inbound.decipherInfo === null) {\n throw new Error('Invalid inbound.decipherInfo');\n }\n\n if (!Buffer.isBuffer(inbound.decipherKey)\n || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) {\n throw new Error('Invalid inbound.decipherKey');\n }\n\n if (inbound.decipherInfo.ivLen\n && (!Buffer.isBuffer(inbound.decipherIV)\n || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) {\n throw new Error('Invalid inbound.decipherIV');\n }\n\n if (typeof inbound.seqno !== 'number'\n || inbound.seqno < 0\n || inbound.seqno > MAX_SEQNO) {\n throw new Error('Invalid inbound.seqno');\n }\n\n const forceNative = !!inbound.forceNative;\n\n switch (inbound.decipherInfo.sslName) {\n case 'aes-128-gcm':\n case 'aes-256-gcm':\n return (AESGCMDecipher && !forceNative\n ? new AESGCMDecipherBinding(config)\n : new AESGCMDecipherNative(config));\n case 'chacha20':\n return (ChaChaPolyDecipher && !forceNative\n ? new ChaChaPolyDecipherBinding(config)\n : new ChaChaPolyDecipherNative(config));\n default: {\n if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null)\n throw new Error('Invalid inbound.macInfo');\n if (!Buffer.isBuffer(inbound.macKey)\n || inbound.macKey.length !== inbound.macInfo.len) {\n throw new Error('Invalid inbound.macKey');\n }\n return (GenericDecipher && !forceNative\n ? new GenericDecipherBinding(config)\n : new GenericDecipherNative(config));\n }\n }\n}\n\nmodule.exports = {\n CIPHER_INFO,\n MAC_INFO,\n bindingAvailable: !!binding,\n init: (() => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n POLY1305_WASM_MODULE = await require('./crypto/poly1305.js')();\n POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16);\n poly1305_auth = POLY1305_WASM_MODULE.cwrap(\n 'poly1305_auth',\n null,\n ['number', 'array', 'number', 'array', 'number', 'array']\n );\n } catch (ex) {\n return reject(ex);\n }\n resolve();\n });\n })(),\n\n NullCipher,\n createCipher,\n NullDecipher,\n createDecipher,\n};\n","\nvar createPoly1305 = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;\n return (\nfunction(createPoly1305) {\n createPoly1305 = createPoly1305 || {};\n\n\nvar b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x=\"object\"===typeof window,y=\"function\"===typeof importScripts,z=\"object\"===typeof process&&\"object\"===typeof process.versions&&\"string\"===typeof process.versions.node,B=\"\",C,D,E,F,G;\nif(z)B=y?require(\"path\").dirname(B)+\"/\":__dirname+\"/\",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=require(\"fs\"));G||(G=require(\"path\"));a=G.normalize(a);return F.readFileSync(a,c?null:\"utf8\")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=require(\"fs\"));G||(G=require(\"path\"));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]=\n0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g=\"\";else g=\"boolean\"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea=\"undefined\"!==typeof TextDecoder?new TextDecoder(\"utf8\"):void 0,ha,Q,P;\nfunction ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={};\nfunction K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError(\"abort(\"+a+\"). Build with -s ASSERTIONS=1 for more info.\");r(a);throw a;}var V=\"data:application/octet-stream;base64,\",W;W=\"data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==\";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw\"both async and sync fetching of the wasm failed\";}catch(d){K(d)}}\nfunction qa(){if(!J&&(x||y)){if(\"function\"===typeof fetch&&!W.startsWith(\"file://\"))return fetch(W,{credentials:\"same-origin\"}).then(function(a){if(!a.ok)throw\"failed to load wasm binary file at '\"+W+\"'\";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})}\nfunction X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}};\n(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I(\"failed to asynchronously prepare wasm: \"+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e,\na)}catch(f){return I(\"Module.instantiateWasm callback failed with error: \"+f),!1}(function(){return J||\"function\"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith(\"file://\")||\"function\"!==typeof fetch?d(c):fetch(W,{credentials:\"same-origin\"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I(\"wasm streaming compile failed: \"+l);I(\"falling back to ArrayBuffer instantiation\");return d(c)})})})().catch(r);return{}})();\nb.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)};\nb._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return\"number\"===l});return\"string\"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)};\nfunction Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for(\"function\"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 {\n // eslint-disable-next-line prefer-const\n for (let [type, handler] of Object.entries(handlers)) {\n type = +type;\n if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length)\n MESSAGE_HANDLERS[type] = handler;\n }\n});\n\nmodule.exports = MESSAGE_HANDLERS;\n","'use strict';\n\nconst {\n bufferSlice,\n bufferParser,\n doFatalError,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst {\n CHANNEL_OPEN_FAILURE,\n COMPAT,\n MESSAGE,\n TERMINAL_MODE,\n} = require('./constants.js');\n\nconst {\n parseKey,\n} = require('./keyParser.js');\n\nconst TERMINAL_MODE_BY_VALUE =\n Array.from(Object.entries(TERMINAL_MODE))\n .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});\n\nmodule.exports = {\n // Transport layer protocol ==================================================\n [MESSAGE.DISCONNECT]: (self, payload) => {\n /*\n byte SSH_MSG_DISCONNECT\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding\n string language tag\n */\n bufferParser.init(payload, 1);\n const reason = bufferParser.readUInt32BE();\n const desc = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed DISCONNECT packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: Received DISCONNECT (${reason}, \"${desc}\")`\n );\n\n const handler = self._handlers.DISCONNECT;\n handler && handler(self, reason, desc);\n },\n [MESSAGE.IGNORE]: (self, payload) => {\n /*\n byte SSH_MSG_IGNORE\n string data\n */\n self._debug && self._debug('Inbound: Received IGNORE');\n },\n [MESSAGE.UNIMPLEMENTED]: (self, payload) => {\n /*\n byte SSH_MSG_UNIMPLEMENTED\n uint32 packet sequence number of rejected message\n */\n bufferParser.init(payload, 1);\n const seqno = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (seqno === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed UNIMPLEMENTED packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`);\n },\n [MESSAGE.DEBUG]: (self, payload) => {\n /*\n byte SSH_MSG_DEBUG\n boolean always_display\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const display = bufferParser.readBool();\n const msg = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed DEBUG packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received DEBUG');\n\n const handler = self._handlers.DEBUG;\n handler && handler(self, display, msg);\n },\n [MESSAGE.SERVICE_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_SERVICE_REQUEST\n string service name\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n bufferParser.clear();\n\n if (name === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed SERVICE_REQUEST packet'\n );\n }\n\n self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`);\n\n const handler = self._handlers.SERVICE_REQUEST;\n handler && handler(self, name);\n },\n [MESSAGE.SERVICE_ACCEPT]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_SERVICE_ACCEPT\n string service name\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n bufferParser.clear();\n\n if (name === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed SERVICE_ACCEPT packet'\n );\n }\n\n self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`);\n\n const handler = self._handlers.SERVICE_ACCEPT;\n handler && handler(self, name);\n },\n\n // User auth protocol -- generic =============================================\n [MESSAGE.USERAUTH_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_USERAUTH_REQUEST\n string user name in ISO-10646 UTF-8 encoding [RFC3629]\n string service name in US-ASCII\n string method name in US-ASCII\n .... method specific fields\n */\n bufferParser.init(payload, 1);\n const user = bufferParser.readString(true);\n const service = bufferParser.readString(true);\n const method = bufferParser.readString(true);\n let methodData;\n let methodDesc;\n switch (method) {\n case 'none':\n methodData = null;\n break;\n case 'password': {\n /*\n boolean \n string plaintext password in ISO-10646 UTF-8 encoding [RFC3629]\n [string new password]\n */\n const isChange = bufferParser.readBool();\n if (isChange !== undefined) {\n methodData = bufferParser.readString(true);\n if (methodData !== undefined && isChange) {\n const newPassword = bufferParser.readString(true);\n if (newPassword !== undefined)\n methodData = { oldPassword: methodData, newPassword };\n else\n methodData = undefined;\n }\n }\n break;\n }\n case 'publickey': {\n /*\n boolean \n string public key algorithm name\n string public key blob\n [string signature]\n */\n const hasSig = bufferParser.readBool();\n if (hasSig !== undefined) {\n const keyAlgo = bufferParser.readString(true);\n const key = bufferParser.readString();\n if (hasSig) {\n const blobEnd = bufferParser.pos();\n let signature = bufferParser.readString();\n if (signature !== undefined) {\n if (signature.length > (4 + keyAlgo.length + 4)\n && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) {\n // Skip algoLen + algo + sigLen\n signature = bufferSlice(signature, 4 + keyAlgo.length + 4);\n }\n\n signature = sigSSHToASN1(signature, keyAlgo);\n if (signature) {\n const sessionID = self._kex.sessionID;\n const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd);\n writeUInt32BE(blob, sessionID.length, 0);\n blob.set(sessionID, 4);\n blob.set(\n new Uint8Array(payload.buffer, payload.byteOffset, blobEnd),\n 4 + sessionID.length\n );\n methodData = {\n keyAlgo,\n key,\n signature,\n blob,\n };\n }\n }\n } else {\n methodData = { keyAlgo, key };\n methodDesc = 'publickey -- check';\n }\n }\n break;\n }\n case 'hostbased': {\n /*\n string public key algorithm for host key\n string public host key and certificates for client host\n string client host name expressed as the FQDN in US-ASCII\n string user name on the client host in ISO-10646 UTF-8 encoding\n [RFC3629]\n string signature\n */\n const keyAlgo = bufferParser.readString(true);\n const key = bufferParser.readString();\n const localHostname = bufferParser.readString(true);\n const localUsername = bufferParser.readString(true);\n\n const blobEnd = bufferParser.pos();\n let signature = bufferParser.readString();\n if (signature !== undefined) {\n if (signature.length > (4 + keyAlgo.length + 4)\n && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) {\n // Skip algoLen + algo + sigLen\n signature = bufferSlice(signature, 4 + keyAlgo.length + 4);\n }\n\n signature = sigSSHToASN1(signature, keyAlgo);\n if (signature !== undefined) {\n const sessionID = self._kex.sessionID;\n const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd);\n writeUInt32BE(blob, sessionID.length, 0);\n blob.set(sessionID, 4);\n blob.set(\n new Uint8Array(payload.buffer, payload.byteOffset, blobEnd),\n 4 + sessionID.length\n );\n methodData = {\n keyAlgo,\n key,\n signature,\n blob,\n localHostname,\n localUsername,\n };\n }\n }\n break;\n }\n case 'keyboard-interactive':\n /*\n string language tag (as defined in [RFC-3066])\n string submethods (ISO-10646 UTF-8)\n */\n // Skip/ignore language field -- it's deprecated in RFC 4256\n bufferParser.skipString();\n\n methodData = bufferParser.readList();\n break;\n default:\n if (method !== undefined)\n methodData = bufferParser.readRaw();\n }\n bufferParser.clear();\n\n if (methodData === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_REQUEST packet'\n );\n }\n\n if (methodDesc === undefined)\n methodDesc = method;\n\n self._authsQueue.push(method);\n\n self._debug\n && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`);\n\n const handler = self._handlers.USERAUTH_REQUEST;\n handler && handler(self, user, service, method, methodData);\n },\n [MESSAGE.USERAUTH_FAILURE]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_FAILURE\n name-list authentications that can continue\n boolean partial success\n */\n bufferParser.init(payload, 1);\n const authMethods = bufferParser.readList();\n const partialSuccess = bufferParser.readBool();\n bufferParser.clear();\n\n if (partialSuccess === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_FAILURE packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`);\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_FAILURE;\n handler && handler(self, authMethods, partialSuccess);\n },\n [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_SUCCESS\n */\n self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS');\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_SUCCESS;\n handler && handler(self);\n },\n [MESSAGE.USERAUTH_BANNER]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_BANNER\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const msg = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_BANNER packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_BANNER');\n\n const handler = self._handlers.USERAUTH_BANNER;\n handler && handler(self, msg);\n },\n\n // User auth protocol -- method-specific =====================================\n 60: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 60 without auth');\n return;\n }\n\n switch (self._authsQueue[0]) {\n case 'password': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ\n string prompt in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const prompt = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet'\n );\n }\n\n self._debug\n && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ');\n\n const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ;\n handler && handler(self, prompt);\n break;\n }\n case 'publickey': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_PK_OK\n string public key algorithm name from the request\n string public key blob from the request\n */\n bufferParser.init(payload, 1);\n const keyAlgo = bufferParser.readString(true);\n const key = bufferParser.readString();\n bufferParser.clear();\n\n if (key === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_PK_OK packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_PK_OK');\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_PK_OK;\n handler && handler(self, keyAlgo, key);\n break;\n }\n case 'keyboard-interactive': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_INFO_REQUEST\n string name (ISO-10646 UTF-8)\n string instruction (ISO-10646 UTF-8)\n string language tag (as defined in [RFC-3066])\n int num-prompts\n string prompt[1] (ISO-10646 UTF-8)\n boolean echo[1]\n ...\n string prompt[num-prompts] (ISO-10646 UTF-8)\n boolean echo[num-prompts]\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n const instructions = bufferParser.readString(true);\n bufferParser.readString(); // skip lang\n const numPrompts = bufferParser.readUInt32BE();\n let prompts;\n if (numPrompts !== undefined) {\n prompts = new Array(numPrompts);\n let i;\n for (i = 0; i < numPrompts; ++i) {\n const prompt = bufferParser.readString(true);\n const echo = bufferParser.readBool();\n if (echo === undefined)\n break;\n prompts[i] = { prompt, echo };\n }\n if (i !== numPrompts)\n prompts = undefined;\n }\n bufferParser.clear();\n\n if (prompts === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_REQUEST packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST');\n\n const handler = self._handlers.USERAUTH_INFO_REQUEST;\n handler && handler(self, name, instructions, prompts);\n break;\n }\n default:\n self._debug\n && self._debug('Inbound: Received unexpected payload type 60');\n }\n },\n 61: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 61 without auth');\n return;\n }\n /*\n byte SSH_MSG_USERAUTH_INFO_RESPONSE\n int num-responses\n string response[1] (ISO-10646 UTF-8)\n ...\n string response[num-responses] (ISO-10646 UTF-8)\n */\n if (self._authsQueue[0] !== 'keyboard-interactive') {\n return doFatalError(\n self,\n 'Inbound: Received unexpected payload type 61'\n );\n }\n bufferParser.init(payload, 1);\n const numResponses = bufferParser.readUInt32BE();\n let responses;\n if (numResponses !== undefined) {\n responses = new Array(numResponses);\n let i;\n for (i = 0; i < numResponses; ++i) {\n const response = bufferParser.readString(true);\n if (response === undefined)\n break;\n responses[i] = response;\n }\n if (i !== numResponses)\n responses = undefined;\n }\n bufferParser.clear();\n\n if (responses === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE');\n\n const handler = self._handlers.USERAUTH_INFO_RESPONSE;\n handler && handler(self, responses);\n },\n\n // Connection protocol -- generic ============================================\n [MESSAGE.GLOBAL_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_GLOBAL_REQUEST\n string request name in US-ASCII only\n boolean want reply\n .... request-specific data follows\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n const wantReply = bufferParser.readBool();\n let data;\n if (wantReply !== undefined) {\n switch (name) {\n case 'tcpip-forward':\n case 'cancel-tcpip-forward': {\n /*\n string address to bind (e.g., \"0.0.0.0\")\n uint32 port number to bind\n */\n const bindAddr = bufferParser.readString(true);\n const bindPort = bufferParser.readUInt32BE();\n if (bindPort !== undefined)\n data = { bindAddr, bindPort };\n break;\n }\n case 'streamlocal-forward@openssh.com':\n case 'cancel-streamlocal-forward@openssh.com': {\n /*\n string socket path\n */\n const socketPath = bufferParser.readString(true);\n if (socketPath !== undefined)\n data = { socketPath };\n break;\n }\n case 'no-more-sessions@openssh.com':\n data = null;\n break;\n case 'hostkeys-00@openssh.com': {\n data = [];\n while (bufferParser.avail() > 0) {\n const keyRaw = bufferParser.readString();\n if (keyRaw === undefined) {\n data = undefined;\n break;\n }\n const key = parseKey(keyRaw);\n if (!(key instanceof Error))\n data.push(key);\n }\n break;\n }\n default:\n data = bufferParser.readRaw();\n }\n }\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed GLOBAL_REQUEST packet'\n );\n }\n\n self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`);\n\n const handler = self._handlers.GLOBAL_REQUEST;\n if (handler)\n handler(self, name, wantReply, data);\n else\n self.requestFailure(); // Auto reject\n },\n [MESSAGE.REQUEST_SUCCESS]: (self, payload) => {\n /*\n byte SSH_MSG_REQUEST_SUCCESS\n .... response specific data\n */\n const data = (payload.length > 1 ? bufferSlice(payload, 1) : null);\n\n self._debug && self._debug('Inbound: REQUEST_SUCCESS');\n\n const handler = self._handlers.REQUEST_SUCCESS;\n handler && handler(self, data);\n },\n [MESSAGE.REQUEST_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_REQUEST_FAILURE\n */\n self._debug && self._debug('Inbound: Received REQUEST_FAILURE');\n\n const handler = self._handlers.REQUEST_FAILURE;\n handler && handler(self);\n },\n\n // Connection protocol -- channel-related ====================================\n [MESSAGE.CHANNEL_OPEN]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN\n string channel type in US-ASCII only\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n .... channel type specific data follows\n */\n bufferParser.init(payload, 1);\n const type = bufferParser.readString(true);\n const sender = bufferParser.readUInt32BE();\n const window = bufferParser.readUInt32BE();\n const packetSize = bufferParser.readUInt32BE();\n let channelInfo;\n\n switch (type) {\n case 'forwarded-tcpip': // S->C\n case 'direct-tcpip': { // C->S\n /*\n string address that was connected / host to connect\n uint32 port that was connected / port to connect\n string originator IP address\n uint32 originator port\n */\n const destIP = bufferParser.readString(true);\n const destPort = bufferParser.readUInt32BE();\n const srcIP = bufferParser.readString(true);\n const srcPort = bufferParser.readUInt32BE();\n if (srcPort !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { destIP, destPort, srcIP, srcPort }\n };\n }\n break;\n }\n case 'forwarded-streamlocal@openssh.com': // S->C\n case 'direct-streamlocal@openssh.com': { // C->S\n /*\n string socket path\n string reserved for future use\n\n (direct-streamlocal@openssh.com additionally has:)\n uint32 reserved\n */\n const socketPath = bufferParser.readString(true);\n if (socketPath !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { socketPath }\n };\n }\n break;\n }\n case 'x11': { // S->C\n /*\n string originator address (e.g., \"192.168.7.38\")\n uint32 originator port\n */\n const srcIP = bufferParser.readString(true);\n const srcPort = bufferParser.readUInt32BE();\n if (srcPort !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { srcIP, srcPort }\n };\n }\n break;\n }\n default:\n // Includes:\n // 'session' (C->S)\n // 'auth-agent@openssh.com' (S->C)\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: {}\n };\n }\n bufferParser.clear();\n\n if (channelInfo === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`);\n\n const handler = self._handlers.CHANNEL_OPEN;\n if (handler) {\n handler(self, channelInfo);\n } else {\n self.channelOpenFail(\n channelInfo.sender,\n CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED,\n '',\n ''\n );\n }\n },\n [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION\n uint32 recipient channel\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n .... channel type specific data follows\n */\n // \"The 'recipient channel' is the channel number given in the\n // original open request, and 'sender channel' is the channel number\n // allocated by the other side.\"\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const sender = bufferParser.readUInt32BE();\n const window = bufferParser.readUInt32BE();\n const packetSize = bufferParser.readUInt32BE();\n const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined);\n bufferParser.clear();\n\n if (packetSize === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})`\n );\n\n const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION;\n if (handler)\n handler(self, { recipient, sender, window, packetSize, data });\n },\n [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN_FAILURE\n uint32 recipient channel\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const reason = bufferParser.readUInt32BE();\n const description = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_OPEN_FAILURE;\n handler && handler(self, recipient, reason, description);\n },\n [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_WINDOW_ADJUST\n uint32 recipient channel\n uint32 bytes to add\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const bytesToAdd = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (bytesToAdd === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})`\n );\n\n const handler = self._handlers.CHANNEL_WINDOW_ADJUST;\n handler && handler(self, recipient, bytesToAdd);\n },\n [MESSAGE.CHANNEL_DATA]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_DATA\n uint32 recipient channel\n string data\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_DATA packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`);\n\n const handler = self._handlers.CHANNEL_DATA;\n handler && handler(self, recipient, data);\n },\n [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_EXTENDED_DATA\n uint32 recipient channel\n uint32 data_type_code\n string data\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const type = bufferParser.readUInt32BE();\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})`\n );\n\n const handler = self._handlers.CHANNEL_EXTENDED_DATA;\n handler && handler(self, recipient, data, type);\n },\n [MESSAGE.CHANNEL_EOF]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_EOF\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_EOF packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_EOF;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_CLOSE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_CLOSE\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_CLOSE packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_CLOSE;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_REQUEST\n uint32 recipient channel\n string request type in US-ASCII characters only\n boolean want reply\n .... type-specific data follows\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const type = bufferParser.readString(true);\n const wantReply = bufferParser.readBool();\n let data;\n if (wantReply !== undefined) {\n switch (type) {\n case 'exit-status': // S->C\n /*\n uint32 exit_status\n */\n data = bufferParser.readUInt32BE();\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'exit-signal': { // S->C\n /*\n string signal name (without the \"SIG\" prefix)\n boolean core dumped\n string error message in ISO-10646 UTF-8 encoding\n string language tag\n */\n let signal;\n let coreDumped;\n if (self._compatFlags & COMPAT.OLD_EXIT) {\n /*\n Instead of `signal name` and `core dumped`, we have just:\n uint32 signal number\n */\n const num = bufferParser.readUInt32BE();\n switch (num) {\n case 1:\n signal = 'HUP';\n break;\n case 2:\n signal = 'INT';\n break;\n case 3:\n signal = 'QUIT';\n break;\n case 6:\n signal = 'ABRT';\n break;\n case 9:\n signal = 'KILL';\n break;\n case 14:\n signal = 'ALRM';\n break;\n case 15:\n signal = 'TERM';\n break;\n default:\n if (num !== undefined) {\n // Unknown or OS-specific\n signal = `UNKNOWN (${num})`;\n }\n }\n coreDumped = false;\n } else {\n signal = bufferParser.readString(true);\n coreDumped = bufferParser.readBool();\n if (coreDumped === undefined)\n signal = undefined;\n }\n const errorMessage = bufferParser.readString(true);\n if (bufferParser.skipString() !== undefined)\n data = { signal, coreDumped, errorMessage };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})`\n );\n break;\n }\n case 'pty-req': { // C->S\n /*\n string TERM environment variable value (e.g., vt100)\n uint32 terminal width, characters (e.g., 80)\n uint32 terminal height, rows (e.g., 24)\n uint32 terminal width, pixels (e.g., 640)\n uint32 terminal height, pixels (e.g., 480)\n string encoded terminal modes\n */\n const term = bufferParser.readString(true);\n const cols = bufferParser.readUInt32BE();\n const rows = bufferParser.readUInt32BE();\n const width = bufferParser.readUInt32BE();\n const height = bufferParser.readUInt32BE();\n const modesBinary = bufferParser.readString();\n if (modesBinary !== undefined) {\n bufferParser.init(modesBinary, 1);\n let modes = {};\n while (bufferParser.avail()) {\n const opcode = bufferParser.readByte();\n if (opcode === TERMINAL_MODE.TTY_OP_END)\n break;\n const name = TERMINAL_MODE_BY_VALUE[opcode];\n const value = bufferParser.readUInt32BE();\n if (opcode === undefined\n || name === undefined\n || value === undefined) {\n modes = undefined;\n break;\n }\n modes[name] = value;\n }\n if (modes !== undefined)\n data = { term, cols, rows, width, height, modes };\n }\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'window-change': { // C->S\n /*\n uint32 terminal width, columns\n uint32 terminal height, rows\n uint32 terminal width, pixels\n uint32 terminal height, pixels\n */\n const cols = bufferParser.readUInt32BE();\n const rows = bufferParser.readUInt32BE();\n const width = bufferParser.readUInt32BE();\n const height = bufferParser.readUInt32BE();\n if (height !== undefined)\n data = { cols, rows, width, height };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'x11-req': { // C->S\n /*\n boolean single connection\n string x11 authentication protocol\n string x11 authentication cookie\n uint32 x11 screen number\n */\n const single = bufferParser.readBool();\n const protocol = bufferParser.readString(true);\n const cookie = bufferParser.readString();\n const screen = bufferParser.readUInt32BE();\n if (screen !== undefined)\n data = { single, protocol, cookie, screen };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'env': { // C->S\n /*\n string variable name\n string variable value\n */\n const name = bufferParser.readString(true);\n const value = bufferParser.readString(true);\n if (value !== undefined)\n data = { name, value };\n if (self._debug) {\n self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: `\n + `${name}=${value})`\n );\n }\n break;\n }\n case 'shell': // C->S\n data = null; // No extra data\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n case 'exec': // C->S\n /*\n string command\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'subsystem': // C->S\n /*\n string subsystem name\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'signal': // C->S\n /*\n string signal name (without the \"SIG\" prefix)\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'xon-xoff': // C->S\n /*\n boolean client can do\n */\n data = bufferParser.readBool();\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'auth-agent-req@openssh.com': // C-S\n data = null; // No extra data\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n default:\n data = (bufferParser.avail() ? bufferParser.readRaw() : null);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n }\n }\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_REQUEST packet'\n );\n }\n\n const handler = self._handlers.CHANNEL_REQUEST;\n handler && handler(self, recipient, type, wantReply, data);\n },\n [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_SUCCESS\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_SUCCESS packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_SUCCESS;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_FAILURE\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_FAILURE packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_FAILURE;\n handler && handler(self, recipient);\n },\n};\n","'use strict';\n\nconst {\n createDiffieHellman,\n createDiffieHellmanGroup,\n createECDH,\n createHash,\n createPublicKey,\n diffieHellman,\n generateKeyPairSync,\n randomFillSync,\n} = require('crypto');\n\nconst { Ber } = require('asn1');\n\nconst {\n COMPAT,\n curve25519Supported,\n DEFAULT_KEX,\n DEFAULT_SERVER_HOST_KEY,\n DEFAULT_CIPHER,\n DEFAULT_MAC,\n DEFAULT_COMPRESSION,\n DISCONNECT_REASON,\n MESSAGE,\n} = require('./constants.js');\nconst {\n CIPHER_INFO,\n createCipher,\n createDecipher,\n MAC_INFO,\n} = require('./crypto.js');\nconst { parseDERKey } = require('./keyParser.js');\nconst {\n bufferFill,\n bufferParser,\n convertSignature,\n doFatalError,\n FastBuffer,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./utils.js');\nconst {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n} = require('./zlib.js');\n\nlet MESSAGE_HANDLERS;\n\nconst GEX_MIN_BITS = 2048; // RFC 8270\nconst GEX_MAX_BITS = 8192; // RFC 8270\n\nconst EMPTY_BUFFER = Buffer.alloc(0);\n\n// Client/Server\nfunction kexinit(self) {\n /*\n byte SSH_MSG_KEXINIT\n byte[16] cookie (random bytes)\n name-list kex_algorithms\n name-list server_host_key_algorithms\n name-list encryption_algorithms_client_to_server\n name-list encryption_algorithms_server_to_client\n name-list mac_algorithms_client_to_server\n name-list mac_algorithms_server_to_client\n name-list compression_algorithms_client_to_server\n name-list compression_algorithms_server_to_client\n name-list languages_client_to_server\n name-list languages_server_to_client\n boolean first_kex_packet_follows\n uint32 0 (reserved for future extension)\n */\n\n let payload;\n if (self._compatFlags & COMPAT.BAD_DHGEX) {\n const entry = self._offer.lists.kex;\n let kex = entry.array;\n let found = false;\n for (let i = 0; i < kex.length; ++i) {\n if (kex[i].includes('group-exchange')) {\n if (!found) {\n found = true;\n // Copy array lazily\n kex = kex.slice();\n }\n kex.splice(i--, 1);\n }\n }\n if (found) {\n let len = 1 + 16 + self._offer.totalSize + 1 + 4;\n const newKexBuf = Buffer.from(kex.join(','));\n len -= (entry.buffer.length - newKexBuf.length);\n\n const all = self._offer.lists.all;\n const rest = new Uint8Array(\n all.buffer,\n all.byteOffset + 4 + entry.buffer.length,\n all.length - (4 + entry.buffer.length)\n );\n\n payload = Buffer.allocUnsafe(len);\n writeUInt32BE(payload, newKexBuf.length, 17);\n payload.set(newKexBuf, 17 + 4);\n payload.set(rest, 17 + 4 + newKexBuf.length);\n }\n }\n\n if (payload === undefined) {\n payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4);\n self._offer.copyAllTo(payload, 17);\n }\n\n self._debug && self._debug('Outbound: Sending KEXINIT');\n\n payload[0] = MESSAGE.KEXINIT;\n randomFillSync(payload, 1, 16);\n\n // Zero-fill first_kex_packet_follows and reserved bytes\n bufferFill(payload, 0, payload.length - 5);\n\n self._kexinit = payload;\n\n // Needed to correct the starting position in allocated \"packets\" when packets\n // will be buffered due to active key exchange\n self._packetRW.write.allocStart = 0;\n\n // TODO: only create single buffer and set _kexinit as slice of packet instead\n {\n const p = self._packetRW.write.allocStartKEX;\n const packet = self._packetRW.write.alloc(payload.length, true);\n packet.set(payload, p);\n self._cipher.encrypt(self._packetRW.write.finalize(packet, true));\n }\n}\n\nfunction handleKexInit(self, payload) {\n /*\n byte SSH_MSG_KEXINIT\n byte[16] cookie (random bytes)\n name-list kex_algorithms\n name-list server_host_key_algorithms\n name-list encryption_algorithms_client_to_server\n name-list encryption_algorithms_server_to_client\n name-list mac_algorithms_client_to_server\n name-list mac_algorithms_server_to_client\n name-list compression_algorithms_client_to_server\n name-list compression_algorithms_server_to_client\n name-list languages_client_to_server\n name-list languages_server_to_client\n boolean first_kex_packet_follows\n uint32 0 (reserved for future extension)\n */\n const init = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n sc: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n };\n\n bufferParser.init(payload, 17);\n\n if ((init.kex = bufferParser.readList()) === undefined\n || (init.serverHostKey = bufferParser.readList()) === undefined\n || (init.cs.cipher = bufferParser.readList()) === undefined\n || (init.sc.cipher = bufferParser.readList()) === undefined\n || (init.cs.mac = bufferParser.readList()) === undefined\n || (init.sc.mac = bufferParser.readList()) === undefined\n || (init.cs.compress = bufferParser.readList()) === undefined\n || (init.sc.compress = bufferParser.readList()) === undefined\n || (init.cs.lang = bufferParser.readList()) === undefined\n || (init.sc.lang = bufferParser.readList()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n self,\n 'Received malformed KEXINIT',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n const pos = bufferParser.pos();\n const firstFollows = (pos < payload.length && payload[pos] === 1);\n bufferParser.clear();\n\n const local = self._offer;\n const remote = init;\n\n let localKex = local.lists.kex.array;\n if (self._compatFlags & COMPAT.BAD_DHGEX) {\n let found = false;\n for (let i = 0; i < localKex.length; ++i) {\n if (localKex[i].indexOf('group-exchange') !== -1) {\n if (!found) {\n found = true;\n // Copy array lazily\n localKex = localKex.slice();\n }\n localKex.splice(i--, 1);\n }\n }\n }\n\n let clientList;\n let serverList;\n let i;\n const debug = self._debug;\n\n debug && debug('Inbound: Handshake in progress');\n\n // Key exchange method =======================================================\n debug && debug(`Handshake: (local) KEX method: ${localKex}`);\n debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`);\n if (self._server) {\n serverList = localKex;\n clientList = remote.kex;\n } else {\n serverList = remote.kex;\n clientList = localKex;\n }\n // Check for agreeable key exchange algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching key exchange algorithm');\n return doFatalError(\n self,\n 'Handshake failed: no matching key exchange algorithm',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.kex = clientList[i];\n debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`);\n if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) {\n // Ignore next inbound packet, it was a wrong first guess at KEX algorithm\n self._skipNextInboundPacket = true;\n }\n\n\n // Server host key format ====================================================\n const localSrvHostKey = local.lists.serverHostKey.array;\n debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`);\n debug && debug(\n `Handshake: (remote) Host key format: ${remote.serverHostKey}`\n );\n if (self._server) {\n serverList = localSrvHostKey;\n clientList = remote.serverHostKey;\n } else {\n serverList = remote.serverHostKey;\n clientList = localSrvHostKey;\n }\n // Check for agreeable server host key format\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching host key format');\n return doFatalError(\n self,\n 'Handshake failed: no matching host key format',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.serverHostKey = clientList[i];\n debug && debug(`Handshake: Host key format: ${clientList[i]}`);\n\n\n // Client->Server cipher =====================================================\n const localCSCipher = local.lists.cs.cipher.array;\n debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`);\n debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`);\n if (self._server) {\n serverList = localCSCipher;\n clientList = remote.cs.cipher;\n } else {\n serverList = remote.cs.cipher;\n clientList = localCSCipher;\n }\n // Check for agreeable client->server cipher\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S cipher');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S cipher',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.cipher = clientList[i];\n debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`);\n\n\n // Server->Client cipher =====================================================\n const localSCCipher = local.lists.sc.cipher.array;\n debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`);\n debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`);\n if (self._server) {\n serverList = localSCCipher;\n clientList = remote.sc.cipher;\n } else {\n serverList = remote.sc.cipher;\n clientList = localSCCipher;\n }\n // Check for agreeable server->client cipher\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C cipher');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C cipher',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.cipher = clientList[i];\n debug && debug(`Handshake: S->C cipher: ${clientList[i]}`);\n\n\n // Client->Server MAC ========================================================\n const localCSMAC = local.lists.cs.mac.array;\n debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`);\n debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`);\n if (CIPHER_INFO[init.cs.cipher].authLen > 0) {\n init.cs.mac = '';\n debug && debug('Handshake: C->S MAC: ');\n } else {\n if (self._server) {\n serverList = localCSMAC;\n clientList = remote.cs.mac;\n } else {\n serverList = remote.cs.mac;\n clientList = localCSMAC;\n }\n // Check for agreeable client->server hmac algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S MAC');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S MAC',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.mac = clientList[i];\n debug && debug(`Handshake: C->S MAC: ${clientList[i]}`);\n }\n\n\n // Server->Client MAC ========================================================\n const localSCMAC = local.lists.sc.mac.array;\n debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`);\n debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`);\n if (CIPHER_INFO[init.sc.cipher].authLen > 0) {\n init.sc.mac = '';\n debug && debug('Handshake: S->C MAC: ');\n } else {\n if (self._server) {\n serverList = localSCMAC;\n clientList = remote.sc.mac;\n } else {\n serverList = remote.sc.mac;\n clientList = localSCMAC;\n }\n // Check for agreeable server->client hmac algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C MAC');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C MAC',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.mac = clientList[i];\n debug && debug(`Handshake: S->C MAC: ${clientList[i]}`);\n }\n\n\n // Client->Server compression ================================================\n const localCSCompress = local.lists.cs.compress.array;\n debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`);\n debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`);\n if (self._server) {\n serverList = localCSCompress;\n clientList = remote.cs.compress;\n } else {\n serverList = remote.cs.compress;\n clientList = localCSCompress;\n }\n // Check for agreeable client->server compression algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S compression');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S compression',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.compress = clientList[i];\n debug && debug(`Handshake: C->S compression: ${clientList[i]}`);\n\n\n // Server->Client compression ================================================\n const localSCCompress = local.lists.sc.compress.array;\n debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`);\n debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`);\n if (self._server) {\n serverList = localSCCompress;\n clientList = remote.sc.compress;\n } else {\n serverList = remote.sc.compress;\n clientList = localSCCompress;\n }\n // Check for agreeable server->client compression algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C compression');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C compression',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.compress = clientList[i];\n debug && debug(`Handshake: S->C compression: ${clientList[i]}`);\n\n init.cs.lang = '';\n init.sc.lang = '';\n\n // XXX: hack -- find a better way to do this\n if (self._kex) {\n if (!self._kexinit) {\n // We received a rekey request, but we haven't sent a KEXINIT in response\n // yet\n kexinit(self);\n }\n self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false });\n }\n\n self._kex = createKeyExchange(init, self, payload);\n self._kex.start();\n}\n\nconst createKeyExchange = (() => {\n function convertToMpint(buf) {\n let idx = 0;\n let length = buf.length;\n while (buf[idx] === 0x00) {\n ++idx;\n --length;\n }\n let newBuf;\n if (buf[idx] & 0x80) {\n newBuf = Buffer.allocUnsafe(1 + length);\n newBuf[0] = 0;\n buf.copy(newBuf, 1, idx);\n buf = newBuf;\n } else if (length !== buf.length) {\n newBuf = Buffer.allocUnsafe(length);\n buf.copy(newBuf, 0, idx);\n buf = newBuf;\n }\n return buf;\n }\n\n class KeyExchange {\n constructor(negotiated, protocol, remoteKexinit) {\n this._protocol = protocol;\n\n this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined);\n this.negotiated = negotiated;\n this._step = 1;\n this._public = null;\n this._dh = null;\n this._sentNEWKEYS = false;\n this._receivedNEWKEYS = false;\n this._finished = false;\n this._hostVerified = false;\n\n // Data needed for initializing cipher/decipher/etc.\n this._kexinit = protocol._kexinit;\n this._remoteKexinit = remoteKexinit;\n this._identRaw = protocol._identRaw;\n this._remoteIdentRaw = protocol._remoteIdentRaw;\n this._hostKey = undefined;\n this._dhData = undefined;\n this._sig = undefined;\n }\n finish() {\n if (this._finished)\n return false;\n this._finished = true;\n\n const isServer = this._protocol._server;\n const negotiated = this.negotiated;\n\n const pubKey = this.convertPublicKey(this._dhData);\n let secret = this.computeSecret(this._dhData);\n if (secret instanceof Error) {\n secret.message =\n `Error while computing DH secret (${this.type}): ${secret.message}`;\n secret.level = 'handshake';\n return doFatalError(\n this._protocol,\n secret,\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n const hash = createHash(this.hashName);\n // V_C\n hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw));\n // \"V_S\"\n hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw));\n // \"I_C\"\n hashString(hash, (isServer ? this._remoteKexinit : this._kexinit));\n // \"I_S\"\n hashString(hash, (isServer ? this._kexinit : this._remoteKexinit));\n // \"K_S\"\n const serverPublicHostKey = (isServer\n ? this._hostKey.getPublicSSH()\n : this._hostKey);\n hashString(hash, serverPublicHostKey);\n\n if (this.type === 'groupex') {\n // Group exchange-specific\n const params = this.getDHParams();\n const num = Buffer.allocUnsafe(4);\n // min (uint32)\n writeUInt32BE(num, this._minBits, 0);\n hash.update(num);\n // preferred (uint32)\n writeUInt32BE(num, this._prefBits, 0);\n hash.update(num);\n // max (uint32)\n writeUInt32BE(num, this._maxBits, 0);\n hash.update(num);\n // prime\n hashString(hash, params.prime);\n // generator\n hashString(hash, params.generator);\n }\n\n // method-specific data sent by client\n hashString(hash, (isServer ? pubKey : this.getPublicKey()));\n // method-specific data sent by server\n const serverPublicKey = (isServer ? this.getPublicKey() : pubKey);\n hashString(hash, serverPublicKey);\n // shared secret (\"K\")\n hashString(hash, secret);\n\n // \"H\"\n const exchangeHash = hash.digest();\n\n if (!isServer) {\n bufferParser.init(this._sig, 0);\n const sigType = bufferParser.readString(true);\n\n if (!sigType) {\n return doFatalError(\n this._protocol,\n 'Malformed packet while reading signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (sigType !== negotiated.serverHostKey) {\n return doFatalError(\n this._protocol,\n `Wrong signature type: ${sigType}, `\n + `expected: ${negotiated.serverHostKey}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // \"s\"\n let sigValue = bufferParser.readString();\n\n bufferParser.clear();\n\n if (sigValue === undefined) {\n return doFatalError(\n this._protocol,\n 'Malformed packet while reading signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (!(sigValue = sigSSHToASN1(sigValue, sigType))) {\n return doFatalError(\n this._protocol,\n 'Malformed signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n let parsedHostKey;\n {\n bufferParser.init(this._hostKey, 0);\n const name = bufferParser.readString(true);\n const hostKey = this._hostKey.slice(bufferParser.pos());\n bufferParser.clear();\n parsedHostKey = parseDERKey(hostKey, name);\n if (parsedHostKey instanceof Error) {\n parsedHostKey.level = 'handshake';\n return doFatalError(\n this._protocol,\n parsedHostKey,\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n let hashAlgo;\n // Check if we need to override the default hash algorithm\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256': hashAlgo = 'sha256'; break;\n case 'rsa-sha2-512': hashAlgo = 'sha512'; break;\n }\n\n this._protocol._debug\n && this._protocol._debug('Verifying signature ...');\n\n const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo);\n if (verified !== true) {\n if (verified instanceof Error) {\n this._protocol._debug && this._protocol._debug(\n `Signature verification failed: ${verified.stack}`\n );\n } else {\n this._protocol._debug && this._protocol._debug(\n 'Signature verification failed'\n );\n }\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature verification failed',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug('Verified signature');\n } else {\n // Server\n\n let hashAlgo;\n // Check if we need to override the default hash algorithm\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256': hashAlgo = 'sha256'; break;\n case 'rsa-sha2-512': hashAlgo = 'sha512'; break;\n }\n\n this._protocol._debug && this._protocol._debug(\n 'Generating signature ...'\n );\n\n let signature = this._hostKey.sign(exchangeHash, hashAlgo);\n if (signature instanceof Error) {\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature generation failed for '\n + `${this._hostKey.type} host key: ${signature.message}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n signature = convertSignature(signature, this._hostKey.type);\n if (signature === false) {\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature conversion failed for '\n + `${this._hostKey.type} host key`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // Send KEX reply\n /*\n byte SSH_MSG_KEXDH_REPLY\n / SSH_MSG_KEX_DH_GEX_REPLY\n / SSH_MSG_KEX_ECDH_REPLY\n string server public host key and certificates (K_S)\n string \n string signature of H\n */\n const sigType = this.negotiated.serverHostKey;\n const sigTypeLen = Buffer.byteLength(sigType);\n const sigLen = 4 + sigTypeLen + 4 + signature.length;\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1\n + 4 + serverPublicHostKey.length\n + 4 + serverPublicKey.length\n + 4 + sigLen,\n true\n );\n\n packet[p] = MESSAGE.KEXDH_REPLY;\n\n writeUInt32BE(packet, serverPublicHostKey.length, ++p);\n packet.set(serverPublicHostKey, p += 4);\n\n writeUInt32BE(packet,\n serverPublicKey.length,\n p += serverPublicHostKey.length);\n packet.set(serverPublicKey, p += 4);\n\n writeUInt32BE(packet, sigLen, p += serverPublicKey.length);\n\n writeUInt32BE(packet, sigTypeLen, p += 4);\n packet.utf8Write(sigType, p += 4, sigTypeLen);\n\n writeUInt32BE(packet, signature.length, p += sigTypeLen);\n packet.set(signature, p += 4);\n\n if (this._protocol._debug) {\n let type;\n switch (this.type) {\n case 'group':\n type = 'KEXDH_REPLY';\n break;\n case 'groupex':\n type = 'KEXDH_GEX_REPLY';\n break;\n default:\n type = 'KEXECDH_REPLY';\n }\n this._protocol._debug(`Outbound: Sending ${type}`);\n }\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n trySendNEWKEYS(this);\n\n const completeHandshake = () => {\n if (!this.sessionID)\n this.sessionID = exchangeHash;\n\n {\n const newSecret = Buffer.allocUnsafe(4 + secret.length);\n writeUInt32BE(newSecret, secret.length, 0);\n newSecret.set(secret, 4);\n secret = newSecret;\n }\n\n // Initialize new ciphers, deciphers, etc.\n\n const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher];\n const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher];\n\n const csIV = generateKEXVal(csCipherInfo.ivLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'A');\n const scIV = generateKEXVal(scCipherInfo.ivLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'B');\n const csKey = generateKEXVal(csCipherInfo.keyLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'C');\n const scKey = generateKEXVal(scCipherInfo.keyLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'D');\n let csMacInfo;\n let csMacKey;\n if (!csCipherInfo.authLen) {\n csMacInfo = MAC_INFO[negotiated.cs.mac];\n csMacKey = generateKEXVal(csMacInfo.len,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'E');\n }\n let scMacInfo;\n let scMacKey;\n if (!scCipherInfo.authLen) {\n scMacInfo = MAC_INFO[negotiated.sc.mac];\n scMacKey = generateKEXVal(scMacInfo.len,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'F');\n }\n\n const config = {\n inbound: {\n onPayload: this._protocol._onPayload,\n seqno: this._protocol._decipher.inSeqno,\n decipherInfo: (!isServer ? scCipherInfo : csCipherInfo),\n decipherIV: (!isServer ? scIV : csIV),\n decipherKey: (!isServer ? scKey : csKey),\n macInfo: (!isServer ? scMacInfo : csMacInfo),\n macKey: (!isServer ? scMacKey : csMacKey),\n },\n outbound: {\n onWrite: this._protocol._onWrite,\n seqno: this._protocol._cipher.outSeqno,\n cipherInfo: (isServer ? scCipherInfo : csCipherInfo),\n cipherIV: (isServer ? scIV : csIV),\n cipherKey: (isServer ? scKey : csKey),\n macInfo: (isServer ? scMacInfo : csMacInfo),\n macKey: (isServer ? scMacKey : csMacKey),\n },\n };\n this._protocol._cipher && this._protocol._cipher.free();\n this._protocol._decipher && this._protocol._decipher.free();\n this._protocol._cipher = createCipher(config);\n this._protocol._decipher = createDecipher(config);\n\n const rw = {\n read: undefined,\n write: undefined,\n };\n switch (negotiated.cs.compress) {\n case 'zlib': // starts immediately\n if (isServer)\n rw.read = new ZlibPacketReader();\n else\n rw.write = new ZlibPacketWriter(this._protocol);\n break;\n case 'zlib@openssh.com':\n // Starts after successful user authentication\n\n if (this._protocol._authenticated) {\n // If a rekey happens and this compression method is selected and\n // we already authenticated successfully, we need to start\n // immediately instead\n if (isServer)\n rw.read = new ZlibPacketReader();\n else\n rw.write = new ZlibPacketWriter(this._protocol);\n break;\n }\n // FALLTHROUGH\n default:\n // none -- never any compression/decompression\n\n if (isServer)\n rw.read = new PacketReader();\n else\n rw.write = new PacketWriter(this._protocol);\n }\n switch (negotiated.sc.compress) {\n case 'zlib': // starts immediately\n if (isServer)\n rw.write = new ZlibPacketWriter(this._protocol);\n else\n rw.read = new ZlibPacketReader();\n break;\n case 'zlib@openssh.com':\n // Starts after successful user authentication\n\n if (this._protocol._authenticated) {\n // If a rekey happens and this compression method is selected and\n // we already authenticated successfully, we need to start\n // immediately instead\n if (isServer)\n rw.write = new ZlibPacketWriter(this._protocol);\n else\n rw.read = new ZlibPacketReader();\n break;\n }\n // FALLTHROUGH\n default:\n // none -- never any compression/decompression\n\n if (isServer)\n rw.write = new PacketWriter(this._protocol);\n else\n rw.read = new PacketReader();\n }\n this._protocol._packetRW.read.cleanup();\n this._protocol._packetRW.write.cleanup();\n this._protocol._packetRW = rw;\n\n // Cleanup/reset various state\n this._public = null;\n this._dh = null;\n this._kexinit = this._protocol._kexinit = undefined;\n this._remoteKexinit = undefined;\n this._identRaw = undefined;\n this._remoteIdentRaw = undefined;\n this._hostKey = undefined;\n this._dhData = undefined;\n this._sig = undefined;\n\n this._protocol._onHandshakeComplete(negotiated);\n\n return false;\n };\n if (!isServer)\n return completeHandshake();\n this.finish = completeHandshake;\n }\n\n start() {\n if (!this._protocol._server) {\n if (this._protocol._debug) {\n let type;\n switch (this.type) {\n case 'group':\n type = 'KEXDH_INIT';\n break;\n default:\n type = 'KEXECDH_INIT';\n }\n this._protocol._debug(`Outbound: Sending ${type}`);\n }\n\n const pubKey = this.getPublicKey();\n\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1 + 4 + pubKey.length,\n true\n );\n packet[p] = MESSAGE.KEXDH_INIT;\n writeUInt32BE(packet, pubKey.length, ++p);\n packet.set(pubKey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n }\n getPublicKey() {\n this.generateKeys();\n\n const key = this._public;\n\n if (key)\n return this.convertPublicKey(key);\n }\n convertPublicKey(key) {\n let newKey;\n let idx = 0;\n let len = key.length;\n while (key[idx] === 0x00) {\n ++idx;\n --len;\n }\n\n if (key[idx] & 0x80) {\n newKey = Buffer.allocUnsafe(1 + len);\n newKey[0] = 0;\n key.copy(newKey, 1, idx);\n return newKey;\n }\n\n if (len !== key.length) {\n newKey = Buffer.allocUnsafe(len);\n key.copy(newKey, 0, idx);\n key = newKey;\n }\n return key;\n }\n computeSecret(otherPublicKey) {\n this.generateKeys();\n\n try {\n return convertToMpint(this._dh.computeSecret(otherPublicKey));\n } catch (ex) {\n return ex;\n }\n }\n parse(payload) {\n const type = payload[0];\n switch (this._step) {\n case 1:\n if (this._protocol._server) {\n // Server\n if (type !== MESSAGE.KEXDH_INIT) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH Init'\n );\n /*\n byte SSH_MSG_KEXDH_INIT\n / SSH_MSG_KEX_ECDH_INIT\n string \n */\n bufferParser.init(payload, 1);\n const dhData = bufferParser.readString();\n bufferParser.clear();\n if (dhData === undefined) {\n return doFatalError(\n this._protocol,\n 'Received malformed KEX*_INIT',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // Client public key\n this._dhData = dhData;\n\n let hostKey =\n this._protocol._hostKeys[this.negotiated.serverHostKey];\n if (Array.isArray(hostKey))\n hostKey = hostKey[0];\n this._hostKey = hostKey;\n\n this.finish();\n } else {\n // Client\n if (type !== MESSAGE.KEXDH_REPLY) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH Reply'\n );\n /*\n byte SSH_MSG_KEXDH_REPLY\n / SSH_MSG_KEX_DH_GEX_REPLY\n / SSH_MSG_KEX_ECDH_REPLY\n string server public host key and certificates (K_S)\n string \n string signature of H\n */\n bufferParser.init(payload, 1);\n let hostPubKey;\n let dhData;\n let sig;\n if ((hostPubKey = bufferParser.readString()) === undefined\n || (dhData = bufferParser.readString()) === undefined\n || (sig = bufferParser.readString()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n this._protocol,\n 'Received malformed KEX*_REPLY',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n bufferParser.clear();\n\n // Check that the host public key type matches what was negotiated\n // during KEXINIT swap\n bufferParser.init(hostPubKey, 0);\n const hostPubKeyType = bufferParser.readString(true);\n bufferParser.clear();\n if (hostPubKeyType === undefined) {\n return doFatalError(\n this._protocol,\n 'Received malformed host public key',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n if (hostPubKeyType !== this.negotiated.serverHostKey) {\n // Check if we need to make an exception\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256':\n case 'rsa-sha2-512':\n if (hostPubKeyType === 'ssh-rsa')\n break;\n // FALLTHROUGH\n default:\n return doFatalError(\n this._protocol,\n 'Host key does not match negotiated type',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n this._hostKey = hostPubKey;\n this._dhData = dhData;\n this._sig = sig;\n\n let checked = false;\n let ret;\n if (this._protocol._hostVerifier === undefined) {\n ret = true;\n this._protocol._debug && this._protocol._debug(\n 'Host accepted by default (no verification)'\n );\n } else {\n ret = this._protocol._hostVerifier(hostPubKey, (permitted) => {\n if (checked)\n return;\n checked = true;\n if (permitted === false) {\n this._protocol._debug && this._protocol._debug(\n 'Host denied (verification failed)'\n );\n return doFatalError(\n this._protocol,\n 'Host denied (verification failed)',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Host accepted (verified)'\n );\n this._hostVerified = true;\n if (this._receivedNEWKEYS)\n this.finish();\n else\n trySendNEWKEYS(this);\n });\n }\n if (ret === undefined) {\n // Async host verification\n ++this._step;\n return;\n }\n checked = true;\n if (ret === false) {\n this._protocol._debug && this._protocol._debug(\n 'Host denied (verification failed)'\n );\n return doFatalError(\n this._protocol,\n 'Host denied (verification failed)',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Host accepted (verified)'\n );\n this._hostVerified = true;\n trySendNEWKEYS(this);\n }\n ++this._step;\n break;\n case 2:\n if (type !== MESSAGE.NEWKEYS) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Inbound: NEWKEYS'\n );\n this._receivedNEWKEYS = true;\n ++this._step;\n if (this._protocol._server || this._hostVerified)\n return this.finish();\n\n // Signal to current decipher that we need to change to a new decipher\n // for the next packet\n return false;\n default:\n return doFatalError(\n this._protocol,\n `Received unexpected packet ${type} after NEWKEYS`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n }\n\n class Curve25519Exchange extends KeyExchange {\n constructor(hashName, ...args) {\n super(...args);\n\n this.type = '25519';\n this.hashName = hashName;\n this._keys = null;\n }\n generateKeys() {\n if (!this._keys)\n this._keys = generateKeyPairSync('x25519');\n }\n getPublicKey() {\n this.generateKeys();\n\n const key = this._keys.publicKey.export({ type: 'spki', format: 'der' });\n return key.slice(-32); // HACK: avoids parsing DER/BER header\n }\n convertPublicKey(key) {\n let newKey;\n let idx = 0;\n let len = key.length;\n while (key[idx] === 0x00) {\n ++idx;\n --len;\n }\n\n if (key.length === 32)\n return key;\n\n if (len !== key.length) {\n newKey = Buffer.allocUnsafe(len);\n key.copy(newKey, 0, idx);\n key = newKey;\n }\n return key;\n }\n computeSecret(otherPublicKey) {\n this.generateKeys();\n\n try {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.110'); // id-X25519\n asnWriter.endSequence();\n\n // PublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(otherPublicKey.length);\n otherPublicKey.copy(asnWriter._buf,\n asnWriter._offset,\n 0,\n otherPublicKey.length);\n asnWriter._offset += otherPublicKey.length;\n asnWriter.endSequence();\n asnWriter.endSequence();\n\n return convertToMpint(diffieHellman({\n privateKey: this._keys.privateKey,\n publicKey: createPublicKey({\n key: asnWriter.buffer,\n type: 'spki',\n format: 'der',\n }),\n }));\n } catch (ex) {\n return ex;\n }\n }\n }\n\n class ECDHExchange extends KeyExchange {\n constructor(curveName, hashName, ...args) {\n super(...args);\n\n this.type = 'ecdh';\n this.curveName = curveName;\n this.hashName = hashName;\n }\n generateKeys() {\n if (!this._dh) {\n this._dh = createECDH(this.curveName);\n this._public = this._dh.generateKeys();\n }\n }\n }\n\n class DHGroupExchange extends KeyExchange {\n constructor(hashName, ...args) {\n super(...args);\n\n this.type = 'groupex';\n this.hashName = hashName;\n this._prime = null;\n this._generator = null;\n this._minBits = GEX_MIN_BITS;\n this._prefBits = dhEstimate(this.negotiated);\n if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE)\n this._prefBits = Math.min(this._prefBits, 4096);\n this._maxBits = GEX_MAX_BITS;\n }\n start() {\n if (this._protocol._server)\n return;\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_GEX_REQUEST'\n );\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1 + 4 + 4 + 4,\n true\n );\n packet[p] = MESSAGE.KEXDH_GEX_REQUEST;\n writeUInt32BE(packet, this._minBits, ++p);\n writeUInt32BE(packet, this._prefBits, p += 4);\n writeUInt32BE(packet, this._maxBits, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n generateKeys() {\n if (!this._dh && this._prime && this._generator) {\n this._dh = createDiffieHellman(this._prime, this._generator);\n this._public = this._dh.generateKeys();\n }\n }\n setDHParams(prime, generator) {\n if (!Buffer.isBuffer(prime))\n throw new Error('Invalid prime value');\n if (!Buffer.isBuffer(generator))\n throw new Error('Invalid generator value');\n this._prime = prime;\n this._generator = generator;\n }\n getDHParams() {\n if (this._dh) {\n return {\n prime: convertToMpint(this._dh.getPrime()),\n generator: convertToMpint(this._dh.getGenerator()),\n };\n }\n }\n parse(payload) {\n const type = payload[0];\n switch (this._step) {\n case 1:\n if (this._protocol._server) {\n if (type !== MESSAGE.KEXDH_GEX_REQUEST) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of `\n + MESSAGE.KEXDH_GEX_REQUEST,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n // TODO: allow user implementation to provide safe prime and\n // generator on demand to support group exchange on server side\n return doFatalError(\n this._protocol,\n 'Group exchange not implemented for server',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (type !== MESSAGE.KEXDH_GEX_GROUP) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Group'\n );\n\n /*\n byte SSH_MSG_KEX_DH_GEX_GROUP\n mpint p, safe prime\n mpint g, generator for subgroup in GF(p)\n */\n bufferParser.init(payload, 1);\n let prime;\n let gen;\n if ((prime = bufferParser.readString()) === undefined\n || (gen = bufferParser.readString()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n this._protocol,\n 'Received malformed KEXDH_GEX_GROUP',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n bufferParser.clear();\n\n // TODO: validate prime\n this.setDHParams(prime, gen);\n this.generateKeys();\n const pubkey = this.getPublicKey();\n\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_GEX_INIT'\n );\n\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet =\n this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true);\n packet[p] = MESSAGE.KEXDH_GEX_INIT;\n writeUInt32BE(packet, pubkey.length, ++p);\n packet.set(pubkey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n\n ++this._step;\n break;\n case 2:\n if (this._protocol._server) {\n if (type !== MESSAGE.KEXDH_GEX_INIT) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Init'\n );\n return doFatalError(\n this._protocol,\n 'Group exchange not implemented for server',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n } else if (type !== MESSAGE.KEXDH_GEX_REPLY) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Reply'\n );\n this._step = 1;\n payload[0] = MESSAGE.KEXDH_REPLY;\n this.parse = KeyExchange.prototype.parse;\n this.parse(payload);\n }\n }\n }\n\n class DHExchange extends KeyExchange {\n constructor(groupName, hashName, ...args) {\n super(...args);\n\n this.type = 'group';\n this.groupName = groupName;\n this.hashName = hashName;\n }\n start() {\n if (!this._protocol._server) {\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_INIT'\n );\n const pubKey = this.getPublicKey();\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet =\n this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true);\n packet[p] = MESSAGE.KEXDH_INIT;\n writeUInt32BE(packet, pubKey.length, ++p);\n packet.set(pubKey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n }\n generateKeys() {\n if (!this._dh) {\n this._dh = createDiffieHellmanGroup(this.groupName);\n this._public = this._dh.generateKeys();\n }\n }\n getDHParams() {\n if (this._dh) {\n return {\n prime: convertToMpint(this._dh.getPrime()),\n generator: convertToMpint(this._dh.getGenerator()),\n };\n }\n }\n }\n\n return (negotiated, ...args) => {\n if (typeof negotiated !== 'object' || negotiated === null)\n throw new Error('Invalid negotiated argument');\n const kexType = negotiated.kex;\n if (typeof kexType === 'string') {\n args = [negotiated, ...args];\n switch (kexType) {\n case 'curve25519-sha256':\n case 'curve25519-sha256@libssh.org':\n if (!curve25519Supported)\n break;\n return new Curve25519Exchange('sha256', ...args);\n\n case 'ecdh-sha2-nistp256':\n return new ECDHExchange('prime256v1', 'sha256', ...args);\n case 'ecdh-sha2-nistp384':\n return new ECDHExchange('secp384r1', 'sha384', ...args);\n case 'ecdh-sha2-nistp521':\n return new ECDHExchange('secp521r1', 'sha512', ...args);\n\n case 'diffie-hellman-group1-sha1':\n return new DHExchange('modp2', 'sha1', ...args);\n case 'diffie-hellman-group14-sha1':\n return new DHExchange('modp14', 'sha1', ...args);\n case 'diffie-hellman-group14-sha256':\n return new DHExchange('modp14', 'sha256', ...args);\n case 'diffie-hellman-group15-sha512':\n return new DHExchange('modp15', 'sha512', ...args);\n case 'diffie-hellman-group16-sha512':\n return new DHExchange('modp16', 'sha512', ...args);\n case 'diffie-hellman-group17-sha512':\n return new DHExchange('modp17', 'sha512', ...args);\n case 'diffie-hellman-group18-sha512':\n return new DHExchange('modp18', 'sha512', ...args);\n\n case 'diffie-hellman-group-exchange-sha1':\n return new DHGroupExchange('sha1', ...args);\n case 'diffie-hellman-group-exchange-sha256':\n return new DHGroupExchange('sha256', ...args);\n }\n throw new Error(`Unsupported key exchange algorithm: ${kexType}`);\n }\n throw new Error(`Invalid key exchange type: ${kexType}`);\n };\n})();\n\nconst KexInit = (() => {\n const KEX_PROPERTY_NAMES = [\n 'kex',\n 'serverHostKey',\n ['cs', 'cipher' ],\n ['sc', 'cipher' ],\n ['cs', 'mac' ],\n ['sc', 'mac' ],\n ['cs', 'compress' ],\n ['sc', 'compress' ],\n ['cs', 'lang' ],\n ['sc', 'lang' ],\n ];\n return class KexInit {\n constructor(obj) {\n if (typeof obj !== 'object' || obj === null)\n throw new TypeError('Argument must be an object');\n\n const lists = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n sc: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n\n all: undefined,\n };\n let totalSize = 0;\n for (const prop of KEX_PROPERTY_NAMES) {\n let base;\n let val;\n let desc;\n let key;\n if (typeof prop === 'string') {\n base = lists;\n val = obj[prop];\n desc = key = prop;\n } else {\n const parent = prop[0];\n base = lists[parent];\n key = prop[1];\n val = obj[parent][key];\n desc = `${parent}.${key}`;\n }\n const entry = { array: undefined, buffer: undefined };\n if (Buffer.isBuffer(val)) {\n entry.array = ('' + val).split(',');\n entry.buffer = val;\n totalSize += 4 + val.length;\n } else {\n if (typeof val === 'string')\n val = val.split(',');\n if (Array.isArray(val)) {\n entry.array = val;\n entry.buffer = Buffer.from(val.join(','));\n } else {\n throw new TypeError(`Invalid \\`${desc}\\` type: ${typeof val}`);\n }\n totalSize += 4 + entry.buffer.length;\n }\n base[key] = entry;\n }\n\n const all = Buffer.allocUnsafe(totalSize);\n lists.all = all;\n\n let allPos = 0;\n for (const prop of KEX_PROPERTY_NAMES) {\n let data;\n if (typeof prop === 'string')\n data = lists[prop].buffer;\n else\n data = lists[prop[0]][prop[1]].buffer;\n allPos = writeUInt32BE(all, data.length, allPos);\n all.set(data, allPos);\n allPos += data.length;\n }\n\n this.totalSize = totalSize;\n this.lists = lists;\n }\n copyAllTo(buf, offset) {\n const src = this.lists.all;\n if (typeof offset !== 'number')\n throw new TypeError(`Invalid offset value: ${typeof offset}`);\n if (buf.length - offset < src.length)\n throw new Error('Insufficient space to copy list');\n buf.set(src, offset);\n return src.length;\n }\n };\n})();\n\nconst hashString = (() => {\n const LEN = Buffer.allocUnsafe(4);\n return (hash, buf) => {\n writeUInt32BE(LEN, buf.length, 0);\n hash.update(LEN);\n hash.update(buf);\n };\n})();\n\nfunction generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) {\n let ret;\n if (len) {\n let digest = createHash(hashName)\n .update(secret)\n .update(exchangeHash)\n .update(char)\n .update(sessionID)\n .digest();\n while (digest.length < len) {\n const chunk = createHash(hashName)\n .update(secret)\n .update(exchangeHash)\n .update(digest)\n .digest();\n const extended = Buffer.allocUnsafe(digest.length + chunk.length);\n extended.set(digest, 0);\n extended.set(chunk, digest.length);\n digest = extended;\n }\n if (digest.length === len)\n ret = digest;\n else\n ret = new FastBuffer(digest.buffer, digest.byteOffset, len);\n } else {\n ret = EMPTY_BUFFER;\n }\n return ret;\n}\n\nfunction onKEXPayload(state, payload) {\n // XXX: move this to the Decipher implementations?\n if (payload.length === 0) {\n this._debug && this._debug('Inbound: Skipping empty packet payload');\n return;\n }\n\n if (this._skipNextInboundPacket) {\n this._skipNextInboundPacket = false;\n return;\n }\n\n payload = this._packetRW.read.read(payload);\n\n const type = payload[0];\n switch (type) {\n case MESSAGE.DISCONNECT:\n case MESSAGE.IGNORE:\n case MESSAGE.UNIMPLEMENTED:\n case MESSAGE.DEBUG:\n if (!MESSAGE_HANDLERS)\n MESSAGE_HANDLERS = require('./handlers.js');\n return MESSAGE_HANDLERS[type](this, payload);\n case MESSAGE.KEXINIT:\n if (!state.firstPacket) {\n return doFatalError(\n this,\n 'Received extra KEXINIT during handshake',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n state.firstPacket = false;\n return handleKexInit(this, payload);\n default:\n if (type < 20 || type > 49) {\n return doFatalError(\n this,\n `Received unexpected packet type ${type}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n return this._kex.parse(payload);\n}\n\nfunction dhEstimate(neg) {\n const csCipher = CIPHER_INFO[neg.cs.cipher];\n const scCipher = CIPHER_INFO[neg.sc.cipher];\n // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will\n // also need to be considered when calculating `bits`\n const bits = Math.max(\n 0,\n (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen),\n csCipher.blockLen,\n csCipher.ivLen,\n (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen),\n scCipher.blockLen,\n scCipher.ivLen\n ) * 8;\n if (bits <= 112)\n return 2048;\n if (bits <= 128)\n return 3072;\n if (bits <= 192)\n return 7680;\n return 8192;\n}\n\nfunction trySendNEWKEYS(kex) {\n if (!kex._sentNEWKEYS) {\n kex._protocol._debug && kex._protocol._debug(\n 'Outbound: Sending NEWKEYS'\n );\n const p = kex._protocol._packetRW.write.allocStartKEX;\n const packet = kex._protocol._packetRW.write.alloc(1, true);\n packet[p] = MESSAGE.NEWKEYS;\n kex._protocol._cipher.encrypt(\n kex._protocol._packetRW.write.finalize(packet, true)\n );\n kex._sentNEWKEYS = true;\n }\n}\n\nmodule.exports = {\n KexInit,\n kexinit,\n onKEXPayload,\n DEFAULT_KEXINIT: new KexInit({\n kex: DEFAULT_KEX,\n serverHostKey: DEFAULT_SERVER_HOST_KEY,\n cs: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n sc: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n }),\n HANDLERS: {\n [MESSAGE.KEXINIT]: handleKexInit,\n },\n};\n","// TODO:\n// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()`\n// * handle multi-line header values (OpenSSH)?\n// * more thorough validation?\n'use strict';\n\nconst {\n createDecipheriv,\n createECDH,\n createHash,\n createHmac,\n createSign,\n createVerify,\n getCiphers,\n sign: sign_,\n verify: verify_,\n} = require('crypto');\nconst supportedOpenSSLCiphers = getCiphers();\n\nconst { Ber } = require('asn1');\nconst bcrypt_pbkdf = require('bcrypt-pbkdf').pbkdf;\n\nconst { CIPHER_INFO } = require('./crypto.js');\nconst { eddsaSupported, SUPPORTED_CIPHER } = require('./constants.js');\nconst {\n bufferSlice,\n makeBufferParser,\n readString,\n readUInt32BE,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst SYM_HASH_ALGO = Symbol('Hash Algorithm');\nconst SYM_PRIV_PEM = Symbol('Private key PEM');\nconst SYM_PUB_PEM = Symbol('Public key PEM');\nconst SYM_PUB_SSH = Symbol('Public key SSH');\nconst SYM_DECRYPTED = Symbol('Decrypted Key');\n\n// Create OpenSSL cipher name -> SSH cipher name conversion table\nconst CIPHER_INFO_OPENSSL = Object.create(null);\n{\n const keys = Object.keys(CIPHER_INFO);\n for (let i = 0; i < keys.length; ++i) {\n const cipherName = CIPHER_INFO[keys[i]].sslName;\n if (!cipherName || CIPHER_INFO_OPENSSL[cipherName])\n continue;\n CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]];\n }\n}\n\nconst binaryKeyParser = makeBufferParser();\n\nfunction makePEM(type, data) {\n data = data.base64Slice(0, data.length);\n let formatted = data.replace(/.{64}/g, '$&\\n');\n if (data.length & 63)\n formatted += '\\n';\n return `-----BEGIN ${type} KEY-----\\n${formatted}-----END ${type} KEY-----`;\n}\n\nfunction combineBuffers(buf1, buf2) {\n const result = Buffer.allocUnsafe(buf1.length + buf2.length);\n result.set(buf1, 0);\n result.set(buf2, buf1.length);\n return result;\n}\n\nfunction skipFields(buf, nfields) {\n const bufLen = buf.length;\n let pos = (buf._pos || 0);\n for (let i = 0; i < nfields; ++i) {\n const left = (bufLen - pos);\n if (pos >= bufLen || left < 4)\n return false;\n const len = readUInt32BE(buf, pos);\n if (left < 4 + len)\n return false;\n pos += 4 + len;\n }\n buf._pos = pos;\n return true;\n}\n\nfunction genOpenSSLRSAPub(n, e) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption\n // algorithm parameters (RSA has none)\n asnWriter.writeNull();\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n asnWriter.startSequence();\n asnWriter.writeBuffer(n, Ber.Integer);\n asnWriter.writeBuffer(e, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHRSAPub(n, e) {\n const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length);\n\n writeUInt32BE(publicKey, 7, 0);\n publicKey.utf8Write('ssh-rsa', 4, 7);\n\n let i = 4 + 7;\n writeUInt32BE(publicKey, e.length, i);\n publicKey.set(e, i += 4);\n\n writeUInt32BE(publicKey, n.length, i += e.length);\n publicKey.set(n, i + 4);\n\n return publicKey;\n}\n\nconst genOpenSSLRSAPriv = (() => {\n function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeInt(0x00, Ber.Integer);\n asnWriter.writeBuffer(n, Ber.Integer);\n asnWriter.writeBuffer(e, Ber.Integer);\n asnWriter.writeBuffer(d, Ber.Integer);\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(dmp1, Ber.Integer);\n asnWriter.writeBuffer(dmq1, Ber.Integer);\n asnWriter.writeBuffer(iqmp, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n\n function bigIntFromBuffer(buf) {\n return BigInt(`0x${buf.hexSlice(0, buf.length)}`);\n }\n\n function bigIntToBuffer(bn) {\n let hex = bn.toString(16);\n if ((hex.length & 1) !== 0) {\n hex = `0${hex}`;\n } else {\n const sigbit = hex.charCodeAt(0);\n // BER/DER integers require leading zero byte to denote a positive value\n // when first byte >= 0x80\n if (sigbit === 56/* '8' */\n || sigbit === 57/* '9' */\n || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) {\n hex = `00${hex}`;\n }\n }\n return Buffer.from(hex, 'hex');\n }\n\n return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) {\n const bn_d = bigIntFromBuffer(d);\n const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n));\n const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n));\n return makePEM('RSA PRIVATE',\n genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp));\n };\n})();\n\nfunction genOpenSSLDSAPub(p, q, g, y) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa\n // algorithm parameters\n asnWriter.startSequence();\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(g, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n asnWriter.writeBuffer(y, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHDSAPub(p, q, g, y) {\n const publicKey = Buffer.allocUnsafe(\n 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length\n );\n\n writeUInt32BE(publicKey, 7, 0);\n publicKey.utf8Write('ssh-dss', 4, 7);\n\n let i = 4 + 7;\n writeUInt32BE(publicKey, p.length, i);\n publicKey.set(p, i += 4);\n\n writeUInt32BE(publicKey, q.length, i += p.length);\n publicKey.set(q, i += 4);\n\n writeUInt32BE(publicKey, g.length, i += q.length);\n publicKey.set(g, i += 4);\n\n writeUInt32BE(publicKey, y.length, i += g.length);\n publicKey.set(y, i + 4);\n\n return publicKey;\n}\n\nfunction genOpenSSLDSAPriv(p, q, g, y, x) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeInt(0x00, Ber.Integer);\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(g, Ber.Integer);\n asnWriter.writeBuffer(y, Ber.Integer);\n asnWriter.writeBuffer(x, Ber.Integer);\n asnWriter.endSequence();\n return makePEM('DSA PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLEdPub(pub) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.112'); // id-Ed25519\n asnWriter.endSequence();\n\n // PublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(pub.length);\n asnWriter._buf.set(pub, asnWriter._offset);\n asnWriter._offset += pub.length;\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHEdPub(pub) {\n const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length);\n\n writeUInt32BE(publicKey, 11, 0);\n publicKey.utf8Write('ssh-ed25519', 4, 11);\n\n writeUInt32BE(publicKey, pub.length, 15);\n publicKey.set(pub, 19);\n\n return publicKey;\n}\n\nfunction genOpenSSLEdPriv(priv) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // version\n asnWriter.writeInt(0x00, Ber.Integer);\n\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.112'); // id-Ed25519\n asnWriter.endSequence();\n\n // PrivateKey\n asnWriter.startSequence(Ber.OctetString);\n asnWriter.writeBuffer(priv, Ber.OctetString);\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLECDSAPub(oid, Q) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey\n // algorithm parameters (namedCurve)\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(Q.length);\n asnWriter._buf.set(Q, asnWriter._offset);\n asnWriter._offset += Q.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHECDSAPub(oid, Q) {\n let curveName;\n switch (oid) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n curveName = 'nistp256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n curveName = 'nistp384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n curveName = 'nistp521';\n break;\n default:\n return;\n }\n\n const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length);\n\n writeUInt32BE(publicKey, 19, 0);\n publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19);\n\n writeUInt32BE(publicKey, 8, 23);\n publicKey.utf8Write(curveName, 27, 8);\n\n writeUInt32BE(publicKey, Q.length, 35);\n publicKey.set(Q, 39);\n\n return publicKey;\n}\n\nfunction genOpenSSLECDSAPriv(oid, pub, priv) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // version\n asnWriter.writeInt(0x01, Ber.Integer);\n // privateKey\n asnWriter.writeBuffer(priv, Ber.OctetString);\n // parameters (optional)\n asnWriter.startSequence(0xA0);\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n // publicKey (optional)\n asnWriter.startSequence(0xA1);\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(pub.length);\n asnWriter._buf.set(pub, asnWriter._offset);\n asnWriter._offset += pub.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('EC PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLECDSAPubFromPriv(curveName, priv) {\n const tempECDH = createECDH(curveName);\n tempECDH.setPrivateKey(priv);\n return tempECDH.getPublicKey();\n}\n\nconst BaseKey = {\n sign: (() => {\n if (typeof sign_ === 'function') {\n return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return sign_(algo, data, pem);\n } catch (ex) {\n return ex;\n }\n };\n }\n return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n const signature = createSign(algo);\n signature.update(data);\n try {\n return signature.sign(pem);\n } catch (ex) {\n return ex;\n }\n };\n })(),\n verify: (() => {\n if (typeof verify_ === 'function') {\n return function verify(data, signature, algo) {\n const pem = this[SYM_PUB_PEM];\n if (pem === null)\n return new Error('No public key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return verify_(algo, data, pem, signature);\n } catch (ex) {\n return ex;\n }\n };\n }\n return function verify(data, signature, algo) {\n const pem = this[SYM_PUB_PEM];\n if (pem === null)\n return new Error('No public key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n const verifier = createVerify(algo);\n verifier.update(data);\n try {\n return verifier.verify(pem, signature);\n } catch (ex) {\n return ex;\n }\n };\n })(),\n isPrivateKey: function isPrivateKey() {\n return (this[SYM_PRIV_PEM] !== null);\n },\n getPrivatePEM: function getPrivatePEM() {\n return this[SYM_PRIV_PEM];\n },\n getPublicPEM: function getPublicPEM() {\n return this[SYM_PUB_PEM];\n },\n getPublicSSH: function getPublicSSH() {\n return this[SYM_PUB_SSH];\n },\n equals: function equals(key) {\n const parsed = parseKey(key);\n if (parsed instanceof Error)\n return false;\n return (\n this.type === parsed.type\n && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM]\n && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM]\n && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH]\n );\n },\n};\n\n\nfunction OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo,\n decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nOpenSSH_Private.prototype = BaseKey;\n{\n const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\\r\\n|\\n)([\\s\\S]+)(?:\\r\\n|\\n)-----END OPENSSH PRIVATE KEY-----$/;\n OpenSSH_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n let ret;\n const data = Buffer.from(m[1], 'base64');\n if (data.length < 31) // magic (+ magic null term.) + minimum field lengths\n return new Error('Malformed OpenSSH private key');\n const magic = data.utf8Slice(0, 15);\n if (magic !== 'openssh-key-v1\\0')\n return new Error(`Unsupported OpenSSH key magic: ${magic}`);\n\n const cipherName = readString(data, 15, true);\n if (cipherName === undefined)\n return new Error('Malformed OpenSSH private key');\n if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1)\n return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`);\n\n const kdfName = readString(data, data._pos, true);\n if (kdfName === undefined)\n return new Error('Malformed OpenSSH private key');\n if (kdfName !== 'none') {\n if (cipherName === 'none')\n return new Error('Malformed OpenSSH private key');\n if (kdfName !== 'bcrypt')\n return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`);\n if (!passphrase) {\n return new Error(\n 'Encrypted private OpenSSH key detected, but no passphrase given'\n );\n }\n } else if (cipherName !== 'none') {\n return new Error('Malformed OpenSSH private key');\n }\n\n let encInfo;\n let cipherKey;\n let cipherIV;\n if (cipherName !== 'none')\n encInfo = CIPHER_INFO[cipherName];\n const kdfOptions = readString(data, data._pos);\n if (kdfOptions === undefined)\n return new Error('Malformed OpenSSH private key');\n if (kdfOptions.length) {\n switch (kdfName) {\n case 'none':\n return new Error('Malformed OpenSSH private key');\n case 'bcrypt':\n /*\n string salt\n uint32 rounds\n */\n const salt = readString(kdfOptions, 0);\n if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length)\n return new Error('Malformed OpenSSH private key');\n const rounds = readUInt32BE(kdfOptions, kdfOptions._pos);\n const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen);\n const r = bcrypt_pbkdf(passphrase,\n passphrase.length,\n salt,\n salt.length,\n gen,\n gen.length,\n rounds);\n if (r !== 0)\n return new Error('Failed to generate information to decrypt key');\n cipherKey = bufferSlice(gen, 0, encInfo.keyLen);\n cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length);\n break;\n }\n } else if (kdfName !== 'none') {\n return new Error('Malformed OpenSSH private key');\n }\n\n if (data._pos + 3 >= data.length)\n return new Error('Malformed OpenSSH private key');\n const keyCount = readUInt32BE(data, data._pos);\n data._pos += 4;\n\n if (keyCount > 0) {\n // TODO: place sensible limit on max `keyCount`\n\n // Read public keys first\n for (let i = 0; i < keyCount; ++i) {\n const pubData = readString(data, data._pos);\n if (pubData === undefined)\n return new Error('Malformed OpenSSH private key');\n const type = readString(pubData, 0, true);\n if (type === undefined)\n return new Error('Malformed OpenSSH private key');\n }\n\n let privBlob = readString(data, data._pos);\n if (privBlob === undefined)\n return new Error('Malformed OpenSSH private key');\n\n if (cipherKey !== undefined) {\n // Encrypted private key(s)\n if (privBlob.length < encInfo.blockLen\n || (privBlob.length % encInfo.blockLen) !== 0) {\n return new Error('Malformed OpenSSH private key');\n }\n try {\n const options = { authTagLength: encInfo.authLen };\n const decipher = createDecipheriv(encInfo.sslName,\n cipherKey,\n cipherIV,\n options);\n if (encInfo.authLen > 0) {\n if (data.length - data._pos < encInfo.authLen)\n return new Error('Malformed OpenSSH private key');\n decipher.setAuthTag(\n bufferSlice(data, data._pos, data._pos += encInfo.authLen)\n );\n }\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n } catch (ex) {\n return ex;\n }\n }\n // Nothing should we follow the private key(s), except a possible\n // authentication tag for relevant ciphers\n if (data._pos !== data.length)\n return new Error('Malformed OpenSSH private key');\n\n ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined);\n } else {\n ret = [];\n }\n if (ret instanceof Error)\n return ret;\n // This will need to change if/when OpenSSH ever starts storing multiple\n // keys in their key files\n return ret[0];\n };\n\n function parseOpenSSHPrivKeys(data, nkeys, decrypted) {\n const keys = [];\n /*\n uint32 checkint\n uint32 checkint\n string privatekey1\n string comment1\n string privatekey2\n string comment2\n ...\n string privatekeyN\n string commentN\n char 1\n char 2\n char 3\n ...\n char padlen % 255\n */\n if (data.length < 8)\n return new Error('Malformed OpenSSH private key');\n const check1 = readUInt32BE(data, 0);\n const check2 = readUInt32BE(data, 4);\n if (check1 !== check2) {\n if (decrypted) {\n return new Error(\n 'OpenSSH key integrity check failed -- bad passphrase?'\n );\n }\n return new Error('OpenSSH key integrity check failed');\n }\n data._pos = 8;\n let i;\n let oid;\n for (i = 0; i < nkeys; ++i) {\n let algo;\n let privPEM;\n let pubPEM;\n let pubSSH;\n // The OpenSSH documentation for the key format actually lies, the\n // entirety of the private key content is not contained with a string\n // field, it's actually the literal contents of the private key, so to be\n // able to find the end of the key data you need to know the layout/format\n // of each key type ...\n const type = readString(data, data._pos, true);\n if (type === undefined)\n return new Error('Malformed OpenSSH private key');\n\n switch (type) {\n case 'ssh-rsa': {\n /*\n string n -- public\n string e -- public\n string d -- private\n string iqmp -- private\n string p -- private\n string q -- private\n */\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed OpenSSH private key');\n const e = readString(data, data._pos);\n if (e === undefined)\n return new Error('Malformed OpenSSH private key');\n const d = readString(data, data._pos);\n if (d === undefined)\n return new Error('Malformed OpenSSH private key');\n const iqmp = readString(data, data._pos);\n if (iqmp === undefined)\n return new Error('Malformed OpenSSH private key');\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed OpenSSH private key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q);\n algo = 'sha1';\n break;\n }\n case 'ssh-dss': {\n /*\n string p -- public\n string q -- public\n string g -- public\n string y -- public\n string x -- private\n */\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed OpenSSH private key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH private key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed OpenSSH private key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed OpenSSH private key');\n const x = readString(data, data._pos);\n if (x === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n privPEM = genOpenSSLDSAPriv(p, q, g, y, x);\n algo = 'sha1';\n break;\n }\n case 'ssh-ed25519': {\n if (!eddsaSupported)\n return new Error(`Unsupported OpenSSH private key type: ${type}`);\n /*\n * string public key\n * string private key + public key\n */\n const edpub = readString(data, data._pos);\n if (edpub === undefined || edpub.length !== 32)\n return new Error('Malformed OpenSSH private key');\n const edpriv = readString(data, data._pos);\n if (edpriv === undefined || edpriv.length !== 64)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLEdPub(edpub);\n pubSSH = genOpenSSHEdPub(edpub);\n privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32));\n algo = null;\n break;\n }\n case 'ecdsa-sha2-nistp256':\n algo = 'sha256';\n oid = '1.2.840.10045.3.1.7';\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp384':\n if (algo === undefined) {\n algo = 'sha384';\n oid = '1.3.132.0.34';\n }\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp521': {\n if (algo === undefined) {\n algo = 'sha512';\n oid = '1.3.132.0.35';\n }\n /*\n string curve name\n string Q -- public\n string d -- private\n */\n // TODO: validate curve name against type\n if (!skipFields(data, 1)) // Skip curve name\n return new Error('Malformed OpenSSH private key');\n const ecpub = readString(data, data._pos);\n if (ecpub === undefined)\n return new Error('Malformed OpenSSH private key');\n const ecpriv = readString(data, data._pos);\n if (ecpriv === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLECDSAPub(oid, ecpub);\n pubSSH = genOpenSSHECDSAPub(oid, ecpub);\n privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv);\n break;\n }\n default:\n return new Error(`Unsupported OpenSSH private key type: ${type}`);\n }\n\n const privComment = readString(data, data._pos, true);\n if (privComment === undefined)\n return new Error('Malformed OpenSSH private key');\n\n keys.push(\n new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo,\n decrypted)\n );\n }\n let cnt = 0;\n for (i = data._pos; i < data.length; ++i) {\n if (data[i] !== (++cnt % 255))\n return new Error('Malformed OpenSSH private key');\n }\n\n return keys;\n }\n}\n\n\nfunction OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo,\n decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nOpenSSH_Old_Private.prototype = BaseKey;\n{\n const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\\r\\n|\\n)((?:[^:]+:\\s*[\\S].*(?:\\r\\n|\\n))*)([\\s\\S]+)(?:\\r\\n|\\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/;\n OpenSSH_Old_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n let privBlob = Buffer.from(m[3], 'base64');\n let headers = m[2];\n let decrypted = false;\n if (headers !== undefined) {\n // encrypted key\n headers = headers.split(/\\r\\n|\\n/g);\n for (let i = 0; i < headers.length; ++i) {\n const header = headers[i];\n let sepIdx = header.indexOf(':');\n if (header.slice(0, sepIdx) === 'DEK-Info') {\n const val = header.slice(sepIdx + 2);\n sepIdx = val.indexOf(',');\n if (sepIdx === -1)\n continue;\n const cipherName = val.slice(0, sepIdx).toLowerCase();\n if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) {\n return new Error(\n `Cipher (${cipherName}) not supported `\n + 'for encrypted OpenSSH private key'\n );\n }\n const encInfo = CIPHER_INFO_OPENSSL[cipherName];\n if (!encInfo) {\n return new Error(\n `Cipher (${cipherName}) not supported `\n + 'for encrypted OpenSSH private key'\n );\n }\n const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex');\n if (cipherIV.length !== encInfo.ivLen)\n return new Error('Malformed encrypted OpenSSH private key');\n if (!passphrase) {\n return new Error(\n 'Encrypted OpenSSH private key detected, but no passphrase given'\n );\n }\n const ivSlice = bufferSlice(cipherIV, 0, 8);\n let cipherKey = createHash('md5')\n .update(passphrase)\n .update(ivSlice)\n .digest();\n while (cipherKey.length < encInfo.keyLen) {\n cipherKey = combineBuffers(\n cipherKey,\n createHash('md5')\n .update(cipherKey)\n .update(passphrase)\n .update(ivSlice)\n .digest()\n );\n }\n if (cipherKey.length > encInfo.keyLen)\n cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen);\n try {\n const decipher = createDecipheriv(cipherName, cipherKey, cipherIV);\n decipher.setAutoPadding(false);\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n decrypted = true;\n } catch (ex) {\n return ex;\n }\n }\n }\n }\n\n let type;\n let privPEM;\n let pubPEM;\n let pubSSH;\n let algo;\n let reader;\n let errMsg = 'Malformed OpenSSH private key';\n if (decrypted)\n errMsg += '. Bad passphrase?';\n switch (m[1]) {\n case 'RSA':\n type = 'ssh-rsa';\n privPEM = makePEM('RSA PRIVATE', privBlob);\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n const n = reader.readString(Ber.Integer, true);\n if (n === null)\n return new Error(errMsg);\n const e = reader.readString(Ber.Integer, true);\n if (e === null)\n return new Error(errMsg);\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n } catch {\n return new Error(errMsg);\n }\n algo = 'sha1';\n break;\n case 'DSA':\n type = 'ssh-dss';\n privPEM = makePEM('DSA PRIVATE', privBlob);\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n const p = reader.readString(Ber.Integer, true);\n if (p === null)\n return new Error(errMsg);\n const q = reader.readString(Ber.Integer, true);\n if (q === null)\n return new Error(errMsg);\n const g = reader.readString(Ber.Integer, true);\n if (g === null)\n return new Error(errMsg);\n const y = reader.readString(Ber.Integer, true);\n if (y === null)\n return new Error(errMsg);\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n } catch {\n return new Error(errMsg);\n }\n algo = 'sha1';\n break;\n case 'EC':\n let ecSSLName;\n let ecPriv;\n let ecOID;\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n ecPriv = reader.readString(Ber.OctetString, true);\n reader.readByte(); // Skip \"complex\" context type byte\n const offset = reader.readLength(); // Skip context length\n if (offset !== null) {\n reader._offset = offset;\n ecOID = reader.readOID();\n if (ecOID === null)\n return new Error(errMsg);\n switch (ecOID) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n ecSSLName = 'prime256v1';\n type = 'ecdsa-sha2-nistp256';\n algo = 'sha256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n ecSSLName = 'secp384r1';\n type = 'ecdsa-sha2-nistp384';\n algo = 'sha384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n ecSSLName = 'secp521r1';\n type = 'ecdsa-sha2-nistp521';\n algo = 'sha512';\n break;\n default:\n return new Error(`Unsupported private key EC OID: ${ecOID}`);\n }\n } else {\n return new Error(errMsg);\n }\n } catch {\n return new Error(errMsg);\n }\n privPEM = makePEM('EC PRIVATE', privBlob);\n const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv);\n pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob);\n pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob);\n break;\n }\n\n return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo,\n decrypted);\n };\n}\n\n\nfunction PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nPPK_Private.prototype = BaseKey;\n{\n const EMPTY_PASSPHRASE = Buffer.alloc(0);\n const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n const PPK_PP1 = Buffer.from([0, 0, 0, 0]);\n const PPK_PP2 = Buffer.from([0, 0, 0, 1]);\n const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\\r?\\nEncryption: (aes256-cbc|none)\\r?\\nComment: ([^\\r\\n]*)\\r?\\nPublic-Lines: \\d+\\r?\\n([\\s\\S]+?)\\r?\\nPrivate-Lines: \\d+\\r?\\n([\\s\\S]+?)\\r?\\nPrivate-MAC: ([^\\r\\n]+)/;\n PPK_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n // m[1] = key type\n // m[2] = encryption type\n // m[3] = comment\n // m[4] = base64-encoded public key data:\n // for \"ssh-rsa\":\n // string \"ssh-rsa\"\n // mpint e (public exponent)\n // mpint n (modulus)\n // for \"ssh-dss\":\n // string \"ssh-dss\"\n // mpint p (modulus)\n // mpint q (prime)\n // mpint g (base number)\n // mpint y (public key parameter: g^x mod p)\n // m[5] = base64-encoded private key data:\n // for \"ssh-rsa\":\n // mpint d (private exponent)\n // mpint p (prime 1)\n // mpint q (prime 2)\n // mpint iqmp ([inverse of q] mod p)\n // for \"ssh-dss\":\n // mpint x (private key parameter)\n // m[6] = SHA1 HMAC over:\n // string name of algorithm (\"ssh-dss\", \"ssh-rsa\")\n // string encryption type\n // string comment\n // string public key data\n // string private-plaintext (including the final padding)\n const cipherName = m[2];\n const encrypted = (cipherName !== 'none');\n if (encrypted && !passphrase) {\n return new Error(\n 'Encrypted PPK private key detected, but no passphrase given'\n );\n }\n\n let privBlob = Buffer.from(m[5], 'base64');\n\n if (encrypted) {\n const encInfo = CIPHER_INFO[cipherName];\n let cipherKey = combineBuffers(\n createHash('sha1').update(PPK_PP1).update(passphrase).digest(),\n createHash('sha1').update(PPK_PP2).update(passphrase).digest()\n );\n if (cipherKey.length > encInfo.keyLen)\n cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen);\n try {\n const decipher = createDecipheriv(encInfo.sslName,\n cipherKey,\n PPK_IV);\n decipher.setAutoPadding(false);\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n } catch (ex) {\n return ex;\n }\n }\n\n const type = m[1];\n const comment = m[3];\n const pubBlob = Buffer.from(m[4], 'base64');\n\n const mac = m[6];\n const typeLen = type.length;\n const cipherNameLen = cipherName.length;\n const commentLen = Buffer.byteLength(comment);\n const pubLen = pubBlob.length;\n const privLen = privBlob.length;\n const macData = Buffer.allocUnsafe(4 + typeLen\n + 4 + cipherNameLen\n + 4 + commentLen\n + 4 + pubLen\n + 4 + privLen);\n let p = 0;\n\n writeUInt32BE(macData, typeLen, p);\n macData.utf8Write(type, p += 4, typeLen);\n writeUInt32BE(macData, cipherNameLen, p += typeLen);\n macData.utf8Write(cipherName, p += 4, cipherNameLen);\n writeUInt32BE(macData, commentLen, p += cipherNameLen);\n macData.utf8Write(comment, p += 4, commentLen);\n writeUInt32BE(macData, pubLen, p += commentLen);\n macData.set(pubBlob, p += 4);\n writeUInt32BE(macData, privLen, p += pubLen);\n macData.set(privBlob, p + 4);\n\n if (!passphrase)\n passphrase = EMPTY_PASSPHRASE;\n\n const calcMAC = createHmac(\n 'sha1',\n createHash('sha1')\n .update('putty-private-key-file-mac-key')\n .update(passphrase)\n .digest()\n ).update(macData).digest('hex');\n\n if (calcMAC !== mac) {\n if (encrypted) {\n return new Error(\n 'PPK private key integrity check failed -- bad passphrase?'\n );\n }\n return new Error('PPK private key integrity check failed');\n }\n\n let pubPEM;\n let pubSSH;\n let privPEM;\n pubBlob._pos = 0;\n skipFields(pubBlob, 1); // skip (duplicate) key type\n switch (type) {\n case 'ssh-rsa': {\n const e = readString(pubBlob, pubBlob._pos);\n if (e === undefined)\n return new Error('Malformed PPK public key');\n const n = readString(pubBlob, pubBlob._pos);\n if (n === undefined)\n return new Error('Malformed PPK public key');\n const d = readString(privBlob, 0);\n if (d === undefined)\n return new Error('Malformed PPK private key');\n const p = readString(privBlob, privBlob._pos);\n if (p === undefined)\n return new Error('Malformed PPK private key');\n const q = readString(privBlob, privBlob._pos);\n if (q === undefined)\n return new Error('Malformed PPK private key');\n const iqmp = readString(privBlob, privBlob._pos);\n if (iqmp === undefined)\n return new Error('Malformed PPK private key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q);\n break;\n }\n case 'ssh-dss': {\n const p = readString(pubBlob, pubBlob._pos);\n if (p === undefined)\n return new Error('Malformed PPK public key');\n const q = readString(pubBlob, pubBlob._pos);\n if (q === undefined)\n return new Error('Malformed PPK public key');\n const g = readString(pubBlob, pubBlob._pos);\n if (g === undefined)\n return new Error('Malformed PPK public key');\n const y = readString(pubBlob, pubBlob._pos);\n if (y === undefined)\n return new Error('Malformed PPK public key');\n const x = readString(privBlob, 0);\n if (x === undefined)\n return new Error('Malformed PPK private key');\n\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n privPEM = genOpenSSLDSAPriv(p, q, g, y, x);\n break;\n }\n }\n\n return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1',\n encrypted);\n };\n}\n\n\nfunction OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = null;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = false;\n}\nOpenSSH_Public.prototype = BaseKey;\n{\n let regexp;\n if (eddsaSupported)\n regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\\s+([\\S].*)?)$/;\n else\n regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\\s+([\\S].*)?)$/;\n OpenSSH_Public.parse = (str) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n // m[1] = full type\n // m[2] = base type\n // m[3] = base64-encoded public key\n // m[4] = comment\n\n const fullType = m[1];\n const baseType = m[2];\n const data = Buffer.from(m[3], 'base64');\n const comment = (m[4] || '');\n\n const type = readString(data, data._pos, true);\n if (type === undefined || type.indexOf(baseType) !== 0)\n return new Error('Malformed OpenSSH public key');\n\n return parseDER(data, baseType, comment, fullType);\n };\n}\n\n\nfunction RFC4716_Public(type, comment, pubPEM, pubSSH, algo) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = null;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = false;\n}\nRFC4716_Public.prototype = BaseKey;\n{\n const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\\r?\\n)((?:.{0,72}\\r?\\n)+)---- END SSH2 PUBLIC KEY ----$/;\n const RE_DATA = /^[A-Z0-9a-z/+=\\r\\n]+$/;\n const RE_HEADER = /^([\\x21-\\x39\\x3B-\\x7E]{1,64}): ((?:[^\\\\]*\\\\\\r?\\n)*[^\\r\\n]+)\\r?\\n/gm;\n const RE_HEADER_ENDS = /\\\\\\r?\\n/g;\n RFC4716_Public.parse = (str) => {\n let m = regexp.exec(str);\n if (m === null)\n return null;\n\n const body = m[1];\n let dataStart = 0;\n let comment = '';\n\n while (m = RE_HEADER.exec(body)) {\n const headerName = m[1];\n const headerValue = m[2].replace(RE_HEADER_ENDS, '');\n if (headerValue.length > 1024) {\n RE_HEADER.lastIndex = 0;\n return new Error('Malformed RFC4716 public key');\n }\n\n dataStart = RE_HEADER.lastIndex;\n\n if (headerName.toLowerCase() === 'comment') {\n comment = headerValue;\n if (comment.length > 1\n && comment.charCodeAt(0) === 34/* '\"' */\n && comment.charCodeAt(comment.length - 1) === 34/* '\"' */) {\n comment = comment.slice(1, -1);\n }\n }\n }\n\n let data = body.slice(dataStart);\n if (!RE_DATA.test(data))\n return new Error('Malformed RFC4716 public key');\n\n data = Buffer.from(data, 'base64');\n\n const type = readString(data, 0, true);\n if (type === undefined)\n return new Error('Malformed RFC4716 public key');\n\n let pubPEM = null;\n let pubSSH = null;\n switch (type) {\n case 'ssh-rsa': {\n const e = readString(data, data._pos);\n if (e === undefined)\n return new Error('Malformed RFC4716 public key');\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed RFC4716 public key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n break;\n }\n case 'ssh-dss': {\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed RFC4716 public key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed RFC4716 public key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed RFC4716 public key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed RFC4716 public key');\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n break;\n }\n default:\n return new Error('Malformed RFC4716 public key');\n }\n\n return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1');\n };\n}\n\n\nfunction parseDER(data, baseType, comment, fullType) {\n if (!isSupportedKeyType(baseType))\n return new Error(`Unsupported OpenSSH public key type: ${baseType}`);\n\n let algo;\n let oid;\n let pubPEM = null;\n let pubSSH = null;\n\n switch (baseType) {\n case 'ssh-rsa': {\n const e = readString(data, data._pos || 0);\n if (e === undefined)\n return new Error('Malformed OpenSSH public key');\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n algo = 'sha1';\n break;\n }\n case 'ssh-dss': {\n const p = readString(data, data._pos || 0);\n if (p === undefined)\n return new Error('Malformed OpenSSH public key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH public key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed OpenSSH public key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n algo = 'sha1';\n break;\n }\n case 'ssh-ed25519': {\n const edpub = readString(data, data._pos || 0);\n if (edpub === undefined || edpub.length !== 32)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLEdPub(edpub);\n pubSSH = genOpenSSHEdPub(edpub);\n algo = null;\n break;\n }\n case 'ecdsa-sha2-nistp256':\n algo = 'sha256';\n oid = '1.2.840.10045.3.1.7';\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp384':\n if (algo === undefined) {\n algo = 'sha384';\n oid = '1.3.132.0.34';\n }\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp521': {\n if (algo === undefined) {\n algo = 'sha512';\n oid = '1.3.132.0.35';\n }\n // TODO: validate curve name against type\n if (!skipFields(data, 1)) // Skip curve name\n return new Error('Malformed OpenSSH public key');\n const ecpub = readString(data, data._pos || 0);\n if (ecpub === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLECDSAPub(oid, ecpub);\n pubSSH = genOpenSSHECDSAPub(oid, ecpub);\n break;\n }\n default:\n return new Error(`Unsupported OpenSSH public key type: ${baseType}`);\n }\n\n return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo);\n}\n\nfunction isSupportedKeyType(type) {\n switch (type) {\n case 'ssh-rsa':\n case 'ssh-dss':\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521':\n return true;\n case 'ssh-ed25519':\n if (eddsaSupported)\n return true;\n // FALLTHROUGH\n default:\n return false;\n }\n}\n\nfunction isParsedKey(val) {\n if (!val)\n return false;\n return (typeof val[SYM_DECRYPTED] === 'boolean');\n}\n\nfunction parseKey(data, passphrase) {\n if (isParsedKey(data))\n return data;\n\n let origBuffer;\n if (Buffer.isBuffer(data)) {\n origBuffer = data;\n data = data.utf8Slice(0, data.length).trim();\n } else if (typeof data === 'string') {\n data = data.trim();\n } else {\n return new Error('Key data must be a Buffer or string');\n }\n\n // eslint-disable-next-line eqeqeq\n if (passphrase != undefined) {\n if (typeof passphrase === 'string')\n passphrase = Buffer.from(passphrase);\n else if (!Buffer.isBuffer(passphrase))\n return new Error('Passphrase must be a string or Buffer when supplied');\n }\n\n let ret;\n\n // First try as printable string format (e.g. PEM)\n\n // Private keys\n if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null)\n return ret;\n if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null)\n return ret;\n if ((ret = PPK_Private.parse(data, passphrase)) !== null)\n return ret;\n\n // Public keys\n if ((ret = OpenSSH_Public.parse(data)) !== null)\n return ret;\n if ((ret = RFC4716_Public.parse(data)) !== null)\n return ret;\n\n // Finally try as a binary format if we were originally passed binary data\n if (origBuffer) {\n binaryKeyParser.init(origBuffer, 0);\n const type = binaryKeyParser.readString(true);\n if (type !== undefined) {\n data = binaryKeyParser.readRaw();\n if (data !== undefined) {\n ret = parseDER(data, type, '', type);\n // Ignore potentially useless errors in case the data was not actually\n // in the binary format\n if (ret instanceof Error)\n ret = null;\n }\n }\n binaryKeyParser.clear();\n }\n\n if (ret)\n return ret;\n\n return new Error('Unsupported key format');\n}\n\nmodule.exports = {\n isParsedKey,\n isSupportedKeyType,\n parseDERKey: (data, type) => parseDER(data, type, '', type),\n parseKey,\n};\n","'use strict';\n\nconst assert = require('assert');\nconst { inspect } = require('util');\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n let res = '';\n let i = val.length;\n const start = val[0] === '-' ? 1 : 0;\n for (; i >= start + 4; i -= 3)\n res = `_${val.slice(i - 3, i)}${res}`;\n return `${val.slice(0, i)}${res}`;\n}\n\nfunction oneOf(expected, thing) {\n assert(typeof thing === 'string', '`thing` has to be of type string');\n if (Array.isArray(expected)) {\n const len = expected.length;\n assert(len > 0, 'At least one expected value needs to be specified');\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or `\n + expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n }\n return `of ${thing} ${expected[0]}`;\n }\n return `of ${thing} ${String(expected)}`;\n}\n\n\nexports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error {\n constructor(message) {\n super();\n Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION);\n\n const suffix = 'This is caused by either a bug in ssh2 '\n + 'or incorrect usage of ssh2 internals.\\n'\n + 'Please open an issue with this stack trace at '\n + 'https://github.com/mscdex/ssh2/issues\\n';\n\n this.message = (message === undefined ? suffix : `${message}\\n${suffix}`);\n }\n};\n\nconst MAX_32BIT_INT = 2 ** 32;\nconst MAX_32BIT_BIGINT = (() => {\n try {\n return new Function('return 2n ** 32n')();\n } catch {}\n})();\nexports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError {\n constructor(str, range, input, replaceDefaultBoolean) {\n super();\n Error.captureStackTrace(this, ERR_OUT_OF_RANGE);\n\n assert(range, 'Missing \"range\" argument');\n let msg = (replaceDefaultBoolean\n ? str\n : `The value of \"${str}\" is out of range.`);\n let received;\n if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) {\n received = addNumericalSeparator(String(input));\n } else if (typeof input === 'bigint') {\n received = String(input);\n if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT)\n received = addNumericalSeparator(received);\n received += 'n';\n } else {\n received = inspect(input);\n }\n msg += ` It must be ${range}. Received ${received}`;\n\n this.message = msg;\n }\n};\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super();\n Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE);\n\n assert(typeof name === 'string', `'name' must be a string`);\n\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && expected.startsWith('not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (name.endsWith(' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = (name.includes('.') ? 'property' : 'argument');\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n\n this.message = msg;\n }\n}\nexports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE;\n\nexports.validateNumber = function validateNumber(value, name) {\n if (typeof value !== 'number')\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value);\n};\n","'use strict';\n\nconst Ber = require('asn1').Ber;\n\nlet DISCONNECT_REASON;\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill;\n\nfunction readUInt32BE(buf, offset) {\n return (buf[offset++] * 16777216)\n + (buf[offset++] * 65536)\n + (buf[offset++] * 256)\n + buf[offset];\n}\n\nfunction bufferCopy(src, dest, srcStart, srcEnd, destStart) {\n if (!destStart)\n destStart = 0;\n if (srcEnd > src.length)\n srcEnd = src.length;\n let nb = srcEnd - srcStart;\n const destLeft = (dest.length - destStart);\n if (nb > destLeft)\n nb = destLeft;\n dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb),\n destStart);\n return nb;\n}\n\nfunction bufferSlice(buf, start, end) {\n if (end === undefined)\n end = buf.length;\n return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start);\n}\n\nfunction makeBufferParser() {\n let pos = 0;\n let buffer;\n\n const self = {\n init: (buf, start) => {\n buffer = buf;\n pos = (typeof start === 'number' ? start : 0);\n },\n pos: () => pos,\n length: () => (buffer ? buffer.length : 0),\n avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0),\n clear: () => {\n buffer = undefined;\n },\n readUInt32BE: () => {\n if (!buffer || pos + 3 >= buffer.length)\n return;\n return (buffer[pos++] * 16777216)\n + (buffer[pos++] * 65536)\n + (buffer[pos++] * 256)\n + buffer[pos++];\n },\n readUInt64BE: (behavior) => {\n if (!buffer || pos + 7 >= buffer.length)\n return;\n switch (behavior) {\n case 'always':\n return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`);\n case 'maybe':\n if (buffer[pos] > 0x1F)\n return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`);\n // FALLTHROUGH\n default:\n return (buffer[pos++] * 72057594037927940)\n + (buffer[pos++] * 281474976710656)\n + (buffer[pos++] * 1099511627776)\n + (buffer[pos++] * 4294967296)\n + (buffer[pos++] * 16777216)\n + (buffer[pos++] * 65536)\n + (buffer[pos++] * 256)\n + buffer[pos++];\n }\n },\n skip: (n) => {\n if (buffer && n > 0)\n pos += n;\n },\n skipString: () => {\n const len = self.readUInt32BE();\n if (len === undefined)\n return;\n pos += len;\n return (pos <= buffer.length ? len : undefined);\n },\n readByte: () => {\n if (buffer && pos < buffer.length)\n return buffer[pos++];\n },\n readBool: () => {\n if (buffer && pos < buffer.length)\n return !!buffer[pos++];\n },\n readList: () => {\n const list = self.readString(true);\n if (list === undefined)\n return;\n return (list ? list.split(',') : []);\n },\n readString: (dest, maxLen) => {\n if (typeof dest === 'number') {\n maxLen = dest;\n dest = undefined;\n }\n\n const len = self.readUInt32BE();\n if (len === undefined)\n return;\n\n if ((buffer.length - pos) < len\n || (typeof maxLen === 'number' && len > maxLen)) {\n return;\n }\n\n if (dest) {\n if (Buffer.isBuffer(dest))\n return bufferCopy(buffer, dest, pos, pos += len);\n return buffer.utf8Slice(pos, pos += len);\n }\n return bufferSlice(buffer, pos, pos += len);\n },\n readRaw: (len) => {\n if (!buffer)\n return;\n if (typeof len !== 'number')\n return bufferSlice(buffer, pos, pos += (buffer.length - pos));\n if ((buffer.length - pos) >= len)\n return bufferSlice(buffer, pos, pos += len);\n },\n };\n\n return self;\n}\n\nfunction makeError(msg, level, fatal) {\n const err = new Error(msg);\n if (typeof level === 'boolean') {\n fatal = level;\n err.level = 'protocol';\n } else {\n err.level = level || 'protocol';\n }\n err.fatal = !!fatal;\n return err;\n}\n\nfunction writeUInt32BE(buf, value, offset) {\n buf[offset++] = (value >>> 24);\n buf[offset++] = (value >>> 16);\n buf[offset++] = (value >>> 8);\n buf[offset++] = value;\n return offset;\n}\n\nconst utilBufferParser = makeBufferParser();\n\nmodule.exports = {\n bufferCopy,\n bufferSlice,\n FastBuffer,\n bufferFill: (buf, value, start, end) => {\n return TypedArrayFill.call(buf, value, start, end);\n },\n makeError,\n doFatalError: (protocol, msg, level, reason) => {\n let err;\n if (DISCONNECT_REASON === undefined)\n ({ DISCONNECT_REASON } = require('./utils.js'));\n if (msg instanceof Error) {\n // doFatalError(protocol, err[, reason])\n err = msg;\n if (typeof level !== 'number')\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n else\n reason = level;\n } else {\n // doFatalError(protocol, msg[, level[, reason]])\n err = makeError(msg, level, true);\n }\n if (typeof reason !== 'number')\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n protocol.disconnect(reason);\n protocol._destruct();\n protocol._onError(err);\n return Infinity;\n },\n readUInt32BE,\n writeUInt32BE,\n writeUInt32LE: (buf, value, offset) => {\n buf[offset++] = value;\n buf[offset++] = (value >>> 8);\n buf[offset++] = (value >>> 16);\n buf[offset++] = (value >>> 24);\n return offset;\n },\n makeBufferParser,\n bufferParser: makeBufferParser(),\n readString: (buffer, start, dest, maxLen) => {\n if (typeof dest === 'number') {\n maxLen = dest;\n dest = undefined;\n }\n\n if (start === undefined)\n start = 0;\n\n const left = (buffer.length - start);\n if (start < 0 || start >= buffer.length || left < 4)\n return;\n\n const len = readUInt32BE(buffer, start);\n if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen))\n return;\n\n start += 4;\n const end = start + len;\n buffer._pos = end;\n\n if (dest) {\n if (Buffer.isBuffer(dest))\n return bufferCopy(buffer, dest, start, end);\n return buffer.utf8Slice(start, end);\n }\n return bufferSlice(buffer, start, end);\n },\n sigSSHToASN1: (sig, type) => {\n switch (type) {\n case 'ssh-dss': {\n if (sig.length > 40)\n return sig;\n // Change bare signature r and s values to ASN.1 BER values for OpenSSL\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n let r = sig.slice(0, 20);\n let s = sig.slice(20);\n if (r[0] & 0x80) {\n const rNew = Buffer.allocUnsafe(21);\n rNew[0] = 0x00;\n r.copy(rNew, 1);\n r = rNew;\n } else if (r[0] === 0x00 && !(r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] & 0x80) {\n const sNew = Buffer.allocUnsafe(21);\n sNew[0] = 0x00;\n s.copy(sNew, 1);\n s = sNew;\n } else if (s[0] === 0x00 && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n asnWriter.writeBuffer(r, Ber.Integer);\n asnWriter.writeBuffer(s, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521': {\n utilBufferParser.init(sig, 0);\n const r = utilBufferParser.readString();\n const s = utilBufferParser.readString();\n utilBufferParser.clear();\n if (r === undefined || s === undefined)\n return;\n\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeBuffer(r, Ber.Integer);\n asnWriter.writeBuffer(s, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n default:\n return sig;\n }\n },\n convertSignature: (signature, keyType) => {\n switch (keyType) {\n case 'ssh-dss': {\n if (signature.length <= 40)\n return signature;\n // This is a quick and dirty way to get from BER encoded r and s that\n // OpenSSL gives us, to just the bare values back to back (40 bytes\n // total) like OpenSSH (and possibly others) are expecting\n const asnReader = new Ber.Reader(signature);\n asnReader.readSequence();\n let r = asnReader.readString(Ber.Integer, true);\n let s = asnReader.readString(Ber.Integer, true);\n let rOffset = 0;\n let sOffset = 0;\n if (r.length < 20) {\n const rNew = Buffer.allocUnsafe(20);\n rNew.set(r, 1);\n r = rNew;\n r[0] = 0;\n }\n if (s.length < 20) {\n const sNew = Buffer.allocUnsafe(20);\n sNew.set(s, 1);\n s = sNew;\n s[0] = 0;\n }\n if (r.length > 20 && r[0] === 0)\n rOffset = 1;\n if (s.length > 20 && s[0] === 0)\n sOffset = 1;\n const newSig =\n Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset));\n bufferCopy(r, newSig, rOffset, r.length, 0);\n bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset);\n return newSig;\n }\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521': {\n if (signature[0] === 0)\n return signature;\n // Convert SSH signature parameters to ASN.1 BER values for OpenSSL\n const asnReader = new Ber.Reader(signature);\n asnReader.readSequence();\n const r = asnReader.readString(Ber.Integer, true);\n const s = asnReader.readString(Ber.Integer, true);\n if (r === null || s === null)\n return;\n const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length);\n writeUInt32BE(newSig, r.length, 0);\n newSig.set(r, 4);\n writeUInt32BE(newSig, s.length, 4 + r.length);\n newSig.set(s, 4 + 4 + r.length);\n return newSig;\n }\n }\n\n return signature;\n },\n sendPacket: (proto, packet, bypass) => {\n if (!bypass && proto._kexinit !== undefined) {\n // We're currently in the middle of a handshake\n\n if (proto._queue === undefined)\n proto._queue = [];\n proto._queue.push(packet);\n proto._debug && proto._debug('Outbound: ... packet queued');\n return false;\n }\n proto._cipher.encrypt(packet);\n return true;\n },\n};\n","'use strict';\n\nconst { kMaxLength } = require('buffer');\nconst {\n createInflate,\n constants: {\n DEFLATE,\n INFLATE,\n Z_DEFAULT_CHUNK,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_MEMLEVEL,\n Z_DEFAULT_STRATEGY,\n Z_DEFAULT_WINDOWBITS,\n Z_PARTIAL_FLUSH,\n }\n} = require('zlib');\nconst ZlibHandle = createInflate()._handle.constructor;\n\nfunction processCallback() {\n throw new Error('Should not get here');\n}\n\nfunction zlibOnError(message, errno, code) {\n const self = this._owner;\n // There is no way to cleanly recover.\n // Continuing only obscures problems.\n\n const error = new Error(message);\n error.errno = errno;\n error.code = code;\n self._err = error;\n}\n\nfunction _close(engine) {\n // Caller may invoke .close after a zlib error (which will null _handle).\n if (!engine._handle)\n return;\n\n engine._handle.close();\n engine._handle = null;\n}\n\nclass Zlib {\n constructor(mode) {\n const windowBits = Z_DEFAULT_WINDOWBITS;\n const level = Z_DEFAULT_COMPRESSION;\n const memLevel = Z_DEFAULT_MEMLEVEL;\n const strategy = Z_DEFAULT_STRATEGY;\n const dictionary = undefined;\n\n this._err = undefined;\n this._writeState = new Uint32Array(2);\n this._chunkSize = Z_DEFAULT_CHUNK;\n this._maxOutputLength = kMaxLength;\n this._outBuffer = Buffer.allocUnsafe(this._chunkSize);\n this._outOffset = 0;\n\n this._handle = new ZlibHandle(mode);\n this._handle._owner = this;\n this._handle.onerror = zlibOnError;\n this._handle.init(windowBits,\n level,\n memLevel,\n strategy,\n this._writeState,\n processCallback,\n dictionary);\n }\n\n writeSync(chunk, retChunks) {\n const handle = this._handle;\n if (!handle)\n throw new Error('Invalid Zlib instance');\n\n let availInBefore = chunk.length;\n let availOutBefore = this._chunkSize - this._outOffset;\n let inOff = 0;\n let availOutAfter;\n let availInAfter;\n\n let buffers;\n let nread = 0;\n const state = this._writeState;\n let buffer = this._outBuffer;\n let offset = this._outOffset;\n const chunkSize = this._chunkSize;\n\n while (true) {\n handle.writeSync(Z_PARTIAL_FLUSH,\n chunk, // in\n inOff, // in_off\n availInBefore, // in_len\n buffer, // out\n offset, // out_off\n availOutBefore); // out_len\n if (this._err)\n throw this._err;\n\n availOutAfter = state[0];\n availInAfter = state[1];\n\n const inDelta = availInBefore - availInAfter;\n const have = availOutBefore - availOutAfter;\n\n if (have > 0) {\n const out = (offset === 0 && have === buffer.length\n ? buffer\n : buffer.slice(offset, offset + have));\n offset += have;\n if (!buffers)\n buffers = out;\n else if (buffers.push === undefined)\n buffers = [buffers, out];\n else\n buffers.push(out);\n nread += out.byteLength;\n\n if (nread > this._maxOutputLength) {\n _close(this);\n throw new Error(\n `Output length exceeded maximum of ${this._maxOutputLength}`\n );\n }\n } else if (have !== 0) {\n throw new Error('have should not go down');\n }\n\n // Exhausted the output buffer, or used all the input create a new one.\n if (availOutAfter === 0 || offset >= chunkSize) {\n availOutBefore = chunkSize;\n offset = 0;\n buffer = Buffer.allocUnsafe(chunkSize);\n }\n\n if (availOutAfter === 0) {\n // Not actually done. Need to reprocess.\n // Also, update the availInBefore to the availInAfter value,\n // so that if we have to hit it a third (fourth, etc.) time,\n // it'll have the correct byte counts.\n inOff += inDelta;\n availInBefore = availInAfter;\n } else {\n break;\n }\n }\n\n this._outBuffer = buffer;\n this._outOffset = offset;\n\n if (nread === 0)\n buffers = Buffer.alloc(0);\n\n if (retChunks) {\n buffers.totalLen = nread;\n return buffers;\n }\n\n if (buffers.push === undefined)\n return buffers;\n\n const output = Buffer.allocUnsafe(nread);\n for (let i = 0, p = 0; i < buffers.length; ++i) {\n const buf = buffers[i];\n output.set(buf, p);\n p += buf.length;\n }\n return output;\n }\n}\n\nclass ZlibPacketWriter {\n constructor(protocol) {\n this.allocStart = 0;\n this.allocStartKEX = 0;\n this._protocol = protocol;\n this._zlib = new Zlib(DEFLATE);\n }\n\n cleanup() {\n if (this._zlib)\n _close(this._zlib);\n }\n\n alloc(payloadSize, force) {\n return Buffer.allocUnsafe(payloadSize);\n }\n\n finalize(payload, force) {\n if (this._protocol._kexinit === undefined || force) {\n const output = this._zlib.writeSync(payload, true);\n const packet = this._protocol._cipher.allocPacket(output.totalLen);\n if (output.push === undefined) {\n packet.set(output, 5);\n } else {\n for (let i = 0, p = 5; i < output.length; ++i) {\n const chunk = output[i];\n packet.set(chunk, p);\n p += chunk.length;\n }\n }\n return packet;\n }\n return payload;\n }\n}\n\nclass PacketWriter {\n constructor(protocol) {\n this.allocStart = 5;\n this.allocStartKEX = 5;\n this._protocol = protocol;\n }\n\n cleanup() {}\n\n alloc(payloadSize, force) {\n if (this._protocol._kexinit === undefined || force)\n return this._protocol._cipher.allocPacket(payloadSize);\n return Buffer.allocUnsafe(payloadSize);\n }\n\n finalize(packet, force) {\n return packet;\n }\n}\n\nclass ZlibPacketReader {\n constructor() {\n this._zlib = new Zlib(INFLATE);\n }\n\n cleanup() {\n if (this._zlib)\n _close(this._zlib);\n }\n\n read(data) {\n return this._zlib.writeSync(data, false);\n }\n}\n\nclass PacketReader {\n cleanup() {}\n\n read(data) {\n return data;\n }\n}\n\nmodule.exports = {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n};\n","// TODO:\n// * convert listenerCount() usage to emit() return value checking?\n// * emit error when connection severed early (e.g. before handshake)\n// * add '.connected' or similar property to connection objects to allow\n// immediate connection status checking\n'use strict';\n\nconst { Server: netServer } = require('net');\nconst EventEmitter = require('events');\nconst { listenerCount } = EventEmitter;\n\nconst {\n CHANNEL_OPEN_FAILURE,\n DEFAULT_CIPHER,\n DEFAULT_COMPRESSION,\n DEFAULT_KEX,\n DEFAULT_MAC,\n DEFAULT_SERVER_HOST_KEY,\n DISCONNECT_REASON,\n DISCONNECT_REASON_BY_VALUE,\n SUPPORTED_CIPHER,\n SUPPORTED_COMPRESSION,\n SUPPORTED_KEX,\n SUPPORTED_MAC,\n SUPPORTED_SERVER_HOST_KEY,\n} = require('./protocol/constants.js');\nconst { init: cryptoInit } = require('./protocol/crypto.js');\nconst { KexInit } = require('./protocol/kex.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst Protocol = require('./protocol/Protocol.js');\nconst { SFTP } = require('./protocol/SFTP.js');\nconst { writeUInt32BE } = require('./protocol/utils.js');\n\nconst {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n} = require('./Channel.js');\n\nconst {\n ChannelManager,\n generateAlgorithmList,\n isWritable,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n} = require('./utils.js');\n\nconst MAX_PENDING_AUTHS = 10;\n\nclass AuthContext extends EventEmitter {\n constructor(protocol, username, service, method, cb) {\n super();\n\n this.username = this.user = username;\n this.service = service;\n this.method = method;\n this._initialResponse = false;\n this._finalResponse = false;\n this._multistep = false;\n this._cbfinal = (allowed, methodsLeft, isPartial) => {\n if (!this._finalResponse) {\n this._finalResponse = true;\n cb(this, allowed, methodsLeft, isPartial);\n }\n };\n this._protocol = protocol;\n }\n\n accept() {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(true);\n }\n reject(methodsLeft, isPartial) {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(false, methodsLeft, isPartial);\n }\n}\n\n\nclass KeyboardAuthContext extends AuthContext {\n constructor(protocol, username, service, method, submethods, cb) {\n super(protocol, username, service, method, cb);\n\n this._multistep = true;\n\n this._cb = undefined;\n this._onInfoResponse = (responses) => {\n const callback = this._cb;\n if (callback) {\n this._cb = undefined;\n callback(responses);\n }\n };\n this.submethods = submethods;\n this.on('abort', () => {\n this._cb && this._cb(new Error('Authentication request aborted'));\n });\n }\n\n prompt(prompts, title, instructions, cb) {\n if (!Array.isArray(prompts))\n prompts = [ prompts ];\n\n if (typeof title === 'function') {\n cb = title;\n title = instructions = undefined;\n } else if (typeof instructions === 'function') {\n cb = instructions;\n instructions = undefined;\n } else if (typeof cb !== 'function') {\n cb = undefined;\n }\n\n for (let i = 0; i < prompts.length; ++i) {\n if (typeof prompts[i] === 'string') {\n prompts[i] = {\n prompt: prompts[i],\n echo: true\n };\n }\n }\n\n this._cb = cb;\n this._initialResponse = true;\n\n this._protocol.authInfoReq(title, instructions, prompts);\n }\n}\n\nclass PKAuthContext extends AuthContext {\n constructor(protocol, username, service, method, pkInfo, cb) {\n super(protocol, username, service, method, cb);\n\n this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };\n this.signature = pkInfo.signature;\n this.blob = pkInfo.blob;\n }\n\n accept() {\n if (!this.signature) {\n this._initialResponse = true;\n this._protocol.authPKOK(this.key.algo, this.key.data);\n } else {\n AuthContext.prototype.accept.call(this);\n }\n }\n}\n\nclass HostbasedAuthContext extends AuthContext {\n constructor(protocol, username, service, method, pkInfo, cb) {\n super(protocol, username, service, method, cb);\n\n this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };\n this.signature = pkInfo.signature;\n this.blob = pkInfo.blob;\n this.localHostname = pkInfo.localHostname;\n this.localUsername = pkInfo.localUsername;\n }\n}\n\nclass PwdAuthContext extends AuthContext {\n constructor(protocol, username, service, method, password, cb) {\n super(protocol, username, service, method, cb);\n\n this.password = password;\n this._changeCb = undefined;\n }\n\n requestChange(prompt, cb) {\n if (this._changeCb)\n throw new Error('Change request already in progress');\n if (typeof prompt !== 'string')\n throw new Error('prompt argument must be a string');\n if (typeof cb !== 'function')\n throw new Error('Callback argument must be a function');\n this._changeCb = cb;\n this._protocol.authPasswdChg(prompt);\n }\n}\n\n\nclass Session extends EventEmitter {\n constructor(client, info, localChan) {\n super();\n\n this.type = 'session';\n this.subtype = undefined;\n this.server = true;\n this._ending = false;\n this._channel = undefined;\n this._chanInfo = {\n type: 'session',\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n }\n}\n\n\nclass Server extends EventEmitter {\n constructor(cfg, listener) {\n super();\n\n if (typeof cfg !== 'object' || cfg === null)\n throw new Error('Missing configuration object');\n\n const hostKeys = Object.create(null);\n const hostKeyAlgoOrder = [];\n\n const hostKeys_ = cfg.hostKeys;\n if (!Array.isArray(hostKeys_))\n throw new Error('hostKeys must be an array');\n\n const cfgAlgos = (\n typeof cfg.algorithms === 'object' && cfg.algorithms !== null\n ? cfg.algorithms\n : {}\n );\n\n const hostKeyAlgos = generateAlgorithmList(\n cfgAlgos.serverHostKey,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY\n );\n for (let i = 0; i < hostKeys_.length; ++i) {\n let privateKey;\n if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string')\n privateKey = parseKey(hostKeys_[i]);\n else\n privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase);\n\n if (privateKey instanceof Error)\n throw new Error(`Cannot parse privateKey: ${privateKey.message}`);\n\n if (Array.isArray(privateKey)) {\n // OpenSSH's newer format only stores 1 key for now\n privateKey = privateKey[0];\n }\n\n if (privateKey.getPrivatePEM() === null)\n throw new Error('privateKey value contains an invalid private key');\n\n // Discard key if we already found a key of the same type\n if (hostKeyAlgoOrder.includes(privateKey.type))\n continue;\n\n if (privateKey.type === 'ssh-rsa') {\n // SSH supports multiple signature hashing algorithms for RSA, so we add\n // the algorithms in the desired order\n let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa');\n const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256');\n const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512');\n if (sha1Pos === -1) {\n // Fall back to giving SHA1 the lowest priority\n sha1Pos = Infinity;\n }\n [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => {\n if (pos === -1)\n return;\n\n let type;\n switch (pos) {\n case sha1Pos: type = 'ssh-rsa'; break;\n case sha256Pos: type = 'rsa-sha2-256'; break;\n case sha512Pos: type = 'rsa-sha2-512'; break;\n default: return;\n }\n\n // Store same RSA key under each hash algorithm name for convenience\n hostKeys[type] = privateKey;\n\n hostKeyAlgoOrder.push(type);\n });\n } else {\n hostKeys[privateKey.type] = privateKey;\n hostKeyAlgoOrder.push(privateKey.type);\n }\n }\n\n const algorithms = {\n kex: generateAlgorithmList(cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX),\n serverHostKey: hostKeyAlgoOrder,\n cs: {\n cipher: generateAlgorithmList(\n cfgAlgos.cipher,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER\n ),\n mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC),\n compress: generateAlgorithmList(\n cfgAlgos.compress,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION\n ),\n lang: [],\n },\n sc: undefined,\n };\n algorithms.sc = algorithms.cs;\n\n if (typeof listener === 'function')\n this.on('connection', listener);\n\n const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);\n const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined);\n const offer = new KexInit(algorithms);\n\n this._srv = new netServer((socket) => {\n if (this._connections >= this.maxConnections) {\n socket.destroy();\n return;\n }\n ++this._connections;\n socket.once('close', () => {\n --this._connections;\n });\n\n let debug;\n if (origDebug) {\n // Prepend debug output with a unique identifier in case there are\n // multiple clients connected at the same time\n const debugPrefix = `[${process.hrtime().join('.')}] `;\n debug = (msg) => {\n origDebug(`${debugPrefix}${msg}`);\n };\n }\n\n // eslint-disable-next-line no-use-before-define\n new Client(socket, hostKeys, ident, offer, debug, this, cfg);\n }).on('error', (err) => {\n this.emit('error', err);\n }).on('listening', () => {\n this.emit('listening');\n }).on('close', () => {\n this.emit('close');\n });\n this._connections = 0;\n this.maxConnections = Infinity;\n }\n\n injectSocket(socket) {\n this._srv.emit('connection', socket);\n }\n\n listen(...args) {\n this._srv.listen(...args);\n return this;\n }\n\n address() {\n return this._srv.address();\n }\n\n getConnections(cb) {\n this._srv.getConnections(cb);\n return this;\n }\n\n close(cb) {\n this._srv.close(cb);\n return this;\n }\n\n ref() {\n this._srv.ref();\n return this;\n }\n\n unref() {\n this._srv.unref();\n return this;\n }\n}\nServer.KEEPALIVE_CLIENT_INTERVAL = 15000;\nServer.KEEPALIVE_CLIENT_COUNT_MAX = 3;\n\n\nclass Client extends EventEmitter {\n constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) {\n super();\n\n let exchanges = 0;\n let acceptedAuthSvc = false;\n let pendingAuths = [];\n let authCtx;\n let kaTimer;\n let onPacket;\n const unsentGlobalRequestsReplies = [];\n this._sock = socket;\n this._chanMgr = new ChannelManager(this);\n this._debug = debug;\n this.noMoreSessions = false;\n this.authenticated = false;\n\n // Silence pre-header errors\n function onClientPreHeaderError(err) {}\n this.on('error', onClientPreHeaderError);\n\n const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {\n debug(`Debug output from client: ${JSON.stringify(msg)}`);\n });\n\n const kaIntvl = (\n typeof srvCfg.keepaliveInterval === 'number'\n && isFinite(srvCfg.keepaliveInterval)\n && srvCfg.keepaliveInterval > 0\n ? srvCfg.keepaliveInterval\n : (\n typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number'\n && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL)\n && Server.KEEPALIVE_CLIENT_INTERVAL > 0\n ? Server.KEEPALIVE_CLIENT_INTERVAL\n : -1\n )\n );\n const kaCountMax = (\n typeof srvCfg.keepaliveCountMax === 'number'\n && isFinite(srvCfg.keepaliveCountMax)\n && srvCfg.keepaliveCountMax >= 0\n ? srvCfg.keepaliveCountMax\n : (\n typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number'\n && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX)\n && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0\n ? Server.KEEPALIVE_CLIENT_COUNT_MAX\n : -1\n )\n );\n let kaCurCount = 0;\n if (kaIntvl !== -1 && kaCountMax !== -1) {\n this.once('ready', () => {\n const onClose = () => {\n clearInterval(kaTimer);\n };\n this.on('close', onClose).on('end', onClose);\n kaTimer = setInterval(() => {\n if (++kaCurCount > kaCountMax) {\n clearInterval(kaTimer);\n const err = new Error('Keepalive timeout');\n err.level = 'client-timeout';\n this.emit('error', err);\n this.end();\n } else {\n // XXX: if the server ever starts sending real global requests to\n // the client, we will need to add a dummy callback here to\n // keep the correct reply order\n proto.ping();\n }\n }, kaIntvl);\n });\n // TODO: re-verify keepalive behavior with OpenSSH\n onPacket = () => {\n kaTimer && kaTimer.refresh();\n kaCurCount = 0;\n };\n }\n\n const proto = this._protocol = new Protocol({\n server: true,\n hostKeys,\n ident,\n offer,\n onPacket,\n greeting: srvCfg.greeting,\n banner: srvCfg.banner,\n onWrite: (data) => {\n if (isWritable(socket))\n socket.write(data);\n },\n onError: (err) => {\n if (!proto._destruct)\n socket.removeAllListeners('data');\n this.emit('error', err);\n try {\n socket.end();\n } catch {}\n },\n onHeader: (header) => {\n this.removeListener('error', onClientPreHeaderError);\n\n const info = {\n ip: socket.remoteAddress,\n family: socket.remoteFamily,\n port: socket.remotePort,\n header,\n };\n if (!server.emit('connection', this, info)) {\n // auto reject\n proto.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n socket.end();\n return;\n }\n\n if (header.greeting)\n this.emit('greeting', header.greeting);\n },\n onHandshakeComplete: (negotiated) => {\n if (++exchanges > 1)\n this.emit('rekey');\n this.emit('handshake', negotiated);\n },\n debug,\n messageHandlers: {\n DEBUG: DEBUG_HANDLER,\n DISCONNECT: (p, reason, desc) => {\n if (reason !== DISCONNECT_REASON.BY_APPLICATION) {\n if (!desc) {\n desc = DISCONNECT_REASON_BY_VALUE[reason];\n if (desc === undefined)\n desc = `Unexpected disconnection reason: ${reason}`;\n }\n const err = new Error(desc);\n err.code = reason;\n this.emit('error', err);\n }\n socket.end();\n },\n CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from client\n\n // Do early reject in some cases to prevent wasteful channel\n // allocation\n if ((info.type === 'session' && this.noMoreSessions)\n || !this.authenticated) {\n const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n return proto.channelOpenFail(info.sender, reasonCode);\n }\n\n let localChan = -1;\n let reason;\n let replied = false;\n\n let accept;\n const reject = () => {\n if (replied)\n return;\n replied = true;\n\n if (reason === undefined) {\n if (localChan === -1)\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n else\n reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;\n }\n\n if (localChan !== -1)\n this._chanMgr.remove(localChan);\n proto.channelOpenFail(info.sender, reason, '');\n };\n const reserveChannel = () => {\n localChan = this._chanMgr.add();\n\n if (localChan === -1) {\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n if (debug) {\n debug('Automatic rejection of incoming channel open: '\n + 'no channels available');\n }\n }\n\n return (localChan !== -1);\n };\n\n const data = info.data;\n switch (info.type) {\n case 'session':\n if (listenerCount(this, 'session') && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const instance = new Session(this, info, localChan);\n this._chanMgr.update(localChan, instance);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return instance;\n };\n\n this.emit('session', accept, reject);\n return;\n }\n break;\n case 'direct-tcpip':\n if (listenerCount(this, 'tcpip') && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const chanInfo = {\n type: undefined,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const stream = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(localChan, stream);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return stream;\n };\n\n this.emit('tcpip', accept, reject, data);\n return;\n }\n break;\n case 'direct-streamlocal@openssh.com':\n if (listenerCount(this, 'openssh.streamlocal')\n && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const chanInfo = {\n type: undefined,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const stream = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(localChan, stream);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return stream;\n };\n\n this.emit('openssh.streamlocal', accept, reject, data);\n return;\n }\n break;\n default:\n // Automatically reject any unsupported channel open requests\n reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;\n if (debug) {\n debug('Automatic rejection of unsupported incoming channel open'\n + ` type: ${info.type}`);\n }\n }\n\n if (reason === undefined) {\n reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n if (debug) {\n debug('Automatic rejection of unexpected incoming channel open'\n + ` for: ${info.type}`);\n }\n }\n\n reject();\n },\n CHANNEL_OPEN_CONFIRMATION: (p, info) => {\n const channel = this._chanMgr.get(info.recipient);\n if (typeof channel !== 'function')\n return;\n\n const chanInfo = {\n type: channel.type,\n incoming: {\n id: info.recipient,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const instance = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(info.recipient, instance);\n channel(undefined, instance);\n },\n CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },\n CHANNEL_DATA: (p, recipient, data) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n // NOOP -- should not be sent by client\n },\n CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },\n CHANNEL_SUCCESS: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(false);\n },\n CHANNEL_FAILURE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },\n CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {\n const session = this._chanMgr.get(recipient);\n if (typeof session !== 'object' || session === null)\n return;\n\n let replied = false;\n let accept;\n let reject;\n\n if (session.constructor !== Session) {\n // normal Channel instance\n if (wantReply)\n proto.channelFailure(session.outgoing.id);\n return;\n }\n\n if (wantReply) {\n // \"real session\" requests will have custom accept behaviors\n if (type !== 'shell'\n && type !== 'exec'\n && type !== 'subsystem') {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n proto.channelSuccess(session._chanInfo.outgoing.id);\n };\n }\n\n reject = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n proto.channelFailure(session._chanInfo.outgoing.id);\n };\n }\n\n if (session._ending) {\n reject && reject();\n return;\n }\n\n switch (type) {\n // \"pre-real session start\" requests\n case 'env':\n if (listenerCount(session, 'env')) {\n session.emit('env', accept, reject, {\n key: data.name,\n val: data.value\n });\n return;\n }\n break;\n case 'pty-req':\n if (listenerCount(session, 'pty')) {\n session.emit('pty', accept, reject, data);\n return;\n }\n break;\n case 'window-change':\n if (listenerCount(session, 'window-change'))\n session.emit('window-change', accept, reject, data);\n else\n reject && reject();\n break;\n case 'x11-req':\n if (listenerCount(session, 'x11')) {\n session.emit('x11', accept, reject, data);\n return;\n }\n break;\n // \"post-real session start\" requests\n case 'signal':\n if (listenerCount(session, 'signal')) {\n session.emit('signal', accept, reject, {\n name: data\n });\n return;\n }\n break;\n // XXX: is `auth-agent-req@openssh.com` really \"post-real session\n // start\"?\n case 'auth-agent-req@openssh.com':\n if (listenerCount(session, 'auth-agent')) {\n session.emit('auth-agent', accept, reject);\n return;\n }\n break;\n // \"real session start\" requests\n case 'shell':\n if (listenerCount(session, 'shell')) {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n const channel = new Channel(\n this, session._chanInfo, { server: true }\n );\n\n channel.subtype = session.subtype = type;\n session._channel = channel;\n\n return channel;\n };\n\n session.emit('shell', accept, reject);\n return;\n }\n break;\n case 'exec':\n if (listenerCount(session, 'exec')) {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n const channel = new Channel(\n this, session._chanInfo, { server: true }\n );\n\n channel.subtype = session.subtype = type;\n session._channel = channel;\n\n return channel;\n };\n\n session.emit('exec', accept, reject, {\n command: data\n });\n return;\n }\n break;\n case 'subsystem': {\n let useSFTP = (data === 'sftp');\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n let instance;\n if (useSFTP) {\n instance = new SFTP(this, session._chanInfo, {\n server: true,\n debug,\n });\n } else {\n instance = new Channel(\n this, session._chanInfo, { server: true }\n );\n instance.subtype =\n session.subtype = `${type}:${data}`;\n }\n session._channel = instance;\n\n return instance;\n };\n\n if (data === 'sftp') {\n if (listenerCount(session, 'sftp')) {\n session.emit('sftp', accept, reject);\n return;\n }\n useSFTP = false;\n }\n if (listenerCount(session, 'subsystem')) {\n session.emit('subsystem', accept, reject, {\n name: data\n });\n return;\n }\n break;\n }\n }\n debug && debug(\n `Automatic rejection of incoming channel request: ${type}`\n );\n reject && reject();\n },\n CHANNEL_EOF: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n if (!channel._ending) {\n channel._ending = true;\n channel.emit('eof');\n channel.emit('end');\n }\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel.incoming.state !== 'open')\n return;\n channel.incoming.state = 'eof';\n\n if (channel.readable)\n channel.push(null);\n },\n CHANNEL_CLOSE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel._ending = true;\n channel.emit('close');\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n onCHANNEL_CLOSE(this, recipient, channel);\n },\n // Begin service/auth-related ==========================================\n SERVICE_REQUEST: (p, service) => {\n if (exchanges === 0\n || acceptedAuthSvc\n || this.authenticated\n || service !== 'ssh-userauth') {\n proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);\n socket.end();\n return;\n }\n\n acceptedAuthSvc = true;\n proto.serviceAccept(service);\n },\n USERAUTH_REQUEST: (p, username, service, method, methodData) => {\n if (exchanges === 0\n || this.authenticated\n || (authCtx\n && (authCtx.username !== username\n || authCtx.service !== service))\n // TODO: support hostbased auth\n || (method !== 'password'\n && method !== 'publickey'\n && method !== 'hostbased'\n && method !== 'keyboard-interactive'\n && method !== 'none')\n || pendingAuths.length === MAX_PENDING_AUTHS) {\n proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR);\n socket.end();\n return;\n } else if (service !== 'ssh-connection') {\n proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);\n socket.end();\n return;\n }\n\n let ctx;\n switch (method) {\n case 'keyboard-interactive':\n ctx = new KeyboardAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'publickey':\n ctx = new PKAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'hostbased':\n ctx = new HostbasedAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'password':\n if (authCtx\n && authCtx instanceof PwdAuthContext\n && authCtx._changeCb) {\n const cb = authCtx._changeCb;\n authCtx._changeCb = undefined;\n cb(methodData.newPassword);\n return;\n }\n ctx = new PwdAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'none':\n ctx = new AuthContext(proto, username, service, method,\n onAuthDecide);\n break;\n }\n\n if (authCtx) {\n if (!authCtx._initialResponse) {\n return pendingAuths.push(ctx);\n } else if (authCtx._multistep && !authCtx._finalResponse) {\n // RFC 4252 says to silently abort the current auth request if a\n // new auth request comes in before the final response from an\n // auth method that requires additional request/response exchanges\n // -- this means keyboard-interactive for now ...\n authCtx._cleanup && authCtx._cleanup();\n authCtx.emit('abort');\n }\n }\n\n authCtx = ctx;\n\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n },\n USERAUTH_INFO_RESPONSE: (p, responses) => {\n if (authCtx && authCtx instanceof KeyboardAuthContext)\n authCtx._onInfoResponse(responses);\n },\n // End service/auth-related ============================================\n GLOBAL_REQUEST: (p, name, wantReply, data) => {\n const reply = {\n type: null,\n buf: null\n };\n\n function setReply(type, buf) {\n reply.type = type;\n reply.buf = buf;\n sendReplies();\n }\n\n if (wantReply)\n unsentGlobalRequestsReplies.push(reply);\n\n if ((name === 'tcpip-forward'\n || name === 'cancel-tcpip-forward'\n || name === 'no-more-sessions@openssh.com'\n || name === 'streamlocal-forward@openssh.com'\n || name === 'cancel-streamlocal-forward@openssh.com')\n && listenerCount(this, 'request')\n && this.authenticated) {\n let accept;\n let reject;\n\n if (wantReply) {\n let replied = false;\n accept = (chosenPort) => {\n if (replied)\n return;\n replied = true;\n let bufPort;\n if (name === 'tcpip-forward'\n && data.bindPort === 0\n && typeof chosenPort === 'number') {\n bufPort = Buffer.allocUnsafe(4);\n writeUInt32BE(bufPort, chosenPort, 0);\n }\n setReply('SUCCESS', bufPort);\n };\n reject = () => {\n if (replied)\n return;\n replied = true;\n setReply('FAILURE');\n };\n }\n\n if (name === 'no-more-sessions@openssh.com') {\n this.noMoreSessions = true;\n accept && accept();\n return;\n }\n\n this.emit('request', accept, reject, name, data);\n } else if (wantReply) {\n setReply('FAILURE');\n }\n },\n },\n });\n\n socket.pause();\n cryptoInit.then(() => {\n proto.start();\n socket.on('data', (data) => {\n try {\n proto.parse(data, 0, data.length);\n } catch (ex) {\n this.emit('error', ex);\n try {\n if (isWritable(socket))\n socket.end();\n } catch {}\n }\n });\n socket.resume();\n }).catch((err) => {\n this.emit('error', err);\n try {\n if (isWritable(socket))\n socket.end();\n } catch {}\n });\n socket.on('error', (err) => {\n err.level = 'socket';\n this.emit('error', err);\n }).once('end', () => {\n debug && debug('Socket ended');\n proto.cleanup();\n this.emit('end');\n }).once('close', () => {\n debug && debug('Socket closed');\n proto.cleanup();\n this.emit('close');\n\n const err = new Error('No response from server');\n\n // Simulate error for pending channels and close any open channels\n this._chanMgr.cleanup(err);\n });\n\n const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => {\n if (authCtx === ctx && !this.authenticated) {\n if (allowed) {\n authCtx = undefined;\n this.authenticated = true;\n proto.authSuccess();\n pendingAuths = [];\n this.emit('ready');\n } else {\n proto.authFailure(methodsLeft, isPartial);\n if (pendingAuths.length) {\n authCtx = pendingAuths.pop();\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n }\n }\n }\n };\n\n function sendReplies() {\n while (unsentGlobalRequestsReplies.length > 0\n && unsentGlobalRequestsReplies[0].type) {\n const reply = unsentGlobalRequestsReplies.shift();\n if (reply.type === 'SUCCESS')\n proto.requestSuccess(reply.buf);\n if (reply.type === 'FAILURE')\n proto.requestFailure();\n }\n }\n }\n\n end() {\n if (this._sock && isWritable(this._sock)) {\n this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n this._sock.end();\n }\n return this;\n }\n\n x11(originAddr, originPort, cb) {\n const opts = { originAddr, originPort };\n openChannel(this, 'x11', opts, cb);\n return this;\n }\n\n forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) {\n const opts = { boundAddr, boundPort, remoteAddr, remotePort };\n openChannel(this, 'forwarded-tcpip', opts, cb);\n return this;\n }\n\n openssh_forwardOutStreamLocal(socketPath, cb) {\n const opts = { socketPath };\n openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb);\n return this;\n }\n\n rekey(cb) {\n let error;\n\n try {\n this._protocol.rekey();\n } catch (ex) {\n error = ex;\n }\n\n // TODO: re-throw error if no callback?\n\n if (typeof cb === 'function') {\n if (error)\n process.nextTick(cb, error);\n else\n this.once('rekey', cb);\n }\n }\n}\n\n\nfunction openChannel(self, type, opts, cb) {\n // Ask the client to open a channel for some purpose (e.g. a forwarded TCP\n // connection)\n const initWindow = MAX_WINDOW;\n const maxPacket = PACKET_SIZE;\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const wrapper = (err, stream) => {\n cb(err, stream);\n };\n wrapper.type = type;\n\n const localChan = self._chanMgr.add(wrapper);\n\n if (localChan === -1) {\n cb(new Error('No free channels available'));\n return;\n }\n\n switch (type) {\n case 'forwarded-tcpip':\n self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts);\n break;\n case 'x11':\n self._protocol.x11(localChan, initWindow, maxPacket, opts);\n break;\n case 'forwarded-streamlocal@openssh.com':\n self._protocol.openssh_forwardedStreamLocal(\n localChan, initWindow, maxPacket, opts\n );\n break;\n default:\n throw new Error(`Unsupported channel type: ${type}`);\n }\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nmodule.exports = Server;\nmodule.exports.IncomingClient = Client;\n","'use strict';\n\nconst { SFTP } = require('./protocol/SFTP.js');\n\nconst MAX_CHANNEL = 2 ** 32 - 1;\n\nfunction onChannelOpenFailure(self, recipient, info, cb) {\n self._chanMgr.remove(recipient);\n if (typeof cb !== 'function')\n return;\n\n let err;\n if (info instanceof Error) {\n err = info;\n } else if (typeof info === 'object' && info !== null) {\n err = new Error(`(SSH) Channel open failure: ${info.description}`);\n err.reason = info.reason;\n } else {\n err = new Error(\n '(SSH) Channel open failure: server closed channel unexpectedly'\n );\n err.reason = '';\n }\n\n cb(err);\n}\n\nfunction onCHANNEL_CLOSE(self, recipient, channel, err, dead) {\n if (typeof channel === 'function') {\n // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when\n // requesting to open a channel\n onChannelOpenFailure(self, recipient, err, channel);\n return;\n }\n\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.incoming && channel.incoming.state === 'closed')\n return;\n\n self._chanMgr.remove(recipient);\n\n if (channel.server && channel.constructor.name === 'Session')\n return;\n\n channel.incoming.state = 'closed';\n\n if (channel.readable)\n channel.push(null);\n if (channel.server) {\n if (channel.stderr.writable)\n channel.stderr.end();\n } else if (channel.stderr.readable) {\n channel.stderr.push(null);\n }\n\n if (channel.constructor !== SFTP\n && (channel.outgoing.state === 'open'\n || channel.outgoing.state === 'eof')\n && !dead) {\n channel.close();\n }\n if (channel.outgoing.state === 'closing')\n channel.outgoing.state = 'closed';\n\n const readState = channel._readableState;\n const writeState = channel._writableState;\n if (writeState && !writeState.ending && !writeState.finished && !dead)\n channel.end();\n\n // Take care of any outstanding channel requests\n const chanCallbacks = channel._callbacks;\n channel._callbacks = [];\n for (let i = 0; i < chanCallbacks.length; ++i)\n chanCallbacks[i](true);\n\n if (channel.server) {\n if (!channel.readable\n || channel.destroyed\n || (readState && readState.endEmitted)) {\n channel.emit('close');\n } else {\n channel.once('end', () => channel.emit('close'));\n }\n } else {\n let doClose;\n switch (channel.type) {\n case 'direct-streamlocal@openssh.com':\n case 'direct-tcpip':\n doClose = () => channel.emit('close');\n break;\n default: {\n // Align more with node child processes, where the close event gets\n // the same arguments as the exit event\n const exit = channel._exit;\n doClose = () => {\n if (exit.code === null)\n channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc);\n else\n channel.emit('close', exit.code);\n };\n }\n }\n if (!channel.readable\n || channel.destroyed\n || (readState && readState.endEmitted)) {\n doClose();\n } else {\n channel.once('end', doClose);\n }\n\n const errReadState = channel.stderr._readableState;\n if (!channel.stderr.readable\n || channel.stderr.destroyed\n || (errReadState && errReadState.endEmitted)) {\n channel.stderr.emit('close');\n } else {\n channel.stderr.once('end', () => channel.stderr.emit('close'));\n }\n }\n}\n\nclass ChannelManager {\n constructor(client) {\n this._client = client;\n this._channels = {};\n this._cur = -1;\n this._count = 0;\n }\n add(val) {\n // Attempt to reserve an id\n\n let id;\n // Optimized paths\n if (this._cur < MAX_CHANNEL) {\n id = ++this._cur;\n } else if (this._count === 0) {\n // Revert and reset back to fast path once we no longer have any channels\n // open\n this._cur = 0;\n id = 0;\n } else {\n // Slower lookup path\n\n // This path is triggered we have opened at least MAX_CHANNEL channels\n // while having at least one channel open at any given time, so we have\n // to search for a free id.\n const channels = this._channels;\n for (let i = 0; i < MAX_CHANNEL; ++i) {\n if (channels[i] === undefined) {\n id = i;\n break;\n }\n }\n }\n\n if (id === undefined)\n return -1;\n\n this._channels[id] = (val || true);\n ++this._count;\n\n return id;\n }\n update(id, val) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n if (val && this._channels[id])\n this._channels[id] = val;\n }\n get(id) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n return this._channels[id];\n }\n remove(id) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n if (this._channels[id]) {\n delete this._channels[id];\n if (this._count)\n --this._count;\n }\n }\n cleanup(err) {\n const channels = this._channels;\n this._channels = {};\n this._cur = -1;\n this._count = 0;\n\n const chanIDs = Object.keys(channels);\n const client = this._client;\n for (let i = 0; i < chanIDs.length; ++i) {\n const id = +chanIDs[i];\n const channel = channels[id];\n onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true);\n }\n }\n}\n\nconst isRegExp = (() => {\n const toString = Object.prototype.toString;\n return (val) => toString.call(val) === '[object RegExp]';\n})();\n\nfunction generateAlgorithmList(algoList, defaultList, supportedList) {\n if (Array.isArray(algoList) && algoList.length > 0) {\n // Exact list\n for (let i = 0; i < algoList.length; ++i) {\n if (supportedList.indexOf(algoList[i]) === -1)\n throw new Error(`Unsupported algorithm: ${algoList[i]}`);\n }\n return algoList;\n }\n\n if (typeof algoList === 'object' && algoList !== null) {\n // Operations based on the default list\n const keys = Object.keys(algoList);\n let list = defaultList;\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n let val = algoList[key];\n switch (key) {\n case 'append':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = 0; j < val.length; ++j) {\n const append = val[j];\n if (typeof append === 'string') {\n if (!append || list.indexOf(append) !== -1)\n continue;\n if (supportedList.indexOf(append) === -1)\n throw new Error(`Unsupported algorithm: ${append}`);\n if (list === defaultList)\n list = list.slice();\n list.push(append);\n } else if (isRegExp(append)) {\n for (let k = 0; k < supportedList.length; ++k) {\n const algo = supportedList[k];\n if (append.test(algo)) {\n if (list.indexOf(algo) !== -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.push(algo);\n }\n }\n }\n }\n }\n break;\n case 'prepend':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = val.length; j >= 0; --j) {\n const prepend = val[j];\n if (typeof prepend === 'string') {\n if (!prepend || list.indexOf(prepend) !== -1)\n continue;\n if (supportedList.indexOf(prepend) === -1)\n throw new Error(`Unsupported algorithm: ${prepend}`);\n if (list === defaultList)\n list = list.slice();\n list.unshift(prepend);\n } else if (isRegExp(prepend)) {\n for (let k = supportedList.length; k >= 0; --k) {\n const algo = supportedList[k];\n if (prepend.test(algo)) {\n if (list.indexOf(algo) !== -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.unshift(algo);\n }\n }\n }\n }\n }\n break;\n case 'remove':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = 0; j < val.length; ++j) {\n const search = val[j];\n if (typeof search === 'string') {\n if (!search)\n continue;\n const idx = list.indexOf(search);\n if (idx === -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.splice(idx, 1);\n } else if (isRegExp(search)) {\n for (let k = 0; k < list.length; ++k) {\n if (search.test(list[k])) {\n if (list === defaultList)\n list = list.slice();\n list.splice(k, 1);\n --k;\n }\n }\n }\n }\n }\n break;\n }\n }\n\n return list;\n }\n\n return defaultList;\n}\n\nmodule.exports = {\n ChannelManager,\n generateAlgorithmList,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n isWritable: (stream) => {\n // XXX: hack to workaround regression in node\n // See: https://github.com/nodejs/node/issues/36029\n return (stream\n && stream.writable\n && stream._readableState\n && stream._readableState.ended === false);\n },\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","var chownr = require('chownr')\nvar tar = require('tar-stream')\nvar pump = require('pump')\nvar mkdirp = require('mkdirp-classic')\nvar fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\nvar win32 = os.platform() === 'win32'\n\nvar noop = function () {}\n\nvar echo = function (name) {\n return name\n}\n\nvar normalize = !win32 ? echo : function (name) {\n return name.replace(/\\\\/g, '/').replace(/[:?<>|]/g, '_')\n}\n\nvar statAll = function (fs, stat, cwd, ignore, entries, sort) {\n var queue = entries || ['.']\n\n return function loop (callback) {\n if (!queue.length) return callback()\n var next = queue.shift()\n var nextAbs = path.join(cwd, next)\n\n stat(nextAbs, function (err, stat) {\n if (err) return callback(err)\n\n if (!stat.isDirectory()) return callback(null, next, stat)\n\n fs.readdir(nextAbs, function (err, files) {\n if (err) return callback(err)\n\n if (sort) files.sort()\n for (var i = 0; i < files.length; i++) {\n if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))\n }\n\n callback(null, next, stat)\n })\n })\n }\n}\n\nvar strip = function (map, level) {\n return function (header) {\n header.name = header.name.split('/').slice(level).join('/')\n\n var linkname = header.linkname\n if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {\n header.linkname = linkname.split('/').slice(level).join('/')\n }\n\n return map(header)\n }\n}\n\nexports.pack = function (cwd, opts) {\n if (!cwd) cwd = '.'\n if (!opts) opts = {}\n\n var xfs = opts.fs || fs\n var ignore = opts.ignore || opts.filter || noop\n var map = opts.map || noop\n var mapStream = opts.mapStream || echo\n var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)\n var strict = opts.strict !== false\n var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()\n var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0\n var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0\n var pack = opts.pack || tar.pack()\n var finish = opts.finish || noop\n\n if (opts.strip) map = strip(map, opts.strip)\n\n if (opts.readable) {\n dmode |= parseInt(555, 8)\n fmode |= parseInt(444, 8)\n }\n if (opts.writable) {\n dmode |= parseInt(333, 8)\n fmode |= parseInt(222, 8)\n }\n\n var onsymlink = function (filename, header) {\n xfs.readlink(path.join(cwd, filename), function (err, linkname) {\n if (err) return pack.destroy(err)\n header.linkname = normalize(linkname)\n pack.entry(header, onnextentry)\n })\n }\n\n var onstat = function (err, filename, stat) {\n if (err) return pack.destroy(err)\n if (!filename) {\n if (opts.finalize !== false) pack.finalize()\n return finish(pack)\n }\n\n if (stat.isSocket()) return onnextentry() // tar does not support sockets...\n\n var header = {\n name: normalize(filename),\n mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,\n mtime: stat.mtime,\n size: stat.size,\n type: 'file',\n uid: stat.uid,\n gid: stat.gid\n }\n\n if (stat.isDirectory()) {\n header.size = 0\n header.type = 'directory'\n header = map(header) || header\n return pack.entry(header, onnextentry)\n }\n\n if (stat.isSymbolicLink()) {\n header.size = 0\n header.type = 'symlink'\n header = map(header) || header\n return onsymlink(filename, header)\n }\n\n // TODO: add fifo etc...\n\n header = map(header) || header\n\n if (!stat.isFile()) {\n if (strict) return pack.destroy(new Error('unsupported type for ' + filename))\n return onnextentry()\n }\n\n var entry = pack.entry(header, onnextentry)\n if (!entry) return\n\n var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)\n\n rs.on('error', function (err) { // always forward errors on destroy\n entry.destroy(err)\n })\n\n pump(rs, entry)\n }\n\n var onnextentry = function (err) {\n if (err) return pack.destroy(err)\n statNext(onstat)\n }\n\n onnextentry()\n\n return pack\n}\n\nvar head = function (list) {\n return list.length ? list[list.length - 1] : null\n}\n\nvar processGetuid = function () {\n return process.getuid ? process.getuid() : -1\n}\n\nvar processUmask = function () {\n return process.umask ? process.umask() : 0\n}\n\nexports.extract = function (cwd, opts) {\n if (!cwd) cwd = '.'\n if (!opts) opts = {}\n\n var xfs = opts.fs || fs\n var ignore = opts.ignore || opts.filter || noop\n var map = opts.map || noop\n var mapStream = opts.mapStream || echo\n var own = opts.chown !== false && !win32 && processGetuid() === 0\n var extract = opts.extract || tar.extract()\n var stack = []\n var now = new Date()\n var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()\n var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0\n var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0\n var strict = opts.strict !== false\n\n if (opts.strip) map = strip(map, opts.strip)\n\n if (opts.readable) {\n dmode |= parseInt(555, 8)\n fmode |= parseInt(444, 8)\n }\n if (opts.writable) {\n dmode |= parseInt(333, 8)\n fmode |= parseInt(222, 8)\n }\n\n var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry\n var top\n while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()\n if (!top) return cb()\n xfs.utimes(top[0], now, top[1], cb)\n }\n\n var utimes = function (name, header, cb) {\n if (opts.utimes === false) return cb()\n\n if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)\n if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?\n\n xfs.utimes(name, now, header.mtime, function (err) {\n if (err) return cb(err)\n utimesParent(name, cb)\n })\n }\n\n var chperm = function (name, header, cb) {\n var link = header.type === 'symlink'\n\n /* eslint-disable node/no-deprecated-api */\n var chmod = link ? xfs.lchmod : xfs.chmod\n var chown = link ? xfs.lchown : xfs.chown\n /* eslint-enable node/no-deprecated-api */\n\n if (!chmod) return cb()\n\n var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask\n chmod(name, mode, function (err) {\n if (err) return cb(err)\n if (!own) return cb()\n if (!chown) return cb()\n chown(name, header.uid, header.gid, cb)\n })\n }\n\n extract.on('entry', function (header, stream, next) {\n header = map(header) || header\n header.name = normalize(header.name)\n var name = path.join(cwd, path.join('/', header.name))\n\n if (ignore(name, header)) {\n stream.resume()\n return next()\n }\n\n var stat = function (err) {\n if (err) return next(err)\n utimes(name, header, function (err) {\n if (err) return next(err)\n if (win32) return next()\n chperm(name, header, next)\n })\n }\n\n var onsymlink = function () {\n if (win32) return next() // skip symlinks on win for now before it can be tested\n xfs.unlink(name, function () {\n xfs.symlink(header.linkname, name, stat)\n })\n }\n\n var onlink = function () {\n if (win32) return next() // skip links on win for now before it can be tested\n xfs.unlink(name, function () {\n var srcpath = path.join(cwd, path.join('/', header.linkname))\n\n xfs.link(srcpath, name, function (err) {\n if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {\n stream = xfs.createReadStream(srcpath)\n return onfile()\n }\n\n stat(err)\n })\n })\n }\n\n var onfile = function () {\n var ws = xfs.createWriteStream(name)\n var rs = mapStream(stream, header)\n\n ws.on('error', function (err) { // always forward errors on destroy\n rs.destroy(err)\n })\n\n pump(rs, ws, function (err) {\n if (err) return next(err)\n ws.on('close', stat)\n })\n }\n\n if (header.type === 'directory') {\n stack.push([name, header.mtime])\n return mkdirfix(name, {\n fs: xfs, own: own, uid: header.uid, gid: header.gid\n }, stat)\n }\n\n var dir = path.dirname(name)\n\n validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {\n if (err) return next(err)\n if (!valid) return next(new Error(dir + ' is not a valid path'))\n\n mkdirfix(dir, {\n fs: xfs, own: own, uid: header.uid, gid: header.gid\n }, function (err) {\n if (err) return next(err)\n\n switch (header.type) {\n case 'file': return onfile()\n case 'link': return onlink()\n case 'symlink': return onsymlink()\n }\n\n if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))\n\n stream.resume()\n next()\n })\n })\n })\n\n if (opts.finish) extract.on('finish', opts.finish)\n\n return extract\n}\n\nfunction validate (fs, name, root, cb) {\n if (name === root) return cb(null, true)\n fs.lstat(name, function (err, st) {\n if (err && err.code !== 'ENOENT') return cb(err)\n if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)\n cb(null, false)\n })\n}\n\nfunction mkdirfix (name, opts, cb) {\n mkdirp(name, { fs: opts.fs }, function (err, made) {\n if (!err && made && opts.own) {\n chownr(made, opts.uid, opts.gid, cb)\n } else {\n cb(err)\n }\n })\n}\n","var util = require('util')\nvar bl = require('bl')\nvar headers = require('./headers')\n\nvar Writable = require('readable-stream').Writable\nvar PassThrough = require('readable-stream').PassThrough\n\nvar noop = function () {}\n\nvar overflow = function (size) {\n size &= 511\n return size && 512 - size\n}\n\nvar emptyStream = function (self, offset) {\n var s = new Source(self, offset)\n s.end()\n return s\n}\n\nvar mixinPax = function (header, pax) {\n if (pax.path) header.name = pax.path\n if (pax.linkpath) header.linkname = pax.linkpath\n if (pax.size) header.size = parseInt(pax.size, 10)\n header.pax = pax\n return header\n}\n\nvar Source = function (self, offset) {\n this._parent = self\n this.offset = offset\n PassThrough.call(this, { autoDestroy: false })\n}\n\nutil.inherits(Source, PassThrough)\n\nSource.prototype.destroy = function (err) {\n this._parent.destroy(err)\n}\n\nvar Extract = function (opts) {\n if (!(this instanceof Extract)) return new Extract(opts)\n Writable.call(this, opts)\n\n opts = opts || {}\n\n this._offset = 0\n this._buffer = bl()\n this._missing = 0\n this._partial = false\n this._onparse = noop\n this._header = null\n this._stream = null\n this._overflow = null\n this._cb = null\n this._locked = false\n this._destroyed = false\n this._pax = null\n this._paxGlobal = null\n this._gnuLongPath = null\n this._gnuLongLinkPath = null\n\n var self = this\n var b = self._buffer\n\n var oncontinue = function () {\n self._continue()\n }\n\n var onunlock = function (err) {\n self._locked = false\n if (err) return self.destroy(err)\n if (!self._stream) oncontinue()\n }\n\n var onstreamend = function () {\n self._stream = null\n var drain = overflow(self._header.size)\n if (drain) self._parse(drain, ondrain)\n else self._parse(512, onheader)\n if (!self._locked) oncontinue()\n }\n\n var ondrain = function () {\n self._buffer.consume(overflow(self._header.size))\n self._parse(512, onheader)\n oncontinue()\n }\n\n var onpaxglobalheader = function () {\n var size = self._header.size\n self._paxGlobal = headers.decodePax(b.slice(0, size))\n b.consume(size)\n onstreamend()\n }\n\n var onpaxheader = function () {\n var size = self._header.size\n self._pax = headers.decodePax(b.slice(0, size))\n if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulongpath = function () {\n var size = self._header.size\n this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulonglinkpath = function () {\n var size = self._header.size\n this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var onheader = function () {\n var offset = self._offset\n var header\n try {\n header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat)\n } catch (err) {\n self.emit('error', err)\n }\n b.consume(512)\n\n if (!header) {\n self._parse(512, onheader)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-path') {\n self._parse(header.size, ongnulongpath)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-link-path') {\n self._parse(header.size, ongnulonglinkpath)\n oncontinue()\n return\n }\n if (header.type === 'pax-global-header') {\n self._parse(header.size, onpaxglobalheader)\n oncontinue()\n return\n }\n if (header.type === 'pax-header') {\n self._parse(header.size, onpaxheader)\n oncontinue()\n return\n }\n\n if (self._gnuLongPath) {\n header.name = self._gnuLongPath\n self._gnuLongPath = null\n }\n\n if (self._gnuLongLinkPath) {\n header.linkname = self._gnuLongLinkPath\n self._gnuLongLinkPath = null\n }\n\n if (self._pax) {\n self._header = header = mixinPax(header, self._pax)\n self._pax = null\n }\n\n self._locked = true\n\n if (!header.size || header.type === 'directory') {\n self._parse(512, onheader)\n self.emit('entry', header, emptyStream(self, offset), onunlock)\n return\n }\n\n self._stream = new Source(self, offset)\n\n self.emit('entry', header, self._stream, onunlock)\n self._parse(header.size, onstreamend)\n oncontinue()\n }\n\n this._onheader = onheader\n this._parse(512, onheader)\n}\n\nutil.inherits(Extract, Writable)\n\nExtract.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream) this._stream.emit('close')\n}\n\nExtract.prototype._parse = function (size, onparse) {\n if (this._destroyed) return\n this._offset += size\n this._missing = size\n if (onparse === this._onheader) this._partial = false\n this._onparse = onparse\n}\n\nExtract.prototype._continue = function () {\n if (this._destroyed) return\n var cb = this._cb\n this._cb = noop\n if (this._overflow) this._write(this._overflow, undefined, cb)\n else cb()\n}\n\nExtract.prototype._write = function (data, enc, cb) {\n if (this._destroyed) return\n\n var s = this._stream\n var b = this._buffer\n var missing = this._missing\n if (data.length) this._partial = true\n\n // we do not reach end-of-chunk now. just forward it\n\n if (data.length < missing) {\n this._missing -= data.length\n this._overflow = null\n if (s) return s.write(data, cb)\n b.append(data)\n return cb()\n }\n\n // end-of-chunk. the parser should call cb.\n\n this._cb = cb\n this._missing = 0\n\n var overflow = null\n if (data.length > missing) {\n overflow = data.slice(missing)\n data = data.slice(0, missing)\n }\n\n if (s) s.end(data)\n else b.append(data)\n\n this._overflow = overflow\n this._onparse()\n}\n\nExtract.prototype._final = function (cb) {\n if (this._partial) return this.destroy(new Error('Unexpected end of data'))\n cb()\n}\n\nmodule.exports = Extract\n","var alloc = Buffer.alloc\n\nvar ZEROS = '0000000000000000000'\nvar SEVENS = '7777777777777777777'\nvar ZERO_OFFSET = '0'.charCodeAt(0)\nvar USTAR_MAGIC = Buffer.from('ustar\\x00', 'binary')\nvar USTAR_VER = Buffer.from('00', 'binary')\nvar GNU_MAGIC = Buffer.from('ustar\\x20', 'binary')\nvar GNU_VER = Buffer.from('\\x20\\x00', 'binary')\nvar MASK = parseInt('7777', 8)\nvar MAGIC_OFFSET = 257\nvar VERSION_OFFSET = 263\n\nvar clamp = function (index, len, defaultValue) {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nvar toType = function (flag) {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n }\n\n return null\n}\n\nvar toTypeflag = function (flag) {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n }\n\n return 0\n}\n\nvar indexOf = function (block, num, offset, end) {\n for (; offset < end; offset++) {\n if (block[offset] === num) return offset\n }\n return end\n}\n\nvar cksum = function (block) {\n var sum = 8 * 32\n for (var i = 0; i < 148; i++) sum += block[i]\n for (var j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nvar encodeOct = function (val, n) {\n val = val.toString(8)\n if (val.length > n) return SEVENS.slice(0, n) + ' '\n else return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n var positive\n if (buf[0] === 0x80) positive = true\n else if (buf[0] === 0xFF) positive = false\n else return null\n\n // build up a base-256 tuple from the least sig to the highest\n var tuple = []\n for (var i = buf.length - 1; i > 0; i--) {\n var byte = buf[i]\n if (positive) tuple.push(byte)\n else tuple.push(0xFF - byte)\n }\n\n var sum = 0\n var l = tuple.length\n for (i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nvar decodeOct = function (val, offset, length) {\n val = val.slice(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if (val[offset] & 0x80) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val[offset] === 32) offset++\n var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n while (offset < end && val[offset] === 0) offset++\n if (end === offset) return 0\n return parseInt(val.slice(offset, end).toString(), 8)\n }\n}\n\nvar decodeStr = function (val, offset, length, encoding) {\n return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding)\n}\n\nvar addLength = function (str) {\n var len = Buffer.byteLength(str)\n var digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n if (len + digits >= Math.pow(10, digits)) digits++\n\n return (len + digits) + str\n}\n\nexports.decodeLongPath = function (buf, encoding) {\n return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function (opts) { // TODO: encode more stuff in pax\n var result = ''\n if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n var pax = opts.pax\n if (pax) {\n for (var key in pax) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n return Buffer.from(result)\n}\n\nexports.decodePax = function (buf) {\n var result = {}\n\n while (buf.length) {\n var i = 0\n while (i < buf.length && buf[i] !== 32) i++\n var len = parseInt(buf.slice(0, i).toString(), 10)\n if (!len) return result\n\n var b = buf.slice(i + 1, len - 1).toString()\n var keyIndex = b.indexOf('=')\n if (keyIndex === -1) return result\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n buf = buf.slice(len)\n }\n\n return result\n}\n\nexports.encode = function (opts) {\n var buf = alloc(512)\n var name = opts.name\n var prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n if (Buffer.byteLength(name) !== name.length) return null // utf-8\n\n while (Buffer.byteLength(name) > 100) {\n var i = name.indexOf('/')\n if (i === -1) return null\n prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null\n if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null\n\n buf.write(name)\n buf.write(encodeOct(opts.mode & MASK, 6), 100)\n buf.write(encodeOct(opts.uid, 6), 108)\n buf.write(encodeOct(opts.gid, 6), 116)\n buf.write(encodeOct(opts.size, 11), 124)\n buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname) buf.write(opts.linkname, 157)\n\n USTAR_MAGIC.copy(buf, MAGIC_OFFSET)\n USTAR_VER.copy(buf, VERSION_OFFSET)\n if (opts.uname) buf.write(opts.uname, 265)\n if (opts.gname) buf.write(opts.gname, 297)\n buf.write(encodeOct(opts.devmajor || 0, 6), 329)\n buf.write(encodeOct(opts.devminor || 0, 6), 337)\n\n if (prefix) buf.write(prefix, 345)\n\n buf.write(encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n\nexports.decode = function (buf, filenameEncoding, allowUnknownFormat) {\n var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n var name = decodeStr(buf, 0, 100, filenameEncoding)\n var mode = decodeOct(buf, 100, 8)\n var uid = decodeOct(buf, 108, 8)\n var gid = decodeOct(buf, 116, 8)\n var size = decodeOct(buf, 124, 12)\n var mtime = decodeOct(buf, 136, 12)\n var type = toType(typeflag)\n var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n var uname = decodeStr(buf, 265, 32)\n var gname = decodeStr(buf, 297, 32)\n var devmajor = decodeOct(buf, 329, 8)\n var devminor = decodeOct(buf, 337, 8)\n\n var c = cksum(buf)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) return null\n\n // valid checksum\n if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 &&\n GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n if (!allowUnknownFormat) {\n throw new Error('Invalid tar header: unknown format.')\n }\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * mtime),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor\n }\n}\n","exports.extract = require('./extract')\nexports.pack = require('./pack')\n","var constants = require('fs-constants')\nvar eos = require('end-of-stream')\nvar inherits = require('inherits')\nvar alloc = Buffer.alloc\n\nvar Readable = require('readable-stream').Readable\nvar Writable = require('readable-stream').Writable\nvar StringDecoder = require('string_decoder').StringDecoder\n\nvar headers = require('./headers')\n\nvar DMODE = parseInt('755', 8)\nvar FMODE = parseInt('644', 8)\n\nvar END_OF_TAR = alloc(1024)\n\nvar noop = function () {}\n\nvar overflow = function (self, size) {\n size &= 511\n if (size) self.push(END_OF_TAR.slice(0, 512 - size))\n}\n\nfunction modeToType (mode) {\n switch (mode & constants.S_IFMT) {\n case constants.S_IFBLK: return 'block-device'\n case constants.S_IFCHR: return 'character-device'\n case constants.S_IFDIR: return 'directory'\n case constants.S_IFIFO: return 'fifo'\n case constants.S_IFLNK: return 'symlink'\n }\n\n return 'file'\n}\n\nvar Sink = function (to) {\n Writable.call(this)\n this.written = 0\n this._to = to\n this._destroyed = false\n}\n\ninherits(Sink, Writable)\n\nSink.prototype._write = function (data, enc, cb) {\n this.written += data.length\n if (this._to.push(data)) return cb()\n this._to._drain = cb\n}\n\nSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar LinkSink = function () {\n Writable.call(this)\n this.linkname = ''\n this._decoder = new StringDecoder('utf-8')\n this._destroyed = false\n}\n\ninherits(LinkSink, Writable)\n\nLinkSink.prototype._write = function (data, enc, cb) {\n this.linkname += this._decoder.write(data)\n cb()\n}\n\nLinkSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Void = function () {\n Writable.call(this)\n this._destroyed = false\n}\n\ninherits(Void, Writable)\n\nVoid.prototype._write = function (data, enc, cb) {\n cb(new Error('No body allowed for this entry'))\n}\n\nVoid.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Pack = function (opts) {\n if (!(this instanceof Pack)) return new Pack(opts)\n Readable.call(this, opts)\n\n this._drain = noop\n this._finalized = false\n this._finalizing = false\n this._destroyed = false\n this._stream = null\n}\n\ninherits(Pack, Readable)\n\nPack.prototype.entry = function (header, buffer, callback) {\n if (this._stream) throw new Error('already piping an entry')\n if (this._finalized || this._destroyed) return\n\n if (typeof buffer === 'function') {\n callback = buffer\n buffer = null\n }\n\n if (!callback) callback = noop\n\n var self = this\n\n if (!header.size || header.type === 'symlink') header.size = 0\n if (!header.type) header.type = modeToType(header.mode)\n if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n if (!header.uid) header.uid = 0\n if (!header.gid) header.gid = 0\n if (!header.mtime) header.mtime = new Date()\n\n if (typeof buffer === 'string') buffer = Buffer.from(buffer)\n if (Buffer.isBuffer(buffer)) {\n header.size = buffer.length\n this._encode(header)\n var ok = this.push(buffer)\n overflow(self, header.size)\n if (ok) process.nextTick(callback)\n else this._drain = callback\n return new Void()\n }\n\n if (header.type === 'symlink' && !header.linkname) {\n var linkSink = new LinkSink()\n eos(linkSink, function (err) {\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n header.linkname = linkSink.linkname\n self._encode(header)\n callback()\n })\n\n return linkSink\n }\n\n this._encode(header)\n\n if (header.type !== 'file' && header.type !== 'contiguous-file') {\n process.nextTick(callback)\n return new Void()\n }\n\n var sink = new Sink(this)\n\n this._stream = sink\n\n eos(sink, function (err) {\n self._stream = null\n\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n if (sink.written !== header.size) { // corrupting tar\n self.destroy()\n return callback(new Error('size mismatch'))\n }\n\n overflow(self, header.size)\n if (self._finalizing) self.finalize()\n callback()\n })\n\n return sink\n}\n\nPack.prototype.finalize = function () {\n if (this._stream) {\n this._finalizing = true\n return\n }\n\n if (this._finalized) return\n this._finalized = true\n this.push(END_OF_TAR)\n this.push(null)\n}\n\nPack.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream && this._stream.destroy) this._stream.destroy()\n}\n\nPack.prototype._encode = function (header) {\n if (!header.pax) {\n var buf = headers.encode(header)\n if (buf) {\n this.push(buf)\n return\n }\n }\n this._encodePax(header)\n}\n\nPack.prototype._encodePax = function (header) {\n var paxHeader = headers.encodePax({\n name: header.name,\n linkname: header.linkname,\n pax: header.pax\n })\n\n var newHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.length,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname && 'PaxHeader',\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n this.push(headers.encode(newHeader))\n this.push(paxHeader)\n overflow(this, paxHeader.length)\n\n newHeader.size = header.size\n newHeader.type = header.type\n this.push(headers.encode(newHeader))\n}\n\nPack.prototype._read = function (n) {\n var drain = this._drain\n this._drain = noop\n drain()\n}\n\nmodule.exports = Pack\n","module.exports = require('./lib/tunnel');\n","'use strict';\n\nvar net = require('net');\nvar tls = require('tls');\nvar http = require('http');\nvar https = require('https');\nvar events = require('events');\nvar assert = require('assert');\nvar util = require('util');\n\n\nexports.httpOverHttp = httpOverHttp;\nexports.httpsOverHttp = httpsOverHttp;\nexports.httpOverHttps = httpOverHttps;\nexports.httpsOverHttps = httpsOverHttps;\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n return agent;\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n return agent;\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this;\n self.options = options || {};\n self.proxyOptions = self.options.proxy || {};\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;\n self.requests = [];\n self.sockets = [];\n\n self.on('free', function onFree(socket, host, port, localAddress) {\n var options = toOptions(host, port, localAddress);\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i];\n if (pending.host === options.host && pending.port === options.port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1);\n pending.request.onSocket(socket);\n return;\n }\n }\n socket.destroy();\n self.removeSocket(socket);\n });\n}\nutil.inherits(TunnelingAgent, events.EventEmitter);\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {\n var self = this;\n var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push(options);\n return;\n }\n\n // If we are under maxSockets create a new one.\n self.createSocket(options, function(socket) {\n socket.on('free', onFree);\n socket.on('close', onCloseOrRemove);\n socket.on('agentRemove', onCloseOrRemove);\n req.onSocket(socket);\n\n function onFree() {\n self.emit('free', socket, options);\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket);\n socket.removeListener('free', onFree);\n socket.removeListener('close', onCloseOrRemove);\n socket.removeListener('agentRemove', onCloseOrRemove);\n }\n });\n};\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this;\n var placeholder = {};\n self.sockets.push(placeholder);\n\n var connectOptions = mergeOptions({}, self.proxyOptions, {\n method: 'CONNECT',\n path: options.host + ':' + options.port,\n agent: false,\n headers: {\n host: options.host + ':' + options.port\n }\n });\n if (options.localAddress) {\n connectOptions.localAddress = options.localAddress;\n }\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {};\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n new Buffer(connectOptions.proxyAuth).toString('base64');\n }\n\n debug('making CONNECT request');\n var connectReq = self.request(connectOptions);\n connectReq.useChunkedEncodingByDefault = false; // for v0.6\n connectReq.once('response', onResponse); // for v0.6\n connectReq.once('upgrade', onUpgrade); // for v0.6\n connectReq.once('connect', onConnect); // for v0.7 or later\n connectReq.once('error', onError);\n connectReq.end();\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true;\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head);\n });\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners();\n socket.removeAllListeners();\n\n if (res.statusCode !== 200) {\n debug('tunneling socket could not be established, statusCode=%d',\n res.statusCode);\n socket.destroy();\n var error = new Error('tunneling socket could not be established, ' +\n 'statusCode=' + res.statusCode);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n if (head.length > 0) {\n debug('got illegal response body from proxy');\n socket.destroy();\n var error = new Error('got illegal response body from proxy');\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n debug('tunneling connection has established');\n self.sockets[self.sockets.indexOf(placeholder)] = socket;\n return cb(socket);\n }\n\n function onError(cause) {\n connectReq.removeAllListeners();\n\n debug('tunneling socket could not be established, cause=%s\\n',\n cause.message, cause.stack);\n var error = new Error('tunneling socket could not be established, ' +\n 'cause=' + cause.message);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n }\n};\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) {\n return;\n }\n this.sockets.splice(pos, 1);\n\n var pending = this.requests.shift();\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createSocket(pending, function(socket) {\n pending.request.onSocket(socket);\n });\n }\n};\n\nfunction createSecureSocket(options, cb) {\n var self = this;\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n var hostHeader = options.request.getHeader('host');\n var tlsOptions = mergeOptions({}, self.options, {\n socket: socket,\n servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host\n });\n\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, tlsOptions);\n self.sockets[self.sockets.indexOf(socket)] = secureSocket;\n cb(secureSocket);\n });\n}\n\n\nfunction toOptions(host, port, localAddress) {\n if (typeof host === 'string') { // since v0.10\n return {\n host: host,\n port: port,\n localAddress: localAddress\n };\n }\n return host; // for v0.11 or later\n}\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i];\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides);\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j];\n if (overrides[k] !== undefined) {\n target[k] = overrides[k];\n }\n }\n }\n }\n return target;\n}\n\n\nvar debug;\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments);\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0];\n } else {\n args.unshift('TUNNEL:');\n }\n console.error.apply(console, args);\n }\n} else {\n debug = function() {};\n}\nexports.debug = debug; // for test\n","(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _0 = new Uint8Array(16);\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_16(x, xi, y, yi) {\n return vn(x,xi,y,yi,16);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction core_salsa20(o, p, k, c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n x0 = x0 + j0 | 0;\n x1 = x1 + j1 | 0;\n x2 = x2 + j2 | 0;\n x3 = x3 + j3 | 0;\n x4 = x4 + j4 | 0;\n x5 = x5 + j5 | 0;\n x6 = x6 + j6 | 0;\n x7 = x7 + j7 | 0;\n x8 = x8 + j8 | 0;\n x9 = x9 + j9 | 0;\n x10 = x10 + j10 | 0;\n x11 = x11 + j11 | 0;\n x12 = x12 + j12 | 0;\n x13 = x13 + j13 | 0;\n x14 = x14 + j14 | 0;\n x15 = x15 + j15 | 0;\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x1 >>> 0 & 0xff;\n o[ 5] = x1 >>> 8 & 0xff;\n o[ 6] = x1 >>> 16 & 0xff;\n o[ 7] = x1 >>> 24 & 0xff;\n\n o[ 8] = x2 >>> 0 & 0xff;\n o[ 9] = x2 >>> 8 & 0xff;\n o[10] = x2 >>> 16 & 0xff;\n o[11] = x2 >>> 24 & 0xff;\n\n o[12] = x3 >>> 0 & 0xff;\n o[13] = x3 >>> 8 & 0xff;\n o[14] = x3 >>> 16 & 0xff;\n o[15] = x3 >>> 24 & 0xff;\n\n o[16] = x4 >>> 0 & 0xff;\n o[17] = x4 >>> 8 & 0xff;\n o[18] = x4 >>> 16 & 0xff;\n o[19] = x4 >>> 24 & 0xff;\n\n o[20] = x5 >>> 0 & 0xff;\n o[21] = x5 >>> 8 & 0xff;\n o[22] = x5 >>> 16 & 0xff;\n o[23] = x5 >>> 24 & 0xff;\n\n o[24] = x6 >>> 0 & 0xff;\n o[25] = x6 >>> 8 & 0xff;\n o[26] = x6 >>> 16 & 0xff;\n o[27] = x6 >>> 24 & 0xff;\n\n o[28] = x7 >>> 0 & 0xff;\n o[29] = x7 >>> 8 & 0xff;\n o[30] = x7 >>> 16 & 0xff;\n o[31] = x7 >>> 24 & 0xff;\n\n o[32] = x8 >>> 0 & 0xff;\n o[33] = x8 >>> 8 & 0xff;\n o[34] = x8 >>> 16 & 0xff;\n o[35] = x8 >>> 24 & 0xff;\n\n o[36] = x9 >>> 0 & 0xff;\n o[37] = x9 >>> 8 & 0xff;\n o[38] = x9 >>> 16 & 0xff;\n o[39] = x9 >>> 24 & 0xff;\n\n o[40] = x10 >>> 0 & 0xff;\n o[41] = x10 >>> 8 & 0xff;\n o[42] = x10 >>> 16 & 0xff;\n o[43] = x10 >>> 24 & 0xff;\n\n o[44] = x11 >>> 0 & 0xff;\n o[45] = x11 >>> 8 & 0xff;\n o[46] = x11 >>> 16 & 0xff;\n o[47] = x11 >>> 24 & 0xff;\n\n o[48] = x12 >>> 0 & 0xff;\n o[49] = x12 >>> 8 & 0xff;\n o[50] = x12 >>> 16 & 0xff;\n o[51] = x12 >>> 24 & 0xff;\n\n o[52] = x13 >>> 0 & 0xff;\n o[53] = x13 >>> 8 & 0xff;\n o[54] = x13 >>> 16 & 0xff;\n o[55] = x13 >>> 24 & 0xff;\n\n o[56] = x14 >>> 0 & 0xff;\n o[57] = x14 >>> 8 & 0xff;\n o[58] = x14 >>> 16 & 0xff;\n o[59] = x14 >>> 24 & 0xff;\n\n o[60] = x15 >>> 0 & 0xff;\n o[61] = x15 >>> 8 & 0xff;\n o[62] = x15 >>> 16 & 0xff;\n o[63] = x15 >>> 24 & 0xff;\n}\n\nfunction core_hsalsa20(o,p,k,c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x5 >>> 0 & 0xff;\n o[ 5] = x5 >>> 8 & 0xff;\n o[ 6] = x5 >>> 16 & 0xff;\n o[ 7] = x5 >>> 24 & 0xff;\n\n o[ 8] = x10 >>> 0 & 0xff;\n o[ 9] = x10 >>> 8 & 0xff;\n o[10] = x10 >>> 16 & 0xff;\n o[11] = x10 >>> 24 & 0xff;\n\n o[12] = x15 >>> 0 & 0xff;\n o[13] = x15 >>> 8 & 0xff;\n o[14] = x15 >>> 16 & 0xff;\n o[15] = x15 >>> 24 & 0xff;\n\n o[16] = x6 >>> 0 & 0xff;\n o[17] = x6 >>> 8 & 0xff;\n o[18] = x6 >>> 16 & 0xff;\n o[19] = x6 >>> 24 & 0xff;\n\n o[20] = x7 >>> 0 & 0xff;\n o[21] = x7 >>> 8 & 0xff;\n o[22] = x7 >>> 16 & 0xff;\n o[23] = x7 >>> 24 & 0xff;\n\n o[24] = x8 >>> 0 & 0xff;\n o[25] = x8 >>> 8 & 0xff;\n o[26] = x8 >>> 16 & 0xff;\n o[27] = x8 >>> 24 & 0xff;\n\n o[28] = x9 >>> 0 & 0xff;\n o[29] = x9 >>> 8 & 0xff;\n o[30] = x9 >>> 16 & 0xff;\n o[31] = x9 >>> 24 & 0xff;\n}\n\nfunction crypto_core_salsa20(out,inp,k,c) {\n core_salsa20(out,inp,k,c);\n}\n\nfunction crypto_core_hsalsa20(out,inp,k,c) {\n core_hsalsa20(out,inp,k,c);\n}\n\nvar sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);\n // \"expand 32-byte k\"\n\nfunction crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n mpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n }\n return 0;\n}\n\nfunction crypto_stream_salsa20(c,cpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = x[i];\n }\n return 0;\n}\n\nfunction crypto_stream(c,cpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20(c,cpos,d,sn,s);\n}\n\nfunction crypto_stream_xor(c,cpos,m,mpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);\n}\n\n/*\n* Port of Andrew Moon's Poly1305-donna-16. Public domain.\n* https://github.com/floodyberry/poly1305-donna\n*/\n\nvar poly1305 = function(key) {\n this.buffer = new Uint8Array(16);\n this.r = new Uint16Array(10);\n this.h = new Uint16Array(10);\n this.pad = new Uint16Array(8);\n this.leftover = 0;\n this.fin = 0;\n\n var t0, t1, t2, t3, t4, t5, t6, t7;\n\n t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;\n t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = ((t4 >>> 1)) & 0x1ffe;\n t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = ((t7 >>> 5)) & 0x007f;\n\n this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;\n this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;\n this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;\n this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;\n this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;\n this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;\n this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;\n this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;\n};\n\npoly1305.prototype.blocks = function(m, mpos, bytes) {\n var hibit = this.fin ? 0 : (1 << 11);\n var t0, t1, t2, t3, t4, t5, t6, t7, c;\n var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;\n\n var h0 = this.h[0],\n h1 = this.h[1],\n h2 = this.h[2],\n h3 = this.h[3],\n h4 = this.h[4],\n h5 = this.h[5],\n h6 = this.h[6],\n h7 = this.h[7],\n h8 = this.h[8],\n h9 = this.h[9];\n\n var r0 = this.r[0],\n r1 = this.r[1],\n r2 = this.r[2],\n r3 = this.r[3],\n r4 = this.r[4],\n r5 = this.r[5],\n r6 = this.r[6],\n r7 = this.r[7],\n r8 = this.r[8],\n r9 = this.r[9];\n\n while (bytes >= 16) {\n t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;\n t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n c = 0;\n\n d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this.h[0] = h0;\n this.h[1] = h1;\n this.h[2] = h2;\n this.h[3] = h3;\n this.h[4] = h4;\n this.h[5] = h5;\n this.h[6] = h6;\n this.h[7] = h7;\n this.h[8] = h8;\n this.h[9] = h9;\n};\n\npoly1305.prototype.finish = function(mac, macpos) {\n var g = new Uint16Array(10);\n var c, mask, f, i;\n\n if (this.leftover) {\n i = this.leftover;\n this.buffer[i++] = 1;\n for (; i < 16; i++) this.buffer[i] = 0;\n this.fin = 1;\n this.blocks(this.buffer, 0, 16);\n }\n\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this.h[i] += c;\n c = this.h[i] >>> 13;\n this.h[i] &= 0x1fff;\n }\n this.h[0] += (c * 5);\n c = this.h[0] >>> 13;\n this.h[0] &= 0x1fff;\n this.h[1] += c;\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n this.h[2] += c;\n\n g[0] = this.h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this.h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];\n\n this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;\n this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;\n this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;\n this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;\n this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;\n this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;\n this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;\n this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;\n\n f = this.h[0] + this.pad[0];\n this.h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;\n this.h[i] = f & 0xffff;\n }\n\n mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;\n mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;\n mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;\n mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;\n mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;\n mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;\n mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;\n mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;\n mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;\n mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;\n mac[macpos+10] = (this.h[5] >>> 0) & 0xff;\n mac[macpos+11] = (this.h[5] >>> 8) & 0xff;\n mac[macpos+12] = (this.h[6] >>> 0) & 0xff;\n mac[macpos+13] = (this.h[6] >>> 8) & 0xff;\n mac[macpos+14] = (this.h[7] >>> 0) & 0xff;\n mac[macpos+15] = (this.h[7] >>> 8) & 0xff;\n};\n\npoly1305.prototype.update = function(m, mpos, bytes) {\n var i, want;\n\n if (this.leftover) {\n want = (16 - this.leftover);\n if (want > bytes)\n want = bytes;\n for (i = 0; i < want; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n bytes -= want;\n mpos += want;\n this.leftover += want;\n if (this.leftover < 16)\n return;\n this.blocks(this.buffer, 0, 16);\n this.leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this.blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (i = 0; i < bytes; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n this.leftover += bytes;\n }\n};\n\nfunction crypto_onetimeauth(out, outpos, m, mpos, n, k) {\n var s = new poly1305(k);\n s.update(m, mpos, n);\n s.finish(out, outpos);\n return 0;\n}\n\nfunction crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {\n var x = new Uint8Array(16);\n crypto_onetimeauth(x,0,m,mpos,n,k);\n return crypto_verify_16(h,hpos,x,0);\n}\n\nfunction crypto_secretbox(c,m,d,n,k) {\n var i;\n if (d < 32) return -1;\n crypto_stream_xor(c,0,m,0,d,n,k);\n crypto_onetimeauth(c, 16, c, 32, d - 32, c);\n for (i = 0; i < 16; i++) c[i] = 0;\n return 0;\n}\n\nfunction crypto_secretbox_open(m,c,d,n,k) {\n var i;\n var x = new Uint8Array(32);\n if (d < 32) return -1;\n crypto_stream(x,0,32,n,k);\n if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;\n crypto_stream_xor(m,0,c,0,d,n,k);\n for (i = 0; i < 32; i++) m[i] = 0;\n return 0;\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction crypto_box_beforenm(k, y, x) {\n var s = new Uint8Array(32);\n crypto_scalarmult(s, x, y);\n return crypto_core_hsalsa20(k, _0, s, sigma);\n}\n\nvar crypto_box_afternm = crypto_secretbox;\nvar crypto_box_open_afternm = crypto_secretbox_open;\n\nfunction crypto_box(c, m, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_afternm(c, m, d, n, k);\n}\n\nfunction crypto_box_open(m, c, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_open_afternm(m, c, d, n, k);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n mlen = n;\n return mlen;\n}\n\nvar crypto_secretbox_KEYBYTES = 32,\n crypto_secretbox_NONCEBYTES = 24,\n crypto_secretbox_ZEROBYTES = 32,\n crypto_secretbox_BOXZEROBYTES = 16,\n crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_box_BEFORENMBYTES = 32,\n crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,\n crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,\n crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32,\n crypto_hash_BYTES = 64;\n\nnacl.lowlevel = {\n crypto_core_hsalsa20: crypto_core_hsalsa20,\n crypto_stream_xor: crypto_stream_xor,\n crypto_stream: crypto_stream,\n crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,\n crypto_stream_salsa20: crypto_stream_salsa20,\n crypto_onetimeauth: crypto_onetimeauth,\n crypto_onetimeauth_verify: crypto_onetimeauth_verify,\n crypto_verify_16: crypto_verify_16,\n crypto_verify_32: crypto_verify_32,\n crypto_secretbox: crypto_secretbox,\n crypto_secretbox_open: crypto_secretbox_open,\n crypto_scalarmult: crypto_scalarmult,\n crypto_scalarmult_base: crypto_scalarmult_base,\n crypto_box_beforenm: crypto_box_beforenm,\n crypto_box_afternm: crypto_box_afternm,\n crypto_box: crypto_box,\n crypto_box_open: crypto_box_open,\n crypto_box_keypair: crypto_box_keypair,\n crypto_hash: crypto_hash,\n crypto_sign: crypto_sign,\n crypto_sign_keypair: crypto_sign_keypair,\n crypto_sign_open: crypto_sign_open,\n\n crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,\n crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,\n crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,\n crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,\n crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,\n crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,\n crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,\n crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,\n crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,\n crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,\n crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,\n crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,\n crypto_sign_BYTES: crypto_sign_BYTES,\n crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,\n crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,\n crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,\n crypto_hash_BYTES: crypto_hash_BYTES\n};\n\n/* High-level API */\n\nfunction checkLengths(k, n) {\n if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');\n if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');\n}\n\nfunction checkBoxLengths(pk, sk) {\n if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');\n if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');\n}\n\nfunction checkArrayTypes() {\n var t, i;\n for (i = 0; i < arguments.length; i++) {\n if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')\n throw new TypeError('unexpected type ' + t + ', use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\n// TODO: Completely remove this in v0.15.\nif (!nacl.util) {\n nacl.util = {};\n nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() {\n throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');\n };\n}\n\nnacl.randomBytes = function(n) {\n var b = new Uint8Array(n);\n randombytes(b, n);\n return b;\n};\n\nnacl.secretbox = function(msg, nonce, key) {\n checkArrayTypes(msg, nonce, key);\n checkLengths(key, nonce);\n var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);\n var c = new Uint8Array(m.length);\n for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];\n crypto_secretbox(c, m, m.length, nonce, key);\n return c.subarray(crypto_secretbox_BOXZEROBYTES);\n};\n\nnacl.secretbox.open = function(box, nonce, key) {\n checkArrayTypes(box, nonce, key);\n checkLengths(key, nonce);\n var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);\n var m = new Uint8Array(c.length);\n for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];\n if (c.length < 32) return false;\n if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false;\n return m.subarray(crypto_secretbox_ZEROBYTES);\n};\n\nnacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;\nnacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;\nnacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.scalarMult.base = function(n) {\n checkArrayTypes(n);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult_base(q, n);\n return q;\n};\n\nnacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;\nnacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;\n\nnacl.box = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox(msg, nonce, k);\n};\n\nnacl.box.before = function(publicKey, secretKey) {\n checkArrayTypes(publicKey, secretKey);\n checkBoxLengths(publicKey, secretKey);\n var k = new Uint8Array(crypto_box_BEFORENMBYTES);\n crypto_box_beforenm(k, publicKey, secretKey);\n return k;\n};\n\nnacl.box.after = nacl.secretbox;\n\nnacl.box.open = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox.open(msg, nonce, k);\n};\n\nnacl.box.open.after = nacl.secretbox.open;\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;\nnacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;\nnacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;\nnacl.box.nonceLength = crypto_box_NONCEBYTES;\nnacl.box.overheadLength = nacl.secretbox.overheadLength;\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.open = function(signedMsg, publicKey) {\n if (arguments.length !== 2)\n throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');\n checkArrayTypes(signedMsg, publicKey);\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var tmp = new Uint8Array(signedMsg.length);\n var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);\n if (mlen < 0) return null;\n var m = new Uint8Array(mlen);\n for (var i = 0; i < m.length; i++) m[i] = tmp[i];\n return m;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;\nnacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;\nnacl.sign.seedLength = crypto_sign_SEEDBYTES;\nnacl.sign.signatureLength = crypto_sign_BYTES;\n\nnacl.hash = function(msg) {\n checkArrayTypes(msg);\n var h = new Uint8Array(crypto_hash_BYTES);\n crypto_hash(h, msg, msg.length);\n return h;\n};\n\nnacl.hash.hashLength = crypto_hash_BYTES;\n\nnacl.verify = function(x, y) {\n checkArrayTypes(x, y);\n // Zero length arguments are considered not equal.\n if (x.length === 0 || y.length === 0) return false;\n if (x.length !== y.length) return false;\n return (vn(x, 0, y, 0, x.length) === 0) ? true : false;\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\n\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\n\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\n\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\n\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\n\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\n\nvar _version = _interopRequireDefault(require(\"./version.js\"));\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction md5(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return _crypto.default.createHash('md5').update(bytes).digest();\n}\n\nvar _default = md5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = '00000000-0000-0000-0000-000000000000';\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nvar _default = parse;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\n\nfunction rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n _crypto.default.randomFillSync(rnds8Pool);\n\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return _crypto.default.createHash('sha1').update(bytes).digest();\n}\n\nvar _default = sha1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nvar _default = stringify;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\nlet _nodeId;\n\nlet _clockseq; // Previous uuid creation time\n\n\nlet _lastMSecs = 0;\nlet _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node || _nodeId;\n let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || (0, _stringify.default)(b);\n}\n\nvar _default = v1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = v3;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = _default;\nexports.URL = exports.DNS = void 0;\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nconst DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexports.DNS = DNS;\nconst URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexports.URL = URL;\n\nfunction _default(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.default)(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction v4(options, buf, offset) {\n options = options || {};\n\n const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.default)(rnds);\n}\n\nvar _default = v4;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = v5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\n\nvar _default = validate;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nvar _default = version;\nexports.default = _default;","// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.cleanupOldImageVersions = exports.run = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst dockerode_1 = __importDefault(require(\"dockerode\"));\nconst docker_tags_1 = require(\"./docker-tags\");\n// This method performs housekeeping checks to remove Docker artifacts\n// which were left behind by old versions of the action or any jobs\n// which may have crashed before deleting their own containers or networks\n//\n// cutoff - a Go duration string to pass to the Docker API's 'until' argument, default '24h'\nfunction run(cutoff = '24h') {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const docker = new dockerode_1.default();\n const untilFilter = { until: [cutoff] };\n core.info(`Pruning networks older than ${cutoff}`);\n yield docker.pruneNetworks({ filters: untilFilter });\n core.info(`Pruning containers older than ${cutoff}`);\n yield docker.pruneContainers({ filters: untilFilter });\n yield cleanupOldImageVersions(docker, docker_tags_1.UPDATER_IMAGE_NAME);\n yield cleanupOldImageVersions(docker, docker_tags_1.PROXY_IMAGE_NAME);\n }\n catch (error) {\n if (error instanceof Error) {\n core.error(`Error cleaning up: ${error.message}`);\n }\n }\n });\n}\nexports.run = run;\nfunction cleanupOldImageVersions(docker, imageName) {\n return __awaiter(this, void 0, void 0, function* () {\n const repo = (0, docker_tags_1.repositoryName)(imageName);\n const options = {\n filters: {\n reference: [repo]\n }\n };\n core.info(`Cleaning up images for ${repo}`);\n docker.listImages(options, function (err, imageInfoList) {\n var _a, _b;\n return __awaiter(this, void 0, void 0, function* () {\n if (imageInfoList && imageInfoList.length > 0) {\n for (const imageInfo of imageInfoList) {\n // The given imageName is expected to be a digest, however to avoid any surprises in future\n // we fail over to check for a match on tags as well.\n //\n // This means we won't remove any image which matches an imageName of either of these notations:\n // - dependabot/image@sha256:$REF (current implementation)\n // - dependabot/image:v1\n //\n // Without checking imageInfo.RepoTags for a match, we would actually remove the latter even if\n // this was the active version.\n if (((_a = imageInfo.RepoDigests) === null || _a === void 0 ? void 0 : _a.includes(imageName)) ||\n ((_b = imageInfo.RepoTags) === null || _b === void 0 ? void 0 : _b.includes(imageName))) {\n core.info(`Skipping current image ${imageInfo.Id}`);\n continue;\n }\n core.info(`Removing image ${imageInfo.Id}`);\n try {\n yield docker.getImage(imageInfo.Id).remove();\n }\n catch (error) {\n if (error instanceof Error) {\n core.info(`Unable to remove ${imageInfo.Id} -- ${error.message}`);\n }\n }\n }\n }\n });\n });\n });\n}\nexports.cleanupOldImageVersions = cleanupOldImageVersions;\nrun();\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.repositoryName = exports.PROXY_IMAGE_NAME = exports.UPDATER_IMAGE_NAME = void 0;\nconst containers_json_1 = __importDefault(require(\"../docker/containers.json\"));\nexports.UPDATER_IMAGE_NAME = containers_json_1.default.updater;\nexports.PROXY_IMAGE_NAME = containers_json_1.default.proxy;\nconst imageNamePattern = '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))((:[a-zA-Z0-9._/-]+)|(@sha256:[a-zA-Z0-9]{64}))?$';\nfunction repositoryName(imageName) {\n const match = imageName.match(imageNamePattern);\n if (match === null || match === void 0 ? void 0 : match.groups) {\n return match.groups['repository'];\n }\n else {\n throw Error('invalid image name');\n }\n}\nexports.repositoryName = repositoryName;\n","module.exports = __non_webpack_require__(__webpack_require__.ab + \"build/Release/cpufeatures.node\")","module.exports = __non_webpack_require__(__webpack_require__.ab + \"lib/protocol/crypto/build/Release/sshcrypto.node\")","module.exports = require(\"assert\");","module.exports = require(\"buffer\");","module.exports = require(\"child_process\");","module.exports = require(\"constants\");","module.exports = require(\"crypto\");","module.exports = require(\"dns\");","module.exports = require(\"events\");","module.exports = require(\"fs\");","module.exports = require(\"http\");","module.exports = require(\"https\");","module.exports = require(\"net\");","module.exports = require(\"os\");","module.exports = require(\"path\");","module.exports = require(\"querystring\");","module.exports = require(\"stream\");","module.exports = require(\"string_decoder\");","module.exports = require(\"tls\");","module.exports = require(\"tty\");","module.exports = require(\"url\");","module.exports = require(\"util\");","module.exports = require(\"zlib\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\tvar threw = true;\n\ttry {\n\t\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\t\tthrew = false;\n\t} finally {\n\t\tif(threw) delete __webpack_module_cache__[moduleId];\n\t}\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","\nif (typeof __webpack_require__ !== 'undefined') __webpack_require__.ab = __dirname + \"/\";","","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(3812);\n",""],"names":[],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"index.js","mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3oBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1WA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3iBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtKA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACniBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5jCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvyDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7FA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnmCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1BA;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtSA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9lEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvlEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn9HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjkDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpwCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC38CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn2CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3YA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtSA;AACA;;;;;;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9PA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn1EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACr0BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/IA;AACA;AACA;AACA;AACA;;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1uEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACzgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5lBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5kBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnmEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACj7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1jBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACroBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrRA;;;;;;;;ACAA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChoBA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnDA;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC7BA;AACA;;;;AEDA;AACA;AACA;AACA","sources":[".././node_modules/@actions/core/lib/command.js",".././node_modules/@actions/core/lib/core.js",".././node_modules/@actions/core/lib/file-command.js",".././node_modules/@actions/core/lib/oidc-utils.js",".././node_modules/@actions/core/lib/path-utils.js",".././node_modules/@actions/core/lib/summary.js",".././node_modules/@actions/core/lib/utils.js",".././node_modules/@actions/http-client/lib/auth.js",".././node_modules/@actions/http-client/lib/index.js",".././node_modules/@actions/http-client/lib/proxy.js",".././node_modules/@balena/dockerignore/ignore.js",".././node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js",".././node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js",".././node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js",".././node_modules/@fastify/busboy/deps/streamsearch/sbmh.js",".././node_modules/@fastify/busboy/lib/main.js",".././node_modules/@fastify/busboy/lib/types/multipart.js",".././node_modules/@fastify/busboy/lib/types/urlencoded.js",".././node_modules/@fastify/busboy/lib/utils/Decoder.js",".././node_modules/@fastify/busboy/lib/utils/basename.js",".././node_modules/@fastify/busboy/lib/utils/decodeText.js",".././node_modules/@fastify/busboy/lib/utils/getLimit.js",".././node_modules/@fastify/busboy/lib/utils/parseParams.js",".././node_modules/asn1/lib/ber/errors.js",".././node_modules/asn1/lib/ber/index.js",".././node_modules/asn1/lib/ber/reader.js",".././node_modules/asn1/lib/ber/types.js",".././node_modules/asn1/lib/ber/writer.js",".././node_modules/asn1/lib/index.js",".././node_modules/bcrypt-pbkdf/index.js",".././node_modules/chownr/chownr.js",".././node_modules/cpu-features/lib/index.js",".././node_modules/debug/src/browser.js",".././node_modules/debug/src/common.js",".././node_modules/debug/src/index.js",".././node_modules/debug/src/node.js",".././node_modules/docker-modem/lib/http.js",".././node_modules/docker-modem/lib/http_duplex.js",".././node_modules/docker-modem/lib/modem.js",".././node_modules/docker-modem/lib/ssh.js",".././node_modules/docker-modem/lib/utils.js",".././node_modules/dockerode/lib/config.js",".././node_modules/dockerode/lib/container.js",".././node_modules/dockerode/lib/docker.js",".././node_modules/dockerode/lib/exec.js",".././node_modules/dockerode/lib/image.js",".././node_modules/dockerode/lib/network.js",".././node_modules/dockerode/lib/node.js",".././node_modules/dockerode/lib/plugin.js",".././node_modules/dockerode/lib/secret.js",".././node_modules/dockerode/lib/service.js",".././node_modules/dockerode/lib/task.js",".././node_modules/dockerode/lib/util.js",".././node_modules/dockerode/lib/volume.js",".././node_modules/end-of-stream/index.js",".././node_modules/fs-constants/index.js",".././node_modules/has-flag/index.js",".././node_modules/inherits/inherits.js",".././node_modules/inherits/inherits_browser.js",".././node_modules/mkdirp-classic/index.js",".././node_modules/ms/index.js",".././node_modules/once/once.js",".././node_modules/pump/index.js",".././node_modules/readable-stream/errors.js",".././node_modules/readable-stream/lib/_stream_duplex.js",".././node_modules/readable-stream/lib/_stream_passthrough.js",".././node_modules/readable-stream/lib/_stream_readable.js",".././node_modules/readable-stream/lib/_stream_transform.js",".././node_modules/readable-stream/lib/_stream_writable.js",".././node_modules/readable-stream/lib/internal/streams/async_iterator.js",".././node_modules/readable-stream/lib/internal/streams/buffer_list.js",".././node_modules/readable-stream/lib/internal/streams/destroy.js",".././node_modules/readable-stream/lib/internal/streams/end-of-stream.js",".././node_modules/readable-stream/lib/internal/streams/from.js",".././node_modules/readable-stream/lib/internal/streams/pipeline.js",".././node_modules/readable-stream/lib/internal/streams/state.js",".././node_modules/readable-stream/lib/internal/streams/stream.js",".././node_modules/readable-stream/readable.js",".././node_modules/safer-buffer/safer.js",".././node_modules/split-ca/index.js",".././node_modules/ssh2/lib/Channel.js",".././node_modules/ssh2/lib/agent.js",".././node_modules/ssh2/lib/client.js",".././node_modules/ssh2/lib/http-agents.js",".././node_modules/ssh2/lib/index.js",".././node_modules/ssh2/lib/keygen.js",".././node_modules/ssh2/lib/protocol/Protocol.js",".././node_modules/ssh2/lib/protocol/SFTP.js",".././node_modules/ssh2/lib/protocol/constants.js",".././node_modules/ssh2/lib/protocol/crypto.js",".././node_modules/ssh2/lib/protocol/crypto/poly1305.js",".././node_modules/ssh2/lib/protocol/handlers.js",".././node_modules/ssh2/lib/protocol/handlers.misc.js",".././node_modules/ssh2/lib/protocol/kex.js",".././node_modules/ssh2/lib/protocol/keyParser.js",".././node_modules/ssh2/lib/protocol/node-fs-compat.js",".././node_modules/ssh2/lib/protocol/utils.js",".././node_modules/ssh2/lib/protocol/zlib.js",".././node_modules/ssh2/lib/server.js",".././node_modules/ssh2/lib/utils.js",".././node_modules/string_decoder/lib/string_decoder.js",".././node_modules/string_decoder/node_modules/safe-buffer/index.js",".././node_modules/supports-color/index.js",".././node_modules/tar-fs/index.js",".././node_modules/tar-fs/node_modules/bl/BufferList.js",".././node_modules/tar-fs/node_modules/bl/bl.js",".././node_modules/tar-fs/node_modules/tar-stream/extract.js",".././node_modules/tar-fs/node_modules/tar-stream/headers.js",".././node_modules/tar-fs/node_modules/tar-stream/index.js",".././node_modules/tar-fs/node_modules/tar-stream/pack.js",".././node_modules/tunnel/index.js",".././node_modules/tunnel/lib/tunnel.js",".././node_modules/tweetnacl/nacl-fast.js",".././node_modules/undici/index.js",".././node_modules/undici/lib/agent.js",".././node_modules/undici/lib/api/abort-signal.js",".././node_modules/undici/lib/api/api-connect.js",".././node_modules/undici/lib/api/api-pipeline.js",".././node_modules/undici/lib/api/api-request.js",".././node_modules/undici/lib/api/api-stream.js",".././node_modules/undici/lib/api/api-upgrade.js",".././node_modules/undici/lib/api/index.js",".././node_modules/undici/lib/api/readable.js",".././node_modules/undici/lib/api/util.js",".././node_modules/undici/lib/balanced-pool.js",".././node_modules/undici/lib/cache/cache.js",".././node_modules/undici/lib/cache/cachestorage.js",".././node_modules/undici/lib/cache/symbols.js",".././node_modules/undici/lib/cache/util.js",".././node_modules/undici/lib/client.js",".././node_modules/undici/lib/compat/dispatcher-weakref.js",".././node_modules/undici/lib/cookies/constants.js",".././node_modules/undici/lib/cookies/index.js",".././node_modules/undici/lib/cookies/parse.js",".././node_modules/undici/lib/cookies/util.js",".././node_modules/undici/lib/core/connect.js",".././node_modules/undici/lib/core/constants.js",".././node_modules/undici/lib/core/errors.js",".././node_modules/undici/lib/core/request.js",".././node_modules/undici/lib/core/symbols.js",".././node_modules/undici/lib/core/util.js",".././node_modules/undici/lib/dispatcher-base.js",".././node_modules/undici/lib/dispatcher.js",".././node_modules/undici/lib/fetch/body.js",".././node_modules/undici/lib/fetch/constants.js",".././node_modules/undici/lib/fetch/dataURL.js",".././node_modules/undici/lib/fetch/file.js",".././node_modules/undici/lib/fetch/formdata.js",".././node_modules/undici/lib/fetch/global.js",".././node_modules/undici/lib/fetch/headers.js",".././node_modules/undici/lib/fetch/index.js",".././node_modules/undici/lib/fetch/request.js",".././node_modules/undici/lib/fetch/response.js",".././node_modules/undici/lib/fetch/symbols.js",".././node_modules/undici/lib/fetch/util.js",".././node_modules/undici/lib/fetch/webidl.js",".././node_modules/undici/lib/fileapi/encoding.js",".././node_modules/undici/lib/fileapi/filereader.js",".././node_modules/undici/lib/fileapi/progressevent.js",".././node_modules/undici/lib/fileapi/symbols.js",".././node_modules/undici/lib/fileapi/util.js",".././node_modules/undici/lib/global.js",".././node_modules/undici/lib/handler/DecoratorHandler.js",".././node_modules/undici/lib/handler/RedirectHandler.js",".././node_modules/undici/lib/handler/RetryHandler.js",".././node_modules/undici/lib/interceptor/redirectInterceptor.js",".././node_modules/undici/lib/llhttp/constants.js",".././node_modules/undici/lib/llhttp/llhttp-wasm.js",".././node_modules/undici/lib/llhttp/llhttp_simd-wasm.js",".././node_modules/undici/lib/llhttp/utils.js",".././node_modules/undici/lib/mock/mock-agent.js",".././node_modules/undici/lib/mock/mock-client.js",".././node_modules/undici/lib/mock/mock-errors.js",".././node_modules/undici/lib/mock/mock-interceptor.js",".././node_modules/undici/lib/mock/mock-pool.js",".././node_modules/undici/lib/mock/mock-symbols.js",".././node_modules/undici/lib/mock/mock-utils.js",".././node_modules/undici/lib/mock/pending-interceptors-formatter.js",".././node_modules/undici/lib/mock/pluralizer.js",".././node_modules/undici/lib/node/fixed-queue.js",".././node_modules/undici/lib/pool-base.js",".././node_modules/undici/lib/pool-stats.js",".././node_modules/undici/lib/pool.js",".././node_modules/undici/lib/proxy-agent.js",".././node_modules/undici/lib/timers.js",".././node_modules/undici/lib/websocket/connection.js",".././node_modules/undici/lib/websocket/constants.js",".././node_modules/undici/lib/websocket/events.js",".././node_modules/undici/lib/websocket/frame.js",".././node_modules/undici/lib/websocket/receiver.js",".././node_modules/undici/lib/websocket/symbols.js",".././node_modules/undici/lib/websocket/util.js",".././node_modules/undici/lib/websocket/websocket.js",".././node_modules/util-deprecate/node.js",".././node_modules/uuid/dist/index.js",".././node_modules/uuid/dist/md5.js",".././node_modules/uuid/dist/nil.js",".././node_modules/uuid/dist/parse.js",".././node_modules/uuid/dist/regex.js",".././node_modules/uuid/dist/rng.js",".././node_modules/uuid/dist/sha1.js",".././node_modules/uuid/dist/stringify.js",".././node_modules/uuid/dist/v1.js",".././node_modules/uuid/dist/v3.js",".././node_modules/uuid/dist/v35.js",".././node_modules/uuid/dist/v4.js",".././node_modules/uuid/dist/v5.js",".././node_modules/uuid/dist/validate.js",".././node_modules/uuid/dist/version.js",".././node_modules/wrappy/wrappy.js",".././src/cleanup.ts",".././src/docker-tags.ts",".././node_modules/cpu-features/build/Release/cpufeatures.node",".././node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node","../external node-commonjs \"assert\"","../external node-commonjs \"async_hooks\"","../external node-commonjs \"buffer\"","../external node-commonjs \"child_process\"","../external node-commonjs \"console\"","../external node-commonjs \"constants\"","../external node-commonjs \"crypto\"","../external node-commonjs \"diagnostics_channel\"","../external node-commonjs \"dns\"","../external node-commonjs \"events\"","../external node-commonjs \"fs\"","../external node-commonjs \"http\"","../external node-commonjs \"http2\"","../external node-commonjs \"https\"","../external node-commonjs \"net\"","../external node-commonjs \"node:events\"","../external node-commonjs \"node:stream\"","../external node-commonjs \"node:util\"","../external node-commonjs \"os\"","../external node-commonjs \"path\"","../external node-commonjs \"perf_hooks\"","../external node-commonjs \"querystring\"","../external node-commonjs \"stream\"","../external node-commonjs \"stream/web\"","../external node-commonjs \"string_decoder\"","../external node-commonjs \"tls\"","../external node-commonjs \"tty\"","../external node-commonjs \"url\"","../external node-commonjs \"util\"","../external node-commonjs \"util/types\"","../external node-commonjs \"worker_threads\"","../external node-commonjs \"zlib\"","../webpack/bootstrap","../webpack/runtime/compat","../webpack/before-startup","../webpack/startup","../webpack/after-startup"],"sourcesContent":["\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issue = exports.issueCommand = void 0;\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\n/**\n * Commands\n *\n * Command Format:\n * ::name key=value,key=value::message\n *\n * Examples:\n * ::warning::This is the message\n * ::set-env name=MY_VAR::some value\n */\nfunction issueCommand(command, properties, message) {\n const cmd = new Command(command, properties, message);\n process.stdout.write(cmd.toString() + os.EOL);\n}\nexports.issueCommand = issueCommand;\nfunction issue(name, message = '') {\n issueCommand(name, {}, message);\n}\nexports.issue = issue;\nconst CMD_STRING = '::';\nclass Command {\n constructor(command, properties, message) {\n if (!command) {\n command = 'missing.command';\n }\n this.command = command;\n this.properties = properties;\n this.message = message;\n }\n toString() {\n let cmdStr = CMD_STRING + this.command;\n if (this.properties && Object.keys(this.properties).length > 0) {\n cmdStr += ' ';\n let first = true;\n for (const key in this.properties) {\n if (this.properties.hasOwnProperty(key)) {\n const val = this.properties[key];\n if (val) {\n if (first) {\n first = false;\n }\n else {\n cmdStr += ',';\n }\n cmdStr += `${key}=${escapeProperty(val)}`;\n }\n }\n }\n }\n cmdStr += `${CMD_STRING}${escapeData(this.message)}`;\n return cmdStr;\n }\n}\nfunction escapeData(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A');\n}\nfunction escapeProperty(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n}\n//# sourceMappingURL=command.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;\nconst command_1 = require(\"./command\");\nconst file_command_1 = require(\"./file-command\");\nconst utils_1 = require(\"./utils\");\nconst os = __importStar(require(\"os\"));\nconst path = __importStar(require(\"path\"));\nconst oidc_utils_1 = require(\"./oidc-utils\");\n/**\n * The code to exit an action\n */\nvar ExitCode;\n(function (ExitCode) {\n /**\n * A code indicating that the action was successful\n */\n ExitCode[ExitCode[\"Success\"] = 0] = \"Success\";\n /**\n * A code indicating that the action was a failure\n */\n ExitCode[ExitCode[\"Failure\"] = 1] = \"Failure\";\n})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));\n//-----------------------------------------------------------------------\n// Variables\n//-----------------------------------------------------------------------\n/**\n * Sets env variable for this action and future actions in the job\n * @param name the name of the variable to set\n * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction exportVariable(name, val) {\n const convertedVal = utils_1.toCommandValue(val);\n process.env[name] = convertedVal;\n const filePath = process.env['GITHUB_ENV'] || '';\n if (filePath) {\n return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val));\n }\n command_1.issueCommand('set-env', { name }, convertedVal);\n}\nexports.exportVariable = exportVariable;\n/**\n * Registers a secret which will get masked from logs\n * @param secret value of the secret\n */\nfunction setSecret(secret) {\n command_1.issueCommand('add-mask', {}, secret);\n}\nexports.setSecret = setSecret;\n/**\n * Prepends inputPath to the PATH (for this action and future actions)\n * @param inputPath\n */\nfunction addPath(inputPath) {\n const filePath = process.env['GITHUB_PATH'] || '';\n if (filePath) {\n file_command_1.issueFileCommand('PATH', inputPath);\n }\n else {\n command_1.issueCommand('add-path', {}, inputPath);\n }\n process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;\n}\nexports.addPath = addPath;\n/**\n * Gets the value of an input.\n * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.\n * Returns an empty string if the value is not defined.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string\n */\nfunction getInput(name, options) {\n const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';\n if (options && options.required && !val) {\n throw new Error(`Input required and not supplied: ${name}`);\n }\n if (options && options.trimWhitespace === false) {\n return val;\n }\n return val.trim();\n}\nexports.getInput = getInput;\n/**\n * Gets the values of an multiline input. Each value is also trimmed.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string[]\n *\n */\nfunction getMultilineInput(name, options) {\n const inputs = getInput(name, options)\n .split('\\n')\n .filter(x => x !== '');\n if (options && options.trimWhitespace === false) {\n return inputs;\n }\n return inputs.map(input => input.trim());\n}\nexports.getMultilineInput = getMultilineInput;\n/**\n * Gets the input value of the boolean type in the YAML 1.2 \"core schema\" specification.\n * Support boolean input list: `true | True | TRUE | false | False | FALSE` .\n * The return value is also in boolean type.\n * ref: https://yaml.org/spec/1.2/spec.html#id2804923\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns boolean\n */\nfunction getBooleanInput(name, options) {\n const trueValue = ['true', 'True', 'TRUE'];\n const falseValue = ['false', 'False', 'FALSE'];\n const val = getInput(name, options);\n if (trueValue.includes(val))\n return true;\n if (falseValue.includes(val))\n return false;\n throw new TypeError(`Input does not meet YAML 1.2 \"Core Schema\" specification: ${name}\\n` +\n `Support boolean input list: \\`true | True | TRUE | false | False | FALSE\\``);\n}\nexports.getBooleanInput = getBooleanInput;\n/**\n * Sets the value of an output.\n *\n * @param name name of the output to set\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setOutput(name, value) {\n const filePath = process.env['GITHUB_OUTPUT'] || '';\n if (filePath) {\n return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value));\n }\n process.stdout.write(os.EOL);\n command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value));\n}\nexports.setOutput = setOutput;\n/**\n * Enables or disables the echoing of commands into stdout for the rest of the step.\n * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.\n *\n */\nfunction setCommandEcho(enabled) {\n command_1.issue('echo', enabled ? 'on' : 'off');\n}\nexports.setCommandEcho = setCommandEcho;\n//-----------------------------------------------------------------------\n// Results\n//-----------------------------------------------------------------------\n/**\n * Sets the action status to failed.\n * When the action exits it will be with an exit code of 1\n * @param message add error issue message\n */\nfunction setFailed(message) {\n process.exitCode = ExitCode.Failure;\n error(message);\n}\nexports.setFailed = setFailed;\n//-----------------------------------------------------------------------\n// Logging Commands\n//-----------------------------------------------------------------------\n/**\n * Gets whether Actions Step Debug is on or not\n */\nfunction isDebug() {\n return process.env['RUNNER_DEBUG'] === '1';\n}\nexports.isDebug = isDebug;\n/**\n * Writes debug message to user log\n * @param message debug message\n */\nfunction debug(message) {\n command_1.issueCommand('debug', {}, message);\n}\nexports.debug = debug;\n/**\n * Adds an error issue\n * @param message error issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction error(message, properties = {}) {\n command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.error = error;\n/**\n * Adds a warning issue\n * @param message warning issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction warning(message, properties = {}) {\n command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.warning = warning;\n/**\n * Adds a notice issue\n * @param message notice issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction notice(message, properties = {}) {\n command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.notice = notice;\n/**\n * Writes info to log with console.log.\n * @param message info message\n */\nfunction info(message) {\n process.stdout.write(message + os.EOL);\n}\nexports.info = info;\n/**\n * Begin an output group.\n *\n * Output until the next `groupEnd` will be foldable in this group\n *\n * @param name The name of the output group\n */\nfunction startGroup(name) {\n command_1.issue('group', name);\n}\nexports.startGroup = startGroup;\n/**\n * End an output group.\n */\nfunction endGroup() {\n command_1.issue('endgroup');\n}\nexports.endGroup = endGroup;\n/**\n * Wrap an asynchronous function call in a group.\n *\n * Returns the same type as the function itself.\n *\n * @param name The name of the group\n * @param fn The function to wrap in the group\n */\nfunction group(name, fn) {\n return __awaiter(this, void 0, void 0, function* () {\n startGroup(name);\n let result;\n try {\n result = yield fn();\n }\n finally {\n endGroup();\n }\n return result;\n });\n}\nexports.group = group;\n//-----------------------------------------------------------------------\n// Wrapper action state\n//-----------------------------------------------------------------------\n/**\n * Saves state for current action, the state can only be retrieved by this action's post job execution.\n *\n * @param name name of the state to store\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction saveState(name, value) {\n const filePath = process.env['GITHUB_STATE'] || '';\n if (filePath) {\n return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value));\n }\n command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value));\n}\nexports.saveState = saveState;\n/**\n * Gets the value of an state set by this action's main execution.\n *\n * @param name name of the state to get\n * @returns string\n */\nfunction getState(name) {\n return process.env[`STATE_${name}`] || '';\n}\nexports.getState = getState;\nfunction getIDToken(aud) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield oidc_utils_1.OidcClient.getIDToken(aud);\n });\n}\nexports.getIDToken = getIDToken;\n/**\n * Summary exports\n */\nvar summary_1 = require(\"./summary\");\nObject.defineProperty(exports, \"summary\", { enumerable: true, get: function () { return summary_1.summary; } });\n/**\n * @deprecated use core.summary\n */\nvar summary_2 = require(\"./summary\");\nObject.defineProperty(exports, \"markdownSummary\", { enumerable: true, get: function () { return summary_2.markdownSummary; } });\n/**\n * Path exports\n */\nvar path_utils_1 = require(\"./path-utils\");\nObject.defineProperty(exports, \"toPosixPath\", { enumerable: true, get: function () { return path_utils_1.toPosixPath; } });\nObject.defineProperty(exports, \"toWin32Path\", { enumerable: true, get: function () { return path_utils_1.toWin32Path; } });\nObject.defineProperty(exports, \"toPlatformPath\", { enumerable: true, get: function () { return path_utils_1.toPlatformPath; } });\n//# sourceMappingURL=core.js.map","\"use strict\";\n// For internal use, subject to change.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.prepareKeyValueMessage = exports.issueFileCommand = void 0;\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst fs = __importStar(require(\"fs\"));\nconst os = __importStar(require(\"os\"));\nconst uuid_1 = require(\"uuid\");\nconst utils_1 = require(\"./utils\");\nfunction issueFileCommand(command, message) {\n const filePath = process.env[`GITHUB_${command}`];\n if (!filePath) {\n throw new Error(`Unable to find environment variable for file command ${command}`);\n }\n if (!fs.existsSync(filePath)) {\n throw new Error(`Missing file at path: ${filePath}`);\n }\n fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {\n encoding: 'utf8'\n });\n}\nexports.issueFileCommand = issueFileCommand;\nfunction prepareKeyValueMessage(key, value) {\n const delimiter = `ghadelimiter_${uuid_1.v4()}`;\n const convertedValue = utils_1.toCommandValue(value);\n // These should realistically never happen, but just in case someone finds a\n // way to exploit uuid generation let's not allow keys or values that contain\n // the delimiter.\n if (key.includes(delimiter)) {\n throw new Error(`Unexpected input: name should not contain the delimiter \"${delimiter}\"`);\n }\n if (convertedValue.includes(delimiter)) {\n throw new Error(`Unexpected input: value should not contain the delimiter \"${delimiter}\"`);\n }\n return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;\n}\nexports.prepareKeyValueMessage = prepareKeyValueMessage;\n//# sourceMappingURL=file-command.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OidcClient = void 0;\nconst http_client_1 = require(\"@actions/http-client\");\nconst auth_1 = require(\"@actions/http-client/lib/auth\");\nconst core_1 = require(\"./core\");\nclass OidcClient {\n static createHttpClient(allowRetry = true, maxRetry = 10) {\n const requestOptions = {\n allowRetries: allowRetry,\n maxRetries: maxRetry\n };\n return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);\n }\n static getRequestToken() {\n const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];\n if (!token) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');\n }\n return token;\n }\n static getIDTokenUrl() {\n const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];\n if (!runtimeUrl) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');\n }\n return runtimeUrl;\n }\n static getCall(id_token_url) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const httpclient = OidcClient.createHttpClient();\n const res = yield httpclient\n .getJson(id_token_url)\n .catch(error => {\n throw new Error(`Failed to get ID Token. \\n \n Error Code : ${error.statusCode}\\n \n Error Message: ${error.message}`);\n });\n const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;\n if (!id_token) {\n throw new Error('Response json body do not have ID Token field');\n }\n return id_token;\n });\n }\n static getIDToken(audience) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // New ID Token is requested from action service\n let id_token_url = OidcClient.getIDTokenUrl();\n if (audience) {\n const encodedAudience = encodeURIComponent(audience);\n id_token_url = `${id_token_url}&audience=${encodedAudience}`;\n }\n core_1.debug(`ID token url is ${id_token_url}`);\n const id_token = yield OidcClient.getCall(id_token_url);\n core_1.setSecret(id_token);\n return id_token;\n }\n catch (error) {\n throw new Error(`Error message: ${error.message}`);\n }\n });\n }\n}\nexports.OidcClient = OidcClient;\n//# sourceMappingURL=oidc-utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;\nconst path = __importStar(require(\"path\"));\n/**\n * toPosixPath converts the given path to the posix form. On Windows, \\\\ will be\n * replaced with /.\n *\n * @param pth. Path to transform.\n * @return string Posix path.\n */\nfunction toPosixPath(pth) {\n return pth.replace(/[\\\\]/g, '/');\n}\nexports.toPosixPath = toPosixPath;\n/**\n * toWin32Path converts the given path to the win32 form. On Linux, / will be\n * replaced with \\\\.\n *\n * @param pth. Path to transform.\n * @return string Win32 path.\n */\nfunction toWin32Path(pth) {\n return pth.replace(/[/]/g, '\\\\');\n}\nexports.toWin32Path = toWin32Path;\n/**\n * toPlatformPath converts the given path to a platform-specific path. It does\n * this by replacing instances of / and \\ with the platform-specific path\n * separator.\n *\n * @param pth The path to platformize.\n * @return string The platform-specific path.\n */\nfunction toPlatformPath(pth) {\n return pth.replace(/[/\\\\]/g, path.sep);\n}\nexports.toPlatformPath = toPlatformPath;\n//# sourceMappingURL=path-utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;\nconst os_1 = require(\"os\");\nconst fs_1 = require(\"fs\");\nconst { access, appendFile, writeFile } = fs_1.promises;\nexports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';\nexports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';\nclass Summary {\n constructor() {\n this._buffer = '';\n }\n /**\n * Finds the summary file path from the environment, rejects if env var is not found or file does not exist\n * Also checks r/w permissions.\n *\n * @returns step summary file path\n */\n filePath() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._filePath) {\n return this._filePath;\n }\n const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];\n if (!pathFromEnv) {\n throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);\n }\n try {\n yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);\n }\n catch (_a) {\n throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);\n }\n this._filePath = pathFromEnv;\n return this._filePath;\n });\n }\n /**\n * Wraps content in an HTML tag, adding any HTML attributes\n *\n * @param {string} tag HTML tag to wrap\n * @param {string | null} content content within the tag\n * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add\n *\n * @returns {string} content wrapped in HTML element\n */\n wrap(tag, content, attrs = {}) {\n const htmlAttrs = Object.entries(attrs)\n .map(([key, value]) => ` ${key}=\"${value}\"`)\n .join('');\n if (!content) {\n return `<${tag}${htmlAttrs}>`;\n }\n return `<${tag}${htmlAttrs}>${content}`;\n }\n /**\n * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.\n *\n * @param {SummaryWriteOptions} [options] (optional) options for write operation\n *\n * @returns {Promise} summary instance\n */\n write(options) {\n return __awaiter(this, void 0, void 0, function* () {\n const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);\n const filePath = yield this.filePath();\n const writeFunc = overwrite ? writeFile : appendFile;\n yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });\n return this.emptyBuffer();\n });\n }\n /**\n * Clears the summary buffer and wipes the summary file\n *\n * @returns {Summary} summary instance\n */\n clear() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.emptyBuffer().write({ overwrite: true });\n });\n }\n /**\n * Returns the current summary buffer as a string\n *\n * @returns {string} string of summary buffer\n */\n stringify() {\n return this._buffer;\n }\n /**\n * If the summary buffer is empty\n *\n * @returns {boolen} true if the buffer is empty\n */\n isEmptyBuffer() {\n return this._buffer.length === 0;\n }\n /**\n * Resets the summary buffer without writing to summary file\n *\n * @returns {Summary} summary instance\n */\n emptyBuffer() {\n this._buffer = '';\n return this;\n }\n /**\n * Adds raw text to the summary buffer\n *\n * @param {string} text content to add\n * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)\n *\n * @returns {Summary} summary instance\n */\n addRaw(text, addEOL = false) {\n this._buffer += text;\n return addEOL ? this.addEOL() : this;\n }\n /**\n * Adds the operating system-specific end-of-line marker to the buffer\n *\n * @returns {Summary} summary instance\n */\n addEOL() {\n return this.addRaw(os_1.EOL);\n }\n /**\n * Adds an HTML codeblock to the summary buffer\n *\n * @param {string} code content to render within fenced code block\n * @param {string} lang (optional) language to syntax highlight code\n *\n * @returns {Summary} summary instance\n */\n addCodeBlock(code, lang) {\n const attrs = Object.assign({}, (lang && { lang }));\n const element = this.wrap('pre', this.wrap('code', code), attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML list to the summary buffer\n *\n * @param {string[]} items list of items to render\n * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)\n *\n * @returns {Summary} summary instance\n */\n addList(items, ordered = false) {\n const tag = ordered ? 'ol' : 'ul';\n const listItems = items.map(item => this.wrap('li', item)).join('');\n const element = this.wrap(tag, listItems);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML table to the summary buffer\n *\n * @param {SummaryTableCell[]} rows table rows\n *\n * @returns {Summary} summary instance\n */\n addTable(rows) {\n const tableBody = rows\n .map(row => {\n const cells = row\n .map(cell => {\n if (typeof cell === 'string') {\n return this.wrap('td', cell);\n }\n const { header, data, colspan, rowspan } = cell;\n const tag = header ? 'th' : 'td';\n const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));\n return this.wrap(tag, data, attrs);\n })\n .join('');\n return this.wrap('tr', cells);\n })\n .join('');\n const element = this.wrap('table', tableBody);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds a collapsable HTML details element to the summary buffer\n *\n * @param {string} label text for the closed state\n * @param {string} content collapsable content\n *\n * @returns {Summary} summary instance\n */\n addDetails(label, content) {\n const element = this.wrap('details', this.wrap('summary', label) + content);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML image tag to the summary buffer\n *\n * @param {string} src path to the image you to embed\n * @param {string} alt text description of the image\n * @param {SummaryImageOptions} options (optional) addition image attributes\n *\n * @returns {Summary} summary instance\n */\n addImage(src, alt, options) {\n const { width, height } = options || {};\n const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));\n const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML section heading element\n *\n * @param {string} text heading text\n * @param {number | string} [level=1] (optional) the heading level, default: 1\n *\n * @returns {Summary} summary instance\n */\n addHeading(text, level) {\n const tag = `h${level}`;\n const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)\n ? tag\n : 'h1';\n const element = this.wrap(allowedTag, text);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML thematic break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addSeparator() {\n const element = this.wrap('hr', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML line break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addBreak() {\n const element = this.wrap('br', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML blockquote to the summary buffer\n *\n * @param {string} text quote text\n * @param {string} cite (optional) citation url\n *\n * @returns {Summary} summary instance\n */\n addQuote(text, cite) {\n const attrs = Object.assign({}, (cite && { cite }));\n const element = this.wrap('blockquote', text, attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML anchor tag to the summary buffer\n *\n * @param {string} text link text/content\n * @param {string} href hyperlink\n *\n * @returns {Summary} summary instance\n */\n addLink(text, href) {\n const element = this.wrap('a', text, { href });\n return this.addRaw(element).addEOL();\n }\n}\nconst _summary = new Summary();\n/**\n * @deprecated use `core.summary`\n */\nexports.markdownSummary = _summary;\nexports.summary = _summary;\n//# sourceMappingURL=summary.js.map","\"use strict\";\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toCommandProperties = exports.toCommandValue = void 0;\n/**\n * Sanitizes an input into a string so it can be passed into issueCommand safely\n * @param input input to sanitize into a string\n */\nfunction toCommandValue(input) {\n if (input === null || input === undefined) {\n return '';\n }\n else if (typeof input === 'string' || input instanceof String) {\n return input;\n }\n return JSON.stringify(input);\n}\nexports.toCommandValue = toCommandValue;\n/**\n *\n * @param annotationProperties\n * @returns The command properties to send with the actual annotation command\n * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646\n */\nfunction toCommandProperties(annotationProperties) {\n if (!Object.keys(annotationProperties).length) {\n return {};\n }\n return {\n title: annotationProperties.title,\n file: annotationProperties.file,\n line: annotationProperties.startLine,\n endLine: annotationProperties.endLine,\n col: annotationProperties.startColumn,\n endColumn: annotationProperties.endColumn\n };\n}\nexports.toCommandProperties = toCommandProperties;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;\nclass BasicCredentialHandler {\n constructor(username, password) {\n this.username = username;\n this.password = password;\n }\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BasicCredentialHandler = BasicCredentialHandler;\nclass BearerCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Bearer ${this.token}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BearerCredentialHandler = BearerCredentialHandler;\nclass PersonalAccessTokenCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;\n//# sourceMappingURL=auth.js.map","\"use strict\";\n/* eslint-disable @typescript-eslint/no-explicit-any */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;\nconst http = __importStar(require(\"http\"));\nconst https = __importStar(require(\"https\"));\nconst pm = __importStar(require(\"./proxy\"));\nconst tunnel = __importStar(require(\"tunnel\"));\nconst undici_1 = require(\"undici\");\nvar HttpCodes;\n(function (HttpCodes) {\n HttpCodes[HttpCodes[\"OK\"] = 200] = \"OK\";\n HttpCodes[HttpCodes[\"MultipleChoices\"] = 300] = \"MultipleChoices\";\n HttpCodes[HttpCodes[\"MovedPermanently\"] = 301] = \"MovedPermanently\";\n HttpCodes[HttpCodes[\"ResourceMoved\"] = 302] = \"ResourceMoved\";\n HttpCodes[HttpCodes[\"SeeOther\"] = 303] = \"SeeOther\";\n HttpCodes[HttpCodes[\"NotModified\"] = 304] = \"NotModified\";\n HttpCodes[HttpCodes[\"UseProxy\"] = 305] = \"UseProxy\";\n HttpCodes[HttpCodes[\"SwitchProxy\"] = 306] = \"SwitchProxy\";\n HttpCodes[HttpCodes[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n HttpCodes[HttpCodes[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n HttpCodes[HttpCodes[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpCodes[HttpCodes[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpCodes[HttpCodes[\"PaymentRequired\"] = 402] = \"PaymentRequired\";\n HttpCodes[HttpCodes[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpCodes[HttpCodes[\"NotFound\"] = 404] = \"NotFound\";\n HttpCodes[HttpCodes[\"MethodNotAllowed\"] = 405] = \"MethodNotAllowed\";\n HttpCodes[HttpCodes[\"NotAcceptable\"] = 406] = \"NotAcceptable\";\n HttpCodes[HttpCodes[\"ProxyAuthenticationRequired\"] = 407] = \"ProxyAuthenticationRequired\";\n HttpCodes[HttpCodes[\"RequestTimeout\"] = 408] = \"RequestTimeout\";\n HttpCodes[HttpCodes[\"Conflict\"] = 409] = \"Conflict\";\n HttpCodes[HttpCodes[\"Gone\"] = 410] = \"Gone\";\n HttpCodes[HttpCodes[\"TooManyRequests\"] = 429] = \"TooManyRequests\";\n HttpCodes[HttpCodes[\"InternalServerError\"] = 500] = \"InternalServerError\";\n HttpCodes[HttpCodes[\"NotImplemented\"] = 501] = \"NotImplemented\";\n HttpCodes[HttpCodes[\"BadGateway\"] = 502] = \"BadGateway\";\n HttpCodes[HttpCodes[\"ServiceUnavailable\"] = 503] = \"ServiceUnavailable\";\n HttpCodes[HttpCodes[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n})(HttpCodes || (exports.HttpCodes = HttpCodes = {}));\nvar Headers;\n(function (Headers) {\n Headers[\"Accept\"] = \"accept\";\n Headers[\"ContentType\"] = \"content-type\";\n})(Headers || (exports.Headers = Headers = {}));\nvar MediaTypes;\n(function (MediaTypes) {\n MediaTypes[\"ApplicationJson\"] = \"application/json\";\n})(MediaTypes || (exports.MediaTypes = MediaTypes = {}));\n/**\n * Returns the proxy URL, depending upon the supplied url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\nfunction getProxyUrl(serverUrl) {\n const proxyUrl = pm.getProxyUrl(new URL(serverUrl));\n return proxyUrl ? proxyUrl.href : '';\n}\nexports.getProxyUrl = getProxyUrl;\nconst HttpRedirectCodes = [\n HttpCodes.MovedPermanently,\n HttpCodes.ResourceMoved,\n HttpCodes.SeeOther,\n HttpCodes.TemporaryRedirect,\n HttpCodes.PermanentRedirect\n];\nconst HttpResponseRetryCodes = [\n HttpCodes.BadGateway,\n HttpCodes.ServiceUnavailable,\n HttpCodes.GatewayTimeout\n];\nconst RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];\nconst ExponentialBackoffCeiling = 10;\nconst ExponentialBackoffTimeSlice = 5;\nclass HttpClientError extends Error {\n constructor(message, statusCode) {\n super(message);\n this.name = 'HttpClientError';\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, HttpClientError.prototype);\n }\n}\nexports.HttpClientError = HttpClientError;\nclass HttpClientResponse {\n constructor(message) {\n this.message = message;\n }\n readBody() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n let output = Buffer.alloc(0);\n this.message.on('data', (chunk) => {\n output = Buffer.concat([output, chunk]);\n });\n this.message.on('end', () => {\n resolve(output.toString());\n });\n }));\n });\n }\n readBodyBuffer() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n const chunks = [];\n this.message.on('data', (chunk) => {\n chunks.push(chunk);\n });\n this.message.on('end', () => {\n resolve(Buffer.concat(chunks));\n });\n }));\n });\n }\n}\nexports.HttpClientResponse = HttpClientResponse;\nfunction isHttps(requestUrl) {\n const parsedUrl = new URL(requestUrl);\n return parsedUrl.protocol === 'https:';\n}\nexports.isHttps = isHttps;\nclass HttpClient {\n constructor(userAgent, handlers, requestOptions) {\n this._ignoreSslError = false;\n this._allowRedirects = true;\n this._allowRedirectDowngrade = false;\n this._maxRedirects = 50;\n this._allowRetries = false;\n this._maxRetries = 1;\n this._keepAlive = false;\n this._disposed = false;\n this.userAgent = userAgent;\n this.handlers = handlers || [];\n this.requestOptions = requestOptions;\n if (requestOptions) {\n if (requestOptions.ignoreSslError != null) {\n this._ignoreSslError = requestOptions.ignoreSslError;\n }\n this._socketTimeout = requestOptions.socketTimeout;\n if (requestOptions.allowRedirects != null) {\n this._allowRedirects = requestOptions.allowRedirects;\n }\n if (requestOptions.allowRedirectDowngrade != null) {\n this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;\n }\n if (requestOptions.maxRedirects != null) {\n this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);\n }\n if (requestOptions.keepAlive != null) {\n this._keepAlive = requestOptions.keepAlive;\n }\n if (requestOptions.allowRetries != null) {\n this._allowRetries = requestOptions.allowRetries;\n }\n if (requestOptions.maxRetries != null) {\n this._maxRetries = requestOptions.maxRetries;\n }\n }\n }\n options(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});\n });\n }\n get(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('GET', requestUrl, null, additionalHeaders || {});\n });\n }\n del(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('DELETE', requestUrl, null, additionalHeaders || {});\n });\n }\n post(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('POST', requestUrl, data, additionalHeaders || {});\n });\n }\n patch(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PATCH', requestUrl, data, additionalHeaders || {});\n });\n }\n put(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PUT', requestUrl, data, additionalHeaders || {});\n });\n }\n head(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('HEAD', requestUrl, null, additionalHeaders || {});\n });\n }\n sendStream(verb, requestUrl, stream, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request(verb, requestUrl, stream, additionalHeaders);\n });\n }\n /**\n * Gets a typed object from an endpoint\n * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise\n */\n getJson(requestUrl, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n const res = yield this.get(requestUrl, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n postJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.post(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n putJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.put(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n patchJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.patch(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n /**\n * Makes a raw http request.\n * All other methods such as get, post, patch, and request ultimately call this.\n * Prefer get, del, post and patch\n */\n request(verb, requestUrl, data, headers) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._disposed) {\n throw new Error('Client has already been disposed.');\n }\n const parsedUrl = new URL(requestUrl);\n let info = this._prepareRequest(verb, parsedUrl, headers);\n // Only perform retries on reads since writes may not be idempotent.\n const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)\n ? this._maxRetries + 1\n : 1;\n let numTries = 0;\n let response;\n do {\n response = yield this.requestRaw(info, data);\n // Check if it's an authentication challenge\n if (response &&\n response.message &&\n response.message.statusCode === HttpCodes.Unauthorized) {\n let authenticationHandler;\n for (const handler of this.handlers) {\n if (handler.canHandleAuthentication(response)) {\n authenticationHandler = handler;\n break;\n }\n }\n if (authenticationHandler) {\n return authenticationHandler.handleAuthentication(this, info, data);\n }\n else {\n // We have received an unauthorized response but have no handlers to handle it.\n // Let the response return to the caller.\n return response;\n }\n }\n let redirectsRemaining = this._maxRedirects;\n while (response.message.statusCode &&\n HttpRedirectCodes.includes(response.message.statusCode) &&\n this._allowRedirects &&\n redirectsRemaining > 0) {\n const redirectUrl = response.message.headers['location'];\n if (!redirectUrl) {\n // if there's no location to redirect to, we won't\n break;\n }\n const parsedRedirectUrl = new URL(redirectUrl);\n if (parsedUrl.protocol === 'https:' &&\n parsedUrl.protocol !== parsedRedirectUrl.protocol &&\n !this._allowRedirectDowngrade) {\n throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');\n }\n // we need to finish reading the response before reassigning response\n // which will leak the open socket.\n yield response.readBody();\n // strip authorization header if redirected to a different hostname\n if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {\n for (const header in headers) {\n // header names are case insensitive\n if (header.toLowerCase() === 'authorization') {\n delete headers[header];\n }\n }\n }\n // let's make the request with the new redirectUrl\n info = this._prepareRequest(verb, parsedRedirectUrl, headers);\n response = yield this.requestRaw(info, data);\n redirectsRemaining--;\n }\n if (!response.message.statusCode ||\n !HttpResponseRetryCodes.includes(response.message.statusCode)) {\n // If not a retry code, return immediately instead of retrying\n return response;\n }\n numTries += 1;\n if (numTries < maxTries) {\n yield response.readBody();\n yield this._performExponentialBackoff(numTries);\n }\n } while (numTries < maxTries);\n return response;\n });\n }\n /**\n * Needs to be called if keepAlive is set to true in request options.\n */\n dispose() {\n if (this._agent) {\n this._agent.destroy();\n }\n this._disposed = true;\n }\n /**\n * Raw request.\n * @param info\n * @param data\n */\n requestRaw(info, data) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n function callbackForResult(err, res) {\n if (err) {\n reject(err);\n }\n else if (!res) {\n // If `err` is not passed, then `res` must be passed.\n reject(new Error('Unknown error'));\n }\n else {\n resolve(res);\n }\n }\n this.requestRawWithCallback(info, data, callbackForResult);\n });\n });\n }\n /**\n * Raw request with callback.\n * @param info\n * @param data\n * @param onResult\n */\n requestRawWithCallback(info, data, onResult) {\n if (typeof data === 'string') {\n if (!info.options.headers) {\n info.options.headers = {};\n }\n info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');\n }\n let callbackCalled = false;\n function handleResult(err, res) {\n if (!callbackCalled) {\n callbackCalled = true;\n onResult(err, res);\n }\n }\n const req = info.httpModule.request(info.options, (msg) => {\n const res = new HttpClientResponse(msg);\n handleResult(undefined, res);\n });\n let socket;\n req.on('socket', sock => {\n socket = sock;\n });\n // If we ever get disconnected, we want the socket to timeout eventually\n req.setTimeout(this._socketTimeout || 3 * 60000, () => {\n if (socket) {\n socket.end();\n }\n handleResult(new Error(`Request timeout: ${info.options.path}`));\n });\n req.on('error', function (err) {\n // err has statusCode property\n // res should have headers\n handleResult(err);\n });\n if (data && typeof data === 'string') {\n req.write(data, 'utf8');\n }\n if (data && typeof data !== 'string') {\n data.on('close', function () {\n req.end();\n });\n data.pipe(req);\n }\n else {\n req.end();\n }\n }\n /**\n * Gets an http agent. This function is useful when you need an http agent that handles\n * routing through a proxy server - depending upon the url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\n getAgent(serverUrl) {\n const parsedUrl = new URL(serverUrl);\n return this._getAgent(parsedUrl);\n }\n getAgentDispatcher(serverUrl) {\n const parsedUrl = new URL(serverUrl);\n const proxyUrl = pm.getProxyUrl(parsedUrl);\n const useProxy = proxyUrl && proxyUrl.hostname;\n if (!useProxy) {\n return;\n }\n return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);\n }\n _prepareRequest(method, requestUrl, headers) {\n const info = {};\n info.parsedUrl = requestUrl;\n const usingSsl = info.parsedUrl.protocol === 'https:';\n info.httpModule = usingSsl ? https : http;\n const defaultPort = usingSsl ? 443 : 80;\n info.options = {};\n info.options.host = info.parsedUrl.hostname;\n info.options.port = info.parsedUrl.port\n ? parseInt(info.parsedUrl.port)\n : defaultPort;\n info.options.path =\n (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');\n info.options.method = method;\n info.options.headers = this._mergeHeaders(headers);\n if (this.userAgent != null) {\n info.options.headers['user-agent'] = this.userAgent;\n }\n info.options.agent = this._getAgent(info.parsedUrl);\n // gives handlers an opportunity to participate\n if (this.handlers) {\n for (const handler of this.handlers) {\n handler.prepareRequest(info.options);\n }\n }\n return info;\n }\n _mergeHeaders(headers) {\n if (this.requestOptions && this.requestOptions.headers) {\n return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));\n }\n return lowercaseKeys(headers || {});\n }\n _getExistingOrDefaultHeader(additionalHeaders, header, _default) {\n let clientHeader;\n if (this.requestOptions && this.requestOptions.headers) {\n clientHeader = lowercaseKeys(this.requestOptions.headers)[header];\n }\n return additionalHeaders[header] || clientHeader || _default;\n }\n _getAgent(parsedUrl) {\n let agent;\n const proxyUrl = pm.getProxyUrl(parsedUrl);\n const useProxy = proxyUrl && proxyUrl.hostname;\n if (this._keepAlive && useProxy) {\n agent = this._proxyAgent;\n }\n if (!useProxy) {\n agent = this._agent;\n }\n // if agent is already assigned use that agent.\n if (agent) {\n return agent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n let maxSockets = 100;\n if (this.requestOptions) {\n maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;\n }\n // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.\n if (proxyUrl && proxyUrl.hostname) {\n const agentOptions = {\n maxSockets,\n keepAlive: this._keepAlive,\n proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {\n proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`\n })), { host: proxyUrl.hostname, port: proxyUrl.port })\n };\n let tunnelAgent;\n const overHttps = proxyUrl.protocol === 'https:';\n if (usingSsl) {\n tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;\n }\n else {\n tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;\n }\n agent = tunnelAgent(agentOptions);\n this._proxyAgent = agent;\n }\n // if tunneling agent isn't assigned create a new agent\n if (!agent) {\n const options = { keepAlive: this._keepAlive, maxSockets };\n agent = usingSsl ? new https.Agent(options) : new http.Agent(options);\n this._agent = agent;\n }\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n agent.options = Object.assign(agent.options || {}, {\n rejectUnauthorized: false\n });\n }\n return agent;\n }\n _getProxyAgentDispatcher(parsedUrl, proxyUrl) {\n let proxyAgent;\n if (this._keepAlive) {\n proxyAgent = this._proxyAgentDispatcher;\n }\n // if agent is already assigned use that agent.\n if (proxyAgent) {\n return proxyAgent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {\n token: `${proxyUrl.username}:${proxyUrl.password}`\n })));\n this._proxyAgentDispatcher = proxyAgent;\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {\n rejectUnauthorized: false\n });\n }\n return proxyAgent;\n }\n _performExponentialBackoff(retryNumber) {\n return __awaiter(this, void 0, void 0, function* () {\n retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);\n const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);\n return new Promise(resolve => setTimeout(() => resolve(), ms));\n });\n }\n _processResponse(res, options) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n const statusCode = res.message.statusCode || 0;\n const response = {\n statusCode,\n result: null,\n headers: {}\n };\n // not found leads to null obj returned\n if (statusCode === HttpCodes.NotFound) {\n resolve(response);\n }\n // get the result from the body\n function dateTimeDeserializer(key, value) {\n if (typeof value === 'string') {\n const a = new Date(value);\n if (!isNaN(a.valueOf())) {\n return a;\n }\n }\n return value;\n }\n let obj;\n let contents;\n try {\n contents = yield res.readBody();\n if (contents && contents.length > 0) {\n if (options && options.deserializeDates) {\n obj = JSON.parse(contents, dateTimeDeserializer);\n }\n else {\n obj = JSON.parse(contents);\n }\n response.result = obj;\n }\n response.headers = res.message.headers;\n }\n catch (err) {\n // Invalid resource (contents not json); leaving result obj null\n }\n // note that 3xx redirects are handled by the http layer.\n if (statusCode > 299) {\n let msg;\n // if exception/error in body, attempt to get better error\n if (obj && obj.message) {\n msg = obj.message;\n }\n else if (contents && contents.length > 0) {\n // it may be the case that the exception is in the body message as string\n msg = contents;\n }\n else {\n msg = `Failed request: (${statusCode})`;\n }\n const err = new HttpClientError(msg, statusCode);\n err.result = response.result;\n reject(err);\n }\n else {\n resolve(response);\n }\n }));\n });\n }\n}\nexports.HttpClient = HttpClient;\nconst lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.checkBypass = exports.getProxyUrl = void 0;\nfunction getProxyUrl(reqUrl) {\n const usingSsl = reqUrl.protocol === 'https:';\n if (checkBypass(reqUrl)) {\n return undefined;\n }\n const proxyVar = (() => {\n if (usingSsl) {\n return process.env['https_proxy'] || process.env['HTTPS_PROXY'];\n }\n else {\n return process.env['http_proxy'] || process.env['HTTP_PROXY'];\n }\n })();\n if (proxyVar) {\n try {\n return new URL(proxyVar);\n }\n catch (_a) {\n if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))\n return new URL(`http://${proxyVar}`);\n }\n }\n else {\n return undefined;\n }\n}\nexports.getProxyUrl = getProxyUrl;\nfunction checkBypass(reqUrl) {\n if (!reqUrl.hostname) {\n return false;\n }\n const reqHost = reqUrl.hostname;\n if (isLoopbackAddress(reqHost)) {\n return true;\n }\n const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';\n if (!noProxy) {\n return false;\n }\n // Determine the request port\n let reqPort;\n if (reqUrl.port) {\n reqPort = Number(reqUrl.port);\n }\n else if (reqUrl.protocol === 'http:') {\n reqPort = 80;\n }\n else if (reqUrl.protocol === 'https:') {\n reqPort = 443;\n }\n // Format the request hostname and hostname with port\n const upperReqHosts = [reqUrl.hostname.toUpperCase()];\n if (typeof reqPort === 'number') {\n upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);\n }\n // Compare request host against noproxy\n for (const upperNoProxyItem of noProxy\n .split(',')\n .map(x => x.trim().toUpperCase())\n .filter(x => x)) {\n if (upperNoProxyItem === '*' ||\n upperReqHosts.some(x => x === upperNoProxyItem ||\n x.endsWith(`.${upperNoProxyItem}`) ||\n (upperNoProxyItem.startsWith('.') &&\n x.endsWith(`${upperNoProxyItem}`)))) {\n return true;\n }\n }\n return false;\n}\nexports.checkBypass = checkBypass;\nfunction isLoopbackAddress(host) {\n const hostLower = host.toLowerCase();\n return (hostLower === 'localhost' ||\n hostLower.startsWith('127.') ||\n hostLower.startsWith('[::1]') ||\n hostLower.startsWith('[0:0:0:0:0:0:0:1]'));\n}\n//# sourceMappingURL=proxy.js.map","'use strict';\n/**\n * @license\n * Copyright 2020 Balena Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * ------------------------------------------------------------------------\n *\n * Copyright 2018 Zeit, Inc.\n * Licensed under the MIT License. See file LICENSE.md for a full copy.\n *\n * ------------------------------------------------------------------------\n */\n\n/**\n * This module implements the [dockerignore\n * spec](https://docs.docker.com/engine/reference/builder/#dockerignore-file),\n * closely following Docker's (Moby) Golang implementation:\n * https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go\n * https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go\n * https://github.com/moby/moby/blob/v19.03.8/pkg/archive/archive.go#L825\n *\n * Something the spec is not clear about, but we discovered by reading source code\n * and testing against the \"docker build\" command, is the handling of backslashes and\n * forward slashes as path separators and escape characters in the .dockerignore file\n * across platforms including Windows, Linux and macOS:\n *\n * * On Linux and macOS, only forward slashes can be used as path separators in the\n * .dockerignore file, and the backslash works as an escape character.\n * * On Windows, both forward slashes and backslashes are allowed as path separators\n * in the .dockerignore file, and the backslash is not used as an escape character.\n *\n * This is consistent with how Windows works generally: both forward slashes and\n * backslashes are accepted as path separators by the cmd.exe Command Prompt or\n * PowerShell, and by library functions like the Golang filepath.Clean or the\n * Node.js path.normalize.\n *\n * Similarly, path strings provided to the IgnoreBase.ignores() and IgnoreBase.filter()\n * methods can use either forward slashes or backslashes as path separators on Windows,\n * but only forward slashes are accepted as path separators on Linux and macOS.\n */\n\nconst path = require('path');\n\nconst factory = options => new IgnoreBase(options); // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L538-L539\n// Fixes typescript module import\n\n\nfactory.default = factory;\nmodule.exports = factory;\n\nfunction make_array(subject) {\n return Array.isArray(subject) ? subject : [subject];\n}\n\nconst REGEX_TRAILING_SLASH = /(?<=.)\\/$/;\nconst REGEX_TRAILING_BACKSLASH = /(?<=.)\\\\$/;\nconst REGEX_TRAILING_PATH_SEP = path.sep === '\\\\' ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH;\nconst KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('dockerignore') : 'dockerignore'; // An implementation of Go's filepath.Clean\n// https://golang.org/pkg/path/filepath/#Clean\n// https://github.com/golang/go/blob/master/src/path/filepath/path.go\n// Note that, like Go, on Windows this function converts forward slashes\n// to backslashes.\n\nfunction cleanPath(file) {\n return path.normalize(file).replace(REGEX_TRAILING_PATH_SEP, '');\n} // Javascript port of Golang's filepath.ToSlash\n// https://golang.org/pkg/path/filepath/#ToSlash\n// https://github.com/golang/go/blob/master/src/path/filepath/path.go\n// Convert any OS-specific path separator to '/'. Backslash is converted\n// to forward slash on Windows, but not on Linux/macOS.\n// Note that both forward slashes and backslashes are valid path separators on\n// Windows. As a result, code such as `pattern.split(path.sep).join('/')` fails\n// on Windows when forward slashes are used as path separators.\n\n\nfunction toSlash(file) {\n if (path.sep === '/') {\n return file;\n }\n\n return file.replace(/\\\\/g, '/');\n} // Javascript port of Golang's filepath.FromSlash\n// https://github.com/golang/go/blob/master/src/path/filepath/path.go\n\n\nfunction fromSlash(file) {\n if (path.sep === '/') {\n return file;\n }\n\n return file.replace(/\\//g, path.sep);\n}\n\nclass IgnoreBase {\n constructor({\n // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L372\n ignorecase = true\n } = {}) {\n this._rules = [];\n this._ignorecase = ignorecase;\n this[KEY_IGNORE] = true;\n\n this._initCache();\n }\n\n _initCache() {\n this._cache = {};\n } // @param {Array.|string|Ignore} pattern\n\n\n add(pattern) {\n this._added = false;\n\n if (typeof pattern === 'string') {\n pattern = pattern.split(/\\r?\\n/g);\n }\n\n make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,\n // making the behavior changed.\n\n if (this._added) {\n this._initCache();\n }\n\n return this;\n } // legacy\n\n\n addPattern(pattern) {\n return this.add(pattern);\n }\n\n _addPattern(pattern) {\n // https://github.com/kaelzhang/node-ignore/issues/32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules);\n this._added = true;\n return;\n }\n\n if (this._checkPattern(pattern)) {\n const rule = this._createRule(pattern.trim());\n\n if (rule !== null) {\n this._added = true;\n\n this._rules.push(rule);\n }\n }\n }\n\n _checkPattern(pattern) {\n // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L34-L40\n return pattern && typeof pattern === 'string' && pattern.indexOf('#') !== 0 && pattern.trim() !== \"\";\n }\n\n filter(paths) {\n return make_array(paths).filter(path => this._filter(path));\n }\n\n createFilter() {\n return path => this._filter(path);\n }\n\n ignores(path) {\n return !this._filter(path);\n } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L41-L53\n // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L29-L55\n\n\n _createRule(pattern) {\n const origin = pattern;\n let negative = false; // > An optional prefix \"!\" which negates the pattern;\n // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L43-L46\n\n if (pattern[0] === '!') {\n negative = true;\n pattern = pattern.substring(1).trim();\n } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L47-L53\n\n\n if (pattern.length > 0) {\n pattern = cleanPath(pattern);\n pattern = toSlash(pattern);\n\n if (pattern.length > 1 && pattern[0] === '/') {\n pattern = pattern.slice(1);\n }\n } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L54-L55\n\n\n if (negative) {\n pattern = '!' + pattern;\n } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L30\n\n\n pattern = pattern.trim();\n\n if (pattern === \"\") {\n return null;\n } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L34\n // convert forward slashes to backslashes on Windows\n\n\n pattern = cleanPath(pattern); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L36-L42\n\n if (pattern[0] === '!') {\n if (pattern.length === 1) {\n return null;\n }\n\n negative = true;\n pattern = pattern.substring(1);\n } else {\n negative = false;\n }\n\n return {\n origin,\n pattern,\n // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L54\n dirs: pattern.split(path.sep),\n negative\n };\n } // @returns `Boolean` true if the `path` is NOT ignored\n\n\n _filter(path) {\n if (!path) {\n return false;\n }\n\n if (path in this._cache) {\n return this._cache[path];\n }\n\n return this._cache[path] = this._test(path);\n } // @returns {Boolean} true if a file is NOT ignored\n // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L62\n\n\n _test(file) {\n file = fromSlash(file); // equivalent to golang filepath.Dir() https://golang.org/src/path/filepath/path.go\n\n const parentPath = cleanPath(path.dirname(file));\n const parentPathDirs = parentPath.split(path.sep);\n let matched = false;\n\n this._rules.forEach(rule => {\n let match = this._match(file, rule); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L80\n\n\n if (!match && parentPath !== \".\") {\n // Check to see if the pattern matches one of our parent dirs.\n if (rule.dirs.includes('**')) {\n // Ah shucks! We have to test every possible parent path that has \n // a number of dirs _n_ where \n // `rule.dirs.filter(doubleStar).length <= _n_ <= parentPathDirs.length`\n // since the ** can imply any number of directories including 0\n for (let i = rule.dirs.filter(x => x !== '**').length; i <= parentPathDirs.length; i++) {\n match = match || this._match(parentPathDirs.slice(0, i).join(path.sep), rule);\n }\n } else if (rule.dirs.length <= parentPathDirs.length) {\n // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L83\n match = this._match(parentPathDirs.slice(0, rule.dirs.length).join(path.sep), rule);\n }\n }\n\n if (match) {\n matched = !rule.negative;\n }\n });\n\n return !matched;\n } // @returns {Boolean} true if a file is matched by a rule\n\n\n _match(file, rule) {\n return this._compile(rule).regexp.test(file);\n } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L139\n\n\n _compile(rule) {\n if (rule.regexp) {\n return rule;\n }\n\n let regStr = '^'; // Go through the pattern and convert it to a regexp.\n\n let escapedSlash = path.sep === '\\\\' ? '\\\\\\\\' : path.sep;\n\n for (let i = 0; i < rule.pattern.length; i++) {\n const ch = rule.pattern[i];\n\n if (ch === '*') {\n if (rule.pattern[i + 1] === '*') {\n // is some flavor of \"**\"\n i++; // Treat **/ as ** so eat the \"/\"\n\n if (rule.pattern[i + 1] === path.sep) {\n i++;\n }\n\n if (rule.pattern[i + 1] === undefined) {\n // is \"**EOF\" - to align with .gitignore just accept all\n regStr += \".*\";\n } else {\n // is \"**\"\n // Note that this allows for any # of /'s (even 0) because\n // the .* will eat everything, even /'s\n regStr += `(.*${escapedSlash})?`;\n }\n } else {\n // is \"*\" so map it to anything but \"/\"\n regStr += `[^${escapedSlash}]*`;\n }\n } else if (ch === '?') {\n // \"?\" is any char except \"/\"\n regStr += `[^${escapedSlash}]`;\n } else if (ch === '.' || ch === '$') {\n // Escape some regexp special chars that have no meaning\n // in golang's filepath.Match\n regStr += `\\\\${ch}`;\n } else if (ch === '\\\\') {\n // escape next char. Note that a trailing \\ in the pattern\n // will be left alone (but need to escape it)\n if (path.sep === '\\\\') {\n // On windows map \"\\\" to \"\\\\\", meaning an escaped backslash,\n // and then just continue because filepath.Match on\n // Windows doesn't allow escaping at all\n regStr += escapedSlash;\n continue;\n }\n\n if (rule.pattern[i + 1] !== undefined) {\n regStr += '\\\\' + rule.pattern[i + 1];\n i++;\n } else {\n regStr += '\\\\';\n }\n } else {\n regStr += ch;\n }\n }\n\n regStr += \"$\";\n rule.regexp = new RegExp(regStr, this._ignorecase ? 'i' : '');\n return rule;\n }\n\n}\n","'use strict'\n\nconst WritableStream = require('node:stream').Writable\nconst inherits = require('node:util').inherits\n\nconst StreamSearch = require('../../streamsearch/sbmh')\n\nconst PartStream = require('./PartStream')\nconst HeaderParser = require('./HeaderParser')\n\nconst DASH = 45\nconst B_ONEDASH = Buffer.from('-')\nconst B_CRLF = Buffer.from('\\r\\n')\nconst EMPTY_FN = function () {}\n\nfunction Dicer (cfg) {\n if (!(this instanceof Dicer)) { return new Dicer(cfg) }\n WritableStream.call(this, cfg)\n\n if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }\n\n if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }\n\n this._headerFirst = cfg.headerFirst\n\n this._dashes = 0\n this._parts = 0\n this._finished = false\n this._realFinish = false\n this._isPreamble = true\n this._justMatched = false\n this._firstWrite = true\n this._inHeader = true\n this._part = undefined\n this._cb = undefined\n this._ignoreData = false\n this._partOpts = { highWaterMark: cfg.partHwm }\n this._pause = false\n\n const self = this\n this._hparser = new HeaderParser(cfg)\n this._hparser.on('header', function (header) {\n self._inHeader = false\n self._part.emit('header', header)\n })\n}\ninherits(Dicer, WritableStream)\n\nDicer.prototype.emit = function (ev) {\n if (ev === 'finish' && !this._realFinish) {\n if (!this._finished) {\n const self = this\n process.nextTick(function () {\n self.emit('error', new Error('Unexpected end of multipart data'))\n if (self._part && !self._ignoreData) {\n const type = (self._isPreamble ? 'Preamble' : 'Part')\n self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))\n self._part.push(null)\n process.nextTick(function () {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n })\n return\n }\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n })\n }\n } else { WritableStream.prototype.emit.apply(this, arguments) }\n}\n\nDicer.prototype._write = function (data, encoding, cb) {\n // ignore unexpected data (e.g. extra trailer data after finished)\n if (!this._hparser && !this._bparser) { return cb() }\n\n if (this._headerFirst && this._isPreamble) {\n if (!this._part) {\n this._part = new PartStream(this._partOpts)\n if (this._events.preamble) { this.emit('preamble', this._part) } else { this._ignore() }\n }\n const r = this._hparser.push(data)\n if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }\n }\n\n // allows for \"easier\" testing\n if (this._firstWrite) {\n this._bparser.push(B_CRLF)\n this._firstWrite = false\n }\n\n this._bparser.push(data)\n\n if (this._pause) { this._cb = cb } else { cb() }\n}\n\nDicer.prototype.reset = function () {\n this._part = undefined\n this._bparser = undefined\n this._hparser = undefined\n}\n\nDicer.prototype.setBoundary = function (boundary) {\n const self = this\n this._bparser = new StreamSearch('\\r\\n--' + boundary)\n this._bparser.on('info', function (isMatch, data, start, end) {\n self._oninfo(isMatch, data, start, end)\n })\n}\n\nDicer.prototype._ignore = function () {\n if (this._part && !this._ignoreData) {\n this._ignoreData = true\n this._part.on('error', EMPTY_FN)\n // we must perform some kind of read on the stream even though we are\n // ignoring the data, otherwise node's Readable stream will not emit 'end'\n // after pushing null to the stream\n this._part.resume()\n }\n}\n\nDicer.prototype._oninfo = function (isMatch, data, start, end) {\n let buf; const self = this; let i = 0; let r; let shouldWriteMore = true\n\n if (!this._part && this._justMatched && data) {\n while (this._dashes < 2 && (start + i) < end) {\n if (data[start + i] === DASH) {\n ++i\n ++this._dashes\n } else {\n if (this._dashes) { buf = B_ONEDASH }\n this._dashes = 0\n break\n }\n }\n if (this._dashes === 2) {\n if ((start + i) < end && this._events.trailer) { this.emit('trailer', data.slice(start + i, end)) }\n this.reset()\n this._finished = true\n // no more parts will be added\n if (self._parts === 0) {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n }\n }\n if (this._dashes) { return }\n }\n if (this._justMatched) { this._justMatched = false }\n if (!this._part) {\n this._part = new PartStream(this._partOpts)\n this._part._read = function (n) {\n self._unpause()\n }\n 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() }\n if (!this._isPreamble) { this._inHeader = true }\n }\n if (data && start < end && !this._ignoreData) {\n if (this._isPreamble || !this._inHeader) {\n if (buf) { shouldWriteMore = this._part.push(buf) }\n shouldWriteMore = this._part.push(data.slice(start, end))\n if (!shouldWriteMore) { this._pause = true }\n } else if (!this._isPreamble && this._inHeader) {\n if (buf) { this._hparser.push(buf) }\n r = this._hparser.push(data.slice(start, end))\n if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }\n }\n }\n if (isMatch) {\n this._hparser.reset()\n if (this._isPreamble) { this._isPreamble = false } else {\n if (start !== end) {\n ++this._parts\n this._part.on('end', function () {\n if (--self._parts === 0) {\n if (self._finished) {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n } else {\n self._unpause()\n }\n }\n })\n }\n }\n this._part.push(null)\n this._part = undefined\n this._ignoreData = false\n this._justMatched = true\n this._dashes = 0\n }\n}\n\nDicer.prototype._unpause = function () {\n if (!this._pause) { return }\n\n this._pause = false\n if (this._cb) {\n const cb = this._cb\n this._cb = undefined\n cb()\n }\n}\n\nmodule.exports = Dicer\n","'use strict'\n\nconst EventEmitter = require('node:events').EventEmitter\nconst inherits = require('node:util').inherits\nconst getLimit = require('../../../lib/utils/getLimit')\n\nconst StreamSearch = require('../../streamsearch/sbmh')\n\nconst B_DCRLF = Buffer.from('\\r\\n\\r\\n')\nconst RE_CRLF = /\\r\\n/g\nconst RE_HDR = /^([^:]+):[ \\t]?([\\x00-\\xFF]+)?$/ // eslint-disable-line no-control-regex\n\nfunction HeaderParser (cfg) {\n EventEmitter.call(this)\n\n cfg = cfg || {}\n const self = this\n this.nread = 0\n this.maxed = false\n this.npairs = 0\n this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)\n this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)\n this.buffer = ''\n this.header = {}\n this.finished = false\n this.ss = new StreamSearch(B_DCRLF)\n this.ss.on('info', function (isMatch, data, start, end) {\n if (data && !self.maxed) {\n if (self.nread + end - start >= self.maxHeaderSize) {\n end = self.maxHeaderSize - self.nread + start\n self.nread = self.maxHeaderSize\n self.maxed = true\n } else { self.nread += (end - start) }\n\n self.buffer += data.toString('binary', start, end)\n }\n if (isMatch) { self._finish() }\n })\n}\ninherits(HeaderParser, EventEmitter)\n\nHeaderParser.prototype.push = function (data) {\n const r = this.ss.push(data)\n if (this.finished) { return r }\n}\n\nHeaderParser.prototype.reset = function () {\n this.finished = false\n this.buffer = ''\n this.header = {}\n this.ss.reset()\n}\n\nHeaderParser.prototype._finish = function () {\n if (this.buffer) { this._parseHeader() }\n this.ss.matches = this.ss.maxMatches\n const header = this.header\n this.header = {}\n this.buffer = ''\n this.finished = true\n this.nread = this.npairs = 0\n this.maxed = false\n this.emit('header', header)\n}\n\nHeaderParser.prototype._parseHeader = function () {\n if (this.npairs === this.maxHeaderPairs) { return }\n\n const lines = this.buffer.split(RE_CRLF)\n const len = lines.length\n let m, h\n\n for (var i = 0; i < len; ++i) { // eslint-disable-line no-var\n if (lines[i].length === 0) { continue }\n if (lines[i][0] === '\\t' || lines[i][0] === ' ') {\n // folded header content\n // RFC2822 says to just remove the CRLF and not the whitespace following\n // it, so we follow the RFC and include the leading whitespace ...\n if (h) {\n this.header[h][this.header[h].length - 1] += lines[i]\n continue\n }\n }\n\n const posColon = lines[i].indexOf(':')\n if (\n posColon === -1 ||\n posColon === 0\n ) {\n return\n }\n m = RE_HDR.exec(lines[i])\n h = m[1].toLowerCase()\n this.header[h] = this.header[h] || []\n this.header[h].push((m[2] || ''))\n if (++this.npairs === this.maxHeaderPairs) { break }\n }\n}\n\nmodule.exports = HeaderParser\n","'use strict'\n\nconst inherits = require('node:util').inherits\nconst ReadableStream = require('node:stream').Readable\n\nfunction PartStream (opts) {\n ReadableStream.call(this, opts)\n}\ninherits(PartStream, ReadableStream)\n\nPartStream.prototype._read = function (n) {}\n\nmodule.exports = PartStream\n","'use strict'\n\n/**\n * Copyright Brian White. All rights reserved.\n *\n * @see https://github.com/mscdex/streamsearch\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation\n * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool\n */\nconst EventEmitter = require('node:events').EventEmitter\nconst inherits = require('node:util').inherits\n\nfunction SBMH (needle) {\n if (typeof needle === 'string') {\n needle = Buffer.from(needle)\n }\n\n if (!Buffer.isBuffer(needle)) {\n throw new TypeError('The needle has to be a String or a Buffer.')\n }\n\n const needleLength = needle.length\n\n if (needleLength === 0) {\n throw new Error('The needle cannot be an empty String/Buffer.')\n }\n\n if (needleLength > 256) {\n throw new Error('The needle cannot have a length bigger than 256.')\n }\n\n this.maxMatches = Infinity\n this.matches = 0\n\n this._occ = new Array(256)\n .fill(needleLength) // Initialize occurrence table.\n this._lookbehind_size = 0\n this._needle = needle\n this._bufpos = 0\n\n this._lookbehind = Buffer.alloc(needleLength)\n\n // Populate occurrence table with analysis of the needle,\n // ignoring last letter.\n for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var\n this._occ[needle[i]] = needleLength - 1 - i\n }\n}\ninherits(SBMH, EventEmitter)\n\nSBMH.prototype.reset = function () {\n this._lookbehind_size = 0\n this.matches = 0\n this._bufpos = 0\n}\n\nSBMH.prototype.push = function (chunk, pos) {\n if (!Buffer.isBuffer(chunk)) {\n chunk = Buffer.from(chunk, 'binary')\n }\n const chlen = chunk.length\n this._bufpos = pos || 0\n let r\n while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }\n return r\n}\n\nSBMH.prototype._sbmh_feed = function (data) {\n const len = data.length\n const needle = this._needle\n const needleLength = needle.length\n const lastNeedleChar = needle[needleLength - 1]\n\n // Positive: points to a position in `data`\n // pos == 3 points to data[3]\n // Negative: points to a position in the lookbehind buffer\n // pos == -2 points to lookbehind[lookbehind_size - 2]\n let pos = -this._lookbehind_size\n let ch\n\n if (pos < 0) {\n // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool\n // search with character lookup code that considers both the\n // lookbehind buffer and the current round's haystack data.\n //\n // Loop until\n // there is a match.\n // or until\n // we've moved past the position that requires the\n // lookbehind buffer. In this case we switch to the\n // optimized loop.\n // or until\n // the character to look at lies outside the haystack.\n while (pos < 0 && pos <= len - needleLength) {\n ch = this._sbmh_lookup_char(data, pos + needleLength - 1)\n\n if (\n ch === lastNeedleChar &&\n this._sbmh_memcmp(data, pos, needleLength - 1)\n ) {\n this._lookbehind_size = 0\n ++this.matches\n this.emit('info', true)\n\n return (this._bufpos = pos + needleLength)\n }\n pos += this._occ[ch]\n }\n\n // No match.\n\n if (pos < 0) {\n // There's too few data for Boyer-Moore-Horspool to run,\n // so let's use a different algorithm to skip as much as\n // we can.\n // Forward pos until\n // the trailing part of lookbehind + data\n // looks like the beginning of the needle\n // or until\n // pos == 0\n while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }\n }\n\n if (pos >= 0) {\n // Discard lookbehind buffer.\n this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)\n this._lookbehind_size = 0\n } else {\n // Cut off part of the lookbehind buffer that has\n // been processed and append the entire haystack\n // into it.\n const bytesToCutOff = this._lookbehind_size + pos\n if (bytesToCutOff > 0) {\n // The cut off data is guaranteed not to contain the needle.\n this.emit('info', false, this._lookbehind, 0, bytesToCutOff)\n }\n\n this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,\n this._lookbehind_size - bytesToCutOff)\n this._lookbehind_size -= bytesToCutOff\n\n data.copy(this._lookbehind, this._lookbehind_size)\n this._lookbehind_size += len\n\n this._bufpos = len\n return len\n }\n }\n\n pos += (pos >= 0) * this._bufpos\n\n // Lookbehind buffer is now empty. We only need to check if the\n // needle is in the haystack.\n if (data.indexOf(needle, pos) !== -1) {\n pos = data.indexOf(needle, pos)\n ++this.matches\n if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }\n\n return (this._bufpos = pos + needleLength)\n } else {\n pos = len - needleLength\n }\n\n // There was no match. If there's trailing haystack data that we cannot\n // match yet using the Boyer-Moore-Horspool algorithm (because the trailing\n // data is less than the needle size) then match using a modified\n // algorithm that starts matching from the beginning instead of the end.\n // Whatever trailing data is left after running this algorithm is added to\n // the lookbehind buffer.\n while (\n pos < len &&\n (\n data[pos] !== needle[0] ||\n (\n (Buffer.compare(\n data.subarray(pos, pos + len - pos),\n needle.subarray(0, len - pos)\n ) !== 0)\n )\n )\n ) {\n ++pos\n }\n if (pos < len) {\n data.copy(this._lookbehind, 0, pos, pos + (len - pos))\n this._lookbehind_size = len - pos\n }\n\n // Everything until pos is guaranteed not to contain needle data.\n if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }\n\n this._bufpos = len\n return len\n}\n\nSBMH.prototype._sbmh_lookup_char = function (data, pos) {\n return (pos < 0)\n ? this._lookbehind[this._lookbehind_size + pos]\n : data[pos]\n}\n\nSBMH.prototype._sbmh_memcmp = function (data, pos, len) {\n for (var i = 0; i < len; ++i) { // eslint-disable-line no-var\n if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }\n }\n return true\n}\n\nmodule.exports = SBMH\n","'use strict'\n\nconst WritableStream = require('node:stream').Writable\nconst { inherits } = require('node:util')\nconst Dicer = require('../deps/dicer/lib/Dicer')\n\nconst MultipartParser = require('./types/multipart')\nconst UrlencodedParser = require('./types/urlencoded')\nconst parseParams = require('./utils/parseParams')\n\nfunction Busboy (opts) {\n if (!(this instanceof Busboy)) { return new Busboy(opts) }\n\n if (typeof opts !== 'object') {\n throw new TypeError('Busboy expected an options-Object.')\n }\n if (typeof opts.headers !== 'object') {\n throw new TypeError('Busboy expected an options-Object with headers-attribute.')\n }\n if (typeof opts.headers['content-type'] !== 'string') {\n throw new TypeError('Missing Content-Type-header.')\n }\n\n const {\n headers,\n ...streamOptions\n } = opts\n\n this.opts = {\n autoDestroy: false,\n ...streamOptions\n }\n WritableStream.call(this, this.opts)\n\n this._done = false\n this._parser = this.getParserByHeaders(headers)\n this._finished = false\n}\ninherits(Busboy, WritableStream)\n\nBusboy.prototype.emit = function (ev) {\n if (ev === 'finish') {\n if (!this._done) {\n this._parser?.end()\n return\n } else if (this._finished) {\n return\n }\n this._finished = true\n }\n WritableStream.prototype.emit.apply(this, arguments)\n}\n\nBusboy.prototype.getParserByHeaders = function (headers) {\n const parsed = parseParams(headers['content-type'])\n\n const cfg = {\n defCharset: this.opts.defCharset,\n fileHwm: this.opts.fileHwm,\n headers,\n highWaterMark: this.opts.highWaterMark,\n isPartAFile: this.opts.isPartAFile,\n limits: this.opts.limits,\n parsedConType: parsed,\n preservePath: this.opts.preservePath\n }\n\n if (MultipartParser.detect.test(parsed[0])) {\n return new MultipartParser(this, cfg)\n }\n if (UrlencodedParser.detect.test(parsed[0])) {\n return new UrlencodedParser(this, cfg)\n }\n throw new Error('Unsupported Content-Type.')\n}\n\nBusboy.prototype._write = function (chunk, encoding, cb) {\n this._parser.write(chunk, cb)\n}\n\nmodule.exports = Busboy\nmodule.exports.default = Busboy\nmodule.exports.Busboy = Busboy\n\nmodule.exports.Dicer = Dicer\n","'use strict'\n\n// TODO:\n// * support 1 nested multipart level\n// (see second multipart example here:\n// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)\n// * support limits.fieldNameSize\n// -- this will require modifications to utils.parseParams\n\nconst { Readable } = require('node:stream')\nconst { inherits } = require('node:util')\n\nconst Dicer = require('../../deps/dicer/lib/Dicer')\n\nconst parseParams = require('../utils/parseParams')\nconst decodeText = require('../utils/decodeText')\nconst basename = require('../utils/basename')\nconst getLimit = require('../utils/getLimit')\n\nconst RE_BOUNDARY = /^boundary$/i\nconst RE_FIELD = /^form-data$/i\nconst RE_CHARSET = /^charset$/i\nconst RE_FILENAME = /^filename$/i\nconst RE_NAME = /^name$/i\n\nMultipart.detect = /^multipart\\/form-data/i\nfunction Multipart (boy, cfg) {\n let i\n let len\n const self = this\n let boundary\n const limits = cfg.limits\n const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))\n const parsedConType = cfg.parsedConType || []\n const defCharset = cfg.defCharset || 'utf8'\n const preservePath = cfg.preservePath\n const fileOpts = { highWaterMark: cfg.fileHwm }\n\n for (i = 0, len = parsedConType.length; i < len; ++i) {\n if (Array.isArray(parsedConType[i]) &&\n RE_BOUNDARY.test(parsedConType[i][0])) {\n boundary = parsedConType[i][1]\n break\n }\n }\n\n function checkFinished () {\n if (nends === 0 && finished && !boy._done) {\n finished = false\n self.end()\n }\n }\n\n if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }\n\n const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)\n const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)\n const filesLimit = getLimit(limits, 'files', Infinity)\n const fieldsLimit = getLimit(limits, 'fields', Infinity)\n const partsLimit = getLimit(limits, 'parts', Infinity)\n const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)\n const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)\n\n let nfiles = 0\n let nfields = 0\n let nends = 0\n let curFile\n let curField\n let finished = false\n\n this._needDrain = false\n this._pause = false\n this._cb = undefined\n this._nparts = 0\n this._boy = boy\n\n const parserCfg = {\n boundary,\n maxHeaderPairs: headerPairsLimit,\n maxHeaderSize: headerSizeLimit,\n partHwm: fileOpts.highWaterMark,\n highWaterMark: cfg.highWaterMark\n }\n\n this.parser = new Dicer(parserCfg)\n this.parser.on('drain', function () {\n self._needDrain = false\n if (self._cb && !self._pause) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n }).on('part', function onPart (part) {\n if (++self._nparts > partsLimit) {\n self.parser.removeListener('part', onPart)\n self.parser.on('part', skipPart)\n boy.hitPartsLimit = true\n boy.emit('partsLimit')\n return skipPart(part)\n }\n\n // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let\n // us emit 'end' early since we know the part has ended if we are already\n // seeing the next part\n if (curField) {\n const field = curField\n field.emit('end')\n field.removeAllListeners('end')\n }\n\n part.on('header', function (header) {\n let contype\n let fieldname\n let parsed\n let charset\n let encoding\n let filename\n let nsize = 0\n\n if (header['content-type']) {\n parsed = parseParams(header['content-type'][0])\n if (parsed[0]) {\n contype = parsed[0].toLowerCase()\n for (i = 0, len = parsed.length; i < len; ++i) {\n if (RE_CHARSET.test(parsed[i][0])) {\n charset = parsed[i][1].toLowerCase()\n break\n }\n }\n }\n }\n\n if (contype === undefined) { contype = 'text/plain' }\n if (charset === undefined) { charset = defCharset }\n\n if (header['content-disposition']) {\n parsed = parseParams(header['content-disposition'][0])\n if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }\n for (i = 0, len = parsed.length; i < len; ++i) {\n if (RE_NAME.test(parsed[i][0])) {\n fieldname = parsed[i][1]\n } else if (RE_FILENAME.test(parsed[i][0])) {\n filename = parsed[i][1]\n if (!preservePath) { filename = basename(filename) }\n }\n }\n } else { return skipPart(part) }\n\n if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }\n\n let onData,\n onEnd\n\n if (isPartAFile(fieldname, contype, filename)) {\n // file/binary field\n if (nfiles === filesLimit) {\n if (!boy.hitFilesLimit) {\n boy.hitFilesLimit = true\n boy.emit('filesLimit')\n }\n return skipPart(part)\n }\n\n ++nfiles\n\n if (!boy._events.file) {\n self.parser._ignore()\n return\n }\n\n ++nends\n const file = new FileStream(fileOpts)\n curFile = file\n file.on('end', function () {\n --nends\n self._pause = false\n checkFinished()\n if (self._cb && !self._needDrain) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n })\n file._read = function (n) {\n if (!self._pause) { return }\n self._pause = false\n if (self._cb && !self._needDrain) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n }\n boy.emit('file', fieldname, file, filename, encoding, contype)\n\n onData = function (data) {\n if ((nsize += data.length) > fileSizeLimit) {\n const extralen = fileSizeLimit - nsize + data.length\n if (extralen > 0) { file.push(data.slice(0, extralen)) }\n file.truncated = true\n file.bytesRead = fileSizeLimit\n part.removeAllListeners('data')\n file.emit('limit')\n return\n } else if (!file.push(data)) { self._pause = true }\n\n file.bytesRead = nsize\n }\n\n onEnd = function () {\n curFile = undefined\n file.push(null)\n }\n } else {\n // non-file field\n if (nfields === fieldsLimit) {\n if (!boy.hitFieldsLimit) {\n boy.hitFieldsLimit = true\n boy.emit('fieldsLimit')\n }\n return skipPart(part)\n }\n\n ++nfields\n ++nends\n let buffer = ''\n let truncated = false\n curField = part\n\n onData = function (data) {\n if ((nsize += data.length) > fieldSizeLimit) {\n const extralen = (fieldSizeLimit - (nsize - data.length))\n buffer += data.toString('binary', 0, extralen)\n truncated = true\n part.removeAllListeners('data')\n } else { buffer += data.toString('binary') }\n }\n\n onEnd = function () {\n curField = undefined\n if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }\n boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)\n --nends\n checkFinished()\n }\n }\n\n /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become\n broken. Streams2/streams3 is a huge black box of confusion, but\n somehow overriding the sync state seems to fix things again (and still\n seems to work for previous node versions).\n */\n part._readableState.sync = false\n\n part.on('data', onData)\n part.on('end', onEnd)\n }).on('error', function (err) {\n if (curFile) { curFile.emit('error', err) }\n })\n }).on('error', function (err) {\n boy.emit('error', err)\n }).on('finish', function () {\n finished = true\n checkFinished()\n })\n}\n\nMultipart.prototype.write = function (chunk, cb) {\n const r = this.parser.write(chunk)\n if (r && !this._pause) {\n cb()\n } else {\n this._needDrain = !r\n this._cb = cb\n }\n}\n\nMultipart.prototype.end = function () {\n const self = this\n\n if (self.parser.writable) {\n self.parser.end()\n } else if (!self._boy._done) {\n process.nextTick(function () {\n self._boy._done = true\n self._boy.emit('finish')\n })\n }\n}\n\nfunction skipPart (part) {\n part.resume()\n}\n\nfunction FileStream (opts) {\n Readable.call(this, opts)\n\n this.bytesRead = 0\n\n this.truncated = false\n}\n\ninherits(FileStream, Readable)\n\nFileStream.prototype._read = function (n) {}\n\nmodule.exports = Multipart\n","'use strict'\n\nconst Decoder = require('../utils/Decoder')\nconst decodeText = require('../utils/decodeText')\nconst getLimit = require('../utils/getLimit')\n\nconst RE_CHARSET = /^charset$/i\n\nUrlEncoded.detect = /^application\\/x-www-form-urlencoded/i\nfunction UrlEncoded (boy, cfg) {\n const limits = cfg.limits\n const parsedConType = cfg.parsedConType\n this.boy = boy\n\n this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)\n this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)\n this.fieldsLimit = getLimit(limits, 'fields', Infinity)\n\n let charset\n for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var\n if (Array.isArray(parsedConType[i]) &&\n RE_CHARSET.test(parsedConType[i][0])) {\n charset = parsedConType[i][1].toLowerCase()\n break\n }\n }\n\n if (charset === undefined) { charset = cfg.defCharset || 'utf8' }\n\n this.decoder = new Decoder()\n this.charset = charset\n this._fields = 0\n this._state = 'key'\n this._checkingBytes = true\n this._bytesKey = 0\n this._bytesVal = 0\n this._key = ''\n this._val = ''\n this._keyTrunc = false\n this._valTrunc = false\n this._hitLimit = false\n}\n\nUrlEncoded.prototype.write = function (data, cb) {\n if (this._fields === this.fieldsLimit) {\n if (!this.boy.hitFieldsLimit) {\n this.boy.hitFieldsLimit = true\n this.boy.emit('fieldsLimit')\n }\n return cb()\n }\n\n let idxeq; let idxamp; let i; let p = 0; const len = data.length\n\n while (p < len) {\n if (this._state === 'key') {\n idxeq = idxamp = undefined\n for (i = p; i < len; ++i) {\n if (!this._checkingBytes) { ++p }\n if (data[i] === 0x3D/* = */) {\n idxeq = i\n break\n } else if (data[i] === 0x26/* & */) {\n idxamp = i\n break\n }\n if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {\n this._hitLimit = true\n break\n } else if (this._checkingBytes) { ++this._bytesKey }\n }\n\n if (idxeq !== undefined) {\n // key with assignment\n if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }\n this._state = 'val'\n\n this._hitLimit = false\n this._checkingBytes = true\n this._val = ''\n this._bytesVal = 0\n this._valTrunc = false\n this.decoder.reset()\n\n p = idxeq + 1\n } else if (idxamp !== undefined) {\n // key with no assignment\n ++this._fields\n let key; const keyTrunc = this._keyTrunc\n if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }\n\n this._hitLimit = false\n this._checkingBytes = true\n this._key = ''\n this._bytesKey = 0\n this._keyTrunc = false\n this.decoder.reset()\n\n if (key.length) {\n this.boy.emit('field', decodeText(key, 'binary', this.charset),\n '',\n keyTrunc,\n false)\n }\n\n p = idxamp + 1\n if (this._fields === this.fieldsLimit) { return cb() }\n } else if (this._hitLimit) {\n // we may not have hit the actual limit if there are encoded bytes...\n if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }\n p = i\n if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {\n // yep, we actually did hit the limit\n this._checkingBytes = false\n this._keyTrunc = true\n }\n } else {\n if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }\n p = len\n }\n } else {\n idxamp = undefined\n for (i = p; i < len; ++i) {\n if (!this._checkingBytes) { ++p }\n if (data[i] === 0x26/* & */) {\n idxamp = i\n break\n }\n if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {\n this._hitLimit = true\n break\n } else if (this._checkingBytes) { ++this._bytesVal }\n }\n\n if (idxamp !== undefined) {\n ++this._fields\n if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n decodeText(this._val, 'binary', this.charset),\n this._keyTrunc,\n this._valTrunc)\n this._state = 'key'\n\n this._hitLimit = false\n this._checkingBytes = true\n this._key = ''\n this._bytesKey = 0\n this._keyTrunc = false\n this.decoder.reset()\n\n p = idxamp + 1\n if (this._fields === this.fieldsLimit) { return cb() }\n } else if (this._hitLimit) {\n // we may not have hit the actual limit if there are encoded bytes...\n if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }\n p = i\n if ((this._val === '' && this.fieldSizeLimit === 0) ||\n (this._bytesVal = this._val.length) === this.fieldSizeLimit) {\n // yep, we actually did hit the limit\n this._checkingBytes = false\n this._valTrunc = true\n }\n } else {\n if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }\n p = len\n }\n }\n }\n cb()\n}\n\nUrlEncoded.prototype.end = function () {\n if (this.boy._done) { return }\n\n if (this._state === 'key' && this._key.length > 0) {\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n '',\n this._keyTrunc,\n false)\n } else if (this._state === 'val') {\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n decodeText(this._val, 'binary', this.charset),\n this._keyTrunc,\n this._valTrunc)\n }\n this.boy._done = true\n this.boy.emit('finish')\n}\n\nmodule.exports = UrlEncoded\n","'use strict'\n\nconst RE_PLUS = /\\+/g\n\nconst HEX = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n]\n\nfunction Decoder () {\n this.buffer = undefined\n}\nDecoder.prototype.write = function (str) {\n // Replace '+' with ' ' before decoding\n str = str.replace(RE_PLUS, ' ')\n let res = ''\n let i = 0; let p = 0; const len = str.length\n for (; i < len; ++i) {\n if (this.buffer !== undefined) {\n if (!HEX[str.charCodeAt(i)]) {\n res += '%' + this.buffer\n this.buffer = undefined\n --i // retry character\n } else {\n this.buffer += str[i]\n ++p\n if (this.buffer.length === 2) {\n res += String.fromCharCode(parseInt(this.buffer, 16))\n this.buffer = undefined\n }\n }\n } else if (str[i] === '%') {\n if (i > p) {\n res += str.substring(p, i)\n p = i\n }\n this.buffer = ''\n ++p\n }\n }\n if (p < len && this.buffer === undefined) { res += str.substring(p) }\n return res\n}\nDecoder.prototype.reset = function () {\n this.buffer = undefined\n}\n\nmodule.exports = Decoder\n","'use strict'\n\nmodule.exports = function basename (path) {\n if (typeof path !== 'string') { return '' }\n for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var\n switch (path.charCodeAt(i)) {\n case 0x2F: // '/'\n case 0x5C: // '\\'\n path = path.slice(i + 1)\n return (path === '..' || path === '.' ? '' : path)\n }\n }\n return (path === '..' || path === '.' ? '' : path)\n}\n","'use strict'\n\n// Node has always utf-8\nconst utf8Decoder = new TextDecoder('utf-8')\nconst textDecoders = new Map([\n ['utf-8', utf8Decoder],\n ['utf8', utf8Decoder]\n])\n\nfunction decodeText (text, textEncoding, destEncoding) {\n if (text) {\n if (textDecoders.has(destEncoding)) {\n try {\n return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))\n } catch (e) { }\n } else {\n try {\n textDecoders.set(destEncoding, new TextDecoder(destEncoding))\n return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))\n } catch (e) { }\n }\n }\n return text\n}\n\nmodule.exports = decodeText\n","'use strict'\n\nmodule.exports = function getLimit (limits, name, defaultLimit) {\n if (\n !limits ||\n limits[name] === undefined ||\n limits[name] === null\n ) { return defaultLimit }\n\n if (\n typeof limits[name] !== 'number' ||\n isNaN(limits[name])\n ) { throw new TypeError('Limit ' + name + ' is not a valid number') }\n\n return limits[name]\n}\n","'use strict'\n\nconst decodeText = require('./decodeText')\n\nconst RE_ENCODED = /%([a-fA-F0-9]{2})/g\n\nfunction encodedReplacer (match, byte) {\n return String.fromCharCode(parseInt(byte, 16))\n}\n\nfunction parseParams (str) {\n const res = []\n let state = 'key'\n let charset = ''\n let inquote = false\n let escaping = false\n let p = 0\n let tmp = ''\n\n for (var i = 0, len = str.length; i < len; ++i) { // eslint-disable-line no-var\n const char = str[i]\n if (char === '\\\\' && inquote) {\n if (escaping) { escaping = false } else {\n escaping = true\n continue\n }\n } else if (char === '\"') {\n if (!escaping) {\n if (inquote) {\n inquote = false\n state = 'key'\n } else { inquote = true }\n continue\n } else { escaping = false }\n } else {\n if (escaping && inquote) { tmp += '\\\\' }\n escaping = false\n if ((state === 'charset' || state === 'lang') && char === \"'\") {\n if (state === 'charset') {\n state = 'lang'\n charset = tmp.substring(1)\n } else { state = 'value' }\n tmp = ''\n continue\n } else if (state === 'key' &&\n (char === '*' || char === '=') &&\n res.length) {\n if (char === '*') { state = 'charset' } else { state = 'value' }\n res[p] = [tmp, undefined]\n tmp = ''\n continue\n } else if (!inquote && char === ';') {\n state = 'key'\n if (charset) {\n if (tmp.length) {\n tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),\n 'binary',\n charset)\n }\n charset = ''\n } else if (tmp.length) {\n tmp = decodeText(tmp, 'binary', 'utf8')\n }\n if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }\n tmp = ''\n ++p\n continue\n } else if (!inquote && (char === ' ' || char === '\\t')) { continue }\n }\n tmp += char\n }\n if (charset && tmp.length) {\n tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),\n 'binary',\n charset)\n } else if (tmp) {\n tmp = decodeText(tmp, 'binary', 'utf8')\n }\n\n if (res[p] === undefined) {\n if (tmp) { res[p] = tmp }\n } else { res[p][1] = tmp }\n\n return res\n}\n\nmodule.exports = parseParams\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n\n newInvalidAsn1Error: function (msg) {\n var e = new Error();\n e.name = 'InvalidAsn1Error';\n e.message = msg || '';\n return e;\n }\n\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar errors = require('./errors');\nvar types = require('./types');\n\nvar Reader = require('./reader');\nvar Writer = require('./writer');\n\n\n// --- Exports\n\nmodule.exports = {\n\n Reader: Reader,\n\n Writer: Writer\n\n};\n\nfor (var t in types) {\n if (types.hasOwnProperty(t))\n module.exports[t] = types[t];\n}\nfor (var e in errors) {\n if (errors.hasOwnProperty(e))\n module.exports[e] = errors[e];\n}\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\n\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\n\n\n// --- API\n\nfunction Reader(data) {\n if (!data || !Buffer.isBuffer(data))\n throw new TypeError('data must be a node Buffer');\n\n this._buf = data;\n this._size = data.length;\n\n // These hold the \"current\" state\n this._len = 0;\n this._offset = 0;\n}\n\nObject.defineProperty(Reader.prototype, 'length', {\n enumerable: true,\n get: function () { return (this._len); }\n});\n\nObject.defineProperty(Reader.prototype, 'offset', {\n enumerable: true,\n get: function () { return (this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'remain', {\n get: function () { return (this._size - this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'buffer', {\n get: function () { return (this._buf.slice(this._offset)); }\n});\n\n\n/**\n * Reads a single byte and advances offset; you can pass in `true` to make this\n * a \"peek\" operation (i.e., get the byte, but don't advance the offset).\n *\n * @param {Boolean} peek true means don't move offset.\n * @return {Number} the next byte, null if not enough data.\n */\nReader.prototype.readByte = function (peek) {\n if (this._size - this._offset < 1)\n return null;\n\n var b = this._buf[this._offset] & 0xff;\n\n if (!peek)\n this._offset += 1;\n\n return b;\n};\n\n\nReader.prototype.peek = function () {\n return this.readByte(true);\n};\n\n\n/**\n * Reads a (potentially) variable length off the BER buffer. This call is\n * not really meant to be called directly, as callers have to manipulate\n * the internal buffer afterwards.\n *\n * As a result of this call, you can call `Reader.length`, until the\n * next thing called that does a readLength.\n *\n * @return {Number} the amount of offset to advance the buffer.\n * @throws {InvalidAsn1Error} on bad ASN.1\n */\nReader.prototype.readLength = function (offset) {\n if (offset === undefined)\n offset = this._offset;\n\n if (offset >= this._size)\n return null;\n\n var lenB = this._buf[offset++] & 0xff;\n if (lenB === null)\n return null;\n\n if ((lenB & 0x80) === 0x80) {\n lenB &= 0x7f;\n\n if (lenB === 0)\n throw newInvalidAsn1Error('Indefinite length not supported');\n\n if (lenB > 4)\n throw newInvalidAsn1Error('encoding too long');\n\n if (this._size - offset < lenB)\n return null;\n\n this._len = 0;\n for (var i = 0; i < lenB; i++)\n this._len = (this._len << 8) + (this._buf[offset++] & 0xff);\n\n } else {\n // Wasn't a variable length\n this._len = lenB;\n }\n\n return offset;\n};\n\n\n/**\n * Parses the next sequence in this BER buffer.\n *\n * To get the length of the sequence, call `Reader.length`.\n *\n * @return {Number} the sequence's tag.\n */\nReader.prototype.readSequence = function (tag) {\n var seq = this.peek();\n if (seq === null)\n return null;\n if (tag !== undefined && tag !== seq)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + seq.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n this._offset = o;\n return seq;\n};\n\n\nReader.prototype.readInt = function () {\n return this._readTag(ASN1.Integer);\n};\n\n\nReader.prototype.readBoolean = function () {\n return (this._readTag(ASN1.Boolean) === 0 ? false : true);\n};\n\n\nReader.prototype.readEnumeration = function () {\n return this._readTag(ASN1.Enumeration);\n};\n\n\nReader.prototype.readString = function (tag, retbuf) {\n if (!tag)\n tag = ASN1.OctetString;\n\n var b = this.peek();\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n\n if (o === null)\n return null;\n\n if (this.length > this._size - o)\n return null;\n\n this._offset = o;\n\n if (this.length === 0)\n return retbuf ? Buffer.alloc(0) : '';\n\n var str = this._buf.slice(this._offset, this._offset + this.length);\n this._offset += this.length;\n\n return retbuf ? str : str.toString('utf8');\n};\n\nReader.prototype.readOID = function (tag) {\n if (!tag)\n tag = ASN1.OID;\n\n var b = this.readString(tag, true);\n if (b === null)\n return null;\n\n var values = [];\n var value = 0;\n\n for (var i = 0; i < b.length; i++) {\n var byte = b[i] & 0xff;\n\n value <<= 7;\n value += byte & 0x7f;\n if ((byte & 0x80) === 0) {\n values.push(value);\n value = 0;\n }\n }\n\n value = values.shift();\n values.unshift(value % 40);\n values.unshift((value / 40) >> 0);\n\n return values.join('.');\n};\n\n\nReader.prototype._readTag = function (tag) {\n assert.ok(tag !== undefined);\n\n var b = this.peek();\n\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n if (this.length > 4)\n throw newInvalidAsn1Error('Integer too long: ' + this.length);\n\n if (this.length > this._size - o)\n return null;\n this._offset = o;\n\n var fb = this._buf[this._offset];\n var value = 0;\n\n for (var i = 0; i < this.length; i++) {\n value <<= 8;\n value |= (this._buf[this._offset++] & 0xff);\n }\n\n if ((fb & 0x80) === 0x80 && i !== 4)\n value -= (1 << (i * 8));\n\n return value >> 0;\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Reader;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n EOC: 0,\n Boolean: 1,\n Integer: 2,\n BitString: 3,\n OctetString: 4,\n Null: 5,\n OID: 6,\n ObjectDescriptor: 7,\n External: 8,\n Real: 9, // float\n Enumeration: 10,\n PDV: 11,\n Utf8String: 12,\n RelativeOID: 13,\n Sequence: 16,\n Set: 17,\n NumericString: 18,\n PrintableString: 19,\n T61String: 20,\n VideotexString: 21,\n IA5String: 22,\n UTCTime: 23,\n GeneralizedTime: 24,\n GraphicString: 25,\n VisibleString: 26,\n GeneralString: 28,\n UniversalString: 29,\n CharacterString: 30,\n BMPString: 31,\n Constructor: 32,\n Context: 128\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\nvar DEFAULT_OPTS = {\n size: 1024,\n growthFactor: 8\n};\n\n\n// --- Helpers\n\nfunction merge(from, to) {\n assert.ok(from);\n assert.equal(typeof (from), 'object');\n assert.ok(to);\n assert.equal(typeof (to), 'object');\n\n var keys = Object.getOwnPropertyNames(from);\n keys.forEach(function (key) {\n if (to[key])\n return;\n\n var value = Object.getOwnPropertyDescriptor(from, key);\n Object.defineProperty(to, key, value);\n });\n\n return to;\n}\n\n\n\n// --- API\n\nfunction Writer(options) {\n options = merge(DEFAULT_OPTS, options || {});\n\n this._buf = Buffer.alloc(options.size || 1024);\n this._size = this._buf.length;\n this._offset = 0;\n this._options = options;\n\n // A list of offsets in the buffer where we need to insert\n // sequence tag/len pairs.\n this._seq = [];\n}\n\nObject.defineProperty(Writer.prototype, 'buffer', {\n get: function () {\n if (this._seq.length)\n throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');\n\n return (this._buf.slice(0, this._offset));\n }\n});\n\nWriter.prototype.writeByte = function (b) {\n if (typeof (b) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(1);\n this._buf[this._offset++] = b;\n};\n\n\nWriter.prototype.writeInt = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Integer;\n\n var sz = 4;\n\n while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&\n (sz > 1)) {\n sz--;\n i <<= 8;\n }\n\n if (sz > 4)\n throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');\n\n this._ensure(2 + sz);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = sz;\n\n while (sz-- > 0) {\n this._buf[this._offset++] = ((i & 0xff000000) >>> 24);\n i <<= 8;\n }\n\n};\n\n\nWriter.prototype.writeNull = function () {\n this.writeByte(ASN1.Null);\n this.writeByte(0x00);\n};\n\n\nWriter.prototype.writeEnumeration = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Enumeration;\n\n return this.writeInt(i, tag);\n};\n\n\nWriter.prototype.writeBoolean = function (b, tag) {\n if (typeof (b) !== 'boolean')\n throw new TypeError('argument must be a Boolean');\n if (typeof (tag) !== 'number')\n tag = ASN1.Boolean;\n\n this._ensure(3);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = 0x01;\n this._buf[this._offset++] = b ? 0xff : 0x00;\n};\n\n\nWriter.prototype.writeString = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');\n if (typeof (tag) !== 'number')\n tag = ASN1.OctetString;\n\n var len = Buffer.byteLength(s);\n this.writeByte(tag);\n this.writeLength(len);\n if (len) {\n this._ensure(len);\n this._buf.write(s, this._offset);\n this._offset += len;\n }\n};\n\n\nWriter.prototype.writeBuffer = function (buf, tag) {\n if (typeof (tag) !== 'number')\n throw new TypeError('tag must be a number');\n if (!Buffer.isBuffer(buf))\n throw new TypeError('argument must be a buffer');\n\n this.writeByte(tag);\n this.writeLength(buf.length);\n this._ensure(buf.length);\n buf.copy(this._buf, this._offset, 0, buf.length);\n this._offset += buf.length;\n};\n\n\nWriter.prototype.writeStringArray = function (strings) {\n if ((!strings instanceof Array))\n throw new TypeError('argument must be an Array[String]');\n\n var self = this;\n strings.forEach(function (s) {\n self.writeString(s);\n });\n};\n\n// This is really to solve DER cases, but whatever for now\nWriter.prototype.writeOID = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string');\n if (typeof (tag) !== 'number')\n tag = ASN1.OID;\n\n if (!/^([0-9]+\\.){3,}[0-9]+$/.test(s))\n throw new Error('argument is not a valid OID string');\n\n function encodeOctet(bytes, octet) {\n if (octet < 128) {\n bytes.push(octet);\n } else if (octet < 16384) {\n bytes.push((octet >>> 7) | 0x80);\n bytes.push(octet & 0x7F);\n } else if (octet < 2097152) {\n bytes.push((octet >>> 14) | 0x80);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else if (octet < 268435456) {\n bytes.push((octet >>> 21) | 0x80);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else {\n bytes.push(((octet >>> 28) | 0x80) & 0xFF);\n bytes.push(((octet >>> 21) | 0x80) & 0xFF);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n }\n }\n\n var tmp = s.split('.');\n var bytes = [];\n bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));\n tmp.slice(2).forEach(function (b) {\n encodeOctet(bytes, parseInt(b, 10));\n });\n\n var self = this;\n this._ensure(2 + bytes.length);\n this.writeByte(tag);\n this.writeLength(bytes.length);\n bytes.forEach(function (b) {\n self.writeByte(b);\n });\n};\n\n\nWriter.prototype.writeLength = function (len) {\n if (typeof (len) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(4);\n\n if (len <= 0x7f) {\n this._buf[this._offset++] = len;\n } else if (len <= 0xff) {\n this._buf[this._offset++] = 0x81;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffff) {\n this._buf[this._offset++] = 0x82;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffffff) {\n this._buf[this._offset++] = 0x83;\n this._buf[this._offset++] = len >> 16;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else {\n throw newInvalidAsn1Error('Length too long (> 4 bytes)');\n }\n};\n\nWriter.prototype.startSequence = function (tag) {\n if (typeof (tag) !== 'number')\n tag = ASN1.Sequence | ASN1.Constructor;\n\n this.writeByte(tag);\n this._seq.push(this._offset);\n this._ensure(3);\n this._offset += 3;\n};\n\n\nWriter.prototype.endSequence = function () {\n var seq = this._seq.pop();\n var start = seq + 3;\n var len = this._offset - start;\n\n if (len <= 0x7f) {\n this._shift(start, len, -2);\n this._buf[seq] = len;\n } else if (len <= 0xff) {\n this._shift(start, len, -1);\n this._buf[seq] = 0x81;\n this._buf[seq + 1] = len;\n } else if (len <= 0xffff) {\n this._buf[seq] = 0x82;\n this._buf[seq + 1] = len >> 8;\n this._buf[seq + 2] = len;\n } else if (len <= 0xffffff) {\n this._shift(start, len, 1);\n this._buf[seq] = 0x83;\n this._buf[seq + 1] = len >> 16;\n this._buf[seq + 2] = len >> 8;\n this._buf[seq + 3] = len;\n } else {\n throw newInvalidAsn1Error('Sequence too long');\n }\n};\n\n\nWriter.prototype._shift = function (start, len, shift) {\n assert.ok(start !== undefined);\n assert.ok(len !== undefined);\n assert.ok(shift);\n\n this._buf.copy(this._buf, start + shift, start, start + len);\n this._offset += shift;\n};\n\nWriter.prototype._ensure = function (len) {\n assert.ok(len);\n\n if (this._size - this._offset < len) {\n var sz = this._size * this._options.growthFactor;\n if (sz - this._offset < len)\n sz += len;\n\n var buf = Buffer.alloc(sz);\n\n this._buf.copy(buf, 0, 0, this._offset);\n this._buf = buf;\n this._size = sz;\n }\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Writer;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n// If you have no idea what ASN.1 or BER is, see this:\n// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc\n\nvar Ber = require('./ber/index');\n\n\n\n// --- Exported API\n\nmodule.exports = {\n\n Ber: Ber,\n\n BerReader: Ber.Reader,\n\n BerWriter: Ber.Writer\n\n};\n","'use strict';\n\nvar crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;\n\n/*\n * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a\n * result, it retains the original copyright and license. The two files are\n * under slightly different (but compatible) licenses, and are here combined in\n * one file.\n *\n * Credit for the actual porting work goes to:\n * Devi Mandiri \n */\n\n/*\n * The Blowfish portions are under the following license:\n *\n * Blowfish block cipher for OpenBSD\n * Copyright 1997 Niels Provos \n * All rights reserved.\n *\n * Implementation advice by David Mazieres .\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * The bcrypt_pbkdf portions are under the following license:\n *\n * Copyright (c) 2013 Ted Unangst \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n/*\n * Performance improvements (Javascript-specific):\n *\n * Copyright 2016, Joyent Inc\n * Author: Alex Wilson \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n// Ported from OpenBSD bcrypt_pbkdf.c v1.9\n\nvar BLF_J = 0;\n\nvar Blowfish = function() {\n this.S = [\n new Uint32Array([\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,\n 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,\n 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,\n 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,\n 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,\n 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,\n 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,\n 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,\n 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,\n 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,\n 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,\n 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,\n 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,\n 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,\n 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,\n 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,\n 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,\n 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,\n 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,\n 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,\n 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,\n 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,\n 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,\n 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,\n 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,\n 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,\n 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,\n 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,\n 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,\n 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,\n 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,\n 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,\n 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,\n 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,\n 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,\n 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,\n 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,\n 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,\n 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,\n 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,\n 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,\n 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,\n 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),\n new Uint32Array([\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,\n 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,\n 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,\n 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,\n 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,\n 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,\n 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,\n 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,\n 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,\n 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,\n 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,\n 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,\n 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,\n 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,\n 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,\n 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,\n 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,\n 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,\n 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,\n 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,\n 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,\n 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,\n 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,\n 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,\n 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,\n 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,\n 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,\n 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,\n 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,\n 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,\n 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,\n 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,\n 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,\n 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,\n 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,\n 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,\n 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,\n 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,\n 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,\n 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,\n 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,\n 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,\n 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),\n new Uint32Array([\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,\n 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,\n 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,\n 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,\n 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,\n 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,\n 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,\n 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,\n 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,\n 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,\n 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,\n 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,\n 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,\n 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,\n 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,\n 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,\n 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,\n 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,\n 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,\n 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,\n 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,\n 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,\n 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,\n 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,\n 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,\n 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,\n 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,\n 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,\n 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,\n 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,\n 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,\n 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,\n 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,\n 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,\n 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,\n 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,\n 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,\n 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,\n 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,\n 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,\n 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,\n 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,\n 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),\n new Uint32Array([\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,\n 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,\n 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,\n 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,\n 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,\n 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,\n 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,\n 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,\n 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,\n 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,\n 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,\n 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,\n 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,\n 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,\n 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,\n 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,\n 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,\n 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,\n 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,\n 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,\n 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,\n 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,\n 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,\n 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,\n 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,\n 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,\n 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,\n 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,\n 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,\n 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,\n 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,\n 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,\n 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,\n 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,\n 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,\n 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,\n 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,\n 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,\n 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,\n 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,\n 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,\n 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,\n 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])\n ];\n this.P = new Uint32Array([\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,\n 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,\n 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,\n 0x9216d5d9, 0x8979fb1b]);\n};\n\nfunction F(S, x8, i) {\n return (((S[0][x8[i+3]] +\n S[1][x8[i+2]]) ^\n S[2][x8[i+1]]) +\n S[3][x8[i]]);\n};\n\nBlowfish.prototype.encipher = function(x, x8) {\n if (x8 === undefined) {\n x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n }\n x[0] ^= this.P[0];\n for (var i = 1; i < 16; i += 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[17];\n x[1] = t;\n};\n\nBlowfish.prototype.decipher = function(x) {\n var x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n x[0] ^= this.P[17];\n for (var i = 16; i > 0; i -= 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[0];\n x[1] = t;\n};\n\nfunction stream2word(data, databytes){\n var i, temp = 0;\n for (i = 0; i < 4; i++, BLF_J++) {\n if (BLF_J >= databytes) BLF_J = 0;\n temp = (temp << 8) | data[BLF_J];\n }\n return temp;\n};\n\nBlowfish.prototype.expand0state = function(key, keybytes) {\n var d = new Uint32Array(2), i, k;\n var d8 = new Uint8Array(d.buffer);\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n BLF_J = 0;\n\n for (i = 0; i < 18; i += 2) {\n this.encipher(d, d8);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n this.encipher(d, d8);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n};\n\nBlowfish.prototype.expandstate = function(data, databytes, key, keybytes) {\n var d = new Uint32Array(2), i, k;\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n\n for (i = 0, BLF_J = 0; i < 18; i += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n BLF_J = 0;\n};\n\nBlowfish.prototype.enc = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.encipher(data.subarray(i*2));\n }\n};\n\nBlowfish.prototype.dec = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.decipher(data.subarray(i*2));\n }\n};\n\nvar BCRYPT_BLOCKS = 8,\n BCRYPT_HASHSIZE = 32;\n\nfunction bcrypt_hash(sha2pass, sha2salt, out) {\n var state = new Blowfish(),\n cdata = new Uint32Array(BCRYPT_BLOCKS), i,\n ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,\n 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,\n 105,116,101]); //\"OxychromaticBlowfishSwatDynamite\"\n\n state.expandstate(sha2salt, 64, sha2pass, 64);\n for (i = 0; i < 64; i++) {\n state.expand0state(sha2salt, 64);\n state.expand0state(sha2pass, 64);\n }\n\n for (i = 0; i < BCRYPT_BLOCKS; i++)\n cdata[i] = stream2word(ciphertext, ciphertext.byteLength);\n for (i = 0; i < 64; i++)\n state.enc(cdata, cdata.byteLength / 8);\n\n for (i = 0; i < BCRYPT_BLOCKS; i++) {\n out[4*i+3] = cdata[i] >>> 24;\n out[4*i+2] = cdata[i] >>> 16;\n out[4*i+1] = cdata[i] >>> 8;\n out[4*i+0] = cdata[i];\n }\n};\n\nfunction bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {\n var sha2pass = new Uint8Array(64),\n sha2salt = new Uint8Array(64),\n out = new Uint8Array(BCRYPT_HASHSIZE),\n tmpout = new Uint8Array(BCRYPT_HASHSIZE),\n countsalt = new Uint8Array(saltlen+4),\n i, j, amt, stride, dest, count,\n origkeylen = keylen;\n\n if (rounds < 1)\n return -1;\n if (passlen === 0 || saltlen === 0 || keylen === 0 ||\n keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))\n return -1;\n\n stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);\n amt = Math.floor((keylen + stride - 1) / stride);\n\n for (i = 0; i < saltlen; i++)\n countsalt[i] = salt[i];\n\n crypto_hash_sha512(sha2pass, pass, passlen);\n\n for (count = 1; keylen > 0; count++) {\n countsalt[saltlen+0] = count >>> 24;\n countsalt[saltlen+1] = count >>> 16;\n countsalt[saltlen+2] = count >>> 8;\n countsalt[saltlen+3] = count;\n\n crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (i = out.byteLength; i--;)\n out[i] = tmpout[i];\n\n for (i = 1; i < rounds; i++) {\n crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (j = 0; j < out.byteLength; j++)\n out[j] ^= tmpout[j];\n }\n\n amt = Math.min(amt, keylen);\n for (i = 0; i < amt; i++) {\n dest = i * stride + (count - 1);\n if (dest >= origkeylen)\n break;\n key[dest] = out[i];\n }\n keylen -= i;\n }\n\n return 0;\n};\n\nmodule.exports = {\n BLOCKS: BCRYPT_BLOCKS,\n HASHSIZE: BCRYPT_HASHSIZE,\n hash: bcrypt_hash,\n pbkdf: bcrypt_pbkdf\n};\n","'use strict'\nconst fs = require('fs')\nconst path = require('path')\n\n/* istanbul ignore next */\nconst LCHOWN = fs.lchown ? 'lchown' : 'chown'\n/* istanbul ignore next */\nconst LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync'\n\n/* istanbul ignore next */\nconst needEISDIRHandled = fs.lchown &&\n !process.version.match(/v1[1-9]+\\./) &&\n !process.version.match(/v10\\.[6-9]/)\n\nconst lchownSync = (path, uid, gid) => {\n try {\n return fs[LCHOWNSYNC](path, uid, gid)\n } catch (er) {\n if (er.code !== 'ENOENT')\n throw er\n }\n}\n\n/* istanbul ignore next */\nconst chownSync = (path, uid, gid) => {\n try {\n return fs.chownSync(path, uid, gid)\n } catch (er) {\n if (er.code !== 'ENOENT')\n throw er\n }\n}\n\n/* istanbul ignore next */\nconst handleEISDIR =\n needEISDIRHandled ? (path, uid, gid, cb) => er => {\n // Node prior to v10 had a very questionable implementation of\n // fs.lchown, which would always try to call fs.open on a directory\n // Fall back to fs.chown in those cases.\n if (!er || er.code !== 'EISDIR')\n cb(er)\n else\n fs.chown(path, uid, gid, cb)\n }\n : (_, __, ___, cb) => cb\n\n/* istanbul ignore next */\nconst handleEISDirSync =\n needEISDIRHandled ? (path, uid, gid) => {\n try {\n return lchownSync(path, uid, gid)\n } catch (er) {\n if (er.code !== 'EISDIR')\n throw er\n chownSync(path, uid, gid)\n }\n }\n : (path, uid, gid) => lchownSync(path, uid, gid)\n\n// fs.readdir could only accept an options object as of node v6\nconst nodeVersion = process.version\nlet readdir = (path, options, cb) => fs.readdir(path, options, cb)\nlet readdirSync = (path, options) => fs.readdirSync(path, options)\n/* istanbul ignore next */\nif (/^v4\\./.test(nodeVersion))\n readdir = (path, options, cb) => fs.readdir(path, cb)\n\nconst chown = (cpath, uid, gid, cb) => {\n fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => {\n // Skip ENOENT error\n cb(er && er.code !== 'ENOENT' ? er : null)\n }))\n}\n\nconst chownrKid = (p, child, uid, gid, cb) => {\n if (typeof child === 'string')\n return fs.lstat(path.resolve(p, child), (er, stats) => {\n // Skip ENOENT error\n if (er)\n return cb(er.code !== 'ENOENT' ? er : null)\n stats.name = child\n chownrKid(p, stats, uid, gid, cb)\n })\n\n if (child.isDirectory()) {\n chownr(path.resolve(p, child.name), uid, gid, er => {\n if (er)\n return cb(er)\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n })\n } else {\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n }\n}\n\n\nconst chownr = (p, uid, gid, cb) => {\n readdir(p, { withFileTypes: true }, (er, children) => {\n // any error other than ENOTDIR or ENOTSUP means it's not readable,\n // or doesn't exist. give up.\n if (er) {\n if (er.code === 'ENOENT')\n return cb()\n else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')\n return cb(er)\n }\n if (er || !children.length)\n return chown(p, uid, gid, cb)\n\n let len = children.length\n let errState = null\n const then = er => {\n if (errState)\n return\n if (er)\n return cb(errState = er)\n if (-- len === 0)\n return chown(p, uid, gid, cb)\n }\n\n children.forEach(child => chownrKid(p, child, uid, gid, then))\n })\n}\n\nconst chownrKidSync = (p, child, uid, gid) => {\n if (typeof child === 'string') {\n try {\n const stats = fs.lstatSync(path.resolve(p, child))\n stats.name = child\n child = stats\n } catch (er) {\n if (er.code === 'ENOENT')\n return\n else\n throw er\n }\n }\n\n if (child.isDirectory())\n chownrSync(path.resolve(p, child.name), uid, gid)\n\n handleEISDirSync(path.resolve(p, child.name), uid, gid)\n}\n\nconst chownrSync = (p, uid, gid) => {\n let children\n try {\n children = readdirSync(p, { withFileTypes: true })\n } catch (er) {\n if (er.code === 'ENOENT')\n return\n else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP')\n return handleEISDirSync(p, uid, gid)\n else\n throw er\n }\n\n if (children && children.length)\n children.forEach(child => chownrKidSync(p, child, uid, gid))\n\n return handleEISDirSync(p, uid, gid)\n}\n\nmodule.exports = chownr\nchownr.sync = chownrSync\n","'use strict';\n\nconst binding = require('../build/Release/cpufeatures.node');\n\nmodule.exports = binding.getCPUInfo;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","//Based on follow-redirects v0.0.x\n\nvar nativeHttps = require('https'),\n nativeHttp = require('http'),\n url = require('url'),\n utils = require('./utils');\n\nvar maxRedirects = module.exports.maxRedirects = 5;\n\nvar protocols = {\n https: nativeHttps,\n http: nativeHttp\n};\n\nfor (var protocol in protocols) {\n var h = function() {};\n h.prototype = protocols[protocol];\n h = new h();\n\n h.request = function(h) {\n return function(options, callback, redirectOptions) {\n\n redirectOptions = redirectOptions || {};\n\n var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects;\n\n var redirect = utils.extend({\n count: 0,\n max: max,\n clientRequest: null,\n userCallback: callback\n }, redirectOptions);\n\n if (redirect.count > redirect.max) {\n var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.');\n redirect.clientRequest.emit('error', err);\n return redirect.clientRequest;\n }\n\n redirect.count++;\n\n var reqUrl;\n if (typeof options === 'string') {\n reqUrl = options;\n } else {\n reqUrl = url.format(utils.extend({\n protocol: protocol\n }, options));\n }\n\n var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect));\n\n if (!redirect.clientRequest) redirect.clientRequest = clientRequest;\n\n function redirectCallback(reqUrl, redirect) {\n return function(res) {\n if (res.statusCode < 300 || res.statusCode > 399) {\n return redirect.userCallback(res);\n }\n\n if (!('location' in res.headers)) {\n return redirect.userCallback(res);\n }\n\n var redirectUrl = url.resolve(reqUrl, res.headers.location);\n\n var proto = url.parse(redirectUrl).protocol;\n proto = proto.substr(0, proto.length - 1);\n return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect);\n };\n }\n\n return clientRequest;\n };\n }(h);\n\n // see https://github.com/joyent/node/blob/master/lib/http.js#L1623\n h.get = function(h) {\n return function(options, cb, redirectOptions) {\n var req = h.request(options, cb, redirectOptions);\n req.end();\n return req;\n };\n }(h);\n\n module.exports[protocol] = h;\n}\n","module.exports = HttpDuplex;\n\nvar util = require('util'),\n stream = require('readable-stream');\n\nutil.inherits(HttpDuplex, stream.Duplex);\n\nfunction HttpDuplex(req, res, options) {\n var self = this;\n\n if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options);\n\n stream.Duplex.call(self, options);\n self._output = null;\n\n self.connect(req, res);\n}\n\nHttpDuplex.prototype.connect = function(req, res) {\n var self = this;\n self.req = req;\n self._output = res;\n self.emit('response', res);\n\n res.on('data', function(c) {\n if (!self.push(c)) self._output.pause();\n });\n res.on('end', function() {\n self.push(null);\n });\n};\n\nHttpDuplex.prototype._read = function(n) {\n if (this._output) this._output.resume();\n};\n\nHttpDuplex.prototype._write = function(chunk, encoding, cb) {\n this.req.write(chunk, encoding);\n cb();\n};\n\nHttpDuplex.prototype.end = function(chunk, encoding, cb) {\n this._output.socket.destroySoon();\n return this.req.end(chunk, encoding, cb);\n};\n\nHttpDuplex.prototype.destroy = function() {\n this.req.destroy();\n this._output.socket.destroy();\n};\n\nHttpDuplex.prototype.destroySoon = function() {\n this.req.destroy();\n this._output.socket.destroy();\n};\n","var querystring = require('querystring'),\n http = require('./http'),\n fs = require('fs'),\n path = require('path'),\n url = require('url'),\n ssh = require('./ssh'),\n HttpDuplex = require('./http_duplex'),\n debug = require('debug')('modem'),\n utils = require('./utils'),\n util = require('util'),\n splitca = require('split-ca'),\n os = require('os'),\n isWin = os.type() === 'Windows_NT',\n stream = require('stream');\n\nvar defaultOpts = function () {\n var host;\n var opts = {};\n\n if (!process.env.DOCKER_HOST) {\n // Windows socket path: //./pipe/docker_engine ( Windows 10 )\n // Linux & Darwin socket path is /var/run/docker.sock when running system-wide,\n // or $HOME/.docker/run/docker.sock in new Docker Desktop installs.\n opts.socketPath = isWin ? '//./pipe/docker_engine' : findDefaultUnixSocket;\n } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) {\n // Strip off unix://, fall back to default if unix:// was passed without a path\n opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket;\n } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) {\n // Strip off npipe://, fall back to default of //./pipe/docker_engine if\n // npipe:// was passed without a path\n opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine';\n } else {\n var hostStr = process.env.DOCKER_HOST;\n if (hostStr.indexOf('\\/\\/') < 0) {\n hostStr = 'tcp://' + hostStr;\n }\n try {\n host = new url.URL(hostStr);\n } catch (err) {\n throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234');\n }\n\n opts.port = host.port;\n\n if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') {\n opts.protocol = 'https';\n } else if (host.protocol === 'ssh:') {\n opts.protocol = 'ssh';\n opts.username = host.username;\n opts.sshOptions = {\n agent: process.env.SSH_AUTH_SOCK,\n }\n } else {\n opts.protocol = 'http';\n }\n\n if (process.env.DOCKER_PATH_PREFIX) {\n opts.pathPrefix = process.env.DOCKER_PATH_PREFIX;\n }\n else {\n opts.pathPrefix = '/';\n }\n\n opts.host = host.hostname;\n\n if (process.env.DOCKER_CERT_PATH) {\n opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem'));\n opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem'));\n opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem'));\n }\n\n if (process.env.DOCKER_CLIENT_TIMEOUT) {\n opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10);\n }\n }\n\n return opts;\n};\n\nvar findDefaultUnixSocket = function () {\n return new Promise(function (resolve) {\n var userDockerSocket = path.join(os.homedir(), '.docker', 'run', 'docker.sock');\n fs.access(userDockerSocket, function (err) {\n if (err) resolve('/var/run/docker.sock');\n else resolve(userDockerSocket);\n })\n });\n}\n\n\nvar Modem = function (options) {\n var optDefaults = defaultOpts();\n var opts = Object.assign({}, optDefaults, options);\n\n this.host = opts.host;\n\n if (!this.host) {\n this.socketPath = opts.socketPath;\n }\n\n this.port = opts.port;\n this.pathPrefix = opts.pathPrefix;\n this.username = opts.username;\n this.password = opts.password;\n this.version = opts.version;\n this.key = opts.key;\n this.cert = opts.cert;\n this.ca = opts.ca;\n this.timeout = opts.timeout;\n this.connectionTimeout = opts.connectionTimeout;\n this.checkServerIdentity = opts.checkServerIdentity;\n this.agent = opts.agent;\n this.headers = opts.headers || {};\n this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions);\n //retrocompabitlity\n if (this.sshOptions.agentForward === undefined) {\n this.sshOptions.agentForward = opts.agentForward;\n }\n\n if (this.key && this.cert && this.ca) {\n this.protocol = 'https';\n }\n this.protocol = opts.protocol || this.protocol || 'http';\n};\n\nModem.prototype.dial = function (options, callback) {\n var opts, address, data;\n\n if (options.options) {\n opts = options.options;\n }\n\n // Prevent credentials from showing up in URL\n if (opts && opts.authconfig) {\n delete opts.authconfig;\n }\n\n // Prevent abortsignal from showing up in the URL\n if (opts && opts.abortSignal) {\n delete opts.abortSignal;\n }\n\n if (this.version) {\n options.path = '/' + this.version + options.path;\n }\n\n if (this.host) {\n var parsed = url.parse(this.host);\n address = url.format({\n protocol: parsed.protocol || this.protocol,\n hostname: parsed.hostname || this.host,\n port: this.port,\n pathname: parsed.pathname || this.pathPrefix,\n });\n address = url.resolve(address, options.path);\n } else {\n address = options.path;\n }\n\n if (options.path.indexOf('?') !== -1) {\n if (opts && Object.keys(opts).length > 0) {\n address += this.buildQuerystring(opts._query || opts);\n } else {\n address = address.substring(0, address.length - 1);\n }\n }\n\n var optionsf = {\n path: address,\n method: options.method,\n headers: options.headers || Object.assign({}, this.headers),\n key: this.key,\n cert: this.cert,\n ca: this.ca\n };\n\n\n if (this.checkServerIdentity) {\n optionsf.checkServerIdentity = this.checkServerIdentity;\n }\n\n if (this.agent) {\n optionsf.agent = this.agent;\n }\n\n if (options.authconfig) {\n optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 ||\n Buffer.from(JSON.stringify(options.authconfig)).toString('base64').replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n }\n\n if (options.registryconfig) {\n optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 ||\n Buffer.from(JSON.stringify(options.registryconfig)).toString('base64');\n }\n\n if (options.abortSignal) {\n optionsf.signal = options.abortSignal;\n }\n\n if (options.file) {\n if (typeof options.file === 'string') {\n data = fs.createReadStream(path.resolve(options.file));\n } else {\n data = options.file;\n }\n optionsf.headers['Content-Type'] = 'application/tar';\n } else if (opts && options.method === 'POST') {\n data = JSON.stringify(opts._body || opts);\n if (options.allowEmpty) {\n optionsf.headers['Content-Type'] = 'application/json';\n } else {\n if (data !== '{}' && data !== '\"\"') {\n optionsf.headers['Content-Type'] = 'application/json';\n } else {\n data = undefined;\n }\n }\n }\n\n if (typeof data === 'string') {\n optionsf.headers['Content-Length'] = Buffer.byteLength(data);\n } else if (Buffer.isBuffer(data) === true) {\n optionsf.headers['Content-Length'] = data.length;\n } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) {\n optionsf.headers['Transfer-Encoding'] = 'chunked';\n }\n\n if (options.hijack) {\n optionsf.headers.Connection = 'Upgrade';\n optionsf.headers.Upgrade = 'tcp';\n }\n\n if (this.socketPath) {\n // SocketPath may be a function that can return a promise:\n this.getSocketPath().then((socketPath) => {\n optionsf.socketPath = socketPath;\n this.buildRequest(optionsf, options, data, callback);\n });\n } else {\n var urlp = url.parse(address);\n optionsf.hostname = urlp.hostname;\n optionsf.port = urlp.port;\n optionsf.path = urlp.path;\n\n this.buildRequest(optionsf, options, data, callback);\n }\n};\n\nModem.prototype.getSocketPath = function () {\n if (!this.socketPath) return;\n if (this.socketPathCache) return Promise.resolve(this.socketPathCache);\n\n var socketPathValue = typeof this.socketPath === 'function'\n ? this.socketPath() : this.socketPath;\n\n this.socketPathCache = socketPathValue;\n\n return Promise.resolve(socketPathValue);\n}\n\nModem.prototype.buildRequest = function (options, context, data, callback) {\n var self = this;\n var connectionTimeoutTimer;\n var finished = false;\n\n var opts = self.protocol === 'ssh' ? Object.assign(options, {\n agent: ssh(Object.assign({}, self.sshOptions, {\n 'host': self.host,\n 'port': self.port,\n 'username': self.username,\n 'password': self.password,\n })),\n protocol: 'http:',\n }) : options;\n\n var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { });\n\n debug('Sending: %s', util.inspect(options, {\n showHidden: true,\n depth: null\n }));\n\n if (self.connectionTimeout) {\n connectionTimeoutTimer = setTimeout(function () {\n debug('Connection Timeout of %s ms exceeded', self.connectionTimeout);\n req.abort();\n }, self.connectionTimeout);\n }\n\n if (self.timeout) {\n req.on('socket', function (socket) {\n socket.setTimeout(self.timeout);\n socket.on('timeout', function () {\n debug('Timeout of %s ms exceeded', self.timeout);\n req.abort();\n });\n });\n }\n\n if (context.hijack === true) {\n clearTimeout(connectionTimeoutTimer);\n req.on('upgrade', function (res, sock, head) {\n if (finished === false) {\n finished = true;\n return callback(null, sock);\n }\n });\n }\n\n req.on('connect', function () {\n clearTimeout(connectionTimeoutTimer);\n });\n\n req.on('disconnect', function () {\n clearTimeout(connectionTimeoutTimer);\n });\n\n req.on('response', function (res) {\n clearTimeout(connectionTimeoutTimer);\n if (context.isStream === true) {\n if (finished === false) {\n finished = true;\n self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback);\n }\n } else {\n // The native 'request' method only handles aborting during the request lifecycle not the response lifecycle.\n // We need to make the response stream abortable so that it's destroyed with an error on abort and then\n // it triggers the request 'error' event\n if (options.signal != null) {\n stream.addAbortSignal(options.signal, res)\n }\n var chunks = [];\n res.on('data', function (chunk) {\n chunks.push(chunk);\n });\n\n res.on('end', function () {\n var buffer = Buffer.concat(chunks);\n var result = buffer.toString();\n\n debug('Received: %s', result);\n\n var json = utils.parseJSON(result) || buffer;\n if (finished === false) {\n finished = true;\n self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback);\n }\n });\n }\n });\n\n req.on('error', function (error) {\n clearTimeout(connectionTimeoutTimer);\n if (finished === false) {\n finished = true;\n self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback);\n }\n });\n\n if (typeof data === 'string' || Buffer.isBuffer(data)) {\n req.write(data);\n } else if (data) {\n data.on('error', function (error) {\n req.destroy(error);\n });\n data.pipe(req);\n }\n\n if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) {\n req.end();\n }\n};\n\nModem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) {\n if (err) return cb(err, null);\n\n if (statusCodes[res.statusCode] !== true) {\n getCause(isStream, res, json, function (err, cause) {\n if (err) {\n return cb(err, null);\n }\n var msg = new Error(\n '(HTTP code ' + res.statusCode + ') ' +\n (statusCodes[res.statusCode] || 'unexpected') + ' - ' +\n (cause.message || cause) + ' '\n );\n msg.reason = statusCodes[res.statusCode];\n msg.statusCode = res.statusCode;\n msg.json = json;\n cb(msg, null);\n });\n } else {\n if (openStdin) {\n cb(null, new HttpDuplex(req, res));\n } else if (isStream) {\n cb(null, res);\n } else {\n cb(null, json);\n }\n }\n\n function getCause(isStream, res, json, callback) {\n var chunks = '';\n var done = false;\n\n if (isStream) {\n res.on('data', function (chunk) {\n chunks += chunk;\n });\n res.on('error', function (err) {\n handler(err, null);\n });\n res.on('end', function () {\n handler(null, utils.parseJSON(chunks) || chunks)\n });\n } else {\n callback(null, json);\n }\n\n function handler(err, data) {\n if (done === false) {\n if (err) {\n callback(err);\n } else {\n callback(null, data);\n }\n }\n done = true;\n }\n }\n};\n\nModem.prototype.demuxStream = function (streama, stdout, stderr) {\n var nextDataType = null;\n var nextDataLength = null;\n var buffer = Buffer.from('');\n function processData(data) {\n if (data) {\n buffer = Buffer.concat([buffer, data]);\n }\n if (!nextDataType) {\n if (buffer.length >= 8) {\n var header = bufferSlice(8);\n nextDataType = header.readUInt8(0);\n nextDataLength = header.readUInt32BE(4);\n // It's possible we got a \"data\" that contains multiple messages\n // Process the next one\n processData();\n }\n } else {\n if (buffer.length >= nextDataLength) {\n var content = bufferSlice(nextDataLength);\n if (nextDataType === 1) {\n stdout.write(content);\n } else {\n stderr.write(content);\n }\n nextDataType = null;\n // It's possible we got a \"data\" that contains multiple messages\n // Process the next one\n processData();\n }\n }\n }\n\n function bufferSlice(end) {\n var out = buffer.subarray(0, end);\n buffer = Buffer.from(buffer.subarray(end, buffer.length));\n return out;\n }\n\n streama.on('data', processData);\n};\n\nModem.prototype.followProgress = function (streama, onFinished, onProgress) {\n var buf = '';\n var output = [];\n var finished = false;\n\n streama.on('data', onStreamEvent);\n streama.on('error', onStreamError);\n streama.on('end', onStreamEnd);\n streama.on('close', onStreamEnd);\n\n function onStreamEvent(data) {\n buf += data.toString();\n pump();\n\n function pump() {\n var pos;\n while ((pos = buf.indexOf('\\n')) >= 0) {\n if (pos == 0) {\n buf = buf.slice(1);\n continue;\n }\n processLine(buf.slice(0, pos));\n buf = buf.slice(pos + 1);\n }\n }\n\n function processLine(line) {\n if (line[line.length - 1] == '\\r') line = line.substr(0, line.length - 1);\n if (line.length > 0) {\n var obj = JSON.parse(line);\n output.push(obj);\n if (onProgress) {\n onProgress(obj);\n }\n }\n }\n };\n\n function onStreamError(err) {\n finished = true;\n streama.removeListener('data', onStreamEvent);\n streama.removeListener('error', onStreamError);\n streama.removeListener('end', onStreamEnd);\n streama.removeListener('close', onStreamEnd);\n onFinished(err, output);\n }\n\n function onStreamEnd() {\n if (!finished) onFinished(null, output);\n finished = true;\n }\n};\n\nModem.prototype.buildQuerystring = function (opts) {\n var clone = {};\n\n // serialize map and array values as JSON strings, else querystring truncates.\n // 't' and 'extrahosts' can be arrays but need special treatment so that they're\n // passed as multiple qs parameters instead of JSON values.\n Object.keys(opts).map(function (key, i) {\n if (opts[key]\n && typeof opts[key] === 'object'\n && !['t', 'extrahosts'].includes(key)\n ) {\n clone[key] = JSON.stringify(opts[key]);\n } else {\n clone[key] = opts[key];\n }\n });\n\n return querystring.stringify(clone);\n};\n\nmodule.exports = Modem;\n","var Client = require('ssh2').Client,\n http = require('http');\n\nmodule.exports = function (opt) {\n var conn = new Client();\n var agent = new http.Agent();\n\n agent.createConnection = function (options, fn) {\n try {\n conn.once('ready', function () {\n conn.exec('docker system dial-stdio', function (err, stream) {\n if (err) {\n handleError(err);\n }\n\n fn(null, stream);\n \n stream.addListener('error', (err) => {\n handleError(err);\n });\n stream.once('close', () => {\n conn.end();\n agent.destroy();\n });\n });\n }).on('error', (err) => {\n handleError(err);\n })\n .connect(opt);\n conn.once('end', () => agent.destroy());\n \n } catch (err) {\n handleError(err);\n }\n };\n\n function handleError(err) {\n conn.end();\n agent.destroy();\n throw err;\n }\n\n return agent;\n};\n","// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js\n\nvar arr = [];\nvar each = arr.forEach;\nvar slice = arr.slice;\n\nmodule.exports.extend = function(obj) {\n each.call(slice.call(arguments, 1), function(source) {\n if (source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\nmodule.exports.parseJSON = function(s) {\n try {\n return JSON.parse(s);\n } catch (e) {\n return null;\n }\n};\n","var util = require('./util');\n\n/**\n * Represents a config\n * @param {Object} modem docker-modem\n * @param {String} id Config's id\n */\nvar Config = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nConfig.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nConfig.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update a config.\n *\n * @param {object} opts\n * @param {function} callback\n */\nConfig.prototype.update = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id + '/update?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Removes the config\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nConfig.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Config;\n","var extend = require('./util').extend,\n Exec = require('./exec'),\n util = require('./util');\n\n/**\n * Represents a Container\n * @param {Object} modem docker-modem\n * @param {String} id Container's ID\n */\nvar Container = function(modem, id) {\n this.modem = modem;\n this.id = id;\n\n this.defaultOptions = {\n top: {},\n start: {},\n commit: {},\n stop: {},\n pause: {},\n unpause: {},\n restart: {},\n resize: {},\n attach: {},\n remove: {},\n copy: {},\n kill: {},\n exec: {},\n rename: {},\n log: {},\n stats: {},\n getArchive: {},\n infoArchive: {},\n putArchive: {},\n update: {},\n wait: {}\n };\n};\n\nContainer.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if supplied will query Docker.\n * @return {Object} ID only and only if callback isn't supplied.\n */\nContainer.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Rename\n * @param {Object} opts Rename options\n * @param {Function} callback Callback\n */\nContainer.prototype.rename = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.rename);\n\n var optsf = {\n path: '/containers/' + this.id + '/rename?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update\n * @param {Object} opts Update options\n * @param {Function} callback Callback\n */\nContainer.prototype.update = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.update);\n\n var optsf = {\n path: '/containers/' + this.id + '/update',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Top\n * @param {Object} opts like 'ps_args' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.top = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.top);\n\n var optsf = {\n path: '/containers/' + this.id + '/top?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Containers changes\n * @param {Object} Options\n * @param {Function} callback Callback\n */\nContainer.prototype.changes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/changes',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Checkpoints list\n * @param {Object} opts List checkpoints options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.listCheckpoint = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Delete checkpoint\n * @param {Object} opts Delete checkpoint options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.deleteCheckpoint = function(checkpoint, opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Create checkpoint\n * @param {Object} opts Create checkpoint options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.createCheckpoint = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n allowEmpty: true,\n statusCodes: {\n 200: true, //unofficial, but proxies may return it\n 201: true,\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Export\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback with the octet-stream.\n */\nContainer.prototype.export = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/export',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Start\n * @param {Object} opts Container start options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.start = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.start);\n\n var optsf = {\n path: '/containers/' + this.id + '/start?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 304: 'container already started',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Pause\n * @param {Object} opts Pause options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.pause = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.pause);\n\n var optsf = {\n path: '/containers/' + this.id + '/pause',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Unpause\n * @param {Object} opts Unpause options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.unpause = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.unpause);\n\n var optsf = {\n path: '/containers/' + this.id + '/unpause',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Setup an exec call to a running container\n *\n * @param {object} opts\n * @param {function} callback\n */\nContainer.prototype.exec = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.exec);\n\n var optsf = {\n path: '/containers/' + this.id + '/exec',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 409: 'container stopped/paused',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(new Exec(self.modem, data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, new Exec(self.modem, data.Id));\n });\n }\n};\n\n/**\n * Commit\n * @param {Object} opts Commit options like 'Hostname' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.commit = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.commit);\n\n args.opts.container = this.id;\n\n var optsf = {\n path: '/commit?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Stop\n * @param {Object} opts Container stop options, like 't' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.stop = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.stop);\n\n var optsf = {\n path: '/containers/' + this.id + '/stop?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 304: 'container already stopped',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Restart\n * @param {Object} opts Container restart options, like 't' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.restart = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.restart);\n\n var optsf = {\n path: '/containers/' + this.id + '/restart?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Kill\n * @param {Object} opts Container kill options, like 'signal' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.kill = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.kill);\n\n var optsf = {\n path: '/containers/' + this.id + '/kill?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container resize\n * @param {[type]} opts Resize options. (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.resize = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.resize);\n\n var optsf = {\n path: '/containers/' + this.id + '/resize?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Attach\n * @param {Object} opts Attach options, like 'logs' (optional)\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.attach = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.attach);\n\n var optsf = {\n path: '/containers/' + this.id + '/attach?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n hijack: args.opts.hijack,\n openStdin: args.opts.stdin,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, stream) {\n if (err) {\n return reject(err);\n }\n resolve(stream);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, stream) {\n args.callback(err, stream);\n });\n }\n};\n\n/**\n * Waits for a container to end.\n * @param {[type]} opts Container wait options, like condition. (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.wait = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.wait);\n\n var optsf = {\n path: '/containers/' + this.id + '/wait?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes a container\n * @param {Object} opts Remove options, like 'force' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.remove);\n\n var optsf = {\n path: '/containers/' + this.id + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Copy (WARNING: DEPRECATED since RAPI v1.20)\n * @param {Object} opts Copy options, like 'Resource' (optional)\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.copy = function(opts, callback) {\n var self = this;\n console.log('container.copy is deprecated since Docker v1.8.x');\n var args = util.processArgs(opts, callback, this.defaultOptions.copy);\n\n var optsf = {\n path: '/containers/' + this.id + '/copy',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * getArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.getArchive = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.getArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * infoArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.infoArchive = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'HEAD',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * putArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.putArchive = function(file, opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.putArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'PUT',\n file: file,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 403: 'client error, permission denied',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nContainer.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.log);\n\n var optsf = {\n path: '/containers/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container stats\n * @param {Object} opts Stats options. (optional)\n * @param {Function} callback Callback with data\n */\nContainer.prototype.stats = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.stats);\n var isStream = true;\n if (args.opts.stream === false) {\n isStream = false;\n }\n var optsf = {\n path: '/containers/' + this.id + '/stats?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: isStream,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Container;\n","var EventEmitter = require('events').EventEmitter,\n Modem = require('docker-modem'),\n Container = require('./container'),\n Image = require('./image'),\n Volume = require('./volume'),\n Network = require('./network'),\n Service = require('./service'),\n Plugin = require('./plugin'),\n Secret = require('./secret'),\n Config = require('./config'),\n Task = require('./task'),\n Node = require('./node'),\n Exec = require('./exec'),\n util = require('./util'),\n extend = util.extend;\n\nvar Docker = function(opts) {\n if (!(this instanceof Docker)) return new Docker(opts);\n\n var plibrary = global.Promise;\n\n if (opts && opts.Promise) {\n plibrary = opts.Promise;\n\n if (Object.keys(opts).length === 1) {\n opts = undefined;\n }\n }\n\n if (opts && opts.modem) {\n this.modem = opts.modem;\n } else {\n this.modem = new Modem(opts);\n }\n this.modem.Promise = plibrary;\n};\n\n/**\n * Creates a new container\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createContainer = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/containers/create?',\n method: 'POST',\n options: opts,\n authconfig: opts.authconfig,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 406: 'impossible to attach',\n 500: 'server error'\n }\n };\n\n delete opts.authconfig;\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getContainer(data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n callback(err, self.getContainer(data.Id));\n });\n }\n};\n\n/**\n * Creates a new image\n * @param {Object} auth Authentication (optional)\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createImage = function(auth, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (!callback && !opts) {\n opts = auth;\n auth = opts.authconfig;\n }\n\n var optsf = {\n path: '/images/create?',\n method: 'POST',\n options: opts,\n authconfig: auth,\n abortSignal: opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Load image\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.loadImage = function(file, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n\n var optsf = {\n path: '/images/load?',\n method: 'POST',\n options: opts,\n file: file,\n abortSignal: opts && opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Import image from a tar archive\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.importImage = function(file, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = undefined;\n }\n\n if (!opts)\n opts = {};\n\n opts.fromSrc = '-';\n\n var optsf = {\n path: '/images/create?',\n method: 'POST',\n options: opts,\n file: file,\n abortSignal: opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Verifies auth\n * @param {Object} opts Options\n * @param {Function} callback Callback\n */\nDocker.prototype.checkAuth = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/auth',\n method: 'POST',\n options: opts,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Builds an image\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.buildImage = function(file, opts, callback) {\n var self = this;\n\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n\n var optsf = {\n path: '/build?',\n method: 'POST',\n file: undefined,\n options: opts,\n abortSignal: opts && opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (opts) {\n if (opts.registryconfig) {\n optsf.registryconfig = optsf.options.registryconfig;\n delete optsf.options.registryconfig;\n }\n\n //undocumented?\n if (opts.authconfig) {\n optsf.authconfig = optsf.options.authconfig;\n delete optsf.options.authconfig;\n }\n }\n\n if (callback === undefined) {\n return new self.modem.Promise(function(resolve, reject) {\n util.prepareBuildContext(file, (ctx) => {\n optsf.file = ctx;\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n });\n } else {\n util.prepareBuildContext(file, (ctx) => {\n optsf.file = ctx;\n self.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n })\n }\n};\n\n/**\n * Fetches a Container by ID\n * @param {String} id Container's ID\n */\nDocker.prototype.getContainer = function(id) {\n return new Container(this.modem, id);\n};\n\n/**\n * Fetches an Image by name\n * @param {String} name Image's name\n */\nDocker.prototype.getImage = function(name) {\n return new Image(this.modem, name);\n};\n\n/**\n * Fetches a Volume by name\n * @param {String} name Volume's name\n */\nDocker.prototype.getVolume = function(name) {\n return new Volume(this.modem, name);\n};\n\n/**\n * Fetches a Plugin by name\n * @param {String} name Volume's name\n */\nDocker.prototype.getPlugin = function(name, remote) {\n return new Plugin(this.modem, name, remote);\n};\n\n/**\n * Fetches a Service by id\n * @param {String} id Services's id\n */\nDocker.prototype.getService = function(id) {\n return new Service(this.modem, id);\n};\n\n/**\n * Fetches a Task by id\n * @param {String} id Task's id\n */\nDocker.prototype.getTask = function(id) {\n return new Task(this.modem, id);\n};\n\n/**\n * Fetches Node by id\n * @param {String} id Node's id\n */\nDocker.prototype.getNode = function(id) {\n return new Node(this.modem, id);\n};\n\n/**\n * Fetches a Network by id\n * @param {String} id network's id\n */\nDocker.prototype.getNetwork = function(id) {\n return new Network(this.modem, id);\n};\n\n/**\n * Fetches a Secret by id\n * @param {String} id network's id\n */\nDocker.prototype.getSecret = function(id) {\n return new Secret(this.modem, id);\n};\n\n/**\n * Fetches a Config by id\n * @param {String} id network's id\n */\nDocker.prototype.getConfig = function(id) {\n return new Config(this.modem, id);\n};\n\n/**\n * Fetches an Exec instance by ID\n * @param {String} id Exec instance's ID\n */\nDocker.prototype.getExec = function(id) {\n return new Exec(this.modem, id);\n};\n\n/**\n * Lists containers\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listContainers = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Get images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.getImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/get?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Services\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listServices = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Nodes\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listNodes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such node',\n 500: 'server error',\n 503: 'node is not part of a swarm',\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Tasks\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listTasks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/tasks?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new secret\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createSecret = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n var optsf = {\n path: '/secrets/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 406: 'server error or node is not part of a swarm',\n 409: 'name conflicts with an existing object',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getSecret(data.ID));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getSecret(data.ID));\n });\n }\n};\n\n\n/**\n * Creates a new config\n * @param {Object} opts Config options\n * @param {Function} callback Callback\n */\nDocker.prototype.createConfig = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n var optsf = {\n path: '/configs/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 406: 'server error or node is not part of a swarm',\n 409: 'name conflicts with an existing object',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getConfig(data.ID));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getConfig(data.ID));\n });\n }\n};\n\n\n/**\n * Lists secrets\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listSecrets = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists configs\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listConfigs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new plugin\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createPlugin = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/plugins/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getPlugin(args.opts.name));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getPlugin(args.opts.name));\n });\n }\n};\n\n\n/**\n * Lists plugins\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listPlugins = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune builder\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneBuilder = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/build/prune',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune containers\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneContainers = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune volumes\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneVolumes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune networks\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneNetworks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Creates a new volume\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createVolume = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/volumes/create?',\n method: 'POST',\n allowEmpty: true,\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getVolume(data.Name));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getVolume(data.Name));\n });\n }\n};\n\n/**\n * Creates a new service\n * @param {Object} auth\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createService = function(auth, opts, callback) {\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (!opts && !callback) {\n opts = auth;\n }\n\n\n var self = this;\n var optsf = {\n path: '/services/create',\n method: 'POST',\n options: opts,\n authconfig: auth,\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 500: 'server error'\n }\n };\n\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getService(data.ID || data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n callback(err, self.getService(data.ID || data.Id));\n });\n }\n};\n\n/**\n * Lists volumes\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listVolumes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new network\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createNetwork = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/networks/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'driver not found',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getNetwork(data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getNetwork(data.Id));\n });\n }\n};\n\n/**\n * Lists networks\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listNetworks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Search images\n * @param {Object} opts Options\n * @param {Function} callback Callback\n */\nDocker.prototype.searchImages = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/images/search?',\n method: 'GET',\n options: opts,\n authconfig: opts.authconfig,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Info\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback with info\n */\nDocker.prototype.info = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/info',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Version\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.version = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/version',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Ping\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.ping = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/_ping',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * SystemDf \tequivalent to system/df API Engine\n *\t\tget usage data information\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.df = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/system/df',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Events\n * @param {Object} opts Events options, like 'since' (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.getEvents = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/events?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Pull is a wrapper around createImage, parsing image's tags.\n * @param {String} repoTag Repository tag\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n * @param {Object} auth Authentication (optional)\n * @return {Object} Image\n */\nDocker.prototype.pull = function(repoTag, opts, callback, auth) {\n var args = util.processArgs(opts, callback);\n\n var imageSrc = util.parseRepositoryTag(repoTag);\n args.opts.fromImage = imageSrc.repository;\n args.opts.tag = imageSrc.tag || 'latest';\n\n var argsf = [args.opts, args.callback];\n if (auth) {\n argsf = [auth, args.opts, args.callback];\n }\n return this.createImage.apply(this, argsf);\n};\n\n/**\n * Like run command from Docker's CLI\n * @param {String} image Image name to be used.\n * @param {Array} cmd Command to run in array format.\n * @param {Object} streamo Output stream\n * @param {Object} createOptions Container create options (optional)\n * @param {Object} startOptions Container start options (optional)\n * @param {Function} callback Callback\n * @return {Object} EventEmitter\n */\nDocker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) {\n if (typeof arguments[arguments.length - 1] === 'function') {\n return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback);\n } else {\n return this.runPromise(image, cmd, streamo, createOptions, startOptions);\n }\n};\n\n\nDocker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) {\n if (!callback && typeof createOptions === 'function') {\n callback = createOptions;\n createOptions = {};\n startOptions = {};\n } else if (!callback && typeof startOptions === 'function') {\n callback = startOptions;\n startOptions = {};\n }\n\n var hub = new EventEmitter();\n\n function handler(err, container) {\n if (err) return callback(err, null, container);\n\n hub.emit('container', container);\n\n container.attach({\n stream: true,\n stdout: true,\n stderr: true\n }, function handler(err, stream) {\n if (err) return callback(err, null, container);\n\n hub.emit('stream', stream);\n\n if (streamo) {\n if (streamo instanceof Array) {\n stream.on('end', function() {\n try {\n streamo[0].end();\n } catch (e) {}\n try {\n streamo[1].end();\n } catch (e) {}\n });\n container.modem.demuxStream(stream, streamo[0], streamo[1]);\n } else {\n stream.setEncoding('utf8');\n stream.pipe(streamo, {\n end: true\n });\n }\n }\n\n container.start(startOptions, function(err, data) {\n if (err) return callback(err, data, container);\n hub.emit('start', container);\n\n container.wait(function(err, data) {\n hub.emit('data', data);\n callback(err, data, container);\n });\n });\n });\n }\n\n var optsc = {\n 'Hostname': '',\n 'User': '',\n 'AttachStdin': false,\n 'AttachStdout': true,\n 'AttachStderr': true,\n 'Tty': true,\n 'OpenStdin': false,\n 'StdinOnce': false,\n 'Env': null,\n 'Cmd': cmd,\n 'Image': image,\n 'Volumes': {},\n 'VolumesFrom': []\n };\n\n extend(optsc, createOptions);\n\n this.createContainer(optsc, handler);\n\n return hub;\n};\n\nDocker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) {\n var self = this;\n\n createOptions = createOptions || {};\n startOptions = startOptions || {};\n\n var optsc = {\n 'Hostname': '',\n 'User': '',\n 'AttachStdin': false,\n 'AttachStdout': true,\n 'AttachStderr': true,\n 'Tty': true,\n 'OpenStdin': false,\n 'StdinOnce': false,\n 'Env': null,\n 'Cmd': cmd,\n 'Image': image,\n 'Volumes': {},\n 'VolumesFrom': []\n };\n\n extend(optsc, createOptions);\n\n var containero;\n\n return new this.modem.Promise(function(resolve, reject) {\n self.createContainer(optsc).then(function(container) {\n containero = container;\n return container.attach({\n stream: true,\n stdout: true,\n stderr: true\n });\n }).then(function(stream) {\n if (streamo) {\n if (streamo instanceof Array) {\n stream.on('end', function() {\n try {\n streamo[0].end();\n } catch (e) {}\n try {\n streamo[1].end();\n } catch (e) {}\n });\n containero.modem.demuxStream(stream, streamo[0], streamo[1]);\n } else {\n stream.setEncoding('utf8');\n stream.pipe(streamo, {\n end: true\n });\n }\n }\n return containero.start(startOptions);\n }).then(function(data) {\n return containero.wait();\n }).then(function(data) {\n resolve([data, containero]);\n }).catch(function(err) {\n reject(err);\n });\n });\n};\n\n/**\n * Init swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmInit = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/init',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Join swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmJoin = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/join',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Leave swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmLeave = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/leave?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 406: 'node is not part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmUpdate = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/update?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Inspect a Swarm.\n * Warning: This method is not documented in the API\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.swarmInspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 406: 'This node is not a swarm manager',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nDocker.Container = Container;\nDocker.Image = Image;\nDocker.Volume = Volume;\nDocker.Network = Network;\nDocker.Service = Service;\nDocker.Plugin = Plugin;\nDocker.Secret = Secret;\nDocker.Task = Task;\nDocker.Node = Node;\nDocker.Exec = Exec;\n\nmodule.exports = Docker;\n","var util = require('./util');\n\n/**\n * Represents an Exec\n * @param {Object} modem docker-modem\n * @param {String} id Exec's ID\n */\nvar Exec = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nExec.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Start the exec call that was setup.\n *\n * @param {object} opts\n * @param {function} callback\n */\nExec.prototype.start = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/start',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n allowEmpty: true,\n hijack: args.opts.hijack,\n openStdin: args.opts.stdin,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such exec',\n 409: 'container stopped/paused',\n 500: 'container not running'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Resize the exec call that was setup.\n *\n * @param {object} opts\n * @param {function} callback\n */\nExec.prototype.resize = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/resize?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such exec',\n 500: 'container not running'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Get low-level information about the exec call.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nExec.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/json',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such exec',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Exec;\n","var util = require('./util');\n\n/**\n * Represents an image\n * @param {Object} modem docker-modem\n * @param {String} name Image's name\n */\nvar Image = function(modem, name) {\n this.modem = modem;\n this.name = name;\n};\n\nImage.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nImage.prototype.inspect = function(callback) {\n var self = this;\n\n var opts = {\n path: '/images/' + this.name + '/json',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Distribution\n * @param {Object} opts\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nImage.prototype.distribution = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n\n var fopts = {\n path: '/distribution/' + this.name + '/json',\n method: 'GET',\n statusCodes: {\n 200: true,\n 401: 'no such image',\n 500: 'server error'\n },\n authconfig: (args.opts) ? args.opts.authconfig : undefined\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(fopts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(fopts, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * History\n * @param {Function} callback Callback\n */\nImage.prototype.history = function(callback) {\n var self = this;\n var opts = {\n path: '/images/' + this.name + '/history',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Get\n * @param {Function} callback Callback with data stream.\n */\nImage.prototype.get = function(callback) {\n var self = this;\n var opts = {\n path: '/images/' + this.name + '/get',\n method: 'GET',\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Push\n * @param {Object} opts Push options, like 'registry' (optional)\n * @param {Function} callback Callback with stream.\n * @param {Object} auth Registry authentication\n */\nImage.prototype.push = function(opts, callback, auth) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var isStream = true;\n if (args.opts.stream === false) {\n isStream = false;\n }\n var optsf = {\n path: '/images/' + this.name + '/push?',\n method: 'POST',\n options: args.opts,\n authconfig: args.opts.authconfig || auth,\n abortSignal: args.opts.abortSignal,\n isStream: isStream,\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n delete optsf.options.authconfig;\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Tag\n * @param {Object} opts Tag options, like 'repo' (optional)\n * @param {Function} callback Callback\n */\nImage.prototype.tag = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/images/' + this.name + '/tag?',\n method: 'POST',\n options: opts,\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 400: 'bad parameter',\n 404: 'no such image',\n 409: 'conflict',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Removes the image\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nImage.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/' + this.name + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Image;\n","var util = require('./util');\n\n/**\n * Represents an network\n * @param {Object} modem docker-modem\n * @param {String} id Network's id\n */\nvar Network = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nNetwork.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Id only if callback isn't specified.\n */\nNetwork.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/networks/' + this.id + '?',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such network',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the network\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such network',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Connects a container to a network\n * @param {[Object]} opts Connect options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.connect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id + '/connect',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 404: 'network or container is not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Disconnects a container from a network\n * @param {[Object]} opts Disconnect options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.disconnect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id + '/disconnect',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 404: 'network or container is not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\n\nmodule.exports = Network;\n","var util = require('./util');\n\n/**\n * Represents an Node\n * @param {Object} modem docker-modem\n * @param {String} id Node's ID\n */\nvar Node = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nNode.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for Node details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nNode.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Update a node.\n *\n * @param {object} opts\n * @param {function} callback\n */\nNode.prototype.update = function(opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n }\n\n var optsf = {\n path: '/nodes/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 406: 'node is not part of a swarm',\n 500: 'server error'\n },\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n/**\n * Remove a Node.\n * Warning: This method is not documented in the API.\n *\n * @param {object} opts\n * @param {function} callback\n */\nNode.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes/' + this.id + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Node;\n","var util = require('./util');\n\n/**\n * Represents a plugin\n * @param {Object} modem docker-modem\n * @param {String} name Plugin's name\n */\nvar Plugin = function(modem, name, remote) {\n this.modem = modem;\n this.name = name;\n this.remote = remote || name;\n};\n\nPlugin.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nPlugin.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin is not installed',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the plugin\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin is not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * get privileges\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n * @return {Object} Name only if callback isn't specified.\n */\nPlugin.prototype.privileges = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/privileges?',\n method: 'GET',\n options: {\n 'remote': this.remote\n },\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Installs a new plugin\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nPlugin.prototype.pull = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n if(args.opts._query && !args.opts._query.name) {\n args.opts._query.name = this.name;\n }\n if(args.opts._query && !args.opts._query.remote) {\n args.opts._query.remote = this.remote;\n }\n\n var optsf = {\n path: '/plugins/pull?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n options: args.opts,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Enable\n * @param {Object} opts Plugin enable options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.enable = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/enable?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Disable\n * @param {Object} opts Plugin disable options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.disable = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/disable',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Push\n * @param {Object} opts Plugin push options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.push = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/push',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * COnfigure\n * @param {Object} opts Plugin configure options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.configure = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/set',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Upgrade plugin\n *\n * @param {object} auth\n * @param {object} opts\n * @param {function} callback\n */\nPlugin.prototype.upgrade = function(auth, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n }\n\n var optsf = {\n path: '/plugins/' + this.name + '/upgrade?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n authconfig: auth,\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Plugin;\n","var util = require('./util');\n\n/**\n * Represents a secret\n * @param {Object} modem docker-modem\n * @param {String} id Secret's id\n */\nvar Secret = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nSecret.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nSecret.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'secret not found',\n 406: 'node is not part of a swarm',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update a secret.\n *\n * @param {object} opts\n * @param {function} callback\n */\nSecret.prototype.update = function(opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n }\n\n var optsf = {\n path: '/secrets/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'secret not found',\n 500: 'server error'\n },\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n/**\n * Removes the secret\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nSecret.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'secret not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Secret;\n","var util = require('./util');\n\n/**\n * Represents an Service\n * @param {Object} modem docker-modem\n * @param {String} id Service's ID\n */\nvar Service = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nService.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for service details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nService.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Delete Service\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nService.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such service',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update service\n *\n * @param {object} auth\n * @param {object} opts\n * @param {function} callback\n */\nService.prototype.update = function(auth, opts, callback) {\n var self = this;\n if (!callback) {\n var t = typeof opts;\n if(t === 'function'){\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (t === 'undefined'){\n opts = auth;\n auth = opts.authconfig || undefined;\n }\n }\n\n var optsf = {\n path: '/services/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error'\n },\n authconfig: auth,\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n\n/**\n * Service logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nService.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, {});\n\n var optsf = {\n path: '/services/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Service;\n","var util = require('./util');\n\n/**\n * Represents an Task\n * @param {Object} modem docker-modem\n * @param {String} id Task's ID\n */\nvar Task = function(modem, id) {\n this.modem = modem;\n this.id = id;\n\n this.defaultOptions = {\n log: {}\n };\n};\n\nTask.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for Task details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nTask.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/tasks/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'unknown task',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Task logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nTask.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.log);\n\n var optsf = {\n path: '/tasks/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 101: true,\n 200: true,\n 404: 'no such container',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Task;\n","var DockerIgnore = require('@balena/dockerignore');\nvar fs = require('fs');\nvar path = require('path');\nvar tar = require('tar-fs');\nvar zlib = require('zlib');\n\n// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js\n\nvar arr = [];\nvar each = arr.forEach;\nvar slice = arr.slice;\n\nmodule.exports.extend = function(obj) {\n each.call(slice.call(arguments, 1), function(source) {\n if (source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\nmodule.exports.processArgs = function(opts, callback, defaultOpts) {\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n return {\n callback: callback,\n opts: module.exports.extend({}, defaultOpts, opts)\n };\n};\n\n\n/**\n * Parse the given repo tag name (as a string) and break it out into repo/tag pair.\n * // if given the input http://localhost:8080/woot:latest\n * {\n * repository: 'http://localhost:8080/woot',\n * tag: 'latest'\n * }\n * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest'\n * @return {Object} input parsed into the repo and tag.\n */\nmodule.exports.parseRepositoryTag = function(input) {\n var separatorPos;\n var digestPos = input.indexOf('@');\n var colonPos = input.lastIndexOf(':');\n // @ symbol is more important\n if (digestPos >= 0) {\n separatorPos = digestPos;\n } else if (colonPos >= 0) {\n separatorPos = colonPos;\n } else {\n // no colon nor @\n return {\n repository: input\n };\n }\n\n // last colon is either the tag (or part of a port designation)\n var tag = input.slice(separatorPos + 1);\n\n // if it contains a / its not a tag and is part of the url\n if (tag.indexOf('/') === -1) {\n return {\n repository: input.slice(0, separatorPos),\n tag: tag\n };\n }\n\n return {\n repository: input\n };\n};\n\n\nmodule.exports.prepareBuildContext = function(file, next) {\n if (file && file.context) {\n fs.readFile(path.join(file.context, '.dockerignore'), (err, data) => {\n let ignoreFn;\n let filterFn;\n\n if (!err) {\n const dockerIgnore = DockerIgnore({ ignorecase: false }).add(data.toString());\n\n filterFn = dockerIgnore.createFilter();\n ignoreFn = (path) => {\n return !filterFn(path);\n }\n }\n\n const entries = file.src.slice() || []\n\n const pack = tar.pack(file.context, {\n entries: filterFn ? entries.filter(filterFn) : entries,\n ignore: ignoreFn // Only works on directories\n });\n\n next(pack.pipe(zlib.createGzip()));\n })\n } else {\n next(file);\n }\n}\n","var util = require('./util');\n\n/**\n * Represents a volume\n * @param {Object} modem docker-modem\n * @param {String} name Volume's name\n */\nvar Volume = function(modem, name) {\n this.modem = modem;\n this.name = name;\n};\n\nVolume.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nVolume.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/' + this.name,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such volume',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the volume\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nVolume.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/' + this.name,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 204: true,\n 404: 'no such volume',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Volume;\n","var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n","module.exports = require('fs').constants || require('constants')\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","var path = require('path');\nvar fs = require('fs');\nvar _0777 = parseInt('0777', 8);\n\nmodule.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;\n\nfunction mkdirP (p, opts, f, made) {\n if (typeof opts === 'function') {\n f = opts;\n opts = {};\n }\n else if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n \n var mode = opts.mode;\n var xfs = opts.fs || fs;\n \n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made) made = null;\n \n var cb = f || function () {};\n p = path.resolve(p);\n \n xfs.mkdir(p, mode, function (er) {\n if (!er) {\n made = made || p;\n return cb(null, made);\n }\n switch (er.code) {\n case 'ENOENT':\n mkdirP(path.dirname(p), opts, function (er, made) {\n if (er) cb(er, made);\n else mkdirP(p, opts, cb, made);\n });\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n xfs.stat(p, function (er2, stat) {\n // if the stat fails, then that's super weird.\n // let the original error be the failure reason.\n if (er2 || !stat.isDirectory()) cb(er, made)\n else cb(null, made);\n });\n break;\n }\n });\n}\n\nmkdirP.sync = function sync (p, opts, made) {\n if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n \n var mode = opts.mode;\n var xfs = opts.fs || fs;\n \n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made) made = null;\n\n p = path.resolve(p);\n\n try {\n xfs.mkdirSync(p, mode);\n made = made || p;\n }\n catch (err0) {\n switch (err0.code) {\n case 'ENOENT' :\n made = sync(path.dirname(p), opts, made);\n sync(p, opts, made);\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n var stat;\n try {\n stat = xfs.statSync(p);\n }\n catch (err1) {\n throw err0;\n }\n if (!stat.isDirectory()) throw err0;\n break;\n }\n }\n\n return made;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n","var once = require('once')\nvar eos = require('end-of-stream')\nvar fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes\n\nvar noop = function () {}\nvar ancient = /^v?\\.0/.test(process.version)\n\nvar isFn = function (fn) {\n return typeof fn === 'function'\n}\n\nvar isFS = function (stream) {\n if (!ancient) return false // newer node version do not need to care about fs is a special way\n if (!fs) return false // browser\n return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)\n}\n\nvar isRequest = function (stream) {\n return stream.setHeader && isFn(stream.abort)\n}\n\nvar destroyer = function (stream, reading, writing, callback) {\n callback = once(callback)\n\n var closed = false\n stream.on('close', function () {\n closed = true\n })\n\n eos(stream, {readable: reading, writable: writing}, function (err) {\n if (err) return callback(err)\n closed = true\n callback()\n })\n\n var destroyed = false\n return function (err) {\n if (closed) return\n if (destroyed) return\n destroyed = true\n\n if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks\n if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want\n\n if (isFn(stream.destroy)) return stream.destroy()\n\n callback(err || new Error('stream was destroyed'))\n }\n}\n\nvar call = function (fn) {\n fn()\n}\n\nvar pipe = function (from, to) {\n return from.pipe(to)\n}\n\nvar pump = function () {\n var streams = Array.prototype.slice.call(arguments)\n var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop\n\n if (Array.isArray(streams[0])) streams = streams[0]\n if (streams.length < 2) throw new Error('pump requires two streams per minimum')\n\n var error\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1\n var writing = i > 0\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err\n if (err) destroys.forEach(call)\n if (reading) return\n destroys.forEach(call)\n callback(error)\n })\n })\n\n return streams.reduce(pipe)\n}\n\nmodule.exports = pump\n","'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};","'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;","'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();","'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;","'use strict';\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;\n\nfunction from(Readable, iterable, opts) {\n var iterator;\n\n if (iterable && typeof iterable.next === 'function') {\n iterator = iterable;\n } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);\n\n var readable = new Readable(_objectSpread({\n objectMode: true\n }, opts)); // Reading boolean to protect against _read\n // being called before last iteration completion.\n\n var reading = false;\n\n readable._read = function () {\n if (!reading) {\n reading = true;\n next();\n }\n };\n\n function next() {\n return _next2.apply(this, arguments);\n }\n\n function _next2() {\n _next2 = _asyncToGenerator(function* () {\n try {\n var _ref = yield iterator.next(),\n value = _ref.value,\n done = _ref.done;\n\n if (done) {\n readable.push(null);\n } else if (readable.push((yield value))) {\n next();\n } else {\n reading = false;\n }\n } catch (err) {\n readable.destroy(err);\n }\n });\n return _next2.apply(this, arguments);\n }\n\n return readable;\n}\n\nmodule.exports = from;","// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\n\n var error;\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1;\n var writing = i > 0;\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err;\n if (err) destroys.forEach(call);\n if (reading) return;\n destroys.forEach(call);\n callback(error);\n });\n });\n return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;","'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};","module.exports = require('stream');\n","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n","/* eslint-disable node/no-deprecated-api */\n\n'use strict'\n\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\nvar safer = {}\n\nvar key\n\nfor (key in buffer) {\n if (!buffer.hasOwnProperty(key)) continue\n if (key === 'SlowBuffer' || key === 'Buffer') continue\n safer[key] = buffer[key]\n}\n\nvar Safer = safer.Buffer = {}\nfor (key in Buffer) {\n if (!Buffer.hasOwnProperty(key)) continue\n if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue\n Safer[key] = Buffer[key]\n}\n\nsafer.Buffer.prototype = Buffer.prototype\n\nif (!Safer.from || Safer.from === Uint8Array.from) {\n Safer.from = function (value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('The \"value\" argument must not be of type number. Received type ' + typeof value)\n }\n if (value && typeof value.length === 'undefined') {\n throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)\n }\n return Buffer(value, encodingOrOffset, length)\n }\n}\n\nif (!Safer.alloc) {\n Safer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('The \"size\" argument must be of type number. Received type ' + typeof size)\n }\n if (size < 0 || size >= 2 * (1 << 30)) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n var buf = Buffer(size)\n if (!fill || fill.length === 0) {\n buf.fill(0)\n } else if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n return buf\n }\n}\n\nif (!safer.kStringMaxLength) {\n try {\n safer.kStringMaxLength = process.binding('buffer').kStringMaxLength\n } catch (e) {\n // we can't determine kStringMaxLength in environments where process.binding\n // is unsupported, so let's not set it\n }\n}\n\nif (!safer.constants) {\n safer.constants = {\n MAX_LENGTH: safer.kMaxLength\n }\n if (safer.kStringMaxLength) {\n safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength\n }\n}\n\nmodule.exports = safer\n","var fs = require('fs');\n\nmodule.exports = function (filepath, split, encoding) {\n split = typeof split !== 'undefined' ? split : \"\\n\";\n encoding = typeof encoding !== 'undefined' ? encoding : \"utf8\";\n\n var ca = [];\n var chain = fs.readFileSync(filepath, encoding);\n if(chain.indexOf(\"-END CERTIFICATE-\") < 0 || chain.indexOf(\"-BEGIN CERTIFICATE-\") < 0){\n throw Error(\"File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'\");\n }\n chain = chain.split(split);\n var cert = [];\n var _i, _len;\n for (_i = 0, _len = chain.length; _i < _len; _i++) {\n var line = chain[_i];\n if (!(line.length !== 0)) {\n continue;\n }\n cert.push(line);\n if (line.match(/-END CERTIFICATE-/)) {\n ca.push(cert.join(split));\n cert = [];\n }\n }\n return ca;\n}\n","'use strict';\n\nconst {\n Duplex: DuplexStream,\n Readable: ReadableStream,\n Writable: WritableStream,\n} = require('stream');\n\nconst {\n CHANNEL_EXTENDED_DATATYPE: { STDERR },\n} = require('./protocol/constants.js');\nconst { bufferSlice } = require('./protocol/utils.js');\n\nconst PACKET_SIZE = 32 * 1024;\nconst MAX_WINDOW = 2 * 1024 * 1024;\nconst WINDOW_THRESHOLD = MAX_WINDOW / 2;\n\nclass ClientStderr extends ReadableStream {\n constructor(channel, streamOpts) {\n super(streamOpts);\n\n this._channel = channel;\n }\n _read(n) {\n if (this._channel._waitChanDrain) {\n this._channel._waitChanDrain = false;\n if (this._channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(this._channel);\n }\n }\n}\n\nclass ServerStderr extends WritableStream {\n constructor(channel) {\n super({ highWaterMark: MAX_WINDOW });\n\n this._channel = channel;\n }\n\n _write(data, encoding, cb) {\n const channel = this._channel;\n const protocol = channel._client._protocol;\n const outgoing = channel.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelExtData(id, data, STDERR);\n else\n protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR);\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n channel._waitWindow = true;\n if (p > 0)\n channel._chunkErr = bufferSlice(data, p, len);\n else\n channel._chunkErr = data;\n channel._chunkcbErr = cb;\n return;\n }\n\n cb();\n }\n}\n\nclass Channel extends DuplexStream {\n constructor(client, info, opts) {\n const streamOpts = {\n highWaterMark: MAX_WINDOW,\n allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)),\n emitClose: false,\n };\n super(streamOpts);\n this.allowHalfOpen = streamOpts.allowHalfOpen;\n\n const server = !!(opts && opts.server);\n\n this.server = server;\n this.type = info.type;\n this.subtype = undefined;\n\n /*\n incoming and outgoing contain these properties:\n {\n id: undefined,\n window: undefined,\n packetSize: undefined,\n state: 'closed'\n }\n */\n this.incoming = info.incoming;\n this.outgoing = info.outgoing;\n this._callbacks = [];\n\n this._client = client;\n this._hasX11 = false;\n this._exit = {\n code: undefined,\n signal: undefined,\n dump: undefined,\n desc: undefined,\n };\n\n this.stdin = this.stdout = this;\n\n if (server)\n this.stderr = new ServerStderr(this);\n else\n this.stderr = new ClientStderr(this, streamOpts);\n\n // Outgoing data\n this._waitWindow = false; // SSH-level backpressure\n\n // Incoming data\n this._waitChanDrain = false; // Channel Readable side backpressure\n\n this._chunk = undefined;\n this._chunkcb = undefined;\n this._chunkErr = undefined;\n this._chunkcbErr = undefined;\n\n this.on('finish', onFinish)\n .on('prefinish', onFinish); // For node v0.11+\n\n this.on('end', onEnd).on('close', onEnd);\n }\n\n _read(n) {\n if (this._waitChanDrain) {\n this._waitChanDrain = false;\n if (this.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(this);\n }\n }\n\n _write(data, encoding, cb) {\n const protocol = this._client._protocol;\n const outgoing = this.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelData(id, data);\n else\n protocol.channelData(id, bufferSlice(data, p, p + sliceLen));\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n this._waitWindow = true;\n if (p > 0)\n this._chunk = bufferSlice(data, p, len);\n else\n this._chunk = data;\n this._chunkcb = cb;\n return;\n }\n\n cb();\n }\n\n eof() {\n if (this.outgoing.state === 'open') {\n this.outgoing.state = 'eof';\n this._client._protocol.channelEOF(this.outgoing.id);\n }\n }\n\n close() {\n if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {\n this.outgoing.state = 'closing';\n this._client._protocol.channelClose(this.outgoing.id);\n }\n }\n\n destroy() {\n this.end();\n this.close();\n return this;\n }\n\n // Session type-specific methods =============================================\n setWindow(rows, cols, height, width) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && (this.subtype === 'shell' || this.subtype === 'exec')\n && this.writable\n && this.outgoing.state === 'open') {\n this._client._protocol.windowChange(this.outgoing.id,\n rows,\n cols,\n height,\n width);\n }\n }\n\n signal(signalName) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open') {\n this._client._protocol.signal(this.outgoing.id, signalName);\n }\n }\n\n exit(statusOrSignal, coreDumped, msg) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open') {\n if (typeof statusOrSignal === 'number') {\n this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal);\n } else {\n this._client._protocol.exitSignal(this.outgoing.id,\n statusOrSignal,\n coreDumped,\n msg);\n }\n }\n }\n\n}\n\nfunction onFinish() {\n this.eof();\n if (this.server || !this.allowHalfOpen)\n this.close();\n this.writable = false;\n}\n\nfunction onEnd() {\n this.readable = false;\n}\n\nfunction windowAdjust(self) {\n if (self.outgoing.state === 'closed')\n return;\n const amt = MAX_WINDOW - self.incoming.window;\n if (amt <= 0)\n return;\n self.incoming.window += amt;\n self._client._protocol.channelWindowAdjust(self.outgoing.id, amt);\n}\n\nmodule.exports = {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n};\n",null,"// TODO:\n// * add `.connected` or similar property to allow immediate connection\n// status checking\n// * add/improve debug output during user authentication phase\n'use strict';\n\nconst {\n createHash,\n getHashes,\n randomFillSync,\n} = require('crypto');\nconst { Socket } = require('net');\nconst { lookup: dnsLookup } = require('dns');\nconst EventEmitter = require('events');\nconst HASHES = getHashes();\n\nconst {\n COMPAT,\n CHANNEL_EXTENDED_DATATYPE: { STDERR },\n CHANNEL_OPEN_FAILURE,\n DEFAULT_CIPHER,\n DEFAULT_COMPRESSION,\n DEFAULT_KEX,\n DEFAULT_MAC,\n DEFAULT_SERVER_HOST_KEY,\n DISCONNECT_REASON,\n DISCONNECT_REASON_BY_VALUE,\n SUPPORTED_CIPHER,\n SUPPORTED_COMPRESSION,\n SUPPORTED_KEX,\n SUPPORTED_MAC,\n SUPPORTED_SERVER_HOST_KEY,\n} = require('./protocol/constants.js');\nconst { init: cryptoInit } = require('./protocol/crypto.js');\nconst Protocol = require('./protocol/Protocol.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst { SFTP } = require('./protocol/SFTP.js');\nconst {\n bufferCopy,\n makeBufferParser,\n makeError,\n readUInt32BE,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./protocol/utils.js');\n\nconst { AgentContext, createAgent, isAgent } = require('./agent.js');\nconst {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n} = require('./Channel.js');\nconst {\n ChannelManager,\n generateAlgorithmList,\n isWritable,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n} = require('./utils.js');\n\nconst bufferParser = makeBufferParser();\nconst sigParser = makeBufferParser();\nconst RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\\d)|(?:\\d{2,})/;\nconst noop = (err) => {};\n\nclass Client extends EventEmitter {\n constructor() {\n super();\n\n this.config = {\n host: undefined,\n port: undefined,\n localAddress: undefined,\n localPort: undefined,\n forceIPv4: undefined,\n forceIPv6: undefined,\n keepaliveCountMax: undefined,\n keepaliveInterval: undefined,\n readyTimeout: undefined,\n ident: undefined,\n\n username: undefined,\n password: undefined,\n privateKey: undefined,\n tryKeyboard: undefined,\n agent: undefined,\n allowAgentFwd: undefined,\n authHandler: undefined,\n\n hostHashAlgo: undefined,\n hostHashCb: undefined,\n strictVendor: undefined,\n debug: undefined\n };\n\n this._agent = undefined;\n this._readyTimeout = undefined;\n this._chanMgr = undefined;\n this._callbacks = undefined;\n this._forwarding = undefined;\n this._forwardingUnix = undefined;\n this._acceptX11 = undefined;\n this._agentFwdEnabled = undefined;\n this._remoteVer = undefined;\n\n this._protocol = undefined;\n this._sock = undefined;\n this._resetKA = undefined;\n }\n\n connect(cfg) {\n if (this._sock && isWritable(this._sock)) {\n this.once('close', () => {\n this.connect(cfg);\n });\n this.end();\n return this;\n }\n\n this.config.host = cfg.hostname || cfg.host || 'localhost';\n this.config.port = cfg.port || 22;\n this.config.localAddress = (typeof cfg.localAddress === 'string'\n ? cfg.localAddress\n : undefined);\n this.config.localPort = (typeof cfg.localPort === 'string'\n || typeof cfg.localPort === 'number'\n ? cfg.localPort\n : undefined);\n this.config.forceIPv4 = cfg.forceIPv4 || false;\n this.config.forceIPv6 = cfg.forceIPv6 || false;\n this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number'\n && cfg.keepaliveCountMax >= 0\n ? cfg.keepaliveCountMax\n : 3);\n this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number'\n && cfg.keepaliveInterval > 0\n ? cfg.keepaliveInterval\n : 0);\n this.config.readyTimeout = (typeof cfg.readyTimeout === 'number'\n && cfg.readyTimeout >= 0\n ? cfg.readyTimeout\n : 20000);\n this.config.ident = (typeof cfg.ident === 'string'\n || Buffer.isBuffer(cfg.ident)\n ? cfg.ident\n : undefined);\n\n const algorithms = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: [],\n },\n sc: undefined,\n };\n let allOfferDefaults = true;\n if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) {\n algorithms.kex = generateAlgorithmList(cfg.algorithms.kex,\n DEFAULT_KEX,\n SUPPORTED_KEX);\n if (algorithms.kex !== DEFAULT_KEX)\n allOfferDefaults = false;\n\n algorithms.serverHostKey =\n generateAlgorithmList(cfg.algorithms.serverHostKey,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY);\n if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY)\n allOfferDefaults = false;\n\n algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER);\n if (algorithms.cs.cipher !== DEFAULT_CIPHER)\n allOfferDefaults = false;\n\n algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac,\n DEFAULT_MAC,\n SUPPORTED_MAC);\n if (algorithms.cs.mac !== DEFAULT_MAC)\n allOfferDefaults = false;\n\n algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION);\n if (algorithms.cs.compress !== DEFAULT_COMPRESSION)\n allOfferDefaults = false;\n\n if (!allOfferDefaults)\n algorithms.sc = algorithms.cs;\n }\n\n if (typeof cfg.username === 'string')\n this.config.username = cfg.username;\n else if (typeof cfg.user === 'string')\n this.config.username = cfg.user;\n else\n throw new Error('Invalid username');\n\n this.config.password = (typeof cfg.password === 'string'\n ? cfg.password\n : undefined);\n this.config.privateKey = (typeof cfg.privateKey === 'string'\n || Buffer.isBuffer(cfg.privateKey)\n ? cfg.privateKey\n : undefined);\n this.config.localHostname = (typeof cfg.localHostname === 'string'\n ? cfg.localHostname\n : undefined);\n this.config.localUsername = (typeof cfg.localUsername === 'string'\n ? cfg.localUsername\n : undefined);\n this.config.tryKeyboard = (cfg.tryKeyboard === true);\n if (typeof cfg.agent === 'string' && cfg.agent.length)\n this.config.agent = createAgent(cfg.agent);\n else if (isAgent(cfg.agent))\n this.config.agent = cfg.agent;\n else\n this.config.agent = undefined;\n this.config.allowAgentFwd = (cfg.agentForward === true\n && this.config.agent !== undefined);\n let authHandler = this.config.authHandler = (\n typeof cfg.authHandler === 'function'\n || Array.isArray(cfg.authHandler)\n ? cfg.authHandler\n : undefined\n );\n\n this.config.strictVendor = (typeof cfg.strictVendor === 'boolean'\n ? cfg.strictVendor\n : true);\n\n const debug = this.config.debug = (typeof cfg.debug === 'function'\n ? cfg.debug\n : undefined);\n\n if (cfg.agentForward === true && !this.config.allowAgentFwd) {\n throw new Error(\n 'You must set a valid agent path to allow agent forwarding'\n );\n }\n\n let callbacks = this._callbacks = [];\n this._chanMgr = new ChannelManager(this);\n this._forwarding = {};\n this._forwardingUnix = {};\n this._acceptX11 = 0;\n this._agentFwdEnabled = false;\n this._agent = (this.config.agent ? this.config.agent : undefined);\n this._remoteVer = undefined;\n let privateKey;\n\n if (this.config.privateKey) {\n privateKey = parseKey(this.config.privateKey, cfg.passphrase);\n if (privateKey instanceof Error)\n throw new Error(`Cannot parse privateKey: ${privateKey.message}`);\n if (Array.isArray(privateKey)) {\n // OpenSSH's newer format only stores 1 key for now\n privateKey = privateKey[0];\n }\n if (privateKey.getPrivatePEM() === null) {\n throw new Error(\n 'privateKey value does not contain a (valid) private key'\n );\n }\n }\n\n let hostVerifier;\n if (typeof cfg.hostVerifier === 'function') {\n const hashCb = cfg.hostVerifier;\n let hasher;\n if (HASHES.indexOf(cfg.hostHash) !== -1) {\n // Default to old behavior of hashing on user's behalf\n hasher = createHash(cfg.hostHash);\n }\n hostVerifier = (key, verify) => {\n if (hasher) {\n hasher.update(key);\n key = hasher.digest('hex');\n }\n const ret = hashCb(key, verify);\n if (ret !== undefined)\n verify(ret);\n };\n }\n\n const sock = this._sock = (cfg.sock || new Socket());\n let ready = false;\n let sawHeader = false;\n if (this._protocol)\n this._protocol.cleanup();\n const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {\n debug(`Debug output from server: ${JSON.stringify(msg)}`);\n });\n let serverSigAlgs;\n const proto = this._protocol = new Protocol({\n ident: this.config.ident,\n offer: (allOfferDefaults ? undefined : algorithms),\n onWrite: (data) => {\n if (isWritable(sock))\n sock.write(data);\n },\n onError: (err) => {\n if (err.level === 'handshake')\n clearTimeout(this._readyTimeout);\n if (!proto._destruct)\n sock.removeAllListeners('data');\n this.emit('error', err);\n try {\n sock.end();\n } catch {}\n },\n onHeader: (header) => {\n sawHeader = true;\n this._remoteVer = header.versions.software;\n if (header.greeting)\n this.emit('greeting', header.greeting);\n },\n onHandshakeComplete: (negotiated) => {\n this.emit('handshake', negotiated);\n if (!ready) {\n ready = true;\n proto.service('ssh-userauth');\n }\n },\n debug,\n hostVerifier,\n messageHandlers: {\n DEBUG: DEBUG_HANDLER,\n DISCONNECT: (p, reason, desc) => {\n if (reason !== DISCONNECT_REASON.BY_APPLICATION) {\n if (!desc) {\n desc = DISCONNECT_REASON_BY_VALUE[reason];\n if (desc === undefined)\n desc = `Unexpected disconnection reason: ${reason}`;\n }\n const err = new Error(desc);\n err.code = reason;\n this.emit('error', err);\n }\n sock.end();\n },\n SERVICE_ACCEPT: (p, name) => {\n if (name === 'ssh-userauth')\n tryNextAuth();\n },\n EXT_INFO: (p, exts) => {\n if (serverSigAlgs === undefined) {\n for (const ext of exts) {\n if (ext.name === 'server-sig-algs') {\n serverSigAlgs = ext.algs;\n return;\n }\n }\n serverSigAlgs = null;\n }\n },\n USERAUTH_BANNER: (p, msg) => {\n this.emit('banner', msg);\n },\n USERAUTH_SUCCESS: (p) => {\n // Start keepalive mechanism\n resetKA();\n\n clearTimeout(this._readyTimeout);\n\n this.emit('ready');\n },\n USERAUTH_FAILURE: (p, authMethods, partialSuccess) => {\n // For key-based authentication, check if we should retry the current\n // key with a different algorithm first\n if (curAuth.keyAlgos) {\n const oldKeyAlgo = curAuth.keyAlgos[0][0];\n if (debug)\n debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`);\n curAuth.keyAlgos.shift();\n if (curAuth.keyAlgos.length) {\n const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0];\n switch (curAuth.type) {\n case 'agent':\n proto.authPK(\n curAuth.username,\n curAuth.agentCtx.currentKey(),\n keyAlgo\n );\n return;\n case 'publickey':\n proto.authPK(curAuth.username, curAuth.key, keyAlgo);\n return;\n case 'hostbased':\n proto.authHostbased(curAuth.username,\n curAuth.key,\n curAuth.localHostname,\n curAuth.localUsername,\n keyAlgo,\n (buf, cb) => {\n const signature = curAuth.key.sign(buf, hashAlgo);\n if (signature instanceof Error) {\n signature.message =\n `Error while signing with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n\n cb(signature);\n });\n return;\n }\n } else {\n curAuth.keyAlgos = undefined;\n }\n }\n\n if (curAuth.type === 'agent') {\n const pos = curAuth.agentCtx.pos();\n debug && debug(`Client: Agent key #${pos + 1} failed`);\n return tryNextAgentKey();\n }\n\n debug && debug(`Client: ${curAuth.type} auth failed`);\n\n curPartial = partialSuccess;\n curAuthsLeft = authMethods;\n tryNextAuth();\n },\n USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => {\n if (curAuth.type === 'password') {\n // TODO: support a `changePrompt()` on `curAuth` that defaults to\n // emitting 'change password' as before\n this.emit('change password', prompt, (newPassword) => {\n proto.authPassword(\n this.config.username,\n this.config.password,\n newPassword\n );\n });\n }\n },\n USERAUTH_PK_OK: (p) => {\n let keyAlgo;\n let hashAlgo;\n if (curAuth.keyAlgos)\n [keyAlgo, hashAlgo] = curAuth.keyAlgos[0];\n if (curAuth.type === 'agent') {\n const key = curAuth.agentCtx.currentKey();\n proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => {\n const opts = { hash: hashAlgo };\n curAuth.agentCtx.sign(key, buf, opts, (err, signed) => {\n if (err) {\n err.level = 'agent';\n this.emit('error', err);\n } else {\n return cb(signed);\n }\n\n tryNextAgentKey();\n });\n });\n } else if (curAuth.type === 'publickey') {\n proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => {\n const signature = curAuth.key.sign(buf, hashAlgo);\n if (signature instanceof Error) {\n signature.message =\n `Error signing data with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n cb(signature);\n });\n }\n },\n USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => {\n if (curAuth.type === 'keyboard-interactive') {\n const nprompts = (Array.isArray(prompts) ? prompts.length : 0);\n if (nprompts === 0) {\n debug && debug(\n 'Client: Sending automatic USERAUTH_INFO_RESPONSE'\n );\n proto.authInfoRes();\n return;\n }\n // We sent a keyboard-interactive user authentication request and\n // now the server is sending us the prompts we need to present to\n // the user\n curAuth.prompt(\n name,\n instructions,\n '',\n prompts,\n (answers) => {\n proto.authInfoRes(answers);\n }\n );\n }\n },\n REQUEST_SUCCESS: (p, data) => {\n if (callbacks.length)\n callbacks.shift()(false, data);\n },\n REQUEST_FAILURE: (p) => {\n if (callbacks.length)\n callbacks.shift()(true);\n },\n GLOBAL_REQUEST: (p, name, wantReply, data) => {\n switch (name) {\n case 'hostkeys-00@openssh.com':\n // Automatically verify keys before passing to end user\n hostKeysProve(this, data, (err, keys) => {\n if (err)\n return;\n this.emit('hostkeys', keys);\n });\n if (wantReply)\n proto.requestSuccess();\n break;\n default:\n // Auto-reject all other global requests, this can be especially\n // useful if the server is sending us dummy keepalive global\n // requests\n if (wantReply)\n proto.requestFailure();\n }\n },\n CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from server, typically a forwarded TCP or\n // X11 connection\n onCHANNEL_OPEN(this, info);\n },\n CHANNEL_OPEN_CONFIRMATION: (p, info) => {\n const channel = this._chanMgr.get(info.recipient);\n if (typeof channel !== 'function')\n return;\n\n const isSFTP = (channel.type === 'sftp');\n const type = (isSFTP ? 'session' : channel.type);\n const chanInfo = {\n type,\n incoming: {\n id: info.recipient,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const instance = (\n isSFTP\n ? new SFTP(this, chanInfo, { debug })\n : new Channel(this, chanInfo)\n );\n this._chanMgr.update(info.recipient, instance);\n channel(undefined, instance);\n },\n CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },\n CHANNEL_DATA: (p, recipient, data) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n if (type !== STDERR)\n return;\n\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (!channel.stderr.push(data)) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },\n CHANNEL_SUCCESS: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n this._resetKA();\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(false);\n },\n CHANNEL_FAILURE: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n this._resetKA();\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },\n CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n const exit = channel._exit;\n if (exit.code !== undefined)\n return;\n switch (type) {\n case 'exit-status':\n channel.emit('exit', exit.code = data);\n return;\n case 'exit-signal':\n channel.emit('exit',\n exit.code = null,\n exit.signal = `SIG${data.signal}`,\n exit.dump = data.coreDumped,\n exit.desc = data.errorMessage);\n return;\n }\n\n // Keepalive request? OpenSSH will send one as a channel request if\n // there is a channel open\n\n if (wantReply)\n p.channelFailure(channel.outgoing.id);\n },\n CHANNEL_EOF: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.incoming.state !== 'open')\n return;\n channel.incoming.state = 'eof';\n\n if (channel.readable)\n channel.push(null);\n if (channel.stderr.readable)\n channel.stderr.push(null);\n },\n CHANNEL_CLOSE: (p, recipient) => {\n onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient));\n },\n },\n });\n\n sock.pause();\n\n // TODO: check keepalive implementation\n // Keepalive-related\n const kainterval = this.config.keepaliveInterval;\n const kacountmax = this.config.keepaliveCountMax;\n let kacount = 0;\n let katimer;\n const sendKA = () => {\n if (++kacount > kacountmax) {\n clearInterval(katimer);\n if (sock.readable) {\n const err = new Error('Keepalive timeout');\n err.level = 'client-timeout';\n this.emit('error', err);\n sock.destroy();\n }\n return;\n }\n if (isWritable(sock)) {\n // Append dummy callback to keep correct callback order\n callbacks.push(resetKA);\n proto.ping();\n } else {\n clearInterval(katimer);\n }\n };\n function resetKA() {\n if (kainterval > 0) {\n kacount = 0;\n clearInterval(katimer);\n if (isWritable(sock))\n katimer = setInterval(sendKA, kainterval);\n }\n }\n this._resetKA = resetKA;\n\n const onDone = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n if (wasConnected && !sawHeader) {\n const err =\n makeError('Connection lost before handshake', 'protocol', true);\n this.emit('error', err);\n }\n };\n })();\n const onConnect = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n\n wasConnected = true;\n debug && debug('Socket connected');\n this.emit('connect');\n\n cryptoInit.then(() => {\n proto.start();\n sock.on('data', (data) => {\n try {\n proto.parse(data, 0, data.length);\n } catch (ex) {\n this.emit('error', ex);\n try {\n if (isWritable(sock))\n sock.end();\n } catch {}\n }\n });\n\n // Drain stderr if we are connection hopping using an exec stream\n if (sock.stderr && typeof sock.stderr.resume === 'function')\n sock.stderr.resume();\n\n sock.resume();\n }).catch((err) => {\n this.emit('error', err);\n try {\n if (isWritable(sock))\n sock.end();\n } catch {}\n });\n };\n })();\n let wasConnected = false;\n sock.on('connect', onConnect)\n .on('timeout', () => {\n this.emit('timeout');\n }).on('error', (err) => {\n debug && debug(`Socket error: ${err.message}`);\n clearTimeout(this._readyTimeout);\n err.level = 'client-socket';\n this.emit('error', err);\n }).on('end', () => {\n debug && debug('Socket ended');\n onDone();\n proto.cleanup();\n clearTimeout(this._readyTimeout);\n clearInterval(katimer);\n this.emit('end');\n }).on('close', () => {\n debug && debug('Socket closed');\n onDone();\n proto.cleanup();\n clearTimeout(this._readyTimeout);\n clearInterval(katimer);\n this.emit('close');\n\n // Notify outstanding channel requests of disconnection ...\n const callbacks_ = callbacks;\n callbacks = this._callbacks = [];\n const err = new Error('No response from server');\n for (let i = 0; i < callbacks_.length; ++i)\n callbacks_[i](err);\n\n // Simulate error for any channels waiting to be opened\n this._chanMgr.cleanup(err);\n });\n\n // Begin authentication handling ===========================================\n let curAuth;\n let curPartial = null;\n let curAuthsLeft = null;\n const authsAllowed = ['none'];\n if (this.config.password !== undefined)\n authsAllowed.push('password');\n if (privateKey !== undefined)\n authsAllowed.push('publickey');\n if (this._agent !== undefined)\n authsAllowed.push('agent');\n if (this.config.tryKeyboard)\n authsAllowed.push('keyboard-interactive');\n if (privateKey !== undefined\n && this.config.localHostname !== undefined\n && this.config.localUsername !== undefined) {\n authsAllowed.push('hostbased');\n }\n\n if (Array.isArray(authHandler))\n authHandler = makeSimpleAuthHandler(authHandler);\n else if (typeof authHandler !== 'function')\n authHandler = makeSimpleAuthHandler(authsAllowed);\n\n let hasSentAuth = false;\n const doNextAuth = (nextAuth) => {\n if (hasSentAuth)\n return;\n hasSentAuth = true;\n\n if (nextAuth === false) {\n const err = new Error('All configured authentication methods failed');\n err.level = 'client-authentication';\n this.emit('error', err);\n this.end();\n return;\n }\n\n if (typeof nextAuth === 'string') {\n // Remain backwards compatible with original `authHandler()` usage,\n // which only supported passing names of next method to try using data\n // from the `connect()` config object\n\n const type = nextAuth;\n if (authsAllowed.indexOf(type) === -1)\n return skipAuth(`Authentication method not allowed: ${type}`);\n\n const username = this.config.username;\n switch (type) {\n case 'password':\n nextAuth = { type, username, password: this.config.password };\n break;\n case 'publickey':\n nextAuth = { type, username, key: privateKey };\n break;\n case 'hostbased':\n nextAuth = {\n type,\n username,\n key: privateKey,\n localHostname: this.config.localHostname,\n localUsername: this.config.localUsername,\n };\n break;\n case 'agent':\n nextAuth = {\n type,\n username,\n agentCtx: new AgentContext(this._agent),\n };\n break;\n case 'keyboard-interactive':\n nextAuth = {\n type,\n username,\n prompt: (...args) => this.emit('keyboard-interactive', ...args),\n };\n break;\n case 'none':\n nextAuth = { type, username };\n break;\n default:\n return skipAuth(\n `Skipping unsupported authentication method: ${nextAuth}`\n );\n }\n } else if (typeof nextAuth !== 'object' || nextAuth === null) {\n return skipAuth(\n `Skipping invalid authentication attempt: ${nextAuth}`\n );\n } else {\n const username = nextAuth.username;\n if (typeof username !== 'string') {\n return skipAuth(\n `Skipping invalid authentication attempt: ${nextAuth}`\n );\n }\n const type = nextAuth.type;\n switch (type) {\n case 'password': {\n const { password } = nextAuth;\n if (typeof password !== 'string' && !Buffer.isBuffer(password))\n return skipAuth('Skipping invalid password auth attempt');\n nextAuth = { type, username, password };\n break;\n }\n case 'publickey': {\n const key = parseKey(nextAuth.key, nextAuth.passphrase);\n if (key instanceof Error)\n return skipAuth('Skipping invalid key auth attempt');\n if (!key.isPrivateKey())\n return skipAuth('Skipping non-private key');\n nextAuth = { type, username, key };\n break;\n }\n case 'hostbased': {\n const { localHostname, localUsername } = nextAuth;\n const key = parseKey(nextAuth.key, nextAuth.passphrase);\n if (key instanceof Error\n || typeof localHostname !== 'string'\n || typeof localUsername !== 'string') {\n return skipAuth('Skipping invalid hostbased auth attempt');\n }\n if (!key.isPrivateKey())\n return skipAuth('Skipping non-private key');\n nextAuth = { type, username, key, localHostname, localUsername };\n break;\n }\n case 'agent': {\n let agent = nextAuth.agent;\n if (typeof agent === 'string' && agent.length) {\n agent = createAgent(agent);\n } else if (!isAgent(agent)) {\n return skipAuth(\n `Skipping invalid agent: ${nextAuth.agent}`\n );\n }\n nextAuth = { type, username, agentCtx: new AgentContext(agent) };\n break;\n }\n case 'keyboard-interactive': {\n const { prompt } = nextAuth;\n if (typeof prompt !== 'function') {\n return skipAuth(\n 'Skipping invalid keyboard-interactive auth attempt'\n );\n }\n nextAuth = { type, username, prompt };\n break;\n }\n case 'none':\n nextAuth = { type, username };\n break;\n default:\n return skipAuth(\n `Skipping unsupported authentication method: ${nextAuth}`\n );\n }\n }\n curAuth = nextAuth;\n\n // Begin authentication method's process\n try {\n const username = curAuth.username;\n switch (curAuth.type) {\n case 'password':\n proto.authPassword(username, curAuth.password);\n break;\n case 'publickey': {\n let keyAlgo;\n curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs);\n if (curAuth.keyAlgos) {\n if (curAuth.keyAlgos.length) {\n keyAlgo = curAuth.keyAlgos[0][0];\n } else {\n return skipAuth(\n 'Skipping key authentication (no mutual hash algorithm)'\n );\n }\n }\n proto.authPK(username, curAuth.key, keyAlgo);\n break;\n }\n case 'hostbased': {\n let keyAlgo;\n let hashAlgo;\n curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs);\n if (curAuth.keyAlgos) {\n if (curAuth.keyAlgos.length) {\n [keyAlgo, hashAlgo] = curAuth.keyAlgos[0];\n } else {\n return skipAuth(\n 'Skipping hostbased authentication (no mutual hash algorithm)'\n );\n }\n }\n\n proto.authHostbased(username,\n curAuth.key,\n curAuth.localHostname,\n curAuth.localUsername,\n keyAlgo,\n (buf, cb) => {\n const signature = curAuth.key.sign(buf, hashAlgo);\n if (signature instanceof Error) {\n signature.message =\n `Error while signing with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n\n cb(signature);\n });\n break;\n }\n case 'agent':\n curAuth.agentCtx.init((err) => {\n if (err) {\n err.level = 'agent';\n this.emit('error', err);\n return tryNextAuth();\n }\n tryNextAgentKey();\n });\n break;\n case 'keyboard-interactive':\n proto.authKeyboard(username);\n break;\n case 'none':\n proto.authNone(username);\n break;\n }\n } finally {\n hasSentAuth = false;\n }\n };\n\n function skipAuth(msg) {\n debug && debug(msg);\n process.nextTick(tryNextAuth);\n }\n\n function tryNextAuth() {\n hasSentAuth = false;\n const auth = authHandler(curAuthsLeft, curPartial, doNextAuth);\n if (hasSentAuth || auth === undefined)\n return;\n doNextAuth(auth);\n }\n\n const tryNextAgentKey = () => {\n if (curAuth.type === 'agent') {\n const key = curAuth.agentCtx.nextKey();\n if (key === false) {\n debug && debug('Agent: No more keys left to try');\n debug && debug('Client: agent auth failed');\n tryNextAuth();\n } else {\n const pos = curAuth.agentCtx.pos();\n let keyAlgo;\n curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs);\n if (curAuth.keyAlgos) {\n if (curAuth.keyAlgos.length) {\n keyAlgo = curAuth.keyAlgos[0][0];\n } else {\n debug && debug(\n `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)`\n );\n tryNextAgentKey();\n return;\n }\n }\n debug && debug(`Agent: Trying key #${pos + 1}`);\n proto.authPK(curAuth.username, key, keyAlgo);\n }\n }\n };\n\n const startTimeout = () => {\n if (this.config.readyTimeout > 0) {\n this._readyTimeout = setTimeout(() => {\n const err = new Error('Timed out while waiting for handshake');\n err.level = 'client-timeout';\n this.emit('error', err);\n sock.destroy();\n }, this.config.readyTimeout);\n }\n };\n\n if (!cfg.sock) {\n let host = this.config.host;\n const forceIPv4 = this.config.forceIPv4;\n const forceIPv6 = this.config.forceIPv6;\n\n debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`);\n\n const doConnect = () => {\n startTimeout();\n sock.connect({\n host,\n port: this.config.port,\n localAddress: this.config.localAddress,\n localPort: this.config.localPort\n });\n sock.setMaxListeners(0);\n sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0);\n };\n\n if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) {\n doConnect();\n } else {\n dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => {\n if (err) {\n const type = (forceIPv4 ? 'IPv4' : 'IPv6');\n const error = new Error(\n `Error while looking up ${type} address for '${host}': ${err}`\n );\n clearTimeout(this._readyTimeout);\n error.level = 'client-dns';\n this.emit('error', error);\n this.emit('close');\n return;\n }\n host = address;\n doConnect();\n });\n }\n } else {\n // Custom socket passed in\n startTimeout();\n if (typeof sock.connecting === 'boolean') {\n // net.Socket\n\n if (!sock.connecting) {\n // Already connected\n onConnect();\n }\n } else {\n // Assume socket/stream is already \"connected\"\n onConnect();\n }\n }\n\n return this;\n }\n\n end() {\n if (this._sock && isWritable(this._sock)) {\n this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n this._sock.end();\n }\n return this;\n }\n\n destroy() {\n this._sock && isWritable(this._sock) && this._sock.destroy();\n return this;\n }\n\n exec(cmd, opts, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) };\n\n openChannel(this, 'session', extraOpts, (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n const todo = [];\n\n function reqCb(err) {\n if (err) {\n chan.close();\n cb(err);\n return;\n }\n if (todo.length)\n todo.shift()();\n }\n\n if (this.config.allowAgentFwd === true\n || (opts\n && opts.agentForward === true\n && this._agent !== undefined)) {\n todo.push(() => reqAgentFwd(chan, reqCb));\n }\n\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.env === 'object' && opts.env !== null)\n reqEnv(chan, opts.env);\n if ((typeof opts.pty === 'object' && opts.pty !== null)\n || opts.pty === true) {\n todo.push(() => reqPty(chan, opts.pty, reqCb));\n }\n if ((typeof opts.x11 === 'object' && opts.x11 !== null)\n || opts.x11 === 'number'\n || opts.x11 === true) {\n todo.push(() => reqX11(chan, opts.x11, reqCb));\n }\n }\n\n todo.push(() => reqExec(chan, cmd, opts, cb));\n todo.shift()();\n });\n\n return this;\n }\n\n shell(wndopts, opts, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof wndopts === 'function') {\n cb = wndopts;\n wndopts = opts = undefined;\n } else if (typeof opts === 'function') {\n cb = opts;\n opts = undefined;\n }\n if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) {\n opts = wndopts;\n wndopts = undefined;\n }\n\n openChannel(this, 'session', (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n const todo = [];\n\n function reqCb(err) {\n if (err) {\n chan.close();\n cb(err);\n return;\n }\n if (todo.length)\n todo.shift()();\n }\n\n if (this.config.allowAgentFwd === true\n || (opts\n && opts.agentForward === true\n && this._agent !== undefined)) {\n todo.push(() => reqAgentFwd(chan, reqCb));\n }\n\n if (wndopts !== false)\n todo.push(() => reqPty(chan, wndopts, reqCb));\n\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.env === 'object' && opts.env !== null)\n reqEnv(chan, opts.env);\n if ((typeof opts.x11 === 'object' && opts.x11 !== null)\n || opts.x11 === 'number'\n || opts.x11 === true) {\n todo.push(() => reqX11(chan, opts.x11, reqCb));\n }\n }\n\n todo.push(() => reqShell(chan, cb));\n todo.shift()();\n });\n\n return this;\n }\n\n subsys(name, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n openChannel(this, 'session', (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n reqSubsystem(chan, name, (err, stream) => {\n if (err) {\n cb(err);\n return;\n }\n\n cb(undefined, stream);\n });\n });\n\n return this;\n }\n\n forwardIn(bindAddr, bindPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request for the server to start forwarding TCP connections to us\n // on a particular address and port\n\n const wantReply = (typeof cb === 'function');\n\n if (wantReply) {\n this._callbacks.push((had_err, data) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${bindAddr}:${bindPort}`));\n return;\n }\n\n let realPort = bindPort;\n if (bindPort === 0 && data && data.length >= 4) {\n realPort = readUInt32BE(data, 0);\n if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG))\n bindPort = realPort;\n }\n\n this._forwarding[`${bindAddr}:${bindPort}`] = realPort;\n\n cb(undefined, realPort);\n });\n }\n\n this._protocol.tcpipForward(bindAddr, bindPort, wantReply);\n\n return this;\n }\n\n unforwardIn(bindAddr, bindPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request to stop forwarding us new connections for a particular\n // address and port\n\n const wantReply = (typeof cb === 'function');\n\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`));\n return;\n }\n\n delete this._forwarding[`${bindAddr}:${bindPort}`];\n\n cb();\n });\n }\n\n this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply);\n\n return this;\n }\n\n forwardOut(srcIP, srcPort, dstIP, dstPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request to forward a TCP connection to the server\n\n const cfg = {\n srcIP: srcIP,\n srcPort: srcPort,\n dstIP: dstIP,\n dstPort: dstPort\n };\n\n if (typeof cb !== 'function')\n cb = noop;\n\n openChannel(this, 'direct-tcpip', cfg, cb);\n\n return this;\n }\n\n openssh_noMoreSessions(cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to disable future sessions'));\n return;\n }\n\n cb();\n });\n }\n\n this._protocol.openssh_noMoreSessions(wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_forwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${socketPath}`));\n return;\n }\n this._forwardingUnix[socketPath] = true;\n cb();\n });\n }\n\n this._protocol.openssh_streamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_unforwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to unbind from ${socketPath}`));\n return;\n }\n delete this._forwardingUnix[socketPath];\n cb();\n });\n }\n\n this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_forwardOutStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof cb !== 'function')\n cb = noop;\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb);\n return this;\n }\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n sftp(cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n openChannel(this, 'sftp', (err, sftp) => {\n if (err) {\n cb(err);\n return;\n }\n\n reqSubsystem(sftp, 'sftp', (err, sftp_) => {\n if (err) {\n cb(err);\n return;\n }\n\n function removeListeners() {\n sftp.removeListener('ready', onReady);\n sftp.removeListener('error', onError);\n sftp.removeListener('exit', onExit);\n sftp.removeListener('close', onExit);\n }\n\n function onReady() {\n // TODO: do not remove exit/close in case remote end closes the\n // channel abruptly and we need to notify outstanding callbacks\n removeListeners();\n cb(undefined, sftp);\n }\n\n function onError(err) {\n removeListeners();\n cb(err);\n }\n\n function onExit(code, signal) {\n removeListeners();\n let msg;\n if (typeof code === 'number')\n msg = `Received exit code ${code} while establishing SFTP session`;\n else if (signal !== undefined)\n msg = `Received signal ${signal} while establishing SFTP session`;\n else\n msg = 'Received unexpected SFTP session termination';\n const err = new Error(msg);\n err.code = code;\n err.signal = signal;\n cb(err);\n }\n\n sftp.on('ready', onReady)\n .on('error', onError)\n .on('exit', onExit)\n .on('close', onExit);\n\n sftp._init();\n });\n });\n\n return this;\n }\n\n setNoDelay(noDelay) {\n if (this._sock && typeof this._sock.setNoDelay === 'function')\n this._sock.setNoDelay(noDelay);\n\n return this;\n }\n}\n\nfunction openChannel(self, type, opts, cb) {\n // Ask the server to open a channel for some purpose\n // (e.g. session (sftp, exec, shell), or forwarding a TCP connection\n const initWindow = MAX_WINDOW;\n const maxPacket = PACKET_SIZE;\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const wrapper = (err, stream) => {\n cb(err, stream);\n };\n wrapper.type = type;\n\n const localChan = self._chanMgr.add(wrapper);\n\n if (localChan === -1) {\n cb(new Error('No free channels available'));\n return;\n }\n\n switch (type) {\n case 'session':\n case 'sftp':\n self._protocol.session(localChan, initWindow, maxPacket);\n break;\n case 'direct-tcpip':\n self._protocol.directTcpip(localChan, initWindow, maxPacket, opts);\n break;\n case 'direct-streamlocal@openssh.com':\n self._protocol.openssh_directStreamLocal(\n localChan, initWindow, maxPacket, opts\n );\n break;\n default:\n throw new Error(`Unsupported channel type: ${type}`);\n }\n}\n\nfunction reqX11(chan, screen, cb) {\n // Asks server to start sending us X11 connections\n const cfg = {\n single: false,\n protocol: 'MIT-MAGIC-COOKIE-1',\n cookie: undefined,\n screen: 0\n };\n\n if (typeof screen === 'function') {\n cb = screen;\n } else if (typeof screen === 'object' && screen !== null) {\n if (typeof screen.single === 'boolean')\n cfg.single = screen.single;\n if (typeof screen.screen === 'number')\n cfg.screen = screen.screen;\n if (typeof screen.protocol === 'string')\n cfg.protocol = screen.protocol;\n if (typeof screen.cookie === 'string')\n cfg.cookie = screen.cookie;\n else if (Buffer.isBuffer(screen.cookie))\n cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length);\n }\n if (cfg.cookie === undefined)\n cfg.cookie = randomCookie();\n\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n if (wantReply)\n cb(new Error('Channel is not open'));\n return;\n }\n\n if (wantReply) {\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to request X11'));\n return;\n }\n\n chan._hasX11 = true;\n ++chan._client._acceptX11;\n chan.once('close', () => {\n if (chan._client._acceptX11)\n --chan._client._acceptX11;\n });\n\n cb();\n });\n }\n\n chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply);\n}\n\nfunction reqPty(chan, opts, cb) {\n let rows = 24;\n let cols = 80;\n let width = 640;\n let height = 480;\n let term = 'vt100';\n let modes = null;\n\n if (typeof opts === 'function') {\n cb = opts;\n } else if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.rows === 'number')\n rows = opts.rows;\n if (typeof opts.cols === 'number')\n cols = opts.cols;\n if (typeof opts.width === 'number')\n width = opts.width;\n if (typeof opts.height === 'number')\n height = opts.height;\n if (typeof opts.term === 'string')\n term = opts.term;\n if (typeof opts.modes === 'object')\n modes = opts.modes;\n }\n\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n if (wantReply)\n cb(new Error('Channel is not open'));\n return;\n }\n\n if (wantReply) {\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to request a pseudo-terminal'));\n return;\n }\n cb();\n });\n }\n\n chan._client._protocol.pty(chan.outgoing.id,\n rows,\n cols,\n height,\n width,\n term,\n modes,\n wantReply);\n}\n\nfunction reqAgentFwd(chan, cb) {\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n wantReply && cb(new Error('Channel is not open'));\n return;\n }\n if (chan._client._agentFwdEnabled) {\n wantReply && cb(false);\n return;\n }\n\n chan._client._agentFwdEnabled = true;\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n chan._client._agentFwdEnabled = false;\n if (wantReply) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to request agent forwarding'));\n }\n return;\n }\n\n if (wantReply)\n cb();\n });\n\n chan._client._protocol.openssh_agentForward(chan.outgoing.id, true);\n}\n\nfunction reqShell(chan, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to open shell'));\n return;\n }\n chan.subtype = 'shell';\n cb(undefined, chan);\n });\n\n chan._client._protocol.shell(chan.outgoing.id, true);\n}\n\nfunction reqExec(chan, cmd, opts, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to exec'));\n return;\n }\n chan.subtype = 'exec';\n chan.allowHalfOpen = (opts.allowHalfOpen !== false);\n cb(undefined, chan);\n });\n\n chan._client._protocol.exec(chan.outgoing.id, cmd, true);\n}\n\nfunction reqEnv(chan, env) {\n if (chan.outgoing.state !== 'open')\n return;\n\n const keys = Object.keys(env || {});\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n const val = env[key];\n chan._client._protocol.env(chan.outgoing.id, key, val, false);\n }\n}\n\nfunction reqSubsystem(chan, name, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to start subsystem: ${name}`));\n return;\n }\n chan.subtype = 'subsystem';\n cb(undefined, chan);\n });\n\n chan._client._protocol.subsystem(chan.outgoing.id, name, true);\n}\n\n// TODO: inline implementation into single call site\nfunction onCHANNEL_OPEN(self, info) {\n // The server is trying to open a channel with us, this is usually when\n // we asked the server to forward us connections on some port and now they\n // are asking us to accept/deny an incoming connection on their side\n\n let localChan = -1;\n let reason;\n\n const accept = () => {\n const chanInfo = {\n type: info.type,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const stream = new Channel(self, chanInfo);\n self._chanMgr.update(localChan, stream);\n\n self._protocol.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n return stream;\n };\n const reject = () => {\n if (reason === undefined) {\n if (localChan === -1)\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n else\n reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;\n }\n\n if (localChan !== -1)\n self._chanMgr.remove(localChan);\n\n self._protocol.channelOpenFail(info.sender, reason, '');\n };\n const reserveChannel = () => {\n localChan = self._chanMgr.add();\n\n if (localChan === -1) {\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of incoming channel open: '\n + 'no channels available'\n );\n }\n }\n\n return (localChan !== -1);\n };\n\n const data = info.data;\n switch (info.type) {\n case 'forwarded-tcpip': {\n const val = self._forwarding[`${data.destIP}:${data.destPort}`];\n if (val !== undefined && reserveChannel()) {\n if (data.destPort === 0)\n data.destPort = val;\n self.emit('tcp connection', data, accept, reject);\n return;\n }\n break;\n }\n case 'forwarded-streamlocal@openssh.com':\n if (self._forwardingUnix[data.socketPath] !== undefined\n && reserveChannel()) {\n self.emit('unix connection', data, accept, reject);\n return;\n }\n break;\n case 'auth-agent@openssh.com':\n if (self._agentFwdEnabled\n && typeof self._agent.getStream === 'function'\n && reserveChannel()) {\n self._agent.getStream((err, stream) => {\n if (err)\n return reject();\n\n const upstream = accept();\n upstream.pipe(stream).pipe(upstream);\n });\n return;\n }\n break;\n case 'x11':\n if (self._acceptX11 !== 0 && reserveChannel()) {\n self.emit('x11', data, accept, reject);\n return;\n }\n break;\n default:\n // Automatically reject any unsupported channel open requests\n reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of unsupported incoming channel open '\n + `type: ${info.type}`\n );\n }\n }\n\n if (reason === undefined) {\n reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of unexpected incoming channel open for: '\n + info.type\n );\n }\n }\n\n reject();\n}\n\nconst randomCookie = (() => {\n const buffer = Buffer.allocUnsafe(16);\n return () => {\n randomFillSync(buffer, 0, 16);\n return buffer.hexSlice(0, 16);\n };\n})();\n\nfunction makeSimpleAuthHandler(authList) {\n if (!Array.isArray(authList))\n throw new Error('authList must be an array');\n\n let a = 0;\n return (authsLeft, partialSuccess, cb) => {\n if (a === authList.length)\n return false;\n return authList[a++];\n };\n}\n\nfunction hostKeysProve(client, keys_, cb) {\n if (!client._sock || !isWritable(client._sock))\n return;\n\n if (typeof cb !== 'function')\n cb = noop;\n\n if (!Array.isArray(keys_))\n throw new TypeError('Invalid keys argument type');\n\n const keys = [];\n for (const key of keys_) {\n const parsed = parseKey(key);\n if (parsed instanceof Error)\n throw parsed;\n keys.push(parsed);\n }\n\n if (!client.config.strictVendor\n || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) {\n client._callbacks.push((had_err, data) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Server failed to prove supplied keys'));\n return;\n }\n\n // TODO: move all of this parsing/verifying logic out of the client?\n const ret = [];\n let keyIdx = 0;\n bufferParser.init(data, 0);\n while (bufferParser.avail()) {\n if (keyIdx === keys.length)\n break;\n const key = keys[keyIdx++];\n const keyPublic = key.getPublicSSH();\n\n const sigEntry = bufferParser.readString();\n sigParser.init(sigEntry, 0);\n const type = sigParser.readString(true);\n let value = sigParser.readString();\n\n let algo;\n if (type !== key.type) {\n if (key.type === 'ssh-rsa') {\n switch (type) {\n case 'rsa-sha2-256':\n algo = 'sha256';\n break;\n case 'rsa-sha2-512':\n algo = 'sha512';\n break;\n default:\n continue;\n }\n } else {\n continue;\n }\n }\n\n const sessionID = client._protocol._kex.sessionID;\n const verifyData = Buffer.allocUnsafe(\n 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length\n );\n let p = 0;\n writeUInt32BE(verifyData, 29, p);\n verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);\n writeUInt32BE(verifyData, sessionID.length, p += 29);\n bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4);\n writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length);\n bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4);\n\n if (!(value = sigSSHToASN1(value, type)))\n continue;\n if (key.verify(verifyData, value, algo) === true)\n ret.push(key);\n }\n sigParser.clear();\n bufferParser.clear();\n\n cb(null, ret);\n });\n\n client._protocol.openssh_hostKeysProve(keys);\n return;\n }\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n}\n\nfunction getKeyAlgos(client, key, serverSigAlgs) {\n switch (key.type) {\n case 'ssh-rsa':\n if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) {\n if (!Array.isArray(serverSigAlgs))\n serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512'];\n else\n serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512', ...serverSigAlgs];\n }\n if (Array.isArray(serverSigAlgs)) {\n if (serverSigAlgs.indexOf('rsa-sha2-256') !== -1)\n return [['rsa-sha2-256', 'sha256']];\n if (serverSigAlgs.indexOf('rsa-sha2-512') !== -1)\n return [['rsa-sha2-512', 'sha512']];\n if (serverSigAlgs.indexOf('ssh-rsa') === -1)\n return [];\n }\n return [['ssh-rsa', 'sha1']];\n }\n}\n\nmodule.exports = Client;\n","'use strict';\n\nconst { Agent: HttpAgent } = require('http');\nconst { Agent: HttpsAgent } = require('https');\nconst { connect: tlsConnect } = require('tls');\n\nlet Client;\n\nfor (const ctor of [HttpAgent, HttpsAgent]) {\n class SSHAgent extends ctor {\n constructor(connectCfg, agentOptions) {\n super(agentOptions);\n\n this._connectCfg = connectCfg;\n this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost';\n }\n\n createConnection(options, cb) {\n const srcIP = (options && options.localAddress) || this._defaultSrcIP;\n const srcPort = (options && options.localPort) || 0;\n const dstIP = options.host;\n const dstPort = options.port;\n\n if (Client === undefined)\n Client = require('./client.js');\n\n const client = new Client();\n let triedForward = false;\n client.on('ready', () => {\n client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => {\n triedForward = true;\n if (err) {\n client.end();\n return cb(err);\n }\n stream.once('close', () => client.end());\n cb(null, decorateStream(stream, ctor, options));\n });\n }).on('error', cb).on('close', () => {\n if (!triedForward)\n cb(new Error('Unexpected connection close'));\n }).connect(this._connectCfg);\n }\n }\n\n exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent;\n}\n\nfunction noop() {}\n\nfunction decorateStream(stream, ctor, options) {\n if (ctor === HttpAgent) {\n // HTTP\n stream.setKeepAlive = noop;\n stream.setNoDelay = noop;\n stream.setTimeout = noop;\n stream.ref = noop;\n stream.unref = noop;\n stream.destroySoon = stream.destroy;\n return stream;\n }\n\n // HTTPS\n options.socket = stream;\n const wrapped = tlsConnect(options);\n\n // This is a workaround for a regression in node v12.16.3+\n // https://github.com/nodejs/node/issues/35904\n const onClose = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n if (stream.isPaused())\n stream.resume();\n };\n })();\n // 'end' listener is needed because 'close' is not emitted in some scenarios\n // in node v12.x for some unknown reason\n wrapped.on('end', onClose).on('close', onClose);\n\n return wrapped;\n}\n","'use strict';\n\nconst {\n AgentProtocol,\n BaseAgent,\n createAgent,\n CygwinAgent,\n OpenSSHAgent,\n PageantAgent,\n} = require('./agent.js');\nconst {\n SSHTTPAgent: HTTPAgent,\n SSHTTPSAgent: HTTPSAgent,\n} = require('./http-agents.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst {\n flagsToString,\n OPEN_MODE,\n STATUS_CODE,\n stringToFlags,\n} = require('./protocol/SFTP.js');\n\nmodule.exports = {\n AgentProtocol,\n BaseAgent,\n createAgent,\n Client: require('./client.js'),\n CygwinAgent,\n HTTPAgent,\n HTTPSAgent,\n OpenSSHAgent,\n PageantAgent,\n Server: require('./server.js'),\n utils: {\n parseKey,\n ...require('./keygen.js'),\n sftp: {\n flagsToString,\n OPEN_MODE,\n STATUS_CODE,\n stringToFlags,\n },\n },\n};\n","'use strict';\n\nconst {\n createCipheriv,\n generateKeyPair: generateKeyPair_,\n generateKeyPairSync: generateKeyPairSync_,\n getCurves,\n randomBytes,\n} = require('crypto');\n\nconst { Ber } = require('asn1');\nconst bcrypt_pbkdf = require('bcrypt-pbkdf').pbkdf;\n\nconst { CIPHER_INFO } = require('./protocol/crypto.js');\n\nconst SALT_LEN = 16;\nconst DEFAULT_ROUNDS = 16;\n\nconst curves = getCurves();\nconst ciphers = new Map(Object.entries(CIPHER_INFO));\n\nfunction makeArgs(type, opts) {\n if (typeof type !== 'string')\n throw new TypeError('Key type must be a string');\n\n const publicKeyEncoding = { type: 'spki', format: 'der' };\n const privateKeyEncoding = { type: 'pkcs8', format: 'der' };\n\n switch (type.toLowerCase()) {\n case 'rsa': {\n if (typeof opts !== 'object' || opts === null)\n throw new TypeError('Missing options object for RSA key');\n const modulusLength = opts.bits;\n if (!Number.isInteger(modulusLength))\n throw new TypeError('RSA bits must be an integer');\n if (modulusLength <= 0 || modulusLength > 16384)\n throw new RangeError('RSA bits must be non-zero and <= 16384');\n return ['rsa', { modulusLength, publicKeyEncoding, privateKeyEncoding }];\n }\n case 'ecdsa': {\n if (typeof opts !== 'object' || opts === null)\n throw new TypeError('Missing options object for ECDSA key');\n if (!Number.isInteger(opts.bits))\n throw new TypeError('ECDSA bits must be an integer');\n let namedCurve;\n switch (opts.bits) {\n case 256:\n namedCurve = 'prime256v1';\n break;\n case 384:\n namedCurve = 'secp384r1';\n break;\n case 521:\n namedCurve = 'secp521r1';\n break;\n default:\n throw new Error('ECDSA bits must be 256, 384, or 521');\n }\n if (!curves.includes(namedCurve))\n throw new Error('Unsupported ECDSA bits value');\n return ['ec', { namedCurve, publicKeyEncoding, privateKeyEncoding }];\n }\n case 'ed25519':\n return ['ed25519', { publicKeyEncoding, privateKeyEncoding }];\n default:\n throw new Error(`Unsupported key type: ${type}`);\n }\n}\n\nfunction parseDERs(keyType, pub, priv) {\n switch (keyType) {\n case 'rsa': {\n // Note: we don't need to parse the public key since the PKCS8 private key\n // already includes the public key parameters\n\n // Parse private key\n let reader = new Ber.Reader(priv);\n reader.readSequence();\n\n // - Version\n if (reader.readInt() !== 0)\n throw new Error('Unsupported version in RSA private key');\n\n // - Algorithm\n reader.readSequence();\n if (reader.readOID() !== '1.2.840.113549.1.1.1')\n throw new Error('Bad RSA private OID');\n // - Algorithm parameters (RSA has none)\n if (reader.readByte() !== Ber.Null)\n throw new Error('Malformed RSA private key (expected null)');\n if (reader.readByte() !== 0x00) {\n throw new Error(\n 'Malformed RSA private key (expected zero-length null)'\n );\n }\n\n reader = new Ber.Reader(reader.readString(Ber.OctetString, true));\n reader.readSequence();\n if (reader.readInt() !== 0)\n throw new Error('Unsupported version in RSA private key');\n const n = reader.readString(Ber.Integer, true);\n const e = reader.readString(Ber.Integer, true);\n const d = reader.readString(Ber.Integer, true);\n const p = reader.readString(Ber.Integer, true);\n const q = reader.readString(Ber.Integer, true);\n reader.readString(Ber.Integer, true); // dmp1\n reader.readString(Ber.Integer, true); // dmq1\n const iqmp = reader.readString(Ber.Integer, true);\n\n /*\n OpenSSH RSA private key:\n string \"ssh-rsa\"\n string n -- public\n string e -- public\n string d -- private\n string iqmp -- private\n string p -- private\n string q -- private\n */\n const keyName = Buffer.from('ssh-rsa');\n const privBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + n.length\n + 4 + e.length\n + 4 + d.length\n + 4 + iqmp.length\n + 4 + p.length\n + 4 + q.length\n );\n let pos = 0;\n\n privBuf.writeUInt32BE(keyName.length, pos += 0);\n privBuf.set(keyName, pos += 4);\n privBuf.writeUInt32BE(n.length, pos += keyName.length);\n privBuf.set(n, pos += 4);\n privBuf.writeUInt32BE(e.length, pos += n.length);\n privBuf.set(e, pos += 4);\n privBuf.writeUInt32BE(d.length, pos += e.length);\n privBuf.set(d, pos += 4);\n privBuf.writeUInt32BE(iqmp.length, pos += d.length);\n privBuf.set(iqmp, pos += 4);\n privBuf.writeUInt32BE(p.length, pos += iqmp.length);\n privBuf.set(p, pos += 4);\n privBuf.writeUInt32BE(q.length, pos += p.length);\n privBuf.set(q, pos += 4);\n\n /*\n OpenSSH RSA public key:\n string \"ssh-rsa\"\n string e -- public\n string n -- public\n */\n const pubBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + e.length\n + 4 + n.length\n );\n pos = 0;\n\n pubBuf.writeUInt32BE(keyName.length, pos += 0);\n pubBuf.set(keyName, pos += 4);\n pubBuf.writeUInt32BE(e.length, pos += keyName.length);\n pubBuf.set(e, pos += 4);\n pubBuf.writeUInt32BE(n.length, pos += e.length);\n pubBuf.set(n, pos += 4);\n\n return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf };\n }\n case 'ec': {\n // Parse public key\n let reader = new Ber.Reader(pub);\n reader.readSequence();\n\n reader.readSequence();\n if (reader.readOID() !== '1.2.840.10045.2.1')\n throw new Error('Bad ECDSA public OID');\n // Skip curve OID, we'll get it from the private key\n reader.readOID();\n let pubBin = reader.readString(Ber.BitString, true);\n {\n // Remove leading zero bytes\n let i = 0;\n for (; i < pubBin.length && pubBin[i] === 0x00; ++i);\n if (i > 0)\n pubBin = pubBin.slice(i);\n }\n\n // Parse private key\n reader = new Ber.Reader(priv);\n reader.readSequence();\n\n // - Version\n if (reader.readInt() !== 0)\n throw new Error('Unsupported version in ECDSA private key');\n\n reader.readSequence();\n if (reader.readOID() !== '1.2.840.10045.2.1')\n throw new Error('Bad ECDSA private OID');\n const curveOID = reader.readOID();\n let sshCurveName;\n switch (curveOID) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n sshCurveName = 'nistp256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n sshCurveName = 'nistp384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n sshCurveName = 'nistp521';\n break;\n default:\n throw new Error('Unsupported curve in ECDSA private key');\n }\n\n reader = new Ber.Reader(reader.readString(Ber.OctetString, true));\n reader.readSequence();\n\n // - Version\n if (reader.readInt() !== 1)\n throw new Error('Unsupported version in ECDSA private key');\n\n // Add leading zero byte to prevent negative bignum in private key\n const privBin = Buffer.concat([\n Buffer.from([0x00]),\n reader.readString(Ber.OctetString, true)\n ]);\n\n /*\n OpenSSH ECDSA private key:\n string \"ecdsa-sha2-\"\n string curve name\n string Q -- public\n string d -- private\n */\n const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`);\n sshCurveName = Buffer.from(sshCurveName);\n const privBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + sshCurveName.length\n + 4 + pubBin.length\n + 4 + privBin.length\n );\n let pos = 0;\n\n privBuf.writeUInt32BE(keyName.length, pos += 0);\n privBuf.set(keyName, pos += 4);\n privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length);\n privBuf.set(sshCurveName, pos += 4);\n privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length);\n privBuf.set(pubBin, pos += 4);\n privBuf.writeUInt32BE(privBin.length, pos += pubBin.length);\n privBuf.set(privBin, pos += 4);\n\n /*\n OpenSSH ECDSA public key:\n string \"ecdsa-sha2-\"\n string curve name\n string Q -- public\n */\n const pubBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + sshCurveName.length\n + 4 + pubBin.length\n );\n pos = 0;\n\n pubBuf.writeUInt32BE(keyName.length, pos += 0);\n pubBuf.set(keyName, pos += 4);\n pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length);\n pubBuf.set(sshCurveName, pos += 4);\n pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length);\n pubBuf.set(pubBin, pos += 4);\n\n return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf };\n }\n case 'ed25519': {\n // Parse public key\n let reader = new Ber.Reader(pub);\n reader.readSequence();\n\n // - Algorithm\n reader.readSequence();\n if (reader.readOID() !== '1.3.101.112')\n throw new Error('Bad ED25519 public OID');\n // - Attributes (absent for ED25519)\n\n let pubBin = reader.readString(Ber.BitString, true);\n {\n // Remove leading zero bytes\n let i = 0;\n for (; i < pubBin.length && pubBin[i] === 0x00; ++i);\n if (i > 0)\n pubBin = pubBin.slice(i);\n }\n\n // Parse private key\n reader = new Ber.Reader(priv);\n reader.readSequence();\n\n // - Version\n if (reader.readInt() !== 0)\n throw new Error('Unsupported version in ED25519 private key');\n\n // - Algorithm\n reader.readSequence();\n if (reader.readOID() !== '1.3.101.112')\n throw new Error('Bad ED25519 private OID');\n // - Attributes (absent)\n\n reader = new Ber.Reader(reader.readString(Ber.OctetString, true));\n const privBin = reader.readString(Ber.OctetString, true);\n\n /*\n OpenSSH ed25519 private key:\n string \"ssh-ed25519\"\n string public key\n string private key + public key\n */\n const keyName = Buffer.from('ssh-ed25519');\n const privBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + pubBin.length\n + 4 + (privBin.length + pubBin.length)\n );\n let pos = 0;\n\n privBuf.writeUInt32BE(keyName.length, pos += 0);\n privBuf.set(keyName, pos += 4);\n privBuf.writeUInt32BE(pubBin.length, pos += keyName.length);\n privBuf.set(pubBin, pos += 4);\n privBuf.writeUInt32BE(\n privBin.length + pubBin.length,\n pos += pubBin.length\n );\n privBuf.set(privBin, pos += 4);\n privBuf.set(pubBin, pos += privBin.length);\n\n /*\n OpenSSH ed25519 public key:\n string \"ssh-ed25519\"\n string public key\n */\n const pubBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + pubBin.length\n );\n pos = 0;\n\n pubBuf.writeUInt32BE(keyName.length, pos += 0);\n pubBuf.set(keyName, pos += 4);\n pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length);\n pubBuf.set(pubBin, pos += 4);\n\n return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf };\n }\n }\n}\n\nfunction convertKeys(keyType, pub, priv, opts) {\n let format = 'new';\n let encrypted;\n let comment = '';\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.comment === 'string' && opts.comment)\n comment = opts.comment;\n if (typeof opts.format === 'string' && opts.format)\n format = opts.format;\n if (opts.passphrase) {\n let passphrase;\n if (typeof opts.passphrase === 'string')\n passphrase = Buffer.from(opts.passphrase);\n else if (Buffer.isBuffer(opts.passphrase))\n passphrase = opts.passphrase;\n else\n throw new Error('Invalid passphrase');\n\n if (opts.cipher === undefined)\n throw new Error('Missing cipher name');\n const cipher = ciphers.get(opts.cipher);\n if (cipher === undefined)\n throw new Error('Invalid cipher name');\n\n if (format === 'new') {\n let rounds = DEFAULT_ROUNDS;\n if (opts.rounds !== undefined) {\n if (!Number.isInteger(opts.rounds))\n throw new TypeError('rounds must be an integer');\n if (opts.rounds > 0)\n rounds = opts.rounds;\n }\n\n const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen);\n const salt = randomBytes(SALT_LEN);\n const r = bcrypt_pbkdf(\n passphrase,\n passphrase.length,\n salt,\n salt.length,\n gen,\n gen.length,\n rounds\n );\n if (r !== 0)\n return new Error('Failed to generate information to encrypt key');\n\n /*\n string salt\n uint32 rounds\n */\n const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4);\n {\n let pos = 0;\n kdfOptions.writeUInt32BE(salt.length, pos += 0);\n kdfOptions.set(salt, pos += 4);\n kdfOptions.writeUInt32BE(rounds, pos += salt.length);\n }\n\n encrypted = {\n cipher,\n cipherName: opts.cipher,\n kdfName: 'bcrypt',\n kdfOptions,\n key: gen.slice(0, cipher.keyLen),\n iv: gen.slice(cipher.keyLen),\n };\n }\n }\n }\n\n switch (format) {\n case 'new': {\n let privateB64 = '-----BEGIN OPENSSH PRIVATE KEY-----\\n';\n let publicB64;\n /*\n byte[] \"openssh-key-v1\\0\"\n string ciphername\n string kdfname\n string kdfoptions\n uint32 number of keys N\n string publickey1\n string encrypted, padded list of private keys\n uint32 checkint\n uint32 checkint\n byte[] privatekey1\n string comment1\n byte 1\n byte 2\n byte 3\n ...\n byte padlen % 255\n */\n const cipherName = Buffer.from(encrypted ? encrypted.cipherName : 'none');\n const kdfName = Buffer.from(encrypted ? encrypted.kdfName : 'none');\n const kdfOptions = (encrypted ? encrypted.kdfOptions : Buffer.alloc(0));\n const blockLen = (encrypted ? encrypted.cipher.blockLen : 8);\n\n const parsed = parseDERs(keyType, pub, priv);\n\n const checkInt = randomBytes(4);\n const commentBin = Buffer.from(comment);\n const privBlobLen = (4 + 4 + parsed.priv.length + 4 + commentBin.length);\n let padding = [];\n for (let i = 1; ((privBlobLen + padding.length) % blockLen); ++i)\n padding.push(i & 0xFF);\n padding = Buffer.from(padding);\n\n let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length);\n let extra;\n {\n let pos = 0;\n privBlob.set(checkInt, pos += 0);\n privBlob.set(checkInt, pos += 4);\n privBlob.set(parsed.priv, pos += 4);\n privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length);\n privBlob.set(commentBin, pos += 4);\n privBlob.set(padding, pos += commentBin.length);\n }\n\n if (encrypted) {\n const options = { authTagLength: encrypted.cipher.authLen };\n const cipher = createCipheriv(\n encrypted.cipher.sslName,\n encrypted.key,\n encrypted.iv,\n options\n );\n cipher.setAutoPadding(false);\n privBlob = Buffer.concat([ cipher.update(privBlob), cipher.final() ]);\n if (encrypted.cipher.authLen > 0)\n extra = cipher.getAuthTag();\n else\n extra = Buffer.alloc(0);\n encrypted.key.fill(0);\n encrypted.iv.fill(0);\n } else {\n extra = Buffer.alloc(0);\n }\n\n const magicBytes = Buffer.from('openssh-key-v1\\0');\n const privBin = Buffer.allocUnsafe(\n magicBytes.length\n + 4 + cipherName.length\n + 4 + kdfName.length\n + 4 + kdfOptions.length\n + 4\n + 4 + parsed.pub.length\n + 4 + privBlob.length\n + extra.length\n );\n {\n let pos = 0;\n privBin.set(magicBytes, pos += 0);\n privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length);\n privBin.set(cipherName, pos += 4);\n privBin.writeUInt32BE(kdfName.length, pos += cipherName.length);\n privBin.set(kdfName, pos += 4);\n privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length);\n privBin.set(kdfOptions, pos += 4);\n privBin.writeUInt32BE(1, pos += kdfOptions.length);\n privBin.writeUInt32BE(parsed.pub.length, pos += 4);\n privBin.set(parsed.pub, pos += 4);\n privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length);\n privBin.set(privBlob, pos += 4);\n privBin.set(extra, pos += privBlob.length);\n }\n\n {\n const b64 = privBin.base64Slice(0, privBin.length);\n let formatted = b64.replace(/.{64}/g, '$&\\n');\n if (b64.length & 63)\n formatted += '\\n';\n privateB64 += formatted;\n }\n\n {\n const b64 = parsed.pub.base64Slice(0, parsed.pub.length);\n publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ''}`;\n }\n\n privateB64 += '-----END OPENSSH PRIVATE KEY-----\\n';\n return {\n private: privateB64,\n public: publicB64,\n };\n }\n default:\n throw new Error('Invalid output key format');\n }\n}\n\nfunction noop() {}\n\nmodule.exports = {\n generateKeyPair: (keyType, opts, cb) => {\n if (typeof opts === 'function') {\n cb = opts;\n opts = undefined;\n }\n if (typeof cb !== 'function')\n cb = noop;\n const args = makeArgs(keyType, opts);\n generateKeyPair_(...args, (err, pub, priv) => {\n if (err)\n return cb(err);\n let ret;\n try {\n ret = convertKeys(args[0], pub, priv, opts);\n } catch (ex) {\n return cb(ex);\n }\n cb(null, ret);\n });\n },\n generateKeyPairSync: (keyType, opts) => {\n const args = makeArgs(keyType, opts);\n const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args);\n return convertKeys(args[0], pub, priv, opts);\n }\n};\n","/*\n TODO:\n * Replace `buffer._pos` usage in keyParser.js and elsewhere\n * Utilize optional \"writev\" support when writing packets from\n cipher.encrypt()\n * Built-in support for automatic re-keying, on by default\n * Revisit receiving unexpected/unknown packets\n * Error (fatal or otherwise) or ignore or pass on to user (in some or all\n cases)?\n * Including server/client check for single directional packet types?\n * Check packets for validity or bail as early as possible?\n * Automatic re-key every 2**31 packets after the last key exchange (sent or\n received), as suggested by RFC4344. OpenSSH currently does this.\n * Automatic re-key every so many blocks depending on cipher. RFC4344:\n Because of a birthday property of block ciphers and some modes of\n operation, implementations must be careful not to encrypt too many\n blocks with the same encryption key.\n\n Let L be the block length (in bits) of an SSH encryption method's\n block cipher (e.g., 128 for AES). If L is at least 128, then, after\n rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4)\n blocks before rekeying again. If L is at least 128, then SSH\n implementations should also attempt to force a rekey before receiving\n more than 2**(L/4) blocks. If L is less than 128 (which is the case\n for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then,\n although it may be too expensive to rekey every 2**(L/4) blocks, it\n is still advisable for SSH implementations to follow the original\n recommendation in [RFC4253]: rekey at least once for every gigabyte\n of transmitted data.\n\n Note that if L is less than or equal to 128, then the recommendation\n in this subsection supersedes the recommendation in Section 3.1. If\n an SSH implementation uses a block cipher with a larger block size\n (e.g., Rijndael with 256-bit blocks), then the recommendations in\n Section 3.1 may supersede the recommendations in this subsection\n (depending on the lengths of the packets).\n*/\n\n'use strict';\n\nconst { inspect } = require('util');\n\nconst { bindingAvailable, NullCipher, NullDecipher } = require('./crypto.js');\nconst {\n COMPAT_CHECKS,\n DISCONNECT_REASON,\n eddsaSupported,\n MESSAGE,\n SIGNALS,\n TERMINAL_MODE,\n} = require('./constants.js');\nconst {\n DEFAULT_KEXINIT_CLIENT,\n DEFAULT_KEXINIT_SERVER,\n KexInit,\n kexinit,\n onKEXPayload,\n} = require('./kex.js');\nconst {\n parseKey,\n} = require('./keyParser.js');\nconst MESSAGE_HANDLERS = require('./handlers.js');\nconst {\n bufferCopy,\n bufferFill,\n bufferSlice,\n convertSignature,\n sendPacket,\n writeUInt32BE,\n} = require('./utils.js');\nconst {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n} = require('./zlib.js');\n\nconst MODULE_VER = require('../../package.json').version;\n\nconst VALID_DISCONNECT_REASONS = new Map(\n Object.values(DISCONNECT_REASON).map((n) => [n, 1])\n);\nconst IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`);\nconst IDENT = Buffer.from(`${IDENT_RAW}\\r\\n`);\nconst MAX_LINE_LEN = 8192;\nconst MAX_LINES = 1024;\nconst PING_PAYLOAD = Buffer.from([\n MESSAGE.GLOBAL_REQUEST,\n // \"keepalive@openssh.com\"\n 0, 0, 0, 21,\n 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115,\n 115, 104, 46, 99, 111, 109,\n // Request a reply\n 1,\n]);\nconst NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]);\n\nfunction noop() {}\n\n/*\n Inbound:\n * kexinit payload (needed only until exchange hash is generated)\n * raw ident\n * rekey packet queue\n * expected packet (implemented as separate _parse() function?)\n Outbound:\n * kexinit payload (needed only until exchange hash is generated)\n * rekey packet queue\n * kex secret (needed only until NEWKEYS)\n * exchange hash (needed only until NEWKEYS)\n * session ID (set to exchange hash from initial handshake)\n*/\nclass Protocol {\n constructor(config) {\n const onWrite = config.onWrite;\n if (typeof onWrite !== 'function')\n throw new Error('Missing onWrite function');\n this._onWrite = (data) => { onWrite(data); };\n\n const onError = config.onError;\n if (typeof onError !== 'function')\n throw new Error('Missing onError function');\n this._onError = (err) => { onError(err); };\n\n const debug = config.debug;\n this._debug = (typeof debug === 'function'\n ? (msg) => { debug(msg); }\n : undefined);\n\n const onHeader = config.onHeader;\n this._onHeader = (typeof onHeader === 'function'\n ? (...args) => { onHeader(...args); }\n : noop);\n\n const onPacket = config.onPacket;\n this._onPacket = (typeof onPacket === 'function'\n ? () => { onPacket(); }\n : noop);\n\n let onHandshakeComplete = config.onHandshakeComplete;\n if (typeof onHandshakeComplete !== 'function')\n onHandshakeComplete = noop;\n let firstHandshake;\n this._onHandshakeComplete = (...args) => {\n this._debug && this._debug('Handshake completed');\n if (firstHandshake === undefined)\n firstHandshake = true;\n else\n firstHandshake = false;\n\n // Process packets queued during a rekey where necessary\n const oldQueue = this._queue;\n if (oldQueue) {\n this._queue = undefined;\n this._debug && this._debug(\n `Draining outbound queue (${oldQueue.length}) ...`\n );\n for (let i = 0; i < oldQueue.length; ++i) {\n const data = oldQueue[i];\n // data === payload only\n\n // XXX: hacky\n let finalized = this._packetRW.write.finalize(data);\n if (finalized === data) {\n const packet = this._cipher.allocPacket(data.length);\n packet.set(data, 5);\n finalized = packet;\n }\n\n sendPacket(this, finalized);\n }\n this._debug && this._debug('... finished draining outbound queue');\n }\n\n if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled)\n sendExtInfo(this);\n\n onHandshakeComplete(...args);\n };\n this._queue = undefined;\n\n const messageHandlers = config.messageHandlers;\n if (typeof messageHandlers === 'object' && messageHandlers !== null)\n this._handlers = messageHandlers;\n else\n this._handlers = {};\n\n this._onPayload = onPayload.bind(this);\n\n this._server = !!config.server;\n this._banner = undefined;\n let greeting;\n if (this._server) {\n if (typeof config.hostKeys !== 'object' || config.hostKeys === null)\n throw new Error('Missing server host key(s)');\n this._hostKeys = config.hostKeys;\n\n // Greeting displayed before the ssh identification string is sent, this\n // is usually ignored by most clients\n if (typeof config.greeting === 'string' && config.greeting.length) {\n greeting = (config.greeting.slice(-2) === '\\r\\n'\n ? config.greeting\n : `${config.greeting}\\r\\n`);\n }\n\n // Banner shown after the handshake completes, but before user\n // authentication begins\n if (typeof config.banner === 'string' && config.banner.length) {\n this._banner = (config.banner.slice(-2) === '\\r\\n'\n ? config.banner\n : `${config.banner}\\r\\n`);\n }\n } else {\n this._hostKeys = undefined;\n }\n\n let offer = config.offer;\n if (typeof offer !== 'object' || offer === null) {\n offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT);\n } else if (offer.constructor !== KexInit) {\n if (this._server) {\n offer.kex = offer.kex.concat(['kex-strict-s-v00@openssh.com']);\n } else {\n offer.kex = offer.kex.concat([\n 'ext-info-c',\n 'kex-strict-c-v00@openssh.com',\n ]);\n }\n offer = new KexInit(offer);\n }\n this._kex = undefined;\n this._strictMode = undefined;\n this._kexinit = undefined;\n this._offer = offer;\n this._cipher = new NullCipher(0, this._onWrite);\n this._decipher = undefined;\n this._skipNextInboundPacket = false;\n this._packetRW = {\n read: new PacketReader(),\n write: new PacketWriter(this),\n };\n this._hostVerifier = (!this._server\n && typeof config.hostVerifier === 'function'\n ? config.hostVerifier\n : undefined);\n\n this._parse = parseHeader;\n this._buffer = undefined;\n this._authsQueue = [];\n this._authenticated = false;\n this._remoteIdentRaw = undefined;\n let sentIdent;\n if (typeof config.ident === 'string') {\n this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`);\n\n sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2);\n sentIdent.set(this._identRaw, 0);\n sentIdent[sentIdent.length - 2] = 13; // '\\r'\n sentIdent[sentIdent.length - 1] = 10; // '\\n'\n } else if (Buffer.isBuffer(config.ident)) {\n const fullIdent = Buffer.allocUnsafe(8 + config.ident.length);\n fullIdent.latin1Write('SSH-2.0-', 0, 8);\n fullIdent.set(config.ident, 8);\n this._identRaw = fullIdent;\n\n sentIdent = Buffer.allocUnsafe(fullIdent.length + 2);\n sentIdent.set(fullIdent, 0);\n sentIdent[sentIdent.length - 2] = 13; // '\\r'\n sentIdent[sentIdent.length - 1] = 10; // '\\n'\n } else {\n this._identRaw = IDENT_RAW;\n sentIdent = IDENT;\n }\n this._compatFlags = 0;\n\n if (this._debug) {\n if (bindingAvailable)\n this._debug('Custom crypto binding available');\n else\n this._debug('Custom crypto binding not available');\n }\n\n this._debug && this._debug(\n `Local ident: ${inspect(this._identRaw.toString())}`\n );\n this.start = () => {\n this.start = undefined;\n if (greeting)\n this._onWrite(greeting);\n this._onWrite(sentIdent);\n };\n }\n _destruct(reason) {\n this._packetRW.read.cleanup();\n this._packetRW.write.cleanup();\n this._cipher && this._cipher.free();\n this._decipher && this._decipher.free();\n if (typeof reason !== 'string' || reason.length === 0)\n reason = 'fatal error';\n this.parse = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };\n this._onWrite = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };\n this._destruct = undefined;\n }\n cleanup() {\n this._destruct && this._destruct();\n }\n parse(chunk, i, len) {\n while (i < len)\n i = this._parse(chunk, i, len);\n }\n\n // Protocol message API\n\n // ===========================================================================\n // Common/Shared =============================================================\n // ===========================================================================\n\n // Global\n // ------\n disconnect(reason) {\n const pktLen = 1 + 4 + 4 + 4;\n // We don't use _packetRW.write.* here because we need to make sure that\n // we always get a full packet allocated because this message can be sent\n // at any time -- even during a key exchange\n let p = this._packetRW.write.allocStartKEX;\n const packet = this._packetRW.write.alloc(pktLen, true);\n const end = p + pktLen;\n\n if (!VALID_DISCONNECT_REASONS.has(reason))\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n\n packet[p] = MESSAGE.DISCONNECT;\n writeUInt32BE(packet, reason, ++p);\n packet.fill(0, p += 4, end);\n\n this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`);\n sendPacket(this, this._packetRW.write.finalize(packet, true), true);\n }\n ping() {\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(PING_PAYLOAD.length);\n\n packet.set(PING_PAYLOAD, p);\n\n this._debug && this._debug(\n 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n rekey() {\n if (this._kexinit === undefined) {\n this._debug && this._debug('Outbound: Initiated explicit rekey');\n this._queue = [];\n kexinit(this);\n } else {\n this._debug && this._debug('Outbound: Ignoring rekey during handshake');\n }\n }\n\n // 'ssh-connection' service-specific\n // ---------------------------------\n requestSuccess(data) {\n let p = this._packetRW.write.allocStart;\n let packet;\n if (Buffer.isBuffer(data)) {\n packet = this._packetRW.write.alloc(1 + data.length);\n\n packet[p] = MESSAGE.REQUEST_SUCCESS;\n\n packet.set(data, ++p);\n } else {\n packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.REQUEST_SUCCESS;\n }\n\n this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n requestFailure() {\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.REQUEST_FAILURE;\n\n this._debug && this._debug('Outbound: Sending REQUEST_FAILURE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelSuccess(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_SUCCESS;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelFailure(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_FAILURE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelEOF(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_EOF;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelClose(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_CLOSE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelWindowAdjust(chan, amount) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, amount, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelData(chan, data) {\n const isBuffer = Buffer.isBuffer(data);\n const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen);\n\n packet[p] = MESSAGE.CHANNEL_DATA;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, dataLen, p += 4);\n\n if (isBuffer)\n packet.set(data, p += 4);\n else\n packet.utf8Write(data, p += 4, dataLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelExtData(chan, data, type) {\n const isBuffer = Buffer.isBuffer(data);\n const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen);\n\n packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, type, p += 4);\n\n writeUInt32BE(packet, dataLen, p += 4);\n\n if (isBuffer)\n packet.set(data, p += 4);\n else\n packet.utf8Write(data, p += 4, dataLen);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelOpenConfirm(remote, local, initWindow, maxPacket) {\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION;\n\n writeUInt32BE(packet, remote, ++p);\n\n writeUInt32BE(packet, local, p += 4);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelOpenFail(remote, reason, desc) {\n if (typeof desc !== 'string')\n desc = '';\n\n const descLen = Buffer.byteLength(desc);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE;\n\n writeUInt32BE(packet, remote, ++p);\n\n writeUInt32BE(packet, reason, p += 4);\n\n writeUInt32BE(packet, descLen, p += 4);\n\n p += 4;\n if (descLen) {\n packet.utf8Write(desc, p, descLen);\n p += descLen;\n }\n\n writeUInt32BE(packet, 0, p); // Empty language tag\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // ===========================================================================\n // Client-specific ===========================================================\n // ===========================================================================\n\n // Global\n // ------\n service(name) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + nameLen);\n\n packet[p] = MESSAGE.SERVICE_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // 'ssh-userauth' service-specific\n // -------------------------------\n authPassword(username, password, newPassword) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n const passLen = Buffer.byteLength(password);\n const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen\n + (newPassword ? 4 + newPassLen : 0)\n );\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 8, p += 14);\n packet.utf8Write('password', p += 4, 8);\n\n packet[p += 8] = (newPassword ? 1 : 0);\n\n writeUInt32BE(packet, passLen, ++p);\n if (Buffer.isBuffer(password))\n bufferCopy(password, packet, 0, passLen, p += 4);\n else\n packet.utf8Write(password, p += 4, passLen);\n\n if (newPassword) {\n writeUInt32BE(packet, newPassLen, p += passLen);\n if (Buffer.isBuffer(newPassword))\n bufferCopy(newPassword, packet, 0, newPassLen, p += 4);\n else\n packet.utf8Write(newPassword, p += 4, newPassLen);\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (changed password)'\n );\n } else {\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (password)'\n );\n }\n\n this._authsQueue.push('password');\n\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authPK(username, pubKey, keyAlgo, cbSign) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n pubKey = parseKey(pubKey);\n if (pubKey instanceof Error)\n throw new Error('Invalid key');\n\n const keyType = pubKey.type;\n pubKey = pubKey.getPublicSSH();\n\n if (typeof keyAlgo === 'function') {\n cbSign = keyAlgo;\n keyAlgo = undefined;\n }\n if (!keyAlgo)\n keyAlgo = keyType;\n\n const userLen = Buffer.byteLength(username);\n const algoLen = Buffer.byteLength(keyAlgo);\n const pubKeyLen = pubKey.length;\n const sessionID = this._kex.sessionID;\n const sesLen = sessionID.length;\n const payloadLen =\n (cbSign ? 4 + sesLen : 0)\n + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen;\n let packet;\n let p;\n if (cbSign) {\n packet = Buffer.allocUnsafe(payloadLen);\n p = 0;\n writeUInt32BE(packet, sesLen, p);\n packet.set(sessionID, p += 4);\n p += sesLen;\n } else {\n packet = this._packetRW.write.alloc(payloadLen);\n p = this._packetRW.write.allocStart;\n }\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 9, p += 14);\n packet.utf8Write('publickey', p += 4, 9);\n\n packet[p += 9] = (cbSign ? 1 : 0);\n\n writeUInt32BE(packet, algoLen, ++p);\n packet.utf8Write(keyAlgo, p += 4, algoLen);\n\n writeUInt32BE(packet, pubKeyLen, p += algoLen);\n packet.set(pubKey, p += 4);\n\n if (!cbSign) {\n this._authsQueue.push('publickey');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n return;\n }\n\n cbSign(packet, (signature) => {\n signature = convertSignature(signature, keyType);\n if (signature === false)\n throw new Error('Error while converting handshake signature');\n\n const sigLen = signature.length;\n p = this._packetRW.write.allocStart;\n packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4\n + 4 + algoLen + 4 + sigLen\n );\n\n // TODO: simply copy from original \"packet\" to new `packet` to avoid\n // having to write each individual field a second time?\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 9, p += 14);\n packet.utf8Write('publickey', p += 4, 9);\n\n packet[p += 9] = 1;\n\n writeUInt32BE(packet, algoLen, ++p);\n packet.utf8Write(keyAlgo, p += 4, algoLen);\n\n writeUInt32BE(packet, pubKeyLen, p += algoLen);\n packet.set(pubKey, p += 4);\n\n writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen);\n\n writeUInt32BE(packet, algoLen, p += 4);\n packet.utf8Write(keyAlgo, p += 4, algoLen);\n\n writeUInt32BE(packet, sigLen, p += algoLen);\n packet.set(signature, p += 4);\n\n // Servers shouldn't send packet type 60 in response to signed publickey\n // attempts, but if they do, interpret as type 60.\n this._authsQueue.push('publickey');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (publickey)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n });\n }\n authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) {\n // TODO: Make DRY by sharing similar code with authPK()\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n pubKey = parseKey(pubKey);\n if (pubKey instanceof Error)\n throw new Error('Invalid key');\n\n const keyType = pubKey.type;\n pubKey = pubKey.getPublicSSH();\n\n if (typeof keyAlgo === 'function') {\n cbSign = keyAlgo;\n keyAlgo = undefined;\n }\n if (!keyAlgo)\n keyAlgo = keyType;\n\n const userLen = Buffer.byteLength(username);\n const algoLen = Buffer.byteLength(keyAlgo);\n const pubKeyLen = pubKey.length;\n const sessionID = this._kex.sessionID;\n const sesLen = sessionID.length;\n const hostnameLen = Buffer.byteLength(hostname);\n const userlocalLen = Buffer.byteLength(userlocal);\n const data = Buffer.allocUnsafe(\n 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen\n + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen\n );\n let p = 0;\n\n writeUInt32BE(data, sesLen, p);\n data.set(sessionID, p += 4);\n\n data[p += sesLen] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(data, userLen, ++p);\n data.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(data, 14, p += userLen);\n data.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(data, 9, p += 14);\n data.utf8Write('hostbased', p += 4, 9);\n\n writeUInt32BE(data, algoLen, p += 9);\n data.utf8Write(keyAlgo, p += 4, algoLen);\n\n writeUInt32BE(data, pubKeyLen, p += algoLen);\n data.set(pubKey, p += 4);\n\n writeUInt32BE(data, hostnameLen, p += pubKeyLen);\n data.utf8Write(hostname, p += 4, hostnameLen);\n\n writeUInt32BE(data, userlocalLen, p += hostnameLen);\n data.utf8Write(userlocal, p += 4, userlocalLen);\n\n cbSign(data, (signature) => {\n signature = convertSignature(signature, keyType);\n if (!signature)\n throw new Error('Error while converting handshake signature');\n\n const sigLen = signature.length;\n const reqDataLen = (data.length - sesLen - 4);\n p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n reqDataLen + 4 + 4 + algoLen + 4 + sigLen\n );\n\n bufferCopy(data, packet, 4 + sesLen, data.length, p);\n\n writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen);\n writeUInt32BE(packet, algoLen, p += 4);\n packet.utf8Write(keyAlgo, p += 4, algoLen);\n writeUInt32BE(packet, sigLen, p += algoLen);\n packet.set(signature, p += 4);\n\n this._authsQueue.push('hostbased');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (hostbased)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n });\n }\n authKeyboard(username) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4\n );\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 20, p += 14);\n packet.utf8Write('keyboard-interactive', p += 4, 20);\n\n writeUInt32BE(packet, 0, p += 20);\n\n writeUInt32BE(packet, 0, p += 4);\n\n this._authsQueue.push('keyboard-interactive');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authNone(username) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4);\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 4, p += 14);\n packet.utf8Write('none', p += 4, 4);\n\n this._authsQueue.push('none');\n\n this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authInfoRes(responses) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let responsesTotalLen = 0;\n let responseLens;\n\n if (responses) {\n responseLens = new Array(responses.length);\n for (let i = 0; i < responses.length; ++i) {\n const len = Buffer.byteLength(responses[i]);\n responseLens[i] = len;\n responsesTotalLen += 4 + len;\n }\n }\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen);\n\n packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE;\n\n if (responses) {\n writeUInt32BE(packet, responses.length, ++p);\n p += 4;\n for (let i = 0; i < responses.length; ++i) {\n const len = responseLens[i];\n writeUInt32BE(packet, len, p);\n p += 4;\n if (len) {\n packet.utf8Write(responses[i], p, len);\n p += len;\n }\n }\n } else {\n writeUInt32BE(packet, 0, ++p);\n }\n\n this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // 'ssh-connection' service-specific\n // ---------------------------------\n tcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 13, ++p);\n packet.utf8Write('tcpip-forward', p += 4, 13);\n\n packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n cancelTcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 20, ++p);\n packet.utf8Write('cancel-tcpip-forward', p += 4, 20);\n\n packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_streamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 31 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 31, ++p);\n packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31);\n\n packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_cancelStreamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 38 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 38, ++p);\n packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38);\n\n packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending GLOBAL_REQUEST '\n + '(cancel-streamlocal-forward@openssh.com)'\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n directTcpip(chan, initWindow, maxPacket, cfg) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const srcLen = Buffer.byteLength(cfg.srcIP);\n const dstLen = Buffer.byteLength(cfg.dstIP);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 12, ++p);\n packet.utf8Write('direct-tcpip', p += 4, 12);\n\n writeUInt32BE(packet, chan, p += 12);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, dstLen, p += 4);\n packet.utf8Write(cfg.dstIP, p += 4, dstLen);\n\n writeUInt32BE(packet, cfg.dstPort, p += dstLen);\n\n writeUInt32BE(packet, srcLen, p += 4);\n packet.utf8Write(cfg.srcIP, p += 4, srcLen);\n\n writeUInt32BE(packet, cfg.srcPort, p += srcLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const pathLen = Buffer.byteLength(cfg.socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 30, ++p);\n packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30);\n\n writeUInt32BE(packet, chan, p += 30);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, pathLen, p += 4);\n packet.utf8Write(cfg.socketPath, p += 4, pathLen);\n\n // zero-fill reserved fields (string and uint32)\n bufferFill(packet, 0, p += pathLen, p + 8);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_OPEN '\n + `(r:${chan}, direct-streamlocal@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_noMoreSessions(wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 28, ++p);\n packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28);\n\n packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n session(chan, initWindow, maxPacket) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 7, ++p);\n packet.utf8Write('session', p += 4, 7);\n\n writeUInt32BE(packet, chan, p += 7);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n windowChange(chan, rows, cols, height, width) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 13, p += 4);\n packet.utf8Write('window-change', p += 4, 13);\n\n packet[p += 13] = 0;\n\n writeUInt32BE(packet, cols, ++p);\n\n writeUInt32BE(packet, rows, p += 4);\n\n writeUInt32BE(packet, width, p += 4);\n\n writeUInt32BE(packet, height, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n pty(chan, rows, cols, height, width, term, modes, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n if (!term || !term.length)\n term = 'vt100';\n if (modes\n && !Buffer.isBuffer(modes)\n && !Array.isArray(modes)\n && typeof modes === 'object'\n && modes !== null) {\n modes = modesToBytes(modes);\n }\n if (!modes || !modes.length)\n modes = NO_TERMINAL_MODES_BUFFER;\n\n const termLen = term.length;\n const modesLen = modes.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 7, p += 4);\n packet.utf8Write('pty-req', p += 4, 7);\n\n packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, termLen, ++p);\n packet.utf8Write(term, p += 4, termLen);\n\n writeUInt32BE(packet, cols, p += termLen);\n\n writeUInt32BE(packet, rows, p += 4);\n\n writeUInt32BE(packet, width, p += 4);\n\n writeUInt32BE(packet, height, p += 4);\n\n writeUInt32BE(packet, modesLen, p += 4);\n p += 4;\n if (Array.isArray(modes)) {\n for (let i = 0; i < modesLen; ++i)\n packet[p++] = modes[i];\n } else if (Buffer.isBuffer(modes)) {\n packet.set(modes, p);\n }\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n shell(chan, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 5, p += 4);\n packet.utf8Write('shell', p += 4, 5);\n\n packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exec(chan, cmd, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const isBuf = Buffer.isBuffer(cmd);\n const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 4, p += 4);\n packet.utf8Write('exec', p += 4, 4);\n\n packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, cmdLen, ++p);\n if (isBuf)\n packet.set(cmd, p += 4);\n else\n packet.utf8Write(cmd, p += 4, cmdLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n signal(chan, signal) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const origSignal = signal;\n\n signal = signal.toUpperCase();\n if (signal.slice(0, 3) === 'SIG')\n signal = signal.slice(3);\n\n if (SIGNALS[signal] !== 1)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n const signalLen = signal.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 6 + 1 + 4 + signalLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 6, p += 4);\n packet.utf8Write('signal', p += 4, 6);\n\n packet[p += 6] = 0;\n\n writeUInt32BE(packet, signalLen, ++p);\n packet.utf8Write(signal, p += 4, signalLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n env(chan, key, val, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const keyLen = Buffer.byteLength(key);\n const isBuf = Buffer.isBuffer(val);\n const valLen = (isBuf ? val.length : Buffer.byteLength(val));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 3, p += 4);\n packet.utf8Write('env', p += 4, 3);\n\n packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, keyLen, ++p);\n packet.utf8Write(key, p += 4, keyLen);\n\n writeUInt32BE(packet, valLen, p += keyLen);\n if (isBuf)\n packet.set(val, p += 4);\n else\n packet.utf8Write(val, p += 4, valLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n x11Forward(chan, cfg, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const protocol = cfg.protocol;\n const cookie = cfg.cookie;\n const isBufProto = Buffer.isBuffer(protocol);\n const protoLen = (isBufProto\n ? protocol.length\n : Buffer.byteLength(protocol));\n const isBufCookie = Buffer.isBuffer(cookie);\n const cookieLen = (isBufCookie\n ? cookie.length\n : Buffer.byteLength(cookie));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 7, p += 4);\n packet.utf8Write('x11-req', p += 4, 7);\n\n packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n packet[++p] = (cfg.single ? 1 : 0);\n\n writeUInt32BE(packet, protoLen, ++p);\n if (isBufProto)\n packet.set(protocol, p += 4);\n else\n packet.utf8Write(protocol, p += 4, protoLen);\n\n writeUInt32BE(packet, cookieLen, p += protoLen);\n if (isBufCookie)\n packet.set(cookie, p += 4);\n else\n packet.latin1Write(cookie, p += 4, cookieLen);\n\n writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n subsystem(chan, name, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 9, p += 4);\n packet.utf8Write('subsystem', p += 4, 9);\n\n packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_agentForward(chan, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 26, p += 4);\n packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26);\n\n packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_REQUEST '\n + `(r:${chan}, auth-agent-req@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_hostKeysProve(keys) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let keysTotal = 0;\n const publicKeys = [];\n for (const key of keys) {\n const publicKey = key.getPublicSSH();\n keysTotal += 4 + publicKey.length;\n publicKeys.push(publicKey);\n }\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 29, ++p);\n packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);\n\n packet[p += 29] = 1; // want reply\n\n ++p;\n for (const buf of publicKeys) {\n writeUInt32BE(packet, buf.length, p);\n bufferCopy(buf, packet, 0, buf.length, p += 4);\n p += buf.length;\n }\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)'\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // ===========================================================================\n // Server-specific ===========================================================\n // ===========================================================================\n\n // Global\n // ------\n serviceAccept(svcName) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const svcNameLen = Buffer.byteLength(svcName);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen);\n\n packet[p] = MESSAGE.SERVICE_ACCEPT;\n\n writeUInt32BE(packet, svcNameLen, ++p);\n packet.utf8Write(svcName, p += 4, svcNameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n\n if (this._server && this._banner && svcName === 'ssh-userauth') {\n const banner = this._banner;\n this._banner = undefined; // Prevent banner from being displayed again\n const bannerLen = Buffer.byteLength(banner);\n p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4);\n\n packet[p] = MESSAGE.USERAUTH_BANNER;\n\n writeUInt32BE(packet, bannerLen, ++p);\n packet.utf8Write(banner, p += 4, bannerLen);\n\n writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag\n\n this._debug && this._debug('Outbound: Sending USERAUTH_BANNER');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n }\n // 'ssh-connection' service-specific\n forwardedTcpip(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const boundAddrLen = Buffer.byteLength(cfg.boundAddr);\n const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 15, ++p);\n packet.utf8Write('forwarded-tcpip', p += 4, 15);\n\n writeUInt32BE(packet, chan, p += 15);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, boundAddrLen, p += 4);\n packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen);\n\n writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen);\n\n writeUInt32BE(packet, remoteAddrLen, p += 4);\n packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen);\n\n writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n x11(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const addrLen = Buffer.byteLength(cfg.originAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 3, ++p);\n packet.utf8Write('x11', p += 4, 3);\n\n writeUInt32BE(packet, chan, p += 3);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, addrLen, p += 4);\n packet.utf8Write(cfg.originAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, cfg.originPort, p += addrLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_authAgent(chan, initWindow, maxPacket) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 22, ++p);\n packet.utf8Write('auth-agent@openssh.com', p += 4, 22);\n\n writeUInt32BE(packet, chan, p += 22);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const pathLen = Buffer.byteLength(cfg.socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 33, ++p);\n packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33);\n\n writeUInt32BE(packet, chan, p += 33);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, pathLen, p += 4);\n packet.utf8Write(cfg.socketPath, p += 4, pathLen);\n\n writeUInt32BE(packet, 0, p += pathLen);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_OPEN '\n + `(r:${chan}, forwarded-streamlocal@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exitStatus(chan, status) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n // Does not consume window space\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 11, p += 4);\n packet.utf8Write('exit-status', p += 4, 11);\n\n packet[p += 11] = 0;\n\n writeUInt32BE(packet, status, ++p);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exitSignal(chan, name, coreDumped, msg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n // Does not consume window space\n\n const origSignal = name;\n\n if (typeof origSignal !== 'string' || !origSignal)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n let signal = name.toUpperCase();\n if (signal.slice(0, 3) === 'SIG')\n signal = signal.slice(3);\n\n if (SIGNALS[signal] !== 1)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n const nameLen = Buffer.byteLength(signal);\n const msgLen = (msg ? Buffer.byteLength(msg) : 0);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 11, p += 4);\n packet.utf8Write('exit-signal', p += 4, 11);\n\n packet[p += 11] = 0;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(signal, p += 4, nameLen);\n\n packet[p += nameLen] = (coreDumped ? 1 : 0);\n\n writeUInt32BE(packet, msgLen, ++p);\n\n p += 4;\n if (msgLen) {\n packet.utf8Write(msg, p, msgLen);\n p += msgLen;\n }\n\n writeUInt32BE(packet, 0, p);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n // 'ssh-userauth' service-specific\n authFailure(authMethods, isPartial) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0)\n throw new Error('No auth in progress');\n\n let methods;\n\n if (typeof authMethods === 'boolean') {\n isPartial = authMethods;\n authMethods = undefined;\n }\n\n if (authMethods) {\n methods = [];\n for (let i = 0; i < authMethods.length; ++i) {\n if (authMethods[i].toLowerCase() === 'none')\n continue;\n methods.push(authMethods[i]);\n }\n methods = methods.join(',');\n } else {\n methods = '';\n }\n\n const methodsLen = methods.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1);\n\n packet[p] = MESSAGE.USERAUTH_FAILURE;\n\n writeUInt32BE(packet, methodsLen, ++p);\n packet.utf8Write(methods, p += 4, methodsLen);\n\n packet[p += methodsLen] = (isPartial === true ? 1 : 0);\n\n this._authsQueue.shift();\n\n this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authSuccess() {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0)\n throw new Error('No auth in progress');\n\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.USERAUTH_SUCCESS;\n\n this._authsQueue.shift();\n this._authenticated = true;\n\n this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS');\n sendPacket(this, this._packetRW.write.finalize(packet));\n\n if (this._kex.negotiated.cs.compress === 'zlib@openssh.com')\n this._packetRW.read = new ZlibPacketReader();\n if (this._kex.negotiated.sc.compress === 'zlib@openssh.com')\n this._packetRW.write = new ZlibPacketWriter(this);\n }\n authPKOK(keyAlgo, key) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey')\n throw new Error('\"publickey\" auth not in progress');\n\n // TODO: support parsed key for `key`\n\n const keyAlgoLen = Buffer.byteLength(keyAlgo);\n const keyLen = key.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen);\n\n packet[p] = MESSAGE.USERAUTH_PK_OK;\n\n writeUInt32BE(packet, keyAlgoLen, ++p);\n packet.utf8Write(keyAlgo, p += 4, keyAlgoLen);\n\n writeUInt32BE(packet, keyLen, p += keyAlgoLen);\n packet.set(key, p += 4);\n\n this._authsQueue.shift();\n\n this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authPasswdChg(prompt) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const promptLen = Buffer.byteLength(prompt);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4);\n\n packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ;\n\n writeUInt32BE(packet, promptLen, ++p);\n packet.utf8Write(prompt, p += 4, promptLen);\n\n writeUInt32BE(packet, 0, p += promptLen); // Empty language tag\n\n this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authInfoReq(name, instructions, prompts) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n let promptsLen = 0;\n const nameLen = name ? Buffer.byteLength(name) : 0;\n const instrLen = instructions ? Buffer.byteLength(instructions) : 0;\n\n for (let i = 0; i < prompts.length; ++i)\n promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1;\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen\n );\n\n packet[p] = MESSAGE.USERAUTH_INFO_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n p += 4;\n if (name) {\n packet.utf8Write(name, p, nameLen);\n p += nameLen;\n }\n\n writeUInt32BE(packet, instrLen, p);\n p += 4;\n if (instructions) {\n packet.utf8Write(instructions, p, instrLen);\n p += instrLen;\n }\n\n writeUInt32BE(packet, 0, p);\n\n writeUInt32BE(packet, prompts.length, p += 4);\n p += 4;\n for (let i = 0; i < prompts.length; ++i) {\n const prompt = prompts[i];\n const promptLen = Buffer.byteLength(prompt.prompt);\n\n writeUInt32BE(packet, promptLen, p);\n p += 4;\n if (promptLen) {\n packet.utf8Write(prompt.prompt, p, promptLen);\n p += promptLen;\n }\n packet[p++] = (prompt.echo ? 1 : 0);\n }\n\n this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n}\n\n// SSH-protoversion-softwareversion (SP comments) CR LF\nconst RE_IDENT = /^SSH-(2\\.0|1\\.99)-([^ ]+)(?: (.*))?$/;\n\n// TODO: optimize this by starting n bytes from the end of this._buffer instead\n// of the beginning\nfunction parseHeader(chunk, p, len) {\n let data;\n let chunkOffset;\n if (this._buffer) {\n data = Buffer.allocUnsafe(this._buffer.length + (len - p));\n data.set(this._buffer, 0);\n if (p === 0) {\n data.set(chunk, this._buffer.length);\n } else {\n data.set(new Uint8Array(chunk.buffer,\n chunk.byteOffset + p,\n (len - p)),\n this._buffer.length);\n }\n chunkOffset = this._buffer.length;\n p = 0;\n } else {\n data = chunk;\n chunkOffset = 0;\n }\n const op = p;\n let start = p;\n let end = p;\n let needNL = false;\n let lineLen = 0;\n let lines = 0;\n for (; p < data.length; ++p) {\n const ch = data[p];\n\n if (ch === 13 /* '\\r' */) {\n needNL = true;\n continue;\n }\n\n if (ch === 10 /* '\\n' */) {\n if (end > start\n && end - start > 4\n && data[start] === 83 /* 'S' */\n && data[start + 1] === 83 /* 'S' */\n && data[start + 2] === 72 /* 'H' */\n && data[start + 3] === 45 /* '-' */) {\n\n const full = data.latin1Slice(op, end + 1);\n const identRaw = (start === op ? full : full.slice(start - op));\n const m = RE_IDENT.exec(identRaw);\n if (!m)\n throw new Error('Invalid identification string');\n\n const header = {\n greeting: (start === op ? '' : full.slice(0, start - op)),\n identRaw,\n versions: {\n protocol: m[1],\n software: m[2],\n },\n comments: m[3]\n };\n\n // Needed during handshake\n this._remoteIdentRaw = Buffer.from(identRaw);\n\n this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`);\n this._compatFlags = getCompatFlags(header);\n\n this._buffer = undefined;\n this._decipher =\n new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true }));\n this._parse = parsePacket;\n\n this._onHeader(header);\n if (!this._destruct) {\n // We disconnected inside _onHeader\n return len;\n }\n\n kexinit(this);\n\n return p + 1 - chunkOffset;\n }\n\n // Only allow pre-ident greetings when we're a client\n if (this._server)\n throw new Error('Greetings from clients not permitted');\n\n if (++lines > MAX_LINES)\n throw new Error('Max greeting lines exceeded');\n\n needNL = false;\n start = p + 1;\n lineLen = 0;\n } else if (needNL) {\n throw new Error('Invalid header: expected newline');\n } else if (++lineLen >= MAX_LINE_LEN) {\n throw new Error('Header line too long');\n }\n\n end = p;\n }\n if (!this._buffer)\n this._buffer = bufferSlice(data, op);\n\n return p - chunkOffset;\n}\n\nfunction parsePacket(chunk, p, len) {\n return this._decipher.decrypt(chunk, p, len);\n}\n\nfunction onPayload(payload) {\n // XXX: move this to the Decipher implementations?\n\n this._onPacket();\n\n if (payload.length === 0) {\n this._debug && this._debug('Inbound: Skipping empty packet payload');\n return;\n }\n\n payload = this._packetRW.read.read(payload);\n\n const type = payload[0];\n if (type === MESSAGE.USERAUTH_SUCCESS\n && !this._server\n && !this._authenticated) {\n this._authenticated = true;\n if (this._kex.negotiated.cs.compress === 'zlib@openssh.com')\n this._packetRW.write = new ZlibPacketWriter(this);\n if (this._kex.negotiated.sc.compress === 'zlib@openssh.com')\n this._packetRW.read = new ZlibPacketReader();\n }\n const handler = MESSAGE_HANDLERS[type];\n if (handler === undefined) {\n this._debug && this._debug(`Inbound: Unsupported message type: ${type}`);\n return;\n }\n\n return handler(this, payload);\n}\n\nfunction getCompatFlags(header) {\n const software = header.versions.software;\n\n let flags = 0;\n\n for (const rule of COMPAT_CHECKS) {\n if (typeof rule[0] === 'string') {\n if (software === rule[0])\n flags |= rule[1];\n } else if (rule[0].test(software)) {\n flags |= rule[1];\n }\n }\n\n return flags;\n}\n\nfunction modesToBytes(modes) {\n const keys = Object.keys(modes);\n const bytes = Buffer.allocUnsafe((5 * keys.length) + 1);\n let b = 0;\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (key === 'TTY_OP_END')\n continue;\n\n const opcode = TERMINAL_MODE[key];\n if (opcode === undefined)\n continue;\n\n const val = modes[key];\n if (typeof val === 'number' && isFinite(val)) {\n bytes[b++] = opcode;\n bytes[b++] = val >>> 24;\n bytes[b++] = val >>> 16;\n bytes[b++] = val >>> 8;\n bytes[b++] = val;\n }\n }\n\n bytes[b++] = TERMINAL_MODE.TTY_OP_END;\n\n if (b < bytes.length)\n return bufferSlice(bytes, 0, b);\n\n return bytes;\n}\n\nfunction sendExtInfo(proto) {\n let serverSigAlgs =\n 'ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521'\n + 'rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss';\n if (eddsaSupported)\n serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`;\n const algsLen = Buffer.byteLength(serverSigAlgs);\n\n let p = proto._packetRW.write.allocStart;\n const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen);\n\n packet[p] = MESSAGE.EXT_INFO;\n\n writeUInt32BE(packet, 1, ++p);\n\n writeUInt32BE(packet, 15, p += 4);\n packet.utf8Write('server-sig-algs', p += 4, 15);\n\n writeUInt32BE(packet, algsLen, p += 15);\n packet.utf8Write(serverSigAlgs, p += 4, algsLen);\n\n proto._debug && proto._debug('Outbound: Sending EXT_INFO');\n sendPacket(proto, proto._packetRW.write.finalize(packet));\n}\n\nmodule.exports = Protocol;\n","'use strict';\n\nconst EventEmitter = require('events');\nconst fs = require('fs');\nconst { constants } = fs;\nconst {\n Readable: ReadableStream,\n Writable: WritableStream\n} = require('stream');\nconst { inherits, isDate } = require('util');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst {\n bufferCopy,\n bufferSlice,\n makeBufferParser,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst ATTR = {\n SIZE: 0x00000001,\n UIDGID: 0x00000002,\n PERMISSIONS: 0x00000004,\n ACMODTIME: 0x00000008,\n EXTENDED: 0x80000000,\n};\n\n// Large enough to store all possible attributes\nconst ATTRS_BUF = Buffer.alloc(28);\n\nconst STATUS_CODE = {\n OK: 0,\n EOF: 1,\n NO_SUCH_FILE: 2,\n PERMISSION_DENIED: 3,\n FAILURE: 4,\n BAD_MESSAGE: 5,\n NO_CONNECTION: 6,\n CONNECTION_LOST: 7,\n OP_UNSUPPORTED: 8\n};\n\nconst VALID_STATUS_CODES = new Map(\n Object.values(STATUS_CODE).map((n) => [n, 1])\n);\n\nconst STATUS_CODE_STR = {\n [STATUS_CODE.OK]: 'No error',\n [STATUS_CODE.EOF]: 'End of file',\n [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory',\n [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied',\n [STATUS_CODE.FAILURE]: 'Failure',\n [STATUS_CODE.BAD_MESSAGE]: 'Bad message',\n [STATUS_CODE.NO_CONNECTION]: 'No connection',\n [STATUS_CODE.CONNECTION_LOST]: 'Connection lost',\n [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported',\n};\n\nconst REQUEST = {\n INIT: 1,\n OPEN: 3,\n CLOSE: 4,\n READ: 5,\n WRITE: 6,\n LSTAT: 7,\n FSTAT: 8,\n SETSTAT: 9,\n FSETSTAT: 10,\n OPENDIR: 11,\n READDIR: 12,\n REMOVE: 13,\n MKDIR: 14,\n RMDIR: 15,\n REALPATH: 16,\n STAT: 17,\n RENAME: 18,\n READLINK: 19,\n SYMLINK: 20,\n EXTENDED: 200\n};\n\nconst RESPONSE = {\n VERSION: 2,\n STATUS: 101,\n HANDLE: 102,\n DATA: 103,\n NAME: 104,\n ATTRS: 105,\n EXTENDED: 201\n};\n\nconst OPEN_MODE = {\n READ: 0x00000001,\n WRITE: 0x00000002,\n APPEND: 0x00000004,\n CREAT: 0x00000008,\n TRUNC: 0x00000010,\n EXCL: 0x00000020\n};\n\nconst PKT_RW_OVERHEAD = 2 * 1024;\nconst MAX_REQID = 2 ** 32 - 1;\nconst CLIENT_VERSION_BUFFER = Buffer.from([\n 0, 0, 0, 5 /* length */,\n REQUEST.INIT,\n 0, 0, 0, 3 /* version */\n]);\nconst SERVER_VERSION_BUFFER = Buffer.from([\n 0, 0, 0, 5 /* length */,\n RESPONSE.VERSION,\n 0, 0, 0, 3 /* version */\n]);\n\nconst RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/;\nconst OPENSSH_MAX_PKT_LEN = 256 * 1024;\n\nconst bufferParser = makeBufferParser();\n\nconst fakeStderr = {\n readable: false,\n writable: false,\n push: (data) => {},\n once: () => {},\n on: () => {},\n emit: () => {},\n end: () => {},\n};\n\nfunction noop() {}\n\n// Emulates enough of `Channel` to be able to be used as a drop-in replacement\n// in order to process incoming data with as little overhead as possible\nclass SFTP extends EventEmitter {\n constructor(client, chanInfo, cfg) {\n super();\n\n if (typeof cfg !== 'object' || !cfg)\n cfg = {};\n\n const remoteIdentRaw = client._protocol._remoteIdentRaw;\n\n this.server = !!cfg.server;\n this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);\n this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw));\n\n this._version = -1;\n this._extensions = {};\n this._biOpt = cfg.biOpt;\n this._pktLenBytes = 0;\n this._pktLen = 0;\n this._pktPos = 0;\n this._pktType = 0;\n this._pktData = undefined;\n this._writeReqid = -1;\n this._requests = {};\n this._maxInPktLen = OPENSSH_MAX_PKT_LEN;\n this._maxOutPktLen = 34000;\n this._maxReadLen =\n (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;\n this._maxWriteLen =\n (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;\n\n this.maxOpenHandles = undefined;\n\n // Channel compatibility\n this._client = client;\n this._protocol = client._protocol;\n this._callbacks = [];\n this._hasX11 = false;\n this._exit = {\n code: undefined,\n signal: undefined,\n dump: undefined,\n desc: undefined,\n };\n this._waitWindow = false; // SSH-level backpressure\n this._chunkcb = undefined;\n this._buffer = [];\n this.type = chanInfo.type;\n this.subtype = undefined;\n this.incoming = chanInfo.incoming;\n this.outgoing = chanInfo.outgoing;\n this.stderr = fakeStderr;\n this.readable = true;\n }\n\n // This handles incoming data to parse\n push(data) {\n if (data === null) {\n cleanupRequests(this);\n if (!this.readable)\n return;\n // No more incoming data from the remote side\n this.readable = false;\n this.emit('end');\n return;\n }\n /*\n uint32 length\n byte type\n byte[length - 1] data payload\n */\n let p = 0;\n\n while (p < data.length) {\n if (this._pktLenBytes < 4) {\n let nb = Math.min(4 - this._pktLenBytes, data.length - p);\n this._pktLenBytes += nb;\n\n while (nb--)\n this._pktLen = (this._pktLen << 8) + data[p++];\n\n if (this._pktLenBytes < 4)\n return;\n if (this._pktLen === 0)\n return doFatalSFTPError(this, 'Invalid packet length');\n if (this._pktLen > this._maxInPktLen) {\n const max = this._maxInPktLen;\n return doFatalSFTPError(\n this,\n `Packet length ${this._pktLen} exceeds max length of ${max}`\n );\n }\n if (p >= data.length)\n return;\n }\n if (this._pktPos < this._pktLen) {\n const nb = Math.min(this._pktLen - this._pktPos, data.length - p);\n if (p !== 0 || nb !== data.length) {\n if (nb === this._pktLen) {\n this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb);\n } else {\n if (!this._pkt)\n this._pkt = Buffer.allocUnsafe(this._pktLen);\n this._pkt.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._pktPos\n );\n }\n } else if (nb === this._pktLen) {\n this._pkt = data;\n } else {\n if (!this._pkt)\n this._pkt = Buffer.allocUnsafe(this._pktLen);\n this._pkt.set(data, this._pktPos);\n }\n p += nb;\n this._pktPos += nb;\n if (this._pktPos < this._pktLen)\n return;\n }\n\n const type = this._pkt[0];\n const payload = this._pkt;\n\n // Prepare for next packet\n this._pktLen = 0;\n this._pktLenBytes = 0;\n this._pkt = undefined;\n this._pktPos = 0;\n\n const handler = (this.server\n ? SERVER_HANDLERS[type]\n : CLIENT_HANDLERS[type]);\n if (!handler)\n return doFatalSFTPError(this, `Unknown packet type ${type}`);\n\n if (this._version === -1) {\n if (this.server) {\n if (type !== REQUEST.INIT)\n return doFatalSFTPError(this, `Expected INIT packet, got ${type}`);\n } else if (type !== RESPONSE.VERSION) {\n return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`);\n }\n }\n\n if (handler(this, payload) === false)\n return;\n }\n }\n\n end() {\n this.destroy();\n }\n destroy() {\n if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {\n this.outgoing.state = 'closing';\n this._protocol.channelClose(this.outgoing.id);\n }\n }\n _init() {\n this._init = noop;\n if (!this.server)\n sendOrBuffer(this, CLIENT_VERSION_BUFFER);\n }\n\n // ===========================================================================\n // Client-specific ===========================================================\n // ===========================================================================\n createReadStream(path, options) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n return new ReadStream(this, path, options);\n }\n createWriteStream(path, options) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n return new WriteStream(this, path, options);\n }\n open(path, flags_, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (typeof attrs === 'function') {\n cb = attrs;\n attrs = undefined;\n }\n\n const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_));\n if (flags === null)\n throw new Error(`Unknown flags string: ${flags_}`);\n\n let attrsFlags = 0;\n let attrsLen = 0;\n if (typeof attrs === 'string' || typeof attrs === 'number')\n attrs = { mode: attrs };\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n attrsFlags = attrs.flags;\n attrsLen = attrs.nb;\n }\n\n /*\n uint32 id\n string filename\n uint32 pflags\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.OPEN;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n writeUInt32BE(buf, attrsFlags, p += 4);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN`\n );\n }\n close(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.CLOSE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE`\n );\n }\n read(handle, buf, off, len, position, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n if (!Buffer.isBuffer(buf))\n throw new Error('buffer is not a Buffer');\n if (off >= buf.length)\n throw new Error('offset is out of bounds');\n if (off + len > buf.length)\n throw new Error('length extends beyond buffer');\n if (position === null)\n throw new Error('null position currently unsupported');\n\n read_(this, handle, buf, off, len, position, cb);\n }\n readData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.read(handle, buf, off, len, position, cb);\n }\n write(handle, buf, off, len, position, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n if (!Buffer.isBuffer(buf))\n throw new Error('buffer is not a Buffer');\n if (off > buf.length)\n throw new Error('offset is out of bounds');\n if (off + len > buf.length)\n throw new Error('length extends beyond buffer');\n if (position === null)\n throw new Error('null position currently unsupported');\n\n if (!len) {\n cb && process.nextTick(cb, undefined, 0);\n return;\n }\n\n const maxDataLen = this._maxWriteLen;\n const overflow = Math.max(len - maxDataLen, 0);\n const origPosition = position;\n\n if (overflow)\n len = maxDataLen;\n\n /*\n uint32 id\n string handle\n uint64 offset\n string data\n */\n const handleLen = handle.length;\n let p = 9;\n const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len);\n\n writeUInt32BE(out, out.length - 4, 0);\n out[4] = REQUEST.WRITE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(out, reqid, 5);\n\n writeUInt32BE(out, handleLen, p);\n out.set(handle, p += 4);\n p += handleLen;\n for (let i = 7; i >= 0; --i) {\n out[p + i] = position & 0xFF;\n position /= 256;\n }\n writeUInt32BE(out, len, p += 8);\n bufferCopy(buf, out, off, off + len, p += 4);\n\n this._requests[reqid] = {\n cb: (err) => {\n if (err) {\n if (typeof cb === 'function')\n cb(err);\n } else if (overflow) {\n this.write(handle,\n buf,\n off + len,\n overflow,\n origPosition + len,\n cb);\n } else if (typeof cb === 'function') {\n cb(undefined, off + len);\n }\n }\n };\n\n const isSent = sendOrBuffer(this, out);\n if (this._debug) {\n const how = (isSent ? 'Sent' : 'Buffered');\n this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`);\n }\n }\n writeData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.write(handle, buf, off, len, position, cb);\n }\n fastGet(remotePath, localPath, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n fastXfer(this, fs, remotePath, localPath, opts, cb);\n }\n fastPut(localPath, remotePath, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n fastXfer(fs, this, localPath, remotePath, opts, cb);\n }\n readFile(path, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, flag: 'r' };\n else if (!options)\n options = { encoding: null, flag: 'r' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n const encoding = options.encoding;\n if (encoding && !Buffer.isEncoding(encoding))\n throw new Error(`Unknown encoding: ${encoding}`);\n\n // First stat the file, so we know the size.\n let size;\n let buffer; // Single buffer with file data\n let buffers; // List for when size is unknown\n let pos = 0;\n let handle;\n\n // SFTPv3 does not support using -1 for read position, so we have to track\n // read position manually\n let bytesRead = 0;\n\n const flag = options.flag || 'r';\n\n const read = () => {\n if (size === 0) {\n buffer = Buffer.allocUnsafe(8192);\n this.read(handle, buffer, 0, 8192, bytesRead, afterRead);\n } else {\n this.read(handle, buffer, pos, size - pos, bytesRead, afterRead);\n }\n };\n\n const afterRead = (er, nbytes) => {\n let eof;\n if (er) {\n eof = (er.code === STATUS_CODE.EOF);\n if (!eof) {\n return this.close(handle, () => {\n return callback && callback(er);\n });\n }\n } else {\n eof = false;\n }\n\n if (eof || (size === 0 && nbytes === 0))\n return close();\n\n bytesRead += nbytes;\n pos += nbytes;\n if (size !== 0) {\n if (pos === size)\n close();\n else\n read();\n } else {\n // Unknown size, just read until we don't get bytes.\n buffers.push(bufferSlice(buffer, 0, nbytes));\n read();\n }\n };\n afterRead._wantEOFError = true;\n\n const close = () => {\n this.close(handle, (er) => {\n if (size === 0) {\n // Collect the data into the buffers list.\n buffer = Buffer.concat(buffers, pos);\n } else if (pos < size) {\n buffer = bufferSlice(buffer, 0, pos);\n }\n\n if (encoding)\n buffer = buffer.toString(encoding);\n return callback && callback(er, buffer);\n });\n };\n\n this.open(path, flag, 0o666, (er, handle_) => {\n if (er)\n return callback && callback(er);\n handle = handle_;\n\n const tryStat = (er, st) => {\n if (er) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.stat(path, (er_, st_) => {\n if (er_) {\n return this.close(handle, () => {\n callback && callback(er);\n });\n }\n tryStat(null, st_);\n });\n return;\n }\n\n size = st.size || 0;\n if (size === 0) {\n // The kernel lies about many files.\n // Go ahead and try to read some bytes.\n buffers = [];\n return read();\n }\n\n buffer = Buffer.allocUnsafe(size);\n read();\n };\n this.fstat(handle, tryStat);\n });\n }\n writeFile(path, data, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, mode: 0o666, flag: 'w' };\n else if (!options)\n options = { encoding: 'utf8', mode: 0o666, flag: 'w' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n if (options.encoding && !Buffer.isEncoding(options.encoding))\n throw new Error(`Unknown encoding: ${options.encoding}`);\n\n const flag = options.flag || 'w';\n this.open(path, flag, options.mode, (openErr, handle) => {\n if (openErr) {\n callback && callback(openErr);\n } else {\n const buffer = (Buffer.isBuffer(data)\n ? data\n : Buffer.from('' + data, options.encoding || 'utf8'));\n const position = (/a/.test(flag) ? null : 0);\n\n // SFTPv3 does not support the notion of 'current position'\n // (null position), so we just attempt to append to the end of the file\n // instead\n if (position === null) {\n const tryStat = (er, st) => {\n if (er) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.stat(path, (er_, st_) => {\n if (er_) {\n return this.close(handle, () => {\n callback && callback(er);\n });\n }\n tryStat(null, st_);\n });\n return;\n }\n writeAll(this, handle, buffer, 0, buffer.length, st.size, callback);\n };\n this.fstat(handle, tryStat);\n return;\n }\n writeAll(this, handle, buffer, 0, buffer.length, position, callback);\n }\n });\n }\n appendFile(path, data, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, mode: 0o666, flag: 'a' };\n else if (!options)\n options = { encoding: 'utf8', mode: 0o666, flag: 'a' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n if (!options.flag)\n options = Object.assign({ flag: 'a' }, options);\n this.writeFile(path, data, options, callback);\n }\n exists(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n this.stat(path, (err) => {\n cb && cb(err ? false : true);\n });\n }\n unlink(filename, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string filename\n */\n const fnameLen = Buffer.byteLength(filename);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.REMOVE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, fnameLen, p);\n buf.utf8Write(filename, p += 4, fnameLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE`\n );\n }\n rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RENAME;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, oldLen, p);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME`\n );\n }\n mkdir(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'function') {\n cb = attrs;\n attrs = undefined;\n }\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n }\n\n /*\n uint32 id\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.MKDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR`\n );\n }\n rmdir(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RMDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR`\n );\n }\n readdir(where, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof opts !== 'object' || opts === null)\n opts = {};\n\n const doFilter = (opts && opts.full ? false : true);\n\n if (!Buffer.isBuffer(where) && typeof where !== 'string')\n throw new Error('missing directory handle or path');\n\n if (typeof where === 'string') {\n const entries = [];\n let e = 0;\n\n const reread = (err, handle) => {\n if (err)\n return cb(err);\n\n this.readdir(handle, opts, (err, list) => {\n const eof = (err && err.code === STATUS_CODE.EOF);\n\n if (err && !eof)\n return this.close(handle, () => cb(err));\n\n if (eof) {\n return this.close(handle, (err) => {\n if (err)\n return cb(err);\n cb(undefined, entries);\n });\n }\n\n for (let i = 0; i < list.length; ++i, ++e)\n entries[e] = list[i];\n\n reread(undefined, handle);\n });\n };\n return this.opendir(where, reread);\n }\n\n /*\n uint32 id\n string handle\n */\n const handleLen = where.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.READDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(where, p += 4);\n\n this._requests[reqid] = {\n cb: (doFilter\n ? (err, list) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n\n for (let i = list.length - 1; i >= 0; --i) {\n if (list[i].filename === '.' || list[i].filename === '..')\n list.splice(i, 1);\n }\n\n cb(undefined, list);\n }\n : cb)\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR`\n );\n }\n fstat(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.FSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT`\n );\n }\n stat(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.STAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT`\n );\n }\n lstat(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.LSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT`\n );\n }\n opendir(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.OPENDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR`\n );\n }\n setstat(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.SETSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT`\n );\n }\n fsetstat(handle, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string handle\n ATTRS attrs\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.FSETSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n writeUInt32BE(buf, flags, p += handleLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT`\n );\n }\n futimes(handle, atime, mtime, cb) {\n return this.fsetstat(handle, {\n atime: toUnixTimestamp(atime),\n mtime: toUnixTimestamp(mtime)\n }, cb);\n }\n utimes(path, atime, mtime, cb) {\n return this.setstat(path, {\n atime: toUnixTimestamp(atime),\n mtime: toUnixTimestamp(mtime)\n }, cb);\n }\n fchown(handle, uid, gid, cb) {\n return this.fsetstat(handle, {\n uid: uid,\n gid: gid\n }, cb);\n }\n chown(path, uid, gid, cb) {\n return this.setstat(path, {\n uid: uid,\n gid: gid\n }, cb);\n }\n fchmod(handle, mode, cb) {\n return this.fsetstat(handle, {\n mode: mode\n }, cb);\n }\n chmod(path, mode, cb) {\n return this.setstat(path, {\n mode: mode\n }, cb);\n }\n readlink(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.READLINK;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing link info'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK`\n );\n }\n symlink(targetPath, linkPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string linkpath\n string targetpath\n */\n const linkLen = Buffer.byteLength(linkPath);\n const targetLen = Buffer.byteLength(targetPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.SYMLINK;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n if (this._isOpenSSH) {\n // OpenSSH has linkpath and targetpath positions switched\n writeUInt32BE(buf, targetLen, p);\n buf.utf8Write(targetPath, p += 4, targetLen);\n writeUInt32BE(buf, linkLen, p += targetLen);\n buf.utf8Write(linkPath, p += 4, linkLen);\n } else {\n writeUInt32BE(buf, linkLen, p);\n buf.utf8Write(linkPath, p += 4, linkLen);\n writeUInt32BE(buf, targetLen, p += linkLen);\n buf.utf8Write(targetPath, p += 4, targetLen);\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK`\n );\n }\n realpath(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.REALPATH;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing path info'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH`\n );\n }\n // extended requests\n ext_openssh_rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['posix-rename@openssh.com'];\n if (!ext || ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"posix-rename@openssh.com\"\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 24, p);\n buf.utf8Write('posix-rename@openssh.com', p += 4, 24);\n writeUInt32BE(buf, oldLen, p += 24);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`);\n }\n }\n ext_openssh_statvfs(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['statvfs@openssh.com'];\n if (!ext || ext !== '2')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"statvfs@openssh.com\"\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 19, p);\n buf.utf8Write('statvfs@openssh.com', p += 4, 19);\n writeUInt32BE(buf, pathLen, p += 19);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { extended: 'statvfs@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`);\n }\n }\n ext_openssh_fstatvfs(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['fstatvfs@openssh.com'];\n if (!ext || ext !== '2')\n throw new Error('Server does not support this extended request');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string \"fstatvfs@openssh.com\"\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('fstatvfs@openssh.com', p += 4, 20);\n writeUInt32BE(buf, handleLen, p += 20);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`);\n }\n }\n ext_openssh_hardlink(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['hardlink@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"hardlink@openssh.com\"\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('hardlink@openssh.com', p += 4, 20);\n writeUInt32BE(buf, oldLen, p += 20);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`);\n }\n }\n ext_openssh_fsync(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['fsync@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string \"fsync@openssh.com\"\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 17, p);\n buf.utf8Write('fsync@openssh.com', p += 4, 17);\n writeUInt32BE(buf, handleLen, p += 17);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com`\n );\n }\n ext_openssh_lsetstat(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['lsetstat@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string \"lsetstat@openssh.com\"\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('lsetstat@openssh.com', p += 4, 20);\n\n writeUInt32BE(buf, pathLen, p += 20);\n buf.utf8Write(path, p += 4, pathLen);\n\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`);\n }\n }\n ext_openssh_expandPath(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['expand-path@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"expand-path@openssh.com\"\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 23, p);\n buf.utf8Write('expand-path@openssh.com', p += 4, 23);\n\n writeUInt32BE(buf, pathLen, p += 20);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing expanded path'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`);\n }\n }\n ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['copy-data'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n if (!Buffer.isBuffer(srcHandle))\n throw new Error('Source handle is not a Buffer');\n\n if (!Buffer.isBuffer(dstHandle))\n throw new Error('Destination handle is not a Buffer');\n\n /*\n uint32 id\n string \"copy-data\"\n string read-from-handle\n uint64 read-from-offset\n uint64 read-data-length\n string write-to-handle\n uint64 write-to-offset\n */\n let p = 0;\n const buf = Buffer.allocUnsafe(\n 4 + 1\n + 4\n + 4 + 9\n + 4 + srcHandle.length\n + 8\n + 8\n + 4 + dstHandle.length\n + 8\n );\n\n writeUInt32BE(buf, buf.length - 4, p);\n p += 4;\n\n buf[p] = REQUEST.EXTENDED;\n ++p;\n\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, p);\n p += 4;\n\n writeUInt32BE(buf, 9, p);\n p += 4;\n buf.utf8Write('copy-data', p, 9);\n p += 9;\n\n writeUInt32BE(buf, srcHandle.length, p);\n p += 4;\n buf.set(srcHandle, p);\n p += srcHandle.length;\n\n for (let i = 7; i >= 0; --i) {\n buf[p + i] = srcOffset & 0xFF;\n srcOffset /= 256;\n }\n p += 8;\n\n for (let i = 7; i >= 0; --i) {\n buf[p + i] = len & 0xFF;\n len /= 256;\n }\n p += 8;\n\n writeUInt32BE(buf, dstHandle.length, p);\n p += 4;\n buf.set(dstHandle, p);\n p += dstHandle.length;\n\n for (let i = 7; i >= 0; --i) {\n buf[p + i] = dstOffset & 0xFF;\n dstOffset /= 256;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} copy-data`);\n }\n }\n ext_home_dir(username, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['home-directory'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n if (typeof username !== 'string')\n throw new TypeError('username is not a string');\n\n /*\n uint32 id\n string \"home-directory\"\n string username\n */\n let p = 0;\n const usernameLen = Buffer.byteLength(username);\n const buf = Buffer.allocUnsafe(\n 4 + 1\n + 4\n + 4 + 14\n + 4 + usernameLen\n );\n\n writeUInt32BE(buf, buf.length - 4, p);\n p += 4;\n\n buf[p] = REQUEST.EXTENDED;\n ++p;\n\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, p);\n p += 4;\n\n writeUInt32BE(buf, 14, p);\n p += 4;\n buf.utf8Write('home-directory', p, 14);\n p += 14;\n\n writeUInt32BE(buf, usernameLen, p);\n p += 4;\n buf.utf8Write(username, p, usernameLen);\n p += usernameLen;\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing home directory'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} home-directory`);\n }\n }\n ext_users_groups(uids, gids, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['users-groups-by-id@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n if (!Array.isArray(uids))\n throw new TypeError('uids is not an array');\n for (const val of uids) {\n if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1))\n throw new Error('uid values must all be 32-bit unsigned integers');\n }\n if (!Array.isArray(gids))\n throw new TypeError('gids is not an array');\n for (const val of gids) {\n if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1))\n throw new Error('gid values must all be 32-bit unsigned integers');\n }\n\n /*\n uint32 id\n string \"users-groups-by-id@openssh.com\"\n string uids\n uint32 uid1\n ...\n string gids\n uint32 gid1\n ...\n */\n let p = 0;\n const buf = Buffer.allocUnsafe(\n 4 + 1\n + 4\n + 4 + 30\n + 4 + (4 * uids.length)\n + 4 + (4 * gids.length)\n );\n\n writeUInt32BE(buf, buf.length - 4, p);\n p += 4;\n\n buf[p] = REQUEST.EXTENDED;\n ++p;\n\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, p);\n p += 4;\n\n writeUInt32BE(buf, 30, p);\n p += 4;\n buf.utf8Write('users-groups-by-id@openssh.com', p, 30);\n p += 30;\n\n writeUInt32BE(buf, 4 * uids.length, p);\n p += 4;\n for (const val of uids) {\n writeUInt32BE(buf, val, p);\n p += 4;\n }\n\n writeUInt32BE(buf, 4 * gids.length, p);\n p += 4;\n for (const val of gids) {\n writeUInt32BE(buf, val, p);\n p += 4;\n }\n\n this._requests[reqid] = { extended: 'users-groups-by-id@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`);\n }\n }\n // ===========================================================================\n // Server-specific ===========================================================\n // ===========================================================================\n handle(reqid, handle) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n const handleLen = handle.length;\n\n if (handleLen > 256)\n throw new Error('handle too large (> 256 bytes)');\n\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.HANDLE;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n if (handleLen)\n buf.set(handle, p += 4);\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE`\n );\n }\n status(reqid, code, message) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!VALID_STATUS_CODES.has(code))\n throw new Error(`Bad status code: ${code}`);\n\n message || (message = '');\n\n const msgLen = Buffer.byteLength(message);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.STATUS;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, code, p);\n\n writeUInt32BE(buf, msgLen, p += 4);\n p += 4;\n if (msgLen) {\n buf.utf8Write(message, p, msgLen);\n p += msgLen;\n }\n\n writeUInt32BE(buf, 0, p); // Empty language tag\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS`\n );\n }\n data(reqid, data, encoding) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n const isBuffer = Buffer.isBuffer(data);\n\n if (!isBuffer && typeof data !== 'string')\n throw new Error('data is not a Buffer or string');\n\n let isUTF8;\n if (!isBuffer && !encoding) {\n encoding = undefined;\n isUTF8 = true;\n }\n\n const dataLen = (\n isBuffer\n ? data.length\n : Buffer.byteLength(data, encoding)\n );\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.DATA;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, dataLen, p);\n if (dataLen) {\n if (isBuffer)\n buf.set(data, p += 4);\n else if (isUTF8)\n buf.utf8Write(data, p += 4, dataLen);\n else\n buf.write(data, p += 4, dataLen, encoding);\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA`\n );\n }\n name(reqid, names) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!Array.isArray(names)) {\n if (typeof names !== 'object' || names === null)\n throw new Error('names is not an object or array');\n names = [ names ];\n }\n\n const count = names.length;\n let namesLen = 0;\n let nameAttrs;\n const attrs = [];\n\n for (let i = 0; i < count; ++i) {\n const name = names[i];\n const filename = (\n !name || !name.filename || typeof name.filename !== 'string'\n ? ''\n : name.filename\n );\n namesLen += 4 + Buffer.byteLength(filename);\n const longname = (\n !name || !name.longname || typeof name.longname !== 'string'\n ? ''\n : name.longname\n );\n namesLen += 4 + Buffer.byteLength(longname);\n\n if (typeof name.attrs === 'object' && name.attrs !== null) {\n nameAttrs = attrsToBytes(name.attrs);\n namesLen += 4 + nameAttrs.nb;\n\n if (nameAttrs.nb) {\n let bytes;\n\n if (nameAttrs.nb === ATTRS_BUF.length) {\n bytes = new Uint8Array(ATTRS_BUF);\n } else {\n bytes = new Uint8Array(nameAttrs.nb);\n bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0);\n }\n\n nameAttrs.bytes = bytes;\n }\n\n attrs.push(nameAttrs);\n } else {\n namesLen += 4;\n attrs.push(null);\n }\n }\n\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.NAME;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, count, p);\n\n p += 4;\n\n for (let i = 0; i < count; ++i) {\n const name = names[i];\n\n {\n const filename = (\n !name || !name.filename || typeof name.filename !== 'string'\n ? ''\n : name.filename\n );\n const len = Buffer.byteLength(filename);\n writeUInt32BE(buf, len, p);\n p += 4;\n if (len) {\n buf.utf8Write(filename, p, len);\n p += len;\n }\n }\n\n {\n const longname = (\n !name || !name.longname || typeof name.longname !== 'string'\n ? ''\n : name.longname\n );\n const len = Buffer.byteLength(longname);\n writeUInt32BE(buf, len, p);\n p += 4;\n if (len) {\n buf.utf8Write(longname, p, len);\n p += len;\n }\n }\n\n const attr = attrs[i];\n if (attr) {\n writeUInt32BE(buf, attr.flags, p);\n p += 4;\n if (attr.flags && attr.bytes) {\n buf.set(attr.bytes, p);\n p += attr.nb;\n }\n } else {\n writeUInt32BE(buf, 0, p);\n p += 4;\n }\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME`\n );\n }\n attrs(reqid, attrs) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (typeof attrs !== 'object' || attrs === null)\n throw new Error('attrs is not an object');\n\n attrs = attrsToBytes(attrs);\n const flags = attrs.flags;\n const attrsLen = attrs.nb;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.ATTRS;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, flags, p);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS`\n );\n }\n}\n\nfunction tryCreateBuffer(size) {\n try {\n return Buffer.allocUnsafe(size);\n } catch (ex) {\n return ex;\n }\n}\n\nfunction read_(self, handle, buf, off, len, position, cb, req_) {\n const maxDataLen = self._maxReadLen;\n const overflow = Math.max(len - maxDataLen, 0);\n\n if (overflow)\n len = maxDataLen;\n\n /*\n uint32 id\n string handle\n uint64 offset\n uint32 len\n */\n const handleLen = handle.length;\n let p = 9;\n let pos = position;\n const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4);\n\n writeUInt32BE(out, out.length - 4, 0);\n out[4] = REQUEST.READ;\n const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(out, reqid, 5);\n\n writeUInt32BE(out, handleLen, p);\n out.set(handle, p += 4);\n p += handleLen;\n for (let i = 7; i >= 0; --i) {\n out[p + i] = pos & 0xFF;\n pos /= 256;\n }\n writeUInt32BE(out, len, p += 8);\n\n if (typeof cb !== 'function')\n cb = noop;\n\n const req = (req_ || {\n nb: 0,\n position,\n off,\n origOff: off,\n len: undefined,\n overflow: undefined,\n cb: (err, data, nb) => {\n const len = req.len;\n const overflow = req.overflow;\n\n if (err) {\n if (cb._wantEOFError || err.code !== STATUS_CODE.EOF)\n return cb(err);\n } else if (nb > len) {\n return cb(new Error('Received more data than requested'));\n } else if (nb === len && overflow) {\n req.nb += nb;\n req.position += nb;\n req.off += nb;\n read_(self, handle, buf, req.off, overflow, req.position, cb, req);\n return;\n }\n\n nb = (nb || 0);\n if (req.origOff === 0 && buf.length === req.nb)\n data = buf;\n else\n data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb);\n cb(undefined, req.nb + nb, data, req.position);\n },\n buffer: undefined,\n });\n\n req.len = len;\n req.overflow = overflow;\n\n // TODO: avoid creating multiple buffer slices when we need to re-call read_()\n // because of overflow\n req.buffer = bufferSlice(buf, off, off + len);\n\n self._requests[reqid] = req;\n\n const isBuffered = sendOrBuffer(self, out);\n self._debug && self._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ`\n );\n}\n\nfunction fastXfer(src, dst, srcPath, dstPath, opts, cb) {\n let concurrency = 64;\n let chunkSize = 32768;\n let onstep;\n let mode;\n let fileSize;\n\n if (typeof opts === 'function') {\n cb = opts;\n } else if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.concurrency === 'number'\n && opts.concurrency > 0\n && !isNaN(opts.concurrency)) {\n concurrency = opts.concurrency;\n }\n if (typeof opts.chunkSize === 'number'\n && opts.chunkSize > 0\n && !isNaN(opts.chunkSize)) {\n chunkSize = opts.chunkSize;\n }\n if (typeof opts.fileSize === 'number'\n && opts.fileSize > 0\n && !isNaN(opts.fileSize)) {\n fileSize = opts.fileSize;\n }\n if (typeof opts.step === 'function')\n onstep = opts.step;\n\n if (typeof opts.mode === 'string' || typeof opts.mode === 'number')\n mode = modeNum(opts.mode);\n }\n\n // Internal state variables\n let fsize;\n let pdst = 0;\n let total = 0;\n let hadError = false;\n let srcHandle;\n let dstHandle;\n let readbuf;\n let bufsize = chunkSize * concurrency;\n\n function onerror(err) {\n if (hadError)\n return;\n\n hadError = true;\n\n let left = 0;\n let cbfinal;\n\n if (srcHandle || dstHandle) {\n cbfinal = () => {\n if (--left === 0)\n cb(err);\n };\n if (srcHandle && (src === fs || src.outgoing.state === 'open'))\n ++left;\n if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))\n ++left;\n if (srcHandle && (src === fs || src.outgoing.state === 'open'))\n src.close(srcHandle, cbfinal);\n if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))\n dst.close(dstHandle, cbfinal);\n } else {\n cb(err);\n }\n }\n\n src.open(srcPath, 'r', (err, sourceHandle) => {\n if (err)\n return onerror(err);\n\n srcHandle = sourceHandle;\n\n if (fileSize === undefined)\n src.fstat(srcHandle, tryStat);\n else\n tryStat(null, { size: fileSize });\n\n function tryStat(err, attrs) {\n if (err) {\n if (src !== fs) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n src.stat(srcPath, (err_, attrs_) => {\n if (err_)\n return onerror(err);\n tryStat(null, attrs_);\n });\n return;\n }\n return onerror(err);\n }\n fsize = attrs.size;\n\n dst.open(dstPath, 'w', (err, destHandle) => {\n if (err)\n return onerror(err);\n\n dstHandle = destHandle;\n\n if (fsize <= 0)\n return onerror();\n\n // Use less memory where possible\n while (bufsize > fsize) {\n if (concurrency === 1) {\n bufsize = fsize;\n break;\n }\n bufsize -= chunkSize;\n --concurrency;\n }\n\n readbuf = tryCreateBuffer(bufsize);\n if (readbuf instanceof Error)\n return onerror(readbuf);\n\n if (mode !== undefined) {\n dst.fchmod(dstHandle, mode, function tryAgain(err) {\n if (err) {\n // Try chmod() for sftp servers that may not support fchmod()\n // for whatever reason\n dst.chmod(dstPath, mode, (err_) => tryAgain());\n return;\n }\n startReads();\n });\n } else {\n startReads();\n }\n\n function onread(err, nb, data, dstpos, datapos, origChunkLen) {\n if (err)\n return onerror(err);\n\n datapos = datapos || 0;\n\n dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb);\n\n function writeCb(err) {\n if (err)\n return onerror(err);\n\n total += nb;\n onstep && onstep(total, nb, fsize);\n\n if (nb < origChunkLen)\n return singleRead(datapos, dstpos + nb, origChunkLen - nb);\n\n if (total === fsize) {\n dst.close(dstHandle, (err) => {\n dstHandle = undefined;\n if (err)\n return onerror(err);\n src.close(srcHandle, (err) => {\n srcHandle = undefined;\n if (err)\n return onerror(err);\n cb();\n });\n });\n return;\n }\n\n if (pdst >= fsize)\n return;\n\n const chunk =\n (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);\n singleRead(datapos, pdst, chunk);\n pdst += chunk;\n }\n }\n\n function makeCb(psrc, pdst, chunk) {\n return (err, nb, data) => {\n onread(err, nb, data, pdst, psrc, chunk);\n };\n }\n\n function singleRead(psrc, pdst, chunk) {\n src.read(srcHandle,\n readbuf,\n psrc,\n chunk,\n pdst,\n makeCb(psrc, pdst, chunk));\n }\n\n function startReads() {\n let reads = 0;\n let psrc = 0;\n while (pdst < fsize && reads < concurrency) {\n const chunk =\n (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);\n singleRead(psrc, pdst, chunk);\n psrc += chunk;\n pdst += chunk;\n ++reads;\n }\n }\n });\n }\n });\n}\n\nfunction writeAll(sftp, handle, buffer, offset, length, position, callback_) {\n const callback = (typeof callback_ === 'function' ? callback_ : undefined);\n\n sftp.write(handle,\n buffer,\n offset,\n length,\n position,\n (writeErr, written) => {\n if (writeErr) {\n return sftp.close(handle, () => {\n callback && callback(writeErr);\n });\n }\n if (written === length) {\n sftp.close(handle, callback);\n } else {\n offset += written;\n length -= written;\n position += written;\n writeAll(sftp, handle, buffer, offset, length, position, callback);\n }\n });\n}\n\nclass Stats {\n constructor(initial) {\n this.mode = (initial && initial.mode);\n this.uid = (initial && initial.uid);\n this.gid = (initial && initial.gid);\n this.size = (initial && initial.size);\n this.atime = (initial && initial.atime);\n this.mtime = (initial && initial.mtime);\n this.extended = (initial && initial.extended);\n }\n isDirectory() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFDIR);\n }\n isFile() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFREG);\n }\n isBlockDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFBLK);\n }\n isCharacterDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFCHR);\n }\n isSymbolicLink() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFLNK);\n }\n isFIFO() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFIFO);\n }\n isSocket() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK);\n }\n}\n\nfunction attrsToBytes(attrs) {\n let flags = 0;\n let nb = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n if (typeof attrs.size === 'number') {\n flags |= ATTR.SIZE;\n const val = attrs.size;\n // Big Endian\n ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56\n ATTRS_BUF[nb++] = val / 281474976710656; // 2**48\n ATTRS_BUF[nb++] = val / 1099511627776; // 2**40\n ATTRS_BUF[nb++] = val / 4294967296; // 2**32\n ATTRS_BUF[nb++] = val / 16777216; // 2**24\n ATTRS_BUF[nb++] = val / 65536; // 2**16\n ATTRS_BUF[nb++] = val / 256; // 2**8\n ATTRS_BUF[nb++] = val;\n }\n if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') {\n flags |= ATTR.UIDGID;\n const uid = attrs.uid;\n const gid = attrs.gid;\n // Big Endian\n ATTRS_BUF[nb++] = uid >>> 24;\n ATTRS_BUF[nb++] = uid >>> 16;\n ATTRS_BUF[nb++] = uid >>> 8;\n ATTRS_BUF[nb++] = uid;\n ATTRS_BUF[nb++] = gid >>> 24;\n ATTRS_BUF[nb++] = gid >>> 16;\n ATTRS_BUF[nb++] = gid >>> 8;\n ATTRS_BUF[nb++] = gid;\n }\n if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') {\n const mode = modeNum(attrs.mode);\n flags |= ATTR.PERMISSIONS;\n // Big Endian\n ATTRS_BUF[nb++] = mode >>> 24;\n ATTRS_BUF[nb++] = mode >>> 16;\n ATTRS_BUF[nb++] = mode >>> 8;\n ATTRS_BUF[nb++] = mode;\n }\n if ((typeof attrs.atime === 'number' || isDate(attrs.atime))\n && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) {\n const atime = toUnixTimestamp(attrs.atime);\n const mtime = toUnixTimestamp(attrs.mtime);\n\n flags |= ATTR.ACMODTIME;\n // Big Endian\n ATTRS_BUF[nb++] = atime >>> 24;\n ATTRS_BUF[nb++] = atime >>> 16;\n ATTRS_BUF[nb++] = atime >>> 8;\n ATTRS_BUF[nb++] = atime;\n ATTRS_BUF[nb++] = mtime >>> 24;\n ATTRS_BUF[nb++] = mtime >>> 16;\n ATTRS_BUF[nb++] = mtime >>> 8;\n ATTRS_BUF[nb++] = mtime;\n }\n // TODO: extended attributes\n }\n\n return { flags, nb };\n}\n\nfunction toUnixTimestamp(time) {\n // eslint-disable-next-line no-self-compare\n if (typeof time === 'number' && time === time) // Valid, non-NaN number\n return time;\n if (isDate(time))\n return parseInt(time.getTime() / 1000, 10);\n throw new Error(`Cannot parse time: ${time}`);\n}\n\nfunction modeNum(mode) {\n // eslint-disable-next-line no-self-compare\n if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number\n return mode;\n if (typeof mode === 'string')\n return modeNum(parseInt(mode, 8));\n throw new Error(`Cannot parse mode: ${mode}`);\n}\n\nconst stringFlagMap = {\n 'r': OPEN_MODE.READ,\n 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE,\n 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE,\n 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL\n};\n\nfunction stringToFlags(str) {\n const flags = stringFlagMap[str];\n return (flags !== undefined ? flags : null);\n}\n\nconst flagsToString = (() => {\n const stringFlagMapKeys = Object.keys(stringFlagMap);\n return (flags) => {\n for (let i = 0; i < stringFlagMapKeys.length; ++i) {\n const key = stringFlagMapKeys[i];\n if (stringFlagMap[key] === flags)\n return key;\n }\n return null;\n };\n})();\n\nfunction readAttrs(biOpt) {\n /*\n uint32 flags\n uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE\n uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID\n uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID\n uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS\n uint32 atime present only if flag SSH_FILEXFER_ACMODTIME\n uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME\n uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED\n string extended_type\n string extended_data\n ... more extended data (extended_type - extended_data pairs),\n so that number of pairs equals extended_count\n */\n const flags = bufferParser.readUInt32BE();\n if (flags === undefined)\n return;\n\n const attrs = new Stats();\n if (flags & ATTR.SIZE) {\n const size = bufferParser.readUInt64BE(biOpt);\n if (size === undefined)\n return;\n attrs.size = size;\n }\n\n if (flags & ATTR.UIDGID) {\n const uid = bufferParser.readUInt32BE();\n const gid = bufferParser.readUInt32BE();\n if (gid === undefined)\n return;\n attrs.uid = uid;\n attrs.gid = gid;\n }\n\n if (flags & ATTR.PERMISSIONS) {\n const mode = bufferParser.readUInt32BE();\n if (mode === undefined)\n return;\n attrs.mode = mode;\n }\n\n if (flags & ATTR.ACMODTIME) {\n const atime = bufferParser.readUInt32BE();\n const mtime = bufferParser.readUInt32BE();\n if (mtime === undefined)\n return;\n attrs.atime = atime;\n attrs.mtime = mtime;\n }\n\n if (flags & ATTR.EXTENDED) {\n const count = bufferParser.readUInt32BE();\n if (count === undefined)\n return;\n const extended = {};\n for (let i = 0; i < count; ++i) {\n const type = bufferParser.readString(true);\n const data = bufferParser.readString();\n if (data === undefined)\n return;\n extended[type] = data;\n }\n attrs.extended = extended;\n }\n\n return attrs;\n}\n\nfunction sendOrBuffer(sftp, payload) {\n const ret = tryWritePayload(sftp, payload);\n if (ret !== undefined) {\n sftp._buffer.push(ret);\n return false;\n }\n return true;\n}\n\nfunction tryWritePayload(sftp, payload) {\n const outgoing = sftp.outgoing;\n if (outgoing.state !== 'open')\n return;\n\n if (outgoing.window === 0) {\n sftp._waitWindow = true;\n sftp._chunkcb = drainBuffer;\n return payload;\n }\n\n let ret;\n const len = payload.length;\n let p = 0;\n\n while (len - p > 0 && outgoing.window > 0) {\n const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize);\n outgoing.window -= actualLen;\n if (outgoing.window === 0) {\n sftp._waitWindow = true;\n sftp._chunkcb = drainBuffer;\n }\n\n if (p === 0 && actualLen === len) {\n sftp._protocol.channelData(sftp.outgoing.id, payload);\n } else {\n sftp._protocol.channelData(sftp.outgoing.id,\n bufferSlice(payload, p, p + actualLen));\n }\n\n p += actualLen;\n }\n\n if (len - p > 0) {\n if (p > 0)\n ret = bufferSlice(payload, p, len);\n else\n ret = payload; // XXX: should never get here?\n }\n\n return ret;\n}\n\nfunction drainBuffer() {\n this._chunkcb = undefined;\n const buffer = this._buffer;\n let i = 0;\n while (i < buffer.length) {\n const payload = buffer[i];\n const ret = tryWritePayload(this, payload);\n if (ret !== undefined) {\n if (ret !== payload)\n buffer[i] = ret;\n if (i > 0)\n this._buffer = buffer.slice(i);\n return;\n }\n ++i;\n }\n if (i > 0)\n this._buffer = [];\n}\n\nfunction doFatalSFTPError(sftp, msg, noDebug) {\n const err = new Error(msg);\n err.level = 'sftp-protocol';\n if (!noDebug && sftp._debug)\n sftp._debug(`SFTP: Inbound: ${msg}`);\n sftp.emit('error', err);\n sftp.destroy();\n cleanupRequests(sftp);\n return false;\n}\n\nfunction cleanupRequests(sftp) {\n const keys = Object.keys(sftp._requests);\n if (keys.length === 0)\n return;\n\n const reqs = sftp._requests;\n sftp._requests = {};\n const err = new Error('No response from server');\n for (let i = 0; i < keys.length; ++i) {\n const req = reqs[keys[i]];\n if (typeof req.cb === 'function')\n req.cb(err);\n }\n}\n\nfunction requestLimits(sftp, cb) {\n /*\n uint32 id\n string \"limits@openssh.com\"\n */\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 18, p);\n buf.utf8Write('limits@openssh.com', p += 4, 18);\n\n sftp._requests[reqid] = { extended: 'limits@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(sftp, buf);\n if (sftp._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`);\n }\n}\n\nconst CLIENT_HANDLERS = {\n [RESPONSE.VERSION]: (sftp, payload) => {\n if (sftp._version !== -1)\n return doFatalSFTPError(sftp, 'Duplicate VERSION packet');\n\n const extensions = {};\n\n /*\n uint32 version\n \n */\n bufferParser.init(payload, 1);\n let version = bufferParser.readUInt32BE();\n while (bufferParser.avail()) {\n const extName = bufferParser.readString(true);\n const extData = bufferParser.readString(true);\n if (extData === undefined) {\n version = undefined;\n break;\n }\n extensions[extName] = extData;\n }\n bufferParser.clear();\n\n if (version === undefined)\n return doFatalSFTPError(sftp, 'Malformed VERSION packet');\n\n if (sftp._debug) {\n const names = Object.keys(extensions);\n if (names.length) {\n sftp._debug(\n `SFTP: Inbound: Received VERSION (v${version}, exts:${names})`\n );\n } else {\n sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`);\n }\n }\n\n sftp._version = version;\n sftp._extensions = extensions;\n\n if (extensions['limits@openssh.com'] === '1') {\n return requestLimits(sftp, (err, limits) => {\n if (!err) {\n if (limits.maxPktLen > 0)\n sftp._maxOutPktLen = limits.maxPktLen;\n if (limits.maxReadLen > 0)\n sftp._maxReadLen = limits.maxReadLen;\n if (limits.maxWriteLen > 0)\n sftp._maxWriteLen = limits.maxWriteLen;\n sftp.maxOpenHandles = (\n limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity\n );\n }\n sftp.emit('ready');\n });\n }\n\n sftp.emit('ready');\n },\n [RESPONSE.STATUS]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n uint32 error/status code\n string error message (ISO-10646 UTF-8)\n string language tag\n */\n const errorCode = bufferParser.readUInt32BE();\n const errorMsg = bufferParser.readString(true);\n bufferParser.clear();\n\n // Note: we avoid checking that the error message and language tag are in\n // the packet because there are some broken implementations that incorrectly\n // omit them. The language tag in general was never really used amongst ssh\n // implementations, so in the case of a missing error message we just\n // default to something sensible.\n\n if (sftp._debug) {\n const jsonMsg = JSON.stringify(errorMsg);\n sftp._debug(\n `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})`\n );\n }\n const req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n if (req && typeof req.cb === 'function') {\n if (errorCode === STATUS_CODE.OK) {\n req.cb();\n return;\n }\n const err = new Error(errorMsg\n || STATUS_CODE_STR[errorCode]\n || 'Unknown status');\n err.code = errorCode;\n req.cb(err);\n }\n },\n [RESPONSE.HANDLE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined) {\n if (reqID !== undefined)\n delete sftp._requests[reqID];\n return doFatalSFTPError(sftp, 'Malformed HANDLE packet');\n }\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`);\n\n const req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n if (req && typeof req.cb === 'function')\n req.cb(undefined, handle);\n },\n [RESPONSE.DATA]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n string data\n */\n if (req && typeof req.cb === 'function') {\n if (req.buffer) {\n // We have already pre-allocated space to store the data\n\n const nb = bufferParser.readString(req.buffer);\n bufferParser.clear();\n\n if (nb !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`\n );\n req.cb(undefined, req.buffer, nb);\n return;\n }\n } else {\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})`\n );\n req.cb(undefined, data);\n return;\n }\n }\n } else {\n const nb = bufferParser.skipString();\n bufferParser.clear();\n if (nb !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`\n );\n return;\n }\n }\n\n return doFatalSFTPError(sftp, 'Malformed DATA packet');\n },\n [RESPONSE.NAME]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n uint32 count\n repeats count times:\n string filename\n string longname\n ATTRS attrs\n */\n const count = bufferParser.readUInt32BE();\n if (count !== undefined) {\n let names = [];\n for (let i = 0; i < count; ++i) {\n // We are going to assume UTF-8 for filenames despite the SFTPv3\n // spec not specifying an encoding because the specs for newer\n // versions of the protocol all explicitly specify UTF-8 for\n // filenames\n const filename = bufferParser.readString(true);\n\n // `longname` only exists in SFTPv3 and since it typically will\n // contain the filename, we assume it is also UTF-8\n const longname = bufferParser.readString(true);\n\n const attrs = readAttrs(sftp._biOpt);\n if (attrs === undefined) {\n names = undefined;\n break;\n }\n names.push({ filename, longname, attrs });\n }\n if (names !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})`\n );\n bufferParser.clear();\n if (req && typeof req.cb === 'function')\n req.cb(undefined, names);\n return;\n }\n }\n\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed NAME packet');\n },\n [RESPONSE.ATTRS]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n ATTRS attrs\n */\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n if (attrs !== undefined) {\n sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`);\n if (req && typeof req.cb === 'function')\n req.cb(undefined, attrs);\n return;\n }\n\n return doFatalSFTPError(sftp, 'Malformed ATTRS packet');\n },\n [RESPONSE.EXTENDED]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n if (reqID !== undefined) {\n const req = sftp._requests[reqID];\n if (req) {\n delete sftp._requests[reqID];\n switch (req.extended) {\n case 'statvfs@openssh.com':\n case 'fstatvfs@openssh.com': {\n /*\n uint64 f_bsize // file system block size\n uint64 f_frsize // fundamental fs block size\n uint64 f_blocks // number of blocks (unit f_frsize)\n uint64 f_bfree // free blocks in file system\n uint64 f_bavail // free blocks for non-root\n uint64 f_files // total file inodes\n uint64 f_ffree // free file inodes\n uint64 f_favail // free file inodes for to non-root\n uint64 f_fsid // file system id\n uint64 f_flag // bit mask of f_flag values\n uint64 f_namemax // maximum filename length\n */\n const biOpt = sftp._biOpt;\n const stats = {\n f_bsize: bufferParser.readUInt64BE(biOpt),\n f_frsize: bufferParser.readUInt64BE(biOpt),\n f_blocks: bufferParser.readUInt64BE(biOpt),\n f_bfree: bufferParser.readUInt64BE(biOpt),\n f_bavail: bufferParser.readUInt64BE(biOpt),\n f_files: bufferParser.readUInt64BE(biOpt),\n f_ffree: bufferParser.readUInt64BE(biOpt),\n f_favail: bufferParser.readUInt64BE(biOpt),\n f_sid: bufferParser.readUInt64BE(biOpt),\n f_flag: bufferParser.readUInt64BE(biOpt),\n f_namemax: bufferParser.readUInt64BE(biOpt),\n };\n if (stats.f_namemax === undefined)\n break;\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, stats);\n return;\n }\n case 'limits@openssh.com': {\n /*\n uint64 max-packet-length\n uint64 max-read-length\n uint64 max-write-length\n uint64 max-open-handles\n */\n const limits = {\n maxPktLen: bufferParser.readUInt64BE(),\n maxReadLen: bufferParser.readUInt64BE(),\n maxWriteLen: bufferParser.readUInt64BE(),\n maxOpenHandles: bufferParser.readUInt64BE(),\n };\n if (limits.maxOpenHandles === undefined)\n break;\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, limits);\n return;\n }\n case 'users-groups-by-id@openssh.com': {\n /*\n string usernames\n string username1\n ...\n string groupnames\n string groupname1\n ...\n */\n const usernameCount = bufferParser.readUInt32BE();\n if (usernameCount === undefined)\n break;\n const usernames = new Array(usernameCount);\n for (let i = 0; i < usernames.length; ++i)\n usernames[i] = bufferParser.readString(true);\n\n const groupnameCount = bufferParser.readUInt32BE();\n if (groupnameCount === undefined)\n break;\n const groupnames = new Array(groupnameCount);\n for (let i = 0; i < groupnames.length; ++i)\n groupnames[i] = bufferParser.readString(true);\n if (groupnames.length > 0\n && groupnames[groupnames.length - 1] === undefined) {\n break;\n }\n\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, usernames, groupnames);\n return;\n }\n default:\n // Unknown extended request\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`\n );\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb();\n return;\n }\n } else {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`\n );\n bufferParser.clear();\n return;\n }\n }\n\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet');\n },\n};\nconst SERVER_HANDLERS = {\n [REQUEST.INIT]: (sftp, payload) => {\n if (sftp._version !== -1)\n return doFatalSFTPError(sftp, 'Duplicate INIT packet');\n\n const extensions = {};\n\n /*\n uint32 version\n \n */\n bufferParser.init(payload, 1);\n let version = bufferParser.readUInt32BE();\n while (bufferParser.avail()) {\n const extName = bufferParser.readString(true);\n const extData = bufferParser.readString(true);\n if (extData === undefined) {\n version = undefined;\n break;\n }\n extensions[extName] = extData;\n }\n bufferParser.clear();\n\n if (version === undefined)\n return doFatalSFTPError(sftp, 'Malformed INIT packet');\n\n if (sftp._debug) {\n const names = Object.keys(extensions);\n if (names.length) {\n sftp._debug(\n `SFTP: Inbound: Received INIT (v${version}, exts:${names})`\n );\n } else {\n sftp._debug(`SFTP: Inbound: Received INIT (v${version})`);\n }\n }\n\n sendOrBuffer(sftp, SERVER_VERSION_BUFFER);\n\n sftp._version = version;\n sftp._extensions = extensions;\n sftp.emit('ready');\n },\n [REQUEST.OPEN]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string filename\n uint32 pflags\n ATTRS attrs\n */\n const filename = bufferParser.readString(true);\n const pflags = bufferParser.readUInt32BE();\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed OPEN packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`);\n\n if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.CLOSE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed CLOSE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`);\n\n if (!sftp.emit('CLOSE', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READ]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n uint64 offset\n uint32 len\n */\n const handle = bufferParser.readString();\n const offset = bufferParser.readUInt64BE(sftp._biOpt);\n const len = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (len === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed READ packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`);\n\n if (!sftp.emit('READ', reqID, handle, offset, len)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.WRITE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n uint64 offset\n string data\n */\n const handle = bufferParser.readString();\n const offset = bufferParser.readUInt64BE(sftp._biOpt);\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed WRITE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`);\n\n if (!sftp.emit('WRITE', reqID, handle, offset, data)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.LSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed LSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`);\n\n if (!sftp.emit('LSTAT', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.FSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed FSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`);\n\n if (!sftp.emit('FSTAT', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.SETSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n ATTRS attrs\n */\n const path = bufferParser.readString(true);\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed SETSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`);\n\n if (!sftp.emit('SETSTAT', reqID, path, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.FSETSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n ATTRS attrs\n */\n const handle = bufferParser.readString();\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received FSETSTAT (id:${reqID})`\n );\n\n if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.OPENDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed OPENDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`);\n\n if (!sftp.emit('OPENDIR', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed READDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`);\n\n if (!sftp.emit('READDIR', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.REMOVE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed REMOVE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`);\n\n if (!sftp.emit('REMOVE', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.MKDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n ATTRS attrs\n */\n const path = bufferParser.readString(true);\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed MKDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`);\n\n if (!sftp.emit('MKDIR', reqID, path, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.RMDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed RMDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`);\n\n if (!sftp.emit('RMDIR', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.REALPATH]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed REALPATH packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received REALPATH (id:${reqID})`\n );\n\n if (!sftp.emit('REALPATH', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.STAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed STAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`);\n\n if (!sftp.emit('STAT', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.RENAME]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string oldpath\n string newpath\n */\n const oldPath = bufferParser.readString(true);\n const newPath = bufferParser.readString(true);\n bufferParser.clear();\n\n if (newPath === undefined)\n return doFatalSFTPError(sftp, 'Malformed RENAME packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`);\n\n if (!sftp.emit('RENAME', reqID, oldPath, newPath)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READLINK]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed READLINK packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received READLINK (id:${reqID})`\n );\n\n if (!sftp.emit('READLINK', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.SYMLINK]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string linkpath\n string targetpath\n */\n const linkPath = bufferParser.readString(true);\n const targetPath = bufferParser.readString(true);\n bufferParser.clear();\n\n if (targetPath === undefined)\n return doFatalSFTPError(sftp, 'Malformed SYMLINK packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`);\n\n let handled;\n if (sftp._isOpenSSH) {\n // OpenSSH has linkpath and targetpath positions switched\n handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath);\n } else {\n handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath);\n }\n if (!handled) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.EXTENDED]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string extended-request\n ... any request-specific data ...\n */\n const extName = bufferParser.readString(true);\n if (extName === undefined) {\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed EXTENDED packet');\n }\n\n let extData;\n if (bufferParser.avail())\n extData = bufferParser.readRaw();\n bufferParser.clear();\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED (id:${reqID})`\n );\n\n if (!sftp.emit('EXTENDED', reqID, extName, extData)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n};\n\n// =============================================================================\n// ReadStream/WriteStream-related ==============================================\n// =============================================================================\nconst {\n ERR_INVALID_ARG_TYPE,\n ERR_OUT_OF_RANGE,\n validateNumber\n} = require('./node-fs-compat');\n\nconst kMinPoolSpace = 128;\n\nlet pool;\n// It can happen that we expect to read a large chunk of data, and reserve\n// a large chunk of the pool accordingly, but the read() call only filled\n// a portion of it. If a concurrently executing read() then uses the same pool,\n// the \"reserved\" portion cannot be used, so we allow it to be re-used as a\n// new pool later.\nconst poolFragments = [];\n\nfunction allocNewPool(poolSize) {\n if (poolFragments.length > 0)\n pool = poolFragments.pop();\n else\n pool = Buffer.allocUnsafe(poolSize);\n pool.used = 0;\n}\n\n// Check the `this.start` and `this.end` of stream.\nfunction checkPosition(pos, name) {\n if (!Number.isSafeInteger(pos)) {\n validateNumber(pos, name);\n if (!Number.isInteger(pos))\n throw new ERR_OUT_OF_RANGE(name, 'an integer', pos);\n throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);\n }\n if (pos < 0)\n throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);\n}\n\nfunction roundUpToMultipleOf8(n) {\n return (n + 7) & ~7; // Align to 8 byte boundary.\n}\n\nfunction ReadStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // A little bit bigger buffer and water marks by default\n if (options.highWaterMark === undefined)\n options.highWaterMark = 64 * 1024;\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n options.autoDestroy = false; // Node 14 major change.\n\n ReadableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'r' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.end = options.end;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesRead = 0;\n this.isClosed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (this.end === undefined) {\n this.end = Infinity;\n } else if (this.end !== Infinity) {\n checkPosition(this.end, 'end');\n\n if (this.start !== undefined && this.start > this.end) {\n throw new ERR_OUT_OF_RANGE(\n 'start',\n `<= \"end\" (here: ${this.end})`,\n this.start\n );\n }\n }\n\n this.on('end', function() {\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}\ninherits(ReadStream, ReadableStream);\n\nReadStream.prototype.open = function() {\n if (this._opening)\n return;\n\n this._opening = true;\n\n this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {\n this._opening = false;\n\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n\n this.handle = handle;\n this.emit('open', handle);\n this.emit('ready');\n // Start the flow of data.\n this.read();\n });\n};\n\nReadStream.prototype._read = function(n) {\n if (!Buffer.isBuffer(this.handle))\n return this.once('open', () => this._read(n));\n\n // XXX: safe to remove this?\n if (this.destroyed)\n return;\n\n if (!pool || pool.length - pool.used < kMinPoolSpace) {\n // Discard the old pool.\n allocNewPool(this.readableHighWaterMark\n || this._readableState.highWaterMark);\n }\n\n // Grab another reference to the pool in the case that while we're\n // in the thread pool another read() finishes up the pool, and\n // allocates a new one.\n const thisPool = pool;\n let toRead = Math.min(pool.length - pool.used, n);\n const start = pool.used;\n\n if (this.end !== undefined)\n toRead = Math.min(this.end - this.pos + 1, toRead);\n\n // Already read everything we were supposed to read!\n // treat as EOF.\n if (toRead <= 0)\n return this.push(null);\n\n // the actual read.\n this.sftp.read(this.handle,\n pool,\n pool.used,\n toRead,\n this.pos,\n (er, bytesRead) => {\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n let b = null;\n\n // Now that we know how much data we have actually read, re-wind the\n // 'used' field if we can, and otherwise allow the remainder of our\n // reservation to be used as a new pool later.\n if (start + toRead === thisPool.used && thisPool === pool) {\n thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead);\n } else {\n // Round down to the next lowest multiple of 8 to ensure the new pool\n // fragment start and end positions are aligned to an 8 byte boundary.\n const alignedEnd = (start + toRead) & ~7;\n const alignedStart = roundUpToMultipleOf8(start + bytesRead);\n if (alignedEnd - alignedStart >= kMinPoolSpace)\n poolFragments.push(thisPool.slice(alignedStart, alignedEnd));\n }\n\n if (bytesRead > 0) {\n this.bytesRead += bytesRead;\n b = thisPool.slice(start, start + bytesRead);\n }\n\n // Move the pool positions, and internal position for reading.\n this.pos += bytesRead;\n\n this.push(b);\n });\n\n pool.used = roundUpToMultipleOf8(pool.used + toRead);\n};\n\nReadStream.prototype._destroy = function(err, cb) {\n if (this._opening && !Buffer.isBuffer(this.handle)) {\n this.once('open', closeStream.bind(null, this, cb, err));\n return;\n }\n\n closeStream(this, cb, err);\n this.handle = null;\n this._opening = false;\n};\n\nfunction closeStream(stream, cb, err) {\n if (!stream.handle)\n return onclose();\n\n stream.sftp.close(stream.handle, onclose);\n\n function onclose(er) {\n er = er || err;\n cb(er);\n stream.isClosed = true;\n if (!er)\n stream.emit('close');\n }\n}\n\nReadStream.prototype.close = function(cb) {\n this.destroy(null, cb);\n};\n\nObject.defineProperty(ReadStream.prototype, 'pending', {\n get() {\n return this.handle === null;\n },\n configurable: true\n});\n\n// TODO: add `concurrency` setting to allow more than one in-flight WRITE\n// request to server to improve throughput\nfunction WriteStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n options.autoDestroy = false; // Node 14 major change.\n\n WritableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'w' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesWritten = 0;\n this.isClosed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (options.encoding)\n this.setDefaultEncoding(options.encoding);\n\n // Node v6.x only\n this.on('finish', function() {\n if (this._writableState.finalCalled)\n return;\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}\ninherits(WriteStream, WritableStream);\n\nWriteStream.prototype._final = function(cb) {\n if (this.autoClose)\n this.destroy();\n cb();\n};\n\nWriteStream.prototype.open = function() {\n if (this._opening)\n return;\n\n this._opening = true;\n\n this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {\n this._opening = false;\n\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n\n this.handle = handle;\n\n const tryAgain = (err) => {\n if (err) {\n // Try chmod() for sftp servers that may not support fchmod() for\n // whatever reason\n this.sftp.chmod(this.path, this.mode, (err_) => tryAgain());\n return;\n }\n\n // SFTPv3 requires absolute offsets, no matter the open flag used\n if (this.flags[0] === 'a') {\n const tryStat = (err, st) => {\n if (err) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.sftp.stat(this.path, (err_, st_) => {\n if (err_) {\n this.destroy();\n this.emit('error', err);\n return;\n }\n tryStat(null, st_);\n });\n return;\n }\n\n this.pos = st.size;\n this.emit('open', handle);\n this.emit('ready');\n };\n\n this.sftp.fstat(handle, tryStat);\n return;\n }\n\n this.emit('open', handle);\n this.emit('ready');\n };\n\n this.sftp.fchmod(handle, this.mode, tryAgain);\n });\n};\n\nWriteStream.prototype._write = function(data, encoding, cb) {\n if (!Buffer.isBuffer(data)) {\n const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data);\n return this.emit('error', err);\n }\n\n if (!Buffer.isBuffer(this.handle)) {\n return this.once('open', function() {\n this._write(data, encoding, cb);\n });\n }\n\n this.sftp.write(this.handle,\n data,\n 0,\n data.length,\n this.pos,\n (er, bytes) => {\n if (er) {\n if (this.autoClose)\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n cb();\n });\n\n this.pos += data.length;\n};\n\nWriteStream.prototype._writev = function(data, cb) {\n if (!Buffer.isBuffer(this.handle)) {\n return this.once('open', function() {\n this._writev(data, cb);\n });\n }\n\n const sftp = this.sftp;\n const handle = this.handle;\n let writesLeft = data.length;\n\n const onwrite = (er, bytes) => {\n if (er) {\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n if (--writesLeft === 0)\n cb();\n };\n\n // TODO: try to combine chunks to reduce number of requests to the server?\n for (let i = 0; i < data.length; ++i) {\n const chunk = data[i].chunk;\n\n sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite);\n this.pos += chunk.length;\n }\n};\n\nif (typeof WritableStream.prototype.destroy !== 'function')\n WriteStream.prototype.destroy = ReadStream.prototype.destroy;\n\nWriteStream.prototype._destroy = ReadStream.prototype._destroy;\nWriteStream.prototype.close = function(cb) {\n if (cb) {\n if (this.isClosed) {\n process.nextTick(cb);\n return;\n }\n this.on('close', cb);\n }\n\n // If we are not autoClosing, we should call\n // destroy on 'finish'.\n if (!this.autoClose)\n this.on('finish', this.destroy.bind(this));\n\n this.end();\n};\n\n// There is no shutdown() for files.\nWriteStream.prototype.destroySoon = WriteStream.prototype.end;\n\nObject.defineProperty(WriteStream.prototype, 'pending', {\n get() {\n return this.handle === null;\n },\n configurable: true\n});\n// =============================================================================\n\nmodule.exports = {\n flagsToString,\n OPEN_MODE,\n SFTP,\n Stats,\n STATUS_CODE,\n stringToFlags,\n};\n","'use strict';\n\nconst crypto = require('crypto');\n\nlet cpuInfo;\ntry {\n cpuInfo = require('cpu-features')();\n} catch {}\n\nconst { bindingAvailable, CIPHER_INFO, MAC_INFO } = require('./crypto.js');\n\nconst eddsaSupported = (() => {\n if (typeof crypto.sign === 'function'\n && typeof crypto.verify === 'function') {\n const key =\n '-----BEGIN PRIVATE KEY-----\\r\\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD'\n + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\\r\\n-----END PRIVATE KEY-----';\n const data = Buffer.from('a');\n let sig;\n let verified;\n try {\n sig = crypto.sign(null, data, key);\n verified = crypto.verify(null, data, key, sig);\n } catch {}\n return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true);\n }\n\n return false;\n})();\n\nconst curve25519Supported = (typeof crypto.diffieHellman === 'function'\n && typeof crypto.generateKeyPairSync === 'function'\n && typeof crypto.createPublicKey === 'function');\n\nconst DEFAULT_KEX = [\n // https://tools.ietf.org/html/rfc5656#section-10.1\n 'ecdh-sha2-nistp256',\n 'ecdh-sha2-nistp384',\n 'ecdh-sha2-nistp521',\n\n // https://tools.ietf.org/html/rfc4419#section-4\n 'diffie-hellman-group-exchange-sha256',\n\n // https://tools.ietf.org/html/rfc8268\n 'diffie-hellman-group14-sha256',\n 'diffie-hellman-group15-sha512',\n 'diffie-hellman-group16-sha512',\n 'diffie-hellman-group17-sha512',\n 'diffie-hellman-group18-sha512',\n];\nif (curve25519Supported) {\n DEFAULT_KEX.unshift('curve25519-sha256');\n DEFAULT_KEX.unshift('curve25519-sha256@libssh.org');\n}\nconst SUPPORTED_KEX = DEFAULT_KEX.concat([\n // https://tools.ietf.org/html/rfc4419#section-4\n 'diffie-hellman-group-exchange-sha1',\n\n 'diffie-hellman-group14-sha1', // REQUIRED\n 'diffie-hellman-group1-sha1', // REQUIRED\n]);\n\n\nconst DEFAULT_SERVER_HOST_KEY = [\n 'ecdsa-sha2-nistp256',\n 'ecdsa-sha2-nistp384',\n 'ecdsa-sha2-nistp521',\n 'rsa-sha2-512', // RFC 8332\n 'rsa-sha2-256', // RFC 8332\n 'ssh-rsa',\n];\nif (eddsaSupported)\n DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519');\nconst SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([\n 'ssh-dss',\n]);\n\n\nconst canUseCipher = (() => {\n const ciphers = crypto.getCiphers();\n return (name) => ciphers.includes(CIPHER_INFO[name].sslName);\n})();\nlet DEFAULT_CIPHER = [\n // http://tools.ietf.org/html/rfc5647\n 'aes128-gcm@openssh.com',\n 'aes256-gcm@openssh.com',\n\n // http://tools.ietf.org/html/rfc4344#section-4\n 'aes128-ctr',\n 'aes192-ctr',\n 'aes256-ctr',\n];\nif (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) {\n // We know for sure the CPU does not support AES acceleration\n if (bindingAvailable)\n DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com');\n else\n DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com');\n} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') {\n // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers\n // seem to outperform it on x86, but it seems to be faster than CTR ciphers\n DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com');\n} else {\n DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com');\n}\nDEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher);\nconst SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([\n 'aes256-cbc',\n 'aes192-cbc',\n 'aes128-cbc',\n 'blowfish-cbc',\n '3des-cbc',\n 'aes128-gcm',\n 'aes256-gcm',\n\n // http://tools.ietf.org/html/rfc4345#section-4:\n 'arcfour256',\n 'arcfour128',\n\n 'cast128-cbc',\n 'arcfour',\n].filter(canUseCipher));\n\n\nconst canUseMAC = (() => {\n const hashes = crypto.getHashes();\n return (name) => hashes.includes(MAC_INFO[name].sslName);\n})();\nconst DEFAULT_MAC = [\n 'hmac-sha2-256-etm@openssh.com',\n 'hmac-sha2-512-etm@openssh.com',\n 'hmac-sha1-etm@openssh.com',\n 'hmac-sha2-256',\n 'hmac-sha2-512',\n 'hmac-sha1',\n].filter(canUseMAC);\nconst SUPPORTED_MAC = DEFAULT_MAC.concat([\n 'hmac-md5',\n 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256\n 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512\n 'hmac-ripemd160',\n 'hmac-sha1-96', // first 96 bits of HMAC-SHA1\n 'hmac-md5-96', // first 96 bits of HMAC-MD5\n].filter(canUseMAC));\n\nconst DEFAULT_COMPRESSION = [\n 'none',\n 'zlib@openssh.com', // ZLIB (LZ77) compression, except\n // compression/decompression does not start until after\n // successful user authentication\n 'zlib', // ZLIB (LZ77) compression\n];\nconst SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([\n]);\n\n\nconst COMPAT = {\n BAD_DHGEX: 1 << 0,\n OLD_EXIT: 1 << 1,\n DYN_RPORT_BUG: 1 << 2,\n BUG_DHGEX_LARGE: 1 << 3,\n IMPLY_RSA_SHA2_SIGALGS: 1 << 4,\n};\n\nmodule.exports = {\n MESSAGE: {\n // Transport layer protocol -- generic (1-19)\n DISCONNECT: 1,\n IGNORE: 2,\n UNIMPLEMENTED: 3,\n DEBUG: 4,\n SERVICE_REQUEST: 5,\n SERVICE_ACCEPT: 6,\n EXT_INFO: 7, // RFC 8308\n\n // Transport layer protocol -- algorithm negotiation (20-29)\n KEXINIT: 20,\n NEWKEYS: 21,\n\n // Transport layer protocol -- key exchange method-specific (30-49)\n KEXDH_INIT: 30,\n KEXDH_REPLY: 31,\n\n KEXDH_GEX_GROUP: 31,\n KEXDH_GEX_INIT: 32,\n KEXDH_GEX_REPLY: 33,\n KEXDH_GEX_REQUEST: 34,\n\n KEXECDH_INIT: 30,\n KEXECDH_REPLY: 31,\n\n // User auth protocol -- generic (50-59)\n USERAUTH_REQUEST: 50,\n USERAUTH_FAILURE: 51,\n USERAUTH_SUCCESS: 52,\n USERAUTH_BANNER: 53,\n\n // User auth protocol -- user auth method-specific (60-79)\n USERAUTH_PASSWD_CHANGEREQ: 60,\n\n USERAUTH_PK_OK: 60,\n\n USERAUTH_INFO_REQUEST: 60,\n USERAUTH_INFO_RESPONSE: 61,\n\n // Connection protocol -- generic (80-89)\n GLOBAL_REQUEST: 80,\n REQUEST_SUCCESS: 81,\n REQUEST_FAILURE: 82,\n\n // Connection protocol -- channel-related (90-127)\n CHANNEL_OPEN: 90,\n CHANNEL_OPEN_CONFIRMATION: 91,\n CHANNEL_OPEN_FAILURE: 92,\n CHANNEL_WINDOW_ADJUST: 93,\n CHANNEL_DATA: 94,\n CHANNEL_EXTENDED_DATA: 95,\n CHANNEL_EOF: 96,\n CHANNEL_CLOSE: 97,\n CHANNEL_REQUEST: 98,\n CHANNEL_SUCCESS: 99,\n CHANNEL_FAILURE: 100\n\n // Reserved for client protocols (128-191)\n\n // Local extensions (192-155)\n },\n DISCONNECT_REASON: {\n HOST_NOT_ALLOWED_TO_CONNECT: 1,\n PROTOCOL_ERROR: 2,\n KEY_EXCHANGE_FAILED: 3,\n RESERVED: 4,\n MAC_ERROR: 5,\n COMPRESSION_ERROR: 6,\n SERVICE_NOT_AVAILABLE: 7,\n PROTOCOL_VERSION_NOT_SUPPORTED: 8,\n HOST_KEY_NOT_VERIFIABLE: 9,\n CONNECTION_LOST: 10,\n BY_APPLICATION: 11,\n TOO_MANY_CONNECTIONS: 12,\n AUTH_CANCELED_BY_USER: 13,\n NO_MORE_AUTH_METHODS_AVAILABLE: 14,\n ILLEGAL_USER_NAME: 15,\n },\n DISCONNECT_REASON_STR: undefined,\n CHANNEL_OPEN_FAILURE: {\n ADMINISTRATIVELY_PROHIBITED: 1,\n CONNECT_FAILED: 2,\n UNKNOWN_CHANNEL_TYPE: 3,\n RESOURCE_SHORTAGE: 4\n },\n TERMINAL_MODE: {\n TTY_OP_END: 0, // Indicates end of options.\n VINTR: 1, // Interrupt character; 255 if none. Similarly for the\n // other characters. Not all of these characters are\n // supported on all systems.\n VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX\n // systems).\n VERASE: 3, // Erase the character to left of the cursor.\n VKILL: 4, // Kill the current input line.\n VEOF: 5, // End-of-file character (sends EOF from the\n // terminal).\n VEOL: 6, // End-of-line character in addition to carriage\n // return and/or linefeed.\n VEOL2: 7, // Additional end-of-line character.\n VSTART: 8, // Continues paused output (normally control-Q).\n VSTOP: 9, // Pauses output (normally control-S).\n VSUSP: 10, // Suspends the current program.\n VDSUSP: 11, // Another suspend character.\n VREPRINT: 12, // Reprints the current input line.\n VWERASE: 13, // Erases a word left of cursor.\n VLNEXT: 14, // Enter the next character typed literally, even if\n // it is a special character\n VFLUSH: 15, // Character to flush output.\n VSWTCH: 16, // Switch to a different shell layer.\n VSTATUS: 17, // Prints system status line (load, command, pid,\n // etc).\n VDISCARD: 18, // Toggles the flushing of terminal output.\n IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0\n // if this flag is FALSE, and 1 if it is TRUE.\n PARMRK: 31, // Mark parity and framing errors.\n INPCK: 32, // Enable checking of parity errors.\n ISTRIP: 33, // Strip 8th bit off characters.\n INLCR: 34, // Map NL into CR on input.\n IGNCR: 35, // Ignore CR on input.\n ICRNL: 36, // Map CR to NL on input.\n IUCLC: 37, // Translate uppercase characters to lowercase.\n IXON: 38, // Enable output flow control.\n IXANY: 39, // Any char will restart after stop.\n IXOFF: 40, // Enable input flow control.\n IMAXBEL: 41, // Ring bell on input queue full.\n ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP.\n ICANON: 51, // Canonicalize input lines.\n XCASE: 52, // Enable input and output of uppercase characters by\n // preceding their lowercase equivalents with \"\\\".\n ECHO: 53, // Enable echoing.\n ECHOE: 54, // Visually erase chars.\n ECHOK: 55, // Kill character discards current line.\n ECHONL: 56, // Echo NL even if ECHO is off.\n NOFLSH: 57, // Don't flush after interrupt.\n TOSTOP: 58, // Stop background jobs from output.\n IEXTEN: 59, // Enable extensions.\n ECHOCTL: 60, // Echo control characters as ^(Char).\n ECHOKE: 61, // Visual erase for line kill.\n PENDIN: 62, // Retype pending input.\n OPOST: 70, // Enable output processing.\n OLCUC: 71, // Convert lowercase to uppercase.\n ONLCR: 72, // Map NL to CR-NL.\n OCRNL: 73, // Translate carriage return to newline (output).\n ONOCR: 74, // Translate newline to carriage return-newline\n // (output).\n ONLRET: 75, // Newline performs a carriage return (output).\n CS7: 90, // 7 bit mode.\n CS8: 91, // 8 bit mode.\n PARENB: 92, // Parity enable.\n PARODD: 93, // Odd parity, else even.\n TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second.\n TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second.\n },\n CHANNEL_EXTENDED_DATATYPE: {\n STDERR: 1,\n },\n\n SIGNALS: [\n 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1',\n 'USR2', 'KILL', 'PIPE'\n ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}),\n\n COMPAT,\n COMPAT_CHECKS: [\n [ 'Cisco-1.25', COMPAT.BAD_DHGEX ],\n [ /^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE ],\n [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations\n [ /^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG ],\n [ /^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS ],\n ],\n\n // KEX proposal-related\n DEFAULT_KEX,\n SUPPORTED_KEX,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER,\n DEFAULT_MAC,\n SUPPORTED_MAC,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION,\n\n curve25519Supported,\n eddsaSupported,\n};\n\nmodule.exports.DISCONNECT_REASON_BY_VALUE =\n Array.from(Object.entries(module.exports.DISCONNECT_REASON))\n .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {});\n","// TODO:\n// * make max packet size configurable\n// * if decompression is enabled, use `._packet` in decipher instances as\n// input to (sync) zlib inflater with appropriate offset and length to\n// avoid an additional copy of payload data before inflation\n// * factor decompression status into packet length checks\n'use strict';\n\nconst {\n createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual\n} = require('crypto');\n\nconst { readUInt32BE, writeUInt32BE } = require('./utils.js');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst MAX_SEQNO = 2 ** 32 - 1;\nconst EMPTY_BUFFER = Buffer.alloc(0);\nconst BUF_INT = Buffer.alloc(4);\nconst DISCARD_CACHE = new Map();\nconst MAX_PACKET_SIZE = 35000;\n\nlet binding;\nlet AESGCMCipher;\nlet ChaChaPolyCipher;\nlet GenericCipher;\nlet AESGCMDecipher;\nlet ChaChaPolyDecipher;\nlet GenericDecipher;\ntry {\n binding = require('./crypto/build/Release/sshcrypto.node');\n ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher,\n AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding);\n} catch {}\n\nconst CIPHER_STREAM = 1 << 0;\nconst CIPHER_INFO = (() => {\n function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) {\n return {\n sslName,\n blockLen,\n keyLen,\n ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM)\n ? ivLen\n : blockLen),\n authLen,\n discardLen,\n stream: !!(flags & CIPHER_STREAM),\n };\n }\n\n return {\n 'chacha20-poly1305@openssh.com':\n info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM),\n\n 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM),\n 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM),\n 'aes128-gcm@openssh.com':\n info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM),\n 'aes256-gcm@openssh.com':\n info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM),\n\n 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0),\n 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0),\n 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0),\n 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0),\n '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0),\n 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0),\n 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0),\n 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0),\n\n 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM),\n 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM),\n 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM),\n '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM),\n 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM),\n 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM),\n\n /* The \"arcfour128\" algorithm is the RC4 cipher, as described in\n [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream\n generated by the cipher MUST be discarded, and the first byte of the\n first encrypted packet MUST be encrypted using the 1537th byte of\n keystream.\n\n -- http://tools.ietf.org/html/rfc4345#section-4 */\n 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM),\n };\n})();\n\nconst MAC_INFO = (() => {\n function info(sslName, len, actualLen, isETM) {\n return {\n sslName,\n len,\n actualLen,\n isETM,\n };\n }\n\n return {\n 'hmac-md5': info('md5', 16, 16, false),\n 'hmac-md5-96': info('md5', 16, 12, false),\n 'hmac-ripemd160': info('ripemd160', 20, 20, false),\n 'hmac-sha1': info('sha1', 20, 20, false),\n 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true),\n 'hmac-sha1-96': info('sha1', 20, 12, false),\n 'hmac-sha2-256': info('sha256', 32, 32, false),\n 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true),\n 'hmac-sha2-256-96': info('sha256', 32, 12, false),\n 'hmac-sha2-512': info('sha512', 64, 64, false),\n 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true),\n 'hmac-sha2-512-96': info('sha512', 64, 12, false),\n };\n})();\n\n\n// Should only_be used during the initial handshake\nclass NullCipher {\n constructor(seqno, onWrite) {\n this.outSeqno = seqno;\n this._onWrite = onWrite;\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - (pktLen & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nconst POLY1305_ZEROS = Buffer.alloc(32);\nconst POLY1305_OUT_COMPUTE = Buffer.alloc(16);\nlet POLY1305_WASM_MODULE;\nlet POLY1305_RESULT_MALLOC;\nlet poly1305_auth;\nclass ChaChaPolyCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encKeyMain = enc.cipherKey.slice(0, 32);\n this._encKeyPktLen = enc.cipherKey.slice(32);\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - ((pktLen - 4) & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Generate Poly1305 key\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12);\n const polyKey =\n createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE)\n .update(POLY1305_ZEROS);\n\n // Encrypt packet length\n const pktLenEnc =\n createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE)\n .update(packet.slice(0, 4));\n this._onWrite(pktLenEnc);\n\n // Encrypt rest of packet\n POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian)\n const payloadEnc =\n createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE)\n .update(packet.slice(4));\n this._onWrite(payloadEnc);\n\n // Calculate Poly1305 MAC\n poly1305_auth(POLY1305_RESULT_MALLOC,\n pktLenEnc,\n pktLenEnc.length,\n payloadEnc,\n payloadEnc.length,\n polyKey);\n const mac = Buffer.allocUnsafe(16);\n mac.set(\n new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer,\n POLY1305_RESULT_MALLOC,\n 16),\n 0\n );\n this._onWrite(mac);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass ChaChaPolyCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._instance = new ChaChaPolyCipher(enc.cipherKey);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - ((pktLen - 4) & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet, this.outSeqno);\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass AESGCMCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encSSLName = enc.cipherInfo.sslName;\n this._encKey = enc.cipherKey;\n this._encIV = enc.cipherIV;\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 16 - ((pktLen - 4) & (16 - 1));\n if (padLen < 4)\n padLen += 16;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV);\n cipher.setAutoPadding(false);\n\n const lenData = packet.slice(0, 4);\n cipher.setAAD(lenData);\n this._onWrite(lenData);\n\n // Encrypt pad length, payload, and padding\n const encrypted = cipher.update(packet.slice(4));\n this._onWrite(encrypted);\n const final = cipher.final();\n // XXX: final.length === 0 always?\n if (final.length)\n this._onWrite(final);\n\n // Generate MAC\n const tag = cipher.getAuthTag();\n this._onWrite(tag);\n\n // Increment counter in IV by 1 for next packet\n ivIncrement(this._encIV);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass AESGCMCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._instance = new AESGCMCipher(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 16 - ((pktLen - 4) & (16 - 1));\n if (padLen < 4)\n padLen += 16;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet);\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass GenericCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encBlockLen = enc.cipherInfo.blockLen;\n this._cipherInstance = createCipheriv(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV);\n this._macSSLName = enc.macInfo.sslName;\n this._macKey = enc.macKey;\n this._macActualLen = enc.macInfo.actualLen;\n this._macETM = enc.macInfo.isETM;\n this._aadLen = (this._macETM ? 4 : 0);\n this._dead = false;\n\n const discardLen = enc.cipherInfo.discardLen;\n if (discardLen) {\n let discard = DISCARD_CACHE.get(discardLen);\n if (discard === undefined) {\n discard = Buffer.alloc(discardLen);\n DISCARD_CACHE.set(discardLen, discard);\n }\n this._cipherInstance.update(discard);\n }\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n const blockLen = this._encBlockLen;\n\n let pktLen = 4 + 1 + payloadLen;\n let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1));\n if (padLen < 4)\n padLen += blockLen;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n let mac;\n if (this._macETM) {\n // Encrypt pad length, payload, and padding\n const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4);\n const encrypted = this._cipherInstance.update(\n new Uint8Array(packet.buffer,\n packet.byteOffset + 4,\n packet.length - 4)\n );\n\n this._onWrite(lenBytes);\n this._onWrite(encrypted);\n\n // TODO: look into storing seqno as 4-byte buffer and incrementing like we\n // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time\n mac = createHmac(this._macSSLName, this._macKey);\n writeUInt32BE(BUF_INT, this.outSeqno, 0);\n mac.update(BUF_INT);\n mac.update(lenBytes);\n mac.update(encrypted);\n } else {\n // Encrypt length field, pad length, payload, and padding\n const encrypted = this._cipherInstance.update(packet);\n this._onWrite(encrypted);\n\n // TODO: look into storing seqno as 4-byte buffer and incrementing like we\n // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time\n mac = createHmac(this._macSSLName, this._macKey);\n writeUInt32BE(BUF_INT, this.outSeqno, 0);\n mac.update(BUF_INT);\n mac.update(packet);\n }\n\n let digest = mac.digest();\n if (digest.length > this._macActualLen)\n digest = digest.slice(0, this._macActualLen);\n this._onWrite(digest);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass GenericCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encBlockLen = enc.cipherInfo.blockLen;\n this._macLen = enc.macInfo.len;\n this._macActualLen = enc.macInfo.actualLen;\n this._aadLen = (enc.macInfo.isETM ? 4 : 0);\n this._instance = new GenericCipher(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV,\n enc.macInfo.sslName,\n enc.macKey,\n enc.macInfo.isETM);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n const blockLen = this._encBlockLen;\n\n let pktLen = 4 + 1 + payloadLen;\n let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1));\n if (padLen < 4)\n padLen += blockLen;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + this._macLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet, this.outSeqno);\n\n if (this._macActualLen < this._macLen) {\n packet = new FastBuffer(packet.buffer,\n packet.byteOffset,\n (packet.length\n - (this._macLen - this._macActualLen)));\n }\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass NullDecipher {\n constructor(seqno, onPayload) {\n this.inSeqno = seqno;\n this._onPayload = onPayload;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n while (p < dataLen) {\n // Read packet length\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n\n if (this._lenBytes < 4)\n return;\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (4 + this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._packetPos < this._len) {\n const nb = Math.min(this._len - this._packetPos, dataLen - p);\n let chunk;\n if (p !== 0 || nb !== dataLen)\n chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n chunk = data;\n if (nb === this._len) {\n this._packet = chunk;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(chunk, this._packetPos);\n }\n p += nb;\n this._packetPos += nb;\n if (this._packetPos < this._len)\n return;\n }\n\n const payload = (!this._packet\n ? EMPTY_BUFFER\n : new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length\n - this._packet[0] - 1));\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass ChaChaPolyDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decKeyMain = dec.decipherKey.slice(0, 32);\n this._decKeyPktLen = dec.decipherKey.slice(32);\n this._len = 0;\n this._lenBuf = Buffer.alloc(4);\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(16);\n this._calcMac = Buffer.allocUnsafe(16);\n this._macPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length\n if (this._lenPos < 4) {\n let nb = Math.min(4 - this._lenPos, dataLen - p);\n while (nb--)\n this._lenBuf[this._lenPos++] = data[p++];\n if (this._lenPos < 4)\n return;\n\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);\n\n const decLenBytes =\n createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE)\n .update(this._lenBuf);\n this._len = readUInt32BE(decLenBytes, 0);\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read Poly1305 MAC\n {\n const nb = Math.min(16 - this._macPos, dataLen - p);\n // TODO: avoid copying if entire MAC is in current chunk\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < 16)\n return;\n }\n\n // Generate Poly1305 key\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);\n const polyKey =\n createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE)\n .update(POLY1305_ZEROS);\n\n // Calculate and compare Poly1305 MACs\n poly1305_auth(POLY1305_RESULT_MALLOC,\n this._lenBuf,\n 4,\n this._packet,\n this._packet.length,\n polyKey);\n\n this._calcMac.set(\n new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer,\n POLY1305_RESULT_MALLOC,\n 16),\n 0\n );\n if (!timingSafeEqual(this._calcMac, this._mac))\n throw new Error('Invalid MAC');\n\n // Decrypt packet\n POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian)\n const packet =\n createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE)\n .update(this._packet);\n\n const payload = new FastBuffer(packet.buffer,\n packet.byteOffset + 1,\n packet.length - packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass ChaChaPolyDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new ChaChaPolyDecipher(dec.decipherKey);\n this._len = 0;\n this._lenBuf = Buffer.alloc(4);\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(16);\n this._macPos = 0;\n }\n free() {\n this._instance.free();\n }\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length\n if (this._lenPos < 4) {\n let nb = Math.min(4 - this._lenPos, dataLen - p);\n while (nb--)\n this._lenBuf[this._lenPos++] = data[p++];\n if (this._lenPos < 4)\n return;\n\n this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno);\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read Poly1305 MAC\n {\n const nb = Math.min(16 - this._macPos, dataLen - p);\n // TODO: avoid copying if entire MAC is in current chunk\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < 16)\n return;\n }\n\n this._instance.decrypt(this._packet, this._mac, this.inSeqno);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass AESGCMDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decipherInstance = null;\n this._decipherSSLName = dec.decipherInfo.sslName;\n this._decipherKey = dec.decipherKey;\n this._decipherIV = dec.decipherIV;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._tag = Buffer.allocUnsafe(16);\n this._tagPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length (unencrypted, but AAD)\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n if (this._lenBytes < 4)\n return;\n\n if ((this._len + 20) > MAX_PACKET_SIZE\n || this._len < 16\n || (this._len & 15) !== 0) {\n throw new Error('Bad packet length');\n }\n\n this._decipherInstance = createDecipheriv(\n this._decipherSSLName,\n this._decipherKey,\n this._decipherIV\n );\n this._decipherInstance.setAutoPadding(false);\n this._decipherInstance.setAAD(intToBytes(this._len));\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let decrypted;\n if (p !== 0 || nb !== dataLen) {\n decrypted = this._decipherInstance.update(\n new Uint8Array(data.buffer, data.byteOffset + p, nb)\n );\n } else {\n decrypted = this._decipherInstance.update(data);\n }\n if (decrypted.length) {\n if (nb === this._len) {\n this._packet = decrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(decrypted, this._packetPos);\n }\n this._packetPos += decrypted.length;\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read authentication tag\n {\n const nb = Math.min(16 - this._tagPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._tag.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._tagPos\n );\n } else {\n this._tag.set(data, this._tagPos);\n }\n p += nb;\n this._tagPos += nb;\n if (this._tagPos < 16)\n return;\n }\n\n {\n // Verify authentication tag\n this._decipherInstance.setAuthTag(this._tag);\n\n const decrypted = this._decipherInstance.final();\n\n // XXX: this should never output any data since stream ciphers always\n // return data from .update() and block ciphers must end on a multiple\n // of the block length, which would have caused an exception to be\n // thrown if the total input was not...\n if (decrypted.length) {\n if (this._packet)\n this._packet.set(decrypted, this._packetPos);\n else\n this._packet = decrypted;\n }\n }\n\n const payload = (!this._packet\n ? EMPTY_BUFFER\n : new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length\n - this._packet[0] - 1));\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n ivIncrement(this._decipherIV);\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._tagPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass AESGCMDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new AESGCMDecipher(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV);\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._pktLen = 0;\n this._tag = Buffer.allocUnsafe(16);\n this._tagPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length (unencrypted, but AAD)\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n if (this._lenBytes < 4)\n return;\n\n if ((this._len + 20) > MAX_PACKET_SIZE\n || this._len < 16\n || (this._len & 15) !== 0) {\n throw new Error(`Bad packet length: ${this._len}`);\n }\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read authentication tag\n {\n const nb = Math.min(16 - this._tagPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._tag.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._tagPos\n );\n } else {\n this._tag.set(data, this._tagPos);\n }\n p += nb;\n this._tagPos += nb;\n if (this._tagPos < 16)\n return;\n }\n\n this._instance.decrypt(this._packet, this._len, this._tag);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._pktLen = 0;\n this._tagPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\n// TODO: test incremental .update()s vs. copying to _packet and doing a single\n// .update() after entire packet read -- a single .update() would allow\n// verifying MAC before decrypting for ETM MACs\nclass GenericDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV);\n this._decipherInstance.setAutoPadding(false);\n this._block = Buffer.allocUnsafe(\n dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen\n );\n this._blockSize = dec.decipherInfo.blockLen;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen);\n this._macPos = 0;\n this._macSSLName = dec.macInfo.sslName;\n this._macKey = dec.macKey;\n this._macActualLen = dec.macInfo.actualLen;\n this._macETM = dec.macInfo.isETM;\n this._macInstance = null;\n\n const discardLen = dec.decipherInfo.discardLen;\n if (discardLen) {\n let discard = DISCARD_CACHE.get(discardLen);\n if (discard === undefined) {\n discard = Buffer.alloc(discardLen);\n DISCARD_CACHE.set(discardLen, discard);\n }\n this._decipherInstance.update(discard);\n }\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read first encrypted block\n if (this._blockPos < this._block.length) {\n const nb = Math.min(this._block.length - this._blockPos, dataLen - p);\n if (p !== 0 || nb !== dataLen || nb < data.length) {\n this._block.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._blockPos\n );\n } else {\n this._block.set(data, this._blockPos);\n }\n\n p += nb;\n this._blockPos += nb;\n if (this._blockPos < this._block.length)\n return;\n\n let decrypted;\n let need;\n if (this._macETM) {\n this._len = need = readUInt32BE(this._block, 0);\n } else {\n // Decrypt first block to get packet length\n decrypted = this._decipherInstance.update(this._block);\n this._len = readUInt32BE(decrypted, 0);\n need = 4 + this._len - this._blockSize;\n }\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 5\n || (need & (this._blockSize - 1)) !== 0) {\n throw new Error('Bad packet length');\n }\n\n // Create MAC up front to calculate in parallel with decryption\n this._macInstance = createHmac(this._macSSLName, this._macKey);\n\n writeUInt32BE(BUF_INT, this.inSeqno, 0);\n this._macInstance.update(BUF_INT);\n if (this._macETM) {\n this._macInstance.update(this._block);\n } else {\n this._macInstance.update(new Uint8Array(decrypted.buffer,\n decrypted.byteOffset,\n 4));\n this._pktLen = decrypted.length - 4;\n this._packetPos = this._pktLen;\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(\n new Uint8Array(decrypted.buffer,\n decrypted.byteOffset + 4,\n this._packetPos),\n 0\n );\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (this._macETM)\n this._macInstance.update(encrypted);\n const decrypted = this._decipherInstance.update(encrypted);\n if (decrypted.length) {\n if (nb === this._len) {\n this._packet = decrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(decrypted, this._packetPos);\n }\n this._packetPos += decrypted.length;\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read MAC\n {\n const nb = Math.min(this._macActualLen - this._macPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < this._macActualLen)\n return;\n }\n\n // Verify MAC\n if (!this._macETM)\n this._macInstance.update(this._packet);\n let calculated = this._macInstance.digest();\n if (this._macActualLen < calculated.length) {\n calculated = new Uint8Array(calculated.buffer,\n calculated.byteOffset,\n this._macActualLen);\n }\n if (!timingSafeEquals(calculated, this._mac))\n throw new Error('Invalid MAC');\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._macPos = 0;\n this._macInstance = null;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass GenericDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new GenericDecipher(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV,\n dec.macInfo.sslName,\n dec.macKey,\n dec.macInfo.isETM,\n dec.macInfo.actualLen);\n this._block = Buffer.allocUnsafe(\n dec.macInfo.isETM || dec.decipherInfo.stream\n ? 4\n : dec.decipherInfo.blockLen\n );\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen);\n this._macPos = 0;\n this._macActualLen = dec.macInfo.actualLen;\n this._macETM = dec.macInfo.isETM;\n }\n free() {\n this._instance.free();\n }\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read first encrypted block\n if (this._blockPos < this._block.length) {\n const nb = Math.min(this._block.length - this._blockPos, dataLen - p);\n if (p !== 0 || nb !== dataLen || nb < data.length) {\n this._block.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._blockPos\n );\n } else {\n this._block.set(data, this._blockPos);\n }\n\n p += nb;\n this._blockPos += nb;\n if (this._blockPos < this._block.length)\n return;\n\n let need;\n if (this._macETM) {\n this._len = need = readUInt32BE(this._block, 0);\n } else {\n // Decrypt first block to get packet length\n this._instance.decryptBlock(this._block);\n this._len = readUInt32BE(this._block, 0);\n need = 4 + this._len - this._block.length;\n }\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 5\n || (need & (this._block.length - 1)) !== 0) {\n throw new Error('Bad packet length');\n }\n\n if (!this._macETM) {\n this._pktLen = (this._block.length - 4);\n if (this._pktLen) {\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(\n new Uint8Array(this._block.buffer,\n this._block.byteOffset + 4,\n this._pktLen),\n 0\n );\n }\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read MAC\n {\n const nb = Math.min(this._macActualLen - this._macPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < this._macActualLen)\n return;\n }\n\n // Decrypt and verify MAC\n this._instance.decrypt(this._packet,\n this.inSeqno,\n this._block,\n this._mac);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n this._macInstance = null;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\n// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV\nfunction ivIncrement(iv) {\n // eslint-disable-next-line no-unused-expressions\n ++iv[11] >>> 8\n && ++iv[10] >>> 8\n && ++iv[9] >>> 8\n && ++iv[8] >>> 8\n && ++iv[7] >>> 8\n && ++iv[6] >>> 8\n && ++iv[5] >>> 8\n && ++iv[4] >>> 8;\n}\n\nconst intToBytes = (() => {\n const ret = Buffer.alloc(4);\n return (n) => {\n ret[0] = (n >>> 24);\n ret[1] = (n >>> 16);\n ret[2] = (n >>> 8);\n ret[3] = n;\n return ret;\n };\n})();\n\nfunction timingSafeEquals(a, b) {\n if (a.length !== b.length) {\n timingSafeEqual(a, a);\n return false;\n }\n return timingSafeEqual(a, b);\n}\n\nfunction createCipher(config) {\n if (typeof config !== 'object' || config === null)\n throw new Error('Invalid config');\n\n if (typeof config.outbound !== 'object' || config.outbound === null)\n throw new Error('Invalid outbound');\n\n const outbound = config.outbound;\n\n if (typeof outbound.onWrite !== 'function')\n throw new Error('Invalid outbound.onWrite');\n\n if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null)\n throw new Error('Invalid outbound.cipherInfo');\n\n if (!Buffer.isBuffer(outbound.cipherKey)\n || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) {\n throw new Error('Invalid outbound.cipherKey');\n }\n\n if (outbound.cipherInfo.ivLen\n && (!Buffer.isBuffer(outbound.cipherIV)\n || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) {\n throw new Error('Invalid outbound.cipherIV');\n }\n\n if (typeof outbound.seqno !== 'number'\n || outbound.seqno < 0\n || outbound.seqno > MAX_SEQNO) {\n throw new Error('Invalid outbound.seqno');\n }\n\n const forceNative = !!outbound.forceNative;\n\n switch (outbound.cipherInfo.sslName) {\n case 'aes-128-gcm':\n case 'aes-256-gcm':\n return (AESGCMCipher && !forceNative\n ? new AESGCMCipherBinding(config)\n : new AESGCMCipherNative(config));\n case 'chacha20':\n return (ChaChaPolyCipher && !forceNative\n ? new ChaChaPolyCipherBinding(config)\n : new ChaChaPolyCipherNative(config));\n default: {\n if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null)\n throw new Error('Invalid outbound.macInfo');\n if (!Buffer.isBuffer(outbound.macKey)\n || outbound.macKey.length !== outbound.macInfo.len) {\n throw new Error('Invalid outbound.macKey');\n }\n return (GenericCipher && !forceNative\n ? new GenericCipherBinding(config)\n : new GenericCipherNative(config));\n }\n }\n}\n\nfunction createDecipher(config) {\n if (typeof config !== 'object' || config === null)\n throw new Error('Invalid config');\n\n if (typeof config.inbound !== 'object' || config.inbound === null)\n throw new Error('Invalid inbound');\n\n const inbound = config.inbound;\n\n if (typeof inbound.onPayload !== 'function')\n throw new Error('Invalid inbound.onPayload');\n\n if (typeof inbound.decipherInfo !== 'object'\n || inbound.decipherInfo === null) {\n throw new Error('Invalid inbound.decipherInfo');\n }\n\n if (!Buffer.isBuffer(inbound.decipherKey)\n || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) {\n throw new Error('Invalid inbound.decipherKey');\n }\n\n if (inbound.decipherInfo.ivLen\n && (!Buffer.isBuffer(inbound.decipherIV)\n || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) {\n throw new Error('Invalid inbound.decipherIV');\n }\n\n if (typeof inbound.seqno !== 'number'\n || inbound.seqno < 0\n || inbound.seqno > MAX_SEQNO) {\n throw new Error('Invalid inbound.seqno');\n }\n\n const forceNative = !!inbound.forceNative;\n\n switch (inbound.decipherInfo.sslName) {\n case 'aes-128-gcm':\n case 'aes-256-gcm':\n return (AESGCMDecipher && !forceNative\n ? new AESGCMDecipherBinding(config)\n : new AESGCMDecipherNative(config));\n case 'chacha20':\n return (ChaChaPolyDecipher && !forceNative\n ? new ChaChaPolyDecipherBinding(config)\n : new ChaChaPolyDecipherNative(config));\n default: {\n if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null)\n throw new Error('Invalid inbound.macInfo');\n if (!Buffer.isBuffer(inbound.macKey)\n || inbound.macKey.length !== inbound.macInfo.len) {\n throw new Error('Invalid inbound.macKey');\n }\n return (GenericDecipher && !forceNative\n ? new GenericDecipherBinding(config)\n : new GenericDecipherNative(config));\n }\n }\n}\n\nmodule.exports = {\n CIPHER_INFO,\n MAC_INFO,\n bindingAvailable: !!binding,\n init: (() => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n POLY1305_WASM_MODULE = await require('./crypto/poly1305.js')();\n POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16);\n poly1305_auth = POLY1305_WASM_MODULE.cwrap(\n 'poly1305_auth',\n null,\n ['number', 'array', 'number', 'array', 'number', 'array']\n );\n } catch (ex) {\n return reject(ex);\n }\n resolve();\n });\n })(),\n\n NullCipher,\n createCipher,\n NullDecipher,\n createDecipher,\n};\n","\nvar createPoly1305 = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;\n return (\nfunction(createPoly1305) {\n createPoly1305 = createPoly1305 || {};\n\n\nvar b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x=\"object\"===typeof window,y=\"function\"===typeof importScripts,z=\"object\"===typeof process&&\"object\"===typeof process.versions&&\"string\"===typeof process.versions.node,B=\"\",C,D,E,F,G;\nif(z)B=y?require(\"path\").dirname(B)+\"/\":__dirname+\"/\",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=require(\"fs\"));G||(G=require(\"path\"));a=G.normalize(a);return F.readFileSync(a,c?null:\"utf8\")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=require(\"fs\"));G||(G=require(\"path\"));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]=\n0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g=\"\";else g=\"boolean\"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea=\"undefined\"!==typeof TextDecoder?new TextDecoder(\"utf8\"):void 0,ha,Q,P;\nfunction ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={};\nfunction K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError(\"abort(\"+a+\"). Build with -s ASSERTIONS=1 for more info.\");r(a);throw a;}var V=\"data:application/octet-stream;base64,\",W;W=\"data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==\";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw\"both async and sync fetching of the wasm failed\";}catch(d){K(d)}}\nfunction qa(){if(!J&&(x||y)){if(\"function\"===typeof fetch&&!W.startsWith(\"file://\"))return fetch(W,{credentials:\"same-origin\"}).then(function(a){if(!a.ok)throw\"failed to load wasm binary file at '\"+W+\"'\";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})}\nfunction X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}};\n(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I(\"failed to asynchronously prepare wasm: \"+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e,\na)}catch(f){return I(\"Module.instantiateWasm callback failed with error: \"+f),!1}(function(){return J||\"function\"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith(\"file://\")||\"function\"!==typeof fetch?d(c):fetch(W,{credentials:\"same-origin\"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I(\"wasm streaming compile failed: \"+l);I(\"falling back to ArrayBuffer instantiation\");return d(c)})})})().catch(r);return{}})();\nb.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)};\nb._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return\"number\"===l});return\"string\"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)};\nfunction Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for(\"function\"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 {\n // eslint-disable-next-line prefer-const\n for (let [type, handler] of Object.entries(handlers)) {\n type = +type;\n if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length)\n MESSAGE_HANDLERS[type] = handler;\n }\n});\n\nmodule.exports = MESSAGE_HANDLERS;\n","'use strict';\n\nconst {\n bufferSlice,\n bufferParser,\n doFatalError,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst {\n CHANNEL_OPEN_FAILURE,\n COMPAT,\n MESSAGE,\n TERMINAL_MODE,\n} = require('./constants.js');\n\nconst {\n parseKey,\n} = require('./keyParser.js');\n\nconst TERMINAL_MODE_BY_VALUE =\n Array.from(Object.entries(TERMINAL_MODE))\n .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});\n\nmodule.exports = {\n // Transport layer protocol ==================================================\n [MESSAGE.DISCONNECT]: (self, payload) => {\n /*\n byte SSH_MSG_DISCONNECT\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding\n string language tag\n */\n bufferParser.init(payload, 1);\n const reason = bufferParser.readUInt32BE();\n const desc = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed DISCONNECT packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: Received DISCONNECT (${reason}, \"${desc}\")`\n );\n\n const handler = self._handlers.DISCONNECT;\n handler && handler(self, reason, desc);\n },\n [MESSAGE.IGNORE]: (self, payload) => {\n /*\n byte SSH_MSG_IGNORE\n string data\n */\n self._debug && self._debug('Inbound: Received IGNORE');\n },\n [MESSAGE.UNIMPLEMENTED]: (self, payload) => {\n /*\n byte SSH_MSG_UNIMPLEMENTED\n uint32 packet sequence number of rejected message\n */\n bufferParser.init(payload, 1);\n const seqno = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (seqno === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed UNIMPLEMENTED packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`);\n },\n [MESSAGE.DEBUG]: (self, payload) => {\n /*\n byte SSH_MSG_DEBUG\n boolean always_display\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const display = bufferParser.readBool();\n const msg = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed DEBUG packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received DEBUG');\n\n const handler = self._handlers.DEBUG;\n handler && handler(self, display, msg);\n },\n [MESSAGE.SERVICE_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_SERVICE_REQUEST\n string service name\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n bufferParser.clear();\n\n if (name === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed SERVICE_REQUEST packet'\n );\n }\n\n self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`);\n\n const handler = self._handlers.SERVICE_REQUEST;\n handler && handler(self, name);\n },\n [MESSAGE.SERVICE_ACCEPT]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_SERVICE_ACCEPT\n string service name\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n bufferParser.clear();\n\n if (name === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed SERVICE_ACCEPT packet'\n );\n }\n\n self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`);\n\n const handler = self._handlers.SERVICE_ACCEPT;\n handler && handler(self, name);\n },\n [MESSAGE.EXT_INFO]: (self, payload) => {\n /*\n byte SSH_MSG_EXT_INFO\n uint32 nr-extensions\n repeat the following 2 fields \"nr-extensions\" times:\n string extension-name\n string extension-value (binary)\n */\n bufferParser.init(payload, 1);\n const numExts = bufferParser.readUInt32BE();\n let exts;\n if (numExts !== undefined) {\n exts = [];\n for (let i = 0; i < numExts; ++i) {\n const name = bufferParser.readString(true);\n const data = bufferParser.readString();\n if (data !== undefined) {\n switch (name) {\n case 'server-sig-algs': {\n const algs = data.latin1Slice(0, data.length).split(',');\n exts.push({ name, algs });\n continue;\n }\n default:\n continue;\n }\n }\n // Malformed\n exts = undefined;\n break;\n }\n }\n bufferParser.clear();\n\n if (exts === undefined)\n return doFatalError(self, 'Inbound: Malformed EXT_INFO packet');\n\n self._debug && self._debug('Inbound: Received EXT_INFO');\n\n const handler = self._handlers.EXT_INFO;\n handler && handler(self, exts);\n },\n\n // User auth protocol -- generic =============================================\n [MESSAGE.USERAUTH_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_USERAUTH_REQUEST\n string user name in ISO-10646 UTF-8 encoding [RFC3629]\n string service name in US-ASCII\n string method name in US-ASCII\n .... method specific fields\n */\n bufferParser.init(payload, 1);\n const user = bufferParser.readString(true);\n const service = bufferParser.readString(true);\n const method = bufferParser.readString(true);\n let methodData;\n let methodDesc;\n switch (method) {\n case 'none':\n methodData = null;\n break;\n case 'password': {\n /*\n boolean \n string plaintext password in ISO-10646 UTF-8 encoding [RFC3629]\n [string new password]\n */\n const isChange = bufferParser.readBool();\n if (isChange !== undefined) {\n methodData = bufferParser.readString(true);\n if (methodData !== undefined && isChange) {\n const newPassword = bufferParser.readString(true);\n if (newPassword !== undefined)\n methodData = { oldPassword: methodData, newPassword };\n else\n methodData = undefined;\n }\n }\n break;\n }\n case 'publickey': {\n /*\n boolean \n string public key algorithm name\n string public key blob\n [string signature]\n */\n const hasSig = bufferParser.readBool();\n if (hasSig !== undefined) {\n const keyAlgo = bufferParser.readString(true);\n let realKeyAlgo = keyAlgo;\n const key = bufferParser.readString();\n\n let hashAlgo;\n switch (keyAlgo) {\n case 'rsa-sha2-256':\n realKeyAlgo = 'ssh-rsa';\n hashAlgo = 'sha256';\n break;\n case 'rsa-sha2-512':\n realKeyAlgo = 'ssh-rsa';\n hashAlgo = 'sha512';\n break;\n }\n\n if (hasSig) {\n const blobEnd = bufferParser.pos();\n let signature = bufferParser.readString();\n if (signature !== undefined) {\n if (signature.length > (4 + keyAlgo.length + 4)\n && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) {\n // Skip algoLen + algo + sigLen\n signature = bufferSlice(signature, 4 + keyAlgo.length + 4);\n }\n\n signature = sigSSHToASN1(signature, realKeyAlgo);\n if (signature) {\n const sessionID = self._kex.sessionID;\n const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd);\n writeUInt32BE(blob, sessionID.length, 0);\n blob.set(sessionID, 4);\n blob.set(\n new Uint8Array(payload.buffer, payload.byteOffset, blobEnd),\n 4 + sessionID.length\n );\n methodData = {\n keyAlgo: realKeyAlgo,\n key,\n signature,\n blob,\n hashAlgo,\n };\n }\n }\n } else {\n methodData = { keyAlgo: realKeyAlgo, key, hashAlgo };\n methodDesc = 'publickey -- check';\n }\n }\n break;\n }\n case 'hostbased': {\n /*\n string public key algorithm for host key\n string public host key and certificates for client host\n string client host name expressed as the FQDN in US-ASCII\n string user name on the client host in ISO-10646 UTF-8 encoding\n [RFC3629]\n string signature\n */\n const keyAlgo = bufferParser.readString(true);\n let realKeyAlgo = keyAlgo;\n const key = bufferParser.readString();\n const localHostname = bufferParser.readString(true);\n const localUsername = bufferParser.readString(true);\n\n let hashAlgo;\n switch (keyAlgo) {\n case 'rsa-sha2-256':\n realKeyAlgo = 'ssh-rsa';\n hashAlgo = 'sha256';\n break;\n case 'rsa-sha2-512':\n realKeyAlgo = 'ssh-rsa';\n hashAlgo = 'sha512';\n break;\n }\n\n const blobEnd = bufferParser.pos();\n let signature = bufferParser.readString();\n if (signature !== undefined) {\n if (signature.length > (4 + keyAlgo.length + 4)\n && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) {\n // Skip algoLen + algo + sigLen\n signature = bufferSlice(signature, 4 + keyAlgo.length + 4);\n }\n\n signature = sigSSHToASN1(signature, realKeyAlgo);\n if (signature !== undefined) {\n const sessionID = self._kex.sessionID;\n const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd);\n writeUInt32BE(blob, sessionID.length, 0);\n blob.set(sessionID, 4);\n blob.set(\n new Uint8Array(payload.buffer, payload.byteOffset, blobEnd),\n 4 + sessionID.length\n );\n methodData = {\n keyAlgo: realKeyAlgo,\n key,\n signature,\n blob,\n localHostname,\n localUsername,\n hashAlgo\n };\n }\n }\n break;\n }\n case 'keyboard-interactive':\n /*\n string language tag (as defined in [RFC-3066])\n string submethods (ISO-10646 UTF-8)\n */\n // Skip/ignore language field -- it's deprecated in RFC 4256\n bufferParser.skipString();\n\n methodData = bufferParser.readList();\n break;\n default:\n if (method !== undefined)\n methodData = bufferParser.readRaw();\n }\n bufferParser.clear();\n\n if (methodData === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_REQUEST packet'\n );\n }\n\n if (methodDesc === undefined)\n methodDesc = method;\n\n self._authsQueue.push(method);\n\n self._debug\n && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`);\n\n const handler = self._handlers.USERAUTH_REQUEST;\n handler && handler(self, user, service, method, methodData);\n },\n [MESSAGE.USERAUTH_FAILURE]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_FAILURE\n name-list authentications that can continue\n boolean partial success\n */\n bufferParser.init(payload, 1);\n const authMethods = bufferParser.readList();\n const partialSuccess = bufferParser.readBool();\n bufferParser.clear();\n\n if (partialSuccess === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_FAILURE packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`);\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_FAILURE;\n handler && handler(self, authMethods, partialSuccess);\n },\n [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_SUCCESS\n */\n self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS');\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_SUCCESS;\n handler && handler(self);\n },\n [MESSAGE.USERAUTH_BANNER]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_BANNER\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const msg = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_BANNER packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_BANNER');\n\n const handler = self._handlers.USERAUTH_BANNER;\n handler && handler(self, msg);\n },\n\n // User auth protocol -- method-specific =====================================\n 60: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 60 without auth');\n return;\n }\n\n switch (self._authsQueue[0]) {\n case 'password': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ\n string prompt in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const prompt = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet'\n );\n }\n\n self._debug\n && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ');\n\n const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ;\n handler && handler(self, prompt);\n break;\n }\n case 'publickey': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_PK_OK\n string public key algorithm name from the request\n string public key blob from the request\n */\n bufferParser.init(payload, 1);\n const keyAlgo = bufferParser.readString(true);\n const key = bufferParser.readString();\n bufferParser.clear();\n\n if (key === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_PK_OK packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_PK_OK');\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_PK_OK;\n handler && handler(self, keyAlgo, key);\n break;\n }\n case 'keyboard-interactive': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_INFO_REQUEST\n string name (ISO-10646 UTF-8)\n string instruction (ISO-10646 UTF-8)\n string language tag (as defined in [RFC-3066])\n int num-prompts\n string prompt[1] (ISO-10646 UTF-8)\n boolean echo[1]\n ...\n string prompt[num-prompts] (ISO-10646 UTF-8)\n boolean echo[num-prompts]\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n const instructions = bufferParser.readString(true);\n bufferParser.readString(); // skip lang\n const numPrompts = bufferParser.readUInt32BE();\n let prompts;\n if (numPrompts !== undefined) {\n prompts = new Array(numPrompts);\n let i;\n for (i = 0; i < numPrompts; ++i) {\n const prompt = bufferParser.readString(true);\n const echo = bufferParser.readBool();\n if (echo === undefined)\n break;\n prompts[i] = { prompt, echo };\n }\n if (i !== numPrompts)\n prompts = undefined;\n }\n bufferParser.clear();\n\n if (prompts === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_REQUEST packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST');\n\n const handler = self._handlers.USERAUTH_INFO_REQUEST;\n handler && handler(self, name, instructions, prompts);\n break;\n }\n default:\n self._debug\n && self._debug('Inbound: Received unexpected payload type 60');\n }\n },\n 61: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 61 without auth');\n return;\n }\n /*\n byte SSH_MSG_USERAUTH_INFO_RESPONSE\n int num-responses\n string response[1] (ISO-10646 UTF-8)\n ...\n string response[num-responses] (ISO-10646 UTF-8)\n */\n if (self._authsQueue[0] !== 'keyboard-interactive') {\n return doFatalError(\n self,\n 'Inbound: Received unexpected payload type 61'\n );\n }\n bufferParser.init(payload, 1);\n const numResponses = bufferParser.readUInt32BE();\n let responses;\n if (numResponses !== undefined) {\n responses = new Array(numResponses);\n let i;\n for (i = 0; i < numResponses; ++i) {\n const response = bufferParser.readString(true);\n if (response === undefined)\n break;\n responses[i] = response;\n }\n if (i !== numResponses)\n responses = undefined;\n }\n bufferParser.clear();\n\n if (responses === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE');\n\n const handler = self._handlers.USERAUTH_INFO_RESPONSE;\n handler && handler(self, responses);\n },\n\n // Connection protocol -- generic ============================================\n [MESSAGE.GLOBAL_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_GLOBAL_REQUEST\n string request name in US-ASCII only\n boolean want reply\n .... request-specific data follows\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n const wantReply = bufferParser.readBool();\n let data;\n if (wantReply !== undefined) {\n switch (name) {\n case 'tcpip-forward':\n case 'cancel-tcpip-forward': {\n /*\n string address to bind (e.g., \"0.0.0.0\")\n uint32 port number to bind\n */\n const bindAddr = bufferParser.readString(true);\n const bindPort = bufferParser.readUInt32BE();\n if (bindPort !== undefined)\n data = { bindAddr, bindPort };\n break;\n }\n case 'streamlocal-forward@openssh.com':\n case 'cancel-streamlocal-forward@openssh.com': {\n /*\n string socket path\n */\n const socketPath = bufferParser.readString(true);\n if (socketPath !== undefined)\n data = { socketPath };\n break;\n }\n case 'no-more-sessions@openssh.com':\n data = null;\n break;\n case 'hostkeys-00@openssh.com': {\n data = [];\n while (bufferParser.avail() > 0) {\n const keyRaw = bufferParser.readString();\n if (keyRaw === undefined) {\n data = undefined;\n break;\n }\n const key = parseKey(keyRaw);\n if (!(key instanceof Error))\n data.push(key);\n }\n break;\n }\n default:\n data = bufferParser.readRaw();\n }\n }\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed GLOBAL_REQUEST packet'\n );\n }\n\n self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`);\n\n const handler = self._handlers.GLOBAL_REQUEST;\n if (handler)\n handler(self, name, wantReply, data);\n else\n self.requestFailure(); // Auto reject\n },\n [MESSAGE.REQUEST_SUCCESS]: (self, payload) => {\n /*\n byte SSH_MSG_REQUEST_SUCCESS\n .... response specific data\n */\n const data = (payload.length > 1 ? bufferSlice(payload, 1) : null);\n\n self._debug && self._debug('Inbound: REQUEST_SUCCESS');\n\n const handler = self._handlers.REQUEST_SUCCESS;\n handler && handler(self, data);\n },\n [MESSAGE.REQUEST_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_REQUEST_FAILURE\n */\n self._debug && self._debug('Inbound: Received REQUEST_FAILURE');\n\n const handler = self._handlers.REQUEST_FAILURE;\n handler && handler(self);\n },\n\n // Connection protocol -- channel-related ====================================\n [MESSAGE.CHANNEL_OPEN]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN\n string channel type in US-ASCII only\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n .... channel type specific data follows\n */\n bufferParser.init(payload, 1);\n const type = bufferParser.readString(true);\n const sender = bufferParser.readUInt32BE();\n const window = bufferParser.readUInt32BE();\n const packetSize = bufferParser.readUInt32BE();\n let channelInfo;\n\n switch (type) {\n case 'forwarded-tcpip': // S->C\n case 'direct-tcpip': { // C->S\n /*\n string address that was connected / host to connect\n uint32 port that was connected / port to connect\n string originator IP address\n uint32 originator port\n */\n const destIP = bufferParser.readString(true);\n const destPort = bufferParser.readUInt32BE();\n const srcIP = bufferParser.readString(true);\n const srcPort = bufferParser.readUInt32BE();\n if (srcPort !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { destIP, destPort, srcIP, srcPort }\n };\n }\n break;\n }\n case 'forwarded-streamlocal@openssh.com': // S->C\n case 'direct-streamlocal@openssh.com': { // C->S\n /*\n string socket path\n string reserved for future use\n\n (direct-streamlocal@openssh.com additionally has:)\n uint32 reserved\n */\n const socketPath = bufferParser.readString(true);\n if (socketPath !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { socketPath }\n };\n }\n break;\n }\n case 'x11': { // S->C\n /*\n string originator address (e.g., \"192.168.7.38\")\n uint32 originator port\n */\n const srcIP = bufferParser.readString(true);\n const srcPort = bufferParser.readUInt32BE();\n if (srcPort !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { srcIP, srcPort }\n };\n }\n break;\n }\n default:\n // Includes:\n // 'session' (C->S)\n // 'auth-agent@openssh.com' (S->C)\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: {}\n };\n }\n bufferParser.clear();\n\n if (channelInfo === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`);\n\n const handler = self._handlers.CHANNEL_OPEN;\n if (handler) {\n handler(self, channelInfo);\n } else {\n self.channelOpenFail(\n channelInfo.sender,\n CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED,\n '',\n ''\n );\n }\n },\n [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION\n uint32 recipient channel\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n .... channel type specific data follows\n */\n // \"The 'recipient channel' is the channel number given in the\n // original open request, and 'sender channel' is the channel number\n // allocated by the other side.\"\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const sender = bufferParser.readUInt32BE();\n const window = bufferParser.readUInt32BE();\n const packetSize = bufferParser.readUInt32BE();\n const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined);\n bufferParser.clear();\n\n if (packetSize === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})`\n );\n\n const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION;\n if (handler)\n handler(self, { recipient, sender, window, packetSize, data });\n },\n [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN_FAILURE\n uint32 recipient channel\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const reason = bufferParser.readUInt32BE();\n const description = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_OPEN_FAILURE;\n handler && handler(self, recipient, reason, description);\n },\n [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_WINDOW_ADJUST\n uint32 recipient channel\n uint32 bytes to add\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const bytesToAdd = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (bytesToAdd === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})`\n );\n\n const handler = self._handlers.CHANNEL_WINDOW_ADJUST;\n handler && handler(self, recipient, bytesToAdd);\n },\n [MESSAGE.CHANNEL_DATA]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_DATA\n uint32 recipient channel\n string data\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_DATA packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`);\n\n const handler = self._handlers.CHANNEL_DATA;\n handler && handler(self, recipient, data);\n },\n [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_EXTENDED_DATA\n uint32 recipient channel\n uint32 data_type_code\n string data\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const type = bufferParser.readUInt32BE();\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})`\n );\n\n const handler = self._handlers.CHANNEL_EXTENDED_DATA;\n handler && handler(self, recipient, data, type);\n },\n [MESSAGE.CHANNEL_EOF]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_EOF\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_EOF packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_EOF;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_CLOSE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_CLOSE\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_CLOSE packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_CLOSE;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_REQUEST\n uint32 recipient channel\n string request type in US-ASCII characters only\n boolean want reply\n .... type-specific data follows\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const type = bufferParser.readString(true);\n const wantReply = bufferParser.readBool();\n let data;\n if (wantReply !== undefined) {\n switch (type) {\n case 'exit-status': // S->C\n /*\n uint32 exit_status\n */\n data = bufferParser.readUInt32BE();\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'exit-signal': { // S->C\n /*\n string signal name (without the \"SIG\" prefix)\n boolean core dumped\n string error message in ISO-10646 UTF-8 encoding\n string language tag\n */\n let signal;\n let coreDumped;\n if (self._compatFlags & COMPAT.OLD_EXIT) {\n /*\n Instead of `signal name` and `core dumped`, we have just:\n uint32 signal number\n */\n const num = bufferParser.readUInt32BE();\n switch (num) {\n case 1:\n signal = 'HUP';\n break;\n case 2:\n signal = 'INT';\n break;\n case 3:\n signal = 'QUIT';\n break;\n case 6:\n signal = 'ABRT';\n break;\n case 9:\n signal = 'KILL';\n break;\n case 14:\n signal = 'ALRM';\n break;\n case 15:\n signal = 'TERM';\n break;\n default:\n if (num !== undefined) {\n // Unknown or OS-specific\n signal = `UNKNOWN (${num})`;\n }\n }\n coreDumped = false;\n } else {\n signal = bufferParser.readString(true);\n coreDumped = bufferParser.readBool();\n if (coreDumped === undefined)\n signal = undefined;\n }\n const errorMessage = bufferParser.readString(true);\n if (bufferParser.skipString() !== undefined)\n data = { signal, coreDumped, errorMessage };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})`\n );\n break;\n }\n case 'pty-req': { // C->S\n /*\n string TERM environment variable value (e.g., vt100)\n uint32 terminal width, characters (e.g., 80)\n uint32 terminal height, rows (e.g., 24)\n uint32 terminal width, pixels (e.g., 640)\n uint32 terminal height, pixels (e.g., 480)\n string encoded terminal modes\n */\n const term = bufferParser.readString(true);\n const cols = bufferParser.readUInt32BE();\n const rows = bufferParser.readUInt32BE();\n const width = bufferParser.readUInt32BE();\n const height = bufferParser.readUInt32BE();\n const modesBinary = bufferParser.readString();\n if (modesBinary !== undefined) {\n bufferParser.init(modesBinary, 1);\n let modes = {};\n while (bufferParser.avail()) {\n const opcode = bufferParser.readByte();\n if (opcode === TERMINAL_MODE.TTY_OP_END)\n break;\n const name = TERMINAL_MODE_BY_VALUE[opcode];\n const value = bufferParser.readUInt32BE();\n if (opcode === undefined\n || name === undefined\n || value === undefined) {\n modes = undefined;\n break;\n }\n modes[name] = value;\n }\n if (modes !== undefined)\n data = { term, cols, rows, width, height, modes };\n }\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'window-change': { // C->S\n /*\n uint32 terminal width, columns\n uint32 terminal height, rows\n uint32 terminal width, pixels\n uint32 terminal height, pixels\n */\n const cols = bufferParser.readUInt32BE();\n const rows = bufferParser.readUInt32BE();\n const width = bufferParser.readUInt32BE();\n const height = bufferParser.readUInt32BE();\n if (height !== undefined)\n data = { cols, rows, width, height };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'x11-req': { // C->S\n /*\n boolean single connection\n string x11 authentication protocol\n string x11 authentication cookie\n uint32 x11 screen number\n */\n const single = bufferParser.readBool();\n const protocol = bufferParser.readString(true);\n const cookie = bufferParser.readString();\n const screen = bufferParser.readUInt32BE();\n if (screen !== undefined)\n data = { single, protocol, cookie, screen };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'env': { // C->S\n /*\n string variable name\n string variable value\n */\n const name = bufferParser.readString(true);\n const value = bufferParser.readString(true);\n if (value !== undefined)\n data = { name, value };\n if (self._debug) {\n self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: `\n + `${name}=${value})`\n );\n }\n break;\n }\n case 'shell': // C->S\n data = null; // No extra data\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n case 'exec': // C->S\n /*\n string command\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'subsystem': // C->S\n /*\n string subsystem name\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'signal': // C->S\n /*\n string signal name (without the \"SIG\" prefix)\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'xon-xoff': // C->S\n /*\n boolean client can do\n */\n data = bufferParser.readBool();\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'auth-agent-req@openssh.com': // C-S\n data = null; // No extra data\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n default:\n data = (bufferParser.avail() ? bufferParser.readRaw() : null);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n }\n }\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_REQUEST packet'\n );\n }\n\n const handler = self._handlers.CHANNEL_REQUEST;\n handler && handler(self, recipient, type, wantReply, data);\n },\n [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_SUCCESS\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_SUCCESS packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_SUCCESS;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_FAILURE\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_FAILURE packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_FAILURE;\n handler && handler(self, recipient);\n },\n};\n","'use strict';\n\nconst {\n createDiffieHellman,\n createDiffieHellmanGroup,\n createECDH,\n createHash,\n createPublicKey,\n diffieHellman,\n generateKeyPairSync,\n randomFillSync,\n} = require('crypto');\n\nconst { Ber } = require('asn1');\n\nconst {\n COMPAT,\n curve25519Supported,\n DEFAULT_KEX,\n DEFAULT_SERVER_HOST_KEY,\n DEFAULT_CIPHER,\n DEFAULT_MAC,\n DEFAULT_COMPRESSION,\n DISCONNECT_REASON,\n MESSAGE,\n} = require('./constants.js');\nconst {\n CIPHER_INFO,\n createCipher,\n createDecipher,\n MAC_INFO,\n} = require('./crypto.js');\nconst { parseDERKey } = require('./keyParser.js');\nconst {\n bufferFill,\n bufferParser,\n convertSignature,\n doFatalError,\n FastBuffer,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./utils.js');\nconst {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n} = require('./zlib.js');\n\nlet MESSAGE_HANDLERS;\n\nconst GEX_MIN_BITS = 2048; // RFC 8270\nconst GEX_MAX_BITS = 8192; // RFC 8270\n\nconst EMPTY_BUFFER = Buffer.alloc(0);\n\n// Client/Server\nfunction kexinit(self) {\n /*\n byte SSH_MSG_KEXINIT\n byte[16] cookie (random bytes)\n name-list kex_algorithms\n name-list server_host_key_algorithms\n name-list encryption_algorithms_client_to_server\n name-list encryption_algorithms_server_to_client\n name-list mac_algorithms_client_to_server\n name-list mac_algorithms_server_to_client\n name-list compression_algorithms_client_to_server\n name-list compression_algorithms_server_to_client\n name-list languages_client_to_server\n name-list languages_server_to_client\n boolean first_kex_packet_follows\n uint32 0 (reserved for future extension)\n */\n\n let payload;\n if (self._compatFlags & COMPAT.BAD_DHGEX) {\n const entry = self._offer.lists.kex;\n let kex = entry.array;\n let found = false;\n for (let i = 0; i < kex.length; ++i) {\n if (kex[i].includes('group-exchange')) {\n if (!found) {\n found = true;\n // Copy array lazily\n kex = kex.slice();\n }\n kex.splice(i--, 1);\n }\n }\n if (found) {\n let len = 1 + 16 + self._offer.totalSize + 1 + 4;\n const newKexBuf = Buffer.from(kex.join(','));\n len -= (entry.buffer.length - newKexBuf.length);\n\n const all = self._offer.lists.all;\n const rest = new Uint8Array(\n all.buffer,\n all.byteOffset + 4 + entry.buffer.length,\n all.length - (4 + entry.buffer.length)\n );\n\n payload = Buffer.allocUnsafe(len);\n writeUInt32BE(payload, newKexBuf.length, 17);\n payload.set(newKexBuf, 17 + 4);\n payload.set(rest, 17 + 4 + newKexBuf.length);\n }\n }\n\n if (payload === undefined) {\n payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4);\n self._offer.copyAllTo(payload, 17);\n }\n\n self._debug && self._debug('Outbound: Sending KEXINIT');\n\n payload[0] = MESSAGE.KEXINIT;\n randomFillSync(payload, 1, 16);\n\n // Zero-fill first_kex_packet_follows and reserved bytes\n bufferFill(payload, 0, payload.length - 5);\n\n self._kexinit = payload;\n\n // Needed to correct the starting position in allocated \"packets\" when packets\n // will be buffered due to active key exchange\n self._packetRW.write.allocStart = 0;\n\n // TODO: only create single buffer and set _kexinit as slice of packet instead\n {\n const p = self._packetRW.write.allocStartKEX;\n const packet = self._packetRW.write.alloc(payload.length, true);\n packet.set(payload, p);\n self._cipher.encrypt(self._packetRW.write.finalize(packet, true));\n }\n}\n\nfunction handleKexInit(self, payload) {\n /*\n byte SSH_MSG_KEXINIT\n byte[16] cookie (random bytes)\n name-list kex_algorithms\n name-list server_host_key_algorithms\n name-list encryption_algorithms_client_to_server\n name-list encryption_algorithms_server_to_client\n name-list mac_algorithms_client_to_server\n name-list mac_algorithms_server_to_client\n name-list compression_algorithms_client_to_server\n name-list compression_algorithms_server_to_client\n name-list languages_client_to_server\n name-list languages_server_to_client\n boolean first_kex_packet_follows\n uint32 0 (reserved for future extension)\n */\n const init = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n sc: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n };\n\n bufferParser.init(payload, 17);\n\n if ((init.kex = bufferParser.readList()) === undefined\n || (init.serverHostKey = bufferParser.readList()) === undefined\n || (init.cs.cipher = bufferParser.readList()) === undefined\n || (init.sc.cipher = bufferParser.readList()) === undefined\n || (init.cs.mac = bufferParser.readList()) === undefined\n || (init.sc.mac = bufferParser.readList()) === undefined\n || (init.cs.compress = bufferParser.readList()) === undefined\n || (init.sc.compress = bufferParser.readList()) === undefined\n || (init.cs.lang = bufferParser.readList()) === undefined\n || (init.sc.lang = bufferParser.readList()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n self,\n 'Received malformed KEXINIT',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n const pos = bufferParser.pos();\n const firstFollows = (pos < payload.length && payload[pos] === 1);\n bufferParser.clear();\n\n const local = self._offer;\n const remote = init;\n\n let localKex = local.lists.kex.array;\n if (self._compatFlags & COMPAT.BAD_DHGEX) {\n let found = false;\n for (let i = 0; i < localKex.length; ++i) {\n if (localKex[i].indexOf('group-exchange') !== -1) {\n if (!found) {\n found = true;\n // Copy array lazily\n localKex = localKex.slice();\n }\n localKex.splice(i--, 1);\n }\n }\n }\n\n let clientList;\n let serverList;\n let i;\n const debug = self._debug;\n\n debug && debug('Inbound: Handshake in progress');\n\n // Key exchange method =======================================================\n debug && debug(`Handshake: (local) KEX method: ${localKex}`);\n debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`);\n let remoteExtInfoEnabled;\n if (self._server) {\n serverList = localKex;\n clientList = remote.kex;\n remoteExtInfoEnabled = (clientList.indexOf('ext-info-c') !== -1);\n } else {\n serverList = remote.kex;\n clientList = localKex;\n remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1);\n }\n if (self._strictMode === undefined) {\n if (self._server) {\n self._strictMode =\n (clientList.indexOf('kex-strict-c-v00@openssh.com') !== -1);\n } else {\n self._strictMode =\n (serverList.indexOf('kex-strict-s-v00@openssh.com') !== -1);\n }\n // Note: We check for seqno of 1 instead of 0 since we increment before\n // calling the packet handler\n if (self._strictMode) {\n debug && debug('Handshake: strict KEX mode enabled');\n if (self._decipher.inSeqno !== 1) {\n if (debug)\n debug('Handshake: KEXINIT not first packet in strict KEX mode');\n return doFatalError(\n self,\n 'Handshake failed: KEXINIT not first packet in strict KEX mode',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n }\n // Check for agreeable key exchange algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: no matching key exchange algorithm');\n return doFatalError(\n self,\n 'Handshake failed: no matching key exchange algorithm',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.kex = clientList[i];\n debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`);\n if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) {\n // Ignore next inbound packet, it was a wrong first guess at KEX algorithm\n self._skipNextInboundPacket = true;\n }\n\n\n // Server host key format ====================================================\n const localSrvHostKey = local.lists.serverHostKey.array;\n debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`);\n debug && debug(\n `Handshake: (remote) Host key format: ${remote.serverHostKey}`\n );\n if (self._server) {\n serverList = localSrvHostKey;\n clientList = remote.serverHostKey;\n } else {\n serverList = remote.serverHostKey;\n clientList = localSrvHostKey;\n }\n // Check for agreeable server host key format\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching host key format');\n return doFatalError(\n self,\n 'Handshake failed: no matching host key format',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.serverHostKey = clientList[i];\n debug && debug(`Handshake: Host key format: ${clientList[i]}`);\n\n\n // Client->Server cipher =====================================================\n const localCSCipher = local.lists.cs.cipher.array;\n debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`);\n debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`);\n if (self._server) {\n serverList = localCSCipher;\n clientList = remote.cs.cipher;\n } else {\n serverList = remote.cs.cipher;\n clientList = localCSCipher;\n }\n // Check for agreeable client->server cipher\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S cipher');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S cipher',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.cipher = clientList[i];\n debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`);\n\n\n // Server->Client cipher =====================================================\n const localSCCipher = local.lists.sc.cipher.array;\n debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`);\n debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`);\n if (self._server) {\n serverList = localSCCipher;\n clientList = remote.sc.cipher;\n } else {\n serverList = remote.sc.cipher;\n clientList = localSCCipher;\n }\n // Check for agreeable server->client cipher\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C cipher');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C cipher',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.cipher = clientList[i];\n debug && debug(`Handshake: S->C cipher: ${clientList[i]}`);\n\n\n // Client->Server MAC ========================================================\n const localCSMAC = local.lists.cs.mac.array;\n debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`);\n debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`);\n if (CIPHER_INFO[init.cs.cipher].authLen > 0) {\n init.cs.mac = '';\n debug && debug('Handshake: C->S MAC: ');\n } else {\n if (self._server) {\n serverList = localCSMAC;\n clientList = remote.cs.mac;\n } else {\n serverList = remote.cs.mac;\n clientList = localCSMAC;\n }\n // Check for agreeable client->server hmac algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S MAC');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S MAC',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.mac = clientList[i];\n debug && debug(`Handshake: C->S MAC: ${clientList[i]}`);\n }\n\n\n // Server->Client MAC ========================================================\n const localSCMAC = local.lists.sc.mac.array;\n debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`);\n debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`);\n if (CIPHER_INFO[init.sc.cipher].authLen > 0) {\n init.sc.mac = '';\n debug && debug('Handshake: S->C MAC: ');\n } else {\n if (self._server) {\n serverList = localSCMAC;\n clientList = remote.sc.mac;\n } else {\n serverList = remote.sc.mac;\n clientList = localSCMAC;\n }\n // Check for agreeable server->client hmac algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C MAC');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C MAC',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.mac = clientList[i];\n debug && debug(`Handshake: S->C MAC: ${clientList[i]}`);\n }\n\n\n // Client->Server compression ================================================\n const localCSCompress = local.lists.cs.compress.array;\n debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`);\n debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`);\n if (self._server) {\n serverList = localCSCompress;\n clientList = remote.cs.compress;\n } else {\n serverList = remote.cs.compress;\n clientList = localCSCompress;\n }\n // Check for agreeable client->server compression algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S compression');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S compression',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.compress = clientList[i];\n debug && debug(`Handshake: C->S compression: ${clientList[i]}`);\n\n\n // Server->Client compression ================================================\n const localSCCompress = local.lists.sc.compress.array;\n debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`);\n debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`);\n if (self._server) {\n serverList = localSCCompress;\n clientList = remote.sc.compress;\n } else {\n serverList = remote.sc.compress;\n clientList = localSCCompress;\n }\n // Check for agreeable server->client compression algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C compression');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C compression',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.compress = clientList[i];\n debug && debug(`Handshake: S->C compression: ${clientList[i]}`);\n\n init.cs.lang = '';\n init.sc.lang = '';\n\n // XXX: hack -- find a better way to do this\n if (self._kex) {\n if (!self._kexinit) {\n // We received a rekey request, but we haven't sent a KEXINIT in response\n // yet\n kexinit(self);\n }\n self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false });\n }\n\n self._kex = createKeyExchange(init, self, payload);\n self._kex.remoteExtInfoEnabled = remoteExtInfoEnabled;\n self._kex.start();\n}\n\nconst createKeyExchange = (() => {\n function convertToMpint(buf) {\n let idx = 0;\n let length = buf.length;\n while (buf[idx] === 0x00) {\n ++idx;\n --length;\n }\n let newBuf;\n if (buf[idx] & 0x80) {\n newBuf = Buffer.allocUnsafe(1 + length);\n newBuf[0] = 0;\n buf.copy(newBuf, 1, idx);\n buf = newBuf;\n } else if (length !== buf.length) {\n newBuf = Buffer.allocUnsafe(length);\n buf.copy(newBuf, 0, idx);\n buf = newBuf;\n }\n return buf;\n }\n\n class KeyExchange {\n constructor(negotiated, protocol, remoteKexinit) {\n this._protocol = protocol;\n\n this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined);\n this.negotiated = negotiated;\n this.remoteExtInfoEnabled = false;\n this._step = 1;\n this._public = null;\n this._dh = null;\n this._sentNEWKEYS = false;\n this._receivedNEWKEYS = false;\n this._finished = false;\n this._hostVerified = false;\n\n // Data needed for initializing cipher/decipher/etc.\n this._kexinit = protocol._kexinit;\n this._remoteKexinit = remoteKexinit;\n this._identRaw = protocol._identRaw;\n this._remoteIdentRaw = protocol._remoteIdentRaw;\n this._hostKey = undefined;\n this._dhData = undefined;\n this._sig = undefined;\n }\n finish(scOnly) {\n if (this._finished)\n return false;\n this._finished = true;\n\n const isServer = this._protocol._server;\n const negotiated = this.negotiated;\n\n const pubKey = this.convertPublicKey(this._dhData);\n let secret = this.computeSecret(this._dhData);\n if (secret instanceof Error) {\n secret.message =\n `Error while computing DH secret (${this.type}): ${secret.message}`;\n secret.level = 'handshake';\n return doFatalError(\n this._protocol,\n secret,\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n const hash = createHash(this.hashName);\n // V_C\n hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw));\n // \"V_S\"\n hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw));\n // \"I_C\"\n hashString(hash, (isServer ? this._remoteKexinit : this._kexinit));\n // \"I_S\"\n hashString(hash, (isServer ? this._kexinit : this._remoteKexinit));\n // \"K_S\"\n const serverPublicHostKey = (isServer\n ? this._hostKey.getPublicSSH()\n : this._hostKey);\n hashString(hash, serverPublicHostKey);\n\n if (this.type === 'groupex') {\n // Group exchange-specific\n const params = this.getDHParams();\n const num = Buffer.allocUnsafe(4);\n // min (uint32)\n writeUInt32BE(num, this._minBits, 0);\n hash.update(num);\n // preferred (uint32)\n writeUInt32BE(num, this._prefBits, 0);\n hash.update(num);\n // max (uint32)\n writeUInt32BE(num, this._maxBits, 0);\n hash.update(num);\n // prime\n hashString(hash, params.prime);\n // generator\n hashString(hash, params.generator);\n }\n\n // method-specific data sent by client\n hashString(hash, (isServer ? pubKey : this.getPublicKey()));\n // method-specific data sent by server\n const serverPublicKey = (isServer ? this.getPublicKey() : pubKey);\n hashString(hash, serverPublicKey);\n // shared secret (\"K\")\n hashString(hash, secret);\n\n // \"H\"\n const exchangeHash = hash.digest();\n\n if (!isServer) {\n bufferParser.init(this._sig, 0);\n const sigType = bufferParser.readString(true);\n\n if (!sigType) {\n return doFatalError(\n this._protocol,\n 'Malformed packet while reading signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (sigType !== negotiated.serverHostKey) {\n return doFatalError(\n this._protocol,\n `Wrong signature type: ${sigType}, `\n + `expected: ${negotiated.serverHostKey}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // \"s\"\n let sigValue = bufferParser.readString();\n\n bufferParser.clear();\n\n if (sigValue === undefined) {\n return doFatalError(\n this._protocol,\n 'Malformed packet while reading signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (!(sigValue = sigSSHToASN1(sigValue, sigType))) {\n return doFatalError(\n this._protocol,\n 'Malformed signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n let parsedHostKey;\n {\n bufferParser.init(this._hostKey, 0);\n const name = bufferParser.readString(true);\n const hostKey = this._hostKey.slice(bufferParser.pos());\n bufferParser.clear();\n parsedHostKey = parseDERKey(hostKey, name);\n if (parsedHostKey instanceof Error) {\n parsedHostKey.level = 'handshake';\n return doFatalError(\n this._protocol,\n parsedHostKey,\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n let hashAlgo;\n // Check if we need to override the default hash algorithm\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256': hashAlgo = 'sha256'; break;\n case 'rsa-sha2-512': hashAlgo = 'sha512'; break;\n }\n\n this._protocol._debug\n && this._protocol._debug('Verifying signature ...');\n\n const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo);\n if (verified !== true) {\n if (verified instanceof Error) {\n this._protocol._debug && this._protocol._debug(\n `Signature verification failed: ${verified.stack}`\n );\n } else {\n this._protocol._debug && this._protocol._debug(\n 'Signature verification failed'\n );\n }\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature verification failed',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug('Verified signature');\n } else {\n // Server\n\n let hashAlgo;\n // Check if we need to override the default hash algorithm\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256': hashAlgo = 'sha256'; break;\n case 'rsa-sha2-512': hashAlgo = 'sha512'; break;\n }\n\n this._protocol._debug && this._protocol._debug(\n 'Generating signature ...'\n );\n\n let signature = this._hostKey.sign(exchangeHash, hashAlgo);\n if (signature instanceof Error) {\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature generation failed for '\n + `${this._hostKey.type} host key: ${signature.message}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n signature = convertSignature(signature, this._hostKey.type);\n if (signature === false) {\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature conversion failed for '\n + `${this._hostKey.type} host key`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // Send KEX reply\n /*\n byte SSH_MSG_KEXDH_REPLY\n / SSH_MSG_KEX_DH_GEX_REPLY\n / SSH_MSG_KEX_ECDH_REPLY\n string server public host key and certificates (K_S)\n string \n string signature of H\n */\n const sigType = this.negotiated.serverHostKey;\n const sigTypeLen = Buffer.byteLength(sigType);\n const sigLen = 4 + sigTypeLen + 4 + signature.length;\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1\n + 4 + serverPublicHostKey.length\n + 4 + serverPublicKey.length\n + 4 + sigLen,\n true\n );\n\n packet[p] = MESSAGE.KEXDH_REPLY;\n\n writeUInt32BE(packet, serverPublicHostKey.length, ++p);\n packet.set(serverPublicHostKey, p += 4);\n\n writeUInt32BE(packet,\n serverPublicKey.length,\n p += serverPublicHostKey.length);\n packet.set(serverPublicKey, p += 4);\n\n writeUInt32BE(packet, sigLen, p += serverPublicKey.length);\n\n writeUInt32BE(packet, sigTypeLen, p += 4);\n packet.utf8Write(sigType, p += 4, sigTypeLen);\n\n writeUInt32BE(packet, signature.length, p += sigTypeLen);\n packet.set(signature, p += 4);\n\n if (this._protocol._debug) {\n let type;\n switch (this.type) {\n case 'group':\n type = 'KEXDH_REPLY';\n break;\n case 'groupex':\n type = 'KEXDH_GEX_REPLY';\n break;\n default:\n type = 'KEXECDH_REPLY';\n }\n this._protocol._debug(`Outbound: Sending ${type}`);\n }\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n\n if (isServer || !scOnly)\n trySendNEWKEYS(this);\n\n let hsCipherConfig;\n let hsWrite;\n const completeHandshake = (partial) => {\n if (hsCipherConfig) {\n trySendNEWKEYS(this);\n hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno;\n this._protocol._cipher.free();\n this._protocol._cipher = createCipher(hsCipherConfig);\n this._protocol._packetRW.write = hsWrite;\n hsCipherConfig = undefined;\n hsWrite = undefined;\n this._protocol._onHandshakeComplete(negotiated);\n\n return false;\n }\n\n if (!this.sessionID)\n this.sessionID = exchangeHash;\n\n {\n const newSecret = Buffer.allocUnsafe(4 + secret.length);\n writeUInt32BE(newSecret, secret.length, 0);\n newSecret.set(secret, 4);\n secret = newSecret;\n }\n\n // Initialize new ciphers, deciphers, etc.\n\n const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher];\n const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher];\n\n const csIV = generateKEXVal(csCipherInfo.ivLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'A');\n const scIV = generateKEXVal(scCipherInfo.ivLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'B');\n const csKey = generateKEXVal(csCipherInfo.keyLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'C');\n const scKey = generateKEXVal(scCipherInfo.keyLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'D');\n let csMacInfo;\n let csMacKey;\n if (!csCipherInfo.authLen) {\n csMacInfo = MAC_INFO[negotiated.cs.mac];\n csMacKey = generateKEXVal(csMacInfo.len,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'E');\n }\n let scMacInfo;\n let scMacKey;\n if (!scCipherInfo.authLen) {\n scMacInfo = MAC_INFO[negotiated.sc.mac];\n scMacKey = generateKEXVal(scMacInfo.len,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'F');\n }\n\n const config = {\n inbound: {\n onPayload: this._protocol._onPayload,\n seqno: this._protocol._decipher.inSeqno,\n decipherInfo: (!isServer ? scCipherInfo : csCipherInfo),\n decipherIV: (!isServer ? scIV : csIV),\n decipherKey: (!isServer ? scKey : csKey),\n macInfo: (!isServer ? scMacInfo : csMacInfo),\n macKey: (!isServer ? scMacKey : csMacKey),\n },\n outbound: {\n onWrite: this._protocol._onWrite,\n seqno: this._protocol._cipher.outSeqno,\n cipherInfo: (isServer ? scCipherInfo : csCipherInfo),\n cipherIV: (isServer ? scIV : csIV),\n cipherKey: (isServer ? scKey : csKey),\n macInfo: (isServer ? scMacInfo : csMacInfo),\n macKey: (isServer ? scMacKey : csMacKey),\n },\n };\n this._protocol._decipher.free();\n hsCipherConfig = config;\n this._protocol._decipher = createDecipher(config);\n\n const rw = {\n read: undefined,\n write: undefined,\n };\n switch (negotiated.cs.compress) {\n case 'zlib': // starts immediately\n if (isServer)\n rw.read = new ZlibPacketReader();\n else\n rw.write = new ZlibPacketWriter(this._protocol);\n break;\n case 'zlib@openssh.com':\n // Starts after successful user authentication\n\n if (this._protocol._authenticated) {\n // If a rekey happens and this compression method is selected and\n // we already authenticated successfully, we need to start\n // immediately instead\n if (isServer)\n rw.read = new ZlibPacketReader();\n else\n rw.write = new ZlibPacketWriter(this._protocol);\n break;\n }\n // FALLTHROUGH\n default:\n // none -- never any compression/decompression\n\n if (isServer)\n rw.read = new PacketReader();\n else\n rw.write = new PacketWriter(this._protocol);\n }\n switch (negotiated.sc.compress) {\n case 'zlib': // starts immediately\n if (isServer)\n rw.write = new ZlibPacketWriter(this._protocol);\n else\n rw.read = new ZlibPacketReader();\n break;\n case 'zlib@openssh.com':\n // Starts after successful user authentication\n\n if (this._protocol._authenticated) {\n // If a rekey happens and this compression method is selected and\n // we already authenticated successfully, we need to start\n // immediately instead\n if (isServer)\n rw.write = new ZlibPacketWriter(this._protocol);\n else\n rw.read = new ZlibPacketReader();\n break;\n }\n // FALLTHROUGH\n default:\n // none -- never any compression/decompression\n\n if (isServer)\n rw.write = new PacketWriter(this._protocol);\n else\n rw.read = new PacketReader();\n }\n this._protocol._packetRW.read.cleanup();\n this._protocol._packetRW.write.cleanup();\n this._protocol._packetRW.read = rw.read;\n hsWrite = rw.write;\n\n // Cleanup/reset various state\n this._public = null;\n this._dh = null;\n this._kexinit = this._protocol._kexinit = undefined;\n this._remoteKexinit = undefined;\n this._identRaw = undefined;\n this._remoteIdentRaw = undefined;\n this._hostKey = undefined;\n this._dhData = undefined;\n this._sig = undefined;\n\n if (!partial)\n return completeHandshake();\n return false;\n };\n\n if (isServer || scOnly)\n this.finish = completeHandshake;\n\n if (!isServer)\n return completeHandshake(scOnly);\n }\n\n start() {\n if (!this._protocol._server) {\n if (this._protocol._debug) {\n let type;\n switch (this.type) {\n case 'group':\n type = 'KEXDH_INIT';\n break;\n default:\n type = 'KEXECDH_INIT';\n }\n this._protocol._debug(`Outbound: Sending ${type}`);\n }\n\n const pubKey = this.getPublicKey();\n\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1 + 4 + pubKey.length,\n true\n );\n packet[p] = MESSAGE.KEXDH_INIT;\n writeUInt32BE(packet, pubKey.length, ++p);\n packet.set(pubKey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n }\n getPublicKey() {\n this.generateKeys();\n\n const key = this._public;\n\n if (key)\n return this.convertPublicKey(key);\n }\n convertPublicKey(key) {\n let newKey;\n let idx = 0;\n let len = key.length;\n while (key[idx] === 0x00) {\n ++idx;\n --len;\n }\n\n if (key[idx] & 0x80) {\n newKey = Buffer.allocUnsafe(1 + len);\n newKey[0] = 0;\n key.copy(newKey, 1, idx);\n return newKey;\n }\n\n if (len !== key.length) {\n newKey = Buffer.allocUnsafe(len);\n key.copy(newKey, 0, idx);\n key = newKey;\n }\n return key;\n }\n computeSecret(otherPublicKey) {\n this.generateKeys();\n\n try {\n return convertToMpint(this._dh.computeSecret(otherPublicKey));\n } catch (ex) {\n return ex;\n }\n }\n parse(payload) {\n const type = payload[0];\n switch (this._step) {\n case 1:\n if (this._protocol._server) {\n // Server\n if (type !== MESSAGE.KEXDH_INIT) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH Init'\n );\n /*\n byte SSH_MSG_KEXDH_INIT\n / SSH_MSG_KEX_ECDH_INIT\n string \n */\n bufferParser.init(payload, 1);\n const dhData = bufferParser.readString();\n bufferParser.clear();\n if (dhData === undefined) {\n return doFatalError(\n this._protocol,\n 'Received malformed KEX*_INIT',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // Client public key\n this._dhData = dhData;\n\n let hostKey =\n this._protocol._hostKeys[this.negotiated.serverHostKey];\n if (Array.isArray(hostKey))\n hostKey = hostKey[0];\n this._hostKey = hostKey;\n\n this.finish();\n } else {\n // Client\n if (type !== MESSAGE.KEXDH_REPLY) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH Reply'\n );\n /*\n byte SSH_MSG_KEXDH_REPLY\n / SSH_MSG_KEX_DH_GEX_REPLY\n / SSH_MSG_KEX_ECDH_REPLY\n string server public host key and certificates (K_S)\n string \n string signature of H\n */\n bufferParser.init(payload, 1);\n let hostPubKey;\n let dhData;\n let sig;\n if ((hostPubKey = bufferParser.readString()) === undefined\n || (dhData = bufferParser.readString()) === undefined\n || (sig = bufferParser.readString()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n this._protocol,\n 'Received malformed KEX*_REPLY',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n bufferParser.clear();\n\n // Check that the host public key type matches what was negotiated\n // during KEXINIT swap\n bufferParser.init(hostPubKey, 0);\n const hostPubKeyType = bufferParser.readString(true);\n bufferParser.clear();\n if (hostPubKeyType === undefined) {\n return doFatalError(\n this._protocol,\n 'Received malformed host public key',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n if (hostPubKeyType !== this.negotiated.serverHostKey) {\n // Check if we need to make an exception\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256':\n case 'rsa-sha2-512':\n if (hostPubKeyType === 'ssh-rsa')\n break;\n // FALLTHROUGH\n default:\n return doFatalError(\n this._protocol,\n 'Host key does not match negotiated type',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n this._hostKey = hostPubKey;\n this._dhData = dhData;\n this._sig = sig;\n\n let checked = false;\n let ret;\n if (this._protocol._hostVerifier === undefined) {\n ret = true;\n this._protocol._debug && this._protocol._debug(\n 'Host accepted by default (no verification)'\n );\n } else {\n ret = this._protocol._hostVerifier(hostPubKey, (permitted) => {\n if (checked)\n return;\n checked = true;\n if (permitted === false) {\n this._protocol._debug && this._protocol._debug(\n 'Host denied (verification failed)'\n );\n return doFatalError(\n this._protocol,\n 'Host denied (verification failed)',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Host accepted (verified)'\n );\n this._hostVerified = true;\n if (this._receivedNEWKEYS)\n this.finish();\n else\n trySendNEWKEYS(this);\n });\n }\n if (ret === undefined) {\n // Async host verification\n ++this._step;\n return;\n }\n checked = true;\n if (ret === false) {\n this._protocol._debug && this._protocol._debug(\n 'Host denied (verification failed)'\n );\n return doFatalError(\n this._protocol,\n 'Host denied (verification failed)',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Host accepted (verified)'\n );\n this._hostVerified = true;\n trySendNEWKEYS(this);\n }\n ++this._step;\n break;\n case 2:\n if (type !== MESSAGE.NEWKEYS) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Inbound: NEWKEYS'\n );\n this._receivedNEWKEYS = true;\n if (this._protocol._strictMode)\n this._protocol._decipher.inSeqno = 0;\n ++this._step;\n\n return this.finish(!this._protocol._server && !this._hostVerified);\n default:\n return doFatalError(\n this._protocol,\n `Received unexpected packet ${type} after NEWKEYS`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n }\n\n class Curve25519Exchange extends KeyExchange {\n constructor(hashName, ...args) {\n super(...args);\n\n this.type = '25519';\n this.hashName = hashName;\n this._keys = null;\n }\n generateKeys() {\n if (!this._keys)\n this._keys = generateKeyPairSync('x25519');\n }\n getPublicKey() {\n this.generateKeys();\n\n const key = this._keys.publicKey.export({ type: 'spki', format: 'der' });\n return key.slice(-32); // HACK: avoids parsing DER/BER header\n }\n convertPublicKey(key) {\n let newKey;\n let idx = 0;\n let len = key.length;\n while (key[idx] === 0x00) {\n ++idx;\n --len;\n }\n\n if (key.length === 32)\n return key;\n\n if (len !== key.length) {\n newKey = Buffer.allocUnsafe(len);\n key.copy(newKey, 0, idx);\n key = newKey;\n }\n return key;\n }\n computeSecret(otherPublicKey) {\n this.generateKeys();\n\n try {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.110'); // id-X25519\n asnWriter.endSequence();\n\n // PublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(otherPublicKey.length);\n otherPublicKey.copy(asnWriter._buf,\n asnWriter._offset,\n 0,\n otherPublicKey.length);\n asnWriter._offset += otherPublicKey.length;\n asnWriter.endSequence();\n asnWriter.endSequence();\n\n return convertToMpint(diffieHellman({\n privateKey: this._keys.privateKey,\n publicKey: createPublicKey({\n key: asnWriter.buffer,\n type: 'spki',\n format: 'der',\n }),\n }));\n } catch (ex) {\n return ex;\n }\n }\n }\n\n class ECDHExchange extends KeyExchange {\n constructor(curveName, hashName, ...args) {\n super(...args);\n\n this.type = 'ecdh';\n this.curveName = curveName;\n this.hashName = hashName;\n }\n generateKeys() {\n if (!this._dh) {\n this._dh = createECDH(this.curveName);\n this._public = this._dh.generateKeys();\n }\n }\n }\n\n class DHGroupExchange extends KeyExchange {\n constructor(hashName, ...args) {\n super(...args);\n\n this.type = 'groupex';\n this.hashName = hashName;\n this._prime = null;\n this._generator = null;\n this._minBits = GEX_MIN_BITS;\n this._prefBits = dhEstimate(this.negotiated);\n if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE)\n this._prefBits = Math.min(this._prefBits, 4096);\n this._maxBits = GEX_MAX_BITS;\n }\n start() {\n if (this._protocol._server)\n return;\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_GEX_REQUEST'\n );\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1 + 4 + 4 + 4,\n true\n );\n packet[p] = MESSAGE.KEXDH_GEX_REQUEST;\n writeUInt32BE(packet, this._minBits, ++p);\n writeUInt32BE(packet, this._prefBits, p += 4);\n writeUInt32BE(packet, this._maxBits, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n generateKeys() {\n if (!this._dh && this._prime && this._generator) {\n this._dh = createDiffieHellman(this._prime, this._generator);\n this._public = this._dh.generateKeys();\n }\n }\n setDHParams(prime, generator) {\n if (!Buffer.isBuffer(prime))\n throw new Error('Invalid prime value');\n if (!Buffer.isBuffer(generator))\n throw new Error('Invalid generator value');\n this._prime = prime;\n this._generator = generator;\n }\n getDHParams() {\n if (this._dh) {\n return {\n prime: convertToMpint(this._dh.getPrime()),\n generator: convertToMpint(this._dh.getGenerator()),\n };\n }\n }\n parse(payload) {\n const type = payload[0];\n switch (this._step) {\n case 1: {\n if (this._protocol._server) {\n if (type !== MESSAGE.KEXDH_GEX_REQUEST) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of `\n + MESSAGE.KEXDH_GEX_REQUEST,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n // TODO: allow user implementation to provide safe prime and\n // generator on demand to support group exchange on server side\n return doFatalError(\n this._protocol,\n 'Group exchange not implemented for server',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (type !== MESSAGE.KEXDH_GEX_GROUP) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Group'\n );\n\n /*\n byte SSH_MSG_KEX_DH_GEX_GROUP\n mpint p, safe prime\n mpint g, generator for subgroup in GF(p)\n */\n bufferParser.init(payload, 1);\n let prime;\n let gen;\n if ((prime = bufferParser.readString()) === undefined\n || (gen = bufferParser.readString()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n this._protocol,\n 'Received malformed KEXDH_GEX_GROUP',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n bufferParser.clear();\n\n // TODO: validate prime\n this.setDHParams(prime, gen);\n this.generateKeys();\n const pubkey = this.getPublicKey();\n\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_GEX_INIT'\n );\n\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet =\n this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true);\n packet[p] = MESSAGE.KEXDH_GEX_INIT;\n writeUInt32BE(packet, pubkey.length, ++p);\n packet.set(pubkey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n\n ++this._step;\n break;\n }\n case 2:\n if (this._protocol._server) {\n if (type !== MESSAGE.KEXDH_GEX_INIT) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Init'\n );\n return doFatalError(\n this._protocol,\n 'Group exchange not implemented for server',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n } else if (type !== MESSAGE.KEXDH_GEX_REPLY) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Reply'\n );\n this._step = 1;\n payload[0] = MESSAGE.KEXDH_REPLY;\n this.parse = KeyExchange.prototype.parse;\n this.parse(payload);\n }\n }\n }\n\n class DHExchange extends KeyExchange {\n constructor(groupName, hashName, ...args) {\n super(...args);\n\n this.type = 'group';\n this.groupName = groupName;\n this.hashName = hashName;\n }\n start() {\n if (!this._protocol._server) {\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_INIT'\n );\n const pubKey = this.getPublicKey();\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet =\n this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true);\n packet[p] = MESSAGE.KEXDH_INIT;\n writeUInt32BE(packet, pubKey.length, ++p);\n packet.set(pubKey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n }\n generateKeys() {\n if (!this._dh) {\n this._dh = createDiffieHellmanGroup(this.groupName);\n this._public = this._dh.generateKeys();\n }\n }\n getDHParams() {\n if (this._dh) {\n return {\n prime: convertToMpint(this._dh.getPrime()),\n generator: convertToMpint(this._dh.getGenerator()),\n };\n }\n }\n }\n\n return (negotiated, ...args) => {\n if (typeof negotiated !== 'object' || negotiated === null)\n throw new Error('Invalid negotiated argument');\n const kexType = negotiated.kex;\n if (typeof kexType === 'string') {\n args = [negotiated, ...args];\n switch (kexType) {\n case 'curve25519-sha256':\n case 'curve25519-sha256@libssh.org':\n if (!curve25519Supported)\n break;\n return new Curve25519Exchange('sha256', ...args);\n\n case 'ecdh-sha2-nistp256':\n return new ECDHExchange('prime256v1', 'sha256', ...args);\n case 'ecdh-sha2-nistp384':\n return new ECDHExchange('secp384r1', 'sha384', ...args);\n case 'ecdh-sha2-nistp521':\n return new ECDHExchange('secp521r1', 'sha512', ...args);\n\n case 'diffie-hellman-group1-sha1':\n return new DHExchange('modp2', 'sha1', ...args);\n case 'diffie-hellman-group14-sha1':\n return new DHExchange('modp14', 'sha1', ...args);\n case 'diffie-hellman-group14-sha256':\n return new DHExchange('modp14', 'sha256', ...args);\n case 'diffie-hellman-group15-sha512':\n return new DHExchange('modp15', 'sha512', ...args);\n case 'diffie-hellman-group16-sha512':\n return new DHExchange('modp16', 'sha512', ...args);\n case 'diffie-hellman-group17-sha512':\n return new DHExchange('modp17', 'sha512', ...args);\n case 'diffie-hellman-group18-sha512':\n return new DHExchange('modp18', 'sha512', ...args);\n\n case 'diffie-hellman-group-exchange-sha1':\n return new DHGroupExchange('sha1', ...args);\n case 'diffie-hellman-group-exchange-sha256':\n return new DHGroupExchange('sha256', ...args);\n }\n throw new Error(`Unsupported key exchange algorithm: ${kexType}`);\n }\n throw new Error(`Invalid key exchange type: ${kexType}`);\n };\n})();\n\nconst KexInit = (() => {\n const KEX_PROPERTY_NAMES = [\n 'kex',\n 'serverHostKey',\n ['cs', 'cipher' ],\n ['sc', 'cipher' ],\n ['cs', 'mac' ],\n ['sc', 'mac' ],\n ['cs', 'compress' ],\n ['sc', 'compress' ],\n ['cs', 'lang' ],\n ['sc', 'lang' ],\n ];\n return class KexInit {\n constructor(obj) {\n if (typeof obj !== 'object' || obj === null)\n throw new TypeError('Argument must be an object');\n\n const lists = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n sc: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n\n all: undefined,\n };\n let totalSize = 0;\n for (const prop of KEX_PROPERTY_NAMES) {\n let base;\n let val;\n let desc;\n let key;\n if (typeof prop === 'string') {\n base = lists;\n val = obj[prop];\n desc = key = prop;\n } else {\n const parent = prop[0];\n base = lists[parent];\n key = prop[1];\n val = obj[parent][key];\n desc = `${parent}.${key}`;\n }\n const entry = { array: undefined, buffer: undefined };\n if (Buffer.isBuffer(val)) {\n entry.array = ('' + val).split(',');\n entry.buffer = val;\n totalSize += 4 + val.length;\n } else {\n if (typeof val === 'string')\n val = val.split(',');\n if (Array.isArray(val)) {\n entry.array = val;\n entry.buffer = Buffer.from(val.join(','));\n } else {\n throw new TypeError(`Invalid \\`${desc}\\` type: ${typeof val}`);\n }\n totalSize += 4 + entry.buffer.length;\n }\n base[key] = entry;\n }\n\n const all = Buffer.allocUnsafe(totalSize);\n lists.all = all;\n\n let allPos = 0;\n for (const prop of KEX_PROPERTY_NAMES) {\n let data;\n if (typeof prop === 'string')\n data = lists[prop].buffer;\n else\n data = lists[prop[0]][prop[1]].buffer;\n allPos = writeUInt32BE(all, data.length, allPos);\n all.set(data, allPos);\n allPos += data.length;\n }\n\n this.totalSize = totalSize;\n this.lists = lists;\n }\n copyAllTo(buf, offset) {\n const src = this.lists.all;\n if (typeof offset !== 'number')\n throw new TypeError(`Invalid offset value: ${typeof offset}`);\n if (buf.length - offset < src.length)\n throw new Error('Insufficient space to copy list');\n buf.set(src, offset);\n return src.length;\n }\n };\n})();\n\nconst hashString = (() => {\n const LEN = Buffer.allocUnsafe(4);\n return (hash, buf) => {\n writeUInt32BE(LEN, buf.length, 0);\n hash.update(LEN);\n hash.update(buf);\n };\n})();\n\nfunction generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) {\n let ret;\n if (len) {\n let digest = createHash(hashName)\n .update(secret)\n .update(exchangeHash)\n .update(char)\n .update(sessionID)\n .digest();\n while (digest.length < len) {\n const chunk = createHash(hashName)\n .update(secret)\n .update(exchangeHash)\n .update(digest)\n .digest();\n const extended = Buffer.allocUnsafe(digest.length + chunk.length);\n extended.set(digest, 0);\n extended.set(chunk, digest.length);\n digest = extended;\n }\n if (digest.length === len)\n ret = digest;\n else\n ret = new FastBuffer(digest.buffer, digest.byteOffset, len);\n } else {\n ret = EMPTY_BUFFER;\n }\n return ret;\n}\n\nfunction onKEXPayload(state, payload) {\n // XXX: move this to the Decipher implementations?\n if (payload.length === 0) {\n this._debug && this._debug('Inbound: Skipping empty packet payload');\n return;\n }\n\n if (this._skipNextInboundPacket) {\n this._skipNextInboundPacket = false;\n return;\n }\n\n payload = this._packetRW.read.read(payload);\n\n const type = payload[0];\n\n if (!this._strictMode) {\n switch (type) {\n case MESSAGE.IGNORE:\n case MESSAGE.UNIMPLEMENTED:\n case MESSAGE.DEBUG:\n if (!MESSAGE_HANDLERS)\n MESSAGE_HANDLERS = require('./handlers.js');\n return MESSAGE_HANDLERS[type](this, payload);\n }\n }\n\n switch (type) {\n case MESSAGE.DISCONNECT:\n if (!MESSAGE_HANDLERS)\n MESSAGE_HANDLERS = require('./handlers.js');\n return MESSAGE_HANDLERS[type](this, payload);\n case MESSAGE.KEXINIT:\n if (!state.firstPacket) {\n return doFatalError(\n this,\n 'Received extra KEXINIT during handshake',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n state.firstPacket = false;\n return handleKexInit(this, payload);\n default:\n // Ensure packet is either an algorithm negotiation or KEX\n // algorithm-specific packet\n if (type < 20 || type > 49) {\n return doFatalError(\n this,\n `Received unexpected packet type ${type}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n return this._kex.parse(payload);\n}\n\nfunction dhEstimate(neg) {\n const csCipher = CIPHER_INFO[neg.cs.cipher];\n const scCipher = CIPHER_INFO[neg.sc.cipher];\n // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will\n // also need to be considered when calculating `bits`\n const bits = Math.max(\n 0,\n (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen),\n csCipher.blockLen,\n csCipher.ivLen,\n (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen),\n scCipher.blockLen,\n scCipher.ivLen\n ) * 8;\n if (bits <= 112)\n return 2048;\n if (bits <= 128)\n return 3072;\n if (bits <= 192)\n return 7680;\n return 8192;\n}\n\nfunction trySendNEWKEYS(kex) {\n if (!kex._sentNEWKEYS) {\n kex._protocol._debug && kex._protocol._debug(\n 'Outbound: Sending NEWKEYS'\n );\n const p = kex._protocol._packetRW.write.allocStartKEX;\n const packet = kex._protocol._packetRW.write.alloc(1, true);\n packet[p] = MESSAGE.NEWKEYS;\n kex._protocol._cipher.encrypt(\n kex._protocol._packetRW.write.finalize(packet, true)\n );\n kex._sentNEWKEYS = true;\n if (kex._protocol._strictMode)\n kex._protocol._cipher.outSeqno = 0;\n }\n}\n\nmodule.exports = {\n KexInit,\n kexinit,\n onKEXPayload,\n DEFAULT_KEXINIT_CLIENT: new KexInit({\n kex: DEFAULT_KEX.concat(['ext-info-c', 'kex-strict-c-v00@openssh.com']),\n serverHostKey: DEFAULT_SERVER_HOST_KEY,\n cs: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n sc: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n }),\n DEFAULT_KEXINIT_SERVER: new KexInit({\n kex: DEFAULT_KEX.concat(['kex-strict-s-v00@openssh.com']),\n serverHostKey: DEFAULT_SERVER_HOST_KEY,\n cs: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n sc: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n }),\n HANDLERS: {\n [MESSAGE.KEXINIT]: handleKexInit,\n },\n};\n","// TODO:\n// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()`\n// * handle multi-line header values (OpenSSH)?\n// * more thorough validation?\n'use strict';\n\nconst {\n createDecipheriv,\n createECDH,\n createHash,\n createHmac,\n createSign,\n createVerify,\n getCiphers,\n sign: sign_,\n verify: verify_,\n} = require('crypto');\nconst supportedOpenSSLCiphers = getCiphers();\n\nconst { Ber } = require('asn1');\nconst bcrypt_pbkdf = require('bcrypt-pbkdf').pbkdf;\n\nconst { CIPHER_INFO } = require('./crypto.js');\nconst { eddsaSupported, SUPPORTED_CIPHER } = require('./constants.js');\nconst {\n bufferSlice,\n makeBufferParser,\n readString,\n readUInt32BE,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst SYM_HASH_ALGO = Symbol('Hash Algorithm');\nconst SYM_PRIV_PEM = Symbol('Private key PEM');\nconst SYM_PUB_PEM = Symbol('Public key PEM');\nconst SYM_PUB_SSH = Symbol('Public key SSH');\nconst SYM_DECRYPTED = Symbol('Decrypted Key');\n\n// Create OpenSSL cipher name -> SSH cipher name conversion table\nconst CIPHER_INFO_OPENSSL = Object.create(null);\n{\n const keys = Object.keys(CIPHER_INFO);\n for (let i = 0; i < keys.length; ++i) {\n const cipherName = CIPHER_INFO[keys[i]].sslName;\n if (!cipherName || CIPHER_INFO_OPENSSL[cipherName])\n continue;\n CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]];\n }\n}\n\nconst binaryKeyParser = makeBufferParser();\n\nfunction makePEM(type, data) {\n data = data.base64Slice(0, data.length);\n let formatted = data.replace(/.{64}/g, '$&\\n');\n if (data.length & 63)\n formatted += '\\n';\n return `-----BEGIN ${type} KEY-----\\n${formatted}-----END ${type} KEY-----`;\n}\n\nfunction combineBuffers(buf1, buf2) {\n const result = Buffer.allocUnsafe(buf1.length + buf2.length);\n result.set(buf1, 0);\n result.set(buf2, buf1.length);\n return result;\n}\n\nfunction skipFields(buf, nfields) {\n const bufLen = buf.length;\n let pos = (buf._pos || 0);\n for (let i = 0; i < nfields; ++i) {\n const left = (bufLen - pos);\n if (pos >= bufLen || left < 4)\n return false;\n const len = readUInt32BE(buf, pos);\n if (left < 4 + len)\n return false;\n pos += 4 + len;\n }\n buf._pos = pos;\n return true;\n}\n\nfunction genOpenSSLRSAPub(n, e) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption\n // algorithm parameters (RSA has none)\n asnWriter.writeNull();\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n asnWriter.startSequence();\n asnWriter.writeBuffer(n, Ber.Integer);\n asnWriter.writeBuffer(e, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHRSAPub(n, e) {\n const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length);\n\n writeUInt32BE(publicKey, 7, 0);\n publicKey.utf8Write('ssh-rsa', 4, 7);\n\n let i = 4 + 7;\n writeUInt32BE(publicKey, e.length, i);\n publicKey.set(e, i += 4);\n\n writeUInt32BE(publicKey, n.length, i += e.length);\n publicKey.set(n, i + 4);\n\n return publicKey;\n}\n\nconst genOpenSSLRSAPriv = (() => {\n function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeInt(0x00, Ber.Integer);\n asnWriter.writeBuffer(n, Ber.Integer);\n asnWriter.writeBuffer(e, Ber.Integer);\n asnWriter.writeBuffer(d, Ber.Integer);\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(dmp1, Ber.Integer);\n asnWriter.writeBuffer(dmq1, Ber.Integer);\n asnWriter.writeBuffer(iqmp, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n\n function bigIntFromBuffer(buf) {\n return BigInt(`0x${buf.hexSlice(0, buf.length)}`);\n }\n\n function bigIntToBuffer(bn) {\n let hex = bn.toString(16);\n if ((hex.length & 1) !== 0) {\n hex = `0${hex}`;\n } else {\n const sigbit = hex.charCodeAt(0);\n // BER/DER integers require leading zero byte to denote a positive value\n // when first byte >= 0x80\n if (sigbit === 56/* '8' */\n || sigbit === 57/* '9' */\n || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) {\n hex = `00${hex}`;\n }\n }\n return Buffer.from(hex, 'hex');\n }\n\n return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) {\n const bn_d = bigIntFromBuffer(d);\n const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n));\n const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n));\n return makePEM('RSA PRIVATE',\n genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp));\n };\n})();\n\nfunction genOpenSSLDSAPub(p, q, g, y) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa\n // algorithm parameters\n asnWriter.startSequence();\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(g, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n asnWriter.writeBuffer(y, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHDSAPub(p, q, g, y) {\n const publicKey = Buffer.allocUnsafe(\n 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length\n );\n\n writeUInt32BE(publicKey, 7, 0);\n publicKey.utf8Write('ssh-dss', 4, 7);\n\n let i = 4 + 7;\n writeUInt32BE(publicKey, p.length, i);\n publicKey.set(p, i += 4);\n\n writeUInt32BE(publicKey, q.length, i += p.length);\n publicKey.set(q, i += 4);\n\n writeUInt32BE(publicKey, g.length, i += q.length);\n publicKey.set(g, i += 4);\n\n writeUInt32BE(publicKey, y.length, i += g.length);\n publicKey.set(y, i + 4);\n\n return publicKey;\n}\n\nfunction genOpenSSLDSAPriv(p, q, g, y, x) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeInt(0x00, Ber.Integer);\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(g, Ber.Integer);\n asnWriter.writeBuffer(y, Ber.Integer);\n asnWriter.writeBuffer(x, Ber.Integer);\n asnWriter.endSequence();\n return makePEM('DSA PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLEdPub(pub) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.112'); // id-Ed25519\n asnWriter.endSequence();\n\n // PublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(pub.length);\n asnWriter._buf.set(pub, asnWriter._offset);\n asnWriter._offset += pub.length;\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHEdPub(pub) {\n const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length);\n\n writeUInt32BE(publicKey, 11, 0);\n publicKey.utf8Write('ssh-ed25519', 4, 11);\n\n writeUInt32BE(publicKey, pub.length, 15);\n publicKey.set(pub, 19);\n\n return publicKey;\n}\n\nfunction genOpenSSLEdPriv(priv) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // version\n asnWriter.writeInt(0x00, Ber.Integer);\n\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.112'); // id-Ed25519\n asnWriter.endSequence();\n\n // PrivateKey\n asnWriter.startSequence(Ber.OctetString);\n asnWriter.writeBuffer(priv, Ber.OctetString);\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLECDSAPub(oid, Q) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey\n // algorithm parameters (namedCurve)\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(Q.length);\n asnWriter._buf.set(Q, asnWriter._offset);\n asnWriter._offset += Q.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHECDSAPub(oid, Q) {\n let curveName;\n switch (oid) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n curveName = 'nistp256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n curveName = 'nistp384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n curveName = 'nistp521';\n break;\n default:\n return;\n }\n\n const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length);\n\n writeUInt32BE(publicKey, 19, 0);\n publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19);\n\n writeUInt32BE(publicKey, 8, 23);\n publicKey.utf8Write(curveName, 27, 8);\n\n writeUInt32BE(publicKey, Q.length, 35);\n publicKey.set(Q, 39);\n\n return publicKey;\n}\n\nfunction genOpenSSLECDSAPriv(oid, pub, priv) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // version\n asnWriter.writeInt(0x01, Ber.Integer);\n // privateKey\n asnWriter.writeBuffer(priv, Ber.OctetString);\n // parameters (optional)\n asnWriter.startSequence(0xA0);\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n // publicKey (optional)\n asnWriter.startSequence(0xA1);\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(pub.length);\n asnWriter._buf.set(pub, asnWriter._offset);\n asnWriter._offset += pub.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('EC PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLECDSAPubFromPriv(curveName, priv) {\n const tempECDH = createECDH(curveName);\n tempECDH.setPrivateKey(priv);\n return tempECDH.getPublicKey();\n}\n\nconst BaseKey = {\n sign: (() => {\n if (typeof sign_ === 'function') {\n return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return sign_(algo, data, pem);\n } catch (ex) {\n return ex;\n }\n };\n }\n return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n const signature = createSign(algo);\n signature.update(data);\n try {\n return signature.sign(pem);\n } catch (ex) {\n return ex;\n }\n };\n })(),\n verify: (() => {\n if (typeof verify_ === 'function') {\n return function verify(data, signature, algo) {\n const pem = this[SYM_PUB_PEM];\n if (pem === null)\n return new Error('No public key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return verify_(algo, data, pem, signature);\n } catch (ex) {\n return ex;\n }\n };\n }\n return function verify(data, signature, algo) {\n const pem = this[SYM_PUB_PEM];\n if (pem === null)\n return new Error('No public key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n const verifier = createVerify(algo);\n verifier.update(data);\n try {\n return verifier.verify(pem, signature);\n } catch (ex) {\n return ex;\n }\n };\n })(),\n isPrivateKey: function isPrivateKey() {\n return (this[SYM_PRIV_PEM] !== null);\n },\n getPrivatePEM: function getPrivatePEM() {\n return this[SYM_PRIV_PEM];\n },\n getPublicPEM: function getPublicPEM() {\n return this[SYM_PUB_PEM];\n },\n getPublicSSH: function getPublicSSH() {\n return this[SYM_PUB_SSH];\n },\n equals: function equals(key) {\n const parsed = parseKey(key);\n if (parsed instanceof Error)\n return false;\n return (\n this.type === parsed.type\n && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM]\n && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM]\n && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH]\n );\n },\n};\n\n\nfunction OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo,\n decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nOpenSSH_Private.prototype = BaseKey;\n{\n const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\\r\\n|\\n)([\\s\\S]+)(?:\\r\\n|\\n)-----END OPENSSH PRIVATE KEY-----$/;\n OpenSSH_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n let ret;\n const data = Buffer.from(m[1], 'base64');\n if (data.length < 31) // magic (+ magic null term.) + minimum field lengths\n return new Error('Malformed OpenSSH private key');\n const magic = data.utf8Slice(0, 15);\n if (magic !== 'openssh-key-v1\\0')\n return new Error(`Unsupported OpenSSH key magic: ${magic}`);\n\n const cipherName = readString(data, 15, true);\n if (cipherName === undefined)\n return new Error('Malformed OpenSSH private key');\n if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1)\n return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`);\n\n const kdfName = readString(data, data._pos, true);\n if (kdfName === undefined)\n return new Error('Malformed OpenSSH private key');\n if (kdfName !== 'none') {\n if (cipherName === 'none')\n return new Error('Malformed OpenSSH private key');\n if (kdfName !== 'bcrypt')\n return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`);\n if (!passphrase) {\n return new Error(\n 'Encrypted private OpenSSH key detected, but no passphrase given'\n );\n }\n } else if (cipherName !== 'none') {\n return new Error('Malformed OpenSSH private key');\n }\n\n let encInfo;\n let cipherKey;\n let cipherIV;\n if (cipherName !== 'none')\n encInfo = CIPHER_INFO[cipherName];\n const kdfOptions = readString(data, data._pos);\n if (kdfOptions === undefined)\n return new Error('Malformed OpenSSH private key');\n if (kdfOptions.length) {\n switch (kdfName) {\n case 'none':\n return new Error('Malformed OpenSSH private key');\n case 'bcrypt': {\n /*\n string salt\n uint32 rounds\n */\n const salt = readString(kdfOptions, 0);\n if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length)\n return new Error('Malformed OpenSSH private key');\n const rounds = readUInt32BE(kdfOptions, kdfOptions._pos);\n const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen);\n const r = bcrypt_pbkdf(passphrase,\n passphrase.length,\n salt,\n salt.length,\n gen,\n gen.length,\n rounds);\n if (r !== 0)\n return new Error('Failed to generate information to decrypt key');\n cipherKey = bufferSlice(gen, 0, encInfo.keyLen);\n cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length);\n break;\n }\n }\n } else if (kdfName !== 'none') {\n return new Error('Malformed OpenSSH private key');\n }\n\n if (data._pos + 3 >= data.length)\n return new Error('Malformed OpenSSH private key');\n const keyCount = readUInt32BE(data, data._pos);\n data._pos += 4;\n\n if (keyCount > 0) {\n // TODO: place sensible limit on max `keyCount`\n\n // Read public keys first\n for (let i = 0; i < keyCount; ++i) {\n const pubData = readString(data, data._pos);\n if (pubData === undefined)\n return new Error('Malformed OpenSSH private key');\n const type = readString(pubData, 0, true);\n if (type === undefined)\n return new Error('Malformed OpenSSH private key');\n }\n\n let privBlob = readString(data, data._pos);\n if (privBlob === undefined)\n return new Error('Malformed OpenSSH private key');\n\n if (cipherKey !== undefined) {\n // Encrypted private key(s)\n if (privBlob.length < encInfo.blockLen\n || (privBlob.length % encInfo.blockLen) !== 0) {\n return new Error('Malformed OpenSSH private key');\n }\n try {\n const options = { authTagLength: encInfo.authLen };\n const decipher = createDecipheriv(encInfo.sslName,\n cipherKey,\n cipherIV,\n options);\n decipher.setAutoPadding(false);\n if (encInfo.authLen > 0) {\n if (data.length - data._pos < encInfo.authLen)\n return new Error('Malformed OpenSSH private key');\n decipher.setAuthTag(\n bufferSlice(data, data._pos, data._pos += encInfo.authLen)\n );\n }\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n } catch (ex) {\n return ex;\n }\n }\n // Nothing should we follow the private key(s), except a possible\n // authentication tag for relevant ciphers\n if (data._pos !== data.length)\n return new Error('Malformed OpenSSH private key');\n\n ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined);\n } else {\n ret = [];\n }\n if (ret instanceof Error)\n return ret;\n // This will need to change if/when OpenSSH ever starts storing multiple\n // keys in their key files\n return ret[0];\n };\n\n function parseOpenSSHPrivKeys(data, nkeys, decrypted) {\n const keys = [];\n /*\n uint32 checkint\n uint32 checkint\n string privatekey1\n string comment1\n string privatekey2\n string comment2\n ...\n string privatekeyN\n string commentN\n char 1\n char 2\n char 3\n ...\n char padlen % 255\n */\n if (data.length < 8)\n return new Error('Malformed OpenSSH private key');\n const check1 = readUInt32BE(data, 0);\n const check2 = readUInt32BE(data, 4);\n if (check1 !== check2) {\n if (decrypted) {\n return new Error(\n 'OpenSSH key integrity check failed -- bad passphrase?'\n );\n }\n return new Error('OpenSSH key integrity check failed');\n }\n data._pos = 8;\n let i;\n let oid;\n for (i = 0; i < nkeys; ++i) {\n let algo;\n let privPEM;\n let pubPEM;\n let pubSSH;\n // The OpenSSH documentation for the key format actually lies, the\n // entirety of the private key content is not contained with a string\n // field, it's actually the literal contents of the private key, so to be\n // able to find the end of the key data you need to know the layout/format\n // of each key type ...\n const type = readString(data, data._pos, true);\n if (type === undefined)\n return new Error('Malformed OpenSSH private key');\n\n switch (type) {\n case 'ssh-rsa': {\n /*\n string n -- public\n string e -- public\n string d -- private\n string iqmp -- private\n string p -- private\n string q -- private\n */\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed OpenSSH private key');\n const e = readString(data, data._pos);\n if (e === undefined)\n return new Error('Malformed OpenSSH private key');\n const d = readString(data, data._pos);\n if (d === undefined)\n return new Error('Malformed OpenSSH private key');\n const iqmp = readString(data, data._pos);\n if (iqmp === undefined)\n return new Error('Malformed OpenSSH private key');\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed OpenSSH private key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q);\n algo = 'sha1';\n break;\n }\n case 'ssh-dss': {\n /*\n string p -- public\n string q -- public\n string g -- public\n string y -- public\n string x -- private\n */\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed OpenSSH private key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH private key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed OpenSSH private key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed OpenSSH private key');\n const x = readString(data, data._pos);\n if (x === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n privPEM = genOpenSSLDSAPriv(p, q, g, y, x);\n algo = 'sha1';\n break;\n }\n case 'ssh-ed25519': {\n if (!eddsaSupported)\n return new Error(`Unsupported OpenSSH private key type: ${type}`);\n /*\n * string public key\n * string private key + public key\n */\n const edpub = readString(data, data._pos);\n if (edpub === undefined || edpub.length !== 32)\n return new Error('Malformed OpenSSH private key');\n const edpriv = readString(data, data._pos);\n if (edpriv === undefined || edpriv.length !== 64)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLEdPub(edpub);\n pubSSH = genOpenSSHEdPub(edpub);\n privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32));\n algo = null;\n break;\n }\n case 'ecdsa-sha2-nistp256':\n algo = 'sha256';\n oid = '1.2.840.10045.3.1.7';\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp384':\n if (algo === undefined) {\n algo = 'sha384';\n oid = '1.3.132.0.34';\n }\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp521': {\n if (algo === undefined) {\n algo = 'sha512';\n oid = '1.3.132.0.35';\n }\n /*\n string curve name\n string Q -- public\n string d -- private\n */\n // TODO: validate curve name against type\n if (!skipFields(data, 1)) // Skip curve name\n return new Error('Malformed OpenSSH private key');\n const ecpub = readString(data, data._pos);\n if (ecpub === undefined)\n return new Error('Malformed OpenSSH private key');\n const ecpriv = readString(data, data._pos);\n if (ecpriv === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLECDSAPub(oid, ecpub);\n pubSSH = genOpenSSHECDSAPub(oid, ecpub);\n privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv);\n break;\n }\n default:\n return new Error(`Unsupported OpenSSH private key type: ${type}`);\n }\n\n const privComment = readString(data, data._pos, true);\n if (privComment === undefined)\n return new Error('Malformed OpenSSH private key');\n\n keys.push(\n new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo,\n decrypted)\n );\n }\n let cnt = 0;\n for (i = data._pos; i < data.length; ++i) {\n if (data[i] !== (++cnt % 255))\n return new Error('Malformed OpenSSH private key');\n }\n\n return keys;\n }\n}\n\n\nfunction OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo,\n decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nOpenSSH_Old_Private.prototype = BaseKey;\n{\n const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\\r\\n|\\n)((?:[^:]+:\\s*[\\S].*(?:\\r\\n|\\n))*)([\\s\\S]+)(?:\\r\\n|\\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/;\n OpenSSH_Old_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n let privBlob = Buffer.from(m[3], 'base64');\n let headers = m[2];\n let decrypted = false;\n if (headers !== undefined) {\n // encrypted key\n headers = headers.split(/\\r\\n|\\n/g);\n for (let i = 0; i < headers.length; ++i) {\n const header = headers[i];\n let sepIdx = header.indexOf(':');\n if (header.slice(0, sepIdx) === 'DEK-Info') {\n const val = header.slice(sepIdx + 2);\n sepIdx = val.indexOf(',');\n if (sepIdx === -1)\n continue;\n const cipherName = val.slice(0, sepIdx).toLowerCase();\n if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) {\n return new Error(\n `Cipher (${cipherName}) not supported `\n + 'for encrypted OpenSSH private key'\n );\n }\n const encInfo = CIPHER_INFO_OPENSSL[cipherName];\n if (!encInfo) {\n return new Error(\n `Cipher (${cipherName}) not supported `\n + 'for encrypted OpenSSH private key'\n );\n }\n const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex');\n if (cipherIV.length !== encInfo.ivLen)\n return new Error('Malformed encrypted OpenSSH private key');\n if (!passphrase) {\n return new Error(\n 'Encrypted OpenSSH private key detected, but no passphrase given'\n );\n }\n const ivSlice = bufferSlice(cipherIV, 0, 8);\n let cipherKey = createHash('md5')\n .update(passphrase)\n .update(ivSlice)\n .digest();\n while (cipherKey.length < encInfo.keyLen) {\n cipherKey = combineBuffers(\n cipherKey,\n createHash('md5')\n .update(cipherKey)\n .update(passphrase)\n .update(ivSlice)\n .digest()\n );\n }\n if (cipherKey.length > encInfo.keyLen)\n cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen);\n try {\n const decipher = createDecipheriv(cipherName, cipherKey, cipherIV);\n decipher.setAutoPadding(false);\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n decrypted = true;\n } catch (ex) {\n return ex;\n }\n }\n }\n }\n\n let type;\n let privPEM;\n let pubPEM;\n let pubSSH;\n let algo;\n let reader;\n let errMsg = 'Malformed OpenSSH private key';\n if (decrypted)\n errMsg += '. Bad passphrase?';\n switch (m[1]) {\n case 'RSA':\n type = 'ssh-rsa';\n privPEM = makePEM('RSA PRIVATE', privBlob);\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n const n = reader.readString(Ber.Integer, true);\n if (n === null)\n return new Error(errMsg);\n const e = reader.readString(Ber.Integer, true);\n if (e === null)\n return new Error(errMsg);\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n } catch {\n return new Error(errMsg);\n }\n algo = 'sha1';\n break;\n case 'DSA':\n type = 'ssh-dss';\n privPEM = makePEM('DSA PRIVATE', privBlob);\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n const p = reader.readString(Ber.Integer, true);\n if (p === null)\n return new Error(errMsg);\n const q = reader.readString(Ber.Integer, true);\n if (q === null)\n return new Error(errMsg);\n const g = reader.readString(Ber.Integer, true);\n if (g === null)\n return new Error(errMsg);\n const y = reader.readString(Ber.Integer, true);\n if (y === null)\n return new Error(errMsg);\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n } catch {\n return new Error(errMsg);\n }\n algo = 'sha1';\n break;\n case 'EC': {\n let ecSSLName;\n let ecPriv;\n let ecOID;\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n ecPriv = reader.readString(Ber.OctetString, true);\n reader.readByte(); // Skip \"complex\" context type byte\n const offset = reader.readLength(); // Skip context length\n if (offset !== null) {\n reader._offset = offset;\n ecOID = reader.readOID();\n if (ecOID === null)\n return new Error(errMsg);\n switch (ecOID) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n ecSSLName = 'prime256v1';\n type = 'ecdsa-sha2-nistp256';\n algo = 'sha256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n ecSSLName = 'secp384r1';\n type = 'ecdsa-sha2-nistp384';\n algo = 'sha384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n ecSSLName = 'secp521r1';\n type = 'ecdsa-sha2-nistp521';\n algo = 'sha512';\n break;\n default:\n return new Error(`Unsupported private key EC OID: ${ecOID}`);\n }\n } else {\n return new Error(errMsg);\n }\n } catch {\n return new Error(errMsg);\n }\n privPEM = makePEM('EC PRIVATE', privBlob);\n const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv);\n pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob);\n pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob);\n break;\n }\n }\n\n return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo,\n decrypted);\n };\n}\n\n\nfunction PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nPPK_Private.prototype = BaseKey;\n{\n const EMPTY_PASSPHRASE = Buffer.alloc(0);\n const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n const PPK_PP1 = Buffer.from([0, 0, 0, 0]);\n const PPK_PP2 = Buffer.from([0, 0, 0, 1]);\n const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\\r?\\nEncryption: (aes256-cbc|none)\\r?\\nComment: ([^\\r\\n]*)\\r?\\nPublic-Lines: \\d+\\r?\\n([\\s\\S]+?)\\r?\\nPrivate-Lines: \\d+\\r?\\n([\\s\\S]+?)\\r?\\nPrivate-MAC: ([^\\r\\n]+)/;\n PPK_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n // m[1] = key type\n // m[2] = encryption type\n // m[3] = comment\n // m[4] = base64-encoded public key data:\n // for \"ssh-rsa\":\n // string \"ssh-rsa\"\n // mpint e (public exponent)\n // mpint n (modulus)\n // for \"ssh-dss\":\n // string \"ssh-dss\"\n // mpint p (modulus)\n // mpint q (prime)\n // mpint g (base number)\n // mpint y (public key parameter: g^x mod p)\n // m[5] = base64-encoded private key data:\n // for \"ssh-rsa\":\n // mpint d (private exponent)\n // mpint p (prime 1)\n // mpint q (prime 2)\n // mpint iqmp ([inverse of q] mod p)\n // for \"ssh-dss\":\n // mpint x (private key parameter)\n // m[6] = SHA1 HMAC over:\n // string name of algorithm (\"ssh-dss\", \"ssh-rsa\")\n // string encryption type\n // string comment\n // string public key data\n // string private-plaintext (including the final padding)\n const cipherName = m[2];\n const encrypted = (cipherName !== 'none');\n if (encrypted && !passphrase) {\n return new Error(\n 'Encrypted PPK private key detected, but no passphrase given'\n );\n }\n\n let privBlob = Buffer.from(m[5], 'base64');\n\n if (encrypted) {\n const encInfo = CIPHER_INFO[cipherName];\n let cipherKey = combineBuffers(\n createHash('sha1').update(PPK_PP1).update(passphrase).digest(),\n createHash('sha1').update(PPK_PP2).update(passphrase).digest()\n );\n if (cipherKey.length > encInfo.keyLen)\n cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen);\n try {\n const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV);\n decipher.setAutoPadding(false);\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n } catch (ex) {\n return ex;\n }\n }\n\n const type = m[1];\n const comment = m[3];\n const pubBlob = Buffer.from(m[4], 'base64');\n\n const mac = m[6];\n const typeLen = type.length;\n const cipherNameLen = cipherName.length;\n const commentLen = Buffer.byteLength(comment);\n const pubLen = pubBlob.length;\n const privLen = privBlob.length;\n const macData = Buffer.allocUnsafe(4 + typeLen\n + 4 + cipherNameLen\n + 4 + commentLen\n + 4 + pubLen\n + 4 + privLen);\n let p = 0;\n\n writeUInt32BE(macData, typeLen, p);\n macData.utf8Write(type, p += 4, typeLen);\n writeUInt32BE(macData, cipherNameLen, p += typeLen);\n macData.utf8Write(cipherName, p += 4, cipherNameLen);\n writeUInt32BE(macData, commentLen, p += cipherNameLen);\n macData.utf8Write(comment, p += 4, commentLen);\n writeUInt32BE(macData, pubLen, p += commentLen);\n macData.set(pubBlob, p += 4);\n writeUInt32BE(macData, privLen, p += pubLen);\n macData.set(privBlob, p + 4);\n\n if (!passphrase)\n passphrase = EMPTY_PASSPHRASE;\n\n const calcMAC = createHmac(\n 'sha1',\n createHash('sha1')\n .update('putty-private-key-file-mac-key')\n .update(passphrase)\n .digest()\n ).update(macData).digest('hex');\n\n if (calcMAC !== mac) {\n if (encrypted) {\n return new Error(\n 'PPK private key integrity check failed -- bad passphrase?'\n );\n }\n return new Error('PPK private key integrity check failed');\n }\n\n let pubPEM;\n let pubSSH;\n let privPEM;\n pubBlob._pos = 0;\n skipFields(pubBlob, 1); // skip (duplicate) key type\n switch (type) {\n case 'ssh-rsa': {\n const e = readString(pubBlob, pubBlob._pos);\n if (e === undefined)\n return new Error('Malformed PPK public key');\n const n = readString(pubBlob, pubBlob._pos);\n if (n === undefined)\n return new Error('Malformed PPK public key');\n const d = readString(privBlob, 0);\n if (d === undefined)\n return new Error('Malformed PPK private key');\n const p = readString(privBlob, privBlob._pos);\n if (p === undefined)\n return new Error('Malformed PPK private key');\n const q = readString(privBlob, privBlob._pos);\n if (q === undefined)\n return new Error('Malformed PPK private key');\n const iqmp = readString(privBlob, privBlob._pos);\n if (iqmp === undefined)\n return new Error('Malformed PPK private key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q);\n break;\n }\n case 'ssh-dss': {\n const p = readString(pubBlob, pubBlob._pos);\n if (p === undefined)\n return new Error('Malformed PPK public key');\n const q = readString(pubBlob, pubBlob._pos);\n if (q === undefined)\n return new Error('Malformed PPK public key');\n const g = readString(pubBlob, pubBlob._pos);\n if (g === undefined)\n return new Error('Malformed PPK public key');\n const y = readString(pubBlob, pubBlob._pos);\n if (y === undefined)\n return new Error('Malformed PPK public key');\n const x = readString(privBlob, 0);\n if (x === undefined)\n return new Error('Malformed PPK private key');\n\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n privPEM = genOpenSSLDSAPriv(p, q, g, y, x);\n break;\n }\n }\n\n return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1',\n encrypted);\n };\n}\n\n\nfunction OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = null;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = false;\n}\nOpenSSH_Public.prototype = BaseKey;\n{\n let regexp;\n if (eddsaSupported)\n regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\\s+([\\S].*)?)$/;\n else\n regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\\s+([\\S].*)?)$/;\n OpenSSH_Public.parse = (str) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n // m[1] = full type\n // m[2] = base type\n // m[3] = base64-encoded public key\n // m[4] = comment\n\n const fullType = m[1];\n const baseType = m[2];\n const data = Buffer.from(m[3], 'base64');\n const comment = (m[4] || '');\n\n const type = readString(data, data._pos, true);\n if (type === undefined || type.indexOf(baseType) !== 0)\n return new Error('Malformed OpenSSH public key');\n\n return parseDER(data, baseType, comment, fullType);\n };\n}\n\n\nfunction RFC4716_Public(type, comment, pubPEM, pubSSH, algo) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = null;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = false;\n}\nRFC4716_Public.prototype = BaseKey;\n{\n const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\\r?\\n)((?:.{0,72}\\r?\\n)+)---- END SSH2 PUBLIC KEY ----$/;\n const RE_DATA = /^[A-Z0-9a-z/+=\\r\\n]+$/;\n const RE_HEADER = /^([\\x21-\\x39\\x3B-\\x7E]{1,64}): ((?:[^\\\\]*\\\\\\r?\\n)*[^\\r\\n]+)\\r?\\n/gm;\n const RE_HEADER_ENDS = /\\\\\\r?\\n/g;\n RFC4716_Public.parse = (str) => {\n let m = regexp.exec(str);\n if (m === null)\n return null;\n\n const body = m[1];\n let dataStart = 0;\n let comment = '';\n\n while (m = RE_HEADER.exec(body)) {\n const headerName = m[1];\n const headerValue = m[2].replace(RE_HEADER_ENDS, '');\n if (headerValue.length > 1024) {\n RE_HEADER.lastIndex = 0;\n return new Error('Malformed RFC4716 public key');\n }\n\n dataStart = RE_HEADER.lastIndex;\n\n if (headerName.toLowerCase() === 'comment') {\n comment = headerValue;\n if (comment.length > 1\n && comment.charCodeAt(0) === 34/* '\"' */\n && comment.charCodeAt(comment.length - 1) === 34/* '\"' */) {\n comment = comment.slice(1, -1);\n }\n }\n }\n\n let data = body.slice(dataStart);\n if (!RE_DATA.test(data))\n return new Error('Malformed RFC4716 public key');\n\n data = Buffer.from(data, 'base64');\n\n const type = readString(data, 0, true);\n if (type === undefined)\n return new Error('Malformed RFC4716 public key');\n\n let pubPEM = null;\n let pubSSH = null;\n switch (type) {\n case 'ssh-rsa': {\n const e = readString(data, data._pos);\n if (e === undefined)\n return new Error('Malformed RFC4716 public key');\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed RFC4716 public key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n break;\n }\n case 'ssh-dss': {\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed RFC4716 public key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed RFC4716 public key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed RFC4716 public key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed RFC4716 public key');\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n break;\n }\n default:\n return new Error('Malformed RFC4716 public key');\n }\n\n return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1');\n };\n}\n\n\nfunction parseDER(data, baseType, comment, fullType) {\n if (!isSupportedKeyType(baseType))\n return new Error(`Unsupported OpenSSH public key type: ${baseType}`);\n\n let algo;\n let oid;\n let pubPEM = null;\n let pubSSH = null;\n\n switch (baseType) {\n case 'ssh-rsa': {\n const e = readString(data, data._pos || 0);\n if (e === undefined)\n return new Error('Malformed OpenSSH public key');\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n algo = 'sha1';\n break;\n }\n case 'ssh-dss': {\n const p = readString(data, data._pos || 0);\n if (p === undefined)\n return new Error('Malformed OpenSSH public key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH public key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed OpenSSH public key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n algo = 'sha1';\n break;\n }\n case 'ssh-ed25519': {\n const edpub = readString(data, data._pos || 0);\n if (edpub === undefined || edpub.length !== 32)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLEdPub(edpub);\n pubSSH = genOpenSSHEdPub(edpub);\n algo = null;\n break;\n }\n case 'ecdsa-sha2-nistp256':\n algo = 'sha256';\n oid = '1.2.840.10045.3.1.7';\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp384':\n if (algo === undefined) {\n algo = 'sha384';\n oid = '1.3.132.0.34';\n }\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp521': {\n if (algo === undefined) {\n algo = 'sha512';\n oid = '1.3.132.0.35';\n }\n // TODO: validate curve name against type\n if (!skipFields(data, 1)) // Skip curve name\n return new Error('Malformed OpenSSH public key');\n const ecpub = readString(data, data._pos || 0);\n if (ecpub === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLECDSAPub(oid, ecpub);\n pubSSH = genOpenSSHECDSAPub(oid, ecpub);\n break;\n }\n default:\n return new Error(`Unsupported OpenSSH public key type: ${baseType}`);\n }\n\n return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo);\n}\n\nfunction isSupportedKeyType(type) {\n switch (type) {\n case 'ssh-rsa':\n case 'ssh-dss':\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521':\n return true;\n case 'ssh-ed25519':\n if (eddsaSupported)\n return true;\n // FALLTHROUGH\n default:\n return false;\n }\n}\n\nfunction isParsedKey(val) {\n if (!val)\n return false;\n return (typeof val[SYM_DECRYPTED] === 'boolean');\n}\n\nfunction parseKey(data, passphrase) {\n if (isParsedKey(data))\n return data;\n\n let origBuffer;\n if (Buffer.isBuffer(data)) {\n origBuffer = data;\n data = data.utf8Slice(0, data.length).trim();\n } else if (typeof data === 'string') {\n data = data.trim();\n } else {\n return new Error('Key data must be a Buffer or string');\n }\n\n // eslint-disable-next-line eqeqeq\n if (passphrase != undefined) {\n if (typeof passphrase === 'string')\n passphrase = Buffer.from(passphrase);\n else if (!Buffer.isBuffer(passphrase))\n return new Error('Passphrase must be a string or Buffer when supplied');\n }\n\n let ret;\n\n // First try as printable string format (e.g. PEM)\n\n // Private keys\n if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null)\n return ret;\n if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null)\n return ret;\n if ((ret = PPK_Private.parse(data, passphrase)) !== null)\n return ret;\n\n // Public keys\n if ((ret = OpenSSH_Public.parse(data)) !== null)\n return ret;\n if ((ret = RFC4716_Public.parse(data)) !== null)\n return ret;\n\n // Finally try as a binary format if we were originally passed binary data\n if (origBuffer) {\n binaryKeyParser.init(origBuffer, 0);\n const type = binaryKeyParser.readString(true);\n if (type !== undefined) {\n data = binaryKeyParser.readRaw();\n if (data !== undefined) {\n ret = parseDER(data, type, '', type);\n // Ignore potentially useless errors in case the data was not actually\n // in the binary format\n if (ret instanceof Error)\n ret = null;\n }\n }\n binaryKeyParser.clear();\n }\n\n if (ret)\n return ret;\n\n return new Error('Unsupported key format');\n}\n\nmodule.exports = {\n isParsedKey,\n isSupportedKeyType,\n parseDERKey: (data, type) => parseDER(data, type, '', type),\n parseKey,\n};\n","'use strict';\n\nconst assert = require('assert');\nconst { inspect } = require('util');\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n let res = '';\n let i = val.length;\n const start = val[0] === '-' ? 1 : 0;\n for (; i >= start + 4; i -= 3)\n res = `_${val.slice(i - 3, i)}${res}`;\n return `${val.slice(0, i)}${res}`;\n}\n\nfunction oneOf(expected, thing) {\n assert(typeof thing === 'string', '`thing` has to be of type string');\n if (Array.isArray(expected)) {\n const len = expected.length;\n assert(len > 0, 'At least one expected value needs to be specified');\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or `\n + expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n }\n return `of ${thing} ${expected[0]}`;\n }\n return `of ${thing} ${String(expected)}`;\n}\n\n\nexports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error {\n constructor(message) {\n super();\n Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION);\n\n const suffix = 'This is caused by either a bug in ssh2 '\n + 'or incorrect usage of ssh2 internals.\\n'\n + 'Please open an issue with this stack trace at '\n + 'https://github.com/mscdex/ssh2/issues\\n';\n\n this.message = (message === undefined ? suffix : `${message}\\n${suffix}`);\n }\n};\n\nconst MAX_32BIT_INT = 2 ** 32;\nconst MAX_32BIT_BIGINT = (() => {\n try {\n return new Function('return 2n ** 32n')();\n } catch {}\n})();\nexports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError {\n constructor(str, range, input, replaceDefaultBoolean) {\n super();\n Error.captureStackTrace(this, ERR_OUT_OF_RANGE);\n\n assert(range, 'Missing \"range\" argument');\n let msg = (replaceDefaultBoolean\n ? str\n : `The value of \"${str}\" is out of range.`);\n let received;\n if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) {\n received = addNumericalSeparator(String(input));\n } else if (typeof input === 'bigint') {\n received = String(input);\n if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT)\n received = addNumericalSeparator(received);\n received += 'n';\n } else {\n received = inspect(input);\n }\n msg += ` It must be ${range}. Received ${received}`;\n\n this.message = msg;\n }\n};\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super();\n Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE);\n\n assert(typeof name === 'string', `'name' must be a string`);\n\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && expected.startsWith('not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (name.endsWith(' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = (name.includes('.') ? 'property' : 'argument');\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n\n this.message = msg;\n }\n}\nexports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE;\n\nexports.validateNumber = function validateNumber(value, name) {\n if (typeof value !== 'number')\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value);\n};\n","'use strict';\n\nconst Ber = require('asn1').Ber;\n\nlet DISCONNECT_REASON;\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill;\n\nfunction readUInt32BE(buf, offset) {\n return (buf[offset++] * 16777216)\n + (buf[offset++] * 65536)\n + (buf[offset++] * 256)\n + buf[offset];\n}\n\nfunction bufferCopy(src, dest, srcStart, srcEnd, destStart) {\n if (!destStart)\n destStart = 0;\n if (srcEnd > src.length)\n srcEnd = src.length;\n let nb = srcEnd - srcStart;\n const destLeft = (dest.length - destStart);\n if (nb > destLeft)\n nb = destLeft;\n dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb),\n destStart);\n return nb;\n}\n\nfunction bufferSlice(buf, start, end) {\n if (end === undefined)\n end = buf.length;\n return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start);\n}\n\nfunction makeBufferParser() {\n let pos = 0;\n let buffer;\n\n const self = {\n init: (buf, start) => {\n buffer = buf;\n pos = (typeof start === 'number' ? start : 0);\n },\n pos: () => pos,\n length: () => (buffer ? buffer.length : 0),\n avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0),\n clear: () => {\n buffer = undefined;\n },\n readUInt32BE: () => {\n if (!buffer || pos + 3 >= buffer.length)\n return;\n return (buffer[pos++] * 16777216)\n + (buffer[pos++] * 65536)\n + (buffer[pos++] * 256)\n + buffer[pos++];\n },\n readUInt64BE: (behavior) => {\n if (!buffer || pos + 7 >= buffer.length)\n return;\n switch (behavior) {\n case 'always':\n return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`);\n case 'maybe':\n if (buffer[pos] > 0x1F)\n return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`);\n // FALLTHROUGH\n default:\n return (buffer[pos++] * 72057594037927940)\n + (buffer[pos++] * 281474976710656)\n + (buffer[pos++] * 1099511627776)\n + (buffer[pos++] * 4294967296)\n + (buffer[pos++] * 16777216)\n + (buffer[pos++] * 65536)\n + (buffer[pos++] * 256)\n + buffer[pos++];\n }\n },\n skip: (n) => {\n if (buffer && n > 0)\n pos += n;\n },\n skipString: () => {\n const len = self.readUInt32BE();\n if (len === undefined)\n return;\n pos += len;\n return (pos <= buffer.length ? len : undefined);\n },\n readByte: () => {\n if (buffer && pos < buffer.length)\n return buffer[pos++];\n },\n readBool: () => {\n if (buffer && pos < buffer.length)\n return !!buffer[pos++];\n },\n readList: () => {\n const list = self.readString(true);\n if (list === undefined)\n return;\n return (list ? list.split(',') : []);\n },\n readString: (dest, maxLen) => {\n if (typeof dest === 'number') {\n maxLen = dest;\n dest = undefined;\n }\n\n const len = self.readUInt32BE();\n if (len === undefined)\n return;\n\n if ((buffer.length - pos) < len\n || (typeof maxLen === 'number' && len > maxLen)) {\n return;\n }\n\n if (dest) {\n if (Buffer.isBuffer(dest))\n return bufferCopy(buffer, dest, pos, pos += len);\n return buffer.utf8Slice(pos, pos += len);\n }\n return bufferSlice(buffer, pos, pos += len);\n },\n readRaw: (len) => {\n if (!buffer)\n return;\n if (typeof len !== 'number')\n return bufferSlice(buffer, pos, pos += (buffer.length - pos));\n if ((buffer.length - pos) >= len)\n return bufferSlice(buffer, pos, pos += len);\n },\n };\n\n return self;\n}\n\nfunction makeError(msg, level, fatal) {\n const err = new Error(msg);\n if (typeof level === 'boolean') {\n fatal = level;\n err.level = 'protocol';\n } else {\n err.level = level || 'protocol';\n }\n err.fatal = !!fatal;\n return err;\n}\n\nfunction writeUInt32BE(buf, value, offset) {\n buf[offset++] = (value >>> 24);\n buf[offset++] = (value >>> 16);\n buf[offset++] = (value >>> 8);\n buf[offset++] = value;\n return offset;\n}\n\nconst utilBufferParser = makeBufferParser();\n\nmodule.exports = {\n bufferCopy,\n bufferSlice,\n FastBuffer,\n bufferFill: (buf, value, start, end) => {\n return TypedArrayFill.call(buf, value, start, end);\n },\n makeError,\n doFatalError: (protocol, msg, level, reason) => {\n let err;\n if (DISCONNECT_REASON === undefined)\n ({ DISCONNECT_REASON } = require('./constants.js'));\n if (msg instanceof Error) {\n // doFatalError(protocol, err[, reason])\n err = msg;\n if (typeof level !== 'number')\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n else\n reason = level;\n } else {\n // doFatalError(protocol, msg[, level[, reason]])\n err = makeError(msg, level, true);\n }\n if (typeof reason !== 'number')\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n protocol.disconnect(reason);\n protocol._destruct();\n protocol._onError(err);\n return Infinity;\n },\n readUInt32BE,\n writeUInt32BE,\n writeUInt32LE: (buf, value, offset) => {\n buf[offset++] = value;\n buf[offset++] = (value >>> 8);\n buf[offset++] = (value >>> 16);\n buf[offset++] = (value >>> 24);\n return offset;\n },\n makeBufferParser,\n bufferParser: makeBufferParser(),\n readString: (buffer, start, dest, maxLen) => {\n if (typeof dest === 'number') {\n maxLen = dest;\n dest = undefined;\n }\n\n if (start === undefined)\n start = 0;\n\n const left = (buffer.length - start);\n if (start < 0 || start >= buffer.length || left < 4)\n return;\n\n const len = readUInt32BE(buffer, start);\n if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen))\n return;\n\n start += 4;\n const end = start + len;\n buffer._pos = end;\n\n if (dest) {\n if (Buffer.isBuffer(dest))\n return bufferCopy(buffer, dest, start, end);\n return buffer.utf8Slice(start, end);\n }\n return bufferSlice(buffer, start, end);\n },\n sigSSHToASN1: (sig, type) => {\n switch (type) {\n case 'ssh-dss': {\n if (sig.length > 40)\n return sig;\n // Change bare signature r and s values to ASN.1 BER values for OpenSSL\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n let r = sig.slice(0, 20);\n let s = sig.slice(20);\n if (r[0] & 0x80) {\n const rNew = Buffer.allocUnsafe(21);\n rNew[0] = 0x00;\n r.copy(rNew, 1);\n r = rNew;\n } else if (r[0] === 0x00 && !(r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] & 0x80) {\n const sNew = Buffer.allocUnsafe(21);\n sNew[0] = 0x00;\n s.copy(sNew, 1);\n s = sNew;\n } else if (s[0] === 0x00 && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n asnWriter.writeBuffer(r, Ber.Integer);\n asnWriter.writeBuffer(s, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521': {\n utilBufferParser.init(sig, 0);\n const r = utilBufferParser.readString();\n const s = utilBufferParser.readString();\n utilBufferParser.clear();\n if (r === undefined || s === undefined)\n return;\n\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeBuffer(r, Ber.Integer);\n asnWriter.writeBuffer(s, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n default:\n return sig;\n }\n },\n convertSignature: (signature, keyType) => {\n switch (keyType) {\n case 'ssh-dss': {\n if (signature.length <= 40)\n return signature;\n // This is a quick and dirty way to get from BER encoded r and s that\n // OpenSSL gives us, to just the bare values back to back (40 bytes\n // total) like OpenSSH (and possibly others) are expecting\n const asnReader = new Ber.Reader(signature);\n asnReader.readSequence();\n let r = asnReader.readString(Ber.Integer, true);\n let s = asnReader.readString(Ber.Integer, true);\n let rOffset = 0;\n let sOffset = 0;\n if (r.length < 20) {\n const rNew = Buffer.allocUnsafe(20);\n rNew.set(r, 1);\n r = rNew;\n r[0] = 0;\n }\n if (s.length < 20) {\n const sNew = Buffer.allocUnsafe(20);\n sNew.set(s, 1);\n s = sNew;\n s[0] = 0;\n }\n if (r.length > 20 && r[0] === 0)\n rOffset = 1;\n if (s.length > 20 && s[0] === 0)\n sOffset = 1;\n const newSig =\n Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset));\n bufferCopy(r, newSig, rOffset, r.length, 0);\n bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset);\n return newSig;\n }\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521': {\n if (signature[0] === 0)\n return signature;\n // Convert SSH signature parameters to ASN.1 BER values for OpenSSL\n const asnReader = new Ber.Reader(signature);\n asnReader.readSequence();\n const r = asnReader.readString(Ber.Integer, true);\n const s = asnReader.readString(Ber.Integer, true);\n if (r === null || s === null)\n return;\n const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length);\n writeUInt32BE(newSig, r.length, 0);\n newSig.set(r, 4);\n writeUInt32BE(newSig, s.length, 4 + r.length);\n newSig.set(s, 4 + 4 + r.length);\n return newSig;\n }\n }\n\n return signature;\n },\n sendPacket: (proto, packet, bypass) => {\n if (!bypass && proto._kexinit !== undefined) {\n // We're currently in the middle of a handshake\n\n if (proto._queue === undefined)\n proto._queue = [];\n proto._queue.push(packet);\n proto._debug && proto._debug('Outbound: ... packet queued');\n return false;\n }\n proto._cipher.encrypt(packet);\n return true;\n },\n};\n","'use strict';\n\nconst { kMaxLength } = require('buffer');\nconst {\n createInflate,\n constants: {\n DEFLATE,\n INFLATE,\n Z_DEFAULT_CHUNK,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_MEMLEVEL,\n Z_DEFAULT_STRATEGY,\n Z_DEFAULT_WINDOWBITS,\n Z_PARTIAL_FLUSH,\n }\n} = require('zlib');\nconst ZlibHandle = createInflate()._handle.constructor;\n\nfunction processCallback() {\n throw new Error('Should not get here');\n}\n\nfunction zlibOnError(message, errno, code) {\n const self = this._owner;\n // There is no way to cleanly recover.\n // Continuing only obscures problems.\n\n const error = new Error(message);\n error.errno = errno;\n error.code = code;\n self._err = error;\n}\n\nfunction _close(engine) {\n // Caller may invoke .close after a zlib error (which will null _handle).\n if (!engine._handle)\n return;\n\n engine._handle.close();\n engine._handle = null;\n}\n\nclass Zlib {\n constructor(mode) {\n const windowBits = Z_DEFAULT_WINDOWBITS;\n const level = Z_DEFAULT_COMPRESSION;\n const memLevel = Z_DEFAULT_MEMLEVEL;\n const strategy = Z_DEFAULT_STRATEGY;\n const dictionary = undefined;\n\n this._err = undefined;\n this._writeState = new Uint32Array(2);\n this._chunkSize = Z_DEFAULT_CHUNK;\n this._maxOutputLength = kMaxLength;\n this._outBuffer = Buffer.allocUnsafe(this._chunkSize);\n this._outOffset = 0;\n\n this._handle = new ZlibHandle(mode);\n this._handle._owner = this;\n this._handle.onerror = zlibOnError;\n this._handle.init(windowBits,\n level,\n memLevel,\n strategy,\n this._writeState,\n processCallback,\n dictionary);\n }\n\n writeSync(chunk, retChunks) {\n const handle = this._handle;\n if (!handle)\n throw new Error('Invalid Zlib instance');\n\n let availInBefore = chunk.length;\n let availOutBefore = this._chunkSize - this._outOffset;\n let inOff = 0;\n let availOutAfter;\n let availInAfter;\n\n let buffers;\n let nread = 0;\n const state = this._writeState;\n let buffer = this._outBuffer;\n let offset = this._outOffset;\n const chunkSize = this._chunkSize;\n\n while (true) {\n handle.writeSync(Z_PARTIAL_FLUSH,\n chunk, // in\n inOff, // in_off\n availInBefore, // in_len\n buffer, // out\n offset, // out_off\n availOutBefore); // out_len\n if (this._err)\n throw this._err;\n\n availOutAfter = state[0];\n availInAfter = state[1];\n\n const inDelta = availInBefore - availInAfter;\n const have = availOutBefore - availOutAfter;\n\n if (have > 0) {\n const out = (offset === 0 && have === buffer.length\n ? buffer\n : buffer.slice(offset, offset + have));\n offset += have;\n if (!buffers)\n buffers = out;\n else if (buffers.push === undefined)\n buffers = [buffers, out];\n else\n buffers.push(out);\n nread += out.byteLength;\n\n if (nread > this._maxOutputLength) {\n _close(this);\n throw new Error(\n `Output length exceeded maximum of ${this._maxOutputLength}`\n );\n }\n } else if (have !== 0) {\n throw new Error('have should not go down');\n }\n\n // Exhausted the output buffer, or used all the input create a new one.\n if (availOutAfter === 0 || offset >= chunkSize) {\n availOutBefore = chunkSize;\n offset = 0;\n buffer = Buffer.allocUnsafe(chunkSize);\n }\n\n if (availOutAfter === 0) {\n // Not actually done. Need to reprocess.\n // Also, update the availInBefore to the availInAfter value,\n // so that if we have to hit it a third (fourth, etc.) time,\n // it'll have the correct byte counts.\n inOff += inDelta;\n availInBefore = availInAfter;\n } else {\n break;\n }\n }\n\n this._outBuffer = buffer;\n this._outOffset = offset;\n\n if (nread === 0)\n buffers = Buffer.alloc(0);\n\n if (retChunks) {\n buffers.totalLen = nread;\n return buffers;\n }\n\n if (buffers.push === undefined)\n return buffers;\n\n const output = Buffer.allocUnsafe(nread);\n for (let i = 0, p = 0; i < buffers.length; ++i) {\n const buf = buffers[i];\n output.set(buf, p);\n p += buf.length;\n }\n return output;\n }\n}\n\nclass ZlibPacketWriter {\n constructor(protocol) {\n this.allocStart = 0;\n this.allocStartKEX = 0;\n this._protocol = protocol;\n this._zlib = new Zlib(DEFLATE);\n }\n\n cleanup() {\n if (this._zlib)\n _close(this._zlib);\n }\n\n alloc(payloadSize, force) {\n return Buffer.allocUnsafe(payloadSize);\n }\n\n finalize(payload, force) {\n if (this._protocol._kexinit === undefined || force) {\n const output = this._zlib.writeSync(payload, true);\n const packet = this._protocol._cipher.allocPacket(output.totalLen);\n if (output.push === undefined) {\n packet.set(output, 5);\n } else {\n for (let i = 0, p = 5; i < output.length; ++i) {\n const chunk = output[i];\n packet.set(chunk, p);\n p += chunk.length;\n }\n }\n return packet;\n }\n return payload;\n }\n}\n\nclass PacketWriter {\n constructor(protocol) {\n this.allocStart = 5;\n this.allocStartKEX = 5;\n this._protocol = protocol;\n }\n\n cleanup() {}\n\n alloc(payloadSize, force) {\n if (this._protocol._kexinit === undefined || force)\n return this._protocol._cipher.allocPacket(payloadSize);\n return Buffer.allocUnsafe(payloadSize);\n }\n\n finalize(packet, force) {\n return packet;\n }\n}\n\nclass ZlibPacketReader {\n constructor() {\n this._zlib = new Zlib(INFLATE);\n }\n\n cleanup() {\n if (this._zlib)\n _close(this._zlib);\n }\n\n read(data) {\n return this._zlib.writeSync(data, false);\n }\n}\n\nclass PacketReader {\n cleanup() {}\n\n read(data) {\n return data;\n }\n}\n\nmodule.exports = {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n};\n","// TODO:\n// * convert listenerCount() usage to emit() return value checking?\n// * emit error when connection severed early (e.g. before handshake)\n// * add '.connected' or similar property to connection objects to allow\n// immediate connection status checking\n'use strict';\n\nconst { Server: netServer } = require('net');\nconst EventEmitter = require('events');\nconst { listenerCount } = EventEmitter;\n\nconst {\n CHANNEL_OPEN_FAILURE,\n DEFAULT_CIPHER,\n DEFAULT_COMPRESSION,\n DEFAULT_KEX,\n DEFAULT_MAC,\n DEFAULT_SERVER_HOST_KEY,\n DISCONNECT_REASON,\n DISCONNECT_REASON_BY_VALUE,\n SUPPORTED_CIPHER,\n SUPPORTED_COMPRESSION,\n SUPPORTED_KEX,\n SUPPORTED_MAC,\n SUPPORTED_SERVER_HOST_KEY,\n} = require('./protocol/constants.js');\nconst { init: cryptoInit } = require('./protocol/crypto.js');\nconst { KexInit } = require('./protocol/kex.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst Protocol = require('./protocol/Protocol.js');\nconst { SFTP } = require('./protocol/SFTP.js');\nconst { writeUInt32BE } = require('./protocol/utils.js');\n\nconst {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n} = require('./Channel.js');\n\nconst {\n ChannelManager,\n generateAlgorithmList,\n isWritable,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n} = require('./utils.js');\n\nconst MAX_PENDING_AUTHS = 10;\n\nclass AuthContext extends EventEmitter {\n constructor(protocol, username, service, method, cb) {\n super();\n\n this.username = this.user = username;\n this.service = service;\n this.method = method;\n this._initialResponse = false;\n this._finalResponse = false;\n this._multistep = false;\n this._cbfinal = (allowed, methodsLeft, isPartial) => {\n if (!this._finalResponse) {\n this._finalResponse = true;\n cb(this, allowed, methodsLeft, isPartial);\n }\n };\n this._protocol = protocol;\n }\n\n accept() {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(true);\n }\n reject(methodsLeft, isPartial) {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(false, methodsLeft, isPartial);\n }\n}\n\n\nclass KeyboardAuthContext extends AuthContext {\n constructor(protocol, username, service, method, submethods, cb) {\n super(protocol, username, service, method, cb);\n\n this._multistep = true;\n\n this._cb = undefined;\n this._onInfoResponse = (responses) => {\n const callback = this._cb;\n if (callback) {\n this._cb = undefined;\n callback(responses);\n }\n };\n this.submethods = submethods;\n this.on('abort', () => {\n this._cb && this._cb(new Error('Authentication request aborted'));\n });\n }\n\n prompt(prompts, title, instructions, cb) {\n if (!Array.isArray(prompts))\n prompts = [ prompts ];\n\n if (typeof title === 'function') {\n cb = title;\n title = instructions = undefined;\n } else if (typeof instructions === 'function') {\n cb = instructions;\n instructions = undefined;\n } else if (typeof cb !== 'function') {\n cb = undefined;\n }\n\n for (let i = 0; i < prompts.length; ++i) {\n if (typeof prompts[i] === 'string') {\n prompts[i] = {\n prompt: prompts[i],\n echo: true\n };\n }\n }\n\n this._cb = cb;\n this._initialResponse = true;\n\n this._protocol.authInfoReq(title, instructions, prompts);\n }\n}\n\nclass PKAuthContext extends AuthContext {\n constructor(protocol, username, service, method, pkInfo, cb) {\n super(protocol, username, service, method, cb);\n\n this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };\n this.hashAlgo = pkInfo.hashAlgo;\n this.signature = pkInfo.signature;\n this.blob = pkInfo.blob;\n }\n\n accept() {\n if (!this.signature) {\n this._initialResponse = true;\n this._protocol.authPKOK(this.key.algo, this.key.data);\n } else {\n AuthContext.prototype.accept.call(this);\n }\n }\n}\n\nclass HostbasedAuthContext extends AuthContext {\n constructor(protocol, username, service, method, pkInfo, cb) {\n super(protocol, username, service, method, cb);\n\n this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };\n this.hashAlgo = pkInfo.hashAlgo;\n this.signature = pkInfo.signature;\n this.blob = pkInfo.blob;\n this.localHostname = pkInfo.localHostname;\n this.localUsername = pkInfo.localUsername;\n }\n}\n\nclass PwdAuthContext extends AuthContext {\n constructor(protocol, username, service, method, password, cb) {\n super(protocol, username, service, method, cb);\n\n this.password = password;\n this._changeCb = undefined;\n }\n\n requestChange(prompt, cb) {\n if (this._changeCb)\n throw new Error('Change request already in progress');\n if (typeof prompt !== 'string')\n throw new Error('prompt argument must be a string');\n if (typeof cb !== 'function')\n throw new Error('Callback argument must be a function');\n this._changeCb = cb;\n this._protocol.authPasswdChg(prompt);\n }\n}\n\n\nclass Session extends EventEmitter {\n constructor(client, info, localChan) {\n super();\n\n this.type = 'session';\n this.subtype = undefined;\n this.server = true;\n this._ending = false;\n this._channel = undefined;\n this._chanInfo = {\n type: 'session',\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n }\n}\n\n\nclass Server extends EventEmitter {\n constructor(cfg, listener) {\n super();\n\n if (typeof cfg !== 'object' || cfg === null)\n throw new Error('Missing configuration object');\n\n const hostKeys = Object.create(null);\n const hostKeyAlgoOrder = [];\n\n const hostKeys_ = cfg.hostKeys;\n if (!Array.isArray(hostKeys_))\n throw new Error('hostKeys must be an array');\n\n const cfgAlgos = (\n typeof cfg.algorithms === 'object' && cfg.algorithms !== null\n ? cfg.algorithms\n : {}\n );\n\n const hostKeyAlgos = generateAlgorithmList(\n cfgAlgos.serverHostKey,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY\n );\n for (let i = 0; i < hostKeys_.length; ++i) {\n let privateKey;\n if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string')\n privateKey = parseKey(hostKeys_[i]);\n else\n privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase);\n\n if (privateKey instanceof Error)\n throw new Error(`Cannot parse privateKey: ${privateKey.message}`);\n\n if (Array.isArray(privateKey)) {\n // OpenSSH's newer format only stores 1 key for now\n privateKey = privateKey[0];\n }\n\n if (privateKey.getPrivatePEM() === null)\n throw new Error('privateKey value contains an invalid private key');\n\n // Discard key if we already found a key of the same type\n if (hostKeyAlgoOrder.includes(privateKey.type))\n continue;\n\n if (privateKey.type === 'ssh-rsa') {\n // SSH supports multiple signature hashing algorithms for RSA, so we add\n // the algorithms in the desired order\n let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa');\n const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256');\n const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512');\n if (sha1Pos === -1) {\n // Fall back to giving SHA1 the lowest priority\n sha1Pos = Infinity;\n }\n [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => {\n if (pos === -1)\n return;\n\n let type;\n switch (pos) {\n case sha1Pos: type = 'ssh-rsa'; break;\n case sha256Pos: type = 'rsa-sha2-256'; break;\n case sha512Pos: type = 'rsa-sha2-512'; break;\n default: return;\n }\n\n // Store same RSA key under each hash algorithm name for convenience\n hostKeys[type] = privateKey;\n\n hostKeyAlgoOrder.push(type);\n });\n } else {\n hostKeys[privateKey.type] = privateKey;\n hostKeyAlgoOrder.push(privateKey.type);\n }\n }\n\n const algorithms = {\n kex: generateAlgorithmList(\n cfgAlgos.kex,\n DEFAULT_KEX,\n SUPPORTED_KEX\n ).concat(['kex-strict-s-v00@openssh.com']),\n serverHostKey: hostKeyAlgoOrder,\n cs: {\n cipher: generateAlgorithmList(\n cfgAlgos.cipher,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER\n ),\n mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC),\n compress: generateAlgorithmList(\n cfgAlgos.compress,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION\n ),\n lang: [],\n },\n sc: undefined,\n };\n algorithms.sc = algorithms.cs;\n\n if (typeof listener === 'function')\n this.on('connection', listener);\n\n const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);\n const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined);\n const offer = new KexInit(algorithms);\n\n this._srv = new netServer((socket) => {\n if (this._connections >= this.maxConnections) {\n socket.destroy();\n return;\n }\n ++this._connections;\n socket.once('close', () => {\n --this._connections;\n });\n\n let debug;\n if (origDebug) {\n // Prepend debug output with a unique identifier in case there are\n // multiple clients connected at the same time\n const debugPrefix = `[${process.hrtime().join('.')}] `;\n debug = (msg) => {\n origDebug(`${debugPrefix}${msg}`);\n };\n }\n\n // eslint-disable-next-line no-use-before-define\n new Client(socket, hostKeys, ident, offer, debug, this, cfg);\n }).on('error', (err) => {\n this.emit('error', err);\n }).on('listening', () => {\n this.emit('listening');\n }).on('close', () => {\n this.emit('close');\n });\n this._connections = 0;\n this.maxConnections = Infinity;\n }\n\n injectSocket(socket) {\n this._srv.emit('connection', socket);\n }\n\n listen(...args) {\n this._srv.listen(...args);\n return this;\n }\n\n address() {\n return this._srv.address();\n }\n\n getConnections(cb) {\n this._srv.getConnections(cb);\n return this;\n }\n\n close(cb) {\n this._srv.close(cb);\n return this;\n }\n\n ref() {\n this._srv.ref();\n return this;\n }\n\n unref() {\n this._srv.unref();\n return this;\n }\n}\nServer.KEEPALIVE_CLIENT_INTERVAL = 15000;\nServer.KEEPALIVE_CLIENT_COUNT_MAX = 3;\n\n\nclass Client extends EventEmitter {\n constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) {\n super();\n\n let exchanges = 0;\n let acceptedAuthSvc = false;\n let pendingAuths = [];\n let authCtx;\n let kaTimer;\n let onPacket;\n const unsentGlobalRequestsReplies = [];\n this._sock = socket;\n this._chanMgr = new ChannelManager(this);\n this._debug = debug;\n this.noMoreSessions = false;\n this.authenticated = false;\n\n // Silence pre-header errors\n function onClientPreHeaderError(err) {}\n this.on('error', onClientPreHeaderError);\n\n const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {\n debug(`Debug output from client: ${JSON.stringify(msg)}`);\n });\n\n const kaIntvl = (\n typeof srvCfg.keepaliveInterval === 'number'\n && isFinite(srvCfg.keepaliveInterval)\n && srvCfg.keepaliveInterval > 0\n ? srvCfg.keepaliveInterval\n : (\n typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number'\n && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL)\n && Server.KEEPALIVE_CLIENT_INTERVAL > 0\n ? Server.KEEPALIVE_CLIENT_INTERVAL\n : -1\n )\n );\n const kaCountMax = (\n typeof srvCfg.keepaliveCountMax === 'number'\n && isFinite(srvCfg.keepaliveCountMax)\n && srvCfg.keepaliveCountMax >= 0\n ? srvCfg.keepaliveCountMax\n : (\n typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number'\n && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX)\n && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0\n ? Server.KEEPALIVE_CLIENT_COUNT_MAX\n : -1\n )\n );\n let kaCurCount = 0;\n if (kaIntvl !== -1 && kaCountMax !== -1) {\n this.once('ready', () => {\n const onClose = () => {\n clearInterval(kaTimer);\n };\n this.on('close', onClose).on('end', onClose);\n kaTimer = setInterval(() => {\n if (++kaCurCount > kaCountMax) {\n clearInterval(kaTimer);\n const err = new Error('Keepalive timeout');\n err.level = 'client-timeout';\n this.emit('error', err);\n this.end();\n } else {\n // XXX: if the server ever starts sending real global requests to\n // the client, we will need to add a dummy callback here to\n // keep the correct reply order\n proto.ping();\n }\n }, kaIntvl);\n });\n // TODO: re-verify keepalive behavior with OpenSSH\n onPacket = () => {\n kaTimer && kaTimer.refresh();\n kaCurCount = 0;\n };\n }\n\n const proto = this._protocol = new Protocol({\n server: true,\n hostKeys,\n ident,\n offer,\n onPacket,\n greeting: srvCfg.greeting,\n banner: srvCfg.banner,\n onWrite: (data) => {\n if (isWritable(socket))\n socket.write(data);\n },\n onError: (err) => {\n if (!proto._destruct)\n socket.removeAllListeners('data');\n this.emit('error', err);\n try {\n socket.end();\n } catch {}\n },\n onHeader: (header) => {\n this.removeListener('error', onClientPreHeaderError);\n\n const info = {\n ip: socket.remoteAddress,\n family: socket.remoteFamily,\n port: socket.remotePort,\n header,\n };\n if (!server.emit('connection', this, info)) {\n // auto reject\n proto.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n socket.end();\n return;\n }\n\n if (header.greeting)\n this.emit('greeting', header.greeting);\n },\n onHandshakeComplete: (negotiated) => {\n if (++exchanges > 1)\n this.emit('rekey');\n this.emit('handshake', negotiated);\n },\n debug,\n messageHandlers: {\n DEBUG: DEBUG_HANDLER,\n DISCONNECT: (p, reason, desc) => {\n if (reason !== DISCONNECT_REASON.BY_APPLICATION) {\n if (!desc) {\n desc = DISCONNECT_REASON_BY_VALUE[reason];\n if (desc === undefined)\n desc = `Unexpected disconnection reason: ${reason}`;\n }\n const err = new Error(desc);\n err.code = reason;\n this.emit('error', err);\n }\n socket.end();\n },\n CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from client\n\n // Do early reject in some cases to prevent wasteful channel\n // allocation\n if ((info.type === 'session' && this.noMoreSessions)\n || !this.authenticated) {\n const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n return proto.channelOpenFail(info.sender, reasonCode);\n }\n\n let localChan = -1;\n let reason;\n let replied = false;\n\n let accept;\n const reject = () => {\n if (replied)\n return;\n replied = true;\n\n if (reason === undefined) {\n if (localChan === -1)\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n else\n reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;\n }\n\n if (localChan !== -1)\n this._chanMgr.remove(localChan);\n proto.channelOpenFail(info.sender, reason, '');\n };\n const reserveChannel = () => {\n localChan = this._chanMgr.add();\n\n if (localChan === -1) {\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n if (debug) {\n debug('Automatic rejection of incoming channel open: '\n + 'no channels available');\n }\n }\n\n return (localChan !== -1);\n };\n\n const data = info.data;\n switch (info.type) {\n case 'session':\n if (listenerCount(this, 'session') && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const instance = new Session(this, info, localChan);\n this._chanMgr.update(localChan, instance);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return instance;\n };\n\n this.emit('session', accept, reject);\n return;\n }\n break;\n case 'direct-tcpip':\n if (listenerCount(this, 'tcpip') && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const chanInfo = {\n type: undefined,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const stream = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(localChan, stream);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return stream;\n };\n\n this.emit('tcpip', accept, reject, data);\n return;\n }\n break;\n case 'direct-streamlocal@openssh.com':\n if (listenerCount(this, 'openssh.streamlocal')\n && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const chanInfo = {\n type: undefined,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const stream = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(localChan, stream);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return stream;\n };\n\n this.emit('openssh.streamlocal', accept, reject, data);\n return;\n }\n break;\n default:\n // Automatically reject any unsupported channel open requests\n reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;\n if (debug) {\n debug('Automatic rejection of unsupported incoming channel open'\n + ` type: ${info.type}`);\n }\n }\n\n if (reason === undefined) {\n reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n if (debug) {\n debug('Automatic rejection of unexpected incoming channel open'\n + ` for: ${info.type}`);\n }\n }\n\n reject();\n },\n CHANNEL_OPEN_CONFIRMATION: (p, info) => {\n const channel = this._chanMgr.get(info.recipient);\n if (typeof channel !== 'function')\n return;\n\n const chanInfo = {\n type: channel.type,\n incoming: {\n id: info.recipient,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const instance = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(info.recipient, instance);\n channel(undefined, instance);\n },\n CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },\n CHANNEL_DATA: (p, recipient, data) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n // NOOP -- should not be sent by client\n },\n CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },\n CHANNEL_SUCCESS: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(false);\n },\n CHANNEL_FAILURE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },\n CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {\n const session = this._chanMgr.get(recipient);\n if (typeof session !== 'object' || session === null)\n return;\n\n let replied = false;\n let accept;\n let reject;\n\n if (session.constructor !== Session) {\n // normal Channel instance\n if (wantReply)\n proto.channelFailure(session.outgoing.id);\n return;\n }\n\n if (wantReply) {\n // \"real session\" requests will have custom accept behaviors\n if (type !== 'shell'\n && type !== 'exec'\n && type !== 'subsystem') {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n proto.channelSuccess(session._chanInfo.outgoing.id);\n };\n }\n\n reject = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n proto.channelFailure(session._chanInfo.outgoing.id);\n };\n }\n\n if (session._ending) {\n reject && reject();\n return;\n }\n\n switch (type) {\n // \"pre-real session start\" requests\n case 'env':\n if (listenerCount(session, 'env')) {\n session.emit('env', accept, reject, {\n key: data.name,\n val: data.value\n });\n return;\n }\n break;\n case 'pty-req':\n if (listenerCount(session, 'pty')) {\n session.emit('pty', accept, reject, data);\n return;\n }\n break;\n case 'window-change':\n if (listenerCount(session, 'window-change'))\n session.emit('window-change', accept, reject, data);\n else\n reject && reject();\n break;\n case 'x11-req':\n if (listenerCount(session, 'x11')) {\n session.emit('x11', accept, reject, data);\n return;\n }\n break;\n // \"post-real session start\" requests\n case 'signal':\n if (listenerCount(session, 'signal')) {\n session.emit('signal', accept, reject, {\n name: data\n });\n return;\n }\n break;\n // XXX: is `auth-agent-req@openssh.com` really \"post-real session\n // start\"?\n case 'auth-agent-req@openssh.com':\n if (listenerCount(session, 'auth-agent')) {\n session.emit('auth-agent', accept, reject);\n return;\n }\n break;\n // \"real session start\" requests\n case 'shell':\n if (listenerCount(session, 'shell')) {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n const channel = new Channel(\n this, session._chanInfo, { server: true }\n );\n\n channel.subtype = session.subtype = type;\n session._channel = channel;\n\n return channel;\n };\n\n session.emit('shell', accept, reject);\n return;\n }\n break;\n case 'exec':\n if (listenerCount(session, 'exec')) {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n const channel = new Channel(\n this, session._chanInfo, { server: true }\n );\n\n channel.subtype = session.subtype = type;\n session._channel = channel;\n\n return channel;\n };\n\n session.emit('exec', accept, reject, {\n command: data\n });\n return;\n }\n break;\n case 'subsystem': {\n let useSFTP = (data === 'sftp');\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n let instance;\n if (useSFTP) {\n instance = new SFTP(this, session._chanInfo, {\n server: true,\n debug,\n });\n } else {\n instance = new Channel(\n this, session._chanInfo, { server: true }\n );\n instance.subtype =\n session.subtype = `${type}:${data}`;\n }\n session._channel = instance;\n\n return instance;\n };\n\n if (data === 'sftp') {\n if (listenerCount(session, 'sftp')) {\n session.emit('sftp', accept, reject);\n return;\n }\n useSFTP = false;\n }\n if (listenerCount(session, 'subsystem')) {\n session.emit('subsystem', accept, reject, {\n name: data\n });\n return;\n }\n break;\n }\n }\n debug && debug(\n `Automatic rejection of incoming channel request: ${type}`\n );\n reject && reject();\n },\n CHANNEL_EOF: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n if (!channel._ending) {\n channel._ending = true;\n channel.emit('eof');\n channel.emit('end');\n }\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel.incoming.state !== 'open')\n return;\n channel.incoming.state = 'eof';\n\n if (channel.readable)\n channel.push(null);\n },\n CHANNEL_CLOSE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel._ending = true;\n channel.emit('close');\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n onCHANNEL_CLOSE(this, recipient, channel);\n },\n // Begin service/auth-related ==========================================\n SERVICE_REQUEST: (p, service) => {\n if (exchanges === 0\n || acceptedAuthSvc\n || this.authenticated\n || service !== 'ssh-userauth') {\n proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);\n socket.end();\n return;\n }\n\n acceptedAuthSvc = true;\n proto.serviceAccept(service);\n },\n USERAUTH_REQUEST: (p, username, service, method, methodData) => {\n if (exchanges === 0\n || this.authenticated\n || (authCtx\n && (authCtx.username !== username\n || authCtx.service !== service))\n // TODO: support hostbased auth\n || (method !== 'password'\n && method !== 'publickey'\n && method !== 'hostbased'\n && method !== 'keyboard-interactive'\n && method !== 'none')\n || pendingAuths.length === MAX_PENDING_AUTHS) {\n proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR);\n socket.end();\n return;\n } else if (service !== 'ssh-connection') {\n proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);\n socket.end();\n return;\n }\n\n let ctx;\n switch (method) {\n case 'keyboard-interactive':\n ctx = new KeyboardAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'publickey':\n ctx = new PKAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'hostbased':\n ctx = new HostbasedAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'password':\n if (authCtx\n && authCtx instanceof PwdAuthContext\n && authCtx._changeCb) {\n const cb = authCtx._changeCb;\n authCtx._changeCb = undefined;\n cb(methodData.newPassword);\n return;\n }\n ctx = new PwdAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'none':\n ctx = new AuthContext(proto, username, service, method,\n onAuthDecide);\n break;\n }\n\n if (authCtx) {\n if (!authCtx._initialResponse) {\n return pendingAuths.push(ctx);\n } else if (authCtx._multistep && !authCtx._finalResponse) {\n // RFC 4252 says to silently abort the current auth request if a\n // new auth request comes in before the final response from an\n // auth method that requires additional request/response exchanges\n // -- this means keyboard-interactive for now ...\n authCtx._cleanup && authCtx._cleanup();\n authCtx.emit('abort');\n }\n }\n\n authCtx = ctx;\n\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n },\n USERAUTH_INFO_RESPONSE: (p, responses) => {\n if (authCtx && authCtx instanceof KeyboardAuthContext)\n authCtx._onInfoResponse(responses);\n },\n // End service/auth-related ============================================\n GLOBAL_REQUEST: (p, name, wantReply, data) => {\n const reply = {\n type: null,\n buf: null\n };\n\n function setReply(type, buf) {\n reply.type = type;\n reply.buf = buf;\n sendReplies();\n }\n\n if (wantReply)\n unsentGlobalRequestsReplies.push(reply);\n\n if ((name === 'tcpip-forward'\n || name === 'cancel-tcpip-forward'\n || name === 'no-more-sessions@openssh.com'\n || name === 'streamlocal-forward@openssh.com'\n || name === 'cancel-streamlocal-forward@openssh.com')\n && listenerCount(this, 'request')\n && this.authenticated) {\n let accept;\n let reject;\n\n if (wantReply) {\n let replied = false;\n accept = (chosenPort) => {\n if (replied)\n return;\n replied = true;\n let bufPort;\n if (name === 'tcpip-forward'\n && data.bindPort === 0\n && typeof chosenPort === 'number') {\n bufPort = Buffer.allocUnsafe(4);\n writeUInt32BE(bufPort, chosenPort, 0);\n }\n setReply('SUCCESS', bufPort);\n };\n reject = () => {\n if (replied)\n return;\n replied = true;\n setReply('FAILURE');\n };\n }\n\n if (name === 'no-more-sessions@openssh.com') {\n this.noMoreSessions = true;\n accept && accept();\n return;\n }\n\n this.emit('request', accept, reject, name, data);\n } else if (wantReply) {\n setReply('FAILURE');\n }\n },\n },\n });\n\n socket.pause();\n cryptoInit.then(() => {\n proto.start();\n socket.on('data', (data) => {\n try {\n proto.parse(data, 0, data.length);\n } catch (ex) {\n this.emit('error', ex);\n try {\n if (isWritable(socket))\n socket.end();\n } catch {}\n }\n });\n socket.resume();\n }).catch((err) => {\n this.emit('error', err);\n try {\n if (isWritable(socket))\n socket.end();\n } catch {}\n });\n socket.on('error', (err) => {\n err.level = 'socket';\n this.emit('error', err);\n }).once('end', () => {\n debug && debug('Socket ended');\n proto.cleanup();\n this.emit('end');\n }).once('close', () => {\n debug && debug('Socket closed');\n proto.cleanup();\n this.emit('close');\n\n const err = new Error('No response from server');\n\n // Simulate error for pending channels and close any open channels\n this._chanMgr.cleanup(err);\n });\n\n const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => {\n if (authCtx === ctx && !this.authenticated) {\n if (allowed) {\n authCtx = undefined;\n this.authenticated = true;\n proto.authSuccess();\n pendingAuths = [];\n this.emit('ready');\n } else {\n proto.authFailure(methodsLeft, isPartial);\n if (pendingAuths.length) {\n authCtx = pendingAuths.pop();\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n }\n }\n }\n };\n\n function sendReplies() {\n while (unsentGlobalRequestsReplies.length > 0\n && unsentGlobalRequestsReplies[0].type) {\n const reply = unsentGlobalRequestsReplies.shift();\n if (reply.type === 'SUCCESS')\n proto.requestSuccess(reply.buf);\n if (reply.type === 'FAILURE')\n proto.requestFailure();\n }\n }\n }\n\n end() {\n if (this._sock && isWritable(this._sock)) {\n this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n this._sock.end();\n }\n return this;\n }\n\n x11(originAddr, originPort, cb) {\n const opts = { originAddr, originPort };\n openChannel(this, 'x11', opts, cb);\n return this;\n }\n\n forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) {\n const opts = { boundAddr, boundPort, remoteAddr, remotePort };\n openChannel(this, 'forwarded-tcpip', opts, cb);\n return this;\n }\n\n openssh_forwardOutStreamLocal(socketPath, cb) {\n const opts = { socketPath };\n openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb);\n return this;\n }\n\n rekey(cb) {\n let error;\n\n try {\n this._protocol.rekey();\n } catch (ex) {\n error = ex;\n }\n\n // TODO: re-throw error if no callback?\n\n if (typeof cb === 'function') {\n if (error)\n process.nextTick(cb, error);\n else\n this.once('rekey', cb);\n }\n }\n\n setNoDelay(noDelay) {\n if (this._sock && typeof this._sock.setNoDelay === 'function')\n this._sock.setNoDelay(noDelay);\n\n return this;\n }\n}\n\n\nfunction openChannel(self, type, opts, cb) {\n // Ask the client to open a channel for some purpose (e.g. a forwarded TCP\n // connection)\n const initWindow = MAX_WINDOW;\n const maxPacket = PACKET_SIZE;\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const wrapper = (err, stream) => {\n cb(err, stream);\n };\n wrapper.type = type;\n\n const localChan = self._chanMgr.add(wrapper);\n\n if (localChan === -1) {\n cb(new Error('No free channels available'));\n return;\n }\n\n switch (type) {\n case 'forwarded-tcpip':\n self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts);\n break;\n case 'x11':\n self._protocol.x11(localChan, initWindow, maxPacket, opts);\n break;\n case 'forwarded-streamlocal@openssh.com':\n self._protocol.openssh_forwardedStreamLocal(\n localChan, initWindow, maxPacket, opts\n );\n break;\n default:\n throw new Error(`Unsupported channel type: ${type}`);\n }\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nmodule.exports = Server;\nmodule.exports.IncomingClient = Client;\n","'use strict';\n\nconst { SFTP } = require('./protocol/SFTP.js');\n\nconst MAX_CHANNEL = 2 ** 32 - 1;\n\nfunction onChannelOpenFailure(self, recipient, info, cb) {\n self._chanMgr.remove(recipient);\n if (typeof cb !== 'function')\n return;\n\n let err;\n if (info instanceof Error) {\n err = info;\n } else if (typeof info === 'object' && info !== null) {\n err = new Error(`(SSH) Channel open failure: ${info.description}`);\n err.reason = info.reason;\n } else {\n err = new Error(\n '(SSH) Channel open failure: server closed channel unexpectedly'\n );\n err.reason = '';\n }\n\n cb(err);\n}\n\nfunction onCHANNEL_CLOSE(self, recipient, channel, err, dead) {\n if (typeof channel === 'function') {\n // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when\n // requesting to open a channel\n onChannelOpenFailure(self, recipient, err, channel);\n return;\n }\n\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.incoming && channel.incoming.state === 'closed')\n return;\n\n self._chanMgr.remove(recipient);\n\n if (channel.server && channel.constructor.name === 'Session')\n return;\n\n channel.incoming.state = 'closed';\n\n if (channel.readable)\n channel.push(null);\n if (channel.server) {\n if (channel.stderr.writable)\n channel.stderr.end();\n } else if (channel.stderr.readable) {\n channel.stderr.push(null);\n }\n\n if (channel.constructor !== SFTP\n && (channel.outgoing.state === 'open'\n || channel.outgoing.state === 'eof')\n && !dead) {\n channel.close();\n }\n if (channel.outgoing.state === 'closing')\n channel.outgoing.state = 'closed';\n\n const readState = channel._readableState;\n const writeState = channel._writableState;\n if (writeState && !writeState.ending && !writeState.finished && !dead)\n channel.end();\n\n // Take care of any outstanding channel requests\n const chanCallbacks = channel._callbacks;\n channel._callbacks = [];\n for (let i = 0; i < chanCallbacks.length; ++i)\n chanCallbacks[i](true);\n\n if (channel.server) {\n if (!channel.readable\n || channel.destroyed\n || (readState && readState.endEmitted)) {\n channel.emit('close');\n } else {\n channel.once('end', () => channel.emit('close'));\n }\n } else {\n let doClose;\n switch (channel.type) {\n case 'direct-streamlocal@openssh.com':\n case 'direct-tcpip':\n doClose = () => channel.emit('close');\n break;\n default: {\n // Align more with node child processes, where the close event gets\n // the same arguments as the exit event\n const exit = channel._exit;\n doClose = () => {\n if (exit.code === null)\n channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc);\n else\n channel.emit('close', exit.code);\n };\n }\n }\n if (!channel.readable\n || channel.destroyed\n || (readState && readState.endEmitted)) {\n doClose();\n } else {\n channel.once('end', doClose);\n }\n\n const errReadState = channel.stderr._readableState;\n if (!channel.stderr.readable\n || channel.stderr.destroyed\n || (errReadState && errReadState.endEmitted)) {\n channel.stderr.emit('close');\n } else {\n channel.stderr.once('end', () => channel.stderr.emit('close'));\n }\n }\n}\n\nclass ChannelManager {\n constructor(client) {\n this._client = client;\n this._channels = {};\n this._cur = -1;\n this._count = 0;\n }\n add(val) {\n // Attempt to reserve an id\n\n let id;\n // Optimized paths\n if (this._cur < MAX_CHANNEL) {\n id = ++this._cur;\n } else if (this._count === 0) {\n // Revert and reset back to fast path once we no longer have any channels\n // open\n this._cur = 0;\n id = 0;\n } else {\n // Slower lookup path\n\n // This path is triggered we have opened at least MAX_CHANNEL channels\n // while having at least one channel open at any given time, so we have\n // to search for a free id.\n const channels = this._channels;\n for (let i = 0; i < MAX_CHANNEL; ++i) {\n if (channels[i] === undefined) {\n id = i;\n break;\n }\n }\n }\n\n if (id === undefined)\n return -1;\n\n this._channels[id] = (val || true);\n ++this._count;\n\n return id;\n }\n update(id, val) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n if (val && this._channels[id])\n this._channels[id] = val;\n }\n get(id) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n return this._channels[id];\n }\n remove(id) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n if (this._channels[id]) {\n delete this._channels[id];\n if (this._count)\n --this._count;\n }\n }\n cleanup(err) {\n const channels = this._channels;\n this._channels = {};\n this._cur = -1;\n this._count = 0;\n\n const chanIDs = Object.keys(channels);\n const client = this._client;\n for (let i = 0; i < chanIDs.length; ++i) {\n const id = +chanIDs[i];\n const channel = channels[id];\n onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true);\n }\n }\n}\n\nconst isRegExp = (() => {\n const toString = Object.prototype.toString;\n return (val) => toString.call(val) === '[object RegExp]';\n})();\n\nfunction generateAlgorithmList(algoList, defaultList, supportedList) {\n if (Array.isArray(algoList) && algoList.length > 0) {\n // Exact list\n for (let i = 0; i < algoList.length; ++i) {\n if (supportedList.indexOf(algoList[i]) === -1)\n throw new Error(`Unsupported algorithm: ${algoList[i]}`);\n }\n return algoList;\n }\n\n if (typeof algoList === 'object' && algoList !== null) {\n // Operations based on the default list\n const keys = Object.keys(algoList);\n let list = defaultList;\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n let val = algoList[key];\n switch (key) {\n case 'append':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = 0; j < val.length; ++j) {\n const append = val[j];\n if (typeof append === 'string') {\n if (!append || list.indexOf(append) !== -1)\n continue;\n if (supportedList.indexOf(append) === -1)\n throw new Error(`Unsupported algorithm: ${append}`);\n if (list === defaultList)\n list = list.slice();\n list.push(append);\n } else if (isRegExp(append)) {\n for (let k = 0; k < supportedList.length; ++k) {\n const algo = supportedList[k];\n if (append.test(algo)) {\n if (list.indexOf(algo) !== -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.push(algo);\n }\n }\n }\n }\n }\n break;\n case 'prepend':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = val.length; j >= 0; --j) {\n const prepend = val[j];\n if (typeof prepend === 'string') {\n if (!prepend || list.indexOf(prepend) !== -1)\n continue;\n if (supportedList.indexOf(prepend) === -1)\n throw new Error(`Unsupported algorithm: ${prepend}`);\n if (list === defaultList)\n list = list.slice();\n list.unshift(prepend);\n } else if (isRegExp(prepend)) {\n for (let k = supportedList.length; k >= 0; --k) {\n const algo = supportedList[k];\n if (prepend.test(algo)) {\n if (list.indexOf(algo) !== -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.unshift(algo);\n }\n }\n }\n }\n }\n break;\n case 'remove':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = 0; j < val.length; ++j) {\n const search = val[j];\n if (typeof search === 'string') {\n if (!search)\n continue;\n const idx = list.indexOf(search);\n if (idx === -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.splice(idx, 1);\n } else if (isRegExp(search)) {\n for (let k = 0; k < list.length; ++k) {\n if (search.test(list[k])) {\n if (list === defaultList)\n list = list.slice();\n list.splice(k, 1);\n --k;\n }\n }\n }\n }\n }\n break;\n }\n }\n\n return list;\n }\n\n return defaultList;\n}\n\nmodule.exports = {\n ChannelManager,\n generateAlgorithmList,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n isWritable: (stream) => {\n // XXX: hack to workaround regression in node\n // See: https://github.com/nodejs/node/issues/36029\n return (stream\n && stream.writable\n && stream._readableState\n && stream._readableState.ended === false);\n },\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","var chownr = require('chownr')\nvar tar = require('tar-stream')\nvar pump = require('pump')\nvar mkdirp = require('mkdirp-classic')\nvar fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\nvar win32 = os.platform() === 'win32'\n\nvar noop = function () {}\n\nvar echo = function (name) {\n return name\n}\n\nvar normalize = !win32 ? echo : function (name) {\n return name.replace(/\\\\/g, '/').replace(/[:?<>|]/g, '_')\n}\n\nvar statAll = function (fs, stat, cwd, ignore, entries, sort) {\n var queue = entries || ['.']\n\n return function loop (callback) {\n if (!queue.length) return callback()\n var next = queue.shift()\n var nextAbs = path.join(cwd, next)\n\n stat(nextAbs, function (err, stat) {\n if (err) return callback(err)\n\n if (!stat.isDirectory()) return callback(null, next, stat)\n\n fs.readdir(nextAbs, function (err, files) {\n if (err) return callback(err)\n\n if (sort) files.sort()\n for (var i = 0; i < files.length; i++) {\n if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))\n }\n\n callback(null, next, stat)\n })\n })\n }\n}\n\nvar strip = function (map, level) {\n return function (header) {\n header.name = header.name.split('/').slice(level).join('/')\n\n var linkname = header.linkname\n if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {\n header.linkname = linkname.split('/').slice(level).join('/')\n }\n\n return map(header)\n }\n}\n\nexports.pack = function (cwd, opts) {\n if (!cwd) cwd = '.'\n if (!opts) opts = {}\n\n var xfs = opts.fs || fs\n var ignore = opts.ignore || opts.filter || noop\n var map = opts.map || noop\n var mapStream = opts.mapStream || echo\n var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)\n var strict = opts.strict !== false\n var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()\n var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0\n var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0\n var pack = opts.pack || tar.pack()\n var finish = opts.finish || noop\n\n if (opts.strip) map = strip(map, opts.strip)\n\n if (opts.readable) {\n dmode |= parseInt(555, 8)\n fmode |= parseInt(444, 8)\n }\n if (opts.writable) {\n dmode |= parseInt(333, 8)\n fmode |= parseInt(222, 8)\n }\n\n var onsymlink = function (filename, header) {\n xfs.readlink(path.join(cwd, filename), function (err, linkname) {\n if (err) return pack.destroy(err)\n header.linkname = normalize(linkname)\n pack.entry(header, onnextentry)\n })\n }\n\n var onstat = function (err, filename, stat) {\n if (err) return pack.destroy(err)\n if (!filename) {\n if (opts.finalize !== false) pack.finalize()\n return finish(pack)\n }\n\n if (stat.isSocket()) return onnextentry() // tar does not support sockets...\n\n var header = {\n name: normalize(filename),\n mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,\n mtime: stat.mtime,\n size: stat.size,\n type: 'file',\n uid: stat.uid,\n gid: stat.gid\n }\n\n if (stat.isDirectory()) {\n header.size = 0\n header.type = 'directory'\n header = map(header) || header\n return pack.entry(header, onnextentry)\n }\n\n if (stat.isSymbolicLink()) {\n header.size = 0\n header.type = 'symlink'\n header = map(header) || header\n return onsymlink(filename, header)\n }\n\n // TODO: add fifo etc...\n\n header = map(header) || header\n\n if (!stat.isFile()) {\n if (strict) return pack.destroy(new Error('unsupported type for ' + filename))\n return onnextentry()\n }\n\n var entry = pack.entry(header, onnextentry)\n if (!entry) return\n\n var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)\n\n rs.on('error', function (err) { // always forward errors on destroy\n entry.destroy(err)\n })\n\n pump(rs, entry)\n }\n\n var onnextentry = function (err) {\n if (err) return pack.destroy(err)\n statNext(onstat)\n }\n\n onnextentry()\n\n return pack\n}\n\nvar head = function (list) {\n return list.length ? list[list.length - 1] : null\n}\n\nvar processGetuid = function () {\n return process.getuid ? process.getuid() : -1\n}\n\nvar processUmask = function () {\n return process.umask ? process.umask() : 0\n}\n\nexports.extract = function (cwd, opts) {\n if (!cwd) cwd = '.'\n if (!opts) opts = {}\n\n var xfs = opts.fs || fs\n var ignore = opts.ignore || opts.filter || noop\n var map = opts.map || noop\n var mapStream = opts.mapStream || echo\n var own = opts.chown !== false && !win32 && processGetuid() === 0\n var extract = opts.extract || tar.extract()\n var stack = []\n var now = new Date()\n var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()\n var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0\n var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0\n var strict = opts.strict !== false\n\n if (opts.strip) map = strip(map, opts.strip)\n\n if (opts.readable) {\n dmode |= parseInt(555, 8)\n fmode |= parseInt(444, 8)\n }\n if (opts.writable) {\n dmode |= parseInt(333, 8)\n fmode |= parseInt(222, 8)\n }\n\n var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry\n var top\n while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()\n if (!top) return cb()\n xfs.utimes(top[0], now, top[1], cb)\n }\n\n var utimes = function (name, header, cb) {\n if (opts.utimes === false) return cb()\n\n if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)\n if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?\n\n xfs.utimes(name, now, header.mtime, function (err) {\n if (err) return cb(err)\n utimesParent(name, cb)\n })\n }\n\n var chperm = function (name, header, cb) {\n var link = header.type === 'symlink'\n\n /* eslint-disable node/no-deprecated-api */\n var chmod = link ? xfs.lchmod : xfs.chmod\n var chown = link ? xfs.lchown : xfs.chown\n /* eslint-enable node/no-deprecated-api */\n\n if (!chmod) return cb()\n\n var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask\n chmod(name, mode, function (err) {\n if (err) return cb(err)\n if (!own) return cb()\n if (!chown) return cb()\n chown(name, header.uid, header.gid, cb)\n })\n }\n\n extract.on('entry', function (header, stream, next) {\n header = map(header) || header\n header.name = normalize(header.name)\n var name = path.join(cwd, path.join('/', header.name))\n\n if (ignore(name, header)) {\n stream.resume()\n return next()\n }\n\n var stat = function (err) {\n if (err) return next(err)\n utimes(name, header, function (err) {\n if (err) return next(err)\n if (win32) return next()\n chperm(name, header, next)\n })\n }\n\n var onsymlink = function () {\n if (win32) return next() // skip symlinks on win for now before it can be tested\n xfs.unlink(name, function () {\n xfs.symlink(header.linkname, name, stat)\n })\n }\n\n var onlink = function () {\n if (win32) return next() // skip links on win for now before it can be tested\n xfs.unlink(name, function () {\n var srcpath = path.join(cwd, path.join('/', header.linkname))\n\n xfs.link(srcpath, name, function (err) {\n if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {\n stream = xfs.createReadStream(srcpath)\n return onfile()\n }\n\n stat(err)\n })\n })\n }\n\n var onfile = function () {\n var ws = xfs.createWriteStream(name)\n var rs = mapStream(stream, header)\n\n ws.on('error', function (err) { // always forward errors on destroy\n rs.destroy(err)\n })\n\n pump(rs, ws, function (err) {\n if (err) return next(err)\n ws.on('close', stat)\n })\n }\n\n if (header.type === 'directory') {\n stack.push([name, header.mtime])\n return mkdirfix(name, {\n fs: xfs, own: own, uid: header.uid, gid: header.gid\n }, stat)\n }\n\n var dir = path.dirname(name)\n\n validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {\n if (err) return next(err)\n if (!valid) return next(new Error(dir + ' is not a valid path'))\n\n mkdirfix(dir, {\n fs: xfs, own: own, uid: header.uid, gid: header.gid\n }, function (err) {\n if (err) return next(err)\n\n switch (header.type) {\n case 'file': return onfile()\n case 'link': return onlink()\n case 'symlink': return onsymlink()\n }\n\n if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))\n\n stream.resume()\n next()\n })\n })\n })\n\n if (opts.finish) extract.on('finish', opts.finish)\n\n return extract\n}\n\nfunction validate (fs, name, root, cb) {\n if (name === root) return cb(null, true)\n fs.lstat(name, function (err, st) {\n if (err && err.code !== 'ENOENT') return cb(err)\n if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)\n cb(null, false)\n })\n}\n\nfunction mkdirfix (name, opts, cb) {\n mkdirp(name, { fs: opts.fs }, function (err, made) {\n if (!err && made && opts.own) {\n chownr(made, opts.uid, opts.gid, cb)\n } else {\n cb(err)\n }\n })\n}\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst symbol = Symbol.for('BufferList')\n\nfunction BufferList (buf) {\n if (!(this instanceof BufferList)) {\n return new BufferList(buf)\n }\n\n BufferList._init.call(this, buf)\n}\n\nBufferList._init = function _init (buf) {\n Object.defineProperty(this, symbol, { value: true })\n\n this._bufs = []\n this.length = 0\n\n if (buf) {\n this.append(buf)\n }\n}\n\nBufferList.prototype._new = function _new (buf) {\n return new BufferList(buf)\n}\n\nBufferList.prototype._offset = function _offset (offset) {\n if (offset === 0) {\n return [0, 0]\n }\n\n let tot = 0\n\n for (let i = 0; i < this._bufs.length; i++) {\n const _t = tot + this._bufs[i].length\n if (offset < _t || i === this._bufs.length - 1) {\n return [i, offset - tot]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n const bufferId = blOffset[0]\n let offset = blOffset[1]\n\n for (let i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n\n return offset\n}\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n\n const offset = this._offset(index)\n\n return this._bufs[offset[0]][offset[1]]\n}\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start === 'number' && start < 0) {\n start += this.length\n }\n\n if (typeof end === 'number' && end < 0) {\n end += this.length\n }\n\n return this.copy(null, 0, start, end)\n}\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart !== 'number' || srcStart < 0) {\n srcStart = 0\n }\n\n if (typeof srcEnd !== 'number' || srcEnd > this.length) {\n srcEnd = this.length\n }\n\n if (srcStart >= this.length) {\n return dst || Buffer.alloc(0)\n }\n\n if (srcEnd <= 0) {\n return dst || Buffer.alloc(0)\n }\n\n const copy = !!dst\n const off = this._offset(srcStart)\n const len = srcEnd - srcStart\n let bytes = len\n let bufoff = (copy && dstStart) || 0\n let start = off[1]\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd === this.length) {\n if (!copy) {\n // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (let i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) {\n // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n }\n\n for (let i = off[0]; i < this._bufs.length; i++) {\n const l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start) {\n start = 0\n }\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0) {\n start += this.length\n }\n\n if (end < 0) {\n end += this.length\n }\n\n if (start === end) {\n return this._new()\n }\n\n const startOffset = this._offset(start)\n const endOffset = this._offset(end)\n const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] === 0) {\n buffers.pop()\n } else {\n buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])\n }\n\n if (startOffset[1] !== 0) {\n buffers[0] = buffers[0].slice(startOffset[1])\n }\n\n return this._new(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n\n return this\n}\n\nBufferList.prototype.duplicate = function duplicate () {\n const copy = this._new()\n\n for (let i = 0; i < this._bufs.length; i++) {\n copy.append(this._bufs[i])\n }\n\n return copy\n}\n\nBufferList.prototype.append = function append (buf) {\n if (buf == null) {\n return this\n }\n\n if (buf.buffer) {\n // append a view of the underlying ArrayBuffer\n this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))\n } else if (Array.isArray(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.append(buf[i])\n }\n } else if (this._isBufferList(buf)) {\n // unwrap argument into individual BufferLists\n for (let i = 0; i < buf._bufs.length; i++) {\n this.append(buf._bufs[i])\n }\n } else {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf === 'number') {\n buf = buf.toString()\n }\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (this._isBufferList(search)) {\n search = search.slice()\n } else if (Array.isArray(search.buffer)) {\n search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n const blOffset = this._offset(offset)\n let blIndex = blOffset[0] // index of which internal buffer we're working on\n let buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (; blIndex < this._bufs.length; blIndex++) {\n const buff = this._bufs[blIndex]\n\n while (buffOffset < buff.length) {\n const availableWindow = buff.length - buffOffset\n\n if (availableWindow >= search.length) {\n const nativeSearchResult = buff.indexOf(search, buffOffset)\n\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n const revOffset = this._reverseOffset([blIndex, buffOffset])\n\n if (this._match(revOffset, search)) {\n return revOffset\n }\n\n buffOffset++\n }\n }\n\n buffOffset = 0\n }\n\n return -1\n}\n\nBufferList.prototype._match = function (offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n\n for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {\n if (this.get(offset + searchOffset) !== search[searchOffset]) {\n return false\n }\n }\n return true\n}\n\n;(function () {\n const methods = {\n readDoubleBE: 8,\n readDoubleLE: 8,\n readFloatBE: 4,\n readFloatLE: 4,\n readInt32BE: 4,\n readInt32LE: 4,\n readUInt32BE: 4,\n readUInt32LE: 4,\n readInt16BE: 2,\n readInt16LE: 2,\n readUInt16BE: 2,\n readUInt16LE: 2,\n readInt8: 1,\n readUInt8: 1,\n readIntBE: null,\n readIntLE: null,\n readUIntBE: null,\n readUIntLE: null\n }\n\n for (const m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n } else {\n BufferList.prototype[m] = function (offset = 0) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n// Used internally by the class and also as an indicator of this object being\n// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser\n// environment because there could be multiple different copies of the\n// BufferList class and some `BufferList`s might be `BufferList`s.\nBufferList.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferList || BufferList.isBufferList(b)\n}\n\nBufferList.isBufferList = function isBufferList (b) {\n return b != null && b[symbol]\n}\n\nmodule.exports = BufferList\n","'use strict'\n\nconst DuplexStream = require('readable-stream').Duplex\nconst inherits = require('inherits')\nconst BufferList = require('./BufferList')\n\nfunction BufferListStream (callback) {\n if (!(this instanceof BufferListStream)) {\n return new BufferListStream(callback)\n }\n\n if (typeof callback === 'function') {\n this._callback = callback\n\n const piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n\n callback = null\n }\n\n BufferList._init.call(this, callback)\n DuplexStream.call(this)\n}\n\ninherits(BufferListStream, DuplexStream)\nObject.assign(BufferListStream.prototype, BufferList.prototype)\n\nBufferListStream.prototype._new = function _new (callback) {\n return new BufferListStream(callback)\n}\n\nBufferListStream.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback === 'function') {\n callback()\n }\n}\n\nBufferListStream.prototype._read = function _read (size) {\n if (!this.length) {\n return this.push(null)\n }\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\nBufferListStream.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\nBufferListStream.prototype._destroy = function _destroy (err, cb) {\n this._bufs.length = 0\n this.length = 0\n cb(err)\n}\n\nBufferListStream.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)\n}\n\nBufferListStream.isBufferList = BufferList.isBufferList\n\nmodule.exports = BufferListStream\nmodule.exports.BufferListStream = BufferListStream\nmodule.exports.BufferList = BufferList\n","var util = require('util')\nvar bl = require('bl')\nvar headers = require('./headers')\n\nvar Writable = require('readable-stream').Writable\nvar PassThrough = require('readable-stream').PassThrough\n\nvar noop = function () {}\n\nvar overflow = function (size) {\n size &= 511\n return size && 512 - size\n}\n\nvar emptyStream = function (self, offset) {\n var s = new Source(self, offset)\n s.end()\n return s\n}\n\nvar mixinPax = function (header, pax) {\n if (pax.path) header.name = pax.path\n if (pax.linkpath) header.linkname = pax.linkpath\n if (pax.size) header.size = parseInt(pax.size, 10)\n header.pax = pax\n return header\n}\n\nvar Source = function (self, offset) {\n this._parent = self\n this.offset = offset\n PassThrough.call(this, { autoDestroy: false })\n}\n\nutil.inherits(Source, PassThrough)\n\nSource.prototype.destroy = function (err) {\n this._parent.destroy(err)\n}\n\nvar Extract = function (opts) {\n if (!(this instanceof Extract)) return new Extract(opts)\n Writable.call(this, opts)\n\n opts = opts || {}\n\n this._offset = 0\n this._buffer = bl()\n this._missing = 0\n this._partial = false\n this._onparse = noop\n this._header = null\n this._stream = null\n this._overflow = null\n this._cb = null\n this._locked = false\n this._destroyed = false\n this._pax = null\n this._paxGlobal = null\n this._gnuLongPath = null\n this._gnuLongLinkPath = null\n\n var self = this\n var b = self._buffer\n\n var oncontinue = function () {\n self._continue()\n }\n\n var onunlock = function (err) {\n self._locked = false\n if (err) return self.destroy(err)\n if (!self._stream) oncontinue()\n }\n\n var onstreamend = function () {\n self._stream = null\n var drain = overflow(self._header.size)\n if (drain) self._parse(drain, ondrain)\n else self._parse(512, onheader)\n if (!self._locked) oncontinue()\n }\n\n var ondrain = function () {\n self._buffer.consume(overflow(self._header.size))\n self._parse(512, onheader)\n oncontinue()\n }\n\n var onpaxglobalheader = function () {\n var size = self._header.size\n self._paxGlobal = headers.decodePax(b.slice(0, size))\n b.consume(size)\n onstreamend()\n }\n\n var onpaxheader = function () {\n var size = self._header.size\n self._pax = headers.decodePax(b.slice(0, size))\n if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulongpath = function () {\n var size = self._header.size\n this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulonglinkpath = function () {\n var size = self._header.size\n this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var onheader = function () {\n var offset = self._offset\n var header\n try {\n header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat)\n } catch (err) {\n self.emit('error', err)\n }\n b.consume(512)\n\n if (!header) {\n self._parse(512, onheader)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-path') {\n self._parse(header.size, ongnulongpath)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-link-path') {\n self._parse(header.size, ongnulonglinkpath)\n oncontinue()\n return\n }\n if (header.type === 'pax-global-header') {\n self._parse(header.size, onpaxglobalheader)\n oncontinue()\n return\n }\n if (header.type === 'pax-header') {\n self._parse(header.size, onpaxheader)\n oncontinue()\n return\n }\n\n if (self._gnuLongPath) {\n header.name = self._gnuLongPath\n self._gnuLongPath = null\n }\n\n if (self._gnuLongLinkPath) {\n header.linkname = self._gnuLongLinkPath\n self._gnuLongLinkPath = null\n }\n\n if (self._pax) {\n self._header = header = mixinPax(header, self._pax)\n self._pax = null\n }\n\n self._locked = true\n\n if (!header.size || header.type === 'directory') {\n self._parse(512, onheader)\n self.emit('entry', header, emptyStream(self, offset), onunlock)\n return\n }\n\n self._stream = new Source(self, offset)\n\n self.emit('entry', header, self._stream, onunlock)\n self._parse(header.size, onstreamend)\n oncontinue()\n }\n\n this._onheader = onheader\n this._parse(512, onheader)\n}\n\nutil.inherits(Extract, Writable)\n\nExtract.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream) this._stream.emit('close')\n}\n\nExtract.prototype._parse = function (size, onparse) {\n if (this._destroyed) return\n this._offset += size\n this._missing = size\n if (onparse === this._onheader) this._partial = false\n this._onparse = onparse\n}\n\nExtract.prototype._continue = function () {\n if (this._destroyed) return\n var cb = this._cb\n this._cb = noop\n if (this._overflow) this._write(this._overflow, undefined, cb)\n else cb()\n}\n\nExtract.prototype._write = function (data, enc, cb) {\n if (this._destroyed) return\n\n var s = this._stream\n var b = this._buffer\n var missing = this._missing\n if (data.length) this._partial = true\n\n // we do not reach end-of-chunk now. just forward it\n\n if (data.length < missing) {\n this._missing -= data.length\n this._overflow = null\n if (s) return s.write(data, cb)\n b.append(data)\n return cb()\n }\n\n // end-of-chunk. the parser should call cb.\n\n this._cb = cb\n this._missing = 0\n\n var overflow = null\n if (data.length > missing) {\n overflow = data.slice(missing)\n data = data.slice(0, missing)\n }\n\n if (s) s.end(data)\n else b.append(data)\n\n this._overflow = overflow\n this._onparse()\n}\n\nExtract.prototype._final = function (cb) {\n if (this._partial) return this.destroy(new Error('Unexpected end of data'))\n cb()\n}\n\nmodule.exports = Extract\n","var alloc = Buffer.alloc\n\nvar ZEROS = '0000000000000000000'\nvar SEVENS = '7777777777777777777'\nvar ZERO_OFFSET = '0'.charCodeAt(0)\nvar USTAR_MAGIC = Buffer.from('ustar\\x00', 'binary')\nvar USTAR_VER = Buffer.from('00', 'binary')\nvar GNU_MAGIC = Buffer.from('ustar\\x20', 'binary')\nvar GNU_VER = Buffer.from('\\x20\\x00', 'binary')\nvar MASK = parseInt('7777', 8)\nvar MAGIC_OFFSET = 257\nvar VERSION_OFFSET = 263\n\nvar clamp = function (index, len, defaultValue) {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nvar toType = function (flag) {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n }\n\n return null\n}\n\nvar toTypeflag = function (flag) {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n }\n\n return 0\n}\n\nvar indexOf = function (block, num, offset, end) {\n for (; offset < end; offset++) {\n if (block[offset] === num) return offset\n }\n return end\n}\n\nvar cksum = function (block) {\n var sum = 8 * 32\n for (var i = 0; i < 148; i++) sum += block[i]\n for (var j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nvar encodeOct = function (val, n) {\n val = val.toString(8)\n if (val.length > n) return SEVENS.slice(0, n) + ' '\n else return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n var positive\n if (buf[0] === 0x80) positive = true\n else if (buf[0] === 0xFF) positive = false\n else return null\n\n // build up a base-256 tuple from the least sig to the highest\n var tuple = []\n for (var i = buf.length - 1; i > 0; i--) {\n var byte = buf[i]\n if (positive) tuple.push(byte)\n else tuple.push(0xFF - byte)\n }\n\n var sum = 0\n var l = tuple.length\n for (i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nvar decodeOct = function (val, offset, length) {\n val = val.slice(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if (val[offset] & 0x80) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val[offset] === 32) offset++\n var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n while (offset < end && val[offset] === 0) offset++\n if (end === offset) return 0\n return parseInt(val.slice(offset, end).toString(), 8)\n }\n}\n\nvar decodeStr = function (val, offset, length, encoding) {\n return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding)\n}\n\nvar addLength = function (str) {\n var len = Buffer.byteLength(str)\n var digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n if (len + digits >= Math.pow(10, digits)) digits++\n\n return (len + digits) + str\n}\n\nexports.decodeLongPath = function (buf, encoding) {\n return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function (opts) { // TODO: encode more stuff in pax\n var result = ''\n if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n var pax = opts.pax\n if (pax) {\n for (var key in pax) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n return Buffer.from(result)\n}\n\nexports.decodePax = function (buf) {\n var result = {}\n\n while (buf.length) {\n var i = 0\n while (i < buf.length && buf[i] !== 32) i++\n var len = parseInt(buf.slice(0, i).toString(), 10)\n if (!len) return result\n\n var b = buf.slice(i + 1, len - 1).toString()\n var keyIndex = b.indexOf('=')\n if (keyIndex === -1) return result\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n buf = buf.slice(len)\n }\n\n return result\n}\n\nexports.encode = function (opts) {\n var buf = alloc(512)\n var name = opts.name\n var prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n if (Buffer.byteLength(name) !== name.length) return null // utf-8\n\n while (Buffer.byteLength(name) > 100) {\n var i = name.indexOf('/')\n if (i === -1) return null\n prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null\n if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null\n\n buf.write(name)\n buf.write(encodeOct(opts.mode & MASK, 6), 100)\n buf.write(encodeOct(opts.uid, 6), 108)\n buf.write(encodeOct(opts.gid, 6), 116)\n buf.write(encodeOct(opts.size, 11), 124)\n buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname) buf.write(opts.linkname, 157)\n\n USTAR_MAGIC.copy(buf, MAGIC_OFFSET)\n USTAR_VER.copy(buf, VERSION_OFFSET)\n if (opts.uname) buf.write(opts.uname, 265)\n if (opts.gname) buf.write(opts.gname, 297)\n buf.write(encodeOct(opts.devmajor || 0, 6), 329)\n buf.write(encodeOct(opts.devminor || 0, 6), 337)\n\n if (prefix) buf.write(prefix, 345)\n\n buf.write(encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n\nexports.decode = function (buf, filenameEncoding, allowUnknownFormat) {\n var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n var name = decodeStr(buf, 0, 100, filenameEncoding)\n var mode = decodeOct(buf, 100, 8)\n var uid = decodeOct(buf, 108, 8)\n var gid = decodeOct(buf, 116, 8)\n var size = decodeOct(buf, 124, 12)\n var mtime = decodeOct(buf, 136, 12)\n var type = toType(typeflag)\n var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n var uname = decodeStr(buf, 265, 32)\n var gname = decodeStr(buf, 297, 32)\n var devmajor = decodeOct(buf, 329, 8)\n var devminor = decodeOct(buf, 337, 8)\n\n var c = cksum(buf)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) return null\n\n // valid checksum\n if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 &&\n GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n if (!allowUnknownFormat) {\n throw new Error('Invalid tar header: unknown format.')\n }\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * mtime),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor\n }\n}\n","exports.extract = require('./extract')\nexports.pack = require('./pack')\n","var constants = require('fs-constants')\nvar eos = require('end-of-stream')\nvar inherits = require('inherits')\nvar alloc = Buffer.alloc\n\nvar Readable = require('readable-stream').Readable\nvar Writable = require('readable-stream').Writable\nvar StringDecoder = require('string_decoder').StringDecoder\n\nvar headers = require('./headers')\n\nvar DMODE = parseInt('755', 8)\nvar FMODE = parseInt('644', 8)\n\nvar END_OF_TAR = alloc(1024)\n\nvar noop = function () {}\n\nvar overflow = function (self, size) {\n size &= 511\n if (size) self.push(END_OF_TAR.slice(0, 512 - size))\n}\n\nfunction modeToType (mode) {\n switch (mode & constants.S_IFMT) {\n case constants.S_IFBLK: return 'block-device'\n case constants.S_IFCHR: return 'character-device'\n case constants.S_IFDIR: return 'directory'\n case constants.S_IFIFO: return 'fifo'\n case constants.S_IFLNK: return 'symlink'\n }\n\n return 'file'\n}\n\nvar Sink = function (to) {\n Writable.call(this)\n this.written = 0\n this._to = to\n this._destroyed = false\n}\n\ninherits(Sink, Writable)\n\nSink.prototype._write = function (data, enc, cb) {\n this.written += data.length\n if (this._to.push(data)) return cb()\n this._to._drain = cb\n}\n\nSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar LinkSink = function () {\n Writable.call(this)\n this.linkname = ''\n this._decoder = new StringDecoder('utf-8')\n this._destroyed = false\n}\n\ninherits(LinkSink, Writable)\n\nLinkSink.prototype._write = function (data, enc, cb) {\n this.linkname += this._decoder.write(data)\n cb()\n}\n\nLinkSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Void = function () {\n Writable.call(this)\n this._destroyed = false\n}\n\ninherits(Void, Writable)\n\nVoid.prototype._write = function (data, enc, cb) {\n cb(new Error('No body allowed for this entry'))\n}\n\nVoid.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Pack = function (opts) {\n if (!(this instanceof Pack)) return new Pack(opts)\n Readable.call(this, opts)\n\n this._drain = noop\n this._finalized = false\n this._finalizing = false\n this._destroyed = false\n this._stream = null\n}\n\ninherits(Pack, Readable)\n\nPack.prototype.entry = function (header, buffer, callback) {\n if (this._stream) throw new Error('already piping an entry')\n if (this._finalized || this._destroyed) return\n\n if (typeof buffer === 'function') {\n callback = buffer\n buffer = null\n }\n\n if (!callback) callback = noop\n\n var self = this\n\n if (!header.size || header.type === 'symlink') header.size = 0\n if (!header.type) header.type = modeToType(header.mode)\n if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n if (!header.uid) header.uid = 0\n if (!header.gid) header.gid = 0\n if (!header.mtime) header.mtime = new Date()\n\n if (typeof buffer === 'string') buffer = Buffer.from(buffer)\n if (Buffer.isBuffer(buffer)) {\n header.size = buffer.length\n this._encode(header)\n var ok = this.push(buffer)\n overflow(self, header.size)\n if (ok) process.nextTick(callback)\n else this._drain = callback\n return new Void()\n }\n\n if (header.type === 'symlink' && !header.linkname) {\n var linkSink = new LinkSink()\n eos(linkSink, function (err) {\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n header.linkname = linkSink.linkname\n self._encode(header)\n callback()\n })\n\n return linkSink\n }\n\n this._encode(header)\n\n if (header.type !== 'file' && header.type !== 'contiguous-file') {\n process.nextTick(callback)\n return new Void()\n }\n\n var sink = new Sink(this)\n\n this._stream = sink\n\n eos(sink, function (err) {\n self._stream = null\n\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n if (sink.written !== header.size) { // corrupting tar\n self.destroy()\n return callback(new Error('size mismatch'))\n }\n\n overflow(self, header.size)\n if (self._finalizing) self.finalize()\n callback()\n })\n\n return sink\n}\n\nPack.prototype.finalize = function () {\n if (this._stream) {\n this._finalizing = true\n return\n }\n\n if (this._finalized) return\n this._finalized = true\n this.push(END_OF_TAR)\n this.push(null)\n}\n\nPack.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream && this._stream.destroy) this._stream.destroy()\n}\n\nPack.prototype._encode = function (header) {\n if (!header.pax) {\n var buf = headers.encode(header)\n if (buf) {\n this.push(buf)\n return\n }\n }\n this._encodePax(header)\n}\n\nPack.prototype._encodePax = function (header) {\n var paxHeader = headers.encodePax({\n name: header.name,\n linkname: header.linkname,\n pax: header.pax\n })\n\n var newHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.length,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname && 'PaxHeader',\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n this.push(headers.encode(newHeader))\n this.push(paxHeader)\n overflow(this, paxHeader.length)\n\n newHeader.size = header.size\n newHeader.type = header.type\n this.push(headers.encode(newHeader))\n}\n\nPack.prototype._read = function (n) {\n var drain = this._drain\n this._drain = noop\n drain()\n}\n\nmodule.exports = Pack\n","module.exports = require('./lib/tunnel');\n","'use strict';\n\nvar net = require('net');\nvar tls = require('tls');\nvar http = require('http');\nvar https = require('https');\nvar events = require('events');\nvar assert = require('assert');\nvar util = require('util');\n\n\nexports.httpOverHttp = httpOverHttp;\nexports.httpsOverHttp = httpsOverHttp;\nexports.httpOverHttps = httpOverHttps;\nexports.httpsOverHttps = httpsOverHttps;\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n return agent;\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n return agent;\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this;\n self.options = options || {};\n self.proxyOptions = self.options.proxy || {};\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;\n self.requests = [];\n self.sockets = [];\n\n self.on('free', function onFree(socket, host, port, localAddress) {\n var options = toOptions(host, port, localAddress);\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i];\n if (pending.host === options.host && pending.port === options.port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1);\n pending.request.onSocket(socket);\n return;\n }\n }\n socket.destroy();\n self.removeSocket(socket);\n });\n}\nutil.inherits(TunnelingAgent, events.EventEmitter);\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {\n var self = this;\n var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push(options);\n return;\n }\n\n // If we are under maxSockets create a new one.\n self.createSocket(options, function(socket) {\n socket.on('free', onFree);\n socket.on('close', onCloseOrRemove);\n socket.on('agentRemove', onCloseOrRemove);\n req.onSocket(socket);\n\n function onFree() {\n self.emit('free', socket, options);\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket);\n socket.removeListener('free', onFree);\n socket.removeListener('close', onCloseOrRemove);\n socket.removeListener('agentRemove', onCloseOrRemove);\n }\n });\n};\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this;\n var placeholder = {};\n self.sockets.push(placeholder);\n\n var connectOptions = mergeOptions({}, self.proxyOptions, {\n method: 'CONNECT',\n path: options.host + ':' + options.port,\n agent: false,\n headers: {\n host: options.host + ':' + options.port\n }\n });\n if (options.localAddress) {\n connectOptions.localAddress = options.localAddress;\n }\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {};\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n new Buffer(connectOptions.proxyAuth).toString('base64');\n }\n\n debug('making CONNECT request');\n var connectReq = self.request(connectOptions);\n connectReq.useChunkedEncodingByDefault = false; // for v0.6\n connectReq.once('response', onResponse); // for v0.6\n connectReq.once('upgrade', onUpgrade); // for v0.6\n connectReq.once('connect', onConnect); // for v0.7 or later\n connectReq.once('error', onError);\n connectReq.end();\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true;\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head);\n });\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners();\n socket.removeAllListeners();\n\n if (res.statusCode !== 200) {\n debug('tunneling socket could not be established, statusCode=%d',\n res.statusCode);\n socket.destroy();\n var error = new Error('tunneling socket could not be established, ' +\n 'statusCode=' + res.statusCode);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n if (head.length > 0) {\n debug('got illegal response body from proxy');\n socket.destroy();\n var error = new Error('got illegal response body from proxy');\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n debug('tunneling connection has established');\n self.sockets[self.sockets.indexOf(placeholder)] = socket;\n return cb(socket);\n }\n\n function onError(cause) {\n connectReq.removeAllListeners();\n\n debug('tunneling socket could not be established, cause=%s\\n',\n cause.message, cause.stack);\n var error = new Error('tunneling socket could not be established, ' +\n 'cause=' + cause.message);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n }\n};\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) {\n return;\n }\n this.sockets.splice(pos, 1);\n\n var pending = this.requests.shift();\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createSocket(pending, function(socket) {\n pending.request.onSocket(socket);\n });\n }\n};\n\nfunction createSecureSocket(options, cb) {\n var self = this;\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n var hostHeader = options.request.getHeader('host');\n var tlsOptions = mergeOptions({}, self.options, {\n socket: socket,\n servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host\n });\n\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, tlsOptions);\n self.sockets[self.sockets.indexOf(socket)] = secureSocket;\n cb(secureSocket);\n });\n}\n\n\nfunction toOptions(host, port, localAddress) {\n if (typeof host === 'string') { // since v0.10\n return {\n host: host,\n port: port,\n localAddress: localAddress\n };\n }\n return host; // for v0.11 or later\n}\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i];\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides);\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j];\n if (overrides[k] !== undefined) {\n target[k] = overrides[k];\n }\n }\n }\n }\n return target;\n}\n\n\nvar debug;\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments);\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0];\n } else {\n args.unshift('TUNNEL:');\n }\n console.error.apply(console, args);\n }\n} else {\n debug = function() {};\n}\nexports.debug = debug; // for test\n","(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _0 = new Uint8Array(16);\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_16(x, xi, y, yi) {\n return vn(x,xi,y,yi,16);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction core_salsa20(o, p, k, c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n x0 = x0 + j0 | 0;\n x1 = x1 + j1 | 0;\n x2 = x2 + j2 | 0;\n x3 = x3 + j3 | 0;\n x4 = x4 + j4 | 0;\n x5 = x5 + j5 | 0;\n x6 = x6 + j6 | 0;\n x7 = x7 + j7 | 0;\n x8 = x8 + j8 | 0;\n x9 = x9 + j9 | 0;\n x10 = x10 + j10 | 0;\n x11 = x11 + j11 | 0;\n x12 = x12 + j12 | 0;\n x13 = x13 + j13 | 0;\n x14 = x14 + j14 | 0;\n x15 = x15 + j15 | 0;\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x1 >>> 0 & 0xff;\n o[ 5] = x1 >>> 8 & 0xff;\n o[ 6] = x1 >>> 16 & 0xff;\n o[ 7] = x1 >>> 24 & 0xff;\n\n o[ 8] = x2 >>> 0 & 0xff;\n o[ 9] = x2 >>> 8 & 0xff;\n o[10] = x2 >>> 16 & 0xff;\n o[11] = x2 >>> 24 & 0xff;\n\n o[12] = x3 >>> 0 & 0xff;\n o[13] = x3 >>> 8 & 0xff;\n o[14] = x3 >>> 16 & 0xff;\n o[15] = x3 >>> 24 & 0xff;\n\n o[16] = x4 >>> 0 & 0xff;\n o[17] = x4 >>> 8 & 0xff;\n o[18] = x4 >>> 16 & 0xff;\n o[19] = x4 >>> 24 & 0xff;\n\n o[20] = x5 >>> 0 & 0xff;\n o[21] = x5 >>> 8 & 0xff;\n o[22] = x5 >>> 16 & 0xff;\n o[23] = x5 >>> 24 & 0xff;\n\n o[24] = x6 >>> 0 & 0xff;\n o[25] = x6 >>> 8 & 0xff;\n o[26] = x6 >>> 16 & 0xff;\n o[27] = x6 >>> 24 & 0xff;\n\n o[28] = x7 >>> 0 & 0xff;\n o[29] = x7 >>> 8 & 0xff;\n o[30] = x7 >>> 16 & 0xff;\n o[31] = x7 >>> 24 & 0xff;\n\n o[32] = x8 >>> 0 & 0xff;\n o[33] = x8 >>> 8 & 0xff;\n o[34] = x8 >>> 16 & 0xff;\n o[35] = x8 >>> 24 & 0xff;\n\n o[36] = x9 >>> 0 & 0xff;\n o[37] = x9 >>> 8 & 0xff;\n o[38] = x9 >>> 16 & 0xff;\n o[39] = x9 >>> 24 & 0xff;\n\n o[40] = x10 >>> 0 & 0xff;\n o[41] = x10 >>> 8 & 0xff;\n o[42] = x10 >>> 16 & 0xff;\n o[43] = x10 >>> 24 & 0xff;\n\n o[44] = x11 >>> 0 & 0xff;\n o[45] = x11 >>> 8 & 0xff;\n o[46] = x11 >>> 16 & 0xff;\n o[47] = x11 >>> 24 & 0xff;\n\n o[48] = x12 >>> 0 & 0xff;\n o[49] = x12 >>> 8 & 0xff;\n o[50] = x12 >>> 16 & 0xff;\n o[51] = x12 >>> 24 & 0xff;\n\n o[52] = x13 >>> 0 & 0xff;\n o[53] = x13 >>> 8 & 0xff;\n o[54] = x13 >>> 16 & 0xff;\n o[55] = x13 >>> 24 & 0xff;\n\n o[56] = x14 >>> 0 & 0xff;\n o[57] = x14 >>> 8 & 0xff;\n o[58] = x14 >>> 16 & 0xff;\n o[59] = x14 >>> 24 & 0xff;\n\n o[60] = x15 >>> 0 & 0xff;\n o[61] = x15 >>> 8 & 0xff;\n o[62] = x15 >>> 16 & 0xff;\n o[63] = x15 >>> 24 & 0xff;\n}\n\nfunction core_hsalsa20(o,p,k,c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x5 >>> 0 & 0xff;\n o[ 5] = x5 >>> 8 & 0xff;\n o[ 6] = x5 >>> 16 & 0xff;\n o[ 7] = x5 >>> 24 & 0xff;\n\n o[ 8] = x10 >>> 0 & 0xff;\n o[ 9] = x10 >>> 8 & 0xff;\n o[10] = x10 >>> 16 & 0xff;\n o[11] = x10 >>> 24 & 0xff;\n\n o[12] = x15 >>> 0 & 0xff;\n o[13] = x15 >>> 8 & 0xff;\n o[14] = x15 >>> 16 & 0xff;\n o[15] = x15 >>> 24 & 0xff;\n\n o[16] = x6 >>> 0 & 0xff;\n o[17] = x6 >>> 8 & 0xff;\n o[18] = x6 >>> 16 & 0xff;\n o[19] = x6 >>> 24 & 0xff;\n\n o[20] = x7 >>> 0 & 0xff;\n o[21] = x7 >>> 8 & 0xff;\n o[22] = x7 >>> 16 & 0xff;\n o[23] = x7 >>> 24 & 0xff;\n\n o[24] = x8 >>> 0 & 0xff;\n o[25] = x8 >>> 8 & 0xff;\n o[26] = x8 >>> 16 & 0xff;\n o[27] = x8 >>> 24 & 0xff;\n\n o[28] = x9 >>> 0 & 0xff;\n o[29] = x9 >>> 8 & 0xff;\n o[30] = x9 >>> 16 & 0xff;\n o[31] = x9 >>> 24 & 0xff;\n}\n\nfunction crypto_core_salsa20(out,inp,k,c) {\n core_salsa20(out,inp,k,c);\n}\n\nfunction crypto_core_hsalsa20(out,inp,k,c) {\n core_hsalsa20(out,inp,k,c);\n}\n\nvar sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);\n // \"expand 32-byte k\"\n\nfunction crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n mpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n }\n return 0;\n}\n\nfunction crypto_stream_salsa20(c,cpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = x[i];\n }\n return 0;\n}\n\nfunction crypto_stream(c,cpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20(c,cpos,d,sn,s);\n}\n\nfunction crypto_stream_xor(c,cpos,m,mpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);\n}\n\n/*\n* Port of Andrew Moon's Poly1305-donna-16. Public domain.\n* https://github.com/floodyberry/poly1305-donna\n*/\n\nvar poly1305 = function(key) {\n this.buffer = new Uint8Array(16);\n this.r = new Uint16Array(10);\n this.h = new Uint16Array(10);\n this.pad = new Uint16Array(8);\n this.leftover = 0;\n this.fin = 0;\n\n var t0, t1, t2, t3, t4, t5, t6, t7;\n\n t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;\n t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = ((t4 >>> 1)) & 0x1ffe;\n t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = ((t7 >>> 5)) & 0x007f;\n\n this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;\n this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;\n this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;\n this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;\n this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;\n this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;\n this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;\n this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;\n};\n\npoly1305.prototype.blocks = function(m, mpos, bytes) {\n var hibit = this.fin ? 0 : (1 << 11);\n var t0, t1, t2, t3, t4, t5, t6, t7, c;\n var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;\n\n var h0 = this.h[0],\n h1 = this.h[1],\n h2 = this.h[2],\n h3 = this.h[3],\n h4 = this.h[4],\n h5 = this.h[5],\n h6 = this.h[6],\n h7 = this.h[7],\n h8 = this.h[8],\n h9 = this.h[9];\n\n var r0 = this.r[0],\n r1 = this.r[1],\n r2 = this.r[2],\n r3 = this.r[3],\n r4 = this.r[4],\n r5 = this.r[5],\n r6 = this.r[6],\n r7 = this.r[7],\n r8 = this.r[8],\n r9 = this.r[9];\n\n while (bytes >= 16) {\n t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;\n t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n c = 0;\n\n d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this.h[0] = h0;\n this.h[1] = h1;\n this.h[2] = h2;\n this.h[3] = h3;\n this.h[4] = h4;\n this.h[5] = h5;\n this.h[6] = h6;\n this.h[7] = h7;\n this.h[8] = h8;\n this.h[9] = h9;\n};\n\npoly1305.prototype.finish = function(mac, macpos) {\n var g = new Uint16Array(10);\n var c, mask, f, i;\n\n if (this.leftover) {\n i = this.leftover;\n this.buffer[i++] = 1;\n for (; i < 16; i++) this.buffer[i] = 0;\n this.fin = 1;\n this.blocks(this.buffer, 0, 16);\n }\n\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this.h[i] += c;\n c = this.h[i] >>> 13;\n this.h[i] &= 0x1fff;\n }\n this.h[0] += (c * 5);\n c = this.h[0] >>> 13;\n this.h[0] &= 0x1fff;\n this.h[1] += c;\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n this.h[2] += c;\n\n g[0] = this.h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this.h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];\n\n this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;\n this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;\n this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;\n this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;\n this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;\n this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;\n this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;\n this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;\n\n f = this.h[0] + this.pad[0];\n this.h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;\n this.h[i] = f & 0xffff;\n }\n\n mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;\n mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;\n mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;\n mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;\n mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;\n mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;\n mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;\n mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;\n mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;\n mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;\n mac[macpos+10] = (this.h[5] >>> 0) & 0xff;\n mac[macpos+11] = (this.h[5] >>> 8) & 0xff;\n mac[macpos+12] = (this.h[6] >>> 0) & 0xff;\n mac[macpos+13] = (this.h[6] >>> 8) & 0xff;\n mac[macpos+14] = (this.h[7] >>> 0) & 0xff;\n mac[macpos+15] = (this.h[7] >>> 8) & 0xff;\n};\n\npoly1305.prototype.update = function(m, mpos, bytes) {\n var i, want;\n\n if (this.leftover) {\n want = (16 - this.leftover);\n if (want > bytes)\n want = bytes;\n for (i = 0; i < want; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n bytes -= want;\n mpos += want;\n this.leftover += want;\n if (this.leftover < 16)\n return;\n this.blocks(this.buffer, 0, 16);\n this.leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this.blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (i = 0; i < bytes; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n this.leftover += bytes;\n }\n};\n\nfunction crypto_onetimeauth(out, outpos, m, mpos, n, k) {\n var s = new poly1305(k);\n s.update(m, mpos, n);\n s.finish(out, outpos);\n return 0;\n}\n\nfunction crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {\n var x = new Uint8Array(16);\n crypto_onetimeauth(x,0,m,mpos,n,k);\n return crypto_verify_16(h,hpos,x,0);\n}\n\nfunction crypto_secretbox(c,m,d,n,k) {\n var i;\n if (d < 32) return -1;\n crypto_stream_xor(c,0,m,0,d,n,k);\n crypto_onetimeauth(c, 16, c, 32, d - 32, c);\n for (i = 0; i < 16; i++) c[i] = 0;\n return 0;\n}\n\nfunction crypto_secretbox_open(m,c,d,n,k) {\n var i;\n var x = new Uint8Array(32);\n if (d < 32) return -1;\n crypto_stream(x,0,32,n,k);\n if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;\n crypto_stream_xor(m,0,c,0,d,n,k);\n for (i = 0; i < 32; i++) m[i] = 0;\n return 0;\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction crypto_box_beforenm(k, y, x) {\n var s = new Uint8Array(32);\n crypto_scalarmult(s, x, y);\n return crypto_core_hsalsa20(k, _0, s, sigma);\n}\n\nvar crypto_box_afternm = crypto_secretbox;\nvar crypto_box_open_afternm = crypto_secretbox_open;\n\nfunction crypto_box(c, m, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_afternm(c, m, d, n, k);\n}\n\nfunction crypto_box_open(m, c, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_open_afternm(m, c, d, n, k);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n mlen = n;\n return mlen;\n}\n\nvar crypto_secretbox_KEYBYTES = 32,\n crypto_secretbox_NONCEBYTES = 24,\n crypto_secretbox_ZEROBYTES = 32,\n crypto_secretbox_BOXZEROBYTES = 16,\n crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_box_BEFORENMBYTES = 32,\n crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,\n crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,\n crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32,\n crypto_hash_BYTES = 64;\n\nnacl.lowlevel = {\n crypto_core_hsalsa20: crypto_core_hsalsa20,\n crypto_stream_xor: crypto_stream_xor,\n crypto_stream: crypto_stream,\n crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,\n crypto_stream_salsa20: crypto_stream_salsa20,\n crypto_onetimeauth: crypto_onetimeauth,\n crypto_onetimeauth_verify: crypto_onetimeauth_verify,\n crypto_verify_16: crypto_verify_16,\n crypto_verify_32: crypto_verify_32,\n crypto_secretbox: crypto_secretbox,\n crypto_secretbox_open: crypto_secretbox_open,\n crypto_scalarmult: crypto_scalarmult,\n crypto_scalarmult_base: crypto_scalarmult_base,\n crypto_box_beforenm: crypto_box_beforenm,\n crypto_box_afternm: crypto_box_afternm,\n crypto_box: crypto_box,\n crypto_box_open: crypto_box_open,\n crypto_box_keypair: crypto_box_keypair,\n crypto_hash: crypto_hash,\n crypto_sign: crypto_sign,\n crypto_sign_keypair: crypto_sign_keypair,\n crypto_sign_open: crypto_sign_open,\n\n crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,\n crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,\n crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,\n crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,\n crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,\n crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,\n crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,\n crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,\n crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,\n crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,\n crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,\n crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,\n crypto_sign_BYTES: crypto_sign_BYTES,\n crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,\n crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,\n crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,\n crypto_hash_BYTES: crypto_hash_BYTES\n};\n\n/* High-level API */\n\nfunction checkLengths(k, n) {\n if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');\n if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');\n}\n\nfunction checkBoxLengths(pk, sk) {\n if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');\n if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');\n}\n\nfunction checkArrayTypes() {\n var t, i;\n for (i = 0; i < arguments.length; i++) {\n if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')\n throw new TypeError('unexpected type ' + t + ', use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\n// TODO: Completely remove this in v0.15.\nif (!nacl.util) {\n nacl.util = {};\n nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() {\n throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');\n };\n}\n\nnacl.randomBytes = function(n) {\n var b = new Uint8Array(n);\n randombytes(b, n);\n return b;\n};\n\nnacl.secretbox = function(msg, nonce, key) {\n checkArrayTypes(msg, nonce, key);\n checkLengths(key, nonce);\n var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);\n var c = new Uint8Array(m.length);\n for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];\n crypto_secretbox(c, m, m.length, nonce, key);\n return c.subarray(crypto_secretbox_BOXZEROBYTES);\n};\n\nnacl.secretbox.open = function(box, nonce, key) {\n checkArrayTypes(box, nonce, key);\n checkLengths(key, nonce);\n var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);\n var m = new Uint8Array(c.length);\n for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];\n if (c.length < 32) return false;\n if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false;\n return m.subarray(crypto_secretbox_ZEROBYTES);\n};\n\nnacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;\nnacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;\nnacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.scalarMult.base = function(n) {\n checkArrayTypes(n);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult_base(q, n);\n return q;\n};\n\nnacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;\nnacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;\n\nnacl.box = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox(msg, nonce, k);\n};\n\nnacl.box.before = function(publicKey, secretKey) {\n checkArrayTypes(publicKey, secretKey);\n checkBoxLengths(publicKey, secretKey);\n var k = new Uint8Array(crypto_box_BEFORENMBYTES);\n crypto_box_beforenm(k, publicKey, secretKey);\n return k;\n};\n\nnacl.box.after = nacl.secretbox;\n\nnacl.box.open = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox.open(msg, nonce, k);\n};\n\nnacl.box.open.after = nacl.secretbox.open;\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;\nnacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;\nnacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;\nnacl.box.nonceLength = crypto_box_NONCEBYTES;\nnacl.box.overheadLength = nacl.secretbox.overheadLength;\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.open = function(signedMsg, publicKey) {\n if (arguments.length !== 2)\n throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');\n checkArrayTypes(signedMsg, publicKey);\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var tmp = new Uint8Array(signedMsg.length);\n var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);\n if (mlen < 0) return null;\n var m = new Uint8Array(mlen);\n for (var i = 0; i < m.length; i++) m[i] = tmp[i];\n return m;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;\nnacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;\nnacl.sign.seedLength = crypto_sign_SEEDBYTES;\nnacl.sign.signatureLength = crypto_sign_BYTES;\n\nnacl.hash = function(msg) {\n checkArrayTypes(msg);\n var h = new Uint8Array(crypto_hash_BYTES);\n crypto_hash(h, msg, msg.length);\n return h;\n};\n\nnacl.hash.hashLength = crypto_hash_BYTES;\n\nnacl.verify = function(x, y) {\n checkArrayTypes(x, y);\n // Zero length arguments are considered not equal.\n if (x.length === 0 || y.length === 0) return false;\n if (x.length !== y.length) return false;\n return (vn(x, 0, y, 0, x.length) === 0) ? true : false;\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","'use strict'\n\nconst Client = require('./lib/client')\nconst Dispatcher = require('./lib/dispatcher')\nconst errors = require('./lib/core/errors')\nconst Pool = require('./lib/pool')\nconst BalancedPool = require('./lib/balanced-pool')\nconst Agent = require('./lib/agent')\nconst util = require('./lib/core/util')\nconst { InvalidArgumentError } = errors\nconst api = require('./lib/api')\nconst buildConnector = require('./lib/core/connect')\nconst MockClient = require('./lib/mock/mock-client')\nconst MockAgent = require('./lib/mock/mock-agent')\nconst MockPool = require('./lib/mock/mock-pool')\nconst mockErrors = require('./lib/mock/mock-errors')\nconst ProxyAgent = require('./lib/proxy-agent')\nconst RetryHandler = require('./lib/handler/RetryHandler')\nconst { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')\nconst DecoratorHandler = require('./lib/handler/DecoratorHandler')\nconst RedirectHandler = require('./lib/handler/RedirectHandler')\nconst createRedirectInterceptor = require('./lib/interceptor/redirectInterceptor')\n\nlet hasCrypto\ntry {\n require('crypto')\n hasCrypto = true\n} catch {\n hasCrypto = false\n}\n\nObject.assign(Dispatcher.prototype, api)\n\nmodule.exports.Dispatcher = Dispatcher\nmodule.exports.Client = Client\nmodule.exports.Pool = Pool\nmodule.exports.BalancedPool = BalancedPool\nmodule.exports.Agent = Agent\nmodule.exports.ProxyAgent = ProxyAgent\nmodule.exports.RetryHandler = RetryHandler\n\nmodule.exports.DecoratorHandler = DecoratorHandler\nmodule.exports.RedirectHandler = RedirectHandler\nmodule.exports.createRedirectInterceptor = createRedirectInterceptor\n\nmodule.exports.buildConnector = buildConnector\nmodule.exports.errors = errors\n\nfunction makeDispatcher (fn) {\n return (url, opts, handler) => {\n if (typeof opts === 'function') {\n handler = opts\n opts = null\n }\n\n if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {\n throw new InvalidArgumentError('invalid url')\n }\n\n if (opts != null && typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (opts && opts.path != null) {\n if (typeof opts.path !== 'string') {\n throw new InvalidArgumentError('invalid opts.path')\n }\n\n let path = opts.path\n if (!opts.path.startsWith('/')) {\n path = `/${path}`\n }\n\n url = new URL(util.parseOrigin(url).origin + path)\n } else {\n if (!opts) {\n opts = typeof url === 'object' ? url : {}\n }\n\n url = util.parseURL(url)\n }\n\n const { agent, dispatcher = getGlobalDispatcher() } = opts\n\n if (agent) {\n throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')\n }\n\n return fn.call(dispatcher, {\n ...opts,\n origin: url.origin,\n path: url.search ? `${url.pathname}${url.search}` : url.pathname,\n method: opts.method || (opts.body ? 'PUT' : 'GET')\n }, handler)\n }\n}\n\nmodule.exports.setGlobalDispatcher = setGlobalDispatcher\nmodule.exports.getGlobalDispatcher = getGlobalDispatcher\n\nif (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {\n let fetchImpl = null\n module.exports.fetch = async function fetch (resource) {\n if (!fetchImpl) {\n fetchImpl = require('./lib/fetch').fetch\n }\n\n try {\n return await fetchImpl(...arguments)\n } catch (err) {\n if (typeof err === 'object') {\n Error.captureStackTrace(err, this)\n }\n\n throw err\n }\n }\n module.exports.Headers = require('./lib/fetch/headers').Headers\n module.exports.Response = require('./lib/fetch/response').Response\n module.exports.Request = require('./lib/fetch/request').Request\n module.exports.FormData = require('./lib/fetch/formdata').FormData\n module.exports.File = require('./lib/fetch/file').File\n module.exports.FileReader = require('./lib/fileapi/filereader').FileReader\n\n const { setGlobalOrigin, getGlobalOrigin } = require('./lib/fetch/global')\n\n module.exports.setGlobalOrigin = setGlobalOrigin\n module.exports.getGlobalOrigin = getGlobalOrigin\n\n const { CacheStorage } = require('./lib/cache/cachestorage')\n const { kConstruct } = require('./lib/cache/symbols')\n\n // Cache & CacheStorage are tightly coupled with fetch. Even if it may run\n // in an older version of Node, it doesn't have any use without fetch.\n module.exports.caches = new CacheStorage(kConstruct)\n}\n\nif (util.nodeMajor >= 16) {\n const { deleteCookie, getCookies, getSetCookies, setCookie } = require('./lib/cookies')\n\n module.exports.deleteCookie = deleteCookie\n module.exports.getCookies = getCookies\n module.exports.getSetCookies = getSetCookies\n module.exports.setCookie = setCookie\n\n const { parseMIMEType, serializeAMimeType } = require('./lib/fetch/dataURL')\n\n module.exports.parseMIMEType = parseMIMEType\n module.exports.serializeAMimeType = serializeAMimeType\n}\n\nif (util.nodeMajor >= 18 && hasCrypto) {\n const { WebSocket } = require('./lib/websocket/websocket')\n\n module.exports.WebSocket = WebSocket\n}\n\nmodule.exports.request = makeDispatcher(api.request)\nmodule.exports.stream = makeDispatcher(api.stream)\nmodule.exports.pipeline = makeDispatcher(api.pipeline)\nmodule.exports.connect = makeDispatcher(api.connect)\nmodule.exports.upgrade = makeDispatcher(api.upgrade)\n\nmodule.exports.MockClient = MockClient\nmodule.exports.MockPool = MockPool\nmodule.exports.MockAgent = MockAgent\nmodule.exports.mockErrors = mockErrors\n","'use strict'\n\nconst { InvalidArgumentError } = require('./core/errors')\nconst { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('./core/symbols')\nconst DispatcherBase = require('./dispatcher-base')\nconst Pool = require('./pool')\nconst Client = require('./client')\nconst util = require('./core/util')\nconst createRedirectInterceptor = require('./interceptor/redirectInterceptor')\nconst { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')()\n\nconst kOnConnect = Symbol('onConnect')\nconst kOnDisconnect = Symbol('onDisconnect')\nconst kOnConnectionError = Symbol('onConnectionError')\nconst kMaxRedirections = Symbol('maxRedirections')\nconst kOnDrain = Symbol('onDrain')\nconst kFactory = Symbol('factory')\nconst kFinalizer = Symbol('finalizer')\nconst kOptions = Symbol('options')\n\nfunction defaultFactory (origin, opts) {\n return opts && opts.connections === 1\n ? new Client(origin, opts)\n : new Pool(origin, opts)\n}\n\nclass Agent extends DispatcherBase {\n constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {\n super()\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n if (connect && typeof connect !== 'function') {\n connect = { ...connect }\n }\n\n this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)\n ? options.interceptors.Agent\n : [createRedirectInterceptor({ maxRedirections })]\n\n this[kOptions] = { ...util.deepClone(options), connect }\n this[kOptions].interceptors = options.interceptors\n ? { ...options.interceptors }\n : undefined\n this[kMaxRedirections] = maxRedirections\n this[kFactory] = factory\n this[kClients] = new Map()\n this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {\n const ref = this[kClients].get(key)\n if (ref !== undefined && ref.deref() === undefined) {\n this[kClients].delete(key)\n }\n })\n\n const agent = this\n\n this[kOnDrain] = (origin, targets) => {\n agent.emit('drain', origin, [agent, ...targets])\n }\n\n this[kOnConnect] = (origin, targets) => {\n agent.emit('connect', origin, [agent, ...targets])\n }\n\n this[kOnDisconnect] = (origin, targets, err) => {\n agent.emit('disconnect', origin, [agent, ...targets], err)\n }\n\n this[kOnConnectionError] = (origin, targets, err) => {\n agent.emit('connectionError', origin, [agent, ...targets], err)\n }\n }\n\n get [kRunning] () {\n let ret = 0\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore next: gc is undeterministic */\n if (client) {\n ret += client[kRunning]\n }\n }\n return ret\n }\n\n [kDispatch] (opts, handler) {\n let key\n if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {\n key = String(opts.origin)\n } else {\n throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')\n }\n\n const ref = this[kClients].get(key)\n\n let dispatcher = ref ? ref.deref() : null\n if (!dispatcher) {\n dispatcher = this[kFactory](opts.origin, this[kOptions])\n .on('drain', this[kOnDrain])\n .on('connect', this[kOnConnect])\n .on('disconnect', this[kOnDisconnect])\n .on('connectionError', this[kOnConnectionError])\n\n this[kClients].set(key, new WeakRef(dispatcher))\n this[kFinalizer].register(dispatcher, key)\n }\n\n return dispatcher.dispatch(opts, handler)\n }\n\n async [kClose] () {\n const closePromises = []\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore else: gc is undeterministic */\n if (client) {\n closePromises.push(client.close())\n }\n }\n\n await Promise.all(closePromises)\n }\n\n async [kDestroy] (err) {\n const destroyPromises = []\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore else: gc is undeterministic */\n if (client) {\n destroyPromises.push(client.destroy(err))\n }\n }\n\n await Promise.all(destroyPromises)\n }\n}\n\nmodule.exports = Agent\n","const { addAbortListener } = require('../core/util')\nconst { RequestAbortedError } = require('../core/errors')\n\nconst kListener = Symbol('kListener')\nconst kSignal = Symbol('kSignal')\n\nfunction abort (self) {\n if (self.abort) {\n self.abort()\n } else {\n self.onError(new RequestAbortedError())\n }\n}\n\nfunction addSignal (self, signal) {\n self[kSignal] = null\n self[kListener] = null\n\n if (!signal) {\n return\n }\n\n if (signal.aborted) {\n abort(self)\n return\n }\n\n self[kSignal] = signal\n self[kListener] = () => {\n abort(self)\n }\n\n addAbortListener(self[kSignal], self[kListener])\n}\n\nfunction removeSignal (self) {\n if (!self[kSignal]) {\n return\n }\n\n if ('removeEventListener' in self[kSignal]) {\n self[kSignal].removeEventListener('abort', self[kListener])\n } else {\n self[kSignal].removeListener('abort', self[kListener])\n }\n\n self[kSignal] = null\n self[kListener] = null\n}\n\nmodule.exports = {\n addSignal,\n removeSignal\n}\n","'use strict'\n\nconst { AsyncResource } = require('async_hooks')\nconst { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors')\nconst util = require('../core/util')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass ConnectHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n const { signal, opaque, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n super('UNDICI_CONNECT')\n\n this.opaque = opaque || null\n this.responseHeaders = responseHeaders || null\n this.callback = callback\n this.abort = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders () {\n throw new SocketError('bad connect', null)\n }\n\n onUpgrade (statusCode, rawHeaders, socket) {\n const { callback, opaque, context } = this\n\n removeSignal(this)\n\n this.callback = null\n\n let headers = rawHeaders\n // Indicates is an HTTP2Session\n if (headers != null) {\n headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n }\n\n this.runInAsyncScope(callback, null, null, {\n statusCode,\n headers,\n socket,\n opaque,\n context\n })\n }\n\n onError (err) {\n const { callback, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n }\n}\n\nfunction connect (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n connect.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n const connectHandler = new ConnectHandler(opts, callback)\n this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = connect\n","'use strict'\n\nconst {\n Readable,\n Duplex,\n PassThrough\n} = require('stream')\nconst {\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\nconst assert = require('assert')\n\nconst kResume = Symbol('resume')\n\nclass PipelineRequest extends Readable {\n constructor () {\n super({ autoDestroy: true })\n\n this[kResume] = null\n }\n\n _read () {\n const { [kResume]: resume } = this\n\n if (resume) {\n this[kResume] = null\n resume()\n }\n }\n\n _destroy (err, callback) {\n this._read()\n\n callback(err)\n }\n}\n\nclass PipelineResponse extends Readable {\n constructor (resume) {\n super({ autoDestroy: true })\n this[kResume] = resume\n }\n\n _read () {\n this[kResume]()\n }\n\n _destroy (err, callback) {\n if (!err && !this._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n callback(err)\n }\n}\n\nclass PipelineHandler extends AsyncResource {\n constructor (opts, handler) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof handler !== 'function') {\n throw new InvalidArgumentError('invalid handler')\n }\n\n const { signal, method, opaque, onInfo, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_PIPELINE')\n\n this.opaque = opaque || null\n this.responseHeaders = responseHeaders || null\n this.handler = handler\n this.abort = null\n this.context = null\n this.onInfo = onInfo || null\n\n this.req = new PipelineRequest().on('error', util.nop)\n\n this.ret = new Duplex({\n readableObjectMode: opts.objectMode,\n autoDestroy: true,\n read: () => {\n const { body } = this\n\n if (body && body.resume) {\n body.resume()\n }\n },\n write: (chunk, encoding, callback) => {\n const { req } = this\n\n if (req.push(chunk, encoding) || req._readableState.destroyed) {\n callback()\n } else {\n req[kResume] = callback\n }\n },\n destroy: (err, callback) => {\n const { body, req, res, ret, abort } = this\n\n if (!err && !ret._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n if (abort && err) {\n abort()\n }\n\n util.destroy(body, err)\n util.destroy(req, err)\n util.destroy(res, err)\n\n removeSignal(this)\n\n callback(err)\n }\n }).on('prefinish', () => {\n const { req } = this\n\n // Node < 15 does not call _final in same tick.\n req.push(null)\n })\n\n this.res = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n const { ret, res } = this\n\n assert(!res, 'pipeline cannot be retried')\n\n if (ret.destroyed) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume) {\n const { opaque, handler, context } = this\n\n if (statusCode < 200) {\n if (this.onInfo) {\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n this.res = new PipelineResponse(resume)\n\n let body\n try {\n this.handler = null\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n body = this.runInAsyncScope(handler, null, {\n statusCode,\n headers,\n opaque,\n body: this.res,\n context\n })\n } catch (err) {\n this.res.on('error', util.nop)\n throw err\n }\n\n if (!body || typeof body.on !== 'function') {\n throw new InvalidReturnValueError('expected Readable')\n }\n\n body\n .on('data', (chunk) => {\n const { ret, body } = this\n\n if (!ret.push(chunk) && body.pause) {\n body.pause()\n }\n })\n .on('error', (err) => {\n const { ret } = this\n\n util.destroy(ret, err)\n })\n .on('end', () => {\n const { ret } = this\n\n ret.push(null)\n })\n .on('close', () => {\n const { ret } = this\n\n if (!ret._readableState.ended) {\n util.destroy(ret, new RequestAbortedError())\n }\n })\n\n this.body = body\n }\n\n onData (chunk) {\n const { res } = this\n return res.push(chunk)\n }\n\n onComplete (trailers) {\n const { res } = this\n res.push(null)\n }\n\n onError (err) {\n const { ret } = this\n this.handler = null\n util.destroy(ret, err)\n }\n}\n\nfunction pipeline (opts, handler) {\n try {\n const pipelineHandler = new PipelineHandler(opts, handler)\n this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)\n return pipelineHandler.ret\n } catch (err) {\n return new PassThrough().destroy(err)\n }\n}\n\nmodule.exports = pipeline\n","'use strict'\n\nconst Readable = require('./readable')\nconst {\n InvalidArgumentError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { getResolveErrorBodyCallback } = require('./util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass RequestHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts\n\n try {\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {\n throw new InvalidArgumentError('invalid highWaterMark')\n }\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_REQUEST')\n } catch (err) {\n if (util.isStream(body)) {\n util.destroy(body.on('error', util.nop), err)\n }\n throw err\n }\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.callback = callback\n this.res = null\n this.abort = null\n this.body = body\n this.trailers = {}\n this.context = null\n this.onInfo = onInfo || null\n this.throwOnError = throwOnError\n this.highWaterMark = highWaterMark\n\n if (util.isStream(body)) {\n body.on('error', (err) => {\n this.onError(err)\n })\n }\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this\n\n const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n\n if (statusCode < 200) {\n if (this.onInfo) {\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers\n const contentType = parsedHeaders['content-type']\n const body = new Readable({ resume, abort, contentType, highWaterMark })\n\n this.callback = null\n this.res = body\n if (callback !== null) {\n if (this.throwOnError && statusCode >= 400) {\n this.runInAsyncScope(getResolveErrorBodyCallback, null,\n { callback, body, contentType, statusCode, statusMessage, headers }\n )\n } else {\n this.runInAsyncScope(callback, null, null, {\n statusCode,\n headers,\n trailers: this.trailers,\n opaque,\n body,\n context\n })\n }\n }\n }\n\n onData (chunk) {\n const { res } = this\n return res.push(chunk)\n }\n\n onComplete (trailers) {\n const { res } = this\n\n removeSignal(this)\n\n util.parseHeaders(trailers, this.trailers)\n\n res.push(null)\n }\n\n onError (err) {\n const { res, callback, body, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n // TODO: Does this need queueMicrotask?\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n\n if (res) {\n this.res = null\n // Ensure all queued handlers are invoked before destroying res.\n queueMicrotask(() => {\n util.destroy(res, err)\n })\n }\n\n if (body) {\n this.body = null\n util.destroy(body, err)\n }\n }\n}\n\nfunction request (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n request.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n this.dispatch(opts, new RequestHandler(opts, callback))\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = request\nmodule.exports.RequestHandler = RequestHandler\n","'use strict'\n\nconst { finished, PassThrough } = require('stream')\nconst {\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { getResolveErrorBodyCallback } = require('./util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass StreamHandler extends AsyncResource {\n constructor (opts, factory, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts\n\n try {\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('invalid factory')\n }\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_STREAM')\n } catch (err) {\n if (util.isStream(body)) {\n util.destroy(body.on('error', util.nop), err)\n }\n throw err\n }\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.factory = factory\n this.callback = callback\n this.res = null\n this.abort = null\n this.context = null\n this.trailers = null\n this.body = body\n this.onInfo = onInfo || null\n this.throwOnError = throwOnError || false\n\n if (util.isStream(body)) {\n body.on('error', (err) => {\n this.onError(err)\n })\n }\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const { factory, opaque, context, callback, responseHeaders } = this\n\n const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n\n if (statusCode < 200) {\n if (this.onInfo) {\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n this.factory = null\n\n let res\n\n if (this.throwOnError && statusCode >= 400) {\n const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers\n const contentType = parsedHeaders['content-type']\n res = new PassThrough()\n\n this.callback = null\n this.runInAsyncScope(getResolveErrorBodyCallback, null,\n { callback, body: res, contentType, statusCode, statusMessage, headers }\n )\n } else {\n if (factory === null) {\n return\n }\n\n res = this.runInAsyncScope(factory, null, {\n statusCode,\n headers,\n opaque,\n context\n })\n\n if (\n !res ||\n typeof res.write !== 'function' ||\n typeof res.end !== 'function' ||\n typeof res.on !== 'function'\n ) {\n throw new InvalidReturnValueError('expected Writable')\n }\n\n // TODO: Avoid finished. It registers an unnecessary amount of listeners.\n finished(res, { readable: false }, (err) => {\n const { callback, res, opaque, trailers, abort } = this\n\n this.res = null\n if (err || !res.readable) {\n util.destroy(res, err)\n }\n\n this.callback = null\n this.runInAsyncScope(callback, null, err || null, { opaque, trailers })\n\n if (err) {\n abort()\n }\n })\n }\n\n res.on('drain', resume)\n\n this.res = res\n\n const needDrain = res.writableNeedDrain !== undefined\n ? res.writableNeedDrain\n : res._writableState && res._writableState.needDrain\n\n return needDrain !== true\n }\n\n onData (chunk) {\n const { res } = this\n\n return res ? res.write(chunk) : true\n }\n\n onComplete (trailers) {\n const { res } = this\n\n removeSignal(this)\n\n if (!res) {\n return\n }\n\n this.trailers = util.parseHeaders(trailers)\n\n res.end()\n }\n\n onError (err) {\n const { res, callback, opaque, body } = this\n\n removeSignal(this)\n\n this.factory = null\n\n if (res) {\n this.res = null\n util.destroy(res, err)\n } else if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n\n if (body) {\n this.body = null\n util.destroy(body, err)\n }\n }\n}\n\nfunction stream (opts, factory, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n stream.call(this, opts, factory, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n this.dispatch(opts, new StreamHandler(opts, factory, callback))\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = stream\n","'use strict'\n\nconst { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors')\nconst { AsyncResource } = require('async_hooks')\nconst util = require('../core/util')\nconst { addSignal, removeSignal } = require('./abort-signal')\nconst assert = require('assert')\n\nclass UpgradeHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n const { signal, opaque, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n super('UNDICI_UPGRADE')\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.callback = callback\n this.abort = null\n this.context = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = null\n }\n\n onHeaders () {\n throw new SocketError('bad upgrade', null)\n }\n\n onUpgrade (statusCode, rawHeaders, socket) {\n const { callback, opaque, context } = this\n\n assert.strictEqual(statusCode, 101)\n\n removeSignal(this)\n\n this.callback = null\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n this.runInAsyncScope(callback, null, null, {\n headers,\n socket,\n opaque,\n context\n })\n }\n\n onError (err) {\n const { callback, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n }\n}\n\nfunction upgrade (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n upgrade.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n const upgradeHandler = new UpgradeHandler(opts, callback)\n this.dispatch({\n ...opts,\n method: opts.method || 'GET',\n upgrade: opts.protocol || 'Websocket'\n }, upgradeHandler)\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = upgrade\n","'use strict'\n\nmodule.exports.request = require('./api-request')\nmodule.exports.stream = require('./api-stream')\nmodule.exports.pipeline = require('./api-pipeline')\nmodule.exports.upgrade = require('./api-upgrade')\nmodule.exports.connect = require('./api-connect')\n","// Ported from https://github.com/nodejs/undici/pull/907\n\n'use strict'\n\nconst assert = require('assert')\nconst { Readable } = require('stream')\nconst { RequestAbortedError, NotSupportedError, InvalidArgumentError } = require('../core/errors')\nconst util = require('../core/util')\nconst { ReadableStreamFrom, toUSVString } = require('../core/util')\n\nlet Blob\n\nconst kConsume = Symbol('kConsume')\nconst kReading = Symbol('kReading')\nconst kBody = Symbol('kBody')\nconst kAbort = Symbol('abort')\nconst kContentType = Symbol('kContentType')\n\nconst noop = () => {}\n\nmodule.exports = class BodyReadable extends Readable {\n constructor ({\n resume,\n abort,\n contentType = '',\n highWaterMark = 64 * 1024 // Same as nodejs fs streams.\n }) {\n super({\n autoDestroy: true,\n read: resume,\n highWaterMark\n })\n\n this._readableState.dataEmitted = false\n\n this[kAbort] = abort\n this[kConsume] = null\n this[kBody] = null\n this[kContentType] = contentType\n\n // Is stream being consumed through Readable API?\n // This is an optimization so that we avoid checking\n // for 'data' and 'readable' listeners in the hot path\n // inside push().\n this[kReading] = false\n }\n\n destroy (err) {\n if (this.destroyed) {\n // Node < 16\n return this\n }\n\n if (!err && !this._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n if (err) {\n this[kAbort]()\n }\n\n return super.destroy(err)\n }\n\n emit (ev, ...args) {\n if (ev === 'data') {\n // Node < 16.7\n this._readableState.dataEmitted = true\n } else if (ev === 'error') {\n // Node < 16\n this._readableState.errorEmitted = true\n }\n return super.emit(ev, ...args)\n }\n\n on (ev, ...args) {\n if (ev === 'data' || ev === 'readable') {\n this[kReading] = true\n }\n return super.on(ev, ...args)\n }\n\n addListener (ev, ...args) {\n return this.on(ev, ...args)\n }\n\n off (ev, ...args) {\n const ret = super.off(ev, ...args)\n if (ev === 'data' || ev === 'readable') {\n this[kReading] = (\n this.listenerCount('data') > 0 ||\n this.listenerCount('readable') > 0\n )\n }\n return ret\n }\n\n removeListener (ev, ...args) {\n return this.off(ev, ...args)\n }\n\n push (chunk) {\n if (this[kConsume] && chunk !== null && this.readableLength === 0) {\n consumePush(this[kConsume], chunk)\n return this[kReading] ? super.push(chunk) : true\n }\n return super.push(chunk)\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-text\n async text () {\n return consume(this, 'text')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-json\n async json () {\n return consume(this, 'json')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-blob\n async blob () {\n return consume(this, 'blob')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-arraybuffer\n async arrayBuffer () {\n return consume(this, 'arrayBuffer')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-formdata\n async formData () {\n // TODO: Implement.\n throw new NotSupportedError()\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-bodyused\n get bodyUsed () {\n return util.isDisturbed(this)\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-body\n get body () {\n if (!this[kBody]) {\n this[kBody] = ReadableStreamFrom(this)\n if (this[kConsume]) {\n // TODO: Is this the best way to force a lock?\n this[kBody].getReader() // Ensure stream is locked.\n assert(this[kBody].locked)\n }\n }\n return this[kBody]\n }\n\n dump (opts) {\n let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144\n const signal = opts && opts.signal\n\n if (signal) {\n try {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n throw new InvalidArgumentError('signal must be an AbortSignal')\n }\n util.throwIfAborted(signal)\n } catch (err) {\n return Promise.reject(err)\n }\n }\n\n if (this.closed) {\n return Promise.resolve(null)\n }\n\n return new Promise((resolve, reject) => {\n const signalListenerCleanup = signal\n ? util.addAbortListener(signal, () => {\n this.destroy()\n })\n : noop\n\n this\n .on('close', function () {\n signalListenerCleanup()\n if (signal && signal.aborted) {\n reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))\n } else {\n resolve(null)\n }\n })\n .on('error', noop)\n .on('data', function (chunk) {\n limit -= chunk.length\n if (limit <= 0) {\n this.destroy()\n }\n })\n .resume()\n })\n }\n}\n\n// https://streams.spec.whatwg.org/#readablestream-locked\nfunction isLocked (self) {\n // Consume is an implicit lock.\n return (self[kBody] && self[kBody].locked === true) || self[kConsume]\n}\n\n// https://fetch.spec.whatwg.org/#body-unusable\nfunction isUnusable (self) {\n return util.isDisturbed(self) || isLocked(self)\n}\n\nasync function consume (stream, type) {\n if (isUnusable(stream)) {\n throw new TypeError('unusable')\n }\n\n assert(!stream[kConsume])\n\n return new Promise((resolve, reject) => {\n stream[kConsume] = {\n type,\n stream,\n resolve,\n reject,\n length: 0,\n body: []\n }\n\n stream\n .on('error', function (err) {\n consumeFinish(this[kConsume], err)\n })\n .on('close', function () {\n if (this[kConsume].body !== null) {\n consumeFinish(this[kConsume], new RequestAbortedError())\n }\n })\n\n process.nextTick(consumeStart, stream[kConsume])\n })\n}\n\nfunction consumeStart (consume) {\n if (consume.body === null) {\n return\n }\n\n const { _readableState: state } = consume.stream\n\n for (const chunk of state.buffer) {\n consumePush(consume, chunk)\n }\n\n if (state.endEmitted) {\n consumeEnd(this[kConsume])\n } else {\n consume.stream.on('end', function () {\n consumeEnd(this[kConsume])\n })\n }\n\n consume.stream.resume()\n\n while (consume.stream.read() != null) {\n // Loop\n }\n}\n\nfunction consumeEnd (consume) {\n const { type, body, resolve, stream, length } = consume\n\n try {\n if (type === 'text') {\n resolve(toUSVString(Buffer.concat(body)))\n } else if (type === 'json') {\n resolve(JSON.parse(Buffer.concat(body)))\n } else if (type === 'arrayBuffer') {\n const dst = new Uint8Array(length)\n\n let pos = 0\n for (const buf of body) {\n dst.set(buf, pos)\n pos += buf.byteLength\n }\n\n resolve(dst.buffer)\n } else if (type === 'blob') {\n if (!Blob) {\n Blob = require('buffer').Blob\n }\n resolve(new Blob(body, { type: stream[kContentType] }))\n }\n\n consumeFinish(consume)\n } catch (err) {\n stream.destroy(err)\n }\n}\n\nfunction consumePush (consume, chunk) {\n consume.length += chunk.length\n consume.body.push(chunk)\n}\n\nfunction consumeFinish (consume, err) {\n if (consume.body === null) {\n return\n }\n\n if (err) {\n consume.reject(err)\n } else {\n consume.resolve()\n }\n\n consume.type = null\n consume.stream = null\n consume.resolve = null\n consume.reject = null\n consume.length = 0\n consume.body = null\n}\n","const assert = require('assert')\nconst {\n ResponseStatusCodeError\n} = require('../core/errors')\nconst { toUSVString } = require('../core/util')\n\nasync function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {\n assert(body)\n\n let chunks = []\n let limit = 0\n\n for await (const chunk of body) {\n chunks.push(chunk)\n limit += chunk.length\n if (limit > 128 * 1024) {\n chunks = null\n break\n }\n }\n\n if (statusCode === 204 || !contentType || !chunks) {\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))\n return\n }\n\n try {\n if (contentType.startsWith('application/json')) {\n const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))\n return\n }\n\n if (contentType.startsWith('text/')) {\n const payload = toUSVString(Buffer.concat(chunks))\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))\n return\n }\n } catch (err) {\n // Process in a fallback if error\n }\n\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))\n}\n\nmodule.exports = { getResolveErrorBodyCallback }\n","'use strict'\n\nconst {\n BalancedPoolMissingUpstreamError,\n InvalidArgumentError\n} = require('./core/errors')\nconst {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kRemoveClient,\n kGetDispatcher\n} = require('./pool-base')\nconst Pool = require('./pool')\nconst { kUrl, kInterceptors } = require('./core/symbols')\nconst { parseOrigin } = require('./core/util')\nconst kFactory = Symbol('factory')\n\nconst kOptions = Symbol('options')\nconst kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')\nconst kCurrentWeight = Symbol('kCurrentWeight')\nconst kIndex = Symbol('kIndex')\nconst kWeight = Symbol('kWeight')\nconst kMaxWeightPerServer = Symbol('kMaxWeightPerServer')\nconst kErrorPenalty = Symbol('kErrorPenalty')\n\nfunction getGreatestCommonDivisor (a, b) {\n if (b === 0) return a\n return getGreatestCommonDivisor(b, a % b)\n}\n\nfunction defaultFactory (origin, opts) {\n return new Pool(origin, opts)\n}\n\nclass BalancedPool extends PoolBase {\n constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {\n super()\n\n this[kOptions] = opts\n this[kIndex] = -1\n this[kCurrentWeight] = 0\n\n this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100\n this[kErrorPenalty] = this[kOptions].errorPenalty || 15\n\n if (!Array.isArray(upstreams)) {\n upstreams = [upstreams]\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)\n ? opts.interceptors.BalancedPool\n : []\n this[kFactory] = factory\n\n for (const upstream of upstreams) {\n this.addUpstream(upstream)\n }\n this._updateBalancedPoolStats()\n }\n\n addUpstream (upstream) {\n const upstreamOrigin = parseOrigin(upstream).origin\n\n if (this[kClients].find((pool) => (\n pool[kUrl].origin === upstreamOrigin &&\n pool.closed !== true &&\n pool.destroyed !== true\n ))) {\n return this\n }\n const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))\n\n this[kAddClient](pool)\n pool.on('connect', () => {\n pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])\n })\n\n pool.on('connectionError', () => {\n pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])\n this._updateBalancedPoolStats()\n })\n\n pool.on('disconnect', (...args) => {\n const err = args[2]\n if (err && err.code === 'UND_ERR_SOCKET') {\n // decrease the weight of the pool.\n pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])\n this._updateBalancedPoolStats()\n }\n })\n\n for (const client of this[kClients]) {\n client[kWeight] = this[kMaxWeightPerServer]\n }\n\n this._updateBalancedPoolStats()\n\n return this\n }\n\n _updateBalancedPoolStats () {\n this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)\n }\n\n removeUpstream (upstream) {\n const upstreamOrigin = parseOrigin(upstream).origin\n\n const pool = this[kClients].find((pool) => (\n pool[kUrl].origin === upstreamOrigin &&\n pool.closed !== true &&\n pool.destroyed !== true\n ))\n\n if (pool) {\n this[kRemoveClient](pool)\n }\n\n return this\n }\n\n get upstreams () {\n return this[kClients]\n .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)\n .map((p) => p[kUrl].origin)\n }\n\n [kGetDispatcher] () {\n // We validate that pools is greater than 0,\n // otherwise we would have to wait until an upstream\n // is added, which might never happen.\n if (this[kClients].length === 0) {\n throw new BalancedPoolMissingUpstreamError()\n }\n\n const dispatcher = this[kClients].find(dispatcher => (\n !dispatcher[kNeedDrain] &&\n dispatcher.closed !== true &&\n dispatcher.destroyed !== true\n ))\n\n if (!dispatcher) {\n return\n }\n\n const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)\n\n if (allClientsBusy) {\n return\n }\n\n let counter = 0\n\n let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])\n\n while (counter++ < this[kClients].length) {\n this[kIndex] = (this[kIndex] + 1) % this[kClients].length\n const pool = this[kClients][this[kIndex]]\n\n // find pool index with the largest weight\n if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {\n maxWeightIndex = this[kIndex]\n }\n\n // decrease the current weight every `this[kClients].length`.\n if (this[kIndex] === 0) {\n // Set the current weight to the next lower weight.\n this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]\n\n if (this[kCurrentWeight] <= 0) {\n this[kCurrentWeight] = this[kMaxWeightPerServer]\n }\n }\n if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {\n return pool\n }\n }\n\n this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]\n this[kIndex] = maxWeightIndex\n return this[kClients][maxWeightIndex]\n }\n}\n\nmodule.exports = BalancedPool\n","'use strict'\n\nconst { kConstruct } = require('./symbols')\nconst { urlEquals, fieldValues: getFieldValues } = require('./util')\nconst { kEnumerableProperty, isDisturbed } = require('../core/util')\nconst { kHeadersList } = require('../core/symbols')\nconst { webidl } = require('../fetch/webidl')\nconst { Response, cloneResponse } = require('../fetch/response')\nconst { Request } = require('../fetch/request')\nconst { kState, kHeaders, kGuard, kRealm } = require('../fetch/symbols')\nconst { fetching } = require('../fetch/index')\nconst { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util')\nconst assert = require('assert')\nconst { getGlobalDispatcher } = require('../global')\n\n/**\n * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation\n * @typedef {Object} CacheBatchOperation\n * @property {'delete' | 'put'} type\n * @property {any} request\n * @property {any} response\n * @property {import('../../types/cache').CacheQueryOptions} options\n */\n\n/**\n * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list\n * @typedef {[any, any][]} requestResponseList\n */\n\nclass Cache {\n /**\n * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list\n * @type {requestResponseList}\n */\n #relevantRequestResponseList\n\n constructor () {\n if (arguments[0] !== kConstruct) {\n webidl.illegalConstructor()\n }\n\n this.#relevantRequestResponseList = arguments[1]\n }\n\n async match (request, options = {}) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })\n\n request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n const p = await this.matchAll(request, options)\n\n if (p.length === 0) {\n return\n }\n\n return p[0]\n }\n\n async matchAll (request = undefined, options = {}) {\n webidl.brandCheck(this, Cache)\n\n if (request !== undefined) request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n // 1.\n let r = null\n\n // 2.\n if (request !== undefined) {\n if (request instanceof Request) {\n // 2.1.1\n r = request[kState]\n\n // 2.1.2\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return []\n }\n } else if (typeof request === 'string') {\n // 2.2.1\n r = new Request(request)[kState]\n }\n }\n\n // 5.\n // 5.1\n const responses = []\n\n // 5.2\n if (request === undefined) {\n // 5.2.1\n for (const requestResponse of this.#relevantRequestResponseList) {\n responses.push(requestResponse[1])\n }\n } else { // 5.3\n // 5.3.1\n const requestResponses = this.#queryCache(r, options)\n\n // 5.3.2\n for (const requestResponse of requestResponses) {\n responses.push(requestResponse[1])\n }\n }\n\n // 5.4\n // We don't implement CORs so we don't need to loop over the responses, yay!\n\n // 5.5.1\n const responseList = []\n\n // 5.5.2\n for (const response of responses) {\n // 5.5.2.1\n const responseObject = new Response(response.body?.source ?? null)\n const body = responseObject[kState].body\n responseObject[kState] = response\n responseObject[kState].body = body\n responseObject[kHeaders][kHeadersList] = response.headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n\n responseList.push(responseObject)\n }\n\n // 6.\n return Object.freeze(responseList)\n }\n\n async add (request) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })\n\n request = webidl.converters.RequestInfo(request)\n\n // 1.\n const requests = [request]\n\n // 2.\n const responseArrayPromise = this.addAll(requests)\n\n // 3.\n return await responseArrayPromise\n }\n\n async addAll (requests) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })\n\n requests = webidl.converters['sequence'](requests)\n\n // 1.\n const responsePromises = []\n\n // 2.\n const requestList = []\n\n // 3.\n for (const request of requests) {\n if (typeof request === 'string') {\n continue\n }\n\n // 3.1\n const r = request[kState]\n\n // 3.2\n if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Expected http/s scheme when method is not GET.'\n })\n }\n }\n\n // 4.\n /** @type {ReturnType[]} */\n const fetchControllers = []\n\n // 5.\n for (const request of requests) {\n // 5.1\n const r = new Request(request)[kState]\n\n // 5.2\n if (!urlIsHttpHttpsScheme(r.url)) {\n throw webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Expected http/s scheme.'\n })\n }\n\n // 5.4\n r.initiator = 'fetch'\n r.destination = 'subresource'\n\n // 5.5\n requestList.push(r)\n\n // 5.6\n const responsePromise = createDeferredPromise()\n\n // 5.7\n fetchControllers.push(fetching({\n request: r,\n dispatcher: getGlobalDispatcher(),\n processResponse (response) {\n // 1.\n if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {\n responsePromise.reject(webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Received an invalid status code or the request failed.'\n }))\n } else if (response.headersList.contains('vary')) { // 2.\n // 2.1\n const fieldValues = getFieldValues(response.headersList.get('vary'))\n\n // 2.2\n for (const fieldValue of fieldValues) {\n // 2.2.1\n if (fieldValue === '*') {\n responsePromise.reject(webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'invalid vary field value'\n }))\n\n for (const controller of fetchControllers) {\n controller.abort()\n }\n\n return\n }\n }\n }\n },\n processResponseEndOfBody (response) {\n // 1.\n if (response.aborted) {\n responsePromise.reject(new DOMException('aborted', 'AbortError'))\n return\n }\n\n // 2.\n responsePromise.resolve(response)\n }\n }))\n\n // 5.8\n responsePromises.push(responsePromise.promise)\n }\n\n // 6.\n const p = Promise.all(responsePromises)\n\n // 7.\n const responses = await p\n\n // 7.1\n const operations = []\n\n // 7.2\n let index = 0\n\n // 7.3\n for (const response of responses) {\n // 7.3.1\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'put', // 7.3.2\n request: requestList[index], // 7.3.3\n response // 7.3.4\n }\n\n operations.push(operation) // 7.3.5\n\n index++ // 7.3.6\n }\n\n // 7.5\n const cacheJobPromise = createDeferredPromise()\n\n // 7.6.1\n let errorData = null\n\n // 7.6.2\n try {\n this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n // 7.6.3\n queueMicrotask(() => {\n // 7.6.3.1\n if (errorData === null) {\n cacheJobPromise.resolve(undefined)\n } else {\n // 7.6.3.2\n cacheJobPromise.reject(errorData)\n }\n })\n\n // 7.7\n return cacheJobPromise.promise\n }\n\n async put (request, response) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })\n\n request = webidl.converters.RequestInfo(request)\n response = webidl.converters.Response(response)\n\n // 1.\n let innerRequest = null\n\n // 2.\n if (request instanceof Request) {\n innerRequest = request[kState]\n } else { // 3.\n innerRequest = new Request(request)[kState]\n }\n\n // 4.\n if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Expected an http/s scheme when method is not GET'\n })\n }\n\n // 5.\n const innerResponse = response[kState]\n\n // 6.\n if (innerResponse.status === 206) {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Got 206 status'\n })\n }\n\n // 7.\n if (innerResponse.headersList.contains('vary')) {\n // 7.1.\n const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))\n\n // 7.2.\n for (const fieldValue of fieldValues) {\n // 7.2.1\n if (fieldValue === '*') {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Got * vary field value'\n })\n }\n }\n }\n\n // 8.\n if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Response body is locked or disturbed'\n })\n }\n\n // 9.\n const clonedResponse = cloneResponse(innerResponse)\n\n // 10.\n const bodyReadPromise = createDeferredPromise()\n\n // 11.\n if (innerResponse.body != null) {\n // 11.1\n const stream = innerResponse.body.stream\n\n // 11.2\n const reader = stream.getReader()\n\n // 11.3\n readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)\n } else {\n bodyReadPromise.resolve(undefined)\n }\n\n // 12.\n /** @type {CacheBatchOperation[]} */\n const operations = []\n\n // 13.\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'put', // 14.\n request: innerRequest, // 15.\n response: clonedResponse // 16.\n }\n\n // 17.\n operations.push(operation)\n\n // 19.\n const bytes = await bodyReadPromise.promise\n\n if (clonedResponse.body != null) {\n clonedResponse.body.source = bytes\n }\n\n // 19.1\n const cacheJobPromise = createDeferredPromise()\n\n // 19.2.1\n let errorData = null\n\n // 19.2.2\n try {\n this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n // 19.2.3\n queueMicrotask(() => {\n // 19.2.3.1\n if (errorData === null) {\n cacheJobPromise.resolve()\n } else { // 19.2.3.2\n cacheJobPromise.reject(errorData)\n }\n })\n\n return cacheJobPromise.promise\n }\n\n async delete (request, options = {}) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })\n\n request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n /**\n * @type {Request}\n */\n let r = null\n\n if (request instanceof Request) {\n r = request[kState]\n\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return false\n }\n } else {\n assert(typeof request === 'string')\n\n r = new Request(request)[kState]\n }\n\n /** @type {CacheBatchOperation[]} */\n const operations = []\n\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'delete',\n request: r,\n options\n }\n\n operations.push(operation)\n\n const cacheJobPromise = createDeferredPromise()\n\n let errorData = null\n let requestResponses\n\n try {\n requestResponses = this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n queueMicrotask(() => {\n if (errorData === null) {\n cacheJobPromise.resolve(!!requestResponses?.length)\n } else {\n cacheJobPromise.reject(errorData)\n }\n })\n\n return cacheJobPromise.promise\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys\n * @param {any} request\n * @param {import('../../types/cache').CacheQueryOptions} options\n * @returns {readonly Request[]}\n */\n async keys (request = undefined, options = {}) {\n webidl.brandCheck(this, Cache)\n\n if (request !== undefined) request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n // 1.\n let r = null\n\n // 2.\n if (request !== undefined) {\n // 2.1\n if (request instanceof Request) {\n // 2.1.1\n r = request[kState]\n\n // 2.1.2\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return []\n }\n } else if (typeof request === 'string') { // 2.2\n r = new Request(request)[kState]\n }\n }\n\n // 4.\n const promise = createDeferredPromise()\n\n // 5.\n // 5.1\n const requests = []\n\n // 5.2\n if (request === undefined) {\n // 5.2.1\n for (const requestResponse of this.#relevantRequestResponseList) {\n // 5.2.1.1\n requests.push(requestResponse[0])\n }\n } else { // 5.3\n // 5.3.1\n const requestResponses = this.#queryCache(r, options)\n\n // 5.3.2\n for (const requestResponse of requestResponses) {\n // 5.3.2.1\n requests.push(requestResponse[0])\n }\n }\n\n // 5.4\n queueMicrotask(() => {\n // 5.4.1\n const requestList = []\n\n // 5.4.2\n for (const request of requests) {\n const requestObject = new Request('https://a')\n requestObject[kState] = request\n requestObject[kHeaders][kHeadersList] = request.headersList\n requestObject[kHeaders][kGuard] = 'immutable'\n requestObject[kRealm] = request.client\n\n // 5.4.2.1\n requestList.push(requestObject)\n }\n\n // 5.4.3\n promise.resolve(Object.freeze(requestList))\n })\n\n return promise.promise\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm\n * @param {CacheBatchOperation[]} operations\n * @returns {requestResponseList}\n */\n #batchCacheOperations (operations) {\n // 1.\n const cache = this.#relevantRequestResponseList\n\n // 2.\n const backupCache = [...cache]\n\n // 3.\n const addedItems = []\n\n // 4.1\n const resultList = []\n\n try {\n // 4.2\n for (const operation of operations) {\n // 4.2.1\n if (operation.type !== 'delete' && operation.type !== 'put') {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'operation type does not match \"delete\" or \"put\"'\n })\n }\n\n // 4.2.2\n if (operation.type === 'delete' && operation.response != null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'delete operation should not have an associated response'\n })\n }\n\n // 4.2.3\n if (this.#queryCache(operation.request, operation.options, addedItems).length) {\n throw new DOMException('???', 'InvalidStateError')\n }\n\n // 4.2.4\n let requestResponses\n\n // 4.2.5\n if (operation.type === 'delete') {\n // 4.2.5.1\n requestResponses = this.#queryCache(operation.request, operation.options)\n\n // TODO: the spec is wrong, this is needed to pass WPTs\n if (requestResponses.length === 0) {\n return []\n }\n\n // 4.2.5.2\n for (const requestResponse of requestResponses) {\n const idx = cache.indexOf(requestResponse)\n assert(idx !== -1)\n\n // 4.2.5.2.1\n cache.splice(idx, 1)\n }\n } else if (operation.type === 'put') { // 4.2.6\n // 4.2.6.1\n if (operation.response == null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'put operation should have an associated response'\n })\n }\n\n // 4.2.6.2\n const r = operation.request\n\n // 4.2.6.3\n if (!urlIsHttpHttpsScheme(r.url)) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'expected http or https scheme'\n })\n }\n\n // 4.2.6.4\n if (r.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'not get method'\n })\n }\n\n // 4.2.6.5\n if (operation.options != null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'options must not be defined'\n })\n }\n\n // 4.2.6.6\n requestResponses = this.#queryCache(operation.request)\n\n // 4.2.6.7\n for (const requestResponse of requestResponses) {\n const idx = cache.indexOf(requestResponse)\n assert(idx !== -1)\n\n // 4.2.6.7.1\n cache.splice(idx, 1)\n }\n\n // 4.2.6.8\n cache.push([operation.request, operation.response])\n\n // 4.2.6.10\n addedItems.push([operation.request, operation.response])\n }\n\n // 4.2.7\n resultList.push([operation.request, operation.response])\n }\n\n // 4.3\n return resultList\n } catch (e) { // 5.\n // 5.1\n this.#relevantRequestResponseList.length = 0\n\n // 5.2\n this.#relevantRequestResponseList = backupCache\n\n // 5.3\n throw e\n }\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#query-cache\n * @param {any} requestQuery\n * @param {import('../../types/cache').CacheQueryOptions} options\n * @param {requestResponseList} targetStorage\n * @returns {requestResponseList}\n */\n #queryCache (requestQuery, options, targetStorage) {\n /** @type {requestResponseList} */\n const resultList = []\n\n const storage = targetStorage ?? this.#relevantRequestResponseList\n\n for (const requestResponse of storage) {\n const [cachedRequest, cachedResponse] = requestResponse\n if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {\n resultList.push(requestResponse)\n }\n }\n\n return resultList\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm\n * @param {any} requestQuery\n * @param {any} request\n * @param {any | null} response\n * @param {import('../../types/cache').CacheQueryOptions | undefined} options\n * @returns {boolean}\n */\n #requestMatchesCachedItem (requestQuery, request, response = null, options) {\n // if (options?.ignoreMethod === false && request.method === 'GET') {\n // return false\n // }\n\n const queryURL = new URL(requestQuery.url)\n\n const cachedURL = new URL(request.url)\n\n if (options?.ignoreSearch) {\n cachedURL.search = ''\n\n queryURL.search = ''\n }\n\n if (!urlEquals(queryURL, cachedURL, true)) {\n return false\n }\n\n if (\n response == null ||\n options?.ignoreVary ||\n !response.headersList.contains('vary')\n ) {\n return true\n }\n\n const fieldValues = getFieldValues(response.headersList.get('vary'))\n\n for (const fieldValue of fieldValues) {\n if (fieldValue === '*') {\n return false\n }\n\n const requestValue = request.headersList.get(fieldValue)\n const queryValue = requestQuery.headersList.get(fieldValue)\n\n // If one has the header and the other doesn't, or one has\n // a different value than the other, return false\n if (requestValue !== queryValue) {\n return false\n }\n }\n\n return true\n }\n}\n\nObject.defineProperties(Cache.prototype, {\n [Symbol.toStringTag]: {\n value: 'Cache',\n configurable: true\n },\n match: kEnumerableProperty,\n matchAll: kEnumerableProperty,\n add: kEnumerableProperty,\n addAll: kEnumerableProperty,\n put: kEnumerableProperty,\n delete: kEnumerableProperty,\n keys: kEnumerableProperty\n})\n\nconst cacheQueryOptionConverters = [\n {\n key: 'ignoreSearch',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'ignoreMethod',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'ignoreVary',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n]\n\nwebidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)\n\nwebidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([\n ...cacheQueryOptionConverters,\n {\n key: 'cacheName',\n converter: webidl.converters.DOMString\n }\n])\n\nwebidl.converters.Response = webidl.interfaceConverter(Response)\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.RequestInfo\n)\n\nmodule.exports = {\n Cache\n}\n","'use strict'\n\nconst { kConstruct } = require('./symbols')\nconst { Cache } = require('./cache')\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\n\nclass CacheStorage {\n /**\n * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map\n * @type {Map}\n */\n async has (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n // 2.1.1\n // 2.2\n return this.#caches.has(cacheName)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open\n * @param {string} cacheName\n * @returns {Promise}\n */\n async open (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n // 2.1\n if (this.#caches.has(cacheName)) {\n // await caches.open('v1') !== await caches.open('v1')\n\n // 2.1.1\n const cache = this.#caches.get(cacheName)\n\n // 2.1.1.1\n return new Cache(kConstruct, cache)\n }\n\n // 2.2\n const cache = []\n\n // 2.3\n this.#caches.set(cacheName, cache)\n\n // 2.4\n return new Cache(kConstruct, cache)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete\n * @param {string} cacheName\n * @returns {Promise}\n */\n async delete (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n return this.#caches.delete(cacheName)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys\n * @returns {string[]}\n */\n async keys () {\n webidl.brandCheck(this, CacheStorage)\n\n // 2.1\n const keys = this.#caches.keys()\n\n // 2.2\n return [...keys]\n }\n}\n\nObject.defineProperties(CacheStorage.prototype, {\n [Symbol.toStringTag]: {\n value: 'CacheStorage',\n configurable: true\n },\n match: kEnumerableProperty,\n has: kEnumerableProperty,\n open: kEnumerableProperty,\n delete: kEnumerableProperty,\n keys: kEnumerableProperty\n})\n\nmodule.exports = {\n CacheStorage\n}\n","'use strict'\n\nmodule.exports = {\n kConstruct: require('../core/symbols').kConstruct\n}\n","'use strict'\n\nconst assert = require('assert')\nconst { URLSerializer } = require('../fetch/dataURL')\nconst { isValidHeaderName } = require('../fetch/util')\n\n/**\n * @see https://url.spec.whatwg.org/#concept-url-equals\n * @param {URL} A\n * @param {URL} B\n * @param {boolean | undefined} excludeFragment\n * @returns {boolean}\n */\nfunction urlEquals (A, B, excludeFragment = false) {\n const serializedA = URLSerializer(A, excludeFragment)\n\n const serializedB = URLSerializer(B, excludeFragment)\n\n return serializedA === serializedB\n}\n\n/**\n * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262\n * @param {string} header\n */\nfunction fieldValues (header) {\n assert(header !== null)\n\n const values = []\n\n for (let value of header.split(',')) {\n value = value.trim()\n\n if (!value.length) {\n continue\n } else if (!isValidHeaderName(value)) {\n continue\n }\n\n values.push(value)\n }\n\n return values\n}\n\nmodule.exports = {\n urlEquals,\n fieldValues\n}\n","// @ts-check\n\n'use strict'\n\n/* global WebAssembly */\n\nconst assert = require('assert')\nconst net = require('net')\nconst http = require('http')\nconst { pipeline } = require('stream')\nconst util = require('./core/util')\nconst timers = require('./timers')\nconst Request = require('./core/request')\nconst DispatcherBase = require('./dispatcher-base')\nconst {\n RequestContentLengthMismatchError,\n ResponseContentLengthMismatchError,\n InvalidArgumentError,\n RequestAbortedError,\n HeadersTimeoutError,\n HeadersOverflowError,\n SocketError,\n InformationalError,\n BodyTimeoutError,\n HTTPParserError,\n ResponseExceededMaxSizeError,\n ClientDestroyedError\n} = require('./core/errors')\nconst buildConnector = require('./core/connect')\nconst {\n kUrl,\n kReset,\n kServerName,\n kClient,\n kBusy,\n kParser,\n kConnect,\n kBlocking,\n kResuming,\n kRunning,\n kPending,\n kSize,\n kWriting,\n kQueue,\n kConnected,\n kConnecting,\n kNeedDrain,\n kNoRef,\n kKeepAliveDefaultTimeout,\n kHostHeader,\n kPendingIdx,\n kRunningIdx,\n kError,\n kPipelining,\n kSocket,\n kKeepAliveTimeoutValue,\n kMaxHeadersSize,\n kKeepAliveMaxTimeout,\n kKeepAliveTimeoutThreshold,\n kHeadersTimeout,\n kBodyTimeout,\n kStrictContentLength,\n kConnector,\n kMaxRedirections,\n kMaxRequests,\n kCounter,\n kClose,\n kDestroy,\n kDispatch,\n kInterceptors,\n kLocalAddress,\n kMaxResponseSize,\n kHTTPConnVersion,\n // HTTP2\n kHost,\n kHTTP2Session,\n kHTTP2SessionState,\n kHTTP2BuildRequest,\n kHTTP2CopyHeaders,\n kHTTP1BuildRequest\n} = require('./core/symbols')\n\n/** @type {import('http2')} */\nlet http2\ntry {\n http2 = require('http2')\n} catch {\n // @ts-ignore\n http2 = { constants: {} }\n}\n\nconst {\n constants: {\n HTTP2_HEADER_AUTHORITY,\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_SCHEME,\n HTTP2_HEADER_CONTENT_LENGTH,\n HTTP2_HEADER_EXPECT,\n HTTP2_HEADER_STATUS\n }\n} = http2\n\n// Experimental\nlet h2ExperimentalWarned = false\n\nconst FastBuffer = Buffer[Symbol.species]\n\nconst kClosedResolve = Symbol('kClosedResolve')\n\nconst channels = {}\n\ntry {\n const diagnosticsChannel = require('diagnostics_channel')\n channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')\n channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')\n channels.connectError = diagnosticsChannel.channel('undici:client:connectError')\n channels.connected = diagnosticsChannel.channel('undici:client:connected')\n} catch {\n channels.sendHeaders = { hasSubscribers: false }\n channels.beforeConnect = { hasSubscribers: false }\n channels.connectError = { hasSubscribers: false }\n channels.connected = { hasSubscribers: false }\n}\n\n/**\n * @type {import('../types/client').default}\n */\nclass Client extends DispatcherBase {\n /**\n *\n * @param {string|URL} url\n * @param {import('../types/client').Client.Options} options\n */\n constructor (url, {\n interceptors,\n maxHeaderSize,\n headersTimeout,\n socketTimeout,\n requestTimeout,\n connectTimeout,\n bodyTimeout,\n idleTimeout,\n keepAlive,\n keepAliveTimeout,\n maxKeepAliveTimeout,\n keepAliveMaxTimeout,\n keepAliveTimeoutThreshold,\n socketPath,\n pipelining,\n tls,\n strictContentLength,\n maxCachedSessions,\n maxRedirections,\n connect,\n maxRequestsPerClient,\n localAddress,\n maxResponseSize,\n autoSelectFamily,\n autoSelectFamilyAttemptTimeout,\n // h2\n allowH2,\n maxConcurrentStreams\n } = {}) {\n super()\n\n if (keepAlive !== undefined) {\n throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')\n }\n\n if (socketTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')\n }\n\n if (requestTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')\n }\n\n if (idleTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')\n }\n\n if (maxKeepAliveTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')\n }\n\n if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {\n throw new InvalidArgumentError('invalid maxHeaderSize')\n }\n\n if (socketPath != null && typeof socketPath !== 'string') {\n throw new InvalidArgumentError('invalid socketPath')\n }\n\n if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {\n throw new InvalidArgumentError('invalid connectTimeout')\n }\n\n if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {\n throw new InvalidArgumentError('invalid keepAliveTimeout')\n }\n\n if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {\n throw new InvalidArgumentError('invalid keepAliveMaxTimeout')\n }\n\n if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {\n throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')\n }\n\n if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {\n throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')\n }\n\n if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {\n throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {\n throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')\n }\n\n if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {\n throw new InvalidArgumentError('localAddress must be valid string IP address')\n }\n\n if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {\n throw new InvalidArgumentError('maxResponseSize must be a positive number')\n }\n\n if (\n autoSelectFamilyAttemptTimeout != null &&\n (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)\n ) {\n throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')\n }\n\n // h2\n if (allowH2 != null && typeof allowH2 !== 'boolean') {\n throw new InvalidArgumentError('allowH2 must be a valid boolean value')\n }\n\n if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {\n throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')\n }\n\n if (typeof connect !== 'function') {\n connect = buildConnector({\n ...tls,\n maxCachedSessions,\n allowH2,\n socketPath,\n timeout: connectTimeout,\n ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),\n ...connect\n })\n }\n\n this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)\n ? interceptors.Client\n : [createRedirectInterceptor({ maxRedirections })]\n this[kUrl] = util.parseOrigin(url)\n this[kConnector] = connect\n this[kSocket] = null\n this[kPipelining] = pipelining != null ? pipelining : 1\n this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize\n this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout\n this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout\n this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold\n this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]\n this[kServerName] = null\n this[kLocalAddress] = localAddress != null ? localAddress : null\n this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming\n this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming\n this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\\r\\n`\n this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3\n this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3\n this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength\n this[kMaxRedirections] = maxRedirections\n this[kMaxRequests] = maxRequestsPerClient\n this[kClosedResolve] = null\n this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1\n this[kHTTPConnVersion] = 'h1'\n\n // HTTP/2\n this[kHTTP2Session] = null\n this[kHTTP2SessionState] = !allowH2\n ? null\n : {\n // streams: null, // Fixed queue of streams - For future support of `push`\n openStreams: 0, // Keep track of them to decide wether or not unref the session\n maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server\n }\n this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`\n\n // kQueue is built up of 3 sections separated by\n // the kRunningIdx and kPendingIdx indices.\n // | complete | running | pending |\n // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length\n // kRunningIdx points to the first running element.\n // kPendingIdx points to the first pending element.\n // This implements a fast queue with an amortized\n // time of O(1).\n\n this[kQueue] = []\n this[kRunningIdx] = 0\n this[kPendingIdx] = 0\n }\n\n get pipelining () {\n return this[kPipelining]\n }\n\n set pipelining (value) {\n this[kPipelining] = value\n resume(this, true)\n }\n\n get [kPending] () {\n return this[kQueue].length - this[kPendingIdx]\n }\n\n get [kRunning] () {\n return this[kPendingIdx] - this[kRunningIdx]\n }\n\n get [kSize] () {\n return this[kQueue].length - this[kRunningIdx]\n }\n\n get [kConnected] () {\n return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed\n }\n\n get [kBusy] () {\n const socket = this[kSocket]\n return (\n (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||\n (this[kSize] >= (this[kPipelining] || 1)) ||\n this[kPending] > 0\n )\n }\n\n /* istanbul ignore: only used for test */\n [kConnect] (cb) {\n connect(this)\n this.once('connect', cb)\n }\n\n [kDispatch] (opts, handler) {\n const origin = opts.origin || this[kUrl].origin\n\n const request = this[kHTTPConnVersion] === 'h2'\n ? Request[kHTTP2BuildRequest](origin, opts, handler)\n : Request[kHTTP1BuildRequest](origin, opts, handler)\n\n this[kQueue].push(request)\n if (this[kResuming]) {\n // Do nothing.\n } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {\n // Wait a tick in case stream/iterator is ended in the same tick.\n this[kResuming] = 1\n process.nextTick(resume, this)\n } else {\n resume(this, true)\n }\n\n if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {\n this[kNeedDrain] = 2\n }\n\n return this[kNeedDrain] < 2\n }\n\n async [kClose] () {\n // TODO: for H2 we need to gracefully flush the remaining enqueued\n // request and close each stream.\n return new Promise((resolve) => {\n if (!this[kSize]) {\n resolve(null)\n } else {\n this[kClosedResolve] = resolve\n }\n })\n }\n\n async [kDestroy] (err) {\n return new Promise((resolve) => {\n const requests = this[kQueue].splice(this[kPendingIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(this, request, err)\n }\n\n const callback = () => {\n if (this[kClosedResolve]) {\n // TODO (fix): Should we error here with ClientDestroyedError?\n this[kClosedResolve]()\n this[kClosedResolve] = null\n }\n resolve()\n }\n\n if (this[kHTTP2Session] != null) {\n util.destroy(this[kHTTP2Session], err)\n this[kHTTP2Session] = null\n this[kHTTP2SessionState] = null\n }\n\n if (!this[kSocket]) {\n queueMicrotask(callback)\n } else {\n util.destroy(this[kSocket].on('close', callback), err)\n }\n\n resume(this)\n })\n }\n}\n\nfunction onHttp2SessionError (err) {\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n this[kSocket][kError] = err\n\n onError(this[kClient], err)\n}\n\nfunction onHttp2FrameError (type, code, id) {\n const err = new InformationalError(`HTTP/2: \"frameError\" received - type ${type}, code ${code}`)\n\n if (id === 0) {\n this[kSocket][kError] = err\n onError(this[kClient], err)\n }\n}\n\nfunction onHttp2SessionEnd () {\n util.destroy(this, new SocketError('other side closed'))\n util.destroy(this[kSocket], new SocketError('other side closed'))\n}\n\nfunction onHTTP2GoAway (code) {\n const client = this[kClient]\n const err = new InformationalError(`HTTP/2: \"GOAWAY\" frame received with code ${code}`)\n client[kSocket] = null\n client[kHTTP2Session] = null\n\n if (client.destroyed) {\n assert(this[kPending] === 0)\n\n // Fail entire queue.\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(this, request, err)\n }\n } else if (client[kRunning] > 0) {\n // Fail head of pipeline.\n const request = client[kQueue][client[kRunningIdx]]\n client[kQueue][client[kRunningIdx]++] = null\n\n errorRequest(client, request, err)\n }\n\n client[kPendingIdx] = client[kRunningIdx]\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect',\n client[kUrl],\n [client],\n err\n )\n\n resume(client)\n}\n\nconst constants = require('./llhttp/constants')\nconst createRedirectInterceptor = require('./interceptor/redirectInterceptor')\nconst EMPTY_BUF = Buffer.alloc(0)\n\nasync function lazyllhttp () {\n const llhttpWasmData = process.env.JEST_WORKER_ID ? require('./llhttp/llhttp-wasm.js') : undefined\n\n let mod\n try {\n mod = await WebAssembly.compile(Buffer.from(require('./llhttp/llhttp_simd-wasm.js'), 'base64'))\n } catch (e) {\n /* istanbul ignore next */\n\n // We could check if the error was caused by the simd option not\n // being enabled, but the occurring of this other error\n // * https://github.com/emscripten-core/emscripten/issues/11495\n // got me to remove that check to avoid breaking Node 12.\n mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || require('./llhttp/llhttp-wasm.js'), 'base64'))\n }\n\n return await WebAssembly.instantiate(mod, {\n env: {\n /* eslint-disable camelcase */\n\n wasm_on_url: (p, at, len) => {\n /* istanbul ignore next */\n return 0\n },\n wasm_on_status: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_message_begin: (p) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onMessageBegin() || 0\n },\n wasm_on_header_field: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_header_value: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0\n },\n wasm_on_body: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_message_complete: (p) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onMessageComplete() || 0\n }\n\n /* eslint-enable camelcase */\n }\n })\n}\n\nlet llhttpInstance = null\nlet llhttpPromise = lazyllhttp()\nllhttpPromise.catch()\n\nlet currentParser = null\nlet currentBufferRef = null\nlet currentBufferSize = 0\nlet currentBufferPtr = null\n\nconst TIMEOUT_HEADERS = 1\nconst TIMEOUT_BODY = 2\nconst TIMEOUT_IDLE = 3\n\nclass Parser {\n constructor (client, socket, { exports }) {\n assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)\n\n this.llhttp = exports\n this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)\n this.client = client\n this.socket = socket\n this.timeout = null\n this.timeoutValue = null\n this.timeoutType = null\n this.statusCode = null\n this.statusText = ''\n this.upgrade = false\n this.headers = []\n this.headersSize = 0\n this.headersMaxSize = client[kMaxHeadersSize]\n this.shouldKeepAlive = false\n this.paused = false\n this.resume = this.resume.bind(this)\n\n this.bytesRead = 0\n\n this.keepAlive = ''\n this.contentLength = ''\n this.connection = ''\n this.maxResponseSize = client[kMaxResponseSize]\n }\n\n setTimeout (value, type) {\n this.timeoutType = type\n if (value !== this.timeoutValue) {\n timers.clearTimeout(this.timeout)\n if (value) {\n this.timeout = timers.setTimeout(onParserTimeout, value, this)\n // istanbul ignore else: only for jest\n if (this.timeout.unref) {\n this.timeout.unref()\n }\n } else {\n this.timeout = null\n }\n this.timeoutValue = value\n } else if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n }\n\n resume () {\n if (this.socket.destroyed || !this.paused) {\n return\n }\n\n assert(this.ptr != null)\n assert(currentParser == null)\n\n this.llhttp.llhttp_resume(this.ptr)\n\n assert(this.timeoutType === TIMEOUT_BODY)\n if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n this.paused = false\n this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.\n this.readMore()\n }\n\n readMore () {\n while (!this.paused && this.ptr) {\n const chunk = this.socket.read()\n if (chunk === null) {\n break\n }\n this.execute(chunk)\n }\n }\n\n execute (data) {\n assert(this.ptr != null)\n assert(currentParser == null)\n assert(!this.paused)\n\n const { socket, llhttp } = this\n\n if (data.length > currentBufferSize) {\n if (currentBufferPtr) {\n llhttp.free(currentBufferPtr)\n }\n currentBufferSize = Math.ceil(data.length / 4096) * 4096\n currentBufferPtr = llhttp.malloc(currentBufferSize)\n }\n\n new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)\n\n // Call `execute` on the wasm parser.\n // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,\n // and finally the length of bytes to parse.\n // The return value is an error code or `constants.ERROR.OK`.\n try {\n let ret\n\n try {\n currentBufferRef = data\n currentParser = this\n ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)\n /* eslint-disable-next-line no-useless-catch */\n } catch (err) {\n /* istanbul ignore next: difficult to make a test case for */\n throw err\n } finally {\n currentParser = null\n currentBufferRef = null\n }\n\n const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr\n\n if (ret === constants.ERROR.PAUSED_UPGRADE) {\n this.onUpgrade(data.slice(offset))\n } else if (ret === constants.ERROR.PAUSED) {\n this.paused = true\n socket.unshift(data.slice(offset))\n } else if (ret !== constants.ERROR.OK) {\n const ptr = llhttp.llhttp_get_error_reason(this.ptr)\n let message = ''\n /* istanbul ignore else: difficult to make a test case for */\n if (ptr) {\n const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)\n message =\n 'Response does not match the HTTP/1.1 protocol (' +\n Buffer.from(llhttp.memory.buffer, ptr, len).toString() +\n ')'\n }\n throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))\n }\n } catch (err) {\n util.destroy(socket, err)\n }\n }\n\n destroy () {\n assert(this.ptr != null)\n assert(currentParser == null)\n\n this.llhttp.llhttp_free(this.ptr)\n this.ptr = null\n\n timers.clearTimeout(this.timeout)\n this.timeout = null\n this.timeoutValue = null\n this.timeoutType = null\n\n this.paused = false\n }\n\n onStatus (buf) {\n this.statusText = buf.toString()\n }\n\n onMessageBegin () {\n const { socket, client } = this\n\n /* istanbul ignore next: difficult to make a test case for */\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n if (!request) {\n return -1\n }\n }\n\n onHeaderField (buf) {\n const len = this.headers.length\n\n if ((len & 1) === 0) {\n this.headers.push(buf)\n } else {\n this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])\n }\n\n this.trackHeader(buf.length)\n }\n\n onHeaderValue (buf) {\n let len = this.headers.length\n\n if ((len & 1) === 1) {\n this.headers.push(buf)\n len += 1\n } else {\n this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])\n }\n\n const key = this.headers[len - 2]\n if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {\n this.keepAlive += buf.toString()\n } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {\n this.connection += buf.toString()\n } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {\n this.contentLength += buf.toString()\n }\n\n this.trackHeader(buf.length)\n }\n\n trackHeader (len) {\n this.headersSize += len\n if (this.headersSize >= this.headersMaxSize) {\n util.destroy(this.socket, new HeadersOverflowError())\n }\n }\n\n onUpgrade (head) {\n const { upgrade, client, socket, headers, statusCode } = this\n\n assert(upgrade)\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert(!socket.destroyed)\n assert(socket === client[kSocket])\n assert(!this.paused)\n assert(request.upgrade || request.method === 'CONNECT')\n\n this.statusCode = null\n this.statusText = ''\n this.shouldKeepAlive = null\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n socket.unshift(head)\n\n socket[kParser].destroy()\n socket[kParser] = null\n\n socket[kClient] = null\n socket[kError] = null\n socket\n .removeListener('error', onSocketError)\n .removeListener('readable', onSocketReadable)\n .removeListener('end', onSocketEnd)\n .removeListener('close', onSocketClose)\n\n client[kSocket] = null\n client[kQueue][client[kRunningIdx]++] = null\n client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))\n\n try {\n request.onUpgrade(statusCode, headers, socket)\n } catch (err) {\n util.destroy(socket, err)\n }\n\n resume(client)\n }\n\n onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {\n const { client, socket, headers, statusText } = this\n\n /* istanbul ignore next: difficult to make a test case for */\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n\n /* istanbul ignore next: difficult to make a test case for */\n if (!request) {\n return -1\n }\n\n assert(!this.upgrade)\n assert(this.statusCode < 200)\n\n if (statusCode === 100) {\n util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))\n return -1\n }\n\n /* this can only happen if server is misbehaving */\n if (upgrade && !request.upgrade) {\n util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))\n return -1\n }\n\n assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)\n\n this.statusCode = statusCode\n this.shouldKeepAlive = (\n shouldKeepAlive ||\n // Override llhttp value which does not allow keepAlive for HEAD.\n (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')\n )\n\n if (this.statusCode >= 200) {\n const bodyTimeout = request.bodyTimeout != null\n ? request.bodyTimeout\n : client[kBodyTimeout]\n this.setTimeout(bodyTimeout, TIMEOUT_BODY)\n } else if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n if (request.method === 'CONNECT') {\n assert(client[kRunning] === 1)\n this.upgrade = true\n return 2\n }\n\n if (upgrade) {\n assert(client[kRunning] === 1)\n this.upgrade = true\n return 2\n }\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n if (this.shouldKeepAlive && client[kPipelining]) {\n const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null\n\n if (keepAliveTimeout != null) {\n const timeout = Math.min(\n keepAliveTimeout - client[kKeepAliveTimeoutThreshold],\n client[kKeepAliveMaxTimeout]\n )\n if (timeout <= 0) {\n socket[kReset] = true\n } else {\n client[kKeepAliveTimeoutValue] = timeout\n }\n } else {\n client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]\n }\n } else {\n // Stop more requests from being dispatched.\n socket[kReset] = true\n }\n\n const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false\n\n if (request.aborted) {\n return -1\n }\n\n if (request.method === 'HEAD') {\n return 1\n }\n\n if (statusCode < 200) {\n return 1\n }\n\n if (socket[kBlocking]) {\n socket[kBlocking] = false\n resume(client)\n }\n\n return pause ? constants.ERROR.PAUSED : 0\n }\n\n onBody (buf) {\n const { client, socket, statusCode, maxResponseSize } = this\n\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert.strictEqual(this.timeoutType, TIMEOUT_BODY)\n if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n assert(statusCode >= 200)\n\n if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {\n util.destroy(socket, new ResponseExceededMaxSizeError())\n return -1\n }\n\n this.bytesRead += buf.length\n\n if (request.onData(buf) === false) {\n return constants.ERROR.PAUSED\n }\n }\n\n onMessageComplete () {\n const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this\n\n if (socket.destroyed && (!statusCode || shouldKeepAlive)) {\n return -1\n }\n\n if (upgrade) {\n return\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert(statusCode >= 100)\n\n this.statusCode = null\n this.statusText = ''\n this.bytesRead = 0\n this.contentLength = ''\n this.keepAlive = ''\n this.connection = ''\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n if (statusCode < 200) {\n return\n }\n\n /* istanbul ignore next: should be handled by llhttp? */\n if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {\n util.destroy(socket, new ResponseContentLengthMismatchError())\n return -1\n }\n\n request.onComplete(headers)\n\n client[kQueue][client[kRunningIdx]++] = null\n\n if (socket[kWriting]) {\n assert.strictEqual(client[kRunning], 0)\n // Response completed before request.\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (!shouldKeepAlive) {\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (socket[kReset] && client[kRunning] === 0) {\n // Destroy socket once all requests have completed.\n // The request at the tail of the pipeline is the one\n // that requested reset and no further requests should\n // have been queued since then.\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (client[kPipelining] === 1) {\n // We must wait a full event loop cycle to reuse this socket to make sure\n // that non-spec compliant servers are not closing the connection even if they\n // said they won't.\n setImmediate(resume, client)\n } else {\n resume(client)\n }\n }\n}\n\nfunction onParserTimeout (parser) {\n const { socket, timeoutType, client } = parser\n\n /* istanbul ignore else */\n if (timeoutType === TIMEOUT_HEADERS) {\n if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {\n assert(!parser.paused, 'cannot be paused while waiting for headers')\n util.destroy(socket, new HeadersTimeoutError())\n }\n } else if (timeoutType === TIMEOUT_BODY) {\n if (!parser.paused) {\n util.destroy(socket, new BodyTimeoutError())\n }\n } else if (timeoutType === TIMEOUT_IDLE) {\n assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])\n util.destroy(socket, new InformationalError('socket idle timeout'))\n }\n}\n\nfunction onSocketReadable () {\n const { [kParser]: parser } = this\n if (parser) {\n parser.readMore()\n }\n}\n\nfunction onSocketError (err) {\n const { [kClient]: client, [kParser]: parser } = this\n\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n if (client[kHTTPConnVersion] !== 'h2') {\n // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded\n // to the user.\n if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so for as a valid response.\n parser.onMessageComplete()\n return\n }\n }\n\n this[kError] = err\n\n onError(this[kClient], err)\n}\n\nfunction onError (client, err) {\n if (\n client[kRunning] === 0 &&\n err.code !== 'UND_ERR_INFO' &&\n err.code !== 'UND_ERR_SOCKET'\n ) {\n // Error is not caused by running request and not a recoverable\n // socket error.\n\n assert(client[kPendingIdx] === client[kRunningIdx])\n\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(client, request, err)\n }\n assert(client[kSize] === 0)\n }\n}\n\nfunction onSocketEnd () {\n const { [kParser]: parser, [kClient]: client } = this\n\n if (client[kHTTPConnVersion] !== 'h2') {\n if (parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so far as a valid response.\n parser.onMessageComplete()\n return\n }\n }\n\n util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))\n}\n\nfunction onSocketClose () {\n const { [kClient]: client, [kParser]: parser } = this\n\n if (client[kHTTPConnVersion] === 'h1' && parser) {\n if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so far as a valid response.\n parser.onMessageComplete()\n }\n\n this[kParser].destroy()\n this[kParser] = null\n }\n\n const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))\n\n client[kSocket] = null\n\n if (client.destroyed) {\n assert(client[kPending] === 0)\n\n // Fail entire queue.\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(client, request, err)\n }\n } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {\n // Fail head of pipeline.\n const request = client[kQueue][client[kRunningIdx]]\n client[kQueue][client[kRunningIdx]++] = null\n\n errorRequest(client, request, err)\n }\n\n client[kPendingIdx] = client[kRunningIdx]\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect', client[kUrl], [client], err)\n\n resume(client)\n}\n\nasync function connect (client) {\n assert(!client[kConnecting])\n assert(!client[kSocket])\n\n let { host, hostname, protocol, port } = client[kUrl]\n\n // Resolve ipv6\n if (hostname[0] === '[') {\n const idx = hostname.indexOf(']')\n\n assert(idx !== -1)\n const ip = hostname.substring(1, idx)\n\n assert(net.isIP(ip))\n hostname = ip\n }\n\n client[kConnecting] = true\n\n if (channels.beforeConnect.hasSubscribers) {\n channels.beforeConnect.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector]\n })\n }\n\n try {\n const socket = await new Promise((resolve, reject) => {\n client[kConnector]({\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n }, (err, socket) => {\n if (err) {\n reject(err)\n } else {\n resolve(socket)\n }\n })\n })\n\n if (client.destroyed) {\n util.destroy(socket.on('error', () => {}), new ClientDestroyedError())\n return\n }\n\n client[kConnecting] = false\n\n assert(socket)\n\n const isH2 = socket.alpnProtocol === 'h2'\n if (isH2) {\n if (!h2ExperimentalWarned) {\n h2ExperimentalWarned = true\n process.emitWarning('H2 support is experimental, expect them to change at any time.', {\n code: 'UNDICI-H2'\n })\n }\n\n const session = http2.connect(client[kUrl], {\n createConnection: () => socket,\n peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams\n })\n\n client[kHTTPConnVersion] = 'h2'\n session[kClient] = client\n session[kSocket] = socket\n session.on('error', onHttp2SessionError)\n session.on('frameError', onHttp2FrameError)\n session.on('end', onHttp2SessionEnd)\n session.on('goaway', onHTTP2GoAway)\n session.on('close', onSocketClose)\n session.unref()\n\n client[kHTTP2Session] = session\n socket[kHTTP2Session] = session\n } else {\n if (!llhttpInstance) {\n llhttpInstance = await llhttpPromise\n llhttpPromise = null\n }\n\n socket[kNoRef] = false\n socket[kWriting] = false\n socket[kReset] = false\n socket[kBlocking] = false\n socket[kParser] = new Parser(client, socket, llhttpInstance)\n }\n\n socket[kCounter] = 0\n socket[kMaxRequests] = client[kMaxRequests]\n socket[kClient] = client\n socket[kError] = null\n\n socket\n .on('error', onSocketError)\n .on('readable', onSocketReadable)\n .on('end', onSocketEnd)\n .on('close', onSocketClose)\n\n client[kSocket] = socket\n\n if (channels.connected.hasSubscribers) {\n channels.connected.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector],\n socket\n })\n }\n client.emit('connect', client[kUrl], [client])\n } catch (err) {\n if (client.destroyed) {\n return\n }\n\n client[kConnecting] = false\n\n if (channels.connectError.hasSubscribers) {\n channels.connectError.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector],\n error: err\n })\n }\n\n if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {\n assert(client[kRunning] === 0)\n while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {\n const request = client[kQueue][client[kPendingIdx]++]\n errorRequest(client, request, err)\n }\n } else {\n onError(client, err)\n }\n\n client.emit('connectionError', client[kUrl], [client], err)\n }\n\n resume(client)\n}\n\nfunction emitDrain (client) {\n client[kNeedDrain] = 0\n client.emit('drain', client[kUrl], [client])\n}\n\nfunction resume (client, sync) {\n if (client[kResuming] === 2) {\n return\n }\n\n client[kResuming] = 2\n\n _resume(client, sync)\n client[kResuming] = 0\n\n if (client[kRunningIdx] > 256) {\n client[kQueue].splice(0, client[kRunningIdx])\n client[kPendingIdx] -= client[kRunningIdx]\n client[kRunningIdx] = 0\n }\n}\n\nfunction _resume (client, sync) {\n while (true) {\n if (client.destroyed) {\n assert(client[kPending] === 0)\n return\n }\n\n if (client[kClosedResolve] && !client[kSize]) {\n client[kClosedResolve]()\n client[kClosedResolve] = null\n return\n }\n\n const socket = client[kSocket]\n\n if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {\n if (client[kSize] === 0) {\n if (!socket[kNoRef] && socket.unref) {\n socket.unref()\n socket[kNoRef] = true\n }\n } else if (socket[kNoRef] && socket.ref) {\n socket.ref()\n socket[kNoRef] = false\n }\n\n if (client[kSize] === 0) {\n if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {\n socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)\n }\n } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {\n if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {\n const request = client[kQueue][client[kRunningIdx]]\n const headersTimeout = request.headersTimeout != null\n ? request.headersTimeout\n : client[kHeadersTimeout]\n socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)\n }\n }\n }\n\n if (client[kBusy]) {\n client[kNeedDrain] = 2\n } else if (client[kNeedDrain] === 2) {\n if (sync) {\n client[kNeedDrain] = 1\n process.nextTick(emitDrain, client)\n } else {\n emitDrain(client)\n }\n continue\n }\n\n if (client[kPending] === 0) {\n return\n }\n\n if (client[kRunning] >= (client[kPipelining] || 1)) {\n return\n }\n\n const request = client[kQueue][client[kPendingIdx]]\n\n if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {\n if (client[kRunning] > 0) {\n return\n }\n\n client[kServerName] = request.servername\n\n if (socket && socket.servername !== request.servername) {\n util.destroy(socket, new InformationalError('servername changed'))\n return\n }\n }\n\n if (client[kConnecting]) {\n return\n }\n\n if (!socket && !client[kHTTP2Session]) {\n connect(client)\n return\n }\n\n if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {\n return\n }\n\n if (client[kRunning] > 0 && !request.idempotent) {\n // Non-idempotent request cannot be retried.\n // Ensure that no other requests are inflight and\n // could cause failure.\n return\n }\n\n if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {\n // Don't dispatch an upgrade until all preceding requests have completed.\n // A misbehaving server might upgrade the connection before all pipelined\n // request has completed.\n return\n }\n\n if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&\n (util.isStream(request.body) || util.isAsyncIterable(request.body))) {\n // Request with stream or iterator body can error while other requests\n // are inflight and indirectly error those as well.\n // Ensure this doesn't happen by waiting for inflight\n // to complete before dispatching.\n\n // Request with stream or iterator body cannot be retried.\n // Ensure that no other requests are inflight and\n // could cause failure.\n return\n }\n\n if (!request.aborted && write(client, request)) {\n client[kPendingIdx]++\n } else {\n client[kQueue].splice(client[kPendingIdx], 1)\n }\n }\n}\n\n// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2\nfunction shouldSendContentLength (method) {\n return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'\n}\n\nfunction write (client, request) {\n if (client[kHTTPConnVersion] === 'h2') {\n writeH2(client, client[kHTTP2Session], request)\n return\n }\n\n const { body, method, path, host, upgrade, headers, blocking, reset } = request\n\n // https://tools.ietf.org/html/rfc7231#section-4.3.1\n // https://tools.ietf.org/html/rfc7231#section-4.3.2\n // https://tools.ietf.org/html/rfc7231#section-4.3.5\n\n // Sending a payload body on a request that does not\n // expect it can cause undefined behavior on some\n // servers and corrupt connection state. Do not\n // re-use the connection for further requests.\n\n const expectsPayload = (\n method === 'PUT' ||\n method === 'POST' ||\n method === 'PATCH'\n )\n\n if (body && typeof body.read === 'function') {\n // Try to read EOF in order to get length.\n body.read(0)\n }\n\n const bodyLength = util.bodyLength(body)\n\n let contentLength = bodyLength\n\n if (contentLength === null) {\n contentLength = request.contentLength\n }\n\n if (contentLength === 0 && !expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD NOT send a Content-Length header field when\n // the request message does not contain a payload body and the method\n // semantics do not anticipate such a body.\n\n contentLength = null\n }\n\n // https://github.com/nodejs/undici/issues/2046\n // A user agent may send a Content-Length header with 0 value, this should be allowed.\n if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {\n if (client[kStrictContentLength]) {\n errorRequest(client, request, new RequestContentLengthMismatchError())\n return false\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n const socket = client[kSocket]\n\n try {\n request.onConnect((err) => {\n if (request.aborted || request.completed) {\n return\n }\n\n errorRequest(client, request, err || new RequestAbortedError())\n\n util.destroy(socket, new InformationalError('aborted'))\n })\n } catch (err) {\n errorRequest(client, request, err)\n }\n\n if (request.aborted) {\n return false\n }\n\n if (method === 'HEAD') {\n // https://github.com/mcollina/undici/issues/258\n // Close after a HEAD request to interop with misbehaving servers\n // that may send a body in the response.\n\n socket[kReset] = true\n }\n\n if (upgrade || method === 'CONNECT') {\n // On CONNECT or upgrade, block pipeline from dispatching further\n // requests on this connection.\n\n socket[kReset] = true\n }\n\n if (reset != null) {\n socket[kReset] = reset\n }\n\n if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {\n socket[kReset] = true\n }\n\n if (blocking) {\n socket[kBlocking] = true\n }\n\n let header = `${method} ${path} HTTP/1.1\\r\\n`\n\n if (typeof host === 'string') {\n header += `host: ${host}\\r\\n`\n } else {\n header += client[kHostHeader]\n }\n\n if (upgrade) {\n header += `connection: upgrade\\r\\nupgrade: ${upgrade}\\r\\n`\n } else if (client[kPipelining] && !socket[kReset]) {\n header += 'connection: keep-alive\\r\\n'\n } else {\n header += 'connection: close\\r\\n'\n }\n\n if (headers) {\n header += headers\n }\n\n if (channels.sendHeaders.hasSubscribers) {\n channels.sendHeaders.publish({ request, headers: header, socket })\n }\n\n /* istanbul ignore else: assertion */\n if (!body || bodyLength === 0) {\n if (contentLength === 0) {\n socket.write(`${header}content-length: 0\\r\\n\\r\\n`, 'latin1')\n } else {\n assert(contentLength === null, 'no body must not have content length')\n socket.write(`${header}\\r\\n`, 'latin1')\n }\n request.onRequestSent()\n } else if (util.isBuffer(body)) {\n assert(contentLength === body.byteLength, 'buffer body must have content length')\n\n socket.cork()\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n socket.write(body)\n socket.uncork()\n request.onBodySent(body)\n request.onRequestSent()\n if (!expectsPayload) {\n socket[kReset] = true\n }\n } else if (util.isBlobLike(body)) {\n if (typeof body.stream === 'function') {\n writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })\n } else {\n writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })\n }\n } else if (util.isStream(body)) {\n writeStream({ body, client, request, socket, contentLength, header, expectsPayload })\n } else if (util.isIterable(body)) {\n writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })\n } else {\n assert(false)\n }\n\n return true\n}\n\nfunction writeH2 (client, session, request) {\n const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request\n\n let headers\n if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())\n else headers = reqHeaders\n\n if (upgrade) {\n errorRequest(client, request, new Error('Upgrade not supported for H2'))\n return false\n }\n\n try {\n // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?\n request.onConnect((err) => {\n if (request.aborted || request.completed) {\n return\n }\n\n errorRequest(client, request, err || new RequestAbortedError())\n })\n } catch (err) {\n errorRequest(client, request, err)\n }\n\n if (request.aborted) {\n return false\n }\n\n /** @type {import('node:http2').ClientHttp2Stream} */\n let stream\n const h2State = client[kHTTP2SessionState]\n\n headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]\n headers[HTTP2_HEADER_METHOD] = method\n\n if (method === 'CONNECT') {\n session.ref()\n // we are already connected, streams are pending, first request\n // will create a new stream. We trigger a request to create the stream and wait until\n // `ready` event is triggered\n // We disabled endStream to allow the user to write to the stream\n stream = session.request(headers, { endStream: false, signal })\n\n if (stream.id && !stream.pending) {\n request.onUpgrade(null, null, stream)\n ++h2State.openStreams\n } else {\n stream.once('ready', () => {\n request.onUpgrade(null, null, stream)\n ++h2State.openStreams\n })\n }\n\n stream.once('close', () => {\n h2State.openStreams -= 1\n // TODO(HTTP/2): unref only if current streams count is 0\n if (h2State.openStreams === 0) session.unref()\n })\n\n return true\n }\n\n // https://tools.ietf.org/html/rfc7540#section-8.3\n // :path and :scheme headers must be omited when sending CONNECT\n\n headers[HTTP2_HEADER_PATH] = path\n headers[HTTP2_HEADER_SCHEME] = 'https'\n\n // https://tools.ietf.org/html/rfc7231#section-4.3.1\n // https://tools.ietf.org/html/rfc7231#section-4.3.2\n // https://tools.ietf.org/html/rfc7231#section-4.3.5\n\n // Sending a payload body on a request that does not\n // expect it can cause undefined behavior on some\n // servers and corrupt connection state. Do not\n // re-use the connection for further requests.\n\n const expectsPayload = (\n method === 'PUT' ||\n method === 'POST' ||\n method === 'PATCH'\n )\n\n if (body && typeof body.read === 'function') {\n // Try to read EOF in order to get length.\n body.read(0)\n }\n\n let contentLength = util.bodyLength(body)\n\n if (contentLength == null) {\n contentLength = request.contentLength\n }\n\n if (contentLength === 0 || !expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD NOT send a Content-Length header field when\n // the request message does not contain a payload body and the method\n // semantics do not anticipate such a body.\n\n contentLength = null\n }\n\n // https://github.com/nodejs/undici/issues/2046\n // A user agent may send a Content-Length header with 0 value, this should be allowed.\n if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {\n if (client[kStrictContentLength]) {\n errorRequest(client, request, new RequestContentLengthMismatchError())\n return false\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n if (contentLength != null) {\n assert(body, 'no body must not have content length')\n headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`\n }\n\n session.ref()\n\n const shouldEndStream = method === 'GET' || method === 'HEAD'\n if (expectContinue) {\n headers[HTTP2_HEADER_EXPECT] = '100-continue'\n stream = session.request(headers, { endStream: shouldEndStream, signal })\n\n stream.once('continue', writeBodyH2)\n } else {\n stream = session.request(headers, {\n endStream: shouldEndStream,\n signal\n })\n writeBodyH2()\n }\n\n // Increment counter as we have new several streams open\n ++h2State.openStreams\n\n stream.once('response', headers => {\n const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers\n\n if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {\n stream.pause()\n }\n })\n\n stream.once('end', () => {\n request.onComplete([])\n })\n\n stream.on('data', (chunk) => {\n if (request.onData(chunk) === false) {\n stream.pause()\n }\n })\n\n stream.once('close', () => {\n h2State.openStreams -= 1\n // TODO(HTTP/2): unref only if current streams count is 0\n if (h2State.openStreams === 0) {\n session.unref()\n }\n })\n\n stream.once('error', function (err) {\n if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {\n h2State.streams -= 1\n util.destroy(stream, err)\n }\n })\n\n stream.once('frameError', (type, code) => {\n const err = new InformationalError(`HTTP/2: \"frameError\" received - type ${type}, code ${code}`)\n errorRequest(client, request, err)\n\n if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {\n h2State.streams -= 1\n util.destroy(stream, err)\n }\n })\n\n // stream.on('aborted', () => {\n // // TODO(HTTP/2): Support aborted\n // })\n\n // stream.on('timeout', () => {\n // // TODO(HTTP/2): Support timeout\n // })\n\n // stream.on('push', headers => {\n // // TODO(HTTP/2): Suppor push\n // })\n\n // stream.on('trailers', headers => {\n // // TODO(HTTP/2): Support trailers\n // })\n\n return true\n\n function writeBodyH2 () {\n /* istanbul ignore else: assertion */\n if (!body) {\n request.onRequestSent()\n } else if (util.isBuffer(body)) {\n assert(contentLength === body.byteLength, 'buffer body must have content length')\n stream.cork()\n stream.write(body)\n stream.uncork()\n stream.end()\n request.onBodySent(body)\n request.onRequestSent()\n } else if (util.isBlobLike(body)) {\n if (typeof body.stream === 'function') {\n writeIterable({\n client,\n request,\n contentLength,\n h2stream: stream,\n expectsPayload,\n body: body.stream(),\n socket: client[kSocket],\n header: ''\n })\n } else {\n writeBlob({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n h2stream: stream,\n header: '',\n socket: client[kSocket]\n })\n }\n } else if (util.isStream(body)) {\n writeStream({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n socket: client[kSocket],\n h2stream: stream,\n header: ''\n })\n } else if (util.isIterable(body)) {\n writeIterable({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n header: '',\n h2stream: stream,\n socket: client[kSocket]\n })\n } else {\n assert(false)\n }\n }\n}\n\nfunction writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')\n\n if (client[kHTTPConnVersion] === 'h2') {\n // For HTTP/2, is enough to pipe the stream\n const pipe = pipeline(\n body,\n h2stream,\n (err) => {\n if (err) {\n util.destroy(body, err)\n util.destroy(h2stream, err)\n } else {\n request.onRequestSent()\n }\n }\n )\n\n pipe.on('data', onPipeData)\n pipe.once('end', () => {\n pipe.removeListener('data', onPipeData)\n util.destroy(pipe)\n })\n\n function onPipeData (chunk) {\n request.onBodySent(chunk)\n }\n\n return\n }\n\n let finished = false\n\n const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })\n\n const onData = function (chunk) {\n if (finished) {\n return\n }\n\n try {\n if (!writer.write(chunk) && this.pause) {\n this.pause()\n }\n } catch (err) {\n util.destroy(this, err)\n }\n }\n const onDrain = function () {\n if (finished) {\n return\n }\n\n if (body.resume) {\n body.resume()\n }\n }\n const onAbort = function () {\n if (finished) {\n return\n }\n const err = new RequestAbortedError()\n queueMicrotask(() => onFinished(err))\n }\n const onFinished = function (err) {\n if (finished) {\n return\n }\n\n finished = true\n\n assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))\n\n socket\n .off('drain', onDrain)\n .off('error', onFinished)\n\n body\n .removeListener('data', onData)\n .removeListener('end', onFinished)\n .removeListener('error', onFinished)\n .removeListener('close', onAbort)\n\n if (!err) {\n try {\n writer.end()\n } catch (er) {\n err = er\n }\n }\n\n writer.destroy(err)\n\n if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {\n util.destroy(body, err)\n } else {\n util.destroy(body)\n }\n }\n\n body\n .on('data', onData)\n .on('end', onFinished)\n .on('error', onFinished)\n .on('close', onAbort)\n\n if (body.resume) {\n body.resume()\n }\n\n socket\n .on('drain', onDrain)\n .on('error', onFinished)\n}\n\nasync function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength === body.size, 'blob body must have content length')\n\n const isH2 = client[kHTTPConnVersion] === 'h2'\n try {\n if (contentLength != null && contentLength !== body.size) {\n throw new RequestContentLengthMismatchError()\n }\n\n const buffer = Buffer.from(await body.arrayBuffer())\n\n if (isH2) {\n h2stream.cork()\n h2stream.write(buffer)\n h2stream.uncork()\n } else {\n socket.cork()\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n socket.write(buffer)\n socket.uncork()\n }\n\n request.onBodySent(buffer)\n request.onRequestSent()\n\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n resume(client)\n } catch (err) {\n util.destroy(isH2 ? h2stream : socket, err)\n }\n}\n\nasync function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')\n\n let callback = null\n function onDrain () {\n if (callback) {\n const cb = callback\n callback = null\n cb()\n }\n }\n\n const waitForDrain = () => new Promise((resolve, reject) => {\n assert(callback === null)\n\n if (socket[kError]) {\n reject(socket[kError])\n } else {\n callback = resolve\n }\n })\n\n if (client[kHTTPConnVersion] === 'h2') {\n h2stream\n .on('close', onDrain)\n .on('drain', onDrain)\n\n try {\n // It's up to the user to somehow abort the async iterable.\n for await (const chunk of body) {\n if (socket[kError]) {\n throw socket[kError]\n }\n\n const res = h2stream.write(chunk)\n request.onBodySent(chunk)\n if (!res) {\n await waitForDrain()\n }\n }\n } catch (err) {\n h2stream.destroy(err)\n } finally {\n request.onRequestSent()\n h2stream.end()\n h2stream\n .off('close', onDrain)\n .off('drain', onDrain)\n }\n\n return\n }\n\n socket\n .on('close', onDrain)\n .on('drain', onDrain)\n\n const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })\n try {\n // It's up to the user to somehow abort the async iterable.\n for await (const chunk of body) {\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (!writer.write(chunk)) {\n await waitForDrain()\n }\n }\n\n writer.end()\n } catch (err) {\n writer.destroy(err)\n } finally {\n socket\n .off('close', onDrain)\n .off('drain', onDrain)\n }\n}\n\nclass AsyncWriter {\n constructor ({ socket, request, contentLength, client, expectsPayload, header }) {\n this.socket = socket\n this.request = request\n this.contentLength = contentLength\n this.client = client\n this.bytesWritten = 0\n this.expectsPayload = expectsPayload\n this.header = header\n\n socket[kWriting] = true\n }\n\n write (chunk) {\n const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this\n\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (socket.destroyed) {\n return false\n }\n\n const len = Buffer.byteLength(chunk)\n if (!len) {\n return true\n }\n\n // We should defer writing chunks.\n if (contentLength !== null && bytesWritten + len > contentLength) {\n if (client[kStrictContentLength]) {\n throw new RequestContentLengthMismatchError()\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n socket.cork()\n\n if (bytesWritten === 0) {\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n if (contentLength === null) {\n socket.write(`${header}transfer-encoding: chunked\\r\\n`, 'latin1')\n } else {\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n }\n }\n\n if (contentLength === null) {\n socket.write(`\\r\\n${len.toString(16)}\\r\\n`, 'latin1')\n }\n\n this.bytesWritten += len\n\n const ret = socket.write(chunk)\n\n socket.uncork()\n\n request.onBodySent(chunk)\n\n if (!ret) {\n if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {\n // istanbul ignore else: only for jest\n if (socket[kParser].timeout.refresh) {\n socket[kParser].timeout.refresh()\n }\n }\n }\n\n return ret\n }\n\n end () {\n const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this\n request.onRequestSent()\n\n socket[kWriting] = false\n\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (socket.destroyed) {\n return\n }\n\n if (bytesWritten === 0) {\n if (expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD send a Content-Length in a request message when\n // no Transfer-Encoding is sent and the request method defines a meaning\n // for an enclosed payload body.\n\n socket.write(`${header}content-length: 0\\r\\n\\r\\n`, 'latin1')\n } else {\n socket.write(`${header}\\r\\n`, 'latin1')\n }\n } else if (contentLength === null) {\n socket.write('\\r\\n0\\r\\n\\r\\n', 'latin1')\n }\n\n if (contentLength !== null && bytesWritten !== contentLength) {\n if (client[kStrictContentLength]) {\n throw new RequestContentLengthMismatchError()\n } else {\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n }\n\n if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {\n // istanbul ignore else: only for jest\n if (socket[kParser].timeout.refresh) {\n socket[kParser].timeout.refresh()\n }\n }\n\n resume(client)\n }\n\n destroy (err) {\n const { socket, client } = this\n\n socket[kWriting] = false\n\n if (err) {\n assert(client[kRunning] <= 1, 'pipeline should only contain this request')\n util.destroy(socket, err)\n }\n }\n}\n\nfunction errorRequest (client, request, err) {\n try {\n request.onError(err)\n assert(request.aborted)\n } catch (err) {\n client.emit('error', err)\n }\n}\n\nmodule.exports = Client\n","'use strict'\n\n/* istanbul ignore file: only for Node 12 */\n\nconst { kConnected, kSize } = require('../core/symbols')\n\nclass CompatWeakRef {\n constructor (value) {\n this.value = value\n }\n\n deref () {\n return this.value[kConnected] === 0 && this.value[kSize] === 0\n ? undefined\n : this.value\n }\n}\n\nclass CompatFinalizer {\n constructor (finalizer) {\n this.finalizer = finalizer\n }\n\n register (dispatcher, key) {\n if (dispatcher.on) {\n dispatcher.on('disconnect', () => {\n if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {\n this.finalizer(key)\n }\n })\n }\n }\n}\n\nmodule.exports = function () {\n // FIXME: remove workaround when the Node bug is fixed\n // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308\n if (process.env.NODE_V8_COVERAGE) {\n return {\n WeakRef: CompatWeakRef,\n FinalizationRegistry: CompatFinalizer\n }\n }\n return {\n WeakRef: global.WeakRef || CompatWeakRef,\n FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer\n }\n}\n","'use strict'\n\n// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size\nconst maxAttributeValueSize = 1024\n\n// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size\nconst maxNameValuePairSize = 4096\n\nmodule.exports = {\n maxAttributeValueSize,\n maxNameValuePairSize\n}\n","'use strict'\n\nconst { parseSetCookie } = require('./parse')\nconst { stringify, getHeadersList } = require('./util')\nconst { webidl } = require('../fetch/webidl')\nconst { Headers } = require('../fetch/headers')\n\n/**\n * @typedef {Object} Cookie\n * @property {string} name\n * @property {string} value\n * @property {Date|number|undefined} expires\n * @property {number|undefined} maxAge\n * @property {string|undefined} domain\n * @property {string|undefined} path\n * @property {boolean|undefined} secure\n * @property {boolean|undefined} httpOnly\n * @property {'Strict'|'Lax'|'None'} sameSite\n * @property {string[]} unparsed\n */\n\n/**\n * @param {Headers} headers\n * @returns {Record}\n */\nfunction getCookies (headers) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const cookie = headers.get('cookie')\n const out = {}\n\n if (!cookie) {\n return out\n }\n\n for (const piece of cookie.split(';')) {\n const [name, ...value] = piece.split('=')\n\n out[name.trim()] = value.join('=')\n }\n\n return out\n}\n\n/**\n * @param {Headers} headers\n * @param {string} name\n * @param {{ path?: string, domain?: string }|undefined} attributes\n * @returns {void}\n */\nfunction deleteCookie (headers, name, attributes) {\n webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n name = webidl.converters.DOMString(name)\n attributes = webidl.converters.DeleteCookieAttributes(attributes)\n\n // Matches behavior of\n // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278\n setCookie(headers, {\n name,\n value: '',\n expires: new Date(0),\n ...attributes\n })\n}\n\n/**\n * @param {Headers} headers\n * @returns {Cookie[]}\n */\nfunction getSetCookies (headers) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const cookies = getHeadersList(headers).cookies\n\n if (!cookies) {\n return []\n }\n\n // In older versions of undici, cookies is a list of name:value.\n return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))\n}\n\n/**\n * @param {Headers} headers\n * @param {Cookie} cookie\n * @returns {void}\n */\nfunction setCookie (headers, cookie) {\n webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n cookie = webidl.converters.Cookie(cookie)\n\n const str = stringify(cookie)\n\n if (str) {\n headers.append('Set-Cookie', stringify(cookie))\n }\n}\n\nwebidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'path',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'domain',\n defaultValue: null\n }\n])\n\nwebidl.converters.Cookie = webidl.dictionaryConverter([\n {\n converter: webidl.converters.DOMString,\n key: 'name'\n },\n {\n converter: webidl.converters.DOMString,\n key: 'value'\n },\n {\n converter: webidl.nullableConverter((value) => {\n if (typeof value === 'number') {\n return webidl.converters['unsigned long long'](value)\n }\n\n return new Date(value)\n }),\n key: 'expires',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters['long long']),\n key: 'maxAge',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'domain',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'path',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.boolean),\n key: 'secure',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.boolean),\n key: 'httpOnly',\n defaultValue: null\n },\n {\n converter: webidl.converters.USVString,\n key: 'sameSite',\n allowedValues: ['Strict', 'Lax', 'None']\n },\n {\n converter: webidl.sequenceConverter(webidl.converters.DOMString),\n key: 'unparsed',\n defaultValue: []\n }\n])\n\nmodule.exports = {\n getCookies,\n deleteCookie,\n getSetCookies,\n setCookie\n}\n","'use strict'\n\nconst { maxNameValuePairSize, maxAttributeValueSize } = require('./constants')\nconst { isCTLExcludingHtab } = require('./util')\nconst { collectASequenceOfCodePointsFast } = require('../fetch/dataURL')\nconst assert = require('assert')\n\n/**\n * @description Parses the field-value attributes of a set-cookie header string.\n * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4\n * @param {string} header\n * @returns if the header is invalid, null will be returned\n */\nfunction parseSetCookie (header) {\n // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F\n // character (CTL characters excluding HTAB): Abort these steps and\n // ignore the set-cookie-string entirely.\n if (isCTLExcludingHtab(header)) {\n return null\n }\n\n let nameValuePair = ''\n let unparsedAttributes = ''\n let name = ''\n let value = ''\n\n // 2. If the set-cookie-string contains a %x3B (\";\") character:\n if (header.includes(';')) {\n // 1. The name-value-pair string consists of the characters up to,\n // but not including, the first %x3B (\";\"), and the unparsed-\n // attributes consist of the remainder of the set-cookie-string\n // (including the %x3B (\";\") in question).\n const position = { position: 0 }\n\n nameValuePair = collectASequenceOfCodePointsFast(';', header, position)\n unparsedAttributes = header.slice(position.position)\n } else {\n // Otherwise:\n\n // 1. The name-value-pair string consists of all the characters\n // contained in the set-cookie-string, and the unparsed-\n // attributes is the empty string.\n nameValuePair = header\n }\n\n // 3. If the name-value-pair string lacks a %x3D (\"=\") character, then\n // the name string is empty, and the value string is the value of\n // name-value-pair.\n if (!nameValuePair.includes('=')) {\n value = nameValuePair\n } else {\n // Otherwise, the name string consists of the characters up to, but\n // not including, the first %x3D (\"=\") character, and the (possibly\n // empty) value string consists of the characters after the first\n // %x3D (\"=\") character.\n const position = { position: 0 }\n name = collectASequenceOfCodePointsFast(\n '=',\n nameValuePair,\n position\n )\n value = nameValuePair.slice(position.position + 1)\n }\n\n // 4. Remove any leading or trailing WSP characters from the name\n // string and the value string.\n name = name.trim()\n value = value.trim()\n\n // 5. If the sum of the lengths of the name string and the value string\n // is more than 4096 octets, abort these steps and ignore the set-\n // cookie-string entirely.\n if (name.length + value.length > maxNameValuePairSize) {\n return null\n }\n\n // 6. The cookie-name is the name string, and the cookie-value is the\n // value string.\n return {\n name, value, ...parseUnparsedAttributes(unparsedAttributes)\n }\n}\n\n/**\n * Parses the remaining attributes of a set-cookie header\n * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4\n * @param {string} unparsedAttributes\n * @param {[Object.]={}} cookieAttributeList\n */\nfunction parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {\n // 1. If the unparsed-attributes string is empty, skip the rest of\n // these steps.\n if (unparsedAttributes.length === 0) {\n return cookieAttributeList\n }\n\n // 2. Discard the first character of the unparsed-attributes (which\n // will be a %x3B (\";\") character).\n assert(unparsedAttributes[0] === ';')\n unparsedAttributes = unparsedAttributes.slice(1)\n\n let cookieAv = ''\n\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n if (unparsedAttributes.includes(';')) {\n // 1. Consume the characters of the unparsed-attributes up to, but\n // not including, the first %x3B (\";\") character.\n cookieAv = collectASequenceOfCodePointsFast(\n ';',\n unparsedAttributes,\n { position: 0 }\n )\n unparsedAttributes = unparsedAttributes.slice(cookieAv.length)\n } else {\n // Otherwise:\n\n // 1. Consume the remainder of the unparsed-attributes.\n cookieAv = unparsedAttributes\n unparsedAttributes = ''\n }\n\n // Let the cookie-av string be the characters consumed in this step.\n\n let attributeName = ''\n let attributeValue = ''\n\n // 4. If the cookie-av string contains a %x3D (\"=\") character:\n if (cookieAv.includes('=')) {\n // 1. The (possibly empty) attribute-name string consists of the\n // characters up to, but not including, the first %x3D (\"=\")\n // character, and the (possibly empty) attribute-value string\n // consists of the characters after the first %x3D (\"=\")\n // character.\n const position = { position: 0 }\n\n attributeName = collectASequenceOfCodePointsFast(\n '=',\n cookieAv,\n position\n )\n attributeValue = cookieAv.slice(position.position + 1)\n } else {\n // Otherwise:\n\n // 1. The attribute-name string consists of the entire cookie-av\n // string, and the attribute-value string is empty.\n attributeName = cookieAv\n }\n\n // 5. Remove any leading or trailing WSP characters from the attribute-\n // name string and the attribute-value string.\n attributeName = attributeName.trim()\n attributeValue = attributeValue.trim()\n\n // 6. If the attribute-value is longer than 1024 octets, ignore the\n // cookie-av string and return to Step 1 of this algorithm.\n if (attributeValue.length > maxAttributeValueSize) {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 7. Process the attribute-name and attribute-value according to the\n // requirements in the following subsections. (Notice that\n // attributes with unrecognized attribute-names are ignored.)\n const attributeNameLowercase = attributeName.toLowerCase()\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1\n // If the attribute-name case-insensitively matches the string\n // \"Expires\", the user agent MUST process the cookie-av as follows.\n if (attributeNameLowercase === 'expires') {\n // 1. Let the expiry-time be the result of parsing the attribute-value\n // as cookie-date (see Section 5.1.1).\n const expiryTime = new Date(attributeValue)\n\n // 2. If the attribute-value failed to parse as a cookie date, ignore\n // the cookie-av.\n\n cookieAttributeList.expires = expiryTime\n } else if (attributeNameLowercase === 'max-age') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2\n // If the attribute-name case-insensitively matches the string \"Max-\n // Age\", the user agent MUST process the cookie-av as follows.\n\n // 1. If the first character of the attribute-value is not a DIGIT or a\n // \"-\" character, ignore the cookie-av.\n const charCode = attributeValue.charCodeAt(0)\n\n if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 2. If the remainder of attribute-value contains a non-DIGIT\n // character, ignore the cookie-av.\n if (!/^\\d+$/.test(attributeValue)) {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 3. Let delta-seconds be the attribute-value converted to an integer.\n const deltaSeconds = Number(attributeValue)\n\n // 4. Let cookie-age-limit be the maximum age of the cookie (which\n // SHOULD be 400 days or less, see Section 4.1.2.2).\n\n // 5. Set delta-seconds to the smaller of its present value and cookie-\n // age-limit.\n // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)\n\n // 6. If delta-seconds is less than or equal to zero (0), let expiry-\n // time be the earliest representable date and time. Otherwise, let\n // the expiry-time be the current date and time plus delta-seconds\n // seconds.\n // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds\n\n // 7. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Max-Age and an attribute-value of expiry-time.\n cookieAttributeList.maxAge = deltaSeconds\n } else if (attributeNameLowercase === 'domain') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3\n // If the attribute-name case-insensitively matches the string \"Domain\",\n // the user agent MUST process the cookie-av as follows.\n\n // 1. Let cookie-domain be the attribute-value.\n let cookieDomain = attributeValue\n\n // 2. If cookie-domain starts with %x2E (\".\"), let cookie-domain be\n // cookie-domain without its leading %x2E (\".\").\n if (cookieDomain[0] === '.') {\n cookieDomain = cookieDomain.slice(1)\n }\n\n // 3. Convert the cookie-domain to lower case.\n cookieDomain = cookieDomain.toLowerCase()\n\n // 4. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Domain and an attribute-value of cookie-domain.\n cookieAttributeList.domain = cookieDomain\n } else if (attributeNameLowercase === 'path') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4\n // If the attribute-name case-insensitively matches the string \"Path\",\n // the user agent MUST process the cookie-av as follows.\n\n // 1. If the attribute-value is empty or if the first character of the\n // attribute-value is not %x2F (\"/\"):\n let cookiePath = ''\n if (attributeValue.length === 0 || attributeValue[0] !== '/') {\n // 1. Let cookie-path be the default-path.\n cookiePath = '/'\n } else {\n // Otherwise:\n\n // 1. Let cookie-path be the attribute-value.\n cookiePath = attributeValue\n }\n\n // 2. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Path and an attribute-value of cookie-path.\n cookieAttributeList.path = cookiePath\n } else if (attributeNameLowercase === 'secure') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5\n // If the attribute-name case-insensitively matches the string \"Secure\",\n // the user agent MUST append an attribute to the cookie-attribute-list\n // with an attribute-name of Secure and an empty attribute-value.\n\n cookieAttributeList.secure = true\n } else if (attributeNameLowercase === 'httponly') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6\n // If the attribute-name case-insensitively matches the string\n // \"HttpOnly\", the user agent MUST append an attribute to the cookie-\n // attribute-list with an attribute-name of HttpOnly and an empty\n // attribute-value.\n\n cookieAttributeList.httpOnly = true\n } else if (attributeNameLowercase === 'samesite') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7\n // If the attribute-name case-insensitively matches the string\n // \"SameSite\", the user agent MUST process the cookie-av as follows:\n\n // 1. Let enforcement be \"Default\".\n let enforcement = 'Default'\n\n const attributeValueLowercase = attributeValue.toLowerCase()\n // 2. If cookie-av's attribute-value is a case-insensitive match for\n // \"None\", set enforcement to \"None\".\n if (attributeValueLowercase.includes('none')) {\n enforcement = 'None'\n }\n\n // 3. If cookie-av's attribute-value is a case-insensitive match for\n // \"Strict\", set enforcement to \"Strict\".\n if (attributeValueLowercase.includes('strict')) {\n enforcement = 'Strict'\n }\n\n // 4. If cookie-av's attribute-value is a case-insensitive match for\n // \"Lax\", set enforcement to \"Lax\".\n if (attributeValueLowercase.includes('lax')) {\n enforcement = 'Lax'\n }\n\n // 5. Append an attribute to the cookie-attribute-list with an\n // attribute-name of \"SameSite\" and an attribute-value of\n // enforcement.\n cookieAttributeList.sameSite = enforcement\n } else {\n cookieAttributeList.unparsed ??= []\n\n cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)\n }\n\n // 8. Return to Step 1 of this algorithm.\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n}\n\nmodule.exports = {\n parseSetCookie,\n parseUnparsedAttributes\n}\n","'use strict'\n\nconst assert = require('assert')\nconst { kHeadersList } = require('../core/symbols')\n\nfunction isCTLExcludingHtab (value) {\n if (value.length === 0) {\n return false\n }\n\n for (const char of value) {\n const code = char.charCodeAt(0)\n\n if (\n (code >= 0x00 || code <= 0x08) ||\n (code >= 0x0A || code <= 0x1F) ||\n code === 0x7F\n ) {\n return false\n }\n }\n}\n\n/**\n CHAR = \n token = 1*\n separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n | \",\" | \";\" | \":\" | \"\\\" | <\">\n | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n | \"{\" | \"}\" | SP | HT\n * @param {string} name\n */\nfunction validateCookieName (name) {\n for (const char of name) {\n const code = char.charCodeAt(0)\n\n if (\n (code <= 0x20 || code > 0x7F) ||\n char === '(' ||\n char === ')' ||\n char === '>' ||\n char === '<' ||\n char === '@' ||\n char === ',' ||\n char === ';' ||\n char === ':' ||\n char === '\\\\' ||\n char === '\"' ||\n char === '/' ||\n char === '[' ||\n char === ']' ||\n char === '?' ||\n char === '=' ||\n char === '{' ||\n char === '}'\n ) {\n throw new Error('Invalid cookie name')\n }\n }\n}\n\n/**\n cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n ; US-ASCII characters excluding CTLs,\n ; whitespace DQUOTE, comma, semicolon,\n ; and backslash\n * @param {string} value\n */\nfunction validateCookieValue (value) {\n for (const char of value) {\n const code = char.charCodeAt(0)\n\n if (\n code < 0x21 || // exclude CTLs (0-31)\n code === 0x22 ||\n code === 0x2C ||\n code === 0x3B ||\n code === 0x5C ||\n code > 0x7E // non-ascii\n ) {\n throw new Error('Invalid header value')\n }\n }\n}\n\n/**\n * path-value = \n * @param {string} path\n */\nfunction validateCookiePath (path) {\n for (const char of path) {\n const code = char.charCodeAt(0)\n\n if (code < 0x21 || char === ';') {\n throw new Error('Invalid cookie path')\n }\n }\n}\n\n/**\n * I have no idea why these values aren't allowed to be honest,\n * but Deno tests these. - Khafra\n * @param {string} domain\n */\nfunction validateCookieDomain (domain) {\n if (\n domain.startsWith('-') ||\n domain.endsWith('.') ||\n domain.endsWith('-')\n ) {\n throw new Error('Invalid cookie domain')\n }\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1\n * @param {number|Date} date\n IMF-fixdate = day-name \",\" SP date1 SP time-of-day SP GMT\n ; fixed length/zone/capitalization subset of the format\n ; see Section 3.3 of [RFC5322]\n\n day-name = %x4D.6F.6E ; \"Mon\", case-sensitive\n / %x54.75.65 ; \"Tue\", case-sensitive\n / %x57.65.64 ; \"Wed\", case-sensitive\n / %x54.68.75 ; \"Thu\", case-sensitive\n / %x46.72.69 ; \"Fri\", case-sensitive\n / %x53.61.74 ; \"Sat\", case-sensitive\n / %x53.75.6E ; \"Sun\", case-sensitive\n date1 = day SP month SP year\n ; e.g., 02 Jun 1982\n\n day = 2DIGIT\n month = %x4A.61.6E ; \"Jan\", case-sensitive\n / %x46.65.62 ; \"Feb\", case-sensitive\n / %x4D.61.72 ; \"Mar\", case-sensitive\n / %x41.70.72 ; \"Apr\", case-sensitive\n / %x4D.61.79 ; \"May\", case-sensitive\n / %x4A.75.6E ; \"Jun\", case-sensitive\n / %x4A.75.6C ; \"Jul\", case-sensitive\n / %x41.75.67 ; \"Aug\", case-sensitive\n / %x53.65.70 ; \"Sep\", case-sensitive\n / %x4F.63.74 ; \"Oct\", case-sensitive\n / %x4E.6F.76 ; \"Nov\", case-sensitive\n / %x44.65.63 ; \"Dec\", case-sensitive\n year = 4DIGIT\n\n GMT = %x47.4D.54 ; \"GMT\", case-sensitive\n\n time-of-day = hour \":\" minute \":\" second\n ; 00:00:00 - 23:59:60 (leap second)\n\n hour = 2DIGIT\n minute = 2DIGIT\n second = 2DIGIT\n */\nfunction toIMFDate (date) {\n if (typeof date === 'number') {\n date = new Date(date)\n }\n\n const days = [\n 'Sun', 'Mon', 'Tue', 'Wed',\n 'Thu', 'Fri', 'Sat'\n ]\n\n const months = [\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'\n ]\n\n const dayName = days[date.getUTCDay()]\n const day = date.getUTCDate().toString().padStart(2, '0')\n const month = months[date.getUTCMonth()]\n const year = date.getUTCFullYear()\n const hour = date.getUTCHours().toString().padStart(2, '0')\n const minute = date.getUTCMinutes().toString().padStart(2, '0')\n const second = date.getUTCSeconds().toString().padStart(2, '0')\n\n return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`\n}\n\n/**\n max-age-av = \"Max-Age=\" non-zero-digit *DIGIT\n ; In practice, both expires-av and max-age-av\n ; are limited to dates representable by the\n ; user agent.\n * @param {number} maxAge\n */\nfunction validateCookieMaxAge (maxAge) {\n if (maxAge < 0) {\n throw new Error('Invalid cookie max-age')\n }\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1\n * @param {import('./index').Cookie} cookie\n */\nfunction stringify (cookie) {\n if (cookie.name.length === 0) {\n return null\n }\n\n validateCookieName(cookie.name)\n validateCookieValue(cookie.value)\n\n const out = [`${cookie.name}=${cookie.value}`]\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2\n if (cookie.name.startsWith('__Secure-')) {\n cookie.secure = true\n }\n\n if (cookie.name.startsWith('__Host-')) {\n cookie.secure = true\n cookie.domain = null\n cookie.path = '/'\n }\n\n if (cookie.secure) {\n out.push('Secure')\n }\n\n if (cookie.httpOnly) {\n out.push('HttpOnly')\n }\n\n if (typeof cookie.maxAge === 'number') {\n validateCookieMaxAge(cookie.maxAge)\n out.push(`Max-Age=${cookie.maxAge}`)\n }\n\n if (cookie.domain) {\n validateCookieDomain(cookie.domain)\n out.push(`Domain=${cookie.domain}`)\n }\n\n if (cookie.path) {\n validateCookiePath(cookie.path)\n out.push(`Path=${cookie.path}`)\n }\n\n if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {\n out.push(`Expires=${toIMFDate(cookie.expires)}`)\n }\n\n if (cookie.sameSite) {\n out.push(`SameSite=${cookie.sameSite}`)\n }\n\n for (const part of cookie.unparsed) {\n if (!part.includes('=')) {\n throw new Error('Invalid unparsed')\n }\n\n const [key, ...value] = part.split('=')\n\n out.push(`${key.trim()}=${value.join('=')}`)\n }\n\n return out.join('; ')\n}\n\nlet kHeadersListNode\n\nfunction getHeadersList (headers) {\n if (headers[kHeadersList]) {\n return headers[kHeadersList]\n }\n\n if (!kHeadersListNode) {\n kHeadersListNode = Object.getOwnPropertySymbols(headers).find(\n (symbol) => symbol.description === 'headers list'\n )\n\n assert(kHeadersListNode, 'Headers cannot be parsed')\n }\n\n const headersList = headers[kHeadersListNode]\n assert(headersList)\n\n return headersList\n}\n\nmodule.exports = {\n isCTLExcludingHtab,\n stringify,\n getHeadersList\n}\n","'use strict'\n\nconst net = require('net')\nconst assert = require('assert')\nconst util = require('./util')\nconst { InvalidArgumentError, ConnectTimeoutError } = require('./errors')\n\nlet tls // include tls conditionally since it is not always available\n\n// TODO: session re-use does not wait for the first\n// connection to resolve the session and might therefore\n// resolve the same servername multiple times even when\n// re-use is enabled.\n\nlet SessionCache\n// FIXME: remove workaround when the Node bug is fixed\n// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308\nif (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {\n SessionCache = class WeakSessionCache {\n constructor (maxCachedSessions) {\n this._maxCachedSessions = maxCachedSessions\n this._sessionCache = new Map()\n this._sessionRegistry = new global.FinalizationRegistry((key) => {\n if (this._sessionCache.size < this._maxCachedSessions) {\n return\n }\n\n const ref = this._sessionCache.get(key)\n if (ref !== undefined && ref.deref() === undefined) {\n this._sessionCache.delete(key)\n }\n })\n }\n\n get (sessionKey) {\n const ref = this._sessionCache.get(sessionKey)\n return ref ? ref.deref() : null\n }\n\n set (sessionKey, session) {\n if (this._maxCachedSessions === 0) {\n return\n }\n\n this._sessionCache.set(sessionKey, new WeakRef(session))\n this._sessionRegistry.register(session, sessionKey)\n }\n }\n} else {\n SessionCache = class SimpleSessionCache {\n constructor (maxCachedSessions) {\n this._maxCachedSessions = maxCachedSessions\n this._sessionCache = new Map()\n }\n\n get (sessionKey) {\n return this._sessionCache.get(sessionKey)\n }\n\n set (sessionKey, session) {\n if (this._maxCachedSessions === 0) {\n return\n }\n\n if (this._sessionCache.size >= this._maxCachedSessions) {\n // remove the oldest session\n const { value: oldestKey } = this._sessionCache.keys().next()\n this._sessionCache.delete(oldestKey)\n }\n\n this._sessionCache.set(sessionKey, session)\n }\n }\n}\n\nfunction buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {\n if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {\n throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')\n }\n\n const options = { path: socketPath, ...opts }\n const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)\n timeout = timeout == null ? 10e3 : timeout\n allowH2 = allowH2 != null ? allowH2 : false\n return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {\n let socket\n if (protocol === 'https:') {\n if (!tls) {\n tls = require('tls')\n }\n servername = servername || options.servername || util.getServerName(host) || null\n\n const sessionKey = servername || hostname\n const session = sessionCache.get(sessionKey) || null\n\n assert(sessionKey)\n\n socket = tls.connect({\n highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...\n ...options,\n servername,\n session,\n localAddress,\n // TODO(HTTP/2): Add support for h2c\n ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],\n socket: httpSocket, // upgrade socket connection\n port: port || 443,\n host: hostname\n })\n\n socket\n .on('session', function (session) {\n // TODO (fix): Can a session become invalid once established? Don't think so?\n sessionCache.set(sessionKey, session)\n })\n } else {\n assert(!httpSocket, 'httpSocket can only be sent on TLS update')\n socket = net.connect({\n highWaterMark: 64 * 1024, // Same as nodejs fs streams.\n ...options,\n localAddress,\n port: port || 80,\n host: hostname\n })\n }\n\n // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket\n if (options.keepAlive == null || options.keepAlive) {\n const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay\n socket.setKeepAlive(true, keepAliveInitialDelay)\n }\n\n const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)\n\n socket\n .setNoDelay(true)\n .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {\n cancelTimeout()\n\n if (callback) {\n const cb = callback\n callback = null\n cb(null, this)\n }\n })\n .on('error', function (err) {\n cancelTimeout()\n\n if (callback) {\n const cb = callback\n callback = null\n cb(err)\n }\n })\n\n return socket\n }\n}\n\nfunction setupTimeout (onConnectTimeout, timeout) {\n if (!timeout) {\n return () => {}\n }\n\n let s1 = null\n let s2 = null\n const timeoutId = setTimeout(() => {\n // setImmediate is added to make sure that we priotorise socket error events over timeouts\n s1 = setImmediate(() => {\n if (process.platform === 'win32') {\n // Windows needs an extra setImmediate probably due to implementation differences in the socket logic\n s2 = setImmediate(() => onConnectTimeout())\n } else {\n onConnectTimeout()\n }\n })\n }, timeout)\n return () => {\n clearTimeout(timeoutId)\n clearImmediate(s1)\n clearImmediate(s2)\n }\n}\n\nfunction onConnectTimeout (socket) {\n util.destroy(socket, new ConnectTimeoutError())\n}\n\nmodule.exports = buildConnector\n","'use strict'\n\n/** @type {Record} */\nconst headerNameLowerCasedRecord = {}\n\n// https://developer.mozilla.org/docs/Web/HTTP/Headers\nconst wellknownHeaderNames = [\n 'Accept',\n 'Accept-Encoding',\n 'Accept-Language',\n 'Accept-Ranges',\n 'Access-Control-Allow-Credentials',\n 'Access-Control-Allow-Headers',\n 'Access-Control-Allow-Methods',\n 'Access-Control-Allow-Origin',\n 'Access-Control-Expose-Headers',\n 'Access-Control-Max-Age',\n 'Access-Control-Request-Headers',\n 'Access-Control-Request-Method',\n 'Age',\n 'Allow',\n 'Alt-Svc',\n 'Alt-Used',\n 'Authorization',\n 'Cache-Control',\n 'Clear-Site-Data',\n 'Connection',\n 'Content-Disposition',\n 'Content-Encoding',\n 'Content-Language',\n 'Content-Length',\n 'Content-Location',\n 'Content-Range',\n 'Content-Security-Policy',\n 'Content-Security-Policy-Report-Only',\n 'Content-Type',\n 'Cookie',\n 'Cross-Origin-Embedder-Policy',\n 'Cross-Origin-Opener-Policy',\n 'Cross-Origin-Resource-Policy',\n 'Date',\n 'Device-Memory',\n 'Downlink',\n 'ECT',\n 'ETag',\n 'Expect',\n 'Expect-CT',\n 'Expires',\n 'Forwarded',\n 'From',\n 'Host',\n 'If-Match',\n 'If-Modified-Since',\n 'If-None-Match',\n 'If-Range',\n 'If-Unmodified-Since',\n 'Keep-Alive',\n 'Last-Modified',\n 'Link',\n 'Location',\n 'Max-Forwards',\n 'Origin',\n 'Permissions-Policy',\n 'Pragma',\n 'Proxy-Authenticate',\n 'Proxy-Authorization',\n 'RTT',\n 'Range',\n 'Referer',\n 'Referrer-Policy',\n 'Refresh',\n 'Retry-After',\n 'Sec-WebSocket-Accept',\n 'Sec-WebSocket-Extensions',\n 'Sec-WebSocket-Key',\n 'Sec-WebSocket-Protocol',\n 'Sec-WebSocket-Version',\n 'Server',\n 'Server-Timing',\n 'Service-Worker-Allowed',\n 'Service-Worker-Navigation-Preload',\n 'Set-Cookie',\n 'SourceMap',\n 'Strict-Transport-Security',\n 'Supports-Loading-Mode',\n 'TE',\n 'Timing-Allow-Origin',\n 'Trailer',\n 'Transfer-Encoding',\n 'Upgrade',\n 'Upgrade-Insecure-Requests',\n 'User-Agent',\n 'Vary',\n 'Via',\n 'WWW-Authenticate',\n 'X-Content-Type-Options',\n 'X-DNS-Prefetch-Control',\n 'X-Frame-Options',\n 'X-Permitted-Cross-Domain-Policies',\n 'X-Powered-By',\n 'X-Requested-With',\n 'X-XSS-Protection'\n]\n\nfor (let i = 0; i < wellknownHeaderNames.length; ++i) {\n const key = wellknownHeaderNames[i]\n const lowerCasedKey = key.toLowerCase()\n headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =\n lowerCasedKey\n}\n\n// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.\nObject.setPrototypeOf(headerNameLowerCasedRecord, null)\n\nmodule.exports = {\n wellknownHeaderNames,\n headerNameLowerCasedRecord\n}\n","'use strict'\n\nclass UndiciError extends Error {\n constructor (message) {\n super(message)\n this.name = 'UndiciError'\n this.code = 'UND_ERR'\n }\n}\n\nclass ConnectTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ConnectTimeoutError)\n this.name = 'ConnectTimeoutError'\n this.message = message || 'Connect Timeout Error'\n this.code = 'UND_ERR_CONNECT_TIMEOUT'\n }\n}\n\nclass HeadersTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, HeadersTimeoutError)\n this.name = 'HeadersTimeoutError'\n this.message = message || 'Headers Timeout Error'\n this.code = 'UND_ERR_HEADERS_TIMEOUT'\n }\n}\n\nclass HeadersOverflowError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, HeadersOverflowError)\n this.name = 'HeadersOverflowError'\n this.message = message || 'Headers Overflow Error'\n this.code = 'UND_ERR_HEADERS_OVERFLOW'\n }\n}\n\nclass BodyTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, BodyTimeoutError)\n this.name = 'BodyTimeoutError'\n this.message = message || 'Body Timeout Error'\n this.code = 'UND_ERR_BODY_TIMEOUT'\n }\n}\n\nclass ResponseStatusCodeError extends UndiciError {\n constructor (message, statusCode, headers, body) {\n super(message)\n Error.captureStackTrace(this, ResponseStatusCodeError)\n this.name = 'ResponseStatusCodeError'\n this.message = message || 'Response Status Code Error'\n this.code = 'UND_ERR_RESPONSE_STATUS_CODE'\n this.body = body\n this.status = statusCode\n this.statusCode = statusCode\n this.headers = headers\n }\n}\n\nclass InvalidArgumentError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InvalidArgumentError)\n this.name = 'InvalidArgumentError'\n this.message = message || 'Invalid Argument Error'\n this.code = 'UND_ERR_INVALID_ARG'\n }\n}\n\nclass InvalidReturnValueError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InvalidReturnValueError)\n this.name = 'InvalidReturnValueError'\n this.message = message || 'Invalid Return Value Error'\n this.code = 'UND_ERR_INVALID_RETURN_VALUE'\n }\n}\n\nclass RequestAbortedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, RequestAbortedError)\n this.name = 'AbortError'\n this.message = message || 'Request aborted'\n this.code = 'UND_ERR_ABORTED'\n }\n}\n\nclass InformationalError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InformationalError)\n this.name = 'InformationalError'\n this.message = message || 'Request information'\n this.code = 'UND_ERR_INFO'\n }\n}\n\nclass RequestContentLengthMismatchError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, RequestContentLengthMismatchError)\n this.name = 'RequestContentLengthMismatchError'\n this.message = message || 'Request body length does not match content-length header'\n this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'\n }\n}\n\nclass ResponseContentLengthMismatchError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ResponseContentLengthMismatchError)\n this.name = 'ResponseContentLengthMismatchError'\n this.message = message || 'Response body length does not match content-length header'\n this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'\n }\n}\n\nclass ClientDestroyedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ClientDestroyedError)\n this.name = 'ClientDestroyedError'\n this.message = message || 'The client is destroyed'\n this.code = 'UND_ERR_DESTROYED'\n }\n}\n\nclass ClientClosedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ClientClosedError)\n this.name = 'ClientClosedError'\n this.message = message || 'The client is closed'\n this.code = 'UND_ERR_CLOSED'\n }\n}\n\nclass SocketError extends UndiciError {\n constructor (message, socket) {\n super(message)\n Error.captureStackTrace(this, SocketError)\n this.name = 'SocketError'\n this.message = message || 'Socket error'\n this.code = 'UND_ERR_SOCKET'\n this.socket = socket\n }\n}\n\nclass NotSupportedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, NotSupportedError)\n this.name = 'NotSupportedError'\n this.message = message || 'Not supported error'\n this.code = 'UND_ERR_NOT_SUPPORTED'\n }\n}\n\nclass BalancedPoolMissingUpstreamError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, NotSupportedError)\n this.name = 'MissingUpstreamError'\n this.message = message || 'No upstream has been added to the BalancedPool'\n this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'\n }\n}\n\nclass HTTPParserError extends Error {\n constructor (message, code, data) {\n super(message)\n Error.captureStackTrace(this, HTTPParserError)\n this.name = 'HTTPParserError'\n this.code = code ? `HPE_${code}` : undefined\n this.data = data ? data.toString() : undefined\n }\n}\n\nclass ResponseExceededMaxSizeError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ResponseExceededMaxSizeError)\n this.name = 'ResponseExceededMaxSizeError'\n this.message = message || 'Response content exceeded max size'\n this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'\n }\n}\n\nclass RequestRetryError extends UndiciError {\n constructor (message, code, { headers, data }) {\n super(message)\n Error.captureStackTrace(this, RequestRetryError)\n this.name = 'RequestRetryError'\n this.message = message || 'Request retry error'\n this.code = 'UND_ERR_REQ_RETRY'\n this.statusCode = code\n this.data = data\n this.headers = headers\n }\n}\n\nmodule.exports = {\n HTTPParserError,\n UndiciError,\n HeadersTimeoutError,\n HeadersOverflowError,\n BodyTimeoutError,\n RequestContentLengthMismatchError,\n ConnectTimeoutError,\n ResponseStatusCodeError,\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError,\n ClientDestroyedError,\n ClientClosedError,\n InformationalError,\n SocketError,\n NotSupportedError,\n ResponseContentLengthMismatchError,\n BalancedPoolMissingUpstreamError,\n ResponseExceededMaxSizeError,\n RequestRetryError\n}\n","'use strict'\n\nconst {\n InvalidArgumentError,\n NotSupportedError\n} = require('./errors')\nconst assert = require('assert')\nconst { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = require('./symbols')\nconst util = require('./util')\n\n// tokenRegExp and headerCharRegex have been lifted from\n// https://github.com/nodejs/node/blob/main/lib/_http_common.js\n\n/**\n * Verifies that the given val is a valid HTTP token\n * per the rules defined in RFC 7230\n * See https://tools.ietf.org/html/rfc7230#section-3.2.6\n */\nconst tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/\n\n/**\n * Matches if val contains an invalid field-vchar\n * field-value = *( field-content / obs-fold )\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n */\nconst headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/\n\n// Verifies that a given path is valid does not contain control chars \\x00 to \\x20\nconst invalidPathRegex = /[^\\u0021-\\u00ff]/\n\nconst kHandler = Symbol('handler')\n\nconst channels = {}\n\nlet extractBody\n\ntry {\n const diagnosticsChannel = require('diagnostics_channel')\n channels.create = diagnosticsChannel.channel('undici:request:create')\n channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')\n channels.headers = diagnosticsChannel.channel('undici:request:headers')\n channels.trailers = diagnosticsChannel.channel('undici:request:trailers')\n channels.error = diagnosticsChannel.channel('undici:request:error')\n} catch {\n channels.create = { hasSubscribers: false }\n channels.bodySent = { hasSubscribers: false }\n channels.headers = { hasSubscribers: false }\n channels.trailers = { hasSubscribers: false }\n channels.error = { hasSubscribers: false }\n}\n\nclass Request {\n constructor (origin, {\n path,\n method,\n body,\n headers,\n query,\n idempotent,\n blocking,\n upgrade,\n headersTimeout,\n bodyTimeout,\n reset,\n throwOnError,\n expectContinue\n }, handler) {\n if (typeof path !== 'string') {\n throw new InvalidArgumentError('path must be a string')\n } else if (\n path[0] !== '/' &&\n !(path.startsWith('http://') || path.startsWith('https://')) &&\n method !== 'CONNECT'\n ) {\n throw new InvalidArgumentError('path must be an absolute URL or start with a slash')\n } else if (invalidPathRegex.exec(path) !== null) {\n throw new InvalidArgumentError('invalid request path')\n }\n\n if (typeof method !== 'string') {\n throw new InvalidArgumentError('method must be a string')\n } else if (tokenRegExp.exec(method) === null) {\n throw new InvalidArgumentError('invalid request method')\n }\n\n if (upgrade && typeof upgrade !== 'string') {\n throw new InvalidArgumentError('upgrade must be a string')\n }\n\n if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {\n throw new InvalidArgumentError('invalid headersTimeout')\n }\n\n if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {\n throw new InvalidArgumentError('invalid bodyTimeout')\n }\n\n if (reset != null && typeof reset !== 'boolean') {\n throw new InvalidArgumentError('invalid reset')\n }\n\n if (expectContinue != null && typeof expectContinue !== 'boolean') {\n throw new InvalidArgumentError('invalid expectContinue')\n }\n\n this.headersTimeout = headersTimeout\n\n this.bodyTimeout = bodyTimeout\n\n this.throwOnError = throwOnError === true\n\n this.method = method\n\n this.abort = null\n\n if (body == null) {\n this.body = null\n } else if (util.isStream(body)) {\n this.body = body\n\n const rState = this.body._readableState\n if (!rState || !rState.autoDestroy) {\n this.endHandler = function autoDestroy () {\n util.destroy(this)\n }\n this.body.on('end', this.endHandler)\n }\n\n this.errorHandler = err => {\n if (this.abort) {\n this.abort(err)\n } else {\n this.error = err\n }\n }\n this.body.on('error', this.errorHandler)\n } else if (util.isBuffer(body)) {\n this.body = body.byteLength ? body : null\n } else if (ArrayBuffer.isView(body)) {\n this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null\n } else if (body instanceof ArrayBuffer) {\n this.body = body.byteLength ? Buffer.from(body) : null\n } else if (typeof body === 'string') {\n this.body = body.length ? Buffer.from(body) : null\n } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {\n this.body = body\n } else {\n throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')\n }\n\n this.completed = false\n\n this.aborted = false\n\n this.upgrade = upgrade || null\n\n this.path = query ? util.buildURL(path, query) : path\n\n this.origin = origin\n\n this.idempotent = idempotent == null\n ? method === 'HEAD' || method === 'GET'\n : idempotent\n\n this.blocking = blocking == null ? false : blocking\n\n this.reset = reset == null ? null : reset\n\n this.host = null\n\n this.contentLength = null\n\n this.contentType = null\n\n this.headers = ''\n\n // Only for H2\n this.expectContinue = expectContinue != null ? expectContinue : false\n\n if (Array.isArray(headers)) {\n if (headers.length % 2 !== 0) {\n throw new InvalidArgumentError('headers array must be even')\n }\n for (let i = 0; i < headers.length; i += 2) {\n processHeader(this, headers[i], headers[i + 1])\n }\n } else if (headers && typeof headers === 'object') {\n const keys = Object.keys(headers)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n processHeader(this, key, headers[key])\n }\n } else if (headers != null) {\n throw new InvalidArgumentError('headers must be an object or an array')\n }\n\n if (util.isFormDataLike(this.body)) {\n if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {\n throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')\n }\n\n if (!extractBody) {\n extractBody = require('../fetch/body.js').extractBody\n }\n\n const [bodyStream, contentType] = extractBody(body)\n if (this.contentType == null) {\n this.contentType = contentType\n this.headers += `content-type: ${contentType}\\r\\n`\n }\n this.body = bodyStream.stream\n this.contentLength = bodyStream.length\n } else if (util.isBlobLike(body) && this.contentType == null && body.type) {\n this.contentType = body.type\n this.headers += `content-type: ${body.type}\\r\\n`\n }\n\n util.validateHandler(handler, method, upgrade)\n\n this.servername = util.getServerName(this.host)\n\n this[kHandler] = handler\n\n if (channels.create.hasSubscribers) {\n channels.create.publish({ request: this })\n }\n }\n\n onBodySent (chunk) {\n if (this[kHandler].onBodySent) {\n try {\n return this[kHandler].onBodySent(chunk)\n } catch (err) {\n this.abort(err)\n }\n }\n }\n\n onRequestSent () {\n if (channels.bodySent.hasSubscribers) {\n channels.bodySent.publish({ request: this })\n }\n\n if (this[kHandler].onRequestSent) {\n try {\n return this[kHandler].onRequestSent()\n } catch (err) {\n this.abort(err)\n }\n }\n }\n\n onConnect (abort) {\n assert(!this.aborted)\n assert(!this.completed)\n\n if (this.error) {\n abort(this.error)\n } else {\n this.abort = abort\n return this[kHandler].onConnect(abort)\n }\n }\n\n onHeaders (statusCode, headers, resume, statusText) {\n assert(!this.aborted)\n assert(!this.completed)\n\n if (channels.headers.hasSubscribers) {\n channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })\n }\n\n try {\n return this[kHandler].onHeaders(statusCode, headers, resume, statusText)\n } catch (err) {\n this.abort(err)\n }\n }\n\n onData (chunk) {\n assert(!this.aborted)\n assert(!this.completed)\n\n try {\n return this[kHandler].onData(chunk)\n } catch (err) {\n this.abort(err)\n return false\n }\n }\n\n onUpgrade (statusCode, headers, socket) {\n assert(!this.aborted)\n assert(!this.completed)\n\n return this[kHandler].onUpgrade(statusCode, headers, socket)\n }\n\n onComplete (trailers) {\n this.onFinally()\n\n assert(!this.aborted)\n\n this.completed = true\n if (channels.trailers.hasSubscribers) {\n channels.trailers.publish({ request: this, trailers })\n }\n\n try {\n return this[kHandler].onComplete(trailers)\n } catch (err) {\n // TODO (fix): This might be a bad idea?\n this.onError(err)\n }\n }\n\n onError (error) {\n this.onFinally()\n\n if (channels.error.hasSubscribers) {\n channels.error.publish({ request: this, error })\n }\n\n if (this.aborted) {\n return\n }\n this.aborted = true\n\n return this[kHandler].onError(error)\n }\n\n onFinally () {\n if (this.errorHandler) {\n this.body.off('error', this.errorHandler)\n this.errorHandler = null\n }\n\n if (this.endHandler) {\n this.body.off('end', this.endHandler)\n this.endHandler = null\n }\n }\n\n // TODO: adjust to support H2\n addHeader (key, value) {\n processHeader(this, key, value)\n return this\n }\n\n static [kHTTP1BuildRequest] (origin, opts, handler) {\n // TODO: Migrate header parsing here, to make Requests\n // HTTP agnostic\n return new Request(origin, opts, handler)\n }\n\n static [kHTTP2BuildRequest] (origin, opts, handler) {\n const headers = opts.headers\n opts = { ...opts, headers: null }\n\n const request = new Request(origin, opts, handler)\n\n request.headers = {}\n\n if (Array.isArray(headers)) {\n if (headers.length % 2 !== 0) {\n throw new InvalidArgumentError('headers array must be even')\n }\n for (let i = 0; i < headers.length; i += 2) {\n processHeader(request, headers[i], headers[i + 1], true)\n }\n } else if (headers && typeof headers === 'object') {\n const keys = Object.keys(headers)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n processHeader(request, key, headers[key], true)\n }\n } else if (headers != null) {\n throw new InvalidArgumentError('headers must be an object or an array')\n }\n\n return request\n }\n\n static [kHTTP2CopyHeaders] (raw) {\n const rawHeaders = raw.split('\\r\\n')\n const headers = {}\n\n for (const header of rawHeaders) {\n const [key, value] = header.split(': ')\n\n if (value == null || value.length === 0) continue\n\n if (headers[key]) headers[key] += `,${value}`\n else headers[key] = value\n }\n\n return headers\n }\n}\n\nfunction processHeaderValue (key, val, skipAppend) {\n if (val && typeof val === 'object') {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n\n val = val != null ? `${val}` : ''\n\n if (headerCharRegex.exec(val) !== null) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n\n return skipAppend ? val : `${key}: ${val}\\r\\n`\n}\n\nfunction processHeader (request, key, val, skipAppend = false) {\n if (val && (typeof val === 'object' && !Array.isArray(val))) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n } else if (val === undefined) {\n return\n }\n\n if (\n request.host === null &&\n key.length === 4 &&\n key.toLowerCase() === 'host'\n ) {\n if (headerCharRegex.exec(val) !== null) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n // Consumed by Client\n request.host = val\n } else if (\n request.contentLength === null &&\n key.length === 14 &&\n key.toLowerCase() === 'content-length'\n ) {\n request.contentLength = parseInt(val, 10)\n if (!Number.isFinite(request.contentLength)) {\n throw new InvalidArgumentError('invalid content-length header')\n }\n } else if (\n request.contentType === null &&\n key.length === 12 &&\n key.toLowerCase() === 'content-type'\n ) {\n request.contentType = val\n if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)\n else request.headers += processHeaderValue(key, val)\n } else if (\n key.length === 17 &&\n key.toLowerCase() === 'transfer-encoding'\n ) {\n throw new InvalidArgumentError('invalid transfer-encoding header')\n } else if (\n key.length === 10 &&\n key.toLowerCase() === 'connection'\n ) {\n const value = typeof val === 'string' ? val.toLowerCase() : null\n if (value !== 'close' && value !== 'keep-alive') {\n throw new InvalidArgumentError('invalid connection header')\n } else if (value === 'close') {\n request.reset = true\n }\n } else if (\n key.length === 10 &&\n key.toLowerCase() === 'keep-alive'\n ) {\n throw new InvalidArgumentError('invalid keep-alive header')\n } else if (\n key.length === 7 &&\n key.toLowerCase() === 'upgrade'\n ) {\n throw new InvalidArgumentError('invalid upgrade header')\n } else if (\n key.length === 6 &&\n key.toLowerCase() === 'expect'\n ) {\n throw new NotSupportedError('expect header not supported')\n } else if (tokenRegExp.exec(key) === null) {\n throw new InvalidArgumentError('invalid header key')\n } else {\n if (Array.isArray(val)) {\n for (let i = 0; i < val.length; i++) {\n if (skipAppend) {\n if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`\n else request.headers[key] = processHeaderValue(key, val[i], skipAppend)\n } else {\n request.headers += processHeaderValue(key, val[i])\n }\n }\n } else {\n if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)\n else request.headers += processHeaderValue(key, val)\n }\n }\n}\n\nmodule.exports = Request\n","module.exports = {\n kClose: Symbol('close'),\n kDestroy: Symbol('destroy'),\n kDispatch: Symbol('dispatch'),\n kUrl: Symbol('url'),\n kWriting: Symbol('writing'),\n kResuming: Symbol('resuming'),\n kQueue: Symbol('queue'),\n kConnect: Symbol('connect'),\n kConnecting: Symbol('connecting'),\n kHeadersList: Symbol('headers list'),\n kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),\n kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),\n kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),\n kKeepAliveTimeoutValue: Symbol('keep alive timeout'),\n kKeepAlive: Symbol('keep alive'),\n kHeadersTimeout: Symbol('headers timeout'),\n kBodyTimeout: Symbol('body timeout'),\n kServerName: Symbol('server name'),\n kLocalAddress: Symbol('local address'),\n kHost: Symbol('host'),\n kNoRef: Symbol('no ref'),\n kBodyUsed: Symbol('used'),\n kRunning: Symbol('running'),\n kBlocking: Symbol('blocking'),\n kPending: Symbol('pending'),\n kSize: Symbol('size'),\n kBusy: Symbol('busy'),\n kQueued: Symbol('queued'),\n kFree: Symbol('free'),\n kConnected: Symbol('connected'),\n kClosed: Symbol('closed'),\n kNeedDrain: Symbol('need drain'),\n kReset: Symbol('reset'),\n kDestroyed: Symbol.for('nodejs.stream.destroyed'),\n kMaxHeadersSize: Symbol('max headers size'),\n kRunningIdx: Symbol('running index'),\n kPendingIdx: Symbol('pending index'),\n kError: Symbol('error'),\n kClients: Symbol('clients'),\n kClient: Symbol('client'),\n kParser: Symbol('parser'),\n kOnDestroyed: Symbol('destroy callbacks'),\n kPipelining: Symbol('pipelining'),\n kSocket: Symbol('socket'),\n kHostHeader: Symbol('host header'),\n kConnector: Symbol('connector'),\n kStrictContentLength: Symbol('strict content length'),\n kMaxRedirections: Symbol('maxRedirections'),\n kMaxRequests: Symbol('maxRequestsPerClient'),\n kProxy: Symbol('proxy agent options'),\n kCounter: Symbol('socket request counter'),\n kInterceptors: Symbol('dispatch interceptors'),\n kMaxResponseSize: Symbol('max response size'),\n kHTTP2Session: Symbol('http2Session'),\n kHTTP2SessionState: Symbol('http2Session state'),\n kHTTP2BuildRequest: Symbol('http2 build request'),\n kHTTP1BuildRequest: Symbol('http1 build request'),\n kHTTP2CopyHeaders: Symbol('http2 copy headers'),\n kHTTPConnVersion: Symbol('http connection version'),\n kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),\n kConstruct: Symbol('constructable')\n}\n","'use strict'\n\nconst assert = require('assert')\nconst { kDestroyed, kBodyUsed } = require('./symbols')\nconst { IncomingMessage } = require('http')\nconst stream = require('stream')\nconst net = require('net')\nconst { InvalidArgumentError } = require('./errors')\nconst { Blob } = require('buffer')\nconst nodeUtil = require('util')\nconst { stringify } = require('querystring')\nconst { headerNameLowerCasedRecord } = require('./constants')\n\nconst [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))\n\nfunction nop () {}\n\nfunction isStream (obj) {\n return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'\n}\n\n// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)\nfunction isBlobLike (object) {\n return (Blob && object instanceof Blob) || (\n object &&\n typeof object === 'object' &&\n (typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function') &&\n /^(Blob|File)$/.test(object[Symbol.toStringTag])\n )\n}\n\nfunction buildURL (url, queryParams) {\n if (url.includes('?') || url.includes('#')) {\n throw new Error('Query params cannot be passed when url already contains \"?\" or \"#\".')\n }\n\n const stringified = stringify(queryParams)\n\n if (stringified) {\n url += '?' + stringified\n }\n\n return url\n}\n\nfunction parseURL (url) {\n if (typeof url === 'string') {\n url = new URL(url)\n\n if (!/^https?:/.test(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n return url\n }\n\n if (!url || typeof url !== 'object') {\n throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')\n }\n\n if (!/^https?:/.test(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n if (!(url instanceof URL)) {\n if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {\n throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')\n }\n\n if (url.path != null && typeof url.path !== 'string') {\n throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')\n }\n\n if (url.pathname != null && typeof url.pathname !== 'string') {\n throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')\n }\n\n if (url.hostname != null && typeof url.hostname !== 'string') {\n throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')\n }\n\n if (url.origin != null && typeof url.origin !== 'string') {\n throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')\n }\n\n const port = url.port != null\n ? url.port\n : (url.protocol === 'https:' ? 443 : 80)\n let origin = url.origin != null\n ? url.origin\n : `${url.protocol}//${url.hostname}:${port}`\n let path = url.path != null\n ? url.path\n : `${url.pathname || ''}${url.search || ''}`\n\n if (origin.endsWith('/')) {\n origin = origin.substring(0, origin.length - 1)\n }\n\n if (path && !path.startsWith('/')) {\n path = `/${path}`\n }\n // new URL(path, origin) is unsafe when `path` contains an absolute URL\n // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:\n // If first parameter is a relative URL, second param is required, and will be used as the base URL.\n // If first parameter is an absolute URL, a given second param will be ignored.\n url = new URL(origin + path)\n }\n\n return url\n}\n\nfunction parseOrigin (url) {\n url = parseURL(url)\n\n if (url.pathname !== '/' || url.search || url.hash) {\n throw new InvalidArgumentError('invalid url')\n }\n\n return url\n}\n\nfunction getHostname (host) {\n if (host[0] === '[') {\n const idx = host.indexOf(']')\n\n assert(idx !== -1)\n return host.substring(1, idx)\n }\n\n const idx = host.indexOf(':')\n if (idx === -1) return host\n\n return host.substring(0, idx)\n}\n\n// IP addresses are not valid server names per RFC6066\n// > Currently, the only server names supported are DNS hostnames\nfunction getServerName (host) {\n if (!host) {\n return null\n }\n\n assert.strictEqual(typeof host, 'string')\n\n const servername = getHostname(host)\n if (net.isIP(servername)) {\n return ''\n }\n\n return servername\n}\n\nfunction deepClone (obj) {\n return JSON.parse(JSON.stringify(obj))\n}\n\nfunction isAsyncIterable (obj) {\n return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')\n}\n\nfunction isIterable (obj) {\n return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))\n}\n\nfunction bodyLength (body) {\n if (body == null) {\n return 0\n } else if (isStream(body)) {\n const state = body._readableState\n return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)\n ? state.length\n : null\n } else if (isBlobLike(body)) {\n return body.size != null ? body.size : null\n } else if (isBuffer(body)) {\n return body.byteLength\n }\n\n return null\n}\n\nfunction isDestroyed (stream) {\n return !stream || !!(stream.destroyed || stream[kDestroyed])\n}\n\nfunction isReadableAborted (stream) {\n const state = stream && stream._readableState\n return isDestroyed(stream) && state && !state.endEmitted\n}\n\nfunction destroy (stream, err) {\n if (stream == null || !isStream(stream) || isDestroyed(stream)) {\n return\n }\n\n if (typeof stream.destroy === 'function') {\n if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {\n // See: https://github.com/nodejs/node/pull/38505/files\n stream.socket = null\n }\n\n stream.destroy(err)\n } else if (err) {\n process.nextTick((stream, err) => {\n stream.emit('error', err)\n }, stream, err)\n }\n\n if (stream.destroyed !== true) {\n stream[kDestroyed] = true\n }\n}\n\nconst KEEPALIVE_TIMEOUT_EXPR = /timeout=(\\d+)/\nfunction parseKeepAliveTimeout (val) {\n const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)\n return m ? parseInt(m[1], 10) * 1000 : null\n}\n\n/**\n * Retrieves a header name and returns its lowercase value.\n * @param {string | Buffer} value Header name\n * @returns {string}\n */\nfunction headerNameToString (value) {\n return headerNameLowerCasedRecord[value] || value.toLowerCase()\n}\n\nfunction parseHeaders (headers, obj = {}) {\n // For H2 support\n if (!Array.isArray(headers)) return headers\n\n for (let i = 0; i < headers.length; i += 2) {\n const key = headers[i].toString().toLowerCase()\n let val = obj[key]\n\n if (!val) {\n if (Array.isArray(headers[i + 1])) {\n obj[key] = headers[i + 1].map(x => x.toString('utf8'))\n } else {\n obj[key] = headers[i + 1].toString('utf8')\n }\n } else {\n if (!Array.isArray(val)) {\n val = [val]\n obj[key] = val\n }\n val.push(headers[i + 1].toString('utf8'))\n }\n }\n\n // See https://github.com/nodejs/node/pull/46528\n if ('content-length' in obj && 'content-disposition' in obj) {\n obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')\n }\n\n return obj\n}\n\nfunction parseRawHeaders (headers) {\n const ret = []\n let hasContentLength = false\n let contentDispositionIdx = -1\n\n for (let n = 0; n < headers.length; n += 2) {\n const key = headers[n + 0].toString()\n const val = headers[n + 1].toString('utf8')\n\n if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {\n ret.push(key, val)\n hasContentLength = true\n } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {\n contentDispositionIdx = ret.push(key, val) - 1\n } else {\n ret.push(key, val)\n }\n }\n\n // See https://github.com/nodejs/node/pull/46528\n if (hasContentLength && contentDispositionIdx !== -1) {\n ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')\n }\n\n return ret\n}\n\nfunction isBuffer (buffer) {\n // See, https://github.com/mcollina/undici/pull/319\n return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)\n}\n\nfunction validateHandler (handler, method, upgrade) {\n if (!handler || typeof handler !== 'object') {\n throw new InvalidArgumentError('handler must be an object')\n }\n\n if (typeof handler.onConnect !== 'function') {\n throw new InvalidArgumentError('invalid onConnect method')\n }\n\n if (typeof handler.onError !== 'function') {\n throw new InvalidArgumentError('invalid onError method')\n }\n\n if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {\n throw new InvalidArgumentError('invalid onBodySent method')\n }\n\n if (upgrade || method === 'CONNECT') {\n if (typeof handler.onUpgrade !== 'function') {\n throw new InvalidArgumentError('invalid onUpgrade method')\n }\n } else {\n if (typeof handler.onHeaders !== 'function') {\n throw new InvalidArgumentError('invalid onHeaders method')\n }\n\n if (typeof handler.onData !== 'function') {\n throw new InvalidArgumentError('invalid onData method')\n }\n\n if (typeof handler.onComplete !== 'function') {\n throw new InvalidArgumentError('invalid onComplete method')\n }\n }\n}\n\n// A body is disturbed if it has been read from and it cannot\n// be re-used without losing state or data.\nfunction isDisturbed (body) {\n return !!(body && (\n stream.isDisturbed\n ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?\n : body[kBodyUsed] ||\n body.readableDidRead ||\n (body._readableState && body._readableState.dataEmitted) ||\n isReadableAborted(body)\n ))\n}\n\nfunction isErrored (body) {\n return !!(body && (\n stream.isErrored\n ? stream.isErrored(body)\n : /state: 'errored'/.test(nodeUtil.inspect(body)\n )))\n}\n\nfunction isReadable (body) {\n return !!(body && (\n stream.isReadable\n ? stream.isReadable(body)\n : /state: 'readable'/.test(nodeUtil.inspect(body)\n )))\n}\n\nfunction getSocketInfo (socket) {\n return {\n localAddress: socket.localAddress,\n localPort: socket.localPort,\n remoteAddress: socket.remoteAddress,\n remotePort: socket.remotePort,\n remoteFamily: socket.remoteFamily,\n timeout: socket.timeout,\n bytesWritten: socket.bytesWritten,\n bytesRead: socket.bytesRead\n }\n}\n\nasync function * convertIterableToBuffer (iterable) {\n for await (const chunk of iterable) {\n yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n }\n}\n\nlet ReadableStream\nfunction ReadableStreamFrom (iterable) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n if (ReadableStream.from) {\n return ReadableStream.from(convertIterableToBuffer(iterable))\n }\n\n let iterator\n return new ReadableStream(\n {\n async start () {\n iterator = iterable[Symbol.asyncIterator]()\n },\n async pull (controller) {\n const { done, value } = await iterator.next()\n if (done) {\n queueMicrotask(() => {\n controller.close()\n })\n } else {\n const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)\n controller.enqueue(new Uint8Array(buf))\n }\n return controller.desiredSize > 0\n },\n async cancel (reason) {\n await iterator.return()\n }\n },\n 0\n )\n}\n\n// The chunk should be a FormData instance and contains\n// all the required methods.\nfunction isFormDataLike (object) {\n return (\n object &&\n typeof object === 'object' &&\n typeof object.append === 'function' &&\n typeof object.delete === 'function' &&\n typeof object.get === 'function' &&\n typeof object.getAll === 'function' &&\n typeof object.has === 'function' &&\n typeof object.set === 'function' &&\n object[Symbol.toStringTag] === 'FormData'\n )\n}\n\nfunction throwIfAborted (signal) {\n if (!signal) { return }\n if (typeof signal.throwIfAborted === 'function') {\n signal.throwIfAborted()\n } else {\n if (signal.aborted) {\n // DOMException not available < v17.0.0\n const err = new Error('The operation was aborted')\n err.name = 'AbortError'\n throw err\n }\n }\n}\n\nfunction addAbortListener (signal, listener) {\n if ('addEventListener' in signal) {\n signal.addEventListener('abort', listener, { once: true })\n return () => signal.removeEventListener('abort', listener)\n }\n signal.addListener('abort', listener)\n return () => signal.removeListener('abort', listener)\n}\n\nconst hasToWellFormed = !!String.prototype.toWellFormed\n\n/**\n * @param {string} val\n */\nfunction toUSVString (val) {\n if (hasToWellFormed) {\n return `${val}`.toWellFormed()\n } else if (nodeUtil.toUSVString) {\n return nodeUtil.toUSVString(val)\n }\n\n return `${val}`\n}\n\n// Parsed accordingly to RFC 9110\n// https://www.rfc-editor.org/rfc/rfc9110#field.content-range\nfunction parseRangeHeader (range) {\n if (range == null || range === '') return { start: 0, end: null, size: null }\n\n const m = range ? range.match(/^bytes (\\d+)-(\\d+)\\/(\\d+)?$/) : null\n return m\n ? {\n start: parseInt(m[1]),\n end: m[2] ? parseInt(m[2]) : null,\n size: m[3] ? parseInt(m[3]) : null\n }\n : null\n}\n\nconst kEnumerableProperty = Object.create(null)\nkEnumerableProperty.enumerable = true\n\nmodule.exports = {\n kEnumerableProperty,\n nop,\n isDisturbed,\n isErrored,\n isReadable,\n toUSVString,\n isReadableAborted,\n isBlobLike,\n parseOrigin,\n parseURL,\n getServerName,\n isStream,\n isIterable,\n isAsyncIterable,\n isDestroyed,\n headerNameToString,\n parseRawHeaders,\n parseHeaders,\n parseKeepAliveTimeout,\n destroy,\n bodyLength,\n deepClone,\n ReadableStreamFrom,\n isBuffer,\n validateHandler,\n getSocketInfo,\n isFormDataLike,\n buildURL,\n throwIfAborted,\n addAbortListener,\n parseRangeHeader,\n nodeMajor,\n nodeMinor,\n nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),\n safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']\n}\n","'use strict'\n\nconst Dispatcher = require('./dispatcher')\nconst {\n ClientDestroyedError,\n ClientClosedError,\n InvalidArgumentError\n} = require('./core/errors')\nconst { kDestroy, kClose, kDispatch, kInterceptors } = require('./core/symbols')\n\nconst kDestroyed = Symbol('destroyed')\nconst kClosed = Symbol('closed')\nconst kOnDestroyed = Symbol('onDestroyed')\nconst kOnClosed = Symbol('onClosed')\nconst kInterceptedDispatch = Symbol('Intercepted Dispatch')\n\nclass DispatcherBase extends Dispatcher {\n constructor () {\n super()\n\n this[kDestroyed] = false\n this[kOnDestroyed] = null\n this[kClosed] = false\n this[kOnClosed] = []\n }\n\n get destroyed () {\n return this[kDestroyed]\n }\n\n get closed () {\n return this[kClosed]\n }\n\n get interceptors () {\n return this[kInterceptors]\n }\n\n set interceptors (newInterceptors) {\n if (newInterceptors) {\n for (let i = newInterceptors.length - 1; i >= 0; i--) {\n const interceptor = this[kInterceptors][i]\n if (typeof interceptor !== 'function') {\n throw new InvalidArgumentError('interceptor must be an function')\n }\n }\n }\n\n this[kInterceptors] = newInterceptors\n }\n\n close (callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n this.close((err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (this[kDestroyed]) {\n queueMicrotask(() => callback(new ClientDestroyedError(), null))\n return\n }\n\n if (this[kClosed]) {\n if (this[kOnClosed]) {\n this[kOnClosed].push(callback)\n } else {\n queueMicrotask(() => callback(null, null))\n }\n return\n }\n\n this[kClosed] = true\n this[kOnClosed].push(callback)\n\n const onClosed = () => {\n const callbacks = this[kOnClosed]\n this[kOnClosed] = null\n for (let i = 0; i < callbacks.length; i++) {\n callbacks[i](null, null)\n }\n }\n\n // Should not error.\n this[kClose]()\n .then(() => this.destroy())\n .then(() => {\n queueMicrotask(onClosed)\n })\n }\n\n destroy (err, callback) {\n if (typeof err === 'function') {\n callback = err\n err = null\n }\n\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n this.destroy(err, (err, data) => {\n return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)\n })\n })\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (this[kDestroyed]) {\n if (this[kOnDestroyed]) {\n this[kOnDestroyed].push(callback)\n } else {\n queueMicrotask(() => callback(null, null))\n }\n return\n }\n\n if (!err) {\n err = new ClientDestroyedError()\n }\n\n this[kDestroyed] = true\n this[kOnDestroyed] = this[kOnDestroyed] || []\n this[kOnDestroyed].push(callback)\n\n const onDestroyed = () => {\n const callbacks = this[kOnDestroyed]\n this[kOnDestroyed] = null\n for (let i = 0; i < callbacks.length; i++) {\n callbacks[i](null, null)\n }\n }\n\n // Should not error.\n this[kDestroy](err).then(() => {\n queueMicrotask(onDestroyed)\n })\n }\n\n [kInterceptedDispatch] (opts, handler) {\n if (!this[kInterceptors] || this[kInterceptors].length === 0) {\n this[kInterceptedDispatch] = this[kDispatch]\n return this[kDispatch](opts, handler)\n }\n\n let dispatch = this[kDispatch].bind(this)\n for (let i = this[kInterceptors].length - 1; i >= 0; i--) {\n dispatch = this[kInterceptors][i](dispatch)\n }\n this[kInterceptedDispatch] = dispatch\n return dispatch(opts, handler)\n }\n\n dispatch (opts, handler) {\n if (!handler || typeof handler !== 'object') {\n throw new InvalidArgumentError('handler must be an object')\n }\n\n try {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('opts must be an object.')\n }\n\n if (this[kDestroyed] || this[kOnDestroyed]) {\n throw new ClientDestroyedError()\n }\n\n if (this[kClosed]) {\n throw new ClientClosedError()\n }\n\n return this[kInterceptedDispatch](opts, handler)\n } catch (err) {\n if (typeof handler.onError !== 'function') {\n throw new InvalidArgumentError('invalid onError method')\n }\n\n handler.onError(err)\n\n return false\n }\n }\n}\n\nmodule.exports = DispatcherBase\n","'use strict'\n\nconst EventEmitter = require('events')\n\nclass Dispatcher extends EventEmitter {\n dispatch () {\n throw new Error('not implemented')\n }\n\n close () {\n throw new Error('not implemented')\n }\n\n destroy () {\n throw new Error('not implemented')\n }\n}\n\nmodule.exports = Dispatcher\n","'use strict'\n\nconst Busboy = require('@fastify/busboy')\nconst util = require('../core/util')\nconst {\n ReadableStreamFrom,\n isBlobLike,\n isReadableStreamLike,\n readableStreamClose,\n createDeferredPromise,\n fullyReadBody\n} = require('./util')\nconst { FormData } = require('./formdata')\nconst { kState } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { DOMException, structuredClone } = require('./constants')\nconst { Blob, File: NativeFile } = require('buffer')\nconst { kBodyUsed } = require('../core/symbols')\nconst assert = require('assert')\nconst { isErrored } = require('../core/util')\nconst { isUint8Array, isArrayBuffer } = require('util/types')\nconst { File: UndiciFile } = require('./file')\nconst { parseMIMEType, serializeAMimeType } = require('./dataURL')\n\nlet ReadableStream = globalThis.ReadableStream\n\n/** @type {globalThis['File']} */\nconst File = NativeFile ?? UndiciFile\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\n// https://fetch.spec.whatwg.org/#concept-bodyinit-extract\nfunction extractBody (object, keepalive = false) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n // 1. Let stream be null.\n let stream = null\n\n // 2. If object is a ReadableStream object, then set stream to object.\n if (object instanceof ReadableStream) {\n stream = object\n } else if (isBlobLike(object)) {\n // 3. Otherwise, if object is a Blob object, set stream to the\n // result of running object’s get stream.\n stream = object.stream()\n } else {\n // 4. Otherwise, set stream to a new ReadableStream object, and set\n // up stream.\n stream = new ReadableStream({\n async pull (controller) {\n controller.enqueue(\n typeof source === 'string' ? textEncoder.encode(source) : source\n )\n queueMicrotask(() => readableStreamClose(controller))\n },\n start () {},\n type: undefined\n })\n }\n\n // 5. Assert: stream is a ReadableStream object.\n assert(isReadableStreamLike(stream))\n\n // 6. Let action be null.\n let action = null\n\n // 7. Let source be null.\n let source = null\n\n // 8. Let length be null.\n let length = null\n\n // 9. Let type be null.\n let type = null\n\n // 10. Switch on object:\n if (typeof object === 'string') {\n // Set source to the UTF-8 encoding of object.\n // Note: setting source to a Uint8Array here breaks some mocking assumptions.\n source = object\n\n // Set type to `text/plain;charset=UTF-8`.\n type = 'text/plain;charset=UTF-8'\n } else if (object instanceof URLSearchParams) {\n // URLSearchParams\n\n // spec says to run application/x-www-form-urlencoded on body.list\n // this is implemented in Node.js as apart of an URLSearchParams instance toString method\n // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490\n // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100\n\n // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.\n source = object.toString()\n\n // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.\n type = 'application/x-www-form-urlencoded;charset=UTF-8'\n } else if (isArrayBuffer(object)) {\n // BufferSource/ArrayBuffer\n\n // Set source to a copy of the bytes held by object.\n source = new Uint8Array(object.slice())\n } else if (ArrayBuffer.isView(object)) {\n // BufferSource/ArrayBufferView\n\n // Set source to a copy of the bytes held by object.\n source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))\n } else if (util.isFormDataLike(object)) {\n const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`\n const prefix = `--${boundary}\\r\\nContent-Disposition: form-data`\n\n /*! formdata-polyfill. MIT License. Jimmy Wärting */\n const escape = (str) =>\n str.replace(/\\n/g, '%0A').replace(/\\r/g, '%0D').replace(/\"/g, '%22')\n const normalizeLinefeeds = (value) => value.replace(/\\r?\\n|\\r/g, '\\r\\n')\n\n // Set action to this step: run the multipart/form-data\n // encoding algorithm, with object’s entry list and UTF-8.\n // - This ensures that the body is immutable and can't be changed afterwords\n // - That the content-length is calculated in advance.\n // - And that all parts are pre-encoded and ready to be sent.\n\n const blobParts = []\n const rn = new Uint8Array([13, 10]) // '\\r\\n'\n length = 0\n let hasUnknownSizeValue = false\n\n for (const [name, value] of object) {\n if (typeof value === 'string') {\n const chunk = textEncoder.encode(prefix +\n `; name=\"${escape(normalizeLinefeeds(name))}\"` +\n `\\r\\n\\r\\n${normalizeLinefeeds(value)}\\r\\n`)\n blobParts.push(chunk)\n length += chunk.byteLength\n } else {\n const chunk = textEncoder.encode(`${prefix}; name=\"${escape(normalizeLinefeeds(name))}\"` +\n (value.name ? `; filename=\"${escape(value.name)}\"` : '') + '\\r\\n' +\n `Content-Type: ${\n value.type || 'application/octet-stream'\n }\\r\\n\\r\\n`)\n blobParts.push(chunk, value, rn)\n if (typeof value.size === 'number') {\n length += chunk.byteLength + value.size + rn.byteLength\n } else {\n hasUnknownSizeValue = true\n }\n }\n }\n\n const chunk = textEncoder.encode(`--${boundary}--`)\n blobParts.push(chunk)\n length += chunk.byteLength\n if (hasUnknownSizeValue) {\n length = null\n }\n\n // Set source to object.\n source = object\n\n action = async function * () {\n for (const part of blobParts) {\n if (part.stream) {\n yield * part.stream()\n } else {\n yield part\n }\n }\n }\n\n // Set type to `multipart/form-data; boundary=`,\n // followed by the multipart/form-data boundary string generated\n // by the multipart/form-data encoding algorithm.\n type = 'multipart/form-data; boundary=' + boundary\n } else if (isBlobLike(object)) {\n // Blob\n\n // Set source to object.\n source = object\n\n // Set length to object’s size.\n length = object.size\n\n // If object’s type attribute is not the empty byte sequence, set\n // type to its value.\n if (object.type) {\n type = object.type\n }\n } else if (typeof object[Symbol.asyncIterator] === 'function') {\n // If keepalive is true, then throw a TypeError.\n if (keepalive) {\n throw new TypeError('keepalive')\n }\n\n // If object is disturbed or locked, then throw a TypeError.\n if (util.isDisturbed(object) || object.locked) {\n throw new TypeError(\n 'Response body object should not be disturbed or locked'\n )\n }\n\n stream =\n object instanceof ReadableStream ? object : ReadableStreamFrom(object)\n }\n\n // 11. If source is a byte sequence, then set action to a\n // step that returns source and length to source’s length.\n if (typeof source === 'string' || util.isBuffer(source)) {\n length = Buffer.byteLength(source)\n }\n\n // 12. If action is non-null, then run these steps in in parallel:\n if (action != null) {\n // Run action.\n let iterator\n stream = new ReadableStream({\n async start () {\n iterator = action(object)[Symbol.asyncIterator]()\n },\n async pull (controller) {\n const { value, done } = await iterator.next()\n if (done) {\n // When running action is done, close stream.\n queueMicrotask(() => {\n controller.close()\n })\n } else {\n // Whenever one or more bytes are available and stream is not errored,\n // enqueue a Uint8Array wrapping an ArrayBuffer containing the available\n // bytes into stream.\n if (!isErrored(stream)) {\n controller.enqueue(new Uint8Array(value))\n }\n }\n return controller.desiredSize > 0\n },\n async cancel (reason) {\n await iterator.return()\n },\n type: undefined\n })\n }\n\n // 13. Let body be a body whose stream is stream, source is source,\n // and length is length.\n const body = { stream, source, length }\n\n // 14. Return (body, type).\n return [body, type]\n}\n\n// https://fetch.spec.whatwg.org/#bodyinit-safely-extract\nfunction safelyExtractBody (object, keepalive = false) {\n if (!ReadableStream) {\n // istanbul ignore next\n ReadableStream = require('stream/web').ReadableStream\n }\n\n // To safely extract a body and a `Content-Type` value from\n // a byte sequence or BodyInit object object, run these steps:\n\n // 1. If object is a ReadableStream object, then:\n if (object instanceof ReadableStream) {\n // Assert: object is neither disturbed nor locked.\n // istanbul ignore next\n assert(!util.isDisturbed(object), 'The body has already been consumed.')\n // istanbul ignore next\n assert(!object.locked, 'The stream is locked.')\n }\n\n // 2. Return the results of extracting object.\n return extractBody(object, keepalive)\n}\n\nfunction cloneBody (body) {\n // To clone a body body, run these steps:\n\n // https://fetch.spec.whatwg.org/#concept-body-clone\n\n // 1. Let « out1, out2 » be the result of teeing body’s stream.\n const [out1, out2] = body.stream.tee()\n const out2Clone = structuredClone(out2, { transfer: [out2] })\n // This, for whatever reasons, unrefs out2Clone which allows\n // the process to exit by itself.\n const [, finalClone] = out2Clone.tee()\n\n // 2. Set body’s stream to out1.\n body.stream = out1\n\n // 3. Return a body whose stream is out2 and other members are copied from body.\n return {\n stream: finalClone,\n length: body.length,\n source: body.source\n }\n}\n\nasync function * consumeBody (body) {\n if (body) {\n if (isUint8Array(body)) {\n yield body\n } else {\n const stream = body.stream\n\n if (util.isDisturbed(stream)) {\n throw new TypeError('The body has already been consumed.')\n }\n\n if (stream.locked) {\n throw new TypeError('The stream is locked.')\n }\n\n // Compat.\n stream[kBodyUsed] = true\n\n yield * stream\n }\n }\n}\n\nfunction throwIfAborted (state) {\n if (state.aborted) {\n throw new DOMException('The operation was aborted.', 'AbortError')\n }\n}\n\nfunction bodyMixinMethods (instance) {\n const methods = {\n blob () {\n // The blob() method steps are to return the result of\n // running consume body with this and the following step\n // given a byte sequence bytes: return a Blob whose\n // contents are bytes and whose type attribute is this’s\n // MIME type.\n return specConsumeBody(this, (bytes) => {\n let mimeType = bodyMimeType(this)\n\n if (mimeType === 'failure') {\n mimeType = ''\n } else if (mimeType) {\n mimeType = serializeAMimeType(mimeType)\n }\n\n // Return a Blob whose contents are bytes and type attribute\n // is mimeType.\n return new Blob([bytes], { type: mimeType })\n }, instance)\n },\n\n arrayBuffer () {\n // The arrayBuffer() method steps are to return the result\n // of running consume body with this and the following step\n // given a byte sequence bytes: return a new ArrayBuffer\n // whose contents are bytes.\n return specConsumeBody(this, (bytes) => {\n return new Uint8Array(bytes).buffer\n }, instance)\n },\n\n text () {\n // The text() method steps are to return the result of running\n // consume body with this and UTF-8 decode.\n return specConsumeBody(this, utf8DecodeBytes, instance)\n },\n\n json () {\n // The json() method steps are to return the result of running\n // consume body with this and parse JSON from bytes.\n return specConsumeBody(this, parseJSONFromBytes, instance)\n },\n\n async formData () {\n webidl.brandCheck(this, instance)\n\n throwIfAborted(this[kState])\n\n const contentType = this.headers.get('Content-Type')\n\n // If mimeType’s essence is \"multipart/form-data\", then:\n if (/multipart\\/form-data/.test(contentType)) {\n const headers = {}\n for (const [key, value] of this.headers) headers[key.toLowerCase()] = value\n\n const responseFormData = new FormData()\n\n let busboy\n\n try {\n busboy = new Busboy({\n headers,\n preservePath: true\n })\n } catch (err) {\n throw new DOMException(`${err}`, 'AbortError')\n }\n\n busboy.on('field', (name, value) => {\n responseFormData.append(name, value)\n })\n busboy.on('file', (name, value, filename, encoding, mimeType) => {\n const chunks = []\n\n if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {\n let base64chunk = ''\n\n value.on('data', (chunk) => {\n base64chunk += chunk.toString().replace(/[\\r\\n]/gm, '')\n\n const end = base64chunk.length - base64chunk.length % 4\n chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))\n\n base64chunk = base64chunk.slice(end)\n })\n value.on('end', () => {\n chunks.push(Buffer.from(base64chunk, 'base64'))\n responseFormData.append(name, new File(chunks, filename, { type: mimeType }))\n })\n } else {\n value.on('data', (chunk) => {\n chunks.push(chunk)\n })\n value.on('end', () => {\n responseFormData.append(name, new File(chunks, filename, { type: mimeType }))\n })\n }\n })\n\n const busboyResolve = new Promise((resolve, reject) => {\n busboy.on('finish', resolve)\n busboy.on('error', (err) => reject(new TypeError(err)))\n })\n\n if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)\n busboy.end()\n await busboyResolve\n\n return responseFormData\n } else if (/application\\/x-www-form-urlencoded/.test(contentType)) {\n // Otherwise, if mimeType’s essence is \"application/x-www-form-urlencoded\", then:\n\n // 1. Let entries be the result of parsing bytes.\n let entries\n try {\n let text = ''\n // application/x-www-form-urlencoded parser will keep the BOM.\n // https://url.spec.whatwg.org/#concept-urlencoded-parser\n // Note that streaming decoder is stateful and cannot be reused\n const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })\n\n for await (const chunk of consumeBody(this[kState].body)) {\n if (!isUint8Array(chunk)) {\n throw new TypeError('Expected Uint8Array chunk')\n }\n text += streamingDecoder.decode(chunk, { stream: true })\n }\n text += streamingDecoder.decode()\n entries = new URLSearchParams(text)\n } catch (err) {\n // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.\n // 2. If entries is failure, then throw a TypeError.\n throw Object.assign(new TypeError(), { cause: err })\n }\n\n // 3. Return a new FormData object whose entries are entries.\n const formData = new FormData()\n for (const [name, value] of entries) {\n formData.append(name, value)\n }\n return formData\n } else {\n // Wait a tick before checking if the request has been aborted.\n // Otherwise, a TypeError can be thrown when an AbortError should.\n await Promise.resolve()\n\n throwIfAborted(this[kState])\n\n // Otherwise, throw a TypeError.\n throw webidl.errors.exception({\n header: `${instance.name}.formData`,\n message: 'Could not parse content as FormData.'\n })\n }\n }\n }\n\n return methods\n}\n\nfunction mixinBody (prototype) {\n Object.assign(prototype.prototype, bodyMixinMethods(prototype))\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-body-consume-body\n * @param {Response|Request} object\n * @param {(value: unknown) => unknown} convertBytesToJSValue\n * @param {Response|Request} instance\n */\nasync function specConsumeBody (object, convertBytesToJSValue, instance) {\n webidl.brandCheck(object, instance)\n\n throwIfAborted(object[kState])\n\n // 1. If object is unusable, then return a promise rejected\n // with a TypeError.\n if (bodyUnusable(object[kState].body)) {\n throw new TypeError('Body is unusable')\n }\n\n // 2. Let promise be a new promise.\n const promise = createDeferredPromise()\n\n // 3. Let errorSteps given error be to reject promise with error.\n const errorSteps = (error) => promise.reject(error)\n\n // 4. Let successSteps given a byte sequence data be to resolve\n // promise with the result of running convertBytesToJSValue\n // with data. If that threw an exception, then run errorSteps\n // with that exception.\n const successSteps = (data) => {\n try {\n promise.resolve(convertBytesToJSValue(data))\n } catch (e) {\n errorSteps(e)\n }\n }\n\n // 5. If object’s body is null, then run successSteps with an\n // empty byte sequence.\n if (object[kState].body == null) {\n successSteps(new Uint8Array())\n return promise.promise\n }\n\n // 6. Otherwise, fully read object’s body given successSteps,\n // errorSteps, and object’s relevant global object.\n await fullyReadBody(object[kState].body, successSteps, errorSteps)\n\n // 7. Return promise.\n return promise.promise\n}\n\n// https://fetch.spec.whatwg.org/#body-unusable\nfunction bodyUnusable (body) {\n // An object including the Body interface mixin is\n // said to be unusable if its body is non-null and\n // its body’s stream is disturbed or locked.\n return body != null && (body.stream.locked || util.isDisturbed(body.stream))\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#utf-8-decode\n * @param {Buffer} buffer\n */\nfunction utf8DecodeBytes (buffer) {\n if (buffer.length === 0) {\n return ''\n }\n\n // 1. Let buffer be the result of peeking three bytes from\n // ioQueue, converted to a byte sequence.\n\n // 2. If buffer is 0xEF 0xBB 0xBF, then read three\n // bytes from ioQueue. (Do nothing with those bytes.)\n if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {\n buffer = buffer.subarray(3)\n }\n\n // 3. Process a queue with an instance of UTF-8’s\n // decoder, ioQueue, output, and \"replacement\".\n const output = textDecoder.decode(buffer)\n\n // 4. Return output.\n return output\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value\n * @param {Uint8Array} bytes\n */\nfunction parseJSONFromBytes (bytes) {\n return JSON.parse(utf8DecodeBytes(bytes))\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-body-mime-type\n * @param {import('./response').Response|import('./request').Request} object\n */\nfunction bodyMimeType (object) {\n const { headersList } = object[kState]\n const contentType = headersList.get('content-type')\n\n if (contentType === null) {\n return 'failure'\n }\n\n return parseMIMEType(contentType)\n}\n\nmodule.exports = {\n extractBody,\n safelyExtractBody,\n cloneBody,\n mixinBody\n}\n","'use strict'\n\nconst { MessageChannel, receiveMessageOnPort } = require('worker_threads')\n\nconst corsSafeListedMethods = ['GET', 'HEAD', 'POST']\nconst corsSafeListedMethodsSet = new Set(corsSafeListedMethods)\n\nconst nullBodyStatus = [101, 204, 205, 304]\n\nconst redirectStatus = [301, 302, 303, 307, 308]\nconst redirectStatusSet = new Set(redirectStatus)\n\n// https://fetch.spec.whatwg.org/#block-bad-port\nconst badPorts = [\n '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',\n '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',\n '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',\n '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',\n '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',\n '10080'\n]\n\nconst badPortsSet = new Set(badPorts)\n\n// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies\nconst referrerPolicy = [\n '',\n 'no-referrer',\n 'no-referrer-when-downgrade',\n 'same-origin',\n 'origin',\n 'strict-origin',\n 'origin-when-cross-origin',\n 'strict-origin-when-cross-origin',\n 'unsafe-url'\n]\nconst referrerPolicySet = new Set(referrerPolicy)\n\nconst requestRedirect = ['follow', 'manual', 'error']\n\nconst safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']\nconst safeMethodsSet = new Set(safeMethods)\n\nconst requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']\n\nconst requestCredentials = ['omit', 'same-origin', 'include']\n\nconst requestCache = [\n 'default',\n 'no-store',\n 'reload',\n 'no-cache',\n 'force-cache',\n 'only-if-cached'\n]\n\n// https://fetch.spec.whatwg.org/#request-body-header-name\nconst requestBodyHeader = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n // See https://github.com/nodejs/undici/issues/2021\n // 'Content-Length' is a forbidden header name, which is typically\n // removed in the Headers implementation. However, undici doesn't\n // filter out headers, so we add it here.\n 'content-length'\n]\n\n// https://fetch.spec.whatwg.org/#enumdef-requestduplex\nconst requestDuplex = [\n 'half'\n]\n\n// http://fetch.spec.whatwg.org/#forbidden-method\nconst forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']\nconst forbiddenMethodsSet = new Set(forbiddenMethods)\n\nconst subresource = [\n 'audio',\n 'audioworklet',\n 'font',\n 'image',\n 'manifest',\n 'paintworklet',\n 'script',\n 'style',\n 'track',\n 'video',\n 'xslt',\n ''\n]\nconst subresourceSet = new Set(subresource)\n\n/** @type {globalThis['DOMException']} */\nconst DOMException = globalThis.DOMException ?? (() => {\n // DOMException was only made a global in Node v17.0.0,\n // but fetch supports >= v16.8.\n try {\n atob('~')\n } catch (err) {\n return Object.getPrototypeOf(err).constructor\n }\n})()\n\nlet channel\n\n/** @type {globalThis['structuredClone']} */\nconst structuredClone =\n globalThis.structuredClone ??\n // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js\n // structuredClone was added in v17.0.0, but fetch supports v16.8\n function structuredClone (value, options = undefined) {\n if (arguments.length === 0) {\n throw new TypeError('missing argument')\n }\n\n if (!channel) {\n channel = new MessageChannel()\n }\n channel.port1.unref()\n channel.port2.unref()\n channel.port1.postMessage(value, options?.transfer)\n return receiveMessageOnPort(channel.port2).message\n }\n\nmodule.exports = {\n DOMException,\n structuredClone,\n subresource,\n forbiddenMethods,\n requestBodyHeader,\n referrerPolicy,\n requestRedirect,\n requestMode,\n requestCredentials,\n requestCache,\n redirectStatus,\n corsSafeListedMethods,\n nullBodyStatus,\n safeMethods,\n badPorts,\n requestDuplex,\n subresourceSet,\n badPortsSet,\n redirectStatusSet,\n corsSafeListedMethodsSet,\n safeMethodsSet,\n forbiddenMethodsSet,\n referrerPolicySet\n}\n","const assert = require('assert')\nconst { atob } = require('buffer')\nconst { isomorphicDecode } = require('./util')\n\nconst encoder = new TextEncoder()\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#http-token-code-point\n */\nconst HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/\nconst HTTP_WHITESPACE_REGEX = /(\\u000A|\\u000D|\\u0009|\\u0020)/ // eslint-disable-line\n/**\n * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point\n */\nconst HTTP_QUOTED_STRING_TOKENS = /[\\u0009|\\u0020-\\u007E|\\u0080-\\u00FF]/ // eslint-disable-line\n\n// https://fetch.spec.whatwg.org/#data-url-processor\n/** @param {URL} dataURL */\nfunction dataURLProcessor (dataURL) {\n // 1. Assert: dataURL’s scheme is \"data\".\n assert(dataURL.protocol === 'data:')\n\n // 2. Let input be the result of running the URL\n // serializer on dataURL with exclude fragment\n // set to true.\n let input = URLSerializer(dataURL, true)\n\n // 3. Remove the leading \"data:\" string from input.\n input = input.slice(5)\n\n // 4. Let position point at the start of input.\n const position = { position: 0 }\n\n // 5. Let mimeType be the result of collecting a\n // sequence of code points that are not equal\n // to U+002C (,), given position.\n let mimeType = collectASequenceOfCodePointsFast(\n ',',\n input,\n position\n )\n\n // 6. Strip leading and trailing ASCII whitespace\n // from mimeType.\n // Undici implementation note: we need to store the\n // length because if the mimetype has spaces removed,\n // the wrong amount will be sliced from the input in\n // step #9\n const mimeTypeLength = mimeType.length\n mimeType = removeASCIIWhitespace(mimeType, true, true)\n\n // 7. If position is past the end of input, then\n // return failure\n if (position.position >= input.length) {\n return 'failure'\n }\n\n // 8. Advance position by 1.\n position.position++\n\n // 9. Let encodedBody be the remainder of input.\n const encodedBody = input.slice(mimeTypeLength + 1)\n\n // 10. Let body be the percent-decoding of encodedBody.\n let body = stringPercentDecode(encodedBody)\n\n // 11. If mimeType ends with U+003B (;), followed by\n // zero or more U+0020 SPACE, followed by an ASCII\n // case-insensitive match for \"base64\", then:\n if (/;(\\u0020){0,}base64$/i.test(mimeType)) {\n // 1. Let stringBody be the isomorphic decode of body.\n const stringBody = isomorphicDecode(body)\n\n // 2. Set body to the forgiving-base64 decode of\n // stringBody.\n body = forgivingBase64(stringBody)\n\n // 3. If body is failure, then return failure.\n if (body === 'failure') {\n return 'failure'\n }\n\n // 4. Remove the last 6 code points from mimeType.\n mimeType = mimeType.slice(0, -6)\n\n // 5. Remove trailing U+0020 SPACE code points from mimeType,\n // if any.\n mimeType = mimeType.replace(/(\\u0020)+$/, '')\n\n // 6. Remove the last U+003B (;) code point from mimeType.\n mimeType = mimeType.slice(0, -1)\n }\n\n // 12. If mimeType starts with U+003B (;), then prepend\n // \"text/plain\" to mimeType.\n if (mimeType.startsWith(';')) {\n mimeType = 'text/plain' + mimeType\n }\n\n // 13. Let mimeTypeRecord be the result of parsing\n // mimeType.\n let mimeTypeRecord = parseMIMEType(mimeType)\n\n // 14. If mimeTypeRecord is failure, then set\n // mimeTypeRecord to text/plain;charset=US-ASCII.\n if (mimeTypeRecord === 'failure') {\n mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')\n }\n\n // 15. Return a new data: URL struct whose MIME\n // type is mimeTypeRecord and body is body.\n // https://fetch.spec.whatwg.org/#data-url-struct\n return { mimeType: mimeTypeRecord, body }\n}\n\n// https://url.spec.whatwg.org/#concept-url-serializer\n/**\n * @param {URL} url\n * @param {boolean} excludeFragment\n */\nfunction URLSerializer (url, excludeFragment = false) {\n if (!excludeFragment) {\n return url.href\n }\n\n const href = url.href\n const hashLength = url.hash.length\n\n return hashLength === 0 ? href : href.substring(0, href.length - hashLength)\n}\n\n// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points\n/**\n * @param {(char: string) => boolean} condition\n * @param {string} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfCodePoints (condition, input, position) {\n // 1. Let result be the empty string.\n let result = ''\n\n // 2. While position doesn’t point past the end of input and the\n // code point at position within input meets the condition condition:\n while (position.position < input.length && condition(input[position.position])) {\n // 1. Append that code point to the end of result.\n result += input[position.position]\n\n // 2. Advance position by 1.\n position.position++\n }\n\n // 3. Return result.\n return result\n}\n\n/**\n * A faster collectASequenceOfCodePoints that only works when comparing a single character.\n * @param {string} char\n * @param {string} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfCodePointsFast (char, input, position) {\n const idx = input.indexOf(char, position.position)\n const start = position.position\n\n if (idx === -1) {\n position.position = input.length\n return input.slice(start)\n }\n\n position.position = idx\n return input.slice(start, position.position)\n}\n\n// https://url.spec.whatwg.org/#string-percent-decode\n/** @param {string} input */\nfunction stringPercentDecode (input) {\n // 1. Let bytes be the UTF-8 encoding of input.\n const bytes = encoder.encode(input)\n\n // 2. Return the percent-decoding of bytes.\n return percentDecode(bytes)\n}\n\n// https://url.spec.whatwg.org/#percent-decode\n/** @param {Uint8Array} input */\nfunction percentDecode (input) {\n // 1. Let output be an empty byte sequence.\n /** @type {number[]} */\n const output = []\n\n // 2. For each byte byte in input:\n for (let i = 0; i < input.length; i++) {\n const byte = input[i]\n\n // 1. If byte is not 0x25 (%), then append byte to output.\n if (byte !== 0x25) {\n output.push(byte)\n\n // 2. Otherwise, if byte is 0x25 (%) and the next two bytes\n // after byte in input are not in the ranges\n // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),\n // and 0x61 (a) to 0x66 (f), all inclusive, append byte\n // to output.\n } else if (\n byte === 0x25 &&\n !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))\n ) {\n output.push(0x25)\n\n // 3. Otherwise:\n } else {\n // 1. Let bytePoint be the two bytes after byte in input,\n // decoded, and then interpreted as hexadecimal number.\n const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])\n const bytePoint = Number.parseInt(nextTwoBytes, 16)\n\n // 2. Append a byte whose value is bytePoint to output.\n output.push(bytePoint)\n\n // 3. Skip the next two bytes in input.\n i += 2\n }\n }\n\n // 3. Return output.\n return Uint8Array.from(output)\n}\n\n// https://mimesniff.spec.whatwg.org/#parse-a-mime-type\n/** @param {string} input */\nfunction parseMIMEType (input) {\n // 1. Remove any leading and trailing HTTP whitespace\n // from input.\n input = removeHTTPWhitespace(input, true, true)\n\n // 2. Let position be a position variable for input,\n // initially pointing at the start of input.\n const position = { position: 0 }\n\n // 3. Let type be the result of collecting a sequence\n // of code points that are not U+002F (/) from\n // input, given position.\n const type = collectASequenceOfCodePointsFast(\n '/',\n input,\n position\n )\n\n // 4. If type is the empty string or does not solely\n // contain HTTP token code points, then return failure.\n // https://mimesniff.spec.whatwg.org/#http-token-code-point\n if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {\n return 'failure'\n }\n\n // 5. If position is past the end of input, then return\n // failure\n if (position.position > input.length) {\n return 'failure'\n }\n\n // 6. Advance position by 1. (This skips past U+002F (/).)\n position.position++\n\n // 7. Let subtype be the result of collecting a sequence of\n // code points that are not U+003B (;) from input, given\n // position.\n let subtype = collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 8. Remove any trailing HTTP whitespace from subtype.\n subtype = removeHTTPWhitespace(subtype, false, true)\n\n // 9. If subtype is the empty string or does not solely\n // contain HTTP token code points, then return failure.\n if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {\n return 'failure'\n }\n\n const typeLowercase = type.toLowerCase()\n const subtypeLowercase = subtype.toLowerCase()\n\n // 10. Let mimeType be a new MIME type record whose type\n // is type, in ASCII lowercase, and subtype is subtype,\n // in ASCII lowercase.\n // https://mimesniff.spec.whatwg.org/#mime-type\n const mimeType = {\n type: typeLowercase,\n subtype: subtypeLowercase,\n /** @type {Map} */\n parameters: new Map(),\n // https://mimesniff.spec.whatwg.org/#mime-type-essence\n essence: `${typeLowercase}/${subtypeLowercase}`\n }\n\n // 11. While position is not past the end of input:\n while (position.position < input.length) {\n // 1. Advance position by 1. (This skips past U+003B (;).)\n position.position++\n\n // 2. Collect a sequence of code points that are HTTP\n // whitespace from input given position.\n collectASequenceOfCodePoints(\n // https://fetch.spec.whatwg.org/#http-whitespace\n char => HTTP_WHITESPACE_REGEX.test(char),\n input,\n position\n )\n\n // 3. Let parameterName be the result of collecting a\n // sequence of code points that are not U+003B (;)\n // or U+003D (=) from input, given position.\n let parameterName = collectASequenceOfCodePoints(\n (char) => char !== ';' && char !== '=',\n input,\n position\n )\n\n // 4. Set parameterName to parameterName, in ASCII\n // lowercase.\n parameterName = parameterName.toLowerCase()\n\n // 5. If position is not past the end of input, then:\n if (position.position < input.length) {\n // 1. If the code point at position within input is\n // U+003B (;), then continue.\n if (input[position.position] === ';') {\n continue\n }\n\n // 2. Advance position by 1. (This skips past U+003D (=).)\n position.position++\n }\n\n // 6. If position is past the end of input, then break.\n if (position.position > input.length) {\n break\n }\n\n // 7. Let parameterValue be null.\n let parameterValue = null\n\n // 8. If the code point at position within input is\n // U+0022 (\"), then:\n if (input[position.position] === '\"') {\n // 1. Set parameterValue to the result of collecting\n // an HTTP quoted string from input, given position\n // and the extract-value flag.\n parameterValue = collectAnHTTPQuotedString(input, position, true)\n\n // 2. Collect a sequence of code points that are not\n // U+003B (;) from input, given position.\n collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 9. Otherwise:\n } else {\n // 1. Set parameterValue to the result of collecting\n // a sequence of code points that are not U+003B (;)\n // from input, given position.\n parameterValue = collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 2. Remove any trailing HTTP whitespace from parameterValue.\n parameterValue = removeHTTPWhitespace(parameterValue, false, true)\n\n // 3. If parameterValue is the empty string, then continue.\n if (parameterValue.length === 0) {\n continue\n }\n }\n\n // 10. If all of the following are true\n // - parameterName is not the empty string\n // - parameterName solely contains HTTP token code points\n // - parameterValue solely contains HTTP quoted-string token code points\n // - mimeType’s parameters[parameterName] does not exist\n // then set mimeType’s parameters[parameterName] to parameterValue.\n if (\n parameterName.length !== 0 &&\n HTTP_TOKEN_CODEPOINTS.test(parameterName) &&\n (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&\n !mimeType.parameters.has(parameterName)\n ) {\n mimeType.parameters.set(parameterName, parameterValue)\n }\n }\n\n // 12. Return mimeType.\n return mimeType\n}\n\n// https://infra.spec.whatwg.org/#forgiving-base64-decode\n/** @param {string} data */\nfunction forgivingBase64 (data) {\n // 1. Remove all ASCII whitespace from data.\n data = data.replace(/[\\u0009\\u000A\\u000C\\u000D\\u0020]/g, '') // eslint-disable-line\n\n // 2. If data’s code point length divides by 4 leaving\n // no remainder, then:\n if (data.length % 4 === 0) {\n // 1. If data ends with one or two U+003D (=) code points,\n // then remove them from data.\n data = data.replace(/=?=$/, '')\n }\n\n // 3. If data’s code point length divides by 4 leaving\n // a remainder of 1, then return failure.\n if (data.length % 4 === 1) {\n return 'failure'\n }\n\n // 4. If data contains a code point that is not one of\n // U+002B (+)\n // U+002F (/)\n // ASCII alphanumeric\n // then return failure.\n if (/[^+/0-9A-Za-z]/.test(data)) {\n return 'failure'\n }\n\n const binary = atob(data)\n const bytes = new Uint8Array(binary.length)\n\n for (let byte = 0; byte < binary.length; byte++) {\n bytes[byte] = binary.charCodeAt(byte)\n }\n\n return bytes\n}\n\n// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string\n// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string\n/**\n * @param {string} input\n * @param {{ position: number }} position\n * @param {boolean?} extractValue\n */\nfunction collectAnHTTPQuotedString (input, position, extractValue) {\n // 1. Let positionStart be position.\n const positionStart = position.position\n\n // 2. Let value be the empty string.\n let value = ''\n\n // 3. Assert: the code point at position within input\n // is U+0022 (\").\n assert(input[position.position] === '\"')\n\n // 4. Advance position by 1.\n position.position++\n\n // 5. While true:\n while (true) {\n // 1. Append the result of collecting a sequence of code points\n // that are not U+0022 (\") or U+005C (\\) from input, given\n // position, to value.\n value += collectASequenceOfCodePoints(\n (char) => char !== '\"' && char !== '\\\\',\n input,\n position\n )\n\n // 2. If position is past the end of input, then break.\n if (position.position >= input.length) {\n break\n }\n\n // 3. Let quoteOrBackslash be the code point at position within\n // input.\n const quoteOrBackslash = input[position.position]\n\n // 4. Advance position by 1.\n position.position++\n\n // 5. If quoteOrBackslash is U+005C (\\), then:\n if (quoteOrBackslash === '\\\\') {\n // 1. If position is past the end of input, then append\n // U+005C (\\) to value and break.\n if (position.position >= input.length) {\n value += '\\\\'\n break\n }\n\n // 2. Append the code point at position within input to value.\n value += input[position.position]\n\n // 3. Advance position by 1.\n position.position++\n\n // 6. Otherwise:\n } else {\n // 1. Assert: quoteOrBackslash is U+0022 (\").\n assert(quoteOrBackslash === '\"')\n\n // 2. Break.\n break\n }\n }\n\n // 6. If the extract-value flag is set, then return value.\n if (extractValue) {\n return value\n }\n\n // 7. Return the code points from positionStart to position,\n // inclusive, within input.\n return input.slice(positionStart, position.position)\n}\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type\n */\nfunction serializeAMimeType (mimeType) {\n assert(mimeType !== 'failure')\n const { parameters, essence } = mimeType\n\n // 1. Let serialization be the concatenation of mimeType’s\n // type, U+002F (/), and mimeType’s subtype.\n let serialization = essence\n\n // 2. For each name → value of mimeType’s parameters:\n for (let [name, value] of parameters.entries()) {\n // 1. Append U+003B (;) to serialization.\n serialization += ';'\n\n // 2. Append name to serialization.\n serialization += name\n\n // 3. Append U+003D (=) to serialization.\n serialization += '='\n\n // 4. If value does not solely contain HTTP token code\n // points or value is the empty string, then:\n if (!HTTP_TOKEN_CODEPOINTS.test(value)) {\n // 1. Precede each occurence of U+0022 (\") or\n // U+005C (\\) in value with U+005C (\\).\n value = value.replace(/(\\\\|\")/g, '\\\\$1')\n\n // 2. Prepend U+0022 (\") to value.\n value = '\"' + value\n\n // 3. Append U+0022 (\") to value.\n value += '\"'\n }\n\n // 5. Append value to serialization.\n serialization += value\n }\n\n // 3. Return serialization.\n return serialization\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-whitespace\n * @param {string} char\n */\nfunction isHTTPWhiteSpace (char) {\n return char === '\\r' || char === '\\n' || char === '\\t' || char === ' '\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-whitespace\n * @param {string} str\n */\nfunction removeHTTPWhitespace (str, leading = true, trailing = true) {\n let lead = 0\n let trail = str.length - 1\n\n if (leading) {\n for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);\n }\n\n if (trailing) {\n for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);\n }\n\n return str.slice(lead, trail + 1)\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#ascii-whitespace\n * @param {string} char\n */\nfunction isASCIIWhitespace (char) {\n return char === '\\r' || char === '\\n' || char === '\\t' || char === '\\f' || char === ' '\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace\n */\nfunction removeASCIIWhitespace (str, leading = true, trailing = true) {\n let lead = 0\n let trail = str.length - 1\n\n if (leading) {\n for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);\n }\n\n if (trailing) {\n for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);\n }\n\n return str.slice(lead, trail + 1)\n}\n\nmodule.exports = {\n dataURLProcessor,\n URLSerializer,\n collectASequenceOfCodePoints,\n collectASequenceOfCodePointsFast,\n stringPercentDecode,\n parseMIMEType,\n collectAnHTTPQuotedString,\n serializeAMimeType\n}\n","'use strict'\n\nconst { Blob, File: NativeFile } = require('buffer')\nconst { types } = require('util')\nconst { kState } = require('./symbols')\nconst { isBlobLike } = require('./util')\nconst { webidl } = require('./webidl')\nconst { parseMIMEType, serializeAMimeType } = require('./dataURL')\nconst { kEnumerableProperty } = require('../core/util')\nconst encoder = new TextEncoder()\n\nclass File extends Blob {\n constructor (fileBits, fileName, options = {}) {\n // The File constructor is invoked with two or three parameters, depending\n // on whether the optional dictionary parameter is used. When the File()\n // constructor is invoked, user agents must run the following steps:\n webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })\n\n fileBits = webidl.converters['sequence'](fileBits)\n fileName = webidl.converters.USVString(fileName)\n options = webidl.converters.FilePropertyBag(options)\n\n // 1. Let bytes be the result of processing blob parts given fileBits and\n // options.\n // Note: Blob handles this for us\n\n // 2. Let n be the fileName argument to the constructor.\n const n = fileName\n\n // 3. Process FilePropertyBag dictionary argument by running the following\n // substeps:\n\n // 1. If the type member is provided and is not the empty string, let t\n // be set to the type dictionary member. If t contains any characters\n // outside the range U+0020 to U+007E, then set t to the empty string\n // and return from these substeps.\n // 2. Convert every character in t to ASCII lowercase.\n let t = options.type\n let d\n\n // eslint-disable-next-line no-labels\n substep: {\n if (t) {\n t = parseMIMEType(t)\n\n if (t === 'failure') {\n t = ''\n // eslint-disable-next-line no-labels\n break substep\n }\n\n t = serializeAMimeType(t).toLowerCase()\n }\n\n // 3. If the lastModified member is provided, let d be set to the\n // lastModified dictionary member. If it is not provided, set d to the\n // current date and time represented as the number of milliseconds since\n // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).\n d = options.lastModified\n }\n\n // 4. Return a new File object F such that:\n // F refers to the bytes byte sequence.\n // F.size is set to the number of total bytes in bytes.\n // F.name is set to n.\n // F.type is set to t.\n // F.lastModified is set to d.\n\n super(processBlobParts(fileBits, options), { type: t })\n this[kState] = {\n name: n,\n lastModified: d,\n type: t\n }\n }\n\n get name () {\n webidl.brandCheck(this, File)\n\n return this[kState].name\n }\n\n get lastModified () {\n webidl.brandCheck(this, File)\n\n return this[kState].lastModified\n }\n\n get type () {\n webidl.brandCheck(this, File)\n\n return this[kState].type\n }\n}\n\nclass FileLike {\n constructor (blobLike, fileName, options = {}) {\n // TODO: argument idl type check\n\n // The File constructor is invoked with two or three parameters, depending\n // on whether the optional dictionary parameter is used. When the File()\n // constructor is invoked, user agents must run the following steps:\n\n // 1. Let bytes be the result of processing blob parts given fileBits and\n // options.\n\n // 2. Let n be the fileName argument to the constructor.\n const n = fileName\n\n // 3. Process FilePropertyBag dictionary argument by running the following\n // substeps:\n\n // 1. If the type member is provided and is not the empty string, let t\n // be set to the type dictionary member. If t contains any characters\n // outside the range U+0020 to U+007E, then set t to the empty string\n // and return from these substeps.\n // TODO\n const t = options.type\n\n // 2. Convert every character in t to ASCII lowercase.\n // TODO\n\n // 3. If the lastModified member is provided, let d be set to the\n // lastModified dictionary member. If it is not provided, set d to the\n // current date and time represented as the number of milliseconds since\n // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).\n const d = options.lastModified ?? Date.now()\n\n // 4. Return a new File object F such that:\n // F refers to the bytes byte sequence.\n // F.size is set to the number of total bytes in bytes.\n // F.name is set to n.\n // F.type is set to t.\n // F.lastModified is set to d.\n\n this[kState] = {\n blobLike,\n name: n,\n type: t,\n lastModified: d\n }\n }\n\n stream (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.stream(...args)\n }\n\n arrayBuffer (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.arrayBuffer(...args)\n }\n\n slice (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.slice(...args)\n }\n\n text (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.text(...args)\n }\n\n get size () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.size\n }\n\n get type () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.type\n }\n\n get name () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].name\n }\n\n get lastModified () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].lastModified\n }\n\n get [Symbol.toStringTag] () {\n return 'File'\n }\n}\n\nObject.defineProperties(File.prototype, {\n [Symbol.toStringTag]: {\n value: 'File',\n configurable: true\n },\n name: kEnumerableProperty,\n lastModified: kEnumerableProperty\n})\n\nwebidl.converters.Blob = webidl.interfaceConverter(Blob)\n\nwebidl.converters.BlobPart = function (V, opts) {\n if (webidl.util.Type(V) === 'Object') {\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (\n ArrayBuffer.isView(V) ||\n types.isAnyArrayBuffer(V)\n ) {\n return webidl.converters.BufferSource(V, opts)\n }\n }\n\n return webidl.converters.USVString(V, opts)\n}\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.BlobPart\n)\n\n// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag\nwebidl.converters.FilePropertyBag = webidl.dictionaryConverter([\n {\n key: 'lastModified',\n converter: webidl.converters['long long'],\n get defaultValue () {\n return Date.now()\n }\n },\n {\n key: 'type',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'endings',\n converter: (value) => {\n value = webidl.converters.DOMString(value)\n value = value.toLowerCase()\n\n if (value !== 'native') {\n value = 'transparent'\n }\n\n return value\n },\n defaultValue: 'transparent'\n }\n])\n\n/**\n * @see https://www.w3.org/TR/FileAPI/#process-blob-parts\n * @param {(NodeJS.TypedArray|Blob|string)[]} parts\n * @param {{ type: string, endings: string }} options\n */\nfunction processBlobParts (parts, options) {\n // 1. Let bytes be an empty sequence of bytes.\n /** @type {NodeJS.TypedArray[]} */\n const bytes = []\n\n // 2. For each element in parts:\n for (const element of parts) {\n // 1. If element is a USVString, run the following substeps:\n if (typeof element === 'string') {\n // 1. Let s be element.\n let s = element\n\n // 2. If the endings member of options is \"native\", set s\n // to the result of converting line endings to native\n // of element.\n if (options.endings === 'native') {\n s = convertLineEndingsNative(s)\n }\n\n // 3. Append the result of UTF-8 encoding s to bytes.\n bytes.push(encoder.encode(s))\n } else if (\n types.isAnyArrayBuffer(element) ||\n types.isTypedArray(element)\n ) {\n // 2. If element is a BufferSource, get a copy of the\n // bytes held by the buffer source, and append those\n // bytes to bytes.\n if (!element.buffer) { // ArrayBuffer\n bytes.push(new Uint8Array(element))\n } else {\n bytes.push(\n new Uint8Array(element.buffer, element.byteOffset, element.byteLength)\n )\n }\n } else if (isBlobLike(element)) {\n // 3. If element is a Blob, append the bytes it represents\n // to bytes.\n bytes.push(element)\n }\n }\n\n // 3. Return bytes.\n return bytes\n}\n\n/**\n * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native\n * @param {string} s\n */\nfunction convertLineEndingsNative (s) {\n // 1. Let native line ending be be the code point U+000A LF.\n let nativeLineEnding = '\\n'\n\n // 2. If the underlying platform’s conventions are to\n // represent newlines as a carriage return and line feed\n // sequence, set native line ending to the code point\n // U+000D CR followed by the code point U+000A LF.\n if (process.platform === 'win32') {\n nativeLineEnding = '\\r\\n'\n }\n\n return s.replace(/\\r?\\n/g, nativeLineEnding)\n}\n\n// If this function is moved to ./util.js, some tools (such as\n// rollup) will warn about circular dependencies. See:\n// https://github.com/nodejs/undici/issues/1629\nfunction isFileLike (object) {\n return (\n (NativeFile && object instanceof NativeFile) ||\n object instanceof File || (\n object &&\n (typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function') &&\n object[Symbol.toStringTag] === 'File'\n )\n )\n}\n\nmodule.exports = { File, FileLike, isFileLike }\n","'use strict'\n\nconst { isBlobLike, toUSVString, makeIterator } = require('./util')\nconst { kState } = require('./symbols')\nconst { File: UndiciFile, FileLike, isFileLike } = require('./file')\nconst { webidl } = require('./webidl')\nconst { Blob, File: NativeFile } = require('buffer')\n\n/** @type {globalThis['File']} */\nconst File = NativeFile ?? UndiciFile\n\n// https://xhr.spec.whatwg.org/#formdata\nclass FormData {\n constructor (form) {\n if (form !== undefined) {\n throw webidl.errors.conversionFailed({\n prefix: 'FormData constructor',\n argument: 'Argument 1',\n types: ['undefined']\n })\n }\n\n this[kState] = []\n }\n\n append (name, value, filename = undefined) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })\n\n if (arguments.length === 3 && !isBlobLike(value)) {\n throw new TypeError(\n \"Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'\"\n )\n }\n\n // 1. Let value be value if given; otherwise blobValue.\n\n name = webidl.converters.USVString(name)\n value = isBlobLike(value)\n ? webidl.converters.Blob(value, { strict: false })\n : webidl.converters.USVString(value)\n filename = arguments.length === 3\n ? webidl.converters.USVString(filename)\n : undefined\n\n // 2. Let entry be the result of creating an entry with\n // name, value, and filename if given.\n const entry = makeEntry(name, value, filename)\n\n // 3. Append entry to this’s entry list.\n this[kState].push(entry)\n }\n\n delete (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })\n\n name = webidl.converters.USVString(name)\n\n // The delete(name) method steps are to remove all entries whose name\n // is name from this’s entry list.\n this[kState] = this[kState].filter(entry => entry.name !== name)\n }\n\n get (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })\n\n name = webidl.converters.USVString(name)\n\n // 1. If there is no entry whose name is name in this’s entry list,\n // then return null.\n const idx = this[kState].findIndex((entry) => entry.name === name)\n if (idx === -1) {\n return null\n }\n\n // 2. Return the value of the first entry whose name is name from\n // this’s entry list.\n return this[kState][idx].value\n }\n\n getAll (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })\n\n name = webidl.converters.USVString(name)\n\n // 1. If there is no entry whose name is name in this’s entry list,\n // then return the empty list.\n // 2. Return the values of all entries whose name is name, in order,\n // from this’s entry list.\n return this[kState]\n .filter((entry) => entry.name === name)\n .map((entry) => entry.value)\n }\n\n has (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })\n\n name = webidl.converters.USVString(name)\n\n // The has(name) method steps are to return true if there is an entry\n // whose name is name in this’s entry list; otherwise false.\n return this[kState].findIndex((entry) => entry.name === name) !== -1\n }\n\n set (name, value, filename = undefined) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })\n\n if (arguments.length === 3 && !isBlobLike(value)) {\n throw new TypeError(\n \"Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'\"\n )\n }\n\n // The set(name, value) and set(name, blobValue, filename) method steps\n // are:\n\n // 1. Let value be value if given; otherwise blobValue.\n\n name = webidl.converters.USVString(name)\n value = isBlobLike(value)\n ? webidl.converters.Blob(value, { strict: false })\n : webidl.converters.USVString(value)\n filename = arguments.length === 3\n ? toUSVString(filename)\n : undefined\n\n // 2. Let entry be the result of creating an entry with name, value, and\n // filename if given.\n const entry = makeEntry(name, value, filename)\n\n // 3. If there are entries in this’s entry list whose name is name, then\n // replace the first such entry with entry and remove the others.\n const idx = this[kState].findIndex((entry) => entry.name === name)\n if (idx !== -1) {\n this[kState] = [\n ...this[kState].slice(0, idx),\n entry,\n ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)\n ]\n } else {\n // 4. Otherwise, append entry to this’s entry list.\n this[kState].push(entry)\n }\n }\n\n entries () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'key+value'\n )\n }\n\n keys () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'key'\n )\n }\n\n values () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'value'\n )\n }\n\n /**\n * @param {(value: string, key: string, self: FormData) => void} callbackFn\n * @param {unknown} thisArg\n */\n forEach (callbackFn, thisArg = globalThis) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })\n\n if (typeof callbackFn !== 'function') {\n throw new TypeError(\n \"Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'.\"\n )\n }\n\n for (const [key, value] of this) {\n callbackFn.apply(thisArg, [value, key, this])\n }\n }\n}\n\nFormData.prototype[Symbol.iterator] = FormData.prototype.entries\n\nObject.defineProperties(FormData.prototype, {\n [Symbol.toStringTag]: {\n value: 'FormData',\n configurable: true\n }\n})\n\n/**\n * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry\n * @param {string} name\n * @param {string|Blob} value\n * @param {?string} filename\n * @returns\n */\nfunction makeEntry (name, value, filename) {\n // 1. Set name to the result of converting name into a scalar value string.\n // \"To convert a string into a scalar value string, replace any surrogates\n // with U+FFFD.\"\n // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end\n name = Buffer.from(name).toString('utf8')\n\n // 2. If value is a string, then set value to the result of converting\n // value into a scalar value string.\n if (typeof value === 'string') {\n value = Buffer.from(value).toString('utf8')\n } else {\n // 3. Otherwise:\n\n // 1. If value is not a File object, then set value to a new File object,\n // representing the same bytes, whose name attribute value is \"blob\"\n if (!isFileLike(value)) {\n value = value instanceof Blob\n ? new File([value], 'blob', { type: value.type })\n : new FileLike(value, 'blob', { type: value.type })\n }\n\n // 2. If filename is given, then set value to a new File object,\n // representing the same bytes, whose name attribute is filename.\n if (filename !== undefined) {\n /** @type {FilePropertyBag} */\n const options = {\n type: value.type,\n lastModified: value.lastModified\n }\n\n value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile\n ? new File([value], filename, options)\n : new FileLike(value, filename, options)\n }\n }\n\n // 4. Return an entry whose name is name and whose value is value.\n return { name, value }\n}\n\nmodule.exports = { FormData }\n","'use strict'\n\n// In case of breaking changes, increase the version\n// number to avoid conflicts.\nconst globalOrigin = Symbol.for('undici.globalOrigin.1')\n\nfunction getGlobalOrigin () {\n return globalThis[globalOrigin]\n}\n\nfunction setGlobalOrigin (newOrigin) {\n if (newOrigin === undefined) {\n Object.defineProperty(globalThis, globalOrigin, {\n value: undefined,\n writable: true,\n enumerable: false,\n configurable: false\n })\n\n return\n }\n\n const parsedURL = new URL(newOrigin)\n\n if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {\n throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)\n }\n\n Object.defineProperty(globalThis, globalOrigin, {\n value: parsedURL,\n writable: true,\n enumerable: false,\n configurable: false\n })\n}\n\nmodule.exports = {\n getGlobalOrigin,\n setGlobalOrigin\n}\n","// https://github.com/Ethan-Arrowood/undici-fetch\n\n'use strict'\n\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst { kGuard } = require('./symbols')\nconst { kEnumerableProperty } = require('../core/util')\nconst {\n makeIterator,\n isValidHeaderName,\n isValidHeaderValue\n} = require('./util')\nconst { webidl } = require('./webidl')\nconst assert = require('assert')\n\nconst kHeadersMap = Symbol('headers map')\nconst kHeadersSortedMap = Symbol('headers map sorted')\n\n/**\n * @param {number} code\n */\nfunction isHTTPWhiteSpaceCharCode (code) {\n return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize\n * @param {string} potentialValue\n */\nfunction headerValueNormalize (potentialValue) {\n // To normalize a byte sequence potentialValue, remove\n // any leading and trailing HTTP whitespace bytes from\n // potentialValue.\n let i = 0; let j = potentialValue.length\n\n while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j\n while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i\n\n return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)\n}\n\nfunction fill (headers, object) {\n // To fill a Headers object headers with a given object object, run these steps:\n\n // 1. If object is a sequence, then for each header in object:\n // Note: webidl conversion to array has already been done.\n if (Array.isArray(object)) {\n for (let i = 0; i < object.length; ++i) {\n const header = object[i]\n // 1. If header does not contain exactly two items, then throw a TypeError.\n if (header.length !== 2) {\n throw webidl.errors.exception({\n header: 'Headers constructor',\n message: `expected name/value pair to be length 2, found ${header.length}.`\n })\n }\n\n // 2. Append (header’s first item, header’s second item) to headers.\n appendHeader(headers, header[0], header[1])\n }\n } else if (typeof object === 'object' && object !== null) {\n // Note: null should throw\n\n // 2. Otherwise, object is a record, then for each key → value in object,\n // append (key, value) to headers\n const keys = Object.keys(object)\n for (let i = 0; i < keys.length; ++i) {\n appendHeader(headers, keys[i], object[keys[i]])\n }\n } else {\n throw webidl.errors.conversionFailed({\n prefix: 'Headers constructor',\n argument: 'Argument 1',\n types: ['sequence>', 'record']\n })\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-headers-append\n */\nfunction appendHeader (headers, name, value) {\n // 1. Normalize value.\n value = headerValueNormalize(value)\n\n // 2. If name is not a header name or value is not a\n // header value, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.append',\n value: name,\n type: 'header name'\n })\n } else if (!isValidHeaderValue(value)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.append',\n value,\n type: 'header value'\n })\n }\n\n // 3. If headers’s guard is \"immutable\", then throw a TypeError.\n // 4. Otherwise, if headers’s guard is \"request\" and name is a\n // forbidden header name, return.\n // Note: undici does not implement forbidden header names\n if (headers[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (headers[kGuard] === 'request-no-cors') {\n // 5. Otherwise, if headers’s guard is \"request-no-cors\":\n // TODO\n }\n\n // 6. Otherwise, if headers’s guard is \"response\" and name is a\n // forbidden response-header name, return.\n\n // 7. Append (name, value) to headers’s header list.\n return headers[kHeadersList].append(name, value)\n\n // 8. If headers’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from headers\n}\n\nclass HeadersList {\n /** @type {[string, string][]|null} */\n cookies = null\n\n constructor (init) {\n if (init instanceof HeadersList) {\n this[kHeadersMap] = new Map(init[kHeadersMap])\n this[kHeadersSortedMap] = init[kHeadersSortedMap]\n this.cookies = init.cookies === null ? null : [...init.cookies]\n } else {\n this[kHeadersMap] = new Map(init)\n this[kHeadersSortedMap] = null\n }\n }\n\n // https://fetch.spec.whatwg.org/#header-list-contains\n contains (name) {\n // A header list list contains a header name name if list\n // contains a header whose name is a byte-case-insensitive\n // match for name.\n name = name.toLowerCase()\n\n return this[kHeadersMap].has(name)\n }\n\n clear () {\n this[kHeadersMap].clear()\n this[kHeadersSortedMap] = null\n this.cookies = null\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-append\n append (name, value) {\n this[kHeadersSortedMap] = null\n\n // 1. If list contains name, then set name to the first such\n // header’s name.\n const lowercaseName = name.toLowerCase()\n const exists = this[kHeadersMap].get(lowercaseName)\n\n // 2. Append (name, value) to list.\n if (exists) {\n const delimiter = lowercaseName === 'cookie' ? '; ' : ', '\n this[kHeadersMap].set(lowercaseName, {\n name: exists.name,\n value: `${exists.value}${delimiter}${value}`\n })\n } else {\n this[kHeadersMap].set(lowercaseName, { name, value })\n }\n\n if (lowercaseName === 'set-cookie') {\n this.cookies ??= []\n this.cookies.push(value)\n }\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-set\n set (name, value) {\n this[kHeadersSortedMap] = null\n const lowercaseName = name.toLowerCase()\n\n if (lowercaseName === 'set-cookie') {\n this.cookies = [value]\n }\n\n // 1. If list contains name, then set the value of\n // the first such header to value and remove the\n // others.\n // 2. Otherwise, append header (name, value) to list.\n this[kHeadersMap].set(lowercaseName, { name, value })\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-delete\n delete (name) {\n this[kHeadersSortedMap] = null\n\n name = name.toLowerCase()\n\n if (name === 'set-cookie') {\n this.cookies = null\n }\n\n this[kHeadersMap].delete(name)\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-get\n get (name) {\n const value = this[kHeadersMap].get(name.toLowerCase())\n\n // 1. If list does not contain name, then return null.\n // 2. Return the values of all headers in list whose name\n // is a byte-case-insensitive match for name,\n // separated from each other by 0x2C 0x20, in order.\n return value === undefined ? null : value.value\n }\n\n * [Symbol.iterator] () {\n // use the lowercased name\n for (const [name, { value }] of this[kHeadersMap]) {\n yield [name, value]\n }\n }\n\n get entries () {\n const headers = {}\n\n if (this[kHeadersMap].size) {\n for (const { name, value } of this[kHeadersMap].values()) {\n headers[name] = value\n }\n }\n\n return headers\n }\n}\n\n// https://fetch.spec.whatwg.org/#headers-class\nclass Headers {\n constructor (init = undefined) {\n if (init === kConstruct) {\n return\n }\n this[kHeadersList] = new HeadersList()\n\n // The new Headers(init) constructor steps are:\n\n // 1. Set this’s guard to \"none\".\n this[kGuard] = 'none'\n\n // 2. If init is given, then fill this with init.\n if (init !== undefined) {\n init = webidl.converters.HeadersInit(init)\n fill(this, init)\n }\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-append\n append (name, value) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })\n\n name = webidl.converters.ByteString(name)\n value = webidl.converters.ByteString(value)\n\n return appendHeader(this, name, value)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-delete\n delete (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.delete',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. If this’s guard is \"immutable\", then throw a TypeError.\n // 3. Otherwise, if this’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 4. Otherwise, if this’s guard is \"request-no-cors\", name\n // is not a no-CORS-safelisted request-header name, and\n // name is not a privileged no-CORS request-header name,\n // return.\n // 5. Otherwise, if this’s guard is \"response\" and name is\n // a forbidden response-header name, return.\n // Note: undici does not implement forbidden header names\n if (this[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (this[kGuard] === 'request-no-cors') {\n // TODO\n }\n\n // 6. If this’s header list does not contain name, then\n // return.\n if (!this[kHeadersList].contains(name)) {\n return\n }\n\n // 7. Delete name from this’s header list.\n // 8. If this’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from this.\n this[kHeadersList].delete(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-get\n get (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.get',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. Return the result of getting name from this’s header\n // list.\n return this[kHeadersList].get(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-has\n has (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.has',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. Return true if this’s header list contains name;\n // otherwise false.\n return this[kHeadersList].contains(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-set\n set (name, value) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })\n\n name = webidl.converters.ByteString(name)\n value = webidl.converters.ByteString(value)\n\n // 1. Normalize value.\n value = headerValueNormalize(value)\n\n // 2. If name is not a header name or value is not a\n // header value, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.set',\n value: name,\n type: 'header name'\n })\n } else if (!isValidHeaderValue(value)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.set',\n value,\n type: 'header value'\n })\n }\n\n // 3. If this’s guard is \"immutable\", then throw a TypeError.\n // 4. Otherwise, if this’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 5. Otherwise, if this’s guard is \"request-no-cors\" and\n // name/value is not a no-CORS-safelisted request-header,\n // return.\n // 6. Otherwise, if this’s guard is \"response\" and name is a\n // forbidden response-header name, return.\n // Note: undici does not implement forbidden header names\n if (this[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (this[kGuard] === 'request-no-cors') {\n // TODO\n }\n\n // 7. Set (name, value) in this’s header list.\n // 8. If this’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from this\n this[kHeadersList].set(name, value)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie\n getSetCookie () {\n webidl.brandCheck(this, Headers)\n\n // 1. If this’s header list does not contain `Set-Cookie`, then return « ».\n // 2. Return the values of all headers in this’s header list whose name is\n // a byte-case-insensitive match for `Set-Cookie`, in order.\n\n const list = this[kHeadersList].cookies\n\n if (list) {\n return [...list]\n }\n\n return []\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n get [kHeadersSortedMap] () {\n if (this[kHeadersList][kHeadersSortedMap]) {\n return this[kHeadersList][kHeadersSortedMap]\n }\n\n // 1. Let headers be an empty list of headers with the key being the name\n // and value the value.\n const headers = []\n\n // 2. Let names be the result of convert header names to a sorted-lowercase\n // set with all the names of the headers in list.\n const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)\n const cookies = this[kHeadersList].cookies\n\n // 3. For each name of names:\n for (let i = 0; i < names.length; ++i) {\n const [name, value] = names[i]\n // 1. If name is `set-cookie`, then:\n if (name === 'set-cookie') {\n // 1. Let values be a list of all values of headers in list whose name\n // is a byte-case-insensitive match for name, in order.\n\n // 2. For each value of values:\n // 1. Append (name, value) to headers.\n for (let j = 0; j < cookies.length; ++j) {\n headers.push([name, cookies[j]])\n }\n } else {\n // 2. Otherwise:\n\n // 1. Let value be the result of getting name from list.\n\n // 2. Assert: value is non-null.\n assert(value !== null)\n\n // 3. Append (name, value) to headers.\n headers.push([name, value])\n }\n }\n\n this[kHeadersList][kHeadersSortedMap] = headers\n\n // 4. Return headers.\n return headers\n }\n\n keys () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'key')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'key'\n )\n }\n\n values () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'value')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'value'\n )\n }\n\n entries () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'key+value')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'key+value'\n )\n }\n\n /**\n * @param {(value: string, key: string, self: Headers) => void} callbackFn\n * @param {unknown} thisArg\n */\n forEach (callbackFn, thisArg = globalThis) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })\n\n if (typeof callbackFn !== 'function') {\n throw new TypeError(\n \"Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'.\"\n )\n }\n\n for (const [key, value] of this) {\n callbackFn.apply(thisArg, [value, key, this])\n }\n }\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n webidl.brandCheck(this, Headers)\n\n return this[kHeadersList]\n }\n}\n\nHeaders.prototype[Symbol.iterator] = Headers.prototype.entries\n\nObject.defineProperties(Headers.prototype, {\n append: kEnumerableProperty,\n delete: kEnumerableProperty,\n get: kEnumerableProperty,\n has: kEnumerableProperty,\n set: kEnumerableProperty,\n getSetCookie: kEnumerableProperty,\n keys: kEnumerableProperty,\n values: kEnumerableProperty,\n entries: kEnumerableProperty,\n forEach: kEnumerableProperty,\n [Symbol.iterator]: { enumerable: false },\n [Symbol.toStringTag]: {\n value: 'Headers',\n configurable: true\n }\n})\n\nwebidl.converters.HeadersInit = function (V) {\n if (webidl.util.Type(V) === 'Object') {\n if (V[Symbol.iterator]) {\n return webidl.converters['sequence>'](V)\n }\n\n return webidl.converters['record'](V)\n }\n\n throw webidl.errors.conversionFailed({\n prefix: 'Headers constructor',\n argument: 'Argument 1',\n types: ['sequence>', 'record']\n })\n}\n\nmodule.exports = {\n fill,\n Headers,\n HeadersList\n}\n","// https://github.com/Ethan-Arrowood/undici-fetch\n\n'use strict'\n\nconst {\n Response,\n makeNetworkError,\n makeAppropriateNetworkError,\n filterResponse,\n makeResponse\n} = require('./response')\nconst { Headers } = require('./headers')\nconst { Request, makeRequest } = require('./request')\nconst zlib = require('zlib')\nconst {\n bytesMatch,\n makePolicyContainer,\n clonePolicyContainer,\n requestBadPort,\n TAOCheck,\n appendRequestOriginHeader,\n responseLocationURL,\n requestCurrentURL,\n setRequestReferrerPolicyOnRedirect,\n tryUpgradeRequestToAPotentiallyTrustworthyURL,\n createOpaqueTimingInfo,\n appendFetchMetadata,\n corsCheck,\n crossOriginResourcePolicyCheck,\n determineRequestsReferrer,\n coarsenedSharedCurrentTime,\n createDeferredPromise,\n isBlobLike,\n sameOrigin,\n isCancelled,\n isAborted,\n isErrorLike,\n fullyReadBody,\n readableStreamClose,\n isomorphicEncode,\n urlIsLocal,\n urlIsHttpHttpsScheme,\n urlHasHttpsScheme\n} = require('./util')\nconst { kState, kHeaders, kGuard, kRealm } = require('./symbols')\nconst assert = require('assert')\nconst { safelyExtractBody } = require('./body')\nconst {\n redirectStatusSet,\n nullBodyStatus,\n safeMethodsSet,\n requestBodyHeader,\n subresourceSet,\n DOMException\n} = require('./constants')\nconst { kHeadersList } = require('../core/symbols')\nconst EE = require('events')\nconst { Readable, pipeline } = require('stream')\nconst { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = require('../core/util')\nconst { dataURLProcessor, serializeAMimeType } = require('./dataURL')\nconst { TransformStream } = require('stream/web')\nconst { getGlobalDispatcher } = require('../global')\nconst { webidl } = require('./webidl')\nconst { STATUS_CODES } = require('http')\nconst GET_OR_HEAD = ['GET', 'HEAD']\n\n/** @type {import('buffer').resolveObjectURL} */\nlet resolveObjectURL\nlet ReadableStream = globalThis.ReadableStream\n\nclass Fetch extends EE {\n constructor (dispatcher) {\n super()\n\n this.dispatcher = dispatcher\n this.connection = null\n this.dump = false\n this.state = 'ongoing'\n // 2 terminated listeners get added per request,\n // but only 1 gets removed. If there are 20 redirects,\n // 21 listeners will be added.\n // See https://github.com/nodejs/undici/issues/1711\n // TODO (fix): Find and fix root cause for leaked listener.\n this.setMaxListeners(21)\n }\n\n terminate (reason) {\n if (this.state !== 'ongoing') {\n return\n }\n\n this.state = 'terminated'\n this.connection?.destroy(reason)\n this.emit('terminated', reason)\n }\n\n // https://fetch.spec.whatwg.org/#fetch-controller-abort\n abort (error) {\n if (this.state !== 'ongoing') {\n return\n }\n\n // 1. Set controller’s state to \"aborted\".\n this.state = 'aborted'\n\n // 2. Let fallbackError be an \"AbortError\" DOMException.\n // 3. Set error to fallbackError if it is not given.\n if (!error) {\n error = new DOMException('The operation was aborted.', 'AbortError')\n }\n\n // 4. Let serializedError be StructuredSerialize(error).\n // If that threw an exception, catch it, and let\n // serializedError be StructuredSerialize(fallbackError).\n\n // 5. Set controller’s serialized abort reason to serializedError.\n this.serializedAbortReason = error\n\n this.connection?.destroy(error)\n this.emit('terminated', error)\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetch-method\nfunction fetch (input, init = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })\n\n // 1. Let p be a new promise.\n const p = createDeferredPromise()\n\n // 2. Let requestObject be the result of invoking the initial value of\n // Request as constructor with input and init as arguments. If this throws\n // an exception, reject p with it and return p.\n let requestObject\n\n try {\n requestObject = new Request(input, init)\n } catch (e) {\n p.reject(e)\n return p.promise\n }\n\n // 3. Let request be requestObject’s request.\n const request = requestObject[kState]\n\n // 4. If requestObject’s signal’s aborted flag is set, then:\n if (requestObject.signal.aborted) {\n // 1. Abort the fetch() call with p, request, null, and\n // requestObject’s signal’s abort reason.\n abortFetch(p, request, null, requestObject.signal.reason)\n\n // 2. Return p.\n return p.promise\n }\n\n // 5. Let globalObject be request’s client’s global object.\n const globalObject = request.client.globalObject\n\n // 6. If globalObject is a ServiceWorkerGlobalScope object, then set\n // request’s service-workers mode to \"none\".\n if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {\n request.serviceWorkers = 'none'\n }\n\n // 7. Let responseObject be null.\n let responseObject = null\n\n // 8. Let relevantRealm be this’s relevant Realm.\n const relevantRealm = null\n\n // 9. Let locallyAborted be false.\n let locallyAborted = false\n\n // 10. Let controller be null.\n let controller = null\n\n // 11. Add the following abort steps to requestObject’s signal:\n addAbortListener(\n requestObject.signal,\n () => {\n // 1. Set locallyAborted to true.\n locallyAborted = true\n\n // 2. Assert: controller is non-null.\n assert(controller != null)\n\n // 3. Abort controller with requestObject’s signal’s abort reason.\n controller.abort(requestObject.signal.reason)\n\n // 4. Abort the fetch() call with p, request, responseObject,\n // and requestObject’s signal’s abort reason.\n abortFetch(p, request, responseObject, requestObject.signal.reason)\n }\n )\n\n // 12. Let handleFetchDone given response response be to finalize and\n // report timing with response, globalObject, and \"fetch\".\n const handleFetchDone = (response) =>\n finalizeAndReportTiming(response, 'fetch')\n\n // 13. Set controller to the result of calling fetch given request,\n // with processResponseEndOfBody set to handleFetchDone, and processResponse\n // given response being these substeps:\n\n const processResponse = (response) => {\n // 1. If locallyAborted is true, terminate these substeps.\n if (locallyAborted) {\n return Promise.resolve()\n }\n\n // 2. If response’s aborted flag is set, then:\n if (response.aborted) {\n // 1. Let deserializedError be the result of deserialize a serialized\n // abort reason given controller’s serialized abort reason and\n // relevantRealm.\n\n // 2. Abort the fetch() call with p, request, responseObject, and\n // deserializedError.\n\n abortFetch(p, request, responseObject, controller.serializedAbortReason)\n return Promise.resolve()\n }\n\n // 3. If response is a network error, then reject p with a TypeError\n // and terminate these substeps.\n if (response.type === 'error') {\n p.reject(\n Object.assign(new TypeError('fetch failed'), { cause: response.error })\n )\n return Promise.resolve()\n }\n\n // 4. Set responseObject to the result of creating a Response object,\n // given response, \"immutable\", and relevantRealm.\n responseObject = new Response()\n responseObject[kState] = response\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kHeadersList] = response.headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 5. Resolve p with responseObject.\n p.resolve(responseObject)\n }\n\n controller = fetching({\n request,\n processResponseEndOfBody: handleFetchDone,\n processResponse,\n dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici\n })\n\n // 14. Return p.\n return p.promise\n}\n\n// https://fetch.spec.whatwg.org/#finalize-and-report-timing\nfunction finalizeAndReportTiming (response, initiatorType = 'other') {\n // 1. If response is an aborted network error, then return.\n if (response.type === 'error' && response.aborted) {\n return\n }\n\n // 2. If response’s URL list is null or empty, then return.\n if (!response.urlList?.length) {\n return\n }\n\n // 3. Let originalURL be response’s URL list[0].\n const originalURL = response.urlList[0]\n\n // 4. Let timingInfo be response’s timing info.\n let timingInfo = response.timingInfo\n\n // 5. Let cacheState be response’s cache state.\n let cacheState = response.cacheState\n\n // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.\n if (!urlIsHttpHttpsScheme(originalURL)) {\n return\n }\n\n // 7. If timingInfo is null, then return.\n if (timingInfo === null) {\n return\n }\n\n // 8. If response’s timing allow passed flag is not set, then:\n if (!response.timingAllowPassed) {\n // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.\n timingInfo = createOpaqueTimingInfo({\n startTime: timingInfo.startTime\n })\n\n // 2. Set cacheState to the empty string.\n cacheState = ''\n }\n\n // 9. Set timingInfo’s end time to the coarsened shared current time\n // given global’s relevant settings object’s cross-origin isolated\n // capability.\n // TODO: given global’s relevant settings object’s cross-origin isolated\n // capability?\n timingInfo.endTime = coarsenedSharedCurrentTime()\n\n // 10. Set response’s timing info to timingInfo.\n response.timingInfo = timingInfo\n\n // 11. Mark resource timing for timingInfo, originalURL, initiatorType,\n // global, and cacheState.\n markResourceTiming(\n timingInfo,\n originalURL,\n initiatorType,\n globalThis,\n cacheState\n )\n}\n\n// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing\nfunction markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {\n if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {\n performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)\n }\n}\n\n// https://fetch.spec.whatwg.org/#abort-fetch\nfunction abortFetch (p, request, responseObject, error) {\n // Note: AbortSignal.reason was added in node v17.2.0\n // which would give us an undefined error to reject with.\n // Remove this once node v16 is no longer supported.\n if (!error) {\n error = new DOMException('The operation was aborted.', 'AbortError')\n }\n\n // 1. Reject promise with error.\n p.reject(error)\n\n // 2. If request’s body is not null and is readable, then cancel request’s\n // body with error.\n if (request.body != null && isReadable(request.body?.stream)) {\n request.body.stream.cancel(error).catch((err) => {\n if (err.code === 'ERR_INVALID_STATE') {\n // Node bug?\n return\n }\n throw err\n })\n }\n\n // 3. If responseObject is null, then return.\n if (responseObject == null) {\n return\n }\n\n // 4. Let response be responseObject’s response.\n const response = responseObject[kState]\n\n // 5. If response’s body is not null and is readable, then error response’s\n // body with error.\n if (response.body != null && isReadable(response.body?.stream)) {\n response.body.stream.cancel(error).catch((err) => {\n if (err.code === 'ERR_INVALID_STATE') {\n // Node bug?\n return\n }\n throw err\n })\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetching\nfunction fetching ({\n request,\n processRequestBodyChunkLength,\n processRequestEndOfBody,\n processResponse,\n processResponseEndOfBody,\n processResponseConsumeBody,\n useParallelQueue = false,\n dispatcher // undici\n}) {\n // 1. Let taskDestination be null.\n let taskDestination = null\n\n // 2. Let crossOriginIsolatedCapability be false.\n let crossOriginIsolatedCapability = false\n\n // 3. If request’s client is non-null, then:\n if (request.client != null) {\n // 1. Set taskDestination to request’s client’s global object.\n taskDestination = request.client.globalObject\n\n // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin\n // isolated capability.\n crossOriginIsolatedCapability =\n request.client.crossOriginIsolatedCapability\n }\n\n // 4. If useParallelQueue is true, then set taskDestination to the result of\n // starting a new parallel queue.\n // TODO\n\n // 5. Let timingInfo be a new fetch timing info whose start time and\n // post-redirect start time are the coarsened shared current time given\n // crossOriginIsolatedCapability.\n const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)\n const timingInfo = createOpaqueTimingInfo({\n startTime: currenTime\n })\n\n // 6. Let fetchParams be a new fetch params whose\n // request is request,\n // timing info is timingInfo,\n // process request body chunk length is processRequestBodyChunkLength,\n // process request end-of-body is processRequestEndOfBody,\n // process response is processResponse,\n // process response consume body is processResponseConsumeBody,\n // process response end-of-body is processResponseEndOfBody,\n // task destination is taskDestination,\n // and cross-origin isolated capability is crossOriginIsolatedCapability.\n const fetchParams = {\n controller: new Fetch(dispatcher),\n request,\n timingInfo,\n processRequestBodyChunkLength,\n processRequestEndOfBody,\n processResponse,\n processResponseConsumeBody,\n processResponseEndOfBody,\n taskDestination,\n crossOriginIsolatedCapability\n }\n\n // 7. If request’s body is a byte sequence, then set request’s body to\n // request’s body as a body.\n // NOTE: Since fetching is only called from fetch, body should already be\n // extracted.\n assert(!request.body || request.body.stream)\n\n // 8. If request’s window is \"client\", then set request’s window to request’s\n // client, if request’s client’s global object is a Window object; otherwise\n // \"no-window\".\n if (request.window === 'client') {\n // TODO: What if request.client is null?\n request.window =\n request.client?.globalObject?.constructor?.name === 'Window'\n ? request.client\n : 'no-window'\n }\n\n // 9. If request’s origin is \"client\", then set request’s origin to request’s\n // client’s origin.\n if (request.origin === 'client') {\n // TODO: What if request.client is null?\n request.origin = request.client?.origin\n }\n\n // 10. If all of the following conditions are true:\n // TODO\n\n // 11. If request’s policy container is \"client\", then:\n if (request.policyContainer === 'client') {\n // 1. If request’s client is non-null, then set request’s policy\n // container to a clone of request’s client’s policy container. [HTML]\n if (request.client != null) {\n request.policyContainer = clonePolicyContainer(\n request.client.policyContainer\n )\n } else {\n // 2. Otherwise, set request’s policy container to a new policy\n // container.\n request.policyContainer = makePolicyContainer()\n }\n }\n\n // 12. If request’s header list does not contain `Accept`, then:\n if (!request.headersList.contains('accept')) {\n // 1. Let value be `*/*`.\n const value = '*/*'\n\n // 2. A user agent should set value to the first matching statement, if\n // any, switching on request’s destination:\n // \"document\"\n // \"frame\"\n // \"iframe\"\n // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`\n // \"image\"\n // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`\n // \"style\"\n // `text/css,*/*;q=0.1`\n // TODO\n\n // 3. Append `Accept`/value to request’s header list.\n request.headersList.append('accept', value)\n }\n\n // 13. If request’s header list does not contain `Accept-Language`, then\n // user agents should append `Accept-Language`/an appropriate value to\n // request’s header list.\n if (!request.headersList.contains('accept-language')) {\n request.headersList.append('accept-language', '*')\n }\n\n // 14. If request’s priority is null, then use request’s initiator and\n // destination appropriately in setting request’s priority to a\n // user-agent-defined object.\n if (request.priority === null) {\n // TODO\n }\n\n // 15. If request is a subresource request, then:\n if (subresourceSet.has(request.destination)) {\n // TODO\n }\n\n // 16. Run main fetch given fetchParams.\n mainFetch(fetchParams)\n .catch(err => {\n fetchParams.controller.terminate(err)\n })\n\n // 17. Return fetchParam's controller\n return fetchParams.controller\n}\n\n// https://fetch.spec.whatwg.org/#concept-main-fetch\nasync function mainFetch (fetchParams, recursive = false) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. If request’s local-URLs-only flag is set and request’s current URL is\n // not local, then set response to a network error.\n if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {\n response = makeNetworkError('local URLs only')\n }\n\n // 4. Run report Content Security Policy violations for request.\n // TODO\n\n // 5. Upgrade request to a potentially trustworthy URL, if appropriate.\n tryUpgradeRequestToAPotentiallyTrustworthyURL(request)\n\n // 6. If should request be blocked due to a bad port, should fetching request\n // be blocked as mixed content, or should request be blocked by Content\n // Security Policy returns blocked, then set response to a network error.\n if (requestBadPort(request) === 'blocked') {\n response = makeNetworkError('bad port')\n }\n // TODO: should fetching request be blocked as mixed content?\n // TODO: should request be blocked by Content Security Policy?\n\n // 7. If request’s referrer policy is the empty string, then set request’s\n // referrer policy to request’s policy container’s referrer policy.\n if (request.referrerPolicy === '') {\n request.referrerPolicy = request.policyContainer.referrerPolicy\n }\n\n // 8. If request’s referrer is not \"no-referrer\", then set request’s\n // referrer to the result of invoking determine request’s referrer.\n if (request.referrer !== 'no-referrer') {\n request.referrer = determineRequestsReferrer(request)\n }\n\n // 9. Set request’s current URL’s scheme to \"https\" if all of the following\n // conditions are true:\n // - request’s current URL’s scheme is \"http\"\n // - request’s current URL’s host is a domain\n // - Matching request’s current URL’s host per Known HSTS Host Domain Name\n // Matching results in either a superdomain match with an asserted\n // includeSubDomains directive or a congruent match (with or without an\n // asserted includeSubDomains directive). [HSTS]\n // TODO\n\n // 10. If recursive is false, then run the remaining steps in parallel.\n // TODO\n\n // 11. If response is null, then set response to the result of running\n // the steps corresponding to the first matching statement:\n if (response === null) {\n response = await (async () => {\n const currentURL = requestCurrentURL(request)\n\n if (\n // - request’s current URL’s origin is same origin with request’s origin,\n // and request’s response tainting is \"basic\"\n (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||\n // request’s current URL’s scheme is \"data\"\n (currentURL.protocol === 'data:') ||\n // - request’s mode is \"navigate\" or \"websocket\"\n (request.mode === 'navigate' || request.mode === 'websocket')\n ) {\n // 1. Set request’s response tainting to \"basic\".\n request.responseTainting = 'basic'\n\n // 2. Return the result of running scheme fetch given fetchParams.\n return await schemeFetch(fetchParams)\n }\n\n // request’s mode is \"same-origin\"\n if (request.mode === 'same-origin') {\n // 1. Return a network error.\n return makeNetworkError('request mode cannot be \"same-origin\"')\n }\n\n // request’s mode is \"no-cors\"\n if (request.mode === 'no-cors') {\n // 1. If request’s redirect mode is not \"follow\", then return a network\n // error.\n if (request.redirect !== 'follow') {\n return makeNetworkError(\n 'redirect mode cannot be \"follow\" for \"no-cors\" request'\n )\n }\n\n // 2. Set request’s response tainting to \"opaque\".\n request.responseTainting = 'opaque'\n\n // 3. Return the result of running scheme fetch given fetchParams.\n return await schemeFetch(fetchParams)\n }\n\n // request’s current URL’s scheme is not an HTTP(S) scheme\n if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {\n // Return a network error.\n return makeNetworkError('URL scheme must be a HTTP(S) scheme')\n }\n\n // - request’s use-CORS-preflight flag is set\n // - request’s unsafe-request flag is set and either request’s method is\n // not a CORS-safelisted method or CORS-unsafe request-header names with\n // request’s header list is not empty\n // 1. Set request’s response tainting to \"cors\".\n // 2. Let corsWithPreflightResponse be the result of running HTTP fetch\n // given fetchParams and true.\n // 3. If corsWithPreflightResponse is a network error, then clear cache\n // entries using request.\n // 4. Return corsWithPreflightResponse.\n // TODO\n\n // Otherwise\n // 1. Set request’s response tainting to \"cors\".\n request.responseTainting = 'cors'\n\n // 2. Return the result of running HTTP fetch given fetchParams.\n return await httpFetch(fetchParams)\n })()\n }\n\n // 12. If recursive is true, then return response.\n if (recursive) {\n return response\n }\n\n // 13. If response is not a network error and response is not a filtered\n // response, then:\n if (response.status !== 0 && !response.internalResponse) {\n // If request’s response tainting is \"cors\", then:\n if (request.responseTainting === 'cors') {\n // 1. Let headerNames be the result of extracting header list values\n // given `Access-Control-Expose-Headers` and response’s header list.\n // TODO\n // 2. If request’s credentials mode is not \"include\" and headerNames\n // contains `*`, then set response’s CORS-exposed header-name list to\n // all unique header names in response’s header list.\n // TODO\n // 3. Otherwise, if headerNames is not null or failure, then set\n // response’s CORS-exposed header-name list to headerNames.\n // TODO\n }\n\n // Set response to the following filtered response with response as its\n // internal response, depending on request’s response tainting:\n if (request.responseTainting === 'basic') {\n response = filterResponse(response, 'basic')\n } else if (request.responseTainting === 'cors') {\n response = filterResponse(response, 'cors')\n } else if (request.responseTainting === 'opaque') {\n response = filterResponse(response, 'opaque')\n } else {\n assert(false)\n }\n }\n\n // 14. Let internalResponse be response, if response is a network error,\n // and response’s internal response otherwise.\n let internalResponse =\n response.status === 0 ? response : response.internalResponse\n\n // 15. If internalResponse’s URL list is empty, then set it to a clone of\n // request’s URL list.\n if (internalResponse.urlList.length === 0) {\n internalResponse.urlList.push(...request.urlList)\n }\n\n // 16. If request’s timing allow failed flag is unset, then set\n // internalResponse’s timing allow passed flag.\n if (!request.timingAllowFailed) {\n response.timingAllowPassed = true\n }\n\n // 17. If response is not a network error and any of the following returns\n // blocked\n // - should internalResponse to request be blocked as mixed content\n // - should internalResponse to request be blocked by Content Security Policy\n // - should internalResponse to request be blocked due to its MIME type\n // - should internalResponse to request be blocked due to nosniff\n // TODO\n\n // 18. If response’s type is \"opaque\", internalResponse’s status is 206,\n // internalResponse’s range-requested flag is set, and request’s header\n // list does not contain `Range`, then set response and internalResponse\n // to a network error.\n if (\n response.type === 'opaque' &&\n internalResponse.status === 206 &&\n internalResponse.rangeRequested &&\n !request.headers.contains('range')\n ) {\n response = internalResponse = makeNetworkError()\n }\n\n // 19. If response is not a network error and either request’s method is\n // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,\n // set internalResponse’s body to null and disregard any enqueuing toward\n // it (if any).\n if (\n response.status !== 0 &&\n (request.method === 'HEAD' ||\n request.method === 'CONNECT' ||\n nullBodyStatus.includes(internalResponse.status))\n ) {\n internalResponse.body = null\n fetchParams.controller.dump = true\n }\n\n // 20. If request’s integrity metadata is not the empty string, then:\n if (request.integrity) {\n // 1. Let processBodyError be this step: run fetch finale given fetchParams\n // and a network error.\n const processBodyError = (reason) =>\n fetchFinale(fetchParams, makeNetworkError(reason))\n\n // 2. If request’s response tainting is \"opaque\", or response’s body is null,\n // then run processBodyError and abort these steps.\n if (request.responseTainting === 'opaque' || response.body == null) {\n processBodyError(response.error)\n return\n }\n\n // 3. Let processBody given bytes be these steps:\n const processBody = (bytes) => {\n // 1. If bytes do not match request’s integrity metadata,\n // then run processBodyError and abort these steps. [SRI]\n if (!bytesMatch(bytes, request.integrity)) {\n processBodyError('integrity mismatch')\n return\n }\n\n // 2. Set response’s body to bytes as a body.\n response.body = safelyExtractBody(bytes)[0]\n\n // 3. Run fetch finale given fetchParams and response.\n fetchFinale(fetchParams, response)\n }\n\n // 4. Fully read response’s body given processBody and processBodyError.\n await fullyReadBody(response.body, processBody, processBodyError)\n } else {\n // 21. Otherwise, run fetch finale given fetchParams and response.\n fetchFinale(fetchParams, response)\n }\n}\n\n// https://fetch.spec.whatwg.org/#concept-scheme-fetch\n// given a fetch params fetchParams\nfunction schemeFetch (fetchParams) {\n // Note: since the connection is destroyed on redirect, which sets fetchParams to a\n // cancelled state, we do not want this condition to trigger *unless* there have been\n // no redirects. See https://github.com/nodejs/undici/issues/1776\n // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {\n return Promise.resolve(makeAppropriateNetworkError(fetchParams))\n }\n\n // 2. Let request be fetchParams’s request.\n const { request } = fetchParams\n\n const { protocol: scheme } = requestCurrentURL(request)\n\n // 3. Switch on request’s current URL’s scheme and run the associated steps:\n switch (scheme) {\n case 'about:': {\n // If request’s current URL’s path is the string \"blank\", then return a new response\n // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,\n // and body is the empty byte sequence as a body.\n\n // Otherwise, return a network error.\n return Promise.resolve(makeNetworkError('about scheme is not supported'))\n }\n case 'blob:': {\n if (!resolveObjectURL) {\n resolveObjectURL = require('buffer').resolveObjectURL\n }\n\n // 1. Let blobURLEntry be request’s current URL’s blob URL entry.\n const blobURLEntry = requestCurrentURL(request)\n\n // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56\n // Buffer.resolveObjectURL does not ignore URL queries.\n if (blobURLEntry.search.length !== 0) {\n return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))\n }\n\n const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())\n\n // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s\n // object is not a Blob object, then return a network error.\n if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {\n return Promise.resolve(makeNetworkError('invalid method'))\n }\n\n // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.\n const bodyWithType = safelyExtractBody(blobURLEntryObject)\n\n // 4. Let body be bodyWithType’s body.\n const body = bodyWithType[0]\n\n // 5. Let length be body’s length, serialized and isomorphic encoded.\n const length = isomorphicEncode(`${body.length}`)\n\n // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.\n const type = bodyWithType[1] ?? ''\n\n // 7. Return a new response whose status message is `OK`, header list is\n // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.\n const response = makeResponse({\n statusText: 'OK',\n headersList: [\n ['content-length', { name: 'Content-Length', value: length }],\n ['content-type', { name: 'Content-Type', value: type }]\n ]\n })\n\n response.body = body\n\n return Promise.resolve(response)\n }\n case 'data:': {\n // 1. Let dataURLStruct be the result of running the\n // data: URL processor on request’s current URL.\n const currentURL = requestCurrentURL(request)\n const dataURLStruct = dataURLProcessor(currentURL)\n\n // 2. If dataURLStruct is failure, then return a\n // network error.\n if (dataURLStruct === 'failure') {\n return Promise.resolve(makeNetworkError('failed to fetch the data URL'))\n }\n\n // 3. Let mimeType be dataURLStruct’s MIME type, serialized.\n const mimeType = serializeAMimeType(dataURLStruct.mimeType)\n\n // 4. Return a response whose status message is `OK`,\n // header list is « (`Content-Type`, mimeType) »,\n // and body is dataURLStruct’s body as a body.\n return Promise.resolve(makeResponse({\n statusText: 'OK',\n headersList: [\n ['content-type', { name: 'Content-Type', value: mimeType }]\n ],\n body: safelyExtractBody(dataURLStruct.body)[0]\n }))\n }\n case 'file:': {\n // For now, unfortunate as it is, file URLs are left as an exercise for the reader.\n // When in doubt, return a network error.\n return Promise.resolve(makeNetworkError('not implemented... yet...'))\n }\n case 'http:':\n case 'https:': {\n // Return the result of running HTTP fetch given fetchParams.\n\n return httpFetch(fetchParams)\n .catch((err) => makeNetworkError(err))\n }\n default: {\n return Promise.resolve(makeNetworkError('unknown scheme'))\n }\n }\n}\n\n// https://fetch.spec.whatwg.org/#finalize-response\nfunction finalizeResponse (fetchParams, response) {\n // 1. Set fetchParams’s request’s done flag.\n fetchParams.request.done = true\n\n // 2, If fetchParams’s process response done is not null, then queue a fetch\n // task to run fetchParams’s process response done given response, with\n // fetchParams’s task destination.\n if (fetchParams.processResponseDone != null) {\n queueMicrotask(() => fetchParams.processResponseDone(response))\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetch-finale\nfunction fetchFinale (fetchParams, response) {\n // 1. If response is a network error, then:\n if (response.type === 'error') {\n // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».\n response.urlList = [fetchParams.request.urlList[0]]\n\n // 2. Set response’s timing info to the result of creating an opaque timing\n // info for fetchParams’s timing info.\n response.timingInfo = createOpaqueTimingInfo({\n startTime: fetchParams.timingInfo.startTime\n })\n }\n\n // 2. Let processResponseEndOfBody be the following steps:\n const processResponseEndOfBody = () => {\n // 1. Set fetchParams’s request’s done flag.\n fetchParams.request.done = true\n\n // If fetchParams’s process response end-of-body is not null,\n // then queue a fetch task to run fetchParams’s process response\n // end-of-body given response with fetchParams’s task destination.\n if (fetchParams.processResponseEndOfBody != null) {\n queueMicrotask(() => fetchParams.processResponseEndOfBody(response))\n }\n }\n\n // 3. If fetchParams’s process response is non-null, then queue a fetch task\n // to run fetchParams’s process response given response, with fetchParams’s\n // task destination.\n if (fetchParams.processResponse != null) {\n queueMicrotask(() => fetchParams.processResponse(response))\n }\n\n // 4. If response’s body is null, then run processResponseEndOfBody.\n if (response.body == null) {\n processResponseEndOfBody()\n } else {\n // 5. Otherwise:\n\n // 1. Let transformStream be a new a TransformStream.\n\n // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,\n // enqueues chunk in transformStream.\n const identityTransformAlgorithm = (chunk, controller) => {\n controller.enqueue(chunk)\n }\n\n // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm\n // and flushAlgorithm set to processResponseEndOfBody.\n const transformStream = new TransformStream({\n start () {},\n transform: identityTransformAlgorithm,\n flush: processResponseEndOfBody\n }, {\n size () {\n return 1\n }\n }, {\n size () {\n return 1\n }\n })\n\n // 4. Set response’s body to the result of piping response’s body through transformStream.\n response.body = { stream: response.body.stream.pipeThrough(transformStream) }\n }\n\n // 6. If fetchParams’s process response consume body is non-null, then:\n if (fetchParams.processResponseConsumeBody != null) {\n // 1. Let processBody given nullOrBytes be this step: run fetchParams’s\n // process response consume body given response and nullOrBytes.\n const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)\n\n // 2. Let processBodyError be this step: run fetchParams’s process\n // response consume body given response and failure.\n const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)\n\n // 3. If response’s body is null, then queue a fetch task to run processBody\n // given null, with fetchParams’s task destination.\n if (response.body == null) {\n queueMicrotask(() => processBody(null))\n } else {\n // 4. Otherwise, fully read response’s body given processBody, processBodyError,\n // and fetchParams’s task destination.\n return fullyReadBody(response.body, processBody, processBodyError)\n }\n return Promise.resolve()\n }\n}\n\n// https://fetch.spec.whatwg.org/#http-fetch\nasync function httpFetch (fetchParams) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. Let actualResponse be null.\n let actualResponse = null\n\n // 4. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 5. If request’s service-workers mode is \"all\", then:\n if (request.serviceWorkers === 'all') {\n // TODO\n }\n\n // 6. If response is null, then:\n if (response === null) {\n // 1. If makeCORSPreflight is true and one of these conditions is true:\n // TODO\n\n // 2. If request’s redirect mode is \"follow\", then set request’s\n // service-workers mode to \"none\".\n if (request.redirect === 'follow') {\n request.serviceWorkers = 'none'\n }\n\n // 3. Set response and actualResponse to the result of running\n // HTTP-network-or-cache fetch given fetchParams.\n actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)\n\n // 4. If request’s response tainting is \"cors\" and a CORS check\n // for request and response returns failure, then return a network error.\n if (\n request.responseTainting === 'cors' &&\n corsCheck(request, response) === 'failure'\n ) {\n return makeNetworkError('cors failure')\n }\n\n // 5. If the TAO check for request and response returns failure, then set\n // request’s timing allow failed flag.\n if (TAOCheck(request, response) === 'failure') {\n request.timingAllowFailed = true\n }\n }\n\n // 7. If either request’s response tainting or response’s type\n // is \"opaque\", and the cross-origin resource policy check with\n // request’s origin, request’s client, request’s destination,\n // and actualResponse returns blocked, then return a network error.\n if (\n (request.responseTainting === 'opaque' || response.type === 'opaque') &&\n crossOriginResourcePolicyCheck(\n request.origin,\n request.client,\n request.destination,\n actualResponse\n ) === 'blocked'\n ) {\n return makeNetworkError('blocked')\n }\n\n // 8. If actualResponse’s status is a redirect status, then:\n if (redirectStatusSet.has(actualResponse.status)) {\n // 1. If actualResponse’s status is not 303, request’s body is not null,\n // and the connection uses HTTP/2, then user agents may, and are even\n // encouraged to, transmit an RST_STREAM frame.\n // See, https://github.com/whatwg/fetch/issues/1288\n if (request.redirect !== 'manual') {\n fetchParams.controller.connection.destroy()\n }\n\n // 2. Switch on request’s redirect mode:\n if (request.redirect === 'error') {\n // Set response to a network error.\n response = makeNetworkError('unexpected redirect')\n } else if (request.redirect === 'manual') {\n // Set response to an opaque-redirect filtered response whose internal\n // response is actualResponse.\n // NOTE(spec): On the web this would return an `opaqueredirect` response,\n // but that doesn't make sense server side.\n // See https://github.com/nodejs/undici/issues/1193.\n response = actualResponse\n } else if (request.redirect === 'follow') {\n // Set response to the result of running HTTP-redirect fetch given\n // fetchParams and response.\n response = await httpRedirectFetch(fetchParams, response)\n } else {\n assert(false)\n }\n }\n\n // 9. Set response’s timing info to timingInfo.\n response.timingInfo = timingInfo\n\n // 10. Return response.\n return response\n}\n\n// https://fetch.spec.whatwg.org/#http-redirect-fetch\nfunction httpRedirectFetch (fetchParams, response) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let actualResponse be response, if response is not a filtered response,\n // and response’s internal response otherwise.\n const actualResponse = response.internalResponse\n ? response.internalResponse\n : response\n\n // 3. Let locationURL be actualResponse’s location URL given request’s current\n // URL’s fragment.\n let locationURL\n\n try {\n locationURL = responseLocationURL(\n actualResponse,\n requestCurrentURL(request).hash\n )\n\n // 4. If locationURL is null, then return response.\n if (locationURL == null) {\n return response\n }\n } catch (err) {\n // 5. If locationURL is failure, then return a network error.\n return Promise.resolve(makeNetworkError(err))\n }\n\n // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network\n // error.\n if (!urlIsHttpHttpsScheme(locationURL)) {\n return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))\n }\n\n // 7. If request’s redirect count is 20, then return a network error.\n if (request.redirectCount === 20) {\n return Promise.resolve(makeNetworkError('redirect count exceeded'))\n }\n\n // 8. Increase request’s redirect count by 1.\n request.redirectCount += 1\n\n // 9. If request’s mode is \"cors\", locationURL includes credentials, and\n // request’s origin is not same origin with locationURL’s origin, then return\n // a network error.\n if (\n request.mode === 'cors' &&\n (locationURL.username || locationURL.password) &&\n !sameOrigin(request, locationURL)\n ) {\n return Promise.resolve(makeNetworkError('cross origin not allowed for request mode \"cors\"'))\n }\n\n // 10. If request’s response tainting is \"cors\" and locationURL includes\n // credentials, then return a network error.\n if (\n request.responseTainting === 'cors' &&\n (locationURL.username || locationURL.password)\n ) {\n return Promise.resolve(makeNetworkError(\n 'URL cannot contain credentials for request mode \"cors\"'\n ))\n }\n\n // 11. If actualResponse’s status is not 303, request’s body is non-null,\n // and request’s body’s source is null, then return a network error.\n if (\n actualResponse.status !== 303 &&\n request.body != null &&\n request.body.source == null\n ) {\n return Promise.resolve(makeNetworkError())\n }\n\n // 12. If one of the following is true\n // - actualResponse’s status is 301 or 302 and request’s method is `POST`\n // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`\n if (\n ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||\n (actualResponse.status === 303 &&\n !GET_OR_HEAD.includes(request.method))\n ) {\n // then:\n // 1. Set request’s method to `GET` and request’s body to null.\n request.method = 'GET'\n request.body = null\n\n // 2. For each headerName of request-body-header name, delete headerName from\n // request’s header list.\n for (const headerName of requestBodyHeader) {\n request.headersList.delete(headerName)\n }\n }\n\n // 13. If request’s current URL’s origin is not same origin with locationURL’s\n // origin, then for each headerName of CORS non-wildcard request-header name,\n // delete headerName from request’s header list.\n if (!sameOrigin(requestCurrentURL(request), locationURL)) {\n // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name\n request.headersList.delete('authorization')\n\n // https://fetch.spec.whatwg.org/#authentication-entries\n request.headersList.delete('proxy-authorization', true)\n\n // \"Cookie\" and \"Host\" are forbidden request-headers, which undici doesn't implement.\n request.headersList.delete('cookie')\n request.headersList.delete('host')\n }\n\n // 14. If request’s body is non-null, then set request’s body to the first return\n // value of safely extracting request’s body’s source.\n if (request.body != null) {\n assert(request.body.source != null)\n request.body = safelyExtractBody(request.body.source)[0]\n }\n\n // 15. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 16. Set timingInfo’s redirect end time and post-redirect start time to the\n // coarsened shared current time given fetchParams’s cross-origin isolated\n // capability.\n timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =\n coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)\n\n // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s\n // redirect start time to timingInfo’s start time.\n if (timingInfo.redirectStartTime === 0) {\n timingInfo.redirectStartTime = timingInfo.startTime\n }\n\n // 18. Append locationURL to request’s URL list.\n request.urlList.push(locationURL)\n\n // 19. Invoke set request’s referrer policy on redirect on request and\n // actualResponse.\n setRequestReferrerPolicyOnRedirect(request, actualResponse)\n\n // 20. Return the result of running main fetch given fetchParams and true.\n return mainFetch(fetchParams, true)\n}\n\n// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch\nasync function httpNetworkOrCacheFetch (\n fetchParams,\n isAuthenticationFetch = false,\n isNewConnectionFetch = false\n) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let httpFetchParams be null.\n let httpFetchParams = null\n\n // 3. Let httpRequest be null.\n let httpRequest = null\n\n // 4. Let response be null.\n let response = null\n\n // 5. Let storedResponse be null.\n // TODO: cache\n\n // 6. Let httpCache be null.\n const httpCache = null\n\n // 7. Let the revalidatingFlag be unset.\n const revalidatingFlag = false\n\n // 8. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. If request’s window is \"no-window\" and request’s redirect mode is\n // \"error\", then set httpFetchParams to fetchParams and httpRequest to\n // request.\n if (request.window === 'no-window' && request.redirect === 'error') {\n httpFetchParams = fetchParams\n httpRequest = request\n } else {\n // Otherwise:\n\n // 1. Set httpRequest to a clone of request.\n httpRequest = makeRequest(request)\n\n // 2. Set httpFetchParams to a copy of fetchParams.\n httpFetchParams = { ...fetchParams }\n\n // 3. Set httpFetchParams’s request to httpRequest.\n httpFetchParams.request = httpRequest\n }\n\n // 3. Let includeCredentials be true if one of\n const includeCredentials =\n request.credentials === 'include' ||\n (request.credentials === 'same-origin' &&\n request.responseTainting === 'basic')\n\n // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s\n // body is non-null; otherwise null.\n const contentLength = httpRequest.body ? httpRequest.body.length : null\n\n // 5. Let contentLengthHeaderValue be null.\n let contentLengthHeaderValue = null\n\n // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or\n // `PUT`, then set contentLengthHeaderValue to `0`.\n if (\n httpRequest.body == null &&\n ['POST', 'PUT'].includes(httpRequest.method)\n ) {\n contentLengthHeaderValue = '0'\n }\n\n // 7. If contentLength is non-null, then set contentLengthHeaderValue to\n // contentLength, serialized and isomorphic encoded.\n if (contentLength != null) {\n contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)\n }\n\n // 8. If contentLengthHeaderValue is non-null, then append\n // `Content-Length`/contentLengthHeaderValue to httpRequest’s header\n // list.\n if (contentLengthHeaderValue != null) {\n httpRequest.headersList.append('content-length', contentLengthHeaderValue)\n }\n\n // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,\n // contentLengthHeaderValue) to httpRequest’s header list.\n\n // 10. If contentLength is non-null and httpRequest’s keepalive is true,\n // then:\n if (contentLength != null && httpRequest.keepalive) {\n // NOTE: keepalive is a noop outside of browser context.\n }\n\n // 11. If httpRequest’s referrer is a URL, then append\n // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,\n // to httpRequest’s header list.\n if (httpRequest.referrer instanceof URL) {\n httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))\n }\n\n // 12. Append a request `Origin` header for httpRequest.\n appendRequestOriginHeader(httpRequest)\n\n // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]\n appendFetchMetadata(httpRequest)\n\n // 14. If httpRequest’s header list does not contain `User-Agent`, then\n // user agents should append `User-Agent`/default `User-Agent` value to\n // httpRequest’s header list.\n if (!httpRequest.headersList.contains('user-agent')) {\n httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')\n }\n\n // 15. If httpRequest’s cache mode is \"default\" and httpRequest’s header\n // list contains `If-Modified-Since`, `If-None-Match`,\n // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set\n // httpRequest’s cache mode to \"no-store\".\n if (\n httpRequest.cache === 'default' &&\n (httpRequest.headersList.contains('if-modified-since') ||\n httpRequest.headersList.contains('if-none-match') ||\n httpRequest.headersList.contains('if-unmodified-since') ||\n httpRequest.headersList.contains('if-match') ||\n httpRequest.headersList.contains('if-range'))\n ) {\n httpRequest.cache = 'no-store'\n }\n\n // 16. If httpRequest’s cache mode is \"no-cache\", httpRequest’s prevent\n // no-cache cache-control header modification flag is unset, and\n // httpRequest’s header list does not contain `Cache-Control`, then append\n // `Cache-Control`/`max-age=0` to httpRequest’s header list.\n if (\n httpRequest.cache === 'no-cache' &&\n !httpRequest.preventNoCacheCacheControlHeaderModification &&\n !httpRequest.headersList.contains('cache-control')\n ) {\n httpRequest.headersList.append('cache-control', 'max-age=0')\n }\n\n // 17. If httpRequest’s cache mode is \"no-store\" or \"reload\", then:\n if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {\n // 1. If httpRequest’s header list does not contain `Pragma`, then append\n // `Pragma`/`no-cache` to httpRequest’s header list.\n if (!httpRequest.headersList.contains('pragma')) {\n httpRequest.headersList.append('pragma', 'no-cache')\n }\n\n // 2. If httpRequest’s header list does not contain `Cache-Control`,\n // then append `Cache-Control`/`no-cache` to httpRequest’s header list.\n if (!httpRequest.headersList.contains('cache-control')) {\n httpRequest.headersList.append('cache-control', 'no-cache')\n }\n }\n\n // 18. If httpRequest’s header list contains `Range`, then append\n // `Accept-Encoding`/`identity` to httpRequest’s header list.\n if (httpRequest.headersList.contains('range')) {\n httpRequest.headersList.append('accept-encoding', 'identity')\n }\n\n // 19. Modify httpRequest’s header list per HTTP. Do not append a given\n // header if httpRequest’s header list contains that header’s name.\n // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129\n if (!httpRequest.headersList.contains('accept-encoding')) {\n if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {\n httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')\n } else {\n httpRequest.headersList.append('accept-encoding', 'gzip, deflate')\n }\n }\n\n httpRequest.headersList.delete('host')\n\n // 20. If includeCredentials is true, then:\n if (includeCredentials) {\n // 1. If the user agent is not configured to block cookies for httpRequest\n // (see section 7 of [COOKIES]), then:\n // TODO: credentials\n // 2. If httpRequest’s header list does not contain `Authorization`, then:\n // TODO: credentials\n }\n\n // 21. If there’s a proxy-authentication entry, use it as appropriate.\n // TODO: proxy-authentication\n\n // 22. Set httpCache to the result of determining the HTTP cache\n // partition, given httpRequest.\n // TODO: cache\n\n // 23. If httpCache is null, then set httpRequest’s cache mode to\n // \"no-store\".\n if (httpCache == null) {\n httpRequest.cache = 'no-store'\n }\n\n // 24. If httpRequest’s cache mode is neither \"no-store\" nor \"reload\",\n // then:\n if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {\n // TODO: cache\n }\n\n // 9. If aborted, then return the appropriate network error for fetchParams.\n // TODO\n\n // 10. If response is null, then:\n if (response == null) {\n // 1. If httpRequest’s cache mode is \"only-if-cached\", then return a\n // network error.\n if (httpRequest.mode === 'only-if-cached') {\n return makeNetworkError('only if cached')\n }\n\n // 2. Let forwardResponse be the result of running HTTP-network fetch\n // given httpFetchParams, includeCredentials, and isNewConnectionFetch.\n const forwardResponse = await httpNetworkFetch(\n httpFetchParams,\n includeCredentials,\n isNewConnectionFetch\n )\n\n // 3. If httpRequest’s method is unsafe and forwardResponse’s status is\n // in the range 200 to 399, inclusive, invalidate appropriate stored\n // responses in httpCache, as per the \"Invalidation\" chapter of HTTP\n // Caching, and set storedResponse to null. [HTTP-CACHING]\n if (\n !safeMethodsSet.has(httpRequest.method) &&\n forwardResponse.status >= 200 &&\n forwardResponse.status <= 399\n ) {\n // TODO: cache\n }\n\n // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,\n // then:\n if (revalidatingFlag && forwardResponse.status === 304) {\n // TODO: cache\n }\n\n // 5. If response is null, then:\n if (response == null) {\n // 1. Set response to forwardResponse.\n response = forwardResponse\n\n // 2. Store httpRequest and forwardResponse in httpCache, as per the\n // \"Storing Responses in Caches\" chapter of HTTP Caching. [HTTP-CACHING]\n // TODO: cache\n }\n }\n\n // 11. Set response’s URL list to a clone of httpRequest’s URL list.\n response.urlList = [...httpRequest.urlList]\n\n // 12. If httpRequest’s header list contains `Range`, then set response’s\n // range-requested flag.\n if (httpRequest.headersList.contains('range')) {\n response.rangeRequested = true\n }\n\n // 13. Set response’s request-includes-credentials to includeCredentials.\n response.requestIncludesCredentials = includeCredentials\n\n // 14. If response’s status is 401, httpRequest’s response tainting is not\n // \"cors\", includeCredentials is true, and request’s window is an environment\n // settings object, then:\n // TODO\n\n // 15. If response’s status is 407, then:\n if (response.status === 407) {\n // 1. If request’s window is \"no-window\", then return a network error.\n if (request.window === 'no-window') {\n return makeNetworkError()\n }\n\n // 2. ???\n\n // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams)) {\n return makeAppropriateNetworkError(fetchParams)\n }\n\n // 4. Prompt the end user as appropriate in request’s window and store\n // the result as a proxy-authentication entry. [HTTP-AUTH]\n // TODO: Invoke some kind of callback?\n\n // 5. Set response to the result of running HTTP-network-or-cache fetch given\n // fetchParams.\n // TODO\n return makeNetworkError('proxy authentication required')\n }\n\n // 16. If all of the following are true\n if (\n // response’s status is 421\n response.status === 421 &&\n // isNewConnectionFetch is false\n !isNewConnectionFetch &&\n // request’s body is null, or request’s body is non-null and request’s body’s source is non-null\n (request.body == null || request.body.source != null)\n ) {\n // then:\n\n // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams)) {\n return makeAppropriateNetworkError(fetchParams)\n }\n\n // 2. Set response to the result of running HTTP-network-or-cache\n // fetch given fetchParams, isAuthenticationFetch, and true.\n\n // TODO (spec): The spec doesn't specify this but we need to cancel\n // the active response before we can start a new one.\n // https://github.com/whatwg/fetch/issues/1293\n fetchParams.controller.connection.destroy()\n\n response = await httpNetworkOrCacheFetch(\n fetchParams,\n isAuthenticationFetch,\n true\n )\n }\n\n // 17. If isAuthenticationFetch is true, then create an authentication entry\n if (isAuthenticationFetch) {\n // TODO\n }\n\n // 18. Return response.\n return response\n}\n\n// https://fetch.spec.whatwg.org/#http-network-fetch\nasync function httpNetworkFetch (\n fetchParams,\n includeCredentials = false,\n forceNewConnection = false\n) {\n assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)\n\n fetchParams.controller.connection = {\n abort: null,\n destroyed: false,\n destroy (err) {\n if (!this.destroyed) {\n this.destroyed = true\n this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))\n }\n }\n }\n\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 4. Let httpCache be the result of determining the HTTP cache partition,\n // given request.\n // TODO: cache\n const httpCache = null\n\n // 5. If httpCache is null, then set request’s cache mode to \"no-store\".\n if (httpCache == null) {\n request.cache = 'no-store'\n }\n\n // 6. Let networkPartitionKey be the result of determining the network\n // partition key given request.\n // TODO\n\n // 7. Let newConnection be \"yes\" if forceNewConnection is true; otherwise\n // \"no\".\n const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars\n\n // 8. Switch on request’s mode:\n if (request.mode === 'websocket') {\n // Let connection be the result of obtaining a WebSocket connection,\n // given request’s current URL.\n // TODO\n } else {\n // Let connection be the result of obtaining a connection, given\n // networkPartitionKey, request’s current URL’s origin,\n // includeCredentials, and forceNewConnection.\n // TODO\n }\n\n // 9. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. If connection is failure, then return a network error.\n\n // 2. Set timingInfo’s final connection timing info to the result of\n // calling clamp and coarsen connection timing info with connection’s\n // timing info, timingInfo’s post-redirect start time, and fetchParams’s\n // cross-origin isolated capability.\n\n // 3. If connection is not an HTTP/2 connection, request’s body is non-null,\n // and request’s body’s source is null, then append (`Transfer-Encoding`,\n // `chunked`) to request’s header list.\n\n // 4. Set timingInfo’s final network-request start time to the coarsened\n // shared current time given fetchParams’s cross-origin isolated\n // capability.\n\n // 5. Set response to the result of making an HTTP request over connection\n // using request with the following caveats:\n\n // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]\n // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]\n\n // - If request’s body is non-null, and request’s body’s source is null,\n // then the user agent may have a buffer of up to 64 kibibytes and store\n // a part of request’s body in that buffer. If the user agent reads from\n // request’s body beyond that buffer’s size and the user agent needs to\n // resend request, then instead return a network error.\n\n // - Set timingInfo’s final network-response start time to the coarsened\n // shared current time given fetchParams’s cross-origin isolated capability,\n // immediately after the user agent’s HTTP parser receives the first byte\n // of the response (e.g., frame header bytes for HTTP/2 or response status\n // line for HTTP/1.x).\n\n // - Wait until all the headers are transmitted.\n\n // - Any responses whose status is in the range 100 to 199, inclusive,\n // and is not 101, are to be ignored, except for the purposes of setting\n // timingInfo’s final network-response start time above.\n\n // - If request’s header list contains `Transfer-Encoding`/`chunked` and\n // response is transferred via HTTP/1.0 or older, then return a network\n // error.\n\n // - If the HTTP request results in a TLS client certificate dialog, then:\n\n // 1. If request’s window is an environment settings object, make the\n // dialog available in request’s window.\n\n // 2. Otherwise, return a network error.\n\n // To transmit request’s body body, run these steps:\n let requestBody = null\n // 1. If body is null and fetchParams’s process request end-of-body is\n // non-null, then queue a fetch task given fetchParams’s process request\n // end-of-body and fetchParams’s task destination.\n if (request.body == null && fetchParams.processRequestEndOfBody) {\n queueMicrotask(() => fetchParams.processRequestEndOfBody())\n } else if (request.body != null) {\n // 2. Otherwise, if body is non-null:\n\n // 1. Let processBodyChunk given bytes be these steps:\n const processBodyChunk = async function * (bytes) {\n // 1. If the ongoing fetch is terminated, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. Run this step in parallel: transmit bytes.\n yield bytes\n\n // 3. If fetchParams’s process request body is non-null, then run\n // fetchParams’s process request body given bytes’s length.\n fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)\n }\n\n // 2. Let processEndOfBody be these steps:\n const processEndOfBody = () => {\n // 1. If fetchParams is canceled, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. If fetchParams’s process request end-of-body is non-null,\n // then run fetchParams’s process request end-of-body.\n if (fetchParams.processRequestEndOfBody) {\n fetchParams.processRequestEndOfBody()\n }\n }\n\n // 3. Let processBodyError given e be these steps:\n const processBodyError = (e) => {\n // 1. If fetchParams is canceled, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. If e is an \"AbortError\" DOMException, then abort fetchParams’s controller.\n if (e.name === 'AbortError') {\n fetchParams.controller.abort()\n } else {\n fetchParams.controller.terminate(e)\n }\n }\n\n // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,\n // processBodyError, and fetchParams’s task destination.\n requestBody = (async function * () {\n try {\n for await (const bytes of request.body.stream) {\n yield * processBodyChunk(bytes)\n }\n processEndOfBody()\n } catch (err) {\n processBodyError(err)\n }\n })()\n }\n\n try {\n // socket is only provided for websockets\n const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })\n\n if (socket) {\n response = makeResponse({ status, statusText, headersList, socket })\n } else {\n const iterator = body[Symbol.asyncIterator]()\n fetchParams.controller.next = () => iterator.next()\n\n response = makeResponse({ status, statusText, headersList })\n }\n } catch (err) {\n // 10. If aborted, then:\n if (err.name === 'AbortError') {\n // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.\n fetchParams.controller.connection.destroy()\n\n // 2. Return the appropriate network error for fetchParams.\n return makeAppropriateNetworkError(fetchParams, err)\n }\n\n return makeNetworkError(err)\n }\n\n // 11. Let pullAlgorithm be an action that resumes the ongoing fetch\n // if it is suspended.\n const pullAlgorithm = () => {\n fetchParams.controller.resume()\n }\n\n // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s\n // controller with reason, given reason.\n const cancelAlgorithm = (reason) => {\n fetchParams.controller.abort(reason)\n }\n\n // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by\n // the user agent.\n // TODO\n\n // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object\n // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.\n // TODO\n\n // 15. Let stream be a new ReadableStream.\n // 16. Set up stream with pullAlgorithm set to pullAlgorithm,\n // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to\n // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n const stream = new ReadableStream(\n {\n async start (controller) {\n fetchParams.controller.controller = controller\n },\n async pull (controller) {\n await pullAlgorithm(controller)\n },\n async cancel (reason) {\n await cancelAlgorithm(reason)\n }\n },\n {\n highWaterMark: 0,\n size () {\n return 1\n }\n }\n )\n\n // 17. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. Set response’s body to a new body whose stream is stream.\n response.body = { stream }\n\n // 2. If response is not a network error and request’s cache mode is\n // not \"no-store\", then update response in httpCache for request.\n // TODO\n\n // 3. If includeCredentials is true and the user agent is not configured\n // to block cookies for request (see section 7 of [COOKIES]), then run the\n // \"set-cookie-string\" parsing algorithm (see section 5.2 of [COOKIES]) on\n // the value of each header whose name is a byte-case-insensitive match for\n // `Set-Cookie` in response’s header list, if any, and request’s current URL.\n // TODO\n\n // 18. If aborted, then:\n // TODO\n\n // 19. Run these steps in parallel:\n\n // 1. Run these steps, but abort when fetchParams is canceled:\n fetchParams.controller.on('terminated', onAborted)\n fetchParams.controller.resume = async () => {\n // 1. While true\n while (true) {\n // 1-3. See onData...\n\n // 4. Set bytes to the result of handling content codings given\n // codings and bytes.\n let bytes\n let isFailure\n try {\n const { done, value } = await fetchParams.controller.next()\n\n if (isAborted(fetchParams)) {\n break\n }\n\n bytes = done ? undefined : value\n } catch (err) {\n if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {\n // zlib doesn't like empty streams.\n bytes = undefined\n } else {\n bytes = err\n\n // err may be propagated from the result of calling readablestream.cancel,\n // which might not be an error. https://github.com/nodejs/undici/issues/2009\n isFailure = true\n }\n }\n\n if (bytes === undefined) {\n // 2. Otherwise, if the bytes transmission for response’s message\n // body is done normally and stream is readable, then close\n // stream, finalize response for fetchParams and response, and\n // abort these in-parallel steps.\n readableStreamClose(fetchParams.controller.controller)\n\n finalizeResponse(fetchParams, response)\n\n return\n }\n\n // 5. Increase timingInfo’s decoded body size by bytes’s length.\n timingInfo.decodedBodySize += bytes?.byteLength ?? 0\n\n // 6. If bytes is failure, then terminate fetchParams’s controller.\n if (isFailure) {\n fetchParams.controller.terminate(bytes)\n return\n }\n\n // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes\n // into stream.\n fetchParams.controller.controller.enqueue(new Uint8Array(bytes))\n\n // 8. If stream is errored, then terminate the ongoing fetch.\n if (isErrored(stream)) {\n fetchParams.controller.terminate()\n return\n }\n\n // 9. If stream doesn’t need more data ask the user agent to suspend\n // the ongoing fetch.\n if (!fetchParams.controller.controller.desiredSize) {\n return\n }\n }\n }\n\n // 2. If aborted, then:\n function onAborted (reason) {\n // 2. If fetchParams is aborted, then:\n if (isAborted(fetchParams)) {\n // 1. Set response’s aborted flag.\n response.aborted = true\n\n // 2. If stream is readable, then error stream with the result of\n // deserialize a serialized abort reason given fetchParams’s\n // controller’s serialized abort reason and an\n // implementation-defined realm.\n if (isReadable(stream)) {\n fetchParams.controller.controller.error(\n fetchParams.controller.serializedAbortReason\n )\n }\n } else {\n // 3. Otherwise, if stream is readable, error stream with a TypeError.\n if (isReadable(stream)) {\n fetchParams.controller.controller.error(new TypeError('terminated', {\n cause: isErrorLike(reason) ? reason : undefined\n }))\n }\n }\n\n // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.\n // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.\n fetchParams.controller.connection.destroy()\n }\n\n // 20. Return response.\n return response\n\n async function dispatch ({ body }) {\n const url = requestCurrentURL(request)\n /** @type {import('../..').Agent} */\n const agent = fetchParams.controller.dispatcher\n\n return new Promise((resolve, reject) => agent.dispatch(\n {\n path: url.pathname + url.search,\n origin: url.origin,\n method: request.method,\n body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,\n headers: request.headersList.entries,\n maxRedirections: 0,\n upgrade: request.mode === 'websocket' ? 'websocket' : undefined\n },\n {\n body: null,\n abort: null,\n\n onConnect (abort) {\n // TODO (fix): Do we need connection here?\n const { connection } = fetchParams.controller\n\n if (connection.destroyed) {\n abort(new DOMException('The operation was aborted.', 'AbortError'))\n } else {\n fetchParams.controller.on('terminated', abort)\n this.abort = connection.abort = abort\n }\n },\n\n onHeaders (status, headersList, resume, statusText) {\n if (status < 200) {\n return\n }\n\n let codings = []\n let location = ''\n\n const headers = new Headers()\n\n // For H2, the headers are a plain JS object\n // We distinguish between them and iterate accordingly\n if (Array.isArray(headersList)) {\n for (let n = 0; n < headersList.length; n += 2) {\n const key = headersList[n + 0].toString('latin1')\n const val = headersList[n + 1].toString('latin1')\n if (key.toLowerCase() === 'content-encoding') {\n // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1\n // \"All content-coding values are case-insensitive...\"\n codings = val.toLowerCase().split(',').map((x) => x.trim())\n } else if (key.toLowerCase() === 'location') {\n location = val\n }\n\n headers[kHeadersList].append(key, val)\n }\n } else {\n const keys = Object.keys(headersList)\n for (const key of keys) {\n const val = headersList[key]\n if (key.toLowerCase() === 'content-encoding') {\n // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1\n // \"All content-coding values are case-insensitive...\"\n codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()\n } else if (key.toLowerCase() === 'location') {\n location = val\n }\n\n headers[kHeadersList].append(key, val)\n }\n }\n\n this.body = new Readable({ read: resume })\n\n const decoders = []\n\n const willFollow = request.redirect === 'follow' &&\n location &&\n redirectStatusSet.has(status)\n\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding\n if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {\n for (const coding of codings) {\n // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2\n if (coding === 'x-gzip' || coding === 'gzip') {\n decoders.push(zlib.createGunzip({\n // Be less strict when decoding compressed responses, since sometimes\n // servers send slightly invalid responses that are still accepted\n // by common browsers.\n // Always using Z_SYNC_FLUSH is what cURL does.\n flush: zlib.constants.Z_SYNC_FLUSH,\n finishFlush: zlib.constants.Z_SYNC_FLUSH\n }))\n } else if (coding === 'deflate') {\n decoders.push(zlib.createInflate())\n } else if (coding === 'br') {\n decoders.push(zlib.createBrotliDecompress())\n } else {\n decoders.length = 0\n break\n }\n }\n }\n\n resolve({\n status,\n statusText,\n headersList: headers[kHeadersList],\n body: decoders.length\n ? pipeline(this.body, ...decoders, () => { })\n : this.body.on('error', () => {})\n })\n\n return true\n },\n\n onData (chunk) {\n if (fetchParams.controller.dump) {\n return\n }\n\n // 1. If one or more bytes have been transmitted from response’s\n // message body, then:\n\n // 1. Let bytes be the transmitted bytes.\n const bytes = chunk\n\n // 2. Let codings be the result of extracting header list values\n // given `Content-Encoding` and response’s header list.\n // See pullAlgorithm.\n\n // 3. Increase timingInfo’s encoded body size by bytes’s length.\n timingInfo.encodedBodySize += bytes.byteLength\n\n // 4. See pullAlgorithm...\n\n return this.body.push(bytes)\n },\n\n onComplete () {\n if (this.abort) {\n fetchParams.controller.off('terminated', this.abort)\n }\n\n fetchParams.controller.ended = true\n\n this.body.push(null)\n },\n\n onError (error) {\n if (this.abort) {\n fetchParams.controller.off('terminated', this.abort)\n }\n\n this.body?.destroy(error)\n\n fetchParams.controller.terminate(error)\n\n reject(error)\n },\n\n onUpgrade (status, headersList, socket) {\n if (status !== 101) {\n return\n }\n\n const headers = new Headers()\n\n for (let n = 0; n < headersList.length; n += 2) {\n const key = headersList[n + 0].toString('latin1')\n const val = headersList[n + 1].toString('latin1')\n\n headers[kHeadersList].append(key, val)\n }\n\n resolve({\n status,\n statusText: STATUS_CODES[status],\n headersList: headers[kHeadersList],\n socket\n })\n\n return true\n }\n }\n ))\n }\n}\n\nmodule.exports = {\n fetch,\n Fetch,\n fetching,\n finalizeAndReportTiming\n}\n","/* globals AbortController */\n\n'use strict'\n\nconst { extractBody, mixinBody, cloneBody } = require('./body')\nconst { Headers, fill: fillHeaders, HeadersList } = require('./headers')\nconst { FinalizationRegistry } = require('../compat/dispatcher-weakref')()\nconst util = require('../core/util')\nconst {\n isValidHTTPToken,\n sameOrigin,\n normalizeMethod,\n makePolicyContainer,\n normalizeMethodRecord\n} = require('./util')\nconst {\n forbiddenMethodsSet,\n corsSafeListedMethodsSet,\n referrerPolicy,\n requestRedirect,\n requestMode,\n requestCredentials,\n requestCache,\n requestDuplex\n} = require('./constants')\nconst { kEnumerableProperty } = util\nconst { kHeaders, kSignal, kState, kGuard, kRealm } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { getGlobalOrigin } = require('./global')\nconst { URLSerializer } = require('./dataURL')\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst assert = require('assert')\nconst { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require('events')\n\nlet TransformStream = globalThis.TransformStream\n\nconst kAbortController = Symbol('abortController')\n\nconst requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {\n signal.removeEventListener('abort', abort)\n})\n\n// https://fetch.spec.whatwg.org/#request-class\nclass Request {\n // https://fetch.spec.whatwg.org/#dom-request\n constructor (input, init = {}) {\n if (input === kConstruct) {\n return\n }\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })\n\n input = webidl.converters.RequestInfo(input)\n init = webidl.converters.RequestInit(init)\n\n // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object\n this[kRealm] = {\n settingsObject: {\n baseUrl: getGlobalOrigin(),\n get origin () {\n return this.baseUrl?.origin\n },\n policyContainer: makePolicyContainer()\n }\n }\n\n // 1. Let request be null.\n let request = null\n\n // 2. Let fallbackMode be null.\n let fallbackMode = null\n\n // 3. Let baseURL be this’s relevant settings object’s API base URL.\n const baseUrl = this[kRealm].settingsObject.baseUrl\n\n // 4. Let signal be null.\n let signal = null\n\n // 5. If input is a string, then:\n if (typeof input === 'string') {\n // 1. Let parsedURL be the result of parsing input with baseURL.\n // 2. If parsedURL is failure, then throw a TypeError.\n let parsedURL\n try {\n parsedURL = new URL(input, baseUrl)\n } catch (err) {\n throw new TypeError('Failed to parse URL from ' + input, { cause: err })\n }\n\n // 3. If parsedURL includes credentials, then throw a TypeError.\n if (parsedURL.username || parsedURL.password) {\n throw new TypeError(\n 'Request cannot be constructed from a URL that includes credentials: ' +\n input\n )\n }\n\n // 4. Set request to a new request whose URL is parsedURL.\n request = makeRequest({ urlList: [parsedURL] })\n\n // 5. Set fallbackMode to \"cors\".\n fallbackMode = 'cors'\n } else {\n // 6. Otherwise:\n\n // 7. Assert: input is a Request object.\n assert(input instanceof Request)\n\n // 8. Set request to input’s request.\n request = input[kState]\n\n // 9. Set signal to input’s signal.\n signal = input[kSignal]\n }\n\n // 7. Let origin be this’s relevant settings object’s origin.\n const origin = this[kRealm].settingsObject.origin\n\n // 8. Let window be \"client\".\n let window = 'client'\n\n // 9. If request’s window is an environment settings object and its origin\n // is same origin with origin, then set window to request’s window.\n if (\n request.window?.constructor?.name === 'EnvironmentSettingsObject' &&\n sameOrigin(request.window, origin)\n ) {\n window = request.window\n }\n\n // 10. If init[\"window\"] exists and is non-null, then throw a TypeError.\n if (init.window != null) {\n throw new TypeError(`'window' option '${window}' must be null`)\n }\n\n // 11. If init[\"window\"] exists, then set window to \"no-window\".\n if ('window' in init) {\n window = 'no-window'\n }\n\n // 12. Set request to a new request with the following properties:\n request = makeRequest({\n // URL request’s URL.\n // undici implementation note: this is set as the first item in request's urlList in makeRequest\n // method request’s method.\n method: request.method,\n // header list A copy of request’s header list.\n // undici implementation note: headersList is cloned in makeRequest\n headersList: request.headersList,\n // unsafe-request flag Set.\n unsafeRequest: request.unsafeRequest,\n // client This’s relevant settings object.\n client: this[kRealm].settingsObject,\n // window window.\n window,\n // priority request’s priority.\n priority: request.priority,\n // origin request’s origin. The propagation of the origin is only significant for navigation requests\n // being handled by a service worker. In this scenario a request can have an origin that is different\n // from the current client.\n origin: request.origin,\n // referrer request’s referrer.\n referrer: request.referrer,\n // referrer policy request’s referrer policy.\n referrerPolicy: request.referrerPolicy,\n // mode request’s mode.\n mode: request.mode,\n // credentials mode request’s credentials mode.\n credentials: request.credentials,\n // cache mode request’s cache mode.\n cache: request.cache,\n // redirect mode request’s redirect mode.\n redirect: request.redirect,\n // integrity metadata request’s integrity metadata.\n integrity: request.integrity,\n // keepalive request’s keepalive.\n keepalive: request.keepalive,\n // reload-navigation flag request’s reload-navigation flag.\n reloadNavigation: request.reloadNavigation,\n // history-navigation flag request’s history-navigation flag.\n historyNavigation: request.historyNavigation,\n // URL list A clone of request’s URL list.\n urlList: [...request.urlList]\n })\n\n const initHasKey = Object.keys(init).length !== 0\n\n // 13. If init is not empty, then:\n if (initHasKey) {\n // 1. If request’s mode is \"navigate\", then set it to \"same-origin\".\n if (request.mode === 'navigate') {\n request.mode = 'same-origin'\n }\n\n // 2. Unset request’s reload-navigation flag.\n request.reloadNavigation = false\n\n // 3. Unset request’s history-navigation flag.\n request.historyNavigation = false\n\n // 4. Set request’s origin to \"client\".\n request.origin = 'client'\n\n // 5. Set request’s referrer to \"client\"\n request.referrer = 'client'\n\n // 6. Set request’s referrer policy to the empty string.\n request.referrerPolicy = ''\n\n // 7. Set request’s URL to request’s current URL.\n request.url = request.urlList[request.urlList.length - 1]\n\n // 8. Set request’s URL list to « request’s URL ».\n request.urlList = [request.url]\n }\n\n // 14. If init[\"referrer\"] exists, then:\n if (init.referrer !== undefined) {\n // 1. Let referrer be init[\"referrer\"].\n const referrer = init.referrer\n\n // 2. If referrer is the empty string, then set request’s referrer to \"no-referrer\".\n if (referrer === '') {\n request.referrer = 'no-referrer'\n } else {\n // 1. Let parsedReferrer be the result of parsing referrer with\n // baseURL.\n // 2. If parsedReferrer is failure, then throw a TypeError.\n let parsedReferrer\n try {\n parsedReferrer = new URL(referrer, baseUrl)\n } catch (err) {\n throw new TypeError(`Referrer \"${referrer}\" is not a valid URL.`, { cause: err })\n }\n\n // 3. If one of the following is true\n // - parsedReferrer’s scheme is \"about\" and path is the string \"client\"\n // - parsedReferrer’s origin is not same origin with origin\n // then set request’s referrer to \"client\".\n if (\n (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||\n (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))\n ) {\n request.referrer = 'client'\n } else {\n // 4. Otherwise, set request’s referrer to parsedReferrer.\n request.referrer = parsedReferrer\n }\n }\n }\n\n // 15. If init[\"referrerPolicy\"] exists, then set request’s referrer policy\n // to it.\n if (init.referrerPolicy !== undefined) {\n request.referrerPolicy = init.referrerPolicy\n }\n\n // 16. Let mode be init[\"mode\"] if it exists, and fallbackMode otherwise.\n let mode\n if (init.mode !== undefined) {\n mode = init.mode\n } else {\n mode = fallbackMode\n }\n\n // 17. If mode is \"navigate\", then throw a TypeError.\n if (mode === 'navigate') {\n throw webidl.errors.exception({\n header: 'Request constructor',\n message: 'invalid request mode navigate.'\n })\n }\n\n // 18. If mode is non-null, set request’s mode to mode.\n if (mode != null) {\n request.mode = mode\n }\n\n // 19. If init[\"credentials\"] exists, then set request’s credentials mode\n // to it.\n if (init.credentials !== undefined) {\n request.credentials = init.credentials\n }\n\n // 18. If init[\"cache\"] exists, then set request’s cache mode to it.\n if (init.cache !== undefined) {\n request.cache = init.cache\n }\n\n // 21. If request’s cache mode is \"only-if-cached\" and request’s mode is\n // not \"same-origin\", then throw a TypeError.\n if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n throw new TypeError(\n \"'only-if-cached' can be set only with 'same-origin' mode\"\n )\n }\n\n // 22. If init[\"redirect\"] exists, then set request’s redirect mode to it.\n if (init.redirect !== undefined) {\n request.redirect = init.redirect\n }\n\n // 23. If init[\"integrity\"] exists, then set request’s integrity metadata to it.\n if (init.integrity != null) {\n request.integrity = String(init.integrity)\n }\n\n // 24. If init[\"keepalive\"] exists, then set request’s keepalive to it.\n if (init.keepalive !== undefined) {\n request.keepalive = Boolean(init.keepalive)\n }\n\n // 25. If init[\"method\"] exists, then:\n if (init.method !== undefined) {\n // 1. Let method be init[\"method\"].\n let method = init.method\n\n // 2. If method is not a method or method is a forbidden method, then\n // throw a TypeError.\n if (!isValidHTTPToken(method)) {\n throw new TypeError(`'${method}' is not a valid HTTP method.`)\n }\n\n if (forbiddenMethodsSet.has(method.toUpperCase())) {\n throw new TypeError(`'${method}' HTTP method is unsupported.`)\n }\n\n // 3. Normalize method.\n method = normalizeMethodRecord[method] ?? normalizeMethod(method)\n\n // 4. Set request’s method to method.\n request.method = method\n }\n\n // 26. If init[\"signal\"] exists, then set signal to it.\n if (init.signal !== undefined) {\n signal = init.signal\n }\n\n // 27. Set this’s request to request.\n this[kState] = request\n\n // 28. Set this’s signal to a new AbortSignal object with this’s relevant\n // Realm.\n // TODO: could this be simplified with AbortSignal.any\n // (https://dom.spec.whatwg.org/#dom-abortsignal-any)\n const ac = new AbortController()\n this[kSignal] = ac.signal\n this[kSignal][kRealm] = this[kRealm]\n\n // 29. If signal is not null, then make this’s signal follow signal.\n if (signal != null) {\n if (\n !signal ||\n typeof signal.aborted !== 'boolean' ||\n typeof signal.addEventListener !== 'function'\n ) {\n throw new TypeError(\n \"Failed to construct 'Request': member signal is not of type AbortSignal.\"\n )\n }\n\n if (signal.aborted) {\n ac.abort(signal.reason)\n } else {\n // Keep a strong ref to ac while request object\n // is alive. This is needed to prevent AbortController\n // from being prematurely garbage collected.\n // See, https://github.com/nodejs/undici/issues/1926.\n this[kAbortController] = ac\n\n const acRef = new WeakRef(ac)\n const abort = function () {\n const ac = acRef.deref()\n if (ac !== undefined) {\n ac.abort(this.reason)\n }\n }\n\n // Third-party AbortControllers may not work with these.\n // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.\n try {\n // If the max amount of listeners is equal to the default, increase it\n // This is only available in node >= v19.9.0\n if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {\n setMaxListeners(100, signal)\n } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {\n setMaxListeners(100, signal)\n }\n } catch {}\n\n util.addAbortListener(signal, abort)\n requestFinalizer.register(ac, { signal, abort })\n }\n }\n\n // 30. Set this’s headers to a new Headers object with this’s relevant\n // Realm, whose header list is request’s header list and guard is\n // \"request\".\n this[kHeaders] = new Headers(kConstruct)\n this[kHeaders][kHeadersList] = request.headersList\n this[kHeaders][kGuard] = 'request'\n this[kHeaders][kRealm] = this[kRealm]\n\n // 31. If this’s request’s mode is \"no-cors\", then:\n if (mode === 'no-cors') {\n // 1. If this’s request’s method is not a CORS-safelisted method,\n // then throw a TypeError.\n if (!corsSafeListedMethodsSet.has(request.method)) {\n throw new TypeError(\n `'${request.method} is unsupported in no-cors mode.`\n )\n }\n\n // 2. Set this’s headers’s guard to \"request-no-cors\".\n this[kHeaders][kGuard] = 'request-no-cors'\n }\n\n // 32. If init is not empty, then:\n if (initHasKey) {\n /** @type {HeadersList} */\n const headersList = this[kHeaders][kHeadersList]\n // 1. Let headers be a copy of this’s headers and its associated header\n // list.\n // 2. If init[\"headers\"] exists, then set headers to init[\"headers\"].\n const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)\n\n // 3. Empty this’s headers’s header list.\n headersList.clear()\n\n // 4. If headers is a Headers object, then for each header in its header\n // list, append header’s name/header’s value to this’s headers.\n if (headers instanceof HeadersList) {\n for (const [key, val] of headers) {\n headersList.append(key, val)\n }\n // Note: Copy the `set-cookie` meta-data.\n headersList.cookies = headers.cookies\n } else {\n // 5. Otherwise, fill this’s headers with headers.\n fillHeaders(this[kHeaders], headers)\n }\n }\n\n // 33. Let inputBody be input’s request’s body if input is a Request\n // object; otherwise null.\n const inputBody = input instanceof Request ? input[kState].body : null\n\n // 34. If either init[\"body\"] exists and is non-null or inputBody is\n // non-null, and request’s method is `GET` or `HEAD`, then throw a\n // TypeError.\n if (\n (init.body != null || inputBody != null) &&\n (request.method === 'GET' || request.method === 'HEAD')\n ) {\n throw new TypeError('Request with GET/HEAD method cannot have body.')\n }\n\n // 35. Let initBody be null.\n let initBody = null\n\n // 36. If init[\"body\"] exists and is non-null, then:\n if (init.body != null) {\n // 1. Let Content-Type be null.\n // 2. Set initBody and Content-Type to the result of extracting\n // init[\"body\"], with keepalive set to request’s keepalive.\n const [extractedBody, contentType] = extractBody(\n init.body,\n request.keepalive\n )\n initBody = extractedBody\n\n // 3, If Content-Type is non-null and this’s headers’s header list does\n // not contain `Content-Type`, then append `Content-Type`/Content-Type to\n // this’s headers.\n if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {\n this[kHeaders].append('content-type', contentType)\n }\n }\n\n // 37. Let inputOrInitBody be initBody if it is non-null; otherwise\n // inputBody.\n const inputOrInitBody = initBody ?? inputBody\n\n // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is\n // null, then:\n if (inputOrInitBody != null && inputOrInitBody.source == null) {\n // 1. If initBody is non-null and init[\"duplex\"] does not exist,\n // then throw a TypeError.\n if (initBody != null && init.duplex == null) {\n throw new TypeError('RequestInit: duplex option is required when sending a body.')\n }\n\n // 2. If this’s request’s mode is neither \"same-origin\" nor \"cors\",\n // then throw a TypeError.\n if (request.mode !== 'same-origin' && request.mode !== 'cors') {\n throw new TypeError(\n 'If request is made from ReadableStream, mode should be \"same-origin\" or \"cors\"'\n )\n }\n\n // 3. Set this’s request’s use-CORS-preflight flag.\n request.useCORSPreflightFlag = true\n }\n\n // 39. Let finalBody be inputOrInitBody.\n let finalBody = inputOrInitBody\n\n // 40. If initBody is null and inputBody is non-null, then:\n if (initBody == null && inputBody != null) {\n // 1. If input is unusable, then throw a TypeError.\n if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {\n throw new TypeError(\n 'Cannot construct a Request with a Request object that has already been used.'\n )\n }\n\n // 2. Set finalBody to the result of creating a proxy for inputBody.\n if (!TransformStream) {\n TransformStream = require('stream/web').TransformStream\n }\n\n // https://streams.spec.whatwg.org/#readablestream-create-a-proxy\n const identityTransform = new TransformStream()\n inputBody.stream.pipeThrough(identityTransform)\n finalBody = {\n source: inputBody.source,\n length: inputBody.length,\n stream: identityTransform.readable\n }\n }\n\n // 41. Set this’s request’s body to finalBody.\n this[kState].body = finalBody\n }\n\n // Returns request’s HTTP method, which is \"GET\" by default.\n get method () {\n webidl.brandCheck(this, Request)\n\n // The method getter steps are to return this’s request’s method.\n return this[kState].method\n }\n\n // Returns the URL of request as a string.\n get url () {\n webidl.brandCheck(this, Request)\n\n // The url getter steps are to return this’s request’s URL, serialized.\n return URLSerializer(this[kState].url)\n }\n\n // Returns a Headers object consisting of the headers associated with request.\n // Note that headers added in the network layer by the user agent will not\n // be accounted for in this object, e.g., the \"Host\" header.\n get headers () {\n webidl.brandCheck(this, Request)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }\n\n // Returns the kind of resource requested by request, e.g., \"document\"\n // or \"script\".\n get destination () {\n webidl.brandCheck(this, Request)\n\n // The destination getter are to return this’s request’s destination.\n return this[kState].destination\n }\n\n // Returns the referrer of request. Its value can be a same-origin URL if\n // explicitly set in init, the empty string to indicate no referrer, and\n // \"about:client\" when defaulting to the global’s default. This is used\n // during fetching to determine the value of the `Referer` header of the\n // request being made.\n get referrer () {\n webidl.brandCheck(this, Request)\n\n // 1. If this’s request’s referrer is \"no-referrer\", then return the\n // empty string.\n if (this[kState].referrer === 'no-referrer') {\n return ''\n }\n\n // 2. If this’s request’s referrer is \"client\", then return\n // \"about:client\".\n if (this[kState].referrer === 'client') {\n return 'about:client'\n }\n\n // Return this’s request’s referrer, serialized.\n return this[kState].referrer.toString()\n }\n\n // Returns the referrer policy associated with request.\n // This is used during fetching to compute the value of the request’s\n // referrer.\n get referrerPolicy () {\n webidl.brandCheck(this, Request)\n\n // The referrerPolicy getter steps are to return this’s request’s referrer policy.\n return this[kState].referrerPolicy\n }\n\n // Returns the mode associated with request, which is a string indicating\n // whether the request will use CORS, or will be restricted to same-origin\n // URLs.\n get mode () {\n webidl.brandCheck(this, Request)\n\n // The mode getter steps are to return this’s request’s mode.\n return this[kState].mode\n }\n\n // Returns the credentials mode associated with request,\n // which is a string indicating whether credentials will be sent with the\n // request always, never, or only when sent to a same-origin URL.\n get credentials () {\n // The credentials getter steps are to return this’s request’s credentials mode.\n return this[kState].credentials\n }\n\n // Returns the cache mode associated with request,\n // which is a string indicating how the request will\n // interact with the browser’s cache when fetching.\n get cache () {\n webidl.brandCheck(this, Request)\n\n // The cache getter steps are to return this’s request’s cache mode.\n return this[kState].cache\n }\n\n // Returns the redirect mode associated with request,\n // which is a string indicating how redirects for the\n // request will be handled during fetching. A request\n // will follow redirects by default.\n get redirect () {\n webidl.brandCheck(this, Request)\n\n // The redirect getter steps are to return this’s request’s redirect mode.\n return this[kState].redirect\n }\n\n // Returns request’s subresource integrity metadata, which is a\n // cryptographic hash of the resource being fetched. Its value\n // consists of multiple hashes separated by whitespace. [SRI]\n get integrity () {\n webidl.brandCheck(this, Request)\n\n // The integrity getter steps are to return this’s request’s integrity\n // metadata.\n return this[kState].integrity\n }\n\n // Returns a boolean indicating whether or not request can outlive the\n // global in which it was created.\n get keepalive () {\n webidl.brandCheck(this, Request)\n\n // The keepalive getter steps are to return this’s request’s keepalive.\n return this[kState].keepalive\n }\n\n // Returns a boolean indicating whether or not request is for a reload\n // navigation.\n get isReloadNavigation () {\n webidl.brandCheck(this, Request)\n\n // The isReloadNavigation getter steps are to return true if this’s\n // request’s reload-navigation flag is set; otherwise false.\n return this[kState].reloadNavigation\n }\n\n // Returns a boolean indicating whether or not request is for a history\n // navigation (a.k.a. back-foward navigation).\n get isHistoryNavigation () {\n webidl.brandCheck(this, Request)\n\n // The isHistoryNavigation getter steps are to return true if this’s request’s\n // history-navigation flag is set; otherwise false.\n return this[kState].historyNavigation\n }\n\n // Returns the signal associated with request, which is an AbortSignal\n // object indicating whether or not request has been aborted, and its\n // abort event handler.\n get signal () {\n webidl.brandCheck(this, Request)\n\n // The signal getter steps are to return this’s signal.\n return this[kSignal]\n }\n\n get body () {\n webidl.brandCheck(this, Request)\n\n return this[kState].body ? this[kState].body.stream : null\n }\n\n get bodyUsed () {\n webidl.brandCheck(this, Request)\n\n return !!this[kState].body && util.isDisturbed(this[kState].body.stream)\n }\n\n get duplex () {\n webidl.brandCheck(this, Request)\n\n return 'half'\n }\n\n // Returns a clone of request.\n clone () {\n webidl.brandCheck(this, Request)\n\n // 1. If this is unusable, then throw a TypeError.\n if (this.bodyUsed || this.body?.locked) {\n throw new TypeError('unusable')\n }\n\n // 2. Let clonedRequest be the result of cloning this’s request.\n const clonedRequest = cloneRequest(this[kState])\n\n // 3. Let clonedRequestObject be the result of creating a Request object,\n // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.\n const clonedRequestObject = new Request(kConstruct)\n clonedRequestObject[kState] = clonedRequest\n clonedRequestObject[kRealm] = this[kRealm]\n clonedRequestObject[kHeaders] = new Headers(kConstruct)\n clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList\n clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]\n clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]\n\n // 4. Make clonedRequestObject’s signal follow this’s signal.\n const ac = new AbortController()\n if (this.signal.aborted) {\n ac.abort(this.signal.reason)\n } else {\n util.addAbortListener(\n this.signal,\n () => {\n ac.abort(this.signal.reason)\n }\n )\n }\n clonedRequestObject[kSignal] = ac.signal\n\n // 4. Return clonedRequestObject.\n return clonedRequestObject\n }\n}\n\nmixinBody(Request)\n\nfunction makeRequest (init) {\n // https://fetch.spec.whatwg.org/#requests\n const request = {\n method: 'GET',\n localURLsOnly: false,\n unsafeRequest: false,\n body: null,\n client: null,\n reservedClient: null,\n replacesClientId: '',\n window: 'client',\n keepalive: false,\n serviceWorkers: 'all',\n initiator: '',\n destination: '',\n priority: null,\n origin: 'client',\n policyContainer: 'client',\n referrer: 'client',\n referrerPolicy: '',\n mode: 'no-cors',\n useCORSPreflightFlag: false,\n credentials: 'same-origin',\n useCredentials: false,\n cache: 'default',\n redirect: 'follow',\n integrity: '',\n cryptoGraphicsNonceMetadata: '',\n parserMetadata: '',\n reloadNavigation: false,\n historyNavigation: false,\n userActivation: false,\n taintedOrigin: false,\n redirectCount: 0,\n responseTainting: 'basic',\n preventNoCacheCacheControlHeaderModification: false,\n done: false,\n timingAllowFailed: false,\n ...init,\n headersList: init.headersList\n ? new HeadersList(init.headersList)\n : new HeadersList()\n }\n request.url = request.urlList[0]\n return request\n}\n\n// https://fetch.spec.whatwg.org/#concept-request-clone\nfunction cloneRequest (request) {\n // To clone a request request, run these steps:\n\n // 1. Let newRequest be a copy of request, except for its body.\n const newRequest = makeRequest({ ...request, body: null })\n\n // 2. If request’s body is non-null, set newRequest’s body to the\n // result of cloning request’s body.\n if (request.body != null) {\n newRequest.body = cloneBody(request.body)\n }\n\n // 3. Return newRequest.\n return newRequest\n}\n\nObject.defineProperties(Request.prototype, {\n method: kEnumerableProperty,\n url: kEnumerableProperty,\n headers: kEnumerableProperty,\n redirect: kEnumerableProperty,\n clone: kEnumerableProperty,\n signal: kEnumerableProperty,\n duplex: kEnumerableProperty,\n destination: kEnumerableProperty,\n body: kEnumerableProperty,\n bodyUsed: kEnumerableProperty,\n isHistoryNavigation: kEnumerableProperty,\n isReloadNavigation: kEnumerableProperty,\n keepalive: kEnumerableProperty,\n integrity: kEnumerableProperty,\n cache: kEnumerableProperty,\n credentials: kEnumerableProperty,\n attribute: kEnumerableProperty,\n referrerPolicy: kEnumerableProperty,\n referrer: kEnumerableProperty,\n mode: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Request',\n configurable: true\n }\n})\n\nwebidl.converters.Request = webidl.interfaceConverter(\n Request\n)\n\n// https://fetch.spec.whatwg.org/#requestinfo\nwebidl.converters.RequestInfo = function (V) {\n if (typeof V === 'string') {\n return webidl.converters.USVString(V)\n }\n\n if (V instanceof Request) {\n return webidl.converters.Request(V)\n }\n\n return webidl.converters.USVString(V)\n}\n\nwebidl.converters.AbortSignal = webidl.interfaceConverter(\n AbortSignal\n)\n\n// https://fetch.spec.whatwg.org/#requestinit\nwebidl.converters.RequestInit = webidl.dictionaryConverter([\n {\n key: 'method',\n converter: webidl.converters.ByteString\n },\n {\n key: 'headers',\n converter: webidl.converters.HeadersInit\n },\n {\n key: 'body',\n converter: webidl.nullableConverter(\n webidl.converters.BodyInit\n )\n },\n {\n key: 'referrer',\n converter: webidl.converters.USVString\n },\n {\n key: 'referrerPolicy',\n converter: webidl.converters.DOMString,\n // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy\n allowedValues: referrerPolicy\n },\n {\n key: 'mode',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#concept-request-mode\n allowedValues: requestMode\n },\n {\n key: 'credentials',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestcredentials\n allowedValues: requestCredentials\n },\n {\n key: 'cache',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestcache\n allowedValues: requestCache\n },\n {\n key: 'redirect',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestredirect\n allowedValues: requestRedirect\n },\n {\n key: 'integrity',\n converter: webidl.converters.DOMString\n },\n {\n key: 'keepalive',\n converter: webidl.converters.boolean\n },\n {\n key: 'signal',\n converter: webidl.nullableConverter(\n (signal) => webidl.converters.AbortSignal(\n signal,\n { strict: false }\n )\n )\n },\n {\n key: 'window',\n converter: webidl.converters.any\n },\n {\n key: 'duplex',\n converter: webidl.converters.DOMString,\n allowedValues: requestDuplex\n }\n])\n\nmodule.exports = { Request, makeRequest }\n","'use strict'\n\nconst { Headers, HeadersList, fill } = require('./headers')\nconst { extractBody, cloneBody, mixinBody } = require('./body')\nconst util = require('../core/util')\nconst { kEnumerableProperty } = util\nconst {\n isValidReasonPhrase,\n isCancelled,\n isAborted,\n isBlobLike,\n serializeJavascriptValueToJSONString,\n isErrorLike,\n isomorphicEncode\n} = require('./util')\nconst {\n redirectStatusSet,\n nullBodyStatus,\n DOMException\n} = require('./constants')\nconst { kState, kHeaders, kGuard, kRealm } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { FormData } = require('./formdata')\nconst { getGlobalOrigin } = require('./global')\nconst { URLSerializer } = require('./dataURL')\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst assert = require('assert')\nconst { types } = require('util')\n\nconst ReadableStream = globalThis.ReadableStream || require('stream/web').ReadableStream\nconst textEncoder = new TextEncoder('utf-8')\n\n// https://fetch.spec.whatwg.org/#response-class\nclass Response {\n // Creates network error Response.\n static error () {\n // TODO\n const relevantRealm = { settingsObject: {} }\n\n // The static error() method steps are to return the result of creating a\n // Response object, given a new network error, \"immutable\", and this’s\n // relevant Realm.\n const responseObject = new Response()\n responseObject[kState] = makeNetworkError()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n return responseObject\n }\n\n // https://fetch.spec.whatwg.org/#dom-response-json\n static json (data, init = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })\n\n if (init !== null) {\n init = webidl.converters.ResponseInit(init)\n }\n\n // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.\n const bytes = textEncoder.encode(\n serializeJavascriptValueToJSONString(data)\n )\n\n // 2. Let body be the result of extracting bytes.\n const body = extractBody(bytes)\n\n // 3. Let responseObject be the result of creating a Response object, given a new response,\n // \"response\", and this’s relevant Realm.\n const relevantRealm = { settingsObject: {} }\n const responseObject = new Response()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kGuard] = 'response'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 4. Perform initialize a response given responseObject, init, and (body, \"application/json\").\n initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })\n\n // 5. Return responseObject.\n return responseObject\n }\n\n // Creates a redirect Response that redirects to url with status status.\n static redirect (url, status = 302) {\n const relevantRealm = { settingsObject: {} }\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })\n\n url = webidl.converters.USVString(url)\n status = webidl.converters['unsigned short'](status)\n\n // 1. Let parsedURL be the result of parsing url with current settings\n // object’s API base URL.\n // 2. If parsedURL is failure, then throw a TypeError.\n // TODO: base-URL?\n let parsedURL\n try {\n parsedURL = new URL(url, getGlobalOrigin())\n } catch (err) {\n throw Object.assign(new TypeError('Failed to parse URL from ' + url), {\n cause: err\n })\n }\n\n // 3. If status is not a redirect status, then throw a RangeError.\n if (!redirectStatusSet.has(status)) {\n throw new RangeError('Invalid status code ' + status)\n }\n\n // 4. Let responseObject be the result of creating a Response object,\n // given a new response, \"immutable\", and this’s relevant Realm.\n const responseObject = new Response()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 5. Set responseObject’s response’s status to status.\n responseObject[kState].status = status\n\n // 6. Let value be parsedURL, serialized and isomorphic encoded.\n const value = isomorphicEncode(URLSerializer(parsedURL))\n\n // 7. Append `Location`/value to responseObject’s response’s header list.\n responseObject[kState].headersList.append('location', value)\n\n // 8. Return responseObject.\n return responseObject\n }\n\n // https://fetch.spec.whatwg.org/#dom-response\n constructor (body = null, init = {}) {\n if (body !== null) {\n body = webidl.converters.BodyInit(body)\n }\n\n init = webidl.converters.ResponseInit(init)\n\n // TODO\n this[kRealm] = { settingsObject: {} }\n\n // 1. Set this’s response to a new response.\n this[kState] = makeResponse({})\n\n // 2. Set this’s headers to a new Headers object with this’s relevant\n // Realm, whose header list is this’s response’s header list and guard\n // is \"response\".\n this[kHeaders] = new Headers(kConstruct)\n this[kHeaders][kGuard] = 'response'\n this[kHeaders][kHeadersList] = this[kState].headersList\n this[kHeaders][kRealm] = this[kRealm]\n\n // 3. Let bodyWithType be null.\n let bodyWithType = null\n\n // 4. If body is non-null, then set bodyWithType to the result of extracting body.\n if (body != null) {\n const [extractedBody, type] = extractBody(body)\n bodyWithType = { body: extractedBody, type }\n }\n\n // 5. Perform initialize a response given this, init, and bodyWithType.\n initializeResponse(this, init, bodyWithType)\n }\n\n // Returns response’s type, e.g., \"cors\".\n get type () {\n webidl.brandCheck(this, Response)\n\n // The type getter steps are to return this’s response’s type.\n return this[kState].type\n }\n\n // Returns response’s URL, if it has one; otherwise the empty string.\n get url () {\n webidl.brandCheck(this, Response)\n\n const urlList = this[kState].urlList\n\n // The url getter steps are to return the empty string if this’s\n // response’s URL is null; otherwise this’s response’s URL,\n // serialized with exclude fragment set to true.\n const url = urlList[urlList.length - 1] ?? null\n\n if (url === null) {\n return ''\n }\n\n return URLSerializer(url, true)\n }\n\n // Returns whether response was obtained through a redirect.\n get redirected () {\n webidl.brandCheck(this, Response)\n\n // The redirected getter steps are to return true if this’s response’s URL\n // list has more than one item; otherwise false.\n return this[kState].urlList.length > 1\n }\n\n // Returns response’s status.\n get status () {\n webidl.brandCheck(this, Response)\n\n // The status getter steps are to return this’s response’s status.\n return this[kState].status\n }\n\n // Returns whether response’s status is an ok status.\n get ok () {\n webidl.brandCheck(this, Response)\n\n // The ok getter steps are to return true if this’s response’s status is an\n // ok status; otherwise false.\n return this[kState].status >= 200 && this[kState].status <= 299\n }\n\n // Returns response’s status message.\n get statusText () {\n webidl.brandCheck(this, Response)\n\n // The statusText getter steps are to return this’s response’s status\n // message.\n return this[kState].statusText\n }\n\n // Returns response’s headers as Headers.\n get headers () {\n webidl.brandCheck(this, Response)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }\n\n get body () {\n webidl.brandCheck(this, Response)\n\n return this[kState].body ? this[kState].body.stream : null\n }\n\n get bodyUsed () {\n webidl.brandCheck(this, Response)\n\n return !!this[kState].body && util.isDisturbed(this[kState].body.stream)\n }\n\n // Returns a clone of response.\n clone () {\n webidl.brandCheck(this, Response)\n\n // 1. If this is unusable, then throw a TypeError.\n if (this.bodyUsed || (this.body && this.body.locked)) {\n throw webidl.errors.exception({\n header: 'Response.clone',\n message: 'Body has already been consumed.'\n })\n }\n\n // 2. Let clonedResponse be the result of cloning this’s response.\n const clonedResponse = cloneResponse(this[kState])\n\n // 3. Return the result of creating a Response object, given\n // clonedResponse, this’s headers’s guard, and this’s relevant Realm.\n const clonedResponseObject = new Response()\n clonedResponseObject[kState] = clonedResponse\n clonedResponseObject[kRealm] = this[kRealm]\n clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList\n clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]\n clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]\n\n return clonedResponseObject\n }\n}\n\nmixinBody(Response)\n\nObject.defineProperties(Response.prototype, {\n type: kEnumerableProperty,\n url: kEnumerableProperty,\n status: kEnumerableProperty,\n ok: kEnumerableProperty,\n redirected: kEnumerableProperty,\n statusText: kEnumerableProperty,\n headers: kEnumerableProperty,\n clone: kEnumerableProperty,\n body: kEnumerableProperty,\n bodyUsed: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Response',\n configurable: true\n }\n})\n\nObject.defineProperties(Response, {\n json: kEnumerableProperty,\n redirect: kEnumerableProperty,\n error: kEnumerableProperty\n})\n\n// https://fetch.spec.whatwg.org/#concept-response-clone\nfunction cloneResponse (response) {\n // To clone a response response, run these steps:\n\n // 1. If response is a filtered response, then return a new identical\n // filtered response whose internal response is a clone of response’s\n // internal response.\n if (response.internalResponse) {\n return filterResponse(\n cloneResponse(response.internalResponse),\n response.type\n )\n }\n\n // 2. Let newResponse be a copy of response, except for its body.\n const newResponse = makeResponse({ ...response, body: null })\n\n // 3. If response’s body is non-null, then set newResponse’s body to the\n // result of cloning response’s body.\n if (response.body != null) {\n newResponse.body = cloneBody(response.body)\n }\n\n // 4. Return newResponse.\n return newResponse\n}\n\nfunction makeResponse (init) {\n return {\n aborted: false,\n rangeRequested: false,\n timingAllowPassed: false,\n requestIncludesCredentials: false,\n type: 'default',\n status: 200,\n timingInfo: null,\n cacheState: '',\n statusText: '',\n ...init,\n headersList: init.headersList\n ? new HeadersList(init.headersList)\n : new HeadersList(),\n urlList: init.urlList ? [...init.urlList] : []\n }\n}\n\nfunction makeNetworkError (reason) {\n const isError = isErrorLike(reason)\n return makeResponse({\n type: 'error',\n status: 0,\n error: isError\n ? reason\n : new Error(reason ? String(reason) : reason),\n aborted: reason && reason.name === 'AbortError'\n })\n}\n\nfunction makeFilteredResponse (response, state) {\n state = {\n internalResponse: response,\n ...state\n }\n\n return new Proxy(response, {\n get (target, p) {\n return p in state ? state[p] : target[p]\n },\n set (target, p, value) {\n assert(!(p in state))\n target[p] = value\n return true\n }\n })\n}\n\n// https://fetch.spec.whatwg.org/#concept-filtered-response\nfunction filterResponse (response, type) {\n // Set response to the following filtered response with response as its\n // internal response, depending on request’s response tainting:\n if (type === 'basic') {\n // A basic filtered response is a filtered response whose type is \"basic\"\n // and header list excludes any headers in internal response’s header list\n // whose name is a forbidden response-header name.\n\n // Note: undici does not implement forbidden response-header names\n return makeFilteredResponse(response, {\n type: 'basic',\n headersList: response.headersList\n })\n } else if (type === 'cors') {\n // A CORS filtered response is a filtered response whose type is \"cors\"\n // and header list excludes any headers in internal response’s header\n // list whose name is not a CORS-safelisted response-header name, given\n // internal response’s CORS-exposed header-name list.\n\n // Note: undici does not implement CORS-safelisted response-header names\n return makeFilteredResponse(response, {\n type: 'cors',\n headersList: response.headersList\n })\n } else if (type === 'opaque') {\n // An opaque filtered response is a filtered response whose type is\n // \"opaque\", URL list is the empty list, status is 0, status message\n // is the empty byte sequence, header list is empty, and body is null.\n\n return makeFilteredResponse(response, {\n type: 'opaque',\n urlList: Object.freeze([]),\n status: 0,\n statusText: '',\n body: null\n })\n } else if (type === 'opaqueredirect') {\n // An opaque-redirect filtered response is a filtered response whose type\n // is \"opaqueredirect\", status is 0, status message is the empty byte\n // sequence, header list is empty, and body is null.\n\n return makeFilteredResponse(response, {\n type: 'opaqueredirect',\n status: 0,\n statusText: '',\n headersList: [],\n body: null\n })\n } else {\n assert(false)\n }\n}\n\n// https://fetch.spec.whatwg.org/#appropriate-network-error\nfunction makeAppropriateNetworkError (fetchParams, err = null) {\n // 1. Assert: fetchParams is canceled.\n assert(isCancelled(fetchParams))\n\n // 2. Return an aborted network error if fetchParams is aborted;\n // otherwise return a network error.\n return isAborted(fetchParams)\n ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))\n : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))\n}\n\n// https://whatpr.org/fetch/1392.html#initialize-a-response\nfunction initializeResponse (response, init, body) {\n // 1. If init[\"status\"] is not in the range 200 to 599, inclusive, then\n // throw a RangeError.\n if (init.status !== null && (init.status < 200 || init.status > 599)) {\n throw new RangeError('init[\"status\"] must be in the range of 200 to 599, inclusive.')\n }\n\n // 2. If init[\"statusText\"] does not match the reason-phrase token production,\n // then throw a TypeError.\n if ('statusText' in init && init.statusText != null) {\n // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:\n // reason-phrase = *( HTAB / SP / VCHAR / obs-text )\n if (!isValidReasonPhrase(String(init.statusText))) {\n throw new TypeError('Invalid statusText')\n }\n }\n\n // 3. Set response’s response’s status to init[\"status\"].\n if ('status' in init && init.status != null) {\n response[kState].status = init.status\n }\n\n // 4. Set response’s response’s status message to init[\"statusText\"].\n if ('statusText' in init && init.statusText != null) {\n response[kState].statusText = init.statusText\n }\n\n // 5. If init[\"headers\"] exists, then fill response’s headers with init[\"headers\"].\n if ('headers' in init && init.headers != null) {\n fill(response[kHeaders], init.headers)\n }\n\n // 6. If body was given, then:\n if (body) {\n // 1. If response's status is a null body status, then throw a TypeError.\n if (nullBodyStatus.includes(response.status)) {\n throw webidl.errors.exception({\n header: 'Response constructor',\n message: 'Invalid response status code ' + response.status\n })\n }\n\n // 2. Set response's body to body's body.\n response[kState].body = body.body\n\n // 3. If body's type is non-null and response's header list does not contain\n // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.\n if (body.type != null && !response[kState].headersList.contains('Content-Type')) {\n response[kState].headersList.append('content-type', body.type)\n }\n }\n}\n\nwebidl.converters.ReadableStream = webidl.interfaceConverter(\n ReadableStream\n)\n\nwebidl.converters.FormData = webidl.interfaceConverter(\n FormData\n)\n\nwebidl.converters.URLSearchParams = webidl.interfaceConverter(\n URLSearchParams\n)\n\n// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit\nwebidl.converters.XMLHttpRequestBodyInit = function (V) {\n if (typeof V === 'string') {\n return webidl.converters.USVString(V)\n }\n\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {\n return webidl.converters.BufferSource(V)\n }\n\n if (util.isFormDataLike(V)) {\n return webidl.converters.FormData(V, { strict: false })\n }\n\n if (V instanceof URLSearchParams) {\n return webidl.converters.URLSearchParams(V)\n }\n\n return webidl.converters.DOMString(V)\n}\n\n// https://fetch.spec.whatwg.org/#bodyinit\nwebidl.converters.BodyInit = function (V) {\n if (V instanceof ReadableStream) {\n return webidl.converters.ReadableStream(V)\n }\n\n // Note: the spec doesn't include async iterables,\n // this is an undici extension.\n if (V?.[Symbol.asyncIterator]) {\n return V\n }\n\n return webidl.converters.XMLHttpRequestBodyInit(V)\n}\n\nwebidl.converters.ResponseInit = webidl.dictionaryConverter([\n {\n key: 'status',\n converter: webidl.converters['unsigned short'],\n defaultValue: 200\n },\n {\n key: 'statusText',\n converter: webidl.converters.ByteString,\n defaultValue: ''\n },\n {\n key: 'headers',\n converter: webidl.converters.HeadersInit\n }\n])\n\nmodule.exports = {\n makeNetworkError,\n makeResponse,\n makeAppropriateNetworkError,\n filterResponse,\n Response,\n cloneResponse\n}\n","'use strict'\n\nmodule.exports = {\n kUrl: Symbol('url'),\n kHeaders: Symbol('headers'),\n kSignal: Symbol('signal'),\n kState: Symbol('state'),\n kGuard: Symbol('guard'),\n kRealm: Symbol('realm')\n}\n","'use strict'\n\nconst { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require('./constants')\nconst { getGlobalOrigin } = require('./global')\nconst { performance } = require('perf_hooks')\nconst { isBlobLike, toUSVString, ReadableStreamFrom } = require('../core/util')\nconst assert = require('assert')\nconst { isUint8Array } = require('util/types')\n\nlet supportedHashes = []\n\n// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable\n/** @type {import('crypto')|undefined} */\nlet crypto\n\ntry {\n crypto = require('crypto')\n const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']\n supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))\n/* c8 ignore next 3 */\n} catch {\n}\n\nfunction responseURL (response) {\n // https://fetch.spec.whatwg.org/#responses\n // A response has an associated URL. It is a pointer to the last URL\n // in response’s URL list and null if response’s URL list is empty.\n const urlList = response.urlList\n const length = urlList.length\n return length === 0 ? null : urlList[length - 1].toString()\n}\n\n// https://fetch.spec.whatwg.org/#concept-response-location-url\nfunction responseLocationURL (response, requestFragment) {\n // 1. If response’s status is not a redirect status, then return null.\n if (!redirectStatusSet.has(response.status)) {\n return null\n }\n\n // 2. Let location be the result of extracting header list values given\n // `Location` and response’s header list.\n let location = response.headersList.get('location')\n\n // 3. If location is a header value, then set location to the result of\n // parsing location with response’s URL.\n if (location !== null && isValidHeaderValue(location)) {\n location = new URL(location, responseURL(response))\n }\n\n // 4. If location is a URL whose fragment is null, then set location’s\n // fragment to requestFragment.\n if (location && !location.hash) {\n location.hash = requestFragment\n }\n\n // 5. Return location.\n return location\n}\n\n/** @returns {URL} */\nfunction requestCurrentURL (request) {\n return request.urlList[request.urlList.length - 1]\n}\n\nfunction requestBadPort (request) {\n // 1. Let url be request’s current URL.\n const url = requestCurrentURL(request)\n\n // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,\n // then return blocked.\n if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {\n return 'blocked'\n }\n\n // 3. Return allowed.\n return 'allowed'\n}\n\nfunction isErrorLike (object) {\n return object instanceof Error || (\n object?.constructor?.name === 'Error' ||\n object?.constructor?.name === 'DOMException'\n )\n}\n\n// Check whether |statusText| is a ByteString and\n// matches the Reason-Phrase token production.\n// RFC 2616: https://tools.ietf.org/html/rfc2616\n// RFC 7230: https://tools.ietf.org/html/rfc7230\n// \"reason-phrase = *( HTAB / SP / VCHAR / obs-text )\"\n// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116\nfunction isValidReasonPhrase (statusText) {\n for (let i = 0; i < statusText.length; ++i) {\n const c = statusText.charCodeAt(i)\n if (\n !(\n (\n c === 0x09 || // HTAB\n (c >= 0x20 && c <= 0x7e) || // SP / VCHAR\n (c >= 0x80 && c <= 0xff)\n ) // obs-text\n )\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * @see https://tools.ietf.org/html/rfc7230#section-3.2.6\n * @param {number} c\n */\nfunction isTokenCharCode (c) {\n switch (c) {\n case 0x22:\n case 0x28:\n case 0x29:\n case 0x2c:\n case 0x2f:\n case 0x3a:\n case 0x3b:\n case 0x3c:\n case 0x3d:\n case 0x3e:\n case 0x3f:\n case 0x40:\n case 0x5b:\n case 0x5c:\n case 0x5d:\n case 0x7b:\n case 0x7d:\n // DQUOTE and \"(),/:;<=>?@[\\]{}\"\n return false\n default:\n // VCHAR %x21-7E\n return c >= 0x21 && c <= 0x7e\n }\n}\n\n/**\n * @param {string} characters\n */\nfunction isValidHTTPToken (characters) {\n if (characters.length === 0) {\n return false\n }\n for (let i = 0; i < characters.length; ++i) {\n if (!isTokenCharCode(characters.charCodeAt(i))) {\n return false\n }\n }\n return true\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-name\n * @param {string} potentialValue\n */\nfunction isValidHeaderName (potentialValue) {\n return isValidHTTPToken(potentialValue)\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-value\n * @param {string} potentialValue\n */\nfunction isValidHeaderValue (potentialValue) {\n // - Has no leading or trailing HTTP tab or space bytes.\n // - Contains no 0x00 (NUL) or HTTP newline bytes.\n if (\n potentialValue.startsWith('\\t') ||\n potentialValue.startsWith(' ') ||\n potentialValue.endsWith('\\t') ||\n potentialValue.endsWith(' ')\n ) {\n return false\n }\n\n if (\n potentialValue.includes('\\0') ||\n potentialValue.includes('\\r') ||\n potentialValue.includes('\\n')\n ) {\n return false\n }\n\n return true\n}\n\n// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect\nfunction setRequestReferrerPolicyOnRedirect (request, actualResponse) {\n // Given a request request and a response actualResponse, this algorithm\n // updates request’s referrer policy according to the Referrer-Policy\n // header (if any) in actualResponse.\n\n // 1. Let policy be the result of executing § 8.1 Parse a referrer policy\n // from a Referrer-Policy header on actualResponse.\n\n // 8.1 Parse a referrer policy from a Referrer-Policy header\n // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.\n const { headersList } = actualResponse\n // 2. Let policy be the empty string.\n // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.\n // 4. Return policy.\n const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')\n\n // Note: As the referrer-policy can contain multiple policies\n // separated by comma, we need to loop through all of them\n // and pick the first valid one.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy\n let policy = ''\n if (policyHeader.length > 0) {\n // The right-most policy takes precedence.\n // The left-most policy is the fallback.\n for (let i = policyHeader.length; i !== 0; i--) {\n const token = policyHeader[i - 1].trim()\n if (referrerPolicyTokens.has(token)) {\n policy = token\n break\n }\n }\n }\n\n // 2. If policy is not the empty string, then set request’s referrer policy to policy.\n if (policy !== '') {\n request.referrerPolicy = policy\n }\n}\n\n// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check\nfunction crossOriginResourcePolicyCheck () {\n // TODO\n return 'allowed'\n}\n\n// https://fetch.spec.whatwg.org/#concept-cors-check\nfunction corsCheck () {\n // TODO\n return 'success'\n}\n\n// https://fetch.spec.whatwg.org/#concept-tao-check\nfunction TAOCheck () {\n // TODO\n return 'success'\n}\n\nfunction appendFetchMetadata (httpRequest) {\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header\n // TODO\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header\n\n // 1. Assert: r’s url is a potentially trustworthy URL.\n // TODO\n\n // 2. Let header be a Structured Header whose value is a token.\n let header = null\n\n // 3. Set header’s value to r’s mode.\n header = httpRequest.mode\n\n // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.\n httpRequest.headersList.set('sec-fetch-mode', header)\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header\n // TODO\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header\n // TODO\n}\n\n// https://fetch.spec.whatwg.org/#append-a-request-origin-header\nfunction appendRequestOriginHeader (request) {\n // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.\n let serializedOrigin = request.origin\n\n // 2. If request’s response tainting is \"cors\" or request’s mode is \"websocket\", then append (`Origin`, serializedOrigin) to request’s header list.\n if (request.responseTainting === 'cors' || request.mode === 'websocket') {\n if (serializedOrigin) {\n request.headersList.append('origin', serializedOrigin)\n }\n\n // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:\n } else if (request.method !== 'GET' && request.method !== 'HEAD') {\n // 1. Switch on request’s referrer policy:\n switch (request.referrerPolicy) {\n case 'no-referrer':\n // Set serializedOrigin to `null`.\n serializedOrigin = null\n break\n case 'no-referrer-when-downgrade':\n case 'strict-origin':\n case 'strict-origin-when-cross-origin':\n // If request’s origin is a tuple origin, its scheme is \"https\", and request’s current URL’s scheme is not \"https\", then set serializedOrigin to `null`.\n if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {\n serializedOrigin = null\n }\n break\n case 'same-origin':\n // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.\n if (!sameOrigin(request, requestCurrentURL(request))) {\n serializedOrigin = null\n }\n break\n default:\n // Do nothing.\n }\n\n if (serializedOrigin) {\n // 2. Append (`Origin`, serializedOrigin) to request’s header list.\n request.headersList.append('origin', serializedOrigin)\n }\n }\n}\n\nfunction coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {\n // TODO\n return performance.now()\n}\n\n// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info\nfunction createOpaqueTimingInfo (timingInfo) {\n return {\n startTime: timingInfo.startTime ?? 0,\n redirectStartTime: 0,\n redirectEndTime: 0,\n postRedirectStartTime: timingInfo.startTime ?? 0,\n finalServiceWorkerStartTime: 0,\n finalNetworkResponseStartTime: 0,\n finalNetworkRequestStartTime: 0,\n endTime: 0,\n encodedBodySize: 0,\n decodedBodySize: 0,\n finalConnectionTimingInfo: null\n }\n}\n\n// https://html.spec.whatwg.org/multipage/origin.html#policy-container\nfunction makePolicyContainer () {\n // Note: the fetch spec doesn't make use of embedder policy or CSP list\n return {\n referrerPolicy: 'strict-origin-when-cross-origin'\n }\n}\n\n// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container\nfunction clonePolicyContainer (policyContainer) {\n return {\n referrerPolicy: policyContainer.referrerPolicy\n }\n}\n\n// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer\nfunction determineRequestsReferrer (request) {\n // 1. Let policy be request's referrer policy.\n const policy = request.referrerPolicy\n\n // Note: policy cannot (shouldn't) be null or an empty string.\n assert(policy)\n\n // 2. Let environment be request’s client.\n\n let referrerSource = null\n\n // 3. Switch on request’s referrer:\n if (request.referrer === 'client') {\n // Note: node isn't a browser and doesn't implement document/iframes,\n // so we bypass this step and replace it with our own.\n\n const globalOrigin = getGlobalOrigin()\n\n if (!globalOrigin || globalOrigin.origin === 'null') {\n return 'no-referrer'\n }\n\n // note: we need to clone it as it's mutated\n referrerSource = new URL(globalOrigin)\n } else if (request.referrer instanceof URL) {\n // Let referrerSource be request’s referrer.\n referrerSource = request.referrer\n }\n\n // 4. Let request’s referrerURL be the result of stripping referrerSource for\n // use as a referrer.\n let referrerURL = stripURLForReferrer(referrerSource)\n\n // 5. Let referrerOrigin be the result of stripping referrerSource for use as\n // a referrer, with the origin-only flag set to true.\n const referrerOrigin = stripURLForReferrer(referrerSource, true)\n\n // 6. If the result of serializing referrerURL is a string whose length is\n // greater than 4096, set referrerURL to referrerOrigin.\n if (referrerURL.toString().length > 4096) {\n referrerURL = referrerOrigin\n }\n\n const areSameOrigin = sameOrigin(request, referrerURL)\n const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&\n !isURLPotentiallyTrustworthy(request.url)\n\n // 8. Execute the switch statements corresponding to the value of policy:\n switch (policy) {\n case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)\n case 'unsafe-url': return referrerURL\n case 'same-origin':\n return areSameOrigin ? referrerOrigin : 'no-referrer'\n case 'origin-when-cross-origin':\n return areSameOrigin ? referrerURL : referrerOrigin\n case 'strict-origin-when-cross-origin': {\n const currentURL = requestCurrentURL(request)\n\n // 1. If the origin of referrerURL and the origin of request’s current\n // URL are the same, then return referrerURL.\n if (sameOrigin(referrerURL, currentURL)) {\n return referrerURL\n }\n\n // 2. If referrerURL is a potentially trustworthy URL and request’s\n // current URL is not a potentially trustworthy URL, then return no\n // referrer.\n if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {\n return 'no-referrer'\n }\n\n // 3. Return referrerOrigin.\n return referrerOrigin\n }\n case 'strict-origin': // eslint-disable-line\n /**\n * 1. If referrerURL is a potentially trustworthy URL and\n * request’s current URL is not a potentially trustworthy URL,\n * then return no referrer.\n * 2. Return referrerOrigin\n */\n case 'no-referrer-when-downgrade': // eslint-disable-line\n /**\n * 1. If referrerURL is a potentially trustworthy URL and\n * request’s current URL is not a potentially trustworthy URL,\n * then return no referrer.\n * 2. Return referrerOrigin\n */\n\n default: // eslint-disable-line\n return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin\n }\n}\n\n/**\n * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url\n * @param {URL} url\n * @param {boolean|undefined} originOnly\n */\nfunction stripURLForReferrer (url, originOnly) {\n // 1. Assert: url is a URL.\n assert(url instanceof URL)\n\n // 2. If url’s scheme is a local scheme, then return no referrer.\n if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {\n return 'no-referrer'\n }\n\n // 3. Set url’s username to the empty string.\n url.username = ''\n\n // 4. Set url’s password to the empty string.\n url.password = ''\n\n // 5. Set url’s fragment to null.\n url.hash = ''\n\n // 6. If the origin-only flag is true, then:\n if (originOnly) {\n // 1. Set url’s path to « the empty string ».\n url.pathname = ''\n\n // 2. Set url’s query to null.\n url.search = ''\n }\n\n // 7. Return url.\n return url\n}\n\nfunction isURLPotentiallyTrustworthy (url) {\n if (!(url instanceof URL)) {\n return false\n }\n\n // If child of about, return true\n if (url.href === 'about:blank' || url.href === 'about:srcdoc') {\n return true\n }\n\n // If scheme is data, return true\n if (url.protocol === 'data:') return true\n\n // If file, return true\n if (url.protocol === 'file:') return true\n\n return isOriginPotentiallyTrustworthy(url.origin)\n\n function isOriginPotentiallyTrustworthy (origin) {\n // If origin is explicitly null, return false\n if (origin == null || origin === 'null') return false\n\n const originAsURL = new URL(origin)\n\n // If secure, return true\n if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {\n return true\n }\n\n // If localhost or variants, return true\n if (/^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^\\[(?:0*:)*?:?0*1\\]$/.test(originAsURL.hostname) ||\n (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||\n (originAsURL.hostname.endsWith('.localhost'))) {\n return true\n }\n\n // If any other, return false\n return false\n }\n}\n\n/**\n * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist\n * @param {Uint8Array} bytes\n * @param {string} metadataList\n */\nfunction bytesMatch (bytes, metadataList) {\n // If node is not built with OpenSSL support, we cannot check\n // a request's integrity, so allow it by default (the spec will\n // allow requests if an invalid hash is given, as precedence).\n /* istanbul ignore if: only if node is built with --without-ssl */\n if (crypto === undefined) {\n return true\n }\n\n // 1. Let parsedMetadata be the result of parsing metadataList.\n const parsedMetadata = parseMetadata(metadataList)\n\n // 2. If parsedMetadata is no metadata, return true.\n if (parsedMetadata === 'no metadata') {\n return true\n }\n\n // 3. If response is not eligible for integrity validation, return false.\n // TODO\n\n // 4. If parsedMetadata is the empty set, return true.\n if (parsedMetadata.length === 0) {\n return true\n }\n\n // 5. Let metadata be the result of getting the strongest\n // metadata from parsedMetadata.\n const strongest = getStrongestMetadata(parsedMetadata)\n const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)\n\n // 6. For each item in metadata:\n for (const item of metadata) {\n // 1. Let algorithm be the alg component of item.\n const algorithm = item.algo\n\n // 2. Let expectedValue be the val component of item.\n const expectedValue = item.hash\n\n // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e\n // \"be liberal with padding\". This is annoying, and it's not even in the spec.\n\n // 3. Let actualValue be the result of applying algorithm to bytes.\n let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')\n\n if (actualValue[actualValue.length - 1] === '=') {\n if (actualValue[actualValue.length - 2] === '=') {\n actualValue = actualValue.slice(0, -2)\n } else {\n actualValue = actualValue.slice(0, -1)\n }\n }\n\n // 4. If actualValue is a case-sensitive match for expectedValue,\n // return true.\n if (compareBase64Mixed(actualValue, expectedValue)) {\n return true\n }\n }\n\n // 7. Return false.\n return false\n}\n\n// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options\n// https://www.w3.org/TR/CSP2/#source-list-syntax\n// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1\nconst parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\\s|$)( +[!-~]*)?)?/i\n\n/**\n * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata\n * @param {string} metadata\n */\nfunction parseMetadata (metadata) {\n // 1. Let result be the empty set.\n /** @type {{ algo: string, hash: string }[]} */\n const result = []\n\n // 2. Let empty be equal to true.\n let empty = true\n\n // 3. For each token returned by splitting metadata on spaces:\n for (const token of metadata.split(' ')) {\n // 1. Set empty to false.\n empty = false\n\n // 2. Parse token as a hash-with-options.\n const parsedToken = parseHashWithOptions.exec(token)\n\n // 3. If token does not parse, continue to the next token.\n if (\n parsedToken === null ||\n parsedToken.groups === undefined ||\n parsedToken.groups.algo === undefined\n ) {\n // Note: Chromium blocks the request at this point, but Firefox\n // gives a warning that an invalid integrity was given. The\n // correct behavior is to ignore these, and subsequently not\n // check the integrity of the resource.\n continue\n }\n\n // 4. Let algorithm be the hash-algo component of token.\n const algorithm = parsedToken.groups.algo.toLowerCase()\n\n // 5. If algorithm is a hash function recognized by the user\n // agent, add the parsed token to result.\n if (supportedHashes.includes(algorithm)) {\n result.push(parsedToken.groups)\n }\n }\n\n // 4. Return no metadata if empty is true, otherwise return result.\n if (empty === true) {\n return 'no metadata'\n }\n\n return result\n}\n\n/**\n * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList\n */\nfunction getStrongestMetadata (metadataList) {\n // Let algorithm be the algo component of the first item in metadataList.\n // Can be sha256\n let algorithm = metadataList[0].algo\n // If the algorithm is sha512, then it is the strongest\n // and we can return immediately\n if (algorithm[3] === '5') {\n return algorithm\n }\n\n for (let i = 1; i < metadataList.length; ++i) {\n const metadata = metadataList[i]\n // If the algorithm is sha512, then it is the strongest\n // and we can break the loop immediately\n if (metadata.algo[3] === '5') {\n algorithm = 'sha512'\n break\n // If the algorithm is sha384, then a potential sha256 or sha384 is ignored\n } else if (algorithm[3] === '3') {\n continue\n // algorithm is sha256, check if algorithm is sha384 and if so, set it as\n // the strongest\n } else if (metadata.algo[3] === '3') {\n algorithm = 'sha384'\n }\n }\n return algorithm\n}\n\nfunction filterMetadataListByAlgorithm (metadataList, algorithm) {\n if (metadataList.length === 1) {\n return metadataList\n }\n\n let pos = 0\n for (let i = 0; i < metadataList.length; ++i) {\n if (metadataList[i].algo === algorithm) {\n metadataList[pos++] = metadataList[i]\n }\n }\n\n metadataList.length = pos\n\n return metadataList\n}\n\n/**\n * Compares two base64 strings, allowing for base64url\n * in the second string.\n *\n* @param {string} actualValue always base64\n * @param {string} expectedValue base64 or base64url\n * @returns {boolean}\n */\nfunction compareBase64Mixed (actualValue, expectedValue) {\n if (actualValue.length !== expectedValue.length) {\n return false\n }\n for (let i = 0; i < actualValue.length; ++i) {\n if (actualValue[i] !== expectedValue[i]) {\n if (\n (actualValue[i] === '+' && expectedValue[i] === '-') ||\n (actualValue[i] === '/' && expectedValue[i] === '_')\n ) {\n continue\n }\n return false\n }\n }\n\n return true\n}\n\n// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request\nfunction tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {\n // TODO\n}\n\n/**\n * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}\n * @param {URL} A\n * @param {URL} B\n */\nfunction sameOrigin (A, B) {\n // 1. If A and B are the same opaque origin, then return true.\n if (A.origin === B.origin && A.origin === 'null') {\n return true\n }\n\n // 2. If A and B are both tuple origins and their schemes,\n // hosts, and port are identical, then return true.\n if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {\n return true\n }\n\n // 3. Return false.\n return false\n}\n\nfunction createDeferredPromise () {\n let res\n let rej\n const promise = new Promise((resolve, reject) => {\n res = resolve\n rej = reject\n })\n\n return { promise, resolve: res, reject: rej }\n}\n\nfunction isAborted (fetchParams) {\n return fetchParams.controller.state === 'aborted'\n}\n\nfunction isCancelled (fetchParams) {\n return fetchParams.controller.state === 'aborted' ||\n fetchParams.controller.state === 'terminated'\n}\n\nconst normalizeMethodRecord = {\n delete: 'DELETE',\n DELETE: 'DELETE',\n get: 'GET',\n GET: 'GET',\n head: 'HEAD',\n HEAD: 'HEAD',\n options: 'OPTIONS',\n OPTIONS: 'OPTIONS',\n post: 'POST',\n POST: 'POST',\n put: 'PUT',\n PUT: 'PUT'\n}\n\n// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.\nObject.setPrototypeOf(normalizeMethodRecord, null)\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-method-normalize\n * @param {string} method\n */\nfunction normalizeMethod (method) {\n return normalizeMethodRecord[method.toLowerCase()] ?? method\n}\n\n// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string\nfunction serializeJavascriptValueToJSONString (value) {\n // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).\n const result = JSON.stringify(value)\n\n // 2. If result is undefined, then throw a TypeError.\n if (result === undefined) {\n throw new TypeError('Value is not JSON serializable')\n }\n\n // 3. Assert: result is a string.\n assert(typeof result === 'string')\n\n // 4. Return result.\n return result\n}\n\n// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object\nconst esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))\n\n/**\n * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object\n * @param {() => unknown[]} iterator\n * @param {string} name name of the instance\n * @param {'key'|'value'|'key+value'} kind\n */\nfunction makeIterator (iterator, name, kind) {\n const object = {\n index: 0,\n kind,\n target: iterator\n }\n\n const i = {\n next () {\n // 1. Let interface be the interface for which the iterator prototype object exists.\n\n // 2. Let thisValue be the this value.\n\n // 3. Let object be ? ToObject(thisValue).\n\n // 4. If object is a platform object, then perform a security\n // check, passing:\n\n // 5. If object is not a default iterator object for interface,\n // then throw a TypeError.\n if (Object.getPrototypeOf(this) !== i) {\n throw new TypeError(\n `'next' called on an object that does not implement interface ${name} Iterator.`\n )\n }\n\n // 6. Let index be object’s index.\n // 7. Let kind be object’s kind.\n // 8. Let values be object’s target's value pairs to iterate over.\n const { index, kind, target } = object\n const values = target()\n\n // 9. Let len be the length of values.\n const len = values.length\n\n // 10. If index is greater than or equal to len, then return\n // CreateIterResultObject(undefined, true).\n if (index >= len) {\n return { value: undefined, done: true }\n }\n\n // 11. Let pair be the entry in values at index index.\n const pair = values[index]\n\n // 12. Set object’s index to index + 1.\n object.index = index + 1\n\n // 13. Return the iterator result for pair and kind.\n return iteratorResult(pair, kind)\n },\n // The class string of an iterator prototype object for a given interface is the\n // result of concatenating the identifier of the interface and the string \" Iterator\".\n [Symbol.toStringTag]: `${name} Iterator`\n }\n\n // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.\n Object.setPrototypeOf(i, esIteratorPrototype)\n // esIteratorPrototype needs to be the prototype of i\n // which is the prototype of an empty object. Yes, it's confusing.\n return Object.setPrototypeOf({}, i)\n}\n\n// https://webidl.spec.whatwg.org/#iterator-result\nfunction iteratorResult (pair, kind) {\n let result\n\n // 1. Let result be a value determined by the value of kind:\n switch (kind) {\n case 'key': {\n // 1. Let idlKey be pair’s key.\n // 2. Let key be the result of converting idlKey to an\n // ECMAScript value.\n // 3. result is key.\n result = pair[0]\n break\n }\n case 'value': {\n // 1. Let idlValue be pair’s value.\n // 2. Let value be the result of converting idlValue to\n // an ECMAScript value.\n // 3. result is value.\n result = pair[1]\n break\n }\n case 'key+value': {\n // 1. Let idlKey be pair’s key.\n // 2. Let idlValue be pair’s value.\n // 3. Let key be the result of converting idlKey to an\n // ECMAScript value.\n // 4. Let value be the result of converting idlValue to\n // an ECMAScript value.\n // 5. Let array be ! ArrayCreate(2).\n // 6. Call ! CreateDataProperty(array, \"0\", key).\n // 7. Call ! CreateDataProperty(array, \"1\", value).\n // 8. result is array.\n result = pair\n break\n }\n }\n\n // 2. Return CreateIterResultObject(result, false).\n return { value: result, done: false }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#body-fully-read\n */\nasync function fullyReadBody (body, processBody, processBodyError) {\n // 1. If taskDestination is null, then set taskDestination to\n // the result of starting a new parallel queue.\n\n // 2. Let successSteps given a byte sequence bytes be to queue a\n // fetch task to run processBody given bytes, with taskDestination.\n const successSteps = processBody\n\n // 3. Let errorSteps be to queue a fetch task to run processBodyError,\n // with taskDestination.\n const errorSteps = processBodyError\n\n // 4. Let reader be the result of getting a reader for body’s stream.\n // If that threw an exception, then run errorSteps with that\n // exception and return.\n let reader\n\n try {\n reader = body.stream.getReader()\n } catch (e) {\n errorSteps(e)\n return\n }\n\n // 5. Read all bytes from reader, given successSteps and errorSteps.\n try {\n const result = await readAllBytes(reader)\n successSteps(result)\n } catch (e) {\n errorSteps(e)\n }\n}\n\n/** @type {ReadableStream} */\nlet ReadableStream = globalThis.ReadableStream\n\nfunction isReadableStreamLike (stream) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n return stream instanceof ReadableStream || (\n stream[Symbol.toStringTag] === 'ReadableStream' &&\n typeof stream.tee === 'function'\n )\n}\n\nconst MAXIMUM_ARGUMENT_LENGTH = 65535\n\n/**\n * @see https://infra.spec.whatwg.org/#isomorphic-decode\n * @param {number[]|Uint8Array} input\n */\nfunction isomorphicDecode (input) {\n // 1. To isomorphic decode a byte sequence input, return a string whose code point\n // length is equal to input’s length and whose code points have the same values\n // as the values of input’s bytes, in the same order.\n\n if (input.length < MAXIMUM_ARGUMENT_LENGTH) {\n return String.fromCharCode(...input)\n }\n\n return input.reduce((previous, current) => previous + String.fromCharCode(current), '')\n}\n\n/**\n * @param {ReadableStreamController} controller\n */\nfunction readableStreamClose (controller) {\n try {\n controller.close()\n } catch (err) {\n // TODO: add comment explaining why this error occurs.\n if (!err.message.includes('Controller is already closed')) {\n throw err\n }\n }\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#isomorphic-encode\n * @param {string} input\n */\nfunction isomorphicEncode (input) {\n // 1. Assert: input contains no code points greater than U+00FF.\n for (let i = 0; i < input.length; i++) {\n assert(input.charCodeAt(i) <= 0xFF)\n }\n\n // 2. Return a byte sequence whose length is equal to input’s code\n // point length and whose bytes have the same values as the\n // values of input’s code points, in the same order\n return input\n}\n\n/**\n * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes\n * @see https://streams.spec.whatwg.org/#read-loop\n * @param {ReadableStreamDefaultReader} reader\n */\nasync function readAllBytes (reader) {\n const bytes = []\n let byteLength = 0\n\n while (true) {\n const { done, value: chunk } = await reader.read()\n\n if (done) {\n // 1. Call successSteps with bytes.\n return Buffer.concat(bytes, byteLength)\n }\n\n // 1. If chunk is not a Uint8Array object, call failureSteps\n // with a TypeError and abort these steps.\n if (!isUint8Array(chunk)) {\n throw new TypeError('Received non-Uint8Array chunk')\n }\n\n // 2. Append the bytes represented by chunk to bytes.\n bytes.push(chunk)\n byteLength += chunk.length\n\n // 3. Read-loop given reader, bytes, successSteps, and failureSteps.\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#is-local\n * @param {URL} url\n */\nfunction urlIsLocal (url) {\n assert('protocol' in url) // ensure it's a url object\n\n const protocol = url.protocol\n\n return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'\n}\n\n/**\n * @param {string|URL} url\n */\nfunction urlHasHttpsScheme (url) {\n if (typeof url === 'string') {\n return url.startsWith('https:')\n }\n\n return url.protocol === 'https:'\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-scheme\n * @param {URL} url\n */\nfunction urlIsHttpHttpsScheme (url) {\n assert('protocol' in url) // ensure it's a url object\n\n const protocol = url.protocol\n\n return protocol === 'http:' || protocol === 'https:'\n}\n\n/**\n * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.\n */\nconst hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))\n\nmodule.exports = {\n isAborted,\n isCancelled,\n createDeferredPromise,\n ReadableStreamFrom,\n toUSVString,\n tryUpgradeRequestToAPotentiallyTrustworthyURL,\n coarsenedSharedCurrentTime,\n determineRequestsReferrer,\n makePolicyContainer,\n clonePolicyContainer,\n appendFetchMetadata,\n appendRequestOriginHeader,\n TAOCheck,\n corsCheck,\n crossOriginResourcePolicyCheck,\n createOpaqueTimingInfo,\n setRequestReferrerPolicyOnRedirect,\n isValidHTTPToken,\n requestBadPort,\n requestCurrentURL,\n responseURL,\n responseLocationURL,\n isBlobLike,\n isURLPotentiallyTrustworthy,\n isValidReasonPhrase,\n sameOrigin,\n normalizeMethod,\n serializeJavascriptValueToJSONString,\n makeIterator,\n isValidHeaderName,\n isValidHeaderValue,\n hasOwn,\n isErrorLike,\n fullyReadBody,\n bytesMatch,\n isReadableStreamLike,\n readableStreamClose,\n isomorphicEncode,\n isomorphicDecode,\n urlIsLocal,\n urlHasHttpsScheme,\n urlIsHttpHttpsScheme,\n readAllBytes,\n normalizeMethodRecord,\n parseMetadata\n}\n","'use strict'\n\nconst { types } = require('util')\nconst { hasOwn, toUSVString } = require('./util')\n\n/** @type {import('../../types/webidl').Webidl} */\nconst webidl = {}\nwebidl.converters = {}\nwebidl.util = {}\nwebidl.errors = {}\n\nwebidl.errors.exception = function (message) {\n return new TypeError(`${message.header}: ${message.message}`)\n}\n\nwebidl.errors.conversionFailed = function (context) {\n const plural = context.types.length === 1 ? '' : ' one of'\n const message =\n `${context.argument} could not be converted to` +\n `${plural}: ${context.types.join(', ')}.`\n\n return webidl.errors.exception({\n header: context.prefix,\n message\n })\n}\n\nwebidl.errors.invalidArgument = function (context) {\n return webidl.errors.exception({\n header: context.prefix,\n message: `\"${context.value}\" is an invalid ${context.type}.`\n })\n}\n\n// https://webidl.spec.whatwg.org/#implements\nwebidl.brandCheck = function (V, I, opts = undefined) {\n if (opts?.strict !== false && !(V instanceof I)) {\n throw new TypeError('Illegal invocation')\n } else {\n return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]\n }\n}\n\nwebidl.argumentLengthCheck = function ({ length }, min, ctx) {\n if (length < min) {\n throw webidl.errors.exception({\n message: `${min} argument${min !== 1 ? 's' : ''} required, ` +\n `but${length ? ' only' : ''} ${length} found.`,\n ...ctx\n })\n }\n}\n\nwebidl.illegalConstructor = function () {\n throw webidl.errors.exception({\n header: 'TypeError',\n message: 'Illegal constructor'\n })\n}\n\n// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values\nwebidl.util.Type = function (V) {\n switch (typeof V) {\n case 'undefined': return 'Undefined'\n case 'boolean': return 'Boolean'\n case 'string': return 'String'\n case 'symbol': return 'Symbol'\n case 'number': return 'Number'\n case 'bigint': return 'BigInt'\n case 'function':\n case 'object': {\n if (V === null) {\n return 'Null'\n }\n\n return 'Object'\n }\n }\n}\n\n// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint\nwebidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {\n let upperBound\n let lowerBound\n\n // 1. If bitLength is 64, then:\n if (bitLength === 64) {\n // 1. Let upperBound be 2^53 − 1.\n upperBound = Math.pow(2, 53) - 1\n\n // 2. If signedness is \"unsigned\", then let lowerBound be 0.\n if (signedness === 'unsigned') {\n lowerBound = 0\n } else {\n // 3. Otherwise let lowerBound be −2^53 + 1.\n lowerBound = Math.pow(-2, 53) + 1\n }\n } else if (signedness === 'unsigned') {\n // 2. Otherwise, if signedness is \"unsigned\", then:\n\n // 1. Let lowerBound be 0.\n lowerBound = 0\n\n // 2. Let upperBound be 2^bitLength − 1.\n upperBound = Math.pow(2, bitLength) - 1\n } else {\n // 3. Otherwise:\n\n // 1. Let lowerBound be -2^bitLength − 1.\n lowerBound = Math.pow(-2, bitLength) - 1\n\n // 2. Let upperBound be 2^bitLength − 1 − 1.\n upperBound = Math.pow(2, bitLength - 1) - 1\n }\n\n // 4. Let x be ? ToNumber(V).\n let x = Number(V)\n\n // 5. If x is −0, then set x to +0.\n if (x === 0) {\n x = 0\n }\n\n // 6. If the conversion is to an IDL type associated\n // with the [EnforceRange] extended attribute, then:\n if (opts.enforceRange === true) {\n // 1. If x is NaN, +∞, or −∞, then throw a TypeError.\n if (\n Number.isNaN(x) ||\n x === Number.POSITIVE_INFINITY ||\n x === Number.NEGATIVE_INFINITY\n ) {\n throw webidl.errors.exception({\n header: 'Integer conversion',\n message: `Could not convert ${V} to an integer.`\n })\n }\n\n // 2. Set x to IntegerPart(x).\n x = webidl.util.IntegerPart(x)\n\n // 3. If x < lowerBound or x > upperBound, then\n // throw a TypeError.\n if (x < lowerBound || x > upperBound) {\n throw webidl.errors.exception({\n header: 'Integer conversion',\n message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`\n })\n }\n\n // 4. Return x.\n return x\n }\n\n // 7. If x is not NaN and the conversion is to an IDL\n // type associated with the [Clamp] extended\n // attribute, then:\n if (!Number.isNaN(x) && opts.clamp === true) {\n // 1. Set x to min(max(x, lowerBound), upperBound).\n x = Math.min(Math.max(x, lowerBound), upperBound)\n\n // 2. Round x to the nearest integer, choosing the\n // even integer if it lies halfway between two,\n // and choosing +0 rather than −0.\n if (Math.floor(x) % 2 === 0) {\n x = Math.floor(x)\n } else {\n x = Math.ceil(x)\n }\n\n // 3. Return x.\n return x\n }\n\n // 8. If x is NaN, +0, +∞, or −∞, then return +0.\n if (\n Number.isNaN(x) ||\n (x === 0 && Object.is(0, x)) ||\n x === Number.POSITIVE_INFINITY ||\n x === Number.NEGATIVE_INFINITY\n ) {\n return 0\n }\n\n // 9. Set x to IntegerPart(x).\n x = webidl.util.IntegerPart(x)\n\n // 10. Set x to x modulo 2^bitLength.\n x = x % Math.pow(2, bitLength)\n\n // 11. If signedness is \"signed\" and x ≥ 2^bitLength − 1,\n // then return x − 2^bitLength.\n if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {\n return x - Math.pow(2, bitLength)\n }\n\n // 12. Otherwise, return x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart\nwebidl.util.IntegerPart = function (n) {\n // 1. Let r be floor(abs(n)).\n const r = Math.floor(Math.abs(n))\n\n // 2. If n < 0, then return -1 × r.\n if (n < 0) {\n return -1 * r\n }\n\n // 3. Otherwise, return r.\n return r\n}\n\n// https://webidl.spec.whatwg.org/#es-sequence\nwebidl.sequenceConverter = function (converter) {\n return (V) => {\n // 1. If Type(V) is not Object, throw a TypeError.\n if (webidl.util.Type(V) !== 'Object') {\n throw webidl.errors.exception({\n header: 'Sequence',\n message: `Value of type ${webidl.util.Type(V)} is not an Object.`\n })\n }\n\n // 2. Let method be ? GetMethod(V, @@iterator).\n /** @type {Generator} */\n const method = V?.[Symbol.iterator]?.()\n const seq = []\n\n // 3. If method is undefined, throw a TypeError.\n if (\n method === undefined ||\n typeof method.next !== 'function'\n ) {\n throw webidl.errors.exception({\n header: 'Sequence',\n message: 'Object is not an iterator.'\n })\n }\n\n // https://webidl.spec.whatwg.org/#create-sequence-from-iterable\n while (true) {\n const { done, value } = method.next()\n\n if (done) {\n break\n }\n\n seq.push(converter(value))\n }\n\n return seq\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-to-record\nwebidl.recordConverter = function (keyConverter, valueConverter) {\n return (O) => {\n // 1. If Type(O) is not Object, throw a TypeError.\n if (webidl.util.Type(O) !== 'Object') {\n throw webidl.errors.exception({\n header: 'Record',\n message: `Value of type ${webidl.util.Type(O)} is not an Object.`\n })\n }\n\n // 2. Let result be a new empty instance of record.\n const result = {}\n\n if (!types.isProxy(O)) {\n // Object.keys only returns enumerable properties\n const keys = Object.keys(O)\n\n for (const key of keys) {\n // 1. Let typedKey be key converted to an IDL value of type K.\n const typedKey = keyConverter(key)\n\n // 2. Let value be ? Get(O, key).\n // 3. Let typedValue be value converted to an IDL value of type V.\n const typedValue = valueConverter(O[key])\n\n // 4. Set result[typedKey] to typedValue.\n result[typedKey] = typedValue\n }\n\n // 5. Return result.\n return result\n }\n\n // 3. Let keys be ? O.[[OwnPropertyKeys]]().\n const keys = Reflect.ownKeys(O)\n\n // 4. For each key of keys.\n for (const key of keys) {\n // 1. Let desc be ? O.[[GetOwnProperty]](key).\n const desc = Reflect.getOwnPropertyDescriptor(O, key)\n\n // 2. If desc is not undefined and desc.[[Enumerable]] is true:\n if (desc?.enumerable) {\n // 1. Let typedKey be key converted to an IDL value of type K.\n const typedKey = keyConverter(key)\n\n // 2. Let value be ? Get(O, key).\n // 3. Let typedValue be value converted to an IDL value of type V.\n const typedValue = valueConverter(O[key])\n\n // 4. Set result[typedKey] to typedValue.\n result[typedKey] = typedValue\n }\n }\n\n // 5. Return result.\n return result\n }\n}\n\nwebidl.interfaceConverter = function (i) {\n return (V, opts = {}) => {\n if (opts.strict !== false && !(V instanceof i)) {\n throw webidl.errors.exception({\n header: i.name,\n message: `Expected ${V} to be an instance of ${i.name}.`\n })\n }\n\n return V\n }\n}\n\nwebidl.dictionaryConverter = function (converters) {\n return (dictionary) => {\n const type = webidl.util.Type(dictionary)\n const dict = {}\n\n if (type === 'Null' || type === 'Undefined') {\n return dict\n } else if (type !== 'Object') {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`\n })\n }\n\n for (const options of converters) {\n const { key, defaultValue, required, converter } = options\n\n if (required === true) {\n if (!hasOwn(dictionary, key)) {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `Missing required key \"${key}\".`\n })\n }\n }\n\n let value = dictionary[key]\n const hasDefault = hasOwn(options, 'defaultValue')\n\n // Only use defaultValue if value is undefined and\n // a defaultValue options was provided.\n if (hasDefault && value !== null) {\n value = value ?? defaultValue\n }\n\n // A key can be optional and have no default value.\n // When this happens, do not perform a conversion,\n // and do not assign the key a value.\n if (required || hasDefault || value !== undefined) {\n value = converter(value)\n\n if (\n options.allowedValues &&\n !options.allowedValues.includes(value)\n ) {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`\n })\n }\n\n dict[key] = value\n }\n }\n\n return dict\n }\n}\n\nwebidl.nullableConverter = function (converter) {\n return (V) => {\n if (V === null) {\n return V\n }\n\n return converter(V)\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-DOMString\nwebidl.converters.DOMString = function (V, opts = {}) {\n // 1. If V is null and the conversion is to an IDL type\n // associated with the [LegacyNullToEmptyString]\n // extended attribute, then return the DOMString value\n // that represents the empty string.\n if (V === null && opts.legacyNullToEmptyString) {\n return ''\n }\n\n // 2. Let x be ? ToString(V).\n if (typeof V === 'symbol') {\n throw new TypeError('Could not convert argument of type symbol to string.')\n }\n\n // 3. Return the IDL DOMString value that represents the\n // same sequence of code units as the one the\n // ECMAScript String value x represents.\n return String(V)\n}\n\n// https://webidl.spec.whatwg.org/#es-ByteString\nwebidl.converters.ByteString = function (V) {\n // 1. Let x be ? ToString(V).\n // Note: DOMString converter perform ? ToString(V)\n const x = webidl.converters.DOMString(V)\n\n // 2. If the value of any element of x is greater than\n // 255, then throw a TypeError.\n for (let index = 0; index < x.length; index++) {\n if (x.charCodeAt(index) > 255) {\n throw new TypeError(\n 'Cannot convert argument to a ByteString because the character at ' +\n `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`\n )\n }\n }\n\n // 3. Return an IDL ByteString value whose length is the\n // length of x, and where the value of each element is\n // the value of the corresponding element of x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-USVString\nwebidl.converters.USVString = toUSVString\n\n// https://webidl.spec.whatwg.org/#es-boolean\nwebidl.converters.boolean = function (V) {\n // 1. Let x be the result of computing ToBoolean(V).\n const x = Boolean(V)\n\n // 2. Return the IDL boolean value that is the one that represents\n // the same truth value as the ECMAScript Boolean value x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-any\nwebidl.converters.any = function (V) {\n return V\n}\n\n// https://webidl.spec.whatwg.org/#es-long-long\nwebidl.converters['long long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 64, \"signed\").\n const x = webidl.util.ConvertToInt(V, 64, 'signed')\n\n // 2. Return the IDL long long value that represents\n // the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-long-long\nwebidl.converters['unsigned long long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 64, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 64, 'unsigned')\n\n // 2. Return the IDL unsigned long long value that\n // represents the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-long\nwebidl.converters['unsigned long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 32, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 32, 'unsigned')\n\n // 2. Return the IDL unsigned long value that\n // represents the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-short\nwebidl.converters['unsigned short'] = function (V, opts) {\n // 1. Let x be ? ConvertToInt(V, 16, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)\n\n // 2. Return the IDL unsigned short value that represents\n // the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#idl-ArrayBuffer\nwebidl.converters.ArrayBuffer = function (V, opts = {}) {\n // 1. If Type(V) is not Object, or V does not have an\n // [[ArrayBufferData]] internal slot, then throw a\n // TypeError.\n // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances\n // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances\n if (\n webidl.util.Type(V) !== 'Object' ||\n !types.isAnyArrayBuffer(V)\n ) {\n throw webidl.errors.conversionFailed({\n prefix: `${V}`,\n argument: `${V}`,\n types: ['ArrayBuffer']\n })\n }\n\n // 2. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V) is true, then throw a\n // TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V) is true, then throw a\n // TypeError.\n // Note: resizable ArrayBuffers are currently a proposal.\n\n // 4. Return the IDL ArrayBuffer value that is a\n // reference to the same object as V.\n return V\n}\n\nwebidl.converters.TypedArray = function (V, T, opts = {}) {\n // 1. Let T be the IDL type V is being converted to.\n\n // 2. If Type(V) is not Object, or V does not have a\n // [[TypedArrayName]] internal slot with a value\n // equal to T’s name, then throw a TypeError.\n if (\n webidl.util.Type(V) !== 'Object' ||\n !types.isTypedArray(V) ||\n V.constructor.name !== T.name\n ) {\n throw webidl.errors.conversionFailed({\n prefix: `${T.name}`,\n argument: `${V}`,\n types: [T.name]\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 4. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n // Note: resizable array buffers are currently a proposal\n\n // 5. Return the IDL value of type T that is a reference\n // to the same object as V.\n return V\n}\n\nwebidl.converters.DataView = function (V, opts = {}) {\n // 1. If Type(V) is not Object, or V does not have a\n // [[DataView]] internal slot, then throw a TypeError.\n if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {\n throw webidl.errors.exception({\n header: 'DataView',\n message: 'Object is not a DataView.'\n })\n }\n\n // 2. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,\n // then throw a TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n // Note: resizable ArrayBuffers are currently a proposal\n\n // 4. Return the IDL DataView value that is a reference\n // to the same object as V.\n return V\n}\n\n// https://webidl.spec.whatwg.org/#BufferSource\nwebidl.converters.BufferSource = function (V, opts = {}) {\n if (types.isAnyArrayBuffer(V)) {\n return webidl.converters.ArrayBuffer(V, opts)\n }\n\n if (types.isTypedArray(V)) {\n return webidl.converters.TypedArray(V, V.constructor)\n }\n\n if (types.isDataView(V)) {\n return webidl.converters.DataView(V, opts)\n }\n\n throw new TypeError(`Could not convert ${V} to a BufferSource.`)\n}\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.ByteString\n)\n\nwebidl.converters['sequence>'] = webidl.sequenceConverter(\n webidl.converters['sequence']\n)\n\nwebidl.converters['record'] = webidl.recordConverter(\n webidl.converters.ByteString,\n webidl.converters.ByteString\n)\n\nmodule.exports = {\n webidl\n}\n","'use strict'\n\n/**\n * @see https://encoding.spec.whatwg.org/#concept-encoding-get\n * @param {string|undefined} label\n */\nfunction getEncoding (label) {\n if (!label) {\n return 'failure'\n }\n\n // 1. Remove any leading and trailing ASCII whitespace from label.\n // 2. If label is an ASCII case-insensitive match for any of the\n // labels listed in the table below, then return the\n // corresponding encoding; otherwise return failure.\n switch (label.trim().toLowerCase()) {\n case 'unicode-1-1-utf-8':\n case 'unicode11utf8':\n case 'unicode20utf8':\n case 'utf-8':\n case 'utf8':\n case 'x-unicode20utf8':\n return 'UTF-8'\n case '866':\n case 'cp866':\n case 'csibm866':\n case 'ibm866':\n return 'IBM866'\n case 'csisolatin2':\n case 'iso-8859-2':\n case 'iso-ir-101':\n case 'iso8859-2':\n case 'iso88592':\n case 'iso_8859-2':\n case 'iso_8859-2:1987':\n case 'l2':\n case 'latin2':\n return 'ISO-8859-2'\n case 'csisolatin3':\n case 'iso-8859-3':\n case 'iso-ir-109':\n case 'iso8859-3':\n case 'iso88593':\n case 'iso_8859-3':\n case 'iso_8859-3:1988':\n case 'l3':\n case 'latin3':\n return 'ISO-8859-3'\n case 'csisolatin4':\n case 'iso-8859-4':\n case 'iso-ir-110':\n case 'iso8859-4':\n case 'iso88594':\n case 'iso_8859-4':\n case 'iso_8859-4:1988':\n case 'l4':\n case 'latin4':\n return 'ISO-8859-4'\n case 'csisolatincyrillic':\n case 'cyrillic':\n case 'iso-8859-5':\n case 'iso-ir-144':\n case 'iso8859-5':\n case 'iso88595':\n case 'iso_8859-5':\n case 'iso_8859-5:1988':\n return 'ISO-8859-5'\n case 'arabic':\n case 'asmo-708':\n case 'csiso88596e':\n case 'csiso88596i':\n case 'csisolatinarabic':\n case 'ecma-114':\n case 'iso-8859-6':\n case 'iso-8859-6-e':\n case 'iso-8859-6-i':\n case 'iso-ir-127':\n case 'iso8859-6':\n case 'iso88596':\n case 'iso_8859-6':\n case 'iso_8859-6:1987':\n return 'ISO-8859-6'\n case 'csisolatingreek':\n case 'ecma-118':\n case 'elot_928':\n case 'greek':\n case 'greek8':\n case 'iso-8859-7':\n case 'iso-ir-126':\n case 'iso8859-7':\n case 'iso88597':\n case 'iso_8859-7':\n case 'iso_8859-7:1987':\n case 'sun_eu_greek':\n return 'ISO-8859-7'\n case 'csiso88598e':\n case 'csisolatinhebrew':\n case 'hebrew':\n case 'iso-8859-8':\n case 'iso-8859-8-e':\n case 'iso-ir-138':\n case 'iso8859-8':\n case 'iso88598':\n case 'iso_8859-8':\n case 'iso_8859-8:1988':\n case 'visual':\n return 'ISO-8859-8'\n case 'csiso88598i':\n case 'iso-8859-8-i':\n case 'logical':\n return 'ISO-8859-8-I'\n case 'csisolatin6':\n case 'iso-8859-10':\n case 'iso-ir-157':\n case 'iso8859-10':\n case 'iso885910':\n case 'l6':\n case 'latin6':\n return 'ISO-8859-10'\n case 'iso-8859-13':\n case 'iso8859-13':\n case 'iso885913':\n return 'ISO-8859-13'\n case 'iso-8859-14':\n case 'iso8859-14':\n case 'iso885914':\n return 'ISO-8859-14'\n case 'csisolatin9':\n case 'iso-8859-15':\n case 'iso8859-15':\n case 'iso885915':\n case 'iso_8859-15':\n case 'l9':\n return 'ISO-8859-15'\n case 'iso-8859-16':\n return 'ISO-8859-16'\n case 'cskoi8r':\n case 'koi':\n case 'koi8':\n case 'koi8-r':\n case 'koi8_r':\n return 'KOI8-R'\n case 'koi8-ru':\n case 'koi8-u':\n return 'KOI8-U'\n case 'csmacintosh':\n case 'mac':\n case 'macintosh':\n case 'x-mac-roman':\n return 'macintosh'\n case 'iso-8859-11':\n case 'iso8859-11':\n case 'iso885911':\n case 'tis-620':\n case 'windows-874':\n return 'windows-874'\n case 'cp1250':\n case 'windows-1250':\n case 'x-cp1250':\n return 'windows-1250'\n case 'cp1251':\n case 'windows-1251':\n case 'x-cp1251':\n return 'windows-1251'\n case 'ansi_x3.4-1968':\n case 'ascii':\n case 'cp1252':\n case 'cp819':\n case 'csisolatin1':\n case 'ibm819':\n case 'iso-8859-1':\n case 'iso-ir-100':\n case 'iso8859-1':\n case 'iso88591':\n case 'iso_8859-1':\n case 'iso_8859-1:1987':\n case 'l1':\n case 'latin1':\n case 'us-ascii':\n case 'windows-1252':\n case 'x-cp1252':\n return 'windows-1252'\n case 'cp1253':\n case 'windows-1253':\n case 'x-cp1253':\n return 'windows-1253'\n case 'cp1254':\n case 'csisolatin5':\n case 'iso-8859-9':\n case 'iso-ir-148':\n case 'iso8859-9':\n case 'iso88599':\n case 'iso_8859-9':\n case 'iso_8859-9:1989':\n case 'l5':\n case 'latin5':\n case 'windows-1254':\n case 'x-cp1254':\n return 'windows-1254'\n case 'cp1255':\n case 'windows-1255':\n case 'x-cp1255':\n return 'windows-1255'\n case 'cp1256':\n case 'windows-1256':\n case 'x-cp1256':\n return 'windows-1256'\n case 'cp1257':\n case 'windows-1257':\n case 'x-cp1257':\n return 'windows-1257'\n case 'cp1258':\n case 'windows-1258':\n case 'x-cp1258':\n return 'windows-1258'\n case 'x-mac-cyrillic':\n case 'x-mac-ukrainian':\n return 'x-mac-cyrillic'\n case 'chinese':\n case 'csgb2312':\n case 'csiso58gb231280':\n case 'gb2312':\n case 'gb_2312':\n case 'gb_2312-80':\n case 'gbk':\n case 'iso-ir-58':\n case 'x-gbk':\n return 'GBK'\n case 'gb18030':\n return 'gb18030'\n case 'big5':\n case 'big5-hkscs':\n case 'cn-big5':\n case 'csbig5':\n case 'x-x-big5':\n return 'Big5'\n case 'cseucpkdfmtjapanese':\n case 'euc-jp':\n case 'x-euc-jp':\n return 'EUC-JP'\n case 'csiso2022jp':\n case 'iso-2022-jp':\n return 'ISO-2022-JP'\n case 'csshiftjis':\n case 'ms932':\n case 'ms_kanji':\n case 'shift-jis':\n case 'shift_jis':\n case 'sjis':\n case 'windows-31j':\n case 'x-sjis':\n return 'Shift_JIS'\n case 'cseuckr':\n case 'csksc56011987':\n case 'euc-kr':\n case 'iso-ir-149':\n case 'korean':\n case 'ks_c_5601-1987':\n case 'ks_c_5601-1989':\n case 'ksc5601':\n case 'ksc_5601':\n case 'windows-949':\n return 'EUC-KR'\n case 'csiso2022kr':\n case 'hz-gb-2312':\n case 'iso-2022-cn':\n case 'iso-2022-cn-ext':\n case 'iso-2022-kr':\n case 'replacement':\n return 'replacement'\n case 'unicodefffe':\n case 'utf-16be':\n return 'UTF-16BE'\n case 'csunicode':\n case 'iso-10646-ucs-2':\n case 'ucs-2':\n case 'unicode':\n case 'unicodefeff':\n case 'utf-16':\n case 'utf-16le':\n return 'UTF-16LE'\n case 'x-user-defined':\n return 'x-user-defined'\n default: return 'failure'\n }\n}\n\nmodule.exports = {\n getEncoding\n}\n","'use strict'\n\nconst {\n staticPropertyDescriptors,\n readOperation,\n fireAProgressEvent\n} = require('./util')\nconst {\n kState,\n kError,\n kResult,\n kEvents,\n kAborted\n} = require('./symbols')\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\n\nclass FileReader extends EventTarget {\n constructor () {\n super()\n\n this[kState] = 'empty'\n this[kResult] = null\n this[kError] = null\n this[kEvents] = {\n loadend: null,\n error: null,\n abort: null,\n load: null,\n progress: null,\n loadstart: null\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer\n * @param {import('buffer').Blob} blob\n */\n readAsArrayBuffer (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsArrayBuffer(blob) method, when invoked,\n // must initiate a read operation for blob with ArrayBuffer.\n readOperation(this, blob, 'ArrayBuffer')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#readAsBinaryString\n * @param {import('buffer').Blob} blob\n */\n readAsBinaryString (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsBinaryString(blob) method, when invoked,\n // must initiate a read operation for blob with BinaryString.\n readOperation(this, blob, 'BinaryString')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#readAsDataText\n * @param {import('buffer').Blob} blob\n * @param {string?} encoding\n */\n readAsText (blob, encoding = undefined) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n if (encoding !== undefined) {\n encoding = webidl.converters.DOMString(encoding)\n }\n\n // The readAsText(blob, encoding) method, when invoked,\n // must initiate a read operation for blob with Text and encoding.\n readOperation(this, blob, 'Text', encoding)\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL\n * @param {import('buffer').Blob} blob\n */\n readAsDataURL (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsDataURL(blob) method, when invoked, must\n // initiate a read operation for blob with DataURL.\n readOperation(this, blob, 'DataURL')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-abort\n */\n abort () {\n // 1. If this's state is \"empty\" or if this's state is\n // \"done\" set this's result to null and terminate\n // this algorithm.\n if (this[kState] === 'empty' || this[kState] === 'done') {\n this[kResult] = null\n return\n }\n\n // 2. If this's state is \"loading\" set this's state to\n // \"done\" and set this's result to null.\n if (this[kState] === 'loading') {\n this[kState] = 'done'\n this[kResult] = null\n }\n\n // 3. If there are any tasks from this on the file reading\n // task source in an affiliated task queue, then remove\n // those tasks from that task queue.\n this[kAborted] = true\n\n // 4. Terminate the algorithm for the read method being processed.\n // TODO\n\n // 5. Fire a progress event called abort at this.\n fireAProgressEvent('abort', this)\n\n // 6. If this's state is not \"loading\", fire a progress\n // event called loadend at this.\n if (this[kState] !== 'loading') {\n fireAProgressEvent('loadend', this)\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate\n */\n get readyState () {\n webidl.brandCheck(this, FileReader)\n\n switch (this[kState]) {\n case 'empty': return this.EMPTY\n case 'loading': return this.LOADING\n case 'done': return this.DONE\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-result\n */\n get result () {\n webidl.brandCheck(this, FileReader)\n\n // The result attribute’s getter, when invoked, must return\n // this's result.\n return this[kResult]\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-error\n */\n get error () {\n webidl.brandCheck(this, FileReader)\n\n // The error attribute’s getter, when invoked, must return\n // this's error.\n return this[kError]\n }\n\n get onloadend () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].loadend\n }\n\n set onloadend (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].loadend) {\n this.removeEventListener('loadend', this[kEvents].loadend)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].loadend = fn\n this.addEventListener('loadend', fn)\n } else {\n this[kEvents].loadend = null\n }\n }\n\n get onerror () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].error\n }\n\n set onerror (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].error) {\n this.removeEventListener('error', this[kEvents].error)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].error = fn\n this.addEventListener('error', fn)\n } else {\n this[kEvents].error = null\n }\n }\n\n get onloadstart () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].loadstart\n }\n\n set onloadstart (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].loadstart) {\n this.removeEventListener('loadstart', this[kEvents].loadstart)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].loadstart = fn\n this.addEventListener('loadstart', fn)\n } else {\n this[kEvents].loadstart = null\n }\n }\n\n get onprogress () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].progress\n }\n\n set onprogress (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].progress) {\n this.removeEventListener('progress', this[kEvents].progress)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].progress = fn\n this.addEventListener('progress', fn)\n } else {\n this[kEvents].progress = null\n }\n }\n\n get onload () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].load\n }\n\n set onload (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].load) {\n this.removeEventListener('load', this[kEvents].load)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].load = fn\n this.addEventListener('load', fn)\n } else {\n this[kEvents].load = null\n }\n }\n\n get onabort () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].abort\n }\n\n set onabort (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].abort) {\n this.removeEventListener('abort', this[kEvents].abort)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].abort = fn\n this.addEventListener('abort', fn)\n } else {\n this[kEvents].abort = null\n }\n }\n}\n\n// https://w3c.github.io/FileAPI/#dom-filereader-empty\nFileReader.EMPTY = FileReader.prototype.EMPTY = 0\n// https://w3c.github.io/FileAPI/#dom-filereader-loading\nFileReader.LOADING = FileReader.prototype.LOADING = 1\n// https://w3c.github.io/FileAPI/#dom-filereader-done\nFileReader.DONE = FileReader.prototype.DONE = 2\n\nObject.defineProperties(FileReader.prototype, {\n EMPTY: staticPropertyDescriptors,\n LOADING: staticPropertyDescriptors,\n DONE: staticPropertyDescriptors,\n readAsArrayBuffer: kEnumerableProperty,\n readAsBinaryString: kEnumerableProperty,\n readAsText: kEnumerableProperty,\n readAsDataURL: kEnumerableProperty,\n abort: kEnumerableProperty,\n readyState: kEnumerableProperty,\n result: kEnumerableProperty,\n error: kEnumerableProperty,\n onloadstart: kEnumerableProperty,\n onprogress: kEnumerableProperty,\n onload: kEnumerableProperty,\n onabort: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onloadend: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'FileReader',\n writable: false,\n enumerable: false,\n configurable: true\n }\n})\n\nObject.defineProperties(FileReader, {\n EMPTY: staticPropertyDescriptors,\n LOADING: staticPropertyDescriptors,\n DONE: staticPropertyDescriptors\n})\n\nmodule.exports = {\n FileReader\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\n\nconst kState = Symbol('ProgressEvent state')\n\n/**\n * @see https://xhr.spec.whatwg.org/#progressevent\n */\nclass ProgressEvent extends Event {\n constructor (type, eventInitDict = {}) {\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})\n\n super(type, eventInitDict)\n\n this[kState] = {\n lengthComputable: eventInitDict.lengthComputable,\n loaded: eventInitDict.loaded,\n total: eventInitDict.total\n }\n }\n\n get lengthComputable () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].lengthComputable\n }\n\n get loaded () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].loaded\n }\n\n get total () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].total\n }\n}\n\nwebidl.converters.ProgressEventInit = webidl.dictionaryConverter([\n {\n key: 'lengthComputable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'loaded',\n converter: webidl.converters['unsigned long long'],\n defaultValue: 0\n },\n {\n key: 'total',\n converter: webidl.converters['unsigned long long'],\n defaultValue: 0\n },\n {\n key: 'bubbles',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'cancelable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'composed',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n])\n\nmodule.exports = {\n ProgressEvent\n}\n","'use strict'\n\nmodule.exports = {\n kState: Symbol('FileReader state'),\n kResult: Symbol('FileReader result'),\n kError: Symbol('FileReader error'),\n kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),\n kEvents: Symbol('FileReader events'),\n kAborted: Symbol('FileReader aborted')\n}\n","'use strict'\n\nconst {\n kState,\n kError,\n kResult,\n kAborted,\n kLastProgressEventFired\n} = require('./symbols')\nconst { ProgressEvent } = require('./progressevent')\nconst { getEncoding } = require('./encoding')\nconst { DOMException } = require('../fetch/constants')\nconst { serializeAMimeType, parseMIMEType } = require('../fetch/dataURL')\nconst { types } = require('util')\nconst { StringDecoder } = require('string_decoder')\nconst { btoa } = require('buffer')\n\n/** @type {PropertyDescriptor} */\nconst staticPropertyDescriptors = {\n enumerable: true,\n writable: false,\n configurable: false\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#readOperation\n * @param {import('./filereader').FileReader} fr\n * @param {import('buffer').Blob} blob\n * @param {string} type\n * @param {string?} encodingName\n */\nfunction readOperation (fr, blob, type, encodingName) {\n // 1. If fr’s state is \"loading\", throw an InvalidStateError\n // DOMException.\n if (fr[kState] === 'loading') {\n throw new DOMException('Invalid state', 'InvalidStateError')\n }\n\n // 2. Set fr’s state to \"loading\".\n fr[kState] = 'loading'\n\n // 3. Set fr’s result to null.\n fr[kResult] = null\n\n // 4. Set fr’s error to null.\n fr[kError] = null\n\n // 5. Let stream be the result of calling get stream on blob.\n /** @type {import('stream/web').ReadableStream} */\n const stream = blob.stream()\n\n // 6. Let reader be the result of getting a reader from stream.\n const reader = stream.getReader()\n\n // 7. Let bytes be an empty byte sequence.\n /** @type {Uint8Array[]} */\n const bytes = []\n\n // 8. Let chunkPromise be the result of reading a chunk from\n // stream with reader.\n let chunkPromise = reader.read()\n\n // 9. Let isFirstChunk be true.\n let isFirstChunk = true\n\n // 10. In parallel, while true:\n // Note: \"In parallel\" just means non-blocking\n // Note 2: readOperation itself cannot be async as double\n // reading the body would then reject the promise, instead\n // of throwing an error.\n ;(async () => {\n while (!fr[kAborted]) {\n // 1. Wait for chunkPromise to be fulfilled or rejected.\n try {\n const { done, value } = await chunkPromise\n\n // 2. If chunkPromise is fulfilled, and isFirstChunk is\n // true, queue a task to fire a progress event called\n // loadstart at fr.\n if (isFirstChunk && !fr[kAborted]) {\n queueMicrotask(() => {\n fireAProgressEvent('loadstart', fr)\n })\n }\n\n // 3. Set isFirstChunk to false.\n isFirstChunk = false\n\n // 4. If chunkPromise is fulfilled with an object whose\n // done property is false and whose value property is\n // a Uint8Array object, run these steps:\n if (!done && types.isUint8Array(value)) {\n // 1. Let bs be the byte sequence represented by the\n // Uint8Array object.\n\n // 2. Append bs to bytes.\n bytes.push(value)\n\n // 3. If roughly 50ms have passed since these steps\n // were last invoked, queue a task to fire a\n // progress event called progress at fr.\n if (\n (\n fr[kLastProgressEventFired] === undefined ||\n Date.now() - fr[kLastProgressEventFired] >= 50\n ) &&\n !fr[kAborted]\n ) {\n fr[kLastProgressEventFired] = Date.now()\n queueMicrotask(() => {\n fireAProgressEvent('progress', fr)\n })\n }\n\n // 4. Set chunkPromise to the result of reading a\n // chunk from stream with reader.\n chunkPromise = reader.read()\n } else if (done) {\n // 5. Otherwise, if chunkPromise is fulfilled with an\n // object whose done property is true, queue a task\n // to run the following steps and abort this algorithm:\n queueMicrotask(() => {\n // 1. Set fr’s state to \"done\".\n fr[kState] = 'done'\n\n // 2. Let result be the result of package data given\n // bytes, type, blob’s type, and encodingName.\n try {\n const result = packageData(bytes, type, blob.type, encodingName)\n\n // 4. Else:\n\n if (fr[kAborted]) {\n return\n }\n\n // 1. Set fr’s result to result.\n fr[kResult] = result\n\n // 2. Fire a progress event called load at the fr.\n fireAProgressEvent('load', fr)\n } catch (error) {\n // 3. If package data threw an exception error:\n\n // 1. Set fr’s error to error.\n fr[kError] = error\n\n // 2. Fire a progress event called error at fr.\n fireAProgressEvent('error', fr)\n }\n\n // 5. If fr’s state is not \"loading\", fire a progress\n // event called loadend at the fr.\n if (fr[kState] !== 'loading') {\n fireAProgressEvent('loadend', fr)\n }\n })\n\n break\n }\n } catch (error) {\n if (fr[kAborted]) {\n return\n }\n\n // 6. Otherwise, if chunkPromise is rejected with an\n // error error, queue a task to run the following\n // steps and abort this algorithm:\n queueMicrotask(() => {\n // 1. Set fr’s state to \"done\".\n fr[kState] = 'done'\n\n // 2. Set fr’s error to error.\n fr[kError] = error\n\n // 3. Fire a progress event called error at fr.\n fireAProgressEvent('error', fr)\n\n // 4. If fr’s state is not \"loading\", fire a progress\n // event called loadend at fr.\n if (fr[kState] !== 'loading') {\n fireAProgressEvent('loadend', fr)\n }\n })\n\n break\n }\n }\n })()\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#fire-a-progress-event\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e The name of the event\n * @param {import('./filereader').FileReader} reader\n */\nfunction fireAProgressEvent (e, reader) {\n // The progress event e does not bubble. e.bubbles must be false\n // The progress event e is NOT cancelable. e.cancelable must be false\n const event = new ProgressEvent(e, {\n bubbles: false,\n cancelable: false\n })\n\n reader.dispatchEvent(event)\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#blob-package-data\n * @param {Uint8Array[]} bytes\n * @param {string} type\n * @param {string?} mimeType\n * @param {string?} encodingName\n */\nfunction packageData (bytes, type, mimeType, encodingName) {\n // 1. A Blob has an associated package data algorithm, given\n // bytes, a type, a optional mimeType, and a optional\n // encodingName, which switches on type and runs the\n // associated steps:\n\n switch (type) {\n case 'DataURL': {\n // 1. Return bytes as a DataURL [RFC2397] subject to\n // the considerations below:\n // * Use mimeType as part of the Data URL if it is\n // available in keeping with the Data URL\n // specification [RFC2397].\n // * If mimeType is not available return a Data URL\n // without a media-type. [RFC2397].\n\n // https://datatracker.ietf.org/doc/html/rfc2397#section-3\n // dataurl := \"data:\" [ mediatype ] [ \";base64\" ] \",\" data\n // mediatype := [ type \"/\" subtype ] *( \";\" parameter )\n // data := *urlchar\n // parameter := attribute \"=\" value\n let dataURL = 'data:'\n\n const parsed = parseMIMEType(mimeType || 'application/octet-stream')\n\n if (parsed !== 'failure') {\n dataURL += serializeAMimeType(parsed)\n }\n\n dataURL += ';base64,'\n\n const decoder = new StringDecoder('latin1')\n\n for (const chunk of bytes) {\n dataURL += btoa(decoder.write(chunk))\n }\n\n dataURL += btoa(decoder.end())\n\n return dataURL\n }\n case 'Text': {\n // 1. Let encoding be failure\n let encoding = 'failure'\n\n // 2. If the encodingName is present, set encoding to the\n // result of getting an encoding from encodingName.\n if (encodingName) {\n encoding = getEncoding(encodingName)\n }\n\n // 3. If encoding is failure, and mimeType is present:\n if (encoding === 'failure' && mimeType) {\n // 1. Let type be the result of parse a MIME type\n // given mimeType.\n const type = parseMIMEType(mimeType)\n\n // 2. If type is not failure, set encoding to the result\n // of getting an encoding from type’s parameters[\"charset\"].\n if (type !== 'failure') {\n encoding = getEncoding(type.parameters.get('charset'))\n }\n }\n\n // 4. If encoding is failure, then set encoding to UTF-8.\n if (encoding === 'failure') {\n encoding = 'UTF-8'\n }\n\n // 5. Decode bytes using fallback encoding encoding, and\n // return the result.\n return decode(bytes, encoding)\n }\n case 'ArrayBuffer': {\n // Return a new ArrayBuffer whose contents are bytes.\n const sequence = combineByteSequences(bytes)\n\n return sequence.buffer\n }\n case 'BinaryString': {\n // Return bytes as a binary string, in which every byte\n // is represented by a code unit of equal value [0..255].\n let binaryString = ''\n\n const decoder = new StringDecoder('latin1')\n\n for (const chunk of bytes) {\n binaryString += decoder.write(chunk)\n }\n\n binaryString += decoder.end()\n\n return binaryString\n }\n }\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#decode\n * @param {Uint8Array[]} ioQueue\n * @param {string} encoding\n */\nfunction decode (ioQueue, encoding) {\n const bytes = combineByteSequences(ioQueue)\n\n // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.\n const BOMEncoding = BOMSniffing(bytes)\n\n let slice = 0\n\n // 2. If BOMEncoding is non-null:\n if (BOMEncoding !== null) {\n // 1. Set encoding to BOMEncoding.\n encoding = BOMEncoding\n\n // 2. Read three bytes from ioQueue, if BOMEncoding is\n // UTF-8; otherwise read two bytes.\n // (Do nothing with those bytes.)\n slice = BOMEncoding === 'UTF-8' ? 3 : 2\n }\n\n // 3. Process a queue with an instance of encoding’s\n // decoder, ioQueue, output, and \"replacement\".\n\n // 4. Return output.\n\n const sliced = bytes.slice(slice)\n return new TextDecoder(encoding).decode(sliced)\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#bom-sniff\n * @param {Uint8Array} ioQueue\n */\nfunction BOMSniffing (ioQueue) {\n // 1. Let BOM be the result of peeking 3 bytes from ioQueue,\n // converted to a byte sequence.\n const [a, b, c] = ioQueue\n\n // 2. For each of the rows in the table below, starting with\n // the first one and going down, if BOM starts with the\n // bytes given in the first column, then return the\n // encoding given in the cell in the second column of that\n // row. Otherwise, return null.\n if (a === 0xEF && b === 0xBB && c === 0xBF) {\n return 'UTF-8'\n } else if (a === 0xFE && b === 0xFF) {\n return 'UTF-16BE'\n } else if (a === 0xFF && b === 0xFE) {\n return 'UTF-16LE'\n }\n\n return null\n}\n\n/**\n * @param {Uint8Array[]} sequences\n */\nfunction combineByteSequences (sequences) {\n const size = sequences.reduce((a, b) => {\n return a + b.byteLength\n }, 0)\n\n let offset = 0\n\n return sequences.reduce((a, b) => {\n a.set(b, offset)\n offset += b.byteLength\n return a\n }, new Uint8Array(size))\n}\n\nmodule.exports = {\n staticPropertyDescriptors,\n readOperation,\n fireAProgressEvent\n}\n","'use strict'\n\n// We include a version number for the Dispatcher API. In case of breaking changes,\n// this version number must be increased to avoid conflicts.\nconst globalDispatcher = Symbol.for('undici.globalDispatcher.1')\nconst { InvalidArgumentError } = require('./core/errors')\nconst Agent = require('./agent')\n\nif (getGlobalDispatcher() === undefined) {\n setGlobalDispatcher(new Agent())\n}\n\nfunction setGlobalDispatcher (agent) {\n if (!agent || typeof agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument agent must implement Agent')\n }\n Object.defineProperty(globalThis, globalDispatcher, {\n value: agent,\n writable: true,\n enumerable: false,\n configurable: false\n })\n}\n\nfunction getGlobalDispatcher () {\n return globalThis[globalDispatcher]\n}\n\nmodule.exports = {\n setGlobalDispatcher,\n getGlobalDispatcher\n}\n","'use strict'\n\nmodule.exports = class DecoratorHandler {\n constructor (handler) {\n this.handler = handler\n }\n\n onConnect (...args) {\n return this.handler.onConnect(...args)\n }\n\n onError (...args) {\n return this.handler.onError(...args)\n }\n\n onUpgrade (...args) {\n return this.handler.onUpgrade(...args)\n }\n\n onHeaders (...args) {\n return this.handler.onHeaders(...args)\n }\n\n onData (...args) {\n return this.handler.onData(...args)\n }\n\n onComplete (...args) {\n return this.handler.onComplete(...args)\n }\n\n onBodySent (...args) {\n return this.handler.onBodySent(...args)\n }\n}\n","'use strict'\n\nconst util = require('../core/util')\nconst { kBodyUsed } = require('../core/symbols')\nconst assert = require('assert')\nconst { InvalidArgumentError } = require('../core/errors')\nconst EE = require('events')\n\nconst redirectableStatusCodes = [300, 301, 302, 303, 307, 308]\n\nconst kBody = Symbol('body')\n\nclass BodyAsyncIterable {\n constructor (body) {\n this[kBody] = body\n this[kBodyUsed] = false\n }\n\n async * [Symbol.asyncIterator] () {\n assert(!this[kBodyUsed], 'disturbed')\n this[kBodyUsed] = true\n yield * this[kBody]\n }\n}\n\nclass RedirectHandler {\n constructor (dispatch, maxRedirections, opts, handler) {\n if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n util.validateHandler(handler, opts.method, opts.upgrade)\n\n this.dispatch = dispatch\n this.location = null\n this.abort = null\n this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy\n this.maxRedirections = maxRedirections\n this.handler = handler\n this.history = []\n\n if (util.isStream(this.opts.body)) {\n // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp\n // so that it can be dispatched again?\n // TODO (fix): Do we need 100-expect support to provide a way to do this properly?\n if (util.bodyLength(this.opts.body) === 0) {\n this.opts.body\n .on('data', function () {\n assert(false)\n })\n }\n\n if (typeof this.opts.body.readableDidRead !== 'boolean') {\n this.opts.body[kBodyUsed] = false\n EE.prototype.on.call(this.opts.body, 'data', function () {\n this[kBodyUsed] = true\n })\n }\n } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {\n // TODO (fix): We can't access ReadableStream internal state\n // to determine whether or not it has been disturbed. This is just\n // a workaround.\n this.opts.body = new BodyAsyncIterable(this.opts.body)\n } else if (\n this.opts.body &&\n typeof this.opts.body !== 'string' &&\n !ArrayBuffer.isView(this.opts.body) &&\n util.isIterable(this.opts.body)\n ) {\n // TODO: Should we allow re-using iterable if !this.opts.idempotent\n // or through some other flag?\n this.opts.body = new BodyAsyncIterable(this.opts.body)\n }\n }\n\n onConnect (abort) {\n this.abort = abort\n this.handler.onConnect(abort, { history: this.history })\n }\n\n onUpgrade (statusCode, headers, socket) {\n this.handler.onUpgrade(statusCode, headers, socket)\n }\n\n onError (error) {\n this.handler.onError(error)\n }\n\n onHeaders (statusCode, headers, resume, statusText) {\n this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)\n ? null\n : parseLocation(statusCode, headers)\n\n if (this.opts.origin) {\n this.history.push(new URL(this.opts.path, this.opts.origin))\n }\n\n if (!this.location) {\n return this.handler.onHeaders(statusCode, headers, resume, statusText)\n }\n\n const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))\n const path = search ? `${pathname}${search}` : pathname\n\n // Remove headers referring to the original URL.\n // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.\n // https://tools.ietf.org/html/rfc7231#section-6.4\n this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)\n this.opts.path = path\n this.opts.origin = origin\n this.opts.maxRedirections = 0\n this.opts.query = null\n\n // https://tools.ietf.org/html/rfc7231#section-6.4.4\n // In case of HTTP 303, always replace method to be either HEAD or GET\n if (statusCode === 303 && this.opts.method !== 'HEAD') {\n this.opts.method = 'GET'\n this.opts.body = null\n }\n }\n\n onData (chunk) {\n if (this.location) {\n /*\n https://tools.ietf.org/html/rfc7231#section-6.4\n\n TLDR: undici always ignores 3xx response bodies.\n\n Redirection is used to serve the requested resource from another URL, so it is assumes that\n no body is generated (and thus can be ignored). Even though generating a body is not prohibited.\n\n For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually\n (which means it's optional and not mandated) contain just an hyperlink to the value of\n the Location response header, so the body can be ignored safely.\n\n For status 300, which is \"Multiple Choices\", the spec mentions both generating a Location\n response header AND a response body with the other possible location to follow.\n Since the spec explicitily chooses not to specify a format for such body and leave it to\n servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.\n */\n } else {\n return this.handler.onData(chunk)\n }\n }\n\n onComplete (trailers) {\n if (this.location) {\n /*\n https://tools.ietf.org/html/rfc7231#section-6.4\n\n TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections\n and neither are useful if present.\n\n See comment on onData method above for more detailed informations.\n */\n\n this.location = null\n this.abort = null\n\n this.dispatch(this.opts, this)\n } else {\n this.handler.onComplete(trailers)\n }\n }\n\n onBodySent (chunk) {\n if (this.handler.onBodySent) {\n this.handler.onBodySent(chunk)\n }\n }\n}\n\nfunction parseLocation (statusCode, headers) {\n if (redirectableStatusCodes.indexOf(statusCode) === -1) {\n return null\n }\n\n for (let i = 0; i < headers.length; i += 2) {\n if (headers[i].toString().toLowerCase() === 'location') {\n return headers[i + 1]\n }\n }\n}\n\n// https://tools.ietf.org/html/rfc7231#section-6.4.4\nfunction shouldRemoveHeader (header, removeContent, unknownOrigin) {\n if (header.length === 4) {\n return util.headerNameToString(header) === 'host'\n }\n if (removeContent && util.headerNameToString(header).startsWith('content-')) {\n return true\n }\n if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {\n const name = util.headerNameToString(header)\n return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'\n }\n return false\n}\n\n// https://tools.ietf.org/html/rfc7231#section-6.4\nfunction cleanRequestHeaders (headers, removeContent, unknownOrigin) {\n const ret = []\n if (Array.isArray(headers)) {\n for (let i = 0; i < headers.length; i += 2) {\n if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {\n ret.push(headers[i], headers[i + 1])\n }\n }\n } else if (headers && typeof headers === 'object') {\n for (const key of Object.keys(headers)) {\n if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {\n ret.push(key, headers[key])\n }\n }\n } else {\n assert(headers == null, 'headers must be an object or an array')\n }\n return ret\n}\n\nmodule.exports = RedirectHandler\n","const assert = require('assert')\n\nconst { kRetryHandlerDefaultRetry } = require('../core/symbols')\nconst { RequestRetryError } = require('../core/errors')\nconst { isDisturbed, parseHeaders, parseRangeHeader } = require('../core/util')\n\nfunction calculateRetryAfterHeader (retryAfter) {\n const current = Date.now()\n const diff = new Date(retryAfter).getTime() - current\n\n return diff\n}\n\nclass RetryHandler {\n constructor (opts, handlers) {\n const { retryOptions, ...dispatchOpts } = opts\n const {\n // Retry scoped\n retry: retryFn,\n maxRetries,\n maxTimeout,\n minTimeout,\n timeoutFactor,\n // Response scoped\n methods,\n errorCodes,\n retryAfter,\n statusCodes\n } = retryOptions ?? {}\n\n this.dispatch = handlers.dispatch\n this.handler = handlers.handler\n this.opts = dispatchOpts\n this.abort = null\n this.aborted = false\n this.retryOpts = {\n retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],\n retryAfter: retryAfter ?? true,\n maxTimeout: maxTimeout ?? 30 * 1000, // 30s,\n timeout: minTimeout ?? 500, // .5s\n timeoutFactor: timeoutFactor ?? 2,\n maxRetries: maxRetries ?? 5,\n // What errors we should retry\n methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],\n // Indicates which errors to retry\n statusCodes: statusCodes ?? [500, 502, 503, 504, 429],\n // List of errors to retry\n errorCodes: errorCodes ?? [\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ENETDOWN',\n 'ENETUNREACH',\n 'EHOSTDOWN',\n 'EHOSTUNREACH',\n 'EPIPE'\n ]\n }\n\n this.retryCount = 0\n this.start = 0\n this.end = null\n this.etag = null\n this.resume = null\n\n // Handle possible onConnect duplication\n this.handler.onConnect(reason => {\n this.aborted = true\n if (this.abort) {\n this.abort(reason)\n } else {\n this.reason = reason\n }\n })\n }\n\n onRequestSent () {\n if (this.handler.onRequestSent) {\n this.handler.onRequestSent()\n }\n }\n\n onUpgrade (statusCode, headers, socket) {\n if (this.handler.onUpgrade) {\n this.handler.onUpgrade(statusCode, headers, socket)\n }\n }\n\n onConnect (abort) {\n if (this.aborted) {\n abort(this.reason)\n } else {\n this.abort = abort\n }\n }\n\n onBodySent (chunk) {\n if (this.handler.onBodySent) return this.handler.onBodySent(chunk)\n }\n\n static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {\n const { statusCode, code, headers } = err\n const { method, retryOptions } = opts\n const {\n maxRetries,\n timeout,\n maxTimeout,\n timeoutFactor,\n statusCodes,\n errorCodes,\n methods\n } = retryOptions\n let { counter, currentTimeout } = state\n\n currentTimeout =\n currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout\n\n // Any code that is not a Undici's originated and allowed to retry\n if (\n code &&\n code !== 'UND_ERR_REQ_RETRY' &&\n code !== 'UND_ERR_SOCKET' &&\n !errorCodes.includes(code)\n ) {\n cb(err)\n return\n }\n\n // If a set of method are provided and the current method is not in the list\n if (Array.isArray(methods) && !methods.includes(method)) {\n cb(err)\n return\n }\n\n // If a set of status code are provided and the current status code is not in the list\n if (\n statusCode != null &&\n Array.isArray(statusCodes) &&\n !statusCodes.includes(statusCode)\n ) {\n cb(err)\n return\n }\n\n // If we reached the max number of retries\n if (counter > maxRetries) {\n cb(err)\n return\n }\n\n let retryAfterHeader = headers != null && headers['retry-after']\n if (retryAfterHeader) {\n retryAfterHeader = Number(retryAfterHeader)\n retryAfterHeader = isNaN(retryAfterHeader)\n ? calculateRetryAfterHeader(retryAfterHeader)\n : retryAfterHeader * 1e3 // Retry-After is in seconds\n }\n\n const retryTimeout =\n retryAfterHeader > 0\n ? Math.min(retryAfterHeader, maxTimeout)\n : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)\n\n state.currentTimeout = retryTimeout\n\n setTimeout(() => cb(null), retryTimeout)\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const headers = parseHeaders(rawHeaders)\n\n this.retryCount += 1\n\n if (statusCode >= 300) {\n this.abort(\n new RequestRetryError('Request failed', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n // Checkpoint for resume from where we left it\n if (this.resume != null) {\n this.resume = null\n\n if (statusCode !== 206) {\n return true\n }\n\n const contentRange = parseRangeHeader(headers['content-range'])\n // If no content range\n if (!contentRange) {\n this.abort(\n new RequestRetryError('Content-Range mismatch', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n // Let's start with a weak etag check\n if (this.etag != null && this.etag !== headers.etag) {\n this.abort(\n new RequestRetryError('ETag mismatch', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n const { start, size, end = size } = contentRange\n\n assert(this.start === start, 'content-range mismatch')\n assert(this.end == null || this.end === end, 'content-range mismatch')\n\n this.resume = resume\n return true\n }\n\n if (this.end == null) {\n if (statusCode === 206) {\n // First time we receive 206\n const range = parseRangeHeader(headers['content-range'])\n\n if (range == null) {\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n const { start, size, end = size } = range\n\n assert(\n start != null && Number.isFinite(start) && this.start !== start,\n 'content-range mismatch'\n )\n assert(Number.isFinite(start))\n assert(\n end != null && Number.isFinite(end) && this.end !== end,\n 'invalid content-length'\n )\n\n this.start = start\n this.end = end\n }\n\n // We make our best to checkpoint the body for further range headers\n if (this.end == null) {\n const contentLength = headers['content-length']\n this.end = contentLength != null ? Number(contentLength) : null\n }\n\n assert(Number.isFinite(this.start))\n assert(\n this.end == null || Number.isFinite(this.end),\n 'invalid content-length'\n )\n\n this.resume = resume\n this.etag = headers.etag != null ? headers.etag : null\n\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n const err = new RequestRetryError('Request failed', statusCode, {\n headers,\n count: this.retryCount\n })\n\n this.abort(err)\n\n return false\n }\n\n onData (chunk) {\n this.start += chunk.length\n\n return this.handler.onData(chunk)\n }\n\n onComplete (rawTrailers) {\n this.retryCount = 0\n return this.handler.onComplete(rawTrailers)\n }\n\n onError (err) {\n if (this.aborted || isDisturbed(this.opts.body)) {\n return this.handler.onError(err)\n }\n\n this.retryOpts.retry(\n err,\n {\n state: { counter: this.retryCount++, currentTimeout: this.retryAfter },\n opts: { retryOptions: this.retryOpts, ...this.opts }\n },\n onRetry.bind(this)\n )\n\n function onRetry (err) {\n if (err != null || this.aborted || isDisturbed(this.opts.body)) {\n return this.handler.onError(err)\n }\n\n if (this.start !== 0) {\n this.opts = {\n ...this.opts,\n headers: {\n ...this.opts.headers,\n range: `bytes=${this.start}-${this.end ?? ''}`\n }\n }\n }\n\n try {\n this.dispatch(this.opts, this)\n } catch (err) {\n this.handler.onError(err)\n }\n }\n }\n}\n\nmodule.exports = RetryHandler\n","'use strict'\n\nconst RedirectHandler = require('../handler/RedirectHandler')\n\nfunction createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {\n return (dispatch) => {\n return function Intercept (opts, handler) {\n const { maxRedirections = defaultMaxRedirections } = opts\n\n if (!maxRedirections) {\n return dispatch(opts, handler)\n }\n\n const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)\n opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.\n return dispatch(opts, redirectHandler)\n }\n }\n}\n\nmodule.exports = createRedirectInterceptor\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;\nconst utils_1 = require(\"./utils\");\n// C headers\nvar ERROR;\n(function (ERROR) {\n ERROR[ERROR[\"OK\"] = 0] = \"OK\";\n ERROR[ERROR[\"INTERNAL\"] = 1] = \"INTERNAL\";\n ERROR[ERROR[\"STRICT\"] = 2] = \"STRICT\";\n ERROR[ERROR[\"LF_EXPECTED\"] = 3] = \"LF_EXPECTED\";\n ERROR[ERROR[\"UNEXPECTED_CONTENT_LENGTH\"] = 4] = \"UNEXPECTED_CONTENT_LENGTH\";\n ERROR[ERROR[\"CLOSED_CONNECTION\"] = 5] = \"CLOSED_CONNECTION\";\n ERROR[ERROR[\"INVALID_METHOD\"] = 6] = \"INVALID_METHOD\";\n ERROR[ERROR[\"INVALID_URL\"] = 7] = \"INVALID_URL\";\n ERROR[ERROR[\"INVALID_CONSTANT\"] = 8] = \"INVALID_CONSTANT\";\n ERROR[ERROR[\"INVALID_VERSION\"] = 9] = \"INVALID_VERSION\";\n ERROR[ERROR[\"INVALID_HEADER_TOKEN\"] = 10] = \"INVALID_HEADER_TOKEN\";\n ERROR[ERROR[\"INVALID_CONTENT_LENGTH\"] = 11] = \"INVALID_CONTENT_LENGTH\";\n ERROR[ERROR[\"INVALID_CHUNK_SIZE\"] = 12] = \"INVALID_CHUNK_SIZE\";\n ERROR[ERROR[\"INVALID_STATUS\"] = 13] = \"INVALID_STATUS\";\n ERROR[ERROR[\"INVALID_EOF_STATE\"] = 14] = \"INVALID_EOF_STATE\";\n ERROR[ERROR[\"INVALID_TRANSFER_ENCODING\"] = 15] = \"INVALID_TRANSFER_ENCODING\";\n ERROR[ERROR[\"CB_MESSAGE_BEGIN\"] = 16] = \"CB_MESSAGE_BEGIN\";\n ERROR[ERROR[\"CB_HEADERS_COMPLETE\"] = 17] = \"CB_HEADERS_COMPLETE\";\n ERROR[ERROR[\"CB_MESSAGE_COMPLETE\"] = 18] = \"CB_MESSAGE_COMPLETE\";\n ERROR[ERROR[\"CB_CHUNK_HEADER\"] = 19] = \"CB_CHUNK_HEADER\";\n ERROR[ERROR[\"CB_CHUNK_COMPLETE\"] = 20] = \"CB_CHUNK_COMPLETE\";\n ERROR[ERROR[\"PAUSED\"] = 21] = \"PAUSED\";\n ERROR[ERROR[\"PAUSED_UPGRADE\"] = 22] = \"PAUSED_UPGRADE\";\n ERROR[ERROR[\"PAUSED_H2_UPGRADE\"] = 23] = \"PAUSED_H2_UPGRADE\";\n ERROR[ERROR[\"USER\"] = 24] = \"USER\";\n})(ERROR = exports.ERROR || (exports.ERROR = {}));\nvar TYPE;\n(function (TYPE) {\n TYPE[TYPE[\"BOTH\"] = 0] = \"BOTH\";\n TYPE[TYPE[\"REQUEST\"] = 1] = \"REQUEST\";\n TYPE[TYPE[\"RESPONSE\"] = 2] = \"RESPONSE\";\n})(TYPE = exports.TYPE || (exports.TYPE = {}));\nvar FLAGS;\n(function (FLAGS) {\n FLAGS[FLAGS[\"CONNECTION_KEEP_ALIVE\"] = 1] = \"CONNECTION_KEEP_ALIVE\";\n FLAGS[FLAGS[\"CONNECTION_CLOSE\"] = 2] = \"CONNECTION_CLOSE\";\n FLAGS[FLAGS[\"CONNECTION_UPGRADE\"] = 4] = \"CONNECTION_UPGRADE\";\n FLAGS[FLAGS[\"CHUNKED\"] = 8] = \"CHUNKED\";\n FLAGS[FLAGS[\"UPGRADE\"] = 16] = \"UPGRADE\";\n FLAGS[FLAGS[\"CONTENT_LENGTH\"] = 32] = \"CONTENT_LENGTH\";\n FLAGS[FLAGS[\"SKIPBODY\"] = 64] = \"SKIPBODY\";\n FLAGS[FLAGS[\"TRAILING\"] = 128] = \"TRAILING\";\n // 1 << 8 is unused\n FLAGS[FLAGS[\"TRANSFER_ENCODING\"] = 512] = \"TRANSFER_ENCODING\";\n})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));\nvar LENIENT_FLAGS;\n(function (LENIENT_FLAGS) {\n LENIENT_FLAGS[LENIENT_FLAGS[\"HEADERS\"] = 1] = \"HEADERS\";\n LENIENT_FLAGS[LENIENT_FLAGS[\"CHUNKED_LENGTH\"] = 2] = \"CHUNKED_LENGTH\";\n LENIENT_FLAGS[LENIENT_FLAGS[\"KEEP_ALIVE\"] = 4] = \"KEEP_ALIVE\";\n})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));\nvar METHODS;\n(function (METHODS) {\n METHODS[METHODS[\"DELETE\"] = 0] = \"DELETE\";\n METHODS[METHODS[\"GET\"] = 1] = \"GET\";\n METHODS[METHODS[\"HEAD\"] = 2] = \"HEAD\";\n METHODS[METHODS[\"POST\"] = 3] = \"POST\";\n METHODS[METHODS[\"PUT\"] = 4] = \"PUT\";\n /* pathological */\n METHODS[METHODS[\"CONNECT\"] = 5] = \"CONNECT\";\n METHODS[METHODS[\"OPTIONS\"] = 6] = \"OPTIONS\";\n METHODS[METHODS[\"TRACE\"] = 7] = \"TRACE\";\n /* WebDAV */\n METHODS[METHODS[\"COPY\"] = 8] = \"COPY\";\n METHODS[METHODS[\"LOCK\"] = 9] = \"LOCK\";\n METHODS[METHODS[\"MKCOL\"] = 10] = \"MKCOL\";\n METHODS[METHODS[\"MOVE\"] = 11] = \"MOVE\";\n METHODS[METHODS[\"PROPFIND\"] = 12] = \"PROPFIND\";\n METHODS[METHODS[\"PROPPATCH\"] = 13] = \"PROPPATCH\";\n METHODS[METHODS[\"SEARCH\"] = 14] = \"SEARCH\";\n METHODS[METHODS[\"UNLOCK\"] = 15] = \"UNLOCK\";\n METHODS[METHODS[\"BIND\"] = 16] = \"BIND\";\n METHODS[METHODS[\"REBIND\"] = 17] = \"REBIND\";\n METHODS[METHODS[\"UNBIND\"] = 18] = \"UNBIND\";\n METHODS[METHODS[\"ACL\"] = 19] = \"ACL\";\n /* subversion */\n METHODS[METHODS[\"REPORT\"] = 20] = \"REPORT\";\n METHODS[METHODS[\"MKACTIVITY\"] = 21] = \"MKACTIVITY\";\n METHODS[METHODS[\"CHECKOUT\"] = 22] = \"CHECKOUT\";\n METHODS[METHODS[\"MERGE\"] = 23] = \"MERGE\";\n /* upnp */\n METHODS[METHODS[\"M-SEARCH\"] = 24] = \"M-SEARCH\";\n METHODS[METHODS[\"NOTIFY\"] = 25] = \"NOTIFY\";\n METHODS[METHODS[\"SUBSCRIBE\"] = 26] = \"SUBSCRIBE\";\n METHODS[METHODS[\"UNSUBSCRIBE\"] = 27] = \"UNSUBSCRIBE\";\n /* RFC-5789 */\n METHODS[METHODS[\"PATCH\"] = 28] = \"PATCH\";\n METHODS[METHODS[\"PURGE\"] = 29] = \"PURGE\";\n /* CalDAV */\n METHODS[METHODS[\"MKCALENDAR\"] = 30] = \"MKCALENDAR\";\n /* RFC-2068, section 19.6.1.2 */\n METHODS[METHODS[\"LINK\"] = 31] = \"LINK\";\n METHODS[METHODS[\"UNLINK\"] = 32] = \"UNLINK\";\n /* icecast */\n METHODS[METHODS[\"SOURCE\"] = 33] = \"SOURCE\";\n /* RFC-7540, section 11.6 */\n METHODS[METHODS[\"PRI\"] = 34] = \"PRI\";\n /* RFC-2326 RTSP */\n METHODS[METHODS[\"DESCRIBE\"] = 35] = \"DESCRIBE\";\n METHODS[METHODS[\"ANNOUNCE\"] = 36] = \"ANNOUNCE\";\n METHODS[METHODS[\"SETUP\"] = 37] = \"SETUP\";\n METHODS[METHODS[\"PLAY\"] = 38] = \"PLAY\";\n METHODS[METHODS[\"PAUSE\"] = 39] = \"PAUSE\";\n METHODS[METHODS[\"TEARDOWN\"] = 40] = \"TEARDOWN\";\n METHODS[METHODS[\"GET_PARAMETER\"] = 41] = \"GET_PARAMETER\";\n METHODS[METHODS[\"SET_PARAMETER\"] = 42] = \"SET_PARAMETER\";\n METHODS[METHODS[\"REDIRECT\"] = 43] = \"REDIRECT\";\n METHODS[METHODS[\"RECORD\"] = 44] = \"RECORD\";\n /* RAOP */\n METHODS[METHODS[\"FLUSH\"] = 45] = \"FLUSH\";\n})(METHODS = exports.METHODS || (exports.METHODS = {}));\nexports.METHODS_HTTP = [\n METHODS.DELETE,\n METHODS.GET,\n METHODS.HEAD,\n METHODS.POST,\n METHODS.PUT,\n METHODS.CONNECT,\n METHODS.OPTIONS,\n METHODS.TRACE,\n METHODS.COPY,\n METHODS.LOCK,\n METHODS.MKCOL,\n METHODS.MOVE,\n METHODS.PROPFIND,\n METHODS.PROPPATCH,\n METHODS.SEARCH,\n METHODS.UNLOCK,\n METHODS.BIND,\n METHODS.REBIND,\n METHODS.UNBIND,\n METHODS.ACL,\n METHODS.REPORT,\n METHODS.MKACTIVITY,\n METHODS.CHECKOUT,\n METHODS.MERGE,\n METHODS['M-SEARCH'],\n METHODS.NOTIFY,\n METHODS.SUBSCRIBE,\n METHODS.UNSUBSCRIBE,\n METHODS.PATCH,\n METHODS.PURGE,\n METHODS.MKCALENDAR,\n METHODS.LINK,\n METHODS.UNLINK,\n METHODS.PRI,\n // TODO(indutny): should we allow it with HTTP?\n METHODS.SOURCE,\n];\nexports.METHODS_ICE = [\n METHODS.SOURCE,\n];\nexports.METHODS_RTSP = [\n METHODS.OPTIONS,\n METHODS.DESCRIBE,\n METHODS.ANNOUNCE,\n METHODS.SETUP,\n METHODS.PLAY,\n METHODS.PAUSE,\n METHODS.TEARDOWN,\n METHODS.GET_PARAMETER,\n METHODS.SET_PARAMETER,\n METHODS.REDIRECT,\n METHODS.RECORD,\n METHODS.FLUSH,\n // For AirPlay\n METHODS.GET,\n METHODS.POST,\n];\nexports.METHOD_MAP = utils_1.enumToMap(METHODS);\nexports.H_METHOD_MAP = {};\nObject.keys(exports.METHOD_MAP).forEach((key) => {\n if (/^H/.test(key)) {\n exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];\n }\n});\nvar FINISH;\n(function (FINISH) {\n FINISH[FINISH[\"SAFE\"] = 0] = \"SAFE\";\n FINISH[FINISH[\"SAFE_WITH_CB\"] = 1] = \"SAFE_WITH_CB\";\n FINISH[FINISH[\"UNSAFE\"] = 2] = \"UNSAFE\";\n})(FINISH = exports.FINISH || (exports.FINISH = {}));\nexports.ALPHA = [];\nfor (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {\n // Upper case\n exports.ALPHA.push(String.fromCharCode(i));\n // Lower case\n exports.ALPHA.push(String.fromCharCode(i + 0x20));\n}\nexports.NUM_MAP = {\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,\n 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n};\nexports.HEX_MAP = {\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,\n 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,\n a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,\n};\nexports.NUM = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n];\nexports.ALPHANUM = exports.ALPHA.concat(exports.NUM);\nexports.MARK = ['-', '_', '.', '!', '~', '*', '\\'', '(', ')'];\nexports.USERINFO_CHARS = exports.ALPHANUM\n .concat(exports.MARK)\n .concat(['%', ';', ':', '&', '=', '+', '$', ',']);\n// TODO(indutny): use RFC\nexports.STRICT_URL_CHAR = [\n '!', '\"', '$', '%', '&', '\\'',\n '(', ')', '*', '+', ',', '-', '.', '/',\n ':', ';', '<', '=', '>',\n '@', '[', '\\\\', ']', '^', '_',\n '`',\n '{', '|', '}', '~',\n].concat(exports.ALPHANUM);\nexports.URL_CHAR = exports.STRICT_URL_CHAR\n .concat(['\\t', '\\f']);\n// All characters with 0x80 bit set to 1\nfor (let i = 0x80; i <= 0xff; i++) {\n exports.URL_CHAR.push(i);\n}\nexports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);\n/* Tokens as defined by rfc 2616. Also lowercases them.\n * token = 1*\n * separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n * | \",\" | \";\" | \":\" | \"\\\" | <\">\n * | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n * | \"{\" | \"}\" | SP | HT\n */\nexports.STRICT_TOKEN = [\n '!', '#', '$', '%', '&', '\\'',\n '*', '+', '-', '.',\n '^', '_', '`',\n '|', '~',\n].concat(exports.ALPHANUM);\nexports.TOKEN = exports.STRICT_TOKEN.concat([' ']);\n/*\n * Verify that a char is a valid visible (printable) US-ASCII\n * character or %x80-FF\n */\nexports.HEADER_CHARS = ['\\t'];\nfor (let i = 32; i <= 255; i++) {\n if (i !== 127) {\n exports.HEADER_CHARS.push(i);\n }\n}\n// ',' = \\x44\nexports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);\nexports.MAJOR = exports.NUM_MAP;\nexports.MINOR = exports.MAJOR;\nvar HEADER_STATE;\n(function (HEADER_STATE) {\n HEADER_STATE[HEADER_STATE[\"GENERAL\"] = 0] = \"GENERAL\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION\"] = 1] = \"CONNECTION\";\n HEADER_STATE[HEADER_STATE[\"CONTENT_LENGTH\"] = 2] = \"CONTENT_LENGTH\";\n HEADER_STATE[HEADER_STATE[\"TRANSFER_ENCODING\"] = 3] = \"TRANSFER_ENCODING\";\n HEADER_STATE[HEADER_STATE[\"UPGRADE\"] = 4] = \"UPGRADE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_KEEP_ALIVE\"] = 5] = \"CONNECTION_KEEP_ALIVE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_CLOSE\"] = 6] = \"CONNECTION_CLOSE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_UPGRADE\"] = 7] = \"CONNECTION_UPGRADE\";\n HEADER_STATE[HEADER_STATE[\"TRANSFER_ENCODING_CHUNKED\"] = 8] = \"TRANSFER_ENCODING_CHUNKED\";\n})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));\nexports.SPECIAL_HEADERS = {\n 'connection': HEADER_STATE.CONNECTION,\n 'content-length': HEADER_STATE.CONTENT_LENGTH,\n 'proxy-connection': HEADER_STATE.CONNECTION,\n 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,\n 'upgrade': HEADER_STATE.UPGRADE,\n};\n//# sourceMappingURL=constants.js.map","module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkBigGLAYwBjQGOAY8BkAGRAZIBkwGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwHLAcoBuAHJAbkByAG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAQDcAQtBACEQDMYBC0EOIRAMxQELQQ0hEAzEAQtBDyEQDMMBC0EQIRAMwgELQRMhEAzBAQtBFCEQDMABC0EVIRAMvwELQRYhEAy+AQtBFyEQDL0BC0EYIRAMvAELQRkhEAy7AQtBGiEQDLoBC0EbIRAMuQELQRwhEAy4AQtBCCEQDLcBC0EdIRAMtgELQSAhEAy1AQtBHyEQDLQBC0EHIRAMswELQSEhEAyyAQtBIiEQDLEBC0EeIRAMsAELQSMhEAyvAQtBEiEQDK4BC0ERIRAMrQELQSQhEAysAQtBJSEQDKsBC0EmIRAMqgELQSchEAypAQtBwwEhEAyoAQtBKSEQDKcBC0ErIRAMpgELQSwhEAylAQtBLSEQDKQBC0EuIRAMowELQS8hEAyiAQtBxAEhEAyhAQtBMCEQDKABC0E0IRAMnwELQQwhEAyeAQtBMSEQDJ0BC0EyIRAMnAELQTMhEAybAQtBOSEQDJoBC0E1IRAMmQELQcUBIRAMmAELQQshEAyXAQtBOiEQDJYBC0E2IRAMlQELQQohEAyUAQtBNyEQDJMBC0E4IRAMkgELQTwhEAyRAQtBOyEQDJABC0E9IRAMjwELQQkhEAyOAQtBKCEQDI0BC0E+IRAMjAELQT8hEAyLAQtBwAAhEAyKAQtBwQAhEAyJAQtBwgAhEAyIAQtBwwAhEAyHAQtBxAAhEAyGAQtBxQAhEAyFAQtBxgAhEAyEAQtBKiEQDIMBC0HHACEQDIIBC0HIACEQDIEBC0HJACEQDIABC0HKACEQDH8LQcsAIRAMfgtBzQAhEAx9C0HMACEQDHwLQc4AIRAMewtBzwAhEAx6C0HQACEQDHkLQdEAIRAMeAtB0gAhEAx3C0HTACEQDHYLQdQAIRAMdQtB1gAhEAx0C0HVACEQDHMLQQYhEAxyC0HXACEQDHELQQUhEAxwC0HYACEQDG8LQQQhEAxuC0HZACEQDG0LQdoAIRAMbAtB2wAhEAxrC0HcACEQDGoLQQMhEAxpC0HdACEQDGgLQd4AIRAMZwtB3wAhEAxmC0HhACEQDGULQeAAIRAMZAtB4gAhEAxjC0HjACEQDGILQQIhEAxhC0HkACEQDGALQeUAIRAMXwtB5gAhEAxeC0HnACEQDF0LQegAIRAMXAtB6QAhEAxbC0HqACEQDFoLQesAIRAMWQtB7AAhEAxYC0HtACEQDFcLQe4AIRAMVgtB7wAhEAxVC0HwACEQDFQLQfEAIRAMUwtB8gAhEAxSC0HzACEQDFELQfQAIRAMUAtB9QAhEAxPC0H2ACEQDE4LQfcAIRAMTQtB+AAhEAxMC0H5ACEQDEsLQfoAIRAMSgtB+wAhEAxJC0H8ACEQDEgLQf0AIRAMRwtB/gAhEAxGC0H/ACEQDEULQYABIRAMRAtBgQEhEAxDC0GCASEQDEILQYMBIRAMQQtBhAEhEAxAC0GFASEQDD8LQYYBIRAMPgtBhwEhEAw9C0GIASEQDDwLQYkBIRAMOwtBigEhEAw6C0GLASEQDDkLQYwBIRAMOAtBjQEhEAw3C0GOASEQDDYLQY8BIRAMNQtBkAEhEAw0C0GRASEQDDMLQZIBIRAMMgtBkwEhEAwxC0GUASEQDDALQZUBIRAMLwtBlgEhEAwuC0GXASEQDC0LQZgBIRAMLAtBmQEhEAwrC0GaASEQDCoLQZsBIRAMKQtBnAEhEAwoC0GdASEQDCcLQZ4BIRAMJgtBnwEhEAwlC0GgASEQDCQLQaEBIRAMIwtBogEhEAwiC0GjASEQDCELQaQBIRAMIAtBpQEhEAwfC0GmASEQDB4LQacBIRAMHQtBqAEhEAwcC0GpASEQDBsLQaoBIRAMGgtBqwEhEAwZC0GsASEQDBgLQa0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAdUB1gHXAdgB2QHaAdsB3AHdAd4B4AHhAeIB4wHkAeUB5gHnAegB6QHqAesB7AHtAe4B7wHwAfEB8gHzAZkCpAKwAv4C/gILIAEiBCACRw3zAUHdASEQDP8DCyABIhAgAkcN3QFBwwEhEAz+AwsgASIBIAJHDZABQfcAIRAM/QMLIAEiASACRw2GAUHvACEQDPwDCyABIgEgAkcNf0HqACEQDPsDCyABIgEgAkcNe0HoACEQDPoDCyABIgEgAkcNeEHmACEQDPkDCyABIgEgAkcNGkEYIRAM+AMLIAEiASACRw0UQRIhEAz3AwsgASIBIAJHDVlBxQAhEAz2AwsgASIBIAJHDUpBPyEQDPUDCyABIgEgAkcNSEE8IRAM9AMLIAEiASACRw1BQTEhEAzzAwsgAC0ALkEBRg3rAwyHAgsgACABIgEgAhDAgICAAEEBRw3mASAAQgA3AyAM5wELIAAgASIBIAIQtICAgAAiEA3nASABIQEM9QILAkAgASIBIAJHDQBBBiEQDPADCyAAIAFBAWoiASACELuAgIAAIhAN6AEgASEBDDELIABCADcDIEESIRAM1QMLIAEiECACRw0rQR0hEAztAwsCQCABIgEgAkYNACABQQFqIQFBECEQDNQDC0EHIRAM7AMLIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN5QFBCCEQDOsDCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEUIRAM0gMLQQkhEAzqAwsgASEBIAApAyBQDeQBIAEhAQzyAgsCQCABIgEgAkcNAEELIRAM6QMLIAAgAUEBaiIBIAIQtoCAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3mASABIQEMDQsgACABIgEgAhC6gICAACIQDecBIAEhAQzwAgsCQCABIgEgAkcNAEEPIRAM5QMLIAEtAAAiEEE7Rg0IIBBBDUcN6AEgAUEBaiEBDO8CCyAAIAEiASACELqAgIAAIhAN6AEgASEBDPICCwNAAkAgAS0AAEHwtYCAAGotAAAiEEEBRg0AIBBBAkcN6wEgACgCBCEQIABBADYCBCAAIBAgAUEBaiIBELmAgIAAIhAN6gEgASEBDPQCCyABQQFqIgEgAkcNAAtBEiEQDOIDCyAAIAEiASACELqAgIAAIhAN6QEgASEBDAoLIAEiASACRw0GQRshEAzgAwsCQCABIgEgAkcNAEEWIRAM4AMLIABBioCAgAA2AgggACABNgIEIAAgASACELiAgIAAIhAN6gEgASEBQSAhEAzGAwsCQCABIgEgAkYNAANAAkAgAS0AAEHwt4CAAGotAAAiEEECRg0AAkAgEEF/ag4E5QHsAQDrAewBCyABQQFqIQFBCCEQDMgDCyABQQFqIgEgAkcNAAtBFSEQDN8DC0EVIRAM3gMLA0ACQCABLQAAQfC5gIAAai0AACIQQQJGDQAgEEF/ag4E3gHsAeAB6wHsAQsgAUEBaiIBIAJHDQALQRghEAzdAwsCQCABIgEgAkYNACAAQYuAgIAANgIIIAAgATYCBCABIQFBByEQDMQDC0EZIRAM3AMLIAFBAWohAQwCCwJAIAEiFCACRw0AQRohEAzbAwsgFCEBAkAgFC0AAEFzag4U3QLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gIA7gILQQAhECAAQQA2AhwgAEGvi4CAADYCECAAQQI2AgwgACAUQQFqNgIUDNoDCwJAIAEtAAAiEEE7Rg0AIBBBDUcN6AEgAUEBaiEBDOUCCyABQQFqIQELQSIhEAy/AwsCQCABIhAgAkcNAEEcIRAM2AMLQgAhESAQIQEgEC0AAEFQag435wHmAQECAwQFBgcIAAAAAAAAAAkKCwwNDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADxAREhMUAAtBHiEQDL0DC0ICIREM5QELQgMhEQzkAQtCBCERDOMBC0IFIREM4gELQgYhEQzhAQtCByERDOABC0IIIREM3wELQgkhEQzeAQtCCiERDN0BC0ILIREM3AELQgwhEQzbAQtCDSERDNoBC0IOIREM2QELQg8hEQzYAQtCCiERDNcBC0ILIREM1gELQgwhEQzVAQtCDSERDNQBC0IOIREM0wELQg8hEQzSAQtCACERAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQLQAAQVBqDjflAeQBAAECAwQFBgfmAeYB5gHmAeYB5gHmAQgJCgsMDeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gEODxAREhPmAQtCAiERDOQBC0IDIREM4wELQgQhEQziAQtCBSERDOEBC0IGIREM4AELQgchEQzfAQtCCCERDN4BC0IJIREM3QELQgohEQzcAQtCCyERDNsBC0IMIREM2gELQg0hEQzZAQtCDiERDNgBC0IPIREM1wELQgohEQzWAQtCCyERDNUBC0IMIREM1AELQg0hEQzTAQtCDiERDNIBC0IPIREM0QELIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN0gFBHyEQDMADCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEkIRAMpwMLQSAhEAy/AwsgACABIhAgAhC+gICAAEF/ag4FtgEAxQIB0QHSAQtBESEQDKQDCyAAQQE6AC8gECEBDLsDCyABIgEgAkcN0gFBJCEQDLsDCyABIg0gAkcNHkHGACEQDLoDCyAAIAEiASACELKAgIAAIhAN1AEgASEBDLUBCyABIhAgAkcNJkHQACEQDLgDCwJAIAEiASACRw0AQSghEAy4AwsgAEEANgIEIABBjICAgAA2AgggACABIAEQsYCAgAAiEA3TASABIQEM2AELAkAgASIQIAJHDQBBKSEQDLcDCyAQLQAAIgFBIEYNFCABQQlHDdMBIBBBAWohAQwVCwJAIAEiASACRg0AIAFBAWohAQwXC0EqIRAMtQMLAkAgASIQIAJHDQBBKyEQDLUDCwJAIBAtAAAiAUEJRg0AIAFBIEcN1QELIAAtACxBCEYN0wEgECEBDJEDCwJAIAEiASACRw0AQSwhEAy0AwsgAS0AAEEKRw3VASABQQFqIQEMyQILIAEiDiACRw3VAUEvIRAMsgMLA0ACQCABLQAAIhBBIEYNAAJAIBBBdmoOBADcAdwBANoBCyABIQEM4AELIAFBAWoiASACRw0AC0ExIRAMsQMLQTIhECABIhQgAkYNsAMgAiAUayAAKAIAIgFqIRUgFCABa0EDaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfC7gIAAai0AAEcNAQJAIAFBA0cNAEEGIQEMlgMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLEDCyAAQQA2AgAgFCEBDNkBC0EzIRAgASIUIAJGDa8DIAIgFGsgACgCACIBaiEVIBQgAWtBCGohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUH0u4CAAGotAABHDQECQCABQQhHDQBBBSEBDJUDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAywAwsgAEEANgIAIBQhAQzYAQtBNCEQIAEiFCACRg2uAyACIBRrIAAoAgAiAWohFSAUIAFrQQVqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw0BAkAgAUEFRw0AQQchAQyUAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMrwMLIABBADYCACAUIQEM1wELAkAgASIBIAJGDQADQAJAIAEtAABBgL6AgABqLQAAIhBBAUYNACAQQQJGDQogASEBDN0BCyABQQFqIgEgAkcNAAtBMCEQDK4DC0EwIRAMrQMLAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AIBBBdmoOBNkB2gHaAdkB2gELIAFBAWoiASACRw0AC0E4IRAMrQMLQTghEAysAwsDQAJAIAEtAAAiEEEgRg0AIBBBCUcNAwsgAUEBaiIBIAJHDQALQTwhEAyrAwsDQAJAIAEtAAAiEEEgRg0AAkACQCAQQXZqDgTaAQEB2gEACyAQQSxGDdsBCyABIQEMBAsgAUEBaiIBIAJHDQALQT8hEAyqAwsgASEBDNsBC0HAACEQIAEiFCACRg2oAyACIBRrIAAoAgAiAWohFiAUIAFrQQZqIRcCQANAIBQtAABBIHIgAUGAwICAAGotAABHDQEgAUEGRg2OAyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAypAwsgAEEANgIAIBQhAQtBNiEQDI4DCwJAIAEiDyACRw0AQcEAIRAMpwMLIABBjICAgAA2AgggACAPNgIEIA8hASAALQAsQX9qDgTNAdUB1wHZAYcDCyABQQFqIQEMzAELAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgciAQIBBBv39qQf8BcUEaSRtB/wFxIhBBCUYNACAQQSBGDQACQAJAAkACQCAQQZ1/ag4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIRAMkQMLIAFBAWohAUEyIRAMkAMLIAFBAWohAUEzIRAMjwMLIAEhAQzQAQsgAUEBaiIBIAJHDQALQTUhEAylAwtBNSEQDKQDCwJAIAEiASACRg0AA0ACQCABLQAAQYC8gIAAai0AAEEBRg0AIAEhAQzTAQsgAUEBaiIBIAJHDQALQT0hEAykAwtBPSEQDKMDCyAAIAEiASACELCAgIAAIhAN1gEgASEBDAELIBBBAWohAQtBPCEQDIcDCwJAIAEiASACRw0AQcIAIRAMoAMLAkADQAJAIAEtAABBd2oOGAAC/gL+AoQD/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4CAP4CCyABQQFqIgEgAkcNAAtBwgAhEAygAwsgAUEBaiEBIAAtAC1BAXFFDb0BIAEhAQtBLCEQDIUDCyABIgEgAkcN0wFBxAAhEAydAwsDQAJAIAEtAABBkMCAgABqLQAAQQFGDQAgASEBDLcCCyABQQFqIgEgAkcNAAtBxQAhEAycAwsgDS0AACIQQSBGDbMBIBBBOkcNgQMgACgCBCEBIABBADYCBCAAIAEgDRCvgICAACIBDdABIA1BAWohAQyzAgtBxwAhECABIg0gAkYNmgMgAiANayAAKAIAIgFqIRYgDSABa0EFaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGQwoCAAGotAABHDYADIAFBBUYN9AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmgMLQcgAIRAgASINIAJGDZkDIAIgDWsgACgCACIBaiEWIA0gAWtBCWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBlsKAgABqLQAARw3/AgJAIAFBCUcNAEECIQEM9QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJkDCwJAIAEiDSACRw0AQckAIRAMmQMLAkACQCANLQAAIgFBIHIgASABQb9/akH/AXFBGkkbQf8BcUGSf2oOBwCAA4ADgAOAA4ADAYADCyANQQFqIQFBPiEQDIADCyANQQFqIQFBPyEQDP8CC0HKACEQIAEiDSACRg2XAyACIA1rIAAoAgAiAWohFiANIAFrQQFqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaDCgIAAai0AAEcN/QIgAUEBRg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyXAwtBywAhECABIg0gAkYNlgMgAiANayAAKAIAIgFqIRYgDSABa0EOaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGiwoCAAGotAABHDfwCIAFBDkYN8AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlgMLQcwAIRAgASINIAJGDZUDIAIgDWsgACgCACIBaiEWIA0gAWtBD2ohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBwMKAgABqLQAARw37AgJAIAFBD0cNAEEDIQEM8QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJUDC0HNACEQIAEiDSACRg2UAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQdDCgIAAai0AAEcN+gICQCABQQVHDQBBBCEBDPACCyABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyUAwsCQCABIg0gAkcNAEHOACEQDJQDCwJAAkACQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZ1/ag4TAP0C/QL9Av0C/QL9Av0C/QL9Av0C/QL9AgH9Av0C/QICA/0CCyANQQFqIQFBwQAhEAz9AgsgDUEBaiEBQcIAIRAM/AILIA1BAWohAUHDACEQDPsCCyANQQFqIQFBxAAhEAz6AgsCQCABIgEgAkYNACAAQY2AgIAANgIIIAAgATYCBCABIQFBxQAhEAz6AgtBzwAhEAySAwsgECEBAkACQCAQLQAAQXZqDgQBqAKoAgCoAgsgEEEBaiEBC0EnIRAM+AILAkAgASIBIAJHDQBB0QAhEAyRAwsCQCABLQAAQSBGDQAgASEBDI0BCyABQQFqIQEgAC0ALUEBcUUNxwEgASEBDIwBCyABIhcgAkcNyAFB0gAhEAyPAwtB0wAhECABIhQgAkYNjgMgAiAUayAAKAIAIgFqIRYgFCABa0EBaiEXA0AgFC0AACABQdbCgIAAai0AAEcNzAEgAUEBRg3HASABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAyOAwsCQCABIgEgAkcNAEHVACEQDI4DCyABLQAAQQpHDcwBIAFBAWohAQzHAQsCQCABIgEgAkcNAEHWACEQDI0DCwJAAkAgAS0AAEF2ag4EAM0BzQEBzQELIAFBAWohAQzHAQsgAUEBaiEBQcoAIRAM8wILIAAgASIBIAIQroCAgAAiEA3LASABIQFBzQAhEAzyAgsgAC0AKUEiRg2FAwymAgsCQCABIgEgAkcNAEHbACEQDIoDC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgAS0AAEFQag4K1AHTAQABAgMEBQYI1QELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMzAELQQkhEEEBIRRBACEXQQAhFgzLAQsCQCABIgEgAkcNAEHdACEQDIkDCyABLQAAQS5HDcwBIAFBAWohAQymAgsgASIBIAJHDcwBQd8AIRAMhwMLAkAgASIBIAJGDQAgAEGOgICAADYCCCAAIAE2AgQgASEBQdAAIRAM7gILQeAAIRAMhgMLQeEAIRAgASIBIAJGDYUDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHiwoCAAGotAABHDc0BIBRBA0YNzAEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhQMLQeIAIRAgASIBIAJGDYQDIAIgAWsgACgCACIUaiEWIAEgFGtBAmohFwNAIAEtAAAgFEHmwoCAAGotAABHDcwBIBRBAkYNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhAMLQeMAIRAgASIBIAJGDYMDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHpwoCAAGotAABHDcsBIBRBA0YNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMgwMLAkAgASIBIAJHDQBB5QAhEAyDAwsgACABQQFqIgEgAhCogICAACIQDc0BIAEhAUHWACEQDOkCCwJAIAEiASACRg0AA0ACQCABLQAAIhBBIEYNAAJAAkACQCAQQbh/ag4LAAHPAc8BzwHPAc8BzwHPAc8BAs8BCyABQQFqIQFB0gAhEAztAgsgAUEBaiEBQdMAIRAM7AILIAFBAWohAUHUACEQDOsCCyABQQFqIgEgAkcNAAtB5AAhEAyCAwtB5AAhEAyBAwsDQAJAIAEtAABB8MKAgABqLQAAIhBBAUYNACAQQX5qDgPPAdAB0QHSAQsgAUEBaiIBIAJHDQALQeYAIRAMgAMLAkAgASIBIAJGDQAgAUEBaiEBDAMLQecAIRAM/wILA0ACQCABLQAAQfDEgIAAai0AACIQQQFGDQACQCAQQX5qDgTSAdMB1AEA1QELIAEhAUHXACEQDOcCCyABQQFqIgEgAkcNAAtB6AAhEAz+AgsCQCABIgEgAkcNAEHpACEQDP4CCwJAIAEtAAAiEEF2ag4augHVAdUBvAHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHKAdUB1QEA0wELIAFBAWohAQtBBiEQDOMCCwNAAkAgAS0AAEHwxoCAAGotAABBAUYNACABIQEMngILIAFBAWoiASACRw0AC0HqACEQDPsCCwJAIAEiASACRg0AIAFBAWohAQwDC0HrACEQDPoCCwJAIAEiASACRw0AQewAIRAM+gILIAFBAWohAQwBCwJAIAEiASACRw0AQe0AIRAM+QILIAFBAWohAQtBBCEQDN4CCwJAIAEiFCACRw0AQe4AIRAM9wILIBQhAQJAAkACQCAULQAAQfDIgIAAai0AAEF/ag4H1AHVAdYBAJwCAQLXAQsgFEEBaiEBDAoLIBRBAWohAQzNAQtBACEQIABBADYCHCAAQZuSgIAANgIQIABBBzYCDCAAIBRBAWo2AhQM9gILAkADQAJAIAEtAABB8MiAgABqLQAAIhBBBEYNAAJAAkAgEEF/ag4H0gHTAdQB2QEABAHZAQsgASEBQdoAIRAM4AILIAFBAWohAUHcACEQDN8CCyABQQFqIgEgAkcNAAtB7wAhEAz2AgsgAUEBaiEBDMsBCwJAIAEiFCACRw0AQfAAIRAM9QILIBQtAABBL0cN1AEgFEEBaiEBDAYLAkAgASIUIAJHDQBB8QAhEAz0AgsCQCAULQAAIgFBL0cNACAUQQFqIQFB3QAhEAzbAgsgAUF2aiIEQRZLDdMBQQEgBHRBiYCAAnFFDdMBDMoCCwJAIAEiASACRg0AIAFBAWohAUHeACEQDNoCC0HyACEQDPICCwJAIAEiFCACRw0AQfQAIRAM8gILIBQhAQJAIBQtAABB8MyAgABqLQAAQX9qDgPJApQCANQBC0HhACEQDNgCCwJAIAEiFCACRg0AA0ACQCAULQAAQfDKgIAAai0AACIBQQNGDQACQCABQX9qDgLLAgDVAQsgFCEBQd8AIRAM2gILIBRBAWoiFCACRw0AC0HzACEQDPECC0HzACEQDPACCwJAIAEiASACRg0AIABBj4CAgAA2AgggACABNgIEIAEhAUHgACEQDNcCC0H1ACEQDO8CCwJAIAEiASACRw0AQfYAIRAM7wILIABBj4CAgAA2AgggACABNgIEIAEhAQtBAyEQDNQCCwNAIAEtAABBIEcNwwIgAUEBaiIBIAJHDQALQfcAIRAM7AILAkAgASIBIAJHDQBB+AAhEAzsAgsgAS0AAEEgRw3OASABQQFqIQEM7wELIAAgASIBIAIQrICAgAAiEA3OASABIQEMjgILAkAgASIEIAJHDQBB+gAhEAzqAgsgBC0AAEHMAEcN0QEgBEEBaiEBQRMhEAzPAQsCQCABIgQgAkcNAEH7ACEQDOkCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRADQCAELQAAIAFB8M6AgABqLQAARw3QASABQQVGDc4BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQfsAIRAM6AILAkAgASIEIAJHDQBB/AAhEAzoAgsCQAJAIAQtAABBvX9qDgwA0QHRAdEB0QHRAdEB0QHRAdEB0QEB0QELIARBAWohAUHmACEQDM8CCyAEQQFqIQFB5wAhEAzOAgsCQCABIgQgAkcNAEH9ACEQDOcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDc8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH9ACEQDOcCCyAAQQA2AgAgEEEBaiEBQRAhEAzMAQsCQCABIgQgAkcNAEH+ACEQDOYCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUH2zoCAAGotAABHDc4BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH+ACEQDOYCCyAAQQA2AgAgEEEBaiEBQRYhEAzLAQsCQCABIgQgAkcNAEH/ACEQDOUCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUH8zoCAAGotAABHDc0BIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH/ACEQDOUCCyAAQQA2AgAgEEEBaiEBQQUhEAzKAQsCQCABIgQgAkcNAEGAASEQDOQCCyAELQAAQdkARw3LASAEQQFqIQFBCCEQDMkBCwJAIAEiBCACRw0AQYEBIRAM4wILAkACQCAELQAAQbJ/ag4DAMwBAcwBCyAEQQFqIQFB6wAhEAzKAgsgBEEBaiEBQewAIRAMyQILAkAgASIEIAJHDQBBggEhEAziAgsCQAJAIAQtAABBuH9qDggAywHLAcsBywHLAcsBAcsBCyAEQQFqIQFB6gAhEAzJAgsgBEEBaiEBQe0AIRAMyAILAkAgASIEIAJHDQBBgwEhEAzhAgsgAiAEayAAKAIAIgFqIRAgBCABa0ECaiEUAkADQCAELQAAIAFBgM+AgABqLQAARw3JASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBA2AgBBgwEhEAzhAgtBACEQIABBADYCACAUQQFqIQEMxgELAkAgASIEIAJHDQBBhAEhEAzgAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBg8+AgABqLQAARw3IASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhAEhEAzgAgsgAEEANgIAIBBBAWohAUEjIRAMxQELAkAgASIEIAJHDQBBhQEhEAzfAgsCQAJAIAQtAABBtH9qDggAyAHIAcgByAHIAcgBAcgBCyAEQQFqIQFB7wAhEAzGAgsgBEEBaiEBQfAAIRAMxQILAkAgASIEIAJHDQBBhgEhEAzeAgsgBC0AAEHFAEcNxQEgBEEBaiEBDIMCCwJAIAEiBCACRw0AQYcBIRAM3QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQYjPgIAAai0AAEcNxQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYcBIRAM3QILIABBADYCACAQQQFqIQFBLSEQDMIBCwJAIAEiBCACRw0AQYgBIRAM3AILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNxAEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYgBIRAM3AILIABBADYCACAQQQFqIQFBKSEQDMEBCwJAIAEiASACRw0AQYkBIRAM2wILQQEhECABLQAAQd8ARw3AASABQQFqIQEMgQILAkAgASIEIAJHDQBBigEhEAzaAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQA0AgBC0AACABQYzPgIAAai0AAEcNwQEgAUEBRg2vAiABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGKASEQDNkCCwJAIAEiBCACRw0AQYsBIRAM2QILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQY7PgIAAai0AAEcNwQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYsBIRAM2QILIABBADYCACAQQQFqIQFBAiEQDL4BCwJAIAEiBCACRw0AQYwBIRAM2AILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNwAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYwBIRAM2AILIABBADYCACAQQQFqIQFBHyEQDL0BCwJAIAEiBCACRw0AQY0BIRAM1wILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNvwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY0BIRAM1wILIABBADYCACAQQQFqIQFBCSEQDLwBCwJAIAEiBCACRw0AQY4BIRAM1gILAkACQCAELQAAQbd/ag4HAL8BvwG/Ab8BvwEBvwELIARBAWohAUH4ACEQDL0CCyAEQQFqIQFB+QAhEAy8AgsCQCABIgQgAkcNAEGPASEQDNUCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGRz4CAAGotAABHDb0BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGPASEQDNUCCyAAQQA2AgAgEEEBaiEBQRghEAy6AQsCQCABIgQgAkcNAEGQASEQDNQCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUGXz4CAAGotAABHDbwBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGQASEQDNQCCyAAQQA2AgAgEEEBaiEBQRchEAy5AQsCQCABIgQgAkcNAEGRASEQDNMCCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUGaz4CAAGotAABHDbsBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGRASEQDNMCCyAAQQA2AgAgEEEBaiEBQRUhEAy4AQsCQCABIgQgAkcNAEGSASEQDNICCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGhz4CAAGotAABHDboBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGSASEQDNICCyAAQQA2AgAgEEEBaiEBQR4hEAy3AQsCQCABIgQgAkcNAEGTASEQDNECCyAELQAAQcwARw24ASAEQQFqIQFBCiEQDLYBCwJAIAQgAkcNAEGUASEQDNACCwJAAkAgBC0AAEG/f2oODwC5AbkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AQG5AQsgBEEBaiEBQf4AIRAMtwILIARBAWohAUH/ACEQDLYCCwJAIAQgAkcNAEGVASEQDM8CCwJAAkAgBC0AAEG/f2oOAwC4AQG4AQsgBEEBaiEBQf0AIRAMtgILIARBAWohBEGAASEQDLUCCwJAIAQgAkcNAEGWASEQDM4CCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUGnz4CAAGotAABHDbYBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGWASEQDM4CCyAAQQA2AgAgEEEBaiEBQQshEAyzAQsCQCAEIAJHDQBBlwEhEAzNAgsCQAJAAkACQCAELQAAQVNqDiMAuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AQG4AbgBuAG4AbgBArgBuAG4AQO4AQsgBEEBaiEBQfsAIRAMtgILIARBAWohAUH8ACEQDLUCCyAEQQFqIQRBgQEhEAy0AgsgBEEBaiEEQYIBIRAMswILAkAgBCACRw0AQZgBIRAMzAILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQanPgIAAai0AAEcNtAEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZgBIRAMzAILIABBADYCACAQQQFqIQFBGSEQDLEBCwJAIAQgAkcNAEGZASEQDMsCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGuz4CAAGotAABHDbMBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGZASEQDMsCCyAAQQA2AgAgEEEBaiEBQQYhEAywAQsCQCAEIAJHDQBBmgEhEAzKAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBtM+AgABqLQAARw2yASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmgEhEAzKAgsgAEEANgIAIBBBAWohAUEcIRAMrwELAkAgBCACRw0AQZsBIRAMyQILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbbPgIAAai0AAEcNsQEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZsBIRAMyQILIABBADYCACAQQQFqIQFBJyEQDK4BCwJAIAQgAkcNAEGcASEQDMgCCwJAAkAgBC0AAEGsf2oOAgABsQELIARBAWohBEGGASEQDK8CCyAEQQFqIQRBhwEhEAyuAgsCQCAEIAJHDQBBnQEhEAzHAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBuM+AgABqLQAARw2vASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBnQEhEAzHAgsgAEEANgIAIBBBAWohAUEmIRAMrAELAkAgBCACRw0AQZ4BIRAMxgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbrPgIAAai0AAEcNrgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ4BIRAMxgILIABBADYCACAQQQFqIQFBAyEQDKsBCwJAIAQgAkcNAEGfASEQDMUCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDa0BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGfASEQDMUCCyAAQQA2AgAgEEEBaiEBQQwhEAyqAQsCQCAEIAJHDQBBoAEhEAzEAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBvM+AgABqLQAARw2sASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBoAEhEAzEAgsgAEEANgIAIBBBAWohAUENIRAMqQELAkAgBCACRw0AQaEBIRAMwwILAkACQCAELQAAQbp/ag4LAKwBrAGsAawBrAGsAawBrAGsAQGsAQsgBEEBaiEEQYsBIRAMqgILIARBAWohBEGMASEQDKkCCwJAIAQgAkcNAEGiASEQDMICCyAELQAAQdAARw2pASAEQQFqIQQM6QELAkAgBCACRw0AQaMBIRAMwQILAkACQCAELQAAQbd/ag4HAaoBqgGqAaoBqgEAqgELIARBAWohBEGOASEQDKgCCyAEQQFqIQFBIiEQDKYBCwJAIAQgAkcNAEGkASEQDMACCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHAz4CAAGotAABHDagBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGkASEQDMACCyAAQQA2AgAgEEEBaiEBQR0hEAylAQsCQCAEIAJHDQBBpQEhEAy/AgsCQAJAIAQtAABBrn9qDgMAqAEBqAELIARBAWohBEGQASEQDKYCCyAEQQFqIQFBBCEQDKQBCwJAIAQgAkcNAEGmASEQDL4CCwJAAkACQAJAAkAgBC0AAEG/f2oOFQCqAaoBqgGqAaoBqgGqAaoBqgGqAQGqAaoBAqoBqgEDqgGqAQSqAQsgBEEBaiEEQYgBIRAMqAILIARBAWohBEGJASEQDKcCCyAEQQFqIQRBigEhEAymAgsgBEEBaiEEQY8BIRAMpQILIARBAWohBEGRASEQDKQCCwJAIAQgAkcNAEGnASEQDL0CCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDaUBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGnASEQDL0CCyAAQQA2AgAgEEEBaiEBQREhEAyiAQsCQCAEIAJHDQBBqAEhEAy8AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBws+AgABqLQAARw2kASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqAEhEAy8AgsgAEEANgIAIBBBAWohAUEsIRAMoQELAkAgBCACRw0AQakBIRAMuwILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQcXPgIAAai0AAEcNowEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQakBIRAMuwILIABBADYCACAQQQFqIQFBKyEQDKABCwJAIAQgAkcNAEGqASEQDLoCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHKz4CAAGotAABHDaIBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGqASEQDLoCCyAAQQA2AgAgEEEBaiEBQRQhEAyfAQsCQCAEIAJHDQBBqwEhEAy5AgsCQAJAAkACQCAELQAAQb5/ag4PAAECpAGkAaQBpAGkAaQBpAGkAaQBpAGkAQOkAQsgBEEBaiEEQZMBIRAMogILIARBAWohBEGUASEQDKECCyAEQQFqIQRBlQEhEAygAgsgBEEBaiEEQZYBIRAMnwILAkAgBCACRw0AQawBIRAMuAILIAQtAABBxQBHDZ8BIARBAWohBAzgAQsCQCAEIAJHDQBBrQEhEAy3AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBzc+AgABqLQAARw2fASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrQEhEAy3AgsgAEEANgIAIBBBAWohAUEOIRAMnAELAkAgBCACRw0AQa4BIRAMtgILIAQtAABB0ABHDZ0BIARBAWohAUElIRAMmwELAkAgBCACRw0AQa8BIRAMtQILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNnQEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQa8BIRAMtQILIABBADYCACAQQQFqIQFBKiEQDJoBCwJAIAQgAkcNAEGwASEQDLQCCwJAAkAgBC0AAEGrf2oOCwCdAZ0BnQGdAZ0BnQGdAZ0BnQEBnQELIARBAWohBEGaASEQDJsCCyAEQQFqIQRBmwEhEAyaAgsCQCAEIAJHDQBBsQEhEAyzAgsCQAJAIAQtAABBv39qDhQAnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBAZwBCyAEQQFqIQRBmQEhEAyaAgsgBEEBaiEEQZwBIRAMmQILAkAgBCACRw0AQbIBIRAMsgILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQdnPgIAAai0AAEcNmgEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbIBIRAMsgILIABBADYCACAQQQFqIQFBISEQDJcBCwJAIAQgAkcNAEGzASEQDLECCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUHdz4CAAGotAABHDZkBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGzASEQDLECCyAAQQA2AgAgEEEBaiEBQRohEAyWAQsCQCAEIAJHDQBBtAEhEAywAgsCQAJAAkAgBC0AAEG7f2oOEQCaAZoBmgGaAZoBmgGaAZoBmgEBmgGaAZoBmgGaAQKaAQsgBEEBaiEEQZ0BIRAMmAILIARBAWohBEGeASEQDJcCCyAEQQFqIQRBnwEhEAyWAgsCQCAEIAJHDQBBtQEhEAyvAgsgAiAEayAAKAIAIgFqIRQgBCABa0EFaiEQAkADQCAELQAAIAFB5M+AgABqLQAARw2XASABQQVGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtQEhEAyvAgsgAEEANgIAIBBBAWohAUEoIRAMlAELAkAgBCACRw0AQbYBIRAMrgILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQerPgIAAai0AAEcNlgEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbYBIRAMrgILIABBADYCACAQQQFqIQFBByEQDJMBCwJAIAQgAkcNAEG3ASEQDK0CCwJAAkAgBC0AAEG7f2oODgCWAZYBlgGWAZYBlgGWAZYBlgGWAZYBlgEBlgELIARBAWohBEGhASEQDJQCCyAEQQFqIQRBogEhEAyTAgsCQCAEIAJHDQBBuAEhEAysAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB7c+AgABqLQAARw2UASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuAEhEAysAgsgAEEANgIAIBBBAWohAUESIRAMkQELAkAgBCACRw0AQbkBIRAMqwILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNkwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbkBIRAMqwILIABBADYCACAQQQFqIQFBICEQDJABCwJAIAQgAkcNAEG6ASEQDKoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHyz4CAAGotAABHDZIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG6ASEQDKoCCyAAQQA2AgAgEEEBaiEBQQ8hEAyPAQsCQCAEIAJHDQBBuwEhEAypAgsCQAJAIAQtAABBt39qDgcAkgGSAZIBkgGSAQGSAQsgBEEBaiEEQaUBIRAMkAILIARBAWohBEGmASEQDI8CCwJAIAQgAkcNAEG8ASEQDKgCCyACIARrIAAoAgAiAWohFCAEIAFrQQdqIRACQANAIAQtAAAgAUH0z4CAAGotAABHDZABIAFBB0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG8ASEQDKgCCyAAQQA2AgAgEEEBaiEBQRshEAyNAQsCQCAEIAJHDQBBvQEhEAynAgsCQAJAAkAgBC0AAEG+f2oOEgCRAZEBkQGRAZEBkQGRAZEBkQEBkQGRAZEBkQGRAZEBApEBCyAEQQFqIQRBpAEhEAyPAgsgBEEBaiEEQacBIRAMjgILIARBAWohBEGoASEQDI0CCwJAIAQgAkcNAEG+ASEQDKYCCyAELQAAQc4ARw2NASAEQQFqIQQMzwELAkAgBCACRw0AQb8BIRAMpQILAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgBC0AAEG/f2oOFQABAgOcAQQFBpwBnAGcAQcICQoLnAEMDQ4PnAELIARBAWohAUHoACEQDJoCCyAEQQFqIQFB6QAhEAyZAgsgBEEBaiEBQe4AIRAMmAILIARBAWohAUHyACEQDJcCCyAEQQFqIQFB8wAhEAyWAgsgBEEBaiEBQfYAIRAMlQILIARBAWohAUH3ACEQDJQCCyAEQQFqIQFB+gAhEAyTAgsgBEEBaiEEQYMBIRAMkgILIARBAWohBEGEASEQDJECCyAEQQFqIQRBhQEhEAyQAgsgBEEBaiEEQZIBIRAMjwILIARBAWohBEGYASEQDI4CCyAEQQFqIQRBoAEhEAyNAgsgBEEBaiEEQaMBIRAMjAILIARBAWohBEGqASEQDIsCCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEGrASEQDIsCC0HAASEQDKMCCyAAIAUgAhCqgICAACIBDYsBIAUhAQxcCwJAIAYgAkYNACAGQQFqIQUMjQELQcIBIRAMoQILA0ACQCAQLQAAQXZqDgSMAQAAjwEACyAQQQFqIhAgAkcNAAtBwwEhEAygAgsCQCAHIAJGDQAgAEGRgICAADYCCCAAIAc2AgQgByEBQQEhEAyHAgtBxAEhEAyfAgsCQCAHIAJHDQBBxQEhEAyfAgsCQAJAIActAABBdmoOBAHOAc4BAM4BCyAHQQFqIQYMjQELIAdBAWohBQyJAQsCQCAHIAJHDQBBxgEhEAyeAgsCQAJAIActAABBdmoOFwGPAY8BAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAQCPAQsgB0EBaiEHC0GwASEQDIQCCwJAIAggAkcNAEHIASEQDJ0CCyAILQAAQSBHDY0BIABBADsBMiAIQQFqIQFBswEhEAyDAgsgASEXAkADQCAXIgcgAkYNASAHLQAAQVBqQf8BcSIQQQpPDcwBAkAgAC8BMiIUQZkzSw0AIAAgFEEKbCIUOwEyIBBB//8DcyAUQf7/A3FJDQAgB0EBaiEXIAAgFCAQaiIQOwEyIBBB//8DcUHoB0kNAQsLQQAhECAAQQA2AhwgAEHBiYCAADYCECAAQQ02AgwgACAHQQFqNgIUDJwCC0HHASEQDJsCCyAAIAggAhCugICAACIQRQ3KASAQQRVHDYwBIABByAE2AhwgACAINgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAyaAgsCQCAJIAJHDQBBzAEhEAyaAgtBACEUQQEhF0EBIRZBACEQAkACQAJAAkACQAJAAkACQAJAIAktAABBUGoOCpYBlQEAAQIDBAUGCJcBC0ECIRAMBgtBAyEQDAULQQQhEAwEC0EFIRAMAwtBBiEQDAILQQchEAwBC0EIIRALQQAhF0EAIRZBACEUDI4BC0EJIRBBASEUQQAhF0EAIRYMjQELAkAgCiACRw0AQc4BIRAMmQILIAotAABBLkcNjgEgCkEBaiEJDMoBCyALIAJHDY4BQdABIRAMlwILAkAgCyACRg0AIABBjoCAgAA2AgggACALNgIEQbcBIRAM/gELQdEBIRAMlgILAkAgBCACRw0AQdIBIRAMlgILIAIgBGsgACgCACIQaiEUIAQgEGtBBGohCwNAIAQtAAAgEEH8z4CAAGotAABHDY4BIBBBBEYN6QEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB0gEhEAyVAgsgACAMIAIQrICAgAAiAQ2NASAMIQEMuAELAkAgBCACRw0AQdQBIRAMlAILIAIgBGsgACgCACIQaiEUIAQgEGtBAWohDANAIAQtAAAgEEGB0ICAAGotAABHDY8BIBBBAUYNjgEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB1AEhEAyTAgsCQCAEIAJHDQBB1gEhEAyTAgsgAiAEayAAKAIAIhBqIRQgBCAQa0ECaiELA0AgBC0AACAQQYPQgIAAai0AAEcNjgEgEEECRg2QASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHWASEQDJICCwJAIAQgAkcNAEHXASEQDJICCwJAAkAgBC0AAEG7f2oOEACPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAY8BCyAEQQFqIQRBuwEhEAz5AQsgBEEBaiEEQbwBIRAM+AELAkAgBCACRw0AQdgBIRAMkQILIAQtAABByABHDYwBIARBAWohBAzEAQsCQCAEIAJGDQAgAEGQgICAADYCCCAAIAQ2AgRBvgEhEAz3AQtB2QEhEAyPAgsCQCAEIAJHDQBB2gEhEAyPAgsgBC0AAEHIAEYNwwEgAEEBOgAoDLkBCyAAQQI6AC8gACAEIAIQpoCAgAAiEA2NAUHCASEQDPQBCyAALQAoQX9qDgK3AbkBuAELA0ACQCAELQAAQXZqDgQAjgGOAQCOAQsgBEEBaiIEIAJHDQALQd0BIRAMiwILIABBADoALyAALQAtQQRxRQ2EAgsgAEEAOgAvIABBAToANCABIQEMjAELIBBBFUYN2gEgAEEANgIcIAAgATYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMiAILAkAgACAQIAIQtICAgAAiBA0AIBAhAQyBAgsCQCAEQRVHDQAgAEEDNgIcIAAgEDYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMiAILIABBADYCHCAAIBA2AhQgAEGnjoCAADYCECAAQRI2AgxBACEQDIcCCyAQQRVGDdYBIABBADYCHCAAIAE2AhQgAEHajYCAADYCECAAQRQ2AgxBACEQDIYCCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNjQEgAEEHNgIcIAAgEDYCFCAAIBQ2AgxBACEQDIUCCyAAIAAvATBBgAFyOwEwIAEhAQtBKiEQDOoBCyAQQRVGDdEBIABBADYCHCAAIAE2AhQgAEGDjICAADYCECAAQRM2AgxBACEQDIICCyAQQRVGDc8BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDIECCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyNAQsgAEEMNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDIACCyAQQRVGDcwBIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDP8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyMAQsgAEENNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDP4BCyAQQRVGDckBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDP0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyLAQsgAEEONgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPwBCyAAQQA2AhwgACABNgIUIABBwJWAgAA2AhAgAEECNgIMQQAhEAz7AQsgEEEVRg3FASAAQQA2AhwgACABNgIUIABBxoyAgAA2AhAgAEEjNgIMQQAhEAz6AQsgAEEQNgIcIAAgATYCFCAAIBA2AgxBACEQDPkBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQzxAQsgAEERNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPgBCyAQQRVGDcEBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPcBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyIAQsgAEETNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPYBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQztAQsgAEEUNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPUBCyAQQRVGDb0BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDPQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyGAQsgAEEWNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPMBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQt4CAgAAiBA0AIAFBAWohAQzpAQsgAEEXNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPIBCyAAQQA2AhwgACABNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzxAQtCASERCyAQQQFqIQECQCAAKQMgIhJC//////////8PVg0AIAAgEkIEhiARhDcDICABIQEMhAELIABBADYCHCAAIAE2AhQgAEGtiYCAADYCECAAQQw2AgxBACEQDO8BCyAAQQA2AhwgACAQNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzuAQsgACgCBCEXIABBADYCBCAQIBGnaiIWIQEgACAXIBAgFiAUGyIQELWAgIAAIhRFDXMgAEEFNgIcIAAgEDYCFCAAIBQ2AgxBACEQDO0BCyAAQQA2AhwgACAQNgIUIABBqpyAgAA2AhAgAEEPNgIMQQAhEAzsAQsgACAQIAIQtICAgAAiAQ0BIBAhAQtBDiEQDNEBCwJAIAFBFUcNACAAQQI2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAzqAQsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAM6QELIAFBAWohEAJAIAAvATAiAUGAAXFFDQACQCAAIBAgAhC7gICAACIBDQAgECEBDHALIAFBFUcNugEgAEEFNgIcIAAgEDYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAM6QELAkAgAUGgBHFBoARHDQAgAC0ALUECcQ0AIABBADYCHCAAIBA2AhQgAEGWk4CAADYCECAAQQQ2AgxBACEQDOkBCyAAIBAgAhC9gICAABogECEBAkACQAJAAkACQCAAIBAgAhCzgICAAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIABBAToALgsgACAALwEwQcAAcjsBMCAQIQELQSYhEAzRAQsgAEEjNgIcIAAgEDYCFCAAQaWWgIAANgIQIABBFTYCDEEAIRAM6QELIABBADYCHCAAIBA2AhQgAEHVi4CAADYCECAAQRE2AgxBACEQDOgBCyAALQAtQQFxRQ0BQcMBIRAMzgELAkAgDSACRg0AA0ACQCANLQAAQSBGDQAgDSEBDMQBCyANQQFqIg0gAkcNAAtBJSEQDOcBC0ElIRAM5gELIAAoAgQhBCAAQQA2AgQgACAEIA0Qr4CAgAAiBEUNrQEgAEEmNgIcIAAgBDYCDCAAIA1BAWo2AhRBACEQDOUBCyAQQRVGDasBIABBADYCHCAAIAE2AhQgAEH9jYCAADYCECAAQR02AgxBACEQDOQBCyAAQSc2AhwgACABNgIUIAAgEDYCDEEAIRAM4wELIBAhAUEBIRQCQAJAAkACQAJAAkACQCAALQAsQX5qDgcGBQUDAQIABQsgACAALwEwQQhyOwEwDAMLQQIhFAwBC0EEIRQLIABBAToALCAAIAAvATAgFHI7ATALIBAhAQtBKyEQDMoBCyAAQQA2AhwgACAQNgIUIABBq5KAgAA2AhAgAEELNgIMQQAhEAziAQsgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDEEAIRAM4QELIABBADoALCAQIQEMvQELIBAhAUEBIRQCQAJAAkACQAJAIAAtACxBe2oOBAMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0EpIRAMxQELIABBADYCHCAAIAE2AhQgAEHwlICAADYCECAAQQM2AgxBACEQDN0BCwJAIA4tAABBDUcNACAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA5BAWohAQx1CyAAQSw2AhwgACABNgIMIAAgDkEBajYCFEEAIRAM3QELIAAtAC1BAXFFDQFBxAEhEAzDAQsCQCAOIAJHDQBBLSEQDNwBCwJAAkADQAJAIA4tAABBdmoOBAIAAAMACyAOQQFqIg4gAkcNAAtBLSEQDN0BCyAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA4hAQx0CyAAQSw2AhwgACAONgIUIAAgATYCDEEAIRAM3AELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHMLIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzbAQsgACgCBCEEIABBADYCBCAAIAQgDhCxgICAACIEDaABIA4hAQzOAQsgEEEsRw0BIAFBAWohEEEBIQECQAJAAkACQAJAIAAtACxBe2oOBAMBAgQACyAQIQEMBAtBAiEBDAELQQQhAQsgAEEBOgAsIAAgAC8BMCABcjsBMCAQIQEMAQsgACAALwEwQQhyOwEwIBAhAQtBOSEQDL8BCyAAQQA6ACwgASEBC0E0IRAMvQELIAAgAC8BMEEgcjsBMCABIQEMAgsgACgCBCEEIABBADYCBAJAIAAgBCABELGAgIAAIgQNACABIQEMxwELIABBNzYCHCAAIAE2AhQgACAENgIMQQAhEAzUAQsgAEEIOgAsIAEhAQtBMCEQDLkBCwJAIAAtAChBAUYNACABIQEMBAsgAC0ALUEIcUUNkwEgASEBDAMLIAAtADBBIHENlAFBxQEhEAy3AQsCQCAPIAJGDQACQANAAkAgDy0AAEFQaiIBQf8BcUEKSQ0AIA8hAUE1IRAMugELIAApAyAiEUKZs+bMmbPmzBlWDQEgACARQgp+IhE3AyAgESABrUL/AYMiEkJ/hVYNASAAIBEgEnw3AyAgD0EBaiIPIAJHDQALQTkhEAzRAQsgACgCBCECIABBADYCBCAAIAIgD0EBaiIEELGAgIAAIgINlQEgBCEBDMMBC0E5IRAMzwELAkAgAC8BMCIBQQhxRQ0AIAAtAChBAUcNACAALQAtQQhxRQ2QAQsgACABQff7A3FBgARyOwEwIA8hAQtBNyEQDLQBCyAAIAAvATBBEHI7ATAMqwELIBBBFUYNiwEgAEEANgIcIAAgATYCFCAAQfCOgIAANgIQIABBHDYCDEEAIRAMywELIABBwwA2AhwgACABNgIMIAAgDUEBajYCFEEAIRAMygELAkAgAS0AAEE6Rw0AIAAoAgQhECAAQQA2AgQCQCAAIBAgARCvgICAACIQDQAgAUEBaiEBDGMLIABBwwA2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMygELIABBADYCHCAAIAE2AhQgAEGxkYCAADYCECAAQQo2AgxBACEQDMkBCyAAQQA2AhwgACABNgIUIABBoJmAgAA2AhAgAEEeNgIMQQAhEAzIAQsgAEEANgIACyAAQYASOwEqIAAgF0EBaiIBIAIQqICAgAAiEA0BIAEhAQtBxwAhEAysAQsgEEEVRw2DASAAQdEANgIcIAAgATYCFCAAQeOXgIAANgIQIABBFTYCDEEAIRAMxAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDF4LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMwwELIABBADYCHCAAIBQ2AhQgAEHBqICAADYCECAAQQc2AgwgAEEANgIAQQAhEAzCAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAzBAQtBACEQIABBADYCHCAAIAE2AhQgAEGAkYCAADYCECAAQQk2AgwMwAELIBBBFUYNfSAAQQA2AhwgACABNgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAy/AQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgAUEBaiEBAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBAJAIAAgECABEK2AgIAAIhANACABIQEMXAsgAEHYADYCHCAAIAE2AhQgACAQNgIMQQAhEAy+AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMrQELIABB2QA2AhwgACABNgIUIAAgBDYCDEEAIRAMvQELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKsBCyAAQdoANgIcIAAgATYCFCAAIAQ2AgxBACEQDLwBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQypAQsgAEHcADYCHCAAIAE2AhQgACAENgIMQQAhEAy7AQsCQCABLQAAQVBqIhBB/wFxQQpPDQAgACAQOgAqIAFBAWohAUHPACEQDKIBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQynAQsgAEHeADYCHCAAIAE2AhQgACAENgIMQQAhEAy6AQsgAEEANgIAIBdBAWohAQJAIAAtAClBI08NACABIQEMWQsgAEEANgIcIAAgATYCFCAAQdOJgIAANgIQIABBCDYCDEEAIRAMuQELIABBADYCAAtBACEQIABBADYCHCAAIAE2AhQgAEGQs4CAADYCECAAQQg2AgwMtwELIABBADYCACAXQQFqIQECQCAALQApQSFHDQAgASEBDFYLIABBADYCHCAAIAE2AhQgAEGbioCAADYCECAAQQg2AgxBACEQDLYBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKSIQQV1qQQtPDQAgASEBDFULAkAgEEEGSw0AQQEgEHRBygBxRQ0AIAEhAQxVC0EAIRAgAEEANgIcIAAgATYCFCAAQfeJgIAANgIQIABBCDYCDAy1AQsgEEEVRg1xIABBADYCHCAAIAE2AhQgAEG5jYCAADYCECAAQRo2AgxBACEQDLQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxUCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLMBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAAgEDoAKSAAKAIEIRAgAEEANgIEIAAgECABEKuAgIAAIhANVCABIQEMPgsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQfGbgIAANgIQIABBBjYCDAyXAQsgAUEVRg1QIABBADYCHCAAIAU2AhQgAEHwjICAADYCECAAQRs2AgxBACEQDJYBCyAAKAIEIQUgAEEANgIEIAAgBSAQEKmAgIAAIgUNASAQQQFqIQULQa0BIRAMewsgAEHBATYCHCAAIAU2AgwgACAQQQFqNgIUQQAhEAyTAQsgACgCBCEGIABBADYCBCAAIAYgEBCpgICAACIGDQEgEEEBaiEGC0GuASEQDHgLIABBwgE2AhwgACAGNgIMIAAgEEEBajYCFEEAIRAMkAELIABBADYCHCAAIAc2AhQgAEGXi4CAADYCECAAQQ02AgxBACEQDI8BCyAAQQA2AhwgACAINgIUIABB45CAgAA2AhAgAEEJNgIMQQAhEAyOAQsgAEEANgIcIAAgCDYCFCAAQZSNgIAANgIQIABBITYCDEEAIRAMjQELQQEhFkEAIRdBACEUQQEhEAsgACAQOgArIAlBAWohCAJAAkAgAC0ALUEQcQ0AAkACQAJAIAAtACoOAwEAAgQLIBZFDQMMAgsgFA0BDAILIBdFDQELIAAoAgQhECAAQQA2AgQgACAQIAgQrYCAgAAiEEUNPSAAQckBNgIcIAAgCDYCFCAAIBA2AgxBACEQDIwBCyAAKAIEIQQgAEEANgIEIAAgBCAIEK2AgIAAIgRFDXYgAEHKATYCHCAAIAg2AhQgACAENgIMQQAhEAyLAQsgACgCBCEEIABBADYCBCAAIAQgCRCtgICAACIERQ10IABBywE2AhwgACAJNgIUIAAgBDYCDEEAIRAMigELIAAoAgQhBCAAQQA2AgQgACAEIAoQrYCAgAAiBEUNciAAQc0BNgIcIAAgCjYCFCAAIAQ2AgxBACEQDIkBCwJAIAstAABBUGoiEEH/AXFBCk8NACAAIBA6ACogC0EBaiEKQbYBIRAMcAsgACgCBCEEIABBADYCBCAAIAQgCxCtgICAACIERQ1wIABBzwE2AhwgACALNgIUIAAgBDYCDEEAIRAMiAELIABBADYCHCAAIAQ2AhQgAEGQs4CAADYCECAAQQg2AgwgAEEANgIAQQAhEAyHAQsgAUEVRg0/IABBADYCHCAAIAw2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDIYBCyAAQYEEOwEoIAAoAgQhECAAQgA3AwAgACAQIAxBAWoiDBCrgICAACIQRQ04IABB0wE2AhwgACAMNgIUIAAgEDYCDEEAIRAMhQELIABBADYCAAtBACEQIABBADYCHCAAIAQ2AhQgAEHYm4CAADYCECAAQQg2AgwMgwELIAAoAgQhECAAQgA3AwAgACAQIAtBAWoiCxCrgICAACIQDQFBxgEhEAxpCyAAQQI6ACgMVQsgAEHVATYCHCAAIAs2AhQgACAQNgIMQQAhEAyAAQsgEEEVRg03IABBADYCHCAAIAQ2AhQgAEGkjICAADYCECAAQRA2AgxBACEQDH8LIAAtADRBAUcNNCAAIAQgAhC8gICAACIQRQ00IBBBFUcNNSAAQdwBNgIcIAAgBDYCFCAAQdWWgIAANgIQIABBFTYCDEEAIRAMfgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQMfQtBACEQDGMLQQIhEAxiC0ENIRAMYQtBDyEQDGALQSUhEAxfC0ETIRAMXgtBFSEQDF0LQRYhEAxcC0EXIRAMWwtBGCEQDFoLQRkhEAxZC0EaIRAMWAtBGyEQDFcLQRwhEAxWC0EdIRAMVQtBHyEQDFQLQSEhEAxTC0EjIRAMUgtBxgAhEAxRC0EuIRAMUAtBLyEQDE8LQTshEAxOC0E9IRAMTQtByAAhEAxMC0HJACEQDEsLQcsAIRAMSgtBzAAhEAxJC0HOACEQDEgLQdEAIRAMRwtB1QAhEAxGC0HYACEQDEULQdkAIRAMRAtB2wAhEAxDC0HkACEQDEILQeUAIRAMQQtB8QAhEAxAC0H0ACEQDD8LQY0BIRAMPgtBlwEhEAw9C0GpASEQDDwLQawBIRAMOwtBwAEhEAw6C0G5ASEQDDkLQa8BIRAMOAtBsQEhEAw3C0GyASEQDDYLQbQBIRAMNQtBtQEhEAw0C0G6ASEQDDMLQb0BIRAMMgtBvwEhEAwxC0HBASEQDDALIABBADYCHCAAIAQ2AhQgAEHpi4CAADYCECAAQR82AgxBACEQDEgLIABB2wE2AhwgACAENgIUIABB+paAgAA2AhAgAEEVNgIMQQAhEAxHCyAAQfgANgIcIAAgDDYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMRgsgAEHRADYCHCAAIAU2AhQgAEGwl4CAADYCECAAQRU2AgxBACEQDEULIABB+QA2AhwgACABNgIUIAAgEDYCDEEAIRAMRAsgAEH4ADYCHCAAIAE2AhQgAEHKmICAADYCECAAQRU2AgxBACEQDEMLIABB5AA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAxCCyAAQdcANgIcIAAgATYCFCAAQcmXgIAANgIQIABBFTYCDEEAIRAMQQsgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMQAsgAEHCADYCHCAAIAE2AhQgAEHjmICAADYCECAAQRU2AgxBACEQDD8LIABBADYCBCAAIA8gDxCxgICAACIERQ0BIABBOjYCHCAAIAQ2AgwgACAPQQFqNgIUQQAhEAw+CyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBEUNACAAQTs2AhwgACAENgIMIAAgAUEBajYCFEEAIRAMPgsgAUEBaiEBDC0LIA9BAWohAQwtCyAAQQA2AhwgACAPNgIUIABB5JKAgAA2AhAgAEEENgIMQQAhEAw7CyAAQTY2AhwgACAENgIUIAAgAjYCDEEAIRAMOgsgAEEuNgIcIAAgDjYCFCAAIAQ2AgxBACEQDDkLIABB0AA2AhwgACABNgIUIABBkZiAgAA2AhAgAEEVNgIMQQAhEAw4CyANQQFqIQEMLAsgAEEVNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMNgsgAEEbNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNQsgAEEPNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNAsgAEELNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMMwsgAEEaNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMgsgAEELNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMQsgAEEKNgIcIAAgATYCFCAAQeSWgIAANgIQIABBFTYCDEEAIRAMMAsgAEEeNgIcIAAgATYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAMLwsgAEEANgIcIAAgEDYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMLgsgAEEENgIcIAAgATYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMLQsgAEEANgIAIAtBAWohCwtBuAEhEAwSCyAAQQA2AgAgEEEBaiEBQfUAIRAMEQsgASEBAkAgAC0AKUEFRw0AQeMAIRAMEQtB4gAhEAwQC0EAIRAgAEEANgIcIABB5JGAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAwoCyAAQQA2AgAgF0EBaiEBQcAAIRAMDgtBASEBCyAAIAE6ACwgAEEANgIAIBdBAWohAQtBKCEQDAsLIAEhAQtBOCEQDAkLAkAgASIPIAJGDQADQAJAIA8tAABBgL6AgABqLQAAIgFBAUYNACABQQJHDQMgD0EBaiEBDAQLIA9BAWoiDyACRw0AC0E+IRAMIgtBPiEQDCELIABBADoALCAPIQEMAQtBCyEQDAYLQTohEAwFCyABQQFqIQFBLSEQDAQLIAAgAToALCAAQQA2AgAgFkEBaiEBQQwhEAwDCyAAQQA2AgAgF0EBaiEBQQohEAwCCyAAQQA2AgALIABBADoALCANIQFBCSEQDAALC0EAIRAgAEEANgIcIAAgCzYCFCAAQc2QgIAANgIQIABBCTYCDAwXC0EAIRAgAEEANgIcIAAgCjYCFCAAQemKgIAANgIQIABBCTYCDAwWC0EAIRAgAEEANgIcIAAgCTYCFCAAQbeQgIAANgIQIABBCTYCDAwVC0EAIRAgAEEANgIcIAAgCDYCFCAAQZyRgIAANgIQIABBCTYCDAwUC0EAIRAgAEEANgIcIAAgATYCFCAAQc2QgIAANgIQIABBCTYCDAwTC0EAIRAgAEEANgIcIAAgATYCFCAAQemKgIAANgIQIABBCTYCDAwSC0EAIRAgAEEANgIcIAAgATYCFCAAQbeQgIAANgIQIABBCTYCDAwRC0EAIRAgAEEANgIcIAAgATYCFCAAQZyRgIAANgIQIABBCTYCDAwQC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwPC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwOC0EAIRAgAEEANgIcIAAgATYCFCAAQcCSgIAANgIQIABBCzYCDAwNC0EAIRAgAEEANgIcIAAgATYCFCAAQZWJgIAANgIQIABBCzYCDAwMC0EAIRAgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDAwLC0EAIRAgAEEANgIcIAAgATYCFCAAQfuPgIAANgIQIABBCjYCDAwKC0EAIRAgAEEANgIcIAAgATYCFCAAQfGZgIAANgIQIABBAjYCDAwJC0EAIRAgAEEANgIcIAAgATYCFCAAQcSUgIAANgIQIABBAjYCDAwIC0EAIRAgAEEANgIcIAAgATYCFCAAQfKVgIAANgIQIABBAjYCDAwHCyAAQQI2AhwgACABNgIUIABBnJqAgAA2AhAgAEEWNgIMQQAhEAwGC0EBIRAMBQtB1AAhECABIgQgAkYNBCADQQhqIAAgBCACQdjCgIAAQQoQxYCAgAAgAygCDCEEIAMoAggOAwEEAgALEMqAgIAAAAsgAEEANgIcIABBtZqAgAA2AhAgAEEXNgIMIAAgBEEBajYCFEEAIRAMAgsgAEEANgIcIAAgBDYCFCAAQcqagIAANgIQIABBCTYCDEEAIRAMAQsCQCABIgQgAkcNAEEiIRAMAQsgAEGJgICAADYCCCAAIAQ2AgRBISEQCyADQRBqJICAgIAAIBALrwEBAn8gASgCACEGAkACQCACIANGDQAgBCAGaiEEIAYgA2ogAmshByACIAZBf3MgBWoiBmohBQNAAkAgAi0AACAELQAARg0AQQIhBAwDCwJAIAYNAEEAIQQgBSECDAMLIAZBf2ohBiAEQQFqIQQgAkEBaiICIANHDQALIAchBiADIQILIABBATYCACABIAY2AgAgACACNgIEDwsgAUEANgIAIAAgBDYCACAAIAI2AgQLCgAgABDHgICAAAvyNgELfyOAgICAAEEQayIBJICAgIAAAkBBACgCoNCAgAANAEEAEMuAgIAAQYDUhIAAayICQdkASQ0AQQAhAwJAQQAoAuDTgIAAIgQNAEEAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEIakFwcUHYqtWqBXMiBDYC4NOAgABBAEEANgL004CAAEEAQQA2AsTTgIAAC0EAIAI2AszTgIAAQQBBgNSEgAA2AsjTgIAAQQBBgNSEgAA2ApjQgIAAQQAgBDYCrNCAgABBAEF/NgKo0ICAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALQYDUhIAAQXhBgNSEgABrQQ9xQQBBgNSEgABBCGpBD3EbIgNqIgRBBGogAkFIaiIFIANrIgNBAXI2AgBBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAQYDUhIAAIAVqQTg2AgQLAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFLDQACQEEAKAKI0ICAACIGQRAgAEETakFwcSAAQQtJGyICQQN2IgR2IgNBA3FFDQACQAJAIANBAXEgBHJBAXMiBUEDdCIEQbDQgIAAaiIDIARBuNCAgABqKAIAIgQoAggiAkcNAEEAIAZBfiAFd3E2AojQgIAADAELIAMgAjYCCCACIAM2AgwLIARBCGohAyAEIAVBA3QiBUEDcjYCBCAEIAVqIgQgBCgCBEEBcjYCBAwMCyACQQAoApDQgIAAIgdNDQECQCADRQ0AAkACQCADIAR0QQIgBHQiA0EAIANrcnEiA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqIgRBA3QiA0Gw0ICAAGoiBSADQbjQgIAAaigCACIDKAIIIgBHDQBBACAGQX4gBHdxIgY2AojQgIAADAELIAUgADYCCCAAIAU2AgwLIAMgAkEDcjYCBCADIARBA3QiBGogBCACayIFNgIAIAMgAmoiACAFQQFyNgIEAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQQCQAJAIAZBASAHQQN2dCIIcQ0AQQAgBiAIcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCAENgIMIAIgBDYCCCAEIAI2AgwgBCAINgIICyADQQhqIQNBACAANgKc0ICAAEEAIAU2ApDQgIAADAwLQQAoAozQgIAAIglFDQEgCUEAIAlrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqQQJ0QbjSgIAAaigCACIAKAIEQXhxIAJrIQQgACEFAkADQAJAIAUoAhAiAw0AIAVBFGooAgAiA0UNAgsgAygCBEF4cSACayIFIAQgBSAESSIFGyEEIAMgACAFGyEAIAMhBQwACwsgACgCGCEKAkAgACgCDCIIIABGDQAgACgCCCIDQQAoApjQgIAASRogCCADNgIIIAMgCDYCDAwLCwJAIABBFGoiBSgCACIDDQAgACgCECIDRQ0DIABBEGohBQsDQCAFIQsgAyIIQRRqIgUoAgAiAw0AIAhBEGohBSAIKAIQIgMNAAsgC0EANgIADAoLQX8hAiAAQb9/Sw0AIABBE2oiA0FwcSECQQAoAozQgIAAIgdFDQBBACELAkAgAkGAAkkNAEEfIQsgAkH///8HSw0AIANBCHYiAyADQYD+P2pBEHZBCHEiA3QiBCAEQYDgH2pBEHZBBHEiBHQiBSAFQYCAD2pBEHZBAnEiBXRBD3YgAyAEciAFcmsiA0EBdCACIANBFWp2QQFxckEcaiELC0EAIAJrIQQCQAJAAkACQCALQQJ0QbjSgIAAaigCACIFDQBBACEDQQAhCAwBC0EAIQMgAkEAQRkgC0EBdmsgC0EfRht0IQBBACEIA0ACQCAFKAIEQXhxIAJrIgYgBE8NACAGIQQgBSEIIAYNAEEAIQQgBSEIIAUhAwwDCyADIAVBFGooAgAiBiAGIAUgAEEddkEEcWpBEGooAgAiBUYbIAMgBhshAyAAQQF0IQAgBQ0ACwsCQCADIAhyDQBBACEIQQIgC3QiA0EAIANrciAHcSIDRQ0DIANBACADa3FBf2oiAyADQQx2QRBxIgN2IgVBBXZBCHEiACADciAFIAB2IgNBAnZBBHEiBXIgAyAFdiIDQQF2QQJxIgVyIAMgBXYiA0EBdkEBcSIFciADIAV2akECdEG40oCAAGooAgAhAwsgA0UNAQsDQCADKAIEQXhxIAJrIgYgBEkhAAJAIAMoAhAiBQ0AIANBFGooAgAhBQsgBiAEIAAbIQQgAyAIIAAbIQggBSEDIAUNAAsLIAhFDQAgBEEAKAKQ0ICAACACa08NACAIKAIYIQsCQCAIKAIMIgAgCEYNACAIKAIIIgNBACgCmNCAgABJGiAAIAM2AgggAyAANgIMDAkLAkAgCEEUaiIFKAIAIgMNACAIKAIQIgNFDQMgCEEQaiEFCwNAIAUhBiADIgBBFGoiBSgCACIDDQAgAEEQaiEFIAAoAhAiAw0ACyAGQQA2AgAMCAsCQEEAKAKQ0ICAACIDIAJJDQBBACgCnNCAgAAhBAJAAkAgAyACayIFQRBJDQAgBCACaiIAIAVBAXI2AgRBACAFNgKQ0ICAAEEAIAA2ApzQgIAAIAQgA2ogBTYCACAEIAJBA3I2AgQMAQsgBCADQQNyNgIEIAQgA2oiAyADKAIEQQFyNgIEQQBBADYCnNCAgABBAEEANgKQ0ICAAAsgBEEIaiEDDAoLAkBBACgClNCAgAAiACACTQ0AQQAoAqDQgIAAIgMgAmoiBCAAIAJrIgVBAXI2AgRBACAFNgKU0ICAAEEAIAQ2AqDQgIAAIAMgAkEDcjYCBCADQQhqIQMMCgsCQAJAQQAoAuDTgIAARQ0AQQAoAujTgIAAIQQMAQtBAEJ/NwLs04CAAEEAQoCAhICAgMAANwLk04CAAEEAIAFBDGpBcHFB2KrVqgVzNgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgABBgIAEIQQLQQAhAwJAIAQgAkHHAGoiB2oiBkEAIARrIgtxIgggAksNAEEAQTA2AvjTgIAADAoLAkBBACgCwNOAgAAiA0UNAAJAQQAoArjTgIAAIgQgCGoiBSAETQ0AIAUgA00NAQtBACEDQQBBMDYC+NOAgAAMCgtBAC0AxNOAgABBBHENBAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQAJAIAMoAgAiBSAESw0AIAUgAygCBGogBEsNAwsgAygCCCIDDQALC0EAEMuAgIAAIgBBf0YNBSAIIQYCQEEAKALk04CAACIDQX9qIgQgAHFFDQAgCCAAayAEIABqQQAgA2txaiEGCyAGIAJNDQUgBkH+////B0sNBQJAQQAoAsDTgIAAIgNFDQBBACgCuNOAgAAiBCAGaiIFIARNDQYgBSADSw0GCyAGEMuAgIAAIgMgAEcNAQwHCyAGIABrIAtxIgZB/v///wdLDQQgBhDLgICAACIAIAMoAgAgAygCBGpGDQMgACEDCwJAIANBf0YNACACQcgAaiAGTQ0AAkAgByAGa0EAKALo04CAACIEakEAIARrcSIEQf7///8HTQ0AIAMhAAwHCwJAIAQQy4CAgABBf0YNACAEIAZqIQYgAyEADAcLQQAgBmsQy4CAgAAaDAQLIAMhACADQX9HDQUMAwtBACEIDAcLQQAhAAwFCyAAQX9HDQILQQBBACgCxNOAgABBBHI2AsTTgIAACyAIQf7///8HSw0BIAgQy4CAgAAhAEEAEMuAgIAAIQMgAEF/Rg0BIANBf0YNASAAIANPDQEgAyAAayIGIAJBOGpNDQELQQBBACgCuNOAgAAgBmoiAzYCuNOAgAACQCADQQAoArzTgIAATQ0AQQAgAzYCvNOAgAALAkACQAJAAkBBACgCoNCAgAAiBEUNAEHI04CAACEDA0AgACADKAIAIgUgAygCBCIIakYNAiADKAIIIgMNAAwDCwsCQAJAQQAoApjQgIAAIgNFDQAgACADTw0BC0EAIAA2ApjQgIAAC0EAIQNBACAGNgLM04CAAEEAIAA2AsjTgIAAQQBBfzYCqNCAgABBAEEAKALg04CAADYCrNCAgABBAEEANgLU04CAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgQgBkFIaiIFIANrIgNBAXI2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAIAAgBWpBODYCBAwCCyADLQAMQQhxDQAgBCAFSQ0AIAQgAE8NACAEQXggBGtBD3FBACAEQQhqQQ9xGyIFaiIAQQAoApTQgIAAIAZqIgsgBWsiBUEBcjYCBCADIAggBmo2AgRBAEEAKALw04CAADYCpNCAgABBACAFNgKU0ICAAEEAIAA2AqDQgIAAIAQgC2pBODYCBAwBCwJAIABBACgCmNCAgAAiCE8NAEEAIAA2ApjQgIAAIAAhCAsgACAGaiEFQcjTgIAAIQMCQAJAAkACQAJAAkACQANAIAMoAgAgBUYNASADKAIIIgMNAAwCCwsgAy0ADEEIcUUNAQtByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiIFIARLDQMLIAMoAgghAwwACwsgAyAANgIAIAMgAygCBCAGajYCBCAAQXggAGtBD3FBACAAQQhqQQ9xG2oiCyACQQNyNgIEIAVBeCAFa0EPcUEAIAVBCGpBD3EbaiIGIAsgAmoiAmshAwJAIAYgBEcNAEEAIAI2AqDQgIAAQQBBACgClNCAgAAgA2oiAzYClNCAgAAgAiADQQFyNgIEDAMLAkAgBkEAKAKc0ICAAEcNAEEAIAI2ApzQgIAAQQBBACgCkNCAgAAgA2oiAzYCkNCAgAAgAiADQQFyNgIEIAIgA2ogAzYCAAwDCwJAIAYoAgQiBEEDcUEBRw0AIARBeHEhBwJAAkAgBEH/AUsNACAGKAIIIgUgBEEDdiIIQQN0QbDQgIAAaiIARhoCQCAGKAIMIgQgBUcNAEEAQQAoAojQgIAAQX4gCHdxNgKI0ICAAAwCCyAEIABGGiAEIAU2AgggBSAENgIMDAELIAYoAhghCQJAAkAgBigCDCIAIAZGDQAgBigCCCIEIAhJGiAAIAQ2AgggBCAANgIMDAELAkAgBkEUaiIEKAIAIgUNACAGQRBqIgQoAgAiBQ0AQQAhAAwBCwNAIAQhCCAFIgBBFGoiBCgCACIFDQAgAEEQaiEEIAAoAhAiBQ0ACyAIQQA2AgALIAlFDQACQAJAIAYgBigCHCIFQQJ0QbjSgIAAaiIEKAIARw0AIAQgADYCACAADQFBAEEAKAKM0ICAAEF+IAV3cTYCjNCAgAAMAgsgCUEQQRQgCSgCECAGRhtqIAA2AgAgAEUNAQsgACAJNgIYAkAgBigCECIERQ0AIAAgBDYCECAEIAA2AhgLIAYoAhQiBEUNACAAQRRqIAQ2AgAgBCAANgIYCyAHIANqIQMgBiAHaiIGKAIEIQQLIAYgBEF+cTYCBCACIANqIAM2AgAgAiADQQFyNgIEAkAgA0H/AUsNACADQXhxQbDQgIAAaiEEAkACQEEAKAKI0ICAACIFQQEgA0EDdnQiA3ENAEEAIAUgA3I2AojQgIAAIAQhAwwBCyAEKAIIIQMLIAMgAjYCDCAEIAI2AgggAiAENgIMIAIgAzYCCAwDC0EfIQQCQCADQf///wdLDQAgA0EIdiIEIARBgP4/akEQdkEIcSIEdCIFIAVBgOAfakEQdkEEcSIFdCIAIABBgIAPakEQdkECcSIAdEEPdiAEIAVyIAByayIEQQF0IAMgBEEVanZBAXFyQRxqIQQLIAIgBDYCHCACQgA3AhAgBEECdEG40oCAAGohBQJAQQAoAozQgIAAIgBBASAEdCIIcQ0AIAUgAjYCAEEAIAAgCHI2AozQgIAAIAIgBTYCGCACIAI2AgggAiACNgIMDAMLIANBAEEZIARBAXZrIARBH0YbdCEEIAUoAgAhAANAIAAiBSgCBEF4cSADRg0CIARBHXYhACAEQQF0IQQgBSAAQQRxakEQaiIIKAIAIgANAAsgCCACNgIAIAIgBTYCGCACIAI2AgwgAiACNgIIDAILIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgsgBkFIaiIIIANrIgNBAXI2AgQgACAIakE4NgIEIAQgBUE3IAVrQQ9xQQAgBUFJakEPcRtqQUFqIgggCCAEQRBqSRsiCEEjNgIEQQBBACgC8NOAgAA2AqTQgIAAQQAgAzYClNCAgABBACALNgKg0ICAACAIQRBqQQApAtDTgIAANwIAIAhBACkCyNOAgAA3AghBACAIQQhqNgLQ04CAAEEAIAY2AszTgIAAQQAgADYCyNOAgABBAEEANgLU04CAACAIQSRqIQMDQCADQQc2AgAgA0EEaiIDIAVJDQALIAggBEYNAyAIIAgoAgRBfnE2AgQgCCAIIARrIgA2AgAgBCAAQQFyNgIEAkAgAEH/AUsNACAAQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgAEEDdnQiAHENAEEAIAUgAHI2AojQgIAAIAMhBQwBCyADKAIIIQULIAUgBDYCDCADIAQ2AgggBCADNgIMIAQgBTYCCAwEC0EfIQMCQCAAQf///wdLDQAgAEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCIIIAhBgIAPakEQdkECcSIIdEEPdiADIAVyIAhyayIDQQF0IAAgA0EVanZBAXFyQRxqIQMLIAQgAzYCHCAEQgA3AhAgA0ECdEG40oCAAGohBQJAQQAoAozQgIAAIghBASADdCIGcQ0AIAUgBDYCAEEAIAggBnI2AozQgIAAIAQgBTYCGCAEIAQ2AgggBCAENgIMDAQLIABBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhCANAIAgiBSgCBEF4cSAARg0DIANBHXYhCCADQQF0IQMgBSAIQQRxakEQaiIGKAIAIggNAAsgBiAENgIAIAQgBTYCGCAEIAQ2AgwgBCAENgIIDAMLIAUoAggiAyACNgIMIAUgAjYCCCACQQA2AhggAiAFNgIMIAIgAzYCCAsgC0EIaiEDDAULIAUoAggiAyAENgIMIAUgBDYCCCAEQQA2AhggBCAFNgIMIAQgAzYCCAtBACgClNCAgAAiAyACTQ0AQQAoAqDQgIAAIgQgAmoiBSADIAJrIgNBAXI2AgRBACADNgKU0ICAAEEAIAU2AqDQgIAAIAQgAkEDcjYCBCAEQQhqIQMMAwtBACEDQQBBMDYC+NOAgAAMAgsCQCALRQ0AAkACQCAIIAgoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAA2AgAgAA0BQQAgB0F+IAV3cSIHNgKM0ICAAAwCCyALQRBBFCALKAIQIAhGG2ogADYCACAARQ0BCyAAIAs2AhgCQCAIKAIQIgNFDQAgACADNgIQIAMgADYCGAsgCEEUaigCACIDRQ0AIABBFGogAzYCACADIAA2AhgLAkACQCAEQQ9LDQAgCCAEIAJqIgNBA3I2AgQgCCADaiIDIAMoAgRBAXI2AgQMAQsgCCACaiIAIARBAXI2AgQgCCACQQNyNgIEIAAgBGogBDYCAAJAIARB/wFLDQAgBEF4cUGw0ICAAGohAwJAAkBBACgCiNCAgAAiBUEBIARBA3Z0IgRxDQBBACAFIARyNgKI0ICAACADIQQMAQsgAygCCCEECyAEIAA2AgwgAyAANgIIIAAgAzYCDCAAIAQ2AggMAQtBHyEDAkAgBEH///8HSw0AIARBCHYiAyADQYD+P2pBEHZBCHEiA3QiBSAFQYDgH2pBEHZBBHEiBXQiAiACQYCAD2pBEHZBAnEiAnRBD3YgAyAFciACcmsiA0EBdCAEIANBFWp2QQFxckEcaiEDCyAAIAM2AhwgAEIANwIQIANBAnRBuNKAgABqIQUCQCAHQQEgA3QiAnENACAFIAA2AgBBACAHIAJyNgKM0ICAACAAIAU2AhggACAANgIIIAAgADYCDAwBCyAEQQBBGSADQQF2ayADQR9GG3QhAyAFKAIAIQICQANAIAIiBSgCBEF4cSAERg0BIANBHXYhAiADQQF0IQMgBSACQQRxakEQaiIGKAIAIgINAAsgBiAANgIAIAAgBTYCGCAAIAA2AgwgACAANgIIDAELIAUoAggiAyAANgIMIAUgADYCCCAAQQA2AhggACAFNgIMIAAgAzYCCAsgCEEIaiEDDAELAkAgCkUNAAJAAkAgACAAKAIcIgVBAnRBuNKAgABqIgMoAgBHDQAgAyAINgIAIAgNAUEAIAlBfiAFd3E2AozQgIAADAILIApBEEEUIAooAhAgAEYbaiAINgIAIAhFDQELIAggCjYCGAJAIAAoAhAiA0UNACAIIAM2AhAgAyAINgIYCyAAQRRqKAIAIgNFDQAgCEEUaiADNgIAIAMgCDYCGAsCQAJAIARBD0sNACAAIAQgAmoiA0EDcjYCBCAAIANqIgMgAygCBEEBcjYCBAwBCyAAIAJqIgUgBEEBcjYCBCAAIAJBA3I2AgQgBSAEaiAENgIAAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQMCQAJAQQEgB0EDdnQiCCAGcQ0AQQAgCCAGcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCADNgIMIAIgAzYCCCADIAI2AgwgAyAINgIIC0EAIAU2ApzQgIAAQQAgBDYCkNCAgAALIABBCGohAwsgAUEQaiSAgICAACADCwoAIAAQyYCAgAAL4g0BB38CQCAARQ0AIABBeGoiASAAQXxqKAIAIgJBeHEiAGohAwJAIAJBAXENACACQQNxRQ0BIAEgASgCACICayIBQQAoApjQgIAAIgRJDQEgAiAAaiEAAkAgAUEAKAKc0ICAAEYNAAJAIAJB/wFLDQAgASgCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgASgCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAwsgAiAGRhogAiAENgIIIAQgAjYCDAwCCyABKAIYIQcCQAJAIAEoAgwiBiABRg0AIAEoAggiAiAESRogBiACNgIIIAIgBjYCDAwBCwJAIAFBFGoiAigCACIEDQAgAUEQaiICKAIAIgQNAEEAIQYMAQsDQCACIQUgBCIGQRRqIgIoAgAiBA0AIAZBEGohAiAGKAIQIgQNAAsgBUEANgIACyAHRQ0BAkACQCABIAEoAhwiBEECdEG40oCAAGoiAigCAEcNACACIAY2AgAgBg0BQQBBACgCjNCAgABBfiAEd3E2AozQgIAADAMLIAdBEEEUIAcoAhAgAUYbaiAGNgIAIAZFDQILIAYgBzYCGAJAIAEoAhAiAkUNACAGIAI2AhAgAiAGNgIYCyABKAIUIgJFDQEgBkEUaiACNgIAIAIgBjYCGAwBCyADKAIEIgJBA3FBA0cNACADIAJBfnE2AgRBACAANgKQ0ICAACABIABqIAA2AgAgASAAQQFyNgIEDwsgASADTw0AIAMoAgQiAkEBcUUNAAJAAkAgAkECcQ0AAkAgA0EAKAKg0ICAAEcNAEEAIAE2AqDQgIAAQQBBACgClNCAgAAgAGoiADYClNCAgAAgASAAQQFyNgIEIAFBACgCnNCAgABHDQNBAEEANgKQ0ICAAEEAQQA2ApzQgIAADwsCQCADQQAoApzQgIAARw0AQQAgATYCnNCAgABBAEEAKAKQ0ICAACAAaiIANgKQ0ICAACABIABBAXI2AgQgASAAaiAANgIADwsgAkF4cSAAaiEAAkACQCACQf8BSw0AIAMoAggiBCACQQN2IgVBA3RBsNCAgABqIgZGGgJAIAMoAgwiAiAERw0AQQBBACgCiNCAgABBfiAFd3E2AojQgIAADAILIAIgBkYaIAIgBDYCCCAEIAI2AgwMAQsgAygCGCEHAkACQCADKAIMIgYgA0YNACADKAIIIgJBACgCmNCAgABJGiAGIAI2AgggAiAGNgIMDAELAkAgA0EUaiICKAIAIgQNACADQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQACQAJAIAMgAygCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAgsgB0EQQRQgBygCECADRhtqIAY2AgAgBkUNAQsgBiAHNgIYAkAgAygCECICRQ0AIAYgAjYCECACIAY2AhgLIAMoAhQiAkUNACAGQRRqIAI2AgAgAiAGNgIYCyABIABqIAA2AgAgASAAQQFyNgIEIAFBACgCnNCAgABHDQFBACAANgKQ0ICAAA8LIAMgAkF+cTYCBCABIABqIAA2AgAgASAAQQFyNgIECwJAIABB/wFLDQAgAEF4cUGw0ICAAGohAgJAAkBBACgCiNCAgAAiBEEBIABBA3Z0IgBxDQBBACAEIAByNgKI0ICAACACIQAMAQsgAigCCCEACyAAIAE2AgwgAiABNgIIIAEgAjYCDCABIAA2AggPC0EfIQICQCAAQf///wdLDQAgAEEIdiICIAJBgP4/akEQdkEIcSICdCIEIARBgOAfakEQdkEEcSIEdCIGIAZBgIAPakEQdkECcSIGdEEPdiACIARyIAZyayICQQF0IAAgAkEVanZBAXFyQRxqIQILIAEgAjYCHCABQgA3AhAgAkECdEG40oCAAGohBAJAAkBBACgCjNCAgAAiBkEBIAJ0IgNxDQAgBCABNgIAQQAgBiADcjYCjNCAgAAgASAENgIYIAEgATYCCCABIAE2AgwMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgBCgCACEGAkADQCAGIgQoAgRBeHEgAEYNASACQR12IQYgAkEBdCECIAQgBkEEcWpBEGoiAygCACIGDQALIAMgATYCACABIAQ2AhggASABNgIMIAEgATYCCAwBCyAEKAIIIgAgATYCDCAEIAE2AgggAUEANgIYIAEgBDYCDCABIAA2AggLQQBBACgCqNCAgABBf2oiAUF/IAEbNgKo0ICAAAsLBAAAAAtOAAJAIAANAD8AQRB0DwsCQCAAQf//A3ENACAAQX9MDQACQCAAQRB2QAAiAEF/Rw0AQQBBMDYC+NOAgABBfw8LIABBEHQPCxDKgICAAAAL8gICA38BfgJAIAJFDQAgACABOgAAIAIgAGoiA0F/aiABOgAAIAJBA0kNACAAIAE6AAIgACABOgABIANBfWogAToAACADQX5qIAE6AAAgAkEHSQ0AIAAgAToAAyADQXxqIAE6AAAgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIFayICQSBJDQAgAa1CgYCAgBB+IQYgAyAFaiEBA0AgASAGNwMYIAEgBjcDECABIAY3AwggASAGNwMAIAFBIGohASACQWBqIgJBH0sNAAsLIAALC45IAQBBgAgLhkgBAAAAAgAAAAMAAAAAAAAAAAAAAAQAAAAFAAAAAAAAAAAAAAAGAAAABwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEludmFsaWQgY2hhciBpbiB1cmwgcXVlcnkAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9ib2R5AENvbnRlbnQtTGVuZ3RoIG92ZXJmbG93AENodW5rIHNpemUgb3ZlcmZsb3cAUmVzcG9uc2Ugb3ZlcmZsb3cASW52YWxpZCBtZXRob2QgZm9yIEhUVFAveC54IHJlcXVlc3QASW52YWxpZCBtZXRob2QgZm9yIFJUU1AveC54IHJlcXVlc3QARXhwZWN0ZWQgU09VUkNFIG1ldGhvZCBmb3IgSUNFL3gueCByZXF1ZXN0AEludmFsaWQgY2hhciBpbiB1cmwgZnJhZ21lbnQgc3RhcnQARXhwZWN0ZWQgZG90AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fc3RhdHVzAEludmFsaWQgcmVzcG9uc2Ugc3RhdHVzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABEdXBsaWNhdGUgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyIGluIHVybCBwYXRoAENvbnRlbnQtTGVuZ3RoIGNhbid0IGJlIHByZXNlbnQgd2l0aCBUcmFuc2Zlci1FbmNvZGluZwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBzaXplAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX3ZhbHVlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgdmFsdWUATWlzc2luZyBleHBlY3RlZCBMRiBhZnRlciBoZWFkZXIgdmFsdWUASW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fbmFtZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIG5hbWUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAXhMAACYTAAAwEAAA8BcAAJ0TAAAVEgAAORcAAPASAAAKEAAAdRIAAK0SAACCEwAATxQAAH8QAACgFQAAIxQAAIkSAACLFAAATRUAANQRAADPFAAAEBgAAMkWAADcFgAAwREAAOAXAAC7FAAAdBQAAHwVAADlFAAACBcAAB8QAABlFQAAoxQAACgVAAACFQAAmRUAACwQAACLGQAATw8AANQOAABqEAAAzhAAAAIXAACJDgAAbhMAABwTAABmFAAAVhcAAMETAADNEwAAbBMAAGgXAABmFwAAXxcAACITAADODwAAaQ4AANgOAABjFgAAyxMAAKoOAAAoFwAAJhcAAMUTAABdFgAA6BEAAGcTAABlEwAA8hYAAHMTAAAdFwAA+RYAAPMRAADPDgAAzhUAAAwSAACzEQAApREAAGEQAAAyFwAAuxMAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIDAgICAgIAAAICAAICAAICAgICAgICAgIABAAAAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAACAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbG9zZWVlcC1hbGl2ZQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AAAAAAAAAAAAAAAAAAAByYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AAAAAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQIAAQMAAAAAAAAAAAAAAAAAAAAAAAAEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAQAAAgAAAAAAAAAAAAAAAAAAAAAAAAMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='\n","module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCrLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AcsBygG4AckBuQHIAboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBANwBC0EAIRAMxgELQQ4hEAzFAQtBDSEQDMQBC0EPIRAMwwELQRAhEAzCAQtBEyEQDMEBC0EUIRAMwAELQRUhEAy/AQtBFiEQDL4BC0EXIRAMvQELQRghEAy8AQtBGSEQDLsBC0EaIRAMugELQRshEAy5AQtBHCEQDLgBC0EIIRAMtwELQR0hEAy2AQtBICEQDLUBC0EfIRAMtAELQQchEAyzAQtBISEQDLIBC0EiIRAMsQELQR4hEAywAQtBIyEQDK8BC0ESIRAMrgELQREhEAytAQtBJCEQDKwBC0ElIRAMqwELQSYhEAyqAQtBJyEQDKkBC0HDASEQDKgBC0EpIRAMpwELQSshEAymAQtBLCEQDKUBC0EtIRAMpAELQS4hEAyjAQtBLyEQDKIBC0HEASEQDKEBC0EwIRAMoAELQTQhEAyfAQtBDCEQDJ4BC0ExIRAMnQELQTIhEAycAQtBMyEQDJsBC0E5IRAMmgELQTUhEAyZAQtBxQEhEAyYAQtBCyEQDJcBC0E6IRAMlgELQTYhEAyVAQtBCiEQDJQBC0E3IRAMkwELQTghEAySAQtBPCEQDJEBC0E7IRAMkAELQT0hEAyPAQtBCSEQDI4BC0EoIRAMjQELQT4hEAyMAQtBPyEQDIsBC0HAACEQDIoBC0HBACEQDIkBC0HCACEQDIgBC0HDACEQDIcBC0HEACEQDIYBC0HFACEQDIUBC0HGACEQDIQBC0EqIRAMgwELQccAIRAMggELQcgAIRAMgQELQckAIRAMgAELQcoAIRAMfwtBywAhEAx+C0HNACEQDH0LQcwAIRAMfAtBzgAhEAx7C0HPACEQDHoLQdAAIRAMeQtB0QAhEAx4C0HSACEQDHcLQdMAIRAMdgtB1AAhEAx1C0HWACEQDHQLQdUAIRAMcwtBBiEQDHILQdcAIRAMcQtBBSEQDHALQdgAIRAMbwtBBCEQDG4LQdkAIRAMbQtB2gAhEAxsC0HbACEQDGsLQdwAIRAMagtBAyEQDGkLQd0AIRAMaAtB3gAhEAxnC0HfACEQDGYLQeEAIRAMZQtB4AAhEAxkC0HiACEQDGMLQeMAIRAMYgtBAiEQDGELQeQAIRAMYAtB5QAhEAxfC0HmACEQDF4LQecAIRAMXQtB6AAhEAxcC0HpACEQDFsLQeoAIRAMWgtB6wAhEAxZC0HsACEQDFgLQe0AIRAMVwtB7gAhEAxWC0HvACEQDFULQfAAIRAMVAtB8QAhEAxTC0HyACEQDFILQfMAIRAMUQtB9AAhEAxQC0H1ACEQDE8LQfYAIRAMTgtB9wAhEAxNC0H4ACEQDEwLQfkAIRAMSwtB+gAhEAxKC0H7ACEQDEkLQfwAIRAMSAtB/QAhEAxHC0H+ACEQDEYLQf8AIRAMRQtBgAEhEAxEC0GBASEQDEMLQYIBIRAMQgtBgwEhEAxBC0GEASEQDEALQYUBIRAMPwtBhgEhEAw+C0GHASEQDD0LQYgBIRAMPAtBiQEhEAw7C0GKASEQDDoLQYsBIRAMOQtBjAEhEAw4C0GNASEQDDcLQY4BIRAMNgtBjwEhEAw1C0GQASEQDDQLQZEBIRAMMwtBkgEhEAwyC0GTASEQDDELQZQBIRAMMAtBlQEhEAwvC0GWASEQDC4LQZcBIRAMLQtBmAEhEAwsC0GZASEQDCsLQZoBIRAMKgtBmwEhEAwpC0GcASEQDCgLQZ0BIRAMJwtBngEhEAwmC0GfASEQDCULQaABIRAMJAtBoQEhEAwjC0GiASEQDCILQaMBIRAMIQtBpAEhEAwgC0GlASEQDB8LQaYBIRAMHgtBpwEhEAwdC0GoASEQDBwLQakBIRAMGwtBqgEhEAwaC0GrASEQDBkLQawBIRAMGAtBrQEhEAwXC0GuASEQDBYLQQEhEAwVC0GvASEQDBQLQbABIRAMEwtBsQEhEAwSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB4fICEjJSg/QEFERUZHSElKS0xNT1BRUlPeA1dZW1xdYGJlZmdoaWprbG1vcHFyc3R1dnd4eXp7fH1+gAGCAYUBhgGHAYkBiwGMAY0BjgGPAZABkQGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwG4AbkBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgHHAcgByQHKAcsBzAHNAc4BzwHQAdEB0gHTAdQB1QHWAdcB2AHZAdoB2wHcAd0B3gHgAeEB4gHjAeQB5QHmAecB6AHpAeoB6wHsAe0B7gHvAfAB8QHyAfMBmQKkArAC/gL+AgsgASIEIAJHDfMBQd0BIRAM/wMLIAEiECACRw3dAUHDASEQDP4DCyABIgEgAkcNkAFB9wAhEAz9AwsgASIBIAJHDYYBQe8AIRAM/AMLIAEiASACRw1/QeoAIRAM+wMLIAEiASACRw17QegAIRAM+gMLIAEiASACRw14QeYAIRAM+QMLIAEiASACRw0aQRghEAz4AwsgASIBIAJHDRRBEiEQDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg0AIABBi4CAgAA2AgggACABNgIEIAEhAUEHIRAMxAMLQRkhEAzcAwsgAUEBaiEBDAILAkAgASIUIAJHDQBBGiEQDNsDCyAUIQECQCAULQAAQXNqDhTdAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAgDuAgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQM2gMLAkAgAS0AACIQQTtGDQAgEEENRw3oASABQQFqIQEM5QILIAFBAWohAQtBIiEQDL8DCwJAIAEiECACRw0AQRwhEAzYAwtCACERIBAhASAQLQAAQVBqDjfnAeYBAQIDBAUGBwgAAAAAAAAACQoLDA0OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPEBESExQAC0EeIRAMvQMLQgIhEQzlAQtCAyERDOQBC0IEIREM4wELQgUhEQziAQtCBiERDOEBC0IHIREM4AELQgghEQzfAQtCCSERDN4BC0IKIREM3QELQgshEQzcAQtCDCERDNsBC0INIREM2gELQg4hEQzZAQtCDyERDNgBC0IKIREM1wELQgshEQzWAQtCDCERDNUBC0INIREM1AELQg4hEQzTAQtCDyERDNIBC0IAIRECQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAtAABBUGoON+UB5AEAAQIDBAUGB+YB5gHmAeYB5gHmAeYBCAkKCwwN5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAQ4PEBESE+YBC0ICIREM5AELQgMhEQzjAQtCBCERDOIBC0IFIREM4QELQgYhEQzgAQtCByERDN8BC0IIIREM3gELQgkhEQzdAQtCCiERDNwBC0ILIREM2wELQgwhEQzaAQtCDSERDNkBC0IOIREM2AELQg8hEQzXAQtCCiERDNYBC0ILIREM1QELQgwhEQzUAQtCDSERDNMBC0IOIREM0gELQg8hEQzRAQsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3SAUEfIRAMwAMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQSQhEAynAwtBICEQDL8DCyAAIAEiECACEL6AgIAAQX9qDgW2AQDFAgHRAdIBC0ERIRAMpAMLIABBAToALyAQIQEMuwMLIAEiASACRw3SAUEkIRAMuwMLIAEiDSACRw0eQcYAIRAMugMLIAAgASIBIAIQsoCAgAAiEA3UASABIQEMtQELIAEiECACRw0mQdAAIRAMuAMLAkAgASIBIAJHDQBBKCEQDLgDCyAAQQA2AgQgAEGMgICAADYCCCAAIAEgARCxgICAACIQDdMBIAEhAQzYAQsCQCABIhAgAkcNAEEpIRAMtwMLIBAtAAAiAUEgRg0UIAFBCUcN0wEgEEEBaiEBDBULAkAgASIBIAJGDQAgAUEBaiEBDBcLQSohEAy1AwsCQCABIhAgAkcNAEErIRAMtQMLAkAgEC0AACIBQQlGDQAgAUEgRw3VAQsgAC0ALEEIRg3TASAQIQEMkQMLAkAgASIBIAJHDQBBLCEQDLQDCyABLQAAQQpHDdUBIAFBAWohAQzJAgsgASIOIAJHDdUBQS8hEAyyAwsDQAJAIAEtAAAiEEEgRg0AAkAgEEF2ag4EANwB3AEA2gELIAEhAQzgAQsgAUEBaiIBIAJHDQALQTEhEAyxAwtBMiEQIAEiFCACRg2wAyACIBRrIAAoAgAiAWohFSAUIAFrQQNqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB8LuAgABqLQAARw0BAkAgAUEDRw0AQQYhAQyWAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMsQMLIABBADYCACAUIQEM2QELQTMhECABIhQgAkYNrwMgAiAUayAAKAIAIgFqIRUgFCABa0EIaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfS7gIAAai0AAEcNAQJAIAFBCEcNAEEFIQEMlQMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLADCyAAQQA2AgAgFCEBDNgBC0E0IRAgASIUIAJGDa4DIAIgFGsgACgCACIBaiEVIBQgAWtBBWohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUHQwoCAAGotAABHDQECQCABQQVHDQBBByEBDJQDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAyvAwsgAEEANgIAIBQhAQzXAQsCQCABIgEgAkYNAANAAkAgAS0AAEGAvoCAAGotAAAiEEEBRg0AIBBBAkYNCiABIQEM3QELIAFBAWoiASACRw0AC0EwIRAMrgMLQTAhEAytAwsCQCABIgEgAkYNAANAAkAgAS0AACIQQSBGDQAgEEF2ag4E2QHaAdoB2QHaAQsgAUEBaiIBIAJHDQALQTghEAytAwtBOCEQDKwDCwNAAkAgAS0AACIQQSBGDQAgEEEJRw0DCyABQQFqIgEgAkcNAAtBPCEQDKsDCwNAAkAgAS0AACIQQSBGDQACQAJAIBBBdmoOBNoBAQHaAQALIBBBLEYN2wELIAEhAQwECyABQQFqIgEgAkcNAAtBPyEQDKoDCyABIQEM2wELQcAAIRAgASIUIAJGDagDIAIgFGsgACgCACIBaiEWIBQgAWtBBmohFwJAA0AgFC0AAEEgciABQYDAgIAAai0AAEcNASABQQZGDY4DIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADKkDCyAAQQA2AgAgFCEBC0E2IRAMjgMLAkAgASIPIAJHDQBBwQAhEAynAwsgAEGMgICAADYCCCAAIA82AgQgDyEBIAAtACxBf2oOBM0B1QHXAdkBhwMLIAFBAWohAQzMAQsCQCABIgEgAkYNAANAAkAgAS0AACIQQSByIBAgEEG/f2pB/wFxQRpJG0H/AXEiEEEJRg0AIBBBIEYNAAJAAkACQAJAIBBBnX9qDhMAAwMDAwMDAwEDAwMDAwMDAwMCAwsgAUEBaiEBQTEhEAyRAwsgAUEBaiEBQTIhEAyQAwsgAUEBaiEBQTMhEAyPAwsgASEBDNABCyABQQFqIgEgAkcNAAtBNSEQDKUDC0E1IRAMpAMLAkAgASIBIAJGDQADQAJAIAEtAABBgLyAgABqLQAAQQFGDQAgASEBDNMBCyABQQFqIgEgAkcNAAtBPSEQDKQDC0E9IRAMowMLIAAgASIBIAIQsICAgAAiEA3WASABIQEMAQsgEEEBaiEBC0E8IRAMhwMLAkAgASIBIAJHDQBBwgAhEAygAwsCQANAAkAgAS0AAEF3ag4YAAL+Av4ChAP+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gIA/gILIAFBAWoiASACRw0AC0HCACEQDKADCyABQQFqIQEgAC0ALUEBcUUNvQEgASEBC0EsIRAMhQMLIAEiASACRw3TAUHEACEQDJ0DCwNAAkAgAS0AAEGQwICAAGotAABBAUYNACABIQEMtwILIAFBAWoiASACRw0AC0HFACEQDJwDCyANLQAAIhBBIEYNswEgEEE6Rw2BAyAAKAIEIQEgAEEANgIEIAAgASANEK+AgIAAIgEN0AEgDUEBaiEBDLMCC0HHACEQIAEiDSACRg2aAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQZDCgIAAai0AAEcNgAMgAUEFRg30AiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyaAwtByAAhECABIg0gAkYNmQMgAiANayAAKAIAIgFqIRYgDSABa0EJaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGWwoCAAGotAABHDf8CAkAgAUEJRw0AQQIhAQz1AgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmQMLAkAgASINIAJHDQBByQAhEAyZAwsCQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZJ/ag4HAIADgAOAA4ADgAMBgAMLIA1BAWohAUE+IRAMgAMLIA1BAWohAUE/IRAM/wILQcoAIRAgASINIAJGDZcDIAIgDWsgACgCACIBaiEWIA0gAWtBAWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBoMKAgABqLQAARw39AiABQQFGDfACIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJcDC0HLACEQIAEiDSACRg2WAyACIA1rIAAoAgAiAWohFiANIAFrQQ5qIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaLCgIAAai0AAEcN/AIgAUEORg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyWAwtBzAAhECABIg0gAkYNlQMgAiANayAAKAIAIgFqIRYgDSABa0EPaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUHAwoCAAGotAABHDfsCAkAgAUEPRw0AQQMhAQzxAgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlQMLQc0AIRAgASINIAJGDZQDIAIgDWsgACgCACIBaiEWIA0gAWtBBWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw36AgJAIAFBBUcNAEEEIQEM8AILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJQDCwJAIAEiDSACRw0AQc4AIRAMlAMLAkACQAJAAkAgDS0AACIBQSByIAEgAUG/f2pB/wFxQRpJG0H/AXFBnX9qDhMA/QL9Av0C/QL9Av0C/QL9Av0C/QL9Av0CAf0C/QL9AgID/QILIA1BAWohAUHBACEQDP0CCyANQQFqIQFBwgAhEAz8AgsgDUEBaiEBQcMAIRAM+wILIA1BAWohAUHEACEQDPoCCwJAIAEiASACRg0AIABBjYCAgAA2AgggACABNgIEIAEhAUHFACEQDPoCC0HPACEQDJIDCyAQIQECQAJAIBAtAABBdmoOBAGoAqgCAKgCCyAQQQFqIQELQSchEAz4AgsCQCABIgEgAkcNAEHRACEQDJEDCwJAIAEtAABBIEYNACABIQEMjQELIAFBAWohASAALQAtQQFxRQ3HASABIQEMjAELIAEiFyACRw3IAUHSACEQDI8DC0HTACEQIAEiFCACRg2OAyACIBRrIAAoAgAiAWohFiAUIAFrQQFqIRcDQCAULQAAIAFB1sKAgABqLQAARw3MASABQQFGDccBIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADI4DCwJAIAEiASACRw0AQdUAIRAMjgMLIAEtAABBCkcNzAEgAUEBaiEBDMcBCwJAIAEiASACRw0AQdYAIRAMjQMLAkACQCABLQAAQXZqDgQAzQHNAQHNAQsgAUEBaiEBDMcBCyABQQFqIQFBygAhEAzzAgsgACABIgEgAhCugICAACIQDcsBIAEhAUHNACEQDPICCyAALQApQSJGDYUDDKYCCwJAIAEiASACRw0AQdsAIRAMigMLQQAhFEEBIRdBASEWQQAhEAJAAkACQAJAAkACQAJAAkACQCABLQAAQVBqDgrUAdMBAAECAwQFBgjVAQtBAiEQDAYLQQMhEAwFC0EEIRAMBAtBBSEQDAMLQQYhEAwCC0EHIRAMAQtBCCEQC0EAIRdBACEWQQAhFAzMAQtBCSEQQQEhFEEAIRdBACEWDMsBCwJAIAEiASACRw0AQd0AIRAMiQMLIAEtAABBLkcNzAEgAUEBaiEBDKYCCyABIgEgAkcNzAFB3wAhEAyHAwsCQCABIgEgAkYNACAAQY6AgIAANgIIIAAgATYCBCABIQFB0AAhEAzuAgtB4AAhEAyGAwtB4QAhECABIgEgAkYNhQMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQeLCgIAAai0AAEcNzQEgFEEDRg3MASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyFAwtB4gAhECABIgEgAkYNhAMgAiABayAAKAIAIhRqIRYgASAUa0ECaiEXA0AgAS0AACAUQebCgIAAai0AAEcNzAEgFEECRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyEAwtB4wAhECABIgEgAkYNgwMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQenCgIAAai0AAEcNywEgFEEDRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyDAwsCQCABIgEgAkcNAEHlACEQDIMDCyAAIAFBAWoiASACEKiAgIAAIhANzQEgASEBQdYAIRAM6QILAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AAkACQAJAIBBBuH9qDgsAAc8BzwHPAc8BzwHPAc8BzwECzwELIAFBAWohAUHSACEQDO0CCyABQQFqIQFB0wAhEAzsAgsgAUEBaiEBQdQAIRAM6wILIAFBAWoiASACRw0AC0HkACEQDIIDC0HkACEQDIEDCwNAAkAgAS0AAEHwwoCAAGotAAAiEEEBRg0AIBBBfmoOA88B0AHRAdIBCyABQQFqIgEgAkcNAAtB5gAhEAyAAwsCQCABIgEgAkYNACABQQFqIQEMAwtB5wAhEAz/AgsDQAJAIAEtAABB8MSAgABqLQAAIhBBAUYNAAJAIBBBfmoOBNIB0wHUAQDVAQsgASEBQdcAIRAM5wILIAFBAWoiASACRw0AC0HoACEQDP4CCwJAIAEiASACRw0AQekAIRAM/gILAkAgAS0AACIQQXZqDhq6AdUB1QG8AdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAcoB1QHVAQDTAQsgAUEBaiEBC0EGIRAM4wILA0ACQCABLQAAQfDGgIAAai0AAEEBRg0AIAEhAQyeAgsgAUEBaiIBIAJHDQALQeoAIRAM+wILAkAgASIBIAJGDQAgAUEBaiEBDAMLQesAIRAM+gILAkAgASIBIAJHDQBB7AAhEAz6AgsgAUEBaiEBDAELAkAgASIBIAJHDQBB7QAhEAz5AgsgAUEBaiEBC0EEIRAM3gILAkAgASIUIAJHDQBB7gAhEAz3AgsgFCEBAkACQAJAIBQtAABB8MiAgABqLQAAQX9qDgfUAdUB1gEAnAIBAtcBCyAUQQFqIQEMCgsgFEEBaiEBDM0BC0EAIRAgAEEANgIcIABBm5KAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAz2AgsCQANAAkAgAS0AAEHwyICAAGotAAAiEEEERg0AAkACQCAQQX9qDgfSAdMB1AHZAQAEAdkBCyABIQFB2gAhEAzgAgsgAUEBaiEBQdwAIRAM3wILIAFBAWoiASACRw0AC0HvACEQDPYCCyABQQFqIQEMywELAkAgASIUIAJHDQBB8AAhEAz1AgsgFC0AAEEvRw3UASAUQQFqIQEMBgsCQCABIhQgAkcNAEHxACEQDPQCCwJAIBQtAAAiAUEvRw0AIBRBAWohAUHdACEQDNsCCyABQXZqIgRBFksN0wFBASAEdEGJgIACcUUN0wEMygILAkAgASIBIAJGDQAgAUEBaiEBQd4AIRAM2gILQfIAIRAM8gILAkAgASIUIAJHDQBB9AAhEAzyAgsgFCEBAkAgFC0AAEHwzICAAGotAABBf2oOA8kClAIA1AELQeEAIRAM2AILAkAgASIUIAJGDQADQAJAIBQtAABB8MqAgABqLQAAIgFBA0YNAAJAIAFBf2oOAssCANUBCyAUIQFB3wAhEAzaAgsgFEEBaiIUIAJHDQALQfMAIRAM8QILQfMAIRAM8AILAkAgASIBIAJGDQAgAEGPgICAADYCCCAAIAE2AgQgASEBQeAAIRAM1wILQfUAIRAM7wILAkAgASIBIAJHDQBB9gAhEAzvAgsgAEGPgICAADYCCCAAIAE2AgQgASEBC0EDIRAM1AILA0AgAS0AAEEgRw3DAiABQQFqIgEgAkcNAAtB9wAhEAzsAgsCQCABIgEgAkcNAEH4ACEQDOwCCyABLQAAQSBHDc4BIAFBAWohAQzvAQsgACABIgEgAhCsgICAACIQDc4BIAEhAQyOAgsCQCABIgQgAkcNAEH6ACEQDOoCCyAELQAAQcwARw3RASAEQQFqIQFBEyEQDM8BCwJAIAEiBCACRw0AQfsAIRAM6QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEANAIAQtAAAgAUHwzoCAAGotAABHDdABIAFBBUYNzgEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBB+wAhEAzoAgsCQCABIgQgAkcNAEH8ACEQDOgCCwJAAkAgBC0AAEG9f2oODADRAdEB0QHRAdEB0QHRAdEB0QHRAQHRAQsgBEEBaiEBQeYAIRAMzwILIARBAWohAUHnACEQDM4CCwJAIAEiBCACRw0AQf0AIRAM5wILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNzwEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf0AIRAM5wILIABBADYCACAQQQFqIQFBECEQDMwBCwJAIAEiBCACRw0AQf4AIRAM5gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQfbOgIAAai0AAEcNzgEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf4AIRAM5gILIABBADYCACAQQQFqIQFBFiEQDMsBCwJAIAEiBCACRw0AQf8AIRAM5QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQfzOgIAAai0AAEcNzQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf8AIRAM5QILIABBADYCACAQQQFqIQFBBSEQDMoBCwJAIAEiBCACRw0AQYABIRAM5AILIAQtAABB2QBHDcsBIARBAWohAUEIIRAMyQELAkAgASIEIAJHDQBBgQEhEAzjAgsCQAJAIAQtAABBsn9qDgMAzAEBzAELIARBAWohAUHrACEQDMoCCyAEQQFqIQFB7AAhEAzJAgsCQCABIgQgAkcNAEGCASEQDOICCwJAAkAgBC0AAEG4f2oOCADLAcsBywHLAcsBywEBywELIARBAWohAUHqACEQDMkCCyAEQQFqIQFB7QAhEAzIAgsCQCABIgQgAkcNAEGDASEQDOECCyACIARrIAAoAgAiAWohECAEIAFrQQJqIRQCQANAIAQtAAAgAUGAz4CAAGotAABHDckBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgEDYCAEGDASEQDOECC0EAIRAgAEEANgIAIBRBAWohAQzGAQsCQCABIgQgAkcNAEGEASEQDOACCyACIARrIAAoAgAiAWohFCAEIAFrQQRqIRACQANAIAQtAAAgAUGDz4CAAGotAABHDcgBIAFBBEYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGEASEQDOACCyAAQQA2AgAgEEEBaiEBQSMhEAzFAQsCQCABIgQgAkcNAEGFASEQDN8CCwJAAkAgBC0AAEG0f2oOCADIAcgByAHIAcgByAEByAELIARBAWohAUHvACEQDMYCCyAEQQFqIQFB8AAhEAzFAgsCQCABIgQgAkcNAEGGASEQDN4CCyAELQAAQcUARw3FASAEQQFqIQEMgwILAkAgASIEIAJHDQBBhwEhEAzdAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBiM+AgABqLQAARw3FASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhwEhEAzdAgsgAEEANgIAIBBBAWohAUEtIRAMwgELAkAgASIEIAJHDQBBiAEhEAzcAgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw3EASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiAEhEAzcAgsgAEEANgIAIBBBAWohAUEpIRAMwQELAkAgASIBIAJHDQBBiQEhEAzbAgtBASEQIAEtAABB3wBHDcABIAFBAWohAQyBAgsCQCABIgQgAkcNAEGKASEQDNoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRADQCAELQAAIAFBjM+AgABqLQAARw3BASABQQFGDa8CIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYoBIRAM2QILAkAgASIEIAJHDQBBiwEhEAzZAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBjs+AgABqLQAARw3BASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiwEhEAzZAgsgAEEANgIAIBBBAWohAUECIRAMvgELAkAgASIEIAJHDQBBjAEhEAzYAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw3AASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjAEhEAzYAgsgAEEANgIAIBBBAWohAUEfIRAMvQELAkAgASIEIAJHDQBBjQEhEAzXAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8s+AgABqLQAARw2/ASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjQEhEAzXAgsgAEEANgIAIBBBAWohAUEJIRAMvAELAkAgASIEIAJHDQBBjgEhEAzWAgsCQAJAIAQtAABBt39qDgcAvwG/Ab8BvwG/AQG/AQsgBEEBaiEBQfgAIRAMvQILIARBAWohAUH5ACEQDLwCCwJAIAEiBCACRw0AQY8BIRAM1QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQZHPgIAAai0AAEcNvQEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY8BIRAM1QILIABBADYCACAQQQFqIQFBGCEQDLoBCwJAIAEiBCACRw0AQZABIRAM1AILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQZfPgIAAai0AAEcNvAEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZABIRAM1AILIABBADYCACAQQQFqIQFBFyEQDLkBCwJAIAEiBCACRw0AQZEBIRAM0wILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQZrPgIAAai0AAEcNuwEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZEBIRAM0wILIABBADYCACAQQQFqIQFBFSEQDLgBCwJAIAEiBCACRw0AQZIBIRAM0gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQaHPgIAAai0AAEcNugEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZIBIRAM0gILIABBADYCACAQQQFqIQFBHiEQDLcBCwJAIAEiBCACRw0AQZMBIRAM0QILIAQtAABBzABHDbgBIARBAWohAUEKIRAMtgELAkAgBCACRw0AQZQBIRAM0AILAkACQCAELQAAQb9/ag4PALkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AbkBAbkBCyAEQQFqIQFB/gAhEAy3AgsgBEEBaiEBQf8AIRAMtgILAkAgBCACRw0AQZUBIRAMzwILAkACQCAELQAAQb9/ag4DALgBAbgBCyAEQQFqIQFB/QAhEAy2AgsgBEEBaiEEQYABIRAMtQILAkAgBCACRw0AQZYBIRAMzgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQafPgIAAai0AAEcNtgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZYBIRAMzgILIABBADYCACAQQQFqIQFBCyEQDLMBCwJAIAQgAkcNAEGXASEQDM0CCwJAAkACQAJAIAQtAABBU2oOIwC4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBAbgBuAG4AbgBuAECuAG4AbgBA7gBCyAEQQFqIQFB+wAhEAy2AgsgBEEBaiEBQfwAIRAMtQILIARBAWohBEGBASEQDLQCCyAEQQFqIQRBggEhEAyzAgsCQCAEIAJHDQBBmAEhEAzMAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBqc+AgABqLQAARw20ASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmAEhEAzMAgsgAEEANgIAIBBBAWohAUEZIRAMsQELAkAgBCACRw0AQZkBIRAMywILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQa7PgIAAai0AAEcNswEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZkBIRAMywILIABBADYCACAQQQFqIQFBBiEQDLABCwJAIAQgAkcNAEGaASEQDMoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG0z4CAAGotAABHDbIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGaASEQDMoCCyAAQQA2AgAgEEEBaiEBQRwhEAyvAQsCQCAEIAJHDQBBmwEhEAzJAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBts+AgABqLQAARw2xASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmwEhEAzJAgsgAEEANgIAIBBBAWohAUEnIRAMrgELAkAgBCACRw0AQZwBIRAMyAILAkACQCAELQAAQax/ag4CAAGxAQsgBEEBaiEEQYYBIRAMrwILIARBAWohBEGHASEQDK4CCwJAIAQgAkcNAEGdASEQDMcCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG4z4CAAGotAABHDa8BIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGdASEQDMcCCyAAQQA2AgAgEEEBaiEBQSYhEAysAQsCQCAEIAJHDQBBngEhEAzGAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBus+AgABqLQAARw2uASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBngEhEAzGAgsgAEEANgIAIBBBAWohAUEDIRAMqwELAkAgBCACRw0AQZ8BIRAMxQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNrQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ8BIRAMxQILIABBADYCACAQQQFqIQFBDCEQDKoBCwJAIAQgAkcNAEGgASEQDMQCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUG8z4CAAGotAABHDawBIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGgASEQDMQCCyAAQQA2AgAgEEEBaiEBQQ0hEAypAQsCQCAEIAJHDQBBoQEhEAzDAgsCQAJAIAQtAABBun9qDgsArAGsAawBrAGsAawBrAGsAawBAawBCyAEQQFqIQRBiwEhEAyqAgsgBEEBaiEEQYwBIRAMqQILAkAgBCACRw0AQaIBIRAMwgILIAQtAABB0ABHDakBIARBAWohBAzpAQsCQCAEIAJHDQBBowEhEAzBAgsCQAJAIAQtAABBt39qDgcBqgGqAaoBqgGqAQCqAQsgBEEBaiEEQY4BIRAMqAILIARBAWohAUEiIRAMpgELAkAgBCACRw0AQaQBIRAMwAILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQcDPgIAAai0AAEcNqAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaQBIRAMwAILIABBADYCACAQQQFqIQFBHSEQDKUBCwJAIAQgAkcNAEGlASEQDL8CCwJAAkAgBC0AAEGuf2oOAwCoAQGoAQsgBEEBaiEEQZABIRAMpgILIARBAWohAUEEIRAMpAELAkAgBCACRw0AQaYBIRAMvgILAkACQAJAAkACQCAELQAAQb9/ag4VAKoBqgGqAaoBqgGqAaoBqgGqAaoBAaoBqgECqgGqAQOqAaoBBKoBCyAEQQFqIQRBiAEhEAyoAgsgBEEBaiEEQYkBIRAMpwILIARBAWohBEGKASEQDKYCCyAEQQFqIQRBjwEhEAylAgsgBEEBaiEEQZEBIRAMpAILAkAgBCACRw0AQacBIRAMvQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNpQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQacBIRAMvQILIABBADYCACAQQQFqIQFBESEQDKIBCwJAIAQgAkcNAEGoASEQDLwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHCz4CAAGotAABHDaQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGoASEQDLwCCyAAQQA2AgAgEEEBaiEBQSwhEAyhAQsCQCAEIAJHDQBBqQEhEAy7AgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBxc+AgABqLQAARw2jASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqQEhEAy7AgsgAEEANgIAIBBBAWohAUErIRAMoAELAkAgBCACRw0AQaoBIRAMugILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQcrPgIAAai0AAEcNogEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaoBIRAMugILIABBADYCACAQQQFqIQFBFCEQDJ8BCwJAIAQgAkcNAEGrASEQDLkCCwJAAkACQAJAIAQtAABBvn9qDg8AAQKkAaQBpAGkAaQBpAGkAaQBpAGkAaQBA6QBCyAEQQFqIQRBkwEhEAyiAgsgBEEBaiEEQZQBIRAMoQILIARBAWohBEGVASEQDKACCyAEQQFqIQRBlgEhEAyfAgsCQCAEIAJHDQBBrAEhEAy4AgsgBC0AAEHFAEcNnwEgBEEBaiEEDOABCwJAIAQgAkcNAEGtASEQDLcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHNz4CAAGotAABHDZ8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGtASEQDLcCCyAAQQA2AgAgEEEBaiEBQQ4hEAycAQsCQCAEIAJHDQBBrgEhEAy2AgsgBC0AAEHQAEcNnQEgBEEBaiEBQSUhEAybAQsCQCAEIAJHDQBBrwEhEAy1AgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw2dASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrwEhEAy1AgsgAEEANgIAIBBBAWohAUEqIRAMmgELAkAgBCACRw0AQbABIRAMtAILAkACQCAELQAAQat/ag4LAJ0BnQGdAZ0BnQGdAZ0BnQGdAQGdAQsgBEEBaiEEQZoBIRAMmwILIARBAWohBEGbASEQDJoCCwJAIAQgAkcNAEGxASEQDLMCCwJAAkAgBC0AAEG/f2oOFACcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAEBnAELIARBAWohBEGZASEQDJoCCyAEQQFqIQRBnAEhEAyZAgsCQCAEIAJHDQBBsgEhEAyyAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFB2c+AgABqLQAARw2aASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBsgEhEAyyAgsgAEEANgIAIBBBAWohAUEhIRAMlwELAkAgBCACRw0AQbMBIRAMsQILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQd3PgIAAai0AAEcNmQEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbMBIRAMsQILIABBADYCACAQQQFqIQFBGiEQDJYBCwJAIAQgAkcNAEG0ASEQDLACCwJAAkACQCAELQAAQbt/ag4RAJoBmgGaAZoBmgGaAZoBmgGaAQGaAZoBmgGaAZoBApoBCyAEQQFqIQRBnQEhEAyYAgsgBEEBaiEEQZ4BIRAMlwILIARBAWohBEGfASEQDJYCCwJAIAQgAkcNAEG1ASEQDK8CCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUHkz4CAAGotAABHDZcBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG1ASEQDK8CCyAAQQA2AgAgEEEBaiEBQSghEAyUAQsCQCAEIAJHDQBBtgEhEAyuAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB6s+AgABqLQAARw2WASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtgEhEAyuAgsgAEEANgIAIBBBAWohAUEHIRAMkwELAkAgBCACRw0AQbcBIRAMrQILAkACQCAELQAAQbt/ag4OAJYBlgGWAZYBlgGWAZYBlgGWAZYBlgGWAQGWAQsgBEEBaiEEQaEBIRAMlAILIARBAWohBEGiASEQDJMCCwJAIAQgAkcNAEG4ASEQDKwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDZQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG4ASEQDKwCCyAAQQA2AgAgEEEBaiEBQRIhEAyRAQsCQCAEIAJHDQBBuQEhEAyrAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw2TASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuQEhEAyrAgsgAEEANgIAIBBBAWohAUEgIRAMkAELAkAgBCACRw0AQboBIRAMqgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNkgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQboBIRAMqgILIABBADYCACAQQQFqIQFBDyEQDI8BCwJAIAQgAkcNAEG7ASEQDKkCCwJAAkAgBC0AAEG3f2oOBwCSAZIBkgGSAZIBAZIBCyAEQQFqIQRBpQEhEAyQAgsgBEEBaiEEQaYBIRAMjwILAkAgBCACRw0AQbwBIRAMqAILIAIgBGsgACgCACIBaiEUIAQgAWtBB2ohEAJAA0AgBC0AACABQfTPgIAAai0AAEcNkAEgAUEHRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbwBIRAMqAILIABBADYCACAQQQFqIQFBGyEQDI0BCwJAIAQgAkcNAEG9ASEQDKcCCwJAAkACQCAELQAAQb5/ag4SAJEBkQGRAZEBkQGRAZEBkQGRAQGRAZEBkQGRAZEBkQECkQELIARBAWohBEGkASEQDI8CCyAEQQFqIQRBpwEhEAyOAgsgBEEBaiEEQagBIRAMjQILAkAgBCACRw0AQb4BIRAMpgILIAQtAABBzgBHDY0BIARBAWohBAzPAQsCQCAEIAJHDQBBvwEhEAylAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAELQAAQb9/ag4VAAECA5wBBAUGnAGcAZwBBwgJCgucAQwNDg+cAQsgBEEBaiEBQegAIRAMmgILIARBAWohAUHpACEQDJkCCyAEQQFqIQFB7gAhEAyYAgsgBEEBaiEBQfIAIRAMlwILIARBAWohAUHzACEQDJYCCyAEQQFqIQFB9gAhEAyVAgsgBEEBaiEBQfcAIRAMlAILIARBAWohAUH6ACEQDJMCCyAEQQFqIQRBgwEhEAySAgsgBEEBaiEEQYQBIRAMkQILIARBAWohBEGFASEQDJACCyAEQQFqIQRBkgEhEAyPAgsgBEEBaiEEQZgBIRAMjgILIARBAWohBEGgASEQDI0CCyAEQQFqIQRBowEhEAyMAgsgBEEBaiEEQaoBIRAMiwILAkAgBCACRg0AIABBkICAgAA2AgggACAENgIEQasBIRAMiwILQcABIRAMowILIAAgBSACEKqAgIAAIgENiwEgBSEBDFwLAkAgBiACRg0AIAZBAWohBQyNAQtBwgEhEAyhAgsDQAJAIBAtAABBdmoOBIwBAACPAQALIBBBAWoiECACRw0AC0HDASEQDKACCwJAIAcgAkYNACAAQZGAgIAANgIIIAAgBzYCBCAHIQFBASEQDIcCC0HEASEQDJ8CCwJAIAcgAkcNAEHFASEQDJ8CCwJAAkAgBy0AAEF2ag4EAc4BzgEAzgELIAdBAWohBgyNAQsgB0EBaiEFDIkBCwJAIAcgAkcNAEHGASEQDJ4CCwJAAkAgBy0AAEF2ag4XAY8BjwEBjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAI8BCyAHQQFqIQcLQbABIRAMhAILAkAgCCACRw0AQcgBIRAMnQILIAgtAABBIEcNjQEgAEEAOwEyIAhBAWohAUGzASEQDIMCCyABIRcCQANAIBciByACRg0BIActAABBUGpB/wFxIhBBCk8NzAECQCAALwEyIhRBmTNLDQAgACAUQQpsIhQ7ATIgEEH//wNzIBRB/v8DcUkNACAHQQFqIRcgACAUIBBqIhA7ATIgEEH//wNxQegHSQ0BCwtBACEQIABBADYCHCAAQcGJgIAANgIQIABBDTYCDCAAIAdBAWo2AhQMnAILQccBIRAMmwILIAAgCCACEK6AgIAAIhBFDcoBIBBBFUcNjAEgAEHIATYCHCAAIAg2AhQgAEHJl4CAADYCECAAQRU2AgxBACEQDJoCCwJAIAkgAkcNAEHMASEQDJoCC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgCS0AAEFQag4KlgGVAQABAgMEBQYIlwELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMjgELQQkhEEEBIRRBACEXQQAhFgyNAQsCQCAKIAJHDQBBzgEhEAyZAgsgCi0AAEEuRw2OASAKQQFqIQkMygELIAsgAkcNjgFB0AEhEAyXAgsCQCALIAJGDQAgAEGOgICAADYCCCAAIAs2AgRBtwEhEAz+AQtB0QEhEAyWAgsCQCAEIAJHDQBB0gEhEAyWAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EEaiELA0AgBC0AACAQQfzPgIAAai0AAEcNjgEgEEEERg3pASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHSASEQDJUCCyAAIAwgAhCsgICAACIBDY0BIAwhAQy4AQsCQCAEIAJHDQBB1AEhEAyUAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EBaiEMA0AgBC0AACAQQYHQgIAAai0AAEcNjwEgEEEBRg2OASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHUASEQDJMCCwJAIAQgAkcNAEHWASEQDJMCCyACIARrIAAoAgAiEGohFCAEIBBrQQJqIQsDQCAELQAAIBBBg9CAgABqLQAARw2OASAQQQJGDZABIBBBAWohECAEQQFqIgQgAkcNAAsgACAUNgIAQdYBIRAMkgILAkAgBCACRw0AQdcBIRAMkgILAkACQCAELQAAQbt/ag4QAI8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwEBjwELIARBAWohBEG7ASEQDPkBCyAEQQFqIQRBvAEhEAz4AQsCQCAEIAJHDQBB2AEhEAyRAgsgBC0AAEHIAEcNjAEgBEEBaiEEDMQBCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEG+ASEQDPcBC0HZASEQDI8CCwJAIAQgAkcNAEHaASEQDI8CCyAELQAAQcgARg3DASAAQQE6ACgMuQELIABBAjoALyAAIAQgAhCmgICAACIQDY0BQcIBIRAM9AELIAAtAChBf2oOArcBuQG4AQsDQAJAIAQtAABBdmoOBACOAY4BAI4BCyAEQQFqIgQgAkcNAAtB3QEhEAyLAgsgAEEAOgAvIAAtAC1BBHFFDYQCCyAAQQA6AC8gAEEBOgA0IAEhAQyMAQsgEEEVRg3aASAAQQA2AhwgACABNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAyIAgsCQCAAIBAgAhC0gICAACIEDQAgECEBDIECCwJAIARBFUcNACAAQQM2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAyIAgsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMhwILIBBBFUYN1gEgAEEANgIcIAAgATYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMhgILIAAoAgQhFyAAQQA2AgQgECARp2oiFiEBIAAgFyAQIBYgFBsiEBC1gICAACIURQ2NASAAQQc2AhwgACAQNgIUIAAgFDYCDEEAIRAMhQILIAAgAC8BMEGAAXI7ATAgASEBC0EqIRAM6gELIBBBFUYN0QEgAEEANgIcIAAgATYCFCAAQYOMgIAANgIQIABBEzYCDEEAIRAMggILIBBBFUYNzwEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAMgQILIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDI0BCyAAQQw2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMgAILIBBBFUYNzAEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM/wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIwBCyAAQQ02AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/gELIBBBFUYNyQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM/QELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIsBCyAAQQ42AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/AELIABBADYCHCAAIAE2AhQgAEHAlYCAADYCECAAQQI2AgxBACEQDPsBCyAQQRVGDcUBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPoBCyAAQRA2AhwgACABNgIUIAAgEDYCDEEAIRAM+QELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDPEBCyAAQRE2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM+AELIBBBFUYNwQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM9wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIgBCyAAQRM2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM9gELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDO0BCyAAQRQ2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM9QELIBBBFUYNvQEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM9AELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIYBCyAAQRY2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM8wELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC3gICAACIEDQAgAUEBaiEBDOkBCyAAQRc2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM8gELIABBADYCHCAAIAE2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDPEBC0IBIRELIBBBAWohAQJAIAApAyAiEkL//////////w9WDQAgACASQgSGIBGENwMgIAEhAQyEAQsgAEEANgIcIAAgATYCFCAAQa2JgIAANgIQIABBDDYCDEEAIRAM7wELIABBADYCHCAAIBA2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDO4BCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNcyAAQQU2AhwgACAQNgIUIAAgFDYCDEEAIRAM7QELIABBADYCHCAAIBA2AhQgAEGqnICAADYCECAAQQ82AgxBACEQDOwBCyAAIBAgAhC0gICAACIBDQEgECEBC0EOIRAM0QELAkAgAUEVRw0AIABBAjYCHCAAIBA2AhQgAEGwmICAADYCECAAQRU2AgxBACEQDOoBCyAAQQA2AhwgACAQNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAzpAQsgAUEBaiEQAkAgAC8BMCIBQYABcUUNAAJAIAAgECACELuAgIAAIgENACAQIQEMcAsgAUEVRw26ASAAQQU2AhwgACAQNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAzpAQsCQCABQaAEcUGgBEcNACAALQAtQQJxDQAgAEEANgIcIAAgEDYCFCAAQZaTgIAANgIQIABBBDYCDEEAIRAM6QELIAAgECACEL2AgIAAGiAQIQECQAJAAkACQAJAIAAgECACELOAgIAADhYCAQAEBAQEBAQEBAQEBAQEBAQEBAQDBAsgAEEBOgAuCyAAIAAvATBBwAByOwEwIBAhAQtBJiEQDNEBCyAAQSM2AhwgACAQNgIUIABBpZaAgAA2AhAgAEEVNgIMQQAhEAzpAQsgAEEANgIcIAAgEDYCFCAAQdWLgIAANgIQIABBETYCDEEAIRAM6AELIAAtAC1BAXFFDQFBwwEhEAzOAQsCQCANIAJGDQADQAJAIA0tAABBIEYNACANIQEMxAELIA1BAWoiDSACRw0AC0ElIRAM5wELQSUhEAzmAQsgACgCBCEEIABBADYCBCAAIAQgDRCvgICAACIERQ2tASAAQSY2AhwgACAENgIMIAAgDUEBajYCFEEAIRAM5QELIBBBFUYNqwEgAEEANgIcIAAgATYCFCAAQf2NgIAANgIQIABBHTYCDEEAIRAM5AELIABBJzYCHCAAIAE2AhQgACAQNgIMQQAhEAzjAQsgECEBQQEhFAJAAkACQAJAAkACQAJAIAAtACxBfmoOBwYFBQMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0ErIRAMygELIABBADYCHCAAIBA2AhQgAEGrkoCAADYCECAAQQs2AgxBACEQDOIBCyAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMQQAhEAzhAQsgAEEAOgAsIBAhAQy9AQsgECEBQQEhFAJAAkACQAJAAkAgAC0ALEF7ag4EAwECAAULIAAgAC8BMEEIcjsBMAwDC0ECIRQMAQtBBCEUCyAAQQE6ACwgACAALwEwIBRyOwEwCyAQIQELQSkhEAzFAQsgAEEANgIcIAAgATYCFCAAQfCUgIAANgIQIABBAzYCDEEAIRAM3QELAkAgDi0AAEENRw0AIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHULIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzdAQsgAC0ALUEBcUUNAUHEASEQDMMBCwJAIA4gAkcNAEEtIRAM3AELAkACQANAAkAgDi0AAEF2ag4EAgAAAwALIA5BAWoiDiACRw0AC0EtIRAM3QELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDiEBDHQLIABBLDYCHCAAIA42AhQgACABNgIMQQAhEAzcAQsgACgCBCEBIABBADYCBAJAIAAgASAOELGAgIAAIgENACAOQQFqIQEMcwsgAEEsNgIcIAAgATYCDCAAIA5BAWo2AhRBACEQDNsBCyAAKAIEIQQgAEEANgIEIAAgBCAOELGAgIAAIgQNoAEgDiEBDM4BCyAQQSxHDQEgAUEBaiEQQQEhAQJAAkACQAJAAkAgAC0ALEF7ag4EAwECBAALIBAhAQwEC0ECIQEMAQtBBCEBCyAAQQE6ACwgACAALwEwIAFyOwEwIBAhAQwBCyAAIAAvATBBCHI7ATAgECEBC0E5IRAMvwELIABBADoALCABIQELQTQhEAy9AQsgACAALwEwQSByOwEwIAEhAQwCCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBA0AIAEhAQzHAQsgAEE3NgIcIAAgATYCFCAAIAQ2AgxBACEQDNQBCyAAQQg6ACwgASEBC0EwIRAMuQELAkAgAC0AKEEBRg0AIAEhAQwECyAALQAtQQhxRQ2TASABIQEMAwsgAC0AMEEgcQ2UAUHFASEQDLcBCwJAIA8gAkYNAAJAA0ACQCAPLQAAQVBqIgFB/wFxQQpJDQAgDyEBQTUhEAy6AQsgACkDICIRQpmz5syZs+bMGVYNASAAIBFCCn4iETcDICARIAGtQv8BgyISQn+FVg0BIAAgESASfDcDICAPQQFqIg8gAkcNAAtBOSEQDNEBCyAAKAIEIQIgAEEANgIEIAAgAiAPQQFqIgQQsYCAgAAiAg2VASAEIQEMwwELQTkhEAzPAQsCQCAALwEwIgFBCHFFDQAgAC0AKEEBRw0AIAAtAC1BCHFFDZABCyAAIAFB9/sDcUGABHI7ATAgDyEBC0E3IRAMtAELIAAgAC8BMEEQcjsBMAyrAQsgEEEVRg2LASAAQQA2AhwgACABNgIUIABB8I6AgAA2AhAgAEEcNgIMQQAhEAzLAQsgAEHDADYCHCAAIAE2AgwgACANQQFqNgIUQQAhEAzKAQsCQCABLQAAQTpHDQAgACgCBCEQIABBADYCBAJAIAAgECABEK+AgIAAIhANACABQQFqIQEMYwsgAEHDADYCHCAAIBA2AgwgACABQQFqNgIUQQAhEAzKAQsgAEEANgIcIAAgATYCFCAAQbGRgIAANgIQIABBCjYCDEEAIRAMyQELIABBADYCHCAAIAE2AhQgAEGgmYCAADYCECAAQR42AgxBACEQDMgBCyAAQQA2AgALIABBgBI7ASogACAXQQFqIgEgAhCogICAACIQDQEgASEBC0HHACEQDKwBCyAQQRVHDYMBIABB0QA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAzEAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAzDAQsgAEEANgIcIAAgFDYCFCAAQcGogIAANgIQIABBBzYCDCAAQQA2AgBBACEQDMIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxdCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDMEBC0EAIRAgAEEANgIcIAAgATYCFCAAQYCRgIAANgIQIABBCTYCDAzAAQsgEEEVRg19IABBADYCHCAAIAE2AhQgAEGUjYCAADYCECAAQSE2AgxBACEQDL8BC0EBIRZBACEXQQAhFEEBIRALIAAgEDoAKyABQQFqIQECQAJAIAAtAC1BEHENAAJAAkACQCAALQAqDgMBAAIECyAWRQ0DDAILIBQNAQwCCyAXRQ0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQrYCAgAAiEA0AIAEhAQxcCyAAQdgANgIcIAAgATYCFCAAIBA2AgxBACEQDL4BCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQytAQsgAEHZADYCHCAAIAE2AhQgACAENgIMQQAhEAy9AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMqwELIABB2gA2AhwgACABNgIUIAAgBDYCDEEAIRAMvAELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKkBCyAAQdwANgIcIAAgATYCFCAAIAQ2AgxBACEQDLsBCwJAIAEtAABBUGoiEEH/AXFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHSADYCHCAAIBQ2AhQgACABNgIMQQAhEAykAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHTADYCHCAAIBQ2AhQgACABNgIMQQAhEAyjAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMQwsgAEHlADYCHCAAIBQ2AhQgACABNgIMQQAhEAyiAQsgAEEANgIcIAAgFDYCFCAAQcOPgIAANgIQIABBBzYCDEEAIRAMoQELIABBADYCHCAAIAE2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKABC0EAIRAgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDAyfAQsgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDEEAIRAMngELIABBADYCHCAAIBQ2AhQgAEH+kYCAADYCECAAQQc2AgxBACEQDJ0BCyAAQQA2AhwgACABNgIUIABBjpuAgAA2AhAgAEEGNgIMQQAhEAycAQsgEEEVRg1XIABBADYCHCAAIAE2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDJsBCyAAQQA2AgAgEEEBaiEBQSQhEAsgACAQOgApIAAoAgQhECAAQQA2AgQgACAQIAEQq4CAgAAiEA1UIAEhAQw+CyAAQQA2AgALQQAhECAAQQA2AhwgACAENgIUIABB8ZuAgAA2AhAgAEEGNgIMDJcBCyABQRVGDVAgAEEANgIcIAAgBTYCFCAAQfCMgIAANgIQIABBGzYCDEEAIRAMlgELIAAoAgQhBSAAQQA2AgQgACAFIBAQqYCAgAAiBQ0BIBBBAWohBQtBrQEhEAx7CyAAQcEBNgIcIAAgBTYCDCAAIBBBAWo2AhRBACEQDJMBCyAAKAIEIQYgAEEANgIEIAAgBiAQEKmAgIAAIgYNASAQQQFqIQYLQa4BIRAMeAsgAEHCATYCHCAAIAY2AgwgACAQQQFqNgIUQQAhEAyQAQsgAEEANgIcIAAgBzYCFCAAQZeLgIAANgIQIABBDTYCDEEAIRAMjwELIABBADYCHCAAIAg2AhQgAEHjkICAADYCECAAQQk2AgxBACEQDI4BCyAAQQA2AhwgACAINgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAyNAQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgCUEBaiEIAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBCAAIBAgCBCtgICAACIQRQ09IABByQE2AhwgACAINgIUIAAgEDYCDEEAIRAMjAELIAAoAgQhBCAAQQA2AgQgACAEIAgQrYCAgAAiBEUNdiAAQcoBNgIcIAAgCDYCFCAAIAQ2AgxBACEQDIsBCyAAKAIEIQQgAEEANgIEIAAgBCAJEK2AgIAAIgRFDXQgAEHLATYCHCAAIAk2AhQgACAENgIMQQAhEAyKAQsgACgCBCEEIABBADYCBCAAIAQgChCtgICAACIERQ1yIABBzQE2AhwgACAKNgIUIAAgBDYCDEEAIRAMiQELAkAgCy0AAEFQaiIQQf8BcUEKTw0AIAAgEDoAKiALQQFqIQpBtgEhEAxwCyAAKAIEIQQgAEEANgIEIAAgBCALEK2AgIAAIgRFDXAgAEHPATYCHCAAIAs2AhQgACAENgIMQQAhEAyIAQsgAEEANgIcIAAgBDYCFCAAQZCzgIAANgIQIABBCDYCDCAAQQA2AgBBACEQDIcBCyABQRVGDT8gAEEANgIcIAAgDDYCFCAAQcyOgIAANgIQIABBIDYCDEEAIRAMhgELIABBgQQ7ASggACgCBCEQIABCADcDACAAIBAgDEEBaiIMEKuAgIAAIhBFDTggAEHTATYCHCAAIAw2AhQgACAQNgIMQQAhEAyFAQsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQdibgIAANgIQIABBCDYCDAyDAQsgACgCBCEQIABCADcDACAAIBAgC0EBaiILEKuAgIAAIhANAUHGASEQDGkLIABBAjoAKAxVCyAAQdUBNgIcIAAgCzYCFCAAIBA2AgxBACEQDIABCyAQQRVGDTcgAEEANgIcIAAgBDYCFCAAQaSMgIAANgIQIABBEDYCDEEAIRAMfwsgAC0ANEEBRw00IAAgBCACELyAgIAAIhBFDTQgEEEVRw01IABB3AE2AhwgACAENgIUIABB1ZaAgAA2AhAgAEEVNgIMQQAhEAx+C0EAIRAgAEEANgIcIABBr4uAgAA2AhAgAEECNgIMIAAgFEEBajYCFAx9C0EAIRAMYwtBAiEQDGILQQ0hEAxhC0EPIRAMYAtBJSEQDF8LQRMhEAxeC0EVIRAMXQtBFiEQDFwLQRchEAxbC0EYIRAMWgtBGSEQDFkLQRohEAxYC0EbIRAMVwtBHCEQDFYLQR0hEAxVC0EfIRAMVAtBISEQDFMLQSMhEAxSC0HGACEQDFELQS4hEAxQC0EvIRAMTwtBOyEQDE4LQT0hEAxNC0HIACEQDEwLQckAIRAMSwtBywAhEAxKC0HMACEQDEkLQc4AIRAMSAtB0QAhEAxHC0HVACEQDEYLQdgAIRAMRQtB2QAhEAxEC0HbACEQDEMLQeQAIRAMQgtB5QAhEAxBC0HxACEQDEALQfQAIRAMPwtBjQEhEAw+C0GXASEQDD0LQakBIRAMPAtBrAEhEAw7C0HAASEQDDoLQbkBIRAMOQtBrwEhEAw4C0GxASEQDDcLQbIBIRAMNgtBtAEhEAw1C0G1ASEQDDQLQboBIRAMMwtBvQEhEAwyC0G/ASEQDDELQcEBIRAMMAsgAEEANgIcIAAgBDYCFCAAQemLgIAANgIQIABBHzYCDEEAIRAMSAsgAEHbATYCHCAAIAQ2AhQgAEH6loCAADYCECAAQRU2AgxBACEQDEcLIABB+AA2AhwgACAMNgIUIABBypiAgAA2AhAgAEEVNgIMQQAhEAxGCyAAQdEANgIcIAAgBTYCFCAAQbCXgIAANgIQIABBFTYCDEEAIRAMRQsgAEH5ADYCHCAAIAE2AhQgACAQNgIMQQAhEAxECyAAQfgANgIcIAAgATYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMQwsgAEHkADYCHCAAIAE2AhQgAEHjl4CAADYCECAAQRU2AgxBACEQDEILIABB1wA2AhwgACABNgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAxBCyAAQQA2AhwgACABNgIUIABBuY2AgAA2AhAgAEEaNgIMQQAhEAxACyAAQcIANgIcIAAgATYCFCAAQeOYgIAANgIQIABBFTYCDEEAIRAMPwsgAEEANgIEIAAgDyAPELGAgIAAIgRFDQEgAEE6NgIcIAAgBDYCDCAAIA9BAWo2AhRBACEQDD4LIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCxgICAACIERQ0AIABBOzYCHCAAIAQ2AgwgACABQQFqNgIUQQAhEAw+CyABQQFqIQEMLQsgD0EBaiEBDC0LIABBADYCHCAAIA82AhQgAEHkkoCAADYCECAAQQQ2AgxBACEQDDsLIABBNjYCHCAAIAQ2AhQgACACNgIMQQAhEAw6CyAAQS42AhwgACAONgIUIAAgBDYCDEEAIRAMOQsgAEHQADYCHCAAIAE2AhQgAEGRmICAADYCECAAQRU2AgxBACEQDDgLIA1BAWohAQwsCyAAQRU2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAw2CyAAQRs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw1CyAAQQ82AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw0CyAAQQs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAwzCyAAQRo2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwyCyAAQQs2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwxCyAAQQo2AhwgACABNgIUIABB5JaAgAA2AhAgAEEVNgIMQQAhEAwwCyAAQR42AhwgACABNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAwvCyAAQQA2AhwgACAQNgIUIABB2o2AgAA2AhAgAEEUNgIMQQAhEAwuCyAAQQQ2AhwgACABNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAwtCyAAQQA2AgAgC0EBaiELC0G4ASEQDBILIABBADYCACAQQQFqIQFB9QAhEAwRCyABIQECQCAALQApQQVHDQBB4wAhEAwRC0HiACEQDBALQQAhECAAQQA2AhwgAEHkkYCAADYCECAAQQc2AgwgACAUQQFqNgIUDCgLIABBADYCACAXQQFqIQFBwAAhEAwOC0EBIQELIAAgAToALCAAQQA2AgAgF0EBaiEBC0EoIRAMCwsgASEBC0E4IRAMCQsCQCABIg8gAkYNAANAAkAgDy0AAEGAvoCAAGotAAAiAUEBRg0AIAFBAkcNAyAPQQFqIQEMBAsgD0EBaiIPIAJHDQALQT4hEAwiC0E+IRAMIQsgAEEAOgAsIA8hAQwBC0ELIRAMBgtBOiEQDAULIAFBAWohAUEtIRAMBAsgACABOgAsIABBADYCACAWQQFqIQFBDCEQDAMLIABBADYCACAXQQFqIQFBCiEQDAILIABBADYCAAsgAEEAOgAsIA0hAUEJIRAMAAsLQQAhECAAQQA2AhwgACALNgIUIABBzZCAgAA2AhAgAEEJNgIMDBcLQQAhECAAQQA2AhwgACAKNgIUIABB6YqAgAA2AhAgAEEJNgIMDBYLQQAhECAAQQA2AhwgACAJNgIUIABBt5CAgAA2AhAgAEEJNgIMDBULQQAhECAAQQA2AhwgACAINgIUIABBnJGAgAA2AhAgAEEJNgIMDBQLQQAhECAAQQA2AhwgACABNgIUIABBzZCAgAA2AhAgAEEJNgIMDBMLQQAhECAAQQA2AhwgACABNgIUIABB6YqAgAA2AhAgAEEJNgIMDBILQQAhECAAQQA2AhwgACABNgIUIABBt5CAgAA2AhAgAEEJNgIMDBELQQAhECAAQQA2AhwgACABNgIUIABBnJGAgAA2AhAgAEEJNgIMDBALQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA8LQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA4LQQAhECAAQQA2AhwgACABNgIUIABBwJKAgAA2AhAgAEELNgIMDA0LQQAhECAAQQA2AhwgACABNgIUIABBlYmAgAA2AhAgAEELNgIMDAwLQQAhECAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMDAsLQQAhECAAQQA2AhwgACABNgIUIABB+4+AgAA2AhAgAEEKNgIMDAoLQQAhECAAQQA2AhwgACABNgIUIABB8ZmAgAA2AhAgAEECNgIMDAkLQQAhECAAQQA2AhwgACABNgIUIABBxJSAgAA2AhAgAEECNgIMDAgLQQAhECAAQQA2AhwgACABNgIUIABB8pWAgAA2AhAgAEECNgIMDAcLIABBAjYCHCAAIAE2AhQgAEGcmoCAADYCECAAQRY2AgxBACEQDAYLQQEhEAwFC0HUACEQIAEiBCACRg0EIANBCGogACAEIAJB2MKAgABBChDFgICAACADKAIMIQQgAygCCA4DAQQCAAsQyoCAgAAACyAAQQA2AhwgAEG1moCAADYCECAAQRc2AgwgACAEQQFqNgIUQQAhEAwCCyAAQQA2AhwgACAENgIUIABBypqAgAA2AhAgAEEJNgIMQQAhEAwBCwJAIAEiBCACRw0AQSIhEAwBCyAAQYmAgIAANgIIIAAgBDYCBEEhIRALIANBEGokgICAgAAgEAuvAQECfyABKAIAIQYCQAJAIAIgA0YNACAEIAZqIQQgBiADaiACayEHIAIgBkF/cyAFaiIGaiEFA0ACQCACLQAAIAQtAABGDQBBAiEEDAMLAkAgBg0AQQAhBCAFIQIMAwsgBkF/aiEGIARBAWohBCACQQFqIgIgA0cNAAsgByEGIAMhAgsgAEEBNgIAIAEgBjYCACAAIAI2AgQPCyABQQA2AgAgACAENgIAIAAgAjYCBAsKACAAEMeAgIAAC/I2AQt/I4CAgIAAQRBrIgEkgICAgAACQEEAKAKg0ICAAA0AQQAQy4CAgABBgNSEgABrIgJB2QBJDQBBACEDAkBBACgC4NOAgAAiBA0AQQBCfzcC7NOAgABBAEKAgISAgIDAADcC5NOAgABBACABQQhqQXBxQdiq1aoFcyIENgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgAALQQAgAjYCzNOAgABBAEGA1ISAADYCyNOAgABBAEGA1ISAADYCmNCAgABBACAENgKs0ICAAEEAQX82AqjQgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAtBgNSEgABBeEGA1ISAAGtBD3FBAEGA1ISAAEEIakEPcRsiA2oiBEEEaiACQUhqIgUgA2siA0EBcjYCAEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgABBgNSEgAAgBWpBODYCBAsCQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHsAUsNAAJAQQAoAojQgIAAIgZBECAAQRNqQXBxIABBC0kbIgJBA3YiBHYiA0EDcUUNAAJAAkAgA0EBcSAEckEBcyIFQQN0IgRBsNCAgABqIgMgBEG40ICAAGooAgAiBCgCCCICRw0AQQAgBkF+IAV3cTYCiNCAgAAMAQsgAyACNgIIIAIgAzYCDAsgBEEIaiEDIAQgBUEDdCIFQQNyNgIEIAQgBWoiBCAEKAIEQQFyNgIEDAwLIAJBACgCkNCAgAAiB00NAQJAIANFDQACQAJAIAMgBHRBAiAEdCIDQQAgA2tycSIDQQAgA2txQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmoiBEEDdCIDQbDQgIAAaiIFIANBuNCAgABqKAIAIgMoAggiAEcNAEEAIAZBfiAEd3EiBjYCiNCAgAAMAQsgBSAANgIIIAAgBTYCDAsgAyACQQNyNgIEIAMgBEEDdCIEaiAEIAJrIgU2AgAgAyACaiIAIAVBAXI2AgQCQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhBAJAAkAgBkEBIAdBA3Z0IghxDQBBACAGIAhyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAQ2AgwgAiAENgIIIAQgAjYCDCAEIAg2AggLIANBCGohA0EAIAA2ApzQgIAAQQAgBTYCkNCAgAAMDAtBACgCjNCAgAAiCUUNASAJQQAgCWtxQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmpBAnRBuNKAgABqKAIAIgAoAgRBeHEgAmshBCAAIQUCQANAAkAgBSgCECIDDQAgBUEUaigCACIDRQ0CCyADKAIEQXhxIAJrIgUgBCAFIARJIgUbIQQgAyAAIAUbIQAgAyEFDAALCyAAKAIYIQoCQCAAKAIMIgggAEYNACAAKAIIIgNBACgCmNCAgABJGiAIIAM2AgggAyAINgIMDAsLAkAgAEEUaiIFKAIAIgMNACAAKAIQIgNFDQMgAEEQaiEFCwNAIAUhCyADIghBFGoiBSgCACIDDQAgCEEQaiEFIAgoAhAiAw0ACyALQQA2AgAMCgtBfyECIABBv39LDQAgAEETaiIDQXBxIQJBACgCjNCAgAAiB0UNAEEAIQsCQCACQYACSQ0AQR8hCyACQf///wdLDQAgA0EIdiIDIANBgP4/akEQdkEIcSIDdCIEIARBgOAfakEQdkEEcSIEdCIFIAVBgIAPakEQdkECcSIFdEEPdiADIARyIAVyayIDQQF0IAIgA0EVanZBAXFyQRxqIQsLQQAgAmshBAJAAkACQAJAIAtBAnRBuNKAgABqKAIAIgUNAEEAIQNBACEIDAELQQAhAyACQQBBGSALQQF2ayALQR9GG3QhAEEAIQgDQAJAIAUoAgRBeHEgAmsiBiAETw0AIAYhBCAFIQggBg0AQQAhBCAFIQggBSEDDAMLIAMgBUEUaigCACIGIAYgBSAAQR12QQRxakEQaigCACIFRhsgAyAGGyEDIABBAXQhACAFDQALCwJAIAMgCHINAEEAIQhBAiALdCIDQQAgA2tyIAdxIgNFDQMgA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBUEFdkEIcSIAIANyIAUgAHYiA0ECdkEEcSIFciADIAV2IgNBAXZBAnEiBXIgAyAFdiIDQQF2QQFxIgVyIAMgBXZqQQJ0QbjSgIAAaigCACEDCyADRQ0BCwNAIAMoAgRBeHEgAmsiBiAESSEAAkAgAygCECIFDQAgA0EUaigCACEFCyAGIAQgABshBCADIAggABshCCAFIQMgBQ0ACwsgCEUNACAEQQAoApDQgIAAIAJrTw0AIAgoAhghCwJAIAgoAgwiACAIRg0AIAgoAggiA0EAKAKY0ICAAEkaIAAgAzYCCCADIAA2AgwMCQsCQCAIQRRqIgUoAgAiAw0AIAgoAhAiA0UNAyAIQRBqIQULA0AgBSEGIAMiAEEUaiIFKAIAIgMNACAAQRBqIQUgACgCECIDDQALIAZBADYCAAwICwJAQQAoApDQgIAAIgMgAkkNAEEAKAKc0ICAACEEAkACQCADIAJrIgVBEEkNACAEIAJqIgAgBUEBcjYCBEEAIAU2ApDQgIAAQQAgADYCnNCAgAAgBCADaiAFNgIAIAQgAkEDcjYCBAwBCyAEIANBA3I2AgQgBCADaiIDIAMoAgRBAXI2AgRBAEEANgKc0ICAAEEAQQA2ApDQgIAACyAEQQhqIQMMCgsCQEEAKAKU0ICAACIAIAJNDQBBACgCoNCAgAAiAyACaiIEIAAgAmsiBUEBcjYCBEEAIAU2ApTQgIAAQQAgBDYCoNCAgAAgAyACQQNyNgIEIANBCGohAwwKCwJAAkBBACgC4NOAgABFDQBBACgC6NOAgAAhBAwBC0EAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEMakFwcUHYqtWqBXM2AuDTgIAAQQBBADYC9NOAgABBAEEANgLE04CAAEGAgAQhBAtBACEDAkAgBCACQccAaiIHaiIGQQAgBGsiC3EiCCACSw0AQQBBMDYC+NOAgAAMCgsCQEEAKALA04CAACIDRQ0AAkBBACgCuNOAgAAiBCAIaiIFIARNDQAgBSADTQ0BC0EAIQNBAEEwNgL404CAAAwKC0EALQDE04CAAEEEcQ0EAkACQAJAQQAoAqDQgIAAIgRFDQBByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiAESw0DCyADKAIIIgMNAAsLQQAQy4CAgAAiAEF/Rg0FIAghBgJAQQAoAuTTgIAAIgNBf2oiBCAAcUUNACAIIABrIAQgAGpBACADa3FqIQYLIAYgAk0NBSAGQf7///8HSw0FAkBBACgCwNOAgAAiA0UNAEEAKAK404CAACIEIAZqIgUgBE0NBiAFIANLDQYLIAYQy4CAgAAiAyAARw0BDAcLIAYgAGsgC3EiBkH+////B0sNBCAGEMuAgIAAIgAgAygCACADKAIEakYNAyAAIQMLAkAgA0F/Rg0AIAJByABqIAZNDQACQCAHIAZrQQAoAujTgIAAIgRqQQAgBGtxIgRB/v///wdNDQAgAyEADAcLAkAgBBDLgICAAEF/Rg0AIAQgBmohBiADIQAMBwtBACAGaxDLgICAABoMBAsgAyEAIANBf0cNBQwDC0EAIQgMBwtBACEADAULIABBf0cNAgtBAEEAKALE04CAAEEEcjYCxNOAgAALIAhB/v///wdLDQEgCBDLgICAACEAQQAQy4CAgAAhAyAAQX9GDQEgA0F/Rg0BIAAgA08NASADIABrIgYgAkE4ak0NAQtBAEEAKAK404CAACAGaiIDNgK404CAAAJAIANBACgCvNOAgABNDQBBACADNgK804CAAAsCQAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQCAAIAMoAgAiBSADKAIEIghqRg0CIAMoAggiAw0ADAMLCwJAAkBBACgCmNCAgAAiA0UNACAAIANPDQELQQAgADYCmNCAgAALQQAhA0EAIAY2AszTgIAAQQAgADYCyNOAgABBAEF/NgKo0ICAAEEAQQAoAuDTgIAANgKs0ICAAEEAQQA2AtTTgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiBCAGQUhqIgUgA2siA0EBcjYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgAAgACAFakE4NgIEDAILIAMtAAxBCHENACAEIAVJDQAgBCAATw0AIARBeCAEa0EPcUEAIARBCGpBD3EbIgVqIgBBACgClNCAgAAgBmoiCyAFayIFQQFyNgIEIAMgCCAGajYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAU2ApTQgIAAQQAgADYCoNCAgAAgBCALakE4NgIEDAELAkAgAEEAKAKY0ICAACIITw0AQQAgADYCmNCAgAAgACEICyAAIAZqIQVByNOAgAAhAwJAAkACQAJAAkACQAJAA0AgAygCACAFRg0BIAMoAggiAw0ADAILCyADLQAMQQhxRQ0BC0HI04CAACEDA0ACQCADKAIAIgUgBEsNACAFIAMoAgRqIgUgBEsNAwsgAygCCCEDDAALCyADIAA2AgAgAyADKAIEIAZqNgIEIABBeCAAa0EPcUEAIABBCGpBD3EbaiILIAJBA3I2AgQgBUF4IAVrQQ9xQQAgBUEIakEPcRtqIgYgCyACaiICayEDAkAgBiAERw0AQQAgAjYCoNCAgABBAEEAKAKU0ICAACADaiIDNgKU0ICAACACIANBAXI2AgQMAwsCQCAGQQAoApzQgIAARw0AQQAgAjYCnNCAgABBAEEAKAKQ0ICAACADaiIDNgKQ0ICAACACIANBAXI2AgQgAiADaiADNgIADAMLAkAgBigCBCIEQQNxQQFHDQAgBEF4cSEHAkACQCAEQf8BSw0AIAYoAggiBSAEQQN2IghBA3RBsNCAgABqIgBGGgJAIAYoAgwiBCAFRw0AQQBBACgCiNCAgABBfiAId3E2AojQgIAADAILIAQgAEYaIAQgBTYCCCAFIAQ2AgwMAQsgBigCGCEJAkACQCAGKAIMIgAgBkYNACAGKAIIIgQgCEkaIAAgBDYCCCAEIAA2AgwMAQsCQCAGQRRqIgQoAgAiBQ0AIAZBEGoiBCgCACIFDQBBACEADAELA0AgBCEIIAUiAEEUaiIEKAIAIgUNACAAQRBqIQQgACgCECIFDQALIAhBADYCAAsgCUUNAAJAAkAgBiAGKAIcIgVBAnRBuNKAgABqIgQoAgBHDQAgBCAANgIAIAANAUEAQQAoAozQgIAAQX4gBXdxNgKM0ICAAAwCCyAJQRBBFCAJKAIQIAZGG2ogADYCACAARQ0BCyAAIAk2AhgCQCAGKAIQIgRFDQAgACAENgIQIAQgADYCGAsgBigCFCIERQ0AIABBFGogBDYCACAEIAA2AhgLIAcgA2ohAyAGIAdqIgYoAgQhBAsgBiAEQX5xNgIEIAIgA2ogAzYCACACIANBAXI2AgQCQCADQf8BSw0AIANBeHFBsNCAgABqIQQCQAJAQQAoAojQgIAAIgVBASADQQN2dCIDcQ0AQQAgBSADcjYCiNCAgAAgBCEDDAELIAQoAgghAwsgAyACNgIMIAQgAjYCCCACIAQ2AgwgAiADNgIIDAMLQR8hBAJAIANB////B0sNACADQQh2IgQgBEGA/j9qQRB2QQhxIgR0IgUgBUGA4B9qQRB2QQRxIgV0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAQgBXIgAHJrIgRBAXQgAyAEQRVqdkEBcXJBHGohBAsgAiAENgIcIAJCADcCECAEQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiAEEBIAR0IghxDQAgBSACNgIAQQAgACAIcjYCjNCAgAAgAiAFNgIYIAIgAjYCCCACIAI2AgwMAwsgA0EAQRkgBEEBdmsgBEEfRht0IQQgBSgCACEAA0AgACIFKAIEQXhxIANGDQIgBEEddiEAIARBAXQhBCAFIABBBHFqQRBqIggoAgAiAA0ACyAIIAI2AgAgAiAFNgIYIAIgAjYCDCACIAI2AggMAgsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiCyAGQUhqIgggA2siA0EBcjYCBCAAIAhqQTg2AgQgBCAFQTcgBWtBD3FBACAFQUlqQQ9xG2pBQWoiCCAIIARBEGpJGyIIQSM2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAs2AqDQgIAAIAhBEGpBACkC0NOAgAA3AgAgCEEAKQLI04CAADcCCEEAIAhBCGo2AtDTgIAAQQAgBjYCzNOAgABBACAANgLI04CAAEEAQQA2AtTTgIAAIAhBJGohAwNAIANBBzYCACADQQRqIgMgBUkNAAsgCCAERg0DIAggCCgCBEF+cTYCBCAIIAggBGsiADYCACAEIABBAXI2AgQCQCAAQf8BSw0AIABBeHFBsNCAgABqIQMCQAJAQQAoAojQgIAAIgVBASAAQQN2dCIAcQ0AQQAgBSAAcjYCiNCAgAAgAyEFDAELIAMoAgghBQsgBSAENgIMIAMgBDYCCCAEIAM2AgwgBCAFNgIIDAQLQR8hAwJAIABB////B0sNACAAQQh2IgMgA0GA/j9qQRB2QQhxIgN0IgUgBUGA4B9qQRB2QQRxIgV0IgggCEGAgA9qQRB2QQJxIgh0QQ92IAMgBXIgCHJrIgNBAXQgACADQRVqdkEBcXJBHGohAwsgBCADNgIcIARCADcCECADQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiCEEBIAN0IgZxDQAgBSAENgIAQQAgCCAGcjYCjNCAgAAgBCAFNgIYIAQgBDYCCCAEIAQ2AgwMBAsgAEEAQRkgA0EBdmsgA0EfRht0IQMgBSgCACEIA0AgCCIFKAIEQXhxIABGDQMgA0EddiEIIANBAXQhAyAFIAhBBHFqQRBqIgYoAgAiCA0ACyAGIAQ2AgAgBCAFNgIYIAQgBDYCDCAEIAQ2AggMAwsgBSgCCCIDIAI2AgwgBSACNgIIIAJBADYCGCACIAU2AgwgAiADNgIICyALQQhqIQMMBQsgBSgCCCIDIAQ2AgwgBSAENgIIIARBADYCGCAEIAU2AgwgBCADNgIIC0EAKAKU0ICAACIDIAJNDQBBACgCoNCAgAAiBCACaiIFIAMgAmsiA0EBcjYCBEEAIAM2ApTQgIAAQQAgBTYCoNCAgAAgBCACQQNyNgIEIARBCGohAwwDC0EAIQNBAEEwNgL404CAAAwCCwJAIAtFDQACQAJAIAggCCgCHCIFQQJ0QbjSgIAAaiIDKAIARw0AIAMgADYCACAADQFBACAHQX4gBXdxIgc2AozQgIAADAILIAtBEEEUIAsoAhAgCEYbaiAANgIAIABFDQELIAAgCzYCGAJAIAgoAhAiA0UNACAAIAM2AhAgAyAANgIYCyAIQRRqKAIAIgNFDQAgAEEUaiADNgIAIAMgADYCGAsCQAJAIARBD0sNACAIIAQgAmoiA0EDcjYCBCAIIANqIgMgAygCBEEBcjYCBAwBCyAIIAJqIgAgBEEBcjYCBCAIIAJBA3I2AgQgACAEaiAENgIAAkAgBEH/AUsNACAEQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgBEEDdnQiBHENAEEAIAUgBHI2AojQgIAAIAMhBAwBCyADKAIIIQQLIAQgADYCDCADIAA2AgggACADNgIMIAAgBDYCCAwBC0EfIQMCQCAEQf///wdLDQAgBEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCICIAJBgIAPakEQdkECcSICdEEPdiADIAVyIAJyayIDQQF0IAQgA0EVanZBAXFyQRxqIQMLIAAgAzYCHCAAQgA3AhAgA0ECdEG40oCAAGohBQJAIAdBASADdCICcQ0AIAUgADYCAEEAIAcgAnI2AozQgIAAIAAgBTYCGCAAIAA2AgggACAANgIMDAELIARBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhAgJAA0AgAiIFKAIEQXhxIARGDQEgA0EddiECIANBAXQhAyAFIAJBBHFqQRBqIgYoAgAiAg0ACyAGIAA2AgAgACAFNgIYIAAgADYCDCAAIAA2AggMAQsgBSgCCCIDIAA2AgwgBSAANgIIIABBADYCGCAAIAU2AgwgACADNgIICyAIQQhqIQMMAQsCQCAKRQ0AAkACQCAAIAAoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAg2AgAgCA0BQQAgCUF+IAV3cTYCjNCAgAAMAgsgCkEQQRQgCigCECAARhtqIAg2AgAgCEUNAQsgCCAKNgIYAkAgACgCECIDRQ0AIAggAzYCECADIAg2AhgLIABBFGooAgAiA0UNACAIQRRqIAM2AgAgAyAINgIYCwJAAkAgBEEPSw0AIAAgBCACaiIDQQNyNgIEIAAgA2oiAyADKAIEQQFyNgIEDAELIAAgAmoiBSAEQQFyNgIEIAAgAkEDcjYCBCAFIARqIAQ2AgACQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhAwJAAkBBASAHQQN2dCIIIAZxDQBBACAIIAZyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAM2AgwgAiADNgIIIAMgAjYCDCADIAg2AggLQQAgBTYCnNCAgABBACAENgKQ0ICAAAsgAEEIaiEDCyABQRBqJICAgIAAIAMLCgAgABDJgICAAAviDQEHfwJAIABFDQAgAEF4aiIBIABBfGooAgAiAkF4cSIAaiEDAkAgAkEBcQ0AIAJBA3FFDQEgASABKAIAIgJrIgFBACgCmNCAgAAiBEkNASACIABqIQACQCABQQAoApzQgIAARg0AAkAgAkH/AUsNACABKAIIIgQgAkEDdiIFQQN0QbDQgIAAaiIGRhoCQCABKAIMIgIgBEcNAEEAQQAoAojQgIAAQX4gBXdxNgKI0ICAAAwDCyACIAZGGiACIAQ2AgggBCACNgIMDAILIAEoAhghBwJAAkAgASgCDCIGIAFGDQAgASgCCCICIARJGiAGIAI2AgggAiAGNgIMDAELAkAgAUEUaiICKAIAIgQNACABQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQECQAJAIAEgASgCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAwsgB0EQQRQgBygCECABRhtqIAY2AgAgBkUNAgsgBiAHNgIYAkAgASgCECICRQ0AIAYgAjYCECACIAY2AhgLIAEoAhQiAkUNASAGQRRqIAI2AgAgAiAGNgIYDAELIAMoAgQiAkEDcUEDRw0AIAMgAkF+cTYCBEEAIAA2ApDQgIAAIAEgAGogADYCACABIABBAXI2AgQPCyABIANPDQAgAygCBCICQQFxRQ0AAkACQCACQQJxDQACQCADQQAoAqDQgIAARw0AQQAgATYCoNCAgABBAEEAKAKU0ICAACAAaiIANgKU0ICAACABIABBAXI2AgQgAUEAKAKc0ICAAEcNA0EAQQA2ApDQgIAAQQBBADYCnNCAgAAPCwJAIANBACgCnNCAgABHDQBBACABNgKc0ICAAEEAQQAoApDQgIAAIABqIgA2ApDQgIAAIAEgAEEBcjYCBCABIABqIAA2AgAPCyACQXhxIABqIQACQAJAIAJB/wFLDQAgAygCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgAygCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAgsgAiAGRhogAiAENgIIIAQgAjYCDAwBCyADKAIYIQcCQAJAIAMoAgwiBiADRg0AIAMoAggiAkEAKAKY0ICAAEkaIAYgAjYCCCACIAY2AgwMAQsCQCADQRRqIgIoAgAiBA0AIANBEGoiAigCACIEDQBBACEGDAELA0AgAiEFIAQiBkEUaiICKAIAIgQNACAGQRBqIQIgBigCECIEDQALIAVBADYCAAsgB0UNAAJAAkAgAyADKAIcIgRBAnRBuNKAgABqIgIoAgBHDQAgAiAGNgIAIAYNAUEAQQAoAozQgIAAQX4gBHdxNgKM0ICAAAwCCyAHQRBBFCAHKAIQIANGG2ogBjYCACAGRQ0BCyAGIAc2AhgCQCADKAIQIgJFDQAgBiACNgIQIAIgBjYCGAsgAygCFCICRQ0AIAZBFGogAjYCACACIAY2AhgLIAEgAGogADYCACABIABBAXI2AgQgAUEAKAKc0ICAAEcNAUEAIAA2ApDQgIAADwsgAyACQX5xNgIEIAEgAGogADYCACABIABBAXI2AgQLAkAgAEH/AUsNACAAQXhxQbDQgIAAaiECAkACQEEAKAKI0ICAACIEQQEgAEEDdnQiAHENAEEAIAQgAHI2AojQgIAAIAIhAAwBCyACKAIIIQALIAAgATYCDCACIAE2AgggASACNgIMIAEgADYCCA8LQR8hAgJAIABB////B0sNACAAQQh2IgIgAkGA/j9qQRB2QQhxIgJ0IgQgBEGA4B9qQRB2QQRxIgR0IgYgBkGAgA9qQRB2QQJxIgZ0QQ92IAIgBHIgBnJrIgJBAXQgACACQRVqdkEBcXJBHGohAgsgASACNgIcIAFCADcCECACQQJ0QbjSgIAAaiEEAkACQEEAKAKM0ICAACIGQQEgAnQiA3ENACAEIAE2AgBBACAGIANyNgKM0ICAACABIAQ2AhggASABNgIIIAEgATYCDAwBCyAAQQBBGSACQQF2ayACQR9GG3QhAiAEKAIAIQYCQANAIAYiBCgCBEF4cSAARg0BIAJBHXYhBiACQQF0IQIgBCAGQQRxakEQaiIDKAIAIgYNAAsgAyABNgIAIAEgBDYCGCABIAE2AgwgASABNgIIDAELIAQoAggiACABNgIMIAQgATYCCCABQQA2AhggASAENgIMIAEgADYCCAtBAEEAKAKo0ICAAEF/aiIBQX8gARs2AqjQgIAACwsEAAAAC04AAkAgAA0APwBBEHQPCwJAIABB//8DcQ0AIABBf0wNAAJAIABBEHZAACIAQX9HDQBBAEEwNgL404CAAEF/DwsgAEEQdA8LEMqAgIAAAAvyAgIDfwF+AkAgAkUNACAAIAE6AAAgAiAAaiIDQX9qIAE6AAAgAkEDSQ0AIAAgAToAAiAAIAE6AAEgA0F9aiABOgAAIANBfmogAToAACACQQdJDQAgACABOgADIANBfGogAToAACACQQlJDQAgAEEAIABrQQNxIgRqIgMgAUH/AXFBgYKECGwiATYCACADIAIgBGtBfHEiBGoiAkF8aiABNgIAIARBCUkNACADIAE2AgggAyABNgIEIAJBeGogATYCACACQXRqIAE2AgAgBEEZSQ0AIAMgATYCGCADIAE2AhQgAyABNgIQIAMgATYCDCACQXBqIAE2AgAgAkFsaiABNgIAIAJBaGogATYCACACQWRqIAE2AgAgBCADQQRxQRhyIgVrIgJBIEkNACABrUKBgICAEH4hBiADIAVqIQEDQCABIAY3AxggASAGNwMQIAEgBjcDCCABIAY3AwAgAUEgaiEBIAJBYGoiAkEfSw0ACwsgAAsLjkgBAEGACAuGSAEAAAACAAAAAwAAAAAAAAAAAAAABAAAAAUAAAAAAAAAAAAAAAYAAAAHAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsb3NlZWVwLWFsaXZlAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgAAAAAAAAAAAAAAAAAAAHJhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KDQpTTQ0KDQpUVFAvQ0UvVFNQLwAAAAAAAAAAAAAAAAECAAEDAAAAAAAAAAAAAAAAAAAAAAAABAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQUBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAABAAACAAAAAAAAAAAAAAAAAAAAAAAAAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.enumToMap = void 0;\nfunction enumToMap(obj) {\n const res = {};\n Object.keys(obj).forEach((key) => {\n const value = obj[key];\n if (typeof value === 'number') {\n res[key] = value;\n }\n });\n return res;\n}\nexports.enumToMap = enumToMap;\n//# sourceMappingURL=utils.js.map","'use strict'\n\nconst { kClients } = require('../core/symbols')\nconst Agent = require('../agent')\nconst {\n kAgent,\n kMockAgentSet,\n kMockAgentGet,\n kDispatches,\n kIsMockActive,\n kNetConnect,\n kGetNetConnect,\n kOptions,\n kFactory\n} = require('./mock-symbols')\nconst MockClient = require('./mock-client')\nconst MockPool = require('./mock-pool')\nconst { matchValue, buildMockOptions } = require('./mock-utils')\nconst { InvalidArgumentError, UndiciError } = require('../core/errors')\nconst Dispatcher = require('../dispatcher')\nconst Pluralizer = require('./pluralizer')\nconst PendingInterceptorsFormatter = require('./pending-interceptors-formatter')\n\nclass FakeWeakRef {\n constructor (value) {\n this.value = value\n }\n\n deref () {\n return this.value\n }\n}\n\nclass MockAgent extends Dispatcher {\n constructor (opts) {\n super(opts)\n\n this[kNetConnect] = true\n this[kIsMockActive] = true\n\n // Instantiate Agent and encapsulate\n if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n const agent = opts && opts.agent ? opts.agent : new Agent(opts)\n this[kAgent] = agent\n\n this[kClients] = agent[kClients]\n this[kOptions] = buildMockOptions(opts)\n }\n\n get (origin) {\n let dispatcher = this[kMockAgentGet](origin)\n\n if (!dispatcher) {\n dispatcher = this[kFactory](origin)\n this[kMockAgentSet](origin, dispatcher)\n }\n return dispatcher\n }\n\n dispatch (opts, handler) {\n // Call MockAgent.get to perform additional setup before dispatching as normal\n this.get(opts.origin)\n return this[kAgent].dispatch(opts, handler)\n }\n\n async close () {\n await this[kAgent].close()\n this[kClients].clear()\n }\n\n deactivate () {\n this[kIsMockActive] = false\n }\n\n activate () {\n this[kIsMockActive] = true\n }\n\n enableNetConnect (matcher) {\n if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {\n if (Array.isArray(this[kNetConnect])) {\n this[kNetConnect].push(matcher)\n } else {\n this[kNetConnect] = [matcher]\n }\n } else if (typeof matcher === 'undefined') {\n this[kNetConnect] = true\n } else {\n throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')\n }\n }\n\n disableNetConnect () {\n this[kNetConnect] = false\n }\n\n // This is required to bypass issues caused by using global symbols - see:\n // https://github.com/nodejs/undici/issues/1447\n get isMockActive () {\n return this[kIsMockActive]\n }\n\n [kMockAgentSet] (origin, dispatcher) {\n this[kClients].set(origin, new FakeWeakRef(dispatcher))\n }\n\n [kFactory] (origin) {\n const mockOptions = Object.assign({ agent: this }, this[kOptions])\n return this[kOptions] && this[kOptions].connections === 1\n ? new MockClient(origin, mockOptions)\n : new MockPool(origin, mockOptions)\n }\n\n [kMockAgentGet] (origin) {\n // First check if we can immediately find it\n const ref = this[kClients].get(origin)\n if (ref) {\n return ref.deref()\n }\n\n // If the origin is not a string create a dummy parent pool and return to user\n if (typeof origin !== 'string') {\n const dispatcher = this[kFactory]('http://localhost:9999')\n this[kMockAgentSet](origin, dispatcher)\n return dispatcher\n }\n\n // If we match, create a pool and assign the same dispatches\n for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {\n const nonExplicitDispatcher = nonExplicitRef.deref()\n if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {\n const dispatcher = this[kFactory](origin)\n this[kMockAgentSet](origin, dispatcher)\n dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]\n return dispatcher\n }\n }\n }\n\n [kGetNetConnect] () {\n return this[kNetConnect]\n }\n\n pendingInterceptors () {\n const mockAgentClients = this[kClients]\n\n return Array.from(mockAgentClients.entries())\n .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))\n .filter(({ pending }) => pending)\n }\n\n assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {\n const pending = this.pendingInterceptors()\n\n if (pending.length === 0) {\n return\n }\n\n const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)\n\n throw new UndiciError(`\n${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:\n\n${pendingInterceptorsFormatter.format(pending)}\n`.trim())\n }\n}\n\nmodule.exports = MockAgent\n","'use strict'\n\nconst { promisify } = require('util')\nconst Client = require('../client')\nconst { buildMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kMockAgent,\n kClose,\n kOriginalClose,\n kOrigin,\n kOriginalDispatch,\n kConnected\n} = require('./mock-symbols')\nconst { MockInterceptor } = require('./mock-interceptor')\nconst Symbols = require('../core/symbols')\nconst { InvalidArgumentError } = require('../core/errors')\n\n/**\n * MockClient provides an API that extends the Client to influence the mockDispatches.\n */\nclass MockClient extends Client {\n constructor (origin, opts) {\n super(origin, opts)\n\n if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n\n this[kMockAgent] = opts.agent\n this[kOrigin] = origin\n this[kDispatches] = []\n this[kConnected] = 1\n this[kOriginalDispatch] = this.dispatch\n this[kOriginalClose] = this.close.bind(this)\n\n this.dispatch = buildMockDispatch.call(this)\n this.close = this[kClose]\n }\n\n get [Symbols.kConnected] () {\n return this[kConnected]\n }\n\n /**\n * Sets up the base interceptor for mocking replies from undici.\n */\n intercept (opts) {\n return new MockInterceptor(opts, this[kDispatches])\n }\n\n async [kClose] () {\n await promisify(this[kOriginalClose])()\n this[kConnected] = 0\n this[kMockAgent][Symbols.kClients].delete(this[kOrigin])\n }\n}\n\nmodule.exports = MockClient\n","'use strict'\n\nconst { UndiciError } = require('../core/errors')\n\nclass MockNotMatchedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, MockNotMatchedError)\n this.name = 'MockNotMatchedError'\n this.message = message || 'The request does not match any registered mock dispatches'\n this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'\n }\n}\n\nmodule.exports = {\n MockNotMatchedError\n}\n","'use strict'\n\nconst { getResponseData, buildKey, addMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kDispatchKey,\n kDefaultHeaders,\n kDefaultTrailers,\n kContentLength,\n kMockDispatch\n} = require('./mock-symbols')\nconst { InvalidArgumentError } = require('../core/errors')\nconst { buildURL } = require('../core/util')\n\n/**\n * Defines the scope API for an interceptor reply\n */\nclass MockScope {\n constructor (mockDispatch) {\n this[kMockDispatch] = mockDispatch\n }\n\n /**\n * Delay a reply by a set amount in ms.\n */\n delay (waitInMs) {\n if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {\n throw new InvalidArgumentError('waitInMs must be a valid integer > 0')\n }\n\n this[kMockDispatch].delay = waitInMs\n return this\n }\n\n /**\n * For a defined reply, never mark as consumed.\n */\n persist () {\n this[kMockDispatch].persist = true\n return this\n }\n\n /**\n * Allow one to define a reply for a set amount of matching requests.\n */\n times (repeatTimes) {\n if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {\n throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')\n }\n\n this[kMockDispatch].times = repeatTimes\n return this\n }\n}\n\n/**\n * Defines an interceptor for a Mock\n */\nclass MockInterceptor {\n constructor (opts, mockDispatches) {\n if (typeof opts !== 'object') {\n throw new InvalidArgumentError('opts must be an object')\n }\n if (typeof opts.path === 'undefined') {\n throw new InvalidArgumentError('opts.path must be defined')\n }\n if (typeof opts.method === 'undefined') {\n opts.method = 'GET'\n }\n // See https://github.com/nodejs/undici/issues/1245\n // As per RFC 3986, clients are not supposed to send URI\n // fragments to servers when they retrieve a document,\n if (typeof opts.path === 'string') {\n if (opts.query) {\n opts.path = buildURL(opts.path, opts.query)\n } else {\n // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811\n const parsedURL = new URL(opts.path, 'data://')\n opts.path = parsedURL.pathname + parsedURL.search\n }\n }\n if (typeof opts.method === 'string') {\n opts.method = opts.method.toUpperCase()\n }\n\n this[kDispatchKey] = buildKey(opts)\n this[kDispatches] = mockDispatches\n this[kDefaultHeaders] = {}\n this[kDefaultTrailers] = {}\n this[kContentLength] = false\n }\n\n createMockScopeDispatchData (statusCode, data, responseOptions = {}) {\n const responseData = getResponseData(data)\n const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}\n const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }\n const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }\n\n return { statusCode, data, headers, trailers }\n }\n\n validateReplyParameters (statusCode, data, responseOptions) {\n if (typeof statusCode === 'undefined') {\n throw new InvalidArgumentError('statusCode must be defined')\n }\n if (typeof data === 'undefined') {\n throw new InvalidArgumentError('data must be defined')\n }\n if (typeof responseOptions !== 'object') {\n throw new InvalidArgumentError('responseOptions must be an object')\n }\n }\n\n /**\n * Mock an undici request with a defined reply.\n */\n reply (replyData) {\n // Values of reply aren't available right now as they\n // can only be available when the reply callback is invoked.\n if (typeof replyData === 'function') {\n // We'll first wrap the provided callback in another function,\n // this function will properly resolve the data from the callback\n // when invoked.\n const wrappedDefaultsCallback = (opts) => {\n // Our reply options callback contains the parameter for statusCode, data and options.\n const resolvedData = replyData(opts)\n\n // Check if it is in the right format\n if (typeof resolvedData !== 'object') {\n throw new InvalidArgumentError('reply options callback must return an object')\n }\n\n const { statusCode, data = '', responseOptions = {} } = resolvedData\n this.validateReplyParameters(statusCode, data, responseOptions)\n // Since the values can be obtained immediately we return them\n // from this higher order function that will be resolved later.\n return {\n ...this.createMockScopeDispatchData(statusCode, data, responseOptions)\n }\n }\n\n // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)\n return new MockScope(newMockDispatch)\n }\n\n // We can have either one or three parameters, if we get here,\n // we should have 1-3 parameters. So we spread the arguments of\n // this function to obtain the parameters, since replyData will always\n // just be the statusCode.\n const [statusCode, data = '', responseOptions = {}] = [...arguments]\n this.validateReplyParameters(statusCode, data, responseOptions)\n\n // Send in-already provided data like usual\n const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)\n return new MockScope(newMockDispatch)\n }\n\n /**\n * Mock an undici request with a defined error.\n */\n replyWithError (error) {\n if (typeof error === 'undefined') {\n throw new InvalidArgumentError('error must be defined')\n }\n\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })\n return new MockScope(newMockDispatch)\n }\n\n /**\n * Set default reply headers on the interceptor for subsequent replies\n */\n defaultReplyHeaders (headers) {\n if (typeof headers === 'undefined') {\n throw new InvalidArgumentError('headers must be defined')\n }\n\n this[kDefaultHeaders] = headers\n return this\n }\n\n /**\n * Set default reply trailers on the interceptor for subsequent replies\n */\n defaultReplyTrailers (trailers) {\n if (typeof trailers === 'undefined') {\n throw new InvalidArgumentError('trailers must be defined')\n }\n\n this[kDefaultTrailers] = trailers\n return this\n }\n\n /**\n * Set reply content length header for replies on the interceptor\n */\n replyContentLength () {\n this[kContentLength] = true\n return this\n }\n}\n\nmodule.exports.MockInterceptor = MockInterceptor\nmodule.exports.MockScope = MockScope\n","'use strict'\n\nconst { promisify } = require('util')\nconst Pool = require('../pool')\nconst { buildMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kMockAgent,\n kClose,\n kOriginalClose,\n kOrigin,\n kOriginalDispatch,\n kConnected\n} = require('./mock-symbols')\nconst { MockInterceptor } = require('./mock-interceptor')\nconst Symbols = require('../core/symbols')\nconst { InvalidArgumentError } = require('../core/errors')\n\n/**\n * MockPool provides an API that extends the Pool to influence the mockDispatches.\n */\nclass MockPool extends Pool {\n constructor (origin, opts) {\n super(origin, opts)\n\n if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n\n this[kMockAgent] = opts.agent\n this[kOrigin] = origin\n this[kDispatches] = []\n this[kConnected] = 1\n this[kOriginalDispatch] = this.dispatch\n this[kOriginalClose] = this.close.bind(this)\n\n this.dispatch = buildMockDispatch.call(this)\n this.close = this[kClose]\n }\n\n get [Symbols.kConnected] () {\n return this[kConnected]\n }\n\n /**\n * Sets up the base interceptor for mocking replies from undici.\n */\n intercept (opts) {\n return new MockInterceptor(opts, this[kDispatches])\n }\n\n async [kClose] () {\n await promisify(this[kOriginalClose])()\n this[kConnected] = 0\n this[kMockAgent][Symbols.kClients].delete(this[kOrigin])\n }\n}\n\nmodule.exports = MockPool\n","'use strict'\n\nmodule.exports = {\n kAgent: Symbol('agent'),\n kOptions: Symbol('options'),\n kFactory: Symbol('factory'),\n kDispatches: Symbol('dispatches'),\n kDispatchKey: Symbol('dispatch key'),\n kDefaultHeaders: Symbol('default headers'),\n kDefaultTrailers: Symbol('default trailers'),\n kContentLength: Symbol('content length'),\n kMockAgent: Symbol('mock agent'),\n kMockAgentSet: Symbol('mock agent set'),\n kMockAgentGet: Symbol('mock agent get'),\n kMockDispatch: Symbol('mock dispatch'),\n kClose: Symbol('close'),\n kOriginalClose: Symbol('original agent close'),\n kOrigin: Symbol('origin'),\n kIsMockActive: Symbol('is mock active'),\n kNetConnect: Symbol('net connect'),\n kGetNetConnect: Symbol('get net connect'),\n kConnected: Symbol('connected')\n}\n","'use strict'\n\nconst { MockNotMatchedError } = require('./mock-errors')\nconst {\n kDispatches,\n kMockAgent,\n kOriginalDispatch,\n kOrigin,\n kGetNetConnect\n} = require('./mock-symbols')\nconst { buildURL, nop } = require('../core/util')\nconst { STATUS_CODES } = require('http')\nconst {\n types: {\n isPromise\n }\n} = require('util')\n\nfunction matchValue (match, value) {\n if (typeof match === 'string') {\n return match === value\n }\n if (match instanceof RegExp) {\n return match.test(value)\n }\n if (typeof match === 'function') {\n return match(value) === true\n }\n return false\n}\n\nfunction lowerCaseEntries (headers) {\n return Object.fromEntries(\n Object.entries(headers).map(([headerName, headerValue]) => {\n return [headerName.toLocaleLowerCase(), headerValue]\n })\n )\n}\n\n/**\n * @param {import('../../index').Headers|string[]|Record} headers\n * @param {string} key\n */\nfunction getHeaderByName (headers, key) {\n if (Array.isArray(headers)) {\n for (let i = 0; i < headers.length; i += 2) {\n if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {\n return headers[i + 1]\n }\n }\n\n return undefined\n } else if (typeof headers.get === 'function') {\n return headers.get(key)\n } else {\n return lowerCaseEntries(headers)[key.toLocaleLowerCase()]\n }\n}\n\n/** @param {string[]} headers */\nfunction buildHeadersFromArray (headers) { // fetch HeadersList\n const clone = headers.slice()\n const entries = []\n for (let index = 0; index < clone.length; index += 2) {\n entries.push([clone[index], clone[index + 1]])\n }\n return Object.fromEntries(entries)\n}\n\nfunction matchHeaders (mockDispatch, headers) {\n if (typeof mockDispatch.headers === 'function') {\n if (Array.isArray(headers)) { // fetch HeadersList\n headers = buildHeadersFromArray(headers)\n }\n return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})\n }\n if (typeof mockDispatch.headers === 'undefined') {\n return true\n }\n if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {\n return false\n }\n\n for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {\n const headerValue = getHeaderByName(headers, matchHeaderName)\n\n if (!matchValue(matchHeaderValue, headerValue)) {\n return false\n }\n }\n return true\n}\n\nfunction safeUrl (path) {\n if (typeof path !== 'string') {\n return path\n }\n\n const pathSegments = path.split('?')\n\n if (pathSegments.length !== 2) {\n return path\n }\n\n const qp = new URLSearchParams(pathSegments.pop())\n qp.sort()\n return [...pathSegments, qp.toString()].join('?')\n}\n\nfunction matchKey (mockDispatch, { path, method, body, headers }) {\n const pathMatch = matchValue(mockDispatch.path, path)\n const methodMatch = matchValue(mockDispatch.method, method)\n const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true\n const headersMatch = matchHeaders(mockDispatch, headers)\n return pathMatch && methodMatch && bodyMatch && headersMatch\n}\n\nfunction getResponseData (data) {\n if (Buffer.isBuffer(data)) {\n return data\n } else if (typeof data === 'object') {\n return JSON.stringify(data)\n } else {\n return data.toString()\n }\n}\n\nfunction getMockDispatch (mockDispatches, key) {\n const basePath = key.query ? buildURL(key.path, key.query) : key.path\n const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath\n\n // Match path\n let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)\n }\n\n // Match method\n matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)\n }\n\n // Match body\n matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)\n }\n\n // Match headers\n matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)\n }\n\n return matchedMockDispatches[0]\n}\n\nfunction addMockDispatch (mockDispatches, key, data) {\n const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }\n const replyData = typeof data === 'function' ? { callback: data } : { ...data }\n const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }\n mockDispatches.push(newMockDispatch)\n return newMockDispatch\n}\n\nfunction deleteMockDispatch (mockDispatches, key) {\n const index = mockDispatches.findIndex(dispatch => {\n if (!dispatch.consumed) {\n return false\n }\n return matchKey(dispatch, key)\n })\n if (index !== -1) {\n mockDispatches.splice(index, 1)\n }\n}\n\nfunction buildKey (opts) {\n const { path, method, body, headers, query } = opts\n return {\n path,\n method,\n body,\n headers,\n query\n }\n}\n\nfunction generateKeyValues (data) {\n return Object.entries(data).reduce((keyValuePairs, [key, value]) => [\n ...keyValuePairs,\n Buffer.from(`${key}`),\n Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)\n ], [])\n}\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status\n * @param {number} statusCode\n */\nfunction getStatusText (statusCode) {\n return STATUS_CODES[statusCode] || 'unknown'\n}\n\nasync function getResponse (body) {\n const buffers = []\n for await (const data of body) {\n buffers.push(data)\n }\n return Buffer.concat(buffers).toString('utf8')\n}\n\n/**\n * Mock dispatch function used to simulate undici dispatches\n */\nfunction mockDispatch (opts, handler) {\n // Get mock dispatch from built key\n const key = buildKey(opts)\n const mockDispatch = getMockDispatch(this[kDispatches], key)\n\n mockDispatch.timesInvoked++\n\n // Here's where we resolve a callback if a callback is present for the dispatch data.\n if (mockDispatch.data.callback) {\n mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }\n }\n\n // Parse mockDispatch data\n const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch\n const { timesInvoked, times } = mockDispatch\n\n // If it's used up and not persistent, mark as consumed\n mockDispatch.consumed = !persist && timesInvoked >= times\n mockDispatch.pending = timesInvoked < times\n\n // If specified, trigger dispatch error\n if (error !== null) {\n deleteMockDispatch(this[kDispatches], key)\n handler.onError(error)\n return true\n }\n\n // Handle the request with a delay if necessary\n if (typeof delay === 'number' && delay > 0) {\n setTimeout(() => {\n handleReply(this[kDispatches])\n }, delay)\n } else {\n handleReply(this[kDispatches])\n }\n\n function handleReply (mockDispatches, _data = data) {\n // fetch's HeadersList is a 1D string array\n const optsHeaders = Array.isArray(opts.headers)\n ? buildHeadersFromArray(opts.headers)\n : opts.headers\n const body = typeof _data === 'function'\n ? _data({ ...opts, headers: optsHeaders })\n : _data\n\n // util.types.isPromise is likely needed for jest.\n if (isPromise(body)) {\n // If handleReply is asynchronous, throwing an error\n // in the callback will reject the promise, rather than\n // synchronously throw the error, which breaks some tests.\n // Rather, we wait for the callback to resolve if it is a\n // promise, and then re-run handleReply with the new body.\n body.then((newData) => handleReply(mockDispatches, newData))\n return\n }\n\n const responseData = getResponseData(body)\n const responseHeaders = generateKeyValues(headers)\n const responseTrailers = generateKeyValues(trailers)\n\n handler.abort = nop\n handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))\n handler.onData(Buffer.from(responseData))\n handler.onComplete(responseTrailers)\n deleteMockDispatch(mockDispatches, key)\n }\n\n function resume () {}\n\n return true\n}\n\nfunction buildMockDispatch () {\n const agent = this[kMockAgent]\n const origin = this[kOrigin]\n const originalDispatch = this[kOriginalDispatch]\n\n return function dispatch (opts, handler) {\n if (agent.isMockActive) {\n try {\n mockDispatch.call(this, opts, handler)\n } catch (error) {\n if (error instanceof MockNotMatchedError) {\n const netConnect = agent[kGetNetConnect]()\n if (netConnect === false) {\n throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)\n }\n if (checkNetConnect(netConnect, origin)) {\n originalDispatch.call(this, opts, handler)\n } else {\n throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)\n }\n } else {\n throw error\n }\n }\n } else {\n originalDispatch.call(this, opts, handler)\n }\n }\n}\n\nfunction checkNetConnect (netConnect, origin) {\n const url = new URL(origin)\n if (netConnect === true) {\n return true\n } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {\n return true\n }\n return false\n}\n\nfunction buildMockOptions (opts) {\n if (opts) {\n const { agent, ...mockOptions } = opts\n return mockOptions\n }\n}\n\nmodule.exports = {\n getResponseData,\n getMockDispatch,\n addMockDispatch,\n deleteMockDispatch,\n buildKey,\n generateKeyValues,\n matchValue,\n getResponse,\n getStatusText,\n mockDispatch,\n buildMockDispatch,\n checkNetConnect,\n buildMockOptions,\n getHeaderByName\n}\n","'use strict'\n\nconst { Transform } = require('stream')\nconst { Console } = require('console')\n\n/**\n * Gets the output of `console.table(…)` as a string.\n */\nmodule.exports = class PendingInterceptorsFormatter {\n constructor ({ disableColors } = {}) {\n this.transform = new Transform({\n transform (chunk, _enc, cb) {\n cb(null, chunk)\n }\n })\n\n this.logger = new Console({\n stdout: this.transform,\n inspectOptions: {\n colors: !disableColors && !process.env.CI\n }\n })\n }\n\n format (pendingInterceptors) {\n const withPrettyHeaders = pendingInterceptors.map(\n ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({\n Method: method,\n Origin: origin,\n Path: path,\n 'Status code': statusCode,\n Persistent: persist ? '✅' : '❌',\n Invocations: timesInvoked,\n Remaining: persist ? Infinity : times - timesInvoked\n }))\n\n this.logger.table(withPrettyHeaders)\n return this.transform.read().toString()\n }\n}\n","'use strict'\n\nconst singulars = {\n pronoun: 'it',\n is: 'is',\n was: 'was',\n this: 'this'\n}\n\nconst plurals = {\n pronoun: 'they',\n is: 'are',\n was: 'were',\n this: 'these'\n}\n\nmodule.exports = class Pluralizer {\n constructor (singular, plural) {\n this.singular = singular\n this.plural = plural\n }\n\n pluralize (count) {\n const one = count === 1\n const keys = one ? singulars : plurals\n const noun = one ? this.singular : this.plural\n return { ...keys, count, noun }\n }\n}\n","/* eslint-disable */\n\n'use strict'\n\n// Extracted from node/lib/internal/fixed_queue.js\n\n// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.\nconst kSize = 2048;\nconst kMask = kSize - 1;\n\n// The FixedQueue is implemented as a singly-linked list of fixed-size\n// circular buffers. It looks something like this:\n//\n// head tail\n// | |\n// v v\n// +-----------+ <-----\\ +-----------+ <------\\ +-----------+\n// | [null] | \\----- | next | \\------- | next |\n// +-----------+ +-----------+ +-----------+\n// | item | <-- bottom | item | <-- bottom | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | bottom --> | item |\n// | item | | item | | item |\n// | ... | | ... | | ... |\n// | item | | item | | item |\n// | item | | item | | item |\n// | [empty] | <-- top | item | | item |\n// | [empty] | | item | | item |\n// | [empty] | | [empty] | <-- top top --> | [empty] |\n// +-----------+ +-----------+ +-----------+\n//\n// Or, if there is only one circular buffer, it looks something\n// like either of these:\n//\n// head tail head tail\n// | | | |\n// v v v v\n// +-----------+ +-----------+\n// | [null] | | [null] |\n// +-----------+ +-----------+\n// | [empty] | | item |\n// | [empty] | | item |\n// | item | <-- bottom top --> | [empty] |\n// | item | | [empty] |\n// | [empty] | <-- top bottom --> | item |\n// | [empty] | | item |\n// +-----------+ +-----------+\n//\n// Adding a value means moving `top` forward by one, removing means\n// moving `bottom` forward by one. After reaching the end, the queue\n// wraps around.\n//\n// When `top === bottom` the current queue is empty and when\n// `top + 1 === bottom` it's full. This wastes a single space of storage\n// but allows much quicker checks.\n\nclass FixedCircularBuffer {\n constructor() {\n this.bottom = 0;\n this.top = 0;\n this.list = new Array(kSize);\n this.next = null;\n }\n\n isEmpty() {\n return this.top === this.bottom;\n }\n\n isFull() {\n return ((this.top + 1) & kMask) === this.bottom;\n }\n\n push(data) {\n this.list[this.top] = data;\n this.top = (this.top + 1) & kMask;\n }\n\n shift() {\n const nextItem = this.list[this.bottom];\n if (nextItem === undefined)\n return null;\n this.list[this.bottom] = undefined;\n this.bottom = (this.bottom + 1) & kMask;\n return nextItem;\n }\n}\n\nmodule.exports = class FixedQueue {\n constructor() {\n this.head = this.tail = new FixedCircularBuffer();\n }\n\n isEmpty() {\n return this.head.isEmpty();\n }\n\n push(data) {\n if (this.head.isFull()) {\n // Head is full: Creates a new queue, sets the old queue's `.next` to it,\n // and sets it as the new main queue.\n this.head = this.head.next = new FixedCircularBuffer();\n }\n this.head.push(data);\n }\n\n shift() {\n const tail = this.tail;\n const next = tail.shift();\n if (tail.isEmpty() && tail.next !== null) {\n // If there is another queue, it forms the new tail.\n this.tail = tail.next;\n }\n return next;\n }\n};\n","'use strict'\n\nconst DispatcherBase = require('./dispatcher-base')\nconst FixedQueue = require('./node/fixed-queue')\nconst { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('./core/symbols')\nconst PoolStats = require('./pool-stats')\n\nconst kClients = Symbol('clients')\nconst kNeedDrain = Symbol('needDrain')\nconst kQueue = Symbol('queue')\nconst kClosedResolve = Symbol('closed resolve')\nconst kOnDrain = Symbol('onDrain')\nconst kOnConnect = Symbol('onConnect')\nconst kOnDisconnect = Symbol('onDisconnect')\nconst kOnConnectionError = Symbol('onConnectionError')\nconst kGetDispatcher = Symbol('get dispatcher')\nconst kAddClient = Symbol('add client')\nconst kRemoveClient = Symbol('remove client')\nconst kStats = Symbol('stats')\n\nclass PoolBase extends DispatcherBase {\n constructor () {\n super()\n\n this[kQueue] = new FixedQueue()\n this[kClients] = []\n this[kQueued] = 0\n\n const pool = this\n\n this[kOnDrain] = function onDrain (origin, targets) {\n const queue = pool[kQueue]\n\n let needDrain = false\n\n while (!needDrain) {\n const item = queue.shift()\n if (!item) {\n break\n }\n pool[kQueued]--\n needDrain = !this.dispatch(item.opts, item.handler)\n }\n\n this[kNeedDrain] = needDrain\n\n if (!this[kNeedDrain] && pool[kNeedDrain]) {\n pool[kNeedDrain] = false\n pool.emit('drain', origin, [pool, ...targets])\n }\n\n if (pool[kClosedResolve] && queue.isEmpty()) {\n Promise\n .all(pool[kClients].map(c => c.close()))\n .then(pool[kClosedResolve])\n }\n }\n\n this[kOnConnect] = (origin, targets) => {\n pool.emit('connect', origin, [pool, ...targets])\n }\n\n this[kOnDisconnect] = (origin, targets, err) => {\n pool.emit('disconnect', origin, [pool, ...targets], err)\n }\n\n this[kOnConnectionError] = (origin, targets, err) => {\n pool.emit('connectionError', origin, [pool, ...targets], err)\n }\n\n this[kStats] = new PoolStats(this)\n }\n\n get [kBusy] () {\n return this[kNeedDrain]\n }\n\n get [kConnected] () {\n return this[kClients].filter(client => client[kConnected]).length\n }\n\n get [kFree] () {\n return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length\n }\n\n get [kPending] () {\n let ret = this[kQueued]\n for (const { [kPending]: pending } of this[kClients]) {\n ret += pending\n }\n return ret\n }\n\n get [kRunning] () {\n let ret = 0\n for (const { [kRunning]: running } of this[kClients]) {\n ret += running\n }\n return ret\n }\n\n get [kSize] () {\n let ret = this[kQueued]\n for (const { [kSize]: size } of this[kClients]) {\n ret += size\n }\n return ret\n }\n\n get stats () {\n return this[kStats]\n }\n\n async [kClose] () {\n if (this[kQueue].isEmpty()) {\n return Promise.all(this[kClients].map(c => c.close()))\n } else {\n return new Promise((resolve) => {\n this[kClosedResolve] = resolve\n })\n }\n }\n\n async [kDestroy] (err) {\n while (true) {\n const item = this[kQueue].shift()\n if (!item) {\n break\n }\n item.handler.onError(err)\n }\n\n return Promise.all(this[kClients].map(c => c.destroy(err)))\n }\n\n [kDispatch] (opts, handler) {\n const dispatcher = this[kGetDispatcher]()\n\n if (!dispatcher) {\n this[kNeedDrain] = true\n this[kQueue].push({ opts, handler })\n this[kQueued]++\n } else if (!dispatcher.dispatch(opts, handler)) {\n dispatcher[kNeedDrain] = true\n this[kNeedDrain] = !this[kGetDispatcher]()\n }\n\n return !this[kNeedDrain]\n }\n\n [kAddClient] (client) {\n client\n .on('drain', this[kOnDrain])\n .on('connect', this[kOnConnect])\n .on('disconnect', this[kOnDisconnect])\n .on('connectionError', this[kOnConnectionError])\n\n this[kClients].push(client)\n\n if (this[kNeedDrain]) {\n process.nextTick(() => {\n if (this[kNeedDrain]) {\n this[kOnDrain](client[kUrl], [this, client])\n }\n })\n }\n\n return this\n }\n\n [kRemoveClient] (client) {\n client.close(() => {\n const idx = this[kClients].indexOf(client)\n if (idx !== -1) {\n this[kClients].splice(idx, 1)\n }\n })\n\n this[kNeedDrain] = this[kClients].some(dispatcher => (\n !dispatcher[kNeedDrain] &&\n dispatcher.closed !== true &&\n dispatcher.destroyed !== true\n ))\n }\n}\n\nmodule.exports = {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kRemoveClient,\n kGetDispatcher\n}\n","const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require('./core/symbols')\nconst kPool = Symbol('pool')\n\nclass PoolStats {\n constructor (pool) {\n this[kPool] = pool\n }\n\n get connected () {\n return this[kPool][kConnected]\n }\n\n get free () {\n return this[kPool][kFree]\n }\n\n get pending () {\n return this[kPool][kPending]\n }\n\n get queued () {\n return this[kPool][kQueued]\n }\n\n get running () {\n return this[kPool][kRunning]\n }\n\n get size () {\n return this[kPool][kSize]\n }\n}\n\nmodule.exports = PoolStats\n","'use strict'\n\nconst {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kGetDispatcher\n} = require('./pool-base')\nconst Client = require('./client')\nconst {\n InvalidArgumentError\n} = require('./core/errors')\nconst util = require('./core/util')\nconst { kUrl, kInterceptors } = require('./core/symbols')\nconst buildConnector = require('./core/connect')\n\nconst kOptions = Symbol('options')\nconst kConnections = Symbol('connections')\nconst kFactory = Symbol('factory')\n\nfunction defaultFactory (origin, opts) {\n return new Client(origin, opts)\n}\n\nclass Pool extends PoolBase {\n constructor (origin, {\n connections,\n factory = defaultFactory,\n connect,\n connectTimeout,\n tls,\n maxCachedSessions,\n socketPath,\n autoSelectFamily,\n autoSelectFamilyAttemptTimeout,\n allowH2,\n ...options\n } = {}) {\n super()\n\n if (connections != null && (!Number.isFinite(connections) || connections < 0)) {\n throw new InvalidArgumentError('invalid connections')\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (typeof connect !== 'function') {\n connect = buildConnector({\n ...tls,\n maxCachedSessions,\n allowH2,\n socketPath,\n timeout: connectTimeout,\n ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),\n ...connect\n })\n }\n\n this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)\n ? options.interceptors.Pool\n : []\n this[kConnections] = connections || null\n this[kUrl] = util.parseOrigin(origin)\n this[kOptions] = { ...util.deepClone(options), connect, allowH2 }\n this[kOptions].interceptors = options.interceptors\n ? { ...options.interceptors }\n : undefined\n this[kFactory] = factory\n }\n\n [kGetDispatcher] () {\n let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])\n\n if (dispatcher) {\n return dispatcher\n }\n\n if (!this[kConnections] || this[kClients].length < this[kConnections]) {\n dispatcher = this[kFactory](this[kUrl], this[kOptions])\n this[kAddClient](dispatcher)\n }\n\n return dispatcher\n }\n}\n\nmodule.exports = Pool\n","'use strict'\n\nconst { kProxy, kClose, kDestroy, kInterceptors } = require('./core/symbols')\nconst { URL } = require('url')\nconst Agent = require('./agent')\nconst Pool = require('./pool')\nconst DispatcherBase = require('./dispatcher-base')\nconst { InvalidArgumentError, RequestAbortedError } = require('./core/errors')\nconst buildConnector = require('./core/connect')\n\nconst kAgent = Symbol('proxy agent')\nconst kClient = Symbol('proxy client')\nconst kProxyHeaders = Symbol('proxy headers')\nconst kRequestTls = Symbol('request tls settings')\nconst kProxyTls = Symbol('proxy tls settings')\nconst kConnectEndpoint = Symbol('connect endpoint function')\n\nfunction defaultProtocolPort (protocol) {\n return protocol === 'https:' ? 443 : 80\n}\n\nfunction buildProxyOptions (opts) {\n if (typeof opts === 'string') {\n opts = { uri: opts }\n }\n\n if (!opts || !opts.uri) {\n throw new InvalidArgumentError('Proxy opts.uri is mandatory')\n }\n\n return {\n uri: opts.uri,\n protocol: opts.protocol || 'https'\n }\n}\n\nfunction defaultFactory (origin, opts) {\n return new Pool(origin, opts)\n}\n\nclass ProxyAgent extends DispatcherBase {\n constructor (opts) {\n super(opts)\n this[kProxy] = buildProxyOptions(opts)\n this[kAgent] = new Agent(opts)\n this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)\n ? opts.interceptors.ProxyAgent\n : []\n\n if (typeof opts === 'string') {\n opts = { uri: opts }\n }\n\n if (!opts || !opts.uri) {\n throw new InvalidArgumentError('Proxy opts.uri is mandatory')\n }\n\n const { clientFactory = defaultFactory } = opts\n\n if (typeof clientFactory !== 'function') {\n throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')\n }\n\n this[kRequestTls] = opts.requestTls\n this[kProxyTls] = opts.proxyTls\n this[kProxyHeaders] = opts.headers || {}\n\n const resolvedUrl = new URL(opts.uri)\n const { origin, port, host, username, password } = resolvedUrl\n\n if (opts.auth && opts.token) {\n throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')\n } else if (opts.auth) {\n /* @deprecated in favour of opts.token */\n this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`\n } else if (opts.token) {\n this[kProxyHeaders]['proxy-authorization'] = opts.token\n } else if (username && password) {\n this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`\n }\n\n const connect = buildConnector({ ...opts.proxyTls })\n this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })\n this[kClient] = clientFactory(resolvedUrl, { connect })\n this[kAgent] = new Agent({\n ...opts,\n connect: async (opts, callback) => {\n let requestedHost = opts.host\n if (!opts.port) {\n requestedHost += `:${defaultProtocolPort(opts.protocol)}`\n }\n try {\n const { socket, statusCode } = await this[kClient].connect({\n origin,\n port,\n path: requestedHost,\n signal: opts.signal,\n headers: {\n ...this[kProxyHeaders],\n host\n }\n })\n if (statusCode !== 200) {\n socket.on('error', () => {}).destroy()\n callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))\n }\n if (opts.protocol !== 'https:') {\n callback(null, socket)\n return\n }\n let servername\n if (this[kRequestTls]) {\n servername = this[kRequestTls].servername\n } else {\n servername = opts.servername\n }\n this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)\n } catch (err) {\n callback(err)\n }\n }\n })\n }\n\n dispatch (opts, handler) {\n const { host } = new URL(opts.origin)\n const headers = buildHeaders(opts.headers)\n throwIfProxyAuthIsSent(headers)\n return this[kAgent].dispatch(\n {\n ...opts,\n headers: {\n ...headers,\n host\n }\n },\n handler\n )\n }\n\n async [kClose] () {\n await this[kAgent].close()\n await this[kClient].close()\n }\n\n async [kDestroy] () {\n await this[kAgent].destroy()\n await this[kClient].destroy()\n }\n}\n\n/**\n * @param {string[] | Record} headers\n * @returns {Record}\n */\nfunction buildHeaders (headers) {\n // When using undici.fetch, the headers list is stored\n // as an array.\n if (Array.isArray(headers)) {\n /** @type {Record} */\n const headersPair = {}\n\n for (let i = 0; i < headers.length; i += 2) {\n headersPair[headers[i]] = headers[i + 1]\n }\n\n return headersPair\n }\n\n return headers\n}\n\n/**\n * @param {Record} headers\n *\n * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers\n * Nevertheless, it was changed and to avoid a security vulnerability by end users\n * this check was created.\n * It should be removed in the next major version for performance reasons\n */\nfunction throwIfProxyAuthIsSent (headers) {\n const existProxyAuth = headers && Object.keys(headers)\n .find((key) => key.toLowerCase() === 'proxy-authorization')\n if (existProxyAuth) {\n throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')\n }\n}\n\nmodule.exports = ProxyAgent\n","'use strict'\n\nlet fastNow = Date.now()\nlet fastNowTimeout\n\nconst fastTimers = []\n\nfunction onTimeout () {\n fastNow = Date.now()\n\n let len = fastTimers.length\n let idx = 0\n while (idx < len) {\n const timer = fastTimers[idx]\n\n if (timer.state === 0) {\n timer.state = fastNow + timer.delay\n } else if (timer.state > 0 && fastNow >= timer.state) {\n timer.state = -1\n timer.callback(timer.opaque)\n }\n\n if (timer.state === -1) {\n timer.state = -2\n if (idx !== len - 1) {\n fastTimers[idx] = fastTimers.pop()\n } else {\n fastTimers.pop()\n }\n len -= 1\n } else {\n idx += 1\n }\n }\n\n if (fastTimers.length > 0) {\n refreshTimeout()\n }\n}\n\nfunction refreshTimeout () {\n if (fastNowTimeout && fastNowTimeout.refresh) {\n fastNowTimeout.refresh()\n } else {\n clearTimeout(fastNowTimeout)\n fastNowTimeout = setTimeout(onTimeout, 1e3)\n if (fastNowTimeout.unref) {\n fastNowTimeout.unref()\n }\n }\n}\n\nclass Timeout {\n constructor (callback, delay, opaque) {\n this.callback = callback\n this.delay = delay\n this.opaque = opaque\n\n // -2 not in timer list\n // -1 in timer list but inactive\n // 0 in timer list waiting for time\n // > 0 in timer list waiting for time to expire\n this.state = -2\n\n this.refresh()\n }\n\n refresh () {\n if (this.state === -2) {\n fastTimers.push(this)\n if (!fastNowTimeout || fastTimers.length === 1) {\n refreshTimeout()\n }\n }\n\n this.state = 0\n }\n\n clear () {\n this.state = -1\n }\n}\n\nmodule.exports = {\n setTimeout (callback, delay, opaque) {\n return delay < 1e3\n ? setTimeout(callback, delay, opaque)\n : new Timeout(callback, delay, opaque)\n },\n clearTimeout (timeout) {\n if (timeout instanceof Timeout) {\n timeout.clear()\n } else {\n clearTimeout(timeout)\n }\n }\n}\n","'use strict'\n\nconst diagnosticsChannel = require('diagnostics_channel')\nconst { uid, states } = require('./constants')\nconst {\n kReadyState,\n kSentClose,\n kByteParser,\n kReceivedClose\n} = require('./symbols')\nconst { fireEvent, failWebsocketConnection } = require('./util')\nconst { CloseEvent } = require('./events')\nconst { makeRequest } = require('../fetch/request')\nconst { fetching } = require('../fetch/index')\nconst { Headers } = require('../fetch/headers')\nconst { getGlobalDispatcher } = require('../global')\nconst { kHeadersList } = require('../core/symbols')\n\nconst channels = {}\nchannels.open = diagnosticsChannel.channel('undici:websocket:open')\nchannels.close = diagnosticsChannel.channel('undici:websocket:close')\nchannels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')\n\n/** @type {import('crypto')} */\nlet crypto\ntry {\n crypto = require('crypto')\n} catch {\n\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#concept-websocket-establish\n * @param {URL} url\n * @param {string|string[]} protocols\n * @param {import('./websocket').WebSocket} ws\n * @param {(response: any) => void} onEstablish\n * @param {Partial} options\n */\nfunction establishWebSocketConnection (url, protocols, ws, onEstablish, options) {\n // 1. Let requestURL be a copy of url, with its scheme set to \"http\", if url’s\n // scheme is \"ws\", and to \"https\" otherwise.\n const requestURL = url\n\n requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'\n\n // 2. Let request be a new request, whose URL is requestURL, client is client,\n // service-workers mode is \"none\", referrer is \"no-referrer\", mode is\n // \"websocket\", credentials mode is \"include\", cache mode is \"no-store\" ,\n // and redirect mode is \"error\".\n const request = makeRequest({\n urlList: [requestURL],\n serviceWorkers: 'none',\n referrer: 'no-referrer',\n mode: 'websocket',\n credentials: 'include',\n cache: 'no-store',\n redirect: 'error'\n })\n\n // Note: undici extension, allow setting custom headers.\n if (options.headers) {\n const headersList = new Headers(options.headers)[kHeadersList]\n\n request.headersList = headersList\n }\n\n // 3. Append (`Upgrade`, `websocket`) to request’s header list.\n // 4. Append (`Connection`, `Upgrade`) to request’s header list.\n // Note: both of these are handled by undici currently.\n // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397\n\n // 5. Let keyValue be a nonce consisting of a randomly selected\n // 16-byte value that has been forgiving-base64-encoded and\n // isomorphic encoded.\n const keyValue = crypto.randomBytes(16).toString('base64')\n\n // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s\n // header list.\n request.headersList.append('sec-websocket-key', keyValue)\n\n // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s\n // header list.\n request.headersList.append('sec-websocket-version', '13')\n\n // 8. For each protocol in protocols, combine\n // (`Sec-WebSocket-Protocol`, protocol) in request’s header\n // list.\n for (const protocol of protocols) {\n request.headersList.append('sec-websocket-protocol', protocol)\n }\n\n // 9. Let permessageDeflate be a user-agent defined\n // \"permessage-deflate\" extension header value.\n // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673\n // TODO: enable once permessage-deflate is supported\n const permessageDeflate = '' // 'permessage-deflate; 15'\n\n // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to\n // request’s header list.\n // request.headersList.append('sec-websocket-extensions', permessageDeflate)\n\n // 11. Fetch request with useParallelQueue set to true, and\n // processResponse given response being these steps:\n const controller = fetching({\n request,\n useParallelQueue: true,\n dispatcher: options.dispatcher ?? getGlobalDispatcher(),\n processResponse (response) {\n // 1. If response is a network error or its status is not 101,\n // fail the WebSocket connection.\n if (response.type === 'error' || response.status !== 101) {\n failWebsocketConnection(ws, 'Received network error or non-101 status code.')\n return\n }\n\n // 2. If protocols is not the empty list and extracting header\n // list values given `Sec-WebSocket-Protocol` and response’s\n // header list results in null, failure, or the empty byte\n // sequence, then fail the WebSocket connection.\n if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {\n failWebsocketConnection(ws, 'Server did not respond with sent protocols.')\n return\n }\n\n // 3. Follow the requirements stated step 2 to step 6, inclusive,\n // of the last set of steps in section 4.1 of The WebSocket\n // Protocol to validate response. This either results in fail\n // the WebSocket connection or the WebSocket connection is\n // established.\n\n // 2. If the response lacks an |Upgrade| header field or the |Upgrade|\n // header field contains a value that is not an ASCII case-\n // insensitive match for the value \"websocket\", the client MUST\n // _Fail the WebSocket Connection_.\n if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {\n failWebsocketConnection(ws, 'Server did not set Upgrade header to \"websocket\".')\n return\n }\n\n // 3. If the response lacks a |Connection| header field or the\n // |Connection| header field doesn't contain a token that is an\n // ASCII case-insensitive match for the value \"Upgrade\", the client\n // MUST _Fail the WebSocket Connection_.\n if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {\n failWebsocketConnection(ws, 'Server did not set Connection header to \"upgrade\".')\n return\n }\n\n // 4. If the response lacks a |Sec-WebSocket-Accept| header field or\n // the |Sec-WebSocket-Accept| contains a value other than the\n // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-\n // Key| (as a string, not base64-decoded) with the string \"258EAFA5-\n // E914-47DA-95CA-C5AB0DC85B11\" but ignoring any leading and\n // trailing whitespace, the client MUST _Fail the WebSocket\n // Connection_.\n const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')\n const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')\n if (secWSAccept !== digest) {\n failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')\n return\n }\n\n // 5. If the response includes a |Sec-WebSocket-Extensions| header\n // field and this header field indicates the use of an extension\n // that was not present in the client's handshake (the server has\n // indicated an extension not requested by the client), the client\n // MUST _Fail the WebSocket Connection_. (The parsing of this\n // header field to determine which extensions are requested is\n // discussed in Section 9.1.)\n const secExtension = response.headersList.get('Sec-WebSocket-Extensions')\n\n if (secExtension !== null && secExtension !== permessageDeflate) {\n failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')\n return\n }\n\n // 6. If the response includes a |Sec-WebSocket-Protocol| header field\n // and this header field indicates the use of a subprotocol that was\n // not present in the client's handshake (the server has indicated a\n // subprotocol not requested by the client), the client MUST _Fail\n // the WebSocket Connection_.\n const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')\n\n if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {\n failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')\n return\n }\n\n response.socket.on('data', onSocketData)\n response.socket.on('close', onSocketClose)\n response.socket.on('error', onSocketError)\n\n if (channels.open.hasSubscribers) {\n channels.open.publish({\n address: response.socket.address(),\n protocol: secProtocol,\n extensions: secExtension\n })\n }\n\n onEstablish(response)\n }\n })\n\n return controller\n}\n\n/**\n * @param {Buffer} chunk\n */\nfunction onSocketData (chunk) {\n if (!this.ws[kByteParser].write(chunk)) {\n this.pause()\n }\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4\n */\nfunction onSocketClose () {\n const { ws } = this\n\n // If the TCP connection was closed after the\n // WebSocket closing handshake was completed, the WebSocket connection\n // is said to have been closed _cleanly_.\n const wasClean = ws[kSentClose] && ws[kReceivedClose]\n\n let code = 1005\n let reason = ''\n\n const result = ws[kByteParser].closingInfo\n\n if (result) {\n code = result.code ?? 1005\n reason = result.reason\n } else if (!ws[kSentClose]) {\n // If _The WebSocket\n // Connection is Closed_ and no Close control frame was received by the\n // endpoint (such as could occur if the underlying transport connection\n // is lost), _The WebSocket Connection Close Code_ is considered to be\n // 1006.\n code = 1006\n }\n\n // 1. Change the ready state to CLOSED (3).\n ws[kReadyState] = states.CLOSED\n\n // 2. If the user agent was required to fail the WebSocket\n // connection, or if the WebSocket connection was closed\n // after being flagged as full, fire an event named error\n // at the WebSocket object.\n // TODO\n\n // 3. Fire an event named close at the WebSocket object,\n // using CloseEvent, with the wasClean attribute\n // initialized to true if the connection closed cleanly\n // and false otherwise, the code attribute initialized to\n // the WebSocket connection close code, and the reason\n // attribute initialized to the result of applying UTF-8\n // decode without BOM to the WebSocket connection close\n // reason.\n fireEvent('close', ws, CloseEvent, {\n wasClean, code, reason\n })\n\n if (channels.close.hasSubscribers) {\n channels.close.publish({\n websocket: ws,\n code,\n reason\n })\n }\n}\n\nfunction onSocketError (error) {\n const { ws } = this\n\n ws[kReadyState] = states.CLOSING\n\n if (channels.socketError.hasSubscribers) {\n channels.socketError.publish(error)\n }\n\n this.destroy()\n}\n\nmodule.exports = {\n establishWebSocketConnection\n}\n","'use strict'\n\n// This is a Globally Unique Identifier unique used\n// to validate that the endpoint accepts websocket\n// connections.\n// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3\nconst uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n\n/** @type {PropertyDescriptor} */\nconst staticPropertyDescriptors = {\n enumerable: true,\n writable: false,\n configurable: false\n}\n\nconst states = {\n CONNECTING: 0,\n OPEN: 1,\n CLOSING: 2,\n CLOSED: 3\n}\n\nconst opcodes = {\n CONTINUATION: 0x0,\n TEXT: 0x1,\n BINARY: 0x2,\n CLOSE: 0x8,\n PING: 0x9,\n PONG: 0xA\n}\n\nconst maxUnsigned16Bit = 2 ** 16 - 1 // 65535\n\nconst parserStates = {\n INFO: 0,\n PAYLOADLENGTH_16: 2,\n PAYLOADLENGTH_64: 3,\n READ_DATA: 4\n}\n\nconst emptyBuffer = Buffer.allocUnsafe(0)\n\nmodule.exports = {\n uid,\n staticPropertyDescriptors,\n states,\n opcodes,\n maxUnsigned16Bit,\n parserStates,\n emptyBuffer\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\nconst { MessagePort } = require('worker_threads')\n\n/**\n * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent\n */\nclass MessageEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.MessageEventInit(eventInitDict)\n\n super(type, eventInitDict)\n\n this.#eventInit = eventInitDict\n }\n\n get data () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.data\n }\n\n get origin () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.origin\n }\n\n get lastEventId () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.lastEventId\n }\n\n get source () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.source\n }\n\n get ports () {\n webidl.brandCheck(this, MessageEvent)\n\n if (!Object.isFrozen(this.#eventInit.ports)) {\n Object.freeze(this.#eventInit.ports)\n }\n\n return this.#eventInit.ports\n }\n\n initMessageEvent (\n type,\n bubbles = false,\n cancelable = false,\n data = null,\n origin = '',\n lastEventId = '',\n source = null,\n ports = []\n ) {\n webidl.brandCheck(this, MessageEvent)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })\n\n return new MessageEvent(type, {\n bubbles, cancelable, data, origin, lastEventId, source, ports\n })\n }\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#the-closeevent-interface\n */\nclass CloseEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.CloseEventInit(eventInitDict)\n\n super(type, eventInitDict)\n\n this.#eventInit = eventInitDict\n }\n\n get wasClean () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.wasClean\n }\n\n get code () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.code\n }\n\n get reason () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.reason\n }\n}\n\n// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface\nclass ErrorEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })\n\n super(type, eventInitDict)\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})\n\n this.#eventInit = eventInitDict\n }\n\n get message () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.message\n }\n\n get filename () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.filename\n }\n\n get lineno () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.lineno\n }\n\n get colno () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.colno\n }\n\n get error () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.error\n }\n}\n\nObject.defineProperties(MessageEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'MessageEvent',\n configurable: true\n },\n data: kEnumerableProperty,\n origin: kEnumerableProperty,\n lastEventId: kEnumerableProperty,\n source: kEnumerableProperty,\n ports: kEnumerableProperty,\n initMessageEvent: kEnumerableProperty\n})\n\nObject.defineProperties(CloseEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'CloseEvent',\n configurable: true\n },\n reason: kEnumerableProperty,\n code: kEnumerableProperty,\n wasClean: kEnumerableProperty\n})\n\nObject.defineProperties(ErrorEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'ErrorEvent',\n configurable: true\n },\n message: kEnumerableProperty,\n filename: kEnumerableProperty,\n lineno: kEnumerableProperty,\n colno: kEnumerableProperty,\n error: kEnumerableProperty\n})\n\nwebidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.MessagePort\n)\n\nconst eventInit = [\n {\n key: 'bubbles',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'cancelable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'composed',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n]\n\nwebidl.converters.MessageEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'data',\n converter: webidl.converters.any,\n defaultValue: null\n },\n {\n key: 'origin',\n converter: webidl.converters.USVString,\n defaultValue: ''\n },\n {\n key: 'lastEventId',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'source',\n // Node doesn't implement WindowProxy or ServiceWorker, so the only\n // valid value for source is a MessagePort.\n converter: webidl.nullableConverter(webidl.converters.MessagePort),\n defaultValue: null\n },\n {\n key: 'ports',\n converter: webidl.converters['sequence'],\n get defaultValue () {\n return []\n }\n }\n])\n\nwebidl.converters.CloseEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'wasClean',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'code',\n converter: webidl.converters['unsigned short'],\n defaultValue: 0\n },\n {\n key: 'reason',\n converter: webidl.converters.USVString,\n defaultValue: ''\n }\n])\n\nwebidl.converters.ErrorEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'message',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'filename',\n converter: webidl.converters.USVString,\n defaultValue: ''\n },\n {\n key: 'lineno',\n converter: webidl.converters['unsigned long'],\n defaultValue: 0\n },\n {\n key: 'colno',\n converter: webidl.converters['unsigned long'],\n defaultValue: 0\n },\n {\n key: 'error',\n converter: webidl.converters.any\n }\n])\n\nmodule.exports = {\n MessageEvent,\n CloseEvent,\n ErrorEvent\n}\n","'use strict'\n\nconst { maxUnsigned16Bit } = require('./constants')\n\n/** @type {import('crypto')} */\nlet crypto\ntry {\n crypto = require('crypto')\n} catch {\n\n}\n\nclass WebsocketFrameSend {\n /**\n * @param {Buffer|undefined} data\n */\n constructor (data) {\n this.frameData = data\n this.maskKey = crypto.randomBytes(4)\n }\n\n createFrame (opcode) {\n const bodyLength = this.frameData?.byteLength ?? 0\n\n /** @type {number} */\n let payloadLength = bodyLength // 0-125\n let offset = 6\n\n if (bodyLength > maxUnsigned16Bit) {\n offset += 8 // payload length is next 8 bytes\n payloadLength = 127\n } else if (bodyLength > 125) {\n offset += 2 // payload length is next 2 bytes\n payloadLength = 126\n }\n\n const buffer = Buffer.allocUnsafe(bodyLength + offset)\n\n // Clear first 2 bytes, everything else is overwritten\n buffer[0] = buffer[1] = 0\n buffer[0] |= 0x80 // FIN\n buffer[0] = (buffer[0] & 0xF0) + opcode // opcode\n\n /*! ws. MIT License. Einar Otto Stangvik */\n buffer[offset - 4] = this.maskKey[0]\n buffer[offset - 3] = this.maskKey[1]\n buffer[offset - 2] = this.maskKey[2]\n buffer[offset - 1] = this.maskKey[3]\n\n buffer[1] = payloadLength\n\n if (payloadLength === 126) {\n buffer.writeUInt16BE(bodyLength, 2)\n } else if (payloadLength === 127) {\n // Clear extended payload length\n buffer[2] = buffer[3] = 0\n buffer.writeUIntBE(bodyLength, 4, 6)\n }\n\n buffer[1] |= 0x80 // MASK\n\n // mask body\n for (let i = 0; i < bodyLength; i++) {\n buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]\n }\n\n return buffer\n }\n}\n\nmodule.exports = {\n WebsocketFrameSend\n}\n","'use strict'\n\nconst { Writable } = require('stream')\nconst diagnosticsChannel = require('diagnostics_channel')\nconst { parserStates, opcodes, states, emptyBuffer } = require('./constants')\nconst { kReadyState, kSentClose, kResponse, kReceivedClose } = require('./symbols')\nconst { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = require('./util')\nconst { WebsocketFrameSend } = require('./frame')\n\n// This code was influenced by ws released under the MIT license.\n// Copyright (c) 2011 Einar Otto Stangvik \n// Copyright (c) 2013 Arnout Kazemier and contributors\n// Copyright (c) 2016 Luigi Pinca and contributors\n\nconst channels = {}\nchannels.ping = diagnosticsChannel.channel('undici:websocket:ping')\nchannels.pong = diagnosticsChannel.channel('undici:websocket:pong')\n\nclass ByteParser extends Writable {\n #buffers = []\n #byteOffset = 0\n\n #state = parserStates.INFO\n\n #info = {}\n #fragments = []\n\n constructor (ws) {\n super()\n\n this.ws = ws\n }\n\n /**\n * @param {Buffer} chunk\n * @param {() => void} callback\n */\n _write (chunk, _, callback) {\n this.#buffers.push(chunk)\n this.#byteOffset += chunk.length\n\n this.run(callback)\n }\n\n /**\n * Runs whenever a new chunk is received.\n * Callback is called whenever there are no more chunks buffering,\n * or not enough bytes are buffered to parse.\n */\n run (callback) {\n while (true) {\n if (this.#state === parserStates.INFO) {\n // If there aren't enough bytes to parse the payload length, etc.\n if (this.#byteOffset < 2) {\n return callback()\n }\n\n const buffer = this.consume(2)\n\n this.#info.fin = (buffer[0] & 0x80) !== 0\n this.#info.opcode = buffer[0] & 0x0F\n\n // If we receive a fragmented message, we use the type of the first\n // frame to parse the full message as binary/text, when it's terminated\n this.#info.originalOpcode ??= this.#info.opcode\n\n this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION\n\n if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {\n // Only text and binary frames can be fragmented\n failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')\n return\n }\n\n const payloadLength = buffer[1] & 0x7F\n\n if (payloadLength <= 125) {\n this.#info.payloadLength = payloadLength\n this.#state = parserStates.READ_DATA\n } else if (payloadLength === 126) {\n this.#state = parserStates.PAYLOADLENGTH_16\n } else if (payloadLength === 127) {\n this.#state = parserStates.PAYLOADLENGTH_64\n }\n\n if (this.#info.fragmented && payloadLength > 125) {\n // A fragmented frame can't be fragmented itself\n failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')\n return\n } else if (\n (this.#info.opcode === opcodes.PING ||\n this.#info.opcode === opcodes.PONG ||\n this.#info.opcode === opcodes.CLOSE) &&\n payloadLength > 125\n ) {\n // Control frames can have a payload length of 125 bytes MAX\n failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')\n return\n } else if (this.#info.opcode === opcodes.CLOSE) {\n if (payloadLength === 1) {\n failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')\n return\n }\n\n const body = this.consume(payloadLength)\n\n this.#info.closeInfo = this.parseCloseBody(false, body)\n\n if (!this.ws[kSentClose]) {\n // If an endpoint receives a Close frame and did not previously send a\n // Close frame, the endpoint MUST send a Close frame in response. (When\n // sending a Close frame in response, the endpoint typically echos the\n // status code it received.)\n const body = Buffer.allocUnsafe(2)\n body.writeUInt16BE(this.#info.closeInfo.code, 0)\n const closeFrame = new WebsocketFrameSend(body)\n\n this.ws[kResponse].socket.write(\n closeFrame.createFrame(opcodes.CLOSE),\n (err) => {\n if (!err) {\n this.ws[kSentClose] = true\n }\n }\n )\n }\n\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n this.ws[kReadyState] = states.CLOSING\n this.ws[kReceivedClose] = true\n\n this.end()\n\n return\n } else if (this.#info.opcode === opcodes.PING) {\n // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in\n // response, unless it already received a Close frame.\n // A Pong frame sent in response to a Ping frame must have identical\n // \"Application data\"\n\n const body = this.consume(payloadLength)\n\n if (!this.ws[kReceivedClose]) {\n const frame = new WebsocketFrameSend(body)\n\n this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))\n\n if (channels.ping.hasSubscribers) {\n channels.ping.publish({\n payload: body\n })\n }\n }\n\n this.#state = parserStates.INFO\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n return\n }\n } else if (this.#info.opcode === opcodes.PONG) {\n // A Pong frame MAY be sent unsolicited. This serves as a\n // unidirectional heartbeat. A response to an unsolicited Pong frame is\n // not expected.\n\n const body = this.consume(payloadLength)\n\n if (channels.pong.hasSubscribers) {\n channels.pong.publish({\n payload: body\n })\n }\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n return\n }\n }\n } else if (this.#state === parserStates.PAYLOADLENGTH_16) {\n if (this.#byteOffset < 2) {\n return callback()\n }\n\n const buffer = this.consume(2)\n\n this.#info.payloadLength = buffer.readUInt16BE(0)\n this.#state = parserStates.READ_DATA\n } else if (this.#state === parserStates.PAYLOADLENGTH_64) {\n if (this.#byteOffset < 8) {\n return callback()\n }\n\n const buffer = this.consume(8)\n const upper = buffer.readUInt32BE(0)\n\n // 2^31 is the maxinimum bytes an arraybuffer can contain\n // on 32-bit systems. Although, on 64-bit systems, this is\n // 2^53-1 bytes.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length\n // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275\n // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e\n if (upper > 2 ** 31 - 1) {\n failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')\n return\n }\n\n const lower = buffer.readUInt32BE(4)\n\n this.#info.payloadLength = (upper << 8) + lower\n this.#state = parserStates.READ_DATA\n } else if (this.#state === parserStates.READ_DATA) {\n if (this.#byteOffset < this.#info.payloadLength) {\n // If there is still more data in this chunk that needs to be read\n return callback()\n } else if (this.#byteOffset >= this.#info.payloadLength) {\n // If the server sent multiple frames in a single chunk\n\n const body = this.consume(this.#info.payloadLength)\n\n this.#fragments.push(body)\n\n // If the frame is unfragmented, or a fragmented frame was terminated,\n // a message was received\n if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {\n const fullMessage = Buffer.concat(this.#fragments)\n\n websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)\n\n this.#info = {}\n this.#fragments.length = 0\n }\n\n this.#state = parserStates.INFO\n }\n }\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n break\n }\n }\n }\n\n /**\n * Take n bytes from the buffered Buffers\n * @param {number} n\n * @returns {Buffer|null}\n */\n consume (n) {\n if (n > this.#byteOffset) {\n return null\n } else if (n === 0) {\n return emptyBuffer\n }\n\n if (this.#buffers[0].length === n) {\n this.#byteOffset -= this.#buffers[0].length\n return this.#buffers.shift()\n }\n\n const buffer = Buffer.allocUnsafe(n)\n let offset = 0\n\n while (offset !== n) {\n const next = this.#buffers[0]\n const { length } = next\n\n if (length + offset === n) {\n buffer.set(this.#buffers.shift(), offset)\n break\n } else if (length + offset > n) {\n buffer.set(next.subarray(0, n - offset), offset)\n this.#buffers[0] = next.subarray(n - offset)\n break\n } else {\n buffer.set(this.#buffers.shift(), offset)\n offset += next.length\n }\n }\n\n this.#byteOffset -= n\n\n return buffer\n }\n\n parseCloseBody (onlyCode, data) {\n // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5\n /** @type {number|undefined} */\n let code\n\n if (data.length >= 2) {\n // _The WebSocket Connection Close Code_ is\n // defined as the status code (Section 7.4) contained in the first Close\n // control frame received by the application\n code = data.readUInt16BE(0)\n }\n\n if (onlyCode) {\n if (!isValidStatusCode(code)) {\n return null\n }\n\n return { code }\n }\n\n // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6\n /** @type {Buffer} */\n let reason = data.subarray(2)\n\n // Remove BOM\n if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {\n reason = reason.subarray(3)\n }\n\n if (code !== undefined && !isValidStatusCode(code)) {\n return null\n }\n\n try {\n // TODO: optimize this\n reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)\n } catch {\n return null\n }\n\n return { code, reason }\n }\n\n get closingInfo () {\n return this.#info.closeInfo\n }\n}\n\nmodule.exports = {\n ByteParser\n}\n","'use strict'\n\nmodule.exports = {\n kWebSocketURL: Symbol('url'),\n kReadyState: Symbol('ready state'),\n kController: Symbol('controller'),\n kResponse: Symbol('response'),\n kBinaryType: Symbol('binary type'),\n kSentClose: Symbol('sent close'),\n kReceivedClose: Symbol('received close'),\n kByteParser: Symbol('byte parser')\n}\n","'use strict'\n\nconst { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols')\nconst { states, opcodes } = require('./constants')\nconst { MessageEvent, ErrorEvent } = require('./events')\n\n/* globals Blob */\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isEstablished (ws) {\n // If the server's response is validated as provided for above, it is\n // said that _The WebSocket Connection is Established_ and that the\n // WebSocket Connection is in the OPEN state.\n return ws[kReadyState] === states.OPEN\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isClosing (ws) {\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n return ws[kReadyState] === states.CLOSING\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isClosed (ws) {\n return ws[kReadyState] === states.CLOSED\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e\n * @param {EventTarget} target\n * @param {EventInit | undefined} eventInitDict\n */\nfunction fireEvent (e, target, eventConstructor = Event, eventInitDict) {\n // 1. If eventConstructor is not given, then let eventConstructor be Event.\n\n // 2. Let event be the result of creating an event given eventConstructor,\n // in the relevant realm of target.\n // 3. Initialize event’s type attribute to e.\n const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap\n\n // 4. Initialize any other IDL attributes of event as described in the\n // invocation of this algorithm.\n\n // 5. Return the result of dispatching event at target, with legacy target\n // override flag set if set.\n target.dispatchEvent(event)\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @param {import('./websocket').WebSocket} ws\n * @param {number} type Opcode\n * @param {Buffer} data application data\n */\nfunction websocketMessageReceived (ws, type, data) {\n // 1. If ready state is not OPEN (1), then return.\n if (ws[kReadyState] !== states.OPEN) {\n return\n }\n\n // 2. Let dataForEvent be determined by switching on type and binary type:\n let dataForEvent\n\n if (type === opcodes.TEXT) {\n // -> type indicates that the data is Text\n // a new DOMString containing data\n try {\n dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)\n } catch {\n failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')\n return\n }\n } else if (type === opcodes.BINARY) {\n if (ws[kBinaryType] === 'blob') {\n // -> type indicates that the data is Binary and binary type is \"blob\"\n // a new Blob object, created in the relevant Realm of the WebSocket\n // object, that represents data as its raw data\n dataForEvent = new Blob([data])\n } else {\n // -> type indicates that the data is Binary and binary type is \"arraybuffer\"\n // a new ArrayBuffer object, created in the relevant Realm of the\n // WebSocket object, whose contents are data\n dataForEvent = new Uint8Array(data).buffer\n }\n }\n\n // 3. Fire an event named message at the WebSocket object, using MessageEvent,\n // with the origin attribute initialized to the serialization of the WebSocket\n // object’s url's origin, and the data attribute initialized to dataForEvent.\n fireEvent('message', ws, MessageEvent, {\n origin: ws[kWebSocketURL].origin,\n data: dataForEvent\n })\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455\n * @see https://datatracker.ietf.org/doc/html/rfc2616\n * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407\n * @param {string} protocol\n */\nfunction isValidSubprotocol (protocol) {\n // If present, this value indicates one\n // or more comma-separated subprotocol the client wishes to speak,\n // ordered by preference. The elements that comprise this value\n // MUST be non-empty strings with characters in the range U+0021 to\n // U+007E not including separator characters as defined in\n // [RFC2616] and MUST all be unique strings.\n if (protocol.length === 0) {\n return false\n }\n\n for (const char of protocol) {\n const code = char.charCodeAt(0)\n\n if (\n code < 0x21 ||\n code > 0x7E ||\n char === '(' ||\n char === ')' ||\n char === '<' ||\n char === '>' ||\n char === '@' ||\n char === ',' ||\n char === ';' ||\n char === ':' ||\n char === '\\\\' ||\n char === '\"' ||\n char === '/' ||\n char === '[' ||\n char === ']' ||\n char === '?' ||\n char === '=' ||\n char === '{' ||\n char === '}' ||\n code === 32 || // SP\n code === 9 // HT\n ) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4\n * @param {number} code\n */\nfunction isValidStatusCode (code) {\n if (code >= 1000 && code < 1015) {\n return (\n code !== 1004 && // reserved\n code !== 1005 && // \"MUST NOT be set as a status code\"\n code !== 1006 // \"MUST NOT be set as a status code\"\n )\n }\n\n return code >= 3000 && code <= 4999\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n * @param {string|undefined} reason\n */\nfunction failWebsocketConnection (ws, reason) {\n const { [kController]: controller, [kResponse]: response } = ws\n\n controller.abort()\n\n if (response?.socket && !response.socket.destroyed) {\n response.socket.destroy()\n }\n\n if (reason) {\n fireEvent('error', ws, ErrorEvent, {\n error: new Error(reason)\n })\n }\n}\n\nmodule.exports = {\n isEstablished,\n isClosing,\n isClosed,\n fireEvent,\n isValidSubprotocol,\n isValidStatusCode,\n failWebsocketConnection,\n websocketMessageReceived\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\nconst { DOMException } = require('../fetch/constants')\nconst { URLSerializer } = require('../fetch/dataURL')\nconst { getGlobalOrigin } = require('../fetch/global')\nconst { staticPropertyDescriptors, states, opcodes, emptyBuffer } = require('./constants')\nconst {\n kWebSocketURL,\n kReadyState,\n kController,\n kBinaryType,\n kResponse,\n kSentClose,\n kByteParser\n} = require('./symbols')\nconst { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = require('./util')\nconst { establishWebSocketConnection } = require('./connection')\nconst { WebsocketFrameSend } = require('./frame')\nconst { ByteParser } = require('./receiver')\nconst { kEnumerableProperty, isBlobLike } = require('../core/util')\nconst { getGlobalDispatcher } = require('../global')\nconst { types } = require('util')\n\nlet experimentalWarned = false\n\n// https://websockets.spec.whatwg.org/#interface-definition\nclass WebSocket extends EventTarget {\n #events = {\n open: null,\n error: null,\n close: null,\n message: null\n }\n\n #bufferedAmount = 0\n #protocol = ''\n #extensions = ''\n\n /**\n * @param {string} url\n * @param {string|string[]} protocols\n */\n constructor (url, protocols = []) {\n super()\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })\n\n if (!experimentalWarned) {\n experimentalWarned = true\n process.emitWarning('WebSockets are experimental, expect them to change at any time.', {\n code: 'UNDICI-WS'\n })\n }\n\n const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)\n\n url = webidl.converters.USVString(url)\n protocols = options.protocols\n\n // 1. Let baseURL be this's relevant settings object's API base URL.\n const baseURL = getGlobalOrigin()\n\n // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.\n let urlRecord\n\n try {\n urlRecord = new URL(url, baseURL)\n } catch (e) {\n // 3. If urlRecord is failure, then throw a \"SyntaxError\" DOMException.\n throw new DOMException(e, 'SyntaxError')\n }\n\n // 4. If urlRecord’s scheme is \"http\", then set urlRecord’s scheme to \"ws\".\n if (urlRecord.protocol === 'http:') {\n urlRecord.protocol = 'ws:'\n } else if (urlRecord.protocol === 'https:') {\n // 5. Otherwise, if urlRecord’s scheme is \"https\", set urlRecord’s scheme to \"wss\".\n urlRecord.protocol = 'wss:'\n }\n\n // 6. If urlRecord’s scheme is not \"ws\" or \"wss\", then throw a \"SyntaxError\" DOMException.\n if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {\n throw new DOMException(\n `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,\n 'SyntaxError'\n )\n }\n\n // 7. If urlRecord’s fragment is non-null, then throw a \"SyntaxError\"\n // DOMException.\n if (urlRecord.hash || urlRecord.href.endsWith('#')) {\n throw new DOMException('Got fragment', 'SyntaxError')\n }\n\n // 8. If protocols is a string, set protocols to a sequence consisting\n // of just that string.\n if (typeof protocols === 'string') {\n protocols = [protocols]\n }\n\n // 9. If any of the values in protocols occur more than once or otherwise\n // fail to match the requirements for elements that comprise the value\n // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket\n // protocol, then throw a \"SyntaxError\" DOMException.\n if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {\n throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')\n }\n\n if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {\n throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')\n }\n\n // 10. Set this's url to urlRecord.\n this[kWebSocketURL] = new URL(urlRecord.href)\n\n // 11. Let client be this's relevant settings object.\n\n // 12. Run this step in parallel:\n\n // 1. Establish a WebSocket connection given urlRecord, protocols,\n // and client.\n this[kController] = establishWebSocketConnection(\n urlRecord,\n protocols,\n this,\n (response) => this.#onConnectionEstablished(response),\n options\n )\n\n // Each WebSocket object has an associated ready state, which is a\n // number representing the state of the connection. Initially it must\n // be CONNECTING (0).\n this[kReadyState] = WebSocket.CONNECTING\n\n // The extensions attribute must initially return the empty string.\n\n // The protocol attribute must initially return the empty string.\n\n // Each WebSocket object has an associated binary type, which is a\n // BinaryType. Initially it must be \"blob\".\n this[kBinaryType] = 'blob'\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#dom-websocket-close\n * @param {number|undefined} code\n * @param {string|undefined} reason\n */\n close (code = undefined, reason = undefined) {\n webidl.brandCheck(this, WebSocket)\n\n if (code !== undefined) {\n code = webidl.converters['unsigned short'](code, { clamp: true })\n }\n\n if (reason !== undefined) {\n reason = webidl.converters.USVString(reason)\n }\n\n // 1. If code is present, but is neither an integer equal to 1000 nor an\n // integer in the range 3000 to 4999, inclusive, throw an\n // \"InvalidAccessError\" DOMException.\n if (code !== undefined) {\n if (code !== 1000 && (code < 3000 || code > 4999)) {\n throw new DOMException('invalid code', 'InvalidAccessError')\n }\n }\n\n let reasonByteLength = 0\n\n // 2. If reason is present, then run these substeps:\n if (reason !== undefined) {\n // 1. Let reasonBytes be the result of encoding reason.\n // 2. If reasonBytes is longer than 123 bytes, then throw a\n // \"SyntaxError\" DOMException.\n reasonByteLength = Buffer.byteLength(reason)\n\n if (reasonByteLength > 123) {\n throw new DOMException(\n `Reason must be less than 123 bytes; received ${reasonByteLength}`,\n 'SyntaxError'\n )\n }\n }\n\n // 3. Run the first matching steps from the following list:\n if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {\n // If this's ready state is CLOSING (2) or CLOSED (3)\n // Do nothing.\n } else if (!isEstablished(this)) {\n // If the WebSocket connection is not yet established\n // Fail the WebSocket connection and set this's ready state\n // to CLOSING (2).\n failWebsocketConnection(this, 'Connection was closed before it was established.')\n this[kReadyState] = WebSocket.CLOSING\n } else if (!isClosing(this)) {\n // If the WebSocket closing handshake has not yet been started\n // Start the WebSocket closing handshake and set this's ready\n // state to CLOSING (2).\n // - If neither code nor reason is present, the WebSocket Close\n // message must not have a body.\n // - If code is present, then the status code to use in the\n // WebSocket Close message must be the integer given by code.\n // - If reason is also present, then reasonBytes must be\n // provided in the Close message after the status code.\n\n const frame = new WebsocketFrameSend()\n\n // If neither code nor reason is present, the WebSocket Close\n // message must not have a body.\n\n // If code is present, then the status code to use in the\n // WebSocket Close message must be the integer given by code.\n if (code !== undefined && reason === undefined) {\n frame.frameData = Buffer.allocUnsafe(2)\n frame.frameData.writeUInt16BE(code, 0)\n } else if (code !== undefined && reason !== undefined) {\n // If reason is also present, then reasonBytes must be\n // provided in the Close message after the status code.\n frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)\n frame.frameData.writeUInt16BE(code, 0)\n // the body MAY contain UTF-8-encoded data with value /reason/\n frame.frameData.write(reason, 2, 'utf-8')\n } else {\n frame.frameData = emptyBuffer\n }\n\n /** @type {import('stream').Duplex} */\n const socket = this[kResponse].socket\n\n socket.write(frame.createFrame(opcodes.CLOSE), (err) => {\n if (!err) {\n this[kSentClose] = true\n }\n })\n\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n this[kReadyState] = states.CLOSING\n } else {\n // Otherwise\n // Set this's ready state to CLOSING (2).\n this[kReadyState] = WebSocket.CLOSING\n }\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#dom-websocket-send\n * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data\n */\n send (data) {\n webidl.brandCheck(this, WebSocket)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })\n\n data = webidl.converters.WebSocketSendData(data)\n\n // 1. If this's ready state is CONNECTING, then throw an\n // \"InvalidStateError\" DOMException.\n if (this[kReadyState] === WebSocket.CONNECTING) {\n throw new DOMException('Sent before connected.', 'InvalidStateError')\n }\n\n // 2. Run the appropriate set of steps from the following list:\n // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1\n // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2\n\n if (!isEstablished(this) || isClosing(this)) {\n return\n }\n\n /** @type {import('stream').Duplex} */\n const socket = this[kResponse].socket\n\n // If data is a string\n if (typeof data === 'string') {\n // If the WebSocket connection is established and the WebSocket\n // closing handshake has not yet started, then the user agent\n // must send a WebSocket Message comprised of the data argument\n // using a text frame opcode; if the data cannot be sent, e.g.\n // because it would need to be buffered but the buffer is full,\n // the user agent must flag the WebSocket as full and then close\n // the WebSocket connection. Any invocation of this method with a\n // string argument that does not throw an exception must increase\n // the bufferedAmount attribute by the number of bytes needed to\n // express the argument as UTF-8.\n\n const value = Buffer.from(data)\n const frame = new WebsocketFrameSend(value)\n const buffer = frame.createFrame(opcodes.TEXT)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n } else if (types.isArrayBuffer(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need\n // to be buffered but the buffer is full, the user agent must flag\n // the WebSocket as full and then close the WebSocket connection.\n // The data to be sent is the data stored in the buffer described\n // by the ArrayBuffer object. Any invocation of this method with an\n // ArrayBuffer argument that does not throw an exception must\n // increase the bufferedAmount attribute by the length of the\n // ArrayBuffer in bytes.\n\n const value = Buffer.from(data)\n const frame = new WebsocketFrameSend(value)\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n } else if (ArrayBuffer.isView(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need to\n // be buffered but the buffer is full, the user agent must flag the\n // WebSocket as full and then close the WebSocket connection. The\n // data to be sent is the data stored in the section of the buffer\n // described by the ArrayBuffer object that data references. Any\n // invocation of this method with this kind of argument that does\n // not throw an exception must increase the bufferedAmount attribute\n // by the length of data’s buffer in bytes.\n\n const ab = Buffer.from(data, data.byteOffset, data.byteLength)\n\n const frame = new WebsocketFrameSend(ab)\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += ab.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= ab.byteLength\n })\n } else if (isBlobLike(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need to\n // be buffered but the buffer is full, the user agent must flag the\n // WebSocket as full and then close the WebSocket connection. The data\n // to be sent is the raw data represented by the Blob object. Any\n // invocation of this method with a Blob argument that does not throw\n // an exception must increase the bufferedAmount attribute by the size\n // of the Blob object’s raw data, in bytes.\n\n const frame = new WebsocketFrameSend()\n\n data.arrayBuffer().then((ab) => {\n const value = Buffer.from(ab)\n frame.frameData = value\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n })\n }\n }\n\n get readyState () {\n webidl.brandCheck(this, WebSocket)\n\n // The readyState getter steps are to return this's ready state.\n return this[kReadyState]\n }\n\n get bufferedAmount () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#bufferedAmount\n }\n\n get url () {\n webidl.brandCheck(this, WebSocket)\n\n // The url getter steps are to return this's url, serialized.\n return URLSerializer(this[kWebSocketURL])\n }\n\n get extensions () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#extensions\n }\n\n get protocol () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#protocol\n }\n\n get onopen () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.open\n }\n\n set onopen (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.open) {\n this.removeEventListener('open', this.#events.open)\n }\n\n if (typeof fn === 'function') {\n this.#events.open = fn\n this.addEventListener('open', fn)\n } else {\n this.#events.open = null\n }\n }\n\n get onerror () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.error\n }\n\n set onerror (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.error) {\n this.removeEventListener('error', this.#events.error)\n }\n\n if (typeof fn === 'function') {\n this.#events.error = fn\n this.addEventListener('error', fn)\n } else {\n this.#events.error = null\n }\n }\n\n get onclose () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.close\n }\n\n set onclose (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.close) {\n this.removeEventListener('close', this.#events.close)\n }\n\n if (typeof fn === 'function') {\n this.#events.close = fn\n this.addEventListener('close', fn)\n } else {\n this.#events.close = null\n }\n }\n\n get onmessage () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.message\n }\n\n set onmessage (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.message) {\n this.removeEventListener('message', this.#events.message)\n }\n\n if (typeof fn === 'function') {\n this.#events.message = fn\n this.addEventListener('message', fn)\n } else {\n this.#events.message = null\n }\n }\n\n get binaryType () {\n webidl.brandCheck(this, WebSocket)\n\n return this[kBinaryType]\n }\n\n set binaryType (type) {\n webidl.brandCheck(this, WebSocket)\n\n if (type !== 'blob' && type !== 'arraybuffer') {\n this[kBinaryType] = 'blob'\n } else {\n this[kBinaryType] = type\n }\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n */\n #onConnectionEstablished (response) {\n // processResponse is called when the \"response’s header list has been received and initialized.\"\n // once this happens, the connection is open\n this[kResponse] = response\n\n const parser = new ByteParser(this)\n parser.on('drain', function onParserDrain () {\n this.ws[kResponse].socket.resume()\n })\n\n response.socket.ws = this\n this[kByteParser] = parser\n\n // 1. Change the ready state to OPEN (1).\n this[kReadyState] = states.OPEN\n\n // 2. Change the extensions attribute’s value to the extensions in use, if\n // it is not the null value.\n // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1\n const extensions = response.headersList.get('sec-websocket-extensions')\n\n if (extensions !== null) {\n this.#extensions = extensions\n }\n\n // 3. Change the protocol attribute’s value to the subprotocol in use, if\n // it is not the null value.\n // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9\n const protocol = response.headersList.get('sec-websocket-protocol')\n\n if (protocol !== null) {\n this.#protocol = protocol\n }\n\n // 4. Fire an event named open at the WebSocket object.\n fireEvent('open', this)\n }\n}\n\n// https://websockets.spec.whatwg.org/#dom-websocket-connecting\nWebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING\n// https://websockets.spec.whatwg.org/#dom-websocket-open\nWebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN\n// https://websockets.spec.whatwg.org/#dom-websocket-closing\nWebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING\n// https://websockets.spec.whatwg.org/#dom-websocket-closed\nWebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED\n\nObject.defineProperties(WebSocket.prototype, {\n CONNECTING: staticPropertyDescriptors,\n OPEN: staticPropertyDescriptors,\n CLOSING: staticPropertyDescriptors,\n CLOSED: staticPropertyDescriptors,\n url: kEnumerableProperty,\n readyState: kEnumerableProperty,\n bufferedAmount: kEnumerableProperty,\n onopen: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onclose: kEnumerableProperty,\n close: kEnumerableProperty,\n onmessage: kEnumerableProperty,\n binaryType: kEnumerableProperty,\n send: kEnumerableProperty,\n extensions: kEnumerableProperty,\n protocol: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'WebSocket',\n writable: false,\n enumerable: false,\n configurable: true\n }\n})\n\nObject.defineProperties(WebSocket, {\n CONNECTING: staticPropertyDescriptors,\n OPEN: staticPropertyDescriptors,\n CLOSING: staticPropertyDescriptors,\n CLOSED: staticPropertyDescriptors\n})\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.DOMString\n)\n\nwebidl.converters['DOMString or sequence'] = function (V) {\n if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {\n return webidl.converters['sequence'](V)\n }\n\n return webidl.converters.DOMString(V)\n}\n\n// This implements the propsal made in https://github.com/whatwg/websockets/issues/42\nwebidl.converters.WebSocketInit = webidl.dictionaryConverter([\n {\n key: 'protocols',\n converter: webidl.converters['DOMString or sequence'],\n get defaultValue () {\n return []\n }\n },\n {\n key: 'dispatcher',\n converter: (V) => V,\n get defaultValue () {\n return getGlobalDispatcher()\n }\n },\n {\n key: 'headers',\n converter: webidl.nullableConverter(webidl.converters.HeadersInit)\n }\n])\n\nwebidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {\n if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {\n return webidl.converters.WebSocketInit(V)\n }\n\n return { protocols: webidl.converters['DOMString or sequence'](V) }\n}\n\nwebidl.converters.WebSocketSendData = function (V) {\n if (webidl.util.Type(V) === 'Object') {\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {\n return webidl.converters.BufferSource(V)\n }\n }\n\n return webidl.converters.USVString(V)\n}\n\nmodule.exports = {\n WebSocket\n}\n","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\n\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\n\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\n\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\n\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\n\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\n\nvar _version = _interopRequireDefault(require(\"./version.js\"));\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction md5(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return _crypto.default.createHash('md5').update(bytes).digest();\n}\n\nvar _default = md5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = '00000000-0000-0000-0000-000000000000';\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nvar _default = parse;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\n\nfunction rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n _crypto.default.randomFillSync(rnds8Pool);\n\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return _crypto.default.createHash('sha1').update(bytes).digest();\n}\n\nvar _default = sha1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nvar _default = stringify;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\nlet _nodeId;\n\nlet _clockseq; // Previous uuid creation time\n\n\nlet _lastMSecs = 0;\nlet _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node || _nodeId;\n let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || (0, _stringify.default)(b);\n}\n\nvar _default = v1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = v3;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = _default;\nexports.URL = exports.DNS = void 0;\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nconst DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexports.DNS = DNS;\nconst URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexports.URL = URL;\n\nfunction _default(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.default)(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction v4(options, buf, offset) {\n options = options || {};\n\n const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.default)(rnds);\n}\n\nvar _default = v4;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = v5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\n\nvar _default = validate;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nvar _default = version;\nexports.default = _default;","// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.cleanupOldImageVersions = exports.run = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst dockerode_1 = __importDefault(require(\"dockerode\"));\nconst docker_tags_1 = require(\"./docker-tags\");\n// This method performs housekeeping checks to remove Docker artifacts\n// which were left behind by old versions of the action or any jobs\n// which may have crashed before deleting their own containers or networks\n//\n// cutoff - a Go duration string to pass to the Docker API's 'until' argument, default '24h'\nfunction run() {\n return __awaiter(this, arguments, void 0, function* (cutoff = '24h') {\n if (process.env.DEPENDABOT_DISABLE_CLEANUP === '1') {\n return;\n }\n try {\n const docker = new dockerode_1.default();\n const untilFilter = { until: [cutoff] };\n core.info(`Pruning networks older than ${cutoff}`);\n yield docker.pruneNetworks({ filters: untilFilter });\n core.info(`Pruning containers older than ${cutoff}`);\n yield docker.pruneContainers({ filters: untilFilter });\n yield Promise.all((0, docker_tags_1.updaterImages)().map((image) => __awaiter(this, void 0, void 0, function* () {\n return cleanupOldImageVersions(docker, image);\n })));\n yield cleanupOldImageVersions(docker, docker_tags_1.PROXY_IMAGE_NAME);\n }\n catch (error) {\n if (error instanceof Error) {\n core.error(`Error cleaning up: ${error.message}`);\n }\n }\n });\n}\nexports.run = run;\nfunction cleanupOldImageVersions(docker, imageName) {\n return __awaiter(this, void 0, void 0, function* () {\n const repo = (0, docker_tags_1.repositoryName)(imageName);\n const options = {\n filters: `{\"reference\":[\"${repo}\"]}`\n };\n core.info(`Cleaning up images for ${repo}`);\n docker.listImages(options, function (err, imageInfoList) {\n return __awaiter(this, void 0, void 0, function* () {\n if (imageInfoList && imageInfoList.length > 0) {\n for (const imageInfo of imageInfoList) {\n // The given imageName is expected to be a tag + digest, however to avoid any surprises in future\n // we fail over to check for a match on just tags as well.\n //\n // This means we won't remove any image which matches an imageName of either of these notations:\n // - dependabot/image:$TAG@sha256:$REF (current implementation)\n // - dependabot/image:v1\n //\n // Without checking imageInfo.RepoTags for a match, we would actually remove the latter even if\n // this was the active version.\n if (imageMatches(imageInfo, imageName)) {\n core.info(`Skipping current image ${imageInfo.Id}`);\n continue;\n }\n core.info(`Removing image ${imageInfo.Id}`);\n try {\n yield docker.getImage(imageInfo.Id).remove();\n }\n catch (error) {\n if (error instanceof Error) {\n core.info(`Unable to remove ${imageInfo.Id} -- ${error.message}`);\n }\n }\n }\n }\n });\n });\n });\n}\nexports.cleanupOldImageVersions = cleanupOldImageVersions;\nfunction imageMatches(imageInfo, imageName) {\n if ((0, docker_tags_1.hasDigest)(imageName)) {\n return imageInfo.RepoDigests\n ? imageInfo.RepoDigests.includes((0, docker_tags_1.digestName)(imageName))\n : false;\n }\n return imageInfo.RepoTags ? imageInfo.RepoTags.includes(imageName) : false;\n}\nrun();\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.digestName = exports.hasDigest = exports.repositoryName = exports.updaterImages = exports.updaterImageName = exports.PROXY_IMAGE_NAME = void 0;\n// eslint-disable-next-line import/extensions\nconst containers_json_1 = __importDefault(require(\"../docker/containers.json\"));\nexports.PROXY_IMAGE_NAME = containers_json_1.default.proxy;\nfunction updaterImageName(packageManager) {\n return containers_json_1.default[packageManager];\n}\nexports.updaterImageName = updaterImageName;\nconst updaterRegex = /ghcr.io\\/dependabot\\/dependabot-updater-([\\w+])/;\nfunction updaterImages() {\n return Object.values(containers_json_1.default).filter(image => image.match(updaterRegex));\n}\nexports.updaterImages = updaterImages;\nconst imageNamePattern = '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))(:[a-zA-Z0-9._/-]+)?(?@sha256:[a-zA-Z0-9]{64})?$';\nfunction repositoryName(imageName) {\n const match = imageName.match(imageNamePattern);\n if (match === null || match === void 0 ? void 0 : match.groups) {\n return match.groups['repository'];\n }\n else {\n throw Error('invalid image name');\n }\n}\nexports.repositoryName = repositoryName;\nfunction hasDigest(imageName) {\n const match = imageName.match(imageNamePattern);\n if (match === null || match === void 0 ? void 0 : match.groups) {\n if (match === null || match === void 0 ? void 0 : match.groups['digest']) {\n return true;\n }\n return false;\n }\n else {\n throw Error('invalid image name');\n }\n}\nexports.hasDigest = hasDigest;\nfunction digestName(imageName) {\n const match = imageName.match(imageNamePattern);\n if (match === null || match === void 0 ? void 0 : match.groups) {\n return match.groups['repository'] + match.groups['digest'];\n }\n else {\n throw Error('invalid image name');\n }\n}\nexports.digestName = digestName;\n","module.exports = __non_webpack_require__(__webpack_require__.ab + \"build/Release/cpufeatures.node\")","module.exports = __non_webpack_require__(__webpack_require__.ab + \"lib/protocol/crypto/build/Release/sshcrypto.node\")","module.exports = require(\"assert\");","module.exports = require(\"async_hooks\");","module.exports = require(\"buffer\");","module.exports = require(\"child_process\");","module.exports = require(\"console\");","module.exports = require(\"constants\");","module.exports = require(\"crypto\");","module.exports = require(\"diagnostics_channel\");","module.exports = require(\"dns\");","module.exports = require(\"events\");","module.exports = require(\"fs\");","module.exports = require(\"http\");","module.exports = require(\"http2\");","module.exports = require(\"https\");","module.exports = require(\"net\");","module.exports = require(\"node:events\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","module.exports = require(\"os\");","module.exports = require(\"path\");","module.exports = require(\"perf_hooks\");","module.exports = require(\"querystring\");","module.exports = require(\"stream\");","module.exports = require(\"stream/web\");","module.exports = require(\"string_decoder\");","module.exports = require(\"tls\");","module.exports = require(\"tty\");","module.exports = require(\"url\");","module.exports = require(\"util\");","module.exports = require(\"util/types\");","module.exports = require(\"worker_threads\");","module.exports = require(\"zlib\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\tvar threw = true;\n\ttry {\n\t\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\t\tthrew = false;\n\t} finally {\n\t\tif(threw) delete __webpack_module_cache__[moduleId];\n\t}\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","\nif (typeof __webpack_require__ !== 'undefined') __webpack_require__.ab = __dirname + \"/\";","","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(3812);\n",""],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/dist/cleanup/licenses.txt b/dist/cleanup/licenses.txt index d1f2cc882..813ea4319 100644 --- a/dist/cleanup/licenses.txt +++ b/dist/cleanup/licenses.txt @@ -35,6 +35,238 @@ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +@balena/dockerignore +Apache-2.0 + +* Copyright 2020 Balena Ltd. under the Apache 2.0 License included in this file. +* Copyright 2018 Zeit Inc. under the MIT License included in this file. + +-------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +-------------------------------------------------------------------------- + +The MIT License (MIT) + +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. + +-------------------------------------------------------------------------- + + +@fastify/busboy +MIT +Copyright Brian White. All rights reserved. + +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. + asn1 MIT Copyright (c) 2011 Mark Cavage, All rights reserved. @@ -190,21 +422,22 @@ debug MIT (The MIT License) -Copyright (c) 2014 TJ Holowaychuk +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon -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, +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 +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 +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. @@ -1086,6 +1319,31 @@ OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to +undici +MIT +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +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. + + util-deprecate MIT (The MIT License) diff --git a/dist/main/index.js b/dist/main/index.js index fa9b83ea8..2fb67fd28 100644 --- a/dist/main/index.js +++ b/dist/main/index.js @@ -140,7 +140,6 @@ const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); const os = __importStar(__nccwpck_require__(2037)); const path = __importStar(__nccwpck_require__(1017)); -const uuid_1 = __nccwpck_require__(5840); const oidc_utils_1 = __nccwpck_require__(8041); /** * The code to exit an action @@ -170,20 +169,9 @@ function exportVariable(name, val) { process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - // These should realistically never happen, but just in case someone finds a way to exploit uuid generation let's not allow keys or values that contain the delimiter. - if (name.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedVal.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); + return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); } + command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -201,7 +189,7 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueCommand('PATH', inputPath); + file_command_1.issueFileCommand('PATH', inputPath); } else { command_1.issueCommand('add-path', {}, inputPath); @@ -241,7 +229,10 @@ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); - return inputs; + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** @@ -274,8 +265,12 @@ exports.getBooleanInput = getBooleanInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); + command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); } exports.setOutput = setOutput; /** @@ -404,7 +399,11 @@ exports.group = group; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); + } + command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); } exports.saveState = saveState; /** @@ -470,13 +469,14 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = void 0; +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__nccwpck_require__(7147)); const os = __importStar(__nccwpck_require__(2037)); +const uuid_1 = __nccwpck_require__(5840); const utils_1 = __nccwpck_require__(5278); -function issueCommand(command, message) { +function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); @@ -488,7 +488,22 @@ function issueCommand(command, message) { encoding: 'utf8' }); } -exports.issueCommand = issueCommand; +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + const convertedValue = utils_1.toCommandValue(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map /***/ }), @@ -509,8 +524,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(1404); -const auth_1 = __nccwpck_require__(6758); +const http_client_1 = __nccwpck_require__(6255); +const auth_1 = __nccwpck_require__(5526); const core_1 = __nccwpck_require__(2186); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { @@ -543,7 +558,7 @@ class OidcClient { .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); + Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { @@ -979,7 +994,260 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 6758: +/***/ 4087: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const fs_1 = __nccwpck_require__(7147); +const os_1 = __nccwpck_require__(2037); +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = + (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +} +exports.Context = Context; +//# sourceMappingURL=context.js.map + +/***/ }), + +/***/ 5438: +/***/ (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 __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(4087)); +const utils_1 = __nccwpck_require__(3030); +exports.context = new Context.Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); +} +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map + +/***/ }), + +/***/ 7914: +/***/ (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 __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; +const httpClient = __importStar(__nccwpck_require__(6255)); +const undici_1 = __nccwpck_require__(1773); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; +} +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); +} +exports.getProxyAgent = getProxyAgent; +function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); +} +exports.getProxyAgentDispatcher = getProxyAgentDispatcher; +function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; +} +exports.getProxyFetch = getProxyFetch; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 3030: +/***/ (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 __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(4087)); +const Utils = __importStar(__nccwpck_require__(7914)); +// octokit + plugins +const core_1 = __nccwpck_require__(6762); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(3044); +const plugin_paginate_rest_1 = __nccwpck_require__(4193); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +exports.defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl), + fetch: Utils.getProxyFetch(baseUrl) + } +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + return opts; +} +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 5526: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -1067,7 +1335,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 1404: +/***/ 6255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1075,7 +1343,11 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + 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]; @@ -1088,7 +1360,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + 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; }; @@ -1105,8 +1377,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(3685)); const https = __importStar(__nccwpck_require__(5687)); -const pm = __importStar(__nccwpck_require__(2843)); +const pm = __importStar(__nccwpck_require__(9835)); const tunnel = __importStar(__nccwpck_require__(4294)); +const undici_1 = __nccwpck_require__(1773); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -1136,16 +1409,16 @@ var HttpCodes; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); +})(Headers || (exports.Headers = Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com @@ -1196,6 +1469,19 @@ class HttpClientResponse { })); }); } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { @@ -1501,6 +1787,15 @@ class HttpClient { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; @@ -1548,7 +1843,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -1580,16 +1875,12 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { + // if tunneling agent isn't assigned create a new agent + if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options @@ -1600,6 +1891,30 @@ class HttpClient { } return agent; } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `${proxyUrl.username}:${proxyUrl.password}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); @@ -1679,7 +1994,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 2843: +/***/ 9835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1700,7 +2015,13 @@ function getProxyUrl(reqUrl) { } })(); if (proxyVar) { - return new URL(proxyVar); + try { + return new URL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new URL(`http://${proxyVar}`); + } } else { return undefined; @@ -1711,6 +2032,10 @@ function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; @@ -1736,1280 +2061,2286 @@ function checkBypass(reqUrl) { .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} //# sourceMappingURL=proxy.js.map /***/ }), -/***/ 4087: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3358: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const fs_1 = __nccwpck_require__(7147); -const os_1 = __nccwpck_require__(2037); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); - } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); - } - } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; +/** + * @license + * Copyright 2020 Balena Ltd. + * + * 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. + * + * ------------------------------------------------------------------------ + * + * Copyright 2018 Zeit, Inc. + * Licensed under the MIT License. See file LICENSE.md for a full copy. + * + * ------------------------------------------------------------------------ + */ + +/** + * This module implements the [dockerignore + * spec](https://docs.docker.com/engine/reference/builder/#dockerignore-file), + * closely following Docker's (Moby) Golang implementation: + * https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go + * https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go + * https://github.com/moby/moby/blob/v19.03.8/pkg/archive/archive.go#L825 + * + * Something the spec is not clear about, but we discovered by reading source code + * and testing against the "docker build" command, is the handling of backslashes and + * forward slashes as path separators and escape characters in the .dockerignore file + * across platforms including Windows, Linux and macOS: + * + * * On Linux and macOS, only forward slashes can be used as path separators in the + * .dockerignore file, and the backslash works as an escape character. + * * On Windows, both forward slashes and backslashes are allowed as path separators + * in the .dockerignore file, and the backslash is not used as an escape character. + * + * This is consistent with how Windows works generally: both forward slashes and + * backslashes are accepted as path separators by the cmd.exe Command Prompt or + * PowerShell, and by library functions like the Golang filepath.Clean or the + * Node.js path.normalize. + * + * Similarly, path strings provided to the IgnoreBase.ignores() and IgnoreBase.filter() + * methods can use either forward slashes or backslashes as path separators on Windows, + * but only forward slashes are accepted as path separators on Linux and macOS. + */ + +const path = __nccwpck_require__(1017); + +const factory = options => new IgnoreBase(options); // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L538-L539 +// Fixes typescript module import + + +factory.default = factory; +module.exports = factory; + +function make_array(subject) { + return Array.isArray(subject) ? subject : [subject]; +} + +const REGEX_TRAILING_SLASH = /(?<=.)\/$/; +const REGEX_TRAILING_BACKSLASH = /(?<=.)\\$/; +const REGEX_TRAILING_PATH_SEP = path.sep === '\\' ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH; +const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('dockerignore') : 'dockerignore'; // An implementation of Go's filepath.Clean +// https://golang.org/pkg/path/filepath/#Clean +// https://github.com/golang/go/blob/master/src/path/filepath/path.go +// Note that, like Go, on Windows this function converts forward slashes +// to backslashes. + +function cleanPath(file) { + return path.normalize(file).replace(REGEX_TRAILING_PATH_SEP, ''); +} // Javascript port of Golang's filepath.ToSlash +// https://golang.org/pkg/path/filepath/#ToSlash +// https://github.com/golang/go/blob/master/src/path/filepath/path.go +// Convert any OS-specific path separator to '/'. Backslash is converted +// to forward slash on Windows, but not on Linux/macOS. +// Note that both forward slashes and backslashes are valid path separators on +// Windows. As a result, code such as `pattern.split(path.sep).join('/')` fails +// on Windows when forward slashes are used as path separators. + + +function toSlash(file) { + if (path.sep === '/') { + return file; + } + + return file.replace(/\\/g, '/'); +} // Javascript port of Golang's filepath.FromSlash +// https://github.com/golang/go/blob/master/src/path/filepath/path.go + + +function fromSlash(file) { + if (path.sep === '/') { + return file; + } + + return file.replace(/\//g, path.sep); +} + +class IgnoreBase { + constructor({ + // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L372 + ignorecase = true + } = {}) { + this._rules = []; + this._ignorecase = ignorecase; + this[KEY_IGNORE] = true; + + this._initCache(); + } + + _initCache() { + this._cache = {}; + } // @param {Array.|string|Ignore} pattern + + + add(pattern) { + this._added = false; + + if (typeof pattern === 'string') { + pattern = pattern.split(/\r?\n/g); } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + + make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore, + // making the behavior changed. + + if (this._added) { + this._initCache(); } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; + + return this; + } // legacy + + + addPattern(pattern) { + return this.add(pattern); + } + + _addPattern(pattern) { + // https://github.com/kaelzhang/node-ignore/issues/32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + + if (this._checkPattern(pattern)) { + const rule = this._createRule(pattern.trim()); + + if (rule !== null) { + this._added = true; + + this._rules.push(rule); + } + } + } + + _checkPattern(pattern) { + // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L34-L40 + return pattern && typeof pattern === 'string' && pattern.indexOf('#') !== 0 && pattern.trim() !== ""; + } + + filter(paths) { + return make_array(paths).filter(path => this._filter(path)); + } + + createFilter() { + return path => this._filter(path); + } + + ignores(path) { + return !this._filter(path); + } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L41-L53 + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L29-L55 + + + _createRule(pattern) { + const origin = pattern; + let negative = false; // > An optional prefix "!" which negates the pattern; + // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L43-L46 + + if (pattern[0] === '!') { + negative = true; + pattern = pattern.substring(1).trim(); + } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L47-L53 + + + if (pattern.length > 0) { + pattern = cleanPath(pattern); + pattern = toSlash(pattern); + + if (pattern.length > 1 && pattern[0] === '/') { + pattern = pattern.slice(1); + } + } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L54-L55 + + + if (negative) { + pattern = '!' + pattern; + } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L30 + + + pattern = pattern.trim(); + + if (pattern === "") { + return null; + } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L34 + // convert forward slashes to backslashes on Windows + + + pattern = cleanPath(pattern); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L36-L42 + + if (pattern[0] === '!') { + if (pattern.length === 1) { + return null; + } + + negative = true; + pattern = pattern.substring(1); + } else { + negative = false; + } + + return { + origin, + pattern, + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L54 + dirs: pattern.split(path.sep), + negative + }; + } // @returns `Boolean` true if the `path` is NOT ignored + + + _filter(path) { + if (!path) { + return false; + } + + if (path in this._cache) { + return this._cache[path]; + } + + return this._cache[path] = this._test(path); + } // @returns {Boolean} true if a file is NOT ignored + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L62 + + + _test(file) { + file = fromSlash(file); // equivalent to golang filepath.Dir() https://golang.org/src/path/filepath/path.go + + const parentPath = cleanPath(path.dirname(file)); + const parentPathDirs = parentPath.split(path.sep); + let matched = false; + + this._rules.forEach(rule => { + let match = this._match(file, rule); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L80 + + + if (!match && parentPath !== ".") { + // Check to see if the pattern matches one of our parent dirs. + if (rule.dirs.includes('**')) { + // Ah shucks! We have to test every possible parent path that has + // a number of dirs _n_ where + // `rule.dirs.filter(doubleStar).length <= _n_ <= parentPathDirs.length` + // since the ** can imply any number of directories including 0 + for (let i = rule.dirs.filter(x => x !== '**').length; i <= parentPathDirs.length; i++) { + match = match || this._match(parentPathDirs.slice(0, i).join(path.sep), rule); + } + } else if (rule.dirs.length <= parentPathDirs.length) { + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L83 + match = this._match(parentPathDirs.slice(0, rule.dirs.length).join(path.sep), rule); } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; + } + + if (match) { + matched = !rule.negative; + } + }); + + return !matched; + } // @returns {Boolean} true if a file is matched by a rule + + + _match(file, rule) { + return this._compile(rule).regexp.test(file); + } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L139 + + + _compile(rule) { + if (rule.regexp) { + return rule; + } + + let regStr = '^'; // Go through the pattern and convert it to a regexp. + + let escapedSlash = path.sep === '\\' ? '\\\\' : path.sep; + + for (let i = 0; i < rule.pattern.length; i++) { + const ch = rule.pattern[i]; + + if (ch === '*') { + if (rule.pattern[i + 1] === '*') { + // is some flavor of "**" + i++; // Treat **/ as ** so eat the "/" + + if (rule.pattern[i + 1] === path.sep) { + i++; + } + + if (rule.pattern[i + 1] === undefined) { + // is "**EOF" - to align with .gitignore just accept all + regStr += ".*"; + } else { + // is "**" + // Note that this allows for any # of /'s (even 0) because + // the .* will eat everything, even /'s + regStr += `(.*${escapedSlash})?`; + } + } else { + // is "*" so map it to anything but "/" + regStr += `[^${escapedSlash}]*`; } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } else if (ch === '?') { + // "?" is any char except "/" + regStr += `[^${escapedSlash}]`; + } else if (ch === '.' || ch === '$') { + // Escape some regexp special chars that have no meaning + // in golang's filepath.Match + regStr += `\\${ch}`; + } else if (ch === '\\') { + // escape next char. Note that a trailing \ in the pattern + // will be left alone (but need to escape it) + if (path.sep === '\\') { + // On windows map "\" to "\\", meaning an escaped backslash, + // and then just continue because filepath.Match on + // Windows doesn't allow escaping at all + regStr += escapedSlash; + continue; + } + + if (rule.pattern[i + 1] !== undefined) { + regStr += '\\' + rule.pattern[i + 1]; + i++; + } else { + regStr += '\\'; + } + } else { + regStr += ch; + } } + + regStr += "$"; + rule.regexp = new RegExp(regStr, this._ignorecase ? 'i' : ''); + return rule; + } + } -exports.Context = Context; -//# sourceMappingURL=context.js.map + /***/ }), -/***/ 5438: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 2856: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(4087)); -const utils_1 = __nccwpck_require__(3030); -exports.context = new Context.Context(); -/** - * Returns a hydrated octokit ready to use for GitHub Actions - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokit(token, options) { - return new utils_1.GitHub(utils_1.getOctokitOptions(token, options)); -} -exports.getOctokit = getOctokit; -//# sourceMappingURL=github.js.map -/***/ }), +const WritableStream = (__nccwpck_require__(4492).Writable) +const inherits = (__nccwpck_require__(7261).inherits) -/***/ 7914: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +const StreamSearch = __nccwpck_require__(8534) -"use strict"; +const PartStream = __nccwpck_require__(8710) +const HeaderParser = __nccwpck_require__(333) -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(9925)); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + 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 + + 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) + +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 if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); + } else { WritableStream.prototype.emit.apply(this, arguments) } +} + +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 (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() } } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + + this._bparser.push(data) + + if (this._pause) { this._cb = cb } else { cb() } } -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); + +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined } -exports.getProxyAgent = getProxyAgent; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; + +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) + }) } -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map + +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() + } +} + +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true + + 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 + } + } + 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 } + } + 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 (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) } + } + } + 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() + } + } + }) + } + } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } +} + +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} + +module.exports = Dicer + /***/ }), -/***/ 3030: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 333: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokitOptions = exports.GitHub = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(4087)); -const Utils = __importStar(__nccwpck_require__(7914)); -// octokit + plugins -const core_1 = __nccwpck_require__(6762); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(3044); -const plugin_paginate_rest_1 = __nccwpck_require__(4193); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -const defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl) + +const EventEmitter = (__nccwpck_require__(5673).EventEmitter) +const inherits = (__nccwpck_require__(7261).inherits) +const getLimit = __nccwpck_require__(9692) + +const StreamSearch = __nccwpck_require__(8534) + +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 HeaderParser (cfg) { + EventEmitter.call(this) + + 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) } + + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) + +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} + +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} + +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) +} + +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h + + 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 + } } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults); -/** - * Convience function to correctly format Octokit Options to pass into the constructor. - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; + + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return } - return opts; + 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 } + } } -exports.getOctokitOptions = getOctokitOptions; -//# sourceMappingURL=utils.js.map + +module.exports = HeaderParser + /***/ }), -/***/ 9925: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 8710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const http = __nccwpck_require__(3685); -const https = __nccwpck_require__(5687); -const pm = __nccwpck_require__(6443); -let tunnel; -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); + +const inherits = (__nccwpck_require__(7261).inherits) +const ReadableStream = (__nccwpck_require__(4492).Readable) + +function PartStream (opts) { + ReadableStream.call(this, opts) +} +inherits(PartStream, ReadableStream) + +PartStream.prototype._read = function (n) {} + +module.exports = PartStream + + +/***/ }), + +/***/ 8534: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + /** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + * 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 */ -function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; +const EventEmitter = (__nccwpck_require__(5673).EventEmitter) +const inherits = (__nccwpck_require__(7261).inherits) + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity + this.matches = 0 + + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + + this._lookbehind = Buffer.alloc(needleLength) + + // 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 + } } -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } +inherits(SBMH, EventEmitter) + +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 } -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - }); - } + +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 } -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - let parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - } - get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - } - del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - } - post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - } - patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - } - put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - } - head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(verb, requestUrl, stream, additionalHeaders); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol == 'https:' && - parsedUrl.protocol != parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); - } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - let socket; - if (typeof data === 'string') { - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - let handleResult = (err, res) => { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, res); - }); - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error('Request timeout: ' + info.options.path), null); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err, null); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - this.handlers.forEach(handler => { - handler.prepareRequest(info.options); - }); - } - return info; - } - _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (!!agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (!!this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __nccwpck_require__(4294); - } - const agentOptions = { - maxSockets: maxSockets, - keepAlive: this._keepAlive, - proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), - host: proxyUrl.hostname, - port: proxyUrl.port - } - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = 'Failed request: (' + statusCode + ')'; - } - let err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - }); - } -} -exports.HttpClient = HttpClient; +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] -/***/ }), + // 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 -/***/ 6443: -/***/ ((__unused_webpack_module, exports) => { + 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) -"use strict"; + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) -Object.defineProperty(exports, "__esModule", ({ value: true })); -function getProxyUrl(reqUrl) { - let usingSsl = reqUrl.protocol === 'https:'; - let proxyUrl; - if (checkBypass(reqUrl)) { - return proxyUrl; - } - let proxyVar; - if (usingSsl) { - proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - if (proxyVar) { - proxyUrl = new URL(proxyVar); - } - return proxyUrl; -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - let upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (let upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { - return true; - } + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] } - return false; -} -exports.checkBypass = checkBypass; + // No match. -/***/ }), + 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 } + } -/***/ 334: -/***/ ((__unused_webpack_module, exports) => { + 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) + } -"use strict"; + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len -Object.defineProperty(exports, "__esModule", ({ value: true })); + this._bufpos = len + return len + } + } -async function auth(token) { - const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; - return { - type: "token", - token: token, - tokenType - }; -} + pos += (pos >= 0) * this._bufpos -/** - * Prefix token for usage in the Authorization header - * - * @param token OAuth token or JSON Web Token - */ -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; + // 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) } + + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + + // 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 + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos } - return `token ${token}`; -} + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); + this._bufpos = len + return len } -const createTokenAuth = function createTokenAuth(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} - if (typeof token !== "string") { - throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); +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 } } + return true +} - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; - -exports.createTokenAuth = createTokenAuth; -//# sourceMappingURL=index.js.map +module.exports = SBMH /***/ }), -/***/ 6762: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3438: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +const WritableStream = (__nccwpck_require__(4492).Writable) +const { inherits } = __nccwpck_require__(7261) +const Dicer = __nccwpck_require__(2856) -var universalUserAgent = __nccwpck_require__(5030); -var beforeAfterHook = __nccwpck_require__(3682); -var request = __nccwpck_require__(6234); -var graphql = __nccwpck_require__(8467); -var authToken = __nccwpck_require__(334); +const MultipartParser = __nccwpck_require__(415) +const UrlencodedParser = __nccwpck_require__(6780) +const parseParams = __nccwpck_require__(4426) -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') } - return target; -} + const { + headers, + ...streamOptions + } = opts -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) - var target = _objectWithoutPropertiesLoose(source, excluded); + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) - var key, i; +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) +} - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } + 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 } - return target; + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') } -const VERSION = "3.4.0"; +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} -class Octokit { - constructor(options = {}) { - const hook = new beforeAfterHook.Collection(); - const requestDefaults = { - baseUrl: 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: "" - } - }; // prepend default user agent with `options.userAgent` if set +module.exports = Busboy +module.exports["default"] = Busboy +module.exports.Busboy = Busboy - requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); +module.exports.Dicer = Dicer - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } +/***/ }), - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } +/***/ 415: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.request = request.request.defaults(requestDefaults); - this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults); - this.log = Object.assign({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); - this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance - // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered. - // (2) If only `options.auth` is set, use the default token authentication strategy. - // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. - // TODO: type `options.auth` based on `options.authStrategy`. +"use strict"; - if (!options.authStrategy) { - if (!options.auth) { - // (1) - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - // (2) - const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ - hook.wrap("request", auth.hook); - this.auth = auth; +// 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 + +const { Readable } = __nccwpck_require__(4492) +const { inherits } = __nccwpck_require__(7261) + +const Dicer = __nccwpck_require__(2856) + +const parseParams = __nccwpck_require__(4426) +const decodeText = __nccwpck_require__(9136) +const basename = __nccwpck_require__(496) +const getLimit = __nccwpck_require__(9692) + +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 + +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 } + + 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 + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + 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) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + 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) + } + + // 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') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + 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 + } + } + } } - } else { - const { - authStrategy - } = options, - otherOptions = _objectWithoutProperties(options, ["authStrategy"]); - - 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)); // @ts-ignore ¯\_(ツ)_/¯ - hook.wrap("request", auth.hook); - this.auth = auth; - } // apply plugins - // https://stackoverflow.com/a/16345172 + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + 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) } - const classConstructor = this.constructor; - classConstructor.plugins.forEach(plugin => { - Object.assign(this, plugin(this, options)); - }); - } + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; + let onData, + onEnd - if (typeof defaults === "function") { - super(defaults(options)); - return; + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } + + ++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) + + 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 } + + file.bytesRead = nsize + } + + 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) } - super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null)); + ++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() + } } - }; - return OctokitWithDefaults; - } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ + /* 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 + + 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 + } +} - static plugin(...newPlugins) { - var _a; +Multipart.prototype.end = function () { + const self = this - const currentPlugins = this.plugins; - const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); - return NewOctokit; + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) } +} +function skipPart (part) { + part.resume() } -Octokit.VERSION = VERSION; -Octokit.plugins = []; -exports.Octokit = Octokit; -//# sourceMappingURL=index.js.map +function FileStream (opts) { + Readable.call(this, opts) + + this.bytesRead = 0 + + this.truncated = false +} + +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart /***/ }), -/***/ 9440: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 6780: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +const Decoder = __nccwpck_require__(9730) +const decodeText = __nccwpck_require__(9136) +const getLimit = __nccwpck_require__(9692) -var isPlainObject = __nccwpck_require__(3287); -var universalUserAgent = __nccwpck_require__(5030); +const RE_CHARSET = /^charset$/i -function lowercaseKeys(object) { - if (!object) { - return {}; - } +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach(key => { - if (isPlainObject.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] - }); + 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 result; + } + + 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 } -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === undefined) { - delete obj[key]; +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() } - return obj; -} + let idxeq; let idxamp; let i; let p = 0; const len = data.length -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); - } // lowercase header names before merging with defaults to avoid duplicates + 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 } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + 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 } + + 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() +} + +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') +} +module.exports = UrlEncoded - options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten +/***/ }), + +/***/ 9730: +/***/ ((module) => { + +"use strict"; + + +const RE_PLUS = /\+/g + +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 +] + +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 +} + +module.exports = Decoder + + +/***/ }), + +/***/ 496: +/***/ ((module) => { + +"use strict"; + + +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) + } + } + return (path === '..' || path === '.' ? '' : path) +} + + +/***/ }), + +/***/ 9136: +/***/ ((module) => { + +"use strict"; + + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function decodeText (text, textEncoding, destEncoding) { + if (text) { + if (textDecoders.has(destEncoding)) { + try { + return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding)) + } catch (e) { } + } else { + try { + textDecoders.set(destEncoding, new TextDecoder(destEncoding)) + return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding)) + } catch (e) { } + } + } + return text +} + +module.exports = decodeText + + +/***/ }), + +/***/ 9692: +/***/ ((module) => { + +"use strict"; + + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} + + +/***/ }), + +/***/ 4426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const decodeText = __nccwpck_require__(9136) + +const RE_ENCODED = /%([a-fA-F0-9]{2})/g + +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 + } + } 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) + } + 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 (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res +} + +module.exports = parseParams + + +/***/ }), + +/***/ 334: +/***/ ((module) => { + +"use strict"; + +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); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createTokenAuth: () => createTokenAuth +}); +module.exports = __toCommonJS(dist_src_exports); + +// 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 + }; +} + +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} + +// 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); +} + +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + 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); + + +/***/ }), + +/***/ 6762: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +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); + +// 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__(5030); +var import_before_after_hook = __nccwpck_require__(3682); +var import_request = __nccwpck_require__(6234); +var import_graphql = __nccwpck_require__(8467); +var import_auth_token = __nccwpck_require__(334); + +// pkg/dist-src/version.js +var VERSION = "5.2.0"; + +// 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; + } + 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 + ) + ); + } + }; + 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)) + ); + } + }; + 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; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + 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; + } + } else { + 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; + } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 9440: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +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); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(5030); + +// pkg/dist-src/version.js +var VERSION = "9.0.5"; + +// 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: "" + } +}; + +// 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; + }, {}); +} + +// 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); +} + +// 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; +} + +// 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; +} - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); +// 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); + } + 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 mergedOptions; } +// 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 => { + return url + separator + names.map((name) => { if (name === "q") { return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } - return `${name}=${encodeURIComponent(parameters[name])}`; }).join("&"); } -const urlVariableRegex = /\{[^}]+\}/g; - +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^}]+\}/g; function removeNonChars(variableName) { return variableName.replace(/^\W+|\W+$/g, "").split(/,/); } - function extractUrlVariableNames(url) { const matches = url.match(urlVariableRegex); - if (!matches) { return []; } - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); } +// pkg/dist-src/util/omit.js function omit(object, keysToOmit) { - return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } + } + return result; } -// Based on https://github.com/bramstein/url-template, licensed under BSD -// TODO: create separate package. -// -// Copyright (c) 2012-2014, Bram Stein -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. The name of the author may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* istanbul ignore file */ +// pkg/dist-src/util/url-template.js function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { + 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 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; } } - function isDefined(value) { - return value !== undefined && value !== null; + return value !== void 0 && value !== null; } - function isKeyOperator(operator) { return operator === ";" || operator === "&" || operator === "?"; } - function getValues(context, operator, key, modifier) { - var value = context[key], - result = []; - + 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 : "")); + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); } else { if (modifier === "*") { if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); }); } else { - Object.keys(value).forEach(function (k) { + Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { result.push(encodeValue(operator, value[k], k)); } @@ -3017,20 +4348,18 @@ function getValues(context, operator, key, modifier) { } } else { const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - tmp.push(encodeValue(operator, value)); + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); }); } else { - Object.keys(value).forEach(function (k) { + 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) { @@ -3049,89 +4378,93 @@ function getValues(context, operator, key, modifier) { result.push(""); } } - return result; } - function parseUrl(template) { return { expand: expand.bind(null, template) }; } - function expand(template, context) { var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return 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; + 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(","); } - - return (values.length !== 0 ? operator : "") + values.join(separator); } else { - return values.join(","); + return encodeReserved(literal); } - } else { - return encodeReserved(literal); } - }); + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } } +// pkg/dist-src/parse.js function parse(options) { - // https://fetch.spec.whatwg.org/#methods - let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible - + 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"]); // extract variable names from URL to calculate remaining variables later - + 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; } - - const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); + 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) { - // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw - headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); } - - if (options.mediaType.previews.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; + headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } } - } // for GET/HEAD requests, set URL query parameters from remaining parameters - // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters - - + } if (["GET", "HEAD"].includes(method)) { url = addQueryParameters(url, remainingParameters); } else { @@ -3140,182 +4473,189 @@ function parse(options) { } else { if (Object.keys(remainingParameters).length) { body = remainingParameters; - } else { - headers["content-length"] = 0; } } - } // default content-type for JSON if body is set - - + } if (!headers["content-type"] && typeof body !== "undefined") { headers["content-type"] = "application/json; charset=utf-8"; - } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. - // fetch does not allow to set `content-length` header, but we can set body to an empty string - - + } if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { body = ""; - } // Only return body/request keys if present - - - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); } +// pkg/dist-src/endpoint-with-defaults.js function endpointWithDefaults(defaults, route, options) { return parse(merge(defaults, route, options)); } +// pkg/dist-src/with-defaults.js function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS = merge(oldDefaults, newDefaults); - const endpoint = endpointWithDefaults.bind(null, DEFAULTS); - return Object.assign(endpoint, { - DEFAULTS, - defaults: withDefaults.bind(null, DEFAULTS), - merge: merge.bind(null, DEFAULTS), + 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 }); } -const VERSION = "6.0.11"; - -const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. -// So we use RequestParameters and add method as additional required property. - -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] - } -}; - -const endpoint = withDefaults(null, DEFAULTS); - -exports.endpoint = endpoint; -//# sourceMappingURL=index.js.map +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), /***/ 8467: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +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); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var request = __nccwpck_require__(6234); -var universalUserAgent = __nccwpck_require__(5030); - -const VERSION = "4.6.2"; - -class GraphqlError extends Error { - constructor(request, response) { - const message = response.data.errors[0].message; - super(message); - Object.assign(this, response.data); - Object.assign(this, { - headers: response.headers - }); - this.name = "GraphqlError"; - this.request = request; // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - +// 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__(6234); +var import_universal_user_agent = __nccwpck_require__(5030); + +// pkg/dist-src/version.js +var VERSION = "7.1.0"; + +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(6234); + +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(6234); + +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +} +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); } } +}; -} - -const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; -const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request, query, options) { +// 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`)); + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); } - 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`)); + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) + continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); } } - - const parsedOptions = typeof query === "string" ? Object.assign({ - query - }, options) : query; - const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { + 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 (!result.variables) { result.variables = {}; } - result.variables[key] = parsedOptions[key]; return result; - }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix - // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 - - const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; - + }, {}); + 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"); } - - return request(requestOptions).then(response => { + 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 GraphqlError(requestOptions, { + throw new GraphqlResponseError( + requestOptions, headers, - data: response.data - }); + response.data + ); } - return response.data.data; }); } -function withDefaults(request$1, newDefaults) { - const newRequest = request$1.defaults(newDefaults); - +// 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: request.request.endpoint + endpoint: newRequest.endpoint }); } -const graphql$1 = withDefaults(request.request, { +// pkg/dist-src/index.js +var graphql2 = withDefaults(import_request3.request, { headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}` + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` }, method: "POST", url: "/graphql" @@ -3326,45 +4666,59 @@ function withCustomRequest(customRequest) { url: "/graphql" }); } - -exports.graphql = graphql$1; -exports.withCustomRequest = withCustomRequest; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), /***/ 4193: -/***/ ((__unused_webpack_module, exports) => { +/***/ ((module) => { "use strict"; +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); -Object.defineProperty(exports, "__esModule", ({ value: true })); +// 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); -const VERSION = "2.13.3"; +// pkg/dist-src/version.js +var VERSION = "9.2.1"; -/** - * Some “list” response that can be paginated have a different response structure - * - * They have a `total_count` key in the response (search also has `incomplete_results`, - * /installation/repositories also has `repository_selection`), as well as a key with - * the list of the items which name varies from endpoint to endpoint. - * - * Octokit normalizes these responses so that paginated results are always returned following - * the same structure. One challenge is that if the list response has only one page, no Link - * header is provided, so this header alone is not sufficient to check wether a response is - * paginated or not. - * - * We check if a "total_count" key is present in the response data, but also make sure that - * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would - * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref - */ +// pkg/dist-src/normalize-paginated-list-response.js function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; + } const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way - // to retrieve the same information. - + if (!responseNeedsNormalization) + return response; const incompleteResults = response.data.incomplete_results; const repositorySelection = response.data.repository_selection; const totalCount = response.data.total_count; @@ -3374,19 +4728,17 @@ function normalizePaginatedListResponse(response) { const namespaceKey = Object.keys(response.data)[0]; const data = response.data[namespaceKey]; response.data = data; - if (typeof incompleteResults !== "undefined") { response.data.incomplete_results = incompleteResults; } - if (typeof repositorySelection !== "undefined") { response.data.repository_selection = repositorySelection; } - response.data.total_count = totalCount; return response; } +// 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; @@ -3396,65 +4748,308 @@ function iterator(octokit, route, parameters) { return { [Symbol.asyncIterator]: () => ({ async next() { - if (!url) return { - done: true - }; - const response = await requestMethod({ - method, - url, - headers - }); - const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format: - // '; rel="next", ; rel="last"' - // sets `url` to undefined if "next" URL is not present or `link` header is not set - - url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: normalizedResponse - }; + 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: [] + } + }; + } } - }) }; } +// pkg/dist-src/paginate.js function paginate(octokit, route, parameters, mapFn) { if (typeof parameters === "function") { mapFn = parameters; - parameters = undefined; + parameters = void 0; } - - return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); } - -function gather(octokit, results, iterator, mapFn) { - return iterator.next().then(result => { +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { if (result.done) { return results; } - let earlyExit = false; - function done() { earlyExit = true; } - - results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); - + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); if (earlyExit) { return results; } - - return gather(octokit, results, iterator, mapFn); + return gather(octokit, results, iterator2, mapFn); }); } -const composePaginateRest = Object.assign(paginate, { +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { iterator }); -const paginatingEndpoints = ["GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/actions/runners/downloads", "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 /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/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/runners/downloads", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "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}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/team-sync/groups", "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}/team-sync/group-mappings", "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/runners", "GET /repos/{owner}/{repo}/actions/runners/downloads", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "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}/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}/branches-where-head", "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}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "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}/requested_reviewers", "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}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /scim/v2/enterprises/{enterprise}/Groups", "GET /scim/v2/enterprises/{enterprise}/Users", "GET /scim/v2/organizations/{org}/Users", "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}/team-sync/group-mappings", "GET /teams/{team_id}/teams", "GET /user/blocks", "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/public_emails", "GET /user/repos", "GET /user/repository_invitations", "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}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"]; +// 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" +]; +// pkg/dist-src/paginating-endpoints.js function isPaginatingEndpoint(arg) { if (typeof arg === "string") { return paginatingEndpoints.includes(arg); @@ -3463,11 +5058,7 @@ function isPaginatingEndpoint(arg) { } } -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ - +// pkg/dist-src/index.js function paginateRest(octokit) { return { paginate: Object.assign(paginate.bind(null, octokit), { @@ -3476,172 +5067,390 @@ function paginateRest(octokit) { }; } paginateRest.VERSION = VERSION; - -exports.composePaginateRest = composePaginateRest; -exports.isPaginatingEndpoint = isPaginatingEndpoint; -exports.paginateRest = paginateRest; -exports.paginatingEndpoints = paginatingEndpoints; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), /***/ 3044: -/***/ ((__unused_webpack_module, exports) => { +/***/ ((module) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); +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 keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods +}); +module.exports = __toCommonJS(dist_src_exports); - return target; -} +// pkg/dist-src/version.js +var VERSION = "10.4.1"; -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -const Endpoints = { +// pkg/dist-src/generated/endpoints.js +var Endpoints = { actions: { - addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"], - cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], - createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + 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}"], - createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], - createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], + 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"], - createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"], - deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + 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}"], - deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], - deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], + 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"], - 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"], - getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"], - getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"], + 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}"], - getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"], - getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], - getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"], - getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"], + 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}"], - getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], - getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, { - renamed: ["actions", "getGithubActionsPermissionsRepository"] - }], + 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}"], - getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"], + 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}"], + 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}"], - getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], - getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], + 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"], - listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], + 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"], - listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"], + 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"], + 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"], - removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - 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"], - setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"], - setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"], - setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"], - setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"] + 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}" + ] }, activity: { checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/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"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], listEventsForAuthenticatedUser: ["GET /users/{username}/events"], listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], + 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"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], listReposStarredByAuthenticatedUser: ["GET /user/starred"], listReposStarredByUser: ["GET /users/{username}/starred"], listReposWatchedByUser: ["GET /users/{username}/subscriptions"], @@ -3650,27 +5459,29 @@ const Endpoints = { 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"], + 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}"], + 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"], - createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], - createContentAttachmentForRepo: ["POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"], + 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"], @@ -3679,97 +5490,323 @@ const Endpoints = { 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}"], + 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"], + 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"], - removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"], + 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"], + 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"], + 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"] + 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"], + 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"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"], - setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"], + 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}"], + 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"], + 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"] - }], + 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}"], + 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", { - mediaType: { - previews: ["scarlet-witch"] - } - }], - getConductCode: ["GET /codes_of_conduct/{key}", { - mediaType: { - previews: ["scarlet-witch"] - } - }], - getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", { - mediaType: { - previews: ["scarlet-witch"] - } - }] + 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"] }, - emojis: { - get: ["GET /emojis"] + 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}" + ] }, - enterpriseAdmin: { - disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"], - getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"], - listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"], - setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"], - setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"], - setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"] + 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"], @@ -3815,33 +5852,52 @@ const Endpoints = { 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"] - }], + 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"] - }], + 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"] - }] + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] }, issues: { - addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + 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"], + 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}"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], + 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}"], @@ -3853,28 +5909,38 @@ const Endpoints = { 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", { - mediaType: { - previews: ["mockingbird"] - } - }], + 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"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/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}"], + 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}"] + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] }, licenses: { get: ["GET /licenses/{license}"], @@ -3883,591 +5949,789 @@ const Endpoints = { }, markdown: { render: ["POST /markdown"], - renderRaw: ["POST /markdown/raw", { - headers: { - "content-type": "text/plain; charset=utf-8" - } - }] + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] }, meta: { get: ["GET /meta"], + getAllVersions: ["GET /versions"], getOctocat: ["GET /octocat"], getZen: ["GET /zen"], root: ["GET /"] }, migrations: { - cancelImport: ["DELETE /repos/{owner}/{repo}/import"], - deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], - getImportStatus: ["GET /repos/{owner}/{repo}/import"], - getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}", { - mediaType: { - previews: ["wyandotte"] - } - }], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}", { - mediaType: { - previews: ["wyandotte"] - } - }], - listForAuthenticatedUser: ["GET /user/migrations", { - mediaType: { - previews: ["wyandotte"] + 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" + } + ], + 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" } - }], - listForOrg: ["GET /orgs/{org}/migrations", { - mediaType: { - previews: ["wyandotte"] + ], + 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" } - }], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories", { - mediaType: { - previews: ["wyandotte"] + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" + } + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" } - }], - listReposForUser: ["GET /user/migrations/{migration_id}/repositories", { - mediaType: { - previews: ["wyandotte"] + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" } - }], - mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], - setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + ], startForAuthenticatedUser: ["POST /user/migrations"], startForOrg: ["POST /orgs/{org}/migrations"], - startImport: ["PUT /repos/{owner}/{repo}/import"], - unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock", { - mediaType: { - previews: ["wyandotte"] - } - }], - unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock", { - mediaType: { - previews: ["wyandotte"] + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" + } + ], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ], + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" } - }], - updateImport: ["PATCH /repos/{owner}/{repo}/import"] + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] }, orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}" + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], blockUser: ["PUT /orgs/{org}/blocks/{username}"], cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteCustomOrganizationRole: [ + "DELETE /orgs/{org}/organization-roles/{role_id}" + ], deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + enableOrDisableSecurityProductOnAllOrgRepos: [ + "POST /orgs/{org}/{security_product}/{enablement}" + ], get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], list: ["GET /organizations"], listAppInstallations: ["GET /orgs/{org}/installations"], listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], listForAuthenticatedUser: ["GET /user/orgs"], listForUser: ["GET /users/{username}/orgs"], listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], listMembers: ["GET /orgs/{org}/members"], listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], listPendingInvitations: ["GET /orgs/{org}/invitations"], listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], listWebhooks: ["GET /orgs/{org}/hooks"], + patchCustomOrganizationRole: [ + "PATCH /orgs/{org}/organization-roles/{role_id}" + ], pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], removeMember: ["DELETE /orgs/{org}/members/{username}"], removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], - removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}" + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] }, packages: { - deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"], - deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"], - deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], - deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, { - renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] - }], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, { - renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"] - }], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"], - getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"], - getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"], - getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"], - getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"], - getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"], - getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], - restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"] + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] }, projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", { - mediaType: { - previews: ["inertia"] - } - }], - createCard: ["POST /projects/columns/{column_id}/cards", { - mediaType: { - previews: ["inertia"] - } - }], - createColumn: ["POST /projects/{project_id}/columns", { - mediaType: { - previews: ["inertia"] - } - }], - createForAuthenticatedUser: ["POST /user/projects", { - mediaType: { - previews: ["inertia"] - } - }], - createForOrg: ["POST /orgs/{org}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - createForRepo: ["POST /repos/{owner}/{repo}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - delete: ["DELETE /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - deleteCard: ["DELETE /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - deleteColumn: ["DELETE /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }], - get: ["GET /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getCard: ["GET /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getColumn: ["GET /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission", { - mediaType: { - previews: ["inertia"] - } - }], - listCards: ["GET /projects/columns/{column_id}/cards", { - mediaType: { - previews: ["inertia"] - } - }], - listCollaborators: ["GET /projects/{project_id}/collaborators", { - mediaType: { - previews: ["inertia"] - } - }], - listColumns: ["GET /projects/{project_id}/columns", { - mediaType: { - previews: ["inertia"] - } - }], - listForOrg: ["GET /orgs/{org}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listForRepo: ["GET /repos/{owner}/{repo}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listForUser: ["GET /users/{username}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - moveCard: ["POST /projects/columns/cards/{card_id}/moves", { - mediaType: { - previews: ["inertia"] - } - }], - moveColumn: ["POST /projects/columns/{column_id}/moves", { - mediaType: { - previews: ["inertia"] - } - }], - removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}", { - mediaType: { - previews: ["inertia"] - } - }], - update: ["PATCH /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - updateCard: ["PATCH /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - updateColumn: ["PATCH /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }] + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], + createCard: ["POST /projects/columns/{column_id}/cards"], + createColumn: ["POST /projects/{project_id}/columns"], + createForAuthenticatedUser: ["POST /user/projects"], + createForOrg: ["POST /orgs/{org}/projects"], + createForRepo: ["POST /repos/{owner}/{repo}/projects"], + delete: ["DELETE /projects/{project_id}"], + deleteCard: ["DELETE /projects/columns/cards/{card_id}"], + deleteColumn: ["DELETE /projects/columns/{column_id}"], + get: ["GET /projects/{project_id}"], + getCard: ["GET /projects/columns/cards/{card_id}"], + getColumn: ["GET /projects/columns/{column_id}"], + getPermissionForUser: [ + "GET /projects/{project_id}/collaborators/{username}/permission" + ], + listCards: ["GET /projects/columns/{column_id}/cards"], + listCollaborators: ["GET /projects/{project_id}/collaborators"], + listColumns: ["GET /projects/{project_id}/columns"], + listForOrg: ["GET /orgs/{org}/projects"], + listForRepo: ["GET /repos/{owner}/{repo}/projects"], + listForUser: ["GET /users/{username}/projects"], + moveCard: ["POST /projects/columns/cards/{card_id}/moves"], + moveColumn: ["POST /projects/columns/{column_id}/moves"], + removeCollaborator: [ + "DELETE /projects/{project_id}/collaborators/{username}" + ], + update: ["PATCH /projects/{project_id}"], + updateCard: ["PATCH /projects/columns/cards/{card_id}"], + updateColumn: ["PATCH /projects/columns/{column_id}"] }, pulls: { checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], - deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch", { - mediaType: { - previews: ["lydian"] - } - }], - updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] - }, - rateLimit: { - get: ["GET /rate_limit"] + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] }, + rateLimit: { get: ["GET /rate_limit"] }, reactions: { - createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteLegacy: ["DELETE /reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }, { - deprecated: "octokit.rest.reactions.deleteLegacy() is deprecated, see https://docs.github.com/rest/reference/reactions/#delete-a-reaction-legacy" - }], - listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }] + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] }, repos: { - acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}"], - addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"], - createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], createDeployKey: ["POST /repos/{owner}/{repo}/keys"], createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], createForAuthenticatedUser: ["POST /user/repos"], createFork: ["POST /repos/{owner}/{repo}/forks"], createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"], + createOrUpdateCustomPropertiesValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], createRelease: ["POST /repos/{owner}/{repo}/releases"], - createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", { - mediaType: { - previews: ["baptiste"] - } - }], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"], - deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }], - deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteTagProtection: [ + "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" + ], deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes", { - mediaType: { - previews: ["london"] - } - }], - disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, { - renamed: ["repos", "downloadZipballArchive"] - }], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes", { - mediaType: { - previews: ["london"] - } - }], - enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], - getAllTopics: ["GET /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], - getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], - getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], getPages: ["GET /repos/{owner}/{repo}/pages"], getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], getReadme: ["GET /repos/{owner}/{repo}/readme"], getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], getViews: ["GET /repos/{owner}/{repo}/traffic/views"], getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", { - mediaType: { - previews: ["groot"] - } - }], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], listCommits: ["GET /repos/{owner}/{repo}/commits"], listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], listDeployments: ["GET /repos/{owner}/{repo}/deployments"], listForAuthenticatedUser: ["GET /user/repos"], listForOrg: ["GET /orgs/{org}/repos"], @@ -4478,496 +6742,831 @@ const Endpoints = { listLanguages: ["GET /repos/{owner}/{repo}/languages"], listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", { - mediaType: { - previews: ["groot"] - } - }], - listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], listTags: ["GET /repos/{owner}/{repo}/tags"], listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], - removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], transfer: ["POST /repos/{owner}/{repo}/transfer"], update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], - updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], - updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { - renamed: ["repos", "updateStatusCheckProtection"] - }], - updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"], - uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { - baseUrl: "https://uploads.github.com" - }] + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] }, search: { code: ["GET /search/code"], - commits: ["GET /search/commits", { - mediaType: { - previews: ["cloak"] - } - }], + commits: ["GET /search/commits"], issuesAndPullRequests: ["GET /search/issues"], labels: ["GET /search/labels"], repos: ["GET /search/repositories"], - topics: ["GET /search/topics", { - mediaType: { - previews: ["mercy"] - } - }], + topics: ["GET /search/topics"], users: ["GET /search/users"] }, secretScanning: { - getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"], + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"] + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] }, teams: { - addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], - addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateProjectPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForProjectInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], list: ["GET /orgs/{org}/teams"], listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], listForAuthenticatedUser: ["GET /user/teams"], listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects", { - mediaType: { - previews: ["inertia"] - } - }], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], - removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeProjectInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] }, users: { - addEmailForAuthenticated: ["POST /user/emails"], + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], block: ["PUT /user/blocks/{username}"], checkBlocked: ["GET /user/blocks/{username}"], checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: ["POST /user/keys"], - deleteEmailForAuthenticated: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], follow: ["PUT /user/following/{username}"], getAuthenticated: ["GET /user"], getByUsername: ["GET /users/{username}"], getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], list: ["GET /users"], - listBlockedByAuthenticated: ["GET /user/blocks"], - listEmailsForAuthenticated: ["GET /user/emails"], - listFollowedByAuthenticated: ["GET /user/following"], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], listFollowersForAuthenticatedUser: ["GET /user/followers"], listFollowersForUser: ["GET /users/{username}/followers"], listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: ["GET /user/gpg_keys"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: ["GET /user/public_emails"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: ["GET /user/keys"], - setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], unblock: ["DELETE /user/blocks/{username}"], unfollow: ["DELETE /user/following/{username}"], updateAuthenticated: ["PATCH /user"] } }; +var endpoints_default = Endpoints; -const VERSION = "5.3.1"; - -function endpointsToMethods(octokit, endpointsMap) { - const newMethods = {}; - - for (const [scope, endpoints] of Object.entries(endpointsMap)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign({ +// pkg/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { method, url - }, defaults); - - if (!newMethods[scope]) { - newMethods[scope] = {}; - } - - const scopeMethods = newMethods[scope]; - - if (decorations) { - scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); - continue; - } - - scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); + }, + defaults + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); + } +} +var handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); } + return cache[methodName]; + } +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); } - return newMethods; } - function decorate(octokit, scope, methodName, defaults, decorations) { const requestWithDefaults = octokit.request.defaults(defaults); - /* istanbul ignore next */ - function withDecorations(...args) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` - + let options = requestWithDefaults.endpoint.merge(...args); if (decorations.mapToData) { options = Object.assign({}, options, { data: options[decorations.mapToData], - [decorations.mapToData]: undefined + [decorations.mapToData]: void 0 }); return requestWithDefaults(options); } - if (decorations.renamed) { const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); } - if (decorations.deprecated) { octokit.log.warn(decorations.deprecated); } - if (decorations.renamedParameters) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - const options = requestWithDefaults.endpoint.merge(...args); - - for (const [name, alias] of Object.entries(decorations.renamedParameters)) { - if (name in options) { - octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); - - if (!(alias in options)) { - options[alias] = options[name]; + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; } - - delete options[name]; + delete options2[name]; } } - - return requestWithDefaults(options); - } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - - + return requestWithDefaults(options2); + } return requestWithDefaults(...args); } - return Object.assign(withDecorations, requestWithDefaults); } +// pkg/dist-src/index.js function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); + const api = endpointsToMethods(octokit); return { rest: api }; } restEndpointMethods.VERSION = VERSION; function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); - return _objectSpread2(_objectSpread2({}, api), {}, { + const api = endpointsToMethods(octokit); + return { + ...api, rest: api - }); + }; } legacyRestEndpointMethods.VERSION = VERSION; - -exports.legacyRestEndpointMethods = legacyRestEndpointMethods; -exports.restEndpointMethods = restEndpointMethods; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), /***/ 537: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var deprecation = __nccwpck_require__(8932); -var once = _interopDefault(__nccwpck_require__(1223)); - -const logOnce = once(deprecation => console.warn(deprecation)); -/** - * Error with extra properties to help with debugging - */ - -class RequestError extends Error { +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + RequestError: () => RequestError +}); +module.exports = __toCommonJS(dist_src_exports); +var import_deprecation = __nccwpck_require__(8932); +var import_once = __toESM(__nccwpck_require__(1223)); +var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var RequestError = class extends Error { constructor(message, statusCode, options) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - + super(message); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } - this.name = "HttpError"; this.status = statusCode; - Object.defineProperty(this, "code", { - get() { - logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; - } - - }); - this.headers = options.headers || {}; // redact request credentials without mutating original request options - + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + authorization: options.request.headers.authorization.replace( + / .*$/, + " [REDACTED]" + ) }); } - - requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); this.request = requestCopy; + Object.defineProperty(this, "code", { + get() { + logOnceCode( + new import_deprecation.Deprecation( + "[@octokit/request-error] `error.code` is deprecated, use `error.status`." + ) + ); + return statusCode; + } + }); + Object.defineProperty(this, "headers", { + get() { + logOnceHeaders( + new import_deprecation.Deprecation( + "[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`." + ) + ); + return headers || {}; + } + }); } - -} - -exports.RequestError = RequestError; -//# sourceMappingURL=index.js.map +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), /***/ 6234: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +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); -Object.defineProperty(exports, "__esModule", ({ value: true })); +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + request: () => request +}); +module.exports = __toCommonJS(dist_src_exports); +var import_endpoint = __nccwpck_require__(9440); +var import_universal_user_agent = __nccwpck_require__(5030); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } +// pkg/dist-src/version.js +var VERSION = "8.4.0"; -var endpoint = __nccwpck_require__(9440); -var universalUserAgent = __nccwpck_require__(5030); -var isPlainObject = __nccwpck_require__(3287); -var nodeFetch = _interopDefault(__nccwpck_require__(467)); -var requestError = __nccwpck_require__(537); +// pkg/dist-src/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); +} -const VERSION = "5.4.15"; +// pkg/dist-src/fetch-wrapper.js +var import_request_error = __nccwpck_require__(537); +// pkg/dist-src/get-buffer-response.js function getBufferResponse(response) { return response.arrayBuffer(); } +// pkg/dist-src/fetch-wrapper.js function fetchWrapper(requestOptions) { - if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); } - let headers = {}; let status; let url; - const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; - return fetch(requestOptions.url, Object.assign({ + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + throw new Error( + "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" + ); + } + return fetch(requestOptions.url, { method: requestOptions.method, body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, headers: requestOptions.headers, - redirect: requestOptions.redirect - }, // `requestOptions.request.agent` type is incompatible - // see https://github.com/octokit/types.ts/pull/264 - requestOptions.request)).then(response => { + signal: (_d = requestOptions.request) == null ? void 0 : _d.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }).then(async (response) => { url = response.url; status = response.status; - for (const keyAndValue of response.headers) { headers[keyAndValue[0]] = keyAndValue[1]; } - + if ("deprecation" in headers) { + const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } if (status === 204 || status === 205) { return; - } // GitHub API returns 200 for HEAD requests - - + } if (requestOptions.method === "HEAD") { if (status < 400) { return; } - - throw new requestError.RequestError(response.statusText, status, { - headers, + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, request: requestOptions }); } - if (status === 304) { - throw new requestError.RequestError("Not modified", status, { - headers, + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, request: requestOptions }); } - if (status >= 400) { - return response.text().then(message => { - const error = new requestError.RequestError(message, status, { + const data = await getResponseData(response); + const error = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, headers, - request: requestOptions - }); - - try { - let responseBody = JSON.parse(error.message); - Object.assign(error, responseBody); - let errors = responseBody.errors; // Assumption `errors` would always be in Array format - - error.message = error.message + ": " + errors.map(JSON.stringify).join(", "); - } catch (e) {// ignore, see octokit/rest.js#684 - } - - throw error; + data + }, + request: requestOptions }); + throw error; } - - const contentType = response.headers.get("content-type"); - - if (/application\/json/.test(contentType)) { - return response.json(); - } - - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); - } - - return getBufferResponse(response); - }).then(data => { + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { return { status, url, headers, data }; - }).catch(error => { - if (error instanceof requestError.RequestError) { + }).catch((error) => { + if (error instanceof import_request_error.RequestError) + throw error; + else if (error.name === "AbortError") throw error; + let message = error.message; + if (error.name === "TypeError" && "cause" in error) { + if (error.cause instanceof Error) { + message = error.cause.message; + } else if (typeof error.cause === "string") { + message = error.cause; + } } - - throw new requestError.RequestError(error.message, 500, { - headers, + throw new import_request_error.RequestError(message, 500, { request: requestOptions }); }); } +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (/application\/json/.test(contentType)) { + return response.json().catch(() => response.text()).catch(() => ""); + } + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + return getBufferResponse(response); +} +function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} +// pkg/dist-src/with-defaults.js function withDefaults(oldEndpoint, newDefaults) { - const endpoint = oldEndpoint.defaults(newDefaults); - - const newApi = function (route, parameters) { - const endpointOptions = endpoint.merge(route, parameters); - + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint.parse(endpointOptions)); + return fetchWrapper(endpoint2.parse(endpointOptions)); } - - const request = (route, parameters) => { - return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); }; - - Object.assign(request, { - endpoint, - defaults: withDefaults.bind(null, endpoint) + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) }); - return endpointOptions.request.hook(request, endpointOptions); + return endpointOptions.request.hook(request2, endpointOptions); }; - return Object.assign(newApi, { - endpoint, - defaults: withDefaults.bind(null, endpoint) + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) }); } -const request = withDefaults(endpoint.endpoint, { +// pkg/dist-src/index.js +var request = withDefaults(import_endpoint.endpoint, { headers: { - "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` } }); - -exports.request = request; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), @@ -5689,69992 +8288,89024 @@ module.exports = { /***/ }), -/***/ 6545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(2618); - -/***/ }), - -/***/ 8104: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(328); -var settle = __nccwpck_require__(3211); -var buildFullPath = __nccwpck_require__(1934); -var buildURL = __nccwpck_require__(646); -var http = __nccwpck_require__(3685); -var https = __nccwpck_require__(5687); -var httpFollow = (__nccwpck_require__(7707).http); -var httpsFollow = (__nccwpck_require__(7707).https); -var url = __nccwpck_require__(7310); -var zlib = __nccwpck_require__(9796); -var VERSION = (__nccwpck_require__(4322).version); -var createError = __nccwpck_require__(5226); -var enhanceError = __nccwpck_require__(1516); -var defaults = __nccwpck_require__(8190); -var Cancel = __nccwpck_require__(8875); - -var isHttps = /https:?/; - -/** - * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} proxy - * @param {string} location - */ -function setProxy(options, proxy, location) { - options.hostname = proxy.host; - options.host = proxy.host; - options.port = proxy.port; - options.path = location; - - // Basic proxy authorization - if (proxy.auth) { - var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } +/***/ 3497: +/***/ ((module) => { - // If a proxy is used, any redirects must also pass through the proxy - options.beforeRedirect = function beforeRedirect(redirection) { - redirection.headers.host = redirection.host; - setProxy(redirection, proxy, redirection.href); - }; +function isBuffer (value) { + return Buffer.isBuffer(value) || value instanceof Uint8Array } -/*eslint consistent-return:0*/ -module.exports = function httpAdapter(config) { - return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { - var onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - var resolve = function resolve(value) { - done(); - resolvePromise(value); - }; - var reject = function reject(value) { - done(); - rejectPromise(value); - }; - var data = config.data; - var headers = config.headers; - var headerNames = {}; - - Object.keys(headers).forEach(function storeLowerName(name) { - headerNames[name.toLowerCase()] = name; - }); - - // Set User-Agent (required by some servers) - // See https://github.com/axios/axios/issues/69 - if ('user-agent' in headerNames) { - // User-Agent is specified; handle case where no UA header is desired - if (!headers[headerNames['user-agent']]) { - delete headers[headerNames['user-agent']]; - } - // Otherwise, use specified value - } else { - // Only set header if it hasn't been set in config - headers['User-Agent'] = 'axios/' + VERSION; - } - - if (data && !utils.isStream(data)) { - if (Buffer.isBuffer(data)) { - // Nothing to do... - } else if (utils.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(createError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - config - )); - } - - // Add Content-Length header if data exists - if (!headerNames['content-length']) { - headers['Content-Length'] = data.length; - } - } - - // HTTP basic authentication - var auth = undefined; - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - auth = username + ':' + password; - } - - // Parse url - var fullPath = buildFullPath(config.baseURL, config.url); - var parsed = url.parse(fullPath); - var protocol = parsed.protocol || 'http:'; - - if (!auth && parsed.auth) { - var urlAuth = parsed.auth.split(':'); - var urlUsername = urlAuth[0] || ''; - var urlPassword = urlAuth[1] || ''; - auth = urlUsername + ':' + urlPassword; - } - - if (auth && headerNames.authorization) { - delete headers[headerNames.authorization]; - } - - var isHttpsRequest = isHttps.test(protocol); - var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; - - var options = { - path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), - method: config.method.toUpperCase(), - headers: headers, - agent: agent, - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth: auth - }; - - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname; - options.port = parsed.port; - } - - var proxy = config.proxy; - if (!proxy && proxy !== false) { - var proxyEnv = protocol.slice(0, -1) + '_proxy'; - var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; - if (proxyUrl) { - var parsedProxyUrl = url.parse(proxyUrl); - var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; - var shouldProxy = true; - - if (noProxyEnv) { - var noProxy = noProxyEnv.split(',').map(function trim(s) { - return s.trim(); - }); - - shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { - if (!proxyElement) { - return false; - } - if (proxyElement === '*') { - return true; - } - if (proxyElement[0] === '.' && - parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { - return true; - } - - return parsed.hostname === proxyElement; - }); - } - - if (shouldProxy) { - proxy = { - host: parsedProxyUrl.hostname, - port: parsedProxyUrl.port, - protocol: parsedProxyUrl.protocol - }; - - if (parsedProxyUrl.auth) { - var proxyUrlAuth = parsedProxyUrl.auth.split(':'); - proxy.auth = { - username: proxyUrlAuth[0], - password: proxyUrlAuth[1] - }; - } - } - } - } - - if (proxy) { - options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); - setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); - } - - var transport; - var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsProxy ? https : http; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - transport = isHttpsProxy ? httpsFollow : httpFollow; - } - - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; - } - - if (config.insecureHTTPParser) { - options.insecureHTTPParser = config.insecureHTTPParser; - } - - // Create the request - var req = transport.request(options, function handleResponse(res) { - if (req.aborted) return; - - // uncompress the response body transparently if required - var stream = res; - - // return the last request in case of redirects - var lastRequest = res.req || req; - - - // if no content, is HEAD request or decompress disabled we should not decompress - if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { - switch (res.headers['content-encoding']) { - /*eslint default-case:0*/ - case 'gzip': - case 'compress': - case 'deflate': - // add the unzipper to the body stream processing pipeline - stream = stream.pipe(zlib.createUnzip()); - - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - } - } - - var response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: res.headers, - config: config, - request: lastRequest - }; - - if (config.responseType === 'stream') { - response.data = stream; - settle(resolve, reject, response); - } else { - var responseBuffer = []; - var totalResponseBytes = 0; - stream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; - - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { - stream.destroy(); - reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - config, null, lastRequest)); - } - }); - - stream.on('error', function handleStreamError(err) { - if (req.aborted) return; - reject(enhanceError(err, config, null, lastRequest)); - }); - - stream.on('end', function handleStreamEnd() { - var responseData = Buffer.concat(responseBuffer); - if (config.responseType !== 'arraybuffer') { - responseData = responseData.toString(config.responseEncoding); - if (!config.responseEncoding || config.responseEncoding === 'utf8') { - responseData = utils.stripBOM(responseData); - } - } - - response.data = responseData; - settle(resolve, reject, response); - }); - } - }); - - // Handle errors - req.on('error', function handleRequestError(err) { - if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return; - reject(enhanceError(err, config, null, req)); - }); - - // Handle request timeout - if (config.timeout) { - // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. - var timeout = parseInt(config.timeout, 10); - - if (isNaN(timeout)) { - reject(createError( - 'error trying to parse `config.timeout` to int', - config, - 'ERR_PARSE_TIMEOUT', - req - )); - - return; - } - - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devoring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(timeout, function handleRequestTimeout() { - req.abort(); - var transitional = config.transitional || defaults.transitional; - reject(createError( - 'timeout of ' + timeout + 'ms exceeded', - config, - transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', - req - )); - }); - } - - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function(cancel) { - if (req.aborted) return; - - req.abort(); - reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel); - }; - - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } - - - // Send the request - if (utils.isStream(data)) { - data.on('error', function handleStreamError(err) { - reject(enhanceError(err, config, null, req)); - }).pipe(req); - } else { - req.end(data); - } - }); -}; - - -/***/ }), - -/***/ 3454: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(328); -var settle = __nccwpck_require__(3211); -var cookies = __nccwpck_require__(1545); -var buildURL = __nccwpck_require__(646); -var buildFullPath = __nccwpck_require__(1934); -var parseHeaders = __nccwpck_require__(6455); -var isURLSameOrigin = __nccwpck_require__(3608); -var createError = __nccwpck_require__(5226); -var defaults = __nccwpck_require__(8190); -var Cancel = __nccwpck_require__(8875); - -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - var responseType = config.responseType; - var onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - - if (utils.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } - - var request = new XMLHttpRequest(); - - // HTTP basic authentication - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } - - var fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - - // Set the request timeout in MS - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } - // Prepare the response - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !responseType || responseType === 'text' || responseType === 'json' ? - request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; - - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - - // Clean up request - request = null; - } - - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } - - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - setTimeout(onloadend); - }; - } - - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } - - reject(createError('Request aborted', config, 'ECONNABORTED', request)); - - // Clean up request - request = null; - }; - - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError('Network Error', config, null, request)); - - // Clean up request - request = null; - }; - - // Handle timeout - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - var transitional = config.transitional || defaults.transitional; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(createError( - timeoutErrorMessage, - config, - transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', - request)); - - // Clean up request - request = null; - }; - - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (utils.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; - - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } - - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } - - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } - - // Add responseType to request if needed - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; - } - - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } - - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } - - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function(cancel) { - if (!request) { - return; - } - reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel); - request.abort(); - request = null; - }; - - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } - - if (!requestData) { - requestData = null; - } - - // Send the request - request.send(requestData); - }); -}; - - -/***/ }), - -/***/ 2618: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(328); -var bind = __nccwpck_require__(7065); -var Axios = __nccwpck_require__(8178); -var mergeConfig = __nccwpck_require__(4831); -var defaults = __nccwpck_require__(8190); - -/** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ -function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind(Axios.prototype.request, context); - - // Copy axios.prototype to instance - utils.extend(instance, Axios.prototype, context); - - // Copy context to instance - utils.extend(instance, context); - - // Factory for creating new instances - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - - return instance; +function isEncoding (encoding) { + return Buffer.isEncoding(encoding) } -// Create the default instance to be exported -var axios = createInstance(defaults); - -// Expose Axios class to allow class inheritance -axios.Axios = Axios; - -// Expose Cancel & CancelToken -axios.Cancel = __nccwpck_require__(8875); -axios.CancelToken = __nccwpck_require__(1587); -axios.isCancel = __nccwpck_require__(4057); -axios.VERSION = (__nccwpck_require__(4322).version); - -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; -axios.spread = __nccwpck_require__(4850); - -// Expose isAxiosError -axios.isAxiosError = __nccwpck_require__(650); - -module.exports = axios; - -// Allow use of default import syntax in TypeScript -module.exports["default"] = axios; - - -/***/ }), - -/***/ 8875: -/***/ ((module) => { - -"use strict"; - - -/** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ -function Cancel(message) { - this.message = message; +function alloc (size, fill, encoding) { + return Buffer.alloc(size, fill, encoding) } -Cancel.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); -}; - -Cancel.prototype.__CANCEL__ = true; - -module.exports = Cancel; - - -/***/ }), - -/***/ 1587: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - +function allocUnsafe (size) { + return Buffer.allocUnsafe(size) +} -var Cancel = __nccwpck_require__(8875); +function allocUnsafeSlow (size) { + return Buffer.allocUnsafeSlow(size) +} -/** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ -function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } +function byteLength (string, encoding) { + return Buffer.byteLength(string, encoding) +} - var resolvePromise; +function compare (a, b) { + return Buffer.compare(a, b) +} - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); +function concat (buffers, totalLength) { + return Buffer.concat(buffers, totalLength) +} - var token = this; +function copy (source, target, targetStart, start, end) { + return toBuffer(source).copy(target, targetStart, start, end) +} - // eslint-disable-next-line func-names - this.promise.then(function(cancel) { - if (!token._listeners) return; +function equals (a, b) { + return toBuffer(a).equals(b) +} - var i; - var l = token._listeners.length; +function fill (buffer, value, offset, end, encoding) { + return toBuffer(buffer).fill(value, offset, end, encoding) +} - for (i = 0; i < l; i++) { - token._listeners[i](cancel); - } - token._listeners = null; - }); +function from (value, encodingOrOffset, length) { + return Buffer.from(value, encodingOrOffset, length) +} - // eslint-disable-next-line func-names - this.promise.then = function(onfulfilled) { - var _resolve; - // eslint-disable-next-line func-names - var promise = new Promise(function(resolve) { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; +function includes (buffer, value, byteOffset, encoding) { + return toBuffer(buffer).includes(value, byteOffset, encoding) +} - return promise; - }; +function indexOf (buffer, value, byfeOffset, encoding) { + return toBuffer(buffer).indexOf(value, byfeOffset, encoding) +} - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; - } +function lastIndexOf (buffer, value, byteOffset, encoding) { + return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding) +} - token.reason = new Cancel(message); - resolvePromise(token.reason); - }); +function swap16 (buffer) { + return toBuffer(buffer).swap16() } -/** - * Throws a `Cancel` if cancellation has been requested. - */ -CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } -}; +function swap32 (buffer) { + return toBuffer(buffer).swap32() +} -/** - * Subscribe to the cancel signal - */ +function swap64 (buffer) { + return toBuffer(buffer).swap64() +} -CancelToken.prototype.subscribe = function subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } +function toBuffer (buffer) { + if (Buffer.isBuffer(buffer)) return buffer + return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) +} - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } -}; +function toString (buffer, encoding, start, end) { + return toBuffer(buffer).toString(encoding, start, end) +} -/** - * Unsubscribe from the cancel signal - */ +function write (buffer, string, offset, length, encoding) { + return toBuffer(buffer).write(string, offset, length, encoding) +} -CancelToken.prototype.unsubscribe = function unsubscribe(listener) { - if (!this._listeners) { - return; - } - var index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); - } -}; +function writeDoubleLE (buffer, value, offset) { + return toBuffer(buffer).writeDoubleLE(value, offset) +} -/** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ -CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; -}; +function writeFloatLE (buffer, value, offset) { + return toBuffer(buffer).writeFloatLE(value, offset) +} -module.exports = CancelToken; +function writeUInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeUInt32LE(value, offset) +} +function writeInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeInt32LE(value, offset) +} -/***/ }), +function readDoubleLE (buffer, offset) { + return toBuffer(buffer).readDoubleLE(offset) +} -/***/ 4057: -/***/ ((module) => { +function readFloatLE (buffer, offset) { + return toBuffer(buffer).readFloatLE(offset) +} -"use strict"; +function readUInt32LE (buffer, offset) { + return toBuffer(buffer).readUInt32LE(offset) +} +function readInt32LE (buffer, offset) { + return toBuffer(buffer).readInt32LE(offset) +} -module.exports = function isCancel(value) { - return !!(value && value.__CANCEL__); -}; +module.exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + writeDoubleLE, + writeFloatLE, + writeUInt32LE, + writeInt32LE, + readDoubleLE, + readFloatLE, + readUInt32LE, + readInt32LE +} /***/ }), -/***/ 8178: +/***/ 5447: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var utils = __nccwpck_require__(328); -var buildURL = __nccwpck_require__(646); -var InterceptorManager = __nccwpck_require__(3214); -var dispatchRequest = __nccwpck_require__(5062); -var mergeConfig = __nccwpck_require__(4831); -var validator = __nccwpck_require__(1632); +var crypto_hash_sha512 = (__nccwpck_require__(8729).lowlevel.crypto_hash); -var validators = validator.validators; -/** - * Create a new instance of Axios +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. * - * @param {Object} instanceConfig The default config for the instance + * Credit for the actual porting work goes to: + * Devi Mandiri */ -function Axios(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; -} -/** - * Dispatch a request +/* + * The Blowfish portions are under the following license: * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ -Axios.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } - - config = mergeConfig(this.defaults, config); - - // Set config.method - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } - - var transitional = config.transitional; - - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); - } - - // filter out skipped interceptors - var requestInterceptorChain = []; - var synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } - - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - - var responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - - var promise; - - if (!synchronousRequestInterceptors) { - var chain = [dispatchRequest, undefined]; - - Array.prototype.unshift.apply(chain, requestInterceptorChain); - chain = chain.concat(responseInterceptorChain); - - promise = Promise.resolve(config); - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } - - return promise; - } - - - var newConfig = config; - while (requestInterceptorChain.length) { - var onFulfilled = requestInterceptorChain.shift(); - var onRejected = requestInterceptorChain.shift(); - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected(error); - break; - } - } - - try { - promise = dispatchRequest(newConfig); - } catch (error) { - return Promise.reject(error); - } - - while (responseInterceptorChain.length) { - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); - } - - return promise; -}; - -Axios.prototype.getUri = function getUri(config) { - config = mergeConfig(this.defaults, config); - return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); -}; - -// Provide aliases for supported request methods -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; -}); - -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, data, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: data - })); - }; -}); - -module.exports = Axios; - - -/***/ }), - -/***/ 3214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(328); - -function InterceptorManager() { - this.handlers = []; -} - -/** - * Add a new interceptor to the stack + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` + * Implementation advice by David Mazieres . * - * @return {Number} An ID used to remove interceptor later - */ -InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; -}; - -/** - * Remove an interceptor from the stack + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. * - * @param {Number} id The ID that was returned by `use` + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -InterceptorManager.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } -}; -/** - * Iterate over all the registered interceptors +/* + * The bcrypt_pbkdf portions are under the following license: * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. + * Copyright (c) 2013 Ted Unangst * - * @param {Function} fn The function to call for each interceptor - */ -InterceptorManager.prototype.forEach = function forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); -}; - -module.exports = InterceptorManager; - - -/***/ }), - -/***/ 1934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var isAbsoluteURL = __nccwpck_require__(1301); -var combineURLs = __nccwpck_require__(7189); - -/** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -module.exports = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -}; - - -/***/ }), - -/***/ 5226: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var enhanceError = __nccwpck_require__(1516); - -/** - * Create an Error with the specified message, config, error code, request and response. +/* + * Performance improvements (Javascript-specific): * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ -module.exports = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError(error, config, code, request, response); -}; - - -/***/ }), - -/***/ 5062: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(328); -var transformData = __nccwpck_require__(9812); -var isCancel = __nccwpck_require__(4057); -var defaults = __nccwpck_require__(8190); -var Cancel = __nccwpck_require__(8875); - -/** - * Throws a `Cancel` if cancellation has been requested. - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - - if (config.signal && config.signal.aborted) { - throw new Cancel('canceled'); - } -} - -/** - * Dispatch a request to the server using the configured adapter. + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -module.exports = function dispatchRequest(config) { - throwIfCancellationRequested(config); - // Ensure headers exist - config.headers = config.headers || {}; +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 - // Transform request data - config.data = transformData.call( - config, - config.data, - config.headers, - config.transformRequest - ); - - // Flatten headers - config.headers = utils.merge( - config.headers.common || {}, - config.headers[config.method] || {}, - config.headers - ); - - utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - function cleanHeaderConfig(method) { - delete config.headers[method]; - } - ); - - var adapter = config.adapter || defaults.adapter; - - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - - // Transform response data - response.data = transformData.call( - config, - response.data, - response.headers, - config.transformResponse - ); - - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - reason.response.data, - reason.response.headers, - config.transformResponse - ); - } - } +var BLF_J = 0; - return Promise.reject(reason); - }); +var Blowfish = function() { + this.S = [ + new Uint32Array([ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), + new Uint32Array([ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), + new Uint32Array([ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), + new Uint32Array([ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) + ]; + this.P = new Uint32Array([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b]); }; +function F(S, x8, i) { + return (((S[0][x8[i+3]] + + S[1][x8[i+2]]) ^ + S[2][x8[i+1]]) + + S[3][x8[i]]); +}; -/***/ }), - -/***/ 1516: -/***/ ((module) => { - -"use strict"; - - -/** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ -module.exports = function enhanceError(error, config, code, request, response) { - error.config = config; - if (code) { - error.code = code; +Blowfish.prototype.encipher = function(x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); } - - error.request = request; - error.response = response; - error.isAxiosError = true; - - error.toJSON = function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - }; - return error; + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; }; +Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; -/***/ }), - -/***/ 4831: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - +function stream2word(data, databytes){ + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +}; -var utils = __nccwpck_require__(328); +Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); -/** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ -module.exports = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; - function getMergedValue(target, source) { - if (utils.isPlainObject(target) && utils.isPlainObject(source)) { - return utils.merge(target, source); - } else if (utils.isPlainObject(source)) { - return utils.merge({}, source); - } else if (utils.isArray(source)) { - return source.slice(); - } - return source; + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i+1] = d[1]; } - // eslint-disable-next-line consistent-return - function mergeDeepProperties(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(config1[prop], config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; } } +}; - // eslint-disable-next-line consistent-return - function valueFromConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } +Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); } - // eslint-disable-next-line consistent-return - function defaultToConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i+1] = d[1]; } - // eslint-disable-next-line consistent-return - function mergeDirectKeys(prop) { - if (prop in config2) { - return getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - return getMergedValue(undefined, config1[prop]); + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; } } - - var mergeMap = { - 'url': valueFromConfig2, - 'method': valueFromConfig2, - 'data': valueFromConfig2, - 'baseURL': defaultToConfig2, - 'transformRequest': defaultToConfig2, - 'transformResponse': defaultToConfig2, - 'paramsSerializer': defaultToConfig2, - 'timeout': defaultToConfig2, - 'timeoutMessage': defaultToConfig2, - 'withCredentials': defaultToConfig2, - 'adapter': defaultToConfig2, - 'responseType': defaultToConfig2, - 'xsrfCookieName': defaultToConfig2, - 'xsrfHeaderName': defaultToConfig2, - 'onUploadProgress': defaultToConfig2, - 'onDownloadProgress': defaultToConfig2, - 'decompress': defaultToConfig2, - 'maxContentLength': defaultToConfig2, - 'maxBodyLength': defaultToConfig2, - 'transport': defaultToConfig2, - 'httpAgent': defaultToConfig2, - 'httpsAgent': defaultToConfig2, - 'cancelToken': defaultToConfig2, - 'socketPath': defaultToConfig2, - 'responseEncoding': defaultToConfig2, - 'validateStatus': mergeDirectKeys - }; - - utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { - var merge = mergeMap[prop] || mergeDeepProperties; - var configValue = merge(prop); - (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - - return config; + BLF_J = 0; }; +Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i*2)); + } +}; -/***/ }), +Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i*2)); + } +}; -/***/ 3211: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; -"use strict"; +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), i, + ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, + 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, + 105,116,101]); //"OxychromaticBlowfishSwatDynamite" + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } -var createError = __nccwpck_require__(5226); + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); -/** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - */ -module.exports = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError( - 'Request failed with status code ' + response.status, - response.config, - null, - response.request, - response - )); + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4*i+3] = cdata[i] >>> 24; + out[4*i+2] = cdata[i] >>> 16; + out[4*i+1] = cdata[i] >>> 8; + out[4*i+0] = cdata[i]; } }; +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen+4), + i, j, amt, stride, dest, count, + origkeylen = keylen; -/***/ }), + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || + keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) + return -1; -/***/ 9812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); -"use strict"; + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; + crypto_hash_sha512(sha2pass, pass, passlen); -var utils = __nccwpck_require__(328); -var defaults = __nccwpck_require__(8190); + for (count = 1; keylen > 0; count++) { + countsalt[saltlen+0] = count >>> 24; + countsalt[saltlen+1] = count >>> 16; + countsalt[saltlen+2] = count >>> 8; + countsalt[saltlen+3] = count; -/** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data - */ -module.exports = function transformData(data, headers, fns) { - var context = this || defaults; - /*eslint no-param-reassign:0*/ - utils.forEach(fns, function transform(fn) { - data = fn.call(context, data, headers); - }); + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--;) + out[i] = tmpout[i]; - return data; + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; + } + + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; + } + keylen -= i; + } + + return 0; +}; + +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf }; /***/ }), -/***/ 8190: +/***/ 3682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -var utils = __nccwpck_require__(328); -var normalizeHeaderName = __nccwpck_require__(6240); -var enhanceError = __nccwpck_require__(1516); +var register = __nccwpck_require__(4670); +var addHook = __nccwpck_require__(5549); +var removeHook = __nccwpck_require__(6819); -var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' -}; +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); -function setContentTypeIfUnset(headers, value) { - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } +function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); } -function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = __nccwpck_require__(3454); - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = __nccwpck_require__(8104); - } - return adapter; +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; } -function stringifySafely(rawValue, parser, encoder) { - if (utils.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } +function HookCollection() { + var state = { + registry: {}, + }; + + var hook = register.bind(null, state); + bindApi(hook, state); - return (encoder || JSON.stringify)(rawValue); + return hook; } -var defaults = { - - transitional: { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }, - - adapter: getDefaultAdapter(), - - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - - if (utils.isFormData(data) || - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { - setContentTypeIfUnset(headers, 'application/json'); - return stringifySafely(data); - } - return data; - }], - - transformResponse: [function transformResponse(data) { - var transitional = this.transitional || defaults.transitional; - var silentJSONParsing = transitional && transitional.silentJSONParsing; - var forcedJSONParsing = transitional && transitional.forcedJSONParsing; - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; - - if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw enhanceError(e, this, 'E_JSON_PARSE'); - } - throw e; - } - } - } - - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - - maxContentLength: -1, - maxBodyLength: -1, - - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - } +var collectionHookDeprecationMessageDisplayed = false; +function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; } -}; - -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); + return HookCollection(); +} -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); -}); +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); -module.exports = defaults; +module.exports = Hook; +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook; +module.exports.Singular = Hook.Singular; +module.exports.Collection = Hook.Collection; /***/ }), -/***/ 4322: +/***/ 5549: /***/ ((module) => { -module.exports = { - "version": "0.23.0" -}; +module.exports = addHook; -/***/ }), +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } -/***/ 7065: -/***/ ((module) => { + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } -"use strict"; + if (kind === "after") { + hook = function (method, options) { + var result; + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_; + return orig(result, options); + }) + .then(function () { + return result; + }); + }; + } + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } -module.exports = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - return fn.apply(thisArg, args); - }; -}; + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} /***/ }), -/***/ 646: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(328); +/***/ 4670: +/***/ ((module) => { -function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); -} +module.exports = register; -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ -module.exports = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); } - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - - utils.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils.forEach(val, function parseValue(v) { - if (utils.isDate(v)) { - v = v.toISOString(); - } else if (utils.isObject(v)) { - v = JSON.stringify(v); - } - parts.push(encode(key) + '=' + encode(v)); - }); - }); + if (!options) { + options = {}; + } - serializedParams = parts.join('&'); + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); } - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); } - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; -}; + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} /***/ }), -/***/ 7189: +/***/ 6819: /***/ ((module) => { -"use strict"; +module.exports = removeHook; +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } -/** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL - */ -module.exports = function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; -}; + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); + + if (index === -1) { + return; + } + + state.registry[name].splice(index, 1); +} /***/ }), -/***/ 1545: +/***/ 9051: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const fs = __nccwpck_require__(7147) +const path = __nccwpck_require__(1017) -var utils = __nccwpck_require__(328); - -module.exports = ( - utils.isStandardBrowserEnv() ? - - // Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); +/* istanbul ignore next */ +const LCHOWN = fs.lchown ? 'lchown' : 'chown' +/* istanbul ignore next */ +const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } +/* istanbul ignore next */ +const needEISDIRHandled = fs.lchown && + !process.version.match(/v1[1-9]+\./) && + !process.version.match(/v10\.[6-9]/) - if (utils.isString(path)) { - cookie.push('path=' + path); - } +const lchownSync = (path, uid, gid) => { + try { + return fs[LCHOWNSYNC](path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } +} - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } +/* istanbul ignore next */ +const chownSync = (path, uid, gid) => { + try { + return fs.chownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } +} - if (secure === true) { - cookie.push('secure'); - } +/* istanbul ignore next */ +const handleEISDIR = + needEISDIRHandled ? (path, uid, gid, cb) => er => { + // Node prior to v10 had a very questionable implementation of + // fs.lchown, which would always try to call fs.open on a directory + // Fall back to fs.chown in those cases. + if (!er || er.code !== 'EISDIR') + cb(er) + else + fs.chown(path, uid, gid, cb) + } + : (_, __, ___, cb) => cb - document.cookie = cookie.join('; '); - }, +/* istanbul ignore next */ +const handleEISDirSync = + needEISDIRHandled ? (path, uid, gid) => { + try { + return lchownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'EISDIR') + throw er + chownSync(path, uid, gid) + } + } + : (path, uid, gid) => lchownSync(path, uid, gid) - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, +// fs.readdir could only accept an options object as of node v6 +const nodeVersion = process.version +let readdir = (path, options, cb) => fs.readdir(path, options, cb) +let readdirSync = (path, options) => fs.readdirSync(path, options) +/* istanbul ignore next */ +if (/^v4\./.test(nodeVersion)) + readdir = (path, options, cb) => fs.readdir(path, cb) - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : +const chown = (cpath, uid, gid, cb) => { + fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { + // Skip ENOENT error + cb(er && er.code !== 'ENOENT' ? er : null) + })) +} - // Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })() -); +const chownrKid = (p, child, uid, gid, cb) => { + if (typeof child === 'string') + return fs.lstat(path.resolve(p, child), (er, stats) => { + // Skip ENOENT error + if (er) + return cb(er.code !== 'ENOENT' ? er : null) + stats.name = child + chownrKid(p, stats, uid, gid, cb) + }) + if (child.isDirectory()) { + chownr(path.resolve(p, child.name), uid, gid, er => { + if (er) + return cb(er) + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + }) + } else { + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + } +} -/***/ }), -/***/ 1301: -/***/ ((module) => { +const chownr = (p, uid, gid, cb) => { + readdir(p, { withFileTypes: true }, (er, children) => { + // any error other than ENOTDIR or ENOTSUP means it's not readable, + // or doesn't exist. give up. + if (er) { + if (er.code === 'ENOENT') + return cb() + else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') + return cb(er) + } + if (er || !children.length) + return chown(p, uid, gid, cb) -"use strict"; + let len = children.length + let errState = null + const then = er => { + if (errState) + return + if (er) + return cb(errState = er) + if (-- len === 0) + return chown(p, uid, gid, cb) + } + children.forEach(child => chownrKid(p, child, uid, gid, then)) + }) +} -/** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ -module.exports = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); -}; +const chownrKidSync = (p, child, uid, gid) => { + if (typeof child === 'string') { + try { + const stats = fs.lstatSync(path.resolve(p, child)) + stats.name = child + child = stats + } catch (er) { + if (er.code === 'ENOENT') + return + else + throw er + } + } + if (child.isDirectory()) + chownrSync(path.resolve(p, child.name), uid, gid) -/***/ }), + handleEISDirSync(path.resolve(p, child.name), uid, gid) +} -/***/ 650: -/***/ ((module) => { +const chownrSync = (p, uid, gid) => { + let children + try { + children = readdirSync(p, { withFileTypes: true }) + } catch (er) { + if (er.code === 'ENOENT') + return + else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') + return handleEISDirSync(p, uid, gid) + else + throw er + } -"use strict"; + if (children && children.length) + children.forEach(child => chownrKidSync(p, child, uid, gid)) + return handleEISDirSync(p, uid, gid) +} -/** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ -module.exports = function isAxiosError(payload) { - return (typeof payload === 'object') && (payload.isAxiosError === true); -}; +module.exports = chownr +chownr.sync = chownrSync /***/ }), -/***/ 3608: +/***/ 4137: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var utils = __nccwpck_require__(328); - -module.exports = ( - utils.isStandardBrowserEnv() ? - - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; - - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - function resolveURL(url) { - var href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); - - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); - - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - return function isURLSameOrigin(requestURL) { - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && - parsed.host === originURL.host); - }; - })() : +const binding = __nccwpck_require__(4240); - // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })() -); +module.exports = binding.getCPUInfo; /***/ }), -/***/ 6240: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 8222: +/***/ ((module, exports, __nccwpck_require__) => { +/* eslint-env browser */ -var utils = __nccwpck_require__(328); +/** + * This is the web browser implementation of `debug()`. + */ -module.exports = function normalizeHeaderName(headers, normalizedName) { - utils.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); -}; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); -/***/ }), +/** + * Colors. + */ -/***/ 6455: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; -"use strict"; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } -var utils = __nccwpck_require__(328); + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } -// Headers whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -var ignoreDuplicateOf = [ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]; + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} /** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` + * Colorize log arguments if enabled. * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object + * @api public */ -module.exports = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - if (!headers) { return parsed; } +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - utils.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils.trim(line.substr(0, i)).toLowerCase(); - val = utils.trim(line.substr(i + 1)); + if (!this.useColors) { + return; + } - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - return parsed; -}; + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + args.splice(lastC, 0, c); +} -/***/ }), +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); -/***/ 4850: -/***/ ((module) => { +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} -"use strict"; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + return r; +} /** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. + * Localstorage attempts to return the localstorage. * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. * - * @param {Function} callback - * @returns {Function} + * @return {LocalStorage} + * @api private */ -module.exports = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = __nccwpck_require__(6243)(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } }; /***/ }), -/***/ 1632: +/***/ 6243: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ -var VERSION = (__nccwpck_require__(4322).version); +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(900); + createDebug.destroy = destroy; -var validators = {}; + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); -// eslint-disable-next-line func-names -['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { - validators[type] = function validator(thing) { - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; -}); + /** + * The currently active debug mode names, and names to skip. + */ -var deprecatedWarnings = {}; + createDebug.names = []; + createDebug.skips = []; -/** - * Transitional option validator - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * @returns {function} - */ -validators.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); - } + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - // eslint-disable-next-line func-names - return function(value, opt, opts) { - if (validator === false) { - throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : ''))); - } + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - // eslint-disable-next-line no-console - console.warn( - formatMessage( - opt, - ' has been deprecated since v' + version + ' and will be removed in the near future' - ) - ); - } + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - return validator ? validator(value, opt, opts) : true; - }; -}; + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; -/** - * Assert object's properties type - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - */ + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; -function assertOptions(options, schema, allowUnknown) { - if (typeof options !== 'object') { - throw new TypeError('options must be an object'); - } - var keys = Object.keys(options); - var i = keys.length; - while (i-- > 0) { - var opt = keys[i]; - var validator = schema[opt]; - if (validator) { - var value = options[opt]; - var result = value === undefined || validator(value, opt, options); - if (result !== true) { - throw new TypeError('option ' + opt + ' must be ' + result); - } - continue; - } - if (allowUnknown !== true) { - throw Error('Unknown option ' + opt); - } - } -} + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } -module.exports = { - assertOptions: assertOptions, - validators: validators -}; + const self = debug; + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -/***/ }), + args[0] = createDebug.coerce(args[0]); -/***/ 328: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } -"use strict"; + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -var bind = __nccwpck_require__(7065); + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -// utils is a library of generic helper functions non-specific to axios + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -var toString = Object.prototype.toString; + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ -function isArray(val) { - return toString.call(val) === '[object Array]'; -} + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } -/** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ -function isUndefined(val) { - return typeof val === 'undefined'; -} + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); -/** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); -} + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } -/** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ -function isArrayBuffer(val) { - return toString.call(val) === '[object ArrayBuffer]'; -} + return debug; + } -/** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ -function isFormData(val) { - return (typeof FormData !== 'undefined') && (val instanceof FormData); -} + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - var result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); - } - return result; -} + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; -/** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ -function isString(val) { - return typeof val === 'string'; -} + createDebug.names = []; + createDebug.skips = []; -/** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ -function isNumber(val) { - return typeof val === 'number'; -} + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; -/** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ -function isObject(val) { - return val !== null && typeof val === 'object'; -} + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -/** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ -function isPlainObject(val) { - if (toString.call(val) !== '[object Object]') { - return false; - } + namespaces = split[i].replace(/\*/g, '.*?'); - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; -} + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -/** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ -function isDate(val) { - return toString.call(val) === '[object Date]'; -} + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } -/** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -function isFile(val) { - return toString.call(val) === '[object File]'; -} + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } -/** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ -function isBlob(val) { - return toString.call(val) === '[object Blob]'; -} + let i; + let len; -/** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -function isFunction(val) { - return toString.call(val) === '[object Function]'; -} + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } -/** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ -function isStream(val) { - return isObject(val) && isFunction(val.pipe); -} + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } -/** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -function isURLSearchParams(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; -} + return false; + } -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ -function trim(str) { - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); -} + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ -function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || - navigator.product === 'NativeScript' || - navigator.product === 'NS')) { - return false; - } - return ( - typeof window !== 'undefined' && - typeof document !== 'undefined' - ); -} + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ -function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } + createDebug.enable(createDebug.load()); - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } + return createDebug; } -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - var result = {}; - function assignValue(val, key) { - if (isPlainObject(result[key]) && isPlainObject(val)) { - result[key] = merge(result[key], val); - } else if (isPlainObject(val)) { - result[key] = merge({}, val); - } else if (isArray(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } +module.exports = setup; - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - return result; -} -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ -function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }); - return a; -} +/***/ }), + +/***/ 8237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -function stripBOM(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; -} -module.exports = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isPlainObject: isPlainObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - extend: extend, - trim: trim, - stripBOM: stripBOM -}; +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(8222); +} else { + module.exports = __nccwpck_require__(4874); +} /***/ }), -/***/ 5447: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 4874: +/***/ ((module, exports, __nccwpck_require__) => { +/** + * Module dependencies. + */ -var crypto_hash_sha512 = (__nccwpck_require__(8729).lowlevel.crypto_hash); +const tty = __nccwpck_require__(6224); +const util = __nccwpck_require__(3837); -/* - * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a - * result, it retains the original copyright and license. The two files are - * under slightly different (but compatible) licenses, and are here combined in - * one file. - * - * Credit for the actual porting work goes to: - * Devi Mandiri +/** + * This is the Node.js implementation of `debug()`. */ -/* - * The Blowfish portions are under the following license: - * - * Blowfish block cipher for OpenBSD - * Copyright 1997 Niels Provos - * All rights reserved. +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(9318); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = __nccwpck_require__(6243)(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + + +/***/ }), + +/***/ 8932: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'Deprecation'; + } + +} + +exports.Deprecation = Deprecation; + + +/***/ }), + +/***/ 4305: +/***/ ((module, exports, __nccwpck_require__) => { + +//Based on follow-redirects v0.0.x + +var nativeHttps = __nccwpck_require__(5687), + nativeHttp = __nccwpck_require__(3685), + url = __nccwpck_require__(7310), + utils = __nccwpck_require__(4967); + +var maxRedirects = module.exports.maxRedirects = 5; + +var protocols = { + https: nativeHttps, + http: nativeHttp +}; + +for (var protocol in protocols) { + var h = function() {}; + h.prototype = protocols[protocol]; + h = new h(); + + h.request = function(h) { + return function(options, callback, redirectOptions) { + + redirectOptions = redirectOptions || {}; + + var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects; + + var redirect = utils.extend({ + count: 0, + max: max, + clientRequest: null, + userCallback: callback + }, redirectOptions); + + if (redirect.count > redirect.max) { + var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.'); + redirect.clientRequest.emit('error', err); + return redirect.clientRequest; + } + + redirect.count++; + + var reqUrl; + if (typeof options === 'string') { + reqUrl = options; + } else { + reqUrl = url.format(utils.extend({ + protocol: protocol + }, options)); + } + + var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect)); + + if (!redirect.clientRequest) redirect.clientRequest = clientRequest; + + function redirectCallback(reqUrl, redirect) { + return function(res) { + if (res.statusCode < 300 || res.statusCode > 399) { + return redirect.userCallback(res); + } + + if (!('location' in res.headers)) { + return redirect.userCallback(res); + } + + var redirectUrl = url.resolve(reqUrl, res.headers.location); + + var proto = url.parse(redirectUrl).protocol; + proto = proto.substr(0, proto.length - 1); + return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect); + }; + } + + return clientRequest; + }; + }(h); + + // see https://github.com/joyent/node/blob/master/lib/http.js#L1623 + h.get = function(h) { + return function(options, cb, redirectOptions) { + var req = h.request(options, cb, redirectOptions); + req.end(); + return req; + }; + }(h); + + module.exports[protocol] = h; +} + + +/***/ }), + +/***/ 3855: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = HttpDuplex; + +var util = __nccwpck_require__(3837), + stream = __nccwpck_require__(1642); + +util.inherits(HttpDuplex, stream.Duplex); + +function HttpDuplex(req, res, options) { + var self = this; + + if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options); + + stream.Duplex.call(self, options); + self._output = null; + + self.connect(req, res); +} + +HttpDuplex.prototype.connect = function(req, res) { + var self = this; + self.req = req; + self._output = res; + self.emit('response', res); + + res.on('data', function(c) { + if (!self.push(c)) self._output.pause(); + }); + res.on('end', function() { + self.push(null); + }); +}; + +HttpDuplex.prototype._read = function(n) { + if (this._output) this._output.resume(); +}; + +HttpDuplex.prototype._write = function(chunk, encoding, cb) { + this.req.write(chunk, encoding); + cb(); +}; + +HttpDuplex.prototype.end = function(chunk, encoding, cb) { + this._output.socket.destroySoon(); + return this.req.end(chunk, encoding, cb); +}; + +HttpDuplex.prototype.destroy = function() { + this.req.destroy(); + this._output.socket.destroy(); +}; + +HttpDuplex.prototype.destroySoon = function() { + this.req.destroy(); + this._output.socket.destroy(); +}; + + +/***/ }), + +/***/ 6042: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var querystring = __nccwpck_require__(3477), + http = __nccwpck_require__(4305), + fs = __nccwpck_require__(7147), + path = __nccwpck_require__(1017), + url = __nccwpck_require__(7310), + ssh = __nccwpck_require__(7964), + HttpDuplex = __nccwpck_require__(3855), + debug = __nccwpck_require__(8237)('modem'), + utils = __nccwpck_require__(4967), + util = __nccwpck_require__(3837), + splitca = __nccwpck_require__(9798), + os = __nccwpck_require__(2037), + isWin = os.type() === 'Windows_NT', + stream = __nccwpck_require__(2781); + +var defaultOpts = function () { + var host; + var opts = {}; + + if (!process.env.DOCKER_HOST) { + // Windows socket path: //./pipe/docker_engine ( Windows 10 ) + // Linux & Darwin socket path is /var/run/docker.sock when running system-wide, + // or $HOME/.docker/run/docker.sock in new Docker Desktop installs. + opts.socketPath = isWin ? '//./pipe/docker_engine' : findDefaultUnixSocket; + } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) { + // Strip off unix://, fall back to default if unix:// was passed without a path + opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket; + } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) { + // Strip off npipe://, fall back to default of //./pipe/docker_engine if + // npipe:// was passed without a path + opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine'; + } else { + var hostStr = process.env.DOCKER_HOST; + if (hostStr.indexOf('\/\/') < 0) { + hostStr = 'tcp://' + hostStr; + } + try { + host = new url.URL(hostStr); + } catch (err) { + throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234'); + } + + opts.port = host.port; + + if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') { + opts.protocol = 'https'; + } else if (host.protocol === 'ssh:') { + opts.protocol = 'ssh'; + opts.username = host.username; + opts.sshOptions = { + agent: process.env.SSH_AUTH_SOCK, + } + } else { + opts.protocol = 'http'; + } + + if (process.env.DOCKER_PATH_PREFIX) { + opts.pathPrefix = process.env.DOCKER_PATH_PREFIX; + } + else { + opts.pathPrefix = '/'; + } + + opts.host = host.hostname; + + if (process.env.DOCKER_CERT_PATH) { + opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem')); + opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem')); + opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem')); + } + + if (process.env.DOCKER_CLIENT_TIMEOUT) { + opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); + } + } + + return opts; +}; + +var findDefaultUnixSocket = function () { + return new Promise(function (resolve) { + var userDockerSocket = path.join(os.homedir(), '.docker', 'run', 'docker.sock'); + fs.access(userDockerSocket, function (err) { + if (err) resolve('/var/run/docker.sock'); + else resolve(userDockerSocket); + }) + }); +} + + +var Modem = function (options) { + var optDefaults = defaultOpts(); + var opts = Object.assign({}, optDefaults, options); + + this.host = opts.host; + + if (!this.host) { + this.socketPath = opts.socketPath; + } + + this.port = opts.port; + this.pathPrefix = opts.pathPrefix; + this.username = opts.username; + this.password = opts.password; + this.version = opts.version; + this.key = opts.key; + this.cert = opts.cert; + this.ca = opts.ca; + this.timeout = opts.timeout; + this.connectionTimeout = opts.connectionTimeout; + this.checkServerIdentity = opts.checkServerIdentity; + this.agent = opts.agent; + this.headers = opts.headers || {}; + this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); + //retrocompabitlity + if (this.sshOptions.agentForward === undefined) { + this.sshOptions.agentForward = opts.agentForward; + } + + if (this.key && this.cert && this.ca) { + this.protocol = 'https'; + } + this.protocol = opts.protocol || this.protocol || 'http'; +}; + +Modem.prototype.dial = function (options, callback) { + var opts, address, data; + + if (options.options) { + opts = options.options; + } + + // Prevent credentials from showing up in URL + if (opts && opts.authconfig) { + delete opts.authconfig; + } + + // Prevent abortsignal from showing up in the URL + if (opts && opts.abortSignal) { + delete opts.abortSignal; + } + + if (this.version) { + options.path = '/' + this.version + options.path; + } + + if (this.host) { + var parsed = url.parse(this.host); + address = url.format({ + protocol: parsed.protocol || this.protocol, + hostname: parsed.hostname || this.host, + port: this.port, + pathname: parsed.pathname || this.pathPrefix, + }); + address = url.resolve(address, options.path); + } else { + address = options.path; + } + + if (options.path.indexOf('?') !== -1) { + if (opts && Object.keys(opts).length > 0) { + address += this.buildQuerystring(opts._query || opts); + } else { + address = address.substring(0, address.length - 1); + } + } + + var optionsf = { + path: address, + method: options.method, + headers: options.headers || Object.assign({}, this.headers), + key: this.key, + cert: this.cert, + ca: this.ca + }; + + + if (this.checkServerIdentity) { + optionsf.checkServerIdentity = this.checkServerIdentity; + } + + if (this.agent) { + optionsf.agent = this.agent; + } + + if (options.authconfig) { + optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 || + Buffer.from(JSON.stringify(options.authconfig)).toString('base64').replace(/\+/g, "-").replace(/\//g, "_"); + } + + if (options.registryconfig) { + optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 || + Buffer.from(JSON.stringify(options.registryconfig)).toString('base64'); + } + + if (options.abortSignal) { + optionsf.signal = options.abortSignal; + } + + if (options.file) { + if (typeof options.file === 'string') { + data = fs.createReadStream(path.resolve(options.file)); + } else { + data = options.file; + } + optionsf.headers['Content-Type'] = 'application/tar'; + } else if (opts && options.method === 'POST') { + data = JSON.stringify(opts._body || opts); + if (options.allowEmpty) { + optionsf.headers['Content-Type'] = 'application/json'; + } else { + if (data !== '{}' && data !== '""') { + optionsf.headers['Content-Type'] = 'application/json'; + } else { + data = undefined; + } + } + } + + if (typeof data === 'string') { + optionsf.headers['Content-Length'] = Buffer.byteLength(data); + } else if (Buffer.isBuffer(data) === true) { + optionsf.headers['Content-Length'] = data.length; + } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) { + optionsf.headers['Transfer-Encoding'] = 'chunked'; + } + + if (options.hijack) { + optionsf.headers.Connection = 'Upgrade'; + optionsf.headers.Upgrade = 'tcp'; + } + + if (this.socketPath) { + // SocketPath may be a function that can return a promise: + this.getSocketPath().then((socketPath) => { + optionsf.socketPath = socketPath; + this.buildRequest(optionsf, options, data, callback); + }); + } else { + var urlp = url.parse(address); + optionsf.hostname = urlp.hostname; + optionsf.port = urlp.port; + optionsf.path = urlp.path; + + this.buildRequest(optionsf, options, data, callback); + } +}; + +Modem.prototype.getSocketPath = function () { + if (!this.socketPath) return; + if (this.socketPathCache) return Promise.resolve(this.socketPathCache); + + var socketPathValue = typeof this.socketPath === 'function' + ? this.socketPath() : this.socketPath; + + this.socketPathCache = socketPathValue; + + return Promise.resolve(socketPathValue); +} + +Modem.prototype.buildRequest = function (options, context, data, callback) { + var self = this; + var connectionTimeoutTimer; + var finished = false; + + var opts = self.protocol === 'ssh' ? Object.assign(options, { + agent: ssh(Object.assign({}, self.sshOptions, { + 'host': self.host, + 'port': self.port, + 'username': self.username, + 'password': self.password, + })), + protocol: 'http:', + }) : options; + + var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { }); + + debug('Sending: %s', util.inspect(options, { + showHidden: true, + depth: null + })); + + if (self.connectionTimeout) { + connectionTimeoutTimer = setTimeout(function () { + debug('Connection Timeout of %s ms exceeded', self.connectionTimeout); + req.abort(); + }, self.connectionTimeout); + } + + if (self.timeout) { + req.on('socket', function (socket) { + socket.setTimeout(self.timeout); + socket.on('timeout', function () { + debug('Timeout of %s ms exceeded', self.timeout); + req.abort(); + }); + }); + } + + if (context.hijack === true) { + clearTimeout(connectionTimeoutTimer); + req.on('upgrade', function (res, sock, head) { + if (finished === false) { + finished = true; + return callback(null, sock); + } + }); + } + + req.on('connect', function () { + clearTimeout(connectionTimeoutTimer); + }); + + req.on('disconnect', function () { + clearTimeout(connectionTimeoutTimer); + }); + + req.on('response', function (res) { + clearTimeout(connectionTimeoutTimer); + if (context.isStream === true) { + if (finished === false) { + finished = true; + self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback); + } + } else { + // The native 'request' method only handles aborting during the request lifecycle not the response lifecycle. + // We need to make the response stream abortable so that it's destroyed with an error on abort and then + // it triggers the request 'error' event + if (options.signal != null) { + stream.addAbortSignal(options.signal, res) + } + var chunks = []; + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + var buffer = Buffer.concat(chunks); + var result = buffer.toString(); + + debug('Received: %s', result); + + var json = utils.parseJSON(result) || buffer; + if (finished === false) { + finished = true; + self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback); + } + }); + } + }); + + req.on('error', function (error) { + clearTimeout(connectionTimeoutTimer); + if (finished === false) { + finished = true; + self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback); + } + }); + + if (typeof data === 'string' || Buffer.isBuffer(data)) { + req.write(data); + } else if (data) { + data.on('error', function (error) { + req.destroy(error); + }); + data.pipe(req); + } + + if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) { + req.end(); + } +}; + +Modem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) { + if (err) return cb(err, null); + + if (statusCodes[res.statusCode] !== true) { + getCause(isStream, res, json, function (err, cause) { + if (err) { + return cb(err, null); + } + var msg = new Error( + '(HTTP code ' + res.statusCode + ') ' + + (statusCodes[res.statusCode] || 'unexpected') + ' - ' + + (cause.message || cause) + ' ' + ); + msg.reason = statusCodes[res.statusCode]; + msg.statusCode = res.statusCode; + msg.json = json; + cb(msg, null); + }); + } else { + if (openStdin) { + cb(null, new HttpDuplex(req, res)); + } else if (isStream) { + cb(null, res); + } else { + cb(null, json); + } + } + + function getCause(isStream, res, json, callback) { + var chunks = ''; + var done = false; + + if (isStream) { + res.on('data', function (chunk) { + chunks += chunk; + }); + res.on('error', function (err) { + handler(err, null); + }); + res.on('end', function () { + handler(null, utils.parseJSON(chunks) || chunks) + }); + } else { + callback(null, json); + } + + function handler(err, data) { + if (done === false) { + if (err) { + callback(err); + } else { + callback(null, data); + } + } + done = true; + } + } +}; + +Modem.prototype.demuxStream = function (streama, stdout, stderr) { + var nextDataType = null; + var nextDataLength = null; + var buffer = Buffer.from(''); + function processData(data) { + if (data) { + buffer = Buffer.concat([buffer, data]); + } + if (!nextDataType) { + if (buffer.length >= 8) { + var header = bufferSlice(8); + nextDataType = header.readUInt8(0); + nextDataLength = header.readUInt32BE(4); + // It's possible we got a "data" that contains multiple messages + // Process the next one + processData(); + } + } else { + if (buffer.length >= nextDataLength) { + var content = bufferSlice(nextDataLength); + if (nextDataType === 1) { + stdout.write(content); + } else { + stderr.write(content); + } + nextDataType = null; + // It's possible we got a "data" that contains multiple messages + // Process the next one + processData(); + } + } + } + + function bufferSlice(end) { + var out = buffer.subarray(0, end); + buffer = Buffer.from(buffer.subarray(end, buffer.length)); + return out; + } + + streama.on('data', processData); +}; + +Modem.prototype.followProgress = function (streama, onFinished, onProgress) { + var buf = ''; + var output = []; + var finished = false; + + streama.on('data', onStreamEvent); + streama.on('error', onStreamError); + streama.on('end', onStreamEnd); + streama.on('close', onStreamEnd); + + function onStreamEvent(data) { + buf += data.toString(); + pump(); + + function pump() { + var pos; + while ((pos = buf.indexOf('\n')) >= 0) { + if (pos == 0) { + buf = buf.slice(1); + continue; + } + processLine(buf.slice(0, pos)); + buf = buf.slice(pos + 1); + } + } + + function processLine(line) { + if (line[line.length - 1] == '\r') line = line.substr(0, line.length - 1); + if (line.length > 0) { + var obj = JSON.parse(line); + output.push(obj); + if (onProgress) { + onProgress(obj); + } + } + } + }; + + function onStreamError(err) { + finished = true; + streama.removeListener('data', onStreamEvent); + streama.removeListener('error', onStreamError); + streama.removeListener('end', onStreamEnd); + streama.removeListener('close', onStreamEnd); + onFinished(err, output); + } + + function onStreamEnd() { + if (!finished) onFinished(null, output); + finished = true; + } +}; + +Modem.prototype.buildQuerystring = function (opts) { + var clone = {}; + + // serialize map and array values as JSON strings, else querystring truncates. + // 't' and 'extrahosts' can be arrays but need special treatment so that they're + // passed as multiple qs parameters instead of JSON values. + Object.keys(opts).map(function (key, i) { + if (opts[key] + && typeof opts[key] === 'object' + && !['t', 'extrahosts'].includes(key) + ) { + clone[key] = JSON.stringify(opts[key]); + } else { + clone[key] = opts[key]; + } + }); + + return querystring.stringify(clone); +}; + +module.exports = Modem; + + +/***/ }), + +/***/ 7964: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Client = (__nccwpck_require__(5869).Client), + http = __nccwpck_require__(3685); + +module.exports = function (opt) { + var conn = new Client(); + var agent = new http.Agent(); + + agent.createConnection = function (options, fn) { + try { + conn.once('ready', function () { + conn.exec('docker system dial-stdio', function (err, stream) { + if (err) { + handleError(err); + } + + fn(null, stream); + + stream.addListener('error', (err) => { + handleError(err); + }); + stream.once('close', () => { + conn.end(); + agent.destroy(); + }); + }); + }).on('error', (err) => { + handleError(err); + }) + .connect(opt); + conn.once('end', () => agent.destroy()); + + } catch (err) { + handleError(err); + } + }; + + function handleError(err) { + conn.end(); + agent.destroy(); + throw err; + } + + return agent; +}; + + +/***/ }), + +/***/ 4967: +/***/ ((module) => { + +// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js + +var arr = []; +var each = arr.forEach; +var slice = arr.slice; + +module.exports.extend = function(obj) { + each.call(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }); + return obj; +}; + +module.exports.parseJSON = function(s) { + try { + return JSON.parse(s); + } catch (e) { + return null; + } +}; + + +/***/ }), + +/***/ 5004: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents a config + * @param {Object} modem docker-modem + * @param {String} id Config's id + */ +var Config = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Config.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Config.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/configs/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'config not found', + 500: 'server error', + 503: 'node is not part of a swarm' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update a config. + * + * @param {object} opts + * @param {function} callback + */ +Config.prototype.update = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/configs/' + this.id + '/update?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'config not found', + 500: 'server error', + 503: 'node is not part of a swarm' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Removes the config + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Config.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/configs/' + this.id, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'config not found', + 500: 'server error', + 503: 'node is not part of a swarm' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + + +module.exports = Config; + + +/***/ }), + +/***/ 5815: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var extend = (__nccwpck_require__(1604).extend), + Exec = __nccwpck_require__(3149), + util = __nccwpck_require__(1604); + +/** + * Represents a Container + * @param {Object} modem docker-modem + * @param {String} id Container's ID + */ +var Container = function(modem, id) { + this.modem = modem; + this.id = id; + + this.defaultOptions = { + top: {}, + start: {}, + commit: {}, + stop: {}, + pause: {}, + unpause: {}, + restart: {}, + resize: {}, + attach: {}, + remove: {}, + copy: {}, + kill: {}, + exec: {}, + rename: {}, + log: {}, + stats: {}, + getArchive: {}, + infoArchive: {}, + putArchive: {}, + update: {}, + wait: {} + }; +}; + +Container.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if supplied will query Docker. + * @return {Object} ID only and only if callback isn't supplied. + */ +Container.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/json?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Rename + * @param {Object} opts Rename options + * @param {Function} callback Callback + */ +Container.prototype.rename = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.rename); + + var optsf = { + path: '/containers/' + this.id + '/rename?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update + * @param {Object} opts Update options + * @param {Function} callback Callback + */ +Container.prototype.update = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.update); + + var optsf = { + path: '/containers/' + this.id + '/update', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 400: 'bad parameter', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Top + * @param {Object} opts like 'ps_args' (optional) + * @param {Function} callback Callback + */ +Container.prototype.top = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.top); + + var optsf = { + path: '/containers/' + this.id + '/top?', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Containers changes + * @param {Object} Options + * @param {Function} callback Callback + */ +Container.prototype.changes = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/changes', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Checkpoints list + * @param {Object} opts List checkpoints options (optional) + * @param {Function} callback Callback + */ +Container.prototype.listCheckpoint = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/checkpoints?', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Delete checkpoint + * @param {Object} opts Delete checkpoint options (optional) + * @param {Function} callback Callback + */ +Container.prototype.deleteCheckpoint = function(checkpoint, opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Create checkpoint + * @param {Object} opts Create checkpoint options (optional) + * @param {Function} callback Callback + */ +Container.prototype.createCheckpoint = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/checkpoints', + method: 'POST', + abortSignal: args.opts.abortSignal, + allowEmpty: true, + statusCodes: { + 200: true, //unofficial, but proxies may return it + 201: true, + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Export + * @param {Object} opts Options (optional) + * @param {Function} callback Callback with the octet-stream. + */ +Container.prototype.export = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/' + this.id + '/export', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Start + * @param {Object} opts Container start options (optional) + * @param {Function} callback Callback + */ +Container.prototype.start = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.start); + + var optsf = { + path: '/containers/' + this.id + '/start?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 304: 'container already started', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Pause + * @param {Object} opts Pause options (optional) + * @param {Function} callback Callback + */ +Container.prototype.pause = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.pause); + + var optsf = { + path: '/containers/' + this.id + '/pause', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Unpause + * @param {Object} opts Unpause options (optional) + * @param {Function} callback Callback + */ +Container.prototype.unpause = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.unpause); + + var optsf = { + path: '/containers/' + this.id + '/unpause', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Setup an exec call to a running container + * + * @param {object} opts + * @param {function} callback + */ +Container.prototype.exec = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.exec); + + var optsf = { + path: '/containers/' + this.id + '/exec', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 404: 'no such container', + 409: 'container stopped/paused', + 500: 'server error' + }, + options: args.opts + }; + + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(new Exec(self.modem, data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, new Exec(self.modem, data.Id)); + }); + } +}; + +/** + * Commit + * @param {Object} opts Commit options like 'Hostname' (optional) + * @param {Function} callback Callback + */ +Container.prototype.commit = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.commit); + + args.opts.container = this.id; + + var optsf = { + path: '/commit?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Stop + * @param {Object} opts Container stop options, like 't' (optional) + * @param {Function} callback Callback + */ +Container.prototype.stop = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.stop); + + var optsf = { + path: '/containers/' + this.id + '/stop?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 304: 'container already stopped', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Restart + * @param {Object} opts Container restart options, like 't' (optional) + * @param {Function} callback Callback + */ +Container.prototype.restart = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.restart); + + var optsf = { + path: '/containers/' + this.id + '/restart?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Kill + * @param {Object} opts Container kill options, like 'signal' (optional) + * @param {Function} callback Callback + */ +Container.prototype.kill = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.kill); + + var optsf = { + path: '/containers/' + this.id + '/kill?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Container resize + * @param {[type]} opts Resize options. (optional) + * @param {Function} callback Callback + */ +Container.prototype.resize = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.resize); + + var optsf = { + path: '/containers/' + this.id + '/resize?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Attach + * @param {Object} opts Attach options, like 'logs' (optional) + * @param {Function} callback Callback with stream. + */ +Container.prototype.attach = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.attach); + + var optsf = { + path: '/containers/' + this.id + '/attach?', + method: 'POST', + abortSignal: args.opts.abortSignal, + isStream: true, + hijack: args.opts.hijack, + openStdin: args.opts.stdin, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, stream) { + if (err) { + return reject(err); + } + resolve(stream); + }); + }); + } else { + this.modem.dial(optsf, function(err, stream) { + args.callback(err, stream); + }); + } +}; + +/** + * Waits for a container to end. + * @param {[type]} opts Container wait options, like condition. (optional) + * @param {Function} callback Callback + */ +Container.prototype.wait = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.wait); + + var optsf = { + path: '/containers/' + this.id + '/wait?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Removes a container + * @param {Object} opts Remove options, like 'force' (optional) + * @param {Function} callback Callback + */ +Container.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.remove); + + var optsf = { + path: '/containers/' + this.id + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 400: 'bad parameter', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Copy (WARNING: DEPRECATED since RAPI v1.20) + * @param {Object} opts Copy options, like 'Resource' (optional) + * @param {Function} callback Callback with stream. + */ +Container.prototype.copy = function(opts, callback) { + var self = this; + console.log('container.copy is deprecated since Docker v1.8.x'); + var args = util.processArgs(opts, callback, this.defaultOptions.copy); + + var optsf = { + path: '/containers/' + this.id + '/copy', + method: 'POST', + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * getArchive + * @param {Object} opts Archive options, like 'path' + * @param {Function} callback Callback with stream. + */ +Container.prototype.getArchive = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.getArchive); + + var optsf = { + path: '/containers/' + this.id + '/archive?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: 'client error, bad parameters', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * infoArchive + * @param {Object} opts Archive options, like 'path' + * @param {Function} callback Callback with stream. + */ +Container.prototype.infoArchive = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive); + + var optsf = { + path: '/containers/' + this.id + '/archive?', + method: 'HEAD', + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: 'client error, bad parameters', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * putArchive + * @param {Object} opts Archive options, like 'path' + * @param {Function} callback Callback with stream. + */ +Container.prototype.putArchive = function(file, opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.putArchive); + + var optsf = { + path: '/containers/' + this.id + '/archive?', + method: 'PUT', + file: file, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'client error, bad parameters', + 403: 'client error, permission denied', + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Container logs + * @param {Object} opts Logs options. (optional) + * @param {Function} callback Callback with data + */ +Container.prototype.logs = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.log); + + var optsf = { + path: '/containers/' + this.id + '/logs?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Container stats + * @param {Object} opts Stats options. (optional) + * @param {Function} callback Callback with data + */ +Container.prototype.stats = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.stats); + var isStream = true; + if (args.opts.stream === false) { + isStream = false; + } + var optsf = { + path: '/containers/' + this.id + '/stats?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: isStream, + statusCodes: { + 200: true, + 404: 'no such container', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +module.exports = Container; + + +/***/ }), + +/***/ 4571: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var EventEmitter = (__nccwpck_require__(2361).EventEmitter), + Modem = __nccwpck_require__(6042), + Container = __nccwpck_require__(5815), + Image = __nccwpck_require__(6689), + Volume = __nccwpck_require__(4877), + Network = __nccwpck_require__(9780), + Service = __nccwpck_require__(8866), + Plugin = __nccwpck_require__(6606), + Secret = __nccwpck_require__(9934), + Config = __nccwpck_require__(5004), + Task = __nccwpck_require__(1385), + Node = __nccwpck_require__(2297), + Exec = __nccwpck_require__(3149), + util = __nccwpck_require__(1604), + extend = util.extend; + +var Docker = function(opts) { + if (!(this instanceof Docker)) return new Docker(opts); + + var plibrary = global.Promise; + + if (opts && opts.Promise) { + plibrary = opts.Promise; + + if (Object.keys(opts).length === 1) { + opts = undefined; + } + } + + if (opts && opts.modem) { + this.modem = opts.modem; + } else { + this.modem = new Modem(opts); + } + this.modem.Promise = plibrary; +}; + +/** + * Creates a new container + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createContainer = function(opts, callback) { + var self = this; + var optsf = { + path: '/containers/create?', + method: 'POST', + options: opts, + authconfig: opts.authconfig, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 400: 'bad parameter', + 404: 'no such container', + 406: 'impossible to attach', + 500: 'server error' + } + }; + + delete opts.authconfig; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getContainer(data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return callback(err, data); + callback(err, self.getContainer(data.Id)); + }); + } +}; + +/** + * Creates a new image + * @param {Object} auth Authentication (optional) + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createImage = function(auth, opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + opts = auth; + auth = opts.authconfig || undefined; + } else if (!callback && !opts) { + opts = auth; + auth = opts.authconfig; + } + + var optsf = { + path: '/images/create?', + method: 'POST', + options: opts, + authconfig: auth, + abortSignal: opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Load image + * @param {String} file File + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.loadImage = function(file, opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + opts = null; + } + + var optsf = { + path: '/images/load?', + method: 'POST', + options: opts, + file: file, + abortSignal: opts && opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Import image from a tar archive + * @param {String} file File + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.importImage = function(file, opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + opts = undefined; + } + + if (!opts) + opts = {}; + + opts.fromSrc = '-'; + + var optsf = { + path: '/images/create?', + method: 'POST', + options: opts, + file: file, + abortSignal: opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Verifies auth + * @param {Object} opts Options + * @param {Function} callback Callback + */ +Docker.prototype.checkAuth = function(opts, callback) { + var self = this; + var optsf = { + path: '/auth', + method: 'POST', + options: opts, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Builds an image + * @param {String} file File + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.buildImage = function(file, opts, callback) { + var self = this; + + if (!callback && typeof opts === 'function') { + callback = opts; + opts = null; + } + + var optsf = { + path: '/build?', + method: 'POST', + file: undefined, + options: opts, + abortSignal: opts && opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (opts) { + if (opts.registryconfig) { + optsf.registryconfig = optsf.options.registryconfig; + delete optsf.options.registryconfig; + } + + //undocumented? + if (opts.authconfig) { + optsf.authconfig = optsf.options.authconfig; + delete optsf.options.authconfig; + } + } + + if (callback === undefined) { + return new self.modem.Promise(function(resolve, reject) { + util.prepareBuildContext(file, (ctx) => { + optsf.file = ctx; + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + }); + } else { + util.prepareBuildContext(file, (ctx) => { + optsf.file = ctx; + self.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + }) + } +}; + +/** + * Fetches a Container by ID + * @param {String} id Container's ID + */ +Docker.prototype.getContainer = function(id) { + return new Container(this.modem, id); +}; + +/** + * Fetches an Image by name + * @param {String} name Image's name + */ +Docker.prototype.getImage = function(name) { + return new Image(this.modem, name); +}; + +/** + * Fetches a Volume by name + * @param {String} name Volume's name + */ +Docker.prototype.getVolume = function(name) { + return new Volume(this.modem, name); +}; + +/** + * Fetches a Plugin by name + * @param {String} name Volume's name + */ +Docker.prototype.getPlugin = function(name, remote) { + return new Plugin(this.modem, name, remote); +}; + +/** + * Fetches a Service by id + * @param {String} id Services's id + */ +Docker.prototype.getService = function(id) { + return new Service(this.modem, id); +}; + +/** + * Fetches a Task by id + * @param {String} id Task's id + */ +Docker.prototype.getTask = function(id) { + return new Task(this.modem, id); +}; + +/** + * Fetches Node by id + * @param {String} id Node's id + */ +Docker.prototype.getNode = function(id) { + return new Node(this.modem, id); +}; + +/** + * Fetches a Network by id + * @param {String} id network's id + */ +Docker.prototype.getNetwork = function(id) { + return new Network(this.modem, id); +}; + +/** + * Fetches a Secret by id + * @param {String} id network's id + */ +Docker.prototype.getSecret = function(id) { + return new Secret(this.modem, id); +}; + +/** + * Fetches a Config by id + * @param {String} id network's id + */ +Docker.prototype.getConfig = function(id) { + return new Config(this.modem, id); +}; + +/** + * Fetches an Exec instance by ID + * @param {String} id Exec instance's ID + */ +Docker.prototype.getExec = function(id) { + return new Exec(this.modem, id); +}; + +/** + * Lists containers + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.listContainers = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/json?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists images + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.listImages = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/images/json?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Get images + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.getImages = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/images/get?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists Services + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listServices = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/services?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists Nodes + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listNodes = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/nodes?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 404: 'no such node', + 500: 'server error', + 503: 'node is not part of a swarm', + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists Tasks + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listTasks = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/tasks?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Creates a new secret + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createSecret = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self = this; + var optsf = { + path: '/secrets/create?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 406: 'server error or node is not part of a swarm', + 409: 'name conflicts with an existing object', + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getSecret(data.ID)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getSecret(data.ID)); + }); + } +}; + + +/** + * Creates a new config + * @param {Object} opts Config options + * @param {Function} callback Callback + */ +Docker.prototype.createConfig = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self = this; + var optsf = { + path: '/configs/create?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 406: 'server error or node is not part of a swarm', + 409: 'name conflicts with an existing object', + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getConfig(data.ID)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getConfig(data.ID)); + }); + } +}; + + +/** + * Lists secrets + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listSecrets = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/secrets?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Lists configs + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listConfigs = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/configs?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Creates a new plugin + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createPlugin = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: '/plugins/create?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getPlugin(args.opts.name)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getPlugin(args.opts.name)); + }); + } +}; + + +/** + * Lists plugins + * @param {Object} opts + * @param {Function} callback Callback + */ +Docker.prototype.listPlugins = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune images + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneImages = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/images/prune?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune builder + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneBuilder = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/build/prune', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune containers + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneContainers = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/containers/prune?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune volumes + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneVolumes = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/volumes/prune?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Prune networks + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.pruneNetworks = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks/prune?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Creates a new volume + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createVolume = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: '/volumes/create?', + method: 'POST', + allowEmpty: true, + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getVolume(data.Name)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getVolume(data.Name)); + }); + } +}; + +/** + * Creates a new service + * @param {Object} auth + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createService = function(auth, opts, callback) { + if (!callback && typeof opts === 'function') { + callback = opts; + opts = auth; + auth = opts.authconfig || undefined; + } else if (!opts && !callback) { + opts = auth; + } + + + var self = this; + var optsf = { + path: '/services/create', + method: 'POST', + options: opts, + authconfig: auth, + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 500: 'server error' + } + }; + + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getService(data.ID || data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return callback(err, data); + callback(err, self.getService(data.ID || data.Id)); + }); + } +}; + +/** + * Lists volumes + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.listVolumes = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/volumes?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Creates a new network + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Docker.prototype.createNetwork = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: '/networks/create?', + method: 'POST', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 404: 'driver not found', + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self.getNetwork(data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self.getNetwork(data.Id)); + }); + } +}; + +/** + * Lists networks + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.listNetworks = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Search images + * @param {Object} opts Options + * @param {Function} callback Callback + */ +Docker.prototype.searchImages = function(opts, callback) { + var self = this; + var optsf = { + path: '/images/search?', + method: 'GET', + options: opts, + authconfig: opts.authconfig, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Info + * @param {Object} opts Options (optional) + * @param {Function} callback Callback with info + */ +Docker.prototype.info = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var opts = { + path: '/info', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Version + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.version = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var opts = { + path: '/version', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Ping + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.ping = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/_ping', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * SystemDf equivalent to system/df API Engine + * get usage data information + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.df = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/system/df', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Events + * @param {Object} opts Events options, like 'since' (optional) + * @param {Function} callback Callback + */ +Docker.prototype.getEvents = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/events?', + method: 'GET', + options: args.opts, + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Pull is a wrapper around createImage, parsing image's tags. + * @param {String} repoTag Repository tag + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + * @param {Object} auth Authentication (optional) + * @return {Object} Image + */ +Docker.prototype.pull = function(repoTag, opts, callback, auth) { + var args = util.processArgs(opts, callback); + + var imageSrc = util.parseRepositoryTag(repoTag); + args.opts.fromImage = imageSrc.repository; + args.opts.tag = imageSrc.tag || 'latest'; + + var argsf = [args.opts, args.callback]; + if (auth) { + argsf = [auth, args.opts, args.callback]; + } + return this.createImage.apply(this, argsf); +}; + +/** + * Like run command from Docker's CLI + * @param {String} image Image name to be used. + * @param {Array} cmd Command to run in array format. + * @param {Object} streamo Output stream + * @param {Object} createOptions Container create options (optional) + * @param {Object} startOptions Container start options (optional) + * @param {Function} callback Callback + * @return {Object} EventEmitter + */ +Docker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) { + if (typeof arguments[arguments.length - 1] === 'function') { + return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback); + } else { + return this.runPromise(image, cmd, streamo, createOptions, startOptions); + } +}; + + +Docker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) { + if (!callback && typeof createOptions === 'function') { + callback = createOptions; + createOptions = {}; + startOptions = {}; + } else if (!callback && typeof startOptions === 'function') { + callback = startOptions; + startOptions = {}; + } + + var hub = new EventEmitter(); + + function handler(err, container) { + if (err) return callback(err, null, container); + + hub.emit('container', container); + + container.attach({ + stream: true, + stdout: true, + stderr: true + }, function handler(err, stream) { + if (err) return callback(err, null, container); + + hub.emit('stream', stream); + + if (streamo) { + if (streamo instanceof Array) { + stream.on('end', function() { + try { + streamo[0].end(); + } catch (e) {} + try { + streamo[1].end(); + } catch (e) {} + }); + container.modem.demuxStream(stream, streamo[0], streamo[1]); + } else { + stream.setEncoding('utf8'); + stream.pipe(streamo, { + end: true + }); + } + } + + container.start(startOptions, function(err, data) { + if (err) return callback(err, data, container); + hub.emit('start', container); + + container.wait(function(err, data) { + hub.emit('data', data); + callback(err, data, container); + }); + }); + }); + } + + var optsc = { + 'Hostname': '', + 'User': '', + 'AttachStdin': false, + 'AttachStdout': true, + 'AttachStderr': true, + 'Tty': true, + 'OpenStdin': false, + 'StdinOnce': false, + 'Env': null, + 'Cmd': cmd, + 'Image': image, + 'Volumes': {}, + 'VolumesFrom': [] + }; + + extend(optsc, createOptions); + + this.createContainer(optsc, handler); + + return hub; +}; + +Docker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) { + var self = this; + + createOptions = createOptions || {}; + startOptions = startOptions || {}; + + var optsc = { + 'Hostname': '', + 'User': '', + 'AttachStdin': false, + 'AttachStdout': true, + 'AttachStderr': true, + 'Tty': true, + 'OpenStdin': false, + 'StdinOnce': false, + 'Env': null, + 'Cmd': cmd, + 'Image': image, + 'Volumes': {}, + 'VolumesFrom': [] + }; + + extend(optsc, createOptions); + + var containero; + + return new this.modem.Promise(function(resolve, reject) { + self.createContainer(optsc).then(function(container) { + containero = container; + return container.attach({ + stream: true, + stdout: true, + stderr: true + }); + }).then(function(stream) { + if (streamo) { + if (streamo instanceof Array) { + stream.on('end', function() { + try { + streamo[0].end(); + } catch (e) {} + try { + streamo[1].end(); + } catch (e) {} + }); + containero.modem.demuxStream(stream, streamo[0], streamo[1]); + } else { + stream.setEncoding('utf8'); + stream.pipe(streamo, { + end: true + }); + } + } + return containero.start(startOptions); + }).then(function(data) { + return containero.wait(); + }).then(function(data) { + resolve([data, containero]); + }).catch(function(err) { + reject(err); + }); + }); +}; + +/** + * Init swarm. + * + * @param {object} opts + * @param {function} callback + */ +Docker.prototype.swarmInit = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm/init', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 406: 'node is already part of a Swarm' + }, + options: args.opts + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Join swarm. + * + * @param {object} opts + * @param {function} callback + */ +Docker.prototype.swarmJoin = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm/join', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 406: 'node is already part of a Swarm' + }, + options: args.opts + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Leave swarm. + * + * @param {object} opts + * @param {function} callback + */ +Docker.prototype.swarmLeave = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm/leave?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 406: 'node is not part of a Swarm' + }, + options: args.opts + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update swarm. + * + * @param {object} opts + * @param {function} callback + */ +Docker.prototype.swarmUpdate = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm/update?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: 'bad parameter', + 406: 'node is already part of a Swarm' + }, + options: args.opts + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Inspect a Swarm. + * Warning: This method is not documented in the API + * + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + */ +Docker.prototype.swarmInspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/swarm', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 406: 'This node is not a swarm manager', + 500: 'server error' + } + }; + + if (args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +Docker.Container = Container; +Docker.Image = Image; +Docker.Volume = Volume; +Docker.Network = Network; +Docker.Service = Service; +Docker.Plugin = Plugin; +Docker.Secret = Secret; +Docker.Task = Task; +Docker.Node = Node; +Docker.Exec = Exec; + +module.exports = Docker; + + +/***/ }), + +/***/ 3149: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an Exec + * @param {Object} modem docker-modem + * @param {String} id Exec's ID + */ +var Exec = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Exec.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Start the exec call that was setup. + * + * @param {object} opts + * @param {function} callback + */ +Exec.prototype.start = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/exec/' + this.id + '/start', + method: 'POST', + abortSignal: args.opts.abortSignal, + isStream: true, + allowEmpty: true, + hijack: args.opts.hijack, + openStdin: args.opts.stdin, + statusCodes: { + 200: true, + 204: true, + 404: 'no such exec', + 409: 'container stopped/paused', + 500: 'container not running' + }, + options: args.opts + }; + + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + +/** + * Resize the exec call that was setup. + * + * @param {object} opts + * @param {function} callback + */ +Exec.prototype.resize = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/exec/' + this.id + '/resize?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such exec', + 500: 'container not running' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + +/** + * Get low-level information about the exec call. + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Exec.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/exec/' + this.id + '/json', + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such exec', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + + +module.exports = Exec; + + +/***/ }), + +/***/ 6689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an image + * @param {Object} modem docker-modem + * @param {String} name Image's name + */ +var Image = function(modem, name) { + this.modem = modem; + this.name = name; +}; + +Image.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Image.prototype.inspect = function(callback) { + var self = this; + + var opts = { + path: '/images/' + this.name + '/json', + method: 'GET', + statusCodes: { + 200: true, + 404: 'no such image', + 500: 'server error' + } + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return callback(err, data); + callback(err, data); + }); + } +}; + +/** + * Distribution + * @param {Object} opts + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Image.prototype.distribution = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self = this; + + var fopts = { + path: '/distribution/' + this.name + '/json', + method: 'GET', + statusCodes: { + 200: true, + 401: 'no such image', + 500: 'server error' + }, + authconfig: (args.opts) ? args.opts.authconfig : undefined + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(fopts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(fopts, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + +/** + * History + * @param {Function} callback Callback + */ +Image.prototype.history = function(callback) { + var self = this; + var opts = { + path: '/images/' + this.name + '/history', + method: 'GET', + statusCodes: { + 200: true, + 404: 'no such image', + 500: 'server error' + } + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return callback(err, data); + callback(err, data); + }); + } +}; + +/** + * Get + * @param {Function} callback Callback with data stream. + */ +Image.prototype.get = function(callback) { + var self = this; + var opts = { + path: '/images/' + this.name + '/get', + method: 'GET', + isStream: true, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return callback(err, data); + callback(err, data); + }); + } +}; + +/** + * Push + * @param {Object} opts Push options, like 'registry' (optional) + * @param {Function} callback Callback with stream. + * @param {Object} auth Registry authentication + */ +Image.prototype.push = function(opts, callback, auth) { + var self = this; + var args = util.processArgs(opts, callback); + var isStream = true; + if (args.opts.stream === false) { + isStream = false; + } + var optsf = { + path: '/images/' + this.name + '/push?', + method: 'POST', + options: args.opts, + authconfig: args.opts.authconfig || auth, + abortSignal: args.opts.abortSignal, + isStream: isStream, + statusCodes: { + 200: true, + 404: 'no such image', + 500: 'server error' + } + }; + + delete optsf.options.authconfig; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Tag + * @param {Object} opts Tag options, like 'repo' (optional) + * @param {Function} callback Callback + */ +Image.prototype.tag = function(opts, callback) { + var self = this; + var optsf = { + path: '/images/' + this.name + '/tag?', + method: 'POST', + options: opts, + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 201: true, + 400: 'bad parameter', + 404: 'no such image', + 409: 'conflict', + 500: 'server error' + } + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + +/** + * Removes the image + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Image.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/images/' + this.name + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such image', + 409: 'conflict', + 500: 'server error' + }, + options: args.opts + }; + + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +module.exports = Image; + + +/***/ }), + +/***/ 9780: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an network + * @param {Object} modem docker-modem + * @param {String} id Network's id + */ +var Network = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Network.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Id only if callback isn't specified. + */ +Network.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var opts = { + path: '/networks/' + this.id + '?', + method: 'GET', + statusCodes: { + 200: true, + 404: 'no such network', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Removes the network + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Network.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks/' + this.id, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'no such network', + 409: 'conflict', + 500: 'server error' + }, + options: args.opts + }; + + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Connects a container to a network + * @param {[Object]} opts Connect options (optional) + * @param {Function} callback Callback + */ +Network.prototype.connect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks/' + this.id + '/connect', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 404: 'network or container is not found', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Disconnects a container from a network + * @param {[Object]} opts Disconnect options (optional) + * @param {Function} callback Callback + */ +Network.prototype.disconnect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/networks/' + this.id + '/disconnect', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 404: 'network or container is not found', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + + + +module.exports = Network; + + +/***/ }), + +/***/ 2297: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an Node + * @param {Object} modem docker-modem + * @param {String} id Node's ID + */ +var Node = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Node.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Query Docker for Node details. + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Node.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/nodes/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such node', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Update a node. + * + * @param {object} opts + * @param {function} callback + */ +Node.prototype.update = function(opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + } + + var optsf = { + path: '/nodes/' + this.id + '/update?', + method: 'POST', + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such node', + 406: 'node is not part of a swarm', + 500: 'server error' + }, + options: opts + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + + +/** + * Remove a Node. + * Warning: This method is not documented in the API. + * + * @param {object} opts + * @param {function} callback + */ +Node.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/nodes/' + this.id + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such node', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +module.exports = Node; + + +/***/ }), + +/***/ 6606: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents a plugin + * @param {Object} modem docker-modem + * @param {String} name Plugin's name + */ +var Plugin = function(modem, name, remote) { + this.modem = modem; + this.name = name; + this.remote = remote || name; +}; + +Plugin.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Plugin.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'plugin is not installed', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Removes the plugin + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '?', + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'plugin is not installed', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } +}; + +/** + * get privileges + * @param {Object} opts Options (optional) + * @param {Function} callback Callback + * @return {Object} Name only if callback isn't specified. + */ +Plugin.prototype.privileges = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/privileges?', + method: 'GET', + options: { + 'remote': this.remote + }, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Installs a new plugin + * @param {Object} opts Create options + * @param {Function} callback Callback + */ +Plugin.prototype.pull = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + if(args.opts._query && !args.opts._query.name) { + args.opts._query.name = this.name; + } + if(args.opts._query && !args.opts._query.remote) { + args.opts._query.remote = this.remote; + } + + var optsf = { + path: '/plugins/pull?', + method: 'POST', + abortSignal: args.opts.abortSignal, + isStream: true, + options: args.opts, + statusCodes: { + 200: true, // unofficial, but proxies may return it + 204: true, + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Enable + * @param {Object} opts Plugin enable options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.enable = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '/enable?', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Disable + * @param {Object} opts Plugin disable options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.disable = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '/disable', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Push + * @param {Object} opts Plugin push options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.push = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '/push', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'plugin not installed', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * COnfigure + * @param {Object} opts Plugin configure options (optional) + * @param {Function} callback Callback + */ +Plugin.prototype.configure = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/plugins/' + this.name + '/set', + method: 'POST', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'plugin not installed', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +/** + * Upgrade plugin + * + * @param {object} auth + * @param {object} opts + * @param {function} callback + */ +Plugin.prototype.upgrade = function(auth, opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + opts = auth; + auth = opts.authconfig || undefined; + } + + var optsf = { + path: '/plugins/' + this.name + '/upgrade?', + method: 'POST', + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'plugin not installed', + 500: 'server error' + }, + authconfig: auth, + options: opts + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + + +module.exports = Plugin; + + +/***/ }), + +/***/ 9934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents a secret + * @param {Object} modem docker-modem + * @param {String} id Secret's id + */ +var Secret = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Secret.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Secret.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/secrets/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'secret not found', + 406: 'node is not part of a swarm', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update a secret. + * + * @param {object} opts + * @param {function} callback + */ +Secret.prototype.update = function(opts, callback) { + var self = this; + if (!callback && typeof opts === 'function') { + callback = opts; + } + + var optsf = { + path: '/secrets/' + this.id + '/update?', + method: 'POST', + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: 'secret not found', + 500: 'server error' + }, + options: opts + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + + +/** + * Removes the secret + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Secret.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/secrets/' + this.id, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'secret not found', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + + +module.exports = Secret; + + +/***/ }), + +/***/ 8866: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an Service + * @param {Object} modem docker-modem + * @param {String} id Service's ID + */ +var Service = function(modem, id) { + this.modem = modem; + this.id = id; +}; + +Service.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Query Docker for service details. + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Service.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/services/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such service', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Delete Service + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Service.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/services/' + this.id, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: 'no such service', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Update service + * + * @param {object} auth + * @param {object} opts + * @param {function} callback + */ +Service.prototype.update = function(auth, opts, callback) { + var self = this; + if (!callback) { + var t = typeof opts; + if(t === 'function'){ + callback = opts; + opts = auth; + auth = opts.authconfig || undefined; + } else if (t === 'undefined'){ + opts = auth; + auth = opts.authconfig || undefined; + } + } + + var optsf = { + path: '/services/' + this.id + '/update?', + method: 'POST', + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such service', + 500: 'server error' + }, + authconfig: auth, + options: opts + }; + + if(callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } +}; + + + +/** + * Service logs + * @param {Object} opts Logs options. (optional) + * @param {Function} callback Callback with data + */ +Service.prototype.logs = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, {}); + + var optsf = { + path: '/services/' + this.id + '/logs?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 200: true, + 404: 'no such service', + 500: 'server error', + 503: 'node is not part of a swarm' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + + +module.exports = Service; + + +/***/ }), + +/***/ 1385: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents an Task + * @param {Object} modem docker-modem + * @param {String} id Task's ID + */ +var Task = function(modem, id) { + this.modem = modem; + this.id = id; + + this.defaultOptions = { + log: {} + }; +}; + +Task.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Query Docker for Task details. + * + * @param {Object} opts Options (optional) + * @param {function} callback + */ +Task.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/tasks/' + this.id, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'unknown task', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Task logs + * @param {Object} opts Logs options. (optional) + * @param {Function} callback Callback with data + */ +Task.prototype.logs = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback, this.defaultOptions.log); + + var optsf = { + path: '/tasks/' + this.id + '/logs?', + method: 'GET', + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 101: true, + 200: true, + 404: 'no such container', + 500: 'server error', + 503: 'node is not part of a swarm' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + + +module.exports = Task; + + +/***/ }), + +/***/ 1604: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var DockerIgnore = __nccwpck_require__(3358); +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); +var tar = __nccwpck_require__(366); +var zlib = __nccwpck_require__(9796); + +// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js + +var arr = []; +var each = arr.forEach; +var slice = arr.slice; + +module.exports.extend = function(obj) { + each.call(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }); + return obj; +}; + +module.exports.processArgs = function(opts, callback, defaultOpts) { + if (!callback && typeof opts === 'function') { + callback = opts; + opts = null; + } + return { + callback: callback, + opts: module.exports.extend({}, defaultOpts, opts) + }; +}; + + +/** + * Parse the given repo tag name (as a string) and break it out into repo/tag pair. + * // if given the input http://localhost:8080/woot:latest + * { + * repository: 'http://localhost:8080/woot', + * tag: 'latest' + * } + * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest' + * @return {Object} input parsed into the repo and tag. + */ +module.exports.parseRepositoryTag = function(input) { + var separatorPos; + var digestPos = input.indexOf('@'); + var colonPos = input.lastIndexOf(':'); + // @ symbol is more important + if (digestPos >= 0) { + separatorPos = digestPos; + } else if (colonPos >= 0) { + separatorPos = colonPos; + } else { + // no colon nor @ + return { + repository: input + }; + } + + // last colon is either the tag (or part of a port designation) + var tag = input.slice(separatorPos + 1); + + // if it contains a / its not a tag and is part of the url + if (tag.indexOf('/') === -1) { + return { + repository: input.slice(0, separatorPos), + tag: tag + }; + } + + return { + repository: input + }; +}; + + +module.exports.prepareBuildContext = function(file, next) { + if (file && file.context) { + fs.readFile(path.join(file.context, '.dockerignore'), (err, data) => { + let ignoreFn; + let filterFn; + + if (!err) { + const dockerIgnore = DockerIgnore({ ignorecase: false }).add(data.toString()); + + filterFn = dockerIgnore.createFilter(); + ignoreFn = (path) => { + return !filterFn(path); + } + } + + const entries = file.src.slice() || [] + + const pack = tar.pack(file.context, { + entries: filterFn ? entries.filter(filterFn) : entries, + ignore: ignoreFn // Only works on directories + }); + + next(pack.pipe(zlib.createGzip())); + }) + } else { + next(file); + } +} + + +/***/ }), + +/***/ 4877: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(1604); + +/** + * Represents a volume + * @param {Object} modem docker-modem + * @param {String} name Volume's name + */ +var Volume = function(modem, name) { + this.modem = modem; + this.name = name; +}; + +Volume.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; + +/** + * Inspect + * @param {Object} opts Options (optional) + * @param {Function} callback Callback, if specified Docker will be queried. + * @return {Object} Name only if callback isn't specified. + */ +Volume.prototype.inspect = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/volumes/' + this.name, + method: 'GET', + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: 'no such volume', + 500: 'server error' + } + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +/** + * Removes the volume + * @param {[Object]} opts Remove options (optional) + * @param {Function} callback Callback + */ +Volume.prototype.remove = function(opts, callback) { + var self = this; + var args = util.processArgs(opts, callback); + + var optsf = { + path: '/volumes/' + this.name, + method: 'DELETE', + abortSignal: args.opts.abortSignal, + statusCodes: { + 204: true, + 404: 'no such volume', + 409: 'conflict', + 500: 'server error' + }, + options: args.opts + }; + + if(args.callback === undefined) { + return new this.modem.Promise(function(resolve, reject) { + self.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } +}; + +module.exports = Volume; + + +/***/ }), + +/***/ 1205: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var once = __nccwpck_require__(1223); + +var noop = function() {}; + +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; + +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; + +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + + callback = once(callback || noop); + + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var cancelled = false; + + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; + + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; + + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; + + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; + + var onerror = function(err) { + callback.call(stream, err); + }; + + var onclose = function() { + process.nextTick(onclosenexttick); + }; + + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + }; + + var onrequest = function() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + cancelled = true; + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +}; + +module.exports = eos; + + +/***/ }), + +/***/ 7030: +/***/ ((module) => { + +module.exports = class FixedFIFO { + constructor (hwm) { + if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two') + this.buffer = new Array(hwm) + this.mask = hwm - 1 + this.top = 0 + this.btm = 0 + this.next = null + } + + clear () { + this.top = this.btm = 0 + this.next = null + this.buffer.fill(undefined) + } + + push (data) { + if (this.buffer[this.top] !== undefined) return false + this.buffer[this.top] = data + this.top = (this.top + 1) & this.mask + return true + } + + shift () { + const last = this.buffer[this.btm] + if (last === undefined) return undefined + this.buffer[this.btm] = undefined + this.btm = (this.btm + 1) & this.mask + return last + } + + peek () { + return this.buffer[this.btm] + } + + isEmpty () { + return this.buffer[this.btm] === undefined + } +} + + +/***/ }), + +/***/ 2958: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const FixedFIFO = __nccwpck_require__(7030) + +module.exports = class FastFIFO { + constructor (hwm) { + this.hwm = hwm || 16 + this.head = new FixedFIFO(this.hwm) + this.tail = this.head + this.length = 0 + } + + clear () { + this.head = this.tail + this.head.clear() + this.length = 0 + } + + push (val) { + this.length++ + if (!this.head.push(val)) { + const prev = this.head + this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length) + this.head.push(val) + } + } + + shift () { + if (this.length !== 0) this.length-- + const val = this.tail.shift() + if (val === undefined && this.tail.next) { + const next = this.tail.next + this.tail.next = null + this.tail = next + return this.tail.shift() + } + + return val + } + + peek () { + return this.tail.peek() + } + + isEmpty () { + return this.head.isEmpty() + } +} + + +/***/ }), + +/***/ 3186: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = (__nccwpck_require__(7147).constants) || __nccwpck_require__(2057) + + +/***/ }), + +/***/ 1621: +/***/ ((module) => { + +"use strict"; + + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; + + +/***/ }), + +/***/ 4124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +try { + var util = __nccwpck_require__(3837); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(8544); +} + + +/***/ }), + +/***/ 8544: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 7614: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var path = __nccwpck_require__(1017); +var fs = __nccwpck_require__(7147); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; + + +/***/ }), + +/***/ 900: +/***/ ((module) => { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + + +/***/ }), + +/***/ 7994: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Advanced Encryption Standard (AES) implementation. + * + * This implementation is based on the public domain library 'jscrypto' which + * was written by: + * + * Emily Stark (estark@stanford.edu) + * Mike Hamburg (mhamburg@stanford.edu) + * Dan Boneh (dabo@cs.stanford.edu) + * + * Parts of this code are based on the OpenSSL implementation of AES: + * http://www.openssl.org + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7088); +__nccwpck_require__(873); +__nccwpck_require__(8339); + +/* AES API */ +module.exports = forge.aes = forge.aes || {}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('AES-', key); + * cipher.start({iv: iv}); + * + * Creates an AES cipher object to encrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as a string of bytes, an array of bytes, + * a byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: false, + mode: mode + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('AES-', key); + * + * Creates an AES cipher object to encrypt data using the given symmetric key. + * + * The key may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: false, + mode: mode + }); +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('AES-', key); + * decipher.start({iv: iv}); + * + * Creates an AES cipher object to decrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as a string of bytes, an array of bytes, + * a byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: true, + mode: mode + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('AES-', key); + * + * Creates an AES cipher object to decrypt data using the given symmetric key. + * + * The key may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: true, + mode: mode + }); +}; + +/** + * Creates a new AES cipher algorithm object. + * + * @param name the name of the algorithm. + * @param mode the mode factory function. + * + * @return the AES algorithm object. + */ +forge.aes.Algorithm = function(name, mode) { + if(!init) { + initialize(); + } + var self = this; + self.name = name; + self.mode = new mode({ + blockSize: 16, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self._w, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self._w, inBlock, outBlock, true); + } + } + }); + self._init = false; +}; + +/** + * Initializes this AES algorithm by expanding its key. + * + * @param options the options to use. + * key the key to use with this algorithm. + * decrypt true if the algorithm should be initialized for decryption, + * false for encryption. + */ +forge.aes.Algorithm.prototype.initialize = function(options) { + if(this._init) { + return; + } + + var key = options.key; + var tmp; + + /* Note: The key may be a string of bytes, an array of bytes, a byte + buffer, or an array of 32-bit integers. If the key is in bytes, then + it must be 16, 24, or 32 bytes in length. If it is in 32-bit + integers, it must be 4, 6, or 8 integers long. */ + + if(typeof key === 'string' && + (key.length === 16 || key.length === 24 || key.length === 32)) { + // convert key string into byte buffer + key = forge.util.createBuffer(key); + } else if(forge.util.isArray(key) && + (key.length === 16 || key.length === 24 || key.length === 32)) { + // convert key integer array into byte buffer + tmp = key; + key = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + + // convert key byte buffer into 32-bit integer array + if(!forge.util.isArray(key)) { + tmp = key; + key = []; + + // key lengths of 16, 24, 32 bytes allowed + var len = tmp.length(); + if(len === 16 || len === 24 || len === 32) { + len = len >>> 2; + for(var i = 0; i < len; ++i) { + key.push(tmp.getInt32()); + } + } + } + + // key must be an array of 32-bit integers by now + if(!forge.util.isArray(key) || + !(key.length === 4 || key.length === 6 || key.length === 8)) { + throw new Error('Invalid key parameter.'); + } + + // encryption operation is always used for these modes + var mode = this.mode.name; + var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); + + // do key expansion + this._w = _expandKey(key, options.decrypt && !encryptOp); + this._init = true; +}; + +/** + * Expands a key. Typically only used for testing. + * + * @param key the symmetric key to expand, as an array of 32-bit words. + * @param decrypt true to expand for decryption, false for encryption. + * + * @return the expanded key. + */ +forge.aes._expandKey = function(key, decrypt) { + if(!init) { + initialize(); + } + return _expandKey(key, decrypt); +}; + +/** + * Updates a single block. Typically only used for testing. + * + * @param w the expanded key to use. + * @param input an array of block-size 32-bit words. + * @param output an array of block-size 32-bit words. + * @param decrypt true to decrypt, false to encrypt. + */ +forge.aes._updateBlock = _updateBlock; + +/** Register AES algorithms **/ + +registerAlgorithm('AES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('AES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('AES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('AES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('AES-CTR', forge.cipher.modes.ctr); +registerAlgorithm('AES-GCM', forge.cipher.modes.gcm); + +function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.aes.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); +} + +/** AES implementation **/ + +var init = false; // not yet initialized +var Nb = 4; // number of words comprising the state (AES = 4) +var sbox; // non-linear substitution table used in key expansion +var isbox; // inversion of sbox +var rcon; // round constant word array +var mix; // mix-columns table +var imix; // inverse mix-columns table + +/** + * Performs initialization, ie: precomputes tables to optimize for speed. + * + * One way to understand how AES works is to imagine that 'addition' and + * 'multiplication' are interfaces that require certain mathematical + * properties to hold true (ie: they are associative) but they might have + * different implementations and produce different kinds of results ... + * provided that their mathematical properties remain true. AES defines + * its own methods of addition and multiplication but keeps some important + * properties the same, ie: associativity and distributivity. The + * explanation below tries to shed some light on how AES defines addition + * and multiplication of bytes and 32-bit words in order to perform its + * encryption and decryption algorithms. + * + * The basics: + * + * The AES algorithm views bytes as binary representations of polynomials + * that have either 1 or 0 as the coefficients. It defines the addition + * or subtraction of two bytes as the XOR operation. It also defines the + * multiplication of two bytes as a finite field referred to as GF(2^8) + * (Note: 'GF' means "Galois Field" which is a field that contains a finite + * number of elements so GF(2^8) has 256 elements). + * + * This means that any two bytes can be represented as binary polynomials; + * when they multiplied together and modularly reduced by an irreducible + * polynomial of the 8th degree, the results are the field GF(2^8). The + * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. + * This multiplication is associative with 0x01 as the identity: + * + * (b * 0x01 = GF(b, 0x01) = b). + * + * The operation GF(b, 0x02) can be performed at the byte level by left + * shifting b once and then XOR'ing it (to perform the modular reduction) + * with 0x11b if b is >= 128. Repeated application of the multiplication + * of 0x02 can be used to implement the multiplication of any two bytes. + * + * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can + * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these + * factors can each be multiplied by 0x57 and then added together. To do + * the multiplication, values for 0x57 multiplied by each of these 3 factors + * can be precomputed and stored in a table. To add them, the values from + * the table are XOR'd together. + * + * AES also defines addition and multiplication of words, that is 4-byte + * numbers represented as polynomials of 3 degrees where the coefficients + * are the values of the bytes. + * + * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. + * + * Addition is performed by XOR'ing like powers of x. Multiplication + * is performed in two steps, the first is an algebriac expansion as + * you would do normally (where addition is XOR). But the result is + * a polynomial larger than 3 degrees and thus it cannot fit in a word. So + * next the result is modularly reduced by an AES-specific polynomial of + * degree 4 which will always produce a polynomial of less than 4 degrees + * such that it will fit in a word. In AES, this polynomial is x^4 + 1. + * + * The modular product of two polynomials 'a' and 'b' is thus: + * + * d(x) = d3x^3 + d2x^2 + d1x + d0 + * with + * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) + * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) + * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) + * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) + * + * As a matrix: + * + * [d0] = [a0 a3 a2 a1][b0] + * [d1] [a1 a0 a3 a2][b1] + * [d2] [a2 a1 a0 a3][b2] + * [d3] [a3 a2 a1 a0][b3] + * + * Special polynomials defined by AES (0x02 == {02}): + * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} + * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. + * + * These polynomials are used in the MixColumns() and InverseMixColumns() + * operations, respectively, to cause each element in the state to affect + * the output (referred to as diffusing). + * + * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the + * polynomial x3. + * + * The ShiftRows() method modifies the last 3 rows in the state (where + * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. + * The 1st byte in the second row is moved to the end of the row. The 1st + * and 2nd bytes in the third row are moved to the end of the row. The 1st, + * 2nd, and 3rd bytes are moved in the fourth row. + * + * More details on how AES arithmetic works: + * + * In the polynomial representation of binary numbers, XOR performs addition + * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) + * corresponds with the multiplication of polynomials modulo an irreducible + * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply + * polynomial 'a' with polynomial 'b' and then do a modular reduction by + * an AES-specific irreducible polynomial of degree 8. + * + * A polynomial is irreducible if its only divisors are one and itself. For + * the AES algorithm, this irreducible polynomial is: + * + * m(x) = x^8 + x^4 + x^3 + x + 1, + * + * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: + * 100011011 = 283 = 0x11b. + * + * For example, GF(0x57, 0x83) = 0xc1 because + * + * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 + * 0x85 = 131 = 10000101 = x^7 + x + 1 + * + * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) + * = x^13 + x^11 + x^9 + x^8 + x^7 + + * x^7 + x^5 + x^3 + x^2 + x + + * x^6 + x^4 + x^2 + x + 1 + * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y + * y modulo (x^8 + x^4 + x^3 + x + 1) + * = x^7 + x^6 + 1. + * + * The modular reduction by m(x) guarantees the result will be a binary + * polynomial of less than degree 8, so that it can fit in a byte. + * + * The operation to multiply a binary polynomial b with x (the polynomial + * x in binary representation is 00000010) is: + * + * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 + * + * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the + * most significant bit is 0 in b) then the result is already reduced. If + * it is 1, then we can reduce it by subtracting m(x) via an XOR. + * + * It follows that multiplication by x (00000010 or 0x02) can be implemented + * by performing a left shift followed by a conditional bitwise XOR with + * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by + * higher powers of x can be implemented by repeated application of xtime(). + * + * By adding intermediate results, multiplication by any constant can be + * implemented. For instance: + * + * GF(0x57, 0x13) = 0xfe because: + * + * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) + * + * Note: We XOR with 0x11b instead of 0x1b because in javascript our + * datatype for b can be larger than 1 byte, so a left shift will not + * automatically eliminate bits that overflow a byte ... by XOR'ing the + * overflow bit with 1 (the extra one from 0x11b) we zero it out. + * + * GF(0x57, 0x02) = xtime(0x57) = 0xae + * GF(0x57, 0x04) = xtime(0xae) = 0x47 + * GF(0x57, 0x08) = xtime(0x47) = 0x8e + * GF(0x57, 0x10) = xtime(0x8e) = 0x07 + * + * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) + * + * And by the distributive property (since XOR is addition and GF() is + * multiplication): + * + * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) + * = 0x57 ^ 0xae ^ 0x07 + * = 0xfe. + */ +function initialize() { + init = true; + + /* Populate the Rcon table. These are the values given by + [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) + in the field of GF(2^8), where i starts at 1. + + rcon[0] = [0x00, 0x00, 0x00, 0x00] + rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 + rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 + ... + rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B + rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 + + We only store the first byte because it is the only one used. + */ + rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; + + // compute xtime table which maps i onto GF(i, 0x02) + var xtime = new Array(256); + for(var i = 0; i < 128; ++i) { + xtime[i] = i << 1; + xtime[i + 128] = (i + 128) << 1 ^ 0x11B; + } + + // compute all other tables + sbox = new Array(256); + isbox = new Array(256); + mix = new Array(4); + imix = new Array(4); + for(var i = 0; i < 4; ++i) { + mix[i] = new Array(256); + imix[i] = new Array(256); + } + var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; + for(var i = 0; i < 256; ++i) { + /* We need to generate the SubBytes() sbox and isbox tables so that + we can perform byte substitutions. This requires us to traverse + all of the elements in GF, find their multiplicative inverses, + and apply to each the following affine transformation: + + bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ + b(i + 7) mod 8 ^ ci + for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the + ith bit of a byte c with the value {63} or {01100011}. + + It is possible to traverse every possible value in a Galois field + using what is referred to as a 'generator'. There are many + generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully + traverse GF we iterate 255 times, multiplying by our generator + each time. + + On each iteration we can determine the multiplicative inverse for + the current element. + + Suppose there is an element in GF 'e'. For a given generator 'g', + e = g^x. The multiplicative inverse of e is g^(255 - x). It turns + out that if use the inverse of a generator as another generator + it will produce all of the corresponding multiplicative inverses + at the same time. For this reason, we choose 5 as our inverse + generator because it only requires 2 multiplies and 1 add and its + inverse, 82, requires relatively few operations as well. + + In order to apply the affine transformation, the multiplicative + inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a + bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and + 'x'. Then 's' is left shifted and the high bit of 's' is made the + low bit. The resulting value is stored in 's'. Then 'x' is XOR'd + with 's' and stored in 'x'. On each subsequent iteration the same + operation is performed. When 4 iterations are complete, 'x' is + XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. + For example: + + s = 01000001 + x = 01000001 + + iteration 1: s = 10000010, x ^= s + iteration 2: s = 00000101, x ^= s + iteration 3: s = 00001010, x ^= s + iteration 4: s = 00010100, x ^= s + x ^= 0x63 + + This can be done with a loop where s = (s << 1) | (s >> 7). However, + it can also be done by using a single 16-bit (in this case 32-bit) + number 'sx'. Since XOR is an associative operation, we can set 'sx' + to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. + The most significant bits will flow into the high 8 bit positions + and be correctly XOR'd with one another. All that remains will be + to cycle the high 8 bits by XOR'ing them all with the lower 8 bits + afterwards. + + At the same time we're populating sbox and isbox we can precompute + the multiplication we'll need to do to do MixColumns() later. + */ + + // apply affine transformation + sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); + sx = (sx >> 8) ^ (sx & 255) ^ 0x63; + + // update tables + sbox[e] = sx; + isbox[sx] = e; + + /* Mixing columns is done using matrix multiplication. The columns + that are to be mixed are each a single word in the current state. + The state has Nb columns (4 columns). Therefore each column is a + 4 byte word. So to mix the columns in a single column 'c' where + its rows are r0, r1, r2, and r3, we use the following matrix + multiplication: + + [2 3 1 1]*[r0,c]=[r'0,c] + [1 2 3 1] [r1,c] [r'1,c] + [1 1 2 3] [r2,c] [r'2,c] + [3 1 1 2] [r3,c] [r'3,c] + + r0, r1, r2, and r3 are each 1 byte of one of the words in the + state (a column). To do matrix multiplication for each mixed + column c' we multiply the corresponding row from the left matrix + with the corresponding column from the right matrix. In total, we + get 4 equations: + + r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c + r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c + r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c + r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c + + As usual, the multiplication is as previously defined and the + addition is XOR. In order to optimize mixing columns we can store + the multiplication results in tables. If you think of the whole + column as a word (it might help to visualize by mentally rotating + the equations above by counterclockwise 90 degrees) then you can + see that it would be useful to map the multiplications performed on + each byte (r0, r1, r2, r3) onto a word as well. For instance, we + could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the + highest 8 bits and 3*r0 in the lowest 8 bits (with the other two + respectively in the middle). This means that a table can be + constructed that uses r0 as an index to the word. We can do the + same with r1, r2, and r3, creating a total of 4 tables. + + To construct a full c', we can just look up each byte of c in + their respective tables and XOR the results together. + + Also, to build each table we only have to calculate the word + for 2,1,1,3 for every byte ... which we can do on each iteration + of this loop since we will iterate over every byte. After we have + calculated 2,1,1,3 we can get the results for the other tables + by cycling the byte at the end to the beginning. For instance + we can take the result of table 2,1,1,3 and produce table 3,2,1,1 + by moving the right most byte to the left most position just like + how you can imagine the 3 moved out of 2,1,1,3 and to the front + to produce 3,2,1,1. + + There is another optimization in that the same multiples of + the current element we need in order to advance our generator + to the next iteration can be reused in performing the 2,1,1,3 + calculation. We also calculate the inverse mix column tables, + with e,9,d,b being the inverse of 2,1,1,3. + + When we're done, and we need to actually mix columns, the first + byte of each state word should be put through mix[0] (2,1,1,3), + the second through mix[1] (3,2,1,1) and so forth. Then they should + be XOR'd together to produce the fully mixed column. + */ + + // calculate mix and imix table values + sx2 = xtime[sx]; + e2 = xtime[e]; + e4 = xtime[e2]; + e8 = xtime[e4]; + me = + (sx2 << 24) ^ // 2 + (sx << 16) ^ // 1 + (sx << 8) ^ // 1 + (sx ^ sx2); // 3 + ime = + (e2 ^ e4 ^ e8) << 24 ^ // E (14) + (e ^ e8) << 16 ^ // 9 + (e ^ e4 ^ e8) << 8 ^ // D (13) + (e ^ e2 ^ e8); // B (11) + // produce each of the mix tables by rotating the 2,1,1,3 value + for(var n = 0; n < 4; ++n) { + mix[n][e] = me; + imix[n][sx] = ime; + // cycle the right most byte to the left most position + // ie: 2,1,1,3 becomes 3,2,1,1 + me = me << 24 | me >>> 8; + ime = ime << 24 | ime >>> 8; + } + + // get next element and inverse + if(e === 0) { + // 1 is the inverse of 1 + e = ei = 1; + } else { + // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) + // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) + e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; + ei ^= xtime[xtime[ei]]; + } + } +} + +/** + * Generates a key schedule using the AES key expansion algorithm. + * + * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion + * routine to generate a key schedule. The Key Expansion generates a total + * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, + * and each of the Nr rounds requires Nb words of key data. The resulting + * key schedule consists of a linear array of 4-byte words, denoted [wi ], + * with i in the range 0 <= i < Nb(Nr + 1). + * + * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) + * AES-128 (Nb=4, Nk=4, Nr=10) + * AES-192 (Nb=4, Nk=6, Nr=12) + * AES-256 (Nb=4, Nk=8, Nr=14) + * Note: Nr=Nk+6. + * + * Nb is the number of columns (32-bit words) comprising the State (or + * number of bytes in a block). For AES, Nb=4. + * + * @param key the key to schedule (as an array of 32-bit words). + * @param decrypt true to modify the key schedule to decrypt, false not to. + * + * @return the generated key schedule. + */ +function _expandKey(key, decrypt) { + // copy the key's words to initialize the key schedule + var w = key.slice(0); + + /* RotWord() will rotate a word, moving the first byte to the last + byte's position (shifting the other bytes left). + + We will be getting the value of Rcon at i / Nk. 'i' will iterate + from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in + a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from + 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will + increase by 1. We use a counter iNk to keep track of this. + */ + + // go through the rounds expanding the key + var temp, iNk = 1; + var Nk = w.length; + var Nr1 = Nk + 6 + 1; + var end = Nb * Nr1; + for(var i = Nk; i < end; ++i) { + temp = w[i - 1]; + if(i % Nk === 0) { + // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] + temp = + sbox[temp >>> 16 & 255] << 24 ^ + sbox[temp >>> 8 & 255] << 16 ^ + sbox[temp & 255] << 8 ^ + sbox[temp >>> 24] ^ (rcon[iNk] << 24); + iNk++; + } else if(Nk > 6 && (i % Nk === 4)) { + // temp = SubWord(temp) + temp = + sbox[temp >>> 24] << 24 ^ + sbox[temp >>> 16 & 255] << 16 ^ + sbox[temp >>> 8 & 255] << 8 ^ + sbox[temp & 255]; + } + w[i] = w[i - Nk] ^ temp; + } + + /* When we are updating a cipher block we always use the code path for + encryption whether we are decrypting or not (to shorten code and + simplify the generation of look up tables). However, because there + are differences in the decryption algorithm, other than just swapping + in different look up tables, we must transform our key schedule to + account for these changes: + + 1. The decryption algorithm gets its key rounds in reverse order. + 2. The decryption algorithm adds the round key before mixing columns + instead of afterwards. + + We don't need to modify our key schedule to handle the first case, + we can just traverse the key schedule in reverse order when decrypting. + + The second case requires a little work. + + The tables we built for performing rounds will take an input and then + perform SubBytes() and MixColumns() or, for the decrypt version, + InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires + us to AddRoundKey() before InvMixColumns(). This means we'll need to + apply some transformations to the round key to inverse-mix its columns + so they'll be correct for moving AddRoundKey() to after the state has + had its columns inverse-mixed. + + To inverse-mix the columns of the state when we're decrypting we use a + lookup table that will apply InvSubBytes() and InvMixColumns() at the + same time. However, the round key's bytes are not inverse-substituted + in the decryption algorithm. To get around this problem, we can first + substitute the bytes in the round key so that when we apply the + transformation via the InvSubBytes()+InvMixColumns() table, it will + undo our substitution leaving us with the original value that we + want -- and then inverse-mix that value. + + This change will correctly alter our key schedule so that we can XOR + each round key with our already transformed decryption state. This + allows us to use the same code path as the encryption algorithm. + + We make one more change to the decryption key. Since the decryption + algorithm runs in reverse from the encryption algorithm, we reverse + the order of the round keys to avoid having to iterate over the key + schedule backwards when running the encryption algorithm later in + decryption mode. In addition to reversing the order of the round keys, + we also swap each round key's 2nd and 4th rows. See the comments + section where rounds are performed for more details about why this is + done. These changes are done inline with the other substitution + described above. + */ + if(decrypt) { + var tmp; + var m0 = imix[0]; + var m1 = imix[1]; + var m2 = imix[2]; + var m3 = imix[3]; + var wnew = w.slice(0); + end = w.length; + for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { + // do not sub the first or last round key (round keys are Nb + // words) as no column mixing is performed before they are added, + // but do change the key order + if(i === 0 || i === (end - Nb)) { + wnew[i] = w[wi]; + wnew[i + 1] = w[wi + 3]; + wnew[i + 2] = w[wi + 2]; + wnew[i + 3] = w[wi + 1]; + } else { + // substitute each round key byte because the inverse-mix + // table will inverse-substitute it (effectively cancel the + // substitution because round key bytes aren't sub'd in + // decryption mode) and swap indexes 3 and 1 + for(var n = 0; n < Nb; ++n) { + tmp = w[wi + n]; + wnew[i + (3&-n)] = + m0[sbox[tmp >>> 24]] ^ + m1[sbox[tmp >>> 16 & 255]] ^ + m2[sbox[tmp >>> 8 & 255]] ^ + m3[sbox[tmp & 255]]; + } + } + } + w = wnew; + } + + return w; +} + +/** + * Updates a single block (16 bytes) using AES. The update will either + * encrypt or decrypt the block. + * + * @param w the key schedule. + * @param input the input block (an array of 32-bit words). + * @param output the updated output block. + * @param decrypt true to decrypt the block, false to encrypt it. + */ +function _updateBlock(w, input, output, decrypt) { + /* + Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) + begin + byte state[4,Nb] + state = in + AddRoundKey(state, w[0, Nb-1]) + for round = 1 step 1 to Nr-1 + SubBytes(state) + ShiftRows(state) + MixColumns(state) + AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) + end for + SubBytes(state) + ShiftRows(state) + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + out = state + end + + InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) + begin + byte state[4,Nb] + state = in + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + for round = Nr-1 step -1 downto 1 + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) + InvMixColumns(state) + end for + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[0, Nb-1]) + out = state + end + */ + + // Encrypt: AddRoundKey(state, w[0, Nb-1]) + // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + var Nr = w.length / 4 - 1; + var m0, m1, m2, m3, sub; + if(decrypt) { + m0 = imix[0]; + m1 = imix[1]; + m2 = imix[2]; + m3 = imix[3]; + sub = isbox; + } else { + m0 = mix[0]; + m1 = mix[1]; + m2 = mix[2]; + m3 = mix[3]; + sub = sbox; + } + var a, b, c, d, a2, b2, c2; + a = input[0] ^ w[0]; + b = input[decrypt ? 3 : 1] ^ w[1]; + c = input[2] ^ w[2]; + d = input[decrypt ? 1 : 3] ^ w[3]; + var i = 3; + + /* In order to share code we follow the encryption algorithm when both + encrypting and decrypting. To account for the changes required in the + decryption algorithm, we use different lookup tables when decrypting + and use a modified key schedule to account for the difference in the + order of transformations applied when performing rounds. We also get + key rounds in reverse order (relative to encryption). */ + for(var round = 1; round < Nr; ++round) { + /* As described above, we'll be using table lookups to perform the + column mixing. Each column is stored as a word in the state (the + array 'input' has one column as a word at each index). In order to + mix a column, we perform these transformations on each row in c, + which is 1 byte in each word. The new column for c0 is c'0: + + m0 m1 m2 m3 + r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 + r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 + r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 + r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 + + So using mix tables where c0 is a word with r0 being its upper + 8 bits and r3 being its lower 8 bits: + + m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] + ... + m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] + + Therefore to mix the columns in each word in the state we + do the following (& 255 omitted for brevity): + c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + + However, before mixing, the algorithm requires us to perform + ShiftRows(). The ShiftRows() transformation cyclically shifts the + last 3 rows of the state over different offsets. The first row + (r = 0) is not shifted. + + s'_r,c = s_r,(c + shift(r, Nb) mod Nb + for 0 < r < 4 and 0 <= c < Nb and + shift(1, 4) = 1 + shift(2, 4) = 2 + shift(3, 4) = 3. + + This causes the first byte in r = 1 to be moved to the end of + the row, the first 2 bytes in r = 2 to be moved to the end of + the row, the first 3 bytes in r = 3 to be moved to the end of + the row: + + r1: [c0 c1 c2 c3] => [c1 c2 c3 c0] + r2: [c0 c1 c2 c3] [c2 c3 c0 c1] + r3: [c0 c1 c2 c3] [c3 c0 c1 c2] + + We can make these substitutions inline with our column mixing to + generate an updated set of equations to produce each word in the + state (note the columns have changed positions): + + c0 c1 c2 c3 => c0 c1 c2 c3 + c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte) + c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes) + c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes) + + Therefore: + + c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3 + c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3 + c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3 + c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3 + + c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0 + c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0 + c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0 + c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0 + + ... and so forth for c'2 and c'3. The important distinction is + that the columns are cycling, with c0 being used with the m0 + map when calculating c0, but c1 being used with the m0 map when + calculating c1 ... and so forth. + + When performing the inverse we transform the mirror image and + skip the bottom row, instead of the top one, and move upwards: + + c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption + c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes) + c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption + c3 c2 c1 c0 c3 c2 c1 c0 + + If you compare the resulting matrices for ShiftRows()+MixColumns() + and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are + different (in encrypt mode vs. decrypt mode). So in order to use + the same code to handle both encryption and decryption, we will + need to do some mapping. + + If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be + a row number in the state, then the resulting matrix in encryption + mode for applying the above transformations would be: + + r1: a b c d + r2: b c d a + r3: c d a b + r4: d a b c + + If we did the same in decryption mode we would get: + + r1: a d c b + r2: b a d c + r3: c b a d + r4: d c b a + + If instead we swap d and b (set b=c3 and d=c1), then we get: + + r1: a b c d + r2: d a b c + r3: c d a b + r4: b c d a + + Now the 1st and 3rd rows are the same as the encryption matrix. All + we need to do then to make the mapping exactly the same is to swap + the 2nd and 4th rows when in decryption mode. To do this without + having to do it on each iteration, we swapped the 2nd and 4th rows + in the decryption key schedule. We also have to do the swap above + when we first pull in the input and when we set the final output. */ + a2 = + m0[a >>> 24] ^ + m1[b >>> 16 & 255] ^ + m2[c >>> 8 & 255] ^ + m3[d & 255] ^ w[++i]; + b2 = + m0[b >>> 24] ^ + m1[c >>> 16 & 255] ^ + m2[d >>> 8 & 255] ^ + m3[a & 255] ^ w[++i]; + c2 = + m0[c >>> 24] ^ + m1[d >>> 16 & 255] ^ + m2[a >>> 8 & 255] ^ + m3[b & 255] ^ w[++i]; + d = + m0[d >>> 24] ^ + m1[a >>> 16 & 255] ^ + m2[b >>> 8 & 255] ^ + m3[c & 255] ^ w[++i]; + a = a2; + b = b2; + c = c2; + } + + /* + Encrypt: + SubBytes(state) + ShiftRows(state) + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + + Decrypt: + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[0, Nb-1]) + */ + // Note: rows are shifted inline + output[0] = + (sub[a >>> 24] << 24) ^ + (sub[b >>> 16 & 255] << 16) ^ + (sub[c >>> 8 & 255] << 8) ^ + (sub[d & 255]) ^ w[++i]; + output[decrypt ? 3 : 1] = + (sub[b >>> 24] << 24) ^ + (sub[c >>> 16 & 255] << 16) ^ + (sub[d >>> 8 & 255] << 8) ^ + (sub[a & 255]) ^ w[++i]; + output[2] = + (sub[c >>> 24] << 24) ^ + (sub[d >>> 16 & 255] << 16) ^ + (sub[a >>> 8 & 255] << 8) ^ + (sub[b & 255]) ^ w[++i]; + output[decrypt ? 1 : 3] = + (sub[d >>> 24] << 24) ^ + (sub[a >>> 16 & 255] << 16) ^ + (sub[b >>> 8 & 255] << 8) ^ + (sub[c & 255]) ^ w[++i]; +} + +/** + * Deprecated. Instead, use: + * + * forge.cipher.createCipher('AES-', key); + * forge.cipher.createDecipher('AES-', key); + * + * Creates a deprecated AES cipher object. This object's mode will default to + * CBC (cipher-block-chaining). + * + * The key and iv may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param options the options to use. + * key the symmetric key to use. + * output the buffer to write to. + * decrypt true for decryption, false for encryption. + * mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +function _createCipher(options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'AES-' + mode; + + var cipher; + if(options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + + // backwards compatible start API + var start = cipher.start; + cipher.start = function(iv, options) { + // backwards compatibility: support second arg as output buffer + var output = null; + if(options instanceof forge.util.ByteBuffer) { + output = options; + options = {}; + } + options = options || {}; + options.output = output; + options.iv = iv; + start.call(cipher, options); + }; + + return cipher; +} + + +/***/ }), + +/***/ 1449: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * A Javascript implementation of AES Cipher Suites for TLS. + * + * @author Dave Longley + * + * Copyright (c) 2009-2015 Digital Bazaar, Inc. + * + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7994); +__nccwpck_require__(9167); + +var tls = module.exports = forge.tls; + +/** + * Supported cipher suites. + */ +tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = { + id: [0x00, 0x2f], + name: 'TLS_RSA_WITH_AES_128_CBC_SHA', + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 16; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState: initConnectionState +}; +tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = { + id: [0x00, 0x35], + name: 'TLS_RSA_WITH_AES_256_CBC_SHA', + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 32; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState: initConnectionState +}; + +function initConnectionState(state, c, sp) { + var client = (c.entity === forge.tls.ConnectionEnd.client); + + // cipher setup + state.read.cipherState = { + init: false, + cipher: forge.cipher.createDecipher('AES-CBC', client ? + sp.keys.server_write_key : sp.keys.client_write_key), + iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV + }; + state.write.cipherState = { + init: false, + cipher: forge.cipher.createCipher('AES-CBC', client ? + sp.keys.client_write_key : sp.keys.server_write_key), + iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV + }; + state.read.cipherFunction = decrypt_aes_cbc_sha1; + state.write.cipherFunction = encrypt_aes_cbc_sha1; + + // MAC setup + state.read.macLength = state.write.macLength = sp.mac_length; + state.read.macFunction = state.write.macFunction = tls.hmac_sha1; +} + +/** + * Encrypts the TLSCompressed record into a TLSCipherText record using AES + * in CBC mode. + * + * @param record the TLSCompressed record to encrypt. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +function encrypt_aes_cbc_sha1(record, s) { + var rval = false; + + // append MAC to fragment, update sequence number + var mac = s.macFunction(s.macKey, s.sequenceNumber, record); + record.fragment.putBytes(mac); + s.updateSequenceNumber(); + + // TLS 1.1+ use an explicit IV every time to protect against CBC attacks + var iv; + if(record.version.minor === tls.Versions.TLS_1_0.minor) { + // use the pre-generated IV when initializing for TLS 1.0, otherwise use + // the residue from the previous encryption + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = forge.random.getBytesSync(16); + } + + s.cipherState.init = true; + + // start cipher + var cipher = s.cipherState.cipher; + cipher.start({iv: iv}); + + // TLS 1.1+ write IV into output + if(record.version.minor >= tls.Versions.TLS_1_1.minor) { + cipher.output.putBytes(iv); + } + + // do encryption (default padding is appropriate) + cipher.update(record.fragment); + if(cipher.finish(encrypt_aes_cbc_sha1_padding)) { + // set record fragment to encrypted output + record.fragment = cipher.output; + record.length = record.fragment.length(); + rval = true; + } + + return rval; +} + +/** + * Handles padding for aes_cbc_sha1 in encrypt mode. + * + * @param blockSize the block size. + * @param input the input buffer. + * @param decrypt true in decrypt mode, false in encrypt mode. + * + * @return true on success, false on failure. + */ +function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { + /* The encrypted data length (TLSCiphertext.length) is one more than the sum + of SecurityParameters.block_length, TLSCompressed.length, + SecurityParameters.mac_length, and padding_length. + + The padding may be any length up to 255 bytes long, as long as it results in + the TLSCiphertext.length being an integral multiple of the block length. + Lengths longer than necessary might be desirable to frustrate attacks on a + protocol based on analysis of the lengths of exchanged messages. Each uint8 + in the padding data vector must be filled with the padding length value. + + The padding length should be such that the total size of the + GenericBlockCipher structure is a multiple of the cipher's block length. + Legal values range from zero to 255, inclusive. This length specifies the + length of the padding field exclusive of the padding_length field itself. + + This is slightly different from PKCS#7 because the padding value is 1 + less than the actual number of padding bytes if you include the + padding_length uint8 itself as a padding byte. */ + if(!decrypt) { + // get the number of padding bytes required to reach the blockSize and + // subtract 1 for the padding value (to make room for the padding_length + // uint8) + var padding = blockSize - (input.length() % blockSize); + input.fillWithByte(padding - 1, padding); + } + return true; +} + +/** + * Handles padding for aes_cbc_sha1 in decrypt mode. + * + * @param blockSize the block size. + * @param output the output buffer. + * @param decrypt true in decrypt mode, false in encrypt mode. + * + * @return true on success, false on failure. + */ +function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { + var rval = true; + if(decrypt) { + /* The last byte in the output specifies the number of padding bytes not + including itself. Each of the padding bytes has the same value as that + last byte (known as the padding_length). Here we check all padding + bytes to ensure they have the value of padding_length even if one of + them is bad in order to ward-off timing attacks. */ + var len = output.length(); + var paddingLength = output.last(); + for(var i = len - 1 - paddingLength; i < len - 1; ++i) { + rval = rval && (output.at(i) == paddingLength); + } + if(rval) { + // trim off padding bytes and last padding length byte + output.truncate(paddingLength + 1); + } + } + return rval; +} + +/** + * Decrypts a TLSCipherText record into a TLSCompressed record using + * AES in CBC mode. + * + * @param record the TLSCipherText record to decrypt. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +function decrypt_aes_cbc_sha1(record, s) { + var rval = false; + + var iv; + if(record.version.minor === tls.Versions.TLS_1_0.minor) { + // use pre-generated IV when initializing for TLS 1.0, otherwise use the + // residue from the previous decryption + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + // TLS 1.1+ use an explicit IV every time to protect against CBC attacks + // that is appended to the record fragment + iv = record.fragment.getBytes(16); + } + + s.cipherState.init = true; + + // start cipher + var cipher = s.cipherState.cipher; + cipher.start({iv: iv}); + + // do decryption + cipher.update(record.fragment); + rval = cipher.finish(decrypt_aes_cbc_sha1_padding); + + // even if decryption fails, keep going to minimize timing attacks + + // decrypted data: + // first (len - 20) bytes = application data + // last 20 bytes = MAC + var macLen = s.macLength; + + // create a random MAC to check against should the mac length check fail + // Note: do this regardless of the failure to keep timing consistent + var mac = forge.random.getBytesSync(macLen); + + // get fragment and mac + var len = cipher.output.length(); + if(len >= macLen) { + record.fragment = cipher.output.getBytes(len - macLen); + mac = cipher.output.getBytes(macLen); + } else { + // bad data, but get bytes anyway to try to keep timing consistent + record.fragment = cipher.output.getBytes(); + } + record.fragment = forge.util.createBuffer(record.fragment); + record.length = record.fragment.length(); + + // see if data integrity checks out, update sequence number + var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); + s.updateSequenceNumber(); + rval = compareMacs(s.macKey, mac, mac2) && rval; + return rval; +} + +/** + * Safely compare two MACs. This function will compare two MACs in a way + * that protects against timing attacks. + * + * TODO: Expose elsewhere as a utility API. + * + * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/ + * + * @param key the MAC key to use. + * @param mac1 as a binary-encoded string of bytes. + * @param mac2 as a binary-encoded string of bytes. + * + * @return true if the MACs are the same, false if not. + */ +function compareMacs(key, mac1, mac2) { + var hmac = forge.hmac.create(); + + hmac.start('SHA1', key); + hmac.update(mac1); + mac1 = hmac.digest().getBytes(); + + hmac.start(null, null); + hmac.update(mac2); + mac2 = hmac.digest().getBytes(); + + return mac1 === mac2; +} + + +/***/ }), + +/***/ 9414: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +/** + * Copyright (c) 2019 Digital Bazaar, Inc. + */ + +var forge = __nccwpck_require__(9177); +__nccwpck_require__(9549); +var asn1 = forge.asn1; + +exports.privateKeyValidator = { + // PrivateKeyInfo + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'PrivateKeyInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // privateKeyAlgorithm + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + }] + }, { + // PrivateKey + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + }] +}; + +exports.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, + // capture group for ed25519PublicKey + { + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + composed: true, + captureBitStringValue: 'ed25519PublicKey' + } + // FIXME: this is capture group for rsaPublicKey, use it in this API or + // discard? + /* { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + } */ + ] +}; + + +/***/ }), + +/***/ 9549: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of Abstract Syntax Notation Number One. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + * + * An API for storing data using the Abstract Syntax Notation Number One + * format using DER (Distinguished Encoding Rules) encoding. This encoding is + * commonly used to store data for PKI, i.e. X.509 Certificates, and this + * implementation exists for that purpose. + * + * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract + * syntax of information without restricting the way the information is encoded + * for transmission. It provides a standard that allows for open systems + * communication. ASN.1 defines the syntax of information data and a number of + * simple data types as well as a notation for describing them and specifying + * values for them. + * + * The RSA algorithm creates public and private keys that are often stored in + * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This + * class provides the most basic functionality required to store and load DSA + * keys that are encoded according to ASN.1. + * + * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules) + * and DER (Distinguished Encoding Rules). DER is just a subset of BER that + * has stricter requirements for how data must be encoded. + * + * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type) + * and a byte array for the value of this ASN1 structure which may be data or a + * list of ASN.1 structures. + * + * Each ASN.1 structure using BER is (Tag-Length-Value): + * + * | byte 0 | bytes X | bytes Y | + * |--------|---------|---------- + * | tag | length | value | + * + * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to + * be two or more octets, but that is not supported by this class. A tag is + * only 1 byte. Bits 1-5 give the tag number (ie the data type within a + * particular 'class'), 6 indicates whether or not the ASN.1 value is + * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If + * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set, + * then the class is APPLICATION. If only bit 8 is set, then the class is + * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE. + * The tag numbers for the data types for the class UNIVERSAL are listed below: + * + * UNIVERSAL 0 Reserved for use by the encoding rules + * UNIVERSAL 1 Boolean type + * UNIVERSAL 2 Integer type + * UNIVERSAL 3 Bitstring type + * UNIVERSAL 4 Octetstring type + * UNIVERSAL 5 Null type + * UNIVERSAL 6 Object identifier type + * UNIVERSAL 7 Object descriptor type + * UNIVERSAL 8 External type and Instance-of type + * UNIVERSAL 9 Real type + * UNIVERSAL 10 Enumerated type + * UNIVERSAL 11 Embedded-pdv type + * UNIVERSAL 12 UTF8String type + * UNIVERSAL 13 Relative object identifier type + * UNIVERSAL 14-15 Reserved for future editions + * UNIVERSAL 16 Sequence and Sequence-of types + * UNIVERSAL 17 Set and Set-of types + * UNIVERSAL 18-22, 25-30 Character string types + * UNIVERSAL 23-24 Time types + * + * The length of an ASN.1 structure is specified after the tag identifier. + * There is a definite form and an indefinite form. The indefinite form may + * be used if the encoding is constructed and not all immediately available. + * The indefinite form is encoded using a length byte with only the 8th bit + * set. The end of the constructed object is marked using end-of-contents + * octets (two zero bytes). + * + * The definite form looks like this: + * + * The length may take up 1 or more bytes, it depends on the length of the + * value of the ASN.1 structure. DER encoding requires that if the ASN.1 + * structure has a value that has a length greater than 127, more than 1 byte + * will be used to store its length, otherwise just one byte will be used. + * This is strict. + * + * In the case that the length of the ASN.1 value is less than 127, 1 octet + * (byte) is used to store the "short form" length. The 8th bit has a value of + * 0 indicating the length is "short form" and not "long form" and bits 7-1 + * give the length of the data. (The 8th bit is the left-most, most significant + * bit: also known as big endian or network format). + * + * In the case that the length of the ASN.1 value is greater than 127, 2 to + * 127 octets (bytes) are used to store the "long form" length. The first + * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1 + * give the number of additional octets. All following octets are in base 256 + * with the most significant digit first (typical big-endian binary unsigned + * integer storage). So, for instance, if the length of a value was 257, the + * first byte would be set to: + * + * 10000010 = 130 = 0x82. + * + * This indicates there are 2 octets (base 256) for the length. The second and + * third bytes (the octets just mentioned) would store the length in base 256: + * + * octet 2: 00000001 = 1 * 256^1 = 256 + * octet 3: 00000001 = 1 * 256^0 = 1 + * total = 257 + * + * The algorithm for converting a js integer value of 257 to base-256 is: + * + * var value = 257; + * var bytes = []; + * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first + * bytes[1] = value & 0xFF; // least significant byte last + * + * On the ASN.1 UNIVERSAL Object Identifier (OID) type: + * + * An OID can be written like: "value1.value2.value3...valueN" + * + * The DER encoding rules: + * + * The first byte has the value 40 * value1 + value2. + * The following bytes, if any, encode the remaining values. Each value is + * encoded in base 128, most significant digit first (big endian), with as + * few digits as possible, and the most significant bit of each byte set + * to 1 except the last in each value's encoding. For example: Given the + * OID "1.2.840.113549", its DER encoding is (remember each byte except the + * last one in each encoding is OR'd with 0x80): + * + * byte 1: 40 * 1 + 2 = 42 = 0x2A. + * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648 + * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D + * + * The final value is: 0x2A864886F70D. + * The full OID (including ASN.1 tag and length of 6 bytes) is: + * 0x06062A864886F70D + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); +__nccwpck_require__(1925); + +/* ASN.1 API */ +var asn1 = module.exports = forge.asn1 = forge.asn1 || {}; + +/** + * ASN.1 classes. + */ +asn1.Class = { + UNIVERSAL: 0x00, + APPLICATION: 0x40, + CONTEXT_SPECIFIC: 0x80, + PRIVATE: 0xC0 +}; + +/** + * ASN.1 types. Not all types are supported by this implementation, only + * those necessary to implement a simple PKI are implemented. + */ +asn1.Type = { + NONE: 0, + BOOLEAN: 1, + INTEGER: 2, + BITSTRING: 3, + OCTETSTRING: 4, + NULL: 5, + OID: 6, + ODESC: 7, + EXTERNAL: 8, + REAL: 9, + ENUMERATED: 10, + EMBEDDED: 11, + UTF8: 12, + ROID: 13, + SEQUENCE: 16, + SET: 17, + PRINTABLESTRING: 19, + IA5STRING: 22, + UTCTIME: 23, + GENERALIZEDTIME: 24, + BMPSTRING: 30 +}; + +/** + * Creates a new asn1 object. + * + * @param tagClass the tag class for the object. + * @param type the data type (tag number) for the object. + * @param constructed true if the asn1 object is in constructed form. + * @param value the value for the object, if it is not constructed. + * @param [options] the options to use: + * [bitStringContents] the plain BIT STRING content including padding + * byte. + * + * @return the asn1 object. + */ +asn1.create = function(tagClass, type, constructed, value, options) { + /* An asn1 object has a tagClass, a type, a constructed flag, and a + value. The value's type depends on the constructed flag. If + constructed, it will contain a list of other asn1 objects. If not, + it will contain the ASN.1 value as an array of bytes formatted + according to the ASN.1 data type. */ + + // remove undefined values + if(forge.util.isArray(value)) { + var tmp = []; + for(var i = 0; i < value.length; ++i) { + if(value[i] !== undefined) { + tmp.push(value[i]); + } + } + value = tmp; + } + + var obj = { + tagClass: tagClass, + type: type, + constructed: constructed, + composed: constructed || forge.util.isArray(value), + value: value + }; + if(options && 'bitStringContents' in options) { + // TODO: copy byte buffer if it's a buffer not a string + obj.bitStringContents = options.bitStringContents; + // TODO: add readonly flag to avoid this overhead + // save copy to detect changes + obj.original = asn1.copy(obj); + } + return obj; +}; + +/** + * Copies an asn1 object. + * + * @param obj the asn1 object. + * @param [options] copy options: + * [excludeBitStringContents] true to not copy bitStringContents + * + * @return the a copy of the asn1 object. + */ +asn1.copy = function(obj, options) { + var copy; + + if(forge.util.isArray(obj)) { + copy = []; + for(var i = 0; i < obj.length; ++i) { + copy.push(asn1.copy(obj[i], options)); + } + return copy; + } + + if(typeof obj === 'string') { + // TODO: copy byte buffer if it's a buffer not a string + return obj; + } + + copy = { + tagClass: obj.tagClass, + type: obj.type, + constructed: obj.constructed, + composed: obj.composed, + value: asn1.copy(obj.value, options) + }; + if(options && !options.excludeBitStringContents) { + // TODO: copy byte buffer if it's a buffer not a string + copy.bitStringContents = obj.bitStringContents; + } + return copy; +}; + +/** + * Compares asn1 objects for equality. + * + * Note this function does not run in constant time. + * + * @param obj1 the first asn1 object. + * @param obj2 the second asn1 object. + * @param [options] compare options: + * [includeBitStringContents] true to compare bitStringContents + * + * @return true if the asn1 objects are equal. + */ +asn1.equals = function(obj1, obj2, options) { + if(forge.util.isArray(obj1)) { + if(!forge.util.isArray(obj2)) { + return false; + } + if(obj1.length !== obj2.length) { + return false; + } + for(var i = 0; i < obj1.length; ++i) { + if(!asn1.equals(obj1[i], obj2[i])) { + return false; + } + } + return true; + } + + if(typeof obj1 !== typeof obj2) { + return false; + } + + if(typeof obj1 === 'string') { + return obj1 === obj2; + } + + var equal = obj1.tagClass === obj2.tagClass && + obj1.type === obj2.type && + obj1.constructed === obj2.constructed && + obj1.composed === obj2.composed && + asn1.equals(obj1.value, obj2.value); + if(options && options.includeBitStringContents) { + equal = equal && (obj1.bitStringContents === obj2.bitStringContents); + } + + return equal; +}; + +/** + * Gets the length of a BER-encoded ASN.1 value. + * + * In case the length is not specified, undefined is returned. + * + * @param b the BER-encoded ASN.1 byte buffer, starting with the first + * length byte. + * + * @return the length of the BER-encoded ASN.1 value or undefined. + */ +asn1.getBerValueLength = function(b) { + // TODO: move this function and related DER/BER functions to a der.js + // file; better abstract ASN.1 away from der/ber. + var b2 = b.getByte(); + if(b2 === 0x80) { + return undefined; + } + + // see if the length is "short form" or "long form" (bit 8 set) + var length; + var longForm = b2 & 0x80; + if(!longForm) { + // length is just the first byte + length = b2; + } else { + // the number of bytes the length is specified in bits 7 through 1 + // and each length byte is in big-endian base-256 + length = b.getInt((b2 & 0x7F) << 3); + } + return length; +}; + +/** + * Check if the byte buffer has enough bytes. Throws an Error if not. + * + * @param bytes the byte buffer to parse from. + * @param remaining the bytes remaining in the current parsing state. + * @param n the number of bytes the buffer must have. + */ +function _checkBufferLength(bytes, remaining, n) { + if(n > remaining) { + var error = new Error('Too few bytes to parse DER.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = n; + throw error; + } +} + +/** + * Gets the length of a BER-encoded ASN.1 value. + * + * In case the length is not specified, undefined is returned. + * + * @param bytes the byte buffer to parse from. + * @param remaining the bytes remaining in the current parsing state. + * + * @return the length of the BER-encoded ASN.1 value or undefined. + */ +var _getValueLength = function(bytes, remaining) { + // TODO: move this function and related DER/BER functions to a der.js + // file; better abstract ASN.1 away from der/ber. + // fromDer already checked that this byte exists + var b2 = bytes.getByte(); + remaining--; + if(b2 === 0x80) { + return undefined; + } + + // see if the length is "short form" or "long form" (bit 8 set) + var length; + var longForm = b2 & 0x80; + if(!longForm) { + // length is just the first byte + length = b2; + } else { + // the number of bytes the length is specified in bits 7 through 1 + // and each length byte is in big-endian base-256 + var longFormBytes = b2 & 0x7F; + _checkBufferLength(bytes, remaining, longFormBytes); + length = bytes.getInt(longFormBytes << 3); + } + // FIXME: this will only happen for 32 bit getInt with high bit set + if(length < 0) { + throw new Error('Negative length: ' + length); + } + return length; +}; + +/** + * Parses an asn1 object from a byte buffer in DER format. + * + * @param bytes the byte buffer to parse from. + * @param [strict] true to be strict when checking value lengths, false to + * allow truncated values (default: true). + * @param [options] object with options or boolean strict flag + * [strict] true to be strict when checking value lengths, false to + * allow truncated values (default: true). + * [parseAllBytes] true to ensure all bytes are parsed + * (default: true) + * [decodeBitStrings] true to attempt to decode the content of + * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that + * without schema support to understand the data context this can + * erroneously decode values that happen to be valid ASN.1. This + * flag will be deprecated or removed as soon as schema support is + * available. (default: true) + * + * @throws Will throw an error for various malformed input conditions. + * + * @return the parsed asn1 object. + */ +asn1.fromDer = function(bytes, options) { + if(options === undefined) { + options = { + strict: true, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if(typeof options === 'boolean') { + options = { + strict: options, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if(!('strict' in options)) { + options.strict = true; + } + if(!('parseAllBytes' in options)) { + options.parseAllBytes = true; + } + if(!('decodeBitStrings' in options)) { + options.decodeBitStrings = true; + } + + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + var byteCount = bytes.length(); + var value = _fromDer(bytes, bytes.length(), 0, options); + if(options.parseAllBytes && bytes.length() !== 0) { + var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.'); + error.byteCount = byteCount; + error.remaining = bytes.length(); + throw error; + } + return value; +}; + +/** + * Internal function to parse an asn1 object from a byte buffer in DER format. + * + * @param bytes the byte buffer to parse from. + * @param remaining the number of bytes remaining for this chunk. + * @param depth the current parsing depth. + * @param options object with same options as fromDer(). + * + * @return the parsed asn1 object. + */ +function _fromDer(bytes, remaining, depth, options) { + // temporary storage for consumption calculations + var start; + + // minimum length for ASN.1 DER structure is 2 + _checkBufferLength(bytes, remaining, 2); + + // get the first byte + var b1 = bytes.getByte(); + // consumed one byte + remaining--; + + // get the tag class + var tagClass = (b1 & 0xC0); + + // get the type (bits 1-5) + var type = b1 & 0x1F; + + // get the variable value length and adjust remaining bytes + start = bytes.length(); + var length = _getValueLength(bytes, remaining); + remaining -= start - bytes.length(); + + // ensure there are enough bytes to get the value + if(length !== undefined && length > remaining) { + if(options.strict) { + var error = new Error('Too few bytes to read ASN.1 value.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = length; + throw error; + } + // Note: be lenient with truncated values and use remaining state bytes + length = remaining; + } + + // value storage + var value; + // possible BIT STRING contents storage + var bitStringContents; + + // constructed flag is bit 6 (32 = 0x20) of the first byte + var constructed = ((b1 & 0x20) === 0x20); + if(constructed) { + // parse child asn1 objects from the value + value = []; + if(length === undefined) { + // asn1 object of indefinite length, read until end tag + for(;;) { + _checkBufferLength(bytes, remaining, 2); + if(bytes.bytes(2) === String.fromCharCode(0, 0)) { + bytes.getBytes(2); + remaining -= 2; + break; + } + start = bytes.length(); + value.push(_fromDer(bytes, remaining, depth + 1, options)); + remaining -= start - bytes.length(); + } + } else { + // parsing asn1 object of definite length + while(length > 0) { + start = bytes.length(); + value.push(_fromDer(bytes, length, depth + 1, options)); + remaining -= start - bytes.length(); + length -= start - bytes.length(); + } + } + } + + // if a BIT STRING, save the contents including padding + if(value === undefined && tagClass === asn1.Class.UNIVERSAL && + type === asn1.Type.BITSTRING) { + bitStringContents = bytes.bytes(length); + } + + // determine if a non-constructed value should be decoded as a composed + // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs) + // can be used this way. + if(value === undefined && options.decodeBitStrings && + tagClass === asn1.Class.UNIVERSAL && + // FIXME: OCTET STRINGs not yet supported here + // .. other parts of forge expect to decode OCTET STRINGs manually + (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) && + length > 1) { + // save read position + var savedRead = bytes.read; + var savedRemaining = remaining; + var unused = 0; + if(type === asn1.Type.BITSTRING) { + /* The first octet gives the number of bits by which the length of the + bit string is less than the next multiple of eight (this is called + the "number of unused bits"). + + The second and following octets give the value of the bit string + converted to an octet string. */ + _checkBufferLength(bytes, remaining, 1); + unused = bytes.getByte(); + remaining--; + } + // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs + if(unused === 0) { + try { + // attempt to parse child asn1 object from the value + // (stored in array to signal composed value) + start = bytes.length(); + var subOptions = { + // enforce strict mode to avoid parsing ASN.1 from plain data + strict: true, + decodeBitStrings: true + }; + var composed = _fromDer(bytes, remaining, depth + 1, subOptions); + var used = start - bytes.length(); + remaining -= used; + if(type == asn1.Type.BITSTRING) { + used++; + } + + // if the data all decoded and the class indicates UNIVERSAL or + // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object + var tc = composed.tagClass; + if(used === length && + (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { + value = [composed]; + } + } catch(ex) { + } + } + if(value === undefined) { + // restore read position + bytes.read = savedRead; + remaining = savedRemaining; + } + } + + if(value === undefined) { + // asn1 not constructed or composed, get raw value + // TODO: do DER to OID conversion and vice-versa in .toDer? + + if(length === undefined) { + if(options.strict) { + throw new Error('Non-constructed ASN.1 object of indefinite length.'); + } + // be lenient and use remaining state bytes + length = remaining; + } + + if(type === asn1.Type.BMPSTRING) { + value = ''; + for(; length > 0; length -= 2) { + _checkBufferLength(bytes, remaining, 2); + value += String.fromCharCode(bytes.getInt16()); + remaining -= 2; + } + } else { + value = bytes.getBytes(length); + remaining -= length; + } + } + + // add BIT STRING contents if available + var asn1Options = bitStringContents === undefined ? null : { + bitStringContents: bitStringContents + }; + + // create and return asn1 object + return asn1.create(tagClass, type, constructed, value, asn1Options); +} + +/** + * Converts the given asn1 object to a buffer of bytes in DER format. + * + * @param asn1 the asn1 object to convert to bytes. + * + * @return the buffer of bytes. + */ +asn1.toDer = function(obj) { + var bytes = forge.util.createBuffer(); + + // build the first byte + var b1 = obj.tagClass | obj.type; + + // for storing the ASN.1 value + var value = forge.util.createBuffer(); + + // use BIT STRING contents if available and data not changed + var useBitStringContents = false; + if('bitStringContents' in obj) { + useBitStringContents = true; + if(obj.original) { + useBitStringContents = asn1.equals(obj, obj.original); + } + } + + if(useBitStringContents) { + value.putBytes(obj.bitStringContents); + } else if(obj.composed) { + // if composed, use each child asn1 object's DER bytes as value + // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed + // from other asn1 objects + if(obj.constructed) { + b1 |= 0x20; + } else { + // type is a bit string, add unused bits of 0x00 + value.putByte(0x00); + } + + // add all of the child DER bytes together + for(var i = 0; i < obj.value.length; ++i) { + if(obj.value[i] !== undefined) { + value.putBuffer(asn1.toDer(obj.value[i])); + } + } + } else { + // use asn1.value directly + if(obj.type === asn1.Type.BMPSTRING) { + for(var i = 0; i < obj.value.length; ++i) { + value.putInt16(obj.value.charCodeAt(i)); + } + } else { + // ensure integer is minimally-encoded + // TODO: should all leading bytes be stripped vs just one? + // .. ex '00 00 01' => '01'? + if(obj.type === asn1.Type.INTEGER && + obj.value.length > 1 && + // leading 0x00 for positive integer + ((obj.value.charCodeAt(0) === 0 && + (obj.value.charCodeAt(1) & 0x80) === 0) || + // leading 0xFF for negative integer + (obj.value.charCodeAt(0) === 0xFF && + (obj.value.charCodeAt(1) & 0x80) === 0x80))) { + value.putBytes(obj.value.substr(1)); + } else { + value.putBytes(obj.value); + } + } + } + + // add tag byte + bytes.putByte(b1); + + // use "short form" encoding + if(value.length() <= 127) { + // one byte describes the length + // bit 8 = 0 and bits 7-1 = length + bytes.putByte(value.length() & 0x7F); + } else { + // use "long form" encoding + // 2 to 127 bytes describe the length + // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes + // other bytes: length in base 256, big-endian + var len = value.length(); + var lenBytes = ''; + do { + lenBytes += String.fromCharCode(len & 0xFF); + len = len >>> 8; + } while(len > 0); + + // set first byte to # bytes used to store the length and turn on + // bit 8 to indicate long-form length is used + bytes.putByte(lenBytes.length | 0x80); + + // concatenate length bytes in reverse since they were generated + // little endian and we need big endian + for(var i = lenBytes.length - 1; i >= 0; --i) { + bytes.putByte(lenBytes.charCodeAt(i)); + } + } + + // concatenate value bytes + bytes.putBuffer(value); + return bytes; +}; + +/** + * Converts an OID dot-separated string to a byte buffer. The byte buffer + * contains only the DER-encoded value, not any tag or length bytes. + * + * @param oid the OID dot-separated string. + * + * @return the byte buffer. + */ +asn1.oidToDer = function(oid) { + // split OID into individual values + var values = oid.split('.'); + var bytes = forge.util.createBuffer(); + + // first byte is 40 * value1 + value2 + bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); + // other bytes are each value in base 128 with 8th bit set except for + // the last byte for each value + var last, valueBytes, value, b; + for(var i = 2; i < values.length; ++i) { + // produce value bytes in reverse because we don't know how many + // bytes it will take to store the value + last = true; + valueBytes = []; + value = parseInt(values[i], 10); + do { + b = value & 0x7F; + value = value >>> 7; + // if value is not last, then turn on 8th bit + if(!last) { + b |= 0x80; + } + valueBytes.push(b); + last = false; + } while(value > 0); + + // add value bytes in reverse (needs to be in big endian) + for(var n = valueBytes.length - 1; n >= 0; --n) { + bytes.putByte(valueBytes[n]); + } + } + + return bytes; +}; + +/** + * Converts a DER-encoded byte buffer to an OID dot-separated string. The + * byte buffer should contain only the DER-encoded value, not any tag or + * length bytes. + * + * @param bytes the byte buffer. + * + * @return the OID dot-separated string. + */ +asn1.derToOid = function(bytes) { + var oid; + + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + // first byte is 40 * value1 + value2 + var b = bytes.getByte(); + oid = Math.floor(b / 40) + '.' + (b % 40); + + // other bytes are each value in base 128 with 8th bit set except for + // the last byte for each value + var value = 0; + while(bytes.length() > 0) { + b = bytes.getByte(); + value = value << 7; + // not the last byte for the value + if(b & 0x80) { + value += b & 0x7F; + } else { + // last byte + oid += '.' + (value + b); + value = 0; + } + } + + return oid; +}; + +/** + * Converts a UTCTime value to a date. + * + * Note: GeneralizedTime has 4 digits for the year and is used for X.509 + * dates past 2049. Parsing that structure hasn't been implemented yet. + * + * @param utc the UTCTime value to convert. + * + * @return the date. + */ +asn1.utcTimeToDate = function(utc) { + /* The following formats can be used: + + YYMMDDhhmmZ + YYMMDDhhmm+hh'mm' + YYMMDDhhmm-hh'mm' + YYMMDDhhmmssZ + YYMMDDhhmmss+hh'mm' + YYMMDDhhmmss-hh'mm' + + Where: + + YY is the least significant two digits of the year + MM is the month (01 to 12) + DD is the day (01 to 31) + hh is the hour (00 to 23) + mm are the minutes (00 to 59) + ss are the seconds (00 to 59) + Z indicates that local time is GMT, + indicates that local time is + later than GMT, and - indicates that local time is earlier than GMT + hh' is the absolute value of the offset from GMT in hours + mm' is the absolute value of the offset from GMT in minutes */ + var date = new Date(); + + // if YY >= 50 use 19xx, if YY < 50 use 20xx + var year = parseInt(utc.substr(0, 2), 10); + year = (year >= 50) ? 1900 + year : 2000 + year; + var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month + var DD = parseInt(utc.substr(4, 2), 10); + var hh = parseInt(utc.substr(6, 2), 10); + var mm = parseInt(utc.substr(8, 2), 10); + var ss = 0; + + // not just YYMMDDhhmmZ + if(utc.length > 11) { + // get character after minutes + var c = utc.charAt(10); + var end = 10; + + // see if seconds are present + if(c !== '+' && c !== '-') { + // get seconds + ss = parseInt(utc.substr(10, 2), 10); + end += 2; + } + } + + // update date + date.setUTCFullYear(year, MM, DD); + date.setUTCHours(hh, mm, ss, 0); + + if(end) { + // get +/- after end of time + c = utc.charAt(end); + if(c === '+' || c === '-') { + // get hours+minutes offset + var hhoffset = parseInt(utc.substr(end + 1, 2), 10); + var mmoffset = parseInt(utc.substr(end + 4, 2), 10); + + // calculate offset in milliseconds + var offset = hhoffset * 60 + mmoffset; + offset *= 60000; + + // apply offset + if(c === '+') { + date.setTime(+date - offset); + } else { + date.setTime(+date + offset); + } + } + } + + return date; +}; + +/** + * Converts a GeneralizedTime value to a date. + * + * @param gentime the GeneralizedTime value to convert. + * + * @return the date. + */ +asn1.generalizedTimeToDate = function(gentime) { + /* The following formats can be used: + + YYYYMMDDHHMMSS + YYYYMMDDHHMMSS.fff + YYYYMMDDHHMMSSZ + YYYYMMDDHHMMSS.fffZ + YYYYMMDDHHMMSS+hh'mm' + YYYYMMDDHHMMSS.fff+hh'mm' + YYYYMMDDHHMMSS-hh'mm' + YYYYMMDDHHMMSS.fff-hh'mm' + + Where: + + YYYY is the year + MM is the month (01 to 12) + DD is the day (01 to 31) + hh is the hour (00 to 23) + mm are the minutes (00 to 59) + ss are the seconds (00 to 59) + .fff is the second fraction, accurate to three decimal places + Z indicates that local time is GMT, + indicates that local time is + later than GMT, and - indicates that local time is earlier than GMT + hh' is the absolute value of the offset from GMT in hours + mm' is the absolute value of the offset from GMT in minutes */ + var date = new Date(); + + var YYYY = parseInt(gentime.substr(0, 4), 10); + var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month + var DD = parseInt(gentime.substr(6, 2), 10); + var hh = parseInt(gentime.substr(8, 2), 10); + var mm = parseInt(gentime.substr(10, 2), 10); + var ss = parseInt(gentime.substr(12, 2), 10); + var fff = 0; + var offset = 0; + var isUTC = false; + + if(gentime.charAt(gentime.length - 1) === 'Z') { + isUTC = true; + } + + var end = gentime.length - 5, c = gentime.charAt(end); + if(c === '+' || c === '-') { + // get hours+minutes offset + var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); + var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); + + // calculate offset in milliseconds + offset = hhoffset * 60 + mmoffset; + offset *= 60000; + + // apply offset + if(c === '+') { + offset *= -1; + } + + isUTC = true; + } + + // check for second fraction + if(gentime.charAt(14) === '.') { + fff = parseFloat(gentime.substr(14), 10) * 1000; + } + + if(isUTC) { + date.setUTCFullYear(YYYY, MM, DD); + date.setUTCHours(hh, mm, ss, fff); + + // apply offset + date.setTime(+date + offset); + } else { + date.setFullYear(YYYY, MM, DD); + date.setHours(hh, mm, ss, fff); + } + + return date; +}; + +/** + * Converts a date to a UTCTime value. + * + * Note: GeneralizedTime has 4 digits for the year and is used for X.509 + * dates past 2049. Converting to a GeneralizedTime hasn't been + * implemented yet. + * + * @param date the date to convert. + * + * @return the UTCTime value. + */ +asn1.dateToUtcTime = function(date) { + // TODO: validate; currently assumes proper format + if(typeof date === 'string') { + return date; + } + + var rval = ''; + + // create format YYMMDDhhmmssZ + var format = []; + format.push(('' + date.getUTCFullYear()).substr(2)); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + + // ensure 2 digits are used for each format entry + for(var i = 0; i < format.length; ++i) { + if(format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + + return rval; +}; + +/** + * Converts a date to a GeneralizedTime value. + * + * @param date the date to convert. + * + * @return the GeneralizedTime value as a string. + */ +asn1.dateToGeneralizedTime = function(date) { + // TODO: validate; currently assumes proper format + if(typeof date === 'string') { + return date; + } + + var rval = ''; + + // create format YYYYMMDDHHMMSSZ + var format = []; + format.push('' + date.getUTCFullYear()); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + + // ensure 2 digits are used for each format entry + for(var i = 0; i < format.length; ++i) { + if(format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + + return rval; +}; + +/** + * Converts a javascript integer to a DER-encoded byte buffer to be used + * as the value for an INTEGER type. + * + * @param x the integer. + * + * @return the byte buffer. + */ +asn1.integerToDer = function(x) { + var rval = forge.util.createBuffer(); + if(x >= -0x80 && x < 0x80) { + return rval.putSignedInt(x, 8); + } + if(x >= -0x8000 && x < 0x8000) { + return rval.putSignedInt(x, 16); + } + if(x >= -0x800000 && x < 0x800000) { + return rval.putSignedInt(x, 24); + } + if(x >= -0x80000000 && x < 0x80000000) { + return rval.putSignedInt(x, 32); + } + var error = new Error('Integer too large; max is 32-bits.'); + error.integer = x; + throw error; +}; + +/** + * Converts a DER-encoded byte buffer to a javascript integer. This is + * typically used to decode the value of an INTEGER type. + * + * @param bytes the byte buffer. + * + * @return the integer. + */ +asn1.derToInteger = function(bytes) { + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + var n = bytes.length() * 8; + if(n > 32) { + throw new Error('Integer too large; max is 32-bits.'); + } + return bytes.getSignedInt(n); +}; + +/** + * Validates that the given ASN.1 object is at least a super set of the + * given ASN.1 structure. Only tag classes and types are checked. An + * optional map may also be provided to capture ASN.1 values while the + * structure is checked. + * + * To capture an ASN.1 value, set an object in the validator's 'capture' + * parameter to the key to use in the capture map. To capture the full + * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including + * the leading unused bits counter byte, specify 'captureBitStringContents'. + * To capture BIT STRING bytes, without the leading unused bits counter byte, + * specify 'captureBitStringValue'. + * + * Objects in the validator may set a field 'optional' to true to indicate + * that it isn't necessary to pass validation. + * + * @param obj the ASN.1 object to validate. + * @param v the ASN.1 structure validator. + * @param capture an optional map to capture values in. + * @param errors an optional array for storing validation errors. + * + * @return true on success, false on failure. + */ +asn1.validate = function(obj, v, capture, errors) { + var rval = false; + + // ensure tag class and type are the same if specified + if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') && + (obj.type === v.type || typeof(v.type) === 'undefined')) { + // ensure constructed flag is the same if specified + if(obj.constructed === v.constructed || + typeof(v.constructed) === 'undefined') { + rval = true; + + // handle sub values + if(v.value && forge.util.isArray(v.value)) { + var j = 0; + for(var i = 0; rval && i < v.value.length; ++i) { + rval = v.value[i].optional || false; + if(obj.value[j]) { + rval = asn1.validate(obj.value[j], v.value[i], capture, errors); + if(rval) { + ++j; + } else if(v.value[i].optional) { + rval = true; + } + } + if(!rval && errors) { + errors.push( + '[' + v.name + '] ' + + 'Tag class "' + v.tagClass + '", type "' + + v.type + '" expected value length "' + + v.value.length + '", got "' + + obj.value.length + '"'); + } + } + } + + if(rval && capture) { + if(v.capture) { + capture[v.capture] = obj.value; + } + if(v.captureAsn1) { + capture[v.captureAsn1] = obj; + } + if(v.captureBitStringContents && 'bitStringContents' in obj) { + capture[v.captureBitStringContents] = obj.bitStringContents; + } + if(v.captureBitStringValue && 'bitStringContents' in obj) { + var value; + if(obj.bitStringContents.length < 2) { + capture[v.captureBitStringValue] = ''; + } else { + // FIXME: support unused bits with data shifting + var unused = obj.bitStringContents.charCodeAt(0); + if(unused !== 0) { + throw new Error( + 'captureBitStringValue only supported for zero unused bits'); + } + capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); + } + } + } + } else if(errors) { + errors.push( + '[' + v.name + '] ' + + 'Expected constructed "' + v.constructed + '", got "' + + obj.constructed + '"'); + } + } else if(errors) { + if(obj.tagClass !== v.tagClass) { + errors.push( + '[' + v.name + '] ' + + 'Expected tag class "' + v.tagClass + '", got "' + + obj.tagClass + '"'); + } + if(obj.type !== v.type) { + errors.push( + '[' + v.name + '] ' + + 'Expected type "' + v.type + '", got "' + obj.type + '"'); + } + } + return rval; +}; + +// regex for testing for non-latin characters +var _nonLatinRegex = /[^\\u0000-\\u00ff]/; + +/** + * Pretty prints an ASN.1 object to a string. + * + * @param obj the object to write out. + * @param level the level in the tree. + * @param indentation the indentation to use. + * + * @return the string. + */ +asn1.prettyPrint = function(obj, level, indentation) { + var rval = ''; + + // set default level and indentation + level = level || 0; + indentation = indentation || 2; + + // start new line for deep levels + if(level > 0) { + rval += '\n'; + } + + // create indent + var indent = ''; + for(var i = 0; i < level * indentation; ++i) { + indent += ' '; + } + + // print class:type + rval += indent + 'Tag: '; + switch(obj.tagClass) { + case asn1.Class.UNIVERSAL: + rval += 'Universal:'; + break; + case asn1.Class.APPLICATION: + rval += 'Application:'; + break; + case asn1.Class.CONTEXT_SPECIFIC: + rval += 'Context-Specific:'; + break; + case asn1.Class.PRIVATE: + rval += 'Private:'; + break; + } + + if(obj.tagClass === asn1.Class.UNIVERSAL) { + rval += obj.type; + + // known types + switch(obj.type) { + case asn1.Type.NONE: + rval += ' (None)'; + break; + case asn1.Type.BOOLEAN: + rval += ' (Boolean)'; + break; + case asn1.Type.INTEGER: + rval += ' (Integer)'; + break; + case asn1.Type.BITSTRING: + rval += ' (Bit string)'; + break; + case asn1.Type.OCTETSTRING: + rval += ' (Octet string)'; + break; + case asn1.Type.NULL: + rval += ' (Null)'; + break; + case asn1.Type.OID: + rval += ' (Object Identifier)'; + break; + case asn1.Type.ODESC: + rval += ' (Object Descriptor)'; + break; + case asn1.Type.EXTERNAL: + rval += ' (External or Instance of)'; + break; + case asn1.Type.REAL: + rval += ' (Real)'; + break; + case asn1.Type.ENUMERATED: + rval += ' (Enumerated)'; + break; + case asn1.Type.EMBEDDED: + rval += ' (Embedded PDV)'; + break; + case asn1.Type.UTF8: + rval += ' (UTF8)'; + break; + case asn1.Type.ROID: + rval += ' (Relative Object Identifier)'; + break; + case asn1.Type.SEQUENCE: + rval += ' (Sequence)'; + break; + case asn1.Type.SET: + rval += ' (Set)'; + break; + case asn1.Type.PRINTABLESTRING: + rval += ' (Printable String)'; + break; + case asn1.Type.IA5String: + rval += ' (IA5String (ASCII))'; + break; + case asn1.Type.UTCTIME: + rval += ' (UTC time)'; + break; + case asn1.Type.GENERALIZEDTIME: + rval += ' (Generalized time)'; + break; + case asn1.Type.BMPSTRING: + rval += ' (BMP String)'; + break; + } + } else { + rval += obj.type; + } + + rval += '\n'; + rval += indent + 'Constructed: ' + obj.constructed + '\n'; + + if(obj.composed) { + var subvalues = 0; + var sub = ''; + for(var i = 0; i < obj.value.length; ++i) { + if(obj.value[i] !== undefined) { + subvalues += 1; + sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); + if((i + 1) < obj.value.length) { + sub += ','; + } + } + } + rval += indent + 'Sub values: ' + subvalues + sub; + } else { + rval += indent + 'Value: '; + if(obj.type === asn1.Type.OID) { + var oid = asn1.derToOid(obj.value); + rval += oid; + if(forge.pki && forge.pki.oids) { + if(oid in forge.pki.oids) { + rval += ' (' + forge.pki.oids[oid] + ') '; + } + } + } + if(obj.type === asn1.Type.INTEGER) { + try { + rval += asn1.derToInteger(obj.value); + } catch(ex) { + rval += '0x' + forge.util.bytesToHex(obj.value); + } + } else if(obj.type === asn1.Type.BITSTRING) { + // TODO: shift bits as needed to display without padding + if(obj.value.length > 1) { + // remove unused bits field + rval += '0x' + forge.util.bytesToHex(obj.value.slice(1)); + } else { + rval += '(none)'; + } + // show unused bit count + if(obj.value.length > 0) { + var unused = obj.value.charCodeAt(0); + if(unused == 1) { + rval += ' (1 unused bit shown)'; + } else if(unused > 1) { + rval += ' (' + unused + ' unused bits shown)'; + } + } + } else if(obj.type === asn1.Type.OCTETSTRING) { + if(!_nonLatinRegex.test(obj.value)) { + rval += '(' + obj.value + ') '; + } + rval += '0x' + forge.util.bytesToHex(obj.value); + } else if(obj.type === asn1.Type.UTF8) { + try { + rval += forge.util.decodeUtf8(obj.value); + } catch(e) { + if(e.message === 'URI malformed') { + rval += + '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)'; + } else { + throw e; + } + } + } else if(obj.type === asn1.Type.PRINTABLESTRING || + obj.type === asn1.Type.IA5String) { + rval += obj.value; + } else if(_nonLatinRegex.test(obj.value)) { + rval += '0x' + forge.util.bytesToHex(obj.value); + } else if(obj.value.length === 0) { + rval += '[null]'; + } else { + rval += obj.value; + } + } + + return rval; +}; + + +/***/ }), + +/***/ 2300: +/***/ ((module) => { + +/** + * Base-N/Base-X encoding/decoding functions. + * + * Original implementation from base-x: + * https://github.com/cryptocoinjs/base-x + * + * Which is MIT licensed: + * + * The MIT License (MIT) + * + * Copyright base-x contributors (c) 2016 + * + * 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. + */ +var api = {}; +module.exports = api; + +// baseN alphabet indexes +var _reverseAlphabets = {}; + +/** + * BaseN-encodes a Uint8Array using the given alphabet. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the baseN-encoded output string. + */ +api.encode = function(input, alphabet, maxline) { + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(maxline !== undefined && typeof maxline !== 'number') { + throw new TypeError('"maxline" must be a number.'); + } + + var output = ''; + + if(!(input instanceof Uint8Array)) { + // assume forge byte buffer + output = _encodeWithByteBuffer(input, alphabet); + } else { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length; ++i) { + for(var j = 0, carry = input[i]; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + // deal with leading zeros + for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + } + + if(maxline) { + var regex = new RegExp('.{1,' + maxline + '}', 'g'); + output = output.match(regex).join('\r\n'); + } + + return output; +}; + +/** + * Decodes a baseN-encoded (using the given alphabet) string to a + * Uint8Array. + * + * @param input the baseN-encoded input string. + * + * @return the Uint8Array. + */ +api.decode = function(input, alphabet) { + if(typeof input !== 'string') { + throw new TypeError('"input" must be a string.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + + var table = _reverseAlphabets[alphabet]; + if(!table) { + // compute reverse alphabet + table = _reverseAlphabets[alphabet] = []; + for(var i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + + // remove whitespace characters + input = input.replace(/\s/g, ''); + + var base = alphabet.length; + var first = alphabet.charAt(0); + var bytes = [0]; + for(var i = 0; i < input.length; i++) { + var value = table[input.charCodeAt(i)]; + if(value === undefined) { + return; + } + + for(var j = 0, carry = value; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 0xff; + carry >>= 8; + } + + while(carry > 0) { + bytes.push(carry & 0xff); + carry >>= 8; + } + } + + // deal with leading zeros + for(var k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + + if(typeof Buffer !== 'undefined') { + return Buffer.from(bytes.reverse()); + } + + return new Uint8Array(bytes.reverse()); +}; + +function _encodeWithByteBuffer(input, alphabet) { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length(); ++i) { + for(var j = 0, carry = input.at(i); j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + var output = ''; + + // deal with leading zeros + for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + + return output; +} + + +/***/ }), + +/***/ 7088: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Cipher base API. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); + +module.exports = forge.cipher = forge.cipher || {}; + +// registered algorithms +forge.cipher.algorithms = forge.cipher.algorithms || {}; + +/** + * Creates a cipher object that can be used to encrypt data using the given + * algorithm and key. The algorithm may be provided as a string value for a + * previously registered algorithm or it may be given as a cipher algorithm + * API object. + * + * @param algorithm the algorithm to use, either a string or an algorithm API + * object. + * @param key the key to use, as a binary-encoded string of bytes or a + * byte buffer. + * + * @return the cipher. + */ +forge.cipher.createCipher = function(algorithm, key) { + var api = algorithm; + if(typeof api === 'string') { + api = forge.cipher.getAlgorithm(api); + if(api) { + api = api(); + } + } + if(!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + + // assume block cipher + return new forge.cipher.BlockCipher({ + algorithm: api, + key: key, + decrypt: false + }); +}; + +/** + * Creates a decipher object that can be used to decrypt data using the given + * algorithm and key. The algorithm may be provided as a string value for a + * previously registered algorithm or it may be given as a cipher algorithm + * API object. + * + * @param algorithm the algorithm to use, either a string or an algorithm API + * object. + * @param key the key to use, as a binary-encoded string of bytes or a + * byte buffer. + * + * @return the cipher. + */ +forge.cipher.createDecipher = function(algorithm, key) { + var api = algorithm; + if(typeof api === 'string') { + api = forge.cipher.getAlgorithm(api); + if(api) { + api = api(); + } + } + if(!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + + // assume block cipher + return new forge.cipher.BlockCipher({ + algorithm: api, + key: key, + decrypt: true + }); +}; + +/** + * Registers an algorithm by name. If the name was already registered, the + * algorithm API object will be overwritten. + * + * @param name the name of the algorithm. + * @param algorithm the algorithm API object. + */ +forge.cipher.registerAlgorithm = function(name, algorithm) { + name = name.toUpperCase(); + forge.cipher.algorithms[name] = algorithm; +}; + +/** + * Gets a registered algorithm by name. + * + * @param name the name of the algorithm. + * + * @return the algorithm, if found, null if not. + */ +forge.cipher.getAlgorithm = function(name) { + name = name.toUpperCase(); + if(name in forge.cipher.algorithms) { + return forge.cipher.algorithms[name]; + } + return null; +}; + +var BlockCipher = forge.cipher.BlockCipher = function(options) { + this.algorithm = options.algorithm; + this.mode = this.algorithm.mode; + this.blockSize = this.mode.blockSize; + this._finish = false; + this._input = null; + this.output = null; + this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; + this._decrypt = options.decrypt; + this.algorithm.initialize(options); +}; + +/** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array + * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in + * bytes, then it must be Nb (16) bytes in length. If the IV is given in as + * 32-bit integers, then it must be 4 integers long. + * + * Note: an IV is not required or used in ECB mode. + * + * For GCM-mode, the IV must be given as a binary-encoded string of bytes or + * a byte buffer. The number of bytes should be 12 (96 bits) as recommended + * by NIST SP-800-38D but another length may be given. + * + * @param options the options to use: + * iv the initialization vector to use as a binary-encoded string of + * bytes, null to reuse the last ciphered block from a previous + * update() (this "residue" method is for legacy support only). + * additionalData additional authentication data as a binary-encoded + * string of bytes, for 'GCM' mode, (default: none). + * tagLength desired length of authentication tag, in bits, for + * 'GCM' mode (0-128, default: 128). + * tag the authentication tag to check if decrypting, as a + * binary-encoded string of bytes. + * output the output the buffer to write to, null to create one. + */ +BlockCipher.prototype.start = function(options) { + options = options || {}; + var opts = {}; + for(var key in options) { + opts[key] = options[key]; + } + opts.decrypt = this._decrypt; + this._finish = false; + this._input = forge.util.createBuffer(); + this.output = options.output || forge.util.createBuffer(); + this.mode.start(opts); +}; + +/** + * Updates the next block according to the cipher mode. + * + * @param input the buffer to read from. + */ +BlockCipher.prototype.update = function(input) { + if(input) { + // input given, so empty it into the input buffer + this._input.putBuffer(input); + } + + // do cipher operation until it needs more input and not finished + while(!this._op.call(this.mode, this._input, this.output, this._finish) && + !this._finish) {} + + // free consumed memory from input buffer + this._input.compact(); +}; + +/** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use in CBC mode, null for default, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ +BlockCipher.prototype.finish = function(pad) { + // backwards-compatibility w/deprecated padding API + // Note: will overwrite padding functions even after another start() call + if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { + this.mode.pad = function(input) { + return pad(this.blockSize, input, false); + }; + this.mode.unpad = function(output) { + return pad(this.blockSize, output, true); + }; + } + + // build options for padding and afterFinish functions + var options = {}; + options.decrypt = this._decrypt; + + // get # of bytes that won't fill a block + options.overflow = this._input.length() % this.blockSize; + + if(!this._decrypt && this.mode.pad) { + if(!this.mode.pad(this._input, options)) { + return false; + } + } + + // do final update + this._finish = true; + this.update(); + + if(this._decrypt && this.mode.unpad) { + if(!this.mode.unpad(this.output, options)) { + return false; + } + } + + if(this.mode.afterFinish) { + if(!this.mode.afterFinish(this.output, options)) { + return false; + } + } + + return true; +}; + + +/***/ }), + +/***/ 873: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Supported cipher modes. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); + +forge.cipher = forge.cipher || {}; + +// supported cipher modes +var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {}; + +/** Electronic codebook (ECB) (Don't use this; it's not secure) **/ + +modes.ecb = function(options) { + options = options || {}; + this.name = 'ECB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); +}; + +modes.ecb.prototype.start = function(options) {}; + +modes.ecb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // write output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } +}; + +modes.ecb.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // decrypt block + this.cipher.decrypt(this._inBlock, this._outBlock); + + // write output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } +}; + +modes.ecb.prototype.pad = function(input, options) { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (input.length() === this.blockSize ? + this.blockSize : (this.blockSize - input.length())); + input.fillWithByte(padding, padding); + return true; +}; + +modes.ecb.prototype.unpad = function(output, options) { + // check for error: input data not a multiple of blockSize + if(options.overflow > 0) { + return false; + } + + // ensure padding byte count is valid + var len = output.length(); + var count = output.at(len - 1); + if(count > (this.blockSize << 2)) { + return false; + } + + // trim off padding bytes + output.truncate(count); + return true; +}; + +/** Cipher-block Chaining (CBC) **/ + +modes.cbc = function(options) { + options = options || {}; + this.name = 'CBC'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); +}; + +modes.cbc.prototype.start = function(options) { + // Note: legacy support for using IV residue (has security flaws) + // if IV is null, reuse block from previous processing + if(options.iv === null) { + // must have a previous block + if(!this._prev) { + throw new Error('Invalid IV parameter.'); + } + this._iv = this._prev.slice(0); + } else if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } else { + // save IV as "previous" block + this._iv = transformIV(options.iv, this.blockSize); + this._prev = this._iv.slice(0); + } +}; + +modes.cbc.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + // CBC XOR's IV (or previous block) with plaintext + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._prev[i] ^ input.getInt32(); + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // write output, save previous block + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + this._prev = this._outBlock; +}; + +modes.cbc.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // decrypt block + this.cipher.decrypt(this._inBlock, this._outBlock); + + // write output, save previous ciphered block + // CBC XOR's IV (or previous block) with ciphertext + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._prev[i] ^ this._outBlock[i]); + } + this._prev = this._inBlock.slice(0); +}; + +modes.cbc.prototype.pad = function(input, options) { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (input.length() === this.blockSize ? + this.blockSize : (this.blockSize - input.length())); + input.fillWithByte(padding, padding); + return true; +}; + +modes.cbc.prototype.unpad = function(output, options) { + // check for error: input data not a multiple of blockSize + if(options.overflow > 0) { + return false; + } + + // ensure padding byte count is valid + var len = output.length(); + var count = output.at(len - 1); + if(count > (this.blockSize << 2)) { + return false; + } + + // trim off padding bytes + output.truncate(count); + return true; +}; + +/** Cipher feedback (CFB) **/ + +modes.cfb = function(options) { + options = options || {}; + this.name = 'CFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.cfb.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.cfb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output, write input as output + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; + output.putInt32(this._inBlock[i]); + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output, write input as partial output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; + this._partialOutput.putInt32(this._partialBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +modes.cfb.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block (CFB always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output, write input as output + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + output.putInt32(this._inBlock[i] ^ this._outBlock[i]); + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output, write input as partial output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32(); + this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +/** Output feedback (OFB) **/ + +modes.ofb = function(options) { + options = options || {}; + this.name = 'OFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.ofb.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.ofb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(input.length() === 0) { + return true; + } + + // encrypt block (OFB always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output and update next input + for(var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + this._inBlock[i] = this._outBlock[i]; + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._outBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; + +/** Counter (CTR) **/ + +modes.ctr = function(options) { + options = options || {}; + this.name = 'CTR'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.ctr.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.ctr.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block (CTR always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + } + } else { + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; + } + + // block complete, increment counter (input block) + inc32(this._inBlock); +}; + +modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; + +/** Galois/Counter Mode (GCM) **/ + +modes.gcm = function(options) { + options = options || {}; + this.name = 'GCM'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + + // R is actually this value concatenated with 120 more zero bits, but + // we only XOR against R so the other zeros have no effect -- we just + // apply this value to the first integer in a block + this._R = 0xE1000000; +}; + +modes.gcm.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // ensure IV is a byte buffer + var iv = forge.util.createBuffer(options.iv); + + // no ciphered data processed yet + this._cipherLength = 0; + + // default additional data is none + var additionalData; + if('additionalData' in options) { + additionalData = forge.util.createBuffer(options.additionalData); + } else { + additionalData = forge.util.createBuffer(); + } + + // default tag length is 128 bits + if('tagLength' in options) { + this._tagLength = options.tagLength; + } else { + this._tagLength = 128; + } + + // if tag is given, ensure tag matches tag length + this._tag = null; + if(options.decrypt) { + // save tag to check later + this._tag = forge.util.createBuffer(options.tag).getBytes(); + if(this._tag.length !== (this._tagLength / 8)) { + throw new Error('Authentication tag does not match tag length.'); + } + } + + // create tmp storage for hash calculation + this._hashBlock = new Array(this._ints); + + // no tag generated yet + this.tag = null; + + // generate hash subkey + // (apply block cipher to "zero" block) + this._hashSubkey = new Array(this._ints); + this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); + + // generate table M + // use 4-bit tables (32 component decomposition of a 16 byte value) + // 8-bit tables take more space and are known to have security + // vulnerabilities (in native implementations) + this.componentBits = 4; + this._m = this.generateHashTable(this._hashSubkey, this.componentBits); + + // Note: support IV length different from 96 bits? (only supporting + // 96 bits is recommended by NIST SP-800-38D) + // generate J_0 + var ivLength = iv.length(); + if(ivLength === 12) { + // 96-bit IV + this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; + } else { + // IV is NOT 96-bits + this._j0 = [0, 0, 0, 0]; + while(iv.length() > 0) { + this._j0 = this.ghash( + this._hashSubkey, this._j0, + [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); + } + this._j0 = this.ghash( + this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); + } + + // generate ICB (initial counter block) + this._inBlock = this._j0.slice(0); + inc32(this._inBlock); + this._partialBytes = 0; + + // consume authentication data + additionalData = forge.util.createBuffer(additionalData); + // save additional data length as a BE 64-bit number + this._aDataLength = from64To32(additionalData.length() * 8); + // pad additional data to 128 bit (16 byte) block size + var overflow = additionalData.length() % this.blockSize; + if(overflow) { + additionalData.fillWithByte(0, this.blockSize - overflow); + } + this._s = [0, 0, 0, 0]; + while(additionalData.length() > 0) { + this._s = this.ghash(this._hashSubkey, this._s, [ + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32() + ]); + } +}; + +modes.gcm.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^= input.getInt32()); + } + this._cipherLength += this.blockSize; + } else { + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes <= 0 || finish) { + // handle overflow prior to hashing + if(finish) { + // get block overflow + var overflow = inputLength % this.blockSize; + this._cipherLength += overflow; + // truncate for hash function + this._partialOutput.truncate(this.blockSize - overflow); + } else { + this._cipherLength += this.blockSize; + } + + // get output block for hashing + for(var i = 0; i < this._ints; ++i) { + this._outBlock[i] = this._partialOutput.getInt32(); + } + this._partialOutput.read -= this.blockSize; + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + // block still incomplete, restore input buffer, get partial output, + // and return early + input.read -= this.blockSize; + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; + } + + // update hash block S + this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); + + // increment counter (input block) + inc32(this._inBlock); +}; + +modes.gcm.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + var inputLength = input.length(); + if(inputLength < this.blockSize && !(finish && inputLength > 0)) { + return true; + } + + // encrypt block (GCM always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // increment counter (input block) + inc32(this._inBlock); + + // update hash block S + this._hashBlock[0] = input.getInt32(); + this._hashBlock[1] = input.getInt32(); + this._hashBlock[2] = input.getInt32(); + this._hashBlock[3] = input.getInt32(); + this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); + + // XOR hash input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); + } + + // increment cipher data length + if(inputLength < this.blockSize) { + this._cipherLength += inputLength % this.blockSize; + } else { + this._cipherLength += this.blockSize; + } +}; + +modes.gcm.prototype.afterFinish = function(output, options) { + var rval = true; + + // handle overflow + if(options.decrypt && options.overflow) { + output.truncate(this.blockSize - options.overflow); + } + + // handle authentication tag + this.tag = forge.util.createBuffer(); + + // concatenate additional data length with cipher length + var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); + + // include lengths in hash + this._s = this.ghash(this._hashSubkey, this._s, lengths); + + // do GCTR(J_0, S) + var tag = []; + this.cipher.encrypt(this._j0, tag); + for(var i = 0; i < this._ints; ++i) { + this.tag.putInt32(this._s[i] ^ tag[i]); + } + + // trim tag to length + this.tag.truncate(this.tag.length() % (this._tagLength / 8)); + + // check authentication tag + if(options.decrypt && this.tag.bytes() !== this._tag) { + rval = false; + } + + return rval; +}; + +/** + * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois + * field multiplication. The field, GF(2^128), is defined by the polynomial: + * + * x^128 + x^7 + x^2 + x + 1 + * + * Which is represented in little-endian binary form as: 11100001 (0xe1). When + * the value of a coefficient is 1, a bit is set. The value R, is the + * concatenation of this value and 120 zero bits, yielding a 128-bit value + * which matches the block size. + * + * This function will multiply two elements (vectors of bytes), X and Y, in + * the field GF(2^128). The result is initialized to zero. For each bit of + * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) + * by the current value of Y. For each bit, the value of Y will be raised by + * a power of x (multiplied by the polynomial x). This can be achieved by + * shifting Y once to the right. If the current value of Y, prior to being + * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. + * Otherwise, we must divide by R after shifting to find the remainder. + * + * @param x the first block to multiply by the second. + * @param y the second block to multiply by the first. + * + * @return the block result of the multiplication. + */ +modes.gcm.prototype.multiply = function(x, y) { + var z_i = [0, 0, 0, 0]; + var v_i = y.slice(0); + + // calculate Z_128 (block has 128 bits) + for(var i = 0; i < 128; ++i) { + // if x_i is 0, Z_{i+1} = Z_i (unchanged) + // else Z_{i+1} = Z_i ^ V_i + // get x_i by finding 32-bit int position, then left shift 1 by remainder + var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); + if(x_i) { + z_i[0] ^= v_i[0]; + z_i[1] ^= v_i[1]; + z_i[2] ^= v_i[2]; + z_i[3] ^= v_i[3]; + } + + // if LSB(V_i) is 1, V_i = V_i >> 1 + // else V_i = (V_i >> 1) ^ R + this.pow(v_i, v_i); + } + + return z_i; +}; + +modes.gcm.prototype.pow = function(x, out) { + // if LSB(x) is 1, x = x >>> 1 + // else x = (x >>> 1) ^ R + var lsb = x[3] & 1; + + // always do x >>> 1: + // starting with the rightmost integer, shift each integer to the right + // one bit, pulling in the bit from the integer to the left as its top + // most bit (do this for the last 3 integers) + for(var i = 3; i > 0; --i) { + out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); + } + // shift the first integer normally + out[0] = x[0] >>> 1; + + // if lsb was not set, then polynomial had a degree of 127 and doesn't + // need to divided; otherwise, XOR with R to find the remainder; we only + // need to XOR the first integer since R technically ends w/120 zero bits + if(lsb) { + out[0] ^= this._R; + } +}; + +modes.gcm.prototype.tableMultiply = function(x) { + // assumes 4-bit tables are used + var z = [0, 0, 0, 0]; + for(var i = 0; i < 32; ++i) { + var idx = (i / 8) | 0; + var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; + var ah = this._m[i][x_i]; + z[0] ^= ah[0]; + z[1] ^= ah[1]; + z[2] ^= ah[2]; + z[3] ^= ah[3]; + } + return z; +}; + +/** + * A continuing version of the GHASH algorithm that operates on a single + * block. The hash block, last hash value (Ym) and the new block to hash + * are given. + * + * @param h the hash block. + * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. + * @param x the block to hash. + * + * @return the hashed value (Ym). + */ +modes.gcm.prototype.ghash = function(h, y, x) { + y[0] ^= x[0]; + y[1] ^= x[1]; + y[2] ^= x[2]; + y[3] ^= x[3]; + return this.tableMultiply(y); + //return this.multiply(y, h); +}; + +/** + * Precomputes a table for multiplying against the hash subkey. This + * mechanism provides a substantial speed increase over multiplication + * performed without a table. The table-based multiplication this table is + * for solves X * H by multiplying each component of X by H and then + * composing the results together using XOR. + * + * This function can be used to generate tables with different bit sizes + * for the components, however, this implementation assumes there are + * 32 components of X (which is a 16 byte vector), therefore each component + * takes 4-bits (so the table is constructed with bits=4). + * + * @param h the hash subkey. + * @param bits the bit size for a component. + */ +modes.gcm.prototype.generateHashTable = function(h, bits) { + // TODO: There are further optimizations that would use only the + // first table M_0 (or some variant) along with a remainder table; + // this can be explored in the future + var multiplier = 8 / bits; + var perInt = 4 * multiplier; + var size = 16 * multiplier; + var m = new Array(size); + for(var i = 0; i < size; ++i) { + var tmp = [0, 0, 0, 0]; + var idx = (i / perInt) | 0; + var shft = ((perInt - 1 - (i % perInt)) * bits); + tmp[idx] = (1 << (bits - 1)) << shft; + m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); + } + return m; +}; + +/** + * Generates a table for multiplying against the hash subkey for one + * particular component (out of all possible component values). + * + * @param mid the pre-multiplied value for the middle key of the table. + * @param bits the bit size for a component. + */ +modes.gcm.prototype.generateSubHashTable = function(mid, bits) { + // compute the table quickly by minimizing the number of + // POW operations -- they only need to be performed for powers of 2, + // all other entries can be composed from those powers using XOR + var size = 1 << bits; + var half = size >>> 1; + var m = new Array(size); + m[half] = mid.slice(0); + var i = half >>> 1; + while(i > 0) { + // raise m0[2 * i] and store in m0[i] + this.pow(m[2 * i], m[i] = []); + i >>= 1; + } + i = 2; + while(i < half) { + for(var j = 1; j < i; ++j) { + var m_i = m[i]; + var m_j = m[j]; + m[i + j] = [ + m_i[0] ^ m_j[0], + m_i[1] ^ m_j[1], + m_i[2] ^ m_j[2], + m_i[3] ^ m_j[3] + ]; + } + i *= 2; + } + m[0] = [0, 0, 0, 0]; + /* Note: We could avoid storing these by doing composition during multiply + calculate top half using composition by speed is preferred. */ + for(i = half + 1; i < size; ++i) { + var c = m[i ^ half]; + m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + } + return m; +}; + +/** Utility functions */ + +function transformIV(iv, blockSize) { + if(typeof iv === 'string') { + // convert iv string into byte buffer + iv = forge.util.createBuffer(iv); + } + + if(forge.util.isArray(iv) && iv.length > 4) { + // convert iv byte array into byte buffer + var tmp = iv; + iv = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + iv.putByte(tmp[i]); + } + } + + if(iv.length() < blockSize) { + throw new Error( + 'Invalid IV length; got ' + iv.length() + + ' bytes and expected ' + blockSize + ' bytes.'); + } + + if(!forge.util.isArray(iv)) { + // convert iv byte buffer into 32-bit integer array + var ints = []; + var blocks = blockSize / 4; + for(var i = 0; i < blocks; ++i) { + ints.push(iv.getInt32()); + } + iv = ints; + } + + return iv; +} + +function inc32(block) { + // increment last 32 bits of block only + block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; +} + +function from64To32(num) { + // convert 64-bit number to two BE Int32s + return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; +} + + +/***/ }), + +/***/ 7157: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * DES (Data Encryption Standard) implementation. + * + * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode. + * It is based on the BSD-licensed implementation by Paul Tero: + * + * Paul Tero, July 2001 + * http://www.tero.co.uk/des/ + * + * Optimised for performance with large blocks by + * Michael Hayworth, November 2001 + * http://www.netdealing.com + * + * THIS SOFTWARE IS PROVIDED "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2012-2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7088); +__nccwpck_require__(873); +__nccwpck_require__(8339); + +/* DES API */ +module.exports = forge.des = forge.des || {}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('DES-', key); + * cipher.start({iv: iv}); + * + * Creates an DES cipher object to encrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as binary-encoded strings of bytes or + * byte buffers. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC' if IV is + * given, 'ECB' if null). + * + * @return the cipher. + */ +forge.des.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: false, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('DES-', key); + * + * Creates an DES cipher object to encrypt data using the given symmetric key. + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.des.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: false, + mode: mode + }); +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('DES-', key); + * decipher.start({iv: iv}); + * + * Creates an DES cipher object to decrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as binary-encoded strings of bytes or + * byte buffers. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC' if IV is + * given, 'ECB' if null). + * + * @return the cipher. + */ +forge.des.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: true, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('DES-', key); + * + * Creates an DES cipher object to decrypt data using the given symmetric key. + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.des.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: true, + mode: mode + }); +}; + +/** + * Creates a new DES cipher algorithm object. + * + * @param name the name of the algorithm. + * @param mode the mode factory function. + * + * @return the DES algorithm object. + */ +forge.des.Algorithm = function(name, mode) { + var self = this; + self.name = name; + self.mode = new mode({ + blockSize: 8, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self._keys, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self._keys, inBlock, outBlock, true); + } + } + }); + self._init = false; +}; + +/** + * Initializes this DES algorithm by expanding its key. + * + * @param options the options to use. + * key the key to use with this algorithm. + * decrypt true if the algorithm should be initialized for decryption, + * false for encryption. + */ +forge.des.Algorithm.prototype.initialize = function(options) { + if(this._init) { + return; + } + + var key = forge.util.createBuffer(options.key); + if(this.name.indexOf('3DES') === 0) { + if(key.length() !== 24) { + throw new Error('Invalid Triple-DES key size: ' + key.length() * 8); + } + } + + // do key expansion to 16 or 48 subkeys (single or triple DES) + this._keys = _createKeys(key); + this._init = true; +}; + +/** Register DES algorithms **/ + +registerAlgorithm('DES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('DES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('DES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('DES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('DES-CTR', forge.cipher.modes.ctr); + +registerAlgorithm('3DES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('3DES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('3DES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('3DES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('3DES-CTR', forge.cipher.modes.ctr); + +function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.des.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); +} + +/** DES implementation **/ + +var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004]; +var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000]; +var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200]; +var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080]; +var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100]; +var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010]; +var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002]; +var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000]; + +/** + * Create necessary sub keys. + * + * @param key the 64-bit or 192-bit key. + * + * @return the expanded keys. + */ +function _createKeys(key) { + var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204], + pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101], + pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808], + pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000], + pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010], + pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420], + pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002], + pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800], + pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002], + pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408], + pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020], + pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200], + pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010], + pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105]; + + // how many iterations (1 for des, 3 for triple des) + // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + var iterations = key.length() > 8 ? 3 : 1; + + // stores the return keys + var keys = []; + + // now define the left shifts which need to be done + var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + + var n = 0, tmp; + for(var j = 0; j < iterations; j++) { + var left = key.getInt32(); + var right = key.getInt32(); + + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + tmp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= tmp; + right ^= (tmp << -16); + + tmp = ((left >>> 2) ^ right) & 0x33333333; + right ^= tmp; + left ^= (tmp << 2); + + tmp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= tmp; + right ^= (tmp << -16); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + // right needs to be shifted and OR'd with last four bits of left + tmp = (left << 8) | ((right >>> 20) & 0x000000f0); + + // left needs to be put upside down + left = ((right << 24) | ((right << 8) & 0xff0000) | + ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0)); + right = tmp; + + // now go through and perform these shifts on the left and right keys + for(var i = 0; i < shifts.length; ++i) { + //shift the keys either one or two bits to the left + if(shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; + + // now apply PC-2, in such a way that E is easier when encrypting or + // decrypting this conversion will look like PC-2 except only the last 6 + // bits of each byte are used rather than 48 consecutive bits and the + // order of lines will be according to how the S selection functions will + // be applied: S2, S4, S6, S8, S1, S3, S5, S7 + var lefttmp = ( + pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | + pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] | + pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | + pc2bytes6[(left >>> 4) & 0xf]); + var righttmp = ( + pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | + pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] | + pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]); + tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff; + keys[n++] = lefttmp ^ tmp; + keys[n++] = righttmp ^ (tmp << 16); + } + } + + return keys; +} + +/** + * Updates a single block (1 byte) using DES. The update will either + * encrypt or decrypt the block. + * + * @param keys the expanded keys. + * @param input the input block (an array of 32-bit words). + * @param output the updated output block. + * @param decrypt true to decrypt the block, false to encrypt it. + */ +function _updateBlock(keys, input, output, decrypt) { + // set up loops for single or triple DES + var iterations = keys.length === 32 ? 3 : 9; + var looping; + if(iterations === 3) { + looping = decrypt ? [30, -2, -2] : [0, 32, 2]; + } else { + looping = (decrypt ? + [94, 62, -2, 32, 64, 2, 30, -2, -2] : + [0, 32, 2, 62, 30, -2, 64, 96, 2]); + } + + var tmp; + + var left = input[0]; + var right = input[1]; + + // first each 64 bit chunk of the message must be permuted according to IP + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + tmp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= tmp; + left ^= (tmp << 16); + + tmp = ((right >>> 2) ^ left) & 0x33333333; + left ^= tmp; + right ^= (tmp << 2); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + // rotate left 1 bit + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); + + for(var j = 0; j < iterations; j += 3) { + var endloop = looping[j + 1]; + var loopinc = looping[j + 2]; + + // now go through and perform the encryption or decryption + for(var i = looping[j]; i != endloop; i += loopinc) { + var right1 = right ^ keys[i]; + var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + + // passing these bytes through the S selection functions + tmp = left; + left = right; + right = tmp ^ ( + spfunction2[(right1 >>> 24) & 0x3f] | + spfunction4[(right1 >>> 16) & 0x3f] | + spfunction6[(right1 >>> 8) & 0x3f] | + spfunction8[right1 & 0x3f] | + spfunction1[(right2 >>> 24) & 0x3f] | + spfunction3[(right2 >>> 16) & 0x3f] | + spfunction5[(right2 >>> 8) & 0x3f] | + spfunction7[right2 & 0x3f]); + } + // unreverse left and right + tmp = left; + left = right; + right = tmp; + } + + // rotate right 1 bit + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); + + // now perform IP-1, which is IP in the opposite direction + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((right >>> 2) ^ left) & 0x33333333; + left ^= tmp; + right ^= (tmp << 2); + + tmp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= tmp; + left ^= (tmp << 16); + + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + output[0] = left; + output[1] = right; +} + +/** + * Deprecated. Instead, use: + * + * forge.cipher.createCipher('DES-', key); + * forge.cipher.createDecipher('DES-', key); + * + * Creates a deprecated DES cipher object. This object's mode will default to + * CBC (cipher-block-chaining). + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param options the options to use. + * key the symmetric key to use (64 or 192 bits). + * output the buffer to write to. + * decrypt true for decryption, false for encryption. + * mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +function _createCipher(options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'DES-' + mode; + + var cipher; + if(options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + + // backwards compatible start API + var start = cipher.start; + cipher.start = function(iv, options) { + // backwards compatibility: support second arg as output buffer + var output = null; + if(options instanceof forge.util.ByteBuffer) { + output = options; + options = {}; + } + options = options || {}; + options.output = output; + options.iv = iv; + start.call(cipher, options); + }; + + return cipher; +} + + +/***/ }), + +/***/ 0: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * JavaScript implementation of Ed25519. + * + * Copyright (c) 2017-2019 Digital Bazaar, Inc. + * + * This implementation is based on the most excellent TweetNaCl which is + * in the public domain. Many thanks to its contributors: + * + * https://github.com/dchest/tweetnacl-js + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7052); +__nccwpck_require__(7821); +__nccwpck_require__(9542); +__nccwpck_require__(8339); +var asn1Validator = __nccwpck_require__(9414); +var publicKeyValidator = asn1Validator.publicKeyValidator; +var privateKeyValidator = asn1Validator.privateKeyValidator; + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; +} + +var ByteBuffer = forge.util.ByteBuffer; +var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer; + +/* + * Ed25519 algorithms, see RFC 8032: + * https://tools.ietf.org/html/rfc8032 + */ +forge.pki = forge.pki || {}; +module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; +var ed25519 = forge.ed25519; + +ed25519.constants = {}; +ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; +ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; +ed25519.constants.SEED_BYTE_LENGTH = 32; +ed25519.constants.SIGN_BYTE_LENGTH = 64; +ed25519.constants.HASH_BYTE_LENGTH = 64; + +ed25519.generateKeyPair = function(options) { + options = options || {}; + var seed = options.seed; + if(seed === undefined) { + // generate seed + seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); + } else if(typeof seed === 'string') { + if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { + throw new TypeError( + '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + + ' bytes in length.'); + } + } else if(!(seed instanceof Uint8Array)) { + throw new TypeError( + '"seed" must be a node.js Buffer, Uint8Array, or a binary string.'); + } + + seed = messageToNativeBuffer({message: seed, encoding: 'binary'}); + + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + for(var i = 0; i < 32; ++i) { + sk[i] = seed[i]; + } + crypto_sign_keypair(pk, sk); + return {publicKey: pk, privateKey: sk}; +}; + +/** + * Converts a private key from a RFC8410 ASN.1 encoding. + * + * @param obj - The asn1 representation of a private key. + * + * @returns {Object} keyInfo - The key information. + * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes. + */ +ed25519.privateKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); + if(!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge.asn1.derToOid(capture.privateKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if(oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + + ed25519Oid + '".'); + } + var privateKey = capture.privateKey; + // manually extract the private key bytes from nested octet string, see FIXME: + // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542 + var privateKeyBytes = messageToNativeBuffer({ + message: forge.asn1.fromDer(privateKey).value, + encoding: 'binary' + }); + // TODO: RFC8410 specifies a format for encoding the public key bytes along + // with the private key bytes. `publicKeyBytes` can be returned in the + // future. https://tools.ietf.org/html/rfc8410#section-10.3 + return {privateKeyBytes: privateKeyBytes}; +}; + +/** + * Converts a public key from a RFC8410 ASN.1 encoding. + * + * @param obj - The asn1 representation of a public key. + * + * @return {Buffer|Uint8Array} - 32 public key bytes. + */ +ed25519.publicKeyFromAsn1 = function(obj) { + // get SubjectPublicKeyInfo + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); + if(!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge.asn1.derToOid(capture.publicKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if(oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + + ed25519Oid + '".'); + } + var publicKeyBytes = capture.ed25519PublicKey; + if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new Error('Key length is invalid.'); + } + return messageToNativeBuffer({ + message: publicKeyBytes, + encoding: 'binary' + }); +}; + +ed25519.publicKeyFromPrivateKey = function(options) { + options = options || {}; + var privateKey = messageToNativeBuffer({ + message: options.privateKey, encoding: 'binary' + }); + if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + for(var i = 0; i < pk.length; ++i) { + pk[i] = privateKey[32 + i]; + } + return pk; +}; + +ed25519.sign = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: 'binary' + }); + if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { + var keyPair = ed25519.generateKeyPair({seed: privateKey}); + privateKey = keyPair.privateKey; + } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + + ed25519.constants.SEED_BYTE_LENGTH + ' or ' + + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + + var signedMsg = new NativeBuffer( + ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + crypto_sign(signedMsg, msg, msg.length, privateKey); + + var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); + for(var i = 0; i < sig.length; ++i) { + sig[i] = signedMsg[i]; + } + return sig; +}; + +ed25519.verify = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + if(options.signature === undefined) { + throw new TypeError( + '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + + 'ByteBuffer, or a binary string.'); + } + var sig = messageToNativeBuffer({ + message: options.signature, + encoding: 'binary' + }); + if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { + throw new TypeError( + '"options.signature" must have a byte length of ' + + ed25519.constants.SIGN_BYTE_LENGTH); + } + var publicKey = messageToNativeBuffer({ + message: options.publicKey, + encoding: 'binary' + }); + if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.publicKey" must have a byte length of ' + + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + } + + var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var i; + for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { + sm[i] = sig[i]; + } + for(i = 0; i < msg.length; ++i) { + sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; + } + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +function messageToNativeBuffer(options) { + var message = options.message; + if(message instanceof Uint8Array || message instanceof NativeBuffer) { + return message; + } + + var encoding = options.encoding; + if(message === undefined) { + if(options.md) { + // TODO: more rigorous validation that `md` is a MessageDigest + message = options.md.digest().getBytes(); + encoding = 'binary'; + } else { + throw new TypeError('"options.message" or "options.md" not specified.'); + } + } + + if(typeof message === 'string' && !encoding) { + throw new TypeError('"options.encoding" must be "binary" or "utf8".'); + } + + if(typeof message === 'string') { + if(typeof Buffer !== 'undefined') { + return Buffer.from(message, encoding); + } + message = new ByteBuffer(message, encoding); + } else if(!(message instanceof ByteBuffer)) { + throw new TypeError( + '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + + 'ByteBuffer, or a string with "options.encoding" specifying its ' + + 'encoding.'); + } + + // convert to native buffer + var buffer = new NativeBuffer(message.length()); + for(var i = 0; i < buffer.length; ++i) { + buffer[i] = message.at(i); + } + return buffer; +} + +var gf0 = gf(); +var gf1 = gf([1]); +var D = gf([ + 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, + 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]); +var D2 = gf([ + 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, + 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]); +var X = gf([ + 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, + 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]); +var Y = gf([ + 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, + 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]); +var L = new Float64Array([ + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); +var I = gf([ + 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, + 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`, +// whichever is available, to improve performance +function sha512(msg, msgLen) { + // Note: `out` and `msg` are NativeBuffer + var md = forge.md.sha512.create(); + var buffer = new ByteBuffer(msg); + md.update(buffer.getBytes(msgLen), 'binary'); + var hash = md.digest().getBytes(); + if(typeof Buffer !== 'undefined') { + return Buffer.from(hash, 'binary'); + } + var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); + for(var i = 0; i < 64; ++i) { + out[i] = hash.charCodeAt(i); + } + return out; +} + +function crypto_sign_keypair(pk, sk) { + var p = [gf(), gf(), gf(), gf()]; + var i; + + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for(i = 0; i < 32; ++i) { + sk[i + 32] = pk[i]; + } + return 0; +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for(i = 0; i < n; ++i) { + sm[64 + i] = m[i]; + } + for(i = 0; i < 32; ++i) { + sm[32 + i] = d[32 + i]; + } + + var r = sha512(sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for(i = 32; i < 64; ++i) { + sm[i] = sk[i]; + } + var h = sha512(sm, n + 64); + reduce(h); + + for(i = 32; i < 64; ++i) { + x[i] = 0; + } + for(i = 0; i < 32; ++i) { + x[i] = r[i]; + } + for(i = 0; i < 32; ++i) { + for(j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new NativeBuffer(32); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + mlen = -1; + if(n < 64) { + return -1; + } + + if(unpackneg(q, pk)) { + return -1; + } + + for(i = 0; i < n; ++i) { + m[i] = sm[i]; + } + for(i = 0; i < 32; ++i) { + m[i + 32] = pk[i]; + } + var h = sha512(m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if(crypto_verify_32(sm, 0, t, 0)) { + for(i = 0; i < n; ++i) { + m[i] = 0; + } + return -1; + } + + for(i = 0; i < n; ++i) { + m[i] = sm[i + 64]; + } + mlen = n; + return mlen; +} + +function modL(r, x) { + var carry, i, j, k; + for(i = 63; i >= 32; --i) { + carry = 0; + for(j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for(j = 0; j < 32; ++j) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for(j = 0; j < 32; ++j) { + x[j] -= carry * L[j]; + } + for(i = 0; i < 32; ++i) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64); + for(var i = 0; i < 64; ++i) { + x[i] = r[i]; + r[i] = 0; + } + modL(r, x); +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + for(var i = 0; i < 4; ++i) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for(i = 0; i < 16; ++i) { + t[i] = n[i]; + } + car25519(t); + car25519(t); + car25519(t); + for(j = 0; j < 2; ++j) { + m[0] = t[0] - 0xffed; + for(i = 1; i < 15; ++i) { + m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); + b = (m[15] >> 16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 0xff; + o[2 * i + 1] = t[i] >> 8; + } +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if(neq25519(chk, num)) { + M(r[0], r[0], I); + } + + S(chk, r[0]); + M(chk, chk, den); + if(neq25519(chk, num)) { + return -1; + } + + if(par25519(r[0]) === (p[31] >> 7)) { + Z(r[0], gf0, r[0]); + } + + M(r[3], r[0], r[1]); + return 0; +} + +function unpack25519(o, n) { + var i; + for(i = 0; i < 16; ++i) { + o[i] = n[2 * i] + (n[2 * i + 1] << 8); + } + o[15] &= 0x7fff; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for(a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for(a = 250; a >= 0; --a) { + S(c, c); + if(a !== 1) { + M(c, c, i); + } + } + for(a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function neq25519(a, b) { + var c = new NativeBuffer(32); + var d = new NativeBuffer(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); +} + +function vn(x, xi, y, yi, n) { + var i, d = 0; + for(i = 0; i < n; ++i) { + d |= x[xi + i] ^ y[yi + i]; + } + return (1 & ((d - 1) >>> 8)) - 1; +} + +function par25519(a) { + var d = new NativeBuffer(32); + pack25519(d, a); + return d[0] & 1; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for(i = 255; i >= 0; --i) { + b = (s[(i / 8)|0] >> (i & 7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function set25519(r, a) { + var i; + for(i = 0; i < 16; i++) { + r[i] = a[i] | 0; + } +} + +function inv25519(o, i) { + var c = gf(); + var a; + for(a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for(a = 253; a >= 0; --a) { + S(c, c); + if(a !== 2 && a !== 4) { + M(c, c, i); + } + } + for(a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function car25519(o) { + var i, v, c = 1; + for(i = 0; i < 16; ++i) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); +} + +function sel25519(p, q, b) { + var t, c = ~(b - 1); + for(var i = 0; i < 16; ++i) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function gf(init) { + var i, r = new Float64Array(16); + if(init) { + for(i = 0; i < init.length; ++i) { + r[i] = init[i]; + } + } + return r; +} + +function A(o, a, b) { + for(var i = 0; i < 16; ++i) { + o[i] = a[i] + b[i]; + } +} + +function Z(o, a, b) { + for(var i = 0; i < 16; ++i) { + o[i] = a[i] - b[i]; + } +} + +function S(o, a) { + M(o, a, a); +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + + +/***/ }), + +/***/ 9177: +/***/ ((module) => { + +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = { + // default options + options: { + usePureJavaScript: false + } +}; + + +/***/ }), + +/***/ 5104: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Hash-based Message Authentication Code implementation. Requires a message + * digest object that can be obtained, for example, from forge.md.sha1 or + * forge.md.md5. + * + * @author Dave Longley + * + * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(6231); +__nccwpck_require__(8339); + +/* HMAC API */ +var hmac = module.exports = forge.hmac = forge.hmac || {}; + +/** + * Creates an HMAC object that uses the given message digest object. + * + * @return an HMAC object. + */ +hmac.create = function() { + // the hmac key to use + var _key = null; + + // the message digest to use + var _md = null; + + // the inner padding + var _ipadding = null; + + // the outer padding + var _opadding = null; + + // hmac context + var ctx = {}; + + /** + * Starts or restarts the HMAC with the given key and message digest. + * + * @param md the message digest to use, null to reuse the previous one, + * a string to use builtin 'sha1', 'md5', 'sha256'. + * @param key the key to use as a string, array of bytes, byte buffer, + * or null to reuse the previous key. + */ + ctx.start = function(md, key) { + if(md !== null) { + if(typeof md === 'string') { + // create builtin message digest + md = md.toLowerCase(); + if(md in forge.md.algorithms) { + _md = forge.md.algorithms[md].create(); + } else { + throw new Error('Unknown hash algorithm "' + md + '"'); + } + } else { + // store message digest + _md = md; + } + } + + if(key === null) { + // reuse previous key + key = _key; + } else { + if(typeof key === 'string') { + // convert string into byte buffer + key = forge.util.createBuffer(key); + } else if(forge.util.isArray(key)) { + // convert byte array into byte buffer + var tmp = key; + key = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + + // if key is longer than blocksize, hash it + var keylen = key.length(); + if(keylen > _md.blockLength) { + _md.start(); + _md.update(key.bytes()); + key = _md.digest(); + } + + // mix key into inner and outer padding + // ipadding = [0x36 * blocksize] ^ key + // opadding = [0x5C * blocksize] ^ key + _ipadding = forge.util.createBuffer(); + _opadding = forge.util.createBuffer(); + keylen = key.length(); + for(var i = 0; i < keylen; ++i) { + var tmp = key.at(i); + _ipadding.putByte(0x36 ^ tmp); + _opadding.putByte(0x5C ^ tmp); + } + + // if key is shorter than blocksize, add additional padding + if(keylen < _md.blockLength) { + var tmp = _md.blockLength - keylen; + for(var i = 0; i < tmp; ++i) { + _ipadding.putByte(0x36); + _opadding.putByte(0x5C); + } + } + _key = key; + _ipadding = _ipadding.bytes(); + _opadding = _opadding.bytes(); + } + + // digest is done like so: hash(opadding | hash(ipadding | message)) + + // prepare to do inner hash + // hash(ipadding | message) + _md.start(); + _md.update(_ipadding); + }; + + /** + * Updates the HMAC with the given message bytes. + * + * @param bytes the bytes to update with. + */ + ctx.update = function(bytes) { + _md.update(bytes); + }; + + /** + * Produces the Message Authentication Code (MAC). + * + * @return a byte buffer containing the digest value. + */ + ctx.getMac = function() { + // digest is done like so: hash(opadding | hash(ipadding | message)) + // here we do the outer hashing + var inner = _md.digest().bytes(); + _md.start(); + _md.update(_opadding); + _md.update(inner); + return _md.digest(); + }; + // alias for getMac + ctx.digest = ctx.getMac; + + return ctx; +}; + + +/***/ }), + +/***/ 7655: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = __nccwpck_require__(9177); +__nccwpck_require__(7994); +__nccwpck_require__(1449); +__nccwpck_require__(9549); +__nccwpck_require__(7088); +__nccwpck_require__(7157); +__nccwpck_require__(0); +__nccwpck_require__(5104); +__nccwpck_require__(5173); +__nccwpck_require__(9994); +__nccwpck_require__(8386); +__nccwpck_require__(3339); +__nccwpck_require__(1611); +__nccwpck_require__(154); +__nccwpck_require__(7014); +__nccwpck_require__(466); +__nccwpck_require__(4829); +__nccwpck_require__(6924); +__nccwpck_require__(6861); +__nccwpck_require__(4467); +__nccwpck_require__(4376); +__nccwpck_require__(7821); +__nccwpck_require__(9965); +__nccwpck_require__(4280); +__nccwpck_require__(9167); +__nccwpck_require__(8339); + + +/***/ }), + +/***/ 7052: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// Copyright (c) 2005 Tom Wu +// All Rights Reserved. +// See "LICENSE" for details. + +// Basic JavaScript BN library - subset useful for RSA encryption. + +/* +Licensing (LICENSE) +------------------- + +This software is covered under the following copyright: +*/ +/* + * Copyright (c) 2003-2005 Tom Wu + * All Rights Reserved. + * + * 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" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, + * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF + * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * In addition, the following condition applies: + * + * All redistributions must retain an intact copy of this copyright notice + * and disclaimer. + */ +/* +Address all questions regarding this license to: + + Tom Wu + tjw@cs.Stanford.EDU +*/ +var forge = __nccwpck_require__(9177); + +module.exports = forge.jsbn = forge.jsbn || {}; + +// Bits per digit +var dbits; + +// JavaScript engine analysis +var canary = 0xdeadbeefcafe; +var j_lm = ((canary&0xffffff)==0xefcafe); + +// (public) Constructor +function BigInteger(a,b,c) { + this.data = []; + if(a != null) + if("number" == typeof a) this.fromNumber(a,b,c); + else if(b == null && "string" != typeof a) this.fromString(a,256); + else this.fromString(a,b); +} +forge.jsbn.BigInteger = BigInteger; + +// return new, unset BigInteger +function nbi() { return new BigInteger(null); } + +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. + +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i,x,w,j,c,n) { + while(--n >= 0) { + var v = x*this.data[i++]+w.data[j]+c; + c = Math.floor(v/0x4000000); + w.data[j++] = v&0x3ffffff; + } + return c; +} +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i,x,w,j,c,n) { + var xl = x&0x7fff, xh = x>>15; + while(--n >= 0) { + var l = this.data[i]&0x7fff; + var h = this.data[i++]>>15; + var m = xh*l+h*xl; + l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff); + c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); + w.data[j++] = l&0x3fffffff; + } + return c; +} +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i,x,w,j,c,n) { + var xl = x&0x3fff, xh = x>>14; + while(--n >= 0) { + var l = this.data[i]&0x3fff; + var h = this.data[i++]>>14; + var m = xh*l+h*xl; + l = xl*l+((m&0x3fff)<<14)+w.data[j]+c; + c = (l>>28)+(m>>14)+xh*h; + w.data[j++] = l&0xfffffff; + } + return c; +} + +// node.js (no browser) +if(typeof(navigator) === 'undefined') +{ + BigInteger.prototype.am = am3; + dbits = 28; +} else if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { + BigInteger.prototype.am = am2; + dbits = 30; +} else if(j_lm && (navigator.appName != "Netscape")) { + BigInteger.prototype.am = am1; + dbits = 26; +} else { // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; +} + +BigInteger.prototype.DB = dbits; +BigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i]; + r.t = this.t; + r.s = this.s; +} + +// (protected) set from integer value x, -DV <= x < DV +function bnpFromInt(x) { + this.t = 1; + this.s = (x<0)?-1:0; + if(x > 0) this.data[0] = x; + else if(x < -1) this.data[0] = x+this.DV; + else this.t = 0; +} + +// return bigint initialized to value +function nbv(i) { var r = nbi(); r.fromInt(i); return r; } + +// (protected) set from string and radix +function bnpFromString(s,b) { + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 256) k = 8; // byte array + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else { this.fromRadix(s,b); return; } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while(--i >= 0) { + var x = (k==8)?s[i]&0xff:intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if(sh == 0) + this.data[this.t++] = x; + else if(sh+k > this.DB) { + this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); + } else + this.data[this.t-1] |= x<= this.DB) sh -= this.DB; + } + if(k == 8 && (s[0]&0x80) != 0) { + this.s = -1; + if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t; +} + +// (public) return string representation in given radix +function bnToString(b) { + if(this.s < 0) return "-"+this.negate().toString(b); + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else return this.toRadix(b); + var km = (1< 0) { + if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); } + while(i >= 0) { + if(p < k) { + d = (this.data[i]&((1<>(p+=this.DB-k); + } else { + d = (this.data[i]>>(p-=k))&km; + if(p <= 0) { p += this.DB; --i; } + } + if(d > 0) m = true; + if(m) r += int2char(d); + } + } + return m?r:"0"; +} + +// (public) -this +function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } + +// (public) |this| +function bnAbs() { return (this.s<0)?this.negate():this; } + +// (public) return + if this > a, - if this < a, 0 if equal +function bnCompareTo(a) { + var r = this.s-a.s; + if(r != 0) return r; + var i = this.t; + r = i-a.t; + if(r != 0) return (this.s<0)?-r:r; + while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r; + return 0; +} + +// returns bit length of the integer x +function nbits(x) { + var r = 1, t; + if((t=x>>>16) != 0) { x = t; r += 16; } + if((t=x>>8) != 0) { x = t; r += 8; } + if((t=x>>4) != 0) { x = t; r += 4; } + if((t=x>>2) != 0) { x = t; r += 2; } + if((t=x>>1) != 0) { x = t; r += 1; } + return r; +} + +// (public) return the number of bits in "this" +function bnBitLength() { + if(this.t <= 0) return 0; + return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM)); +} + +// (protected) r = this << n*DB +function bnpDLShiftTo(n,r) { + var i; + for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i]; + for(i = n-1; i >= 0; --i) r.data[i] = 0; + r.t = this.t+n; + r.s = this.s; +} + +// (protected) r = this >> n*DB +function bnpDRShiftTo(n,r) { + for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i]; + r.t = Math.max(this.t-n,0); + r.s = this.s; +} + +// (protected) r = this << n +function bnpLShiftTo(n,r) { + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<= 0; --i) { + r.data[i+ds+1] = (this.data[i]>>cbs)|c; + c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0; + r.data[ds] = c; + r.t = this.t+ds+1; + r.s = this.s; + r.clamp(); +} + +// (protected) r = this >> n +function bnpRShiftTo(n,r) { + r.s = this.s; + var ds = Math.floor(n/this.DB); + if(ds >= this.t) { r.t = 0; return; } + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<>bs; + for(var i = ds+1; i < this.t; ++i) { + r.data[i-ds-1] |= (this.data[i]&bm)<>bs; + } + if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB; + } + if(a.t < this.t) { + c -= a.s; + while(i < this.t) { + c += this.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while(i < a.t) { + c -= a.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c<0)?-1:0; + if(c < -1) r.data[i++] = this.DV+c; + else if(c > 0) r.data[i++] = c; + r.t = i; + r.clamp(); +} + +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. +function bnpMultiplyTo(a,r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i+y.t; + while(--i >= 0) r.data[i] = 0; + for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t); + r.s = 0; + r.clamp(); + if(this.s != a.s) BigInteger.ZERO.subTo(r,r); +} + +// (protected) r = this^2, r != this (HAC 14.16) +function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2*x.t; + while(--i >= 0) r.data[i] = 0; + for(i = 0; i < x.t-1; ++i) { + var c = x.am(i,x.data[i],r,2*i,0,1); + if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { + r.data[i+x.t] -= x.DV; + r.data[i+x.t+1] = 1; + } + } + if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1); + r.s = 0; + r.clamp(); +} + +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. +function bnpDivRemTo(m,q,r) { + var pm = m.abs(); + if(pm.t <= 0) return; + var pt = this.abs(); + if(pt.t < pm.t) { + if(q != null) q.fromInt(0); + if(r != null) this.copyTo(r); + return; + } + if(r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus + if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } + var ys = y.t; + var y0 = y.data[ys-1]; + if(y0 == 0) return; + var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0); + var d1 = this.FV/yt, d2 = (1<= 0) { + r.data[r.t++] = 1; + r.subTo(t,r); + } + BigInteger.ONE.dlShiftTo(ys,t); + t.subTo(y,y); // "negative" y so we can replace sub with am later + while(y.t < ys) y.data[y.t++] = 0; + while(--j >= 0) { + // Estimate quotient digit + var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2); + if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out + y.dlShiftTo(j,t); + r.subTo(t,r); + while(r.data[i] < --qd) r.subTo(t,r); + } + } + if(q != null) { + r.drShiftTo(ys,q); + if(ts != ms) BigInteger.ZERO.subTo(q,q); + } + r.t = ys; + r.clamp(); + if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder + if(ts < 0) BigInteger.ZERO.subTo(r,r); +} + +// (public) this mod a +function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a,null,r); + if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); + return r; +} + +// Modular reduction using "classic" algorithm +function Classic(m) { this.m = m; } +function cConvert(x) { + if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; +} +function cRevert(x) { return x; } +function cReduce(x) { x.divRemTo(this.m,null,x); } +function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +Classic.prototype.convert = cConvert; +Classic.prototype.revert = cRevert; +Classic.prototype.reduce = cReduce; +Classic.prototype.mulTo = cMulTo; +Classic.prototype.sqrTo = cSqrTo; + +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. +function bnpInvDigit() { + if(this.t < 1) return 0; + var x = this.data[0]; + if((x&1) == 0) return 0; + var y = x&3; // y == 1/x mod 2^2 + y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 + y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 + y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y>0)?this.DV-y:-y; +} + +// Montgomery reduction +function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp&0x7fff; + this.mph = this.mp>>15; + this.um = (1<<(m.DB-15))-1; + this.mt2 = 2*m.t; +} + +// xR mod m +function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t,r); + r.divRemTo(this.m,null,r); + if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); + return r; +} + +// x/R mod m +function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; +} + +// x = x/R mod m (HAC 14.32) +function montReduce(x) { + while(x.t <= this.mt2) // pad x so am has enough room later + x.data[x.t++] = 0; + for(var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x.data[i]*mp mod DV + var j = x.data[i]&0x7fff; + var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM; + // use am to combine the multiply-shift-add into one call + j = i+this.m.t; + x.data[j] += this.m.am(0,u0,x,i,0,this.m.t); + // propagate carry + while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; } + } + x.clamp(); + x.drShiftTo(this.m.t,x); + if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +// r = "x^2/R mod m"; x != r +function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +// r = "xy/R mod m"; x,y != r +function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Montgomery.prototype.convert = montConvert; +Montgomery.prototype.revert = montRevert; +Montgomery.prototype.reduce = montReduce; +Montgomery.prototype.mulTo = montMulTo; +Montgomery.prototype.sqrTo = montSqrTo; + +// (protected) true iff this is even +function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; } + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) +function bnpExp(e,z) { + if(e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; + g.copyTo(r); + while(--i >= 0) { + z.sqrTo(r,r2); + if((e&(1< 0) z.mulTo(r2,g,r); + else { var t = r; r = r2; r2 = t; } + } + return z.revert(r); +} + +// (public) this^e % m, 0 <= e < 2^32 +function bnModPowInt(e,m) { + var z; + if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); + return this.exp(e,z); +} + +// protected +BigInteger.prototype.copyTo = bnpCopyTo; +BigInteger.prototype.fromInt = bnpFromInt; +BigInteger.prototype.fromString = bnpFromString; +BigInteger.prototype.clamp = bnpClamp; +BigInteger.prototype.dlShiftTo = bnpDLShiftTo; +BigInteger.prototype.drShiftTo = bnpDRShiftTo; +BigInteger.prototype.lShiftTo = bnpLShiftTo; +BigInteger.prototype.rShiftTo = bnpRShiftTo; +BigInteger.prototype.subTo = bnpSubTo; +BigInteger.prototype.multiplyTo = bnpMultiplyTo; +BigInteger.prototype.squareTo = bnpSquareTo; +BigInteger.prototype.divRemTo = bnpDivRemTo; +BigInteger.prototype.invDigit = bnpInvDigit; +BigInteger.prototype.isEven = bnpIsEven; +BigInteger.prototype.exp = bnpExp; + +// public +BigInteger.prototype.toString = bnToString; +BigInteger.prototype.negate = bnNegate; +BigInteger.prototype.abs = bnAbs; +BigInteger.prototype.compareTo = bnCompareTo; +BigInteger.prototype.bitLength = bnBitLength; +BigInteger.prototype.mod = bnMod; +BigInteger.prototype.modPowInt = bnModPowInt; + +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); + +// jsbn2 lib + +//Copyright (c) 2005-2009 Tom Wu +//All Rights Reserved. +//See "LICENSE" for details (See jsbn.js for LICENSE). + +//Extended JavaScript BN functions, required for RSA private ops. + +//Version 1.1: new BigInteger("0", 10) returns "proper" zero + +//(public) +function bnClone() { var r = nbi(); this.copyTo(r); return r; } + +//(public) return value as integer +function bnIntValue() { +if(this.s < 0) { + if(this.t == 1) return this.data[0]-this.DV; + else if(this.t == 0) return -1; +} else if(this.t == 1) return this.data[0]; +else if(this.t == 0) return 0; +// assumes 16 < DB < 32 +return ((this.data[1]&((1<<(32-this.DB))-1))<>24; } + +//(public) return value as short (assumes DB>=16) +function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; } + +//(protected) return x s.t. r^x < DV +function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } + +//(public) 0 if this == 0, 1 if this > 0 +function bnSigNum() { +if(this.s < 0) return -1; +else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; +else return 1; +} + +//(protected) convert to radix string +function bnpToRadix(b) { +if(b == null) b = 10; +if(this.signum() == 0 || b < 2 || b > 36) return "0"; +var cs = this.chunkSize(b); +var a = Math.pow(b,cs); +var d = nbv(a), y = nbi(), z = nbi(), r = ""; +this.divRemTo(d,y,z); +while(y.signum() > 0) { + r = (a+z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d,y,z); +} +return z.intValue().toString(b) + r; +} + +//(protected) convert from radix string +function bnpFromRadix(s,b) { +this.fromInt(0); +if(b == null) b = 10; +var cs = this.chunkSize(b); +var d = Math.pow(b,cs), mi = false, j = 0, w = 0; +for(var i = 0; i < s.length; ++i) { + var x = intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b*w+x; + if(++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w,0); + j = 0; + w = 0; + } +} +if(j > 0) { + this.dMultiply(Math.pow(b,j)); + this.dAddOffset(w,0); +} +if(mi) BigInteger.ZERO.subTo(this,this); +} + +//(protected) alternate constructor +function bnpFromNumber(a,b,c) { +if("number" == typeof b) { + // new BigInteger(int,int,RNG) + if(a < 2) this.fromInt(1); + else { + this.fromNumber(a,c); + if(!this.testBit(a-1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); + if(this.isEven()) this.dAddOffset(1,0); // force odd + while(!this.isProbablePrime(b)) { + this.dAddOffset(2,0); + if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); + } + } +} else { + // new BigInteger(int,RNG) + var x = new Array(), t = a&7; + x.length = (a>>3)+1; + b.nextBytes(x); + if(t > 0) x[0] &= ((1< 0) { + if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p) + r[k++] = d|(this.s<<(this.DB-p)); + while(i >= 0) { + if(p < 8) { + d = (this.data[i]&((1<>(p+=this.DB-8); + } else { + d = (this.data[i]>>(p-=8))&0xff; + if(p <= 0) { p += this.DB; --i; } + } + if((d&0x80) != 0) d |= -256; + if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; + if(k > 0 || d != this.s) r[k++] = d; + } +} +return r; +} + +function bnEquals(a) { return(this.compareTo(a)==0); } +function bnMin(a) { return(this.compareTo(a)<0)?this:a; } +function bnMax(a) { return(this.compareTo(a)>0)?this:a; } + +//(protected) r = this op a (bitwise) +function bnpBitwiseTo(a,op,r) { +var i, f, m = Math.min(a.t,this.t); +for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]); +if(a.t < this.t) { + f = a.s&this.DM; + for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f); + r.t = this.t; +} else { + f = this.s&this.DM; + for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]); + r.t = a.t; +} +r.s = op(this.s,a.s); +r.clamp(); +} + +//(public) this & a +function op_and(x,y) { return x&y; } +function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } + +//(public) this | a +function op_or(x,y) { return x|y; } +function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } + +//(public) this ^ a +function op_xor(x,y) { return x^y; } +function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } + +//(public) this & ~a +function op_andnot(x,y) { return x&~y; } +function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } + +//(public) ~this +function bnNot() { +var r = nbi(); +for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i]; +r.t = this.t; +r.s = ~this.s; +return r; +} + +//(public) this << n +function bnShiftLeft(n) { +var r = nbi(); +if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); +return r; +} + +//(public) this >> n +function bnShiftRight(n) { +var r = nbi(); +if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); +return r; +} + +//return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { +if(x == 0) return -1; +var r = 0; +if((x&0xffff) == 0) { x >>= 16; r += 16; } +if((x&0xff) == 0) { x >>= 8; r += 8; } +if((x&0xf) == 0) { x >>= 4; r += 4; } +if((x&3) == 0) { x >>= 2; r += 2; } +if((x&1) == 0) ++r; +return r; +} + +//(public) returns index of lowest 1-bit (or -1 if none) +function bnGetLowestSetBit() { +for(var i = 0; i < this.t; ++i) + if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]); +if(this.s < 0) return this.t*this.DB; +return -1; +} + +//return number of 1 bits in x +function cbit(x) { +var r = 0; +while(x != 0) { x &= x-1; ++r; } +return r; +} + +//(public) return number of set bits +function bnBitCount() { +var r = 0, x = this.s&this.DM; +for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x); +return r; +} + +//(public) true iff nth bit is set +function bnTestBit(n) { +var j = Math.floor(n/this.DB); +if(j >= this.t) return(this.s!=0); +return((this.data[j]&(1<<(n%this.DB)))!=0); +} + +//(protected) this op (1<>= this.DB; +} +if(a.t < this.t) { + c += a.s; + while(i < this.t) { + c += this.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; +} else { + c += this.s; + while(i < a.t) { + c += a.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += a.s; +} +r.s = (c<0)?-1:0; +if(c > 0) r.data[i++] = c; +else if(c < -1) r.data[i++] = this.DV+c; +r.t = i; +r.clamp(); +} + +//(public) this + a +function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } + +//(public) this - a +function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } + +//(public) this * a +function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } + +//(public) this / a +function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } + +//(public) this % a +function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + +//(public) [this/a,this%a] +function bnDivideAndRemainder(a) { +var q = nbi(), r = nbi(); +this.divRemTo(a,q,r); +return new Array(q,r); +} + +//(protected) this *= n, this >= 0, 1 < n < DV +function bnpDMultiply(n) { +this.data[this.t] = this.am(0,n-1,this,0,0,this.t); +++this.t; +this.clamp(); +} + +//(protected) this += n << w words, this >= 0 +function bnpDAddOffset(n,w) { +if(n == 0) return; +while(this.t <= w) this.data[this.t++] = 0; +this.data[w] += n; +while(this.data[w] >= this.DV) { + this.data[w] -= this.DV; + if(++w >= this.t) this.data[this.t++] = 0; + ++this.data[w]; +} +} + +//A "null" reducer +function NullExp() {} +function nNop(x) { return x; } +function nMulTo(x,y,r) { x.multiplyTo(y,r); } +function nSqrTo(x,r) { x.squareTo(r); } + +NullExp.prototype.convert = nNop; +NullExp.prototype.revert = nNop; +NullExp.prototype.mulTo = nMulTo; +NullExp.prototype.sqrTo = nSqrTo; + +//(public) this^e +function bnPow(e) { return this.exp(e,new NullExp()); } + +//(protected) r = lower n words of "this * a", a.t <= n +//"this" should be the larger one if appropriate. +function bnpMultiplyLowerTo(a,n,r) { +var i = Math.min(this.t+a.t,n); +r.s = 0; // assumes a,this >= 0 +r.t = i; +while(i > 0) r.data[--i] = 0; +var j; +for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t); +for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i); +r.clamp(); +} + +//(protected) r = "this * a" without lower n words, n > 0 +//"this" should be the larger one if appropriate. +function bnpMultiplyUpperTo(a,n,r) { +--n; +var i = r.t = this.t+a.t-n; +r.s = 0; // assumes a,this >= 0 +while(--i >= 0) r.data[i] = 0; +for(i = Math.max(n-this.t,0); i < a.t; ++i) + r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n); +r.clamp(); +r.drShiftTo(1,r); +} + +//Barrett modular reduction +function Barrett(m) { +// setup Barrett +this.r2 = nbi(); +this.q3 = nbi(); +BigInteger.ONE.dlShiftTo(2*m.t,this.r2); +this.mu = this.r2.divide(m); +this.m = m; +} + +function barrettConvert(x) { +if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); +else if(x.compareTo(this.m) < 0) return x; +else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } +} + +function barrettRevert(x) { return x; } + +//x = x mod m (HAC 14.42) +function barrettReduce(x) { +x.drShiftTo(this.m.t-1,this.r2); +if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } +this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); +this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); +while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); +x.subTo(this.r2,x); +while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +//r = x^2 mod m; x != r +function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +//r = x*y mod m; x,y != r +function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Barrett.prototype.convert = barrettConvert; +Barrett.prototype.revert = barrettRevert; +Barrett.prototype.reduce = barrettReduce; +Barrett.prototype.mulTo = barrettMulTo; +Barrett.prototype.sqrTo = barrettSqrTo; + +//(public) this^e % m (HAC 14.85) +function bnModPow(e,m) { +var i = e.bitLength(), k, r = nbv(1), z; +if(i <= 0) return r; +else if(i < 18) k = 1; +else if(i < 48) k = 3; +else if(i < 144) k = 4; +else if(i < 768) k = 5; +else k = 6; +if(i < 8) + z = new Classic(m); +else if(m.isEven()) + z = new Barrett(m); +else + z = new Montgomery(m); + +// precomputation +var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1],g2); + while(n <= km) { + g[n] = nbi(); + z.mulTo(g2,g[n-2],g[n]); + n += 2; + } +} + +var j = e.t-1, w, is1 = true, r2 = nbi(), t; +i = nbits(e.data[j])-1; +while(j >= 0) { + if(i >= k1) w = (e.data[j]>>(i-k1))&km; + else { + w = (e.data[j]&((1<<(i+1))-1))<<(k1-i); + if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1); + } + + n = k; + while((w&1) == 0) { w >>= 1; --n; } + if((i -= n) < 0) { i += this.DB; --j; } + if(is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } else { + while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } + if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } + z.mulTo(r2,g[w],r); + } + + while(j >= 0 && (e.data[j]&(1< 0) { + x.rShiftTo(g,x); + y.rShiftTo(g,y); +} +while(x.signum() > 0) { + if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); + if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); + if(x.compareTo(y) >= 0) { + x.subTo(y,x); + x.rShiftTo(1,x); + } else { + y.subTo(x,y); + y.rShiftTo(1,y); + } +} +if(g > 0) y.lShiftTo(g,y); +return y; +} + +//(protected) this % n, n < 2^26 +function bnpModInt(n) { +if(n <= 0) return 0; +var d = this.DV%n, r = (this.s<0)?n-1:0; +if(this.t > 0) + if(d == 0) r = this.data[0]%n; + else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n; +return r; +} + +//(public) 1/this % m (HAC 14.61) +function bnModInverse(m) { +var ac = m.isEven(); +if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; +var u = m.clone(), v = this.clone(); +var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); +while(u.signum() != 0) { + while(u.isEven()) { + u.rShiftTo(1,u); + if(ac) { + if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } + a.rShiftTo(1,a); + } else if(!b.isEven()) b.subTo(m,b); + b.rShiftTo(1,b); + } + while(v.isEven()) { + v.rShiftTo(1,v); + if(ac) { + if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } + c.rShiftTo(1,c); + } else if(!d.isEven()) d.subTo(m,d); + d.rShiftTo(1,d); + } + if(u.compareTo(v) >= 0) { + u.subTo(v,u); + if(ac) a.subTo(c,a); + b.subTo(d,b); + } else { + v.subTo(u,v); + if(ac) c.subTo(a,c); + d.subTo(b,d); + } +} +if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; +if(d.compareTo(m) >= 0) return d.subtract(m); +if(d.signum() < 0) d.addTo(m,d); else return d; +if(d.signum() < 0) return d.add(m); else return d; +} + +var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; +var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + +//(public) test primality with certainty >= 1-.5^t +function bnIsProbablePrime(t) { +var i, x = this.abs(); +if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) { + for(i = 0; i < lowprimes.length; ++i) + if(x.data[0] == lowprimes[i]) return true; + return false; +} +if(x.isEven()) return false; +i = 1; +while(i < lowprimes.length) { + var m = lowprimes[i], j = i+1; + while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while(i < j) if(m%lowprimes[i++] == 0) return false; +} +return x.millerRabin(t); +} + +//(protected) true if probably prime (HAC 4.24, Miller-Rabin) +function bnpMillerRabin(t) { +var n1 = this.subtract(BigInteger.ONE); +var k = n1.getLowestSetBit(); +if(k <= 0) return false; +var r = n1.shiftRight(k); +var prng = bnGetPrng(); +var a; +for(var i = 0; i < t; ++i) { + // select witness 'a' at random from between 1 and n1 + do { + a = new BigInteger(this.bitLength(), prng); + } + while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); + var y = a.modPow(r,this); + if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while(j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2,this); + if(y.compareTo(BigInteger.ONE) == 0) return false; + } + if(y.compareTo(n1) != 0) return false; + } +} +return true; +} + +// get pseudo random number generator +function bnGetPrng() { + // create prng with api that matches BigInteger secure random + return { + // x is an array to fill with bytes + nextBytes: function(x) { + for(var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 0x0100); + } + } + }; +} + +//protected +BigInteger.prototype.chunkSize = bnpChunkSize; +BigInteger.prototype.toRadix = bnpToRadix; +BigInteger.prototype.fromRadix = bnpFromRadix; +BigInteger.prototype.fromNumber = bnpFromNumber; +BigInteger.prototype.bitwiseTo = bnpBitwiseTo; +BigInteger.prototype.changeBit = bnpChangeBit; +BigInteger.prototype.addTo = bnpAddTo; +BigInteger.prototype.dMultiply = bnpDMultiply; +BigInteger.prototype.dAddOffset = bnpDAddOffset; +BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; +BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; +BigInteger.prototype.modInt = bnpModInt; +BigInteger.prototype.millerRabin = bnpMillerRabin; + +//public +BigInteger.prototype.clone = bnClone; +BigInteger.prototype.intValue = bnIntValue; +BigInteger.prototype.byteValue = bnByteValue; +BigInteger.prototype.shortValue = bnShortValue; +BigInteger.prototype.signum = bnSigNum; +BigInteger.prototype.toByteArray = bnToByteArray; +BigInteger.prototype.equals = bnEquals; +BigInteger.prototype.min = bnMin; +BigInteger.prototype.max = bnMax; +BigInteger.prototype.and = bnAnd; +BigInteger.prototype.or = bnOr; +BigInteger.prototype.xor = bnXor; +BigInteger.prototype.andNot = bnAndNot; +BigInteger.prototype.not = bnNot; +BigInteger.prototype.shiftLeft = bnShiftLeft; +BigInteger.prototype.shiftRight = bnShiftRight; +BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; +BigInteger.prototype.bitCount = bnBitCount; +BigInteger.prototype.testBit = bnTestBit; +BigInteger.prototype.setBit = bnSetBit; +BigInteger.prototype.clearBit = bnClearBit; +BigInteger.prototype.flipBit = bnFlipBit; +BigInteger.prototype.add = bnAdd; +BigInteger.prototype.subtract = bnSubtract; +BigInteger.prototype.multiply = bnMultiply; +BigInteger.prototype.divide = bnDivide; +BigInteger.prototype.remainder = bnRemainder; +BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; +BigInteger.prototype.modPow = bnModPow; +BigInteger.prototype.modInverse = bnModInverse; +BigInteger.prototype.pow = bnPow; +BigInteger.prototype.gcd = bnGCD; +BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + +//BigInteger interfaces not implemented in jsbn: + +//BigInteger(int signum, byte[] magnitude) +//double doubleValue() +//float floatValue() +//int hashCode() +//long longValue() +//static BigInteger valueOf(long val) + + +/***/ }), + +/***/ 5173: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of RSA-KEM. + * + * @author Lautaro Cozzani Rodriguez + * @author Dave Longley + * + * Copyright (c) 2014 Lautaro Cozzani + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); +__nccwpck_require__(7821); +__nccwpck_require__(7052); + +module.exports = forge.kem = forge.kem || {}; + +var BigInteger = forge.jsbn.BigInteger; + +/** + * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2. + */ +forge.kem.rsa = {}; + +/** + * Creates an RSA KEM API object for generating a secret asymmetric key. + * + * The symmetric key may be generated via a call to 'encrypt', which will + * produce a ciphertext to be transmitted to the recipient and a key to be + * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which + * will produce the same secret key for the recipient to use to decrypt a + * message that was encrypted with the secret key. + * + * @param kdf the KDF API to use (eg: new forge.kem.kdf1()). + * @param options the options to use. + * [prng] a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + */ +forge.kem.rsa.create = function(kdf, options) { + options = options || {}; + var prng = options.prng || forge.random; + + var kem = {}; + + /** + * Generates a secret key and its encapsulation. + * + * @param publicKey the RSA public key to encrypt with. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return an object with: + * encapsulation: the ciphertext for generating the secret key, as a + * binary-encoded string of bytes. + * key: the secret key to use for encrypting a message. + */ + kem.encrypt = function(publicKey, keyLength) { + // generate a random r where 1 < r < n + var byteLength = Math.ceil(publicKey.n.bitLength() / 8); + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(prng.getBytesSync(byteLength)), + 16).mod(publicKey.n); + } while(r.compareTo(BigInteger.ONE) <= 0); + + // prepend r with zeros + r = forge.util.hexToBytes(r.toString(16)); + var zeros = byteLength - r.length; + if(zeros > 0) { + r = forge.util.fillString(String.fromCharCode(0), zeros) + r; + } + + // encrypt the random + var encapsulation = publicKey.encrypt(r, 'NONE'); + + // generate the secret key + var key = kdf.generate(r, keyLength); + + return {encapsulation: encapsulation, key: key}; + }; + + /** + * Decrypts an encapsulated secret key. + * + * @param privateKey the RSA private key to decrypt with. + * @param encapsulation the ciphertext for generating the secret key, as + * a binary-encoded string of bytes. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return the secret key as a binary-encoded string of bytes. + */ + kem.decrypt = function(privateKey, encapsulation, keyLength) { + // decrypt the encapsulation and generate the secret key + var r = privateKey.decrypt(encapsulation, 'NONE'); + return kdf.generate(r, keyLength); + }; + + return kem; +}; + +// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API? + +/** + * Creates a key derivation API object that implements KDF1 per ISO 18033-2. + * + * @param md the hash API to use. + * @param [digestLength] an optional digest length that must be positive and + * less than or equal to md.digestLength. + * + * @return a KDF1 API object. + */ +forge.kem.kdf1 = function(md, digestLength) { + _createKDF(this, md, 0, digestLength || md.digestLength); +}; + +/** + * Creates a key derivation API object that implements KDF2 per ISO 18033-2. + * + * @param md the hash API to use. + * @param [digestLength] an optional digest length that must be positive and + * less than or equal to md.digestLength. + * + * @return a KDF2 API object. + */ +forge.kem.kdf2 = function(md, digestLength) { + _createKDF(this, md, 1, digestLength || md.digestLength); +}; + +/** + * Creates a KDF1 or KDF2 API object. + * + * @param md the hash API to use. + * @param counterStart the starting index for the counter. + * @param digestLength the digest length to use. + * + * @return the KDF API object. + */ +function _createKDF(kdf, md, counterStart, digestLength) { + /** + * Generate a key of the specified length. + * + * @param x the binary-encoded byte string to generate a key from. + * @param length the number of bytes to generate (the size of the key). + * + * @return the key as a binary-encoded string. + */ + kdf.generate = function(x, length) { + var key = new forge.util.ByteBuffer(); + + // run counter from counterStart to ceil(length / Hash.len) + var k = Math.ceil(length / digestLength) + counterStart; + + var c = new forge.util.ByteBuffer(); + for(var i = counterStart; i < k; ++i) { + // I2OSP(i, 4): convert counter to an octet string of 4 octets + c.putInt32(i); + + // digest 'x' and the counter and add the result to the key + md.start(); + md.update(x + c.getBytes()); + var hash = md.digest(); + key.putBytes(hash.getBytes(digestLength)); + } + + // truncate to the correct key length + key.truncate(key.length() - length); + return key.getBytes(); + }; +} + + +/***/ }), + +/***/ 9994: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Cross-browser support for logging in a web application. + * + * @author David I. Lehn + * + * Copyright (c) 2008-2013 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); + +/* LOG API */ +module.exports = forge.log = forge.log || {}; + +/** + * Application logging system. + * + * Each logger level available as it's own function of the form: + * forge.log.level(category, args...) + * The category is an arbitrary string, and the args are the same as + * Firebug's console.log API. By default the call will be output as: + * 'LEVEL [category] , args[1], ...' + * This enables proper % formatting via the first argument. + * Each category is enabled by default but can be enabled or disabled with + * the setCategoryEnabled() function. + */ +// list of known levels +forge.log.levels = [ + 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max']; +// info on the levels indexed by name: +// index: level index +// name: uppercased display name +var sLevelInfo = {}; +// list of loggers +var sLoggers = []; +/** + * Standard console logger. If no console support is enabled this will + * remain null. Check before using. + */ +var sConsoleLogger = null; + +// logger flags +/** + * Lock the level at the current value. Used in cases where user config may + * set the level such that only critical messages are seen but more verbose + * messages are needed for debugging or other purposes. + */ +forge.log.LEVEL_LOCKED = (1 << 1); +/** + * Always call log function. By default, the logging system will check the + * message level against logger.level before calling the log function. This + * flag allows the function to do its own check. + */ +forge.log.NO_LEVEL_CHECK = (1 << 2); +/** + * Perform message interpolation with the passed arguments. "%" style + * fields in log messages will be replaced by arguments as needed. Some + * loggers, such as Firebug, may do this automatically. The original log + * message will be available as 'message' and the interpolated version will + * be available as 'fullMessage'. + */ +forge.log.INTERPOLATE = (1 << 3); + +// setup each log level +for(var i = 0; i < forge.log.levels.length; ++i) { + var level = forge.log.levels[i]; + sLevelInfo[level] = { + index: i, + name: level.toUpperCase() + }; +} + +/** + * Message logger. Will dispatch a message to registered loggers as needed. + * + * @param message message object + */ +forge.log.logMessage = function(message) { + var messageLevelIndex = sLevelInfo[message.level].index; + for(var i = 0; i < sLoggers.length; ++i) { + var logger = sLoggers[i]; + if(logger.flags & forge.log.NO_LEVEL_CHECK) { + logger.f(message); + } else { + // get logger level + var loggerLevelIndex = sLevelInfo[logger.level].index; + // check level + if(messageLevelIndex <= loggerLevelIndex) { + // message critical enough, call logger + logger.f(logger, message); + } + } + } +}; + +/** + * Sets the 'standard' key on a message object to: + * "LEVEL [category] " + message + * + * @param message a message log object + */ +forge.log.prepareStandard = function(message) { + if(!('standard' in message)) { + message.standard = + sLevelInfo[message.level].name + + //' ' + +message.timestamp + + ' [' + message.category + '] ' + + message.message; + } +}; + +/** + * Sets the 'full' key on a message object to the original message + * interpolated via % formatting with the message arguments. + * + * @param message a message log object. + */ +forge.log.prepareFull = function(message) { + if(!('full' in message)) { + // copy args and insert message at the front + var args = [message.message]; + args = args.concat([] || 0); + // format the message + message.full = forge.util.format.apply(this, args); + } +}; + +/** + * Applies both preparseStandard() and prepareFull() to a message object and + * store result in 'standardFull'. + * + * @param message a message log object. + */ +forge.log.prepareStandardFull = function(message) { + if(!('standardFull' in message)) { + // FIXME implement 'standardFull' logging + forge.log.prepareStandard(message); + message.standardFull = message.standard; + } +}; + +// create log level functions +if(true) { + // levels for which we want functions + var levels = ['error', 'warning', 'info', 'debug', 'verbose']; + for(var i = 0; i < levels.length; ++i) { + // wrap in a function to ensure proper level var is passed + (function(level) { + // create function for this level + forge.log[level] = function(category, message/*, args...*/) { + // convert arguments to real array, remove category and message + var args = Array.prototype.slice.call(arguments).slice(2); + // create message object + // Note: interpolation and standard formatting is done lazily + var msg = { + timestamp: new Date(), + level: level, + category: category, + message: message, + 'arguments': args + /*standard*/ + /*full*/ + /*fullMessage*/ + }; + // process this message + forge.log.logMessage(msg); + }; + })(levels[i]); + } +} + +/** + * Creates a new logger with specified custom logging function. + * + * The logging function has a signature of: + * function(logger, message) + * logger: current logger + * message: object: + * level: level id + * category: category + * message: string message + * arguments: Array of extra arguments + * fullMessage: interpolated message and arguments if INTERPOLATE flag set + * + * @param logFunction a logging function which takes a log message object + * as a parameter. + * + * @return a logger object. + */ +forge.log.makeLogger = function(logFunction) { + var logger = { + flags: 0, + f: logFunction + }; + forge.log.setLevel(logger, 'none'); + return logger; +}; + +/** + * Sets the current log level on a logger. + * + * @param logger the target logger. + * @param level the new maximum log level as a string. + * + * @return true if set, false if not. + */ +forge.log.setLevel = function(logger, level) { + var rval = false; + if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) { + for(var i = 0; i < forge.log.levels.length; ++i) { + var aValidLevel = forge.log.levels[i]; + if(level == aValidLevel) { + // set level + logger.level = level; + rval = true; + break; + } + } + } + + return rval; +}; + +/** + * Locks the log level at its current value. + * + * @param logger the target logger. + * @param lock boolean lock value, default to true. + */ +forge.log.lock = function(logger, lock) { + if(typeof lock === 'undefined' || lock) { + logger.flags |= forge.log.LEVEL_LOCKED; + } else { + logger.flags &= ~forge.log.LEVEL_LOCKED; + } +}; + +/** + * Adds a logger. + * + * @param logger the logger object. + */ +forge.log.addLogger = function(logger) { + sLoggers.push(logger); +}; + +// setup the console logger if possible, else create fake console.log +if(typeof(console) !== 'undefined' && 'log' in console) { + var logger; + if(console.error && console.warn && console.info && console.debug) { + // looks like Firebug-style logging is available + // level handlers map + var levelHandlers = { + error: console.error, + warning: console.warn, + info: console.info, + debug: console.debug, + verbose: console.debug + }; + var f = function(logger, message) { + forge.log.prepareStandard(message); + var handler = levelHandlers[message.level]; + // prepend standard message and concat args + var args = [message.standard]; + args = args.concat(message['arguments'].slice()); + // apply to low-level console function + handler.apply(console, args); + }; + logger = forge.log.makeLogger(f); + } else { + // only appear to have basic console.log + var f = function(logger, message) { + forge.log.prepareStandardFull(message); + console.log(message.standardFull); + }; + logger = forge.log.makeLogger(f); + } + forge.log.setLevel(logger, 'debug'); + forge.log.addLogger(logger); + sConsoleLogger = logger; +} else { + // define fake console.log to avoid potential script errors on + // browsers that do not have console logging + console = { + log: function() {} + }; +} + +/* + * Check for logging control query vars in current URL. + * + * console.level= + * Set's the console log level by name. Useful to override defaults and + * allow more verbose logging before a user config is loaded. + * + * console.lock= + * Lock the console log level at whatever level it is set at. This is run + * after console.level is processed. Useful to force a level of verbosity + * that could otherwise be limited by a user config. + */ +if(sConsoleLogger !== null && + typeof window !== 'undefined' && window.location +) { + var query = new URL(window.location.href).searchParams; + if(query.has('console.level')) { + // set with last value + forge.log.setLevel( + sConsoleLogger, query.get('console.level').slice(-1)[0]); + } + if(query.has('console.lock')) { + // set with last value + var lock = query.get('console.lock').slice(-1)[0]; + if(lock == 'true') { + forge.log.lock(sConsoleLogger); + } + } +} + +// provide public access to console logger +forge.log.consoleLogger = sConsoleLogger; + + +/***/ }), + +/***/ 8386: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Node.js module for all known Forge message digests. + * + * @author Dave Longley + * + * Copyright 2011-2017 Digital Bazaar, Inc. + */ +module.exports = __nccwpck_require__(6231); + +__nccwpck_require__(6594); +__nccwpck_require__(279); +__nccwpck_require__(4086); +__nccwpck_require__(9542); + + +/***/ }), + +/***/ 6231: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Node.js module for Forge message digests. + * + * @author Dave Longley + * + * Copyright 2011-2017 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); + +module.exports = forge.md = forge.md || {}; +forge.md.algorithms = forge.md.algorithms || {}; + + +/***/ }), + +/***/ 6594: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(6231); +__nccwpck_require__(8339); + +var md5 = module.exports = forge.md5 = forge.md5 || {}; +forge.md.md5 = forge.md.algorithms.md5 = md5; + +/** + * Creates an MD5 message digest object. + * + * @return a message digest object. + */ +md5.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // MD5 state contains four 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(16); + + // message digest object + var md = { + algorithm: 'md5', + blockLength: 64, + digestLength: 16, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = (len[1] / 0x100000000) >>> 0; + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate MD5 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in little-endian order; since length + // is stored in bytes we multiply by 8 and add carry + var bits, carry = 0; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + bits = md.fullMessageLength[i] * 8 + carry; + carry = (bits / 0x100000000) >>> 0; + finalBlock.putInt32Le(bits >>> 0); + } + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32Le(s2.h0); + rval.putInt32Le(s2.h1); + rval.putInt32Le(s2.h2); + rval.putInt32Le(s2.h3); + return rval; + }; + + return md; +}; + +// padding, constant tables for calculating md5 +var _padding = null; +var _g = null; +var _r = null; +var _k = null; +var _initialized = false; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // g values + _g = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, + 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, + 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9]; + + // rounds table + _r = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]; + + // get the result of abs(sin(i + 1)) as a 32-bit integer + _k = new Array(64); + for(var i = 0; i < 64; ++i) { + _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000); + } + + // now initialized + _initialized = true; +} + +/** + * Updates an MD5 state with the given byte buffer. + * + * @param s the MD5 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, f, r, i; + var len = bytes.length(); + while(len >= 64) { + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + + // round 1 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32Le(); + f = d ^ (b & (c ^ d)); + t = (a + f + _k[i] + w[i]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 2 + for(; i < 32; ++i) { + f = c ^ (d & (b ^ c)); + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 3 + for(; i < 48; ++i) { + f = b ^ c ^ d; + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 4 + for(; i < 64; ++i) { + f = c ^ (b | ~d); + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + + len -= 64; + } +} + + +/***/ }), + +/***/ 7973: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Node.js module for Forge mask generation functions. + * + * @author Stefan Siegl + * + * Copyright 2012 Stefan Siegl + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(3339); + +module.exports = forge.mgf = forge.mgf || {}; +forge.mgf.mgf1 = forge.mgf1; + + +/***/ }), + +/***/ 3339: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of mask generation function MGF1. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); + +forge.mgf = forge.mgf || {}; +var mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; + +/** + * Creates a MGF1 mask generation function object. + * + * @param md the message digest API to use (eg: forge.md.sha1.create()). + * + * @return a mask generation function object. + */ +mgf1.create = function(md) { + var mgf = { + /** + * Generate mask of specified length. + * + * @param {String} seed The seed for mask generation. + * @param maskLen Number of bytes to generate. + * @return {String} The generated mask. + */ + generate: function(seed, maskLen) { + /* 2. Let T be the empty octet string. */ + var t = new forge.util.ByteBuffer(); + + /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */ + var len = Math.ceil(maskLen / md.digestLength); + for(var i = 0; i < len; i++) { + /* a. Convert counter to an octet string C of length 4 octets */ + var c = new forge.util.ByteBuffer(); + c.putInt32(i); + + /* b. Concatenate the hash of the seed mgfSeed and C to the octet + * string T: */ + md.start(); + md.update(seed + c.getBytes()); + t.putBuffer(md.digest()); + } + + /* Output the leading maskLen octets of T as the octet string mask. */ + t.truncate(t.length() - maskLen); + return t.getBytes(); + } + }; + + return mgf; +}; + + +/***/ }), + +/***/ 1925: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Object IDs for ASN.1. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); + +forge.pki = forge.pki || {}; +var oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {}; + +// set id to name mapping and name to id mapping +function _IN(id, name) { + oids[id] = name; + oids[name] = id; +} +// set id to name mapping only +function _I_(id, name) { + oids[id] = name; +} + +// algorithm OIDs +_IN('1.2.840.113549.1.1.1', 'rsaEncryption'); +// Note: md2 & md4 not implemented +//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption'); +//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption'); +_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); +_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); +_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); +_IN('1.2.840.113549.1.1.8', 'mgf1'); +_IN('1.2.840.113549.1.1.9', 'pSpecified'); +_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); +_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); +_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); +_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); +// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519 +_IN('1.3.101.112', 'EdDSA25519'); + +_IN('1.2.840.10040.4.3', 'dsa-with-sha1'); + +_IN('1.3.14.3.2.7', 'desCBC'); + +_IN('1.3.14.3.2.26', 'sha1'); +// Deprecated equivalent of sha1WithRSAEncryption +_IN('1.3.14.3.2.29', 'sha1WithRSASignature'); +_IN('2.16.840.1.101.3.4.2.1', 'sha256'); +_IN('2.16.840.1.101.3.4.2.2', 'sha384'); +_IN('2.16.840.1.101.3.4.2.3', 'sha512'); +_IN('2.16.840.1.101.3.4.2.4', 'sha224'); +_IN('2.16.840.1.101.3.4.2.5', 'sha512-224'); +_IN('2.16.840.1.101.3.4.2.6', 'sha512-256'); +_IN('1.2.840.113549.2.2', 'md2'); +_IN('1.2.840.113549.2.5', 'md5'); + +// pkcs#7 content types +_IN('1.2.840.113549.1.7.1', 'data'); +_IN('1.2.840.113549.1.7.2', 'signedData'); +_IN('1.2.840.113549.1.7.3', 'envelopedData'); +_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); +_IN('1.2.840.113549.1.7.5', 'digestedData'); +_IN('1.2.840.113549.1.7.6', 'encryptedData'); + +// pkcs#9 oids +_IN('1.2.840.113549.1.9.1', 'emailAddress'); +_IN('1.2.840.113549.1.9.2', 'unstructuredName'); +_IN('1.2.840.113549.1.9.3', 'contentType'); +_IN('1.2.840.113549.1.9.4', 'messageDigest'); +_IN('1.2.840.113549.1.9.5', 'signingTime'); +_IN('1.2.840.113549.1.9.6', 'counterSignature'); +_IN('1.2.840.113549.1.9.7', 'challengePassword'); +_IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); +_IN('1.2.840.113549.1.9.14', 'extensionRequest'); + +_IN('1.2.840.113549.1.9.20', 'friendlyName'); +_IN('1.2.840.113549.1.9.21', 'localKeyId'); +_IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); + +// pkcs#12 safe bags +_IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); +_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); +_IN('1.2.840.113549.1.12.10.1.3', 'certBag'); +_IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); +_IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); +_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); + +// password-based-encryption for pkcs#12 +_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); +_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); + +_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); +_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); +_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); +_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); +_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); +_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); + +// hmac OIDs +_IN('1.2.840.113549.2.7', 'hmacWithSHA1'); +_IN('1.2.840.113549.2.8', 'hmacWithSHA224'); +_IN('1.2.840.113549.2.9', 'hmacWithSHA256'); +_IN('1.2.840.113549.2.10', 'hmacWithSHA384'); +_IN('1.2.840.113549.2.11', 'hmacWithSHA512'); + +// symmetric key algorithm oids +_IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); +_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); +_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); +_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); + +// certificate issuer/subject OIDs +_IN('2.5.4.3', 'commonName'); +_IN('2.5.4.4', 'surname'); +_IN('2.5.4.5', 'serialNumber'); +_IN('2.5.4.6', 'countryName'); +_IN('2.5.4.7', 'localityName'); +_IN('2.5.4.8', 'stateOrProvinceName'); +_IN('2.5.4.9', 'streetAddress'); +_IN('2.5.4.10', 'organizationName'); +_IN('2.5.4.11', 'organizationalUnitName'); +_IN('2.5.4.12', 'title'); +_IN('2.5.4.13', 'description'); +_IN('2.5.4.15', 'businessCategory'); +_IN('2.5.4.17', 'postalCode'); +_IN('2.5.4.42', 'givenName'); +_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName'); +_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName'); + +// X.509 extension OIDs +_IN('2.16.840.1.113730.1.1', 'nsCertType'); +_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used +_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35 +_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15 +_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32 +_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15 +_I_('2.5.29.5', 'policyMapping'); // deprecated use .33 +_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30 +_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17 +_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18 +_I_('2.5.29.9', 'subjectDirectoryAttributes'); +_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19 +_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30 +_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36 +_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19 +_IN('2.5.29.14', 'subjectKeyIdentifier'); +_IN('2.5.29.15', 'keyUsage'); +_I_('2.5.29.16', 'privateKeyUsagePeriod'); +_IN('2.5.29.17', 'subjectAltName'); +_IN('2.5.29.18', 'issuerAltName'); +_IN('2.5.29.19', 'basicConstraints'); +_I_('2.5.29.20', 'cRLNumber'); +_I_('2.5.29.21', 'cRLReason'); +_I_('2.5.29.22', 'expirationDate'); +_I_('2.5.29.23', 'instructionCode'); +_I_('2.5.29.24', 'invalidityDate'); +_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31 +_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28 +_I_('2.5.29.27', 'deltaCRLIndicator'); +_I_('2.5.29.28', 'issuingDistributionPoint'); +_I_('2.5.29.29', 'certificateIssuer'); +_I_('2.5.29.30', 'nameConstraints'); +_IN('2.5.29.31', 'cRLDistributionPoints'); +_IN('2.5.29.32', 'certificatePolicies'); +_I_('2.5.29.33', 'policyMappings'); +_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36 +_IN('2.5.29.35', 'authorityKeyIdentifier'); +_I_('2.5.29.36', 'policyConstraints'); +_IN('2.5.29.37', 'extKeyUsage'); +_I_('2.5.29.46', 'freshestCRL'); +_I_('2.5.29.54', 'inhibitAnyPolicy'); + +// extKeyUsage purposes +_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); +_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); +_IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); +_IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); +_IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); +_IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); +_IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); + + +/***/ }), + +/***/ 1281: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Password-based encryption functions. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * An EncryptedPrivateKeyInfo: + * + * EncryptedPrivateKeyInfo ::= SEQUENCE { + * encryptionAlgorithm EncryptionAlgorithmIdentifier, + * encryptedData EncryptedData } + * + * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * EncryptedData ::= OCTET STRING + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7994); +__nccwpck_require__(9549); +__nccwpck_require__(7157); +__nccwpck_require__(6231); +__nccwpck_require__(1925); +__nccwpck_require__(1611); +__nccwpck_require__(154); +__nccwpck_require__(7821); +__nccwpck_require__(9965); +__nccwpck_require__(3921); +__nccwpck_require__(8339); + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; +} + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +/* Password-based encryption implementation. */ +var pki = forge.pki = forge.pki || {}; +module.exports = pki.pbe = forge.pbe = forge.pbe || {}; +var oids = pki.oids; + +// validator for an EncryptedPrivateKeyInfo structure +// Note: Currently only works w/algorithm params +var encryptedPrivateKeyValidator = { + name: 'EncryptedPrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encryptionOid' + }, { + name: 'AlgorithmIdentifier.parameters', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'encryptionParams' + }] + }, { + // encryptedData + name: 'EncryptedPrivateKeyInfo.encryptedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encryptedData' + }] +}; + +// validator for a PBES2Algorithms structure +// Note: Currently only works w/PBKDF2 + AES encryption schemes +var PBES2AlgorithmsValidator = { + name: 'PBES2Algorithms', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.keyDerivationFunc', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.keyDerivationFunc.oid', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'kdfOid' + }, { + name: 'PBES2Algorithms.params', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.params.salt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'kdfSalt' + }, { + name: 'PBES2Algorithms.params.iterationCount', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'kdfIterationCount' + }, { + name: 'PBES2Algorithms.params.keyLength', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: 'keyLength' + }, { + // prf + name: 'PBES2Algorithms.params.prf', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'PBES2Algorithms.params.prf.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'prfOid' + }] + }] + }] + }, { + name: 'PBES2Algorithms.encryptionScheme', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.encryptionScheme.oid', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encOid' + }, { + name: 'PBES2Algorithms.encryptionScheme.iv', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encIv' + }] + }] +}; + +var pkcs12PbeParamsValidator = { + name: 'pkcs-12PbeParams', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'pkcs-12PbeParams.salt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'salt' + }, { + name: 'pkcs-12PbeParams.iterations', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'iterations' + }] +}; + +/** + * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo. + * + * PBES2Algorithms ALGORITHM-IDENTIFIER ::= + * { {PBES2-params IDENTIFIED BY id-PBES2}, ...} + * + * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} + * + * PBES2-params ::= SEQUENCE { + * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}}, + * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} + * } + * + * PBES2-KDFs ALGORITHM-IDENTIFIER ::= + * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... } + * + * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... } + * + * PBKDF2-params ::= SEQUENCE { + * salt CHOICE { + * specified OCTET STRING, + * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}} + * }, + * iterationCount INTEGER (1..MAX), + * keyLength INTEGER (1..MAX) OPTIONAL, + * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 + * } + * + * @param obj the ASN.1 PrivateKeyInfo object. + * @param password the password to encrypt with. + * @param options: + * algorithm the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. + * count the iteration count to use. + * saltSize the salt size to use. + * prfAlgorithm the PRF message digest algorithm to use + * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512') + * + * @return the ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptPrivateKeyInfo = function(obj, password, options) { + // set default options + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || 'aes128'; + options.prfAlgorithm = options.prfAlgorithm || 'sha1'; + + // generate PBE params + var salt = forge.random.getBytesSync(options.saltSize); + var count = options.count; + var countBytes = asn1.integerToDer(count); + var dkLen; + var encryptionAlgorithm; + var encryptedData; + if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') { + // do PBES2 + var ivLen, encOid, cipherFn; + switch(options.algorithm) { + case 'aes128': + dkLen = 16; + ivLen = 16; + encOid = oids['aes128-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes192': + dkLen = 24; + ivLen = 16; + encOid = oids['aes192-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes256': + dkLen = 32; + ivLen = 16; + encOid = oids['aes256-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'des': + dkLen = 8; + ivLen = 8; + encOid = oids['desCBC']; + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + + // get PRF message digest + var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase(); + var md = prfAlgorithmToMessageDigest(prfAlgorithm); + + // encrypt private key using pbe SHA-1 and AES/DES + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = forge.random.getBytesSync(ivLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + + // get PBKDF2-params + var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); + + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pkcs5PBES2']).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // keyDerivationFunc + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()), + // PBKDF2-params + params + ]), + // encryptionScheme + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(encOid).getBytes()), + // iv + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv) + ]) + ]) + ]); + } else if(options.algorithm === '3des') { + // Do PKCS12 PBE + dkLen = 24; + + var saltBytes = new forge.util.ByteBuffer(salt); + var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); + var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); + var cipher = forge.des.createEncryptionCipher(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()), + // pkcs-12PbeParams + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), + // iteration count + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + countBytes.getBytes()) + ]) + ]); + } else { + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + + // EncryptedPrivateKeyInfo + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // encryptionAlgorithm + encryptionAlgorithm, + // encryptedData + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData) + ]); + return rval; +}; + +/** + * Decrypts a ASN.1 PrivateKeyInfo object. + * + * @param obj the ASN.1 EncryptedPrivateKeyInfo object. + * @param password the password to decrypt with. + * + * @return the ASN.1 PrivateKeyInfo on success, null on failure. + */ +pki.decryptPrivateKeyInfo = function(obj, password) { + var rval = null; + + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read encrypted private key. ' + + 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + // get cipher + var oid = asn1.derToOid(capture.encryptionOid); + var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password); + + // get encrypted data + var encrypted = forge.util.createBuffer(capture.encryptedData); + + cipher.update(encrypted); + if(cipher.finish()) { + rval = asn1.fromDer(cipher.output); + } + + return rval; +}; + +/** + * Converts a EncryptedPrivateKeyInfo to PEM format. + * + * @param epki the EncryptedPrivateKeyInfo. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted encrypted private key. + */ +pki.encryptedPrivateKeyToPem = function(epki, maxline) { + // convert to DER, then PEM-encode + var msg = { + type: 'ENCRYPTED PRIVATE KEY', + body: asn1.toDer(epki).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption + * is not performed. + * + * @param pem the EncryptedPrivateKeyInfo in PEM-format. + * + * @return the ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptedPrivateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'ENCRYPTED PRIVATE KEY') { + var error = new Error('Could not convert encrypted private key from PEM; ' + + 'PEM header type is "ENCRYPTED PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert encrypted private key from PEM; ' + + 'PEM is encrypted.'); + } + + // convert DER to ASN.1 object + return asn1.fromDer(msg.body); +}; + +/** + * Encrypts an RSA private key. By default, the key will be wrapped in + * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo. + * This is the standard, preferred way to encrypt a private key. + * + * To produce a non-standard PEM-encrypted private key that uses encapsulated + * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL + * private key encryption), set the 'legacy' option to true. Note: Using this + * option will cause the iteration count to be forced to 1. + * + * Note: The 'des' algorithm is supported, but it is not considered to be + * secure because it only uses a single 56-bit key. If possible, it is highly + * recommended that a different algorithm be used. + * + * @param rsaKey the RSA key to encrypt. + * @param password the password to use. + * @param options: + * algorithm: the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des', 'des'). + * count: the iteration count to use. + * saltSize: the salt size to use. + * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated + * headers (DEK-Info) private key. + * + * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptRsaPrivateKey = function(rsaKey, password, options) { + // standard PKCS#8 + options = options || {}; + if(!options.legacy) { + // encrypt PrivateKeyInfo + var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey)); + rval = pki.encryptPrivateKeyInfo(rval, password, options); + return pki.encryptedPrivateKeyToPem(rval); + } + + // legacy non-PKCS#8 + var algorithm; + var iv; + var dkLen; + var cipherFn; + switch(options.algorithm) { + case 'aes128': + algorithm = 'AES-128-CBC'; + dkLen = 16; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes192': + algorithm = 'AES-192-CBC'; + dkLen = 24; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes256': + algorithm = 'AES-256-CBC'; + dkLen = 32; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case '3des': + algorithm = 'DES-EDE3-CBC'; + dkLen = 24; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + case 'des': + algorithm = 'DES-CBC'; + dkLen = 8; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error = new Error('Could not encrypt RSA private key; unsupported ' + + 'encryption algorithm "' + options.algorithm + '".'); + error.algorithm = options.algorithm; + throw error; + } + + // encrypt private key using OpenSSL legacy key derivation + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))); + cipher.finish(); + + var msg = { + type: 'RSA PRIVATE KEY', + procType: { + version: '4', + type: 'ENCRYPTED' + }, + dekInfo: { + algorithm: algorithm, + parameters: forge.util.bytesToHex(iv).toUpperCase() + }, + body: cipher.output.getBytes() + }; + return forge.pem.encode(msg); +}; + +/** + * Decrypts an RSA private key. + * + * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt. + * @param password the password to use. + * + * @return the RSA key on success, null on failure. + */ +pki.decryptRsaPrivateKey = function(pem, password) { + var rval = null; + + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'ENCRYPTED PRIVATE KEY' && + msg.type !== 'PRIVATE KEY' && + msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM header type ' + + 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); + error.headerType = error; + throw error; + } + + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + var dkLen; + var cipherFn; + switch(msg.dekInfo.algorithm) { + case 'DES-CBC': + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'DES-EDE3-CBC': + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'AES-128-CBC': + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'AES-192-CBC': + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'AES-256-CBC': + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'RC2-40-CBC': + dkLen = 5; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 40); + }; + break; + case 'RC2-64-CBC': + dkLen = 8; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 64); + }; + break; + case 'RC2-128-CBC': + dkLen = 16; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 128); + }; + break; + default: + var error = new Error('Could not decrypt private key; unsupported ' + + 'encryption algorithm "' + msg.dekInfo.algorithm + '".'); + error.algorithm = msg.dekInfo.algorithm; + throw error; + } + + // use OpenSSL legacy key derivation + var iv = forge.util.hexToBytes(msg.dekInfo.parameters); + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(forge.util.createBuffer(msg.body)); + if(cipher.finish()) { + rval = cipher.output.getBytes(); + } else { + return rval; + } + } else { + rval = msg.body; + } + + if(msg.type === 'ENCRYPTED PRIVATE KEY') { + rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password); + } else { + // decryption already performed above + rval = asn1.fromDer(rval); + } + + if(rval !== null) { + rval = pki.privateKeyFromAsn1(rval); + } + + return rval; +}; + +/** + * Derives a PKCS#12 key. + * + * @param password the password to derive the key material from, null or + * undefined for none. + * @param salt the salt, as a ByteBuffer, to use. + * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). + * @param iter the iteration count. + * @param n the number of bytes to derive from the password. + * @param md the message digest to use, defaults to SHA-1. + * + * @return a ByteBuffer with the bytes derived from the password. + */ +pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { + var j, l; + + if(typeof md === 'undefined' || md === null) { + if(!('sha1' in forge.md)) { + throw new Error('"sha1" hash algorithm unavailable.'); + } + md = forge.md.sha1.create(); + } + + var u = md.digestLength; + var v = md.blockLength; + var result = new forge.util.ByteBuffer(); + + /* Convert password to Unicode byte buffer + trailing 0-byte. */ + var passBuf = new forge.util.ByteBuffer(); + if(password !== null && password !== undefined) { + for(l = 0; l < password.length; l++) { + passBuf.putInt16(password.charCodeAt(l)); + } + passBuf.putInt16(0); + } + + /* Length of salt and password in BYTES. */ + var p = passBuf.length(); + var s = salt.length(); + + /* 1. Construct a string, D (the "diversifier"), by concatenating + v copies of ID. */ + var D = new forge.util.ByteBuffer(); + D.fillWithByte(id, v); + + /* 2. Concatenate copies of the salt together to create a string S of length + v * ceil(s / v) bytes (the final copy of the salt may be trunacted + to create S). + Note that if the salt is the empty string, then so is S. */ + var Slen = v * Math.ceil(s / v); + var S = new forge.util.ByteBuffer(); + for(l = 0; l < Slen; l++) { + S.putByte(salt.at(l % s)); + } + + /* 3. Concatenate copies of the password together to create a string P of + length v * ceil(p / v) bytes (the final copy of the password may be + truncated to create P). + Note that if the password is the empty string, then so is P. */ + var Plen = v * Math.ceil(p / v); + var P = new forge.util.ByteBuffer(); + for(l = 0; l < Plen; l++) { + P.putByte(passBuf.at(l % p)); + } + + /* 4. Set I=S||P to be the concatenation of S and P. */ + var I = S; + I.putBuffer(P); + + /* 5. Set c=ceil(n / u). */ + var c = Math.ceil(n / u); + + /* 6. For i=1, 2, ..., c, do the following: */ + for(var i = 1; i <= c; i++) { + /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */ + var buf = new forge.util.ByteBuffer(); + buf.putBytes(D.bytes()); + buf.putBytes(I.bytes()); + for(var round = 0; round < iter; round++) { + md.start(); + md.update(buf.getBytes()); + buf = md.digest(); + } + + /* b) Concatenate copies of Ai to create a string B of length v bytes (the + final copy of Ai may be truncated to create B). */ + var B = new forge.util.ByteBuffer(); + for(l = 0; l < v; l++) { + B.putByte(buf.at(l % u)); + } + + /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks, + where k=ceil(s / v) + ceil(p / v), modify I by setting + Ij=(Ij+B+1) mod 2v for each j. */ + var k = Math.ceil(s / v) + Math.ceil(p / v); + var Inew = new forge.util.ByteBuffer(); + for(j = 0; j < k; j++) { + var chunk = new forge.util.ByteBuffer(I.getBytes(v)); + var x = 0x1ff; + for(l = B.length() - 1; l >= 0; l--) { + x = x >> 8; + x += B.at(l) + chunk.at(l); + chunk.setAt(l, x & 0xff); + } + Inew.putBuffer(chunk); + } + I = Inew; + + /* Add Ai to A. */ + result.putBuffer(buf); + } + + result.truncate(result.length() - n); + return result; +}; + +/** + * Get new Forge cipher object instance. + * + * @param oid the OID (in string notation). + * @param params the ASN.1 params object. + * @param password the password to decrypt with. + * + * @return new cipher object instance. + */ +pki.pbe.getCipher = function(oid, params, password) { + switch(oid) { + case pki.oids['pkcs5PBES2']: + return pki.pbe.getCipherForPBES2(oid, params, password); + + case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + case pki.oids['pbewithSHAAnd40BitRC2-CBC']: + return pki.pbe.getCipherForPKCS12PBE(oid, params, password); + + default: + var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.'); + error.oid = oid; + error.supportedOids = [ + 'pkcs5PBES2', + 'pbeWithSHAAnd3-KeyTripleDES-CBC', + 'pbewithSHAAnd40BitRC2-CBC' + ]; + throw error; + } +}; + +/** + * Get new Forge cipher object instance according to PBES2 params block. + * + * The returned cipher instance is already started using the IV + * from PBES2 parameter block. + * + * @param oid the PKCS#5 PBKDF2 OID (in string notation). + * @param params the ASN.1 PBES2-params object. + * @param password the password to decrypt with. + * + * @return new cipher object instance. + */ +pki.pbe.getCipherForPBES2 = function(oid, params, password) { + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + // check oids + oid = asn1.derToOid(capture.kdfOid); + if(oid !== pki.oids['pkcs5PBKDF2']) { + var error = new Error('Cannot read encrypted private key. ' + + 'Unsupported key derivation function OID.'); + error.oid = oid; + error.supportedOids = ['pkcs5PBKDF2']; + throw error; + } + oid = asn1.derToOid(capture.encOid); + if(oid !== pki.oids['aes128-CBC'] && + oid !== pki.oids['aes192-CBC'] && + oid !== pki.oids['aes256-CBC'] && + oid !== pki.oids['des-EDE3-CBC'] && + oid !== pki.oids['desCBC']) { + var error = new Error('Cannot read encrypted private key. ' + + 'Unsupported encryption scheme OID.'); + error.oid = oid; + error.supportedOids = [ + 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC']; + throw error; + } + + // set PBE params + var salt = capture.kdfSalt; + var count = forge.util.createBuffer(capture.kdfIterationCount); + count = count.getInt(count.length() << 3); + var dkLen; + var cipherFn; + switch(pki.oids[oid]) { + case 'aes128-CBC': + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'aes192-CBC': + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'aes256-CBC': + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'des-EDE3-CBC': + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'desCBC': + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + } + + // get PRF message digest + var md = prfOidToMessageDigest(capture.prfOid); + + // decrypt private key using pbe with chosen PRF and AES/DES + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = capture.encIv; + var cipher = cipherFn(dk); + cipher.start(iv); + + return cipher; +}; + +/** + * Get new Forge cipher object instance for PKCS#12 PBE. + * + * The returned cipher instance is already started using the key & IV + * derived from the provided password and PKCS#12 PBE salt. + * + * @param oid The PKCS#12 PBE OID (in string notation). + * @param params The ASN.1 PKCS#12 PBE-params object. + * @param password The password to decrypt with. + * + * @return the new cipher object instance. + */ +pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) { + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + var salt = forge.util.createBuffer(capture.salt); + var count = forge.util.createBuffer(capture.iterations); + count = count.getInt(count.length() << 3); + + var dkLen, dIvLen, cipherFn; + switch(oid) { + case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + dkLen = 24; + dIvLen = 8; + cipherFn = forge.des.startDecrypting; + break; + + case pki.oids['pbewithSHAAnd40BitRC2-CBC']: + dkLen = 5; + dIvLen = 8; + cipherFn = function(key, iv) { + var cipher = forge.rc2.createDecryptionCipher(key, 40); + cipher.start(iv, null); + return cipher; + }; + break; + + default: + var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.'); + error.oid = oid; + throw error; + } + + // get PRF message digest + var md = prfOidToMessageDigest(capture.prfOid); + var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); + md.start(); + var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); + + return cipherFn(key, iv); +}; + +/** + * OpenSSL's legacy key derivation function. + * + * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html + * + * @param password the password to derive the key from. + * @param salt the salt to use, null for none. + * @param dkLen the number of bytes needed for the derived key. + * @param [options] the options to use: + * [md] an optional message digest object to use. + */ +pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { + if(typeof md === 'undefined' || md === null) { + if(!('md5' in forge.md)) { + throw new Error('"md5" hash algorithm unavailable.'); + } + md = forge.md.md5.create(); + } + if(salt === null) { + salt = ''; + } + var digests = [hash(md, password + salt)]; + for(var length = 16, i = 1; length < dkLen; ++i, length += 16) { + digests.push(hash(md, digests[i - 1] + password + salt)); + } + return digests.join('').substr(0, dkLen); +}; + +function hash(md, bytes) { + return md.start().update(bytes).digest().getBytes(); +} + +function prfOidToMessageDigest(prfOid) { + // get PRF algorithm, default to SHA-1 + var prfAlgorithm; + if(!prfOid) { + prfAlgorithm = 'hmacWithSHA1'; + } else { + prfAlgorithm = pki.oids[asn1.derToOid(prfOid)]; + if(!prfAlgorithm) { + var error = new Error('Unsupported PRF OID.'); + error.oid = prfOid; + error.supported = [ + 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', + 'hmacWithSHA512']; + throw error; + } + } + return prfAlgorithmToMessageDigest(prfAlgorithm); +} + +function prfAlgorithmToMessageDigest(prfAlgorithm) { + var factory = forge.md; + switch(prfAlgorithm) { + case 'hmacWithSHA224': + factory = forge.md.sha512; + case 'hmacWithSHA1': + case 'hmacWithSHA256': + case 'hmacWithSHA384': + case 'hmacWithSHA512': + prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); + break; + default: + var error = new Error('Unsupported PRF algorithm.'); + error.algorithm = prfAlgorithm; + error.supported = [ + 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', + 'hmacWithSHA512']; + throw error; + } + if(!factory || !(prfAlgorithm in factory)) { + throw new Error('Unknown hash algorithm: ' + prfAlgorithm); + } + return factory[prfAlgorithm].create(); +} + +function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { + var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), + // iteration count + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + countBytes.getBytes()) + ]); + // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm + if(prfAlgorithm !== 'hmacWithSHA1') { + params.value.push( + // key length + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(dkLen.toString(16))), + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + } + return params; +} + + +/***/ }), + +/***/ 1611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Password-Based Key-Derivation Function #2 implementation. + * + * See RFC 2898 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(5104); +__nccwpck_require__(6231); +__nccwpck_require__(8339); + +var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; + +var crypto; +if(forge.util.isNodejs && !forge.options.usePureJavaScript) { + crypto = __nccwpck_require__(6113); +} + +/** + * Derives a key from a password. + * + * @param p the password as a binary-encoded string of bytes. + * @param s the salt as a binary-encoded string of bytes. + * @param c the iteration count, a positive integer. + * @param dkLen the intended length, in bytes, of the derived key, + * (max: 2^32 - 1) * hash length of the PRF. + * @param [md] the message digest (or algorithm identifier as a string) to use + * in the PRF, defaults to SHA-1. + * @param [callback(err, key)] presence triggers asynchronous version, called + * once the operation completes. + * + * @return the derived key, as a binary-encoded string of bytes, for the + * synchronous version (if no callback is specified). + */ +module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function( + p, s, c, dkLen, md, callback) { + if(typeof md === 'function') { + callback = md; + md = null; + } + + // use native implementation if possible and not disabled, note that + // some node versions only support SHA-1, others allow digest to be changed + if(forge.util.isNodejs && !forge.options.usePureJavaScript && + crypto.pbkdf2 && (md === null || typeof md !== 'object') && + (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) { + if(typeof md !== 'string') { + // default prf to SHA-1 + md = 'sha1'; + } + p = Buffer.from(p, 'binary'); + s = Buffer.from(s, 'binary'); + if(!callback) { + if(crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary'); + } + return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); + } + if(crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2(p, s, c, dkLen, function(err, key) { + if(err) { + return callback(err); + } + callback(null, key.toString('binary')); + }); + } + return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) { + if(err) { + return callback(err); + } + callback(null, key.toString('binary')); + }); + } + + if(typeof md === 'undefined' || md === null) { + // default prf to SHA-1 + md = 'sha1'; + } + if(typeof md === 'string') { + if(!(md in forge.md.algorithms)) { + throw new Error('Unknown hash algorithm: ' + md); + } + md = forge.md[md].create(); + } + + var hLen = md.digestLength; + + /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and + stop. */ + if(dkLen > (0xFFFFFFFF * hLen)) { + var err = new Error('Derived key is too long.'); + if(callback) { + return callback(err); + } + throw err; + } + + /* 2. Let len be the number of hLen-octet blocks in the derived key, + rounding up, and let r be the number of octets in the last + block: + + len = CEIL(dkLen / hLen), + r = dkLen - (len - 1) * hLen. */ + var len = Math.ceil(dkLen / hLen); + var r = dkLen - (len - 1) * hLen; + + /* 3. For each block of the derived key apply the function F defined + below to the password P, the salt S, the iteration count c, and + the block index to compute the block: + + T_1 = F(P, S, c, 1), + T_2 = F(P, S, c, 2), + ... + T_len = F(P, S, c, len), + + where the function F is defined as the exclusive-or sum of the + first c iterates of the underlying pseudorandom function PRF + applied to the password P and the concatenation of the salt S + and the block index i: + + F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c + + where + + u_1 = PRF(P, S || INT(i)), + u_2 = PRF(P, u_1), + ... + u_c = PRF(P, u_{c-1}). + + Here, INT(i) is a four-octet encoding of the integer i, most + significant octet first. */ + var prf = forge.hmac.create(); + prf.start(md, p); + var dk = ''; + var xor, u_c, u_c1; + + // sync version + if(!callback) { + for(var i = 1; i <= len; ++i) { + // PRF(P, S || INT(i)) (first iteration) + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + + // PRF(P, u_{c-1}) (other iterations) + for(var j = 2; j <= c; ++j) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + // F(p, s, c, i) + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + } + + /* 4. Concatenate the blocks and extract the first dkLen octets to + produce a derived key DK: + + DK = T_1 || T_2 || ... || T_len<0..r-1> */ + dk += (i < len) ? xor : xor.substr(0, r); + } + /* 5. Output the derived key DK. */ + return dk; + } + + // async version + var i = 1, j; + function outer() { + if(i > len) { + // done + return callback(null, dk); + } + + // PRF(P, S || INT(i)) (first iteration) + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + + // PRF(P, u_{c-1}) (other iterations) + j = 2; + inner(); + } + + function inner() { + if(j <= c) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + // F(p, s, c, i) + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + ++j; + return forge.util.setImmediate(inner); + } + + /* 4. Concatenate the blocks and extract the first dkLen octets to + produce a derived key DK: + + DK = T_1 || T_2 || ... || T_len<0..r-1> */ + dk += (i < len) ? xor : xor.substr(0, r); + + ++i; + outer(); + } + + outer(); +}; + + +/***/ }), + +/***/ 154: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms. + * + * See: RFC 1421. + * + * @author Dave Longley + * + * Copyright (c) 2013-2014 Digital Bazaar, Inc. + * + * A Forge PEM object has the following fields: + * + * type: identifies the type of message (eg: "RSA PRIVATE KEY"). + * + * procType: identifies the type of processing performed on the message, + * it has two subfields: version and type, eg: 4,ENCRYPTED. + * + * contentDomain: identifies the type of content in the message, typically + * only uses the value: "RFC822". + * + * dekInfo: identifies the message encryption algorithm and mode and includes + * any parameters for the algorithm, it has two subfields: algorithm and + * parameters, eg: DES-CBC,F8143EDE5960C597. + * + * headers: contains all other PEM encapsulated headers -- where order is + * significant (for pairing data like recipient ID + key info). + * + * body: the binary-encoded body. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); + +// shortcut for pem API +var pem = module.exports = forge.pem = forge.pem || {}; + +/** + * Encodes (serializes) the given PEM object. + * + * @param msg the PEM message object to encode. + * @param options the options to use: + * maxline the maximum characters per line for the body, (default: 64). + * + * @return the PEM-formatted string. + */ +pem.encode = function(msg, options) { + options = options || {}; + var rval = '-----BEGIN ' + msg.type + '-----\r\n'; + + // encode special headers + var header; + if(msg.procType) { + header = { + name: 'Proc-Type', + values: [String(msg.procType.version), msg.procType.type] + }; + rval += foldHeader(header); + } + if(msg.contentDomain) { + header = {name: 'Content-Domain', values: [msg.contentDomain]}; + rval += foldHeader(header); + } + if(msg.dekInfo) { + header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]}; + if(msg.dekInfo.parameters) { + header.values.push(msg.dekInfo.parameters); + } + rval += foldHeader(header); + } + + if(msg.headers) { + // encode all other headers + for(var i = 0; i < msg.headers.length; ++i) { + rval += foldHeader(msg.headers[i]); + } + } + + // terminate header + if(msg.procType) { + rval += '\r\n'; + } + + // add body + rval += forge.util.encode64(msg.body, options.maxline || 64) + '\r\n'; + + rval += '-----END ' + msg.type + '-----\r\n'; + return rval; +}; + +/** + * Decodes (deserializes) all PEM messages found in the given string. + * + * @param str the PEM-formatted string to decode. + * + * @return the PEM message objects in an array. + */ +pem.decode = function(str) { + var rval = []; + + // split string into PEM messages (be lenient w/EOF on BEGIN line) + var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; + var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; + var rCRLF = /\r?\n/; + var match; + while(true) { + match = rMessage.exec(str); + if(!match) { + break; + } + + // accept "NEW CERTIFICATE REQUEST" as "CERTIFICATE REQUEST" + // https://datatracker.ietf.org/doc/html/rfc7468#section-7 + var type = match[1]; + if(type === 'NEW CERTIFICATE REQUEST') { + type = 'CERTIFICATE REQUEST'; + } + + var msg = { + type: type, + procType: null, + contentDomain: null, + dekInfo: null, + headers: [], + body: forge.util.decode64(match[3]) + }; + rval.push(msg); + + // no headers + if(!match[2]) { + continue; + } + + // parse headers + var lines = match[2].split(rCRLF); + var li = 0; + while(match && li < lines.length) { + // get line, trim any rhs whitespace + var line = lines[li].replace(/\s+$/, ''); + + // RFC2822 unfold any following folded lines + for(var nl = li + 1; nl < lines.length; ++nl) { + var next = lines[nl]; + if(!/\s/.test(next[0])) { + break; + } + line += next; + li = nl; + } + + // parse header + match = line.match(rHeader); + if(match) { + var header = {name: match[1], values: []}; + var values = match[2].split(','); + for(var vi = 0; vi < values.length; ++vi) { + header.values.push(ltrim(values[vi])); + } + + // Proc-Type must be the first header + if(!msg.procType) { + if(header.name !== 'Proc-Type') { + throw new Error('Invalid PEM formatted message. The first ' + + 'encapsulated header must be "Proc-Type".'); + } else if(header.values.length !== 2) { + throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + + 'header must have two subfields.'); + } + msg.procType = {version: values[0], type: values[1]}; + } else if(!msg.contentDomain && header.name === 'Content-Domain') { + // special-case Content-Domain + msg.contentDomain = values[0] || ''; + } else if(!msg.dekInfo && header.name === 'DEK-Info') { + // special-case DEK-Info + if(header.values.length === 0) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + + 'header must have at least one subfield.'); + } + msg.dekInfo = {algorithm: values[0], parameters: values[1] || null}; + } else { + msg.headers.push(header); + } + } + + ++li; + } + + if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + + 'header must be present if "Proc-Type" is "ENCRYPTED".'); + } + } + + if(rval.length === 0) { + throw new Error('Invalid PEM formatted message.'); + } + + return rval; +}; + +function foldHeader(header) { + var rval = header.name + ': '; + + // ensure values with CRLF are folded + var values = []; + var insertSpace = function(match, $1) { + return ' ' + $1; + }; + for(var i = 0; i < header.values.length; ++i) { + values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); + } + rval += values.join(',') + '\r\n'; + + // do folding + var length = 0; + var candidate = -1; + for(var i = 0; i < rval.length; ++i, ++length) { + if(length > 65 && candidate !== -1) { + var insert = rval[candidate]; + if(insert === ',') { + ++candidate; + rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate); + } else { + rval = rval.substr(0, candidate) + + '\r\n' + insert + rval.substr(candidate + 1); + } + length = (i - candidate - 1); + candidate = -1; + ++i; + } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') { + candidate = i; + } + } + + return rval; +} + +function ltrim(str) { + return str.replace(/^\s+/, ''); +} + + +/***/ }), + +/***/ 7014: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Partial implementation of PKCS#1 v2.2: RSA-OEAP + * + * Modified but based on the following MIT and BSD licensed code: + * + * https://github.com/kjur/jsjws/blob/master/rsa.js: + * + * The 'jsjws'(JSON Web Signature JavaScript Library) License + * + * Copyright (c) 2012 Kenji Urushima + * + * 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. + * + * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain: + * + * RSAES-OAEP.js + * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $ + * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002) + * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003. + * Contact: ellis@nukinetics.com + * Distributed under the BSD License. + * + * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125 + * + * @author Evan Jones (http://evanjones.ca/) + * @author Dave Longley + * + * Copyright (c) 2013-2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); +__nccwpck_require__(7821); +__nccwpck_require__(279); + +// shortcut for PKCS#1 API +var pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {}; + +/** + * Encode the given RSAES-OAEP message (M) using key, with optional label (L) + * and seed. + * + * This method does not perform RSA encryption, it only encodes the message + * using RSAES-OAEP. + * + * @param key the RSA key to use. + * @param message the message to encode. + * @param options the options to use: + * label an optional label to use. + * seed the seed to use. + * md the message digest object to use, undefined for SHA-1. + * mgf1 optional mgf1 parameters: + * md the message digest object to use for MGF1. + * + * @return the encoded message bytes. + */ +pkcs1.encode_rsa_oaep = function(key, message, options) { + // parse arguments + var label; + var seed; + var md; + var mgf1Md; + // legacy args (label, seed, md) + if(typeof options === 'string') { + label = options; + seed = arguments[3] || undefined; + md = arguments[4] || undefined; + } else if(options) { + label = options.label || undefined; + seed = options.seed || undefined; + md = options.md || undefined; + if(options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + + // default OAEP to SHA-1 message digest + if(!md) { + md = forge.md.sha1.create(); + } else { + md.start(); + } + + // default MGF-1 to same as OAEP + if(!mgf1Md) { + mgf1Md = md; + } + + // compute length in bytes and check output + var keyLength = Math.ceil(key.n.bitLength() / 8); + var maxLength = keyLength - 2 * md.digestLength - 2; + if(message.length > maxLength) { + var error = new Error('RSAES-OAEP input message length is too long.'); + error.length = message.length; + error.maxLength = maxLength; + throw error; + } + + if(!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest(); + + var PS = ''; + var PS_length = maxLength - message.length; + for(var i = 0; i < PS_length; i++) { + PS += '\x00'; + } + + var DB = lHash.getBytes() + PS + '\x01' + message; + + if(!seed) { + seed = forge.random.getBytes(md.digestLength); + } else if(seed.length !== md.digestLength) { + var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + + 'match the digest length.'); + error.seedLength = seed.length; + error.digestLength = md.digestLength; + throw error; + } + + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); + + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); + + // return encoded message + return '\x00' + maskedSeed + maskedDB; +}; + +/** + * Decode the given RSAES-OAEP encoded message (EM) using key, with optional + * label (L). + * + * This method does not perform RSA decryption, it only decodes the message + * using RSAES-OAEP. + * + * @param key the RSA key to use. + * @param em the encoded message to decode. + * @param options the options to use: + * label an optional label to use. + * md the message digest object to use for OAEP, undefined for SHA-1. + * mgf1 optional mgf1 parameters: + * md the message digest object to use for MGF1. + * + * @return the decoded message bytes. + */ +pkcs1.decode_rsa_oaep = function(key, em, options) { + // parse args + var label; + var md; + var mgf1Md; + // legacy args + if(typeof options === 'string') { + label = options; + md = arguments[3] || undefined; + } else if(options) { + label = options.label || undefined; + md = options.md || undefined; + if(options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + + // compute length in bytes + var keyLength = Math.ceil(key.n.bitLength() / 8); + + if(em.length !== keyLength) { + var error = new Error('RSAES-OAEP encoded message length is invalid.'); + error.length = em.length; + error.expectedLength = keyLength; + throw error; + } + + // default OAEP to SHA-1 message digest + if(md === undefined) { + md = forge.md.sha1.create(); + } else { + md.start(); + } + + // default MGF-1 to same as OAEP + if(!mgf1Md) { + mgf1Md = md; + } + + if(keyLength < 2 * md.digestLength + 2) { + throw new Error('RSAES-OAEP key is too short for the hash function.'); + } + + if(!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest().getBytes(); + + // split the message into its parts + var y = em.charAt(0); + var maskedSeed = em.substring(1, md.digestLength + 1); + var maskedDB = em.substring(1 + md.digestLength); + + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); + + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); + + var lHashPrime = db.substring(0, md.digestLength); + + // constant time check that all values match what is expected + var error = (y !== '\x00'); + + // constant time check lHash vs lHashPrime + for(var i = 0; i < md.digestLength; ++i) { + error |= (lHash.charAt(i) !== lHashPrime.charAt(i)); + } + + // "constant time" find the 0x1 byte separating the padding (zeros) from the + // message + // TODO: It must be possible to do this in a better/smarter way? + var in_ps = 1; + var index = md.digestLength; + for(var j = md.digestLength; j < db.length; j++) { + var code = db.charCodeAt(j); + + var is_0 = (code & 0x1) ^ 0x1; + + // non-zero if not 0 or 1 in the ps section + var error_mask = in_ps ? 0xfffe : 0x0000; + error |= (code & error_mask); + + // latch in_ps to zero after we find 0x1 + in_ps = in_ps & is_0; + index += in_ps; + } + + if(error || db.charCodeAt(index) !== 0x1) { + throw new Error('Invalid RSAES-OAEP padding.'); + } + + return db.substring(index + 1); +}; + +function rsa_mgf1(seed, maskLength, hash) { + // default to SHA-1 message digest + if(!hash) { + hash = forge.md.sha1.create(); + } + var t = ''; + var count = Math.ceil(maskLength / hash.digestLength); + for(var i = 0; i < count; ++i) { + var c = String.fromCharCode( + (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF); + hash.start(); + hash.update(seed + c); + t += hash.digest().getBytes(); + } + return t.substring(0, maskLength); +} + + +/***/ }), + +/***/ 466: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of PKCS#12. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * The ASN.1 representation of PKCS#12 is as follows + * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details) + * + * PFX ::= SEQUENCE { + * version INTEGER {v3(3)}(v3,...), + * authSafe ContentInfo, + * macData MacData OPTIONAL + * } + * + * MacData ::= SEQUENCE { + * mac DigestInfo, + * macSalt OCTET STRING, + * iterations INTEGER DEFAULT 1 + * } + * Note: The iterations default is for historical reasons and its use is + * deprecated. A higher value, like 1024, is recommended. + * + * DigestInfo is defined in PKCS#7 as follows: + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of SHA1 there is none. + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * Digest ::= OCTET STRING + * + * + * ContentInfo ::= SEQUENCE { + * contentType ContentType, + * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL + * } + * + * ContentType ::= OBJECT IDENTIFIER + * + * AuthenticatedSafe ::= SEQUENCE OF ContentInfo + * -- Data if unencrypted + * -- EncryptedData if password-encrypted + * -- EnvelopedData if public key-encrypted + * + * + * SafeContents ::= SEQUENCE OF SafeBag + * + * SafeBag ::= SEQUENCE { + * bagId BAG-TYPE.&id ({PKCS12BagSet}) + * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), + * bagAttributes SET OF PKCS12Attribute OPTIONAL + * } + * + * PKCS12Attribute ::= SEQUENCE { + * attrId ATTRIBUTE.&id ({PKCS12AttrSet}), + * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId}) + * } -- This type is compatible with the X.500 type 'Attribute' + * + * PKCS12AttrSet ATTRIBUTE ::= { + * friendlyName | -- from PKCS #9 + * localKeyId, -- from PKCS #9 + * ... -- Other attributes are allowed + * } + * + * CertBag ::= SEQUENCE { + * certId BAG-TYPE.&id ({CertTypes}), + * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) + * } + * + * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}} + * -- DER-encoded X.509 certificate stored in OCTET STRING + * + * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}} + * -- Base64-encoded SDSI certificate stored in IA5String + * + * CertTypes BAG-TYPE ::= { + * x509Certificate | + * sdsiCertificate, + * ... -- For future extensions + * } + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(9549); +__nccwpck_require__(5104); +__nccwpck_require__(1925); +__nccwpck_require__(266); +__nccwpck_require__(1281); +__nccwpck_require__(7821); +__nccwpck_require__(3921); +__nccwpck_require__(279); +__nccwpck_require__(8339); +__nccwpck_require__(8180); + +// shortcut for asn.1 & PKI API +var asn1 = forge.asn1; +var pki = forge.pki; + +// shortcut for PKCS#12 API +var p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {}; + +var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // a ContentInfo + constructed: true, + value: [{ + name: 'ContentInfo.contentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'ContentInfo.content', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'content' + }] +}; + +var pfxValidator = { + name: 'PFX', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PFX.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, + contentInfoValidator, { + name: 'PFX.macData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'mac', + value: [{ + name: 'PFX.macData.mac', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // DigestInfo + constructed: true, + value: [{ + name: 'PFX.macData.mac.digestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier + constructed: true, + value: [{ + name: 'PFX.macData.mac.digestAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'macAlgorithm' + }, { + name: 'PFX.macData.mac.digestAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: 'macAlgorithmParameters' + }] + }, { + name: 'PFX.macData.mac.digest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'macDigest' + }] + }, { + name: 'PFX.macData.macSalt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'macSalt' + }, { + name: 'PFX.macData.iterations', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: 'macIterations' + }] + }] +}; + +var safeBagValidator = { + name: 'SafeBag', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SafeBag.bagId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'bagId' + }, { + name: 'SafeBag.bagValue', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'bagValue' + }, { + name: 'SafeBag.bagAttributes', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + optional: true, + capture: 'bagAttributes' + }] +}; + +var attributeValidator = { + name: 'Attribute', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Attribute.attrId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'oid' + }, { + name: 'Attribute.attrValues', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + capture: 'values' + }] +}; + +var certBagValidator = { + name: 'CertBag', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'CertBag.certId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certId' + }, { + name: 'CertBag.certValue', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + /* So far we only support X.509 certificates (which are wrapped in + an OCTET STRING, hence hard code that here). */ + value: [{ + name: 'CertBag.certValue[0]', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.OCTETSTRING, + constructed: false, + capture: 'cert' + }] + }] +}; + +/** + * Search SafeContents structure for bags with matching attributes. + * + * The search can optionally be narrowed by a certain bag type. + * + * @param safeContents the SafeContents structure to search in. + * @param attrName the name of the attribute to compare against. + * @param attrValue the attribute value to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of matching bags. + */ +function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { + var result = []; + + for(var i = 0; i < safeContents.length; i++) { + for(var j = 0; j < safeContents[i].safeBags.length; j++) { + var bag = safeContents[i].safeBags[j]; + if(bagType !== undefined && bag.type !== bagType) { + continue; + } + // only filter by bag type, no attribute specified + if(attrName === null) { + result.push(bag); + continue; + } + if(bag.attributes[attrName] !== undefined && + bag.attributes[attrName].indexOf(attrValue) >= 0) { + result.push(bag); + } + } + } + + return result; +} + +/** + * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object. + * + * @param obj The PKCS#12 PFX in ASN.1 notation. + * @param strict true to use strict DER decoding, false not to (default: true). + * @param {String} password Password to decrypt with (optional). + * + * @return PKCS#12 PFX object. + */ +p12.pkcs12FromAsn1 = function(obj, strict, password) { + // handle args + if(typeof strict === 'string') { + password = strict; + strict = true; + } else if(strict === undefined) { + strict = true; + } + + // validate PFX and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, pfxValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 PFX. ' + + 'ASN.1 object is not an PKCS#12 PFX.'); + error.errors = error; + throw error; + } + + var pfx = { + version: capture.version.charCodeAt(0), + safeContents: [], + + /** + * Gets bags with matching attributes. + * + * @param filter the attributes to filter by: + * [localKeyId] the localKeyId to search for. + * [localKeyIdHex] the localKeyId in hex to search for. + * [friendlyName] the friendly name to search for. + * [bagType] bag type to narrow each attribute search by. + * + * @return a map of attribute type to an array of matching bags or, if no + * attribute was given but a bag type, the map key will be the + * bag type. + */ + getBags: function(filter) { + var rval = {}; + + var localKeyId; + if('localKeyId' in filter) { + localKeyId = filter.localKeyId; + } else if('localKeyIdHex' in filter) { + localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); + } + + // filter on bagType only + if(localKeyId === undefined && !('friendlyName' in filter) && + 'bagType' in filter) { + rval[filter.bagType] = _getBagsByAttribute( + pfx.safeContents, null, null, filter.bagType); + } + + if(localKeyId !== undefined) { + rval.localKeyId = _getBagsByAttribute( + pfx.safeContents, 'localKeyId', + localKeyId, filter.bagType); + } + if('friendlyName' in filter) { + rval.friendlyName = _getBagsByAttribute( + pfx.safeContents, 'friendlyName', + filter.friendlyName, filter.bagType); + } + + return rval; + }, + + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching friendlyName attribute. + * + * @param friendlyName the friendly name to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching friendlyName attribute. + */ + getBagsByFriendlyName: function(friendlyName, bagType) { + return _getBagsByAttribute( + pfx.safeContents, 'friendlyName', friendlyName, bagType); + }, + + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching localKeyId attribute. + * + * @param localKeyId the localKeyId to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching localKeyId attribute. + */ + getBagsByLocalKeyId: function(localKeyId, bagType) { + return _getBagsByAttribute( + pfx.safeContents, 'localKeyId', localKeyId, bagType); + } + }; + + if(capture.version.charCodeAt(0) !== 3) { + var error = new Error('PKCS#12 PFX of version other than 3 not supported.'); + error.version = capture.version.charCodeAt(0); + throw error; + } + + if(asn1.derToOid(capture.contentType) !== pki.oids.data) { + var error = new Error('Only PKCS#12 PFX in password integrity mode supported.'); + error.oid = asn1.derToOid(capture.contentType); + throw error; + } + + var data = capture.content.value[0]; + if(data.tagClass !== asn1.Class.UNIVERSAL || + data.type !== asn1.Type.OCTETSTRING) { + throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.'); + } + data = _decodePkcs7Data(data); + + // check for MAC + if(capture.mac) { + var md = null; + var macKeyBytes = 0; + var macAlgorithm = asn1.derToOid(capture.macAlgorithm); + switch(macAlgorithm) { + case pki.oids.sha1: + md = forge.md.sha1.create(); + macKeyBytes = 20; + break; + case pki.oids.sha256: + md = forge.md.sha256.create(); + macKeyBytes = 32; + break; + case pki.oids.sha384: + md = forge.md.sha384.create(); + macKeyBytes = 48; + break; + case pki.oids.sha512: + md = forge.md.sha512.create(); + macKeyBytes = 64; + break; + case pki.oids.md5: + md = forge.md.md5.create(); + macKeyBytes = 16; + break; + } + if(md === null) { + throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm); + } + + // verify MAC (iterations default to 1) + var macSalt = new forge.util.ByteBuffer(capture.macSalt); + var macIterations = (('macIterations' in capture) ? + parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1); + var macKey = p12.generateKey( + password, macSalt, 3, macIterations, macKeyBytes, md); + var mac = forge.hmac.create(); + mac.start(md, macKey); + mac.update(data.value); + var macValue = mac.getMac(); + if(macValue.getBytes() !== capture.macDigest) { + throw new Error('PKCS#12 MAC could not be verified. Invalid password?'); + } + } + + _decodeAuthenticatedSafe(pfx, data.value, strict, password); + return pfx; +}; + +/** + * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING, + * but it is sometimes an OCTET STRING that is composed/constructed of chunks, + * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This + * function transforms this corner-case into the usual simple, + * non-composed/constructed OCTET STRING. + * + * This function may be moved to ASN.1 at some point to better deal with + * more BER-encoding issues, should they arise. + * + * @param data the ASN.1 Data object to transform. + */ +function _decodePkcs7Data(data) { + // handle special case of "chunked" data content: an octet string composed + // of other octet strings + if(data.composed || data.constructed) { + var value = forge.util.createBuffer(); + for(var i = 0; i < data.value.length; ++i) { + value.putBytes(data.value[i].value); + } + data.composed = data.constructed = false; + data.value = value.getBytes(); + } + return data; +} + +/** + * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object. + * + * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo. + * + * @param pfx The PKCS#12 PFX object to fill. + * @param {String} authSafe BER-encoded AuthenticatedSafe. + * @param strict true to use strict DER decoding, false not to. + * @param {String} password Password to decrypt with (optional). + */ +function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { + authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */ + + if(authSafe.tagClass !== asn1.Class.UNIVERSAL || + authSafe.type !== asn1.Type.SEQUENCE || + authSafe.constructed !== true) { + throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' + + 'SEQUENCE OF ContentInfo'); + } + + for(var i = 0; i < authSafe.value.length; i++) { + var contentInfo = authSafe.value[i]; + + // validate contentInfo and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read ContentInfo.'); + error.errors = errors; + throw error; + } + + var obj = { + encrypted: false + }; + var safeContents = null; + var data = capture.content.value[0]; + switch(asn1.derToOid(capture.contentType)) { + case pki.oids.data: + if(data.tagClass !== asn1.Class.UNIVERSAL || + data.type !== asn1.Type.OCTETSTRING) { + throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.'); + } + safeContents = _decodePkcs7Data(data).value; + break; + case pki.oids.encryptedData: + safeContents = _decryptSafeContents(data, password); + obj.encrypted = true; + break; + default: + var error = new Error('Unsupported PKCS#12 contentType.'); + error.contentType = asn1.derToOid(capture.contentType); + throw error; + } + + obj.safeBags = _decodeSafeContents(safeContents, strict, password); + pfx.safeContents.push(obj); + } +} + +/** + * Decrypt PKCS#7 EncryptedData structure. + * + * @param data ASN.1 encoded EncryptedContentInfo object. + * @param password The user-provided password. + * + * @return The decrypted SafeContents (ASN.1 object). + */ +function _decryptSafeContents(data, password) { + var capture = {}; + var errors = []; + if(!asn1.validate( + data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) { + var error = new Error('Cannot read EncryptedContentInfo.'); + error.errors = errors; + throw error; + } + + var oid = asn1.derToOid(capture.contentType); + if(oid !== pki.oids.data) { + var error = new Error( + 'PKCS#12 EncryptedContentInfo ContentType is not Data.'); + error.oid = oid; + throw error; + } + + // get cipher + oid = asn1.derToOid(capture.encAlgorithm); + var cipher = pki.pbe.getCipher(oid, capture.encParameter, password); + + // get encrypted data + var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); + var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); + + cipher.update(encrypted); + if(!cipher.finish()) { + throw new Error('Failed to decrypt PKCS#12 SafeContents.'); + } + + return cipher.output.getBytes(); +} + +/** + * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects. + * + * The safeContents is a BER-encoded SEQUENCE OF SafeBag. + * + * @param {String} safeContents BER-encoded safeContents. + * @param strict true to use strict DER decoding, false not to. + * @param {String} password Password to decrypt with (optional). + * + * @return {Array} Array of Bag objects. + */ +function _decodeSafeContents(safeContents, strict, password) { + // if strict and no safe contents, return empty safes + if(!strict && safeContents.length === 0) { + return []; + } + + // actually it's BER-encoded + safeContents = asn1.fromDer(safeContents, strict); + + if(safeContents.tagClass !== asn1.Class.UNIVERSAL || + safeContents.type !== asn1.Type.SEQUENCE || + safeContents.constructed !== true) { + throw new Error( + 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.'); + } + + var res = []; + for(var i = 0; i < safeContents.value.length; i++) { + var safeBag = safeContents.value[i]; + + // validate SafeBag and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) { + var error = new Error('Cannot read SafeBag.'); + error.errors = errors; + throw error; + } + + /* Create bag object and push to result array. */ + var bag = { + type: asn1.derToOid(capture.bagId), + attributes: _decodeBagAttributes(capture.bagAttributes) + }; + res.push(bag); + + var validator, decoder; + var bagAsn1 = capture.bagValue.value[0]; + switch(bag.type) { + case pki.oids.pkcs8ShroudedKeyBag: + /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt. + Afterwards we can handle it like a keyBag, + which is a PrivateKeyInfo. */ + bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password); + if(bagAsn1 === null) { + throw new Error( + 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?'); + } + + /* fall through */ + case pki.oids.keyBag: + /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our + PKI module, hence we don't have to do validation/capturing here, + just pass what we already got. */ + try { + bag.key = pki.privateKeyFromAsn1(bagAsn1); + } catch(e) { + // ignore unknown key type, pass asn1 value + bag.key = null; + bag.asn1 = bagAsn1; + } + continue; /* Nothing more to do. */ + + case pki.oids.certBag: + /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates. + Therefore put the SafeBag content through another validator to + capture the fields. Afterwards check & store the results. */ + validator = certBagValidator; + decoder = function() { + if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) { + var error = new Error( + 'Unsupported certificate type, only X.509 supported.'); + error.oid = asn1.derToOid(capture.certId); + throw error; + } + + // true=produce cert hash + var certAsn1 = asn1.fromDer(capture.cert, strict); + try { + bag.cert = pki.certificateFromAsn1(certAsn1, true); + } catch(e) { + // ignore unknown cert type, pass asn1 value + bag.cert = null; + bag.asn1 = certAsn1; + } + }; + break; + + default: + var error = new Error('Unsupported PKCS#12 SafeBag type.'); + error.oid = bag.type; + throw error; + } + + /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */ + if(validator !== undefined && + !asn1.validate(bagAsn1, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 ' + validator.name); + error.errors = errors; + throw error; + } + + /* Call decoder function from above to store the results. */ + decoder(); + } + + return res; +} + +/** + * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object. + * + * @param attributes SET OF PKCS12Attribute (ASN.1 object). + * + * @return the decoded attributes. + */ +function _decodeBagAttributes(attributes) { + var decodedAttrs = {}; + + if(attributes !== undefined) { + for(var i = 0; i < attributes.length; ++i) { + var capture = {}; + var errors = []; + if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 BagAttribute.'); + error.errors = errors; + throw error; + } + + var oid = asn1.derToOid(capture.oid); + if(pki.oids[oid] === undefined) { + // unsupported attribute type, ignore. + continue; + } + + decodedAttrs[pki.oids[oid]] = []; + for(var j = 0; j < capture.values.length; ++j) { + decodedAttrs[pki.oids[oid]].push(capture.values[j].value); + } + } + } + + return decodedAttrs; +} + +/** + * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a + * password is provided then the private key will be encrypted. + * + * An entire certificate chain may also be included. To do this, pass + * an array for the "cert" parameter where the first certificate is + * the one that is paired with the private key and each subsequent one + * verifies the previous one. The certificates may be in PEM format or + * have been already parsed by Forge. + * + * @todo implement password-based-encryption for the whole package + * + * @param key the private key. + * @param cert the certificate (may be an array of certificates in order + * to specify a certificate chain). + * @param password the password to use, null for none. + * @param options: + * algorithm the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. + * count the iteration count to use. + * saltSize the salt size to use. + * useMac true to include a MAC, false not to, defaults to true. + * localKeyId the local key ID to use, in hex. + * friendlyName the friendly name to use. + * generateLocalKeyId true to generate a random local key ID, + * false not to, defaults to true. + * + * @return the PKCS#12 PFX ASN.1 object. + */ +p12.toPkcs12Asn1 = function(key, cert, password, options) { + // set default options + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || options.encAlgorithm || 'aes128'; + if(!('useMac' in options)) { + options.useMac = true; + } + if(!('localKeyId' in options)) { + options.localKeyId = null; + } + if(!('generateLocalKeyId' in options)) { + options.generateLocalKeyId = true; + } + + var localKeyId = options.localKeyId; + var bagAttrs; + if(localKeyId !== null) { + localKeyId = forge.util.hexToBytes(localKeyId); + } else if(options.generateLocalKeyId) { + // use SHA-1 of paired cert, if available + if(cert) { + var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; + if(typeof pairedCert === 'string') { + pairedCert = pki.certificateFromPem(pairedCert); + } + var sha1 = forge.md.sha1.create(); + sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()); + localKeyId = sha1.digest().getBytes(); + } else { + // FIXME: consider using SHA-1 of public key (which can be generated + // from private key components), see: cert.generateSubjectKeyIdentifier + // generate random bytes + localKeyId = forge.random.getBytes(20); + } + } + + var attrs = []; + if(localKeyId !== null) { + attrs.push( + // localKeyID + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.localKeyId).getBytes()), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + localKeyId) + ]) + ])); + } + if('friendlyName' in options) { + attrs.push( + // friendlyName + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.friendlyName).getBytes()), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false, + options.friendlyName) + ]) + ])); + } + + if(attrs.length > 0) { + bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); + } + + // collect contents for AuthenticatedSafe + var contents = []; + + // create safe bag(s) for certificate chain + var chain = []; + if(cert !== null) { + if(forge.util.isArray(cert)) { + chain = cert; + } else { + chain = [cert]; + } + } + + var certSafeBags = []; + for(var i = 0; i < chain.length; ++i) { + // convert cert from PEM as necessary + cert = chain[i]; + if(typeof cert === 'string') { + cert = pki.certificateFromPem(cert); + } + + // SafeBag + var certBagAttrs = (i === 0) ? bagAttrs : undefined; + var certAsn1 = pki.certificateToAsn1(cert); + var certSafeBag = + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.certBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // CertBag + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // certId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.x509Certificate).getBytes()), + // certValue (x509Certificate) + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(certAsn1).getBytes()) + ])])]), + // bagAttributes (OPTIONAL) + certBagAttrs + ]); + certSafeBags.push(certSafeBag); + } + + if(certSafeBags.length > 0) { + // SafeContents + var certSafeContents = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags); + + // ContentInfo + var certCI = + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(certSafeContents).getBytes()) + ]) + ]); + contents.push(certCI); + } + + // create safe contents for private key + var keyBag = null; + if(key !== null) { + // SafeBag + var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key)); + if(password === null) { + // no encryption + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.keyBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // PrivateKeyInfo + pkAsn1 + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } else { + // encrypted PrivateKeyInfo + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // EncryptedPrivateKeyInfo + pki.encryptPrivateKeyInfo(pkAsn1, password, options) + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } + + // SafeContents + var keySafeContents = + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); + + // ContentInfo + var keyCI = + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(keySafeContents).getBytes()) + ]) + ]); + contents.push(keyCI); + } + + // create AuthenticatedSafe by stringing together the contents + var safe = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents); + + var macData; + if(options.useMac) { + // MacData + var sha1 = forge.md.sha1.create(); + var macSalt = new forge.util.ByteBuffer( + forge.random.getBytes(options.saltSize)); + var count = options.count; + // 160-bit key + var key = p12.generateKey(password, macSalt, 3, count, 20); + var mac = forge.hmac.create(); + mac.start(sha1, key); + mac.update(asn1.toDer(safe).getBytes()); + var macValue = mac.getMac(); + macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // mac DigestInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm = SHA-1 + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.sha1).getBytes()), + // parameters = Null + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // digest + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, + false, macValue.getBytes()) + ]), + // macSalt OCTET STRING + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()), + // iterations INTEGER (XXX: Only support count < 65536) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(count).getBytes() + ) + ]); + } + + // PFX + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (3) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(3).getBytes()), + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(safe).getBytes()) + ]) + ]), + macData + ]); +}; + +/** + * Derives a PKCS#12 key. + * + * @param password the password to derive the key material from, null or + * undefined for none. + * @param salt the salt, as a ByteBuffer, to use. + * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). + * @param iter the iteration count. + * @param n the number of bytes to derive from the password. + * @param md the message digest to use, defaults to SHA-1. + * + * @return a ByteBuffer with the bytes derived from the password. + */ +p12.generateKey = forge.pbe.generatePkcs12Key; + + +/***/ }), + +/***/ 4829: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of PKCS#7 v1.5. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2012-2015 Digital Bazaar, Inc. + * + * Currently this implementation only supports ContentType of EnvelopedData, + * EncryptedData, or SignedData at the root level. The top level elements may + * contain only a ContentInfo of ContentType Data, i.e. plain data. Further + * nesting is not (yet) supported. + * + * The Forge validators for PKCS #7's ASN.1 structures are available from + * a separate file pkcs7asn1.js, since those are referenced from other + * PKCS standards like PKCS #12. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7994); +__nccwpck_require__(9549); +__nccwpck_require__(7157); +__nccwpck_require__(1925); +__nccwpck_require__(154); +__nccwpck_require__(266); +__nccwpck_require__(7821); +__nccwpck_require__(8339); +__nccwpck_require__(8180); + +// shortcut for ASN.1 API +var asn1 = forge.asn1; + +// shortcut for PKCS#7 API +var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {}; + +/** + * Converts a PKCS#7 message from PEM format. + * + * @param pem the PEM-formatted PKCS#7 message. + * + * @return the PKCS#7 message. + */ +p7.messageFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'PKCS7') { + var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' + + 'header type is not "PKCS#7".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return p7.messageFromAsn1(obj); +}; + +/** + * Converts a PKCS#7 message to PEM format. + * + * @param msg The PKCS#7 message object + * @param maxline The maximum characters per line, defaults to 64. + * + * @return The PEM-formatted PKCS#7 message. + */ +p7.messageToPem = function(msg, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var pemObj = { + type: 'PKCS7', + body: asn1.toDer(msg.toAsn1()).getBytes() + }; + return forge.pem.encode(pemObj, {maxline: maxline}); +}; + +/** + * Converts a PKCS#7 message from an ASN.1 object. + * + * @param obj the ASN.1 representation of a ContentInfo. + * + * @return the PKCS#7 message. + */ +p7.messageFromAsn1 = function(obj) { + // validate root level ContentInfo and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + + 'ASN.1 object is not an PKCS#7 ContentInfo.'); + error.errors = errors; + throw error; + } + + var contentType = asn1.derToOid(capture.contentType); + var msg; + + switch(contentType) { + case forge.pki.oids.envelopedData: + msg = p7.createEnvelopedData(); + break; + + case forge.pki.oids.encryptedData: + msg = p7.createEncryptedData(); + break; + + case forge.pki.oids.signedData: + msg = p7.createSignedData(); + break; + + default: + throw new Error('Cannot read PKCS#7 message. ContentType with OID ' + + contentType + ' is not (yet) supported.'); + } + + msg.fromAsn1(capture.content.value[0]); + return msg; +}; + +p7.createSignedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.signedData, + version: 1, + certificates: [], + crls: [], + // TODO: add json-formatted signer stuff here? + signers: [], + // populated during sign() + digestAlgorithmIdentifiers: [], + contentInfo: null, + signerInfos: [], + + fromAsn1: function(obj) { + // validate SignedData content block and capture data. + _fromAsn1(msg, obj, p7.asn1.signedDataValidator); + msg.certificates = []; + msg.crls = []; + msg.digestAlgorithmIdentifiers = []; + msg.contentInfo = null; + msg.signerInfos = []; + + if(msg.rawCapture.certificates) { + var certs = msg.rawCapture.certificates.value; + for(var i = 0; i < certs.length; ++i) { + msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); + } + } + + // TODO: parse crls + }, + + toAsn1: function() { + // degenerate case with no content + if(!msg.contentInfo) { + msg.sign(); + } + + var certs = []; + for(var i = 0; i < msg.certificates.length; ++i) { + certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); + } + + var crls = []; + // TODO: implement CRLs + + // [0] SignedData + var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(msg.version).getBytes()), + // DigestAlgorithmIdentifiers + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SET, true, + msg.digestAlgorithmIdentifiers), + // ContentInfo + msg.contentInfo + ]) + ]); + if(certs.length > 0) { + // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)); + } + if(crls.length > 0) { + // [1] IMPLICIT CertificateRevocationLists OPTIONAL + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)); + } + // SignerInfos + signedData.value[0].value.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, + msg.signerInfos)); + + // ContentInfo + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(msg.type).getBytes()), + // [0] SignedData + signedData + ]); + }, + + /** + * Add (another) entity to list of signers. + * + * Note: If authenticatedAttributes are provided, then, per RFC 2315, + * they must include at least two attributes: content type and + * message digest. The message digest attribute value will be + * auto-calculated during signing and will be ignored if provided. + * + * Here's an example of providing these two attributes: + * + * forge.pkcs7.createSignedData(); + * p7.addSigner({ + * issuer: cert.issuer.attributes, + * serialNumber: cert.serialNumber, + * key: privateKey, + * digestAlgorithm: forge.pki.oids.sha1, + * authenticatedAttributes: [{ + * type: forge.pki.oids.contentType, + * value: forge.pki.oids.data + * }, { + * type: forge.pki.oids.messageDigest + * }] + * }); + * + * TODO: Support [subjectKeyIdentifier] as signer's ID. + * + * @param signer the signer information: + * key the signer's private key. + * [certificate] a certificate containing the public key + * associated with the signer's private key; use this option as + * an alternative to specifying signer.issuer and + * signer.serialNumber. + * [issuer] the issuer attributes (eg: cert.issuer.attributes). + * [serialNumber] the signer's certificate's serial number in + * hexadecimal (eg: cert.serialNumber). + * [digestAlgorithm] the message digest OID, as a string, to use + * (eg: forge.pki.oids.sha1). + * [authenticatedAttributes] an optional array of attributes + * to also sign along with the content. + */ + addSigner: function(signer) { + var issuer = signer.issuer; + var serialNumber = signer.serialNumber; + if(signer.certificate) { + var cert = signer.certificate; + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + issuer = cert.issuer.attributes; + serialNumber = cert.serialNumber; + } + var key = signer.key; + if(!key) { + throw new Error( + 'Could not add PKCS#7 signer; no private key specified.'); + } + if(typeof key === 'string') { + key = forge.pki.privateKeyFromPem(key); + } + + // ensure OID known for digest algorithm + var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; + switch(digestAlgorithm) { + case forge.pki.oids.sha1: + case forge.pki.oids.sha256: + case forge.pki.oids.sha384: + case forge.pki.oids.sha512: + case forge.pki.oids.md5: + break; + default: + throw new Error( + 'Could not add PKCS#7 signer; unknown message digest algorithm: ' + + digestAlgorithm); + } + + // if authenticatedAttributes is present, then the attributes + // must contain at least PKCS #9 content-type and message-digest + var authenticatedAttributes = signer.authenticatedAttributes || []; + if(authenticatedAttributes.length > 0) { + var contentType = false; + var messageDigest = false; + for(var i = 0; i < authenticatedAttributes.length; ++i) { + var attr = authenticatedAttributes[i]; + if(!contentType && attr.type === forge.pki.oids.contentType) { + contentType = true; + if(messageDigest) { + break; + } + continue; + } + if(!messageDigest && attr.type === forge.pki.oids.messageDigest) { + messageDigest = true; + if(contentType) { + break; + } + continue; + } + } + + if(!contentType || !messageDigest) { + throw new Error('Invalid signer.authenticatedAttributes. If ' + + 'signer.authenticatedAttributes is specified, then it must ' + + 'contain at least two attributes, PKCS #9 content-type and ' + + 'PKCS #9 message-digest.'); + } + } + + msg.signers.push({ + key: key, + version: 1, + issuer: issuer, + serialNumber: serialNumber, + digestAlgorithm: digestAlgorithm, + signatureAlgorithm: forge.pki.oids.rsaEncryption, + signature: null, + authenticatedAttributes: authenticatedAttributes, + unauthenticatedAttributes: [] + }); + }, + + /** + * Signs the content. + * @param options Options to apply when signing: + * [detached] boolean. If signing should be done in detached mode. Defaults to false. + */ + sign: function(options) { + options = options || {}; + // auto-generate content info + if(typeof msg.content !== 'object' || msg.contentInfo === null) { + // use Data ContentInfo + msg.contentInfo = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(forge.pki.oids.data).getBytes()) + ]); + + // add actual content, if present + if('content' in msg) { + var content; + if(msg.content instanceof forge.util.ByteBuffer) { + content = msg.content.bytes(); + } else if(typeof msg.content === 'string') { + content = forge.util.encodeUtf8(msg.content); + } + + if (options.detached) { + msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); + } else { + msg.contentInfo.value.push( + // [0] EXPLICIT content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + content) + ])); + } + } + } + + // no signers, return early (degenerate case for certificate container) + if(msg.signers.length === 0) { + return; + } + + // generate digest algorithm identifiers + var mds = addDigestAlgorithmIds(); + + // generate signerInfos + addSignerInfos(mds); + }, + + verify: function() { + throw new Error('PKCS#7 signature verification not yet implemented.'); + }, + + /** + * Add a certificate. + * + * @param cert the certificate to add. + */ + addCertificate: function(cert) { + // convert from PEM + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + msg.certificates.push(cert); + }, + + /** + * Add a certificate revokation list. + * + * @param crl the certificate revokation list to add. + */ + addCertificateRevokationList: function(crl) { + throw new Error('PKCS#7 CRL support not yet implemented.'); + } + }; + return msg; + + function addDigestAlgorithmIds() { + var mds = {}; + + for(var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + var oid = signer.digestAlgorithm; + if(!(oid in mds)) { + // content digest + mds[oid] = forge.md[forge.pki.oids[oid]].create(); + } + if(signer.authenticatedAttributes.length === 0) { + // no custom attributes to digest; use content message digest + signer.md = mds[oid]; + } else { + // custom attributes to be digested; use own message digest + // TODO: optimize to just copy message digest state if that + // feature is ever supported with message digests + signer.md = forge.md[forge.pki.oids[oid]].create(); + } + } + + // add unique digest algorithm identifiers + msg.digestAlgorithmIdentifiers = []; + for(var oid in mds) { + msg.digestAlgorithmIdentifiers.push( + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oid).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + } + + return mds; + } + + function addSignerInfos(mds) { + var content; + + if (msg.detachedContent) { + // Signature has been made in detached mode. + content = msg.detachedContent; + } else { + // Note: ContentInfo is a SEQUENCE with 2 values, second value is + // the content field and is optional for a ContentInfo but required here + // since signers are present + // get ContentInfo content + content = msg.contentInfo.value[1]; + // skip [0] EXPLICIT content wrapper + content = content.value[0]; + } + + if(!content) { + throw new Error( + 'Could not sign PKCS#7 message; there is no content to sign.'); + } + + // get ContentInfo content type + var contentType = asn1.derToOid(msg.contentInfo.value[0].value); + + // serialize content + var bytes = asn1.toDer(content); + + // skip identifier and length per RFC 2315 9.3 + // skip identifier (1 byte) + bytes.getByte(); + // read and discard length bytes + asn1.getBerValueLength(bytes); + bytes = bytes.getBytes(); + + // digest content DER value bytes + for(var oid in mds) { + mds[oid].start().update(bytes); + } + + // sign content + var signingTime = new Date(); + for(var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + + if(signer.authenticatedAttributes.length === 0) { + // if ContentInfo content type is not "Data", then + // authenticatedAttributes must be present per RFC 2315 + if(contentType !== forge.pki.oids.data) { + throw new Error( + 'Invalid signer; authenticatedAttributes must be present ' + + 'when the ContentInfo content type is not PKCS#7 Data.'); + } + } else { + // process authenticated attributes + // [0] IMPLICIT + signer.authenticatedAttributesAsn1 = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + + // per RFC 2315, attributes are to be digested using a SET container + // not the above [0] IMPLICIT container + var attrsAsn1 = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SET, true, []); + + for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { + var attr = signer.authenticatedAttributes[ai]; + if(attr.type === forge.pki.oids.messageDigest) { + // use content message digest as value + attr.value = mds[signer.digestAlgorithm].digest(); + } else if(attr.type === forge.pki.oids.signingTime) { + // auto-populate signing time if not already set + if(!attr.value) { + attr.value = signingTime; + } + } + + // convert to ASN.1 and push onto Attributes SET (for signing) and + // onto authenticatedAttributesAsn1 to complete SignedData ASN.1 + // TODO: optimize away duplication + attrsAsn1.value.push(_attributeToAsn1(attr)); + signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); + } + + // DER-serialize and digest SET OF attributes only + bytes = asn1.toDer(attrsAsn1).getBytes(); + signer.md.start().update(bytes); + } + + // sign digest + signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5'); + } + + // add signer info + msg.signerInfos = _signersToAsn1(msg.signers); + } +}; + +/** + * Creates an empty PKCS#7 message of type EncryptedData. + * + * @return the message. + */ +p7.createEncryptedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.encryptedData, + version: 0, + encryptedContent: { + algorithm: forge.pki.oids['aes256-CBC'] + }, + + /** + * Reads an EncryptedData content block (in ASN.1 format) + * + * @param obj The ASN.1 representation of the EncryptedData content block + */ + fromAsn1: function(obj) { + // Validate EncryptedData content block and capture data. + _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); + }, + + /** + * Decrypt encrypted content + * + * @param key The (symmetric) key as a byte buffer + */ + decrypt: function(key) { + if(key !== undefined) { + msg.encryptedContent.key = key; + } + _decryptContent(msg); + } + }; + return msg; +}; + +/** + * Creates an empty PKCS#7 message of type EnvelopedData. + * + * @return the message. + */ +p7.createEnvelopedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.envelopedData, + version: 0, + recipients: [], + encryptedContent: { + algorithm: forge.pki.oids['aes256-CBC'] + }, + + /** + * Reads an EnvelopedData content block (in ASN.1 format) + * + * @param obj the ASN.1 representation of the EnvelopedData content block. + */ + fromAsn1: function(obj) { + // validate EnvelopedData content block and capture data + var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); + msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); + }, + + toAsn1: function() { + // ContentInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(msg.type).getBytes()), + // [0] EnvelopedData + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(msg.version).getBytes()), + // RecipientInfos + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, + _recipientsToAsn1(msg.recipients)), + // EncryptedContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, + _encryptedContentToAsn1(msg.encryptedContent)) + ]) + ]) + ]); + }, + + /** + * Find recipient by X.509 certificate's issuer. + * + * @param cert the certificate with the issuer to look for. + * + * @return the recipient object. + */ + findRecipient: function(cert) { + var sAttr = cert.issuer.attributes; + + for(var i = 0; i < msg.recipients.length; ++i) { + var r = msg.recipients[i]; + var rAttr = r.issuer; + + if(r.serialNumber !== cert.serialNumber) { + continue; + } + + if(rAttr.length !== sAttr.length) { + continue; + } + + var match = true; + for(var j = 0; j < sAttr.length; ++j) { + if(rAttr[j].type !== sAttr[j].type || + rAttr[j].value !== sAttr[j].value) { + match = false; + break; + } + } + + if(match) { + return r; + } + } + + return null; + }, + + /** + * Decrypt enveloped content + * + * @param recipient The recipient object related to the private key + * @param privKey The (RSA) private key object + */ + decrypt: function(recipient, privKey) { + if(msg.encryptedContent.key === undefined && recipient !== undefined && + privKey !== undefined) { + switch(recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + case forge.pki.oids.desCBC: + var key = privKey.decrypt(recipient.encryptedContent.content); + msg.encryptedContent.key = forge.util.createBuffer(key); + break; + + default: + throw new Error('Unsupported asymmetric cipher, ' + + 'OID ' + recipient.encryptedContent.algorithm); + } + } + + _decryptContent(msg); + }, + + /** + * Add (another) entity to list of recipients. + * + * @param cert The certificate of the entity to add. + */ + addRecipient: function(cert) { + msg.recipients.push({ + version: 0, + issuer: cert.issuer.attributes, + serialNumber: cert.serialNumber, + encryptedContent: { + // We simply assume rsaEncryption here, since forge.pki only + // supports RSA so far. If the PKI module supports other + // ciphers one day, we need to modify this one as well. + algorithm: forge.pki.oids.rsaEncryption, + key: cert.publicKey + } + }); + }, + + /** + * Encrypt enveloped content. + * + * This function supports two optional arguments, cipher and key, which + * can be used to influence symmetric encryption. Unless cipher is + * provided, the cipher specified in encryptedContent.algorithm is used + * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key + * is (re-)used. If that one's not set, a random key will be generated + * automatically. + * + * @param [key] The key to be used for symmetric encryption. + * @param [cipher] The OID of the symmetric cipher to use. + */ + encrypt: function(key, cipher) { + // Part 1: Symmetric encryption + if(msg.encryptedContent.content === undefined) { + cipher = cipher || msg.encryptedContent.algorithm; + key = key || msg.encryptedContent.key; + + var keyLen, ivLen, ciphFn; + switch(cipher) { + case forge.pki.oids['aes128-CBC']: + keyLen = 16; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['aes192-CBC']: + keyLen = 24; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['aes256-CBC']: + keyLen = 32; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['des-EDE3-CBC']: + keyLen = 24; + ivLen = 8; + ciphFn = forge.des.createEncryptionCipher; + break; + + default: + throw new Error('Unsupported symmetric cipher, OID ' + cipher); + } + + if(key === undefined) { + key = forge.util.createBuffer(forge.random.getBytes(keyLen)); + } else if(key.length() != keyLen) { + throw new Error('Symmetric key has wrong length; ' + + 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); + } + + // Keep a copy of the key & IV in the object, so the caller can + // use it for whatever reason. + msg.encryptedContent.algorithm = cipher; + msg.encryptedContent.key = key; + msg.encryptedContent.parameter = forge.util.createBuffer( + forge.random.getBytes(ivLen)); + + var ciph = ciphFn(key); + ciph.start(msg.encryptedContent.parameter.copy()); + ciph.update(msg.content); + + // The finish function does PKCS#7 padding by default, therefore + // no action required by us. + if(!ciph.finish()) { + throw new Error('Symmetric encryption failed.'); + } + + msg.encryptedContent.content = ciph.output; + } + + // Part 2: asymmetric encryption for each recipient + for(var i = 0; i < msg.recipients.length; ++i) { + var recipient = msg.recipients[i]; + + // Nothing to do, encryption already done. + if(recipient.encryptedContent.content !== undefined) { + continue; + } + + switch(recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + recipient.encryptedContent.content = + recipient.encryptedContent.key.encrypt( + msg.encryptedContent.key.data); + break; + + default: + throw new Error('Unsupported asymmetric cipher, OID ' + + recipient.encryptedContent.algorithm); + } + } + } + }; + return msg; +}; + +/** + * Converts a single recipient from an ASN.1 object. + * + * @param obj the ASN.1 RecipientInfo. + * + * @return the recipient object. + */ +function _recipientFromAsn1(obj) { + // validate EnvelopedData content block and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + + 'ASN.1 object is not an PKCS#7 RecipientInfo.'); + error.errors = errors; + throw error; + } + + return { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + encryptedContent: { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: capture.encParameter ? capture.encParameter.value : undefined, + content: capture.encKey + } + }; +} + +/** + * Converts a single recipient object to an ASN.1 object. + * + * @param obj the recipient object. + * + * @return the ASN.1 RecipientInfo. + */ +function _recipientToAsn1(obj) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(obj.version).getBytes()), + // IssuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Name + forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), + // Serial + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(obj.serialNumber)) + ]), + // KeyEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), + // Parameter, force NULL, only RSA supported for now. + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // EncryptedKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + obj.encryptedContent.content) + ]); +} + +/** + * Map a set of RecipientInfo ASN.1 objects to recipient objects. + * + * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF). + * + * @return an array of recipient objects. + */ +function _recipientsFromAsn1(infos) { + var ret = []; + for(var i = 0; i < infos.length; ++i) { + ret.push(_recipientFromAsn1(infos[i])); + } + return ret; +} + +/** + * Map an array of recipient objects to ASN.1 RecipientInfo objects. + * + * @param recipients an array of recipientInfo objects. + * + * @return an array of ASN.1 RecipientInfos. + */ +function _recipientsToAsn1(recipients) { + var ret = []; + for(var i = 0; i < recipients.length; ++i) { + ret.push(_recipientToAsn1(recipients[i])); + } + return ret; +} + +/** + * Converts a single signer from an ASN.1 object. + * + * @param obj the ASN.1 representation of a SignerInfo. + * + * @return the signer object. + */ +function _signerFromAsn1(obj) { + // validate EnvelopedData content block and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 SignerInfo. ' + + 'ASN.1 object is not an PKCS#7 SignerInfo.'); + error.errors = errors; + throw error; + } + + var rval = { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + digestAlgorithm: asn1.derToOid(capture.digestAlgorithm), + signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm), + signature: capture.signature, + authenticatedAttributes: [], + unauthenticatedAttributes: [] + }; + + // TODO: convert attributes + var authenticatedAttributes = capture.authenticatedAttributes || []; + var unauthenticatedAttributes = capture.unauthenticatedAttributes || []; + + return rval; +} + +/** + * Converts a single signerInfo object to an ASN.1 object. + * + * @param obj the signerInfo object. + * + * @return the ASN.1 representation of a SignerInfo. + */ +function _signerToAsn1(obj) { + // SignerInfo + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(obj.version).getBytes()), + // issuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // name + forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), + // serial + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(obj.serialNumber)) + ]), + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.digestAlgorithm).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]); + + // authenticatedAttributes (OPTIONAL) + if(obj.authenticatedAttributesAsn1) { + // add ASN.1 previously generated during signing + rval.value.push(obj.authenticatedAttributesAsn1); + } + + // digestEncryptionAlgorithm + rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.signatureAlgorithm).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + + // encryptedDigest + rval.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); + + // unauthenticatedAttributes (OPTIONAL) + if(obj.unauthenticatedAttributes.length > 0) { + // [1] IMPLICIT + var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); + for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { + var attr = obj.unauthenticatedAttributes[i]; + attrsAsn1.values.push(_attributeToAsn1(attr)); + } + rval.value.push(attrsAsn1); + } + + return rval; +} + +/** + * Map a set of SignerInfo ASN.1 objects to an array of signer objects. + * + * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF). + * + * @return an array of signers objects. + */ +function _signersFromAsn1(signerInfoAsn1s) { + var ret = []; + for(var i = 0; i < signerInfoAsn1s.length; ++i) { + ret.push(_signerFromAsn1(signerInfoAsn1s[i])); + } + return ret; +} + +/** + * Map an array of signer objects to ASN.1 objects. + * + * @param signers an array of signer objects. + * + * @return an array of ASN.1 SignerInfos. + */ +function _signersToAsn1(signers) { + var ret = []; + for(var i = 0; i < signers.length; ++i) { + ret.push(_signerToAsn1(signers[i])); + } + return ret; +} + +/** + * Convert an attribute object to an ASN.1 Attribute. + * + * @param attr the attribute object. + * + * @return the ASN.1 Attribute. + */ +function _attributeToAsn1(attr) { + var value; + + // TODO: generalize to support more attributes + if(attr.type === forge.pki.oids.contentType) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.value).getBytes()); + } else if(attr.type === forge.pki.oids.messageDigest) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + attr.value.bytes()); + } else if(attr.type === forge.pki.oids.signingTime) { + /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049 + (inclusive) MUST be encoded as UTCTime. Any dates with year values + before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,] + UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST + include seconds (i.e., times are YYMMDDHHMMSSZ), even where the + number of seconds is zero. Midnight (GMT) must be represented as + "YYMMDD000000Z". */ + // TODO: make these module-level constants + var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); + var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + var date = attr.value; + if(typeof date === 'string') { + // try to parse date + var timestamp = Date.parse(date); + if(!isNaN(timestamp)) { + date = new Date(timestamp); + } else if(date.length === 13) { + // YYMMDDHHMMSSZ (13 chars for UTCTime) + date = asn1.utcTimeToDate(date); + } else { + // assume generalized time + date = asn1.generalizedTimeToDate(date); + } + } + + if(date >= jan_1_1950 && date < jan_1_2050) { + value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, + asn1.dateToUtcTime(date)); + } else { + value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, + asn1.dateToGeneralizedTime(date)); + } + } + + // TODO: expose as common API call + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + value + ]) + ]); +} + +/** + * Map messages encrypted content to ASN.1 objects. + * + * @param ec The encryptedContent object of the message. + * + * @return ASN.1 representation of the encryptedContent object (SEQUENCE). + */ +function _encryptedContentToAsn1(ec) { + return [ + // ContentType, always Data for the moment + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(forge.pki.oids.data).getBytes()), + // ContentEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(ec.algorithm).getBytes()), + // Parameters (IV) + !ec.parameter ? + undefined : + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + ec.parameter.getBytes()) + ]), + // [0] EncryptedContent + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + ec.content.getBytes()) + ]) + ]; +} + +/** + * Reads the "common part" of an PKCS#7 content block (in ASN.1 format) + * + * This function reads the "common part" of the PKCS#7 content blocks + * EncryptedData and EnvelopedData, i.e. version number and symmetrically + * encrypted content block. + * + * The result of the ASN.1 validate and capture process is returned + * to allow the caller to extract further data, e.g. the list of recipients + * in case of a EnvelopedData object. + * + * @param msg the PKCS#7 object to read the data to. + * @param obj the ASN.1 representation of the content block. + * @param validator the ASN.1 structure validator object to use. + * + * @return the value map captured by validator object. + */ +function _fromAsn1(msg, obj, validator) { + var capture = {}; + var errors = []; + if(!asn1.validate(obj, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + + 'ASN.1 object is not a supported PKCS#7 message.'); + error.errors = error; + throw error; + } + + // Check contentType, so far we only support (raw) Data. + var contentType = asn1.derToOid(capture.contentType); + if(contentType !== forge.pki.oids.data) { + throw new Error('Unsupported PKCS#7 message. ' + + 'Only wrapped ContentType Data supported.'); + } + + if(capture.encryptedContent) { + var content = ''; + if(forge.util.isArray(capture.encryptedContent)) { + for(var i = 0; i < capture.encryptedContent.length; ++i) { + if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting encrypted ' + + 'content constructed of only OCTET STRING objects.'); + } + content += capture.encryptedContent[i].value; + } + } else { + content = capture.encryptedContent; + } + msg.encryptedContent = { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: forge.util.createBuffer(capture.encParameter.value), + content: forge.util.createBuffer(content) + }; + } + + if(capture.content) { + var content = ''; + if(forge.util.isArray(capture.content)) { + for(var i = 0; i < capture.content.length; ++i) { + if(capture.content[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting ' + + 'content constructed of only OCTET STRING objects.'); + } + content += capture.content[i].value; + } + } else { + content = capture.content; + } + msg.content = forge.util.createBuffer(content); + } + + msg.version = capture.version.charCodeAt(0); + msg.rawCapture = capture; + + return capture; +} + +/** + * Decrypt the symmetrically encrypted content block of the PKCS#7 message. + * + * Decryption is skipped in case the PKCS#7 message object already has a + * (decrypted) content attribute. The algorithm, key and cipher parameters + * (probably the iv) are taken from the encryptedContent attribute of the + * message object. + * + * @param The PKCS#7 message object. + */ +function _decryptContent(msg) { + if(msg.encryptedContent.key === undefined) { + throw new Error('Symmetric key not available.'); + } + + if(msg.content === undefined) { + var ciph; + + switch(msg.encryptedContent.algorithm) { + case forge.pki.oids['aes128-CBC']: + case forge.pki.oids['aes192-CBC']: + case forge.pki.oids['aes256-CBC']: + ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); + break; + + case forge.pki.oids['desCBC']: + case forge.pki.oids['des-EDE3-CBC']: + ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); + break; + + default: + throw new Error('Unsupported symmetric cipher, OID ' + + msg.encryptedContent.algorithm); + } + ciph.start(msg.encryptedContent.parameter); + ciph.update(msg.encryptedContent.content); + + if(!ciph.finish()) { + throw new Error('Symmetric decryption failed.'); + } + + msg.content = ciph.output; + } +} + + +/***/ }), + +/***/ 266: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of ASN.1 validators for PKCS#7 v1.5. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2012-2015 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * The ASN.1 representation of PKCS#7 is as follows + * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt): + * + * A PKCS#7 message consists of a ContentInfo on root level, which may + * contain any number of further ContentInfo nested into it. + * + * ContentInfo ::= SEQUENCE { + * contentType ContentType, + * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL + * } + * + * ContentType ::= OBJECT IDENTIFIER + * + * EnvelopedData ::= SEQUENCE { + * version Version, + * recipientInfos RecipientInfos, + * encryptedContentInfo EncryptedContentInfo + * } + * + * EncryptedData ::= SEQUENCE { + * version Version, + * encryptedContentInfo EncryptedContentInfo + * } + * + * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2) + * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 } + * + * SignedData ::= SEQUENCE { + * version INTEGER, + * digestAlgorithms DigestAlgorithmIdentifiers, + * contentInfo ContentInfo, + * certificates [0] IMPLICIT Certificates OPTIONAL, + * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, + * signerInfos SignerInfos + * } + * + * SignerInfos ::= SET OF SignerInfo + * + * SignerInfo ::= SEQUENCE { + * version Version, + * issuerAndSerialNumber IssuerAndSerialNumber, + * digestAlgorithm DigestAlgorithmIdentifier, + * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, + * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, + * encryptedDigest EncryptedDigest, + * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL + * } + * + * EncryptedDigest ::= OCTET STRING + * + * Attributes ::= SET OF Attribute + * + * Attribute ::= SEQUENCE { + * attrType OBJECT IDENTIFIER, + * attrValues SET OF AttributeValue + * } + * + * AttributeValue ::= ANY + * + * Version ::= INTEGER + * + * RecipientInfos ::= SET OF RecipientInfo + * + * EncryptedContentInfo ::= SEQUENCE { + * contentType ContentType, + * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, + * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL + * } + * + * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of AES and DES3, there is only one, + * the IV. + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * EncryptedContent ::= OCTET STRING + * + * RecipientInfo ::= SEQUENCE { + * version Version, + * issuerAndSerialNumber IssuerAndSerialNumber, + * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier, + * encryptedKey EncryptedKey + * } + * + * IssuerAndSerialNumber ::= SEQUENCE { + * issuer Name, + * serialNumber CertificateSerialNumber + * } + * + * CertificateSerialNumber ::= INTEGER + * + * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * EncryptedKey ::= OCTET STRING + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(9549); +__nccwpck_require__(8339); + +// shortcut for ASN.1 API +var asn1 = forge.asn1; + +// shortcut for PKCS#7 API +var p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; +forge.pkcs7 = forge.pkcs7 || {}; +forge.pkcs7.asn1 = p7v; + +var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'ContentInfo.ContentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'ContentInfo.content', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + captureAsn1: 'content' + }] +}; +p7v.contentInfoValidator = contentInfoValidator; + +var encryptedContentInfoValidator = { + name: 'EncryptedContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedContentInfo.contentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: 'encParameter' + }] + }, { + name: 'EncryptedContentInfo.encryptedContent', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + /* The PKCS#7 structure output by OpenSSL somewhat differs from what + * other implementations do generate. + * + * OpenSSL generates a structure like this: + * SEQUENCE { + * ... + * [0] + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * + * Whereas other implementations (and this PKCS#7 module) generate: + * SEQUENCE { + * ... + * [0] { + * OCTET STRING + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * } + * + * In order to support both, we just capture the context specific + * field here. The OCTET STRING bit is removed below. + */ + capture: 'encryptedContent', + captureAsn1: 'encryptedContentAsn1' + }] +}; + +p7v.envelopedDataValidator = { + name: 'EnvelopedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EnvelopedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'EnvelopedData.RecipientInfos', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: 'recipientInfos' + }].concat(encryptedContentInfoValidator) +}; + +p7v.encryptedDataValidator = { + name: 'EncryptedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }].concat(encryptedContentInfoValidator) +}; + +var signerValidator = { + name: 'SignerInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false + }, { + name: 'SignerInfo.issuerAndSerialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.issuerAndSerialNumber.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, { + name: 'SignerInfo.issuerAndSerialNumber.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'serial' + }] + }, { + name: 'SignerInfo.digestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.digestAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'digestAlgorithm' + }, { + name: 'SignerInfo.digestAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'digestParameter', + optional: true + }] + }, { + name: 'SignerInfo.authenticatedAttributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'authenticatedAttributes' + }, { + name: 'SignerInfo.digestEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + capture: 'signatureAlgorithm' + }, { + name: 'SignerInfo.encryptedDigest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'signature' + }, { + name: 'SignerInfo.unauthenticatedAttributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + capture: 'unauthenticatedAttributes' + }] +}; + +p7v.signedDataValidator = { + name: 'SignedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'SignedData.DigestAlgorithms', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: 'digestAlgorithms' + }, + contentInfoValidator, + { + name: 'SignedData.Certificates', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + optional: true, + captureAsn1: 'certificates' + }, { + name: 'SignedData.CertificateRevocationLists', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + optional: true, + captureAsn1: 'crls' + }, { + name: 'SignedData.SignerInfos', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + capture: 'signerInfos', + optional: true, + value: [signerValidator] + }] +}; + +p7v.recipientInfoValidator = { + name: 'RecipientInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'RecipientInfo.issuerAndSerial', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.issuerAndSerial.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, { + name: 'RecipientInfo.issuerAndSerial.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'serial' + }] + }, { + name: 'RecipientInfo.keyEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, { + name: 'RecipientInfo.keyEncryptionAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'encParameter', + optional: true + }] + }, { + name: 'RecipientInfo.encryptedKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encKey' + }] +}; + + +/***/ }), + +/***/ 6924: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of a basic Public Key Infrastructure, including + * support for RSA public and private keys. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(9549); +__nccwpck_require__(1925); +__nccwpck_require__(1281); +__nccwpck_require__(154); +__nccwpck_require__(1611); +__nccwpck_require__(466); +__nccwpck_require__(4376); +__nccwpck_require__(3921); +__nccwpck_require__(8339); +__nccwpck_require__(8180); + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +/* Public Key Infrastructure (PKI) implementation. */ +var pki = module.exports = forge.pki = forge.pki || {}; + +/** + * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead. + * + * Converts PEM-formatted data to DER. + * + * @param pem the PEM-formatted data. + * + * @return the DER-formatted data. + */ +pki.pemToDer = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PEM to DER; PEM is encrypted.'); + } + return forge.util.createBuffer(msg.body); +}; + +/** + * Converts an RSA private key from PEM format. + * + * @param pem the PEM-formatted private key. + * + * @return the private key. + */ +pki.privateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM ' + + 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert private key from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return pki.privateKeyFromAsn1(obj); +}; + +/** + * Converts an RSA private key to PEM format. + * + * @param key the private key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted private key. + */ +pki.privateKeyToPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'RSA PRIVATE KEY', + body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts a PrivateKeyInfo to PEM format. + * + * @param pki the PrivateKeyInfo. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted private key. + */ +pki.privateKeyInfoToPem = function(pki, maxline) { + // convert to DER, then PEM-encode + var msg = { + type: 'PRIVATE KEY', + body: asn1.toDer(pki).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + + +/***/ }), + +/***/ 6861: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Prime number generation API. + * + * @author Dave Longley + * + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); +__nccwpck_require__(7052); +__nccwpck_require__(7821); + +(function() { + +// forge.prime already defined +if(forge.prime) { + module.exports = forge.prime; + return; +} + +/* PRIME API */ +var prime = module.exports = forge.prime = forge.prime || {}; + +var BigInteger = forge.jsbn.BigInteger; + +// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; +var THIRTY = new BigInteger(null); +THIRTY.fromInt(30); +var op_or = function(x, y) {return x|y;}; + +/** + * Generates a random probable prime with the given number of bits. + * + * Alternative algorithms can be specified by name as a string or as an + * object with custom options like so: + * + * { + * name: 'PRIMEINC', + * options: { + * maxBlockTime: , + * millerRabinTests: , + * workerScript: , + * workers: . + * workLoad: the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * } + * } + * + * @param bits the number of bits for the prime number. + * @param options the options to use. + * [algorithm] the algorithm to use (default: 'PRIMEINC'). + * [prng] a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + * + * @return callback(err, num) called once the operation completes. + */ +prime.generateProbablePrime = function(bits, options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + // default to PRIMEINC algorithm + var algorithm = options.algorithm || 'PRIMEINC'; + if(typeof algorithm === 'string') { + algorithm = {name: algorithm}; + } + algorithm.options = algorithm.options || {}; + + // create prng with api that matches BigInteger secure random + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for(var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + + if(algorithm.name === 'PRIMEINC') { + return primeincFindPrime(bits, rng, algorithm.options, callback); + } + + throw new Error('Invalid prime generation algorithm: ' + algorithm.name); +}; + +function primeincFindPrime(bits, rng, options, callback) { + if('workers' in options) { + return primeincFindPrimeWithWorkers(bits, rng, options, callback); + } + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); +} + +function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { + // initialize random number + var num = generateRandom(bits, rng); + + /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The + number we are given is always aligned at 30k + 1. Each time the number is + determined not to be prime we add to get to the next 'i', eg: if the number + was at 30k + 1 we add 6. */ + var deltaIdx = 0; + + // get required number of MR tests + var mrTests = getMillerRabinTests(num.bitLength()); + if('millerRabinTests' in options) { + mrTests = options.millerRabinTests; + } + + // find prime nearest to 'num' for maxBlockTime ms + // 10 ms gives 5ms of leeway for other calculations before dropping + // below 60fps (1000/60 == 16.67), but in reality, the number will + // likely be higher due to an 'atomic' big int modPow + var maxBlockTime = 10; + if('maxBlockTime' in options) { + maxBlockTime = options.maxBlockTime; + } + + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); +} + +function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { + var start = +new Date(); + do { + // overflow, regenerate random number + if(num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + // do primality test + if(num.isProbablePrime(mrTests)) { + return callback(null, num); + } + // get next potential prime + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime)); + + // keep trying later + forge.util.setImmediate(function() { + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + }); +} + +// NOTE: This algorithm is indeterminate in nature because workers +// run in parallel looking at different segments of numbers. Even if this +// algorithm is run twice with the same input from a predictable RNG, it +// may produce different outputs. +function primeincFindPrimeWithWorkers(bits, rng, options, callback) { + // web workers unavailable + if(typeof Worker === 'undefined') { + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + + // initialize random number + var num = generateRandom(bits, rng); + + // use web workers to generate keys + var numWorkers = options.workers; + var workLoad = options.workLoad || 100; + var range = workLoad * 30 / 8; + var workerScript = options.workerScript || 'forge/prime.worker.js'; + if(numWorkers === -1) { + return forge.util.estimateCores(function(err, cores) { + if(err) { + // default to 2 + cores = 2; + } + numWorkers = cores - 1; + generate(); + }); + } + generate(); + + function generate() { + // require at least 1 worker + numWorkers = Math.max(1, numWorkers); + + // TODO: consider optimizing by starting workers outside getPrime() ... + // note that in order to clean up they will have to be made internally + // asynchronous which may actually be slower + + // start workers immediately + var workers = []; + for(var i = 0; i < numWorkers; ++i) { + // FIXME: fix path or use blob URLs + workers[i] = new Worker(workerScript); + } + var running = numWorkers; + + // listen for requests from workers and assign ranges to find prime + for(var i = 0; i < numWorkers; ++i) { + workers[i].addEventListener('message', workerMessage); + } + + /* Note: The distribution of random numbers is unknown. Therefore, each + web worker is continuously allocated a range of numbers to check for a + random number until one is found. + + Every 30 numbers will be checked just 8 times, because prime numbers + have the form: + + 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) + + Therefore, if we want a web worker to run N checks before asking for + a new range of numbers, each range must contain N*30/8 numbers. + + For 100 checks (workLoad), this is a range of 375. */ + + var found = false; + function workerMessage(e) { + // ignore message, prime already found + if(found) { + return; + } + + --running; + var data = e.data; + if(data.found) { + // terminate all workers + for(var i = 0; i < workers.length; ++i) { + workers[i].terminate(); + } + found = true; + return callback(null, new BigInteger(data.prime, 16)); + } + + // overflow, regenerate random number + if(num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + + // assign new range to check + var hex = num.toString(16); + + // start prime search + e.target.postMessage({ + hex: hex, + workLoad: workLoad + }); + + num.dAddOffset(range, 0); + } + } +} + +/** + * Generates a random number using the given number of bits and RNG. + * + * @param bits the number of bits for the number. + * @param rng the random number generator to use. + * + * @return the random number. + */ +function generateRandom(bits, rng) { + var num = new BigInteger(bits, rng); + // force MSB set + var bits1 = bits - 1; + if(!num.testBit(bits1)) { + num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); + } + // align number on 30k+1 boundary + num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); + return num; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} + +})(); + + +/***/ }), + +/***/ 4467: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * A javascript implementation of a cryptographically-secure + * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed + * here though the use of SHA-256 is not enforced; when generating an + * a PRNG context, the hashing algorithm and block cipher used for + * the generator are specified via a plugin. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); + +var _crypto = null; +if(forge.util.isNodejs && !forge.options.usePureJavaScript && + !process.versions['node-webkit']) { + _crypto = __nccwpck_require__(6113); +} + +/* PRNG API */ +var prng = module.exports = forge.prng = forge.prng || {}; + +/** + * Creates a new PRNG context. + * + * A PRNG plugin must be passed in that will provide: + * + * 1. A function that initializes the key and seed of a PRNG context. It + * will be given a 16 byte key and a 16 byte seed. Any key expansion + * or transformation of the seed from a byte string into an array of + * integers (or similar) should be performed. + * 2. The cryptographic function used by the generator. It takes a key and + * a seed. + * 3. A seed increment function. It takes the seed and returns seed + 1. + * 4. An api to create a message digest. + * + * For an example, see random.js. + * + * @param plugin the PRNG plugin to use. + */ +prng.create = function(plugin) { + var ctx = { + plugin: plugin, + key: null, + seed: null, + time: null, + // number of reseeds so far + reseeds: 0, + // amount of data generated so far + generated: 0, + // no initial key bytes + keyBytes: '' + }; + + // create 32 entropy pools (each is a message digest) + var md = plugin.md; + var pools = new Array(32); + for(var i = 0; i < 32; ++i) { + pools[i] = md.create(); + } + ctx.pools = pools; + + // entropy pools are written to cyclically, starting at index 0 + ctx.pool = 0; + + /** + * Generates random bytes. The bytes may be generated synchronously or + * asynchronously. Web workers must use the asynchronous interface or + * else the behavior is undefined. + * + * @param count the number of random bytes to generate. + * @param [callback(err, bytes)] called once the operation completes. + * + * @return count random bytes as a string. + */ + ctx.generate = function(count, callback) { + // do synchronously + if(!callback) { + return ctx.generateSync(count); + } + + // simple generator using counter-based CBC + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + var b = forge.util.createBuffer(); + + // paranoid deviation from Fortuna: + // reset key for every request to protect previously + // generated random bytes should the key be discovered; + // there is no 100ms based reseeding because of this + // forced reseed for every `generate` call + ctx.key = null; + + generate(); + + function generate(err) { + if(err) { + return callback(err); + } + + // sufficient bytes generated + if(b.length() >= count) { + return callback(null, b.getBytes(count)); + } + + // if amount of data generated is greater than 1 MiB, trigger reseed + if(ctx.generated > 0xfffff) { + ctx.key = null; + } + + if(ctx.key === null) { + // prevent stack overflow + return forge.util.nextTick(function() { + _reseed(generate); + }); + } + + // generate the random bytes + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + + // generate bytes for a new key and seed + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + + forge.util.setImmediate(generate); + } + }; + + /** + * Generates random bytes synchronously. + * + * @param count the number of random bytes to generate. + * + * @return count random bytes as a string. + */ + ctx.generateSync = function(count) { + // simple generator using counter-based CBC + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + + // paranoid deviation from Fortuna: + // reset key for every request to protect previously + // generated random bytes should the key be discovered; + // there is no 100ms based reseeding because of this + // forced reseed for every `generateSync` call + ctx.key = null; + + var b = forge.util.createBuffer(); + while(b.length() < count) { + // if amount of data generated is greater than 1 MiB, trigger reseed + if(ctx.generated > 0xfffff) { + ctx.key = null; + } + + if(ctx.key === null) { + _reseedSync(); + } + + // generate the random bytes + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + + // generate bytes for a new key and seed + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + } + + return b.getBytes(count); + }; + + /** + * Private function that asynchronously reseeds a generator. + * + * @param callback(err) called once the operation completes. + */ + function _reseed(callback) { + if(ctx.pools[0].messageLength >= 32) { + _seed(); + return callback(); + } + // not enough seed data... + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.seedFile(needed, function(err, bytes) { + if(err) { + return callback(err); + } + ctx.collect(bytes); + _seed(); + callback(); + }); + } + + /** + * Private function that synchronously reseeds a generator. + */ + function _reseedSync() { + if(ctx.pools[0].messageLength >= 32) { + return _seed(); + } + // not enough seed data... + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.collect(ctx.seedFileSync(needed)); + _seed(); + } + + /** + * Private function that seeds a generator once enough bytes are available. + */ + function _seed() { + // update reseed count + ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; + + // goal is to update `key` via: + // key = hash(key + s) + // where 's' is all collected entropy from selected pools, then... + + // create a plugin-based message digest + var md = ctx.plugin.md.create(); + + // consume current key bytes + md.update(ctx.keyBytes); + + // digest the entropy of pools whose index k meet the + // condition 'n mod 2^k == 0' where n is the number of reseeds + var _2powK = 1; + for(var k = 0; k < 32; ++k) { + if(ctx.reseeds % _2powK === 0) { + md.update(ctx.pools[k].digest().getBytes()); + ctx.pools[k].start(); + } + _2powK = _2powK << 1; + } + + // get digest for key bytes + ctx.keyBytes = md.digest().getBytes(); + + // paranoid deviation from Fortuna: + // update `seed` via `seed = hash(key)` + // instead of initializing to zero once and only + // ever incrementing it + md.start(); + md.update(ctx.keyBytes); + var seedBytes = md.digest().getBytes(); + + // update state + ctx.key = ctx.plugin.formatKey(ctx.keyBytes); + ctx.seed = ctx.plugin.formatSeed(seedBytes); + ctx.generated = 0; + } + + /** + * The built-in default seedFile. This seedFile is used when entropy + * is needed immediately. + * + * @param needed the number of bytes that are needed. + * + * @return the random bytes. + */ + function defaultSeedFile(needed) { + // use window.crypto.getRandomValues strong source of entropy if available + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto = globalScope.crypto || globalScope.msCrypto; + if(_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; + } + + var b = forge.util.createBuffer(); + if(getRandomValues) { + while(b.length() < needed) { + // max byte length is 65536 before QuotaExceededError is thrown + // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues + var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); + var entropy = new Uint32Array(Math.floor(count)); + try { + getRandomValues(entropy); + for(var i = 0; i < entropy.length; ++i) { + b.putInt32(entropy[i]); + } + } catch(e) { + /* only ignore QuotaExceededError */ + if(!(typeof QuotaExceededError !== 'undefined' && + e instanceof QuotaExceededError)) { + throw e; + } + } + } + } + + // be sad and add some weak random data + if(b.length() < needed) { + /* Draws from Park-Miller "minimal standard" 31 bit PRNG, + implemented with David G. Carta's optimization: with 32 bit math + and without division (Public Domain). */ + var hi, lo, next; + var seed = Math.floor(Math.random() * 0x010000); + while(b.length() < needed) { + lo = 16807 * (seed & 0xFFFF); + hi = 16807 * (seed >> 16); + lo += (hi & 0x7FFF) << 16; + lo += hi >> 15; + lo = (lo & 0x7FFFFFFF) + (lo >> 31); + seed = lo & 0xFFFFFFFF; + + // consume lower 3 bytes of seed + for(var i = 0; i < 3; ++i) { + // throw in more pseudo random + next = seed >>> (i << 3); + next ^= Math.floor(Math.random() * 0x0100); + b.putByte(next & 0xFF); + } + } + } + + return b.getBytes(needed); + } + // initialize seed file APIs + if(_crypto) { + // use nodejs async API + ctx.seedFile = function(needed, callback) { + _crypto.randomBytes(needed, function(err, bytes) { + if(err) { + return callback(err); + } + callback(null, bytes.toString()); + }); + }; + // use nodejs sync API + ctx.seedFileSync = function(needed) { + return _crypto.randomBytes(needed).toString(); + }; + } else { + ctx.seedFile = function(needed, callback) { + try { + callback(null, defaultSeedFile(needed)); + } catch(e) { + callback(e); + } + }; + ctx.seedFileSync = defaultSeedFile; + } + + /** + * Adds entropy to a prng ctx's accumulator. + * + * @param bytes the bytes of entropy as a string. + */ + ctx.collect = function(bytes) { + // iterate over pools distributing entropy cyclically + var count = bytes.length; + for(var i = 0; i < count; ++i) { + ctx.pools[ctx.pool].update(bytes.substr(i, 1)); + ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1; + } + }; + + /** + * Collects an integer of n bits. + * + * @param i the integer entropy. + * @param n the number of bits in the integer. + */ + ctx.collectInt = function(i, n) { + var bytes = ''; + for(var x = 0; x < n; x += 8) { + bytes += String.fromCharCode((i >> x) & 0xFF); + } + ctx.collect(bytes); + }; + + /** + * Registers a Web Worker to receive immediate entropy from the main thread. + * This method is required until Web Workers can access the native crypto + * API. This method should be called twice for each created worker, once in + * the main thread, and once in the worker itself. + * + * @param worker the worker to register. + */ + ctx.registerWorker = function(worker) { + // worker receives random bytes + if(worker === self) { + ctx.seedFile = function(needed, callback) { + function listener(e) { + var data = e.data; + if(data.forge && data.forge.prng) { + self.removeEventListener('message', listener); + callback(data.forge.prng.err, data.forge.prng.bytes); + } + } + self.addEventListener('message', listener); + self.postMessage({forge: {prng: {needed: needed}}}); + }; + } else { + // main thread sends random bytes upon request + var listener = function(e) { + var data = e.data; + if(data.forge && data.forge.prng) { + ctx.seedFile(data.forge.prng.needed, function(err, bytes) { + worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); + }); + } + }; + // TODO: do we need to remove the event listener when the worker dies? + worker.addEventListener('message', listener); + } + }; + + return ctx; +}; + + +/***/ }), + +/***/ 4376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Javascript implementation of PKCS#1 PSS signature padding. * - * Implementation advice by David Mazieres . + * @author Stefan Siegl * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * Copyright (c) 2012 Stefan Siegl + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7821); +__nccwpck_require__(8339); + +// shortcut for PSS API +var pss = module.exports = forge.pss = forge.pss || {}; + +/** + * Creates a PSS signature scheme object. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * There are several ways to provide a salt for encoding: + * + * 1. Specify the saltLength only and the built-in PRNG will generate it. + * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that + * will be used. + * 3. Specify the salt itself as a forge.util.ByteBuffer. + * + * @param options the options to use: + * md the message digest object to use, a forge md instance. + * mgf the mask generation function to use, a forge mgf instance. + * [saltLength] the length of the salt in octets. + * [prng] the pseudo-random number generator to use to produce a salt. + * [salt] the salt to use when encoding. + * + * @return a signature scheme object. */ +pss.create = function(options) { + // backwards compatibility w/legacy args: hash, mgf, sLen + if(arguments.length === 3) { + options = { + md: arguments[0], + mgf: arguments[1], + saltLength: arguments[2] + }; + } + + var hash = options.md; + var mgf = options.mgf; + var hLen = hash.digestLength; + + var salt_ = options.salt || null; + if(typeof salt_ === 'string') { + // assume binary-encoded string + salt_ = forge.util.createBuffer(salt_); + } + + var sLen; + if('saltLength' in options) { + sLen = options.saltLength; + } else if(salt_ !== null) { + sLen = salt_.length(); + } else { + throw new Error('Salt length not specified or specific salt not given.'); + } + + if(salt_ !== null && salt_.length() !== sLen) { + throw new Error('Given salt length does not match length of given salt.'); + } + + var prng = options.prng || forge.random; + + var pssobj = {}; + + /** + * Encodes a PSS signature. + * + * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1. + * + * @param md the message digest object with the hash to sign. + * @param modsBits the length of the RSA modulus in bits. + * + * @return the encoded message as a binary-encoded string of length + * ceil((modBits - 1) / 8). + */ + pssobj.encode = function(md, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + + /* 2. Let mHash = Hash(M), an octet string of length hLen. */ + var mHash = md.digest().getBytes(); + + /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */ + if(emLen < hLen + sLen + 2) { + throw new Error('Message is too long to encrypt.'); + } + + /* 4. Generate a random octet string salt of length sLen; if sLen = 0, + * then salt is the empty string. */ + var salt; + if(salt_ === null) { + salt = prng.getBytesSync(sLen); + } else { + salt = salt_.bytes(); + } + + /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */ + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + + /* 6. Let H = Hash(M'), an octet string of length hLen. */ + hash.start(); + hash.update(m_.getBytes()); + var h = hash.digest().getBytes(); + + /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 + * zero octets. The length of PS may be 0. */ + var ps = new forge.util.ByteBuffer(); + ps.fillWithByte(0, emLen - sLen - hLen - 2); + + /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length + * emLen - hLen - 1. */ + ps.putByte(0x01); + ps.putBytes(salt); + var db = ps.getBytes(); + + /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */ + var maskLen = emLen - hLen - 1; + var dbMask = mgf.generate(h, maskLen); + + /* 10. Let maskedDB = DB \xor dbMask. */ + var maskedDB = ''; + for(i = 0; i < maskLen; i++) { + maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + + /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in + * maskedDB to zero. */ + var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; + maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + + maskedDB.substr(1); + + /* 12. Let EM = maskedDB || H || 0xbc. + * 13. Output EM. */ + return maskedDB + h + String.fromCharCode(0xbc); + }; + + /** + * Verifies a PSS signature. + * + * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2. + * + * @param mHash the message digest hash, as a binary-encoded string, to + * compare against the signature. + * @param em the encoded message, as a binary-encoded string + * (RSA decryption result). + * @param modsBits the length of the RSA modulus in bits. + * + * @return true if the signature was verified, false if not. + */ + pssobj.verify = function(mHash, em, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + + /* c. Convert the message representative m to an encoded message EM + * of length emLen = ceil((modBits - 1) / 8) octets, where modBits + * is the length in bits of the RSA modulus n */ + em = em.substr(-emLen); + + /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */ + if(emLen < hLen + sLen + 2) { + throw new Error('Inconsistent parameters to PSS signature verification.'); + } + + /* 4. If the rightmost octet of EM does not have hexadecimal value + * 0xbc, output "inconsistent" and stop. */ + if(em.charCodeAt(emLen - 1) !== 0xbc) { + throw new Error('Encoded message does not end in 0xBC.'); + } + + /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and + * let H be the next hLen octets. */ + var maskLen = emLen - hLen - 1; + var maskedDB = em.substr(0, maskLen); + var h = em.substr(maskLen, hLen); -/* - * The bcrypt_pbkdf portions are under the following license: - * - * Copyright (c) 2013 Ted Unangst - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ + /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in + * maskedDB are not all equal to zero, output "inconsistent" and stop. */ + var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; + if((maskedDB.charCodeAt(0) & mask) !== 0) { + throw new Error('Bits beyond keysize not zero as expected.'); + } -/* - * Performance improvements (Javascript-specific): + /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */ + var dbMask = mgf.generate(h, maskLen); + + /* 8. Let DB = maskedDB \xor dbMask. */ + var db = ''; + for(i = 0; i < maskLen; i++) { + db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + + /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet + * in DB to zero. */ + db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); + + /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero + * or if the octet at position emLen - hLen - sLen - 1 (the leftmost + * position is "position 1") does not have hexadecimal value 0x01, + * output "inconsistent" and stop. */ + var checkLen = emLen - hLen - sLen - 2; + for(i = 0; i < checkLen; i++) { + if(db.charCodeAt(i) !== 0x00) { + throw new Error('Leftmost octets not zero as expected'); + } + } + + if(db.charCodeAt(checkLen) !== 0x01) { + throw new Error('Inconsistent PSS signature, 0x01 marker not found'); + } + + /* 11. Let salt be the last sLen octets of DB. */ + var salt = db.substr(-sLen); + + /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */ + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + + /* 13. Let H' = Hash(M'), an octet string of length hLen. */ + hash.start(); + hash.update(m_.getBytes()); + var h_ = hash.digest().getBytes(); + + /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */ + return h === h_; + }; + + return pssobj; +}; + + +/***/ }), + +/***/ 7821: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * An API for getting cryptographically-secure random bytes. The bytes are + * generated using the Fortuna algorithm devised by Bruce Schneier and + * Niels Ferguson. * - * Copyright 2016, Joyent Inc - * Author: Alex Wilson + * Getting strong random bytes is not yet easy to do in javascript. The only + * truish random entropy that can be collected is from the mouse, keyboard, or + * from timing with respect to page loads, etc. This generator makes a poor + * attempt at providing random bytes when those sources haven't yet provided + * enough entropy to initially seed or to reseed the PRNG. * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. + * @author Dave Longley * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * Copyright (c) 2009-2014 Digital Bazaar, Inc. */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7994); +__nccwpck_require__(4086); +__nccwpck_require__(4467); +__nccwpck_require__(8339); -// Ported from OpenBSD bcrypt_pbkdf.c v1.9 +(function() { -var BLF_J = 0; +// forge.random already defined +if(forge.random && forge.random.getBytes) { + module.exports = forge.random; + return; +} -var Blowfish = function() { - this.S = [ - new Uint32Array([ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, - 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, - 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, - 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, - 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, - 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, - 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, - 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, - 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, - 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, - 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, - 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, - 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, - 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, - 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, - 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, - 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, - 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, - 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, - 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, - 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, - 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, - 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, - 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, - 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, - 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, - 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, - 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, - 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, - 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, - 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, - 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, - 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, - 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, - 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, - 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, - 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, - 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, - 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, - 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, - 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, - 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, - 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), - new Uint32Array([ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, - 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, - 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, - 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, - 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, - 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, - 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, - 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, - 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, - 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, - 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, - 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, - 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, - 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, - 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, - 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, - 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, - 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, - 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, - 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, - 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, - 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, - 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, - 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, - 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, - 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, - 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, - 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, - 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, - 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, - 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, - 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, - 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, - 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, - 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, - 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, - 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, - 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, - 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, - 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, - 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, - 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, - 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), - new Uint32Array([ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, - 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, - 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, - 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, - 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, - 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, - 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, - 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, - 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, - 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, - 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, - 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, - 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, - 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, - 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, - 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, - 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, - 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, - 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, - 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, - 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, - 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, - 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, - 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, - 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, - 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, - 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, - 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, - 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, - 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, - 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, - 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, - 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, - 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, - 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, - 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, - 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, - 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, - 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, - 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, - 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, - 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, - 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), - new Uint32Array([ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, - 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, - 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, - 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, - 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, - 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, - 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, - 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, - 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, - 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, - 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, - 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, - 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, - 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, - 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, - 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, - 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, - 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, - 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, - 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, - 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, - 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, - 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, - 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, - 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, - 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, - 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, - 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, - 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, - 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, - 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, - 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, - 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, - 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, - 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, - 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, - 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, - 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, - 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, - 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, - 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, - 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, - 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) - ]; - this.P = new Uint32Array([ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, - 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, - 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, - 0x9216d5d9, 0x8979fb1b]); -}; +(function(jQuery) { -function F(S, x8, i) { - return (((S[0][x8[i+3]] + - S[1][x8[i+2]]) ^ - S[2][x8[i+1]]) + - S[3][x8[i]]); -}; +// the default prng plugin, uses AES-128 +var prng_aes = {}; +var _prng_aes_output = new Array(4); +var _prng_aes_buffer = forge.util.createBuffer(); +prng_aes.formatKey = function(key) { + // convert the key into 32-bit integers + var tmp = forge.util.createBuffer(key); + key = new Array(4); + key[0] = tmp.getInt32(); + key[1] = tmp.getInt32(); + key[2] = tmp.getInt32(); + key[3] = tmp.getInt32(); -Blowfish.prototype.encipher = function(x, x8) { - if (x8 === undefined) { - x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - } - x[0] ^= this.P[0]; - for (var i = 1; i < 16; i += 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[17]; - x[1] = t; + // return the expanded key + return forge.aes._expandKey(key, false); }; - -Blowfish.prototype.decipher = function(x) { - var x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - x[0] ^= this.P[17]; - for (var i = 16; i > 0; i -= 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[0]; - x[1] = t; +prng_aes.formatSeed = function(seed) { + // convert seed into 32-bit integers + var tmp = forge.util.createBuffer(seed); + seed = new Array(4); + seed[0] = tmp.getInt32(); + seed[1] = tmp.getInt32(); + seed[2] = tmp.getInt32(); + seed[3] = tmp.getInt32(); + return seed; }; - -function stream2word(data, databytes){ - var i, temp = 0; - for (i = 0; i < 4; i++, BLF_J++) { - if (BLF_J >= databytes) BLF_J = 0; - temp = (temp << 8) | data[BLF_J]; - } - return temp; +prng_aes.cipher = function(key, seed) { + forge.aes._updateBlock(key, seed, _prng_aes_output, false); + _prng_aes_buffer.putInt32(_prng_aes_output[0]); + _prng_aes_buffer.putInt32(_prng_aes_output[1]); + _prng_aes_buffer.putInt32(_prng_aes_output[2]); + _prng_aes_buffer.putInt32(_prng_aes_output[3]); + return _prng_aes_buffer.getBytes(); +}; +prng_aes.increment = function(seed) { + // FIXME: do we care about carry or signed issues? + ++seed[3]; + return seed; }; +prng_aes.md = forge.md.sha256; -Blowfish.prototype.expand0state = function(key, keybytes) { - var d = new Uint32Array(2), i, k; - var d8 = new Uint8Array(d.buffer); +/** + * Creates a new PRNG. + */ +function spawnPrng() { + var ctx = forge.prng.create(prng_aes); - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - BLF_J = 0; + /** + * Gets random bytes. If a native secure crypto API is unavailable, this + * method tries to make the bytes more unpredictable by drawing from data that + * can be collected from the user of the browser, eg: mouse movement. + * + * If a callback is given, this method will be called asynchronously. + * + * @param count the number of random bytes to get. + * @param [callback(err, bytes)] called once the operation completes. + * + * @return the random bytes in a string. + */ + ctx.getBytes = function(count, callback) { + return ctx.generate(count, callback); + }; - for (i = 0; i < 18; i += 2) { - this.encipher(d, d8); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } + /** + * Gets random bytes asynchronously. If a native secure crypto API is + * unavailable, this method tries to make the bytes more unpredictable by + * drawing from data that can be collected from the user of the browser, + * eg: mouse movement. + * + * @param count the number of random bytes to get. + * + * @return the random bytes in a string. + */ + ctx.getBytesSync = function(count) { + return ctx.generate(count); + }; - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - this.encipher(d, d8); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } -}; + return ctx; +} -Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { - var d = new Uint32Array(2), i, k; +// create default prng context +var _ctx = spawnPrng(); - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } +// add other sources of entropy only if window.crypto.getRandomValues is not +// available -- otherwise this source will be automatically used by the prng +var getRandomValues = null; +var globalScope = forge.util.globalScope; +var _crypto = globalScope.crypto || globalScope.msCrypto; +if(_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; +} - for (i = 0, BLF_J = 0; i < 18; i += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.P[i] = d[0]; - this.P[i+1] = d[1]; +if(forge.options.usePureJavaScript || + (!forge.util.isNodejs && !getRandomValues)) { + // if this is a web worker, do not use weak entropy, instead register to + // receive strong entropy asynchronously from the main thread + if(typeof window === 'undefined' || window.document === undefined) { + // FIXME: } - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } - BLF_J = 0; -}; + // get load time entropy + _ctx.collectInt(+new Date(), 32); -Blowfish.prototype.enc = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.encipher(data.subarray(i*2)); - } -}; + // add some entropy from navigator object + if(typeof(navigator) !== 'undefined') { + var _navBytes = ''; + for(var key in navigator) { + try { + if(typeof(navigator[key]) == 'string') { + _navBytes += navigator[key]; + } + } catch(e) { + /* Some navigator keys might not be accessible, e.g. the geolocation + attribute throws an exception if touched in Mozilla chrome:// + context. -Blowfish.prototype.dec = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.decipher(data.subarray(i*2)); + Silently ignore this and just don't use this as a source of + entropy. */ + } + } + _ctx.collect(_navBytes); + _navBytes = null; } -}; - -var BCRYPT_BLOCKS = 8, - BCRYPT_HASHSIZE = 32; -function bcrypt_hash(sha2pass, sha2salt, out) { - var state = new Blowfish(), - cdata = new Uint32Array(BCRYPT_BLOCKS), i, - ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, - 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, - 105,116,101]); //"OxychromaticBlowfishSwatDynamite" + // add mouse and keyboard collectors if jquery is available + if(jQuery) { + // set up mouse entropy capture + jQuery().mousemove(function(e) { + // add mouse coords + _ctx.collectInt(e.clientX, 16); + _ctx.collectInt(e.clientY, 16); + }); - state.expandstate(sha2salt, 64, sha2pass, 64); - for (i = 0; i < 64; i++) { - state.expand0state(sha2salt, 64); - state.expand0state(sha2pass, 64); + // set up keyboard entropy capture + jQuery().keypress(function(e) { + _ctx.collectInt(e.charCode, 8); + }); } +} - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = stream2word(ciphertext, ciphertext.byteLength); - for (i = 0; i < 64; i++) - state.enc(cdata, cdata.byteLength / 8); - - for (i = 0; i < BCRYPT_BLOCKS; i++) { - out[4*i+3] = cdata[i] >>> 24; - out[4*i+2] = cdata[i] >>> 16; - out[4*i+1] = cdata[i] >>> 8; - out[4*i+0] = cdata[i]; +/* Random API */ +if(!forge.random) { + forge.random = _ctx; +} else { + // extend forge.random with _ctx + for(var key in _ctx) { + forge.random[key] = _ctx[key]; } -}; +} -function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { - var sha2pass = new Uint8Array(64), - sha2salt = new Uint8Array(64), - out = new Uint8Array(BCRYPT_HASHSIZE), - tmpout = new Uint8Array(BCRYPT_HASHSIZE), - countsalt = new Uint8Array(saltlen+4), - i, j, amt, stride, dest, count, - origkeylen = keylen; +// expose spawn PRNG +forge.random.createInstance = spawnPrng; - if (rounds < 1) - return -1; - if (passlen === 0 || saltlen === 0 || keylen === 0 || - keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) - return -1; +module.exports = forge.random; - stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); - amt = Math.floor((keylen + stride - 1) / stride); +})(typeof(jQuery) !== 'undefined' ? jQuery : null); - for (i = 0; i < saltlen; i++) - countsalt[i] = salt[i]; +})(); - crypto_hash_sha512(sha2pass, pass, passlen); - for (count = 1; keylen > 0; count++) { - countsalt[saltlen+0] = count >>> 24; - countsalt[saltlen+1] = count >>> 16; - countsalt[saltlen+2] = count >>> 8; - countsalt[saltlen+3] = count; +/***/ }), - crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (i = out.byteLength; i--;) - out[i] = tmpout[i]; +/***/ 9965: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (i = 1; i < rounds; i++) { - crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (j = 0; j < out.byteLength; j++) - out[j] ^= tmpout[j]; - } +/** + * RC2 implementation. + * + * @author Stefan Siegl + * + * Copyright (c) 2012 Stefan Siegl + * + * Information on the RC2 cipher is available from RFC #2268, + * http://www.ietf.org/rfc/rfc2268.txt + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(8339); - amt = Math.min(amt, keylen); - for (i = 0; i < amt; i++) { - dest = i * stride + (count - 1); - if (dest >= origkeylen) - break; - key[dest] = out[i]; - } - keylen -= i; - } +var piTable = [ + 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, + 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, + 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, + 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, + 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, + 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, + 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, + 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, + 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, + 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, + 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, + 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, + 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, + 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, + 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, + 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad +]; - return 0; +var s = [1, 2, 3, 5]; + +/** + * Rotate a word left by given number of bits. + * + * Bits that are shifted out on the left are put back in on the right + * hand side. + * + * @param word The word to shift left. + * @param bits The number of bits to shift by. + * @return The rotated word. + */ +var rol = function(word, bits) { + return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits)); }; -module.exports = { - BLOCKS: BCRYPT_BLOCKS, - HASHSIZE: BCRYPT_HASHSIZE, - hash: bcrypt_hash, - pbkdf: bcrypt_pbkdf +/** + * Rotate a word right by given number of bits. + * + * Bits that are shifted out on the right are put back in on the left + * hand side. + * + * @param word The word to shift right. + * @param bits The number of bits to shift by. + * @return The rotated word. + */ +var ror = function(word, bits) { + return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff); }; +/* RC2 API */ +module.exports = forge.rc2 = forge.rc2 || {}; -/***/ }), +/** + * Perform RC2 key expansion as per RFC #2268, section 2. + * + * @param key variable-length user key (between 1 and 128 bytes) + * @param effKeyBits number of effective key bits (default: 128) + * @return the expanded RC2 key (ByteBuffer of 128 bytes) + */ +forge.rc2.expandKey = function(key, effKeyBits) { + if(typeof key === 'string') { + key = forge.util.createBuffer(key); + } + effKeyBits = effKeyBits || 128; -/***/ 3682: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* introduce variables that match the names used in RFC #2268 */ + var L = key; + var T = key.length(); + var T1 = effKeyBits; + var T8 = Math.ceil(T1 / 8); + var TM = 0xff >> (T1 & 0x07); + var i; -var register = __nccwpck_require__(4670) -var addHook = __nccwpck_require__(5549) -var removeHook = __nccwpck_require__(6819) + for(i = T; i < 128; i++) { + L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]); + } -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) + L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef + for(i = 127 - T8; i >= 0; i--) { + L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); + } - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) -} + return L; +}; -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} +/** + * Creates a RC2 cipher object. + * + * @param key the symmetric key to use (as base for key generation). + * @param bits the number of effective key bits. + * @param encrypt false for decryption, true for encryption. + * + * @return the cipher. + */ +var createCipher = function(key, bits, encrypt) { + var _finish = false, _input = null, _output = null, _iv = null; + var mixRound, mashRound; + var i, j, K = []; -function HookCollection () { - var state = { - registry: {} + /* Expand key and fill into K[] Array */ + key = forge.rc2.expandKey(key, bits); + for(i = 0; i < 64; i++) { + K.push(key.getInt16Le()); } - var hook = register.bind(null, state) - bindApi(hook, state) + if(encrypt) { + /** + * Perform one mixing round "in place". + * + * @param R Array of four words to perform mixing on. + */ + mixRound = function(R) { + for(i = 0; i < 4; i++) { + R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); + R[i] = rol(R[i], s[i]); + j++; + } + }; - return hook -} + /** + * Perform one mashing round "in place". + * + * @param R Array of four words to perform mashing on. + */ + mashRound = function(R) { + for(i = 0; i < 4; i++) { + R[i] += K[R[(i + 3) % 4] & 63]; + } + }; + } else { + /** + * Perform one r-mixing round "in place". + * + * @param R Array of four words to perform mixing on. + */ + mixRound = function(R) { + for(i = 3; i >= 0; i--) { + R[i] = ror(R[i], s[i]); + R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); + j--; + } + }; -var collectionHookDeprecationMessageDisplayed = false -function Hook () { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') - collectionHookDeprecationMessageDisplayed = true + /** + * Perform one r-mashing round "in place". + * + * @param R Array of four words to perform mashing on. + */ + mashRound = function(R) { + for(i = 3; i >= 0; i--) { + R[i] -= K[R[(i + 3) % 4] & 63]; + } + }; } - return HookCollection() -} -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() + /** + * Run the specified cipher execution plan. + * + * This function takes four words from the input buffer, applies the IV on + * it (if requested) and runs the provided execution plan. + * + * The plan must be put together in form of a array of arrays. Where the + * outer one is simply a list of steps to perform and the inner one needs + * to have two elements: the first one telling how many rounds to perform, + * the second one telling what to do (i.e. the function to call). + * + * @param {Array} plan The plan to execute. + */ + var runPlan = function(plan) { + var R = []; -module.exports = Hook -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook -module.exports.Singular = Hook.Singular -module.exports.Collection = Hook.Collection + /* Get data from input buffer and fill the four words into R */ + for(i = 0; i < 4; i++) { + var val = _input.getInt16Le(); + if(_iv !== null) { + if(encrypt) { + /* We're encrypting, apply the IV first. */ + val ^= _iv.getInt16Le(); + } else { + /* We're decryption, keep cipher text for next block. */ + _iv.putInt16Le(val); + } + } -/***/ }), + R.push(val & 0xffff); + } -/***/ 5549: -/***/ ((module) => { + /* Reset global "j" variable as per spec. */ + j = encrypt ? 0 : 63; -module.exports = addHook; + /* Run execution plan. */ + for(var ptr = 0; ptr < plan.length; ptr++) { + for(var ctr = 0; ctr < plan[ptr][0]; ctr++) { + plan[ptr][1](R); + } + } -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } + /* Write back result to output buffer. */ + for(i = 0; i < 4; i++) { + if(_iv !== null) { + if(encrypt) { + /* We're encrypting in CBC-mode, feed back encrypted bytes into + IV buffer to carry it forward to next block. */ + _iv.putInt16Le(R[i]); + } else { + R[i] ^= _iv.getInt16Le(); + } + } - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } + _output.putInt16Le(R[i]); + } + }; - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } + /* Create cipher object */ + var cipher = null; + cipher = { + /** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * To use the cipher in CBC mode, iv may be given either as a string + * of bytes, or as a byte buffer. For ECB mode, give null as iv. + * + * @param iv the initialization vector to use, null for ECB mode. + * @param output the output the buffer to write to, null to create one. + */ + start: function(iv, output) { + if(iv) { + /* CBC mode */ + if(typeof iv === 'string') { + iv = forge.util.createBuffer(iv); + } + } - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } + _finish = false; + _input = forge.util.createBuffer(); + _output = output || new forge.util.createBuffer(); + _iv = iv; - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} + cipher.output = _output; + }, + /** + * Updates the next block. + * + * @param input the buffer to read from. + */ + update: function(input) { + if(!_finish) { + // not finishing, so fill the input buffer with more input + _input.putBuffer(input); + } -/***/ }), + while(_input.length() >= 8) { + runPlan([ + [ 5, mixRound ], + [ 1, mashRound ], + [ 6, mixRound ], + [ 1, mashRound ], + [ 5, mixRound ] + ]); + } + }, -/***/ 4670: -/***/ ((module) => { + /** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use, null for PKCS#7 padding, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ + finish: function(pad) { + var rval = true; -module.exports = register; + if(encrypt) { + if(pad) { + rval = pad(8, _input, !encrypt); + } else { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (_input.length() === 8) ? 8 : (8 - _input.length()); + _input.fillWithByte(padding, padding); + } + } -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } + if(rval) { + // do final update + _finish = true; + cipher.update(); + } - if (!options) { - options = {}; - } + if(!encrypt) { + // check for error: input data not a multiple of block size + rval = (_input.length() === 0); + if(rval) { + if(pad) { + rval = pad(8, _output, !encrypt); + } else { + // ensure padding byte count is valid + var len = _output.length(); + var count = _output.at(len - 1); - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } + if(count > len) { + rval = false; + } else { + // trim off padding bytes + _output.truncate(count); + } + } + } + } - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); + return rval; } + }; - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} + return cipher; +}; +/** + * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the + * given symmetric key. The output will be stored in the 'output' member + * of the returned cipher. + * + * The key and iv may be given as a string of bytes or a byte buffer. + * The cipher is initialized to use 128 effective key bits. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * + * @return the cipher. + */ +forge.rc2.startEncrypting = function(key, iv, output) { + var cipher = forge.rc2.createEncryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; +}; -/***/ }), +/** + * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the + * given symmetric key. + * + * The key may be given as a string of bytes or a byte buffer. + * + * To start encrypting call start() on the cipher with an iv and optional + * output buffer. + * + * @param key the symmetric key to use. + * + * @return the cipher. + */ +forge.rc2.createEncryptionCipher = function(key, bits) { + return createCipher(key, bits, true); +}; -/***/ 6819: -/***/ ((module) => { +/** + * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the + * given symmetric key. The output will be stored in the 'output' member + * of the returned cipher. + * + * The key and iv may be given as a string of bytes or a byte buffer. + * The cipher is initialized to use 128 effective key bits. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * + * @return the cipher. + */ +forge.rc2.startDecrypting = function(key, iv, output) { + var cipher = forge.rc2.createDecryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; +}; -module.exports = removeHook; +/** + * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the + * given symmetric key. + * + * The key may be given as a string of bytes or a byte buffer. + * + * To start decrypting call start() on the cipher with an iv and optional + * output buffer. + * + * @param key the symmetric key to use. + * + * @return the cipher. + */ +forge.rc2.createDecryptionCipher = function(key, bits) { + return createCipher(key, bits, false); +}; -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); +/***/ }), - if (index === -1) { - return; - } +/***/ 3921: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - state.registry[name].splice(index, 1); +/** + * Javascript implementation of basic RSA algorithms. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * + * The only algorithm currently supported for PKI is RSA. + * + * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo + * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier + * and a subjectPublicKey of type bit string. + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of RSA, there aren't any. + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * For an RSA public key, the subjectPublicKey is: + * + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * + * PrivateKeyInfo ::= SEQUENCE { + * version Version, + * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, + * privateKey PrivateKey, + * attributes [0] IMPLICIT Attributes OPTIONAL + * } + * + * Version ::= INTEGER + * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier + * PrivateKey ::= OCTET STRING + * Attributes ::= SET OF Attribute + * + * An RSA private key as the following structure: + * + * RSAPrivateKey ::= SEQUENCE { + * version Version, + * modulus INTEGER, -- n + * publicExponent INTEGER, -- e + * privateExponent INTEGER, -- d + * prime1 INTEGER, -- p + * prime2 INTEGER, -- q + * exponent1 INTEGER, -- d mod (p-1) + * exponent2 INTEGER, -- d mod (q-1) + * coefficient INTEGER -- (inverse of q) mod p + * } + * + * Version ::= INTEGER + * + * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(9549); +__nccwpck_require__(7052); +__nccwpck_require__(1925); +__nccwpck_require__(7014); +__nccwpck_require__(6861); +__nccwpck_require__(7821); +__nccwpck_require__(8339); + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; } +var _crypto = forge.util.isNodejs ? __nccwpck_require__(6113) : null; -/***/ }), +// shortcut for asn.1 API +var asn1 = forge.asn1; -/***/ 3664: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// shortcut for util API +var util = forge.util; -"use strict"; +/* + * RSA encryption and decryption, see RFC 2313. + */ +forge.pki = forge.pki || {}; +module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; +var pki = forge.pki; +// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; -const { Buffer } = __nccwpck_require__(4300) -const symbol = Symbol.for('BufferList') +// validator for a PrivateKeyInfo structure +var privateKeyValidator = { + // PrivateKeyInfo + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'PrivateKeyInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // privateKeyAlgorithm + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + }] + }, { + // PrivateKey + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + }] +}; -function BufferList (buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf) - } +// validator for an RSA private key +var rsaPrivateKeyValidator = { + // RSAPrivateKey + name: 'RSAPrivateKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'RSAPrivateKey.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // modulus (n) + name: 'RSAPrivateKey.modulus', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyModulus' + }, { + // publicExponent (e) + name: 'RSAPrivateKey.publicExponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPublicExponent' + }, { + // privateExponent (d) + name: 'RSAPrivateKey.privateExponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrivateExponent' + }, { + // prime1 (p) + name: 'RSAPrivateKey.prime1', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime1' + }, { + // prime2 (q) + name: 'RSAPrivateKey.prime2', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime2' + }, { + // exponent1 (d mod (p-1)) + name: 'RSAPrivateKey.exponent1', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent1' + }, { + // exponent2 (d mod (q-1)) + name: 'RSAPrivateKey.exponent2', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent2' + }, { + // coefficient ((inverse of q) mod p) + name: 'RSAPrivateKey.coefficient', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyCoefficient' + }] +}; - BufferList._init.call(this, buf) -} +// validator for an RSA public key +var rsaPublicKeyValidator = { + // RSAPublicKey + name: 'RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // modulus (n) + name: 'RSAPublicKey.modulus', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'publicKeyModulus' + }, { + // publicExponent (e) + name: 'RSAPublicKey.exponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'publicKeyExponent' + }] +}; -BufferList._init = function _init (buf) { - Object.defineProperty(this, symbol, { value: true }) +// validator for an SubjectPublicKeyInfo structure +// Note: Currently only works with an RSA public key +var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + }] +}; - this._bufs = [] - this.length = 0 +// validator for a DigestInfo structure +var digestInfoValidator = { + name: 'DigestInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'DigestInfo.DigestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'algorithmIdentifier' + }, { + // NULL paramters + name: 'DigestInfo.DigestAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.NULL, + // captured only to check existence for md2 and md5 + capture: 'parameters', + optional: true, + constructed: false + }] + }, { + // digest + name: 'DigestInfo.digest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'digest' + }] +}; - if (buf) { - this.append(buf) +/** + * Wrap digest in DigestInfo object. + * + * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * Digest ::= OCTET STRING + * + * @param md the message digest object with the hash to sign. + * + * @return the encoded message (ready for RSA encrytion) + */ +var emsaPkcs1v15encode = function(md) { + // get the oid for the algorithm + var oid; + if(md.algorithm in pki.oids) { + oid = pki.oids[md.algorithm]; + } else { + var error = new Error('Unknown message digest algorithm.'); + error.algorithm = md.algorithm; + throw error; } -} - -BufferList.prototype._new = function _new (buf) { - return new BufferList(buf) -} + var oidBytes = asn1.oidToDer(oid).getBytes(); -BufferList.prototype._offset = function _offset (offset) { - if (offset === 0) { - return [0, 0] - } + // create the digest info + var digestInfo = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var digestAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); + var digest = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, + false, md.digest().getBytes()); + digestInfo.value.push(digestAlgorithm); + digestInfo.value.push(digest); - let tot = 0 + // encode digest info + return asn1.toDer(digestInfo).getBytes(); +}; - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot] - } - tot = _t +/** + * Performs x^c mod n (RSA encryption or decryption operation). + * + * @param x the number to raise and mod. + * @param key the key to use. + * @param pub true if the key is public, false if private. + * + * @return the result of x^c mod n. + */ +var _modPow = function(x, key, pub) { + if(pub) { + return x.modPow(key.e, key.n); } -} - -BufferList.prototype._reverseOffset = function (blOffset) { - const bufferId = blOffset[0] - let offset = blOffset[1] - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length + if(!key.p || !key.q) { + // allow calculation without CRT params (slow) + return x.modPow(key.d, key.n); } - return offset -} - -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined + // pre-compute dP, dQ, and qInv if necessary + if(!key.dP) { + key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); + } + if(!key.dQ) { + key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); + } + if(!key.qInv) { + key.qInv = key.q.modInverse(key.p); } - const offset = this._offset(index) + /* Chinese remainder theorem (CRT) states: - return this._bufs[offset[0]][offset[1]] -} + Suppose n1, n2, ..., nk are positive integers which are pairwise + coprime (n1 and n2 have no common factors other than 1). For any + integers x1, x2, ..., xk there exists an integer x solving the + system of simultaneous congruences (where ~= means modularly + congruent so a ~= b mod n means a mod n = b mod n): -BufferList.prototype.slice = function slice (start, end) { - if (typeof start === 'number' && start < 0) { - start += this.length - } + x ~= x1 mod n1 + x ~= x2 mod n2 + ... + x ~= xk mod nk - if (typeof end === 'number' && end < 0) { - end += this.length - } + This system of congruences has a single simultaneous solution x + between 0 and n - 1. Furthermore, each xk solution and x itself + is congruent modulo the product n = n1*n2*...*nk. + So x1 mod n = x2 mod n = xk mod n = x mod n. - return this.copy(null, 0, start, end) -} + The single simultaneous solution x can be solved with the following + equation: -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== 'number' || srcStart < 0) { - srcStart = 0 - } + x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. - if (typeof srcEnd !== 'number' || srcEnd > this.length) { - srcEnd = this.length - } + Where x is less than n, xi = x mod ni. - if (srcStart >= this.length) { - return dst || Buffer.alloc(0) - } + For RSA we are only concerned with k = 2. The modulus n = pq, where + p and q are coprime. The RSA decryption algorithm is: - if (srcEnd <= 0) { - return dst || Buffer.alloc(0) - } + y = x^d mod n - const copy = !!dst - const off = this._offset(srcStart) - const len = srcEnd - srcStart - let bytes = len - let bufoff = (copy && dstStart) || 0 - let start = off[1] + Given the above: - // copy/slice everything - if (srcStart === 0 && srcEnd === this.length) { - if (!copy) { - // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } + x1 = x^d mod p + r1 = n/p = q + s1 = q^-1 mod p + x2 = x^d mod q + r2 = n/q = p + s2 = p^-1 mod q - // copy, need to copy individual buffers - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } + So y = (x1r1s1 + x2r2s2) mod n + = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n - return dst - } + According to Fermat's Little Theorem, if the modulus P is prime, + for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. + Since A is not divisible by P it follows that if: + N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } + A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort + to calculate). In order to calculate x^d mod p more quickly the + exponent d mod (p - 1) is stored in the RSA private key (the same + is done for x^d mod q). These values are referred to as dP and dQ + respectively. Therefore we now have: - if (!copy) { - // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - } + y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start + Since we'll be reducing x^dP by modulo p (same for q) we can also + reduce x by p (and q respectively) before hand. Therefore, let - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break - } + xp = ((x mod p)^dP mod p), and + xq = ((x mod q)^dQ mod q), yielding: - bytes -= l + y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n - if (start) { - start = 0 - } - } + This can be further reduced to a simple algorithm that only + requires 1 inverse (the q inverse is used) to be used and stored. + The algorithm is called Garner's algorithm. If qInv is the + inverse of q, we simply calculate: - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) + y = (qInv*(xp - xq) mod p) * q + xq - return dst -} + However, there are two further complications. First, we need to + ensure that xp > xq to prevent signed BigIntegers from being used + so we add p until this is true (since we will be mod'ing with + p anyway). Then, there is a known timing attack on algorithms + using the CRT. To mitigate this risk, "cryptographic blinding" + should be used. This requires simply generating a random number r + between 0 and n-1 and its inverse and multiplying x by r^e before + calculating y and then multiplying y by r^-1 afterwards. Note that + r must be coprime with n (gcd(r, n) === 1) in order to have an + inverse. + */ -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end + // cryptographic blinding + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), + 16); + } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); + x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); - if (start < 0) { - start += this.length - } + // calculate xp and xq + var xp = x.mod(key.p).modPow(key.dP, key.p); + var xq = x.mod(key.q).modPow(key.dQ, key.q); - if (end < 0) { - end += this.length + // xp must be larger than xq to avoid signed bit usage + while(xp.compareTo(xq) < 0) { + xp = xp.add(key.p); } - if (start === end) { - return this._new() - } + // do last step + var y = xp.subtract(xq) + .multiply(key.qInv).mod(key.p) + .multiply(key.q).add(xq); - const startOffset = this._offset(start) - const endOffset = this._offset(end) - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) + // remove effect of random for cryptographic blinding + y = y.multiply(r.modInverse(key.n)).mod(key.n); - if (endOffset[1] === 0) { - buffers.pop() + return y; +}; + +/** + * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or + * 'encrypt' on a public key object instead. + * + * Performs RSA encryption. + * + * The parameter bt controls whether to put padding bytes before the + * message passed in. Set bt to either true or false to disable padding + * completely (in order to handle e.g. EMSA-PSS encoding seperately before), + * signaling whether the encryption operation is a public key operation + * (i.e. encrypting data) or not, i.e. private key operation (data signing). + * + * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 + * (for signing) or 0x02 (for encryption). The key operation mode (private + * or public) is derived from this flag in that case). + * + * @param m the message to encrypt as a byte string. + * @param key the RSA key to use. + * @param bt for PKCS#1 v1.5 padding, the block type to use + * (0x01 for private key, 0x02 for public), + * to disable padding: true = public key, false = private key. + * + * @return the encrypted bytes as a string. + */ +pki.rsa.encrypt = function(m, key, bt) { + var pub = bt; + var eb; + + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + if(bt !== false && bt !== true) { + // legacy, default to PKCS#1 v1.5 padding + pub = (bt === 0x02); + eb = _encodePkcs1_v1_5(m, key, bt); } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) + eb = forge.util.createBuffer(); + eb.putBytes(m); } - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]) - } + // load encryption block as big integer 'x' + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var x = new BigInteger(eb.toHex(), 16); - return this._new(buffers) -} + // do RSA encryption + var y = _modPow(x, key, pub); -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} + // convert y into the encrypted data byte string, if y is shorter in + // bytes than k, then prepend zero bytes to fill up ed + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var yhex = y.toString(16); + var ed = forge.util.createBuffer(); + var zeros = k - Math.ceil(yhex.length / 2); + while(zeros > 0) { + ed.putByte(0x00); + --zeros; + } + ed.putBytes(forge.util.hexToBytes(yhex)); + return ed.getBytes(); +}; -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this +/** + * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or + * 'verify' on a public key object instead. + * + * Performs RSA decryption. + * + * The parameter ml controls whether to apply PKCS#1 v1.5 padding + * or not. Set ml = false to disable padding removal completely + * (in order to handle e.g. EMSA-PSS later on) and simply pass back + * the RSA encryption block. + * + * @param ed the encrypted data to decrypt in as a byte string. + * @param key the RSA key to use. + * @param pub true for a public key operation, false for private. + * @param ml the message length, if known, false to disable padding. + * + * @return the decrypted message as a byte string. + */ +pki.rsa.decrypt = function(ed, key, pub, ml) { + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } + // error if the length of the encrypted data ED is not k + if(ed.length !== k) { + var error = new Error('Encrypted message length is invalid.'); + error.length = ed.length; + error.expected = k; + throw error; } - return this -} - -BufferList.prototype.duplicate = function duplicate () { - const copy = this._new() + // convert encrypted data into a big integer + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]) + // y must be less than the modulus or it wasn't the result of + // a previous mod operation (encryption) using that modulus + if(y.compareTo(key.n) >= 0) { + throw new Error('Encrypted message is invalid.'); } - return copy -} + // do RSA decryption + var x = _modPow(y, key, pub); -BufferList.prototype.append = function append (buf) { - if (buf == null) { - return this + // create the encryption block, if x is shorter in bytes than k, then + // prepend zero bytes to fill up eb + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var xhex = x.toString(16); + var eb = forge.util.createBuffer(); + var zeros = k - Math.ceil(xhex.length / 2); + while(zeros > 0) { + eb.putByte(0x00); + --zeros; } + eb.putBytes(forge.util.hexToBytes(xhex)); - if (buf.buffer) { - // append a view of the underlying ArrayBuffer - this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]) - } - } else if (this._isBufferList(buf)) { - // unwrap argument into individual BufferLists - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]) - } - } else { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf === 'number') { - buf = buf.toString() - } - - this._appendBuffer(Buffer.from(buf)) + if(ml !== false) { + // legacy, default to PKCS#1 v1.5 padding + return _decodePkcs1_v1_5(eb.getBytes(), key, pub); } - return this -} + // return message + return eb.getBytes(); +}; -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} +/** + * Creates an RSA key-pair generation state object. It is used to allow + * key-generation to be performed in steps. It also allows for a UI to + * display progress updates. + * + * @param bits the size for the private key in bits, defaults to 2048. + * @param e the public exponent to use, defaults to 65537 (0x10001). + * @param [options] the options to use. + * prng a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + * algorithm the algorithm to use (default: 'PRIMEINC'). + * + * @return the state object to use to generate the key-pair. + */ +pki.rsa.createKeyPairGenerationState = function(bits, e, options) { + // TODO: migrate step-based prime generation code to forge.prime -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined + // set default bits + if(typeof(bits) === 'string') { + bits = parseInt(bits, 10); } + bits = bits || 2048; - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (this._isBufferList(search)) { - search = search.slice() - } else if (Array.isArray(search.buffer)) { - search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } + // create prng with api that matches BigInteger secure random + options = options || {}; + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for(var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; - offset = Number(offset || 0) + var algorithm = options.algorithm || 'PRIMEINC'; - if (isNaN(offset)) { - offset = 0 + // create PRIMEINC algorithm state + var rval; + if(algorithm === 'PRIMEINC') { + rval = { + algorithm: algorithm, + state: 0, + bits: bits, + rng: rng, + eInt: e || 65537, + e: new BigInteger(null), + p: null, + q: null, + qBits: bits >> 1, + pBits: bits - (bits >> 1), + pqState: 0, + num: null, + keys: null + }; + rval.e.fromInt(rval.eInt); + } else { + throw new Error('Invalid key generation algorithm: ' + algorithm); } - if (offset < 0) { - offset = this.length + offset - } + return rval; +}; - if (offset < 0) { - offset = 0 +/** + * Attempts to runs the key-generation algorithm for at most n seconds + * (approximately) using the given state. When key-generation has completed, + * the keys will be stored in state.keys. + * + * To use this function to update a UI while generating a key or to prevent + * causing browser lockups/warnings, set "n" to a value other than 0. A + * simple pattern for generating a key and showing a progress indicator is: + * + * var state = pki.rsa.createKeyPairGenerationState(2048); + * var step = function() { + * // step key-generation, run algorithm for 100 ms, repeat + * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { + * setTimeout(step, 1); + * } else { + * // key-generation complete + * // TODO: turn off progress indicator here + * // TODO: use the generated key-pair in "state.keys" + * } + * }; + * // TODO: turn on progress indicator here + * setTimeout(step, 0); + * + * @param state the state to use. + * @param n the maximum number of milliseconds to run the algorithm for, 0 + * to run the algorithm to completion. + * + * @return true if the key-generation completed, false if not. + */ +pki.rsa.stepKeyPairGenerationState = function(state, n) { + // set default algorithm if not set + if(!('algorithm' in state)) { + state.algorithm = 'PRIMEINC'; } - if (search.length === 0) { - return offset > this.length ? this.length : offset - } + // TODO: migrate step-based prime generation code to forge.prime + // TODO: abstract as PRIMEINC algorithm - const blOffset = this._offset(offset) - let blIndex = blOffset[0] // index of which internal buffer we're working on - let buffOffset = blOffset[1] // offset of the internal buffer we're working on + // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) + // with some minor optimizations and designed to run in steps - // scan over each buffer - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex] + // local state vars + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var deltaIdx = 0; + var op_or = function(x, y) {return x | y;}; + + // keep stepping until time limit is reached or done + var t1 = +new Date(); + var t2; + var total = 0; + while(state.keys === null && (n <= 0 || total < n)) { + // generate p or q + if(state.state === 0) { + /* Note: All primes are of the form: - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset + 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset) + When we generate a random number, we always align it at 30k + 1. Each + time the number is determined not to be prime we add to get to the + next 'i', eg: if the number was at 30k + 1 we add 6. */ + var bits = (state.p === null) ? state.pBits : state.qBits; + var bits1 = bits - 1; - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) + // get a random number + if(state.pqState === 0) { + state.num = new BigInteger(bits, state.rng); + // force MSB set + if(!state.num.testBit(bits1)) { + state.num.bitwiseTo( + BigInteger.ONE.shiftLeft(bits1), op_or, state.num); } + // align number on 30k+1 boundary + state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); + deltaIdx = 0; - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]) + ++state.pqState; + } else if(state.pqState === 1) { + // try to make the number a prime + if(state.num.bitLength() > bits) { + // overflow, try again + state.pqState = 0; + // do primality test + } else if(state.num.isProbablePrime( + _getMillerRabinTests(state.num.bitLength()))) { + ++state.pqState; + } else { + // get next potential prime + state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + } else if(state.pqState === 2) { + // ensure number is coprime with e + state.pqState = + (state.num.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) === 0) ? 3 : 0; + } else if(state.pqState === 3) { + // store p or q + state.pqState = 0; + if(state.p === null) { + state.p = state.num; + } else { + state.q = state.num; + } - if (this._match(revOffset, search)) { - return revOffset + // advance state if both p and q are ready + if(state.p !== null && state.q !== null) { + ++state.state; } + state.num = null; + } + } else if(state.state === 1) { + // ensure p is larger than q (swap them if not) + if(state.p.compareTo(state.q) < 0) { + state.num = state.p; + state.p = state.q; + state.q = state.num; + } + ++state.state; + } else if(state.state === 2) { + // compute phi: (p - 1)(q - 1) (Euler's totient function) + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + ++state.state; + } else if(state.state === 3) { + // ensure e and phi are coprime + if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { + // phi and e are coprime, advance + ++state.state; + } else { + // phi and e aren't coprime, so generate a new p and q + state.p = null; + state.q = null; + state.state = 0; + } + } else if(state.state === 4) { + // create n, ensure n is has the right number of bits + state.n = state.p.multiply(state.q); - buffOffset++ + // ensure n is right number of bits + if(state.n.bitLength() === state.bits) { + // success, advance + ++state.state; + } else { + // failed, get new q + state.q = null; + state.state = 0; } + } else if(state.state === 5) { + // set keys + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki.rsa.setPrivateKey( + state.n, state.e, d, state.p, state.q, + d.mod(state.p1), d.mod(state.q1), + state.q.modInverse(state.p)), + publicKey: pki.rsa.setPublicKey(state.n, state.e) + }; } - buffOffset = 0 + // update timing + t2 = +new Date(); + total += t2 - t1; + t1 = t2; } - return -1 -} - -BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false - } + return state.keys !== null; +}; - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false +/** + * Generates an RSA public-private key pair in a single call. + * + * To generate a key-pair in steps (to allow for progress updates and to + * prevent blocking or warnings in slow browsers) then use the key-pair + * generation state functions. + * + * To generate a key-pair asynchronously (either through web-workers, if + * available, or by breaking up the work on the main thread), pass a + * callback function. + * + * @param [bits] the size for the private key in bits, defaults to 2048. + * @param [e] the public exponent to use, defaults to 65537. + * @param [options] options for key-pair generation, if given then 'bits' + * and 'e' must *not* be given: + * bits the size for the private key in bits, (default: 2048). + * e the public exponent to use, (default: 65537 (0x10001)). + * workerScript the worker script URL. + * workers the number of web workers (if supported) to use, + * (default: 2). + * workLoad the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * prng a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". Disables use of native APIs. + * algorithm the algorithm to use (default: 'PRIMEINC'). + * @param [callback(err, keypair)] called once the operation completes. + * + * @return an object with privateKey and publicKey properties. + */ +pki.rsa.generateKeyPair = function(bits, e, options, callback) { + // (bits), (options), (callback) + if(arguments.length === 1) { + if(typeof bits === 'object') { + options = bits; + bits = undefined; + } else if(typeof bits === 'function') { + callback = bits; + bits = undefined; + } + } else if(arguments.length === 2) { + // (bits, e), (bits, options), (bits, callback), (options, callback) + if(typeof bits === 'number') { + if(typeof e === 'function') { + callback = e; + e = undefined; + } else if(typeof e !== 'number') { + options = e; + e = undefined; + } + } else { + options = bits; + callback = e; + bits = undefined; + e = undefined; + } + } else if(arguments.length === 3) { + // (bits, e, options), (bits, e, callback), (bits, options, callback) + if(typeof e === 'number') { + if(typeof options === 'function') { + callback = options; + options = undefined; + } + } else { + callback = options; + options = e; + e = undefined; } } - return true -} - -;(function () { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null + options = options || {}; + if(bits === undefined) { + bits = options.bits || 2048; + } + if(e === undefined) { + e = options.e || 0x10001; } - for (const m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } else { - BufferList.prototype[m] = function (offset = 0) { - return this.slice(offset, offset + methods[m])[m](0) - } + // use native code if permitted, available, and parameters are acceptable + if(!forge.options.usePureJavaScript && !options.prng && + bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { + if(callback) { + // try native async + if(_detectNodeCrypto('generateKeyPair')) { + return _crypto.generateKeyPair('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }, function(err, pub, priv) { + if(err) { + return callback(err); + } + callback(null, { + privateKey: pki.privateKeyFromPem(priv), + publicKey: pki.publicKeyFromPem(pub) + }); + }); } - }(m)) + if(_detectSubtleCrypto('generateKey') && + _detectSubtleCrypto('exportKey')) { + // use standard native generateKey + return util.globalScope.crypto.subtle.generateKey({ + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, true /* key can be exported*/, ['sign', 'verify']) + .then(function(pair) { + return util.globalScope.crypto.subtle.exportKey( + 'pkcs8', pair.privateKey); + // avoiding catch(function(err) {...}) to support IE <= 8 + }).then(undefined, function(err) { + callback(err); + }).then(function(pkcs8) { + if(pkcs8) { + var privateKey = pki.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8))); + callback(null, { + privateKey: privateKey, + publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) + }); + } + }); + } + if(_detectSubtleMsCrypto('generateKey') && + _detectSubtleMsCrypto('exportKey')) { + var genOp = util.globalScope.msCrypto.subtle.generateKey({ + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, true /* key can be exported*/, ['sign', 'verify']); + genOp.oncomplete = function(e) { + var pair = e.target.result; + var exportOp = util.globalScope.msCrypto.subtle.exportKey( + 'pkcs8', pair.privateKey); + exportOp.oncomplete = function(e) { + var pkcs8 = e.target.result; + var privateKey = pki.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8))); + callback(null, { + privateKey: privateKey, + publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) + }); + }; + exportOp.onerror = function(err) { + callback(err); + }; + }; + genOp.onerror = function(err) { + callback(err); + }; + return; + } + } else { + // try native sync + if(_detectNodeCrypto('generateKeyPairSync')) { + var keypair = _crypto.generateKeyPairSync('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }); + return { + privateKey: pki.privateKeyFromPem(keypair.privateKey), + publicKey: pki.publicKeyFromPem(keypair.publicKey) + }; + } + } } -}()) - -// Used internally by the class and also as an indicator of this object being -// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser -// environment because there could be multiple different copies of the -// BufferList class and some `BufferList`s might be `BufferList`s. -BufferList.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferList || BufferList.isBufferList(b) -} - -BufferList.isBufferList = function isBufferList (b) { - return b != null && b[symbol] -} - -module.exports = BufferList - - -/***/ }), -/***/ 336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // use JavaScript implementation + var state = pki.rsa.createKeyPairGenerationState(bits, e, options); + if(!callback) { + pki.rsa.stepKeyPairGenerationState(state, 0); + return state.keys; + } + _generateKeyPair(state, options, callback); +}; -"use strict"; +/** + * Sets an RSA public key from BigIntegers modulus and exponent. + * + * @param n the modulus. + * @param e the exponent. + * + * @return the public key. + */ +pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { + var key = { + n: n, + e: e + }; + /** + * Encrypts the given data with this public key. Newer applications + * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for + * legacy applications. + * + * @param data the byte string to encrypt. + * @param scheme the encryption scheme to use: + * 'RSAES-PKCS1-V1_5' (default), + * 'RSA-OAEP', + * 'RAW', 'NONE', or null to perform raw RSA encryption, + * an object with an 'encode' property set to a function + * with the signature 'function(data, key)' that returns + * a binary-encoded string representing the encoded data. + * @param schemeOptions any scheme-specific options. + * + * @return the encrypted byte string. + */ + key.encrypt = function(data, scheme, schemeOptions) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } -const DuplexStream = (__nccwpck_require__(1642).Duplex) -const inherits = __nccwpck_require__(4124) -const BufferList = __nccwpck_require__(3664) + if(scheme === 'RSAES-PKCS1-V1_5') { + scheme = { + encode: function(m, key, pub) { + return _encodePkcs1_v1_5(m, key, 0x02).getBytes(); + } + }; + } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + encode: function(m, key) { + return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions); + } + }; + } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = {encode: function(e) {return e;}}; + } else if(typeof scheme === 'string') { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } -function BufferListStream (callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback) - } + // do scheme-based encoding then rsa encryption + var e = scheme.encode(data, key, true); + return pki.rsa.encrypt(e, key, true); + }; - if (typeof callback === 'function') { - this._callback = callback + /** + * Verifies the given signature against the given digest. + * + * PKCS#1 supports multiple (currently two) signature schemes: + * RSASSA-PKCS1-V1_5 and RSASSA-PSS. + * + * By default this implementation uses the "old scheme", i.e. + * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the + * signature is an OCTET STRING that holds a DigestInfo. + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * Digest ::= OCTET STRING + * + * To perform PSS signature verification, provide an instance + * of Forge PSS object as the scheme parameter. + * + * @param digest the message digest hash to compare against the signature, + * as a binary-encoded string. + * @param signature the signature to verify, as a binary-encoded string. + * @param scheme signature verification scheme to use: + * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, + * a Forge PSS object for RSASSA-PSS, + * 'NONE' or null for none, DigestInfo will not be expected, but + * PKCS#1 v1.5 padding will still be used. + * @param options optional verify options + * _parseAllDigestBytes testing flag to control parsing of all + * digest bytes. Unsupported and not for general usage. + * (default: true) + * + * @return true if the signature was verified, false if not. + */ + key.verify = function(digest, signature, scheme, options) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSASSA-PKCS1-V1_5'; + } + if(options === undefined) { + options = { + _parseAllDigestBytes: true + }; + } + if(!('_parseAllDigestBytes' in options)) { + options._parseAllDigestBytes = true; + } - const piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) + if(scheme === 'RSASSA-PKCS1-V1_5') { + scheme = { + verify: function(digest, d) { + // remove padding + d = _decodePkcs1_v1_5(d, key, true); + // d is ASN.1 BER-encoded DigestInfo + var obj = asn1.fromDer(d, { + parseAllBytes: options._parseAllDigestBytes + }); - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) + // validate DigestInfo + var capture = {}; + var errors = []; + if(!asn1.validate(obj, digestInfoValidator, capture, errors)) { + var error = new Error( + 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + + 'DigestInfo value.'); + error.errors = errors; + throw error; + } + // check hash algorithm identifier + // see PKCS1-v1-5DigestAlgorithms in RFC 8017 + // FIXME: add support to vaidator for strict value choices + var oid = asn1.derToOid(capture.algorithmIdentifier); + if(!(oid === forge.oids.md2 || + oid === forge.oids.md5 || + oid === forge.oids.sha1 || + oid === forge.oids.sha224 || + oid === forge.oids.sha256 || + oid === forge.oids.sha384 || + oid === forge.oids.sha512 || + oid === forge.oids['sha512-224'] || + oid === forge.oids['sha512-256'])) { + var error = new Error( + 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.'); + error.oid = oid; + throw error; + } - callback = null - } + // special check for md2 and md5 that NULL parameters exist + if(oid === forge.oids.md2 || oid === forge.oids.md5) { + if(!('parameters' in capture)) { + throw new Error( + 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + + 'DigestInfo value. ' + + 'Missing algorithm identifer NULL parameters.'); + } + } - BufferList._init.call(this, callback) - DuplexStream.call(this) -} + // compare the given digest to the decrypted one + return digest === capture.digest; + } + }; + } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = { + verify: function(digest, d) { + // remove padding + d = _decodePkcs1_v1_5(d, key, true); + return digest === d; + } + }; + } -inherits(BufferListStream, DuplexStream) -Object.assign(BufferListStream.prototype, BufferList.prototype) + // do rsa decryption w/o any decoding, then verify -- which does decoding + var d = pki.rsa.decrypt(signature, key, true, false); + return scheme.verify(digest, d, key.n.bitLength()); + }; -BufferListStream.prototype._new = function _new (callback) { - return new BufferListStream(callback) -} + return key; +}; -BufferListStream.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) +/** + * Sets an RSA private key from BigIntegers modulus, exponent, primes, + * prime exponents, and modular multiplicative inverse. + * + * @param n the modulus. + * @param e the public exponent. + * @param d the private exponent ((inverse of e) mod n). + * @param p the first prime. + * @param q the second prime. + * @param dP exponent1 (d mod (p-1)). + * @param dQ exponent2 (d mod (q-1)). + * @param qInv ((inverse of q) mod p) + * + * @return the private key. + */ +pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function( + n, e, d, p, q, dP, dQ, qInv) { + var key = { + n: n, + e: e, + d: d, + p: p, + q: q, + dP: dP, + dQ: dQ, + qInv: qInv + }; - if (typeof callback === 'function') { - callback() - } -} + /** + * Decrypts the given data with this private key. The decryption scheme + * must match the one used to encrypt the data. + * + * @param data the byte string to decrypt. + * @param scheme the decryption scheme to use: + * 'RSAES-PKCS1-V1_5' (default), + * 'RSA-OAEP', + * 'RAW', 'NONE', or null to perform raw RSA decryption. + * @param schemeOptions any scheme-specific options. + * + * @return the decrypted byte string. + */ + key.decrypt = function(data, scheme, schemeOptions) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } -BufferListStream.prototype._read = function _read (size) { - if (!this.length) { - return this.push(null) - } + // do rsa decryption w/o any decoding + var d = pki.rsa.decrypt(data, key, false, false); - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} + if(scheme === 'RSAES-PKCS1-V1_5') { + scheme = {decode: _decodePkcs1_v1_5}; + } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + decode: function(d, key) { + return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions); + } + }; + } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = {decode: function(d) {return d;}}; + } else { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } -BufferListStream.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) + // decode according to scheme + return scheme.decode(d, key, false); + }; - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} + /** + * Signs the given digest, producing a signature. + * + * PKCS#1 supports multiple (currently two) signature schemes: + * RSASSA-PKCS1-V1_5 and RSASSA-PSS. + * + * By default this implementation uses the "old scheme", i.e. + * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide + * an instance of Forge PSS object as the scheme parameter. + * + * @param md the message digest object with the hash to sign. + * @param scheme the signature scheme to use: + * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, + * a Forge PSS object for RSASSA-PSS, + * 'NONE' or null for none, DigestInfo will not be used but + * PKCS#1 v1.5 padding will still be used. + * + * @return the signature as a byte string. + */ + key.sign = function(md, scheme) { + /* Note: The internal implementation of RSA operations is being + transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy + code like the use of an encoding block identifier 'bt' will eventually + be removed. */ -BufferListStream.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) -} + // private key operation + var bt = false; -BufferListStream.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) -} + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } -BufferListStream.isBufferList = BufferList.isBufferList + if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { + scheme = {encode: emsaPkcs1v15encode}; + bt = 0x01; + } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = {encode: function() {return md;}}; + bt = 0x01; + } -module.exports = BufferListStream -module.exports.BufferListStream = BufferListStream -module.exports.BufferList = BufferList + // encode and then encrypt + var d = scheme.encode(md, key.n.bitLength()); + return pki.rsa.encrypt(d, key, bt); + }; + return key; +}; -/***/ }), +/** + * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object. + * + * @param rsaKey the ASN.1 RSAPrivateKey. + * + * @return the ASN.1 PrivateKeyInfo. + */ +pki.wrapRsaPrivateKey = function(rsaKey) { + // PrivateKeyInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(0).getBytes()), + // privateKeyAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // PrivateKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(rsaKey).getBytes()) + ]); +}; -/***/ 9051: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Converts a private key from an ASN.1 object. + * + * @param obj the ASN.1 representation of a PrivateKeyInfo containing an + * RSAPrivateKey or an RSAPrivateKey. + * + * @return the private key. + */ +pki.privateKeyFromAsn1 = function(obj) { + // get PrivateKeyInfo + var capture = {}; + var errors = []; + if(asn1.validate(obj, privateKeyValidator, capture, errors)) { + obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); + } -"use strict"; + // get RSAPrivateKey + capture = {}; + errors = []; + if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read private key. ' + + 'ASN.1 object does not contain an RSAPrivateKey.'); + error.errors = errors; + throw error; + } -const fs = __nccwpck_require__(7147) -const path = __nccwpck_require__(1017) + // Note: Version is currently ignored. + // capture.privateKeyVersion + // FIXME: inefficient, get a BigInteger that uses byte strings + var n, e, d, p, q, dP, dQ, qInv; + n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); + e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); + d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); + p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); + q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); + dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); + dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); + qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); -/* istanbul ignore next */ -const LCHOWN = fs.lchown ? 'lchown' : 'chown' -/* istanbul ignore next */ -const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' + // set private key + return pki.setRsaPrivateKey( + new BigInteger(n, 16), + new BigInteger(e, 16), + new BigInteger(d, 16), + new BigInteger(p, 16), + new BigInteger(q, 16), + new BigInteger(dP, 16), + new BigInteger(dQ, 16), + new BigInteger(qInv, 16)); +}; -/* istanbul ignore next */ -const needEISDIRHandled = fs.lchown && - !process.version.match(/v1[1-9]+\./) && - !process.version.match(/v10\.[6-9]/) +/** + * Converts a private key to an ASN.1 RSAPrivateKey. + * + * @param key the private key. + * + * @return the ASN.1 representation of an RSAPrivateKey. + */ +pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) { + // RSAPrivateKey + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0 = only 2 primes, 1 multiple primes) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(0).getBytes()), + // modulus (n) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.e)), + // privateExponent (d) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.d)), + // privateKeyPrime1 (p) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.p)), + // privateKeyPrime2 (q) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.q)), + // privateKeyExponent1 (dP) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.dP)), + // privateKeyExponent2 (dQ) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.dQ)), + // coefficient (qInv) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.qInv)) + ]); +}; -const lchownSync = (path, uid, gid) => { - try { - return fs[LCHOWNSYNC](path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er +/** + * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey. + * + * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey. + * + * @return the public key. + */ +pki.publicKeyFromAsn1 = function(obj) { + // get SubjectPublicKeyInfo + var capture = {}; + var errors = []; + if(asn1.validate(obj, publicKeyValidator, capture, errors)) { + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + var error = new Error('Cannot read public key. Unknown OID.'); + error.oid = oid; + throw error; + } + obj = capture.rsaPublicKey; } -} -/* istanbul ignore next */ -const chownSync = (path, uid, gid) => { - try { - return fs.chownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er + // get RSA params + errors = []; + if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { + var error = new Error('Cannot read public key. ' + + 'ASN.1 object does not contain an RSAPublicKey.'); + error.errors = errors; + throw error; } -} -/* istanbul ignore next */ -const handleEISDIR = - needEISDIRHandled ? (path, uid, gid, cb) => er => { - // Node prior to v10 had a very questionable implementation of - // fs.lchown, which would always try to call fs.open on a directory - // Fall back to fs.chown in those cases. - if (!er || er.code !== 'EISDIR') - cb(er) - else - fs.chown(path, uid, gid, cb) - } - : (_, __, ___, cb) => cb + // FIXME: inefficient, get a BigInteger that uses byte strings + var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); + var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); -/* istanbul ignore next */ -const handleEISDirSync = - needEISDIRHandled ? (path, uid, gid) => { - try { - return lchownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'EISDIR') - throw er - chownSync(path, uid, gid) - } - } - : (path, uid, gid) => lchownSync(path, uid, gid) + // set public key + return pki.setRsaPublicKey( + new BigInteger(n, 16), + new BigInteger(e, 16)); +}; -// fs.readdir could only accept an options object as of node v6 -const nodeVersion = process.version -let readdir = (path, options, cb) => fs.readdir(path, options, cb) -let readdirSync = (path, options) => fs.readdirSync(path, options) -/* istanbul ignore next */ -if (/^v4\./.test(nodeVersion)) - readdir = (path, options, cb) => fs.readdir(path, cb) +/** + * Converts a public key to an ASN.1 SubjectPublicKeyInfo. + * + * @param key the public key. + * + * @return the asn1 representation of a SubjectPublicKeyInfo. + */ +pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) { + // SubjectPublicKeyInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // subjectPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ + pki.publicKeyToRSAPublicKey(key) + ]) + ]); +}; -const chown = (cpath, uid, gid, cb) => { - fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { - // Skip ENOENT error - cb(er && er.code !== 'ENOENT' ? er : null) - })) -} +/** + * Converts a public key to an ASN.1 RSAPublicKey. + * + * @param key the public key. + * + * @return the asn1 representation of a RSAPublicKey. + */ +pki.publicKeyToRSAPublicKey = function(key) { + // RSAPublicKey + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // modulus (n) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.e)) + ]); +}; -const chownrKid = (p, child, uid, gid, cb) => { - if (typeof child === 'string') - return fs.lstat(path.resolve(p, child), (er, stats) => { - // Skip ENOENT error - if (er) - return cb(er.code !== 'ENOENT' ? er : null) - stats.name = child - chownrKid(p, stats, uid, gid, cb) - }) +/** + * Encodes a message using PKCS#1 v1.5 padding. + * + * @param m the message to encode. + * @param key the RSA key to use. + * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02 + * (for encryption). + * + * @return the padded byte buffer. + */ +function _encodePkcs1_v1_5(m, key, bt) { + var eb = forge.util.createBuffer(); - if (child.isDirectory()) { - chownr(path.resolve(p, child.name), uid, gid, er => { - if (er) - return cb(er) - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - }) - } else { - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + /* use PKCS#1 v1.5 padding */ + if(m.length > (k - 11)) { + var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); + error.length = m.length; + error.max = k - 11; + throw error; } -} + /* A block type BT, a padding string PS, and the data D shall be + formatted into an octet string EB, the encryption block: -const chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { - // any error other than ENOTDIR or ENOTSUP means it's not readable, - // or doesn't exist. give up. - if (er) { - if (er.code === 'ENOENT') - return cb() - else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') - return cb(er) - } - if (er || !children.length) - return chown(p, uid, gid, cb) + EB = 00 || BT || PS || 00 || D - let len = children.length - let errState = null - const then = er => { - if (errState) - return - if (er) - return cb(errState = er) - if (-- len === 0) - return chown(p, uid, gid, cb) - } + The block type BT shall be a single octet indicating the structure of + the encryption block. For this version of the document it shall have + value 00, 01, or 02. For a private-key operation, the block type + shall be 00 or 01. For a public-key operation, it shall be 02. + + The padding string PS shall consist of k-3-||D|| octets. For block + type 00, the octets shall have value 00; for block type 01, they + shall have value FF; and for block type 02, they shall be + pseudorandomly generated and nonzero. This makes the length of the + encryption block EB equal to k. */ - children.forEach(child => chownrKid(p, child, uid, gid, then)) - }) -} + // build the encryption block + eb.putByte(0x00); + eb.putByte(bt); -const chownrKidSync = (p, child, uid, gid) => { - if (typeof child === 'string') { - try { - const stats = fs.lstatSync(path.resolve(p, child)) - stats.name = child - child = stats - } catch (er) { - if (er.code === 'ENOENT') - return - else - throw er + // create the padding + var padNum = k - 3 - m.length; + var padByte; + // private key op + if(bt === 0x00 || bt === 0x01) { + padByte = (bt === 0x00) ? 0x00 : 0xFF; + for(var i = 0; i < padNum; ++i) { + eb.putByte(padByte); + } + } else { + // public key op + // pad with random non-zero values + while(padNum > 0) { + var numZeros = 0; + var padBytes = forge.random.getBytes(padNum); + for(var i = 0; i < padNum; ++i) { + padByte = padBytes.charCodeAt(i); + if(padByte === 0) { + ++numZeros; + } else { + eb.putByte(padByte); + } + } + padNum = numZeros; } } - if (child.isDirectory()) - chownrSync(path.resolve(p, child.name), uid, gid) + // zero followed by message + eb.putByte(0x00); + eb.putBytes(m); - handleEISDirSync(path.resolve(p, child.name), uid, gid) + return eb; } -const chownrSync = (p, uid, gid) => { - let children - try { - children = readdirSync(p, { withFileTypes: true }) - } catch (er) { - if (er.code === 'ENOENT') - return - else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') - return handleEISDirSync(p, uid, gid) - else - throw er - } +/** + * Decodes a message using PKCS#1 v1.5 padding. + * + * @param em the message to decode. + * @param key the RSA key to use. + * @param pub true if the key is a public key, false if it is private. + * @param ml the message length, if specified. + * + * @return the decoded bytes. + */ +function _decodePkcs1_v1_5(em, key, pub, ml) { + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); - if (children && children.length) - children.forEach(child => chownrKidSync(p, child, uid, gid)) + /* It is an error if any of the following conditions occurs: - return handleEISDirSync(p, uid, gid) -} + 1. The encryption block EB cannot be parsed unambiguously. + 2. The padding string PS consists of fewer than eight octets + or is inconsisent with the block type BT. + 3. The decryption process is a public-key operation and the block + type BT is not 00 or 01, or the decryption process is a + private-key operation and the block type is not 02. + */ -module.exports = chownr -chownr.sync = chownrSync + // parse the encryption block + var eb = forge.util.createBuffer(em); + var first = eb.getByte(); + var bt = eb.getByte(); + if(first !== 0x00 || + (pub && bt !== 0x00 && bt !== 0x01) || + (!pub && bt != 0x02) || + (pub && bt === 0x00 && typeof(ml) === 'undefined')) { + throw new Error('Encryption block is invalid.'); + } + var padNum = 0; + if(bt === 0x00) { + // check all padding bytes for 0x00 + padNum = k - 3 - ml; + for(var i = 0; i < padNum; ++i) { + if(eb.getByte() !== 0x00) { + throw new Error('Encryption block is invalid.'); + } + } + } else if(bt === 0x01) { + // find the first byte that isn't 0xFF, should be after all padding + padNum = 0; + while(eb.length() > 1) { + if(eb.getByte() !== 0xFF) { + --eb.read; + break; + } + ++padNum; + } + } else if(bt === 0x02) { + // look for 0x00 byte + padNum = 0; + while(eb.length() > 1) { + if(eb.getByte() === 0x00) { + --eb.read; + break; + } + ++padNum; + } + } -/***/ }), + // zero must be 0x00 and padNum must be (k - 3 - message length) + var zero = eb.getByte(); + if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) { + throw new Error('Encryption block is invalid.'); + } -/***/ 4137: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return eb.getBytes(); +} -const binding = __nccwpck_require__(4240); +/** + * Runs the key-generation algorithm asynchronously, either in the background + * via Web Workers, or using the main thread and setImmediate. + * + * @param state the key-pair generation state. + * @param [options] options for key-pair generation: + * workerScript the worker script URL. + * workers the number of web workers (if supported) to use, + * (default: 2, -1 to use estimated cores minus one). + * workLoad the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * @param callback(err, keypair) called once the operation completes. + */ +function _generateKeyPair(state, options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; -module.exports = binding.getCPUInfo; + var opts = { + algorithm: { + name: options.algorithm || 'PRIMEINC', + options: { + workers: options.workers || 2, + workLoad: options.workLoad || 100, + workerScript: options.workerScript + } + } + }; + if('prng' in options) { + opts.prng = options.prng; + } + generate(); -/***/ }), + function generate() { + // find p and then q (done in series to simplify) + getPrime(state.pBits, function(err, num) { + if(err) { + return callback(err); + } + state.p = num; + if(state.q !== null) { + return finish(err, state.q); + } + getPrime(state.qBits, finish); + }); + } -/***/ 8222: -/***/ ((module, exports, __nccwpck_require__) => { + function getPrime(bits, callback) { + forge.prime.generateProbablePrime(bits, opts, callback); + } -/* eslint-env browser */ + function finish(err, num) { + if(err) { + return callback(err); + } -/** - * This is the web browser implementation of `debug()`. - */ + // set q + state.q = num; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; + // ensure p is larger than q (swap them if not) + if(state.p.compareTo(state.q) < 0) { + var tmp = state.p; + state.p = state.q; + state.q = tmp; + } - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); + // ensure p is coprime with e + if(state.p.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) !== 0) { + state.p = null; + generate(); + return; + } -/** - * Colors. - */ + // ensure q is coprime with e + if(state.q.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) !== 0) { + state.q = null; + getPrime(state.qBits, finish); + return; + } -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; + // compute phi: (p - 1)(q - 1) (Euler's totient function) + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + // ensure e and phi are coprime + if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + // phi and e aren't coprime, so generate a new p and q + state.p = state.q = null; + generate(); + return; + } -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } + // create n, ensure n is has the right number of bits + state.n = state.p.multiply(state.q); + if(state.n.bitLength() !== state.bits) { + // failed, get new q + state.q = null; + getPrime(state.qBits, finish); + return; + } - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + // set keys + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki.rsa.setPrivateKey( + state.n, state.e, d, state.p, state.q, + d.mod(state.p1), d.mod(state.q1), + state.q.modInverse(state.p)), + publicKey: pki.rsa.setPublicKey(state.n, state.e) + }; - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + callback(null, state.keys); + } } /** - * Colorize log arguments if enabled. + * Converts a positive BigInteger into 2's-complement big-endian bytes. * - * @api public + * @param b the big integer to convert. + * + * @return the bytes. */ +function _bnToBytes(b) { + // prepend 0x00 if first byte >= 0x80 + var hex = b.toString(16); + if(hex[0] >= '8') { + hex = '00' + hex; + } + var bytes = forge.util.hexToBytes(hex); -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); + // ensure integer is minimally-encoded + if(bytes.length > 1 && + // leading 0x00 for positive integer + ((bytes.charCodeAt(0) === 0 && + (bytes.charCodeAt(1) & 0x80) === 0) || + // leading 0xFF for negative integer + (bytes.charCodeAt(0) === 0xFF && + (bytes.charCodeAt(1) & 0x80) === 0x80))) { + return bytes.substr(1); + } + return bytes; } /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. * - * @api public + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. */ -exports.log = console.debug || console.log || (() => {}); +function _getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} /** - * Save `namespaces`. + * Performs feature detection on the Node crypto interface. * - * @param {String} namespaces - * @api private + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function _detectNodeCrypto(fn) { + return forge.util.isNodejs && typeof _crypto[fn] === 'function'; } /** - * Load `namespaces`. + * Performs feature detection on the SubtleCrypto interface. * - * @return {String} returns the previously persisted debug modes - * @api private + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; +function _detectSubtleCrypto(fn) { + return (typeof util.globalScope !== 'undefined' && + typeof util.globalScope.crypto === 'object' && + typeof util.globalScope.crypto.subtle === 'object' && + typeof util.globalScope.crypto.subtle[fn] === 'function'); } /** - * Localstorage attempts to return the localstorage. + * Performs feature detection on the deprecated Microsoft Internet Explorer + * outdated SubtleCrypto interface. This function should only be used after + * checking for the modern, standard SubtleCrypto interface. * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * @param fn the feature (function) to detect. * - * @return {LocalStorage} - * @api private + * @return true if detected, false if not. */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function _detectSubtleMsCrypto(fn) { + return (typeof util.globalScope !== 'undefined' && + typeof util.globalScope.msCrypto === 'object' && + typeof util.globalScope.msCrypto.subtle === 'object' && + typeof util.globalScope.msCrypto.subtle[fn] === 'function'); } -module.exports = __nccwpck_require__(6243)(exports); +function _intToUint8Array(x) { + var bytes = forge.util.hexToBytes(x.toString(16)); + var buffer = new Uint8Array(bytes.length); + for(var i = 0; i < bytes.length; ++i) { + buffer[i] = bytes.charCodeAt(i); + } + return buffer; +} -const {formatters} = module.exports; +function _privateKeyFromJwk(jwk) { + if(jwk.kty !== 'RSA') { + throw new Error( + 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".'); + } + return pki.setRsaPrivateKey( + _base64ToBigInt(jwk.n), + _base64ToBigInt(jwk.e), + _base64ToBigInt(jwk.d), + _base64ToBigInt(jwk.p), + _base64ToBigInt(jwk.q), + _base64ToBigInt(jwk.dp), + _base64ToBigInt(jwk.dq), + _base64ToBigInt(jwk.qi)); +} -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ +function _publicKeyFromJwk(jwk) { + if(jwk.kty !== 'RSA') { + throw new Error('Key algorithm must be "RSA".'); + } + return pki.setRsaPublicKey( + _base64ToBigInt(jwk.n), + _base64ToBigInt(jwk.e)); +} -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; +function _base64ToBigInt(b64) { + return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16); +} /***/ }), -/***/ 6243: +/***/ 279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(6231); +__nccwpck_require__(8339); -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(900); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ +var sha1 = module.exports = forge.sha1 = forge.sha1 || {}; +forge.md.sha1 = forge.md.algorithms.sha1 = sha1; - createDebug.names = []; - createDebug.skips = []; +/** + * Creates a SHA-1 message digest object. + * + * @return a message digest object. + */ +sha1.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; + // SHA-1 state contains five 32-bit integers + var _state = null; - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; + // input buffer + var _input = forge.util.createBuffer(); - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + // used for word storage + var _w = new Array(80); - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + // message digest object + var md = { + algorithm: 'sha1', + blockLength: 64, + digestLength: 20, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476, + h4: 0xC3D2E1F0 + }; + return md; + }; + // start digest automatically for first time + md.start(); - const self = debug; + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } - args[0] = createDebug.coerce(args[0]); + // add bytes to input buffer + _input.putBytes(msg); - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } + // process bytes + _update(_state, _w, _input); - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + return md; + }; - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-1 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, - set: v => { - enableOverride = v; - } - }); + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); - return debug; - } + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + return rval; + }; - createDebug.names = []; - createDebug.skips = []; + return md; +}; - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +// sha-1 padding bytes not initialized yet +var _padding = null; +var _initialized = false; - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); - namespaces = split[i].replace(/\*/g, '.*?'); + // now initialized + _initialized = true; +} - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } +/** + * Updates a SHA-1 state with the given byte buffer. + * + * @param s the SHA-1 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, e, f, i; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 80 32-bit words according to SHA-1 algorithm + // and for 32-79 using Max Locktyukhin's optimization - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + // round 1 + for(i = 0; i < 16; ++i) { + t = bytes.getInt32(); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 20; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 2 + for(; i < 32; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 40; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 3 + for(; i < 60; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = (b & c) | (d & (b ^ c)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 4 + for(; i < 80; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } - let i; - let len; + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } + len -= 64; + } +} - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - return false; - } +/***/ }), - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } +/***/ 4086: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } +/** + * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. + * + * See FIPS 180-2 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(6231); +__nccwpck_require__(8339); - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } +var sha256 = module.exports = forge.sha256 = forge.sha256 || {}; +forge.md.sha256 = forge.md.algorithms.sha256 = sha256; - createDebug.enable(createDebug.load()); +/** + * Creates a SHA-256 message digest object. + * + * @return a message digest object. + */ +sha256.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } - return createDebug; -} + // SHA-256 state contains eight 32-bit integers + var _state = null; -module.exports = setup; + // input buffer + var _input = forge.util.createBuffer(); + // used for word storage + var _w = new Array(64); -/***/ }), + // message digest object + var md = { + algorithm: 'sha256', + blockLength: 64, + digestLength: 32, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; -/***/ 8237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x6A09E667, + h1: 0xBB67AE85, + h2: 0x3C6EF372, + h3: 0xA54FF53A, + h4: 0x510E527F, + h5: 0x9B05688C, + h6: 0x1F83D9AB, + h7: 0x5BE0CD19 + }; + return md; + }; + // start digest automatically for first time + md.start(); -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(8222); -} else { - module.exports = __nccwpck_require__(5332); -} + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } -/***/ }), + // add bytes to input buffer + _input.putBytes(msg); -/***/ 5332: -/***/ ((module, exports, __nccwpck_require__) => { + // process bytes + _update(_state, _w, _input); -/** - * Module dependencies. - */ + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } -const tty = __nccwpck_require__(6224); -const util = __nccwpck_require__(3837); + return md; + }; -/** - * This is the Node.js implementation of `debug()`. - */ + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-256 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. -/** - * Colors. - */ + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ -exports.colors = [6, 2, 3, 4, 5, 1]; + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(9318); + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4, + h5: _state.h5, + h6: _state.h6, + h7: _state.h7 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + rval.putInt32(s2.h5); + rval.putInt32(s2.h6); + rval.putInt32(s2.h7); + return rval; + }; - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } + return md; +}; - obj[prop] = val; - return obj; -}, {}); +// sha-256 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +// table of constants +var _k = null; /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Initializes the constant tables. */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); + // create K table for SHA-256 + _k = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; + + // now initialized + _initialized = true; } /** - * Adds ANSI color escape codes if enabled. + * Updates a SHA-256 state with the given byte buffer. * - * @api public + * @param s the SHA-256 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 64 32-bit words according to SHA-256 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32(); + } + for(; i < 64; ++i) { + // XOR word 2 words ago rot right 17, rot right 19, shft right 10 + t1 = w[i - 2]; + t1 = + ((t1 >>> 17) | (t1 << 15)) ^ + ((t1 >>> 19) | (t1 << 13)) ^ + (t1 >>> 10); + // XOR word 15 words ago rot right 7, rot right 18, shft right 3 + t2 = w[i - 15]; + t2 = + ((t2 >>> 7) | (t2 << 25)) ^ + ((t2 >>> 18) | (t2 << 14)) ^ + (t2 >>> 3); + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 + w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; + } -function formatArgs(args) { - const {namespace: name, useColors} = this; + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + f = s.h5; + g = s.h6; + h = s.h7; - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + // round function + for(i = 0; i < 64; ++i) { + // Sum1(e) + s1 = + ((e >>> 6) | (e << 26)) ^ + ((e >>> 11) | (e << 21)) ^ + ((e >>> 25) | (e << 7)); + // Ch(e, f, g) (optimized the same way as SHA-1) + ch = g ^ (e & (f ^ g)); + // Sum0(a) + s0 = + ((a >>> 2) | (a << 30)) ^ + ((a >>> 13) | (a << 19)) ^ + ((a >>> 22) | (a << 10)); + // Maj(a, b, c) (optimized the same way as SHA-1) + maj = (a & b) | (c & (a ^ b)); - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} + // main algorithm + t1 = h + s1 + ch + _k[i] + w[i]; + t2 = s0 + maj; + h = g; + g = f; + f = e; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + e = (d + t1) >>> 0; + d = c; + c = b; + b = a; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + a = (t1 + t2) >>> 0; + } -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + s.h5 = (s.h5 + f) | 0; + s.h6 = (s.h6 + g) | 0; + s.h7 = (s.h7 + h) | 0; + len -= 64; + } } -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} +/***/ }), -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} +/***/ 9542: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Load `namespaces`. + * Secure Hash Algorithm with a 1024-bit block size implementation. * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. + * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For + * SHA-256 (block size 512 bits), see sha256.js. * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * See FIPS 180-4 for details. + * + * @author Dave Longley + * + * Copyright (c) 2014-2015 Digital Bazaar, Inc. */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(6231); +__nccwpck_require__(8339); -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} +var sha512 = module.exports = forge.sha512 = forge.sha512 || {}; -module.exports = __nccwpck_require__(6243)(exports); +// SHA-512 +forge.md.sha512 = forge.md.algorithms.sha512 = sha512; -const {formatters} = module.exports; +// SHA-384 +var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; +sha384.create = function() { + return sha512.create('SHA-384'); +}; +forge.md.sha384 = forge.md.algorithms.sha384 = sha384; -/** - * Map %o to `util.inspect()`, all on a single line. - */ +// SHA-512/256 +forge.sha512.sha256 = forge.sha512.sha256 || { + create: function() { + return sha512.create('SHA-512/256'); + } +}; +forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] = + forge.sha512.sha256; -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); +// SHA-512/224 +forge.sha512.sha224 = forge.sha512.sha224 || { + create: function() { + return sha512.create('SHA-512/224'); + } }; +forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] = + forge.sha512.sha224; /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * Creates a SHA-2 message digest object. + * + * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224, + * SHA-512/256). + * + * @return a message digest object. */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), - -/***/ 8932: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'Deprecation'; +sha512.create = function(algorithm) { + // do initialization as necessary + if(!_initialized) { + _init(); } -} + if(typeof algorithm === 'undefined') { + algorithm = 'SHA-512'; + } -exports.Deprecation = Deprecation; + if(!(algorithm in _states)) { + throw new Error('Invalid SHA-512 algorithm: ' + algorithm); + } + // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints) + var _state = _states[algorithm]; + var _h = null; -/***/ }), + // input buffer + var _input = forge.util.createBuffer(); -/***/ 4305: -/***/ ((module, exports, __nccwpck_require__) => { + // used for 64-bit word storage + var _w = new Array(80); + for(var wi = 0; wi < 80; ++wi) { + _w[wi] = new Array(2); + } -//Based on follow-redirects v0.0.x + // determine digest length by algorithm name (default) + var digestLength = 64; + switch(algorithm) { + case 'SHA-384': + digestLength = 48; + break; + case 'SHA-512/256': + digestLength = 32; + break; + case 'SHA-512/224': + digestLength = 28; + break; + } -var nativeHttps = __nccwpck_require__(5687), - nativeHttp = __nccwpck_require__(3685), - url = __nccwpck_require__(7310), - utils = __nccwpck_require__(4967); + // message digest object + var md = { + // SHA-512 => sha512 + algorithm: algorithm.replace('-', '').toLowerCase(), + blockLength: 128, + digestLength: digestLength, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 16 + }; -var maxRedirects = module.exports.maxRedirects = 5; + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; -var protocols = { - https: nativeHttps, - http: nativeHttp -}; + // full message length (set md.messageLength128 for backwards-compatibility) + md.fullMessageLength = md.messageLength128 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _h = new Array(_state.length); + for(var i = 0; i < _state.length; ++i) { + _h[i] = _state[i].slice(0); + } + return md; + }; + // start digest automatically for first time + md.start(); -for (var protocol in protocols) { - var h = function() {}; - h.prototype = protocols[protocol]; - h = new h(); + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } - h.request = function(h) { - return function(options, callback, redirectOptions) { + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } - redirectOptions = redirectOptions || {}; + // add bytes to input buffer + _input.putBytes(msg); - var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects; + // process bytes + _update(_h, _w, _input); - var redirect = utils.extend({ - count: 0, - max: max, - clientRequest: null, - userCallback: callback - }, redirectOptions); + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } - if (redirect.count > redirect.max) { - var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.'); - redirect.clientRequest.emit('error', err); - return redirect.clientRequest; - } + return md; + }; - redirect.count++; + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-512 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ - var reqUrl; - if (typeof options === 'string') { - reqUrl = options; - } else { - reqUrl = url.format(utils.extend({ - protocol: protocol - }, options)); - } + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 896 mod 1024. In other words, + the data to be digested must be a multiple of 1024 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 16 bytes (128 + bits), that means that the last segment of the data must have 112 bytes + (896 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 896 mod 1024 because + 1024 - 128 = 896. - var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect)); + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 896 mod 1024, then 1024 padding bits must be added. */ - if (!redirect.clientRequest) redirect.clientRequest = clientRequest; + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); - function redirectCallback(reqUrl, redirect) { - return function(res) { - if (res.statusCode < 300 || res.statusCode > 399) { - return redirect.userCallback(res); - } + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); - if (!('location' in res.headers)) { - return redirect.userCallback(res); - } + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var redirectUrl = url.resolve(reqUrl, res.headers.location); + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); - var proto = url.parse(redirectUrl).protocol; - proto = proto.substr(0, proto.length - 1); - return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect); - }; + var h = new Array(_h.length); + for(var i = 0; i < _h.length; ++i) { + h[i] = _h[i].slice(0); + } + _update(h, _w, finalBlock); + var rval = forge.util.createBuffer(); + var hlen; + if(algorithm === 'SHA-512') { + hlen = h.length; + } else if(algorithm === 'SHA-384') { + hlen = h.length - 2; + } else { + hlen = h.length - 4; + } + for(var i = 0; i < hlen; ++i) { + rval.putInt32(h[i][0]); + if(i !== hlen - 1 || algorithm !== 'SHA-512/224') { + rval.putInt32(h[i][1]); } + } + return rval; + }; - return clientRequest; - }; - }(h); - - // see https://github.com/joyent/node/blob/master/lib/http.js#L1623 - h.get = function(h) { - return function(options, cb, redirectOptions) { - var req = h.request(options, cb, redirectOptions); - req.end(); - return req; - }; - }(h); - - module.exports[protocol] = h; -} - - -/***/ }), - -/***/ 3855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = HttpDuplex; - -var util = __nccwpck_require__(3837), - stream = __nccwpck_require__(1642); + return md; +}; -util.inherits(HttpDuplex, stream.Duplex); +// sha-512 padding bytes not initialized yet +var _padding = null; +var _initialized = false; -function HttpDuplex(req, res, options) { - var self = this; +// table of constants +var _k = null; - if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options); +// initial hash states +var _states = null; - stream.Duplex.call(self, options); - self._output = null; +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 128); - self.connect(req, res); -} + // create K table for SHA-512 + _k = [ + [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd], + [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc], + [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019], + [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118], + [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe], + [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2], + [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1], + [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694], + [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3], + [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65], + [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483], + [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5], + [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210], + [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4], + [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725], + [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70], + [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926], + [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df], + [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8], + [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b], + [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001], + [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30], + [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910], + [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8], + [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53], + [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8], + [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb], + [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3], + [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60], + [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec], + [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9], + [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b], + [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207], + [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178], + [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6], + [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b], + [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493], + [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c], + [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a], + [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817] + ]; -HttpDuplex.prototype.connect = function(req, res) { - var self = this; - self.req = req; - self._output = res; - self.emit('response', res); + // initial hash states + _states = {}; + _states['SHA-512'] = [ + [0x6a09e667, 0xf3bcc908], + [0xbb67ae85, 0x84caa73b], + [0x3c6ef372, 0xfe94f82b], + [0xa54ff53a, 0x5f1d36f1], + [0x510e527f, 0xade682d1], + [0x9b05688c, 0x2b3e6c1f], + [0x1f83d9ab, 0xfb41bd6b], + [0x5be0cd19, 0x137e2179] + ]; + _states['SHA-384'] = [ + [0xcbbb9d5d, 0xc1059ed8], + [0x629a292a, 0x367cd507], + [0x9159015a, 0x3070dd17], + [0x152fecd8, 0xf70e5939], + [0x67332667, 0xffc00b31], + [0x8eb44a87, 0x68581511], + [0xdb0c2e0d, 0x64f98fa7], + [0x47b5481d, 0xbefa4fa4] + ]; + _states['SHA-512/256'] = [ + [0x22312194, 0xFC2BF72C], + [0x9F555FA3, 0xC84C64C2], + [0x2393B86B, 0x6F53B151], + [0x96387719, 0x5940EABD], + [0x96283EE2, 0xA88EFFE3], + [0xBE5E1E25, 0x53863992], + [0x2B0199FC, 0x2C85B8AA], + [0x0EB72DDC, 0x81C52CA2] + ]; + _states['SHA-512/224'] = [ + [0x8C3D37C8, 0x19544DA2], + [0x73E19966, 0x89DCD4D6], + [0x1DFAB7AE, 0x32FF9C82], + [0x679DD514, 0x582F9FCF], + [0x0F6D2B69, 0x7BD44DA8], + [0x77E36F73, 0x04C48942], + [0x3F9D85A8, 0x6A1D36C8], + [0x1112E6AD, 0x91D692A1] + ]; - res.on('data', function(c) { - if (!self.push(c)) self._output.pause(); - }); - res.on('end', function() { - self.push(null); - }); -}; + // now initialized + _initialized = true; +} -HttpDuplex.prototype._read = function(n) { - if (this._output) this._output.resume(); -}; +/** + * Updates a SHA-512 state with the given byte buffer. + * + * @param s the SHA-512 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (128 byte) chunks + var t1_hi, t1_lo; + var t2_hi, t2_lo; + var s0_hi, s0_lo; + var s1_hi, s1_lo; + var ch_hi, ch_lo; + var maj_hi, maj_lo; + var a_hi, a_lo; + var b_hi, b_lo; + var c_hi, c_lo; + var d_hi, d_lo; + var e_hi, e_lo; + var f_hi, f_lo; + var g_hi, g_lo; + var h_hi, h_lo; + var i, hi, lo, w2, w7, w15, w16; + var len = bytes.length(); + while(len >= 128) { + // the w array will be populated with sixteen 64-bit big-endian words + // and then extended into 64 64-bit words according to SHA-512 + for(i = 0; i < 16; ++i) { + w[i][0] = bytes.getInt32() >>> 0; + w[i][1] = bytes.getInt32() >>> 0; + } + for(; i < 80; ++i) { + // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x) + w2 = w[i - 2]; + hi = w2[0]; + lo = w2[1]; -HttpDuplex.prototype._write = function(chunk, encoding, cb) { - this.req.write(chunk, encoding); - cb(); -}; + // high bits + t1_hi = ( + ((hi >>> 19) | (lo << 13)) ^ // ROTR 19 + ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29) + (hi >>> 6)) >>> 0; // SHR 6 + // low bits + t1_lo = ( + ((hi << 13) | (lo >>> 19)) ^ // ROTR 19 + ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29) + ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6 -HttpDuplex.prototype.end = function(chunk, encoding, cb) { - this._output.socket.destroy(); - return this.req.end(chunk, encoding, cb); -}; + // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x) + w15 = w[i - 15]; + hi = w15[0]; + lo = w15[1]; -HttpDuplex.prototype.destroy = function() { - this.req.destroy(); - this._output.socket.destroy(); -}; + // high bits + t2_hi = ( + ((hi >>> 1) | (lo << 31)) ^ // ROTR 1 + ((hi >>> 8) | (lo << 24)) ^ // ROTR 8 + (hi >>> 7)) >>> 0; // SHR 7 + // low bits + t2_lo = ( + ((hi << 31) | (lo >>> 1)) ^ // ROTR 1 + ((hi << 24) | (lo >>> 8)) ^ // ROTR 8 + ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7 + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow) + w7 = w[i - 7]; + w16 = w[i - 16]; + lo = (t1_lo + w7[1] + t2_lo + w16[1]); + w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + + ((lo / 0x100000000) >>> 0)) >>> 0; + w[i][1] = lo >>> 0; + } -/***/ }), + // initialize hash value for this chunk + a_hi = s[0][0]; + a_lo = s[0][1]; + b_hi = s[1][0]; + b_lo = s[1][1]; + c_hi = s[2][0]; + c_lo = s[2][1]; + d_hi = s[3][0]; + d_lo = s[3][1]; + e_hi = s[4][0]; + e_lo = s[4][1]; + f_hi = s[5][0]; + f_lo = s[5][1]; + g_hi = s[6][0]; + g_lo = s[6][1]; + h_hi = s[7][0]; + h_lo = s[7][1]; -/***/ 6042: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // round function + for(i = 0; i < 80; ++i) { + // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e) + s1_hi = ( + ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14 + ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18 + ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9) + s1_lo = ( + ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14 + ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18 + ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9) -var querystring = __nccwpck_require__(3477), - http = __nccwpck_require__(4305), - fs = __nccwpck_require__(7147), - path = __nccwpck_require__(1017), - url = __nccwpck_require__(7310), - ssh = __nccwpck_require__(7964), - HttpDuplex = __nccwpck_require__(3855), - debug = __nccwpck_require__(8237)('modem'), - utils = __nccwpck_require__(4967), - util = __nccwpck_require__(3837), - url = __nccwpck_require__(7310), - splitca = __nccwpck_require__(9798), - isWin = (__nccwpck_require__(2037).type)() === 'Windows_NT'; + // Ch(e, f, g) (optimized the same way as SHA-1) + ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; + ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; -var defaultOpts = function () { - var host; - var opts = {}; + // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a) + s0_hi = ( + ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28 + ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2) + ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7) + s0_lo = ( + ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28 + ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2) + ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7) - if (!process.env.DOCKER_HOST) { - // Windows socket path: //./pipe/docker_engine ( Windows 10 ) - // Linux & Darwin socket path: /var/run/docker.sock - opts.socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock'; - } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) { - // Strip off unix://, fall back to default of /var/run/docker.sock if - // unix:// was passed without a path - opts.socketPath = process.env.DOCKER_HOST.substring(7) || '/var/run/docker.sock'; - } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) { - // Strip off npipe://, fall back to default of //./pipe/docker_engine if - // npipe:// was passed without a path - opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine'; - } else { - var hostStr = process.env.DOCKER_HOST; - if (hostStr.indexOf('\/\/') < 0) { - hostStr = 'tcp://' + hostStr; - } - try { - host = new url.URL(hostStr); - } catch (err) { - throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234'); - } + // Maj(a, b, c) (optimized the same way as SHA-1) + maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; + maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; - opts.port = host.port; + // main algorithm + // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow) + lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]); + t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + + ((lo / 0x100000000) >>> 0)) >>> 0; + t1_lo = lo >>> 0; - if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') { - opts.protocol = 'https'; - } else if (host.protocol === 'ssh:') { - opts.protocol = 'ssh'; - opts.username = host.username; - opts.sshOptions = { - agent: process.env.SSH_AUTH_SOCK, - } - } else { - opts.protocol = 'http'; - } + // t2 = s0 + maj modulo 2^64 (carry lo overflow) + lo = s0_lo + maj_lo; + t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + t2_lo = lo >>> 0; - opts.host = host.hostname; + h_hi = g_hi; + h_lo = g_lo; - if (process.env.DOCKER_CERT_PATH) { - opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem')); - opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem')); - opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem')); - } + g_hi = f_hi; + g_lo = f_lo; - if (process.env.DOCKER_CLIENT_TIMEOUT) { - opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); - } - } + f_hi = e_hi; + f_lo = e_lo; - return opts; -}; + // e = (d + t1) modulo 2^64 (carry lo overflow) + lo = d_lo + t1_lo; + e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + e_lo = lo >>> 0; + d_hi = c_hi; + d_lo = c_lo; -var Modem = function (options) { - var optDefaults = defaultOpts(); - var opts = Object.assign({}, optDefaults, options); + c_hi = b_hi; + c_lo = b_lo; - this.host = opts.host; + b_hi = a_hi; + b_lo = a_lo; - if(!this.host) { - this.socketPath = opts.socketPath; - } + // a = (t1 + t2) modulo 2^64 (carry lo overflow) + lo = t1_lo + t2_lo; + a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + a_lo = lo >>> 0; + } - this.port = opts.port; - this.username = opts.username; - this.password = opts.password; - this.version = opts.version; - this.key = opts.key; - this.cert = opts.cert; - this.ca = opts.ca; - this.timeout = opts.timeout; - this.connectionTimeout = opts.connectionTimeout; - this.checkServerIdentity = opts.checkServerIdentity; - this.agent = opts.agent; - this.headers = opts.headers || {}; - this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); - //retrocompabitlity - if(this.sshOptions.agentForward === undefined) { - this.sshOptions.agentForward = opts.agentForward; - } + // update hash state (additional modulo 2^64) + lo = s[0][1] + a_lo; + s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[0][1] = lo >>> 0; - if (this.key && this.cert && this.ca) { - this.protocol = 'https'; - } - this.protocol = opts.protocol || this.protocol || 'http'; -}; + lo = s[1][1] + b_lo; + s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[1][1] = lo >>> 0; -Modem.prototype.dial = function (options, callback) { - var opts, address, data; - var self = this; + lo = s[2][1] + c_lo; + s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[2][1] = lo >>> 0; - if (options.options) { - opts = options.options; - } + lo = s[3][1] + d_lo; + s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[3][1] = lo >>> 0; - // Prevent credentials from showing up in URL - if (opts && opts.authconfig) { - delete opts.authconfig; - } + lo = s[4][1] + e_lo; + s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[4][1] = lo >>> 0; - // Prevent abortsignal from showing up in the URL - if (opts && opts.abortSignal) { - delete opts.abortSignal; - } + lo = s[5][1] + f_lo; + s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[5][1] = lo >>> 0; - if (this.version) { - options.path = '/' + this.version + options.path; - } + lo = s[6][1] + g_lo; + s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[6][1] = lo >>> 0; - if (this.host) { - var parsed = url.parse(self.host); - address = url.format({ - 'protocol': parsed.protocol || self.protocol, - 'hostname': parsed.hostname || self.host, - 'port': self.port - }); - address = url.resolve(address, options.path); - } else { - address = options.path; - } + lo = s[7][1] + h_lo; + s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[7][1] = lo >>> 0; - if (options.path.indexOf('?') !== -1) { - if (opts && Object.keys(opts).length > 0) { - address += this.buildQuerystring(opts._query || opts); - } else { - address = address.substring(0, address.length - 1); - } + len -= 128; } +} - var optionsf = { - path: address, - method: options.method, - headers: options.headers || Object.assign({}, self.headers), - key: self.key, - cert: self.cert, - ca: self.ca - }; - - if (this.checkServerIdentity) { - optionsf.checkServerIdentity = this.checkServerIdentity; - } - if (this.agent) { - optionsf.agent = this.agent; - } +/***/ }), - if (options.authconfig) { - optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 || - Buffer.from(JSON.stringify(options.authconfig)).toString('base64'); - } +/***/ 4280: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (options.registryconfig) { - optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 || - Buffer.from(JSON.stringify(options.registryconfig)).toString('base64'); - } +/** + * Functions to output keys in SSH-friendly formats. + * + * This is part of the Forge project which may be used under the terms of + * either the BSD License or the GNU General Public License (GPL) Version 2. + * + * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE + * + * @author https://github.com/shellac + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7994); +__nccwpck_require__(5104); +__nccwpck_require__(6594); +__nccwpck_require__(279); +__nccwpck_require__(8339); - if (options.abortSignal) { - optionsf.signal = options.abortSignal; - } +var ssh = module.exports = forge.ssh = forge.ssh || {}; - if (options.file) { - if (typeof options.file === 'string') { - data = fs.createReadStream(path.resolve(options.file)); - } else { - data = options.file; - } - optionsf.headers['Content-Type'] = 'application/tar'; - } else if (opts && options.method === 'POST') { - data = JSON.stringify(opts._body || opts); - if (options.allowEmpty) { - optionsf.headers['Content-Type'] = 'application/json'; - } else { - if (data !== '{}' && data !== '""') { - optionsf.headers['Content-Type'] = 'application/json'; - } else { - data = undefined; - } - } - } +/** + * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file. + * + * @param privateKey the key. + * @param passphrase a passphrase to protect the key (falsy for no encryption). + * @param comment a comment to include in the key file. + * + * @return the PPK file as a string. + */ +ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { + comment = comment || ''; + passphrase = passphrase || ''; + var algorithm = 'ssh-rsa'; + var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc'; - if (typeof data === 'string') { - optionsf.headers['Content-Length'] = Buffer.byteLength(data); - } else if (Buffer.isBuffer(data) === true) { - optionsf.headers['Content-Length'] = data.length; - } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) { - optionsf.headers['Transfer-Encoding'] = 'chunked'; - } + var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n'; + ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n'; + ppk += 'Comment: ' + comment + '\r\n'; - if (options.hijack) { - optionsf.headers.Connection = 'Upgrade'; - optionsf.headers.Upgrade = 'tcp'; - } + // public key into buffer for ppk + var pubbuffer = forge.util.createBuffer(); + _addStringToBuffer(pubbuffer, algorithm); + _addBigIntegerToBuffer(pubbuffer, privateKey.e); + _addBigIntegerToBuffer(pubbuffer, privateKey.n); - if (this.socketPath) { - optionsf.socketPath = this.socketPath; - } else { - var urlp = url.parse(address); - optionsf.hostname = urlp.hostname; - optionsf.port = urlp.port; - optionsf.path = urlp.path; - } + // write public key + var pub = forge.util.encode64(pubbuffer.bytes(), 64); + var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n + ppk += 'Public-Lines: ' + length + '\r\n'; + ppk += pub; - this.buildRequest(optionsf, options, data, callback); -}; + // private key into a buffer + var privbuffer = forge.util.createBuffer(); + _addBigIntegerToBuffer(privbuffer, privateKey.d); + _addBigIntegerToBuffer(privbuffer, privateKey.p); + _addBigIntegerToBuffer(privbuffer, privateKey.q); + _addBigIntegerToBuffer(privbuffer, privateKey.qInv); -Modem.prototype.buildRequest = function (options, context, data, callback) { - var self = this; - var connectionTimeoutTimer; + // optionally encrypt the private key + var priv; + if(!passphrase) { + // use the unencrypted buffer + priv = forge.util.encode64(privbuffer.bytes(), 64); + } else { + // encrypt RSA key using passphrase + var encLen = privbuffer.length() + 16 - 1; + encLen -= encLen % 16; - var opts = self.protocol === 'ssh' ? Object.assign(options, { - agent: ssh(Object.assign({}, self.sshOptions, { - 'host': self.host, - 'port': self.port, - 'username': self.username, - 'password': self.password, - })), - protocol: 'http:', - }) : options; + // pad private key with sha1-d data -- needs to be a multiple of 16 + var padding = _sha1(privbuffer.bytes()); - var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { }); + padding.truncate(padding.length() - encLen + privbuffer.length()); + privbuffer.putBuffer(padding); - debug('Sending: %s', util.inspect(options, { - showHidden: true, - depth: null - })); + var aeskey = forge.util.createBuffer(); + aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase)); + aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase)); - if (self.connectionTimeout) { - connectionTimeoutTimer = setTimeout(function () { - debug('Connection Timeout of %s ms exceeded', self.connectionTimeout); - req.abort(); - }, self.connectionTimeout); - } + // encrypt some bytes using CBC mode + // key is 40 bytes, so truncate *by* 8 bytes + var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC'); + cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); + cipher.update(privbuffer.copy()); + cipher.finish(); + var encrypted = cipher.output; - if (self.timeout) { - req.on('socket', function (socket) { - socket.setTimeout(self.timeout); - socket.on('timeout', function () { - debug('Timeout of %s ms exceeded', self.timeout); - req.abort(); - }); - }); - } + // Note: this appears to differ from Putty -- is forge wrong, or putty? + // due to padding we finish as an exact multiple of 16 + encrypted.truncate(16); // all padding - if (context.hijack === true) { - clearTimeout(connectionTimeoutTimer); - req.on('upgrade', function (res, sock, head) { - return callback(null, sock); - }); + priv = forge.util.encode64(encrypted.bytes(), 64); } - req.on('connect', function () { - clearTimeout(connectionTimeoutTimer); - }); + // output private key + length = Math.floor(priv.length / 66) + 1; // 64 + \r\n + ppk += '\r\nPrivate-Lines: ' + length + '\r\n'; + ppk += priv; - req.on('disconnect', function () { - clearTimeout(connectionTimeoutTimer); - }); + // MAC + var mackey = _sha1('putty-private-key-file-mac-key', passphrase); - req.on('response', function (res) { - clearTimeout(connectionTimeoutTimer); - if (context.isStream === true) { - self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback); - } else { - var chunks = []; - res.on('data', function (chunk) { - chunks.push(chunk); - }); + var macbuffer = forge.util.createBuffer(); + _addStringToBuffer(macbuffer, algorithm); + _addStringToBuffer(macbuffer, encryptionAlgorithm); + _addStringToBuffer(macbuffer, comment); + macbuffer.putInt32(pubbuffer.length()); + macbuffer.putBuffer(pubbuffer); + macbuffer.putInt32(privbuffer.length()); + macbuffer.putBuffer(privbuffer); - res.on('end', function () { - var buffer = Buffer.concat(chunks); - var result = buffer.toString(); + var hmac = forge.hmac.create(); + hmac.start('sha1', mackey); + hmac.update(macbuffer.bytes()); - debug('Received: %s', result); + ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n'; - var json = utils.parseJSON(result) || buffer; - self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback); - }); - } - }); + return ppk; +}; - req.on('error', function (error) { - clearTimeout(connectionTimeoutTimer); - self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback); - }); +/** + * Encodes a public RSA key as an OpenSSH file. + * + * @param key the key. + * @param comment a comment. + * + * @return the public key in OpenSSH format. + */ +ssh.publicKeyToOpenSSH = function(key, comment) { + var type = 'ssh-rsa'; + comment = comment || ''; - if (typeof data === 'string' || Buffer.isBuffer(data)) { - req.write(data); - } else if (data) { - data.on('error', function (error) { - req.destroy(error); - }); - data.pipe(req); - } + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); - if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) { - req.end(); + return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment; +}; + +/** + * Encodes a private RSA key as an OpenSSH file. + * + * @param key the key. + * @param passphrase a passphrase to protect the key (falsy for no encryption). + * + * @return the public key in OpenSSH format. + */ +ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { + if(!passphrase) { + return forge.pki.privateKeyToPem(privateKey); } + // OpenSSH private key is just a legacy format, it seems + return forge.pki.encryptRsaPrivateKey(privateKey, passphrase, + {legacy: true, algorithm: 'aes128'}); }; -Modem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) { - if (err) return cb(err, null); +/** + * Gets the SSH fingerprint for the given public key. + * + * @param options the options to use. + * [md] the message digest object to use (defaults to forge.md.md5). + * [encoding] an alternative output encoding, such as 'hex' + * (defaults to none, outputs a byte buffer). + * [delimiter] the delimiter to use between bytes for 'hex' encoded + * output, eg: ':' (defaults to none). + * + * @return the fingerprint as a byte buffer or other encoding based on options. + */ +ssh.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge.md.md5.create(); - if (statusCodes[res.statusCode] !== true) { - getCause(isStream, res, json, function (err, cause) { - var msg = new Error( - '(HTTP code ' + res.statusCode + ') ' + - (statusCodes[res.statusCode] || 'unexpected') + ' - ' + - (cause.message || cause) + ' ' - ); - msg.reason = statusCodes[res.statusCode]; - msg.statusCode = res.statusCode; - msg.json = json; - cb(msg, null); - }); - } else { - if (openStdin) { - cb(null, new HttpDuplex(req, res)); - } else if (isStream) { - cb(null, res); - } else { - cb(null, json); - } - } + var type = 'ssh-rsa'; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); - function getCause(isStream, res, json, callback) { - var chunks = ''; - if (isStream) { - res.on('data', function (chunk) { - chunks += chunk; - }); - res.on('end', function () { - callback(null, utils.parseJSON(chunks) || chunks); - }); - } else { - callback(null, json); + // hash public key bytes + md.start(); + md.update(buffer.getBytes()); + var digest = md.digest(); + if(options.encoding === 'hex') { + var hex = digest.toHex(); + if(options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); } + return hex; + } else if(options.encoding === 'binary') { + return digest.getBytes(); + } else if(options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); } + return digest; }; -Modem.prototype.demuxStream = function (stream, stdout, stderr) { - var nextDataType = null; - var nextDataLength = null; - var buffer = Buffer.from(''); - function processData(data) { - if (data) { - buffer = Buffer.concat([buffer, data]); - } - if (!nextDataType) { - if (buffer.length >= 8) { - var header = bufferSlice(8); - nextDataType = header.readUInt8(0); - nextDataLength = header.readUInt32BE(4); - // It's possible we got a "data" that contains multiple messages - // Process the next one - processData(); - } - } else { - if (buffer.length >= nextDataLength) { - var content = bufferSlice(nextDataLength); - if (nextDataType === 1) { - stdout.write(content); - } else { - stderr.write(content); - } - nextDataType = null; - // It's possible we got a "data" that contains multiple messages - // Process the next one - processData(); - } - } +/** + * Adds len(val) then val to a buffer. + * + * @param buffer the buffer to add to. + * @param val a big integer. + */ +function _addBigIntegerToBuffer(buffer, val) { + var hexVal = val.toString(16); + // ensure 2s complement +ve + if(hexVal[0] >= '8') { + hexVal = '00' + hexVal; } + var bytes = forge.util.hexToBytes(hexVal); + buffer.putInt32(bytes.length); + buffer.putBytes(bytes); +} - function bufferSlice(end) { - var out = buffer.slice(0, end); - buffer = Buffer.from(buffer.slice(end, buffer.length)); - return out; +/** + * Adds len(val) then val to a buffer. + * + * @param buffer the buffer to add to. + * @param val a string. + */ +function _addStringToBuffer(buffer, val) { + buffer.putInt32(val.length); + buffer.putString(val); +} + +/** + * Hashes the arguments into one value using SHA-1. + * + * @return the sha1 hash of the provided arguments. + */ +function _sha1() { + var sha = forge.md.sha1.create(); + var num = arguments.length; + for (var i = 0; i < num; ++i) { + sha.update(arguments[i]); } + return sha.digest(); +} - stream.on('data', processData); -}; -Modem.prototype.followProgress = function (stream, onFinished, onProgress) { - var buf = ''; - var output = []; - var finished = false; +/***/ }), - stream.on('data', onStreamEvent); - stream.on('error', onStreamError); - stream.on('end', onStreamEnd); - stream.on('close', onStreamEnd); +/***/ 9167: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function onStreamEvent(data) { - buf += data.toString(); - pump(); +/** + * A Javascript implementation of Transport Layer Security (TLS). + * + * @author Dave Longley + * + * Copyright (c) 2009-2014 Digital Bazaar, Inc. + * + * The TLS Handshake Protocol involves the following steps: + * + * - Exchange hello messages to agree on algorithms, exchange random values, + * and check for session resumption. + * + * - Exchange the necessary cryptographic parameters to allow the client and + * server to agree on a premaster secret. + * + * - Exchange certificates and cryptographic information to allow the client + * and server to authenticate themselves. + * + * - Generate a master secret from the premaster secret and exchanged random + * values. + * + * - Provide security parameters to the record layer. + * + * - Allow the client and server to verify that their peer has calculated the + * same security parameters and that the handshake occurred without tampering + * by an attacker. + * + * Up to 4 different messages may be sent during a key exchange. The server + * certificate, the server key exchange, the client certificate, and the + * client key exchange. + * + * A typical handshake (from the client's perspective). + * + * 1. Client sends ClientHello. + * 2. Client receives ServerHello. + * 3. Client receives optional Certificate. + * 4. Client receives optional ServerKeyExchange. + * 5. Client receives ServerHelloDone. + * 6. Client sends optional Certificate. + * 7. Client sends ClientKeyExchange. + * 8. Client sends optional CertificateVerify. + * 9. Client sends ChangeCipherSpec. + * 10. Client sends Finished. + * 11. Client receives ChangeCipherSpec. + * 12. Client receives Finished. + * 13. Client sends/receives application data. + * + * To reuse an existing session: + * + * 1. Client sends ClientHello with session ID for reuse. + * 2. Client receives ServerHello with same session ID if reusing. + * 3. Client receives ChangeCipherSpec message if reusing. + * 4. Client receives Finished. + * 5. Client sends ChangeCipherSpec. + * 6. Client sends Finished. + * + * Note: Client ignores HelloRequest if in the middle of a handshake. + * + * Record Layer: + * + * The record layer fragments information blocks into TLSPlaintext records + * carrying data in chunks of 2^14 bytes or less. Client message boundaries are + * not preserved in the record layer (i.e., multiple client messages of the + * same ContentType MAY be coalesced into a single TLSPlaintext record, or a + * single message MAY be fragmented across several records). + * + * struct { + * uint8 major; + * uint8 minor; + * } ProtocolVersion; + * + * struct { + * ContentType type; + * ProtocolVersion version; + * uint16 length; + * opaque fragment[TLSPlaintext.length]; + * } TLSPlaintext; + * + * type: + * The higher-level protocol used to process the enclosed fragment. + * + * version: + * The version of the protocol being employed. TLS Version 1.2 uses version + * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that + * supports multiple versions of TLS may not know what version will be + * employed before it receives the ServerHello. + * + * length: + * The length (in bytes) of the following TLSPlaintext.fragment. The length + * MUST NOT exceed 2^14 = 16384 bytes. + * + * fragment: + * The application data. This data is transparent and treated as an + * independent block to be dealt with by the higher-level protocol specified + * by the type field. + * + * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or + * ChangeCipherSpec content types. Zero-length fragments of Application data + * MAY be sent as they are potentially useful as a traffic analysis + * countermeasure. + * + * Note: Data of different TLS record layer content types MAY be interleaved. + * Application data is generally of lower precedence for transmission than + * other content types. However, records MUST be delivered to the network in + * the same order as they are protected by the record layer. Recipients MUST + * receive and process interleaved application layer traffic during handshakes + * subsequent to the first one on a connection. + * + * struct { + * ContentType type; // same as TLSPlaintext.type + * ProtocolVersion version;// same as TLSPlaintext.version + * uint16 length; + * opaque fragment[TLSCompressed.length]; + * } TLSCompressed; + * + * length: + * The length (in bytes) of the following TLSCompressed.fragment. + * The length MUST NOT exceed 2^14 + 1024. + * + * fragment: + * The compressed form of TLSPlaintext.fragment. + * + * Note: A CompressionMethod.null operation is an identity operation; no fields + * are altered. In this implementation, since no compression is supported, + * uncompressed records are always the same as compressed records. + * + * Encryption Information: + * + * The encryption and MAC functions translate a TLSCompressed structure into a + * TLSCiphertext. The decryption functions reverse the process. The MAC of the + * record also includes a sequence number so that missing, extra, or repeated + * messages are detectable. + * + * struct { + * ContentType type; + * ProtocolVersion version; + * uint16 length; + * select (SecurityParameters.cipher_type) { + * case stream: GenericStreamCipher; + * case block: GenericBlockCipher; + * case aead: GenericAEADCipher; + * } fragment; + * } TLSCiphertext; + * + * type: + * The type field is identical to TLSCompressed.type. + * + * version: + * The version field is identical to TLSCompressed.version. + * + * length: + * The length (in bytes) of the following TLSCiphertext.fragment. + * The length MUST NOT exceed 2^14 + 2048. + * + * fragment: + * The encrypted form of TLSCompressed.fragment, with the MAC. + * + * Note: Only CBC Block Ciphers are supported by this implementation. + * + * The TLSCompressed.fragment structures are converted to/from block + * TLSCiphertext.fragment structures. + * + * struct { + * opaque IV[SecurityParameters.record_iv_length]; + * block-ciphered struct { + * opaque content[TLSCompressed.length]; + * opaque MAC[SecurityParameters.mac_length]; + * uint8 padding[GenericBlockCipher.padding_length]; + * uint8 padding_length; + * }; + * } GenericBlockCipher; + * + * The MAC is generated as described in Section 6.2.3.1. + * + * IV: + * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be + * unpredictable. Note that in versions of TLS prior to 1.1, there was no + * IV field, and the last ciphertext block of the previous record (the "CBC + * residue") was used as the IV. This was changed to prevent the attacks + * described in [CBCATT]. For block ciphers, the IV length is of length + * SecurityParameters.record_iv_length, which is equal to the + * SecurityParameters.block_size. + * + * padding: + * Padding that is added to force the length of the plaintext to be an + * integral multiple of the block cipher's block length. The padding MAY be + * any length up to 255 bytes, as long as it results in the + * TLSCiphertext.length being an integral multiple of the block length. + * Lengths longer than necessary might be desirable to frustrate attacks on + * a protocol that are based on analysis of the lengths of exchanged + * messages. Each uint8 in the padding data vector MUST be filled with the + * padding length value. The receiver MUST check this padding and MUST use + * the bad_record_mac alert to indicate padding errors. + * + * padding_length: + * The padding length MUST be such that the total size of the + * GenericBlockCipher structure is a multiple of the cipher's block length. + * Legal values range from zero to 255, inclusive. This length specifies the + * length of the padding field exclusive of the padding_length field itself. + * + * The encrypted data length (TLSCiphertext.length) is one more than the sum of + * SecurityParameters.block_length, TLSCompressed.length, + * SecurityParameters.mac_length, and padding_length. + * + * Example: If the block length is 8 bytes, the content length + * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the + * length before padding is 82 bytes (this does not include the IV. Thus, the + * padding length modulo 8 must be equal to 6 in order to make the total length + * an even multiple of 8 bytes (the block length). The padding length can be + * 6, 14, 22, and so on, through 254. If the padding length were the minimum + * necessary, 6, the padding would be 6 bytes, each containing the value 6. + * Thus, the last 8 octets of the GenericBlockCipher before block encryption + * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC. + * + * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical + * that the entire plaintext of the record be known before any ciphertext is + * transmitted. Otherwise, it is possible for the attacker to mount the attack + * described in [CBCATT]. + * + * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing + * attack on CBC padding based on the time required to compute the MAC. In + * order to defend against this attack, implementations MUST ensure that + * record processing time is essentially the same whether or not the padding + * is correct. In general, the best way to do this is to compute the MAC even + * if the padding is incorrect, and only then reject the packet. For instance, + * if the pad appears to be incorrect, the implementation might assume a + * zero-length pad and then compute the MAC. This leaves a small timing + * channel, since MAC performance depends, to some extent, on the size of the + * data fragment, but it is not believed to be large enough to be exploitable, + * due to the large block size of existing MACs and the small size of the + * timing signal. + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(9549); +__nccwpck_require__(5104); +__nccwpck_require__(6594); +__nccwpck_require__(154); +__nccwpck_require__(6924); +__nccwpck_require__(7821); +__nccwpck_require__(279); +__nccwpck_require__(8339); + +/** + * Generates pseudo random bytes by mixing the result of two hash functions, + * MD5 and SHA-1. + * + * prf_TLS1(secret, label, seed) = + * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed); + * + * Each P_hash function functions as follows: + * + * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + + * HMAC_hash(secret, A(2) + seed) + + * HMAC_hash(secret, A(3) + seed) + ... + * A() is defined as: + * A(0) = seed + * A(i) = HMAC_hash(secret, A(i-1)) + * + * The '+' operator denotes concatenation. + * + * As many iterations A(N) as are needed are performed to generate enough + * pseudo random byte output. If an iteration creates more data than is + * necessary, then it is truncated. + * + * Therefore: + * A(1) = HMAC_hash(secret, A(0)) + * = HMAC_hash(secret, seed) + * A(2) = HMAC_hash(secret, A(1)) + * = HMAC_hash(secret, HMAC_hash(secret, seed)) + * + * Therefore: + * P_hash(secret, seed) = + * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) + + * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) + + * ... + * + * Therefore: + * P_hash(secret, seed) = + * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) + + * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) + + * ... + * + * @param secret the secret to use. + * @param label the label to use. + * @param seed the seed value to use. + * @param length the number of bytes to generate. + * + * @return the pseudo random bytes in a byte buffer. + */ +var prf_TLS1 = function(secret, label, seed, length) { + var rval = forge.util.createBuffer(); + + /* For TLS 1.0, the secret is split in half, into two secrets of equal + length. If the secret has an odd length then the last byte of the first + half will be the same as the first byte of the second. The length of the + two secrets is half of the secret rounded up. */ + var idx = (secret.length >> 1); + var slen = idx + (secret.length & 1); + var s1 = secret.substr(0, slen); + var s2 = secret.substr(idx, slen); + var ai = forge.util.createBuffer(); + var hmac = forge.hmac.create(); + seed = label + seed; - function pump() { - var pos; - while ((pos = buf.indexOf('\n')) >= 0) { - if (pos == 0) { - buf = buf.slice(1); - continue; - } - processLine(buf.slice(0, pos)); - buf = buf.slice(pos + 1); - } - } + // determine the number of iterations that must be performed to generate + // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20 + var md5itr = Math.ceil(length / 16); + var sha1itr = Math.ceil(length / 20); - function processLine(line) { - if (line[line.length - 1] == '\r') line = line.substr(0, line.length - 1); - if (line.length > 0) { - var obj = JSON.parse(line); - output.push(obj); - if (onProgress) { - onProgress(obj); - } - } - } - }; + // do md5 iterations + hmac.start('MD5', s1); + var md5bytes = forge.util.createBuffer(); + ai.putBytes(seed); + for(var i = 0; i < md5itr; ++i) { + // HMAC_hash(secret, A(i-1)) + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); - function onStreamError(err) { - finished = true; - stream.removeListener('data', onStreamEvent); - stream.removeListener('error', onStreamError); - stream.removeListener('end', onStreamEnd); - stream.removeListener('close', onStreamEnd); - onFinished(err, output); + // HMAC_hash(secret, A(i) + seed) + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + md5bytes.putBuffer(hmac.digest()); } - function onStreamEnd() { - if(!finished) onFinished(null, output); - finished = true; - } -}; + // do sha1 iterations + hmac.start('SHA1', s2); + var sha1bytes = forge.util.createBuffer(); + ai.clear(); + ai.putBytes(seed); + for(var i = 0; i < sha1itr; ++i) { + // HMAC_hash(secret, A(i-1)) + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); -Modem.prototype.buildQuerystring = function (opts) { - var clone = {}; + // HMAC_hash(secret, A(i) + seed) + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + sha1bytes.putBuffer(hmac.digest()); + } - // serialize map values as JSON strings, else querystring truncates. - Object.keys(opts).map(function (key, i) { - if (opts[key] - && typeof opts[key] === 'object' - && !Array.isArray(opts[key]) - // Ref: https://docs.docker.com/engine/api/v1.40/#operation/ImageBuild - // > cachefrom (string) JSON array of images used for build cache resolution. - || key === 'cachefrom' - ) { - clone[key] = JSON.stringify(opts[key]); - } else { - clone[key] = opts[key]; - } - }); + // XOR the md5 bytes with the sha1 bytes + rval.putBytes(forge.util.xorBytes( + md5bytes.getBytes(), sha1bytes.getBytes(), length)); - return querystring.stringify(clone); + return rval; }; -module.exports = Modem; - - -/***/ }), - -/***/ 7964: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Client = (__nccwpck_require__(5869).Client), - http = __nccwpck_require__(3685); - -module.exports = function(opt) { - var conn = new Client(); - var agent = new http.Agent(); - - agent.createConnection = function(options, fn) { - conn.once('ready', function() { - conn.exec('docker system dial-stdio', function(err, stream) { - if (err) { - conn.end(); - agent.destroy(); - return; - } - - fn(null, stream); - - stream.once('close', () => { - conn.end(); - agent.destroy(); - }); - }); - }).connect(opt); - - conn.once('end', () => agent.destroy()); - }; - - return agent; +/** + * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2. + * + * @param secret the secret to use. + * @param label the label to use. + * @param seed the seed value to use. + * @param length the number of bytes to generate. + * + * @return the pseudo random bytes in a byte buffer. + */ +var prf_sha256 = function(secret, label, seed, length) { + // FIXME: implement me for TLS 1.2 }; +/** + * Gets a MAC for a record using the SHA-1 hash algorithm. + * + * @param key the mac key. + * @param state the sequence number (array of two 32-bit integers). + * @param record the record. + * + * @return the sha-1 hash (20 bytes) for the given record. + */ +var hmac_sha1 = function(key, seqNum, record) { + /* MAC is computed like so: + HMAC_hash( + key, seqNum + + TLSCompressed.type + + TLSCompressed.version + + TLSCompressed.length + + TLSCompressed.fragment) + */ + var hmac = forge.hmac.create(); + hmac.start('SHA1', key); + var b = forge.util.createBuffer(); + b.putInt32(seqNum[0]); + b.putInt32(seqNum[1]); + b.putByte(record.type); + b.putByte(record.version.major); + b.putByte(record.version.minor); + b.putInt16(record.length); + b.putBytes(record.fragment.bytes()); + hmac.update(b.getBytes()); + return hmac.digest().getBytes(); +}; -/***/ }), - -/***/ 4967: -/***/ ((module) => { - -// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js +/** + * Compresses the TLSPlaintext record into a TLSCompressed record using the + * deflate algorithm. + * + * @param c the TLS connection. + * @param record the TLSPlaintext record to compress. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +var deflate = function(c, record, s) { + var rval = false; -var arr = []; -var each = arr.forEach; -var slice = arr.slice; + try { + var bytes = c.deflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch(ex) { + // deflate error, fail out + } -module.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; + return rval; }; -module.exports.parseJSON = function(s) { +/** + * Decompresses the TLSCompressed record into a TLSPlaintext record using the + * deflate algorithm. + * + * @param c the TLS connection. + * @param record the TLSCompressed record to decompress. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +var inflate = function(c, record, s) { + var rval = false; + try { - return JSON.parse(s); - } catch (e) { - return null; + var bytes = c.inflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch(ex) { + // inflate error, fail out } + + return rval; }; +/** + * Reads a TLS variable-length vector from a byte buffer. + * + * Variable-length vectors are defined by specifying a subrange of legal + * lengths, inclusively, using the notation . When these are + * encoded, the actual length precedes the vector's contents in the byte + * stream. The length will be in the form of a number consuming as many bytes + * as required to hold the vector's specified maximum (ceiling) length. A + * variable-length vector with an actual length field of zero is referred to + * as an empty vector. + * + * @param b the byte buffer. + * @param lenBytes the number of bytes required to store the length. + * + * @return the resulting byte buffer. + */ +var readVector = function(b, lenBytes) { + var len = 0; + switch(lenBytes) { + case 1: + len = b.getByte(); + break; + case 2: + len = b.getInt16(); + break; + case 3: + len = b.getInt24(); + break; + case 4: + len = b.getInt32(); + break; + } -/***/ }), + // read vector bytes into a new buffer + return forge.util.createBuffer(b.getBytes(len)); +}; -/***/ 5004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Writes a TLS variable-length vector to a byte buffer. + * + * @param b the byte buffer. + * @param lenBytes the number of bytes required to store the length. + * @param v the byte buffer vector. + */ +var writeVector = function(b, lenBytes, v) { + // encode length at the start of the vector, where the number of bytes for + // the length is the maximum number of bytes it would take to encode the + // vector's ceiling + b.putInt(v.length(), lenBytes << 3); + b.putBuffer(v); +}; -var util = __nccwpck_require__(1604); +/** + * The tls implementation. + */ +var tls = {}; /** - * Represents a config - * @param {Object} modem docker-modem - * @param {String} id Config's id + * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and + * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time + * of this implementation so TLS 1.0 was implemented instead. */ -var Config = function(modem, id) { - this.modem = modem; - this.id = id; +tls.Versions = { + TLS_1_0: {major: 3, minor: 1}, + TLS_1_1: {major: 3, minor: 2}, + TLS_1_2: {major: 3, minor: 3} }; - -Config.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; +tls.SupportedVersions = [ + tls.Versions.TLS_1_1, + tls.Versions.TLS_1_0 +]; +tls.Version = tls.SupportedVersions[0]; /** - * Inspect - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. + * Maximum fragment size. True maximum is 16384, but we fragment before that + * to allow for unusual small increases during compression. */ -Config.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.MaxFragment = 16384 - 1024; - var optsf = { - path: '/configs/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - } - }; +/** + * Whether this entity is considered the "client" or "server". + * enum { server, client } ConnectionEnd; + */ +tls.ConnectionEnd = { + server: 0, + client: 1 +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +/** + * Pseudo-random function algorithm used to generate keys from the master + * secret. + * enum { tls_prf_sha256 } PRFAlgorithm; + */ +tls.PRFAlgorithm = { + tls_prf_sha256: 0 }; /** - * Update a config. - * - * @param {object} opts - * @param {function} callback + * Bulk encryption algorithms. + * enum { null, rc4, des3, aes } BulkCipherAlgorithm; */ -Config.prototype.update = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.BulkCipherAlgorithm = { + none: null, + rc4: 0, + des3: 1, + aes: 2 +}; - var optsf = { - path: '/configs/' + this.id + '/update?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; +/** + * Cipher types. + * enum { stream, block, aead } CipherType; + */ +tls.CipherType = { + stream: 0, + block: 1, + aead: 2 +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +/** + * MAC (Message Authentication Code) algorithms. + * enum { null, hmac_md5, hmac_sha1, hmac_sha256, + * hmac_sha384, hmac_sha512} MACAlgorithm; + */ +tls.MACAlgorithm = { + none: null, + hmac_md5: 0, + hmac_sha1: 1, + hmac_sha256: 2, + hmac_sha384: 3, + hmac_sha512: 4 }; +/** + * Compression algorithms. + * enum { null(0), deflate(1), (255) } CompressionMethod; + */ +tls.CompressionMethod = { + none: 0, + deflate: 1 +}; /** - * Removes the config - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback + * TLS record content types. + * enum { + * change_cipher_spec(20), alert(21), handshake(22), + * application_data(23), (255) + * } ContentType; */ -Config.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.ContentType = { + change_cipher_spec: 20, + alert: 21, + handshake: 22, + application_data: 23, + heartbeat: 24 +}; - var optsf = { - path: '/configs/' + this.id, - method: 'DELETE', - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; +/** + * TLS handshake types. + * enum { + * hello_request(0), client_hello(1), server_hello(2), + * certificate(11), server_key_exchange (12), + * certificate_request(13), server_hello_done(14), + * certificate_verify(15), client_key_exchange(16), + * finished(20), (255) + * } HandshakeType; + */ +tls.HandshakeType = { + hello_request: 0, + client_hello: 1, + server_hello: 2, + certificate: 11, + server_key_exchange: 12, + certificate_request: 13, + server_hello_done: 14, + certificate_verify: 15, + client_key_exchange: 16, + finished: 20 +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +/** + * TLS Alert Protocol. + * + * enum { warning(1), fatal(2), (255) } AlertLevel; + * + * enum { + * close_notify(0), + * unexpected_message(10), + * bad_record_mac(20), + * decryption_failed(21), + * record_overflow(22), + * decompression_failure(30), + * handshake_failure(40), + * bad_certificate(42), + * unsupported_certificate(43), + * certificate_revoked(44), + * certificate_expired(45), + * certificate_unknown(46), + * illegal_parameter(47), + * unknown_ca(48), + * access_denied(49), + * decode_error(50), + * decrypt_error(51), + * export_restriction(60), + * protocol_version(70), + * insufficient_security(71), + * internal_error(80), + * user_canceled(90), + * no_renegotiation(100), + * (255) + * } AlertDescription; + * + * struct { + * AlertLevel level; + * AlertDescription description; + * } Alert; + */ +tls.Alert = {}; +tls.Alert.Level = { + warning: 1, + fatal: 2 +}; +tls.Alert.Description = { + close_notify: 0, + unexpected_message: 10, + bad_record_mac: 20, + decryption_failed: 21, + record_overflow: 22, + decompression_failure: 30, + handshake_failure: 40, + bad_certificate: 42, + unsupported_certificate: 43, + certificate_revoked: 44, + certificate_expired: 45, + certificate_unknown: 46, + illegal_parameter: 47, + unknown_ca: 48, + access_denied: 49, + decode_error: 50, + decrypt_error: 51, + export_restriction: 60, + protocol_version: 70, + insufficient_security: 71, + internal_error: 80, + user_canceled: 90, + no_renegotiation: 100 }; - - - -module.exports = Config; - - -/***/ }), - -/***/ 5815: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var extend = (__nccwpck_require__(1604).extend), - Exec = __nccwpck_require__(3149), - util = __nccwpck_require__(1604); /** - * Represents a Container - * @param {Object} modem docker-modem - * @param {String} id Container's ID + * TLS Heartbeat Message types. + * enum { + * heartbeat_request(1), + * heartbeat_response(2), + * (255) + * } HeartbeatMessageType; */ -var Container = function(modem, id) { - this.modem = modem; - this.id = id; - - this.defaultOptions = { - top: {}, - start: {}, - commit: {}, - stop: {}, - pause: {}, - unpause: {}, - restart: {}, - resize: {}, - attach: {}, - remove: {}, - copy: {}, - kill: {}, - exec: {}, - rename: {}, - log: {}, - stats: {}, - getArchive: {}, - infoArchive: {}, - putArchive: {}, - update: {}, - wait: {} - }; +tls.HeartbeatMessageType = { + heartbeat_request: 1, + heartbeat_response: 2 }; -Container.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; - /** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if supplied will query Docker. - * @return {Object} ID only and only if callback isn't supplied. + * Supported cipher suites. */ -Container.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.CipherSuites = {}; - var optsf = { - path: '/containers/' + this.id + '/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' +/** + * Gets a supported cipher suite from its 2 byte ID. + * + * @param twoBytes two bytes in a string. + * + * @return the matching supported cipher suite or null. + */ +tls.getCipherSuite = function(twoBytes) { + var rval = null; + for(var key in tls.CipherSuites) { + var cs = tls.CipherSuites[key]; + if(cs.id[0] === twoBytes.charCodeAt(0) && + cs.id[1] === twoBytes.charCodeAt(1)) { + rval = cs; + break; } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); } + return rval; }; /** - * Rename - * @param {Object} opts Rename options - * @param {Function} callback Callback + * Called when an unexpected record is encountered. + * + * @param c the connection. + * @param record the record. */ -Container.prototype.rename = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.rename); - - var optsf = { - path: '/containers/' + this.id + '/rename?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); +tls.handleUnexpected = function(c, record) { + // if connection is client and closed, ignore unexpected messages + var ignore = (!c.open && c.entity === tls.ConnectionEnd.client); + if(!ignore) { + c.error(c, { + message: 'Unexpected message. Received TLS record out of order.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } }); } }; /** - * Update - * @param {Object} opts Update options - * @param {Function} callback Callback + * Called when a client receives a HelloRequest record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.update = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.update); - - var optsf = { - path: '/containers/' + this.id + '/update', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +tls.handleHelloRequest = function(c, record, length) { + // ignore renegotiation requests from the server during a handshake, but + // if handshaking, send a warning alert that renegotation is denied + if(!c.handshaking && c.handshakes > 0) { + // send alert warning + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.no_renegotiation + })); + tls.flush(c); } + + // continue + c.process(); }; /** - * Top - * @param {Object} opts like 'ps_args' (optional) - * @param {Function} callback Callback + * Parses a hello message from a ClientHello or ServerHello record. + * + * @param record the record to parse. + * + * @return the parsed message. */ -Container.prototype.top = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.top); +tls.parseHelloMessage = function(c, record, length) { + var msg = null; - var optsf = { - path: '/containers/' + this.id + '/top?', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + var client = (c.entity === tls.ConnectionEnd.client); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); + // minimum of 38 bytes in message + if(length < 38) { + c.error(c, { + message: client ? + 'Invalid ServerHello message. Message too short.' : + 'Invalid ClientHello message. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } }); } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + // use 'remaining' to calculate # of remaining bytes in the message + var b = record.fragment; + var remaining = b.length(); + msg = { + version: { + major: b.getByte(), + minor: b.getByte() + }, + random: forge.util.createBuffer(b.getBytes(32)), + session_id: readVector(b, 1), + extensions: [] + }; + if(client) { + msg.cipher_suite = b.getBytes(2); + msg.compression_method = b.getByte(); + } else { + msg.cipher_suites = readVector(b, 2); + msg.compression_methods = readVector(b, 1); + } -/** - * Containers changes - * @param {Object} Options - * @param {Function} callback Callback - */ -Container.prototype.changes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // read extensions if there are any bytes left in the message + remaining = length - (remaining - b.length()); + if(remaining > 0) { + // parse extensions + var exts = readVector(b, 2); + while(exts.length() > 0) { + msg.extensions.push({ + type: [exts.getByte(), exts.getByte()], + data: readVector(exts, 2) + }); + } - var optsf = { - path: '/containers/' + this.id + '/changes', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' + // TODO: make extension support modular + if(!client) { + for(var i = 0; i < msg.extensions.length; ++i) { + var ext = msg.extensions[i]; + + // support SNI extension + if(ext.type[0] === 0x00 && ext.type[1] === 0x00) { + // get server name list + var snl = readVector(ext.data, 2); + while(snl.length() > 0) { + // read server name type + var snType = snl.getByte(); + + // only HostName type (0x00) is known, break out if + // another type is detected + if(snType !== 0x00) { + break; + } + + // add host name to server name list + c.session.extensions.server_name.serverNameList.push( + readVector(snl, 2).getBytes()); + } + } + } + } } - }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + // version already set, do not allow version change + if(c.session.version) { + if(msg.version.major !== c.session.version.major || + msg.version.minor !== c.session.version.minor) { + return c.error(c, { + message: 'TLS version change is disallowed during renegotiation.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + + // get the chosen (ServerHello) cipher suite + if(client) { + // FIXME: should be checking configured acceptable cipher suites + c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); + } else { + // get a supported preferred (ClientHello) cipher suite + // choose the first supported cipher suite + var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); + while(tmp.length() > 0) { + // FIXME: should be checking configured acceptable suites + // cipher suites take up 2 bytes + c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); + if(c.session.cipherSuite !== null) { + break; } - resolve(data); + } + } + + // cipher suite not supported + if(c.session.cipherSuite === null) { + return c.error(c, { + message: 'No cipher suites in common.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + }, + cipherSuite: forge.util.bytesToHex(msg.cipher_suite) }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + } + + // TODO: handle compression methods + if(client) { + c.session.compressionMethod = msg.compression_method; + } else { + // no compression + c.session.compressionMethod = tls.CompressionMethod.none; + } } + + return msg; }; /** - * Checkpoints list - * @param {Object} opts List checkpoints options (optional) - * @param {Function} callback Callback + * Creates security parameters for the given connection based on the given + * hello message. + * + * @param c the TLS connection. + * @param msg the hello message. */ -Container.prototype.listCheckpoint = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.createSecurityParameters = function(c, msg) { + /* Note: security params are from TLS 1.2, some values like prf_algorithm + are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is + used. */ - var optsf = { - path: '/containers/' + this.id + '/checkpoints?', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts + // TODO: handle other options from server when more supported + + // get client and server randoms + var client = (c.entity === tls.ConnectionEnd.client); + var msgRandom = msg.random.bytes(); + var cRandom = client ? c.session.sp.client_random : msgRandom; + var sRandom = client ? msgRandom : tls.createRandom().getBytes(); + + // create new security parameters + c.session.sp = { + entity: c.entity, + prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, + bulk_cipher_algorithm: null, + cipher_type: null, + enc_key_length: null, + block_length: null, + fixed_iv_length: null, + record_iv_length: null, + mac_algorithm: null, + mac_length: null, + mac_key_length: null, + compression_algorithm: c.session.compressionMethod, + pre_master_secret: null, + master_secret: null, + client_random: cRandom, + server_random: sRandom }; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); +/** + * Called when a client receives a ServerHello record. + * + * When a ServerHello message will be sent: + * The server will send this message in response to a client hello message + * when it was able to find an acceptable set of algorithms. If it cannot + * find such a match, it will respond with a handshake failure alert. + * + * uint24 length; + * struct { + * ProtocolVersion server_version; + * Random random; + * SessionID session_id; + * CipherSuite cipher_suite; + * CompressionMethod compression_method; + * select(extensions_present) { + * case false: + * struct {}; + * case true: + * Extension extensions<0..2^16-1>; + * }; + * } ServerHello; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleServerHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if(c.fail) { + return; + } + + // ensure server version is compatible + if(msg.version.minor <= c.version.minor) { + c.version.minor = msg.version.minor; } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); + return c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } }); } -}; + // indicate session version has been set + c.session.version = c.version; -/** - * Delete checkpoint - * @param {Object} opts Delete checkpoint options (optional) - * @param {Function} callback Callback - */ -Container.prototype.deleteCheckpoint = function(checkpoint, opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // get the session ID from the message + var sessionId = msg.session_id.bytes(); - var optsf = { - path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // if the session ID is not blank and matches the cached one, resume + // the session + if(sessionId.length > 0 && sessionId === c.session.id) { + // resuming session, expect a ChangeCipherSpec next + c.expect = SCC; + c.session.resuming = true; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); + // get new server random + c.session.sp.server_random = msg.random.bytes(); } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // not resuming, expect a server Certificate message next + c.expect = SCE; + c.session.resuming = false; + + // create new security parameters + tls.createSecurityParameters(c, msg); } + + // set new session ID + c.session.id = sessionId; + + // continue + c.process(); }; /** - * Create checkpoint - * @param {Object} opts Create checkpoint options (optional) - * @param {Function} callback Callback + * Called when a server receives a ClientHello record. + * + * When a ClientHello message will be sent: + * When a client first connects to a server it is required to send the + * client hello as its first message. The client can also send a client + * hello in response to a hello request or on its own initiative in order + * to renegotiate the security parameters in an existing connection. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.createCheckpoint = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.handleClientHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if(c.fail) { + return; + } - var optsf = { - path: '/containers/' + this.id + '/checkpoints', - method: 'POST', - abortSignal: args.opts.abortSignal, - allowEmpty: true, - statusCodes: { - 200: true, //unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // get the session ID from the message + var sessionId = msg.session_id.bytes(); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // see if the given session ID is in the cache + var session = null; + if(c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + if(session === null) { + // session ID not found + sessionId = ''; + } else if(session.version.major !== msg.version.major || + session.version.minor > msg.version.minor) { + // if session version is incompatible with client version, do not resume + session = null; + sessionId = ''; + } } -}; + // no session found to resume, generate a new session ID + if(sessionId.length === 0) { + sessionId = forge.random.getBytes(32); + } -/** - * Export - * @param {Object} opts Options (optional) - * @param {Function} callback Callback with the octet-stream. - */ -Container.prototype.export = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/export', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' + // update session + c.session.id = sessionId; + c.session.clientHelloVersion = msg.version; + c.session.sp = {}; + if(session) { + // use version and security parameters from resumed session + c.version = c.session.version = session.version; + c.session.sp = session.sp; + } else { + // use highest compatible minor version + var version; + for(var i = 1; i < tls.SupportedVersions.length; ++i) { + version = tls.SupportedVersions[i]; + if(version.minor <= msg.version.minor) { + break; + } } - }; + c.version = {major: version.major, minor: version.minor}; + c.session.version = c.version; + } - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); + // if a session is set, resume it + if(session !== null) { + // resuming session, expect a ChangeCipherSpec next + c.expect = CCC; + c.session.resuming = true; + + // get new client random + c.session.sp.client_random = msg.random.bytes(); } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // not resuming, expect a Certificate or ClientKeyExchange + c.expect = (c.verifyClient !== false) ? CCE : CKE; + c.session.resuming = false; + + // create new security parameters + tls.createSecurityParameters(c, msg); } -}; -/** - * Start - * @param {Object} opts Container start options (optional) - * @param {Function} callback Callback - */ -Container.prototype.start = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.start); + // connection now open + c.open = true; - var optsf = { - path: '/containers/' + this.id + '/start?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 304: 'container already started', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // queue server hello + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHello(c) + })); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); + if(c.session.resuming) { + // queue change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + + // create pending state + c.state.pending = tls.createConnectionState(c); + + // change current write state to pending write state + c.state.current.write = c.state.pending.write; + + // queue finished + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // queue server certificate + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + })); + + if(!c.fail) { + // queue server key exchange + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerKeyExchange(c) + })); + + // request client certificate if set + if(c.verifyClient !== false) { + // queue certificate request + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateRequest(c) + })); + } + + // queue server hello done + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHelloDone(c) + })); + } } + + // send records + tls.flush(c); + + // continue + c.process(); }; /** - * Pause - * @param {Object} opts Pause options (optional) - * @param {Function} callback Callback + * Called when a client receives a Certificate record. + * + * When this message will be sent: + * The server must send a certificate whenever the agreed-upon key exchange + * method is not an anonymous one. This message will always immediately + * follow the server hello message. + * + * Meaning of this message: + * The certificate type must be appropriate for the selected cipher suite's + * key exchange algorithm, and is generally an X.509v3 certificate. It must + * contain a key which matches the key exchange method, as follows. Unless + * otherwise specified, the signing algorithm for the certificate must be + * the same as the algorithm for the certificate key. Unless otherwise + * specified, the public key may be of any length. + * + * opaque ASN.1Cert<1..2^24-1>; + * struct { + * ASN.1Cert certificate_list<1..2^24-1>; + * } Certificate; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.pause = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.pause); +tls.handleCertificate = function(c, record, length) { + // minimum of 3 bytes in message + if(length < 3) { + return c.error(c, { + message: 'Invalid Certificate message. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } - var optsf = { - path: '/containers/' + this.id + '/pause', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - }, - options: args.opts + var b = record.fragment; + var msg = { + certificate_list: readVector(b, 3) }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); + /* The sender's certificate will be first in the list (chain), each + subsequent one that follows will certify the previous one, but root + certificates (self-signed) that specify the certificate authority may + be omitted under the assumption that clients must already possess it. */ + var cert, asn1; + var certs = []; + try { + while(msg.certificate_list.length() > 0) { + // each entry in msg.certificate_list is a vector with 3 len bytes + cert = readVector(msg.certificate_list, 3); + asn1 = forge.asn1.fromDer(cert); + cert = forge.pki.certificateFromAsn1(asn1, true); + certs.push(cert); + } + } catch(ex) { + return c.error(c, { + message: 'Could not parse certificate list.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); + } + + // ensure at least 1 certificate was provided if in client-mode + // or if verifyClient was set to true to require a certificate + // (as opposed to 'optional') + var client = (c.entity === tls.ConnectionEnd.client); + if((client || c.verifyClient === true) && certs.length === 0) { + // error, no certificate + c.error(c, { + message: client ? + 'No server certificate provided.' : + 'No client certificate provided.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } }); + } else if(certs.length === 0) { + // no certs to verify + // expect a ServerKeyExchange or ClientKeyExchange message next + c.expect = client ? SKE : CKE; + } else { + // save certificate in session + if(client) { + c.session.serverCertificate = certs[0]; + } else { + c.session.clientCertificate = certs[0]; + } + + if(tls.verifyCertificateChain(c, certs)) { + // expect a ServerKeyExchange or ClientKeyExchange message next + c.expect = client ? SKE : CKE; + } } + + // continue + c.process(); }; /** - * Unpause - * @param {Object} opts Unpause options (optional) - * @param {Function} callback Callback + * Called when a client receives a ServerKeyExchange record. + * + * When this message will be sent: + * This message will be sent immediately after the server certificate + * message (or the server hello message, if this is an anonymous + * negotiation). + * + * The server key exchange message is sent by the server only when the + * server certificate message (if sent) does not contain enough data to + * allow the client to exchange a premaster secret. + * + * Meaning of this message: + * This message conveys cryptographic information to allow the client to + * communicate the premaster secret: either an RSA public key to encrypt + * the premaster secret with, or a Diffie-Hellman public key with which the + * client can complete a key exchange (with the result being the premaster + * secret.) + * + * enum { + * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa + * } KeyExchangeAlgorithm; + * + * struct { + * opaque dh_p<1..2^16-1>; + * opaque dh_g<1..2^16-1>; + * opaque dh_Ys<1..2^16-1>; + * } ServerDHParams; + * + * struct { + * select(KeyExchangeAlgorithm) { + * case dh_anon: + * ServerDHParams params; + * case dhe_dss: + * case dhe_rsa: + * ServerDHParams params; + * digitally-signed struct { + * opaque client_random[32]; + * opaque server_random[32]; + * ServerDHParams params; + * } signed_params; + * case rsa: + * case dh_dss: + * case dh_rsa: + * struct {}; + * }; + * } ServerKeyExchange; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.unpause = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.unpause); - - var optsf = { - path: '/containers/' + this.id + '/unpause', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); +tls.handleServerKeyExchange = function(c, record, length) { + // this implementation only supports RSA, no Diffie-Hellman support + // so any length > 0 is invalid + if(length > 0) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } }); } + + // expect an optional CertificateRequest message next + c.expect = SCR; + + // continue + c.process(); }; /** - * Setup an exec call to a running container + * Called when a client receives a ClientKeyExchange record. * - * @param {object} opts - * @param {function} callback + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.exec = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.exec); +tls.handleClientKeyExchange = function(c, record, length) { + // this implementation only supports RSA, no Diffie-Hellman support + // so any length < 48 is invalid + if(length < 48) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } - var optsf = { - path: '/containers/' + this.id + '/exec', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 409: 'container stopped/paused', - 500: 'server error' - }, - options: args.opts + var b = record.fragment; + var msg = { + enc_pre_master_secret: readVector(b, 2).getBytes() }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + // do rsa decryption + var privateKey = null; + if(c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.serverCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch(ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error } - resolve(new Exec(self.modem, data.Id)); }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, new Exec(self.modem, data.Id)); - }); + } } -}; -/** - * Commit - * @param {Object} opts Commit options like 'Hostname' (optional) - * @param {Function} callback Callback - */ -Container.prototype.commit = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.commit); + if(privateKey === null) { + return c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } - args.opts.container = this.id; + try { + // decrypt 48-byte pre-master secret + var sp = c.session.sp; + sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); - var optsf = { - path: '/commit?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // ensure client hello version matches first 2 bytes + var version = c.session.clientHelloVersion; + if(version.major !== sp.pre_master_secret.charCodeAt(0) || + version.minor !== sp.pre_master_secret.charCodeAt(1)) { + // error, do not send alert (see BLEI attack below) + throw new Error('TLS version rollback attack detected.'); + } + } catch(ex) { + /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a + TLS server which is using PKCS#1 encoded RSA, so instead of + failing here, we generate 48 random bytes and use that as + the pre-master secret. */ + sp.pre_master_secret = forge.random.getBytes(48); + } - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // expect a CertificateVerify message if a Certificate was received that + // does not have fixed Diffie-Hellman params, otherwise expect + // ChangeCipherSpec + c.expect = CCC; + if(c.session.clientCertificate !== null) { + // only RSA support, so expect CertificateVerify + // TODO: support Diffie-Hellman + c.expect = CCV; } + + // continue + c.process(); }; /** - * Stop - * @param {Object} opts Container stop options, like 't' (optional) - * @param {Function} callback Callback + * Called when a client receives a CertificateRequest record. + * + * When this message will be sent: + * A non-anonymous server can optionally request a certificate from the + * client, if appropriate for the selected cipher suite. This message, if + * sent, will immediately follow the Server Key Exchange message (if it is + * sent; otherwise, the Server Certificate message). + * + * enum { + * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4), + * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6), + * fortezza_dms_RESERVED(20), (255) + * } ClientCertificateType; + * + * opaque DistinguishedName<1..2^16-1>; + * + * struct { + * ClientCertificateType certificate_types<1..2^8-1>; + * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>; + * DistinguishedName certificate_authorities<0..2^16-1>; + * } CertificateRequest; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.stop = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stop); +tls.handleCertificateRequest = function(c, record, length) { + // minimum of 3 bytes in message + if(length < 3) { + return c.error(c, { + message: 'Invalid CertificateRequest. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } - var optsf = { - path: '/containers/' + this.id + '/stop?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 304: 'container already stopped', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts + // TODO: TLS 1.2+ has different format including + // SignatureAndHashAlgorithm after cert types + var b = record.fragment; + var msg = { + certificate_types: readVector(b, 1), + certificate_authorities: readVector(b, 2) }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + // save certificate request in session + c.session.certificateRequest = msg; + + // expect a ServerHelloDone message next + c.expect = SHD; + + // continue + c.process(); }; /** - * Restart - * @param {Object} opts Container restart options, like 't' (optional) - * @param {Function} callback Callback + * Called when a server receives a CertificateVerify record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.restart = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.restart); - - var optsf = { - path: '/containers/' + this.id + '/restart?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); +tls.handleCertificateVerify = function(c, record, length) { + if(length < 2) { + return c.error(c, { + message: 'Invalid CertificateVerify. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } }); } -}; -/** - * Kill - * @param {Object} opts Container kill options, like 'signal' (optional) - * @param {Function} callback Callback - */ -Container.prototype.kill = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.kill); + // rewind to get full bytes for message so it can be manually + // digested below (special case for CertificateVerify messages because + // they must be digested *after* handling as opposed to all others) + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; - var optsf = { - path: '/containers/' + this.id + '/kill?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts + var msg = { + signature: readVector(b, 2).getBytes() }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + // TODO: add support for DSA -/** - * Container resize - * @param {[type]} opts Resize options. (optional) - * @param {Function} callback Callback - */ -Container.prototype.resize = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.resize); + // generate data to verify + var verify = forge.util.createBuffer(); + verify.putBuffer(c.session.md5.digest()); + verify.putBuffer(c.session.sha1.digest()); + verify = verify.getBytes(); - var optsf = { - path: '/containers/' + this.id + '/resize?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + try { + var cert = c.session.clientCertificate; + /*b = forge.pki.rsa.decrypt( + msg.signature, cert.publicKey, true, verify.length); + if(b !== verify) {*/ + if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) { + throw new Error('CertificateVerify signature does not match.'); + } - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); + // digest message now that it has been handled + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + } catch(ex) { + return c.error(c, { + message: 'Bad signature in CertificateVerify.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + } }); } + + // expect ChangeCipherSpec + c.expect = CCC; + + // continue + c.process(); }; /** - * Attach - * @param {Object} opts Attach options, like 'logs' (optional) - * @param {Function} callback Callback with stream. + * Called when a client receives a ServerHelloDone record. + * + * When this message will be sent: + * The server hello done message is sent by the server to indicate the end + * of the server hello and associated messages. After sending this message + * the server will wait for a client response. + * + * Meaning of this message: + * This message means that the server is done sending messages to support + * the key exchange, and the client can proceed with its phase of the key + * exchange. + * + * Upon receipt of the server hello done message the client should verify + * that the server provided a valid certificate if required and check that + * the server hello parameters are acceptable. + * + * struct {} ServerHelloDone; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.attach = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.attach); +tls.handleServerHelloDone = function(c, record, length) { + // len must be 0 bytes + if(length > 0) { + return c.error(c, { + message: 'Invalid ServerHelloDone message. Invalid length.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.record_overflow + } + }); + } - var optsf = { - path: '/containers/' + this.id + '/attach?', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + if(c.serverCertificate === null) { + // no server certificate was provided + var error = { + message: 'No server certificate provided. Not enough security.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.insufficient_security + } + }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, stream) { - if (err) { - return reject(err); + // call application callback + var depth = 0; + var ret = c.verify(c, error.alert.description, depth, []); + if(ret !== true) { + // check for custom alert info + if(ret || ret === 0) { + // set custom message and alert description + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + if(ret.message) { + error.message = ret.message; + } + if(ret.alert) { + error.alert.description = ret.alert; + } + } else if(typeof ret === 'number') { + // set custom alert description + error.alert.description = ret; } - resolve(stream); - }); - }); - } else { - this.modem.dial(optsf, function(err, stream) { - args.callback(err, stream); + } + + // send error + return c.error(c, error); + } + } + + // create client certificate message if requested + if(c.session.certificateRequest !== null) { + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) }); + tls.queue(c, record); } -}; -/** - * Waits for a container to end. - * @param {[type]} opts Container wait options, like condition. (optional) - * @param {Function} callback Callback - */ -Container.prototype.wait = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.wait); + // create client key exchange message + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientKeyExchange(c) + }); + tls.queue(c, record); + + // expect no messages until the following callback has been called + c.expect = SER; + + // create callback to handle client signature (for client-certs) + var callback = function(c, signature) { + if(c.session.certificateRequest !== null && + c.session.clientCertificate !== null) { + // create certificate verify message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateVerify(c, signature) + })); + } + + // create change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + + // create pending state + c.state.pending = tls.createConnectionState(c); - var optsf = { - path: '/containers/' + this.id + '/wait?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // change current write state to pending write state + c.state.current.write = c.state.pending.write; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + // create finished message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); -/** - * Removes a container - * @param {Object} opts Remove options, like 'force' (optional) - * @param {Function} callback Callback - */ -Container.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.remove); + // expect a server ChangeCipherSpec message next + c.expect = SCC; - var optsf = { - path: '/containers/' + this.id + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts + // send records + tls.flush(c); + + // continue + c.process(); }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // if there is no certificate request or no client certificate, do + // callback immediately + if(c.session.certificateRequest === null || + c.session.clientCertificate === null) { + return callback(c, null); } + + // otherwise get the client signature + tls.getClientSignature(c, callback); }; /** - * Copy (WARNING: DEPRECATED since RAPI v1.20) - * @param {Object} opts Copy options, like 'Resource' (optional) - * @param {Function} callback Callback with stream. + * Called when a ChangeCipherSpec record is received. + * + * @param c the connection. + * @param record the record. */ -Container.prototype.copy = function(opts, callback) { - var self = this; - console.log('container.copy is deprecated since Docker v1.8.x'); - var args = util.processArgs(opts, callback, this.defaultOptions.copy); - - var optsf = { - path: '/containers/' + this.id + '/copy', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); +tls.handleChangeCipherSpec = function(c, record) { + if(record.fragment.getByte() !== 0x01) { + return c.error(c, { + message: 'Invalid ChangeCipherSpec message received.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } }); } -}; -/** - * getArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.getArchive = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.getArchive); + // create pending state if: + // 1. Resuming session in client mode OR + // 2. NOT resuming session in server mode + var client = (c.entity === tls.ConnectionEnd.client); + if((c.session.resuming && client) || (!c.session.resuming && !client)) { + c.state.pending = tls.createConnectionState(c); + } - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // change current read state to pending read state + c.state.current.read = c.state.pending.read; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // clear pending state if: + // 1. NOT resuming session in client mode OR + // 2. resuming a session in server mode + if((!c.session.resuming && client) || (c.session.resuming && !client)) { + c.state.pending = null; } + + // expect a Finished record next + c.expect = client ? SFI : CFI; + + // continue + c.process(); }; /** - * infoArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. + * Called when a Finished record is received. + * + * When this message will be sent: + * A finished message is always sent immediately after a change + * cipher spec message to verify that the key exchange and + * authentication processes were successful. It is essential that a + * change cipher spec message be received between the other + * handshake messages and the Finished message. + * + * Meaning of this message: + * The finished message is the first protected with the just- + * negotiated algorithms, keys, and secrets. Recipients of finished + * messages must verify that the contents are correct. Once a side + * has sent its Finished message and received and validated the + * Finished message from its peer, it may begin to send and receive + * application data over the connection. + * + * struct { + * opaque verify_data[verify_data_length]; + * } Finished; + * + * verify_data + * PRF(master_secret, finished_label, Hash(handshake_messages)) + * [0..verify_data_length-1]; + * + * finished_label + * For Finished messages sent by the client, the string + * "client finished". For Finished messages sent by the server, the + * string "server finished". + * + * verify_data_length depends on the cipher suite. If it is not specified + * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used + * 12 bytes. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. */ -Container.prototype.infoArchive = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive); +tls.handleFinished = function(c, record, length) { + // rewind to get full bytes for message so it can be manually + // digested below (special case for Finished messages because they + // must be digested *after* handling as opposed to all others) + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'HEAD', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // message contains only verify_data + var vd = record.fragment.getBytes(); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); + // ensure verify data is correct + b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + + // set label based on entity type + var client = (c.entity === tls.ConnectionEnd.client); + var label = client ? 'server finished' : 'client finished'; + + // TODO: determine prf function and verify length for TLS 1.2 + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + if(b.getBytes() !== vd) { + return c.error(c, { + message: 'Invalid verify_data in Finished message.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decrypt_error + } }); } -}; -/** - * putArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.putArchive = function(file, opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.putArchive); + // digest finished message now that it has been handled + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'PUT', - file: file, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 403: 'client error, permission denied', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // resuming session as client or NOT resuming session as server + if((c.session.resuming && client) || (!c.session.resuming && !client)) { + // create change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // change current write state to pending write state, clear pending + c.state.current.write = c.state.pending.write; + c.state.pending = null; + + // create finished message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); } -}; -/** - * Container logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Container.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); + // expect application data next + c.expect = client ? SAD : CAD; - var optsf = { - path: '/containers/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; + // handshake complete + c.handshaking = false; + ++c.handshakes; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + // save access to peer certificate + c.peerCertificate = client ? + c.session.serverCertificate : c.session.clientCertificate; + + // send records + tls.flush(c); + + // now connected + c.isConnected = true; + c.connected(c); + + // continue + c.process(); }; /** - * Container stats - * @param {Object} opts Stats options. (optional) - * @param {Function} callback Callback with data + * Called when an Alert record is received. + * + * @param c the connection. + * @param record the record. */ -Container.prototype.stats = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stats); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: '/containers/' + this.id + '/stats?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: isStream, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts +tls.handleAlert = function(c, record) { + // read alert + var b = record.fragment; + var alert = { + level: b.getByte(), + description: b.getByte() }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // TODO: consider using a table? + // get appropriate message + var msg; + switch(alert.description) { + case tls.Alert.Description.close_notify: + msg = 'Connection closed.'; + break; + case tls.Alert.Description.unexpected_message: + msg = 'Unexpected message.'; + break; + case tls.Alert.Description.bad_record_mac: + msg = 'Bad record MAC.'; + break; + case tls.Alert.Description.decryption_failed: + msg = 'Decryption failed.'; + break; + case tls.Alert.Description.record_overflow: + msg = 'Record overflow.'; + break; + case tls.Alert.Description.decompression_failure: + msg = 'Decompression failed.'; + break; + case tls.Alert.Description.handshake_failure: + msg = 'Handshake failure.'; + break; + case tls.Alert.Description.bad_certificate: + msg = 'Bad certificate.'; + break; + case tls.Alert.Description.unsupported_certificate: + msg = 'Unsupported certificate.'; + break; + case tls.Alert.Description.certificate_revoked: + msg = 'Certificate revoked.'; + break; + case tls.Alert.Description.certificate_expired: + msg = 'Certificate expired.'; + break; + case tls.Alert.Description.certificate_unknown: + msg = 'Certificate unknown.'; + break; + case tls.Alert.Description.illegal_parameter: + msg = 'Illegal parameter.'; + break; + case tls.Alert.Description.unknown_ca: + msg = 'Unknown certificate authority.'; + break; + case tls.Alert.Description.access_denied: + msg = 'Access denied.'; + break; + case tls.Alert.Description.decode_error: + msg = 'Decode error.'; + break; + case tls.Alert.Description.decrypt_error: + msg = 'Decrypt error.'; + break; + case tls.Alert.Description.export_restriction: + msg = 'Export restriction.'; + break; + case tls.Alert.Description.protocol_version: + msg = 'Unsupported protocol version.'; + break; + case tls.Alert.Description.insufficient_security: + msg = 'Insufficient security.'; + break; + case tls.Alert.Description.internal_error: + msg = 'Internal error.'; + break; + case tls.Alert.Description.user_canceled: + msg = 'User canceled.'; + break; + case tls.Alert.Description.no_renegotiation: + msg = 'Renegotiation not supported.'; + break; + default: + msg = 'Unknown error.'; + break; } -}; -module.exports = Container; + // close connection on close_notify, not an error + if(alert.description === tls.Alert.Description.close_notify) { + return c.close(); + } + // call error handler + c.error(c, { + message: msg, + send: false, + // origin is the opposite end + origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client', + alert: alert + }); -/***/ }), + // continue + c.process(); +}; -/***/ 4571: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Called when a Handshake record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleHandshake = function(c, record) { + // get the handshake type and message length + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt24(); -var EventEmitter = (__nccwpck_require__(2361).EventEmitter), - Modem = __nccwpck_require__(6042), - tar = __nccwpck_require__(366), - zlib = __nccwpck_require__(9796), - Container = __nccwpck_require__(5815), - Image = __nccwpck_require__(6689), - Volume = __nccwpck_require__(4877), - Network = __nccwpck_require__(9780), - Service = __nccwpck_require__(8866), - Plugin = __nccwpck_require__(6606), - Secret = __nccwpck_require__(9934), - Config = __nccwpck_require__(5004), - Task = __nccwpck_require__(1385), - Node = __nccwpck_require__(2297), - Exec = __nccwpck_require__(3149), - util = __nccwpck_require__(1604), - extend = util.extend; + // see if the record fragment doesn't yet contain the full message + if(length > b.length()) { + // cache the record, clear its fragment, and reset the buffer read + // pointer before the type and length were read + c.fragmented = record; + record.fragment = forge.util.createBuffer(); + b.read -= 4; -var Docker = function(opts) { - if (!(this instanceof Docker)) return new Docker(opts); + // continue + return c.process(); + } - var plibrary = global.Promise; + // full message now available, clear cache, reset read pointer to + // before type and length + c.fragmented = null; + b.read -= 4; - if (opts && opts.Promise) { - plibrary = opts.Promise; + // save the handshake bytes for digestion after handler is found + // (include type and length of handshake msg) + var bytes = b.bytes(length + 4); - if (Object.keys(opts).length === 1) { - opts = undefined; + // restore read pointer + b.read += 4; + + // handle expected message + if(type in hsTable[c.entity][c.expect]) { + // initialize server session + if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { + c.handshaking = true; + c.session = { + version: null, + extensions: { + server_name: { + serverNameList: [] + } + }, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + clientCertificate: null, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; } - } - this.modem = new Modem(opts); - this.modem.Promise = plibrary; + /* Update handshake messages digest. Finished and CertificateVerify + messages are not digested here. They can't be digested as part of + the verify_data that they contain. These messages are manually + digested in their handlers. HelloRequest messages are simply never + included in the handshake message digest according to spec. */ + if(type !== tls.HandshakeType.hello_request && + type !== tls.HandshakeType.certificate_verify && + type !== tls.HandshakeType.finished) { + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + } + + // handle specific handshake type record + hsTable[c.entity][c.expect][type](c, record, length); + } else { + // unexpected record + tls.handleUnexpected(c, record); + } }; /** - * Creates a new container - * @param {Object} opts Create options - * @param {Function} callback Callback + * Called when an ApplicationData record is received. + * + * @param c the connection. + * @param record the record. */ -Docker.prototype.createContainer = function(opts, callback) { - var self = this; - var optsf = { - path: '/containers/create?', - method: 'POST', - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 406: 'impossible to attach', - 500: 'server error' - } - }; - - delete opts.authconfig; +tls.handleApplicationData = function(c, record) { + // buffer data, notify that its ready + c.data.putBuffer(record.fragment); + c.dataReady(c); - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getContainer(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self.getContainer(data.Id)); - }); - } + // continue + c.process(); }; /** - * Creates a new image - * @param {Object} auth Authentication (optional) - * @param {Object} opts Create options - * @param {Function} callback Callback + * Called when a Heartbeat record is received. + * + * @param c the connection. + * @param record the record. */ -Docker.prototype.createImage = function(auth, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (!callback && !opts) { - opts = auth; - auth = opts.authconfig; - } +tls.handleHeartbeat = function(c, record) { + // get the heartbeat type and payload + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt16(); + var payload = b.getBytes(length); - var optsf = { - path: '/images/create?', - method: 'POST', - options: opts, - authconfig: auth, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' + if(type === tls.HeartbeatMessageType.heartbeat_request) { + // discard request during handshake or if length is too large + if(c.handshaking || length > payload.length) { + // continue + return c.process(); + } + // retransmit payload + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_response, payload) + })); + tls.flush(c); + } else if(type === tls.HeartbeatMessageType.heartbeat_response) { + // check payload against expected payload, discard heartbeat if no match + if(payload !== c.expectedHeartbeatPayload) { + // continue + return c.process(); } - }; - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + // notify that a valid heartbeat was received + if(c.heartbeatReceived) { + c.heartbeatReceived(c, forge.util.createBuffer(payload)); + } } + + // continue + c.process(); }; /** - * Load image - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * The transistional state tables for receiving TLS records. It maps the + * current TLS engine state and a received record to a function to handle the + * record and update the state. + * + * For instance, if the current state is SHE, then the TLS engine is expecting + * a ServerHello record. Once a record is received, the handler function is + * looked up using the state SHE and the record's content type. + * + * The resulting function will either be an error handler or a record handler. + * The function will take whatever action is appropriate and update the state + * for the next record. + * + * The states are all based on possible server record types. Note that the + * client will never specifically expect to receive a HelloRequest or an alert + * from the server so there is no state that reflects this. These messages may + * occur at any time. + * + * There are two tables for mapping states because there is a second tier of + * types for handshake messages. Once a record with a content type of handshake + * is received, the handshake record handler will look up the handshake type in + * the secondary map to get its appropriate handler. + * + * Valid message orders are as follows: + * + * =======================FULL HANDSHAKE====================== + * Client Server + * + * ClientHello --------> + * ServerHello + * Certificate* + * ServerKeyExchange* + * CertificateRequest* + * <-------- ServerHelloDone + * Certificate* + * ClientKeyExchange + * CertificateVerify* + * [ChangeCipherSpec] + * Finished --------> + * [ChangeCipherSpec] + * <-------- Finished + * Application Data <-------> Application Data + * + * =====================SESSION RESUMPTION===================== + * Client Server + * + * ClientHello --------> + * ServerHello + * [ChangeCipherSpec] + * <-------- Finished + * [ChangeCipherSpec] + * Finished --------> + * Application Data <-------> Application Data */ -Docker.prototype.loadImage = function(file, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } +// client expect states (indicate which records are expected to be received) +var SHE = 0; // rcv server hello +var SCE = 1; // rcv server certificate +var SKE = 2; // rcv server key exchange +var SCR = 3; // rcv certificate request +var SHD = 4; // rcv server hello done +var SCC = 5; // rcv change cipher spec +var SFI = 6; // rcv finished +var SAD = 7; // rcv application data +var SER = 8; // not expecting any messages at this point - var optsf = { - path: '/images/load?', - method: 'POST', - options: opts, - file: file, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; +// server expect states +var CHE = 0; // rcv client hello +var CCE = 1; // rcv client certificate +var CKE = 2; // rcv client key exchange +var CCV = 3; // rcv certificate verify +var CCC = 4; // rcv change cipher spec +var CFI = 5; // rcv finished +var CAD = 6; // rcv application data +var CER = 7; // not expecting any messages at this point - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; +// map client current expect state and content type to function +var __ = tls.handleUnexpected; +var R0 = tls.handleChangeCipherSpec; +var R1 = tls.handleAlert; +var R2 = tls.handleHandshake; +var R3 = tls.handleApplicationData; +var R4 = tls.handleHeartbeat; +var ctTable = []; +ctTable[tls.ConnectionEnd.client] = [ +// CC,AL,HS,AD,HB +/*SHE*/[__,R1,R2,__,R4], +/*SCE*/[__,R1,R2,__,R4], +/*SKE*/[__,R1,R2,__,R4], +/*SCR*/[__,R1,R2,__,R4], +/*SHD*/[__,R1,R2,__,R4], +/*SCC*/[R0,R1,__,__,R4], +/*SFI*/[__,R1,R2,__,R4], +/*SAD*/[__,R1,R2,R3,R4], +/*SER*/[__,R1,R2,__,R4] +]; + +// map server current expect state and content type to function +ctTable[tls.ConnectionEnd.server] = [ +// CC,AL,HS,AD +/*CHE*/[__,R1,R2,__,R4], +/*CCE*/[__,R1,R2,__,R4], +/*CKE*/[__,R1,R2,__,R4], +/*CCV*/[__,R1,R2,__,R4], +/*CCC*/[R0,R1,__,__,R4], +/*CFI*/[__,R1,R2,__,R4], +/*CAD*/[__,R1,R2,R3,R4], +/*CER*/[__,R1,R2,__,R4] +]; + +// map client current expect state and handshake type to function +var H0 = tls.handleHelloRequest; +var H1 = tls.handleServerHello; +var H2 = tls.handleCertificate; +var H3 = tls.handleServerKeyExchange; +var H4 = tls.handleCertificateRequest; +var H5 = tls.handleServerHelloDone; +var H6 = tls.handleFinished; +var hsTable = []; +hsTable[tls.ConnectionEnd.client] = [ +// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI +/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__], +/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__], +/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__], +/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__], +/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], +/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] +]; + +// map server current expect state and handshake type to function +// Note: CAD[CH] does not map to FB because renegotation is prohibited +var H7 = tls.handleClientHello; +var H8 = tls.handleClientKeyExchange; +var H9 = tls.handleCertificateVerify; +hsTable[tls.ConnectionEnd.server] = [ +// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI +/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__], +/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__], +/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__], +/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], +/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] +]; /** - * Import image from a tar archive - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * Generates the master_secret and keys using the given security parameters. + * + * The security parameters for a TLS connection state are defined as such: + * + * struct { + * ConnectionEnd entity; + * PRFAlgorithm prf_algorithm; + * BulkCipherAlgorithm bulk_cipher_algorithm; + * CipherType cipher_type; + * uint8 enc_key_length; + * uint8 block_length; + * uint8 fixed_iv_length; + * uint8 record_iv_length; + * MACAlgorithm mac_algorithm; + * uint8 mac_length; + * uint8 mac_key_length; + * CompressionMethod compression_algorithm; + * opaque master_secret[48]; + * opaque client_random[32]; + * opaque server_random[32]; + * } SecurityParameters; + * + * Note that this definition is from TLS 1.2. In TLS 1.0 some of these + * parameters are ignored because, for instance, the PRFAlgorithm is a + * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0. + * + * The Record Protocol requires an algorithm to generate keys required by the + * current connection state. + * + * The master secret is expanded into a sequence of secure bytes, which is then + * split to a client write MAC key, a server write MAC key, a client write + * encryption key, and a server write encryption key. In TLS 1.0 a client write + * IV and server write IV are also generated. Each of these is generated from + * the byte sequence in that order. Unused values are empty. In TLS 1.2, some + * AEAD ciphers may additionally require a client write IV and a server write + * IV (see Section 6.2.3.3). + * + * When keys, MAC keys, and IVs are generated, the master secret is used as an + * entropy source. + * + * To generate the key material, compute: + * + * master_secret = PRF(pre_master_secret, "master secret", + * ClientHello.random + ServerHello.random) + * + * key_block = PRF(SecurityParameters.master_secret, + * "key expansion", + * SecurityParameters.server_random + + * SecurityParameters.client_random); + * + * until enough output has been generated. Then, the key_block is + * partitioned as follows: + * + * client_write_MAC_key[SecurityParameters.mac_key_length] + * server_write_MAC_key[SecurityParameters.mac_key_length] + * client_write_key[SecurityParameters.enc_key_length] + * server_write_key[SecurityParameters.enc_key_length] + * client_write_IV[SecurityParameters.fixed_iv_length] + * server_write_IV[SecurityParameters.fixed_iv_length] + * + * In TLS 1.2, the client_write_IV and server_write_IV are only generated for + * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This + * implementation uses TLS 1.0 so IVs are generated. + * + * Implementation note: The currently defined cipher suite which requires the + * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32 + * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also + * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material. + * + * @param c the connection. + * @param sp the security parameters to use. + * + * @return the security keys. */ -Docker.prototype.importImage = function(file, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = undefined; +tls.generateKeys = function(c, sp) { + // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) & + // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented + // at present + + // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with + // TLS 1.0 but we don't care right now because AES is better and we have + // an implementation for it + + // TODO: TLS 1.2 implementation + /* + // determine the PRF + var prf; + switch(sp.prf_algorithm) { + case tls.PRFAlgorithm.tls_prf_sha256: + prf = prf_sha256; + break; + default: + // should never happen + throw new Error('Invalid PRF'); } + */ - if (!opts) - opts = {}; + // TLS 1.0/1.1 implementation + var prf = prf_TLS1; - opts.fromSrc = '-'; + // concatenate server and client random + var random = sp.client_random + sp.server_random; - var optsf = { - path: '/images/create?', - method: 'POST', - options: opts, - file: file, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + // only create master secret if session is new + if(!c.session.resuming) { + // create master secret, clean up pre-master secret + sp.master_secret = prf( + sp.pre_master_secret, 'master secret', random, 48).bytes(); + sp.pre_master_secret = null; + } - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + // generate the amount of key material needed + random = sp.server_random + sp.client_random; + var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; + + // include IV for TLS/1.0 + var tls10 = (c.version.major === tls.Versions.TLS_1_0.major && + c.version.minor === tls.Versions.TLS_1_0.minor); + if(tls10) { + length += 2 * sp.fixed_iv_length; } -}; + var km = prf(sp.master_secret, 'key expansion', random, length); -/** - * Verifies auth - * @param {Object} opts Options - * @param {Function} callback Callback - */ -Docker.prototype.checkAuth = function(opts, callback) { - var self = this; - var optsf = { - path: '/auth', - method: 'POST', - options: opts, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 500: 'server error' - } + // split the key material into the MAC and encryption keys + var rval = { + client_write_MAC_key: km.getBytes(sp.mac_key_length), + server_write_MAC_key: km.getBytes(sp.mac_key_length), + client_write_key: km.getBytes(sp.enc_key_length), + server_write_key: km.getBytes(sp.enc_key_length) }; - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + // include TLS 1.0 IVs + if(tls10) { + rval.client_write_IV = km.getBytes(sp.fixed_iv_length); + rval.server_write_IV = km.getBytes(sp.fixed_iv_length); } + + return rval; }; /** - * Builds an image - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * Creates a new initialized TLS connection state. A connection state has + * a read mode and a write mode. + * + * compression state: + * The current state of the compression algorithm. + * + * cipher state: + * The current state of the encryption algorithm. This will consist of the + * scheduled key for that connection. For stream ciphers, this will also + * contain whatever state information is necessary to allow the stream to + * continue to encrypt or decrypt data. + * + * MAC key: + * The MAC key for the connection. + * + * sequence number: + * Each connection state contains a sequence number, which is maintained + * separately for read and write states. The sequence number MUST be set to + * zero whenever a connection state is made the active state. Sequence + * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do + * not wrap. If a TLS implementation would need to wrap a sequence number, + * it must renegotiate instead. A sequence number is incremented after each + * record: specifically, the first record transmitted under a particular + * connection state MUST use sequence number 0. + * + * @param c the connection. + * + * @return the new initialized TLS connection state. */ -Docker.prototype.buildImage = function(file, opts, callback) { - var self = this; - - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } +tls.createConnectionState = function(c) { + var client = (c.entity === tls.ConnectionEnd.client); - function build(file) { - var optsf = { - path: '/build?', - method: 'POST', - file: file, - options: opts, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' + var createMode = function() { + var mode = { + // two 32-bit numbers, first is most significant + sequenceNumber: [0, 0], + macKey: null, + macLength: 0, + macFunction: null, + cipherState: null, + cipherFunction: function(record) {return true;}, + compressionState: null, + compressFunction: function(record) {return true;}, + updateSequenceNumber: function() { + if(mode.sequenceNumber[1] === 0xFFFFFFFF) { + mode.sequenceNumber[1] = 0; + ++mode.sequenceNumber[0]; + } else { + ++mode.sequenceNumber[1]; + } } }; + return mode; + }; + var state = { + read: createMode(), + write: createMode() + }; - if (opts) { - if (opts.registryconfig) { - optsf.registryconfig = optsf.options.registryconfig; - delete optsf.options.registryconfig; - } - - //undocumented? - if (opts.authconfig) { - optsf.authconfig = optsf.options.authconfig; - delete optsf.options.authconfig; - } + // update function in read mode will decrypt then decompress a record + state.read.update = function(c, record) { + if(!state.read.cipherFunction(record, state.read)) { + c.error(c, { + message: 'Could not decrypt record or bad MAC.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + // doesn't matter if decryption failed or MAC was + // invalid, return the same error so as not to reveal + // which one occurred + description: tls.Alert.Description.bad_record_mac + } + }); + } else if(!state.read.compressFunction(c, record, state.read)) { + c.error(c, { + message: 'Could not decompress record.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decompression_failure + } + }); } + return !c.fail; + }; - if (callback === undefined) { - return new self.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); + // update function in write mode will compress then encrypt a record + state.write.update = function(c, record) { + if(!state.write.compressFunction(c, record, state.write)) { + // error, but do not send alert since it would require + // compression as well + c.error(c, { + message: 'Could not compress record.', + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } }); - } else { - self.modem.dial(optsf, function(err, data) { - callback(err, data); + } else if(!state.write.cipherFunction(record, state.write)) { + // error, but do not send alert since it would require + // encryption as well + c.error(c, { + message: 'Could not encrypt record.', + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } }); } - } - - if (file && file.context) { - var pack = tar.pack(file.context, { - entries: file.src - }); - return build(pack.pipe(zlib.createGzip())); - } else { - return build(file); - } -}; - -/** - * Fetches a Container by ID - * @param {String} id Container's ID - */ -Docker.prototype.getContainer = function(id) { - return new Container(this.modem, id); -}; - -/** - * Fetches an Image by name - * @param {String} name Image's name - */ -Docker.prototype.getImage = function(name) { - return new Image(this.modem, name); -}; - -/** - * Fetches a Volume by name - * @param {String} name Volume's name - */ -Docker.prototype.getVolume = function(name) { - return new Volume(this.modem, name); -}; + return !c.fail; + }; -/** - * Fetches a Plugin by name - * @param {String} name Volume's name - */ -Docker.prototype.getPlugin = function(name, remote) { - return new Plugin(this.modem, name, remote); -}; + // handle security parameters + if(c.session) { + var sp = c.session.sp; + c.session.cipherSuite.initSecurityParameters(sp); -/** - * Fetches a Service by id - * @param {String} id Services's id - */ -Docker.prototype.getService = function(id) { - return new Service(this.modem, id); -}; + // generate keys + sp.keys = tls.generateKeys(c, sp); + state.read.macKey = client ? + sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; + state.write.macKey = client ? + sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; -/** - * Fetches a Task by id - * @param {String} id Task's id - */ -Docker.prototype.getTask = function(id) { - return new Task(this.modem, id); -}; + // cipher suite setup + c.session.cipherSuite.initConnectionState(state, c, sp); -/** - * Fetches Node by id - * @param {String} id Node's id - */ -Docker.prototype.getNode = function(id) { - return new Node(this.modem, id); -}; + // compression setup + switch(sp.compression_algorithm) { + case tls.CompressionMethod.none: + break; + case tls.CompressionMethod.deflate: + state.read.compressFunction = inflate; + state.write.compressFunction = deflate; + break; + default: + throw new Error('Unsupported compression algorithm.'); + } + } -/** - * Fetches a Network by id - * @param {String} id network's id - */ -Docker.prototype.getNetwork = function(id) { - return new Network(this.modem, id); + return state; }; /** - * Fetches a Secret by id - * @param {String} id network's id + * Creates a Random structure. + * + * struct { + * uint32 gmt_unix_time; + * opaque random_bytes[28]; + * } Random; + * + * gmt_unix_time: + * The current time and date in standard UNIX 32-bit format (seconds since + * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according + * to the sender's internal clock. Clocks are not required to be set + * correctly by the basic TLS protocol; higher-level or application + * protocols may define additional requirements. Note that, for historical + * reasons, the data element is named using GMT, the predecessor of the + * current worldwide time base, UTC. + * random_bytes: + * 28 bytes generated by a secure random number generator. + * + * @return the Random structure as a byte array. */ -Docker.prototype.getSecret = function(id) { - return new Secret(this.modem, id); +tls.createRandom = function() { + // get UTC milliseconds + var d = new Date(); + var utc = +d + d.getTimezoneOffset() * 60000; + var rval = forge.util.createBuffer(); + rval.putInt32(utc); + rval.putBytes(forge.random.getBytes(28)); + return rval; }; /** - * Fetches a Config by id - * @param {String} id network's id + * Creates a TLS record with the given type and data. + * + * @param c the connection. + * @param options: + * type: the record type. + * data: the plain text data in a byte buffer. + * + * @return the created record. */ -Docker.prototype.getConfig = function(id) { - return new Config(this.modem, id); +tls.createRecord = function(c, options) { + if(!options.data) { + return null; + } + var record = { + type: options.type, + version: { + major: c.version.major, + minor: c.version.minor + }, + length: options.data.length(), + fragment: options.data + }; + return record; }; /** - * Fetches an Exec instance by ID - * @param {String} id Exec instance's ID + * Creates a TLS alert record. + * + * @param c the connection. + * @param alert: + * level: the TLS alert level. + * description: the TLS alert description. + * + * @return the created alert record. */ -Docker.prototype.getExec = function(id) { - return new Exec(this.modem, id); +tls.createAlert = function(c, alert) { + var b = forge.util.createBuffer(); + b.putByte(alert.level); + b.putByte(alert.description); + return tls.createRecord(c, { + type: tls.ContentType.alert, + data: b + }); }; -/** - * Lists containers - * @param {Object} opts Options (optional) - * @param {Function} callback Callback +/* The structure of a TLS handshake message. + * + * struct { + * HandshakeType msg_type; // handshake type + * uint24 length; // bytes in message + * select(HandshakeType) { + * case hello_request: HelloRequest; + * case client_hello: ClientHello; + * case server_hello: ServerHello; + * case certificate: Certificate; + * case server_key_exchange: ServerKeyExchange; + * case certificate_request: CertificateRequest; + * case server_hello_done: ServerHelloDone; + * case certificate_verify: CertificateVerify; + * case client_key_exchange: ClientKeyExchange; + * case finished: Finished; + * } body; + * } Handshake; */ -Docker.prototype.listContainers = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; /** - * Lists images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } + * Creates a ClientHello message. + * + * opaque SessionID<0..32>; + * enum { null(0), deflate(1), (255) } CompressionMethod; + * uint8 CipherSuite[2]; + * + * struct { + * ProtocolVersion client_version; + * Random random; + * SessionID session_id; + * CipherSuite cipher_suites<2..2^16-2>; + * CompressionMethod compression_methods<1..2^8-1>; + * select(extensions_present) { + * case false: + * struct {}; + * case true: + * Extension extensions<0..2^16-1>; + * }; + * } ClientHello; + * + * The extension format for extended client hellos and server hellos is: + * + * struct { + * ExtensionType extension_type; + * opaque extension_data<0..2^16-1>; + * } Extension; + * + * Here: + * + * - "extension_type" identifies the particular extension type. + * - "extension_data" contains information specific to the particular + * extension type. + * + * The extension types defined in this document are: + * + * enum { + * server_name(0), max_fragment_length(1), + * client_certificate_url(2), trusted_ca_keys(3), + * truncated_hmac(4), status_request(5), (65535) + * } ExtensionType; + * + * @param c the connection. + * + * @return the ClientHello byte buffer. + */ +tls.createClientHello = function(c) { + // save hello version + c.session.clientHelloVersion = { + major: c.version.major, + minor: c.version.minor }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // create supported cipher suites + var cipherSuites = forge.util.createBuffer(); + for(var i = 0; i < c.cipherSuites.length; ++i) { + var cs = c.cipherSuites[i]; + cipherSuites.putByte(cs.id[0]); + cipherSuites.putByte(cs.id[1]); } -}; - -/** - * Get images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.getImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/get?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; + var cSuites = cipherSuites.length(); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // create supported compression methods, null always supported, but + // also support deflate if connection has inflate and deflate methods + var compressionMethods = forge.util.createBuffer(); + compressionMethods.putByte(tls.CompressionMethod.none); + // FIXME: deflate support disabled until issues with raw deflate data + // without zlib headers are resolved + /* + if(c.inflate !== null && c.deflate !== null) { + compressionMethods.putByte(tls.CompressionMethod.deflate); } -}; + */ + var cMethods = compressionMethods.length(); -/** - * Lists Services - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listServices = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // create TLS SNI (server name indication) extension if virtual host + // has been specified, see RFC 3546 + var extensions = forge.util.createBuffer(); + if(c.virtualHost) { + // create extension struct + var ext = forge.util.createBuffer(); + ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes) + ext.putByte(0x00); - var optsf = { - path: '/services?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + /* In order to provide the server name, clients MAY include an + * extension of type "server_name" in the (extended) client hello. + * The "extension_data" field of this extension SHALL contain + * "ServerNameList" where: + * + * struct { + * NameType name_type; + * select(name_type) { + * case host_name: HostName; + * } name; + * } ServerName; + * + * enum { + * host_name(0), (255) + * } NameType; + * + * opaque HostName<1..2^16-1>; + * + * struct { + * ServerName server_name_list<1..2^16-1> + * } ServerNameList; + */ + var serverName = forge.util.createBuffer(); + serverName.putByte(0x00); // type host_name + writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // ServerNameList is in extension_data + var snList = forge.util.createBuffer(); + writeVector(snList, 2, serverName); + writeVector(ext, 2, snList); + extensions.putBuffer(ext); + } + var extLength = extensions.length(); + if(extLength > 0) { + // add extension vector length + extLength += 2; } -}; - -/** - * Lists Nodes - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listNodes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/nodes?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such node', - 500: 'server error', - 503: 'node is not part of a swarm', - } - }; + // determine length of the handshake message + // cipher suites and compression methods size will need to be + // updated if more get added to the list + var sessionId = c.session.id; + var length = + sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + cSuites + // cipher suites vector + 1 + cMethods + // compression methods vector + extLength; // extensions vector - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_hello); + rval.putInt24(length); // handshake length + rval.putByte(c.version.major); // major version + rval.putByte(c.version.minor); // minor version + rval.putBytes(c.session.sp.client_random); // random time + bytes + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + writeVector(rval, 2, cipherSuites); + writeVector(rval, 1, compressionMethods); + if(extLength > 0) { + writeVector(rval, 2, extensions); } + return rval; }; /** - * Lists Tasks - * @param {Object} opts - * @param {Function} callback Callback + * Creates a ServerHello message. + * + * @param c the connection. + * + * @return the ServerHello byte buffer. */ -Docker.prototype.listTasks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/tasks?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; +tls.createServerHello = function(c) { + // determine length of the handshake message + var sessionId = c.session.id; + var length = + sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + // chosen cipher suite + 1; // chosen compression method - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello); + rval.putInt24(length); // handshake length + rval.putByte(c.version.major); // major version + rval.putByte(c.version.minor); // minor version + rval.putBytes(c.session.sp.server_random); // random time + bytes + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + rval.putByte(c.session.cipherSuite.id[0]); + rval.putByte(c.session.cipherSuite.id[1]); + rval.putByte(c.session.compressionMethod); + return rval; }; /** - * Creates a new secret - * @param {Object} opts Create options - * @param {Function} callback Callback + * Creates a Certificate message. + * + * When this message will be sent: + * This is the first message the client can send after receiving a server + * hello done message and the first message the server can send after + * sending a ServerHello. This client message is only sent if the server + * requests a certificate. If no suitable certificate is available, the + * client should send a certificate message containing no certificates. If + * client authentication is required by the server for the handshake to + * continue, it may respond with a fatal handshake failure alert. + * + * opaque ASN.1Cert<1..2^24-1>; + * + * struct { + * ASN.1Cert certificate_list<0..2^24-1>; + * } Certificate; + * + * @param c the connection. + * + * @return the Certificate byte buffer. */ -Docker.prototype.createSecret = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - var optsf = { - path: '/secrets/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 406: 'server error or node is not part of a swarm', - 409: 'name conflicts with an existing object', - 500: 'server error' - } - }; +tls.createCertificate = function(c) { + // TODO: check certificate request to ensure types are supported + // get a certificate (a certificate as a PEM string) + var client = (c.entity === tls.ConnectionEnd.client); + var cert = null; + if(c.getCertificate) { + var hint; + if(client) { + hint = c.session.certificateRequest; + } else { + hint = c.session.extensions.server_name.serverNameList; + } + cert = c.getCertificate(c, hint); + } - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + // buffer to hold certificate list + var certList = forge.util.createBuffer(); + if(cert !== null) { + try { + // normalize cert to a chain of certificates + if(!forge.util.isArray(cert)) { + cert = [cert]; + } + var asn1 = null; + for(var i = 0; i < cert.length; ++i) { + var msg = forge.pem.decode(cert[i])[0]; + if(msg.type !== 'CERTIFICATE' && + msg.type !== 'X509 CERTIFICATE' && + msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error('Could not convert certificate from PEM; PEM ' + + 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' + + '"TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certificate from PEM; PEM is encrypted.'); } - resolve(self.getSecret(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getSecret(data.ID)); - }); - } -}; + var der = forge.util.createBuffer(msg.body); + if(asn1 === null) { + asn1 = forge.asn1.fromDer(der.bytes(), false); + } -/** - * Creates a new config - * @param {Object} opts Config options - * @param {Function} callback Callback - */ -Docker.prototype.createConfig = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - var optsf = { - path: '/configs/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 406: 'server error or node is not part of a swarm', - 409: 'name conflicts with an existing object', - 500: 'server error' - } - }; + // certificate entry is itself a vector with 3 length bytes + var certBuffer = forge.util.createBuffer(); + writeVector(certBuffer, 3, der); + // add cert vector to cert list vector + certList.putBuffer(certBuffer); + } - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + // save certificate + cert = forge.pki.certificateFromAsn1(asn1); + if(client) { + c.session.clientCertificate = cert; + } else { + c.session.serverCertificate = cert; + } + } catch(ex) { + return c.error(c, { + message: 'Could not send certificate list.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate } - resolve(self.getConfig(data.ID)); }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getConfig(data.ID)); - }); + } } -}; + // determine length of the handshake message + var length = 3 + certList.length(); // cert list vector + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate); + rval.putInt24(length); + writeVector(rval, 3, certList); + return rval; +}; /** - * Lists secrets - * @param {Object} opts - * @param {Function} callback Callback + * Creates a ClientKeyExchange message. + * + * When this message will be sent: + * This message is always sent by the client. It will immediately follow the + * client certificate message, if it is sent. Otherwise it will be the first + * message sent by the client after it receives the server hello done + * message. + * + * Meaning of this message: + * With this message, the premaster secret is set, either though direct + * transmission of the RSA-encrypted secret, or by the transmission of + * Diffie-Hellman parameters which will allow each side to agree upon the + * same premaster secret. When the key exchange method is DH_RSA or DH_DSS, + * client certification has been requested, and the client was able to + * respond with a certificate which contained a Diffie-Hellman public key + * whose parameters (group and generator) matched those specified by the + * server in its certificate, this message will not contain any data. + * + * Meaning of this message: + * If RSA is being used for key agreement and authentication, the client + * generates a 48-byte premaster secret, encrypts it using the public key + * from the server's certificate or the temporary RSA key provided in a + * server key exchange message, and sends the result in an encrypted + * premaster secret message. This structure is a variant of the client + * key exchange message, not a message in itself. + * + * struct { + * select(KeyExchangeAlgorithm) { + * case rsa: EncryptedPreMasterSecret; + * case diffie_hellman: ClientDiffieHellmanPublic; + * } exchange_keys; + * } ClientKeyExchange; + * + * struct { + * ProtocolVersion client_version; + * opaque random[46]; + * } PreMasterSecret; + * + * struct { + * public-key-encrypted PreMasterSecret pre_master_secret; + * } EncryptedPreMasterSecret; + * + * A public-key-encrypted element is encoded as a vector <0..2^16-1>. + * + * @param c the connection. + * + * @return the ClientKeyExchange byte buffer. */ -Docker.prototype.listSecrets = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.createClientKeyExchange = function(c) { + // create buffer to encrypt + var b = forge.util.createBuffer(); - var optsf = { - path: '/secrets?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + // add highest client-supported protocol to help server avoid version + // rollback attacks + b.putByte(c.session.clientHelloVersion.major); + b.putByte(c.session.clientHelloVersion.minor); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + // generate and add 46 random bytes + b.putBytes(forge.random.getBytes(46)); -/** - * Lists configs - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listConfigs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // save pre-master secret + var sp = c.session.sp; + sp.pre_master_secret = b.getBytes(); - var optsf = { - path: '/configs?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + // RSA-encrypt the pre-master secret + var key = c.session.serverCertificate.publicKey; + b = key.encrypt(sp.pre_master_secret); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + /* Note: The encrypted pre-master secret will be stored in a + public-key-encrypted opaque vector that has the length prefixed using + 2 bytes, so include those 2 bytes in the handshake message length. This + is done as a minor optimization instead of calling writeVector(). */ + + // determine length of the handshake message + var length = b.length + 2; + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_key_exchange); + rval.putInt24(length); + // add vector length bytes + rval.putInt16(b.length); + rval.putBytes(b); + return rval; }; /** - * Creates a new plugin - * @param {Object} opts Create options - * @param {Function} callback Callback + * Creates a ServerKeyExchange message. + * + * @param c the connection. + * + * @return the ServerKeyExchange byte buffer. */ -Docker.prototype.createPlugin = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/plugins/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - } - }; +tls.createServerKeyExchange = function(c) { + // this implementation only supports RSA, no Diffie-Hellman support, + // so this record is empty + // determine length of the handshake message + var length = 0; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getPlugin(args.opts.name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getPlugin(args.opts.name)); - }); + // build record fragment + var rval = forge.util.createBuffer(); + if(length > 0) { + rval.putByte(tls.HandshakeType.server_key_exchange); + rval.putInt24(length); } + return rval; }; - /** - * Lists plugins - * @param {Object} opts - * @param {Function} callback Callback + * Gets the signed data used to verify a client-side certificate. See + * tls.createCertificateVerify() for details. + * + * @param c the connection. + * @param callback the callback to call once the signed data is ready. */ -Docker.prototype.listPlugins = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.getClientSignature = function(c, callback) { + // generate data to RSA encrypt + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + b = b.getBytes(); - var optsf = { - path: '/plugins?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + // create default signing function as necessary + c.getSignature = c.getSignature || function(c, b, callback) { + // do rsa encryption, call callback + var privateKey = null; + if(c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.clientCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch(ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + if(privateKey === null) { + c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error } - resolve(data); }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + } else { + b = privateKey.sign(b, null); } + callback(c, b); }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + // get client signature + c.getSignature(c, b, callback); }; /** - * Prune builder - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * Creates a CertificateVerify message. + * + * Meaning of this message: + * This structure conveys the client's Diffie-Hellman public value + * (Yc) if it was not already included in the client's certificate. + * The encoding used for Yc is determined by the enumerated + * PublicValueEncoding. This structure is a variant of the client + * key exchange message, not a message in itself. + * + * When this message will be sent: + * This message is used to provide explicit verification of a client + * certificate. This message is only sent following a client + * certificate that has signing capability (i.e. all certificates + * except those containing fixed Diffie-Hellman parameters). When + * sent, it will immediately follow the client key exchange message. + * + * struct { + * Signature signature; + * } CertificateVerify; + * + * CertificateVerify.signature.md5_hash + * MD5(handshake_messages); + * + * Certificate.signature.sha_hash + * SHA(handshake_messages); + * + * Here handshake_messages refers to all handshake messages sent or + * received starting at client hello up to but not including this + * message, including the type and length fields of the handshake + * messages. + * + * select(SignatureAlgorithm) { + * case anonymous: struct { }; + * case rsa: + * digitally-signed struct { + * opaque md5_hash[16]; + * opaque sha_hash[20]; + * }; + * case dsa: + * digitally-signed struct { + * opaque sha_hash[20]; + * }; + * } Signature; + * + * In digital signing, one-way hash functions are used as input for a + * signing algorithm. A digitally-signed element is encoded as an opaque + * vector <0..2^16-1>, where the length is specified by the signing + * algorithm and key. + * + * In RSA signing, a 36-byte structure of two hashes (one SHA and one + * MD5) is signed (encrypted with the private key). It is encoded with + * PKCS #1 block type 0 or type 1 as described in [PKCS1]. + * + * In DSS, the 20 bytes of the SHA hash are run directly through the + * Digital Signing Algorithm with no additional hashing. + * + * @param c the connection. + * @param signature the signature to include in the message. + * + * @return the CertificateVerify byte buffer. */ -Docker.prototype.pruneBuilder = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.createCertificateVerify = function(c, signature) { + /* Note: The signature will be stored in a "digitally-signed" opaque + vector that has the length prefixed using 2 bytes, so include those + 2 bytes in the handshake message length. This is done as a minor + optimization instead of calling writeVector(). */ - var optsf = { - path: '/build/prune', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + // determine length of the handshake message + var length = signature.length + 2; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_verify); + rval.putInt24(length); + // add vector length bytes + rval.putInt16(signature.length); + rval.putBytes(signature); + return rval; }; /** - * Prune containers - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * Creates a CertificateRequest message. + * + * @param c the connection. + * + * @return the CertificateRequest byte buffer. */ -Docker.prototype.pruneContainers = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.createCertificateRequest = function(c) { + // TODO: support other certificate types + var certTypes = forge.util.createBuffer(); - var optsf = { - path: '/containers/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + // common RSA certificate type + certTypes.putByte(0x01); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // add distinguished names from CA store + var cAs = forge.util.createBuffer(); + for(var key in c.caStore.certs) { + var cert = c.caStore.certs[key]; + var dn = forge.pki.distinguishedNameToAsn1(cert.subject); + var byteBuffer = forge.asn1.toDer(dn); + cAs.putInt16(byteBuffer.length()); + cAs.putBuffer(byteBuffer); } -}; -/** - * Prune volumes - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneVolumes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // TODO: TLS 1.2+ has a different format - var optsf = { - path: '/volumes/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; + // determine length of the handshake message + var length = + 1 + certTypes.length() + + 2 + cAs.length(); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_request); + rval.putInt24(length); + writeVector(rval, 1, certTypes); + writeVector(rval, 2, cAs); + return rval; }; /** - * Prune networks - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * Creates a ServerHelloDone message. + * + * @param c the connection. + * + * @return the ServerHelloDone byte buffer. */ -Docker.prototype.pruneNetworks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +tls.createServerHelloDone = function(c) { + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello_done); + rval.putInt24(0); + return rval; }; +/** + * Creates a ChangeCipherSpec message. + * + * The change cipher spec protocol exists to signal transitions in + * ciphering strategies. The protocol consists of a single message, + * which is encrypted and compressed under the current (not the pending) + * connection state. The message consists of a single byte of value 1. + * + * struct { + * enum { change_cipher_spec(1), (255) } type; + * } ChangeCipherSpec; + * + * @return the ChangeCipherSpec byte buffer. + */ +tls.createChangeCipherSpec = function() { + var rval = forge.util.createBuffer(); + rval.putByte(0x01); + return rval; +}; /** - * Creates a new volume - * @param {Object} opts Create options - * @param {Function} callback Callback + * Creates a Finished message. + * + * struct { + * opaque verify_data[12]; + * } Finished; + * + * verify_data + * PRF(master_secret, finished_label, MD5(handshake_messages) + + * SHA-1(handshake_messages)) [0..11]; + * + * finished_label + * For Finished messages sent by the client, the string "client + * finished". For Finished messages sent by the server, the + * string "server finished". + * + * handshake_messages + * All of the data from all handshake messages up to but not + * including this message. This is only data visible at the + * handshake layer and does not include record layer headers. + * This is the concatenation of all the Handshake structures as + * defined in 7.4 exchanged thus far. + * + * @param c the connection. + * + * @return the Finished byte buffer. */ -Docker.prototype.createVolume = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/volumes/create?', - method: 'POST', - allowEmpty: true, - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 500: 'server error' - } - }; +tls.createFinished = function(c) { + // generate verify_data + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + // TODO: determine prf function and verify length for TLS 1.2 + var client = (c.entity === tls.ConnectionEnd.client); + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + var label = client ? 'client finished' : 'server finished'; + b = prf(sp.master_secret, label, b.getBytes(), vdl); - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getVolume(data.Name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getVolume(data.Name)); - }); - } + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.finished); + rval.putInt24(b.length()); + rval.putBuffer(b); + return rval; }; /** - * Creates a new service - * @param {Object} auth - * @param {Object} opts Create options - * @param {Function} callback Callback + * Creates a HeartbeatMessage (See RFC 6520). + * + * struct { + * HeartbeatMessageType type; + * uint16 payload_length; + * opaque payload[HeartbeatMessage.payload_length]; + * opaque padding[padding_length]; + * } HeartbeatMessage; + * + * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or + * max_fragment_length when negotiated as defined in [RFC6066]. + * + * type: The message type, either heartbeat_request or heartbeat_response. + * + * payload_length: The length of the payload. + * + * payload: The payload consists of arbitrary content. + * + * padding: The padding is random content that MUST be ignored by the + * receiver. The length of a HeartbeatMessage is TLSPlaintext.length + * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the + * length of the type field is 1 byte, and the length of the + * payload_length is 2. Therefore, the padding_length is + * TLSPlaintext.length - payload_length - 3 for TLS and + * DTLSPlaintext.length - payload_length - 3 for DTLS. The + * padding_length MUST be at least 16. + * + * The sender of a HeartbeatMessage MUST use a random padding of at + * least 16 bytes. The padding of a received HeartbeatMessage message + * MUST be ignored. + * + * If the payload_length of a received HeartbeatMessage is too large, + * the received HeartbeatMessage MUST be discarded silently. + * + * @param c the connection. + * @param type the tls.HeartbeatMessageType. + * @param payload the heartbeat data to send as the payload. + * @param [payloadLength] the payload length to use, defaults to the + * actual payload length. + * + * @return the HeartbeatRequest byte buffer. */ -Docker.prototype.createService = function(auth, opts, callback) { - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (!opts && !callback) { - opts = auth; - } - - - var self = this; - var optsf = { - path: '/services/create', - method: 'POST', - options: opts, - authconfig: auth, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 500: 'server error' - } - }; - - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getService(data.ID || data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self.getService(data.ID || data.Id)); - }); +tls.createHeartbeat = function(type, payload, payloadLength) { + if(typeof payloadLength === 'undefined') { + payloadLength = payload.length; } + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(type); // heartbeat message type + rval.putInt16(payloadLength); // payload length + rval.putBytes(payload); // payload + // padding + var plaintextLength = rval.length(); + var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); + rval.putBytes(forge.random.getBytes(paddingLength)); + return rval; }; /** - * Lists volumes - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * Fragments, compresses, encrypts, and queues a record for delivery. + * + * @param c the connection. + * @param record the record to queue. */ -Docker.prototype.listVolumes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +tls.queue = function(c, record) { + // error during record creation + if(!record) { + return; } -}; -/** - * Creates a new network - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createNetwork = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/networks/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'driver not found', - 500: 'server error' + if(record.fragment.length() === 0) { + if(record.type === tls.ContentType.handshake || + record.type === tls.ContentType.alert || + record.type === tls.ContentType.change_cipher_spec) { + // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent. + return; } - }; + } + // if the record is a handshake record, update handshake hashes + if(record.type === tls.ContentType.handshake) { + var bytes = record.fragment.bytes(); + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + bytes = null; + } - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getNetwork(data.Id)); - }); - }); + // handle record fragmentation + var records; + if(record.fragment.length() <= tls.MaxFragment) { + records = [record]; } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getNetwork(data.Id)); - }); + // fragment data as long as it is too long + records = []; + var data = record.fragment.bytes(); + while(data.length > tls.MaxFragment) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) + })); + data = data.slice(tls.MaxFragment); + } + // add last record + if(data.length > 0) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data) + })); + } } -}; - -/** - * Lists networks - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listNetworks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/networks?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' + // compress and encrypt all fragmented records + for(var i = 0; i < records.length && !c.fail; ++i) { + // update the record using current write state + var rec = records[i]; + var s = c.state.current.write; + if(s.update(c, rec)) { + // store record + c.records.push(rec); } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); } }; /** - * Search images - * @param {Object} opts Options - * @param {Function} callback Callback + * Flushes all queued records to the output buffer and calls the + * tlsDataReady() handler on the given connection. + * + * @param c the connection. + * + * @return true on success, false on failure. */ -Docker.prototype.searchImages = function(opts, callback) { - var self = this; - var optsf = { - path: '/images/search?', - method: 'GET', - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; +tls.flush = function(c) { + for(var i = 0; i < c.records.length; ++i) { + var record = c.records[i]; - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + // add record header and fragment + c.tlsData.putByte(record.type); + c.tlsData.putByte(record.version.major); + c.tlsData.putByte(record.version.minor); + c.tlsData.putInt16(record.fragment.length()); + c.tlsData.putBuffer(c.records[i].fragment); } + c.records = []; + return c.tlsDataReady(c); }; /** - * Info - * @param {Object} opts Options (optional) - * @param {Function} callback Callback with info + * Maps a pki.certificateError to a tls.Alert.Description. + * + * @param error the error to map. + * + * @return the alert description. */ -Docker.prototype.info = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var opts = { - path: '/info', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); +var _certErrorToAlertDesc = function(error) { + switch(error) { + case true: + return true; + case forge.pki.certificateError.bad_certificate: + return tls.Alert.Description.bad_certificate; + case forge.pki.certificateError.unsupported_certificate: + return tls.Alert.Description.unsupported_certificate; + case forge.pki.certificateError.certificate_revoked: + return tls.Alert.Description.certificate_revoked; + case forge.pki.certificateError.certificate_expired: + return tls.Alert.Description.certificate_expired; + case forge.pki.certificateError.certificate_unknown: + return tls.Alert.Description.certificate_unknown; + case forge.pki.certificateError.unknown_ca: + return tls.Alert.Description.unknown_ca; + default: + return tls.Alert.Description.bad_certificate; } }; /** - * Version - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * Maps a tls.Alert.Description to a pki.certificateError. + * + * @param desc the alert description. + * + * @return the certificate error. */ -Docker.prototype.version = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var opts = { - path: '/version', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); +var _alertDescToCertError = function(desc) { + switch(desc) { + case true: + return true; + case tls.Alert.Description.bad_certificate: + return forge.pki.certificateError.bad_certificate; + case tls.Alert.Description.unsupported_certificate: + return forge.pki.certificateError.unsupported_certificate; + case tls.Alert.Description.certificate_revoked: + return forge.pki.certificateError.certificate_revoked; + case tls.Alert.Description.certificate_expired: + return forge.pki.certificateError.certificate_expired; + case tls.Alert.Description.certificate_unknown: + return forge.pki.certificateError.certificate_unknown; + case tls.Alert.Description.unknown_ca: + return forge.pki.certificateError.unknown_ca; + default: + return forge.pki.certificateError.bad_certificate; } }; /** - * Ping - * @param {Object} opts Options (optional) - * @param {Function} callback Callback + * Verifies a certificate chain against the given connection's + * Certificate Authority store. + * + * @param c the TLS connection. + * @param chain the certificate chain to verify, with the root or highest + * authority at the end. + * + * @return true if successful, false if not. */ -Docker.prototype.ping = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/_ping', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' +tls.verifyCertificateChain = function(c, chain) { + try { + // Make a copy of c.verifyOptions so that we can modify options.verify + // without modifying c.verifyOptions. + var options = {}; + for (var key in c.verifyOptions) { + options[key] = c.verifyOptions[key]; } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + options.verify = function(vfd, depth, chain) { + // convert pki.certificateError to tls alert description + var desc = _certErrorToAlertDesc(vfd); + + // call application callback + var ret = c.verify(c, vfd, depth, chain); + if(ret !== true) { + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + // throw custom error + var error = new Error('The application rejected the certificate.'); + error.send = true; + error.alert = { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + }; + if(ret.message) { + error.message = ret.message; + } + if(ret.alert) { + error.alert.description = ret.alert; + } + throw error; } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; -/** - * SystemDf equivalent to system/df API Engine - * get usage data information - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.df = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // convert tls alert description to pki.certificateError + if(ret !== vfd) { + ret = _alertDescToCertError(ret); + } + } + + return ret; + }; - var optsf = { - path: '/system/df', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' + // verify chain + forge.pki.verifyCertificateChain(c.caStore, chain, options); + } catch(ex) { + // build tls error if not already customized + var err = ex; + if(typeof err !== 'object' || forge.util.isArray(err)) { + err = { + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(ex) + } + }; + } + if(!('send' in err)) { + err.send = true; + } + if(!('alert' in err)) { + err.alert = { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(err.error) + }; } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // send error + c.error(c, err); } + + return !c.fail; }; /** - * Events - * @param {Object} opts Events options, like 'since' (optional) - * @param {Function} callback Callback + * Creates a new TLS session cache. + * + * @param cache optional map of session ID to cached session. + * @param capacity the maximum size for the cache (default: 100). + * + * @return the new TLS session cache. */ -Docker.prototype.getEvents = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +tls.createSessionCache = function(cache, capacity) { + var rval = null; - var optsf = { - path: '/events?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' + // assume input is already a session cache object + if(cache && cache.getSession && cache.setSession && cache.order) { + rval = cache; + } else { + // create cache + rval = {}; + rval.cache = cache || {}; + rval.capacity = Math.max(capacity || 100, 1); + rval.order = []; + + // store order for sessions, delete session overflow + for(var key in cache) { + if(rval.order.length <= capacity) { + rval.order.push(key); + } else { + delete cache[key]; + } } - }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + // get a session from a session ID (or get any session) + rval.getSession = function(sessionId) { + var session = null; + var key = null; -/** - * Pull is a wrapper around createImage, parsing image's tags. - * @param {String} repoTag Repository tag - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @param {Object} auth Authentication (optional) - * @return {Object} Image - */ -Docker.prototype.pull = function(repoTag, opts, callback, auth) { - var args = util.processArgs(opts, callback); + // if session ID provided, use it + if(sessionId) { + key = forge.util.bytesToHex(sessionId); + } else if(rval.order.length > 0) { + // get first session from cache + key = rval.order[0]; + } - var imageSrc = util.parseRepositoryTag(repoTag); - args.opts.fromImage = imageSrc.repository; - args.opts.tag = imageSrc.tag || 'latest'; + if(key !== null && key in rval.cache) { + // get cached session and remove from cache + session = rval.cache[key]; + delete rval.cache[key]; + for(var i in rval.order) { + if(rval.order[i] === key) { + rval.order.splice(i, 1); + break; + } + } + } - var argsf = [args.opts, args.callback]; - if (auth) { - argsf = [auth, args.opts, args.callback]; + return session; + }; + + // set a session in the cache + rval.setSession = function(sessionId, session) { + // remove session from cache if at capacity + if(rval.order.length === rval.capacity) { + var key = rval.order.shift(); + delete rval.cache[key]; + } + // add session to cache + var key = forge.util.bytesToHex(sessionId); + rval.order.push(key); + rval.cache[key] = session; + }; } - return this.createImage.apply(this, argsf); + + return rval; }; /** - * Like run command from Docker's CLI - * @param {String} image Image name to be used. - * @param {Array} cmd Command to run in array format. - * @param {Object} streamo Output stream - * @param {Object} createOptions Container create options (optional) - * @param {Object} startOptions Container start options (optional) - * @param {Function} callback Callback - * @return {Object} EventEmitter + * Creates a new TLS connection. + * + * See public createConnection() docs for more details. + * + * @param options the options for this connection. + * + * @return the new TLS connection. */ -Docker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (typeof arguments[arguments.length - 1] === 'function') { - return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback); +tls.createConnection = function(options) { + var caStore = null; + if(options.caStore) { + // if CA store is an array, convert it to a CA store object + if(forge.util.isArray(options.caStore)) { + caStore = forge.pki.createCaStore(options.caStore); + } else { + caStore = options.caStore; + } } else { - return this.runPromise(image, cmd, streamo, createOptions, startOptions); + // create empty CA store + caStore = forge.pki.createCaStore(); } -}; - -Docker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (!callback && typeof createOptions === 'function') { - callback = createOptions; - createOptions = {}; - startOptions = {}; - } else if (!callback && typeof startOptions === 'function') { - callback = startOptions; - startOptions = {}; + // setup default cipher suites + var cipherSuites = options.cipherSuites || null; + if(cipherSuites === null) { + cipherSuites = []; + for(var key in tls.CipherSuites) { + cipherSuites.push(tls.CipherSuites[key]); + } } - var hub = new EventEmitter(); - - function handler(err, container) { - if (err) return callback(err, null, container); + // set default entity + var entity = (options.server || false) ? + tls.ConnectionEnd.server : tls.ConnectionEnd.client; - hub.emit('container', container); + // create session cache if requested + var sessionCache = options.sessionCache ? + tls.createSessionCache(options.sessionCache) : null; - container.attach({ - stream: true, - stdout: true, - stderr: true - }, function handler(err, stream) { - if (err) return callback(err, null, container); + // create TLS connection + var c = { + version: {major: tls.Version.major, minor: tls.Version.minor}, + entity: entity, + sessionId: options.sessionId, + caStore: caStore, + sessionCache: sessionCache, + cipherSuites: cipherSuites, + connected: options.connected, + virtualHost: options.virtualHost || null, + verifyClient: options.verifyClient || false, + verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;}, + verifyOptions: options.verifyOptions || {}, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + input: forge.util.createBuffer(), + tlsData: forge.util.createBuffer(), + data: forge.util.createBuffer(), + tlsDataReady: options.tlsDataReady, + dataReady: options.dataReady, + heartbeatReceived: options.heartbeatReceived, + closed: options.closed, + error: function(c, ex) { + // set origin if not set + ex.origin = ex.origin || + ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server'); - hub.emit('stream', stream); + // send TLS alert + if(ex.send) { + tls.queue(c, tls.createAlert(c, ex.alert)); + tls.flush(c); + } - if (streamo) { - if (streamo instanceof Array) { - stream.on('end', function() { - try { - streamo[0].end(); - } catch (e) {} - try { - streamo[1].end(); - } catch (e) {} - }); - container.modem.demuxStream(stream, streamo[0], streamo[1]); - } else { - stream.setEncoding('utf8'); - stream.pipe(streamo, { - end: true - }); - } + // error is fatal by default + var fatal = (ex.fatal !== false); + if(fatal) { + // set fail flag + c.fail = true; } - container.start(startOptions, function(err, data) { - if (err) return callback(err, data, container); - hub.emit('start', container); + // call error handler first + options.error(c, ex); - container.wait(function(err, data) { - hub.emit('data', data); - callback(err, data, container); - }); - }); - }); - } + if(fatal) { + // fatal error, close connection, do not clear fail + c.close(false); + } + }, + deflate: options.deflate || null, + inflate: options.inflate || null + }; - var optsc = { - 'Hostname': '', - 'User': '', - 'AttachStdin': false, - 'AttachStdout': true, - 'AttachStderr': true, - 'Tty': true, - 'OpenStdin': false, - 'StdinOnce': false, - 'Env': null, - 'Cmd': cmd, - 'Image': image, - 'Volumes': {}, - 'VolumesFrom': [] + /** + * Resets a closed TLS connection for reuse. Called in c.close(). + * + * @param clearFail true to clear the fail flag (default: true). + */ + c.reset = function(clearFail) { + c.version = {major: tls.Version.major, minor: tls.Version.minor}; + c.record = null; + c.session = null; + c.peerCertificate = null; + c.state = { + pending: null, + current: null + }; + c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE; + c.fragmented = null; + c.records = []; + c.open = false; + c.handshakes = 0; + c.handshaking = false; + c.isConnected = false; + c.fail = !(clearFail || typeof(clearFail) === 'undefined'); + c.input.clear(); + c.tlsData.clear(); + c.data.clear(); + c.state.current = tls.createConnectionState(c); }; - extend(optsc, createOptions); + // do initial reset of connection + c.reset(); - this.createContainer(optsc, handler); + /** + * Updates the current TLS engine state based on the given record. + * + * @param c the TLS connection. + * @param record the TLS record to act on. + */ + var _update = function(c, record) { + // get record handler (align type in table by subtracting lowest) + var aligned = record.type - tls.ContentType.change_cipher_spec; + var handlers = ctTable[c.entity][c.expect]; + if(aligned in handlers) { + handlers[aligned](c, record); + } else { + // unexpected record + tls.handleUnexpected(c, record); + } + }; - return hub; -}; + /** + * Reads the record header and initializes the next record on the given + * connection. + * + * @param c the TLS connection with the next record. + * + * @return 0 if the input data could be processed, otherwise the + * number of bytes required for data to be processed. + */ + var _readRecordHeader = function(c) { + var rval = 0; -Docker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) { - var self = this; + // get input buffer and its length + var b = c.input; + var len = b.length(); - createOptions = createOptions || {}; - startOptions = startOptions || {}; + // need at least 5 bytes to initialize a record + if(len < 5) { + rval = 5 - len; + } else { + // enough bytes for header + // initialize record + c.record = { + type: b.getByte(), + version: { + major: b.getByte(), + minor: b.getByte() + }, + length: b.getInt16(), + fragment: forge.util.createBuffer(), + ready: false + }; - var optsc = { - 'Hostname': '', - 'User': '', - 'AttachStdin': false, - 'AttachStdout': true, - 'AttachStderr': true, - 'Tty': true, - 'OpenStdin': false, - 'StdinOnce': false, - 'Env': null, - 'Cmd': cmd, - 'Image': image, - 'Volumes': {}, - 'VolumesFrom': [] + // check record version + var compatibleVersion = (c.record.version.major === c.version.major); + if(compatibleVersion && c.session && c.session.version) { + // session version already set, require same minor version + compatibleVersion = (c.record.version.minor === c.version.minor); + } + if(!compatibleVersion) { + c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + + return rval; }; - extend(optsc, createOptions); + /** + * Reads the next record's contents and appends its message to any + * previously fragmented message. + * + * @param c the TLS connection with the next record. + * + * @return 0 if the input data could be processed, otherwise the + * number of bytes required for data to be processed. + */ + var _readRecord = function(c) { + var rval = 0; - var containero; + // ensure there is enough input data to get the entire record + var b = c.input; + var len = b.length(); + if(len < c.record.length) { + // not enough data yet, return how much is required + rval = c.record.length - len; + } else { + // there is enough data to parse the pending record + // fill record fragment and compact input buffer + c.record.fragment.putBytes(b.getBytes(c.record.length)); + b.compact(); - return new this.modem.Promise(function(resolve, reject) { - self.createContainer(optsc).then(function(container) { - containero = container; - return container.attach({ - stream: true, - stdout: true, - stderr: true - }); - }).then(function(stream) { - if (streamo) { - if (streamo instanceof Array) { - stream.on('end', function() { - try { - streamo[0].end(); - } catch (e) {} - try { - streamo[1].end(); - } catch (e) {} - }); - containero.modem.demuxStream(stream, streamo[0], streamo[1]); - } else { - stream.setEncoding('utf8'); - stream.pipe(streamo, { - end: true - }); - } - } - return containero.start(startOptions); - }).then(function(data) { - return containero.wait(); - }).then(function(data) { - resolve([data, containero]); - }).catch(function(err) { - reject(err); - }); - }); -}; + // update record using current read state + var s = c.state.current.read; + if(s.update(c, c.record)) { + // see if there is a previously fragmented message that the + // new record's message fragment should be appended to + if(c.fragmented !== null) { + // if the record type matches a previously fragmented + // record, append the record fragment to it + if(c.fragmented.type === c.record.type) { + // concatenate record fragments + c.fragmented.fragment.putBuffer(c.record.fragment); + c.record = c.fragmented; + } else { + // error, invalid fragmented record + c.error(c, { + message: 'Invalid fragmented record.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: + tls.Alert.Description.unexpected_message + } + }); + } + } -/** - * Init swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmInit = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // record is now ready + c.record.ready = true; + } + } - var optsf = { - path: '/swarm/init', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts + return rval; }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); + /** + * Performs a handshake using the TLS Handshake Protocol, as a client. + * + * This method should only be called if the connection is in client mode. + * + * @param sessionId the session ID to use, null to start a new one. + */ + c.handshake = function(sessionId) { + // error to call this in non-client mode + if(c.entity !== tls.ConnectionEnd.client) { + // not fatal error + c.error(c, { + message: 'Cannot initiate handshake as a server.', + fatal: false }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + } else if(c.handshaking) { + // handshake is already in progress, fail but not fatal error + c.error(c, { + message: 'Handshake already in progress.', + fatal: false + }); + } else { + // clear fail flag on reuse + if(c.fail && !c.open && c.handshakes === 0) { + c.fail = false; + } -/** - * Join swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmJoin = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // now handshaking + c.handshaking = true; - var optsf = { - path: '/swarm/join', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; + // default to blank (new session) + sessionId = sessionId || ''; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + // if a session ID was specified, try to find it in the cache + var session = null; + if(sessionId.length > 0) { + if(c.sessionCache) { + session = c.sessionCache.getSession(sessionId); } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Leave swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmLeave = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/swarm/leave?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: 'node is not part of a Swarm' - }, - options: args.opts - }; + // matching session not found in cache, clear session ID + if(session === null) { + sessionId = ''; + } + } - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + // no session given, grab a session from the cache, if available + if(sessionId.length === 0 && c.sessionCache) { + session = c.sessionCache.getSession(); + if(session !== null) { + sessionId = session.id; } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + } -/** - * Update swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmUpdate = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // set up session + c.session = { + id: sessionId, + version: null, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + certificateRequest: null, + clientCertificate: null, + sp: {}, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; - var optsf = { - path: '/swarm/update?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts + // use existing session information + if(session) { + // only update version on connection, session version not yet set + c.version = session.version; + c.session.sp = session.sp; + } + + // generate new client random + c.session.sp.client_random = tls.createRandom().getBytes(); + + // connection now open + c.open = true; + + // send hello + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientHello(c) + })); + tls.flush(c); + } }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + /** + * Called when TLS protocol data has been received from somewhere and should + * be processed by the TLS engine. + * + * @param data the TLS protocol data, as a string, to process. + * + * @return 0 if the data could be processed, otherwise the number of bytes + * required for data to be processed. + */ + c.process = function(data) { + var rval = 0; + // buffer input data + if(data) { + c.input.putBytes(data); + } -/** - * Inspect a Swarm. - * Warning: This method is not documented in the API - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.swarmInspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // process next record if no failure, process will be called after + // each record is handled (since handling can be asynchronous) + if(!c.fail) { + // reset record if ready and now empty + if(c.record !== null && + c.record.ready && c.record.fragment.isEmpty()) { + c.record = null; + } - var optsf = { - path: '/swarm', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: 'This node is not a swarm manager', - 500: 'server error' + // if there is no pending record, try to read record header + if(c.record === null) { + rval = _readRecordHeader(c); + } + + // read the next record (if record not yet ready) + if(!c.fail && c.record !== null && !c.record.ready) { + rval = _readRecord(c); + } + + // record ready to be handled, update engine state + if(!c.fail && c.record !== null && c.record.ready) { + _update(c, c.record); + } } + + return rval; }; - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; + /** + * Requests that application data be packaged into a TLS record. The + * tlsDataReady handler will be called when the TLS record(s) have been + * prepared. + * + * @param data the application data, as a raw 'binary' encoded string, to + * be sent; to send utf-16/utf-8 string data, use the return value + * of util.encodeUtf8(str). + * + * @return true on success, false on failure. + */ + c.prepare = function(data) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.application_data, + data: forge.util.createBuffer(data) + })); + return tls.flush(c); + }; -Docker.Container = Container; -Docker.Image = Image; -Docker.Volume = Volume; -Docker.Network = Network; -Docker.Service = Service; -Docker.Plugin = Plugin; -Docker.Secret = Secret; -Docker.Task = Task; -Docker.Node = Node; -Docker.Exec = Exec; + /** + * Requests that a heartbeat request be packaged into a TLS record for + * transmission. The tlsDataReady handler will be called when TLS record(s) + * have been prepared. + * + * When a heartbeat response has been received, the heartbeatReceived + * handler will be called with the matching payload. This handler can + * be used to clear a retransmission timer, etc. + * + * @param payload the heartbeat data to send as the payload in the message. + * @param [payloadLength] the payload length to use, defaults to the + * actual payload length. + * + * @return true on success, false on failure. + */ + c.prepareHeartbeatRequest = function(payload, payloadLength) { + if(payload instanceof forge.util.ByteBuffer) { + payload = payload.bytes(); + } + if(typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + c.expectedHeartbeatPayload = payload; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength) + })); + return tls.flush(c); + }; -module.exports = Docker; + /** + * Closes the connection (sends a close_notify alert). + * + * @param clearFail true to clear the fail flag (default: true). + */ + c.close = function(clearFail) { + // save session if connection didn't fail + if(!c.fail && c.sessionCache && c.session) { + // only need to preserve session ID, version, and security params + var session = { + id: c.session.id, + version: c.session.version, + sp: c.session.sp + }; + session.sp.keys = null; + c.sessionCache.setSession(session.id, session); + } + if(c.open) { + // connection no longer open, clear input + c.open = false; + c.input.clear(); -/***/ }), + // if connected or handshaking, send an alert + if(c.isConnected || c.handshaking) { + c.isConnected = c.handshaking = false; -/***/ 3149: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // send close_notify alert + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.close_notify + })); + tls.flush(c); + } -var util = __nccwpck_require__(1604); + // call handler + c.closed(c); + } -/** - * Represents an Exec - * @param {Object} modem docker-modem - * @param {String} id Exec's ID - */ -var Exec = function(modem, id) { - this.modem = modem; - this.id = id; + // reset TLS connection, do not clear fail flag + c.reset(clearFail); + }; + + return c; }; -Exec.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; +/* TLS API */ +module.exports = forge.tls = forge.tls || {}; + +// expose non-functions +for(var key in tls) { + if(typeof tls[key] !== 'function') { + forge.tls[key] = tls[key]; + } +} + +// expose prf_tls1 for testing +forge.tls.prf_tls1 = prf_TLS1; + +// expose sha1 hmac method +forge.tls.hmac_sha1 = hmac_sha1; + +// expose session cache creation +forge.tls.createSessionCache = tls.createSessionCache; /** - * Start the exec call that was setup. + * Creates a new TLS connection. This does not make any assumptions about the + * transport layer that TLS is working on top of, ie: it does not assume there + * is a TCP/IP connection or establish one. A TLS connection is totally + * abstracted away from the layer is runs on top of, it merely establishes a + * secure channel between a client" and a "server". + * + * A TLS connection contains 4 connection states: pending read and write, and + * current read and write. + * + * At initialization, the current read and write states will be null. Only once + * the security parameters have been set and the keys have been generated can + * the pending states be converted into current states. Current states will be + * updated for each record processed. + * + * A custom certificate verify callback may be provided to check information + * like the common name on the server's certificate. It will be called for + * every certificate in the chain. It has the following signature: + * + * variable func(c, certs, index, preVerify) + * Where: + * c The TLS connection + * verified Set to true if certificate was verified, otherwise the alert + * tls.Alert.Description for why the certificate failed. + * depth The current index in the chain, where 0 is the server's cert. + * certs The certificate chain, *NOTE* if the server was anonymous then + * the chain will be empty. + * + * The function returns true on success and on failure either the appropriate + * tls.Alert.Description or an object with 'alert' set to the appropriate + * tls.Alert.Description and 'message' set to a custom error message. If true + * is not returned then the connection will abort using, in order of + * availability, first the returned alert description, second the preVerify + * alert description, and lastly the default 'bad_certificate'. + * + * There are three callbacks that can be used to make use of client-side + * certificates where each takes the TLS connection as the first parameter: + * + * getCertificate(conn, hint) + * The second parameter is a hint as to which certificate should be + * returned. If the connection entity is a client, then the hint will be + * the CertificateRequest message from the server that is part of the + * TLS protocol. If the connection entity is a server, then it will be + * the servername list provided via an SNI extension the ClientHello, if + * one was provided (empty array if not). The hint can be examined to + * determine which certificate to use (advanced). Most implementations + * will just return a certificate. The return value must be a + * PEM-formatted certificate or an array of PEM-formatted certificates + * that constitute a certificate chain, with the first in the array/chain + * being the client's certificate. + * getPrivateKey(conn, certificate) + * The second parameter is an forge.pki X.509 certificate object that + * is associated with the requested private key. The return value must + * be a PEM-formatted private key. + * getSignature(conn, bytes, callback) + * This callback can be used instead of getPrivateKey if the private key + * is not directly accessible in javascript or should not be. For + * instance, a secure external web service could provide the signature + * in exchange for appropriate credentials. The second parameter is a + * string of bytes to be signed that are part of the TLS protocol. These + * bytes are used to verify that the private key for the previously + * provided client-side certificate is accessible to the client. The + * callback is a function that takes 2 parameters, the TLS connection + * and the RSA encrypted (signed) bytes as a string. This callback must + * be called once the signature is ready. + * + * @param options the options for this connection: + * server: true if the connection is server-side, false for client. + * sessionId: a session ID to reuse, null for a new connection. + * caStore: an array of certificates to trust. + * sessionCache: a session cache to use. + * cipherSuites: an optional array of cipher suites to use, + * see tls.CipherSuites. + * connected: function(conn) called when the first handshake completes. + * virtualHost: the virtual server name to use in a TLS SNI extension. + * verifyClient: true to require a client certificate in server mode, + * 'optional' to request one, false not to (default: false). + * verify: a handler used to custom verify certificates in the chain. + * verifyOptions: an object with options for the certificate chain validation. + * See documentation of pki.verifyCertificateChain for possible options. + * verifyOptions.verify is ignored. If you wish to specify a verify handler + * use the verify key. + * getCertificate: an optional callback used to get a certificate or + * a chain of certificates (as an array). + * getPrivateKey: an optional callback used to get a private key. + * getSignature: an optional callback used to get a signature. + * tlsDataReady: function(conn) called when TLS protocol data has been + * prepared and is ready to be used (typically sent over a socket + * connection to its destination), read from conn.tlsData buffer. + * dataReady: function(conn) called when application data has + * been parsed from a TLS record and should be consumed by the + * application, read from conn.data buffer. + * closed: function(conn) called when the connection has been closed. + * error: function(conn, error) called when there was an error. + * deflate: function(inBytes) if provided, will deflate TLS records using + * the deflate algorithm if the server supports it. + * inflate: function(inBytes) if provided, will inflate TLS records using + * the deflate algorithm if the server supports it. * - * @param {object} opts - * @param {function} callback + * @return the new TLS connection. */ -Exec.prototype.start = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +forge.tls.createConnection = tls.createConnection; - var optsf = { - path: '/exec/' + this.id + '/start', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - allowEmpty: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 204: true, - 404: 'no such exec', - 409: 'container stopped/paused', - 500: 'container not running' - }, - options: args.opts - }; +/***/ }), - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; +/***/ 8339: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Resize the exec call that was setup. + * Utility functions for web applications. * - * @param {object} opts - * @param {function} callback + * @author Dave Longley + * + * Copyright (c) 2010-2018 Digital Bazaar, Inc. */ -Exec.prototype.resize = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +var forge = __nccwpck_require__(9177); +var baseN = __nccwpck_require__(2300); - var optsf = { - path: '/exec/' + this.id + '/resize?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such exec', - 500: 'container not running' - }, - options: args.opts - }; +/* Utilities API */ +var util = module.exports = forge.util = forge.util || {}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); +// define setImmediate and nextTick +(function() { + // use native nextTick (unless we're in webpack) + // webpack (or better node-libs-browser polyfill) sets process.browser. + // this way we can detect webpack properly + if(typeof process !== 'undefined' && process.nextTick && !process.browser) { + util.nextTick = process.nextTick; + if(typeof setImmediate === 'function') { + util.setImmediate = setImmediate; + } else { + // polyfill setImmediate with nextTick, older versions of node + // (those w/o setImmediate) won't totally starve IO + util.setImmediate = util.nextTick; + } + return; } -}; -/** - * Get low-level information about the exec call. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Exec.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // polyfill nextTick with native setImmediate + if(typeof setImmediate === 'function') { + util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; + util.nextTick = function(callback) { + return setImmediate(callback); + }; + return; + } - var optsf = { - path: '/exec/' + this.id + '/json', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such exec', - 500: 'server error' - } + /* Note: A polyfill upgrade pattern is used here to allow combining + polyfills. For example, MutationObserver is fast, but blocks UI updates, + so it needs to allow UI updates periodically, so it falls back on + postMessage or setTimeout. */ + + // polyfill with setTimeout + util.setImmediate = function(callback) { + setTimeout(callback, 0); }; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - args.callback(err, data); - }); + // upgrade polyfill to use postMessage + if(typeof window !== 'undefined' && + typeof window.postMessage === 'function') { + var msg = 'forge.setImmediate'; + var callbacks = []; + util.setImmediate = function(callback) { + callbacks.push(callback); + // only send message when one hasn't been sent in + // the current turn of the event loop + if(callbacks.length === 1) { + window.postMessage(msg, '*'); + } + }; + function handler(event) { + if(event.source === window && event.data === msg) { + event.stopPropagation(); + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + } + } + window.addEventListener('message', handler, true); } -}; + // upgrade polyfill to use MutationObserver + if(typeof MutationObserver !== 'undefined') { + // polyfill with MutationObserver + var now = Date.now(); + var attr = true; + var div = document.createElement('div'); + var callbacks = []; + new MutationObserver(function() { + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + }).observe(div, {attributes: true}); + var oldSetImmediate = util.setImmediate; + util.setImmediate = function(callback) { + if(Date.now() - now > 15) { + now = Date.now(); + oldSetImmediate(callback); + } else { + callbacks.push(callback); + // only trigger observer when it hasn't been triggered in + // the current turn of the event loop + if(callbacks.length === 1) { + div.setAttribute('a', attr = !attr); + } + } + }; + } -module.exports = Exec; + util.nextTick = util.setImmediate; +})(); +// check if running under Node.js +util.isNodejs = + typeof process !== 'undefined' && process.versions && process.versions.node; -/***/ }), -/***/ 6689: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while +// it will point to `window` in the main thread. +// To remain compatible with older browsers, we fall back to 'window' if 'self' +// is not available. +util.globalScope = (function() { + if(util.isNodejs) { + return global; + } -var util = __nccwpck_require__(1604); + return typeof self === 'undefined' ? window : self; +})(); -/** - * Represents an image - * @param {Object} modem docker-modem - * @param {String} name Image's name - */ -var Image = function(modem, name) { - this.modem = modem; - this.name = name; +// define isArray +util.isArray = Array.isArray || function(x) { + return Object.prototype.toString.call(x) === '[object Array]'; }; -Image.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Image.prototype.inspect = function(callback) { - var self = this; - - var opts = { - path: '/images/' + this.name + '/json', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } +// define isArrayBuffer +util.isArrayBuffer = function(x) { + return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; }; -/** - * Distribution - * @param {Object} opts - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Image.prototype.distribution = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - - var fopts = { - path: '/distribution/' + this.name + '/json', - method: 'GET', - statusCodes: { - 200: true, - 401: 'no such image', - 500: 'server error' - }, - authconfig: (args.opts) ? args.opts.authconfig : undefined - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(fopts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(fopts, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } +// define isArrayBufferView +util.isArrayBufferView = function(x) { + return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; }; /** - * History - * @param {Function} callback Callback + * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for + * algorithms where bit manipulation, JavaScript limitations, and/or algorithm + * design only allow for byte operations of a limited size. + * + * @param n number of bits. + * + * Throw Error if n invalid. */ -Image.prototype.history = function(callback) { - var self = this; - var opts = { - path: '/images/' + this.name + '/history', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); +function _checkBitsParam(n) { + if(!(n === 8 || n === 16 || n === 24 || n === 32)) { + throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); } -}; +} -/** - * Get - * @param {Function} callback Callback with data stream. - */ -Image.prototype.get = function(callback) { - var self = this; - var opts = { - path: '/images/' + this.name + '/get', - method: 'GET', - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; +// TODO: set ByteBuffer to best available backing +util.ByteBuffer = ByteStringBuffer; - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } -}; +/** Buffer w/BinaryString backing */ /** - * Push - * @param {Object} opts Push options, like 'registry' (optional) - * @param {Function} callback Callback with stream. - * @param {Object} auth Registry authentication + * Constructor for a binary string backed byte buffer. + * + * @param [b] the bytes to wrap (either encoded as string, one byte per + * character, or as an ArrayBuffer or Typed Array). */ -Image.prototype.push = function(opts, callback, auth) { - var self = this; - var args = util.processArgs(opts, callback); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: '/images/' + this.name + '/push?', - method: 'POST', - options: args.opts, - authconfig: args.opts.authconfig || auth, - abortSignal: args.opts.abortSignal, - isStream: isStream, - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; +function ByteStringBuffer(b) { + // TODO: update to match DataBuffer API - delete optsf.options.authconfig; + // the data in this buffer + this.data = ''; + // the pointer for reading from this buffer + this.read = 0; - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); + if(typeof b === 'string') { + this.data = b; + } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { + if(typeof Buffer !== 'undefined' && b instanceof Buffer) { + this.data = b.toString('binary'); + } else { + // convert native buffer to forge buffer + // FIXME: support native buffers internally instead + var arr = new Uint8Array(b); + try { + this.data = String.fromCharCode.apply(null, arr); + } catch(e) { + for(var i = 0; i < arr.length; ++i) { + this.putByte(arr[i]); } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + } + } + } else if(b instanceof ByteStringBuffer || + (typeof b === 'object' && typeof b.data === 'string' && + typeof b.read === 'number')) { + // copy existing buffer + this.data = b.data; + this.read = b.read; } -}; -/** - * Tag - * @param {Object} opts Tag options, like 'repo' (optional) - * @param {Function} callback Callback - */ -Image.prototype.tag = function(opts, callback) { - var self = this; - var optsf = { - path: '/images/' + this.name + '/tag?', - method: 'POST', - options: opts, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 400: 'bad parameter', - 404: 'no such image', - 409: 'conflict', - 500: 'server error' - } - }; + // used for v8 optimization + this._constructedStringLength = 0; +} +util.ByteStringBuffer = ByteStringBuffer; - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); +/* Note: This is an optimization for V8-based browsers. When V8 concatenates + a string, the strings are only joined logically using a "cons string" or + "constructed/concatenated string". These containers keep references to one + another and can result in very large memory usage. For example, if a 2MB + string is constructed by concatenating 4 bytes together at a time, the + memory usage will be ~44MB; so ~22x increase. The strings are only joined + together when an operation requiring their joining takes place, such as + substr(). This function is called when adding data to this buffer to ensure + these types of strings are periodically joined to reduce the memory + footprint. */ +var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; +util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { + this._constructedStringLength += x; + if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { + // this substr() should cause the constructed string to join + this.data.substr(0, 1); + this._constructedStringLength = 0; } }; /** - * Removes the image - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. */ -Image.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +util.ByteStringBuffer.prototype.length = function() { + return this.data.length - this.read; +}; - var optsf = { - path: '/images/' + this.name + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such image', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util.ByteStringBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putByte = function(b) { + return this.putBytes(String.fromCharCode(b)); +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { + b = String.fromCharCode(b); + var d = this.data; + while(n > 0) { + if(n & 1) { + d += b; + } + n >>>= 1; + if(n > 0) { + b += b; + } } + this.data = d; + this._optimizeConstructedString(n); + return this; }; -module.exports = Image; +/** + * Puts bytes in this buffer. + * + * @param bytes the bytes (as a binary encoded string) to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putBytes = function(bytes) { + this.data += bytes; + this._optimizeConstructedString(bytes.length); + return this; +}; +/** + * Puts a UTF-16 encoded string into this buffer. + * + * @param str the string to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putString = function(str) { + return this.putBytes(util.encodeUtf8(str)); +}; -/***/ }), +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt16 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; -/***/ 9780: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt24 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; -var util = __nccwpck_require__(1604); +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt32 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; /** - * Represents an network - * @param {Object} modem docker-modem - * @param {String} id Network's id + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. */ -var Network = function(modem, id) { - this.modem = modem; - this.id = id; +util.ByteStringBuffer.prototype.putInt16Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF)); }; -Network.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt24Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF)); +}; /** - * Inspect - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Id only if callback isn't specified. + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. */ -Network.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +util.ByteStringBuffer.prototype.putInt32Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 24 & 0xFF)); +}; - var opts = { - path: '/networks/' + this.id + '?', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such network', - 500: 'server error' - }, - options: args.opts - }; +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + var bytes = ''; + do { + n -= 8; + bytes += String.fromCharCode((i >> n) & 0xFF); + } while(n > 0); + return this.putBytes(bytes); +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { + // putInt checks n + if(i < 0) { + i += 2 << (n - 1); } + return this.putInt(i, n); }; /** - * Removes the network - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. */ -Network.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +util.ByteStringBuffer.prototype.putBuffer = function(buffer) { + return this.putBytes(buffer.getBytes()); +}; - var optsf = { - path: '/networks/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such network', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util.ByteStringBuffer.prototype.getByte = function() { + return this.data.charCodeAt(this.read++); +}; +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.ByteStringBuffer.prototype.getInt16 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 8 ^ + this.data.charCodeAt(this.read + 1)); + this.read += 2; + return rval; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.ByteStringBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 16 ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2)); + this.read += 3; + return rval; }; /** - * Connects a container to a network - * @param {[Object]} opts Connect options (optional) - * @param {Function} callback Callback + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. */ -Network.prototype.connect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +util.ByteStringBuffer.prototype.getInt32 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 24 ^ + this.data.charCodeAt(this.read + 1) << 16 ^ + this.data.charCodeAt(this.read + 2) << 8 ^ + this.data.charCodeAt(this.read + 3)); + this.read += 4; + return rval; +}; - var optsf = { - path: '/networks/' + this.id + '/connect', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: 'network or container is not found', - 500: 'server error' - }, - options: args.opts - }; +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.ByteStringBuffer.prototype.getInt16Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8); + this.read += 2; + return rval; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.ByteStringBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16); + this.read += 3; + return rval; }; +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.ByteStringBuffer.prototype.getInt32Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16 ^ + this.data.charCodeAt(this.read + 3) << 24); + this.read += 4; + return rval; +}; /** - * Disconnects a container from a network - * @param {[Object]} opts Disconnect options (optional) - * @param {Function} callback Callback + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by ceil(n/8). + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. */ -Network.prototype.disconnect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +util.ByteStringBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.charCodeAt(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; - var optsf = { - path: '/networks/' + this.id + '/disconnect', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: 'network or container is not found', - 500: 'server error' - }, - options: args.opts - }; +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.ByteStringBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. Note that the resulting string is binary encoded (in node.js this + * encoding is referred to as `binary`, it is *not* `utf8`). + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util.ByteStringBuffer.prototype.getBytes = function(count) { + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); } + return rval; }; - - - -module.exports = Network; - - -/***/ }), - -/***/ 2297: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(1604); +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util.ByteStringBuffer.prototype.bytes = function(count) { + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; /** - * Represents an Node - * @param {Object} modem docker-modem - * @param {String} id Node's ID + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. */ -var Node = function(modem, id) { - this.modem = modem; - this.id = id; +util.ByteStringBuffer.prototype.at = function(i) { + return this.data.charCodeAt(this.read + i); }; -Node.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; - /** - * Query Docker for Node details. + * Puts a byte at the given index without modifying the read pointer. * - * @param {Object} opts Options (optional) - * @param {function} callback + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. */ -Node.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/nodes/' + this.id, - method: 'GET', - abortSignal: args.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +util.ByteStringBuffer.prototype.setAt = function(i, b) { + this.data = this.data.substr(0, this.read + i) + + String.fromCharCode(b) + + this.data.substr(this.read + i + 1); + return this; }; - /** - * Update a node. + * Gets the last byte without modifying the read pointer. * - * @param {object} opts - * @param {function} callback + * @return the last byte. */ -Node.prototype.update = function(opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - } - - var optsf = { - path: '/nodes/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 406: 'node is not part of a swarm', - 500: 'server error' - }, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } +util.ByteStringBuffer.prototype.last = function() { + return this.data.charCodeAt(this.data.length - 1); }; - /** - * Remove a Node. - * Warning: This method is not documented in the API. + * Creates a copy of this buffer. * - * @param {object} opts - * @param {function} callback + * @return the copy. */ -Node.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/nodes/' + this.id + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 500: 'server error' - }, - options: args.opts - }; +util.ByteStringBuffer.prototype.copy = function() { + var c = util.createBuffer(this.data); + c.read = this.read; + return c; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.compact = function() { + if(this.read > 0) { + this.data = this.data.slice(this.read); + this.read = 0; } + return this; }; - -module.exports = Node; - - -/***/ }), - -/***/ 6606: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(1604); - /** - * Represents a plugin - * @param {Object} modem docker-modem - * @param {String} name Plugin's name + * Clears this buffer. + * + * @return this buffer. */ -var Plugin = function(modem, name, remote) { - this.modem = modem; - this.name = name; - this.remote = remote || name; +util.ByteStringBuffer.prototype.clear = function() { + this.data = ''; + this.read = 0; + return this; }; -Plugin.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; - /** - * Inspect + * Shortens this buffer by triming bytes off of the end of this buffer. * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. + * @param count the number of bytes to trim off. + * + * @return this buffer. */ -Plugin.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin is not installed', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +util.ByteStringBuffer.prototype.truncate = function(count) { + var len = Math.max(0, this.length() - count); + this.data = this.data.substr(this.read, len); + this.read = 0; + return this; }; /** - * Removes the plugin - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. */ -Plugin.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin is not installed', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); +util.ByteStringBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.length; ++i) { + var b = this.data.charCodeAt(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); } + return rval; }; /** - * get privileges - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @return {Object} Name only if callback isn't specified. + * Converts this buffer to a UTF-16 string (standard JavaScript string). + * + * @return a UTF-16 string. */ -Plugin.prototype.privileges = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/privileges?', - method: 'GET', - options: { - 'remote': this.remote - }, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +util.ByteStringBuffer.prototype.toString = function() { + return util.decodeUtf8(this.bytes()); }; +/** End Buffer w/BinaryString backing */ + +/** Buffer w/UInt8Array backing */ /** - * Installs a new plugin - * @param {Object} opts Create options - * @param {Function} callback Callback + * FIXME: Experimental. Do not use yet. + * + * Constructor for an ArrayBuffer-backed byte buffer. + * + * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a + * TypedArray. + * + * If a string is given, its encoding should be provided as an option, + * otherwise it will default to 'binary'. A 'binary' string is encoded such + * that each character is one byte in length and size. + * + * If an ArrayBuffer, DataView, or TypedArray is given, it will be used + * *directly* without any copying. Note that, if a write to the buffer requires + * more space, the buffer will allocate a new backing ArrayBuffer to + * accommodate. The starting read and write offsets for the buffer may be + * given as options. + * + * @param [b] the initial bytes for this buffer. + * @param options the options to use: + * [readOffset] the starting read offset to use (default: 0). + * [writeOffset] the starting write offset to use (default: the + * length of the first parameter). + * [growSize] the minimum amount, in bytes, to grow the buffer by to + * accommodate writes (default: 1024). + * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the + * first parameter, if it is a string (default: 'binary'). */ -Plugin.prototype.pull = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +function DataBuffer(b, options) { + // default options + options = options || {}; - if(args.opts._query && !args.opts._query.name) { - args.opts._query.name = this.name; - } - if(args.opts._query && !args.opts._query.remote) { - args.opts._query.remote = this.remote; - } + // pointers for read from/write to buffer + this.read = options.readOffset || 0; + this.growSize = options.growSize || 1024; - var optsf = { - path: '/plugins/pull?', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - options: args.opts, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' + var isArrayBuffer = util.isArrayBuffer(b); + var isArrayBufferView = util.isArrayBufferView(b); + if(isArrayBuffer || isArrayBufferView) { + // use ArrayBuffer directly + if(isArrayBuffer) { + this.data = new DataView(b); + } else { + // TODO: adjust read/write offset based on the type of view + // or specify that this must be done in the options ... that the + // offsets are byte-based + this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + this.write = ('writeOffset' in options ? + options.writeOffset : this.data.byteLength); + return; } -}; - -/** - * Enable - * @param {Object} opts Plugin enable options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.enable = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); + // initialize to empty array buffer and add any given bytes using putBytes + this.data = new DataView(new ArrayBuffer(0)); + this.write = 0; - var optsf = { - path: '/plugins/' + this.name + '/enable?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - }, - options: args.opts - }; + if(b !== null && b !== undefined) { + this.putBytes(b); + } - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + if('writeOffset' in options) { + this.write = options.writeOffset; } -}; +} +util.DataBuffer = DataBuffer; /** - * Disable - * @param {Object} opts Plugin disable options (optional) - * @param {Function} callback Callback + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. */ -Plugin.prototype.disable = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/disable', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +util.DataBuffer.prototype.length = function() { + return this.write - this.read; }; /** - * Push - * @param {Object} opts Plugin push options (optional) - * @param {Function} callback Callback + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. */ -Plugin.prototype.push = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/push', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin not installed', - 500: 'server error' - }, - options: args.opts - }; +util.DataBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +/** + * Ensures this buffer has enough empty space to accommodate the given number + * of bytes. An optional parameter may be given that indicates a minimum + * amount to grow the buffer if necessary. If the parameter is not given, + * the buffer will be grown by some previously-specified default amount + * or heuristic. + * + * @param amount the number of bytes to accommodate. + * @param [growSize] the minimum amount, in bytes, to grow the buffer by if + * necessary. + */ +util.DataBuffer.prototype.accommodate = function(amount, growSize) { + if(this.length() >= amount) { + return this; } + growSize = Math.max(growSize || this.growSize, amount); + + // grow buffer + var src = new Uint8Array( + this.data.buffer, this.data.byteOffset, this.data.byteLength); + var dst = new Uint8Array(this.length() + growSize); + dst.set(src); + this.data = new DataView(dst.buffer); + + return this; }; /** - * COnfigure - * @param {Object} opts Plugin configure options (optional) - * @param {Function} callback Callback + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. */ -Plugin.prototype.configure = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/set', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin not installed', - 500: 'server error' - }, - options: args.opts - }; +util.DataBuffer.prototype.putByte = function(b) { + this.accommodate(1); + this.data.setUint8(this.write++, b); + return this; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.fillWithByte = function(b, n) { + this.accommodate(n); + for(var i = 0; i < n; ++i) { + this.data.setUint8(b); } + return this; }; - /** - * Upgrade plugin + * Puts bytes in this buffer. The bytes may be given as a string, an + * ArrayBuffer, a DataView, or a TypedArray. * - * @param {object} auth - * @param {object} opts - * @param {function} callback + * @param bytes the bytes to put. + * @param [encoding] the encoding for the first parameter ('binary', 'utf8', + * 'utf16', 'hex'), if it is a string (default: 'binary'). + * + * @return this buffer. */ -Plugin.prototype.upgrade = function(auth, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; +util.DataBuffer.prototype.putBytes = function(bytes, encoding) { + if(util.isArrayBufferView(bytes)) { + var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var len = src.byteLength - src.byteOffset; + this.accommodate(len); + var dst = new Uint8Array(this.data.buffer, this.write); + dst.set(src); + this.write += len; + return this; } - var optsf = { - path: '/plugins/' + this.name + '/upgrade?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'plugin not installed', - 500: 'server error' - }, - authconfig: auth, - options: opts - }; + if(util.isArrayBuffer(bytes)) { + var src = new Uint8Array(bytes); + this.accommodate(src.byteLength); + var dst = new Uint8Array(this.data.buffer); + dst.set(src, this.write); + this.write += src.byteLength; + return this; + } - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); + // bytes is a util.DataBuffer or equivalent + if(bytes instanceof util.DataBuffer || + (typeof bytes === 'object' && + typeof bytes.read === 'number' && typeof bytes.write === 'number' && + util.isArrayBufferView(bytes.data))) { + var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); + this.accommodate(src.byteLength); + var dst = new Uint8Array(bytes.data.byteLength, this.write); + dst.set(src); + this.write += src.byteLength; + return this; } -}; + if(bytes instanceof util.ByteStringBuffer) { + // copy binary string and process as the same as a string parameter below + bytes = bytes.data; + encoding = 'binary'; + } -module.exports = Plugin; + // string conversion + encoding = encoding || 'binary'; + if(typeof bytes === 'string') { + var view; + // decode from string + if(encoding === 'hex') { + this.accommodate(Math.ceil(bytes.length / 2)); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.hex.decode(bytes, view, this.write); + return this; + } + if(encoding === 'base64') { + this.accommodate(Math.ceil(bytes.length / 4) * 3); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.base64.decode(bytes, view, this.write); + return this; + } -/***/ }), + // encode text as UTF-8 bytes + if(encoding === 'utf8') { + // encode as UTF-8 then decode string as raw binary + bytes = util.encodeUtf8(bytes); + encoding = 'binary'; + } -/***/ 9934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // decode string as raw binary + if(encoding === 'binary' || encoding === 'raw') { + // one byte per character + this.accommodate(bytes.length); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.raw.decode(view); + return this; + } -var util = __nccwpck_require__(1604); + // encode text as UTF-16 bytes + if(encoding === 'utf16') { + // two bytes per character + this.accommodate(bytes.length * 2); + view = new Uint16Array(this.data.buffer, this.write); + this.write += util.text.utf16.encode(view); + return this; + } + + throw new Error('Invalid encoding: ' + encoding); + } + + throw Error('Invalid parameter: ' + bytes); +}; /** - * Represents a secret - * @param {Object} modem docker-modem - * @param {String} id Secret's id + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. */ -var Secret = function(modem, id) { - this.modem = modem; - this.id = id; +util.DataBuffer.prototype.putBuffer = function(buffer) { + this.putBytes(buffer); + buffer.clear(); + return this; }; -Secret.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; - /** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. + * Puts a string into this buffer. + * + * @param str the string to put. + * @param [encoding] the encoding for the string (default: 'utf16'). + * + * @return this buffer. */ -Secret.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/secrets/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'secret not found', - 406: 'node is not part of a swarm', - 500: 'server error' - } - }; +util.DataBuffer.prototype.putString = function(str) { + return this.putBytes(str, 'utf16'); +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt16 = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i); + this.write += 2; + return this; }; /** - * Update a secret. + * Puts a 24-bit integer in this buffer in big-endian order. * - * @param {object} opts - * @param {function} callback + * @param i the 24-bit integer. + * + * @return this buffer. */ -Secret.prototype.update = function(opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - } +util.DataBuffer.prototype.putInt24 = function(i) { + this.accommodate(3); + this.data.setInt16(this.write, i >> 8 & 0xFFFF); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.write += 3; + return this; +}; - var optsf = { - path: '/secrets/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'secret not found', - 500: 'server error' - }, - options: opts - }; +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt32 = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i); + this.write += 4; + return this; +}; - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt16Le = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i, true); + this.write += 2; + return this; }; +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt24Le = function(i) { + this.accommodate(3); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); + this.write += 3; + return this; +}; /** - * Removes the secret - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. */ -Secret.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); +util.DataBuffer.prototype.putInt32Le = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i, true); + this.write += 4; + return this; +}; - var optsf = { - path: '/secrets/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'secret not found', - 500: 'server error' - }, - options: args.opts - }; +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + do { + n -= 8; + this.data.setInt8(this.write++, (i >> n) & 0xFF); + } while(n > 0); + return this; +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putSignedInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + if(i < 0) { + i += 2 << (n - 1); } + return this.putInt(i, n); }; +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util.DataBuffer.prototype.getByte = function() { + return this.data.getInt8(this.read++); +}; +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.DataBuffer.prototype.getInt16 = function() { + var rval = this.data.getInt16(this.read); + this.read += 2; + return rval; +}; -module.exports = Secret; +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.DataBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.getInt16(this.read) << 8 ^ + this.data.getInt8(this.read + 2)); + this.read += 3; + return rval; +}; +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.DataBuffer.prototype.getInt32 = function() { + var rval = this.data.getInt32(this.read); + this.read += 4; + return rval; +}; -/***/ }), +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.DataBuffer.prototype.getInt16Le = function() { + var rval = this.data.getInt16(this.read, true); + this.read += 2; + return rval; +}; -/***/ 8866: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.DataBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.getInt8(this.read) ^ + this.data.getInt16(this.read + 1, true) << 8); + this.read += 3; + return rval; +}; -var util = __nccwpck_require__(1604); +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.DataBuffer.prototype.getInt32Le = function() { + var rval = this.data.getInt32(this.read, true); + this.read += 4; + return rval; +}; /** - * Represents an Service - * @param {Object} modem docker-modem - * @param {String} id Service's ID + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. */ -var Service = function(modem, id) { - this.modem = modem; - this.id = id; +util.DataBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.getInt8(this.read++); + n -= 8; + } while(n > 0); + return rval; }; -Service.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; - /** - * Query Docker for service details. + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. * - * @param {Object} opts Options (optional) - * @param {function} callback + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. */ -Service.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/services/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +util.DataBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; } + return x; }; /** - * Delete Service + * Reads bytes out as a binary encoded string and clears them from the + * buffer. * - * @param {Object} opts Options (optional) - * @param {function} callback + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. */ -Service.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/services/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such service', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); +util.DataBuffer.prototype.getBytes = function(count) { + // TODO: deprecate this method, it is poorly named and + // this.toString('binary') replaces it + // add a toTypedArray()/toArrayBuffer() function + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); } + return rval; }; /** - * Update service + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. * - * @param {object} auth - * @param {object} opts - * @param {function} callback + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. */ -Service.prototype.update = function(auth, opts, callback) { - var self = this; - if (!callback) { - var t = typeof opts; - if(t === 'function'){ - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (t === 'undefined'){ - opts = auth; - auth = opts.authconfig || undefined; - } - } - - var optsf = { - path: '/services/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error' - }, - authconfig: auth, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } +util.DataBuffer.prototype.bytes = function(count) { + // TODO: deprecate this method, it is poorly named, add "getString()" + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); }; - - /** - * Service logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. */ -Service.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, {}); - - var optsf = { - path: '/services/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +util.DataBuffer.prototype.at = function(i) { + return this.data.getUint8(this.read + i); }; - - -module.exports = Service; - - -/***/ }), - -/***/ 1385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(1604); - /** - * Represents an Task - * @param {Object} modem docker-modem - * @param {String} id Task's ID + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. */ -var Task = function(modem, id) { - this.modem = modem; - this.id = id; - - this.defaultOptions = { - log: {} - }; +util.DataBuffer.prototype.setAt = function(i, b) { + this.data.setUint8(i, b); + return this; }; -Task.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; - /** - * Query Docker for Task details. + * Gets the last byte without modifying the read pointer. * - * @param {Object} opts Options (optional) - * @param {function} callback + * @return the last byte. */ -Task.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/tasks/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'unknown task', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } +util.DataBuffer.prototype.last = function() { + return this.data.getUint8(this.write - 1); }; /** - * Task logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data + * Creates a copy of this buffer. + * + * @return the copy. */ -Task.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); - - var optsf = { - path: '/tasks/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 101: true, - 200: true, - 404: 'no such container', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; +util.DataBuffer.prototype.copy = function() { + return new util.DataBuffer(this); +}; - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.compact = function() { + if(this.read > 0) { + var src = new Uint8Array(this.data.buffer, this.read); + var dst = new Uint8Array(src.byteLength); + dst.set(src); + this.data = new DataView(dst); + this.write -= this.read; + this.read = 0; } + return this; }; +/** + * Clears this buffer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.clear = function() { + this.data = new DataView(new ArrayBuffer(0)); + this.read = this.write = 0; + return this; +}; -module.exports = Task; - - -/***/ }), - -/***/ 1604: -/***/ ((module) => { - -// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js - -var arr = []; -var each = arr.forEach; -var slice = arr.slice; - -module.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; +/** + * Shortens this buffer by triming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util.DataBuffer.prototype.truncate = function(count) { + this.write = Math.max(0, this.length() - count); + this.read = Math.min(this.read, this.write); + return this; }; -module.exports.processArgs = function(opts, callback, defaultOpts) { - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util.DataBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.byteLength; ++i) { + var b = this.data.getUint8(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); } - return { - callback: callback, - opts: module.exports.extend({}, defaultOpts, opts) - }; + return rval; }; - /** - * Parse the given repo tag name (as a string) and break it out into repo/tag pair. - * // if given the input http://localhost:8080/woot:latest - * { - * repository: 'http://localhost:8080/woot', - * tag: 'latest' - * } - * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest' - * @return {Object} input parsed into the repo and tag. + * Converts this buffer to a string, using the given encoding. If no + * encoding is given, 'utf8' (UTF-8) is used. + * + * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', + * 'base64' (default: 'utf8'). + * + * @return a string representation of the bytes in this buffer. */ -module.exports.parseRepositoryTag = function(input) { - var separatorPos; - var digestPos = input.indexOf('@'); - var colonPos = input.lastIndexOf(':'); - // @ symbol is more important - if (digestPos >= 0) { - separatorPos = digestPos; - } else if (colonPos >= 0) { - separatorPos = colonPos; - } else { - // no colon nor @ - return { - repository: input - }; - } +util.DataBuffer.prototype.toString = function(encoding) { + var view = new Uint8Array(this.data, this.read, this.length()); + encoding = encoding || 'utf8'; - // last colon is either the tag (or part of a port designation) - var tag = input.slice(separatorPos + 1); + // encode to string + if(encoding === 'binary' || encoding === 'raw') { + return util.binary.raw.encode(view); + } + if(encoding === 'hex') { + return util.binary.hex.encode(view); + } + if(encoding === 'base64') { + return util.binary.base64.encode(view); + } - // if it contains a / its not a tag and is part of the url - if (tag.indexOf('/') === -1) { - return { - repository: input.slice(0, separatorPos), - tag: tag - }; + // decode to text + if(encoding === 'utf8') { + return util.text.utf8.decode(view); + } + if(encoding === 'utf16') { + return util.text.utf16.decode(view); } - return { - repository: input - }; + throw new Error('Invalid encoding: ' + encoding); }; +/** End Buffer w/UInt8Array backing */ -/***/ }), - -/***/ 4877: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(1604); +/** + * Creates a buffer that stores bytes. A value may be given to populate the + * buffer with data. This value can either be string of encoded bytes or a + * regular string of characters. When passing a string of binary encoded + * bytes, the encoding `raw` should be given. This is also the default. When + * passing a string of characters, the encoding `utf8` should be given. + * + * @param [input] a string with encoded bytes to store in the buffer. + * @param [encoding] (default: 'raw', other: 'utf8'). + */ +util.createBuffer = function(input, encoding) { + // TODO: deprecate, use new ByteBuffer() instead + encoding = encoding || 'raw'; + if(input !== undefined && encoding === 'utf8') { + input = util.encodeUtf8(input); + } + return new util.ByteBuffer(input); +}; /** - * Represents a volume - * @param {Object} modem docker-modem - * @param {String} name Volume's name + * Fills a string with a particular value. If you want the string to be a byte + * string, pass in String.fromCharCode(theByte). + * + * @param c the character to fill the string with, use String.fromCharCode + * to fill the string with a byte value. + * @param n the number of characters of value c to fill with. + * + * @return the filled string. */ -var Volume = function(modem, name) { - this.modem = modem; - this.name = name; +util.fillString = function(c, n) { + var s = ''; + while(n > 0) { + if(n & 1) { + s += c; + } + n >>>= 1; + if(n > 0) { + c += c; + } + } + return s; }; -Volume.prototype[(__nccwpck_require__(3837).inspect.custom)] = function() { return this; }; - /** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. + * Performs a per byte XOR between two byte strings and returns the result as a + * string of bytes. + * + * @param s1 first string of bytes. + * @param s2 second string of bytes. + * @param n the number of bytes to XOR. + * + * @return the XOR'd result. */ -Volume.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes/' + this.name, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such volume', - 500: 'server error' +util.xorBytes = function(s1, s2, n) { + var s3 = ''; + var b = ''; + var t = ''; + var i = 0; + var c = 0; + for(; n > 0; --n, ++i) { + b = s1.charCodeAt(i) ^ s2.charCodeAt(i); + if(c >= 10) { + s3 += t; + t = ''; + c = 0; } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); + t += String.fromCharCode(b); + ++c; } + s3 += t; + return s3; }; /** - * Removes the volume - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback + * Converts a hex string into a 'binary' encoded string of bytes. + * + * @param hex the hexadecimal string to convert. + * + * @return the binary-encoded string of bytes. */ -Volume.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes/' + this.name, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 204: true, - 404: 'no such volume', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); +util.hexToBytes = function(hex) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." + var rval = ''; + var i = 0; + if(hex.length & 1 == 1) { + // odd number of characters, convert first character alone + i = 1; + rval += String.fromCharCode(parseInt(hex[0], 16)); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); } + return rval; }; -module.exports = Volume; - - -/***/ }), - -/***/ 1205: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(1223); - -var noop = function() {}; - -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; +/** + * Converts a 'binary' encoded string of bytes to hex. + * + * @param bytes the byte string to convert. + * + * @return the string of hexadecimal characters. + */ +util.bytesToHex = function(bytes) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." + return util.createBuffer(bytes).toHex(); }; -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +/** + * Converts an 32-bit integer to 4-big-endian byte string. + * + * @param i the integer. + * + * @return the byte string. + */ +util.int32ToBytes = function(i) { + return ( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); }; -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - - callback = once(callback || noop); - - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; - - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; - - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; - - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; - - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; - - var onerror = function(err) { - callback.call(stream, err); - }; - - var onclose = function() { - process.nextTick(onclosenexttick); - }; - - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); - }; - - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +// base64 characters, reverse mapping +var _base64 = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +var _base64Idx = [ +/*43 -43 = 0*/ +/*'+', 1, 2, 3,'/' */ + 62, -1, -1, -1, 63, - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } +/*'0','1','2','3','4','5','6','7','8','9' */ + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, - if (isChildProcess(stream)) stream.on('exit', onexit); +/*15, 16, 17,'=', 19, 20, 21 */ + -1, -1, -1, 64, -1, -1, -1, - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); +/*65 - 43 = 22*/ +/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, - return function() { - cancelled = true; - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -}; +/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -module.exports = eos; +/*91 - 43 = 48 */ +/*48, 49, 50, 51, 52, 53 */ + -1, -1, -1, -1, -1, -1, +/*97 - 43 = 54*/ +/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, -/***/ }), +/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 +]; -/***/ 1133: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// base58 characters (Bitcoin alphabet) +var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; -var debug; +/** + * Base64 encodes a 'binary' encoded string of bytes. + * + * @param input the binary encoded string of bytes to base64-encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output. + */ +util.encode64 = function(input, maxline) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = __nccwpck_require__(8237)("follow-redirects"); + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); } - catch (error) { /* */ } - if (typeof debug !== "function") { - debug = function () { /* */ }; + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); } } - debug.apply(null, arguments); + output += line; + return output; }; +/** + * Base64 decodes a string into a 'binary' encoded string of bytes. + * + * @param input the base64-encoded input. + * + * @return the binary encoded string. + */ +util.decode64 = function(input) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." -/***/ }), - -/***/ 7707: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var url = __nccwpck_require__(7310); -var URL = url.URL; -var http = __nccwpck_require__(3685); -var https = __nccwpck_require__(5687); -var Writable = (__nccwpck_require__(2781).Writable); -var assert = __nccwpck_require__(9491); -var debug = __nccwpck_require__(1133); - -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); -// Error types with codes -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded" -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); + var output = ''; + var enc1, enc2, enc3, enc4; + var i = 0; -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); + output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); + if(enc3 !== 64) { + // decoded at least 2 bytes + output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); + if(enc4 !== 64) { + // decoded 3 bytes + output += String.fromCharCode(((enc3 & 3) << 6) | enc4); + } + } } - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - self._processResponse(response); - }; - - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); - -RedirectableRequest.prototype.abort = function () { - abortRequest(this._currentRequest); - this.emit("abort"); + return output; }; -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } - - // Validate input and shift parameters if necessary - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } +/** + * Encodes the given string of characters (a standard JavaScript + * string) as a binary encoded string where the bytes represent + * a UTF-8 encoded string of characters. Non-ASCII characters will be + * encoded as multiple bytes according to UTF-8. + * + * @param str a standard string of characters to encode. + * + * @return the binary encoded string. + */ +util.encodeUtf8 = function(str) { + return unescape(encodeURIComponent(str)); }; -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (typeof data === "function") { - callback = data; - data = encoding = null; - } - else if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } +/** + * Decodes a binary encoded string that contains bytes that + * represent a UTF-8 encoded string of characters -- into a + * string of characters (a standard JavaScript string). + * + * @param str the binary encoded string to decode. + * + * @return the resulting standard string of characters. + */ +util.decodeUtf8 = function(str) { + return decodeURIComponent(escape(str)); }; -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); +// binary encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util.binary = { + raw: {}, + hex: {}, + base64: {}, + base58: {}, + baseN : { + encode: baseN.encode, + decode: baseN.decode + } }; -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); +/** + * Encodes a Uint8Array as a binary-encoded string. This encoding uses + * a value between 0 and 255 for each character. + * + * @param bytes the Uint8Array to encode. + * + * @return the binary-encoded string. + */ +util.binary.raw.encode = function(bytes) { + return String.fromCharCode.apply(null, bytes); }; -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); +/** + * Decodes a binary-encoded string to a Uint8Array. This encoding uses + * a value between 0 and 255 for each character. + * + * @param str the binary-encoded string to decode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.raw.decode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length); } - - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); } + return output ? (j - offset) : out; +}; - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } - - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - if (callback) { - self.removeListener("timeout", callback); - } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); - } - } +/** + * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or + * ByteBuffer as a string of hexadecimal characters. + * + * @param bytes the bytes to convert. + * + * @return the string of hexadecimal characters. + */ +util.binary.hex.encode = util.bytesToHex; - // Attach callback if passed - if (callback) { - this.on("timeout", callback); +/** + * Decodes a hex-encoded string to a Uint8Array. + * + * @param hex the hexadecimal string to convert. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.hex.decode = function(hex, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(hex.length / 2)); } - - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); + offset = offset || 0; + var i = 0, j = offset; + if(hex.length & 1) { + // odd number of characters, convert first character alone + i = 1; + out[j++] = parseInt(hex[0], 16); } - else { - this._currentRequest.once("socket", startTimer); + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + out[j++] = parseInt(hex.substr(i, 2), 16); } - - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - - return this; + return output ? (j - offset) : out; }; -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); - -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); - -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } +/** + * Base64-encodes a Uint8Array. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output string. + */ +util.binary.base64.encode = function(input, maxline) { + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); } - delete options.host; - } - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); } } + output += line; + return output; }; - -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - this.emit("error", new TypeError("Unsupported protocol " + protocol)); - return; +/** + * Decodes a base64-encoded string to a Uint8Array. + * + * @param input the base64-encoded input string. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.base64.decode = function(input, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(input.length / 4) * 3); } - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.substr(0, protocol.length - 1); - this._options.agent = this._options.agents[scheme]; - } + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); - // Create the native request - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - this._currentUrl = url.format(this._options); + offset = offset || 0; + var enc1, enc2, enc3, enc4; + var i = 0, j = offset; - // Set up event handlers - request._redirectable = this; - for (var e = 0; e < events.length; e++) { - request.on(events[e], eventHandlers[events[e]]); - } + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end. - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - /* istanbul ignore else */ - if (request === self._currentRequest) { - // Report any write errors - /* istanbul ignore if */ - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - /* istanbul ignore else */ - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } + out[j++] = (enc1 << 2) | (enc2 >> 4); + if(enc3 !== 64) { + // decoded at least 2 bytes + out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); + if(enc4 !== 64) { + // decoded 3 bytes + out[j++] = ((enc3 & 3) << 6) | enc4; } - }()); - } -}; - -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); + } } - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - - // Clean up - this._requestBodyBuffers = []; - return; - } + // make sure result is the exact decoded length + return output ? (j - offset) : out.subarray(0, j); +}; - // The response is a redirect, so abort the current request - abortRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); +// add support for base58 encoding/decoding with Bitcoin alphabet +util.binary.base58.encode = function(input, maxline) { + return util.binary.baseN.encode(input, _base58, maxline); +}; +util.binary.base58.decode = function(input, maxline) { + return util.binary.baseN.decode(input, _base58, maxline); +}; - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - this.emit("error", new TooManyRedirectsError()); - return; - } +// text encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util.text = { + utf8: {}, + utf16: {} +}; - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); - - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = url.parse(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); - - // Determine the URL of the redirection - var redirectUrl; - try { - redirectUrl = url.resolve(currentUrl, location); - } - catch (cause) { - this.emit("error", new RedirectionError(cause)); - return; +/** + * Encodes the given string as UTF-8 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.text.utf8.encode = function(str, output, offset) { + str = util.encodeUtf8(str); + var out = output; + if(!out) { + out = new Uint8Array(str.length); } - - // Create the redirected request - debug("redirecting to", redirectUrl); - this._isRedirect = true; - var redirectUrlParts = url.parse(redirectUrl); - Object.assign(this._options, redirectUrlParts); - - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrlParts.protocol !== currentUrlParts.protocol && - redirectUrlParts.protocol !== "https:" || - redirectUrlParts.host !== currentHost && - !isSubdomain(redirectUrlParts.host, currentHost)) { - removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); } + return output ? (j - offset) : out; +}; - // Evaluate the beforeRedirect callback - if (typeof this._options.beforeRedirect === "function") { - var responseDetails = { headers: response.headers }; - try { - this._options.beforeRedirect.call(null, this._options, responseDetails); - } - catch (err) { - this.emit("error", err); - return; - } - this._sanitizeOptions(this._options); - } +/** + * Decodes the UTF-8 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util.text.utf8.decode = function(bytes) { + return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); +}; - // Perform the redirected request - try { - this._performRequest(); +/** + * Encodes the given string as UTF-16 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.text.utf16.encode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length * 2); } - catch (cause) { - this.emit("error", new RedirectionError(cause)); + var view = new Uint16Array(out.buffer); + offset = offset || 0; + var j = offset; + var k = offset; + for(var i = 0; i < str.length; ++i) { + view[k++] = str.charCodeAt(i); + j += 2; } + return output ? (j - offset) : out; }; -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters - if (typeof input === "string") { - var urlStr = input; - try { - input = urlToOptions(new URL(urlStr)); - } - catch (err) { - /* istanbul ignore next */ - input = url.parse(urlStr); - } - } - else if (URL && (input instanceof URL)) { - input = urlToOptions(input); - } - else { - callback = options; - options = input; - input = { protocol: protocol }; - } - if (typeof options === "function") { - callback = options; - options = null; - } - - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; +/** + * Decodes the UTF-16 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util.text.utf16.decode = function(bytes) { + return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); +}; - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } +/** + * Deflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true to return only raw deflate data, false to include zlib + * header and trailer. + * + * @return the deflated data as a string. + */ +util.deflate = function(api, bytes, raw) { + bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; + // strip zlib header and trailer if necessary + if(raw) { + // zlib header is 2 bytes (CMF,FLG) where FLG indicates that + // there is a 4-byte DICT (alder-32) block before the data if + // its 5th bit is set + var start = 2; + var flg = bytes.charCodeAt(1); + if(flg & 0x20) { + start = 6; } + // zlib trailer is 4 bytes of adler-32 + bytes = bytes.substring(start, bytes.length - 4); + } - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} + return bytes; +}; -/* istanbul ignore next */ -function noop() { /* empty */ } - -// from https://github.com/nodejs/node/blob/master/lib/internal/url.js -function urlToOptions(urlObject) { - var options = { - protocol: urlObject.protocol, - hostname: urlObject.hostname.startsWith("[") ? - /* istanbul ignore next */ - urlObject.hostname.slice(1, -1) : - urlObject.hostname, - hash: urlObject.hash, - search: urlObject.search, - pathname: urlObject.pathname, - path: urlObject.pathname + urlObject.search, - href: urlObject.href, - }; - if (urlObject.port !== "") { - options.port = Number(urlObject.port); - } - return options; -} +/** + * Inflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true if the incoming data has no zlib header or trailer and is + * raw DEFLATE data. + * + * @return the inflated data as a string, null on error. + */ +util.inflate = function(api, bytes, raw) { + // TODO: add zlib header and trailer if necessary/possible + var rval = api.inflate(util.encode64(bytes)).rval; + return (rval === null) ? null : util.decode64(rval); +}; -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } +/** + * Sets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param obj the storage object, null to remove. + */ +var _setStorageObject = function(api, id, obj) { + if(!api) { + throw new Error('WebStorage not available.'); } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} -function createErrorType(code, defaultMessage) { - function CustomError(cause) { - Error.captureStackTrace(this, this.constructor); - if (!cause) { - this.message = defaultMessage; - } - else { - this.message = defaultMessage + ": " + cause.message; - this.cause = cause; - } + var rval; + if(obj === null) { + rval = api.removeItem(id); + } else { + // json-encode and base64-encode object + obj = util.encode64(JSON.stringify(obj)); + rval = api.setItem(id, obj); } - CustomError.prototype = new Error(); - CustomError.prototype.constructor = CustomError; - CustomError.prototype.name = "Error [" + code + "]"; - CustomError.prototype.code = code; - return CustomError; -} -function abortRequest(request) { - for (var e = 0; e < events.length; e++) { - request.removeListener(events[e], eventHandlers[events[e]]); + // handle potential flash error + if(typeof(rval) !== 'undefined' && rval.rval !== true) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; } - request.on("error", noop); - request.abort(); -} - -function isSubdomain(subdomain, domain) { - const dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); -} - -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; - - -/***/ }), - -/***/ 3186: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = (__nccwpck_require__(7147).constants) || __nccwpck_require__(2057) - - -/***/ }), - -/***/ 1621: -/***/ ((module) => { - -"use strict"; - - -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; +/** + * Gets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * + * @return the storage object entry or null if none exists. + */ +var _getStorageObject = function(api, id) { + if(!api) { + throw new Error('WebStorage not available.'); + } -/***/ }), - -/***/ 4124: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -try { - var util = __nccwpck_require__(3837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(8544); -} - - -/***/ }), + // get the existing entry + var rval = api.getItem(id); -/***/ 8544: -/***/ ((module) => { + /* Note: We check api.init because we can't do (api == localStorage) + on IE because of "Class doesn't support Automation" exception. Only + the flash api has an init method so this works too, but we need a + better solution in the future. */ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor + // flash returns item wrapped in an object, handle special case + if(api.init) { + if(rval.rval === null) { + if(rval.error) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } + // no error, but also no item + rval = null; + } else { + rval = rval.rval; } } -} - - -/***/ }), - -/***/ 3287: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; + // handle decoding + if(rval !== null) { + // base64-decode and json-decode data + rval = JSON.parse(util.decode64(rval)); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + return rval; +}; -/*! - * is-plain-object +/** + * Stores an item in local storage. * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). */ - -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - if (isObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; - - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; +var _setItem = function(api, id, key, data) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj === null) { + // create a new storage object + obj = {}; } + // update key + obj[key] = data; - // Most likely a plain Object - return true; -} - -exports.isPlainObject = isPlainObject; - - -/***/ }), + // set storage object + _setStorageObject(api, id, obj); +}; -/***/ 7614: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Gets an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * + * @return the item. + */ +var _getItem = function(api, id, key) { + // get storage object + var rval = _getStorageObject(api, id); + if(rval !== null) { + // return data at key + rval = (key in rval) ? rval[key] : null; + } -var path = __nccwpck_require__(1017); -var fs = __nccwpck_require__(7147); -var _0777 = parseInt('0777', 8); + return rval; +}; -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; +/** + * Removes an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + */ +var _removeItem = function(api, id, key) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj !== null && key in obj) { + // remove key + delete obj[key]; -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; + // see if entry has no keys remaining + var empty = true; + for(var prop in obj) { + empty = false; + break; } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); + if(empty) { + // remove entry entirely if no keys are left + obj = null; } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} + // set storage object + _setStorageObject(api, id, obj); + } +}; -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; +/** + * Clears the local disk storage identified by the given ID. + * + * @param api the storage interface. + * @param id the storage ID to use. + */ +var _clearItems = function(api, id) { + _setStorageObject(api, id, null); +}; + +/** + * Calls a storage function. + * + * @param func the function to call. + * @param args the arguments for the function. + * @param location the location argument. + * + * @return the return value from the function. + */ +var _callStorageFunction = function(func, args, location) { + var rval = null; - p = path.resolve(p); + // default storage types + if(typeof(location) === 'undefined') { + location = ['web', 'flash']; + } + // apply storage types in order of preference + var type; + var done = false; + var exception = null; + for(var idx in location) { + type = location[idx]; try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; + if(type === 'flash' || type === 'both') { + if(args[0] === null) { + throw new Error('Flash local storage not available.'); } + rval = func.apply(this, args); + done = (type === 'flash'); + } + if(type === 'web' || type === 'both') { + args[0] = localStorage; + rval = func.apply(this, args); + done = true; + } + } catch(ex) { + exception = ex; } + if(done) { + break; + } + } - return made; + if(!done) { + throw exception; + } + + return rval; }; +/** + * Stores an item on local disk. + * + * The available types of local storage include 'flash', 'web', and 'both'. + * + * The type 'flash' refers to flash local storage (SharedObject). In order + * to use flash local storage, the 'api' parameter must be valid. The type + * 'web' refers to WebStorage, if supported by the browser. The type 'both' + * refers to storing using both 'flash' and 'web', not just one or the + * other. + * + * The location array should list the storage types to use in order of + * preference: + * + * ['flash']: flash only storage + * ['web']: web only storage + * ['both']: try to store in both + * ['flash','web']: store in flash first, but if not available, 'web' + * ['web','flash']: store in web first, but if not available, 'flash' + * + * The location array defaults to: ['web', 'flash'] + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + * @param location an array with the preferred types of storage to use. + */ +util.setItem = function(api, id, key, data, location) { + _callStorageFunction(_setItem, arguments, location); +}; -/***/ }), +/** + * Gets an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + * + * @return the item. + */ +util.getItem = function(api, id, key, location) { + return _callStorageFunction(_getItem, arguments, location); +}; -/***/ 900: -/***/ ((module) => { +/** + * Removes an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + */ +util.removeItem = function(api, id, key, location) { + _callStorageFunction(_removeItem, arguments, location); +}; /** - * Helpers. + * Clears the local disk storage identified by the given ID. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface if flash is available. + * @param id the storage ID to use. + * @param location an array with the preferred types of storage to use. */ +util.clearItems = function(api, id, location) { + _callStorageFunction(_clearItems, arguments, location); +}; -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; +/** + * Check if an object is empty. + * + * Taken from: + * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 + * + * @param object the object to check. + */ +util.isEmpty = function(obj) { + for(var prop in obj) { + if(obj.hasOwnProperty(prop)) { + return false; + } + } + return true; +}; /** - * Parse or format the given `val`. + * Format with simple printf-style interpolation. * - * Options: + * %%: literal '%' + * %s,%o: convert next argument into a string. * - * - `long` verbose formatting [false] + * @param format the string to format. + * @param ... arguments to interpolate into the format string. + */ +util.format = function(format) { + var re = /%./g; + // current match + var match; + // current part + var part; + // current arg index + var argi = 0; + // collected parts to recombine later + var parts = []; + // last index found + var last = 0; + // loop while matches remain + while((match = re.exec(format))) { + part = format.substring(last, re.lastIndex - 2); + // don't add empty strings (ie, parts between %s%s) + if(part.length > 0) { + parts.push(part); + } + last = re.lastIndex; + // switch on % code + var code = match[0][1]; + switch(code) { + case 's': + case 'o': + // check if enough arguments were given + if(argi < arguments.length) { + parts.push(arguments[argi++ + 1]); + } else { + parts.push(''); + } + break; + // FIXME: do proper formating for numbers, etc + //case 'f': + //case 'd': + case '%': + parts.push('%'); + break; + default: + parts.push('<%' + code + '?>'); + } + } + // add trailing part of format string + parts.push(format.substring(last)); + return parts.join(''); +}; + +/** + * Formats a number. * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ */ +util.formatNumber = function(number, decimals, dec_point, thousands_sep) { + // http://kevin.vanzonneveld.net + // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfix by: Michael White (http://crestidg.com) + // + bugfix by: Benjamin Lupton + // + bugfix by: Allan Jensen (http://www.winternet.no) + // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // * example 1: number_format(1234.5678, 2, '.', ''); + // * returns 1: 1234.57 -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); + var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; + var d = dec_point === undefined ? ',' : dec_point; + var t = thousands_sep === undefined ? + '.' : thousands_sep, s = n < 0 ? '-' : ''; + var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; + var j = (i.length > 3) ? i.length % 3 : 0; + return s + (j ? i.substr(0, j) + t : '') + + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); }; /** - * Parse the given `str` and return milliseconds. + * Formats a byte size. * - * @param {String} str - * @return {Number} - * @api private + * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ */ +util.formatSize = function(size) { + if(size >= 1073741824) { + size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; + } else if(size >= 1048576) { + size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; + } else if(size >= 1024) { + size = util.formatNumber(size / 1024, 0) + ' KiB'; + } else { + size = util.formatNumber(size, 0) + ' bytes'; + } + return size; +}; -function parse(str) { - str = String(str); - if (str.length > 100) { - return; +/** + * Converts an IPv4 or IPv6 string representation into bytes (in network order). + * + * @param ip the IPv4 or IPv6 address to convert. + * + * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't + * be parsed. + */ +util.bytesFromIP = function(ip) { + if(ip.indexOf('.') !== -1) { + return util.bytesFromIPv4(ip); } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; + if(ip.indexOf(':') !== -1) { + return util.bytesFromIPv6(ip); } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; + return null; +}; + +/** + * Converts an IPv4 string representation into bytes (in network order). + * + * @param ip the IPv4 address to convert. + * + * @return the 4-byte address or null if the address can't be parsed. + */ +util.bytesFromIPv4 = function(ip) { + ip = ip.split('.'); + if(ip.length !== 4) { + return null; } -} + var b = util.createBuffer(); + for(var i = 0; i < ip.length; ++i) { + var num = parseInt(ip[i], 10); + if(isNaN(num)) { + return null; + } + b.putByte(num); + } + return b.getBytes(); +}; /** - * Short format for `ms`. + * Converts an IPv6 string representation into bytes (in network order). * - * @param {Number} ms - * @return {String} - * @api private + * @param ip the IPv6 address to convert. + * + * @return the 16-byte address or null if the address can't be parsed. */ +util.bytesFromIPv6 = function(ip) { + var blanks = 0; + ip = ip.split(':').filter(function(e) { + if(e.length === 0) ++blanks; + return true; + }); + var zeros = (8 - ip.length + blanks) * 2; + var b = util.createBuffer(); + for(var i = 0; i < 8; ++i) { + if(!ip[i] || ip[i].length === 0) { + b.fillWithByte(0, zeros); + zeros = 0; + continue; + } + var bytes = util.hexToBytes(ip[i]); + if(bytes.length < 2) { + b.putByte(0); + } + b.putBytes(bytes); + } + return b.getBytes(); +}; -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; +/** + * Converts 4-bytes into an IPv4 string representation or 16-bytes into + * an IPv6 string representation. The bytes must be in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, + * respectively, are given, otherwise null. + */ +util.bytesToIP = function(bytes) { + if(bytes.length === 4) { + return util.bytesToIPv4(bytes); } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; + if(bytes.length === 16) { + return util.bytesToIPv6(bytes); } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; + return null; +}; + +/** + * Converts 4-bytes into an IPv4 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 string representation or null for an invalid # of bytes. + */ +util.bytesToIPv4 = function(bytes) { + if(bytes.length !== 4) { + return null; } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; + var ip = []; + for(var i = 0; i < bytes.length; ++i) { + ip.push(bytes.charCodeAt(i)); } - return ms + 'ms'; -} + return ip.join('.'); +}; /** - * Long format for `ms`. + * Converts 16-bytes into an IPv16 string representation. The bytes must be + * in network order. * - * @param {Number} ms - * @return {String} - * @api private + * @param bytes the bytes to convert. + * + * @return the IPv16 string representation or null for an invalid # of bytes. */ +util.bytesToIPv6 = function(bytes) { + if(bytes.length !== 16) { + return null; + } + var ip = []; + var zeroGroups = []; + var zeroMaxGroup = 0; + for(var i = 0; i < bytes.length; i += 2) { + var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); + // canonicalize zero representation + while(hex[0] === '0' && hex !== '0') { + hex = hex.substr(1); + } + if(hex === '0') { + var last = zeroGroups[zeroGroups.length - 1]; + var idx = ip.length; + if(!last || idx !== last.end + 1) { + zeroGroups.push({start: idx, end: idx}); + } else { + last.end = idx; + if((last.end - last.start) > + (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { + zeroMaxGroup = zeroGroups.length - 1; + } + } + } + ip.push(hex); + } + if(zeroGroups.length > 0) { + var group = zeroGroups[zeroMaxGroup]; + // only shorten group of length > 0 + if(group.end - group.start > 0) { + ip.splice(group.start, group.end - group.start + 1, ''); + if(group.start === 0) { + ip.unshift(''); + } + if(group.end === 7) { + ip.push(''); + } + } + } + return ip.join(':'); +}; -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); +/** + * Estimates the number of processes that can be run concurrently. If + * creating Web Workers, keep in mind that the main JavaScript process needs + * its own core. + * + * @param options the options to use: + * update true to force an update (not use the cached value). + * @param callback(err, max) called once the operation completes. + */ +util.estimateCores = function(options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); + options = options || {}; + if('cores' in util && !options.update) { + return callback(null, util.cores); + } + if(typeof navigator !== 'undefined' && + 'hardwareConcurrency' in navigator && + navigator.hardwareConcurrency > 0) { + util.cores = navigator.hardwareConcurrency; + return callback(null, util.cores); + } + if(typeof Worker === 'undefined') { + // workers not available + util.cores = 1; + return callback(null, util.cores); } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); + if(typeof Blob === 'undefined') { + // can't estimate, default to 2 + util.cores = 2; + return callback(null, util.cores); } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); + + // create worker concurrency estimation code as blob + var blobUrl = URL.createObjectURL(new Blob(['(', + function() { + self.addEventListener('message', function(e) { + // run worker for 4 ms + var st = Date.now(); + var et = st + 4; + while(Date.now() < et); + self.postMessage({st: st, et: et}); + }); + }.toString(), + ')()'], {type: 'application/javascript'})); + + // take 5 samples using 16 workers + sample([], 5, 16); + + function sample(max, samples, numWorkers) { + if(samples === 0) { + // get overlap average + var avg = Math.floor(max.reduce(function(avg, x) { + return avg + x; + }, 0) / max.length); + util.cores = Math.max(1, avg); + URL.revokeObjectURL(blobUrl); + return callback(null, util.cores); + } + map(numWorkers, function(err, results) { + max.push(reduce(numWorkers, results)); + sample(max, samples - 1, numWorkers); + }); } - return ms + ' ms'; -} -/** - * Pluralization helper. - */ + function map(numWorkers, callback) { + var workers = []; + var results = []; + for(var i = 0; i < numWorkers; ++i) { + var worker = new Worker(blobUrl); + worker.addEventListener('message', function(e) { + results.push(e.data); + if(results.length === numWorkers) { + for(var i = 0; i < numWorkers; ++i) { + workers[i].terminate(); + } + callback(null, results); + } + }); + workers.push(worker); + } + for(var i = 0; i < numWorkers; ++i) { + workers[i].postMessage(i); + } + } -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} + function reduce(numWorkers, results) { + // find overlapping time windows + var overlaps = []; + for(var n = 0; n < numWorkers; ++n) { + var r1 = results[n]; + var overlap = overlaps[n] = []; + for(var i = 0; i < numWorkers; ++i) { + if(n === i) { + continue; + } + var r2 = results[i]; + if((r1.st > r2.st && r1.st < r2.et) || + (r2.st > r1.st && r2.st < r1.et)) { + overlap.push(i); + } + } + } + // get maximum overlaps ... don't include overlapping worker itself + // as the main JS process was also being scheduled during the work and + // would have to be subtracted from the estimate anyway + return overlaps.reduce(function(max, overlap) { + return Math.max(max, overlap.length); + }, 0); + } +}; /***/ }), -/***/ 467: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 8180: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Javascript implementation of X.509 and related components (such as + * Certification Signing Requests) of a Public Key Infrastructure. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * + * The ASN.1 representation of an X.509v3 certificate is as follows + * (see RFC 2459): + * + * Certificate ::= SEQUENCE { + * tbsCertificate TBSCertificate, + * signatureAlgorithm AlgorithmIdentifier, + * signatureValue BIT STRING + * } + * + * TBSCertificate ::= SEQUENCE { + * version [0] EXPLICIT Version DEFAULT v1, + * serialNumber CertificateSerialNumber, + * signature AlgorithmIdentifier, + * issuer Name, + * validity Validity, + * subject Name, + * subjectPublicKeyInfo SubjectPublicKeyInfo, + * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, + * -- If present, version shall be v2 or v3 + * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, + * -- If present, version shall be v2 or v3 + * extensions [3] EXPLICIT Extensions OPTIONAL + * -- If present, version shall be v3 + * } + * + * Version ::= INTEGER { v1(0), v2(1), v3(2) } + * + * CertificateSerialNumber ::= INTEGER + * + * Name ::= CHOICE { + * // only one possible choice for now + * RDNSequence + * } + * + * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName + * + * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue + * + * AttributeTypeAndValue ::= SEQUENCE { + * type AttributeType, + * value AttributeValue + * } + * AttributeType ::= OBJECT IDENTIFIER + * AttributeValue ::= ANY DEFINED BY AttributeType + * + * Validity ::= SEQUENCE { + * notBefore Time, + * notAfter Time + * } + * + * Time ::= CHOICE { + * utcTime UTCTime, + * generalTime GeneralizedTime + * } + * + * UniqueIdentifier ::= BIT STRING + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension + * + * Extension ::= SEQUENCE { + * extnID OBJECT IDENTIFIER, + * critical BOOLEAN DEFAULT FALSE, + * extnValue OCTET STRING + * } + * + * The only key algorithm currently supported for PKI is RSA. + * + * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055. + * + * PKCS#10 v1.7 describes certificate signing requests: + * + * CertificationRequestInfo: + * + * CertificationRequestInfo ::= SEQUENCE { + * version INTEGER { v1(0) } (v1,...), + * subject Name, + * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, + * attributes [0] Attributes{{ CRIAttributes }} + * } + * + * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} + * + * CRIAttributes ATTRIBUTE ::= { + * ... -- add any locally defined attributes here -- } + * + * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { + * type ATTRIBUTE.&id({IOSet}), + * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type}) + * } + * + * CertificationRequest ::= SEQUENCE { + * certificationRequestInfo CertificationRequestInfo, + * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, + * signature BIT STRING + * } + */ +var forge = __nccwpck_require__(9177); +__nccwpck_require__(7994); +__nccwpck_require__(9549); +__nccwpck_require__(7157); +__nccwpck_require__(6231); +__nccwpck_require__(7973); +__nccwpck_require__(1925); +__nccwpck_require__(154); +__nccwpck_require__(4376); +__nccwpck_require__(3921); +__nccwpck_require__(8339); -Object.defineProperty(exports, "__esModule", ({ value: true })); +// shortcut for asn.1 API +var asn1 = forge.asn1; -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Stream = _interopDefault(__nccwpck_require__(2781)); -var http = _interopDefault(__nccwpck_require__(3685)); -var Url = _interopDefault(__nccwpck_require__(7310)); -var whatwgUrl = _interopDefault(__nccwpck_require__(3323)); -var https = _interopDefault(__nccwpck_require__(5687)); -var zlib = _interopDefault(__nccwpck_require__(9796)); - -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; - -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); - -class Blob { - constructor() { - this[TYPE] = ''; - - const blobParts = arguments[0]; - const options = arguments[1]; - - const buffers = []; - let size = 0; - - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } +/* Public Key Infrastructure (PKI) implementation. */ +var pki = module.exports = forge.pki = forge.pki || {}; +var oids = pki.oids; - this[BUFFER] = Buffer.concat(buffers); +// short name OID mappings +var _shortNames = {}; +_shortNames['CN'] = oids['commonName']; +_shortNames['commonName'] = 'CN'; +_shortNames['C'] = oids['countryName']; +_shortNames['countryName'] = 'C'; +_shortNames['L'] = oids['localityName']; +_shortNames['localityName'] = 'L'; +_shortNames['ST'] = oids['stateOrProvinceName']; +_shortNames['stateOrProvinceName'] = 'ST'; +_shortNames['O'] = oids['organizationName']; +_shortNames['organizationName'] = 'O'; +_shortNames['OU'] = oids['organizationalUnitName']; +_shortNames['organizationalUnitName'] = 'OU'; +_shortNames['E'] = oids['emailAddress']; +_shortNames['emailAddress'] = 'E'; - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; - - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); +// validator for an SubjectPublicKeyInfo structure +// Note: Currently only works with an RSA public key +var publicKeyValidator = forge.pki.rsa.publicKeyValidator; - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} +// validator for an X.509v3 certificate +var x509CertificateValidator = { + name: 'Certificate', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Certificate.TBSCertificate', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'tbsCertificate', + value: [{ + name: 'Certificate.TBSCertificate.version', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.version.integer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certVersion' + }] + }, { + name: 'Certificate.TBSCertificate.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certSerialNumber' + }, { + name: 'Certificate.TBSCertificate.signature', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Certificate.TBSCertificate.signature.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certinfoSignatureOid' + }, { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certinfoSignatureParams' + }] + }, { + name: 'Certificate.TBSCertificate.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certIssuer' + }, { + name: 'Certificate.TBSCertificate.validity', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + // Note: UTC and generalized times may both appear so the capture + // names are based on their detected order, the names used below + // are only for the common case, which validity time really means + // "notBefore" and which means "notAfter" will be determined by order + value: [{ + // notBefore (Time) (UTC time case) + name: 'Certificate.TBSCertificate.validity.notBefore (utc)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity1UTCTime' + }, { + // notBefore (Time) (generalized time case) + name: 'Certificate.TBSCertificate.validity.notBefore (generalized)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity2GeneralizedTime' + }, { + // notAfter (Time) (only UTC time is supported) + name: 'Certificate.TBSCertificate.validity.notAfter (utc)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity3UTCTime' + }, { + // notAfter (Time) (only UTC time is supported) + name: 'Certificate.TBSCertificate.validity.notAfter (generalized)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity4GeneralizedTime' + }] + }, { + // Name (subject) (RDNSequence) + name: 'Certificate.TBSCertificate.subject', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certSubject' + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + // issuerUniqueID (optional) + name: 'Certificate.TBSCertificate.issuerUniqueID', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.issuerUniqueID.id', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: 'certIssuerUniqueId' + }] + }, { + // subjectUniqueID (optional) + name: 'Certificate.TBSCertificate.subjectUniqueID', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.subjectUniqueID.id', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: 'certSubjectUniqueId' + }] + }, { + // Extensions (optional) + name: 'Certificate.TBSCertificate.extensions', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + constructed: true, + captureAsn1: 'certExtensions', + optional: true + }] + }, { + // AlgorithmIdentifier (signature algorithm) + name: 'Certificate.signatureAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: 'Certificate.signatureAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certSignatureOid' + }, { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certSignatureParams' + }] + }, { + // SignatureValue + name: 'Certificate.signatureValue', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'certSignature' + }] +}; -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); +var rsassaPssParameterValidator = { + name: 'rsapss', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'rsapss.hashAlgorithm', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + value: [{ + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'hashOid' + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }, { + name: 'rsapss.maskGenAlgorithm', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'maskGenOid' + }, { + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'maskGenHashOid' + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }] + }, { + name: 'rsapss.saltLength', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + optional: true, + value: [{ + name: 'rsapss.saltLength.saltLength', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: 'saltLength' + }] + }, { + name: 'rsapss.trailerField', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + optional: true, + value: [{ + name: 'rsapss.trailer.trailer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: 'trailer' + }] + }] +}; -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); +// validator for a CertificationRequestInfo structure +var certificationRequestInfoValidator = { + name: 'CertificationRequestInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfo', + value: [{ + name: 'CertificationRequestInfo.integer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certificationRequestInfoVersion' + }, { + // Name (subject) (RDNSequence) + name: 'CertificationRequestInfo.subject', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfoSubject' + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + name: 'CertificationRequestInfo.attributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'certificationRequestInfoAttributes', + value: [{ + name: 'CertificationRequestInfo.attributes', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'CertificationRequestInfo.attributes.type', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false + }, { + name: 'CertificationRequestInfo.attributes.value', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true + }] + }] + }] +}; -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ +// validator for a CertificationRequest structure +var certificationRequestValidator = { + name: 'CertificationRequest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'csr', + value: [ + certificationRequestInfoValidator, { + // AlgorithmIdentifier (signature algorithm) + name: 'CertificationRequest.signatureAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: 'CertificationRequest.signatureAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'csrSignatureOid' + }, { + name: 'CertificationRequest.signatureAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'csrSignatureParams' + }] + }, { + // signature + name: 'CertificationRequest.signature', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'csrSignature' + } + ] +}; /** - * Create FetchError instance + * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName + * sets into an array with objects that have type and value properties. * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError + * @param rdn the RDNSequence to convert. + * @param md a message digest to append type and value to if provided. */ -function FetchError(message, type, systemError) { - Error.call(this, message); +pki.RDNAttributesAsArray = function(rdn, md) { + var rval = []; - this.message = message; - this.type = type; + // each value in 'rdn' in is a SET of RelativeDistinguishedName + var set, attr, obj; + for(var si = 0; si < rdn.value.length; ++si) { + // get the RelativeDistinguishedName set + set = rdn.value[si]; - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; + // each value in the SET is an AttributeTypeAndValue sequence + // containing first a type (an OID) and second a value (defined by + // the OID) + for(var i = 0; i < set.value.length; ++i) { + obj = {}; + attr = set.value[i]; + obj.type = asn1.derToOid(attr.value[0].value); + obj.value = attr.value[1].value; + obj.valueTagClass = attr.value[1].type; + // if the OID is known, get its name and short name + if(obj.type in oids) { + obj.name = oids[obj.type]; + if(obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + if(md) { + md.update(obj.type); + md.update(obj.value); + } + rval.push(obj); + } } - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = (__nccwpck_require__(2877).convert); -} catch (e) {} - -const INTERNALS = Symbol('Body internals'); - -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; + return rval; +}; /** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body + * Converts ASN.1 CRIAttributes into an array with objects that have type and + * value properties. * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void + * @param attributes the CRIAttributes to convert. */ -function Body(body) { - var _this = this; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; - - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } -} - -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - - get bodyUsed() { - return this[INTERNALS].disturbed; - }, - - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, - - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, - - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; - - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, - - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, - - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; +pki.CRIAttributesAsArray = function(attributes) { + var rval = []; - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; + // each value in 'attributes' in is a SEQUENCE with an OID and a SET + for(var si = 0; si < attributes.length; ++si) { + // get the attribute sequence + var seq = attributes[si]; -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); + // each value in the SEQUENCE containing first a type (an OID) and + // second a set of values (defined by the OID) + var type = asn1.derToOid(seq.value[0].value); + var values = seq.value[1].value; + for(var vi = 0; vi < values.length; ++vi) { + var obj = {}; + obj.type = type; + obj.value = values[vi].value; + obj.valueTagClass = values[vi].type; + // if the OID is known, get its name and short name + if(obj.type in oids) { + obj.name = oids[obj.type]; + if(obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + // parse extensions + if(obj.type === oids.extensionRequest) { + obj.extensions = []; + for(var ei = 0; ei < obj.value.length; ++ei) { + obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei])); + } + } + rval.push(obj); + } + } -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } + return rval; }; /** - * Consume and convert an entire Body to a Buffer. + * Gets an issuer or subject attribute from its name, type, or short name. * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param obj the issuer or subject object. + * @param options a short name string or an object with: + * shortName the short name for the attribute. + * name the name for the attribute. + * type the type for the attribute. * - * @return Promise + * @return the attribute. */ -function consumeBody() { - var _this4 = this; - - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } - - this[INTERNALS].disturbed = true; - - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } - - let body = this.body; - - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is blob - if (isBlob(body)) { - body = body.stream(); - } - - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } - - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; - - return new Body.Promise(function (resolve, reject) { - let resTimeout; - - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } - - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } - - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } - - accumBytes += chunk.length; - accum.push(chunk); - }); - - body.on('end', function () { - if (abort) { - return; - } - - clearTimeout(resTimeout); +function _getAttribute(obj, options) { + if(typeof options === 'string') { + options = {shortName: options}; + } - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); + var rval = null; + var attr; + for(var i = 0; rval === null && i < obj.attributes.length; ++i) { + attr = obj.attributes[i]; + if(options.type && options.type === attr.type) { + rval = attr; + } else if(options.name && options.name === attr.name) { + rval = attr; + } else if(options.shortName && options.shortName === attr.shortName) { + rval = attr; + } + } + return rval; } /** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * Converts signature parameters from ASN.1 structure. * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; - - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } - - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); - - // html5 - if (!res && str) { - res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - this[MAP] = Object.create(null); - - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - - return; - } - - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } - - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } - - return this[MAP][key].join(', '); - } - - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } - - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } - - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } - - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } - - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } - - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); - -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; +var _createSignatureDigest = function(options) { + switch(oids[options.signatureOid]) { + case 'sha1WithRSAEncryption': + // deprecated alias + case 'sha1WithRSASignature': + return forge.md.sha1.create(); + case 'md5WithRSAEncryption': + return forge.md.md5.create(); + case 'sha256WithRSAEncryption': + return forge.md.sha256.create(); + case 'sha384WithRSAEncryption': + return forge.md.sha384.create(); + case 'sha512WithRSAEncryption': + return forge.md.sha512.create(); + case 'RSASSA-PSS': + return forge.md.sha256.create(); + default: + var error = new Error( + 'Could not compute ' + options.type + ' digest. ' + + 'Unknown signature OID.'); + error.signatureOid = options.signatureOid; + throw error; + } +}; - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} +/** + * Verify signature on certificate or CSR. + * + * @param options: + * certificate the certificate or CSR to verify. + * md the signature digest. + * signature the signature + * @return a created md instance. throws if unknown oid. + */ +var _verifySignature = function(options) { + var cert = options.certificate; + var scheme; -const INTERNAL = Symbol('internal'); + switch(cert.signatureOid) { + case oids.sha1WithRSAEncryption: + // deprecated alias + case oids.sha1WithRSASignature: + /* use PKCS#1 v1.5 padding scheme */ + break; + case oids['RSASSA-PSS']: + var hash, mgf; -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} + /* initialize mgf */ + hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; + if(hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported MGF hash function.'); + error.oid = cert.signatureParameters.mgf.hash.algorithmOid; + error.name = hash; + throw error; + } -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } + mgf = oids[cert.signatureParameters.mgf.algorithmOid]; + if(mgf === undefined || forge.mgf[mgf] === undefined) { + var error = new Error('Unsupported MGF function.'); + error.oid = cert.signatureParameters.mgf.algorithmOid; + error.name = mgf; + throw error; + } - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; - - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } + mgf = forge.mgf[mgf].create(forge.md[hash].create()); - this[INTERNAL].index = index + 1; + /* initialize hash function */ + hash = oids[cert.signatureParameters.hash.algorithmOid]; + if(hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported RSASSA-PSS hash function.'); + error.oid = cert.signatureParameters.hash.algorithmOid; + error.name = hash; + throw error; + } - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + scheme = forge.pss.create( + forge.md[hash].create(), mgf, cert.signatureParameters.saltLength + ); + break; + } -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); + // verify signature on cert using public key + return cert.publicKey.verify( + options.md.digest().getBytes(), options.signature, scheme + ); +}; /** - * Export the Headers object in a form that Node.js can consume. + * Converts an X.509 certificate from PEM format. + * + * Note: If the certificate is to be verified then compute hash should + * be set to true. This will scan the TBSCertificate part of the ASN.1 + * object while it is converted so it doesn't need to be converted back + * to ASN.1-DER-encoding later. * - * @param Headers headers - * @return Object + * @param pem the PEM-formatted certificate. + * @param computeHash true to compute the hash for verification. + * @param strict true to be strict when checking ASN.1 value lengths, false to + * allow truncated values (default: true). + * + * @return the certificate. */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); +pki.certificateFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } + if(msg.type !== 'CERTIFICATE' && + msg.type !== 'X509 CERTIFICATE' && + msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error( + 'Could not convert certificate from PEM; PEM header type ' + + 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error( + 'Could not convert certificate from PEM; PEM is encrypted.'); + } - return obj; -} + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body, strict); + + return pki.certificateFromAsn1(obj, computeHash); +}; /** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. + * Converts an X.509 certificate to PEM format. + * + * @param cert the certificate. + * @param maxline the maximum characters per line, defaults to 64. * - * @param Object obj Object of headers - * @return Headers + * @return the PEM-formatted certificate. */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} - -const INTERNALS$1 = Symbol('Response internals'); - -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; +pki.certificateToPem = function(cert, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'CERTIFICATE', + body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; /** - * Response class + * Converts an RSA public key from PEM format. * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void + * @param pem the PEM-formatted public key. + * + * @return the public key. */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - Body.call(this, body, opts); - - const status = opts.status || 200; - const headers = new Headers(opts.headers); - - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } - - get url() { - return this[INTERNALS$1].url || ''; - } - - get status() { - return this[INTERNALS$1].status; - } - - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } - - get redirected() { - return this[INTERNALS$1].counter > 0; - } - - get statusText() { - return this[INTERNALS$1].statusText; - } - - get headers() { - return this[INTERNALS$1].headers; - } - - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } -} - -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); +pki.publicKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); + if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') { + var error = new Error('Could not convert public key from PEM; PEM header ' + + 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert public key from PEM; PEM is encrypted.'); + } -const INTERNALS$2 = Symbol('Request internals'); -const URL = Url.URL || whatwgUrl.URL; + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; + return pki.publicKeyFromAsn1(obj); +}; /** - * Wrapper around `new URL` to handle arbitrary URLs + * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo). * - * @param {string} urlStr - * @return {void} - */ -function parseURL(urlStr) { - /* - Check whether the URL is absolute or not - Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 - Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + * @param key the public key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted public key. */ - if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL(urlStr).toString(); - } - - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); -} - -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; +pki.publicKeyToPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'PUBLIC KEY', + body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; /** - * Check if a value is an instance of Request. + * Converts an RSA public key to PEM format (using an RSAPublicKey). + * + * @param key the public key. + * @param maxline the maximum characters per line, defaults to 64. * - * @param Mixed input - * @return Boolean + * @return the PEM-formatted public key. */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} +pki.publicKeyToRSAPublicKeyPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'RSA PUBLIC KEY', + body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; /** - * Request class + * Gets a fingerprint for the given public key. + * + * @param options the options to use. + * [md] the message digest object to use (defaults to forge.md.sha1). + * [type] the type of fingerprint, such as 'RSAPublicKey', + * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey'). + * [encoding] an alternative output encoding, such as 'hex' + * (defaults to none, outputs a byte buffer). + * [delimiter] the delimiter to use between bytes for 'hex' encoded + * output, eg: ':' (defaults to none). * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void + * @return the fingerprint as a byte buffer or other encoding based on options. */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parseURL(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parseURL(`${input}`); - } - input = {}; - } else { - parsedURL = parseURL(input.url); - } - - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); - - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } - - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); - - const headers = new Headers(init.headers || input.headers || {}); - - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; - - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } - - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; - - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - - get method() { - return this[INTERNALS$2].method; - } - - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } - - get headers() { - return this[INTERNALS$2].headers; - } - - get redirect() { - return this[INTERNALS$2].redirect; - } - - get signal() { - return this[INTERNALS$2].signal; - } - - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } -} - -Body.mixIn(Request.prototype); +pki.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge.md.sha1.create(); + var type = options.type || 'RSAPublicKey'; -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); + var bytes; + switch(type) { + case 'RSAPublicKey': + bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes(); + break; + case 'SubjectPublicKeyInfo': + bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes(); + break; + default: + throw new Error('Unknown fingerprint type "' + options.type + '".'); + } -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); + // hash public key bytes + md.start(); + md.update(bytes); + var digest = md.digest(); + if(options.encoding === 'hex') { + var hex = digest.toHex(); + if(options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if(options.encoding === 'binary') { + return digest.getBytes(); + } else if(options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; +}; /** - * Convert a Request to Node.js http request options. + * Converts a PKCS#10 certification request (CSR) from PEM format. + * + * Note: If the certification request is to be verified then compute hash + * should be set to true. This will scan the CertificationRequestInfo part of + * the ASN.1 object while it is converted so it doesn't need to be converted + * back to ASN.1-DER-encoding later. + * + * @param pem the PEM-formatted certificate. + * @param computeHash true to compute the hash for verification. + * @param strict true to be strict when checking ASN.1 value lengths, false to + * allow truncated values (default: true). * - * @param Request A Request instance - * @return Object The options object to be passed to http.request + * @return the certification request (CSR). */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); - - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } - - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } - - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } - - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } - - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } - - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } +pki.certificationRequestFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } + if(msg.type !== 'CERTIFICATE REQUEST') { + var error = new Error('Could not convert certification request from PEM; ' + + 'PEM header type is not "CERTIFICATE REQUEST".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certification request from PEM; ' + + 'PEM is encrypted.'); + } - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body, strict); - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); -} + return pki.certificationRequestFromAsn1(obj, computeHash); +}; /** - * abort-error.js + * Converts a PKCS#10 certification request (CSR) to PEM format. + * + * @param csr the certification request. + * @param maxline the maximum characters per line, defaults to 64. * - * AbortError interface for cancelled requests + * @return the PEM-formatted certification request. */ +pki.certificationRequestToPem = function(csr, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'CERTIFICATE REQUEST', + body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; /** - * Create AbortError instance + * Creates an empty X.509v3 RSA certificate. * - * @param String message Error message for human - * @return AbortError + * @return the certificate. */ -function AbortError(message) { - Error.call(this, message); +pki.createCertificate = function() { + var cert = {}; + cert.version = 0x02; + cert.serialNumber = '00'; + cert.signatureOid = null; + cert.signature = null; + cert.siginfo = {}; + cert.siginfo.algorithmOid = null; + cert.validity = {}; + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(); - this.type = 'aborted'; - this.message = message; + cert.issuer = {}; + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = []; + cert.issuer.hash = null; - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} + cert.subject = {}; + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = []; + cert.subject.hash = null; -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; + cert.extensions = []; + cert.publicKey = null; + cert.md = null; -const URL$1 = Url.URL || whatwgUrl.URL; + /** + * Sets the subject of this certificate. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + cert.setSubject = function(attrs, uniqueId) { + // set new attributes, clear hash + _fillMissingFields(attrs); + cert.subject.attributes = attrs; + delete cert.subject.uniqueId; + if(uniqueId) { + // TODO: support arbitrary bit length ids + cert.subject.uniqueId = uniqueId; + } + cert.subject.hash = null; + }; -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; + /** + * Sets the issuer of this certificate. + * + * @param attrs the array of issuer attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + cert.setIssuer = function(attrs, uniqueId) { + // set new attributes, clear hash + _fillMissingFields(attrs); + cert.issuer.attributes = attrs; + delete cert.issuer.uniqueId; + if(uniqueId) { + // TODO: support arbitrary bit length ids + cert.issuer.uniqueId = uniqueId; + } + cert.issuer.hash = null; + }; -const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { - const orig = new URL$1(original).hostname; - const dest = new URL$1(destination).hostname; + /** + * Sets the extensions of this certificate. + * + * @param exts the array of extensions to use. + */ + cert.setExtensions = function(exts) { + for(var i = 0; i < exts.length; ++i) { + _fillMissingExtensionFields(exts[i], {cert: cert}); + } + // set new extensions + cert.extensions = exts; + }; - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); -}; + /** + * Gets an extension by its name or id. + * + * @param options the name to use or an object with: + * name the name to use. + * id the id to use. + * + * @return the extension or null if not found. + */ + cert.getExtension = function(options) { + if(typeof options === 'string') { + options = {name: options}; + } -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { + var rval = null; + var ext; + for(var i = 0; rval === null && i < cert.extensions.length; ++i) { + ext = cert.extensions[i]; + if(options.id && ext.id === options.id) { + rval = ext; + } else if(options.name && ext.name === options.name) { + rval = ext; + } + } + return rval; + }; - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } + /** + * Signs this certificate using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + cert.sign = function(key, md) { + // TODO: get signature OID from private key + cert.md = md || forge.md.sha1.create(); + var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption']; + if(!algorithmOid) { + var error = new Error('Could not compute certificate digest. ' + + 'Unknown message digest algorithm OID.'); + error.algorithm = cert.md.algorithm; + throw error; + } + cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; - Body.Promise = fetch.Promise; + // get TBSCertificate, convert to DER + cert.tbsCertificate = pki.getTBSCertificate(cert); + var bytes = asn1.toDer(cert.tbsCertificate); - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); + // digest and sign + cert.md.update(bytes.getBytes()); + cert.signature = key.sign(cert.md); + }; - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; + /** + * Attempts verify the signature on the passed certificate using this + * certificate's public key. + * + * @param child the certificate to verify. + * + * @return true if verified, false if not. + */ + cert.verify = function(child) { + var rval = false; - let response = null; + if(!cert.issued(child)) { + var issuer = child.issuer; + var subject = cert.subject; + var error = new Error( + 'The parent certificate did not issue the given child ' + + 'certificate; the child certificate\'s issuer does not match the ' + + 'parent\'s subject.'); + error.expectedIssuer = subject.attributes; + error.actualIssuer = issuer.attributes; + throw error; + } - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; + var md = child.md; + if(md === null) { + // create digest for OID signature types + md = _createSignatureDigest({ + signatureOid: child.signatureOid, + type: 'certificate' + }); - if (signal && signal.aborted) { - abort(); - return; - } + // produce DER formatted TBSCertificate and digest it + var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child); + var bytes = asn1.toDer(tbsCertificate); + md.update(bytes.getBytes()); + } - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; + if(md !== null) { + rval = _verifySignature({ + certificate: cert, md: md, signature: child.signature + }); + } - // send request - const req = send(options); - let reqTimeout; + return rval; + }; - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } + /** + * Returns true if this certificate's issuer matches the passed + * certificate's subject. Note that no signature check is performed. + * + * @param parent the certificate to check. + * + * @return true if this certificate's issuer matches the passed certificate's + * subject. + */ + cert.isIssuer = function(parent) { + var rval = false; - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } + var i = cert.issuer; + var s = parent.subject; - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } + // compare hashes if present + if(i.hash && s.hash) { + rval = (i.hash === s.hash); + } else if(i.attributes.length === s.attributes.length) { + // all attributes are the same so issuer matches subject + rval = true; + var iattr, sattr; + for(var n = 0; rval && n < i.attributes.length; ++n) { + iattr = i.attributes[n]; + sattr = s.attributes[n]; + if(iattr.type !== sattr.type || iattr.value !== sattr.value) { + // attribute mismatch + rval = false; + } + } + } - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - finalize(); - }); + return rval; + }; - req.on('response', function (res) { - clearTimeout(reqTimeout); - - const headers = createHeadersLenient(res.headers); - - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); - - // HTTP fetch step 5.3 - let locationURL = null; - try { - locationURL = location === null ? null : new URL$1(location, request.url).toString(); - } catch (err) { - // error here can only be invalid URL in Location: header - // do not throw when options.redirect == manual - // let the user extract the errorneous redirect URL - if (request.redirect !== 'manual') { - reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); - finalize(); - return; - } - } + /** + * Returns true if this certificate's subject matches the issuer of the + * given certificate). Note that not signature check is performed. + * + * @param child the certificate to check. + * + * @return true if this certificate's subject matches the passed + * certificate's issuer. + */ + cert.issued = function(child) { + return child.isIssuer(cert); + }; - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } - - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; - - if (!isDomainOrSubdomain(request.url, locationURL)) { - for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { - requestOpts.headers.delete(name); - } - } - - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } - - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } + /** + * Generates the subjectKeyIdentifier for this certificate as byte buffer. + * + * @return the subjectKeyIdentifier for this certificate as byte buffer. + */ + cert.generateSubjectKeyIdentifier = function() { + /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either: - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); - - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; - - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); - - // HTTP-network fetch step 12.1.1.4: handle content codings - - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } + (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the + value of the BIT STRING subjectPublicKey (excluding the tag, + length, and number of unused bits). - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; - - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } + (2) The keyIdentifier is composed of a four bit type field with + the value 0100 followed by the least significant 60 bits of the + SHA-1 hash of the value of the BIT STRING subjectPublicKey + (excluding the tag, length, and number of unused bit string bits). + */ - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - return; - } + // skipping the tag, length, and number of unused bits is the same + // as just using the RSAPublicKey (for RSA keys, which are the + // only ones supported) + return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'}); + }; - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } + /** + * Verifies the subjectKeyIdentifier extension value for this certificate + * against its public key. If no extension is found, false will be + * returned. + * + * @return true if verified, false if not. + */ + cert.verifySubjectKeyIdentifier = function() { + var oid = oids['subjectKeyIdentifier']; + for(var i = 0; i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if(ext.id === oid) { + var ski = cert.generateSubjectKeyIdentifier().getBytes(); + return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski); + } + } + return false; + }; - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); + return cert; +}; - writeToStream(req, request); - }); -} /** - * Redirect code matching + * Converts an X.509v3 RSA certificate from an ASN.1 object. + * + * Note: If the certificate is to be verified then compute hash should + * be set to true. There is currently no implementation for converting + * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1 + * object needs to be scanned before the cert object is created. + * + * @param obj the asn1 representation of an X.509v3 RSA certificate. + * @param computeHash true to compute the hash for verification. * - * @param Number code Status code - * @return Boolean + * @return the certificate. */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; - -// expose Promise -fetch.Promise = global.Promise; +pki.certificateFromAsn1 = function(obj, computeHash) { + // validate certificate and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) { + var error = new Error('Cannot read X.509 certificate. ' + + 'ASN.1 object is not an X509v3 Certificate.'); + error.errors = errors; + throw error; + } -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + // create certificate + var cert = pki.createCertificate(); + cert.version = capture.certVersion ? + capture.certVersion.charCodeAt(0) : 0; + var serial = forge.util.createBuffer(capture.certSerialNumber); + cert.serialNumber = serial.toHex(); + cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); + cert.signatureParameters = _readSignatureParameters( + cert.signatureOid, capture.certSignatureParams, true); + cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); + cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, + capture.certinfoSignatureParams, false); + cert.signature = capture.certSignature; -/***/ }), + var validity = []; + if(capture.certValidity1UTCTime !== undefined) { + validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); + } + if(capture.certValidity2GeneralizedTime !== undefined) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity2GeneralizedTime)); + } + if(capture.certValidity3UTCTime !== undefined) { + validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); + } + if(capture.certValidity4GeneralizedTime !== undefined) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity4GeneralizedTime)); + } + if(validity.length > 2) { + throw new Error('Cannot read notBefore/notAfter validity times; more ' + + 'than two times were provided in the certificate.'); + } + if(validity.length < 2) { + throw new Error('Cannot read notBefore/notAfter validity times; they ' + + 'were not provided as either UTCTime or GeneralizedTime.'); + } + cert.validity.notBefore = validity[0]; + cert.validity.notAfter = validity[1]; -/***/ 2299: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // keep TBSCertificate to preserve signature when exporting + cert.tbsCertificate = capture.tbsCertificate; -"use strict"; + if(computeHash) { + // create digest for OID signature type + cert.md = _createSignatureDigest({ + signatureOid: cert.signatureOid, + type: 'certificate' + }); + // produce DER formatted TBSCertificate and digest it + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + } -var punycode = __nccwpck_require__(5477); -var mappingTable = __nccwpck_require__(1907); + // handle issuer, build issuer message digest + var imd = forge.md.sha1.create(); + var ibytes = asn1.toDer(capture.certIssuer); + imd.update(ibytes.getBytes()); + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer); + if(capture.certIssuerUniqueId) { + cert.issuer.uniqueId = capture.certIssuerUniqueId; + } + cert.issuer.hash = imd.digest().toHex(); -var PROCESSING_OPTIONS = { - TRANSITIONAL: 0, - NONTRANSITIONAL: 1 -}; + // handle subject, build subject message digest + var smd = forge.md.sha1.create(); + var sbytes = asn1.toDer(capture.certSubject); + smd.update(sbytes.getBytes()); + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject); + if(capture.certSubjectUniqueId) { + cert.subject.uniqueId = capture.certSubjectUniqueId; + } + cert.subject.hash = smd.digest().toHex(); -function normalize(str) { // fix bug in v8 - return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); -} + // handle extensions + if(capture.certExtensions) { + cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions); + } else { + cert.extensions = []; + } -function findStatus(val) { - var start = 0; - var end = mappingTable.length - 1; + // convert RSA public key from ASN.1 + cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - while (start <= end) { - var mid = Math.floor((start + end) / 2); + return cert; +}; - var target = mappingTable[mid]; - if (target[0][0] <= val && target[0][1] >= val) { - return target; - } else if (target[0][0] > val) { - end = mid - 1; - } else { - start = mid + 1; +/** + * Converts an ASN.1 extensions object (with extension sequences as its + * values) into an array of extension objects with types and values. + * + * Supported extensions: + * + * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } + * KeyUsage ::= BIT STRING { + * digitalSignature (0), + * nonRepudiation (1), + * keyEncipherment (2), + * dataEncipherment (3), + * keyAgreement (4), + * keyCertSign (5), + * cRLSign (6), + * encipherOnly (7), + * decipherOnly (8) + * } + * + * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } + * BasicConstraints ::= SEQUENCE { + * cA BOOLEAN DEFAULT FALSE, + * pathLenConstraint INTEGER (0..MAX) OPTIONAL + * } + * + * subjectAltName EXTENSION ::= { + * SYNTAX GeneralNames + * IDENTIFIED BY id-ce-subjectAltName + * } + * + * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName + * + * GeneralName ::= CHOICE { + * otherName [0] INSTANCE OF OTHER-NAME, + * rfc822Name [1] IA5String, + * dNSName [2] IA5String, + * x400Address [3] ORAddress, + * directoryName [4] Name, + * ediPartyName [5] EDIPartyName, + * uniformResourceIdentifier [6] IA5String, + * IPAddress [7] OCTET STRING, + * registeredID [8] OBJECT IDENTIFIER + * } + * + * OTHER-NAME ::= TYPE-IDENTIFIER + * + * EDIPartyName ::= SEQUENCE { + * nameAssigner [0] DirectoryString {ub-name} OPTIONAL, + * partyName [1] DirectoryString {ub-name} + * } + * + * @param exts the extensions ASN.1 with extension sequences to parse. + * + * @return the array. + */ +pki.certificateExtensionsFromAsn1 = function(exts) { + var rval = []; + for(var i = 0; i < exts.value.length; ++i) { + // get extension sequence + var extseq = exts.value[i]; + for(var ei = 0; ei < extseq.value.length; ++ei) { + rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei])); } } - return null; -} + return rval; +}; -var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; +/** + * Parses a single certificate extension from ASN.1. + * + * @param ext the extension in ASN.1 format. + * + * @return the parsed extension as an object. + */ +pki.certificateExtensionFromAsn1 = function(ext) { + // an extension has: + // [0] extnID OBJECT IDENTIFIER + // [1] critical BOOLEAN DEFAULT FALSE + // [2] extnValue OCTET STRING + var e = {}; + e.id = asn1.derToOid(ext.value[0].value); + e.critical = false; + if(ext.value[1].type === asn1.Type.BOOLEAN) { + e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00); + e.value = ext.value[2].value; + } else { + e.value = ext.value[1].value; + } + // if the oid is known, get its name + if(e.id in oids) { + e.name = oids[e.id]; -function countSymbols(string) { - return string - // replace every surrogate pair with a BMP symbol - .replace(regexAstralSymbols, '_') - // then get the length - .length; -} + // handle key usage + if(e.name === 'keyUsage') { + // get value as BIT STRING + var ev = asn1.fromDer(e.value); + var b2 = 0x00; + var b3 = 0x00; + if(ev.value.length > 1) { + // skip first byte, just indicates unused bits which + // will be padded with 0s anyway + // get bytes with flag bits + b2 = ev.value.charCodeAt(1); + b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; + } + // set flags + e.digitalSignature = (b2 & 0x80) === 0x80; + e.nonRepudiation = (b2 & 0x40) === 0x40; + e.keyEncipherment = (b2 & 0x20) === 0x20; + e.dataEncipherment = (b2 & 0x10) === 0x10; + e.keyAgreement = (b2 & 0x08) === 0x08; + e.keyCertSign = (b2 & 0x04) === 0x04; + e.cRLSign = (b2 & 0x02) === 0x02; + e.encipherOnly = (b2 & 0x01) === 0x01; + e.decipherOnly = (b3 & 0x80) === 0x80; + } else if(e.name === 'basicConstraints') { + // handle basic constraints + // get value as SEQUENCE + var ev = asn1.fromDer(e.value); + // get cA BOOLEAN flag (defaults to false) + if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { + e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00); + } else { + e.cA = false; + } + // get path length constraint + var value = null; + if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { + value = ev.value[0].value; + } else if(ev.value.length > 1) { + value = ev.value[1].value; + } + if(value !== null) { + e.pathLenConstraint = asn1.derToInteger(value); + } + } else if(e.name === 'extKeyUsage') { + // handle extKeyUsage + // value is a SEQUENCE of OIDs + var ev = asn1.fromDer(e.value); + for(var vi = 0; vi < ev.value.length; ++vi) { + var oid = asn1.derToOid(ev.value[vi].value); + if(oid in oids) { + e[oids[oid]] = true; + } else { + e[oid] = true; + } + } + } else if(e.name === 'nsCertType') { + // handle nsCertType + // get value as BIT STRING + var ev = asn1.fromDer(e.value); + var b2 = 0x00; + if(ev.value.length > 1) { + // skip first byte, just indicates unused bits which + // will be padded with 0s anyway + // get bytes with flag bits + b2 = ev.value.charCodeAt(1); + } + // set flags + e.client = (b2 & 0x80) === 0x80; + e.server = (b2 & 0x40) === 0x40; + e.email = (b2 & 0x20) === 0x20; + e.objsign = (b2 & 0x10) === 0x10; + e.reserved = (b2 & 0x08) === 0x08; + e.sslCA = (b2 & 0x04) === 0x04; + e.emailCA = (b2 & 0x02) === 0x02; + e.objCA = (b2 & 0x01) === 0x01; + } else if( + e.name === 'subjectAltName' || + e.name === 'issuerAltName') { + // handle subjectAltName/issuerAltName + e.altNames = []; -function mapChars(domain_name, useSTD3, processing_option) { - var hasError = false; - var processed = ""; + // ev is a SYNTAX SEQUENCE + var gn; + var ev = asn1.fromDer(e.value); + for(var n = 0; n < ev.value.length; ++n) { + // get GeneralName + gn = ev.value[n]; - var len = countSymbols(domain_name); - for (var i = 0; i < len; ++i) { - var codePoint = domain_name.codePointAt(i); - var status = findStatus(codePoint); + var altName = { + type: gn.type, + value: gn.value + }; + e.altNames.push(altName); - switch (status[1]) { - case "disallowed": - hasError = true; - processed += String.fromCodePoint(codePoint); - break; - case "ignored": - break; - case "mapped": - processed += String.fromCodePoint.apply(String, status[2]); - break; - case "deviation": - if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { - processed += String.fromCodePoint.apply(String, status[2]); - } else { - processed += String.fromCodePoint(codePoint); - } - break; - case "valid": - processed += String.fromCodePoint(codePoint); - break; - case "disallowed_STD3_mapped": - if (useSTD3) { - hasError = true; - processed += String.fromCodePoint(codePoint); - } else { - processed += String.fromCodePoint.apply(String, status[2]); - } - break; - case "disallowed_STD3_valid": - if (useSTD3) { - hasError = true; + // Note: Support for types 1,2,6,7,8 + switch(gn.type) { + // rfc822Name + case 1: + // dNSName + case 2: + // uniformResourceIdentifier (URI) + case 6: + break; + // IPAddress + case 7: + // convert to IPv4/IPv6 string representation + altName.ip = forge.util.bytesToIP(gn.value); + break; + // registeredID + case 8: + altName.oid = asn1.derToOid(gn.value); + break; + default: + // unsupported } - - processed += String.fromCodePoint(codePoint); - break; + } + } else if(e.name === 'subjectKeyIdentifier') { + // value is an OCTETSTRING w/the hash of the key-type specific + // public key structure (eg: RSAPublicKey) + var ev = asn1.fromDer(e.value); + e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); } } + return e; +}; - return { - string: processed, - error: hasError - }; -} - -var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; +/** + * Converts a PKCS#10 certification request (CSR) from an ASN.1 object. + * + * Note: If the certification request is to be verified then compute hash + * should be set to true. There is currently no implementation for converting + * a certificate back to ASN.1 so the CertificationRequestInfo part of the + * ASN.1 object needs to be scanned before the csr object is created. + * + * @param obj the asn1 representation of a PKCS#10 certification request (CSR). + * @param computeHash true to compute the hash for verification. + * + * @return the certification request (CSR). + */ +pki.certificationRequestFromAsn1 = function(obj, computeHash) { + // validate certification request and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#10 certificate request. ' + + 'ASN.1 object is not a PKCS#10 CertificationRequest.'); + error.errors = errors; + throw error; + } -function validateLabel(label, processing_option) { - if (label.substr(0, 4) === "xn--") { - label = punycode.toUnicode(label); - processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); } - var error = false; + // create certification request + var csr = pki.createCertificationRequest(); + csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; + csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.signatureParameters = _readSignatureParameters( + csr.signatureOid, capture.csrSignatureParams, true); + csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.siginfo.parameters = _readSignatureParameters( + csr.siginfo.algorithmOid, capture.csrSignatureParams, false); + csr.signature = capture.csrSignature; + + // keep CertificationRequestInfo to preserve signature when exporting + csr.certificationRequestInfo = capture.certificationRequestInfo; - if (normalize(label) !== label || - (label[3] === "-" && label[4] === "-") || - label[0] === "-" || label[label.length - 1] === "-" || - label.indexOf(".") !== -1 || - label.search(combiningMarksRegex) === 0) { - error = true; - } + if(computeHash) { + // create digest for OID signature type + csr.md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: 'certification request' + }); - var len = countSymbols(label); - for (var i = 0; i < len; ++i) { - var status = findStatus(label.codePointAt(i)); - if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || - (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && - status[1] !== "valid" && status[1] !== "deviation")) { - error = true; - break; - } + // produce DER formatted CertificationRequestInfo and digest it + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); } - return { - label: label, - error: error + // handle subject, build subject message digest + var smd = forge.md.sha1.create(); + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); }; -} - -function processing(domain_name, useSTD3, processing_option) { - var result = mapChars(domain_name, useSTD3, processing_option); - result.string = normalize(result.string); - - var labels = result.string.split("."); - for (var i = 0; i < labels.length; ++i) { - try { - var validation = validateLabel(labels[i]); - labels[i] = validation.label; - result.error = result.error || validation.error; - } catch(e) { - result.error = true; - } - } - - return { - string: labels.join("."), - error: result.error + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); }; -} - -module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { - var result = processing(domain_name, useSTD3, processing_option); - var labels = result.string.split("."); - labels = labels.map(function(l) { - try { - return punycode.toASCII(l); - } catch(e) { - result.error = true; - return l; - } - }); + csr.subject.attributes = pki.RDNAttributesAsArray( + capture.certificationRequestInfoSubject, smd); + csr.subject.hash = smd.digest().toHex(); - if (verifyDnsLength) { - var total = labels.slice(0, labels.length - 1).join(".").length; - if (total.length > 253 || total.length === 0) { - result.error = true; - } + // convert RSA public key from ASN.1 + csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - for (var i=0; i < labels.length; ++i) { - if (labels.length > 63 || labels.length === 0) { - result.error = true; - break; - } - } - } + // convert attributes from ASN.1 + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.attributes = pki.CRIAttributesAsArray( + capture.certificationRequestInfoAttributes || []); - if (result.error) return null; - return labels.join("."); + return csr; }; -module.exports.toUnicode = function(domain_name, useSTD3) { - var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); +/** + * Creates an empty certification request (a CSR or certificate signing + * request). Once created, its public key and attributes can be set and then + * it can be signed. + * + * @return the empty certification request. + */ +pki.createCertificationRequest = function() { + var csr = {}; + csr.version = 0x00; + csr.signatureOid = null; + csr.signature = null; + csr.siginfo = {}; + csr.siginfo.algorithmOid = null; - return { - domain: result.string, - error: result.error + csr.subject = {}; + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); }; -}; - -module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; - - -/***/ }), - -/***/ 5871: -/***/ ((module) => { - -"use strict"; - + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = []; + csr.subject.hash = null; -var conversions = {}; -module.exports = conversions; + csr.publicKey = null; + csr.attributes = []; + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.md = null; -function sign(x) { - return x < 0 ? -1 : 1; -} + /** + * Sets the subject of this certification request. + * + * @param attrs the array of subject attributes to use. + */ + csr.setSubject = function(attrs) { + // set new attributes + _fillMissingFields(attrs); + csr.subject.attributes = attrs; + csr.subject.hash = null; + }; -function evenRound(x) { - // Round x to the nearest integer, choosing the even integer if it lies halfway between two. - if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) - return Math.floor(x); - } else { - return Math.round(x); - } -} + /** + * Sets the attributes of this certification request. + * + * @param attrs the array of attributes to use. + */ + csr.setAttributes = function(attrs) { + // set new attributes + _fillMissingFields(attrs); + csr.attributes = attrs; + }; -function createNumberConversion(bitLength, typeOpts) { - if (!typeOpts.unsigned) { - --bitLength; + /** + * Signs this certification request using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + csr.sign = function(key, md) { + // TODO: get signature OID from private key + csr.md = md || forge.md.sha1.create(); + var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption']; + if(!algorithmOid) { + var error = new Error('Could not compute certification request digest. ' + + 'Unknown message digest algorithm OID.'); + error.algorithm = csr.md.algorithm; + throw error; } - const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); - const upperBound = Math.pow(2, bitLength) - 1; - - const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); - const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); - - return function(V, opts) { - if (!opts) opts = {}; - - let x = +V; - - if (opts.enforceRange) { - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite number"); - } - - x = sign(x) * Math.floor(Math.abs(x)); - if (x < lowerBound || x > upperBound) { - throw new TypeError("Argument is not in byte range"); - } - - return x; - } + csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; - if (!isNaN(x) && opts.clamp) { - x = evenRound(x); + // get CertificationRequestInfo, convert to DER + csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(csr.certificationRequestInfo); - if (x < lowerBound) x = lowerBound; - if (x > upperBound) x = upperBound; - return x; - } + // digest and sign + csr.md.update(bytes.getBytes()); + csr.signature = key.sign(csr.md); + }; - if (!Number.isFinite(x) || x === 0) { - return 0; - } + /** + * Attempts verify the signature on the passed certification request using + * its public key. + * + * A CSR that has been exported to a file in PEM format can be verified using + * OpenSSL using this command: + * + * openssl req -in -verify -noout -text + * + * @return true if verified, false if not. + */ + csr.verify = function() { + var rval = false; - x = sign(x) * Math.floor(Math.abs(x)); - x = x % moduloVal; + var md = csr.md; + if(md === null) { + md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: 'certification request' + }); - if (!typeOpts.unsigned && x >= moduloBound) { - return x - moduloVal; - } else if (typeOpts.unsigned) { - if (x < 0) { - x += moduloVal; - } else if (x === -0) { // don't return negative zero - return 0; - } - } + // produce DER formatted CertificationRequestInfo and digest it + var cri = csr.certificationRequestInfo || + pki.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(cri); + md.update(bytes.getBytes()); + } - return x; + if(md !== null) { + rval = _verifySignature({ + certificate: csr, md: md, signature: csr.signature + }); } -} -conversions["void"] = function () { - return undefined; -}; + return rval; + }; -conversions["boolean"] = function (val) { - return !!val; + return csr; }; -conversions["byte"] = createNumberConversion(8, { unsigned: false }); -conversions["octet"] = createNumberConversion(8, { unsigned: true }); - -conversions["short"] = createNumberConversion(16, { unsigned: false }); -conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); - -conversions["long"] = createNumberConversion(32, { unsigned: false }); -conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); - -conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); -conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); - -conversions["double"] = function (V) { - const x = +V; - - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite floating-point value"); - } +/** + * Converts an X.509 subject or issuer to an ASN.1 RDNSequence. + * + * @param obj the subject or issuer (distinguished name). + * + * @return the ASN.1 RDNSequence. + */ +function _dnToAsn1(obj) { + // create an empty RDNSequence + var rval = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - return x; -}; + // iterate over attributes + var attr, set; + var attrs = obj.attributes; + for(var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + var value = attr.value; -conversions["unrestricted double"] = function (V) { - const x = +V; + // reuse tag class for attribute value if available + var valueTagClass = asn1.Type.PRINTABLESTRING; + if('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; - if (isNaN(x)) { - throw new TypeError("Argument is NaN"); + if(valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + // FIXME: handle more encodings } - return x; -}; - -// not quite valid, but good enough for JS -conversions["float"] = conversions["double"]; -conversions["unrestricted float"] = conversions["unrestricted double"]; - -conversions["DOMString"] = function (V, opts) { - if (!opts) opts = {}; - - if (opts.treatNullAsEmptyString && V === null) { - return ""; - } + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + // AttributeValue + asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) + ]) + ]); + rval.value.push(set); + } - return String(V); -}; + return rval; +} -conversions["ByteString"] = function (V, opts) { - const x = String(V); - let c = undefined; - for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { - if (c > 255) { - throw new TypeError("Argument is not a valid bytestring"); - } +/** + * Gets all printable attributes (typically of an issuer or subject) in a + * simplified JSON format for display. + * + * @param attrs the attributes. + * + * @return the JSON for display. + */ +function _getAttributesAsJson(attrs) { + var rval = {}; + for(var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + if(attr.shortName && ( + attr.valueTagClass === asn1.Type.UTF8 || + attr.valueTagClass === asn1.Type.PRINTABLESTRING || + attr.valueTagClass === asn1.Type.IA5STRING)) { + var value = attr.value; + if(attr.valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(attr.value); + } + if(!(attr.shortName in rval)) { + rval[attr.shortName] = value; + } else if(forge.util.isArray(rval[attr.shortName])) { + rval[attr.shortName].push(value); + } else { + rval[attr.shortName] = [rval[attr.shortName], value]; + } } + } + return rval; +} - return x; -}; +/** + * Fills in missing fields in attributes. + * + * @param attrs the attributes to fill missing fields in. + */ +function _fillMissingFields(attrs) { + var attr; + for(var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; -conversions["USVString"] = function (V) { - const S = String(V); - const n = S.length; - const U = []; - for (let i = 0; i < n; ++i) { - const c = S.charCodeAt(i); - if (c < 0xD800 || c > 0xDFFF) { - U.push(String.fromCodePoint(c)); - } else if (0xDC00 <= c && c <= 0xDFFF) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - if (i === n - 1) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - const d = S.charCodeAt(i + 1); - if (0xDC00 <= d && d <= 0xDFFF) { - const a = c & 0x3FF; - const b = d & 0x3FF; - U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); - ++i; - } else { - U.push(String.fromCodePoint(0xFFFD)); - } - } - } + // populate missing name + if(typeof attr.name === 'undefined') { + if(attr.type && attr.type in pki.oids) { + attr.name = pki.oids[attr.type]; + } else if(attr.shortName && attr.shortName in _shortNames) { + attr.name = pki.oids[_shortNames[attr.shortName]]; + } } - return U.join(''); -}; - -conversions["Date"] = function (V, opts) { - if (!(V instanceof Date)) { - throw new TypeError("Argument is not a Date object"); - } - if (isNaN(V)) { - return undefined; + // populate missing type (OID) + if(typeof attr.type === 'undefined') { + if(attr.name && attr.name in pki.oids) { + attr.type = pki.oids[attr.name]; + } else { + var error = new Error('Attribute type not specified.'); + error.attribute = attr; + throw error; + } } - return V; -}; - -conversions["RegExp"] = function (V, opts) { - if (!(V instanceof RegExp)) { - V = new RegExp(V); + // populate missing shortname + if(typeof attr.shortName === 'undefined') { + if(attr.name && attr.name in _shortNames) { + attr.shortName = _shortNames[attr.name]; + } } - return V; -}; - - -/***/ }), - -/***/ 8262: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -const usm = __nccwpck_require__(33); - -exports.implementation = class URLImpl { - constructor(constructorArgs) { - const url = constructorArgs[0]; - const base = constructorArgs[1]; - - let parsedBase = null; - if (base !== undefined) { - parsedBase = usm.basicURLParse(base); - if (parsedBase === "failure") { - throw new TypeError("Invalid base URL"); + // convert extensions to value + if(attr.type === oids.extensionRequest) { + attr.valueConstructed = true; + attr.valueTagClass = asn1.Type.SEQUENCE; + if(!attr.value && attr.extensions) { + attr.value = []; + for(var ei = 0; ei < attr.extensions.length; ++ei) { + attr.value.push(pki.certificateExtensionToAsn1( + _fillMissingExtensionFields(attr.extensions[ei]))); + } } } - const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); + if(typeof attr.value === 'undefined') { + var error = new Error('Attribute value not specified.'); + error.attribute = attr; + throw error; } - - this._url = parsedURL; - - // TODO: query stuff } +} - get href() { - return usm.serializeURL(this._url); - } +/** + * Fills in missing fields in certificate extensions. + * + * @param e the extension. + * @param [options] the options to use. + * [cert] the certificate the extensions are for. + * + * @return the extension. + */ +function _fillMissingExtensionFields(e, options) { + options = options || {}; - set href(v) { - const parsedURL = usm.basicURLParse(v); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); + // populate missing name + if(typeof e.name === 'undefined') { + if(e.id && e.id in pki.oids) { + e.name = pki.oids[e.id]; } - - this._url = parsedURL; } - get origin() { - return usm.serializeURLOrigin(this._url); - } - - get protocol() { - return this._url.scheme + ":"; + // populate missing id + if(typeof e.id === 'undefined') { + if(e.name && e.name in pki.oids) { + e.id = pki.oids[e.name]; + } else { + var error = new Error('Extension ID not specified.'); + error.extension = e; + throw error; + } } - set protocol(v) { - usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + if(typeof e.value !== 'undefined') { + return e; } - get username() { - return this._url.username; - } + // handle missing value: - set username(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; + // value is a BIT STRING + if(e.name === 'keyUsage') { + // build flags + var unused = 0; + var b2 = 0x00; + var b3 = 0x00; + if(e.digitalSignature) { + b2 |= 0x80; + unused = 7; } - - usm.setTheUsername(this._url, v); - } - - get password() { - return this._url.password; - } - - set password(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; + if(e.nonRepudiation) { + b2 |= 0x40; + unused = 6; } - - usm.setThePassword(this._url, v); - } - - get host() { - const url = this._url; - - if (url.host === null) { - return ""; + if(e.keyEncipherment) { + b2 |= 0x20; + unused = 5; } - - if (url.port === null) { - return usm.serializeHost(url.host); + if(e.dataEncipherment) { + b2 |= 0x10; + unused = 4; } - - return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); - } - - set host(v) { - if (this._url.cannotBeABaseURL) { - return; + if(e.keyAgreement) { + b2 |= 0x08; + unused = 3; } - - usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); - } - - get hostname() { - if (this._url.host === null) { - return ""; + if(e.keyCertSign) { + b2 |= 0x04; + unused = 2; } - - return usm.serializeHost(this._url.host); - } - - set hostname(v) { - if (this._url.cannotBeABaseURL) { - return; + if(e.cRLSign) { + b2 |= 0x02; + unused = 1; + } + if(e.encipherOnly) { + b2 |= 0x01; + unused = 0; + } + if(e.decipherOnly) { + b3 |= 0x80; + unused = 7; } - usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); - } + // create bit string + var value = String.fromCharCode(unused); + if(b3 !== 0) { + value += String.fromCharCode(b2) + String.fromCharCode(b3); + } else if(b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); + } else if(e.name === 'basicConstraints') { + // basicConstraints is a SEQUENCE + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + // cA BOOLEAN flag defaults to false + if(e.cA) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, + String.fromCharCode(0xFF))); + } + if('pathLenConstraint' in e) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(e.pathLenConstraint).getBytes())); + } + } else if(e.name === 'extKeyUsage') { + // extKeyUsage is a SEQUENCE of OIDs + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + for(var key in e) { + if(e[key] !== true) { + continue; + } + // key is name in OID map + if(key in oids) { + seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, + false, asn1.oidToDer(oids[key]).getBytes())); + } else if(key.indexOf('.') !== -1) { + // assume key is an OID + seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, + false, asn1.oidToDer(key).getBytes())); + } + } + } else if(e.name === 'nsCertType') { + // nsCertType is a BIT STRING + // build flags + var unused = 0; + var b2 = 0x00; - get port() { - if (this._url.port === null) { - return ""; + if(e.client) { + b2 |= 0x80; + unused = 7; + } + if(e.server) { + b2 |= 0x40; + unused = 6; + } + if(e.email) { + b2 |= 0x20; + unused = 5; + } + if(e.objsign) { + b2 |= 0x10; + unused = 4; + } + if(e.reserved) { + b2 |= 0x08; + unused = 3; } - - return usm.serializeInteger(this._url.port); - } - - set port(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; + if(e.sslCA) { + b2 |= 0x04; + unused = 2; } - - if (v === "") { - this._url.port = null; - } else { - usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + if(e.emailCA) { + b2 |= 0x02; + unused = 1; } - } - - get pathname() { - if (this._url.cannotBeABaseURL) { - return this._url.path[0]; + if(e.objCA) { + b2 |= 0x01; + unused = 0; } - if (this._url.path.length === 0) { - return ""; + // create bit string + var value = String.fromCharCode(unused); + if(b2 !== 0) { + value += String.fromCharCode(b2); } + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); + } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') { + // SYNTAX SEQUENCE + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - return "/" + this._url.path.join("/"); - } - - set pathname(v) { - if (this._url.cannotBeABaseURL) { - return; + var altName; + for(var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + // handle IP + if(altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if(value === null) { + var error = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if(altName.type === 8) { + // handle OID + if(altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + // deprecated ... convert value to OID + value = asn1.oidToDer(value); + } + } + e.value.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, altName.type, false, + value)); } - - this._url.path = []; - usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); - } - - get search() { - if (this._url.query === null || this._url.query === "") { - return ""; + } else if(e.name === 'nsComment' && options.cert) { + // sanity check value is ASCII (req'd) and not too big + if(!(/^[\x00-\x7F]*$/.test(e.comment)) || + (e.comment.length < 1) || (e.comment.length > 128)) { + throw new Error('Invalid "nsComment" content.'); } + // IA5STRING opaque comment + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment); + } else if(e.name === 'subjectKeyIdentifier' && options.cert) { + var ski = options.cert.generateSubjectKeyIdentifier(); + e.subjectKeyIdentifier = ski.toHex(); + // OCTETSTRING w/digest + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes()); + } else if(e.name === 'authorityKeyIdentifier' && options.cert) { + // SYNTAX SEQUENCE + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; - return "?" + this._url.query; - } - - set search(v) { - // TODO: query stuff - - const url = this._url; - - if (v === "") { - url.query = null; - return; + if(e.keyIdentifier) { + var keyIdentifier = (e.keyIdentifier === true ? + options.cert.generateSubjectKeyIdentifier().getBytes() : + e.keyIdentifier); + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier)); } - const input = v[0] === "?" ? v.substring(1) : v; - url.query = ""; - usm.basicURLParse(input, { url, stateOverride: "query" }); - } + if(e.authorityCertIssuer) { + var authorityCertIssuer = [ + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ + _dnToAsn1(e.authorityCertIssuer === true ? + options.cert.issuer : e.authorityCertIssuer) + ]) + ]; + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer)); + } - get hash() { - if (this._url.fragment === null || this._url.fragment === "") { - return ""; + if(e.serialNumber) { + var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? + options.cert.serialNumber : e.serialNumber); + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber)); } + } else if(e.name === 'cRLDistributionPoints') { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; - return "#" + this._url.fragment; - } + // Create sub SEQUENCE of DistributionPointName + var subSeq = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - set hash(v) { - if (v === "") { - this._url.fragment = null; - return; + // Create fullName CHOICE + var fullNameGeneralNames = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + var altName; + for(var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + // handle IP + if(altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if(value === null) { + var error = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if(altName.type === 8) { + // handle OID + if(altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + // deprecated ... convert value to OID + value = asn1.oidToDer(value); + } + } + fullNameGeneralNames.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, altName.type, false, + value)); } - const input = v[0] === "#" ? v.substring(1) : v; - this._url.fragment = ""; - usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + // Add to the parent SEQUENCE + subSeq.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames])); + seq.push(subSeq); } - toJSON() { - return this.href; + // ensure value has been defined by now + if(typeof e.value === 'undefined') { + var error = new Error('Extension value not specified.'); + error.extension = e; + throw error; } -}; - -/***/ }), + return e; +} -/***/ 653: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Convert signature parameters object to ASN.1 + * + * @param {String} oid Signature algorithm OID + * @param params The signature parametrs object + * @return ASN.1 object representing signature parameters + */ +function _signatureParametersToAsn1(oid, params) { + switch(oid) { + case oids['RSASSA-PSS']: + var parts = []; -"use strict"; + if(params.hash.algorithmOid !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.hash.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ])); + } + if(params.mgf.algorithmOid !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.mgf.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]) + ])); + } -const conversions = __nccwpck_require__(5871); -const utils = __nccwpck_require__(276); -const Impl = __nccwpck_require__(8262); + if(params.saltLength !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(params.saltLength).getBytes()) + ])); + } -const impl = utils.implSymbol; + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); -function URL(url) { - if (!this || this[impl] || !(this instanceof URL)) { - throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); - } - if (arguments.length < 1) { - throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); - } - const args = []; - for (let i = 0; i < arguments.length && i < 2; ++i) { - args[i] = arguments[i]; - } - args[0] = conversions["USVString"](args[0]); - if (args[1] !== undefined) { - args[1] = conversions["USVString"](args[1]); + default: + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''); } - - module.exports.setup(this, args); } -URL.prototype.toJSON = function toJSON() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - const args = []; - for (let i = 0; i < arguments.length && i < 0; ++i) { - args[i] = arguments[i]; - } - return this[impl].toJSON.apply(this[impl], args); -}; -Object.defineProperty(URL.prototype, "href", { - get() { - return this[impl].href; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].href = V; - }, - enumerable: true, - configurable: true -}); - -URL.prototype.toString = function () { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - return this.href; -}; - -Object.defineProperty(URL.prototype, "origin", { - get() { - return this[impl].origin; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "protocol", { - get() { - return this[impl].protocol; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].protocol = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "username", { - get() { - return this[impl].username; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].username = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "password", { - get() { - return this[impl].password; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].password = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "host", { - get() { - return this[impl].host; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].host = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "hostname", { - get() { - return this[impl].hostname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hostname = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "port", { - get() { - return this[impl].port; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].port = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "pathname", { - get() { - return this[impl].pathname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].pathname = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "search", { - get() { - return this[impl].search; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].search = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "hash", { - get() { - return this[impl].hash; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hash = V; - }, - enumerable: true, - configurable: true -}); - - -module.exports = { - is(obj) { - return !!obj && obj[impl] instanceof Impl.implementation; - }, - create(constructorArgs, privateData) { - let obj = Object.create(URL.prototype); - this.setup(obj, constructorArgs, privateData); - return obj; - }, - setup(obj, constructorArgs, privateData) { - if (!privateData) privateData = {}; - privateData.wrapper = obj; +/** + * Converts a certification request's attributes to an ASN.1 set of + * CRIAttributes. + * + * @param csr certification request. + * + * @return the ASN.1 set of CRIAttributes. + */ +function _CRIAttributesToAsn1(csr) { + // create an empty context-specific container + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); - obj[impl] = new Impl.implementation(constructorArgs, privateData); - obj[impl][utils.wrapperSymbol] = obj; - }, - interface: URL, - expose: { - Window: { URL: URL }, - Worker: { URL: URL } + // no attributes, return empty container + if(csr.attributes.length === 0) { + return rval; } -}; - - - -/***/ }), - -/***/ 3323: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -exports.URL = __nccwpck_require__(653)["interface"]; -exports.serializeURL = __nccwpck_require__(33).serializeURL; -exports.serializeURLOrigin = __nccwpck_require__(33).serializeURLOrigin; -exports.basicURLParse = __nccwpck_require__(33).basicURLParse; -exports.setTheUsername = __nccwpck_require__(33).setTheUsername; -exports.setThePassword = __nccwpck_require__(33).setThePassword; -exports.serializeHost = __nccwpck_require__(33).serializeHost; -exports.serializeInteger = __nccwpck_require__(33).serializeInteger; -exports.parseURL = __nccwpck_require__(33).parseURL; - - -/***/ }), - -/***/ 33: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const punycode = __nccwpck_require__(5477); -const tr46 = __nccwpck_require__(2299); - -const specialSchemes = { - ftp: 21, - file: null, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443 -}; - -const failure = Symbol("failure"); - -function countSymbols(str) { - return punycode.ucs2.decode(str).length; -} - -function at(input, idx) { - const c = input[idx]; - return isNaN(c) ? undefined : String.fromCodePoint(c); -} - -function isASCIIDigit(c) { - return c >= 0x30 && c <= 0x39; -} - -function isASCIIAlpha(c) { - return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); -} - -function isASCIIAlphanumeric(c) { - return isASCIIAlpha(c) || isASCIIDigit(c); -} - -function isASCIIHex(c) { - return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); -} - -function isSingleDot(buffer) { - return buffer === "." || buffer.toLowerCase() === "%2e"; -} - -function isDoubleDot(buffer) { - buffer = buffer.toLowerCase(); - return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; -} - -function isWindowsDriveLetterCodePoints(cp1, cp2) { - return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); -} - -function isWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); -} - -function isNormalizedWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; -} - -function containsForbiddenHostCodePoint(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function containsForbiddenHostCodePointExcludingPercent(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function isSpecialScheme(scheme) { - return specialSchemes[scheme] !== undefined; -} - -function isSpecial(url) { - return isSpecialScheme(url.scheme); -} - -function defaultPort(scheme) { - return specialSchemes[scheme]; -} - -function percentEncode(c) { - let hex = c.toString(16).toUpperCase(); - if (hex.length === 1) { - hex = "0" + hex; - } - - return "%" + hex; -} - -function utf8PercentEncode(c) { - const buf = new Buffer(c); - - let str = ""; - - for (let i = 0; i < buf.length; ++i) { - str += percentEncode(buf[i]); - } - - return str; -} - -function utf8PercentDecode(str) { - const input = new Buffer(str); - const output = []; - for (let i = 0; i < input.length; ++i) { - if (input[i] !== 37) { - output.push(input[i]); - } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { - output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); - i += 2; - } else { - output.push(input[i]); - } - } - return new Buffer(output).toString(); -} - -function isC0ControlPercentEncode(c) { - return c <= 0x1F || c > 0x7E; -} - -const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); -function isPathPercentEncode(c) { - return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); -} - -const extraUserinfoPercentEncodeSet = - new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); -function isUserinfoPercentEncode(c) { - return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); -} - -function percentEncodeChar(c, encodeSetPredicate) { - const cStr = String.fromCodePoint(c); - - if (encodeSetPredicate(c)) { - return utf8PercentEncode(cStr); - } - - return cStr; -} - -function parseIPv4Number(input) { - let R = 10; - - if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { - input = input.substring(2); - R = 16; - } else if (input.length >= 2 && input.charAt(0) === "0") { - input = input.substring(1); - R = 8; - } - - if (input === "") { - return 0; - } - - const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); - if (regex.test(input)) { - return failure; - } - - return parseInt(input, R); -} - -function parseIPv4(input) { - const parts = input.split("."); - if (parts[parts.length - 1] === "") { - if (parts.length > 1) { - parts.pop(); - } - } - - if (parts.length > 4) { - return input; - } - - const numbers = []; - for (const part of parts) { - if (part === "") { - return input; - } - const n = parseIPv4Number(part); - if (n === failure) { - return input; - } - - numbers.push(n); - } - - for (let i = 0; i < numbers.length - 1; ++i) { - if (numbers[i] > 255) { - return failure; - } - } - if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { - return failure; - } - - let ipv4 = numbers.pop(); - let counter = 0; - - for (const n of numbers) { - ipv4 += n * Math.pow(256, 3 - counter); - ++counter; - } - - return ipv4; -} - -function serializeIPv4(address) { - let output = ""; - let n = address; - - for (let i = 1; i <= 4; ++i) { - output = String(n % 256) + output; - if (i !== 4) { - output = "." + output; - } - n = Math.floor(n / 256); - } - - return output; -} - -function parseIPv6(input) { - const address = [0, 0, 0, 0, 0, 0, 0, 0]; - let pieceIndex = 0; - let compress = null; - let pointer = 0; - - input = punycode.ucs2.decode(input); - - if (input[pointer] === 58) { - if (input[pointer + 1] !== 58) { - return failure; - } - - pointer += 2; - ++pieceIndex; - compress = pieceIndex; - } - - while (pointer < input.length) { - if (pieceIndex === 8) { - return failure; - } - - if (input[pointer] === 58) { - if (compress !== null) { - return failure; - } - ++pointer; - ++pieceIndex; - compress = pieceIndex; - continue; - } - - let value = 0; - let length = 0; - - while (length < 4 && isASCIIHex(input[pointer])) { - value = value * 0x10 + parseInt(at(input, pointer), 16); - ++pointer; - ++length; - } - - if (input[pointer] === 46) { - if (length === 0) { - return failure; - } - - pointer -= length; - - if (pieceIndex > 6) { - return failure; - } - - let numbersSeen = 0; - - while (input[pointer] !== undefined) { - let ipv4Piece = null; - - if (numbersSeen > 0) { - if (input[pointer] === 46 && numbersSeen < 4) { - ++pointer; - } else { - return failure; - } - } - - if (!isASCIIDigit(input[pointer])) { - return failure; - } - - while (isASCIIDigit(input[pointer])) { - const number = parseInt(at(input, pointer)); - if (ipv4Piece === null) { - ipv4Piece = number; - } else if (ipv4Piece === 0) { - return failure; - } else { - ipv4Piece = ipv4Piece * 10 + number; - } - if (ipv4Piece > 255) { - return failure; - } - ++pointer; - } - - address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; - - ++numbersSeen; - - if (numbersSeen === 2 || numbersSeen === 4) { - ++pieceIndex; - } - } - - if (numbersSeen !== 4) { - return failure; - } - - break; - } else if (input[pointer] === 58) { - ++pointer; - if (input[pointer] === undefined) { - return failure; - } - } else if (input[pointer] !== undefined) { - return failure; - } - - address[pieceIndex] = value; - ++pieceIndex; - } - - if (compress !== null) { - let swaps = pieceIndex - compress; - pieceIndex = 7; - while (pieceIndex !== 0 && swaps > 0) { - const temp = address[compress + swaps - 1]; - address[compress + swaps - 1] = address[pieceIndex]; - address[pieceIndex] = temp; - --pieceIndex; - --swaps; - } - } else if (compress === null && pieceIndex !== 8) { - return failure; - } - - return address; -} - -function serializeIPv6(address) { - let output = ""; - const seqResult = findLongestZeroSequence(address); - const compress = seqResult.idx; - let ignore0 = false; - - for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { - if (ignore0 && address[pieceIndex] === 0) { - continue; - } else if (ignore0) { - ignore0 = false; - } - - if (compress === pieceIndex) { - const separator = pieceIndex === 0 ? "::" : ":"; - output += separator; - ignore0 = true; - continue; - } - - output += address[pieceIndex].toString(16); - - if (pieceIndex !== 7) { - output += ":"; - } - } - - return output; -} - -function parseHost(input, isSpecialArg) { - if (input[0] === "[") { - if (input[input.length - 1] !== "]") { - return failure; - } - - return parseIPv6(input.substring(1, input.length - 1)); - } - - if (!isSpecialArg) { - return parseOpaqueHost(input); - } - - const domain = utf8PercentDecode(input); - const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); - if (asciiDomain === null) { - return failure; - } - - if (containsForbiddenHostCodePoint(asciiDomain)) { - return failure; - } - - const ipv4Host = parseIPv4(asciiDomain); - if (typeof ipv4Host === "number" || ipv4Host === failure) { - return ipv4Host; - } - - return asciiDomain; -} - -function parseOpaqueHost(input) { - if (containsForbiddenHostCodePointExcludingPercent(input)) { - return failure; - } - - let output = ""; - const decoded = punycode.ucs2.decode(input); - for (let i = 0; i < decoded.length; ++i) { - output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); - } - return output; -} - -function findLongestZeroSequence(arr) { - let maxIdx = null; - let maxLen = 1; // only find elements > 1 - let currStart = null; - let currLen = 0; - - for (let i = 0; i < arr.length; ++i) { - if (arr[i] !== 0) { - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - currStart = null; - currLen = 0; - } else { - if (currStart === null) { - currStart = i; - } - ++currLen; - } - } - - // if trailing zeros - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - return { - idx: maxIdx, - len: maxLen - }; -} - -function serializeHost(host) { - if (typeof host === "number") { - return serializeIPv4(host); - } - - // IPv6 serializer - if (host instanceof Array) { - return "[" + serializeIPv6(host) + "]"; - } - - return host; -} - -function trimControlChars(url) { - return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); -} - -function trimTabAndNewline(url) { - return url.replace(/\u0009|\u000A|\u000D/g, ""); -} - -function shortenPath(url) { - const path = url.path; - if (path.length === 0) { - return; - } - if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { - return; - } - - path.pop(); -} - -function includesCredentials(url) { - return url.username !== "" || url.password !== ""; -} - -function cannotHaveAUsernamePasswordPort(url) { - return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; -} - -function isNormalizedWindowsDriveLetter(string) { - return /^[A-Za-z]:$/.test(string); -} - -function URLStateMachine(input, base, encodingOverride, url, stateOverride) { - this.pointer = 0; - this.input = input; - this.base = base || null; - this.encodingOverride = encodingOverride || "utf-8"; - this.stateOverride = stateOverride; - this.url = url; - this.failure = false; - this.parseError = false; - - if (!this.url) { - this.url = { - scheme: "", - username: "", - password: "", - host: null, - port: null, - path: [], - query: null, - fragment: null, - - cannotBeABaseURL: false - }; - - const res = trimControlChars(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - } - - const res = trimTabAndNewline(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - - this.state = stateOverride || "scheme start"; - - this.buffer = ""; - this.atFlag = false; - this.arrFlag = false; - this.passwordTokenSeenFlag = false; - - this.input = punycode.ucs2.decode(this.input); - - for (; this.pointer <= this.input.length; ++this.pointer) { - const c = this.input[this.pointer]; - const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); - - // exec state machine - const ret = this["parse " + this.state](c, cStr); - if (!ret) { - break; // terminate algorithm - } else if (ret === failure) { - this.failure = true; - break; - } - } -} - -URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { - if (isASCIIAlpha(c)) { - this.buffer += cStr.toLowerCase(); - this.state = "scheme"; - } else if (!this.stateOverride) { - this.state = "no scheme"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { - if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { - this.buffer += cStr.toLowerCase(); - } else if (c === 58) { - if (this.stateOverride) { - if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { - return false; - } - - if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { - return false; - } - - if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { - return false; - } - - if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { - return false; - } - } - this.url.scheme = this.buffer; - this.buffer = ""; - if (this.stateOverride) { - return false; - } - if (this.url.scheme === "file") { - if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { - this.parseError = true; - } - this.state = "file"; - } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { - this.state = "special relative or authority"; - } else if (isSpecial(this.url)) { - this.state = "special authority slashes"; - } else if (this.input[this.pointer + 1] === 47) { - this.state = "path or authority"; - ++this.pointer; - } else { - this.url.cannotBeABaseURL = true; - this.url.path.push(""); - this.state = "cannot-be-a-base-URL path"; - } - } else if (!this.stateOverride) { - this.buffer = ""; - this.state = "no scheme"; - this.pointer = -1; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { - if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { - return failure; - } else if (this.base.cannotBeABaseURL && c === 35) { - this.url.scheme = this.base.scheme; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.url.cannotBeABaseURL = true; - this.state = "fragment"; - } else if (this.base.scheme === "file") { - this.state = "file"; - --this.pointer; - } else { - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { - if (c === 47) { - this.state = "authority"; - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative"] = function parseRelative(c) { - this.url.scheme = this.base.scheme; - if (isNaN(c)) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 47) { - this.state = "relative slash"; - } else if (c === 63) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else if (isSpecial(this.url) && c === 92) { - this.parseError = true; - this.state = "relative slash"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(0, this.base.path.length - 1); - - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { - if (isSpecial(this.url) && (c === 47 || c === 92)) { - if (c === 92) { - this.parseError = true; - } - this.state = "special authority ignore slashes"; - } else if (c === 47) { - this.state = "authority"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "special authority ignore slashes"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { - if (c !== 47 && c !== 92) { - this.state = "authority"; - --this.pointer; - } else { - this.parseError = true; - } - - return true; -}; - -URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { - if (c === 64) { - this.parseError = true; - if (this.atFlag) { - this.buffer = "%40" + this.buffer; - } - this.atFlag = true; - - // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars - const len = countSymbols(this.buffer); - for (let pointer = 0; pointer < len; ++pointer) { - const codePoint = this.buffer.codePointAt(pointer); - - if (codePoint === 58 && !this.passwordTokenSeenFlag) { - this.passwordTokenSeenFlag = true; - continue; - } - const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); - if (this.passwordTokenSeenFlag) { - this.url.password += encodedCodePoints; - } else { - this.url.username += encodedCodePoints; - } - } - this.buffer = ""; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - if (this.atFlag && this.buffer === "") { - this.parseError = true; - return failure; - } - this.pointer -= countSymbols(this.buffer) + 1; - this.buffer = ""; - this.state = "host"; - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse hostname"] = -URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { - if (this.stateOverride && this.url.scheme === "file") { - --this.pointer; - this.state = "file host"; - } else if (c === 58 && !this.arrFlag) { - if (this.buffer === "") { - this.parseError = true; - return failure; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "port"; - if (this.stateOverride === "hostname") { - return false; - } - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - --this.pointer; - if (isSpecial(this.url) && this.buffer === "") { - this.parseError = true; - return failure; - } else if (this.stateOverride && this.buffer === "" && - (includesCredentials(this.url) || this.url.port !== null)) { - this.parseError = true; - return false; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "path start"; - if (this.stateOverride) { - return false; - } - } else { - if (c === 91) { - this.arrFlag = true; - } else if (c === 93) { - this.arrFlag = false; - } - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { - if (isASCIIDigit(c)) { - this.buffer += cStr; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92) || - this.stateOverride) { - if (this.buffer !== "") { - const port = parseInt(this.buffer); - if (port > Math.pow(2, 16) - 1) { - this.parseError = true; - return failure; - } - this.url.port = port === defaultPort(this.url.scheme) ? null : port; - this.buffer = ""; - } - if (this.stateOverride) { - return false; - } - this.state = "path start"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); - -URLStateMachine.prototype["parse file"] = function parseFile(c) { - this.url.scheme = "file"; - - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file slash"; - } else if (this.base !== null && this.base.scheme === "file") { - if (isNaN(c)) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 63) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else { - if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points - !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || - (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points - !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - shortenPath(this.url); - } else { - this.parseError = true; - } - - this.state = "path"; - --this.pointer; - } - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file host"; - } else { - if (this.base !== null && this.base.scheme === "file") { - if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { - this.url.path.push(this.base.path[0]); - } else { - this.url.host = this.base.host; - } - } - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { - if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { - --this.pointer; - if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { - this.parseError = true; - this.state = "path"; - } else if (this.buffer === "") { - this.url.host = ""; - if (this.stateOverride) { - return false; - } - this.state = "path start"; - } else { - let host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - if (host === "localhost") { - host = ""; - } - this.url.host = host; - - if (this.stateOverride) { - return false; - } - - this.buffer = ""; - this.state = "path start"; - } - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { - if (isSpecial(this.url)) { - if (c === 92) { - this.parseError = true; - } - this.state = "path"; - - if (c !== 47 && c !== 92) { - --this.pointer; - } - } else if (!this.stateOverride && c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (!this.stateOverride && c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else if (c !== undefined) { - this.state = "path"; - if (c !== 47) { - --this.pointer; - } - } - - return true; -}; - -URLStateMachine.prototype["parse path"] = function parsePath(c) { - if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || - (!this.stateOverride && (c === 63 || c === 35))) { - if (isSpecial(this.url) && c === 92) { - this.parseError = true; - } - - if (isDoubleDot(this.buffer)) { - shortenPath(this.url); - if (c !== 47 && !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } - } else if (isSingleDot(this.buffer) && c !== 47 && - !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } else if (!isSingleDot(this.buffer)) { - if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { - if (this.url.host !== "" && this.url.host !== null) { - this.parseError = true; - this.url.host = ""; - } - this.buffer = this.buffer[0] + ":"; - } - this.url.path.push(this.buffer); - } - this.buffer = ""; - if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { - while (this.url.path.length > 1 && this.url.path[0] === "") { - this.parseError = true; - this.url.path.shift(); - } - } - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += percentEncodeChar(c, isPathPercentEncode); - } - - return true; -}; - -URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else { - // TODO: Add: not a URL code point - if (!isNaN(c) && c !== 37) { - this.parseError = true; - } - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - if (!isNaN(c)) { - this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); - } - } - - return true; -}; - -URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { - if (isNaN(c) || (!this.stateOverride && c === 35)) { - if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { - this.encodingOverride = "utf-8"; - } - - const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead - for (let i = 0; i < buffer.length; ++i) { - if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || - buffer[i] === 0x3C || buffer[i] === 0x3E) { - this.url.query += percentEncode(buffer[i]); - } else { - this.url.query += String.fromCodePoint(buffer[i]); - } - } - - this.buffer = ""; - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { - if (isNaN(c)) { // do nothing - } else if (c === 0x0) { - this.parseError = true; - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); - } - - return true; -}; - -function serializeURL(url, excludeFragment) { - let output = url.scheme + ":"; - if (url.host !== null) { - output += "//"; - - if (url.username !== "" || url.password !== "") { - output += url.username; - if (url.password !== "") { - output += ":" + url.password; - } - output += "@"; - } - - output += serializeHost(url.host); - - if (url.port !== null) { - output += ":" + url.port; - } - } else if (url.host === null && url.scheme === "file") { - output += "//"; - } - - if (url.cannotBeABaseURL) { - output += url.path[0]; - } else { - for (const string of url.path) { - output += "/" + string; - } - } - - if (url.query !== null) { - output += "?" + url.query; - } - - if (!excludeFragment && url.fragment !== null) { - output += "#" + url.fragment; - } - - return output; -} - -function serializeOrigin(tuple) { - let result = tuple.scheme + "://"; - result += serializeHost(tuple.host); - - if (tuple.port !== null) { - result += ":" + tuple.port; - } - - return result; -} - -module.exports.serializeURL = serializeURL; - -module.exports.serializeURLOrigin = function (url) { - // https://url.spec.whatwg.org/#concept-url-origin - switch (url.scheme) { - case "blob": - try { - return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); - } catch (e) { - // serializing an opaque origin returns "null" - return "null"; - } - case "ftp": - case "gopher": - case "http": - case "https": - case "ws": - case "wss": - return serializeOrigin({ - scheme: url.scheme, - host: url.host, - port: url.port - }); - case "file": - // spec says "exercise to the reader", chrome says "file://" - return "file://"; - default: - // serializing an opaque origin returns "null" - return "null"; - } -}; - -module.exports.basicURLParse = function (input, options) { - if (options === undefined) { - options = {}; - } - - const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); - if (usm.failure) { - return "failure"; - } - - return usm.url; -}; - -module.exports.setTheUsername = function (url, username) { - url.username = ""; - const decoded = punycode.ucs2.decode(username); - for (let i = 0; i < decoded.length; ++i) { - url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.setThePassword = function (url, password) { - url.password = ""; - const decoded = punycode.ucs2.decode(password); - for (let i = 0; i < decoded.length; ++i) { - url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.serializeHost = serializeHost; - -module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; - -module.exports.serializeInteger = function (integer) { - return String(integer); -}; - -module.exports.parseURL = function (input, options) { - if (options === undefined) { - options = {}; - } - - // We don't handle blobs, so this just delegates: - return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); -}; - - -/***/ }), -/***/ 276: -/***/ ((module) => { - -"use strict"; + // each attribute has a sequence with a type and a set of values + var attrs = csr.attributes; + for(var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + var value = attr.value; + // reuse tag class for attribute value if available + var valueTagClass = asn1.Type.UTF8; + if('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + } + if(valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + var valueConstructed = false; + if('valueConstructed' in attr) { + valueConstructed = attr.valueConstructed; + } + // FIXME: handle more encodings -module.exports.mixin = function mixin(target, source) { - const keys = Object.getOwnPropertyNames(source); - for (let i = 0; i < keys.length; ++i) { - Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + asn1.create( + asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value) + ]) + ]); + rval.value.push(seq); } -}; - -module.exports.wrapperSymbol = Symbol("wrapper"); -module.exports.implSymbol = Symbol("impl"); - -module.exports.wrapperForImpl = function (impl) { - return impl[module.exports.wrapperSymbol]; -}; - -module.exports.implForWrapper = function (wrapper) { - return wrapper[module.exports.implSymbol]; -}; - - -/***/ }), + return rval; +} -/***/ 7994: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); +var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); /** - * Advanced Encryption Standard (AES) implementation. - * - * This implementation is based on the public domain library 'jscrypto' which - * was written by: - * - * Emily Stark (estark@stanford.edu) - * Mike Hamburg (mhamburg@stanford.edu) - * Dan Boneh (dabo@cs.stanford.edu) - * - * Parts of this code are based on the OpenSSL implementation of AES: - * http://www.openssl.org + * Converts a Date object to ASN.1 + * Handles the different format before and after 1st January 2050 * - * @author Dave Longley + * @param date date object. * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * @return the ASN.1 object representing the date. */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7088); -__nccwpck_require__(873); -__nccwpck_require__(8339); - -/* AES API */ -module.exports = forge.aes = forge.aes || {}; +function _dateToAsn1(date) { + if(date >= jan_1_1950 && date < jan_1_2050) { + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, + asn1.dateToUtcTime(date)); + } else { + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, + asn1.dateToGeneralizedTime(date)); + } +} /** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('AES-', key); - * cipher.start({iv: iv}); - * - * Creates an AES cipher object to encrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as a string of bytes, an array of bytes, - * a byte buffer, or an array of 32-bit words. + * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate. * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC'). + * @param cert the certificate. * - * @return the cipher. + * @return the asn1 TBSCertificate. */ -forge.aes.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key: key, - output: output, - decrypt: false, - mode: mode - }); - cipher.start(iv); - return cipher; -}; +pki.getTBSCertificate = function(cert) { + // TBSCertificate + var notBefore = _dateToAsn1(cert.validity.notBefore); + var notAfter = _dateToAsn1(cert.validity.notAfter); + var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // integer + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(cert.version).getBytes()) + ]), + // serialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(cert.serialNumber)), + // signature + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()), + // parameters + _signatureParametersToAsn1( + cert.siginfo.algorithmOid, cert.siginfo.parameters) + ]), + // issuer + _dnToAsn1(cert.issuer), + // validity + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + notBefore, + notAfter + ]), + // subject + _dnToAsn1(cert.subject), + // SubjectPublicKeyInfo + pki.publicKeyToAsn1(cert.publicKey) + ]); -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('AES-', key); - * - * Creates an AES cipher object to encrypt data using the given symmetric key. - * - * The key may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. + if(cert.issuer.uniqueId) { + // issuerUniqueID (optional) + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0x00) + + cert.issuer.uniqueId + ) + ]) + ); + } + if(cert.subject.uniqueId) { + // subjectUniqueID (optional) + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0x00) + + cert.subject.uniqueId + ) + ]) + ); + } + + if(cert.extensions.length > 0) { + // extensions (optional) + tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions)); + } + + return tbs; +}; + +/** + * Gets the ASN.1 CertificationRequestInfo part of a + * PKCS#10 CertificationRequest. * - * @param key the symmetric key to use. - * @param mode the cipher mode to use (default: 'CBC'). + * @param csr the certification request. * - * @return the cipher. + * @return the asn1 CertificationRequestInfo. */ -forge.aes.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key: key, - output: null, - decrypt: false, - mode: mode - }); +pki.getCertificationRequestInfo = function(csr) { + // CertificationRequestInfo + var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(csr.version).getBytes()), + // subject + _dnToAsn1(csr.subject), + // SubjectPublicKeyInfo + pki.publicKeyToAsn1(csr.publicKey), + // attributes + _CRIAttributesToAsn1(csr) + ]); + + return cri; }; /** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('AES-', key); - * decipher.start({iv: iv}); - * - * Creates an AES cipher object to decrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as a string of bytes, an array of bytes, - * a byte buffer, or an array of 32-bit words. + * Converts a DistinguishedName (subject or issuer) to an ASN.1 object. * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC'). + * @param dn the DistinguishedName. * - * @return the cipher. + * @return the asn1 representation of a DistinguishedName. */ -forge.aes.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key: key, - output: output, - decrypt: true, - mode: mode - }); - cipher.start(iv); - return cipher; +pki.distinguishedNameToAsn1 = function(dn) { + return _dnToAsn1(dn); }; /** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('AES-', key); - * - * Creates an AES cipher object to decrypt data using the given symmetric key. - * - * The key may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. + * Converts an X.509v3 RSA certificate to an ASN.1 object. * - * @param key the symmetric key to use. - * @param mode the cipher mode to use (default: 'CBC'). + * @param cert the certificate. * - * @return the cipher. + * @return the asn1 representation of an X.509v3 RSA certificate. */ -forge.aes.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key: key, - output: null, - decrypt: true, - mode: mode - }); +pki.certificateToAsn1 = function(cert) { + // prefer cached TBSCertificate over generating one + var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert); + + // Certificate + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // TBSCertificate + tbsCertificate, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(cert.signatureOid).getBytes()), + // parameters + _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) + ]), + // SignatureValue + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + String.fromCharCode(0x00) + cert.signature) + ]); }; /** - * Creates a new AES cipher algorithm object. + * Converts X.509v3 certificate extensions to ASN.1. * - * @param name the name of the algorithm. - * @param mode the mode factory function. + * @param exts the extensions to convert. * - * @return the AES algorithm object. + * @return the extensions in ASN.1 format. */ -forge.aes.Algorithm = function(name, mode) { - if(!init) { - initialize(); +pki.certificateExtensionsToAsn1 = function(exts) { + // create top-level extension container + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); + + // create extension sequence (stores a sequence for each extension) + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + rval.value.push(seq); + + for(var i = 0; i < exts.length; ++i) { + seq.value.push(pki.certificateExtensionToAsn1(exts[i])); } - var self = this; - self.name = name; - self.mode = new mode({ - blockSize: 16, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self._w, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self._w, inBlock, outBlock, true); - } - } - }); - self._init = false; + + return rval; }; /** - * Initializes this AES algorithm by expanding its key. + * Converts a single certificate extension to ASN.1. * - * @param options the options to use. - * key the key to use with this algorithm. - * decrypt true if the algorithm should be initialized for decryption, - * false for encryption. + * @param ext the extension to convert. + * + * @return the extension in ASN.1 format. */ -forge.aes.Algorithm.prototype.initialize = function(options) { - if(this._init) { - return; - } - - var key = options.key; - var tmp; - - /* Note: The key may be a string of bytes, an array of bytes, a byte - buffer, or an array of 32-bit integers. If the key is in bytes, then - it must be 16, 24, or 32 bytes in length. If it is in 32-bit - integers, it must be 4, 6, or 8 integers long. */ - - if(typeof key === 'string' && - (key.length === 16 || key.length === 24 || key.length === 32)) { - // convert key string into byte buffer - key = forge.util.createBuffer(key); - } else if(forge.util.isArray(key) && - (key.length === 16 || key.length === 24 || key.length === 32)) { - // convert key integer array into byte buffer - tmp = key; - key = forge.util.createBuffer(); - for(var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } +pki.certificateExtensionToAsn1 = function(ext) { + // create a sequence for each extension + var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - // convert key byte buffer into 32-bit integer array - if(!forge.util.isArray(key)) { - tmp = key; - key = []; + // extnID (OID) + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(ext.id).getBytes())); - // key lengths of 16, 24, 32 bytes allowed - var len = tmp.length(); - if(len === 16 || len === 24 || len === 32) { - len = len >>> 2; - for(var i = 0; i < len; ++i) { - key.push(tmp.getInt32()); - } - } + // critical defaults to false + if(ext.critical) { + // critical BOOLEAN DEFAULT FALSE + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, + String.fromCharCode(0xFF))); } - // key must be an array of 32-bit integers by now - if(!forge.util.isArray(key) || - !(key.length === 4 || key.length === 6 || key.length === 8)) { - throw new Error('Invalid key parameter.'); + var value = ext.value; + if(typeof ext.value !== 'string') { + // value is asn.1 + value = asn1.toDer(value).getBytes(); } - // encryption operation is always used for these modes - var mode = this.mode.name; - var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); + // extnValue (OCTET STRING) + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value)); - // do key expansion - this._w = _expandKey(key, options.decrypt && !encryptOp); - this._init = true; + return extseq; }; /** - * Expands a key. Typically only used for testing. - * - * @param key the symmetric key to expand, as an array of 32-bit words. - * @param decrypt true to expand for decryption, false for encryption. + * Converts a PKCS#10 certification request to an ASN.1 object. * - * @return the expanded key. - */ -forge.aes._expandKey = function(key, decrypt) { - if(!init) { - initialize(); - } - return _expandKey(key, decrypt); -}; - -/** - * Updates a single block. Typically only used for testing. + * @param csr the certification request. * - * @param w the expanded key to use. - * @param input an array of block-size 32-bit words. - * @param output an array of block-size 32-bit words. - * @param decrypt true to decrypt, false to encrypt. + * @return the asn1 representation of a certification request. */ -forge.aes._updateBlock = _updateBlock; - -/** Register AES algorithms **/ - -registerAlgorithm('AES-ECB', forge.cipher.modes.ecb); -registerAlgorithm('AES-CBC', forge.cipher.modes.cbc); -registerAlgorithm('AES-CFB', forge.cipher.modes.cfb); -registerAlgorithm('AES-OFB', forge.cipher.modes.ofb); -registerAlgorithm('AES-CTR', forge.cipher.modes.ctr); -registerAlgorithm('AES-GCM', forge.cipher.modes.gcm); - -function registerAlgorithm(name, mode) { - var factory = function() { - return new forge.aes.Algorithm(name, mode); - }; - forge.cipher.registerAlgorithm(name, factory); -} - -/** AES implementation **/ +pki.certificationRequestToAsn1 = function(csr) { + // prefer cached CertificationRequestInfo over generating one + var cri = csr.certificationRequestInfo || + pki.getCertificationRequestInfo(csr); -var init = false; // not yet initialized -var Nb = 4; // number of words comprising the state (AES = 4) -var sbox; // non-linear substitution table used in key expansion -var isbox; // inversion of sbox -var rcon; // round constant word array -var mix; // mix-columns table -var imix; // inverse mix-columns table + // Certificate + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // CertificationRequestInfo + cri, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(csr.signatureOid).getBytes()), + // parameters + _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) + ]), + // signature + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + String.fromCharCode(0x00) + csr.signature) + ]); +}; /** - * Performs initialization, ie: precomputes tables to optimize for speed. - * - * One way to understand how AES works is to imagine that 'addition' and - * 'multiplication' are interfaces that require certain mathematical - * properties to hold true (ie: they are associative) but they might have - * different implementations and produce different kinds of results ... - * provided that their mathematical properties remain true. AES defines - * its own methods of addition and multiplication but keeps some important - * properties the same, ie: associativity and distributivity. The - * explanation below tries to shed some light on how AES defines addition - * and multiplication of bytes and 32-bit words in order to perform its - * encryption and decryption algorithms. - * - * The basics: - * - * The AES algorithm views bytes as binary representations of polynomials - * that have either 1 or 0 as the coefficients. It defines the addition - * or subtraction of two bytes as the XOR operation. It also defines the - * multiplication of two bytes as a finite field referred to as GF(2^8) - * (Note: 'GF' means "Galois Field" which is a field that contains a finite - * number of elements so GF(2^8) has 256 elements). - * - * This means that any two bytes can be represented as binary polynomials; - * when they multiplied together and modularly reduced by an irreducible - * polynomial of the 8th degree, the results are the field GF(2^8). The - * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. - * This multiplication is associative with 0x01 as the identity: - * - * (b * 0x01 = GF(b, 0x01) = b). - * - * The operation GF(b, 0x02) can be performed at the byte level by left - * shifting b once and then XOR'ing it (to perform the modular reduction) - * with 0x11b if b is >= 128. Repeated application of the multiplication - * of 0x02 can be used to implement the multiplication of any two bytes. - * - * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can - * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these - * factors can each be multiplied by 0x57 and then added together. To do - * the multiplication, values for 0x57 multiplied by each of these 3 factors - * can be precomputed and stored in a table. To add them, the values from - * the table are XOR'd together. - * - * AES also defines addition and multiplication of words, that is 4-byte - * numbers represented as polynomials of 3 degrees where the coefficients - * are the values of the bytes. - * - * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. - * - * Addition is performed by XOR'ing like powers of x. Multiplication - * is performed in two steps, the first is an algebriac expansion as - * you would do normally (where addition is XOR). But the result is - * a polynomial larger than 3 degrees and thus it cannot fit in a word. So - * next the result is modularly reduced by an AES-specific polynomial of - * degree 4 which will always produce a polynomial of less than 4 degrees - * such that it will fit in a word. In AES, this polynomial is x^4 + 1. - * - * The modular product of two polynomials 'a' and 'b' is thus: - * - * d(x) = d3x^3 + d2x^2 + d1x + d0 - * with - * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) - * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) - * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) - * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) - * - * As a matrix: - * - * [d0] = [a0 a3 a2 a1][b0] - * [d1] [a1 a0 a3 a2][b1] - * [d2] [a2 a1 a0 a3][b2] - * [d3] [a3 a2 a1 a0][b3] - * - * Special polynomials defined by AES (0x02 == {02}): - * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} - * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. - * - * These polynomials are used in the MixColumns() and InverseMixColumns() - * operations, respectively, to cause each element in the state to affect - * the output (referred to as diffusing). - * - * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the - * polynomial x3. - * - * The ShiftRows() method modifies the last 3 rows in the state (where - * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. - * The 1st byte in the second row is moved to the end of the row. The 1st - * and 2nd bytes in the third row are moved to the end of the row. The 1st, - * 2nd, and 3rd bytes are moved in the fourth row. - * - * More details on how AES arithmetic works: - * - * In the polynomial representation of binary numbers, XOR performs addition - * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) - * corresponds with the multiplication of polynomials modulo an irreducible - * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply - * polynomial 'a' with polynomial 'b' and then do a modular reduction by - * an AES-specific irreducible polynomial of degree 8. - * - * A polynomial is irreducible if its only divisors are one and itself. For - * the AES algorithm, this irreducible polynomial is: - * - * m(x) = x^8 + x^4 + x^3 + x + 1, - * - * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: - * 100011011 = 283 = 0x11b. - * - * For example, GF(0x57, 0x83) = 0xc1 because - * - * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 - * 0x85 = 131 = 10000101 = x^7 + x + 1 - * - * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) - * = x^13 + x^11 + x^9 + x^8 + x^7 + - * x^7 + x^5 + x^3 + x^2 + x + - * x^6 + x^4 + x^2 + x + 1 - * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y - * y modulo (x^8 + x^4 + x^3 + x + 1) - * = x^7 + x^6 + 1. - * - * The modular reduction by m(x) guarantees the result will be a binary - * polynomial of less than degree 8, so that it can fit in a byte. - * - * The operation to multiply a binary polynomial b with x (the polynomial - * x in binary representation is 00000010) is: - * - * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 - * - * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the - * most significant bit is 0 in b) then the result is already reduced. If - * it is 1, then we can reduce it by subtracting m(x) via an XOR. - * - * It follows that multiplication by x (00000010 or 0x02) can be implemented - * by performing a left shift followed by a conditional bitwise XOR with - * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by - * higher powers of x can be implemented by repeated application of xtime(). - * - * By adding intermediate results, multiplication by any constant can be - * implemented. For instance: - * - * GF(0x57, 0x13) = 0xfe because: - * - * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) - * - * Note: We XOR with 0x11b instead of 0x1b because in javascript our - * datatype for b can be larger than 1 byte, so a left shift will not - * automatically eliminate bits that overflow a byte ... by XOR'ing the - * overflow bit with 1 (the extra one from 0x11b) we zero it out. - * - * GF(0x57, 0x02) = xtime(0x57) = 0xae - * GF(0x57, 0x04) = xtime(0xae) = 0x47 - * GF(0x57, 0x08) = xtime(0x47) = 0x8e - * GF(0x57, 0x10) = xtime(0x8e) = 0x07 - * - * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) + * Creates a CA store. * - * And by the distributive property (since XOR is addition and GF() is - * multiplication): + * @param certs an optional array of certificate objects or PEM-formatted + * certificate strings to add to the CA store. * - * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) - * = 0x57 ^ 0xae ^ 0x07 - * = 0xfe. + * @return the CA store. */ -function initialize() { - init = true; - - /* Populate the Rcon table. These are the values given by - [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) - in the field of GF(2^8), where i starts at 1. - - rcon[0] = [0x00, 0x00, 0x00, 0x00] - rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 - rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 - ... - rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B - rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 - - We only store the first byte because it is the only one used. - */ - rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; - - // compute xtime table which maps i onto GF(i, 0x02) - var xtime = new Array(256); - for(var i = 0; i < 128; ++i) { - xtime[i] = i << 1; - xtime[i + 128] = (i + 128) << 1 ^ 0x11B; - } - - // compute all other tables - sbox = new Array(256); - isbox = new Array(256); - mix = new Array(4); - imix = new Array(4); - for(var i = 0; i < 4; ++i) { - mix[i] = new Array(256); - imix[i] = new Array(256); - } - var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; - for(var i = 0; i < 256; ++i) { - /* We need to generate the SubBytes() sbox and isbox tables so that - we can perform byte substitutions. This requires us to traverse - all of the elements in GF, find their multiplicative inverses, - and apply to each the following affine transformation: - - bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ - b(i + 7) mod 8 ^ ci - for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the - ith bit of a byte c with the value {63} or {01100011}. - - It is possible to traverse every possible value in a Galois field - using what is referred to as a 'generator'. There are many - generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully - traverse GF we iterate 255 times, multiplying by our generator - each time. +pki.createCaStore = function(certs) { + // create CA store + var caStore = { + // stored certificates + certs: {} + }; - On each iteration we can determine the multiplicative inverse for - the current element. + /** + * Gets the certificate that issued the passed certificate or its + * 'parent'. + * + * @param cert the certificate to get the parent for. + * + * @return the parent certificate or null if none was found. + */ + caStore.getIssuer = function(cert) { + var rval = getBySubject(cert.issuer); - Suppose there is an element in GF 'e'. For a given generator 'g', - e = g^x. The multiplicative inverse of e is g^(255 - x). It turns - out that if use the inverse of a generator as another generator - it will produce all of the corresponding multiplicative inverses - at the same time. For this reason, we choose 5 as our inverse - generator because it only requires 2 multiplies and 1 add and its - inverse, 82, requires relatively few operations as well. + // see if there are multiple matches + /*if(forge.util.isArray(rval)) { + // TODO: resolve multiple matches by checking + // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc. + // FIXME: or alternatively do authority key mapping + // if possible (X.509v1 certs can't work?) + throw new Error('Resolving multiple issuer matches not implemented yet.'); + }*/ - In order to apply the affine transformation, the multiplicative - inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a - bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and - 'x'. Then 's' is left shifted and the high bit of 's' is made the - low bit. The resulting value is stored in 's'. Then 'x' is XOR'd - with 's' and stored in 'x'. On each subsequent iteration the same - operation is performed. When 4 iterations are complete, 'x' is - XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. - For example: + return rval; + }; - s = 01000001 - x = 01000001 + /** + * Adds a trusted certificate to the store. + * + * @param cert the certificate to add as a trusted certificate (either a + * pki.certificate object or a PEM-formatted certificate). + */ + caStore.addCertificate = function(cert) { + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } - iteration 1: s = 10000010, x ^= s - iteration 2: s = 00000101, x ^= s - iteration 3: s = 00001010, x ^= s - iteration 4: s = 00010100, x ^= s - x ^= 0x63 + ensureSubjectHasHash(cert.subject); - This can be done with a loop where s = (s << 1) | (s >> 7). However, - it can also be done by using a single 16-bit (in this case 32-bit) - number 'sx'. Since XOR is an associative operation, we can set 'sx' - to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. - The most significant bits will flow into the high 8 bit positions - and be correctly XOR'd with one another. All that remains will be - to cycle the high 8 bits by XOR'ing them all with the lower 8 bits - afterwards. + if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store + if(cert.subject.hash in caStore.certs) { + // subject hash already exists, append to array + var tmp = caStore.certs[cert.subject.hash]; + if(!forge.util.isArray(tmp)) { + tmp = [tmp]; + } + tmp.push(cert); + caStore.certs[cert.subject.hash] = tmp; + } else { + caStore.certs[cert.subject.hash] = cert; + } + } + }; - At the same time we're populating sbox and isbox we can precompute - the multiplication we'll need to do to do MixColumns() later. - */ + /** + * Checks to see if the given certificate is in the store. + * + * @param cert the certificate to check (either a pki.certificate or a + * PEM-formatted certificate). + * + * @return true if the certificate is in the store, false if not. + */ + caStore.hasCertificate = function(cert) { + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } - // apply affine transformation - sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); - sx = (sx >> 8) ^ (sx & 255) ^ 0x63; + var match = getBySubject(cert.subject); + if(!match) { + return false; + } + if(!forge.util.isArray(match)) { + match = [match]; + } + // compare DER-encoding of certificates + var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes(); + for(var i = 0; i < match.length; ++i) { + var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes(); + if(der1 === der2) { + return true; + } + } + return false; + }; - // update tables - sbox[e] = sx; - isbox[sx] = e; + /** + * Lists all of the certificates kept in the store. + * + * @return an array of all of the pki.certificate objects in the store. + */ + caStore.listAllCertificates = function() { + var certList = []; - /* Mixing columns is done using matrix multiplication. The columns - that are to be mixed are each a single word in the current state. - The state has Nb columns (4 columns). Therefore each column is a - 4 byte word. So to mix the columns in a single column 'c' where - its rows are r0, r1, r2, and r3, we use the following matrix - multiplication: + for(var hash in caStore.certs) { + if(caStore.certs.hasOwnProperty(hash)) { + var value = caStore.certs[hash]; + if(!forge.util.isArray(value)) { + certList.push(value); + } else { + for(var i = 0; i < value.length; ++i) { + certList.push(value[i]); + } + } + } + } - [2 3 1 1]*[r0,c]=[r'0,c] - [1 2 3 1] [r1,c] [r'1,c] - [1 1 2 3] [r2,c] [r'2,c] - [3 1 1 2] [r3,c] [r'3,c] + return certList; + }; - r0, r1, r2, and r3 are each 1 byte of one of the words in the - state (a column). To do matrix multiplication for each mixed - column c' we multiply the corresponding row from the left matrix - with the corresponding column from the right matrix. In total, we - get 4 equations: + /** + * Removes a certificate from the store. + * + * @param cert the certificate to remove (either a pki.certificate or a + * PEM-formatted certificate). + * + * @return the certificate that was removed or null if the certificate + * wasn't in store. + */ + caStore.removeCertificate = function(cert) { + var result; - r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c - r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c - r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c - r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + ensureSubjectHasHash(cert.subject); + if(!caStore.hasCertificate(cert)) { + return null; + } - As usual, the multiplication is as previously defined and the - addition is XOR. In order to optimize mixing columns we can store - the multiplication results in tables. If you think of the whole - column as a word (it might help to visualize by mentally rotating - the equations above by counterclockwise 90 degrees) then you can - see that it would be useful to map the multiplications performed on - each byte (r0, r1, r2, r3) onto a word as well. For instance, we - could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the - highest 8 bits and 3*r0 in the lowest 8 bits (with the other two - respectively in the middle). This means that a table can be - constructed that uses r0 as an index to the word. We can do the - same with r1, r2, and r3, creating a total of 4 tables. + var match = getBySubject(cert.subject); - To construct a full c', we can just look up each byte of c in - their respective tables and XOR the results together. + if(!forge.util.isArray(match)) { + result = caStore.certs[cert.subject.hash]; + delete caStore.certs[cert.subject.hash]; + return result; + } - Also, to build each table we only have to calculate the word - for 2,1,1,3 for every byte ... which we can do on each iteration - of this loop since we will iterate over every byte. After we have - calculated 2,1,1,3 we can get the results for the other tables - by cycling the byte at the end to the beginning. For instance - we can take the result of table 2,1,1,3 and produce table 3,2,1,1 - by moving the right most byte to the left most position just like - how you can imagine the 3 moved out of 2,1,1,3 and to the front - to produce 3,2,1,1. + // compare DER-encoding of certificates + var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes(); + for(var i = 0; i < match.length; ++i) { + var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes(); + if(der1 === der2) { + result = match[i]; + match.splice(i, 1); + } + } + if(match.length === 0) { + delete caStore.certs[cert.subject.hash]; + } - There is another optimization in that the same multiples of - the current element we need in order to advance our generator - to the next iteration can be reused in performing the 2,1,1,3 - calculation. We also calculate the inverse mix column tables, - with e,9,d,b being the inverse of 2,1,1,3. + return result; + }; - When we're done, and we need to actually mix columns, the first - byte of each state word should be put through mix[0] (2,1,1,3), - the second through mix[1] (3,2,1,1) and so forth. Then they should - be XOR'd together to produce the fully mixed column. - */ + function getBySubject(subject) { + ensureSubjectHasHash(subject); + return caStore.certs[subject.hash] || null; + } - // calculate mix and imix table values - sx2 = xtime[sx]; - e2 = xtime[e]; - e4 = xtime[e2]; - e8 = xtime[e4]; - me = - (sx2 << 24) ^ // 2 - (sx << 16) ^ // 1 - (sx << 8) ^ // 1 - (sx ^ sx2); // 3 - ime = - (e2 ^ e4 ^ e8) << 24 ^ // E (14) - (e ^ e8) << 16 ^ // 9 - (e ^ e4 ^ e8) << 8 ^ // D (13) - (e ^ e2 ^ e8); // B (11) - // produce each of the mix tables by rotating the 2,1,1,3 value - for(var n = 0; n < 4; ++n) { - mix[n][e] = me; - imix[n][sx] = ime; - // cycle the right most byte to the left most position - // ie: 2,1,1,3 becomes 3,2,1,1 - me = me << 24 | me >>> 8; - ime = ime << 24 | ime >>> 8; + function ensureSubjectHasHash(subject) { + // produce subject hash if it doesn't exist + if(!subject.hash) { + var md = forge.md.sha1.create(); + subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md); + subject.hash = md.digest().toHex(); } + } - // get next element and inverse - if(e === 0) { - // 1 is the inverse of 1 - e = ei = 1; - } else { - // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) - // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) - e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; - ei ^= xtime[xtime[ei]]; + // auto-add passed in certs + if(certs) { + // parse PEM-formatted certificates as necessary + for(var i = 0; i < certs.length; ++i) { + var cert = certs[i]; + caStore.addCertificate(cert); } } -} + + return caStore; +}; /** - * Generates a key schedule using the AES key expansion algorithm. + * Certificate verification errors, based on TLS. + */ +pki.certificateError = { + bad_certificate: 'forge.pki.BadCertificate', + unsupported_certificate: 'forge.pki.UnsupportedCertificate', + certificate_revoked: 'forge.pki.CertificateRevoked', + certificate_expired: 'forge.pki.CertificateExpired', + certificate_unknown: 'forge.pki.CertificateUnknown', + unknown_ca: 'forge.pki.UnknownCertificateAuthority' +}; + +/** + * Verifies a certificate chain against the given Certificate Authority store + * with an optional custom verify callback. * - * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion - * routine to generate a key schedule. The Key Expansion generates a total - * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, - * and each of the Nr rounds requires Nb words of key data. The resulting - * key schedule consists of a linear array of 4-byte words, denoted [wi ], - * with i in the range 0 <= i < Nb(Nr + 1). + * @param caStore a certificate store to verify against. + * @param chain the certificate chain to verify, with the root or highest + * authority at the end (an array of certificates). + * @param options a callback to be called for every certificate in the chain or + * an object with: + * verify a callback to be called for every certificate in the + * chain + * validityCheckDate the date against which the certificate + * validity period should be checked. Pass null to not check + * the validity period. By default, the current date is used. * - * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) - * AES-128 (Nb=4, Nk=4, Nr=10) - * AES-192 (Nb=4, Nk=6, Nr=12) - * AES-256 (Nb=4, Nk=8, Nr=14) - * Note: Nr=Nk+6. + * The verify callback has the following signature: * - * Nb is the number of columns (32-bit words) comprising the State (or - * number of bytes in a block). For AES, Nb=4. + * verified - Set to true if certificate was verified, otherwise the + * pki.certificateError for why the certificate failed. + * depth - The current index in the chain, where 0 is the end point's cert. + * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous + * end point. * - * @param key the key to schedule (as an array of 32-bit words). - * @param decrypt true to modify the key schedule to decrypt, false not to. + * The function returns true on success and on failure either the appropriate + * pki.certificateError or an object with 'error' set to the appropriate + * pki.certificateError and 'message' set to a custom error message. * - * @return the generated key schedule. + * @return true if successful, error thrown if not. */ -function _expandKey(key, decrypt) { - // copy the key's words to initialize the key schedule - var w = key.slice(0); +pki.verifyCertificateChain = function(caStore, chain, options) { + /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate + Section 6: Certification Path Validation + See inline parentheticals related to this particular implementation. - /* RotWord() will rotate a word, moving the first byte to the last - byte's position (shifting the other bytes left). + The primary goal of path validation is to verify the binding between + a subject distinguished name or a subject alternative name and subject + public key, as represented in the end entity certificate, based on the + public key of the trust anchor. This requires obtaining a sequence of + certificates that support that binding. That sequence should be provided + in the passed 'chain'. The trust anchor should be in the given CA + store. The 'end entity' certificate is the certificate provided by the + end point (typically a server) and is the first in the chain. - We will be getting the value of Rcon at i / Nk. 'i' will iterate - from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in - a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from - 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will - increase by 1. We use a counter iNk to keep track of this. - */ + To meet this goal, the path validation process verifies, among other + things, that a prospective certification path (a sequence of n + certificates or a 'chain') satisfies the following conditions: - // go through the rounds expanding the key - var temp, iNk = 1; - var Nk = w.length; - var Nr1 = Nk + 6 + 1; - var end = Nb * Nr1; - for(var i = Nk; i < end; ++i) { - temp = w[i - 1]; - if(i % Nk === 0) { - // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] - temp = - sbox[temp >>> 16 & 255] << 24 ^ - sbox[temp >>> 8 & 255] << 16 ^ - sbox[temp & 255] << 8 ^ - sbox[temp >>> 24] ^ (rcon[iNk] << 24); - iNk++; - } else if(Nk > 6 && (i % Nk === 4)) { - // temp = SubWord(temp) - temp = - sbox[temp >>> 24] << 24 ^ - sbox[temp >>> 16 & 255] << 16 ^ - sbox[temp >>> 8 & 255] << 8 ^ - sbox[temp & 255]; - } - w[i] = w[i - Nk] ^ temp; + (a) for all x in {1, ..., n-1}, the subject of certificate x is + the issuer of certificate x+1; + + (b) certificate 1 is issued by the trust anchor; + + (c) certificate n is the certificate to be validated; and + + (d) for all x in {1, ..., n}, the certificate was valid at the + time in question. + + Note that here 'n' is index 0 in the chain and 1 is the last certificate + in the chain and it must be signed by a certificate in the connection's + CA store. + + The path validation process also determines the set of certificate + policies that are valid for this path, based on the certificate policies + extension, policy mapping extension, policy constraints extension, and + inhibit any-policy extension. + + Note: Policy mapping extension not supported (Not Required). + + Note: If the certificate has an unsupported critical extension, then it + must be rejected. + + Note: A certificate is self-issued if the DNs that appear in the subject + and issuer fields are identical and are not empty. + + The path validation algorithm assumes the following seven inputs are + provided to the path processing logic. What this specific implementation + will use is provided parenthetically: + + (a) a prospective certification path of length n (the 'chain') + (b) the current date/time: ('now'). + (c) user-initial-policy-set: A set of certificate policy identifiers + naming the policies that are acceptable to the certificate user. + The user-initial-policy-set contains the special value any-policy + if the user is not concerned about certificate policy + (Not implemented. Any policy is accepted). + (d) trust anchor information, describing a CA that serves as a trust + anchor for the certification path. The trust anchor information + includes: + + (1) the trusted issuer name, + (2) the trusted public key algorithm, + (3) the trusted public key, and + (4) optionally, the trusted public key parameters associated + with the public key. + + (Trust anchors are provided via certificates in the CA store). + + The trust anchor information may be provided to the path processing + procedure in the form of a self-signed certificate. The trusted anchor + information is trusted because it was delivered to the path processing + procedure by some trustworthy out-of-band procedure. If the trusted + public key algorithm requires parameters, then the parameters are + provided along with the trusted public key (No parameters used in this + implementation). + + (e) initial-policy-mapping-inhibit, which indicates if policy mapping is + allowed in the certification path. + (Not implemented, no policy checking) + + (f) initial-explicit-policy, which indicates if the path must be valid + for at least one of the certificate policies in the user-initial- + policy-set. + (Not implemented, no policy checking) + + (g) initial-any-policy-inhibit, which indicates whether the + anyPolicy OID should be processed if it is included in a + certificate. + (Not implemented, so any policy is valid provided that it is + not marked as critical) */ + + /* Basic Path Processing: + + For each certificate in the 'chain', the following is checked: + + 1. The certificate validity period includes the current time. + 2. The certificate was signed by its parent (where the parent is either + the next in the chain or from the CA store). Allow processing to + continue to the next step if no parent is found but the certificate is + in the CA store. + 3. TODO: The certificate has not been revoked. + 4. The certificate issuer name matches the parent's subject name. + 5. TODO: If the certificate is self-issued and not the final certificate + in the chain, skip this step, otherwise verify that the subject name + is within one of the permitted subtrees of X.500 distinguished names + and that each of the alternative names in the subjectAltName extension + (critical or non-critical) is within one of the permitted subtrees for + that name type. + 6. TODO: If the certificate is self-issued and not the final certificate + in the chain, skip this step, otherwise verify that the subject name + is not within one of the excluded subtrees for X.500 distinguished + names and none of the subjectAltName extension names are excluded for + that name type. + 7. The other steps in the algorithm for basic path processing involve + handling the policy extension which is not presently supported in this + implementation. Instead, if a critical policy extension is found, the + certificate is rejected as not supported. + 8. If the certificate is not the first or if its the only certificate in + the chain (having no parent from the CA store or is self-signed) and it + has a critical key usage extension, verify that the keyCertSign bit is + set. If the key usage extension exists, verify that the basic + constraints extension exists. If the basic constraints extension exists, + verify that the cA flag is set. If pathLenConstraint is set, ensure that + the number of certificates that precede in the chain (come earlier + in the chain as implemented below), excluding the very first in the + chain (typically the end-entity one), isn't greater than the + pathLenConstraint. This constraint limits the number of intermediate + CAs that may appear below a CA before only end-entity certificates + may be issued. */ + + // if a verify callback is passed as the third parameter, package it within + // the options object. This is to support a legacy function signature that + // expected the verify callback as the third parameter. + if(typeof options === 'function') { + options = {verify: options}; } + options = options || {}; - /* When we are updating a cipher block we always use the code path for - encryption whether we are decrypting or not (to shorten code and - simplify the generation of look up tables). However, because there - are differences in the decryption algorithm, other than just swapping - in different look up tables, we must transform our key schedule to - account for these changes: + // copy cert chain references to another array to protect against changes + // in verify callback + chain = chain.slice(0); + var certs = chain.slice(0); - 1. The decryption algorithm gets its key rounds in reverse order. - 2. The decryption algorithm adds the round key before mixing columns - instead of afterwards. + var validityCheckDate = options.validityCheckDate; + // if no validityCheckDate is specified, default to the current date. Make + // sure to maintain the value null because it indicates that the validity + // period should not be checked. + if(typeof validityCheckDate === 'undefined') { + validityCheckDate = new Date(); + } - We don't need to modify our key schedule to handle the first case, - we can just traverse the key schedule in reverse order when decrypting. + // verify each cert in the chain using its parent, where the parent + // is either the next in the chain or from the CA store + var first = true; + var error = null; + var depth = 0; + do { + var cert = chain.shift(); + var parent = null; + var selfSigned = false; - The second case requires a little work. + if(validityCheckDate) { + // 1. check valid time + if(validityCheckDate < cert.validity.notBefore || + validityCheckDate > cert.validity.notAfter) { + error = { + message: 'Certificate is not valid yet or has expired.', + error: pki.certificateError.certificate_expired, + notBefore: cert.validity.notBefore, + notAfter: cert.validity.notAfter, + // TODO: we might want to reconsider renaming 'now' to + // 'validityCheckDate' should this API be changed in the future. + now: validityCheckDate + }; + } + } - The tables we built for performing rounds will take an input and then - perform SubBytes() and MixColumns() or, for the decrypt version, - InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires - us to AddRoundKey() before InvMixColumns(). This means we'll need to - apply some transformations to the round key to inverse-mix its columns - so they'll be correct for moving AddRoundKey() to after the state has - had its columns inverse-mixed. + // 2. verify with parent from chain or CA store + if(error === null) { + parent = chain[0] || caStore.getIssuer(cert); + if(parent === null) { + // check for self-signed cert + if(cert.isIssuer(cert)) { + selfSigned = true; + parent = cert; + } + } - To inverse-mix the columns of the state when we're decrypting we use a - lookup table that will apply InvSubBytes() and InvMixColumns() at the - same time. However, the round key's bytes are not inverse-substituted - in the decryption algorithm. To get around this problem, we can first - substitute the bytes in the round key so that when we apply the - transformation via the InvSubBytes()+InvMixColumns() table, it will - undo our substitution leaving us with the original value that we - want -- and then inverse-mix that value. + if(parent) { + // FIXME: current CA store implementation might have multiple + // certificates where the issuer can't be determined from the + // certificate (happens rarely with, eg: old certificates) so normalize + // by always putting parents into an array + // TODO: there's may be an extreme degenerate case currently uncovered + // where an old intermediate certificate seems to have a matching parent + // but none of the parents actually verify ... but the intermediate + // is in the CA and it should pass this check; needs investigation + var parents = parent; + if(!forge.util.isArray(parents)) { + parents = [parents]; + } - This change will correctly alter our key schedule so that we can XOR - each round key with our already transformed decryption state. This - allows us to use the same code path as the encryption algorithm. + // try to verify with each possible parent (typically only one) + var verified = false; + while(!verified && parents.length > 0) { + parent = parents.shift(); + try { + verified = parent.verify(cert); + } catch(ex) { + // failure to verify, don't care why, try next one + } + } - We make one more change to the decryption key. Since the decryption - algorithm runs in reverse from the encryption algorithm, we reverse - the order of the round keys to avoid having to iterate over the key - schedule backwards when running the encryption algorithm later in - decryption mode. In addition to reversing the order of the round keys, - we also swap each round key's 2nd and 4th rows. See the comments - section where rounds are performed for more details about why this is - done. These changes are done inline with the other substitution - described above. - */ - if(decrypt) { - var tmp; - var m0 = imix[0]; - var m1 = imix[1]; - var m2 = imix[2]; - var m3 = imix[3]; - var wnew = w.slice(0); - end = w.length; - for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { - // do not sub the first or last round key (round keys are Nb - // words) as no column mixing is performed before they are added, - // but do change the key order - if(i === 0 || i === (end - Nb)) { - wnew[i] = w[wi]; - wnew[i + 1] = w[wi + 3]; - wnew[i + 2] = w[wi + 2]; - wnew[i + 3] = w[wi + 1]; - } else { - // substitute each round key byte because the inverse-mix - // table will inverse-substitute it (effectively cancel the - // substitution because round key bytes aren't sub'd in - // decryption mode) and swap indexes 3 and 1 - for(var n = 0; n < Nb; ++n) { - tmp = w[wi + n]; - wnew[i + (3&-n)] = - m0[sbox[tmp >>> 24]] ^ - m1[sbox[tmp >>> 16 & 255]] ^ - m2[sbox[tmp >>> 8 & 255]] ^ - m3[sbox[tmp & 255]]; + if(!verified) { + error = { + message: 'Certificate signature is invalid.', + error: pki.certificateError.bad_certificate + }; } } + + if(error === null && (!parent || selfSigned) && + !caStore.hasCertificate(cert)) { + // no parent issuer and certificate itself is not trusted + error = { + message: 'Certificate is not trusted.', + error: pki.certificateError.unknown_ca + }; + } } - w = wnew; - } - return w; -} + // TODO: 3. check revoked -/** - * Updates a single block (16 bytes) using AES. The update will either - * encrypt or decrypt the block. - * - * @param w the key schedule. - * @param input the input block (an array of 32-bit words). - * @param output the updated output block. - * @param decrypt true to decrypt the block, false to encrypt it. - */ -function _updateBlock(w, input, output, decrypt) { - /* - Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) - begin - byte state[4,Nb] - state = in - AddRoundKey(state, w[0, Nb-1]) - for round = 1 step 1 to Nr-1 - SubBytes(state) - ShiftRows(state) - MixColumns(state) - AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) - end for - SubBytes(state) - ShiftRows(state) - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - out = state - end + // 4. check for matching issuer/subject + if(error === null && parent && !cert.isIssuer(parent)) { + // parent is not issuer + error = { + message: 'Certificate issuer is invalid.', + error: pki.certificateError.bad_certificate + }; + } - InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) - begin - byte state[4,Nb] - state = in - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - for round = Nr-1 step -1 downto 1 - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) - InvMixColumns(state) - end for - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[0, Nb-1]) - out = state - end - */ + // 5. TODO: check names with permitted names tree - // Encrypt: AddRoundKey(state, w[0, Nb-1]) - // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - var Nr = w.length / 4 - 1; - var m0, m1, m2, m3, sub; - if(decrypt) { - m0 = imix[0]; - m1 = imix[1]; - m2 = imix[2]; - m3 = imix[3]; - sub = isbox; - } else { - m0 = mix[0]; - m1 = mix[1]; - m2 = mix[2]; - m3 = mix[3]; - sub = sbox; - } - var a, b, c, d, a2, b2, c2; - a = input[0] ^ w[0]; - b = input[decrypt ? 3 : 1] ^ w[1]; - c = input[2] ^ w[2]; - d = input[decrypt ? 1 : 3] ^ w[3]; - var i = 3; + // 6. TODO: check names against excluded names tree - /* In order to share code we follow the encryption algorithm when both - encrypting and decrypting. To account for the changes required in the - decryption algorithm, we use different lookup tables when decrypting - and use a modified key schedule to account for the difference in the - order of transformations applied when performing rounds. We also get - key rounds in reverse order (relative to encryption). */ - for(var round = 1; round < Nr; ++round) { - /* As described above, we'll be using table lookups to perform the - column mixing. Each column is stored as a word in the state (the - array 'input' has one column as a word at each index). In order to - mix a column, we perform these transformations on each row in c, - which is 1 byte in each word. The new column for c0 is c'0: + // 7. check for unsupported critical extensions + if(error === null) { + // supported extensions + var se = { + keyUsage: true, + basicConstraints: true + }; + for(var i = 0; error === null && i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if(ext.critical && !(ext.name in se)) { + error = { + message: + 'Certificate has an unsupported critical extension.', + error: pki.certificateError.unsupported_certificate + }; + } + } + } - m0 m1 m2 m3 - r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 - r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 - r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 - r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 + // 8. check for CA if cert is not first or is the only certificate + // remaining in chain with no parent or is self-signed + if(error === null && + (!first || (chain.length === 0 && (!parent || selfSigned)))) { + // first check keyUsage extension and then basic constraints + var bcExt = cert.getExtension('basicConstraints'); + var keyUsageExt = cert.getExtension('keyUsage'); + if(keyUsageExt !== null) { + // keyCertSign must be true and there must be a basic + // constraints extension + if(!keyUsageExt.keyCertSign || bcExt === null) { + // bad certificate + error = { + message: + 'Certificate keyUsage or basicConstraints conflict ' + + 'or indicate that the certificate is not a CA. ' + + 'If the certificate is the only one in the chain or ' + + 'isn\'t the first then the certificate must be a ' + + 'valid CA.', + error: pki.certificateError.bad_certificate + }; + } + } + // basic constraints cA flag must be set + if(error === null && bcExt !== null && !bcExt.cA) { + // bad certificate + error = { + message: + 'Certificate basicConstraints indicates the certificate ' + + 'is not a CA.', + error: pki.certificateError.bad_certificate + }; + } + // if error is not null and keyUsage is available, then we know it + // has keyCertSign and there is a basic constraints extension too, + // which means we can check pathLenConstraint (if it exists) + if(error === null && keyUsageExt !== null && + 'pathLenConstraint' in bcExt) { + // pathLen is the maximum # of intermediate CA certs that can be + // found between the current certificate and the end-entity (depth 0) + // certificate; this number does not include the end-entity (depth 0, + // last in the chain) even if it happens to be a CA certificate itself + var pathLen = depth - 1; + if(pathLen > bcExt.pathLenConstraint) { + // pathLenConstraint violated, bad certificate + error = { + message: + 'Certificate basicConstraints pathLenConstraint violated.', + error: pki.certificateError.bad_certificate + }; + } + } + } - So using mix tables where c0 is a word with r0 being its upper - 8 bits and r3 being its lower 8 bits: + // call application callback + var vfd = (error === null) ? true : error.error; + var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; + if(ret === true) { + // clear any set error + error = null; + } else { + // if passed basic tests, set default message and alert + if(vfd === true) { + error = { + message: 'The application rejected the certificate.', + error: pki.certificateError.bad_certificate + }; + } - m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] - ... - m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] + // check for custom error info + if(ret || ret === 0) { + // set custom message and error + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + if(ret.message) { + error.message = ret.message; + } + if(ret.error) { + error.error = ret.error; + } + } else if(typeof ret === 'string') { + // set custom error + error.error = ret; + } + } - Therefore to mix the columns in each word in the state we - do the following (& 255 omitted for brevity): - c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + // throw error + throw error; + } - However, before mixing, the algorithm requires us to perform - ShiftRows(). The ShiftRows() transformation cyclically shifts the - last 3 rows of the state over different offsets. The first row - (r = 0) is not shifted. + // no longer first cert in chain + first = false; + ++depth; + } while(chain.length > 0); - s'_r,c = s_r,(c + shift(r, Nb) mod Nb - for 0 < r < 4 and 0 <= c < Nb and - shift(1, 4) = 1 - shift(2, 4) = 2 - shift(3, 4) = 3. + return true; +}; - This causes the first byte in r = 1 to be moved to the end of - the row, the first 2 bytes in r = 2 to be moved to the end of - the row, the first 3 bytes in r = 3 to be moved to the end of - the row: - r1: [c0 c1 c2 c3] => [c1 c2 c3 c0] - r2: [c0 c1 c2 c3] [c2 c3 c0 c1] - r3: [c0 c1 c2 c3] [c3 c0 c1 c2] +/***/ }), - We can make these substitutions inline with our column mixing to - generate an updated set of equations to produce each word in the - state (note the columns have changed positions): +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - c0 c1 c2 c3 => c0 c1 c2 c3 - c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte) - c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes) - c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes) +var wrappy = __nccwpck_require__(2940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) - Therefore: +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) - c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3 - c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3 - c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3 - c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3 + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) - c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0 - c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0 - c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0 - c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0 +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} - ... and so forth for c'2 and c'3. The important distinction is - that the columns are cycling, with c0 being used with the m0 - map when calculating c0, but c1 being used with the m0 map when - calculating c1 ... and so forth. +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} - When performing the inverse we transform the mirror image and - skip the bottom row, instead of the top one, and move upwards: - c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption - c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes) - c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption - c3 c2 c1 c0 c3 c2 c1 c0 +/***/ }), - If you compare the resulting matrices for ShiftRows()+MixColumns() - and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are - different (in encrypt mode vs. decrypt mode). So in order to use - the same code to handle both encryption and decryption, we will - need to do some mapping. +/***/ 8341: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be - a row number in the state, then the resulting matrix in encryption - mode for applying the above transformations would be: +var once = __nccwpck_require__(1223) +var eos = __nccwpck_require__(1205) +var fs = __nccwpck_require__(7147) // we only need fs to get the ReadStream and WriteStream prototypes - r1: a b c d - r2: b c d a - r3: c d a b - r4: d a b c +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) - If we did the same in decryption mode we would get: +var isFn = function (fn) { + return typeof fn === 'function' +} - r1: a d c b - r2: b a d c - r3: c b a d - r4: d c b a +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) +} - If instead we swap d and b (set b=c3 and d=c1), then we get: +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} - r1: a b c d - r2: d a b c - r3: c d a b - r4: b c d a +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) - Now the 1st and 3rd rows are the same as the encryption matrix. All - we need to do then to make the mapping exactly the same is to swap - the 2nd and 4th rows when in decryption mode. To do this without - having to do it on each iteration, we swapped the 2nd and 4th rows - in the decryption key schedule. We also have to do the swap above - when we first pull in the input and when we set the final output. */ - a2 = - m0[a >>> 24] ^ - m1[b >>> 16 & 255] ^ - m2[c >>> 8 & 255] ^ - m3[d & 255] ^ w[++i]; - b2 = - m0[b >>> 24] ^ - m1[c >>> 16 & 255] ^ - m2[d >>> 8 & 255] ^ - m3[a & 255] ^ w[++i]; - c2 = - m0[c >>> 24] ^ - m1[d >>> 16 & 255] ^ - m2[a >>> 8 & 255] ^ - m3[b & 255] ^ w[++i]; - d = - m0[d >>> 24] ^ - m1[a >>> 16 & 255] ^ - m2[b >>> 8 & 255] ^ - m3[c & 255] ^ w[++i]; - a = a2; - b = b2; - c = c2; + 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')) } +} - /* - Encrypt: - SubBytes(state) - ShiftRows(state) - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) +var call = function (fn) { + fn() +} - Decrypt: - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[0, Nb-1]) - */ - // Note: rows are shifted inline - output[0] = - (sub[a >>> 24] << 24) ^ - (sub[b >>> 16 & 255] << 16) ^ - (sub[c >>> 8 & 255] << 8) ^ - (sub[d & 255]) ^ w[++i]; - output[decrypt ? 3 : 1] = - (sub[b >>> 24] << 24) ^ - (sub[c >>> 16 & 255] << 16) ^ - (sub[d >>> 8 & 255] << 8) ^ - (sub[a & 255]) ^ w[++i]; - output[2] = - (sub[c >>> 24] << 24) ^ - (sub[d >>> 16 & 255] << 16) ^ - (sub[a >>> 8 & 255] << 8) ^ - (sub[b & 255]) ^ w[++i]; - output[decrypt ? 1 : 3] = - (sub[d >>> 24] << 24) ^ - (sub[a >>> 16 & 255] << 16) ^ - (sub[b >>> 8 & 255] << 8) ^ - (sub[c & 255]) ^ w[++i]; +var pipe = function (from, to) { + return from.pipe(to) } -/** - * Deprecated. Instead, use: - * - * forge.cipher.createCipher('AES-', key); - * forge.cipher.createDecipher('AES-', key); - * - * Creates a deprecated AES cipher object. This object's mode will default to - * CBC (cipher-block-chaining). - * - * The key and iv may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. - * - * @param options the options to use. - * key the symmetric key to use. - * output the buffer to write to. - * decrypt true for decryption, false for encryption. - * mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -function _createCipher(options) { - options = options || {}; - var mode = (options.mode || 'CBC').toUpperCase(); - var algorithm = 'AES-' + mode; +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop - var cipher; - if(options.decrypt) { - cipher = forge.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge.cipher.createCipher(algorithm, options.key); - } + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') - // backwards compatible start API - var start = cipher.start; - cipher.start = function(iv, options) { - // backwards compatibility: support second arg as output buffer - var output = null; - if(options instanceof forge.util.ByteBuffer) { - output = options; - options = {}; - } - options = options || {}; - options.output = output; - options.iv = iv; - start.call(cipher, options); - }; + 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 cipher; + return streams.reduce(pipe) } +module.exports = pump + /***/ }), -/***/ 1449: +/***/ 5322: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * A Javascript implementation of AES Cipher Suites for TLS. - * - * @author Dave Longley - * - * Copyright (c) 2009-2015 Digital Bazaar, Inc. - * - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7994); -__nccwpck_require__(9167); +module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function') + ? process.nextTick.bind(process) + : __nccwpck_require__(1031) -var tls = module.exports = forge.tls; -/** - * Supported cipher suites. - */ -tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = { - id: [0x00, 0x2f], - name: 'TLS_RSA_WITH_AES_128_CBC_SHA', - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 16; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState: initConnectionState -}; -tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = { - id: [0x00, 0x35], - name: 'TLS_RSA_WITH_AES_256_CBC_SHA', - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 32; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState: initConnectionState -}; +/***/ }), -function initConnectionState(state, c, sp) { - var client = (c.entity === forge.tls.ConnectionEnd.client); +/***/ 1031: +/***/ ((module) => { - // cipher setup - state.read.cipherState = { - init: false, - cipher: forge.cipher.createDecipher('AES-CBC', client ? - sp.keys.server_write_key : sp.keys.client_write_key), - iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV - }; - state.write.cipherState = { - init: false, - cipher: forge.cipher.createCipher('AES-CBC', client ? - sp.keys.client_write_key : sp.keys.server_write_key), - iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV - }; - state.read.cipherFunction = decrypt_aes_cbc_sha1; - state.write.cipherFunction = encrypt_aes_cbc_sha1; +module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn) - // MAC setup - state.read.macLength = state.write.macLength = sp.mac_length; - state.read.macFunction = state.write.macFunction = tls.hmac_sha1; -} -/** - * Encrypts the TLSCompressed record into a TLSCipherText record using AES - * in CBC mode. - * - * @param record the TLSCompressed record to encrypt. - * @param s the ConnectionState to use. - * - * @return true on success, false on failure. - */ -function encrypt_aes_cbc_sha1(record, s) { - var rval = false; +/***/ }), - // append MAC to fragment, update sequence number - var mac = s.macFunction(s.macKey, s.sequenceNumber, record); - record.fragment.putBytes(mac); - s.updateSequenceNumber(); +/***/ 7214: +/***/ ((module) => { - // TLS 1.1+ use an explicit IV every time to protect against CBC attacks - var iv; - if(record.version.minor === tls.Versions.TLS_1_0.minor) { - // use the pre-generated IV when initializing for TLS 1.0, otherwise use - // the residue from the previous encryption - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = forge.random.getBytesSync(16); - } +"use strict"; - s.cipherState.init = true; - // start cipher - var cipher = s.cipherState.cipher; - cipher.start({iv: iv}); +const codes = {}; - // TLS 1.1+ write IV into output - if(record.version.minor >= tls.Versions.TLS_1_1.minor) { - cipher.output.putBytes(iv); +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error } - // do encryption (default padding is appropriate) - cipher.update(record.fragment); - if(cipher.finish(encrypt_aes_cbc_sha1_padding)) { - // set record fragment to encrypted output - record.fragment = cipher.output; - record.length = record.fragment.length(); - rval = true; + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } } - return rval; + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; } -/** - * Handles padding for aes_cbc_sha1 in encrypt mode. - * - * @param blockSize the block size. - * @param input the input buffer. - * @param decrypt true in decrypt mode, false in encrypt mode. - * - * @return true on success, false on failure. - */ -function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { - /* The encrypted data length (TLSCiphertext.length) is one more than the sum - of SecurityParameters.block_length, TLSCompressed.length, - SecurityParameters.mac_length, and padding_length. +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} - The padding may be any length up to 255 bytes long, as long as it results in - the TLSCiphertext.length being an integral multiple of the block length. - Lengths longer than necessary might be desirable to frustrate attacks on a - protocol based on analysis of the lengths of exchanged messages. Each uint8 - in the padding data vector must be filled with the padding length value. +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} - The padding length should be such that the total size of the - GenericBlockCipher structure is a multiple of the cipher's block length. - Legal values range from zero to 255, inclusive. This length specifies the - length of the padding field exclusive of the padding_length field itself. +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} - This is slightly different from PKCS#7 because the padding value is 1 - less than the actual number of padding bytes if you include the - padding_length uint8 itself as a padding byte. */ - if(!decrypt) { - // get the number of padding bytes required to reach the blockSize and - // subtract 1 for the padding value (to make room for the padding_length - // uint8) - var padding = blockSize - (input.length() % blockSize); - input.fillWithByte(padding - 1, padding); +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; } - return true; -} -/** - * Handles padding for aes_cbc_sha1 in decrypt mode. - * - * @param blockSize the block size. - * @param output the output buffer. - * @param decrypt true in decrypt mode, false in encrypt mode. - * - * @return true on success, false on failure. - */ -function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { - var rval = true; - if(decrypt) { - /* The last byte in the output specifies the number of padding bytes not - including itself. Each of the padding bytes has the same value as that - last byte (known as the padding_length). Here we check all padding - bytes to ensure they have the value of padding_length even if one of - them is bad in order to ward-off timing attacks. */ - var len = output.length(); - var paddingLength = output.last(); - for(var i = len - 1 - paddingLength; i < len - 1; ++i) { - rval = rval && (output.at(i) == paddingLength); - } - if(rval) { - // trim off padding bytes and last padding length byte - output.truncate(paddingLength + 1); - } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; } - return rval; } -/** - * Decrypts a TLSCipherText record into a TLSCompressed record using - * AES in CBC mode. - * - * @param record the TLSCipherText record to decrypt. - * @param s the ConnectionState to use. - * - * @return true on success, false on failure. - */ -function decrypt_aes_cbc_sha1(record, s) { - var rval = false; +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } - var iv; - if(record.version.minor === tls.Versions.TLS_1_0.minor) { - // use pre-generated IV when initializing for TLS 1.0, otherwise use the - // residue from the previous decryption - iv = s.cipherState.init ? null : s.cipherState.iv; + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { - // TLS 1.1+ use an explicit IV every time to protect against CBC attacks - // that is appended to the record fragment - iv = record.fragment.getBytes(16); + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } - s.cipherState.init = true; + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - // start cipher - var cipher = s.cipherState.cipher; - cipher.start({iv: iv}); +module.exports.q = codes; - // do decryption - cipher.update(record.fragment); - rval = cipher.finish(decrypt_aes_cbc_sha1_padding); - // even if decryption fails, keep going to minimize timing attacks +/***/ }), - // decrypted data: - // first (len - 20) bytes = application data - // last 20 bytes = MAC - var macLen = s.macLength; +/***/ 1359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // create a random MAC to check against should the mac length check fail - // Note: do this regardless of the failure to keep timing consistent - var mac = forge.random.getBytesSync(macLen); +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. - // get fragment and mac - var len = cipher.output.length(); - if(len >= macLen) { - record.fragment = cipher.output.getBytes(len - macLen); - mac = cipher.output.getBytes(macLen); - } else { - // bad data, but get bytes anyway to try to keep timing consistent - record.fragment = cipher.output.getBytes(); +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); } - record.fragment = forge.util.createBuffer(record.fragment); - record.length = record.fragment.length(); - // see if data integrity checks out, update sequence number - var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); - s.updateSequenceNumber(); - rval = compareMacs(s.macKey, mac, mac2) && rval; - return rval; -} + return keys; +}; +/**/ -/** - * Safely compare two MACs. This function will compare two MACs in a way - * that protects against timing attacks. - * - * TODO: Expose elsewhere as a utility API. - * - * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/ - * - * @param key the MAC key to use. - * @param mac1 as a binary-encoded string of bytes. - * @param mac2 as a binary-encoded string of bytes. - * - * @return true if the MACs are the same, false if not. - */ -function compareMacs(key, mac1, mac2) { - var hmac = forge.hmac.create(); - hmac.start('SHA1', key); - hmac.update(mac1); - mac1 = hmac.digest().getBytes(); +module.exports = Duplex; + +var Readable = __nccwpck_require__(1433); + +var Writable = __nccwpck_require__(6993); + +__nccwpck_require__(4124)(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; - hmac.start(null, null); - hmac.update(mac2); - mac2 = hmac.digest().getBytes(); + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; - return mac1 === mac2; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } } +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer -/***/ }), - -/***/ 9414: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. -/** - * Copyright (c) 2019 Digital Bazaar, Inc. - */ + process.nextTick(onEndNT, this); +} -var forge = __nccwpck_require__(9177); -__nccwpck_require__(9549); -var asn1 = forge.asn1; +function onEndNT(self) { + self.end(); +} -exports.privateKeyValidator = { - // PrivateKeyInfo - name: 'PrivateKeyInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: 'PrivateKeyInfo.version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyVersion' - }, { - // privateKeyAlgorithm - name: 'PrivateKeyInfo.privateKeyAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'privateKeyOid' - }] - }, { - // PrivateKey - name: 'PrivateKeyInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'privateKey' - }] -}; +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } -exports.publicKeyValidator = { - name: 'SubjectPublicKeyInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'subjectPublicKeyInfo', - value: [{ - name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'publicKeyOid' - }] + return this._readableState.destroyed && this._writableState.destroyed; }, - // capture group for ed25519PublicKey - { - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - composed: true, - captureBitStringValue: 'ed25519PublicKey' - } - // FIXME: this is capture group for rsaPublicKey, use it in this API or - // discard? - /* { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - } */ - ] -}; + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + /***/ }), -/***/ 9549: +/***/ 1542: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Javascript implementation of Abstract Syntax Notation Number One. - * - * @author Dave Longley - * - * Copyright (c) 2010-2015 Digital Bazaar, Inc. - * - * An API for storing data using the Abstract Syntax Notation Number One - * format using DER (Distinguished Encoding Rules) encoding. This encoding is - * commonly used to store data for PKI, i.e. X.509 Certificates, and this - * implementation exists for that purpose. - * - * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract - * syntax of information without restricting the way the information is encoded - * for transmission. It provides a standard that allows for open systems - * communication. ASN.1 defines the syntax of information data and a number of - * simple data types as well as a notation for describing them and specifying - * values for them. - * - * The RSA algorithm creates public and private keys that are often stored in - * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This - * class provides the most basic functionality required to store and load DSA - * keys that are encoded according to ASN.1. - * - * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules) - * and DER (Distinguished Encoding Rules). DER is just a subset of BER that - * has stricter requirements for how data must be encoded. - * - * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type) - * and a byte array for the value of this ASN1 structure which may be data or a - * list of ASN.1 structures. - * - * Each ASN.1 structure using BER is (Tag-Length-Value): - * - * | byte 0 | bytes X | bytes Y | - * |--------|---------|---------- - * | tag | length | value | - * - * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to - * be two or more octets, but that is not supported by this class. A tag is - * only 1 byte. Bits 1-5 give the tag number (ie the data type within a - * particular 'class'), 6 indicates whether or not the ASN.1 value is - * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If - * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set, - * then the class is APPLICATION. If only bit 8 is set, then the class is - * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE. - * The tag numbers for the data types for the class UNIVERSAL are listed below: - * - * UNIVERSAL 0 Reserved for use by the encoding rules - * UNIVERSAL 1 Boolean type - * UNIVERSAL 2 Integer type - * UNIVERSAL 3 Bitstring type - * UNIVERSAL 4 Octetstring type - * UNIVERSAL 5 Null type - * UNIVERSAL 6 Object identifier type - * UNIVERSAL 7 Object descriptor type - * UNIVERSAL 8 External type and Instance-of type - * UNIVERSAL 9 Real type - * UNIVERSAL 10 Enumerated type - * UNIVERSAL 11 Embedded-pdv type - * UNIVERSAL 12 UTF8String type - * UNIVERSAL 13 Relative object identifier type - * UNIVERSAL 14-15 Reserved for future editions - * UNIVERSAL 16 Sequence and Sequence-of types - * UNIVERSAL 17 Set and Set-of types - * UNIVERSAL 18-22, 25-30 Character string types - * UNIVERSAL 23-24 Time types - * - * The length of an ASN.1 structure is specified after the tag identifier. - * There is a definite form and an indefinite form. The indefinite form may - * be used if the encoding is constructed and not all immediately available. - * The indefinite form is encoded using a length byte with only the 8th bit - * set. The end of the constructed object is marked using end-of-contents - * octets (two zero bytes). - * - * The definite form looks like this: - * - * The length may take up 1 or more bytes, it depends on the length of the - * value of the ASN.1 structure. DER encoding requires that if the ASN.1 - * structure has a value that has a length greater than 127, more than 1 byte - * will be used to store its length, otherwise just one byte will be used. - * This is strict. - * - * In the case that the length of the ASN.1 value is less than 127, 1 octet - * (byte) is used to store the "short form" length. The 8th bit has a value of - * 0 indicating the length is "short form" and not "long form" and bits 7-1 - * give the length of the data. (The 8th bit is the left-most, most significant - * bit: also known as big endian or network format). - * - * In the case that the length of the ASN.1 value is greater than 127, 2 to - * 127 octets (bytes) are used to store the "long form" length. The first - * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1 - * give the number of additional octets. All following octets are in base 256 - * with the most significant digit first (typical big-endian binary unsigned - * integer storage). So, for instance, if the length of a value was 257, the - * first byte would be set to: - * - * 10000010 = 130 = 0x82. - * - * This indicates there are 2 octets (base 256) for the length. The second and - * third bytes (the octets just mentioned) would store the length in base 256: - * - * octet 2: 00000001 = 1 * 256^1 = 256 - * octet 3: 00000001 = 1 * 256^0 = 1 - * total = 257 - * - * The algorithm for converting a js integer value of 257 to base-256 is: - * - * var value = 257; - * var bytes = []; - * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first - * bytes[1] = value & 0xFF; // least significant byte last - * - * On the ASN.1 UNIVERSAL Object Identifier (OID) type: - * - * An OID can be written like: "value1.value2.value3...valueN" - * - * The DER encoding rules: - * - * The first byte has the value 40 * value1 + value2. - * The following bytes, if any, encode the remaining values. Each value is - * encoded in base 128, most significant digit first (big endian), with as - * few digits as possible, and the most significant bit of each byte set - * to 1 except the last in each value's encoding. For example: Given the - * OID "1.2.840.113549", its DER encoding is (remember each byte except the - * last one in each encoding is OR'd with 0x80): - * - * byte 1: 40 * 1 + 2 = 42 = 0x2A. - * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648 - * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D - * - * The final value is: 0x2A864886F70D. - * The full OID (including ASN.1 tag and length of 6 bytes) is: - * 0x06062A864886F70D - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); -__nccwpck_require__(1925); +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. -/* ASN.1 API */ -var asn1 = module.exports = forge.asn1 = forge.asn1 || {}; -/** - * ASN.1 classes. - */ -asn1.Class = { - UNIVERSAL: 0x00, - APPLICATION: 0x40, - CONTEXT_SPECIFIC: 0x80, - PRIVATE: 0xC0 -}; +module.exports = PassThrough; -/** - * ASN.1 types. Not all types are supported by this implementation, only - * those necessary to implement a simple PKI are implemented. - */ -asn1.Type = { - NONE: 0, - BOOLEAN: 1, - INTEGER: 2, - BITSTRING: 3, - OCTETSTRING: 4, - NULL: 5, - OID: 6, - ODESC: 7, - EXTERNAL: 8, - REAL: 9, - ENUMERATED: 10, - EMBEDDED: 11, - UTF8: 12, - ROID: 13, - SEQUENCE: 16, - SET: 17, - PRINTABLESTRING: 19, - IA5STRING: 22, - UTCTIME: 23, - GENERALIZEDTIME: 24, - BMPSTRING: 30 -}; +var Transform = __nccwpck_require__(4415); -/** - * Creates a new asn1 object. - * - * @param tagClass the tag class for the object. - * @param type the data type (tag number) for the object. - * @param constructed true if the asn1 object is in constructed form. - * @param value the value for the object, if it is not constructed. - * @param [options] the options to use: - * [bitStringContents] the plain BIT STRING content including padding - * byte. - * - * @return the asn1 object. - */ -asn1.create = function(tagClass, type, constructed, value, options) { - /* An asn1 object has a tagClass, a type, a constructed flag, and a - value. The value's type depends on the constructed flag. If - constructed, it will contain a list of other asn1 objects. If not, - it will contain the ASN.1 value as an array of bytes formatted - according to the ASN.1 data type. */ +__nccwpck_require__(4124)(PassThrough, Transform); - // remove undefined values - if(forge.util.isArray(value)) { - var tmp = []; - for(var i = 0; i < value.length; ++i) { - if(value[i] !== undefined) { - tmp.push(value[i]); - } - } - value = tmp; - } +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} - var obj = { - tagClass: tagClass, - type: type, - constructed: constructed, - composed: constructed || forge.util.isArray(value), - value: value - }; - if(options && 'bitStringContents' in options) { - // TODO: copy byte buffer if it's a buffer not a string - obj.bitStringContents = options.bitStringContents; - // TODO: add readonly flag to avoid this overhead - // save copy to detect changes - obj.original = asn1.copy(obj); - } - return obj; +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); }; -/** - * Copies an asn1 object. - * - * @param obj the asn1 object. - * @param [options] copy options: - * [excludeBitStringContents] true to not copy bitStringContents - * - * @return the a copy of the asn1 object. - */ -asn1.copy = function(obj, options) { - var copy; - - if(forge.util.isArray(obj)) { - copy = []; - for(var i = 0; i < obj.length; ++i) { - copy.push(asn1.copy(obj[i], options)); - } - return copy; - } - - if(typeof obj === 'string') { - // TODO: copy byte buffer if it's a buffer not a string - return obj; - } +/***/ }), - copy = { - tagClass: obj.tagClass, - type: obj.type, - constructed: obj.constructed, - composed: obj.composed, - value: asn1.copy(obj.value, options) - }; - if(options && !options.excludeBitStringContents) { - // TODO: copy byte buffer if it's a buffer not a string - copy.bitStringContents = obj.bitStringContents; - } - return copy; -}; +/***/ 1433: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Compares asn1 objects for equality. - * - * Note this function does not run in constant time. - * - * @param obj1 the first asn1 object. - * @param obj2 the second asn1 object. - * @param [options] compare options: - * [includeBitStringContents] true to compare bitStringContents - * - * @return true if the asn1 objects are equal. - */ -asn1.equals = function(obj1, obj2, options) { - if(forge.util.isArray(obj1)) { - if(!forge.util.isArray(obj2)) { - return false; - } - if(obj1.length !== obj2.length) { - return false; - } - for(var i = 0; i < obj1.length; ++i) { - if(!asn1.equals(obj1[i], obj2[i])) { - return false; - } - } - return true; - } +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. - if(typeof obj1 !== typeof obj2) { - return false; - } - if(typeof obj1 === 'string') { - return obj1 === obj2; - } +module.exports = Readable; +/**/ - var equal = obj1.tagClass === obj2.tagClass && - obj1.type === obj2.type && - obj1.constructed === obj2.constructed && - obj1.composed === obj2.composed && - asn1.equals(obj1.value, obj2.value); - if(options && options.includeBitStringContents) { - equal = equal && (obj1.bitStringContents === obj2.bitStringContents); - } +var Duplex; +/**/ - return equal; -}; +Readable.ReadableState = ReadableState; +/**/ -/** - * Gets the length of a BER-encoded ASN.1 value. - * - * In case the length is not specified, undefined is returned. - * - * @param b the BER-encoded ASN.1 byte buffer, starting with the first - * length byte. - * - * @return the length of the BER-encoded ASN.1 value or undefined. - */ -asn1.getBerValueLength = function(b) { - // TODO: move this function and related DER/BER functions to a der.js - // file; better abstract ASN.1 away from der/ber. - var b2 = b.getByte(); - if(b2 === 0x80) { - return undefined; - } +var EE = (__nccwpck_require__(2361).EventEmitter); - // see if the length is "short form" or "long form" (bit 8 set) - var length; - var longForm = b2 & 0x80; - if(!longForm) { - // length is just the first byte - length = b2; - } else { - // the number of bytes the length is specified in bits 7 through 1 - // and each length byte is in big-endian base-256 - length = b.getInt((b2 & 0x7F) << 3); - } - return length; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; }; +/**/ -/** - * Check if the byte buffer has enough bytes. Throws an Error if not. - * - * @param bytes the byte buffer to parse from. - * @param remaining the bytes remaining in the current parsing state. - * @param n the number of bytes the buffer must have. - */ -function _checkBufferLength(bytes, remaining, n) { - if(n > remaining) { - var error = new Error('Too few bytes to parse DER.'); - error.available = bytes.length(); - error.remaining = remaining; - error.requested = n; - throw error; - } +/**/ + + +var Stream = __nccwpck_require__(2387); +/**/ + + +var Buffer = (__nccwpck_require__(4300).Buffer); + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); } -/** - * Gets the length of a BER-encoded ASN.1 value. - * - * In case the length is not specified, undefined is returned. - * - * @param bytes the byte buffer to parse from. - * @param remaining the bytes remaining in the current parsing state. - * - * @return the length of the BER-encoded ASN.1 value or undefined. - */ -var _getValueLength = function(bytes, remaining) { - // TODO: move this function and related DER/BER functions to a der.js - // file; better abstract ASN.1 away from der/ber. - // fromDer already checked that this byte exists - var b2 = bytes.getByte(); - remaining--; - if(b2 === 0x80) { - return undefined; - } +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ - // see if the length is "short form" or "long form" (bit 8 set) - var length; - var longForm = b2 & 0x80; - if(!longForm) { - // length is just the first byte - length = b2; - } else { - // the number of bytes the length is specified in bits 7 through 1 - // and each length byte is in big-endian base-256 - var longFormBytes = b2 & 0x7F; - _checkBufferLength(bytes, remaining, longFormBytes); - length = bytes.getInt(longFormBytes << 3); - } - // FIXME: this will only happen for 32 bit getInt with high bit set - if(length < 0) { - throw new Error('Negative length: ' + length); - } - return length; -}; -/** - * Parses an asn1 object from a byte buffer in DER format. - * - * @param bytes the byte buffer to parse from. - * @param [strict] true to be strict when checking value lengths, false to - * allow truncated values (default: true). - * @param [options] object with options or boolean strict flag - * [strict] true to be strict when checking value lengths, false to - * allow truncated values (default: true). - * [parseAllBytes] true to ensure all bytes are parsed - * (default: true) - * [decodeBitStrings] true to attempt to decode the content of - * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that - * without schema support to understand the data context this can - * erroneously decode values that happen to be valid ASN.1. This - * flag will be deprecated or removed as soon as schema support is - * available. (default: true) - * - * @throws Will throw an error for various malformed input conditions. - * - * @return the parsed asn1 object. - */ -asn1.fromDer = function(bytes, options) { - if(options === undefined) { - options = { - strict: true, - parseAllBytes: true, - decodeBitStrings: true - }; - } - if(typeof options === 'boolean') { - options = { - strict: options, - parseAllBytes: true, - decodeBitStrings: true - }; - } - if(!('strict' in options)) { - options.strict = true; - } - if(!('parseAllBytes' in options)) { - options.parseAllBytes = true; - } - if(!('decodeBitStrings' in options)) { - options.decodeBitStrings = true; - } +var debugUtil = __nccwpck_require__(3837); - // wrap in buffer if needed - if(typeof bytes === 'string') { - bytes = forge.util.createBuffer(bytes); - } +var debug; - var byteCount = bytes.length(); - var value = _fromDer(bytes, bytes.length(), 0, options); - if(options.parseAllBytes && bytes.length() !== 0) { - var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.'); - error.byteCount = byteCount; - error.remaining = bytes.length(); - throw error; - } - return value; -}; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ -/** - * Internal function to parse an asn1 object from a byte buffer in DER format. - * - * @param bytes the byte buffer to parse from. - * @param remaining the number of bytes remaining for this chunk. - * @param depth the current parsing depth. - * @param options object with same options as fromDer(). - * - * @return the parsed asn1 object. - */ -function _fromDer(bytes, remaining, depth, options) { - // temporary storage for consumption calculations - var start; - // minimum length for ASN.1 DER structure is 2 - _checkBufferLength(bytes, remaining, 2); +var BufferList = __nccwpck_require__(6522); - // get the first byte - var b1 = bytes.getByte(); - // consumed one byte - remaining--; +var destroyImpl = __nccwpck_require__(7049); - // get the tag class - var tagClass = (b1 & 0xC0); +var _require = __nccwpck_require__(9948), + getHighWaterMark = _require.getHighWaterMark; - // get the type (bits 1-5) - var type = b1 & 0x1F; +var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - // get the variable value length and adjust remaining bytes - start = bytes.length(); - var length = _getValueLength(bytes, remaining); - remaining -= start - bytes.length(); - // ensure there are enough bytes to get the value - if(length !== undefined && length > remaining) { - if(options.strict) { - var error = new Error('Too few bytes to read ASN.1 value.'); - error.available = bytes.length(); - error.remaining = remaining; - error.requested = length; - throw error; - } - // Note: be lenient with truncated values and use remaining state bytes - length = remaining; - } +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; - // value storage - var value; - // possible BIT STRING contents storage - var bitStringContents; +__nccwpck_require__(4124)(Readable, Stream); - // constructed flag is bit 6 (32 = 0x20) of the first byte - var constructed = ((b1 & 0x20) === 0x20); - if(constructed) { - // parse child asn1 objects from the value - value = []; - if(length === undefined) { - // asn1 object of indefinite length, read until end tag - for(;;) { - _checkBufferLength(bytes, remaining, 2); - if(bytes.bytes(2) === String.fromCharCode(0, 0)) { - bytes.getBytes(2); - remaining -= 2; - break; - } - start = bytes.length(); - value.push(_fromDer(bytes, remaining, depth + 1, options)); - remaining -= start - bytes.length(); - } - } else { - // parsing asn1 object of definite length - while(length > 0) { - start = bytes.length(); - value.push(_fromDer(bytes, length, depth + 1, options)); - remaining -= start - bytes.length(); - length -= start - bytes.length(); - } - } - } +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - // if a BIT STRING, save the contents including padding - if(value === undefined && tagClass === asn1.Class.UNIVERSAL && - type === asn1.Type.BITSTRING) { - bitStringContents = bytes.bytes(length); - } +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. - // determine if a non-constructed value should be decoded as a composed - // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs) - // can be used this way. - if(value === undefined && options.decodeBitStrings && - tagClass === asn1.Class.UNIVERSAL && - // FIXME: OCTET STRINGs not yet supported here - // .. other parts of forge expect to decode OCTET STRINGs manually - (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) && - length > 1) { - // save read position - var savedRead = bytes.read; - var savedRemaining = remaining; - var unused = 0; - if(type === asn1.Type.BITSTRING) { - /* The first octet gives the number of bits by which the length of the - bit string is less than the next multiple of eight (this is called - the "number of unused bits"). + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} - The second and following octets give the value of the bit string - converted to an octet string. */ - _checkBufferLength(bytes, remaining, 1); - unused = bytes.getByte(); - remaining--; - } - // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs - if(unused === 0) { - try { - // attempt to parse child asn1 object from the value - // (stored in array to signal composed value) - start = bytes.length(); - var subOptions = { - // enforce strict mode to avoid parsing ASN.1 from plain data - strict: true, - decodeBitStrings: true - }; - var composed = _fromDer(bytes, remaining, depth + 1, subOptions); - var used = start - bytes.length(); - remaining -= used; - if(type == asn1.Type.BITSTRING) { - used++; - } +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(1359); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. - // if the data all decoded and the class indicates UNIVERSAL or - // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object - var tc = composed.tagClass; - if(used === length && - (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { - value = [composed]; - } - } catch(ex) { - } - } - if(value === undefined) { - // restore read position - bytes.read = savedRead; - remaining = savedRemaining; - } - } + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away - if(value === undefined) { - // asn1 not constructed or composed, get raw value - // TODO: do DER to OID conversion and vice-versa in .toDer? + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" - if(length === undefined) { - if(options.strict) { - throw new Error('Non-constructed ASN.1 object of indefinite length.'); - } - // be lenient and use remaining state bytes - length = remaining; - } + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() - if(type === asn1.Type.BMPSTRING) { - value = ''; - for(; length > 0; length -= 2) { - _checkBufferLength(bytes, remaining, 2); - value += String.fromCharCode(bytes.getInt16()); - remaining -= 2; - } - } else { - value = bytes.getBytes(length); - remaining -= length; - } - } + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. - // add BIT STRING contents if available - var asn1Options = bitStringContents === undefined ? null : { - bitStringContents: bitStringContents - }; + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - // create and return asn1 object - return asn1.create(tagClass, type, constructed, value, asn1Options); + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } } -/** - * Converts the given asn1 object to a buffer of bytes in DER format. - * - * @param asn1 the asn1 object to convert to bytes. - * - * @return the buffer of bytes. - */ -asn1.toDer = function(obj) { - var bytes = forge.util.createBuffer(); +function Readable(options) { + Duplex = Duplex || __nccwpck_require__(1359); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 - // build the first byte - var b1 = obj.tagClass | obj.type; + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy - // for storing the ASN.1 value - var value = forge.util.createBuffer(); + this.readable = true; - // use BIT STRING contents if available and data not changed - var useBitStringContents = false; - if('bitStringContents' in obj) { - useBitStringContents = true; - if(obj.original) { - useBitStringContents = asn1.equals(obj, obj.original); - } + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; } - if(useBitStringContents) { - value.putBytes(obj.bitStringContents); - } else if(obj.composed) { - // if composed, use each child asn1 object's DER bytes as value - // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed - // from other asn1 objects - if(obj.constructed) { - b1 |= 0x20; - } else { - // type is a bit string, add unused bits of 0x00 - value.putByte(0x00); - } + Stream.call(this); +} - // add all of the child DER bytes together - for(var i = 0; i < obj.value.length; ++i) { - if(obj.value[i] !== undefined) { - value.putBuffer(asn1.toDer(obj.value[i])); - } - } - } else { - // use asn1.value directly - if(obj.type === asn1.Type.BMPSTRING) { - for(var i = 0; i < obj.value.length; ++i) { - value.putInt16(obj.value.charCodeAt(i)); - } - } else { - // ensure integer is minimally-encoded - // TODO: should all leading bytes be stripped vs just one? - // .. ex '00 00 01' => '01'? - if(obj.type === asn1.Type.INTEGER && - obj.value.length > 1 && - // leading 0x00 for positive integer - ((obj.value.charCodeAt(0) === 0 && - (obj.value.charCodeAt(1) & 0x80) === 0) || - // leading 0xFF for negative integer - (obj.value.charCodeAt(0) === 0xFF && - (obj.value.charCodeAt(1) & 0x80) === 0x80))) { - value.putBytes(obj.value.substr(1)); - } else { - value.putBytes(obj.value); - } +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; } - } - - // add tag byte - bytes.putByte(b1); - // use "short form" encoding - if(value.length() <= 127) { - // one byte describes the length - // bit 8 = 0 and bits 7-1 = length - bytes.putByte(value.length() & 0x7F); - } else { - // use "long form" encoding - // 2 to 127 bytes describe the length - // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes - // other bytes: length in base 256, big-endian - var len = value.length(); - var lenBytes = ''; - do { - lenBytes += String.fromCharCode(len & 0xFF); - len = len >>> 8; - } while(len > 0); + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - // set first byte to # bytes used to store the length and turn on - // bit 8 to indicate long-form length is used - bytes.putByte(lenBytes.length | 0x80); - // concatenate length bytes in reverse since they were generated - // little endian and we need big endian - for(var i = lenBytes.length - 1; i >= 0; --i) { - bytes.putByte(lenBytes.charCodeAt(i)); - } + this._readableState.destroyed = value; } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; - // concatenate value bytes - bytes.putBuffer(value); - return bytes; -}; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. -/** - * Converts an OID dot-separated string to a byte buffer. The byte buffer - * contains only the DER-encoded value, not any tag or length bytes. - * - * @param oid the OID dot-separated string. - * - * @return the byte buffer. - */ -asn1.oidToDer = function(oid) { - // split OID into individual values - var values = oid.split('.'); - var bytes = forge.util.createBuffer(); - // first byte is 40 * value1 + value2 - bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); - // other bytes are each value in base 128 with 8th bit set except for - // the last byte for each value - var last, valueBytes, value, b; - for(var i = 2; i < values.length; ++i) { - // produce value bytes in reverse because we don't know how many - // bytes it will take to store the value - last = true; - valueBytes = []; - value = parseInt(values[i], 10); - do { - b = value & 0x7F; - value = value >>> 7; - // if value is not last, then turn on 8th bit - if(!last) { - b |= 0x80; +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; } - valueBytes.push(b); - last = false; - } while(value > 0); - // add value bytes in reverse (needs to be in big endian) - for(var n = valueBytes.length - 1; n >= 0; --n) { - bytes.putByte(valueBytes[n]); + skipChunkCheck = true; } + } else { + skipChunkCheck = true; } - return bytes; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() + + +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); }; -/** - * Converts a DER-encoded byte buffer to an OID dot-separated string. The - * byte buffer should contain only the DER-encoded value, not any tag or - * length bytes. - * - * @param bytes the byte buffer. - * - * @return the OID dot-separated string. - */ -asn1.derToOid = function(bytes) { - var oid; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; - // wrap in buffer if needed - if(typeof bytes === 'string') { - bytes = forge.util.createBuffer(bytes); - } + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); - // first byte is 40 * value1 + value2 - var b = bytes.getByte(); - oid = Math.floor(b / 40) + '.' + (b % 40); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } - // other bytes are each value in base 128 with 8th bit set except for - // the last byte for each value - var value = 0; - while(bytes.length() > 0) { - b = bytes.getByte(); - value = value << 7; - // not the last byte for the value - if(b & 0x80) { - value += b & 0x7F; - } else { - // last byte - oid += '.' + (value + b); - value = 0; + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); } - } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. - return oid; -}; -/** - * Converts a UTCTime value to a date. - * - * Note: GeneralizedTime has 4 digits for the year and is used for X.509 - * dates past 2049. Parsing that structure hasn't been implemented yet. - * - * @param utc the UTCTime value to convert. - * - * @return the date. - */ -asn1.utcTimeToDate = function(utc) { - /* The following formats can be used: + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} - YYMMDDhhmmZ - YYMMDDhhmm+hh'mm' - YYMMDDhhmm-hh'mm' - YYMMDDhhmmssZ - YYMMDDhhmmss+hh'mm' - YYMMDDhhmmss-hh'mm' +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } - Where: + maybeReadMore(stream, state); +} - YY is the least significant two digits of the year - MM is the month (01 to 12) - DD is the day (01 to 31) - hh is the hour (00 to 23) - mm are the minutes (00 to 59) - ss are the seconds (00 to 59) - Z indicates that local time is GMT, + indicates that local time is - later than GMT, and - indicates that local time is earlier than GMT - hh' is the absolute value of the offset from GMT in hours - mm' is the absolute value of the offset from GMT in minutes */ - var date = new Date(); +function chunkInvalid(state, chunk) { + var er; - // if YY >= 50 use 19xx, if YY < 50 use 20xx - var year = parseInt(utc.substr(0, 2), 10); - year = (year >= 50) ? 1900 + year : 2000 + year; - var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month - var DD = parseInt(utc.substr(4, 2), 10); - var hh = parseInt(utc.substr(6, 2), 10); - var mm = parseInt(utc.substr(8, 2), 10); - var ss = 0; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } - // not just YYMMDDhhmmZ - if(utc.length > 11) { - // get character after minutes - var c = utc.charAt(10); - var end = 10; + return er; +} - // see if seconds are present - if(c !== '+' && c !== '-') { - // get seconds - ss = parseInt(utc.substr(10, 2), 10); - end += 2; - } - } +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. - // update date - date.setUTCFullYear(year, MM, DD); - date.setUTCHours(hh, mm, ss, 0); - if(end) { - // get +/- after end of time - c = utc.charAt(end); - if(c === '+' || c === '-') { - // get hours+minutes offset - var hhoffset = parseInt(utc.substr(end + 1, 2), 10); - var mmoffset = parseInt(utc.substr(end + 4, 2), 10); +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - // calculate offset in milliseconds - var offset = hhoffset * 60 + mmoffset; - offset *= 60000; + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - // apply offset - if(c === '+') { - date.setTime(+date - offset); - } else { - date.setTime(+date + offset); - } - } + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; } - return date; -}; + this._readableState.buffer.clear(); -/** - * Converts a GeneralizedTime value to a date. - * - * @param gentime the GeneralizedTime value to convert. - * - * @return the date. - */ -asn1.generalizedTimeToDate = function(gentime) { - /* The following formats can be used: + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB - YYYYMMDDHHMMSS - YYYYMMDDHHMMSS.fff - YYYYMMDDHHMMSSZ - YYYYMMDDHHMMSS.fffZ - YYYYMMDDHHMMSS+hh'mm' - YYYYMMDDHHMMSS.fff+hh'mm' - YYYYMMDDHHMMSS-hh'mm' - YYYYMMDDHHMMSS.fff-hh'mm' - Where: +var MAX_HWM = 0x40000000; - YYYY is the year - MM is the month (01 to 12) - DD is the day (01 to 31) - hh is the hour (00 to 23) - mm are the minutes (00 to 59) - ss are the seconds (00 to 59) - .fff is the second fraction, accurate to three decimal places - Z indicates that local time is GMT, + indicates that local time is - later than GMT, and - indicates that local time is earlier than GMT - hh' is the absolute value of the offset from GMT in hours - mm' is the absolute value of the offset from GMT in minutes */ - var date = new Date(); +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } - var YYYY = parseInt(gentime.substr(0, 4), 10); - var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month - var DD = parseInt(gentime.substr(6, 2), 10); - var hh = parseInt(gentime.substr(8, 2), 10); - var mm = parseInt(gentime.substr(10, 2), 10); - var ss = parseInt(gentime.substr(12, 2), 10); - var fff = 0; - var offset = 0; - var isUTC = false; + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. - if(gentime.charAt(gentime.length - 1) === 'Z') { - isUTC = true; - } - var end = gentime.length - 5, c = gentime.charAt(end); - if(c === '+' || c === '-') { - // get hours+minutes offset - var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); - var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; - // calculate offset in milliseconds - offset = hhoffset * 60 + mmoffset; - offset *= 60000; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. - // apply offset - if(c === '+') { - offset *= -1; - } - isUTC = true; - } + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough - // check for second fraction - if(gentime.charAt(14) === '.') { - fff = parseFloat(gentime.substr(14), 10) * 1000; + if (!state.ended) { + state.needReadable = true; + return 0; } - if(isUTC) { - date.setUTCFullYear(YYYY, MM, DD); - date.setUTCHours(hh, mm, ss, fff); + return state.length; +} // you can override either this method, or the async _read(n) below. - // apply offset - date.setTime(+date + offset); - } else { - date.setFullYear(YYYY, MM, DD); - date.setHours(hh, mm, ss, fff); - } - return date; -}; +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. -/** - * Converts a date to a UTCTime value. - * - * Note: GeneralizedTime has 4 digits for the year and is used for X.509 - * dates past 2049. Converting to a GeneralizedTime hasn't been - * implemented yet. - * - * @param date the date to convert. - * - * @return the UTCTime value. - */ -asn1.dateToUtcTime = function(date) { - // TODO: validate; currently assumes proper format - if(typeof date === 'string') { - return date; + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; } - var rval = ''; + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - // create format YYMMDDhhmmssZ - var format = []; - format.push(('' + date.getUTCFullYear()).substr(2)); - format.push('' + (date.getUTCMonth() + 1)); - format.push('' + date.getUTCDate()); - format.push('' + date.getUTCHours()); - format.push('' + date.getUTCMinutes()); - format.push('' + date.getUTCSeconds()); + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. - // ensure 2 digits are used for each format entry - for(var i = 0; i < format.length; ++i) { - if(format[i].length < 2) { - rval += '0'; - } - rval += format[i]; - } - rval += 'Z'; - return rval; -}; + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some -/** - * Converts a date to a GeneralizedTime value. - * - * @param date the date to convert. - * - * @return the GeneralizedTime value as a string. - */ -asn1.dateToGeneralizedTime = function(date) { - // TODO: validate; currently assumes proper format - if(typeof date === 'string') { - return date; - } + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. - var rval = ''; - // create format YYYYMMDDHHMMSSZ - var format = []; - format.push('' + date.getUTCFullYear()); - format.push('' + (date.getUTCMonth() + 1)); - format.push('' + date.getUTCDate()); - format.push('' + date.getUTCHours()); - format.push('' + date.getUTCMinutes()); - format.push('' + date.getUTCSeconds()); + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. - // ensure 2 digits are used for each format entry - for(var i = 0; i < format.length; ++i) { - if(format[i].length < 2) { - rval += '0'; - } - rval += format[i]; + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); } - rval += 'Z'; - return rval; -}; + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; -/** - * Converts a javascript integer to a DER-encoded byte buffer to be used - * as the value for an INTEGER type. - * - * @param x the integer. - * - * @return the byte buffer. - */ -asn1.integerToDer = function(x) { - var rval = forge.util.createBuffer(); - if(x >= -0x80 && x < 0x80) { - return rval.putSignedInt(x, 8); - } - if(x >= -0x8000 && x < 0x8000) { - return rval.putSignedInt(x, 16); - } - if(x >= -0x800000 && x < 0x800000) { - return rval.putSignedInt(x, 24); - } - if(x >= -0x80000000 && x < 0x80000000) { - return rval.putSignedInt(x, 32); + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; } - var error = new Error('Integer too large; max is 32-bits.'); - error.integer = x; - throw error; -}; -/** - * Converts a DER-encoded byte buffer to a javascript integer. This is - * typically used to decode the value of an INTEGER type. - * - * @param bytes the byte buffer. - * - * @return the integer. - */ -asn1.derToInteger = function(bytes) { - // wrap in buffer if needed - if(typeof bytes === 'string') { - bytes = forge.util.createBuffer(bytes); - } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - var n = bytes.length() * 8; - if(n > 32) { - throw new Error('Integer too large; max is 32-bits.'); + if (nOrig !== n && state.ended) endReadable(this); } - return bytes.getSignedInt(n); -}; -/** - * Validates that the given ASN.1 object is at least a super set of the - * given ASN.1 structure. Only tag classes and types are checked. An - * optional map may also be provided to capture ASN.1 values while the - * structure is checked. - * - * To capture an ASN.1 value, set an object in the validator's 'capture' - * parameter to the key to use in the capture map. To capture the full - * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including - * the leading unused bits counter byte, specify 'captureBitStringContents'. - * To capture BIT STRING bytes, without the leading unused bits counter byte, - * specify 'captureBitStringValue'. - * - * Objects in the validator may set a field 'optional' to true to indicate - * that it isn't necessary to pass validation. - * - * @param obj the ASN.1 object to validate. - * @param v the ASN.1 structure validator. - * @param capture an optional map to capture values in. - * @param errors an optional array for storing validation errors. - * - * @return true on success, false on failure. - */ -asn1.validate = function(obj, v, capture, errors) { - var rval = false; + if (ret !== null) this.emit('data', ret); + return ret; +}; - // ensure tag class and type are the same if specified - if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') && - (obj.type === v.type || typeof(v.type) === 'undefined')) { - // ensure constructed flag is the same if specified - if(obj.constructed === v.constructed || - typeof(v.constructed) === 'undefined') { - rval = true; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; - // handle sub values - if(v.value && forge.util.isArray(v.value)) { - var j = 0; - for(var i = 0; rval && i < v.value.length; ++i) { - rval = v.value[i].optional || false; - if(obj.value[j]) { - rval = asn1.validate(obj.value[j], v.value[i], capture, errors); - if(rval) { - ++j; - } else if(v.value[i].optional) { - rval = true; - } - } - if(!rval && errors) { - errors.push( - '[' + v.name + '] ' + - 'Tag class "' + v.tagClass + '", type "' + - v.type + '" expected value length "' + - v.value.length + '", got "' + - obj.value.length + '"'); - } - } - } + if (state.decoder) { + var chunk = state.decoder.end(); - if(rval && capture) { - if(v.capture) { - capture[v.capture] = obj.value; - } - if(v.captureAsn1) { - capture[v.captureAsn1] = obj; - } - if(v.captureBitStringContents && 'bitStringContents' in obj) { - capture[v.captureBitStringContents] = obj.bitStringContents; - } - if(v.captureBitStringValue && 'bitStringContents' in obj) { - var value; - if(obj.bitStringContents.length < 2) { - capture[v.captureBitStringValue] = ''; - } else { - // FIXME: support unused bits with data shifting - var unused = obj.bitStringContents.charCodeAt(0); - if(unused !== 0) { - throw new Error( - 'captureBitStringValue only supported for zero unused bits'); - } - capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); - } - } - } - } else if(errors) { - errors.push( - '[' + v.name + '] ' + - 'Expected constructed "' + v.constructed + '", got "' + - obj.constructed + '"'); - } - } else if(errors) { - if(obj.tagClass !== v.tagClass) { - errors.push( - '[' + v.name + '] ' + - 'Expected tag class "' + v.tagClass + '", got "' + - obj.tagClass + '"'); - } - if(obj.type !== v.type) { - errors.push( - '[' + v.name + '] ' + - 'Expected type "' + v.type + '", got "' + obj.type + '"'); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } } - return rval; -}; - -// regex for testing for non-latin characters -var _nonLatinRegex = /[^\\u0000-\\u00ff]/; -/** - * Pretty prints an ASN.1 object to a string. - * - * @param obj the object to write out. - * @param level the level in the tree. - * @param indentation the indentation to use. - * - * @return the string. - */ -asn1.prettyPrint = function(obj, level, indentation) { - var rval = ''; + state.ended = true; - // set default level and indentation - level = level || 0; - indentation = indentation || 2; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; - // start new line for deep levels - if(level > 0) { - rval += '\n'; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } } +} // Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. - // create indent - var indent = ''; - for(var i = 0; i < level * indentation; ++i) { - indent += ' '; - } - // print class:type - rval += indent + 'Tag: '; - switch(obj.tagClass) { - case asn1.Class.UNIVERSAL: - rval += 'Universal:'; - break; - case asn1.Class.APPLICATION: - rval += 'Application:'; - break; - case asn1.Class.CONTEXT_SPECIFIC: - rval += 'Context-Specific:'; - break; - case asn1.Class.PRIVATE: - rval += 'Private:'; - break; +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); } +} - if(obj.tagClass === asn1.Class.UNIVERSAL) { - rval += obj.type; +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); - // known types - switch(obj.type) { - case asn1.Type.NONE: - rval += ' (None)'; - break; - case asn1.Type.BOOLEAN: - rval += ' (Boolean)'; - break; - case asn1.Type.INTEGER: - rval += ' (Integer)'; - break; - case asn1.Type.BITSTRING: - rval += ' (Bit string)'; - break; - case asn1.Type.OCTETSTRING: - rval += ' (Octet string)'; - break; - case asn1.Type.NULL: - rval += ' (Null)'; - break; - case asn1.Type.OID: - rval += ' (Object Identifier)'; - break; - case asn1.Type.ODESC: - rval += ' (Object Descriptor)'; - break; - case asn1.Type.EXTERNAL: - rval += ' (External or Instance of)'; - break; - case asn1.Type.REAL: - rval += ' (Real)'; - break; - case asn1.Type.ENUMERATED: - rval += ' (Enumerated)'; - break; - case asn1.Type.EMBEDDED: - rval += ' (Embedded PDV)'; - break; - case asn1.Type.UTF8: - rval += ' (UTF8)'; - break; - case asn1.Type.ROID: - rval += ' (Relative Object Identifier)'; - break; - case asn1.Type.SEQUENCE: - rval += ' (Sequence)'; - break; - case asn1.Type.SET: - rval += ' (Set)'; - break; - case asn1.Type.PRINTABLESTRING: - rval += ' (Printable String)'; - break; - case asn1.Type.IA5String: - rval += ' (IA5String (ASCII))'; - break; - case asn1.Type.UTCTIME: - rval += ' (UTC time)'; - break; - case asn1.Type.GENERALIZEDTIME: - rval += ' (Generalized time)'; - break; - case asn1.Type.BMPSTRING: - rval += ' (BMP String)'; - break; - } - } else { - rval += obj.type; - } + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. - rval += '\n'; - rval += indent + 'Constructed: ' + obj.constructed + '\n'; - if(obj.composed) { - var subvalues = 0; - var sub = ''; - for(var i = 0; i < obj.value.length; ++i) { - if(obj.value[i] !== undefined) { - subvalues += 1; - sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); - if((i + 1) < obj.value.length) { - sub += ','; - } - } - } - rval += indent + 'Sub values: ' + subvalues + sub; - } else { - rval += indent + 'Value: '; - if(obj.type === asn1.Type.OID) { - var oid = asn1.derToOid(obj.value); - rval += oid; - if(forge.pki && forge.pki.oids) { - if(oid in forge.pki.oids) { - rval += ' (' + forge.pki.oids[oid] + ') '; - } - } - } - if(obj.type === asn1.Type.INTEGER) { - try { - rval += asn1.derToInteger(obj.value); - } catch(ex) { - rval += '0x' + forge.util.bytesToHex(obj.value); - } - } else if(obj.type === asn1.Type.BITSTRING) { - // TODO: shift bits as needed to display without padding - if(obj.value.length > 1) { - // remove unused bits field - rval += '0x' + forge.util.bytesToHex(obj.value.slice(1)); - } else { - rval += '(none)'; - } - // show unused bit count - if(obj.value.length > 0) { - var unused = obj.value.charCodeAt(0); - if(unused == 1) { - rval += ' (1 unused bit shown)'; - } else if(unused > 1) { - rval += ' (' + unused + ' unused bits shown)'; - } - } - } else if(obj.type === asn1.Type.OCTETSTRING) { - if(!_nonLatinRegex.test(obj.value)) { - rval += '(' + obj.value + ') '; - } - rval += '0x' + forge.util.bytesToHex(obj.value); - } else if(obj.type === asn1.Type.UTF8) { - try { - rval += forge.util.decodeUtf8(obj.value); - } catch(e) { - if(e.message === 'URI malformed') { - rval += - '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)'; - } else { - throw e; - } - } - } else if(obj.type === asn1.Type.PRINTABLESTRING || - obj.type === asn1.Type.IA5String) { - rval += obj.value; - } else if(_nonLatinRegex.test(obj.value)) { - rval += '0x' + forge.util.bytesToHex(obj.value); - } else if(obj.value.length === 0) { - rval += '[null]'; - } else { - rval += obj.value; - } + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. + + +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); } +} - return rval; -}; +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. -/***/ }), -/***/ 2300: -/***/ ((module) => { +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; -/** - * Base-N/Base-X encoding/decoding functions. - * - * Original implementation from base-x: - * https://github.com/cryptocoinjs/base-x - * - * Which is MIT licensed: - * - * The MIT License (MIT) - * - * Copyright base-x contributors (c) 2016 - * - * 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. - */ -var api = {}; -module.exports = api; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; -// baseN alphabet indexes -var _reverseAlphabets = {}; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; -/** - * BaseN-encodes a Uint8Array using the given alphabet. - * - * @param input the Uint8Array to encode. - * @param maxline the maximum number of encoded characters per line to use, - * defaults to none. - * - * @return the baseN-encoded output string. - */ -api.encode = function(input, alphabet, maxline) { - if(typeof alphabet !== 'string') { - throw new TypeError('"alphabet" must be a string.'); - } - if(maxline !== undefined && typeof maxline !== 'number') { - throw new TypeError('"maxline" must be a number.'); + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; } - var output = ''; + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); - if(!(input instanceof Uint8Array)) { - // assume forge byte buffer - output = _encodeWithByteBuffer(input, alphabet); - } else { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for(i = 0; i < input.length; ++i) { - for(var j = 0, carry = input[i]; j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = (carry / base) | 0; - } + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); - while(carry > 0) { - digits.push(carry % base); - carry = (carry / base) | 0; + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); } } - - // deal with leading zeros - for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { - output += first; - } - // convert digits to a string - for(i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } } - if(maxline) { - var regex = new RegExp('.{1,' + maxline + '}', 'g'); - output = output.match(regex).join('\r\n'); - } + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. - return output; -}; -/** - * Decodes a baseN-encoded (using the given alphabet) string to a - * Uint8Array. - * - * @param input the baseN-encoded input string. - * - * @return the Uint8Array. - */ -api.decode = function(input, alphabet) { - if(typeof input !== 'string') { - throw new TypeError('"input" must be a string.'); - } - if(typeof alphabet !== 'string') { - throw new TypeError('"alphabet" must be a string.'); - } + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; - var table = _reverseAlphabets[alphabet]; - if(!table) { - // compute reverse alphabet - table = _reverseAlphabets[alphabet] = []; - for(var i = 0; i < alphabet.length; ++i) { - table[alphabet.charCodeAt(i)] = i; - } + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - // remove whitespace characters - input = input.replace(/\s/g, ''); + src.on('data', ondata); - var base = alphabet.length; - var first = alphabet.charAt(0); - var bytes = [0]; - for(var i = 0; i < input.length; i++) { - var value = table[input.charCodeAt(i)]; - if(value === undefined) { - return; - } + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); - for(var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * base; - bytes[j] = carry & 0xff; - carry >>= 8; - } + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } - while(carry > 0) { - bytes.push(carry & 0xff); - carry >>= 8; + src.pause(); } - } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - // deal with leading zeros - for(var k = 0; input[k] === first && k < input.length - 1; ++k) { - bytes.push(0); - } - if(typeof Buffer !== 'undefined') { - return Buffer.from(bytes.reverse()); - } + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. - return new Uint8Array(bytes.reverse()); -}; -function _encodeWithByteBuffer(input, alphabet) { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for(i = 0; i < input.length(); ++i) { - for(var j = 0, carry = input.at(i); j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = (carry / base) | 0; - } + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - while(carry > 0) { - digits.push(carry % base); - carry = (carry / base) | 0; - } + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - var output = ''; + dest.once('close', onclose); - // deal with leading zeros - for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { - output += first; + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); } - // convert digits to a string - for(i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); } - return output; + return dest; +}; + +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; } +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. -/***/ }), + if (state.pipesCount === 0) return this; // just one destination. most common case. -/***/ 7088: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. -/** - * Cipher base API. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. -module.exports = forge.cipher = forge.cipher || {}; -// registered algorithms -forge.cipher.algorithms = forge.cipher.algorithms || {}; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; -/** - * Creates a cipher object that can be used to encrypt data using the given - * algorithm and key. The algorithm may be provided as a string value for a - * previously registered algorithm or it may be given as a cipher algorithm - * API object. - * - * @param algorithm the algorithm to use, either a string or an algorithm API - * object. - * @param key the key to use, as a binary-encoded string of bytes or a - * byte buffer. - * - * @return the cipher. - */ -forge.cipher.createCipher = function(algorithm, key) { - var api = algorithm; - if(typeof api === 'string') { - api = forge.cipher.getAlgorithm(api); - if(api) { - api = api(); + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); } - } - if(!api) { - throw new Error('Unsupported algorithm: ' + algorithm); - } - // assume block cipher - return new forge.cipher.BlockCipher({ - algorithm: api, - key: key, - decrypt: false - }); -}; + return this; + } // try to find the right one. -/** - * Creates a decipher object that can be used to decrypt data using the given - * algorithm and key. The algorithm may be provided as a string value for a - * previously registered algorithm or it may be given as a cipher algorithm - * API object. - * - * @param algorithm the algorithm to use, either a string or an algorithm API - * object. - * @param key the key to use, as a binary-encoded string of bytes or a - * byte buffer. - * - * @return the cipher. - */ -forge.cipher.createDecipher = function(algorithm, key) { - var api = algorithm; - if(typeof api === 'string') { - api = forge.cipher.getAlgorithm(api); - if(api) { - api = api(); + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; // set up data events if they are asked for +// Ensure readable listeners eventually get something + + +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } } } - if(!api) { - throw new Error('Unsupported algorithm: ' + algorithm); - } - // assume block cipher - return new forge.cipher.BlockCipher({ - algorithm: api, - key: key, - decrypt: true - }); + return res; }; -/** - * Registers an algorithm by name. If the name was already registered, the - * algorithm API object will be overwritten. - * - * @param name the name of the algorithm. - * @param algorithm the algorithm API object. - */ -forge.cipher.registerAlgorithm = function(name, algorithm) { - name = name.toUpperCase(); - forge.cipher.algorithms[name] = algorithm; -}; +Readable.prototype.addListener = Readable.prototype.on; -/** - * Gets a registered algorithm by name. - * - * @param name the name of the algorithm. - * - * @return the algorithm, if found, null if not. - */ -forge.cipher.getAlgorithm = function(name) { - name = name.toUpperCase(); - if(name in forge.cipher.algorithms) { - return forge.cipher.algorithms[name]; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); } - return null; -}; -var BlockCipher = forge.cipher.BlockCipher = function(options) { - this.algorithm = options.algorithm; - this.mode = this.algorithm.mode; - this.blockSize = this.mode.blockSize; - this._finish = false; - this._input = null; - this.output = null; - this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; - this._decrypt = options.decrypt; - this.algorithm.initialize(options); + return res; }; -/** - * Starts or restarts the encryption or decryption process, whichever - * was previously configured. - * - * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array - * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in - * bytes, then it must be Nb (16) bytes in length. If the IV is given in as - * 32-bit integers, then it must be 4 integers long. - * - * Note: an IV is not required or used in ECB mode. - * - * For GCM-mode, the IV must be given as a binary-encoded string of bytes or - * a byte buffer. The number of bytes should be 12 (96 bits) as recommended - * by NIST SP-800-38D but another length may be given. - * - * @param options the options to use: - * iv the initialization vector to use as a binary-encoded string of - * bytes, null to reuse the last ciphered block from a previous - * update() (this "residue" method is for legacy support only). - * additionalData additional authentication data as a binary-encoded - * string of bytes, for 'GCM' mode, (default: none). - * tagLength desired length of authentication tag, in bits, for - * 'GCM' mode (0-128, default: 128). - * tag the authentication tag to check if decrypting, as a - * binary-encoded string of bytes. - * output the output the buffer to write to, null to create one. - */ -BlockCipher.prototype.start = function(options) { - options = options || {}; - var opts = {}; - for(var key in options) { - opts[key] = options[key]; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); } - opts.decrypt = this._decrypt; - this._finish = false; - this._input = forge.util.createBuffer(); - this.output = options.output || forge.util.createBuffer(); - this.mode.start(opts); + + return res; }; -/** - * Updates the next block according to the cipher mode. - * - * @param input the buffer to read from. - */ -BlockCipher.prototype.update = function(input) { - if(input) { - // input given, so empty it into the input buffer - this._input.putBuffer(input); +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); } +} - // do cipher operation until it needs more input and not finished - while(!this._op.call(this.mode, this._input, this.output, this._finish) && - !this._finish) {} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. - // free consumed memory from input buffer - this._input.compact(); + +Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; }; -/** - * Finishes encrypting or decrypting. - * - * @param pad a padding function to use in CBC mode, null for default, - * signature(blockSize, buffer, decrypt). - * - * @return true if successful, false on error. - */ -BlockCipher.prototype.finish = function(pad) { - // backwards-compatibility w/deprecated padding API - // Note: will overwrite padding functions even after another start() call - if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { - this.mode.pad = function(input) { - return pad(this.blockSize, input, false); - }; - this.mode.unpad = function(output) { - return pad(this.blockSize, output, true); - }; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); } +} - // build options for padding and afterFinish functions - var options = {}; - options.decrypt = this._decrypt; - - // get # of bytes that won't fill a block - options.overflow = this._input.length() % this.blockSize; +function resume_(stream, state) { + debug('resume', state.reading); - if(!this._decrypt && this.mode.pad) { - if(!this.mode.pad(this._input, options)) { - return false; - } + if (!state.reading) { + stream.read(0); } - // do final update - this._finish = true; - this.update(); + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} - if(this._decrypt && this.mode.unpad) { - if(!this.mode.unpad(this.output, options)) { - return false; - } - } +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); - if(this.mode.afterFinish) { - if(!this.mode.afterFinish(this.output, options)) { - return false; - } + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); } - return true; + this._readableState.paused = true; + return this; }; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); -/***/ }), + while (state.flowing && stream.read() !== null) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. -/***/ 873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Supported cipher modes. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); +Readable.prototype.wrap = function (stream) { + var _this = this; -forge.cipher = forge.cipher || {}; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); -// supported cipher modes -var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {}; + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } -/** Electronic codebook (ECB) (Don't use this; it's not secure) **/ + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode -modes.ecb = function(options) { - options = options || {}; - this.name = 'ECB'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); -}; + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; -modes.ecb.prototype.start = function(options) {}; + var ret = _this.push(chunk); -modes.ecb.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - if(input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. - // get next block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. - // encrypt block - this.cipher.encrypt(this._inBlock, this._outBlock); - // write output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } -}; + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. -modes.ecb.prototype.decrypt = function(input, output, finish) { - // not enough input to decrypt - if(input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - // get next block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } + this._read = function (n) { + debug('wrapped _read', n); - // decrypt block - this.cipher.decrypt(this._inBlock, this._outBlock); + if (paused) { + paused = false; + stream.resume(); + } + }; - // write output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } + return this; }; -modes.ecb.prototype.pad = function(input, options) { - // add PKCS#7 padding to block (each pad byte is the - // value of the number of pad bytes) - var padding = (input.length() === this.blockSize ? - this.blockSize : (this.blockSize - input.length())); - input.fillWithByte(padding, padding); - return true; -}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __nccwpck_require__(3306); + } -modes.ecb.prototype.unpad = function(output, options) { - // check for error: input data not a multiple of blockSize - if(options.overflow > 0) { - return false; - } + return createReadableStreamAsyncIterator(this); + }; +} - // ensure padding byte count is valid - var len = output.length(); - var count = output.at(len - 1); - if(count > (this.blockSize << 2)) { - return false; +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; } - - // trim off padding bytes - output.truncate(count); - return true; -}; - -/** Cipher-block Chaining (CBC) **/ - -modes.cbc = function(options) { - options = options || {}; - this.name = 'CBC'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); -}; - -modes.cbc.prototype.start = function(options) { - // Note: legacy support for using IV residue (has security flaws) - // if IV is null, reuse block from previous processing - if(options.iv === null) { - // must have a previous block - if(!this._prev) { - throw new Error('Invalid IV parameter.'); +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; } - this._iv = this._prev.slice(0); - } else if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } else { - // save IV as "previous" block - this._iv = transformIV(options.iv, this.blockSize); - this._prev = this._iv.slice(0); } -}; +}); // exposed for testing purposes only. -modes.cbc.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - if(input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; } +}); // Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. - // get next block - // CBC XOR's IV (or previous block) with plaintext - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._prev[i] ^ input.getInt32(); +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); } + return ret; +} - // encrypt block - this.cipher.encrypt(this._inBlock, this._outBlock); +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); - // write output, save previous block - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); } - this._prev = this._outBlock; -}; +} -modes.cbc.prototype.decrypt = function(input, output, finish) { - // not enough input to decrypt - if(input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - // get next block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); - // decrypt block - this.cipher.decrypt(this._inBlock, this._outBlock); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; - // write output, save previous ciphered block - // CBC XOR's IV (or previous block) with ciphertext - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._prev[i] ^ this._outBlock[i]); + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } } - this._prev = this._inBlock.slice(0); -}; +} -modes.cbc.prototype.pad = function(input, options) { - // add PKCS#7 padding to block (each pad byte is the - // value of the number of pad bytes) - var padding = (input.length() === this.blockSize ? - this.blockSize : (this.blockSize - input.length())); - input.fillWithByte(padding, padding); - return true; -}; +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __nccwpck_require__(9082); + } -modes.cbc.prototype.unpad = function(output, options) { - // check for error: input data not a multiple of blockSize - if(options.overflow > 0) { - return false; - } + return from(Readable, iterable, opts); + }; +} - // ensure padding byte count is valid - var len = output.length(); - var count = output.at(len - 1); - if(count > (this.blockSize << 2)) { - return false; +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } - // trim off padding bytes - output.truncate(count); - return true; -}; + return -1; +} -/** Cipher feedback (CFB) **/ +/***/ }), -modes.cfb = function(options) { - options = options || {}; - this.name = 'CFB'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; -}; +/***/ 4415: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -modes.cfb.prototype.start = function(options) { - if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } - // use IV as first input - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; -}; +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. -modes.cfb.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - var inputLength = input.length(); - if(inputLength === 0) { - return true; - } - // encrypt block - this.cipher.encrypt(this._inBlock, this._outBlock); +module.exports = Transform; - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output, write input as output - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; - output.putInt32(this._inBlock[i]); - } - return; +var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + +var Duplex = __nccwpck_require__(1359); + +__nccwpck_require__(4124)(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. - // XOR input with output, write input as partial output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; - this._partialOutput.putInt32(this._partialBlock[i]); - } - if(partialBytes > 0) { - // block still incomplete, restore input buffer - input.read -= this.blockSize; - } else { - // block complete, update input block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } + this.on('prefinish', prefinish); +} - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } +function prefinish() { + var _this = this; - if(partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); } +} - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; -}; +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. -modes.cfb.prototype.decrypt = function(input, output, finish) { - // not enough input to decrypt - var inputLength = input.length(); - if(inputLength === 0) { - return true; - } - // encrypt block (CFB always uses encryption mode) - this.cipher.encrypt(this._inBlock, this._outBlock); +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output, write input as output - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - output.putInt32(this._inBlock[i] ^ this._outBlock[i]); - } - return; - } +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. - // XOR input with output, write input as partial output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32(); - this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); - } - if(partialBytes > 0) { - // block still incomplete, restore input buffer - input.read -= this.blockSize; - } else { - // block complete, update input block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } +Transform.prototype._read = function (n) { + var ts = this._transformState; - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; - if(partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } +}; - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); }; -/** Output feedback (OFB) **/ +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided -modes.ofb = function(options) { - options = options || {}; - this.name = 'OFB'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; -}; + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} -modes.ofb.prototype.start = function(options) { - if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } - // use IV as first input - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; -}; +/***/ }), -modes.ofb.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - var inputLength = input.length(); - if(input.length() === 0) { - return true; - } +/***/ 6993: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // encrypt block (OFB always uses encryption mode) - this.cipher.encrypt(this._inBlock, this._outBlock); +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output and update next input - for(var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - this._inBlock[i] = this._outBlock[i]; - } - return; - } - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } +module.exports = Writable; +/* */ - // XOR input with output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream - if(partialBytes > 0) { - // block still incomplete, restore input buffer - input.read -= this.blockSize; - } else { - // block complete, update input block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._outBlock[i]; - } - } - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } +function CorkedRequest(state) { + var _this = this; - if(partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; - } + this.next = null; + this.entry = null; - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; -}; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ -modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; +/**/ -/** Counter (CTR) **/ -modes.ctr = function(options) { - options = options || {}; - this.name = 'CTR'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; -}; +var Duplex; +/**/ -modes.ctr.prototype.start = function(options) { - if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } - // use IV as first input - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; +Writable.WritableState = WritableState; +/**/ + +var internalUtil = { + deprecate: __nccwpck_require__(7127) }; +/**/ -modes.ctr.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - var inputLength = input.length(); - if(inputLength === 0) { - return true; - } +/**/ - // encrypt block (CTR always uses encryption mode) - this.cipher.encrypt(this._inBlock, this._outBlock); +var Stream = __nccwpck_require__(2387); +/**/ - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - } - } else { - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - // XOR input with output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } +var Buffer = (__nccwpck_require__(4300).Buffer); - if(partialBytes > 0) { - // block still incomplete, restore input buffer - input.read -= this.blockSize; - } +var OurUint8Array = global.Uint8Array || function () {}; - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} - if(partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; - } +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; - } +var destroyImpl = __nccwpck_require__(7049); - // block complete, increment counter (input block) - inc32(this._inBlock); -}; +var _require = __nccwpck_require__(9948), + getHighWaterMark = _require.getHighWaterMark; -modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; +var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; -/** Galois/Counter Mode (GCM) **/ +var errorOrDestroy = destroyImpl.errorOrDestroy; -modes.gcm = function(options) { - options = options || {}; - this.name = 'GCM'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; +__nccwpck_require__(4124)(Writable, Stream); - // R is actually this value concatenated with 120 more zero bits, but - // we only XOR against R so the other zeros have no effect -- we just - // apply this value to the first integer in a block - this._R = 0xE1000000; -}; +function nop() {} -modes.gcm.prototype.start = function(options) { - if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } - // ensure IV is a byte buffer - var iv = forge.util.createBuffer(options.iv); +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(1359); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - // no ciphered data processed yet - this._cipherLength = 0; + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. - // default additional data is none - var additionalData; - if('additionalData' in options) { - additionalData = forge.util.createBuffer(options.additionalData); - } else { - additionalData = forge.util.createBuffer(); - } + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() - // default tag length is 128 bits - if('tagLength' in options) { - this._tagLength = options.tagLength; - } else { - this._tagLength = 128; - } + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - // if tag is given, ensure tag matches tag length - this._tag = null; - if(options.decrypt) { - // save tag to check later - this._tag = forge.util.createBuffer(options.tag).getBytes(); - if(this._tag.length !== (this._tagLength / 8)) { - throw new Error('Authentication tag does not match tag length.'); - } - } + this.finalCalled = false; // drain event flag. - // create tmp storage for hash calculation - this._hashBlock = new Array(this._ints); + this.needDrain = false; // at the start of calling end() - // no tag generated yet - this.tag = null; + this.ending = false; // when end() has been called, and returned - // generate hash subkey - // (apply block cipher to "zero" block) - this._hashSubkey = new Array(this._ints); - this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); + this.ended = false; // when 'finish' is emitted - // generate table M - // use 4-bit tables (32 component decomposition of a 16 byte value) - // 8-bit tables take more space and are known to have security - // vulnerabilities (in native implementations) - this.componentBits = 4; - this._m = this.generateHashTable(this._hashSubkey, this.componentBits); + this.finished = false; // has it been destroyed - // Note: support IV length different from 96 bits? (only supporting - // 96 bits is recommended by NIST SP-800-38D) - // generate J_0 - var ivLength = iv.length(); - if(ivLength === 12) { - // 96-bit IV - this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; - } else { - // IV is NOT 96-bits - this._j0 = [0, 0, 0, 0]; - while(iv.length() > 0) { - this._j0 = this.ghash( - this._hashSubkey, this._j0, - [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); - } - this._j0 = this.ghash( - this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); - } + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. - // generate ICB (initial counter block) - this._inBlock = this._j0.slice(0); - inc32(this._inBlock); - this._partialBytes = 0; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - // consume authentication data - additionalData = forge.util.createBuffer(additionalData); - // save additional data length as a BE 64-bit number - this._aDataLength = from64To32(additionalData.length() * 8); - // pad additional data to 128 bit (16 byte) block size - var overflow = additionalData.length() % this.blockSize; - if(overflow) { - additionalData.fillWithByte(0, this.blockSize - overflow); - } - this._s = [0, 0, 0, 0]; - while(additionalData.length() > 0) { - this._s = this.ghash(this._hashSubkey, this._s, [ - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32() - ]); - } -}; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. -modes.gcm.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - var inputLength = input.length(); - if(inputLength === 0) { - return true; - } + this.length = 0; // a flag to see when we're in the middle of a write. - // encrypt block - this.cipher.encrypt(this._inBlock, this._outBlock); + this.writing = false; // when true all writes will be buffered until .uncork() call - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^= input.getInt32()); - } - this._cipherLength += this.blockSize; - } else { - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. - // XOR input with output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. - if(partialBytes <= 0 || finish) { - // handle overflow prior to hashing - if(finish) { - // get block overflow - var overflow = inputLength % this.blockSize; - this._cipherLength += overflow; - // truncate for hash function - this._partialOutput.truncate(this.blockSize - overflow); - } else { - this._cipherLength += this.blockSize; - } + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - // get output block for hashing - for(var i = 0; i < this._ints; ++i) { - this._outBlock[i] = this._partialOutput.getInt32(); - } - this._partialOutput.read -= this.blockSize; - } + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if(partialBytes > 0 && !finish) { - // block still incomplete, restore input buffer, get partial output, - // and return early - input.read -= this.blockSize; - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; - } + this.writecb = null; // the amount that is being written when _write is called. - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; - } + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted - // update hash block S - this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - // increment counter (input block) - inc32(this._inBlock); -}; + this.prefinished = false; // True if the error was already emitted and should not be thrown again -modes.gcm.prototype.decrypt = function(input, output, finish) { - // not enough input to decrypt - var inputLength = input.length(); - if(inputLength < this.blockSize && !(finish && inputLength > 0)) { - return true; - } + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - // encrypt block (GCM always uses encryption mode) - this.cipher.encrypt(this._inBlock, this._outBlock); + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - // increment counter (input block) - inc32(this._inBlock); + this.autoDestroy = !!options.autoDestroy; // count buffered requests - // update hash block S - this._hashBlock[0] = input.getInt32(); - this._hashBlock[1] = input.getInt32(); - this._hashBlock[2] = input.getInt32(); - this._hashBlock[3] = input.getInt32(); - this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two - // XOR hash input with output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); - } + this.corkedRequestsFree = new CorkedRequest(this); +} - // increment cipher data length - if(inputLength < this.blockSize) { - this._cipherLength += inputLength % this.blockSize; - } else { - this._cipherLength += this.blockSize; +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; } + + return out; }; -modes.gcm.prototype.afterFinish = function(output, options) { - var rval = true; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. - // handle overflow - if(options.decrypt && options.overflow) { - output.truncate(this.blockSize - options.overflow); - } - // handle authentication tag - this.tag = forge.util.createBuffer(); +var realHasInstance; - // concatenate additional data length with cipher length - var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} - // include lengths in hash - this._s = this.ghash(this._hashSubkey, this._s, lengths); +function Writable(options) { + Duplex = Duplex || __nccwpck_require__(1359); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 - // do GCTR(J_0, S) - var tag = []; - this.cipher.encrypt(this._j0, tag); - for(var i = 0; i < this._ints; ++i) { - this.tag.putInt32(this._s[i] ^ tag[i]); - } + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. - // trim tag to length - this.tag.truncate(this.tag.length() % (this._tagLength / 8)); + this.writable = true; - // check authentication tag - if(options.decrypt && this.tag.bytes() !== this._tag) { - rval = false; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; } - return rval; + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. + + +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; -/** - * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois - * field multiplication. The field, GF(2^128), is defined by the polynomial: - * - * x^128 + x^7 + x^2 + x + 1 - * - * Which is represented in little-endian binary form as: 11100001 (0xe1). When - * the value of a coefficient is 1, a bit is set. The value R, is the - * concatenation of this value and 120 zero bits, yielding a 128-bit value - * which matches the block size. - * - * This function will multiply two elements (vectors of bytes), X and Y, in - * the field GF(2^128). The result is initialized to zero. For each bit of - * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) - * by the current value of Y. For each bit, the value of Y will be raised by - * a power of x (multiplied by the polynomial x). This can be achieved by - * shifting Y once to the right. If the current value of Y, prior to being - * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. - * Otherwise, we must divide by R after shifting to find the remainder. - * - * @param x the first block to multiply by the second. - * @param y the second block to multiply by the first. - * - * @return the block result of the multiplication. - */ -modes.gcm.prototype.multiply = function(x, y) { - var z_i = [0, 0, 0, 0]; - var v_i = y.slice(0); +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - // calculate Z_128 (block has 128 bits) - for(var i = 0; i < 128; ++i) { - // if x_i is 0, Z_{i+1} = Z_i (unchanged) - // else Z_{i+1} = Z_i ^ V_i - // get x_i by finding 32-bit int position, then left shift 1 by remainder - var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); - if(x_i) { - z_i[0] ^= v_i[0]; - z_i[1] ^= v_i[1]; - z_i[2] ^= v_i[2]; - z_i[3] ^= v_i[3]; - } + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. - // if LSB(V_i) is 1, V_i = V_i >> 1 - // else V_i = (V_i >> 1) ^ R - this.pow(v_i, v_i); + +function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } - return z_i; -}; + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } -modes.gcm.prototype.pow = function(x, out) { - // if LSB(x) is 1, x = x >>> 1 - // else x = (x >>> 1) ^ R - var lsb = x[3] & 1; + return true; +} - // always do x >>> 1: - // starting with the rightmost integer, shift each integer to the right - // one bit, pulling in the bit from the integer to the left as its top - // most bit (do this for the last 3 integers) - for(var i = 3; i > 0; --i) { - out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); } - // shift the first integer normally - out[0] = x[0] >>> 1; - // if lsb was not set, then polynomial had a degree of 127 and doesn't - // need to divided; otherwise, XOR with R to find the remainder; we only - // need to XOR the first integer since R technically ends w/120 zero bits - if(lsb) { - out[0] ^= this._R; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } -}; -modes.gcm.prototype.tableMultiply = function(x) { - // assumes 4-bit tables are used - var z = [0, 0, 0, 0]; - for(var i = 0; i < 32; ++i) { - var idx = (i / 8) | 0; - var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; - var ah = this._m[i][x_i]; - z[0] ^= ah[0]; - z[1] ^= ah[1]; - z[2] ^= ah[2]; - z[3] ^= ah[3]; + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } - return z; + return ret; }; -/** - * A continuing version of the GHASH algorithm that operates on a single - * block. The hash block, last hash value (Ym) and the new block to hash - * are given. - * - * @param h the hash block. - * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. - * @param x the block to hash. - * - * @return the hashed value (Ym). - */ -modes.gcm.prototype.ghash = function(h, y, x) { - y[0] ^= x[0]; - y[1] ^= x[1]; - y[2] ^= x[2]; - y[3] ^= x[3]; - return this.tableMultiply(y); - //return this.multiply(y, h); +Writable.prototype.cork = function () { + this._writableState.corked++; }; -/** - * Precomputes a table for multiplying against the hash subkey. This - * mechanism provides a substantial speed increase over multiplication - * performed without a table. The table-based multiplication this table is - * for solves X * H by multiplying each component of X by H and then - * composing the results together using XOR. - * - * This function can be used to generate tables with different bit sizes - * for the components, however, this implementation assumes there are - * 32 components of X (which is a 16 byte vector), therefore each component - * takes 4-bits (so the table is constructed with bits=4). - * - * @param h the hash subkey. - * @param bits the bit size for a component. - */ -modes.gcm.prototype.generateHashTable = function(h, bits) { - // TODO: There are further optimizations that would use only the - // first table M_0 (or some variant) along with a remainder table; - // this can be explored in the future - var multiplier = 8 / bits; - var perInt = 4 * multiplier; - var size = 16 * multiplier; - var m = new Array(size); - for(var i = 0; i < size; ++i) { - var tmp = [0, 0, 0, 0]; - var idx = (i / perInt) | 0; - var shft = ((perInt - 1 - (i % perInt)) * bits); - tmp[idx] = (1 << (bits - 1)) << shft; - m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } - return m; }; -/** - * Generates a table for multiplying against the hash subkey for one - * particular component (out of all possible component values). - * - * @param mid the pre-multiplied value for the middle key of the table. - * @param bits the bit size for a component. - */ -modes.gcm.prototype.generateSubHashTable = function(mid, bits) { - // compute the table quickly by minimizing the number of - // POW operations -- they only need to be performed for powers of 2, - // all other entries can be composed from those powers using XOR - var size = 1 << bits; - var half = size >>> 1; - var m = new Array(size); - m[half] = mid.slice(0); - var i = half >>> 1; - while(i > 0) { - // raise m0[2 * i] and store in m0[i] - this.pow(m[2 * i], m[i] = []); - i >>= 1; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); } - i = 2; - while(i < half) { - for(var j = 1; j < i; ++j) { - var m_i = m[i]; - var m_j = m[j]; - m[i + j] = [ - m_i[0] ^ m_j[0], - m_i[1] ^ m_j[1], - m_i[2] ^ m_j[2], - m_i[3] ^ m_j[3] - ]; - } - i *= 2; +}); + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); } - m[0] = [0, 0, 0, 0]; - /* Note: We could avoid storing these by doing composition during multiply - calculate top half using composition by speed is preferred. */ - for(i = half + 1; i < size; ++i) { - var c = m[i ^ half]; - m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; } - return m; -}; +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. -/** Utility functions */ +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); -function transformIV(iv, blockSize) { - if(typeof iv === 'string') { - // convert iv string into byte buffer - iv = forge.util.createBuffer(iv); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } } - if(forge.util.isArray(iv) && iv.length > 4) { - // convert iv byte array into byte buffer - var tmp = iv; - iv = forge.util.createBuffer(); - for(var i = 0; i < tmp.length; ++i) { - iv.putByte(tmp[i]); + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; } + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; - if(iv.length() < blockSize) { - throw new Error( - 'Invalid IV length; got ' + iv.length() + - ' bytes and expected ' + blockSize + ' bytes.'); - } + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } - if(!forge.util.isArray(iv)) { - // convert iv byte buffer into 32-bit integer array - var ints = []; - var blocks = blockSize / 4; - for(var i = 0; i < blocks; ++i) { - ints.push(iv.getInt32()); + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); } - iv = ints; } - - return iv; } -function inc32(block) { - // increment last 32 bits of block only - block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; -} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. -function from64To32(num) { - // convert 64-bit number to two BE Int32s - return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; -} +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it -/***/ }), -/***/ 7157: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; -/** - * DES (Data Encryption Standard) implementation. - * - * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode. - * It is based on the BSD-licensed implementation by Paul Tero: - * - * Paul Tero, July 2001 - * http://www.tero.co.uk/des/ - * - * Optimised for performance with large blocks by - * Michael Hayworth, November 2001 - * http://www.netdealing.com - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @author Stefan Siegl - * @author Dave Longley - * - * Copyright (c) 2012 Stefan Siegl - * Copyright (c) 2012-2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7088); -__nccwpck_require__(873); -__nccwpck_require__(8339); + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; -/* DES API */ -module.exports = forge.des = forge.des || {}; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('DES-', key); - * cipher.start({iv: iv}); - * - * Creates an DES cipher object to encrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as binary-encoded strings of bytes or - * byte buffers. - * - * @param key the symmetric key to use (64 or 192 bits). - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC' if IV is - * given, 'ECB' if null). - * - * @return the cipher. - */ -forge.des.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key: key, - output: output, - decrypt: false, - mode: mode || (iv === null ? 'ECB' : 'CBC') - }); - cipher.start(iv); - return cipher; -}; + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('DES-', key); - * - * Creates an DES cipher object to encrypt data using the given symmetric key. - * - * The key may be given as a binary-encoded string of bytes or a byte buffer. - * - * @param key the symmetric key to use (64 or 192 bits). - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge.des.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key: key, - output: null, - decrypt: false, - mode: mode - }); -}; + state.pendingcb++; + state.lastBufferedRequest = null; -/** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('DES-', key); - * decipher.start({iv: iv}); - * - * Creates an DES cipher object to decrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as binary-encoded strings of bytes or - * byte buffers. - * - * @param key the symmetric key to use (64 or 192 bits). - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC' if IV is - * given, 'ECB' if null). - * - * @return the cipher. - */ -forge.des.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key: key, - output: output, - decrypt: true, - mode: mode || (iv === null ? 'ECB' : 'CBC') - }); - cipher.start(iv); - return cipher; -}; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } -/** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('DES-', key); - * - * Creates an DES cipher object to decrypt data using the given symmetric key. - * - * The key may be given as a binary-encoded string of bytes or a byte buffer. - * - * @param key the symmetric key to use (64 or 192 bits). - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge.des.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key: key, - output: null, - decrypt: true, - mode: mode - }); -}; + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. -/** - * Creates a new DES cipher algorithm object. - * - * @param name the name of the algorithm. - * @param mode the mode factory function. - * - * @return the DES algorithm object. - */ -forge.des.Algorithm = function(name, mode) { - var self = this; - self.name = name; - self.mode = new mode({ - blockSize: 8, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self._keys, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self._keys, inBlock, outBlock, true); + if (state.writing) { + break; } } - }); - self._init = false; -}; -/** - * Initializes this DES algorithm by expanding its key. - * - * @param options the options to use. - * key the key to use with this algorithm. - * decrypt true if the algorithm should be initialized for decryption, - * false for encryption. - */ -forge.des.Algorithm.prototype.initialize = function(options) { - if(this._init) { - return; + if (entry === null) state.lastBufferedRequest = null; } - var key = forge.util.createBuffer(options.key); - if(this.name.indexOf('3DES') === 0) { - if(key.length() !== 24) { - throw new Error('Invalid Triple-DES key size: ' + key.length() * 8); - } - } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} - // do key expansion to 16 or 48 subkeys (single or triple DES) - this._keys = _createKeys(key); - this._init = true; +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; -/** Register DES algorithms **/ - -registerAlgorithm('DES-ECB', forge.cipher.modes.ecb); -registerAlgorithm('DES-CBC', forge.cipher.modes.cbc); -registerAlgorithm('DES-CFB', forge.cipher.modes.cfb); -registerAlgorithm('DES-OFB', forge.cipher.modes.ofb); -registerAlgorithm('DES-CTR', forge.cipher.modes.ctr); - -registerAlgorithm('3DES-ECB', forge.cipher.modes.ecb); -registerAlgorithm('3DES-CBC', forge.cipher.modes.cbc); -registerAlgorithm('3DES-CFB', forge.cipher.modes.cfb); -registerAlgorithm('3DES-OFB', forge.cipher.modes.ofb); -registerAlgorithm('3DES-CTR', forge.cipher.modes.ctr); - -function registerAlgorithm(name, mode) { - var factory = function() { - return new forge.des.Algorithm(name, mode); - }; - forge.cipher.registerAlgorithm(name, factory); -} +Writable.prototype._writev = null; -/** DES implementation **/ +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; -var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004]; -var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000]; -var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200]; -var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080]; -var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100]; -var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010]; -var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002]; -var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000]; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -/** - * Create necessary sub keys. - * - * @param key the 64-bit or 192-bit key. - * - * @return the expanded keys. - */ -function _createKeys(key) { - var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204], - pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101], - pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808], - pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000], - pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010], - pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420], - pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002], - pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800], - pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002], - pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408], - pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020], - pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200], - pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010], - pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105]; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - // how many iterations (1 for des, 3 for triple des) - // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys - var iterations = key.length() > 8 ? 3 : 1; + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. - // stores the return keys - var keys = []; - // now define the left shifts which need to be done - var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + if (!state.ending) endWritable(this, state, cb); + return this; +}; - var n = 0, tmp; - for(var j = 0; j < iterations; j++) { - var left = key.getInt32(); - var right = key.getInt32(); +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); - tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= tmp; - left ^= (tmp << 4); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} - tmp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= tmp; - right ^= (tmp << -16); +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; - tmp = ((left >>> 2) ^ right) & 0x33333333; - right ^= tmp; - left ^= (tmp << 2); + if (err) { + errorOrDestroy(stream, err); + } - tmp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= tmp; - right ^= (tmp << -16); + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} - tmp = ((left >>> 1) ^ right) & 0x55555555; - right ^= tmp; - left ^= (tmp << 1); +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} - tmp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= tmp; - right ^= (tmp << 8); +function finishMaybe(stream, state) { + var need = needFinish(state); - tmp = ((left >>> 1) ^ right) & 0x55555555; - right ^= tmp; - left ^= (tmp << 1); + if (need) { + prefinish(stream, state); - // right needs to be shifted and OR'd with last four bits of left - tmp = (left << 8) | ((right >>> 20) & 0x000000f0); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); - // left needs to be put upside down - left = ((right << 24) | ((right << 8) & 0xff0000) | - ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0)); - right = tmp; + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; - // now go through and perform these shifts on the left and right keys - for(var i = 0; i < shifts.length; ++i) { - //shift the keys either one or two bits to the left - if(shifts[i]) { - left = (left << 2) | (left >>> 26); - right = (right << 2) | (right >>> 26); - } else { - left = (left << 1) | (left >>> 27); - right = (right << 1) | (right >>> 27); + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } } - left &= -0xf; - right &= -0xf; - - // now apply PC-2, in such a way that E is easier when encrypting or - // decrypting this conversion will look like PC-2 except only the last 6 - // bits of each byte are used rather than 48 consecutive bits and the - // order of lines will be according to how the S selection functions will - // be applied: S2, S4, S6, S8, S1, S3, S5, S7 - var lefttmp = ( - pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | - pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] | - pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | - pc2bytes6[(left >>> 4) & 0xf]); - var righttmp = ( - pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | - pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] | - pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | - pc2bytes13[(right >>> 4) & 0xf]); - tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff; - keys[n++] = lefttmp ^ tmp; - keys[n++] = righttmp ^ (tmp << 16); } } - return keys; + return need; } -/** - * Updates a single block (1 byte) using DES. The update will either - * encrypt or decrypt the block. - * - * @param keys the expanded keys. - * @param input the input block (an array of 32-bit words). - * @param output the updated output block. - * @param decrypt true to decrypt the block, false to encrypt it. - */ -function _updateBlock(keys, input, output, decrypt) { - // set up loops for single or triple DES - var iterations = keys.length === 32 ? 3 : 9; - var looping; - if(iterations === 3) { - looping = decrypt ? [30, -2, -2] : [0, 32, 2]; - } else { - looping = (decrypt ? - [94, 62, -2, 32, 64, 2, 30, -2, -2] : - [0, 32, 2, 62, 30, -2, 64, 96, 2]); +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); } - var tmp; + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + - var left = input[0]; - var right = input[1]; + state.corkedRequestsFree.next = corkReq; +} - // first each 64 bit chunk of the message must be permuted according to IP - tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= tmp; - left ^= (tmp << 4); +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } - tmp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= tmp; - left ^= (tmp << 16); + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - tmp = ((right >>> 2) ^ left) & 0x33333333; - left ^= tmp; - right ^= (tmp << 2); - tmp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= tmp; - right ^= (tmp << 8); + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; - tmp = ((left >>> 1) ^ right) & 0x55555555; - right ^= tmp; - left ^= (tmp << 1); +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; - // rotate left 1 bit - left = ((left << 1) | (left >>> 31)); - right = ((right << 1) | (right >>> 31)); +/***/ }), - for(var j = 0; j < iterations; j += 3) { - var endloop = looping[j + 1]; - var loopinc = looping[j + 2]; +/***/ 3306: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // now go through and perform the encryption or decryption - for(var i = looping[j]; i != endloop; i += loopinc) { - var right1 = right ^ keys[i]; - var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; +"use strict"; - // passing these bytes through the S selection functions - tmp = left; - left = right; - right = tmp ^ ( - spfunction2[(right1 >>> 24) & 0x3f] | - spfunction4[(right1 >>> 16) & 0x3f] | - spfunction6[(right1 >>> 8) & 0x3f] | - spfunction8[right1 & 0x3f] | - spfunction1[(right2 >>> 24) & 0x3f] | - spfunction3[(right2 >>> 16) & 0x3f] | - spfunction5[(right2 >>> 8) & 0x3f] | - spfunction7[right2 & 0x3f]); - } - // unreverse left and right - tmp = left; - left = right; - right = tmp; - } - // rotate right 1 bit - left = ((left >>> 1) | (left << 31)); - right = ((right >>> 1) | (right << 31)); +var _Object$setPrototypeO; - // now perform IP-1, which is IP in the opposite direction - tmp = ((left >>> 1) ^ right) & 0x55555555; - right ^= tmp; - left ^= (tmp << 1); +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - tmp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= tmp; - right ^= (tmp << 8); +var finished = __nccwpck_require__(6080); - tmp = ((right >>> 2) ^ left) & 0x33333333; - left ^= tmp; - right ^= (tmp << 2); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); - tmp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= tmp; - left ^= (tmp << 16); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} - tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= tmp; - left ^= (tmp << 4); +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; - output[0] = left; - output[1] = right; + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } } -/** - * Deprecated. Instead, use: - * - * forge.cipher.createCipher('DES-', key); - * forge.cipher.createDecipher('DES-', key); - * - * Creates a deprecated DES cipher object. This object's mode will default to - * CBC (cipher-block-chaining). - * - * The key may be given as a binary-encoded string of bytes or a byte buffer. - * - * @param options the options to use. - * key the symmetric key to use (64 or 192 bits). - * output the buffer to write to. - * decrypt true for decryption, false for encryption. - * mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -function _createCipher(options) { - options = options || {}; - var mode = (options.mode || 'CBC').toUpperCase(); - var algorithm = 'DES-' + mode; +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} - var cipher; - if(options.decrypt) { - cipher = forge.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge.cipher.createCipher(algorithm, options.key); - } +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } - // backwards compatible start API - var start = cipher.start; - cipher.start = function(iv, options) { - // backwards compatibility: support second arg as output buffer - var output = null; - if(options instanceof forge.util.ByteBuffer) { - output = options; - options = {}; - } - options = options || {}; - options.output = output; - options.iv = iv; - start.call(cipher, options); + iter[kHandlePromise](resolve, reject); + }, reject); }; - - return cipher; } +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, -/***/ }), + next: function next() { + var _this = this; -/***/ 0: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; -/** - * JavaScript implementation of Ed25519. - * - * Copyright (c) 2017-2019 Digital Bazaar, Inc. - * - * This implementation is based on the most excellent TweetNaCl which is - * in the public domain. Many thanks to its contributors: - * - * https://github.com/dchest/tweetnacl-js - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7052); -__nccwpck_require__(7821); -__nccwpck_require__(9542); -__nccwpck_require__(8339); -var asn1Validator = __nccwpck_require__(9414); -var publicKeyValidator = asn1Validator.publicKeyValidator; -var privateKeyValidator = asn1Validator.privateKeyValidator; + if (error !== null) { + return Promise.reject(error); + } -if(typeof BigInteger === 'undefined') { - var BigInteger = forge.jsbn.BigInteger; -} + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } -var ByteBuffer = forge.util.ByteBuffer; -var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer; + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time -/* - * Ed25519 algorithms, see RFC 8032: - * https://tools.ietf.org/html/rfc8032 - */ -forge.pki = forge.pki || {}; -module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; -var ed25519 = forge.ed25519; -ed25519.constants = {}; -ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; -ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; -ed25519.constants.SEED_BYTE_LENGTH = 32; -ed25519.constants.SIGN_BYTE_LENGTH = 64; -ed25519.constants.HASH_BYTE_LENGTH = 64; + var lastPromise = this[kLastPromise]; + var promise; -ed25519.generateKeyPair = function(options) { - options = options || {}; - var seed = options.seed; - if(seed === undefined) { - // generate seed - seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); - } else if(typeof seed === 'string') { - if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { - throw new TypeError( - '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + - ' bytes in length.'); - } - } else if(!(seed instanceof Uint8Array)) { - throw new TypeError( - '"seed" must be a node.js Buffer, Uint8Array, or a binary string.'); - } + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); - seed = messageToNativeBuffer({message: seed, encoding: 'binary'}); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - for(var i = 0; i < 32; ++i) { - sk[i] = seed[i]; - } - crypto_sign_keypair(pk, sk); - return {publicKey: pk, privateKey: sk}; -}; + promise = new Promise(this[kHandlePromise]); + } -/** - * Converts a private key from a RFC8410 ASN.1 encoding. - * - * @param obj - The asn1 representation of a private key. - * - * @returns {Object} keyInfo - The key information. - * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes. - */ -ed25519.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); - if(!valid) { - var error = new Error('Invalid Key.'); - error.errors = errors; - throw error; - } - var oid = forge.asn1.derToOid(capture.privateKeyOid); - var ed25519Oid = forge.oids.EdDSA25519; - if(oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + - ed25519Oid + '".'); + this[kLastPromise] = promise; + return promise; } - var privateKey = capture.privateKey; - // manually extract the private key bytes from nested octet string, see FIXME: - // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542 - var privateKeyBytes = messageToNativeBuffer({ - message: forge.asn1.fromDer(privateKey).value, - encoding: 'binary' - }); - // TODO: RFC8410 specifies a format for encoding the public key bytes along - // with the private key bytes. `publicKeyBytes` can be returned in the - // future. https://tools.ietf.org/html/rfc8410#section-10.3 - return {privateKeyBytes: privateKeyBytes}; -}; +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; -/** - * Converts a public key from a RFC8410 ASN.1 encoding. - * - * @param obj - The asn1 representation of a public key. - * - * @return {Buffer|Uint8Array} - 32 public key bytes. - */ -ed25519.publicKeyFromAsn1 = function(obj) { - // get SubjectPublicKeyInfo - var capture = {}; - var errors = []; - var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); - if(!valid) { - var error = new Error('Invalid Key.'); - error.errors = errors; - throw error; - } - var oid = forge.asn1.derToOid(capture.publicKeyOid); - var ed25519Oid = forge.oids.EdDSA25519; - if(oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + - ed25519Oid + '".'); - } - var publicKeyBytes = capture.ed25519PublicKey; - if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new Error('Key length is invalid.'); - } - return messageToNativeBuffer({ - message: publicKeyBytes, - encoding: 'binary' - }); -}; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } -ed25519.publicKeyFromPrivateKey = function(options) { - options = options || {}; - var privateKey = messageToNativeBuffer({ - message: options.privateKey, encoding: 'binary' + resolve(createIterResult(undefined, true)); + }); }); - if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + - ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - } +}), _Object$setPrototypeO), AsyncIteratorPrototype); - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - for(var i = 0; i < pk.length; ++i) { - pk[i] = privateKey[32 + i]; - } - return pk; -}; +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; -ed25519.sign = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: 'binary' - }); - if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { - var keyPair = ed25519.generateKeyPair({seed: privateKey}); - privateKey = keyPair.privateKey; - } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + - ed25519.constants.SEED_BYTE_LENGTH + ' or ' + - ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - } + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); - var signedMsg = new NativeBuffer( - ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - crypto_sign(signedMsg, msg, msg.length, privateKey); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error - var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); - for(var i = 0; i < sig.length; ++i) { - sig[i] = signedMsg[i]; - } - return sig; -}; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } -ed25519.verify = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - if(options.signature === undefined) { - throw new TypeError( - '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + - 'ByteBuffer, or a binary string.'); - } - var sig = messageToNativeBuffer({ - message: options.signature, - encoding: 'binary' - }); - if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { - throw new TypeError( - '"options.signature" must have a byte length of ' + - ed25519.constants.SIGN_BYTE_LENGTH); - } - var publicKey = messageToNativeBuffer({ - message: options.publicKey, - encoding: 'binary' - }); - if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.publicKey" must have a byte length of ' + - ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - } + iterator[kError] = err; + return; + } - var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var i; - for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { - sm[i] = sig[i]; - } - for(i = 0; i < msg.length; ++i) { - sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; - } - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; }; -function messageToNativeBuffer(options) { - var message = options.message; - if(message instanceof Uint8Array || message instanceof NativeBuffer) { - return message; - } +module.exports = createReadableStreamAsyncIterator; - var encoding = options.encoding; - if(message === undefined) { - if(options.md) { - // TODO: more rigorous validation that `md` is a MessageDigest - message = options.md.digest().getBytes(); - encoding = 'binary'; - } else { - throw new TypeError('"options.message" or "options.md" not specified.'); - } - } +/***/ }), - if(typeof message === 'string' && !encoding) { - throw new TypeError('"options.encoding" must be "binary" or "utf8".'); - } +/***/ 6522: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if(typeof message === 'string') { - if(typeof Buffer !== 'undefined') { - return Buffer.from(message, encoding); - } - message = new ByteBuffer(message, encoding); - } else if(!(message instanceof ByteBuffer)) { - throw new TypeError( - '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + - 'ByteBuffer, or a string with "options.encoding" specifying its ' + - 'encoding.'); - } +"use strict"; - // convert to native buffer - var buffer = new NativeBuffer(message.length()); - for(var i = 0; i < buffer.length; ++i) { - buffer[i] = message.at(i); - } - return buffer; -} -var gf0 = gf(); -var gf1 = gf([1]); -var D = gf([ - 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, - 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]); -var D2 = gf([ - 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, - 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]); -var X = gf([ - 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, - 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]); -var Y = gf([ - 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, - 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]); -var L = new Float64Array([ - 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, - 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); -var I = gf([ - 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, - 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } -// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`, -// whichever is available, to improve performance -function sha512(msg, msgLen) { - // Note: `out` and `msg` are NativeBuffer - var md = forge.md.sha512.create(); - var buffer = new ByteBuffer(msg); - md.update(buffer.getBytes(msgLen), 'binary'); - var hash = md.digest().getBytes(); - if(typeof Buffer !== 'undefined') { - return Buffer.from(hash, 'binary'); - } - var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); - for(var i = 0; i < 64; ++i) { - out[i] = hash.charCodeAt(i); - } - return out; -} +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } -function crypto_sign_keypair(pk, sk) { - var p = [gf(), gf(), gf(), gf()]; - var i; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - scalarbase(p, d); - pack(pk, p); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - for(i = 0; i < 32; ++i) { - sk[i + 32] = pk[i]; - } - return 0; -} +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; +var _require = __nccwpck_require__(4300), + Buffer = _require.Buffer; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; +var _require2 = __nccwpck_require__(3837), + inspect = _require2.inspect; - var smlen = n + 64; - for(i = 0; i < n; ++i) { - sm[64 + i] = m[i]; - } - for(i = 0; i < 32; ++i) { - sm[32 + i] = d[32 + i]; - } +var custom = inspect && inspect.custom || 'inspect'; - var r = sha512(sm.subarray(32), n + 32); - reduce(r); - scalarbase(p, r); - pack(sm, p); +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} - for(i = 32; i < 64; ++i) { - sm[i] = sk[i]; - } - var h = sha512(sm, n + 64); - reduce(h); +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); - for(i = 32; i < 64; ++i) { - x[i] = 0; - } - for(i = 0; i < 32; ++i) { - x[i] = r[i]; + this.head = null; + this.tail = null; + this.length = 0; } - for(i = 0; i < 32; ++i) { - for(j = 0; j < 32; j++) { - x[i + j] += h[i] * d[j]; + + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; } - } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; - modL(sm.subarray(32), x); - return smlen; -} + while (p = p.next) { + ret += s + p.data; + } -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new NativeBuffer(32); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; - mlen = -1; - if(n < 64) { - return -1; - } + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } - if(unpackneg(q, pk)) { - return -1; - } + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. - for(i = 0; i < n; ++i) { - m[i] = sm[i]; - } - for(i = 0; i < 32; ++i) { - m[i + 32] = pk[i]; - } - var h = sha512(m, n); - reduce(h); - scalarmult(p, q, h); + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } - n -= 64; - if(crypto_verify_32(sm, 0, t, 0)) { - for(i = 0; i < n; ++i) { - m[i] = 0; + return ret; } - return -1; - } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. - for(i = 0; i < n; ++i) { - m[i] = sm[i + 64]; - } - mlen = n; - return mlen; -} + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; -function modL(r, x) { - var carry, i, j, k; - for(i = 63; i >= 32; --i) { - carry = 0; - for(j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for(j = 0; j < 32; ++j) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for(j = 0; j < 32; ++j) { - x[j] -= carry * L[j]; - } - for(i = 0; i < 32; ++i) { - x[i + 1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; -function reduce(r) { - var x = new Float64Array(64); - for(var i = 0; i < 64; ++i) { - x[i] = r[i]; - r[i] = 0; - } - modL(r, x); -} + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); + break; + } - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); + ++c; + } - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. -function cswap(p, q, b) { - for(var i = 0; i < 4; ++i) { - sel25519(p[i], q[i], b); - } -} + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for(i = 0; i < 16; ++i) { - t[i] = n[i]; - } - car25519(t); - car25519(t); - car25519(t); - for(j = 0; j < 2; ++j) { - m[0] = t[0] - 0xffed; - for(i = 1; i < 15; ++i) { - m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); - b = (m[15] >> 16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1 - b); - } - for (i = 0; i < 16; i++) { - o[2 * i] = t[i] & 0xff; - o[2 * i + 1] = t[i] >> 8; - } -} + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); + break; + } - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); + ++c; + } - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); - S(chk, r[0]); - M(chk, chk, den); - if(neq25519(chk, num)) { - M(r[0], r[0], I); - } + return BufferList; +}(); - S(chk, r[0]); - M(chk, chk, den); - if(neq25519(chk, num)) { - return -1; - } +/***/ }), - if(par25519(r[0]) === (p[31] >> 7)) { - Z(r[0], gf0, r[0]); - } +/***/ 7049: +/***/ ((module) => { - M(r[3], r[0], r[1]); - return 0; -} +"use strict"; + // undocumented cb() API, needed for core, not for public API -function unpack25519(o, n) { - var i; - for(i = 0; i < 16; ++i) { - o[i] = n[2 * i] + (n[2 * i + 1] << 8); - } - o[15] &= 0x7fff; -} +function destroy(err, cb) { + var _this = this; -function pow2523(o, i) { - var c = gf(); - var a; - for(a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for(a = 250; a >= 0; --a) { - S(c, c); - if(a !== 1) { - M(c, c, i); + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } } - } - for(a = 0; a < 16; ++a) { - o[a] = c[a]; - } -} -function neq25519(a, b) { - var c = new NativeBuffer(32); - var d = new NativeBuffer(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks -function crypto_verify_32(x, xi, y, yi) { - return vn(x, xi, y, yi, 32); -} -function vn(x, xi, y, yi, n) { - var i, d = 0; - for(i = 0; i < n; ++i) { - d |= x[xi + i] ^ y[yi + i]; - } - return (1 & ((d - 1) >>> 8)) - 1; -} + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well -function par25519(a) { - var d = new NativeBuffer(32); - pack25519(d, a); - return d[0] & 1; -} -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for(i = 255; i >= 0; --i) { - b = (s[(i / 8)|0] >> (i & 7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); + if (this._writableState) { + this._writableState.destroyed = true; } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + + return this; } -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); } -function set25519(r, a) { - var i; - for(i = 0; i < 16; i++) { - r[i] = a[i] | 0; - } +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); } -function inv25519(o, i) { - var c = gf(); - var a; - for(a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for(a = 253; a >= 0; --a) { - S(c, c); - if(a !== 2 && a !== 4) { - M(c, c, i); - } +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - for(a = 0; a < 16; ++a) { - o[a] = c[a]; + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; } } -function car25519(o) { - var i, v, c = 1; - for(i = 0; i < 16; ++i) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c - 1 + 37 * (c - 1); +function emitErrorNT(self, err) { + self.emit('error', err); } -function sel25519(p, q, b) { - var t, c = ~(b - 1); - for(var i = 0; i < 16; ++i) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } -function gf(init) { - var i, r = new Float64Array(16); - if(init) { - for(i = 0; i < init.length; ++i) { - r[i] = init[i]; +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; + +/***/ }), + +/***/ 6080: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + + +var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(7214)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - } - return r; -} -function A(o, a, b) { - for(var i = 0; i < 16; ++i) { - o[i] = a[i] + b[i]; - } + callback.apply(this, args); + }; } -function Z(o, a, b) { - for(var i = 0; i < 16; ++i) { - o[i] = a[i] - b[i]; - } -} +function noop() {} -function S(o, a) { - M(o, a, a); +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; } -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + var readableEnded = stream._readableState && stream._readableState.endEmitted; - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; -/***/ }), + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } -/***/ 9177: -/***/ ((module) => { + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; -/** - * Node.js module for Forge. - * - * @author Dave Longley - * - * Copyright 2011-2016 Digital Bazaar, Inc. - */ -module.exports = { - // default options - options: { - usePureJavaScript: false + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); } -}; + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} + +module.exports = eos; /***/ }), -/***/ 5104: +/***/ 9082: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Hash-based Message Authentication Code implementation. Requires a message - * digest object that can be obtained, for example, from forge.md.sha1 or - * forge.md.md5. - * - * @author Dave Longley - * - * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(6231); -__nccwpck_require__(8339); +"use strict"; -/* HMAC API */ -var hmac = module.exports = forge.hmac = forge.hmac || {}; -/** - * Creates an HMAC object that uses the given message digest object. - * - * @return an HMAC object. - */ -hmac.create = function() { - // the hmac key to use - var _key = null; +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - // the message digest to use - var _md = null; +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - // the inner padding - var _ipadding = null; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - // the outer padding - var _opadding = null; +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - // hmac context - var ctx = {}; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - /** - * Starts or restarts the HMAC with the given key and message digest. - * - * @param md the message digest to use, null to reuse the previous one, - * a string to use builtin 'sha1', 'md5', 'sha256'. - * @param key the key to use as a string, array of bytes, byte buffer, - * or null to reuse the previous key. - */ - ctx.start = function(md, key) { - if(md !== null) { - if(typeof md === 'string') { - // create builtin message digest - md = md.toLowerCase(); - if(md in forge.md.algorithms) { - _md = forge.md.algorithms[md].create(); +var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(7214)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE); + +function from(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); } else { - throw new Error('Unknown hash algorithm "' + md + '"'); + reading = false; } - } else { - // store message digest - _md = md; + } catch (err) { + readable.destroy(err); } + }); + return _next2.apply(this, arguments); + } + + return readable; +} + +module.exports = from; + +/***/ }), + +/***/ 6989: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + + +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} + +var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __nccwpck_require__(6080); + 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; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + 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 = pipeline; + +/***/ }), + +/***/ 9948: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(7214)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); + +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); } - if(key === null) { - // reuse previous key - key = _key; - } else { - if(typeof key === 'string') { - // convert string into byte buffer - key = forge.util.createBuffer(key); - } else if(forge.util.isArray(key)) { - // convert byte array into byte buffer - var tmp = key; - key = forge.util.createBuffer(); - for(var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } + return Math.floor(hwm); + } // Default value - // if key is longer than blocksize, hash it - var keylen = key.length(); - if(keylen > _md.blockLength) { - _md.start(); - _md.update(key.bytes()); - key = _md.digest(); - } - // mix key into inner and outer padding - // ipadding = [0x36 * blocksize] ^ key - // opadding = [0x5C * blocksize] ^ key - _ipadding = forge.util.createBuffer(); - _opadding = forge.util.createBuffer(); - keylen = key.length(); - for(var i = 0; i < keylen; ++i) { - var tmp = key.at(i); - _ipadding.putByte(0x36 ^ tmp); - _opadding.putByte(0x5C ^ tmp); - } + return state.objectMode ? 16 : 16 * 1024; +} - // if key is shorter than blocksize, add additional padding - if(keylen < _md.blockLength) { - var tmp = _md.blockLength - keylen; - for(var i = 0; i < tmp; ++i) { - _ipadding.putByte(0x36); - _opadding.putByte(0x5C); - } - } - _key = key; - _ipadding = _ipadding.bytes(); - _opadding = _opadding.bytes(); +module.exports = { + getHighWaterMark: getHighWaterMark +}; + +/***/ }), + +/***/ 2387: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(2781); + + +/***/ }), + +/***/ 1642: +/***/ ((module, exports, __nccwpck_require__) => { + +var Stream = __nccwpck_require__(2781); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = __nccwpck_require__(1433); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(6993); + exports.Duplex = __nccwpck_require__(1359); + exports.Transform = __nccwpck_require__(4415); + exports.PassThrough = __nccwpck_require__(1542); + exports.finished = __nccwpck_require__(6080); + exports.pipeline = __nccwpck_require__(6989); +} + + +/***/ }), + +/***/ 5118: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* eslint-disable node/no-deprecated-api */ + + + +var buffer = __nccwpck_require__(4300) +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 + } +} - // digest is done like so: hash(opadding | hash(ipadding | message)) +module.exports = safer - // prepare to do inner hash - // hash(ipadding | message) - _md.start(); - _md.update(_ipadding); - }; - /** - * Updates the HMAC with the given message bytes. - * - * @param bytes the bytes to update with. - */ - ctx.update = function(bytes) { - _md.update(bytes); - }; +/***/ }), - /** - * Produces the Message Authentication Code (MAC). - * - * @return a byte buffer containing the digest value. - */ - ctx.getMac = function() { - // digest is done like so: hash(opadding | hash(ipadding | message)) - // here we do the outer hashing - var inner = _md.digest().bytes(); - _md.start(); - _md.update(_opadding); - _md.update(inner); - return _md.digest(); - }; - // alias for getMac - ctx.digest = ctx.getMac; +/***/ 9798: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return ctx; -}; +var fs = __nccwpck_require__(7147); + +module.exports = function (filepath, split, encoding) { + split = typeof split !== 'undefined' ? split : "\n"; + encoding = typeof encoding !== 'undefined' ? encoding : "utf8"; + + var ca = []; + var chain = fs.readFileSync(filepath, encoding); + if(chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0){ + throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); + } + chain = chain.split(split); + var cert = []; + var _i, _len; + for (_i = 0, _len = chain.length; _i < _len; _i++) { + var line = chain[_i]; + if (!(line.length !== 0)) { + continue; + } + cert.push(line); + if (line.match(/-END CERTIFICATE-/)) { + ca.push(cert.join(split)); + cert = []; + } + } + return ca; +} /***/ }), -/***/ 7655: +/***/ 3204: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Node.js module for Forge. - * - * @author Dave Longley - * - * Copyright 2011-2016 Digital Bazaar, Inc. - */ -module.exports = __nccwpck_require__(9177); -__nccwpck_require__(7994); -__nccwpck_require__(1449); -__nccwpck_require__(9549); -__nccwpck_require__(7088); -__nccwpck_require__(7157); -__nccwpck_require__(0); -__nccwpck_require__(5104); -__nccwpck_require__(5173); -__nccwpck_require__(9994); -__nccwpck_require__(1145); -__nccwpck_require__(3339); -__nccwpck_require__(1611); -__nccwpck_require__(154); -__nccwpck_require__(7014); -__nccwpck_require__(466); -__nccwpck_require__(4829); -__nccwpck_require__(6924); -__nccwpck_require__(6861); -__nccwpck_require__(4467); -__nccwpck_require__(4376); -__nccwpck_require__(7821); -__nccwpck_require__(9965); -__nccwpck_require__(4280); -__nccwpck_require__(9167); -__nccwpck_require__(8339); +"use strict"; -/***/ }), +const { + Duplex: DuplexStream, + Readable: ReadableStream, + Writable: WritableStream, +} = __nccwpck_require__(2781); -/***/ 7052: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const { + CHANNEL_EXTENDED_DATATYPE: { STDERR }, +} = __nccwpck_require__(6832); +const { bufferSlice } = __nccwpck_require__(9475); -// Copyright (c) 2005 Tom Wu -// All Rights Reserved. -// See "LICENSE" for details. +const PACKET_SIZE = 32 * 1024; +const MAX_WINDOW = 2 * 1024 * 1024; +const WINDOW_THRESHOLD = MAX_WINDOW / 2; -// Basic JavaScript BN library - subset useful for RSA encryption. +class ClientStderr extends ReadableStream { + constructor(channel, streamOpts) { + super(streamOpts); -/* -Licensing (LICENSE) -------------------- + this._channel = channel; + } + _read(n) { + if (this._channel._waitChanDrain) { + this._channel._waitChanDrain = false; + if (this._channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(this._channel); + } + } +} -This software is covered under the following copyright: -*/ -/* - * Copyright (c) 2003-2005 Tom Wu - * All Rights Reserved. - * - * 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" AND WITHOUT WARRANTY OF ANY KIND, - * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY - * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - * - * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, - * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF - * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT - * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * In addition, the following condition applies: - * - * All redistributions must retain an intact copy of this copyright notice - * and disclaimer. - */ -/* -Address all questions regarding this license to: +class ServerStderr extends WritableStream { + constructor(channel) { + super({ highWaterMark: MAX_WINDOW }); - Tom Wu - tjw@cs.Stanford.EDU -*/ -var forge = __nccwpck_require__(9177); + this._channel = channel; + } -module.exports = forge.jsbn = forge.jsbn || {}; + _write(data, encoding, cb) { + const channel = this._channel; + const protocol = channel._client._protocol; + const outgoing = channel.outgoing; + const packetSize = outgoing.packetSize; + const id = outgoing.id; + let window = outgoing.window; + const len = data.length; + let p = 0; -// Bits per digit -var dbits; + if (outgoing.state !== 'open') + return; -// JavaScript engine analysis -var canary = 0xdeadbeefcafe; -var j_lm = ((canary&0xffffff)==0xefcafe); + while (len - p > 0 && window > 0) { + let sliceLen = len - p; + if (sliceLen > window) + sliceLen = window; + if (sliceLen > packetSize) + sliceLen = packetSize; -// (public) Constructor -function BigInteger(a,b,c) { - this.data = []; - if(a != null) - if("number" == typeof a) this.fromNumber(a,b,c); - else if(b == null && "string" != typeof a) this.fromString(a,256); - else this.fromString(a,b); -} -forge.jsbn.BigInteger = BigInteger; + if (p === 0 && sliceLen === len) + protocol.channelExtData(id, data, STDERR); + else + protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); -// return new, unset BigInteger -function nbi() { return new BigInteger(null); } + p += sliceLen; + window -= sliceLen; + } -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. + outgoing.window = window; -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) -function am1(i,x,w,j,c,n) { - while(--n >= 0) { - var v = x*this.data[i++]+w.data[j]+c; - c = Math.floor(v/0x4000000); - w.data[j++] = v&0x3ffffff; + if (len - p > 0) { + if (window === 0) + channel._waitWindow = true; + if (p > 0) + channel._chunkErr = bufferSlice(data, p, len); + else + channel._chunkErr = data; + channel._chunkcbErr = cb; + return; + } + + cb(); } - return c; } -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) -function am2(i,x,w,j,c,n) { - var xl = x&0x7fff, xh = x>>15; - while(--n >= 0) { - var l = this.data[i]&0x7fff; - var h = this.data[i++]>>15; - var m = xh*l+h*xl; - l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff); - c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); - w.data[j++] = l&0x3fffffff; + +class Channel extends DuplexStream { + constructor(client, info, opts) { + const streamOpts = { + highWaterMark: MAX_WINDOW, + allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), + emitClose: false, + }; + super(streamOpts); + this.allowHalfOpen = streamOpts.allowHalfOpen; + + const server = !!(opts && opts.server); + + this.server = server; + this.type = info.type; + this.subtype = undefined; + + /* + incoming and outgoing contain these properties: + { + id: undefined, + window: undefined, + packetSize: undefined, + state: 'closed' + } + */ + this.incoming = info.incoming; + this.outgoing = info.outgoing; + this._callbacks = []; + + this._client = client; + this._hasX11 = false; + this._exit = { + code: undefined, + signal: undefined, + dump: undefined, + desc: undefined, + }; + + this.stdin = this.stdout = this; + + if (server) + this.stderr = new ServerStderr(this); + else + this.stderr = new ClientStderr(this, streamOpts); + + // Outgoing data + this._waitWindow = false; // SSH-level backpressure + + // Incoming data + this._waitChanDrain = false; // Channel Readable side backpressure + + this._chunk = undefined; + this._chunkcb = undefined; + this._chunkErr = undefined; + this._chunkcbErr = undefined; + + this.on('finish', onFinish) + .on('prefinish', onFinish); // For node v0.11+ + + this.on('end', onEnd).on('close', onEnd); } - return c; -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. -function am3(i,x,w,j,c,n) { - var xl = x&0x3fff, xh = x>>14; - while(--n >= 0) { - var l = this.data[i]&0x3fff; - var h = this.data[i++]>>14; - var m = xh*l+h*xl; - l = xl*l+((m&0x3fff)<<14)+w.data[j]+c; - c = (l>>28)+(m>>14)+xh*h; - w.data[j++] = l&0xfffffff; + + _read(n) { + if (this._waitChanDrain) { + this._waitChanDrain = false; + if (this.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(this); + } } - return c; -} -// node.js (no browser) -if(typeof(navigator) === 'undefined') -{ - BigInteger.prototype.am = am3; - dbits = 28; -} else if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; -} else if(j_lm && (navigator.appName != "Netscape")) { - BigInteger.prototype.am = am1; - dbits = 26; -} else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; -} + _write(data, encoding, cb) { + const protocol = this._client._protocol; + const outgoing = this.outgoing; + const packetSize = outgoing.packetSize; + const id = outgoing.id; + let window = outgoing.window; + const len = data.length; + let p = 0; -BigInteger.prototype.DB = dbits; -BigInteger.prototype.DM = ((1< 0 && window > 0) { + let sliceLen = len - p; + if (sliceLen > window) + sliceLen = window; + if (sliceLen > packetSize) + sliceLen = packetSize; -// Digit conversions -var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; -var BI_RC = new Array(); -var rr,vv; -rr = "0".charCodeAt(0); -for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; -rr = "a".charCodeAt(0); -for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; -rr = "A".charCodeAt(0); -for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + if (p === 0 && sliceLen === len) + protocol.channelData(id, data); + else + protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); -function int2char(n) { return BI_RM.charAt(n); } -function intAt(s,i) { - var c = BI_RC[s.charCodeAt(i)]; - return (c==null)?-1:c; -} + p += sliceLen; + window -= sliceLen; + } -// (protected) copy this to r -function bnpCopyTo(r) { - for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i]; - r.t = this.t; - r.s = this.s; -} + outgoing.window = window; -// (protected) set from integer value x, -DV <= x < DV -function bnpFromInt(x) { - this.t = 1; - this.s = (x<0)?-1:0; - if(x > 0) this.data[0] = x; - else if(x < -1) this.data[0] = x+this.DV; - else this.t = 0; -} + if (len - p > 0) { + if (window === 0) + this._waitWindow = true; + if (p > 0) + this._chunk = bufferSlice(data, p, len); + else + this._chunk = data; + this._chunkcb = cb; + return; + } -// return bigint initialized to value -function nbv(i) { var r = nbi(); r.fromInt(i); return r; } + cb(); + } -// (protected) set from string and radix -function bnpFromString(s,b) { - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 256) k = 8; // byte array - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else { this.fromRadix(s,b); return; } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while(--i >= 0) { - var x = (k==8)?s[i]&0xff:intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-") mi = true; - continue; + eof() { + if (this.outgoing.state === 'open') { + this.outgoing.state = 'eof'; + this._client._protocol.channelEOF(this.outgoing.id); } - mi = false; - if(sh == 0) - this.data[this.t++] = x; - else if(sh+k > this.DB) { - this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); - } else - this.data[this.t-1] |= x<= this.DB) sh -= this.DB; } - if(k == 8 && (s[0]&0x80) != 0) { - this.s = -1; - if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t; -} + exit(statusOrSignal, coreDumped, msg) { + if (!this.server) + throw new Error('Server-only method called in client mode'); -// (public) return string representation in given radix -function bnToString(b) { - if(this.s < 0) return "-"+this.negate().toString(b); - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else return this.toRadix(b); - var km = (1< 0) { - if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); } - while(i >= 0) { - if(p < k) { - d = (this.data[i]&((1<>(p+=this.DB-k); + if (this.type === 'session' + && this.writable + && this.outgoing.state === 'open') { + if (typeof statusOrSignal === 'number') { + this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); } else { - d = (this.data[i]>>(p-=k))&km; - if(p <= 0) { p += this.DB; --i; } + this._client._protocol.exitSignal(this.outgoing.id, + statusOrSignal, + coreDumped, + msg); } - if(d > 0) m = true; - if(m) r += int2char(d); } } - return m?r:"0"; -} - -// (public) -this -function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } - -// (public) |this| -function bnAbs() { return (this.s<0)?this.negate():this; } -// (public) return + if this > a, - if this < a, 0 if equal -function bnCompareTo(a) { - var r = this.s-a.s; - if(r != 0) return r; - var i = this.t; - r = i-a.t; - if(r != 0) return (this.s<0)?-r:r; - while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r; - return 0; } -// returns bit length of the integer x -function nbits(x) { - var r = 1, t; - if((t=x>>>16) != 0) { x = t; r += 16; } - if((t=x>>8) != 0) { x = t; r += 8; } - if((t=x>>4) != 0) { x = t; r += 4; } - if((t=x>>2) != 0) { x = t; r += 2; } - if((t=x>>1) != 0) { x = t; r += 1; } - return r; +function onFinish() { + this.eof(); + if (this.server || !this.allowHalfOpen) + this.close(); + this.writable = false; } -// (public) return the number of bits in "this" -function bnBitLength() { - if(this.t <= 0) return 0; - return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM)); +function onEnd() { + this.readable = false; } -// (protected) r = this << n*DB -function bnpDLShiftTo(n,r) { - var i; - for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i]; - for(i = n-1; i >= 0; --i) r.data[i] = 0; - r.t = this.t+n; - r.s = this.s; +function windowAdjust(self) { + if (self.outgoing.state === 'closed') + return; + const amt = MAX_WINDOW - self.incoming.window; + if (amt <= 0) + return; + self.incoming.window += amt; + self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); } -// (protected) r = this >> n*DB -function bnpDRShiftTo(n,r) { - for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i]; - r.t = Math.max(this.t-n,0); - r.s = this.s; -} +module.exports = { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD, +}; -// (protected) r = this << n -function bnpLShiftTo(n,r) { - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<= 0; --i) { - r.data[i+ds+1] = (this.data[i]>>cbs)|c; - c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0; - r.data[ds] = c; - r.t = this.t+ds+1; - r.s = this.s; - r.clamp(); -} -// (protected) r = this >> n -function bnpRShiftTo(n,r) { - r.s = this.s; - var ds = Math.floor(n/this.DB); - if(ds >= this.t) { r.t = 0; return; } - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<>bs; - for(var i = ds+1; i < this.t; ++i) { - r.data[i-ds-1] |= (this.data[i]&bm)<>bs; - } - if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB; - } - if(a.t < this.t) { - c -= a.s; - while(i < this.t) { - c += this.data[i]; - r.data[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while(i < a.t) { - c -= a.data[i]; - r.data[i++] = c&this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = (c<0)?-1:0; - if(c < -1) r.data[i++] = this.DV+c; - else if(c > 0) r.data[i++] = c; - r.t = i; - r.clamp(); +/***/ 6119: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { Socket } = __nccwpck_require__(1808); +const { Duplex } = __nccwpck_require__(2781); +const { resolve } = __nccwpck_require__(1017); +const { readFile } = __nccwpck_require__(7147); +const { execFile, spawn } = __nccwpck_require__(2081); + +const { isParsedKey, parseKey } = __nccwpck_require__(2218); + +const { + makeBufferParser, + readUInt32BE, + writeUInt32BE, + writeUInt32LE, +} = __nccwpck_require__(9475); + +function once(cb) { + let called = false; + return (...args) => { + if (called) + return; + called = true; + cb(...args); + }; } -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. -function bnpMultiplyTo(a,r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i+y.t; - while(--i >= 0) r.data[i] = 0; - for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t); - r.s = 0; - r.clamp(); - if(this.s != a.s) BigInteger.ZERO.subTo(r,r); +function concat(buf1, buf2) { + const combined = Buffer.allocUnsafe(buf1.length + buf2.length); + buf1.copy(combined, 0); + buf2.copy(combined, buf1.length); + return combined; } -// (protected) r = this^2, r != this (HAC 14.16) -function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2*x.t; - while(--i >= 0) r.data[i] = 0; - for(i = 0; i < x.t-1; ++i) { - var c = x.am(i,x.data[i],r,2*i,0,1); - if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { - r.data[i+x.t] -= x.DV; - r.data[i+x.t+1] = 1; - } +function noop() {} + +const EMPTY_BUF = Buffer.alloc(0); + +const binaryParser = makeBufferParser(); + +class BaseAgent { + getIdentities(cb) { + cb(new Error('Missing getIdentities() implementation')); + } + sign(pubKey, data, options, cb) { + if (typeof options === 'function') + cb = options; + cb(new Error('Missing sign() implementation')); } - if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1); - r.s = 0; - r.clamp(); } -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. -function bnpDivRemTo(m,q,r) { - var pm = m.abs(); - if(pm.t <= 0) return; - var pt = this.abs(); - if(pt.t < pm.t) { - if(q != null) q.fromInt(0); - if(r != null) this.copyTo(r); - return; - } - if(r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus - if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } - var ys = y.t; - var y0 = y.data[ys-1]; - if(y0 == 0) return; - var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0); - var d1 = this.FV/yt, d2 = (1<= 0) { - r.data[r.t++] = 1; - r.subTo(t,r); +class OpenSSHAgent extends BaseAgent { + constructor(socketPath) { + super(); + this.socketPath = socketPath; } - BigInteger.ONE.dlShiftTo(ys,t); - t.subTo(y,y); // "negative" y so we can replace sub with am later - while(y.t < ys) y.data[y.t++] = 0; - while(--j >= 0) { - // Estimate quotient digit - var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2); - if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out - y.dlShiftTo(j,t); - r.subTo(t,r); - while(r.data[i] < --qd) r.subTo(t,r); + + getStream(cb) { + cb = once(cb); + const sock = new Socket(); + sock.on('connect', () => { + cb(null, sock); + }); + sock.on('close', onFail) + .on('end', onFail) + .on('error', onFail); + sock.connect(this.socketPath); + + function onFail() { + try { + sock.destroy(); + } catch {} + + cb(new Error('Failed to connect to agent')); } } - if(q != null) { - r.drShiftTo(ys,q); - if(ts != ms) BigInteger.ZERO.subTo(q,q); + + getIdentities(cb) { + cb = once(cb); + this.getStream((err, stream) => { + function onFail(err) { + if (stream) { + try { + stream.destroy(); + } catch {} + } + if (!err) + err = new Error('Failed to retrieve identities from agent'); + cb(err); + } + + if (err) + return onFail(err); + + const protocol = new AgentProtocol(true); + protocol.on('error', onFail); + protocol.pipe(stream).pipe(protocol); + + stream.on('close', onFail) + .on('end', onFail) + .on('error', onFail); + + protocol.getIdentities((err, keys) => { + if (err) + return onFail(err); + try { + stream.destroy(); + } catch {} + cb(null, keys); + }); + }); } - r.t = ys; - r.clamp(); - if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder - if(ts < 0) BigInteger.ZERO.subTo(r,r); -} -// (public) this mod a -function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a,null,r); - if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); - return r; -} + sign(pubKey, data, options, cb) { + if (typeof options === 'function') { + cb = options; + options = undefined; + } else if (typeof options !== 'object' || options === null) { + options = undefined; + } -// Modular reduction using "classic" algorithm -function Classic(m) { this.m = m; } -function cConvert(x) { - if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; -} -function cRevert(x) { return x; } -function cReduce(x) { x.divRemTo(this.m,null,x); } -function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } -function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + cb = once(cb); + this.getStream((err, stream) => { + function onFail(err) { + if (stream) { + try { + stream.destroy(); + } catch {} + } + if (!err) + err = new Error('Failed to sign data with agent'); + cb(err); + } -Classic.prototype.convert = cConvert; -Classic.prototype.revert = cRevert; -Classic.prototype.reduce = cReduce; -Classic.prototype.mulTo = cMulTo; -Classic.prototype.sqrTo = cSqrTo; + if (err) + return onFail(err); -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. -function bnpInvDigit() { - if(this.t < 1) return 0; - var x = this.data[0]; - if((x&1) == 0) return 0; - var y = x&3; // y == 1/x mod 2^2 - y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 - y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 - y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y>0)?this.DV-y:-y; -} + const protocol = new AgentProtocol(true); + protocol.on('error', onFail); + protocol.pipe(stream).pipe(protocol); -// Montgomery reduction -function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp&0x7fff; - this.mph = this.mp>>15; - this.um = (1<<(m.DB-15))-1; - this.mt2 = 2*m.t; -} + stream.on('close', onFail) + .on('end', onFail) + .on('error', onFail); -// xR mod m -function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t,r); - r.divRemTo(this.m,null,r); - if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); - return r; -} + protocol.sign(pubKey, data, options, (err, sig) => { + if (err) + return onFail(err); -// x/R mod m -function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; -} + try { + stream.destroy(); + } catch {} -// x = x/R mod m (HAC 14.32) -function montReduce(x) { - while(x.t <= this.mt2) // pad x so am has enough room later - x.data[x.t++] = 0; - for(var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x.data[i]*mp mod DV - var j = x.data[i]&0x7fff; - var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM; - // use am to combine the multiply-shift-add into one call - j = i+this.m.t; - x.data[j] += this.m.am(0,u0,x,i,0,this.m.t); - // propagate carry - while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; } + cb(null, sig); + }); + }); } - x.clamp(); - x.drShiftTo(this.m.t,x); - if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } -// r = "x^2/R mod m"; x != r -function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } +const PageantAgent = (() => { + const RET_ERR_BADARGS = 10; + const RET_ERR_UNAVAILABLE = 11; + const RET_ERR_NOMAP = 12; + const RET_ERR_BINSTDIN = 13; + const RET_ERR_BINSTDOUT = 14; + const RET_ERR_BADLEN = 15; -// r = "xy/R mod m"; x,y != r -function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + const EXEPATH = __nccwpck_require__.ab + "pagent.exe"; + const ERROR = { + [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), + [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), + [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), + [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), + [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), + [RET_ERR_BADLEN]: + new Error('pagent.exe did not get expected input payload'), + }; -Montgomery.prototype.convert = montConvert; -Montgomery.prototype.revert = montRevert; -Montgomery.prototype.reduce = montReduce; -Montgomery.prototype.mulTo = montMulTo; -Montgomery.prototype.sqrTo = montSqrTo; + function destroy(stream) { + stream.buffer = null; + if (stream.proc) { + stream.proc.kill(); + stream.proc = undefined; + } + } -// (protected) true iff this is even -function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; } + class PageantSocket extends Duplex { + constructor() { + super(); + this.proc = undefined; + this.buffer = null; + } + _read(n) {} + _write(data, encoding, cb) { + if (this.buffer === null) { + this.buffer = data; + } else { + const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); + this.buffer.copy(newBuffer, 0); + data.copy(newBuffer, this.buffer.length); + this.buffer = newBuffer; + } + // Wait for at least all length bytes + if (this.buffer.length < 4) + return cb(); -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) -function bnpExp(e,z) { - if(e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; - g.copyTo(r); - while(--i >= 0) { - z.sqrTo(r,r2); - if((e&(1< 0) z.mulTo(r2,g,r); - else { var t = r; r = r2; r2 = t; } - } - return z.revert(r); -} + const len = readUInt32BE(this.buffer, 0); + // Make sure we have a full message before querying pageant + if ((this.buffer.length - 4) < len) + return cb(); -// (public) this^e % m, 0 <= e < 2^32 -function bnModPowInt(e,m) { - var z; - if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); - return this.exp(e,z); -} + data = this.buffer.slice(0, 4 + len); + if (this.buffer.length > (4 + len)) + return cb(new Error('Unexpected multiple agent requests')); + this.buffer = null; -// protected -BigInteger.prototype.copyTo = bnpCopyTo; -BigInteger.prototype.fromInt = bnpFromInt; -BigInteger.prototype.fromString = bnpFromString; -BigInteger.prototype.clamp = bnpClamp; -BigInteger.prototype.dlShiftTo = bnpDLShiftTo; -BigInteger.prototype.drShiftTo = bnpDRShiftTo; -BigInteger.prototype.lShiftTo = bnpLShiftTo; -BigInteger.prototype.rShiftTo = bnpRShiftTo; -BigInteger.prototype.subTo = bnpSubTo; -BigInteger.prototype.multiplyTo = bnpMultiplyTo; -BigInteger.prototype.squareTo = bnpSquareTo; -BigInteger.prototype.divRemTo = bnpDivRemTo; -BigInteger.prototype.invDigit = bnpInvDigit; -BigInteger.prototype.isEven = bnpIsEven; -BigInteger.prototype.exp = bnpExp; + let error; + const proc = this.proc = spawn(__nccwpck_require__.ab + "pagent.exe", [ data.length ]); + proc.stdout.on('data', (data) => { + this.push(data); + }); + proc.on('error', (err) => { + error = err; + cb(error); + }); + proc.on('close', (code) => { + this.proc = undefined; + if (!error) { + if (error = ERROR[code]) + return cb(error); + cb(); + } + }); + proc.stdin.end(data); + } + _final(cb) { + destroy(this); + cb(); + } + _destroy(err, cb) { + destroy(this); + cb(); + } + } -// public -BigInteger.prototype.toString = bnToString; -BigInteger.prototype.negate = bnNegate; -BigInteger.prototype.abs = bnAbs; -BigInteger.prototype.compareTo = bnCompareTo; -BigInteger.prototype.bitLength = bnBitLength; -BigInteger.prototype.mod = bnMod; -BigInteger.prototype.modPowInt = bnModPowInt; + return class PageantAgent extends OpenSSHAgent { + getStream(cb) { + cb(null, new PageantSocket()); + } + }; +})(); -// "constants" -BigInteger.ZERO = nbv(0); -BigInteger.ONE = nbv(1); +const CygwinAgent = (() => { + const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; -// jsbn2 lib + return class CygwinAgent extends OpenSSHAgent { + getStream(cb) { + cb = once(cb); -//Copyright (c) 2005-2009 Tom Wu -//All Rights Reserved. -//See "LICENSE" for details (See jsbn.js for LICENSE). + // The cygwin ssh-agent connection process looks like this: + // 1. Read the "socket" as a file to get the underlying TCP port and a + // special "secret" that must be sent to the TCP server. + // 2. Connect to the server listening on localhost at the TCP port. + // 3. Send the "secret" to the server. + // 4. The server sends back the same "secret". + // 5. Send three 32-bit integer values of zero. This is ordinarily the + // pid, uid, and gid of this process, but cygwin will actually + // send us the correct values as a response. + // 6. The server sends back the pid, uid, gid. + // 7. Disconnect. + // 8. Repeat steps 2-6, except send the received pid, uid, and gid in + // step 5 instead of zeroes. + // 9. Connection is ready to be used. -//Extended JavaScript BN functions, required for RSA private ops. + let socketPath = this.socketPath; + let triedCygpath = false; + readFile(socketPath, function readCygsocket(err, data) { + if (err) { + if (triedCygpath) + return cb(new Error('Invalid cygwin unix socket path')); -//Version 1.1: new BigInteger("0", 10) returns "proper" zero + // Try using `cygpath` to convert a possible *nix-style path to the + // real Windows path before giving up ... + execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { + if (err || stdout.length === 0) + return cb(new Error('Invalid cygwin unix socket path')); -//(public) -function bnClone() { var r = nbi(); this.copyTo(r); return r; } + triedCygpath = true; + socketPath = stdout.toString().replace(/[\r\n]/g, ''); + readFile(socketPath, readCygsocket); + }); + return; + } -//(public) return value as integer -function bnIntValue() { -if(this.s < 0) { - if(this.t == 1) return this.data[0]-this.DV; - else if(this.t == 0) return -1; -} else if(this.t == 1) return this.data[0]; -else if(this.t == 0) return 0; -// assumes 16 < DB < 32 -return ((this.data[1]&((1<<(32-this.DB))-1))<>24; } + let state; + let bc = 0; + let isRetrying = false; + const inBuf = []; + let sock; -//(public) return value as short (assumes DB>=16) -function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; } + // Use 0 for pid, uid, and gid to ensure we get an error and also + // a valid uid and gid from cygwin so that we don't have to figure it + // out ourselves + let credsBuf = Buffer.alloc(12); -//(protected) return x s.t. r^x < DV -function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } + // Parse cygwin unix socket file contents + const port = parseInt(m[1], 10); + const secret = m[2].replace(/-/g, ''); + const secretBuf = Buffer.allocUnsafe(16); + for (let i = 0, j = 0; j < 32; ++i, j += 2) + secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); -//(public) 0 if this == 0, 1 if this > 0 -function bnSigNum() { -if(this.s < 0) return -1; -else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; -else return 1; -} + // Convert to host order (always LE for Windows) + for (let i = 0; i < 16; i += 4) + writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); -//(protected) convert to radix string -function bnpToRadix(b) { -if(b == null) b = 10; -if(this.signum() == 0 || b < 2 || b > 36) return "0"; -var cs = this.chunkSize(b); -var a = Math.pow(b,cs); -var d = nbv(a), y = nbi(), z = nbi(), r = ""; -this.divRemTo(d,y,z); -while(y.signum() > 0) { - r = (a+z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d,y,z); -} -return z.intValue().toString(b) + r; -} + tryConnect(); -//(protected) convert from radix string -function bnpFromRadix(s,b) { -this.fromInt(0); -if(b == null) b = 10; -var cs = this.chunkSize(b); -var d = Math.pow(b,cs), mi = false, j = 0, w = 0; -for(var i = 0; i < s.length; ++i) { - var x = intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b*w+x; - if(++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w,0); - j = 0; - w = 0; - } -} -if(j > 0) { - this.dMultiply(Math.pow(b,j)); - this.dAddOffset(w,0); -} -if(mi) BigInteger.ZERO.subTo(this,this); -} + function _onconnect() { + bc = 0; + state = 'secret'; + sock.write(secretBuf); + } -//(protected) alternate constructor -function bnpFromNumber(a,b,c) { -if("number" == typeof b) { - // new BigInteger(int,int,RNG) - if(a < 2) this.fromInt(1); - else { - this.fromNumber(a,c); - if(!this.testBit(a-1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); - if(this.isEven()) this.dAddOffset(1,0); // force odd - while(!this.isProbablePrime(b)) { - this.dAddOffset(2,0); - if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); - } - } -} else { - // new BigInteger(int,RNG) - var x = new Array(), t = a&7; - x.length = (a>>3)+1; - b.nextBytes(x); - if(t > 0) x[0] &= ((1< 0) { - if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p) - r[k++] = d|(this.s<<(this.DB-p)); - while(i >= 0) { - if(p < 8) { - d = (this.data[i]&((1<>(p+=this.DB-8); - } else { - d = (this.data[i]>>(p-=8))&0xff; - if(p <= 0) { p += this.DB; --i; } - } - if((d&0x80) != 0) d |= -256; - if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; - if(k > 0 || d != this.s) r[k++] = d; - } -} -return r; -} + if (state === 'secret') { + // The secret we sent is echoed back to us by cygwin, not sure of + // the reason for that, but we ignore it nonetheless ... + if (bc === 16) { + bc = 0; + state = 'creds'; + sock.write(credsBuf); + } + return; + } -function bnEquals(a) { return(this.compareTo(a)==0); } -function bnMin(a) { return(this.compareTo(a)<0)?this:a; } -function bnMax(a) { return(this.compareTo(a)>0)?this:a; } + if (state === 'creds') { + // If this is the first attempt, make sure to gather the valid + // uid and gid for our next attempt + if (!isRetrying) + inBuf.push(data); -//(protected) r = this op a (bitwise) -function bnpBitwiseTo(a,op,r) { -var i, f, m = Math.min(a.t,this.t); -for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]); -if(a.t < this.t) { - f = a.s&this.DM; - for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f); - r.t = this.t; -} else { - f = this.s&this.DM; - for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]); - r.t = a.t; -} -r.s = op(this.s,a.s); -r.clamp(); -} + if (bc === 12) { + sock.removeListener('connect', _onconnect); + sock.removeListener('data', _ondata); + sock.removeListener('error', onFail); + sock.removeListener('end', onFail); + sock.removeListener('close', onFail); -//(public) this & a -function op_and(x,y) { return x&y; } -function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } + if (isRetrying) + return cb(null, sock); -//(public) this | a -function op_or(x,y) { return x|y; } -function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } + isRetrying = true; + credsBuf = Buffer.concat(inBuf); + writeUInt32LE(credsBuf, process.pid, 0); + sock.on('error', () => {}); + sock.destroy(); -//(public) this ^ a -function op_xor(x,y) { return x^y; } -function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } + tryConnect(); + } + } + } -//(public) this & ~a -function op_andnot(x,y) { return x&~y; } -function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } + function onFail() { + cb(new Error('Problem negotiating cygwin unix socket security')); + } -//(public) ~this -function bnNot() { -var r = nbi(); -for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i]; -r.t = this.t; -r.s = ~this.s; -return r; -} + function tryConnect() { + sock = new Socket(); + sock.on('connect', _onconnect); + sock.on('data', _ondata); + sock.on('error', onFail); + sock.on('end', onFail); + sock.on('close', onFail); + sock.connect(port); + } + }); + } + }; +})(); -//(public) this << n -function bnShiftLeft(n) { -var r = nbi(); -if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); -return r; +// Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes +// being interchangeable +const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; +function createAgent(path) { + if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { + return (path === 'pageant' + ? new PageantAgent() + : new CygwinAgent(path)); + } + return new OpenSSHAgent(path); } -//(public) this >> n -function bnShiftRight(n) { -var r = nbi(); -if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); -return r; -} +const AgentProtocol = (() => { + // Client->Server messages + const SSH_AGENTC_REQUEST_IDENTITIES = 11; + const SSH_AGENTC_SIGN_REQUEST = 13; + // const SSH_AGENTC_ADD_IDENTITY = 17; + // const SSH_AGENTC_REMOVE_IDENTITY = 18; + // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; + // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; + // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; + // const SSH_AGENTC_LOCK = 22; + // const SSH_AGENTC_UNLOCK = 23; + // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; + // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; + // const SSH_AGENTC_EXTENSION = 27; + // Server->Client messages + const SSH_AGENT_FAILURE = 5; + // const SSH_AGENT_SUCCESS = 6; + const SSH_AGENT_IDENTITIES_ANSWER = 12; + const SSH_AGENT_SIGN_RESPONSE = 14; + // const SSH_AGENT_EXTENSION_FAILURE = 28; -//return index of lowest 1-bit in x, x < 2^31 -function lbit(x) { -if(x == 0) return -1; -var r = 0; -if((x&0xffff) == 0) { x >>= 16; r += 16; } -if((x&0xff) == 0) { x >>= 8; r += 8; } -if((x&0xf) == 0) { x >>= 4; r += 4; } -if((x&3) == 0) { x >>= 2; r += 2; } -if((x&1) == 0) ++r; -return r; -} + // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; + // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; + // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; -//(public) returns index of lowest 1-bit (or -1 if none) -function bnGetLowestSetBit() { -for(var i = 0; i < this.t; ++i) - if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]); -if(this.s < 0) return this.t*this.DB; -return -1; -} + const SSH_AGENT_RSA_SHA2_256 = (1 << 1); + const SSH_AGENT_RSA_SHA2_512 = (1 << 2); -//return number of 1 bits in x -function cbit(x) { -var r = 0; -while(x != 0) { x &= x-1; ++r; } -return r; -} + const ROLE_CLIENT = 0; + const ROLE_SERVER = 1; -//(public) return number of set bits -function bnBitCount() { -var r = 0, x = this.s&this.DM; -for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x); -return r; -} + // Ensures that responses get sent back in the same order the requests were + // received + function processResponses(protocol) { + let ret; + while (protocol[SYM_REQS].length) { + const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; + if (nextResponse === undefined) + break; -//(public) true iff nth bit is set -function bnTestBit(n) { -var j = Math.floor(n/this.DB); -if(j >= this.t) return(this.s!=0); -return((this.data[j]&(1<<(n%this.DB)))!=0); -} + protocol[SYM_REQS].shift(); + ret = protocol.push(nextResponse); + } + return ret; + } -//(protected) this op (1< { + if (!protocol[SYM_ENDED]) + protocol.emit('end'); + if (!protocol[SYM_CLOSED]) + protocol.emit('close'); + }); + } -//(public) this ^ (1<>= this.DB; -} -if(a.t < this.t) { - c += a.s; - while(i < this.t) { - c += this.data[i]; - r.data[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; -} else { - c += this.s; - while(i < a.t) { - c += a.data[i]; - r.data[i++] = c&this.DM; - c >>= this.DB; - } - c += a.s; -} -r.s = (c<0)?-1:0; -if(c > 0) r.data[i++] = c; -else if(c < -1) r.data[i++] = this.DV+c; -r.t = i; -r.clamp(); -} + function onEnd() { + this[SYM_ENDED] = true; + } -//(public) this + a -function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } + const SYM_REQS = Symbol('Requests'); + const SYM_MODE = Symbol('Agent Protocol Role'); + const SYM_BUFFER = Symbol('Agent Protocol Buffer'); + const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); + const SYM_CLOSED = Symbol('Agent Protocol Closed'); + const SYM_ENDED = Symbol('Agent Protocol Ended'); + // Implementation based on: + // https://tools.ietf.org/html/draft-miller-ssh-agent-04 + return class AgentProtocol extends Duplex { + /* + Notes: + - `constraint` type consists of: + byte constraint_type + byte[] constraint_data + where `constraint_type` is one of: + * SSH_AGENT_CONSTRAIN_LIFETIME + - `constraint_data` consists of: + uint32 seconds + * SSH_AGENT_CONSTRAIN_CONFIRM + - `constraint_data` N/A + * SSH_AGENT_CONSTRAIN_EXTENSION + - `constraint_data` consists of: + string extension name + byte[] extension-specific details + */ -//(public) this - a -function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } + constructor(isClient) { + super({ autoDestroy: true, emitClose: false }); + this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); + this[SYM_REQS] = []; + this[SYM_BUFFER] = null; + this[SYM_MSGLEN] = -1; + this.once('end', onEnd); + this.once('close', onClose); + } -//(public) this * a -function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } + _read(n) {} -//(public) this / a -function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } + _write(data, encoding, cb) { + /* + Messages are of the format: + uint32 message length + byte message type + byte[message length - 1] message contents + */ + if (this[SYM_BUFFER] === null) + this[SYM_BUFFER] = data; + else + this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); -//(public) this % a -function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + let buffer = this[SYM_BUFFER]; + let bufferLen = buffer.length; -//(public) [this/a,this%a] -function bnDivideAndRemainder(a) { -var q = nbi(), r = nbi(); -this.divRemTo(a,q,r); -return new Array(q,r); -} + let p = 0; + while (p < bufferLen) { + // Wait for length + type + if (bufferLen < 5) + break; -//(protected) this *= n, this >= 0, 1 < n < DV -function bnpDMultiply(n) { -this.data[this.t] = this.am(0,n-1,this,0,0,this.t); -++this.t; -this.clamp(); -} + if (this[SYM_MSGLEN] === -1) + this[SYM_MSGLEN] = readUInt32BE(buffer, p); -//(protected) this += n << w words, this >= 0 -function bnpDAddOffset(n,w) { -if(n == 0) return; -while(this.t <= w) this.data[this.t++] = 0; -this.data[w] += n; -while(this.data[w] >= this.DV) { - this.data[w] -= this.DV; - if(++w >= this.t) this.data[this.t++] = 0; - ++this.data[w]; -} -} + // Check if we have the entire message + if (bufferLen < (4 + this[SYM_MSGLEN])) + break; -//A "null" reducer -function NullExp() {} -function nNop(x) { return x; } -function nMulTo(x,y,r) { x.multiplyTo(y,r); } -function nSqrTo(x,r) { x.squareTo(r); } + const msgType = buffer[p += 4]; + ++p; -NullExp.prototype.convert = nNop; -NullExp.prototype.revert = nNop; -NullExp.prototype.mulTo = nMulTo; -NullExp.prototype.sqrTo = nSqrTo; + if (this[SYM_MODE] === ROLE_CLIENT) { + if (this[SYM_REQS].length === 0) + return cb(new Error('Received unexpected message from server')); -//(public) this^e -function bnPow(e) { return this.exp(e,new NullExp()); } + const req = this[SYM_REQS].shift(); -//(protected) r = lower n words of "this * a", a.t <= n -//"this" should be the larger one if appropriate. -function bnpMultiplyLowerTo(a,n,r) { -var i = Math.min(this.t+a.t,n); -r.s = 0; // assumes a,this >= 0 -r.t = i; -while(i > 0) r.data[--i] = 0; -var j; -for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t); -for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i); -r.clamp(); -} + switch (msgType) { + case SSH_AGENT_FAILURE: + req.cb(new Error('Agent responded with failure')); + break; + case SSH_AGENT_IDENTITIES_ANSWER: { + if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) + return cb(new Error('Agent responded with wrong message type')); -//(protected) r = "this * a" without lower n words, n > 0 -//"this" should be the larger one if appropriate. -function bnpMultiplyUpperTo(a,n,r) { ---n; -var i = r.t = this.t+a.t-n; -r.s = 0; // assumes a,this >= 0 -while(--i >= 0) r.data[i] = 0; -for(i = Math.max(n-this.t,0); i < a.t; ++i) - r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n); -r.clamp(); -r.drShiftTo(1,r); -} + /* + byte SSH_AGENT_IDENTITIES_ANSWER + uint32 nkeys -//Barrett modular reduction -function Barrett(m) { -// setup Barrett -this.r2 = nbi(); -this.q3 = nbi(); -BigInteger.ONE.dlShiftTo(2*m.t,this.r2); -this.mu = this.r2.divide(m); -this.m = m; -} + where `nkeys` is 0 or more of: + string key blob + string comment + */ -function barrettConvert(x) { -if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); -else if(x.compareTo(this.m) < 0) return x; -else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } -} + binaryParser.init(buffer, p); -function barrettRevert(x) { return x; } + const numKeys = binaryParser.readUInt32BE(); -//x = x mod m (HAC 14.42) -function barrettReduce(x) { -x.drShiftTo(this.m.t-1,this.r2); -if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } -this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); -this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); -while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); -x.subTo(this.r2,x); -while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); -} + if (numKeys === undefined) { + binaryParser.clear(); + return cb(new Error('Malformed agent response')); + } -//r = x^2 mod m; x != r -function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + const keys = []; + for (let i = 0; i < numKeys; ++i) { + let pubKey = binaryParser.readString(); + if (pubKey === undefined) { + binaryParser.clear(); + return cb(new Error('Malformed agent response')); + } -//r = x*y mod m; x,y != r -function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + const comment = binaryParser.readString(true); + if (comment === undefined) { + binaryParser.clear(); + return cb(new Error('Malformed agent response')); + } -Barrett.prototype.convert = barrettConvert; -Barrett.prototype.revert = barrettRevert; -Barrett.prototype.reduce = barrettReduce; -Barrett.prototype.mulTo = barrettMulTo; -Barrett.prototype.sqrTo = barrettSqrTo; + pubKey = parseKey(pubKey); + // We continue parsing the packet if we encounter an error + // in case the error is due to the key being an unsupported + // type + if (pubKey instanceof Error) + continue; -//(public) this^e % m (HAC 14.85) -function bnModPow(e,m) { -var i = e.bitLength(), k, r = nbv(1), z; -if(i <= 0) return r; -else if(i < 18) k = 1; -else if(i < 48) k = 3; -else if(i < 144) k = 4; -else if(i < 768) k = 5; -else k = 6; -if(i < 8) - z = new Classic(m); -else if(m.isEven()) - z = new Barrett(m); -else - z = new Montgomery(m); + pubKey.comment = pubKey.comment || comment; -// precomputation -var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { - var g2 = nbi(); - z.sqrTo(g[1],g2); - while(n <= km) { - g[n] = nbi(); - z.mulTo(g2,g[n-2],g[n]); - n += 2; - } -} + keys.push(pubKey); + } + p = binaryParser.pos(); + binaryParser.clear(); -var j = e.t-1, w, is1 = true, r2 = nbi(), t; -i = nbits(e.data[j])-1; -while(j >= 0) { - if(i >= k1) w = (e.data[j]>>(i-k1))&km; - else { - w = (e.data[j]&((1<<(i+1))-1))<<(k1-i); - if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1); - } + req.cb(null, keys); + break; + } + case SSH_AGENT_SIGN_RESPONSE: { + if (req.type !== SSH_AGENTC_SIGN_REQUEST) + return cb(new Error('Agent responded with wrong message type')); - n = k; - while((w&1) == 0) { w >>= 1; --n; } - if((i -= n) < 0) { i += this.DB; --j; } - if(is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } else { - while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } - if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } - z.mulTo(r2,g[w],r); - } + /* + byte SSH_AGENT_SIGN_RESPONSE + string signature + */ - while(j >= 0 && (e.data[j]&(1< 0) { - x.rShiftTo(g,x); - y.rShiftTo(g,y); -} -while(x.signum() > 0) { - if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); - if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); - if(x.compareTo(y) >= 0) { - x.subTo(y,x); - x.rShiftTo(1,x); - } else { - y.subTo(x,y); - y.rShiftTo(1,y); - } -} -if(g > 0) y.lShiftTo(g,y); -return y; -} + if (signature === undefined) + return cb(new Error('Malformed agent response')); -//(protected) this % n, n < 2^26 -function bnpModInt(n) { -if(n <= 0) return 0; -var d = this.DV%n, r = (this.s<0)?n-1:0; -if(this.t > 0) - if(d == 0) r = this.data[0]%n; - else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n; -return r; -} + // We strip the algorithm from OpenSSH's output and assume it's + // using the algorithm we specified. This makes it easier on + // custom Agent implementations so they don't have to construct + // the correct binary format for a (OpenSSH-style) signature. -//(public) 1/this % m (HAC 14.61) -function bnModInverse(m) { -var ac = m.isEven(); -if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; -var u = m.clone(), v = this.clone(); -var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); -while(u.signum() != 0) { - while(u.isEven()) { - u.rShiftTo(1,u); - if(ac) { - if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } - a.rShiftTo(1,a); - } else if(!b.isEven()) b.subTo(m,b); - b.rShiftTo(1,b); - } - while(v.isEven()) { - v.rShiftTo(1,v); - if(ac) { - if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } - c.rShiftTo(1,c); - } else if(!d.isEven()) d.subTo(m,d); - d.rShiftTo(1,d); - } - if(u.compareTo(v) >= 0) { - u.subTo(v,u); - if(ac) a.subTo(c,a); - b.subTo(d,b); - } else { - v.subTo(u,v); - if(ac) c.subTo(a,c); - d.subTo(b,d); - } -} -if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; -if(d.compareTo(m) >= 0) return d.subtract(m); -if(d.signum() < 0) d.addTo(m,d); else return d; -if(d.signum() < 0) return d.add(m); else return d; -} + // TODO: verify signature type based on key and options used + // during initial sign request + binaryParser.init(signature, 0); + binaryParser.readString(true); + signature = binaryParser.readString(); + binaryParser.clear(); -var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; -var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + if (signature === undefined) + return cb(new Error('Malformed OpenSSH signature format')); -//(public) test primality with certainty >= 1-.5^t -function bnIsProbablePrime(t) { -var i, x = this.abs(); -if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) { - for(i = 0; i < lowprimes.length; ++i) - if(x.data[0] == lowprimes[i]) return true; - return false; -} -if(x.isEven()) return false; -i = 1; -while(i < lowprimes.length) { - var m = lowprimes[i], j = i+1; - while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while(i < j) if(m%lowprimes[i++] == 0) return false; -} -return x.millerRabin(t); -} + req.cb(null, signature); + break; + } + default: + return cb( + new Error('Agent responded with unsupported message type') + ); + } + } else { + switch (msgType) { + case SSH_AGENTC_REQUEST_IDENTITIES: { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + /* + byte SSH_AGENTC_REQUEST_IDENTITIES + */ + this.emit('identities', req); + break; + } + case SSH_AGENTC_SIGN_REQUEST: { + /* + byte SSH_AGENTC_SIGN_REQUEST + string key_blob + string data + uint32 flags + */ + binaryParser.init(buffer, p); + let pubKey = binaryParser.readString(); + const data = binaryParser.readString(); + const flagsVal = binaryParser.readUInt32BE(); + p = binaryParser.pos(); + binaryParser.clear(); + if (flagsVal === undefined) { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + return this.failureReply(req); + } -//(protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { -var n1 = this.subtract(BigInteger.ONE); -var k = n1.getLowestSetBit(); -if(k <= 0) return false; -var r = n1.shiftRight(k); -var prng = bnGetPrng(); -var a; -for(var i = 0; i < t; ++i) { - // select witness 'a' at random from between 1 and n1 - do { - a = new BigInteger(this.bitLength(), prng); - } - while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); - var y = a.modPow(r,this); - if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while(j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2,this); - if(y.compareTo(BigInteger.ONE) == 0) return false; - } - if(y.compareTo(n1) != 0) return false; - } -} -return true; -} + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + return this.failureReply(req); + } -// get pseudo random number generator -function bnGetPrng() { - // create prng with api that matches BigInteger secure random - return { - // x is an array to fill with bytes - nextBytes: function(x) { - for(var i = 0; i < x.length; ++i) { - x[i] = Math.floor(Math.random() * 0x0100); - } - } - }; -} + const flags = { + hash: undefined, + }; + let ctx; + if (pubKey.type === 'ssh-rsa') { + if (flagsVal & SSH_AGENT_RSA_SHA2_256) { + ctx = 'rsa-sha2-256'; + flags.hash = 'sha256'; + } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { + ctx = 'rsa-sha2-512'; + flags.hash = 'sha512'; + } + } + if (ctx === undefined) + ctx = pubKey.type; -//protected -BigInteger.prototype.chunkSize = bnpChunkSize; -BigInteger.prototype.toRadix = bnpToRadix; -BigInteger.prototype.fromRadix = bnpFromRadix; -BigInteger.prototype.fromNumber = bnpFromNumber; -BigInteger.prototype.bitwiseTo = bnpBitwiseTo; -BigInteger.prototype.changeBit = bnpChangeBit; -BigInteger.prototype.addTo = bnpAddTo; -BigInteger.prototype.dMultiply = bnpDMultiply; -BigInteger.prototype.dAddOffset = bnpDAddOffset; -BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; -BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; -BigInteger.prototype.modInt = bnpModInt; -BigInteger.prototype.millerRabin = bnpMillerRabin; + const req = new AgentInboundRequest(msgType, ctx); + this[SYM_REQS].push(req); -//public -BigInteger.prototype.clone = bnClone; -BigInteger.prototype.intValue = bnIntValue; -BigInteger.prototype.byteValue = bnByteValue; -BigInteger.prototype.shortValue = bnShortValue; -BigInteger.prototype.signum = bnSigNum; -BigInteger.prototype.toByteArray = bnToByteArray; -BigInteger.prototype.equals = bnEquals; -BigInteger.prototype.min = bnMin; -BigInteger.prototype.max = bnMax; -BigInteger.prototype.and = bnAnd; -BigInteger.prototype.or = bnOr; -BigInteger.prototype.xor = bnXor; -BigInteger.prototype.andNot = bnAndNot; -BigInteger.prototype.not = bnNot; -BigInteger.prototype.shiftLeft = bnShiftLeft; -BigInteger.prototype.shiftRight = bnShiftRight; -BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; -BigInteger.prototype.bitCount = bnBitCount; -BigInteger.prototype.testBit = bnTestBit; -BigInteger.prototype.setBit = bnSetBit; -BigInteger.prototype.clearBit = bnClearBit; -BigInteger.prototype.flipBit = bnFlipBit; -BigInteger.prototype.add = bnAdd; -BigInteger.prototype.subtract = bnSubtract; -BigInteger.prototype.multiply = bnMultiply; -BigInteger.prototype.divide = bnDivide; -BigInteger.prototype.remainder = bnRemainder; -BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; -BigInteger.prototype.modPow = bnModPow; -BigInteger.prototype.modInverse = bnModInverse; -BigInteger.prototype.pow = bnPow; -BigInteger.prototype.gcd = bnGCD; -BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + this.emit('sign', req, pubKey, data, flags); + break; + } + default: { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + this.failureReply(req); + } + } + } -//BigInteger interfaces not implemented in jsbn: + // Get ready for next message + this[SYM_MSGLEN] = -1; + if (p === bufferLen) { + // Nothing left to process for now + this[SYM_BUFFER] = null; + break; + } else { + this[SYM_BUFFER] = buffer = buffer.slice(p); + bufferLen = buffer.length; + p = 0; + } + } -//BigInteger(int signum, byte[] magnitude) -//double doubleValue() -//float floatValue() -//int hashCode() -//long longValue() -//static BigInteger valueOf(long val) + cb(); + } + _destroy(err, cb) { + cleanup(this); + cb(); + } -/***/ }), + _final(cb) { + cleanup(this); + cb(); + } -/***/ 5173: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Client->Server messages ================================================= + sign(pubKey, data, options, cb) { + if (this[SYM_MODE] !== ROLE_CLIENT) + throw new Error('Client-only method called with server role'); -/** - * Javascript implementation of RSA-KEM. - * - * @author Lautaro Cozzani Rodriguez - * @author Dave Longley - * - * Copyright (c) 2014 Lautaro Cozzani - * Copyright (c) 2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); -__nccwpck_require__(7821); -__nccwpck_require__(7052); + if (typeof options === 'function') { + cb = options; + options = undefined; + } else if (typeof options !== 'object' || options === null) { + options = undefined; + } -module.exports = forge.kem = forge.kem || {}; + let flags = 0; -var BigInteger = forge.jsbn.BigInteger; + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error('Invalid public key argument'); -/** - * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2. - */ -forge.kem.rsa = {}; + if (pubKey.type === 'ssh-rsa' && options) { + switch (options.hash) { + case 'sha256': + flags = SSH_AGENT_RSA_SHA2_256; + break; + case 'sha512': + flags = SSH_AGENT_RSA_SHA2_512; + break; + } + } + pubKey = pubKey.getPublicSSH(); -/** - * Creates an RSA KEM API object for generating a secret asymmetric key. - * - * The symmetric key may be generated via a call to 'encrypt', which will - * produce a ciphertext to be transmitted to the recipient and a key to be - * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which - * will produce the same secret key for the recipient to use to decrypt a - * message that was encrypted with the secret key. - * - * @param kdf the KDF API to use (eg: new forge.kem.kdf1()). - * @param options the options to use. - * [prng] a custom crypto-secure pseudo-random number generator to use, - * that must define "getBytesSync". - */ -forge.kem.rsa.create = function(kdf, options) { - options = options || {}; - var prng = options.prng || forge.random; + /* + byte SSH_AGENTC_SIGN_REQUEST + string key_blob + string data + uint32 flags + */ + const type = SSH_AGENTC_SIGN_REQUEST; + const keyLen = pubKey.length; + const dataLen = data.length; + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); - var kem = {}; + writeUInt32BE(buf, buf.length - 4, p); - /** - * Generates a secret key and its encapsulation. - * - * @param publicKey the RSA public key to encrypt with. - * @param keyLength the length, in bytes, of the secret key to generate. - * - * @return an object with: - * encapsulation: the ciphertext for generating the secret key, as a - * binary-encoded string of bytes. - * key: the secret key to use for encrypting a message. - */ - kem.encrypt = function(publicKey, keyLength) { - // generate a random r where 1 < r < n - var byteLength = Math.ceil(publicKey.n.bitLength() / 8); - var r; - do { - r = new BigInteger( - forge.util.bytesToHex(prng.getBytesSync(byteLength)), - 16).mod(publicKey.n); - } while(r.compareTo(BigInteger.ONE) <= 0); + buf[p += 4] = type; - // prepend r with zeros - r = forge.util.hexToBytes(r.toString(16)); - var zeros = byteLength - r.length; - if(zeros > 0) { - r = forge.util.fillString(String.fromCharCode(0), zeros) + r; - } + writeUInt32BE(buf, keyLen, ++p); + pubKey.copy(buf, p += 4); - // encrypt the random - var encapsulation = publicKey.encrypt(r, 'NONE'); + writeUInt32BE(buf, dataLen, p += keyLen); + data.copy(buf, p += 4); - // generate the secret key - var key = kdf.generate(r, keyLength); + writeUInt32BE(buf, flags, p += dataLen); - return {encapsulation: encapsulation, key: key}; - }; + if (typeof cb !== 'function') + cb = noop; - /** - * Decrypts an encapsulated secret key. - * - * @param privateKey the RSA private key to decrypt with. - * @param encapsulation the ciphertext for generating the secret key, as - * a binary-encoded string of bytes. - * @param keyLength the length, in bytes, of the secret key to generate. - * - * @return the secret key as a binary-encoded string of bytes. - */ - kem.decrypt = function(privateKey, encapsulation, keyLength) { - // decrypt the encapsulation and generate the secret key - var r = privateKey.decrypt(encapsulation, 'NONE'); - return kdf.generate(r, keyLength); - }; + this[SYM_REQS].push({ type, cb }); - return kem; -}; + return this.push(buf); + } + getIdentities(cb) { + if (this[SYM_MODE] !== ROLE_CLIENT) + throw new Error('Client-only method called with server role'); -// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API? + /* + byte SSH_AGENTC_REQUEST_IDENTITIES + */ + const type = SSH_AGENTC_REQUEST_IDENTITIES; -/** - * Creates a key derivation API object that implements KDF1 per ISO 18033-2. - * - * @param md the hash API to use. - * @param [digestLength] an optional digest length that must be positive and - * less than or equal to md.digestLength. - * - * @return a KDF1 API object. - */ -forge.kem.kdf1 = function(md, digestLength) { - _createKDF(this, md, 0, digestLength || md.digestLength); -}; + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1); -/** - * Creates a key derivation API object that implements KDF2 per ISO 18033-2. - * - * @param md the hash API to use. - * @param [digestLength] an optional digest length that must be positive and - * less than or equal to md.digestLength. - * - * @return a KDF2 API object. - */ -forge.kem.kdf2 = function(md, digestLength) { - _createKDF(this, md, 1, digestLength || md.digestLength); -}; + writeUInt32BE(buf, buf.length - 4, p); -/** - * Creates a KDF1 or KDF2 API object. - * - * @param md the hash API to use. - * @param counterStart the starting index for the counter. - * @param digestLength the digest length to use. - * - * @return the KDF API object. - */ -function _createKDF(kdf, md, counterStart, digestLength) { - /** - * Generate a key of the specified length. - * - * @param x the binary-encoded byte string to generate a key from. - * @param length the number of bytes to generate (the size of the key). - * - * @return the key as a binary-encoded string. - */ - kdf.generate = function(x, length) { - var key = new forge.util.ByteBuffer(); + buf[p += 4] = type; - // run counter from counterStart to ceil(length / Hash.len) - var k = Math.ceil(length / digestLength) + counterStart; + if (typeof cb !== 'function') + cb = noop; - var c = new forge.util.ByteBuffer(); - for(var i = counterStart; i < k; ++i) { - // I2OSP(i, 4): convert counter to an octet string of 4 octets - c.putInt32(i); + this[SYM_REQS].push({ type, cb }); - // digest 'x' and the counter and add the result to the key - md.start(); - md.update(x + c.getBytes()); - var hash = md.digest(); - key.putBytes(hash.getBytes(digestLength)); + return this.push(buf); } - // truncate to the correct key length - key.truncate(key.length() - length); - return key.getBytes(); - }; -} + // Server->Client messages ================================================= + failureReply(req) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error('Server-only method called with client role'); + if (!(req instanceof AgentInboundRequest)) + throw new Error('Wrong request argument'); -/***/ }), + if (req.hasResponded()) + return true; -/***/ 9994: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1); -/** - * Cross-browser support for logging in a web application. - * - * @author David I. Lehn - * - * Copyright (c) 2008-2013 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); + writeUInt32BE(buf, buf.length - 4, p); -/* LOG API */ -module.exports = forge.log = forge.log || {}; + buf[p += 4] = SSH_AGENT_FAILURE; -/** - * Application logging system. - * - * Each logger level available as it's own function of the form: - * forge.log.level(category, args...) - * The category is an arbitrary string, and the args are the same as - * Firebug's console.log API. By default the call will be output as: - * 'LEVEL [category] , args[1], ...' - * This enables proper % formatting via the first argument. - * Each category is enabled by default but can be enabled or disabled with - * the setCategoryEnabled() function. - */ -// list of known levels -forge.log.levels = [ - 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max']; -// info on the levels indexed by name: -// index: level index -// name: uppercased display name -var sLevelInfo = {}; -// list of loggers -var sLoggers = []; -/** - * Standard console logger. If no console support is enabled this will - * remain null. Check before using. - */ -var sConsoleLogger = null; + return respond(this, req, buf); + } + getIdentitiesReply(req, keys) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error('Server-only method called with client role'); -// logger flags -/** - * Lock the level at the current value. Used in cases where user config may - * set the level such that only critical messages are seen but more verbose - * messages are needed for debugging or other purposes. - */ -forge.log.LEVEL_LOCKED = (1 << 1); -/** - * Always call log function. By default, the logging system will check the - * message level against logger.level before calling the log function. This - * flag allows the function to do its own check. - */ -forge.log.NO_LEVEL_CHECK = (1 << 2); -/** - * Perform message interpolation with the passed arguments. "%" style - * fields in log messages will be replaced by arguments as needed. Some - * loggers, such as Firebug, may do this automatically. The original log - * message will be available as 'message' and the interpolated version will - * be available as 'fullMessage'. - */ -forge.log.INTERPOLATE = (1 << 3); + if (!(req instanceof AgentInboundRequest)) + throw new Error('Wrong request argument'); -// setup each log level -for(var i = 0; i < forge.log.levels.length; ++i) { - var level = forge.log.levels[i]; - sLevelInfo[level] = { - index: i, - name: level.toUpperCase() - }; -} + if (req.hasResponded()) + return true; -/** - * Message logger. Will dispatch a message to registered loggers as needed. - * - * @param message message object - */ -forge.log.logMessage = function(message) { - var messageLevelIndex = sLevelInfo[message.level].index; - for(var i = 0; i < sLoggers.length; ++i) { - var logger = sLoggers[i]; - if(logger.flags & forge.log.NO_LEVEL_CHECK) { - logger.f(message); - } else { - // get logger level - var loggerLevelIndex = sLevelInfo[logger.level].index; - // check level - if(messageLevelIndex <= loggerLevelIndex) { - // message critical enough, call logger - logger.f(logger, message); - } - } - } -}; + /* + byte SSH_AGENT_IDENTITIES_ANSWER + uint32 nkeys -/** - * Sets the 'standard' key on a message object to: - * "LEVEL [category] " + message - * - * @param message a message log object - */ -forge.log.prepareStandard = function(message) { - if(!('standard' in message)) { - message.standard = - sLevelInfo[message.level].name + - //' ' + +message.timestamp + - ' [' + message.category + '] ' + - message.message; - } -}; + where `nkeys` is 0 or more of: + string key blob + string comment + */ -/** - * Sets the 'full' key on a message object to the original message - * interpolated via % formatting with the message arguments. - * - * @param message a message log object. - */ -forge.log.prepareFull = function(message) { - if(!('full' in message)) { - // copy args and insert message at the front - var args = [message.message]; - args = args.concat([] || 0); - // format the message - message.full = forge.util.format.apply(this, args); - } -}; + if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) + throw new Error('Invalid response to request'); -/** - * Applies both preparseStandard() and prepareFull() to a message object and - * store result in 'standardFull'. - * - * @param message a message log object. - */ -forge.log.prepareStandardFull = function(message) { - if(!('standardFull' in message)) { - // FIXME implement 'standardFull' logging - forge.log.prepareStandard(message); - message.standardFull = message.standard; - } -}; + if (!Array.isArray(keys)) + throw new Error('Keys argument must be an array'); -// create log level functions -if(true) { - // levels for which we want functions - var levels = ['error', 'warning', 'info', 'debug', 'verbose']; - for(var i = 0; i < levels.length; ++i) { - // wrap in a function to ensure proper level var is passed - (function(level) { - // create function for this level - forge.log[level] = function(category, message/*, args...*/) { - // convert arguments to real array, remove category and message - var args = Array.prototype.slice.call(arguments).slice(2); - // create message object - // Note: interpolation and standard formatting is done lazily - var msg = { - timestamp: new Date(), - level: level, - category: category, - message: message, - 'arguments': args - /*standard*/ - /*full*/ - /*fullMessage*/ - }; - // process this message - forge.log.logMessage(msg); - }; - })(levels[i]); - } -} + let totalKeysLen = 4; // Include `nkeys` size + + const newKeys = []; + for (let i = 0; i < keys.length; ++i) { + const entry = keys[i]; + if (typeof entry !== 'object' || entry === null) + throw new Error(`Invalid key entry: ${entry}`); + + let pubKey; + let comment; + if (isParsedKey(entry)) { + pubKey = entry; + } else if (isParsedKey(entry.pubKey)) { + pubKey = entry.pubKey; + } else { + if (typeof entry.pubKey !== 'object' || entry.pubKey === null) + continue; + ({ pubKey, comment } = entry.pubKey); + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + continue; // TODO: add debug output + } + comment = pubKey.comment || comment; + pubKey = pubKey.getPublicSSH(); -/** - * Creates a new logger with specified custom logging function. - * - * The logging function has a signature of: - * function(logger, message) - * logger: current logger - * message: object: - * level: level id - * category: category - * message: string message - * arguments: Array of extra arguments - * fullMessage: interpolated message and arguments if INTERPOLATE flag set - * - * @param logFunction a logging function which takes a log message object - * as a parameter. - * - * @return a logger object. - */ -forge.log.makeLogger = function(logFunction) { - var logger = { - flags: 0, - f: logFunction - }; - forge.log.setLevel(logger, 'none'); - return logger; -}; + totalKeysLen += 4 + pubKey.length; -/** - * Sets the current log level on a logger. - * - * @param logger the target logger. - * @param level the new maximum log level as a string. - * - * @return true if set, false if not. - */ -forge.log.setLevel = function(logger, level) { - var rval = false; - if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) { - for(var i = 0; i < forge.log.levels.length; ++i) { - var aValidLevel = forge.log.levels[i]; - if(level == aValidLevel) { - // set level - logger.level = level; - rval = true; - break; - } - } - } + if (comment && typeof comment === 'string') + comment = Buffer.from(comment); + else if (!Buffer.isBuffer(comment)) + comment = EMPTY_BUF; - return rval; -}; + totalKeysLen += 4 + comment.length; -/** - * Locks the log level at its current value. - * - * @param logger the target logger. - * @param lock boolean lock value, default to true. - */ -forge.log.lock = function(logger, lock) { - if(typeof lock === 'undefined' || lock) { - logger.flags |= forge.log.LEVEL_LOCKED; - } else { - logger.flags &= ~forge.log.LEVEL_LOCKED; - } -}; + newKeys.push({ pubKey, comment }); + } -/** - * Adds a logger. - * - * @param logger the logger object. - */ -forge.log.addLogger = function(logger) { - sLoggers.push(logger); -}; + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); -// setup the console logger if possible, else create fake console.log -if(typeof(console) !== 'undefined' && 'log' in console) { - var logger; - if(console.error && console.warn && console.info && console.debug) { - // looks like Firebug-style logging is available - // level handlers map - var levelHandlers = { - error: console.error, - warning: console.warn, - info: console.info, - debug: console.debug, - verbose: console.debug - }; - var f = function(logger, message) { - forge.log.prepareStandard(message); - var handler = levelHandlers[message.level]; - // prepend standard message and concat args - var args = [message.standard]; - args = args.concat(message['arguments'].slice()); - // apply to low-level console function - handler.apply(console, args); - }; - logger = forge.log.makeLogger(f); - } else { - // only appear to have basic console.log - var f = function(logger, message) { - forge.log.prepareStandardFull(message); - console.log(message.standardFull); - }; - logger = forge.log.makeLogger(f); - } - forge.log.setLevel(logger, 'debug'); - forge.log.addLogger(logger); - sConsoleLogger = logger; -} else { - // define fake console.log to avoid potential script errors on - // browsers that do not have console logging - console = { - log: function() {} - }; -} + writeUInt32BE(buf, buf.length - 4, p); -/* - * Check for logging control query vars in current URL. - * - * console.level= - * Set's the console log level by name. Useful to override defaults and - * allow more verbose logging before a user config is loaded. - * - * console.lock= - * Lock the console log level at whatever level it is set at. This is run - * after console.level is processed. Useful to force a level of verbosity - * that could otherwise be limited by a user config. - */ -if(sConsoleLogger !== null && - typeof window !== 'undefined' && window.location -) { - var query = new URL(window.location.href).searchParams; - if(query.has('console.level')) { - // set with last value - forge.log.setLevel( - sConsoleLogger, query.get('console.level').slice(-1)[0]); - } - if(query.has('console.lock')) { - // set with last value - var lock = query.get('console.lock').slice(-1)[0]; - if(lock == 'true') { - forge.log.lock(sConsoleLogger); - } - } -} + buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; -// provide public access to console logger -forge.log.consoleLogger = sConsoleLogger; + writeUInt32BE(buf, newKeys.length, ++p); + p += 4; + for (let i = 0; i < newKeys.length; ++i) { + const { pubKey, comment } = newKeys[i]; + writeUInt32BE(buf, pubKey.length, p); + pubKey.copy(buf, p += 4); -/***/ }), + writeUInt32BE(buf, comment.length, p += pubKey.length); + p += 4; + if (comment.length) { + comment.copy(buf, p); + p += comment.length; + } + } -/***/ 1145: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return respond(this, req, buf); + } + signReply(req, signature) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error('Server-only method called with client role'); -/** - * Node.js module for all known Forge message digests. - * - * @author Dave Longley - * - * Copyright 2011-2017 Digital Bazaar, Inc. - */ -module.exports = __nccwpck_require__(6231); + if (!(req instanceof AgentInboundRequest)) + throw new Error('Wrong request argument'); -__nccwpck_require__(6594); -__nccwpck_require__(279); -__nccwpck_require__(4086); -__nccwpck_require__(9542); + if (req.hasResponded()) + return true; + /* + byte SSH_AGENT_SIGN_RESPONSE + string signature + */ -/***/ }), + if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) + throw new Error('Invalid response to request'); -/***/ 6231: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!Buffer.isBuffer(signature)) + throw new Error('Signature argument must be a Buffer'); -/** - * Node.js module for Forge message digests. - * - * @author Dave Longley - * - * Copyright 2011-2017 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); + if (signature.length === 0) + throw new Error('Signature argument must be non-empty'); -module.exports = forge.md = forge.md || {}; -forge.md.algorithms = forge.md.algorithms || {}; + /* + OpenSSH agent signatures are encoded as: + string signature format identifier (as specified by the + public key/certificate format) + byte[n] signature blob in format specific encoding. + - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 + types + */ -/***/ }), + let p = 0; + const sigFormat = req.getContext(); + const sigFormatLen = Buffer.byteLength(sigFormat); + const buf = Buffer.allocUnsafe( + 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length + ); -/***/ 6594: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + writeUInt32BE(buf, buf.length - 4, p); -/** - * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(6231); -__nccwpck_require__(8339); + buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; -var md5 = module.exports = forge.md5 = forge.md5 || {}; -forge.md.md5 = forge.md.algorithms.md5 = md5; + writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); + writeUInt32BE(buf, sigFormatLen, p += 4); + buf.utf8Write(sigFormat, p += 4, sigFormatLen); + writeUInt32BE(buf, signature.length, p += sigFormatLen); + signature.copy(buf, p += 4); -/** - * Creates an MD5 message digest object. - * - * @return a message digest object. - */ -md5.create = function() { - // do initialization as necessary - if(!_initialized) { - _init(); + return respond(this, req, buf); + } + }; +})(); + +const SYM_AGENT = Symbol('Agent'); +const SYM_AGENT_KEYS = Symbol('Agent Keys'); +const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); +const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); +class AgentContext { + constructor(agent) { + if (typeof agent === 'string') + agent = createAgent(agent); + else if (!isAgent(agent)) + throw new Error('Invalid agent argument'); + this[SYM_AGENT] = agent; + this[SYM_AGENT_KEYS] = null; + this[SYM_AGENT_KEYS_IDX] = -1; + this[SYM_AGENT_CBS] = null; } + init(cb) { + if (typeof cb !== 'function') + cb = noop; - // MD5 state contains four 32-bit integers - var _state = null; + if (this[SYM_AGENT_KEYS] === null) { + if (this[SYM_AGENT_CBS] === null) { + this[SYM_AGENT_CBS] = [cb]; - // input buffer - var _input = forge.util.createBuffer(); + const doCbs = (...args) => { + process.nextTick(() => { + const cbs = this[SYM_AGENT_CBS]; + this[SYM_AGENT_CBS] = null; + for (const cb of cbs) + cb(...args); + }); + }; - // used for word storage - var _w = new Array(16); + this[SYM_AGENT].getIdentities(once((err, keys) => { + if (err) + return doCbs(err); - // message digest object - var md = { - algorithm: 'md5', - blockLength: 64, - digestLength: 16, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; + if (!Array.isArray(keys)) { + return doCbs(new Error( + 'Agent implementation failed to provide keys' + )); + } - /** - * Starts the digest. - * - * @return this digest object. - */ - md.start = function() { - // up to 56-bit message length for convenience - md.messageLength = 0; + const newKeys = []; + for (let key of keys) { + key = parseKey(key); + if (key instanceof Error) { + // TODO: add debug output + continue; + } + newKeys.push(key); + } - // full message length (set md.messageLength64 for backwards-compatibility) - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for(var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); + this[SYM_AGENT_KEYS] = newKeys; + this[SYM_AGENT_KEYS_IDX] = -1; + doCbs(); + })); + } else { + this[SYM_AGENT_CBS].push(cb); + } + } else { + process.nextTick(cb); + } + } + nextKey() { + if (this[SYM_AGENT_KEYS] === null + || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return false; } - _input = forge.util.createBuffer(); - _state = { - h0: 0x67452301, - h1: 0xEFCDAB89, - h2: 0x98BADCFE, - h3: 0x10325476 - }; - return md; - }; - // start digest automatically for first time - md.start(); - /** - * Updates the digest with the given message input. The given input can - * treated as raw input (no encoding will be applied) or an encoding of - * 'utf8' maybe given to encode the input using UTF-8. - * - * @param msg the message input to update with. - * @param encoding the encoding to use (default: 'raw', other: 'utf8'). - * - * @return this digest object. - */ - md.update = function(msg, encoding) { - if(encoding === 'utf8') { - msg = forge.util.encodeUtf8(msg); + return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; + } + currentKey() { + if (this[SYM_AGENT_KEYS] === null + || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return null; } - // update message length - var len = msg.length; - md.messageLength += len; - len = [(len / 0x100000000) >>> 0, len >>> 0]; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = (len[1] / 0x100000000) >>> 0; + return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; + } + pos() { + if (this[SYM_AGENT_KEYS] === null + || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return -1; } - // add bytes to input buffer - _input.putBytes(msg); + return this[SYM_AGENT_KEYS_IDX]; + } + reset() { + this[SYM_AGENT_KEYS_IDX] = -1; + } - // process bytes - _update(_state, _w, _input); + sign(...args) { + this[SYM_AGENT].sign(...args); + } +} - // compact input buffer every 2K or if empty - if(_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } +function isAgent(val) { + return (val instanceof BaseAgent); +} + +module.exports = { + AgentContext, + AgentProtocol, + BaseAgent, + createAgent, + CygwinAgent, + isAgent, + OpenSSHAgent, + PageantAgent, +}; + + +/***/ }), + +/***/ 6063: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// TODO: +// * add `.connected` or similar property to allow immediate connection +// status checking +// * add/improve debug output during user authentication phase + + +const { + createHash, + getHashes, + randomFillSync, +} = __nccwpck_require__(6113); +const { Socket } = __nccwpck_require__(1808); +const { lookup: dnsLookup } = __nccwpck_require__(9523); +const EventEmitter = __nccwpck_require__(2361); +const HASHES = getHashes(); + +const { + COMPAT, + CHANNEL_EXTENDED_DATATYPE: { STDERR }, + CHANNEL_OPEN_FAILURE, + DEFAULT_CIPHER, + DEFAULT_COMPRESSION, + DEFAULT_KEX, + DEFAULT_MAC, + DEFAULT_SERVER_HOST_KEY, + DISCONNECT_REASON, + DISCONNECT_REASON_BY_VALUE, + SUPPORTED_CIPHER, + SUPPORTED_COMPRESSION, + SUPPORTED_KEX, + SUPPORTED_MAC, + SUPPORTED_SERVER_HOST_KEY, +} = __nccwpck_require__(6832); +const { init: cryptoInit } = __nccwpck_require__(5708); +const Protocol = __nccwpck_require__(9031); +const { parseKey } = __nccwpck_require__(2218); +const { SFTP } = __nccwpck_require__(2026); +const { + bufferCopy, + makeBufferParser, + makeError, + readUInt32BE, + sigSSHToASN1, + writeUInt32BE, +} = __nccwpck_require__(9475); + +const { AgentContext, createAgent, isAgent } = __nccwpck_require__(6119); +const { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD, +} = __nccwpck_require__(3204); +const { + ChannelManager, + generateAlgorithmList, + isWritable, + onChannelOpenFailure, + onCHANNEL_CLOSE, +} = __nccwpck_require__(834); - return md; - }; +const bufferParser = makeBufferParser(); +const sigParser = makeBufferParser(); +const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; +const noop = (err) => {}; - /** - * Produces the digest. - * - * @return a byte buffer containing the digest value. - */ - md.digest = function() { - /* Note: Here we copy the remaining bytes in the input buffer and - add the appropriate MD5 padding. Then we do the final update - on a copy of the state so that if the user wants to get - intermediate digests they can do so. */ +class Client extends EventEmitter { + constructor() { + super(); - /* Determine the number of bytes that must be added to the message - to ensure its length is congruent to 448 mod 512. In other words, - the data to be digested must be a multiple of 512 bits (or 128 bytes). - This data includes the message, some padding, and the length of the - message. Since the length of the message will be encoded as 8 bytes (64 - bits), that means that the last segment of the data must have 56 bytes - (448 bits) of message and padding. Therefore, the length of the message - plus the padding must be congruent to 448 mod 512 because - 512 - 128 = 448. + this.config = { + host: undefined, + port: undefined, + localAddress: undefined, + localPort: undefined, + forceIPv4: undefined, + forceIPv6: undefined, + keepaliveCountMax: undefined, + keepaliveInterval: undefined, + readyTimeout: undefined, + ident: undefined, - In order to fill up the message length it must be filled with - padding that begins with 1 bit followed by all 0 bits. Padding - must *always* be present, so if the message length is already - congruent to 448 mod 512, then 512 padding bits must be added. */ + username: undefined, + password: undefined, + privateKey: undefined, + tryKeyboard: undefined, + agent: undefined, + allowAgentFwd: undefined, + authHandler: undefined, - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); + hostHashAlgo: undefined, + hostHashCb: undefined, + strictVendor: undefined, + debug: undefined + }; - // compute remaining size to be digested (include message length size) - var remaining = ( - md.fullMessageLength[md.fullMessageLength.length - 1] + - md.messageLengthSize); + this._agent = undefined; + this._readyTimeout = undefined; + this._chanMgr = undefined; + this._callbacks = undefined; + this._forwarding = undefined; + this._forwardingUnix = undefined; + this._acceptX11 = undefined; + this._agentFwdEnabled = undefined; + this._remoteVer = undefined; - // add padding for overflow blockSize - overflow - // _padding starts with 1 byte with first bit is set (byte value 128), then - // there may be up to (blockSize - 1) other pad bytes - var overflow = remaining & (md.blockLength - 1); - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + this._protocol = undefined; + this._sock = undefined; + this._resetKA = undefined; + } - // serialize message length in bits in little-endian order; since length - // is stored in bytes we multiply by 8 and add carry - var bits, carry = 0; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - bits = md.fullMessageLength[i] * 8 + carry; - carry = (bits / 0x100000000) >>> 0; - finalBlock.putInt32Le(bits >>> 0); + connect(cfg) { + if (this._sock && isWritable(this._sock)) { + this.once('close', () => { + this.connect(cfg); + }); + this.end(); + return this; } - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3 + this.config.host = cfg.hostname || cfg.host || 'localhost'; + this.config.port = cfg.port || 22; + this.config.localAddress = (typeof cfg.localAddress === 'string' + ? cfg.localAddress + : undefined); + this.config.localPort = (typeof cfg.localPort === 'string' + || typeof cfg.localPort === 'number' + ? cfg.localPort + : undefined); + this.config.forceIPv4 = cfg.forceIPv4 || false; + this.config.forceIPv6 = cfg.forceIPv6 || false; + this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' + && cfg.keepaliveCountMax >= 0 + ? cfg.keepaliveCountMax + : 3); + this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' + && cfg.keepaliveInterval > 0 + ? cfg.keepaliveInterval + : 0); + this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' + && cfg.readyTimeout >= 0 + ? cfg.readyTimeout + : 20000); + this.config.ident = (typeof cfg.ident === 'string' + || Buffer.isBuffer(cfg.ident) + ? cfg.ident + : undefined); + + const algorithms = { + kex: undefined, + serverHostKey: undefined, + cs: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: [], + }, + sc: undefined, }; - _update(s2, _w, finalBlock); - var rval = forge.util.createBuffer(); - rval.putInt32Le(s2.h0); - rval.putInt32Le(s2.h1); - rval.putInt32Le(s2.h2); - rval.putInt32Le(s2.h3); - return rval; - }; + let allOfferDefaults = true; + if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { + algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, + DEFAULT_KEX, + SUPPORTED_KEX); + if (algorithms.kex !== DEFAULT_KEX) + allOfferDefaults = false; - return md; -}; + algorithms.serverHostKey = + generateAlgorithmList(cfg.algorithms.serverHostKey, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY); + if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) + allOfferDefaults = false; -// padding, constant tables for calculating md5 -var _padding = null; -var _g = null; -var _r = null; -var _k = null; -var _initialized = false; + algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, + DEFAULT_CIPHER, + SUPPORTED_CIPHER); + if (algorithms.cs.cipher !== DEFAULT_CIPHER) + allOfferDefaults = false; -/** - * Initializes the constant tables. - */ -function _init() { - // create padding - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, + DEFAULT_MAC, + SUPPORTED_MAC); + if (algorithms.cs.mac !== DEFAULT_MAC) + allOfferDefaults = false; - // g values - _g = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, - 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, - 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9]; + algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION); + if (algorithms.cs.compress !== DEFAULT_COMPRESSION) + allOfferDefaults = false; - // rounds table - _r = [ - 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, - 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, - 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, - 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]; + if (!allOfferDefaults) + algorithms.sc = algorithms.cs; + } - // get the result of abs(sin(i + 1)) as a 32-bit integer - _k = new Array(64); - for(var i = 0; i < 64; ++i) { - _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000); - } + if (typeof cfg.username === 'string') + this.config.username = cfg.username; + else if (typeof cfg.user === 'string') + this.config.username = cfg.user; + else + throw new Error('Invalid username'); - // now initialized - _initialized = true; -} + this.config.password = (typeof cfg.password === 'string' + ? cfg.password + : undefined); + this.config.privateKey = (typeof cfg.privateKey === 'string' + || Buffer.isBuffer(cfg.privateKey) + ? cfg.privateKey + : undefined); + this.config.localHostname = (typeof cfg.localHostname === 'string' + ? cfg.localHostname + : undefined); + this.config.localUsername = (typeof cfg.localUsername === 'string' + ? cfg.localUsername + : undefined); + this.config.tryKeyboard = (cfg.tryKeyboard === true); + if (typeof cfg.agent === 'string' && cfg.agent.length) + this.config.agent = createAgent(cfg.agent); + else if (isAgent(cfg.agent)) + this.config.agent = cfg.agent; + else + this.config.agent = undefined; + this.config.allowAgentFwd = (cfg.agentForward === true + && this.config.agent !== undefined); + let authHandler = this.config.authHandler = ( + typeof cfg.authHandler === 'function' + || Array.isArray(cfg.authHandler) + ? cfg.authHandler + : undefined + ); -/** - * Updates an MD5 state with the given byte buffer. - * - * @param s the MD5 state to update. - * @param w the array to use to store words. - * @param bytes the byte buffer to update with. - */ -function _update(s, w, bytes) { - // consume 512 bit (64 byte) chunks - var t, a, b, c, d, f, r, i; - var len = bytes.length(); - while(len >= 64) { - // initialize hash value for this chunk - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; + this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' + ? cfg.strictVendor + : true); - // round 1 - for(i = 0; i < 16; ++i) { - w[i] = bytes.getInt32Le(); - f = d ^ (b & (c ^ d)); - t = (a + f + _k[i] + w[i]); - r = _r[i]; - a = d; - d = c; - c = b; - b += (t << r) | (t >>> (32 - r)); - } - // round 2 - for(; i < 32; ++i) { - f = c ^ (d & (b ^ c)); - t = (a + f + _k[i] + w[_g[i]]); - r = _r[i]; - a = d; - d = c; - c = b; - b += (t << r) | (t >>> (32 - r)); + const debug = this.config.debug = (typeof cfg.debug === 'function' + ? cfg.debug + : undefined); + + if (cfg.agentForward === true && !this.config.allowAgentFwd) { + throw new Error( + 'You must set a valid agent path to allow agent forwarding' + ); } - // round 3 - for(; i < 48; ++i) { - f = b ^ c ^ d; - t = (a + f + _k[i] + w[_g[i]]); - r = _r[i]; - a = d; - d = c; - c = b; - b += (t << r) | (t >>> (32 - r)); + + let callbacks = this._callbacks = []; + this._chanMgr = new ChannelManager(this); + this._forwarding = {}; + this._forwardingUnix = {}; + this._acceptX11 = 0; + this._agentFwdEnabled = false; + this._agent = (this.config.agent ? this.config.agent : undefined); + this._remoteVer = undefined; + let privateKey; + + if (this.config.privateKey) { + privateKey = parseKey(this.config.privateKey, cfg.passphrase); + if (privateKey instanceof Error) + throw new Error(`Cannot parse privateKey: ${privateKey.message}`); + if (Array.isArray(privateKey)) { + // OpenSSH's newer format only stores 1 key for now + privateKey = privateKey[0]; + } + if (privateKey.getPrivatePEM() === null) { + throw new Error( + 'privateKey value does not contain a (valid) private key' + ); + } } - // round 4 - for(; i < 64; ++i) { - f = c ^ (b | ~d); - t = (a + f + _k[i] + w[_g[i]]); - r = _r[i]; - a = d; - d = c; - c = b; - b += (t << r) | (t >>> (32 - r)); + + let hostVerifier; + if (typeof cfg.hostVerifier === 'function') { + const hashCb = cfg.hostVerifier; + let hasher; + if (HASHES.indexOf(cfg.hostHash) !== -1) { + // Default to old behavior of hashing on user's behalf + hasher = createHash(cfg.hostHash); + } + hostVerifier = (key, verify) => { + if (hasher) { + hasher.update(key); + key = hasher.digest('hex'); + } + const ret = hashCb(key, verify); + if (ret !== undefined) + verify(ret); + }; } - // update hash state - s.h0 = (s.h0 + a) | 0; - s.h1 = (s.h1 + b) | 0; - s.h2 = (s.h2 + c) | 0; - s.h3 = (s.h3 + d) | 0; + const sock = this._sock = (cfg.sock || new Socket()); + let ready = false; + let sawHeader = false; + if (this._protocol) + this._protocol.cleanup(); + const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { + debug(`Debug output from server: ${JSON.stringify(msg)}`); + }); + let serverSigAlgs; + const proto = this._protocol = new Protocol({ + ident: this.config.ident, + offer: (allOfferDefaults ? undefined : algorithms), + onWrite: (data) => { + if (isWritable(sock)) + sock.write(data); + }, + onError: (err) => { + if (err.level === 'handshake') + clearTimeout(this._readyTimeout); + if (!proto._destruct) + sock.removeAllListeners('data'); + this.emit('error', err); + try { + sock.end(); + } catch {} + }, + onHeader: (header) => { + sawHeader = true; + this._remoteVer = header.versions.software; + if (header.greeting) + this.emit('greeting', header.greeting); + }, + onHandshakeComplete: (negotiated) => { + this.emit('handshake', negotiated); + if (!ready) { + ready = true; + proto.service('ssh-userauth'); + } + }, + debug, + hostVerifier, + messageHandlers: { + DEBUG: DEBUG_HANDLER, + DISCONNECT: (p, reason, desc) => { + if (reason !== DISCONNECT_REASON.BY_APPLICATION) { + if (!desc) { + desc = DISCONNECT_REASON_BY_VALUE[reason]; + if (desc === undefined) + desc = `Unexpected disconnection reason: ${reason}`; + } + const err = new Error(desc); + err.code = reason; + this.emit('error', err); + } + sock.end(); + }, + SERVICE_ACCEPT: (p, name) => { + if (name === 'ssh-userauth') + tryNextAuth(); + }, + EXT_INFO: (p, exts) => { + if (serverSigAlgs === undefined) { + for (const ext of exts) { + if (ext.name === 'server-sig-algs') { + serverSigAlgs = ext.algs; + return; + } + } + serverSigAlgs = null; + } + }, + USERAUTH_BANNER: (p, msg) => { + this.emit('banner', msg); + }, + USERAUTH_SUCCESS: (p) => { + // Start keepalive mechanism + resetKA(); - len -= 64; - } -} + clearTimeout(this._readyTimeout); + this.emit('ready'); + }, + USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { + // For key-based authentication, check if we should retry the current + // key with a different algorithm first + if (curAuth.keyAlgos) { + const oldKeyAlgo = curAuth.keyAlgos[0][0]; + if (debug) + debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); + curAuth.keyAlgos.shift(); + if (curAuth.keyAlgos.length) { + const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + switch (curAuth.type) { + case 'agent': + proto.authPK( + curAuth.username, + curAuth.agentCtx.currentKey(), + keyAlgo + ); + return; + case 'publickey': + proto.authPK(curAuth.username, curAuth.key, keyAlgo); + return; + case 'hostbased': + proto.authHostbased(curAuth.username, + curAuth.key, + curAuth.localHostname, + curAuth.localUsername, + keyAlgo, + (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = + `Error while signing with key: ${signature.message}`; + signature.level = 'client-authentication'; + this.emit('error', signature); + return tryNextAuth(); + } -/***/ }), + cb(signature); + }); + return; + } + } else { + curAuth.keyAlgos = undefined; + } + } -/***/ 7973: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (curAuth.type === 'agent') { + const pos = curAuth.agentCtx.pos(); + debug && debug(`Client: Agent key #${pos + 1} failed`); + return tryNextAgentKey(); + } -/** - * Node.js module for Forge mask generation functions. - * - * @author Stefan Siegl - * - * Copyright 2012 Stefan Siegl - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(3339); + debug && debug(`Client: ${curAuth.type} auth failed`); -module.exports = forge.mgf = forge.mgf || {}; -forge.mgf.mgf1 = forge.mgf1; + curPartial = partialSuccess; + curAuthsLeft = authMethods; + tryNextAuth(); + }, + USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { + if (curAuth.type === 'password') { + // TODO: support a `changePrompt()` on `curAuth` that defaults to + // emitting 'change password' as before + this.emit('change password', prompt, (newPassword) => { + proto.authPassword( + this.config.username, + this.config.password, + newPassword + ); + }); + } + }, + USERAUTH_PK_OK: (p) => { + let keyAlgo; + let hashAlgo; + if (curAuth.keyAlgos) + [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + if (curAuth.type === 'agent') { + const key = curAuth.agentCtx.currentKey(); + proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => { + const opts = { hash: hashAlgo }; + curAuth.agentCtx.sign(key, buf, opts, (err, signed) => { + if (err) { + err.level = 'agent'; + this.emit('error', err); + } else { + return cb(signed); + } + + tryNextAgentKey(); + }); + }); + } else if (curAuth.type === 'publickey') { + proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = + `Error signing data with key: ${signature.message}`; + signature.level = 'client-authentication'; + this.emit('error', signature); + return tryNextAuth(); + } + cb(signature); + }); + } + }, + USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { + if (curAuth.type === 'keyboard-interactive') { + const nprompts = (Array.isArray(prompts) ? prompts.length : 0); + if (nprompts === 0) { + debug && debug( + 'Client: Sending automatic USERAUTH_INFO_RESPONSE' + ); + proto.authInfoRes(); + return; + } + // We sent a keyboard-interactive user authentication request and + // now the server is sending us the prompts we need to present to + // the user + curAuth.prompt( + name, + instructions, + '', + prompts, + (answers) => { + proto.authInfoRes(answers); + } + ); + } + }, + REQUEST_SUCCESS: (p, data) => { + if (callbacks.length) + callbacks.shift()(false, data); + }, + REQUEST_FAILURE: (p) => { + if (callbacks.length) + callbacks.shift()(true); + }, + GLOBAL_REQUEST: (p, name, wantReply, data) => { + switch (name) { + case 'hostkeys-00@openssh.com': + // Automatically verify keys before passing to end user + hostKeysProve(this, data, (err, keys) => { + if (err) + return; + this.emit('hostkeys', keys); + }); + if (wantReply) + proto.requestSuccess(); + break; + default: + // Auto-reject all other global requests, this can be especially + // useful if the server is sending us dummy keepalive global + // requests + if (wantReply) + proto.requestFailure(); + } + }, + CHANNEL_OPEN: (p, info) => { + // Handle incoming requests from server, typically a forwarded TCP or + // X11 connection + onCHANNEL_OPEN(this, info); + }, + CHANNEL_OPEN_CONFIRMATION: (p, info) => { + const channel = this._chanMgr.get(info.recipient); + if (typeof channel !== 'function') + return; + const isSFTP = (channel.type === 'sftp'); + const type = (isSFTP ? 'session' : channel.type); + const chanInfo = { + type, + incoming: { + id: info.recipient, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; + const instance = ( + isSFTP + ? new SFTP(this, chanInfo, { debug }) + : new Channel(this, chanInfo) + ); + this._chanMgr.update(info.recipient, instance); + channel(undefined, instance); + }, + CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'function') + return; -/***/ }), + const info = { reason, description }; + onChannelOpenFailure(this, recipient, info, channel); + }, + CHANNEL_DATA: (p, recipient, data) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -/***/ 3339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // The remote party should not be sending us data if there is no + // window space available ... + // TODO: raise error on data with not enough window? + if (channel.incoming.window === 0) + return; -/** - * Javascript implementation of mask generation function MGF1. - * - * @author Stefan Siegl - * @author Dave Longley - * - * Copyright (c) 2012 Stefan Siegl - * Copyright (c) 2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); + channel.incoming.window -= data.length; -forge.mgf = forge.mgf || {}; -var mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; + if (channel.push(data) === false) { + channel._waitChanDrain = true; + return; + } -/** - * Creates a MGF1 mask generation function object. - * - * @param md the message digest API to use (eg: forge.md.sha1.create()). - * - * @return a mask generation function object. - */ -mgf1.create = function(md) { - var mgf = { - /** - * Generate mask of specified length. - * - * @param {String} seed The seed for mask generation. - * @param maskLen Number of bytes to generate. - * @return {String} The generated mask. - */ - generate: function(seed, maskLen) { - /* 2. Let T be the empty octet string. */ - var t = new forge.util.ByteBuffer(); + if (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { + if (type !== STDERR) + return; - /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */ - var len = Math.ceil(maskLen / md.digestLength); - for(var i = 0; i < len; i++) { - /* a. Convert counter to an octet string C of length 4 octets */ - var c = new forge.util.ByteBuffer(); - c.putInt32(i); + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; - /* b. Concatenate the hash of the seed mgfSeed and C to the octet - * string T: */ - md.start(); - md.update(seed + c.getBytes()); - t.putBuffer(md.digest()); - } + // The remote party should not be sending us data if there is no + // window space available ... + // TODO: raise error on data with not enough window? + if (channel.incoming.window === 0) + return; - /* Output the leading maskLen octets of T as the octet string mask. */ - t.truncate(t.length() - maskLen); - return t.getBytes(); - } - }; + channel.incoming.window -= data.length; - return mgf; -}; + if (!channel.stderr.push(data)) { + channel._waitChanDrain = true; + return; + } + if (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -/***/ }), + // The other side is allowing us to send `amount` more bytes of data + channel.outgoing.window += amount; -/***/ 1925: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (channel._waitWindow) { + channel._waitWindow = false; -/** - * Object IDs for ASN.1. - * - * @author Dave Longley - * - * Copyright (c) 2010-2013 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); + if (channel._chunk) { + channel._write(channel._chunk, null, channel._chunkcb); + } else if (channel._chunkcb) { + channel._chunkcb(); + } else if (channel._chunkErr) { + channel.stderr._write(channel._chunkErr, + null, + channel._chunkcbErr); + } else if (channel._chunkcbErr) { + channel._chunkcbErr(); + } + } + }, + CHANNEL_SUCCESS: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -forge.pki = forge.pki || {}; -var oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {}; + this._resetKA(); -// set id to name mapping and name to id mapping -function _IN(id, name) { - oids[id] = name; - oids[name] = id; -} -// set id to name mapping only -function _I_(id, name) { - oids[id] = name; -} + if (channel._callbacks.length) + channel._callbacks.shift()(false); + }, + CHANNEL_FAILURE: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -// algorithm OIDs -_IN('1.2.840.113549.1.1.1', 'rsaEncryption'); -// Note: md2 & md4 not implemented -//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption'); -//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption'); -_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); -_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); -_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); -_IN('1.2.840.113549.1.1.8', 'mgf1'); -_IN('1.2.840.113549.1.1.9', 'pSpecified'); -_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); -_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); -_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); -_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); -// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519 -_IN('1.3.101.112', 'EdDSA25519'); + this._resetKA(); -_IN('1.2.840.10040.4.3', 'dsa-with-sha1'); + if (channel._callbacks.length) + channel._callbacks.shift()(true); + }, + CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -_IN('1.3.14.3.2.7', 'desCBC'); + const exit = channel._exit; + if (exit.code !== undefined) + return; + switch (type) { + case 'exit-status': + channel.emit('exit', exit.code = data); + return; + case 'exit-signal': + channel.emit('exit', + exit.code = null, + exit.signal = `SIG${data.signal}`, + exit.dump = data.coreDumped, + exit.desc = data.errorMessage); + return; + } -_IN('1.3.14.3.2.26', 'sha1'); -// Deprecated equivalent of sha1WithRSAEncryption -_IN('1.3.14.3.2.29', 'sha1WithRSASignature'); -_IN('2.16.840.1.101.3.4.2.1', 'sha256'); -_IN('2.16.840.1.101.3.4.2.2', 'sha384'); -_IN('2.16.840.1.101.3.4.2.3', 'sha512'); -_IN('2.16.840.1.101.3.4.2.4', 'sha224'); -_IN('2.16.840.1.101.3.4.2.5', 'sha512-224'); -_IN('2.16.840.1.101.3.4.2.6', 'sha512-256'); -_IN('1.2.840.113549.2.2', 'md2'); -_IN('1.2.840.113549.2.5', 'md5'); + // Keepalive request? OpenSSH will send one as a channel request if + // there is a channel open -// pkcs#7 content types -_IN('1.2.840.113549.1.7.1', 'data'); -_IN('1.2.840.113549.1.7.2', 'signedData'); -_IN('1.2.840.113549.1.7.3', 'envelopedData'); -_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); -_IN('1.2.840.113549.1.7.5', 'digestedData'); -_IN('1.2.840.113549.1.7.6', 'encryptedData'); + if (wantReply) + p.channelFailure(channel.outgoing.id); + }, + CHANNEL_EOF: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -// pkcs#9 oids -_IN('1.2.840.113549.1.9.1', 'emailAddress'); -_IN('1.2.840.113549.1.9.2', 'unstructuredName'); -_IN('1.2.840.113549.1.9.3', 'contentType'); -_IN('1.2.840.113549.1.9.4', 'messageDigest'); -_IN('1.2.840.113549.1.9.5', 'signingTime'); -_IN('1.2.840.113549.1.9.6', 'counterSignature'); -_IN('1.2.840.113549.1.9.7', 'challengePassword'); -_IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); -_IN('1.2.840.113549.1.9.14', 'extensionRequest'); + if (channel.incoming.state !== 'open') + return; + channel.incoming.state = 'eof'; -_IN('1.2.840.113549.1.9.20', 'friendlyName'); -_IN('1.2.840.113549.1.9.21', 'localKeyId'); -_IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); + if (channel.readable) + channel.push(null); + if (channel.stderr.readable) + channel.stderr.push(null); + }, + CHANNEL_CLOSE: (p, recipient) => { + onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); + }, + }, + }); -// pkcs#12 safe bags -_IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); -_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); -_IN('1.2.840.113549.1.12.10.1.3', 'certBag'); -_IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); -_IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); -_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); + sock.pause(); -// password-based-encryption for pkcs#12 -_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); -_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); + // TODO: check keepalive implementation + // Keepalive-related + const kainterval = this.config.keepaliveInterval; + const kacountmax = this.config.keepaliveCountMax; + let kacount = 0; + let katimer; + const sendKA = () => { + if (++kacount > kacountmax) { + clearInterval(katimer); + if (sock.readable) { + const err = new Error('Keepalive timeout'); + err.level = 'client-timeout'; + this.emit('error', err); + sock.destroy(); + } + return; + } + if (isWritable(sock)) { + // Append dummy callback to keep correct callback order + callbacks.push(resetKA); + proto.ping(); + } else { + clearInterval(katimer); + } + }; + function resetKA() { + if (kainterval > 0) { + kacount = 0; + clearInterval(katimer); + if (isWritable(sock)) + katimer = setInterval(sendKA, kainterval); + } + } + this._resetKA = resetKA; -_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); -_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); -_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); -_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); -_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); -_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); + const onDone = (() => { + let called = false; + return () => { + if (called) + return; + called = true; + if (wasConnected && !sawHeader) { + const err = + makeError('Connection lost before handshake', 'protocol', true); + this.emit('error', err); + } + }; + })(); + const onConnect = (() => { + let called = false; + return () => { + if (called) + return; + called = true; -// hmac OIDs -_IN('1.2.840.113549.2.7', 'hmacWithSHA1'); -_IN('1.2.840.113549.2.8', 'hmacWithSHA224'); -_IN('1.2.840.113549.2.9', 'hmacWithSHA256'); -_IN('1.2.840.113549.2.10', 'hmacWithSHA384'); -_IN('1.2.840.113549.2.11', 'hmacWithSHA512'); + wasConnected = true; + debug && debug('Socket connected'); + this.emit('connect'); -// symmetric key algorithm oids -_IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); -_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); -_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); -_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); + cryptoInit.then(() => { + proto.start(); + sock.on('data', (data) => { + try { + proto.parse(data, 0, data.length); + } catch (ex) { + this.emit('error', ex); + try { + if (isWritable(sock)) + sock.end(); + } catch {} + } + }); -// certificate issuer/subject OIDs -_IN('2.5.4.3', 'commonName'); -_IN('2.5.4.4', 'surname'); -_IN('2.5.4.5', 'serialNumber'); -_IN('2.5.4.6', 'countryName'); -_IN('2.5.4.7', 'localityName'); -_IN('2.5.4.8', 'stateOrProvinceName'); -_IN('2.5.4.9', 'streetAddress'); -_IN('2.5.4.10', 'organizationName'); -_IN('2.5.4.11', 'organizationalUnitName'); -_IN('2.5.4.12', 'title'); -_IN('2.5.4.13', 'description'); -_IN('2.5.4.15', 'businessCategory'); -_IN('2.5.4.17', 'postalCode'); -_IN('2.5.4.42', 'givenName'); -_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName'); -_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName'); + // Drain stderr if we are connection hopping using an exec stream + if (sock.stderr && typeof sock.stderr.resume === 'function') + sock.stderr.resume(); -// X.509 extension OIDs -_IN('2.16.840.1.113730.1.1', 'nsCertType'); -_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used -_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35 -_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15 -_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32 -_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15 -_I_('2.5.29.5', 'policyMapping'); // deprecated use .33 -_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30 -_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17 -_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18 -_I_('2.5.29.9', 'subjectDirectoryAttributes'); -_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19 -_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30 -_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36 -_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19 -_IN('2.5.29.14', 'subjectKeyIdentifier'); -_IN('2.5.29.15', 'keyUsage'); -_I_('2.5.29.16', 'privateKeyUsagePeriod'); -_IN('2.5.29.17', 'subjectAltName'); -_IN('2.5.29.18', 'issuerAltName'); -_IN('2.5.29.19', 'basicConstraints'); -_I_('2.5.29.20', 'cRLNumber'); -_I_('2.5.29.21', 'cRLReason'); -_I_('2.5.29.22', 'expirationDate'); -_I_('2.5.29.23', 'instructionCode'); -_I_('2.5.29.24', 'invalidityDate'); -_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31 -_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28 -_I_('2.5.29.27', 'deltaCRLIndicator'); -_I_('2.5.29.28', 'issuingDistributionPoint'); -_I_('2.5.29.29', 'certificateIssuer'); -_I_('2.5.29.30', 'nameConstraints'); -_IN('2.5.29.31', 'cRLDistributionPoints'); -_IN('2.5.29.32', 'certificatePolicies'); -_I_('2.5.29.33', 'policyMappings'); -_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36 -_IN('2.5.29.35', 'authorityKeyIdentifier'); -_I_('2.5.29.36', 'policyConstraints'); -_IN('2.5.29.37', 'extKeyUsage'); -_I_('2.5.29.46', 'freshestCRL'); -_I_('2.5.29.54', 'inhibitAnyPolicy'); + sock.resume(); + }).catch((err) => { + this.emit('error', err); + try { + if (isWritable(sock)) + sock.end(); + } catch {} + }); + }; + })(); + let wasConnected = false; + sock.on('connect', onConnect) + .on('timeout', () => { + this.emit('timeout'); + }).on('error', (err) => { + debug && debug(`Socket error: ${err.message}`); + clearTimeout(this._readyTimeout); + err.level = 'client-socket'; + this.emit('error', err); + }).on('end', () => { + debug && debug('Socket ended'); + onDone(); + proto.cleanup(); + clearTimeout(this._readyTimeout); + clearInterval(katimer); + this.emit('end'); + }).on('close', () => { + debug && debug('Socket closed'); + onDone(); + proto.cleanup(); + clearTimeout(this._readyTimeout); + clearInterval(katimer); + this.emit('close'); -// extKeyUsage purposes -_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); -_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); -_IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); -_IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); -_IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); -_IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); -_IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); + // Notify outstanding channel requests of disconnection ... + const callbacks_ = callbacks; + callbacks = this._callbacks = []; + const err = new Error('No response from server'); + for (let i = 0; i < callbacks_.length; ++i) + callbacks_[i](err); + // Simulate error for any channels waiting to be opened + this._chanMgr.cleanup(err); + }); -/***/ }), + // Begin authentication handling =========================================== + let curAuth; + let curPartial = null; + let curAuthsLeft = null; + const authsAllowed = ['none']; + if (this.config.password !== undefined) + authsAllowed.push('password'); + if (privateKey !== undefined) + authsAllowed.push('publickey'); + if (this._agent !== undefined) + authsAllowed.push('agent'); + if (this.config.tryKeyboard) + authsAllowed.push('keyboard-interactive'); + if (privateKey !== undefined + && this.config.localHostname !== undefined + && this.config.localUsername !== undefined) { + authsAllowed.push('hostbased'); + } -/***/ 1281: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (Array.isArray(authHandler)) + authHandler = makeSimpleAuthHandler(authHandler); + else if (typeof authHandler !== 'function') + authHandler = makeSimpleAuthHandler(authsAllowed); -/** - * Password-based encryption functions. - * - * @author Dave Longley - * @author Stefan Siegl - * - * Copyright (c) 2010-2013 Digital Bazaar, Inc. - * Copyright (c) 2012 Stefan Siegl - * - * An EncryptedPrivateKeyInfo: - * - * EncryptedPrivateKeyInfo ::= SEQUENCE { - * encryptionAlgorithm EncryptionAlgorithmIdentifier, - * encryptedData EncryptedData } - * - * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier - * - * EncryptedData ::= OCTET STRING - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7994); -__nccwpck_require__(9549); -__nccwpck_require__(7157); -__nccwpck_require__(6231); -__nccwpck_require__(1925); -__nccwpck_require__(1611); -__nccwpck_require__(154); -__nccwpck_require__(7821); -__nccwpck_require__(9965); -__nccwpck_require__(3921); -__nccwpck_require__(8339); + let hasSentAuth = false; + const doNextAuth = (nextAuth) => { + if (hasSentAuth) + return; + hasSentAuth = true; -if(typeof BigInteger === 'undefined') { - var BigInteger = forge.jsbn.BigInteger; -} + if (nextAuth === false) { + const err = new Error('All configured authentication methods failed'); + err.level = 'client-authentication'; + this.emit('error', err); + this.end(); + return; + } -// shortcut for asn.1 API -var asn1 = forge.asn1; + if (typeof nextAuth === 'string') { + // Remain backwards compatible with original `authHandler()` usage, + // which only supported passing names of next method to try using data + // from the `connect()` config object -/* Password-based encryption implementation. */ -var pki = forge.pki = forge.pki || {}; -module.exports = pki.pbe = forge.pbe = forge.pbe || {}; -var oids = pki.oids; + const type = nextAuth; + if (authsAllowed.indexOf(type) === -1) + return skipAuth(`Authentication method not allowed: ${type}`); -// validator for an EncryptedPrivateKeyInfo structure -// Note: Currently only works w/algorithm params -var encryptedPrivateKeyValidator = { - name: 'EncryptedPrivateKeyInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'encryptionOid' - }, { - name: 'AlgorithmIdentifier.parameters', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'encryptionParams' - }] - }, { - // encryptedData - name: 'EncryptedPrivateKeyInfo.encryptedData', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'encryptedData' - }] -}; + const username = this.config.username; + switch (type) { + case 'password': + nextAuth = { type, username, password: this.config.password }; + break; + case 'publickey': + nextAuth = { type, username, key: privateKey }; + break; + case 'hostbased': + nextAuth = { + type, + username, + key: privateKey, + localHostname: this.config.localHostname, + localUsername: this.config.localUsername, + }; + break; + case 'agent': + nextAuth = { + type, + username, + agentCtx: new AgentContext(this._agent), + }; + break; + case 'keyboard-interactive': + nextAuth = { + type, + username, + prompt: (...args) => this.emit('keyboard-interactive', ...args), + }; + break; + case 'none': + nextAuth = { type, username }; + break; + default: + return skipAuth( + `Skipping unsupported authentication method: ${nextAuth}` + ); + } + } else if (typeof nextAuth !== 'object' || nextAuth === null) { + return skipAuth( + `Skipping invalid authentication attempt: ${nextAuth}` + ); + } else { + const username = nextAuth.username; + if (typeof username !== 'string') { + return skipAuth( + `Skipping invalid authentication attempt: ${nextAuth}` + ); + } + const type = nextAuth.type; + switch (type) { + case 'password': { + const { password } = nextAuth; + if (typeof password !== 'string' && !Buffer.isBuffer(password)) + return skipAuth('Skipping invalid password auth attempt'); + nextAuth = { type, username, password }; + break; + } + case 'publickey': { + const key = parseKey(nextAuth.key, nextAuth.passphrase); + if (key instanceof Error) + return skipAuth('Skipping invalid key auth attempt'); + if (!key.isPrivateKey()) + return skipAuth('Skipping non-private key'); + nextAuth = { type, username, key }; + break; + } + case 'hostbased': { + const { localHostname, localUsername } = nextAuth; + const key = parseKey(nextAuth.key, nextAuth.passphrase); + if (key instanceof Error + || typeof localHostname !== 'string' + || typeof localUsername !== 'string') { + return skipAuth('Skipping invalid hostbased auth attempt'); + } + if (!key.isPrivateKey()) + return skipAuth('Skipping non-private key'); + nextAuth = { type, username, key, localHostname, localUsername }; + break; + } + case 'agent': { + let agent = nextAuth.agent; + if (typeof agent === 'string' && agent.length) { + agent = createAgent(agent); + } else if (!isAgent(agent)) { + return skipAuth( + `Skipping invalid agent: ${nextAuth.agent}` + ); + } + nextAuth = { type, username, agentCtx: new AgentContext(agent) }; + break; + } + case 'keyboard-interactive': { + const { prompt } = nextAuth; + if (typeof prompt !== 'function') { + return skipAuth( + 'Skipping invalid keyboard-interactive auth attempt' + ); + } + nextAuth = { type, username, prompt }; + break; + } + case 'none': + nextAuth = { type, username }; + break; + default: + return skipAuth( + `Skipping unsupported authentication method: ${nextAuth}` + ); + } + } + curAuth = nextAuth; -// validator for a PBES2Algorithms structure -// Note: Currently only works w/PBKDF2 + AES encryption schemes -var PBES2AlgorithmsValidator = { - name: 'PBES2Algorithms', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PBES2Algorithms.keyDerivationFunc', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PBES2Algorithms.keyDerivationFunc.oid', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'kdfOid' - }, { - name: 'PBES2Algorithms.params', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PBES2Algorithms.params.salt', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'kdfSalt' - }, { - name: 'PBES2Algorithms.params.iterationCount', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'kdfIterationCount' - }, { - name: 'PBES2Algorithms.params.keyLength', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: 'keyLength' - }, { - // prf - name: 'PBES2Algorithms.params.prf', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: 'PBES2Algorithms.params.prf.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'prfOid' - }] - }] - }] - }, { - name: 'PBES2Algorithms.encryptionScheme', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PBES2Algorithms.encryptionScheme.oid', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'encOid' - }, { - name: 'PBES2Algorithms.encryptionScheme.iv', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'encIv' - }] - }] -}; + // Begin authentication method's process + try { + const username = curAuth.username; + switch (curAuth.type) { + case 'password': + proto.authPassword(username, curAuth.password); + break; + case 'publickey': { + let keyAlgo; + curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + keyAlgo = curAuth.keyAlgos[0][0]; + } else { + return skipAuth( + 'Skipping key authentication (no mutual hash algorithm)' + ); + } + } + proto.authPK(username, curAuth.key, keyAlgo); + break; + } + case 'hostbased': { + let keyAlgo; + let hashAlgo; + curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + } else { + return skipAuth( + 'Skipping hostbased authentication (no mutual hash algorithm)' + ); + } + } -var pkcs12PbeParamsValidator = { - name: 'pkcs-12PbeParams', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'pkcs-12PbeParams.salt', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'salt' - }, { - name: 'pkcs-12PbeParams.iterations', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'iterations' - }] -}; + proto.authHostbased(username, + curAuth.key, + curAuth.localHostname, + curAuth.localUsername, + keyAlgo, + (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = + `Error while signing with key: ${signature.message}`; + signature.level = 'client-authentication'; + this.emit('error', signature); + return tryNextAuth(); + } -/** - * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo. - * - * PBES2Algorithms ALGORITHM-IDENTIFIER ::= - * { {PBES2-params IDENTIFIED BY id-PBES2}, ...} - * - * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} - * - * PBES2-params ::= SEQUENCE { - * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}}, - * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} - * } - * - * PBES2-KDFs ALGORITHM-IDENTIFIER ::= - * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... } - * - * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... } - * - * PBKDF2-params ::= SEQUENCE { - * salt CHOICE { - * specified OCTET STRING, - * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}} - * }, - * iterationCount INTEGER (1..MAX), - * keyLength INTEGER (1..MAX) OPTIONAL, - * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 - * } - * - * @param obj the ASN.1 PrivateKeyInfo object. - * @param password the password to encrypt with. - * @param options: - * algorithm the encryption algorithm to use - * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. - * count the iteration count to use. - * saltSize the salt size to use. - * prfAlgorithm the PRF message digest algorithm to use - * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512') - * - * @return the ASN.1 EncryptedPrivateKeyInfo. - */ -pki.encryptPrivateKeyInfo = function(obj, password, options) { - // set default options - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || 'aes128'; - options.prfAlgorithm = options.prfAlgorithm || 'sha1'; + cb(signature); + }); + break; + } + case 'agent': + curAuth.agentCtx.init((err) => { + if (err) { + err.level = 'agent'; + this.emit('error', err); + return tryNextAuth(); + } + tryNextAgentKey(); + }); + break; + case 'keyboard-interactive': + proto.authKeyboard(username); + break; + case 'none': + proto.authNone(username); + break; + } + } finally { + hasSentAuth = false; + } + }; - // generate PBE params - var salt = forge.random.getBytesSync(options.saltSize); - var count = options.count; - var countBytes = asn1.integerToDer(count); - var dkLen; - var encryptionAlgorithm; - var encryptedData; - if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') { - // do PBES2 - var ivLen, encOid, cipherFn; - switch(options.algorithm) { - case 'aes128': - dkLen = 16; - ivLen = 16; - encOid = oids['aes128-CBC']; - cipherFn = forge.aes.createEncryptionCipher; - break; - case 'aes192': - dkLen = 24; - ivLen = 16; - encOid = oids['aes192-CBC']; - cipherFn = forge.aes.createEncryptionCipher; - break; - case 'aes256': - dkLen = 32; - ivLen = 16; - encOid = oids['aes256-CBC']; - cipherFn = forge.aes.createEncryptionCipher; - break; - case 'des': - dkLen = 8; - ivLen = 8; - encOid = oids['desCBC']; - cipherFn = forge.des.createEncryptionCipher; - break; - default: - var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); - error.algorithm = options.algorithm; - throw error; + function skipAuth(msg) { + debug && debug(msg); + process.nextTick(tryNextAuth); } - // get PRF message digest - var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase(); - var md = prfAlgorithmToMessageDigest(prfAlgorithm); - - // encrypt private key using pbe SHA-1 and AES/DES - var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = forge.random.getBytesSync(ivLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - - // get PBKDF2-params - var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); - - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(oids['pkcs5PBES2']).getBytes()), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // keyDerivationFunc - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()), - // PBKDF2-params - params - ]), - // encryptionScheme - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(encOid).getBytes()), - // iv - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv) - ]) - ]) - ]); - } else if(options.algorithm === '3des') { - // Do PKCS12 PBE - dkLen = 24; + function tryNextAuth() { + hasSentAuth = false; + const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); + if (hasSentAuth || auth === undefined) + return; + doNextAuth(auth); + } - var saltBytes = new forge.util.ByteBuffer(salt); - var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); - var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); - var cipher = forge.des.createEncryptionCipher(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); + const tryNextAgentKey = () => { + if (curAuth.type === 'agent') { + const key = curAuth.agentCtx.nextKey(); + if (key === false) { + debug && debug('Agent: No more keys left to try'); + debug && debug('Client: agent auth failed'); + tryNextAuth(); + } else { + const pos = curAuth.agentCtx.pos(); + let keyAlgo; + curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + keyAlgo = curAuth.keyAlgos[0][0]; + } else { + debug && debug( + `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` + ); + tryNextAgentKey(); + return; + } + } + debug && debug(`Agent: Trying key #${pos + 1}`); + proto.authPK(curAuth.username, key, keyAlgo); + } + } + }; - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()), - // pkcs-12PbeParams - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), - // iteration count - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - countBytes.getBytes()) - ]) - ]); - } else { - var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); - error.algorithm = options.algorithm; - throw error; - } + const startTimeout = () => { + if (this.config.readyTimeout > 0) { + this._readyTimeout = setTimeout(() => { + const err = new Error('Timed out while waiting for handshake'); + err.level = 'client-timeout'; + this.emit('error', err); + sock.destroy(); + }, this.config.readyTimeout); + } + }; - // EncryptedPrivateKeyInfo - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // encryptionAlgorithm - encryptionAlgorithm, - // encryptedData - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData) - ]); - return rval; -}; + if (!cfg.sock) { + let host = this.config.host; + const forceIPv4 = this.config.forceIPv4; + const forceIPv6 = this.config.forceIPv6; -/** - * Decrypts a ASN.1 PrivateKeyInfo object. - * - * @param obj the ASN.1 EncryptedPrivateKeyInfo object. - * @param password the password to decrypt with. - * - * @return the ASN.1 PrivateKeyInfo on success, null on failure. - */ -pki.decryptPrivateKeyInfo = function(obj, password) { - var rval = null; + debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); - // get PBE params - var capture = {}; - var errors = []; - if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { - var error = new Error('Cannot read encrypted private key. ' + - 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); - error.errors = errors; - throw error; - } + const doConnect = () => { + startTimeout(); + sock.connect({ + host, + port: this.config.port, + localAddress: this.config.localAddress, + localPort: this.config.localPort + }); + sock.setMaxListeners(0); + sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); + }; - // get cipher - var oid = asn1.derToOid(capture.encryptionOid); - var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password); + if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { + doConnect(); + } else { + dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { + if (err) { + const type = (forceIPv4 ? 'IPv4' : 'IPv6'); + const error = new Error( + `Error while looking up ${type} address for '${host}': ${err}` + ); + clearTimeout(this._readyTimeout); + error.level = 'client-dns'; + this.emit('error', error); + this.emit('close'); + return; + } + host = address; + doConnect(); + }); + } + } else { + // Custom socket passed in + startTimeout(); + if (typeof sock.connecting === 'boolean') { + // net.Socket - // get encrypted data - var encrypted = forge.util.createBuffer(capture.encryptedData); + if (!sock.connecting) { + // Already connected + onConnect(); + } + } else { + // Assume socket/stream is already "connected" + onConnect(); + } + } - cipher.update(encrypted); - if(cipher.finish()) { - rval = asn1.fromDer(cipher.output); + return this; } - return rval; -}; + end() { + if (this._sock && isWritable(this._sock)) { + this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); + this._sock.end(); + } + return this; + } -/** - * Converts a EncryptedPrivateKeyInfo to PEM format. - * - * @param epki the EncryptedPrivateKeyInfo. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted encrypted private key. - */ -pki.encryptedPrivateKeyToPem = function(epki, maxline) { - // convert to DER, then PEM-encode - var msg = { - type: 'ENCRYPTED PRIVATE KEY', - body: asn1.toDer(epki).getBytes() - }; - return forge.pem.encode(msg, {maxline: maxline}); -}; + destroy() { + this._sock && isWritable(this._sock) && this._sock.destroy(); + return this; + } -/** - * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption - * is not performed. - * - * @param pem the EncryptedPrivateKeyInfo in PEM-format. - * - * @return the ASN.1 EncryptedPrivateKeyInfo. - */ -pki.encryptedPrivateKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; + exec(cmd, opts, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - if(msg.type !== 'ENCRYPTED PRIVATE KEY') { - var error = new Error('Could not convert encrypted private key from PEM; ' + - 'PEM header type is "ENCRYPTED PRIVATE KEY".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert encrypted private key from PEM; ' + - 'PEM is encrypted.'); - } + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } - // convert DER to ASN.1 object - return asn1.fromDer(msg.body); -}; + const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; -/** - * Encrypts an RSA private key. By default, the key will be wrapped in - * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo. - * This is the standard, preferred way to encrypt a private key. - * - * To produce a non-standard PEM-encrypted private key that uses encapsulated - * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL - * private key encryption), set the 'legacy' option to true. Note: Using this - * option will cause the iteration count to be forced to 1. - * - * Note: The 'des' algorithm is supported, but it is not considered to be - * secure because it only uses a single 56-bit key. If possible, it is highly - * recommended that a different algorithm be used. - * - * @param rsaKey the RSA key to encrypt. - * @param password the password to use. - * @param options: - * algorithm: the encryption algorithm to use - * ('aes128', 'aes192', 'aes256', '3des', 'des'). - * count: the iteration count to use. - * saltSize: the salt size to use. - * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated - * headers (DEK-Info) private key. - * - * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo. - */ -pki.encryptRsaPrivateKey = function(rsaKey, password, options) { - // standard PKCS#8 - options = options || {}; - if(!options.legacy) { - // encrypt PrivateKeyInfo - var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey)); - rval = pki.encryptPrivateKeyInfo(rval, password, options); - return pki.encryptedPrivateKeyToPem(rval); - } + openChannel(this, 'session', extraOpts, (err, chan) => { + if (err) { + cb(err); + return; + } - // legacy non-PKCS#8 - var algorithm; - var iv; - var dkLen; - var cipherFn; - switch(options.algorithm) { - case 'aes128': - algorithm = 'AES-128-CBC'; - dkLen = 16; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case 'aes192': - algorithm = 'AES-192-CBC'; - dkLen = 24; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case 'aes256': - algorithm = 'AES-256-CBC'; - dkLen = 32; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case '3des': - algorithm = 'DES-EDE3-CBC'; - dkLen = 24; - iv = forge.random.getBytesSync(8); - cipherFn = forge.des.createEncryptionCipher; - break; - case 'des': - algorithm = 'DES-CBC'; - dkLen = 8; - iv = forge.random.getBytesSync(8); - cipherFn = forge.des.createEncryptionCipher; - break; - default: - var error = new Error('Could not encrypt RSA private key; unsupported ' + - 'encryption algorithm "' + options.algorithm + '".'); - error.algorithm = options.algorithm; - throw error; - } + const todo = []; - // encrypt private key using OpenSSL legacy key derivation - var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))); - cipher.finish(); + function reqCb(err) { + if (err) { + chan.close(); + cb(err); + return; + } + if (todo.length) + todo.shift()(); + } - var msg = { - type: 'RSA PRIVATE KEY', - procType: { - version: '4', - type: 'ENCRYPTED' - }, - dekInfo: { - algorithm: algorithm, - parameters: forge.util.bytesToHex(iv).toUpperCase() - }, - body: cipher.output.getBytes() - }; - return forge.pem.encode(msg); -}; + if (this.config.allowAgentFwd === true + || (opts + && opts.agentForward === true + && this._agent !== undefined)) { + todo.push(() => reqAgentFwd(chan, reqCb)); + } -/** - * Decrypts an RSA private key. - * - * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt. - * @param password the password to use. - * - * @return the RSA key on success, null on failure. - */ -pki.decryptRsaPrivateKey = function(pem, password) { - var rval = null; + if (typeof opts === 'object' && opts !== null) { + if (typeof opts.env === 'object' && opts.env !== null) + reqEnv(chan, opts.env); + if ((typeof opts.pty === 'object' && opts.pty !== null) + || opts.pty === true) { + todo.push(() => reqPty(chan, opts.pty, reqCb)); + } + if ((typeof opts.x11 === 'object' && opts.x11 !== null) + || opts.x11 === 'number' + || opts.x11 === true) { + todo.push(() => reqX11(chan, opts.x11, reqCb)); + } + } - var msg = forge.pem.decode(pem)[0]; + todo.push(() => reqExec(chan, cmd, opts, cb)); + todo.shift()(); + }); - if(msg.type !== 'ENCRYPTED PRIVATE KEY' && - msg.type !== 'PRIVATE KEY' && - msg.type !== 'RSA PRIVATE KEY') { - var error = new Error('Could not convert private key from PEM; PEM header type ' + - 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); - error.headerType = error; - throw error; + return this; } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - var dkLen; - var cipherFn; - switch(msg.dekInfo.algorithm) { - case 'DES-CBC': - dkLen = 8; - cipherFn = forge.des.createDecryptionCipher; - break; - case 'DES-EDE3-CBC': - dkLen = 24; - cipherFn = forge.des.createDecryptionCipher; - break; - case 'AES-128-CBC': - dkLen = 16; - cipherFn = forge.aes.createDecryptionCipher; - break; - case 'AES-192-CBC': - dkLen = 24; - cipherFn = forge.aes.createDecryptionCipher; - break; - case 'AES-256-CBC': - dkLen = 32; - cipherFn = forge.aes.createDecryptionCipher; - break; - case 'RC2-40-CBC': - dkLen = 5; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 40); - }; - break; - case 'RC2-64-CBC': - dkLen = 8; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 64); - }; - break; - case 'RC2-128-CBC': - dkLen = 16; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 128); - }; - break; - default: - var error = new Error('Could not decrypt private key; unsupported ' + - 'encryption algorithm "' + msg.dekInfo.algorithm + '".'); - error.algorithm = msg.dekInfo.algorithm; - throw error; - } + shell(wndopts, opts, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - // use OpenSSL legacy key derivation - var iv = forge.util.hexToBytes(msg.dekInfo.parameters); - var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(forge.util.createBuffer(msg.body)); - if(cipher.finish()) { - rval = cipher.output.getBytes(); - } else { - return rval; + if (typeof wndopts === 'function') { + cb = wndopts; + wndopts = opts = undefined; + } else if (typeof opts === 'function') { + cb = opts; + opts = undefined; + } + if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { + opts = wndopts; + wndopts = undefined; } - } else { - rval = msg.body; - } - if(msg.type === 'ENCRYPTED PRIVATE KEY') { - rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password); - } else { - // decryption already performed above - rval = asn1.fromDer(rval); - } + openChannel(this, 'session', (err, chan) => { + if (err) { + cb(err); + return; + } - if(rval !== null) { - rval = pki.privateKeyFromAsn1(rval); - } + const todo = []; - return rval; -}; + function reqCb(err) { + if (err) { + chan.close(); + cb(err); + return; + } + if (todo.length) + todo.shift()(); + } -/** - * Derives a PKCS#12 key. - * - * @param password the password to derive the key material from, null or - * undefined for none. - * @param salt the salt, as a ByteBuffer, to use. - * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). - * @param iter the iteration count. - * @param n the number of bytes to derive from the password. - * @param md the message digest to use, defaults to SHA-1. - * - * @return a ByteBuffer with the bytes derived from the password. - */ -pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { - var j, l; + if (this.config.allowAgentFwd === true + || (opts + && opts.agentForward === true + && this._agent !== undefined)) { + todo.push(() => reqAgentFwd(chan, reqCb)); + } + + if (wndopts !== false) + todo.push(() => reqPty(chan, wndopts, reqCb)); - if(typeof md === 'undefined' || md === null) { - if(!('sha1' in forge.md)) { - throw new Error('"sha1" hash algorithm unavailable.'); - } - md = forge.md.sha1.create(); - } + if (typeof opts === 'object' && opts !== null) { + if (typeof opts.env === 'object' && opts.env !== null) + reqEnv(chan, opts.env); + if ((typeof opts.x11 === 'object' && opts.x11 !== null) + || opts.x11 === 'number' + || opts.x11 === true) { + todo.push(() => reqX11(chan, opts.x11, reqCb)); + } + } - var u = md.digestLength; - var v = md.blockLength; - var result = new forge.util.ByteBuffer(); + todo.push(() => reqShell(chan, cb)); + todo.shift()(); + }); - /* Convert password to Unicode byte buffer + trailing 0-byte. */ - var passBuf = new forge.util.ByteBuffer(); - if(password !== null && password !== undefined) { - for(l = 0; l < password.length; l++) { - passBuf.putInt16(password.charCodeAt(l)); - } - passBuf.putInt16(0); + return this; } - /* Length of salt and password in BYTES. */ - var p = passBuf.length(); - var s = salt.length(); + subsys(name, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - /* 1. Construct a string, D (the "diversifier"), by concatenating - v copies of ID. */ - var D = new forge.util.ByteBuffer(); - D.fillWithByte(id, v); + openChannel(this, 'session', (err, chan) => { + if (err) { + cb(err); + return; + } - /* 2. Concatenate copies of the salt together to create a string S of length - v * ceil(s / v) bytes (the final copy of the salt may be trunacted - to create S). - Note that if the salt is the empty string, then so is S. */ - var Slen = v * Math.ceil(s / v); - var S = new forge.util.ByteBuffer(); - for(l = 0; l < Slen; l++) { - S.putByte(salt.at(l % s)); - } + reqSubsystem(chan, name, (err, stream) => { + if (err) { + cb(err); + return; + } - /* 3. Concatenate copies of the password together to create a string P of - length v * ceil(p / v) bytes (the final copy of the password may be - truncated to create P). - Note that if the password is the empty string, then so is P. */ - var Plen = v * Math.ceil(p / v); - var P = new forge.util.ByteBuffer(); - for(l = 0; l < Plen; l++) { - P.putByte(passBuf.at(l % p)); - } + cb(undefined, stream); + }); + }); - /* 4. Set I=S||P to be the concatenation of S and P. */ - var I = S; - I.putBuffer(P); + return this; + } - /* 5. Set c=ceil(n / u). */ - var c = Math.ceil(n / u); + forwardIn(bindAddr, bindPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - /* 6. For i=1, 2, ..., c, do the following: */ - for(var i = 1; i <= c; i++) { - /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */ - var buf = new forge.util.ByteBuffer(); - buf.putBytes(D.bytes()); - buf.putBytes(I.bytes()); - for(var round = 0; round < iter; round++) { - md.start(); - md.update(buf.getBytes()); - buf = md.digest(); - } + // Send a request for the server to start forwarding TCP connections to us + // on a particular address and port - /* b) Concatenate copies of Ai to create a string B of length v bytes (the - final copy of Ai may be truncated to create B). */ - var B = new forge.util.ByteBuffer(); - for(l = 0; l < v; l++) { - B.putByte(buf.at(l % u)); - } + const wantReply = (typeof cb === 'function'); - /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks, - where k=ceil(s / v) + ceil(p / v), modify I by setting - Ij=(Ij+B+1) mod 2v for each j. */ - var k = Math.ceil(s / v) + Math.ceil(p / v); - var Inew = new forge.util.ByteBuffer(); - for(j = 0; j < k; j++) { - var chunk = new forge.util.ByteBuffer(I.getBytes(v)); - var x = 0x1ff; - for(l = B.length() - 1; l >= 0; l--) { - x = x >> 8; - x += B.at(l) + chunk.at(l); - chunk.setAt(l, x & 0xff); - } - Inew.putBuffer(chunk); - } - I = Inew; + if (wantReply) { + this._callbacks.push((had_err, data) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); + return; + } - /* Add Ai to A. */ - result.putBuffer(buf); - } + let realPort = bindPort; + if (bindPort === 0 && data && data.length >= 4) { + realPort = readUInt32BE(data, 0); + if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) + bindPort = realPort; + } - result.truncate(result.length() - n); - return result; -}; + this._forwarding[`${bindAddr}:${bindPort}`] = realPort; -/** - * Get new Forge cipher object instance. - * - * @param oid the OID (in string notation). - * @param params the ASN.1 params object. - * @param password the password to decrypt with. - * - * @return new cipher object instance. - */ -pki.pbe.getCipher = function(oid, params, password) { - switch(oid) { - case pki.oids['pkcs5PBES2']: - return pki.pbe.getCipherForPBES2(oid, params, password); + cb(undefined, realPort); + }); + } - case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: - case pki.oids['pbewithSHAAnd40BitRC2-CBC']: - return pki.pbe.getCipherForPKCS12PBE(oid, params, password); + this._protocol.tcpipForward(bindAddr, bindPort, wantReply); - default: - var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.'); - error.oid = oid; - error.supportedOids = [ - 'pkcs5PBES2', - 'pbeWithSHAAnd3-KeyTripleDES-CBC', - 'pbewithSHAAnd40BitRC2-CBC' - ]; - throw error; + return this; } -}; -/** - * Get new Forge cipher object instance according to PBES2 params block. - * - * The returned cipher instance is already started using the IV - * from PBES2 parameter block. - * - * @param oid the PKCS#5 PBKDF2 OID (in string notation). - * @param params the ASN.1 PBES2-params object. - * @param password the password to decrypt with. - * - * @return new cipher object instance. - */ -pki.pbe.getCipherForPBES2 = function(oid, params, password) { - // get PBE params - var capture = {}; - var errors = []; - if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { - var error = new Error('Cannot read password-based-encryption algorithm ' + - 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); - error.errors = errors; - throw error; - } + unforwardIn(bindAddr, bindPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - // check oids - oid = asn1.derToOid(capture.kdfOid); - if(oid !== pki.oids['pkcs5PBKDF2']) { - var error = new Error('Cannot read encrypted private key. ' + - 'Unsupported key derivation function OID.'); - error.oid = oid; - error.supportedOids = ['pkcs5PBKDF2']; - throw error; - } - oid = asn1.derToOid(capture.encOid); - if(oid !== pki.oids['aes128-CBC'] && - oid !== pki.oids['aes192-CBC'] && - oid !== pki.oids['aes256-CBC'] && - oid !== pki.oids['des-EDE3-CBC'] && - oid !== pki.oids['desCBC']) { - var error = new Error('Cannot read encrypted private key. ' + - 'Unsupported encryption scheme OID.'); - error.oid = oid; - error.supportedOids = [ - 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC']; - throw error; - } + // Send a request to stop forwarding us new connections for a particular + // address and port - // set PBE params - var salt = capture.kdfSalt; - var count = forge.util.createBuffer(capture.kdfIterationCount); - count = count.getInt(count.length() << 3); - var dkLen; - var cipherFn; - switch(pki.oids[oid]) { - case 'aes128-CBC': - dkLen = 16; - cipherFn = forge.aes.createDecryptionCipher; - break; - case 'aes192-CBC': - dkLen = 24; - cipherFn = forge.aes.createDecryptionCipher; - break; - case 'aes256-CBC': - dkLen = 32; - cipherFn = forge.aes.createDecryptionCipher; - break; - case 'des-EDE3-CBC': - dkLen = 24; - cipherFn = forge.des.createDecryptionCipher; - break; - case 'desCBC': - dkLen = 8; - cipherFn = forge.des.createDecryptionCipher; - break; - } + const wantReply = (typeof cb === 'function'); - // get PRF message digest - var md = prfOidToMessageDigest(capture.prfOid); + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); + return; + } - // decrypt private key using pbe with chosen PRF and AES/DES - var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = capture.encIv; - var cipher = cipherFn(dk); - cipher.start(iv); + delete this._forwarding[`${bindAddr}:${bindPort}`]; - return cipher; -}; + cb(); + }); + } -/** - * Get new Forge cipher object instance for PKCS#12 PBE. - * - * The returned cipher instance is already started using the key & IV - * derived from the provided password and PKCS#12 PBE salt. - * - * @param oid The PKCS#12 PBE OID (in string notation). - * @param params The ASN.1 PKCS#12 PBE-params object. - * @param password The password to decrypt with. - * - * @return the new cipher object instance. - */ -pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) { - // get PBE params - var capture = {}; - var errors = []; - if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { - var error = new Error('Cannot read password-based-encryption algorithm ' + - 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); - error.errors = errors; - throw error; + this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); + + return this; } - var salt = forge.util.createBuffer(capture.salt); - var count = forge.util.createBuffer(capture.iterations); - count = count.getInt(count.length() << 3); + forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - var dkLen, dIvLen, cipherFn; - switch(oid) { - case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: - dkLen = 24; - dIvLen = 8; - cipherFn = forge.des.startDecrypting; - break; + // Send a request to forward a TCP connection to the server - case pki.oids['pbewithSHAAnd40BitRC2-CBC']: - dkLen = 5; - dIvLen = 8; - cipherFn = function(key, iv) { - var cipher = forge.rc2.createDecryptionCipher(key, 40); - cipher.start(iv, null); - return cipher; - }; - break; + const cfg = { + srcIP: srcIP, + srcPort: srcPort, + dstIP: dstIP, + dstPort: dstPort + }; - default: - var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.'); - error.oid = oid; - throw error; + if (typeof cb !== 'function') + cb = noop; + + openChannel(this, 'direct-tcpip', cfg, cb); + + return this; } - // get PRF message digest - var md = prfOidToMessageDigest(capture.prfOid); - var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); - md.start(); - var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); + openssh_noMoreSessions(cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - return cipherFn(key, iv); -}; + const wantReply = (typeof cb === 'function'); -/** - * OpenSSL's legacy key derivation function. - * - * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html - * - * @param password the password to derive the key from. - * @param salt the salt to use, null for none. - * @param dkLen the number of bytes needed for the derived key. - * @param [options] the options to use: - * [md] an optional message digest object to use. - */ -pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { - if(typeof md === 'undefined' || md === null) { - if(!('md5' in forge.md)) { - throw new Error('"md5" hash algorithm unavailable.'); - } - md = forge.md.md5.create(); - } - if(salt === null) { - salt = ''; - } - var digests = [hash(md, password + salt)]; - for(var length = 16, i = 1; length < dkLen; ++i, length += 16) { - digests.push(hash(md, digests[i - 1] + password + salt)); - } - return digests.join('').substr(0, dkLen); -}; + if (!this.config.strictVendor + || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error('Unable to disable future sessions')); + return; + } -function hash(md, bytes) { - return md.start().update(bytes).digest().getBytes(); -} + cb(); + }); + } -function prfOidToMessageDigest(prfOid) { - // get PRF algorithm, default to SHA-1 - var prfAlgorithm; - if(!prfOid) { - prfAlgorithm = 'hmacWithSHA1'; - } else { - prfAlgorithm = pki.oids[asn1.derToOid(prfOid)]; - if(!prfAlgorithm) { - var error = new Error('Unsupported PRF OID.'); - error.oid = prfOid; - error.supported = [ - 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', - 'hmacWithSHA512']; - throw error; + this._protocol.openssh_noMoreSessions(wantReply); + return this; } - } - return prfAlgorithmToMessageDigest(prfAlgorithm); -} -function prfAlgorithmToMessageDigest(prfAlgorithm) { - var factory = forge.md; - switch(prfAlgorithm) { - case 'hmacWithSHA224': - factory = forge.md.sha512; - case 'hmacWithSHA1': - case 'hmacWithSHA256': - case 'hmacWithSHA384': - case 'hmacWithSHA512': - prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); - break; - default: - var error = new Error('Unsupported PRF algorithm.'); - error.algorithm = prfAlgorithm; - error.supported = [ - 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', - 'hmacWithSHA512']; - throw error; - } - if(!factory || !(prfAlgorithm in factory)) { - throw new Error('Unknown hash algorithm: ' + prfAlgorithm); - } - return factory[prfAlgorithm].create(); -} + if (!wantReply) + return this; -function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { - var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), - // iteration count - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - countBytes.getBytes()) - ]); - // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm - if(prfAlgorithm !== 'hmacWithSHA1') { - params.value.push( - // key length - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - forge.util.hexToBytes(dkLen.toString(16))), - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ])); + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); + + return this; } - return params; -} + openssh_forwardInStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); -/***/ }), + const wantReply = (typeof cb === 'function'); -/***/ 1611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!this.config.strictVendor + || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to bind to ${socketPath}`)); + return; + } + this._forwardingUnix[socketPath] = true; + cb(); + }); + } -/** - * Password-Based Key-Derivation Function #2 implementation. - * - * See RFC 2898 for details. - * - * @author Dave Longley - * - * Copyright (c) 2010-2013 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(5104); -__nccwpck_require__(6231); -__nccwpck_require__(8339); + this._protocol.openssh_streamLocalForward(socketPath, wantReply); + return this; + } -var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; + if (!wantReply) + return this; -var crypto; -if(forge.util.isNodejs && !forge.options.usePureJavaScript) { - crypto = __nccwpck_require__(6113); -} + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); -/** - * Derives a key from a password. - * - * @param p the password as a binary-encoded string of bytes. - * @param s the salt as a binary-encoded string of bytes. - * @param c the iteration count, a positive integer. - * @param dkLen the intended length, in bytes, of the derived key, - * (max: 2^32 - 1) * hash length of the PRF. - * @param [md] the message digest (or algorithm identifier as a string) to use - * in the PRF, defaults to SHA-1. - * @param [callback(err, key)] presence triggers asynchronous version, called - * once the operation completes. - * - * @return the derived key, as a binary-encoded string of bytes, for the - * synchronous version (if no callback is specified). - */ -module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function( - p, s, c, dkLen, md, callback) { - if(typeof md === 'function') { - callback = md; - md = null; + return this; } - // use native implementation if possible and not disabled, note that - // some node versions only support SHA-1, others allow digest to be changed - if(forge.util.isNodejs && !forge.options.usePureJavaScript && - crypto.pbkdf2 && (md === null || typeof md !== 'object') && - (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) { - if(typeof md !== 'string') { - // default prf to SHA-1 - md = 'sha1'; - } - p = Buffer.from(p, 'binary'); - s = Buffer.from(s, 'binary'); - if(!callback) { - if(crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary'); - } - return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); - } - if(crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2(p, s, c, dkLen, function(err, key) { - if(err) { - return callback(err); - } - callback(null, key.toString('binary')); - }); - } - return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) { - if(err) { - return callback(err); + openssh_unforwardInStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); + + const wantReply = (typeof cb === 'function'); + + if (!this.config.strictVendor + || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to unbind from ${socketPath}`)); + return; + } + delete this._forwardingUnix[socketPath]; + cb(); + }); } - callback(null, key.toString('binary')); - }); - } - if(typeof md === 'undefined' || md === null) { - // default prf to SHA-1 - md = 'sha1'; - } - if(typeof md === 'string') { - if(!(md in forge.md.algorithms)) { - throw new Error('Unknown hash algorithm: ' + md); + this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); + return this; } - md = forge.md[md].create(); + + if (!wantReply) + return this; + + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); + + return this; } - var hLen = md.digestLength; + openssh_forwardOutStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and - stop. */ - if(dkLen > (0xFFFFFFFF * hLen)) { - var err = new Error('Derived key is too long.'); - if(callback) { - return callback(err); + if (typeof cb !== 'function') + cb = noop; + + if (!this.config.strictVendor + || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { + openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); + return this; } - throw err; + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); + + return this; } - /* 2. Let len be the number of hLen-octet blocks in the derived key, - rounding up, and let r be the number of octets in the last - block: + sftp(cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error('Not connected'); - len = CEIL(dkLen / hLen), - r = dkLen - (len - 1) * hLen. */ - var len = Math.ceil(dkLen / hLen); - var r = dkLen - (len - 1) * hLen; + openChannel(this, 'sftp', (err, sftp) => { + if (err) { + cb(err); + return; + } - /* 3. For each block of the derived key apply the function F defined - below to the password P, the salt S, the iteration count c, and - the block index to compute the block: + reqSubsystem(sftp, 'sftp', (err, sftp_) => { + if (err) { + cb(err); + return; + } - T_1 = F(P, S, c, 1), - T_2 = F(P, S, c, 2), - ... - T_len = F(P, S, c, len), + function removeListeners() { + sftp.removeListener('ready', onReady); + sftp.removeListener('error', onError); + sftp.removeListener('exit', onExit); + sftp.removeListener('close', onExit); + } - where the function F is defined as the exclusive-or sum of the - first c iterates of the underlying pseudorandom function PRF - applied to the password P and the concatenation of the salt S - and the block index i: + function onReady() { + // TODO: do not remove exit/close in case remote end closes the + // channel abruptly and we need to notify outstanding callbacks + removeListeners(); + cb(undefined, sftp); + } - F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c + function onError(err) { + removeListeners(); + cb(err); + } - where + function onExit(code, signal) { + removeListeners(); + let msg; + if (typeof code === 'number') + msg = `Received exit code ${code} while establishing SFTP session`; + else if (signal !== undefined) + msg = `Received signal ${signal} while establishing SFTP session`; + else + msg = 'Received unexpected SFTP session termination'; + const err = new Error(msg); + err.code = code; + err.signal = signal; + cb(err); + } - u_1 = PRF(P, S || INT(i)), - u_2 = PRF(P, u_1), - ... - u_c = PRF(P, u_{c-1}). + sftp.on('ready', onReady) + .on('error', onError) + .on('exit', onExit) + .on('close', onExit); - Here, INT(i) is a four-octet encoding of the integer i, most - significant octet first. */ - var prf = forge.hmac.create(); - prf.start(md, p); - var dk = ''; - var xor, u_c, u_c1; + sftp._init(); + }); + }); - // sync version - if(!callback) { - for(var i = 1; i <= len; ++i) { - // PRF(P, S || INT(i)) (first iteration) - prf.start(null, null); - prf.update(s); - prf.update(forge.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); + return this; + } - // PRF(P, u_{c-1}) (other iterations) - for(var j = 2; j <= c; ++j) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - // F(p, s, c, i) - xor = forge.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - } + setNoDelay(noDelay) { + if (this._sock && typeof this._sock.setNoDelay === 'function') + this._sock.setNoDelay(noDelay); - /* 4. Concatenate the blocks and extract the first dkLen octets to - produce a derived key DK: + return this; + } +} - DK = T_1 || T_2 || ... || T_len<0..r-1> */ - dk += (i < len) ? xor : xor.substr(0, r); - } - /* 5. Output the derived key DK. */ - return dk; +function openChannel(self, type, opts, cb) { + // Ask the server to open a channel for some purpose + // (e.g. session (sftp, exec, shell), or forwarding a TCP connection + const initWindow = MAX_WINDOW; + const maxPacket = PACKET_SIZE; + + if (typeof opts === 'function') { + cb = opts; + opts = {}; } - // async version - var i = 1, j; - function outer() { - if(i > len) { - // done - return callback(null, dk); - } + const wrapper = (err, stream) => { + cb(err, stream); + }; + wrapper.type = type; - // PRF(P, S || INT(i)) (first iteration) - prf.start(null, null); - prf.update(s); - prf.update(forge.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); + const localChan = self._chanMgr.add(wrapper); - // PRF(P, u_{c-1}) (other iterations) - j = 2; - inner(); + if (localChan === -1) { + cb(new Error('No free channels available')); + return; } - function inner() { - if(j <= c) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - // F(p, s, c, i) - xor = forge.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - ++j; - return forge.util.setImmediate(inner); - } - - /* 4. Concatenate the blocks and extract the first dkLen octets to - produce a derived key DK: + switch (type) { + case 'session': + case 'sftp': + self._protocol.session(localChan, initWindow, maxPacket); + break; + case 'direct-tcpip': + self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); + break; + case 'direct-streamlocal@openssh.com': + self._protocol.openssh_directStreamLocal( + localChan, initWindow, maxPacket, opts + ); + break; + default: + throw new Error(`Unsupported channel type: ${type}`); + } +} - DK = T_1 || T_2 || ... || T_len<0..r-1> */ - dk += (i < len) ? xor : xor.substr(0, r); +function reqX11(chan, screen, cb) { + // Asks server to start sending us X11 connections + const cfg = { + single: false, + protocol: 'MIT-MAGIC-COOKIE-1', + cookie: undefined, + screen: 0 + }; - ++i; - outer(); + if (typeof screen === 'function') { + cb = screen; + } else if (typeof screen === 'object' && screen !== null) { + if (typeof screen.single === 'boolean') + cfg.single = screen.single; + if (typeof screen.screen === 'number') + cfg.screen = screen.screen; + if (typeof screen.protocol === 'string') + cfg.protocol = screen.protocol; + if (typeof screen.cookie === 'string') + cfg.cookie = screen.cookie; + else if (Buffer.isBuffer(screen.cookie)) + cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); } + if (cfg.cookie === undefined) + cfg.cookie = randomCookie(); - outer(); -}; + const wantReply = (typeof cb === 'function'); + if (chan.outgoing.state !== 'open') { + if (wantReply) + cb(new Error('Channel is not open')); + return; + } -/***/ }), + if (wantReply) { + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error('Unable to request X11')); + return; + } -/***/ 154: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + chan._hasX11 = true; + ++chan._client._acceptX11; + chan.once('close', () => { + if (chan._client._acceptX11) + --chan._client._acceptX11; + }); -/** - * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms. - * - * See: RFC 1421. - * - * @author Dave Longley - * - * Copyright (c) 2013-2014 Digital Bazaar, Inc. - * - * A Forge PEM object has the following fields: - * - * type: identifies the type of message (eg: "RSA PRIVATE KEY"). - * - * procType: identifies the type of processing performed on the message, - * it has two subfields: version and type, eg: 4,ENCRYPTED. - * - * contentDomain: identifies the type of content in the message, typically - * only uses the value: "RFC822". - * - * dekInfo: identifies the message encryption algorithm and mode and includes - * any parameters for the algorithm, it has two subfields: algorithm and - * parameters, eg: DES-CBC,F8143EDE5960C597. - * - * headers: contains all other PEM encapsulated headers -- where order is - * significant (for pairing data like recipient ID + key info). - * - * body: the binary-encoded body. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); + cb(); + }); + } -// shortcut for pem API -var pem = module.exports = forge.pem = forge.pem || {}; + chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); +} -/** - * Encodes (serializes) the given PEM object. - * - * @param msg the PEM message object to encode. - * @param options the options to use: - * maxline the maximum characters per line for the body, (default: 64). - * - * @return the PEM-formatted string. - */ -pem.encode = function(msg, options) { - options = options || {}; - var rval = '-----BEGIN ' + msg.type + '-----\r\n'; +function reqPty(chan, opts, cb) { + let rows = 24; + let cols = 80; + let width = 640; + let height = 480; + let term = 'vt100'; + let modes = null; - // encode special headers - var header; - if(msg.procType) { - header = { - name: 'Proc-Type', - values: [String(msg.procType.version), msg.procType.type] - }; - rval += foldHeader(header); - } - if(msg.contentDomain) { - header = {name: 'Content-Domain', values: [msg.contentDomain]}; - rval += foldHeader(header); - } - if(msg.dekInfo) { - header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]}; - if(msg.dekInfo.parameters) { - header.values.push(msg.dekInfo.parameters); - } - rval += foldHeader(header); + if (typeof opts === 'function') { + cb = opts; + } else if (typeof opts === 'object' && opts !== null) { + if (typeof opts.rows === 'number') + rows = opts.rows; + if (typeof opts.cols === 'number') + cols = opts.cols; + if (typeof opts.width === 'number') + width = opts.width; + if (typeof opts.height === 'number') + height = opts.height; + if (typeof opts.term === 'string') + term = opts.term; + if (typeof opts.modes === 'object') + modes = opts.modes; } - if(msg.headers) { - // encode all other headers - for(var i = 0; i < msg.headers.length; ++i) { - rval += foldHeader(msg.headers[i]); - } + const wantReply = (typeof cb === 'function'); + + if (chan.outgoing.state !== 'open') { + if (wantReply) + cb(new Error('Channel is not open')); + return; } - // terminate header - if(msg.procType) { - rval += '\r\n'; + if (wantReply) { + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error('Unable to request a pseudo-terminal')); + return; + } + cb(); + }); } - // add body - rval += forge.util.encode64(msg.body, options.maxline || 64) + '\r\n'; + chan._client._protocol.pty(chan.outgoing.id, + rows, + cols, + height, + width, + term, + modes, + wantReply); +} - rval += '-----END ' + msg.type + '-----\r\n'; - return rval; -}; +function reqAgentFwd(chan, cb) { + const wantReply = (typeof cb === 'function'); -/** - * Decodes (deserializes) all PEM messages found in the given string. - * - * @param str the PEM-formatted string to decode. - * - * @return the PEM message objects in an array. - */ -pem.decode = function(str) { - var rval = []; + if (chan.outgoing.state !== 'open') { + wantReply && cb(new Error('Channel is not open')); + return; + } + if (chan._client._agentFwdEnabled) { + wantReply && cb(false); + return; + } - // split string into PEM messages (be lenient w/EOF on BEGIN line) - var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; - var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; - var rCRLF = /\r?\n/; - var match; - while(true) { - match = rMessage.exec(str); - if(!match) { - break; - } + chan._client._agentFwdEnabled = true; - // accept "NEW CERTIFICATE REQUEST" as "CERTIFICATE REQUEST" - // https://datatracker.ietf.org/doc/html/rfc7468#section-7 - var type = match[1]; - if(type === 'NEW CERTIFICATE REQUEST') { - type = 'CERTIFICATE REQUEST'; + chan._callbacks.push((had_err) => { + if (had_err) { + chan._client._agentFwdEnabled = false; + if (wantReply) { + cb(had_err !== true + ? had_err + : new Error('Unable to request agent forwarding')); + } + return; } - var msg = { - type: type, - procType: null, - contentDomain: null, - dekInfo: null, - headers: [], - body: forge.util.decode64(match[3]) - }; - rval.push(msg); + if (wantReply) + cb(); + }); - // no headers - if(!match[2]) { - continue; - } + chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); +} - // parse headers - var lines = match[2].split(rCRLF); - var li = 0; - while(match && li < lines.length) { - // get line, trim any rhs whitespace - var line = lines[li].replace(/\s+$/, ''); +function reqShell(chan, cb) { + if (chan.outgoing.state !== 'open') { + cb(new Error('Channel is not open')); + return; + } - // RFC2822 unfold any following folded lines - for(var nl = li + 1; nl < lines.length; ++nl) { - var next = lines[nl]; - if(!/\s/.test(next[0])) { - break; - } - line += next; - li = nl; - } + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error('Unable to open shell')); + return; + } + chan.subtype = 'shell'; + cb(undefined, chan); + }); - // parse header - match = line.match(rHeader); - if(match) { - var header = {name: match[1], values: []}; - var values = match[2].split(','); - for(var vi = 0; vi < values.length; ++vi) { - header.values.push(ltrim(values[vi])); - } + chan._client._protocol.shell(chan.outgoing.id, true); +} - // Proc-Type must be the first header - if(!msg.procType) { - if(header.name !== 'Proc-Type') { - throw new Error('Invalid PEM formatted message. The first ' + - 'encapsulated header must be "Proc-Type".'); - } else if(header.values.length !== 2) { - throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + - 'header must have two subfields.'); - } - msg.procType = {version: values[0], type: values[1]}; - } else if(!msg.contentDomain && header.name === 'Content-Domain') { - // special-case Content-Domain - msg.contentDomain = values[0] || ''; - } else if(!msg.dekInfo && header.name === 'DEK-Info') { - // special-case DEK-Info - if(header.values.length === 0) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + - 'header must have at least one subfield.'); - } - msg.dekInfo = {algorithm: values[0], parameters: values[1] || null}; - } else { - msg.headers.push(header); - } - } +function reqExec(chan, cmd, opts, cb) { + if (chan.outgoing.state !== 'open') { + cb(new Error('Channel is not open')); + return; + } - ++li; + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error('Unable to exec')); + return; } + chan.subtype = 'exec'; + chan.allowHalfOpen = (opts.allowHalfOpen !== false); + cb(undefined, chan); + }); - if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + - 'header must be present if "Proc-Type" is "ENCRYPTED".'); - } - } + chan._client._protocol.exec(chan.outgoing.id, cmd, true); +} - if(rval.length === 0) { - throw new Error('Invalid PEM formatted message.'); - } +function reqEnv(chan, env) { + if (chan.outgoing.state !== 'open') + return; - return rval; -}; + const keys = Object.keys(env || {}); -function foldHeader(header) { - var rval = header.name + ': '; + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + const val = env[key]; + chan._client._protocol.env(chan.outgoing.id, key, val, false); + } +} - // ensure values with CRLF are folded - var values = []; - var insertSpace = function(match, $1) { - return ' ' + $1; - }; - for(var i = 0; i < header.values.length; ++i) { - values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); +function reqSubsystem(chan, name, cb) { + if (chan.outgoing.state !== 'open') { + cb(new Error('Channel is not open')); + return; } - rval += values.join(',') + '\r\n'; - // do folding - var length = 0; - var candidate = -1; - for(var i = 0; i < rval.length; ++i, ++length) { - if(length > 65 && candidate !== -1) { - var insert = rval[candidate]; - if(insert === ',') { - ++candidate; - rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate); - } else { - rval = rval.substr(0, candidate) + - '\r\n' + insert + rval.substr(candidate + 1); - } - length = (i - candidate - 1); - candidate = -1; - ++i; - } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') { - candidate = i; + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error(`Unable to start subsystem: ${name}`)); + return; } - } + chan.subtype = 'subsystem'; + cb(undefined, chan); + }); - return rval; + chan._client._protocol.subsystem(chan.outgoing.id, name, true); } -function ltrim(str) { - return str.replace(/^\s+/, ''); -} +// TODO: inline implementation into single call site +function onCHANNEL_OPEN(self, info) { + // The server is trying to open a channel with us, this is usually when + // we asked the server to forward us connections on some port and now they + // are asking us to accept/deny an incoming connection on their side + let localChan = -1; + let reason; -/***/ }), + const accept = () => { + const chanInfo = { + type: info.type, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; + const stream = new Channel(self, chanInfo); + self._chanMgr.update(localChan, stream); -/***/ 7014: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + self._protocol.channelOpenConfirm(info.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE); + return stream; + }; + const reject = () => { + if (reason === undefined) { + if (localChan === -1) + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + else + reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; + } -/** - * Partial implementation of PKCS#1 v2.2: RSA-OEAP - * - * Modified but based on the following MIT and BSD licensed code: - * - * https://github.com/kjur/jsjws/blob/master/rsa.js: - * - * The 'jsjws'(JSON Web Signature JavaScript Library) License - * - * Copyright (c) 2012 Kenji Urushima - * - * 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. - * - * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain: - * - * RSAES-OAEP.js - * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $ - * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002) - * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003. - * Contact: ellis@nukinetics.com - * Distributed under the BSD License. - * - * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125 - * - * @author Evan Jones (http://evanjones.ca/) - * @author Dave Longley - * - * Copyright (c) 2013-2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); -__nccwpck_require__(7821); -__nccwpck_require__(279); + if (localChan !== -1) + self._chanMgr.remove(localChan); -// shortcut for PKCS#1 API -var pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {}; + self._protocol.channelOpenFail(info.sender, reason, ''); + }; + const reserveChannel = () => { + localChan = self._chanMgr.add(); -/** - * Encode the given RSAES-OAEP message (M) using key, with optional label (L) - * and seed. - * - * This method does not perform RSA encryption, it only encodes the message - * using RSAES-OAEP. - * - * @param key the RSA key to use. - * @param message the message to encode. - * @param options the options to use: - * label an optional label to use. - * seed the seed to use. - * md the message digest object to use, undefined for SHA-1. - * mgf1 optional mgf1 parameters: - * md the message digest object to use for MGF1. - * - * @return the encoded message bytes. - */ -pkcs1.encode_rsa_oaep = function(key, message, options) { - // parse arguments - var label; - var seed; - var md; - var mgf1Md; - // legacy args (label, seed, md) - if(typeof options === 'string') { - label = options; - seed = arguments[3] || undefined; - md = arguments[4] || undefined; - } else if(options) { - label = options.label || undefined; - seed = options.seed || undefined; - md = options.md || undefined; - if(options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; + if (localChan === -1) { + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + if (self.config.debug) { + self.config.debug( + 'Client: Automatic rejection of incoming channel open: ' + + 'no channels available' + ); + } } - } - // default OAEP to SHA-1 message digest - if(!md) { - md = forge.md.sha1.create(); - } else { - md.start(); - } + return (localChan !== -1); + }; - // default MGF-1 to same as OAEP - if(!mgf1Md) { - mgf1Md = md; - } + const data = info.data; + switch (info.type) { + case 'forwarded-tcpip': { + const val = self._forwarding[`${data.destIP}:${data.destPort}`]; + if (val !== undefined && reserveChannel()) { + if (data.destPort === 0) + data.destPort = val; + self.emit('tcp connection', data, accept, reject); + return; + } + break; + } + case 'forwarded-streamlocal@openssh.com': + if (self._forwardingUnix[data.socketPath] !== undefined + && reserveChannel()) { + self.emit('unix connection', data, accept, reject); + return; + } + break; + case 'auth-agent@openssh.com': + if (self._agentFwdEnabled + && typeof self._agent.getStream === 'function' + && reserveChannel()) { + self._agent.getStream((err, stream) => { + if (err) + return reject(); - // compute length in bytes and check output - var keyLength = Math.ceil(key.n.bitLength() / 8); - var maxLength = keyLength - 2 * md.digestLength - 2; - if(message.length > maxLength) { - var error = new Error('RSAES-OAEP input message length is too long.'); - error.length = message.length; - error.maxLength = maxLength; - throw error; + const upstream = accept(); + upstream.pipe(stream).pipe(upstream); + }); + return; + } + break; + case 'x11': + if (self._acceptX11 !== 0 && reserveChannel()) { + self.emit('x11', data, accept, reject); + return; + } + break; + default: + // Automatically reject any unsupported channel open requests + reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; + if (self.config.debug) { + self.config.debug( + 'Client: Automatic rejection of unsupported incoming channel open ' + + `type: ${info.type}` + ); + } } - if(!label) { - label = ''; + if (reason === undefined) { + reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + if (self.config.debug) { + self.config.debug( + 'Client: Automatic rejection of unexpected incoming channel open for: ' + + info.type + ); + } } - md.update(label, 'raw'); - var lHash = md.digest(); - var PS = ''; - var PS_length = maxLength - message.length; - for(var i = 0; i < PS_length; i++) { - PS += '\x00'; - } + reject(); +} - var DB = lHash.getBytes() + PS + '\x01' + message; +const randomCookie = (() => { + const buffer = Buffer.allocUnsafe(16); + return () => { + randomFillSync(buffer, 0, 16); + return buffer.hexSlice(0, 16); + }; +})(); - if(!seed) { - seed = forge.random.getBytes(md.digestLength); - } else if(seed.length !== md.digestLength) { - var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + - 'match the digest length.'); - error.seedLength = seed.length; - error.digestLength = md.digestLength; - throw error; - } +function makeSimpleAuthHandler(authList) { + if (!Array.isArray(authList)) + throw new Error('authList must be an array'); - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); + let a = 0; + return (authsLeft, partialSuccess, cb) => { + if (a === authList.length) + return false; + return authList[a++]; + }; +} - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); +function hostKeysProve(client, keys_, cb) { + if (!client._sock || !isWritable(client._sock)) + return; - // return encoded message - return '\x00' + maskedSeed + maskedDB; -}; + if (typeof cb !== 'function') + cb = noop; -/** - * Decode the given RSAES-OAEP encoded message (EM) using key, with optional - * label (L). - * - * This method does not perform RSA decryption, it only decodes the message - * using RSAES-OAEP. - * - * @param key the RSA key to use. - * @param em the encoded message to decode. - * @param options the options to use: - * label an optional label to use. - * md the message digest object to use for OAEP, undefined for SHA-1. - * mgf1 optional mgf1 parameters: - * md the message digest object to use for MGF1. - * - * @return the decoded message bytes. - */ -pkcs1.decode_rsa_oaep = function(key, em, options) { - // parse args - var label; - var md; - var mgf1Md; - // legacy args - if(typeof options === 'string') { - label = options; - md = arguments[3] || undefined; - } else if(options) { - label = options.label || undefined; - md = options.md || undefined; - if(options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } + if (!Array.isArray(keys_)) + throw new TypeError('Invalid keys argument type'); + + const keys = []; + for (const key of keys_) { + const parsed = parseKey(key); + if (parsed instanceof Error) + throw parsed; + keys.push(parsed); } - // compute length in bytes - var keyLength = Math.ceil(key.n.bitLength() / 8); + if (!client.config.strictVendor + || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { + client._callbacks.push((had_err, data) => { + if (had_err) { + cb(had_err !== true + ? had_err + : new Error('Server failed to prove supplied keys')); + return; + } + + // TODO: move all of this parsing/verifying logic out of the client? + const ret = []; + let keyIdx = 0; + bufferParser.init(data, 0); + while (bufferParser.avail()) { + if (keyIdx === keys.length) + break; + const key = keys[keyIdx++]; + const keyPublic = key.getPublicSSH(); + + const sigEntry = bufferParser.readString(); + sigParser.init(sigEntry, 0); + const type = sigParser.readString(true); + let value = sigParser.readString(); + + let algo; + if (type !== key.type) { + if (key.type === 'ssh-rsa') { + switch (type) { + case 'rsa-sha2-256': + algo = 'sha256'; + break; + case 'rsa-sha2-512': + algo = 'sha512'; + break; + default: + continue; + } + } else { + continue; + } + } + + const sessionID = client._protocol._kex.sessionID; + const verifyData = Buffer.allocUnsafe( + 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length + ); + let p = 0; + writeUInt32BE(verifyData, 29, p); + verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); + writeUInt32BE(verifyData, sessionID.length, p += 29); + bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); + writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); + bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); - if(em.length !== keyLength) { - var error = new Error('RSAES-OAEP encoded message length is invalid.'); - error.length = em.length; - error.expectedLength = keyLength; - throw error; - } + if (!(value = sigSSHToASN1(value, type))) + continue; + if (key.verify(verifyData, value, algo) === true) + ret.push(key); + } + sigParser.clear(); + bufferParser.clear(); - // default OAEP to SHA-1 message digest - if(md === undefined) { - md = forge.md.sha1.create(); - } else { - md.start(); - } + cb(null, ret); + }); - // default MGF-1 to same as OAEP - if(!mgf1Md) { - mgf1Md = md; + client._protocol.openssh_hostKeysProve(keys); + return; } - if(keyLength < 2 * md.digestLength + 2) { - throw new Error('RSAES-OAEP key is too short for the hash function.'); - } + process.nextTick( + cb, + new Error( + 'strictVendor enabled and server is not OpenSSH or compatible version' + ) + ); +} - if(!label) { - label = ''; +function getKeyAlgos(client, key, serverSigAlgs) { + switch (key.type) { + case 'ssh-rsa': + if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) { + if (!Array.isArray(serverSigAlgs)) + serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512']; + else + serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512', ...serverSigAlgs]; + } + if (Array.isArray(serverSigAlgs)) { + if (serverSigAlgs.indexOf('rsa-sha2-256') !== -1) + return [['rsa-sha2-256', 'sha256']]; + if (serverSigAlgs.indexOf('rsa-sha2-512') !== -1) + return [['rsa-sha2-512', 'sha512']]; + if (serverSigAlgs.indexOf('ssh-rsa') === -1) + return []; + } + return [['ssh-rsa', 'sha1']]; } - md.update(label, 'raw'); - var lHash = md.digest().getBytes(); +} - // split the message into its parts - var y = em.charAt(0); - var maskedSeed = em.substring(1, md.digestLength + 1); - var maskedDB = em.substring(1 + md.digestLength); +module.exports = Client; - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); +/***/ }), - var lHashPrime = db.substring(0, md.digestLength); +/***/ 2994: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // constant time check that all values match what is expected - var error = (y !== '\x00'); +"use strict"; - // constant time check lHash vs lHashPrime - for(var i = 0; i < md.digestLength; ++i) { - error |= (lHash.charAt(i) !== lHashPrime.charAt(i)); - } - // "constant time" find the 0x1 byte separating the padding (zeros) from the - // message - // TODO: It must be possible to do this in a better/smarter way? - var in_ps = 1; - var index = md.digestLength; - for(var j = md.digestLength; j < db.length; j++) { - var code = db.charCodeAt(j); +const { Agent: HttpAgent } = __nccwpck_require__(3685); +const { Agent: HttpsAgent } = __nccwpck_require__(5687); +const { connect: tlsConnect } = __nccwpck_require__(4404); - var is_0 = (code & 0x1) ^ 0x1; +let Client; - // non-zero if not 0 or 1 in the ps section - var error_mask = in_ps ? 0xfffe : 0x0000; - error |= (code & error_mask); +for (const ctor of [HttpAgent, HttpsAgent]) { + class SSHAgent extends ctor { + constructor(connectCfg, agentOptions) { + super(agentOptions); - // latch in_ps to zero after we find 0x1 - in_ps = in_ps & is_0; - index += in_ps; - } + this._connectCfg = connectCfg; + this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; + } - if(error || db.charCodeAt(index) !== 0x1) { - throw new Error('Invalid RSAES-OAEP padding.'); - } + createConnection(options, cb) { + const srcIP = (options && options.localAddress) || this._defaultSrcIP; + const srcPort = (options && options.localPort) || 0; + const dstIP = options.host; + const dstPort = options.port; - return db.substring(index + 1); -}; + if (Client === undefined) + Client = __nccwpck_require__(6063); -function rsa_mgf1(seed, maskLength, hash) { - // default to SHA-1 message digest - if(!hash) { - hash = forge.md.sha1.create(); + const client = new Client(); + let triedForward = false; + client.on('ready', () => { + client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { + triedForward = true; + if (err) { + client.end(); + return cb(err); + } + stream.once('close', () => client.end()); + cb(null, decorateStream(stream, ctor, options)); + }); + }).on('error', cb).on('close', () => { + if (!triedForward) + cb(new Error('Unexpected connection close')); + }).connect(this._connectCfg); + } } - var t = ''; - var count = Math.ceil(maskLength / hash.digestLength); - for(var i = 0; i < count; ++i) { - var c = String.fromCharCode( - (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF); - hash.start(); - hash.update(seed + c); - t += hash.digest().getBytes(); + + exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; +} + +function noop() {} + +function decorateStream(stream, ctor, options) { + if (ctor === HttpAgent) { + // HTTP + stream.setKeepAlive = noop; + stream.setNoDelay = noop; + stream.setTimeout = noop; + stream.ref = noop; + stream.unref = noop; + stream.destroySoon = stream.destroy; + return stream; } - return t.substring(0, maskLength); + + // HTTPS + options.socket = stream; + const wrapped = tlsConnect(options); + + // This is a workaround for a regression in node v12.16.3+ + // https://github.com/nodejs/node/issues/35904 + const onClose = (() => { + let called = false; + return () => { + if (called) + return; + called = true; + if (stream.isPaused()) + stream.resume(); + }; + })(); + // 'end' listener is needed because 'close' is not emitted in some scenarios + // in node v12.x for some unknown reason + wrapped.on('end', onClose).on('close', onClose); + + return wrapped; } /***/ }), -/***/ 466: +/***/ 5869: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Javascript implementation of PKCS#12. - * - * @author Dave Longley - * @author Stefan Siegl - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - * Copyright (c) 2012 Stefan Siegl - * - * The ASN.1 representation of PKCS#12 is as follows - * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details) - * - * PFX ::= SEQUENCE { - * version INTEGER {v3(3)}(v3,...), - * authSafe ContentInfo, - * macData MacData OPTIONAL - * } - * - * MacData ::= SEQUENCE { - * mac DigestInfo, - * macSalt OCTET STRING, - * iterations INTEGER DEFAULT 1 - * } - * Note: The iterations default is for historical reasons and its use is - * deprecated. A higher value, like 1024, is recommended. - * - * DigestInfo is defined in PKCS#7 as follows: - * - * DigestInfo ::= SEQUENCE { - * digestAlgorithm DigestAlgorithmIdentifier, - * digest Digest - * } - * - * DigestAlgorithmIdentifier ::= AlgorithmIdentifier - * - * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters - * for the algorithm, if any. In the case of SHA1 there is none. - * - * AlgorithmIdentifer ::= SEQUENCE { - * algorithm OBJECT IDENTIFIER, - * parameters ANY DEFINED BY algorithm OPTIONAL - * } - * - * Digest ::= OCTET STRING - * - * - * ContentInfo ::= SEQUENCE { - * contentType ContentType, - * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL - * } - * - * ContentType ::= OBJECT IDENTIFIER - * - * AuthenticatedSafe ::= SEQUENCE OF ContentInfo - * -- Data if unencrypted - * -- EncryptedData if password-encrypted - * -- EnvelopedData if public key-encrypted - * - * - * SafeContents ::= SEQUENCE OF SafeBag - * - * SafeBag ::= SEQUENCE { - * bagId BAG-TYPE.&id ({PKCS12BagSet}) - * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), - * bagAttributes SET OF PKCS12Attribute OPTIONAL - * } - * - * PKCS12Attribute ::= SEQUENCE { - * attrId ATTRIBUTE.&id ({PKCS12AttrSet}), - * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId}) - * } -- This type is compatible with the X.500 type 'Attribute' - * - * PKCS12AttrSet ATTRIBUTE ::= { - * friendlyName | -- from PKCS #9 - * localKeyId, -- from PKCS #9 - * ... -- Other attributes are allowed - * } - * - * CertBag ::= SEQUENCE { - * certId BAG-TYPE.&id ({CertTypes}), - * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) - * } - * - * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}} - * -- DER-encoded X.509 certificate stored in OCTET STRING - * - * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}} - * -- Base64-encoded SDSI certificate stored in IA5String - * - * CertTypes BAG-TYPE ::= { - * x509Certificate | - * sdsiCertificate, - * ... -- For future extensions - * } - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(9549); -__nccwpck_require__(5104); -__nccwpck_require__(1925); -__nccwpck_require__(266); -__nccwpck_require__(1281); -__nccwpck_require__(7821); -__nccwpck_require__(3921); -__nccwpck_require__(279); -__nccwpck_require__(8339); -__nccwpck_require__(8180); - -// shortcut for asn.1 & PKI API -var asn1 = forge.asn1; -var pki = forge.pki; +"use strict"; -// shortcut for PKCS#12 API -var p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {}; -var contentInfoValidator = { - name: 'ContentInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, // a ContentInfo - constructed: true, - value: [{ - name: 'ContentInfo.contentType', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'contentType' - }, { - name: 'ContentInfo.content', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: 'content' - }] -}; +const { + AgentProtocol, + BaseAgent, + createAgent, + CygwinAgent, + OpenSSHAgent, + PageantAgent, +} = __nccwpck_require__(6119); +const { + SSHTTPAgent: HTTPAgent, + SSHTTPSAgent: HTTPSAgent, +} = __nccwpck_require__(2994); +const { parseKey } = __nccwpck_require__(2218); +const { + flagsToString, + OPEN_MODE, + STATUS_CODE, + stringToFlags, +} = __nccwpck_require__(2026); -var pfxValidator = { - name: 'PFX', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PFX.version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'version' +module.exports = { + AgentProtocol, + BaseAgent, + createAgent, + Client: __nccwpck_require__(6063), + CygwinAgent, + HTTPAgent, + HTTPSAgent, + OpenSSHAgent, + PageantAgent, + Server: __nccwpck_require__(2986), + utils: { + parseKey, + ...__nccwpck_require__(3823), + sftp: { + flagsToString, + OPEN_MODE, + STATUS_CODE, + stringToFlags, + }, }, - contentInfoValidator, { - name: 'PFX.macData', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'mac', - value: [{ - name: 'PFX.macData.mac', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, // DigestInfo - constructed: true, - value: [{ - name: 'PFX.macData.mac.digestAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier - constructed: true, - value: [{ - name: 'PFX.macData.mac.digestAlgorithm.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'macAlgorithm' - }, { - name: 'PFX.macData.mac.digestAlgorithm.parameters', - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: 'macAlgorithmParameters' - }] - }, { - name: 'PFX.macData.mac.digest', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'macDigest' - }] - }, { - name: 'PFX.macData.macSalt', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'macSalt' - }, { - name: 'PFX.macData.iterations', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: 'macIterations' - }] - }] }; -var safeBagValidator = { - name: 'SafeBag', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SafeBag.bagId', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'bagId' - }, { - name: 'SafeBag.bagValue', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: 'bagValue' - }, { - name: 'SafeBag.bagAttributes', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - optional: true, - capture: 'bagAttributes' - }] -}; -var attributeValidator = { - name: 'Attribute', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'Attribute.attrId', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'oid' - }, { - name: 'Attribute.attrValues', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - capture: 'values' - }] -}; +/***/ }), -var certBagValidator = { - name: 'CertBag', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'CertBag.certId', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'certId' - }, { - name: 'CertBag.certValue', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - /* So far we only support X.509 certificates (which are wrapped in - an OCTET STRING, hence hard code that here). */ - value: [{ - name: 'CertBag.certValue[0]', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.OCTETSTRING, - constructed: false, - capture: 'cert' - }] - }] -}; +/***/ 3823: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Search SafeContents structure for bags with matching attributes. - * - * The search can optionally be narrowed by a certain bag type. - * - * @param safeContents the SafeContents structure to search in. - * @param attrName the name of the attribute to compare against. - * @param attrValue the attribute value to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of matching bags. - */ -function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { - var result = []; +"use strict"; + + +const { + createCipheriv, + generateKeyPair: generateKeyPair_, + generateKeyPairSync: generateKeyPairSync_, + getCurves, + randomBytes, +} = __nccwpck_require__(6113); + +const { Ber } = __nccwpck_require__(970); +const bcrypt_pbkdf = (__nccwpck_require__(5447).pbkdf); - for(var i = 0; i < safeContents.length; i++) { - for(var j = 0; j < safeContents[i].safeBags.length; j++) { - var bag = safeContents[i].safeBags[j]; - if(bagType !== undefined && bag.type !== bagType) { - continue; - } - // only filter by bag type, no attribute specified - if(attrName === null) { - result.push(bag); - continue; - } - if(bag.attributes[attrName] !== undefined && - bag.attributes[attrName].indexOf(attrValue) >= 0) { - result.push(bag); +const { CIPHER_INFO } = __nccwpck_require__(5708); + +const SALT_LEN = 16; +const DEFAULT_ROUNDS = 16; + +const curves = getCurves(); +const ciphers = new Map(Object.entries(CIPHER_INFO)); + +function makeArgs(type, opts) { + if (typeof type !== 'string') + throw new TypeError('Key type must be a string'); + + const publicKeyEncoding = { type: 'spki', format: 'der' }; + const privateKeyEncoding = { type: 'pkcs8', format: 'der' }; + + switch (type.toLowerCase()) { + case 'rsa': { + if (typeof opts !== 'object' || opts === null) + throw new TypeError('Missing options object for RSA key'); + const modulusLength = opts.bits; + if (!Number.isInteger(modulusLength)) + throw new TypeError('RSA bits must be an integer'); + if (modulusLength <= 0 || modulusLength > 16384) + throw new RangeError('RSA bits must be non-zero and <= 16384'); + return ['rsa', { modulusLength, publicKeyEncoding, privateKeyEncoding }]; + } + case 'ecdsa': { + if (typeof opts !== 'object' || opts === null) + throw new TypeError('Missing options object for ECDSA key'); + if (!Number.isInteger(opts.bits)) + throw new TypeError('ECDSA bits must be an integer'); + let namedCurve; + switch (opts.bits) { + case 256: + namedCurve = 'prime256v1'; + break; + case 384: + namedCurve = 'secp384r1'; + break; + case 521: + namedCurve = 'secp521r1'; + break; + default: + throw new Error('ECDSA bits must be 256, 384, or 521'); } + if (!curves.includes(namedCurve)) + throw new Error('Unsupported ECDSA bits value'); + return ['ec', { namedCurve, publicKeyEncoding, privateKeyEncoding }]; } + case 'ed25519': + return ['ed25519', { publicKeyEncoding, privateKeyEncoding }]; + default: + throw new Error(`Unsupported key type: ${type}`); } - - return result; } -/** - * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object. - * - * @param obj The PKCS#12 PFX in ASN.1 notation. - * @param strict true to use strict DER decoding, false not to (default: true). - * @param {String} password Password to decrypt with (optional). - * - * @return PKCS#12 PFX object. - */ -p12.pkcs12FromAsn1 = function(obj, strict, password) { - // handle args - if(typeof strict === 'string') { - password = strict; - strict = true; - } else if(strict === undefined) { - strict = true; - } - - // validate PFX and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(obj, pfxValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#12 PFX. ' + - 'ASN.1 object is not an PKCS#12 PFX.'); - error.errors = error; - throw error; - } +function parseDERs(keyType, pub, priv) { + switch (keyType) { + case 'rsa': { + // Note: we don't need to parse the public key since the PKCS8 private key + // already includes the public key parameters - var pfx = { - version: capture.version.charCodeAt(0), - safeContents: [], + // Parse private key + let reader = new Ber.Reader(priv); + reader.readSequence(); - /** - * Gets bags with matching attributes. - * - * @param filter the attributes to filter by: - * [localKeyId] the localKeyId to search for. - * [localKeyIdHex] the localKeyId in hex to search for. - * [friendlyName] the friendly name to search for. - * [bagType] bag type to narrow each attribute search by. - * - * @return a map of attribute type to an array of matching bags or, if no - * attribute was given but a bag type, the map key will be the - * bag type. - */ - getBags: function(filter) { - var rval = {}; + // - Version + if (reader.readInt() !== 0) + throw new Error('Unsupported version in RSA private key'); - var localKeyId; - if('localKeyId' in filter) { - localKeyId = filter.localKeyId; - } else if('localKeyIdHex' in filter) { - localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); + // - Algorithm + reader.readSequence(); + if (reader.readOID() !== '1.2.840.113549.1.1.1') + throw new Error('Bad RSA private OID'); + // - Algorithm parameters (RSA has none) + if (reader.readByte() !== Ber.Null) + throw new Error('Malformed RSA private key (expected null)'); + if (reader.readByte() !== 0x00) { + throw new Error( + 'Malformed RSA private key (expected zero-length null)' + ); } - // filter on bagType only - if(localKeyId === undefined && !('friendlyName' in filter) && - 'bagType' in filter) { - rval[filter.bagType] = _getBagsByAttribute( - pfx.safeContents, null, null, filter.bagType); - } + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + reader.readSequence(); + if (reader.readInt() !== 0) + throw new Error('Unsupported version in RSA private key'); + const n = reader.readString(Ber.Integer, true); + const e = reader.readString(Ber.Integer, true); + const d = reader.readString(Ber.Integer, true); + const p = reader.readString(Ber.Integer, true); + const q = reader.readString(Ber.Integer, true); + reader.readString(Ber.Integer, true); // dmp1 + reader.readString(Ber.Integer, true); // dmq1 + const iqmp = reader.readString(Ber.Integer, true); - if(localKeyId !== undefined) { - rval.localKeyId = _getBagsByAttribute( - pfx.safeContents, 'localKeyId', - localKeyId, filter.bagType); - } - if('friendlyName' in filter) { - rval.friendlyName = _getBagsByAttribute( - pfx.safeContents, 'friendlyName', - filter.friendlyName, filter.bagType); + /* + OpenSSH RSA private key: + string "ssh-rsa" + string n -- public + string e -- public + string d -- private + string iqmp -- private + string p -- private + string q -- private + */ + const keyName = Buffer.from('ssh-rsa'); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + n.length + + 4 + e.length + + 4 + d.length + + 4 + iqmp.length + + 4 + p.length + + 4 + q.length + ); + let pos = 0; + + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(n.length, pos += keyName.length); + privBuf.set(n, pos += 4); + privBuf.writeUInt32BE(e.length, pos += n.length); + privBuf.set(e, pos += 4); + privBuf.writeUInt32BE(d.length, pos += e.length); + privBuf.set(d, pos += 4); + privBuf.writeUInt32BE(iqmp.length, pos += d.length); + privBuf.set(iqmp, pos += 4); + privBuf.writeUInt32BE(p.length, pos += iqmp.length); + privBuf.set(p, pos += 4); + privBuf.writeUInt32BE(q.length, pos += p.length); + privBuf.set(q, pos += 4); + + /* + OpenSSH RSA public key: + string "ssh-rsa" + string e -- public + string n -- public + */ + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + e.length + + 4 + n.length + ); + pos = 0; + + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(e.length, pos += keyName.length); + pubBuf.set(e, pos += 4); + pubBuf.writeUInt32BE(n.length, pos += e.length); + pubBuf.set(n, pos += 4); + + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; + } + case 'ec': { + // Parse public key + let reader = new Ber.Reader(pub); + reader.readSequence(); + + reader.readSequence(); + if (reader.readOID() !== '1.2.840.10045.2.1') + throw new Error('Bad ECDSA public OID'); + // Skip curve OID, we'll get it from the private key + reader.readOID(); + let pubBin = reader.readString(Ber.BitString, true); + { + // Remove leading zero bytes + let i = 0; + for (; i < pubBin.length && pubBin[i] === 0x00; ++i); + if (i > 0) + pubBin = pubBin.slice(i); + } + + // Parse private key + reader = new Ber.Reader(priv); + reader.readSequence(); + + // - Version + if (reader.readInt() !== 0) + throw new Error('Unsupported version in ECDSA private key'); + + reader.readSequence(); + if (reader.readOID() !== '1.2.840.10045.2.1') + throw new Error('Bad ECDSA private OID'); + const curveOID = reader.readOID(); + let sshCurveName; + switch (curveOID) { + case '1.2.840.10045.3.1.7': + // prime256v1/secp256r1 + sshCurveName = 'nistp256'; + break; + case '1.3.132.0.34': + // secp384r1 + sshCurveName = 'nistp384'; + break; + case '1.3.132.0.35': + // secp521r1 + sshCurveName = 'nistp521'; + break; + default: + throw new Error('Unsupported curve in ECDSA private key'); } - return rval; - }, + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + reader.readSequence(); - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching friendlyName attribute. - * - * @param friendlyName the friendly name to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching friendlyName attribute. - */ - getBagsByFriendlyName: function(friendlyName, bagType) { - return _getBagsByAttribute( - pfx.safeContents, 'friendlyName', friendlyName, bagType); - }, + // - Version + if (reader.readInt() !== 1) + throw new Error('Unsupported version in ECDSA private key'); - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching localKeyId attribute. - * - * @param localKeyId the localKeyId to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching localKeyId attribute. - */ - getBagsByLocalKeyId: function(localKeyId, bagType) { - return _getBagsByAttribute( - pfx.safeContents, 'localKeyId', localKeyId, bagType); - } - }; + // Add leading zero byte to prevent negative bignum in private key + const privBin = Buffer.concat([ + Buffer.from([0x00]), + reader.readString(Ber.OctetString, true) + ]); - if(capture.version.charCodeAt(0) !== 3) { - var error = new Error('PKCS#12 PFX of version other than 3 not supported.'); - error.version = capture.version.charCodeAt(0); - throw error; - } + /* + OpenSSH ECDSA private key: + string "ecdsa-sha2-" + string curve name + string Q -- public + string d -- private + */ + const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`); + sshCurveName = Buffer.from(sshCurveName); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + sshCurveName.length + + 4 + pubBin.length + + 4 + privBin.length + ); + let pos = 0; - if(asn1.derToOid(capture.contentType) !== pki.oids.data) { - var error = new Error('Only PKCS#12 PFX in password integrity mode supported.'); - error.oid = asn1.derToOid(capture.contentType); - throw error; - } + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); + privBuf.set(sshCurveName, pos += 4); + privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); + privBuf.set(pubBin, pos += 4); + privBuf.writeUInt32BE(privBin.length, pos += pubBin.length); + privBuf.set(privBin, pos += 4); - var data = capture.content.value[0]; - if(data.tagClass !== asn1.Class.UNIVERSAL || - data.type !== asn1.Type.OCTETSTRING) { - throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.'); - } - data = _decodePkcs7Data(data); + /* + OpenSSH ECDSA public key: + string "ecdsa-sha2-" + string curve name + string Q -- public + */ + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + sshCurveName.length + + 4 + pubBin.length + ); + pos = 0; - // check for MAC - if(capture.mac) { - var md = null; - var macKeyBytes = 0; - var macAlgorithm = asn1.derToOid(capture.macAlgorithm); - switch(macAlgorithm) { - case pki.oids.sha1: - md = forge.md.sha1.create(); - macKeyBytes = 20; - break; - case pki.oids.sha256: - md = forge.md.sha256.create(); - macKeyBytes = 32; - break; - case pki.oids.sha384: - md = forge.md.sha384.create(); - macKeyBytes = 48; - break; - case pki.oids.sha512: - md = forge.md.sha512.create(); - macKeyBytes = 64; - break; - case pki.oids.md5: - md = forge.md.md5.create(); - macKeyBytes = 16; - break; - } - if(md === null) { - throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm); - } + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); + pubBuf.set(sshCurveName, pos += 4); + pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); + pubBuf.set(pubBin, pos += 4); - // verify MAC (iterations default to 1) - var macSalt = new forge.util.ByteBuffer(capture.macSalt); - var macIterations = (('macIterations' in capture) ? - parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1); - var macKey = p12.generateKey( - password, macSalt, 3, macIterations, macKeyBytes, md); - var mac = forge.hmac.create(); - mac.start(md, macKey); - mac.update(data.value); - var macValue = mac.getMac(); - if(macValue.getBytes() !== capture.macDigest) { - throw new Error('PKCS#12 MAC could not be verified. Invalid password?'); + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; } - } + case 'ed25519': { + // Parse public key + let reader = new Ber.Reader(pub); + reader.readSequence(); - _decodeAuthenticatedSafe(pfx, data.value, strict, password); - return pfx; -}; + // - Algorithm + reader.readSequence(); + if (reader.readOID() !== '1.3.101.112') + throw new Error('Bad ED25519 public OID'); + // - Attributes (absent for ED25519) -/** - * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING, - * but it is sometimes an OCTET STRING that is composed/constructed of chunks, - * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This - * function transforms this corner-case into the usual simple, - * non-composed/constructed OCTET STRING. - * - * This function may be moved to ASN.1 at some point to better deal with - * more BER-encoding issues, should they arise. - * - * @param data the ASN.1 Data object to transform. - */ -function _decodePkcs7Data(data) { - // handle special case of "chunked" data content: an octet string composed - // of other octet strings - if(data.composed || data.constructed) { - var value = forge.util.createBuffer(); - for(var i = 0; i < data.value.length; ++i) { - value.putBytes(data.value[i].value); + let pubBin = reader.readString(Ber.BitString, true); + { + // Remove leading zero bytes + let i = 0; + for (; i < pubBin.length && pubBin[i] === 0x00; ++i); + if (i > 0) + pubBin = pubBin.slice(i); + } + + // Parse private key + reader = new Ber.Reader(priv); + reader.readSequence(); + + // - Version + if (reader.readInt() !== 0) + throw new Error('Unsupported version in ED25519 private key'); + + // - Algorithm + reader.readSequence(); + if (reader.readOID() !== '1.3.101.112') + throw new Error('Bad ED25519 private OID'); + // - Attributes (absent) + + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + const privBin = reader.readString(Ber.OctetString, true); + + /* + OpenSSH ed25519 private key: + string "ssh-ed25519" + string public key + string private key + public key + */ + const keyName = Buffer.from('ssh-ed25519'); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + pubBin.length + + 4 + (privBin.length + pubBin.length) + ); + let pos = 0; + + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(pubBin.length, pos += keyName.length); + privBuf.set(pubBin, pos += 4); + privBuf.writeUInt32BE( + privBin.length + pubBin.length, + pos += pubBin.length + ); + privBuf.set(privBin, pos += 4); + privBuf.set(pubBin, pos += privBin.length); + + /* + OpenSSH ed25519 public key: + string "ssh-ed25519" + string public key + */ + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + + 4 + pubBin.length + ); + pos = 0; + + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length); + pubBuf.set(pubBin, pos += 4); + + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; } - data.composed = data.constructed = false; - data.value = value.getBytes(); } - return data; } -/** - * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object. - * - * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo. - * - * @param pfx The PKCS#12 PFX object to fill. - * @param {String} authSafe BER-encoded AuthenticatedSafe. - * @param strict true to use strict DER decoding, false not to. - * @param {String} password Password to decrypt with (optional). - */ -function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { - authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */ +function convertKeys(keyType, pub, priv, opts) { + let format = 'new'; + let encrypted; + let comment = ''; + if (typeof opts === 'object' && opts !== null) { + if (typeof opts.comment === 'string' && opts.comment) + comment = opts.comment; + if (typeof opts.format === 'string' && opts.format) + format = opts.format; + if (opts.passphrase) { + let passphrase; + if (typeof opts.passphrase === 'string') + passphrase = Buffer.from(opts.passphrase); + else if (Buffer.isBuffer(opts.passphrase)) + passphrase = opts.passphrase; + else + throw new Error('Invalid passphrase'); + + if (opts.cipher === undefined) + throw new Error('Missing cipher name'); + const cipher = ciphers.get(opts.cipher); + if (cipher === undefined) + throw new Error('Invalid cipher name'); + + if (format === 'new') { + let rounds = DEFAULT_ROUNDS; + if (opts.rounds !== undefined) { + if (!Number.isInteger(opts.rounds)) + throw new TypeError('rounds must be an integer'); + if (opts.rounds > 0) + rounds = opts.rounds; + } - if(authSafe.tagClass !== asn1.Class.UNIVERSAL || - authSafe.type !== asn1.Type.SEQUENCE || - authSafe.constructed !== true) { - throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' + - 'SEQUENCE OF ContentInfo'); - } + const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen); + const salt = randomBytes(SALT_LEN); + const r = bcrypt_pbkdf( + passphrase, + passphrase.length, + salt, + salt.length, + gen, + gen.length, + rounds + ); + if (r !== 0) + return new Error('Failed to generate information to encrypt key'); - for(var i = 0; i < authSafe.value.length; i++) { - var contentInfo = authSafe.value[i]; + /* + string salt + uint32 rounds + */ + const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4); + { + let pos = 0; + kdfOptions.writeUInt32BE(salt.length, pos += 0); + kdfOptions.set(salt, pos += 4); + kdfOptions.writeUInt32BE(rounds, pos += salt.length); + } - // validate contentInfo and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { - var error = new Error('Cannot read ContentInfo.'); - error.errors = errors; - throw error; + encrypted = { + cipher, + cipherName: opts.cipher, + kdfName: 'bcrypt', + kdfOptions, + key: gen.slice(0, cipher.keyLen), + iv: gen.slice(cipher.keyLen), + }; + } } + } - var obj = { - encrypted: false - }; - var safeContents = null; - var data = capture.content.value[0]; - switch(asn1.derToOid(capture.contentType)) { - case pki.oids.data: - if(data.tagClass !== asn1.Class.UNIVERSAL || - data.type !== asn1.Type.OCTETSTRING) { - throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.'); + switch (format) { + case 'new': { + let privateB64 = '-----BEGIN OPENSSH PRIVATE KEY-----\n'; + let publicB64; + /* + byte[] "openssh-key-v1\0" + string ciphername + string kdfname + string kdfoptions + uint32 number of keys N + string publickey1 + string encrypted, padded list of private keys + uint32 checkint + uint32 checkint + byte[] privatekey1 + string comment1 + byte 1 + byte 2 + byte 3 + ... + byte padlen % 255 + */ + const cipherName = Buffer.from(encrypted ? encrypted.cipherName : 'none'); + const kdfName = Buffer.from(encrypted ? encrypted.kdfName : 'none'); + const kdfOptions = (encrypted ? encrypted.kdfOptions : Buffer.alloc(0)); + const blockLen = (encrypted ? encrypted.cipher.blockLen : 8); + + const parsed = parseDERs(keyType, pub, priv); + + const checkInt = randomBytes(4); + const commentBin = Buffer.from(comment); + const privBlobLen = (4 + 4 + parsed.priv.length + 4 + commentBin.length); + let padding = []; + for (let i = 1; ((privBlobLen + padding.length) % blockLen); ++i) + padding.push(i & 0xFF); + padding = Buffer.from(padding); + + let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length); + let extra; + { + let pos = 0; + privBlob.set(checkInt, pos += 0); + privBlob.set(checkInt, pos += 4); + privBlob.set(parsed.priv, pos += 4); + privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length); + privBlob.set(commentBin, pos += 4); + privBlob.set(padding, pos += commentBin.length); } - safeContents = _decodePkcs7Data(data).value; - break; - case pki.oids.encryptedData: - safeContents = _decryptSafeContents(data, password); - obj.encrypted = true; - break; - default: - var error = new Error('Unsupported PKCS#12 contentType.'); - error.contentType = asn1.derToOid(capture.contentType); - throw error; - } - obj.safeBags = _decodeSafeContents(safeContents, strict, password); - pfx.safeContents.push(obj); + if (encrypted) { + const options = { authTagLength: encrypted.cipher.authLen }; + const cipher = createCipheriv( + encrypted.cipher.sslName, + encrypted.key, + encrypted.iv, + options + ); + cipher.setAutoPadding(false); + privBlob = Buffer.concat([ cipher.update(privBlob), cipher.final() ]); + if (encrypted.cipher.authLen > 0) + extra = cipher.getAuthTag(); + else + extra = Buffer.alloc(0); + encrypted.key.fill(0); + encrypted.iv.fill(0); + } else { + extra = Buffer.alloc(0); + } + + const magicBytes = Buffer.from('openssh-key-v1\0'); + const privBin = Buffer.allocUnsafe( + magicBytes.length + + 4 + cipherName.length + + 4 + kdfName.length + + 4 + kdfOptions.length + + 4 + + 4 + parsed.pub.length + + 4 + privBlob.length + + extra.length + ); + { + let pos = 0; + privBin.set(magicBytes, pos += 0); + privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length); + privBin.set(cipherName, pos += 4); + privBin.writeUInt32BE(kdfName.length, pos += cipherName.length); + privBin.set(kdfName, pos += 4); + privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length); + privBin.set(kdfOptions, pos += 4); + privBin.writeUInt32BE(1, pos += kdfOptions.length); + privBin.writeUInt32BE(parsed.pub.length, pos += 4); + privBin.set(parsed.pub, pos += 4); + privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length); + privBin.set(privBlob, pos += 4); + privBin.set(extra, pos += privBlob.length); + } + + { + const b64 = privBin.base64Slice(0, privBin.length); + let formatted = b64.replace(/.{64}/g, '$&\n'); + if (b64.length & 63) + formatted += '\n'; + privateB64 += formatted; + } + + { + const b64 = parsed.pub.base64Slice(0, parsed.pub.length); + publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ''}`; + } + + privateB64 += '-----END OPENSSH PRIVATE KEY-----\n'; + return { + private: privateB64, + public: publicB64, + }; + } + default: + throw new Error('Invalid output key format'); } } -/** - * Decrypt PKCS#7 EncryptedData structure. - * - * @param data ASN.1 encoded EncryptedContentInfo object. - * @param password The user-provided password. - * - * @return The decrypted SafeContents (ASN.1 object). - */ -function _decryptSafeContents(data, password) { - var capture = {}; - var errors = []; - if(!asn1.validate( - data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) { - var error = new Error('Cannot read EncryptedContentInfo.'); - error.errors = errors; - throw error; - } +function noop() {} - var oid = asn1.derToOid(capture.contentType); - if(oid !== pki.oids.data) { - var error = new Error( - 'PKCS#12 EncryptedContentInfo ContentType is not Data.'); - error.oid = oid; - throw error; +module.exports = { + generateKeyPair: (keyType, opts, cb) => { + if (typeof opts === 'function') { + cb = opts; + opts = undefined; + } + if (typeof cb !== 'function') + cb = noop; + const args = makeArgs(keyType, opts); + generateKeyPair_(...args, (err, pub, priv) => { + if (err) + return cb(err); + let ret; + try { + ret = convertKeys(args[0], pub, priv, opts); + } catch (ex) { + return cb(ex); + } + cb(null, ret); + }); + }, + generateKeyPairSync: (keyType, opts) => { + const args = makeArgs(keyType, opts); + const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args); + return convertKeys(args[0], pub, priv, opts); } +}; - // get cipher - oid = asn1.derToOid(capture.encAlgorithm); - var cipher = pki.pbe.getCipher(oid, capture.encParameter, password); - // get encrypted data - var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); - var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); +/***/ }), - cipher.update(encrypted); - if(!cipher.finish()) { - throw new Error('Failed to decrypt PKCS#12 SafeContents.'); - } +/***/ 9031: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return cipher.output.getBytes(); -} +"use strict"; +/* + TODO: + * Replace `buffer._pos` usage in keyParser.js and elsewhere + * Utilize optional "writev" support when writing packets from + cipher.encrypt() + * Built-in support for automatic re-keying, on by default + * Revisit receiving unexpected/unknown packets + * Error (fatal or otherwise) or ignore or pass on to user (in some or all + cases)? + * Including server/client check for single directional packet types? + * Check packets for validity or bail as early as possible? + * Automatic re-key every 2**31 packets after the last key exchange (sent or + received), as suggested by RFC4344. OpenSSH currently does this. + * Automatic re-key every so many blocks depending on cipher. RFC4344: + Because of a birthday property of block ciphers and some modes of + operation, implementations must be careful not to encrypt too many + blocks with the same encryption key. -/** - * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects. - * - * The safeContents is a BER-encoded SEQUENCE OF SafeBag. - * - * @param {String} safeContents BER-encoded safeContents. - * @param strict true to use strict DER decoding, false not to. - * @param {String} password Password to decrypt with (optional). - * - * @return {Array} Array of Bag objects. - */ -function _decodeSafeContents(safeContents, strict, password) { - // if strict and no safe contents, return empty safes - if(!strict && safeContents.length === 0) { - return []; - } + Let L be the block length (in bits) of an SSH encryption method's + block cipher (e.g., 128 for AES). If L is at least 128, then, after + rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) + blocks before rekeying again. If L is at least 128, then SSH + implementations should also attempt to force a rekey before receiving + more than 2**(L/4) blocks. If L is less than 128 (which is the case + for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, + although it may be too expensive to rekey every 2**(L/4) blocks, it + is still advisable for SSH implementations to follow the original + recommendation in [RFC4253]: rekey at least once for every gigabyte + of transmitted data. - // actually it's BER-encoded - safeContents = asn1.fromDer(safeContents, strict); + Note that if L is less than or equal to 128, then the recommendation + in this subsection supersedes the recommendation in Section 3.1. If + an SSH implementation uses a block cipher with a larger block size + (e.g., Rijndael with 256-bit blocks), then the recommendations in + Section 3.1 may supersede the recommendations in this subsection + (depending on the lengths of the packets). +*/ - if(safeContents.tagClass !== asn1.Class.UNIVERSAL || - safeContents.type !== asn1.Type.SEQUENCE || - safeContents.constructed !== true) { - throw new Error( - 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.'); - } - var res = []; - for(var i = 0; i < safeContents.value.length; i++) { - var safeBag = safeContents.value[i]; - // validate SafeBag and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) { - var error = new Error('Cannot read SafeBag.'); - error.errors = errors; - throw error; - } +const { inspect } = __nccwpck_require__(3837); + +const { bindingAvailable, NullCipher, NullDecipher } = __nccwpck_require__(5708); +const { + COMPAT_CHECKS, + DISCONNECT_REASON, + eddsaSupported, + MESSAGE, + SIGNALS, + TERMINAL_MODE, +} = __nccwpck_require__(6832); +const { + DEFAULT_KEXINIT_CLIENT, + DEFAULT_KEXINIT_SERVER, + KexInit, + kexinit, + onKEXPayload, +} = __nccwpck_require__(4126); +const { + parseKey, +} = __nccwpck_require__(2218); +const MESSAGE_HANDLERS = __nccwpck_require__(172); +const { + bufferCopy, + bufferFill, + bufferSlice, + convertSignature, + sendPacket, + writeUInt32BE, +} = __nccwpck_require__(9475); +const { + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter, +} = __nccwpck_require__(6715); + +const MODULE_VER = (__nccwpck_require__(6674)/* .version */ .i8); + +const VALID_DISCONNECT_REASONS = new Map( + Object.values(DISCONNECT_REASON).map((n) => [n, 1]) +); +const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); +const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); +const MAX_LINE_LEN = 8192; +const MAX_LINES = 1024; +const PING_PAYLOAD = Buffer.from([ + MESSAGE.GLOBAL_REQUEST, + // "keepalive@openssh.com" + 0, 0, 0, 21, + 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, + 115, 104, 46, 99, 111, 109, + // Request a reply + 1, +]); +const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); + +function noop() {} + +/* + Inbound: + * kexinit payload (needed only until exchange hash is generated) + * raw ident + * rekey packet queue + * expected packet (implemented as separate _parse() function?) + Outbound: + * kexinit payload (needed only until exchange hash is generated) + * rekey packet queue + * kex secret (needed only until NEWKEYS) + * exchange hash (needed only until NEWKEYS) + * session ID (set to exchange hash from initial handshake) +*/ +class Protocol { + constructor(config) { + const onWrite = config.onWrite; + if (typeof onWrite !== 'function') + throw new Error('Missing onWrite function'); + this._onWrite = (data) => { onWrite(data); }; + + const onError = config.onError; + if (typeof onError !== 'function') + throw new Error('Missing onError function'); + this._onError = (err) => { onError(err); }; + + const debug = config.debug; + this._debug = (typeof debug === 'function' + ? (msg) => { debug(msg); } + : undefined); - /* Create bag object and push to result array. */ - var bag = { - type: asn1.derToOid(capture.bagId), - attributes: _decodeBagAttributes(capture.bagAttributes) - }; - res.push(bag); + const onHeader = config.onHeader; + this._onHeader = (typeof onHeader === 'function' + ? (...args) => { onHeader(...args); } + : noop); - var validator, decoder; - var bagAsn1 = capture.bagValue.value[0]; - switch(bag.type) { - case pki.oids.pkcs8ShroudedKeyBag: - /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt. - Afterwards we can handle it like a keyBag, - which is a PrivateKeyInfo. */ - bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password); - if(bagAsn1 === null) { - throw new Error( - 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?'); - } + const onPacket = config.onPacket; + this._onPacket = (typeof onPacket === 'function' + ? () => { onPacket(); } + : noop); - /* fall through */ - case pki.oids.keyBag: - /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our - PKI module, hence we don't have to do validation/capturing here, - just pass what we already got. */ - try { - bag.key = pki.privateKeyFromAsn1(bagAsn1); - } catch(e) { - // ignore unknown key type, pass asn1 value - bag.key = null; - bag.asn1 = bagAsn1; - } - continue; /* Nothing more to do. */ + let onHandshakeComplete = config.onHandshakeComplete; + if (typeof onHandshakeComplete !== 'function') + onHandshakeComplete = noop; + let firstHandshake; + this._onHandshakeComplete = (...args) => { + this._debug && this._debug('Handshake completed'); + if (firstHandshake === undefined) + firstHandshake = true; + else + firstHandshake = false; - case pki.oids.certBag: - /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates. - Therefore put the SafeBag content through another validator to - capture the fields. Afterwards check & store the results. */ - validator = certBagValidator; - decoder = function() { - if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) { - var error = new Error( - 'Unsupported certificate type, only X.509 supported.'); - error.oid = asn1.derToOid(capture.certId); - throw error; - } + // Process packets queued during a rekey where necessary + const oldQueue = this._queue; + if (oldQueue) { + this._queue = undefined; + this._debug && this._debug( + `Draining outbound queue (${oldQueue.length}) ...` + ); + for (let i = 0; i < oldQueue.length; ++i) { + const data = oldQueue[i]; + // data === payload only - // true=produce cert hash - var certAsn1 = asn1.fromDer(capture.cert, strict); - try { - bag.cert = pki.certificateFromAsn1(certAsn1, true); - } catch(e) { - // ignore unknown cert type, pass asn1 value - bag.cert = null; - bag.asn1 = certAsn1; + // XXX: hacky + let finalized = this._packetRW.write.finalize(data); + if (finalized === data) { + const packet = this._cipher.allocPacket(data.length); + packet.set(data, 5); + finalized = packet; } - }; - break; - default: - var error = new Error('Unsupported PKCS#12 SafeBag type.'); - error.oid = bag.type; - throw error; - } + sendPacket(this, finalized); + } + this._debug && this._debug('... finished draining outbound queue'); + } - /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */ - if(validator !== undefined && - !asn1.validate(bagAsn1, validator, capture, errors)) { - var error = new Error('Cannot read PKCS#12 ' + validator.name); - error.errors = errors; - throw error; - } + if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled) + sendExtInfo(this); - /* Call decoder function from above to store the results. */ - decoder(); - } + onHandshakeComplete(...args); + }; + this._queue = undefined; - return res; -} + const messageHandlers = config.messageHandlers; + if (typeof messageHandlers === 'object' && messageHandlers !== null) + this._handlers = messageHandlers; + else + this._handlers = {}; -/** - * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object. - * - * @param attributes SET OF PKCS12Attribute (ASN.1 object). - * - * @return the decoded attributes. - */ -function _decodeBagAttributes(attributes) { - var decodedAttrs = {}; + this._onPayload = onPayload.bind(this); - if(attributes !== undefined) { - for(var i = 0; i < attributes.length; ++i) { - var capture = {}; - var errors = []; - if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#12 BagAttribute.'); - error.errors = errors; - throw error; - } + this._server = !!config.server; + this._banner = undefined; + let greeting; + if (this._server) { + if (typeof config.hostKeys !== 'object' || config.hostKeys === null) + throw new Error('Missing server host key(s)'); + this._hostKeys = config.hostKeys; - var oid = asn1.derToOid(capture.oid); - if(pki.oids[oid] === undefined) { - // unsupported attribute type, ignore. - continue; + // Greeting displayed before the ssh identification string is sent, this + // is usually ignored by most clients + if (typeof config.greeting === 'string' && config.greeting.length) { + greeting = (config.greeting.slice(-2) === '\r\n' + ? config.greeting + : `${config.greeting}\r\n`); } - decodedAttrs[pki.oids[oid]] = []; - for(var j = 0; j < capture.values.length; ++j) { - decodedAttrs[pki.oids[oid]].push(capture.values[j].value); + // Banner shown after the handshake completes, but before user + // authentication begins + if (typeof config.banner === 'string' && config.banner.length) { + this._banner = (config.banner.slice(-2) === '\r\n' + ? config.banner + : `${config.banner}\r\n`); } + } else { + this._hostKeys = undefined; } - } - - return decodedAttrs; -} - -/** - * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a - * password is provided then the private key will be encrypted. - * - * An entire certificate chain may also be included. To do this, pass - * an array for the "cert" parameter where the first certificate is - * the one that is paired with the private key and each subsequent one - * verifies the previous one. The certificates may be in PEM format or - * have been already parsed by Forge. - * - * @todo implement password-based-encryption for the whole package - * - * @param key the private key. - * @param cert the certificate (may be an array of certificates in order - * to specify a certificate chain). - * @param password the password to use, null for none. - * @param options: - * algorithm the encryption algorithm to use - * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. - * count the iteration count to use. - * saltSize the salt size to use. - * useMac true to include a MAC, false not to, defaults to true. - * localKeyId the local key ID to use, in hex. - * friendlyName the friendly name to use. - * generateLocalKeyId true to generate a random local key ID, - * false not to, defaults to true. - * - * @return the PKCS#12 PFX ASN.1 object. - */ -p12.toPkcs12Asn1 = function(key, cert, password, options) { - // set default options - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || options.encAlgorithm || 'aes128'; - if(!('useMac' in options)) { - options.useMac = true; - } - if(!('localKeyId' in options)) { - options.localKeyId = null; - } - if(!('generateLocalKeyId' in options)) { - options.generateLocalKeyId = true; - } - var localKeyId = options.localKeyId; - var bagAttrs; - if(localKeyId !== null) { - localKeyId = forge.util.hexToBytes(localKeyId); - } else if(options.generateLocalKeyId) { - // use SHA-1 of paired cert, if available - if(cert) { - var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; - if(typeof pairedCert === 'string') { - pairedCert = pki.certificateFromPem(pairedCert); + let offer = config.offer; + if (typeof offer !== 'object' || offer === null) { + offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT); + } else if (offer.constructor !== KexInit) { + if (this._server) { + offer.kex = offer.kex.concat(['kex-strict-s-v00@openssh.com']); + } else { + offer.kex = offer.kex.concat([ + 'ext-info-c', + 'kex-strict-c-v00@openssh.com', + ]); } - var sha1 = forge.md.sha1.create(); - sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()); - localKeyId = sha1.digest().getBytes(); - } else { - // FIXME: consider using SHA-1 of public key (which can be generated - // from private key components), see: cert.generateSubjectKeyIdentifier - // generate random bytes - localKeyId = forge.random.getBytes(20); + offer = new KexInit(offer); } - } - - var attrs = []; - if(localKeyId !== null) { - attrs.push( - // localKeyID - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.localKeyId).getBytes()), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - localKeyId) - ]) - ])); - } - if('friendlyName' in options) { - attrs.push( - // friendlyName - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.friendlyName).getBytes()), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false, - options.friendlyName) - ]) - ])); - } + this._kex = undefined; + this._strictMode = undefined; + this._kexinit = undefined; + this._offer = offer; + this._cipher = new NullCipher(0, this._onWrite); + this._decipher = undefined; + this._skipNextInboundPacket = false; + this._packetRW = { + read: new PacketReader(), + write: new PacketWriter(this), + }; + this._hostVerifier = (!this._server + && typeof config.hostVerifier === 'function' + ? config.hostVerifier + : undefined); - if(attrs.length > 0) { - bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); - } + this._parse = parseHeader; + this._buffer = undefined; + this._authsQueue = []; + this._authenticated = false; + this._remoteIdentRaw = undefined; + let sentIdent; + if (typeof config.ident === 'string') { + this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); - // collect contents for AuthenticatedSafe - var contents = []; + sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); + sentIdent.set(this._identRaw, 0); + sentIdent[sentIdent.length - 2] = 13; // '\r' + sentIdent[sentIdent.length - 1] = 10; // '\n' + } else if (Buffer.isBuffer(config.ident)) { + const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); + fullIdent.latin1Write('SSH-2.0-', 0, 8); + fullIdent.set(config.ident, 8); + this._identRaw = fullIdent; - // create safe bag(s) for certificate chain - var chain = []; - if(cert !== null) { - if(forge.util.isArray(cert)) { - chain = cert; + sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); + sentIdent.set(fullIdent, 0); + sentIdent[sentIdent.length - 2] = 13; // '\r' + sentIdent[sentIdent.length - 1] = 10; // '\n' } else { - chain = [cert]; - } - } - - var certSafeBags = []; - for(var i = 0; i < chain.length; ++i) { - // convert cert from PEM as necessary - cert = chain[i]; - if(typeof cert === 'string') { - cert = pki.certificateFromPem(cert); + this._identRaw = IDENT_RAW; + sentIdent = IDENT; } + this._compatFlags = 0; - // SafeBag - var certBagAttrs = (i === 0) ? bagAttrs : undefined; - var certAsn1 = pki.certificateToAsn1(cert); - var certSafeBag = - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.certBag).getBytes()), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // CertBag - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // certId - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.x509Certificate).getBytes()), - // certValue (x509Certificate) - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - asn1.toDer(certAsn1).getBytes()) - ])])]), - // bagAttributes (OPTIONAL) - certBagAttrs - ]); - certSafeBags.push(certSafeBag); - } - - if(certSafeBags.length > 0) { - // SafeContents - var certSafeContents = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags); - - // ContentInfo - var certCI = - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes()), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - asn1.toDer(certSafeContents).getBytes()) - ]) - ]); - contents.push(certCI); - } - - // create safe contents for private key - var keyBag = null; - if(key !== null) { - // SafeBag - var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key)); - if(password === null) { - // no encryption - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.keyBag).getBytes()), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // PrivateKeyInfo - pkAsn1 - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } else { - // encrypted PrivateKeyInfo - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // EncryptedPrivateKeyInfo - pki.encryptPrivateKeyInfo(pkAsn1, password, options) - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); + if (this._debug) { + if (bindingAvailable) + this._debug('Custom crypto binding available'); + else + this._debug('Custom crypto binding not available'); } - // SafeContents - var keySafeContents = - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); - - // ContentInfo - var keyCI = - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes()), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - asn1.toDer(keySafeContents).getBytes()) - ]) - ]); - contents.push(keyCI); + this._debug && this._debug( + `Local ident: ${inspect(this._identRaw.toString())}` + ); + this.start = () => { + this.start = undefined; + if (greeting) + this._onWrite(greeting); + this._onWrite(sentIdent); + }; } - - // create AuthenticatedSafe by stringing together the contents - var safe = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents); - - var macData; - if(options.useMac) { - // MacData - var sha1 = forge.md.sha1.create(); - var macSalt = new forge.util.ByteBuffer( - forge.random.getBytes(options.saltSize)); - var count = options.count; - // 160-bit key - var key = p12.generateKey(password, macSalt, 3, count, 20); - var mac = forge.hmac.create(); - mac.start(sha1, key); - mac.update(asn1.toDer(safe).getBytes()); - var macValue = mac.getMac(); - macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // mac DigestInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm = SHA-1 - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.sha1).getBytes()), - // parameters = Null - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]), - // digest - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, - false, macValue.getBytes()) - ]), - // macSalt OCTET STRING - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()), - // iterations INTEGER (XXX: Only support count < 65536) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(count).getBytes() - ) - ]); + _destruct(reason) { + this._packetRW.read.cleanup(); + this._packetRW.write.cleanup(); + this._cipher && this._cipher.free(); + this._decipher && this._decipher.free(); + if (typeof reason !== 'string' || reason.length === 0) + reason = 'fatal error'; + this.parse = () => { + throw new Error(`Instance unusable after ${reason}`); + }; + this._onWrite = () => { + throw new Error(`Instance unusable after ${reason}`); + }; + this._destruct = undefined; + } + cleanup() { + this._destruct && this._destruct(); + } + parse(chunk, i, len) { + while (i < len) + i = this._parse(chunk, i, len); } - // PFX - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (3) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(3).getBytes()), - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes()), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - asn1.toDer(safe).getBytes()) - ]) - ]), - macData - ]); -}; + // Protocol message API -/** - * Derives a PKCS#12 key. - * - * @param password the password to derive the key material from, null or - * undefined for none. - * @param salt the salt, as a ByteBuffer, to use. - * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). - * @param iter the iteration count. - * @param n the number of bytes to derive from the password. - * @param md the message digest to use, defaults to SHA-1. - * - * @return a ByteBuffer with the bytes derived from the password. - */ -p12.generateKey = forge.pbe.generatePkcs12Key; + // =========================================================================== + // Common/Shared ============================================================= + // =========================================================================== + // Global + // ------ + disconnect(reason) { + const pktLen = 1 + 4 + 4 + 4; + // We don't use _packetRW.write.* here because we need to make sure that + // we always get a full packet allocated because this message can be sent + // at any time -- even during a key exchange + let p = this._packetRW.write.allocStartKEX; + const packet = this._packetRW.write.alloc(pktLen, true); + const end = p + pktLen; -/***/ }), + if (!VALID_DISCONNECT_REASONS.has(reason)) + reason = DISCONNECT_REASON.PROTOCOL_ERROR; -/***/ 4829: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + packet[p] = MESSAGE.DISCONNECT; + writeUInt32BE(packet, reason, ++p); + packet.fill(0, p += 4, end); -/** - * Javascript implementation of PKCS#7 v1.5. - * - * @author Stefan Siegl - * @author Dave Longley - * - * Copyright (c) 2012 Stefan Siegl - * Copyright (c) 2012-2015 Digital Bazaar, Inc. - * - * Currently this implementation only supports ContentType of EnvelopedData, - * EncryptedData, or SignedData at the root level. The top level elements may - * contain only a ContentInfo of ContentType Data, i.e. plain data. Further - * nesting is not (yet) supported. - * - * The Forge validators for PKCS #7's ASN.1 structures are available from - * a separate file pkcs7asn1.js, since those are referenced from other - * PKCS standards like PKCS #12. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7994); -__nccwpck_require__(9549); -__nccwpck_require__(7157); -__nccwpck_require__(1925); -__nccwpck_require__(154); -__nccwpck_require__(266); -__nccwpck_require__(7821); -__nccwpck_require__(8339); -__nccwpck_require__(8180); + this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); + sendPacket(this, this._packetRW.write.finalize(packet, true), true); + } + ping() { + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); -// shortcut for ASN.1 API -var asn1 = forge.asn1; + packet.set(PING_PAYLOAD, p); -// shortcut for PKCS#7 API -var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {}; + this._debug && this._debug( + 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + rekey() { + if (this._kexinit === undefined) { + this._debug && this._debug('Outbound: Initiated explicit rekey'); + this._queue = []; + kexinit(this); + } else { + this._debug && this._debug('Outbound: Ignoring rekey during handshake'); + } + } -/** - * Converts a PKCS#7 message from PEM format. - * - * @param pem the PEM-formatted PKCS#7 message. - * - * @return the PKCS#7 message. - */ -p7.messageFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; + // 'ssh-connection' service-specific + // --------------------------------- + requestSuccess(data) { + let p = this._packetRW.write.allocStart; + let packet; + if (Buffer.isBuffer(data)) { + packet = this._packetRW.write.alloc(1 + data.length); - if(msg.type !== 'PKCS7') { - var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' + - 'header type is not "PKCS#7".'); - error.headerType = msg.type; - throw error; + packet[p] = MESSAGE.REQUEST_SUCCESS; + + packet.set(data, ++p); + } else { + packet = this._packetRW.write.alloc(1); + + packet[p] = MESSAGE.REQUEST_SUCCESS; + } + + this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); + sendPacket(this, this._packetRW.write.finalize(packet)); } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.'); + requestFailure() { + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1); + + packet[p] = MESSAGE.REQUEST_FAILURE; + + this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); + sendPacket(this, this._packetRW.write.finalize(packet)); } + channelSuccess(chan) { + // Does not consume window space - // convert DER to ASN.1 object - var obj = asn1.fromDer(msg.body); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); - return p7.messageFromAsn1(obj); -}; + packet[p] = MESSAGE.CHANNEL_SUCCESS; -/** - * Converts a PKCS#7 message to PEM format. - * - * @param msg The PKCS#7 message object - * @param maxline The maximum characters per line, defaults to 64. - * - * @return The PEM-formatted PKCS#7 message. - */ -p7.messageToPem = function(msg, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var pemObj = { - type: 'PKCS7', - body: asn1.toDer(msg.toAsn1()).getBytes() - }; - return forge.pem.encode(pemObj, {maxline: maxline}); -}; + writeUInt32BE(packet, chan, ++p); -/** - * Converts a PKCS#7 message from an ASN.1 object. - * - * @param obj the ASN.1 representation of a ContentInfo. - * - * @return the PKCS#7 message. - */ -p7.messageFromAsn1 = function(obj) { - // validate root level ContentInfo and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#7 message. ' + - 'ASN.1 object is not an PKCS#7 ContentInfo.'); - error.errors = errors; - throw error; + this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); } + channelFailure(chan) { + // Does not consume window space - var contentType = asn1.derToOid(capture.contentType); - var msg; - - switch(contentType) { - case forge.pki.oids.envelopedData: - msg = p7.createEnvelopedData(); - break; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); - case forge.pki.oids.encryptedData: - msg = p7.createEncryptedData(); - break; + packet[p] = MESSAGE.CHANNEL_FAILURE; - case forge.pki.oids.signedData: - msg = p7.createSignedData(); - break; + writeUInt32BE(packet, chan, ++p); - default: - throw new Error('Cannot read PKCS#7 message. ContentType with OID ' + - contentType + ' is not (yet) supported.'); + this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); } + channelEOF(chan) { + // Does not consume window space - msg.fromAsn1(capture.content.value[0]); - return msg; -}; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); -p7.createSignedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.signedData, - version: 1, - certificates: [], - crls: [], - // TODO: add json-formatted signer stuff here? - signers: [], - // populated during sign() - digestAlgorithmIdentifiers: [], - contentInfo: null, - signerInfos: [], + packet[p] = MESSAGE.CHANNEL_EOF; - fromAsn1: function(obj) { - // validate SignedData content block and capture data. - _fromAsn1(msg, obj, p7.asn1.signedDataValidator); - msg.certificates = []; - msg.crls = []; - msg.digestAlgorithmIdentifiers = []; - msg.contentInfo = null; - msg.signerInfos = []; + writeUInt32BE(packet, chan, ++p); - if(msg.rawCapture.certificates) { - var certs = msg.rawCapture.certificates.value; - for(var i = 0; i < certs.length; ++i) { - msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); - } - } + this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelClose(chan) { + // Does not consume window space - // TODO: parse crls - }, + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); - toAsn1: function() { - // degenerate case with no content - if(!msg.contentInfo) { - msg.sign(); - } + packet[p] = MESSAGE.CHANNEL_CLOSE; - var certs = []; - for(var i = 0; i < msg.certificates.length; ++i) { - certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); - } + writeUInt32BE(packet, chan, ++p); - var crls = []; - // TODO: implement CRLs + this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelWindowAdjust(chan, amount) { + // Does not consume window space - // [0] SignedData - var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(msg.version).getBytes()), - // DigestAlgorithmIdentifiers - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SET, true, - msg.digestAlgorithmIdentifiers), - // ContentInfo - msg.contentInfo - ]) - ]); - if(certs.length > 0) { - // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)); - } - if(crls.length > 0) { - // [1] IMPLICIT CertificateRevocationLists OPTIONAL - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)); - } - // SignerInfos - signedData.value[0].value.push( - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, - msg.signerInfos)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4); - // ContentInfo - return asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(msg.type).getBytes()), - // [0] SignedData - signedData - ]); - }, + packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; - /** - * Add (another) entity to list of signers. - * - * Note: If authenticatedAttributes are provided, then, per RFC 2315, - * they must include at least two attributes: content type and - * message digest. The message digest attribute value will be - * auto-calculated during signing and will be ignored if provided. - * - * Here's an example of providing these two attributes: - * - * forge.pkcs7.createSignedData(); - * p7.addSigner({ - * issuer: cert.issuer.attributes, - * serialNumber: cert.serialNumber, - * key: privateKey, - * digestAlgorithm: forge.pki.oids.sha1, - * authenticatedAttributes: [{ - * type: forge.pki.oids.contentType, - * value: forge.pki.oids.data - * }, { - * type: forge.pki.oids.messageDigest - * }] - * }); - * - * TODO: Support [subjectKeyIdentifier] as signer's ID. - * - * @param signer the signer information: - * key the signer's private key. - * [certificate] a certificate containing the public key - * associated with the signer's private key; use this option as - * an alternative to specifying signer.issuer and - * signer.serialNumber. - * [issuer] the issuer attributes (eg: cert.issuer.attributes). - * [serialNumber] the signer's certificate's serial number in - * hexadecimal (eg: cert.serialNumber). - * [digestAlgorithm] the message digest OID, as a string, to use - * (eg: forge.pki.oids.sha1). - * [authenticatedAttributes] an optional array of attributes - * to also sign along with the content. - */ - addSigner: function(signer) { - var issuer = signer.issuer; - var serialNumber = signer.serialNumber; - if(signer.certificate) { - var cert = signer.certificate; - if(typeof cert === 'string') { - cert = forge.pki.certificateFromPem(cert); - } - issuer = cert.issuer.attributes; - serialNumber = cert.serialNumber; - } - var key = signer.key; - if(!key) { - throw new Error( - 'Could not add PKCS#7 signer; no private key specified.'); - } - if(typeof key === 'string') { - key = forge.pki.privateKeyFromPem(key); - } + writeUInt32BE(packet, chan, ++p); - // ensure OID known for digest algorithm - var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; - switch(digestAlgorithm) { - case forge.pki.oids.sha1: - case forge.pki.oids.sha256: - case forge.pki.oids.sha384: - case forge.pki.oids.sha512: - case forge.pki.oids.md5: - break; - default: - throw new Error( - 'Could not add PKCS#7 signer; unknown message digest algorithm: ' + - digestAlgorithm); - } + writeUInt32BE(packet, amount, p += 4); - // if authenticatedAttributes is present, then the attributes - // must contain at least PKCS #9 content-type and message-digest - var authenticatedAttributes = signer.authenticatedAttributes || []; - if(authenticatedAttributes.length > 0) { - var contentType = false; - var messageDigest = false; - for(var i = 0; i < authenticatedAttributes.length; ++i) { - var attr = authenticatedAttributes[i]; - if(!contentType && attr.type === forge.pki.oids.contentType) { - contentType = true; - if(messageDigest) { - break; - } - continue; - } - if(!messageDigest && attr.type === forge.pki.oids.messageDigest) { - messageDigest = true; - if(contentType) { - break; - } - continue; - } - } + this._debug && this._debug( + `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelData(chan, data) { + const isBuffer = Buffer.isBuffer(data); + const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); - if(!contentType || !messageDigest) { - throw new Error('Invalid signer.authenticatedAttributes. If ' + - 'signer.authenticatedAttributes is specified, then it must ' + - 'contain at least two attributes, PKCS #9 content-type and ' + - 'PKCS #9 message-digest.'); - } - } + packet[p] = MESSAGE.CHANNEL_DATA; - msg.signers.push({ - key: key, - version: 1, - issuer: issuer, - serialNumber: serialNumber, - digestAlgorithm: digestAlgorithm, - signatureAlgorithm: forge.pki.oids.rsaEncryption, - signature: null, - authenticatedAttributes: authenticatedAttributes, - unauthenticatedAttributes: [] - }); - }, + writeUInt32BE(packet, chan, ++p); - /** - * Signs the content. - * @param options Options to apply when signing: - * [detached] boolean. If signing should be done in detached mode. Defaults to false. - */ - sign: function(options) { - options = options || {}; - // auto-generate content info - if(typeof msg.content !== 'object' || msg.contentInfo === null) { - // use Data ContentInfo - msg.contentInfo = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(forge.pki.oids.data).getBytes()) - ]); + writeUInt32BE(packet, dataLen, p += 4); - // add actual content, if present - if('content' in msg) { - var content; - if(msg.content instanceof forge.util.ByteBuffer) { - content = msg.content.bytes(); - } else if(typeof msg.content === 'string') { - content = forge.util.encodeUtf8(msg.content); - } + if (isBuffer) + packet.set(data, p += 4); + else + packet.utf8Write(data, p += 4, dataLen); - if (options.detached) { - msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); - } else { - msg.contentInfo.value.push( - // [0] EXPLICIT content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - content) - ])); - } - } - } + this._debug && this._debug( + `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelExtData(chan, data, type) { + const isBuffer = Buffer.isBuffer(data); + const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); - // no signers, return early (degenerate case for certificate container) - if(msg.signers.length === 0) { - return; - } + packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; - // generate digest algorithm identifiers - var mds = addDigestAlgorithmIds(); + writeUInt32BE(packet, chan, ++p); - // generate signerInfos - addSignerInfos(mds); - }, + writeUInt32BE(packet, type, p += 4); - verify: function() { - throw new Error('PKCS#7 signature verification not yet implemented.'); - }, + writeUInt32BE(packet, dataLen, p += 4); - /** - * Add a certificate. - * - * @param cert the certificate to add. - */ - addCertificate: function(cert) { - // convert from PEM - if(typeof cert === 'string') { - cert = forge.pki.certificateFromPem(cert); - } - msg.certificates.push(cert); - }, + if (isBuffer) + packet.set(data, p += 4); + else + packet.utf8Write(data, p += 4, dataLen); - /** - * Add a certificate revokation list. - * - * @param crl the certificate revokation list to add. - */ - addCertificateRevokationList: function(crl) { - throw new Error('PKCS#7 CRL support not yet implemented.'); - } - }; - return msg; + this._debug + && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelOpenConfirm(remote, local, initWindow, maxPacket) { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); - function addDigestAlgorithmIds() { - var mds = {}; + packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; - for(var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - var oid = signer.digestAlgorithm; - if(!(oid in mds)) { - // content digest - mds[oid] = forge.md[forge.pki.oids[oid]].create(); - } - if(signer.authenticatedAttributes.length === 0) { - // no custom attributes to digest; use content message digest - signer.md = mds[oid]; - } else { - // custom attributes to be digested; use own message digest - // TODO: optimize to just copy message digest state if that - // feature is ever supported with message digests - signer.md = forge.md[forge.pki.oids[oid]].create(); - } - } + writeUInt32BE(packet, remote, ++p); - // add unique digest algorithm identifiers - msg.digestAlgorithmIdentifiers = []; - for(var oid in mds) { - msg.digestAlgorithmIdentifiers.push( - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(oid).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ])); - } + writeUInt32BE(packet, local, p += 4); - return mds; - } + writeUInt32BE(packet, initWindow, p += 4); - function addSignerInfos(mds) { - var content; + writeUInt32BE(packet, maxPacket, p += 4); - if (msg.detachedContent) { - // Signature has been made in detached mode. - content = msg.detachedContent; - } else { - // Note: ContentInfo is a SEQUENCE with 2 values, second value is - // the content field and is optional for a ContentInfo but required here - // since signers are present - // get ContentInfo content - content = msg.contentInfo.value[1]; - // skip [0] EXPLICIT content wrapper - content = content.value[0]; - } + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelOpenFail(remote, reason, desc) { + if (typeof desc !== 'string') + desc = ''; - if(!content) { - throw new Error( - 'Could not sign PKCS#7 message; there is no content to sign.'); - } + const descLen = Buffer.byteLength(desc); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); - // get ContentInfo content type - var contentType = asn1.derToOid(msg.contentInfo.value[0].value); + packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; - // serialize content - var bytes = asn1.toDer(content); + writeUInt32BE(packet, remote, ++p); - // skip identifier and length per RFC 2315 9.3 - // skip identifier (1 byte) - bytes.getByte(); - // read and discard length bytes - asn1.getBerValueLength(bytes); - bytes = bytes.getBytes(); + writeUInt32BE(packet, reason, p += 4); - // digest content DER value bytes - for(var oid in mds) { - mds[oid].start().update(bytes); + writeUInt32BE(packet, descLen, p += 4); + + p += 4; + if (descLen) { + packet.utf8Write(desc, p, descLen); + p += descLen; } - // sign content - var signingTime = new Date(); - for(var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; + writeUInt32BE(packet, 0, p); // Empty language tag - if(signer.authenticatedAttributes.length === 0) { - // if ContentInfo content type is not "Data", then - // authenticatedAttributes must be present per RFC 2315 - if(contentType !== forge.pki.oids.data) { - throw new Error( - 'Invalid signer; authenticatedAttributes must be present ' + - 'when the ContentInfo content type is not PKCS#7 Data.'); - } - } else { - // process authenticated attributes - // [0] IMPLICIT - signer.authenticatedAttributesAsn1 = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + this._debug + && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } - // per RFC 2315, attributes are to be digested using a SET container - // not the above [0] IMPLICIT container - var attrsAsn1 = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SET, true, []); + // =========================================================================== + // Client-specific =========================================================== + // =========================================================================== - for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { - var attr = signer.authenticatedAttributes[ai]; - if(attr.type === forge.pki.oids.messageDigest) { - // use content message digest as value - attr.value = mds[signer.digestAlgorithm].digest(); - } else if(attr.type === forge.pki.oids.signingTime) { - // auto-populate signing time if not already set - if(!attr.value) { - attr.value = signingTime; - } - } + // Global + // ------ + service(name) { + if (this._server) + throw new Error('Client-only method called in server mode'); - // convert to ASN.1 and push onto Attributes SET (for signing) and - // onto authenticatedAttributesAsn1 to complete SignedData ASN.1 - // TODO: optimize away duplication - attrsAsn1.value.push(_attributeToAsn1(attr)); - signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); - } + const nameLen = Buffer.byteLength(name); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + nameLen); - // DER-serialize and digest SET OF attributes only - bytes = asn1.toDer(attrsAsn1).getBytes(); - signer.md.start().update(bytes); - } + packet[p] = MESSAGE.SERVICE_REQUEST; - // sign digest - signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5'); - } + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(name, p += 4, nameLen); - // add signer info - msg.signerInfos = _signersToAsn1(msg.signers); + this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); + sendPacket(this, this._packetRW.write.finalize(packet)); } -}; -/** - * Creates an empty PKCS#7 message of type EncryptedData. - * - * @return the message. - */ -p7.createEncryptedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.encryptedData, - version: 0, - encryptedContent: { - algorithm: forge.pki.oids['aes256-CBC'] - }, + // 'ssh-userauth' service-specific + // ------------------------------- + authPassword(username, password, newPassword) { + if (this._server) + throw new Error('Client-only method called in server mode'); - /** - * Reads an EncryptedData content block (in ASN.1 format) - * - * @param obj The ASN.1 representation of the EncryptedData content block - */ - fromAsn1: function(obj) { - // Validate EncryptedData content block and capture data. - _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); - }, + const userLen = Buffer.byteLength(username); + const passLen = Buffer.byteLength(password); + const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen + + (newPassword ? 4 + newPassLen : 0) + ); - /** - * Decrypt encrypted content - * - * @param key The (symmetric) key as a byte buffer - */ - decrypt: function(key) { - if(key !== undefined) { - msg.encryptedContent.key = key; - } - _decryptContent(msg); - } - }; - return msg; -}; + packet[p] = MESSAGE.USERAUTH_REQUEST; -/** - * Creates an empty PKCS#7 message of type EnvelopedData. - * - * @return the message. - */ -p7.createEnvelopedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.envelopedData, - version: 0, - recipients: [], - encryptedContent: { - algorithm: forge.pki.oids['aes256-CBC'] - }, + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); - /** - * Reads an EnvelopedData content block (in ASN.1 format) - * - * @param obj the ASN.1 representation of the EnvelopedData content block. - */ - fromAsn1: function(obj) { - // validate EnvelopedData content block and capture data - var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); - msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); - }, + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); - toAsn1: function() { - // ContentInfo - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(msg.type).getBytes()), - // [0] EnvelopedData - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(msg.version).getBytes()), - // RecipientInfos - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, - _recipientsToAsn1(msg.recipients)), - // EncryptedContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, - _encryptedContentToAsn1(msg.encryptedContent)) - ]) - ]) - ]); - }, + writeUInt32BE(packet, 8, p += 14); + packet.utf8Write('password', p += 4, 8); - /** - * Find recipient by X.509 certificate's issuer. - * - * @param cert the certificate with the issuer to look for. - * - * @return the recipient object. - */ - findRecipient: function(cert) { - var sAttr = cert.issuer.attributes; + packet[p += 8] = (newPassword ? 1 : 0); - for(var i = 0; i < msg.recipients.length; ++i) { - var r = msg.recipients[i]; - var rAttr = r.issuer; + writeUInt32BE(packet, passLen, ++p); + if (Buffer.isBuffer(password)) + bufferCopy(password, packet, 0, passLen, p += 4); + else + packet.utf8Write(password, p += 4, passLen); - if(r.serialNumber !== cert.serialNumber) { - continue; - } + if (newPassword) { + writeUInt32BE(packet, newPassLen, p += passLen); + if (Buffer.isBuffer(newPassword)) + bufferCopy(newPassword, packet, 0, newPassLen, p += 4); + else + packet.utf8Write(newPassword, p += 4, newPassLen); + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (changed password)' + ); + } else { + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (password)' + ); + } - if(rAttr.length !== sAttr.length) { - continue; - } + this._authsQueue.push('password'); - var match = true; - for(var j = 0; j < sAttr.length; ++j) { - if(rAttr[j].type !== sAttr[j].type || - rAttr[j].value !== sAttr[j].value) { - match = false; - break; - } - } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authPK(username, pubKey, keyAlgo, cbSign) { + if (this._server) + throw new Error('Client-only method called in server mode'); - if(match) { - return r; - } - } + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error('Invalid key'); - return null; - }, + const keyType = pubKey.type; + pubKey = pubKey.getPublicSSH(); - /** - * Decrypt enveloped content - * - * @param recipient The recipient object related to the private key - * @param privKey The (RSA) private key object - */ - decrypt: function(recipient, privKey) { - if(msg.encryptedContent.key === undefined && recipient !== undefined && - privKey !== undefined) { - switch(recipient.encryptedContent.algorithm) { - case forge.pki.oids.rsaEncryption: - case forge.pki.oids.desCBC: - var key = privKey.decrypt(recipient.encryptedContent.content); - msg.encryptedContent.key = forge.util.createBuffer(key); - break; + if (typeof keyAlgo === 'function') { + cbSign = keyAlgo; + keyAlgo = undefined; + } + if (!keyAlgo) + keyAlgo = keyType; - default: - throw new Error('Unsupported asymmetric cipher, ' + - 'OID ' + recipient.encryptedContent.algorithm); - } - } + const userLen = Buffer.byteLength(username); + const algoLen = Buffer.byteLength(keyAlgo); + const pubKeyLen = pubKey.length; + const sessionID = this._kex.sessionID; + const sesLen = sessionID.length; + const payloadLen = + (cbSign ? 4 + sesLen : 0) + + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; + let packet; + let p; + if (cbSign) { + packet = Buffer.allocUnsafe(payloadLen); + p = 0; + writeUInt32BE(packet, sesLen, p); + packet.set(sessionID, p += 4); + p += sesLen; + } else { + packet = this._packetRW.write.alloc(payloadLen); + p = this._packetRW.write.allocStart; + } - _decryptContent(msg); - }, + packet[p] = MESSAGE.USERAUTH_REQUEST; - /** - * Add (another) entity to list of recipients. - * - * @param cert The certificate of the entity to add. - */ - addRecipient: function(cert) { - msg.recipients.push({ - version: 0, - issuer: cert.issuer.attributes, - serialNumber: cert.serialNumber, - encryptedContent: { - // We simply assume rsaEncryption here, since forge.pki only - // supports RSA so far. If the PKI module supports other - // ciphers one day, we need to modify this one as well. - algorithm: forge.pki.oids.rsaEncryption, - key: cert.publicKey - } - }); - }, + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); - /** - * Encrypt enveloped content. - * - * This function supports two optional arguments, cipher and key, which - * can be used to influence symmetric encryption. Unless cipher is - * provided, the cipher specified in encryptedContent.algorithm is used - * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key - * is (re-)used. If that one's not set, a random key will be generated - * automatically. - * - * @param [key] The key to be used for symmetric encryption. - * @param [cipher] The OID of the symmetric cipher to use. - */ - encrypt: function(key, cipher) { - // Part 1: Symmetric encryption - if(msg.encryptedContent.content === undefined) { - cipher = cipher || msg.encryptedContent.algorithm; - key = key || msg.encryptedContent.key; + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); - var keyLen, ivLen, ciphFn; - switch(cipher) { - case forge.pki.oids['aes128-CBC']: - keyLen = 16; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; + writeUInt32BE(packet, 9, p += 14); + packet.utf8Write('publickey', p += 4, 9); - case forge.pki.oids['aes192-CBC']: - keyLen = 24; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; + packet[p += 9] = (cbSign ? 1 : 0); - case forge.pki.oids['aes256-CBC']: - keyLen = 32; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; + writeUInt32BE(packet, algoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, algoLen); - case forge.pki.oids['des-EDE3-CBC']: - keyLen = 24; - ivLen = 8; - ciphFn = forge.des.createEncryptionCipher; - break; + writeUInt32BE(packet, pubKeyLen, p += algoLen); + packet.set(pubKey, p += 4); + + if (!cbSign) { + this._authsQueue.push('publickey'); + + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + return; + } + + cbSign(packet, (signature) => { + signature = convertSignature(signature, keyType); + if (signature === false) + throw new Error('Error while converting handshake signature'); + + const sigLen = signature.length; + p = this._packetRW.write.allocStart; + packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 + + 4 + algoLen + 4 + sigLen + ); + + // TODO: simply copy from original "packet" to new `packet` to avoid + // having to write each individual field a second time? + packet[p] = MESSAGE.USERAUTH_REQUEST; - default: - throw new Error('Unsupported symmetric cipher, OID ' + cipher); - } + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); - if(key === undefined) { - key = forge.util.createBuffer(forge.random.getBytes(keyLen)); - } else if(key.length() != keyLen) { - throw new Error('Symmetric key has wrong length; ' + - 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); - } + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); - // Keep a copy of the key & IV in the object, so the caller can - // use it for whatever reason. - msg.encryptedContent.algorithm = cipher; - msg.encryptedContent.key = key; - msg.encryptedContent.parameter = forge.util.createBuffer( - forge.random.getBytes(ivLen)); + writeUInt32BE(packet, 9, p += 14); + packet.utf8Write('publickey', p += 4, 9); - var ciph = ciphFn(key); - ciph.start(msg.encryptedContent.parameter.copy()); - ciph.update(msg.content); + packet[p += 9] = 1; - // The finish function does PKCS#7 padding by default, therefore - // no action required by us. - if(!ciph.finish()) { - throw new Error('Symmetric encryption failed.'); - } + writeUInt32BE(packet, algoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, algoLen); - msg.encryptedContent.content = ciph.output; - } + writeUInt32BE(packet, pubKeyLen, p += algoLen); + packet.set(pubKey, p += 4); - // Part 2: asymmetric encryption for each recipient - for(var i = 0; i < msg.recipients.length; ++i) { - var recipient = msg.recipients[i]; + writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); - // Nothing to do, encryption already done. - if(recipient.encryptedContent.content !== undefined) { - continue; - } + writeUInt32BE(packet, algoLen, p += 4); + packet.utf8Write(keyAlgo, p += 4, algoLen); - switch(recipient.encryptedContent.algorithm) { - case forge.pki.oids.rsaEncryption: - recipient.encryptedContent.content = - recipient.encryptedContent.key.encrypt( - msg.encryptedContent.key.data); - break; + writeUInt32BE(packet, sigLen, p += algoLen); + packet.set(signature, p += 4); - default: - throw new Error('Unsupported asymmetric cipher, OID ' + - recipient.encryptedContent.algorithm); - } - } - } - }; - return msg; -}; + // Servers shouldn't send packet type 60 in response to signed publickey + // attempts, but if they do, interpret as type 60. + this._authsQueue.push('publickey'); -/** - * Converts a single recipient from an ASN.1 object. - * - * @param obj the ASN.1 RecipientInfo. - * - * @return the recipient object. - */ -function _recipientFromAsn1(obj) { - // validate EnvelopedData content block and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + - 'ASN.1 object is not an PKCS#7 RecipientInfo.'); - error.errors = errors; - throw error; + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (publickey)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + }); } + authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) { + // TODO: Make DRY by sharing similar code with authPK() + if (this._server) + throw new Error('Client-only method called in server mode'); - return { - version: capture.version.charCodeAt(0), - issuer: forge.pki.RDNAttributesAsArray(capture.issuer), - serialNumber: forge.util.createBuffer(capture.serial).toHex(), - encryptedContent: { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: capture.encParameter ? capture.encParameter.value : undefined, - content: capture.encKey - } - }; -} + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error('Invalid key'); -/** - * Converts a single recipient object to an ASN.1 object. - * - * @param obj the recipient object. - * - * @return the ASN.1 RecipientInfo. - */ -function _recipientToAsn1(obj) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(obj.version).getBytes()), - // IssuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Name - forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), - // Serial - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - forge.util.hexToBytes(obj.serialNumber)) - ]), - // KeyEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), - // Parameter, force NULL, only RSA supported for now. - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]), - // EncryptedKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - obj.encryptedContent.content) - ]); -} + const keyType = pubKey.type; + pubKey = pubKey.getPublicSSH(); -/** - * Map a set of RecipientInfo ASN.1 objects to recipient objects. - * - * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF). - * - * @return an array of recipient objects. - */ -function _recipientsFromAsn1(infos) { - var ret = []; - for(var i = 0; i < infos.length; ++i) { - ret.push(_recipientFromAsn1(infos[i])); - } - return ret; -} + if (typeof keyAlgo === 'function') { + cbSign = keyAlgo; + keyAlgo = undefined; + } + if (!keyAlgo) + keyAlgo = keyType; -/** - * Map an array of recipient objects to ASN.1 RecipientInfo objects. - * - * @param recipients an array of recipientInfo objects. - * - * @return an array of ASN.1 RecipientInfos. - */ -function _recipientsToAsn1(recipients) { - var ret = []; - for(var i = 0; i < recipients.length; ++i) { - ret.push(_recipientToAsn1(recipients[i])); - } - return ret; -} + const userLen = Buffer.byteLength(username); + const algoLen = Buffer.byteLength(keyAlgo); + const pubKeyLen = pubKey.length; + const sessionID = this._kex.sessionID; + const sesLen = sessionID.length; + const hostnameLen = Buffer.byteLength(hostname); + const userlocalLen = Buffer.byteLength(userlocal); + const data = Buffer.allocUnsafe( + 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen + + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen + ); + let p = 0; -/** - * Converts a single signer from an ASN.1 object. - * - * @param obj the ASN.1 representation of a SignerInfo. - * - * @return the signer object. - */ -function _signerFromAsn1(obj) { - // validate EnvelopedData content block and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#7 SignerInfo. ' + - 'ASN.1 object is not an PKCS#7 SignerInfo.'); - error.errors = errors; - throw error; - } + writeUInt32BE(data, sesLen, p); + data.set(sessionID, p += 4); - var rval = { - version: capture.version.charCodeAt(0), - issuer: forge.pki.RDNAttributesAsArray(capture.issuer), - serialNumber: forge.util.createBuffer(capture.serial).toHex(), - digestAlgorithm: asn1.derToOid(capture.digestAlgorithm), - signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm), - signature: capture.signature, - authenticatedAttributes: [], - unauthenticatedAttributes: [] - }; + data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; - // TODO: convert attributes - var authenticatedAttributes = capture.authenticatedAttributes || []; - var unauthenticatedAttributes = capture.unauthenticatedAttributes || []; + writeUInt32BE(data, userLen, ++p); + data.utf8Write(username, p += 4, userLen); - return rval; -} + writeUInt32BE(data, 14, p += userLen); + data.utf8Write('ssh-connection', p += 4, 14); -/** - * Converts a single signerInfo object to an ASN.1 object. - * - * @param obj the signerInfo object. - * - * @return the ASN.1 representation of a SignerInfo. - */ -function _signerToAsn1(obj) { - // SignerInfo - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(obj.version).getBytes()), - // issuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // name - forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), - // serial - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - forge.util.hexToBytes(obj.serialNumber)) - ]), - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(obj.digestAlgorithm).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]) - ]); + writeUInt32BE(data, 9, p += 14); + data.utf8Write('hostbased', p += 4, 9); - // authenticatedAttributes (OPTIONAL) - if(obj.authenticatedAttributesAsn1) { - // add ASN.1 previously generated during signing - rval.value.push(obj.authenticatedAttributesAsn1); - } + writeUInt32BE(data, algoLen, p += 9); + data.utf8Write(keyAlgo, p += 4, algoLen); - // digestEncryptionAlgorithm - rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(obj.signatureAlgorithm).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ])); + writeUInt32BE(data, pubKeyLen, p += algoLen); + data.set(pubKey, p += 4); - // encryptedDigest - rval.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); + writeUInt32BE(data, hostnameLen, p += pubKeyLen); + data.utf8Write(hostname, p += 4, hostnameLen); - // unauthenticatedAttributes (OPTIONAL) - if(obj.unauthenticatedAttributes.length > 0) { - // [1] IMPLICIT - var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); - for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { - var attr = obj.unauthenticatedAttributes[i]; - attrsAsn1.values.push(_attributeToAsn1(attr)); - } - rval.value.push(attrsAsn1); - } + writeUInt32BE(data, userlocalLen, p += hostnameLen); + data.utf8Write(userlocal, p += 4, userlocalLen); - return rval; -} + cbSign(data, (signature) => { + signature = convertSignature(signature, keyType); + if (!signature) + throw new Error('Error while converting handshake signature'); -/** - * Map a set of SignerInfo ASN.1 objects to an array of signer objects. - * - * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF). - * - * @return an array of signers objects. - */ -function _signersFromAsn1(signerInfoAsn1s) { - var ret = []; - for(var i = 0; i < signerInfoAsn1s.length; ++i) { - ret.push(_signerFromAsn1(signerInfoAsn1s[i])); - } - return ret; -} + const sigLen = signature.length; + const reqDataLen = (data.length - sesLen - 4); + p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + reqDataLen + 4 + 4 + algoLen + 4 + sigLen + ); -/** - * Map an array of signer objects to ASN.1 objects. - * - * @param signers an array of signer objects. - * - * @return an array of ASN.1 SignerInfos. - */ -function _signersToAsn1(signers) { - var ret = []; - for(var i = 0; i < signers.length; ++i) { - ret.push(_signerToAsn1(signers[i])); - } - return ret; -} + bufferCopy(data, packet, 4 + sesLen, data.length, p); -/** - * Convert an attribute object to an ASN.1 Attribute. - * - * @param attr the attribute object. - * - * @return the ASN.1 Attribute. - */ -function _attributeToAsn1(attr) { - var value; + writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); + writeUInt32BE(packet, algoLen, p += 4); + packet.utf8Write(keyAlgo, p += 4, algoLen); + writeUInt32BE(packet, sigLen, p += algoLen); + packet.set(signature, p += 4); - // TODO: generalize to support more attributes - if(attr.type === forge.pki.oids.contentType) { - value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(attr.value).getBytes()); - } else if(attr.type === forge.pki.oids.messageDigest) { - value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - attr.value.bytes()); - } else if(attr.type === forge.pki.oids.signingTime) { - /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049 - (inclusive) MUST be encoded as UTCTime. Any dates with year values - before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,] - UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST - include seconds (i.e., times are YYMMDDHHMMSSZ), even where the - number of seconds is zero. Midnight (GMT) must be represented as - "YYMMDD000000Z". */ - // TODO: make these module-level constants - var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); - var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); - var date = attr.value; - if(typeof date === 'string') { - // try to parse date - var timestamp = Date.parse(date); - if(!isNaN(timestamp)) { - date = new Date(timestamp); - } else if(date.length === 13) { - // YYMMDDHHMMSSZ (13 chars for UTCTime) - date = asn1.utcTimeToDate(date); - } else { - // assume generalized time - date = asn1.generalizedTimeToDate(date); - } - } + this._authsQueue.push('hostbased'); - if(date >= jan_1_1950 && date < jan_1_2050) { - value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, - asn1.dateToUtcTime(date)); - } else { - value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, - asn1.dateToGeneralizedTime(date)); - } + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (hostbased)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + }); } + authKeyboard(username) { + if (this._server) + throw new Error('Client-only method called in server mode'); - // TODO: expose as common API call - // create a RelativeDistinguishedName set - // each value in the set is an AttributeTypeAndValue first - // containing the type (an OID) and second the value - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(attr.type).getBytes()), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - value - ]) - ]); -} + const userLen = Buffer.byteLength(username); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 + ); -/** - * Map messages encrypted content to ASN.1 objects. - * - * @param ec The encryptedContent object of the message. - * - * @return ASN.1 representation of the encryptedContent object (SEQUENCE). - */ -function _encryptedContentToAsn1(ec) { - return [ - // ContentType, always Data for the moment - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(forge.pki.oids.data).getBytes()), - // ContentEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(ec.algorithm).getBytes()), - // Parameters (IV) - !ec.parameter ? - undefined : - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - ec.parameter.getBytes()) - ]), - // [0] EncryptedContent - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - ec.content.getBytes()) - ]) - ]; -} + packet[p] = MESSAGE.USERAUTH_REQUEST; -/** - * Reads the "common part" of an PKCS#7 content block (in ASN.1 format) - * - * This function reads the "common part" of the PKCS#7 content blocks - * EncryptedData and EnvelopedData, i.e. version number and symmetrically - * encrypted content block. - * - * The result of the ASN.1 validate and capture process is returned - * to allow the caller to extract further data, e.g. the list of recipients - * in case of a EnvelopedData object. - * - * @param msg the PKCS#7 object to read the data to. - * @param obj the ASN.1 representation of the content block. - * @param validator the ASN.1 structure validator object to use. - * - * @return the value map captured by validator object. - */ -function _fromAsn1(msg, obj, validator) { - var capture = {}; - var errors = []; - if(!asn1.validate(obj, validator, capture, errors)) { - var error = new Error('Cannot read PKCS#7 message. ' + - 'ASN.1 object is not a supported PKCS#7 message.'); - error.errors = error; - throw error; - } + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); - // Check contentType, so far we only support (raw) Data. - var contentType = asn1.derToOid(capture.contentType); - if(contentType !== forge.pki.oids.data) { - throw new Error('Unsupported PKCS#7 message. ' + - 'Only wrapped ContentType Data supported.'); - } + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); - if(capture.encryptedContent) { - var content = ''; - if(forge.util.isArray(capture.encryptedContent)) { - for(var i = 0; i < capture.encryptedContent.length; ++i) { - if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { - throw new Error('Malformed PKCS#7 message, expecting encrypted ' + - 'content constructed of only OCTET STRING objects.'); - } - content += capture.encryptedContent[i].value; - } - } else { - content = capture.encryptedContent; - } - msg.encryptedContent = { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: forge.util.createBuffer(capture.encParameter.value), - content: forge.util.createBuffer(content) - }; - } + writeUInt32BE(packet, 20, p += 14); + packet.utf8Write('keyboard-interactive', p += 4, 20); - if(capture.content) { - var content = ''; - if(forge.util.isArray(capture.content)) { - for(var i = 0; i < capture.content.length; ++i) { - if(capture.content[i].type !== asn1.Type.OCTETSTRING) { - throw new Error('Malformed PKCS#7 message, expecting ' + - 'content constructed of only OCTET STRING objects.'); - } - content += capture.content[i].value; - } - } else { - content = capture.content; - } - msg.content = forge.util.createBuffer(content); - } + writeUInt32BE(packet, 0, p += 20); - msg.version = capture.version.charCodeAt(0); - msg.rawCapture = capture; + writeUInt32BE(packet, 0, p += 4); - return capture; -} + this._authsQueue.push('keyboard-interactive'); -/** - * Decrypt the symmetrically encrypted content block of the PKCS#7 message. - * - * Decryption is skipped in case the PKCS#7 message object already has a - * (decrypted) content attribute. The algorithm, key and cipher parameters - * (probably the iv) are taken from the encryptedContent attribute of the - * message object. - * - * @param The PKCS#7 message object. - */ -function _decryptContent(msg) { - if(msg.encryptedContent.key === undefined) { - throw new Error('Symmetric key not available.'); + this._debug && this._debug( + 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); } + authNone(username) { + if (this._server) + throw new Error('Client-only method called in server mode'); - if(msg.content === undefined) { - var ciph; + const userLen = Buffer.byteLength(username); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); - switch(msg.encryptedContent.algorithm) { - case forge.pki.oids['aes128-CBC']: - case forge.pki.oids['aes192-CBC']: - case forge.pki.oids['aes256-CBC']: - ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); - break; + packet[p] = MESSAGE.USERAUTH_REQUEST; - case forge.pki.oids['desCBC']: - case forge.pki.oids['des-EDE3-CBC']: - ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); - break; + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); - default: - throw new Error('Unsupported symmetric cipher, OID ' + - msg.encryptedContent.algorithm); - } - ciph.start(msg.encryptedContent.parameter); - ciph.update(msg.encryptedContent.content); + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write('ssh-connection', p += 4, 14); - if(!ciph.finish()) { - throw new Error('Symmetric decryption failed.'); - } + writeUInt32BE(packet, 4, p += 14); + packet.utf8Write('none', p += 4, 4); - msg.content = ciph.output; + this._authsQueue.push('none'); + + this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); + sendPacket(this, this._packetRW.write.finalize(packet)); } -} + authInfoRes(responses) { + if (this._server) + throw new Error('Client-only method called in server mode'); + let responsesTotalLen = 0; + let responseLens; -/***/ }), + if (responses) { + responseLens = new Array(responses.length); + for (let i = 0; i < responses.length; ++i) { + const len = Buffer.byteLength(responses[i]); + responseLens[i] = len; + responsesTotalLen += 4 + len; + } + } -/***/ 266: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); -/** - * Javascript implementation of ASN.1 validators for PKCS#7 v1.5. - * - * @author Dave Longley - * @author Stefan Siegl - * - * Copyright (c) 2012-2015 Digital Bazaar, Inc. - * Copyright (c) 2012 Stefan Siegl - * - * The ASN.1 representation of PKCS#7 is as follows - * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt): - * - * A PKCS#7 message consists of a ContentInfo on root level, which may - * contain any number of further ContentInfo nested into it. - * - * ContentInfo ::= SEQUENCE { - * contentType ContentType, - * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL - * } - * - * ContentType ::= OBJECT IDENTIFIER - * - * EnvelopedData ::= SEQUENCE { - * version Version, - * recipientInfos RecipientInfos, - * encryptedContentInfo EncryptedContentInfo - * } - * - * EncryptedData ::= SEQUENCE { - * version Version, - * encryptedContentInfo EncryptedContentInfo - * } - * - * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2) - * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 } - * - * SignedData ::= SEQUENCE { - * version INTEGER, - * digestAlgorithms DigestAlgorithmIdentifiers, - * contentInfo ContentInfo, - * certificates [0] IMPLICIT Certificates OPTIONAL, - * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, - * signerInfos SignerInfos - * } - * - * SignerInfos ::= SET OF SignerInfo - * - * SignerInfo ::= SEQUENCE { - * version Version, - * issuerAndSerialNumber IssuerAndSerialNumber, - * digestAlgorithm DigestAlgorithmIdentifier, - * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, - * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, - * encryptedDigest EncryptedDigest, - * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL - * } - * - * EncryptedDigest ::= OCTET STRING - * - * Attributes ::= SET OF Attribute - * - * Attribute ::= SEQUENCE { - * attrType OBJECT IDENTIFIER, - * attrValues SET OF AttributeValue - * } - * - * AttributeValue ::= ANY - * - * Version ::= INTEGER - * - * RecipientInfos ::= SET OF RecipientInfo - * - * EncryptedContentInfo ::= SEQUENCE { - * contentType ContentType, - * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, - * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL - * } - * - * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier - * - * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters - * for the algorithm, if any. In the case of AES and DES3, there is only one, - * the IV. - * - * AlgorithmIdentifer ::= SEQUENCE { - * algorithm OBJECT IDENTIFIER, - * parameters ANY DEFINED BY algorithm OPTIONAL - * } - * - * EncryptedContent ::= OCTET STRING - * - * RecipientInfo ::= SEQUENCE { - * version Version, - * issuerAndSerialNumber IssuerAndSerialNumber, - * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier, - * encryptedKey EncryptedKey - * } - * - * IssuerAndSerialNumber ::= SEQUENCE { - * issuer Name, - * serialNumber CertificateSerialNumber - * } - * - * CertificateSerialNumber ::= INTEGER - * - * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier - * - * EncryptedKey ::= OCTET STRING - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(9549); -__nccwpck_require__(8339); + packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; -// shortcut for ASN.1 API -var asn1 = forge.asn1; + if (responses) { + writeUInt32BE(packet, responses.length, ++p); + p += 4; + for (let i = 0; i < responses.length; ++i) { + const len = responseLens[i]; + writeUInt32BE(packet, len, p); + p += 4; + if (len) { + packet.utf8Write(responses[i], p, len); + p += len; + } + } + } else { + writeUInt32BE(packet, 0, ++p); + } -// shortcut for PKCS#7 API -var p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; -forge.pkcs7 = forge.pkcs7 || {}; -forge.pkcs7.asn1 = p7v; + this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } -var contentInfoValidator = { - name: 'ContentInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'ContentInfo.ContentType', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'contentType' - }, { - name: 'ContentInfo.content', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - captureAsn1: 'content' - }] -}; -p7v.contentInfoValidator = contentInfoValidator; + // 'ssh-connection' service-specific + // --------------------------------- + tcpipForward(bindAddr, bindPort, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); -var encryptedContentInfoValidator = { - name: 'EncryptedContentInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EncryptedContentInfo.contentType', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'contentType' - }, { - name: 'EncryptedContentInfo.contentEncryptionAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'encAlgorithm' - }, { - name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter', - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: 'encParameter' - }] - }, { - name: 'EncryptedContentInfo.encryptedContent', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - /* The PKCS#7 structure output by OpenSSL somewhat differs from what - * other implementations do generate. - * - * OpenSSL generates a structure like this: - * SEQUENCE { - * ... - * [0] - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * - * Whereas other implementations (and this PKCS#7 module) generate: - * SEQUENCE { - * ... - * [0] { - * OCTET STRING - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * } - * - * In order to support both, we just capture the context specific - * field here. The OCTET STRING bit is removed below. - */ - capture: 'encryptedContent', - captureAsn1: 'encryptedContentAsn1' - }] -}; + const addrLen = Buffer.byteLength(bindAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); -p7v.envelopedDataValidator = { - name: 'EnvelopedData', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EnvelopedData.Version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'version' - }, { - name: 'EnvelopedData.RecipientInfos', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: 'recipientInfos' - }].concat(encryptedContentInfoValidator) -}; + packet[p] = MESSAGE.GLOBAL_REQUEST; -p7v.encryptedDataValidator = { - name: 'EncryptedData', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EncryptedData.Version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'version' - }].concat(encryptedContentInfoValidator) -}; + writeUInt32BE(packet, 13, ++p); + packet.utf8Write('tcpip-forward', p += 4, 13); -var signerValidator = { - name: 'SignerInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SignerInfo.version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false - }, { - name: 'SignerInfo.issuerAndSerialNumber', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SignerInfo.issuerAndSerialNumber.issuer', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'issuer' - }, { - name: 'SignerInfo.issuerAndSerialNumber.serialNumber', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'serial' - }] - }, { - name: 'SignerInfo.digestAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SignerInfo.digestAlgorithm.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'digestAlgorithm' - }, { - name: 'SignerInfo.digestAlgorithm.parameter', - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: 'digestParameter', - optional: true - }] - }, { - name: 'SignerInfo.authenticatedAttributes', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: 'authenticatedAttributes' - }, { - name: 'SignerInfo.digestEncryptionAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - capture: 'signatureAlgorithm' - }, { - name: 'SignerInfo.encryptedDigest', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'signature' - }, { - name: 'SignerInfo.unauthenticatedAttributes', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - capture: 'unauthenticatedAttributes' - }] -}; + packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); -p7v.signedDataValidator = { - name: 'SignedData', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SignedData.Version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'version' - }, { - name: 'SignedData.DigestAlgorithms', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: 'digestAlgorithms' - }, - contentInfoValidator, - { - name: 'SignedData.Certificates', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - optional: true, - captureAsn1: 'certificates' - }, { - name: 'SignedData.CertificateRevocationLists', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - optional: true, - captureAsn1: 'crls' - }, { - name: 'SignedData.SignerInfos', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - capture: 'signerInfos', - optional: true, - value: [signerValidator] - }] -}; + writeUInt32BE(packet, addrLen, ++p); + packet.utf8Write(bindAddr, p += 4, addrLen); -p7v.recipientInfoValidator = { - name: 'RecipientInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'RecipientInfo.version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'version' - }, { - name: 'RecipientInfo.issuerAndSerial', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'RecipientInfo.issuerAndSerial.issuer', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'issuer' - }, { - name: 'RecipientInfo.issuerAndSerial.serialNumber', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'serial' - }] - }, { - name: 'RecipientInfo.keyEncryptionAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'encAlgorithm' - }, { - name: 'RecipientInfo.keyEncryptionAlgorithm.parameter', - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: 'encParameter', - optional: true - }] - }, { - name: 'RecipientInfo.encryptedKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'encKey' - }] -}; + writeUInt32BE(packet, bindPort, p += addrLen); + this._debug + && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + cancelTcpipForward(bindAddr, bindPort, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); -/***/ }), + const addrLen = Buffer.byteLength(bindAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); -/***/ 6924: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + packet[p] = MESSAGE.GLOBAL_REQUEST; -/** - * Javascript implementation of a basic Public Key Infrastructure, including - * support for RSA public and private keys. - * - * @author Dave Longley - * - * Copyright (c) 2010-2013 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(9549); -__nccwpck_require__(1925); -__nccwpck_require__(1281); -__nccwpck_require__(154); -__nccwpck_require__(1611); -__nccwpck_require__(466); -__nccwpck_require__(4376); -__nccwpck_require__(3921); -__nccwpck_require__(8339); -__nccwpck_require__(8180); + writeUInt32BE(packet, 20, ++p); + packet.utf8Write('cancel-tcpip-forward', p += 4, 20); -// shortcut for asn.1 API -var asn1 = forge.asn1; + packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); -/* Public Key Infrastructure (PKI) implementation. */ -var pki = module.exports = forge.pki = forge.pki || {}; + writeUInt32BE(packet, addrLen, ++p); + packet.utf8Write(bindAddr, p += 4, addrLen); -/** - * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead. - * - * Converts PEM-formatted data to DER. - * - * @param pem the PEM-formatted data. - * - * @return the DER-formatted data. - */ -pki.pemToDer = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert PEM to DER; PEM is encrypted.'); + writeUInt32BE(packet, bindPort, p += addrLen); + + this._debug + && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); + sendPacket(this, this._packetRW.write.finalize(packet)); } - return forge.util.createBuffer(msg.body); -}; + openssh_streamLocalForward(socketPath, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); -/** - * Converts an RSA private key from PEM format. - * - * @param pem the PEM-formatted private key. - * - * @return the private key. - */ -pki.privateKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; + const socketPathLen = Buffer.byteLength(socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 31 + 1 + 4 + socketPathLen + ); - if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { - var error = new Error('Could not convert private key from PEM; PEM ' + - 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert private key from PEM; PEM is encrypted.'); + packet[p] = MESSAGE.GLOBAL_REQUEST; + + writeUInt32BE(packet, 31, ++p); + packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); + + packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, socketPathLen, ++p); + packet.utf8Write(socketPath, p += 4, socketPathLen); + + this._debug && this._debug( + 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); } + openssh_cancelStreamLocalForward(socketPath, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); - // convert DER to ASN.1 object - var obj = asn1.fromDer(msg.body); + const socketPathLen = Buffer.byteLength(socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 38 + 1 + 4 + socketPathLen + ); - return pki.privateKeyFromAsn1(obj); -}; + packet[p] = MESSAGE.GLOBAL_REQUEST; -/** - * Converts an RSA private key to PEM format. - * - * @param key the private key. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted private key. - */ -pki.privateKeyToPem = function(key, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'RSA PRIVATE KEY', - body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes() - }; - return forge.pem.encode(msg, {maxline: maxline}); -}; + writeUInt32BE(packet, 38, ++p); + packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); -/** - * Converts a PrivateKeyInfo to PEM format. - * - * @param pki the PrivateKeyInfo. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted private key. - */ -pki.privateKeyInfoToPem = function(pki, maxline) { - // convert to DER, then PEM-encode - var msg = { - type: 'PRIVATE KEY', - body: asn1.toDer(pki).getBytes() - }; - return forge.pem.encode(msg, {maxline: maxline}); -}; + packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); + writeUInt32BE(packet, socketPathLen, ++p); + packet.utf8Write(socketPath, p += 4, socketPathLen); -/***/ }), + if (this._debug) { + this._debug( + 'Outbound: Sending GLOBAL_REQUEST ' + + '(cancel-streamlocal-forward@openssh.com)' + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + directTcpip(chan, initWindow, maxPacket, cfg) { + if (this._server) + throw new Error('Client-only method called in server mode'); -/***/ 6861: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const srcLen = Buffer.byteLength(cfg.srcIP); + const dstLen = Buffer.byteLength(cfg.dstIP); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 + ); -/** - * Prime number generation API. - * - * @author Dave Longley - * - * Copyright (c) 2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); -__nccwpck_require__(7052); -__nccwpck_require__(7821); + packet[p] = MESSAGE.CHANNEL_OPEN; -(function() { + writeUInt32BE(packet, 12, ++p); + packet.utf8Write('direct-tcpip', p += 4, 12); -// forge.prime already defined -if(forge.prime) { - module.exports = forge.prime; - return; -} + writeUInt32BE(packet, chan, p += 12); -/* PRIME API */ -var prime = module.exports = forge.prime = forge.prime || {}; + writeUInt32BE(packet, initWindow, p += 4); -var BigInteger = forge.jsbn.BigInteger; + writeUInt32BE(packet, maxPacket, p += 4); -// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 -var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; -var THIRTY = new BigInteger(null); -THIRTY.fromInt(30); -var op_or = function(x, y) {return x|y;}; + writeUInt32BE(packet, dstLen, p += 4); + packet.utf8Write(cfg.dstIP, p += 4, dstLen); -/** - * Generates a random probable prime with the given number of bits. - * - * Alternative algorithms can be specified by name as a string or as an - * object with custom options like so: - * - * { - * name: 'PRIMEINC', - * options: { - * maxBlockTime: , - * millerRabinTests: , - * workerScript: , - * workers: . - * workLoad: the size of the work load, ie: number of possible prime - * numbers for each web worker to check per work assignment, - * (default: 100). - * } - * } - * - * @param bits the number of bits for the prime number. - * @param options the options to use. - * [algorithm] the algorithm to use (default: 'PRIMEINC'). - * [prng] a custom crypto-secure pseudo-random number generator to use, - * that must define "getBytesSync". - * - * @return callback(err, num) called once the operation completes. - */ -prime.generateProbablePrime = function(bits, options, callback) { - if(typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; + writeUInt32BE(packet, cfg.dstPort, p += dstLen); - // default to PRIMEINC algorithm - var algorithm = options.algorithm || 'PRIMEINC'; - if(typeof algorithm === 'string') { - algorithm = {name: algorithm}; - } - algorithm.options = algorithm.options || {}; + writeUInt32BE(packet, srcLen, p += 4); + packet.utf8Write(cfg.srcIP, p += 4, srcLen); - // create prng with api that matches BigInteger secure random - var prng = options.prng || forge.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for(var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; + writeUInt32BE(packet, cfg.srcPort, p += srcLen); - if(algorithm.name === 'PRIMEINC') { - return primeincFindPrime(bits, rng, algorithm.options, callback); + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); } + openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { + if (this._server) + throw new Error('Client-only method called in server mode'); - throw new Error('Invalid prime generation algorithm: ' + algorithm.name); -}; + const pathLen = Buffer.byteLength(cfg.socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 + ); -function primeincFindPrime(bits, rng, options, callback) { - if('workers' in options) { - return primeincFindPrimeWithWorkers(bits, rng, options, callback); - } - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); -} + packet[p] = MESSAGE.CHANNEL_OPEN; -function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { - // initialize random number - var num = generateRandom(bits, rng); + writeUInt32BE(packet, 30, ++p); + packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); - /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The - number we are given is always aligned at 30k + 1. Each time the number is - determined not to be prime we add to get to the next 'i', eg: if the number - was at 30k + 1 we add 6. */ - var deltaIdx = 0; + writeUInt32BE(packet, chan, p += 30); - // get required number of MR tests - var mrTests = getMillerRabinTests(num.bitLength()); - if('millerRabinTests' in options) { - mrTests = options.millerRabinTests; - } + writeUInt32BE(packet, initWindow, p += 4); - // find prime nearest to 'num' for maxBlockTime ms - // 10 ms gives 5ms of leeway for other calculations before dropping - // below 60fps (1000/60 == 16.67), but in reality, the number will - // likely be higher due to an 'atomic' big int modPow - var maxBlockTime = 10; - if('maxBlockTime' in options) { - maxBlockTime = options.maxBlockTime; - } + writeUInt32BE(packet, maxPacket, p += 4); - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); -} + writeUInt32BE(packet, pathLen, p += 4); + packet.utf8Write(cfg.socketPath, p += 4, pathLen); -function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { - var start = +new Date(); - do { - // overflow, regenerate random number - if(num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - // do primality test - if(num.isProbablePrime(mrTests)) { - return callback(null, num); + // zero-fill reserved fields (string and uint32) + bufferFill(packet, 0, p += pathLen, p + 8); + + if (this._debug) { + this._debug( + 'Outbound: Sending CHANNEL_OPEN ' + + `(r:${chan}, direct-streamlocal@openssh.com)` + ); } - // get next potential prime - num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime)); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_noMoreSessions(wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); - // keep trying later - forge.util.setImmediate(function() { - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - }); -} + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); -// NOTE: This algorithm is indeterminate in nature because workers -// run in parallel looking at different segments of numbers. Even if this -// algorithm is run twice with the same input from a predictable RNG, it -// may produce different outputs. -function primeincFindPrimeWithWorkers(bits, rng, options, callback) { - // web workers unavailable - if(typeof Worker === 'undefined') { - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + packet[p] = MESSAGE.GLOBAL_REQUEST; + + writeUInt32BE(packet, 28, ++p); + packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); + + packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); + + this._debug && this._debug( + 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' + ); + sendPacket(this, this._packetRW.write.finalize(packet)); } + session(chan, initWindow, maxPacket) { + if (this._server) + throw new Error('Client-only method called in server mode'); - // initialize random number - var num = generateRandom(bits, rng); + // Does not consume window space - // use web workers to generate keys - var numWorkers = options.workers; - var workLoad = options.workLoad || 100; - var range = workLoad * 30 / 8; - var workerScript = options.workerScript || 'forge/prime.worker.js'; - if(numWorkers === -1) { - return forge.util.estimateCores(function(err, cores) { - if(err) { - // default to 2 - cores = 2; - } - numWorkers = cores - 1; - generate(); - }); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); + + packet[p] = MESSAGE.CHANNEL_OPEN; + + writeUInt32BE(packet, 7, ++p); + packet.utf8Write('session', p += 4, 7); + + writeUInt32BE(packet, chan, p += 7); + + writeUInt32BE(packet, initWindow, p += 4); + + writeUInt32BE(packet, maxPacket, p += 4); + + this._debug + && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); + sendPacket(this, this._packetRW.write.finalize(packet)); } - generate(); + windowChange(chan, rows, cols, height, width) { + if (this._server) + throw new Error('Client-only method called in server mode'); - function generate() { - // require at least 1 worker - numWorkers = Math.max(1, numWorkers); + // Does not consume window space - // TODO: consider optimizing by starting workers outside getPrime() ... - // note that in order to clean up they will have to be made internally - // asynchronous which may actually be slower + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 + ); - // start workers immediately - var workers = []; - for(var i = 0; i < numWorkers; ++i) { - // FIXME: fix path or use blob URLs - workers[i] = new Worker(workerScript); - } - var running = numWorkers; + packet[p] = MESSAGE.CHANNEL_REQUEST; - // listen for requests from workers and assign ranges to find prime - for(var i = 0; i < numWorkers; ++i) { - workers[i].addEventListener('message', workerMessage); - } + writeUInt32BE(packet, chan, ++p); - /* Note: The distribution of random numbers is unknown. Therefore, each - web worker is continuously allocated a range of numbers to check for a - random number until one is found. + writeUInt32BE(packet, 13, p += 4); + packet.utf8Write('window-change', p += 4, 13); - Every 30 numbers will be checked just 8 times, because prime numbers - have the form: + packet[p += 13] = 0; - 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) + writeUInt32BE(packet, cols, ++p); - Therefore, if we want a web worker to run N checks before asking for - a new range of numbers, each range must contain N*30/8 numbers. + writeUInt32BE(packet, rows, p += 4); - For 100 checks (workLoad), this is a range of 375. */ + writeUInt32BE(packet, width, p += 4); - var found = false; - function workerMessage(e) { - // ignore message, prime already found - if(found) { - return; - } + writeUInt32BE(packet, height, p += 4); - --running; - var data = e.data; - if(data.found) { - // terminate all workers - for(var i = 0; i < workers.length; ++i) { - workers[i].terminate(); - } - found = true; - return callback(null, new BigInteger(data.prime, 16)); - } + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + pty(chan, rows, cols, height, width, term, modes, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); - // overflow, regenerate random number - if(num.bitLength() > bits) { - num = generateRandom(bits, rng); - } + // Does not consume window space - // assign new range to check - var hex = num.toString(16); + if (!term || !term.length) + term = 'vt100'; + if (modes + && !Buffer.isBuffer(modes) + && !Array.isArray(modes) + && typeof modes === 'object' + && modes !== null) { + modes = modesToBytes(modes); + } + if (!modes || !modes.length) + modes = NO_TERMINAL_MODES_BUFFER; + + const termLen = term.length; + const modesLen = modes.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen + ); + + packet[p] = MESSAGE.CHANNEL_REQUEST; + + writeUInt32BE(packet, chan, ++p); + + writeUInt32BE(packet, 7, p += 4); + packet.utf8Write('pty-req', p += 4, 7); + + packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); + + writeUInt32BE(packet, termLen, ++p); + packet.utf8Write(term, p += 4, termLen); + + writeUInt32BE(packet, cols, p += termLen); + + writeUInt32BE(packet, rows, p += 4); - // start prime search - e.target.postMessage({ - hex: hex, - workLoad: workLoad - }); + writeUInt32BE(packet, width, p += 4); - num.dAddOffset(range, 0); + writeUInt32BE(packet, height, p += 4); + + writeUInt32BE(packet, modesLen, p += 4); + p += 4; + if (Array.isArray(modes)) { + for (let i = 0; i < modesLen; ++i) + packet[p++] = modes[i]; + } else if (Buffer.isBuffer(modes)) { + packet.set(modes, p); } - } -} -/** - * Generates a random number using the given number of bits and RNG. - * - * @param bits the number of bits for the number. - * @param rng the random number generator to use. - * - * @return the random number. - */ -function generateRandom(bits, rng) { - var num = new BigInteger(bits, rng); - // force MSB set - var bits1 = bits - 1; - if(!num.testBit(bits1)) { - num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); + this._debug + && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); + sendPacket(this, this._packetRW.write.finalize(packet)); } - // align number on 30k+1 boundary - num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); - return num; -} + shell(chan, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); -/** - * Returns the required number of Miller-Rabin tests to generate a - * prime with an error probability of (1/2)^80. - * - * See Handbook of Applied Cryptography Chapter 4, Table 4.4. - * - * @param bits the bit size. - * - * @return the required number of iterations. - */ -function getMillerRabinTests(bits) { - if(bits <= 100) return 27; - if(bits <= 150) return 18; - if(bits <= 200) return 15; - if(bits <= 250) return 12; - if(bits <= 300) return 9; - if(bits <= 350) return 8; - if(bits <= 400) return 7; - if(bits <= 500) return 6; - if(bits <= 600) return 5; - if(bits <= 800) return 4; - if(bits <= 1250) return 3; - return 2; -} + // Does not consume window space -})(); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); + packet[p] = MESSAGE.CHANNEL_REQUEST; -/***/ }), + writeUInt32BE(packet, chan, ++p); -/***/ 4467: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + writeUInt32BE(packet, 5, p += 4); + packet.utf8Write('shell', p += 4, 5); -/** - * A javascript implementation of a cryptographically-secure - * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed - * here though the use of SHA-256 is not enforced; when generating an - * a PRNG context, the hashing algorithm and block cipher used for - * the generator are specified via a plugin. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); + packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); -var _crypto = null; -if(forge.util.isNodejs && !forge.options.usePureJavaScript && - !process.versions['node-webkit']) { - _crypto = __nccwpck_require__(6113); -} + this._debug + && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + exec(chan, cmd, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); -/* PRNG API */ -var prng = module.exports = forge.prng = forge.prng || {}; + // Does not consume window space -/** - * Creates a new PRNG context. - * - * A PRNG plugin must be passed in that will provide: - * - * 1. A function that initializes the key and seed of a PRNG context. It - * will be given a 16 byte key and a 16 byte seed. Any key expansion - * or transformation of the seed from a byte string into an array of - * integers (or similar) should be performed. - * 2. The cryptographic function used by the generator. It takes a key and - * a seed. - * 3. A seed increment function. It takes the seed and returns seed + 1. - * 4. An api to create a message digest. - * - * For an example, see random.js. - * - * @param plugin the PRNG plugin to use. - */ -prng.create = function(plugin) { - var ctx = { - plugin: plugin, - key: null, - seed: null, - time: null, - // number of reseeds so far - reseeds: 0, - // amount of data generated so far - generated: 0, - // no initial key bytes - keyBytes: '' - }; + const isBuf = Buffer.isBuffer(cmd); + const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); - // create 32 entropy pools (each is a message digest) - var md = plugin.md; - var pools = new Array(32); - for(var i = 0; i < 32; ++i) { - pools[i] = md.create(); - } - ctx.pools = pools; + packet[p] = MESSAGE.CHANNEL_REQUEST; - // entropy pools are written to cyclically, starting at index 0 - ctx.pool = 0; + writeUInt32BE(packet, chan, ++p); - /** - * Generates random bytes. The bytes may be generated synchronously or - * asynchronously. Web workers must use the asynchronous interface or - * else the behavior is undefined. - * - * @param count the number of random bytes to generate. - * @param [callback(err, bytes)] called once the operation completes. - * - * @return count random bytes as a string. - */ - ctx.generate = function(count, callback) { - // do synchronously - if(!callback) { - return ctx.generateSync(count); - } + writeUInt32BE(packet, 4, p += 4); + packet.utf8Write('exec', p += 4, 4); - // simple generator using counter-based CBC - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - var b = forge.util.createBuffer(); + packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); - // paranoid deviation from Fortuna: - // reset key for every request to protect previously - // generated random bytes should the key be discovered; - // there is no 100ms based reseeding because of this - // forced reseed for every `generate` call - ctx.key = null; + writeUInt32BE(packet, cmdLen, ++p); + if (isBuf) + packet.set(cmd, p += 4); + else + packet.utf8Write(cmd, p += 4, cmdLen); - generate(); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + signal(chan, signal) { + if (this._server) + throw new Error('Client-only method called in server mode'); - function generate(err) { - if(err) { - return callback(err); - } + // Does not consume window space - // sufficient bytes generated - if(b.length() >= count) { - return callback(null, b.getBytes(count)); - } + const origSignal = signal; - // if amount of data generated is greater than 1 MiB, trigger reseed - if(ctx.generated > 0xfffff) { - ctx.key = null; - } + signal = signal.toUpperCase(); + if (signal.slice(0, 3) === 'SIG') + signal = signal.slice(3); - if(ctx.key === null) { - // prevent stack overflow - return forge.util.nextTick(function() { - _reseed(generate); - }); - } + if (SIGNALS[signal] !== 1) + throw new Error(`Invalid signal: ${origSignal}`); - // generate the random bytes - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); + const signalLen = signal.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 6 + 1 + 4 + signalLen + ); - // generate bytes for a new key and seed - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + packet[p] = MESSAGE.CHANNEL_REQUEST; - forge.util.setImmediate(generate); - } - }; + writeUInt32BE(packet, chan, ++p); - /** - * Generates random bytes synchronously. - * - * @param count the number of random bytes to generate. - * - * @return count random bytes as a string. - */ - ctx.generateSync = function(count) { - // simple generator using counter-based CBC - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; + writeUInt32BE(packet, 6, p += 4); + packet.utf8Write('signal', p += 4, 6); - // paranoid deviation from Fortuna: - // reset key for every request to protect previously - // generated random bytes should the key be discovered; - // there is no 100ms based reseeding because of this - // forced reseed for every `generateSync` call - ctx.key = null; + packet[p += 6] = 0; - var b = forge.util.createBuffer(); - while(b.length() < count) { - // if amount of data generated is greater than 1 MiB, trigger reseed - if(ctx.generated > 0xfffff) { - ctx.key = null; - } + writeUInt32BE(packet, signalLen, ++p); + packet.utf8Write(signal, p += 4, signalLen); - if(ctx.key === null) { - _reseedSync(); - } + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + env(chan, key, val, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); - // generate the random bytes - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); + // Does not consume window space - // generate bytes for a new key and seed - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - } + const keyLen = Buffer.byteLength(key); + const isBuf = Buffer.isBuffer(val); + const valLen = (isBuf ? val.length : Buffer.byteLength(val)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen + ); - return b.getBytes(count); - }; + packet[p] = MESSAGE.CHANNEL_REQUEST; - /** - * Private function that asynchronously reseeds a generator. - * - * @param callback(err) called once the operation completes. - */ - function _reseed(callback) { - if(ctx.pools[0].messageLength >= 32) { - _seed(); - return callback(); - } - // not enough seed data... - var needed = (32 - ctx.pools[0].messageLength) << 5; - ctx.seedFile(needed, function(err, bytes) { - if(err) { - return callback(err); - } - ctx.collect(bytes); - _seed(); - callback(); - }); - } + writeUInt32BE(packet, chan, ++p); - /** - * Private function that synchronously reseeds a generator. - */ - function _reseedSync() { - if(ctx.pools[0].messageLength >= 32) { - return _seed(); - } - // not enough seed data... - var needed = (32 - ctx.pools[0].messageLength) << 5; - ctx.collect(ctx.seedFileSync(needed)); - _seed(); - } + writeUInt32BE(packet, 3, p += 4); + packet.utf8Write('env', p += 4, 3); - /** - * Private function that seeds a generator once enough bytes are available. - */ - function _seed() { - // update reseed count - ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; + packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); - // goal is to update `key` via: - // key = hash(key + s) - // where 's' is all collected entropy from selected pools, then... + writeUInt32BE(packet, keyLen, ++p); + packet.utf8Write(key, p += 4, keyLen); - // create a plugin-based message digest - var md = ctx.plugin.md.create(); + writeUInt32BE(packet, valLen, p += keyLen); + if (isBuf) + packet.set(val, p += 4); + else + packet.utf8Write(val, p += 4, valLen); - // consume current key bytes - md.update(ctx.keyBytes); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + x11Forward(chan, cfg, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); - // digest the entropy of pools whose index k meet the - // condition 'n mod 2^k == 0' where n is the number of reseeds - var _2powK = 1; - for(var k = 0; k < 32; ++k) { - if(ctx.reseeds % _2powK === 0) { - md.update(ctx.pools[k].digest().getBytes()); - ctx.pools[k].start(); - } - _2powK = _2powK << 1; - } + // Does not consume window space - // get digest for key bytes - ctx.keyBytes = md.digest().getBytes(); + const protocol = cfg.protocol; + const cookie = cfg.cookie; + const isBufProto = Buffer.isBuffer(protocol); + const protoLen = (isBufProto + ? protocol.length + : Buffer.byteLength(protocol)); + const isBufCookie = Buffer.isBuffer(cookie); + const cookieLen = (isBufCookie + ? cookie.length + : Buffer.byteLength(cookie)); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 + ); - // paranoid deviation from Fortuna: - // update `seed` via `seed = hash(key)` - // instead of initializing to zero once and only - // ever incrementing it - md.start(); - md.update(ctx.keyBytes); - var seedBytes = md.digest().getBytes(); + packet[p] = MESSAGE.CHANNEL_REQUEST; - // update state - ctx.key = ctx.plugin.formatKey(ctx.keyBytes); - ctx.seed = ctx.plugin.formatSeed(seedBytes); - ctx.generated = 0; - } + writeUInt32BE(packet, chan, ++p); - /** - * The built-in default seedFile. This seedFile is used when entropy - * is needed immediately. - * - * @param needed the number of bytes that are needed. - * - * @return the random bytes. - */ - function defaultSeedFile(needed) { - // use window.crypto.getRandomValues strong source of entropy if available - var getRandomValues = null; - var globalScope = forge.util.globalScope; - var _crypto = globalScope.crypto || globalScope.msCrypto; - if(_crypto && _crypto.getRandomValues) { - getRandomValues = function(arr) { - return _crypto.getRandomValues(arr); - }; - } + writeUInt32BE(packet, 7, p += 4); + packet.utf8Write('x11-req', p += 4, 7); - var b = forge.util.createBuffer(); - if(getRandomValues) { - while(b.length() < needed) { - // max byte length is 65536 before QuotaExceededError is thrown - // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues - var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); - var entropy = new Uint32Array(Math.floor(count)); - try { - getRandomValues(entropy); - for(var i = 0; i < entropy.length; ++i) { - b.putInt32(entropy[i]); - } - } catch(e) { - /* only ignore QuotaExceededError */ - if(!(typeof QuotaExceededError !== 'undefined' && - e instanceof QuotaExceededError)) { - throw e; - } - } - } - } + packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - // be sad and add some weak random data - if(b.length() < needed) { - /* Draws from Park-Miller "minimal standard" 31 bit PRNG, - implemented with David G. Carta's optimization: with 32 bit math - and without division (Public Domain). */ - var hi, lo, next; - var seed = Math.floor(Math.random() * 0x010000); - while(b.length() < needed) { - lo = 16807 * (seed & 0xFFFF); - hi = 16807 * (seed >> 16); - lo += (hi & 0x7FFF) << 16; - lo += hi >> 15; - lo = (lo & 0x7FFFFFFF) + (lo >> 31); - seed = lo & 0xFFFFFFFF; + packet[++p] = (cfg.single ? 1 : 0); - // consume lower 3 bytes of seed - for(var i = 0; i < 3; ++i) { - // throw in more pseudo random - next = seed >>> (i << 3); - next ^= Math.floor(Math.random() * 0x0100); - b.putByte(next & 0xFF); - } - } - } + writeUInt32BE(packet, protoLen, ++p); + if (isBufProto) + packet.set(protocol, p += 4); + else + packet.utf8Write(protocol, p += 4, protoLen); - return b.getBytes(needed); - } - // initialize seed file APIs - if(_crypto) { - // use nodejs async API - ctx.seedFile = function(needed, callback) { - _crypto.randomBytes(needed, function(err, bytes) { - if(err) { - return callback(err); - } - callback(null, bytes.toString()); - }); - }; - // use nodejs sync API - ctx.seedFileSync = function(needed) { - return _crypto.randomBytes(needed).toString(); - }; - } else { - ctx.seedFile = function(needed, callback) { - try { - callback(null, defaultSeedFile(needed)); - } catch(e) { - callback(e); - } - }; - ctx.seedFileSync = defaultSeedFile; + writeUInt32BE(packet, cookieLen, p += protoLen); + if (isBufCookie) + packet.set(cookie, p += 4); + else + packet.latin1Write(cookie, p += 4, cookieLen); + + writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); + + this._debug + && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); + sendPacket(this, this._packetRW.write.finalize(packet)); } + subsystem(chan, name, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); - /** - * Adds entropy to a prng ctx's accumulator. - * - * @param bytes the bytes of entropy as a string. - */ - ctx.collect = function(bytes) { - // iterate over pools distributing entropy cyclically - var count = bytes.length; - for(var i = 0; i < count; ++i) { - ctx.pools[ctx.pool].update(bytes.substr(i, 1)); - ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1; - } - }; + // Does not consume window space + const nameLen = Buffer.byteLength(name); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); - /** - * Collects an integer of n bits. - * - * @param i the integer entropy. - * @param n the number of bits in the integer. - */ - ctx.collectInt = function(i, n) { - var bytes = ''; - for(var x = 0; x < n; x += 8) { - bytes += String.fromCharCode((i >> x) & 0xFF); - } - ctx.collect(bytes); - }; + packet[p] = MESSAGE.CHANNEL_REQUEST; - /** - * Registers a Web Worker to receive immediate entropy from the main thread. - * This method is required until Web Workers can access the native crypto - * API. This method should be called twice for each created worker, once in - * the main thread, and once in the worker itself. - * - * @param worker the worker to register. - */ - ctx.registerWorker = function(worker) { - // worker receives random bytes - if(worker === self) { - ctx.seedFile = function(needed, callback) { - function listener(e) { - var data = e.data; - if(data.forge && data.forge.prng) { - self.removeEventListener('message', listener); - callback(data.forge.prng.err, data.forge.prng.bytes); - } - } - self.addEventListener('message', listener); - self.postMessage({forge: {prng: {needed: needed}}}); - }; - } else { - // main thread sends random bytes upon request - var listener = function(e) { - var data = e.data; - if(data.forge && data.forge.prng) { - ctx.seedFile(data.forge.prng.needed, function(err, bytes) { - worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); - }); - } - }; - // TODO: do we need to remove the event listener when the worker dies? - worker.addEventListener('message', listener); - } - }; + writeUInt32BE(packet, chan, ++p); - return ctx; -}; + writeUInt32BE(packet, 9, p += 4); + packet.utf8Write('subsystem', p += 4, 9); + packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); -/***/ }), + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(name, p += 4, nameLen); -/***/ 4376: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_agentForward(chan, wantReply) { + if (this._server) + throw new Error('Client-only method called in server mode'); -/** - * Javascript implementation of PKCS#1 PSS signature padding. - * - * @author Stefan Siegl - * - * Copyright (c) 2012 Stefan Siegl - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7821); -__nccwpck_require__(8339); + // Does not consume window space -// shortcut for PSS API -var pss = module.exports = forge.pss = forge.pss || {}; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); -/** - * Creates a PSS signature scheme object. - * - * There are several ways to provide a salt for encoding: - * - * 1. Specify the saltLength only and the built-in PRNG will generate it. - * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that - * will be used. - * 3. Specify the salt itself as a forge.util.ByteBuffer. - * - * @param options the options to use: - * md the message digest object to use, a forge md instance. - * mgf the mask generation function to use, a forge mgf instance. - * [saltLength] the length of the salt in octets. - * [prng] the pseudo-random number generator to use to produce a salt. - * [salt] the salt to use when encoding. - * - * @return a signature scheme object. - */ -pss.create = function(options) { - // backwards compatibility w/legacy args: hash, mgf, sLen - if(arguments.length === 3) { - options = { - md: arguments[0], - mgf: arguments[1], - saltLength: arguments[2] - }; - } + packet[p] = MESSAGE.CHANNEL_REQUEST; - var hash = options.md; - var mgf = options.mgf; - var hLen = hash.digestLength; + writeUInt32BE(packet, chan, ++p); - var salt_ = options.salt || null; - if(typeof salt_ === 'string') { - // assume binary-encoded string - salt_ = forge.util.createBuffer(salt_); - } + writeUInt32BE(packet, 26, p += 4); + packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); - var sLen; - if('saltLength' in options) { - sLen = options.saltLength; - } else if(salt_ !== null) { - sLen = salt_.length(); - } else { - throw new Error('Salt length not specified or specific salt not given.'); - } + packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); - if(salt_ !== null && salt_.length() !== sLen) { - throw new Error('Given salt length does not match length of given salt.'); + if (this._debug) { + this._debug( + 'Outbound: Sending CHANNEL_REQUEST ' + + `(r:${chan}, auth-agent-req@openssh.com)` + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); } + openssh_hostKeysProve(keys) { + if (this._server) + throw new Error('Client-only method called in server mode'); - var prng = options.prng || forge.random; + let keysTotal = 0; + const publicKeys = []; + for (const key of keys) { + const publicKey = key.getPublicSSH(); + keysTotal += 4 + publicKey.length; + publicKeys.push(publicKey); + } - var pssobj = {}; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); - /** - * Encodes a PSS signature. - * - * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1. - * - * @param md the message digest object with the hash to sign. - * @param modsBits the length of the RSA modulus in bits. - * - * @return the encoded message as a binary-encoded string of length - * ceil((modBits - 1) / 8). - */ - pssobj.encode = function(md, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); + packet[p] = MESSAGE.GLOBAL_REQUEST; - /* 2. Let mHash = Hash(M), an octet string of length hLen. */ - var mHash = md.digest().getBytes(); + writeUInt32BE(packet, 29, ++p); + packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */ - if(emLen < hLen + sLen + 2) { - throw new Error('Message is too long to encrypt.'); + packet[p += 29] = 1; // want reply + + ++p; + for (const buf of publicKeys) { + writeUInt32BE(packet, buf.length, p); + bufferCopy(buf, packet, 0, buf.length, p += 4); + p += buf.length; } - /* 4. Generate a random octet string salt of length sLen; if sLen = 0, - * then salt is the empty string. */ - var salt; - if(salt_ === null) { - salt = prng.getBytesSync(sLen); - } else { - salt = salt_.bytes(); + if (this._debug) { + this._debug( + 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' + ); } + sendPacket(this, this._packetRW.write.finalize(packet)); + } - /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */ - var m_ = new forge.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); + // =========================================================================== + // Server-specific =========================================================== + // =========================================================================== - /* 6. Let H = Hash(M'), an octet string of length hLen. */ - hash.start(); - hash.update(m_.getBytes()); - var h = hash.digest().getBytes(); + // Global + // ------ + serviceAccept(svcName) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 - * zero octets. The length of PS may be 0. */ - var ps = new forge.util.ByteBuffer(); - ps.fillWithByte(0, emLen - sLen - hLen - 2); + const svcNameLen = Buffer.byteLength(svcName); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); - /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length - * emLen - hLen - 1. */ - ps.putByte(0x01); - ps.putBytes(salt); - var db = ps.getBytes(); + packet[p] = MESSAGE.SERVICE_ACCEPT; - /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */ - var maskLen = emLen - hLen - 1; - var dbMask = mgf.generate(h, maskLen); + writeUInt32BE(packet, svcNameLen, ++p); + packet.utf8Write(svcName, p += 4, svcNameLen); - /* 10. Let maskedDB = DB \xor dbMask. */ - var maskedDB = ''; - for(i = 0; i < maskLen; i++) { - maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } + this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); + sendPacket(this, this._packetRW.write.finalize(packet)); - /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in - * maskedDB to zero. */ - var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; - maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + - maskedDB.substr(1); + if (this._server && this._banner && svcName === 'ssh-userauth') { + const banner = this._banner; + this._banner = undefined; // Prevent banner from being displayed again + const bannerLen = Buffer.byteLength(banner); + p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); - /* 12. Let EM = maskedDB || H || 0xbc. - * 13. Output EM. */ - return maskedDB + h + String.fromCharCode(0xbc); - }; + packet[p] = MESSAGE.USERAUTH_BANNER; - /** - * Verifies a PSS signature. - * - * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2. - * - * @param mHash the message digest hash, as a binary-encoded string, to - * compare against the signature. - * @param em the encoded message, as a binary-encoded string - * (RSA decryption result). - * @param modsBits the length of the RSA modulus in bits. - * - * @return true if the signature was verified, false if not. - */ - pssobj.verify = function(mHash, em, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); + writeUInt32BE(packet, bannerLen, ++p); + packet.utf8Write(banner, p += 4, bannerLen); - /* c. Convert the message representative m to an encoded message EM - * of length emLen = ceil((modBits - 1) / 8) octets, where modBits - * is the length in bits of the RSA modulus n */ - em = em.substr(-emLen); + writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag - /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */ - if(emLen < hLen + sLen + 2) { - throw new Error('Inconsistent parameters to PSS signature verification.'); + this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); + sendPacket(this, this._packetRW.write.finalize(packet)); } + } + // 'ssh-connection' service-specific + forwardedTcpip(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - /* 4. If the rightmost octet of EM does not have hexadecimal value - * 0xbc, output "inconsistent" and stop. */ - if(em.charCodeAt(emLen - 1) !== 0xbc) { - throw new Error('Encoded message does not end in 0xBC.'); - } + const boundAddrLen = Buffer.byteLength(cfg.boundAddr); + const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 + ); - /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and - * let H be the next hLen octets. */ - var maskLen = emLen - hLen - 1; - var maskedDB = em.substr(0, maskLen); - var h = em.substr(maskLen, hLen); + packet[p] = MESSAGE.CHANNEL_OPEN; - /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in - * maskedDB are not all equal to zero, output "inconsistent" and stop. */ - var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; - if((maskedDB.charCodeAt(0) & mask) !== 0) { - throw new Error('Bits beyond keysize not zero as expected.'); - } + writeUInt32BE(packet, 15, ++p); + packet.utf8Write('forwarded-tcpip', p += 4, 15); - /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */ - var dbMask = mgf.generate(h, maskLen); + writeUInt32BE(packet, chan, p += 15); - /* 8. Let DB = maskedDB \xor dbMask. */ - var db = ''; - for(i = 0; i < maskLen; i++) { - db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } + writeUInt32BE(packet, initWindow, p += 4); - /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet - * in DB to zero. */ - db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); + writeUInt32BE(packet, maxPacket, p += 4); - /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero - * or if the octet at position emLen - hLen - sLen - 1 (the leftmost - * position is "position 1") does not have hexadecimal value 0x01, - * output "inconsistent" and stop. */ - var checkLen = emLen - hLen - sLen - 2; - for(i = 0; i < checkLen; i++) { - if(db.charCodeAt(i) !== 0x00) { - throw new Error('Leftmost octets not zero as expected'); - } - } + writeUInt32BE(packet, boundAddrLen, p += 4); + packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); - if(db.charCodeAt(checkLen) !== 0x01) { - throw new Error('Inconsistent PSS signature, 0x01 marker not found'); - } + writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); - /* 11. Let salt be the last sLen octets of DB. */ - var salt = db.substr(-sLen); + writeUInt32BE(packet, remoteAddrLen, p += 4); + packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); - /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */ - var m_ = new forge.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); + writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); - /* 13. Let H' = Hash(M'), an octet string of length hLen. */ - hash.start(); - hash.update(m_.getBytes()); - var h_ = hash.digest().getBytes(); + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + x11(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */ - return h === h_; - }; + const addrLen = Buffer.byteLength(cfg.originAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 + ); - return pssobj; -}; + packet[p] = MESSAGE.CHANNEL_OPEN; + writeUInt32BE(packet, 3, ++p); + packet.utf8Write('x11', p += 4, 3); -/***/ }), + writeUInt32BE(packet, chan, p += 3); -/***/ 7821: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + writeUInt32BE(packet, initWindow, p += 4); -/** - * An API for getting cryptographically-secure random bytes. The bytes are - * generated using the Fortuna algorithm devised by Bruce Schneier and - * Niels Ferguson. - * - * Getting strong random bytes is not yet easy to do in javascript. The only - * truish random entropy that can be collected is from the mouse, keyboard, or - * from timing with respect to page loads, etc. This generator makes a poor - * attempt at providing random bytes when those sources haven't yet provided - * enough entropy to initially seed or to reseed the PRNG. - * - * @author Dave Longley - * - * Copyright (c) 2009-2014 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7994); -__nccwpck_require__(4086); -__nccwpck_require__(4467); -__nccwpck_require__(8339); + writeUInt32BE(packet, maxPacket, p += 4); -(function() { + writeUInt32BE(packet, addrLen, p += 4); + packet.utf8Write(cfg.originAddr, p += 4, addrLen); -// forge.random already defined -if(forge.random && forge.random.getBytes) { - module.exports = forge.random; - return; -} + writeUInt32BE(packet, cfg.originPort, p += addrLen); -(function(jQuery) { + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_authAgent(chan, initWindow, maxPacket) { + if (!this._server) + throw new Error('Server-only method called in client mode'); -// the default prng plugin, uses AES-128 -var prng_aes = {}; -var _prng_aes_output = new Array(4); -var _prng_aes_buffer = forge.util.createBuffer(); -prng_aes.formatKey = function(key) { - // convert the key into 32-bit integers - var tmp = forge.util.createBuffer(key); - key = new Array(4); - key[0] = tmp.getInt32(); - key[1] = tmp.getInt32(); - key[2] = tmp.getInt32(); - key[3] = tmp.getInt32(); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); - // return the expanded key - return forge.aes._expandKey(key, false); -}; -prng_aes.formatSeed = function(seed) { - // convert seed into 32-bit integers - var tmp = forge.util.createBuffer(seed); - seed = new Array(4); - seed[0] = tmp.getInt32(); - seed[1] = tmp.getInt32(); - seed[2] = tmp.getInt32(); - seed[3] = tmp.getInt32(); - return seed; -}; -prng_aes.cipher = function(key, seed) { - forge.aes._updateBlock(key, seed, _prng_aes_output, false); - _prng_aes_buffer.putInt32(_prng_aes_output[0]); - _prng_aes_buffer.putInt32(_prng_aes_output[1]); - _prng_aes_buffer.putInt32(_prng_aes_output[2]); - _prng_aes_buffer.putInt32(_prng_aes_output[3]); - return _prng_aes_buffer.getBytes(); -}; -prng_aes.increment = function(seed) { - // FIXME: do we care about carry or signed issues? - ++seed[3]; - return seed; -}; -prng_aes.md = forge.md.sha256; + packet[p] = MESSAGE.CHANNEL_OPEN; + + writeUInt32BE(packet, 22, ++p); + packet.utf8Write('auth-agent@openssh.com', p += 4, 22); + + writeUInt32BE(packet, chan, p += 22); + + writeUInt32BE(packet, initWindow, p += 4); + + writeUInt32BE(packet, maxPacket, p += 4); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error('Server-only method called in client mode'); + + const pathLen = Buffer.byteLength(cfg.socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 + ); + + packet[p] = MESSAGE.CHANNEL_OPEN; -/** - * Creates a new PRNG. - */ -function spawnPrng() { - var ctx = forge.prng.create(prng_aes); + writeUInt32BE(packet, 33, ++p); + packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); - /** - * Gets random bytes. If a native secure crypto API is unavailable, this - * method tries to make the bytes more unpredictable by drawing from data that - * can be collected from the user of the browser, eg: mouse movement. - * - * If a callback is given, this method will be called asynchronously. - * - * @param count the number of random bytes to get. - * @param [callback(err, bytes)] called once the operation completes. - * - * @return the random bytes in a string. - */ - ctx.getBytes = function(count, callback) { - return ctx.generate(count, callback); - }; + writeUInt32BE(packet, chan, p += 33); - /** - * Gets random bytes asynchronously. If a native secure crypto API is - * unavailable, this method tries to make the bytes more unpredictable by - * drawing from data that can be collected from the user of the browser, - * eg: mouse movement. - * - * @param count the number of random bytes to get. - * - * @return the random bytes in a string. - */ - ctx.getBytesSync = function(count) { - return ctx.generate(count); - }; + writeUInt32BE(packet, initWindow, p += 4); - return ctx; -} + writeUInt32BE(packet, maxPacket, p += 4); -// create default prng context -var _ctx = spawnPrng(); + writeUInt32BE(packet, pathLen, p += 4); + packet.utf8Write(cfg.socketPath, p += 4, pathLen); -// add other sources of entropy only if window.crypto.getRandomValues is not -// available -- otherwise this source will be automatically used by the prng -var getRandomValues = null; -var globalScope = forge.util.globalScope; -var _crypto = globalScope.crypto || globalScope.msCrypto; -if(_crypto && _crypto.getRandomValues) { - getRandomValues = function(arr) { - return _crypto.getRandomValues(arr); - }; -} + writeUInt32BE(packet, 0, p += pathLen); -if(forge.options.usePureJavaScript || - (!forge.util.isNodejs && !getRandomValues)) { - // if this is a web worker, do not use weak entropy, instead register to - // receive strong entropy asynchronously from the main thread - if(typeof window === 'undefined' || window.document === undefined) { - // FIXME: + if (this._debug) { + this._debug( + 'Outbound: Sending CHANNEL_OPEN ' + + `(r:${chan}, forwarded-streamlocal@openssh.com)` + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); } + exitStatus(chan, status) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - // get load time entropy - _ctx.collectInt(+new Date(), 32); + // Does not consume window space + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); - // add some entropy from navigator object - if(typeof(navigator) !== 'undefined') { - var _navBytes = ''; - for(var key in navigator) { - try { - if(typeof(navigator[key]) == 'string') { - _navBytes += navigator[key]; - } - } catch(e) { - /* Some navigator keys might not be accessible, e.g. the geolocation - attribute throws an exception if touched in Mozilla chrome:// - context. + packet[p] = MESSAGE.CHANNEL_REQUEST; - Silently ignore this and just don't use this as a source of - entropy. */ - } - } - _ctx.collect(_navBytes); - _navBytes = null; - } + writeUInt32BE(packet, chan, ++p); - // add mouse and keyboard collectors if jquery is available - if(jQuery) { - // set up mouse entropy capture - jQuery().mousemove(function(e) { - // add mouse coords - _ctx.collectInt(e.clientX, 16); - _ctx.collectInt(e.clientY, 16); - }); + writeUInt32BE(packet, 11, p += 4); + packet.utf8Write('exit-status', p += 4, 11); - // set up keyboard entropy capture - jQuery().keypress(function(e) { - _ctx.collectInt(e.charCode, 8); - }); - } -} + packet[p += 11] = 0; -/* Random API */ -if(!forge.random) { - forge.random = _ctx; -} else { - // extend forge.random with _ctx - for(var key in _ctx) { - forge.random[key] = _ctx[key]; + writeUInt32BE(packet, status, ++p); + + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); } -} + exitSignal(chan, name, coreDumped, msg) { + if (!this._server) + throw new Error('Server-only method called in client mode'); -// expose spawn PRNG -forge.random.createInstance = spawnPrng; + // Does not consume window space -module.exports = forge.random; + const origSignal = name; -})(typeof(jQuery) !== 'undefined' ? jQuery : null); + if (typeof origSignal !== 'string' || !origSignal) + throw new Error(`Invalid signal: ${origSignal}`); -})(); + let signal = name.toUpperCase(); + if (signal.slice(0, 3) === 'SIG') + signal = signal.slice(3); + if (SIGNALS[signal] !== 1) + throw new Error(`Invalid signal: ${origSignal}`); -/***/ }), + const nameLen = Buffer.byteLength(signal); + const msgLen = (msg ? Buffer.byteLength(msg) : 0); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 + ); -/***/ 9965: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + packet[p] = MESSAGE.CHANNEL_REQUEST; -/** - * RC2 implementation. - * - * @author Stefan Siegl - * - * Copyright (c) 2012 Stefan Siegl - * - * Information on the RC2 cipher is available from RFC #2268, - * http://www.ietf.org/rfc/rfc2268.txt - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(8339); + writeUInt32BE(packet, chan, ++p); -var piTable = [ - 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, - 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, - 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, - 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, - 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, - 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, - 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, - 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, - 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, - 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, - 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, - 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, - 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, - 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, - 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, - 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad -]; + writeUInt32BE(packet, 11, p += 4); + packet.utf8Write('exit-signal', p += 4, 11); -var s = [1, 2, 3, 5]; + packet[p += 11] = 0; -/** - * Rotate a word left by given number of bits. - * - * Bits that are shifted out on the left are put back in on the right - * hand side. - * - * @param word The word to shift left. - * @param bits The number of bits to shift by. - * @return The rotated word. - */ -var rol = function(word, bits) { - return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits)); -}; + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(signal, p += 4, nameLen); -/** - * Rotate a word right by given number of bits. - * - * Bits that are shifted out on the right are put back in on the left - * hand side. - * - * @param word The word to shift right. - * @param bits The number of bits to shift by. - * @return The rotated word. - */ -var ror = function(word, bits) { - return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff); -}; + packet[p += nameLen] = (coreDumped ? 1 : 0); -/* RC2 API */ -module.exports = forge.rc2 = forge.rc2 || {}; + writeUInt32BE(packet, msgLen, ++p); -/** - * Perform RC2 key expansion as per RFC #2268, section 2. - * - * @param key variable-length user key (between 1 and 128 bytes) - * @param effKeyBits number of effective key bits (default: 128) - * @return the expanded RC2 key (ByteBuffer of 128 bytes) - */ -forge.rc2.expandKey = function(key, effKeyBits) { - if(typeof key === 'string') { - key = forge.util.createBuffer(key); - } - effKeyBits = effKeyBits || 128; + p += 4; + if (msgLen) { + packet.utf8Write(msg, p, msgLen); + p += msgLen; + } - /* introduce variables that match the names used in RFC #2268 */ - var L = key; - var T = key.length(); - var T1 = effKeyBits; - var T8 = Math.ceil(T1 / 8); - var TM = 0xff >> (T1 & 0x07); - var i; + writeUInt32BE(packet, 0, p); - for(i = T; i < 128; i++) { - L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); } + // 'ssh-userauth' service-specific + authFailure(authMethods, isPartial) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); + if (this._authsQueue.length === 0) + throw new Error('No auth in progress'); - for(i = 127 - T8; i >= 0; i--) { - L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); - } + let methods; - return L; -}; + if (typeof authMethods === 'boolean') { + isPartial = authMethods; + authMethods = undefined; + } -/** - * Creates a RC2 cipher object. - * - * @param key the symmetric key to use (as base for key generation). - * @param bits the number of effective key bits. - * @param encrypt false for decryption, true for encryption. - * - * @return the cipher. - */ -var createCipher = function(key, bits, encrypt) { - var _finish = false, _input = null, _output = null, _iv = null; - var mixRound, mashRound; - var i, j, K = []; + if (authMethods) { + methods = []; + for (let i = 0; i < authMethods.length; ++i) { + if (authMethods[i].toLowerCase() === 'none') + continue; + methods.push(authMethods[i]); + } + methods = methods.join(','); + } else { + methods = ''; + } - /* Expand key and fill into K[] Array */ - key = forge.rc2.expandKey(key, bits); - for(i = 0; i < 64; i++) { - K.push(key.getInt16Le()); - } + const methodsLen = methods.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); - if(encrypt) { - /** - * Perform one mixing round "in place". - * - * @param R Array of four words to perform mixing on. - */ - mixRound = function(R) { - for(i = 0; i < 4; i++) { - R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + - ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); - R[i] = rol(R[i], s[i]); - j++; - } - }; + packet[p] = MESSAGE.USERAUTH_FAILURE; - /** - * Perform one mashing round "in place". - * - * @param R Array of four words to perform mashing on. - */ - mashRound = function(R) { - for(i = 0; i < 4; i++) { - R[i] += K[R[(i + 3) % 4] & 63]; - } - }; - } else { - /** - * Perform one r-mixing round "in place". - * - * @param R Array of four words to perform mixing on. - */ - mixRound = function(R) { - for(i = 3; i >= 0; i--) { - R[i] = ror(R[i], s[i]); - R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + - ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); - j--; - } - }; + writeUInt32BE(packet, methodsLen, ++p); + packet.utf8Write(methods, p += 4, methodsLen); - /** - * Perform one r-mashing round "in place". - * - * @param R Array of four words to perform mashing on. - */ - mashRound = function(R) { - for(i = 3; i >= 0; i--) { - R[i] -= K[R[(i + 3) % 4] & 63]; - } - }; - } + packet[p += methodsLen] = (isPartial === true ? 1 : 0); - /** - * Run the specified cipher execution plan. - * - * This function takes four words from the input buffer, applies the IV on - * it (if requested) and runs the provided execution plan. - * - * The plan must be put together in form of a array of arrays. Where the - * outer one is simply a list of steps to perform and the inner one needs - * to have two elements: the first one telling how many rounds to perform, - * the second one telling what to do (i.e. the function to call). - * - * @param {Array} plan The plan to execute. - */ - var runPlan = function(plan) { - var R = []; + this._authsQueue.shift(); - /* Get data from input buffer and fill the four words into R */ - for(i = 0; i < 4; i++) { - var val = _input.getInt16Le(); + this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authSuccess() { + if (!this._server) + throw new Error('Server-only method called in client mode'); - if(_iv !== null) { - if(encrypt) { - /* We're encrypting, apply the IV first. */ - val ^= _iv.getInt16Le(); - } else { - /* We're decryption, keep cipher text for next block. */ - _iv.putInt16Le(val); - } - } + if (this._authsQueue.length === 0) + throw new Error('No auth in progress'); - R.push(val & 0xffff); - } + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1); - /* Reset global "j" variable as per spec. */ - j = encrypt ? 0 : 63; + packet[p] = MESSAGE.USERAUTH_SUCCESS; - /* Run execution plan. */ - for(var ptr = 0; ptr < plan.length; ptr++) { - for(var ctr = 0; ctr < plan[ptr][0]; ctr++) { - plan[ptr][1](R); - } - } + this._authsQueue.shift(); + this._authenticated = true; - /* Write back result to output buffer. */ - for(i = 0; i < 4; i++) { - if(_iv !== null) { - if(encrypt) { - /* We're encrypting in CBC-mode, feed back encrypted bytes into - IV buffer to carry it forward to next block. */ - _iv.putInt16Le(R[i]); - } else { - R[i] ^= _iv.getInt16Le(); - } - } + this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); + sendPacket(this, this._packetRW.write.finalize(packet)); - _output.putInt16Le(R[i]); - } - }; + if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') + this._packetRW.read = new ZlibPacketReader(); + if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') + this._packetRW.write = new ZlibPacketWriter(this); + } + authPKOK(keyAlgo, key) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - /* Create cipher object */ - var cipher = null; - cipher = { - /** - * Starts or restarts the encryption or decryption process, whichever - * was previously configured. - * - * To use the cipher in CBC mode, iv may be given either as a string - * of bytes, or as a byte buffer. For ECB mode, give null as iv. - * - * @param iv the initialization vector to use, null for ECB mode. - * @param output the output the buffer to write to, null to create one. - */ - start: function(iv, output) { - if(iv) { - /* CBC mode */ - if(typeof iv === 'string') { - iv = forge.util.createBuffer(iv); - } - } + if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') + throw new Error('"publickey" auth not in progress'); - _finish = false; - _input = forge.util.createBuffer(); - _output = output || new forge.util.createBuffer(); - _iv = iv; + // TODO: support parsed key for `key` - cipher.output = _output; - }, + const keyAlgoLen = Buffer.byteLength(keyAlgo); + const keyLen = key.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); - /** - * Updates the next block. - * - * @param input the buffer to read from. - */ - update: function(input) { - if(!_finish) { - // not finishing, so fill the input buffer with more input - _input.putBuffer(input); - } + packet[p] = MESSAGE.USERAUTH_PK_OK; - while(_input.length() >= 8) { - runPlan([ - [ 5, mixRound ], - [ 1, mashRound ], - [ 6, mixRound ], - [ 1, mashRound ], - [ 5, mixRound ] - ]); - } - }, + writeUInt32BE(packet, keyAlgoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); - /** - * Finishes encrypting or decrypting. - * - * @param pad a padding function to use, null for PKCS#7 padding, - * signature(blockSize, buffer, decrypt). - * - * @return true if successful, false on error. - */ - finish: function(pad) { - var rval = true; + writeUInt32BE(packet, keyLen, p += keyAlgoLen); + packet.set(key, p += 4); - if(encrypt) { - if(pad) { - rval = pad(8, _input, !encrypt); - } else { - // add PKCS#7 padding to block (each pad byte is the - // value of the number of pad bytes) - var padding = (_input.length() === 8) ? 8 : (8 - _input.length()); - _input.fillWithByte(padding, padding); - } - } + this._authsQueue.shift(); + + this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authPasswdChg(prompt) { + if (!this._server) + throw new Error('Server-only method called in client mode'); - if(rval) { - // do final update - _finish = true; - cipher.update(); - } + const promptLen = Buffer.byteLength(prompt); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); - if(!encrypt) { - // check for error: input data not a multiple of block size - rval = (_input.length() === 0); - if(rval) { - if(pad) { - rval = pad(8, _output, !encrypt); - } else { - // ensure padding byte count is valid - var len = _output.length(); - var count = _output.at(len - 1); + packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; - if(count > len) { - rval = false; - } else { - // trim off padding bytes - _output.truncate(count); - } - } - } - } + writeUInt32BE(packet, promptLen, ++p); + packet.utf8Write(prompt, p += 4, promptLen); - return rval; - } - }; + writeUInt32BE(packet, 0, p += promptLen); // Empty language tag - return cipher; -}; + this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authInfoReq(name, instructions, prompts) { + if (!this._server) + throw new Error('Server-only method called in client mode'); -/** - * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the - * given symmetric key. The output will be stored in the 'output' member - * of the returned cipher. - * - * The key and iv may be given as a string of bytes or a byte buffer. - * The cipher is initialized to use 128 effective key bits. - * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * - * @return the cipher. - */ -forge.rc2.startEncrypting = function(key, iv, output) { - var cipher = forge.rc2.createEncryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; -}; + let promptsLen = 0; + const nameLen = name ? Buffer.byteLength(name) : 0; + const instrLen = instructions ? Buffer.byteLength(instructions) : 0; -/** - * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the - * given symmetric key. - * - * The key may be given as a string of bytes or a byte buffer. - * - * To start encrypting call start() on the cipher with an iv and optional - * output buffer. - * - * @param key the symmetric key to use. - * - * @return the cipher. - */ -forge.rc2.createEncryptionCipher = function(key, bits) { - return createCipher(key, bits, true); -}; + for (let i = 0; i < prompts.length; ++i) + promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; -/** - * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the - * given symmetric key. The output will be stored in the 'output' member - * of the returned cipher. - * - * The key and iv may be given as a string of bytes or a byte buffer. - * The cipher is initialized to use 128 effective key bits. - * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * - * @return the cipher. - */ -forge.rc2.startDecrypting = function(key, iv, output) { - var cipher = forge.rc2.createDecryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; -}; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen + ); -/** - * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the - * given symmetric key. - * - * The key may be given as a string of bytes or a byte buffer. - * - * To start decrypting call start() on the cipher with an iv and optional - * output buffer. - * - * @param key the symmetric key to use. - * - * @return the cipher. - */ -forge.rc2.createDecryptionCipher = function(key, bits) { - return createCipher(key, bits, false); -}; + packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; + + writeUInt32BE(packet, nameLen, ++p); + p += 4; + if (name) { + packet.utf8Write(name, p, nameLen); + p += nameLen; + } + writeUInt32BE(packet, instrLen, p); + p += 4; + if (instructions) { + packet.utf8Write(instructions, p, instrLen); + p += instrLen; + } -/***/ }), + writeUInt32BE(packet, 0, p); -/***/ 3921: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + writeUInt32BE(packet, prompts.length, p += 4); + p += 4; + for (let i = 0; i < prompts.length; ++i) { + const prompt = prompts[i]; + const promptLen = Buffer.byteLength(prompt.prompt); -/** - * Javascript implementation of basic RSA algorithms. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - * - * The only algorithm currently supported for PKI is RSA. - * - * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo - * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier - * and a subjectPublicKey of type bit string. - * - * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters - * for the algorithm, if any. In the case of RSA, there aren't any. - * - * SubjectPublicKeyInfo ::= SEQUENCE { - * algorithm AlgorithmIdentifier, - * subjectPublicKey BIT STRING - * } - * - * AlgorithmIdentifer ::= SEQUENCE { - * algorithm OBJECT IDENTIFIER, - * parameters ANY DEFINED BY algorithm OPTIONAL - * } - * - * For an RSA public key, the subjectPublicKey is: - * - * RSAPublicKey ::= SEQUENCE { - * modulus INTEGER, -- n - * publicExponent INTEGER -- e - * } - * - * PrivateKeyInfo ::= SEQUENCE { - * version Version, - * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, - * privateKey PrivateKey, - * attributes [0] IMPLICIT Attributes OPTIONAL - * } - * - * Version ::= INTEGER - * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier - * PrivateKey ::= OCTET STRING - * Attributes ::= SET OF Attribute - * - * An RSA private key as the following structure: - * - * RSAPrivateKey ::= SEQUENCE { - * version Version, - * modulus INTEGER, -- n - * publicExponent INTEGER, -- e - * privateExponent INTEGER, -- d - * prime1 INTEGER, -- p - * prime2 INTEGER, -- q - * exponent1 INTEGER, -- d mod (p-1) - * exponent2 INTEGER, -- d mod (q-1) - * coefficient INTEGER -- (inverse of q) mod p - * } - * - * Version ::= INTEGER - * - * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(9549); -__nccwpck_require__(7052); -__nccwpck_require__(1925); -__nccwpck_require__(7014); -__nccwpck_require__(6861); -__nccwpck_require__(7821); -__nccwpck_require__(8339); + writeUInt32BE(packet, promptLen, p); + p += 4; + if (promptLen) { + packet.utf8Write(prompt.prompt, p, promptLen); + p += promptLen; + } + packet[p++] = (prompt.echo ? 1 : 0); + } -if(typeof BigInteger === 'undefined') { - var BigInteger = forge.jsbn.BigInteger; + this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); + sendPacket(this, this._packetRW.write.finalize(packet)); + } } -var _crypto = forge.util.isNodejs ? __nccwpck_require__(6113) : null; +// SSH-protoversion-softwareversion (SP comments) CR LF +const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; -// shortcut for asn.1 API -var asn1 = forge.asn1; +// TODO: optimize this by starting n bytes from the end of this._buffer instead +// of the beginning +function parseHeader(chunk, p, len) { + let data; + let chunkOffset; + if (this._buffer) { + data = Buffer.allocUnsafe(this._buffer.length + (len - p)); + data.set(this._buffer, 0); + if (p === 0) { + data.set(chunk, this._buffer.length); + } else { + data.set(new Uint8Array(chunk.buffer, + chunk.byteOffset + p, + (len - p)), + this._buffer.length); + } + chunkOffset = this._buffer.length; + p = 0; + } else { + data = chunk; + chunkOffset = 0; + } + const op = p; + let start = p; + let end = p; + let needNL = false; + let lineLen = 0; + let lines = 0; + for (; p < data.length; ++p) { + const ch = data[p]; -// shortcut for util API -var util = forge.util; + if (ch === 13 /* '\r' */) { + needNL = true; + continue; + } -/* - * RSA encryption and decryption, see RFC 2313. - */ -forge.pki = forge.pki || {}; -module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; -var pki = forge.pki; + if (ch === 10 /* '\n' */) { + if (end > start + && end - start > 4 + && data[start] === 83 /* 'S' */ + && data[start + 1] === 83 /* 'S' */ + && data[start + 2] === 72 /* 'H' */ + && data[start + 3] === 45 /* '-' */) { -// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 -var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + const full = data.latin1Slice(op, end + 1); + const identRaw = (start === op ? full : full.slice(start - op)); + const m = RE_IDENT.exec(identRaw); + if (!m) + throw new Error('Invalid identification string'); -// validator for a PrivateKeyInfo structure -var privateKeyValidator = { - // PrivateKeyInfo - name: 'PrivateKeyInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: 'PrivateKeyInfo.version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyVersion' - }, { - // privateKeyAlgorithm - name: 'PrivateKeyInfo.privateKeyAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'privateKeyOid' - }] - }, { - // PrivateKey - name: 'PrivateKeyInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'privateKey' - }] -}; + const header = { + greeting: (start === op ? '' : full.slice(0, start - op)), + identRaw, + versions: { + protocol: m[1], + software: m[2], + }, + comments: m[3] + }; -// validator for an RSA private key -var rsaPrivateKeyValidator = { - // RSAPrivateKey - name: 'RSAPrivateKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: 'RSAPrivateKey.version', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyVersion' - }, { - // modulus (n) - name: 'RSAPrivateKey.modulus', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyModulus' - }, { - // publicExponent (e) - name: 'RSAPrivateKey.publicExponent', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyPublicExponent' - }, { - // privateExponent (d) - name: 'RSAPrivateKey.privateExponent', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyPrivateExponent' - }, { - // prime1 (p) - name: 'RSAPrivateKey.prime1', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyPrime1' - }, { - // prime2 (q) - name: 'RSAPrivateKey.prime2', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyPrime2' - }, { - // exponent1 (d mod (p-1)) - name: 'RSAPrivateKey.exponent1', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyExponent1' - }, { - // exponent2 (d mod (q-1)) - name: 'RSAPrivateKey.exponent2', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyExponent2' - }, { - // coefficient ((inverse of q) mod p) - name: 'RSAPrivateKey.coefficient', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'privateKeyCoefficient' - }] -}; + // Needed during handshake + this._remoteIdentRaw = Buffer.from(identRaw); -// validator for an RSA public key -var rsaPublicKeyValidator = { - // RSAPublicKey - name: 'RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // modulus (n) - name: 'RSAPublicKey.modulus', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'publicKeyModulus' - }, { - // publicExponent (e) - name: 'RSAPublicKey.exponent', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'publicKeyExponent' - }] -}; + this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); + this._compatFlags = getCompatFlags(header); -// validator for an SubjectPublicKeyInfo structure -// Note: Currently only works with an RSA public key -var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { - name: 'SubjectPublicKeyInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'subjectPublicKeyInfo', - value: [{ - name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'publicKeyOid' - }] - }, { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - }] -}; + this._buffer = undefined; + this._decipher = + new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); + this._parse = parsePacket; -// validator for a DigestInfo structure -var digestInfoValidator = { - name: 'DigestInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'DigestInfo.DigestAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'algorithmIdentifier' - }, { - // NULL paramters - name: 'DigestInfo.DigestAlgorithm.parameters', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.NULL, - constructed: false - }] - }, { - // digest - name: 'DigestInfo.digest', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: 'digest' - }] -}; + this._onHeader(header); + if (!this._destruct) { + // We disconnected inside _onHeader + return len; + } -/** - * Wrap digest in DigestInfo object. - * - * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. - * - * DigestInfo ::= SEQUENCE { - * digestAlgorithm DigestAlgorithmIdentifier, - * digest Digest - * } - * - * DigestAlgorithmIdentifier ::= AlgorithmIdentifier - * Digest ::= OCTET STRING - * - * @param md the message digest object with the hash to sign. - * - * @return the encoded message (ready for RSA encrytion) - */ -var emsaPkcs1v15encode = function(md) { - // get the oid for the algorithm - var oid; - if(md.algorithm in pki.oids) { - oid = pki.oids[md.algorithm]; - } else { - var error = new Error('Unknown message digest algorithm.'); - error.algorithm = md.algorithm; - throw error; - } - var oidBytes = asn1.oidToDer(oid).getBytes(); + kexinit(this); - // create the digest info - var digestInfo = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var digestAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); - var digest = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, - false, md.digest().getBytes()); - digestInfo.value.push(digestAlgorithm); - digestInfo.value.push(digest); + return p + 1 - chunkOffset; + } - // encode digest info - return asn1.toDer(digestInfo).getBytes(); -}; + // Only allow pre-ident greetings when we're a client + if (this._server) + throw new Error('Greetings from clients not permitted'); -/** - * Performs x^c mod n (RSA encryption or decryption operation). - * - * @param x the number to raise and mod. - * @param key the key to use. - * @param pub true if the key is public, false if private. - * - * @return the result of x^c mod n. - */ -var _modPow = function(x, key, pub) { - if(pub) { - return x.modPow(key.e, key.n); + if (++lines > MAX_LINES) + throw new Error('Max greeting lines exceeded'); + + needNL = false; + start = p + 1; + lineLen = 0; + } else if (needNL) { + throw new Error('Invalid header: expected newline'); + } else if (++lineLen >= MAX_LINE_LEN) { + throw new Error('Header line too long'); + } + + end = p; } + if (!this._buffer) + this._buffer = bufferSlice(data, op); - if(!key.p || !key.q) { - // allow calculation without CRT params (slow) - return x.modPow(key.d, key.n); + return p - chunkOffset; +} + +function parsePacket(chunk, p, len) { + return this._decipher.decrypt(chunk, p, len); +} + +function onPayload(payload) { + // XXX: move this to the Decipher implementations? + + this._onPacket(); + + if (payload.length === 0) { + this._debug && this._debug('Inbound: Skipping empty packet payload'); + return; } - // pre-compute dP, dQ, and qInv if necessary - if(!key.dP) { - key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); + payload = this._packetRW.read.read(payload); + + const type = payload[0]; + if (type === MESSAGE.USERAUTH_SUCCESS + && !this._server + && !this._authenticated) { + this._authenticated = true; + if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') + this._packetRW.write = new ZlibPacketWriter(this); + if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') + this._packetRW.read = new ZlibPacketReader(); } - if(!key.dQ) { - key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); + const handler = MESSAGE_HANDLERS[type]; + if (handler === undefined) { + this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); + return; } - if(!key.qInv) { - key.qInv = key.q.modInverse(key.p); + + return handler(this, payload); +} + +function getCompatFlags(header) { + const software = header.versions.software; + + let flags = 0; + + for (const rule of COMPAT_CHECKS) { + if (typeof rule[0] === 'string') { + if (software === rule[0]) + flags |= rule[1]; + } else if (rule[0].test(software)) { + flags |= rule[1]; + } } - /* Chinese remainder theorem (CRT) states: + return flags; +} - Suppose n1, n2, ..., nk are positive integers which are pairwise - coprime (n1 and n2 have no common factors other than 1). For any - integers x1, x2, ..., xk there exists an integer x solving the - system of simultaneous congruences (where ~= means modularly - congruent so a ~= b mod n means a mod n = b mod n): +function modesToBytes(modes) { + const keys = Object.keys(modes); + const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); + let b = 0; - x ~= x1 mod n1 - x ~= x2 mod n2 - ... - x ~= xk mod nk + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (key === 'TTY_OP_END') + continue; - This system of congruences has a single simultaneous solution x - between 0 and n - 1. Furthermore, each xk solution and x itself - is congruent modulo the product n = n1*n2*...*nk. - So x1 mod n = x2 mod n = xk mod n = x mod n. + const opcode = TERMINAL_MODE[key]; + if (opcode === undefined) + continue; - The single simultaneous solution x can be solved with the following - equation: + const val = modes[key]; + if (typeof val === 'number' && isFinite(val)) { + bytes[b++] = opcode; + bytes[b++] = val >>> 24; + bytes[b++] = val >>> 16; + bytes[b++] = val >>> 8; + bytes[b++] = val; + } + } - x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. + bytes[b++] = TERMINAL_MODE.TTY_OP_END; - Where x is less than n, xi = x mod ni. + if (b < bytes.length) + return bufferSlice(bytes, 0, b); - For RSA we are only concerned with k = 2. The modulus n = pq, where - p and q are coprime. The RSA decryption algorithm is: + return bytes; +} - y = x^d mod n +function sendExtInfo(proto) { + let serverSigAlgs = + 'ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521' + + 'rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss'; + if (eddsaSupported) + serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`; + const algsLen = Buffer.byteLength(serverSigAlgs); - Given the above: + let p = proto._packetRW.write.allocStart; + const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen); - x1 = x^d mod p - r1 = n/p = q - s1 = q^-1 mod p - x2 = x^d mod q - r2 = n/q = p - s2 = p^-1 mod q + packet[p] = MESSAGE.EXT_INFO; - So y = (x1r1s1 + x2r2s2) mod n - = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n + writeUInt32BE(packet, 1, ++p); - According to Fermat's Little Theorem, if the modulus P is prime, - for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. - Since A is not divisible by P it follows that if: - N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: + writeUInt32BE(packet, 15, p += 4); + packet.utf8Write('server-sig-algs', p += 4, 15); - A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort - to calculate). In order to calculate x^d mod p more quickly the - exponent d mod (p - 1) is stored in the RSA private key (the same - is done for x^d mod q). These values are referred to as dP and dQ - respectively. Therefore we now have: + writeUInt32BE(packet, algsLen, p += 15); + packet.utf8Write(serverSigAlgs, p += 4, algsLen); - y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n + proto._debug && proto._debug('Outbound: Sending EXT_INFO'); + sendPacket(proto, proto._packetRW.write.finalize(packet)); +} - Since we'll be reducing x^dP by modulo p (same for q) we can also - reduce x by p (and q respectively) before hand. Therefore, let +module.exports = Protocol; - xp = ((x mod p)^dP mod p), and - xq = ((x mod q)^dQ mod q), yielding: - y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n +/***/ }), - This can be further reduced to a simple algorithm that only - requires 1 inverse (the q inverse is used) to be used and stored. - The algorithm is called Garner's algorithm. If qInv is the - inverse of q, we simply calculate: +/***/ 2026: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - y = (qInv*(xp - xq) mod p) * q + xq +"use strict"; - However, there are two further complications. First, we need to - ensure that xp > xq to prevent signed BigIntegers from being used - so we add p until this is true (since we will be mod'ing with - p anyway). Then, there is a known timing attack on algorithms - using the CRT. To mitigate this risk, "cryptographic blinding" - should be used. This requires simply generating a random number r - between 0 and n-1 and its inverse and multiplying x by r^e before - calculating y and then multiplying y by r^-1 afterwards. Note that - r must be coprime with n (gcd(r, n) === 1) in order to have an - inverse. - */ - // cryptographic blinding - var r; - do { - r = new BigInteger( - forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), - 16); - } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); - x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); +const EventEmitter = __nccwpck_require__(2361); +const fs = __nccwpck_require__(7147); +const { constants } = fs; +const { + Readable: ReadableStream, + Writable: WritableStream +} = __nccwpck_require__(2781); +const { inherits, isDate } = __nccwpck_require__(3837); - // calculate xp and xq - var xp = x.mod(key.p).modPow(key.dP, key.p); - var xq = x.mod(key.q).modPow(key.dQ, key.q); +const FastBuffer = Buffer[Symbol.species]; - // xp must be larger than xq to avoid signed bit usage - while(xp.compareTo(xq) < 0) { - xp = xp.add(key.p); - } +const { + bufferCopy, + bufferSlice, + makeBufferParser, + writeUInt32BE, +} = __nccwpck_require__(9475); - // do last step - var y = xp.subtract(xq) - .multiply(key.qInv).mod(key.p) - .multiply(key.q).add(xq); +const ATTR = { + SIZE: 0x00000001, + UIDGID: 0x00000002, + PERMISSIONS: 0x00000004, + ACMODTIME: 0x00000008, + EXTENDED: 0x80000000, +}; - // remove effect of random for cryptographic blinding - y = y.multiply(r.modInverse(key.n)).mod(key.n); +// Large enough to store all possible attributes +const ATTRS_BUF = Buffer.alloc(28); - return y; +const STATUS_CODE = { + OK: 0, + EOF: 1, + NO_SUCH_FILE: 2, + PERMISSION_DENIED: 3, + FAILURE: 4, + BAD_MESSAGE: 5, + NO_CONNECTION: 6, + CONNECTION_LOST: 7, + OP_UNSUPPORTED: 8 }; -/** - * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or - * 'encrypt' on a public key object instead. - * - * Performs RSA encryption. - * - * The parameter bt controls whether to put padding bytes before the - * message passed in. Set bt to either true or false to disable padding - * completely (in order to handle e.g. EMSA-PSS encoding seperately before), - * signaling whether the encryption operation is a public key operation - * (i.e. encrypting data) or not, i.e. private key operation (data signing). - * - * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 - * (for signing) or 0x02 (for encryption). The key operation mode (private - * or public) is derived from this flag in that case). - * - * @param m the message to encrypt as a byte string. - * @param key the RSA key to use. - * @param bt for PKCS#1 v1.5 padding, the block type to use - * (0x01 for private key, 0x02 for public), - * to disable padding: true = public key, false = private key. - * - * @return the encrypted bytes as a string. - */ -pki.rsa.encrypt = function(m, key, bt) { - var pub = bt; - var eb; +const VALID_STATUS_CODES = new Map( + Object.values(STATUS_CODE).map((n) => [n, 1]) +); - // get the length of the modulus in bytes - var k = Math.ceil(key.n.bitLength() / 8); +const STATUS_CODE_STR = { + [STATUS_CODE.OK]: 'No error', + [STATUS_CODE.EOF]: 'End of file', + [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', + [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', + [STATUS_CODE.FAILURE]: 'Failure', + [STATUS_CODE.BAD_MESSAGE]: 'Bad message', + [STATUS_CODE.NO_CONNECTION]: 'No connection', + [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', + [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', +}; - if(bt !== false && bt !== true) { - // legacy, default to PKCS#1 v1.5 padding - pub = (bt === 0x02); - eb = _encodePkcs1_v1_5(m, key, bt); - } else { - eb = forge.util.createBuffer(); - eb.putBytes(m); +const REQUEST = { + INIT: 1, + OPEN: 3, + CLOSE: 4, + READ: 5, + WRITE: 6, + LSTAT: 7, + FSTAT: 8, + SETSTAT: 9, + FSETSTAT: 10, + OPENDIR: 11, + READDIR: 12, + REMOVE: 13, + MKDIR: 14, + RMDIR: 15, + REALPATH: 16, + STAT: 17, + RENAME: 18, + READLINK: 19, + SYMLINK: 20, + EXTENDED: 200 +}; + +const RESPONSE = { + VERSION: 2, + STATUS: 101, + HANDLE: 102, + DATA: 103, + NAME: 104, + ATTRS: 105, + EXTENDED: 201 +}; + +const OPEN_MODE = { + READ: 0x00000001, + WRITE: 0x00000002, + APPEND: 0x00000004, + CREAT: 0x00000008, + TRUNC: 0x00000010, + EXCL: 0x00000020 +}; + +const PKT_RW_OVERHEAD = 2 * 1024; +const MAX_REQID = 2 ** 32 - 1; +const CLIENT_VERSION_BUFFER = Buffer.from([ + 0, 0, 0, 5 /* length */, + REQUEST.INIT, + 0, 0, 0, 3 /* version */ +]); +const SERVER_VERSION_BUFFER = Buffer.from([ + 0, 0, 0, 5 /* length */, + RESPONSE.VERSION, + 0, 0, 0, 3 /* version */ +]); + +const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; +const OPENSSH_MAX_PKT_LEN = 256 * 1024; + +const bufferParser = makeBufferParser(); + +const fakeStderr = { + readable: false, + writable: false, + push: (data) => {}, + once: () => {}, + on: () => {}, + emit: () => {}, + end: () => {}, +}; + +function noop() {} + +// Emulates enough of `Channel` to be able to be used as a drop-in replacement +// in order to process incoming data with as little overhead as possible +class SFTP extends EventEmitter { + constructor(client, chanInfo, cfg) { + super(); + + if (typeof cfg !== 'object' || !cfg) + cfg = {}; + + const remoteIdentRaw = client._protocol._remoteIdentRaw; + + this.server = !!cfg.server; + this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); + this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); + + this._version = -1; + this._extensions = {}; + this._biOpt = cfg.biOpt; + this._pktLenBytes = 0; + this._pktLen = 0; + this._pktPos = 0; + this._pktType = 0; + this._pktData = undefined; + this._writeReqid = -1; + this._requests = {}; + this._maxInPktLen = OPENSSH_MAX_PKT_LEN; + this._maxOutPktLen = 34000; + this._maxReadLen = + (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; + this._maxWriteLen = + (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; + + this.maxOpenHandles = undefined; + + // Channel compatibility + this._client = client; + this._protocol = client._protocol; + this._callbacks = []; + this._hasX11 = false; + this._exit = { + code: undefined, + signal: undefined, + dump: undefined, + desc: undefined, + }; + this._waitWindow = false; // SSH-level backpressure + this._chunkcb = undefined; + this._buffer = []; + this.type = chanInfo.type; + this.subtype = undefined; + this.incoming = chanInfo.incoming; + this.outgoing = chanInfo.outgoing; + this.stderr = fakeStderr; + this.readable = true; } - // load encryption block as big integer 'x' - // FIXME: hex conversion inefficient, get BigInteger w/byte strings - var x = new BigInteger(eb.toHex(), 16); + // This handles incoming data to parse + push(data) { + if (data === null) { + cleanupRequests(this); + if (!this.readable) + return; + // No more incoming data from the remote side + this.readable = false; + this.emit('end'); + return; + } + /* + uint32 length + byte type + byte[length - 1] data payload + */ + let p = 0; + + while (p < data.length) { + if (this._pktLenBytes < 4) { + let nb = Math.min(4 - this._pktLenBytes, data.length - p); + this._pktLenBytes += nb; + + while (nb--) + this._pktLen = (this._pktLen << 8) + data[p++]; + + if (this._pktLenBytes < 4) + return; + if (this._pktLen === 0) + return doFatalSFTPError(this, 'Invalid packet length'); + if (this._pktLen > this._maxInPktLen) { + const max = this._maxInPktLen; + return doFatalSFTPError( + this, + `Packet length ${this._pktLen} exceeds max length of ${max}` + ); + } + if (p >= data.length) + return; + } + if (this._pktPos < this._pktLen) { + const nb = Math.min(this._pktLen - this._pktPos, data.length - p); + if (p !== 0 || nb !== data.length) { + if (nb === this._pktLen) { + this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); + } else { + if (!this._pkt) + this._pkt = Buffer.allocUnsafe(this._pktLen); + this._pkt.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._pktPos + ); + } + } else if (nb === this._pktLen) { + this._pkt = data; + } else { + if (!this._pkt) + this._pkt = Buffer.allocUnsafe(this._pktLen); + this._pkt.set(data, this._pktPos); + } + p += nb; + this._pktPos += nb; + if (this._pktPos < this._pktLen) + return; + } + + const type = this._pkt[0]; + const payload = this._pkt; - // do RSA encryption - var y = _modPow(x, key, pub); + // Prepare for next packet + this._pktLen = 0; + this._pktLenBytes = 0; + this._pkt = undefined; + this._pktPos = 0; - // convert y into the encrypted data byte string, if y is shorter in - // bytes than k, then prepend zero bytes to fill up ed - // FIXME: hex conversion inefficient, get BigInteger w/byte strings - var yhex = y.toString(16); - var ed = forge.util.createBuffer(); - var zeros = k - Math.ceil(yhex.length / 2); - while(zeros > 0) { - ed.putByte(0x00); - --zeros; - } - ed.putBytes(forge.util.hexToBytes(yhex)); - return ed.getBytes(); -}; + const handler = (this.server + ? SERVER_HANDLERS[type] + : CLIENT_HANDLERS[type]); + if (!handler) + return doFatalSFTPError(this, `Unknown packet type ${type}`); -/** - * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or - * 'verify' on a public key object instead. - * - * Performs RSA decryption. - * - * The parameter ml controls whether to apply PKCS#1 v1.5 padding - * or not. Set ml = false to disable padding removal completely - * (in order to handle e.g. EMSA-PSS later on) and simply pass back - * the RSA encryption block. - * - * @param ed the encrypted data to decrypt in as a byte string. - * @param key the RSA key to use. - * @param pub true for a public key operation, false for private. - * @param ml the message length, if known, false to disable padding. - * - * @return the decrypted message as a byte string. - */ -pki.rsa.decrypt = function(ed, key, pub, ml) { - // get the length of the modulus in bytes - var k = Math.ceil(key.n.bitLength() / 8); + if (this._version === -1) { + if (this.server) { + if (type !== REQUEST.INIT) + return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); + } else if (type !== RESPONSE.VERSION) { + return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); + } + } - // error if the length of the encrypted data ED is not k - if(ed.length !== k) { - var error = new Error('Encrypted message length is invalid.'); - error.length = ed.length; - error.expected = k; - throw error; + if (handler(this, payload) === false) + return; + } } - // convert encrypted data into a big integer - // FIXME: hex conversion inefficient, get BigInteger w/byte strings - var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); - - // y must be less than the modulus or it wasn't the result of - // a previous mod operation (encryption) using that modulus - if(y.compareTo(key.n) >= 0) { - throw new Error('Encrypted message is invalid.'); + end() { + this.destroy(); } - - // do RSA decryption - var x = _modPow(y, key, pub); - - // create the encryption block, if x is shorter in bytes than k, then - // prepend zero bytes to fill up eb - // FIXME: hex conversion inefficient, get BigInteger w/byte strings - var xhex = x.toString(16); - var eb = forge.util.createBuffer(); - var zeros = k - Math.ceil(xhex.length / 2); - while(zeros > 0) { - eb.putByte(0x00); - --zeros; + destroy() { + if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { + this.outgoing.state = 'closing'; + this._protocol.channelClose(this.outgoing.id); + } } - eb.putBytes(forge.util.hexToBytes(xhex)); - - if(ml !== false) { - // legacy, default to PKCS#1 v1.5 padding - return _decodePkcs1_v1_5(eb.getBytes(), key, pub); + _init() { + this._init = noop; + if (!this.server) + sendOrBuffer(this, CLIENT_VERSION_BUFFER); } - // return message - return eb.getBytes(); -}; + // =========================================================================== + // Client-specific =========================================================== + // =========================================================================== + createReadStream(path, options) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Creates an RSA key-pair generation state object. It is used to allow - * key-generation to be performed in steps. It also allows for a UI to - * display progress updates. - * - * @param bits the size for the private key in bits, defaults to 2048. - * @param e the public exponent to use, defaults to 65537 (0x10001). - * @param [options] the options to use. - * prng a custom crypto-secure pseudo-random number generator to use, - * that must define "getBytesSync". - * algorithm the algorithm to use (default: 'PRIMEINC'). - * - * @return the state object to use to generate the key-pair. - */ -pki.rsa.createKeyPairGenerationState = function(bits, e, options) { - // TODO: migrate step-based prime generation code to forge.prime + return new ReadStream(this, path, options); + } + createWriteStream(path, options) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // set default bits - if(typeof(bits) === 'string') { - bits = parseInt(bits, 10); + return new WriteStream(this, path, options); } - bits = bits || 2048; + open(path, flags_, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // create prng with api that matches BigInteger secure random - options = options || {}; - var prng = options.prng || forge.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for(var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } + if (typeof attrs === 'function') { + cb = attrs; + attrs = undefined; } - }; - var algorithm = options.algorithm || 'PRIMEINC'; + const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); + if (flags === null) + throw new Error(`Unknown flags string: ${flags_}`); - // create PRIMEINC algorithm state - var rval; - if(algorithm === 'PRIMEINC') { - rval = { - algorithm: algorithm, - state: 0, - bits: bits, - rng: rng, - eInt: e || 65537, - e: new BigInteger(null), - p: null, - q: null, - qBits: bits >> 1, - pBits: bits - (bits >> 1), - pqState: 0, - num: null, - keys: null - }; - rval.e.fromInt(rval.eInt); - } else { - throw new Error('Invalid key generation algorithm: ' + algorithm); - } + let attrsFlags = 0; + let attrsLen = 0; + if (typeof attrs === 'string' || typeof attrs === 'number') + attrs = { mode: attrs }; + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + attrsFlags = attrs.flags; + attrsLen = attrs.nb; + } - return rval; -}; + /* + uint32 id + string filename + uint32 pflags + ATTRS attrs + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); -/** - * Attempts to runs the key-generation algorithm for at most n seconds - * (approximately) using the given state. When key-generation has completed, - * the keys will be stored in state.keys. - * - * To use this function to update a UI while generating a key or to prevent - * causing browser lockups/warnings, set "n" to a value other than 0. A - * simple pattern for generating a key and showing a progress indicator is: - * - * var state = pki.rsa.createKeyPairGenerationState(2048); - * var step = function() { - * // step key-generation, run algorithm for 100 ms, repeat - * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { - * setTimeout(step, 1); - * } else { - * // key-generation complete - * // TODO: turn off progress indicator here - * // TODO: use the generated key-pair in "state.keys" - * } - * }; - * // TODO: turn on progress indicator here - * setTimeout(step, 0); - * - * @param state the state to use. - * @param n the maximum number of milliseconds to run the algorithm for, 0 - * to run the algorithm to completion. - * - * @return true if the key-generation completed, false if not. - */ -pki.rsa.stepKeyPairGenerationState = function(state, n) { - // set default algorithm if not set - if(!('algorithm' in state)) { - state.algorithm = 'PRIMEINC'; - } + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.OPEN; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - // TODO: migrate step-based prime generation code to forge.prime - // TODO: abstract as PRIMEINC algorithm + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + writeUInt32BE(buf, attrsFlags, p += 4); + if (attrsLen) { + p += 4; - // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) - // with some minor optimizations and designed to run in steps + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - // local state vars - var THIRTY = new BigInteger(null); - THIRTY.fromInt(30); - var deltaIdx = 0; - var op_or = function(x, y) {return x | y;}; + p += attrsLen; + } + this._requests[reqid] = { cb }; - // keep stepping until time limit is reached or done - var t1 = +new Date(); - var t2; - var total = 0; - while(state.keys === null && (n <= 0 || total < n)) { - // generate p or q - if(state.state === 0) { - /* Note: All primes are of the form: + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` + ); + } + close(handle, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - When we generate a random number, we always align it at 30k + 1. Each - time the number is determined not to be prime we add to get to the - next 'i', eg: if the number was at 30k + 1 we add 6. */ - var bits = (state.p === null) ? state.pBits : state.qBits; - var bits1 = bits - 1; + /* + uint32 id + string handle + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - // get a random number - if(state.pqState === 0) { - state.num = new BigInteger(bits, state.rng); - // force MSB set - if(!state.num.testBit(bits1)) { - state.num.bitwiseTo( - BigInteger.ONE.shiftLeft(bits1), op_or, state.num); - } - // align number on 30k+1 boundary - state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); - deltaIdx = 0; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.CLOSE; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - ++state.pqState; - } else if(state.pqState === 1) { - // try to make the number a prime - if(state.num.bitLength() > bits) { - // overflow, try again - state.pqState = 0; - // do primality test - } else if(state.num.isProbablePrime( - _getMillerRabinTests(state.num.bitLength()))) { - ++state.pqState; - } else { - // get next potential prime - state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } - } else if(state.pqState === 2) { - // ensure number is coprime with e - state.pqState = - (state.num.subtract(BigInteger.ONE).gcd(state.e) - .compareTo(BigInteger.ONE) === 0) ? 3 : 0; - } else if(state.pqState === 3) { - // store p or q - state.pqState = 0; - if(state.p === null) { - state.p = state.num; - } else { - state.q = state.num; - } + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); - // advance state if both p and q are ready - if(state.p !== null && state.q !== null) { - ++state.state; - } - state.num = null; - } - } else if(state.state === 1) { - // ensure p is larger than q (swap them if not) - if(state.p.compareTo(state.q) < 0) { - state.num = state.p; - state.p = state.q; - state.q = state.num; - } - ++state.state; - } else if(state.state === 2) { - // compute phi: (p - 1)(q - 1) (Euler's totient function) - state.p1 = state.p.subtract(BigInteger.ONE); - state.q1 = state.q.subtract(BigInteger.ONE); - state.phi = state.p1.multiply(state.q1); - ++state.state; - } else if(state.state === 3) { - // ensure e and phi are coprime - if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { - // phi and e are coprime, advance - ++state.state; - } else { - // phi and e aren't coprime, so generate a new p and q - state.p = null; - state.q = null; - state.state = 0; - } - } else if(state.state === 4) { - // create n, ensure n is has the right number of bits - state.n = state.p.multiply(state.q); + this._requests[reqid] = { cb }; - // ensure n is right number of bits - if(state.n.bitLength() === state.bits) { - // success, advance - ++state.state; - } else { - // failed, get new q - state.q = null; - state.state = 0; - } - } else if(state.state === 5) { - // set keys - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki.rsa.setPrivateKey( - state.n, state.e, d, state.p, state.q, - d.mod(state.p1), d.mod(state.q1), - state.q.modInverse(state.p)), - publicKey: pki.rsa.setPublicKey(state.n, state.e) - }; - } + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` + ); + } + read(handle, buf, off, len, position, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); + if (!Buffer.isBuffer(buf)) + throw new Error('buffer is not a Buffer'); + if (off >= buf.length) + throw new Error('offset is out of bounds'); + if (off + len > buf.length) + throw new Error('length extends beyond buffer'); + if (position === null) + throw new Error('null position currently unsupported'); - // update timing - t2 = +new Date(); - total += t2 - t1; - t1 = t2; + read_(this, handle, buf, off, len, position, cb); + } + readData(handle, buf, off, len, position, cb) { + // Backwards compatibility + this.read(handle, buf, off, len, position, cb); } + write(handle, buf, off, len, position, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - return state.keys !== null; -}; + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); + if (!Buffer.isBuffer(buf)) + throw new Error('buffer is not a Buffer'); + if (off > buf.length) + throw new Error('offset is out of bounds'); + if (off + len > buf.length) + throw new Error('length extends beyond buffer'); + if (position === null) + throw new Error('null position currently unsupported'); -/** - * Generates an RSA public-private key pair in a single call. - * - * To generate a key-pair in steps (to allow for progress updates and to - * prevent blocking or warnings in slow browsers) then use the key-pair - * generation state functions. - * - * To generate a key-pair asynchronously (either through web-workers, if - * available, or by breaking up the work on the main thread), pass a - * callback function. - * - * @param [bits] the size for the private key in bits, defaults to 2048. - * @param [e] the public exponent to use, defaults to 65537. - * @param [options] options for key-pair generation, if given then 'bits' - * and 'e' must *not* be given: - * bits the size for the private key in bits, (default: 2048). - * e the public exponent to use, (default: 65537 (0x10001)). - * workerScript the worker script URL. - * workers the number of web workers (if supported) to use, - * (default: 2). - * workLoad the size of the work load, ie: number of possible prime - * numbers for each web worker to check per work assignment, - * (default: 100). - * prng a custom crypto-secure pseudo-random number generator to use, - * that must define "getBytesSync". Disables use of native APIs. - * algorithm the algorithm to use (default: 'PRIMEINC'). - * @param [callback(err, keypair)] called once the operation completes. - * - * @return an object with privateKey and publicKey properties. - */ -pki.rsa.generateKeyPair = function(bits, e, options, callback) { - // (bits), (options), (callback) - if(arguments.length === 1) { - if(typeof bits === 'object') { - options = bits; - bits = undefined; - } else if(typeof bits === 'function') { - callback = bits; - bits = undefined; - } - } else if(arguments.length === 2) { - // (bits, e), (bits, options), (bits, callback), (options, callback) - if(typeof bits === 'number') { - if(typeof e === 'function') { - callback = e; - e = undefined; - } else if(typeof e !== 'number') { - options = e; - e = undefined; - } - } else { - options = bits; - callback = e; - bits = undefined; - e = undefined; + if (!len) { + cb && process.nextTick(cb, undefined, 0); + return; } - } else if(arguments.length === 3) { - // (bits, e, options), (bits, e, callback), (bits, options, callback) - if(typeof e === 'number') { - if(typeof options === 'function') { - callback = options; - options = undefined; + + const maxDataLen = this._maxWriteLen; + const overflow = Math.max(len - maxDataLen, 0); + const origPosition = position; + + if (overflow) + len = maxDataLen; + + /* + uint32 id + string handle + uint64 offset + string data + */ + const handleLen = handle.length; + let p = 9; + const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); + + writeUInt32BE(out, out.length - 4, 0); + out[4] = REQUEST.WRITE; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(out, reqid, 5); + + writeUInt32BE(out, handleLen, p); + out.set(handle, p += 4); + p += handleLen; + for (let i = 7; i >= 0; --i) { + out[p + i] = position & 0xFF; + position /= 256; + } + writeUInt32BE(out, len, p += 8); + bufferCopy(buf, out, off, off + len, p += 4); + + this._requests[reqid] = { + cb: (err) => { + if (err) { + if (typeof cb === 'function') + cb(err); + } else if (overflow) { + this.write(handle, + buf, + off + len, + overflow, + origPosition + len, + cb); + } else if (typeof cb === 'function') { + cb(undefined, off + len); + } } - } else { - callback = options; - options = e; - e = undefined; + }; + + const isSent = sendOrBuffer(this, out); + if (this._debug) { + const how = (isSent ? 'Sent' : 'Buffered'); + this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); } } - options = options || {}; - if(bits === undefined) { - bits = options.bits || 2048; + writeData(handle, buf, off, len, position, cb) { + // Backwards compatibility + this.write(handle, buf, off, len, position, cb); } - if(e === undefined) { - e = options.e || 0x10001; + fastGet(remotePath, localPath, opts, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); + + fastXfer(this, fs, remotePath, localPath, opts, cb); } + fastPut(localPath, remotePath, opts, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // use native code if permitted, available, and parameters are acceptable - if(!forge.options.usePureJavaScript && !options.prng && - bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { - if(callback) { - // try native async - if(_detectNodeCrypto('generateKeyPair')) { - return _crypto.generateKeyPair('rsa', { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: 'spki', - format: 'pem' - }, - privateKeyEncoding: { - type: 'pkcs8', - format: 'pem' - } - }, function(err, pub, priv) { - if(err) { - return callback(err); - } - callback(null, { - privateKey: pki.privateKeyFromPem(priv), - publicKey: pki.publicKeyFromPem(pub) - }); - }); - } - if(_detectSubtleCrypto('generateKey') && - _detectSubtleCrypto('exportKey')) { - // use standard native generateKey - return util.globalScope.crypto.subtle.generateKey({ - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: {name: 'SHA-256'} - }, true /* key can be exported*/, ['sign', 'verify']) - .then(function(pair) { - return util.globalScope.crypto.subtle.exportKey( - 'pkcs8', pair.privateKey); - // avoiding catch(function(err) {...}) to support IE <= 8 - }).then(undefined, function(err) { - callback(err); - }).then(function(pkcs8) { - if(pkcs8) { - var privateKey = pki.privateKeyFromAsn1( - asn1.fromDer(forge.util.createBuffer(pkcs8))); - callback(null, { - privateKey: privateKey, - publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) - }); - } - }); + fastXfer(fs, this, localPath, remotePath, opts, cb); + } + readFile(path, options, callback_) { + if (this.server) + throw new Error('Client-only method called in server mode'); + + let callback; + if (typeof callback_ === 'function') { + callback = callback_; + } else if (typeof options === 'function') { + callback = options; + options = undefined; + } + + if (typeof options === 'string') + options = { encoding: options, flag: 'r' }; + else if (!options) + options = { encoding: null, flag: 'r' }; + else if (typeof options !== 'object') + throw new TypeError('Bad arguments'); + + const encoding = options.encoding; + if (encoding && !Buffer.isEncoding(encoding)) + throw new Error(`Unknown encoding: ${encoding}`); + + // First stat the file, so we know the size. + let size; + let buffer; // Single buffer with file data + let buffers; // List for when size is unknown + let pos = 0; + let handle; + + // SFTPv3 does not support using -1 for read position, so we have to track + // read position manually + let bytesRead = 0; + + const flag = options.flag || 'r'; + + const read = () => { + if (size === 0) { + buffer = Buffer.allocUnsafe(8192); + this.read(handle, buffer, 0, 8192, bytesRead, afterRead); + } else { + this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); } - if(_detectSubtleMsCrypto('generateKey') && - _detectSubtleMsCrypto('exportKey')) { - var genOp = util.globalScope.msCrypto.subtle.generateKey({ - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: {name: 'SHA-256'} - }, true /* key can be exported*/, ['sign', 'verify']); - genOp.oncomplete = function(e) { - var pair = e.target.result; - var exportOp = util.globalScope.msCrypto.subtle.exportKey( - 'pkcs8', pair.privateKey); - exportOp.oncomplete = function(e) { - var pkcs8 = e.target.result; - var privateKey = pki.privateKeyFromAsn1( - asn1.fromDer(forge.util.createBuffer(pkcs8))); - callback(null, { - privateKey: privateKey, - publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) - }); - }; - exportOp.onerror = function(err) { - callback(err); - }; - }; - genOp.onerror = function(err) { - callback(err); - }; - return; + }; + + const afterRead = (er, nbytes) => { + let eof; + if (er) { + eof = (er.code === STATUS_CODE.EOF); + if (!eof) { + return this.close(handle, () => { + return callback && callback(er); + }); + } + } else { + eof = false; } - } else { - // try native sync - if(_detectNodeCrypto('generateKeyPairSync')) { - var keypair = _crypto.generateKeyPairSync('rsa', { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: 'spki', - format: 'pem' - }, - privateKeyEncoding: { - type: 'pkcs8', - format: 'pem' - } - }); - return { - privateKey: pki.privateKeyFromPem(keypair.privateKey), - publicKey: pki.publicKeyFromPem(keypair.publicKey) - }; + + if (eof || (size === 0 && nbytes === 0)) + return close(); + + bytesRead += nbytes; + pos += nbytes; + if (size !== 0) { + if (pos === size) + close(); + else + read(); + } else { + // Unknown size, just read until we don't get bytes. + buffers.push(bufferSlice(buffer, 0, nbytes)); + read(); } - } - } + }; + afterRead._wantEOFError = true; - // use JavaScript implementation - var state = pki.rsa.createKeyPairGenerationState(bits, e, options); - if(!callback) { - pki.rsa.stepKeyPairGenerationState(state, 0); - return state.keys; - } - _generateKeyPair(state, options, callback); -}; + const close = () => { + this.close(handle, (er) => { + if (size === 0) { + // Collect the data into the buffers list. + buffer = Buffer.concat(buffers, pos); + } else if (pos < size) { + buffer = bufferSlice(buffer, 0, pos); + } -/** - * Sets an RSA public key from BigIntegers modulus and exponent. - * - * @param n the modulus. - * @param e the exponent. - * - * @return the public key. - */ -pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { - var key = { - n: n, - e: e - }; + if (encoding) + buffer = buffer.toString(encoding); + return callback && callback(er, buffer); + }); + }; - /** - * Encrypts the given data with this public key. Newer applications - * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for - * legacy applications. - * - * @param data the byte string to encrypt. - * @param scheme the encryption scheme to use: - * 'RSAES-PKCS1-V1_5' (default), - * 'RSA-OAEP', - * 'RAW', 'NONE', or null to perform raw RSA encryption, - * an object with an 'encode' property set to a function - * with the signature 'function(data, key)' that returns - * a binary-encoded string representing the encoded data. - * @param schemeOptions any scheme-specific options. - * - * @return the encrypted byte string. - */ - key.encrypt = function(data, scheme, schemeOptions) { - if(typeof scheme === 'string') { - scheme = scheme.toUpperCase(); - } else if(scheme === undefined) { - scheme = 'RSAES-PKCS1-V1_5'; - } + this.open(path, flag, 0o666, (er, handle_) => { + if (er) + return callback && callback(er); + handle = handle_; - if(scheme === 'RSAES-PKCS1-V1_5') { - scheme = { - encode: function(m, key, pub) { - return _encodePkcs1_v1_5(m, key, 0x02).getBytes(); - } - }; - } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { - scheme = { - encode: function(m, key) { - return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions); + const tryStat = (er, st) => { + if (er) { + // Try stat() for sftp servers that may not support fstat() for + // whatever reason + this.stat(path, (er_, st_) => { + if (er_) { + return this.close(handle, () => { + callback && callback(er); + }); + } + tryStat(null, st_); + }); + return; } - }; - } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { - scheme = {encode: function(e) {return e;}}; - } else if(typeof scheme === 'string') { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - // do scheme-based encoding then rsa encryption - var e = scheme.encode(data, key, true); - return pki.rsa.encrypt(e, key, true); - }; + size = st.size || 0; + if (size === 0) { + // The kernel lies about many files. + // Go ahead and try to read some bytes. + buffers = []; + return read(); + } - /** - * Verifies the given signature against the given digest. - * - * PKCS#1 supports multiple (currently two) signature schemes: - * RSASSA-PKCS1-V1_5 and RSASSA-PSS. - * - * By default this implementation uses the "old scheme", i.e. - * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the - * signature is an OCTET STRING that holds a DigestInfo. - * - * DigestInfo ::= SEQUENCE { - * digestAlgorithm DigestAlgorithmIdentifier, - * digest Digest - * } - * DigestAlgorithmIdentifier ::= AlgorithmIdentifier - * Digest ::= OCTET STRING - * - * To perform PSS signature verification, provide an instance - * of Forge PSS object as the scheme parameter. - * - * @param digest the message digest hash to compare against the signature, - * as a binary-encoded string. - * @param signature the signature to verify, as a binary-encoded string. - * @param scheme signature verification scheme to use: - * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, - * a Forge PSS object for RSASSA-PSS, - * 'NONE' or null for none, DigestInfo will not be expected, but - * PKCS#1 v1.5 padding will still be used. - * @param options optional verify options - * _parseAllDigestBytes testing flag to control parsing of all - * digest bytes. Unsupported and not for general usage. - * (default: true) - * - * @return true if the signature was verified, false if not. - */ - key.verify = function(digest, signature, scheme, options) { - if(typeof scheme === 'string') { - scheme = scheme.toUpperCase(); - } else if(scheme === undefined) { - scheme = 'RSASSA-PKCS1-V1_5'; - } - if(options === undefined) { - options = { - _parseAllDigestBytes: true + buffer = Buffer.allocUnsafe(size); + read(); }; - } - if(!('_parseAllDigestBytes' in options)) { - options._parseAllDigestBytes = true; + this.fstat(handle, tryStat); + }); + } + writeFile(path, data, options, callback_) { + if (this.server) + throw new Error('Client-only method called in server mode'); + + let callback; + if (typeof callback_ === 'function') { + callback = callback_; + } else if (typeof options === 'function') { + callback = options; + options = undefined; } - if(scheme === 'RSASSA-PKCS1-V1_5') { - scheme = { - verify: function(digest, d) { - // remove padding - d = _decodePkcs1_v1_5(d, key, true); - // d is ASN.1 BER-encoded DigestInfo - var obj = asn1.fromDer(d, { - parseAllBytes: options._parseAllDigestBytes - }); + if (typeof options === 'string') + options = { encoding: options, mode: 0o666, flag: 'w' }; + else if (!options) + options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; + else if (typeof options !== 'object') + throw new TypeError('Bad arguments'); - // validate DigestInfo - var capture = {}; - var errors = []; - if(!asn1.validate(obj, digestInfoValidator, capture, errors)) { - var error = new Error( - 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + - 'DigestInfo value.'); - error.errors = errors; - throw error; - } - // check hash algorithm identifier - // see PKCS1-v1-5DigestAlgorithms in RFC 8017 - // FIXME: add support to vaidator for strict value choices - var oid = asn1.derToOid(capture.algorithmIdentifier); - if(!(oid === forge.oids.md2 || - oid === forge.oids.md5 || - oid === forge.oids.sha1 || - oid === forge.oids.sha224 || - oid === forge.oids.sha256 || - oid === forge.oids.sha384 || - oid === forge.oids.sha512 || - oid === forge.oids['sha512-224'] || - oid === forge.oids['sha512-256'])) { - var error = new Error( - 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.'); - error.oid = oid; - throw error; - } + if (options.encoding && !Buffer.isEncoding(options.encoding)) + throw new Error(`Unknown encoding: ${options.encoding}`); - // compare the given digest to the decrypted one - return digest === capture.digest; - } - }; - } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { - scheme = { - verify: function(digest, d) { - // remove padding - d = _decodePkcs1_v1_5(d, key, true); - return digest === d; + const flag = options.flag || 'w'; + this.open(path, flag, options.mode, (openErr, handle) => { + if (openErr) { + callback && callback(openErr); + } else { + const buffer = (Buffer.isBuffer(data) + ? data + : Buffer.from('' + data, options.encoding || 'utf8')); + const position = (/a/.test(flag) ? null : 0); + + // SFTPv3 does not support the notion of 'current position' + // (null position), so we just attempt to append to the end of the file + // instead + if (position === null) { + const tryStat = (er, st) => { + if (er) { + // Try stat() for sftp servers that may not support fstat() for + // whatever reason + this.stat(path, (er_, st_) => { + if (er_) { + return this.close(handle, () => { + callback && callback(er); + }); + } + tryStat(null, st_); + }); + return; + } + writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); + }; + this.fstat(handle, tryStat); + return; } - }; + writeAll(this, handle, buffer, 0, buffer.length, position, callback); + } + }); + } + appendFile(path, data, options, callback_) { + if (this.server) + throw new Error('Client-only method called in server mode'); + + let callback; + if (typeof callback_ === 'function') { + callback = callback_; + } else if (typeof options === 'function') { + callback = options; + options = undefined; } - // do rsa decryption w/o any decoding, then verify -- which does decoding - var d = pki.rsa.decrypt(signature, key, true, false); - return scheme.verify(digest, d, key.n.bitLength()); - }; + if (typeof options === 'string') + options = { encoding: options, mode: 0o666, flag: 'a' }; + else if (!options) + options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; + else if (typeof options !== 'object') + throw new TypeError('Bad arguments'); - return key; -}; + if (!options.flag) + options = Object.assign({ flag: 'a' }, options); + this.writeFile(path, data, options, callback); + } + exists(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Sets an RSA private key from BigIntegers modulus, exponent, primes, - * prime exponents, and modular multiplicative inverse. - * - * @param n the modulus. - * @param e the public exponent. - * @param d the private exponent ((inverse of e) mod n). - * @param p the first prime. - * @param q the second prime. - * @param dP exponent1 (d mod (p-1)). - * @param dQ exponent2 (d mod (q-1)). - * @param qInv ((inverse of q) mod p) - * - * @return the private key. - */ -pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function( - n, e, d, p, q, dP, dQ, qInv) { - var key = { - n: n, - e: e, - d: d, - p: p, - q: q, - dP: dP, - dQ: dQ, - qInv: qInv - }; + this.stat(path, (err) => { + cb && cb(err ? false : true); + }); + } + unlink(filename, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - /** - * Decrypts the given data with this private key. The decryption scheme - * must match the one used to encrypt the data. - * - * @param data the byte string to decrypt. - * @param scheme the decryption scheme to use: - * 'RSAES-PKCS1-V1_5' (default), - * 'RSA-OAEP', - * 'RAW', 'NONE', or null to perform raw RSA decryption. - * @param schemeOptions any scheme-specific options. - * - * @return the decrypted byte string. - */ - key.decrypt = function(data, scheme, schemeOptions) { - if(typeof scheme === 'string') { - scheme = scheme.toUpperCase(); - } else if(scheme === undefined) { - scheme = 'RSAES-PKCS1-V1_5'; - } + /* + uint32 id + string filename + */ + const fnameLen = Buffer.byteLength(filename); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); - // do rsa decryption w/o any decoding - var d = pki.rsa.decrypt(data, key, false, false); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.REMOVE; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if(scheme === 'RSAES-PKCS1-V1_5') { - scheme = {decode: _decodePkcs1_v1_5}; - } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { - scheme = { - decode: function(d, key) { - return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions); - } - }; - } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { - scheme = {decode: function(d) {return d;}}; - } else { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } + writeUInt32BE(buf, fnameLen, p); + buf.utf8Write(filename, p += 4, fnameLen); - // decode according to scheme - return scheme.decode(d, key, false); - }; + this._requests[reqid] = { cb }; - /** - * Signs the given digest, producing a signature. - * - * PKCS#1 supports multiple (currently two) signature schemes: - * RSASSA-PKCS1-V1_5 and RSASSA-PSS. - * - * By default this implementation uses the "old scheme", i.e. - * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide - * an instance of Forge PSS object as the scheme parameter. - * - * @param md the message digest object with the hash to sign. - * @param scheme the signature scheme to use: - * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, - * a Forge PSS object for RSASSA-PSS, - * 'NONE' or null for none, DigestInfo will not be used but - * PKCS#1 v1.5 padding will still be used. - * - * @return the signature as a byte string. - */ - key.sign = function(md, scheme) { - /* Note: The internal implementation of RSA operations is being - transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy - code like the use of an encoding block identifier 'bt' will eventually - be removed. */ + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` + ); + } + rename(oldPath, newPath, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // private key operation - var bt = false; + /* + uint32 id + string oldpath + string newpath + */ + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); - if(typeof scheme === 'string') { - scheme = scheme.toUpperCase(); - } + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.RENAME; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { - scheme = {encode: emsaPkcs1v15encode}; - bt = 0x01; - } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { - scheme = {encode: function() {return md;}}; - bt = 0x01; - } + writeUInt32BE(buf, oldLen, p); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); - // encode and then encrypt - var d = scheme.encode(md, key.n.bitLength()); - return pki.rsa.encrypt(d, key, bt); - }; + this._requests[reqid] = { cb }; - return key; -}; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` + ); + } + mkdir(path, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -/** - * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object. - * - * @param rsaKey the ASN.1 RSAPrivateKey. - * - * @return the ASN.1 PrivateKeyInfo. - */ -pki.wrapRsaPrivateKey = function(rsaKey) { - // PrivateKeyInfo - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(0).getBytes()), - // privateKeyAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]), - // PrivateKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - asn1.toDer(rsaKey).getBytes()) - ]); -}; + let flags = 0; + let attrsLen = 0; -/** - * Converts a private key from an ASN.1 object. - * - * @param obj the ASN.1 representation of a PrivateKeyInfo containing an - * RSAPrivateKey or an RSAPrivateKey. - * - * @return the private key. - */ -pki.privateKeyFromAsn1 = function(obj) { - // get PrivateKeyInfo - var capture = {}; - var errors = []; - if(asn1.validate(obj, privateKeyValidator, capture, errors)) { - obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); - } + if (typeof attrs === 'function') { + cb = attrs; + attrs = undefined; + } + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } - // get RSAPrivateKey - capture = {}; - errors = []; - if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { - var error = new Error('Cannot read private key. ' + - 'ASN.1 object does not contain an RSAPrivateKey.'); - error.errors = errors; - throw error; - } + /* + uint32 id + string path + ATTRS attrs + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - // Note: Version is currently ignored. - // capture.privateKeyVersion - // FIXME: inefficient, get a BigInteger that uses byte strings - var n, e, d, p, q, dP, dQ, qInv; - n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); - e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); - d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); - p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); - q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); - dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); - dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); - qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.MKDIR; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - // set private key - return pki.setRsaPrivateKey( - new BigInteger(n, 16), - new BigInteger(e, 16), - new BigInteger(d, 16), - new BigInteger(p, 16), - new BigInteger(q, 16), - new BigInteger(dP, 16), - new BigInteger(dQ, 16), - new BigInteger(qInv, 16)); -}; + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; -/** - * Converts a private key to an ASN.1 RSAPrivateKey. - * - * @param key the private key. - * - * @return the ASN.1 representation of an RSAPrivateKey. - */ -pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) { - // RSAPrivateKey - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0 = only 2 primes, 1 multiple primes) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(0).getBytes()), - // modulus (n) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.n)), - // publicExponent (e) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.e)), - // privateExponent (d) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.d)), - // privateKeyPrime1 (p) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.p)), - // privateKeyPrime2 (q) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.q)), - // privateKeyExponent1 (dP) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.dP)), - // privateKeyExponent2 (dQ) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.dQ)), - // coefficient (qInv) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.qInv)) - ]); -}; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); -/** - * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey. - * - * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey. - * - * @return the public key. - */ -pki.publicKeyFromAsn1 = function(obj) { - // get SubjectPublicKeyInfo - var capture = {}; - var errors = []; - if(asn1.validate(obj, publicKeyValidator, capture, errors)) { - // get oid - var oid = asn1.derToOid(capture.publicKeyOid); - if(oid !== pki.oids.rsaEncryption) { - var error = new Error('Cannot read public key. Unknown OID.'); - error.oid = oid; - throw error; + p += attrsLen; } - obj = capture.rsaPublicKey; + + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` + ); } + rmdir(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // get RSA params - errors = []; - if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { - var error = new Error('Cannot read public key. ' + - 'ASN.1 object does not contain an RSAPublicKey.'); - error.errors = errors; - throw error; + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.RMDIR; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` + ); } + readdir(where, opts, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // FIXME: inefficient, get a BigInteger that uses byte strings - var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); - var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (typeof opts !== 'object' || opts === null) + opts = {}; - // set public key - return pki.setRsaPublicKey( - new BigInteger(n, 16), - new BigInteger(e, 16)); -}; + const doFilter = (opts && opts.full ? false : true); -/** - * Converts a public key to an ASN.1 SubjectPublicKeyInfo. - * - * @param key the public key. - * - * @return the asn1 representation of a SubjectPublicKeyInfo. - */ -pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) { - // SubjectPublicKeyInfo - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]), - // subjectPublicKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ - pki.publicKeyToRSAPublicKey(key) - ]) - ]); -}; + if (!Buffer.isBuffer(where) && typeof where !== 'string') + throw new Error('missing directory handle or path'); -/** - * Converts a public key to an ASN.1 RSAPublicKey. - * - * @param key the public key. - * - * @return the asn1 representation of a RSAPublicKey. - */ -pki.publicKeyToRSAPublicKey = function(key) { - // RSAPublicKey - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // modulus (n) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.n)), - // publicExponent (e) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.e)) - ]); -}; + if (typeof where === 'string') { + const entries = []; + let e = 0; -/** - * Encodes a message using PKCS#1 v1.5 padding. - * - * @param m the message to encode. - * @param key the RSA key to use. - * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02 - * (for encryption). - * - * @return the padded byte buffer. - */ -function _encodePkcs1_v1_5(m, key, bt) { - var eb = forge.util.createBuffer(); + const reread = (err, handle) => { + if (err) + return cb(err); - // get the length of the modulus in bytes - var k = Math.ceil(key.n.bitLength() / 8); + this.readdir(handle, opts, (err, list) => { + const eof = (err && err.code === STATUS_CODE.EOF); - /* use PKCS#1 v1.5 padding */ - if(m.length > (k - 11)) { - var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); - error.length = m.length; - error.max = k - 11; - throw error; - } + if (err && !eof) + return this.close(handle, () => cb(err)); - /* A block type BT, a padding string PS, and the data D shall be - formatted into an octet string EB, the encryption block: + if (eof) { + return this.close(handle, (err) => { + if (err) + return cb(err); + cb(undefined, entries); + }); + } + + for (let i = 0; i < list.length; ++i, ++e) + entries[e] = list[i]; + + reread(undefined, handle); + }); + }; + return this.opendir(where, reread); + } + + /* + uint32 id + string handle + */ + const handleLen = where.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.READDIR; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - EB = 00 || BT || PS || 00 || D + writeUInt32BE(buf, handleLen, p); + buf.set(where, p += 4); - The block type BT shall be a single octet indicating the structure of - the encryption block. For this version of the document it shall have - value 00, 01, or 02. For a private-key operation, the block type - shall be 00 or 01. For a public-key operation, it shall be 02. + this._requests[reqid] = { + cb: (doFilter + ? (err, list) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); - The padding string PS shall consist of k-3-||D|| octets. For block - type 00, the octets shall have value 00; for block type 01, they - shall have value FF; and for block type 02, they shall be - pseudorandomly generated and nonzero. This makes the length of the - encryption block EB equal to k. */ + for (let i = list.length - 1; i >= 0; --i) { + if (list[i].filename === '.' || list[i].filename === '..') + list.splice(i, 1); + } - // build the encryption block - eb.putByte(0x00); - eb.putByte(bt); + cb(undefined, list); + } + : cb) + }; - // create the padding - var padNum = k - 3 - m.length; - var padByte; - // private key op - if(bt === 0x00 || bt === 0x01) { - padByte = (bt === 0x00) ? 0x00 : 0xFF; - for(var i = 0; i < padNum; ++i) { - eb.putByte(padByte); - } - } else { - // public key op - // pad with random non-zero values - while(padNum > 0) { - var numZeros = 0; - var padBytes = forge.random.getBytes(padNum); - for(var i = 0; i < padNum; ++i) { - padByte = padBytes.charCodeAt(i); - if(padByte === 0) { - ++numZeros; - } else { - eb.putByte(padByte); - } - } - padNum = numZeros; - } + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` + ); } + fstat(handle, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // zero followed by message - eb.putByte(0x00); - eb.putBytes(m); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - return eb; -} + /* + uint32 id + string handle + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); -/** - * Decodes a message using PKCS#1 v1.5 padding. - * - * @param em the message to decode. - * @param key the RSA key to use. - * @param pub true if the key is a public key, false if it is private. - * @param ml the message length, if specified. - * - * @return the decoded bytes. - */ -function _decodePkcs1_v1_5(em, key, pub, ml) { - // get the length of the modulus in bytes - var k = Math.ceil(key.n.bitLength() / 8); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.FSTAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - /* It is an error if any of the following conditions occurs: + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); - 1. The encryption block EB cannot be parsed unambiguously. - 2. The padding string PS consists of fewer than eight octets - or is inconsisent with the block type BT. - 3. The decryption process is a public-key operation and the block - type BT is not 00 or 01, or the decryption process is a - private-key operation and the block type is not 02. - */ + this._requests[reqid] = { cb }; - // parse the encryption block - var eb = forge.util.createBuffer(em); - var first = eb.getByte(); - var bt = eb.getByte(); - if(first !== 0x00 || - (pub && bt !== 0x00 && bt !== 0x01) || - (!pub && bt != 0x02) || - (pub && bt === 0x00 && typeof(ml) === 'undefined')) { - throw new Error('Encryption block is invalid.'); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` + ); } + stat(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - var padNum = 0; - if(bt === 0x00) { - // check all padding bytes for 0x00 - padNum = k - 3 - ml; - for(var i = 0; i < padNum; ++i) { - if(eb.getByte() !== 0x00) { - throw new Error('Encryption block is invalid.'); - } - } - } else if(bt === 0x01) { - // find the first byte that isn't 0xFF, should be after all padding - padNum = 0; - while(eb.length() > 1) { - if(eb.getByte() !== 0xFF) { - --eb.read; - break; - } - ++padNum; - } - } else if(bt === 0x02) { - // look for 0x00 byte - padNum = 0; - while(eb.length() > 1) { - if(eb.getByte() === 0x00) { - --eb.read; - break; - } - ++padNum; - } - } + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - // zero must be 0x00 and padNum must be (k - 3 - message length) - var zero = eb.getByte(); - if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) { - throw new Error('Encryption block is invalid.'); - } + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.STAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - return eb.getBytes(); -} + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); -/** - * Runs the key-generation algorithm asynchronously, either in the background - * via Web Workers, or using the main thread and setImmediate. - * - * @param state the key-pair generation state. - * @param [options] options for key-pair generation: - * workerScript the worker script URL. - * workers the number of web workers (if supported) to use, - * (default: 2, -1 to use estimated cores minus one). - * workLoad the size of the work load, ie: number of possible prime - * numbers for each web worker to check per work assignment, - * (default: 100). - * @param callback(err, keypair) called once the operation completes. - */ -function _generateKeyPair(state, options, callback) { - if(typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; + this._requests[reqid] = { cb }; - var opts = { - algorithm: { - name: options.algorithm || 'PRIMEINC', - options: { - workers: options.workers || 2, - workLoad: options.workLoad || 100, - workerScript: options.workerScript - } - } - }; - if('prng' in options) { - opts.prng = options.prng; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` + ); } + lstat(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - generate(); - - function generate() { - // find p and then q (done in series to simplify) - getPrime(state.pBits, function(err, num) { - if(err) { - return callback(err); - } - state.p = num; - if(state.q !== null) { - return finish(err, state.q); - } - getPrime(state.qBits, finish); - }); - } + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - function getPrime(bits, callback) { - forge.prime.generateProbablePrime(bits, opts, callback); - } + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.LSTAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - function finish(err, num) { - if(err) { - return callback(err); - } + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); - // set q - state.q = num; + this._requests[reqid] = { cb }; - // ensure p is larger than q (swap them if not) - if(state.p.compareTo(state.q) < 0) { - var tmp = state.p; - state.p = state.q; - state.q = tmp; - } + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` + ); + } + opendir(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // ensure p is coprime with e - if(state.p.subtract(BigInteger.ONE).gcd(state.e) - .compareTo(BigInteger.ONE) !== 0) { - state.p = null; - generate(); - return; - } + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - // ensure q is coprime with e - if(state.q.subtract(BigInteger.ONE).gcd(state.e) - .compareTo(BigInteger.ONE) !== 0) { - state.q = null; - getPrime(state.qBits, finish); - return; - } + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.OPENDIR; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - // compute phi: (p - 1)(q - 1) (Euler's totient function) - state.p1 = state.p.subtract(BigInteger.ONE); - state.q1 = state.q.subtract(BigInteger.ONE); - state.phi = state.p1.multiply(state.q1); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); - // ensure e and phi are coprime - if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { - // phi and e aren't coprime, so generate a new p and q - state.p = state.q = null; - generate(); - return; - } + this._requests[reqid] = { cb }; - // create n, ensure n is has the right number of bits - state.n = state.p.multiply(state.q); - if(state.n.bitLength() !== state.bits) { - // failed, get new q - state.q = null; - getPrime(state.qBits, finish); - return; - } + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` + ); + } + setstat(path, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // set keys - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki.rsa.setPrivateKey( - state.n, state.e, d, state.p, state.q, - d.mod(state.p1), d.mod(state.q1), - state.q.modInverse(state.p)), - publicKey: pki.rsa.setPublicKey(state.n, state.e) - }; + let flags = 0; + let attrsLen = 0; - callback(null, state.keys); - } -} + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === 'function') { + cb = attrs; + } -/** - * Converts a positive BigInteger into 2's-complement big-endian bytes. - * - * @param b the big integer to convert. - * - * @return the bytes. - */ -function _bnToBytes(b) { - // prepend 0x00 if first byte >= 0x80 - var hex = b.toString(16); - if(hex[0] >= '8') { - hex = '00' + hex; - } - var bytes = forge.util.hexToBytes(hex); + /* + uint32 id + string path + ATTRS attrs + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - // ensure integer is minimally-encoded - if(bytes.length > 1 && - // leading 0x00 for positive integer - ((bytes.charCodeAt(0) === 0 && - (bytes.charCodeAt(1) & 0x80) === 0) || - // leading 0xFF for negative integer - (bytes.charCodeAt(0) === 0xFF && - (bytes.charCodeAt(1) & 0x80) === 0x80))) { - return bytes.substr(1); - } - return bytes; -} + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.SETSTAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/** - * Returns the required number of Miller-Rabin tests to generate a - * prime with an error probability of (1/2)^80. - * - * See Handbook of Applied Cryptography Chapter 4, Table 4.4. - * - * @param bits the bit size. - * - * @return the required number of iterations. - */ -function _getMillerRabinTests(bits) { - if(bits <= 100) return 27; - if(bits <= 150) return 18; - if(bits <= 200) return 15; - if(bits <= 250) return 12; - if(bits <= 300) return 9; - if(bits <= 350) return 8; - if(bits <= 400) return 7; - if(bits <= 500) return 6; - if(bits <= 600) return 5; - if(bits <= 800) return 4; - if(bits <= 1250) return 3; - return 2; -} + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; -/** - * Performs feature detection on the Node crypto interface. - * - * @param fn the feature (function) to detect. - * - * @return true if detected, false if not. - */ -function _detectNodeCrypto(fn) { - return forge.util.isNodejs && typeof _crypto[fn] === 'function'; -} + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); -/** - * Performs feature detection on the SubtleCrypto interface. - * - * @param fn the feature (function) to detect. - * - * @return true if detected, false if not. - */ -function _detectSubtleCrypto(fn) { - return (typeof util.globalScope !== 'undefined' && - typeof util.globalScope.crypto === 'object' && - typeof util.globalScope.crypto.subtle === 'object' && - typeof util.globalScope.crypto.subtle[fn] === 'function'); -} + p += attrsLen; + } -/** - * Performs feature detection on the deprecated Microsoft Internet Explorer - * outdated SubtleCrypto interface. This function should only be used after - * checking for the modern, standard SubtleCrypto interface. - * - * @param fn the feature (function) to detect. - * - * @return true if detected, false if not. - */ -function _detectSubtleMsCrypto(fn) { - return (typeof util.globalScope !== 'undefined' && - typeof util.globalScope.msCrypto === 'object' && - typeof util.globalScope.msCrypto.subtle === 'object' && - typeof util.globalScope.msCrypto.subtle[fn] === 'function'); -} + this._requests[reqid] = { cb }; -function _intToUint8Array(x) { - var bytes = forge.util.hexToBytes(x.toString(16)); - var buffer = new Uint8Array(bytes.length); - for(var i = 0; i < bytes.length; ++i) { - buffer[i] = bytes.charCodeAt(i); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` + ); } - return buffer; -} + fsetstat(handle, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -function _privateKeyFromJwk(jwk) { - if(jwk.kty !== 'RSA') { - throw new Error( - 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".'); - } - return pki.setRsaPrivateKey( - _base64ToBigInt(jwk.n), - _base64ToBigInt(jwk.e), - _base64ToBigInt(jwk.d), - _base64ToBigInt(jwk.p), - _base64ToBigInt(jwk.q), - _base64ToBigInt(jwk.dp), - _base64ToBigInt(jwk.dq), - _base64ToBigInt(jwk.qi)); -} + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); -function _publicKeyFromJwk(jwk) { - if(jwk.kty !== 'RSA') { - throw new Error('Key algorithm must be "RSA".'); - } - return pki.setRsaPublicKey( - _base64ToBigInt(jwk.n), - _base64ToBigInt(jwk.e)); -} + let flags = 0; + let attrsLen = 0; -function _base64ToBigInt(b64) { - return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16); -} + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === 'function') { + cb = attrs; + } + + /* + uint32 id + string handle + ATTRS attrs + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.FSETSTAT; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/***/ }), + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); + writeUInt32BE(buf, flags, p += handleLen); + if (attrsLen) { + p += 4; -/***/ 279: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); -/** - * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. - * - * @author Dave Longley - * - * Copyright (c) 2010-2015 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(6231); -__nccwpck_require__(8339); + p += attrsLen; + } -var sha1 = module.exports = forge.sha1 = forge.sha1 || {}; -forge.md.sha1 = forge.md.algorithms.sha1 = sha1; + this._requests[reqid] = { cb }; -/** - * Creates a SHA-1 message digest object. - * - * @return a message digest object. - */ -sha1.create = function() { - // do initialization as necessary - if(!_initialized) { - _init(); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` + ); } + futimes(handle, atime, mtime, cb) { + return this.fsetstat(handle, { + atime: toUnixTimestamp(atime), + mtime: toUnixTimestamp(mtime) + }, cb); + } + utimes(path, atime, mtime, cb) { + return this.setstat(path, { + atime: toUnixTimestamp(atime), + mtime: toUnixTimestamp(mtime) + }, cb); + } + fchown(handle, uid, gid, cb) { + return this.fsetstat(handle, { + uid: uid, + gid: gid + }, cb); + } + chown(path, uid, gid, cb) { + return this.setstat(path, { + uid: uid, + gid: gid + }, cb); + } + fchmod(handle, mode, cb) { + return this.fsetstat(handle, { + mode: mode + }, cb); + } + chmod(path, mode, cb) { + return this.setstat(path, { + mode: mode + }, cb); + } + readlink(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // SHA-1 state contains five 32-bit integers - var _state = null; - - // input buffer - var _input = forge.util.createBuffer(); - - // used for word storage - var _w = new Array(80); + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - // message digest object - var md = { - algorithm: 'sha1', - blockLength: 64, - digestLength: 20, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.READLINK; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - /** - * Starts the digest. - * - * @return this digest object. - */ - md.start = function() { - // up to 56-bit message length for convenience - md.messageLength = 0; + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); - // full message length (set md.messageLength64 for backwards-compatibility) - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for(var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _state = { - h0: 0x67452301, - h1: 0xEFCDAB89, - h2: 0x98BADCFE, - h3: 0x10325476, - h4: 0xC3D2E1F0 + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error('Response missing link info')); + cb(undefined, names[0].filename); + } }; - return md; - }; - // start digest automatically for first time - md.start(); - - /** - * Updates the digest with the given message input. The given input can - * treated as raw input (no encoding will be applied) or an encoding of - * 'utf8' maybe given to encode the input using UTF-8. - * - * @param msg the message input to update with. - * @param encoding the encoding to use (default: 'raw', other: 'utf8'). - * - * @return this digest object. - */ - md.update = function(msg, encoding) { - if(encoding === 'utf8') { - msg = forge.util.encodeUtf8(msg); - } - // update message length - var len = msg.length; - md.messageLength += len; - len = [(len / 0x100000000) >>> 0, len >>> 0]; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = ((len[1] / 0x100000000) >>> 0); - } + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` + ); + } + symlink(targetPath, linkPath, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // add bytes to input buffer - _input.putBytes(msg); + /* + uint32 id + string linkpath + string targetpath + */ + const linkLen = Buffer.byteLength(linkPath); + const targetLen = Buffer.byteLength(targetPath); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); - // process bytes - _update(_state, _w, _input); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.SYMLINK; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - // compact input buffer every 2K or if empty - if(_input.read > 2048 || _input.length() === 0) { - _input.compact(); + if (this._isOpenSSH) { + // OpenSSH has linkpath and targetpath positions switched + writeUInt32BE(buf, targetLen, p); + buf.utf8Write(targetPath, p += 4, targetLen); + writeUInt32BE(buf, linkLen, p += targetLen); + buf.utf8Write(linkPath, p += 4, linkLen); + } else { + writeUInt32BE(buf, linkLen, p); + buf.utf8Write(linkPath, p += 4, linkLen); + writeUInt32BE(buf, targetLen, p += linkLen); + buf.utf8Write(targetPath, p += 4, targetLen); } - return md; - }; - - /** - * Produces the digest. - * - * @return a byte buffer containing the digest value. - */ - md.digest = function() { - /* Note: Here we copy the remaining bytes in the input buffer and - add the appropriate SHA-1 padding. Then we do the final update - on a copy of the state so that if the user wants to get - intermediate digests they can do so. */ - - /* Determine the number of bytes that must be added to the message - to ensure its length is congruent to 448 mod 512. In other words, - the data to be digested must be a multiple of 512 bits (or 128 bytes). - This data includes the message, some padding, and the length of the - message. Since the length of the message will be encoded as 8 bytes (64 - bits), that means that the last segment of the data must have 56 bytes - (448 bits) of message and padding. Therefore, the length of the message - plus the padding must be congruent to 448 mod 512 because - 512 - 128 = 448. - - In order to fill up the message length it must be filled with - padding that begins with 1 bit followed by all 0 bits. Padding - must *always* be present, so if the message length is already - congruent to 448 mod 512, then 512 padding bits must be added. */ + this._requests[reqid] = { cb }; - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` + ); + } + realpath(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // compute remaining size to be digested (include message length size) - var remaining = ( - md.fullMessageLength[md.fullMessageLength.length - 1] + - md.messageLengthSize); + /* + uint32 id + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - // add padding for overflow blockSize - overflow - // _padding starts with 1 byte with first bit is set (byte value 128), then - // there may be up to (blockSize - 1) other pad bytes - var overflow = remaining & (md.blockLength - 1); - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.REALPATH; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - // serialize message length in bits in big-endian order; since length - // is stored in bytes we multiply by 8 and add carry from next int - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = (next / 0x100000000) >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4 + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error('Response missing path info')); + cb(undefined, names[0].filename); + } }; - _update(s2, _w, finalBlock); - var rval = forge.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - return rval; - }; - return md; -}; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` + ); + } + // extended requests + ext_openssh_rename(oldPath, newPath, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -// sha-1 padding bytes not initialized yet -var _padding = null; -var _initialized = false; + const ext = this._extensions['posix-rename@openssh.com']; + if (!ext || ext !== '1') + throw new Error('Server does not support this extended request'); -/** - * Initializes the constant tables. - */ -function _init() { - // create padding - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + /* + uint32 id + string "posix-rename@openssh.com" + string oldpath + string newpath + */ + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = + Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); - // now initialized - _initialized = true; -} + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/** - * Updates a SHA-1 state with the given byte buffer. - * - * @param s the SHA-1 state to update. - * @param w the array to use to store words. - * @param bytes the byte buffer to update with. - */ -function _update(s, w, bytes) { - // consume 512 bit (64 byte) chunks - var t, a, b, c, d, e, f, i; - var len = bytes.length(); - while(len >= 64) { - // the w array will be populated with sixteen 32-bit big-endian words - // and then extended into 80 32-bit words according to SHA-1 algorithm - // and for 32-79 using Max Locktyukhin's optimization + writeUInt32BE(buf, 24, p); + buf.utf8Write('posix-rename@openssh.com', p += 4, 24); + writeUInt32BE(buf, oldLen, p += 24); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); - // initialize hash value for this chunk - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; + this._requests[reqid] = { cb }; - // round 1 - for(i = 0; i < 16; ++i) { - t = bytes.getInt32(); - w[i] = t; - f = d ^ (b & (c ^ d)); - t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - for(; i < 20; ++i) { - t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); - t = (t << 1) | (t >>> 31); - w[i] = t; - f = d ^ (b & (c ^ d)); - t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - // round 2 - for(; i < 32; ++i) { - t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); - t = (t << 1) | (t >>> 31); - w[i] = t; - f = b ^ c ^ d; - t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - for(; i < 40; ++i) { - t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); - t = (t << 2) | (t >>> 30); - w[i] = t; - f = b ^ c ^ d; - t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - // round 3 - for(; i < 60; ++i) { - t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); - t = (t << 2) | (t >>> 30); - w[i] = t; - f = (b & c) | (d & (b ^ c)); - t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - // round 4 - for(; i < 80; ++i) { - t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); - t = (t << 2) | (t >>> 30); - w[i] = t; - f = b ^ c ^ d; - t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); } - - // update hash state - s.h0 = (s.h0 + a) | 0; - s.h1 = (s.h1 + b) | 0; - s.h2 = (s.h2 + c) | 0; - s.h3 = (s.h3 + d) | 0; - s.h4 = (s.h4 + e) | 0; - - len -= 64; } -} + ext_openssh_statvfs(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); + const ext = this._extensions['statvfs@openssh.com']; + if (!ext || ext !== '2') + throw new Error('Server does not support this extended request'); -/***/ }), + /* + uint32 id + string "statvfs@openssh.com" + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); -/***/ 4086: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -/** - * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. - * - * See FIPS 180-2 for details. - * - * @author Dave Longley - * - * Copyright (c) 2010-2015 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(6231); -__nccwpck_require__(8339); + writeUInt32BE(buf, 19, p); + buf.utf8Write('statvfs@openssh.com', p += 4, 19); + writeUInt32BE(buf, pathLen, p += 19); + buf.utf8Write(path, p += 4, pathLen); -var sha256 = module.exports = forge.sha256 = forge.sha256 || {}; -forge.md.sha256 = forge.md.algorithms.sha256 = sha256; + this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; -/** - * Creates a SHA-256 message digest object. - * - * @return a message digest object. - */ -sha256.create = function() { - // do initialization as necessary - if(!_initialized) { - _init(); + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); + } } + ext_openssh_fstatvfs(handle, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // SHA-256 state contains eight 32-bit integers - var _state = null; + const ext = this._extensions['fstatvfs@openssh.com']; + if (!ext || ext !== '2') + throw new Error('Server does not support this extended request'); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - // input buffer - var _input = forge.util.createBuffer(); + /* + uint32 id + string "fstatvfs@openssh.com" + string handle + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); - // used for word storage - var _w = new Array(64); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - // message digest object - var md = { - algorithm: 'sha256', - blockLength: 64, - digestLength: 32, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; + writeUInt32BE(buf, 20, p); + buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); + writeUInt32BE(buf, handleLen, p += 20); + buf.set(handle, p += 4); - /** - * Starts the digest. - * - * @return this digest object. - */ - md.start = function() { - // up to 56-bit message length for convenience - md.messageLength = 0; + this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; - // full message length (set md.messageLength64 for backwards-compatibility) - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for(var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); } - _input = forge.util.createBuffer(); - _state = { - h0: 0x6A09E667, - h1: 0xBB67AE85, - h2: 0x3C6EF372, - h3: 0xA54FF53A, - h4: 0x510E527F, - h5: 0x9B05688C, - h6: 0x1F83D9AB, - h7: 0x5BE0CD19 - }; - return md; - }; - // start digest automatically for first time - md.start(); + } + ext_openssh_hardlink(oldPath, newPath, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - /** - * Updates the digest with the given message input. The given input can - * treated as raw input (no encoding will be applied) or an encoding of - * 'utf8' maybe given to encode the input using UTF-8. - * - * @param msg the message input to update with. - * @param encoding the encoding to use (default: 'raw', other: 'utf8'). - * - * @return this digest object. - */ - md.update = function(msg, encoding) { - if(encoding === 'utf8') { - msg = forge.util.encodeUtf8(msg); - } + const ext = this._extensions['hardlink@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - // update message length - var len = msg.length; - md.messageLength += len; - len = [(len / 0x100000000) >>> 0, len >>> 0]; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = ((len[1] / 0x100000000) >>> 0); - } + /* + uint32 id + string "hardlink@openssh.com" + string oldpath + string newpath + */ + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = + Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); - // add bytes to input buffer - _input.putBytes(msg); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - // process bytes - _update(_state, _w, _input); + writeUInt32BE(buf, 20, p); + buf.utf8Write('hardlink@openssh.com', p += 4, 20); + writeUInt32BE(buf, oldLen, p += 20); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); - // compact input buffer every 2K or if empty - if(_input.read > 2048 || _input.length() === 0) { - _input.compact(); + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); } + } + ext_openssh_fsync(handle, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - return md; - }; + const ext = this._extensions['fsync@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - /** - * Produces the digest. - * - * @return a byte buffer containing the digest value. - */ - md.digest = function() { - /* Note: Here we copy the remaining bytes in the input buffer and - add the appropriate SHA-256 padding. Then we do the final update - on a copy of the state so that if the user wants to get - intermediate digests they can do so. */ + /* + uint32 id + string "fsync@openssh.com" + string handle + */ + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); - /* Determine the number of bytes that must be added to the message - to ensure its length is congruent to 448 mod 512. In other words, - the data to be digested must be a multiple of 512 bits (or 128 bytes). - This data includes the message, some padding, and the length of the - message. Since the length of the message will be encoded as 8 bytes (64 - bits), that means that the last segment of the data must have 56 bytes - (448 bits) of message and padding. Therefore, the length of the message - plus the padding must be congruent to 448 mod 512 because - 512 - 128 = 448. + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - In order to fill up the message length it must be filled with - padding that begins with 1 bit followed by all 0 bits. Padding - must *always* be present, so if the message length is already - congruent to 448 mod 512, then 512 padding bits must be added. */ + writeUInt32BE(buf, 17, p); + buf.utf8Write('fsync@openssh.com', p += 4, 17); + writeUInt32BE(buf, handleLen, p += 17); + buf.set(handle, p += 4); - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); + this._requests[reqid] = { cb }; - // compute remaining size to be digested (include message length size) - var remaining = ( - md.fullMessageLength[md.fullMessageLength.length - 1] + - md.messageLengthSize); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` + ); + } + ext_openssh_lsetstat(path, attrs, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - // add padding for overflow blockSize - overflow - // _padding starts with 1 byte with first bit is set (byte value 128), then - // there may be up to (blockSize - 1) other pad bytes - var overflow = remaining & (md.blockLength - 1); - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + const ext = this._extensions['lsetstat@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - // serialize message length in bits in big-endian order; since length - // is stored in bytes we multiply by 8 and add carry from next int - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = (next / 0x100000000) >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); + let flags = 0; + let attrsLen = 0; - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4, - h5: _state.h5, - h6: _state.h6, - h7: _state.h7 - }; - _update(s2, _w, finalBlock); - var rval = forge.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - rval.putInt32(s2.h5); - rval.putInt32(s2.h6); - rval.putInt32(s2.h7); - return rval; - }; + if (typeof attrs === 'object' && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === 'function') { + cb = attrs; + } - return md; -}; + /* + uint32 id + string "lsetstat@openssh.com" + string path + ATTRS attrs + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = + Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); -// sha-256 padding bytes not initialized yet -var _padding = null; -var _initialized = false; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -// table of constants -var _k = null; + writeUInt32BE(buf, 20, p); + buf.utf8Write('lsetstat@openssh.com', p += 4, 20); -/** - * Initializes the constant tables. - */ -function _init() { - // create padding - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + writeUInt32BE(buf, pathLen, p += 20); + buf.utf8Write(path, p += 4, pathLen); - // create K table for SHA-256 - _k = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; - // now initialized - _initialized = true; -} + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); -/** - * Updates a SHA-256 state with the given byte buffer. - * - * @param s the SHA-256 state to update. - * @param w the array to use to store words. - * @param bytes the byte buffer to update with. - */ -function _update(s, w, bytes) { - // consume 512 bit (64 byte) chunks - var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; - var len = bytes.length(); - while(len >= 64) { - // the w array will be populated with sixteen 32-bit big-endian words - // and then extended into 64 32-bit words according to SHA-256 - for(i = 0; i < 16; ++i) { - w[i] = bytes.getInt32(); - } - for(; i < 64; ++i) { - // XOR word 2 words ago rot right 17, rot right 19, shft right 10 - t1 = w[i - 2]; - t1 = - ((t1 >>> 17) | (t1 << 15)) ^ - ((t1 >>> 19) | (t1 << 13)) ^ - (t1 >>> 10); - // XOR word 15 words ago rot right 7, rot right 18, shft right 3 - t2 = w[i - 15]; - t2 = - ((t2 >>> 7) | (t2 << 25)) ^ - ((t2 >>> 18) | (t2 << 14)) ^ - (t2 >>> 3); - // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 - w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; + p += attrsLen; } - // initialize hash value for this chunk - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - f = s.h5; - g = s.h6; - h = s.h7; - - // round function - for(i = 0; i < 64; ++i) { - // Sum1(e) - s1 = - ((e >>> 6) | (e << 26)) ^ - ((e >>> 11) | (e << 21)) ^ - ((e >>> 25) | (e << 7)); - // Ch(e, f, g) (optimized the same way as SHA-1) - ch = g ^ (e & (f ^ g)); - // Sum0(a) - s0 = - ((a >>> 2) | (a << 30)) ^ - ((a >>> 13) | (a << 19)) ^ - ((a >>> 22) | (a << 10)); - // Maj(a, b, c) (optimized the same way as SHA-1) - maj = (a & b) | (c & (a ^ b)); + this._requests[reqid] = { cb }; - // main algorithm - t1 = h + s1 + ch + _k[i] + w[i]; - t2 = s0 + maj; - h = g; - g = f; - f = e; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - // can't truncate with `| 0` - e = (d + t1) >>> 0; - d = c; - c = b; - b = a; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - // can't truncate with `| 0` - a = (t1 + t2) >>> 0; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); } - - // update hash state - s.h0 = (s.h0 + a) | 0; - s.h1 = (s.h1 + b) | 0; - s.h2 = (s.h2 + c) | 0; - s.h3 = (s.h3 + d) | 0; - s.h4 = (s.h4 + e) | 0; - s.h5 = (s.h5 + f) | 0; - s.h6 = (s.h6 + g) | 0; - s.h7 = (s.h7 + h) | 0; - len -= 64; } -} - - -/***/ }), - -/***/ 9542: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/** - * Secure Hash Algorithm with a 1024-bit block size implementation. - * - * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For - * SHA-256 (block size 512 bits), see sha256.js. - * - * See FIPS 180-4 for details. - * - * @author Dave Longley - * - * Copyright (c) 2014-2015 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(6231); -__nccwpck_require__(8339); + ext_openssh_expandPath(path, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); -var sha512 = module.exports = forge.sha512 = forge.sha512 || {}; + const ext = this._extensions['expand-path@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); -// SHA-512 -forge.md.sha512 = forge.md.algorithms.sha512 = sha512; + /* + uint32 id + string "expand-path@openssh.com" + string path + */ + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); -// SHA-384 -var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; -sha384.create = function() { - return sha512.create('SHA-384'); -}; -forge.md.sha384 = forge.md.algorithms.sha384 = sha384; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); -// SHA-512/256 -forge.sha512.sha256 = forge.sha512.sha256 || { - create: function() { - return sha512.create('SHA-512/256'); - } -}; -forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] = - forge.sha512.sha256; + writeUInt32BE(buf, 23, p); + buf.utf8Write('expand-path@openssh.com', p += 4, 23); -// SHA-512/224 -forge.sha512.sha224 = forge.sha512.sha224 || { - create: function() { - return sha512.create('SHA-512/224'); - } -}; -forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] = - forge.sha512.sha224; + writeUInt32BE(buf, pathLen, p += 20); + buf.utf8Write(path, p += 4, pathLen); -/** - * Creates a SHA-2 message digest object. - * - * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224, - * SHA-512/256). - * - * @return a message digest object. - */ -sha512.create = function(algorithm) { - // do initialization as necessary - if(!_initialized) { - _init(); - } + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error('Response missing expanded path')); + cb(undefined, names[0].filename); + } + }; - if(typeof algorithm === 'undefined') { - algorithm = 'SHA-512'; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); + } } + ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - if(!(algorithm in _states)) { - throw new Error('Invalid SHA-512 algorithm: ' + algorithm); - } + const ext = this._extensions['copy-data']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints) - var _state = _states[algorithm]; - var _h = null; + if (!Buffer.isBuffer(srcHandle)) + throw new Error('Source handle is not a Buffer'); - // input buffer - var _input = forge.util.createBuffer(); + if (!Buffer.isBuffer(dstHandle)) + throw new Error('Destination handle is not a Buffer'); - // used for 64-bit word storage - var _w = new Array(80); - for(var wi = 0; wi < 80; ++wi) { - _w[wi] = new Array(2); - } + /* + uint32 id + string "copy-data" + string read-from-handle + uint64 read-from-offset + uint64 read-data-length + string write-to-handle + uint64 write-to-offset + */ + let p = 0; + const buf = Buffer.allocUnsafe( + 4 + 1 + + 4 + + 4 + 9 + + 4 + srcHandle.length + + 8 + + 8 + + 4 + dstHandle.length + + 8 + ); - // determine digest length by algorithm name (default) - var digestLength = 64; - switch(algorithm) { - case 'SHA-384': - digestLength = 48; - break; - case 'SHA-512/256': - digestLength = 32; - break; - case 'SHA-512/224': - digestLength = 28; - break; - } + writeUInt32BE(buf, buf.length - 4, p); + p += 4; - // message digest object - var md = { - // SHA-512 => sha512 - algorithm: algorithm.replace('-', '').toLowerCase(), - blockLength: 128, - digestLength: digestLength, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 16 - }; + buf[p] = REQUEST.EXTENDED; + ++p; - /** - * Starts the digest. - * - * @return this digest object. - */ - md.start = function() { - // up to 56-bit message length for convenience - md.messageLength = 0; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; - // full message length (set md.messageLength128 for backwards-compatibility) - md.fullMessageLength = md.messageLength128 = []; - var int32s = md.messageLengthSize / 4; - for(var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _h = new Array(_state.length); - for(var i = 0; i < _state.length; ++i) { - _h[i] = _state[i].slice(0); - } - return md; - }; - // start digest automatically for first time - md.start(); + writeUInt32BE(buf, 9, p); + p += 4; + buf.utf8Write('copy-data', p, 9); + p += 9; - /** - * Updates the digest with the given message input. The given input can - * treated as raw input (no encoding will be applied) or an encoding of - * 'utf8' maybe given to encode the input using UTF-8. - * - * @param msg the message input to update with. - * @param encoding the encoding to use (default: 'raw', other: 'utf8'). - * - * @return this digest object. - */ - md.update = function(msg, encoding) { - if(encoding === 'utf8') { - msg = forge.util.encodeUtf8(msg); + writeUInt32BE(buf, srcHandle.length, p); + p += 4; + buf.set(srcHandle, p); + p += srcHandle.length; + + for (let i = 7; i >= 0; --i) { + buf[p + i] = srcOffset & 0xFF; + srcOffset /= 256; } + p += 8; - // update message length - var len = msg.length; - md.messageLength += len; - len = [(len / 0x100000000) >>> 0, len >>> 0]; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = ((len[1] / 0x100000000) >>> 0); + for (let i = 7; i >= 0; --i) { + buf[p + i] = len & 0xFF; + len /= 256; } + p += 8; - // add bytes to input buffer - _input.putBytes(msg); + writeUInt32BE(buf, dstHandle.length, p); + p += 4; + buf.set(dstHandle, p); + p += dstHandle.length; - // process bytes - _update(_h, _w, _input); + for (let i = 7; i >= 0; --i) { + buf[p + i] = dstOffset & 0xFF; + dstOffset /= 256; + } - // compact input buffer every 2K or if empty - if(_input.read > 2048 || _input.length() === 0) { - _input.compact(); + this._requests[reqid] = { cb }; + + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} copy-data`); } + } + ext_home_dir(username, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - return md; - }; + const ext = this._extensions['home-directory']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); - /** - * Produces the digest. - * - * @return a byte buffer containing the digest value. - */ - md.digest = function() { - /* Note: Here we copy the remaining bytes in the input buffer and - add the appropriate SHA-512 padding. Then we do the final update - on a copy of the state so that if the user wants to get - intermediate digests they can do so. */ + if (typeof username !== 'string') + throw new TypeError('username is not a string'); - /* Determine the number of bytes that must be added to the message - to ensure its length is congruent to 896 mod 1024. In other words, - the data to be digested must be a multiple of 1024 bits (or 128 bytes). - This data includes the message, some padding, and the length of the - message. Since the length of the message will be encoded as 16 bytes (128 - bits), that means that the last segment of the data must have 112 bytes - (896 bits) of message and padding. Therefore, the length of the message - plus the padding must be congruent to 896 mod 1024 because - 1024 - 128 = 896. + /* + uint32 id + string "home-directory" + string username + */ + let p = 0; + const usernameLen = Buffer.byteLength(username); + const buf = Buffer.allocUnsafe( + 4 + 1 + + 4 + + 4 + 14 + + 4 + usernameLen + ); - In order to fill up the message length it must be filled with - padding that begins with 1 bit followed by all 0 bits. Padding - must *always* be present, so if the message length is already - congruent to 896 mod 1024, then 1024 padding bits must be added. */ + writeUInt32BE(buf, buf.length - 4, p); + p += 4; - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); + buf[p] = REQUEST.EXTENDED; + ++p; - // compute remaining size to be digested (include message length size) - var remaining = ( - md.fullMessageLength[md.fullMessageLength.length - 1] + - md.messageLengthSize); + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; - // add padding for overflow blockSize - overflow - // _padding starts with 1 byte with first bit is set (byte value 128), then - // there may be up to (blockSize - 1) other pad bytes - var overflow = remaining & (md.blockLength - 1); - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + writeUInt32BE(buf, 14, p); + p += 4; + buf.utf8Write('home-directory', p, 14); + p += 14; - // serialize message length in bits in big-endian order; since length - // is stored in bytes we multiply by 8 and add carry from next int - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = (next / 0x100000000) >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); + writeUInt32BE(buf, usernameLen, p); + p += 4; + buf.utf8Write(username, p, usernameLen); + p += usernameLen; - var h = new Array(_h.length); - for(var i = 0; i < _h.length; ++i) { - h[i] = _h[i].slice(0); - } - _update(h, _w, finalBlock); - var rval = forge.util.createBuffer(); - var hlen; - if(algorithm === 'SHA-512') { - hlen = h.length; - } else if(algorithm === 'SHA-384') { - hlen = h.length - 2; - } else { - hlen = h.length - 4; - } - for(var i = 0; i < hlen; ++i) { - rval.putInt32(h[i][0]); - if(i !== hlen - 1 || algorithm !== 'SHA-512/224') { - rval.putInt32(h[i][1]); + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== 'function') + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error('Response missing home directory')); + cb(undefined, names[0].filename); } + }; + + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} home-directory`); } - return rval; - }; + } + ext_users_groups(uids, gids, cb) { + if (this.server) + throw new Error('Client-only method called in server mode'); - return md; -}; + const ext = this._extensions['users-groups-by-id@openssh.com']; + if (ext !== '1') + throw new Error('Server does not support this extended request'); -// sha-512 padding bytes not initialized yet -var _padding = null; -var _initialized = false; + if (!Array.isArray(uids)) + throw new TypeError('uids is not an array'); + for (const val of uids) { + if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) + throw new Error('uid values must all be 32-bit unsigned integers'); + } + if (!Array.isArray(gids)) + throw new TypeError('gids is not an array'); + for (const val of gids) { + if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) + throw new Error('gid values must all be 32-bit unsigned integers'); + } -// table of constants -var _k = null; + /* + uint32 id + string "users-groups-by-id@openssh.com" + string uids + uint32 uid1 + ... + string gids + uint32 gid1 + ... + */ + let p = 0; + const buf = Buffer.allocUnsafe( + 4 + 1 + + 4 + + 4 + 30 + + 4 + (4 * uids.length) + + 4 + (4 * gids.length) + ); -// initial hash states -var _states = null; + writeUInt32BE(buf, buf.length - 4, p); + p += 4; -/** - * Initializes the constant tables. - */ -function _init() { - // create padding - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0x00), 128); + buf[p] = REQUEST.EXTENDED; + ++p; - // create K table for SHA-512 - _k = [ - [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd], - [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc], - [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019], - [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118], - [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe], - [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2], - [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1], - [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694], - [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3], - [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65], - [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483], - [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5], - [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210], - [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4], - [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725], - [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70], - [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926], - [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df], - [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8], - [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b], - [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001], - [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30], - [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910], - [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8], - [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53], - [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8], - [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb], - [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3], - [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60], - [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec], - [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9], - [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b], - [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207], - [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178], - [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6], - [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b], - [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493], - [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c], - [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a], - [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817] - ]; + const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; - // initial hash states - _states = {}; - _states['SHA-512'] = [ - [0x6a09e667, 0xf3bcc908], - [0xbb67ae85, 0x84caa73b], - [0x3c6ef372, 0xfe94f82b], - [0xa54ff53a, 0x5f1d36f1], - [0x510e527f, 0xade682d1], - [0x9b05688c, 0x2b3e6c1f], - [0x1f83d9ab, 0xfb41bd6b], - [0x5be0cd19, 0x137e2179] - ]; - _states['SHA-384'] = [ - [0xcbbb9d5d, 0xc1059ed8], - [0x629a292a, 0x367cd507], - [0x9159015a, 0x3070dd17], - [0x152fecd8, 0xf70e5939], - [0x67332667, 0xffc00b31], - [0x8eb44a87, 0x68581511], - [0xdb0c2e0d, 0x64f98fa7], - [0x47b5481d, 0xbefa4fa4] - ]; - _states['SHA-512/256'] = [ - [0x22312194, 0xFC2BF72C], - [0x9F555FA3, 0xC84C64C2], - [0x2393B86B, 0x6F53B151], - [0x96387719, 0x5940EABD], - [0x96283EE2, 0xA88EFFE3], - [0xBE5E1E25, 0x53863992], - [0x2B0199FC, 0x2C85B8AA], - [0x0EB72DDC, 0x81C52CA2] - ]; - _states['SHA-512/224'] = [ - [0x8C3D37C8, 0x19544DA2], - [0x73E19966, 0x89DCD4D6], - [0x1DFAB7AE, 0x32FF9C82], - [0x679DD514, 0x582F9FCF], - [0x0F6D2B69, 0x7BD44DA8], - [0x77E36F73, 0x04C48942], - [0x3F9D85A8, 0x6A1D36C8], - [0x1112E6AD, 0x91D692A1] - ]; + writeUInt32BE(buf, 30, p); + p += 4; + buf.utf8Write('users-groups-by-id@openssh.com', p, 30); + p += 30; - // now initialized - _initialized = true; -} + writeUInt32BE(buf, 4 * uids.length, p); + p += 4; + for (const val of uids) { + writeUInt32BE(buf, val, p); + p += 4; + } -/** - * Updates a SHA-512 state with the given byte buffer. - * - * @param s the SHA-512 state to update. - * @param w the array to use to store words. - * @param bytes the byte buffer to update with. - */ -function _update(s, w, bytes) { - // consume 512 bit (128 byte) chunks - var t1_hi, t1_lo; - var t2_hi, t2_lo; - var s0_hi, s0_lo; - var s1_hi, s1_lo; - var ch_hi, ch_lo; - var maj_hi, maj_lo; - var a_hi, a_lo; - var b_hi, b_lo; - var c_hi, c_lo; - var d_hi, d_lo; - var e_hi, e_lo; - var f_hi, f_lo; - var g_hi, g_lo; - var h_hi, h_lo; - var i, hi, lo, w2, w7, w15, w16; - var len = bytes.length(); - while(len >= 128) { - // the w array will be populated with sixteen 64-bit big-endian words - // and then extended into 64 64-bit words according to SHA-512 - for(i = 0; i < 16; ++i) { - w[i][0] = bytes.getInt32() >>> 0; - w[i][1] = bytes.getInt32() >>> 0; + writeUInt32BE(buf, 4 * gids.length, p); + p += 4; + for (const val of gids) { + writeUInt32BE(buf, val, p); + p += 4; } - for(; i < 80; ++i) { - // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x) - w2 = w[i - 2]; - hi = w2[0]; - lo = w2[1]; - // high bits - t1_hi = ( - ((hi >>> 19) | (lo << 13)) ^ // ROTR 19 - ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29) - (hi >>> 6)) >>> 0; // SHR 6 - // low bits - t1_lo = ( - ((hi << 13) | (lo >>> 19)) ^ // ROTR 19 - ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29) - ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6 + this._requests[reqid] = { extended: 'users-groups-by-id@openssh.com', cb }; - // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x) - w15 = w[i - 15]; - hi = w15[0]; - lo = w15[1]; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = (isBuffered ? 'Buffered' : 'Sending'); + this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`); + } + } + // =========================================================================== + // Server-specific =========================================================== + // =========================================================================== + handle(reqid, handle) { + if (!this.server) + throw new Error('Server-only method called in client mode'); - // high bits - t2_hi = ( - ((hi >>> 1) | (lo << 31)) ^ // ROTR 1 - ((hi >>> 8) | (lo << 24)) ^ // ROTR 8 - (hi >>> 7)) >>> 0; // SHR 7 - // low bits - t2_lo = ( - ((hi << 31) | (lo >>> 1)) ^ // ROTR 1 - ((hi << 24) | (lo >>> 8)) ^ // ROTR 8 - ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7 + if (!Buffer.isBuffer(handle)) + throw new Error('handle is not a Buffer'); - // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow) - w7 = w[i - 7]; - w16 = w[i - 16]; - lo = (t1_lo + w7[1] + t2_lo + w16[1]); - w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + - ((lo / 0x100000000) >>> 0)) >>> 0; - w[i][1] = lo >>> 0; - } + const handleLen = handle.length; - // initialize hash value for this chunk - a_hi = s[0][0]; - a_lo = s[0][1]; - b_hi = s[1][0]; - b_lo = s[1][1]; - c_hi = s[2][0]; - c_lo = s[2][1]; - d_hi = s[3][0]; - d_lo = s[3][1]; - e_hi = s[4][0]; - e_lo = s[4][1]; - f_hi = s[5][0]; - f_lo = s[5][1]; - g_hi = s[6][0]; - g_lo = s[6][1]; - h_hi = s[7][0]; - h_lo = s[7][1]; + if (handleLen > 256) + throw new Error('handle too large (> 256 bytes)'); - // round function - for(i = 0; i < 80; ++i) { - // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e) - s1_hi = ( - ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14 - ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18 - ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9) - s1_lo = ( - ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14 - ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18 - ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9) + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - // Ch(e, f, g) (optimized the same way as SHA-1) - ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; - ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.HANDLE; + writeUInt32BE(buf, reqid, 5); - // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a) - s0_hi = ( - ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28 - ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2) - ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7) - s0_lo = ( - ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28 - ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2) - ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7) + writeUInt32BE(buf, handleLen, p); + if (handleLen) + buf.set(handle, p += 4); - // Maj(a, b, c) (optimized the same way as SHA-1) - maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; - maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` + ); + } + status(reqid, code, message) { + if (!this.server) + throw new Error('Server-only method called in client mode'); - // main algorithm - // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow) - lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]); - t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + - ((lo / 0x100000000) >>> 0)) >>> 0; - t1_lo = lo >>> 0; + if (!VALID_STATUS_CODES.has(code)) + throw new Error(`Bad status code: ${code}`); - // t2 = s0 + maj modulo 2^64 (carry lo overflow) - lo = s0_lo + maj_lo; - t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - t2_lo = lo >>> 0; + message || (message = ''); + + const msgLen = Buffer.byteLength(message); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); - h_hi = g_hi; - h_lo = g_lo; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.STATUS; + writeUInt32BE(buf, reqid, 5); - g_hi = f_hi; - g_lo = f_lo; + writeUInt32BE(buf, code, p); - f_hi = e_hi; - f_lo = e_lo; + writeUInt32BE(buf, msgLen, p += 4); + p += 4; + if (msgLen) { + buf.utf8Write(message, p, msgLen); + p += msgLen; + } - // e = (d + t1) modulo 2^64 (carry lo overflow) - lo = d_lo + t1_lo; - e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - e_lo = lo >>> 0; + writeUInt32BE(buf, 0, p); // Empty language tag - d_hi = c_hi; - d_lo = c_lo; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` + ); + } + data(reqid, data, encoding) { + if (!this.server) + throw new Error('Server-only method called in client mode'); - c_hi = b_hi; - c_lo = b_lo; + const isBuffer = Buffer.isBuffer(data); - b_hi = a_hi; - b_lo = a_lo; + if (!isBuffer && typeof data !== 'string') + throw new Error('data is not a Buffer or string'); - // a = (t1 + t2) modulo 2^64 (carry lo overflow) - lo = t1_lo + t2_lo; - a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - a_lo = lo >>> 0; + let isUTF8; + if (!isBuffer && !encoding) { + encoding = undefined; + isUTF8 = true; } - // update hash state (additional modulo 2^64) - lo = s[0][1] + a_lo; - s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[0][1] = lo >>> 0; + const dataLen = ( + isBuffer + ? data.length + : Buffer.byteLength(data, encoding) + ); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); - lo = s[1][1] + b_lo; - s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[1][1] = lo >>> 0; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.DATA; + writeUInt32BE(buf, reqid, 5); - lo = s[2][1] + c_lo; - s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[2][1] = lo >>> 0; + writeUInt32BE(buf, dataLen, p); + if (dataLen) { + if (isBuffer) + buf.set(data, p += 4); + else if (isUTF8) + buf.utf8Write(data, p += 4, dataLen); + else + buf.write(data, p += 4, dataLen, encoding); + } - lo = s[3][1] + d_lo; - s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[3][1] = lo >>> 0; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` + ); + } + name(reqid, names) { + if (!this.server) + throw new Error('Server-only method called in client mode'); - lo = s[4][1] + e_lo; - s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[4][1] = lo >>> 0; + if (!Array.isArray(names)) { + if (typeof names !== 'object' || names === null) + throw new Error('names is not an object or array'); + names = [ names ]; + } - lo = s[5][1] + f_lo; - s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[5][1] = lo >>> 0; + const count = names.length; + let namesLen = 0; + let nameAttrs; + const attrs = []; - lo = s[6][1] + g_lo; - s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[6][1] = lo >>> 0; + for (let i = 0; i < count; ++i) { + const name = names[i]; + const filename = ( + !name || !name.filename || typeof name.filename !== 'string' + ? '' + : name.filename + ); + namesLen += 4 + Buffer.byteLength(filename); + const longname = ( + !name || !name.longname || typeof name.longname !== 'string' + ? '' + : name.longname + ); + namesLen += 4 + Buffer.byteLength(longname); - lo = s[7][1] + h_lo; - s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[7][1] = lo >>> 0; + if (typeof name.attrs === 'object' && name.attrs !== null) { + nameAttrs = attrsToBytes(name.attrs); + namesLen += 4 + nameAttrs.nb; - len -= 128; - } -} + if (nameAttrs.nb) { + let bytes; + if (nameAttrs.nb === ATTRS_BUF.length) { + bytes = new Uint8Array(ATTRS_BUF); + } else { + bytes = new Uint8Array(nameAttrs.nb); + bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); + } -/***/ }), + nameAttrs.bytes = bytes; + } -/***/ 4280: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + attrs.push(nameAttrs); + } else { + namesLen += 4; + attrs.push(null); + } + } -/** - * Functions to output keys in SSH-friendly formats. - * - * This is part of the Forge project which may be used under the terms of - * either the BSD License or the GNU General Public License (GPL) Version 2. - * - * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE - * - * @author https://github.com/shellac - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7994); -__nccwpck_require__(5104); -__nccwpck_require__(6594); -__nccwpck_require__(279); -__nccwpck_require__(8339); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); -var ssh = module.exports = forge.ssh = forge.ssh || {}; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.NAME; + writeUInt32BE(buf, reqid, 5); -/** - * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file. - * - * @param privateKey the key. - * @param passphrase a passphrase to protect the key (falsy for no encryption). - * @param comment a comment to include in the key file. - * - * @return the PPK file as a string. - */ -ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { - comment = comment || ''; - passphrase = passphrase || ''; - var algorithm = 'ssh-rsa'; - var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc'; + writeUInt32BE(buf, count, p); - var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n'; - ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n'; - ppk += 'Comment: ' + comment + '\r\n'; + p += 4; - // public key into buffer for ppk - var pubbuffer = forge.util.createBuffer(); - _addStringToBuffer(pubbuffer, algorithm); - _addBigIntegerToBuffer(pubbuffer, privateKey.e); - _addBigIntegerToBuffer(pubbuffer, privateKey.n); + for (let i = 0; i < count; ++i) { + const name = names[i]; - // write public key - var pub = forge.util.encode64(pubbuffer.bytes(), 64); - var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n - ppk += 'Public-Lines: ' + length + '\r\n'; - ppk += pub; + { + const filename = ( + !name || !name.filename || typeof name.filename !== 'string' + ? '' + : name.filename + ); + const len = Buffer.byteLength(filename); + writeUInt32BE(buf, len, p); + p += 4; + if (len) { + buf.utf8Write(filename, p, len); + p += len; + } + } - // private key into a buffer - var privbuffer = forge.util.createBuffer(); - _addBigIntegerToBuffer(privbuffer, privateKey.d); - _addBigIntegerToBuffer(privbuffer, privateKey.p); - _addBigIntegerToBuffer(privbuffer, privateKey.q); - _addBigIntegerToBuffer(privbuffer, privateKey.qInv); + { + const longname = ( + !name || !name.longname || typeof name.longname !== 'string' + ? '' + : name.longname + ); + const len = Buffer.byteLength(longname); + writeUInt32BE(buf, len, p); + p += 4; + if (len) { + buf.utf8Write(longname, p, len); + p += len; + } + } - // optionally encrypt the private key - var priv; - if(!passphrase) { - // use the unencrypted buffer - priv = forge.util.encode64(privbuffer.bytes(), 64); - } else { - // encrypt RSA key using passphrase - var encLen = privbuffer.length() + 16 - 1; - encLen -= encLen % 16; + const attr = attrs[i]; + if (attr) { + writeUInt32BE(buf, attr.flags, p); + p += 4; + if (attr.flags && attr.bytes) { + buf.set(attr.bytes, p); + p += attr.nb; + } + } else { + writeUInt32BE(buf, 0, p); + p += 4; + } + } - // pad private key with sha1-d data -- needs to be a multiple of 16 - var padding = _sha1(privbuffer.bytes()); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` + ); + } + attrs(reqid, attrs) { + if (!this.server) + throw new Error('Server-only method called in client mode'); - padding.truncate(padding.length() - encLen + privbuffer.length()); - privbuffer.putBuffer(padding); + if (typeof attrs !== 'object' || attrs === null) + throw new Error('attrs is not an object'); - var aeskey = forge.util.createBuffer(); - aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase)); - aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase)); + attrs = attrsToBytes(attrs); + const flags = attrs.flags; + const attrsLen = attrs.nb; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); - // encrypt some bytes using CBC mode - // key is 40 bytes, so truncate *by* 8 bytes - var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC'); - cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); - cipher.update(privbuffer.copy()); - cipher.finish(); - var encrypted = cipher.output; + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.ATTRS; + writeUInt32BE(buf, reqid, 5); - // Note: this appears to differ from Putty -- is forge wrong, or putty? - // due to padding we finish as an exact multiple of 16 - encrypted.truncate(16); // all padding + writeUInt32BE(buf, flags, p); + if (attrsLen) { + p += 4; - priv = forge.util.encode64(encrypted.bytes(), 64); + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + + p += attrsLen; + } + + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` + ); } +} - // output private key - length = Math.floor(priv.length / 66) + 1; // 64 + \r\n - ppk += '\r\nPrivate-Lines: ' + length + '\r\n'; - ppk += priv; +function tryCreateBuffer(size) { + try { + return Buffer.allocUnsafe(size); + } catch (ex) { + return ex; + } +} - // MAC - var mackey = _sha1('putty-private-key-file-mac-key', passphrase); +function read_(self, handle, buf, off, len, position, cb, req_) { + const maxDataLen = self._maxReadLen; + const overflow = Math.max(len - maxDataLen, 0); - var macbuffer = forge.util.createBuffer(); - _addStringToBuffer(macbuffer, algorithm); - _addStringToBuffer(macbuffer, encryptionAlgorithm); - _addStringToBuffer(macbuffer, comment); - macbuffer.putInt32(pubbuffer.length()); - macbuffer.putBuffer(pubbuffer); - macbuffer.putInt32(privbuffer.length()); - macbuffer.putBuffer(privbuffer); + if (overflow) + len = maxDataLen; - var hmac = forge.hmac.create(); - hmac.start('sha1', mackey); - hmac.update(macbuffer.bytes()); + /* + uint32 id + string handle + uint64 offset + uint32 len + */ + const handleLen = handle.length; + let p = 9; + let pos = position; + const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); - ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n'; + writeUInt32BE(out, out.length - 4, 0); + out[4] = REQUEST.READ; + const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; + writeUInt32BE(out, reqid, 5); - return ppk; -}; + writeUInt32BE(out, handleLen, p); + out.set(handle, p += 4); + p += handleLen; + for (let i = 7; i >= 0; --i) { + out[p + i] = pos & 0xFF; + pos /= 256; + } + writeUInt32BE(out, len, p += 8); -/** - * Encodes a public RSA key as an OpenSSH file. - * - * @param key the key. - * @param comment a comment. - * - * @return the public key in OpenSSH format. - */ -ssh.publicKeyToOpenSSH = function(key, comment) { - var type = 'ssh-rsa'; - comment = comment || ''; + if (typeof cb !== 'function') + cb = noop; - var buffer = forge.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); + const req = (req_ || { + nb: 0, + position, + off, + origOff: off, + len: undefined, + overflow: undefined, + cb: (err, data, nb) => { + const len = req.len; + const overflow = req.overflow; - return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment; -}; + if (err) { + if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) + return cb(err); + } else if (nb > len) { + return cb(new Error('Received more data than requested')); + } else if (nb === len && overflow) { + req.nb += nb; + req.position += nb; + req.off += nb; + read_(self, handle, buf, req.off, overflow, req.position, cb, req); + return; + } -/** - * Encodes a private RSA key as an OpenSSH file. - * - * @param key the key. - * @param passphrase a passphrase to protect the key (falsy for no encryption). - * - * @return the public key in OpenSSH format. - */ -ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { - if(!passphrase) { - return forge.pki.privateKeyToPem(privateKey); - } - // OpenSSH private key is just a legacy format, it seems - return forge.pki.encryptRsaPrivateKey(privateKey, passphrase, - {legacy: true, algorithm: 'aes128'}); -}; + nb = (nb || 0); + if (req.origOff === 0 && buf.length === req.nb) + data = buf; + else + data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb); + cb(undefined, req.nb + nb, data, req.position); + }, + buffer: undefined, + }); -/** - * Gets the SSH fingerprint for the given public key. - * - * @param options the options to use. - * [md] the message digest object to use (defaults to forge.md.md5). - * [encoding] an alternative output encoding, such as 'hex' - * (defaults to none, outputs a byte buffer). - * [delimiter] the delimiter to use between bytes for 'hex' encoded - * output, eg: ':' (defaults to none). - * - * @return the fingerprint as a byte buffer or other encoding based on options. - */ -ssh.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge.md.md5.create(); + req.len = len; + req.overflow = overflow; - var type = 'ssh-rsa'; - var buffer = forge.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); + // TODO: avoid creating multiple buffer slices when we need to re-call read_() + // because of overflow + req.buffer = bufferSlice(buf, off, off + len); - // hash public key bytes - md.start(); - md.update(buffer.getBytes()); - var digest = md.digest(); - if(options.encoding === 'hex') { - var hex = digest.toHex(); - if(options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if(options.encoding === 'binary') { - return digest.getBytes(); - } else if(options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; -}; + self._requests[reqid] = req; -/** - * Adds len(val) then val to a buffer. - * - * @param buffer the buffer to add to. - * @param val a big integer. - */ -function _addBigIntegerToBuffer(buffer, val) { - var hexVal = val.toString(16); - // ensure 2s complement +ve - if(hexVal[0] >= '8') { - hexVal = '00' + hexVal; - } - var bytes = forge.util.hexToBytes(hexVal); - buffer.putInt32(bytes.length); - buffer.putBytes(bytes); + const isBuffered = sendOrBuffer(self, out); + self._debug && self._debug( + `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` + ); } -/** - * Adds len(val) then val to a buffer. - * - * @param buffer the buffer to add to. - * @param val a string. - */ -function _addStringToBuffer(buffer, val) { - buffer.putInt32(val.length); - buffer.putString(val); -} +function fastXfer(src, dst, srcPath, dstPath, opts, cb) { + let concurrency = 64; + let chunkSize = 32768; + let onstep; + let mode; + let fileSize; + + if (typeof opts === 'function') { + cb = opts; + } else if (typeof opts === 'object' && opts !== null) { + if (typeof opts.concurrency === 'number' + && opts.concurrency > 0 + && !isNaN(opts.concurrency)) { + concurrency = opts.concurrency; + } + if (typeof opts.chunkSize === 'number' + && opts.chunkSize > 0 + && !isNaN(opts.chunkSize)) { + chunkSize = opts.chunkSize; + } + if (typeof opts.fileSize === 'number' + && opts.fileSize > 0 + && !isNaN(opts.fileSize)) { + fileSize = opts.fileSize; + } + if (typeof opts.step === 'function') + onstep = opts.step; -/** - * Hashes the arguments into one value using SHA-1. - * - * @return the sha1 hash of the provided arguments. - */ -function _sha1() { - var sha = forge.md.sha1.create(); - var num = arguments.length; - for (var i = 0; i < num; ++i) { - sha.update(arguments[i]); + if (typeof opts.mode === 'string' || typeof opts.mode === 'number') + mode = modeNum(opts.mode); } - return sha.digest(); -} + // Internal state variables + let fsize; + let pdst = 0; + let total = 0; + let hadError = false; + let srcHandle; + let dstHandle; + let readbuf; + let bufsize = chunkSize * concurrency; -/***/ }), + function onerror(err) { + if (hadError) + return; -/***/ 9167: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + hadError = true; -/** - * A Javascript implementation of Transport Layer Security (TLS). - * - * @author Dave Longley - * - * Copyright (c) 2009-2014 Digital Bazaar, Inc. - * - * The TLS Handshake Protocol involves the following steps: - * - * - Exchange hello messages to agree on algorithms, exchange random values, - * and check for session resumption. - * - * - Exchange the necessary cryptographic parameters to allow the client and - * server to agree on a premaster secret. - * - * - Exchange certificates and cryptographic information to allow the client - * and server to authenticate themselves. - * - * - Generate a master secret from the premaster secret and exchanged random - * values. - * - * - Provide security parameters to the record layer. - * - * - Allow the client and server to verify that their peer has calculated the - * same security parameters and that the handshake occurred without tampering - * by an attacker. - * - * Up to 4 different messages may be sent during a key exchange. The server - * certificate, the server key exchange, the client certificate, and the - * client key exchange. - * - * A typical handshake (from the client's perspective). - * - * 1. Client sends ClientHello. - * 2. Client receives ServerHello. - * 3. Client receives optional Certificate. - * 4. Client receives optional ServerKeyExchange. - * 5. Client receives ServerHelloDone. - * 6. Client sends optional Certificate. - * 7. Client sends ClientKeyExchange. - * 8. Client sends optional CertificateVerify. - * 9. Client sends ChangeCipherSpec. - * 10. Client sends Finished. - * 11. Client receives ChangeCipherSpec. - * 12. Client receives Finished. - * 13. Client sends/receives application data. - * - * To reuse an existing session: - * - * 1. Client sends ClientHello with session ID for reuse. - * 2. Client receives ServerHello with same session ID if reusing. - * 3. Client receives ChangeCipherSpec message if reusing. - * 4. Client receives Finished. - * 5. Client sends ChangeCipherSpec. - * 6. Client sends Finished. - * - * Note: Client ignores HelloRequest if in the middle of a handshake. - * - * Record Layer: - * - * The record layer fragments information blocks into TLSPlaintext records - * carrying data in chunks of 2^14 bytes or less. Client message boundaries are - * not preserved in the record layer (i.e., multiple client messages of the - * same ContentType MAY be coalesced into a single TLSPlaintext record, or a - * single message MAY be fragmented across several records). - * - * struct { - * uint8 major; - * uint8 minor; - * } ProtocolVersion; - * - * struct { - * ContentType type; - * ProtocolVersion version; - * uint16 length; - * opaque fragment[TLSPlaintext.length]; - * } TLSPlaintext; - * - * type: - * The higher-level protocol used to process the enclosed fragment. - * - * version: - * The version of the protocol being employed. TLS Version 1.2 uses version - * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that - * supports multiple versions of TLS may not know what version will be - * employed before it receives the ServerHello. - * - * length: - * The length (in bytes) of the following TLSPlaintext.fragment. The length - * MUST NOT exceed 2^14 = 16384 bytes. - * - * fragment: - * The application data. This data is transparent and treated as an - * independent block to be dealt with by the higher-level protocol specified - * by the type field. - * - * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or - * ChangeCipherSpec content types. Zero-length fragments of Application data - * MAY be sent as they are potentially useful as a traffic analysis - * countermeasure. - * - * Note: Data of different TLS record layer content types MAY be interleaved. - * Application data is generally of lower precedence for transmission than - * other content types. However, records MUST be delivered to the network in - * the same order as they are protected by the record layer. Recipients MUST - * receive and process interleaved application layer traffic during handshakes - * subsequent to the first one on a connection. - * - * struct { - * ContentType type; // same as TLSPlaintext.type - * ProtocolVersion version;// same as TLSPlaintext.version - * uint16 length; - * opaque fragment[TLSCompressed.length]; - * } TLSCompressed; - * - * length: - * The length (in bytes) of the following TLSCompressed.fragment. - * The length MUST NOT exceed 2^14 + 1024. - * - * fragment: - * The compressed form of TLSPlaintext.fragment. - * - * Note: A CompressionMethod.null operation is an identity operation; no fields - * are altered. In this implementation, since no compression is supported, - * uncompressed records are always the same as compressed records. - * - * Encryption Information: - * - * The encryption and MAC functions translate a TLSCompressed structure into a - * TLSCiphertext. The decryption functions reverse the process. The MAC of the - * record also includes a sequence number so that missing, extra, or repeated - * messages are detectable. - * - * struct { - * ContentType type; - * ProtocolVersion version; - * uint16 length; - * select (SecurityParameters.cipher_type) { - * case stream: GenericStreamCipher; - * case block: GenericBlockCipher; - * case aead: GenericAEADCipher; - * } fragment; - * } TLSCiphertext; - * - * type: - * The type field is identical to TLSCompressed.type. - * - * version: - * The version field is identical to TLSCompressed.version. - * - * length: - * The length (in bytes) of the following TLSCiphertext.fragment. - * The length MUST NOT exceed 2^14 + 2048. - * - * fragment: - * The encrypted form of TLSCompressed.fragment, with the MAC. - * - * Note: Only CBC Block Ciphers are supported by this implementation. - * - * The TLSCompressed.fragment structures are converted to/from block - * TLSCiphertext.fragment structures. - * - * struct { - * opaque IV[SecurityParameters.record_iv_length]; - * block-ciphered struct { - * opaque content[TLSCompressed.length]; - * opaque MAC[SecurityParameters.mac_length]; - * uint8 padding[GenericBlockCipher.padding_length]; - * uint8 padding_length; - * }; - * } GenericBlockCipher; - * - * The MAC is generated as described in Section 6.2.3.1. - * - * IV: - * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be - * unpredictable. Note that in versions of TLS prior to 1.1, there was no - * IV field, and the last ciphertext block of the previous record (the "CBC - * residue") was used as the IV. This was changed to prevent the attacks - * described in [CBCATT]. For block ciphers, the IV length is of length - * SecurityParameters.record_iv_length, which is equal to the - * SecurityParameters.block_size. - * - * padding: - * Padding that is added to force the length of the plaintext to be an - * integral multiple of the block cipher's block length. The padding MAY be - * any length up to 255 bytes, as long as it results in the - * TLSCiphertext.length being an integral multiple of the block length. - * Lengths longer than necessary might be desirable to frustrate attacks on - * a protocol that are based on analysis of the lengths of exchanged - * messages. Each uint8 in the padding data vector MUST be filled with the - * padding length value. The receiver MUST check this padding and MUST use - * the bad_record_mac alert to indicate padding errors. - * - * padding_length: - * The padding length MUST be such that the total size of the - * GenericBlockCipher structure is a multiple of the cipher's block length. - * Legal values range from zero to 255, inclusive. This length specifies the - * length of the padding field exclusive of the padding_length field itself. - * - * The encrypted data length (TLSCiphertext.length) is one more than the sum of - * SecurityParameters.block_length, TLSCompressed.length, - * SecurityParameters.mac_length, and padding_length. - * - * Example: If the block length is 8 bytes, the content length - * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the - * length before padding is 82 bytes (this does not include the IV. Thus, the - * padding length modulo 8 must be equal to 6 in order to make the total length - * an even multiple of 8 bytes (the block length). The padding length can be - * 6, 14, 22, and so on, through 254. If the padding length were the minimum - * necessary, 6, the padding would be 6 bytes, each containing the value 6. - * Thus, the last 8 octets of the GenericBlockCipher before block encryption - * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC. - * - * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical - * that the entire plaintext of the record be known before any ciphertext is - * transmitted. Otherwise, it is possible for the attacker to mount the attack - * described in [CBCATT]. - * - * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing - * attack on CBC padding based on the time required to compute the MAC. In - * order to defend against this attack, implementations MUST ensure that - * record processing time is essentially the same whether or not the padding - * is correct. In general, the best way to do this is to compute the MAC even - * if the padding is incorrect, and only then reject the packet. For instance, - * if the pad appears to be incorrect, the implementation might assume a - * zero-length pad and then compute the MAC. This leaves a small timing - * channel, since MAC performance depends, to some extent, on the size of the - * data fragment, but it is not believed to be large enough to be exploitable, - * due to the large block size of existing MACs and the small size of the - * timing signal. - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(9549); -__nccwpck_require__(5104); -__nccwpck_require__(6594); -__nccwpck_require__(154); -__nccwpck_require__(6924); -__nccwpck_require__(7821); -__nccwpck_require__(279); -__nccwpck_require__(8339); + let left = 0; + let cbfinal; -/** - * Generates pseudo random bytes by mixing the result of two hash functions, - * MD5 and SHA-1. - * - * prf_TLS1(secret, label, seed) = - * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed); - * - * Each P_hash function functions as follows: - * - * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + - * HMAC_hash(secret, A(2) + seed) + - * HMAC_hash(secret, A(3) + seed) + ... - * A() is defined as: - * A(0) = seed - * A(i) = HMAC_hash(secret, A(i-1)) - * - * The '+' operator denotes concatenation. - * - * As many iterations A(N) as are needed are performed to generate enough - * pseudo random byte output. If an iteration creates more data than is - * necessary, then it is truncated. - * - * Therefore: - * A(1) = HMAC_hash(secret, A(0)) - * = HMAC_hash(secret, seed) - * A(2) = HMAC_hash(secret, A(1)) - * = HMAC_hash(secret, HMAC_hash(secret, seed)) - * - * Therefore: - * P_hash(secret, seed) = - * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) + - * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) + - * ... - * - * Therefore: - * P_hash(secret, seed) = - * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) + - * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) + - * ... - * - * @param secret the secret to use. - * @param label the label to use. - * @param seed the seed value to use. - * @param length the number of bytes to generate. - * - * @return the pseudo random bytes in a byte buffer. - */ -var prf_TLS1 = function(secret, label, seed, length) { - var rval = forge.util.createBuffer(); + if (srcHandle || dstHandle) { + cbfinal = () => { + if (--left === 0) + cb(err); + }; + if (srcHandle && (src === fs || src.outgoing.state === 'open')) + ++left; + if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) + ++left; + if (srcHandle && (src === fs || src.outgoing.state === 'open')) + src.close(srcHandle, cbfinal); + if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) + dst.close(dstHandle, cbfinal); + } else { + cb(err); + } + } - /* For TLS 1.0, the secret is split in half, into two secrets of equal - length. If the secret has an odd length then the last byte of the first - half will be the same as the first byte of the second. The length of the - two secrets is half of the secret rounded up. */ - var idx = (secret.length >> 1); - var slen = idx + (secret.length & 1); - var s1 = secret.substr(0, slen); - var s2 = secret.substr(idx, slen); - var ai = forge.util.createBuffer(); - var hmac = forge.hmac.create(); - seed = label + seed; + src.open(srcPath, 'r', (err, sourceHandle) => { + if (err) + return onerror(err); - // determine the number of iterations that must be performed to generate - // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20 - var md5itr = Math.ceil(length / 16); - var sha1itr = Math.ceil(length / 20); + srcHandle = sourceHandle; - // do md5 iterations - hmac.start('MD5', s1); - var md5bytes = forge.util.createBuffer(); - ai.putBytes(seed); - for(var i = 0; i < md5itr; ++i) { - // HMAC_hash(secret, A(i-1)) - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); + if (fileSize === undefined) + src.fstat(srcHandle, tryStat); + else + tryStat(null, { size: fileSize }); - // HMAC_hash(secret, A(i) + seed) - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - md5bytes.putBuffer(hmac.digest()); - } + function tryStat(err, attrs) { + if (err) { + if (src !== fs) { + // Try stat() for sftp servers that may not support fstat() for + // whatever reason + src.stat(srcPath, (err_, attrs_) => { + if (err_) + return onerror(err); + tryStat(null, attrs_); + }); + return; + } + return onerror(err); + } + fsize = attrs.size; - // do sha1 iterations - hmac.start('SHA1', s2); - var sha1bytes = forge.util.createBuffer(); - ai.clear(); - ai.putBytes(seed); - for(var i = 0; i < sha1itr; ++i) { - // HMAC_hash(secret, A(i-1)) - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); + dst.open(dstPath, 'w', (err, destHandle) => { + if (err) + return onerror(err); - // HMAC_hash(secret, A(i) + seed) - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - sha1bytes.putBuffer(hmac.digest()); - } + dstHandle = destHandle; - // XOR the md5 bytes with the sha1 bytes - rval.putBytes(forge.util.xorBytes( - md5bytes.getBytes(), sha1bytes.getBytes(), length)); + if (fsize <= 0) + return onerror(); - return rval; -}; + // Use less memory where possible + while (bufsize > fsize) { + if (concurrency === 1) { + bufsize = fsize; + break; + } + bufsize -= chunkSize; + --concurrency; + } -/** - * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2. - * - * @param secret the secret to use. - * @param label the label to use. - * @param seed the seed value to use. - * @param length the number of bytes to generate. - * - * @return the pseudo random bytes in a byte buffer. - */ -var prf_sha256 = function(secret, label, seed, length) { - // FIXME: implement me for TLS 1.2 -}; + readbuf = tryCreateBuffer(bufsize); + if (readbuf instanceof Error) + return onerror(readbuf); -/** - * Gets a MAC for a record using the SHA-1 hash algorithm. - * - * @param key the mac key. - * @param state the sequence number (array of two 32-bit integers). - * @param record the record. - * - * @return the sha-1 hash (20 bytes) for the given record. - */ -var hmac_sha1 = function(key, seqNum, record) { - /* MAC is computed like so: - HMAC_hash( - key, seqNum + - TLSCompressed.type + - TLSCompressed.version + - TLSCompressed.length + - TLSCompressed.fragment) - */ - var hmac = forge.hmac.create(); - hmac.start('SHA1', key); - var b = forge.util.createBuffer(); - b.putInt32(seqNum[0]); - b.putInt32(seqNum[1]); - b.putByte(record.type); - b.putByte(record.version.major); - b.putByte(record.version.minor); - b.putInt16(record.length); - b.putBytes(record.fragment.bytes()); - hmac.update(b.getBytes()); - return hmac.digest().getBytes(); -}; + if (mode !== undefined) { + dst.fchmod(dstHandle, mode, function tryAgain(err) { + if (err) { + // Try chmod() for sftp servers that may not support fchmod() + // for whatever reason + dst.chmod(dstPath, mode, (err_) => tryAgain()); + return; + } + startReads(); + }); + } else { + startReads(); + } -/** - * Compresses the TLSPlaintext record into a TLSCompressed record using the - * deflate algorithm. - * - * @param c the TLS connection. - * @param record the TLSPlaintext record to compress. - * @param s the ConnectionState to use. - * - * @return true on success, false on failure. - */ -var deflate = function(c, record, s) { - var rval = false; + function onread(err, nb, data, dstpos, datapos, origChunkLen) { + if (err) + return onerror(err); - try { - var bytes = c.deflate(record.fragment.getBytes()); - record.fragment = forge.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch(ex) { - // deflate error, fail out - } + datapos = datapos || 0; - return rval; -}; + dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); -/** - * Decompresses the TLSCompressed record into a TLSPlaintext record using the - * deflate algorithm. - * - * @param c the TLS connection. - * @param record the TLSCompressed record to decompress. - * @param s the ConnectionState to use. - * - * @return true on success, false on failure. - */ -var inflate = function(c, record, s) { - var rval = false; + function writeCb(err) { + if (err) + return onerror(err); - try { - var bytes = c.inflate(record.fragment.getBytes()); - record.fragment = forge.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch(ex) { - // inflate error, fail out - } + total += nb; + onstep && onstep(total, nb, fsize); - return rval; -}; + if (nb < origChunkLen) + return singleRead(datapos, dstpos + nb, origChunkLen - nb); -/** - * Reads a TLS variable-length vector from a byte buffer. - * - * Variable-length vectors are defined by specifying a subrange of legal - * lengths, inclusively, using the notation . When these are - * encoded, the actual length precedes the vector's contents in the byte - * stream. The length will be in the form of a number consuming as many bytes - * as required to hold the vector's specified maximum (ceiling) length. A - * variable-length vector with an actual length field of zero is referred to - * as an empty vector. - * - * @param b the byte buffer. - * @param lenBytes the number of bytes required to store the length. - * - * @return the resulting byte buffer. - */ -var readVector = function(b, lenBytes) { - var len = 0; - switch(lenBytes) { - case 1: - len = b.getByte(); - break; - case 2: - len = b.getInt16(); - break; - case 3: - len = b.getInt24(); - break; - case 4: - len = b.getInt32(); - break; - } + if (total === fsize) { + dst.close(dstHandle, (err) => { + dstHandle = undefined; + if (err) + return onerror(err); + src.close(srcHandle, (err) => { + srcHandle = undefined; + if (err) + return onerror(err); + cb(); + }); + }); + return; + } - // read vector bytes into a new buffer - return forge.util.createBuffer(b.getBytes(len)); -}; + if (pdst >= fsize) + return; -/** - * Writes a TLS variable-length vector to a byte buffer. - * - * @param b the byte buffer. - * @param lenBytes the number of bytes required to store the length. - * @param v the byte buffer vector. - */ -var writeVector = function(b, lenBytes, v) { - // encode length at the start of the vector, where the number of bytes for - // the length is the maximum number of bytes it would take to encode the - // vector's ceiling - b.putInt(v.length(), lenBytes << 3); - b.putBuffer(v); -}; + const chunk = + (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); + singleRead(datapos, pdst, chunk); + pdst += chunk; + } + } -/** - * The tls implementation. - */ -var tls = {}; + function makeCb(psrc, pdst, chunk) { + return (err, nb, data) => { + onread(err, nb, data, pdst, psrc, chunk); + }; + } -/** - * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and - * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time - * of this implementation so TLS 1.0 was implemented instead. - */ -tls.Versions = { - TLS_1_0: {major: 3, minor: 1}, - TLS_1_1: {major: 3, minor: 2}, - TLS_1_2: {major: 3, minor: 3} -}; -tls.SupportedVersions = [ - tls.Versions.TLS_1_1, - tls.Versions.TLS_1_0 -]; -tls.Version = tls.SupportedVersions[0]; + function singleRead(psrc, pdst, chunk) { + src.read(srcHandle, + readbuf, + psrc, + chunk, + pdst, + makeCb(psrc, pdst, chunk)); + } -/** - * Maximum fragment size. True maximum is 16384, but we fragment before that - * to allow for unusual small increases during compression. - */ -tls.MaxFragment = 16384 - 1024; + function startReads() { + let reads = 0; + let psrc = 0; + while (pdst < fsize && reads < concurrency) { + const chunk = + (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); + singleRead(psrc, pdst, chunk); + psrc += chunk; + pdst += chunk; + ++reads; + } + } + }); + } + }); +} -/** - * Whether this entity is considered the "client" or "server". - * enum { server, client } ConnectionEnd; - */ -tls.ConnectionEnd = { - server: 0, - client: 1 -}; +function writeAll(sftp, handle, buffer, offset, length, position, callback_) { + const callback = (typeof callback_ === 'function' ? callback_ : undefined); -/** - * Pseudo-random function algorithm used to generate keys from the master - * secret. - * enum { tls_prf_sha256 } PRFAlgorithm; - */ -tls.PRFAlgorithm = { - tls_prf_sha256: 0 -}; + sftp.write(handle, + buffer, + offset, + length, + position, + (writeErr, written) => { + if (writeErr) { + return sftp.close(handle, () => { + callback && callback(writeErr); + }); + } + if (written === length) { + sftp.close(handle, callback); + } else { + offset += written; + length -= written; + position += written; + writeAll(sftp, handle, buffer, offset, length, position, callback); + } + }); +} -/** - * Bulk encryption algorithms. - * enum { null, rc4, des3, aes } BulkCipherAlgorithm; - */ -tls.BulkCipherAlgorithm = { - none: null, - rc4: 0, - des3: 1, - aes: 2 -}; +class Stats { + constructor(initial) { + this.mode = (initial && initial.mode); + this.uid = (initial && initial.uid); + this.gid = (initial && initial.gid); + this.size = (initial && initial.size); + this.atime = (initial && initial.atime); + this.mtime = (initial && initial.mtime); + this.extended = (initial && initial.extended); + } + isDirectory() { + return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); + } + isFile() { + return ((this.mode & constants.S_IFMT) === constants.S_IFREG); + } + isBlockDevice() { + return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); + } + isCharacterDevice() { + return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); + } + isSymbolicLink() { + return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); + } + isFIFO() { + return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); + } + isSocket() { + return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); + } +} -/** - * Cipher types. - * enum { stream, block, aead } CipherType; - */ -tls.CipherType = { - stream: 0, - block: 1, - aead: 2 -}; +function attrsToBytes(attrs) { + let flags = 0; + let nb = 0; -/** - * MAC (Message Authentication Code) algorithms. - * enum { null, hmac_md5, hmac_sha1, hmac_sha256, - * hmac_sha384, hmac_sha512} MACAlgorithm; - */ -tls.MACAlgorithm = { - none: null, - hmac_md5: 0, - hmac_sha1: 1, - hmac_sha256: 2, - hmac_sha384: 3, - hmac_sha512: 4 -}; + if (typeof attrs === 'object' && attrs !== null) { + if (typeof attrs.size === 'number') { + flags |= ATTR.SIZE; + const val = attrs.size; + // Big Endian + ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 + ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 + ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 + ATTRS_BUF[nb++] = val / 4294967296; // 2**32 + ATTRS_BUF[nb++] = val / 16777216; // 2**24 + ATTRS_BUF[nb++] = val / 65536; // 2**16 + ATTRS_BUF[nb++] = val / 256; // 2**8 + ATTRS_BUF[nb++] = val; + } + if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { + flags |= ATTR.UIDGID; + const uid = attrs.uid; + const gid = attrs.gid; + // Big Endian + ATTRS_BUF[nb++] = uid >>> 24; + ATTRS_BUF[nb++] = uid >>> 16; + ATTRS_BUF[nb++] = uid >>> 8; + ATTRS_BUF[nb++] = uid; + ATTRS_BUF[nb++] = gid >>> 24; + ATTRS_BUF[nb++] = gid >>> 16; + ATTRS_BUF[nb++] = gid >>> 8; + ATTRS_BUF[nb++] = gid; + } + if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { + const mode = modeNum(attrs.mode); + flags |= ATTR.PERMISSIONS; + // Big Endian + ATTRS_BUF[nb++] = mode >>> 24; + ATTRS_BUF[nb++] = mode >>> 16; + ATTRS_BUF[nb++] = mode >>> 8; + ATTRS_BUF[nb++] = mode; + } + if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) + && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { + const atime = toUnixTimestamp(attrs.atime); + const mtime = toUnixTimestamp(attrs.mtime); -/** - * Compression algorithms. - * enum { null(0), deflate(1), (255) } CompressionMethod; - */ -tls.CompressionMethod = { - none: 0, - deflate: 1 -}; + flags |= ATTR.ACMODTIME; + // Big Endian + ATTRS_BUF[nb++] = atime >>> 24; + ATTRS_BUF[nb++] = atime >>> 16; + ATTRS_BUF[nb++] = atime >>> 8; + ATTRS_BUF[nb++] = atime; + ATTRS_BUF[nb++] = mtime >>> 24; + ATTRS_BUF[nb++] = mtime >>> 16; + ATTRS_BUF[nb++] = mtime >>> 8; + ATTRS_BUF[nb++] = mtime; + } + // TODO: extended attributes + } -/** - * TLS record content types. - * enum { - * change_cipher_spec(20), alert(21), handshake(22), - * application_data(23), (255) - * } ContentType; - */ -tls.ContentType = { - change_cipher_spec: 20, - alert: 21, - handshake: 22, - application_data: 23, - heartbeat: 24 -}; + return { flags, nb }; +} -/** - * TLS handshake types. - * enum { - * hello_request(0), client_hello(1), server_hello(2), - * certificate(11), server_key_exchange (12), - * certificate_request(13), server_hello_done(14), - * certificate_verify(15), client_key_exchange(16), - * finished(20), (255) - * } HandshakeType; - */ -tls.HandshakeType = { - hello_request: 0, - client_hello: 1, - server_hello: 2, - certificate: 11, - server_key_exchange: 12, - certificate_request: 13, - server_hello_done: 14, - certificate_verify: 15, - client_key_exchange: 16, - finished: 20 -}; +function toUnixTimestamp(time) { + // eslint-disable-next-line no-self-compare + if (typeof time === 'number' && time === time) // Valid, non-NaN number + return time; + if (isDate(time)) + return parseInt(time.getTime() / 1000, 10); + throw new Error(`Cannot parse time: ${time}`); +} -/** - * TLS Alert Protocol. - * - * enum { warning(1), fatal(2), (255) } AlertLevel; - * - * enum { - * close_notify(0), - * unexpected_message(10), - * bad_record_mac(20), - * decryption_failed(21), - * record_overflow(22), - * decompression_failure(30), - * handshake_failure(40), - * bad_certificate(42), - * unsupported_certificate(43), - * certificate_revoked(44), - * certificate_expired(45), - * certificate_unknown(46), - * illegal_parameter(47), - * unknown_ca(48), - * access_denied(49), - * decode_error(50), - * decrypt_error(51), - * export_restriction(60), - * protocol_version(70), - * insufficient_security(71), - * internal_error(80), - * user_canceled(90), - * no_renegotiation(100), - * (255) - * } AlertDescription; - * - * struct { - * AlertLevel level; - * AlertDescription description; - * } Alert; - */ -tls.Alert = {}; -tls.Alert.Level = { - warning: 1, - fatal: 2 -}; -tls.Alert.Description = { - close_notify: 0, - unexpected_message: 10, - bad_record_mac: 20, - decryption_failed: 21, - record_overflow: 22, - decompression_failure: 30, - handshake_failure: 40, - bad_certificate: 42, - unsupported_certificate: 43, - certificate_revoked: 44, - certificate_expired: 45, - certificate_unknown: 46, - illegal_parameter: 47, - unknown_ca: 48, - access_denied: 49, - decode_error: 50, - decrypt_error: 51, - export_restriction: 60, - protocol_version: 70, - insufficient_security: 71, - internal_error: 80, - user_canceled: 90, - no_renegotiation: 100 -}; +function modeNum(mode) { + // eslint-disable-next-line no-self-compare + if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number + return mode; + if (typeof mode === 'string') + return modeNum(parseInt(mode, 8)); + throw new Error(`Cannot parse mode: ${mode}`); +} -/** - * TLS Heartbeat Message types. - * enum { - * heartbeat_request(1), - * heartbeat_response(2), - * (255) - * } HeartbeatMessageType; - */ -tls.HeartbeatMessageType = { - heartbeat_request: 1, - heartbeat_response: 2 +const stringFlagMap = { + 'r': OPEN_MODE.READ, + 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, + 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, + 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, + 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE + | OPEN_MODE.EXCL, + 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE + | OPEN_MODE.EXCL, + 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, + 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, + 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE + | OPEN_MODE.EXCL, + 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE + | OPEN_MODE.EXCL }; -/** - * Supported cipher suites. - */ -tls.CipherSuites = {}; +function stringToFlags(str) { + const flags = stringFlagMap[str]; + return (flags !== undefined ? flags : null); +} -/** - * Gets a supported cipher suite from its 2 byte ID. - * - * @param twoBytes two bytes in a string. - * - * @return the matching supported cipher suite or null. - */ -tls.getCipherSuite = function(twoBytes) { - var rval = null; - for(var key in tls.CipherSuites) { - var cs = tls.CipherSuites[key]; - if(cs.id[0] === twoBytes.charCodeAt(0) && - cs.id[1] === twoBytes.charCodeAt(1)) { - rval = cs; - break; +const flagsToString = (() => { + const stringFlagMapKeys = Object.keys(stringFlagMap); + return (flags) => { + for (let i = 0; i < stringFlagMapKeys.length; ++i) { + const key = stringFlagMapKeys[i]; + if (stringFlagMap[key] === flags) + return key; } - } - return rval; -}; + return null; + }; +})(); -/** - * Called when an unexpected record is encountered. - * - * @param c the connection. - * @param record the record. - */ -tls.handleUnexpected = function(c, record) { - // if connection is client and closed, ignore unexpected messages - var ignore = (!c.open && c.entity === tls.ConnectionEnd.client); - if(!ignore) { - c.error(c, { - message: 'Unexpected message. Received TLS record out of order.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); - } -}; +function readAttrs(biOpt) { + /* + uint32 flags + uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE + uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID + uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID + uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS + uint32 atime present only if flag SSH_FILEXFER_ACMODTIME + uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME + uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED + string extended_type + string extended_data + ... more extended data (extended_type - extended_data pairs), + so that number of pairs equals extended_count + */ + const flags = bufferParser.readUInt32BE(); + if (flags === undefined) + return; -/** - * Called when a client receives a HelloRequest record. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleHelloRequest = function(c, record, length) { - // ignore renegotiation requests from the server during a handshake, but - // if handshaking, send a warning alert that renegotation is denied - if(!c.handshaking && c.handshakes > 0) { - // send alert warning - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.no_renegotiation - })); - tls.flush(c); + const attrs = new Stats(); + if (flags & ATTR.SIZE) { + const size = bufferParser.readUInt64BE(biOpt); + if (size === undefined) + return; + attrs.size = size; } - // continue - c.process(); -}; + if (flags & ATTR.UIDGID) { + const uid = bufferParser.readUInt32BE(); + const gid = bufferParser.readUInt32BE(); + if (gid === undefined) + return; + attrs.uid = uid; + attrs.gid = gid; + } -/** - * Parses a hello message from a ClientHello or ServerHello record. - * - * @param record the record to parse. - * - * @return the parsed message. - */ -tls.parseHelloMessage = function(c, record, length) { - var msg = null; + if (flags & ATTR.PERMISSIONS) { + const mode = bufferParser.readUInt32BE(); + if (mode === undefined) + return; + attrs.mode = mode; + } - var client = (c.entity === tls.ConnectionEnd.client); + if (flags & ATTR.ACMODTIME) { + const atime = bufferParser.readUInt32BE(); + const mtime = bufferParser.readUInt32BE(); + if (mtime === undefined) + return; + attrs.atime = atime; + attrs.mtime = mtime; + } - // minimum of 38 bytes in message - if(length < 38) { - c.error(c, { - message: client ? - 'Invalid ServerHello message. Message too short.' : - 'Invalid ClientHello message. Message too short.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } else { - // use 'remaining' to calculate # of remaining bytes in the message - var b = record.fragment; - var remaining = b.length(); - msg = { - version: { - major: b.getByte(), - minor: b.getByte() - }, - random: forge.util.createBuffer(b.getBytes(32)), - session_id: readVector(b, 1), - extensions: [] - }; - if(client) { - msg.cipher_suite = b.getBytes(2); - msg.compression_method = b.getByte(); - } else { - msg.cipher_suites = readVector(b, 2); - msg.compression_methods = readVector(b, 1); + if (flags & ATTR.EXTENDED) { + const count = bufferParser.readUInt32BE(); + if (count === undefined) + return; + const extended = {}; + for (let i = 0; i < count; ++i) { + const type = bufferParser.readString(true); + const data = bufferParser.readString(); + if (data === undefined) + return; + extended[type] = data; } + attrs.extended = extended; + } - // read extensions if there are any bytes left in the message - remaining = length - (remaining - b.length()); - if(remaining > 0) { - // parse extensions - var exts = readVector(b, 2); - while(exts.length() > 0) { - msg.extensions.push({ - type: [exts.getByte(), exts.getByte()], - data: readVector(exts, 2) - }); - } + return attrs; +} - // TODO: make extension support modular - if(!client) { - for(var i = 0; i < msg.extensions.length; ++i) { - var ext = msg.extensions[i]; +function sendOrBuffer(sftp, payload) { + const ret = tryWritePayload(sftp, payload); + if (ret !== undefined) { + sftp._buffer.push(ret); + return false; + } + return true; +} - // support SNI extension - if(ext.type[0] === 0x00 && ext.type[1] === 0x00) { - // get server name list - var snl = readVector(ext.data, 2); - while(snl.length() > 0) { - // read server name type - var snType = snl.getByte(); +function tryWritePayload(sftp, payload) { + const outgoing = sftp.outgoing; + if (outgoing.state !== 'open') + return; - // only HostName type (0x00) is known, break out if - // another type is detected - if(snType !== 0x00) { - break; - } + if (outgoing.window === 0) { + sftp._waitWindow = true; + sftp._chunkcb = drainBuffer; + return payload; + } - // add host name to server name list - c.session.extensions.server_name.serverNameList.push( - readVector(snl, 2).getBytes()); - } - } - } - } - } + let ret; + const len = payload.length; + let p = 0; - // version already set, do not allow version change - if(c.session.version) { - if(msg.version.major !== c.session.version.major || - msg.version.minor !== c.session.version.minor) { - return c.error(c, { - message: 'TLS version change is disallowed during renegotiation.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } + while (len - p > 0 && outgoing.window > 0) { + const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); + outgoing.window -= actualLen; + if (outgoing.window === 0) { + sftp._waitWindow = true; + sftp._chunkcb = drainBuffer; } - // get the chosen (ServerHello) cipher suite - if(client) { - // FIXME: should be checking configured acceptable cipher suites - c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); + if (p === 0 && actualLen === len) { + sftp._protocol.channelData(sftp.outgoing.id, payload); } else { - // get a supported preferred (ClientHello) cipher suite - // choose the first supported cipher suite - var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); - while(tmp.length() > 0) { - // FIXME: should be checking configured acceptable suites - // cipher suites take up 2 bytes - c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); - if(c.session.cipherSuite !== null) { - break; - } - } - } - - // cipher suite not supported - if(c.session.cipherSuite === null) { - return c.error(c, { - message: 'No cipher suites in common.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - }, - cipherSuite: forge.util.bytesToHex(msg.cipher_suite) - }); + sftp._protocol.channelData(sftp.outgoing.id, + bufferSlice(payload, p, p + actualLen)); } - // TODO: handle compression methods - if(client) { - c.session.compressionMethod = msg.compression_method; - } else { - // no compression - c.session.compressionMethod = tls.CompressionMethod.none; - } + p += actualLen; } - return msg; -}; - -/** - * Creates security parameters for the given connection based on the given - * hello message. - * - * @param c the TLS connection. - * @param msg the hello message. - */ -tls.createSecurityParameters = function(c, msg) { - /* Note: security params are from TLS 1.2, some values like prf_algorithm - are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is - used. */ + if (len - p > 0) { + if (p > 0) + ret = bufferSlice(payload, p, len); + else + ret = payload; // XXX: should never get here? + } - // TODO: handle other options from server when more supported + return ret; +} - // get client and server randoms - var client = (c.entity === tls.ConnectionEnd.client); - var msgRandom = msg.random.bytes(); - var cRandom = client ? c.session.sp.client_random : msgRandom; - var sRandom = client ? msgRandom : tls.createRandom().getBytes(); +function drainBuffer() { + this._chunkcb = undefined; + const buffer = this._buffer; + let i = 0; + while (i < buffer.length) { + const payload = buffer[i]; + const ret = tryWritePayload(this, payload); + if (ret !== undefined) { + if (ret !== payload) + buffer[i] = ret; + if (i > 0) + this._buffer = buffer.slice(i); + return; + } + ++i; + } + if (i > 0) + this._buffer = []; +} - // create new security parameters - c.session.sp = { - entity: c.entity, - prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, - bulk_cipher_algorithm: null, - cipher_type: null, - enc_key_length: null, - block_length: null, - fixed_iv_length: null, - record_iv_length: null, - mac_algorithm: null, - mac_length: null, - mac_key_length: null, - compression_algorithm: c.session.compressionMethod, - pre_master_secret: null, - master_secret: null, - client_random: cRandom, - server_random: sRandom - }; -}; +function doFatalSFTPError(sftp, msg, noDebug) { + const err = new Error(msg); + err.level = 'sftp-protocol'; + if (!noDebug && sftp._debug) + sftp._debug(`SFTP: Inbound: ${msg}`); + sftp.emit('error', err); + sftp.destroy(); + cleanupRequests(sftp); + return false; +} -/** - * Called when a client receives a ServerHello record. - * - * When a ServerHello message will be sent: - * The server will send this message in response to a client hello message - * when it was able to find an acceptable set of algorithms. If it cannot - * find such a match, it will respond with a handshake failure alert. - * - * uint24 length; - * struct { - * ProtocolVersion server_version; - * Random random; - * SessionID session_id; - * CipherSuite cipher_suite; - * CompressionMethod compression_method; - * select(extensions_present) { - * case false: - * struct {}; - * case true: - * Extension extensions<0..2^16-1>; - * }; - * } ServerHello; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleServerHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if(c.fail) { +function cleanupRequests(sftp) { + const keys = Object.keys(sftp._requests); + if (keys.length === 0) return; - } - // ensure server version is compatible - if(msg.version.minor <= c.version.minor) { - c.version.minor = msg.version.minor; - } else { - return c.error(c, { - message: 'Incompatible TLS version.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); + const reqs = sftp._requests; + sftp._requests = {}; + const err = new Error('No response from server'); + for (let i = 0; i < keys.length; ++i) { + const req = reqs[keys[i]]; + if (typeof req.cb === 'function') + req.cb(err); } +} - // indicate session version has been set - c.session.version = c.version; +function requestLimits(sftp, cb) { + /* + uint32 id + string "limits@openssh.com" + */ + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); - // get the session ID from the message - var sessionId = msg.session_id.bytes(); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; + writeUInt32BE(buf, reqid, 5); - // if the session ID is not blank and matches the cached one, resume - // the session - if(sessionId.length > 0 && sessionId === c.session.id) { - // resuming session, expect a ChangeCipherSpec next - c.expect = SCC; - c.session.resuming = true; + writeUInt32BE(buf, 18, p); + buf.utf8Write('limits@openssh.com', p += 4, 18); - // get new server random - c.session.sp.server_random = msg.random.bytes(); - } else { - // not resuming, expect a server Certificate message next - c.expect = SCE; - c.session.resuming = false; + sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; - // create new security parameters - tls.createSecurityParameters(c, msg); + const isBuffered = sendOrBuffer(sftp, buf); + if (sftp._debug) { + const which = (isBuffered ? 'Buffered' : 'Sending'); + sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); } +} - // set new session ID - c.session.id = sessionId; - - // continue - c.process(); -}; - -/** - * Called when a server receives a ClientHello record. - * - * When a ClientHello message will be sent: - * When a client first connects to a server it is required to send the - * client hello as its first message. The client can also send a client - * hello in response to a hello request or on its own initiative in order - * to renegotiate the security parameters in an existing connection. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleClientHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if(c.fail) { - return; - } +const CLIENT_HANDLERS = { + [RESPONSE.VERSION]: (sftp, payload) => { + if (sftp._version !== -1) + return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); - // get the session ID from the message - var sessionId = msg.session_id.bytes(); + const extensions = {}; - // see if the given session ID is in the cache - var session = null; - if(c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - if(session === null) { - // session ID not found - sessionId = ''; - } else if(session.version.major !== msg.version.major || - session.version.minor > msg.version.minor) { - // if session version is incompatible with client version, do not resume - session = null; - sessionId = ''; + /* + uint32 version + + */ + bufferParser.init(payload, 1); + let version = bufferParser.readUInt32BE(); + while (bufferParser.avail()) { + const extName = bufferParser.readString(true); + const extData = bufferParser.readString(true); + if (extData === undefined) { + version = undefined; + break; + } + extensions[extName] = extData; } - } - - // no session found to resume, generate a new session ID - if(sessionId.length === 0) { - sessionId = forge.random.getBytes(32); - } + bufferParser.clear(); - // update session - c.session.id = sessionId; - c.session.clientHelloVersion = msg.version; - c.session.sp = {}; - if(session) { - // use version and security parameters from resumed session - c.version = c.session.version = session.version; - c.session.sp = session.sp; - } else { - // use highest compatible minor version - var version; - for(var i = 1; i < tls.SupportedVersions.length; ++i) { - version = tls.SupportedVersions[i]; - if(version.minor <= msg.version.minor) { - break; + if (version === undefined) + return doFatalSFTPError(sftp, 'Malformed VERSION packet'); + + if (sftp._debug) { + const names = Object.keys(extensions); + if (names.length) { + sftp._debug( + `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` + ); + } else { + sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); } } - c.version = {major: version.major, minor: version.minor}; - c.session.version = c.version; - } - // if a session is set, resume it - if(session !== null) { - // resuming session, expect a ChangeCipherSpec next - c.expect = CCC; - c.session.resuming = true; + sftp._version = version; + sftp._extensions = extensions; - // get new client random - c.session.sp.client_random = msg.random.bytes(); - } else { - // not resuming, expect a Certificate or ClientKeyExchange - c.expect = (c.verifyClient !== false) ? CCE : CKE; - c.session.resuming = false; + if (extensions['limits@openssh.com'] === '1') { + return requestLimits(sftp, (err, limits) => { + if (!err) { + if (limits.maxPktLen > 0) + sftp._maxOutPktLen = limits.maxPktLen; + if (limits.maxReadLen > 0) + sftp._maxReadLen = limits.maxReadLen; + if (limits.maxWriteLen > 0) + sftp._maxWriteLen = limits.maxWriteLen; + sftp.maxOpenHandles = ( + limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity + ); + } + sftp.emit('ready'); + }); + } - // create new security parameters - tls.createSecurityParameters(c, msg); - } + sftp.emit('ready'); + }, + [RESPONSE.STATUS]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + uint32 error/status code + string error message (ISO-10646 UTF-8) + string language tag + */ + const errorCode = bufferParser.readUInt32BE(); + const errorMsg = bufferParser.readString(true); + bufferParser.clear(); - // connection now open - c.open = true; + // Note: we avoid checking that the error message and language tag are in + // the packet because there are some broken implementations that incorrectly + // omit them. The language tag in general was never really used amongst ssh + // implementations, so in the case of a missing error message we just + // default to something sensible. - // queue server hello - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHello(c) - })); + if (sftp._debug) { + const jsonMsg = JSON.stringify(errorMsg); + sftp._debug( + `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` + ); + } + const req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + if (req && typeof req.cb === 'function') { + if (errorCode === STATUS_CODE.OK) { + req.cb(); + return; + } + const err = new Error(errorMsg + || STATUS_CODE_STR[errorCode] + || 'Unknown status'); + err.code = errorCode; + req.cb(err); + } + }, + [RESPONSE.HANDLE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + */ + const handle = bufferParser.readString(); + bufferParser.clear(); - if(c.session.resuming) { - // queue change cipher spec message - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); + if (handle === undefined) { + if (reqID !== undefined) + delete sftp._requests[reqID]; + return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); + } - // create pending state - c.state.pending = tls.createConnectionState(c); + sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); - // change current write state to pending write state - c.state.current.write = c.state.pending.write; + const req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + if (req && typeof req.cb === 'function') + req.cb(undefined, handle); + }, + [RESPONSE.DATA]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== undefined) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + /* + string data + */ + if (req && typeof req.cb === 'function') { + if (req.buffer) { + // We have already pre-allocated space to store the data - // queue finished - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } else { - // queue server certificate - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - })); + const nb = bufferParser.readString(req.buffer); + bufferParser.clear(); - if(!c.fail) { - // queue server key exchange - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerKeyExchange(c) - })); + if (nb !== undefined) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` + ); + req.cb(undefined, req.buffer, nb); + return; + } + } else { + const data = bufferParser.readString(); + bufferParser.clear(); - // request client certificate if set - if(c.verifyClient !== false) { - // queue certificate request - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificateRequest(c) - })); + if (data !== undefined) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` + ); + req.cb(undefined, data); + return; + } + } + } else { + const nb = bufferParser.skipString(); + bufferParser.clear(); + if (nb !== undefined) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` + ); + return; } - - // queue server hello done - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHelloDone(c) - })); } - } - - // send records - tls.flush(c); - - // continue - c.process(); -}; -/** - * Called when a client receives a Certificate record. - * - * When this message will be sent: - * The server must send a certificate whenever the agreed-upon key exchange - * method is not an anonymous one. This message will always immediately - * follow the server hello message. - * - * Meaning of this message: - * The certificate type must be appropriate for the selected cipher suite's - * key exchange algorithm, and is generally an X.509v3 certificate. It must - * contain a key which matches the key exchange method, as follows. Unless - * otherwise specified, the signing algorithm for the certificate must be - * the same as the algorithm for the certificate key. Unless otherwise - * specified, the public key may be of any length. - * - * opaque ASN.1Cert<1..2^24-1>; - * struct { - * ASN.1Cert certificate_list<1..2^24-1>; - * } Certificate; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleCertificate = function(c, record, length) { - // minimum of 3 bytes in message - if(length < 3) { - return c.error(c, { - message: 'Invalid Certificate message. Message too short.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } + return doFatalSFTPError(sftp, 'Malformed DATA packet'); + }, + [RESPONSE.NAME]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== undefined) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + /* + uint32 count + repeats count times: + string filename + string longname + ATTRS attrs + */ + const count = bufferParser.readUInt32BE(); + if (count !== undefined) { + let names = []; + for (let i = 0; i < count; ++i) { + // We are going to assume UTF-8 for filenames despite the SFTPv3 + // spec not specifying an encoding because the specs for newer + // versions of the protocol all explicitly specify UTF-8 for + // filenames + const filename = bufferParser.readString(true); - var b = record.fragment; - var msg = { - certificate_list: readVector(b, 3) - }; + // `longname` only exists in SFTPv3 and since it typically will + // contain the filename, we assume it is also UTF-8 + const longname = bufferParser.readString(true); - /* The sender's certificate will be first in the list (chain), each - subsequent one that follows will certify the previous one, but root - certificates (self-signed) that specify the certificate authority may - be omitted under the assumption that clients must already possess it. */ - var cert, asn1; - var certs = []; - try { - while(msg.certificate_list.length() > 0) { - // each entry in msg.certificate_list is a vector with 3 len bytes - cert = readVector(msg.certificate_list, 3); - asn1 = forge.asn1.fromDer(cert); - cert = forge.pki.certificateFromAsn1(asn1, true); - certs.push(cert); - } - } catch(ex) { - return c.error(c, { - message: 'Could not parse certificate list.', - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate + const attrs = readAttrs(sftp._biOpt); + if (attrs === undefined) { + names = undefined; + break; + } + names.push({ filename, longname, attrs }); } - }); - } - - // ensure at least 1 certificate was provided if in client-mode - // or if verifyClient was set to true to require a certificate - // (as opposed to 'optional') - var client = (c.entity === tls.ConnectionEnd.client); - if((client || c.verifyClient === true) && certs.length === 0) { - // error, no certificate - c.error(c, { - message: client ? - 'No server certificate provided.' : - 'No client certificate provided.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter + if (names !== undefined) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` + ); + bufferParser.clear(); + if (req && typeof req.cb === 'function') + req.cb(undefined, names); + return; } - }); - } else if(certs.length === 0) { - // no certs to verify - // expect a ServerKeyExchange or ClientKeyExchange message next - c.expect = client ? SKE : CKE; - } else { - // save certificate in session - if(client) { - c.session.serverCertificate = certs[0]; - } else { - c.session.clientCertificate = certs[0]; } - if(tls.verifyCertificateChain(c, certs)) { - // expect a ServerKeyExchange or ClientKeyExchange message next - c.expect = client ? SKE : CKE; + bufferParser.clear(); + return doFatalSFTPError(sftp, 'Malformed NAME packet'); + }, + [RESPONSE.ATTRS]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== undefined) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + /* + ATTRS attrs + */ + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); + if (attrs !== undefined) { + sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); + if (req && typeof req.cb === 'function') + req.cb(undefined, attrs); + return; } - } - // continue - c.process(); -}; + return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); + }, + [RESPONSE.EXTENDED]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + if (reqID !== undefined) { + const req = sftp._requests[reqID]; + if (req) { + delete sftp._requests[reqID]; + switch (req.extended) { + case 'statvfs@openssh.com': + case 'fstatvfs@openssh.com': { + /* + uint64 f_bsize // file system block size + uint64 f_frsize // fundamental fs block size + uint64 f_blocks // number of blocks (unit f_frsize) + uint64 f_bfree // free blocks in file system + uint64 f_bavail // free blocks for non-root + uint64 f_files // total file inodes + uint64 f_ffree // free file inodes + uint64 f_favail // free file inodes for to non-root + uint64 f_fsid // file system id + uint64 f_flag // bit mask of f_flag values + uint64 f_namemax // maximum filename length + */ + const biOpt = sftp._biOpt; + const stats = { + f_bsize: bufferParser.readUInt64BE(biOpt), + f_frsize: bufferParser.readUInt64BE(biOpt), + f_blocks: bufferParser.readUInt64BE(biOpt), + f_bfree: bufferParser.readUInt64BE(biOpt), + f_bavail: bufferParser.readUInt64BE(biOpt), + f_files: bufferParser.readUInt64BE(biOpt), + f_ffree: bufferParser.readUInt64BE(biOpt), + f_favail: bufferParser.readUInt64BE(biOpt), + f_sid: bufferParser.readUInt64BE(biOpt), + f_flag: bufferParser.readUInt64BE(biOpt), + f_namemax: bufferParser.readUInt64BE(biOpt), + }; + if (stats.f_namemax === undefined) + break; + if (sftp._debug) { + sftp._debug( + 'SFTP: Inbound: Received EXTENDED_REPLY ' + + `(id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === 'function') + req.cb(undefined, stats); + return; + } + case 'limits@openssh.com': { + /* + uint64 max-packet-length + uint64 max-read-length + uint64 max-write-length + uint64 max-open-handles + */ + const limits = { + maxPktLen: bufferParser.readUInt64BE(), + maxReadLen: bufferParser.readUInt64BE(), + maxWriteLen: bufferParser.readUInt64BE(), + maxOpenHandles: bufferParser.readUInt64BE(), + }; + if (limits.maxOpenHandles === undefined) + break; + if (sftp._debug) { + sftp._debug( + 'SFTP: Inbound: Received EXTENDED_REPLY ' + + `(id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === 'function') + req.cb(undefined, limits); + return; + } + case 'users-groups-by-id@openssh.com': { + /* + string usernames + string username1 + ... + string groupnames + string groupname1 + ... + */ + const usernameCount = bufferParser.readUInt32BE(); + if (usernameCount === undefined) + break; + const usernames = new Array(usernameCount); + for (let i = 0; i < usernames.length; ++i) + usernames[i] = bufferParser.readString(true); -/** - * Called when a client receives a ServerKeyExchange record. - * - * When this message will be sent: - * This message will be sent immediately after the server certificate - * message (or the server hello message, if this is an anonymous - * negotiation). - * - * The server key exchange message is sent by the server only when the - * server certificate message (if sent) does not contain enough data to - * allow the client to exchange a premaster secret. - * - * Meaning of this message: - * This message conveys cryptographic information to allow the client to - * communicate the premaster secret: either an RSA public key to encrypt - * the premaster secret with, or a Diffie-Hellman public key with which the - * client can complete a key exchange (with the result being the premaster - * secret.) - * - * enum { - * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa - * } KeyExchangeAlgorithm; - * - * struct { - * opaque dh_p<1..2^16-1>; - * opaque dh_g<1..2^16-1>; - * opaque dh_Ys<1..2^16-1>; - * } ServerDHParams; - * - * struct { - * select(KeyExchangeAlgorithm) { - * case dh_anon: - * ServerDHParams params; - * case dhe_dss: - * case dhe_rsa: - * ServerDHParams params; - * digitally-signed struct { - * opaque client_random[32]; - * opaque server_random[32]; - * ServerDHParams params; - * } signed_params; - * case rsa: - * case dh_dss: - * case dh_rsa: - * struct {}; - * }; - * } ServerKeyExchange; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleServerKeyExchange = function(c, record, length) { - // this implementation only supports RSA, no Diffie-Hellman support - // so any length > 0 is invalid - if(length > 0) { - return c.error(c, { - message: 'Invalid key parameters. Only RSA is supported.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate + const groupnameCount = bufferParser.readUInt32BE(); + if (groupnameCount === undefined) + break; + const groupnames = new Array(groupnameCount); + for (let i = 0; i < groupnames.length; ++i) + groupnames[i] = bufferParser.readString(true); + if (groupnames.length > 0 + && groupnames[groupnames.length - 1] === undefined) { + break; + } + + if (sftp._debug) { + sftp._debug( + 'SFTP: Inbound: Received EXTENDED_REPLY ' + + `(id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === 'function') + req.cb(undefined, usernames, groupnames); + return; + } + default: + // Unknown extended request + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` + ); + bufferParser.clear(); + if (typeof req.cb === 'function') + req.cb(); + return; + } + } else { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` + ); + bufferParser.clear(); + return; } - }); - } - - // expect an optional CertificateRequest message next - c.expect = SCR; + } - // continue - c.process(); + bufferParser.clear(); + return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); + }, }; +const SERVER_HANDLERS = { + [REQUEST.INIT]: (sftp, payload) => { + if (sftp._version !== -1) + return doFatalSFTPError(sftp, 'Duplicate INIT packet'); -/** - * Called when a client receives a ClientKeyExchange record. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleClientKeyExchange = function(c, record, length) { - // this implementation only supports RSA, no Diffie-Hellman support - // so any length < 48 is invalid - if(length < 48) { - return c.error(c, { - message: 'Invalid key parameters. Only RSA is supported.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate + const extensions = {}; + + /* + uint32 version + + */ + bufferParser.init(payload, 1); + let version = bufferParser.readUInt32BE(); + while (bufferParser.avail()) { + const extName = bufferParser.readString(true); + const extData = bufferParser.readString(true); + if (extData === undefined) { + version = undefined; + break; } - }); - } + extensions[extName] = extData; + } + bufferParser.clear(); - var b = record.fragment; - var msg = { - enc_pre_master_secret: readVector(b, 2).getBytes() - }; + if (version === undefined) + return doFatalSFTPError(sftp, 'Malformed INIT packet'); - // do rsa decryption - var privateKey = null; - if(c.getPrivateKey) { - try { - privateKey = c.getPrivateKey(c, c.session.serverCertificate); - privateKey = forge.pki.privateKeyFromPem(privateKey); - } catch(ex) { - c.error(c, { - message: 'Could not get private key.', - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); + if (sftp._debug) { + const names = Object.keys(extensions); + if (names.length) { + sftp._debug( + `SFTP: Inbound: Received INIT (v${version}, exts:${names})` + ); + } else { + sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); + } } - } - if(privateKey === null) { - return c.error(c, { - message: 'No private key set.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } + sendOrBuffer(sftp, SERVER_VERSION_BUFFER); - try { - // decrypt 48-byte pre-master secret - var sp = c.session.sp; - sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); + sftp._version = version; + sftp._extensions = extensions; + sftp.emit('ready'); + }, + [REQUEST.OPEN]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string filename + uint32 pflags + ATTRS attrs + */ + const filename = bufferParser.readString(true); + const pflags = bufferParser.readUInt32BE(); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); - // ensure client hello version matches first 2 bytes - var version = c.session.clientHelloVersion; - if(version.major !== sp.pre_master_secret.charCodeAt(0) || - version.minor !== sp.pre_master_secret.charCodeAt(1)) { - // error, do not send alert (see BLEI attack below) - throw new Error('TLS version rollback attack detected.'); + if (attrs === undefined) + return doFatalSFTPError(sftp, 'Malformed OPEN packet'); + + sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); + + if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } - } catch(ex) { - /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a - TLS server which is using PKCS#1 encoded RSA, so instead of - failing here, we generate 48 random bytes and use that as - the pre-master secret. */ - sp.pre_master_secret = forge.random.getBytes(48); - } + }, + [REQUEST.CLOSE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + */ + const handle = bufferParser.readString(); + bufferParser.clear(); - // expect a CertificateVerify message if a Certificate was received that - // does not have fixed Diffie-Hellman params, otherwise expect - // ChangeCipherSpec - c.expect = CCC; - if(c.session.clientCertificate !== null) { - // only RSA support, so expect CertificateVerify - // TODO: support Diffie-Hellman - c.expect = CCV; - } + if (handle === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); - // continue - c.process(); -}; + sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); -/** - * Called when a client receives a CertificateRequest record. - * - * When this message will be sent: - * A non-anonymous server can optionally request a certificate from the - * client, if appropriate for the selected cipher suite. This message, if - * sent, will immediately follow the Server Key Exchange message (if it is - * sent; otherwise, the Server Certificate message). - * - * enum { - * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4), - * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6), - * fortezza_dms_RESERVED(20), (255) - * } ClientCertificateType; - * - * opaque DistinguishedName<1..2^16-1>; - * - * struct { - * ClientCertificateType certificate_types<1..2^8-1>; - * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>; - * DistinguishedName certificate_authorities<0..2^16-1>; - * } CertificateRequest; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleCertificateRequest = function(c, record, length) { - // minimum of 3 bytes in message - if(length < 3) { - return c.error(c, { - message: 'Invalid CertificateRequest. Message too short.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } + if (!sftp.emit('CLOSE', reqID, handle)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.READ]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + uint64 offset + uint32 len + */ + const handle = bufferParser.readString(); + const offset = bufferParser.readUInt64BE(sftp._biOpt); + const len = bufferParser.readUInt32BE(); + bufferParser.clear(); - // TODO: TLS 1.2+ has different format including - // SignatureAndHashAlgorithm after cert types - var b = record.fragment; - var msg = { - certificate_types: readVector(b, 1), - certificate_authorities: readVector(b, 2) - }; + if (len === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed READ packet'); - // save certificate request in session - c.session.certificateRequest = msg; + sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); - // expect a ServerHelloDone message next - c.expect = SHD; + if (!sftp.emit('READ', reqID, handle, offset, len)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.WRITE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + uint64 offset + string data + */ + const handle = bufferParser.readString(); + const offset = bufferParser.readUInt64BE(sftp._biOpt); + const data = bufferParser.readString(); + bufferParser.clear(); - // continue - c.process(); -}; + if (data === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed WRITE packet'); -/** - * Called when a server receives a CertificateVerify record. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleCertificateVerify = function(c, record, length) { - if(length < 2) { - return c.error(c, { - message: 'Invalid CertificateVerify. Message too short.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } + sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); - // rewind to get full bytes for message so it can be manually - // digested below (special case for CertificateVerify messages because - // they must be digested *after* handling as opposed to all others) - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; + if (!sftp.emit('WRITE', reqID, handle, offset, data)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.LSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - var msg = { - signature: readVector(b, 2).getBytes() - }; + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); - // TODO: add support for DSA + sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); - // generate data to verify - var verify = forge.util.createBuffer(); - verify.putBuffer(c.session.md5.digest()); - verify.putBuffer(c.session.sha1.digest()); - verify = verify.getBytes(); + if (!sftp.emit('LSTAT', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.FSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + */ + const handle = bufferParser.readString(); + bufferParser.clear(); - try { - var cert = c.session.clientCertificate; - /*b = forge.pki.rsa.decrypt( - msg.signature, cert.publicKey, true, verify.length); - if(b !== verify) {*/ - if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) { - throw new Error('CertificateVerify signature does not match.'); + if (handle === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); + + sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); + + if (!sftp.emit('FSTAT', reqID, handle)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } + }, + [REQUEST.SETSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + ATTRS attrs + */ + const path = bufferParser.readString(true); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); - // digest message now that it has been handled - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - } catch(ex) { - return c.error(c, { - message: 'Bad signature in CertificateVerify.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - } - }); - } + if (attrs === undefined) + return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); - // expect ChangeCipherSpec - c.expect = CCC; + sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); - // continue - c.process(); -}; + if (!sftp.emit('SETSTAT', reqID, path, attrs)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.FSETSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + ATTRS attrs + */ + const handle = bufferParser.readString(); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); -/** - * Called when a client receives a ServerHelloDone record. - * - * When this message will be sent: - * The server hello done message is sent by the server to indicate the end - * of the server hello and associated messages. After sending this message - * the server will wait for a client response. - * - * Meaning of this message: - * This message means that the server is done sending messages to support - * the key exchange, and the client can proceed with its phase of the key - * exchange. - * - * Upon receipt of the server hello done message the client should verify - * that the server provided a valid certificate if required and check that - * the server hello parameters are acceptable. - * - * struct {} ServerHelloDone; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleServerHelloDone = function(c, record, length) { - // len must be 0 bytes - if(length > 0) { - return c.error(c, { - message: 'Invalid ServerHelloDone message. Invalid length.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.record_overflow - } - }); - } + if (attrs === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); - if(c.serverCertificate === null) { - // no server certificate was provided - var error = { - message: 'No server certificate provided. Not enough security.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.insufficient_security - } - }; + sftp._debug && sftp._debug( + `SFTP: Inbound: Received FSETSTAT (id:${reqID})` + ); - // call application callback - var depth = 0; - var ret = c.verify(c, error.alert.description, depth, []); - if(ret !== true) { - // check for custom alert info - if(ret || ret === 0) { - // set custom message and alert description - if(typeof ret === 'object' && !forge.util.isArray(ret)) { - if(ret.message) { - error.message = ret.message; - } - if(ret.alert) { - error.alert.description = ret.alert; - } - } else if(typeof ret === 'number') { - // set custom alert description - error.alert.description = ret; - } - } + if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.OPENDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); + + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); + + sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); + + if (!sftp.emit('OPENDIR', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.READDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string handle + */ + const handle = bufferParser.readString(); + bufferParser.clear(); + + if (handle === undefined || handle.length > 256) + return doFatalSFTPError(sftp, 'Malformed READDIR packet'); + + sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); + + if (!sftp.emit('READDIR', reqID, handle)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.REMOVE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - // send error - return c.error(c, error); - } - } + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); - // create client certificate message if requested - if(c.session.certificateRequest !== null) { - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - }); - tls.queue(c, record); - } + sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); - // create client key exchange message - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientKeyExchange(c) - }); - tls.queue(c, record); + if (!sftp.emit('REMOVE', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.MKDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + ATTRS attrs + */ + const path = bufferParser.readString(true); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); - // expect no messages until the following callback has been called - c.expect = SER; + if (attrs === undefined) + return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); - // create callback to handle client signature (for client-certs) - var callback = function(c, signature) { - if(c.session.certificateRequest !== null && - c.session.clientCertificate !== null) { - // create certificate verify message - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificateVerify(c, signature) - })); - } + sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); - // create change cipher spec message - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); + if (!sftp.emit('MKDIR', reqID, path, attrs)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.RMDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - // create pending state - c.state.pending = tls.createConnectionState(c); + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); - // change current write state to pending write state - c.state.current.write = c.state.pending.write; + sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); - // create finished message - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); + if (!sftp.emit('RMDIR', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.REALPATH]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - // expect a server ChangeCipherSpec message next - c.expect = SCC; + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); - // send records - tls.flush(c); + sftp._debug && sftp._debug( + `SFTP: Inbound: Received REALPATH (id:${reqID})` + ); - // continue - c.process(); - }; + if (!sftp.emit('REALPATH', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.STAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - // if there is no certificate request or no client certificate, do - // callback immediately - if(c.session.certificateRequest === null || - c.session.clientCertificate === null) { - return callback(c, null); - } + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed STAT packet'); - // otherwise get the client signature - tls.getClientSignature(c, callback); -}; + sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); -/** - * Called when a ChangeCipherSpec record is received. - * - * @param c the connection. - * @param record the record. - */ -tls.handleChangeCipherSpec = function(c, record) { - if(record.fragment.getByte() !== 0x01) { - return c.error(c, { - message: 'Invalid ChangeCipherSpec message received.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } + if (!sftp.emit('STAT', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.RENAME]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string oldpath + string newpath + */ + const oldPath = bufferParser.readString(true); + const newPath = bufferParser.readString(true); + bufferParser.clear(); - // create pending state if: - // 1. Resuming session in client mode OR - // 2. NOT resuming session in server mode - var client = (c.entity === tls.ConnectionEnd.client); - if((c.session.resuming && client) || (!c.session.resuming && !client)) { - c.state.pending = tls.createConnectionState(c); - } + if (newPath === undefined) + return doFatalSFTPError(sftp, 'Malformed RENAME packet'); - // change current read state to pending read state - c.state.current.read = c.state.pending.read; + sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); - // clear pending state if: - // 1. NOT resuming session in client mode OR - // 2. resuming a session in server mode - if((!c.session.resuming && client) || (c.session.resuming && !client)) { - c.state.pending = null; - } + if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.READLINK]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string path + */ + const path = bufferParser.readString(true); + bufferParser.clear(); - // expect a Finished record next - c.expect = client ? SFI : CFI; + if (path === undefined) + return doFatalSFTPError(sftp, 'Malformed READLINK packet'); - // continue - c.process(); -}; + sftp._debug && sftp._debug( + `SFTP: Inbound: Received READLINK (id:${reqID})` + ); -/** - * Called when a Finished record is received. - * - * When this message will be sent: - * A finished message is always sent immediately after a change - * cipher spec message to verify that the key exchange and - * authentication processes were successful. It is essential that a - * change cipher spec message be received between the other - * handshake messages and the Finished message. - * - * Meaning of this message: - * The finished message is the first protected with the just- - * negotiated algorithms, keys, and secrets. Recipients of finished - * messages must verify that the contents are correct. Once a side - * has sent its Finished message and received and validated the - * Finished message from its peer, it may begin to send and receive - * application data over the connection. - * - * struct { - * opaque verify_data[verify_data_length]; - * } Finished; - * - * verify_data - * PRF(master_secret, finished_label, Hash(handshake_messages)) - * [0..verify_data_length-1]; - * - * finished_label - * For Finished messages sent by the client, the string - * "client finished". For Finished messages sent by the server, the - * string "server finished". - * - * verify_data_length depends on the cipher suite. If it is not specified - * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used - * 12 bytes. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls.handleFinished = function(c, record, length) { - // rewind to get full bytes for message so it can be manually - // digested below (special case for Finished messages because they - // must be digested *after* handling as opposed to all others) - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; + if (!sftp.emit('READLINK', reqID, path)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.SYMLINK]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string linkpath + string targetpath + */ + const linkPath = bufferParser.readString(true); + const targetPath = bufferParser.readString(true); + bufferParser.clear(); - // message contains only verify_data - var vd = record.fragment.getBytes(); + if (targetPath === undefined) + return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); - // ensure verify data is correct - b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); + sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); - // set label based on entity type - var client = (c.entity === tls.ConnectionEnd.client); - var label = client ? 'server finished' : 'client finished'; + let handled; + if (sftp._isOpenSSH) { + // OpenSSH has linkpath and targetpath positions switched + handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); + } else { + handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); + } + if (!handled) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.EXTENDED]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + /* + string extended-request + ... any request-specific data ... + */ + const extName = bufferParser.readString(true); + if (extName === undefined) { + bufferParser.clear(); + return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); + } - // TODO: determine prf function and verify length for TLS 1.2 - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - if(b.getBytes() !== vd) { - return c.error(c, { - message: 'Invalid verify_data in Finished message.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decrypt_error - } - }); - } + let extData; + if (bufferParser.avail()) + extData = bufferParser.readRaw(); + bufferParser.clear(); - // digest finished message now that it has been handled - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED (id:${reqID})` + ); - // resuming session as client or NOT resuming session as server - if((c.session.resuming && client) || (!c.session.resuming && !client)) { - // create change cipher spec message - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); + if (!sftp.emit('EXTENDED', reqID, extName, extData)) { + // Automatically reject request if no handler for request type + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, +}; - // change current write state to pending write state, clear pending - c.state.current.write = c.state.pending.write; - c.state.pending = null; +// ============================================================================= +// ReadStream/WriteStream-related ============================================== +// ============================================================================= +const { + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE, + validateNumber +} = __nccwpck_require__(7609); - // create finished message - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } +const kMinPoolSpace = 128; - // expect application data next - c.expect = client ? SAD : CAD; +let pool; +// It can happen that we expect to read a large chunk of data, and reserve +// a large chunk of the pool accordingly, but the read() call only filled +// a portion of it. If a concurrently executing read() then uses the same pool, +// the "reserved" portion cannot be used, so we allow it to be re-used as a +// new pool later. +const poolFragments = []; - // handshake complete - c.handshaking = false; - ++c.handshakes; +function allocNewPool(poolSize) { + if (poolFragments.length > 0) + pool = poolFragments.pop(); + else + pool = Buffer.allocUnsafe(poolSize); + pool.used = 0; +} - // save access to peer certificate - c.peerCertificate = client ? - c.session.serverCertificate : c.session.clientCertificate; +// Check the `this.start` and `this.end` of stream. +function checkPosition(pos, name) { + if (!Number.isSafeInteger(pos)) { + validateNumber(pos, name); + if (!Number.isInteger(pos)) + throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); + throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); + } + if (pos < 0) + throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); +} - // send records - tls.flush(c); +function roundUpToMultipleOf8(n) { + return (n + 7) & ~7; // Align to 8 byte boundary. +} - // now connected - c.isConnected = true; - c.connected(c); +function ReadStream(sftp, path, options) { + if (options === undefined) + options = {}; + else if (typeof options === 'string') + options = { encoding: options }; + else if (options === null || typeof options !== 'object') + throw new TypeError('"options" argument must be a string or an object'); + else + options = Object.create(options); - // continue - c.process(); -}; + // A little bit bigger buffer and water marks by default + if (options.highWaterMark === undefined) + options.highWaterMark = 64 * 1024; -/** - * Called when an Alert record is received. - * - * @param c the connection. - * @param record the record. - */ -tls.handleAlert = function(c, record) { - // read alert - var b = record.fragment; - var alert = { - level: b.getByte(), - description: b.getByte() - }; + // For backwards compat do not emit close on destroy. + options.emitClose = false; + options.autoDestroy = false; // Node 14 major change. - // TODO: consider using a table? - // get appropriate message - var msg; - switch(alert.description) { - case tls.Alert.Description.close_notify: - msg = 'Connection closed.'; - break; - case tls.Alert.Description.unexpected_message: - msg = 'Unexpected message.'; - break; - case tls.Alert.Description.bad_record_mac: - msg = 'Bad record MAC.'; - break; - case tls.Alert.Description.decryption_failed: - msg = 'Decryption failed.'; - break; - case tls.Alert.Description.record_overflow: - msg = 'Record overflow.'; - break; - case tls.Alert.Description.decompression_failure: - msg = 'Decompression failed.'; - break; - case tls.Alert.Description.handshake_failure: - msg = 'Handshake failure.'; - break; - case tls.Alert.Description.bad_certificate: - msg = 'Bad certificate.'; - break; - case tls.Alert.Description.unsupported_certificate: - msg = 'Unsupported certificate.'; - break; - case tls.Alert.Description.certificate_revoked: - msg = 'Certificate revoked.'; - break; - case tls.Alert.Description.certificate_expired: - msg = 'Certificate expired.'; - break; - case tls.Alert.Description.certificate_unknown: - msg = 'Certificate unknown.'; - break; - case tls.Alert.Description.illegal_parameter: - msg = 'Illegal parameter.'; - break; - case tls.Alert.Description.unknown_ca: - msg = 'Unknown certificate authority.'; - break; - case tls.Alert.Description.access_denied: - msg = 'Access denied.'; - break; - case tls.Alert.Description.decode_error: - msg = 'Decode error.'; - break; - case tls.Alert.Description.decrypt_error: - msg = 'Decrypt error.'; - break; - case tls.Alert.Description.export_restriction: - msg = 'Export restriction.'; - break; - case tls.Alert.Description.protocol_version: - msg = 'Unsupported protocol version.'; - break; - case tls.Alert.Description.insufficient_security: - msg = 'Insufficient security.'; - break; - case tls.Alert.Description.internal_error: - msg = 'Internal error.'; - break; - case tls.Alert.Description.user_canceled: - msg = 'User canceled.'; - break; - case tls.Alert.Description.no_renegotiation: - msg = 'Renegotiation not supported.'; - break; - default: - msg = 'Unknown error.'; - break; + ReadableStream.call(this, options); + + this.path = path; + this.flags = options.flags === undefined ? 'r' : options.flags; + this.mode = options.mode === undefined ? 0o666 : options.mode; + + this.start = options.start; + this.end = options.end; + this.autoClose = options.autoClose === undefined ? true : options.autoClose; + this.pos = 0; + this.bytesRead = 0; + this.isClosed = false; + + this.handle = options.handle === undefined ? null : options.handle; + this.sftp = sftp; + this._opening = false; + + if (this.start !== undefined) { + checkPosition(this.start, 'start'); + + this.pos = this.start; } - // close connection on close_notify, not an error - if(alert.description === tls.Alert.Description.close_notify) { - return c.close(); + if (this.end === undefined) { + this.end = Infinity; + } else if (this.end !== Infinity) { + checkPosition(this.end, 'end'); + + if (this.start !== undefined && this.start > this.end) { + throw new ERR_OUT_OF_RANGE( + 'start', + `<= "end" (here: ${this.end})`, + this.start + ); + } } - // call error handler - c.error(c, { - message: msg, - send: false, - // origin is the opposite end - origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client', - alert: alert + this.on('end', function() { + if (this.autoClose) + this.destroy(); }); - // continue - c.process(); + if (!Buffer.isBuffer(this.handle)) + this.open(); +} +inherits(ReadStream, ReadableStream); + +ReadStream.prototype.open = function() { + if (this._opening) + return; + + this._opening = true; + + this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { + this._opening = false; + + if (er) { + this.emit('error', er); + if (this.autoClose) + this.destroy(); + return; + } + + this.handle = handle; + this.emit('open', handle); + this.emit('ready'); + // Start the flow of data. + this.read(); + }); }; -/** - * Called when a Handshake record is received. - * - * @param c the connection. - * @param record the record. - */ -tls.handleHandshake = function(c, record) { - // get the handshake type and message length - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt24(); +ReadStream.prototype._read = function(n) { + if (!Buffer.isBuffer(this.handle)) + return this.once('open', () => this._read(n)); - // see if the record fragment doesn't yet contain the full message - if(length > b.length()) { - // cache the record, clear its fragment, and reset the buffer read - // pointer before the type and length were read - c.fragmented = record; - record.fragment = forge.util.createBuffer(); - b.read -= 4; + // XXX: safe to remove this? + if (this.destroyed) + return; - // continue - return c.process(); + if (!pool || pool.length - pool.used < kMinPoolSpace) { + // Discard the old pool. + allocNewPool(this.readableHighWaterMark + || this._readableState.highWaterMark); } - // full message now available, clear cache, reset read pointer to - // before type and length - c.fragmented = null; - b.read -= 4; + // Grab another reference to the pool in the case that while we're + // in the thread pool another read() finishes up the pool, and + // allocates a new one. + const thisPool = pool; + let toRead = Math.min(pool.length - pool.used, n); + const start = pool.used; - // save the handshake bytes for digestion after handler is found - // (include type and length of handshake msg) - var bytes = b.bytes(length + 4); + if (this.end !== undefined) + toRead = Math.min(this.end - this.pos + 1, toRead); - // restore read pointer - b.read += 4; + // Already read everything we were supposed to read! + // treat as EOF. + if (toRead <= 0) + return this.push(null); - // handle expected message - if(type in hsTable[c.entity][c.expect]) { - // initialize server session - if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { - c.handshaking = true; - c.session = { - version: null, - extensions: { - server_name: { - serverNameList: [] - } - }, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - clientCertificate: null, - md5: forge.md.md5.create(), - sha1: forge.md.sha1.create() - }; + // the actual read. + this.sftp.read(this.handle, + pool, + pool.used, + toRead, + this.pos, + (er, bytesRead) => { + if (er) { + this.emit('error', er); + if (this.autoClose) + this.destroy(); + return; } + let b = null; - /* Update handshake messages digest. Finished and CertificateVerify - messages are not digested here. They can't be digested as part of - the verify_data that they contain. These messages are manually - digested in their handlers. HelloRequest messages are simply never - included in the handshake message digest according to spec. */ - if(type !== tls.HandshakeType.hello_request && - type !== tls.HandshakeType.certificate_verify && - type !== tls.HandshakeType.finished) { - c.session.md5.update(bytes); - c.session.sha1.update(bytes); + // Now that we know how much data we have actually read, re-wind the + // 'used' field if we can, and otherwise allow the remainder of our + // reservation to be used as a new pool later. + if (start + toRead === thisPool.used && thisPool === pool) { + thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); + } else { + // Round down to the next lowest multiple of 8 to ensure the new pool + // fragment start and end positions are aligned to an 8 byte boundary. + const alignedEnd = (start + toRead) & ~7; + const alignedStart = roundUpToMultipleOf8(start + bytesRead); + if (alignedEnd - alignedStart >= kMinPoolSpace) + poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); } - // handle specific handshake type record - hsTable[c.entity][c.expect][type](c, record, length); - } else { - // unexpected record - tls.handleUnexpected(c, record); - } + if (bytesRead > 0) { + this.bytesRead += bytesRead; + b = thisPool.slice(start, start + bytesRead); + } + + // Move the pool positions, and internal position for reading. + this.pos += bytesRead; + + this.push(b); + }); + + pool.used = roundUpToMultipleOf8(pool.used + toRead); }; -/** - * Called when an ApplicationData record is received. - * - * @param c the connection. - * @param record the record. - */ -tls.handleApplicationData = function(c, record) { - // buffer data, notify that its ready - c.data.putBuffer(record.fragment); - c.dataReady(c); +ReadStream.prototype._destroy = function(err, cb) { + if (this._opening && !Buffer.isBuffer(this.handle)) { + this.once('open', closeStream.bind(null, this, cb, err)); + return; + } - // continue - c.process(); + closeStream(this, cb, err); + this.handle = null; + this._opening = false; }; -/** - * Called when a Heartbeat record is received. - * - * @param c the connection. - * @param record the record. - */ -tls.handleHeartbeat = function(c, record) { - // get the heartbeat type and payload - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt16(); - var payload = b.getBytes(length); +function closeStream(stream, cb, err) { + if (!stream.handle) + return onclose(); - if(type === tls.HeartbeatMessageType.heartbeat_request) { - // discard request during handshake or if length is too large - if(c.handshaking || length > payload.length) { - // continue - return c.process(); - } - // retransmit payload - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_response, payload) - })); - tls.flush(c); - } else if(type === tls.HeartbeatMessageType.heartbeat_response) { - // check payload against expected payload, discard heartbeat if no match - if(payload !== c.expectedHeartbeatPayload) { - // continue - return c.process(); - } + stream.sftp.close(stream.handle, onclose); - // notify that a valid heartbeat was received - if(c.heartbeatReceived) { - c.heartbeatReceived(c, forge.util.createBuffer(payload)); - } + function onclose(er) { + er = er || err; + cb(er); + stream.isClosed = true; + if (!er) + stream.emit('close'); } +} - // continue - c.process(); +ReadStream.prototype.close = function(cb) { + this.destroy(null, cb); }; -/** - * The transistional state tables for receiving TLS records. It maps the - * current TLS engine state and a received record to a function to handle the - * record and update the state. - * - * For instance, if the current state is SHE, then the TLS engine is expecting - * a ServerHello record. Once a record is received, the handler function is - * looked up using the state SHE and the record's content type. - * - * The resulting function will either be an error handler or a record handler. - * The function will take whatever action is appropriate and update the state - * for the next record. - * - * The states are all based on possible server record types. Note that the - * client will never specifically expect to receive a HelloRequest or an alert - * from the server so there is no state that reflects this. These messages may - * occur at any time. - * - * There are two tables for mapping states because there is a second tier of - * types for handshake messages. Once a record with a content type of handshake - * is received, the handshake record handler will look up the handshake type in - * the secondary map to get its appropriate handler. - * - * Valid message orders are as follows: - * - * =======================FULL HANDSHAKE====================== - * Client Server - * - * ClientHello --------> - * ServerHello - * Certificate* - * ServerKeyExchange* - * CertificateRequest* - * <-------- ServerHelloDone - * Certificate* - * ClientKeyExchange - * CertificateVerify* - * [ChangeCipherSpec] - * Finished --------> - * [ChangeCipherSpec] - * <-------- Finished - * Application Data <-------> Application Data - * - * =====================SESSION RESUMPTION===================== - * Client Server - * - * ClientHello --------> - * ServerHello - * [ChangeCipherSpec] - * <-------- Finished - * [ChangeCipherSpec] - * Finished --------> - * Application Data <-------> Application Data - */ -// client expect states (indicate which records are expected to be received) -var SHE = 0; // rcv server hello -var SCE = 1; // rcv server certificate -var SKE = 2; // rcv server key exchange -var SCR = 3; // rcv certificate request -var SHD = 4; // rcv server hello done -var SCC = 5; // rcv change cipher spec -var SFI = 6; // rcv finished -var SAD = 7; // rcv application data -var SER = 8; // not expecting any messages at this point - -// server expect states -var CHE = 0; // rcv client hello -var CCE = 1; // rcv client certificate -var CKE = 2; // rcv client key exchange -var CCV = 3; // rcv certificate verify -var CCC = 4; // rcv change cipher spec -var CFI = 5; // rcv finished -var CAD = 6; // rcv application data -var CER = 7; // not expecting any messages at this point +Object.defineProperty(ReadStream.prototype, 'pending', { + get() { + return this.handle === null; + }, + configurable: true +}); -// map client current expect state and content type to function -var __ = tls.handleUnexpected; -var R0 = tls.handleChangeCipherSpec; -var R1 = tls.handleAlert; -var R2 = tls.handleHandshake; -var R3 = tls.handleApplicationData; -var R4 = tls.handleHeartbeat; -var ctTable = []; -ctTable[tls.ConnectionEnd.client] = [ -// CC,AL,HS,AD,HB -/*SHE*/[__,R1,R2,__,R4], -/*SCE*/[__,R1,R2,__,R4], -/*SKE*/[__,R1,R2,__,R4], -/*SCR*/[__,R1,R2,__,R4], -/*SHD*/[__,R1,R2,__,R4], -/*SCC*/[R0,R1,__,__,R4], -/*SFI*/[__,R1,R2,__,R4], -/*SAD*/[__,R1,R2,R3,R4], -/*SER*/[__,R1,R2,__,R4] -]; +// TODO: add `concurrency` setting to allow more than one in-flight WRITE +// request to server to improve throughput +function WriteStream(sftp, path, options) { + if (options === undefined) + options = {}; + else if (typeof options === 'string') + options = { encoding: options }; + else if (options === null || typeof options !== 'object') + throw new TypeError('"options" argument must be a string or an object'); + else + options = Object.create(options); -// map server current expect state and content type to function -ctTable[tls.ConnectionEnd.server] = [ -// CC,AL,HS,AD -/*CHE*/[__,R1,R2,__,R4], -/*CCE*/[__,R1,R2,__,R4], -/*CKE*/[__,R1,R2,__,R4], -/*CCV*/[__,R1,R2,__,R4], -/*CCC*/[R0,R1,__,__,R4], -/*CFI*/[__,R1,R2,__,R4], -/*CAD*/[__,R1,R2,R3,R4], -/*CER*/[__,R1,R2,__,R4] -]; + // For backwards compat do not emit close on destroy. + options.emitClose = false; + options.autoDestroy = false; // Node 14 major change. -// map client current expect state and handshake type to function -var H0 = tls.handleHelloRequest; -var H1 = tls.handleServerHello; -var H2 = tls.handleCertificate; -var H3 = tls.handleServerKeyExchange; -var H4 = tls.handleCertificateRequest; -var H5 = tls.handleServerHelloDone; -var H6 = tls.handleFinished; -var hsTable = []; -hsTable[tls.ConnectionEnd.client] = [ -// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI -/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__], -/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__], -/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__], -/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__], -/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], -/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] -]; + WritableStream.call(this, options); -// map server current expect state and handshake type to function -// Note: CAD[CH] does not map to FB because renegotation is prohibited -var H7 = tls.handleClientHello; -var H8 = tls.handleClientKeyExchange; -var H9 = tls.handleCertificateVerify; -hsTable[tls.ConnectionEnd.server] = [ -// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI -/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__], -/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__], -/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__], -/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], -/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] -]; + this.path = path; + this.flags = options.flags === undefined ? 'w' : options.flags; + this.mode = options.mode === undefined ? 0o666 : options.mode; -/** - * Generates the master_secret and keys using the given security parameters. - * - * The security parameters for a TLS connection state are defined as such: - * - * struct { - * ConnectionEnd entity; - * PRFAlgorithm prf_algorithm; - * BulkCipherAlgorithm bulk_cipher_algorithm; - * CipherType cipher_type; - * uint8 enc_key_length; - * uint8 block_length; - * uint8 fixed_iv_length; - * uint8 record_iv_length; - * MACAlgorithm mac_algorithm; - * uint8 mac_length; - * uint8 mac_key_length; - * CompressionMethod compression_algorithm; - * opaque master_secret[48]; - * opaque client_random[32]; - * opaque server_random[32]; - * } SecurityParameters; - * - * Note that this definition is from TLS 1.2. In TLS 1.0 some of these - * parameters are ignored because, for instance, the PRFAlgorithm is a - * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0. - * - * The Record Protocol requires an algorithm to generate keys required by the - * current connection state. - * - * The master secret is expanded into a sequence of secure bytes, which is then - * split to a client write MAC key, a server write MAC key, a client write - * encryption key, and a server write encryption key. In TLS 1.0 a client write - * IV and server write IV are also generated. Each of these is generated from - * the byte sequence in that order. Unused values are empty. In TLS 1.2, some - * AEAD ciphers may additionally require a client write IV and a server write - * IV (see Section 6.2.3.3). - * - * When keys, MAC keys, and IVs are generated, the master secret is used as an - * entropy source. - * - * To generate the key material, compute: - * - * master_secret = PRF(pre_master_secret, "master secret", - * ClientHello.random + ServerHello.random) - * - * key_block = PRF(SecurityParameters.master_secret, - * "key expansion", - * SecurityParameters.server_random + - * SecurityParameters.client_random); - * - * until enough output has been generated. Then, the key_block is - * partitioned as follows: - * - * client_write_MAC_key[SecurityParameters.mac_key_length] - * server_write_MAC_key[SecurityParameters.mac_key_length] - * client_write_key[SecurityParameters.enc_key_length] - * server_write_key[SecurityParameters.enc_key_length] - * client_write_IV[SecurityParameters.fixed_iv_length] - * server_write_IV[SecurityParameters.fixed_iv_length] - * - * In TLS 1.2, the client_write_IV and server_write_IV are only generated for - * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This - * implementation uses TLS 1.0 so IVs are generated. - * - * Implementation note: The currently defined cipher suite which requires the - * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32 - * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also - * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material. - * - * @param c the connection. - * @param sp the security parameters to use. - * - * @return the security keys. - */ -tls.generateKeys = function(c, sp) { - // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) & - // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented - // at present + this.start = options.start; + this.autoClose = options.autoClose === undefined ? true : options.autoClose; + this.pos = 0; + this.bytesWritten = 0; + this.isClosed = false; - // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with - // TLS 1.0 but we don't care right now because AES is better and we have - // an implementation for it + this.handle = options.handle === undefined ? null : options.handle; + this.sftp = sftp; + this._opening = false; - // TODO: TLS 1.2 implementation - /* - // determine the PRF - var prf; - switch(sp.prf_algorithm) { - case tls.PRFAlgorithm.tls_prf_sha256: - prf = prf_sha256; - break; - default: - // should never happen - throw new Error('Invalid PRF'); + if (this.start !== undefined) { + checkPosition(this.start, 'start'); + + this.pos = this.start; } - */ - // TLS 1.0/1.1 implementation - var prf = prf_TLS1; + if (options.encoding) + this.setDefaultEncoding(options.encoding); - // concatenate server and client random - var random = sp.client_random + sp.server_random; + // Node v6.x only + this.on('finish', function() { + if (this._writableState.finalCalled) + return; + if (this.autoClose) + this.destroy(); + }); - // only create master secret if session is new - if(!c.session.resuming) { - // create master secret, clean up pre-master secret - sp.master_secret = prf( - sp.pre_master_secret, 'master secret', random, 48).bytes(); - sp.pre_master_secret = null; - } + if (!Buffer.isBuffer(this.handle)) + this.open(); +} +inherits(WriteStream, WritableStream); - // generate the amount of key material needed - random = sp.server_random + sp.client_random; - var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; +WriteStream.prototype._final = function(cb) { + if (this.autoClose) + this.destroy(); + cb(); +}; - // include IV for TLS/1.0 - var tls10 = (c.version.major === tls.Versions.TLS_1_0.major && - c.version.minor === tls.Versions.TLS_1_0.minor); - if(tls10) { - length += 2 * sp.fixed_iv_length; - } - var km = prf(sp.master_secret, 'key expansion', random, length); +WriteStream.prototype.open = function() { + if (this._opening) + return; - // split the key material into the MAC and encryption keys - var rval = { - client_write_MAC_key: km.getBytes(sp.mac_key_length), - server_write_MAC_key: km.getBytes(sp.mac_key_length), - client_write_key: km.getBytes(sp.enc_key_length), - server_write_key: km.getBytes(sp.enc_key_length) - }; + this._opening = true; - // include TLS 1.0 IVs - if(tls10) { - rval.client_write_IV = km.getBytes(sp.fixed_iv_length); - rval.server_write_IV = km.getBytes(sp.fixed_iv_length); - } + this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { + this._opening = false; - return rval; -}; + if (er) { + this.emit('error', er); + if (this.autoClose) + this.destroy(); + return; + } -/** - * Creates a new initialized TLS connection state. A connection state has - * a read mode and a write mode. - * - * compression state: - * The current state of the compression algorithm. - * - * cipher state: - * The current state of the encryption algorithm. This will consist of the - * scheduled key for that connection. For stream ciphers, this will also - * contain whatever state information is necessary to allow the stream to - * continue to encrypt or decrypt data. - * - * MAC key: - * The MAC key for the connection. - * - * sequence number: - * Each connection state contains a sequence number, which is maintained - * separately for read and write states. The sequence number MUST be set to - * zero whenever a connection state is made the active state. Sequence - * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do - * not wrap. If a TLS implementation would need to wrap a sequence number, - * it must renegotiate instead. A sequence number is incremented after each - * record: specifically, the first record transmitted under a particular - * connection state MUST use sequence number 0. - * - * @param c the connection. - * - * @return the new initialized TLS connection state. - */ -tls.createConnectionState = function(c) { - var client = (c.entity === tls.ConnectionEnd.client); + this.handle = handle; - var createMode = function() { - var mode = { - // two 32-bit numbers, first is most significant - sequenceNumber: [0, 0], - macKey: null, - macLength: 0, - macFunction: null, - cipherState: null, - cipherFunction: function(record) {return true;}, - compressionState: null, - compressFunction: function(record) {return true;}, - updateSequenceNumber: function() { - if(mode.sequenceNumber[1] === 0xFFFFFFFF) { - mode.sequenceNumber[1] = 0; - ++mode.sequenceNumber[0]; - } else { - ++mode.sequenceNumber[1]; - } + const tryAgain = (err) => { + if (err) { + // Try chmod() for sftp servers that may not support fchmod() for + // whatever reason + this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); + return; + } + + // SFTPv3 requires absolute offsets, no matter the open flag used + if (this.flags[0] === 'a') { + const tryStat = (err, st) => { + if (err) { + // Try stat() for sftp servers that may not support fstat() for + // whatever reason + this.sftp.stat(this.path, (err_, st_) => { + if (err_) { + this.destroy(); + this.emit('error', err); + return; + } + tryStat(null, st_); + }); + return; + } + + this.pos = st.size; + this.emit('open', handle); + this.emit('ready'); + }; + + this.sftp.fstat(handle, tryStat); + return; } + + this.emit('open', handle); + this.emit('ready'); }; - return mode; - }; - var state = { - read: createMode(), - write: createMode() - }; - // update function in read mode will decrypt then decompress a record - state.read.update = function(c, record) { - if(!state.read.cipherFunction(record, state.read)) { - c.error(c, { - message: 'Could not decrypt record or bad MAC.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - // doesn't matter if decryption failed or MAC was - // invalid, return the same error so as not to reveal - // which one occurred - description: tls.Alert.Description.bad_record_mac - } - }); - } else if(!state.read.compressFunction(c, record, state.read)) { - c.error(c, { - message: 'Could not decompress record.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decompression_failure - } - }); + this.sftp.fchmod(handle, this.mode, tryAgain); + }); +}; + +WriteStream.prototype._write = function(data, encoding, cb) { + if (!Buffer.isBuffer(data)) { + const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); + return this.emit('error', err); + } + + if (!Buffer.isBuffer(this.handle)) { + return this.once('open', function() { + this._write(data, encoding, cb); + }); + } + + this.sftp.write(this.handle, + data, + 0, + data.length, + this.pos, + (er, bytes) => { + if (er) { + if (this.autoClose) + this.destroy(); + return cb(er); } - return !c.fail; - }; + this.bytesWritten += bytes; + cb(); + }); - // update function in write mode will compress then encrypt a record - state.write.update = function(c, record) { - if(!state.write.compressFunction(c, record, state.write)) { - // error, but do not send alert since it would require - // compression as well - c.error(c, { - message: 'Could not compress record.', - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } else if(!state.write.cipherFunction(record, state.write)) { - // error, but do not send alert since it would require - // encryption as well - c.error(c, { - message: 'Could not encrypt record.', - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); + this.pos += data.length; +}; + +WriteStream.prototype._writev = function(data, cb) { + if (!Buffer.isBuffer(this.handle)) { + return this.once('open', function() { + this._writev(data, cb); + }); + } + + const sftp = this.sftp; + const handle = this.handle; + let writesLeft = data.length; + + const onwrite = (er, bytes) => { + if (er) { + this.destroy(); + return cb(er); } - return !c.fail; + this.bytesWritten += bytes; + if (--writesLeft === 0) + cb(); }; - // handle security parameters - if(c.session) { - var sp = c.session.sp; - c.session.cipherSuite.initSecurityParameters(sp); + // TODO: try to combine chunks to reduce number of requests to the server? + for (let i = 0; i < data.length; ++i) { + const chunk = data[i].chunk; - // generate keys - sp.keys = tls.generateKeys(c, sp); - state.read.macKey = client ? - sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; - state.write.macKey = client ? - sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; + sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); + this.pos += chunk.length; + } +}; - // cipher suite setup - c.session.cipherSuite.initConnectionState(state, c, sp); +if (typeof WritableStream.prototype.destroy !== 'function') + WriteStream.prototype.destroy = ReadStream.prototype.destroy; - // compression setup - switch(sp.compression_algorithm) { - case tls.CompressionMethod.none: - break; - case tls.CompressionMethod.deflate: - state.read.compressFunction = inflate; - state.write.compressFunction = deflate; - break; - default: - throw new Error('Unsupported compression algorithm.'); +WriteStream.prototype._destroy = ReadStream.prototype._destroy; +WriteStream.prototype.close = function(cb) { + if (cb) { + if (this.isClosed) { + process.nextTick(cb); + return; } + this.on('close', cb); } - return state; -}; + // If we are not autoClosing, we should call + // destroy on 'finish'. + if (!this.autoClose) + this.on('finish', this.destroy.bind(this)); + + this.end(); +}; + +// There is no shutdown() for files. +WriteStream.prototype.destroySoon = WriteStream.prototype.end; + +Object.defineProperty(WriteStream.prototype, 'pending', { + get() { + return this.handle === null; + }, + configurable: true +}); +// ============================================================================= + +module.exports = { + flagsToString, + OPEN_MODE, + SFTP, + Stats, + STATUS_CODE, + stringToFlags, +}; + + +/***/ }), + +/***/ 6832: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const crypto = __nccwpck_require__(6113); + +let cpuInfo; +try { + cpuInfo = __nccwpck_require__(4137)(); +} catch {} + +const { bindingAvailable, CIPHER_INFO, MAC_INFO } = __nccwpck_require__(5708); + +const eddsaSupported = (() => { + if (typeof crypto.sign === 'function' + && typeof crypto.verify === 'function') { + const key = + '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' + + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; + const data = Buffer.from('a'); + let sig; + let verified; + try { + sig = crypto.sign(null, data, key); + verified = crypto.verify(null, data, key, sig); + } catch {} + return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); + } + + return false; +})(); + +const curve25519Supported = (typeof crypto.diffieHellman === 'function' + && typeof crypto.generateKeyPairSync === 'function' + && typeof crypto.createPublicKey === 'function'); + +const DEFAULT_KEX = [ + // https://tools.ietf.org/html/rfc5656#section-10.1 + 'ecdh-sha2-nistp256', + 'ecdh-sha2-nistp384', + 'ecdh-sha2-nistp521', + + // https://tools.ietf.org/html/rfc4419#section-4 + 'diffie-hellman-group-exchange-sha256', + + // https://tools.ietf.org/html/rfc8268 + 'diffie-hellman-group14-sha256', + 'diffie-hellman-group15-sha512', + 'diffie-hellman-group16-sha512', + 'diffie-hellman-group17-sha512', + 'diffie-hellman-group18-sha512', +]; +if (curve25519Supported) { + DEFAULT_KEX.unshift('curve25519-sha256'); + DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); +} +const SUPPORTED_KEX = DEFAULT_KEX.concat([ + // https://tools.ietf.org/html/rfc4419#section-4 + 'diffie-hellman-group-exchange-sha1', + + 'diffie-hellman-group14-sha1', // REQUIRED + 'diffie-hellman-group1-sha1', // REQUIRED +]); + + +const DEFAULT_SERVER_HOST_KEY = [ + 'ecdsa-sha2-nistp256', + 'ecdsa-sha2-nistp384', + 'ecdsa-sha2-nistp521', + 'rsa-sha2-512', // RFC 8332 + 'rsa-sha2-256', // RFC 8332 + 'ssh-rsa', +]; +if (eddsaSupported) + DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); +const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ + 'ssh-dss', +]); + + +const canUseCipher = (() => { + const ciphers = crypto.getCiphers(); + return (name) => ciphers.includes(CIPHER_INFO[name].sslName); +})(); +let DEFAULT_CIPHER = [ + // http://tools.ietf.org/html/rfc5647 + 'aes128-gcm@openssh.com', + 'aes256-gcm@openssh.com', + + // http://tools.ietf.org/html/rfc4344#section-4 + 'aes128-ctr', + 'aes192-ctr', + 'aes256-ctr', +]; +if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { + // We know for sure the CPU does not support AES acceleration + if (bindingAvailable) + DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); + else + DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); +} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { + // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers + // seem to outperform it on x86, but it seems to be faster than CTR ciphers + DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); +} else { + DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); +} +DEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher); +const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ + 'aes256-cbc', + 'aes192-cbc', + 'aes128-cbc', + 'blowfish-cbc', + '3des-cbc', + 'aes128-gcm', + 'aes256-gcm', + + // http://tools.ietf.org/html/rfc4345#section-4: + 'arcfour256', + 'arcfour128', + + 'cast128-cbc', + 'arcfour', +].filter(canUseCipher)); + + +const canUseMAC = (() => { + const hashes = crypto.getHashes(); + return (name) => hashes.includes(MAC_INFO[name].sslName); +})(); +const DEFAULT_MAC = [ + 'hmac-sha2-256-etm@openssh.com', + 'hmac-sha2-512-etm@openssh.com', + 'hmac-sha1-etm@openssh.com', + 'hmac-sha2-256', + 'hmac-sha2-512', + 'hmac-sha1', +].filter(canUseMAC); +const SUPPORTED_MAC = DEFAULT_MAC.concat([ + 'hmac-md5', + 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 + 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 + 'hmac-ripemd160', + 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 + 'hmac-md5-96', // first 96 bits of HMAC-MD5 +].filter(canUseMAC)); + +const DEFAULT_COMPRESSION = [ + 'none', + 'zlib@openssh.com', // ZLIB (LZ77) compression, except + // compression/decompression does not start until after + // successful user authentication + 'zlib', // ZLIB (LZ77) compression +]; +const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ +]); + + +const COMPAT = { + BAD_DHGEX: 1 << 0, + OLD_EXIT: 1 << 1, + DYN_RPORT_BUG: 1 << 2, + BUG_DHGEX_LARGE: 1 << 3, + IMPLY_RSA_SHA2_SIGALGS: 1 << 4, +}; + +module.exports = { + MESSAGE: { + // Transport layer protocol -- generic (1-19) + DISCONNECT: 1, + IGNORE: 2, + UNIMPLEMENTED: 3, + DEBUG: 4, + SERVICE_REQUEST: 5, + SERVICE_ACCEPT: 6, + EXT_INFO: 7, // RFC 8308 + + // Transport layer protocol -- algorithm negotiation (20-29) + KEXINIT: 20, + NEWKEYS: 21, -/** - * Creates a Random structure. - * - * struct { - * uint32 gmt_unix_time; - * opaque random_bytes[28]; - * } Random; - * - * gmt_unix_time: - * The current time and date in standard UNIX 32-bit format (seconds since - * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according - * to the sender's internal clock. Clocks are not required to be set - * correctly by the basic TLS protocol; higher-level or application - * protocols may define additional requirements. Note that, for historical - * reasons, the data element is named using GMT, the predecessor of the - * current worldwide time base, UTC. - * random_bytes: - * 28 bytes generated by a secure random number generator. - * - * @return the Random structure as a byte array. - */ -tls.createRandom = function() { - // get UTC milliseconds - var d = new Date(); - var utc = +d + d.getTimezoneOffset() * 60000; - var rval = forge.util.createBuffer(); - rval.putInt32(utc); - rval.putBytes(forge.random.getBytes(28)); - return rval; -}; + // Transport layer protocol -- key exchange method-specific (30-49) + KEXDH_INIT: 30, + KEXDH_REPLY: 31, -/** - * Creates a TLS record with the given type and data. - * - * @param c the connection. - * @param options: - * type: the record type. - * data: the plain text data in a byte buffer. - * - * @return the created record. - */ -tls.createRecord = function(c, options) { - if(!options.data) { - return null; - } - var record = { - type: options.type, - version: { - major: c.version.major, - minor: c.version.minor - }, - length: options.data.length(), - fragment: options.data - }; - return record; -}; + KEXDH_GEX_GROUP: 31, + KEXDH_GEX_INIT: 32, + KEXDH_GEX_REPLY: 33, + KEXDH_GEX_REQUEST: 34, -/** - * Creates a TLS alert record. - * - * @param c the connection. - * @param alert: - * level: the TLS alert level. - * description: the TLS alert description. - * - * @return the created alert record. - */ -tls.createAlert = function(c, alert) { - var b = forge.util.createBuffer(); - b.putByte(alert.level); - b.putByte(alert.description); - return tls.createRecord(c, { - type: tls.ContentType.alert, - data: b - }); -}; + KEXECDH_INIT: 30, + KEXECDH_REPLY: 31, -/* The structure of a TLS handshake message. - * - * struct { - * HandshakeType msg_type; // handshake type - * uint24 length; // bytes in message - * select(HandshakeType) { - * case hello_request: HelloRequest; - * case client_hello: ClientHello; - * case server_hello: ServerHello; - * case certificate: Certificate; - * case server_key_exchange: ServerKeyExchange; - * case certificate_request: CertificateRequest; - * case server_hello_done: ServerHelloDone; - * case certificate_verify: CertificateVerify; - * case client_key_exchange: ClientKeyExchange; - * case finished: Finished; - * } body; - * } Handshake; - */ + // User auth protocol -- generic (50-59) + USERAUTH_REQUEST: 50, + USERAUTH_FAILURE: 51, + USERAUTH_SUCCESS: 52, + USERAUTH_BANNER: 53, -/** - * Creates a ClientHello message. - * - * opaque SessionID<0..32>; - * enum { null(0), deflate(1), (255) } CompressionMethod; - * uint8 CipherSuite[2]; - * - * struct { - * ProtocolVersion client_version; - * Random random; - * SessionID session_id; - * CipherSuite cipher_suites<2..2^16-2>; - * CompressionMethod compression_methods<1..2^8-1>; - * select(extensions_present) { - * case false: - * struct {}; - * case true: - * Extension extensions<0..2^16-1>; - * }; - * } ClientHello; - * - * The extension format for extended client hellos and server hellos is: - * - * struct { - * ExtensionType extension_type; - * opaque extension_data<0..2^16-1>; - * } Extension; - * - * Here: - * - * - "extension_type" identifies the particular extension type. - * - "extension_data" contains information specific to the particular - * extension type. - * - * The extension types defined in this document are: - * - * enum { - * server_name(0), max_fragment_length(1), - * client_certificate_url(2), trusted_ca_keys(3), - * truncated_hmac(4), status_request(5), (65535) - * } ExtensionType; - * - * @param c the connection. - * - * @return the ClientHello byte buffer. - */ -tls.createClientHello = function(c) { - // save hello version - c.session.clientHelloVersion = { - major: c.version.major, - minor: c.version.minor - }; + // User auth protocol -- user auth method-specific (60-79) + USERAUTH_PASSWD_CHANGEREQ: 60, - // create supported cipher suites - var cipherSuites = forge.util.createBuffer(); - for(var i = 0; i < c.cipherSuites.length; ++i) { - var cs = c.cipherSuites[i]; - cipherSuites.putByte(cs.id[0]); - cipherSuites.putByte(cs.id[1]); - } - var cSuites = cipherSuites.length(); + USERAUTH_PK_OK: 60, - // create supported compression methods, null always supported, but - // also support deflate if connection has inflate and deflate methods - var compressionMethods = forge.util.createBuffer(); - compressionMethods.putByte(tls.CompressionMethod.none); - // FIXME: deflate support disabled until issues with raw deflate data - // without zlib headers are resolved - /* - if(c.inflate !== null && c.deflate !== null) { - compressionMethods.putByte(tls.CompressionMethod.deflate); - } - */ - var cMethods = compressionMethods.length(); + USERAUTH_INFO_REQUEST: 60, + USERAUTH_INFO_RESPONSE: 61, - // create TLS SNI (server name indication) extension if virtual host - // has been specified, see RFC 3546 - var extensions = forge.util.createBuffer(); - if(c.virtualHost) { - // create extension struct - var ext = forge.util.createBuffer(); - ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes) - ext.putByte(0x00); + // Connection protocol -- generic (80-89) + GLOBAL_REQUEST: 80, + REQUEST_SUCCESS: 81, + REQUEST_FAILURE: 82, - /* In order to provide the server name, clients MAY include an - * extension of type "server_name" in the (extended) client hello. - * The "extension_data" field of this extension SHALL contain - * "ServerNameList" where: - * - * struct { - * NameType name_type; - * select(name_type) { - * case host_name: HostName; - * } name; - * } ServerName; - * - * enum { - * host_name(0), (255) - * } NameType; - * - * opaque HostName<1..2^16-1>; - * - * struct { - * ServerName server_name_list<1..2^16-1> - * } ServerNameList; - */ - var serverName = forge.util.createBuffer(); - serverName.putByte(0x00); // type host_name - writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); + // Connection protocol -- channel-related (90-127) + CHANNEL_OPEN: 90, + CHANNEL_OPEN_CONFIRMATION: 91, + CHANNEL_OPEN_FAILURE: 92, + CHANNEL_WINDOW_ADJUST: 93, + CHANNEL_DATA: 94, + CHANNEL_EXTENDED_DATA: 95, + CHANNEL_EOF: 96, + CHANNEL_CLOSE: 97, + CHANNEL_REQUEST: 98, + CHANNEL_SUCCESS: 99, + CHANNEL_FAILURE: 100 - // ServerNameList is in extension_data - var snList = forge.util.createBuffer(); - writeVector(snList, 2, serverName); - writeVector(ext, 2, snList); - extensions.putBuffer(ext); - } - var extLength = extensions.length(); - if(extLength > 0) { - // add extension vector length - extLength += 2; - } + // Reserved for client protocols (128-191) - // determine length of the handshake message - // cipher suites and compression methods size will need to be - // updated if more get added to the list - var sessionId = c.session.id; - var length = - sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + cSuites + // cipher suites vector - 1 + cMethods + // compression methods vector - extLength; // extensions vector + // Local extensions (192-155) + }, + DISCONNECT_REASON: { + HOST_NOT_ALLOWED_TO_CONNECT: 1, + PROTOCOL_ERROR: 2, + KEY_EXCHANGE_FAILED: 3, + RESERVED: 4, + MAC_ERROR: 5, + COMPRESSION_ERROR: 6, + SERVICE_NOT_AVAILABLE: 7, + PROTOCOL_VERSION_NOT_SUPPORTED: 8, + HOST_KEY_NOT_VERIFIABLE: 9, + CONNECTION_LOST: 10, + BY_APPLICATION: 11, + TOO_MANY_CONNECTIONS: 12, + AUTH_CANCELED_BY_USER: 13, + NO_MORE_AUTH_METHODS_AVAILABLE: 14, + ILLEGAL_USER_NAME: 15, + }, + DISCONNECT_REASON_STR: undefined, + CHANNEL_OPEN_FAILURE: { + ADMINISTRATIVELY_PROHIBITED: 1, + CONNECT_FAILED: 2, + UNKNOWN_CHANNEL_TYPE: 3, + RESOURCE_SHORTAGE: 4 + }, + TERMINAL_MODE: { + TTY_OP_END: 0, // Indicates end of options. + VINTR: 1, // Interrupt character; 255 if none. Similarly for the + // other characters. Not all of these characters are + // supported on all systems. + VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX + // systems). + VERASE: 3, // Erase the character to left of the cursor. + VKILL: 4, // Kill the current input line. + VEOF: 5, // End-of-file character (sends EOF from the + // terminal). + VEOL: 6, // End-of-line character in addition to carriage + // return and/or linefeed. + VEOL2: 7, // Additional end-of-line character. + VSTART: 8, // Continues paused output (normally control-Q). + VSTOP: 9, // Pauses output (normally control-S). + VSUSP: 10, // Suspends the current program. + VDSUSP: 11, // Another suspend character. + VREPRINT: 12, // Reprints the current input line. + VWERASE: 13, // Erases a word left of cursor. + VLNEXT: 14, // Enter the next character typed literally, even if + // it is a special character + VFLUSH: 15, // Character to flush output. + VSWTCH: 16, // Switch to a different shell layer. + VSTATUS: 17, // Prints system status line (load, command, pid, + // etc). + VDISCARD: 18, // Toggles the flushing of terminal output. + IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 + // if this flag is FALSE, and 1 if it is TRUE. + PARMRK: 31, // Mark parity and framing errors. + INPCK: 32, // Enable checking of parity errors. + ISTRIP: 33, // Strip 8th bit off characters. + INLCR: 34, // Map NL into CR on input. + IGNCR: 35, // Ignore CR on input. + ICRNL: 36, // Map CR to NL on input. + IUCLC: 37, // Translate uppercase characters to lowercase. + IXON: 38, // Enable output flow control. + IXANY: 39, // Any char will restart after stop. + IXOFF: 40, // Enable input flow control. + IMAXBEL: 41, // Ring bell on input queue full. + ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. + ICANON: 51, // Canonicalize input lines. + XCASE: 52, // Enable input and output of uppercase characters by + // preceding their lowercase equivalents with "\". + ECHO: 53, // Enable echoing. + ECHOE: 54, // Visually erase chars. + ECHOK: 55, // Kill character discards current line. + ECHONL: 56, // Echo NL even if ECHO is off. + NOFLSH: 57, // Don't flush after interrupt. + TOSTOP: 58, // Stop background jobs from output. + IEXTEN: 59, // Enable extensions. + ECHOCTL: 60, // Echo control characters as ^(Char). + ECHOKE: 61, // Visual erase for line kill. + PENDIN: 62, // Retype pending input. + OPOST: 70, // Enable output processing. + OLCUC: 71, // Convert lowercase to uppercase. + ONLCR: 72, // Map NL to CR-NL. + OCRNL: 73, // Translate carriage return to newline (output). + ONOCR: 74, // Translate newline to carriage return-newline + // (output). + ONLRET: 75, // Newline performs a carriage return (output). + CS7: 90, // 7 bit mode. + CS8: 91, // 8 bit mode. + PARENB: 92, // Parity enable. + PARODD: 93, // Odd parity, else even. + TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. + TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. + }, + CHANNEL_EXTENDED_DATATYPE: { + STDERR: 1, + }, - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_hello); - rval.putInt24(length); // handshake length - rval.putByte(c.version.major); // major version - rval.putByte(c.version.minor); // minor version - rval.putBytes(c.session.sp.client_random); // random time + bytes - writeVector(rval, 1, forge.util.createBuffer(sessionId)); - writeVector(rval, 2, cipherSuites); - writeVector(rval, 1, compressionMethods); - if(extLength > 0) { - writeVector(rval, 2, extensions); - } - return rval; -}; + SIGNALS: [ + 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', + 'USR2', 'KILL', 'PIPE' + ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), -/** - * Creates a ServerHello message. - * - * @param c the connection. - * - * @return the ServerHello byte buffer. - */ -tls.createServerHello = function(c) { - // determine length of the handshake message - var sessionId = c.session.id; - var length = - sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + // chosen cipher suite - 1; // chosen compression method + COMPAT, + COMPAT_CHECKS: [ + [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], + [ /^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE ], + [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations + [ /^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG ], + [ /^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS ], + ], - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello); - rval.putInt24(length); // handshake length - rval.putByte(c.version.major); // major version - rval.putByte(c.version.minor); // minor version - rval.putBytes(c.session.sp.server_random); // random time + bytes - writeVector(rval, 1, forge.util.createBuffer(sessionId)); - rval.putByte(c.session.cipherSuite.id[0]); - rval.putByte(c.session.cipherSuite.id[1]); - rval.putByte(c.session.compressionMethod); - return rval; + // KEX proposal-related + DEFAULT_KEX, + SUPPORTED_KEX, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY, + DEFAULT_CIPHER, + SUPPORTED_CIPHER, + DEFAULT_MAC, + SUPPORTED_MAC, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION, + + curve25519Supported, + eddsaSupported, }; -/** - * Creates a Certificate message. - * - * When this message will be sent: - * This is the first message the client can send after receiving a server - * hello done message and the first message the server can send after - * sending a ServerHello. This client message is only sent if the server - * requests a certificate. If no suitable certificate is available, the - * client should send a certificate message containing no certificates. If - * client authentication is required by the server for the handshake to - * continue, it may respond with a fatal handshake failure alert. - * - * opaque ASN.1Cert<1..2^24-1>; - * - * struct { - * ASN.1Cert certificate_list<0..2^24-1>; - * } Certificate; - * - * @param c the connection. - * - * @return the Certificate byte buffer. - */ -tls.createCertificate = function(c) { - // TODO: check certificate request to ensure types are supported +module.exports.DISCONNECT_REASON_BY_VALUE = + Array.from(Object.entries(module.exports.DISCONNECT_REASON)) + .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); - // get a certificate (a certificate as a PEM string) - var client = (c.entity === tls.ConnectionEnd.client); - var cert = null; - if(c.getCertificate) { - var hint; - if(client) { - hint = c.session.certificateRequest; - } else { - hint = c.session.extensions.server_name.serverNameList; - } - cert = c.getCertificate(c, hint); - } - // buffer to hold certificate list - var certList = forge.util.createBuffer(); - if(cert !== null) { - try { - // normalize cert to a chain of certificates - if(!forge.util.isArray(cert)) { - cert = [cert]; - } - var asn1 = null; - for(var i = 0; i < cert.length; ++i) { - var msg = forge.pem.decode(cert[i])[0]; - if(msg.type !== 'CERTIFICATE' && - msg.type !== 'X509 CERTIFICATE' && - msg.type !== 'TRUSTED CERTIFICATE') { - var error = new Error('Could not convert certificate from PEM; PEM ' + - 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' + - '"TRUSTED CERTIFICATE".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert certificate from PEM; PEM is encrypted.'); - } +/***/ }), - var der = forge.util.createBuffer(msg.body); - if(asn1 === null) { - asn1 = forge.asn1.fromDer(der.bytes(), false); - } +/***/ 5708: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // certificate entry is itself a vector with 3 length bytes - var certBuffer = forge.util.createBuffer(); - writeVector(certBuffer, 3, der); +"use strict"; +// TODO: +// * make max packet size configurable +// * if decompression is enabled, use `._packet` in decipher instances as +// input to (sync) zlib inflater with appropriate offset and length to +// avoid an additional copy of payload data before inflation +// * factor decompression status into packet length checks - // add cert vector to cert list vector - certList.putBuffer(certBuffer); - } - // save certificate - cert = forge.pki.certificateFromAsn1(asn1); - if(client) { - c.session.clientCertificate = cert; - } else { - c.session.serverCertificate = cert; - } - } catch(ex) { - return c.error(c, { - message: 'Could not send certificate list.', - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - } - }); - } - } +const { + createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual +} = __nccwpck_require__(6113); + +const { readUInt32BE, writeUInt32BE } = __nccwpck_require__(9475); - // determine length of the handshake message - var length = 3 + certList.length(); // cert list vector +const FastBuffer = Buffer[Symbol.species]; +const MAX_SEQNO = 2 ** 32 - 1; +const EMPTY_BUFFER = Buffer.alloc(0); +const BUF_INT = Buffer.alloc(4); +const DISCARD_CACHE = new Map(); +const MAX_PACKET_SIZE = 35000; - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate); - rval.putInt24(length); - writeVector(rval, 3, certList); - return rval; -}; +let binding; +let AESGCMCipher; +let ChaChaPolyCipher; +let GenericCipher; +let AESGCMDecipher; +let ChaChaPolyDecipher; +let GenericDecipher; +try { + binding = __nccwpck_require__(9041); + ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, + AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); +} catch {} -/** - * Creates a ClientKeyExchange message. - * - * When this message will be sent: - * This message is always sent by the client. It will immediately follow the - * client certificate message, if it is sent. Otherwise it will be the first - * message sent by the client after it receives the server hello done - * message. - * - * Meaning of this message: - * With this message, the premaster secret is set, either though direct - * transmission of the RSA-encrypted secret, or by the transmission of - * Diffie-Hellman parameters which will allow each side to agree upon the - * same premaster secret. When the key exchange method is DH_RSA or DH_DSS, - * client certification has been requested, and the client was able to - * respond with a certificate which contained a Diffie-Hellman public key - * whose parameters (group and generator) matched those specified by the - * server in its certificate, this message will not contain any data. - * - * Meaning of this message: - * If RSA is being used for key agreement and authentication, the client - * generates a 48-byte premaster secret, encrypts it using the public key - * from the server's certificate or the temporary RSA key provided in a - * server key exchange message, and sends the result in an encrypted - * premaster secret message. This structure is a variant of the client - * key exchange message, not a message in itself. - * - * struct { - * select(KeyExchangeAlgorithm) { - * case rsa: EncryptedPreMasterSecret; - * case diffie_hellman: ClientDiffieHellmanPublic; - * } exchange_keys; - * } ClientKeyExchange; - * - * struct { - * ProtocolVersion client_version; - * opaque random[46]; - * } PreMasterSecret; - * - * struct { - * public-key-encrypted PreMasterSecret pre_master_secret; - * } EncryptedPreMasterSecret; - * - * A public-key-encrypted element is encoded as a vector <0..2^16-1>. - * - * @param c the connection. - * - * @return the ClientKeyExchange byte buffer. - */ -tls.createClientKeyExchange = function(c) { - // create buffer to encrypt - var b = forge.util.createBuffer(); +const CIPHER_STREAM = 1 << 0; +const CIPHER_INFO = (() => { + function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { + return { + sslName, + blockLen, + keyLen, + ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) + ? ivLen + : blockLen), + authLen, + discardLen, + stream: !!(flags & CIPHER_STREAM), + }; + } - // add highest client-supported protocol to help server avoid version - // rollback attacks - b.putByte(c.session.clientHelloVersion.major); - b.putByte(c.session.clientHelloVersion.minor); + return { + 'chacha20-poly1305@openssh.com': + info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), - // generate and add 46 random bytes - b.putBytes(forge.random.getBytes(46)); + 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), + 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), + 'aes128-gcm@openssh.com': + info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), + 'aes256-gcm@openssh.com': + info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - // save pre-master secret - var sp = c.session.sp; - sp.pre_master_secret = b.getBytes(); + 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), + 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), + 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), + 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), + '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), + 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), + 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), + 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), - // RSA-encrypt the pre-master secret - var key = c.session.serverCertificate.publicKey; - b = key.encrypt(sp.pre_master_secret); + 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), + 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), + 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), + '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), + 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), + 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - /* Note: The encrypted pre-master secret will be stored in a - public-key-encrypted opaque vector that has the length prefixed using - 2 bytes, so include those 2 bytes in the handshake message length. This - is done as a minor optimization instead of calling writeVector(). */ + /* The "arcfour128" algorithm is the RC4 cipher, as described in + [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream + generated by the cipher MUST be discarded, and the first byte of the + first encrypted packet MUST be encrypted using the 1537th byte of + keystream. - // determine length of the handshake message - var length = b.length + 2; + -- http://tools.ietf.org/html/rfc4345#section-4 */ + 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), + 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), + 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), + 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), + }; +})(); - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_key_exchange); - rval.putInt24(length); - // add vector length bytes - rval.putInt16(b.length); - rval.putBytes(b); - return rval; -}; +const MAC_INFO = (() => { + function info(sslName, len, actualLen, isETM) { + return { + sslName, + len, + actualLen, + isETM, + }; + } -/** - * Creates a ServerKeyExchange message. - * - * @param c the connection. - * - * @return the ServerKeyExchange byte buffer. - */ -tls.createServerKeyExchange = function(c) { - // this implementation only supports RSA, no Diffie-Hellman support, - // so this record is empty + return { + 'hmac-md5': info('md5', 16, 16, false), + 'hmac-md5-96': info('md5', 16, 12, false), + 'hmac-ripemd160': info('ripemd160', 20, 20, false), + 'hmac-sha1': info('sha1', 20, 20, false), + 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), + 'hmac-sha1-96': info('sha1', 20, 12, false), + 'hmac-sha2-256': info('sha256', 32, 32, false), + 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), + 'hmac-sha2-256-96': info('sha256', 32, 12, false), + 'hmac-sha2-512': info('sha512', 64, 64, false), + 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), + 'hmac-sha2-512-96': info('sha512', 64, 12, false), + }; +})(); - // determine length of the handshake message - var length = 0; - // build record fragment - var rval = forge.util.createBuffer(); - if(length > 0) { - rval.putByte(tls.HandshakeType.server_key_exchange); - rval.putInt24(length); +// Should only_be used during the initial handshake +class NullCipher { + constructor(seqno, onWrite) { + this.outSeqno = seqno; + this._onWrite = onWrite; + this._dead = false; } - return rval; -}; + free() { + this._dead = true; + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - (pktLen & (8 - 1)); + if (padLen < 4) + padLen += 8; + pktLen += padLen; -/** - * Gets the signed data used to verify a client-side certificate. See - * tls.createCertificateVerify() for details. - * - * @param c the connection. - * @param callback the callback to call once the signed data is ready. - */ -tls.getClientSignature = function(c, callback) { - // generate data to RSA encrypt - var b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - b = b.getBytes(); + const packet = Buffer.allocUnsafe(pktLen); - // create default signing function as necessary - c.getSignature = c.getSignature || function(c, b, callback) { - // do rsa encryption, call callback - var privateKey = null; - if(c.getPrivateKey) { - try { - privateKey = c.getPrivateKey(c, c.session.clientCertificate); - privateKey = forge.pki.privateKeyFromPem(privateKey); - } catch(ex) { - c.error(c, { - message: 'Could not get private key.', - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - } - if(privateKey === null) { - c.error(c, { - message: 'No private key set.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } else { - b = privateKey.sign(b, null); - } - callback(c, b); - }; + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; - // get client signature - c.getSignature(c, b, callback); -}; + randomFillSync(packet, 5 + payloadLen, padLen); -/** - * Creates a CertificateVerify message. - * - * Meaning of this message: - * This structure conveys the client's Diffie-Hellman public value - * (Yc) if it was not already included in the client's certificate. - * The encoding used for Yc is determined by the enumerated - * PublicValueEncoding. This structure is a variant of the client - * key exchange message, not a message in itself. - * - * When this message will be sent: - * This message is used to provide explicit verification of a client - * certificate. This message is only sent following a client - * certificate that has signing capability (i.e. all certificates - * except those containing fixed Diffie-Hellman parameters). When - * sent, it will immediately follow the client key exchange message. - * - * struct { - * Signature signature; - * } CertificateVerify; - * - * CertificateVerify.signature.md5_hash - * MD5(handshake_messages); - * - * Certificate.signature.sha_hash - * SHA(handshake_messages); - * - * Here handshake_messages refers to all handshake messages sent or - * received starting at client hello up to but not including this - * message, including the type and length fields of the handshake - * messages. - * - * select(SignatureAlgorithm) { - * case anonymous: struct { }; - * case rsa: - * digitally-signed struct { - * opaque md5_hash[16]; - * opaque sha_hash[20]; - * }; - * case dsa: - * digitally-signed struct { - * opaque sha_hash[20]; - * }; - * } Signature; - * - * In digital signing, one-way hash functions are used as input for a - * signing algorithm. A digitally-signed element is encoded as an opaque - * vector <0..2^16-1>, where the length is specified by the signing - * algorithm and key. - * - * In RSA signing, a 36-byte structure of two hashes (one SHA and one - * MD5) is signed (encrypted with the private key). It is encoded with - * PKCS #1 block type 0 or type 1 as described in [PKCS1]. - * - * In DSS, the 20 bytes of the SHA hash are run directly through the - * Digital Signing Algorithm with no additional hashing. - * - * @param c the connection. - * @param signature the signature to include in the message. - * - * @return the CertificateVerify byte buffer. - */ -tls.createCertificateVerify = function(c, signature) { - /* Note: The signature will be stored in a "digitally-signed" opaque - vector that has the length prefixed using 2 bytes, so include those - 2 bytes in the handshake message length. This is done as a minor - optimization instead of calling writeVector(). */ + return packet; + } + encrypt(packet) { + // `packet` === unencrypted packet - // determine length of the handshake message - var length = signature.length + 2; + if (this._dead) + return; - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_verify); - rval.putInt24(length); - // add vector length bytes - rval.putInt16(signature.length); - rval.putBytes(signature); - return rval; -}; + this._onWrite(packet); -/** - * Creates a CertificateRequest message. - * - * @param c the connection. - * - * @return the CertificateRequest byte buffer. - */ -tls.createCertificateRequest = function(c) { - // TODO: support other certificate types - var certTypes = forge.util.createBuffer(); + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} - // common RSA certificate type - certTypes.putByte(0x01); - // add distinguished names from CA store - var cAs = forge.util.createBuffer(); - for(var key in c.caStore.certs) { - var cert = c.caStore.certs[key]; - var dn = forge.pki.distinguishedNameToAsn1(cert.subject); - var byteBuffer = forge.asn1.toDer(dn); - cAs.putInt16(byteBuffer.length()); - cAs.putBuffer(byteBuffer); +const POLY1305_ZEROS = Buffer.alloc(32); +const POLY1305_OUT_COMPUTE = Buffer.alloc(16); +let POLY1305_WASM_MODULE; +let POLY1305_RESULT_MALLOC; +let poly1305_auth; +class ChaChaPolyCipherNative { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encKeyMain = enc.cipherKey.slice(0, 32); + this._encKeyPktLen = enc.cipherKey.slice(32); + this._dead = false; + } + free() { + this._dead = true; } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - ((pktLen - 4) & (8 - 1)); + if (padLen < 4) + padLen += 8; + pktLen += padLen; - // TODO: TLS 1.2+ has a different format + const packet = Buffer.allocUnsafe(pktLen); - // determine length of the handshake message - var length = - 1 + certTypes.length() + - 2 + cAs.length(); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_request); - rval.putInt24(length); - writeVector(rval, 1, certTypes); - writeVector(rval, 2, cAs); - return rval; -}; + randomFillSync(packet, 5 + payloadLen, padLen); -/** - * Creates a ServerHelloDone message. - * - * @param c the connection. - * - * @return the ServerHelloDone byte buffer. - */ -tls.createServerHelloDone = function(c) { - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello_done); - rval.putInt24(0); - return rval; -}; + return packet; + } + encrypt(packet) { + // `packet` === unencrypted packet -/** - * Creates a ChangeCipherSpec message. - * - * The change cipher spec protocol exists to signal transitions in - * ciphering strategies. The protocol consists of a single message, - * which is encrypted and compressed under the current (not the pending) - * connection state. The message consists of a single byte of value 1. - * - * struct { - * enum { change_cipher_spec(1), (255) } type; - * } ChangeCipherSpec; - * - * @return the ChangeCipherSpec byte buffer. - */ -tls.createChangeCipherSpec = function() { - var rval = forge.util.createBuffer(); - rval.putByte(0x01); - return rval; -}; + if (this._dead) + return; -/** - * Creates a Finished message. - * - * struct { - * opaque verify_data[12]; - * } Finished; - * - * verify_data - * PRF(master_secret, finished_label, MD5(handshake_messages) + - * SHA-1(handshake_messages)) [0..11]; - * - * finished_label - * For Finished messages sent by the client, the string "client - * finished". For Finished messages sent by the server, the - * string "server finished". - * - * handshake_messages - * All of the data from all handshake messages up to but not - * including this message. This is only data visible at the - * handshake layer and does not include record layer headers. - * This is the concatenation of all the Handshake structures as - * defined in 7.4 exchanged thus far. - * - * @param c the connection. - * - * @return the Finished byte buffer. - */ -tls.createFinished = function(c) { - // generate verify_data - var b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); + // Generate Poly1305 key + POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) + writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); + const polyKey = + createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) + .update(POLY1305_ZEROS); - // TODO: determine prf function and verify length for TLS 1.2 - var client = (c.entity === tls.ConnectionEnd.client); - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - var label = client ? 'client finished' : 'server finished'; - b = prf(sp.master_secret, label, b.getBytes(), vdl); + // Encrypt packet length + const pktLenEnc = + createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) + .update(packet.slice(0, 4)); + this._onWrite(pktLenEnc); - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.finished); - rval.putInt24(b.length()); - rval.putBuffer(b); - return rval; -}; + // Encrypt rest of packet + POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) + const payloadEnc = + createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) + .update(packet.slice(4)); + this._onWrite(payloadEnc); -/** - * Creates a HeartbeatMessage (See RFC 6520). - * - * struct { - * HeartbeatMessageType type; - * uint16 payload_length; - * opaque payload[HeartbeatMessage.payload_length]; - * opaque padding[padding_length]; - * } HeartbeatMessage; - * - * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or - * max_fragment_length when negotiated as defined in [RFC6066]. - * - * type: The message type, either heartbeat_request or heartbeat_response. - * - * payload_length: The length of the payload. - * - * payload: The payload consists of arbitrary content. - * - * padding: The padding is random content that MUST be ignored by the - * receiver. The length of a HeartbeatMessage is TLSPlaintext.length - * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the - * length of the type field is 1 byte, and the length of the - * payload_length is 2. Therefore, the padding_length is - * TLSPlaintext.length - payload_length - 3 for TLS and - * DTLSPlaintext.length - payload_length - 3 for DTLS. The - * padding_length MUST be at least 16. - * - * The sender of a HeartbeatMessage MUST use a random padding of at - * least 16 bytes. The padding of a received HeartbeatMessage message - * MUST be ignored. - * - * If the payload_length of a received HeartbeatMessage is too large, - * the received HeartbeatMessage MUST be discarded silently. - * - * @param c the connection. - * @param type the tls.HeartbeatMessageType. - * @param payload the heartbeat data to send as the payload. - * @param [payloadLength] the payload length to use, defaults to the - * actual payload length. - * - * @return the HeartbeatRequest byte buffer. - */ -tls.createHeartbeat = function(type, payload, payloadLength) { - if(typeof payloadLength === 'undefined') { - payloadLength = payload.length; - } - // build record fragment - var rval = forge.util.createBuffer(); - rval.putByte(type); // heartbeat message type - rval.putInt16(payloadLength); // payload length - rval.putBytes(payload); // payload - // padding - var plaintextLength = rval.length(); - var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); - rval.putBytes(forge.random.getBytes(paddingLength)); - return rval; -}; + // Calculate Poly1305 MAC + poly1305_auth(POLY1305_RESULT_MALLOC, + pktLenEnc, + pktLenEnc.length, + payloadEnc, + payloadEnc.length, + polyKey); + const mac = Buffer.allocUnsafe(16); + mac.set( + new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, + POLY1305_RESULT_MALLOC, + 16), + 0 + ); + this._onWrite(mac); -/** - * Fragments, compresses, encrypts, and queues a record for delivery. - * - * @param c the connection. - * @param record the record to queue. - */ -tls.queue = function(c, record) { - // error during record creation - if(!record) { - return; + this.outSeqno = (this.outSeqno + 1) >>> 0; } +} - if(record.fragment.length() === 0) { - if(record.type === tls.ContentType.handshake || - record.type === tls.ContentType.alert || - record.type === tls.ContentType.change_cipher_spec) { - // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent. - return; - } +class ChaChaPolyCipherBinding { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._instance = new ChaChaPolyCipher(enc.cipherKey); + this._dead = false; + } + free() { + this._dead = true; + this._instance.free(); } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - ((pktLen - 4) & (8 - 1)); + if (padLen < 4) + padLen += 8; + pktLen += padLen; - // if the record is a handshake record, update handshake hashes - if(record.type === tls.ContentType.handshake) { - var bytes = record.fragment.bytes(); - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - bytes = null; + const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); + + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + + randomFillSync(packet, 5 + payloadLen, padLen); + + return packet; } + encrypt(packet) { + // `packet` === unencrypted packet - // handle record fragmentation - var records; - if(record.fragment.length() <= tls.MaxFragment) { - records = [record]; - } else { - // fragment data as long as it is too long - records = []; - var data = record.fragment.bytes(); - while(data.length > tls.MaxFragment) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) - })); - data = data.slice(tls.MaxFragment); - } - // add last record - if(data.length > 0) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge.util.createBuffer(data) - })); - } + if (this._dead) + return; + + // Encrypts in-place + this._instance.encrypt(packet, this.outSeqno); + + this._onWrite(packet); + + this.outSeqno = (this.outSeqno + 1) >>> 0; } +} - // compress and encrypt all fragmented records - for(var i = 0; i < records.length && !c.fail; ++i) { - // update the record using current write state - var rec = records[i]; - var s = c.state.current.write; - if(s.update(c, rec)) { - // store record - c.records.push(rec); - } + +class AESGCMCipherNative { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encSSLName = enc.cipherInfo.sslName; + this._encKey = enc.cipherKey; + this._encIV = enc.cipherIV; + this._dead = false; } -}; + free() { + this._dead = true; + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 16 - ((pktLen - 4) & (16 - 1)); + if (padLen < 4) + padLen += 16; + pktLen += padLen; -/** - * Flushes all queued records to the output buffer and calls the - * tlsDataReady() handler on the given connection. - * - * @param c the connection. - * - * @return true on success, false on failure. - */ -tls.flush = function(c) { - for(var i = 0; i < c.records.length; ++i) { - var record = c.records[i]; + const packet = Buffer.allocUnsafe(pktLen); - // add record header and fragment - c.tlsData.putByte(record.type); - c.tlsData.putByte(record.version.major); - c.tlsData.putByte(record.version.minor); - c.tlsData.putInt16(record.fragment.length()); - c.tlsData.putBuffer(c.records[i].fragment); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + + randomFillSync(packet, 5 + payloadLen, padLen); + + return packet; } - c.records = []; - return c.tlsDataReady(c); -}; + encrypt(packet) { + // `packet` === unencrypted packet -/** - * Maps a pki.certificateError to a tls.Alert.Description. - * - * @param error the error to map. - * - * @return the alert description. - */ -var _certErrorToAlertDesc = function(error) { - switch(error) { - case true: - return true; - case forge.pki.certificateError.bad_certificate: - return tls.Alert.Description.bad_certificate; - case forge.pki.certificateError.unsupported_certificate: - return tls.Alert.Description.unsupported_certificate; - case forge.pki.certificateError.certificate_revoked: - return tls.Alert.Description.certificate_revoked; - case forge.pki.certificateError.certificate_expired: - return tls.Alert.Description.certificate_expired; - case forge.pki.certificateError.certificate_unknown: - return tls.Alert.Description.certificate_unknown; - case forge.pki.certificateError.unknown_ca: - return tls.Alert.Description.unknown_ca; - default: - return tls.Alert.Description.bad_certificate; + if (this._dead) + return; + + const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); + cipher.setAutoPadding(false); + + const lenData = packet.slice(0, 4); + cipher.setAAD(lenData); + this._onWrite(lenData); + + // Encrypt pad length, payload, and padding + const encrypted = cipher.update(packet.slice(4)); + this._onWrite(encrypted); + const final = cipher.final(); + // XXX: final.length === 0 always? + if (final.length) + this._onWrite(final); + + // Generate MAC + const tag = cipher.getAuthTag(); + this._onWrite(tag); + + // Increment counter in IV by 1 for next packet + ivIncrement(this._encIV); + + this.outSeqno = (this.outSeqno + 1) >>> 0; } -}; +} -/** - * Maps a tls.Alert.Description to a pki.certificateError. - * - * @param desc the alert description. - * - * @return the certificate error. - */ -var _alertDescToCertError = function(desc) { - switch(desc) { - case true: - return true; - case tls.Alert.Description.bad_certificate: - return forge.pki.certificateError.bad_certificate; - case tls.Alert.Description.unsupported_certificate: - return forge.pki.certificateError.unsupported_certificate; - case tls.Alert.Description.certificate_revoked: - return forge.pki.certificateError.certificate_revoked; - case tls.Alert.Description.certificate_expired: - return forge.pki.certificateError.certificate_expired; - case tls.Alert.Description.certificate_unknown: - return forge.pki.certificateError.certificate_unknown; - case tls.Alert.Description.unknown_ca: - return forge.pki.certificateError.unknown_ca; - default: - return forge.pki.certificateError.bad_certificate; +class AESGCMCipherBinding { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._instance = new AESGCMCipher(enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV); + this._dead = false; } -}; + free() { + this._dead = true; + this._instance.free(); + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 16 - ((pktLen - 4) & (16 - 1)); + if (padLen < 4) + padLen += 16; + pktLen += padLen; -/** - * Verifies a certificate chain against the given connection's - * Certificate Authority store. - * - * @param c the TLS connection. - * @param chain the certificate chain to verify, with the root or highest - * authority at the end. - * - * @return true if successful, false if not. - */ -tls.verifyCertificateChain = function(c, chain) { - try { - // Make a copy of c.verifyOptions so that we can modify options.verify - // without modifying c.verifyOptions. - var options = {}; - for (var key in c.verifyOptions) { - options[key] = c.verifyOptions[key]; - } + const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); - options.verify = function(vfd, depth, chain) { - // convert pki.certificateError to tls alert description - var desc = _certErrorToAlertDesc(vfd); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; - // call application callback - var ret = c.verify(c, vfd, depth, chain); - if(ret !== true) { - if(typeof ret === 'object' && !forge.util.isArray(ret)) { - // throw custom error - var error = new Error('The application rejected the certificate.'); - error.send = true; - error.alert = { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - }; - if(ret.message) { - error.message = ret.message; - } - if(ret.alert) { - error.alert.description = ret.alert; - } - throw error; - } + randomFillSync(packet, 5 + payloadLen, padLen); - // convert tls alert description to pki.certificateError - if(ret !== vfd) { - ret = _alertDescToCertError(ret); - } - } + return packet; + } + encrypt(packet) { + // `packet` === unencrypted packet - return ret; - }; + if (this._dead) + return; - // verify chain - forge.pki.verifyCertificateChain(c.caStore, chain, options); - } catch(ex) { - // build tls error if not already customized - var err = ex; - if(typeof err !== 'object' || forge.util.isArray(err)) { - err = { - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(ex) - } - }; - } - if(!('send' in err)) { - err.send = true; - } - if(!('alert' in err)) { - err.alert = { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(err.error) - }; - } + // Encrypts in-place + this._instance.encrypt(packet); - // send error - c.error(c, err); - } + this._onWrite(packet); - return !c.fail; -}; + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} -/** - * Creates a new TLS session cache. - * - * @param cache optional map of session ID to cached session. - * @param capacity the maximum size for the cache (default: 100). - * - * @return the new TLS session cache. - */ -tls.createSessionCache = function(cache, capacity) { - var rval = null; - // assume input is already a session cache object - if(cache && cache.getSession && cache.setSession && cache.order) { - rval = cache; - } else { - // create cache - rval = {}; - rval.cache = cache || {}; - rval.capacity = Math.max(capacity || 100, 1); - rval.order = []; +class GenericCipherNative { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encBlockLen = enc.cipherInfo.blockLen; + this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV); + this._macSSLName = enc.macInfo.sslName; + this._macKey = enc.macKey; + this._macActualLen = enc.macInfo.actualLen; + this._macETM = enc.macInfo.isETM; + this._aadLen = (this._macETM ? 4 : 0); + this._dead = false; - // store order for sessions, delete session overflow - for(var key in cache) { - if(rval.order.length <= capacity) { - rval.order.push(key); - } else { - delete cache[key]; + const discardLen = enc.cipherInfo.discardLen; + if (discardLen) { + let discard = DISCARD_CACHE.get(discardLen); + if (discard === undefined) { + discard = Buffer.alloc(discardLen); + DISCARD_CACHE.set(discardLen, discard); } + this._cipherInstance.update(discard); } + } + free() { + this._dead = true; + } + allocPacket(payloadLen) { + const blockLen = this._encBlockLen; - // get a session from a session ID (or get any session) - rval.getSession = function(sessionId) { - var session = null; - var key = null; + let pktLen = 4 + 1 + payloadLen; + let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); + if (padLen < 4) + padLen += blockLen; + pktLen += padLen; - // if session ID provided, use it - if(sessionId) { - key = forge.util.bytesToHex(sessionId); - } else if(rval.order.length > 0) { - // get first session from cache - key = rval.order[0]; - } + const packet = Buffer.allocUnsafe(pktLen); - if(key !== null && key in rval.cache) { - // get cached session and remove from cache - session = rval.cache[key]; - delete rval.cache[key]; - for(var i in rval.order) { - if(rval.order[i] === key) { - rval.order.splice(i, 1); - break; - } - } - } + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; - return session; - }; + randomFillSync(packet, 5 + payloadLen, padLen); - // set a session in the cache - rval.setSession = function(sessionId, session) { - // remove session from cache if at capacity - if(rval.order.length === rval.capacity) { - var key = rval.order.shift(); - delete rval.cache[key]; - } - // add session to cache - var key = forge.util.bytesToHex(sessionId); - rval.order.push(key); - rval.cache[key] = session; - }; + return packet; } + encrypt(packet) { + // `packet` === unencrypted packet - return rval; -}; + if (this._dead) + return; -/** - * Creates a new TLS connection. - * - * See public createConnection() docs for more details. - * - * @param options the options for this connection. - * - * @return the new TLS connection. - */ -tls.createConnection = function(options) { - var caStore = null; - if(options.caStore) { - // if CA store is an array, convert it to a CA store object - if(forge.util.isArray(options.caStore)) { - caStore = forge.pki.createCaStore(options.caStore); + let mac; + if (this._macETM) { + // Encrypt pad length, payload, and padding + const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); + const encrypted = this._cipherInstance.update( + new Uint8Array(packet.buffer, + packet.byteOffset + 4, + packet.length - 4) + ); + + this._onWrite(lenBytes); + this._onWrite(encrypted); + + // TODO: look into storing seqno as 4-byte buffer and incrementing like we + // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time + mac = createHmac(this._macSSLName, this._macKey); + writeUInt32BE(BUF_INT, this.outSeqno, 0); + mac.update(BUF_INT); + mac.update(lenBytes); + mac.update(encrypted); } else { - caStore = options.caStore; + // Encrypt length field, pad length, payload, and padding + const encrypted = this._cipherInstance.update(packet); + this._onWrite(encrypted); + + // TODO: look into storing seqno as 4-byte buffer and incrementing like we + // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time + mac = createHmac(this._macSSLName, this._macKey); + writeUInt32BE(BUF_INT, this.outSeqno, 0); + mac.update(BUF_INT); + mac.update(packet); } - } else { - // create empty CA store - caStore = forge.pki.createCaStore(); + + let digest = mac.digest(); + if (digest.length > this._macActualLen) + digest = digest.slice(0, this._macActualLen); + this._onWrite(digest); + + this.outSeqno = (this.outSeqno + 1) >>> 0; } +} - // setup default cipher suites - var cipherSuites = options.cipherSuites || null; - if(cipherSuites === null) { - cipherSuites = []; - for(var key in tls.CipherSuites) { - cipherSuites.push(tls.CipherSuites[key]); - } +class GenericCipherBinding { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encBlockLen = enc.cipherInfo.blockLen; + this._macLen = enc.macInfo.len; + this._macActualLen = enc.macInfo.actualLen; + this._aadLen = (enc.macInfo.isETM ? 4 : 0); + this._instance = new GenericCipher(enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV, + enc.macInfo.sslName, + enc.macKey, + enc.macInfo.isETM); + this._dead = false; } + free() { + this._dead = true; + this._instance.free(); + } + allocPacket(payloadLen) { + const blockLen = this._encBlockLen; - // set default entity - var entity = (options.server || false) ? - tls.ConnectionEnd.server : tls.ConnectionEnd.client; + let pktLen = 4 + 1 + payloadLen; + let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); + if (padLen < 4) + padLen += blockLen; + pktLen += padLen; - // create session cache if requested - var sessionCache = options.sessionCache ? - tls.createSessionCache(options.sessionCache) : null; + const packet = Buffer.allocUnsafe(pktLen + this._macLen); - // create TLS connection - var c = { - version: {major: tls.Version.major, minor: tls.Version.minor}, - entity: entity, - sessionId: options.sessionId, - caStore: caStore, - sessionCache: sessionCache, - cipherSuites: cipherSuites, - connected: options.connected, - virtualHost: options.virtualHost || null, - verifyClient: options.verifyClient || false, - verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;}, - verifyOptions: options.verifyOptions || {}, - getCertificate: options.getCertificate || null, - getPrivateKey: options.getPrivateKey || null, - getSignature: options.getSignature || null, - input: forge.util.createBuffer(), - tlsData: forge.util.createBuffer(), - data: forge.util.createBuffer(), - tlsDataReady: options.tlsDataReady, - dataReady: options.dataReady, - heartbeatReceived: options.heartbeatReceived, - closed: options.closed, - error: function(c, ex) { - // set origin if not set - ex.origin = ex.origin || - ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server'); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; - // send TLS alert - if(ex.send) { - tls.queue(c, tls.createAlert(c, ex.alert)); - tls.flush(c); - } + randomFillSync(packet, 5 + payloadLen, padLen); - // error is fatal by default - var fatal = (ex.fatal !== false); - if(fatal) { - // set fail flag - c.fail = true; - } + return packet; + } + encrypt(packet) { + // `packet` === unencrypted packet - // call error handler first - options.error(c, ex); + if (this._dead) + return; - if(fatal) { - // fatal error, close connection, do not clear fail - c.close(false); - } - }, - deflate: options.deflate || null, - inflate: options.inflate || null - }; + // Encrypts in-place + this._instance.encrypt(packet, this.outSeqno); - /** - * Resets a closed TLS connection for reuse. Called in c.close(). - * - * @param clearFail true to clear the fail flag (default: true). - */ - c.reset = function(clearFail) { - c.version = {major: tls.Version.major, minor: tls.Version.minor}; - c.record = null; - c.session = null; - c.peerCertificate = null; - c.state = { - pending: null, - current: null - }; - c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE; - c.fragmented = null; - c.records = []; - c.open = false; - c.handshakes = 0; - c.handshaking = false; - c.isConnected = false; - c.fail = !(clearFail || typeof(clearFail) === 'undefined'); - c.input.clear(); - c.tlsData.clear(); - c.data.clear(); - c.state.current = tls.createConnectionState(c); - }; + if (this._macActualLen < this._macLen) { + packet = new FastBuffer(packet.buffer, + packet.byteOffset, + (packet.length + - (this._macLen - this._macActualLen))); + } + this._onWrite(packet); - // do initial reset of connection - c.reset(); + this.outSeqno = (this.outSeqno + 1) >>> 0; + } +} - /** - * Updates the current TLS engine state based on the given record. - * - * @param c the TLS connection. - * @param record the TLS record to act on. - */ - var _update = function(c, record) { - // get record handler (align type in table by subtracting lowest) - var aligned = record.type - tls.ContentType.change_cipher_spec; - var handlers = ctTable[c.entity][c.expect]; - if(aligned in handlers) { - handlers[aligned](c, record); - } else { - // unexpected record - tls.handleUnexpected(c, record); - } - }; - /** - * Reads the record header and initializes the next record on the given - * connection. - * - * @param c the TLS connection with the next record. - * - * @return 0 if the input data could be processed, otherwise the - * number of bytes required for data to be processed. - */ - var _readRecordHeader = function(c) { - var rval = 0; +class NullDecipher { + constructor(seqno, onPayload) { + this.inSeqno = seqno; + this._onPayload = onPayload; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + } + free() {} + decrypt(data, p, dataLen) { + while (p < dataLen) { + // Read packet length + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); - // get input buffer and its length - var b = c.input; - var len = b.length(); + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; - // need at least 5 bytes to initialize a record - if(len < 5) { - rval = 5 - len; - } else { - // enough bytes for header - // initialize record - c.record = { - type: b.getByte(), - version: { - major: b.getByte(), - minor: b.getByte() - }, - length: b.getInt16(), - fragment: forge.util.createBuffer(), - ready: false - }; + if (this._lenBytes < 4) + return; - // check record version - var compatibleVersion = (c.record.version.major === c.version.major); - if(compatibleVersion && c.session && c.session.version) { - // session version already set, require same minor version - compatibleVersion = (c.record.version.minor === c.version.minor); - } - if(!compatibleVersion) { - c.error(c, { - message: 'Incompatible TLS version.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); + if (this._len > MAX_PACKET_SIZE + || this._len < 8 + || (4 + this._len & 7) !== 0) { + throw new Error('Bad packet length'); + } + if (p >= dataLen) + return; } - } - - return rval; - }; - /** - * Reads the next record's contents and appends its message to any - * previously fragmented message. - * - * @param c the TLS connection with the next record. - * - * @return 0 if the input data could be processed, otherwise the - * number of bytes required for data to be processed. - */ - var _readRecord = function(c) { - var rval = 0; + // Read padding length, payload, and padding + if (this._packetPos < this._len) { + const nb = Math.min(this._len - this._packetPos, dataLen - p); + let chunk; + if (p !== 0 || nb !== dataLen) + chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + chunk = data; + if (nb === this._len) { + this._packet = chunk; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(chunk, this._packetPos); + } + p += nb; + this._packetPos += nb; + if (this._packetPos < this._len) + return; + } - // ensure there is enough input data to get the entire record - var b = c.input; - var len = b.length(); - if(len < c.record.length) { - // not enough data yet, return how much is required - rval = c.record.length - len; - } else { - // there is enough data to parse the pending record - // fill record fragment and compact input buffer - c.record.fragment.putBytes(b.getBytes(c.record.length)); - b.compact(); + const payload = (!this._packet + ? EMPTY_BUFFER + : new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length + - this._packet[0] - 1)); - // update record using current read state - var s = c.state.current.read; - if(s.update(c, c.record)) { - // see if there is a previously fragmented message that the - // new record's message fragment should be appended to - if(c.fragmented !== null) { - // if the record type matches a previously fragmented - // record, append the record fragment to it - if(c.fragmented.type === c.record.type) { - // concatenate record fragments - c.fragmented.fragment.putBuffer(c.record.fragment); - c.record = c.fragmented; - } else { - // error, invalid fragmented record - c.error(c, { - message: 'Invalid fragmented record.', - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: - tls.Alert.Description.unexpected_message - } - }); - } - } + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; - // record is now ready - c.record.ready = true; + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); } } + } +} - return rval; - }; +class ChaChaPolyDecipherNative { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decKeyMain = dec.decipherKey.slice(0, 32); + this._decKeyPktLen = dec.decipherKey.slice(32); + this._len = 0; + this._lenBuf = Buffer.alloc(4); + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(16); + this._calcMac = Buffer.allocUnsafe(16); + this._macPos = 0; + } + free() {} + decrypt(data, p, dataLen) { + // `data` === encrypted data - /** - * Performs a handshake using the TLS Handshake Protocol, as a client. - * - * This method should only be called if the connection is in client mode. - * - * @param sessionId the session ID to use, null to start a new one. - */ - c.handshake = function(sessionId) { - // error to call this in non-client mode - if(c.entity !== tls.ConnectionEnd.client) { - // not fatal error - c.error(c, { - message: 'Cannot initiate handshake as a server.', - fatal: false - }); - } else if(c.handshaking) { - // handshake is already in progress, fail but not fatal error - c.error(c, { - message: 'Handshake already in progress.', - fatal: false - }); - } else { - // clear fail flag on reuse - if(c.fail && !c.open && c.handshakes === 0) { - c.fail = false; - } + while (p < dataLen) { + // Read packet length + if (this._lenPos < 4) { + let nb = Math.min(4 - this._lenPos, dataLen - p); + while (nb--) + this._lenBuf[this._lenPos++] = data[p++]; + if (this._lenPos < 4) + return; - // now handshaking - c.handshaking = true; + POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) + writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - // default to blank (new session) - sessionId = sessionId || ''; + const decLenBytes = + createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) + .update(this._lenBuf); + this._len = readUInt32BE(decLenBytes, 0); - // if a session ID was specified, try to find it in the cache - var session = null; - if(sessionId.length > 0) { - if(c.sessionCache) { - session = c.sessionCache.getSession(sessionId); + if (this._len > MAX_PACKET_SIZE + || this._len < 8 + || (this._len & 7) !== 0) { + throw new Error('Bad packet length'); } + } - // matching session not found in cache, clear session ID - if(session === null) { - sessionId = ''; + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } + + // Read Poly1305 MAC + { + const nb = Math.min(16 - this._macPos, dataLen - p); + // TODO: avoid copying if entire MAC is in current chunk + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); } + p += nb; + this._macPos += nb; + if (this._macPos < 16) + return; } - // no session given, grab a session from the cache, if available - if(sessionId.length === 0 && c.sessionCache) { - session = c.sessionCache.getSession(); - if(session !== null) { - sessionId = session.id; - } - } + // Generate Poly1305 key + POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) + writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); + const polyKey = + createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) + .update(POLY1305_ZEROS); - // set up session - c.session = { - id: sessionId, - version: null, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - certificateRequest: null, - clientCertificate: null, - sp: {}, - md5: forge.md.md5.create(), - sha1: forge.md.sha1.create() - }; + // Calculate and compare Poly1305 MACs + poly1305_auth(POLY1305_RESULT_MALLOC, + this._lenBuf, + 4, + this._packet, + this._packet.length, + polyKey); - // use existing session information - if(session) { - // only update version on connection, session version not yet set - c.version = session.version; - c.session.sp = session.sp; - } + this._calcMac.set( + new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, + POLY1305_RESULT_MALLOC, + 16), + 0 + ); + if (!timingSafeEqual(this._calcMac, this._mac)) + throw new Error('Invalid MAC'); - // generate new client random - c.session.sp.client_random = tls.createRandom().getBytes(); + // Decrypt packet + POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) + const packet = + createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) + .update(this._packet); - // connection now open - c.open = true; + const payload = new FastBuffer(packet.buffer, + packet.byteOffset + 1, + packet.length - packet[0] - 1); - // send hello - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientHello(c) - })); - tls.flush(c); + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._len = 0; + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; + + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } } - }; + } +} - /** - * Called when TLS protocol data has been received from somewhere and should - * be processed by the TLS engine. - * - * @param data the TLS protocol data, as a string, to process. - * - * @return 0 if the data could be processed, otherwise the number of bytes - * required for data to be processed. - */ - c.process = function(data) { - var rval = 0; +class ChaChaPolyDecipherBinding { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new ChaChaPolyDecipher(dec.decipherKey); + this._len = 0; + this._lenBuf = Buffer.alloc(4); + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(16); + this._macPos = 0; + } + free() { + this._instance.free(); + } + decrypt(data, p, dataLen) { + // `data` === encrypted data - // buffer input data - if(data) { - c.input.putBytes(data); - } + while (p < dataLen) { + // Read packet length + if (this._lenPos < 4) { + let nb = Math.min(4 - this._lenPos, dataLen - p); + while (nb--) + this._lenBuf[this._lenPos++] = data[p++]; + if (this._lenPos < 4) + return; - // process next record if no failure, process will be called after - // each record is handled (since handling can be asynchronous) - if(!c.fail) { - // reset record if ready and now empty - if(c.record !== null && - c.record.ready && c.record.fragment.isEmpty()) { - c.record = null; - } + this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); - // if there is no pending record, try to read record header - if(c.record === null) { - rval = _readRecordHeader(c); - } + if (this._len > MAX_PACKET_SIZE + || this._len < 8 + || (this._len & 7) !== 0) { + throw new Error('Bad packet length'); + } - // read the next record (if record not yet ready) - if(!c.fail && c.record !== null && !c.record.ready) { - rval = _readRecord(c); + if (p >= dataLen) + return; } - // record ready to be handled, update engine state - if(!c.fail && c.record !== null && c.record.ready) { - _update(c, c.record); + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; } - } - - return rval; - }; - - /** - * Requests that application data be packaged into a TLS record. The - * tlsDataReady handler will be called when the TLS record(s) have been - * prepared. - * - * @param data the application data, as a raw 'binary' encoded string, to - * be sent; to send utf-16/utf-8 string data, use the return value - * of util.encodeUtf8(str). - * - * @return true on success, false on failure. - */ - c.prepare = function(data) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.application_data, - data: forge.util.createBuffer(data) - })); - return tls.flush(c); - }; - /** - * Requests that a heartbeat request be packaged into a TLS record for - * transmission. The tlsDataReady handler will be called when TLS record(s) - * have been prepared. - * - * When a heartbeat response has been received, the heartbeatReceived - * handler will be called with the matching payload. This handler can - * be used to clear a retransmission timer, etc. - * - * @param payload the heartbeat data to send as the payload in the message. - * @param [payloadLength] the payload length to use, defaults to the - * actual payload length. - * - * @return true on success, false on failure. - */ - c.prepareHeartbeatRequest = function(payload, payloadLength) { - if(payload instanceof forge.util.ByteBuffer) { - payload = payload.bytes(); - } - if(typeof payloadLength === 'undefined') { - payloadLength = payload.length; - } - c.expectedHeartbeatPayload = payload; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength) - })); - return tls.flush(c); - }; + // Read Poly1305 MAC + { + const nb = Math.min(16 - this._macPos, dataLen - p); + // TODO: avoid copying if entire MAC is in current chunk + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < 16) + return; + } - /** - * Closes the connection (sends a close_notify alert). - * - * @param clearFail true to clear the fail flag (default: true). - */ - c.close = function(clearFail) { - // save session if connection didn't fail - if(!c.fail && c.sessionCache && c.session) { - // only need to preserve session ID, version, and security params - var session = { - id: c.session.id, - version: c.session.version, - sp: c.session.sp - }; - session.sp.keys = null; - c.sessionCache.setSession(session.id, session); - } + this._instance.decrypt(this._packet, this._mac, this.inSeqno); - if(c.open) { - // connection no longer open, clear input - c.open = false; - c.input.clear(); + const payload = new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1); - // if connected or handshaking, send an alert - if(c.isConnected || c.handshaking) { - c.isConnected = c.handshaking = false; + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._len = 0; + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; - // send close_notify alert - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.close_notify - })); - tls.flush(c); + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); } - - // call handler - c.closed(c); } - - // reset TLS connection, do not clear fail flag - c.reset(clearFail); - }; - - return c; -}; - -/* TLS API */ -module.exports = forge.tls = forge.tls || {}; - -// expose non-functions -for(var key in tls) { - if(typeof tls[key] !== 'function') { - forge.tls[key] = tls[key]; } } -// expose prf_tls1 for testing -forge.tls.prf_tls1 = prf_TLS1; - -// expose sha1 hmac method -forge.tls.hmac_sha1 = hmac_sha1; - -// expose session cache creation -forge.tls.createSessionCache = tls.createSessionCache; +class AESGCMDecipherNative { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decipherInstance = null; + this._decipherSSLName = dec.decipherInfo.sslName; + this._decipherKey = dec.decipherKey; + this._decipherIV = dec.decipherIV; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._tag = Buffer.allocUnsafe(16); + this._tagPos = 0; + } + free() {} + decrypt(data, p, dataLen) { + // `data` === encrypted data -/** - * Creates a new TLS connection. This does not make any assumptions about the - * transport layer that TLS is working on top of, ie: it does not assume there - * is a TCP/IP connection or establish one. A TLS connection is totally - * abstracted away from the layer is runs on top of, it merely establishes a - * secure channel between a client" and a "server". - * - * A TLS connection contains 4 connection states: pending read and write, and - * current read and write. - * - * At initialization, the current read and write states will be null. Only once - * the security parameters have been set and the keys have been generated can - * the pending states be converted into current states. Current states will be - * updated for each record processed. - * - * A custom certificate verify callback may be provided to check information - * like the common name on the server's certificate. It will be called for - * every certificate in the chain. It has the following signature: - * - * variable func(c, certs, index, preVerify) - * Where: - * c The TLS connection - * verified Set to true if certificate was verified, otherwise the alert - * tls.Alert.Description for why the certificate failed. - * depth The current index in the chain, where 0 is the server's cert. - * certs The certificate chain, *NOTE* if the server was anonymous then - * the chain will be empty. - * - * The function returns true on success and on failure either the appropriate - * tls.Alert.Description or an object with 'alert' set to the appropriate - * tls.Alert.Description and 'message' set to a custom error message. If true - * is not returned then the connection will abort using, in order of - * availability, first the returned alert description, second the preVerify - * alert description, and lastly the default 'bad_certificate'. - * - * There are three callbacks that can be used to make use of client-side - * certificates where each takes the TLS connection as the first parameter: - * - * getCertificate(conn, hint) - * The second parameter is a hint as to which certificate should be - * returned. If the connection entity is a client, then the hint will be - * the CertificateRequest message from the server that is part of the - * TLS protocol. If the connection entity is a server, then it will be - * the servername list provided via an SNI extension the ClientHello, if - * one was provided (empty array if not). The hint can be examined to - * determine which certificate to use (advanced). Most implementations - * will just return a certificate. The return value must be a - * PEM-formatted certificate or an array of PEM-formatted certificates - * that constitute a certificate chain, with the first in the array/chain - * being the client's certificate. - * getPrivateKey(conn, certificate) - * The second parameter is an forge.pki X.509 certificate object that - * is associated with the requested private key. The return value must - * be a PEM-formatted private key. - * getSignature(conn, bytes, callback) - * This callback can be used instead of getPrivateKey if the private key - * is not directly accessible in javascript or should not be. For - * instance, a secure external web service could provide the signature - * in exchange for appropriate credentials. The second parameter is a - * string of bytes to be signed that are part of the TLS protocol. These - * bytes are used to verify that the private key for the previously - * provided client-side certificate is accessible to the client. The - * callback is a function that takes 2 parameters, the TLS connection - * and the RSA encrypted (signed) bytes as a string. This callback must - * be called once the signature is ready. - * - * @param options the options for this connection: - * server: true if the connection is server-side, false for client. - * sessionId: a session ID to reuse, null for a new connection. - * caStore: an array of certificates to trust. - * sessionCache: a session cache to use. - * cipherSuites: an optional array of cipher suites to use, - * see tls.CipherSuites. - * connected: function(conn) called when the first handshake completes. - * virtualHost: the virtual server name to use in a TLS SNI extension. - * verifyClient: true to require a client certificate in server mode, - * 'optional' to request one, false not to (default: false). - * verify: a handler used to custom verify certificates in the chain. - * verifyOptions: an object with options for the certificate chain validation. - * See documentation of pki.verifyCertificateChain for possible options. - * verifyOptions.verify is ignored. If you wish to specify a verify handler - * use the verify key. - * getCertificate: an optional callback used to get a certificate or - * a chain of certificates (as an array). - * getPrivateKey: an optional callback used to get a private key. - * getSignature: an optional callback used to get a signature. - * tlsDataReady: function(conn) called when TLS protocol data has been - * prepared and is ready to be used (typically sent over a socket - * connection to its destination), read from conn.tlsData buffer. - * dataReady: function(conn) called when application data has - * been parsed from a TLS record and should be consumed by the - * application, read from conn.data buffer. - * closed: function(conn) called when the connection has been closed. - * error: function(conn, error) called when there was an error. - * deflate: function(inBytes) if provided, will deflate TLS records using - * the deflate algorithm if the server supports it. - * inflate: function(inBytes) if provided, will inflate TLS records using - * the deflate algorithm if the server supports it. - * - * @return the new TLS connection. - */ -forge.tls.createConnection = tls.createConnection; + while (p < dataLen) { + // Read packet length (unencrypted, but AAD) + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; + if (this._lenBytes < 4) + return; + if ((this._len + 20) > MAX_PACKET_SIZE + || this._len < 16 + || (this._len & 15) !== 0) { + throw new Error('Bad packet length'); + } -/***/ }), + this._decipherInstance = createDecipheriv( + this._decipherSSLName, + this._decipherKey, + this._decipherIV + ); + this._decipherInstance.setAutoPadding(false); + this._decipherInstance.setAAD(intToBytes(this._len)); + } -/***/ 8339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let decrypted; + if (p !== 0 || nb !== dataLen) { + decrypted = this._decipherInstance.update( + new Uint8Array(data.buffer, data.byteOffset + p, nb) + ); + } else { + decrypted = this._decipherInstance.update(data); + } + if (decrypted.length) { + if (nb === this._len) { + this._packet = decrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(decrypted, this._packetPos); + } + this._packetPos += decrypted.length; + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } -/** - * Utility functions for web applications. - * - * @author Dave Longley - * - * Copyright (c) 2010-2018 Digital Bazaar, Inc. - */ -var forge = __nccwpck_require__(9177); -var baseN = __nccwpck_require__(2300); + // Read authentication tag + { + const nb = Math.min(16 - this._tagPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._tag.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._tagPos + ); + } else { + this._tag.set(data, this._tagPos); + } + p += nb; + this._tagPos += nb; + if (this._tagPos < 16) + return; + } -/* Utilities API */ -var util = module.exports = forge.util = forge.util || {}; + { + // Verify authentication tag + this._decipherInstance.setAuthTag(this._tag); -// define setImmediate and nextTick -(function() { - // use native nextTick (unless we're in webpack) - // webpack (or better node-libs-browser polyfill) sets process.browser. - // this way we can detect webpack properly - if(typeof process !== 'undefined' && process.nextTick && !process.browser) { - util.nextTick = process.nextTick; - if(typeof setImmediate === 'function') { - util.setImmediate = setImmediate; - } else { - // polyfill setImmediate with nextTick, older versions of node - // (those w/o setImmediate) won't totally starve IO - util.setImmediate = util.nextTick; - } - return; - } + const decrypted = this._decipherInstance.final(); - // polyfill nextTick with native setImmediate - if(typeof setImmediate === 'function') { - util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; - util.nextTick = function(callback) { - return setImmediate(callback); - }; - return; - } + // XXX: this should never output any data since stream ciphers always + // return data from .update() and block ciphers must end on a multiple + // of the block length, which would have caused an exception to be + // thrown if the total input was not... + if (decrypted.length) { + if (this._packet) + this._packet.set(decrypted, this._packetPos); + else + this._packet = decrypted; + } + } - /* Note: A polyfill upgrade pattern is used here to allow combining - polyfills. For example, MutationObserver is fast, but blocks UI updates, - so it needs to allow UI updates periodically, so it falls back on - postMessage or setTimeout. */ + const payload = (!this._packet + ? EMPTY_BUFFER + : new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length + - this._packet[0] - 1)); - // polyfill with setTimeout - util.setImmediate = function(callback) { - setTimeout(callback, 0); - }; + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + ivIncrement(this._decipherIV); + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._tagPos = 0; - // upgrade polyfill to use postMessage - if(typeof window !== 'undefined' && - typeof window.postMessage === 'function') { - var msg = 'forge.setImmediate'; - var callbacks = []; - util.setImmediate = function(callback) { - callbacks.push(callback); - // only send message when one hasn't been sent in - // the current turn of the event loop - if(callbacks.length === 1) { - window.postMessage(msg, '*'); - } - }; - function handler(event) { - if(event.source === window && event.data === msg) { - event.stopPropagation(); - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); } } - window.addEventListener('message', handler, true); } +} - // upgrade polyfill to use MutationObserver - if(typeof MutationObserver !== 'undefined') { - // polyfill with MutationObserver - var now = Date.now(); - var attr = true; - var div = document.createElement('div'); - var callbacks = []; - new MutationObserver(function() { - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - }).observe(div, {attributes: true}); - var oldSetImmediate = util.setImmediate; - util.setImmediate = function(callback) { - if(Date.now() - now > 15) { - now = Date.now(); - oldSetImmediate(callback); - } else { - callbacks.push(callback); - // only trigger observer when it hasn't been triggered in - // the current turn of the event loop - if(callbacks.length === 1) { - div.setAttribute('a', attr = !attr); - } - } - }; +class AESGCMDecipherBinding { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV); + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._pktLen = 0; + this._tag = Buffer.allocUnsafe(16); + this._tagPos = 0; } + free() {} + decrypt(data, p, dataLen) { + // `data` === encrypted data - util.nextTick = util.setImmediate; -})(); - -// check if running under Node.js -util.isNodejs = - typeof process !== 'undefined' && process.versions && process.versions.node; + while (p < dataLen) { + // Read packet length (unencrypted, but AAD) + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; + if (this._lenBytes < 4) + return; + if ((this._len + 20) > MAX_PACKET_SIZE + || this._len < 16 + || (this._len & 15) !== 0) { + throw new Error(`Bad packet length: ${this._len}`); + } + } -// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while -// it will point to `window` in the main thread. -// To remain compatible with older browsers, we fall back to 'window' if 'self' -// is not available. -util.globalScope = (function() { - if(util.isNodejs) { - return global; - } + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } - return typeof self === 'undefined' ? window : self; -})(); + // Read authentication tag + { + const nb = Math.min(16 - this._tagPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._tag.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._tagPos + ); + } else { + this._tag.set(data, this._tagPos); + } + p += nb; + this._tagPos += nb; + if (this._tagPos < 16) + return; + } -// define isArray -util.isArray = Array.isArray || function(x) { - return Object.prototype.toString.call(x) === '[object Array]'; -}; + this._instance.decrypt(this._packet, this._len, this._tag); -// define isArrayBuffer -util.isArrayBuffer = function(x) { - return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; -}; + const payload = new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1); -// define isArrayBufferView -util.isArrayBufferView = function(x) { - return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; -}; + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._pktLen = 0; + this._tagPos = 0; -/** - * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for - * algorithms where bit manipulation, JavaScript limitations, and/or algorithm - * design only allow for byte operations of a limited size. - * - * @param n number of bits. - * - * Throw Error if n invalid. - */ -function _checkBitsParam(n) { - if(!(n === 8 || n === 16 || n === 24 || n === 32)) { - throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } + } } } -// TODO: set ByteBuffer to best available backing -util.ByteBuffer = ByteStringBuffer; - -/** Buffer w/BinaryString backing */ - -/** - * Constructor for a binary string backed byte buffer. - * - * @param [b] the bytes to wrap (either encoded as string, one byte per - * character, or as an ArrayBuffer or Typed Array). - */ -function ByteStringBuffer(b) { - // TODO: update to match DataBuffer API - - // the data in this buffer - this.data = ''; - // the pointer for reading from this buffer - this.read = 0; +// TODO: test incremental .update()s vs. copying to _packet and doing a single +// .update() after entire packet read -- a single .update() would allow +// verifying MAC before decrypting for ETM MACs +class GenericDecipherNative { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV); + this._decipherInstance.setAutoPadding(false); + this._block = Buffer.allocUnsafe( + dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen + ); + this._blockSize = dec.decipherInfo.blockLen; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); + this._macPos = 0; + this._macSSLName = dec.macInfo.sslName; + this._macKey = dec.macKey; + this._macActualLen = dec.macInfo.actualLen; + this._macETM = dec.macInfo.isETM; + this._macInstance = null; - if(typeof b === 'string') { - this.data = b; - } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { - if(typeof Buffer !== 'undefined' && b instanceof Buffer) { - this.data = b.toString('binary'); - } else { - // convert native buffer to forge buffer - // FIXME: support native buffers internally instead - var arr = new Uint8Array(b); - try { - this.data = String.fromCharCode.apply(null, arr); - } catch(e) { - for(var i = 0; i < arr.length; ++i) { - this.putByte(arr[i]); - } + const discardLen = dec.decipherInfo.discardLen; + if (discardLen) { + let discard = DISCARD_CACHE.get(discardLen); + if (discard === undefined) { + discard = Buffer.alloc(discardLen); + DISCARD_CACHE.set(discardLen, discard); } + this._decipherInstance.update(discard); } - } else if(b instanceof ByteStringBuffer || - (typeof b === 'object' && typeof b.data === 'string' && - typeof b.read === 'number')) { - // copy existing buffer - this.data = b.data; - this.read = b.read; - } - - // used for v8 optimization - this._constructedStringLength = 0; -} -util.ByteStringBuffer = ByteStringBuffer; - -/* Note: This is an optimization for V8-based browsers. When V8 concatenates - a string, the strings are only joined logically using a "cons string" or - "constructed/concatenated string". These containers keep references to one - another and can result in very large memory usage. For example, if a 2MB - string is constructed by concatenating 4 bytes together at a time, the - memory usage will be ~44MB; so ~22x increase. The strings are only joined - together when an operation requiring their joining takes place, such as - substr(). This function is called when adding data to this buffer to ensure - these types of strings are periodically joined to reduce the memory - footprint. */ -var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; -util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { - this._constructedStringLength += x; - if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { - // this substr() should cause the constructed string to join - this.data.substr(0, 1); - this._constructedStringLength = 0; } -}; + free() {} + decrypt(data, p, dataLen) { + // `data` === encrypted data -/** - * Gets the number of bytes in this buffer. - * - * @return the number of bytes in this buffer. - */ -util.ByteStringBuffer.prototype.length = function() { - return this.data.length - this.read; -}; + while (p < dataLen) { + // Read first encrypted block + if (this._blockPos < this._block.length) { + const nb = Math.min(this._block.length - this._blockPos, dataLen - p); + if (p !== 0 || nb !== dataLen || nb < data.length) { + this._block.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._blockPos + ); + } else { + this._block.set(data, this._blockPos); + } -/** - * Gets whether or not this buffer is empty. - * - * @return true if this buffer is empty, false if not. - */ -util.ByteStringBuffer.prototype.isEmpty = function() { - return this.length() <= 0; -}; + p += nb; + this._blockPos += nb; + if (this._blockPos < this._block.length) + return; -/** - * Puts a byte in this buffer. - * - * @param b the byte to put. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putByte = function(b) { - return this.putBytes(String.fromCharCode(b)); -}; + let decrypted; + let need; + if (this._macETM) { + this._len = need = readUInt32BE(this._block, 0); + } else { + // Decrypt first block to get packet length + decrypted = this._decipherInstance.update(this._block); + this._len = readUInt32BE(decrypted, 0); + need = 4 + this._len - this._blockSize; + } -/** - * Puts a byte in this buffer N times. - * - * @param b the byte to put. - * @param n the number of bytes of value b to put. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { - b = String.fromCharCode(b); - var d = this.data; - while(n > 0) { - if(n & 1) { - d += b; - } - n >>>= 1; - if(n > 0) { - b += b; - } - } - this.data = d; - this._optimizeConstructedString(n); - return this; -}; + if (this._len > MAX_PACKET_SIZE + || this._len < 5 + || (need & (this._blockSize - 1)) !== 0) { + throw new Error('Bad packet length'); + } -/** - * Puts bytes in this buffer. - * - * @param bytes the bytes (as a binary encoded string) to put. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putBytes = function(bytes) { - this.data += bytes; - this._optimizeConstructedString(bytes.length); - return this; -}; + // Create MAC up front to calculate in parallel with decryption + this._macInstance = createHmac(this._macSSLName, this._macKey); -/** - * Puts a UTF-16 encoded string into this buffer. - * - * @param str the string to put. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putString = function(str) { - return this.putBytes(util.encodeUtf8(str)); -}; + writeUInt32BE(BUF_INT, this.inSeqno, 0); + this._macInstance.update(BUF_INT); + if (this._macETM) { + this._macInstance.update(this._block); + } else { + this._macInstance.update(new Uint8Array(decrypted.buffer, + decrypted.byteOffset, + 4)); + this._pktLen = decrypted.length - 4; + this._packetPos = this._pktLen; + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set( + new Uint8Array(decrypted.buffer, + decrypted.byteOffset + 4, + this._packetPos), + 0 + ); + } -/** - * Puts a 16-bit integer in this buffer in big-endian order. - * - * @param i the 16-bit integer. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putInt16 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i & 0xFF)); -}; + if (p >= dataLen) + return; + } -/** - * Puts a 24-bit integer in this buffer in big-endian order. - * - * @param i the 24-bit integer. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putInt24 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 16 & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i & 0xFF)); -}; + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (this._macETM) + this._macInstance.update(encrypted); + const decrypted = this._decipherInstance.update(encrypted); + if (decrypted.length) { + if (nb === this._len) { + this._packet = decrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(decrypted, this._packetPos); + } + this._packetPos += decrypted.length; + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } -/** - * Puts a 32-bit integer in this buffer in big-endian order. - * - * @param i the 32-bit integer. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putInt32 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 24 & 0xFF) + - String.fromCharCode(i >> 16 & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i & 0xFF)); -}; + // Read MAC + { + const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < this._macActualLen) + return; + } -/** - * Puts a 16-bit integer in this buffer in little-endian order. - * - * @param i the 16-bit integer. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putInt16Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF)); -}; + // Verify MAC + if (!this._macETM) + this._macInstance.update(this._packet); + let calculated = this._macInstance.digest(); + if (this._macActualLen < calculated.length) { + calculated = new Uint8Array(calculated.buffer, + calculated.byteOffset, + this._macActualLen); + } + if (!timingSafeEquals(calculated, this._mac)) + throw new Error('Invalid MAC'); -/** - * Puts a 24-bit integer in this buffer in little-endian order. - * - * @param i the 24-bit integer. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putInt24Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i >> 16 & 0xFF)); -}; + const payload = new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1); -/** - * Puts a 32-bit integer in this buffer in little-endian order. - * - * @param i the 32-bit integer. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putInt32Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i >> 16 & 0xFF) + - String.fromCharCode(i >> 24 & 0xFF)); -}; + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._macPos = 0; + this._macInstance = null; -/** - * Puts an n-bit integer in this buffer in big-endian order. - * - * @param i the n-bit integer. - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - var bytes = ''; - do { - n -= 8; - bytes += String.fromCharCode((i >> n) & 0xFF); - } while(n > 0); - return this.putBytes(bytes); -}; + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } + } + } +} -/** - * Puts a signed n-bit integer in this buffer in big-endian order. Two's - * complement representation is used. - * - * @param i the n-bit integer. - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { - // putInt checks n - if(i < 0) { - i += 2 << (n - 1); +class GenericDecipherBinding { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new GenericDecipher(dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV, + dec.macInfo.sslName, + dec.macKey, + dec.macInfo.isETM, + dec.macInfo.actualLen); + this._block = Buffer.allocUnsafe( + dec.macInfo.isETM || dec.decipherInfo.stream + ? 4 + : dec.decipherInfo.blockLen + ); + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); + this._macPos = 0; + this._macActualLen = dec.macInfo.actualLen; + this._macETM = dec.macInfo.isETM; } - return this.putInt(i, n); -}; + free() { + this._instance.free(); + } + decrypt(data, p, dataLen) { + // `data` === encrypted data -/** - * Puts the given buffer into this buffer. - * - * @param buffer the buffer to put into this one. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.putBuffer = function(buffer) { - return this.putBytes(buffer.getBytes()); -}; + while (p < dataLen) { + // Read first encrypted block + if (this._blockPos < this._block.length) { + const nb = Math.min(this._block.length - this._blockPos, dataLen - p); + if (p !== 0 || nb !== dataLen || nb < data.length) { + this._block.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._blockPos + ); + } else { + this._block.set(data, this._blockPos); + } -/** - * Gets a byte from this buffer and advances the read pointer by 1. - * - * @return the byte. - */ -util.ByteStringBuffer.prototype.getByte = function() { - return this.data.charCodeAt(this.read++); -}; + p += nb; + this._blockPos += nb; + if (this._blockPos < this._block.length) + return; -/** - * Gets a uint16 from this buffer in big-endian order and advances the read - * pointer by 2. - * - * @return the uint16. - */ -util.ByteStringBuffer.prototype.getInt16 = function() { - var rval = ( - this.data.charCodeAt(this.read) << 8 ^ - this.data.charCodeAt(this.read + 1)); - this.read += 2; - return rval; -}; + let need; + if (this._macETM) { + this._len = need = readUInt32BE(this._block, 0); + } else { + // Decrypt first block to get packet length + this._instance.decryptBlock(this._block); + this._len = readUInt32BE(this._block, 0); + need = 4 + this._len - this._block.length; + } -/** - * Gets a uint24 from this buffer in big-endian order and advances the read - * pointer by 3. - * - * @return the uint24. - */ -util.ByteStringBuffer.prototype.getInt24 = function() { - var rval = ( - this.data.charCodeAt(this.read) << 16 ^ - this.data.charCodeAt(this.read + 1) << 8 ^ - this.data.charCodeAt(this.read + 2)); - this.read += 3; - return rval; -}; + if (this._len > MAX_PACKET_SIZE + || this._len < 5 + || (need & (this._block.length - 1)) !== 0) { + throw new Error('Bad packet length'); + } -/** - * Gets a uint32 from this buffer in big-endian order and advances the read - * pointer by 4. - * - * @return the word. - */ -util.ByteStringBuffer.prototype.getInt32 = function() { - var rval = ( - this.data.charCodeAt(this.read) << 24 ^ - this.data.charCodeAt(this.read + 1) << 16 ^ - this.data.charCodeAt(this.read + 2) << 8 ^ - this.data.charCodeAt(this.read + 3)); - this.read += 4; - return rval; -}; + if (!this._macETM) { + this._pktLen = (this._block.length - 4); + if (this._pktLen) { + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set( + new Uint8Array(this._block.buffer, + this._block.byteOffset + 4, + this._pktLen), + 0 + ); + } + } -/** - * Gets a uint16 from this buffer in little-endian order and advances the read - * pointer by 2. - * - * @return the uint16. - */ -util.ByteStringBuffer.prototype.getInt16Le = function() { - var rval = ( - this.data.charCodeAt(this.read) ^ - this.data.charCodeAt(this.read + 1) << 8); - this.read += 2; - return rval; -}; + if (p >= dataLen) + return; + } -/** - * Gets a uint24 from this buffer in little-endian order and advances the read - * pointer by 3. - * - * @return the uint24. - */ -util.ByteStringBuffer.prototype.getInt24Le = function() { - var rval = ( - this.data.charCodeAt(this.read) ^ - this.data.charCodeAt(this.read + 1) << 8 ^ - this.data.charCodeAt(this.read + 2) << 16); - this.read += 3; - return rval; -}; + // Read padding length, payload, and padding + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } -/** - * Gets a uint32 from this buffer in little-endian order and advances the read - * pointer by 4. - * - * @return the word. - */ -util.ByteStringBuffer.prototype.getInt32Le = function() { - var rval = ( - this.data.charCodeAt(this.read) ^ - this.data.charCodeAt(this.read + 1) << 8 ^ - this.data.charCodeAt(this.read + 2) << 16 ^ - this.data.charCodeAt(this.read + 3) << 24); - this.read += 4; - return rval; -}; + // Read MAC + { + const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < this._macActualLen) + return; + } -/** - * Gets an n-bit integer from this buffer in big-endian order and advances the - * read pointer by ceil(n/8). - * - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return the integer. - */ -util.ByteStringBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. - rval = (rval << 8) + this.data.charCodeAt(this.read++); - n -= 8; - } while(n > 0); - return rval; -}; + // Decrypt and verify MAC + this._instance.decrypt(this._packet, + this.inSeqno, + this._block, + this._mac); -/** - * Gets a signed n-bit integer from this buffer in big-endian order, using - * two's complement, and advances the read pointer by n/8. - * - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return the integer. - */ -util.ByteStringBuffer.prototype.getSignedInt = function(n) { - // getInt checks n - var x = this.getInt(n); - var max = 2 << (n - 2); - if(x >= max) { - x -= max << 1; - } - return x; -}; + const payload = new FastBuffer(this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1); -/** - * Reads bytes out as a binary encoded string and clears them from the - * buffer. Note that the resulting string is binary encoded (in node.js this - * encoding is referred to as `binary`, it is *not* `utf8`). - * - * @param count the number of bytes to read, undefined or null for all. - * - * @return a binary encoded string of bytes. - */ -util.ByteStringBuffer.prototype.getBytes = function(count) { - var rval; - if(count) { - // read count bytes - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if(count === 0) { - rval = ''; - } else { - // read all bytes, optimize to only copy when needed - rval = (this.read === 0) ? this.data : this.data.slice(this.read); - this.clear(); + // Prepare for next packet + this.inSeqno = (this.inSeqno + 1) >>> 0; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; + this._macInstance = null; + + { + const ret = this._onPayload(payload); + if (ret !== undefined) + return (ret === false ? p : ret); + } + } } - return rval; -}; +} -/** - * Gets a binary encoded string of the bytes from this buffer without - * modifying the read pointer. - * - * @param count the number of bytes to get, omit to get all. - * - * @return a string full of binary encoded characters. - */ -util.ByteStringBuffer.prototype.bytes = function(count) { - return (typeof(count) === 'undefined' ? - this.data.slice(this.read) : - this.data.slice(this.read, this.read + count)); -}; +// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV +function ivIncrement(iv) { + // eslint-disable-next-line no-unused-expressions + ++iv[11] >>> 8 + && ++iv[10] >>> 8 + && ++iv[9] >>> 8 + && ++iv[8] >>> 8 + && ++iv[7] >>> 8 + && ++iv[6] >>> 8 + && ++iv[5] >>> 8 + && ++iv[4] >>> 8; +} -/** - * Gets a byte at the given index without modifying the read pointer. - * - * @param i the byte index. - * - * @return the byte. - */ -util.ByteStringBuffer.prototype.at = function(i) { - return this.data.charCodeAt(this.read + i); -}; +const intToBytes = (() => { + const ret = Buffer.alloc(4); + return (n) => { + ret[0] = (n >>> 24); + ret[1] = (n >>> 16); + ret[2] = (n >>> 8); + ret[3] = n; + return ret; + }; +})(); -/** - * Puts a byte at the given index without modifying the read pointer. - * - * @param i the byte index. - * @param b the byte to put. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.setAt = function(i, b) { - this.data = this.data.substr(0, this.read + i) + - String.fromCharCode(b) + - this.data.substr(this.read + i + 1); - return this; -}; +function timingSafeEquals(a, b) { + if (a.length !== b.length) { + timingSafeEqual(a, a); + return false; + } + return timingSafeEqual(a, b); +} + +function createCipher(config) { + if (typeof config !== 'object' || config === null) + throw new Error('Invalid config'); -/** - * Gets the last byte without modifying the read pointer. - * - * @return the last byte. - */ -util.ByteStringBuffer.prototype.last = function() { - return this.data.charCodeAt(this.data.length - 1); -}; + if (typeof config.outbound !== 'object' || config.outbound === null) + throw new Error('Invalid outbound'); -/** - * Creates a copy of this buffer. - * - * @return the copy. - */ -util.ByteStringBuffer.prototype.copy = function() { - var c = util.createBuffer(this.data); - c.read = this.read; - return c; -}; + const outbound = config.outbound; -/** - * Compacts this buffer. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.compact = function() { - if(this.read > 0) { - this.data = this.data.slice(this.read); - this.read = 0; + if (typeof outbound.onWrite !== 'function') + throw new Error('Invalid outbound.onWrite'); + + if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) + throw new Error('Invalid outbound.cipherInfo'); + + if (!Buffer.isBuffer(outbound.cipherKey) + || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { + throw new Error('Invalid outbound.cipherKey'); } - return this; -}; -/** - * Clears this buffer. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.clear = function() { - this.data = ''; - this.read = 0; - return this; -}; + if (outbound.cipherInfo.ivLen + && (!Buffer.isBuffer(outbound.cipherIV) + || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { + throw new Error('Invalid outbound.cipherIV'); + } -/** - * Shortens this buffer by triming bytes off of the end of this buffer. - * - * @param count the number of bytes to trim off. - * - * @return this buffer. - */ -util.ByteStringBuffer.prototype.truncate = function(count) { - var len = Math.max(0, this.length() - count); - this.data = this.data.substr(this.read, len); - this.read = 0; - return this; -}; + if (typeof outbound.seqno !== 'number' + || outbound.seqno < 0 + || outbound.seqno > MAX_SEQNO) { + throw new Error('Invalid outbound.seqno'); + } -/** - * Converts this buffer to a hexadecimal string. - * - * @return a hexadecimal string. - */ -util.ByteStringBuffer.prototype.toHex = function() { - var rval = ''; - for(var i = this.read; i < this.data.length; ++i) { - var b = this.data.charCodeAt(i); - if(b < 16) { - rval += '0'; + const forceNative = !!outbound.forceNative; + + switch (outbound.cipherInfo.sslName) { + case 'aes-128-gcm': + case 'aes-256-gcm': + return (AESGCMCipher && !forceNative + ? new AESGCMCipherBinding(config) + : new AESGCMCipherNative(config)); + case 'chacha20': + return (ChaChaPolyCipher && !forceNative + ? new ChaChaPolyCipherBinding(config) + : new ChaChaPolyCipherNative(config)); + default: { + if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) + throw new Error('Invalid outbound.macInfo'); + if (!Buffer.isBuffer(outbound.macKey) + || outbound.macKey.length !== outbound.macInfo.len) { + throw new Error('Invalid outbound.macKey'); + } + return (GenericCipher && !forceNative + ? new GenericCipherBinding(config) + : new GenericCipherNative(config)); } - rval += b.toString(16); } - return rval; -}; +} -/** - * Converts this buffer to a UTF-16 string (standard JavaScript string). - * - * @return a UTF-16 string. - */ -util.ByteStringBuffer.prototype.toString = function() { - return util.decodeUtf8(this.bytes()); -}; +function createDecipher(config) { + if (typeof config !== 'object' || config === null) + throw new Error('Invalid config'); -/** End Buffer w/BinaryString backing */ + if (typeof config.inbound !== 'object' || config.inbound === null) + throw new Error('Invalid inbound'); -/** Buffer w/UInt8Array backing */ + const inbound = config.inbound; -/** - * FIXME: Experimental. Do not use yet. - * - * Constructor for an ArrayBuffer-backed byte buffer. - * - * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a - * TypedArray. - * - * If a string is given, its encoding should be provided as an option, - * otherwise it will default to 'binary'. A 'binary' string is encoded such - * that each character is one byte in length and size. - * - * If an ArrayBuffer, DataView, or TypedArray is given, it will be used - * *directly* without any copying. Note that, if a write to the buffer requires - * more space, the buffer will allocate a new backing ArrayBuffer to - * accommodate. The starting read and write offsets for the buffer may be - * given as options. - * - * @param [b] the initial bytes for this buffer. - * @param options the options to use: - * [readOffset] the starting read offset to use (default: 0). - * [writeOffset] the starting write offset to use (default: the - * length of the first parameter). - * [growSize] the minimum amount, in bytes, to grow the buffer by to - * accommodate writes (default: 1024). - * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the - * first parameter, if it is a string (default: 'binary'). - */ -function DataBuffer(b, options) { - // default options - options = options || {}; + if (typeof inbound.onPayload !== 'function') + throw new Error('Invalid inbound.onPayload'); - // pointers for read from/write to buffer - this.read = options.readOffset || 0; - this.growSize = options.growSize || 1024; + if (typeof inbound.decipherInfo !== 'object' + || inbound.decipherInfo === null) { + throw new Error('Invalid inbound.decipherInfo'); + } - var isArrayBuffer = util.isArrayBuffer(b); - var isArrayBufferView = util.isArrayBufferView(b); - if(isArrayBuffer || isArrayBufferView) { - // use ArrayBuffer directly - if(isArrayBuffer) { - this.data = new DataView(b); - } else { - // TODO: adjust read/write offset based on the type of view - // or specify that this must be done in the options ... that the - // offsets are byte-based - this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); - } - this.write = ('writeOffset' in options ? - options.writeOffset : this.data.byteLength); - return; + if (!Buffer.isBuffer(inbound.decipherKey) + || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { + throw new Error('Invalid inbound.decipherKey'); } - // initialize to empty array buffer and add any given bytes using putBytes - this.data = new DataView(new ArrayBuffer(0)); - this.write = 0; + if (inbound.decipherInfo.ivLen + && (!Buffer.isBuffer(inbound.decipherIV) + || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { + throw new Error('Invalid inbound.decipherIV'); + } - if(b !== null && b !== undefined) { - this.putBytes(b); + if (typeof inbound.seqno !== 'number' + || inbound.seqno < 0 + || inbound.seqno > MAX_SEQNO) { + throw new Error('Invalid inbound.seqno'); } - if('writeOffset' in options) { - this.write = options.writeOffset; + const forceNative = !!inbound.forceNative; + + switch (inbound.decipherInfo.sslName) { + case 'aes-128-gcm': + case 'aes-256-gcm': + return (AESGCMDecipher && !forceNative + ? new AESGCMDecipherBinding(config) + : new AESGCMDecipherNative(config)); + case 'chacha20': + return (ChaChaPolyDecipher && !forceNative + ? new ChaChaPolyDecipherBinding(config) + : new ChaChaPolyDecipherNative(config)); + default: { + if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) + throw new Error('Invalid inbound.macInfo'); + if (!Buffer.isBuffer(inbound.macKey) + || inbound.macKey.length !== inbound.macInfo.len) { + throw new Error('Invalid inbound.macKey'); + } + return (GenericDecipher && !forceNative + ? new GenericDecipherBinding(config) + : new GenericDecipherNative(config)); + } } } -util.DataBuffer = DataBuffer; -/** - * Gets the number of bytes in this buffer. - * - * @return the number of bytes in this buffer. - */ -util.DataBuffer.prototype.length = function() { - return this.write - this.read; -}; +module.exports = { + CIPHER_INFO, + MAC_INFO, + bindingAvailable: !!binding, + init: (() => { + // eslint-disable-next-line no-async-promise-executor + return new Promise(async (resolve, reject) => { + try { + POLY1305_WASM_MODULE = await __nccwpck_require__(4989)(); + POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); + poly1305_auth = POLY1305_WASM_MODULE.cwrap( + 'poly1305_auth', + null, + ['number', 'array', 'number', 'array', 'number', 'array'] + ); + } catch (ex) { + return reject(ex); + } + resolve(); + }); + })(), -/** - * Gets whether or not this buffer is empty. - * - * @return true if this buffer is empty, false if not. - */ -util.DataBuffer.prototype.isEmpty = function() { - return this.length() <= 0; + NullCipher, + createCipher, + NullDecipher, + createDecipher, }; -/** - * Ensures this buffer has enough empty space to accommodate the given number - * of bytes. An optional parameter may be given that indicates a minimum - * amount to grow the buffer if necessary. If the parameter is not given, - * the buffer will be grown by some previously-specified default amount - * or heuristic. - * - * @param amount the number of bytes to accommodate. - * @param [growSize] the minimum amount, in bytes, to grow the buffer by if - * necessary. - */ -util.DataBuffer.prototype.accommodate = function(amount, growSize) { - if(this.length() >= amount) { - return this; - } - growSize = Math.max(growSize || this.growSize, amount); - // grow buffer - var src = new Uint8Array( - this.data.buffer, this.data.byteOffset, this.data.byteLength); - var dst = new Uint8Array(this.length() + growSize); - dst.set(src); - this.data = new DataView(dst.buffer); +/***/ }), - return this; -}; +/***/ 4989: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Puts a byte in this buffer. - * - * @param b the byte to put. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putByte = function(b) { - this.accommodate(1); - this.data.setUint8(this.write++, b); - return this; -}; -/** - * Puts a byte in this buffer N times. - * - * @param b the byte to put. - * @param n the number of bytes of value b to put. - * - * @return this buffer. - */ -util.DataBuffer.prototype.fillWithByte = function(b, n) { - this.accommodate(n); - for(var i = 0; i < n; ++i) { - this.data.setUint8(b); - } - return this; -}; +var createPoly1305 = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(createPoly1305) { + createPoly1305 = createPoly1305 || {}; -/** - * Puts bytes in this buffer. The bytes may be given as a string, an - * ArrayBuffer, a DataView, or a TypedArray. - * - * @param bytes the bytes to put. - * @param [encoding] the encoding for the first parameter ('binary', 'utf8', - * 'utf16', 'hex'), if it is a string (default: 'binary'). - * - * @return this buffer. - */ -util.DataBuffer.prototype.putBytes = function(bytes, encoding) { - if(util.isArrayBufferView(bytes)) { - var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); - var len = src.byteLength - src.byteOffset; - this.accommodate(len); - var dst = new Uint8Array(this.data.buffer, this.write); - dst.set(src); - this.write += len; - return this; - } - if(util.isArrayBuffer(bytes)) { - var src = new Uint8Array(bytes); - this.accommodate(src.byteLength); - var dst = new Uint8Array(this.data.buffer); - dst.set(src, this.write); - this.write += src.byteLength; - return this; - } +var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; +if(z)B=y?(__nccwpck_require__(1017).dirname)(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=__nccwpck_require__(7147));G||(G=__nccwpck_require__(1017));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=__nccwpck_require__(7147));G||(G=__nccwpck_require__(1017));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= +0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; +function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; +function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} +function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} +function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; +(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, +a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); +b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; +b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; +function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 { - // decode string as raw binary - if(encoding === 'binary' || encoding === 'raw') { - // one byte per character - this.accommodate(bytes.length); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.raw.decode(view); - return this; - } +"use strict"; - // encode text as UTF-16 bytes - if(encoding === 'utf16') { - // two bytes per character - this.accommodate(bytes.length * 2); - view = new Uint16Array(this.data.buffer, this.write); - this.write += util.text.utf16.encode(view); - return this; - } - throw new Error('Invalid encoding: ' + encoding); +const MESSAGE_HANDLERS = new Array(256); +[ + (__nccwpck_require__(4126).HANDLERS), + __nccwpck_require__(6475), +].forEach((handlers) => { + // eslint-disable-next-line prefer-const + for (let [type, handler] of Object.entries(handlers)) { + type = +type; + if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) + MESSAGE_HANDLERS[type] = handler; } +}); - throw Error('Invalid parameter: ' + bytes); -}; +module.exports = MESSAGE_HANDLERS; -/** - * Puts the given buffer into this buffer. - * - * @param buffer the buffer to put into this one. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putBuffer = function(buffer) { - this.putBytes(buffer); - buffer.clear(); - return this; -}; -/** - * Puts a string into this buffer. - * - * @param str the string to put. - * @param [encoding] the encoding for the string (default: 'utf16'). - * - * @return this buffer. - */ -util.DataBuffer.prototype.putString = function(str) { - return this.putBytes(str, 'utf16'); -}; +/***/ }), -/** - * Puts a 16-bit integer in this buffer in big-endian order. - * - * @param i the 16-bit integer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putInt16 = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i); - this.write += 2; - return this; -}; +/***/ 6475: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + bufferSlice, + bufferParser, + doFatalError, + sigSSHToASN1, + writeUInt32BE, +} = __nccwpck_require__(9475); + +const { + CHANNEL_OPEN_FAILURE, + COMPAT, + MESSAGE, + TERMINAL_MODE, +} = __nccwpck_require__(6832); -/** - * Puts a 24-bit integer in this buffer in big-endian order. - * - * @param i the 24-bit integer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putInt24 = function(i) { - this.accommodate(3); - this.data.setInt16(this.write, i >> 8 & 0xFFFF); - this.data.setInt8(this.write, i >> 16 & 0xFF); - this.write += 3; - return this; -}; +const { + parseKey, +} = __nccwpck_require__(2218); -/** - * Puts a 32-bit integer in this buffer in big-endian order. - * - * @param i the 32-bit integer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putInt32 = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i); - this.write += 4; - return this; -}; +const TERMINAL_MODE_BY_VALUE = + Array.from(Object.entries(TERMINAL_MODE)) + .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); -/** - * Puts a 16-bit integer in this buffer in little-endian order. - * - * @param i the 16-bit integer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putInt16Le = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i, true); - this.write += 2; - return this; -}; +module.exports = { + // Transport layer protocol ================================================== + [MESSAGE.DISCONNECT]: (self, payload) => { + /* + byte SSH_MSG_DISCONNECT + uint32 reason code + string description in ISO-10646 UTF-8 encoding + string language tag + */ + bufferParser.init(payload, 1); + const reason = bufferParser.readUInt32BE(); + const desc = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); -/** - * Puts a 24-bit integer in this buffer in little-endian order. - * - * @param i the 24-bit integer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putInt24Le = function(i) { - this.accommodate(3); - this.data.setInt8(this.write, i >> 16 & 0xFF); - this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); - this.write += 3; - return this; -}; + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed DISCONNECT packet' + ); + } -/** - * Puts a 32-bit integer in this buffer in little-endian order. - * - * @param i the 32-bit integer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putInt32Le = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i, true); - this.write += 4; - return this; -}; + self._debug && self._debug( + `Inbound: Received DISCONNECT (${reason}, "${desc}")` + ); -/** - * Puts an n-bit integer in this buffer in big-endian order. - * - * @param i the n-bit integer. - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return this buffer. - */ -util.DataBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - do { - n -= 8; - this.data.setInt8(this.write++, (i >> n) & 0xFF); - } while(n > 0); - return this; -}; + const handler = self._handlers.DISCONNECT; + handler && handler(self, reason, desc); + }, + [MESSAGE.IGNORE]: (self, payload) => { + /* + byte SSH_MSG_IGNORE + string data + */ + self._debug && self._debug('Inbound: Received IGNORE'); + }, + [MESSAGE.UNIMPLEMENTED]: (self, payload) => { + /* + byte SSH_MSG_UNIMPLEMENTED + uint32 packet sequence number of rejected message + */ + bufferParser.init(payload, 1); + const seqno = bufferParser.readUInt32BE(); + bufferParser.clear(); -/** - * Puts a signed n-bit integer in this buffer in big-endian order. Two's - * complement representation is used. - * - * @param i the n-bit integer. - * @param n the number of bits in the integer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.putSignedInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - if(i < 0) { - i += 2 << (n - 1); - } - return this.putInt(i, n); -}; + if (seqno === undefined) { + return doFatalError( + self, + 'Inbound: Malformed UNIMPLEMENTED packet' + ); + } -/** - * Gets a byte from this buffer and advances the read pointer by 1. - * - * @return the byte. - */ -util.DataBuffer.prototype.getByte = function() { - return this.data.getInt8(this.read++); -}; + self._debug + && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); + }, + [MESSAGE.DEBUG]: (self, payload) => { + /* + byte SSH_MSG_DEBUG + boolean always_display + string message in ISO-10646 UTF-8 encoding [RFC3629] + string language tag [RFC3066] + */ + bufferParser.init(payload, 1); + const display = bufferParser.readBool(); + const msg = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); -/** - * Gets a uint16 from this buffer in big-endian order and advances the read - * pointer by 2. - * - * @return the uint16. - */ -util.DataBuffer.prototype.getInt16 = function() { - var rval = this.data.getInt16(this.read); - this.read += 2; - return rval; -}; + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed DEBUG packet' + ); + } -/** - * Gets a uint24 from this buffer in big-endian order and advances the read - * pointer by 3. - * - * @return the uint24. - */ -util.DataBuffer.prototype.getInt24 = function() { - var rval = ( - this.data.getInt16(this.read) << 8 ^ - this.data.getInt8(this.read + 2)); - this.read += 3; - return rval; -}; + self._debug && self._debug('Inbound: Received DEBUG'); -/** - * Gets a uint32 from this buffer in big-endian order and advances the read - * pointer by 4. - * - * @return the word. - */ -util.DataBuffer.prototype.getInt32 = function() { - var rval = this.data.getInt32(this.read); - this.read += 4; - return rval; -}; + const handler = self._handlers.DEBUG; + handler && handler(self, display, msg); + }, + [MESSAGE.SERVICE_REQUEST]: (self, payload) => { + /* + byte SSH_MSG_SERVICE_REQUEST + string service name + */ + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + bufferParser.clear(); -/** - * Gets a uint16 from this buffer in little-endian order and advances the read - * pointer by 2. - * - * @return the uint16. - */ -util.DataBuffer.prototype.getInt16Le = function() { - var rval = this.data.getInt16(this.read, true); - this.read += 2; - return rval; -}; + if (name === undefined) { + return doFatalError( + self, + 'Inbound: Malformed SERVICE_REQUEST packet' + ); + } -/** - * Gets a uint24 from this buffer in little-endian order and advances the read - * pointer by 3. - * - * @return the uint24. - */ -util.DataBuffer.prototype.getInt24Le = function() { - var rval = ( - this.data.getInt8(this.read) ^ - this.data.getInt16(this.read + 1, true) << 8); - this.read += 3; - return rval; -}; + self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); -/** - * Gets a uint32 from this buffer in little-endian order and advances the read - * pointer by 4. - * - * @return the word. - */ -util.DataBuffer.prototype.getInt32Le = function() { - var rval = this.data.getInt32(this.read, true); - this.read += 4; - return rval; -}; + const handler = self._handlers.SERVICE_REQUEST; + handler && handler(self, name); + }, + [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { + // S->C + /* + byte SSH_MSG_SERVICE_ACCEPT + string service name + */ + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + bufferParser.clear(); -/** - * Gets an n-bit integer from this buffer in big-endian order and advances the - * read pointer by n/8. - * - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return the integer. - */ -util.DataBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. - rval = (rval << 8) + this.data.getInt8(this.read++); - n -= 8; - } while(n > 0); - return rval; -}; + if (name === undefined) { + return doFatalError( + self, + 'Inbound: Malformed SERVICE_ACCEPT packet' + ); + } -/** - * Gets a signed n-bit integer from this buffer in big-endian order, using - * two's complement, and advances the read pointer by n/8. - * - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return the integer. - */ -util.DataBuffer.prototype.getSignedInt = function(n) { - // getInt checks n - var x = this.getInt(n); - var max = 2 << (n - 2); - if(x >= max) { - x -= max << 1; - } - return x; -}; + self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); -/** - * Reads bytes out as a binary encoded string and clears them from the - * buffer. - * - * @param count the number of bytes to read, undefined or null for all. - * - * @return a binary encoded string of bytes. - */ -util.DataBuffer.prototype.getBytes = function(count) { - // TODO: deprecate this method, it is poorly named and - // this.toString('binary') replaces it - // add a toTypedArray()/toArrayBuffer() function - var rval; - if(count) { - // read count bytes - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if(count === 0) { - rval = ''; - } else { - // read all bytes, optimize to only copy when needed - rval = (this.read === 0) ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; -}; + const handler = self._handlers.SERVICE_ACCEPT; + handler && handler(self, name); + }, + [MESSAGE.EXT_INFO]: (self, payload) => { + /* + byte SSH_MSG_EXT_INFO + uint32 nr-extensions + repeat the following 2 fields "nr-extensions" times: + string extension-name + string extension-value (binary) + */ + bufferParser.init(payload, 1); + const numExts = bufferParser.readUInt32BE(); + let exts; + if (numExts !== undefined) { + exts = []; + for (let i = 0; i < numExts; ++i) { + const name = bufferParser.readString(true); + const data = bufferParser.readString(); + if (data !== undefined) { + switch (name) { + case 'server-sig-algs': { + const algs = data.latin1Slice(0, data.length).split(','); + exts.push({ name, algs }); + continue; + } + default: + continue; + } + } + // Malformed + exts = undefined; + break; + } + } + bufferParser.clear(); -/** - * Gets a binary encoded string of the bytes from this buffer without - * modifying the read pointer. - * - * @param count the number of bytes to get, omit to get all. - * - * @return a string full of binary encoded characters. - */ -util.DataBuffer.prototype.bytes = function(count) { - // TODO: deprecate this method, it is poorly named, add "getString()" - return (typeof(count) === 'undefined' ? - this.data.slice(this.read) : - this.data.slice(this.read, this.read + count)); -}; + if (exts === undefined) + return doFatalError(self, 'Inbound: Malformed EXT_INFO packet'); -/** - * Gets a byte at the given index without modifying the read pointer. - * - * @param i the byte index. - * - * @return the byte. - */ -util.DataBuffer.prototype.at = function(i) { - return this.data.getUint8(this.read + i); -}; + self._debug && self._debug('Inbound: Received EXT_INFO'); -/** - * Puts a byte at the given index without modifying the read pointer. - * - * @param i the byte index. - * @param b the byte to put. - * - * @return this buffer. - */ -util.DataBuffer.prototype.setAt = function(i, b) { - this.data.setUint8(i, b); - return this; -}; + const handler = self._handlers.EXT_INFO; + handler && handler(self, exts); + }, -/** - * Gets the last byte without modifying the read pointer. - * - * @return the last byte. - */ -util.DataBuffer.prototype.last = function() { - return this.data.getUint8(this.write - 1); -}; + // User auth protocol -- generic ============================================= + [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { + /* + byte SSH_MSG_USERAUTH_REQUEST + string user name in ISO-10646 UTF-8 encoding [RFC3629] + string service name in US-ASCII + string method name in US-ASCII + .... method specific fields + */ + bufferParser.init(payload, 1); + const user = bufferParser.readString(true); + const service = bufferParser.readString(true); + const method = bufferParser.readString(true); + let methodData; + let methodDesc; + switch (method) { + case 'none': + methodData = null; + break; + case 'password': { + /* + boolean + string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] + [string new password] + */ + const isChange = bufferParser.readBool(); + if (isChange !== undefined) { + methodData = bufferParser.readString(true); + if (methodData !== undefined && isChange) { + const newPassword = bufferParser.readString(true); + if (newPassword !== undefined) + methodData = { oldPassword: methodData, newPassword }; + else + methodData = undefined; + } + } + break; + } + case 'publickey': { + /* + boolean + string public key algorithm name + string public key blob + [string signature] + */ + const hasSig = bufferParser.readBool(); + if (hasSig !== undefined) { + const keyAlgo = bufferParser.readString(true); + let realKeyAlgo = keyAlgo; + const key = bufferParser.readString(); + + let hashAlgo; + switch (keyAlgo) { + case 'rsa-sha2-256': + realKeyAlgo = 'ssh-rsa'; + hashAlgo = 'sha256'; + break; + case 'rsa-sha2-512': + realKeyAlgo = 'ssh-rsa'; + hashAlgo = 'sha512'; + break; + } + + if (hasSig) { + const blobEnd = bufferParser.pos(); + let signature = bufferParser.readString(); + if (signature !== undefined) { + if (signature.length > (4 + keyAlgo.length + 4) + && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { + // Skip algoLen + algo + sigLen + signature = bufferSlice(signature, 4 + keyAlgo.length + 4); + } + + signature = sigSSHToASN1(signature, realKeyAlgo); + if (signature) { + const sessionID = self._kex.sessionID; + const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); + writeUInt32BE(blob, sessionID.length, 0); + blob.set(sessionID, 4); + blob.set( + new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), + 4 + sessionID.length + ); + methodData = { + keyAlgo: realKeyAlgo, + key, + signature, + blob, + hashAlgo, + }; + } + } + } else { + methodData = { keyAlgo: realKeyAlgo, key, hashAlgo }; + methodDesc = 'publickey -- check'; + } + } + break; + } + case 'hostbased': { + /* + string public key algorithm for host key + string public host key and certificates for client host + string client host name expressed as the FQDN in US-ASCII + string user name on the client host in ISO-10646 UTF-8 encoding + [RFC3629] + string signature + */ + const keyAlgo = bufferParser.readString(true); + let realKeyAlgo = keyAlgo; + const key = bufferParser.readString(); + const localHostname = bufferParser.readString(true); + const localUsername = bufferParser.readString(true); -/** - * Creates a copy of this buffer. - * - * @return the copy. - */ -util.DataBuffer.prototype.copy = function() { - return new util.DataBuffer(this); -}; + let hashAlgo; + switch (keyAlgo) { + case 'rsa-sha2-256': + realKeyAlgo = 'ssh-rsa'; + hashAlgo = 'sha256'; + break; + case 'rsa-sha2-512': + realKeyAlgo = 'ssh-rsa'; + hashAlgo = 'sha512'; + break; + } -/** - * Compacts this buffer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.compact = function() { - if(this.read > 0) { - var src = new Uint8Array(this.data.buffer, this.read); - var dst = new Uint8Array(src.byteLength); - dst.set(src); - this.data = new DataView(dst); - this.write -= this.read; - this.read = 0; - } - return this; -}; + const blobEnd = bufferParser.pos(); + let signature = bufferParser.readString(); + if (signature !== undefined) { + if (signature.length > (4 + keyAlgo.length + 4) + && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { + // Skip algoLen + algo + sigLen + signature = bufferSlice(signature, 4 + keyAlgo.length + 4); + } -/** - * Clears this buffer. - * - * @return this buffer. - */ -util.DataBuffer.prototype.clear = function() { - this.data = new DataView(new ArrayBuffer(0)); - this.read = this.write = 0; - return this; -}; + signature = sigSSHToASN1(signature, realKeyAlgo); + if (signature !== undefined) { + const sessionID = self._kex.sessionID; + const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); + writeUInt32BE(blob, sessionID.length, 0); + blob.set(sessionID, 4); + blob.set( + new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), + 4 + sessionID.length + ); + methodData = { + keyAlgo: realKeyAlgo, + key, + signature, + blob, + localHostname, + localUsername, + hashAlgo + }; + } + } + break; + } + case 'keyboard-interactive': + /* + string language tag (as defined in [RFC-3066]) + string submethods (ISO-10646 UTF-8) + */ + // Skip/ignore language field -- it's deprecated in RFC 4256 + bufferParser.skipString(); -/** - * Shortens this buffer by triming bytes off of the end of this buffer. - * - * @param count the number of bytes to trim off. - * - * @return this buffer. - */ -util.DataBuffer.prototype.truncate = function(count) { - this.write = Math.max(0, this.length() - count); - this.read = Math.min(this.read, this.write); - return this; -}; + methodData = bufferParser.readList(); + break; + default: + if (method !== undefined) + methodData = bufferParser.readRaw(); + } + bufferParser.clear(); -/** - * Converts this buffer to a hexadecimal string. - * - * @return a hexadecimal string. - */ -util.DataBuffer.prototype.toHex = function() { - var rval = ''; - for(var i = this.read; i < this.data.byteLength; ++i) { - var b = this.data.getUint8(i); - if(b < 16) { - rval += '0'; + if (methodData === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_REQUEST packet' + ); } - rval += b.toString(16); - } - return rval; -}; -/** - * Converts this buffer to a string, using the given encoding. If no - * encoding is given, 'utf8' (UTF-8) is used. - * - * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', - * 'base64' (default: 'utf8'). - * - * @return a string representation of the bytes in this buffer. - */ -util.DataBuffer.prototype.toString = function(encoding) { - var view = new Uint8Array(this.data, this.read, this.length()); - encoding = encoding || 'utf8'; + if (methodDesc === undefined) + methodDesc = method; - // encode to string - if(encoding === 'binary' || encoding === 'raw') { - return util.binary.raw.encode(view); - } - if(encoding === 'hex') { - return util.binary.hex.encode(view); - } - if(encoding === 'base64') { - return util.binary.base64.encode(view); - } + self._authsQueue.push(method); - // decode to text - if(encoding === 'utf8') { - return util.text.utf8.decode(view); - } - if(encoding === 'utf16') { - return util.text.utf16.decode(view); - } + self._debug + && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); - throw new Error('Invalid encoding: ' + encoding); -}; + const handler = self._handlers.USERAUTH_REQUEST; + handler && handler(self, user, service, method, methodData); + }, + [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { + // S->C + /* + byte SSH_MSG_USERAUTH_FAILURE + name-list authentications that can continue + boolean partial success + */ + bufferParser.init(payload, 1); + const authMethods = bufferParser.readList(); + const partialSuccess = bufferParser.readBool(); + bufferParser.clear(); -/** End Buffer w/UInt8Array backing */ + if (partialSuccess === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_FAILURE packet' + ); + } -/** - * Creates a buffer that stores bytes. A value may be given to populate the - * buffer with data. This value can either be string of encoded bytes or a - * regular string of characters. When passing a string of binary encoded - * bytes, the encoding `raw` should be given. This is also the default. When - * passing a string of characters, the encoding `utf8` should be given. - * - * @param [input] a string with encoded bytes to store in the buffer. - * @param [encoding] (default: 'raw', other: 'utf8'). - */ -util.createBuffer = function(input, encoding) { - // TODO: deprecate, use new ByteBuffer() instead - encoding = encoding || 'raw'; - if(input !== undefined && encoding === 'utf8') { - input = util.encodeUtf8(input); - } - return new util.ByteBuffer(input); -}; + self._debug + && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); -/** - * Fills a string with a particular value. If you want the string to be a byte - * string, pass in String.fromCharCode(theByte). - * - * @param c the character to fill the string with, use String.fromCharCode - * to fill the string with a byte value. - * @param n the number of characters of value c to fill with. - * - * @return the filled string. - */ -util.fillString = function(c, n) { - var s = ''; - while(n > 0) { - if(n & 1) { - s += c; - } - n >>>= 1; - if(n > 0) { - c += c; - } - } - return s; -}; + self._authsQueue.shift(); + const handler = self._handlers.USERAUTH_FAILURE; + handler && handler(self, authMethods, partialSuccess); + }, + [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { + // S->C + /* + byte SSH_MSG_USERAUTH_SUCCESS + */ + self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); -/** - * Performs a per byte XOR between two byte strings and returns the result as a - * string of bytes. - * - * @param s1 first string of bytes. - * @param s2 second string of bytes. - * @param n the number of bytes to XOR. - * - * @return the XOR'd result. - */ -util.xorBytes = function(s1, s2, n) { - var s3 = ''; - var b = ''; - var t = ''; - var i = 0; - var c = 0; - for(; n > 0; --n, ++i) { - b = s1.charCodeAt(i) ^ s2.charCodeAt(i); - if(c >= 10) { - s3 += t; - t = ''; - c = 0; - } - t += String.fromCharCode(b); - ++c; - } - s3 += t; - return s3; -}; + self._authsQueue.shift(); + const handler = self._handlers.USERAUTH_SUCCESS; + handler && handler(self); + }, + [MESSAGE.USERAUTH_BANNER]: (self, payload) => { + // S->C + /* + byte SSH_MSG_USERAUTH_BANNER + string message in ISO-10646 UTF-8 encoding [RFC3629] + string language tag [RFC3066] + */ + bufferParser.init(payload, 1); + const msg = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); -/** - * Converts a hex string into a 'binary' encoded string of bytes. - * - * @param hex the hexadecimal string to convert. - * - * @return the binary-encoded string of bytes. - */ -util.hexToBytes = function(hex) { - // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." - var rval = ''; - var i = 0; - if(hex.length & 1 == 1) { - // odd number of characters, convert first character alone - i = 1; - rval += String.fromCharCode(parseInt(hex[0], 16)); - } - // convert 2 characters (1 byte) at a time - for(; i < hex.length; i += 2) { - rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - } - return rval; -}; + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_BANNER packet' + ); + } -/** - * Converts a 'binary' encoded string of bytes to hex. - * - * @param bytes the byte string to convert. - * - * @return the string of hexadecimal characters. - */ -util.bytesToHex = function(bytes) { - // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." - return util.createBuffer(bytes).toHex(); -}; + self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); -/** - * Converts an 32-bit integer to 4-big-endian byte string. - * - * @param i the integer. - * - * @return the byte string. - */ -util.int32ToBytes = function(i) { - return ( - String.fromCharCode(i >> 24 & 0xFF) + - String.fromCharCode(i >> 16 & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i & 0xFF)); -}; + const handler = self._handlers.USERAUTH_BANNER; + handler && handler(self, msg); + }, -// base64 characters, reverse mapping -var _base64 = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -var _base64Idx = [ -/*43 -43 = 0*/ -/*'+', 1, 2, 3,'/' */ - 62, -1, -1, -1, 63, + // User auth protocol -- method-specific ===================================== + 60: (self, payload) => { + if (!self._authsQueue.length) { + self._debug + && self._debug('Inbound: Received payload type 60 without auth'); + return; + } -/*'0','1','2','3','4','5','6','7','8','9' */ - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, + switch (self._authsQueue[0]) { + case 'password': { + // S->C + /* + byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ + string prompt in ISO-10646 UTF-8 encoding [RFC3629] + string language tag [RFC3066] + */ + bufferParser.init(payload, 1); + const prompt = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); -/*15, 16, 17,'=', 19, 20, 21 */ - -1, -1, -1, 64, -1, -1, -1, + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' + ); + } -/*65 - 43 = 22*/ -/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + self._debug + && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); -/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ - 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; + handler && handler(self, prompt); + break; + } + case 'publickey': { + // S->C + /* + byte SSH_MSG_USERAUTH_PK_OK + string public key algorithm name from the request + string public key blob from the request + */ + bufferParser.init(payload, 1); + const keyAlgo = bufferParser.readString(true); + const key = bufferParser.readString(); + bufferParser.clear(); -/*91 - 43 = 48 */ -/*48, 49, 50, 51, 52, 53 */ - -1, -1, -1, -1, -1, -1, + if (key === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_PK_OK packet' + ); + } -/*97 - 43 = 54*/ -/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ - 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); -/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 -]; + self._authsQueue.shift(); + const handler = self._handlers.USERAUTH_PK_OK; + handler && handler(self, keyAlgo, key); + break; + } + case 'keyboard-interactive': { + // S->C + /* + byte SSH_MSG_USERAUTH_INFO_REQUEST + string name (ISO-10646 UTF-8) + string instruction (ISO-10646 UTF-8) + string language tag (as defined in [RFC-3066]) + int num-prompts + string prompt[1] (ISO-10646 UTF-8) + boolean echo[1] + ... + string prompt[num-prompts] (ISO-10646 UTF-8) + boolean echo[num-prompts] + */ + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + const instructions = bufferParser.readString(true); + bufferParser.readString(); // skip lang + const numPrompts = bufferParser.readUInt32BE(); + let prompts; + if (numPrompts !== undefined) { + prompts = new Array(numPrompts); + let i; + for (i = 0; i < numPrompts; ++i) { + const prompt = bufferParser.readString(true); + const echo = bufferParser.readBool(); + if (echo === undefined) + break; + prompts[i] = { prompt, echo }; + } + if (i !== numPrompts) + prompts = undefined; + } + bufferParser.clear(); -// base58 characters (Bitcoin alphabet) -var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + if (prompts === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' + ); + } -/** - * Base64 encodes a 'binary' encoded string of bytes. - * - * @param input the binary encoded string of bytes to base64-encode. - * @param maxline the maximum number of encoded characters per line to use, - * defaults to none. - * - * @return the base64-encoded output. - */ -util.encode64 = function(input, maxline) { - // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." - var line = ''; - var output = ''; - var chr1, chr2, chr3; - var i = 0; - while(i < input.length) { - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); + self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); - // encode 4 character group - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); - if(isNaN(chr2)) { - line += '=='; - } else { - line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); - line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + const handler = self._handlers.USERAUTH_INFO_REQUEST; + handler && handler(self, name, instructions, prompts); + break; + } + default: + self._debug + && self._debug('Inbound: Received unexpected payload type 60'); + } + }, + 61: (self, payload) => { + if (!self._authsQueue.length) { + self._debug + && self._debug('Inbound: Received payload type 61 without auth'); + return; + } + /* + byte SSH_MSG_USERAUTH_INFO_RESPONSE + int num-responses + string response[1] (ISO-10646 UTF-8) + ... + string response[num-responses] (ISO-10646 UTF-8) + */ + if (self._authsQueue[0] !== 'keyboard-interactive') { + return doFatalError( + self, + 'Inbound: Received unexpected payload type 61' + ); + } + bufferParser.init(payload, 1); + const numResponses = bufferParser.readUInt32BE(); + let responses; + if (numResponses !== undefined) { + responses = new Array(numResponses); + let i; + for (i = 0; i < numResponses; ++i) { + const response = bufferParser.readString(true); + if (response === undefined) + break; + responses[i] = response; + } + if (i !== numResponses) + responses = undefined; } + bufferParser.clear(); - if(maxline && line.length > maxline) { - output += line.substr(0, maxline) + '\r\n'; - line = line.substr(maxline); + if (responses === undefined) { + return doFatalError( + self, + 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' + ); } - } - output += line; - return output; -}; - -/** - * Base64 decodes a string into a 'binary' encoded string of bytes. - * - * @param input the base64-encoded input. - * - * @return the binary encoded string. - */ -util.decode64 = function(input) { - // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." - // remove all non-base64 characters - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); - - var output = ''; - var enc1, enc2, enc3, enc4; - var i = 0; + self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); - while(i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + const handler = self._handlers.USERAUTH_INFO_RESPONSE; + handler && handler(self, responses); + }, - output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); - if(enc3 !== 64) { - // decoded at least 2 bytes - output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); - if(enc4 !== 64) { - // decoded 3 bytes - output += String.fromCharCode(((enc3 & 3) << 6) | enc4); + // Connection protocol -- generic ============================================ + [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { + /* + byte SSH_MSG_GLOBAL_REQUEST + string request name in US-ASCII only + boolean want reply + .... request-specific data follows + */ + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + const wantReply = bufferParser.readBool(); + let data; + if (wantReply !== undefined) { + switch (name) { + case 'tcpip-forward': + case 'cancel-tcpip-forward': { + /* + string address to bind (e.g., "0.0.0.0") + uint32 port number to bind + */ + const bindAddr = bufferParser.readString(true); + const bindPort = bufferParser.readUInt32BE(); + if (bindPort !== undefined) + data = { bindAddr, bindPort }; + break; + } + case 'streamlocal-forward@openssh.com': + case 'cancel-streamlocal-forward@openssh.com': { + /* + string socket path + */ + const socketPath = bufferParser.readString(true); + if (socketPath !== undefined) + data = { socketPath }; + break; + } + case 'no-more-sessions@openssh.com': + data = null; + break; + case 'hostkeys-00@openssh.com': { + data = []; + while (bufferParser.avail() > 0) { + const keyRaw = bufferParser.readString(); + if (keyRaw === undefined) { + data = undefined; + break; + } + const key = parseKey(keyRaw); + if (!(key instanceof Error)) + data.push(key); + } + break; + } + default: + data = bufferParser.readRaw(); } } - } + bufferParser.clear(); - return output; -}; + if (data === undefined) { + return doFatalError( + self, + 'Inbound: Malformed GLOBAL_REQUEST packet' + ); + } -/** - * Encodes the given string of characters (a standard JavaScript - * string) as a binary encoded string where the bytes represent - * a UTF-8 encoded string of characters. Non-ASCII characters will be - * encoded as multiple bytes according to UTF-8. - * - * @param str a standard string of characters to encode. - * - * @return the binary encoded string. - */ -util.encodeUtf8 = function(str) { - return unescape(encodeURIComponent(str)); -}; + self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); -/** - * Decodes a binary encoded string that contains bytes that - * represent a UTF-8 encoded string of characters -- into a - * string of characters (a standard JavaScript string). - * - * @param str the binary encoded string to decode. - * - * @return the resulting standard string of characters. - */ -util.decodeUtf8 = function(str) { - return decodeURIComponent(escape(str)); -}; + const handler = self._handlers.GLOBAL_REQUEST; + if (handler) + handler(self, name, wantReply, data); + else + self.requestFailure(); // Auto reject + }, + [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { + /* + byte SSH_MSG_REQUEST_SUCCESS + .... response specific data + */ + const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); -// binary encoding/decoding tools -// FIXME: Experimental. Do not use yet. -util.binary = { - raw: {}, - hex: {}, - base64: {}, - base58: {}, - baseN : { - encode: baseN.encode, - decode: baseN.decode - } -}; + self._debug && self._debug('Inbound: REQUEST_SUCCESS'); -/** - * Encodes a Uint8Array as a binary-encoded string. This encoding uses - * a value between 0 and 255 for each character. - * - * @param bytes the Uint8Array to encode. - * - * @return the binary-encoded string. - */ -util.binary.raw.encode = function(bytes) { - return String.fromCharCode.apply(null, bytes); -}; + const handler = self._handlers.REQUEST_SUCCESS; + handler && handler(self, data); + }, + [MESSAGE.REQUEST_FAILURE]: (self, payload) => { + /* + byte SSH_MSG_REQUEST_FAILURE + */ + self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); -/** - * Decodes a binary-encoded string to a Uint8Array. This encoding uses - * a value between 0 and 255 for each character. - * - * @param str the binary-encoded string to decode. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util.binary.raw.decode = function(str, output, offset) { - var out = output; - if(!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for(var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? (j - offset) : out; -}; + const handler = self._handlers.REQUEST_FAILURE; + handler && handler(self); + }, -/** - * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or - * ByteBuffer as a string of hexadecimal characters. - * - * @param bytes the bytes to convert. - * - * @return the string of hexadecimal characters. - */ -util.binary.hex.encode = util.bytesToHex; + // Connection protocol -- channel-related ==================================== + [MESSAGE.CHANNEL_OPEN]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_OPEN + string channel type in US-ASCII only + uint32 sender channel + uint32 initial window size + uint32 maximum packet size + .... channel type specific data follows + */ + bufferParser.init(payload, 1); + const type = bufferParser.readString(true); + const sender = bufferParser.readUInt32BE(); + const window = bufferParser.readUInt32BE(); + const packetSize = bufferParser.readUInt32BE(); + let channelInfo; -/** - * Decodes a hex-encoded string to a Uint8Array. - * - * @param hex the hexadecimal string to convert. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util.binary.hex.decode = function(hex, output, offset) { - var out = output; - if(!out) { - out = new Uint8Array(Math.ceil(hex.length / 2)); - } - offset = offset || 0; - var i = 0, j = offset; - if(hex.length & 1) { - // odd number of characters, convert first character alone - i = 1; - out[j++] = parseInt(hex[0], 16); - } - // convert 2 characters (1 byte) at a time - for(; i < hex.length; i += 2) { - out[j++] = parseInt(hex.substr(i, 2), 16); - } - return output ? (j - offset) : out; -}; + switch (type) { + case 'forwarded-tcpip': // S->C + case 'direct-tcpip': { // C->S + /* + string address that was connected / host to connect + uint32 port that was connected / port to connect + string originator IP address + uint32 originator port + */ + const destIP = bufferParser.readString(true); + const destPort = bufferParser.readUInt32BE(); + const srcIP = bufferParser.readString(true); + const srcPort = bufferParser.readUInt32BE(); + if (srcPort !== undefined) { + channelInfo = { + type, + sender, + window, + packetSize, + data: { destIP, destPort, srcIP, srcPort } + }; + } + break; + } + case 'forwarded-streamlocal@openssh.com': // S->C + case 'direct-streamlocal@openssh.com': { // C->S + /* + string socket path + string reserved for future use -/** - * Base64-encodes a Uint8Array. - * - * @param input the Uint8Array to encode. - * @param maxline the maximum number of encoded characters per line to use, - * defaults to none. - * - * @return the base64-encoded output string. - */ -util.binary.base64.encode = function(input, maxline) { - var line = ''; - var output = ''; - var chr1, chr2, chr3; - var i = 0; - while(i < input.byteLength) { - chr1 = input[i++]; - chr2 = input[i++]; - chr3 = input[i++]; + (direct-streamlocal@openssh.com additionally has:) + uint32 reserved + */ + const socketPath = bufferParser.readString(true); + if (socketPath !== undefined) { + channelInfo = { + type, + sender, + window, + packetSize, + data: { socketPath } + }; + } + break; + } + case 'x11': { // S->C + /* + string originator address (e.g., "192.168.7.38") + uint32 originator port + */ + const srcIP = bufferParser.readString(true); + const srcPort = bufferParser.readUInt32BE(); + if (srcPort !== undefined) { + channelInfo = { + type, + sender, + window, + packetSize, + data: { srcIP, srcPort } + }; + } + break; + } + default: + // Includes: + // 'session' (C->S) + // 'auth-agent@openssh.com' (S->C) + channelInfo = { + type, + sender, + window, + packetSize, + data: {} + }; + } + bufferParser.clear(); - // encode 4 character group - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); - if(isNaN(chr2)) { - line += '=='; + if (channelInfo === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_OPEN packet' + ); + } + + self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); + + const handler = self._handlers.CHANNEL_OPEN; + if (handler) { + handler(self, channelInfo); } else { - line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); - line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + self.channelOpenFail( + channelInfo.sender, + CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, + '', + '' + ); } + }, + [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION + uint32 recipient channel + uint32 sender channel + uint32 initial window size + uint32 maximum packet size + .... channel type specific data follows + */ + // "The 'recipient channel' is the channel number given in the + // original open request, and 'sender channel' is the channel number + // allocated by the other side." + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const sender = bufferParser.readUInt32BE(); + const window = bufferParser.readUInt32BE(); + const packetSize = bufferParser.readUInt32BE(); + const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); + bufferParser.clear(); - if(maxline && line.length > maxline) { - output += line.substr(0, maxline) + '\r\n'; - line = line.substr(maxline); + if (packetSize === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' + ); } - } - output += line; - return output; -}; -/** - * Decodes a base64-encoded string to a Uint8Array. - * - * @param input the base64-encoded input string. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util.binary.base64.decode = function(input, output, offset) { - var out = output; - if(!out) { - out = new Uint8Array(Math.ceil(input.length / 4) * 3); - } + self._debug && self._debug( + `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` + ); - // remove all non-base64 characters - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; + if (handler) + handler(self, { recipient, sender, window, packetSize, data }); + }, + [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_OPEN_FAILURE + uint32 recipient channel + uint32 reason code + string description in ISO-10646 UTF-8 encoding [RFC3629] + string language tag [RFC3066] + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const reason = bufferParser.readUInt32BE(); + const description = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); - offset = offset || 0; - var enc1, enc2, enc3, enc4; - var i = 0, j = offset; + if (lang === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' + ); + } - while(i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + self._debug + && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); - out[j++] = (enc1 << 2) | (enc2 >> 4); - if(enc3 !== 64) { - // decoded at least 2 bytes - out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); - if(enc4 !== 64) { - // decoded 3 bytes - out[j++] = ((enc3 & 3) << 6) | enc4; - } + const handler = self._handlers.CHANNEL_OPEN_FAILURE; + handler && handler(self, recipient, reason, description); + }, + [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_WINDOW_ADJUST + uint32 recipient channel + uint32 bytes to add + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const bytesToAdd = bufferParser.readUInt32BE(); + bufferParser.clear(); + + if (bytesToAdd === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' + ); + } + + self._debug && self._debug( + `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` + ); + + const handler = self._handlers.CHANNEL_WINDOW_ADJUST; + handler && handler(self, recipient, bytesToAdd); + }, + [MESSAGE.CHANNEL_DATA]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_DATA + uint32 recipient channel + string data + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const data = bufferParser.readString(); + bufferParser.clear(); + + if (data === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_DATA packet' + ); } - } - // make sure result is the exact decoded length - return output ? (j - offset) : out.subarray(0, j); -}; + self._debug + && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); -// add support for base58 encoding/decoding with Bitcoin alphabet -util.binary.base58.encode = function(input, maxline) { - return util.binary.baseN.encode(input, _base58, maxline); -}; -util.binary.base58.decode = function(input, maxline) { - return util.binary.baseN.decode(input, _base58, maxline); -}; + const handler = self._handlers.CHANNEL_DATA; + handler && handler(self, recipient, data); + }, + [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_EXTENDED_DATA + uint32 recipient channel + uint32 data_type_code + string data + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const type = bufferParser.readUInt32BE(); + const data = bufferParser.readString(); + bufferParser.clear(); -// text encoding/decoding tools -// FIXME: Experimental. Do not use yet. -util.text = { - utf8: {}, - utf16: {} -}; + if (data === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' + ); + } -/** - * Encodes the given string as UTF-8 in a Uint8Array. - * - * @param str the string to encode. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util.text.utf8.encode = function(str, output, offset) { - str = util.encodeUtf8(str); - var out = output; - if(!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for(var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? (j - offset) : out; -}; + self._debug && self._debug( + `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` + ); -/** - * Decodes the UTF-8 contents from a Uint8Array. - * - * @param bytes the Uint8Array to decode. - * - * @return the resulting string. - */ -util.text.utf8.decode = function(bytes) { - return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); -}; + const handler = self._handlers.CHANNEL_EXTENDED_DATA; + handler && handler(self, recipient, data, type); + }, + [MESSAGE.CHANNEL_EOF]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_EOF + uint32 recipient channel + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); -/** - * Encodes the given string as UTF-16 in a Uint8Array. - * - * @param str the string to encode. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util.text.utf16.encode = function(str, output, offset) { - var out = output; - if(!out) { - out = new Uint8Array(str.length * 2); - } - var view = new Uint16Array(out.buffer); - offset = offset || 0; - var j = offset; - var k = offset; - for(var i = 0; i < str.length; ++i) { - view[k++] = str.charCodeAt(i); - j += 2; - } - return output ? (j - offset) : out; -}; + if (recipient === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_EOF packet' + ); + } -/** - * Decodes the UTF-16 contents from a Uint8Array. - * - * @param bytes the Uint8Array to decode. - * - * @return the resulting string. - */ -util.text.utf16.decode = function(bytes) { - return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); -}; + self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); -/** - * Deflates the given data using a flash interface. - * - * @param api the flash interface. - * @param bytes the data. - * @param raw true to return only raw deflate data, false to include zlib - * header and trailer. - * - * @return the deflated data as a string. - */ -util.deflate = function(api, bytes, raw) { - bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); + const handler = self._handlers.CHANNEL_EOF; + handler && handler(self, recipient); + }, + [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_CLOSE + uint32 recipient channel + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); - // strip zlib header and trailer if necessary - if(raw) { - // zlib header is 2 bytes (CMF,FLG) where FLG indicates that - // there is a 4-byte DICT (alder-32) block before the data if - // its 5th bit is set - var start = 2; - var flg = bytes.charCodeAt(1); - if(flg & 0x20) { - start = 6; + if (recipient === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_CLOSE packet' + ); } - // zlib trailer is 4 bytes of adler-32 - bytes = bytes.substring(start, bytes.length - 4); - } - - return bytes; -}; -/** - * Inflates the given data using a flash interface. - * - * @param api the flash interface. - * @param bytes the data. - * @param raw true if the incoming data has no zlib header or trailer and is - * raw DEFLATE data. - * - * @return the inflated data as a string, null on error. - */ -util.inflate = function(api, bytes, raw) { - // TODO: add zlib header and trailer if necessary/possible - var rval = api.inflate(util.encode64(bytes)).rval; - return (rval === null) ? null : util.decode64(rval); -}; + self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); -/** - * Sets a storage object. - * - * @param api the storage interface. - * @param id the storage ID to use. - * @param obj the storage object, null to remove. - */ -var _setStorageObject = function(api, id, obj) { - if(!api) { - throw new Error('WebStorage not available.'); - } + const handler = self._handlers.CHANNEL_CLOSE; + handler && handler(self, recipient); + }, + [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_REQUEST + uint32 recipient channel + string request type in US-ASCII characters only + boolean want reply + .... type-specific data follows + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const type = bufferParser.readString(true); + const wantReply = bufferParser.readBool(); + let data; + if (wantReply !== undefined) { + switch (type) { + case 'exit-status': // S->C + /* + uint32 exit_status + */ + data = bufferParser.readUInt32BE(); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'exit-signal': { // S->C + /* + string signal name (without the "SIG" prefix) + boolean core dumped + string error message in ISO-10646 UTF-8 encoding + string language tag + */ + let signal; + let coreDumped; + if (self._compatFlags & COMPAT.OLD_EXIT) { + /* + Instead of `signal name` and `core dumped`, we have just: + uint32 signal number + */ + const num = bufferParser.readUInt32BE(); + switch (num) { + case 1: + signal = 'HUP'; + break; + case 2: + signal = 'INT'; + break; + case 3: + signal = 'QUIT'; + break; + case 6: + signal = 'ABRT'; + break; + case 9: + signal = 'KILL'; + break; + case 14: + signal = 'ALRM'; + break; + case 15: + signal = 'TERM'; + break; + default: + if (num !== undefined) { + // Unknown or OS-specific + signal = `UNKNOWN (${num})`; + } + } + coreDumped = false; + } else { + signal = bufferParser.readString(true); + coreDumped = bufferParser.readBool(); + if (coreDumped === undefined) + signal = undefined; + } + const errorMessage = bufferParser.readString(true); + if (bufferParser.skipString() !== undefined) + data = { signal, coreDumped, errorMessage }; + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` + ); + break; + } + case 'pty-req': { // C->S + /* + string TERM environment variable value (e.g., vt100) + uint32 terminal width, characters (e.g., 80) + uint32 terminal height, rows (e.g., 24) + uint32 terminal width, pixels (e.g., 640) + uint32 terminal height, pixels (e.g., 480) + string encoded terminal modes + */ + const term = bufferParser.readString(true); + const cols = bufferParser.readUInt32BE(); + const rows = bufferParser.readUInt32BE(); + const width = bufferParser.readUInt32BE(); + const height = bufferParser.readUInt32BE(); + const modesBinary = bufferParser.readString(); + if (modesBinary !== undefined) { + bufferParser.init(modesBinary, 1); + let modes = {}; + while (bufferParser.avail()) { + const opcode = bufferParser.readByte(); + if (opcode === TERMINAL_MODE.TTY_OP_END) + break; + const name = TERMINAL_MODE_BY_VALUE[opcode]; + const value = bufferParser.readUInt32BE(); + if (opcode === undefined + || name === undefined + || value === undefined) { + modes = undefined; + break; + } + modes[name] = value; + } + if (modes !== undefined) + data = { term, cols, rows, width, height, modes }; + } + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case 'window-change': { // C->S + /* + uint32 terminal width, columns + uint32 terminal height, rows + uint32 terminal width, pixels + uint32 terminal height, pixels + */ + const cols = bufferParser.readUInt32BE(); + const rows = bufferParser.readUInt32BE(); + const width = bufferParser.readUInt32BE(); + const height = bufferParser.readUInt32BE(); + if (height !== undefined) + data = { cols, rows, width, height }; + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case 'x11-req': { // C->S + /* + boolean single connection + string x11 authentication protocol + string x11 authentication cookie + uint32 x11 screen number + */ + const single = bufferParser.readBool(); + const protocol = bufferParser.readString(true); + const cookie = bufferParser.readString(); + const screen = bufferParser.readUInt32BE(); + if (screen !== undefined) + data = { single, protocol, cookie, screen }; + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case 'env': { // C->S + /* + string variable name + string variable value + */ + const name = bufferParser.readString(true); + const value = bufferParser.readString(true); + if (value !== undefined) + data = { name, value }; + if (self._debug) { + self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` + + `${name}=${value})` + ); + } + break; + } + case 'shell': // C->S + data = null; // No extra data + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + case 'exec': // C->S + /* + string command + */ + data = bufferParser.readString(true); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'subsystem': // C->S + /* + string subsystem name + */ + data = bufferParser.readString(true); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'signal': // C->S + /* + string signal name (without the "SIG" prefix) + */ + data = bufferParser.readString(true); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'xon-xoff': // C->S + /* + boolean client can do + */ + data = bufferParser.readBool(); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case 'auth-agent-req@openssh.com': // C-S + data = null; // No extra data + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + default: + data = (bufferParser.avail() ? bufferParser.readRaw() : null); + self._debug && self._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + } + } + bufferParser.clear(); - var rval; - if(obj === null) { - rval = api.removeItem(id); - } else { - // json-encode and base64-encode object - obj = util.encode64(JSON.stringify(obj)); - rval = api.setItem(id, obj); - } + if (data === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_REQUEST packet' + ); + } - // handle potential flash error - if(typeof(rval) !== 'undefined' && rval.rval !== true) { - var error = new Error(rval.error.message); - error.id = rval.error.id; - error.name = rval.error.name; - throw error; - } -}; + const handler = self._handlers.CHANNEL_REQUEST; + handler && handler(self, recipient, type, wantReply, data); + }, + [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_SUCCESS + uint32 recipient channel + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); -/** - * Gets a storage object. - * - * @param api the storage interface. - * @param id the storage ID to use. - * - * @return the storage object entry or null if none exists. - */ -var _getStorageObject = function(api, id) { - if(!api) { - throw new Error('WebStorage not available.'); - } + if (recipient === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_SUCCESS packet' + ); + } - // get the existing entry - var rval = api.getItem(id); + self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); - /* Note: We check api.init because we can't do (api == localStorage) - on IE because of "Class doesn't support Automation" exception. Only - the flash api has an init method so this works too, but we need a - better solution in the future. */ + const handler = self._handlers.CHANNEL_SUCCESS; + handler && handler(self, recipient); + }, + [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { + /* + byte SSH_MSG_CHANNEL_FAILURE + uint32 recipient channel + */ + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); - // flash returns item wrapped in an object, handle special case - if(api.init) { - if(rval.rval === null) { - if(rval.error) { - var error = new Error(rval.error.message); - error.id = rval.error.id; - error.name = rval.error.name; - throw error; - } - // no error, but also no item - rval = null; - } else { - rval = rval.rval; + if (recipient === undefined) { + return doFatalError( + self, + 'Inbound: Malformed CHANNEL_FAILURE packet' + ); } - } - // handle decoding - if(rval !== null) { - // base64-decode and json-decode data - rval = JSON.parse(util.decode64(rval)); - } + self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); - return rval; + const handler = self._handlers.CHANNEL_FAILURE; + handler && handler(self, recipient); + }, }; -/** - * Stores an item in local storage. - * - * @param api the storage interface. - * @param id the storage ID to use. - * @param key the key for the item. - * @param data the data for the item (any javascript object/primitive). - */ -var _setItem = function(api, id, key, data) { - // get storage object - var obj = _getStorageObject(api, id); - if(obj === null) { - // create a new storage object - obj = {}; - } - // update key - obj[key] = data; - // set storage object - _setStorageObject(api, id, obj); -}; +/***/ }), -/** - * Gets an item from local storage. - * - * @param api the storage interface. - * @param id the storage ID to use. - * @param key the key for the item. - * - * @return the item. - */ -var _getItem = function(api, id, key) { - // get storage object - var rval = _getStorageObject(api, id); - if(rval !== null) { - // return data at key - rval = (key in rval) ? rval[key] : null; - } +/***/ 4126: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return rval; -}; +"use strict"; -/** - * Removes an item from local storage. - * - * @param api the storage interface. - * @param id the storage ID to use. - * @param key the key for the item. - */ -var _removeItem = function(api, id, key) { - // get storage object - var obj = _getStorageObject(api, id); - if(obj !== null && key in obj) { - // remove key - delete obj[key]; - // see if entry has no keys remaining - var empty = true; - for(var prop in obj) { - empty = false; - break; - } - if(empty) { - // remove entry entirely if no keys are left - obj = null; - } +const { + createDiffieHellman, + createDiffieHellmanGroup, + createECDH, + createHash, + createPublicKey, + diffieHellman, + generateKeyPairSync, + randomFillSync, +} = __nccwpck_require__(6113); - // set storage object - _setStorageObject(api, id, obj); - } -}; +const { Ber } = __nccwpck_require__(970); -/** - * Clears the local disk storage identified by the given ID. - * - * @param api the storage interface. - * @param id the storage ID to use. - */ -var _clearItems = function(api, id) { - _setStorageObject(api, id, null); -}; +const { + COMPAT, + curve25519Supported, + DEFAULT_KEX, + DEFAULT_SERVER_HOST_KEY, + DEFAULT_CIPHER, + DEFAULT_MAC, + DEFAULT_COMPRESSION, + DISCONNECT_REASON, + MESSAGE, +} = __nccwpck_require__(6832); +const { + CIPHER_INFO, + createCipher, + createDecipher, + MAC_INFO, +} = __nccwpck_require__(5708); +const { parseDERKey } = __nccwpck_require__(2218); +const { + bufferFill, + bufferParser, + convertSignature, + doFatalError, + FastBuffer, + sigSSHToASN1, + writeUInt32BE, +} = __nccwpck_require__(9475); +const { + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter, +} = __nccwpck_require__(6715); -/** - * Calls a storage function. - * - * @param func the function to call. - * @param args the arguments for the function. - * @param location the location argument. - * - * @return the return value from the function. - */ -var _callStorageFunction = function(func, args, location) { - var rval = null; +let MESSAGE_HANDLERS; - // default storage types - if(typeof(location) === 'undefined') { - location = ['web', 'flash']; - } +const GEX_MIN_BITS = 2048; // RFC 8270 +const GEX_MAX_BITS = 8192; // RFC 8270 - // apply storage types in order of preference - var type; - var done = false; - var exception = null; - for(var idx in location) { - type = location[idx]; - try { - if(type === 'flash' || type === 'both') { - if(args[0] === null) { - throw new Error('Flash local storage not available.'); +const EMPTY_BUFFER = Buffer.alloc(0); + +// Client/Server +function kexinit(self) { + /* + byte SSH_MSG_KEXINIT + byte[16] cookie (random bytes) + name-list kex_algorithms + name-list server_host_key_algorithms + name-list encryption_algorithms_client_to_server + name-list encryption_algorithms_server_to_client + name-list mac_algorithms_client_to_server + name-list mac_algorithms_server_to_client + name-list compression_algorithms_client_to_server + name-list compression_algorithms_server_to_client + name-list languages_client_to_server + name-list languages_server_to_client + boolean first_kex_packet_follows + uint32 0 (reserved for future extension) + */ + + let payload; + if (self._compatFlags & COMPAT.BAD_DHGEX) { + const entry = self._offer.lists.kex; + let kex = entry.array; + let found = false; + for (let i = 0; i < kex.length; ++i) { + if (kex[i].includes('group-exchange')) { + if (!found) { + found = true; + // Copy array lazily + kex = kex.slice(); } - rval = func.apply(this, args); - done = (type === 'flash'); - } - if(type === 'web' || type === 'both') { - args[0] = localStorage; - rval = func.apply(this, args); - done = true; + kex.splice(i--, 1); } - } catch(ex) { - exception = ex; } - if(done) { - break; + if (found) { + let len = 1 + 16 + self._offer.totalSize + 1 + 4; + const newKexBuf = Buffer.from(kex.join(',')); + len -= (entry.buffer.length - newKexBuf.length); + + const all = self._offer.lists.all; + const rest = new Uint8Array( + all.buffer, + all.byteOffset + 4 + entry.buffer.length, + all.length - (4 + entry.buffer.length) + ); + + payload = Buffer.allocUnsafe(len); + writeUInt32BE(payload, newKexBuf.length, 17); + payload.set(newKexBuf, 17 + 4); + payload.set(rest, 17 + 4 + newKexBuf.length); } } - if(!done) { - throw exception; + if (payload === undefined) { + payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); + self._offer.copyAllTo(payload, 17); } - return rval; -}; + self._debug && self._debug('Outbound: Sending KEXINIT'); -/** - * Stores an item on local disk. - * - * The available types of local storage include 'flash', 'web', and 'both'. - * - * The type 'flash' refers to flash local storage (SharedObject). In order - * to use flash local storage, the 'api' parameter must be valid. The type - * 'web' refers to WebStorage, if supported by the browser. The type 'both' - * refers to storing using both 'flash' and 'web', not just one or the - * other. - * - * The location array should list the storage types to use in order of - * preference: - * - * ['flash']: flash only storage - * ['web']: web only storage - * ['both']: try to store in both - * ['flash','web']: store in flash first, but if not available, 'web' - * ['web','flash']: store in web first, but if not available, 'flash' - * - * The location array defaults to: ['web', 'flash'] - * - * @param api the flash interface, null to use only WebStorage. - * @param id the storage ID to use. - * @param key the key for the item. - * @param data the data for the item (any javascript object/primitive). - * @param location an array with the preferred types of storage to use. - */ -util.setItem = function(api, id, key, data, location) { - _callStorageFunction(_setItem, arguments, location); -}; + payload[0] = MESSAGE.KEXINIT; + randomFillSync(payload, 1, 16); -/** - * Gets an item on local disk. - * - * Set setItem() for details on storage types. - * - * @param api the flash interface, null to use only WebStorage. - * @param id the storage ID to use. - * @param key the key for the item. - * @param location an array with the preferred types of storage to use. - * - * @return the item. - */ -util.getItem = function(api, id, key, location) { - return _callStorageFunction(_getItem, arguments, location); -}; + // Zero-fill first_kex_packet_follows and reserved bytes + bufferFill(payload, 0, payload.length - 5); -/** - * Removes an item on local disk. - * - * Set setItem() for details on storage types. - * - * @param api the flash interface. - * @param id the storage ID to use. - * @param key the key for the item. - * @param location an array with the preferred types of storage to use. - */ -util.removeItem = function(api, id, key, location) { - _callStorageFunction(_removeItem, arguments, location); -}; + self._kexinit = payload; -/** - * Clears the local disk storage identified by the given ID. - * - * Set setItem() for details on storage types. - * - * @param api the flash interface if flash is available. - * @param id the storage ID to use. - * @param location an array with the preferred types of storage to use. - */ -util.clearItems = function(api, id, location) { - _callStorageFunction(_clearItems, arguments, location); -}; + // Needed to correct the starting position in allocated "packets" when packets + // will be buffered due to active key exchange + self._packetRW.write.allocStart = 0; -/** - * Check if an object is empty. - * - * Taken from: - * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 - * - * @param object the object to check. - */ -util.isEmpty = function(obj) { - for(var prop in obj) { - if(obj.hasOwnProperty(prop)) { - return false; - } + // TODO: only create single buffer and set _kexinit as slice of packet instead + { + const p = self._packetRW.write.allocStartKEX; + const packet = self._packetRW.write.alloc(payload.length, true); + packet.set(payload, p); + self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); } - return true; -}; +} -/** - * Format with simple printf-style interpolation. - * - * %%: literal '%' - * %s,%o: convert next argument into a string. - * - * @param format the string to format. - * @param ... arguments to interpolate into the format string. - */ -util.format = function(format) { - var re = /%./g; - // current match - var match; - // current part - var part; - // current arg index - var argi = 0; - // collected parts to recombine later - var parts = []; - // last index found - var last = 0; - // loop while matches remain - while((match = re.exec(format))) { - part = format.substring(last, re.lastIndex - 2); - // don't add empty strings (ie, parts between %s%s) - if(part.length > 0) { - parts.push(part); - } - last = re.lastIndex; - // switch on % code - var code = match[0][1]; - switch(code) { - case 's': - case 'o': - // check if enough arguments were given - if(argi < arguments.length) { - parts.push(arguments[argi++ + 1]); - } else { - parts.push(''); - } - break; - // FIXME: do proper formating for numbers, etc - //case 'f': - //case 'd': - case '%': - parts.push('%'); - break; - default: - parts.push('<%' + code + '?>'); - } +function handleKexInit(self, payload) { + /* + byte SSH_MSG_KEXINIT + byte[16] cookie (random bytes) + name-list kex_algorithms + name-list server_host_key_algorithms + name-list encryption_algorithms_client_to_server + name-list encryption_algorithms_server_to_client + name-list mac_algorithms_client_to_server + name-list mac_algorithms_server_to_client + name-list compression_algorithms_client_to_server + name-list compression_algorithms_server_to_client + name-list languages_client_to_server + name-list languages_server_to_client + boolean first_kex_packet_follows + uint32 0 (reserved for future extension) + */ + const init = { + kex: undefined, + serverHostKey: undefined, + cs: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: undefined, + }, + sc: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: undefined, + }, + }; + + bufferParser.init(payload, 17); + + if ((init.kex = bufferParser.readList()) === undefined + || (init.serverHostKey = bufferParser.readList()) === undefined + || (init.cs.cipher = bufferParser.readList()) === undefined + || (init.sc.cipher = bufferParser.readList()) === undefined + || (init.cs.mac = bufferParser.readList()) === undefined + || (init.sc.mac = bufferParser.readList()) === undefined + || (init.cs.compress = bufferParser.readList()) === undefined + || (init.sc.compress = bufferParser.readList()) === undefined + || (init.cs.lang = bufferParser.readList()) === undefined + || (init.sc.lang = bufferParser.readList()) === undefined) { + bufferParser.clear(); + return doFatalError( + self, + 'Received malformed KEXINIT', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - // add trailing part of format string - parts.push(format.substring(last)); - return parts.join(''); -}; -/** - * Formats a number. - * - * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ - */ -util.formatNumber = function(number, decimals, dec_point, thousands_sep) { - // http://kevin.vanzonneveld.net - // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) - // + bugfix by: Michael White (http://crestidg.com) - // + bugfix by: Benjamin Lupton - // + bugfix by: Allan Jensen (http://www.winternet.no) - // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) - // * example 1: number_format(1234.5678, 2, '.', ''); - // * returns 1: 1234.57 + const pos = bufferParser.pos(); + const firstFollows = (pos < payload.length && payload[pos] === 1); + bufferParser.clear(); - var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; - var d = dec_point === undefined ? ',' : dec_point; - var t = thousands_sep === undefined ? - '.' : thousands_sep, s = n < 0 ? '-' : ''; - var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; - var j = (i.length > 3) ? i.length % 3 : 0; - return s + (j ? i.substr(0, j) + t : '') + - i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + - (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); -}; + const local = self._offer; + const remote = init; -/** - * Formats a byte size. - * - * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ - */ -util.formatSize = function(size) { - if(size >= 1073741824) { - size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; - } else if(size >= 1048576) { - size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; - } else if(size >= 1024) { - size = util.formatNumber(size / 1024, 0) + ' KiB'; - } else { - size = util.formatNumber(size, 0) + ' bytes'; + let localKex = local.lists.kex.array; + if (self._compatFlags & COMPAT.BAD_DHGEX) { + let found = false; + for (let i = 0; i < localKex.length; ++i) { + if (localKex[i].indexOf('group-exchange') !== -1) { + if (!found) { + found = true; + // Copy array lazily + localKex = localKex.slice(); + } + localKex.splice(i--, 1); + } + } } - return size; -}; -/** - * Converts an IPv4 or IPv6 string representation into bytes (in network order). - * - * @param ip the IPv4 or IPv6 address to convert. - * - * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't - * be parsed. - */ -util.bytesFromIP = function(ip) { - if(ip.indexOf('.') !== -1) { - return util.bytesFromIPv4(ip); - } - if(ip.indexOf(':') !== -1) { - return util.bytesFromIPv6(ip); - } - return null; -}; + let clientList; + let serverList; + let i; + const debug = self._debug; -/** - * Converts an IPv4 string representation into bytes (in network order). - * - * @param ip the IPv4 address to convert. - * - * @return the 4-byte address or null if the address can't be parsed. - */ -util.bytesFromIPv4 = function(ip) { - ip = ip.split('.'); - if(ip.length !== 4) { - return null; + debug && debug('Inbound: Handshake in progress'); + + // Key exchange method ======================================================= + debug && debug(`Handshake: (local) KEX method: ${localKex}`); + debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); + let remoteExtInfoEnabled; + if (self._server) { + serverList = localKex; + clientList = remote.kex; + remoteExtInfoEnabled = (clientList.indexOf('ext-info-c') !== -1); + } else { + serverList = remote.kex; + clientList = localKex; + remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1); } - var b = util.createBuffer(); - for(var i = 0; i < ip.length; ++i) { - var num = parseInt(ip[i], 10); - if(isNaN(num)) { - return null; + if (self._strictMode === undefined) { + if (self._server) { + self._strictMode = + (clientList.indexOf('kex-strict-c-v00@openssh.com') !== -1); + } else { + self._strictMode = + (serverList.indexOf('kex-strict-s-v00@openssh.com') !== -1); + } + // Note: We check for seqno of 1 instead of 0 since we increment before + // calling the packet handler + if (self._strictMode) { + debug && debug('Handshake: strict KEX mode enabled'); + if (self._decipher.inSeqno !== 1) { + if (debug) + debug('Handshake: KEXINIT not first packet in strict KEX mode'); + return doFatalError( + self, + 'Handshake failed: KEXINIT not first packet in strict KEX mode', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } } - b.putByte(num); } - return b.getBytes(); -}; - -/** - * Converts an IPv6 string representation into bytes (in network order). - * - * @param ip the IPv6 address to convert. - * - * @return the 16-byte address or null if the address can't be parsed. - */ -util.bytesFromIPv6 = function(ip) { - var blanks = 0; - ip = ip.split(':').filter(function(e) { - if(e.length === 0) ++blanks; - return true; - }); - var zeros = (8 - ip.length + blanks) * 2; - var b = util.createBuffer(); - for(var i = 0; i < 8; ++i) { - if(!ip[i] || ip[i].length === 0) { - b.fillWithByte(0, zeros); - zeros = 0; - continue; - } - var bytes = util.hexToBytes(ip[i]); - if(bytes.length < 2) { - b.putByte(0); - } - b.putBytes(bytes); + // Check for agreeable key exchange algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: no matching key exchange algorithm'); + return doFatalError( + self, + 'Handshake failed: no matching key exchange algorithm', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.kex = clientList[i]; + debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); + if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { + // Ignore next inbound packet, it was a wrong first guess at KEX algorithm + self._skipNextInboundPacket = true; } - return b.getBytes(); -}; -/** - * Converts 4-bytes into an IPv4 string representation or 16-bytes into - * an IPv6 string representation. The bytes must be in network order. - * - * @param bytes the bytes to convert. - * - * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, - * respectively, are given, otherwise null. - */ -util.bytesToIP = function(bytes) { - if(bytes.length === 4) { - return util.bytesToIPv4(bytes); + + // Server host key format ==================================================== + const localSrvHostKey = local.lists.serverHostKey.array; + debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); + debug && debug( + `Handshake: (remote) Host key format: ${remote.serverHostKey}` + ); + if (self._server) { + serverList = localSrvHostKey; + clientList = remote.serverHostKey; + } else { + serverList = remote.serverHostKey; + clientList = localSrvHostKey; } - if(bytes.length === 16) { - return util.bytesToIPv6(bytes); + // Check for agreeable server host key format + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching host key format'); + return doFatalError( + self, + 'Handshake failed: no matching host key format', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - return null; -}; + init.serverHostKey = clientList[i]; + debug && debug(`Handshake: Host key format: ${clientList[i]}`); -/** - * Converts 4-bytes into an IPv4 string representation. The bytes must be - * in network order. - * - * @param bytes the bytes to convert. - * - * @return the IPv4 string representation or null for an invalid # of bytes. - */ -util.bytesToIPv4 = function(bytes) { - if(bytes.length !== 4) { - return null; + + // Client->Server cipher ===================================================== + const localCSCipher = local.lists.cs.cipher.array; + debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); + debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); + if (self._server) { + serverList = localCSCipher; + clientList = remote.cs.cipher; + } else { + serverList = remote.cs.cipher; + clientList = localCSCipher; } - var ip = []; - for(var i = 0; i < bytes.length; ++i) { - ip.push(bytes.charCodeAt(i)); + // Check for agreeable client->server cipher + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching C->S cipher'); + return doFatalError( + self, + 'Handshake failed: no matching C->S cipher', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - return ip.join('.'); -}; + init.cs.cipher = clientList[i]; + debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); -/** - * Converts 16-bytes into an IPv16 string representation. The bytes must be - * in network order. - * - * @param bytes the bytes to convert. - * - * @return the IPv16 string representation or null for an invalid # of bytes. - */ -util.bytesToIPv6 = function(bytes) { - if(bytes.length !== 16) { - return null; + + // Server->Client cipher ===================================================== + const localSCCipher = local.lists.sc.cipher.array; + debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); + debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); + if (self._server) { + serverList = localSCCipher; + clientList = remote.sc.cipher; + } else { + serverList = remote.sc.cipher; + clientList = localSCCipher; } - var ip = []; - var zeroGroups = []; - var zeroMaxGroup = 0; - for(var i = 0; i < bytes.length; i += 2) { - var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); - // canonicalize zero representation - while(hex[0] === '0' && hex !== '0') { - hex = hex.substr(1); + // Check for agreeable server->client cipher + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching S->C cipher'); + return doFatalError( + self, + 'Handshake failed: no matching S->C cipher', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.sc.cipher = clientList[i]; + debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); + + + // Client->Server MAC ======================================================== + const localCSMAC = local.lists.cs.mac.array; + debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); + debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); + if (CIPHER_INFO[init.cs.cipher].authLen > 0) { + init.cs.mac = ''; + debug && debug('Handshake: C->S MAC: '); + } else { + if (self._server) { + serverList = localCSMAC; + clientList = remote.cs.mac; + } else { + serverList = remote.cs.mac; + clientList = localCSMAC; } - if(hex === '0') { - var last = zeroGroups[zeroGroups.length - 1]; - var idx = ip.length; - if(!last || idx !== last.end + 1) { - zeroGroups.push({start: idx, end: idx}); - } else { - last.end = idx; - if((last.end - last.start) > - (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { - zeroMaxGroup = zeroGroups.length - 1; - } - } + // Check for agreeable client->server hmac algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching C->S MAC'); + return doFatalError( + self, + 'Handshake failed: no matching C->S MAC', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - ip.push(hex); + init.cs.mac = clientList[i]; + debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); } - if(zeroGroups.length > 0) { - var group = zeroGroups[zeroMaxGroup]; - // only shorten group of length > 0 - if(group.end - group.start > 0) { - ip.splice(group.start, group.end - group.start + 1, ''); - if(group.start === 0) { - ip.unshift(''); - } - if(group.end === 7) { - ip.push(''); - } + + + // Server->Client MAC ======================================================== + const localSCMAC = local.lists.sc.mac.array; + debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); + debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); + if (CIPHER_INFO[init.sc.cipher].authLen > 0) { + init.sc.mac = ''; + debug && debug('Handshake: S->C MAC: '); + } else { + if (self._server) { + serverList = localSCMAC; + clientList = remote.sc.mac; + } else { + serverList = remote.sc.mac; + clientList = localSCMAC; + } + // Check for agreeable server->client hmac algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching S->C MAC'); + return doFatalError( + self, + 'Handshake failed: no matching S->C MAC', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } + init.sc.mac = clientList[i]; + debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); } - return ip.join(':'); -}; -/** - * Estimates the number of processes that can be run concurrently. If - * creating Web Workers, keep in mind that the main JavaScript process needs - * its own core. - * - * @param options the options to use: - * update true to force an update (not use the cached value). - * @param callback(err, max) called once the operation completes. - */ -util.estimateCores = function(options, callback) { - if(typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - if('cores' in util && !options.update) { - return callback(null, util.cores); + + // Client->Server compression ================================================ + const localCSCompress = local.lists.cs.compress.array; + debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); + debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); + if (self._server) { + serverList = localCSCompress; + clientList = remote.cs.compress; + } else { + serverList = remote.cs.compress; + clientList = localCSCompress; } - if(typeof navigator !== 'undefined' && - 'hardwareConcurrency' in navigator && - navigator.hardwareConcurrency > 0) { - util.cores = navigator.hardwareConcurrency; - return callback(null, util.cores); + // Check for agreeable client->server compression algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching C->S compression'); + return doFatalError( + self, + 'Handshake failed: no matching C->S compression', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - if(typeof Worker === 'undefined') { - // workers not available - util.cores = 1; - return callback(null, util.cores); + init.cs.compress = clientList[i]; + debug && debug(`Handshake: C->S compression: ${clientList[i]}`); + + + // Server->Client compression ================================================ + const localSCCompress = local.lists.sc.compress.array; + debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); + debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); + if (self._server) { + serverList = localSCCompress; + clientList = remote.sc.compress; + } else { + serverList = remote.sc.compress; + clientList = localSCCompress; } - if(typeof Blob === 'undefined') { - // can't estimate, default to 2 - util.cores = 2; - return callback(null, util.cores); + // Check for agreeable server->client compression algorithm + for (i = 0; + i < clientList.length && serverList.indexOf(clientList[i]) === -1; + ++i); + if (i === clientList.length) { + // No suitable match found! + debug && debug('Handshake: No matching S->C compression'); + return doFatalError( + self, + 'Handshake failed: no matching S->C compression', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } + init.sc.compress = clientList[i]; + debug && debug(`Handshake: S->C compression: ${clientList[i]}`); - // create worker concurrency estimation code as blob - var blobUrl = URL.createObjectURL(new Blob(['(', - function() { - self.addEventListener('message', function(e) { - // run worker for 4 ms - var st = Date.now(); - var et = st + 4; - while(Date.now() < et); - self.postMessage({st: st, et: et}); - }); - }.toString(), - ')()'], {type: 'application/javascript'})); - - // take 5 samples using 16 workers - sample([], 5, 16); + init.cs.lang = ''; + init.sc.lang = ''; - function sample(max, samples, numWorkers) { - if(samples === 0) { - // get overlap average - var avg = Math.floor(max.reduce(function(avg, x) { - return avg + x; - }, 0) / max.length); - util.cores = Math.max(1, avg); - URL.revokeObjectURL(blobUrl); - return callback(null, util.cores); + // XXX: hack -- find a better way to do this + if (self._kex) { + if (!self._kexinit) { + // We received a rekey request, but we haven't sent a KEXINIT in response + // yet + kexinit(self); } - map(numWorkers, function(err, results) { - max.push(reduce(numWorkers, results)); - sample(max, samples - 1, numWorkers); - }); + self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); } - function map(numWorkers, callback) { - var workers = []; - var results = []; - for(var i = 0; i < numWorkers; ++i) { - var worker = new Worker(blobUrl); - worker.addEventListener('message', function(e) { - results.push(e.data); - if(results.length === numWorkers) { - for(var i = 0; i < numWorkers; ++i) { - workers[i].terminate(); - } - callback(null, results); - } - }); - workers.push(worker); + self._kex = createKeyExchange(init, self, payload); + self._kex.remoteExtInfoEnabled = remoteExtInfoEnabled; + self._kex.start(); +} + +const createKeyExchange = (() => { + function convertToMpint(buf) { + let idx = 0; + let length = buf.length; + while (buf[idx] === 0x00) { + ++idx; + --length; } - for(var i = 0; i < numWorkers; ++i) { - workers[i].postMessage(i); + let newBuf; + if (buf[idx] & 0x80) { + newBuf = Buffer.allocUnsafe(1 + length); + newBuf[0] = 0; + buf.copy(newBuf, 1, idx); + buf = newBuf; + } else if (length !== buf.length) { + newBuf = Buffer.allocUnsafe(length); + buf.copy(newBuf, 0, idx); + buf = newBuf; + } + return buf; + } + + class KeyExchange { + constructor(negotiated, protocol, remoteKexinit) { + this._protocol = protocol; + + this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); + this.negotiated = negotiated; + this.remoteExtInfoEnabled = false; + this._step = 1; + this._public = null; + this._dh = null; + this._sentNEWKEYS = false; + this._receivedNEWKEYS = false; + this._finished = false; + this._hostVerified = false; + + // Data needed for initializing cipher/decipher/etc. + this._kexinit = protocol._kexinit; + this._remoteKexinit = remoteKexinit; + this._identRaw = protocol._identRaw; + this._remoteIdentRaw = protocol._remoteIdentRaw; + this._hostKey = undefined; + this._dhData = undefined; + this._sig = undefined; } - } + finish(scOnly) { + if (this._finished) + return false; + this._finished = true; - function reduce(numWorkers, results) { - // find overlapping time windows - var overlaps = []; - for(var n = 0; n < numWorkers; ++n) { - var r1 = results[n]; - var overlap = overlaps[n] = []; - for(var i = 0; i < numWorkers; ++i) { - if(n === i) { - continue; - } - var r2 = results[i]; - if((r1.st > r2.st && r1.st < r2.et) || - (r2.st > r1.st && r2.st < r1.et)) { - overlap.push(i); - } + const isServer = this._protocol._server; + const negotiated = this.negotiated; + + const pubKey = this.convertPublicKey(this._dhData); + let secret = this.computeSecret(this._dhData); + if (secret instanceof Error) { + secret.message = + `Error while computing DH secret (${this.type}): ${secret.message}`; + secret.level = 'handshake'; + return doFatalError( + this._protocol, + secret, + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - } - // get maximum overlaps ... don't include overlapping worker itself - // as the main JS process was also being scheduled during the work and - // would have to be subtracted from the estimate anyway - return overlaps.reduce(function(max, overlap) { - return Math.max(max, overlap.length); - }, 0); - } -}; + const hash = createHash(this.hashName); + // V_C + hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); + // "V_S" + hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); + // "I_C" + hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); + // "I_S" + hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); + // "K_S" + const serverPublicHostKey = (isServer + ? this._hostKey.getPublicSSH() + : this._hostKey); + hashString(hash, serverPublicHostKey); -/***/ }), + if (this.type === 'groupex') { + // Group exchange-specific + const params = this.getDHParams(); + const num = Buffer.allocUnsafe(4); + // min (uint32) + writeUInt32BE(num, this._minBits, 0); + hash.update(num); + // preferred (uint32) + writeUInt32BE(num, this._prefBits, 0); + hash.update(num); + // max (uint32) + writeUInt32BE(num, this._maxBits, 0); + hash.update(num); + // prime + hashString(hash, params.prime); + // generator + hashString(hash, params.generator); + } -/***/ 8180: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // method-specific data sent by client + hashString(hash, (isServer ? pubKey : this.getPublicKey())); + // method-specific data sent by server + const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); + hashString(hash, serverPublicKey); + // shared secret ("K") + hashString(hash, secret); -/** - * Javascript implementation of X.509 and related components (such as - * Certification Signing Requests) of a Public Key Infrastructure. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - * - * The ASN.1 representation of an X.509v3 certificate is as follows - * (see RFC 2459): - * - * Certificate ::= SEQUENCE { - * tbsCertificate TBSCertificate, - * signatureAlgorithm AlgorithmIdentifier, - * signatureValue BIT STRING - * } - * - * TBSCertificate ::= SEQUENCE { - * version [0] EXPLICIT Version DEFAULT v1, - * serialNumber CertificateSerialNumber, - * signature AlgorithmIdentifier, - * issuer Name, - * validity Validity, - * subject Name, - * subjectPublicKeyInfo SubjectPublicKeyInfo, - * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, - * -- If present, version shall be v2 or v3 - * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, - * -- If present, version shall be v2 or v3 - * extensions [3] EXPLICIT Extensions OPTIONAL - * -- If present, version shall be v3 - * } - * - * Version ::= INTEGER { v1(0), v2(1), v3(2) } - * - * CertificateSerialNumber ::= INTEGER - * - * Name ::= CHOICE { - * // only one possible choice for now - * RDNSequence - * } - * - * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName - * - * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue - * - * AttributeTypeAndValue ::= SEQUENCE { - * type AttributeType, - * value AttributeValue - * } - * AttributeType ::= OBJECT IDENTIFIER - * AttributeValue ::= ANY DEFINED BY AttributeType - * - * Validity ::= SEQUENCE { - * notBefore Time, - * notAfter Time - * } - * - * Time ::= CHOICE { - * utcTime UTCTime, - * generalTime GeneralizedTime - * } - * - * UniqueIdentifier ::= BIT STRING - * - * SubjectPublicKeyInfo ::= SEQUENCE { - * algorithm AlgorithmIdentifier, - * subjectPublicKey BIT STRING - * } - * - * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension - * - * Extension ::= SEQUENCE { - * extnID OBJECT IDENTIFIER, - * critical BOOLEAN DEFAULT FALSE, - * extnValue OCTET STRING - * } - * - * The only key algorithm currently supported for PKI is RSA. - * - * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055. - * - * PKCS#10 v1.7 describes certificate signing requests: - * - * CertificationRequestInfo: - * - * CertificationRequestInfo ::= SEQUENCE { - * version INTEGER { v1(0) } (v1,...), - * subject Name, - * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, - * attributes [0] Attributes{{ CRIAttributes }} - * } - * - * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} - * - * CRIAttributes ATTRIBUTE ::= { - * ... -- add any locally defined attributes here -- } - * - * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { - * type ATTRIBUTE.&id({IOSet}), - * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type}) - * } - * - * CertificationRequest ::= SEQUENCE { - * certificationRequestInfo CertificationRequestInfo, - * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, - * signature BIT STRING - * } - */ -var forge = __nccwpck_require__(9177); -__nccwpck_require__(7994); -__nccwpck_require__(9549); -__nccwpck_require__(7157); -__nccwpck_require__(6231); -__nccwpck_require__(7973); -__nccwpck_require__(1925); -__nccwpck_require__(154); -__nccwpck_require__(4376); -__nccwpck_require__(3921); -__nccwpck_require__(8339); + // "H" + const exchangeHash = hash.digest(); -// shortcut for asn.1 API -var asn1 = forge.asn1; + if (!isServer) { + bufferParser.init(this._sig, 0); + const sigType = bufferParser.readString(true); -/* Public Key Infrastructure (PKI) implementation. */ -var pki = module.exports = forge.pki = forge.pki || {}; -var oids = pki.oids; + if (!sigType) { + return doFatalError( + this._protocol, + 'Malformed packet while reading signature', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -// short name OID mappings -var _shortNames = {}; -_shortNames['CN'] = oids['commonName']; -_shortNames['commonName'] = 'CN'; -_shortNames['C'] = oids['countryName']; -_shortNames['countryName'] = 'C'; -_shortNames['L'] = oids['localityName']; -_shortNames['localityName'] = 'L'; -_shortNames['ST'] = oids['stateOrProvinceName']; -_shortNames['stateOrProvinceName'] = 'ST'; -_shortNames['O'] = oids['organizationName']; -_shortNames['organizationName'] = 'O'; -_shortNames['OU'] = oids['organizationalUnitName']; -_shortNames['organizationalUnitName'] = 'OU'; -_shortNames['E'] = oids['emailAddress']; -_shortNames['emailAddress'] = 'E'; + if (sigType !== negotiated.serverHostKey) { + return doFatalError( + this._protocol, + `Wrong signature type: ${sigType}, ` + + `expected: ${negotiated.serverHostKey}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -// validator for an SubjectPublicKeyInfo structure -// Note: Currently only works with an RSA public key -var publicKeyValidator = forge.pki.rsa.publicKeyValidator; + // "s" + let sigValue = bufferParser.readString(); -// validator for an X.509v3 certificate -var x509CertificateValidator = { - name: 'Certificate', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'Certificate.TBSCertificate', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'tbsCertificate', - value: [{ - name: 'Certificate.TBSCertificate.version', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - value: [{ - name: 'Certificate.TBSCertificate.version.integer', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'certVersion' - }] - }, { - name: 'Certificate.TBSCertificate.serialNumber', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'certSerialNumber' - }, { - name: 'Certificate.TBSCertificate.signature', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'Certificate.TBSCertificate.signature.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'certinfoSignatureOid' - }, { - name: 'Certificate.TBSCertificate.signature.parameters', - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: 'certinfoSignatureParams' - }] - }, { - name: 'Certificate.TBSCertificate.issuer', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'certIssuer' - }, { - name: 'Certificate.TBSCertificate.validity', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - // Note: UTC and generalized times may both appear so the capture - // names are based on their detected order, the names used below - // are only for the common case, which validity time really means - // "notBefore" and which means "notAfter" will be determined by order - value: [{ - // notBefore (Time) (UTC time case) - name: 'Certificate.TBSCertificate.validity.notBefore (utc)', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: 'certValidity1UTCTime' - }, { - // notBefore (Time) (generalized time case) - name: 'Certificate.TBSCertificate.validity.notBefore (generalized)', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: 'certValidity2GeneralizedTime' - }, { - // notAfter (Time) (only UTC time is supported) - name: 'Certificate.TBSCertificate.validity.notAfter (utc)', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: 'certValidity3UTCTime' - }, { - // notAfter (Time) (only UTC time is supported) - name: 'Certificate.TBSCertificate.validity.notAfter (generalized)', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: 'certValidity4GeneralizedTime' - }] - }, { - // Name (subject) (RDNSequence) - name: 'Certificate.TBSCertificate.subject', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'certSubject' - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - // issuerUniqueID (optional) - name: 'Certificate.TBSCertificate.issuerUniqueID', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - value: [{ - name: 'Certificate.TBSCertificate.issuerUniqueID.id', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: 'certIssuerUniqueId' - }] - }, { - // subjectUniqueID (optional) - name: 'Certificate.TBSCertificate.subjectUniqueID', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - constructed: true, - optional: true, - value: [{ - name: 'Certificate.TBSCertificate.subjectUniqueID.id', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: 'certSubjectUniqueId' - }] - }, { - // Extensions (optional) - name: 'Certificate.TBSCertificate.extensions', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - constructed: true, - captureAsn1: 'certExtensions', - optional: true - }] - }, { - // AlgorithmIdentifier (signature algorithm) - name: 'Certificate.signatureAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: 'Certificate.signatureAlgorithm.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'certSignatureOid' - }, { - name: 'Certificate.TBSCertificate.signature.parameters', - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: 'certSignatureParams' - }] - }, { - // SignatureValue - name: 'Certificate.signatureValue', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: 'certSignature' - }] -}; + bufferParser.clear(); -var rsassaPssParameterValidator = { - name: 'rsapss', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'rsapss.hashAlgorithm', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - value: [{ - name: 'rsapss.hashAlgorithm.AlgorithmIdentifier', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'hashOid' - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }, { - name: 'rsapss.maskGenAlgorithm', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - value: [{ - name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'maskGenOid' - }, { - name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'maskGenHashOid' - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }] - }, { - name: 'rsapss.saltLength', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - optional: true, - value: [{ - name: 'rsapss.saltLength.saltLength', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: 'saltLength' - }] - }, { - name: 'rsapss.trailerField', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - optional: true, - value: [{ - name: 'rsapss.trailer.trailer', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: 'trailer' - }] - }] -}; + if (sigValue === undefined) { + return doFatalError( + this._protocol, + 'Malformed packet while reading signature', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -// validator for a CertificationRequestInfo structure -var certificationRequestInfoValidator = { - name: 'CertificationRequestInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'certificationRequestInfo', - value: [{ - name: 'CertificationRequestInfo.integer', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: 'certificationRequestInfoVersion' - }, { - // Name (subject) (RDNSequence) - name: 'CertificationRequestInfo.subject', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'certificationRequestInfoSubject' - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - name: 'CertificationRequestInfo.attributes', - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: 'certificationRequestInfoAttributes', - value: [{ - name: 'CertificationRequestInfo.attributes', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'CertificationRequestInfo.attributes.type', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false - }, { - name: 'CertificationRequestInfo.attributes.value', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true - }] - }] - }] -}; + if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { + return doFatalError( + this._protocol, + 'Malformed signature', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -// validator for a CertificationRequest structure -var certificationRequestValidator = { - name: 'CertificationRequest', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'csr', - value: [ - certificationRequestInfoValidator, { - // AlgorithmIdentifier (signature algorithm) - name: 'CertificationRequest.signatureAlgorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: 'CertificationRequest.signatureAlgorithm.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'csrSignatureOid' - }, { - name: 'CertificationRequest.signatureAlgorithm.parameters', - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: 'csrSignatureParams' - }] - }, { - // signature - name: 'CertificationRequest.signature', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: 'csrSignature' - } - ] -}; + let parsedHostKey; + { + bufferParser.init(this._hostKey, 0); + const name = bufferParser.readString(true); + const hostKey = this._hostKey.slice(bufferParser.pos()); + bufferParser.clear(); + parsedHostKey = parseDERKey(hostKey, name); + if (parsedHostKey instanceof Error) { + parsedHostKey.level = 'handshake'; + return doFatalError( + this._protocol, + parsedHostKey, + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } -/** - * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName - * sets into an array with objects that have type and value properties. - * - * @param rdn the RDNSequence to convert. - * @param md a message digest to append type and value to if provided. - */ -pki.RDNAttributesAsArray = function(rdn, md) { - var rval = []; + let hashAlgo; + // Check if we need to override the default hash algorithm + switch (this.negotiated.serverHostKey) { + case 'rsa-sha2-256': hashAlgo = 'sha256'; break; + case 'rsa-sha2-512': hashAlgo = 'sha512'; break; + } - // each value in 'rdn' in is a SET of RelativeDistinguishedName - var set, attr, obj; - for(var si = 0; si < rdn.value.length; ++si) { - // get the RelativeDistinguishedName set - set = rdn.value[si]; + this._protocol._debug + && this._protocol._debug('Verifying signature ...'); - // each value in the SET is an AttributeTypeAndValue sequence - // containing first a type (an OID) and second a value (defined by - // the OID) - for(var i = 0; i < set.value.length; ++i) { - obj = {}; - attr = set.value[i]; - obj.type = asn1.derToOid(attr.value[0].value); - obj.value = attr.value[1].value; - obj.valueTagClass = attr.value[1].type; - // if the OID is known, get its name and short name - if(obj.type in oids) { - obj.name = oids[obj.type]; - if(obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; + const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); + if (verified !== true) { + if (verified instanceof Error) { + this._protocol._debug && this._protocol._debug( + `Signature verification failed: ${verified.stack}` + ); + } else { + this._protocol._debug && this._protocol._debug( + 'Signature verification failed' + ); + } + return doFatalError( + this._protocol, + 'Handshake failed: signature verification failed', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - } - if(md) { - md.update(obj.type); - md.update(obj.value); - } - rval.push(obj); - } - } + this._protocol._debug && this._protocol._debug('Verified signature'); + } else { + // Server - return rval; -}; + let hashAlgo; + // Check if we need to override the default hash algorithm + switch (this.negotiated.serverHostKey) { + case 'rsa-sha2-256': hashAlgo = 'sha256'; break; + case 'rsa-sha2-512': hashAlgo = 'sha512'; break; + } -/** - * Converts ASN.1 CRIAttributes into an array with objects that have type and - * value properties. - * - * @param attributes the CRIAttributes to convert. - */ -pki.CRIAttributesAsArray = function(attributes) { - var rval = []; + this._protocol._debug && this._protocol._debug( + 'Generating signature ...' + ); - // each value in 'attributes' in is a SEQUENCE with an OID and a SET - for(var si = 0; si < attributes.length; ++si) { - // get the attribute sequence - var seq = attributes[si]; + let signature = this._hostKey.sign(exchangeHash, hashAlgo); + if (signature instanceof Error) { + return doFatalError( + this._protocol, + 'Handshake failed: signature generation failed for ' + + `${this._hostKey.type} host key: ${signature.message}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } - // each value in the SEQUENCE containing first a type (an OID) and - // second a set of values (defined by the OID) - var type = asn1.derToOid(seq.value[0].value); - var values = seq.value[1].value; - for(var vi = 0; vi < values.length; ++vi) { - var obj = {}; - obj.type = type; - obj.value = values[vi].value; - obj.valueTagClass = values[vi].type; - // if the OID is known, get its name and short name - if(obj.type in oids) { - obj.name = oids[obj.type]; - if(obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; + signature = convertSignature(signature, this._hostKey.type); + if (signature === false) { + return doFatalError( + this._protocol, + 'Handshake failed: signature conversion failed for ' + + `${this._hostKey.type} host key`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); } - } - // parse extensions - if(obj.type === oids.extensionRequest) { - obj.extensions = []; - for(var ei = 0; ei < obj.value.length; ++ei) { - obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei])); + + // Send KEX reply + /* + byte SSH_MSG_KEXDH_REPLY + / SSH_MSG_KEX_DH_GEX_REPLY + / SSH_MSG_KEX_ECDH_REPLY + string server public host key and certificates (K_S) + string + string signature of H + */ + const sigType = this.negotiated.serverHostKey; + const sigTypeLen = Buffer.byteLength(sigType); + const sigLen = 4 + sigTypeLen + 4 + signature.length; + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + + 4 + serverPublicHostKey.length + + 4 + serverPublicKey.length + + 4 + sigLen, + true + ); + + packet[p] = MESSAGE.KEXDH_REPLY; + + writeUInt32BE(packet, serverPublicHostKey.length, ++p); + packet.set(serverPublicHostKey, p += 4); + + writeUInt32BE(packet, + serverPublicKey.length, + p += serverPublicHostKey.length); + packet.set(serverPublicKey, p += 4); + + writeUInt32BE(packet, sigLen, p += serverPublicKey.length); + + writeUInt32BE(packet, sigTypeLen, p += 4); + packet.utf8Write(sigType, p += 4, sigTypeLen); + + writeUInt32BE(packet, signature.length, p += sigTypeLen); + packet.set(signature, p += 4); + + if (this._protocol._debug) { + let type; + switch (this.type) { + case 'group': + type = 'KEXDH_REPLY'; + break; + case 'groupex': + type = 'KEXDH_GEX_REPLY'; + break; + default: + type = 'KEXECDH_REPLY'; + } + this._protocol._debug(`Outbound: Sending ${type}`); } + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); } - rval.push(obj); - } - } - return rval; -}; + if (isServer || !scOnly) + trySendNEWKEYS(this); -/** - * Gets an issuer or subject attribute from its name, type, or short name. - * - * @param obj the issuer or subject object. - * @param options a short name string or an object with: - * shortName the short name for the attribute. - * name the name for the attribute. - * type the type for the attribute. - * - * @return the attribute. - */ -function _getAttribute(obj, options) { - if(typeof options === 'string') { - options = {shortName: options}; - } + let hsCipherConfig; + let hsWrite; + const completeHandshake = (partial) => { + if (hsCipherConfig) { + trySendNEWKEYS(this); + hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno; + this._protocol._cipher.free(); + this._protocol._cipher = createCipher(hsCipherConfig); + this._protocol._packetRW.write = hsWrite; + hsCipherConfig = undefined; + hsWrite = undefined; + this._protocol._onHandshakeComplete(negotiated); - var rval = null; - var attr; - for(var i = 0; rval === null && i < obj.attributes.length; ++i) { - attr = obj.attributes[i]; - if(options.type && options.type === attr.type) { - rval = attr; - } else if(options.name && options.name === attr.name) { - rval = attr; - } else if(options.shortName && options.shortName === attr.shortName) { - rval = attr; - } - } - return rval; -} + return false; + } -/** - * Converts signature parameters from ASN.1 structure. - * - * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had - * no parameters. - * - * RSASSA-PSS-params ::= SEQUENCE { - * hashAlgorithm [0] HashAlgorithm DEFAULT - * sha1Identifier, - * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT - * mgf1SHA1Identifier, - * saltLength [2] INTEGER DEFAULT 20, - * trailerField [3] INTEGER DEFAULT 1 - * } - * - * HashAlgorithm ::= AlgorithmIdentifier - * - * MaskGenAlgorithm ::= AlgorithmIdentifier - * - * AlgorithmIdentifer ::= SEQUENCE { - * algorithm OBJECT IDENTIFIER, - * parameters ANY DEFINED BY algorithm OPTIONAL - * } - * - * @param oid The OID specifying the signature algorithm - * @param obj The ASN.1 structure holding the parameters - * @param fillDefaults Whether to use return default values where omitted - * @return signature parameter object - */ -var _readSignatureParameters = function(oid, obj, fillDefaults) { - var params = {}; + if (!this.sessionID) + this.sessionID = exchangeHash; - if(oid !== oids['RSASSA-PSS']) { - return params; - } + { + const newSecret = Buffer.allocUnsafe(4 + secret.length); + writeUInt32BE(newSecret, secret.length, 0); + newSecret.set(secret, 4); + secret = newSecret; + } - if(fillDefaults) { - params = { - hash: { - algorithmOid: oids['sha1'] - }, - mgf: { - algorithmOid: oids['mgf1'], - hash: { - algorithmOid: oids['sha1'] + // Initialize new ciphers, deciphers, etc. + + const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; + const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; + + const csIV = generateKEXVal(csCipherInfo.ivLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'A'); + const scIV = generateKEXVal(scCipherInfo.ivLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'B'); + const csKey = generateKEXVal(csCipherInfo.keyLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'C'); + const scKey = generateKEXVal(scCipherInfo.keyLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'D'); + let csMacInfo; + let csMacKey; + if (!csCipherInfo.authLen) { + csMacInfo = MAC_INFO[negotiated.cs.mac]; + csMacKey = generateKEXVal(csMacInfo.len, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'E'); + } + let scMacInfo; + let scMacKey; + if (!scCipherInfo.authLen) { + scMacInfo = MAC_INFO[negotiated.sc.mac]; + scMacKey = generateKEXVal(scMacInfo.len, + this.hashName, + secret, + exchangeHash, + this.sessionID, + 'F'); + } + + const config = { + inbound: { + onPayload: this._protocol._onPayload, + seqno: this._protocol._decipher.inSeqno, + decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), + decipherIV: (!isServer ? scIV : csIV), + decipherKey: (!isServer ? scKey : csKey), + macInfo: (!isServer ? scMacInfo : csMacInfo), + macKey: (!isServer ? scMacKey : csMacKey), + }, + outbound: { + onWrite: this._protocol._onWrite, + seqno: this._protocol._cipher.outSeqno, + cipherInfo: (isServer ? scCipherInfo : csCipherInfo), + cipherIV: (isServer ? scIV : csIV), + cipherKey: (isServer ? scKey : csKey), + macInfo: (isServer ? scMacInfo : csMacInfo), + macKey: (isServer ? scMacKey : csMacKey), + }, + }; + this._protocol._decipher.free(); + hsCipherConfig = config; + this._protocol._decipher = createDecipher(config); + + const rw = { + read: undefined, + write: undefined, + }; + switch (negotiated.cs.compress) { + case 'zlib': // starts immediately + if (isServer) + rw.read = new ZlibPacketReader(); + else + rw.write = new ZlibPacketWriter(this._protocol); + break; + case 'zlib@openssh.com': + // Starts after successful user authentication + + if (this._protocol._authenticated) { + // If a rekey happens and this compression method is selected and + // we already authenticated successfully, we need to start + // immediately instead + if (isServer) + rw.read = new ZlibPacketReader(); + else + rw.write = new ZlibPacketWriter(this._protocol); + break; + } + // FALLTHROUGH + default: + // none -- never any compression/decompression + + if (isServer) + rw.read = new PacketReader(); + else + rw.write = new PacketWriter(this._protocol); + } + switch (negotiated.sc.compress) { + case 'zlib': // starts immediately + if (isServer) + rw.write = new ZlibPacketWriter(this._protocol); + else + rw.read = new ZlibPacketReader(); + break; + case 'zlib@openssh.com': + // Starts after successful user authentication + + if (this._protocol._authenticated) { + // If a rekey happens and this compression method is selected and + // we already authenticated successfully, we need to start + // immediately instead + if (isServer) + rw.write = new ZlibPacketWriter(this._protocol); + else + rw.read = new ZlibPacketReader(); + break; + } + // FALLTHROUGH + default: + // none -- never any compression/decompression + + if (isServer) + rw.write = new PacketWriter(this._protocol); + else + rw.read = new PacketReader(); } - }, - saltLength: 20 - }; - } + this._protocol._packetRW.read.cleanup(); + this._protocol._packetRW.write.cleanup(); + this._protocol._packetRW.read = rw.read; + hsWrite = rw.write; - var capture = {}; - var errors = []; - if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { - var error = new Error('Cannot read RSASSA-PSS parameter block.'); - error.errors = errors; - throw error; - } + // Cleanup/reset various state + this._public = null; + this._dh = null; + this._kexinit = this._protocol._kexinit = undefined; + this._remoteKexinit = undefined; + this._identRaw = undefined; + this._remoteIdentRaw = undefined; + this._hostKey = undefined; + this._dhData = undefined; + this._sig = undefined; - if(capture.hashOid !== undefined) { - params.hash = params.hash || {}; - params.hash.algorithmOid = asn1.derToOid(capture.hashOid); - } + if (!partial) + return completeHandshake(); + return false; + }; - if(capture.maskGenOid !== undefined) { - params.mgf = params.mgf || {}; - params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); - params.mgf.hash = params.mgf.hash || {}; - params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); - } + if (isServer || scOnly) + this.finish = completeHandshake; - if(capture.saltLength !== undefined) { - params.saltLength = capture.saltLength.charCodeAt(0); - } + if (!isServer) + return completeHandshake(scOnly); + } - return params; -}; + start() { + if (!this._protocol._server) { + if (this._protocol._debug) { + let type; + switch (this.type) { + case 'group': + type = 'KEXDH_INIT'; + break; + default: + type = 'KEXECDH_INIT'; + } + this._protocol._debug(`Outbound: Sending ${type}`); + } -/** - * Create signature digest for OID. - * - * @param options - * signatureOid: the OID specifying the signature algorithm. - * type: a human readable type for error messages - * @return a created md instance. throws if unknown oid. - */ -var _createSignatureDigest = function(options) { - switch(oids[options.signatureOid]) { - case 'sha1WithRSAEncryption': - // deprecated alias - case 'sha1WithRSASignature': - return forge.md.sha1.create(); - case 'md5WithRSAEncryption': - return forge.md.md5.create(); - case 'sha256WithRSAEncryption': - return forge.md.sha256.create(); - case 'sha384WithRSAEncryption': - return forge.md.sha384.create(); - case 'sha512WithRSAEncryption': - return forge.md.sha512.create(); - case 'RSASSA-PSS': - return forge.md.sha256.create(); - default: - var error = new Error( - 'Could not compute ' + options.type + ' digest. ' + - 'Unknown signature OID.'); - error.signatureOid = options.signatureOid; - throw error; - } -}; + const pubKey = this.getPublicKey(); -/** - * Verify signature on certificate or CSR. - * - * @param options: - * certificate the certificate or CSR to verify. - * md the signature digest. - * signature the signature - * @return a created md instance. throws if unknown oid. - */ -var _verifySignature = function(options) { - var cert = options.certificate; - var scheme; + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + 4 + pubKey.length, + true + ); + packet[p] = MESSAGE.KEXDH_INIT; + writeUInt32BE(packet, pubKey.length, ++p); + packet.set(pubKey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + } + getPublicKey() { + this.generateKeys(); - switch(cert.signatureOid) { - case oids.sha1WithRSAEncryption: - // deprecated alias - case oids.sha1WithRSASignature: - /* use PKCS#1 v1.5 padding scheme */ - break; - case oids['RSASSA-PSS']: - var hash, mgf; + const key = this._public; - /* initialize mgf */ - hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; - if(hash === undefined || forge.md[hash] === undefined) { - var error = new Error('Unsupported MGF hash function.'); - error.oid = cert.signatureParameters.mgf.hash.algorithmOid; - error.name = hash; - throw error; + if (key) + return this.convertPublicKey(key); + } + convertPublicKey(key) { + let newKey; + let idx = 0; + let len = key.length; + while (key[idx] === 0x00) { + ++idx; + --len; } - mgf = oids[cert.signatureParameters.mgf.algorithmOid]; - if(mgf === undefined || forge.mgf[mgf] === undefined) { - var error = new Error('Unsupported MGF function.'); - error.oid = cert.signatureParameters.mgf.algorithmOid; - error.name = mgf; - throw error; + if (key[idx] & 0x80) { + newKey = Buffer.allocUnsafe(1 + len); + newKey[0] = 0; + key.copy(newKey, 1, idx); + return newKey; } - mgf = forge.mgf[mgf].create(forge.md[hash].create()); + if (len !== key.length) { + newKey = Buffer.allocUnsafe(len); + key.copy(newKey, 0, idx); + key = newKey; + } + return key; + } + computeSecret(otherPublicKey) { + this.generateKeys(); - /* initialize hash function */ - hash = oids[cert.signatureParameters.hash.algorithmOid]; - if(hash === undefined || forge.md[hash] === undefined) { - var error = new Error('Unsupported RSASSA-PSS hash function.'); - error.oid = cert.signatureParameters.hash.algorithmOid; - error.name = hash; - throw error; + try { + return convertToMpint(this._dh.computeSecret(otherPublicKey)); + } catch (ex) { + return ex; } + } + parse(payload) { + const type = payload[0]; + switch (this._step) { + case 1: + if (this._protocol._server) { + // Server + if (type !== MESSAGE.KEXDH_INIT) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Received DH Init' + ); + /* + byte SSH_MSG_KEXDH_INIT + / SSH_MSG_KEX_ECDH_INIT + string + */ + bufferParser.init(payload, 1); + const dhData = bufferParser.readString(); + bufferParser.clear(); + if (dhData === undefined) { + return doFatalError( + this._protocol, + 'Received malformed KEX*_INIT', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } - scheme = forge.pss.create( - forge.md[hash].create(), mgf, cert.signatureParameters.saltLength - ); - break; - } + // Client public key + this._dhData = dhData; - // verify signature on cert using public key - return cert.publicKey.verify( - options.md.digest().getBytes(), options.signature, scheme - ); -}; + let hostKey = + this._protocol._hostKeys[this.negotiated.serverHostKey]; + if (Array.isArray(hostKey)) + hostKey = hostKey[0]; + this._hostKey = hostKey; -/** - * Converts an X.509 certificate from PEM format. - * - * Note: If the certificate is to be verified then compute hash should - * be set to true. This will scan the TBSCertificate part of the ASN.1 - * object while it is converted so it doesn't need to be converted back - * to ASN.1-DER-encoding later. - * - * @param pem the PEM-formatted certificate. - * @param computeHash true to compute the hash for verification. - * @param strict true to be strict when checking ASN.1 value lengths, false to - * allow truncated values (default: true). - * - * @return the certificate. - */ -pki.certificateFromPem = function(pem, computeHash, strict) { - var msg = forge.pem.decode(pem)[0]; + this.finish(); + } else { + // Client + if (type !== MESSAGE.KEXDH_REPLY) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Received DH Reply' + ); + /* + byte SSH_MSG_KEXDH_REPLY + / SSH_MSG_KEX_DH_GEX_REPLY + / SSH_MSG_KEX_ECDH_REPLY + string server public host key and certificates (K_S) + string + string signature of H + */ + bufferParser.init(payload, 1); + let hostPubKey; + let dhData; + let sig; + if ((hostPubKey = bufferParser.readString()) === undefined + || (dhData = bufferParser.readString()) === undefined + || (sig = bufferParser.readString()) === undefined) { + bufferParser.clear(); + return doFatalError( + this._protocol, + 'Received malformed KEX*_REPLY', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + bufferParser.clear(); - if(msg.type !== 'CERTIFICATE' && - msg.type !== 'X509 CERTIFICATE' && - msg.type !== 'TRUSTED CERTIFICATE') { - var error = new Error( - 'Could not convert certificate from PEM; PEM header type ' + - 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error( - 'Could not convert certificate from PEM; PEM is encrypted.'); + // Check that the host public key type matches what was negotiated + // during KEXINIT swap + bufferParser.init(hostPubKey, 0); + const hostPubKeyType = bufferParser.readString(true); + bufferParser.clear(); + if (hostPubKeyType === undefined) { + return doFatalError( + this._protocol, + 'Received malformed host public key', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + if (hostPubKeyType !== this.negotiated.serverHostKey) { + // Check if we need to make an exception + switch (this.negotiated.serverHostKey) { + case 'rsa-sha2-256': + case 'rsa-sha2-512': + if (hostPubKeyType === 'ssh-rsa') + break; + // FALLTHROUGH + default: + return doFatalError( + this._protocol, + 'Host key does not match negotiated type', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } + + this._hostKey = hostPubKey; + this._dhData = dhData; + this._sig = sig; + + let checked = false; + let ret; + if (this._protocol._hostVerifier === undefined) { + ret = true; + this._protocol._debug && this._protocol._debug( + 'Host accepted by default (no verification)' + ); + } else { + ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { + if (checked) + return; + checked = true; + if (permitted === false) { + this._protocol._debug && this._protocol._debug( + 'Host denied (verification failed)' + ); + return doFatalError( + this._protocol, + 'Host denied (verification failed)', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Host accepted (verified)' + ); + this._hostVerified = true; + if (this._receivedNEWKEYS) + this.finish(); + else + trySendNEWKEYS(this); + }); + } + if (ret === undefined) { + // Async host verification + ++this._step; + return; + } + checked = true; + if (ret === false) { + this._protocol._debug && this._protocol._debug( + 'Host denied (verification failed)' + ); + return doFatalError( + this._protocol, + 'Host denied (verification failed)', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Host accepted (verified)' + ); + this._hostVerified = true; + trySendNEWKEYS(this); + } + ++this._step; + break; + case 2: + if (type !== MESSAGE.NEWKEYS) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Inbound: NEWKEYS' + ); + this._receivedNEWKEYS = true; + if (this._protocol._strictMode) + this._protocol._decipher.inSeqno = 0; + ++this._step; + + return this.finish(!this._protocol._server && !this._hostVerified); + default: + return doFatalError( + this._protocol, + `Received unexpected packet ${type} after NEWKEYS`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } } - // convert DER to ASN.1 object - var obj = asn1.fromDer(msg.body, strict); + class Curve25519Exchange extends KeyExchange { + constructor(hashName, ...args) { + super(...args); - return pki.certificateFromAsn1(obj, computeHash); -}; + this.type = '25519'; + this.hashName = hashName; + this._keys = null; + } + generateKeys() { + if (!this._keys) + this._keys = generateKeyPairSync('x25519'); + } + getPublicKey() { + this.generateKeys(); -/** - * Converts an X.509 certificate to PEM format. - * - * @param cert the certificate. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted certificate. - */ -pki.certificateToPem = function(cert, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'CERTIFICATE', - body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes() - }; - return forge.pem.encode(msg, {maxline: maxline}); -}; + const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); + return key.slice(-32); // HACK: avoids parsing DER/BER header + } + convertPublicKey(key) { + let newKey; + let idx = 0; + let len = key.length; + while (key[idx] === 0x00) { + ++idx; + --len; + } -/** - * Converts an RSA public key from PEM format. - * - * @param pem the PEM-formatted public key. - * - * @return the public key. - */ -pki.publicKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; + if (key.length === 32) + return key; - if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') { - var error = new Error('Could not convert public key from PEM; PEM header ' + - 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); - error.headerType = msg.type; - throw error; + if (len !== key.length) { + newKey = Buffer.allocUnsafe(len); + key.copy(newKey, 0, idx); + key = newKey; + } + return key; + } + computeSecret(otherPublicKey) { + this.generateKeys(); + + try { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.3.101.110'); // id-X25519 + asnWriter.endSequence(); + + // PublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + // XXX: hack to write a raw buffer without a tag -- yuck + asnWriter._ensure(otherPublicKey.length); + otherPublicKey.copy(asnWriter._buf, + asnWriter._offset, + 0, + otherPublicKey.length); + asnWriter._offset += otherPublicKey.length; + asnWriter.endSequence(); + asnWriter.endSequence(); + + return convertToMpint(diffieHellman({ + privateKey: this._keys.privateKey, + publicKey: createPublicKey({ + key: asnWriter.buffer, + type: 'spki', + format: 'der', + }), + })); + } catch (ex) { + return ex; + } + } } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert public key from PEM; PEM is encrypted.'); + + class ECDHExchange extends KeyExchange { + constructor(curveName, hashName, ...args) { + super(...args); + + this.type = 'ecdh'; + this.curveName = curveName; + this.hashName = hashName; + } + generateKeys() { + if (!this._dh) { + this._dh = createECDH(this.curveName); + this._public = this._dh.generateKeys(); + } + } } - // convert DER to ASN.1 object - var obj = asn1.fromDer(msg.body); + class DHGroupExchange extends KeyExchange { + constructor(hashName, ...args) { + super(...args); - return pki.publicKeyFromAsn1(obj); -}; + this.type = 'groupex'; + this.hashName = hashName; + this._prime = null; + this._generator = null; + this._minBits = GEX_MIN_BITS; + this._prefBits = dhEstimate(this.negotiated); + if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) + this._prefBits = Math.min(this._prefBits, 4096); + this._maxBits = GEX_MAX_BITS; + } + start() { + if (this._protocol._server) + return; + this._protocol._debug && this._protocol._debug( + 'Outbound: Sending KEXDH_GEX_REQUEST' + ); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + 4 + 4 + 4, + true + ); + packet[p] = MESSAGE.KEXDH_GEX_REQUEST; + writeUInt32BE(packet, this._minBits, ++p); + writeUInt32BE(packet, this._prefBits, p += 4); + writeUInt32BE(packet, this._maxBits, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + generateKeys() { + if (!this._dh && this._prime && this._generator) { + this._dh = createDiffieHellman(this._prime, this._generator); + this._public = this._dh.generateKeys(); + } + } + setDHParams(prime, generator) { + if (!Buffer.isBuffer(prime)) + throw new Error('Invalid prime value'); + if (!Buffer.isBuffer(generator)) + throw new Error('Invalid generator value'); + this._prime = prime; + this._generator = generator; + } + getDHParams() { + if (this._dh) { + return { + prime: convertToMpint(this._dh.getPrime()), + generator: convertToMpint(this._dh.getGenerator()), + }; + } + } + parse(payload) { + const type = payload[0]; + switch (this._step) { + case 1: { + if (this._protocol._server) { + if (type !== MESSAGE.KEXDH_GEX_REQUEST) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ` + + MESSAGE.KEXDH_GEX_REQUEST, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + // TODO: allow user implementation to provide safe prime and + // generator on demand to support group exchange on server side + return doFatalError( + this._protocol, + 'Group exchange not implemented for server', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -/** - * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo). - * - * @param key the public key. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted public key. - */ -pki.publicKeyToPem = function(key, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'PUBLIC KEY', - body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes() - }; - return forge.pem.encode(msg, {maxline: maxline}); -}; + if (type !== MESSAGE.KEXDH_GEX_GROUP) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } -/** - * Converts an RSA public key to PEM format (using an RSAPublicKey). - * - * @param key the public key. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted public key. - */ -pki.publicKeyToRSAPublicKeyPem = function(key, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'RSA PUBLIC KEY', - body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes() - }; - return forge.pem.encode(msg, {maxline: maxline}); -}; + this._protocol._debug && this._protocol._debug( + 'Received DH GEX Group' + ); -/** - * Gets a fingerprint for the given public key. - * - * @param options the options to use. - * [md] the message digest object to use (defaults to forge.md.sha1). - * [type] the type of fingerprint, such as 'RSAPublicKey', - * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey'). - * [encoding] an alternative output encoding, such as 'hex' - * (defaults to none, outputs a byte buffer). - * [delimiter] the delimiter to use between bytes for 'hex' encoded - * output, eg: ':' (defaults to none). - * - * @return the fingerprint as a byte buffer or other encoding based on options. - */ -pki.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge.md.sha1.create(); - var type = options.type || 'RSAPublicKey'; + /* + byte SSH_MSG_KEX_DH_GEX_GROUP + mpint p, safe prime + mpint g, generator for subgroup in GF(p) + */ + bufferParser.init(payload, 1); + let prime; + let gen; + if ((prime = bufferParser.readString()) === undefined + || (gen = bufferParser.readString()) === undefined) { + bufferParser.clear(); + return doFatalError( + this._protocol, + 'Received malformed KEXDH_GEX_GROUP', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + bufferParser.clear(); - var bytes; - switch(type) { - case 'RSAPublicKey': - bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes(); - break; - case 'SubjectPublicKeyInfo': - bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes(); - break; - default: - throw new Error('Unknown fingerprint type "' + options.type + '".'); - } + // TODO: validate prime + this.setDHParams(prime, gen); + this.generateKeys(); + const pubkey = this.getPublicKey(); - // hash public key bytes - md.start(); - md.update(bytes); - var digest = md.digest(); - if(options.encoding === 'hex') { - var hex = digest.toHex(); - if(options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); + this._protocol._debug && this._protocol._debug( + 'Outbound: Sending KEXDH_GEX_INIT' + ); + + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = + this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); + packet[p] = MESSAGE.KEXDH_GEX_INIT; + writeUInt32BE(packet, pubkey.length, ++p); + packet.set(pubkey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + + ++this._step; + break; + } + case 2: + if (this._protocol._server) { + if (type !== MESSAGE.KEXDH_GEX_INIT) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Received DH GEX Init' + ); + return doFatalError( + this._protocol, + 'Group exchange not implemented for server', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + 'Received DH GEX Reply' + ); + this._step = 1; + payload[0] = MESSAGE.KEXDH_REPLY; + this.parse = KeyExchange.prototype.parse; + this.parse(payload); + } } - return hex; - } else if(options.encoding === 'binary') { - return digest.getBytes(); - } else if(options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); } - return digest; -}; -/** - * Converts a PKCS#10 certification request (CSR) from PEM format. - * - * Note: If the certification request is to be verified then compute hash - * should be set to true. This will scan the CertificationRequestInfo part of - * the ASN.1 object while it is converted so it doesn't need to be converted - * back to ASN.1-DER-encoding later. - * - * @param pem the PEM-formatted certificate. - * @param computeHash true to compute the hash for verification. - * @param strict true to be strict when checking ASN.1 value lengths, false to - * allow truncated values (default: true). - * - * @return the certification request (CSR). - */ -pki.certificationRequestFromPem = function(pem, computeHash, strict) { - var msg = forge.pem.decode(pem)[0]; + class DHExchange extends KeyExchange { + constructor(groupName, hashName, ...args) { + super(...args); - if(msg.type !== 'CERTIFICATE REQUEST') { - var error = new Error('Could not convert certification request from PEM; ' + - 'PEM header type is not "CERTIFICATE REQUEST".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert certification request from PEM; ' + - 'PEM is encrypted.'); + this.type = 'group'; + this.groupName = groupName; + this.hashName = hashName; + } + start() { + if (!this._protocol._server) { + this._protocol._debug && this._protocol._debug( + 'Outbound: Sending KEXDH_INIT' + ); + const pubKey = this.getPublicKey(); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = + this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); + packet[p] = MESSAGE.KEXDH_INIT; + writeUInt32BE(packet, pubKey.length, ++p); + packet.set(pubKey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + } + generateKeys() { + if (!this._dh) { + this._dh = createDiffieHellmanGroup(this.groupName); + this._public = this._dh.generateKeys(); + } + } + getDHParams() { + if (this._dh) { + return { + prime: convertToMpint(this._dh.getPrime()), + generator: convertToMpint(this._dh.getGenerator()), + }; + } + } } - // convert DER to ASN.1 object - var obj = asn1.fromDer(msg.body, strict); + return (negotiated, ...args) => { + if (typeof negotiated !== 'object' || negotiated === null) + throw new Error('Invalid negotiated argument'); + const kexType = negotiated.kex; + if (typeof kexType === 'string') { + args = [negotiated, ...args]; + switch (kexType) { + case 'curve25519-sha256': + case 'curve25519-sha256@libssh.org': + if (!curve25519Supported) + break; + return new Curve25519Exchange('sha256', ...args); - return pki.certificationRequestFromAsn1(obj, computeHash); -}; + case 'ecdh-sha2-nistp256': + return new ECDHExchange('prime256v1', 'sha256', ...args); + case 'ecdh-sha2-nistp384': + return new ECDHExchange('secp384r1', 'sha384', ...args); + case 'ecdh-sha2-nistp521': + return new ECDHExchange('secp521r1', 'sha512', ...args); -/** - * Converts a PKCS#10 certification request (CSR) to PEM format. - * - * @param csr the certification request. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted certification request. - */ -pki.certificationRequestToPem = function(csr, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'CERTIFICATE REQUEST', - body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes() + case 'diffie-hellman-group1-sha1': + return new DHExchange('modp2', 'sha1', ...args); + case 'diffie-hellman-group14-sha1': + return new DHExchange('modp14', 'sha1', ...args); + case 'diffie-hellman-group14-sha256': + return new DHExchange('modp14', 'sha256', ...args); + case 'diffie-hellman-group15-sha512': + return new DHExchange('modp15', 'sha512', ...args); + case 'diffie-hellman-group16-sha512': + return new DHExchange('modp16', 'sha512', ...args); + case 'diffie-hellman-group17-sha512': + return new DHExchange('modp17', 'sha512', ...args); + case 'diffie-hellman-group18-sha512': + return new DHExchange('modp18', 'sha512', ...args); + + case 'diffie-hellman-group-exchange-sha1': + return new DHGroupExchange('sha1', ...args); + case 'diffie-hellman-group-exchange-sha256': + return new DHGroupExchange('sha256', ...args); + } + throw new Error(`Unsupported key exchange algorithm: ${kexType}`); + } + throw new Error(`Invalid key exchange type: ${kexType}`); }; - return forge.pem.encode(msg, {maxline: maxline}); -}; +})(); -/** - * Creates an empty X.509v3 RSA certificate. - * - * @return the certificate. - */ -pki.createCertificate = function() { - var cert = {}; - cert.version = 0x02; - cert.serialNumber = '00'; - cert.signatureOid = null; - cert.signature = null; - cert.siginfo = {}; - cert.siginfo.algorithmOid = null; - cert.validity = {}; - cert.validity.notBefore = new Date(); - cert.validity.notAfter = new Date(); +const KexInit = (() => { + const KEX_PROPERTY_NAMES = [ + 'kex', + 'serverHostKey', + ['cs', 'cipher' ], + ['sc', 'cipher' ], + ['cs', 'mac' ], + ['sc', 'mac' ], + ['cs', 'compress' ], + ['sc', 'compress' ], + ['cs', 'lang' ], + ['sc', 'lang' ], + ]; + return class KexInit { + constructor(obj) { + if (typeof obj !== 'object' || obj === null) + throw new TypeError('Argument must be an object'); - cert.issuer = {}; - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = []; - cert.issuer.hash = null; + const lists = { + kex: undefined, + serverHostKey: undefined, + cs: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: undefined, + }, + sc: { + cipher: undefined, + mac: undefined, + compress: undefined, + lang: undefined, + }, - cert.subject = {}; - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = []; - cert.subject.hash = null; + all: undefined, + }; + let totalSize = 0; + for (const prop of KEX_PROPERTY_NAMES) { + let base; + let val; + let desc; + let key; + if (typeof prop === 'string') { + base = lists; + val = obj[prop]; + desc = key = prop; + } else { + const parent = prop[0]; + base = lists[parent]; + key = prop[1]; + val = obj[parent][key]; + desc = `${parent}.${key}`; + } + const entry = { array: undefined, buffer: undefined }; + if (Buffer.isBuffer(val)) { + entry.array = ('' + val).split(','); + entry.buffer = val; + totalSize += 4 + val.length; + } else { + if (typeof val === 'string') + val = val.split(','); + if (Array.isArray(val)) { + entry.array = val; + entry.buffer = Buffer.from(val.join(',')); + } else { + throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); + } + totalSize += 4 + entry.buffer.length; + } + base[key] = entry; + } - cert.extensions = []; - cert.publicKey = null; - cert.md = null; + const all = Buffer.allocUnsafe(totalSize); + lists.all = all; + + let allPos = 0; + for (const prop of KEX_PROPERTY_NAMES) { + let data; + if (typeof prop === 'string') + data = lists[prop].buffer; + else + data = lists[prop[0]][prop[1]].buffer; + allPos = writeUInt32BE(all, data.length, allPos); + all.set(data, allPos); + allPos += data.length; + } - /** - * Sets the subject of this certificate. - * - * @param attrs the array of subject attributes to use. - * @param uniqueId an optional a unique ID to use. - */ - cert.setSubject = function(attrs, uniqueId) { - // set new attributes, clear hash - _fillMissingFields(attrs); - cert.subject.attributes = attrs; - delete cert.subject.uniqueId; - if(uniqueId) { - // TODO: support arbitrary bit length ids - cert.subject.uniqueId = uniqueId; + this.totalSize = totalSize; + this.lists = lists; } - cert.subject.hash = null; - }; - - /** - * Sets the issuer of this certificate. - * - * @param attrs the array of issuer attributes to use. - * @param uniqueId an optional a unique ID to use. - */ - cert.setIssuer = function(attrs, uniqueId) { - // set new attributes, clear hash - _fillMissingFields(attrs); - cert.issuer.attributes = attrs; - delete cert.issuer.uniqueId; - if(uniqueId) { - // TODO: support arbitrary bit length ids - cert.issuer.uniqueId = uniqueId; + copyAllTo(buf, offset) { + const src = this.lists.all; + if (typeof offset !== 'number') + throw new TypeError(`Invalid offset value: ${typeof offset}`); + if (buf.length - offset < src.length) + throw new Error('Insufficient space to copy list'); + buf.set(src, offset); + return src.length; } - cert.issuer.hash = null; }; +})(); - /** - * Sets the extensions of this certificate. - * - * @param exts the array of extensions to use. - */ - cert.setExtensions = function(exts) { - for(var i = 0; i < exts.length; ++i) { - _fillMissingExtensionFields(exts[i], {cert: cert}); - } - // set new extensions - cert.extensions = exts; +const hashString = (() => { + const LEN = Buffer.allocUnsafe(4); + return (hash, buf) => { + writeUInt32BE(LEN, buf.length, 0); + hash.update(LEN); + hash.update(buf); }; +})(); - /** - * Gets an extension by its name or id. - * - * @param options the name to use or an object with: - * name the name to use. - * id the id to use. - * - * @return the extension or null if not found. - */ - cert.getExtension = function(options) { - if(typeof options === 'string') { - options = {name: options}; - } - - var rval = null; - var ext; - for(var i = 0; rval === null && i < cert.extensions.length; ++i) { - ext = cert.extensions[i]; - if(options.id && ext.id === options.id) { - rval = ext; - } else if(options.name && ext.name === options.name) { - rval = ext; - } +function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { + let ret; + if (len) { + let digest = createHash(hashName) + .update(secret) + .update(exchangeHash) + .update(char) + .update(sessionID) + .digest(); + while (digest.length < len) { + const chunk = createHash(hashName) + .update(secret) + .update(exchangeHash) + .update(digest) + .digest(); + const extended = Buffer.allocUnsafe(digest.length + chunk.length); + extended.set(digest, 0); + extended.set(chunk, digest.length); + digest = extended; } - return rval; - }; + if (digest.length === len) + ret = digest; + else + ret = new FastBuffer(digest.buffer, digest.byteOffset, len); + } else { + ret = EMPTY_BUFFER; + } + return ret; +} - /** - * Signs this certificate using the given private key. - * - * @param key the private key to sign with. - * @param md the message digest object to use (defaults to forge.md.sha1). - */ - cert.sign = function(key, md) { - // TODO: get signature OID from private key - cert.md = md || forge.md.sha1.create(); - var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption']; - if(!algorithmOid) { - var error = new Error('Could not compute certificate digest. ' + - 'Unknown message digest algorithm OID.'); - error.algorithm = cert.md.algorithm; - throw error; - } - cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; +function onKEXPayload(state, payload) { + // XXX: move this to the Decipher implementations? + if (payload.length === 0) { + this._debug && this._debug('Inbound: Skipping empty packet payload'); + return; + } - // get TBSCertificate, convert to DER - cert.tbsCertificate = pki.getTBSCertificate(cert); - var bytes = asn1.toDer(cert.tbsCertificate); + if (this._skipNextInboundPacket) { + this._skipNextInboundPacket = false; + return; + } - // digest and sign - cert.md.update(bytes.getBytes()); - cert.signature = key.sign(cert.md); - }; + payload = this._packetRW.read.read(payload); - /** - * Attempts verify the signature on the passed certificate using this - * certificate's public key. - * - * @param child the certificate to verify. - * - * @return true if verified, false if not. - */ - cert.verify = function(child) { - var rval = false; + const type = payload[0]; - if(!cert.issued(child)) { - var issuer = child.issuer; - var subject = cert.subject; - var error = new Error( - 'The parent certificate did not issue the given child ' + - 'certificate; the child certificate\'s issuer does not match the ' + - 'parent\'s subject.'); - error.expectedIssuer = subject.attributes; - error.actualIssuer = issuer.attributes; - throw error; + if (!this._strictMode) { + switch (type) { + case MESSAGE.IGNORE: + case MESSAGE.UNIMPLEMENTED: + case MESSAGE.DEBUG: + if (!MESSAGE_HANDLERS) + MESSAGE_HANDLERS = __nccwpck_require__(172); + return MESSAGE_HANDLERS[type](this, payload); } + } - var md = child.md; - if(md === null) { - // create digest for OID signature types - md = _createSignatureDigest({ - signatureOid: child.signatureOid, - type: 'certificate' - }); - - // produce DER formatted TBSCertificate and digest it - var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child); - var bytes = asn1.toDer(tbsCertificate); - md.update(bytes.getBytes()); - } + switch (type) { + case MESSAGE.DISCONNECT: + if (!MESSAGE_HANDLERS) + MESSAGE_HANDLERS = __nccwpck_require__(172); + return MESSAGE_HANDLERS[type](this, payload); + case MESSAGE.KEXINIT: + if (!state.firstPacket) { + return doFatalError( + this, + 'Received extra KEXINIT during handshake', + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + state.firstPacket = false; + return handleKexInit(this, payload); + default: + // Ensure packet is either an algorithm negotiation or KEX + // algorithm-specific packet + if (type < 20 || type > 49) { + return doFatalError( + this, + `Received unexpected packet type ${type}`, + 'handshake', + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } - if(md !== null) { - rval = _verifySignature({ - certificate: cert, md: md, signature: child.signature - }); - } + return this._kex.parse(payload); +} - return rval; - }; +function dhEstimate(neg) { + const csCipher = CIPHER_INFO[neg.cs.cipher]; + const scCipher = CIPHER_INFO[neg.sc.cipher]; + // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will + // also need to be considered when calculating `bits` + const bits = Math.max( + 0, + (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), + csCipher.blockLen, + csCipher.ivLen, + (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), + scCipher.blockLen, + scCipher.ivLen + ) * 8; + if (bits <= 112) + return 2048; + if (bits <= 128) + return 3072; + if (bits <= 192) + return 7680; + return 8192; +} - /** - * Returns true if this certificate's issuer matches the passed - * certificate's subject. Note that no signature check is performed. - * - * @param parent the certificate to check. - * - * @return true if this certificate's issuer matches the passed certificate's - * subject. - */ - cert.isIssuer = function(parent) { - var rval = false; +function trySendNEWKEYS(kex) { + if (!kex._sentNEWKEYS) { + kex._protocol._debug && kex._protocol._debug( + 'Outbound: Sending NEWKEYS' + ); + const p = kex._protocol._packetRW.write.allocStartKEX; + const packet = kex._protocol._packetRW.write.alloc(1, true); + packet[p] = MESSAGE.NEWKEYS; + kex._protocol._cipher.encrypt( + kex._protocol._packetRW.write.finalize(packet, true) + ); + kex._sentNEWKEYS = true; + if (kex._protocol._strictMode) + kex._protocol._cipher.outSeqno = 0; + } +} - var i = cert.issuer; - var s = parent.subject; +module.exports = { + KexInit, + kexinit, + onKEXPayload, + DEFAULT_KEXINIT_CLIENT: new KexInit({ + kex: DEFAULT_KEX.concat(['ext-info-c', 'kex-strict-c-v00@openssh.com']), + serverHostKey: DEFAULT_SERVER_HOST_KEY, + cs: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [], + }, + sc: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [], + }, + }), + DEFAULT_KEXINIT_SERVER: new KexInit({ + kex: DEFAULT_KEX.concat(['kex-strict-s-v00@openssh.com']), + serverHostKey: DEFAULT_SERVER_HOST_KEY, + cs: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [], + }, + sc: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [], + }, + }), + HANDLERS: { + [MESSAGE.KEXINIT]: handleKexInit, + }, +}; - // compare hashes if present - if(i.hash && s.hash) { - rval = (i.hash === s.hash); - } else if(i.attributes.length === s.attributes.length) { - // all attributes are the same so issuer matches subject - rval = true; - var iattr, sattr; - for(var n = 0; rval && n < i.attributes.length; ++n) { - iattr = i.attributes[n]; - sattr = s.attributes[n]; - if(iattr.type !== sattr.type || iattr.value !== sattr.value) { - // attribute mismatch - rval = false; - } - } - } - return rval; - }; +/***/ }), - /** - * Returns true if this certificate's subject matches the issuer of the - * given certificate). Note that not signature check is performed. - * - * @param child the certificate to check. - * - * @return true if this certificate's subject matches the passed - * certificate's issuer. - */ - cert.issued = function(child) { - return child.isIssuer(cert); - }; +/***/ 2218: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Generates the subjectKeyIdentifier for this certificate as byte buffer. - * - * @return the subjectKeyIdentifier for this certificate as byte buffer. - */ - cert.generateSubjectKeyIdentifier = function() { - /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either: +"use strict"; +// TODO: +// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` +// * handle multi-line header values (OpenSSH)? +// * more thorough validation? - (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the - value of the BIT STRING subjectPublicKey (excluding the tag, - length, and number of unused bits). - (2) The keyIdentifier is composed of a four bit type field with - the value 0100 followed by the least significant 60 bits of the - SHA-1 hash of the value of the BIT STRING subjectPublicKey - (excluding the tag, length, and number of unused bit string bits). - */ +const { + createDecipheriv, + createECDH, + createHash, + createHmac, + createSign, + createVerify, + getCiphers, + sign: sign_, + verify: verify_, +} = __nccwpck_require__(6113); +const supportedOpenSSLCiphers = getCiphers(); - // skipping the tag, length, and number of unused bits is the same - // as just using the RSAPublicKey (for RSA keys, which are the - // only ones supported) - return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'}); - }; +const { Ber } = __nccwpck_require__(970); +const bcrypt_pbkdf = (__nccwpck_require__(5447).pbkdf); - /** - * Verifies the subjectKeyIdentifier extension value for this certificate - * against its public key. If no extension is found, false will be - * returned. - * - * @return true if verified, false if not. - */ - cert.verifySubjectKeyIdentifier = function() { - var oid = oids['subjectKeyIdentifier']; - for(var i = 0; i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if(ext.id === oid) { - var ski = cert.generateSubjectKeyIdentifier().getBytes(); - return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski); - } - } - return false; - }; +const { CIPHER_INFO } = __nccwpck_require__(5708); +const { eddsaSupported, SUPPORTED_CIPHER } = __nccwpck_require__(6832); +const { + bufferSlice, + makeBufferParser, + readString, + readUInt32BE, + writeUInt32BE, +} = __nccwpck_require__(9475); - return cert; -}; +const SYM_HASH_ALGO = Symbol('Hash Algorithm'); +const SYM_PRIV_PEM = Symbol('Private key PEM'); +const SYM_PUB_PEM = Symbol('Public key PEM'); +const SYM_PUB_SSH = Symbol('Public key SSH'); +const SYM_DECRYPTED = Symbol('Decrypted Key'); -/** - * Converts an X.509v3 RSA certificate from an ASN.1 object. - * - * Note: If the certificate is to be verified then compute hash should - * be set to true. There is currently no implementation for converting - * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1 - * object needs to be scanned before the cert object is created. - * - * @param obj the asn1 representation of an X.509v3 RSA certificate. - * @param computeHash true to compute the hash for verification. - * - * @return the certificate. - */ -pki.certificateFromAsn1 = function(obj, computeHash) { - // validate certificate and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) { - var error = new Error('Cannot read X.509 certificate. ' + - 'ASN.1 object is not an X509v3 Certificate.'); - error.errors = errors; - throw error; +// Create OpenSSL cipher name -> SSH cipher name conversion table +const CIPHER_INFO_OPENSSL = Object.create(null); +{ + const keys = Object.keys(CIPHER_INFO); + for (let i = 0; i < keys.length; ++i) { + const cipherName = CIPHER_INFO[keys[i]].sslName; + if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) + continue; + CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; } +} - // get oid - var oid = asn1.derToOid(capture.publicKeyOid); - if(oid !== pki.oids.rsaEncryption) { - throw new Error('Cannot read public key. OID is not RSA.'); - } +const binaryKeyParser = makeBufferParser(); - // create certificate - var cert = pki.createCertificate(); - cert.version = capture.certVersion ? - capture.certVersion.charCodeAt(0) : 0; - var serial = forge.util.createBuffer(capture.certSerialNumber); - cert.serialNumber = serial.toHex(); - cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); - cert.signatureParameters = _readSignatureParameters( - cert.signatureOid, capture.certSignatureParams, true); - cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); - cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, - capture.certinfoSignatureParams, false); - cert.signature = capture.certSignature; +function makePEM(type, data) { + data = data.base64Slice(0, data.length); + let formatted = data.replace(/.{64}/g, '$&\n'); + if (data.length & 63) + formatted += '\n'; + return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; +} - var validity = []; - if(capture.certValidity1UTCTime !== undefined) { - validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); - } - if(capture.certValidity2GeneralizedTime !== undefined) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity2GeneralizedTime)); - } - if(capture.certValidity3UTCTime !== undefined) { - validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); - } - if(capture.certValidity4GeneralizedTime !== undefined) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity4GeneralizedTime)); - } - if(validity.length > 2) { - throw new Error('Cannot read notBefore/notAfter validity times; more ' + - 'than two times were provided in the certificate.'); - } - if(validity.length < 2) { - throw new Error('Cannot read notBefore/notAfter validity times; they ' + - 'were not provided as either UTCTime or GeneralizedTime.'); - } - cert.validity.notBefore = validity[0]; - cert.validity.notAfter = validity[1]; +function combineBuffers(buf1, buf2) { + const result = Buffer.allocUnsafe(buf1.length + buf2.length); + result.set(buf1, 0); + result.set(buf2, buf1.length); + return result; +} - // keep TBSCertificate to preserve signature when exporting - cert.tbsCertificate = capture.tbsCertificate; +function skipFields(buf, nfields) { + const bufLen = buf.length; + let pos = (buf._pos || 0); + for (let i = 0; i < nfields; ++i) { + const left = (bufLen - pos); + if (pos >= bufLen || left < 4) + return false; + const len = readUInt32BE(buf, pos); + if (left < 4 + len) + return false; + pos += 4 + len; + } + buf._pos = pos; + return true; +} - if(computeHash) { - // create digest for OID signature type - cert.md = _createSignatureDigest({ - signatureOid: cert.signatureOid, - type: 'certificate' - }); +function genOpenSSLRSAPub(n, e) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption + // algorithm parameters (RSA has none) + asnWriter.writeNull(); + asnWriter.endSequence(); - // produce DER formatted TBSCertificate and digest it - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - } + // subjectPublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + asnWriter.startSequence(); + asnWriter.writeBuffer(n, Ber.Integer); + asnWriter.writeBuffer(e, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PUBLIC', asnWriter.buffer); +} - // handle issuer, build issuer message digest - var imd = forge.md.sha1.create(); - var ibytes = asn1.toDer(capture.certIssuer); - imd.update(ibytes.getBytes()); - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer); - if(capture.certIssuerUniqueId) { - cert.issuer.uniqueId = capture.certIssuerUniqueId; - } - cert.issuer.hash = imd.digest().toHex(); +function genOpenSSHRSAPub(n, e) { + const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); - // handle subject, build subject message digest - var smd = forge.md.sha1.create(); - var sbytes = asn1.toDer(capture.certSubject); - smd.update(sbytes.getBytes()); - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject); - if(capture.certSubjectUniqueId) { - cert.subject.uniqueId = capture.certSubjectUniqueId; - } - cert.subject.hash = smd.digest().toHex(); + writeUInt32BE(publicKey, 7, 0); + publicKey.utf8Write('ssh-rsa', 4, 7); - // handle extensions - if(capture.certExtensions) { - cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions); - } else { - cert.extensions = []; - } + let i = 4 + 7; + writeUInt32BE(publicKey, e.length, i); + publicKey.set(e, i += 4); - // convert RSA public key from ASN.1 - cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + writeUInt32BE(publicKey, n.length, i += e.length); + publicKey.set(n, i + 4); - return cert; -}; + return publicKey; +} -/** - * Converts an ASN.1 extensions object (with extension sequences as its - * values) into an array of extension objects with types and values. - * - * Supported extensions: - * - * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } - * KeyUsage ::= BIT STRING { - * digitalSignature (0), - * nonRepudiation (1), - * keyEncipherment (2), - * dataEncipherment (3), - * keyAgreement (4), - * keyCertSign (5), - * cRLSign (6), - * encipherOnly (7), - * decipherOnly (8) - * } - * - * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } - * BasicConstraints ::= SEQUENCE { - * cA BOOLEAN DEFAULT FALSE, - * pathLenConstraint INTEGER (0..MAX) OPTIONAL - * } - * - * subjectAltName EXTENSION ::= { - * SYNTAX GeneralNames - * IDENTIFIED BY id-ce-subjectAltName - * } - * - * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName - * - * GeneralName ::= CHOICE { - * otherName [0] INSTANCE OF OTHER-NAME, - * rfc822Name [1] IA5String, - * dNSName [2] IA5String, - * x400Address [3] ORAddress, - * directoryName [4] Name, - * ediPartyName [5] EDIPartyName, - * uniformResourceIdentifier [6] IA5String, - * IPAddress [7] OCTET STRING, - * registeredID [8] OBJECT IDENTIFIER - * } - * - * OTHER-NAME ::= TYPE-IDENTIFIER - * - * EDIPartyName ::= SEQUENCE { - * nameAssigner [0] DirectoryString {ub-name} OPTIONAL, - * partyName [1] DirectoryString {ub-name} - * } - * - * @param exts the extensions ASN.1 with extension sequences to parse. - * - * @return the array. - */ -pki.certificateExtensionsFromAsn1 = function(exts) { - var rval = []; - for(var i = 0; i < exts.value.length; ++i) { - // get extension sequence - var extseq = exts.value[i]; - for(var ei = 0; ei < extseq.value.length; ++ei) { - rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei])); - } +const genOpenSSLRSAPriv = (() => { + function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeInt(0x00, Ber.Integer); + asnWriter.writeBuffer(n, Ber.Integer); + asnWriter.writeBuffer(e, Ber.Integer); + asnWriter.writeBuffer(d, Ber.Integer); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(dmp1, Ber.Integer); + asnWriter.writeBuffer(dmq1, Ber.Integer); + asnWriter.writeBuffer(iqmp, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; } - return rval; -}; - -/** - * Parses a single certificate extension from ASN.1. - * - * @param ext the extension in ASN.1 format. - * - * @return the parsed extension as an object. - */ -pki.certificateExtensionFromAsn1 = function(ext) { - // an extension has: - // [0] extnID OBJECT IDENTIFIER - // [1] critical BOOLEAN DEFAULT FALSE - // [2] extnValue OCTET STRING - var e = {}; - e.id = asn1.derToOid(ext.value[0].value); - e.critical = false; - if(ext.value[1].type === asn1.Type.BOOLEAN) { - e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00); - e.value = ext.value[2].value; - } else { - e.value = ext.value[1].value; + function bigIntFromBuffer(buf) { + return BigInt(`0x${buf.hexSlice(0, buf.length)}`); } - // if the oid is known, get its name - if(e.id in oids) { - e.name = oids[e.id]; - // handle key usage - if(e.name === 'keyUsage') { - // get value as BIT STRING - var ev = asn1.fromDer(e.value); - var b2 = 0x00; - var b3 = 0x00; - if(ev.value.length > 1) { - // skip first byte, just indicates unused bits which - // will be padded with 0s anyway - // get bytes with flag bits - b2 = ev.value.charCodeAt(1); - b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; - } - // set flags - e.digitalSignature = (b2 & 0x80) === 0x80; - e.nonRepudiation = (b2 & 0x40) === 0x40; - e.keyEncipherment = (b2 & 0x20) === 0x20; - e.dataEncipherment = (b2 & 0x10) === 0x10; - e.keyAgreement = (b2 & 0x08) === 0x08; - e.keyCertSign = (b2 & 0x04) === 0x04; - e.cRLSign = (b2 & 0x02) === 0x02; - e.encipherOnly = (b2 & 0x01) === 0x01; - e.decipherOnly = (b3 & 0x80) === 0x80; - } else if(e.name === 'basicConstraints') { - // handle basic constraints - // get value as SEQUENCE - var ev = asn1.fromDer(e.value); - // get cA BOOLEAN flag (defaults to false) - if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { - e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00); - } else { - e.cA = false; - } - // get path length constraint - var value = null; - if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { - value = ev.value[0].value; - } else if(ev.value.length > 1) { - value = ev.value[1].value; - } - if(value !== null) { - e.pathLenConstraint = asn1.derToInteger(value); - } - } else if(e.name === 'extKeyUsage') { - // handle extKeyUsage - // value is a SEQUENCE of OIDs - var ev = asn1.fromDer(e.value); - for(var vi = 0; vi < ev.value.length; ++vi) { - var oid = asn1.derToOid(ev.value[vi].value); - if(oid in oids) { - e[oids[oid]] = true; - } else { - e[oid] = true; - } - } - } else if(e.name === 'nsCertType') { - // handle nsCertType - // get value as BIT STRING - var ev = asn1.fromDer(e.value); - var b2 = 0x00; - if(ev.value.length > 1) { - // skip first byte, just indicates unused bits which - // will be padded with 0s anyway - // get bytes with flag bits - b2 = ev.value.charCodeAt(1); + function bigIntToBuffer(bn) { + let hex = bn.toString(16); + if ((hex.length & 1) !== 0) { + hex = `0${hex}`; + } else { + const sigbit = hex.charCodeAt(0); + // BER/DER integers require leading zero byte to denote a positive value + // when first byte >= 0x80 + if (sigbit === 56/* '8' */ + || sigbit === 57/* '9' */ + || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { + hex = `00${hex}`; } - // set flags - e.client = (b2 & 0x80) === 0x80; - e.server = (b2 & 0x40) === 0x40; - e.email = (b2 & 0x20) === 0x20; - e.objsign = (b2 & 0x10) === 0x10; - e.reserved = (b2 & 0x08) === 0x08; - e.sslCA = (b2 & 0x04) === 0x04; - e.emailCA = (b2 & 0x02) === 0x02; - e.objCA = (b2 & 0x01) === 0x01; - } else if( - e.name === 'subjectAltName' || - e.name === 'issuerAltName') { - // handle subjectAltName/issuerAltName - e.altNames = []; + } + return Buffer.from(hex, 'hex'); + } - // ev is a SYNTAX SEQUENCE - var gn; - var ev = asn1.fromDer(e.value); - for(var n = 0; n < ev.value.length; ++n) { - // get GeneralName - gn = ev.value[n]; + return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { + const bn_d = bigIntFromBuffer(d); + const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); + const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); + return makePEM('RSA PRIVATE', + genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); + }; +})(); - var altName = { - type: gn.type, - value: gn.value - }; - e.altNames.push(altName); +function genOpenSSLDSAPub(p, q, g, y) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa + // algorithm parameters + asnWriter.startSequence(); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(g, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); - // Note: Support for types 1,2,6,7,8 - switch(gn.type) { - // rfc822Name - case 1: - // dNSName - case 2: - // uniformResourceIdentifier (URI) - case 6: - break; - // IPAddress - case 7: - // convert to IPv4/IPv6 string representation - altName.ip = forge.util.bytesToIP(gn.value); - break; - // registeredID - case 8: - altName.oid = asn1.derToOid(gn.value); - break; - default: - // unsupported - } - } - } else if(e.name === 'subjectKeyIdentifier') { - // value is an OCTETSTRING w/the hash of the key-type specific - // public key structure (eg: RSAPublicKey) - var ev = asn1.fromDer(e.value); - e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); - } - } - return e; -}; + // subjectPublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + asnWriter.writeBuffer(y, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PUBLIC', asnWriter.buffer); +} -/** - * Converts a PKCS#10 certification request (CSR) from an ASN.1 object. - * - * Note: If the certification request is to be verified then compute hash - * should be set to true. There is currently no implementation for converting - * a certificate back to ASN.1 so the CertificationRequestInfo part of the - * ASN.1 object needs to be scanned before the csr object is created. - * - * @param obj the asn1 representation of a PKCS#10 certification request (CSR). - * @param computeHash true to compute the hash for verification. - * - * @return the certification request (CSR). - */ -pki.certificationRequestFromAsn1 = function(obj, computeHash) { - // validate certification request and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#10 certificate request. ' + - 'ASN.1 object is not a PKCS#10 CertificationRequest.'); - error.errors = errors; - throw error; - } +function genOpenSSHDSAPub(p, q, g, y) { + const publicKey = Buffer.allocUnsafe( + 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length + ); - // get oid - var oid = asn1.derToOid(capture.publicKeyOid); - if(oid !== pki.oids.rsaEncryption) { - throw new Error('Cannot read public key. OID is not RSA.'); - } + writeUInt32BE(publicKey, 7, 0); + publicKey.utf8Write('ssh-dss', 4, 7); - // create certification request - var csr = pki.createCertificationRequest(); - csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; - csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); - csr.signatureParameters = _readSignatureParameters( - csr.signatureOid, capture.csrSignatureParams, true); - csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); - csr.siginfo.parameters = _readSignatureParameters( - csr.siginfo.algorithmOid, capture.csrSignatureParams, false); - csr.signature = capture.csrSignature; + let i = 4 + 7; + writeUInt32BE(publicKey, p.length, i); + publicKey.set(p, i += 4); - // keep CertificationRequestInfo to preserve signature when exporting - csr.certificationRequestInfo = capture.certificationRequestInfo; + writeUInt32BE(publicKey, q.length, i += p.length); + publicKey.set(q, i += 4); - if(computeHash) { - // create digest for OID signature type - csr.md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: 'certification request' - }); + writeUInt32BE(publicKey, g.length, i += q.length); + publicKey.set(g, i += 4); - // produce DER formatted CertificationRequestInfo and digest it - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - } + writeUInt32BE(publicKey, y.length, i += g.length); + publicKey.set(y, i + 4); - // handle subject, build subject message digest - var smd = forge.md.sha1.create(); - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = pki.RDNAttributesAsArray( - capture.certificationRequestInfoSubject, smd); - csr.subject.hash = smd.digest().toHex(); + return publicKey; +} - // convert RSA public key from ASN.1 - csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); +function genOpenSSLDSAPriv(p, q, g, y, x) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeInt(0x00, Ber.Integer); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(g, Ber.Integer); + asnWriter.writeBuffer(y, Ber.Integer); + asnWriter.writeBuffer(x, Ber.Integer); + asnWriter.endSequence(); + return makePEM('DSA PRIVATE', asnWriter.buffer); +} - // convert attributes from ASN.1 - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.attributes = pki.CRIAttributesAsArray( - capture.certificationRequestInfoAttributes || []); +function genOpenSSLEdPub(pub) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.3.101.112'); // id-Ed25519 + asnWriter.endSequence(); - return csr; -}; + // PublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + // XXX: hack to write a raw buffer without a tag -- yuck + asnWriter._ensure(pub.length); + asnWriter._buf.set(pub, asnWriter._offset); + asnWriter._offset += pub.length; + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PUBLIC', asnWriter.buffer); +} -/** - * Creates an empty certification request (a CSR or certificate signing - * request). Once created, its public key and attributes can be set and then - * it can be signed. - * - * @return the empty certification request. - */ -pki.createCertificationRequest = function() { - var csr = {}; - csr.version = 0x00; - csr.signatureOid = null; - csr.signature = null; - csr.siginfo = {}; - csr.siginfo.algorithmOid = null; +function genOpenSSHEdPub(pub) { + const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); - csr.subject = {}; - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = []; - csr.subject.hash = null; + writeUInt32BE(publicKey, 11, 0); + publicKey.utf8Write('ssh-ed25519', 4, 11); - csr.publicKey = null; - csr.attributes = []; - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.md = null; + writeUInt32BE(publicKey, pub.length, 15); + publicKey.set(pub, 19); - /** - * Sets the subject of this certification request. - * - * @param attrs the array of subject attributes to use. - */ - csr.setSubject = function(attrs) { - // set new attributes - _fillMissingFields(attrs); - csr.subject.attributes = attrs; - csr.subject.hash = null; - }; + return publicKey; +} - /** - * Sets the attributes of this certification request. - * - * @param attrs the array of attributes to use. - */ - csr.setAttributes = function(attrs) { - // set new attributes - _fillMissingFields(attrs); - csr.attributes = attrs; - }; +function genOpenSSLEdPriv(priv) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // version + asnWriter.writeInt(0x00, Ber.Integer); - /** - * Signs this certification request using the given private key. - * - * @param key the private key to sign with. - * @param md the message digest object to use (defaults to forge.md.sha1). - */ - csr.sign = function(key, md) { - // TODO: get signature OID from private key - csr.md = md || forge.md.sha1.create(); - var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption']; - if(!algorithmOid) { - var error = new Error('Could not compute certification request digest. ' + - 'Unknown message digest algorithm OID.'); - error.algorithm = csr.md.algorithm; - throw error; - } - csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.3.101.112'); // id-Ed25519 + asnWriter.endSequence(); - // get CertificationRequestInfo, convert to DER - csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(csr.certificationRequestInfo); + // PrivateKey + asnWriter.startSequence(Ber.OctetString); + asnWriter.writeBuffer(priv, Ber.OctetString); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PRIVATE', asnWriter.buffer); +} - // digest and sign - csr.md.update(bytes.getBytes()); - csr.signature = key.sign(csr.md); - }; +function genOpenSSLECDSAPub(oid, Q) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // algorithm + asnWriter.startSequence(); + asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey + // algorithm parameters (namedCurve) + asnWriter.writeOID(oid); + asnWriter.endSequence(); - /** - * Attempts verify the signature on the passed certification request using - * its public key. - * - * A CSR that has been exported to a file in PEM format can be verified using - * OpenSSL using this command: - * - * openssl req -in -verify -noout -text - * - * @return true if verified, false if not. - */ - csr.verify = function() { - var rval = false; + // subjectPublicKey + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + // XXX: hack to write a raw buffer without a tag -- yuck + asnWriter._ensure(Q.length); + asnWriter._buf.set(Q, asnWriter._offset); + asnWriter._offset += Q.length; + // end hack + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('PUBLIC', asnWriter.buffer); +} - var md = csr.md; - if(md === null) { - md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: 'certification request' - }); +function genOpenSSHECDSAPub(oid, Q) { + let curveName; + switch (oid) { + case '1.2.840.10045.3.1.7': + // prime256v1/secp256r1 + curveName = 'nistp256'; + break; + case '1.3.132.0.34': + // secp384r1 + curveName = 'nistp384'; + break; + case '1.3.132.0.35': + // secp521r1 + curveName = 'nistp521'; + break; + default: + return; + } - // produce DER formatted CertificationRequestInfo and digest it - var cri = csr.certificationRequestInfo || - pki.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(cri); - md.update(bytes.getBytes()); - } + const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); - if(md !== null) { - rval = _verifySignature({ - certificate: csr, md: md, signature: csr.signature - }); - } + writeUInt32BE(publicKey, 19, 0); + publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); - return rval; - }; + writeUInt32BE(publicKey, 8, 23); + publicKey.utf8Write(curveName, 27, 8); - return csr; -}; + writeUInt32BE(publicKey, Q.length, 35); + publicKey.set(Q, 39); -/** - * Converts an X.509 subject or issuer to an ASN.1 RDNSequence. - * - * @param obj the subject or issuer (distinguished name). - * - * @return the ASN.1 RDNSequence. - */ -function _dnToAsn1(obj) { - // create an empty RDNSequence - var rval = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + return publicKey; +} - // iterate over attributes - var attr, set; - var attrs = obj.attributes; - for(var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - var value = attr.value; +function genOpenSSLECDSAPriv(oid, pub, priv) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + // version + asnWriter.writeInt(0x01, Ber.Integer); + // privateKey + asnWriter.writeBuffer(priv, Ber.OctetString); + // parameters (optional) + asnWriter.startSequence(0xA0); + asnWriter.writeOID(oid); + asnWriter.endSequence(); + // publicKey (optional) + asnWriter.startSequence(0xA1); + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0x00); + // XXX: hack to write a raw buffer without a tag -- yuck + asnWriter._ensure(pub.length); + asnWriter._buf.set(pub, asnWriter._offset); + asnWriter._offset += pub.length; + // end hack + asnWriter.endSequence(); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM('EC PRIVATE', asnWriter.buffer); +} - // reuse tag class for attribute value if available - var valueTagClass = asn1.Type.PRINTABLESTRING; - if('valueTagClass' in attr) { - valueTagClass = attr.valueTagClass; +function genOpenSSLECDSAPubFromPriv(curveName, priv) { + const tempECDH = createECDH(curveName); + tempECDH.setPrivateKey(priv); + return tempECDH.getPublicKey(); +} - if(valueTagClass === asn1.Type.UTF8) { - value = forge.util.encodeUtf8(value); +const BaseKey = { + sign: (() => { + if (typeof sign_ === 'function') { + return function sign(data, algo) { + const pem = this[SYM_PRIV_PEM]; + if (pem === null) + return new Error('No private key available'); + if (!algo || typeof algo !== 'string') + algo = this[SYM_HASH_ALGO]; + try { + return sign_(algo, data, pem); + } catch (ex) { + return ex; + } + }; + } + return function sign(data, algo) { + const pem = this[SYM_PRIV_PEM]; + if (pem === null) + return new Error('No private key available'); + if (!algo || typeof algo !== 'string') + algo = this[SYM_HASH_ALGO]; + const signature = createSign(algo); + signature.update(data); + try { + return signature.sign(pem); + } catch (ex) { + return ex; } - // FIXME: handle more encodings + }; + })(), + verify: (() => { + if (typeof verify_ === 'function') { + return function verify(data, signature, algo) { + const pem = this[SYM_PUB_PEM]; + if (pem === null) + return new Error('No public key available'); + if (!algo || typeof algo !== 'string') + algo = this[SYM_HASH_ALGO]; + try { + return verify_(algo, data, pem, signature); + } catch (ex) { + return ex; + } + }; } + return function verify(data, signature, algo) { + const pem = this[SYM_PUB_PEM]; + if (pem === null) + return new Error('No public key available'); + if (!algo || typeof algo !== 'string') + algo = this[SYM_HASH_ALGO]; + const verifier = createVerify(algo); + verifier.update(data); + try { + return verifier.verify(pem, signature); + } catch (ex) { + return ex; + } + }; + })(), + isPrivateKey: function isPrivateKey() { + return (this[SYM_PRIV_PEM] !== null); + }, + getPrivatePEM: function getPrivatePEM() { + return this[SYM_PRIV_PEM]; + }, + getPublicPEM: function getPublicPEM() { + return this[SYM_PUB_PEM]; + }, + getPublicSSH: function getPublicSSH() { + return this[SYM_PUB_SSH]; + }, + equals: function equals(key) { + const parsed = parseKey(key); + if (parsed instanceof Error) + return false; + return ( + this.type === parsed.type + && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] + && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] + && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH] + ); + }, +}; - // create a RelativeDistinguishedName set - // each value in the set is an AttributeTypeAndValue first - // containing the type (an OID) and second the value - set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(attr.type).getBytes()), - // AttributeValue - asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) - ]) - ]); - rval.value.push(set); - } - return rval; +function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, + decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; } +OpenSSH_Private.prototype = BaseKey; +{ + const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; + OpenSSH_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + let ret; + const data = Buffer.from(m[1], 'base64'); + if (data.length < 31) // magic (+ magic null term.) + minimum field lengths + return new Error('Malformed OpenSSH private key'); + const magic = data.utf8Slice(0, 15); + if (magic !== 'openssh-key-v1\0') + return new Error(`Unsupported OpenSSH key magic: ${magic}`); -/** - * Gets all printable attributes (typically of an issuer or subject) in a - * simplified JSON format for display. - * - * @param attrs the attributes. - * - * @return the JSON for display. - */ -function _getAttributesAsJson(attrs) { - var rval = {}; - for(var i = 0; i < attrs.length; ++i) { - var attr = attrs[i]; - if(attr.shortName && ( - attr.valueTagClass === asn1.Type.UTF8 || - attr.valueTagClass === asn1.Type.PRINTABLESTRING || - attr.valueTagClass === asn1.Type.IA5STRING)) { - var value = attr.value; - if(attr.valueTagClass === asn1.Type.UTF8) { - value = forge.util.encodeUtf8(attr.value); + const cipherName = readString(data, 15, true); + if (cipherName === undefined) + return new Error('Malformed OpenSSH private key'); + if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) + return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); + + const kdfName = readString(data, data._pos, true); + if (kdfName === undefined) + return new Error('Malformed OpenSSH private key'); + if (kdfName !== 'none') { + if (cipherName === 'none') + return new Error('Malformed OpenSSH private key'); + if (kdfName !== 'bcrypt') + return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); + if (!passphrase) { + return new Error( + 'Encrypted private OpenSSH key detected, but no passphrase given' + ); } - if(!(attr.shortName in rval)) { - rval[attr.shortName] = value; - } else if(forge.util.isArray(rval[attr.shortName])) { - rval[attr.shortName].push(value); - } else { - rval[attr.shortName] = [rval[attr.shortName], value]; + } else if (cipherName !== 'none') { + return new Error('Malformed OpenSSH private key'); + } + + let encInfo; + let cipherKey; + let cipherIV; + if (cipherName !== 'none') + encInfo = CIPHER_INFO[cipherName]; + const kdfOptions = readString(data, data._pos); + if (kdfOptions === undefined) + return new Error('Malformed OpenSSH private key'); + if (kdfOptions.length) { + switch (kdfName) { + case 'none': + return new Error('Malformed OpenSSH private key'); + case 'bcrypt': { + /* + string salt + uint32 rounds + */ + const salt = readString(kdfOptions, 0); + if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) + return new Error('Malformed OpenSSH private key'); + const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); + const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); + const r = bcrypt_pbkdf(passphrase, + passphrase.length, + salt, + salt.length, + gen, + gen.length, + rounds); + if (r !== 0) + return new Error('Failed to generate information to decrypt key'); + cipherKey = bufferSlice(gen, 0, encInfo.keyLen); + cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); + break; + } } + } else if (kdfName !== 'none') { + return new Error('Malformed OpenSSH private key'); } - } - return rval; -} -/** - * Fills in missing fields in attributes. - * - * @param attrs the attributes to fill missing fields in. - */ -function _fillMissingFields(attrs) { - var attr; - for(var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; + if (data._pos + 3 >= data.length) + return new Error('Malformed OpenSSH private key'); + const keyCount = readUInt32BE(data, data._pos); + data._pos += 4; - // populate missing name - if(typeof attr.name === 'undefined') { - if(attr.type && attr.type in pki.oids) { - attr.name = pki.oids[attr.type]; - } else if(attr.shortName && attr.shortName in _shortNames) { - attr.name = pki.oids[_shortNames[attr.shortName]]; + if (keyCount > 0) { + // TODO: place sensible limit on max `keyCount` + + // Read public keys first + for (let i = 0; i < keyCount; ++i) { + const pubData = readString(data, data._pos); + if (pubData === undefined) + return new Error('Malformed OpenSSH private key'); + const type = readString(pubData, 0, true); + if (type === undefined) + return new Error('Malformed OpenSSH private key'); + } + + let privBlob = readString(data, data._pos); + if (privBlob === undefined) + return new Error('Malformed OpenSSH private key'); + + if (cipherKey !== undefined) { + // Encrypted private key(s) + if (privBlob.length < encInfo.blockLen + || (privBlob.length % encInfo.blockLen) !== 0) { + return new Error('Malformed OpenSSH private key'); + } + try { + const options = { authTagLength: encInfo.authLen }; + const decipher = createDecipheriv(encInfo.sslName, + cipherKey, + cipherIV, + options); + decipher.setAutoPadding(false); + if (encInfo.authLen > 0) { + if (data.length - data._pos < encInfo.authLen) + return new Error('Malformed OpenSSH private key'); + decipher.setAuthTag( + bufferSlice(data, data._pos, data._pos += encInfo.authLen) + ); + } + privBlob = combineBuffers(decipher.update(privBlob), + decipher.final()); + } catch (ex) { + return ex; + } + } + // Nothing should we follow the private key(s), except a possible + // authentication tag for relevant ciphers + if (data._pos !== data.length) + return new Error('Malformed OpenSSH private key'); + + ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); + } else { + ret = []; + } + if (ret instanceof Error) + return ret; + // This will need to change if/when OpenSSH ever starts storing multiple + // keys in their key files + return ret[0]; + }; + + function parseOpenSSHPrivKeys(data, nkeys, decrypted) { + const keys = []; + /* + uint32 checkint + uint32 checkint + string privatekey1 + string comment1 + string privatekey2 + string comment2 + ... + string privatekeyN + string commentN + char 1 + char 2 + char 3 + ... + char padlen % 255 + */ + if (data.length < 8) + return new Error('Malformed OpenSSH private key'); + const check1 = readUInt32BE(data, 0); + const check2 = readUInt32BE(data, 4); + if (check1 !== check2) { + if (decrypted) { + return new Error( + 'OpenSSH key integrity check failed -- bad passphrase?' + ); } + return new Error('OpenSSH key integrity check failed'); } + data._pos = 8; + let i; + let oid; + for (i = 0; i < nkeys; ++i) { + let algo; + let privPEM; + let pubPEM; + let pubSSH; + // The OpenSSH documentation for the key format actually lies, the + // entirety of the private key content is not contained with a string + // field, it's actually the literal contents of the private key, so to be + // able to find the end of the key data you need to know the layout/format + // of each key type ... + const type = readString(data, data._pos, true); + if (type === undefined) + return new Error('Malformed OpenSSH private key'); - // populate missing type (OID) - if(typeof attr.type === 'undefined') { - if(attr.name && attr.name in pki.oids) { - attr.type = pki.oids[attr.name]; - } else { - var error = new Error('Attribute type not specified.'); - error.attribute = attr; - throw error; - } - } + switch (type) { + case 'ssh-rsa': { + /* + string n -- public + string e -- public + string d -- private + string iqmp -- private + string p -- private + string q -- private + */ + const n = readString(data, data._pos); + if (n === undefined) + return new Error('Malformed OpenSSH private key'); + const e = readString(data, data._pos); + if (e === undefined) + return new Error('Malformed OpenSSH private key'); + const d = readString(data, data._pos); + if (d === undefined) + return new Error('Malformed OpenSSH private key'); + const iqmp = readString(data, data._pos); + if (iqmp === undefined) + return new Error('Malformed OpenSSH private key'); + const p = readString(data, data._pos); + if (p === undefined) + return new Error('Malformed OpenSSH private key'); + const q = readString(data, data._pos); + if (q === undefined) + return new Error('Malformed OpenSSH private key'); - // populate missing shortname - if(typeof attr.shortName === 'undefined') { - if(attr.name && attr.name in _shortNames) { - attr.shortName = _shortNames[attr.name]; - } - } + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); + algo = 'sha1'; + break; + } + case 'ssh-dss': { + /* + string p -- public + string q -- public + string g -- public + string y -- public + string x -- private + */ + const p = readString(data, data._pos); + if (p === undefined) + return new Error('Malformed OpenSSH private key'); + const q = readString(data, data._pos); + if (q === undefined) + return new Error('Malformed OpenSSH private key'); + const g = readString(data, data._pos); + if (g === undefined) + return new Error('Malformed OpenSSH private key'); + const y = readString(data, data._pos); + if (y === undefined) + return new Error('Malformed OpenSSH private key'); + const x = readString(data, data._pos); + if (x === undefined) + return new Error('Malformed OpenSSH private key'); - // convert extensions to value - if(attr.type === oids.extensionRequest) { - attr.valueConstructed = true; - attr.valueTagClass = asn1.Type.SEQUENCE; - if(!attr.value && attr.extensions) { - attr.value = []; - for(var ei = 0; ei < attr.extensions.length; ++ei) { - attr.value.push(pki.certificateExtensionToAsn1( - _fillMissingExtensionFields(attr.extensions[ei]))); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + privPEM = genOpenSSLDSAPriv(p, q, g, y, x); + algo = 'sha1'; + break; } - } - } + case 'ssh-ed25519': { + if (!eddsaSupported) + return new Error(`Unsupported OpenSSH private key type: ${type}`); + /* + * string public key + * string private key + public key + */ + const edpub = readString(data, data._pos); + if (edpub === undefined || edpub.length !== 32) + return new Error('Malformed OpenSSH private key'); + const edpriv = readString(data, data._pos); + if (edpriv === undefined || edpriv.length !== 64) + return new Error('Malformed OpenSSH private key'); - if(typeof attr.value === 'undefined') { - var error = new Error('Attribute value not specified.'); - error.attribute = attr; - throw error; - } - } -} + pubPEM = genOpenSSLEdPub(edpub); + pubSSH = genOpenSSHEdPub(edpub); + privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); + algo = null; + break; + } + case 'ecdsa-sha2-nistp256': + algo = 'sha256'; + oid = '1.2.840.10045.3.1.7'; + // FALLTHROUGH + case 'ecdsa-sha2-nistp384': + if (algo === undefined) { + algo = 'sha384'; + oid = '1.3.132.0.34'; + } + // FALLTHROUGH + case 'ecdsa-sha2-nistp521': { + if (algo === undefined) { + algo = 'sha512'; + oid = '1.3.132.0.35'; + } + /* + string curve name + string Q -- public + string d -- private + */ + // TODO: validate curve name against type + if (!skipFields(data, 1)) // Skip curve name + return new Error('Malformed OpenSSH private key'); + const ecpub = readString(data, data._pos); + if (ecpub === undefined) + return new Error('Malformed OpenSSH private key'); + const ecpriv = readString(data, data._pos); + if (ecpriv === undefined) + return new Error('Malformed OpenSSH private key'); -/** - * Fills in missing fields in certificate extensions. - * - * @param e the extension. - * @param [options] the options to use. - * [cert] the certificate the extensions are for. - * - * @return the extension. - */ -function _fillMissingExtensionFields(e, options) { - options = options || {}; + pubPEM = genOpenSSLECDSAPub(oid, ecpub); + pubSSH = genOpenSSHECDSAPub(oid, ecpub); + privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); + break; + } + default: + return new Error(`Unsupported OpenSSH private key type: ${type}`); + } - // populate missing name - if(typeof e.name === 'undefined') { - if(e.id && e.id in pki.oids) { - e.name = pki.oids[e.id]; - } - } + const privComment = readString(data, data._pos, true); + if (privComment === undefined) + return new Error('Malformed OpenSSH private key'); - // populate missing id - if(typeof e.id === 'undefined') { - if(e.name && e.name in pki.oids) { - e.id = pki.oids[e.name]; - } else { - var error = new Error('Extension ID not specified.'); - error.extension = e; - throw error; + keys.push( + new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, + decrypted) + ); + } + let cnt = 0; + for (i = data._pos; i < data.length; ++i) { + if (data[i] !== (++cnt % 255)) + return new Error('Malformed OpenSSH private key'); } - } - if(typeof e.value !== 'undefined') { - return e; + return keys; } +} - // handle missing value: - - // value is a BIT STRING - if(e.name === 'keyUsage') { - // build flags - var unused = 0; - var b2 = 0x00; - var b3 = 0x00; - if(e.digitalSignature) { - b2 |= 0x80; - unused = 7; - } - if(e.nonRepudiation) { - b2 |= 0x40; - unused = 6; - } - if(e.keyEncipherment) { - b2 |= 0x20; - unused = 5; - } - if(e.dataEncipherment) { - b2 |= 0x10; - unused = 4; - } - if(e.keyAgreement) { - b2 |= 0x08; - unused = 3; - } - if(e.keyCertSign) { - b2 |= 0x04; - unused = 2; - } - if(e.cRLSign) { - b2 |= 0x02; - unused = 1; - } - if(e.encipherOnly) { - b2 |= 0x01; - unused = 0; - } - if(e.decipherOnly) { - b3 |= 0x80; - unused = 7; - } - // create bit string - var value = String.fromCharCode(unused); - if(b3 !== 0) { - value += String.fromCharCode(b2) + String.fromCharCode(b3); - } else if(b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); - } else if(e.name === 'basicConstraints') { - // basicConstraints is a SEQUENCE - e.value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - // cA BOOLEAN flag defaults to false - if(e.cA) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, - String.fromCharCode(0xFF))); - } - if('pathLenConstraint' in e) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(e.pathLenConstraint).getBytes())); - } - } else if(e.name === 'extKeyUsage') { - // extKeyUsage is a SEQUENCE of OIDs - e.value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - for(var key in e) { - if(e[key] !== true) { - continue; - } - // key is name in OID map - if(key in oids) { - seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, - false, asn1.oidToDer(oids[key]).getBytes())); - } else if(key.indexOf('.') !== -1) { - // assume key is an OID - seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, - false, asn1.oidToDer(key).getBytes())); +function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, + decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; +} +OpenSSH_Old_Private.prototype = BaseKey; +{ + const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; + OpenSSH_Old_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + let privBlob = Buffer.from(m[3], 'base64'); + let headers = m[2]; + let decrypted = false; + if (headers !== undefined) { + // encrypted key + headers = headers.split(/\r\n|\n/g); + for (let i = 0; i < headers.length; ++i) { + const header = headers[i]; + let sepIdx = header.indexOf(':'); + if (header.slice(0, sepIdx) === 'DEK-Info') { + const val = header.slice(sepIdx + 2); + sepIdx = val.indexOf(','); + if (sepIdx === -1) + continue; + const cipherName = val.slice(0, sepIdx).toLowerCase(); + if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { + return new Error( + `Cipher (${cipherName}) not supported ` + + 'for encrypted OpenSSH private key' + ); + } + const encInfo = CIPHER_INFO_OPENSSL[cipherName]; + if (!encInfo) { + return new Error( + `Cipher (${cipherName}) not supported ` + + 'for encrypted OpenSSH private key' + ); + } + const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); + if (cipherIV.length !== encInfo.ivLen) + return new Error('Malformed encrypted OpenSSH private key'); + if (!passphrase) { + return new Error( + 'Encrypted OpenSSH private key detected, but no passphrase given' + ); + } + const ivSlice = bufferSlice(cipherIV, 0, 8); + let cipherKey = createHash('md5') + .update(passphrase) + .update(ivSlice) + .digest(); + while (cipherKey.length < encInfo.keyLen) { + cipherKey = combineBuffers( + cipherKey, + createHash('md5') + .update(cipherKey) + .update(passphrase) + .update(ivSlice) + .digest() + ); + } + if (cipherKey.length > encInfo.keyLen) + cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); + try { + const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); + decipher.setAutoPadding(false); + privBlob = combineBuffers(decipher.update(privBlob), + decipher.final()); + decrypted = true; + } catch (ex) { + return ex; + } + } } } - } else if(e.name === 'nsCertType') { - // nsCertType is a BIT STRING - // build flags - var unused = 0; - var b2 = 0x00; - - if(e.client) { - b2 |= 0x80; - unused = 7; - } - if(e.server) { - b2 |= 0x40; - unused = 6; - } - if(e.email) { - b2 |= 0x20; - unused = 5; - } - if(e.objsign) { - b2 |= 0x10; - unused = 4; - } - if(e.reserved) { - b2 |= 0x08; - unused = 3; - } - if(e.sslCA) { - b2 |= 0x04; - unused = 2; - } - if(e.emailCA) { - b2 |= 0x02; - unused = 1; - } - if(e.objCA) { - b2 |= 0x01; - unused = 0; - } - - // create bit string - var value = String.fromCharCode(unused); - if(b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); - } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') { - // SYNTAX SEQUENCE - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var altName; - for(var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - // handle IP - if(altName.type === 7 && altName.ip) { - value = forge.util.bytesFromIP(altName.ip); - if(value === null) { - var error = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); - error.extension = e; - throw error; + let type; + let privPEM; + let pubPEM; + let pubSSH; + let algo; + let reader; + let errMsg = 'Malformed OpenSSH private key'; + if (decrypted) + errMsg += '. Bad passphrase?'; + switch (m[1]) { + case 'RSA': + type = 'ssh-rsa'; + privPEM = makePEM('RSA PRIVATE', privBlob); + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); // skip version + const n = reader.readString(Ber.Integer, true); + if (n === null) + return new Error(errMsg); + const e = reader.readString(Ber.Integer, true); + if (e === null) + return new Error(errMsg); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + } catch { + return new Error(errMsg); } - } else if(altName.type === 8) { - // handle OID - if(altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - // deprecated ... convert value to OID - value = asn1.oidToDer(value); + algo = 'sha1'; + break; + case 'DSA': + type = 'ssh-dss'; + privPEM = makePEM('DSA PRIVATE', privBlob); + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); // skip version + const p = reader.readString(Ber.Integer, true); + if (p === null) + return new Error(errMsg); + const q = reader.readString(Ber.Integer, true); + if (q === null) + return new Error(errMsg); + const g = reader.readString(Ber.Integer, true); + if (g === null) + return new Error(errMsg); + const y = reader.readString(Ber.Integer, true); + if (y === null) + return new Error(errMsg); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + } catch { + return new Error(errMsg); + } + algo = 'sha1'; + break; + case 'EC': { + let ecSSLName; + let ecPriv; + let ecOID; + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); // skip version + ecPriv = reader.readString(Ber.OctetString, true); + reader.readByte(); // Skip "complex" context type byte + const offset = reader.readLength(); // Skip context length + if (offset !== null) { + reader._offset = offset; + ecOID = reader.readOID(); + if (ecOID === null) + return new Error(errMsg); + switch (ecOID) { + case '1.2.840.10045.3.1.7': + // prime256v1/secp256r1 + ecSSLName = 'prime256v1'; + type = 'ecdsa-sha2-nistp256'; + algo = 'sha256'; + break; + case '1.3.132.0.34': + // secp384r1 + ecSSLName = 'secp384r1'; + type = 'ecdsa-sha2-nistp384'; + algo = 'sha384'; + break; + case '1.3.132.0.35': + // secp521r1 + ecSSLName = 'secp521r1'; + type = 'ecdsa-sha2-nistp521'; + algo = 'sha512'; + break; + default: + return new Error(`Unsupported private key EC OID: ${ecOID}`); + } + } else { + return new Error(errMsg); + } + } catch { + return new Error(errMsg); } + privPEM = makePEM('EC PRIVATE', privBlob); + const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); + pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); + pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); + break; } - e.value.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, altName.type, false, - value)); - } - } else if(e.name === 'nsComment' && options.cert) { - // sanity check value is ASCII (req'd) and not too big - if(!(/^[\x00-\x7F]*$/.test(e.comment)) || - (e.comment.length < 1) || (e.comment.length > 128)) { - throw new Error('Invalid "nsComment" content.'); } - // IA5STRING opaque comment - e.value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment); - } else if(e.name === 'subjectKeyIdentifier' && options.cert) { - var ski = options.cert.generateSubjectKeyIdentifier(); - e.subjectKeyIdentifier = ski.toHex(); - // OCTETSTRING w/digest - e.value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes()); - } else if(e.name === 'authorityKeyIdentifier' && options.cert) { - // SYNTAX SEQUENCE - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - if(e.keyIdentifier) { - var keyIdentifier = (e.keyIdentifier === true ? - options.cert.generateSubjectKeyIdentifier().getBytes() : - e.keyIdentifier); - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier)); - } + return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, + decrypted); + }; +} - if(e.authorityCertIssuer) { - var authorityCertIssuer = [ - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ - _dnToAsn1(e.authorityCertIssuer === true ? - options.cert.issuer : e.authorityCertIssuer) - ]) - ]; - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer)); - } - if(e.serialNumber) { - var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? - options.cert.serialNumber : e.serialNumber); - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber)); +function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; +} +PPK_Private.prototype = BaseKey; +{ + const EMPTY_PASSPHRASE = Buffer.alloc(0); + const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + const PPK_PP1 = Buffer.from([0, 0, 0, 0]); + const PPK_PP2 = Buffer.from([0, 0, 0, 1]); + const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; + PPK_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + // m[1] = key type + // m[2] = encryption type + // m[3] = comment + // m[4] = base64-encoded public key data: + // for "ssh-rsa": + // string "ssh-rsa" + // mpint e (public exponent) + // mpint n (modulus) + // for "ssh-dss": + // string "ssh-dss" + // mpint p (modulus) + // mpint q (prime) + // mpint g (base number) + // mpint y (public key parameter: g^x mod p) + // m[5] = base64-encoded private key data: + // for "ssh-rsa": + // mpint d (private exponent) + // mpint p (prime 1) + // mpint q (prime 2) + // mpint iqmp ([inverse of q] mod p) + // for "ssh-dss": + // mpint x (private key parameter) + // m[6] = SHA1 HMAC over: + // string name of algorithm ("ssh-dss", "ssh-rsa") + // string encryption type + // string comment + // string public key data + // string private-plaintext (including the final padding) + const cipherName = m[2]; + const encrypted = (cipherName !== 'none'); + if (encrypted && !passphrase) { + return new Error( + 'Encrypted PPK private key detected, but no passphrase given' + ); } - } else if(e.name === 'cRLDistributionPoints') { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - // Create sub SEQUENCE of DistributionPointName - var subSeq = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + let privBlob = Buffer.from(m[5], 'base64'); - // Create fullName CHOICE - var fullNameGeneralNames = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, 0, true, []); - var altName; - for(var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - // handle IP - if(altName.type === 7 && altName.ip) { - value = forge.util.bytesFromIP(altName.ip); - if(value === null) { - var error = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); - error.extension = e; - throw error; - } - } else if(altName.type === 8) { - // handle OID - if(altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - // deprecated ... convert value to OID - value = asn1.oidToDer(value); - } + if (encrypted) { + const encInfo = CIPHER_INFO[cipherName]; + let cipherKey = combineBuffers( + createHash('sha1').update(PPK_PP1).update(passphrase).digest(), + createHash('sha1').update(PPK_PP2).update(passphrase).digest() + ); + if (cipherKey.length > encInfo.keyLen) + cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); + try { + const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV); + decipher.setAutoPadding(false); + privBlob = combineBuffers(decipher.update(privBlob), + decipher.final()); + } catch (ex) { + return ex; } - fullNameGeneralNames.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, altName.type, false, - value)); } - // Add to the parent SEQUENCE - subSeq.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames])); - seq.push(subSeq); - } - - // ensure value has been defined by now - if(typeof e.value === 'undefined') { - var error = new Error('Extension value not specified.'); - error.extension = e; - throw error; - } + const type = m[1]; + const comment = m[3]; + const pubBlob = Buffer.from(m[4], 'base64'); - return e; -} + const mac = m[6]; + const typeLen = type.length; + const cipherNameLen = cipherName.length; + const commentLen = Buffer.byteLength(comment); + const pubLen = pubBlob.length; + const privLen = privBlob.length; + const macData = Buffer.allocUnsafe(4 + typeLen + + 4 + cipherNameLen + + 4 + commentLen + + 4 + pubLen + + 4 + privLen); + let p = 0; -/** - * Convert signature parameters object to ASN.1 - * - * @param {String} oid Signature algorithm OID - * @param params The signature parametrs object - * @return ASN.1 object representing signature parameters - */ -function _signatureParametersToAsn1(oid, params) { - switch(oid) { - case oids['RSASSA-PSS']: - var parts = []; + writeUInt32BE(macData, typeLen, p); + macData.utf8Write(type, p += 4, typeLen); + writeUInt32BE(macData, cipherNameLen, p += typeLen); + macData.utf8Write(cipherName, p += 4, cipherNameLen); + writeUInt32BE(macData, commentLen, p += cipherNameLen); + macData.utf8Write(comment, p += 4, commentLen); + writeUInt32BE(macData, pubLen, p += commentLen); + macData.set(pubBlob, p += 4); + writeUInt32BE(macData, privLen, p += pubLen); + macData.set(privBlob, p + 4); - if(params.hash.algorithmOid !== undefined) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(params.hash.algorithmOid).getBytes()), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]) - ])); - } + if (!passphrase) + passphrase = EMPTY_PASSPHRASE; - if(params.mgf.algorithmOid !== undefined) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(params.mgf.algorithmOid).getBytes()), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]) - ]) - ])); - } + const calcMAC = createHmac( + 'sha1', + createHash('sha1') + .update('putty-private-key-file-mac-key') + .update(passphrase) + .digest() + ).update(macData).digest('hex'); - if(params.saltLength !== undefined) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(params.saltLength).getBytes()) - ])); + if (calcMAC !== mac) { + if (encrypted) { + return new Error( + 'PPK private key integrity check failed -- bad passphrase?' + ); } - - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); - - default: - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''); - } -} - -/** - * Converts a certification request's attributes to an ASN.1 set of - * CRIAttributes. - * - * @param csr certification request. - * - * @return the ASN.1 set of CRIAttributes. - */ -function _CRIAttributesToAsn1(csr) { - // create an empty context-specific container - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); - - // no attributes, return empty container - if(csr.attributes.length === 0) { - return rval; - } - - // each attribute has a sequence with a type and a set of values - var attrs = csr.attributes; - for(var i = 0; i < attrs.length; ++i) { - var attr = attrs[i]; - var value = attr.value; - - // reuse tag class for attribute value if available - var valueTagClass = asn1.Type.UTF8; - if('valueTagClass' in attr) { - valueTagClass = attr.valueTagClass; - } - if(valueTagClass === asn1.Type.UTF8) { - value = forge.util.encodeUtf8(value); - } - var valueConstructed = false; - if('valueConstructed' in attr) { - valueConstructed = attr.valueConstructed; + return new Error('PPK private key integrity check failed'); } - // FIXME: handle more encodings - - // create a RelativeDistinguishedName set - // each value in the set is an AttributeTypeAndValue first - // containing the type (an OID) and second the value - var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(attr.type).getBytes()), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - asn1.create( - asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value) - ]) - ]); - rval.value.push(seq); - } - - return rval; -} - -var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); -var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); - -/** - * Converts a Date object to ASN.1 - * Handles the different format before and after 1st January 2050 - * - * @param date date object. - * - * @return the ASN.1 object representing the date. - */ -function _dateToAsn1(date) { - if(date >= jan_1_1950 && date < jan_1_2050) { - return asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, - asn1.dateToUtcTime(date)); - } else { - return asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, - asn1.dateToGeneralizedTime(date)); - } -} - -/** - * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate. - * - * @param cert the certificate. - * - * @return the asn1 TBSCertificate. - */ -pki.getTBSCertificate = function(cert) { - // TBSCertificate - var notBefore = _dateToAsn1(cert.validity.notBefore); - var notAfter = _dateToAsn1(cert.validity.notAfter); - var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // integer - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(cert.version).getBytes()) - ]), - // serialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - forge.util.hexToBytes(cert.serialNumber)), - // signature - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()), - // parameters - _signatureParametersToAsn1( - cert.siginfo.algorithmOid, cert.siginfo.parameters) - ]), - // issuer - _dnToAsn1(cert.issuer), - // validity - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - notBefore, - notAfter - ]), - // subject - _dnToAsn1(cert.subject), - // SubjectPublicKeyInfo - pki.publicKeyToAsn1(cert.publicKey) - ]); - - if(cert.issuer.uniqueId) { - // issuerUniqueID (optional) - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0x00) + - cert.issuer.uniqueId - ) - ]) - ); - } - if(cert.subject.uniqueId) { - // subjectUniqueID (optional) - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0x00) + - cert.subject.uniqueId - ) - ]) - ); - } - - if(cert.extensions.length > 0) { - // extensions (optional) - tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions)); - } - - return tbs; -}; - -/** - * Gets the ASN.1 CertificationRequestInfo part of a - * PKCS#10 CertificationRequest. - * - * @param csr the certification request. - * - * @return the asn1 CertificationRequestInfo. - */ -pki.getCertificationRequestInfo = function(csr) { - // CertificationRequestInfo - var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(csr.version).getBytes()), - // subject - _dnToAsn1(csr.subject), - // SubjectPublicKeyInfo - pki.publicKeyToAsn1(csr.publicKey), - // attributes - _CRIAttributesToAsn1(csr) - ]); - - return cri; -}; -/** - * Converts a DistinguishedName (subject or issuer) to an ASN.1 object. - * - * @param dn the DistinguishedName. - * - * @return the asn1 representation of a DistinguishedName. - */ -pki.distinguishedNameToAsn1 = function(dn) { - return _dnToAsn1(dn); -}; + let pubPEM; + let pubSSH; + let privPEM; + pubBlob._pos = 0; + skipFields(pubBlob, 1); // skip (duplicate) key type + switch (type) { + case 'ssh-rsa': { + const e = readString(pubBlob, pubBlob._pos); + if (e === undefined) + return new Error('Malformed PPK public key'); + const n = readString(pubBlob, pubBlob._pos); + if (n === undefined) + return new Error('Malformed PPK public key'); + const d = readString(privBlob, 0); + if (d === undefined) + return new Error('Malformed PPK private key'); + const p = readString(privBlob, privBlob._pos); + if (p === undefined) + return new Error('Malformed PPK private key'); + const q = readString(privBlob, privBlob._pos); + if (q === undefined) + return new Error('Malformed PPK private key'); + const iqmp = readString(privBlob, privBlob._pos); + if (iqmp === undefined) + return new Error('Malformed PPK private key'); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); + break; + } + case 'ssh-dss': { + const p = readString(pubBlob, pubBlob._pos); + if (p === undefined) + return new Error('Malformed PPK public key'); + const q = readString(pubBlob, pubBlob._pos); + if (q === undefined) + return new Error('Malformed PPK public key'); + const g = readString(pubBlob, pubBlob._pos); + if (g === undefined) + return new Error('Malformed PPK public key'); + const y = readString(pubBlob, pubBlob._pos); + if (y === undefined) + return new Error('Malformed PPK public key'); + const x = readString(privBlob, 0); + if (x === undefined) + return new Error('Malformed PPK private key'); -/** - * Converts an X.509v3 RSA certificate to an ASN.1 object. - * - * @param cert the certificate. - * - * @return the asn1 representation of an X.509v3 RSA certificate. - */ -pki.certificateToAsn1 = function(cert) { - // prefer cached TBSCertificate over generating one - var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + privPEM = genOpenSSLDSAPriv(p, q, g, y, x); + break; + } + } - // Certificate - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // TBSCertificate - tbsCertificate, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(cert.signatureOid).getBytes()), - // parameters - _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) - ]), - // SignatureValue - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, - String.fromCharCode(0x00) + cert.signature) - ]); -}; + return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', + encrypted); + }; +} -/** - * Converts X.509v3 certificate extensions to ASN.1. - * - * @param exts the extensions to convert. - * - * @return the extensions in ASN.1 format. - */ -pki.certificateExtensionsToAsn1 = function(exts) { - // create top-level extension container - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); - // create extension sequence (stores a sequence for each extension) - var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - rval.value.push(seq); +function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = null; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = false; +} +OpenSSH_Public.prototype = BaseKey; +{ + let regexp; + if (eddsaSupported) + regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; + else + regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; + OpenSSH_Public.parse = (str) => { + const m = regexp.exec(str); + if (m === null) + return null; + // m[1] = full type + // m[2] = base type + // m[3] = base64-encoded public key + // m[4] = comment - for(var i = 0; i < exts.length; ++i) { - seq.value.push(pki.certificateExtensionToAsn1(exts[i])); - } + const fullType = m[1]; + const baseType = m[2]; + const data = Buffer.from(m[3], 'base64'); + const comment = (m[4] || ''); - return rval; -}; + const type = readString(data, data._pos, true); + if (type === undefined || type.indexOf(baseType) !== 0) + return new Error('Malformed OpenSSH public key'); -/** - * Converts a single certificate extension to ASN.1. - * - * @param ext the extension to convert. - * - * @return the extension in ASN.1 format. - */ -pki.certificateExtensionToAsn1 = function(ext) { - // create a sequence for each extension - var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + return parseDER(data, baseType, comment, fullType); + }; +} - // extnID (OID) - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(ext.id).getBytes())); - // critical defaults to false - if(ext.critical) { - // critical BOOLEAN DEFAULT FALSE - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, - String.fromCharCode(0xFF))); - } +function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = null; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = false; +} +RFC4716_Public.prototype = BaseKey; +{ + const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; + const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; + const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; + const RE_HEADER_ENDS = /\\\r?\n/g; + RFC4716_Public.parse = (str) => { + let m = regexp.exec(str); + if (m === null) + return null; - var value = ext.value; - if(typeof ext.value !== 'string') { - // value is asn.1 - value = asn1.toDer(value).getBytes(); - } + const body = m[1]; + let dataStart = 0; + let comment = ''; - // extnValue (OCTET STRING) - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value)); + while (m = RE_HEADER.exec(body)) { + const headerName = m[1]; + const headerValue = m[2].replace(RE_HEADER_ENDS, ''); + if (headerValue.length > 1024) { + RE_HEADER.lastIndex = 0; + return new Error('Malformed RFC4716 public key'); + } - return extseq; -}; + dataStart = RE_HEADER.lastIndex; -/** - * Converts a PKCS#10 certification request to an ASN.1 object. - * - * @param csr the certification request. - * - * @return the asn1 representation of a certification request. - */ -pki.certificationRequestToAsn1 = function(csr) { - // prefer cached CertificationRequestInfo over generating one - var cri = csr.certificationRequestInfo || - pki.getCertificationRequestInfo(csr); + if (headerName.toLowerCase() === 'comment') { + comment = headerValue; + if (comment.length > 1 + && comment.charCodeAt(0) === 34/* '"' */ + && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { + comment = comment.slice(1, -1); + } + } + } - // Certificate - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // CertificationRequestInfo - cri, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(csr.signatureOid).getBytes()), - // parameters - _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) - ]), - // signature - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, - String.fromCharCode(0x00) + csr.signature) - ]); -}; + let data = body.slice(dataStart); + if (!RE_DATA.test(data)) + return new Error('Malformed RFC4716 public key'); -/** - * Creates a CA store. - * - * @param certs an optional array of certificate objects or PEM-formatted - * certificate strings to add to the CA store. - * - * @return the CA store. - */ -pki.createCaStore = function(certs) { - // create CA store - var caStore = { - // stored certificates - certs: {} - }; + data = Buffer.from(data, 'base64'); - /** - * Gets the certificate that issued the passed certificate or its - * 'parent'. - * - * @param cert the certificate to get the parent for. - * - * @return the parent certificate or null if none was found. - */ - caStore.getIssuer = function(cert) { - var rval = getBySubject(cert.issuer); + const type = readString(data, 0, true); + if (type === undefined) + return new Error('Malformed RFC4716 public key'); - // see if there are multiple matches - /*if(forge.util.isArray(rval)) { - // TODO: resolve multiple matches by checking - // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc. - // FIXME: or alternatively do authority key mapping - // if possible (X.509v1 certs can't work?) - throw new Error('Resolving multiple issuer matches not implemented yet.'); - }*/ + let pubPEM = null; + let pubSSH = null; + switch (type) { + case 'ssh-rsa': { + const e = readString(data, data._pos); + if (e === undefined) + return new Error('Malformed RFC4716 public key'); + const n = readString(data, data._pos); + if (n === undefined) + return new Error('Malformed RFC4716 public key'); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + break; + } + case 'ssh-dss': { + const p = readString(data, data._pos); + if (p === undefined) + return new Error('Malformed RFC4716 public key'); + const q = readString(data, data._pos); + if (q === undefined) + return new Error('Malformed RFC4716 public key'); + const g = readString(data, data._pos); + if (g === undefined) + return new Error('Malformed RFC4716 public key'); + const y = readString(data, data._pos); + if (y === undefined) + return new Error('Malformed RFC4716 public key'); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + break; + } + default: + return new Error('Malformed RFC4716 public key'); + } - return rval; + return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); }; +} - /** - * Adds a trusted certificate to the store. - * - * @param cert the certificate to add as a trusted certificate (either a - * pki.certificate object or a PEM-formatted certificate). - */ - caStore.addCertificate = function(cert) { - // convert from pem if necessary - if(typeof cert === 'string') { - cert = forge.pki.certificateFromPem(cert); - } - ensureSubjectHasHash(cert.subject); +function parseDER(data, baseType, comment, fullType) { + if (!isSupportedKeyType(baseType)) + return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store - if(cert.subject.hash in caStore.certs) { - // subject hash already exists, append to array - var tmp = caStore.certs[cert.subject.hash]; - if(!forge.util.isArray(tmp)) { - tmp = [tmp]; - } - tmp.push(cert); - caStore.certs[cert.subject.hash] = tmp; - } else { - caStore.certs[cert.subject.hash] = cert; - } - } - }; + let algo; + let oid; + let pubPEM = null; + let pubSSH = null; - /** - * Checks to see if the given certificate is in the store. - * - * @param cert the certificate to check (either a pki.certificate or a - * PEM-formatted certificate). - * - * @return true if the certificate is in the store, false if not. - */ - caStore.hasCertificate = function(cert) { - // convert from pem if necessary - if(typeof cert === 'string') { - cert = forge.pki.certificateFromPem(cert); + switch (baseType) { + case 'ssh-rsa': { + const e = readString(data, data._pos || 0); + if (e === undefined) + return new Error('Malformed OpenSSH public key'); + const n = readString(data, data._pos); + if (n === undefined) + return new Error('Malformed OpenSSH public key'); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + algo = 'sha1'; + break; } - - var match = getBySubject(cert.subject); - if(!match) { - return false; + case 'ssh-dss': { + const p = readString(data, data._pos || 0); + if (p === undefined) + return new Error('Malformed OpenSSH public key'); + const q = readString(data, data._pos); + if (q === undefined) + return new Error('Malformed OpenSSH public key'); + const g = readString(data, data._pos); + if (g === undefined) + return new Error('Malformed OpenSSH public key'); + const y = readString(data, data._pos); + if (y === undefined) + return new Error('Malformed OpenSSH public key'); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + algo = 'sha1'; + break; } - if(!forge.util.isArray(match)) { - match = [match]; + case 'ssh-ed25519': { + const edpub = readString(data, data._pos || 0); + if (edpub === undefined || edpub.length !== 32) + return new Error('Malformed OpenSSH public key'); + pubPEM = genOpenSSLEdPub(edpub); + pubSSH = genOpenSSHEdPub(edpub); + algo = null; + break; } - // compare DER-encoding of certificates - var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes(); - for(var i = 0; i < match.length; ++i) { - var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes(); - if(der1 === der2) { - return true; + case 'ecdsa-sha2-nistp256': + algo = 'sha256'; + oid = '1.2.840.10045.3.1.7'; + // FALLTHROUGH + case 'ecdsa-sha2-nistp384': + if (algo === undefined) { + algo = 'sha384'; + oid = '1.3.132.0.34'; + } + // FALLTHROUGH + case 'ecdsa-sha2-nistp521': { + if (algo === undefined) { + algo = 'sha512'; + oid = '1.3.132.0.35'; } + // TODO: validate curve name against type + if (!skipFields(data, 1)) // Skip curve name + return new Error('Malformed OpenSSH public key'); + const ecpub = readString(data, data._pos || 0); + if (ecpub === undefined) + return new Error('Malformed OpenSSH public key'); + pubPEM = genOpenSSLECDSAPub(oid, ecpub); + pubSSH = genOpenSSHECDSAPub(oid, ecpub); + break; } + default: + return new Error(`Unsupported OpenSSH public key type: ${baseType}`); + } + + return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); +} + +function isSupportedKeyType(type) { + switch (type) { + case 'ssh-rsa': + case 'ssh-dss': + case 'ecdsa-sha2-nistp256': + case 'ecdsa-sha2-nistp384': + case 'ecdsa-sha2-nistp521': + return true; + case 'ssh-ed25519': + if (eddsaSupported) + return true; + // FALLTHROUGH + default: + return false; + } +} + +function isParsedKey(val) { + if (!val) return false; - }; + return (typeof val[SYM_DECRYPTED] === 'boolean'); +} - /** - * Lists all of the certificates kept in the store. - * - * @return an array of all of the pki.certificate objects in the store. - */ - caStore.listAllCertificates = function() { - var certList = []; +function parseKey(data, passphrase) { + if (isParsedKey(data)) + return data; - for(var hash in caStore.certs) { - if(caStore.certs.hasOwnProperty(hash)) { - var value = caStore.certs[hash]; - if(!forge.util.isArray(value)) { - certList.push(value); - } else { - for(var i = 0; i < value.length; ++i) { - certList.push(value[i]); - } - } + let origBuffer; + if (Buffer.isBuffer(data)) { + origBuffer = data; + data = data.utf8Slice(0, data.length).trim(); + } else if (typeof data === 'string') { + data = data.trim(); + } else { + return new Error('Key data must be a Buffer or string'); + } + + // eslint-disable-next-line eqeqeq + if (passphrase != undefined) { + if (typeof passphrase === 'string') + passphrase = Buffer.from(passphrase); + else if (!Buffer.isBuffer(passphrase)) + return new Error('Passphrase must be a string or Buffer when supplied'); + } + + let ret; + + // First try as printable string format (e.g. PEM) + + // Private keys + if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) + return ret; + if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) + return ret; + if ((ret = PPK_Private.parse(data, passphrase)) !== null) + return ret; + + // Public keys + if ((ret = OpenSSH_Public.parse(data)) !== null) + return ret; + if ((ret = RFC4716_Public.parse(data)) !== null) + return ret; + + // Finally try as a binary format if we were originally passed binary data + if (origBuffer) { + binaryKeyParser.init(origBuffer, 0); + const type = binaryKeyParser.readString(true); + if (type !== undefined) { + data = binaryKeyParser.readRaw(); + if (data !== undefined) { + ret = parseDER(data, type, '', type); + // Ignore potentially useless errors in case the data was not actually + // in the binary format + if (ret instanceof Error) + ret = null; } } + binaryKeyParser.clear(); + } - return certList; - }; + if (ret) + return ret; - /** - * Removes a certificate from the store. - * - * @param cert the certificate to remove (either a pki.certificate or a - * PEM-formatted certificate). - * - * @return the certificate that was removed or null if the certificate - * wasn't in store. - */ - caStore.removeCertificate = function(cert) { - var result; + return new Error('Unsupported key format'); +} - // convert from pem if necessary - if(typeof cert === 'string') { - cert = forge.pki.certificateFromPem(cert); - } - ensureSubjectHasHash(cert.subject); - if(!caStore.hasCertificate(cert)) { - return null; - } +module.exports = { + isParsedKey, + isSupportedKeyType, + parseDERKey: (data, type) => parseDER(data, type, '', type), + parseKey, +}; - var match = getBySubject(cert.subject); - if(!forge.util.isArray(match)) { - result = caStore.certs[cert.subject.hash]; - delete caStore.certs[cert.subject.hash]; - return result; - } +/***/ }), - // compare DER-encoding of certificates - var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes(); - for(var i = 0; i < match.length; ++i) { - var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes(); - if(der1 === der2) { - result = match[i]; - match.splice(i, 1); - } - } - if(match.length === 0) { - delete caStore.certs[cert.subject.hash]; - } +/***/ 7609: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return result; - }; +"use strict"; - function getBySubject(subject) { - ensureSubjectHasHash(subject); - return caStore.certs[subject.hash] || null; - } - function ensureSubjectHasHash(subject) { - // produce subject hash if it doesn't exist - if(!subject.hash) { - var md = forge.md.sha1.create(); - subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md); - subject.hash = md.digest().toHex(); - } - } +const assert = __nccwpck_require__(9491); +const { inspect } = __nccwpck_require__(3837); - // auto-add passed in certs - if(certs) { - // parse PEM-formatted certificates as necessary - for(var i = 0; i < certs.length; ++i) { - var cert = certs[i]; - caStore.addCertificate(cert); +// Only use this for integers! Decimal numbers do not work with this function. +function addNumericalSeparator(val) { + let res = ''; + let i = val.length; + const start = val[0] === '-' ? 1 : 0; + for (; i >= start + 4; i -= 3) + res = `_${val.slice(i - 3, i)}${res}`; + return `${val.slice(0, i)}${res}`; +} + +function oneOf(expected, thing) { + assert(typeof thing === 'string', '`thing` has to be of type string'); + if (Array.isArray(expected)) { + const len = expected.length; + assert(len > 0, 'At least one expected value needs to be specified'); + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; } + return `of ${thing} ${expected[0]}`; } + return `of ${thing} ${String(expected)}`; +} - return caStore; -}; - -/** - * Certificate verification errors, based on TLS. - */ -pki.certificateError = { - bad_certificate: 'forge.pki.BadCertificate', - unsupported_certificate: 'forge.pki.UnsupportedCertificate', - certificate_revoked: 'forge.pki.CertificateRevoked', - certificate_expired: 'forge.pki.CertificateExpired', - certificate_unknown: 'forge.pki.CertificateUnknown', - unknown_ca: 'forge.pki.UnknownCertificateAuthority' -}; -/** - * Verifies a certificate chain against the given Certificate Authority store - * with an optional custom verify callback. - * - * @param caStore a certificate store to verify against. - * @param chain the certificate chain to verify, with the root or highest - * authority at the end (an array of certificates). - * @param options a callback to be called for every certificate in the chain or - * an object with: - * verify a callback to be called for every certificate in the - * chain - * validityCheckDate the date against which the certificate - * validity period should be checked. Pass null to not check - * the validity period. By default, the current date is used. - * - * The verify callback has the following signature: - * - * verified - Set to true if certificate was verified, otherwise the - * pki.certificateError for why the certificate failed. - * depth - The current index in the chain, where 0 is the end point's cert. - * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous - * end point. - * - * The function returns true on success and on failure either the appropriate - * pki.certificateError or an object with 'error' set to the appropriate - * pki.certificateError and 'message' set to a custom error message. - * - * @return true if successful, error thrown if not. - */ -pki.verifyCertificateChain = function(caStore, chain, options) { - /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate - Section 6: Certification Path Validation - See inline parentheticals related to this particular implementation. +exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { + constructor(message) { + super(); + Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); - The primary goal of path validation is to verify the binding between - a subject distinguished name or a subject alternative name and subject - public key, as represented in the end entity certificate, based on the - public key of the trust anchor. This requires obtaining a sequence of - certificates that support that binding. That sequence should be provided - in the passed 'chain'. The trust anchor should be in the given CA - store. The 'end entity' certificate is the certificate provided by the - end point (typically a server) and is the first in the chain. + const suffix = 'This is caused by either a bug in ssh2 ' + + 'or incorrect usage of ssh2 internals.\n' + + 'Please open an issue with this stack trace at ' + + 'https://github.com/mscdex/ssh2/issues\n'; - To meet this goal, the path validation process verifies, among other - things, that a prospective certification path (a sequence of n - certificates or a 'chain') satisfies the following conditions: + this.message = (message === undefined ? suffix : `${message}\n${suffix}`); + } +}; - (a) for all x in {1, ..., n-1}, the subject of certificate x is - the issuer of certificate x+1; +const MAX_32BIT_INT = 2 ** 32; +const MAX_32BIT_BIGINT = (() => { + try { + return new Function('return 2n ** 32n')(); + } catch {} +})(); +exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { + constructor(str, range, input, replaceDefaultBoolean) { + super(); + Error.captureStackTrace(this, ERR_OUT_OF_RANGE); - (b) certificate 1 is issued by the trust anchor; + assert(range, 'Missing "range" argument'); + let msg = (replaceDefaultBoolean + ? str + : `The value of "${str}" is out of range.`); + let received; + if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === 'bigint') { + received = String(input); + if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) + received = addNumericalSeparator(received); + received += 'n'; + } else { + received = inspect(input); + } + msg += ` It must be ${range}. Received ${received}`; - (c) certificate n is the certificate to be validated; and + this.message = msg; + } +}; - (d) for all x in {1, ..., n}, the certificate was valid at the - time in question. +class ERR_INVALID_ARG_TYPE extends TypeError { + constructor(name, expected, actual) { + super(); + Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); - Note that here 'n' is index 0 in the chain and 1 is the last certificate - in the chain and it must be signed by a certificate in the connection's - CA store. + assert(typeof name === 'string', `'name' must be a string`); - The path validation process also determines the set of certificate - policies that are valid for this path, based on the certificate policies - extension, policy mapping extension, policy constraints extension, and - inhibit any-policy extension. + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && expected.startsWith('not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } - Note: Policy mapping extension not supported (Not Required). + let msg; + if (name.endsWith(' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = (name.includes('.') ? 'property' : 'argument'); + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } - Note: If the certificate has an unsupported critical extension, then it - must be rejected. + msg += `. Received type ${typeof actual}`; - Note: A certificate is self-issued if the DNs that appear in the subject - and issuer fields are identical and are not empty. + this.message = msg; + } +} +exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; - The path validation algorithm assumes the following seven inputs are - provided to the path processing logic. What this specific implementation - will use is provided parenthetically: +exports.validateNumber = function validateNumber(value, name) { + if (typeof value !== 'number') + throw new ERR_INVALID_ARG_TYPE(name, 'number', value); +}; - (a) a prospective certification path of length n (the 'chain') - (b) the current date/time: ('now'). - (c) user-initial-policy-set: A set of certificate policy identifiers - naming the policies that are acceptable to the certificate user. - The user-initial-policy-set contains the special value any-policy - if the user is not concerned about certificate policy - (Not implemented. Any policy is accepted). - (d) trust anchor information, describing a CA that serves as a trust - anchor for the certification path. The trust anchor information - includes: - (1) the trusted issuer name, - (2) the trusted public key algorithm, - (3) the trusted public key, and - (4) optionally, the trusted public key parameters associated - with the public key. +/***/ }), - (Trust anchors are provided via certificates in the CA store). +/***/ 9475: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - The trust anchor information may be provided to the path processing - procedure in the form of a self-signed certificate. The trusted anchor - information is trusted because it was delivered to the path processing - procedure by some trustworthy out-of-band procedure. If the trusted - public key algorithm requires parameters, then the parameters are - provided along with the trusted public key (No parameters used in this - implementation). +"use strict"; - (e) initial-policy-mapping-inhibit, which indicates if policy mapping is - allowed in the certification path. - (Not implemented, no policy checking) - (f) initial-explicit-policy, which indicates if the path must be valid - for at least one of the certificate policies in the user-initial- - policy-set. - (Not implemented, no policy checking) +const Ber = (__nccwpck_require__(970).Ber); - (g) initial-any-policy-inhibit, which indicates whether the - anyPolicy OID should be processed if it is included in a - certificate. - (Not implemented, so any policy is valid provided that it is - not marked as critical) */ +let DISCONNECT_REASON; - /* Basic Path Processing: +const FastBuffer = Buffer[Symbol.species]; +const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; - For each certificate in the 'chain', the following is checked: +function readUInt32BE(buf, offset) { + return (buf[offset++] * 16777216) + + (buf[offset++] * 65536) + + (buf[offset++] * 256) + + buf[offset]; +} - 1. The certificate validity period includes the current time. - 2. The certificate was signed by its parent (where the parent is either - the next in the chain or from the CA store). Allow processing to - continue to the next step if no parent is found but the certificate is - in the CA store. - 3. TODO: The certificate has not been revoked. - 4. The certificate issuer name matches the parent's subject name. - 5. TODO: If the certificate is self-issued and not the final certificate - in the chain, skip this step, otherwise verify that the subject name - is within one of the permitted subtrees of X.500 distinguished names - and that each of the alternative names in the subjectAltName extension - (critical or non-critical) is within one of the permitted subtrees for - that name type. - 6. TODO: If the certificate is self-issued and not the final certificate - in the chain, skip this step, otherwise verify that the subject name - is not within one of the excluded subtrees for X.500 distinguished - names and none of the subjectAltName extension names are excluded for - that name type. - 7. The other steps in the algorithm for basic path processing involve - handling the policy extension which is not presently supported in this - implementation. Instead, if a critical policy extension is found, the - certificate is rejected as not supported. - 8. If the certificate is not the first or if its the only certificate in - the chain (having no parent from the CA store or is self-signed) and it - has a critical key usage extension, verify that the keyCertSign bit is - set. If the key usage extension exists, verify that the basic - constraints extension exists. If the basic constraints extension exists, - verify that the cA flag is set. If pathLenConstraint is set, ensure that - the number of certificates that precede in the chain (come earlier - in the chain as implemented below), excluding the very first in the - chain (typically the end-entity one), isn't greater than the - pathLenConstraint. This constraint limits the number of intermediate - CAs that may appear below a CA before only end-entity certificates - may be issued. */ +function bufferCopy(src, dest, srcStart, srcEnd, destStart) { + if (!destStart) + destStart = 0; + if (srcEnd > src.length) + srcEnd = src.length; + let nb = srcEnd - srcStart; + const destLeft = (dest.length - destStart); + if (nb > destLeft) + nb = destLeft; + dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), + destStart); + return nb; +} - // if a verify callback is passed as the third parameter, package it within - // the options object. This is to support a legacy function signature that - // expected the verify callback as the third parameter. - if(typeof options === 'function') { - options = {verify: options}; - } - options = options || {}; +function bufferSlice(buf, start, end) { + if (end === undefined) + end = buf.length; + return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); +} - // copy cert chain references to another array to protect against changes - // in verify callback - chain = chain.slice(0); - var certs = chain.slice(0); +function makeBufferParser() { + let pos = 0; + let buffer; - var validityCheckDate = options.validityCheckDate; - // if no validityCheckDate is specified, default to the current date. Make - // sure to maintain the value null because it indicates that the validity - // period should not be checked. - if(typeof validityCheckDate === 'undefined') { - validityCheckDate = new Date(); - } + const self = { + init: (buf, start) => { + buffer = buf; + pos = (typeof start === 'number' ? start : 0); + }, + pos: () => pos, + length: () => (buffer ? buffer.length : 0), + avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), + clear: () => { + buffer = undefined; + }, + readUInt32BE: () => { + if (!buffer || pos + 3 >= buffer.length) + return; + return (buffer[pos++] * 16777216) + + (buffer[pos++] * 65536) + + (buffer[pos++] * 256) + + buffer[pos++]; + }, + readUInt64BE: (behavior) => { + if (!buffer || pos + 7 >= buffer.length) + return; + switch (behavior) { + case 'always': + return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); + case 'maybe': + if (buffer[pos] > 0x1F) + return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); + // FALLTHROUGH + default: + return (buffer[pos++] * 72057594037927940) + + (buffer[pos++] * 281474976710656) + + (buffer[pos++] * 1099511627776) + + (buffer[pos++] * 4294967296) + + (buffer[pos++] * 16777216) + + (buffer[pos++] * 65536) + + (buffer[pos++] * 256) + + buffer[pos++]; + } + }, + skip: (n) => { + if (buffer && n > 0) + pos += n; + }, + skipString: () => { + const len = self.readUInt32BE(); + if (len === undefined) + return; + pos += len; + return (pos <= buffer.length ? len : undefined); + }, + readByte: () => { + if (buffer && pos < buffer.length) + return buffer[pos++]; + }, + readBool: () => { + if (buffer && pos < buffer.length) + return !!buffer[pos++]; + }, + readList: () => { + const list = self.readString(true); + if (list === undefined) + return; + return (list ? list.split(',') : []); + }, + readString: (dest, maxLen) => { + if (typeof dest === 'number') { + maxLen = dest; + dest = undefined; + } - // verify each cert in the chain using its parent, where the parent - // is either the next in the chain or from the CA store - var first = true; - var error = null; - var depth = 0; - do { - var cert = chain.shift(); - var parent = null; - var selfSigned = false; + const len = self.readUInt32BE(); + if (len === undefined) + return; - if(validityCheckDate) { - // 1. check valid time - if(validityCheckDate < cert.validity.notBefore || - validityCheckDate > cert.validity.notAfter) { - error = { - message: 'Certificate is not valid yet or has expired.', - error: pki.certificateError.certificate_expired, - notBefore: cert.validity.notBefore, - notAfter: cert.validity.notAfter, - // TODO: we might want to reconsider renaming 'now' to - // 'validityCheckDate' should this API be changed in the future. - now: validityCheckDate - }; + if ((buffer.length - pos) < len + || (typeof maxLen === 'number' && len > maxLen)) { + return; } - } - // 2. verify with parent from chain or CA store - if(error === null) { - parent = chain[0] || caStore.getIssuer(cert); - if(parent === null) { - // check for self-signed cert - if(cert.isIssuer(cert)) { - selfSigned = true; - parent = cert; - } + if (dest) { + if (Buffer.isBuffer(dest)) + return bufferCopy(buffer, dest, pos, pos += len); + return buffer.utf8Slice(pos, pos += len); } + return bufferSlice(buffer, pos, pos += len); + }, + readRaw: (len) => { + if (!buffer) + return; + if (typeof len !== 'number') + return bufferSlice(buffer, pos, pos += (buffer.length - pos)); + if ((buffer.length - pos) >= len) + return bufferSlice(buffer, pos, pos += len); + }, + }; - if(parent) { - // FIXME: current CA store implementation might have multiple - // certificates where the issuer can't be determined from the - // certificate (happens rarely with, eg: old certificates) so normalize - // by always putting parents into an array - // TODO: there's may be an extreme degenerate case currently uncovered - // where an old intermediate certificate seems to have a matching parent - // but none of the parents actually verify ... but the intermediate - // is in the CA and it should pass this check; needs investigation - var parents = parent; - if(!forge.util.isArray(parents)) { - parents = [parents]; - } + return self; +} - // try to verify with each possible parent (typically only one) - var verified = false; - while(!verified && parents.length > 0) { - parent = parents.shift(); - try { - verified = parent.verify(cert); - } catch(ex) { - // failure to verify, don't care why, try next one - } - } +function makeError(msg, level, fatal) { + const err = new Error(msg); + if (typeof level === 'boolean') { + fatal = level; + err.level = 'protocol'; + } else { + err.level = level || 'protocol'; + } + err.fatal = !!fatal; + return err; +} - if(!verified) { - error = { - message: 'Certificate signature is invalid.', - error: pki.certificateError.bad_certificate - }; - } - } +function writeUInt32BE(buf, value, offset) { + buf[offset++] = (value >>> 24); + buf[offset++] = (value >>> 16); + buf[offset++] = (value >>> 8); + buf[offset++] = value; + return offset; +} - if(error === null && (!parent || selfSigned) && - !caStore.hasCertificate(cert)) { - // no parent issuer and certificate itself is not trusted - error = { - message: 'Certificate is not trusted.', - error: pki.certificateError.unknown_ca - }; - } +const utilBufferParser = makeBufferParser(); + +module.exports = { + bufferCopy, + bufferSlice, + FastBuffer, + bufferFill: (buf, value, start, end) => { + return TypedArrayFill.call(buf, value, start, end); + }, + makeError, + doFatalError: (protocol, msg, level, reason) => { + let err; + if (DISCONNECT_REASON === undefined) + ({ DISCONNECT_REASON } = __nccwpck_require__(6832)); + if (msg instanceof Error) { + // doFatalError(protocol, err[, reason]) + err = msg; + if (typeof level !== 'number') + reason = DISCONNECT_REASON.PROTOCOL_ERROR; + else + reason = level; + } else { + // doFatalError(protocol, msg[, level[, reason]]) + err = makeError(msg, level, true); + } + if (typeof reason !== 'number') + reason = DISCONNECT_REASON.PROTOCOL_ERROR; + protocol.disconnect(reason); + protocol._destruct(); + protocol._onError(err); + return Infinity; + }, + readUInt32BE, + writeUInt32BE, + writeUInt32LE: (buf, value, offset) => { + buf[offset++] = value; + buf[offset++] = (value >>> 8); + buf[offset++] = (value >>> 16); + buf[offset++] = (value >>> 24); + return offset; + }, + makeBufferParser, + bufferParser: makeBufferParser(), + readString: (buffer, start, dest, maxLen) => { + if (typeof dest === 'number') { + maxLen = dest; + dest = undefined; } - // TODO: 3. check revoked + if (start === undefined) + start = 0; - // 4. check for matching issuer/subject - if(error === null && parent && !cert.isIssuer(parent)) { - // parent is not issuer - error = { - message: 'Certificate issuer is invalid.', - error: pki.certificateError.bad_certificate - }; - } + const left = (buffer.length - start); + if (start < 0 || start >= buffer.length || left < 4) + return; - // 5. TODO: check names with permitted names tree + const len = readUInt32BE(buffer, start); + if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) + return; - // 6. TODO: check names against excluded names tree + start += 4; + const end = start + len; + buffer._pos = end; - // 7. check for unsupported critical extensions - if(error === null) { - // supported extensions - var se = { - keyUsage: true, - basicConstraints: true - }; - for(var i = 0; error === null && i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if(ext.critical && !(ext.name in se)) { - error = { - message: - 'Certificate has an unsupported critical extension.', - error: pki.certificateError.unsupported_certificate - }; - } - } + if (dest) { + if (Buffer.isBuffer(dest)) + return bufferCopy(buffer, dest, start, end); + return buffer.utf8Slice(start, end); } - - // 8. check for CA if cert is not first or is the only certificate - // remaining in chain with no parent or is self-signed - if(error === null && - (!first || (chain.length === 0 && (!parent || selfSigned)))) { - // first check keyUsage extension and then basic constraints - var bcExt = cert.getExtension('basicConstraints'); - var keyUsageExt = cert.getExtension('keyUsage'); - if(keyUsageExt !== null) { - // keyCertSign must be true and there must be a basic - // constraints extension - if(!keyUsageExt.keyCertSign || bcExt === null) { - // bad certificate - error = { - message: - 'Certificate keyUsage or basicConstraints conflict ' + - 'or indicate that the certificate is not a CA. ' + - 'If the certificate is the only one in the chain or ' + - 'isn\'t the first then the certificate must be a ' + - 'valid CA.', - error: pki.certificateError.bad_certificate - }; + return bufferSlice(buffer, start, end); + }, + sigSSHToASN1: (sig, type) => { + switch (type) { + case 'ssh-dss': { + if (sig.length > 40) + return sig; + // Change bare signature r and s values to ASN.1 BER values for OpenSSL + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + let r = sig.slice(0, 20); + let s = sig.slice(20); + if (r[0] & 0x80) { + const rNew = Buffer.allocUnsafe(21); + rNew[0] = 0x00; + r.copy(rNew, 1); + r = rNew; + } else if (r[0] === 0x00 && !(r[1] & 0x80)) { + r = r.slice(1); } - } - // basic constraints cA flag must be set - if(error === null && bcExt !== null && !bcExt.cA) { - // bad certificate - error = { - message: - 'Certificate basicConstraints indicates the certificate ' + - 'is not a CA.', - error: pki.certificateError.bad_certificate - }; - } - // if error is not null and keyUsage is available, then we know it - // has keyCertSign and there is a basic constraints extension too, - // which means we can check pathLenConstraint (if it exists) - if(error === null && keyUsageExt !== null && - 'pathLenConstraint' in bcExt) { - // pathLen is the maximum # of intermediate CA certs that can be - // found between the current certificate and the end-entity (depth 0) - // certificate; this number does not include the end-entity (depth 0, - // last in the chain) even if it happens to be a CA certificate itself - var pathLen = depth - 1; - if(pathLen > bcExt.pathLenConstraint) { - // pathLenConstraint violated, bad certificate - error = { - message: - 'Certificate basicConstraints pathLenConstraint violated.', - error: pki.certificateError.bad_certificate - }; + if (s[0] & 0x80) { + const sNew = Buffer.allocUnsafe(21); + sNew[0] = 0x00; + s.copy(sNew, 1); + s = sNew; + } else if (s[0] === 0x00 && !(s[1] & 0x80)) { + s = s.slice(1); } + asnWriter.writeBuffer(r, Ber.Integer); + asnWriter.writeBuffer(s, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; } - } + case 'ecdsa-sha2-nistp256': + case 'ecdsa-sha2-nistp384': + case 'ecdsa-sha2-nistp521': { + utilBufferParser.init(sig, 0); + const r = utilBufferParser.readString(); + const s = utilBufferParser.readString(); + utilBufferParser.clear(); + if (r === undefined || s === undefined) + return; - // call application callback - var vfd = (error === null) ? true : error.error; - var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; - if(ret === true) { - // clear any set error - error = null; - } else { - // if passed basic tests, set default message and alert - if(vfd === true) { - error = { - message: 'The application rejected the certificate.', - error: pki.certificateError.bad_certificate - }; + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeBuffer(r, Ber.Integer); + asnWriter.writeBuffer(s, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; } - - // check for custom error info - if(ret || ret === 0) { - // set custom message and error - if(typeof ret === 'object' && !forge.util.isArray(ret)) { - if(ret.message) { - error.message = ret.message; - } - if(ret.error) { - error.error = ret.error; - } - } else if(typeof ret === 'string') { - // set custom error - error.error = ret; + default: + return sig; + } + }, + convertSignature: (signature, keyType) => { + switch (keyType) { + case 'ssh-dss': { + if (signature.length <= 40) + return signature; + // This is a quick and dirty way to get from BER encoded r and s that + // OpenSSL gives us, to just the bare values back to back (40 bytes + // total) like OpenSSH (and possibly others) are expecting + const asnReader = new Ber.Reader(signature); + asnReader.readSequence(); + let r = asnReader.readString(Ber.Integer, true); + let s = asnReader.readString(Ber.Integer, true); + let rOffset = 0; + let sOffset = 0; + if (r.length < 20) { + const rNew = Buffer.allocUnsafe(20); + rNew.set(r, 1); + r = rNew; + r[0] = 0; + } + if (s.length < 20) { + const sNew = Buffer.allocUnsafe(20); + sNew.set(s, 1); + s = sNew; + s[0] = 0; } + if (r.length > 20 && r[0] === 0) + rOffset = 1; + if (s.length > 20 && s[0] === 0) + sOffset = 1; + const newSig = + Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); + bufferCopy(r, newSig, rOffset, r.length, 0); + bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); + return newSig; + } + case 'ecdsa-sha2-nistp256': + case 'ecdsa-sha2-nistp384': + case 'ecdsa-sha2-nistp521': { + if (signature[0] === 0) + return signature; + // Convert SSH signature parameters to ASN.1 BER values for OpenSSL + const asnReader = new Ber.Reader(signature); + asnReader.readSequence(); + const r = asnReader.readString(Ber.Integer, true); + const s = asnReader.readString(Ber.Integer, true); + if (r === null || s === null) + return; + const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); + writeUInt32BE(newSig, r.length, 0); + newSig.set(r, 4); + writeUInt32BE(newSig, s.length, 4 + r.length); + newSig.set(s, 4 + 4 + r.length); + return newSig; } - - // throw error - throw error; } - // no longer first cert in chain - first = false; - ++depth; - } while(chain.length > 0); + return signature; + }, + sendPacket: (proto, packet, bypass) => { + if (!bypass && proto._kexinit !== undefined) { + // We're currently in the middle of a handshake - return true; + if (proto._queue === undefined) + proto._queue = []; + proto._queue.push(packet); + proto._debug && proto._debug('Outbound: ... packet queued'); + return false; + } + proto._cipher.encrypt(packet); + return true; + }, }; /***/ }), -/***/ 1223: +/***/ 6715: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var wrappy = __nccwpck_require__(2940) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) +"use strict"; - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) +const { kMaxLength } = __nccwpck_require__(4300); +const { + createInflate, + constants: { + DEFLATE, + INFLATE, + Z_DEFAULT_CHUNK, + Z_DEFAULT_COMPRESSION, + Z_DEFAULT_MEMLEVEL, + Z_DEFAULT_STRATEGY, + Z_DEFAULT_WINDOWBITS, + Z_PARTIAL_FLUSH, } - f.called = false - return f -} +} = __nccwpck_require__(9796); +const ZlibHandle = createInflate()._handle.constructor; -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f +function processCallback() { + throw new Error('Should not get here'); } +function zlibOnError(message, errno, code) { + const self = this._owner; + // There is no way to cleanly recover. + // Continuing only obscures problems. -/***/ }), - -/***/ 8341: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(1223) -var eos = __nccwpck_require__(1205) -var fs = __nccwpck_require__(7147) // 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' + const error = new Error(message); + error.errno = errno; + error.code = code; + self._err = error; } -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) -} +function _close(engine) { + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) + return; -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) + engine._handle.close(); + engine._handle = null; } -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 +class Zlib { + constructor(mode) { + const windowBits = Z_DEFAULT_WINDOWBITS; + const level = Z_DEFAULT_COMPRESSION; + const memLevel = Z_DEFAULT_MEMLEVEL; + const strategy = Z_DEFAULT_STRATEGY; + const dictionary = undefined; - if (isFn(stream.destroy)) return stream.destroy() + this._err = undefined; + this._writeState = new Uint32Array(2); + this._chunkSize = Z_DEFAULT_CHUNK; + this._maxOutputLength = kMaxLength; + this._outBuffer = Buffer.allocUnsafe(this._chunkSize); + this._outOffset = 0; - callback(err || new Error('stream was destroyed')) + this._handle = new ZlibHandle(mode); + this._handle._owner = this; + this._handle.onerror = zlibOnError; + this._handle.init(windowBits, + level, + memLevel, + strategy, + this._writeState, + processCallback, + dictionary); } -} -var call = function (fn) { - fn() -} + writeSync(chunk, retChunks) { + const handle = this._handle; + if (!handle) + throw new Error('Invalid Zlib instance'); -var pipe = function (from, to) { - return from.pipe(to) -} + let availInBefore = chunk.length; + let availOutBefore = this._chunkSize - this._outOffset; + let inOff = 0; + let availOutAfter; + let availInAfter; -var pump = function () { - var streams = Array.prototype.slice.call(arguments) - var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + let buffers; + let nread = 0; + const state = this._writeState; + let buffer = this._outBuffer; + let offset = this._outOffset; + const chunkSize = this._chunkSize; - if (Array.isArray(streams[0])) streams = streams[0] - if (streams.length < 2) throw new Error('pump requires two streams per minimum') + while (true) { + handle.writeSync(Z_PARTIAL_FLUSH, + chunk, // in + inOff, // in_off + availInBefore, // in_len + buffer, // out + offset, // out_off + availOutBefore); // out_len + if (this._err) + throw this._err; - 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) - }) - }) + availOutAfter = state[0]; + availInAfter = state[1]; - return streams.reduce(pipe) -} + const inDelta = availInBefore - availInAfter; + const have = availOutBefore - availOutAfter; -module.exports = pump + if (have > 0) { + const out = (offset === 0 && have === buffer.length + ? buffer + : buffer.slice(offset, offset + have)); + offset += have; + if (!buffers) + buffers = out; + else if (buffers.push === undefined) + buffers = [buffers, out]; + else + buffers.push(out); + nread += out.byteLength; + if (nread > this._maxOutputLength) { + _close(this); + throw new Error( + `Output length exceeded maximum of ${this._maxOutputLength}` + ); + } + } else if (have !== 0) { + throw new Error('have should not go down'); + } -/***/ }), + // Exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || offset >= chunkSize) { + availOutBefore = chunkSize; + offset = 0; + buffer = Buffer.allocUnsafe(chunkSize); + } -/***/ 7214: -/***/ ((module) => { + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += inDelta; + availInBefore = availInAfter; + } else { + break; + } + } -"use strict"; + this._outBuffer = buffer; + this._outOffset = offset; + if (nread === 0) + buffers = Buffer.alloc(0); -const codes = {}; + if (retChunks) { + buffers.totalLen = nread; + return buffers; + } -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error - } + if (buffers.push === undefined) + return buffers; - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) + const output = Buffer.allocUnsafe(nread); + for (let i = 0, p = 0; i < buffers.length; ++i) { + const buf = buffers[i]; + output.set(buf, p); + p += buf.length; } + return output; } +} - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } +class ZlibPacketWriter { + constructor(protocol) { + this.allocStart = 0; + this.allocStartKEX = 0; + this._protocol = protocol; + this._zlib = new Zlib(DEFLATE); } - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; + cleanup() { + if (this._zlib) + _close(this._zlib); + } - codes[code] = NodeError; -} + alloc(payloadSize, force) { + return Buffer.allocUnsafe(payloadSize); + } -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; + finalize(payload, force) { + if (this._protocol._kexinit === undefined || force) { + const output = this._zlib.writeSync(payload, true); + const packet = this._protocol._cipher.allocPacket(output.totalLen); + if (output.push === undefined) { + packet.set(output, 5); + } else { + for (let i = 0, p = 5; i < output.length; ++i) { + const chunk = output[i]; + packet.set(chunk, p); + p += chunk.length; + } + } + return packet; } - } else { - return `of ${thing} ${String(expected)}`; + return payload; } } -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} +class PacketWriter { + constructor(protocol) { + this.allocStart = 5; + this.allocStartKEX = 5; + this._protocol = protocol; + } -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} + cleanup() {} -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; + alloc(payloadSize, force) { + if (this._protocol._kexinit === undefined || force) + return this._protocol._cipher.allocPacket(payloadSize); + return Buffer.allocUnsafe(payloadSize); } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; + finalize(packet, force) { + return packet; } } -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; +class ZlibPacketReader { + constructor() { + this._zlib = new Zlib(INFLATE); } - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + cleanup() { + if (this._zlib) + _close(this._zlib); } - msg += `. Received type ${typeof actual}`; - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + read(data) { + return this._zlib.writeSync(data, false); + } +} -module.exports.q = codes; +class PacketReader { + cleanup() {} + + read(data) { + return data; + } +} + +module.exports = { + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter, +}; /***/ }), -/***/ 1359: +/***/ 2986: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. +// TODO: +// * convert listenerCount() usage to emit() return value checking? +// * emit error when connection severed early (e.g. before handshake) +// * add '.connected' or similar property to connection objects to allow +// immediate connection status checking -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; +const { Server: netServer } = __nccwpck_require__(1808); +const EventEmitter = __nccwpck_require__(2361); +const { listenerCount } = EventEmitter; - for (var key in obj) { - keys.push(key); - } +const { + CHANNEL_OPEN_FAILURE, + DEFAULT_CIPHER, + DEFAULT_COMPRESSION, + DEFAULT_KEX, + DEFAULT_MAC, + DEFAULT_SERVER_HOST_KEY, + DISCONNECT_REASON, + DISCONNECT_REASON_BY_VALUE, + SUPPORTED_CIPHER, + SUPPORTED_COMPRESSION, + SUPPORTED_KEX, + SUPPORTED_MAC, + SUPPORTED_SERVER_HOST_KEY, +} = __nccwpck_require__(6832); +const { init: cryptoInit } = __nccwpck_require__(5708); +const { KexInit } = __nccwpck_require__(4126); +const { parseKey } = __nccwpck_require__(2218); +const Protocol = __nccwpck_require__(9031); +const { SFTP } = __nccwpck_require__(2026); +const { writeUInt32BE } = __nccwpck_require__(9475); - return keys; -}; -/**/ +const { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD, +} = __nccwpck_require__(3204); +const { + ChannelManager, + generateAlgorithmList, + isWritable, + onChannelOpenFailure, + onCHANNEL_CLOSE, +} = __nccwpck_require__(834); -module.exports = Duplex; +const MAX_PENDING_AUTHS = 10; -var Readable = __nccwpck_require__(1433); +class AuthContext extends EventEmitter { + constructor(protocol, username, service, method, cb) { + super(); -var Writable = __nccwpck_require__(6993); + this.username = this.user = username; + this.service = service; + this.method = method; + this._initialResponse = false; + this._finalResponse = false; + this._multistep = false; + this._cbfinal = (allowed, methodsLeft, isPartial) => { + if (!this._finalResponse) { + this._finalResponse = true; + cb(this, allowed, methodsLeft, isPartial); + } + }; + this._protocol = protocol; + } -__nccwpck_require__(4124)(Duplex, Readable); + accept() { + this._cleanup && this._cleanup(); + this._initialResponse = true; + this._cbfinal(true); + } + reject(methodsLeft, isPartial) { + this._cleanup && this._cleanup(); + this._initialResponse = true; + this._cbfinal(false, methodsLeft, isPartial); + } +} -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +class KeyboardAuthContext extends AuthContext { + constructor(protocol, username, service, method, submethods, cb) { + super(protocol, username, service, method, cb); + + this._multistep = true; + + this._cb = undefined; + this._onInfoResponse = (responses) => { + const callback = this._cb; + if (callback) { + this._cb = undefined; + callback(responses); + } + }; + this.submethods = submethods; + this.on('abort', () => { + this._cb && this._cb(new Error('Authentication request aborted')); + }); } -} -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; + prompt(prompts, title, instructions, cb) { + if (!Array.isArray(prompts)) + prompts = [ prompts ]; - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; + if (typeof title === 'function') { + cb = title; + title = instructions = undefined; + } else if (typeof instructions === 'function') { + cb = instructions; + instructions = undefined; + } else if (typeof cb !== 'function') { + cb = undefined; + } - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); + for (let i = 0; i < prompts.length; ++i) { + if (typeof prompts[i] === 'string') { + prompts[i] = { + prompt: prompts[i], + echo: true + }; + } } + + this._cb = cb; + this._initialResponse = true; + + this._protocol.authInfoReq(title, instructions, prompts); } } -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); +class PKAuthContext extends AuthContext { + constructor(protocol, username, service, method, pkInfo, cb) { + super(protocol, username, service, method, cb); + + this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; + this.hashAlgo = pkInfo.hashAlgo; + this.signature = pkInfo.signature; + this.blob = pkInfo.blob; } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + + accept() { + if (!this.signature) { + this._initialResponse = true; + this._protocol.authPKOK(this.key.algo, this.key.data); + } else { + AuthContext.prototype.accept.call(this); + } } -}); // the no-half-open enforcer +} -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. +class HostbasedAuthContext extends AuthContext { + constructor(protocol, username, service, method, pkInfo, cb) { + super(protocol, username, service, method, cb); - process.nextTick(onEndNT, this); + this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; + this.hashAlgo = pkInfo.hashAlgo; + this.signature = pkInfo.signature; + this.blob = pkInfo.blob; + this.localHostname = pkInfo.localHostname; + this.localUsername = pkInfo.localUsername; + } } -function onEndNT(self) { - self.end(); -} +class PwdAuthContext extends AuthContext { + constructor(protocol, username, service, method, password, cb) { + super(protocol, username, service, method, cb); -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } + this.password = password; + this._changeCb = undefined; + } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + requestChange(prompt, cb) { + if (this._changeCb) + throw new Error('Change request already in progress'); + if (typeof prompt !== 'string') + throw new Error('prompt argument must be a string'); + if (typeof cb !== 'function') + throw new Error('Callback argument must be a function'); + this._changeCb = cb; + this._protocol.authPasswdChg(prompt); + } +} - this._readableState.destroyed = value; - this._writableState.destroyed = value; +class Session extends EventEmitter { + constructor(client, info, localChan) { + super(); + + this.type = 'session'; + this.subtype = undefined; + this.server = true; + this._ending = false; + this._channel = undefined; + this._chanInfo = { + type: 'session', + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; } -}); +} -/***/ }), -/***/ 1542: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +class Server extends EventEmitter { + constructor(cfg, listener) { + super(); + + if (typeof cfg !== 'object' || cfg === null) + throw new Error('Missing configuration object'); + + const hostKeys = Object.create(null); + const hostKeyAlgoOrder = []; -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. + const hostKeys_ = cfg.hostKeys; + if (!Array.isArray(hostKeys_)) + throw new Error('hostKeys must be an array'); + const cfgAlgos = ( + typeof cfg.algorithms === 'object' && cfg.algorithms !== null + ? cfg.algorithms + : {} + ); -module.exports = PassThrough; + const hostKeyAlgos = generateAlgorithmList( + cfgAlgos.serverHostKey, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY + ); + for (let i = 0; i < hostKeys_.length; ++i) { + let privateKey; + if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') + privateKey = parseKey(hostKeys_[i]); + else + privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); -var Transform = __nccwpck_require__(4415); + if (privateKey instanceof Error) + throw new Error(`Cannot parse privateKey: ${privateKey.message}`); -__nccwpck_require__(4124)(PassThrough, Transform); + if (Array.isArray(privateKey)) { + // OpenSSH's newer format only stores 1 key for now + privateKey = privateKey[0]; + } -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} + if (privateKey.getPrivatePEM() === null) + throw new Error('privateKey value contains an invalid private key'); -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; + // Discard key if we already found a key of the same type + if (hostKeyAlgoOrder.includes(privateKey.type)) + continue; -/***/ }), + if (privateKey.type === 'ssh-rsa') { + // SSH supports multiple signature hashing algorithms for RSA, so we add + // the algorithms in the desired order + let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); + const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); + const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); + if (sha1Pos === -1) { + // Fall back to giving SHA1 the lowest priority + sha1Pos = Infinity; + } + [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { + if (pos === -1) + return; -/***/ 1433: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let type; + switch (pos) { + case sha1Pos: type = 'ssh-rsa'; break; + case sha256Pos: type = 'rsa-sha2-256'; break; + case sha512Pos: type = 'rsa-sha2-512'; break; + default: return; + } -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. + // Store same RSA key under each hash algorithm name for convenience + hostKeys[type] = privateKey; + hostKeyAlgoOrder.push(type); + }); + } else { + hostKeys[privateKey.type] = privateKey; + hostKeyAlgoOrder.push(privateKey.type); + } + } -module.exports = Readable; -/**/ + const algorithms = { + kex: generateAlgorithmList( + cfgAlgos.kex, + DEFAULT_KEX, + SUPPORTED_KEX + ).concat(['kex-strict-s-v00@openssh.com']), + serverHostKey: hostKeyAlgoOrder, + cs: { + cipher: generateAlgorithmList( + cfgAlgos.cipher, + DEFAULT_CIPHER, + SUPPORTED_CIPHER + ), + mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), + compress: generateAlgorithmList( + cfgAlgos.compress, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION + ), + lang: [], + }, + sc: undefined, + }; + algorithms.sc = algorithms.cs; -var Duplex; -/**/ + if (typeof listener === 'function') + this.on('connection', listener); -Readable.ReadableState = ReadableState; -/**/ + const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); + const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); + const offer = new KexInit(algorithms); -var EE = (__nccwpck_require__(2361).EventEmitter); + this._srv = new netServer((socket) => { + if (this._connections >= this.maxConnections) { + socket.destroy(); + return; + } + ++this._connections; + socket.once('close', () => { + --this._connections; + }); -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + let debug; + if (origDebug) { + // Prepend debug output with a unique identifier in case there are + // multiple clients connected at the same time + const debugPrefix = `[${process.hrtime().join('.')}] `; + debug = (msg) => { + origDebug(`${debugPrefix}${msg}`); + }; + } -/**/ + // eslint-disable-next-line no-use-before-define + new Client(socket, hostKeys, ident, offer, debug, this, cfg); + }).on('error', (err) => { + this.emit('error', err); + }).on('listening', () => { + this.emit('listening'); + }).on('close', () => { + this.emit('close'); + }); + this._connections = 0; + this.maxConnections = Infinity; + } + injectSocket(socket) { + this._srv.emit('connection', socket); + } -var Stream = __nccwpck_require__(2387); -/**/ + listen(...args) { + this._srv.listen(...args); + return this; + } + address() { + return this._srv.address(); + } -var Buffer = (__nccwpck_require__(4300).Buffer); + getConnections(cb) { + this._srv.getConnections(cb); + return this; + } -var OurUint8Array = global.Uint8Array || function () {}; + close(cb) { + this._srv.close(cb); + return this; + } -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} + ref() { + this._srv.ref(); + return this; + } -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + unref() { + this._srv.unref(); + return this; + } } -/**/ +Server.KEEPALIVE_CLIENT_INTERVAL = 15000; +Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; -var debugUtil = __nccwpck_require__(3837); +class Client extends EventEmitter { + constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { + super(); -var debug; + let exchanges = 0; + let acceptedAuthSvc = false; + let pendingAuths = []; + let authCtx; + let kaTimer; + let onPacket; + const unsentGlobalRequestsReplies = []; + this._sock = socket; + this._chanMgr = new ChannelManager(this); + this._debug = debug; + this.noMoreSessions = false; + this.authenticated = false; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ + // Silence pre-header errors + function onClientPreHeaderError(err) {} + this.on('error', onClientPreHeaderError); + const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { + debug(`Debug output from client: ${JSON.stringify(msg)}`); + }); -var BufferList = __nccwpck_require__(6522); + const kaIntvl = ( + typeof srvCfg.keepaliveInterval === 'number' + && isFinite(srvCfg.keepaliveInterval) + && srvCfg.keepaliveInterval > 0 + ? srvCfg.keepaliveInterval + : ( + typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' + && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) + && Server.KEEPALIVE_CLIENT_INTERVAL > 0 + ? Server.KEEPALIVE_CLIENT_INTERVAL + : -1 + ) + ); + const kaCountMax = ( + typeof srvCfg.keepaliveCountMax === 'number' + && isFinite(srvCfg.keepaliveCountMax) + && srvCfg.keepaliveCountMax >= 0 + ? srvCfg.keepaliveCountMax + : ( + typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' + && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) + && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 + ? Server.KEEPALIVE_CLIENT_COUNT_MAX + : -1 + ) + ); + let kaCurCount = 0; + if (kaIntvl !== -1 && kaCountMax !== -1) { + this.once('ready', () => { + const onClose = () => { + clearInterval(kaTimer); + }; + this.on('close', onClose).on('end', onClose); + kaTimer = setInterval(() => { + if (++kaCurCount > kaCountMax) { + clearInterval(kaTimer); + const err = new Error('Keepalive timeout'); + err.level = 'client-timeout'; + this.emit('error', err); + this.end(); + } else { + // XXX: if the server ever starts sending real global requests to + // the client, we will need to add a dummy callback here to + // keep the correct reply order + proto.ping(); + } + }, kaIntvl); + }); + // TODO: re-verify keepalive behavior with OpenSSH + onPacket = () => { + kaTimer && kaTimer.refresh(); + kaCurCount = 0; + }; + } -var destroyImpl = __nccwpck_require__(7049); + const proto = this._protocol = new Protocol({ + server: true, + hostKeys, + ident, + offer, + onPacket, + greeting: srvCfg.greeting, + banner: srvCfg.banner, + onWrite: (data) => { + if (isWritable(socket)) + socket.write(data); + }, + onError: (err) => { + if (!proto._destruct) + socket.removeAllListeners('data'); + this.emit('error', err); + try { + socket.end(); + } catch {} + }, + onHeader: (header) => { + this.removeListener('error', onClientPreHeaderError); -var _require = __nccwpck_require__(9948), - getHighWaterMark = _require.getHighWaterMark; + const info = { + ip: socket.remoteAddress, + family: socket.remoteFamily, + port: socket.remotePort, + header, + }; + if (!server.emit('connection', this, info)) { + // auto reject + proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); + socket.end(); + return; + } -var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + if (header.greeting) + this.emit('greeting', header.greeting); + }, + onHandshakeComplete: (negotiated) => { + if (++exchanges > 1) + this.emit('rekey'); + this.emit('handshake', negotiated); + }, + debug, + messageHandlers: { + DEBUG: DEBUG_HANDLER, + DISCONNECT: (p, reason, desc) => { + if (reason !== DISCONNECT_REASON.BY_APPLICATION) { + if (!desc) { + desc = DISCONNECT_REASON_BY_VALUE[reason]; + if (desc === undefined) + desc = `Unexpected disconnection reason: ${reason}`; + } + const err = new Error(desc); + err.code = reason; + this.emit('error', err); + } + socket.end(); + }, + CHANNEL_OPEN: (p, info) => { + // Handle incoming requests from client + // Do early reject in some cases to prevent wasteful channel + // allocation + if ((info.type === 'session' && this.noMoreSessions) + || !this.authenticated) { + const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + return proto.channelOpenFail(info.sender, reasonCode); + } -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; + let localChan = -1; + let reason; + let replied = false; -__nccwpck_require__(4124)(Readable, Stream); + let accept; + const reject = () => { + if (replied) + return; + replied = true; -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + if (reason === undefined) { + if (localChan === -1) + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + else + reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; + } -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. + if (localChan !== -1) + this._chanMgr.remove(localChan); + proto.channelOpenFail(info.sender, reason, ''); + }; + const reserveChannel = () => { + localChan = this._chanMgr.add(); - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} + if (localChan === -1) { + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + if (debug) { + debug('Automatic rejection of incoming channel open: ' + + 'no channels available'); + } + } -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(1359); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. + return (localChan !== -1); + }; - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away + const data = info.data; + switch (info.type) { + case 'session': + if (listenerCount(this, 'session') && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" + const instance = new Session(this, info, localChan); + this._chanMgr.update(localChan, instance); - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() + proto.channelOpenConfirm(info.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE); - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. + return instance; + }; - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. + this.emit('session', accept, reject); + return; + } + break; + case 'direct-tcpip': + if (listenerCount(this, 'tcpip') && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. + const chanInfo = { + type: undefined, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + const stream = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(localChan, stream); - this.autoDestroy = !!options.autoDestroy; // has it been destroyed + proto.channelOpenConfirm(info.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE); - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + return stream; + }; - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + this.emit('tcpip', accept, reject, data); + return; + } + break; + case 'direct-streamlocal@openssh.com': + if (listenerCount(this, 'openssh.streamlocal') + && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + const chanInfo = { + type: undefined, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; - this.readingMore = false; - this.decoder = null; - this.encoding = null; + const stream = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(localChan, stream); - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} + proto.channelOpenConfirm(info.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE); -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(1359); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 + return stream; + }; - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy + this.emit('openssh.streamlocal', accept, reject, data); + return; + } + break; + default: + // Automatically reject any unsupported channel open requests + reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; + if (debug) { + debug('Automatic rejection of unsupported incoming channel open' + + ` type: ${info.type}`); + } + } - this.readable = true; + if (reason === undefined) { + reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + if (debug) { + debug('Automatic rejection of unexpected incoming channel open' + + ` for: ${info.type}`); + } + } - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } + reject(); + }, + CHANNEL_OPEN_CONFIRMATION: (p, info) => { + const channel = this._chanMgr.get(info.recipient); + if (typeof channel !== 'function') + return; - Stream.call(this); -} + const chanInfo = { + type: channel.type, + incoming: { + id: info.recipient, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: 'open' + }, + outgoing: { + id: info.sender, + window: info.window, + packetSize: info.packetSize, + state: 'open' + } + }; -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } + const instance = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(info.recipient, instance); + channel(undefined, instance); + }, + CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== 'function') + return; - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + const info = { reason, description }; + onChannelOpenFailure(this, recipient, info, channel); + }, + CHANNEL_DATA: (p, recipient, data) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; + // The remote party should not be sending us data if there is no + // window space available ... + // TODO: raise error on data with not enough window? + if (channel.incoming.window === 0) + return; -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. + channel.incoming.window -= data.length; + if (channel.push(data) === false) { + channel._waitChanDrain = true; + return; + } -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + if (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { + // NOOP -- should not be sent by client + }, + CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } + // The other side is allowing us to send `amount` more bytes of data + channel.outgoing.window += amount; - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } + if (channel._waitWindow) { + channel._waitWindow = false; - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() + if (channel._chunk) { + channel._write(channel._chunk, null, channel._chunkcb); + } else if (channel._chunkcb) { + channel._chunkcb(); + } else if (channel._chunkErr) { + channel.stderr._write(channel._chunkErr, + null, + channel._chunkcbErr); + } else if (channel._chunkcbErr) { + channel._chunkcbErr(); + } + } + }, + CHANNEL_SUCCESS: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; + if (channel._callbacks.length) + channel._callbacks.shift()(false); + }, + CHANNEL_FAILURE: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (channel._callbacks.length) + channel._callbacks.shift()(true); + }, + CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { + const session = this._chanMgr.get(recipient); + if (typeof session !== 'object' || session === null) + return; - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + let replied = false; + let accept; + let reject; - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; + if (session.constructor !== Session) { + // normal Channel instance + if (wantReply) + proto.channelFailure(session.outgoing.id); + return; + } - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. + if (wantReply) { + // "real session" requests will have custom accept behaviors + if (type !== 'shell' + && type !== 'exec' + && type !== 'subsystem') { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; + proto.channelSuccess(session._chanInfo.outgoing.id); + }; + } - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} + reject = () => { + if (replied || session._ending || session._channel) + return; + replied = true; -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } + proto.channelFailure(session._chanInfo.outgoing.id); + }; + } - maybeReadMore(stream, state); -} + if (session._ending) { + reject && reject(); + return; + } -function chunkInvalid(state, chunk) { - var er; + switch (type) { + // "pre-real session start" requests + case 'env': + if (listenerCount(session, 'env')) { + session.emit('env', accept, reject, { + key: data.name, + val: data.value + }); + return; + } + break; + case 'pty-req': + if (listenerCount(session, 'pty')) { + session.emit('pty', accept, reject, data); + return; + } + break; + case 'window-change': + if (listenerCount(session, 'window-change')) + session.emit('window-change', accept, reject, data); + else + reject && reject(); + break; + case 'x11-req': + if (listenerCount(session, 'x11')) { + session.emit('x11', accept, reject, data); + return; + } + break; + // "post-real session start" requests + case 'signal': + if (listenerCount(session, 'signal')) { + session.emit('signal', accept, reject, { + name: data + }); + return; + } + break; + // XXX: is `auth-agent-req@openssh.com` really "post-real session + // start"? + case 'auth-agent-req@openssh.com': + if (listenerCount(session, 'auth-agent')) { + session.emit('auth-agent', accept, reject); + return; + } + break; + // "real session start" requests + case 'shell': + if (listenerCount(session, 'shell')) { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); - return er; -} + const channel = new Channel( + this, session._chanInfo, { server: true } + ); -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. + channel.subtype = session.subtype = type; + session._channel = channel; + return channel; + }; -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + session.emit('shell', accept, reject); + return; + } + break; + case 'exec': + if (listenerCount(session, 'exec')) { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); - var p = this._readableState.buffer.head; - var content = ''; + const channel = new Channel( + this, session._chanInfo, { server: true } + ); - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } + channel.subtype = session.subtype = type; + session._channel = channel; - this._readableState.buffer.clear(); + return channel; + }; - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB + session.emit('exec', accept, reject, { + command: data + }); + return; + } + break; + case 'subsystem': { + let useSFTP = (data === 'sftp'); + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); -var MAX_HWM = 0x40000000; + let instance; + if (useSFTP) { + instance = new SFTP(this, session._chanInfo, { + server: true, + debug, + }); + } else { + instance = new Channel( + this, session._chanInfo, { server: true } + ); + instance.subtype = + session.subtype = `${type}:${data}`; + } + session._channel = instance; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } + return instance; + }; - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. + if (data === 'sftp') { + if (listenerCount(session, 'sftp')) { + session.emit('sftp', accept, reject); + return; + } + useSFTP = false; + } + if (listenerCount(session, 'subsystem')) { + session.emit('subsystem', accept, reject, { + name: data + }); + return; + } + break; + } + } + debug && debug( + `Automatic rejection of incoming channel request: ${type}` + ); + reject && reject(); + }, + CHANNEL_EOF: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + if (channel.constructor === Session) { + if (!channel._ending) { + channel._ending = true; + channel.emit('eof'); + channel.emit('end'); + } + channel = channel._channel; + if (!channel) + return; + } -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; + if (channel.incoming.state !== 'open') + return; + channel.incoming.state = 'eof'; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. + if (channel.readable) + channel.push(null); + }, + CHANNEL_CLOSE: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== 'object' || channel === null) + return; + if (channel.constructor === Session) { + channel._ending = true; + channel.emit('close'); + channel = channel._channel; + if (!channel) + return; + } - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough + onCHANNEL_CLOSE(this, recipient, channel); + }, + // Begin service/auth-related ========================================== + SERVICE_REQUEST: (p, service) => { + if (exchanges === 0 + || acceptedAuthSvc + || this.authenticated + || service !== 'ssh-userauth') { + proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); + socket.end(); + return; + } - if (!state.ended) { - state.needReadable = true; - return 0; - } + acceptedAuthSvc = true; + proto.serviceAccept(service); + }, + USERAUTH_REQUEST: (p, username, service, method, methodData) => { + if (exchanges === 0 + || this.authenticated + || (authCtx + && (authCtx.username !== username + || authCtx.service !== service)) + // TODO: support hostbased auth + || (method !== 'password' + && method !== 'publickey' + && method !== 'hostbased' + && method !== 'keyboard-interactive' + && method !== 'none') + || pendingAuths.length === MAX_PENDING_AUTHS) { + proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); + socket.end(); + return; + } else if (service !== 'ssh-connection') { + proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); + socket.end(); + return; + } - return state.length; -} // you can override either this method, or the async _read(n) below. + let ctx; + switch (method) { + case 'keyboard-interactive': + ctx = new KeyboardAuthContext(proto, username, service, method, + methodData, onAuthDecide); + break; + case 'publickey': + ctx = new PKAuthContext(proto, username, service, method, + methodData, onAuthDecide); + break; + case 'hostbased': + ctx = new HostbasedAuthContext(proto, username, service, method, + methodData, onAuthDecide); + break; + case 'password': + if (authCtx + && authCtx instanceof PwdAuthContext + && authCtx._changeCb) { + const cb = authCtx._changeCb; + authCtx._changeCb = undefined; + cb(methodData.newPassword); + return; + } + ctx = new PwdAuthContext(proto, username, service, method, + methodData, onAuthDecide); + break; + case 'none': + ctx = new AuthContext(proto, username, service, method, + onAuthDecide); + break; + } + if (authCtx) { + if (!authCtx._initialResponse) { + return pendingAuths.push(ctx); + } else if (authCtx._multistep && !authCtx._finalResponse) { + // RFC 4252 says to silently abort the current auth request if a + // new auth request comes in before the final response from an + // auth method that requires additional request/response exchanges + // -- this means keyboard-interactive for now ... + authCtx._cleanup && authCtx._cleanup(); + authCtx.emit('abort'); + } + } -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. + authCtx = ctx; - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } + if (listenerCount(this, 'authentication')) + this.emit('authentication', authCtx); + else + authCtx.reject(); + }, + USERAUTH_INFO_RESPONSE: (p, responses) => { + if (authCtx && authCtx instanceof KeyboardAuthContext) + authCtx._onInfoResponse(responses); + }, + // End service/auth-related ============================================ + GLOBAL_REQUEST: (p, name, wantReply, data) => { + const reply = { + type: null, + buf: null + }; - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + function setReply(type, buf) { + reply.type = type; + reply.buf = buf; + sendReplies(); + } - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. + if (wantReply) + unsentGlobalRequestsReplies.push(reply); + if ((name === 'tcpip-forward' + || name === 'cancel-tcpip-forward' + || name === 'no-more-sessions@openssh.com' + || name === 'streamlocal-forward@openssh.com' + || name === 'cancel-streamlocal-forward@openssh.com') + && listenerCount(this, 'request') + && this.authenticated) { + let accept; + let reject; - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + if (wantReply) { + let replied = false; + accept = (chosenPort) => { + if (replied) + return; + replied = true; + let bufPort; + if (name === 'tcpip-forward' + && data.bindPort === 0 + && typeof chosenPort === 'number') { + bufPort = Buffer.allocUnsafe(4); + writeUInt32BE(bufPort, chosenPort, 0); + } + setReply('SUCCESS', bufPort); + }; + reject = () => { + if (replied) + return; + replied = true; + setReply('FAILURE'); + }; + } - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. + if (name === 'no-more-sessions@openssh.com') { + this.noMoreSessions = true; + accept && accept(); + return; + } + this.emit('request', accept, reject, name, data); + } else if (wantReply) { + setReply('FAILURE'); + } + }, + }, + }); - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. + socket.pause(); + cryptoInit.then(() => { + proto.start(); + socket.on('data', (data) => { + try { + proto.parse(data, 0, data.length); + } catch (ex) { + this.emit('error', ex); + try { + if (isWritable(socket)) + socket.end(); + } catch {} + } + }); + socket.resume(); + }).catch((err) => { + this.emit('error', err); + try { + if (isWritable(socket)) + socket.end(); + } catch {} + }); + socket.on('error', (err) => { + err.level = 'socket'; + this.emit('error', err); + }).once('end', () => { + debug && debug('Socket ended'); + proto.cleanup(); + this.emit('end'); + }).once('close', () => { + debug && debug('Socket closed'); + proto.cleanup(); + this.emit('close'); - if (state.length === 0) state.needReadable = true; // call internal read method + const err = new Error('No response from server'); - this._read(state.highWaterMark); + // Simulate error for pending channels and close any open channels + this._chanMgr.cleanup(err); + }); - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. + const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { + if (authCtx === ctx && !this.authenticated) { + if (allowed) { + authCtx = undefined; + this.authenticated = true; + proto.authSuccess(); + pendingAuths = []; + this.emit('ready'); + } else { + proto.authFailure(methodsLeft, isPartial); + if (pendingAuths.length) { + authCtx = pendingAuths.pop(); + if (listenerCount(this, 'authentication')) + this.emit('authentication', authCtx); + else + authCtx.reject(); + } + } + } + }; - if (!state.reading) n = howMuchToRead(nOrig, state); + function sendReplies() { + while (unsentGlobalRequestsReplies.length > 0 + && unsentGlobalRequestsReplies[0].type) { + const reply = unsentGlobalRequestsReplies.shift(); + if (reply.type === 'SUCCESS') + proto.requestSuccess(reply.buf); + if (reply.type === 'FAILURE') + proto.requestFailure(); + } + } } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; + end() { + if (this._sock && isWritable(this._sock)) { + this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); + this._sock.end(); + } + return this; } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); + x11(originAddr, originPort, cb) { + const opts = { originAddr, originPort }; + openChannel(this, 'x11', opts, cb); + return this; } - if (ret !== null) this.emit('data', ret); - return ret; -}; + forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { + const opts = { boundAddr, boundPort, remoteAddr, remotePort }; + openChannel(this, 'forwarded-tcpip', opts, cb); + return this; + } -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; + openssh_forwardOutStreamLocal(socketPath, cb) { + const opts = { socketPath }; + openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); + return this; + } - if (state.decoder) { - var chunk = state.decoder.end(); + rekey(cb) { + let error; - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + try { + this._protocol.rekey(); + } catch (ex) { + error = ex; } - } - - state.ended = true; - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; + // TODO: re-throw error if no callback? - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); + if (typeof cb === 'function') { + if (error) + process.nextTick(cb, error); + else + this.once('rekey', cb); } } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; + setNoDelay(noDelay) { + if (this._sock && typeof this._sock.setNoDelay === 'function') + this._sock.setNoDelay(noDelay); - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); + return this; } } -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} +function openChannel(self, type, opts, cb) { + // Ask the client to open a channel for some purpose (e.g. a forwarded TCP + // connection) + const initWindow = MAX_WINDOW; + const maxPacket = PACKET_SIZE; -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; + if (typeof opts === 'function') { + cb = opts; + opts = {}; } - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - + const wrapper = (err, stream) => { + cb(err, stream); + }; + wrapper.type = type; -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; + const localChan = self._chanMgr.add(wrapper); -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + if (localChan === -1) { + cb(new Error('No free channels available')); + return; + } - switch (state.pipesCount) { - case 0: - state.pipes = dest; + switch (type) { + case 'forwarded-tcpip': + self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); break; - - case 1: - state.pipes = [state.pipes, dest]; + case 'x11': + self._protocol.x11(localChan, initWindow, maxPacket, opts); break; - - default: - state.pipes.push(dest); + case 'forwarded-streamlocal@openssh.com': + self._protocol.openssh_forwardedStreamLocal( + localChan, initWindow, maxPacket, opts + ); break; + default: + throw new Error(`Unsupported channel type: ${type}`); } +} - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. +function compareNumbers(a, b) { + return a - b; +} +module.exports = Server; +module.exports.IncomingClient = Client; - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken +/***/ }), - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. +/***/ 834: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } +"use strict"; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); +const { SFTP } = __nccwpck_require__(2026); - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } +const MAX_CHANNEL = 2 ** 32 - 1; - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. +function onChannelOpenFailure(self, recipient, info, cb) { + self._chanMgr.remove(recipient); + if (typeof cb !== 'function') + return; + + let err; + if (info instanceof Error) { + err = info; + } else if (typeof info === 'object' && info !== null) { + err = new Error(`(SSH) Channel open failure: ${info.description}`); + err.reason = info.reason; + } else { + err = new Error( + '(SSH) Channel open failure: server closed channel unexpectedly' + ); + err.reason = ''; + } + cb(err); +} - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. +function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { + if (typeof channel === 'function') { + // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when + // requesting to open a channel + onChannelOpenFailure(self, recipient, err, channel); + return; + } + if (typeof channel !== 'object' || channel === null) + return; - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + if (channel.incoming && channel.incoming.state === 'closed') + return; - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } + self._chanMgr.remove(recipient); - dest.once('close', onclose); + if (channel.server && channel.constructor.name === 'Session') + return; - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + channel.incoming.state = 'closed'; + + if (channel.readable) + channel.push(null); + if (channel.server) { + if (channel.stderr.writable) + channel.stderr.end(); + } else if (channel.stderr.readable) { + channel.stderr.push(null); } - dest.once('finish', onfinish); + if (channel.constructor !== SFTP + && (channel.outgoing.state === 'open' + || channel.outgoing.state === 'eof') + && !dead) { + channel.close(); + } + if (channel.outgoing.state === 'closing') + channel.outgoing.state = 'closed'; - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to + const readState = channel._readableState; + const writeState = channel._writableState; + if (writeState && !writeState.ending && !writeState.finished && !dead) + channel.end(); + // Take care of any outstanding channel requests + const chanCallbacks = channel._callbacks; + channel._callbacks = []; + for (let i = 0; i < chanCallbacks.length; ++i) + chanCallbacks[i](true); - dest.emit('pipe', src); // start the flow if it hasn't been started already. + if (channel.server) { + if (!channel.readable + || channel.destroyed + || (readState && readState.endEmitted)) { + channel.emit('close'); + } else { + channel.once('end', () => channel.emit('close')); + } + } else { + let doClose; + switch (channel.type) { + case 'direct-streamlocal@openssh.com': + case 'direct-tcpip': + doClose = () => channel.emit('close'); + break; + default: { + // Align more with node child processes, where the close event gets + // the same arguments as the exit event + const exit = channel._exit; + doClose = () => { + if (exit.code === null) + channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); + else + channel.emit('close', exit.code); + }; + } + } + if (!channel.readable + || channel.destroyed + || (readState && readState.endEmitted)) { + doClose(); + } else { + channel.once('end', doClose); + } - if (!state.flowing) { - debug('pipe resume'); - src.resume(); + const errReadState = channel.stderr._readableState; + if (!channel.stderr.readable + || channel.stderr.destroyed + || (errReadState && errReadState.endEmitted)) { + channel.stderr.emit('close'); + } else { + channel.stderr.once('end', () => channel.stderr.emit('close')); + } } +} - return dest; -}; +class ChannelManager { + constructor(client) { + this._client = client; + this._channels = {}; + this._cur = -1; + this._count = 0; + } + add(val) { + // Attempt to reserve an id -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; + let id; + // Optimized paths + if (this._cur < MAX_CHANNEL) { + id = ++this._cur; + } else if (this._count === 0) { + // Revert and reset back to fast path once we no longer have any channels + // open + this._cur = 0; + id = 0; + } else { + // Slower lookup path - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); + // This path is triggered we have opened at least MAX_CHANNEL channels + // while having at least one channel open at any given time, so we have + // to search for a free id. + const channels = this._channels; + for (let i = 0; i < MAX_CHANNEL; ++i) { + if (channels[i] === undefined) { + id = i; + break; + } + } } - }; -} -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + if (id === undefined) + return -1; - if (state.pipesCount === 0) return this; // just one destination. most common case. + this._channels[id] = (val || true); + ++this._count; - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + return id; + } + update(id, val) { + if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + if (val && this._channels[id]) + this._channels[id] = val; + } + get(id) { + if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); + return this._channels[id]; + } + remove(id) { + if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + if (this._channels[id]) { + delete this._channels[id]; + if (this._count) + --this._count; + } + } + cleanup(err) { + const channels = this._channels; + this._channels = {}; + this._cur = -1; + this._count = 0; - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); + const chanIDs = Object.keys(channels); + const client = this._client; + for (let i = 0; i < chanIDs.length; ++i) { + const id = +chanIDs[i]; + const channel = channels[id]; + onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); } + } +} - return this; - } // try to find the right one. +const isRegExp = (() => { + const toString = Object.prototype.toString; + return (val) => toString.call(val) === '[object RegExp]'; +})(); +function generateAlgorithmList(algoList, defaultList, supportedList) { + if (Array.isArray(algoList) && algoList.length > 0) { + // Exact list + for (let i = 0; i < algoList.length; ++i) { + if (supportedList.indexOf(algoList[i]) === -1) + throw new Error(`Unsupported algorithm: ${algoList[i]}`); + } + return algoList; + } - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something + if (typeof algoList === 'object' && algoList !== null) { + // Operations based on the default list + const keys = Object.keys(algoList); + let list = defaultList; + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + let val = algoList[key]; + switch (key) { + case 'append': + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = 0; j < val.length; ++j) { + const append = val[j]; + if (typeof append === 'string') { + if (!append || list.indexOf(append) !== -1) + continue; + if (supportedList.indexOf(append) === -1) + throw new Error(`Unsupported algorithm: ${append}`); + if (list === defaultList) + list = list.slice(); + list.push(append); + } else if (isRegExp(append)) { + for (let k = 0; k < supportedList.length; ++k) { + const algo = supportedList[k]; + if (append.test(algo)) { + if (list.indexOf(algo) !== -1) + continue; + if (list === defaultList) + list = list.slice(); + list.push(algo); + } + } + } + } + } + break; + case 'prepend': + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = val.length; j >= 0; --j) { + const prepend = val[j]; + if (typeof prepend === 'string') { + if (!prepend || list.indexOf(prepend) !== -1) + continue; + if (supportedList.indexOf(prepend) === -1) + throw new Error(`Unsupported algorithm: ${prepend}`); + if (list === defaultList) + list = list.slice(); + list.unshift(prepend); + } else if (isRegExp(prepend)) { + for (let k = supportedList.length; k >= 0; --k) { + const algo = supportedList[k]; + if (prepend.test(algo)) { + if (list.indexOf(algo) !== -1) + continue; + if (list === defaultList) + list = list.slice(); + list.unshift(algo); + } + } + } + } + } + break; + case 'remove': + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = 0; j < val.length; ++j) { + const search = val[j]; + if (typeof search === 'string') { + if (!search) + continue; + const idx = list.indexOf(search); + if (idx === -1) + continue; + if (list === defaultList) + list = list.slice(); + list.splice(idx, 1); + } else if (isRegExp(search)) { + for (let k = 0; k < list.length; ++k) { + if (search.test(list[k])) { + if (list === defaultList) + list = list.slice(); + list.splice(k, 1); + --k; + } + } + } + } + } + break; + } + } + return list; + } -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; + return defaultList; +} - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused +module.exports = { + ChannelManager, + generateAlgorithmList, + onChannelOpenFailure, + onCHANNEL_CLOSE, + isWritable: (stream) => { + // XXX: hack to workaround regression in node + // See: https://github.com/nodejs/node/issues/36029 + return (stream + && stream.writable + && stream._readableState + && stream._readableState.ended === false); + }, +}; - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } +/***/ }), + +/***/ 5147: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { EventEmitter } = __nccwpck_require__(2361) +const STREAM_DESTROYED = new Error('Stream was destroyed') +const PREMATURE_CLOSE = new Error('Premature close') + +const queueTick = __nccwpck_require__(5322) +const FIFO = __nccwpck_require__(2958) + +/* eslint-disable no-multi-spaces */ + +// 27 bits used total (4 from shared, 13 from read, and 10 from write) +const MAX = ((1 << 27) - 1) + +// Shared state +const OPENING = 0b0001 +const PREDESTROYING = 0b0010 +const DESTROYING = 0b0100 +const DESTROYED = 0b1000 + +const NOT_OPENING = MAX ^ OPENING +const NOT_PREDESTROYING = MAX ^ PREDESTROYING + +// Read state (4 bit offset from shared state) +const READ_ACTIVE = 0b0000000000001 << 4 +const READ_UPDATING = 0b0000000000010 << 4 +const READ_PRIMARY = 0b0000000000100 << 4 +const READ_QUEUED = 0b0000000001000 << 4 +const READ_RESUMED = 0b0000000010000 << 4 +const READ_PIPE_DRAINED = 0b0000000100000 << 4 +const READ_ENDING = 0b0000001000000 << 4 +const READ_EMIT_DATA = 0b0000010000000 << 4 +const READ_EMIT_READABLE = 0b0000100000000 << 4 +const READ_EMITTED_READABLE = 0b0001000000000 << 4 +const READ_DONE = 0b0010000000000 << 4 +const READ_NEXT_TICK = 0b0100000000000 << 4 +const READ_NEEDS_PUSH = 0b1000000000000 << 4 + +// Combined read state +const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED +const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH +const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE +const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED + +const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE +const READ_NON_PRIMARY = MAX ^ READ_PRIMARY +const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH) +const READ_PUSHED = MAX ^ READ_NEEDS_PUSH +const READ_PAUSED = MAX ^ READ_RESUMED +const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE) +const READ_NOT_ENDING = MAX ^ READ_ENDING +const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING +const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK +const READ_NOT_UPDATING = MAX ^ READ_UPDATING + +// Write state (17 bit offset, 4 bit offset from shared state and 13 from read state) +const WRITE_ACTIVE = 0b0000000001 << 17 +const WRITE_UPDATING = 0b0000000010 << 17 +const WRITE_PRIMARY = 0b0000000100 << 17 +const WRITE_QUEUED = 0b0000001000 << 17 +const WRITE_UNDRAINED = 0b0000010000 << 17 +const WRITE_DONE = 0b0000100000 << 17 +const WRITE_EMIT_DRAIN = 0b0001000000 << 17 +const WRITE_NEXT_TICK = 0b0010000000 << 17 +const WRITE_WRITING = 0b0100000000 << 17 +const WRITE_FINISHING = 0b1000000000 << 17 + +const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING) +const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY +const WRITE_NOT_FINISHING = MAX ^ WRITE_FINISHING +const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED +const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED +const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK +const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING + +// Combined shared state +const ACTIVE = READ_ACTIVE | WRITE_ACTIVE +const NOT_ACTIVE = MAX ^ ACTIVE +const DONE = READ_DONE | WRITE_DONE +const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING +const OPEN_STATUS = DESTROY_STATUS | OPENING +const AUTO_DESTROY = DESTROY_STATUS | DONE +const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY +const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK +const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE +const IS_OPENING = OPEN_STATUS | TICKING + +// Combined shared state and read state +const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE +const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED +const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED +const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE +const SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH +const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE +const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY + +// Combined write state +const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE +const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED +const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE +const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE +const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED +const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE +const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING +const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE +const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE +const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY + +const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator') + +class WritableState { + constructor (stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) { + this.stream = stream + this.queue = new FIFO() + this.highWaterMark = highWaterMark + this.buffered = 0 + this.error = null + this.pipeline = null + this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr + this.byteLength = byteLengthWritable || byteLength || defaultByteLength + this.map = mapWritable || map + this.afterWrite = afterWrite.bind(this) + this.afterUpdateNextTick = updateWriteNT.bind(this) + } + + get ended () { + return (this.stream._duplexState & WRITE_DONE) !== 0 + } + + push (data) { + if (this.map !== null) data = this.map(data) + + this.buffered += this.byteLength(data) + this.queue.push(data) + + if (this.buffered < this.highWaterMark) { + this.stream._duplexState |= WRITE_QUEUED + return true + } + + this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED + return false } - return res; -}; + shift () { + const data = this.queue.shift() -Readable.prototype.addListener = Readable.prototype.on; + this.buffered -= this.byteLength(data) + if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); + return data + } - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); + end (data) { + if (typeof data === 'function') this.stream.once('finish', data) + else if (data !== undefined && data !== null) this.push(data) + this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY } - return res; -}; + autoBatch (data, cb) { + const buffer = [] + const stream = this.stream -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); + buffer.push(data) + while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) { + buffer.push(stream._writableState.shift()) + } - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); + if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null) + stream._writev(buffer, cb) } - return res; -}; + update () { + const stream = this.stream -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; + stream._duplexState |= WRITE_UPDATING - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); + do { + while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) { + const data = this.shift() + stream._duplexState |= WRITE_ACTIVE_AND_WRITING + stream._write(data, this.afterWrite) + } + + if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary() + } while (this.continueUpdate() === true) + + stream._duplexState &= WRITE_NOT_UPDATING } -} -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. + updateNonPrimary () { + const stream = this.stream + if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) { + stream._duplexState = (stream._duplexState | WRITE_ACTIVE) & WRITE_NOT_FINISHING + stream._final(afterFinal.bind(this)) + return + } -Readable.prototype.resume = function () { - var state = this._readableState; + if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { + if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { + stream._duplexState |= ACTIVE + stream._destroy(afterDestroy.bind(this)) + } + return + } - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + if ((stream._duplexState & IS_OPENING) === OPENING) { + stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING + stream._open(afterOpen.bind(this)) + } + } - state.flowing = !state.readableListening; - resume(this, state); + continueUpdate () { + if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false + this.stream._duplexState &= WRITE_NOT_NEXT_TICK + return true } - state.paused = false; - return this; -}; + updateCallback () { + if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update() + else this.updateNextTick() + } -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); + updateNextTick () { + if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return + this.stream._duplexState |= WRITE_NEXT_TICK + if ((this.stream._duplexState & WRITE_UPDATING) === 0) queueTick(this.afterUpdateNextTick) } } -function resume_(stream, state) { - debug('resume', state.reading); +class ReadableState { + constructor (stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) { + this.stream = stream + this.queue = new FIFO() + this.highWaterMark = highWaterMark + this.buffered = 0 + this.error = null + this.pipeline = null + this.byteLength = byteLengthReadable || byteLength || defaultByteLength + this.map = mapReadable || map + this.pipeTo = null + this.afterRead = afterRead.bind(this) + this.afterUpdateNextTick = updateReadNT.bind(this) + } - if (!state.reading) { - stream.read(0); + get ended () { + return (this.stream._duplexState & READ_DONE) !== 0 } - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} + pipe (pipeTo, cb) { + if (this.pipeTo !== null) throw new Error('Can only pipe to one destination') + if (typeof cb !== 'function') cb = null -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); + this.stream._duplexState |= READ_PIPE_DRAINED + this.pipeTo = pipeTo + this.pipeline = new Pipeline(this.stream, pipeTo, cb) - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); + if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes + + if (isStreamx(pipeTo)) { + pipeTo._writableState.pipeline = this.pipeline + if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes + pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself + } else { + const onerror = this.pipeline.done.bind(this.pipeline, pipeTo) + const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg + pipeTo.on('error', onerror) + pipeTo.on('close', onclose) + pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) + } + + pipeTo.on('drain', afterDrain.bind(this)) + this.stream.emit('piping', pipeTo) + pipeTo.emit('pipe', this.stream) } - this._readableState.paused = true; - return this; -}; + push (data) { + const stream = this.stream -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); + if (data === null) { + this.highWaterMark = 0 + stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED + return false + } - while (state.flowing && stream.read() !== null) { - ; + if (this.map !== null) data = this.map(data) + this.buffered += this.byteLength(data) + this.queue.push(data) + + stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED + + return this.buffered < this.highWaterMark } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. + shift () { + const data = this.queue.shift() -Readable.prototype.wrap = function (stream) { - var _this = this; + this.buffered -= this.byteLength(data) + if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED + return data + } - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); + unshift (data) { + const pending = [this.map !== null ? this.map(data) : data] + while (this.buffered > 0) pending.push(this.shift()) - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); + for (let i = 0; i < pending.length - 1; i++) { + const data = pending[i] + this.buffered += this.byteLength(data) + this.queue.push(data) } - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + this.push(pending[pending.length - 1]) + } - var ret = _this.push(chunk); + read () { + const stream = this.stream - if (!ret) { - paused = true; - stream.pause(); + if ((stream._duplexState & READ_STATUS) === READ_QUEUED) { + const data = this.shift() + if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED + if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data) + return data } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); + return null + } + + drain () { + const stream = this.stream + + while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) { + const data = this.shift() + if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED + if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data) } - } // proxy certain important events. + } + update () { + const stream = this.stream - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. + stream._duplexState |= READ_UPDATING + do { + this.drain() - this._read = function (n) { - debug('wrapped _read', n); + while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === 0) { + stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH + stream._read(this.afterRead) + this.drain() + } - if (paused) { - paused = false; - stream.resume(); - } - }; + if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) { + stream._duplexState |= READ_EMITTED_READABLE + stream.emit('readable') + } - return this; -}; + if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary() + } while (this.continueUpdate() === true) -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = __nccwpck_require__(3306); + stream._duplexState &= READ_NOT_UPDATING + } + + updateNonPrimary () { + const stream = this.stream + + if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) { + stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING + stream.emit('end') + if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING + if (this.pipeTo !== null) this.pipeTo.end() } - return createReadableStreamAsyncIterator(this); - }; -} + if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { + if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { + stream._duplexState |= ACTIVE + stream._destroy(afterDestroy.bind(this)) + } + return + } -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; + if ((stream._duplexState & IS_OPENING) === OPENING) { + stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING + stream._open(afterOpen.bind(this)) } } -}); // exposed for testing purposes only. -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; + continueUpdate () { + if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false + this.stream._duplexState &= READ_NOT_NEXT_TICK + return true } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); + updateCallback () { + if ((this.stream._readableState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update() + else this.updateNextTick() } - return ret; -} -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); + updateNextTick () { + if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return + this.stream._duplexState |= READ_NEXT_TICK + if ((this.stream._duplexState & READ_UPDATING) === 0) queueTick(this.afterUpdateNextTick) + } +} - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); +class TransformState { + constructor (stream) { + this.data = null + this.afterTransform = afterTransform.bind(stream) + this.afterFinal = null } } -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. +class Pipeline { + constructor (src, dst, cb) { + this.from = src + this.to = dst + this.afterPipe = cb + this.error = null + this.pipeToFinished = false + } - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + finished () { + this.pipeToFinished = true + } - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; + done (stream, err) { + if (err) this.error = err - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); + if (stream === this.to) { + this.to = null + + if (this.from !== null) { + if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) { + this.from.destroy(this.error || new Error('Writable stream closed prematurely')) + } + return } } - } -} -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = __nccwpck_require__(9082); - } + if (stream === this.from) { + this.from = null - return from(Readable, iterable, opts); - }; -} + if (this.to !== null) { + if ((stream._duplexState & READ_DONE) === 0) { + this.to.destroy(this.error || new Error('Readable stream closed before ending')) + } + return + } + } -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + if (this.afterPipe !== null) this.afterPipe(this.error) + this.to = this.from = this.afterPipe = null } - - return -1; } -/***/ }), - -/***/ 4415: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - +function afterDrain () { + this.stream._duplexState |= READ_PIPE_DRAINED + this.updateCallback() +} -module.exports = Transform; +function afterFinal (err) { + const stream = this.stream + if (err) stream.destroy(err) + if ((stream._duplexState & DESTROY_STATUS) === 0) { + stream._duplexState |= WRITE_DONE + stream.emit('finish') + } + if ((stream._duplexState & AUTO_DESTROY) === DONE) { + stream._duplexState |= DESTROYING + } -var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + stream._duplexState &= WRITE_NOT_ACTIVE -var Duplex = __nccwpck_require__(1359); + // no need to wait the extra tick here, so we short circuit that + if ((stream._duplexState & WRITE_UPDATING) === 0) this.update() + else this.updateNextTick() +} -__nccwpck_require__(4124)(Transform, Duplex); +function afterDestroy (err) { + const stream = this.stream -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; + if (!err && this.error !== STREAM_DESTROYED) err = this.error + if (err) stream.emit('error', err) + stream._duplexState |= DESTROYED + stream.emit('close') - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } + const rs = stream._readableState + const ws = stream._writableState - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; + if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err) - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); + if (ws !== null) { + while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false) + if (ws.pipeline !== null) ws.pipeline.done(stream, err) } } -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. +function afterWrite (err) { + const stream = this.stream - this._readableState.sync = false; + if (err) stream.destroy(err) + stream._duplexState &= WRITE_NOT_ACTIVE - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. + if (this.drains !== null) tickDrains(this.drains) + if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) { + stream._duplexState &= WRITE_DRAINED + if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) { + stream.emit('drain') + } + } - this.on('prefinish', prefinish); + this.updateCallback() } -function prefinish() { - var _this = this; +function afterRead (err) { + if (err) this.stream.destroy(err) + this.stream._duplexState &= READ_NOT_ACTIVE + this.updateCallback() +} - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); +function updateReadNT () { + if ((this.stream._duplexState & READ_UPDATING) === 0) { + this.stream._duplexState &= READ_NOT_NEXT_TICK + this.update() } } -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. +function updateWriteNT () { + if ((this.stream._duplexState & WRITE_UPDATING) === 0) { + this.stream._duplexState &= WRITE_NOT_NEXT_TICK + this.update() + } +} +function tickDrains (drains) { + for (let i = 0; i < drains.length; i++) { + // drains.writes are monotonic, so if one is 0 its always the first one + if (--drains[i].writes === 0) { + drains.shift().resolve(true) + i-- + } + } +} -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; +function afterOpen (err) { + const stream = this.stream -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; + if (err) stream.destroy(err) - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + if ((stream._duplexState & DESTROYING) === 0) { + if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY + if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY + stream.emit('open') } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. + stream._duplexState &= NOT_ACTIVE -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + if (stream._writableState !== null) { + stream._writableState.updateCallback() } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided + if (stream._readableState !== null) { + stream._readableState.updateCallback() + } +} - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); +function afterTransform (err, data) { + if (data !== undefined && data !== null) this.push(data) + this._writableState.afterWrite(err) } -/***/ }), +class Stream extends EventEmitter { + constructor (opts) { + super() -/***/ 6993: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._duplexState = 0 + this._readableState = null + this._writableState = null -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. + if (opts) { + if (opts.open) this._open = opts.open + if (opts.destroy) this._destroy = opts.destroy + if (opts.predestroy) this._predestroy = opts.predestroy + if (opts.signal) { + opts.signal.addEventListener('abort', abort.bind(this)) + } + } + } + _open (cb) { + cb(null) + } -module.exports = Writable; -/* */ + _destroy (cb) { + cb(null) + } -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream + _predestroy () { + // does nothing + } + get readable () { + return this._readableState !== null ? true : undefined + } -function CorkedRequest(state) { - var _this = this; + get writable () { + return this._writableState !== null ? true : undefined + } - this.next = null; - this.entry = null; + get destroyed () { + return (this._duplexState & DESTROYED) !== 0 + } - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ + get destroying () { + return (this._duplexState & DESTROY_STATUS) !== 0 + } -/**/ + destroy (err) { + if ((this._duplexState & DESTROY_STATUS) === 0) { + if (!err) err = STREAM_DESTROYED + this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY + if (this._readableState !== null) { + this._readableState.highWaterMark = 0 + this._readableState.error = err + } + if (this._writableState !== null) { + this._writableState.highWaterMark = 0 + this._writableState.error = err + } -var Duplex; -/**/ + this._duplexState |= PREDESTROYING + this._predestroy() + this._duplexState &= NOT_PREDESTROYING -Writable.WritableState = WritableState; -/**/ + if (this._readableState !== null) this._readableState.updateNextTick() + if (this._writableState !== null) this._writableState.updateNextTick() + } + } -var internalUtil = { - deprecate: __nccwpck_require__(7127) -}; -/**/ + on (name, fn) { + if (this._readableState !== null) { + if (name === 'data') { + this._duplexState |= (READ_EMIT_DATA | READ_RESUMED) + this._readableState.updateNextTick() + } + if (name === 'readable') { + this._duplexState |= READ_EMIT_READABLE + this._readableState.updateNextTick() + } + } -/**/ + if (this._writableState !== null) { + if (name === 'drain') { + this._duplexState |= WRITE_EMIT_DRAIN + this._writableState.updateNextTick() + } + } -var Stream = __nccwpck_require__(2387); -/**/ + return super.on(name, fn) + } +} +class Readable extends Stream { + constructor (opts) { + super(opts) -var Buffer = (__nccwpck_require__(4300).Buffer); + this._duplexState |= OPENING | WRITE_DONE + this._readableState = new ReadableState(this, opts) -var OurUint8Array = global.Uint8Array || function () {}; + if (opts) { + if (opts.read) this._read = opts.read + if (opts.eagerOpen) this._readableState.updateNextTick() + } + } -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} + _read (cb) { + cb(null) + } -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} + pipe (dest, cb) { + this._readableState.updateNextTick() + this._readableState.pipe(dest, cb) + return dest + } -var destroyImpl = __nccwpck_require__(7049); + read () { + this._readableState.updateNextTick() + return this._readableState.read() + } -var _require = __nccwpck_require__(9948), - getHighWaterMark = _require.getHighWaterMark; + push (data) { + this._readableState.updateNextTick() + return this._readableState.push(data) + } -var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + unshift (data) { + this._readableState.updateNextTick() + return this._readableState.unshift(data) + } -var errorOrDestroy = destroyImpl.errorOrDestroy; + resume () { + this._duplexState |= READ_RESUMED + this._readableState.updateNextTick() + return this + } -__nccwpck_require__(4124)(Writable, Stream); + pause () { + this._duplexState &= READ_PAUSED + return this + } -function nop() {} + static _fromAsyncIterator (ite, opts) { + let destroy -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(1359); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + const rs = new Readable({ + ...opts, + read (cb) { + ite.next().then(push).then(cb.bind(null, null)).catch(cb) + }, + predestroy () { + destroy = ite.return() + }, + destroy (cb) { + if (!destroy) return cb(null) + destroy.then(cb.bind(null, null)).catch(cb) + } + }) - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. + return rs - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() + function push (data) { + if (data.done) rs.push(null) + else rs.push(data.value) + } + } - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + static from (data, opts) { + if (isReadStreamx(data)) return data + if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts) + if (!Array.isArray(data)) data = data === undefined ? [] : [data] - this.finalCalled = false; // drain event flag. + let i = 0 + return new Readable({ + ...opts, + read (cb) { + this.push(i === data.length ? null : data[i++]) + cb(null) + } + }) + } - this.needDrain = false; // at the start of calling end() + static isBackpressured (rs) { + return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark + } - this.ending = false; // when end() has been called, and returned + static isPaused (rs) { + return (rs._duplexState & READ_RESUMED) === 0 + } - this.ended = false; // when 'finish' is emitted + [asyncIterator] () { + const stream = this - this.finished = false; // has it been destroyed + let error = null + let promiseResolve = null + let promiseReject = null - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. + this.on('error', (err) => { error = err }) + this.on('readable', onreadable) + this.on('close', onclose) - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + return { + [asyncIterator] () { + return this + }, + next () { + return new Promise(function (resolve, reject) { + promiseResolve = resolve + promiseReject = reject + const data = stream.read() + if (data !== null) ondata(data) + else if ((stream._duplexState & DESTROYED) !== 0) ondata(null) + }) + }, + return () { + return destroy(null) + }, + throw (err) { + return destroy(err) + } + } - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. + function onreadable () { + if (promiseResolve !== null) ondata(stream.read()) + } - this.length = 0; // a flag to see when we're in the middle of a write. + function onclose () { + if (promiseResolve !== null) ondata(null) + } - this.writing = false; // when true all writes will be buffered until .uncork() call + function ondata (data) { + if (promiseReject === null) return + if (error) promiseReject(error) + else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED) + else promiseResolve({ value: data, done: data === null }) + promiseReject = promiseResolve = null + } - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. + function destroy (err) { + stream.destroy(err) + return new Promise((resolve, reject) => { + if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true }) + stream.once('close', function () { + if (err) reject(err) + else resolve({ value: undefined, done: true }) + }) + }) + } + } +} - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. +class Writable extends Stream { + constructor (opts) { + super(opts) - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + this._duplexState |= OPENING | READ_DONE + this._writableState = new WritableState(this, opts) - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) + if (opts) { + if (opts.writev) this._writev = opts.writev + if (opts.write) this._write = opts.write + if (opts.final) this._final = opts.final + if (opts.eagerOpen) this._writableState.updateNextTick() + } + } + _writev (batch, cb) { + cb(null) + } - this.writecb = null; // the amount that is being written when _write is called. + _write (data, cb) { + this._writableState.autoBatch(data, cb) + } - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted + _final (cb) { + cb(null) + } - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams + static isBackpressured (ws) { + return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0 + } - this.prefinished = false; // True if the error was already emitted and should not be thrown again + static drained (ws) { + if (ws.destroyed) return Promise.resolve(false) + const state = ws._writableState + const writes = state.queue.length + ((ws._duplexState & WRITE_WRITING) ? 1 : 0) + if (writes === 0) return Promise.resolve(true) + if (state.drains === null) state.drains = [] + return new Promise((resolve) => { + state.drains.push({ writes, resolve }) + }) + } - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + write (data) { + this._writableState.updateNextTick() + return this._writableState.push(data) + } - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + end (data) { + this._writableState.updateNextTick() + this._writableState.end(data) + return this + } +} - this.autoDestroy = !!options.autoDestroy; // count buffered requests +class Duplex extends Readable { // and Writable + constructor (opts) { + super(opts) - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two + this._duplexState = OPENING + this._writableState = new WritableState(this, opts) - this.corkedRequestsFree = new CorkedRequest(this); -} + if (opts) { + if (opts.writev) this._writev = opts.writev + if (opts.write) this._write = opts.write + if (opts.final) this._final = opts.final + } + } -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; + _writev (batch, cb) { + cb(null) + } - while (current) { - out.push(current); - current = current.next; + _write (data, cb) { + this._writableState.autoBatch(data, cb) } - return out; -}; + _final (cb) { + cb(null) + } -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. + write (data) { + this._writableState.updateNextTick() + return this._writableState.push(data) + } + + end (data) { + this._writableState.updateNextTick() + this._writableState.end(data) + return this + } +} +class Transform extends Duplex { + constructor (opts) { + super(opts) + this._transformState = new TransformState(this) -var realHasInstance; + if (opts) { + if (opts.transform) this._transform = opts.transform + if (opts.flush) this._flush = opts.flush + } + } -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; + _write (data, cb) { + if (this._readableState.buffered >= this._readableState.highWaterMark) { + this._transformState.data = data + } else { + this._transform(data, this._transformState.afterTransform) } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} + } -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(1359); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 + _read (cb) { + if (this._transformState.data !== null) { + const data = this._transformState.data + this._transformState.data = null + cb(null) + this._transform(data, this._transformState.afterTransform) + } else { + cb(null) + } + } - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. + _transform (data, cb) { + cb(null, data) + } - this.writable = true; + _flush (cb) { + cb(null) + } - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; + _final (cb) { + this._transformState.afterFinal = cb + this._flush(transformAfterFlush.bind(this)) } +} - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. +class PassThrough extends Transform {} +function transformAfterFlush (err, data) { + const cb = this._transformState.afterFinal + if (err) return cb(err) + if (data !== null && data !== undefined) this.push(data) + this.push(null) + cb(null) +} -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; +function pipelinePromise (...streams) { + return new Promise((resolve, reject) => { + return pipeline(...streams, (err) => { + if (err) return reject(err) + resolve() + }) + }) +} -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb +function pipeline (stream, ...streams) { + const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams] + const done = (all.length && typeof all[all.length - 1] === 'function') ? all.pop() : null - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. + if (all.length < 2) throw new Error('Pipeline requires at least 2 streams') + let src = all[0] + let dest = null + let error = null -function validChunk(stream, state, chunk, cb) { - var er; + for (let i = 1; i < all.length; i++) { + dest = all[i] - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } + if (isStreamx(src)) { + src.pipe(dest, onerror) + } else { + errorHandle(src, true, i > 1, onerror) + src.pipe(dest) + } - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; + src = dest } - return true; -} + if (done) { + let fin = false -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy) - var isBuf = !state.objectMode && _isUint8Array(chunk); + dest.on('error', (err) => { + if (error === null) error = err + }) - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); + dest.on('finish', () => { + fin = true + if (!autoDestroy) done(error) + }) + + if (autoDestroy) { + dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE))) + } } - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + return dest + + function errorHandle (s, rd, wr, onerror) { + s.on('error', onerror) + s.on('close', onclose) + + function onclose () { + if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE) + if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE) + } } - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + function onerror (err) { + if (!err || error) return + error = err + + for (const s of all) { + s.destroy(err) + } } - return ret; -}; +} -Writable.prototype.cork = function () { - this._writableState.corked++; -}; +function isStream (stream) { + return !!stream._readableState || !!stream._writableState +} -Writable.prototype.uncork = function () { - var state = this._writableState; +function isStreamx (stream) { + return typeof stream._duplexState === 'number' && isStream(stream) +} - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; +function getStreamError (stream) { + const err = (stream._readableState && stream._readableState.error) || (stream._writableState && stream._writableState.error) + return err === STREAM_DESTROYED ? null : err // only explicit errors +} -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; +function isReadStreamx (stream) { + return isStreamx(stream) && stream.readable +} -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); +function isTypedArray (data) { + return typeof data === 'object' && data !== null && typeof data.byteLength === 'number' +} -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } +function defaultByteLength (data) { + return isTypedArray(data) ? data.byteLength : 1024 +} - return chunk; +function noop () {} + +function abort () { + this.destroy(new Error('Stream aborted.')) } -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. +module.exports = { + pipeline, + pipelinePromise, + isStream, + isStreamx, + getStreamError, + Stream, + Writable, + Readable, + Duplex, + Transform, + // Export PassThrough for compatibility with Node.js core's stream module + PassThrough +} -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } +/***/ }), - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. +/***/ 4841: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!ret) state.needDrain = true; +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); +/**/ + +var Buffer = (__nccwpck_require__(2279).Buffer); +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; } +}; - return ret; +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; } -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); } -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error +StringDecoder.prototype.end = utf8End; - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; - finishMaybe(stream, state); +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); } -} + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; } -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } } } } -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); } -} // if there's something in the buffer waiting, then process it - + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} - state.bufferedRequestCount = 0; +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} - if (state.writing) { - break; - } - } +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} - if (entry === null) state.lastBufferedRequest = null; - } +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} - state.bufferedRequest = entry; - state.bufferProcessing = false; +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; } -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; +/***/ }), -Writable.prototype._writev = null; +/***/ 2279: +/***/ ((module, exports, __nccwpck_require__) => { -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(4300) +var Buffer = buffer.Buffer - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; +// 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 +} - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} +SafeBuffer.prototype = Object.create(Buffer.prototype) - if (!state.ending) endWritable(this, state, cb); - return this; -}; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + return Buffer(arg, encodingOrOffset, length) } -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); +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 +} - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) } -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return buffer.SlowBuffer(size) } -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); +/***/ }), - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); +/***/ 9318: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; +"use strict"; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } +const os = __nccwpck_require__(2037); +const tty = __nccwpck_require__(6224); +const hasFlag = __nccwpck_require__(1621); - return need; +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; } -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } +function translateLevel(level) { + if (level === 0) { + return false; + } - state.ended = true; - stream.writable = false; + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; } -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + if (hasFlag('color=256')) { + return 2; + } - state.corkedRequestsFree.next = corkReq; -} + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } + const min = forceColor || 0; - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + if (env.TERM === 'dumb') { + return min; + } + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; + return 1; + } -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } -/***/ }), + return min; + } -/***/ 3306: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } -"use strict"; + if (env.COLORTERM === 'truecolor') { + return 3; + } + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); -var _Object$setPrototypeO; + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } -var finished = __nccwpck_require__(6080); + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); + if ('COLORTERM' in env) { + return 1; + } -function createIterResult(value, done) { - return { - value: value, - done: done - }; + return min; } -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} +/***/ }), + +/***/ 366: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var chownr = __nccwpck_require__(9051) +var tar = __nccwpck_require__(1260) +var pump = __nccwpck_require__(8341) +var mkdirp = __nccwpck_require__(7614) +var fs = __nccwpck_require__(7147) +var path = __nccwpck_require__(1017) +var os = __nccwpck_require__(2037) + +var win32 = os.platform() === 'win32' -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } +var noop = function () {} - iter[kHandlePromise](resolve, reject); - }, reject); - }; +var echo = function (name) { + return name } -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; +var normalize = !win32 ? echo : function (name) { + return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_') +} - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; +var statAll = function (fs, stat, cwd, ignore, entries, sort) { + var queue = entries || ['.'] - if (error !== null) { - return Promise.reject(error); - } + return function loop (callback) { + if (!queue.length) return callback() + var next = queue.shift() + var nextAbs = path.join(cwd, next) - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } + stat(nextAbs, function (err, stat) { + if (err) return callback(err) - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time + if (!stat.isDirectory()) return callback(null, next, stat) + fs.readdir(nextAbs, function (err, files) { + if (err) return callback(err) - var lastPromise = this[kLastPromise]; - var promise; + if (sort) files.sort() + for (var i = 0; i < files.length; i++) { + if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) + } - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); + callback(null, next, stat) + }) + }) + } +} - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } +var strip = function (map, level) { + return function (header) { + header.name = header.name.split('/').slice(level).join('/') - promise = new Promise(this[kHandlePromise]); + var linkname = header.linkname + if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { + header.linkname = linkname.split('/').slice(level).join('/') } - this[kLastPromise] = promise; - return promise; + return map(header) } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; +} - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } +exports.pack = function (cwd, opts) { + if (!cwd) cwd = '.' + if (!opts) opts = {} - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); + var xfs = opts.fs || fs + var ignore = opts.ignore || opts.filter || noop + var map = opts.map || noop + var mapStream = opts.mapStream || echo + var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) + var strict = opts.strict !== false + var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() + var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 + var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 + var pack = opts.pack || tar.pack() + var finish = opts.finish || noop -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; + if (opts.strip) map = strip(map, opts.strip) - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); + if (opts.readable) { + dmode |= parseInt(555, 8) + fmode |= parseInt(444, 8) + } + if (opts.writable) { + dmode |= parseInt(333, 8) + fmode |= parseInt(222, 8) + } - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error + var onsymlink = function (filename, header) { + xfs.readlink(path.join(cwd, filename), function (err, linkname) { + if (err) return pack.destroy(err) + header.linkname = normalize(linkname) + pack.entry(header, onnextentry) + }) + } - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } + var onstat = function (err, filename, stat) { + if (err) return pack.destroy(err) + if (!filename) { + if (opts.finalize !== false) pack.finalize() + return finish(pack) + } - iterator[kError] = err; - return; + if (stat.isSocket()) return onnextentry() // tar does not support sockets... + + var header = { + name: normalize(filename), + mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, + mtime: stat.mtime, + size: stat.size, + type: 'file', + uid: stat.uid, + gid: stat.gid } - var resolve = iterator[kLastResolve]; + if (stat.isDirectory()) { + header.size = 0 + header.type = 'directory' + header = map(header) || header + return pack.entry(header, onnextentry) + } - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); + if (stat.isSymbolicLink()) { + header.size = 0 + header.type = 'symlink' + header = map(header) || header + return onsymlink(filename, header) } - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; + // TODO: add fifo etc... -module.exports = createReadableStreamAsyncIterator; + header = map(header) || header -/***/ }), + if (!stat.isFile()) { + if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) + return onnextentry() + } -/***/ 6522: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var entry = pack.entry(header, onnextentry) + if (!entry) return -"use strict"; + var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header) + rs.on('error', function (err) { // always forward errors on destroy + entry.destroy(err) + }) -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + pump(rs, entry) + } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + var onnextentry = function (err) { + if (err) return pack.destroy(err) + statNext(onstat) + } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + onnextentry() -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return pack +} -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +var head = function (list) { + return list.length ? list[list.length - 1] : null +} -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } +var processGetuid = function () { + return process.getuid ? process.getuid() : -1 +} -var _require = __nccwpck_require__(4300), - Buffer = _require.Buffer; +var processUmask = function () { + return process.umask ? process.umask() : 0 +} -var _require2 = __nccwpck_require__(3837), - inspect = _require2.inspect; +exports.extract = function (cwd, opts) { + if (!cwd) cwd = '.' + if (!opts) opts = {} -var custom = inspect && inspect.custom || 'inspect'; + var xfs = opts.fs || fs + var ignore = opts.ignore || opts.filter || noop + var map = opts.map || noop + var mapStream = opts.mapStream || echo + var own = opts.chown !== false && !win32 && processGetuid() === 0 + var extract = opts.extract || tar.extract() + var stack = [] + var now = new Date() + var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() + var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 + var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 + var strict = opts.strict !== false -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} + if (opts.strip) map = strip(map, opts.strip) -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); + if (opts.readable) { + dmode |= parseInt(555, 8) + fmode |= parseInt(444, 8) + } + if (opts.writable) { + dmode |= parseInt(333, 8) + fmode |= parseInt(222, 8) + } - this.head = null; - this.tail = null; - this.length = 0; + var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry + var top + while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() + if (!top) return cb() + xfs.utimes(top[0], now, top[1], cb) } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; + var utimes = function (name, header, cb) { + if (opts.utimes === false) return cb() - while (p = p.next) { - ret += s + p.data; - } + if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) + if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; + xfs.utimes(name, now, header.mtime, function (err) { + if (err) return cb(err) + utimesParent(name, cb) + }) + } - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } + var chperm = function (name, header, cb) { + var link = header.type === 'symlink' - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. + /* eslint-disable node/no-deprecated-api */ + var chmod = link ? xfs.lchmod : xfs.chmod + var chown = link ? xfs.lchown : xfs.chown + /* eslint-enable node/no-deprecated-api */ - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; + if (!chmod) return cb() - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } + var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask + chmod(name, mode, function (err) { + if (err) return cb(err) + if (!own) return cb() + if (!chown) return cb() + chown(name, header.uid, header.gid, cb) + }) + } - return ret; + extract.on('entry', function (header, stream, next) { + header = map(header) || header + header.name = normalize(header.name) + var name = path.join(cwd, path.join('/', header.name)) + + if (ignore(name, header)) { + stream.resume() + return next() } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; + var stat = function (err) { + if (err) return next(err) + utimes(name, header, function (err) { + if (err) return next(err) + if (win32) return next() + chperm(name, header, next) + }) + } - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; + var onsymlink = function () { + if (win32) return next() // skip symlinks on win for now before it can be tested + xfs.unlink(name, function () { + xfs.symlink(header.linkname, name, stat) + }) + } - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); + var onlink = function () { + if (win32) return next() // skip links on win for now before it can be tested + xfs.unlink(name, function () { + var srcpath = path.join(cwd, path.join('/', header.linkname)) + + xfs.link(srcpath, name, function (err) { + if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { + stream = xfs.createReadStream(srcpath) + return onfile() } - break; - } + stat(err) + }) + }) + } - ++c; - } + var onfile = function () { + var ws = xfs.createWriteStream(name) + var rs = mapStream(stream, header) - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. + ws.on('error', function (err) { // always forward errors on destroy + rs.destroy(err) + }) - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; + pump(rs, ws, function (err) { + if (err) return next(err) + ws.on('close', stat) + }) + } - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; + if (header.type === 'directory') { + stack.push([name, header.mtime]) + return mkdirfix(name, { + fs: xfs, own: own, uid: header.uid, gid: header.gid + }, stat) + } + + var dir = path.dirname(name) + + validate(xfs, dir, path.join(cwd, '.'), function (err, valid) { + if (err) return next(err) + if (!valid) return next(new Error(dir + ' is not a valid path')) - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } + mkdirfix(dir, { + fs: xfs, own: own, uid: header.uid, gid: header.gid + }, function (err) { + if (err) return next(err) - break; + switch (header.type) { + case 'file': return onfile() + case 'link': return onlink() + case 'symlink': return onsymlink() } - ++c; - } + if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. + stream.resume() + next() + }) + }) + }) - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); + if (opts.finish) extract.on('finish', opts.finish) + + return extract +} + +function validate (fs, name, root, cb) { + if (name === root) return cb(null, true) + fs.lstat(name, function (err, st) { + if (err && err.code !== 'ENOENT') return cb(err) + if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb) + cb(null, false) + }) +} + +function mkdirfix (name, opts, cb) { + mkdirp(name, { fs: opts.fs }, function (err, made) { + if (!err && made && opts.own) { + chownr(made, opts.uid, opts.gid, cb) + } else { + cb(err) } - }]); + }) +} - return BufferList; -}(); /***/ }), -/***/ 7049: -/***/ ((module) => { +/***/ 1515: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - // undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; +const { Buffer } = __nccwpck_require__(4300) +const symbol = Symbol.for('BufferList') - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } +function BufferList (buf) { + if (!(this instanceof BufferList)) { + return new BufferList(buf) + } - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks + BufferList._init.call(this, buf) +} +BufferList._init = function _init (buf) { + Object.defineProperty(this, symbol, { value: true }) - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well + this._bufs = [] + this.length = 0 + + if (buf) { + this.append(buf) + } +} +BufferList.prototype._new = function _new (buf) { + return new BufferList(buf) +} - if (this._writableState) { - this._writableState.destroyed = true; +BufferList.prototype._offset = function _offset (offset) { + if (offset === 0) { + return [0, 0] } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); + let tot = 0 - return this; + for (let i = 0; i < this._bufs.length; i++) { + const _t = tot + this._bufs[i].length + if (offset < _t || i === this._bufs.length - 1) { + return [i, offset - tot] + } + tot = _t + } } -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); +BufferList.prototype._reverseOffset = function (blOffset) { + const bufferId = blOffset[0] + let offset = blOffset[1] + + for (let i = 0; i < bufferId; i++) { + offset += this._bufs[i].length + } + + return offset } -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); +BufferList.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined + } + + const offset = this._offset(index) + + return this._bufs[offset[0]][offset[1]] } -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; +BufferList.prototype.slice = function slice (start, end) { + if (typeof start === 'number' && start < 0) { + start += this.length } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; + if (typeof end === 'number' && end < 0) { + end += this.length } -} -function emitErrorNT(self, err) { - self.emit('error', err); + return this.copy(null, 0, start, end) } -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} +BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart !== 'number' || srcStart < 0) { + srcStart = 0 + } -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; + if (typeof srcEnd !== 'number' || srcEnd > this.length) { + srcEnd = this.length + } -/***/ }), + if (srcStart >= this.length) { + return dst || Buffer.alloc(0) + } -/***/ 6080: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (srcEnd <= 0) { + return dst || Buffer.alloc(0) + } -"use strict"; -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). + const copy = !!dst + const off = this._offset(srcStart) + const len = srcEnd - srcStart + let bytes = len + let bufoff = (copy && dstStart) || 0 + let start = off[1] + // copy/slice everything + if (srcStart === 0 && srcEnd === this.length) { + if (!copy) { + // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer.concat(this._bufs, this.length) + } -var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(7214)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); + // copy, need to copy individual buffers + for (let i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; + return dst + } - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } + + if (!copy) { + // a slice, we need something to copy in to + dst = Buffer.allocUnsafe(len) + } + + for (let i = off[0]; i < this._bufs.length; i++) { + const l = this._bufs[i].length - start + + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + bufoff += l + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l + break } - callback.apply(this, args); - }; -} + bytes -= l -function noop() {} + if (start) { + start = 0 + } + } -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) + + return dst } -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = typeof end !== 'number' ? this.length : end - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; + if (start < 0) { + start += this.length + } - var writableEnded = stream._writableState && stream._writableState.finished; + if (end < 0) { + end += this.length + } - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; + if (start === end) { + return this._new() + } - var readableEnded = stream._readableState && stream._readableState.endEmitted; + const startOffset = this._offset(start) + const endOffset = this._offset(end) + const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; + if (endOffset[1] === 0) { + buffers.pop() + } else { + buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) + } - var onerror = function onerror(err) { - callback.call(stream, err); - }; + if (startOffset[1] !== 0) { + buffers[0] = buffers[0].slice(startOffset[1]) + } - var onclose = function onclose() { - var err; + return this._new(buffers) +} - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); +BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this + + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() + } else { + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break } - }; + } - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; + return this +} - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); +BufferList.prototype.duplicate = function duplicate () { + const copy = this._new() + + for (let i = 0; i < this._bufs.length; i++) { + copy.append(this._bufs[i]) } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; + return copy } -module.exports = eos; +BufferList.prototype.append = function append (buf) { + if (buf == null) { + return this + } -/***/ }), + if (buf.buffer) { + // append a view of the underlying ArrayBuffer + this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) + } else if (Array.isArray(buf)) { + for (let i = 0; i < buf.length; i++) { + this.append(buf[i]) + } + } else if (this._isBufferList(buf)) { + // unwrap argument into individual BufferLists + for (let i = 0; i < buf._bufs.length; i++) { + this.append(buf._bufs[i]) + } + } else { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf === 'number') { + buf = buf.toString() + } -/***/ 9082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._appendBuffer(Buffer.from(buf)) + } -"use strict"; + return this +} +BufferList.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf) + this.length += buf.length +} -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +BufferList.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer.from([search]) + } else if (typeof search === 'string') { + search = Buffer.from(search, encoding) + } else if (this._isBufferList(search)) { + search = search.slice() + } else if (Array.isArray(search.buffer)) { + search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) + } else if (!Buffer.isBuffer(search)) { + search = Buffer.from(search) + } -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + offset = Number(offset || 0) -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + if (isNaN(offset)) { + offset = 0 + } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + if (offset < 0) { + offset = this.length + offset + } -var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(7214)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE); + if (offset < 0) { + offset = 0 + } -function from(Readable, iterable, opts) { - var iterator; + if (search.length === 0) { + return offset > this.length ? this.length : offset + } - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + const blOffset = this._offset(offset) + let blIndex = blOffset[0] // index of which internal buffer we're working on + let buffOffset = blOffset[1] // offset of the internal buffer we're working on - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); // Reading boolean to protect against _read - // being called before last iteration completion. + // scan over each buffer + for (; blIndex < this._bufs.length; blIndex++) { + const buff = this._bufs[blIndex] + + while (buffOffset < buff.length) { + const availableWindow = buff.length - buffOffset + + if (availableWindow >= search.length) { + const nativeSearchResult = buff.indexOf(search, buffOffset) + + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) + } + + buffOffset = buff.length - search.length + 1 // end of native search window + } else { + const revOffset = this._reverseOffset([blIndex, buffOffset]) + + if (this._match(revOffset, search)) { + return revOffset + } + + buffOffset++ + } + } + + buffOffset = 0 + } + + return -1 +} - var reading = false; +BufferList.prototype._match = function (offset, search) { + if (this.length - offset < search.length) { + return false + } - readable._read = function () { - if (!reading) { - reading = true; - next(); + for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { + if (this.get(offset + searchOffset) !== search[searchOffset]) { + return false } - }; - - function next() { - return _next2.apply(this, arguments); } + return true +} - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _ref = yield iterator.next(), - value = _ref.value, - done = _ref.done; +;(function () { + const methods = { + readDoubleBE: 8, + readDoubleLE: 8, + readFloatBE: 4, + readFloatLE: 4, + readInt32BE: 4, + readInt32LE: 4, + readUInt32BE: 4, + readUInt32LE: 4, + readInt16BE: 2, + readInt16LE: 2, + readUInt16BE: 2, + readUInt16LE: 2, + readInt8: 1, + readUInt8: 1, + readIntBE: null, + readIntLE: null, + readUIntBE: null, + readUIntLE: null + } - if (done) { - readable.push(null); - } else if (readable.push((yield value))) { - next(); - } else { - reading = false; + for (const m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) + } + } else { + BufferList.prototype[m] = function (offset = 0) { + return this.slice(offset, offset + methods[m])[m](0) } - } catch (err) { - readable.destroy(err); } - }); - return _next2.apply(this, arguments); + }(m)) } +}()) - return readable; +// Used internally by the class and also as an indicator of this object being +// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser +// environment because there could be multiple different copies of the +// BufferList class and some `BufferList`s might be `BufferList`s. +BufferList.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferList || BufferList.isBufferList(b) } -module.exports = from; +BufferList.isBufferList = function isBufferList (b) { + return b != null && b[symbol] +} + +module.exports = BufferList + /***/ }), -/***/ 6989: +/***/ 6136: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -var eos; +const DuplexStream = (__nccwpck_require__(1642).Duplex) +const inherits = __nccwpck_require__(4124) +const BufferList = __nccwpck_require__(1515) -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} +function BufferListStream (callback) { + if (!(this instanceof BufferListStream)) { + return new BufferListStream(callback) + } -var _require$codes = (__nccwpck_require__(7214)/* .codes */ .q), - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + if (typeof callback === 'function') { + this._callback = callback -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} + const piper = function piper (err) { + if (this._callback) { + this._callback(err) + this._callback = null + } + }.bind(this) -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} + this.on('pipe', function onPipe (src) { + src.on('error', piper) + }) + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper) + }) -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = __nccwpck_require__(6080); - 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; // request.destroy just do .end - .abort is what we want + callback = null + } - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; + BufferList._init.call(this, callback) + DuplexStream.call(this) } -function call(fn) { - fn(); -} +inherits(BufferListStream, DuplexStream) +Object.assign(BufferListStream.prototype, BufferList.prototype) -function pipe(from, to) { - return from.pipe(to); +BufferListStream.prototype._new = function _new (callback) { + return new BufferListStream(callback) } -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); +BufferListStream.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf) + + if (typeof callback === 'function') { + callback() + } } -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; +BufferListStream.prototype._read = function _read (size) { + if (!this.length) { + return this.push(null) } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); +BufferListStream.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk) + + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null } +} - 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); +BufferListStream.prototype._destroy = function _destroy (err, cb) { + this._bufs.length = 0 + this.length = 0 + cb(err) } -module.exports = pipeline; +BufferListStream.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) +} + +BufferListStream.isBufferList = BufferList.isBufferList + +module.exports = BufferListStream +module.exports.BufferListStream = BufferListStream +module.exports.BufferList = BufferList + /***/ }), -/***/ 9948: +/***/ 9545: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var util = __nccwpck_require__(3837) +var bl = __nccwpck_require__(6136) +var headers = __nccwpck_require__(6834) +var Writable = (__nccwpck_require__(1642).Writable) +var PassThrough = (__nccwpck_require__(1642).PassThrough) -var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(7214)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); +var noop = function () {} -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +var overflow = function (size) { + size &= 511 + return size && 512 - size } -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); +var emptyStream = function (self, offset) { + var s = new Source(self, offset) + s.end() + return s +} - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } +var mixinPax = function (header, pax) { + if (pax.path) header.name = pax.path + if (pax.linkpath) header.linkname = pax.linkpath + if (pax.size) header.size = parseInt(pax.size, 10) + header.pax = pax + return header +} - return Math.floor(hwm); - } // Default value +var Source = function (self, offset) { + this._parent = self + this.offset = offset + PassThrough.call(this, { autoDestroy: false }) +} +util.inherits(Source, PassThrough) - return state.objectMode ? 16 : 16 * 1024; +Source.prototype.destroy = function (err) { + this._parent.destroy(err) } -module.exports = { - getHighWaterMark: getHighWaterMark -}; +var Extract = function (opts) { + if (!(this instanceof Extract)) return new Extract(opts) + Writable.call(this, opts) -/***/ }), + opts = opts || {} -/***/ 2387: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._offset = 0 + this._buffer = bl() + this._missing = 0 + this._partial = false + this._onparse = noop + this._header = null + this._stream = null + this._overflow = null + this._cb = null + this._locked = false + this._destroyed = false + this._pax = null + this._paxGlobal = null + this._gnuLongPath = null + this._gnuLongLinkPath = null -module.exports = __nccwpck_require__(2781); + var self = this + var b = self._buffer + var oncontinue = function () { + self._continue() + } -/***/ }), + var onunlock = function (err) { + self._locked = false + if (err) return self.destroy(err) + if (!self._stream) oncontinue() + } -/***/ 1642: -/***/ ((module, exports, __nccwpck_require__) => { + var onstreamend = function () { + self._stream = null + var drain = overflow(self._header.size) + if (drain) self._parse(drain, ondrain) + else self._parse(512, onheader) + if (!self._locked) oncontinue() + } -var Stream = __nccwpck_require__(2781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream.Readable; - Object.assign(module.exports, Stream); - module.exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(1433); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(6993); - exports.Duplex = __nccwpck_require__(1359); - exports.Transform = __nccwpck_require__(4415); - exports.PassThrough = __nccwpck_require__(1542); - exports.finished = __nccwpck_require__(6080); - exports.pipeline = __nccwpck_require__(6989); -} + var ondrain = function () { + self._buffer.consume(overflow(self._header.size)) + self._parse(512, onheader) + oncontinue() + } + var onpaxglobalheader = function () { + var size = self._header.size + self._paxGlobal = headers.decodePax(b.slice(0, size)) + b.consume(size) + onstreamend() + } -/***/ }), + var onpaxheader = function () { + var size = self._header.size + self._pax = headers.decodePax(b.slice(0, size)) + if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax) + b.consume(size) + onstreamend() + } -/***/ 5118: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var ongnulongpath = function () { + var size = self._header.size + this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) + b.consume(size) + onstreamend() + } -"use strict"; -/* eslint-disable node/no-deprecated-api */ + var ongnulonglinkpath = function () { + var size = self._header.size + this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) + b.consume(size) + onstreamend() + } + var onheader = function () { + var offset = self._offset + var header + try { + header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat) + } catch (err) { + self.emit('error', err) + } + b.consume(512) + if (!header) { + self._parse(512, onheader) + oncontinue() + return + } + if (header.type === 'gnu-long-path') { + self._parse(header.size, ongnulongpath) + oncontinue() + return + } + if (header.type === 'gnu-long-link-path') { + self._parse(header.size, ongnulonglinkpath) + oncontinue() + return + } + if (header.type === 'pax-global-header') { + self._parse(header.size, onpaxglobalheader) + oncontinue() + return + } + if (header.type === 'pax-header') { + self._parse(header.size, onpaxheader) + oncontinue() + return + } -var buffer = __nccwpck_require__(4300) -var Buffer = buffer.Buffer + if (self._gnuLongPath) { + header.name = self._gnuLongPath + self._gnuLongPath = null + } -var safer = {} + if (self._gnuLongLinkPath) { + header.linkname = self._gnuLongLinkPath + self._gnuLongLinkPath = null + } -var key + if (self._pax) { + self._header = header = mixinPax(header, self._pax) + self._pax = null + } -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} + self._locked = true -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} + if (!header.size || header.type === 'directory') { + self._parse(512, onheader) + self.emit('entry', header, emptyStream(self, offset), onunlock) + return + } -safer.Buffer.prototype = Buffer.prototype + self._stream = new Source(self, offset) -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) + self.emit('entry', header, self._stream, onunlock) + self._parse(header.size, onstreamend) + oncontinue() } + + this._onheader = onheader + this._parse(512, onheader) } -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 - } +util.inherits(Extract, Writable) + +Extract.prototype.destroy = function (err) { + if (this._destroyed) return + this._destroyed = true + + if (err) this.emit('error', err) + this.emit('close') + if (this._stream) this._stream.emit('close') } -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 - } +Extract.prototype._parse = function (size, onparse) { + if (this._destroyed) return + this._offset += size + this._missing = size + if (onparse === this._onheader) this._partial = false + this._onparse = onparse } -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } +Extract.prototype._continue = function () { + if (this._destroyed) return + var cb = this._cb + this._cb = noop + if (this._overflow) this._write(this._overflow, undefined, cb) + else cb() } -module.exports = safer +Extract.prototype._write = function (data, enc, cb) { + if (this._destroyed) return + + var s = this._stream + var b = this._buffer + var missing = this._missing + if (data.length) this._partial = true + + // we do not reach end-of-chunk now. just forward it + + if (data.length < missing) { + this._missing -= data.length + this._overflow = null + if (s) return s.write(data, cb) + b.append(data) + return cb() + } + // end-of-chunk. the parser should call cb. -/***/ }), + this._cb = cb + this._missing = 0 -/***/ 9798: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var overflow = null + if (data.length > missing) { + overflow = data.slice(missing) + data = data.slice(0, missing) + } -var fs = __nccwpck_require__(7147); + if (s) s.end(data) + else b.append(data) -module.exports = function (filepath, split, encoding) { - split = typeof split !== 'undefined' ? split : "\n"; - encoding = typeof encoding !== 'undefined' ? encoding : "utf8"; + this._overflow = overflow + this._onparse() +} - var ca = []; - var chain = fs.readFileSync(filepath, encoding); - if(chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0){ - throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); - } - chain = chain.split(split); - var cert = []; - var _i, _len; - for (_i = 0, _len = chain.length; _i < _len; _i++) { - var line = chain[_i]; - if (!(line.length !== 0)) { - continue; - } - cert.push(line); - if (line.match(/-END CERTIFICATE-/)) { - ca.push(cert.join(split)); - cert = []; - } - } - return ca; +Extract.prototype._final = function (cb) { + if (this._partial) return this.destroy(new Error('Unexpected end of data')) + cb() } +module.exports = Extract -/***/ }), -/***/ 3204: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -"use strict"; +/***/ 6834: +/***/ ((__unused_webpack_module, exports) => { +var alloc = Buffer.alloc -const { - Duplex: DuplexStream, - Readable: ReadableStream, - Writable: WritableStream, -} = __nccwpck_require__(2781); +var ZEROS = '0000000000000000000' +var SEVENS = '7777777777777777777' +var ZERO_OFFSET = '0'.charCodeAt(0) +var USTAR_MAGIC = Buffer.from('ustar\x00', 'binary') +var USTAR_VER = Buffer.from('00', 'binary') +var GNU_MAGIC = Buffer.from('ustar\x20', 'binary') +var GNU_VER = Buffer.from('\x20\x00', 'binary') +var MASK = parseInt('7777', 8) +var MAGIC_OFFSET = 257 +var VERSION_OFFSET = 263 -const { - CHANNEL_EXTENDED_DATATYPE: { STDERR }, -} = __nccwpck_require__(6832); -const { bufferSlice } = __nccwpck_require__(9475); +var clamp = function (index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue + index = ~~index // Coerce to integer. + if (index >= len) return len + if (index >= 0) return index + index += len + if (index >= 0) return index + return 0 +} -const PACKET_SIZE = 32 * 1024; -const MAX_WINDOW = 2 * 1024 * 1024; -const WINDOW_THRESHOLD = MAX_WINDOW / 2; +var toType = function (flag) { + switch (flag) { + case 0: + return 'file' + case 1: + return 'link' + case 2: + return 'symlink' + case 3: + return 'character-device' + case 4: + return 'block-device' + case 5: + return 'directory' + case 6: + return 'fifo' + case 7: + return 'contiguous-file' + case 72: + return 'pax-header' + case 55: + return 'pax-global-header' + case 27: + return 'gnu-long-link-path' + case 28: + case 30: + return 'gnu-long-path' + } -class ClientStderr extends ReadableStream { - constructor(channel, streamOpts) { - super(streamOpts); + return null +} - this._channel = channel; - } - _read(n) { - if (this._channel._waitChanDrain) { - this._channel._waitChanDrain = false; - if (this._channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this._channel); - } +var toTypeflag = function (flag) { + switch (flag) { + case 'file': + return 0 + case 'link': + return 1 + case 'symlink': + return 2 + case 'character-device': + return 3 + case 'block-device': + return 4 + case 'directory': + return 5 + case 'fifo': + return 6 + case 'contiguous-file': + return 7 + case 'pax-header': + return 72 } -} -class ServerStderr extends WritableStream { - constructor(channel) { - super({ highWaterMark: MAX_WINDOW }); + return 0 +} - this._channel = channel; +var indexOf = function (block, num, offset, end) { + for (; offset < end; offset++) { + if (block[offset] === num) return offset } + return end +} - _write(data, encoding, cb) { - const channel = this._channel; - const protocol = channel._client._protocol; - const outgoing = channel.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; +var cksum = function (block) { + var sum = 8 * 32 + for (var i = 0; i < 148; i++) sum += block[i] + for (var j = 156; j < 512; j++) sum += block[j] + return sum +} - if (outgoing.state !== 'open') - return; +var encodeOct = function (val, n) { + val = val.toString(8) + if (val.length > n) return SEVENS.slice(0, n) + ' ' + else return ZEROS.slice(0, n - val.length) + val + ' ' +} - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; +/* Copied from the node-tar repo and modified to meet + * tar-stream coding standard. + * + * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 + */ +function parse256 (buf) { + // first byte MUST be either 80 or FF + // 80 for positive, FF for 2's comp + var positive + if (buf[0] === 0x80) positive = true + else if (buf[0] === 0xFF) positive = false + else return null - if (p === 0 && sliceLen === len) - protocol.channelExtData(id, data, STDERR); - else - protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); + // build up a base-256 tuple from the least sig to the highest + var tuple = [] + for (var i = buf.length - 1; i > 0; i--) { + var byte = buf[i] + if (positive) tuple.push(byte) + else tuple.push(0xFF - byte) + } - p += sliceLen; - window -= sliceLen; - } + var sum = 0 + var l = tuple.length + for (i = 0; i < l; i++) { + sum += tuple[i] * Math.pow(256, i) + } - outgoing.window = window; + return positive ? sum : -1 * sum +} - if (len - p > 0) { - if (window === 0) - channel._waitWindow = true; - if (p > 0) - channel._chunkErr = bufferSlice(data, p, len); - else - channel._chunkErr = data; - channel._chunkcbErr = cb; - return; - } +var decodeOct = function (val, offset, length) { + val = val.slice(offset, offset + length) + offset = 0 - cb(); + // If prefixed with 0x80 then parse as a base-256 integer + if (val[offset] & 0x80) { + return parse256(val) + } else { + // Older versions of tar can prefix with spaces + while (offset < val.length && val[offset] === 32) offset++ + var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) + while (offset < end && val[offset] === 0) offset++ + if (end === offset) return 0 + return parseInt(val.slice(offset, end).toString(), 8) } } -class Channel extends DuplexStream { - constructor(client, info, opts) { - const streamOpts = { - highWaterMark: MAX_WINDOW, - allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), - emitClose: false, - }; - super(streamOpts); - this.allowHalfOpen = streamOpts.allowHalfOpen; - - const server = !!(opts && opts.server); - - this.server = server; - this.type = info.type; - this.subtype = undefined; - - /* - incoming and outgoing contain these properties: - { - id: undefined, - window: undefined, - packetSize: undefined, - state: 'closed' - } - */ - this.incoming = info.incoming; - this.outgoing = info.outgoing; - this._callbacks = []; +var decodeStr = function (val, offset, length, encoding) { + return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding) +} - this._client = client; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; +var addLength = function (str) { + var len = Buffer.byteLength(str) + var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 + if (len + digits >= Math.pow(10, digits)) digits++ - this.stdin = this.stdout = this; + return (len + digits) + str +} - if (server) - this.stderr = new ServerStderr(this); - else - this.stderr = new ClientStderr(this, streamOpts); +exports.decodeLongPath = function (buf, encoding) { + return decodeStr(buf, 0, buf.length, encoding) +} - // Outgoing data - this._waitWindow = false; // SSH-level backpressure +exports.encodePax = function (opts) { // TODO: encode more stuff in pax + var result = '' + if (opts.name) result += addLength(' path=' + opts.name + '\n') + if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') + var pax = opts.pax + if (pax) { + for (var key in pax) { + result += addLength(' ' + key + '=' + pax[key] + '\n') + } + } + return Buffer.from(result) +} - // Incoming data - this._waitChanDrain = false; // Channel Readable side backpressure +exports.decodePax = function (buf) { + var result = {} - this._chunk = undefined; - this._chunkcb = undefined; - this._chunkErr = undefined; - this._chunkcbErr = undefined; + while (buf.length) { + var i = 0 + while (i < buf.length && buf[i] !== 32) i++ + var len = parseInt(buf.slice(0, i).toString(), 10) + if (!len) return result - this.on('finish', onFinish) - .on('prefinish', onFinish); // For node v0.11+ + var b = buf.slice(i + 1, len - 1).toString() + var keyIndex = b.indexOf('=') + if (keyIndex === -1) return result + result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) - this.on('end', onEnd).on('close', onEnd); + buf = buf.slice(len) } - _read(n) { - if (this._waitChanDrain) { - this._waitChanDrain = false; - if (this.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this); - } - } + return result +} - _write(data, encoding, cb) { - const protocol = this._client._protocol; - const outgoing = this.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; +exports.encode = function (opts) { + var buf = alloc(512) + var name = opts.name + var prefix = '' - if (outgoing.state !== 'open') - return; + if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' + if (Buffer.byteLength(name) !== name.length) return null // utf-8 - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; + while (Buffer.byteLength(name) > 100) { + var i = name.indexOf('/') + if (i === -1) return null + prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) + name = name.slice(i + 1) + } - if (p === 0 && sliceLen === len) - protocol.channelData(id, data); - else - protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); + if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null + if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null - p += sliceLen; - window -= sliceLen; - } + buf.write(name) + buf.write(encodeOct(opts.mode & MASK, 6), 100) + buf.write(encodeOct(opts.uid, 6), 108) + buf.write(encodeOct(opts.gid, 6), 116) + buf.write(encodeOct(opts.size, 11), 124) + buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) - outgoing.window = window; + buf[156] = ZERO_OFFSET + toTypeflag(opts.type) - if (len - p > 0) { - if (window === 0) - this._waitWindow = true; - if (p > 0) - this._chunk = bufferSlice(data, p, len); - else - this._chunk = data; - this._chunkcb = cb; - return; - } + if (opts.linkname) buf.write(opts.linkname, 157) - cb(); - } + USTAR_MAGIC.copy(buf, MAGIC_OFFSET) + USTAR_VER.copy(buf, VERSION_OFFSET) + if (opts.uname) buf.write(opts.uname, 265) + if (opts.gname) buf.write(opts.gname, 297) + buf.write(encodeOct(opts.devmajor || 0, 6), 329) + buf.write(encodeOct(opts.devminor || 0, 6), 337) - eof() { - if (this.outgoing.state === 'open') { - this.outgoing.state = 'eof'; - this._client._protocol.channelEOF(this.outgoing.id); - } - } + if (prefix) buf.write(prefix, 345) - close() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._client._protocol.channelClose(this.outgoing.id); - } - } + buf.write(encodeOct(cksum(buf), 6), 148) - destroy() { - this.end(); - this.close(); - return this; - } + return buf +} - // Session type-specific methods ============================================= - setWindow(rows, cols, height, width) { - if (this.server) - throw new Error('Client-only method called in server mode'); +exports.decode = function (buf, filenameEncoding, allowUnknownFormat) { + var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET - if (this.type === 'session' - && (this.subtype === 'shell' || this.subtype === 'exec') - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.windowChange(this.outgoing.id, - rows, - cols, - height, - width); - } - } + var name = decodeStr(buf, 0, 100, filenameEncoding) + var mode = decodeOct(buf, 100, 8) + var uid = decodeOct(buf, 108, 8) + var gid = decodeOct(buf, 116, 8) + var size = decodeOct(buf, 124, 12) + var mtime = decodeOct(buf, 136, 12) + var type = toType(typeflag) + var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) + var uname = decodeStr(buf, 265, 32) + var gname = decodeStr(buf, 297, 32) + var devmajor = decodeOct(buf, 329, 8) + var devminor = decodeOct(buf, 337, 8) - signal(signalName) { - if (this.server) - throw new Error('Client-only method called in server mode'); + var c = cksum(buf) - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.signal(this.outgoing.id, signalName); - } - } + // checksum is still initial value if header was null. + if (c === 8 * 32) return null - exit(statusOrSignal, coreDumped, msg) { - if (!this.server) - throw new Error('Server-only method called in client mode'); + // valid checksum + if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - if (typeof statusOrSignal === 'number') { - this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); - } else { - this._client._protocol.exitSignal(this.outgoing.id, - statusOrSignal, - coreDumped, - msg); - } + if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { + // ustar (posix) format. + // prepend prefix, if present. + if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name + } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && + GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { + // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and + // multi-volume tarballs. + } else { + if (!allowUnknownFormat) { + throw new Error('Invalid tar header: unknown format.') } } -} + // to support old tar versions that use trailing / to indicate dirs + if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 -function onFinish() { - this.eof(); - if (this.server || !this.allowHalfOpen) - this.close(); - this.writable = false; + return { + name, + mode, + uid, + gid, + size, + mtime: new Date(1000 * mtime), + type, + linkname, + uname, + gname, + devmajor, + devminor + } } -function onEnd() { - this.readable = false; -} -function windowAdjust(self) { - if (self.outgoing.state === 'closed') - return; - const amt = MAX_WINDOW - self.incoming.window; - if (amt <= 0) - return; - self.incoming.window += amt; - self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); -} +/***/ }), -module.exports = { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -}; +/***/ 1260: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +exports.extract = __nccwpck_require__(9545) +exports.pack = __nccwpck_require__(2456) /***/ }), -/***/ 9054: +/***/ 2456: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var constants = __nccwpck_require__(3186) +var eos = __nccwpck_require__(1205) +var inherits = __nccwpck_require__(4124) +var alloc = Buffer.alloc +var Readable = (__nccwpck_require__(1642).Readable) +var Writable = (__nccwpck_require__(1642).Writable) +var StringDecoder = (__nccwpck_require__(1576).StringDecoder) -const { Socket } = __nccwpck_require__(1808); -const { Duplex } = __nccwpck_require__(2781); -const { resolve } = __nccwpck_require__(1017); -const { readFile } = __nccwpck_require__(7147); -const { execFile, spawn } = __nccwpck_require__(2081); +var headers = __nccwpck_require__(6834) -const { isParsedKey, parseKey } = __nccwpck_require__(2218); +var DMODE = parseInt('755', 8) +var FMODE = parseInt('644', 8) -const { - makeBufferParser, - readUInt32BE, - writeUInt32BE, - writeUInt32LE, -} = __nccwpck_require__(9475); +var END_OF_TAR = alloc(1024) -function once(cb) { - let called = false; - return (...args) => { - if (called) - return; - called = true; - cb(...args); - }; -} +var noop = function () {} -function concat(buf1, buf2) { - const combined = Buffer.allocUnsafe(buf1.length + buf2.length); - buf1.copy(combined, 0); - buf2.copy(combined, buf1.length); - return combined; +var overflow = function (self, size) { + size &= 511 + if (size) self.push(END_OF_TAR.slice(0, 512 - size)) } -function noop() {} - -const EMPTY_BUF = Buffer.alloc(0); - -const binaryParser = makeBufferParser(); - -class BaseAgent { - getIdentities(cb) { - cb(new Error('Missing getIdentities() implementation')); - } - sign(pubKey, data, options, cb) { - if (typeof options === 'function') - cb = options; - cb(new Error('Missing sign() implementation')); +function modeToType (mode) { + switch (mode & constants.S_IFMT) { + case constants.S_IFBLK: return 'block-device' + case constants.S_IFCHR: return 'character-device' + case constants.S_IFDIR: return 'directory' + case constants.S_IFIFO: return 'fifo' + case constants.S_IFLNK: return 'symlink' } + + return 'file' } -class OpenSSHAgent extends BaseAgent { - constructor(socketPath) { - super(); - this.socketPath = socketPath; - } +var Sink = function (to) { + Writable.call(this) + this.written = 0 + this._to = to + this._destroyed = false +} - getStream(cb) { - cb = once(cb); - const sock = new Socket(); - sock.on('connect', () => { - cb(null, sock); - }); - sock.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - sock.connect(this.socketPath); +inherits(Sink, Writable) - function onFail() { - try { - sock.destroy(); - } catch {} +Sink.prototype._write = function (data, enc, cb) { + this.written += data.length + if (this._to.push(data)) return cb() + this._to._drain = cb +} - cb(new Error('Failed to connect to agent')); - } - } +Sink.prototype.destroy = function () { + if (this._destroyed) return + this._destroyed = true + this.emit('close') +} - getIdentities(cb) { - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to retrieve identities from agent'); - cb(err); - } +var LinkSink = function () { + Writable.call(this) + this.linkname = '' + this._decoder = new StringDecoder('utf-8') + this._destroyed = false +} - if (err) - return onFail(err); +inherits(LinkSink, Writable) - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); +LinkSink.prototype._write = function (data, enc, cb) { + this.linkname += this._decoder.write(data) + cb() +} - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); +LinkSink.prototype.destroy = function () { + if (this._destroyed) return + this._destroyed = true + this.emit('close') +} - protocol.getIdentities((err, keys) => { - if (err) - return onFail(err); - try { - stream.destroy(); - } catch {} - cb(null, keys); - }); - }); - } +var Void = function () { + Writable.call(this) + this._destroyed = false +} - sign(pubKey, data, options, cb) { - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } +inherits(Void, Writable) - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to sign data with agent'); - cb(err); - } +Void.prototype._write = function (data, enc, cb) { + cb(new Error('No body allowed for this entry')) +} - if (err) - return onFail(err); +Void.prototype.destroy = function () { + if (this._destroyed) return + this._destroyed = true + this.emit('close') +} - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); +var Pack = function (opts) { + if (!(this instanceof Pack)) return new Pack(opts) + Readable.call(this, opts) - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); + this._drain = noop + this._finalized = false + this._finalizing = false + this._destroyed = false + this._stream = null +} - protocol.sign(pubKey, data, options, (err, sig) => { - if (err) - return onFail(err); +inherits(Pack, Readable) - try { - stream.destroy(); - } catch {} +Pack.prototype.entry = function (header, buffer, callback) { + if (this._stream) throw new Error('already piping an entry') + if (this._finalized || this._destroyed) return - cb(null, sig); - }); - }); + if (typeof buffer === 'function') { + callback = buffer + buffer = null } -} -const PageantAgent = (() => { - const RET_ERR_BADARGS = 10; - const RET_ERR_UNAVAILABLE = 11; - const RET_ERR_NOMAP = 12; - const RET_ERR_BINSTDIN = 13; - const RET_ERR_BINSTDOUT = 14; - const RET_ERR_BADLEN = 15; + if (!callback) callback = noop - const EXEPATH = __nccwpck_require__.ab + "pagent.exe"; - const ERROR = { - [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), - [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), - [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), - [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), - [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), - [RET_ERR_BADLEN]: - new Error('pagent.exe did not get expected input payload'), - }; + var self = this - function destroy(stream) { - stream.buffer = null; - if (stream.proc) { - stream.proc.kill(); - stream.proc = undefined; - } + if (!header.size || header.type === 'symlink') header.size = 0 + if (!header.type) header.type = modeToType(header.mode) + if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE + if (!header.uid) header.uid = 0 + if (!header.gid) header.gid = 0 + if (!header.mtime) header.mtime = new Date() + + if (typeof buffer === 'string') buffer = Buffer.from(buffer) + if (Buffer.isBuffer(buffer)) { + header.size = buffer.length + this._encode(header) + var ok = this.push(buffer) + overflow(self, header.size) + if (ok) process.nextTick(callback) + else this._drain = callback + return new Void() } - class PageantSocket extends Duplex { - constructor() { - super(); - this.proc = undefined; - this.buffer = null; - } - _read(n) {} - _write(data, encoding, cb) { - if (this.buffer === null) { - this.buffer = data; - } else { - const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); - this.buffer.copy(newBuffer, 0); - data.copy(newBuffer, this.buffer.length); - this.buffer = newBuffer; + if (header.type === 'symlink' && !header.linkname) { + var linkSink = new LinkSink() + eos(linkSink, function (err) { + if (err) { // stream was closed + self.destroy() + return callback(err) } - // Wait for at least all length bytes - if (this.buffer.length < 4) - return cb(); - - const len = readUInt32BE(this.buffer, 0); - // Make sure we have a full message before querying pageant - if ((this.buffer.length - 4) < len) - return cb(); - data = this.buffer.slice(0, 4 + len); - if (this.buffer.length > (4 + len)) - return cb(new Error('Unexpected multiple agent requests')); - this.buffer = null; + header.linkname = linkSink.linkname + self._encode(header) + callback() + }) - let error; - const proc = this.proc = spawn(__nccwpck_require__.ab + "pagent.exe", [ data.length ]); - proc.stdout.on('data', (data) => { - this.push(data); - }); - proc.on('error', (err) => { - error = err; - cb(error); - }); - proc.on('close', (code) => { - this.proc = undefined; - if (!error) { - if (error = ERROR[code]) - return cb(error); - cb(); - } - }); - proc.stdin.end(data); - } - _final(cb) { - destroy(this); - cb(); - } - _destroy(err, cb) { - destroy(this); - cb(); - } + return linkSink } - return class PageantAgent extends OpenSSHAgent { - getStream(cb) { - cb(null, new PageantSocket()); - } - }; -})(); + this._encode(header) -const CygwinAgent = (() => { - const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; + if (header.type !== 'file' && header.type !== 'contiguous-file') { + process.nextTick(callback) + return new Void() + } - return class CygwinAgent extends OpenSSHAgent { - getStream(cb) { - cb = once(cb); + var sink = new Sink(this) - // The cygwin ssh-agent connection process looks like this: - // 1. Read the "socket" as a file to get the underlying TCP port and a - // special "secret" that must be sent to the TCP server. - // 2. Connect to the server listening on localhost at the TCP port. - // 3. Send the "secret" to the server. - // 4. The server sends back the same "secret". - // 5. Send three 32-bit integer values of zero. This is ordinarily the - // pid, uid, and gid of this process, but cygwin will actually - // send us the correct values as a response. - // 6. The server sends back the pid, uid, gid. - // 7. Disconnect. - // 8. Repeat steps 2-6, except send the received pid, uid, and gid in - // step 5 instead of zeroes. - // 9. Connection is ready to be used. + this._stream = sink - let socketPath = this.socketPath; - let triedCygpath = false; - readFile(socketPath, function readCygsocket(err, data) { - if (err) { - if (triedCygpath) - return cb(new Error('Invalid cygwin unix socket path')); + eos(sink, function (err) { + self._stream = null - // Try using `cygpath` to convert a possible *nix-style path to the - // real Windows path before giving up ... - execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { - if (err || stdout.length === 0) - return cb(new Error('Invalid cygwin unix socket path')); + if (err) { // stream was closed + self.destroy() + return callback(err) + } - triedCygpath = true; - socketPath = stdout.toString().replace(/[\r\n]/g, ''); - readFile(socketPath, readCygsocket); - }); - return; - } + if (sink.written !== header.size) { // corrupting tar + self.destroy() + return callback(new Error('size mismatch')) + } - const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); - if (!m) - return cb(new Error('Malformed cygwin unix socket file')); + overflow(self, header.size) + if (self._finalizing) self.finalize() + callback() + }) - let state; - let bc = 0; - let isRetrying = false; - const inBuf = []; - let sock; + return sink +} - // Use 0 for pid, uid, and gid to ensure we get an error and also - // a valid uid and gid from cygwin so that we don't have to figure it - // out ourselves - let credsBuf = Buffer.alloc(12); +Pack.prototype.finalize = function () { + if (this._stream) { + this._finalizing = true + return + } - // Parse cygwin unix socket file contents - const port = parseInt(m[1], 10); - const secret = m[2].replace(/-/g, ''); - const secretBuf = Buffer.allocUnsafe(16); - for (let i = 0, j = 0; j < 32; ++i, j += 2) - secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); + if (this._finalized) return + this._finalized = true + this.push(END_OF_TAR) + this.push(null) +} - // Convert to host order (always LE for Windows) - for (let i = 0; i < 16; i += 4) - writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); +Pack.prototype.destroy = function (err) { + if (this._destroyed) return + this._destroyed = true - tryConnect(); + if (err) this.emit('error', err) + this.emit('close') + if (this._stream && this._stream.destroy) this._stream.destroy() +} - function _onconnect() { - bc = 0; - state = 'secret'; - sock.write(secretBuf); - } +Pack.prototype._encode = function (header) { + if (!header.pax) { + var buf = headers.encode(header) + if (buf) { + this.push(buf) + return + } + } + this._encodePax(header) +} - function _ondata(data) { - bc += data.length; +Pack.prototype._encodePax = function (header) { + var paxHeader = headers.encodePax({ + name: header.name, + linkname: header.linkname, + pax: header.pax + }) - if (state === 'secret') { - // The secret we sent is echoed back to us by cygwin, not sure of - // the reason for that, but we ignore it nonetheless ... - if (bc === 16) { - bc = 0; - state = 'creds'; - sock.write(credsBuf); - } - return; - } + var newHeader = { + name: 'PaxHeader', + mode: header.mode, + uid: header.uid, + gid: header.gid, + size: paxHeader.length, + mtime: header.mtime, + type: 'pax-header', + linkname: header.linkname && 'PaxHeader', + uname: header.uname, + gname: header.gname, + devmajor: header.devmajor, + devminor: header.devminor + } - if (state === 'creds') { - // If this is the first attempt, make sure to gather the valid - // uid and gid for our next attempt - if (!isRetrying) - inBuf.push(data); + this.push(headers.encode(newHeader)) + this.push(paxHeader) + overflow(this, paxHeader.length) + + newHeader.size = header.size + newHeader.type = header.type + this.push(headers.encode(newHeader)) +} - if (bc === 12) { - sock.removeListener('connect', _onconnect); - sock.removeListener('data', _ondata); - sock.removeListener('error', onFail); - sock.removeListener('end', onFail); - sock.removeListener('close', onFail); +Pack.prototype._read = function (n) { + var drain = this._drain + this._drain = noop + drain() +} - if (isRetrying) - return cb(null, sock); +module.exports = Pack - isRetrying = true; - credsBuf = Buffer.concat(inBuf); - writeUInt32LE(credsBuf, process.pid, 0); - sock.on('error', () => {}); - sock.destroy(); - tryConnect(); - } - } - } +/***/ }), - function onFail() { - cb(new Error('Problem negotiating cygwin unix socket security')); - } +/***/ 8926: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function tryConnect() { - sock = new Socket(); - sock.on('connect', _onconnect); - sock.on('data', _ondata); - sock.on('error', onFail); - sock.on('end', onFail); - sock.on('close', onFail); - sock.connect(port); - } - }); - } - }; -})(); +const constants = { // just for envs without fs + S_IFMT: 61440, + S_IFDIR: 16384, + S_IFCHR: 8192, + S_IFBLK: 24576, + S_IFIFO: 4096, + S_IFLNK: 40960 +} -// Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes -// being interchangeable -const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; -function createAgent(path) { - if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { - return (path === 'pageant' - ? new PageantAgent() - : new CygwinAgent(path)); - } - return new OpenSSHAgent(path); +try { + module.exports = (__nccwpck_require__(7147).constants) || constants +} catch { + module.exports = constants } -const AgentProtocol = (() => { - // Client->Server messages - const SSH_AGENTC_REQUEST_IDENTITIES = 11; - const SSH_AGENTC_SIGN_REQUEST = 13; - // const SSH_AGENTC_ADD_IDENTITY = 17; - // const SSH_AGENTC_REMOVE_IDENTITY = 18; - // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; - // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; - // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; - // const SSH_AGENTC_LOCK = 22; - // const SSH_AGENTC_UNLOCK = 23; - // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; - // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; - // const SSH_AGENTC_EXTENSION = 27; - // Server->Client messages - const SSH_AGENT_FAILURE = 5; - // const SSH_AGENT_SUCCESS = 6; - const SSH_AGENT_IDENTITIES_ANSWER = 12; - const SSH_AGENT_SIGN_RESPONSE = 14; - // const SSH_AGENT_EXTENSION_FAILURE = 28; - // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; - // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; - // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; +/***/ }), - const SSH_AGENT_RSA_SHA2_256 = (1 << 1); - const SSH_AGENT_RSA_SHA2_512 = (1 << 2); +/***/ 7882: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const ROLE_CLIENT = 0; - const ROLE_SERVER = 1; +const { Writable, Readable, getStreamError } = __nccwpck_require__(5147) +const FIFO = __nccwpck_require__(2958) +const b4a = __nccwpck_require__(3497) +const headers = __nccwpck_require__(8860) - // Ensures that responses get sent back in the same order the requests were - // received - function processResponses(protocol) { - let ret; - while (protocol[SYM_REQS].length) { - const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; - if (nextResponse === undefined) - break; +const EMPTY = b4a.alloc(0) - protocol[SYM_REQS].shift(); - ret = protocol.push(nextResponse); - } - return ret; +class BufferList { + constructor () { + this.buffered = 0 + this.shifted = 0 + this.queue = new FIFO() + + this._offset = 0 } - const SYM_TYPE = Symbol('Inbound Request Type'); - const SYM_RESP = Symbol('Inbound Request Response'); - const SYM_CTX = Symbol('Inbound Request Context'); - class AgentInboundRequest { - constructor(type, ctx) { - this[SYM_TYPE] = type; - this[SYM_RESP] = undefined; - this[SYM_CTX] = ctx; - } - hasResponded() { - return (this[SYM_RESP] !== undefined); - } - getType() { - return this[SYM_TYPE]; - } - getContext() { - return this[SYM_CTX]; - } + push (buffer) { + this.buffered += buffer.byteLength + this.queue.push(buffer) } - function respond(protocol, req, data) { - req[SYM_RESP] = data; - return processResponses(protocol); + + shiftFirst (size) { + return this._buffered === 0 ? null : this._next(size) } - function cleanup(protocol) { - protocol[SYM_BUFFER] = null; - if (protocol[SYM_MODE] === ROLE_CLIENT) { - const reqs = protocol[SYM_REQS]; - if (reqs && reqs.length) { - protocol[SYM_REQS] = []; - for (const req of reqs) - req.cb(new Error('No reply from server')); - } - } + shift (size) { + if (size > this.buffered) return null + if (size === 0) return EMPTY - // Node streams hackery to make streams do the "right thing" - try { - protocol.end(); - } catch {} - setImmediate(() => { - if (!protocol[SYM_ENDED]) - protocol.emit('end'); - if (!protocol[SYM_CLOSED]) - protocol.emit('close'); - }); - } + let chunk = this._next(size) - function onClose() { - this[SYM_CLOSED] = true; - } + if (size === chunk.byteLength) return chunk // likely case - function onEnd() { - this[SYM_ENDED] = true; + const chunks = [chunk] + + while ((size -= chunk.byteLength) > 0) { + chunk = this._next(size) + chunks.push(chunk) + } + + return b4a.concat(chunks) } - const SYM_REQS = Symbol('Requests'); - const SYM_MODE = Symbol('Agent Protocol Role'); - const SYM_BUFFER = Symbol('Agent Protocol Buffer'); - const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); - const SYM_CLOSED = Symbol('Agent Protocol Closed'); - const SYM_ENDED = Symbol('Agent Protocol Ended'); - // Implementation based on: - // https://tools.ietf.org/html/draft-miller-ssh-agent-04 - return class AgentProtocol extends Duplex { - /* - Notes: - - `constraint` type consists of: - byte constraint_type - byte[] constraint_data - where `constraint_type` is one of: - * SSH_AGENT_CONSTRAIN_LIFETIME - - `constraint_data` consists of: - uint32 seconds - * SSH_AGENT_CONSTRAIN_CONFIRM - - `constraint_data` N/A - * SSH_AGENT_CONSTRAIN_EXTENSION - - `constraint_data` consists of: - string extension name - byte[] extension-specific details - */ + _next (size) { + const buf = this.queue.peek() + const rem = buf.byteLength - this._offset - constructor(isClient) { - super({ autoDestroy: true, emitClose: false }); - this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); - this[SYM_REQS] = []; - this[SYM_BUFFER] = null; - this[SYM_MSGLEN] = -1; - this.once('end', onEnd); - this.once('close', onClose); + if (size >= rem) { + const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf + this.queue.shift() + this._offset = 0 + this.buffered -= rem + this.shifted += rem + return sub } - _read(n) {} + this.buffered -= size + this.shifted += size - _write(data, encoding, cb) { - /* - Messages are of the format: - uint32 message length - byte message type - byte[message length - 1] message contents - */ - if (this[SYM_BUFFER] === null) - this[SYM_BUFFER] = data; - else - this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); + return buf.subarray(this._offset, (this._offset += size)) + } +} - let buffer = this[SYM_BUFFER]; - let bufferLen = buffer.length; +class Source extends Readable { + constructor (self, header, offset) { + super() - let p = 0; - while (p < bufferLen) { - // Wait for length + type - if (bufferLen < 5) - break; + this.header = header + this.offset = offset - if (this[SYM_MSGLEN] === -1) - this[SYM_MSGLEN] = readUInt32BE(buffer, p); + this._parent = self + } - // Check if we have the entire message - if (bufferLen < (4 + this[SYM_MSGLEN])) - break; + _read (cb) { + if (this.header.size === 0) { + this.push(null) + } + if (this._parent._stream === this) { + this._parent._update() + } + cb(null) + } - const msgType = buffer[p += 4]; - ++p; + _predestroy () { + this._parent.destroy(getStreamError(this)) + } - if (this[SYM_MODE] === ROLE_CLIENT) { - if (this[SYM_REQS].length === 0) - return cb(new Error('Received unexpected message from server')); + _detach () { + if (this._parent._stream === this) { + this._parent._stream = null + this._parent._missing = overflow(this.header.size) + this._parent._update() + } + } - const req = this[SYM_REQS].shift(); + _destroy (cb) { + this._detach() + cb(null) + } +} - switch (msgType) { - case SSH_AGENT_FAILURE: - req.cb(new Error('Agent responded with failure')); - break; - case SSH_AGENT_IDENTITIES_ANSWER: { - if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) - return cb(new Error('Agent responded with wrong message type')); +class Extract extends Writable { + constructor (opts) { + super(opts) - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys + if (!opts) opts = {} - where `nkeys` is 0 or more of: - string key blob - string comment - */ + this._buffer = new BufferList() + this._offset = 0 + this._header = null + this._stream = null + this._missing = 0 + this._longHeader = false + this._callback = noop + this._locked = false + this._finished = false + this._pax = null + this._paxGlobal = null + this._gnuLongPath = null + this._gnuLongLinkPath = null + this._filenameEncoding = opts.filenameEncoding || 'utf-8' + this._allowUnknownFormat = !!opts.allowUnknownFormat + this._unlockBound = this._unlock.bind(this) + } - binaryParser.init(buffer, p); + _unlock (err) { + this._locked = false - const numKeys = binaryParser.readUInt32BE(); + if (err) { + this.destroy(err) + this._continueWrite(err) + return + } - if (numKeys === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } + this._update() + } - const keys = []; - for (let i = 0; i < numKeys; ++i) { - let pubKey = binaryParser.readString(); - if (pubKey === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } + _consumeHeader () { + if (this._locked) return false - const comment = binaryParser.readString(true); - if (comment === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } + this._offset = this._buffer.shifted - pubKey = parseKey(pubKey); - // We continue parsing the packet if we encounter an error - // in case the error is due to the key being an unsupported - // type - if (pubKey instanceof Error) - continue; + try { + this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat) + } catch (err) { + this._continueWrite(err) + return false + } - pubKey.comment = pubKey.comment || comment; + if (!this._header) return true - keys.push(pubKey); - } - p = binaryParser.pos(); - binaryParser.clear(); + switch (this._header.type) { + case 'gnu-long-path': + case 'gnu-long-link-path': + case 'pax-global-header': + case 'pax-header': + this._longHeader = true + this._missing = this._header.size + return true + } - req.cb(null, keys); - break; - } - case SSH_AGENT_SIGN_RESPONSE: { - if (req.type !== SSH_AGENTC_SIGN_REQUEST) - return cb(new Error('Agent responded with wrong message type')); + this._locked = true + this._applyLongHeaders() - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ + if (this._header.size === 0 || this._header.type === 'directory') { + this.emit('entry', this._header, this._createStream(), this._unlockBound) + return true + } - binaryParser.init(buffer, p); - let signature = binaryParser.readString(); - p = binaryParser.pos(); - binaryParser.clear(); + this._stream = this._createStream() + this._missing = this._header.size - if (signature === undefined) - return cb(new Error('Malformed agent response')); + this.emit('entry', this._header, this._stream, this._unlockBound) + return true + } - // We strip the algorithm from OpenSSH's output and assume it's - // using the algorithm we specified. This makes it easier on - // custom Agent implementations so they don't have to construct - // the correct binary format for a (OpenSSH-style) signature. + _applyLongHeaders () { + if (this._gnuLongPath) { + this._header.name = this._gnuLongPath + this._gnuLongPath = null + } - // TODO: verify signature type based on key and options used - // during initial sign request - binaryParser.init(signature, 0); - binaryParser.readString(true); - signature = binaryParser.readString(); - binaryParser.clear(); + if (this._gnuLongLinkPath) { + this._header.linkname = this._gnuLongLinkPath + this._gnuLongLinkPath = null + } - if (signature === undefined) - return cb(new Error('Malformed OpenSSH signature format')); + if (this._pax) { + if (this._pax.path) this._header.name = this._pax.path + if (this._pax.linkpath) this._header.linkname = this._pax.linkpath + if (this._pax.size) this._header.size = parseInt(this._pax.size, 10) + this._header.pax = this._pax + this._pax = null + } + } - req.cb(null, signature); - break; - } - default: - return cb( - new Error('Agent responded with unsupported message type') - ); - } - } else { - switch (msgType) { - case SSH_AGENTC_REQUEST_IDENTITIES: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - this.emit('identities', req); - break; - } - case SSH_AGENTC_SIGN_REQUEST: { - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - binaryParser.init(buffer, p); - let pubKey = binaryParser.readString(); - const data = binaryParser.readString(); - const flagsVal = binaryParser.readUInt32BE(); - p = binaryParser.pos(); - binaryParser.clear(); - if (flagsVal === undefined) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } + _decodeLongHeader (buf) { + switch (this._header.type) { + case 'gnu-long-path': + this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding) + break + case 'gnu-long-link-path': + this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding) + break + case 'pax-global-header': + this._paxGlobal = headers.decodePax(buf) + break + case 'pax-header': + this._pax = this._paxGlobal === null + ? headers.decodePax(buf) + : Object.assign({}, this._paxGlobal, headers.decodePax(buf)) + break + } + } - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } + _consumeLongHeader () { + this._longHeader = false + this._missing = overflow(this._header.size) - const flags = { - hash: undefined, - }; - let ctx; - if (pubKey.type === 'ssh-rsa') { - if (flagsVal & SSH_AGENT_RSA_SHA2_256) { - ctx = 'rsa-sha2-256'; - flags.hash = 'sha256'; - } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { - ctx = 'rsa-sha2-512'; - flags.hash = 'sha512'; - } - } - if (ctx === undefined) - ctx = pubKey.type; + const buf = this._buffer.shift(this._header.size) - const req = new AgentInboundRequest(msgType, ctx); - this[SYM_REQS].push(req); + try { + this._decodeLongHeader(buf) + } catch (err) { + this._continueWrite(err) + return false + } - this.emit('sign', req, pubKey, data, flags); - break; - } - default: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - this.failureReply(req); - } - } - } + return true + } - // Get ready for next message - this[SYM_MSGLEN] = -1; - if (p === bufferLen) { - // Nothing left to process for now - this[SYM_BUFFER] = null; - break; - } else { - this[SYM_BUFFER] = buffer = buffer.slice(p); - bufferLen = buffer.length; - p = 0; - } - } + _consumeStream () { + const buf = this._buffer.shiftFirst(this._missing) + if (buf === null) return false - cb(); - } + this._missing -= buf.byteLength + const drained = this._stream.push(buf) - _destroy(err, cb) { - cleanup(this); - cb(); + if (this._missing === 0) { + this._stream.push(null) + if (drained) this._stream._detach() + return drained && this._locked === false } - _final(cb) { - cleanup(this); - cb(); - } + return drained + } - // Client->Server messages ================================================= - sign(pubKey, data, options, cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); + _createStream () { + return new Source(this, this._header, this._offset) + } - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; + _update () { + while (this._buffer.buffered > 0 && !this.destroying) { + if (this._missing > 0) { + if (this._stream !== null) { + if (this._consumeStream() === false) return + continue + } + + if (this._longHeader === true) { + if (this._missing > this._buffer.buffered) break + if (this._consumeLongHeader() === false) return false + continue + } + + const ignore = this._buffer.shiftFirst(this._missing) + if (ignore !== null) this._missing -= ignore.byteLength + continue } - let flags = 0; + if (this._buffer.buffered < 512) break + if (this._stream !== null || this._consumeHeader() === false) return + } - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid public key argument'); + this._continueWrite(null) + } - if (pubKey.type === 'ssh-rsa' && options) { - switch (options.hash) { - case 'sha256': - flags = SSH_AGENT_RSA_SHA2_256; - break; - case 'sha512': - flags = SSH_AGENT_RSA_SHA2_512; - break; - } - } - pubKey = pubKey.getPublicSSH(); + _continueWrite (err) { + const cb = this._callback + this._callback = noop + cb(err) + } - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - const type = SSH_AGENTC_SIGN_REQUEST; - const keyLen = pubKey.length; - const dataLen = data.length; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); + _write (data, cb) { + this._callback = cb + this._buffer.push(data) + this._update() + } - writeUInt32BE(buf, buf.length - 4, p); + _final (cb) { + this._finished = this._missing === 0 && this._buffer.buffered === 0 + cb(this._finished ? null : new Error('Unexpected end of data')) + } - buf[p += 4] = type; + _predestroy () { + this._continueWrite(null) + } - writeUInt32BE(buf, keyLen, ++p); - pubKey.copy(buf, p += 4); + _destroy (cb) { + if (this._stream) this._stream.destroy(getStreamError(this)) + cb(null) + } - writeUInt32BE(buf, dataLen, p += keyLen); - data.copy(buf, p += 4); + [Symbol.asyncIterator] () { + let error = null - writeUInt32BE(buf, flags, p += dataLen); + let promiseResolve = null + let promiseReject = null - if (typeof cb !== 'function') - cb = noop; + let entryStream = null + let entryCallback = null - this[SYM_REQS].push({ type, cb }); + const extract = this - return this.push(buf); - } - getIdentities(cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); + this.on('entry', onentry) + this.on('error', (err) => { error = err }) + this.on('close', onclose) - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - const type = SSH_AGENTC_REQUEST_IDENTITIES; + return { + [Symbol.asyncIterator] () { + return this + }, + next () { + return new Promise(onnext) + }, + return () { + return destroy(null) + }, + throw (err) { + return destroy(err) + } + } - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); + function consumeCallback (err) { + if (!entryCallback) return + const cb = entryCallback + entryCallback = null + cb(err) + } - writeUInt32BE(buf, buf.length - 4, p); + function onnext (resolve, reject) { + if (error) { + return reject(error) + } - buf[p += 4] = type; + if (entryStream) { + resolve({ value: entryStream, done: false }) + entryStream = null + return + } - if (typeof cb !== 'function') - cb = noop; + promiseResolve = resolve + promiseReject = reject - this[SYM_REQS].push({ type, cb }); + consumeCallback(null) - return this.push(buf); + if (extract._finished && promiseResolve) { + promiseResolve({ value: undefined, done: true }) + promiseResolve = promiseReject = null + } } - // Server->Client messages ================================================= - failureReply(req) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); + function onentry (header, stream, callback) { + entryCallback = callback + stream.on('error', noop) // no way around this due to tick sillyness - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); + if (promiseResolve) { + promiseResolve({ value: stream, done: false }) + promiseResolve = promiseReject = null + } else { + entryStream = stream + } + } - if (req.hasResponded()) - return true; + function onclose () { + consumeCallback(error) + if (!promiseResolve) return + if (error) promiseReject(error) + else promiseResolve({ value: undefined, done: true }) + promiseResolve = promiseReject = null + } - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); + function destroy (err) { + extract.destroy(err) + consumeCallback(err) + return new Promise((resolve, reject) => { + if (extract.destroyed) return resolve({ value: undefined, done: true }) + extract.once('close', function () { + if (err) reject(err) + else resolve({ value: undefined, done: true }) + }) + }) + } + } +} - writeUInt32BE(buf, buf.length - 4, p); +module.exports = function extract (opts) { + return new Extract(opts) +} - buf[p += 4] = SSH_AGENT_FAILURE; +function noop () {} - return respond(this, req, buf); - } - getIdentitiesReply(req, keys) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); +function overflow (size) { + size &= 511 + return size && 512 - size +} - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - if (req.hasResponded()) - return true; +/***/ }), - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys +/***/ 8860: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - where `nkeys` is 0 or more of: - string key blob - string comment - */ +const b4a = __nccwpck_require__(3497) - if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) - throw new Error('Invalid response to request'); +const ZEROS = '0000000000000000000' +const SEVENS = '7777777777777777777' +const ZERO_OFFSET = '0'.charCodeAt(0) +const USTAR_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x00]) // ustar\x00 +const USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]) +const GNU_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x20]) // ustar\x20 +const GNU_VER = b4a.from([0x20, 0x00]) +const MASK = 0o7777 +const MAGIC_OFFSET = 257 +const VERSION_OFFSET = 263 - if (!Array.isArray(keys)) - throw new Error('Keys argument must be an array'); +exports.decodeLongPath = function decodeLongPath (buf, encoding) { + return decodeStr(buf, 0, buf.length, encoding) +} - let totalKeysLen = 4; // Include `nkeys` size +exports.encodePax = function encodePax (opts) { // TODO: encode more stuff in pax + let result = '' + if (opts.name) result += addLength(' path=' + opts.name + '\n') + if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') + const pax = opts.pax + if (pax) { + for (const key in pax) { + result += addLength(' ' + key + '=' + pax[key] + '\n') + } + } + return b4a.from(result) +} - const newKeys = []; - for (let i = 0; i < keys.length; ++i) { - const entry = keys[i]; - if (typeof entry !== 'object' || entry === null) - throw new Error(`Invalid key entry: ${entry}`); +exports.decodePax = function decodePax (buf) { + const result = {} - let pubKey; - let comment; - if (isParsedKey(entry)) { - pubKey = entry; - } else if (isParsedKey(entry.pubKey)) { - pubKey = entry.pubKey; - } else { - if (typeof entry.pubKey !== 'object' || entry.pubKey === null) - continue; - ({ pubKey, comment } = entry.pubKey); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - continue; // TODO: add debug output - } - comment = pubKey.comment || comment; - pubKey = pubKey.getPublicSSH(); + while (buf.length) { + let i = 0 + while (i < buf.length && buf[i] !== 32) i++ + const len = parseInt(b4a.toString(buf.subarray(0, i)), 10) + if (!len) return result - totalKeysLen += 4 + pubKey.length; + const b = b4a.toString(buf.subarray(i + 1, len - 1)) + const keyIndex = b.indexOf('=') + if (keyIndex === -1) return result + result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) - if (comment && typeof comment === 'string') - comment = Buffer.from(comment); - else if (!Buffer.isBuffer(comment)) - comment = EMPTY_BUF; + buf = buf.subarray(len) + } - totalKeysLen += 4 + comment.length; + return result +} - newKeys.push({ pubKey, comment }); - } +exports.encode = function encode (opts) { + const buf = b4a.alloc(512) + let name = opts.name + let prefix = '' - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); + if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' + if (b4a.byteLength(name) !== name.length) return null // utf-8 - writeUInt32BE(buf, buf.length - 4, p); + while (b4a.byteLength(name) > 100) { + const i = name.indexOf('/') + if (i === -1) return null + prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) + name = name.slice(i + 1) + } - buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; + if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null + if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null - writeUInt32BE(buf, newKeys.length, ++p); - p += 4; - for (let i = 0; i < newKeys.length; ++i) { - const { pubKey, comment } = newKeys[i]; + b4a.write(buf, name) + b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100) + b4a.write(buf, encodeOct(opts.uid, 6), 108) + b4a.write(buf, encodeOct(opts.gid, 6), 116) + encodeSize(opts.size, buf, 124) + b4a.write(buf, encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) - writeUInt32BE(buf, pubKey.length, p); - pubKey.copy(buf, p += 4); + buf[156] = ZERO_OFFSET + toTypeflag(opts.type) - writeUInt32BE(buf, comment.length, p += pubKey.length); - p += 4; - if (comment.length) { - comment.copy(buf, p); - p += comment.length; - } - } + if (opts.linkname) b4a.write(buf, opts.linkname, 157) - return respond(this, req, buf); - } - signReply(req, signature) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); + b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET) + b4a.copy(USTAR_VER, buf, VERSION_OFFSET) + if (opts.uname) b4a.write(buf, opts.uname, 265) + if (opts.gname) b4a.write(buf, opts.gname, 297) + b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329) + b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337) - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); + if (prefix) b4a.write(buf, prefix, 345) - if (req.hasResponded()) - return true; + b4a.write(buf, encodeOct(cksum(buf), 6), 148) - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ + return buf +} - if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) - throw new Error('Invalid response to request'); +exports.decode = function decode (buf, filenameEncoding, allowUnknownFormat) { + let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET - if (!Buffer.isBuffer(signature)) - throw new Error('Signature argument must be a Buffer'); + let name = decodeStr(buf, 0, 100, filenameEncoding) + const mode = decodeOct(buf, 100, 8) + const uid = decodeOct(buf, 108, 8) + const gid = decodeOct(buf, 116, 8) + const size = decodeOct(buf, 124, 12) + const mtime = decodeOct(buf, 136, 12) + const type = toType(typeflag) + const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) + const uname = decodeStr(buf, 265, 32) + const gname = decodeStr(buf, 297, 32) + const devmajor = decodeOct(buf, 329, 8) + const devminor = decodeOct(buf, 337, 8) - if (signature.length === 0) - throw new Error('Signature argument must be non-empty'); + const c = cksum(buf) - /* - OpenSSH agent signatures are encoded as: + // checksum is still initial value if header was null. + if (c === 8 * 32) return null - string signature format identifier (as specified by the - public key/certificate format) - byte[n] signature blob in format specific encoding. - - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 - types - */ + // valid checksum + if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') - let p = 0; - const sigFormat = req.getContext(); - const sigFormatLen = Buffer.byteLength(sigFormat); - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length - ); + if (isUSTAR(buf)) { + // ustar (posix) format. + // prepend prefix, if present. + if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name + } else if (isGNU(buf)) { + // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and + // multi-volume tarballs. + } else { + if (!allowUnknownFormat) { + throw new Error('Invalid tar header: unknown format.') + } + } - writeUInt32BE(buf, buf.length - 4, p); + // to support old tar versions that use trailing / to indicate dirs + if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 - buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; + return { + name, + mode, + uid, + gid, + size, + mtime: new Date(1000 * mtime), + type, + linkname, + uname, + gname, + devmajor, + devminor, + pax: null + } +} - writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); - writeUInt32BE(buf, sigFormatLen, p += 4); - buf.utf8Write(sigFormat, p += 4, sigFormatLen); - writeUInt32BE(buf, signature.length, p += sigFormatLen); - signature.copy(buf, p += 4); +function isUSTAR (buf) { + return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) +} - return respond(this, req, buf); - } - }; -})(); +function isGNU (buf) { + return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && + b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2)) +} -const SYM_AGENT = Symbol('Agent'); -const SYM_AGENT_KEYS = Symbol('Agent Keys'); -const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); -const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); -class AgentContext { - constructor(agent) { - if (typeof agent === 'string') - agent = createAgent(agent); - else if (!isAgent(agent)) - throw new Error('Invalid agent argument'); - this[SYM_AGENT] = agent; - this[SYM_AGENT_KEYS] = null; - this[SYM_AGENT_KEYS_IDX] = -1; - this[SYM_AGENT_CBS] = null; +function clamp (index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue + index = ~~index // Coerce to integer. + if (index >= len) return len + if (index >= 0) return index + index += len + if (index >= 0) return index + return 0 +} + +function toType (flag) { + switch (flag) { + case 0: + return 'file' + case 1: + return 'link' + case 2: + return 'symlink' + case 3: + return 'character-device' + case 4: + return 'block-device' + case 5: + return 'directory' + case 6: + return 'fifo' + case 7: + return 'contiguous-file' + case 72: + return 'pax-header' + case 55: + return 'pax-global-header' + case 27: + return 'gnu-long-link-path' + case 28: + case 30: + return 'gnu-long-path' } - init(cb) { - if (typeof cb !== 'function') - cb = noop; - if (this[SYM_AGENT_KEYS] === null) { - if (this[SYM_AGENT_CBS] === null) { - this[SYM_AGENT_CBS] = [cb]; + return null +} - const doCbs = (...args) => { - process.nextTick(() => { - const cbs = this[SYM_AGENT_CBS]; - this[SYM_AGENT_CBS] = null; - for (const cb of cbs) - cb(...args); - }); - }; +function toTypeflag (flag) { + switch (flag) { + case 'file': + return 0 + case 'link': + return 1 + case 'symlink': + return 2 + case 'character-device': + return 3 + case 'block-device': + return 4 + case 'directory': + return 5 + case 'fifo': + return 6 + case 'contiguous-file': + return 7 + case 'pax-header': + return 72 + } - this[SYM_AGENT].getIdentities(once((err, keys) => { - if (err) - return doCbs(err); + return 0 +} - if (!Array.isArray(keys)) { - return doCbs(new Error( - 'Agent implementation failed to provide keys' - )); - } +function indexOf (block, num, offset, end) { + for (; offset < end; offset++) { + if (block[offset] === num) return offset + } + return end +} - const newKeys = []; - for (let key of keys) { - key = parseKey(key); - if (key instanceof Error) { - // TODO: add debug output - continue; - } - newKeys.push(key); - } +function cksum (block) { + let sum = 8 * 32 + for (let i = 0; i < 148; i++) sum += block[i] + for (let j = 156; j < 512; j++) sum += block[j] + return sum +} - this[SYM_AGENT_KEYS] = newKeys; - this[SYM_AGENT_KEYS_IDX] = -1; - doCbs(); - })); - } else { - this[SYM_AGENT_CBS].push(cb); - } - } else { - process.nextTick(cb); - } - } - nextKey() { - if (this[SYM_AGENT_KEYS] === null - || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return false; - } +function encodeOct (val, n) { + val = val.toString(8) + if (val.length > n) return SEVENS.slice(0, n) + ' ' + return ZEROS.slice(0, n - val.length) + val + ' ' +} - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; +function encodeSizeBin (num, buf, off) { + buf[off] = 0x80 + for (let i = 11; i > 0; i--) { + buf[off + i] = num & 0xff + num = Math.floor(num / 0x100) } - currentKey() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return null; - } +} - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; +function encodeSize (num, buf, off) { + if (num.toString(8).length > 11) { + encodeSizeBin(num, buf, off) + } else { + b4a.write(buf, encodeOct(num, 11), off) } - pos() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return -1; - } +} - return this[SYM_AGENT_KEYS_IDX]; +/* Copied from the node-tar repo and modified to meet + * tar-stream coding standard. + * + * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 + */ +function parse256 (buf) { + // first byte MUST be either 80 or FF + // 80 for positive, FF for 2's comp + let positive + if (buf[0] === 0x80) positive = true + else if (buf[0] === 0xFF) positive = false + else return null + + // build up a base-256 tuple from the least sig to the highest + const tuple = [] + let i + for (i = buf.length - 1; i > 0; i--) { + const byte = buf[i] + if (positive) tuple.push(byte) + else tuple.push(0xFF - byte) } - reset() { - this[SYM_AGENT_KEYS_IDX] = -1; + + let sum = 0 + const l = tuple.length + for (i = 0; i < l; i++) { + sum += tuple[i] * Math.pow(256, i) } - sign(...args) { - this[SYM_AGENT].sign(...args); + return positive ? sum : -1 * sum +} + +function decodeOct (val, offset, length) { + val = val.subarray(offset, offset + length) + offset = 0 + + // If prefixed with 0x80 then parse as a base-256 integer + if (val[offset] & 0x80) { + return parse256(val) + } else { + // Older versions of tar can prefix with spaces + while (offset < val.length && val[offset] === 32) offset++ + const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) + while (offset < end && val[offset] === 0) offset++ + if (end === offset) return 0 + return parseInt(b4a.toString(val.subarray(offset, end)), 8) } } -function isAgent(val) { - return (val instanceof BaseAgent); +function decodeStr (val, offset, length, encoding) { + return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding) } -module.exports = { - AgentContext, - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - isAgent, - OpenSSHAgent, - PageantAgent, -}; +function addLength (str) { + const len = b4a.byteLength(str) + let digits = Math.floor(Math.log(len) / Math.log(10)) + 1 + if (len + digits >= Math.pow(10, digits)) digits++ + + return (len + digits) + str +} /***/ }), -/***/ 6063: +/***/ 2283: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +exports.extract = __nccwpck_require__(7882) +exports.pack = __nccwpck_require__(4930) + + +/***/ }), + +/***/ 4930: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// TODO: -// * add `.connected` or similar property to allow immediate connection -// status checking -// * add/improve debug output during user authentication phase +const { Readable, Writable, getStreamError } = __nccwpck_require__(5147) +const b4a = __nccwpck_require__(3497) +const constants = __nccwpck_require__(8926) +const headers = __nccwpck_require__(8860) -const { - createHash, - getHashes, - randomFillSync, -} = __nccwpck_require__(6113); -const { Socket } = __nccwpck_require__(1808); -const { lookup: dnsLookup } = __nccwpck_require__(9523); -const EventEmitter = __nccwpck_require__(2361); -const HASHES = getHashes(); +const DMODE = 0o755 +const FMODE = 0o644 -const { - COMPAT, - CHANNEL_EXTENDED_DATATYPE: { STDERR }, - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = __nccwpck_require__(6832); -const { init: cryptoInit } = __nccwpck_require__(5708); -const Protocol = __nccwpck_require__(9031); -const { parseKey } = __nccwpck_require__(2218); -const { SFTP } = __nccwpck_require__(2026); -const { - bufferCopy, - makeBufferParser, - makeError, - readUInt32BE, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(9475); +const END_OF_TAR = b4a.alloc(1024) -const { AgentContext, createAgent, isAgent } = __nccwpck_require__(9054); -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = __nccwpck_require__(3204); -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = __nccwpck_require__(834); +class Sink extends Writable { + constructor (pack, header, callback) { + super({ mapWritable, eagerOpen: true }) -const bufferParser = makeBufferParser(); -const sigParser = makeBufferParser(); -const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; -const noop = (err) => {}; + this.written = 0 + this.header = header -class Client extends EventEmitter { - constructor() { - super(); + this._callback = callback + this._linkname = null + this._isLinkname = header.type === 'symlink' && !header.linkname + this._isVoid = header.type !== 'file' && header.type !== 'contiguous-file' + this._finished = false + this._pack = pack + this._openCallback = null - this.config = { - host: undefined, - port: undefined, - localAddress: undefined, - localPort: undefined, - forceIPv4: undefined, - forceIPv6: undefined, - keepaliveCountMax: undefined, - keepaliveInterval: undefined, - readyTimeout: undefined, - ident: undefined, + if (this._pack._stream === null) this._pack._stream = this + else this._pack._pending.push(this) + } - username: undefined, - password: undefined, - privateKey: undefined, - tryKeyboard: undefined, - agent: undefined, - allowAgentFwd: undefined, - authHandler: undefined, + _open (cb) { + this._openCallback = cb + if (this._pack._stream === this) this._continueOpen() + } - hostHashAlgo: undefined, - hostHashCb: undefined, - strictVendor: undefined, - debug: undefined - }; + _continuePack (err) { + if (this._callback === null) return - this._agent = undefined; - this._readyTimeout = undefined; - this._chanMgr = undefined; - this._callbacks = undefined; - this._forwarding = undefined; - this._forwardingUnix = undefined; - this._acceptX11 = undefined; - this._agentFwdEnabled = undefined; - this._remoteVer = undefined; + const callback = this._callback + this._callback = null - this._protocol = undefined; - this._sock = undefined; - this._resetKA = undefined; + callback(err) } - connect(cfg) { - if (this._sock && isWritable(this._sock)) { - this.once('close', () => { - this.connect(cfg); - }); - this.end(); - return this; + _continueOpen () { + if (this._pack._stream === null) this._pack._stream = this + + const cb = this._openCallback + this._openCallback = null + if (cb === null) return + + if (this._pack.destroying) return cb(new Error('pack stream destroyed')) + if (this._pack._finalized) return cb(new Error('pack stream is already finalized')) + + this._pack._stream = this + + if (!this._isLinkname) { + this._pack._encode(this.header) + } + + if (this._isVoid) { + this._finish() + this._continuePack(null) + } + + cb(null) + } + + _write (data, cb) { + if (this._isLinkname) { + this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data + return cb(null) + } + + if (this._isVoid) { + if (data.byteLength > 0) { + return cb(new Error('No body allowed for this entry')) + } + return cb() + } + + this.written += data.byteLength + if (this._pack.push(data)) return cb() + this._pack._drain = cb + } + + _finish () { + if (this._finished) return + this._finished = true + + if (this._isLinkname) { + this.header.linkname = this._linkname ? b4a.toString(this._linkname, 'utf-8') : '' + this._pack._encode(this.header) } - this.config.host = cfg.hostname || cfg.host || 'localhost'; - this.config.port = cfg.port || 22; - this.config.localAddress = (typeof cfg.localAddress === 'string' - ? cfg.localAddress - : undefined); - this.config.localPort = (typeof cfg.localPort === 'string' - || typeof cfg.localPort === 'number' - ? cfg.localPort - : undefined); - this.config.forceIPv4 = cfg.forceIPv4 || false; - this.config.forceIPv6 = cfg.forceIPv6 || false; - this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' - && cfg.keepaliveCountMax >= 0 - ? cfg.keepaliveCountMax - : 3); - this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' - && cfg.keepaliveInterval > 0 - ? cfg.keepaliveInterval - : 0); - this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' - && cfg.readyTimeout >= 0 - ? cfg.readyTimeout - : 20000); - this.config.ident = (typeof cfg.ident === 'string' - || Buffer.isBuffer(cfg.ident) - ? cfg.ident - : undefined); + overflow(this._pack, this.header.size) - const algorithms = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: [], - }, - sc: undefined, - }; - let allOfferDefaults = true; - if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { - algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, - DEFAULT_KEX, - SUPPORTED_KEX); - if (algorithms.kex !== DEFAULT_KEX) - allOfferDefaults = false; + this._pack._done(this) + } - algorithms.serverHostKey = - generateAlgorithmList(cfg.algorithms.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY); - if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) - allOfferDefaults = false; + _final (cb) { + if (this.written !== this.header.size) { // corrupting tar + return cb(new Error('Size mismatch')) + } - algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER); - if (algorithms.cs.cipher !== DEFAULT_CIPHER) - allOfferDefaults = false; + this._finish() + cb(null) + } - algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, - DEFAULT_MAC, - SUPPORTED_MAC); - if (algorithms.cs.mac !== DEFAULT_MAC) - allOfferDefaults = false; + _getError () { + return getStreamError(this) || new Error('tar entry destroyed') + } - algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION); - if (algorithms.cs.compress !== DEFAULT_COMPRESSION) - allOfferDefaults = false; + _predestroy () { + this._pack.destroy(this._getError()) + } - if (!allOfferDefaults) - algorithms.sc = algorithms.cs; - } + _destroy (cb) { + this._pack._done(this) - if (typeof cfg.username === 'string') - this.config.username = cfg.username; - else if (typeof cfg.user === 'string') - this.config.username = cfg.user; - else - throw new Error('Invalid username'); + this._continuePack(this._finished ? null : this._getError()) - this.config.password = (typeof cfg.password === 'string' - ? cfg.password - : undefined); - this.config.privateKey = (typeof cfg.privateKey === 'string' - || Buffer.isBuffer(cfg.privateKey) - ? cfg.privateKey - : undefined); - this.config.localHostname = (typeof cfg.localHostname === 'string' - ? cfg.localHostname - : undefined); - this.config.localUsername = (typeof cfg.localUsername === 'string' - ? cfg.localUsername - : undefined); - this.config.tryKeyboard = (cfg.tryKeyboard === true); - if (typeof cfg.agent === 'string' && cfg.agent.length) - this.config.agent = createAgent(cfg.agent); - else if (isAgent(cfg.agent)) - this.config.agent = cfg.agent; - else - this.config.agent = undefined; - this.config.allowAgentFwd = (cfg.agentForward === true - && this.config.agent !== undefined); - let authHandler = this.config.authHandler = ( - typeof cfg.authHandler === 'function' - || Array.isArray(cfg.authHandler) - ? cfg.authHandler - : undefined - ); + cb() + } +} - this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' - ? cfg.strictVendor - : true); +class Pack extends Readable { + constructor (opts) { + super(opts) + this._drain = noop + this._finalized = false + this._finalizing = false + this._pending = [] + this._stream = null + } - const debug = this.config.debug = (typeof cfg.debug === 'function' - ? cfg.debug - : undefined); + entry (header, buffer, callback) { + if (this._finalized || this.destroying) throw new Error('already finalized or destroyed') - if (cfg.agentForward === true && !this.config.allowAgentFwd) { - throw new Error( - 'You must set a valid agent path to allow agent forwarding' - ); + if (typeof buffer === 'function') { + callback = buffer + buffer = null } - let callbacks = this._callbacks = []; - this._chanMgr = new ChannelManager(this); - this._forwarding = {}; - this._forwardingUnix = {}; - this._acceptX11 = 0; - this._agentFwdEnabled = false; - this._agent = (this.config.agent ? this.config.agent : undefined); - this._remoteVer = undefined; - let privateKey; + if (!callback) callback = noop - if (this.config.privateKey) { - privateKey = parseKey(this.config.privateKey, cfg.passphrase); - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - if (privateKey.getPrivatePEM() === null) { - throw new Error( - 'privateKey value does not contain a (valid) private key' - ); - } + if (!header.size || header.type === 'symlink') header.size = 0 + if (!header.type) header.type = modeToType(header.mode) + if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE + if (!header.uid) header.uid = 0 + if (!header.gid) header.gid = 0 + if (!header.mtime) header.mtime = new Date() + + if (typeof buffer === 'string') buffer = b4a.from(buffer) + + const sink = new Sink(this, header, callback) + + if (b4a.isBuffer(buffer)) { + header.size = buffer.byteLength + sink.write(buffer) + sink.end() + return sink } - let hostVerifier; - if (typeof cfg.hostVerifier === 'function') { - const hashCb = cfg.hostVerifier; - let hasher; - if (HASHES.indexOf(cfg.hostHash) !== -1) { - // Default to old behavior of hashing on user's behalf - hasher = createHash(cfg.hostHash); - } - hostVerifier = (key, verify) => { - if (hasher) { - hasher.update(key); - key = hasher.digest('hex'); - } - const ret = hashCb(key, verify); - if (ret !== undefined) - verify(ret); - }; + if (sink._isVoid) { + return sink } - const sock = this._sock = (cfg.sock || new Socket()); - let ready = false; - let sawHeader = false; - if (this._protocol) - this._protocol.cleanup(); - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from server: ${JSON.stringify(msg)}`); - }); - const proto = this._protocol = new Protocol({ - ident: this.config.ident, - offer: (allOfferDefaults ? undefined : algorithms), - onWrite: (data) => { - if (isWritable(sock)) - sock.write(data); - }, - onError: (err) => { - if (err.level === 'handshake') - clearTimeout(this._readyTimeout); - if (!proto._destruct) - sock.removeAllListeners('data'); - this.emit('error', err); - try { - sock.end(); - } catch {} - }, - onHeader: (header) => { - sawHeader = true; - this._remoteVer = header.versions.software; - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - this.emit('handshake', negotiated); - if (!ready) { - ready = true; - proto.service('ssh-userauth'); - } - }, - debug, - hostVerifier, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - sock.end(); - }, - SERVICE_ACCEPT: (p, name) => { - if (name === 'ssh-userauth') - tryNextAuth(); - }, - USERAUTH_BANNER: (p, msg) => { - this.emit('banner', msg); - }, - USERAUTH_SUCCESS: (p) => { - // Start keepalive mechanism - resetKA(); + return sink + } - clearTimeout(this._readyTimeout); + finalize () { + if (this._stream || this._pending.length > 0) { + this._finalizing = true + return + } - this.emit('ready'); - }, - USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { - if (curAuth.type === 'agent') { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Client: Agent key #${pos + 1} failed`); - return tryNextAgentKey(); - } + if (this._finalized) return + this._finalized = true - debug && debug(`Client: ${curAuth.type} auth failed`); + this.push(END_OF_TAR) + this.push(null) + } - curPartial = partialSuccess; - curAuthsLeft = authMethods; - tryNextAuth(); - }, - USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { - if (curAuth.type === 'password') { - // TODO: support a `changePrompt()` on `curAuth` that defaults to - // emitting 'change password' as before - this.emit('change password', prompt, (newPassword) => { - proto.authPassword( - this.config.username, - this.config.password, - newPassword - ); - }); - } - }, - USERAUTH_PK_OK: (p) => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.currentKey(); - proto.authPK(curAuth.username, key, (buf, cb) => { - curAuth.agentCtx.sign(key, buf, {}, (err, signed) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - } else { - return cb(signed); - } + _done (stream) { + if (stream !== this._stream) return - tryNextAgentKey(); - }); - }); - } else if (curAuth.type === 'publickey') { - proto.authPK(curAuth.username, curAuth.key, (buf, cb) => { - const signature = curAuth.key.sign(buf); - if (signature instanceof Error) { - signature.message = - `Error signing data with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - cb(signature); - }); - } - }, - USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { - if (curAuth.type === 'keyboard-interactive') { - const nprompts = (Array.isArray(prompts) ? prompts.length : 0); - if (nprompts === 0) { - debug && debug( - 'Client: Sending automatic USERAUTH_INFO_RESPONSE' - ); - proto.authInfoRes(); - return; - } - // We sent a keyboard-interactive user authentication request and - // now the server is sending us the prompts we need to present to - // the user - curAuth.prompt( - name, - instructions, - '', - prompts, - (answers) => { - proto.authInfoRes(answers); - } - ); - } - }, - REQUEST_SUCCESS: (p, data) => { - if (callbacks.length) - callbacks.shift()(false, data); - }, - REQUEST_FAILURE: (p) => { - if (callbacks.length) - callbacks.shift()(true); - }, - GLOBAL_REQUEST: (p, name, wantReply, data) => { - switch (name) { - case 'hostkeys-00@openssh.com': - // Automatically verify keys before passing to end user - hostKeysProve(this, data, (err, keys) => { - if (err) - return; - this.emit('hostkeys', keys); - }); - if (wantReply) - proto.requestSuccess(); - break; - default: - // Auto-reject all other global requests, this can be especially - // useful if the server is sending us dummy keepalive global - // requests - if (wantReply) - proto.requestFailure(); - } - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from server, typically a forwarded TCP or - // X11 connection - onCHANNEL_OPEN(this, info); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; + this._stream = null - const isSFTP = (channel.type === 'sftp'); - const type = (isSFTP ? 'session' : channel.type); - const chanInfo = { - type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const instance = ( - isSFTP - ? new SFTP(this, chanInfo, { debug }) - : new Channel(this, chanInfo) - ); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; + if (this._finalizing) this.finalize() + if (this._pending.length) this._pending.shift()._continueOpen() + } - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + _encode (header) { + if (!header.pax) { + const buf = headers.encode(header) + if (buf) { + this.push(buf) + return + } + } + this._encodePax(header) + } - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; + _encodePax (header) { + const paxHeader = headers.encodePax({ + name: header.name, + linkname: header.linkname, + pax: header.pax + }) - channel.incoming.window -= data.length; + const newHeader = { + name: 'PaxHeader', + mode: header.mode, + uid: header.uid, + gid: header.gid, + size: paxHeader.byteLength, + mtime: header.mtime, + type: 'pax-header', + linkname: header.linkname && 'PaxHeader', + uname: header.uname, + gname: header.gname, + devmajor: header.devmajor, + devminor: header.devminor + } - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } + this.push(headers.encode(newHeader)) + this.push(paxHeader) + overflow(this, paxHeader.byteLength) - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - if (type !== STDERR) - return; + newHeader.size = header.size + newHeader.type = header.type + this.push(headers.encode(newHeader)) + } - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + _doDrain () { + const drain = this._drain + this._drain = noop + drain() + } - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; + _predestroy () { + const err = getStreamError(this) - channel.incoming.window -= data.length; + if (this._stream) this._stream.destroy(err) - if (!channel.stderr.push(data)) { - channel._waitChanDrain = true; - return; - } + while (this._pending.length) { + const stream = this._pending.shift() + stream.destroy(err) + stream._continueOpen() + } - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + this._doDrain() + } - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; + _read (cb) { + this._doDrain() + cb() + } +} - if (channel._waitWindow) { - channel._waitWindow = false; +module.exports = function pack (opts) { + return new Pack(opts) +} - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +function modeToType (mode) { + switch (mode & constants.S_IFMT) { + case constants.S_IFBLK: return 'block-device' + case constants.S_IFCHR: return 'character-device' + case constants.S_IFDIR: return 'directory' + case constants.S_IFIFO: return 'fifo' + case constants.S_IFLNK: return 'symlink' + } - this._resetKA(); + return 'file' +} - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +function noop () {} - this._resetKA(); +function overflow (self, size) { + size &= 511 + if (size) self.push(END_OF_TAR.subarray(0, 512 - size)) +} - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +function mapWritable (buf) { + return b4a.isBuffer(buf) ? buf : b4a.from(buf) +} - const exit = channel._exit; - if (exit.code !== undefined) - return; - switch (type) { - case 'exit-status': - channel.emit('exit', exit.code = data); - return; - case 'exit-signal': - channel.emit('exit', - exit.code = null, - exit.signal = `SIG${data.signal}`, - exit.dump = data.coreDumped, - exit.desc = data.errorMessage); - return; - } - // Keepalive request? OpenSSH will send one as a channel request if - // there is a channel open +/***/ }), - if (wantReply) - p.channelFailure(channel.outgoing.id); - }, - CHANNEL_EOF: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +/***/ 4294: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; +module.exports = __nccwpck_require__(4219); - if (channel.readable) - channel.push(null); - if (channel.stderr.readable) - channel.stderr.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); - }, - }, - }); - sock.pause(); +/***/ }), - // TODO: check keepalive implementation - // Keepalive-related - const kainterval = this.config.keepaliveInterval; - const kacountmax = this.config.keepaliveCountMax; - let kacount = 0; - let katimer; - const sendKA = () => { - if (++kacount > kacountmax) { - clearInterval(katimer); - if (sock.readable) { - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - } - return; - } - if (isWritable(sock)) { - // Append dummy callback to keep correct callback order - callbacks.push(resetKA); - proto.ping(); - } else { - clearInterval(katimer); - } - }; - function resetKA() { - if (kainterval > 0) { - kacount = 0; - clearInterval(katimer); - if (isWritable(sock)) - katimer = setInterval(sendKA, kainterval); - } - } - this._resetKA = resetKA; +/***/ 4219: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const onDone = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (wasConnected && !sawHeader) { - const err = - makeError('Connection lost before handshake', 'protocol', true); - this.emit('error', err); - } - }; - })(); - const onConnect = (() => { - let called = false; - return () => { - if (called) - return; - called = true; +"use strict"; - wasConnected = true; - debug && debug('Socket connected'); - this.emit('connect'); - cryptoInit.then(() => { - proto.start(); - sock.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - } - }); +var net = __nccwpck_require__(1808); +var tls = __nccwpck_require__(4404); +var http = __nccwpck_require__(3685); +var https = __nccwpck_require__(5687); +var events = __nccwpck_require__(2361); +var assert = __nccwpck_require__(9491); +var util = __nccwpck_require__(3837); - // Drain stderr if we are connection hopping using an exec stream - if (sock.stderr && typeof sock.stderr.resume === 'function') - sock.stderr.resume(); - sock.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - }); - }; - })(); - let wasConnected = false; - sock.on('connect', onConnect) - .on('timeout', () => { - this.emit('timeout'); - }).on('error', (err) => { - debug && debug(`Socket error: ${err.message}`); - clearTimeout(this._readyTimeout); - err.level = 'client-socket'; - this.emit('error', err); - }).on('end', () => { - debug && debug('Socket ended'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('end'); - }).on('close', () => { - debug && debug('Socket closed'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('close'); +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; - // Notify outstanding channel requests of disconnection ... - const callbacks_ = callbacks; - callbacks = this._callbacks = []; - const err = new Error('No response from server'); - for (let i = 0; i < callbacks_.length; ++i) - callbacks_[i](err); - // Simulate error for any channels waiting to be opened - this._chanMgr.cleanup(err); - }); +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} - // Begin authentication handling =========================================== - let curAuth; - let curPartial = null; - let curAuthsLeft = null; - const authsAllowed = ['none']; - if (this.config.password !== undefined) - authsAllowed.push('password'); - if (privateKey !== undefined) - authsAllowed.push('publickey'); - if (this._agent !== undefined) - authsAllowed.push('agent'); - if (this.config.tryKeyboard) - authsAllowed.push('keyboard-interactive'); - if (privateKey !== undefined - && this.config.localHostname !== undefined - && this.config.localUsername !== undefined) { - authsAllowed.push('hostbased'); - } +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} - if (Array.isArray(authHandler)) - authHandler = makeSimpleAuthHandler(authHandler); - else if (typeof authHandler !== 'function') - authHandler = makeSimpleAuthHandler(authsAllowed); +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} - let hasSentAuth = false; - const doNextAuth = (nextAuth) => { - if (hasSentAuth) - return; - hasSentAuth = true; +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} - if (nextAuth === false) { - const err = new Error('All configured authentication methods failed'); - err.level = 'client-authentication'; - this.emit('error', err); - this.end(); + +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; + + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); return; } + } + socket.destroy(); + self.removeSocket(socket); + }); +} +util.inherits(TunnelingAgent, events.EventEmitter); - if (typeof nextAuth === 'string') { - // Remain backwards compatible with original `authHandler()` usage, - // which only supported passing names of next method to try using data - // from the `connect()` config object +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - const type = nextAuth; - if (authsAllowed.indexOf(type) === -1) - return skipAuth(`Authentication method not allowed: ${type}`); + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } - const username = this.config.username; - switch (type) { - case 'password': - nextAuth = { type, username, password: this.config.password }; - break; - case 'publickey': - nextAuth = { type, username, key: privateKey }; - break; - case 'hostbased': - nextAuth = { - type, - username, - key: privateKey, - localHostname: this.config.localHostname, - localUsername: this.config.localUsername, - }; - break; - case 'agent': - nextAuth = { - type, - username, - agentCtx: new AgentContext(this._agent), - }; - break; - case 'keyboard-interactive': - nextAuth = { - type, - username, - prompt: (...args) => this.emit('keyboard-interactive', ...args), - }; - break; - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } else if (typeof nextAuth !== 'object' || nextAuth === null) { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } else { - const username = nextAuth.username; - if (typeof username !== 'string') { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } - const type = nextAuth.type; - switch (type) { - case 'password': { - const { password } = nextAuth; - if (typeof password !== 'string' && !Buffer.isBuffer(password)) - return skipAuth('Skipping invalid password auth attempt'); - nextAuth = { type, username, password }; - break; - } - case 'publickey': { - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error) - return skipAuth('Skipping invalid key auth attempt'); - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key }; - break; - } - case 'hostbased': { - const { localHostname, localUsername } = nextAuth; - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error - || typeof localHostname !== 'string' - || typeof localUsername !== 'string') { - return skipAuth('Skipping invalid hostbased auth attempt'); - } - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key, localHostname, localUsername }; - break; - } - case 'agent': { - let agent = nextAuth.agent; - if (typeof agent === 'string' && agent.length) { - agent = createAgent(agent); - } else if (!isAgent(agent)) { - return skipAuth( - `Skipping invalid agent: ${nextAuth.agent}` - ); - } - nextAuth = { type, username, agentCtx: new AgentContext(agent) }; - break; - } - case 'keyboard-interactive': { - const { prompt } = nextAuth; - if (typeof prompt !== 'function') { - return skipAuth( - 'Skipping invalid keyboard-interactive auth attempt' - ); - } - nextAuth = { type, username, prompt }; - break; - } - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } - curAuth = nextAuth; + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); - // Begin authentication method's process - try { - const username = curAuth.username; - switch (curAuth.type) { - case 'password': - proto.authPassword(username, curAuth.password); - break; - case 'publickey': - proto.authPK(username, curAuth.key); - break; - case 'hostbased': - proto.authHostbased(username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - (buf, cb) => { - const signature = curAuth.key.sign(buf); - if (signature instanceof Error) { - signature.message = - `Error while signing with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } + function onFree() { + self.emit('free', socket, options); + } - cb(signature); - }); - break; - case 'agent': - curAuth.agentCtx.init((err) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - return tryNextAuth(); - } - tryNextAgentKey(); - }); - break; - case 'keyboard-interactive': - proto.authKeyboard(username); - break; - case 'none': - proto.authNone(username); - break; - } - } finally { - hasSentAuth = false; - } - }; + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); +}; - function skipAuth(msg) { - debug && debug(msg); - process.nextTick(tryNextAuth); +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); + + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } - function tryNextAuth() { - hasSentAuth = false; - const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); - if (hasSentAuth || auth === undefined) - return; - doNextAuth(auth); + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); + + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } - const tryNextAgentKey = () => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.nextKey(); - if (key === false) { - debug && debug('Agent: No more keys left to try'); - debug && debug('Client: agent auth failed'); - tryNextAuth(); - } else { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Agent: Trying key #${pos + 1}`); - proto.authPK(curAuth.username, key); - } - } - }; + function onError(cause) { + connectReq.removeAllListeners(); + + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; - const startTimeout = () => { - if (this.config.readyTimeout > 0) { - this._readyTimeout = setTimeout(() => { - const err = new Error('Timed out while waiting for handshake'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - }, this.config.readyTimeout); - } - }; +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); - if (!cfg.sock) { - let host = this.config.host; - const forceIPv4 = this.config.forceIPv4; - const forceIPv6 = this.config.forceIPv6; + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); + } +}; - debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); - const doConnect = () => { - startTimeout(); - sock.connect({ - host, - port: this.config.port, - localAddress: this.config.localAddress, - localPort: this.config.localPort - }); - sock.setNoDelay(true); - sock.setMaxListeners(0); - sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); - }; + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} - if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { - doConnect(); - } else { - dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { - if (err) { - const type = (forceIPv4 ? 'IPv4' : 'IPv6'); - const error = new Error( - `Error while looking up ${type} address for '${host}': ${err}` - ); - clearTimeout(this._readyTimeout); - error.level = 'client-dns'; - this.emit('error', error); - this.emit('close'); - return; - } - host = address; - doConnect(); - }); - } - } else { - // Custom socket passed in - startTimeout(); - if (typeof sock.connecting === 'boolean') { - // net.Socket - if (!sock.connecting) { - // Already connected - onConnect(); +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later +} + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; } - } else { - // Assume socket/stream is already "connected" - onConnect(); } } - - return this; } + return target; +} - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); + +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); } - return this; + console.error.apply(console, args); } +} else { + debug = function() {}; +} +exports.debug = debug; // for test - destroy() { - this._sock && isWritable(this._sock) && this._sock.destroy(); - return this; - } - exec(cmd, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); +/***/ }), - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } +/***/ 8729: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; +(function(nacl) { +'use strict'; - openChannel(this, 'session', extraOpts, (err, chan) => { - if (err) { - cb(err); - return; - } +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ - const todo = []; +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.pty === 'object' && opts.pty !== null) - || opts.pty === true) { - todo.push(() => reqPty(chan, opts.pty, reqCb)); - } - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - todo.push(() => reqExec(chan, cmd, opts, cb)); - todo.shift()(); - }); +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} - return this; - } +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} - shell(wndopts, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} - if (typeof wndopts === 'function') { - cb = wndopts; - wndopts = opts = undefined; - } else if (typeof opts === 'function') { - cb = opts; - opts = undefined; - } - if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { - opts = wndopts; - wndopts = undefined; - } +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; - const todo = []; + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); - if (wndopts !== false) - todo.push(() => reqPty(chan, wndopts, reqCb)); + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); - todo.push(() => reqShell(chan, cb)); - todo.shift()(); - }); + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); - return this; + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; - subsys(name, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; - reqSubsystem(chan, name, (err, stream) => { - if (err) { - cb(err); - return; - } + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; - cb(undefined, stream); - }); - }); + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; - return this; - } + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; - forwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; - // Send a request for the server to start forwarding TCP connections to us - // on a particular address and port + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; - const wantReply = (typeof cb === 'function'); + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; - if (wantReply) { - this._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); - return; - } + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; - let realPort = bindPort; - if (bindPort === 0 && data && data.length >= 4) { - realPort = readUInt32BE(data, 0); - if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) - bindPort = realPort; - } + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; - this._forwarding[`${bindAddr}:${bindPort}`] = realPort; + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; - cb(undefined, realPort); - }); - } + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; - this._protocol.tcpipForward(bindAddr, bindPort, wantReply); + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; - return this; - } + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; - unforwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} + +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; - // Send a request to stop forwarding us new connections for a particular - // address and port + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; - const wantReply = (typeof cb === 'function'); + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); - return; - } + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); - delete this._forwarding[`${bindAddr}:${bindPort}`]; + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); - cb(); - }); - } + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); - this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); - return this; - } + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); - forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); - // Send a request to forward a TCP connection to the server + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } - const cfg = { - srcIP: srcIP, - srcPort: srcPort, - dstIP: dstIP, - dstPort: dstPort - }; + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; - if (typeof cb !== 'function') - cb = noop; + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; - openChannel(this, 'direct-tcpip', cfg, cb); + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; - return this; - } + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; - openssh_noMoreSessions(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; - const wantReply = (typeof cb === 'function'); + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to disable future sessions')); - return; - } + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; - cb(); - }); - } + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} - this._protocol.openssh_noMoreSessions(wantReply); - return this; - } +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} - if (!wantReply) - return this; +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" - return this; +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; } + return 0; +} - openssh_forwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} - const wantReply = (typeof cb === 'function'); +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${socketPath}`)); - return; - } - this._forwardingUnix[socketPath] = true; - cb(); - }); - } +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} - this._protocol.openssh_streamLocalForward(socketPath, wantReply); - return this; - } +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ - if (!wantReply) - return this; +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); + var t0, t1, t2, t3, t4, t5, t6, t7; - return this; - } + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; - openssh_unforwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; - const wantReply = (typeof cb === 'function'); +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${socketPath}`)); - return; - } - delete this._forwardingUnix[socketPath]; - cb(); - }); - } + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; - this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); - return this; - } + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; - if (!wantReply) - return this; + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); + c = 0; - return this; - } + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; - openssh_forwardOutStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; - if (typeof cb !== 'function') - cb = noop; + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); - return this; - } - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; - return this; - } + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; - sftp(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; - openChannel(this, 'sftp', (err, sftp) => { - if (err) { - cb(err); - return; - } + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; - reqSubsystem(sftp, 'sftp', (err, sftp_) => { - if (err) { - cb(err); - return; - } + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; - function removeListeners() { - sftp.removeListener('ready', onReady); - sftp.removeListener('error', onError); - sftp.removeListener('exit', onExit); - sftp.removeListener('close', onExit); - } + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; - function onReady() { - // TODO: do not remove exit/close in case remote end closes the - // channel abruptly and we need to notify outstanding callbacks - removeListeners(); - cb(undefined, sftp); - } + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; - function onError(err) { - removeListeners(); - cb(err); - } + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; - function onExit(code, signal) { - removeListeners(); - let msg; - if (typeof code === 'number') - msg = `Received exit code ${code} while establishing SFTP session`; - else if (signal !== undefined) - msg = `Received signal ${signal} while establishing SFTP session`; - else - msg = 'Received unexpected SFTP session termination'; - const err = new Error(msg); - err.code = code; - err.signal = signal; - cb(err); - } + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; - sftp.on('ready', onReady) - .on('error', onError) - .on('exit', onExit) - .on('close', onExit); + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; - sftp._init(); - }); - }); +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; - return this; + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); } -} -function openChannel(self, type, opts, cb) { - // Ask the server to open a channel for some purpose - // (e.g. session (sftp, exec, shell), or forwarding a TCP connection - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; - if (typeof opts === 'function') { - cb = opts; - opts = {}; + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; } + g[9] -= (1 << 13); - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; - const localChan = self._chanMgr.add(wrapper); + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; - if (localChan === -1) { - cb(new Error('No free channels available')); - return; + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; } - switch (type) { - case 'session': - case 'sftp': - self._protocol.session(localChan, initWindow, maxPacket); - break; - case 'direct-tcpip': - self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'direct-streamlocal@openssh.com': - self._protocol.openssh_directStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; -function reqX11(chan, screen, cb) { - // Asks server to start sending us X11 connections - const cfg = { - single: false, - protocol: 'MIT-MAGIC-COOKIE-1', - cookie: undefined, - screen: 0 - }; +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; - if (typeof screen === 'function') { - cb = screen; - } else if (typeof screen === 'object' && screen !== null) { - if (typeof screen.single === 'boolean') - cfg.single = screen.single; - if (typeof screen.screen === 'number') - cfg.screen = screen.screen; - if (typeof screen.protocol === 'string') - cfg.protocol = screen.protocol; - if (typeof screen.cookie === 'string') - cfg.cookie = screen.cookie; - else if (Buffer.isBuffer(screen.cookie)) - cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; } - if (cfg.cookie === undefined) - cfg.cookie = randomCookie(); - const wantReply = (typeof cb === 'function'); + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; } +}; - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to request X11')); - return; - } +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} - chan._hasX11 = true; - ++chan._client._acceptX11; - chan.once('close', () => { - if (chan._client._acceptX11) - --chan._client._acceptX11; - }); +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} - cb(); - }); - } +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} - chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; } -function reqPty(chan, opts, cb) { - let rows = 24; - let cols = 80; - let width = 640; - let height = 480; - let term = 'vt100'; - let modes = null; +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.rows === 'number') - rows = opts.rows; - if (typeof opts.cols === 'number') - cols = opts.cols; - if (typeof opts.width === 'number') - width = opts.width; - if (typeof opts.height === 'number') - height = opts.height; - if (typeof opts.term === 'string') - term = opts.term; - if (typeof opts.modes === 'object') - modes = opts.modes; +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; } + o[0] += c-1 + 37 * (c-1); +} - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; } +} - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to request a pseudo-terminal')); - return; - } - cb(); - }); +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; } +} - chan._client._protocol.pty(chan.outgoing.id, - rows, - cols, - height, - width, - term, - modes, - wantReply); +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); } -function reqAgentFwd(chan, cb) { - const wantReply = (typeof cb === 'function'); +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} - if (chan.outgoing.state !== 'open') { - wantReply && cb(new Error('Channel is not open')); - return; - } - if (chan._client._agentFwdEnabled) { - wantReply && cb(false); - return; - } +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; - chan._client._agentFwdEnabled = true; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is - chan._callbacks.push((had_err) => { - if (had_err) { - chan._client._agentFwdEnabled = false; - if (wantReply) { - cb(had_err !== true - ? had_err - : new Error('Unable to request agent forwarding')); - } - return; - } + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - if (wantReply) - cb(); - }); + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; } -function reqShell(chan, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to open shell')); - return; - } - chan.subtype = 'shell'; - cb(undefined, chan); - }); - - chan._client._protocol.shell(chan.outgoing.id, true); +function S(o, a) { + M(o, a, a); } -function reqExec(chan, cmd, opts, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to exec')); - return; - } - chan.subtype = 'exec'; - chan.allowHalfOpen = (opts.allowHalfOpen !== false); - cb(undefined, chan); - }); - - chan._client._protocol.exec(chan.outgoing.id, cmd, true); + for (a = 0; a < 16; a++) o[a] = c[a]; } -function reqEnv(chan, env) { - if (chan.outgoing.state !== 'open') - return; - - const keys = Object.keys(env || {}); - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const val = env[key]; - chan._client._protocol.env(chan.outgoing.id, key, val, false); +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; } -function reqSubsystem(chan, name, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to start subsystem: ${name}`)); - return; - } - chan.subtype = 'subsystem'; - cb(undefined, chan); - }); - - chan._client._protocol.subsystem(chan.outgoing.id, name, true); -} - -// TODO: inline implementation into single call site -function onCHANNEL_OPEN(self, info) { - // The server is trying to open a channel with us, this is usually when - // we asked the server to forward us connections on some port and now they - // are asking us to accept/deny an incoming connection on their side - - let localChan = -1; - let reason; - - const accept = () => { - const chanInfo = { - type: info.type, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const stream = new Channel(self, chanInfo); - self._chanMgr.update(localChan, stream); - - self._protocol.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - return stream; - }; - const reject = () => { - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - - if (localChan !== -1) - self._chanMgr.remove(localChan); - - self._protocol.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = self._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of incoming channel open: ' - + 'no channels available' - ); - } - } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'forwarded-tcpip': { - const val = self._forwarding[`${data.destIP}:${data.destPort}`]; - if (val !== undefined && reserveChannel()) { - if (data.destPort === 0) - data.destPort = val; - self.emit('tcp connection', data, accept, reject); - return; - } - break; - } - case 'forwarded-streamlocal@openssh.com': - if (self._forwardingUnix[data.socketPath] !== undefined - && reserveChannel()) { - self.emit('unix connection', data, accept, reject); - return; - } - break; - case 'auth-agent@openssh.com': - if (self._agentFwdEnabled - && typeof self._agent.getStream === 'function' - && reserveChannel()) { - self._agent.getStream((err, stream) => { - if (err) - return reject(); - - const upstream = accept(); - upstream.pipe(stream).pipe(upstream); - }); - return; - } - break; - case 'x11': - if (self._acceptX11 !== 0 && reserveChannel()) { - self.emit('x11', data, accept, reject); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unsupported incoming channel open ' - + `type: ${info.type}` - ); - } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unexpected incoming channel open for: ' - + info.type - ); - } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; } - - reject(); + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; } -const randomCookie = (() => { - const buffer = Buffer.allocUnsafe(16); - return () => { - randomFillSync(buffer, 0, 16); - return buffer.hexSlice(0, 16); - }; -})(); - -function makeSimpleAuthHandler(authList) { - if (!Array.isArray(authList)) - throw new Error('authList must be an array'); - - let a = 0; - return (authsLeft, partialSuccess, cb) => { - if (a === authList.length) - return false; - return authList[a++]; - }; +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); } -function hostKeysProve(client, keys_, cb) { - if (!client._sock || !isWritable(client._sock)) - return; - - if (typeof cb !== 'function') - cb = noop; - - if (!Array.isArray(keys_)) - throw new TypeError('Invalid keys argument type'); +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} - const keys = []; - for (const key of keys_) { - const parsed = parseKey(key); - if (parsed instanceof Error) - throw parsed; - keys.push(parsed); - } +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} - if (!client.config.strictVendor - || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { - client._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Server failed to prove supplied keys')); - return; - } +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; - // TODO: move all of this parsing/verifying logic out of the client? - const ret = []; - let keyIdx = 0; - bufferParser.init(data, 0); - while (bufferParser.avail()) { - if (keyIdx === keys.length) - break; - const key = keys[keyIdx++]; - const keyPublic = key.getPublicSSH(); +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} - const sigEntry = bufferParser.readString(); - sigParser.init(sigEntry, 0); - const type = sigParser.readString(true); - let value = sigParser.readString(); +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} - let algo; - if (type !== key.type) { - if (key.type === 'ssh-rsa') { - switch (type) { - case 'rsa-sha2-256': - algo = 'sha256'; - break; - case 'rsa-sha2-512': - algo = 'sha512'; - break; - default: - continue; - } - } else { - continue; - } - } +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; - const sessionID = client._protocol._kex.sessionID; - const verifyData = Buffer.allocUnsafe( - 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length - ); - let p = 0; - writeUInt32BE(verifyData, 29, p); - verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - writeUInt32BE(verifyData, sessionID.length, p += 29); - bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); - writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); - bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; - if (!(value = sigSSHToASN1(value, type))) - continue; - if (key.verify(verifyData, value, algo) === true) - ret.push(key); - } - sigParser.clear(); - bufferParser.clear(); + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], - cb(null, ret); - }); + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; - client._protocol.openssh_hostKeysProve(keys); - return; - } + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); -} + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; -module.exports = Client; + // add + h = ah7; + l = al7; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -/***/ }), + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); -/***/ 2994: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -"use strict"; + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -const { Agent: HttpAgent } = __nccwpck_require__(3685); -const { Agent: HttpsAgent } = __nccwpck_require__(5687); -const { connect: tlsConnect } = __nccwpck_require__(4404); + // K + h = K[i*2]; + l = K[i*2+1]; -let Client; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -for (const ctor of [HttpAgent, HttpsAgent]) { - class SSHAgent extends ctor { - constructor(connectCfg, agentOptions) { - super(agentOptions); + // w + h = wh[i%16]; + l = wl[i%16]; - this._connectCfg = connectCfg; - this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - createConnection(options, cb) { - const srcIP = (options && options.localAddress) || this._defaultSrcIP; - const srcPort = (options && options.localPort) || 0; - const dstIP = options.host; - const dstPort = options.port; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - if (Client === undefined) - Client = __nccwpck_require__(6063); + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; - const client = new Client(); - let triedForward = false; - client.on('ready', () => { - client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { - triedForward = true; - if (err) { - client.end(); - return cb(err); - } - stream.once('close', () => client.end()); - cb(null, decorateStream(stream, ctor, options)); - }); - }).on('error', cb).on('close', () => { - if (!triedForward) - cb(new Error('Unexpected connection close')); - }).connect(this._connectCfg); - } - } + // add + h = th; + l = tl; - exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; -} + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -function noop() {} + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); -function decorateStream(stream, ctor, options) { - if (ctor === HttpAgent) { - // HTTP - stream.setKeepAlive = noop; - stream.setNoDelay = noop; - stream.setTimeout = noop; - stream.ref = noop; - stream.unref = noop; - stream.destroySoon = stream.destroy; - return stream; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // HTTPS - options.socket = stream; - const wrapped = tlsConnect(options); + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); - // This is a workaround for a regression in node v12.16.3+ - // https://github.com/nodejs/node/issues/35904 - const onClose = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (stream.isPaused()) - stream.resume(); - }; - })(); - // 'end' listener is needed because 'close' is not emitted in some scenarios - // in node v12.x for some unknown reason - wrapped.on('end', onClose).on('close', onClose); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - return wrapped; -} + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); -/***/ }), + // add + h = bh3; + l = bl3; -/***/ 5869: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -"use strict"; + h = th; + l = tl; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -const { - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - OpenSSHAgent, - PageantAgent, -} = __nccwpck_require__(9054); -const { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent, -} = __nccwpck_require__(2994); -const { parseKey } = __nccwpck_require__(2218); -const { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, -} = __nccwpck_require__(2026); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; -module.exports = { - AgentProtocol, - BaseAgent, - createAgent, - Client: __nccwpck_require__(6063), - CygwinAgent, - HTTPAgent, - HTTPSAgent, - OpenSSHAgent, - PageantAgent, - Server: __nccwpck_require__(2986), - utils: { - parseKey, - sftp: { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, - }, - }, -}; + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; -/***/ }), + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; -/***/ 9031: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; -"use strict"; -/* - TODO: - * Replace `buffer._pos` usage in keyParser.js and elsewhere - * Utilize optional "writev" support when writing packets from - cipher.encrypt() - * Built-in support for automatic re-keying, on by default - * Revisit receiving unexpected/unknown packets - * Error (fatal or otherwise) or ignore or pass on to user (in some or all - cases)? - * Including server/client check for single directional packet types? - * Check packets for validity or bail as early as possible? - * Automatic re-key every 2**31 packets after the last key exchange (sent or - received), as suggested by RFC4344. OpenSSH currently does this. - * Automatic re-key every so many blocks depending on cipher. RFC4344: - Because of a birthday property of block ciphers and some modes of - operation, implementations must be careful not to encrypt too many - blocks with the same encryption key. + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - Let L be the block length (in bits) of an SSH encryption method's - block cipher (e.g., 128 for AES). If L is at least 128, then, after - rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) - blocks before rekeying again. If L is at least 128, then SSH - implementations should also attempt to force a rekey before receiving - more than 2**(L/4) blocks. If L is less than 128 (which is the case - for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, - although it may be too expensive to rekey every 2**(L/4) blocks, it - is still advisable for SSH implementations to follow the original - recommendation in [RFC4253]: rekey at least once for every gigabyte - of transmitted data. + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; - Note that if L is less than or equal to 128, then the recommendation - in this subsection supersedes the recommendation in Section 3.1. If - an SSH implementation uses a block cipher with a larger block size - (e.g., Rijndael with 256-bit blocks), then the recommendations in - Section 3.1 may supersede the recommendations in this subsection - (depending on the lengths of the packets). -*/ + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -const { inspect } = __nccwpck_require__(3837); + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); -const { bindingAvailable, NullCipher, NullDecipher } = __nccwpck_require__(5708); -const { - COMPAT_CHECKS, - DISCONNECT_REASON, - MESSAGE, - SIGNALS, - TERMINAL_MODE, -} = __nccwpck_require__(6832); -const { - DEFAULT_KEXINIT, - KexInit, - kexinit, - onKEXPayload, -} = __nccwpck_require__(4126); -const { - parseKey, -} = __nccwpck_require__(2218); -const MESSAGE_HANDLERS = __nccwpck_require__(172); -const { - bufferCopy, - bufferFill, - bufferSlice, - convertSignature, - sendPacket, - writeUInt32BE, -} = __nccwpck_require__(9475); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = __nccwpck_require__(6715); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -const MODULE_VER = (__nccwpck_require__(6674)/* .version */ .i8); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; -const VALID_DISCONNECT_REASONS = new Map( - Object.values(DISCONNECT_REASON).map((n) => [n, 1]) -); -const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); -const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); -const MAX_LINE_LEN = 8192; -const MAX_LINES = 1024; -const PING_PAYLOAD = Buffer.from([ - MESSAGE.GLOBAL_REQUEST, - // "keepalive@openssh.com" - 0, 0, 0, 21, - 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, - 115, 104, 46, 99, 111, 109, - // Request a reply - 1, -]); -const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } -function noop() {} + // add + h = ah0; + l = al0; -/* - Inbound: - * kexinit payload (needed only until exchange hash is generated) - * raw ident - * rekey packet queue - * expected packet (implemented as separate _parse() function?) - Outbound: - * kexinit payload (needed only until exchange hash is generated) - * rekey packet queue - * kex secret (needed only until NEWKEYS) - * exchange hash (needed only until NEWKEYS) - * session ID (set to exchange hash from initial handshake) -*/ -class Protocol { - constructor(config) { - const onWrite = config.onWrite; - if (typeof onWrite !== 'function') - throw new Error('Missing onWrite function'); - this._onWrite = (data) => { onWrite(data); }; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - const onError = config.onError; - if (typeof onError !== 'function') - throw new Error('Missing onError function'); - this._onError = (err) => { onError(err); }; + h = hh[0]; + l = hl[0]; - const debug = config.debug; - this._debug = (typeof debug === 'function' - ? (msg) => { debug(msg); } - : undefined); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - const onHeader = config.onHeader; - this._onHeader = (typeof onHeader === 'function' - ? (...args) => { onHeader(...args); } - : noop); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - const onPacket = config.onPacket; - this._onPacket = (typeof onPacket === 'function' - ? () => { onPacket(); } - : noop); + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); - let onHandshakeComplete = config.onHandshakeComplete; - if (typeof onHandshakeComplete !== 'function') - onHandshakeComplete = noop; - this._onHandshakeComplete = (...args) => { - this._debug && this._debug('Handshake completed'); + h = ah1; + l = al1; - // Process packets queued during a rekey where necessary - const oldQueue = this._queue; - if (oldQueue) { - this._queue = undefined; - this._debug && this._debug( - `Draining outbound queue (${oldQueue.length}) ...` - ); - for (let i = 0; i < oldQueue.length; ++i) { - const data = oldQueue[i]; - // data === payload only + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - // XXX: hacky - let finalized = this._packetRW.write.finalize(data); - if (finalized === data) { - const packet = this._cipher.allocPacket(data.length); - packet.set(data, 5); - finalized = packet; - } + h = hh[1]; + l = hl[1]; - sendPacket(this, finalized); - } - this._debug && this._debug('... finished draining outbound queue'); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - onHandshakeComplete(...args); - }; - this._queue = undefined; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - const messageHandlers = config.messageHandlers; - if (typeof messageHandlers === 'object' && messageHandlers !== null) - this._handlers = messageHandlers; - else - this._handlers = {}; + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); - this._onPayload = onPayload.bind(this); + h = ah2; + l = al2; - this._server = !!config.server; - this._banner = undefined; - let greeting; - if (this._server) { - if (typeof config.hostKeys !== 'object' || config.hostKeys === null) - throw new Error('Missing server host key(s)'); - this._hostKeys = config.hostKeys; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - // Greeting displayed before the ssh identification string is sent, this - // is usually ignored by most clients - if (typeof config.greeting === 'string' && config.greeting.length) { - greeting = (config.greeting.slice(-2) === '\r\n' - ? config.greeting - : `${config.greeting}\r\n`); - } + h = hh[2]; + l = hl[2]; - // Banner shown after the handshake completes, but before user - // authentication begins - if (typeof config.banner === 'string' && config.banner.length) { - this._banner = (config.banner.slice(-2) === '\r\n' - ? config.banner - : `${config.banner}\r\n`); - } - } else { - this._hostKeys = undefined; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - let offer = config.offer; - if (typeof offer !== 'object' || offer === null) - offer = DEFAULT_KEXINIT; - else if (offer.constructor !== KexInit) - offer = new KexInit(offer); - this._kex = undefined; - this._kexinit = undefined; - this._offer = offer; - this._cipher = new NullCipher(0, this._onWrite); - this._decipher = undefined; - this._skipNextInboundPacket = false; - this._packetRW = { - read: new PacketReader(), - write: new PacketWriter(this), - }; - this._hostVerifier = (!this._server - && typeof config.hostVerifier === 'function' - ? config.hostVerifier - : undefined); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - this._parse = parseHeader; - this._buffer = undefined; - this._authsQueue = []; - this._authenticated = false; - this._remoteIdentRaw = undefined; - let sentIdent; - if (typeof config.ident === 'string') { - this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); - sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); - sentIdent.set(this._identRaw, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else if (Buffer.isBuffer(config.ident)) { - const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); - fullIdent.latin1Write('SSH-2.0-', 0, 8); - fullIdent.set(config.ident, 8); - this._identRaw = fullIdent; + h = ah3; + l = al3; - sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); - sentIdent.set(fullIdent, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else { - this._identRaw = IDENT_RAW; - sentIdent = IDENT; - } - this._compatFlags = 0; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (this._debug) { - if (bindingAvailable) - this._debug('Custom crypto binding available'); - else - this._debug('Custom crypto binding not available'); - } + h = hh[3]; + l = hl[3]; - this._debug && this._debug( - `Local ident: ${inspect(this._identRaw.toString())}` - ); - this.start = () => { - this.start = undefined; - if (greeting) - this._onWrite(greeting); - this._onWrite(sentIdent); - }; - } - _destruct(reason) { - this._packetRW.read.cleanup(); - this._packetRW.write.cleanup(); - this._cipher && this._cipher.free(); - this._decipher && this._decipher.free(); - if (typeof reason !== 'string' || reason.length === 0) - reason = 'fatal error'; - this.parse = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._onWrite = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._destruct = undefined; - } - cleanup() { - this._destruct && this._destruct(); - } - parse(chunk, i, len) { - while (i < len) - i = this._parse(chunk, i, len); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // Protocol message API + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - // =========================================================================== - // Common/Shared ============================================================= - // =========================================================================== + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); - // Global - // ------ - disconnect(reason) { - const pktLen = 1 + 4 + 4 + 4; - // We don't use _packetRW.write.* here because we need to make sure that - // we always get a full packet allocated because this message can be sent - // at any time -- even during a key exchange - let p = this._packetRW.write.allocStartKEX; - const packet = this._packetRW.write.alloc(pktLen, true); - const end = p + pktLen; + h = ah4; + l = al4; - if (!VALID_DISCONNECT_REASONS.has(reason)) - reason = DISCONNECT_REASON.PROTOCOL_ERROR; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - packet[p] = MESSAGE.DISCONNECT; - writeUInt32BE(packet, reason, ++p); - packet.fill(0, p += 4, end); + h = hh[4]; + l = hl[4]; - this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); - sendPacket(this, this._packetRW.write.finalize(packet, true), true); - } - ping() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - packet.set(PING_PAYLOAD, p); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - this._debug && this._debug( - 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - rekey() { - if (this._kexinit === undefined) { - this._debug && this._debug('Outbound: Initiated explicit rekey'); - this._queue = []; - kexinit(this); - } else { - this._debug && this._debug('Outbound: Ignoring rekey during handshake'); - } - } + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); - // 'ssh-connection' service-specific - // --------------------------------- - requestSuccess(data) { - let p = this._packetRW.write.allocStart; - let packet; - if (Buffer.isBuffer(data)) { - packet = this._packetRW.write.alloc(1 + data.length); + h = ah5; + l = al5; - packet[p] = MESSAGE.REQUEST_SUCCESS; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - packet.set(data, ++p); - } else { - packet = this._packetRW.write.alloc(1); + h = hh[5]; + l = hl[5]; - packet[p] = MESSAGE.REQUEST_SUCCESS; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - requestFailure() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - packet[p] = MESSAGE.REQUEST_FAILURE; + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); - this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelSuccess(chan) { - // Does not consume window space + h = ah6; + l = al6; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - packet[p] = MESSAGE.CHANNEL_SUCCESS; + h = hh[6]; + l = hl[6]; - writeUInt32BE(packet, chan, ++p); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelFailure(chan) { - // Does not consume window space + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); - packet[p] = MESSAGE.CHANNEL_FAILURE; + h = ah7; + l = al7; - writeUInt32BE(packet, chan, ++p); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelEOF(chan) { - // Does not consume window space + h = hh[7]; + l = hl[7]; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - packet[p] = MESSAGE.CHANNEL_EOF; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - writeUInt32BE(packet, chan, ++p); + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); - this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); + pos += 128; + n -= 128; } - channelClose(chan) { - // Does not consume window space - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); + return n; +} - packet[p] = MESSAGE.CHANNEL_CLOSE; +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; - writeUInt32BE(packet, chan, ++p); + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; - this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelWindowAdjust(chan, amount) { - // Does not consume window space + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4); + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; - packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; - writeUInt32BE(packet, chan, ++p); + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); - writeUInt32BE(packet, amount, p += 4); + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); - this._debug && this._debug( - `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelData(chan, data) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); + return 0; +} - packet[p] = MESSAGE.CHANNEL_DATA; +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); - writeUInt32BE(packet, chan, ++p); + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); - writeUInt32BE(packet, dataLen, p += 4); + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} - this._debug && this._debug( - `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); } - channelExtData(chan, data, type) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); +} - packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} - writeUInt32BE(packet, chan, ++p); +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; - writeUInt32BE(packet, type, p += 4); + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - writeUInt32BE(packet, dataLen, p += 4); + scalarbase(p, d); + pack(pk, p); - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} - this._debug - && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; } - channelOpenConfirm(remote, local, initWindow, maxPacket) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} - packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} - writeUInt32BE(packet, remote, ++p); +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; - writeUInt32BE(packet, local, p += 4); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - writeUInt32BE(packet, initWindow, p += 4); + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - writeUInt32BE(packet, maxPacket, p += 4); + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } } - channelOpenFail(remote, reason, desc) { - if (typeof desc !== 'string') - desc = ''; - const descLen = Buffer.byteLength(desc); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); + modL(sm.subarray(32), x); + return smlen; +} - packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); - writeUInt32BE(packet, remote, ++p); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); - writeUInt32BE(packet, reason, p += 4); + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); - writeUInt32BE(packet, descLen, p += 4); + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); - p += 4; - if (descLen) { - packet.utf8Write(desc, p, descLen); - p += descLen; - } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); - writeUInt32BE(packet, 0, p); // Empty language tag + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== + M(r[3], r[0], r[1]); + return 0; +} - // Global - // ------ - service(name) { - if (this._server) - throw new Error('Client-only method called in server mode'); +function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + nameLen); + mlen = -1; + if (n < 64) return -1; - packet[p] = MESSAGE.SERVICE_REQUEST; + if (unpackneg(q, pk)) return -1; - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); - this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); - sendPacket(this, this._packetRW.write.finalize(packet)); + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; } - // 'ssh-userauth' service-specific - // ------------------------------- - authPassword(username, password, newPassword) { - if (this._server) - throw new Error('Client-only method called in server mode'); + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + mlen = n; + return mlen; +} - const userLen = Buffer.byteLength(username); - const passLen = Buffer.byteLength(password); - const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen - + (newPassword ? 4 + newPassLen : 0) - ); +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; - packet[p] = MESSAGE.USERAUTH_REQUEST; +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES +}; - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); +/* High-level API */ - writeUInt32BE(packet, 8, p += 14); - packet.utf8Write('password', p += 4, 8); +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} - packet[p += 8] = (newPassword ? 1 : 0); +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} - writeUInt32BE(packet, passLen, ++p); - if (Buffer.isBuffer(password)) - bufferCopy(password, packet, 0, passLen, p += 4); - else - packet.utf8Write(password, p += 4, passLen); +function checkArrayTypes() { + var t, i; + for (i = 0; i < arguments.length; i++) { + if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') + throw new TypeError('unexpected type ' + t + ', use Uint8Array'); + } +} - if (newPassword) { - writeUInt32BE(packet, newPassLen, p += passLen); - if (Buffer.isBuffer(newPassword)) - bufferCopy(newPassword, packet, 0, newPassLen, p += 4); - else - packet.utf8Write(newPassword, p += 4, newPassLen); - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (changed password)' - ); - } else { - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (password)' - ); - } +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} - this._authsQueue.push('password'); +// TODO: Completely remove this in v0.15. +if (!nacl.util) { + nacl.util = {}; + nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { + throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); + }; +} - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPK(username, pubKey, cbSign) { - if (this._server) - throw new Error('Client-only method called in server mode'); +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return false; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyType); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const payloadLen = - (cbSign ? 4 + sesLen : 0) - + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; - let packet; - let p; - if (cbSign) { - packet = Buffer.allocUnsafe(payloadLen); - p = 0; - writeUInt32BE(packet, sesLen, p); - packet.set(sessionID, p += 4); - p += sesLen; - } else { - packet = this._packetRW.write.alloc(payloadLen); - p = this._packetRW.write.allocStart; - } +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - packet[p] = MESSAGE.USERAUTH_REQUEST; +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; - packet[p += 9] = (cbSign ? 1 : 0); +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyType, p += 4, algoLen); +nacl.box.after = nacl.secretbox; - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; - if (!cbSign) { - this._authsQueue.push('publickey'); +nacl.box.open.after = nacl.secretbox.open; - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - return; - } +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; - cbSign(packet, (signature) => { - signature = convertSignature(signature, keyType); - if (signature === false) - throw new Error('Error while converting handshake signature'); +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; - const sigLen = signature.length; - p = this._packetRW.write.allocStart; - packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 - + 4 + algoLen + 4 + sigLen - ); +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; - // TODO: simply copy from original "packet" to new `packet` to avoid - // having to write each individual field a second time? - packet[p] = MESSAGE.USERAUTH_REQUEST; +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); +nacl.sign.open = function(signedMsg, publicKey) { + if (arguments.length !== 2) + throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; - packet[p += 9] = 1; +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyType, p += 4, algoLen); +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyType, p += 4, algoLen); +nacl.hash.hashLength = crypto_hash_BYTES; - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; - // Servers shouldn't send packet type 60 in response to signed publickey - // attempts, but if they do, interpret as type 60. - this._authsQueue.push('publickey'); +nacl.setPRNG = function(fn) { + randombytes = fn; +}; - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); }); + } else if (true) { + // Node.js. + crypto = __nccwpck_require__(6113); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } } - authHostbased(username, pubKey, hostname, userlocal, cbSign) { - // TODO: Make DRY by sharing similar code with authPK() - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); +})(); - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyType); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const hostnameLen = Buffer.byteLength(hostname); - const userlocalLen = Buffer.byteLength(userlocal); - const data = Buffer.allocUnsafe( - 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen - + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen - ); - let p = 0; +})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); - writeUInt32BE(data, sesLen, p); - data.set(sessionID, p += 4); - data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; +/***/ }), - writeUInt32BE(data, userLen, ++p); - data.utf8Write(username, p += 4, userLen); +/***/ 1773: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(data, 14, p += userLen); - data.utf8Write('ssh-connection', p += 4, 14); +"use strict"; - writeUInt32BE(data, 9, p += 14); - data.utf8Write('hostbased', p += 4, 9); - writeUInt32BE(data, algoLen, p += 9); - data.utf8Write(keyType, p += 4, algoLen); +const Client = __nccwpck_require__(3598) +const Dispatcher = __nccwpck_require__(412) +const errors = __nccwpck_require__(8045) +const Pool = __nccwpck_require__(4634) +const BalancedPool = __nccwpck_require__(7931) +const Agent = __nccwpck_require__(7890) +const util = __nccwpck_require__(3983) +const { InvalidArgumentError } = errors +const api = __nccwpck_require__(4059) +const buildConnector = __nccwpck_require__(2067) +const MockClient = __nccwpck_require__(8687) +const MockAgent = __nccwpck_require__(6771) +const MockPool = __nccwpck_require__(6193) +const mockErrors = __nccwpck_require__(888) +const ProxyAgent = __nccwpck_require__(7858) +const RetryHandler = __nccwpck_require__(2286) +const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(1892) +const DecoratorHandler = __nccwpck_require__(6930) +const RedirectHandler = __nccwpck_require__(2860) +const createRedirectInterceptor = __nccwpck_require__(8861) + +let hasCrypto +try { + __nccwpck_require__(6113) + hasCrypto = true +} catch { + hasCrypto = false +} - writeUInt32BE(data, pubKeyLen, p += algoLen); - data.set(pubKey, p += 4); +Object.assign(Dispatcher.prototype, api) - writeUInt32BE(data, hostnameLen, p += pubKeyLen); - data.utf8Write(hostname, p += 4, hostnameLen); +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent +module.exports.RetryHandler = RetryHandler - writeUInt32BE(data, userlocalLen, p += hostnameLen); - data.utf8Write(userlocal, p += 4, userlocalLen); +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor - cbSign(data, (signature) => { - signature = convertSignature(signature, keyType); - if (!signature) - throw new Error('Error while converting handshake signature'); +module.exports.buildConnector = buildConnector +module.exports.errors = errors - const sigLen = signature.length; - const reqDataLen = (data.length - sesLen - 4); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - reqDataLen + 4 + 4 + algoLen + 4 + sigLen - ); +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } - bufferCopy(data, packet, 4 + sesLen, data.length, p); + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyType, p += 4, algoLen); - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - this._authsQueue.push('hostbased'); + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (hostbased)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authKeyboard(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 - ); + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } - packet[p] = MESSAGE.USERAUTH_REQUEST; + url = util.parseURL(url) + } - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); + const { agent, dispatcher = getGlobalDispatcher() } = opts - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } - writeUInt32BE(packet, 20, p += 14); - packet.utf8Write('keyboard-interactive', p += 4, 20); + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } +} - writeUInt32BE(packet, 0, p += 20); +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher - writeUInt32BE(packet, 0, p += 4); +if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { + let fetchImpl = null + module.exports.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = (__nccwpck_require__(4881).fetch) + } - this._authsQueue.push('keyboard-interactive'); + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) + } - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + throw err + } } - authNone(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); + module.exports.Headers = __nccwpck_require__(554).Headers + module.exports.Response = __nccwpck_require__(7823).Response + module.exports.Request = __nccwpck_require__(8359).Request + module.exports.FormData = __nccwpck_require__(2015).FormData + module.exports.File = __nccwpck_require__(8511).File + module.exports.FileReader = __nccwpck_require__(1446).FileReader - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); + const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1246) - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin - writeUInt32BE(packet, 4, p += 14); - packet.utf8Write('none', p += 4, 4); + const { CacheStorage } = __nccwpck_require__(7907) + const { kConstruct } = __nccwpck_require__(9174) - this._authsQueue.push('none'); + // Cache & CacheStorage are tightly coupled with fetch. Even if it may run + // in an older version of Node, it doesn't have any use without fetch. + module.exports.caches = new CacheStorage(kConstruct) +} - this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoRes(responses) { - if (this._server) - throw new Error('Client-only method called in server mode'); +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(1724) - let responsesTotalLen = 0; - let responseLens; + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie - if (responses) { - responseLens = new Array(responses.length); - for (let i = 0; i < responses.length; ++i) { - const len = Buffer.byteLength(responses[i]); - responseLens[i] = len; - responsesTotalLen += 4 + len; - } - } + const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType +} - packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = __nccwpck_require__(4284) - if (responses) { - writeUInt32BE(packet, responses.length, ++p); - p += 4; - for (let i = 0; i < responses.length; ++i) { - const len = responseLens[i]; - writeUInt32BE(packet, len, p); - p += 4; - if (len) { - packet.utf8Write(responses[i], p, len); - p += len; - } - } - } else { - writeUInt32BE(packet, 0, ++p); - } + module.exports.WebSocket = WebSocket +} - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) - // 'ssh-connection' service-specific - // --------------------------------- - tcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); - packet[p] = MESSAGE.GLOBAL_REQUEST; +/***/ }), - writeUInt32BE(packet, 13, ++p); - packet.utf8Write('tcpip-forward', p += 4, 13); +/***/ 7890: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); +"use strict"; - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - writeUInt32BE(packet, bindPort, p += addrLen); +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(2785) +const DispatcherBase = __nccwpck_require__(4839) +const Pool = __nccwpck_require__(4634) +const Client = __nccwpck_require__(3598) +const util = __nccwpck_require__(3983) +const createRedirectInterceptor = __nccwpck_require__(8861) +const { WeakRef, FinalizationRegistry } = __nccwpck_require__(6436)() - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - cancelTcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kMaxRedirections = Symbol('maxRedirections') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kFinalizer = Symbol('finalizer') +const kOptions = Symbol('options') - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} - packet[p] = MESSAGE.GLOBAL_REQUEST; +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super() - writeUInt32BE(packet, 20, ++p); - packet.utf8Write('cancel-tcpip-forward', p += 4, 20); + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } - packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } - writeUInt32BE(packet, bindPort, p += addrLen); + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_streamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); + this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 31 + 1 + 4 + socketPathLen - ); + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kMaxRedirections] = maxRedirections + this[kFactory] = factory + this[kClients] = new Map() + this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { + const ref = this[kClients].get(key) + if (ref !== undefined && ref.deref() === undefined) { + this[kClients].delete(key) + } + }) - packet[p] = MESSAGE.GLOBAL_REQUEST; + const agent = this - writeUInt32BE(packet, 31, ++p); - packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) + } - packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) + } - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } } - openssh_cancelStreamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 38 + 1 + 4 + socketPathLen - ); - packet[p] = MESSAGE.GLOBAL_REQUEST; + get [kRunning] () { + let ret = 0 + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore next: gc is undeterministic */ + if (client) { + ret += client[kRunning] + } + } + return ret + } - writeUInt32BE(packet, 38, ++p); - packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } - packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); + const ref = this[kClients].get(key) - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); + let dispatcher = ref ? ref.deref() : null + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST ' - + '(cancel-streamlocal-forward@openssh.com)' - ); + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) } - sendPacket(this, this._packetRW.write.finalize(packet)); + + return dispatcher.dispatch(opts, handler) } - directTcpip(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - const srcLen = Buffer.byteLength(cfg.srcIP); - const dstLen = Buffer.byteLength(cfg.dstIP); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 - ); + async [kClose] () { + const closePromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + closePromises.push(client.close()) + } + } - packet[p] = MESSAGE.CHANNEL_OPEN; + await Promise.all(closePromises) + } - writeUInt32BE(packet, 12, ++p); - packet.utf8Write('direct-tcpip', p += 4, 12); + async [kDestroy] (err) { + const destroyPromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + destroyPromises.push(client.destroy(err)) + } + } - writeUInt32BE(packet, chan, p += 12); + await Promise.all(destroyPromises) + } +} - writeUInt32BE(packet, initWindow, p += 4); +module.exports = Agent - writeUInt32BE(packet, maxPacket, p += 4); - writeUInt32BE(packet, dstLen, p += 4); - packet.utf8Write(cfg.dstIP, p += 4, dstLen); +/***/ }), - writeUInt32BE(packet, cfg.dstPort, p += dstLen); +/***/ 7032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(packet, srcLen, p += 4); - packet.utf8Write(cfg.srcIP, p += 4, srcLen); +const { addAbortListener } = __nccwpck_require__(3983) +const { RequestAbortedError } = __nccwpck_require__(8045) - writeUInt32BE(packet, cfg.srcPort, p += srcLen); +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) } - openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 30, ++p); - packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); +} - writeUInt32BE(packet, chan, p += 30); +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null - writeUInt32BE(packet, initWindow, p += 4); + if (!signal) { + return + } - writeUInt32BE(packet, maxPacket, p += 4); + if (signal.aborted) { + abort(self) + return + } - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } - // zero-fill reserved fields (string and uint32) - bufferFill(packet, 0, p += pathLen, p + 8); + addAbortListener(self[kSignal], self[kListener]) +} - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, direct-streamlocal@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); +function removeSignal (self) { + if (!self[kSignal]) { + return } - openssh_noMoreSessions(wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } - packet[p] = MESSAGE.GLOBAL_REQUEST; + self[kSignal] = null + self[kListener] = null +} - writeUInt32BE(packet, 28, ++p); - packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); +module.exports = { + addSignal, + removeSignal +} - packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - session(chan, initWindow, maxPacket) { - if (this._server) - throw new Error('Client-only method called in server mode'); +/***/ }), - // Does not consume window space +/***/ 9744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); +"use strict"; - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 7, ++p); - packet.utf8Write('session', p += 4, 7); +const { AsyncResource } = __nccwpck_require__(852) +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { addSignal, removeSignal } = __nccwpck_require__(7032) - writeUInt32BE(packet, chan, p += 7); +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - writeUInt32BE(packet, initWindow, p += 4); + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - writeUInt32BE(packet, maxPacket, p += 4); + const { signal, opaque, responseHeaders } = opts - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - windowChange(chan, rows, cols, height, width) { - if (this._server) - throw new Error('Client-only method called in server mode'); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - // Does not consume window space + super('UNDICI_CONNECT') - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 - ); + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null - packet[p] = MESSAGE.CHANNEL_REQUEST; + addSignal(this, signal) + } - writeUInt32BE(packet, chan, ++p); + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - writeUInt32BE(packet, 13, p += 4); - packet.utf8Write('window-change', p += 4, 13); + this.abort = abort + this.context = context + } - packet[p += 13] = 0; + onHeaders () { + throw new SocketError('bad connect', null) + } - writeUInt32BE(packet, cols, ++p); + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this - writeUInt32BE(packet, rows, p += 4); + removeSignal(this) - writeUInt32BE(packet, width, p += 4); + this.callback = null - writeUInt32BE(packet, height, p += 4); + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) } - pty(chan, rows, cols, height, width, term, modes, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - // Does not consume window space + onError (err) { + const { callback, opaque } = this - if (!term || !term.length) - term = 'vt100'; - if (modes - && !Buffer.isBuffer(modes) - && !Array.isArray(modes) - && typeof modes === 'object' - && modes !== null) { - modes = modesToBytes(modes); + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - if (!modes || !modes.length) - modes = NO_TERMINAL_MODES_BUFFER; + } +} - const termLen = term.length; - const modesLen = modes.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen - ); +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - packet[p] = MESSAGE.CHANNEL_REQUEST; + try { + const connectHandler = new ConnectHandler(opts, callback) + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} - writeUInt32BE(packet, chan, ++p); +module.exports = connect - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('pty-req', p += 4, 7); - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); +/***/ }), - writeUInt32BE(packet, termLen, ++p); - packet.utf8Write(term, p += 4, termLen); +/***/ 8752: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(packet, cols, p += termLen); +"use strict"; - writeUInt32BE(packet, rows, p += 4); - writeUInt32BE(packet, width, p += 4); +const { + Readable, + Duplex, + PassThrough +} = __nccwpck_require__(2781) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) +const assert = __nccwpck_require__(9491) - writeUInt32BE(packet, height, p += 4); +const kResume = Symbol('resume') - writeUInt32BE(packet, modesLen, p += 4); - p += 4; - if (Array.isArray(modes)) { - for (let i = 0; i < modesLen; ++i) - packet[p++] = modes[i]; - } else if (Buffer.isBuffer(modes)) { - packet.set(modes, p); - } +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); + this[kResume] = null } - shell(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - // Does not consume window space + _read () { + const { [kResume]: resume } = this - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); + if (resume) { + this[kResume] = null + resume() + } + } - packet[p] = MESSAGE.CHANNEL_REQUEST; + _destroy (err, callback) { + this._read() - writeUInt32BE(packet, chan, ++p); + callback(err) + } +} - writeUInt32BE(packet, 5, p += 4); - packet.utf8Write('shell', p += 4, 5); +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } - packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); + _read () { + this[kResume]() + } - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); - sendPacket(this, this._packetRW.write.finalize(packet)); + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + callback(err) } - exec(chan, cmd, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +} - // Does not consume window space +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - const isBuf = Buffer.isBuffer(cmd); - const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } - packet[p] = MESSAGE.CHANNEL_REQUEST; + const { signal, method, opaque, onInfo, responseHeaders } = opts - writeUInt32BE(packet, chan, ++p); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - writeUInt32BE(packet, 4, p += 4); - packet.utf8Write('exec', p += 4, 4); + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } - writeUInt32BE(packet, cmdLen, ++p); - if (isBuf) - packet.set(cmd, p += 4); - else - packet.utf8Write(cmd, p += 4, cmdLen); + super('UNDICI_PIPELINE') - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - signal(chan, signal) { - if (this._server) - throw new Error('Client-only method called in server mode'); + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null - // Does not consume window space + this.req = new PipelineRequest().on('error', util.nop) - const origSignal = signal; + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this - signal = signal.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); + if (body && body.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this - const signalLen = signal.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 6 + 1 + 4 + signalLen - ); + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } - packet[p] = MESSAGE.CHANNEL_REQUEST; + if (abort && err) { + abort() + } - writeUInt32BE(packet, chan, ++p); + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) - writeUInt32BE(packet, 6, p += 4); - packet.utf8Write('signal', p += 4, 6); + removeSignal(this) - packet[p += 6] = 0; + callback(err) + } + }).on('prefinish', () => { + const { req } = this - writeUInt32BE(packet, signalLen, ++p); - packet.utf8Write(signal, p += 4, signalLen); + // Node < 15 does not call _final in same tick. + req.push(null) + }) - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - env(chan, key, val, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); + this.res = null - // Does not consume window space + addSignal(this, signal) + } - const keyLen = Buffer.byteLength(key); - const isBuf = Buffer.isBuffer(val); - const valLen = (isBuf ? val.length : Buffer.byteLength(val)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen - ); + onConnect (abort, context) { + const { ret, res } = this - packet[p] = MESSAGE.CHANNEL_REQUEST; + assert(!res, 'pipeline cannot be retried') - writeUInt32BE(packet, chan, ++p); + if (ret.destroyed) { + throw new RequestAbortedError() + } - writeUInt32BE(packet, 3, p += 4); - packet.utf8Write('env', p += 4, 3); + this.abort = abort + this.context = context + } - packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this - writeUInt32BE(packet, keyLen, ++p); - packet.utf8Write(key, p += 4, keyLen); + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } - writeUInt32BE(packet, valLen, p += keyLen); - if (isBuf) - packet.set(val, p += 4); - else - packet.utf8Write(val, p += 4, valLen); + this.res = new PipelineResponse(resume) - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11Forward(chan, cfg, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', util.nop) + throw err + } - // Does not consume window space + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } - const protocol = cfg.protocol; - const cookie = cfg.cookie; - const isBufProto = Buffer.isBuffer(protocol); - const protoLen = (isBufProto - ? protocol.length - : Buffer.byteLength(protocol)); - const isBufCookie = Buffer.isBuffer(cookie); - const cookieLen = (isBufCookie - ? cookie.length - : Buffer.byteLength(cookie)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 - ); + body + .on('data', (chunk) => { + const { ret, body } = this - packet[p] = MESSAGE.CHANNEL_REQUEST; + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this - writeUInt32BE(packet, chan, ++p); + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('x11-req', p += 4, 7); + ret.push(null) + }) + .on('close', () => { + const { ret } = this - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) - packet[++p] = (cfg.single ? 1 : 0); + this.body = body + } - writeUInt32BE(packet, protoLen, ++p); - if (isBufProto) - packet.set(protocol, p += 4); - else - packet.utf8Write(protocol, p += 4, protoLen); + onData (chunk) { + const { res } = this + return res.push(chunk) + } - writeUInt32BE(packet, cookieLen, p += protoLen); - if (isBufCookie) - packet.set(cookie, p += 4); - else - packet.latin1Write(cookie, p += 4, cookieLen); + onComplete (trailers) { + const { res } = this + res.push(null) + } - writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) } - subsystem(chan, name, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +} - // Does not consume window space - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); +module.exports = pipeline - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); +/***/ }), - writeUInt32BE(packet, 9, p += 4); - packet.utf8Write('subsystem', p += 4, 9); +/***/ 5448: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); +"use strict"; - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_agentForward(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +const Readable = __nccwpck_require__(3858) +const { + InvalidArgumentError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - // Does not consume window space + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - packet[p] = MESSAGE.CHANNEL_REQUEST; + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } - writeUInt32BE(packet, chan, ++p); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - writeUInt32BE(packet, 26, p += 4); - packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_REQUEST ' - + `(r:${chan}, auth-agent-req@openssh.com)` - ); + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.throwOnError = throwOnError + this.highWaterMark = highWaterMark + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) } - sendPacket(this, this._packetRW.write.finalize(packet)); + + addSignal(this, signal) } - openssh_hostKeysProve(keys) { - if (this._server) - throw new Error('Client-only method called in server mode'); - let keysTotal = 0; - const publicKeys = []; - for (const key of keys) { - const publicKey = key.getPublicSSH(); - keysTotal += 4 + publicKey.length; - publicKeys.push(publicKey); + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() } - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); - - packet[p] = MESSAGE.GLOBAL_REQUEST; + this.abort = abort + this.context = context + } - writeUInt32BE(packet, 29, ++p); - packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this - packet[p += 29] = 1; // want reply + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - ++p; - for (const buf of publicKeys) { - writeUInt32BE(packet, buf.length, p); - bufferCopy(buf, packet, 0, buf.length, p += 4); - p += buf.length; + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return } - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' - ); + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const body = new Readable({ resume, abort, contentType, highWaterMark }) + + this.callback = null + this.res = body + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body, contentType, statusCode, statusMessage, headers } + ) + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body, + context + }) + } } - sendPacket(this, this._packetRW.write.finalize(packet)); } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - - // Global - // ------ - serviceAccept(svcName) { - if (!this._server) - throw new Error('Server-only method called in client mode'); + onData (chunk) { + const { res } = this + return res.push(chunk) + } - const svcNameLen = Buffer.byteLength(svcName); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); + onComplete (trailers) { + const { res } = this - packet[p] = MESSAGE.SERVICE_ACCEPT; + removeSignal(this) - writeUInt32BE(packet, svcNameLen, ++p); - packet.utf8Write(svcName, p += 4, svcNameLen); + util.parseHeaders(trailers, this.trailers) - this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); - sendPacket(this, this._packetRW.write.finalize(packet)); + res.push(null) + } - if (this._server && this._banner && svcName === 'ssh-userauth') { - const banner = this._banner; - this._banner = undefined; // Prevent banner from being displayed again - const bannerLen = Buffer.byteLength(banner); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); + onError (err) { + const { res, callback, body, opaque } = this - packet[p] = MESSAGE.USERAUTH_BANNER; + removeSignal(this) - writeUInt32BE(packet, bannerLen, ++p); - packet.utf8Write(banner, p += 4, bannerLen); + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } - writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } - this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); - sendPacket(this, this._packetRW.write.finalize(packet)); + if (body) { + this.body = null + util.destroy(body, err) } } - // 'ssh-connection' service-specific - forwardedTcpip(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const boundAddrLen = Buffer.byteLength(cfg.boundAddr); - const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 - ); +} - packet[p] = MESSAGE.CHANNEL_OPEN; +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - writeUInt32BE(packet, 15, ++p); - packet.utf8Write('forwarded-tcpip', p += 4, 15); + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} - writeUInt32BE(packet, chan, p += 15); +module.exports = request +module.exports.RequestHandler = RequestHandler - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); +/***/ }), - writeUInt32BE(packet, boundAddrLen, p += 4); - packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); +/***/ 5395: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); +"use strict"; - writeUInt32BE(packet, remoteAddrLen, p += 4); - packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); - writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); +const { finished, PassThrough } = __nccwpck_require__(2781) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts - const addrLen = Buffer.byteLength(cfg.originAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 - ); + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - packet[p] = MESSAGE.CHANNEL_OPEN; + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } - writeUInt32BE(packet, 3, ++p); - packet.utf8Write('x11', p += 4, 3); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - writeUInt32BE(packet, chan, p += 3); + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - writeUInt32BE(packet, initWindow, p += 4); + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } - writeUInt32BE(packet, maxPacket, p += 4); + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + this.throwOnError = throwOnError || false + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } - writeUInt32BE(packet, addrLen, p += 4); - packet.utf8Write(cfg.originAddr, p += 4, addrLen); + addSignal(this, signal) + } - writeUInt32BE(packet, cfg.originPort, p += addrLen); + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + this.abort = abort + this.context = context } - openssh_authAgent(chan, initWindow, maxPacket) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this - packet[p] = MESSAGE.CHANNEL_OPEN; + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - writeUInt32BE(packet, 22, ++p); - packet.utf8Write('auth-agent@openssh.com', p += 4, 22); + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } - writeUInt32BE(packet, chan, p += 22); + this.factory = null - writeUInt32BE(packet, initWindow, p += 4); + let res - writeUInt32BE(packet, maxPacket, p += 4); + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + if (factory === null) { + return + } - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 - ); + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) - packet[p] = MESSAGE.CHANNEL_OPEN; + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } - writeUInt32BE(packet, 33, ++p); - packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this - writeUInt32BE(packet, chan, p += 33); + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } - writeUInt32BE(packet, initWindow, p += 4); + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) - writeUInt32BE(packet, maxPacket, p += 4); + if (err) { + abort() + } + }) + } - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); + res.on('drain', resume) - writeUInt32BE(packet, 0, p += pathLen); + this.res = res - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, forwarded-streamlocal@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain + + return needDrain !== true } - exitStatus(chan, status) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - // Does not consume window space - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); + onData (chunk) { + const { res } = this - packet[p] = MESSAGE.CHANNEL_REQUEST; + return res ? res.write(chunk) : true + } - writeUInt32BE(packet, chan, ++p); + onComplete (trailers) { + const { res } = this - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-status', p += 4, 11); + removeSignal(this) - packet[p += 11] = 0; + if (!res) { + return + } - writeUInt32BE(packet, status, ++p); + this.trailers = util.parseHeaders(trailers) - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + res.end() } - exitSignal(chan, name, coreDumped, msg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - // Does not consume window space + onError (err) { + const { res, callback, opaque, body } = this - const origSignal = name; + removeSignal(this) - if (typeof origSignal !== 'string' || !origSignal) - throw new Error(`Invalid signal: ${origSignal}`); + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} - let signal = name.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); +module.exports = stream - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - const nameLen = Buffer.byteLength(signal); - const msgLen = (msg ? Buffer.byteLength(msg) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 - ); +/***/ }), - packet[p] = MESSAGE.CHANNEL_REQUEST; +/***/ 6923: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(packet, chan, ++p); +"use strict"; - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-signal', p += 4, 11); - packet[p += 11] = 0; +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) +const { AsyncResource } = __nccwpck_require__(852) +const util = __nccwpck_require__(3983) +const { addSignal, removeSignal } = __nccwpck_require__(7032) +const assert = __nccwpck_require__(9491) - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(signal, p += 4, nameLen); +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - packet[p += nameLen] = (coreDumped ? 1 : 0); + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - writeUInt32BE(packet, msgLen, ++p); + const { signal, opaque, responseHeaders } = opts - p += 4; - if (msgLen) { - packet.utf8Write(msg, p, msgLen); - p += msgLen; + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } - writeUInt32BE(packet, 0, p); + super('UNDICI_UPGRADE') - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) } - // 'ssh-userauth' service-specific - authFailure(authMethods, isPartial) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - let methods; + this.abort = abort + this.context = null + } - if (typeof authMethods === 'boolean') { - isPartial = authMethods; - authMethods = undefined; - } + onHeaders () { + throw new SocketError('bad upgrade', null) + } - if (authMethods) { - methods = []; - for (let i = 0; i < authMethods.length; ++i) { - if (authMethods[i].toLowerCase() === 'none') - continue; - methods.push(authMethods[i]); - } - methods = methods.join(','); - } else { - methods = ''; - } + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this - const methodsLen = methods.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); + assert.strictEqual(statusCode, 101) - packet[p] = MESSAGE.USERAUTH_FAILURE; + removeSignal(this) - writeUInt32BE(packet, methodsLen, ++p); - packet.utf8Write(methods, p += 4, methodsLen); + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } - packet[p += methodsLen] = (isPartial === true ? 1 : 0); + onError (err) { + const { callback, opaque } = this - this._authsQueue.shift(); + removeSignal(this) - this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } } - authSuccess() { - if (!this._server) - throw new Error('Server-only method called in client mode'); +} - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} - packet[p] = MESSAGE.USERAUTH_SUCCESS; +module.exports = upgrade - this._authsQueue.shift(); - this._authenticated = true; - this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); +/***/ }), - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - } - authPKOK(keyAlgo, key) { - if (!this._server) - throw new Error('Server-only method called in client mode'); +/***/ 4059: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') - throw new Error('"publickey" auth not in progress'); +"use strict"; - // TODO: support parsed key for `key` - const keyAlgoLen = Buffer.byteLength(keyAlgo); - const keyLen = key.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); +module.exports.request = __nccwpck_require__(5448) +module.exports.stream = __nccwpck_require__(5395) +module.exports.pipeline = __nccwpck_require__(8752) +module.exports.upgrade = __nccwpck_require__(6923) +module.exports.connect = __nccwpck_require__(9744) - packet[p] = MESSAGE.USERAUTH_PK_OK; - writeUInt32BE(packet, keyAlgoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); +/***/ }), - writeUInt32BE(packet, keyLen, p += keyAlgoLen); - packet.set(key, p += 4); +/***/ 3858: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._authsQueue.shift(); +"use strict"; +// Ported from https://github.com/nodejs/undici/pull/907 - this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPasswdChg(prompt) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - const promptLen = Buffer.byteLength(prompt); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); - packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; +const assert = __nccwpck_require__(9491) +const { Readable } = __nccwpck_require__(2781) +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3983) - writeUInt32BE(packet, promptLen, ++p); - packet.utf8Write(prompt, p += 4, promptLen); +let Blob - writeUInt32BE(packet, 0, p += promptLen); // Empty language tag +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') - this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoReq(name, instructions, prompts) { - if (!this._server) - throw new Error('Server-only method called in client mode'); +const noop = () => {} - let promptsLen = 0; - const nameLen = name ? Buffer.byteLength(name) : 0; - const instrLen = instructions ? Buffer.byteLength(instructions) : 0; +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) - for (let i = 0; i < prompts.length; ++i) - promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; + this._readableState.dataEmitted = false - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen - ); + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType - packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false + } - writeUInt32BE(packet, nameLen, ++p); - p += 4; - if (name) { - packet.utf8Write(name, p, nameLen); - p += nameLen; + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this } - writeUInt32BE(packet, instrLen, p); - p += 4; - if (instructions) { - packet.utf8Write(instructions, p, instrLen); - p += instrLen; + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() } - writeUInt32BE(packet, 0, p); - - writeUInt32BE(packet, prompts.length, p += 4); - p += 4; - for (let i = 0; i < prompts.length; ++i) { - const prompt = prompts[i]; - const promptLen = Buffer.byteLength(prompt.prompt); - - writeUInt32BE(packet, promptLen, p); - p += 4; - if (promptLen) { - packet.utf8Write(prompt.prompt, p, promptLen); - p += promptLen; - } - packet[p++] = (prompt.echo ? 1 : 0); + if (err) { + this[kAbort]() } - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); - sendPacket(this, this._packetRW.write.finalize(packet)); + return super.destroy(err) } -} -// SSH-protoversion-softwareversion (SP comments) CR LF -const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; + emit (ev, ...args) { + if (ev === 'data') { + // Node < 16.7 + this._readableState.dataEmitted = true + } else if (ev === 'error') { + // Node < 16 + this._readableState.errorEmitted = true + } + return super.emit(ev, ...args) + } -// TODO: optimize this by starting n bytes from the end of this._buffer instead -// of the beginning -function parseHeader(chunk, p, len) { - let data; - let chunkOffset; - if (this._buffer) { - data = Buffer.allocUnsafe(this._buffer.length + (len - p)); - data.set(this._buffer, 0); - if (p === 0) { - data.set(chunk, this._buffer.length); - } else { - data.set(new Uint8Array(chunk.buffer, - chunk.byteOffset + p, - (len - p)), - this._buffer.length); + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true } - chunkOffset = this._buffer.length; - p = 0; - } else { - data = chunk; - chunkOffset = 0; + return super.on(ev, ...args) } - const op = p; - let start = p; - let end = p; - let needNL = false; - let lineLen = 0; - let lines = 0; - for (; p < data.length; ++p) { - const ch = data[p]; - if (ch === 13 /* '\r' */) { - needNL = true; - continue; + addListener (ev, ...args) { + return this.on(ev, ...args) + } + + off (ev, ...args) { + const ret = super.off(ev, ...args) + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) } + return ret + } - if (ch === 10 /* '\n' */) { - if (end > start - && end - start > 4 - && data[start] === 83 /* 'S' */ - && data[start + 1] === 83 /* 'S' */ - && data[start + 2] === 72 /* 'H' */ - && data[start + 3] === 45 /* '-' */) { + removeListener (ev, ...args) { + return this.off(ev, ...args) + } - const full = data.latin1Slice(op, end + 1); - const identRaw = (start === op ? full : full.slice(start - op)); - const m = RE_IDENT.exec(identRaw); - if (!m) - throw new Error('Invalid identification string'); + push (chunk) { + if (this[kConsume] && chunk !== null && this.readableLength === 0) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } - const header = { - greeting: (start === op ? '' : full.slice(0, start - op)), - identRaw, - versions: { - protocol: m[1], - software: m[2], - }, - comments: m[3] - }; + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } - // Needed during handshake - this._remoteIdentRaw = Buffer.from(identRaw); + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } - this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); - this._compatFlags = getCompatFlags(header); + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } - this._buffer = undefined; - this._decipher = - new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); - this._parse = parsePacket; + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } - this._onHeader(header); - if (!this._destruct) { - // We disconnected inside _onHeader - return len; - } + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } - kexinit(this); + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } - return p + 1 - chunkOffset; + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) } + } + return this[kBody] + } - // Only allow pre-ident greetings when we're a client - if (this._server) - throw new Error('Greetings from clients not permitted'); + dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal - if (++lines > MAX_LINES) - throw new Error('Max greeting lines exceeded'); + if (signal) { + try { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + util.throwIfAborted(signal) + } catch (err) { + return Promise.reject(err) + } + } - needNL = false; - start = p + 1; - lineLen = 0; - } else if (needNL) { - throw new Error('Invalid header: expected newline'); - } else if (++lineLen >= MAX_LINE_LEN) { - throw new Error('Header line too long'); + if (this.closed) { + return Promise.resolve(null) } - end = p; - } - if (!this._buffer) - this._buffer = bufferSlice(data, op); + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal + ? util.addAbortListener(signal, () => { + this.destroy() + }) + : noop - return p - chunkOffset; + this + .on('close', function () { + signalListenerCleanup() + if (signal && signal.aborted) { + reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) + } else { + resolve(null) + } + }) + .on('error', noop) + .on('data', function (chunk) { + limit -= chunk.length + if (limit <= 0) { + this.destroy() + } + }) + .resume() + }) + } } -function parsePacket(chunk, p, len) { - return this._decipher.decrypt(chunk, p, len); +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] } -function onPayload(payload) { - // XXX: move this to the Decipher implementations? - - this._onPacket(); +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') } - payload = this._packetRW.read.read(payload); + assert(!stream[kConsume]) - const type = payload[0]; - if (type === MESSAGE.USERAUTH_SUCCESS - && !this._server - && !this._authenticated) { - this._authenticated = true; - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - } - const handler = MESSAGE_HANDLERS[type]; - if (handler === undefined) { - this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); - return; - } + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } - return handler(this, payload); + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + process.nextTick(consumeStart, stream[kConsume]) + }) } -function getCompatFlags(header) { - const software = header.versions.software; +function consumeStart (consume) { + if (consume.body === null) { + return + } - let flags = 0; + const { _readableState: state } = consume.stream - for (const rule of COMPAT_CHECKS) { - if (typeof rule[0] === 'string') { - if (software === rule[0]) - flags |= rule[1]; - } else if (rule[0].test(software)) { - flags |= rule[1]; - } + for (const chunk of state.buffer) { + consumePush(consume, chunk) } - return flags; + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } + + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop + } } -function modesToBytes(modes) { - const keys = Object.keys(modes); - const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); - let b = 0; +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === 'TTY_OP_END') - continue; + try { + if (type === 'text') { + resolve(toUSVString(Buffer.concat(body))) + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))) + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length) - const opcode = TERMINAL_MODE[key]; - if (opcode === undefined) - continue; + let pos = 0 + for (const buf of body) { + dst.set(buf, pos) + pos += buf.byteLength + } - const val = modes[key]; - if (typeof val === 'number' && isFinite(val)) { - bytes[b++] = opcode; - bytes[b++] = val >>> 24; - bytes[b++] = val >>> 16; - bytes[b++] = val >>> 8; - bytes[b++] = val; + resolve(dst.buffer) + } else if (type === 'blob') { + if (!Blob) { + Blob = (__nccwpck_require__(4300).Blob) + } + resolve(new Blob(body, { type: stream[kContentType] })) } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) } +} - bytes[b++] = TERMINAL_MODE.TTY_OP_END; +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} - if (b < bytes.length) - return bufferSlice(bytes, 0, b); +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } - return bytes; -} + if (err) { + consume.reject(err) + } else { + consume.resolve() + } -module.exports = Protocol; + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} /***/ }), -/***/ 2026: +/***/ 7474: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -const EventEmitter = __nccwpck_require__(2361); -const fs = __nccwpck_require__(7147); -const { constants } = fs; -const { - Readable: ReadableStream, - Writable: WritableStream -} = __nccwpck_require__(2781); -const { inherits, isDate } = __nccwpck_require__(3837); - -const FastBuffer = Buffer[Symbol.species]; - +const assert = __nccwpck_require__(9491) const { - bufferCopy, - bufferSlice, - makeBufferParser, - writeUInt32BE, -} = __nccwpck_require__(9475); - -const ATTR = { - SIZE: 0x00000001, - UIDGID: 0x00000002, - PERMISSIONS: 0x00000004, - ACMODTIME: 0x00000008, - EXTENDED: 0x80000000, -}; - -// Large enough to store all possible attributes -const ATTRS_BUF = Buffer.alloc(28); + ResponseStatusCodeError +} = __nccwpck_require__(8045) +const { toUSVString } = __nccwpck_require__(3983) -const STATUS_CODE = { - OK: 0, - EOF: 1, - NO_SUCH_FILE: 2, - PERMISSION_DENIED: 3, - FAILURE: 4, - BAD_MESSAGE: 5, - NO_CONNECTION: 6, - CONNECTION_LOST: 7, - OP_UNSUPPORTED: 8 -}; +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) -const VALID_STATUS_CODES = new Map( - Object.values(STATUS_CODE).map((n) => [n, 1]) -); + let chunks = [] + let limit = 0 -const STATUS_CODE_STR = { - [STATUS_CODE.OK]: 'No error', - [STATUS_CODE.EOF]: 'End of file', - [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', - [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', - [STATUS_CODE.FAILURE]: 'Failure', - [STATUS_CODE.BAD_MESSAGE]: 'Bad message', - [STATUS_CODE.NO_CONNECTION]: 'No connection', - [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', - [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', -}; + for await (const chunk of body) { + chunks.push(chunk) + limit += chunk.length + if (limit > 128 * 1024) { + chunks = null + break + } + } -const REQUEST = { - INIT: 1, - OPEN: 3, - CLOSE: 4, - READ: 5, - WRITE: 6, - LSTAT: 7, - FSTAT: 8, - SETSTAT: 9, - FSETSTAT: 10, - OPENDIR: 11, - READDIR: 12, - REMOVE: 13, - MKDIR: 14, - RMDIR: 15, - REALPATH: 16, - STAT: 17, - RENAME: 18, - READLINK: 19, - SYMLINK: 20, - EXTENDED: 200 -}; + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return + } -const RESPONSE = { - VERSION: 2, - STATUS: 101, - HANDLE: 102, - DATA: 103, - NAME: 104, - ATTRS: 105, - EXTENDED: 201 -}; + try { + if (contentType.startsWith('application/json')) { + const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } -const OPEN_MODE = { - READ: 0x00000001, - WRITE: 0x00000002, - APPEND: 0x00000004, - CREAT: 0x00000008, - TRUNC: 0x00000010, - EXCL: 0x00000020 -}; + if (contentType.startsWith('text/')) { + const payload = toUSVString(Buffer.concat(chunks)) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + } catch (err) { + // Process in a fallback if error + } -const PKT_RW_OVERHEAD = 2 * 1024; -const MAX_REQID = 2 ** 32 - 1; -const CLIENT_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - REQUEST.INIT, - 0, 0, 0, 3 /* version */ -]); -const SERVER_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - RESPONSE.VERSION, - 0, 0, 0, 3 /* version */ -]); + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) +} -const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; -const OPENSSH_MAX_PKT_LEN = 256 * 1024; +module.exports = { getResolveErrorBodyCallback } -const bufferParser = makeBufferParser(); -const fakeStderr = { - readable: false, - writable: false, - push: (data) => {}, - once: () => {}, - on: () => {}, - emit: () => {}, - end: () => {}, -}; +/***/ }), -function noop() {} +/***/ 7931: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Emulates enough of `Channel` to be able to be used as a drop-in replacement -// in order to process incoming data with as little overhead as possible -class SFTP extends EventEmitter { - constructor(client, chanInfo, cfg) { - super(); +"use strict"; - if (typeof cfg !== 'object' || !cfg) - cfg = {}; - const remoteIdentRaw = client._protocol._remoteIdentRaw; +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = __nccwpck_require__(8045) +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = __nccwpck_require__(3198) +const Pool = __nccwpck_require__(4634) +const { kUrl, kInterceptors } = __nccwpck_require__(2785) +const { parseOrigin } = __nccwpck_require__(3983) +const kFactory = Symbol('factory') - this.server = !!cfg.server; - this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') - this._version = -1; - this._extensions = {}; - this._biOpt = cfg.biOpt; - this._pktLenBytes = 0; - this._pktLen = 0; - this._pktPos = 0; - this._pktType = 0; - this._pktData = undefined; - this._writeReqid = -1; - this._requests = {}; - this._maxInPktLen = OPENSSH_MAX_PKT_LEN; - this._maxOutPktLen = 34000; - this._maxReadLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - this._maxWriteLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} - this.maxOpenHandles = undefined; +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} - // Channel compatibility - this._client = client; - this._protocol = client._protocol; - this._callbacks = []; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - this._waitWindow = false; // SSH-level backpressure - this._chunkcb = undefined; - this._buffer = []; - this.type = chanInfo.type; - this.subtype = undefined; - this.incoming = chanInfo.incoming; - this.outgoing = chanInfo.outgoing; - this.stderr = fakeStderr; - this.readable = true; - } +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() - // This handles incoming data to parse - push(data) { - if (data === null) { - cleanupRequests(this); - if (!this.readable) - return; - // No more incoming data from the remote side - this.readable = false; - this.emit('end'); - return; + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] } - /* - uint32 length - byte type - byte[length - 1] data payload - */ - let p = 0; - while (p < data.length) { - if (this._pktLenBytes < 4) { - let nb = Math.min(4 - this._pktLenBytes, data.length - p); - this._pktLenBytes += nb; + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } - while (nb--) - this._pktLen = (this._pktLen << 8) + data[p++]; + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory - if (this._pktLenBytes < 4) - return; - if (this._pktLen === 0) - return doFatalSFTPError(this, 'Invalid packet length'); - if (this._pktLen > this._maxInPktLen) { - const max = this._maxInPktLen; - return doFatalSFTPError( - this, - `Packet length ${this._pktLen} exceeds max length of ${max}` - ); - } - if (p >= data.length) - return; - } - if (this._pktPos < this._pktLen) { - const nb = Math.min(this._pktLen - this._pktPos, data.length - p); - if (p !== 0 || nb !== data.length) { - if (nb === this._pktLen) { - this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._pktPos - ); - } - } else if (nb === this._pktLen) { - this._pkt = data; - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set(data, this._pktPos); - } - p += nb; - this._pktPos += nb; - if (this._pktPos < this._pktLen) - return; - } + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } - const type = this._pkt[0]; - const payload = this._pkt; + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - // Prepare for next packet - this._pktLen = 0; - this._pktLenBytes = 0; - this._pkt = undefined; - this._pktPos = 0; + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) - const handler = (this.server - ? SERVER_HANDLERS[type] - : CLIENT_HANDLERS[type]); - if (!handler) - return doFatalSFTPError(this, `Unknown packet type ${type}`); + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) - if (this._version === -1) { - if (this.server) { - if (type !== REQUEST.INIT) - return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); - } else if (type !== RESPONSE.VERSION) { - return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); - } + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() } + }) - if (handler(this, payload) === false) - return; + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] } - } - end() { - this.destroy(); - } - destroy() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._protocol.channelClose(this.outgoing.id); - } + this._updateBalancedPoolStats() + + return this } - _init() { - this._init = noop; - if (!this.server) - sendOrBuffer(this, CLIENT_VERSION_BUFFER); + + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) } - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - createReadStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - return new ReadStream(this, path, options); + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) + } + + return this } - createWriteStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - return new WriteStream(this, path, options); + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) } - open(path, flags_, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() } - const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); - if (flags === null) - throw new Error(`Unknown flags string: ${flags_}`); + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) - let attrsFlags = 0; - let attrsLen = 0; - if (typeof attrs === 'string' || typeof attrs === 'number') - attrs = { mode: attrs }; - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - attrsFlags = attrs.flags; - attrsLen = attrs.nb; + if (!dispatcher) { + return } - /* - uint32 id - string filename - uint32 pflags - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPEN; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + if (allClientsBusy) { + return + } - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - writeUInt32BE(buf, attrsFlags, p += 4); - if (attrsLen) { - p += 4; + let counter = 0 - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) - p += attrsLen; + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } } - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` - ); + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] } - close(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +} - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); +module.exports = BalancedPool - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.CLOSE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +/***/ }), - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); +/***/ 6101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._requests[reqid] = { cb }; +"use strict"; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` - ); - } - read(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off >= buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - read_(this, handle, buf, off, len, position, cb); - } - readData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.read(handle, buf, off, len, position, cb); - } - write(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +const { kConstruct } = __nccwpck_require__(9174) +const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(2396) +const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3983) +const { kHeadersList } = __nccwpck_require__(2785) +const { webidl } = __nccwpck_require__(1744) +const { Response, cloneResponse } = __nccwpck_require__(7823) +const { Request } = __nccwpck_require__(8359) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const { fetching } = __nccwpck_require__(4881) +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(2538) +const assert = __nccwpck_require__(9491) +const { getGlobalDispatcher } = __nccwpck_require__(1892) - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off > buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../types/cache').CacheQueryOptions} options + */ - if (!len) { - cb && process.nextTick(cb, undefined, 0); - return; - } +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ - const maxDataLen = this._maxWriteLen; - const overflow = Math.max(len - maxDataLen, 0); - const origPosition = position; +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList - if (overflow) - len = maxDataLen; + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() + } - /* - uint32 id - string handle - uint64 offset - string data - */ - const handleLen = handle.length; - let p = 9; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); + this.#relevantRequestResponseList = arguments[1] + } - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.WRITE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = position & 0xFF; - position /= 256; - } - writeUInt32BE(out, len, p += 8); - bufferCopy(buf, out, off, off + len, p += 4); + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - this._requests[reqid] = { - cb: (err) => { - if (err) { - if (typeof cb === 'function') - cb(err); - } else if (overflow) { - this.write(handle, - buf, - off + len, - overflow, - origPosition + len, - cb); - } else if (typeof cb === 'function') { - cb(undefined, off + len); - } - } - }; + const p = await this.matchAll(request, options) - const isSent = sendOrBuffer(this, out); - if (this._debug) { - const how = (isSent ? 'Sent' : 'Buffered'); - this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); + if (p.length === 0) { + return } - } - writeData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.write(handle, buf, off, len, position, cb); - } - fastGet(remotePath, localPath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(this, fs, remotePath, localPath, opts, cb); - } - fastPut(localPath, remotePath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - fastXfer(fs, this, localPath, remotePath, opts, cb); + return p[0] } - readFile(path, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) - if (typeof options === 'string') - options = { encoding: options, flag: 'r' }; - else if (!options) - options = { encoding: null, flag: 'r' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - const encoding = options.encoding; - if (encoding && !Buffer.isEncoding(encoding)) - throw new Error(`Unknown encoding: ${encoding}`); + // 1. + let r = null - // First stat the file, so we know the size. - let size; - let buffer; // Single buffer with file data - let buffers; // List for when size is unknown - let pos = 0; - let handle; + // 2. + if (request !== undefined) { + if (request instanceof Request) { + // 2.1.1 + r = request[kState] - // SFTPv3 does not support using -1 for read position, so we have to track - // read position manually - let bytesRead = 0; + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = new Request(request)[kState] + } + } - const flag = options.flag || 'r'; + // 5. + // 5.1 + const responses = [] - const read = () => { - if (size === 0) { - buffer = Buffer.allocUnsafe(8192); - this.read(handle, buffer, 0, 8192, bytesRead, afterRead); - } else { - this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]) } - }; + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) - const afterRead = (er, nbytes) => { - let eof; - if (er) { - eof = (er.code === STATUS_CODE.EOF); - if (!eof) { - return this.close(handle, () => { - return callback && callback(er); - }); - } - } else { - eof = false; + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) } + } - if (eof || (size === 0 && nbytes === 0)) - return close(); + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! - bytesRead += nbytes; - pos += nbytes; - if (size !== 0) { - if (pos === size) - close(); - else - read(); - } else { - // Unknown size, just read until we don't get bytes. - buffers.push(bufferSlice(buffer, 0, nbytes)); - read(); - } - }; - afterRead._wantEOFError = true; + // 5.5.1 + const responseList = [] - const close = () => { - this.close(handle, (er) => { - if (size === 0) { - // Collect the data into the buffers list. - buffer = Buffer.concat(buffers, pos); - } else if (pos < size) { - buffer = bufferSlice(buffer, 0, pos); - } + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = new Response(response.body?.source ?? null) + const body = responseObject[kState].body + responseObject[kState] = response + responseObject[kState].body = body + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' - if (encoding) - buffer = buffer.toString(encoding); - return callback && callback(er, buffer); - }); - }; + responseList.push(responseObject) + } - this.open(path, flag, 0o666, (er, handle_) => { - if (er) - return callback && callback(er); - handle = handle_; + // 6. + return Object.freeze(responseList) + } - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } + async add (request) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) - size = st.size || 0; - if (size === 0) { - // The kernel lies about many files. - // Go ahead and try to read some bytes. - buffers = []; - return read(); - } + request = webidl.converters.RequestInfo(request) - buffer = Buffer.allocUnsafe(size); - read(); - }; - this.fstat(handle, tryStat); - }); + // 1. + const requests = [request] + + // 2. + const responseArrayPromise = this.addAll(requests) + + // 3. + return await responseArrayPromise } - writeFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; + async addAll (requests) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) + + requests = webidl.converters['sequence'](requests) + + // 1. + const responsePromises = [] + + // 2. + const requestList = [] + + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = request[kState] + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme when method is not GET.' + }) + } } - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'w' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] - if (options.encoding && !Buffer.isEncoding(options.encoding)) - throw new Error(`Unknown encoding: ${options.encoding}`); + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] - const flag = options.flag || 'w'; - this.open(path, flag, options.mode, (openErr, handle) => { - if (openErr) { - callback && callback(openErr); - } else { - const buffer = (Buffer.isBuffer(data) - ? data - : Buffer.from('' + data, options.encoding || 'utf8')); - const position = (/a/.test(flag) ? null : 0); + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme.' + }) + } - // SFTPv3 does not support the notion of 'current position' - // (null position), so we just attempt to append to the end of the file - // instead - if (position === null) { - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' + + // 5.5 + requestList.push(r) + + // 5.6 + const responsePromise = createDeferredPromise() + + // 5.7 + fetchControllers.push(fetching({ + request: r, + dispatcher: getGlobalDispatcher(), + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })) + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')) + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })) + + for (const controller of fetchControllers) { + controller.abort() } - tryStat(null, st_); - }); - return; + + return + } } - writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); - }; - this.fstat(handle, tryStat); - return; + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } + + // 2. + responsePromise.resolve(response) } - writeAll(this, handle, buffer, 0, buffer.length, position, callback); + })) + + // 5.8 + responsePromises.push(responsePromise.promise) + } + + // 6. + const p = Promise.all(responsePromises) + + // 7. + const responses = await p + + // 7.1 + const operations = [] + + // 7.2 + let index = 0 + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 } - }); - } - appendFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; + operations.push(operation) // 7.3.5 + + index++ // 7.3.6 } - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'a' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); + // 7.5 + const cacheJobPromise = createDeferredPromise() - if (!options.flag) - options = Object.assign({ flag: 'a' }, options); - this.writeFile(path, data, options, callback); - } - exists(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 7.6.1 + let errorData = null - this.stat(path, (err) => { - cb && cb(err ? false : true); - }); + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) + + // 7.7 + return cacheJobPromise.promise } - unlink(filename, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - /* - uint32 id - string filename - */ - const fnameLen = Buffer.byteLength(filename); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); + async put (request, response) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REMOVE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + request = webidl.converters.RequestInfo(request) + response = webidl.converters.Response(response) - writeUInt32BE(buf, fnameLen, p); - buf.utf8Write(filename, p += 4, fnameLen); + // 1. + let innerRequest = null - this._requests[reqid] = { cb }; + // 2. + if (request instanceof Request) { + innerRequest = request[kState] + } else { // 3. + innerRequest = new Request(request)[kState] + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` - ); - } - rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Expected an http/s scheme when method is not GET' + }) + } - /* - uint32 id - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); + // 5. + const innerResponse = response[kState] - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RENAME; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) + } - writeUInt32BE(buf, oldLen, p); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) - this._requests[reqid] = { cb }; + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` - ); - } - mkdir(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Response body is locked or disturbed' + }) + } - let flags = 0; - let attrsLen = 0; + // 9. + const clonedResponse = cloneResponse(innerResponse) - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; + // 10. + const bodyReadPromise = createDeferredPromise() + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream + + // 11.2 + const reader = stream.getReader() + + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) } - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. } - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); + // 17. + operations.push(operation) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.MKDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 19. + const bytes = await bodyReadPromise.promise - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + // 19.1 + const cacheJobPromise = createDeferredPromise() - p += attrsLen; + // 19.2.1 + let errorData = null + + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e } - this._requests[reqid] = { cb }; + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } + }) - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` - ); + return cacheJobPromise.promise } - rmdir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RMDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + /** + * @type {Request} + */ + let r = null - this._requests[reqid] = { cb }; + if (request instanceof Request) { + r = request[kState] - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` - ); - } - readdir(where, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string') - if (typeof opts === 'function') { - cb = opts; - opts = {}; + r = new Request(request)[kState] } - if (typeof opts !== 'object' || opts === null) - opts = {}; - const doFilter = (opts && opts.full ? false : true); + /** @type {CacheBatchOperation[]} */ + const operations = [] - if (!Buffer.isBuffer(where) && typeof where !== 'string') - throw new Error('missing directory handle or path'); + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } - if (typeof where === 'string') { - const entries = []; - let e = 0; + operations.push(operation) - const reread = (err, handle) => { - if (err) - return cb(err); + const cacheJobPromise = createDeferredPromise() - this.readdir(handle, opts, (err, list) => { - const eof = (err && err.code === STATUS_CODE.EOF); + let errorData = null + let requestResponses - if (err && !eof) - return this.close(handle, () => cb(err)); + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } - if (eof) { - return this.close(handle, (err) => { - if (err) - return cb(err); - cb(undefined, entries); - }); - } + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) - for (let i = 0; i < list.length; ++i, ++e) - entries[e] = list[i]; + return cacheJobPromise.promise + } - reread(undefined, handle); - }); - }; - return this.opendir(where, reread); - } + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../types/cache').CacheQueryOptions} options + * @returns {readonly Request[]} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) - /* - uint32 id - string handle - */ - const handleLen = where.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 1. + let r = null - writeUInt32BE(buf, handleLen, p); - buf.set(where, p += 4); + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] - this._requests[reqid] = { - cb: (doFilter - ? (err, list) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } + } - for (let i = list.length - 1; i >= 0; --i) { - if (list[i].filename === '.' || list[i].filename === '..') - list.splice(i, 1); - } + // 4. + const promise = createDeferredPromise() - cb(undefined, list); - } - : cb) - }; + // 5. + // 5.1 + const requests = [] - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` - ); - } - fstat(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } + } - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 5.4.2 + for (const request of requests) { + const requestObject = new Request('https://a') + requestObject[kState] = request + requestObject[kHeaders][kHeadersList] = request.headersList + requestObject[kHeaders][kGuard] = 'immutable' + requestObject[kRealm] = request.client - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); + // 5.4.2.1 + requestList.push(requestObject) + } - this._requests[reqid] = { cb }; + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` - ); + return promise.promise } - stat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.STAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 2. + const backupCache = [...cache] - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + // 3. + const addedItems = [] - this._requests[reqid] = { cb }; + // 4.1 + const resultList = [] - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` - ); - } - lstat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.LSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + // 4.2.4 + let requestResponses - this._requests[reqid] = { cb }; + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` - ); - } - opendir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPENDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 4.2.5.2.1 + cache.splice(idx, 1) + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); + // 4.2.6.2 + const r = operation.request - this._requests[reqid] = { cb }; + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` - ); - } - setstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } - let flags = 0; - let attrsLen = 0; + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 4.2.6.7.1 + cache.splice(idx, 1) + } - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; + // 4.2.6.8 + cache.push([operation.request, operation.response]) - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } - p += attrsLen; + // 4.2.7 + resultList.push([operation.request, operation.response]) + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 + + // 5.2 + this.#relevantRequestResponseList = backupCache + + // 5.3 + throw e } + } - this._requests[reqid] = { cb }; + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = [] - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` - ); + const storage = targetStorage ?? this.#relevantRequestResponseList + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } + } + + return resultList } - fsetstat(handle, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } - let flags = 0; - let attrsLen = 0; + const queryURL = new URL(requestQuery.url) - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; + const cachedURL = new URL(request.url) + + if (options?.ignoreSearch) { + cachedURL.search = '' + + queryURL.search = '' } - /* - uint32 id - string handle - ATTRS attrs - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - writeUInt32BE(buf, flags, p += handleLen); - if (attrsLen) { - p += 4; + const fieldValues = getFieldValues(response.headersList.get('vary')) + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) - p += attrsLen; + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } } - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` - ); - } - futimes(handle, atime, mtime, cb) { - return this.fsetstat(handle, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - utimes(path, atime, mtime, cb) { - return this.setstat(path, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - fchown(handle, uid, gid, cb) { - return this.fsetstat(handle, { - uid: uid, - gid: gid - }, cb); - } - chown(path, uid, gid, cb) { - return this.setstat(path, { - uid: uid, - gid: gid - }, cb); + return true } - fchmod(handle, mode, cb) { - return this.fsetstat(handle, { - mode: mode - }, cb); +} + +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: false } - chmod(path, mode, cb) { - return this.setstat(path, { - mode: mode - }, cb); +] + +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) + +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString } - readlink(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +]) - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); +webidl.converters.Response = webidl.interfaceConverter(Response) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); +module.exports = { + Cache +} - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing link info')); - cb(undefined, names[0].filename); - } - }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` - ); - } - symlink(targetPath, linkPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +/***/ }), - /* - uint32 id - string linkpath - string targetpath - */ - const linkLen = Buffer.byteLength(linkPath); - const targetLen = Buffer.byteLength(targetPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); +/***/ 7907: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SYMLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +"use strict"; - if (this._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - writeUInt32BE(buf, targetLen, p); - buf.utf8Write(targetPath, p += 4, targetLen); - writeUInt32BE(buf, linkLen, p += targetLen); - buf.utf8Write(linkPath, p += 4, linkLen); - } else { - writeUInt32BE(buf, linkLen, p); - buf.utf8Write(linkPath, p += 4, linkLen); - writeUInt32BE(buf, targetLen, p += linkLen); - buf.utf8Write(targetPath, p += 4, targetLen); - } - this._requests[reqid] = { cb }; +const { kConstruct } = __nccwpck_require__(9174) +const { Cache } = __nccwpck_require__(6101) +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` - ); +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing path info')); - cb(undefined, names[0].filename); + return await cache.match(request, options) } - }; + } else { // 2. + // 2.2 + for (const cacheList of this.#caches.values()) { + const cache = new Cache(kConstruct, cacheList) - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` - ); + // 2.2.1.2 + const response = await cache.match(request, options) + + if (response !== undefined) { + return response + } + } + } } - // extended requests - ext_openssh_rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - const ext = this._extensions['posix-rename@openssh.com']; - if (!ext || ext !== '1') - throw new Error('Server does not support this extended request'); + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-has + * @param {string} cacheName + * @returns {Promise} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) - /* - uint32 id - string "posix-rename@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); + cacheName = webidl.converters.DOMString(cacheName) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } - writeUInt32BE(buf, 24, p); - buf.utf8Write('posix-rename@openssh.com', p += 4, 24); - writeUInt32BE(buf, oldLen, p += 24); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) - this._requests[reqid] = { cb }; + cacheName = webidl.converters.DOMString(cacheName) - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) } + + // 2.2 + const cache = [] + + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) } - ext_openssh_statvfs(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - const ext = this._extensions['statvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) - /* - uint32 id - string "statvfs@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); + cacheName = webidl.converters.DOMString(cacheName) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + return this.#caches.delete(cacheName) + } - writeUInt32BE(buf, 19, p); - buf.utf8Write('statvfs@openssh.com', p += 4, 19); - writeUInt32BE(buf, pathLen, p += 19); - buf.utf8Write(path, p += 4, pathLen); + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) - this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; + // 2.1 + const keys = this.#caches.keys() - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); - } + // 2.2 + return [...keys] } - ext_openssh_fstatvfs(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +} - const ext = this._extensions['fstatvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) - /* - uint32 id - string "fstatvfs@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); +module.exports = { + CacheStorage +} - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 20, p); - buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); - writeUInt32BE(buf, handleLen, p += 20); - buf.set(handle, p += 4); +/***/ }), - this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; +/***/ 9174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); - } - } - ext_openssh_hardlink(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +"use strict"; - const ext = this._extensions['hardlink@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - /* - uint32 id - string "hardlink@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); +module.exports = { + kConstruct: (__nccwpck_require__(2785).kConstruct) +} - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 20, p); - buf.utf8Write('hardlink@openssh.com', p += 4, 20); - writeUInt32BE(buf, oldLen, p += 20); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); +/***/ }), - this._requests[reqid] = { cb }; +/***/ 2396: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); - } - } - ext_openssh_fsync(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +"use strict"; - const ext = this._extensions['fsync@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - /* - uint32 id - string "fsync@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); +const assert = __nccwpck_require__(9491) +const { URLSerializer } = __nccwpck_require__(685) +const { isValidHeaderName } = __nccwpck_require__(2538) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +/** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ +function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment) - writeUInt32BE(buf, 17, p); - buf.utf8Write('fsync@openssh.com', p += 4, 17); - writeUInt32BE(buf, handleLen, p += 17); - buf.set(handle, p += 4); + const serializedB = URLSerializer(B, excludeFragment) - this._requests[reqid] = { cb }; + return serializedA === serializedB +} - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` - ); - } - ext_openssh_lsetstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +/** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ +function fieldValues (header) { + assert(header !== null) - const ext = this._extensions['lsetstat@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); + const values = [] - let flags = 0; - let attrsLen = 0; + for (let value of header.split(',')) { + value = value.trim() - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue } - /* - uint32 id - string "lsetstat@openssh.com" - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); + values.push(value) + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + return values +} - writeUInt32BE(buf, 20, p); - buf.utf8Write('lsetstat@openssh.com', p += 4, 20); +module.exports = { + urlEquals, + fieldValues +} - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; +/***/ }), - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); +/***/ 3598: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - p += attrsLen; - } +"use strict"; +// @ts-check - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); - } + +/* global WebAssembly */ + +const assert = __nccwpck_require__(9491) +const net = __nccwpck_require__(1808) +const http = __nccwpck_require__(3685) +const { pipeline } = __nccwpck_require__(2781) +const util = __nccwpck_require__(3983) +const timers = __nccwpck_require__(9459) +const Request = __nccwpck_require__(2905) +const DispatcherBase = __nccwpck_require__(4839) +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError +} = __nccwpck_require__(8045) +const buildConnector = __nccwpck_require__(2067) +const { + kUrl, + kReset, + kServerName, + kClient, + kBusy, + kParser, + kConnect, + kBlocking, + kResuming, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize, + kHTTPConnVersion, + // HTTP2 + kHost, + kHTTP2Session, + kHTTP2SessionState, + kHTTP2BuildRequest, + kHTTP2CopyHeaders, + kHTTP1BuildRequest +} = __nccwpck_require__(2785) + +/** @type {import('http2')} */ +let http2 +try { + http2 = __nccwpck_require__(5158) +} catch { + // @ts-ignore + http2 = { constants: {} } +} + +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS } - ext_openssh_expandPath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +} = http2 - const ext = this._extensions['expand-path@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); +// Experimental +let h2ExperimentalWarned = false - /* - uint32 id - string "expand-path@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); +const FastBuffer = Buffer[Symbol.species] - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +const kClosedResolve = Symbol('kClosedResolve') - writeUInt32BE(buf, 23, p); - buf.utf8Write('expand-path@openssh.com', p += 4, 23); +const channels = {} - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); +try { + const diagnosticsChannel = __nccwpck_require__(7643) + channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') + channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') + channels.connectError = diagnosticsChannel.channel('undici:client:connectError') + channels.connected = diagnosticsChannel.channel('undici:client:connected') +} catch { + channels.sendHeaders = { hasSubscribers: false } + channels.beforeConnect = { hasSubscribers: false } + channels.connectError = { hasSubscribers: false } + channels.connected = { hasSubscribers: false } +} - this._requests[reqid] = { cb }; +/** + * @type {import('../types/client').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../types/client').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + allowH2, + maxConcurrentStreams + } = {}) { + super() - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') } - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - handle(reqid, handle) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } - const handleLen = handle.length; + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } - if (handleLen > 256) - throw new Error('handle too large (> 256 bytes)'); + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.HANDLE; - writeUInt32BE(buf, reqid, 5); + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } - writeUInt32BE(buf, handleLen, p); - if (handleLen) - buf.set(handle, p += 4); + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` - ); - } - status(reqid, code, message) { - if (!this.server) - throw new Error('Server-only method called in client mode'); + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } - if (!VALID_STATUS_CODES.has(code)) - throw new Error(`Bad status code: ${code}`); + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } - message || (message = ''); + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } - const msgLen = Buffer.byteLength(message); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.STATUS; - writeUInt32BE(buf, reqid, 5); + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } - writeUInt32BE(buf, code, p); + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } - writeUInt32BE(buf, msgLen, p += 4); - p += 4; - if (msgLen) { - buf.utf8Write(message, p, msgLen); - p += msgLen; + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') } - writeUInt32BE(buf, 0, p); // Empty language tag + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` - ); - } - data(reqid, data, encoding) { - if (!this.server) - throw new Error('Server-only method called in client mode'); + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } - const isBuffer = Buffer.isBuffer(data); + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } - if (!isBuffer && typeof data !== 'string') - throw new Error('data is not a Buffer or string'); + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } - let isUTF8; - if (!isBuffer && !encoding) { - encoding = undefined; - isUTF8 = true; + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') } - const dataLen = ( - isBuffer - ? data.length - : Buffer.byteLength(data, encoding) - ); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.DATA; - writeUInt32BE(buf, reqid, 5); + this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) + ? interceptors.Client + : [createRedirectInterceptor({ maxRedirections })] + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kSocket] = null + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRedirections] = maxRedirections + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + this[kHTTPConnVersion] = 'h1' + + // HTTP/2 + this[kHTTP2Session] = null + this[kHTTP2SessionState] = !allowH2 + ? null + : { + // streams: null, // Fixed queue of streams - For future support of `push` + openStreams: 0, // Keep track of them to decide wether or not unref the session + maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + } + this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` - writeUInt32BE(buf, dataLen, p); - if (dataLen) { - if (isBuffer) - buf.set(data, p += 4); - else if (isUTF8) - buf.utf8Write(data, p += 4, dataLen); - else - buf.write(data, p += 4, dataLen, encoding); - } + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` - ); + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 } - name(reqid, names) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - if (!Array.isArray(names)) { - if (typeof names !== 'object' || names === null) - throw new Error('names is not an object or array'); - names = [ names ]; - } + get pipelining () { + return this[kPipelining] + } - const count = names.length; - let namesLen = 0; - let nameAttrs; - const attrs = []; + set pipelining (value) { + this[kPipelining] = value + resume(this, true) + } - for (let i = 0; i < count; ++i) { - const name = names[i]; - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - namesLen += 4 + Buffer.byteLength(filename); - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - namesLen += 4 + Buffer.byteLength(longname); + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } - if (typeof name.attrs === 'object' && name.attrs !== null) { - nameAttrs = attrsToBytes(name.attrs); - namesLen += 4 + nameAttrs.nb; + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } - if (nameAttrs.nb) { - let bytes; + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } - if (nameAttrs.nb === ATTRS_BUF.length) { - bytes = new Uint8Array(ATTRS_BUF); - } else { - bytes = new Uint8Array(nameAttrs.nb); - bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); - } + get [kConnected] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed + } - nameAttrs.bytes = bytes; - } + get [kBusy] () { + const socket = this[kSocket] + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize] >= (this[kPipelining] || 1)) || + this[kPending] > 0 + ) + } - attrs.push(nameAttrs); - } else { - namesLen += 4; - attrs.push(null); - } - } + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.NAME; - writeUInt32BE(buf, reqid, 5); + const request = this[kHTTPConnVersion] === 'h2' + ? Request[kHTTP2BuildRequest](origin, opts, handler) + : Request[kHTTP1BuildRequest](origin, opts, handler) - writeUInt32BE(buf, count, p); + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + process.nextTick(resume, this) + } else { + resume(this, true) + } - p += 4; + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } - for (let i = 0; i < count; ++i) { - const name = names[i]; + return this[kNeedDrain] < 2 + } - { - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - const len = Buffer.byteLength(filename); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(filename, p, len); - p += len; - } + async [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (!this[kSize]) { + resolve(null) + } else { + this[kClosedResolve] = resolve } + }) + } - { - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - const len = Buffer.byteLength(longname); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(longname, p, len); - p += len; - } + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) } - const attr = attrs[i]; - if (attr) { - writeUInt32BE(buf, attr.flags, p); - p += 4; - if (attr.flags && attr.bytes) { - buf.set(attr.bytes, p); - p += attr.nb; + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null } + resolve() + } + + if (this[kHTTP2Session] != null) { + util.destroy(this[kHTTP2Session], err) + this[kHTTP2Session] = null + this[kHTTP2SessionState] = null + } + + if (!this[kSocket]) { + queueMicrotask(callback) } else { - writeUInt32BE(buf, 0, p); - p += 4; + util.destroy(this[kSocket].on('close', callback), err) } - } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` - ); + resume(this) + }) } - attrs(reqid, attrs) { - if (!this.server) - throw new Error('Server-only method called in client mode'); +} - if (typeof attrs !== 'object' || attrs === null) - throw new Error('attrs is not an object'); +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - attrs = attrsToBytes(attrs); - const flags = attrs.flags; - const attrsLen = attrs.nb; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); + this[kSocket][kError] = err - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.ATTRS; - writeUInt32BE(buf, reqid, 5); + onError(this[kClient], err) +} - writeUInt32BE(buf, flags, p); - if (attrsLen) { - p += 4; +function onHttp2FrameError (type, code, id) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + if (id === 0) { + this[kSocket][kError] = err + onError(this[kClient], err) + } +} - p += attrsLen; +function onHttp2SessionEnd () { + util.destroy(this, new SocketError('other side closed')) + util.destroy(this[kSocket], new SocketError('other side closed')) +} + +function onHTTP2GoAway (code) { + const client = this[kClient] + const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) + client[kSocket] = null + client[kHTTP2Session] = null + + if (client.destroyed) { + assert(this[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) } + } else if (client[kRunning] > 0) { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` - ); + errorRequest(client, request, err) } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', + client[kUrl], + [client], + err + ) + + resume(client) } -function tryCreateBuffer(size) { +const constants = __nccwpck_require__(953) +const createRedirectInterceptor = __nccwpck_require__(8861) +const EMPTY_BUF = Buffer.alloc(0) + +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(1145) : undefined + + let mod try { - return Buffer.allocUnsafe(size); - } catch (ex) { - return ex; + mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(5627), 'base64')) + } catch (e) { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(1145), 'base64')) } + + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ + + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageComplete() || 0 + } + + /* eslint-enable camelcase */ + } + }) } -function read_(self, handle, buf, off, len, position, cb, req_) { - const maxDataLen = self._maxReadLen; - const overflow = Math.max(len - maxDataLen, 0); +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() + +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null + +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 + +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) + + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = null + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (value, type) { + this.timeoutType = type + if (value !== this.timeoutValue) { + timers.clearTimeout(this.timeout) + if (value) { + this.timeout = timers.setTimeout(onParserTimeout, value, this) + // istanbul ignore else: only for jest + if (this.timeout.unref) { + this.timeout.unref() + } + } else { + this.timeout = null + } + this.timeoutValue = value + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + } - if (overflow) - len = maxDataLen; + resume () { + if (this.socket.destroyed || !this.paused) { + return + } - /* - uint32 id - string handle - uint64 offset - uint32 len - */ - const handleLen = handle.length; - let p = 9; - let pos = position; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); + assert(this.ptr != null) + assert(currentParser == null) - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.READ; - const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); + this.llhttp.llhttp_resume(this.ptr) - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = pos & 0xFF; - pos /= 256; + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() } - writeUInt32BE(out, len, p += 8); - if (typeof cb !== 'function') - cb = noop; + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } - const req = (req_ || { - nb: 0, - position, - off, - origOff: off, - len: undefined, - overflow: undefined, - cb: (err, data, nb) => { - const len = req.len; - const overflow = req.overflow; + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) - if (err) { - if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) - return cb(err); - } else if (nb > len) { - return cb(new Error('Received more data than requested')); - } else if (nb === len && overflow) { - req.nb += nb; - req.position += nb; - req.off += nb; - read_(self, handle, buf, req.off, overflow, req.position, cb, req); - return; + const { socket, llhttp } = this + + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } - if (req.origOff === 0 && buf.length === req.nb) - data = buf; - else - data = bufferSlice(buf, req.origOff, req.origOff + req.nb); - cb(undefined, req.nb + (nb || 0), data, req.position); - }, - buffer: undefined, - }); + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) - req.len = len; - req.overflow = overflow; + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret - // TODO: avoid creating multiple buffer slices when we need to re-call read_() - // because of overflow - req.buffer = bufferSlice(buf, off, off + len); + try { + currentBufferRef = data + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(data.slice(offset)) + } else if (ret !== constants.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + /* istanbul ignore else: difficult to make a test case for */ + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')' + } + throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) + } + } catch (err) { + util.destroy(socket, err) + } + } - self._requests[reqid] = req; + destroy () { + assert(this.ptr != null) + assert(currentParser == null) - const isBuffered = sendOrBuffer(self, out); - self._debug && self._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` - ); -} + this.llhttp.llhttp_free(this.ptr) + this.ptr = null -function fastXfer(src, dst, srcPath, dstPath, opts, cb) { - let concurrency = 64; - let chunkSize = 32768; - let onstep; - let mode; - let fileSize; + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.concurrency === 'number' - && opts.concurrency > 0 - && !isNaN(opts.concurrency)) { - concurrency = opts.concurrency; + this.paused = false + } + + onStatus (buf) { + this.statusText = buf.toString() + } + + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 } - if (typeof opts.chunkSize === 'number' - && opts.chunkSize > 0 - && !isNaN(opts.chunkSize)) { - chunkSize = opts.chunkSize; + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 } - if (typeof opts.fileSize === 'number' - && opts.fileSize > 0 - && !isNaN(opts.fileSize)) { - fileSize = opts.fileSize; + } + + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } - if (typeof opts.step === 'function') - onstep = opts.step; - if (typeof opts.mode === 'string' || typeof opts.mode === 'number') - mode = modeNum(opts.mode); + this.trackHeader(buf.length) } - // Internal state variables - let fsize; - let pdst = 0; - let total = 0; - let hadError = false; - let srcHandle; - let dstHandle; - let readbuf; - let bufsize = chunkSize * concurrency; + onHeaderValue (buf) { + let len = this.headers.length - function onerror(err) { - if (hadError) - return; + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } - hadError = true; + const key = this.headers[len - 2] + if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { + this.connection += buf.toString() + } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { + this.contentLength += buf.toString() + } - let left = 0; - let cbfinal; + this.trackHeader(buf.length) + } - if (srcHandle || dstHandle) { - cbfinal = () => { - if (--left === 0) - cb(err); - }; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - ++left; - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - ++left; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - src.close(srcHandle, cbfinal); - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - dst.close(dstHandle, cbfinal); - } else { - cb(err); + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) } } - src.open(srcPath, 'r', (err, sourceHandle) => { - if (err) - return onerror(err); + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this - srcHandle = sourceHandle; + assert(upgrade) - if (fileSize === undefined) - src.fstat(srcHandle, tryStat); - else - tryStat(null, { size: fileSize }); + const request = client[kQueue][client[kRunningIdx]] + assert(request) - function tryStat(err, attrs) { - if (err) { - if (src !== fs) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - src.stat(srcPath, (err_, attrs_) => { - if (err_) - return onerror(err); - tryStat(null, attrs_); - }); - return; - } - return onerror(err); - } - fsize = attrs.size; + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') - dst.open(dstPath, 'w', (err, destHandle) => { - if (err) - return onerror(err); + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null - dstHandle = destHandle; + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - if (fsize <= 0) - return onerror(); + socket.unshift(head) - // Use less memory where possible - while (bufsize > fsize) { - if (concurrency === 1) { - bufsize = fsize; - break; - } - bufsize -= chunkSize; - --concurrency; - } + socket[kParser].destroy() + socket[kParser] = null - readbuf = tryCreateBuffer(bufsize); - if (readbuf instanceof Error) - return onerror(readbuf); + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) - if (mode !== undefined) { - dst.fchmod(dstHandle, mode, function tryAgain(err) { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() - // for whatever reason - dst.chmod(dstPath, mode, (err_) => tryAgain()); - return; - } - startReads(); - }); - } else { - startReads(); - } + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) - function onread(err, nb, data, dstpos, datapos, origChunkLen) { - if (err) - return onerror(err); + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } - datapos = datapos || 0; + resume(client) + } - dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this - function writeCb(err) { - if (err) - return onerror(err); + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } - total += nb; - onstep && onstep(total, nb, fsize); + const request = client[kQueue][client[kRunningIdx]] - if (nb < origChunkLen) - return singleRead(datapos, dstpos + nb, origChunkLen - nb); + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } - if (total === fsize) { - dst.close(dstHandle, (err) => { - dstHandle = undefined; - if (err) - return onerror(err); - src.close(srcHandle, (err) => { - srcHandle = undefined; - if (err) - return onerror(err); - cb(); - }); - }); - return; - } + assert(!this.upgrade) + assert(this.statusCode < 200) - if (pdst >= fsize) - return; + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(datapos, pdst, chunk); - pdst += chunk; - } - } + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } - function makeCb(psrc, pdst, chunk) { - return (err, nb, data) => { - onread(err, nb, data, pdst, psrc, chunk); - }; - } + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) - function singleRead(psrc, pdst, chunk) { - src.read(srcHandle, - readbuf, - psrc, - chunk, - pdst, - makeCb(psrc, pdst, chunk)); - } + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) - function startReads() { - let reads = 0; - let psrc = 0; - while (pdst < fsize && reads < concurrency) { - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(psrc, pdst, chunk); - psrc += chunk; - pdst += chunk; - ++reads; - } + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout } - }); + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true } - }); -} -function writeAll(sftp, handle, buffer, offset, length, position, callback_) { - const callback = (typeof callback_ === 'function' ? callback_ : undefined); + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false - sftp.write(handle, - buffer, - offset, - length, - position, - (writeErr, written) => { - if (writeErr) { - return sftp.close(handle, () => { - callback && callback(writeErr); - }); + if (request.aborted) { + return -1 } - if (written === length) { - sftp.close(handle, callback); - } else { - offset += written; - length -= written; - position += written; - writeAll(sftp, handle, buffer, offset, length, position, callback); + + if (request.method === 'HEAD') { + return 1 } - }); -} -class Stats { - constructor(initial) { - this.mode = (initial && initial.mode); - this.uid = (initial && initial.uid); - this.gid = (initial && initial.gid); - this.size = (initial && initial.size); - this.atime = (initial && initial.atime); - this.mtime = (initial && initial.mtime); - this.extended = (initial && initial.extended); - } - isDirectory() { - return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); - } - isFile() { - return ((this.mode & constants.S_IFMT) === constants.S_IFREG); - } - isBlockDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); - } - isCharacterDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); - } - isSymbolicLink() { - return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); - } - isFIFO() { - return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); - } - isSocket() { - return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) + } + + return pause ? constants.ERROR.PAUSED : 0 } -} -function attrsToBytes(attrs) { - let flags = 0; - let nb = 0; + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this - if (typeof attrs === 'object' && attrs !== null) { - if (typeof attrs.size === 'number') { - flags |= ATTR.SIZE; - const val = attrs.size; - // Big Endian - ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 - ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 - ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 - ATTRS_BUF[nb++] = val / 4294967296; // 2**32 - ATTRS_BUF[nb++] = val / 16777216; // 2**24 - ATTRS_BUF[nb++] = val / 65536; // 2**16 - ATTRS_BUF[nb++] = val / 256; // 2**8 - ATTRS_BUF[nb++] = val; + if (socket.destroyed) { + return -1 } - if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { - flags |= ATTR.UIDGID; - const uid = attrs.uid; - const gid = attrs.gid; - // Big Endian - ATTRS_BUF[nb++] = uid >>> 24; - ATTRS_BUF[nb++] = uid >>> 16; - ATTRS_BUF[nb++] = uid >>> 8; - ATTRS_BUF[nb++] = uid; - ATTRS_BUF[nb++] = gid >>> 24; - ATTRS_BUF[nb++] = gid >>> 16; - ATTRS_BUF[nb++] = gid >>> 8; - ATTRS_BUF[nb++] = gid; + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert.strictEqual(this.timeoutType, TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } } - if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { - const mode = modeNum(attrs.mode); - flags |= ATTR.PERMISSIONS; - // Big Endian - ATTRS_BUF[nb++] = mode >>> 24; - ATTRS_BUF[nb++] = mode >>> 16; - ATTRS_BUF[nb++] = mode >>> 8; - ATTRS_BUF[nb++] = mode; + + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 } - if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) - && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { - const atime = toUnixTimestamp(attrs.atime); - const mtime = toUnixTimestamp(attrs.mtime); - flags |= ATTR.ACMODTIME; - // Big Endian - ATTRS_BUF[nb++] = atime >>> 24; - ATTRS_BUF[nb++] = atime >>> 16; - ATTRS_BUF[nb++] = atime >>> 8; - ATTRS_BUF[nb++] = atime; - ATTRS_BUF[nb++] = mtime >>> 24; - ATTRS_BUF[nb++] = mtime >>> 16; - ATTRS_BUF[nb++] = mtime >>> 8; - ATTRS_BUF[nb++] = mtime; + this.bytesRead += buf.length + + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED } - // TODO: extended attributes } - return { flags, nb }; -} + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this -function toUnixTimestamp(time) { - // eslint-disable-next-line no-self-compare - if (typeof time === 'number' && time === time) // Valid, non-NaN number - return time; - if (isDate(time)) - return parseInt(time.getTime() / 1000, 10); - throw new Error(`Cannot parse time: ${time}`); -} + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } -function modeNum(mode) { - // eslint-disable-next-line no-self-compare - if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number - return mode; - if (typeof mode === 'string') - return modeNum(parseInt(mode, 8)); - throw new Error(`Cannot parse mode: ${mode}`); -} + if (upgrade) { + return + } -const stringFlagMap = { - 'r': OPEN_MODE.READ, - 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, - 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL -}; + const request = client[kQueue][client[kRunningIdx]] + assert(request) -function stringToFlags(str) { - const flags = stringFlagMap[str]; - return (flags !== undefined ? flags : null); -} + assert(statusCode >= 100) -const flagsToString = (() => { - const stringFlagMapKeys = Object.keys(stringFlagMap); - return (flags) => { - for (let i = 0; i < stringFlagMapKeys.length; ++i) { - const key = stringFlagMapKeys[i]; - if (stringFlagMap[key] === flags) - return key; - } - return null; - }; -})(); + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' -function readAttrs(biOpt) { - /* - uint32 flags - uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE - uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS - uint32 atime present only if flag SSH_FILEXFER_ACMODTIME - uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME - uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED - string extended_type - string extended_data - ... more extended data (extended_type - extended_data pairs), - so that number of pairs equals extended_count - */ - const flags = bufferParser.readUInt32BE(); - if (flags === undefined) - return; + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - const attrs = new Stats(); - if (flags & ATTR.SIZE) { - const size = bufferParser.readUInt64BE(biOpt); - if (size === undefined) - return; - attrs.size = size; - } + if (statusCode < 200) { + return + } - if (flags & ATTR.UIDGID) { - const uid = bufferParser.readUInt32BE(); - const gid = bufferParser.readUInt32BE(); - if (gid === undefined) - return; - attrs.uid = uid; - attrs.gid = gid; + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + request.onComplete(headers) + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert.strictEqual(client[kRunning], 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(resume, client) + } else { + resume(client) + } } +} - if (flags & ATTR.PERMISSIONS) { - const mode = bufferParser.readUInt32BE(); - if (mode === undefined) - return; - attrs.mode = mode; +function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!parser.paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!parser.paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_IDLE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) } +} - if (flags & ATTR.ACMODTIME) { - const atime = bufferParser.readUInt32BE(); - const mtime = bufferParser.readUInt32BE(); - if (mtime === undefined) - return; - attrs.atime = atime; - attrs.mtime = mtime; +function onSocketReadable () { + const { [kParser]: parser } = this + if (parser) { + parser.readMore() } +} - if (flags & ATTR.EXTENDED) { - const count = bufferParser.readUInt32BE(); - if (count === undefined) - return; - const extended = {}; - for (let i = 0; i < count; ++i) { - const type = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data === undefined) - return; - extended[type] = data; +function onSocketError (err) { + const { [kClient]: client, [kParser]: parser } = this + + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + if (client[kHTTPConnVersion] !== 'h2') { + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete() + return } - attrs.extended = extended; } - return attrs; + this[kError] = err + + onError(this[kClient], err) } -function sendOrBuffer(sftp, payload) { - const ret = tryWritePayload(sftp, payload); - if (ret !== undefined) { - sftp._buffer.push(ret); - return false; +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + assert(client[kSize] === 0) } - return true; } -function tryWritePayload(sftp, payload) { - const outgoing = sftp.outgoing; - if (outgoing.state !== 'open') - return; +function onSocketEnd () { + const { [kParser]: parser, [kClient]: client } = this - if (outgoing.window === 0) { - sftp._waitWindow = true; // XXX: Unnecessary? - return payload; + if (client[kHTTPConnVersion] !== 'h2') { + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return + } } - let ret; - const len = payload.length; - let p = 0; + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} - while (len - p > 0 && outgoing.window > 0) { - const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); - outgoing.window -= actualLen; - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; - } +function onSocketClose () { + const { [kClient]: client, [kParser]: parser } = this - if (p === 0 && actualLen === len) { - sftp._protocol.channelData(sftp.outgoing.id, payload); - } else { - sftp._protocol.channelData(sftp.outgoing.id, - bufferSlice(payload, p, p + actualLen)); + if (client[kHTTPConnVersion] === 'h1' && parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() } - p += actualLen; + this[kParser].destroy() + this[kParser] = null } - if (len - p > 0) { - if (p > 0) - ret = bufferSlice(payload, p, len); - else - ret = payload; // XXX: should never get here? - } + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) - return ret; -} + client[kSocket] = null -function drainBuffer() { - this._chunkcb = undefined; - const buffer = this._buffer; - let i = 0; - while (i < buffer.length) { - const payload = buffer[i]; - const ret = tryWritePayload(this, payload); - if (ret !== undefined) { - if (ret !== payload) - buffer[i] = ret; - if (i > 0) - this._buffer = buffer.slice(i); - return; + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) } - ++i; + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + errorRequest(client, request, err) } - if (i > 0) - this._buffer = []; -} -function doFatalSFTPError(sftp, msg, noDebug) { - const err = new Error(msg); - err.level = 'sftp-protocol'; - if (!noDebug && sftp._debug) - sftp._debug(`SFTP: Inbound: ${msg}`); - sftp.emit('error', err); - sftp.destroy(); - cleanupRequests(sftp); - return false; -} + client[kPendingIdx] = client[kRunningIdx] -function cleanupRequests(sftp) { - const keys = Object.keys(sftp._requests); - if (keys.length === 0) - return; + assert(client[kRunning] === 0) - const reqs = sftp._requests; - sftp._requests = {}; - const err = new Error('No response from server'); - for (let i = 0; i < keys.length; ++i) { - const req = reqs[keys[i]]; - if (typeof req.cb === 'function') - req.cb(err); - } + client.emit('disconnect', client[kUrl], [client], err) + + resume(client) } -function requestLimits(sftp, cb) { - /* - uint32 id - string "limits@openssh.com" - */ - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); + let { host, hostname, protocol, port } = client[kUrl] - writeUInt32BE(buf, 18, p); - buf.utf8Write('limits@openssh.com', p += 4, 18); + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') - sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; + assert(idx !== -1) + const ip = hostname.substring(1, idx) - const isBuffered = sendOrBuffer(sftp, buf); - if (sftp._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); + assert(net.isIP(ip)) + hostname = ip } -} -const CLIENT_HANDLERS = { - [RESPONSE.VERSION]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); + client[kConnecting] = true - const extensions = {}; + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err) + } else { + resolve(socket) + } + }) + }) + + if (client.destroyed) { + util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) + return } - bufferParser.clear(); - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed VERSION packet'); + client[kConnecting] = false - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); + assert(socket) + + const isH2 = socket.alpnProtocol === 'h2' + if (isH2) { + if (!h2ExperimentalWarned) { + h2ExperimentalWarned = true + process.emitWarning('H2 support is experimental, expect them to change at any time.', { + code: 'UNDICI-H2' + }) } - } - sftp._version = version; - sftp._extensions = extensions; + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }) - if (extensions['limits@openssh.com'] === '1') { - return requestLimits(sftp, (err, limits) => { - if (!err) { - if (limits.maxPktLen > 0) - sftp._maxOutPktLen = limits.maxPktLen; - if (limits.maxReadLen > 0) - sftp._maxReadLen = limits.maxReadLen; - if (limits.maxWriteLen > 0) - sftp._maxWriteLen = limits.maxWriteLen; - sftp.maxOpenHandles = ( - limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity - ); - } - sftp.emit('ready'); - }); + client[kHTTPConnVersion] = 'h2' + session[kClient] = client + session[kSocket] = socket + session.on('error', onHttp2SessionError) + session.on('frameError', onHttp2FrameError) + session.on('end', onHttp2SessionEnd) + session.on('goaway', onHTTP2GoAway) + session.on('close', onSocketClose) + session.unref() + + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + } else { + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = null + } + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) } - sftp.emit('ready'); - }, - [RESPONSE.STATUS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - uint32 error/status code - string error message (ISO-10646 UTF-8) - string language tag - */ - const errorCode = bufferParser.readUInt32BE(); - const errorMsg = bufferParser.readString(true); - bufferParser.clear(); + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null - // Note: we avoid checking that the error message and language tag are in - // the packet because there are some broken implementations that incorrectly - // omit them. The language tag in general was never really used amongst ssh - // implementations, so in the case of a missing error message we just - // default to something sensible. + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) - if (sftp._debug) { - const jsonMsg = JSON.stringify(errorMsg); - sftp._debug( - `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` - ); + client[kSocket] = socket + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) } - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') { - if (errorCode === STATUS_CODE.OK) { - req.cb(); - return; - } - const err = new Error(errorMsg - || STATUS_CODE_STR[errorCode] - || 'Unknown status'); - err.code = errorCode; - req.cb(err); + client.emit('connect', client[kUrl], [client]) + } catch (err) { + if (client.destroyed) { + return } - }, - [RESPONSE.HANDLE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - if (handle === undefined) { - if (reqID !== undefined) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) } - sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + errorRequest(client, request, err) + } + } else { + onError(client, err) + } - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') - req.cb(undefined, handle); - }, - [RESPONSE.DATA]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; + client.emit('connectionError', client[kUrl], [client], err) + } + + resume(client) +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } + + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return } - /* - string data - */ - if (req && typeof req.cb === 'function') { - if (req.buffer) { - // We have already pre-allocated space to store the data - const nb = bufferParser.readString(req.buffer); - bufferParser.clear(); + const socket = client[kSocket] - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - req.cb(undefined, req.buffer, nb); - return; + if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true } - } else { - const data = bufferParser.readString(); - bufferParser.clear(); + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } - if (data !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` - ); - req.cb(undefined, data); - return; + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) } } - } else { - const nb = bufferParser.skipString(); - bufferParser.clear(); - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - return; + } + + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) + } else { + emitDrain(client) } + continue } - return doFatalSFTPError(sftp, 'Malformed DATA packet'); - }, - [RESPONSE.NAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; + if (client[kPending] === 0) { + return } - /* - uint32 count - repeats count times: - string filename - string longname - ATTRS attrs - */ - const count = bufferParser.readUInt32BE(); - if (count !== undefined) { - let names = []; - for (let i = 0; i < count; ++i) { - // We are going to assume UTF-8 for filenames despite the SFTPv3 - // spec not specifying an encoding because the specs for newer - // versions of the protocol all explicitly specify UTF-8 for - // filenames - const filename = bufferParser.readString(true); - // `longname` only exists in SFTPv3 and since it typically will - // contain the filename, we assume it is also UTF-8 - const longname = bufferParser.readString(true); + if (client[kRunning] >= (client[kPipelining] || 1)) { + return + } - const attrs = readAttrs(sftp._biOpt); - if (attrs === undefined) { - names = undefined; - break; - } - names.push({ filename, longname, attrs }); + const request = client[kQueue][client[kPendingIdx]] + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return } - if (names !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` - ); - bufferParser.clear(); - if (req && typeof req.cb === 'function') - req.cb(undefined, names); - return; + + client[kServerName] = request.servername + + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return } } - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed NAME packet'); - }, - [RESPONSE.ATTRS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - ATTRS attrs - */ - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs !== undefined) { - sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); - if (req && typeof req.cb === 'function') - req.cb(undefined, attrs); - return; + if (client[kConnecting]) { + return } - return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); - }, - [RESPONSE.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - if (reqID !== undefined) { - const req = sftp._requests[reqID]; - if (req) { - delete sftp._requests[reqID]; - switch (req.extended) { - case 'statvfs@openssh.com': - case 'fstatvfs@openssh.com': { - /* - uint64 f_bsize // file system block size - uint64 f_frsize // fundamental fs block size - uint64 f_blocks // number of blocks (unit f_frsize) - uint64 f_bfree // free blocks in file system - uint64 f_bavail // free blocks for non-root - uint64 f_files // total file inodes - uint64 f_ffree // free file inodes - uint64 f_favail // free file inodes for to non-root - uint64 f_fsid // file system id - uint64 f_flag // bit mask of f_flag values - uint64 f_namemax // maximum filename length - */ - const biOpt = sftp._biOpt; - const stats = { - f_bsize: bufferParser.readUInt64BE(biOpt), - f_frsize: bufferParser.readUInt64BE(biOpt), - f_blocks: bufferParser.readUInt64BE(biOpt), - f_bfree: bufferParser.readUInt64BE(biOpt), - f_bavail: bufferParser.readUInt64BE(biOpt), - f_files: bufferParser.readUInt64BE(biOpt), - f_ffree: bufferParser.readUInt64BE(biOpt), - f_favail: bufferParser.readUInt64BE(biOpt), - f_sid: bufferParser.readUInt64BE(biOpt), - f_flag: bufferParser.readUInt64BE(biOpt), - f_namemax: bufferParser.readUInt64BE(biOpt), - }; - if (stats.f_namemax === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, stats); - return; - } - case 'limits@openssh.com': { - /* - uint64 max-packet-length - uint64 max-read-length - uint64 max-write-length - uint64 max-open-handles - */ - const limits = { - maxPktLen: bufferParser.readUInt64BE(), - maxReadLen: bufferParser.readUInt64BE(), - maxWriteLen: bufferParser.readUInt64BE(), - maxOpenHandles: bufferParser.readUInt64BE(), - }; - if (limits.maxOpenHandles === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, limits); - return; - } - default: - // Unknown extended request - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(); - return; - } - } else { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - return; - } + if (!socket && !client[kHTTP2Session]) { + connect(client) + return } - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); - }, -}; -const SERVER_HANDLERS = { - [REQUEST.INIT]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate INIT packet'); + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return + } - const extensions = {}; + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return } - bufferParser.clear(); - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed INIT packet'); + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received INIT (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); - } + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return } - sendOrBuffer(sftp, SERVER_VERSION_BUFFER); + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } + } +} - sftp._version = version; - sftp._extensions = extensions; - sftp.emit('ready'); - }, - [REQUEST.OPEN]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string filename - uint32 pflags - ATTRS attrs - */ - const filename = bufferParser.readString(true); - const pflags = bufferParser.readUInt32BE(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed OPEN packet'); +function write (client, request) { + if (client[kHTTPConnVersion] === 'h2') { + writeH2(client, client[kHTTP2Session], request) + return + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); + const { body, method, path, host, upgrade, headers, blocking, reset } = request - if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.CLOSE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. - sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) - if (!sftp.emit('CLOSE', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READ]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - uint32 len - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const len = bufferParser.readUInt32BE(); - bufferParser.clear(); + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } - if (len === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READ packet'); + const bodyLength = util.bodyLength(body) - sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); + let contentLength = bodyLength - if (!sftp.emit('READ', reqID, handle, offset, len)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.WRITE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - string data - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const data = bufferParser.readString(); - bufferParser.clear(); + if (contentLength === null) { + contentLength = request.contentLength + } - if (data === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed WRITE packet'); + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. - sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); + contentLength = null + } - if (!sftp.emit('WRITE', reqID, handle, offset, data)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false } - }, - [REQUEST.LSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); + process.emitWarning(new RequestContentLengthMismatchError()) + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); + const socket = client[kSocket] - if (!sftp.emit('LSTAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); + errorRequest(client, request, err || new RequestAbortedError()) - sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) + } - if (!sftp.emit('FSTAT', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.SETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); + if (request.aborted) { + return false + } - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. - sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); + socket[kReset] = true + } - if (!sftp.emit('SETSTAT', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - ATTRS attrs - */ - const handle = bufferParser.readString(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. - if (attrs === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); + socket[kReset] = true + } - sftp._debug && sftp._debug( - `SFTP: Inbound: Received FSETSTAT (id:${reqID})` - ); + if (reset != null) { + socket[kReset] = reset + } - if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.OPENDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); + if (blocking) { + socket[kBlocking] = true + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); + let header = `${method} ${path} HTTP/1.1\r\n` - if (!sftp.emit('OPENDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READDIR packet'); + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); + if (headers) { + header += headers + } - if (!sftp.emit('READDIR', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + /* istanbul ignore else: assertion */ + if (!body || bodyLength === 0) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'latin1') + } + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(body) + socket.uncork() + request.onBodySent(body) + request.onRequestSent() + if (!expectsPayload) { + socket[kReset] = true + } + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) + } else { + writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) } - }, - [REQUEST.REMOVE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); + } else if (util.isStream(body)) { + writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) + } else if (util.isIterable(body)) { + writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) + } else { + assert(false) + } - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); + return true +} - sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); +function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request - if (!sftp.emit('REMOVE', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.MKDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); + let headers + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) + else headers = reqHeaders - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } - if (!sftp.emit('MKDIR', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RMDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); + errorRequest(client, request, err || new RequestAbortedError()) + }) + } catch (err) { + errorRequest(client, request, err) + } - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); + if (request.aborted) { + return false + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream + const h2State = client[kHTTP2SessionState] - if (!sftp.emit('RMDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] + headers[HTTP2_HEADER_METHOD] = method + + if (method === 'CONNECT') { + session.ref() + // we are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }) + + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + }) } - }, - [REQUEST.REALPATH]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref() + }) - sftp._debug && sftp._debug( - `SFTP: Inbound: Received REALPATH (id:${reqID})` - ); + return true + } - if (!sftp.emit('REALPATH', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.STAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed STAT packet'); + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' - sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 - if (!sftp.emit('STAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RENAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string oldpath - string newpath - */ - const oldPath = bufferParser.readString(true); - const newPath = bufferParser.readString(true); - bufferParser.clear(); + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. - if (newPath === undefined) - return doFatalSFTPError(sftp, 'Malformed RENAME packet'); + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) - sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } - if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); + let contentLength = util.bodyLength(body) - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed READLINK packet'); + if (contentLength == null) { + contentLength = request.contentLength + } - sftp._debug && sftp._debug( - `SFTP: Inbound: Received READLINK (id:${reqID})` - ); + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. - if (!sftp.emit('READLINK', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false } - }, - [REQUEST.SYMLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string linkpath - string targetpath - */ - const linkPath = bufferParser.readString(true); - const targetPath = bufferParser.readString(true); - bufferParser.clear(); - if (targetPath === undefined) - return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); + process.emitWarning(new RequestContentLengthMismatchError()) + } - sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } - let handled; - if (sftp._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); - } else { - handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); + session.ref() + + const shouldEndStream = method === 'GET' || method === 'HEAD' + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + stream = session.request(headers, { endStream: shouldEndStream, signal }) + + stream.once('continue', writeBodyH2) + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + writeBodyH2() + } + + // Increment counter as we have new several streams open + ++h2State.openStreams + + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + + if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { + stream.pause() } - if (!handled) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + }) + + stream.once('end', () => { + request.onComplete([]) + }) + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause() } - }, - [REQUEST.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string extended-request - ... any request-specific data ... - */ - const extName = bufferParser.readString(true); - if (extName === undefined) { - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); + }) + + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) { + session.unref() } + }) - let extData; - if (bufferParser.avail()) - extData = bufferParser.readRaw(); - bufferParser.clear(); + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED (id:${reqID})` - ); + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + errorRequest(client, request, err) - if (!sftp.emit('EXTENDED', reqID, extName, extData)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) } - }, -}; + }) -// ============================================================================= -// ReadStream/WriteStream-related ============================================== -// ============================================================================= -const { - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE, - validateNumber -} = __nccwpck_require__(7609); + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) -const kMinPoolSpace = 128; + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) -let pool; -// It can happen that we expect to read a large chunk of data, and reserve -// a large chunk of the pool accordingly, but the read() call only filled -// a portion of it. If a concurrently executing read() then uses the same pool, -// the "reserved" portion cannot be used, so we allow it to be re-used as a -// new pool later. -const poolFragments = []; + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) -function allocNewPool(poolSize) { - if (poolFragments.length > 0) - pool = poolFragments.pop(); - else - pool = Buffer.allocUnsafe(poolSize); - pool.used = 0; -} + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) -// Check the `this.start` and `this.end` of stream. -function checkPosition(pos, name) { - if (!Number.isSafeInteger(pos)) { - validateNumber(pos, name); - if (!Number.isInteger(pos)) - throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); - } - if (pos < 0) - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); -} + return true -function roundUpToMultipleOf8(n) { - return (n + 7) & ~7; // Align to 8 byte boundary. + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body) { + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + stream.cork() + stream.write(body) + stream.uncork() + stream.end() + request.onBodySent(body) + request.onRequestSent() + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ + client, + request, + contentLength, + h2stream: stream, + expectsPayload, + body: body.stream(), + socket: client[kSocket], + header: '' + }) + } else { + writeBlob({ + body, + client, + request, + contentLength, + expectsPayload, + h2stream: stream, + header: '', + socket: client[kSocket] + }) + } + } else if (util.isStream(body)) { + writeStream({ + body, + client, + request, + contentLength, + expectsPayload, + socket: client[kSocket], + h2stream: stream, + header: '' + }) + } else if (util.isIterable(body)) { + writeIterable({ + body, + client, + request, + contentLength, + expectsPayload, + header: '', + h2stream: stream, + socket: client[kSocket] + }) + } else { + assert(false) + } + } } -function ReadStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); +function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') - // A little bit bigger buffer and water marks by default - if (options.highWaterMark === undefined) - options.highWaterMark = 64 * 1024; + if (client[kHTTPConnVersion] === 'h2') { + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(body, err) + util.destroy(h2stream, err) + } else { + request.onRequestSent() + } + } + ) - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. + pipe.on('data', onPipeData) + pipe.once('end', () => { + pipe.removeListener('data', onPipeData) + util.destroy(pipe) + }) - ReadableStream.call(this, options); + function onPipeData (chunk) { + request.onBodySent(chunk) + } - this.path = path; - this.flags = options.flags === undefined ? 'r' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; + return + } - this.start = options.start; - this.end = options.end; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesRead = 0; - this.closed = false; + let finished = false - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) - if (this.start !== undefined) { - checkPosition(this.start, 'start'); + const onData = function (chunk) { + if (finished) { + return + } - this.pos = this.start; + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } } + const onDrain = function () { + if (finished) { + return + } - if (this.end === undefined) { - this.end = Infinity; - } else if (this.end !== Infinity) { - checkPosition(this.end, 'end'); - - if (this.start !== undefined && this.start > this.end) { - throw new ERR_OUT_OF_RANGE( - 'start', - `<= "end" (here: ${this.end})`, - this.start - ); + if (body.resume) { + body.resume() } } + const onAbort = function () { + if (finished) { + return + } + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) + } + const onFinished = function (err) { + if (finished) { + return + } - this.on('end', function() { - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(ReadStream, ReadableStream); + finished = true -ReadStream.prototype.open = function() { - if (this._opening) - return; + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) - this._opening = true; + socket + .off('drain', onDrain) + .off('error', onFinished) - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } } - this.handle = handle; - this.emit('open', handle); - this.emit('ready'); - // Start the flow of data. - this.read(); - }); -}; + writer.destroy(err) -ReadStream.prototype._read = function(n) { - if (!Buffer.isBuffer(this.handle)) - return this.once('open', () => this._read(n)); + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } - // XXX: safe to remove this? - if (this.destroyed) - return; + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) - if (!pool || pool.length - pool.used < kMinPoolSpace) { - // Discard the old pool. - allocNewPool(this.readableHighWaterMark - || this._readableState.highWaterMark); + if (body.resume) { + body.resume() } - // Grab another reference to the pool in the case that while we're - // in the thread pool another read() finishes up the pool, and - // allocates a new one. - const thisPool = pool; - let toRead = Math.min(pool.length - pool.used, n); - const start = pool.used; - - if (this.end !== undefined) - toRead = Math.min(this.end - this.pos + 1, toRead); + socket + .on('drain', onDrain) + .on('error', onFinished) +} - // Already read everything we were supposed to read! - // treat as EOF. - if (toRead <= 0) - return this.push(null); +async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') - // the actual read. - this.sftp.read(this.handle, - pool, - pool.used, - toRead, - this.pos, - (er, bytesRead) => { - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + const isH2 = client[kHTTPConnVersion] === 'h2' + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() } - let b = null; - // Now that we know how much data we have actually read, re-wind the - // 'used' field if we can, and otherwise allow the remainder of our - // reservation to be used as a new pool later. - if (start + toRead === thisPool.used && thisPool === pool) { - thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); + const buffer = Buffer.from(await body.arrayBuffer()) + + if (isH2) { + h2stream.cork() + h2stream.write(buffer) + h2stream.uncork() } else { - // Round down to the next lowest multiple of 8 to ensure the new pool - // fragment start and end positions are aligned to an 8 byte boundary. - const alignedEnd = (start + toRead) & ~7; - const alignedStart = roundUpToMultipleOf8(start + bytesRead); - if (alignedEnd - alignedStart >= kMinPoolSpace) - poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(buffer) + socket.uncork() } - if (bytesRead > 0) { - this.bytesRead += bytesRead; - b = thisPool.slice(start, start + bytesRead); + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true } - // Move the pool positions, and internal position for reading. - this.pos += bytesRead; + resume(client) + } catch (err) { + util.destroy(isH2 ? h2stream : socket, err) + } +} - this.push(b); - }); +async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') - pool.used = roundUpToMultipleOf8(pool.used + toRead); -}; + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } -ReadStream.prototype._destroy = function(err, cb) { - if (this._opening && !Buffer.isBuffer(this.handle)) { - this.once('open', closeStream.bind(null, this, cb, err)); - return; + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain) + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { + await waitForDrain() + } + } + } catch (err) { + h2stream.destroy(err) + } finally { + request.onRequestSent() + h2stream.end() + h2stream + .off('close', onDrain) + .off('drain', onDrain) + } + + return } - closeStream(this, cb, err); - this.handle = null; - this._opening = false; -}; + socket + .on('close', onDrain) + .on('drain', onDrain) -function closeStream(stream, cb, err) { - if (!stream.handle) - return onclose(); + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } - stream.sftp.close(stream.handle, onclose); + if (!writer.write(chunk)) { + await waitForDrain() + } + } - function onclose(er) { - er = er || err; - cb(er); - stream.closed = true; - if (!er) - stream.emit('close'); + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) } } -ReadStream.prototype.close = function(cb) { - this.destroy(null, cb); -}; - -Object.defineProperty(ReadStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); +class AsyncWriter { + constructor ({ socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header -// TODO: add `concurrency` setting to allow more than one in-flight WRITE -// request to server to improve throughput -function WriteStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); + socket[kWriting] = true + } - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this - WritableStream.call(this, options); + if (socket[kError]) { + throw socket[kError] + } - this.path = path; - this.flags = options.flags === undefined ? 'w' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; + if (socket.destroyed) { + return false + } - this.start = options.start; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesWritten = 0; - this.closed = false; + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } - if (this.start !== undefined) { - checkPosition(this.start, 'start'); + process.emitWarning(new RequestContentLengthMismatchError()) + } - this.pos = this.start; - } + socket.cork() - if (options.encoding) - this.setDefaultEncoding(options.encoding); + if (bytesWritten === 0) { + if (!expectsPayload) { + socket[kReset] = true + } - // Node v6.x only - this.on('finish', function() { - if (this._writableState.finalCalled) - return; - if (this.autoClose) - this.destroy(); - }); + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + } + } - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(WriteStream, WritableStream); + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } -WriteStream.prototype._final = function(cb) { - if (this.autoClose) - this.destroy(); - cb(); -}; + this.bytesWritten += len -WriteStream.prototype.open = function() { - if (this._opening) - return; + const ret = socket.write(chunk) - this._opening = true; + socket.uncork() - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; + request.onBodySent(chunk) - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } } - this.handle = handle; + return ret + } - const tryAgain = (err) => { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() for - // whatever reason - this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); - return; - } + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() - // SFTPv3 requires absolute offsets, no matter the open flag used - if (this.flags[0] === 'a') { - const tryStat = (err, st) => { - if (err) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.sftp.stat(this.path, (err_, st_) => { - if (err_) { - this.destroy(); - this.emit('error', err); - return; - } - tryStat(null, st_); - }); - return; - } + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] + } - this.pos = st.size; - this.emit('open', handle); - this.emit('ready'); - }; + if (socket.destroyed) { + return + } - this.sftp.fstat(handle, tryStat); - return; + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + socket.write(`${header}\r\n`, 'latin1') } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1') + } - this.emit('open', handle); - this.emit('ready'); - }; + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } - this.sftp.fchmod(handle, this.mode, tryAgain); - }); -}; + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } -WriteStream.prototype._write = function(data, encoding, cb) { - if (!Buffer.isBuffer(data)) { - const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); - return this.emit('error', err); + resume(client) } - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._write(data, encoding, cb); - }); - } + destroy (err) { + const { socket, client } = this - this.sftp.write(this.handle, - data, - 0, - data.length, - this.pos, - (er, bytes) => { - if (er) { - if (this.autoClose) - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - cb(); - }); + socket[kWriting] = false - this.pos += data.length; -}; + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + util.destroy(socket, err) + } + } +} -WriteStream.prototype._writev = function(data, cb) { - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._writev(data, cb); - }); +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) } +} - const sftp = this.sftp; - const handle = this.handle; - let writesLeft = data.length; +module.exports = Client - const onwrite = (er, bytes) => { - if (er) { - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - if (--writesLeft === 0) - cb(); - }; - // TODO: try to combine chunks to reduce number of requests to the server? - for (let i = 0; i < data.length; ++i) { - const chunk = data[i].chunk; +/***/ }), - sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); - this.pos += chunk.length; +/***/ 6436: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +/* istanbul ignore file: only for Node 12 */ + +const { kConnected, kSize } = __nccwpck_require__(2785) + +class CompatWeakRef { + constructor (value) { + this.value = value } -}; -if (typeof WritableStream.prototype.destroy !== 'function') - WriteStream.prototype.destroy = ReadStream.prototype.destroy; + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} -WriteStream.prototype._destroy = ReadStream.prototype._destroy; -WriteStream.prototype.close = function(cb) { - if (cb) { - if (this.closed) { - process.nextTick(cb); - return; +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer + } + + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) } - this.on('close', cb); } +} - // If we are not autoClosing, we should call - // destroy on 'finish'. - if (!this.autoClose) - this.on('finish', this.destroy.bind(this)); +module.exports = function () { + // FIXME: remove workaround when the Node bug is fixed + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (process.env.NODE_V8_COVERAGE) { + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + } + } + return { + WeakRef: global.WeakRef || CompatWeakRef, + FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer + } +} - this.end(); -}; -// There is no shutdown() for files. -WriteStream.prototype.destroySoon = WriteStream.prototype.end; +/***/ }), -Object.defineProperty(WriteStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); -// ============================================================================= +/***/ 663: +/***/ ((module) => { + +"use strict"; + + +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 module.exports = { - flagsToString, - OPEN_MODE, - SFTP, - Stats, - STATUS_CODE, - stringToFlags, -}; + maxAttributeValueSize, + maxNameValuePairSize +} /***/ }), -/***/ 6832: +/***/ 1724: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const crypto = __nccwpck_require__(6113); +const { parseSetCookie } = __nccwpck_require__(4408) +const { stringify, getHeadersList } = __nccwpck_require__(3121) +const { webidl } = __nccwpck_require__(1744) +const { Headers } = __nccwpck_require__(554) -let cpuInfo; -try { - cpuInfo = __nccwpck_require__(4137)(); -} catch {} +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ -const { bindingAvailable } = __nccwpck_require__(5708); +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) -const eddsaSupported = (() => { - if (typeof crypto.sign === 'function' - && typeof crypto.verify === 'function') { - const key = - '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' - + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; - const data = Buffer.from('a'); - let sig; - let verified; - try { - sig = crypto.sign(null, data, key); - verified = crypto.verify(null, data, key, sig); - } catch {} - return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); - } + webidl.brandCheck(headers, Headers, { strict: false }) - return false; -})(); + const cookie = headers.get('cookie') + const out = {} -const curve25519Supported = (typeof crypto.diffieHellman === 'function' - && typeof crypto.generateKeyPairSync === 'function' - && typeof crypto.createPublicKey === 'function'); + if (!cookie) { + return out + } -const DEFAULT_KEX = [ - // https://tools.ietf.org/html/rfc5656#section-10.1 - 'ecdh-sha2-nistp256', - 'ecdh-sha2-nistp384', - 'ecdh-sha2-nistp521', + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha256', + out[name.trim()] = value.join('=') + } - // https://tools.ietf.org/html/rfc8268 - 'diffie-hellman-group14-sha256', - 'diffie-hellman-group15-sha512', - 'diffie-hellman-group16-sha512', - 'diffie-hellman-group17-sha512', - 'diffie-hellman-group18-sha512', -]; -if (curve25519Supported) { - DEFAULT_KEX.unshift('curve25519-sha256'); - DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); + return out } -const SUPPORTED_KEX = DEFAULT_KEX.concat([ - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha1', - 'diffie-hellman-group14-sha1', // REQUIRED - 'diffie-hellman-group1-sha1', // REQUIRED -]); +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) + webidl.brandCheck(headers, Headers, { strict: false }) -const DEFAULT_SERVER_HOST_KEY = [ - 'ecdsa-sha2-nistp256', - 'ecdsa-sha2-nistp384', - 'ecdsa-sha2-nistp521', - 'rsa-sha2-512', // RFC 8332 - 'rsa-sha2-256', // RFC 8332 - 'ssh-rsa', -]; -if (eddsaSupported) - DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); -const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ - 'ssh-dss', -]); + name = webidl.converters.DOMString(name) + attributes = webidl.converters.DeleteCookieAttributes(attributes) + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} -const DEFAULT_CIPHER = [ - // http://tools.ietf.org/html/rfc5647 - 'aes128-gcm@openssh.com', - 'aes256-gcm@openssh.com', +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) - // http://tools.ietf.org/html/rfc4344#section-4 - 'aes128-ctr', - 'aes192-ctr', - 'aes256-ctr', -]; -if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { - // We know for sure the CPU does not support AES acceleration - if (bindingAvailable) - DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); - else - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { - // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers - // seem to outperform it on x86, but it seems to be faster than CTR ciphers - DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); -} else { - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookies = getHeadersList(headers).cookies + + if (!cookies) { + return [] + } + + // In older versions of undici, cookies is a list of name:value. + return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair)) } -const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ - 'aes256-cbc', - 'aes192-cbc', - 'aes128-cbc', - 'blowfish-cbc', - '3des-cbc', - 'aes128-gcm', - 'aes256-gcm', - // http://tools.ietf.org/html/rfc4345#section-4: - 'arcfour256', - 'arcfour128', +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) - 'cast128-cbc', - 'arcfour', -]); + webidl.brandCheck(headers, Headers, { strict: false }) + cookie = webidl.converters.Cookie(cookie) -const DEFAULT_MAC = [ - 'hmac-sha2-256-etm@openssh.com', - 'hmac-sha2-512-etm@openssh.com', - 'hmac-sha1-etm@openssh.com', - 'hmac-sha2-256', - 'hmac-sha2-512', - 'hmac-sha1', -]; -const SUPPORTED_MAC = DEFAULT_MAC.concat([ - 'hmac-md5', - 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 - 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 - 'hmac-ripemd160', - 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 - 'hmac-md5-96', // first 96 bits of HMAC-MD5 -]); + const str = stringify(cookie) -const DEFAULT_COMPRESSION = [ - 'none', - 'zlib@openssh.com', // ZLIB (LZ77) compression, except - // compression/decompression does not start until after - // successful user authentication - 'zlib', // ZLIB (LZ77) compression -]; -const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ -]); + if (str) { + headers.append('Set-Cookie', stringify(cookie)) + } +} +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + } +]) -const COMPAT = { - BAD_DHGEX: 1 << 0, - OLD_EXIT: 1 << 1, - DYN_RPORT_BUG: 1 << 2, - BUG_DHGEX_LARGE: 1 << 3, -}; +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: [] + } +]) module.exports = { - MESSAGE: { - // Transport layer protocol -- generic (1-19) - DISCONNECT: 1, - IGNORE: 2, - UNIMPLEMENTED: 3, - DEBUG: 4, - SERVICE_REQUEST: 5, - SERVICE_ACCEPT: 6, + getCookies, + deleteCookie, + getSetCookies, + setCookie +} - // Transport layer protocol -- algorithm negotiation (20-29) - KEXINIT: 20, - NEWKEYS: 21, - // Transport layer protocol -- key exchange method-specific (30-49) - KEXDH_INIT: 30, - KEXDH_REPLY: 31, +/***/ }), - KEXDH_GEX_GROUP: 31, - KEXDH_GEX_INIT: 32, - KEXDH_GEX_REPLY: 33, - KEXDH_GEX_REQUEST: 34, +/***/ 4408: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - KEXECDH_INIT: 30, - KEXECDH_REPLY: 31, +"use strict"; - // User auth protocol -- generic (50-59) - USERAUTH_REQUEST: 50, - USERAUTH_FAILURE: 51, - USERAUTH_SUCCESS: 52, - USERAUTH_BANNER: 53, - // User auth protocol -- user auth method-specific (60-79) - USERAUTH_PASSWD_CHANGEREQ: 60, +const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(663) +const { isCTLExcludingHtab } = __nccwpck_require__(3121) +const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685) +const assert = __nccwpck_require__(9491) - USERAUTH_PK_OK: 60, +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } - USERAUTH_INFO_REQUEST: 60, - USERAUTH_INFO_RESPONSE: 61, + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' - // Connection protocol -- generic (80-89) - GLOBAL_REQUEST: 80, - REQUEST_SUCCESS: 81, - REQUEST_FAILURE: 82, + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } - // Connection protocol -- channel-related (90-127) - CHANNEL_OPEN: 90, - CHANNEL_OPEN_CONFIRMATION: 91, - CHANNEL_OPEN_FAILURE: 92, - CHANNEL_WINDOW_ADJUST: 93, - CHANNEL_DATA: 94, - CHANNEL_EXTENDED_DATA: 95, - CHANNEL_EOF: 96, - CHANNEL_CLOSE: 97, - CHANNEL_REQUEST: 98, - CHANNEL_SUCCESS: 99, - CHANNEL_FAILURE: 100 + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: - // Reserved for client protocols (128-191) + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header + } - // Local extensions (192-155) - }, - DISCONNECT_REASON: { - HOST_NOT_ALLOWED_TO_CONNECT: 1, - PROTOCOL_ERROR: 2, - KEY_EXCHANGE_FAILED: 3, - RESERVED: 4, - MAC_ERROR: 5, - COMPRESSION_ERROR: 6, - SERVICE_NOT_AVAILABLE: 7, - PROTOCOL_VERSION_NOT_SUPPORTED: 8, - HOST_KEY_NOT_VERIFIABLE: 9, - CONNECTION_LOST: 10, - BY_APPLICATION: 11, - TOO_MANY_CONNECTIONS: 12, - AUTH_CANCELED_BY_USER: 13, - NO_MORE_AUTH_METHODS_AVAILABLE: 14, - ILLEGAL_USER_NAME: 15, - }, - DISCONNECT_REASON_STR: undefined, - CHANNEL_OPEN_FAILURE: { - ADMINISTRATIVELY_PROHIBITED: 1, - CONNECT_FAILED: 2, - UNKNOWN_CHANNEL_TYPE: 3, - RESOURCE_SHORTAGE: 4 - }, - TERMINAL_MODE: { - TTY_OP_END: 0, // Indicates end of options. - VINTR: 1, // Interrupt character; 255 if none. Similarly for the - // other characters. Not all of these characters are - // supported on all systems. - VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX - // systems). - VERASE: 3, // Erase the character to left of the cursor. - VKILL: 4, // Kill the current input line. - VEOF: 5, // End-of-file character (sends EOF from the - // terminal). - VEOL: 6, // End-of-line character in addition to carriage - // return and/or linefeed. - VEOL2: 7, // Additional end-of-line character. - VSTART: 8, // Continues paused output (normally control-Q). - VSTOP: 9, // Pauses output (normally control-S). - VSUSP: 10, // Suspends the current program. - VDSUSP: 11, // Another suspend character. - VREPRINT: 12, // Reprints the current input line. - VWERASE: 13, // Erases a word left of cursor. - VLNEXT: 14, // Enter the next character typed literally, even if - // it is a special character - VFLUSH: 15, // Character to flush output. - VSWTCH: 16, // Switch to a different shell layer. - VSTATUS: 17, // Prints system status line (load, command, pid, - // etc). - VDISCARD: 18, // Toggles the flushing of terminal output. - IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 - // if this flag is FALSE, and 1 if it is TRUE. - PARMRK: 31, // Mark parity and framing errors. - INPCK: 32, // Enable checking of parity errors. - ISTRIP: 33, // Strip 8th bit off characters. - INLCR: 34, // Map NL into CR on input. - IGNCR: 35, // Ignore CR on input. - ICRNL: 36, // Map CR to NL on input. - IUCLC: 37, // Translate uppercase characters to lowercase. - IXON: 38, // Enable output flow control. - IXANY: 39, // Any char will restart after stop. - IXOFF: 40, // Enable input flow control. - IMAXBEL: 41, // Ring bell on input queue full. - ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. - ICANON: 51, // Canonicalize input lines. - XCASE: 52, // Enable input and output of uppercase characters by - // preceding their lowercase equivalents with "\". - ECHO: 53, // Enable echoing. - ECHOE: 54, // Visually erase chars. - ECHOK: 55, // Kill character discards current line. - ECHONL: 56, // Echo NL even if ECHO is off. - NOFLSH: 57, // Don't flush after interrupt. - TOSTOP: 58, // Stop background jobs from output. - IEXTEN: 59, // Enable extensions. - ECHOCTL: 60, // Echo control characters as ^(Char). - ECHOKE: 61, // Visual erase for line kill. - PENDIN: 62, // Retype pending input. - OPOST: 70, // Enable output processing. - OLCUC: 71, // Convert lowercase to uppercase. - ONLCR: 72, // Map NL to CR-NL. - OCRNL: 73, // Translate carriage return to newline (output). - ONOCR: 74, // Translate newline to carriage return-newline - // (output). - ONLRET: 75, // Newline performs a carriage return (output). - CS7: 90, // 7 bit mode. - CS8: 91, // 8 bit mode. - PARENB: 92, // Parity enable. - PARODD: 93, // Odd parity, else even. - TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. - TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. - }, - CHANNEL_EXTENDED_DATATYPE: { - STDERR: 1, - }, + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } - SIGNALS: [ - 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', - 'USR2', 'KILL', 'PIPE' - ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() - COMPAT, - COMPAT_CHECKS: [ - [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], - [ /^Cisco-1\./, COMPAT.BUG_DHGEX_LARGE ], - [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations - [ /^OpenSSH_5\.\d+/, COMPAT.DYN_RPORT_BUG ], - ], + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } +} + +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = '' + let attributeValue = '' + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } - // KEX proposal-related - DEFAULT_KEX, - SUPPORTED_KEX, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY, - DEFAULT_CIPHER, - SUPPORTED_CIPHER, - DEFAULT_MAC, - SUPPORTED_MAC, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION, + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] - curve25519Supported, - eddsaSupported, -}; + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + } -module.exports.DISCONNECT_REASON_BY_VALUE = - Array.from(Object.entries(module.exports.DISCONNECT_REASON)) - .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} + +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} /***/ }), -/***/ 5708: +/***/ 3121: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// TODO: -// * make max packet size configurable -// * if decompression is enabled, use `._packet` in decipher instances as -// input to (sync) zlib inflater with appropriate offset and length to -// avoid an additional copy of payload data before inflation -// * factor decompression status into packet length checks -const { - createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual -} = __nccwpck_require__(6113); +const assert = __nccwpck_require__(9491) +const { kHeadersList } = __nccwpck_require__(2785) -const { readUInt32BE, writeUInt32BE } = __nccwpck_require__(9475); +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } -const FastBuffer = Buffer[Symbol.species]; -const MAX_SEQNO = 2 ** 32 - 1; -const EMPTY_BUFFER = Buffer.alloc(0); -const BUF_INT = Buffer.alloc(4); -const DISCARD_CACHE = new Map(); -const MAX_PACKET_SIZE = 35000; + for (const char of value) { + const code = char.charCodeAt(0) -let binding; -let AESGCMCipher; -let ChaChaPolyCipher; -let GenericCipher; -let AESGCMDecipher; -let ChaChaPolyDecipher; -let GenericDecipher; -try { - binding = __nccwpck_require__(9041); - ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, - AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); -} catch {} + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false + } + } +} -const CIPHER_STREAM = 1 << 0; -const CIPHER_INFO = (() => { - function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { - return { - sslName, - blockLen, - keyLen, - ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) - ? ivLen - : blockLen), - authLen, - discardLen, - stream: !!(flags & CIPHER_STREAM), - }; +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) + + if ( + (code <= 0x20 || code > 0x7F) || + char === '(' || + char === ')' || + char === '>' || + char === '<' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' + ) { + throw new Error('Invalid cookie name') + } } +} - return { - 'chacha20-poly1305@openssh.com': - info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + for (const char of value) { + const code = char.charCodeAt(0) - 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - 'aes128-gcm@openssh.com': - info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm@openssh.com': - info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), + if ( + code < 0x21 || // exclude CTLs (0-31) + code === 0x22 || + code === 0x2C || + code === 0x3B || + code === 0x5C || + code > 0x7E // non-ascii + ) { + throw new Error('Invalid header value') + } + } +} - 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), - 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), - 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), - 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), - 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), - 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) - 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), - 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), - 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), - '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), - 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') + } + } +} - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} - -- http://tools.ietf.org/html/rfc4345#section-4 */ - 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), - 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), - }; -})(); +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] -const MAC_INFO = (() => { - function info(sslName, len, actualLen, isETM) { - return { - sslName, - len, - actualLen, - isETM, - }; + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) } - return { - 'hmac-md5': info('md5', 16, 16, false), - 'hmac-md5-96': info('md5', 16, 12, false), - 'hmac-ripemd160': info('ripemd160', 20, 20, false), - 'hmac-sha1': info('sha1', 20, 20, false), - 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), - 'hmac-sha1-96': info('sha1', 20, 12, false), - 'hmac-sha2-256': info('sha256', 32, 32, false), - 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), - 'hmac-sha2-256-96': info('sha256', 32, 12, false), - 'hmac-sha2-512': info('sha512', 64, 64, false), - 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), - 'hmac-sha2-512-96': info('sha512', 64, 12, false), - }; -})(); + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ] + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ] -// Should only_be used during the initial handshake -class NullCipher { - constructor(seqno, onWrite) { - this.outSeqno = seqno; - this._onWrite = onWrite; - this._dead = false; + const dayName = days[date.getUTCDay()] + const day = date.getUTCDate().toString().padStart(2, '0') + const month = months[date.getUTCMonth()] + const year = date.getUTCFullYear() + const hour = date.getUTCHours().toString().padStart(2, '0') + const minute = date.getUTCMinutes().toString().padStart(2, '0') + const second = date.getUTCSeconds().toString().padStart(2, '0') + + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') } - free() { - this._dead = true; +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); + validateCookieName(cookie.name) + validateCookieValue(cookie.value) - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; + const out = [`${cookie.name}=${cookie.value}`] - randomFillSync(packet, 5 + payloadLen, padLen); + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } - return packet; + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' } - encrypt(packet) { - // `packet` === unencrypted packet - if (this._dead) - return; + if (cookie.secure) { + out.push('Secure') + } - this._onWrite(packet); + if (cookie.httpOnly) { + out.push('HttpOnly') + } - this.outSeqno = (this.outSeqno + 1) >>> 0; + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) } -} + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } -const POLY1305_ZEROS = Buffer.alloc(32); -const POLY1305_OUT_COMPUTE = Buffer.alloc(16); -let POLY1305_WASM_MODULE; -let POLY1305_RESULT_MALLOC; -let poly1305_auth; -class ChaChaPolyCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encKeyMain = enc.cipherKey.slice(0, 32); - this._encKeyPktLen = enc.cipherKey.slice(32); - this._dead = false; + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) } - free() { - this._dead = true; + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } - randomFillSync(packet, 5 + payloadLen, padLen); + const [key, ...value] = part.split('=') - return packet; + out.push(`${key.trim()}=${value.join('=')}`) } - encrypt(packet) { - // `packet` === unencrypted packet - if (this._dead) - return; - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); + return out.join('; ') +} - // Encrypt packet length - const pktLenEnc = - createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) - .update(packet.slice(0, 4)); - this._onWrite(pktLenEnc); +let kHeadersListNode - // Encrypt rest of packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const payloadEnc = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(packet.slice(4)); - this._onWrite(payloadEnc); +function getHeadersList (headers) { + if (headers[kHeadersList]) { + return headers[kHeadersList] + } - // Calculate Poly1305 MAC - poly1305_auth(POLY1305_RESULT_MALLOC, - pktLenEnc, - pktLenEnc.length, - payloadEnc, - payloadEnc.length, - polyKey); - const mac = Buffer.allocUnsafe(16); - mac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - this._onWrite(mac); + if (!kHeadersListNode) { + kHeadersListNode = Object.getOwnPropertySymbols(headers).find( + (symbol) => symbol.description === 'headers list' + ) - this.outSeqno = (this.outSeqno + 1) >>> 0; + assert(kHeadersListNode, 'Headers cannot be parsed') } + + const headersList = headers[kHeadersListNode] + assert(headersList) + + return headersList } -class ChaChaPolyCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new ChaChaPolyCipher(enc.cipherKey); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; +module.exports = { + isCTLExcludingHtab, + stringify, + getHeadersList +} - const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; +/***/ }), - randomFillSync(packet, 5 + payloadLen, padLen); +/***/ 2067: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return packet; +"use strict"; + + +const net = __nccwpck_require__(1808) +const assert = __nccwpck_require__(9491) +const util = __nccwpck_require__(3983) +const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8045) + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +let SessionCache +// FIXME: remove workaround when the Node bug is fixed +// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 +if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new global.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } } - encrypt(packet) { - // `packet` === unencrypted packet +} else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + } - if (this._dead) - return; + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } - this._onWrite(packet); + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } - this.outSeqno = (this.outSeqno + 1) >>> 0; + this._sessionCache.set(sessionKey, session) + } } } +function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } -class AESGCMCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encSSLName = enc.cipherInfo.sslName; - this._encKey = enc.cipherKey; - this._encIV = enc.cipherIV; - this._dead = false; + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = __nccwpck_require__(4404) + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null + + assert(sessionKey) + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + // TODO(HTTP/2): Add support for h2c + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port: port || 443, + host: hostname + }) + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port: port || 80, + host: hostname + }) + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket } - free() { - this._dead = true; +} + +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); + let s1 = null + let s2 = null + const timeoutId = setTimeout(() => { + // setImmediate is added to make sure that we priotorise socket error events over timeouts + s1 = setImmediate(() => { + if (process.platform === 'win32') { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout()) + } else { + onConnectTimeout() + } + }) + }, timeout) + return () => { + clearTimeout(timeoutId) + clearImmediate(s1) + clearImmediate(s2) + } +} - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) +} - randomFillSync(packet, 5 + payloadLen, padLen); +module.exports = buildConnector - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - if (this._dead) - return; +/***/ }), - const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); - cipher.setAutoPadding(false); +/***/ 4462: +/***/ ((module) => { - const lenData = packet.slice(0, 4); - cipher.setAAD(lenData); - this._onWrite(lenData); +"use strict"; - // Encrypt pad length, payload, and padding - const encrypted = cipher.update(packet.slice(4)); - this._onWrite(encrypted); - const final = cipher.final(); - // XXX: final.length === 0 always? - if (final.length) - this._onWrite(final); - // Generate MAC - const tag = cipher.getAuthTag(); - this._onWrite(tag); +/** @type {Record} */ +const headerNameLowerCasedRecord = {} + +// https://developer.mozilla.org/docs/Web/HTTP/Headers +const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +] + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) - // Increment counter in IV by 1 for next packet - ivIncrement(this._encIV); +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord +} - this.outSeqno = (this.outSeqno + 1) >>> 0; + +/***/ }), + +/***/ 8045: +/***/ ((module) => { + +"use strict"; + + +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' } } -class AESGCMCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new AESGCMCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._dead = false; +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ConnectTimeoutError) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' } - free() { - this._dead = true; - this._instance.free(); +} + +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersTimeoutError) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; +} - const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersOverflowError) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } +} - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, BodyTimeoutError) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } +} - randomFillSync(packet, 5 + payloadLen, padLen); +class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message) + Error.captureStackTrace(this, ResponseStatusCodeError) + this.name = 'ResponseStatusCodeError' + this.message = message || 'Response Status Code Error' + this.code = 'UND_ERR_RESPONSE_STATUS_CODE' + this.body = body + this.status = statusCode + this.statusCode = statusCode + this.headers = headers + } +} - return packet; +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidArgumentError) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' } - encrypt(packet) { - // `packet` === unencrypted packet +} - if (this._dead) - return; +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidReturnValueError) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } +} - // Encrypts in-place - this._instance.encrypt(packet); +class RequestAbortedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestAbortedError) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } +} - this._onWrite(packet); +class InformationalError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InformationalError) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } +} - this.outSeqno = (this.outSeqno + 1) >>> 0; +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestContentLengthMismatchError) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' } } +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseContentLengthMismatchError) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } +} -class GenericCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._macSSLName = enc.macInfo.sslName; - this._macKey = enc.macKey; - this._macActualLen = enc.macInfo.actualLen; - this._macETM = enc.macInfo.isETM; - this._aadLen = (this._macETM ? 4 : 0); - this._dead = false; +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientDestroyedError) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } +} - const discardLen = enc.cipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._cipherInstance.update(discard); - } +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientClosedError) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' } - free() { - this._dead = true; +} + +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + Error.captureStackTrace(this, SocketError) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; +} + +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } +} + +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } +} + +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + Error.captureStackTrace(this, HTTPParserError) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } +} + +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseExceededMaxSizeError) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } +} + +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + Error.captureStackTrace(this, RequestRetryError) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers + } +} - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; +module.exports = { + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError +} - const packet = Buffer.allocUnsafe(pktLen); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; +/***/ }), - randomFillSync(packet, 5 + payloadLen, padLen); +/***/ 2905: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet +"use strict"; - if (this._dead) - return; - let mac; - if (this._macETM) { - // Encrypt pad length, payload, and padding - const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); - const encrypted = this._cipherInstance.update( - new Uint8Array(packet.buffer, - packet.byteOffset + 4, - packet.length - 4) - ); +const { + InvalidArgumentError, + NotSupportedError +} = __nccwpck_require__(8045) +const assert = __nccwpck_require__(9491) +const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(2785) +const util = __nccwpck_require__(3983) - this._onWrite(lenBytes); - this._onWrite(encrypted); +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(lenBytes); - mac.update(encrypted); - } else { - // Encrypt length field, pad length, payload, and padding - const encrypted = this._cipherInstance.update(packet); - this._onWrite(encrypted); +/** + * Verifies that the given val is a valid HTTP token + * per the rules defined in RFC 7230 + * See https://tools.ietf.org/html/rfc7230#section-3.2.6 + */ +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(packet); - } +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ - let digest = mac.digest(); - if (digest.length > this._macActualLen) - digest = digest.slice(0, this._macActualLen); - this._onWrite(digest); +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} +const kHandler = Symbol('handler') -class GenericCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._macLen = enc.macInfo.len; - this._macActualLen = enc.macInfo.actualLen; - this._aadLen = (enc.macInfo.isETM ? 4 : 0); - this._instance = new GenericCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV, - enc.macInfo.sslName, - enc.macKey, - enc.macInfo.isETM); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; +const channels = {} - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; +let extractBody - const packet = Buffer.allocUnsafe(pktLen + this._macLen); +try { + const diagnosticsChannel = __nccwpck_require__(7643) + channels.create = diagnosticsChannel.channel('undici:request:create') + channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') + channels.headers = diagnosticsChannel.channel('undici:request:headers') + channels.trailers = diagnosticsChannel.channel('undici:request:trailers') + channels.error = diagnosticsChannel.channel('undici:request:error') +} catch { + channels.create = { hasSubscribers: false } + channels.bodySent = { hasSubscribers: false } + channels.headers = { hasSubscribers: false } + channels.trailers = { hasSubscribers: false } + channels.error = { hasSubscribers: false } +} - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError, + expectContinue + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.exec(path) !== null) { + throw new InvalidArgumentError('invalid request path') + } - randomFillSync(packet, 5 + payloadLen, padLen); + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') + } - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } - if (this._dead) - return; + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } - if (this._macActualLen < this._macLen) { - packet = new FastBuffer(packet.buffer, - packet.byteOffset, - (packet.length - - (this._macLen - this._macActualLen))); + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') } - this._onWrite(packet); - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + this.headersTimeout = headersTimeout -class NullDecipher { - constructor(seqno, onPayload) { - this.inSeqno = seqno; - this._onPayload = onPayload; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - while (p < dataLen) { - // Read packet length - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); + this.bodyTimeout = bodyTimeout - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; + this.throwOnError = throwOnError === true - if (this._lenBytes < 4) - return; + this.method = method - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (4 + this._len & 7) !== 0) { - throw new Error('Bad packet length'); + this.abort = null + + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body + + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + util.destroy(this) } - if (p >= dataLen) - return; + this.body.on('end', this.endHandler) } - // Read padding length, payload, and padding - if (this._packetPos < this._len) { - const nb = Math.min(this._len - this._packetPos, dataLen - p); - let chunk; - if (p !== 0 || nb !== dataLen) - chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - chunk = data; - if (nb === this._len) { - this._packet = chunk; + this.errorHandler = err => { + if (this.abort) { + this.abort(err) } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(chunk, this._packetPos); + this.error = err } - p += nb; - this._packetPos += nb; - if (this._packetPos < this._len) - return; } + this.body.on('error', this.errorHandler) + } else if (util.isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); + this.completed = false - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; + this.aborted = false - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} + this.upgrade = upgrade || null -class ChaChaPolyDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decKeyMain = dec.decipherKey.slice(0, 32); - this._decKeyPktLen = dec.decipherKey.slice(32); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._calcMac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data + this.path = query ? util.buildURL(path, query) : path - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; + this.origin = origin - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent - const decLenBytes = - createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) - .update(this._lenBuf); - this._len = readUInt32BE(decLenBytes, 0); + this.blocking = blocking == null ? false : blocking - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - } + this.reset = reset == null ? null : reset - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } + this.host = null - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } + this.contentLength = null - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); + this.contentType = null - // Calculate and compare Poly1305 MACs - poly1305_auth(POLY1305_RESULT_MALLOC, - this._lenBuf, - 4, - this._packet, - this._packet.length, - polyKey); + this.headers = '' - this._calcMac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - if (!timingSafeEqual(this._calcMac, this._mac)) - throw new Error('Invalid MAC'); + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false - // Decrypt packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const packet = - createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(this._packet); + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(this, key, headers[key]) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } - const payload = new FastBuffer(packet.buffer, - packet.byteOffset + 1, - packet.length - packet[0] - 1); + if (util.isFormDataLike(this.body)) { + if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { + throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') + } - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; + if (!extractBody) { + extractBody = (__nccwpck_require__(1472).extractBody) + } - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); + const [bodyStream, contentType] = extractBody(body) + if (this.contentType == null) { + this.contentType = contentType + this.headers += `content-type: ${contentType}\r\n` } + this.body = bodyStream.stream + this.contentLength = bodyStream.length + } else if (util.isBlobLike(body) && this.contentType == null && body.type) { + this.contentType = body.type + this.headers += `content-type: ${body.type}\r\n` } - } -} -class ChaChaPolyDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new ChaChaPolyDecipher(dec.decipherKey); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data + util.validateHandler(handler, method, upgrade) - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; + this.servername = util.getServerName(this.host) - this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); + this[kHandler] = handler - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } - if (p >= dataLen) - return; + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) } + } + } - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) } + } + } - this._instance.decrypt(this._packet, this._mac, this.inSeqno); + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } + } - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) } } -} -class AESGCMDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = null; - this._decipherSSLName = dec.decipherInfo.sslName; - this._decipherKey = dec.decipherKey; - this._decipherIV = dec.decipherIV; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error('Bad packet length'); - } + return this[kHandler].onUpgrade(statusCode, headers, socket) + } - this._decipherInstance = createDecipheriv( - this._decipherSSLName, - this._decipherKey, - this._decipherIV - ); - this._decipherInstance.setAutoPadding(false); - this._decipherInstance.setAAD(intToBytes(this._len)); - } + onComplete (trailers) { + this.onFinally() - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let decrypted; - if (p !== 0 || nb !== dataLen) { - decrypted = this._decipherInstance.update( - new Uint8Array(data.buffer, data.byteOffset + p, nb) - ); - } else { - decrypted = this._decipherInstance.update(data); - } - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } + assert(!this.aborted) - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } - { - // Verify authentication tag - this._decipherInstance.setAuthTag(this._tag); + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } - const decrypted = this._decipherInstance.final(); + onError (error) { + this.onFinally() - // XXX: this should never output any data since stream ciphers always - // return data from .update() and block ciphers must end on a multiple - // of the block length, which would have caused an exception to be - // thrown if the total input was not... - if (decrypted.length) { - if (this._packet) - this._packet.set(decrypted, this._packetPos); - else - this._packet = decrypted; - } - } + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); + if (this.aborted) { + return + } + this.aborted = true - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - ivIncrement(this._decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tagPos = 0; + return this[kHandler].onError(error) + } - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } + + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null } } -} -class AESGCMDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value) + return this } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; + static [kHTTP1BuildRequest] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error(`Bad packet length: ${this._len}`); - } - } + static [kHTTP2BuildRequest] (origin, opts, handler) { + const headers = opts.headers + opts = { ...opts, headers: null } - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } + const request = new Request(origin, opts, handler) - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; + request.headers = {} + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(request, headers[i], headers[i + 1], true) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(request, key, headers[key], true) } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } - this._instance.decrypt(this._packet, this._len, this._tag); + return request + } - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); + static [kHTTP2CopyHeaders] (raw) { + const rawHeaders = raw.split('\r\n') + const headers = {} - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tagPos = 0; + for (const header of rawHeaders) { + const [key, value] = header.split(': ') - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + if (value == null || value.length === 0) continue + + if (headers[key]) headers[key] += `,${value}` + else headers[key] = value } + + return headers } } -// TODO: test incremental .update()s vs. copying to _packet and doing a single -// .update() after entire packet read -- a single .update() would allow -// verifying MAC before decrypting for ETM MACs -class GenericDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._decipherInstance.setAutoPadding(false); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen - ); - this._blockSize = dec.decipherInfo.blockLen; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macSSLName = dec.macInfo.sslName; - this._macKey = dec.macKey; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - this._macInstance = null; +function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } - const discardLen = dec.decipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._decipherInstance.update(discard); - } + val = val != null ? `${val}` : '' + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } + return skipAppend ? val : `${key}: ${val}\r\n` +} - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; +function processHeader (request, key, val, skipAppend = false) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } - let decrypted; - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); + if ( + request.host === null && + key.length === 4 && + key.toLowerCase() === 'host' + ) { + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + // Consumed by Client + request.host = val + } else if ( + request.contentLength === null && + key.length === 14 && + key.toLowerCase() === 'content-length' + ) { + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if ( + request.contentType === null && + key.length === 12 && + key.toLowerCase() === 'content-type' + ) { + request.contentType = val + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } else if ( + key.length === 17 && + key.toLowerCase() === 'transfer-encoding' + ) { + throw new InvalidArgumentError('invalid transfer-encoding header') + } else if ( + key.length === 10 && + key.toLowerCase() === 'connection' + ) { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } else if (value === 'close') { + request.reset = true + } + } else if ( + key.length === 10 && + key.toLowerCase() === 'keep-alive' + ) { + throw new InvalidArgumentError('invalid keep-alive header') + } else if ( + key.length === 7 && + key.toLowerCase() === 'upgrade' + ) { + throw new InvalidArgumentError('invalid upgrade header') + } else if ( + key.length === 6 && + key.toLowerCase() === 'expect' + ) { + throw new NotSupportedError('expect header not supported') + } else if (tokenRegExp.exec(key) === null) { + throw new InvalidArgumentError('invalid header key') + } else { + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (skipAppend) { + if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` + else request.headers[key] = processHeaderValue(key, val[i], skipAppend) } else { - // Decrypt first block to get packet length - decrypted = this._decipherInstance.update(this._block); - this._len = readUInt32BE(decrypted, 0); - need = 4 + this._len - this._blockSize; + request.headers += processHeaderValue(key, val[i]) } + } + } else { + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } + } +} - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._blockSize - 1)) !== 0) { - throw new Error('Bad packet length'); - } +module.exports = Request - // Create MAC up front to calculate in parallel with decryption - this._macInstance = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.inSeqno, 0); - this._macInstance.update(BUF_INT); - if (this._macETM) { - this._macInstance.update(this._block); - } else { - this._macInstance.update(new Uint8Array(decrypted.buffer, - decrypted.byteOffset, - 4)); - this._pktLen = decrypted.length - 4; - this._packetPos = this._pktLen; - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(decrypted.buffer, - decrypted.byteOffset + 4, - this._packetPos), - 0 - ); - } +/***/ }), - if (p >= dataLen) - return; - } +/***/ 2785: +/***/ ((module) => { - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (this._macETM) - this._macInstance.update(encrypted); - const decrypted = this._decipherInstance.update(encrypted); - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kHeadersList: Symbol('headers list'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kHTTP2BuildRequest: Symbol('http2 build request'), + kHTTP1BuildRequest: Symbol('http1 build request'), + kHTTP2CopyHeaders: Symbol('http2 copy headers'), + kHTTPConnVersion: Symbol('http connection version'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable') +} - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - // Verify MAC - if (!this._macETM) - this._macInstance.update(this._packet); - let calculated = this._macInstance.digest(); - if (this._macActualLen < calculated.length) { - calculated = new Uint8Array(calculated.buffer, - calculated.byteOffset, - this._macActualLen); - } - if (!timingSafeEquals(calculated, this._mac)) - throw new Error('Invalid MAC'); +/***/ }), - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); +/***/ 3983: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; +"use strict"; - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } + +const assert = __nccwpck_require__(9491) +const { kDestroyed, kBodyUsed } = __nccwpck_require__(2785) +const { IncomingMessage } = __nccwpck_require__(3685) +const stream = __nccwpck_require__(2781) +const net = __nccwpck_require__(1808) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { Blob } = __nccwpck_require__(4300) +const nodeUtil = __nccwpck_require__(3837) +const { stringify } = __nccwpck_require__(3477) +const { headerNameLowerCasedRecord } = __nccwpck_require__(4462) + +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + +function nop () {} + +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' } -class GenericDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new GenericDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV, - dec.macInfo.sslName, - dec.macKey, - dec.macInfo.isETM, - dec.macInfo.actualLen); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM || dec.decipherInfo.stream - ? 4 - : dec.decipherInfo.blockLen - ); - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; +// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) +function isBlobLike (object) { + return (Blob && object instanceof Blob) || ( + object && + typeof object === 'object' && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) +} + +function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') } - free() { - this._instance.free(); + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified } - decrypt(data, p, dataLen) { - // `data` === encrypted data - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } + return url +} - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; +function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url) - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - this._instance.decryptBlock(this._block); - this._len = readUInt32BE(this._block, 0); - need = 4 + this._len - this._block.length; - } + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._block.length - 1)) !== 0) { - throw new Error('Bad packet length'); - } + return url + } - if (!this._macETM) { - this._pktLen = (this._block.length - 4); - if (this._pktLen) { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(this._block.buffer, - this._block.byteOffset + 4, - this._pktLen), - 0 - ); - } - } + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } - if (p >= dataLen) - return; - } + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } - // Decrypt and verify MAC - this._instance.decrypt(this._packet, - this.inSeqno, - this._block, - this._mac); + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol}//${url.hostname}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` + + if (origin.endsWith('/')) { + origin = origin.substring(0, origin.length - 1) } + + if (path && !path.startsWith('/')) { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + url = new URL(origin + path) } + + return url } -// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV -function ivIncrement(iv) { - // eslint-disable-next-line no-unused-expressions - ++iv[11] >>> 8 - && ++iv[10] >>> 8 - && ++iv[9] >>> 8 - && ++iv[8] >>> 8 - && ++iv[7] >>> 8 - && ++iv[6] >>> 8 - && ++iv[5] >>> 8 - && ++iv[4] >>> 8; +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url } -const intToBytes = (() => { - const ret = Buffer.alloc(4); - return (n) => { - ret[0] = (n >>> 24); - ret[1] = (n >>> 16); - ret[2] = (n >>> 8); - ret[3] = n; - return ret; - }; -})(); +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') -function timingSafeEquals(a, b) { - if (a.length !== b.length) { - timingSafeEqual(a, a); - return false; + assert(idx !== -1) + return host.substring(1, idx) } - return timingSafeEqual(a, b); + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substring(0, idx) +} + +// IP addresses are not valid server names per RFC6066 +// > Currently, the only server names supported are DNS hostnames +function getServerName (host) { + if (!host) { + return null + } + + assert.strictEqual(typeof host, 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } + + return servername } -function createCipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} - if (typeof config.outbound !== 'object' || config.outbound === null) - throw new Error('Invalid outbound'); +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} - const outbound = config.outbound; +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} - if (typeof outbound.onWrite !== 'function') - throw new Error('Invalid outbound.onWrite'); +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } - if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) - throw new Error('Invalid outbound.cipherInfo'); + return null +} - if (!Buffer.isBuffer(outbound.cipherKey) - || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { - throw new Error('Invalid outbound.cipherKey'); +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) +} + +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted +} + +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return } - if (outbound.cipherInfo.ivLen - && (!Buffer.isBuffer(outbound.cipherIV) - || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { - throw new Error('Invalid outbound.cipherIV'); + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } + + stream.destroy(err) + } else if (err) { + process.nextTick((stream, err) => { + stream.emit('error', err) + }, stream, err) } - if (typeof outbound.seqno !== 'number' - || outbound.seqno < 0 - || outbound.seqno > MAX_SEQNO) { - throw new Error('Invalid outbound.seqno'); + if (stream.destroyed !== true) { + stream[kDestroyed] = true } +} - const forceNative = !!outbound.forceNative; +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} - switch (outbound.cipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMCipher && !forceNative - ? new AESGCMCipherBinding(config) - : new AESGCMCipherNative(config)); - case 'chacha20': - return (ChaChaPolyCipher && !forceNative - ? new ChaChaPolyCipherBinding(config) - : new ChaChaPolyCipherNative(config)); - default: { - if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) - throw new Error('Invalid outbound.macInfo'); - if (!Buffer.isBuffer(outbound.macKey) - || outbound.macKey.length !== outbound.macInfo.len) { - throw new Error('Invalid outbound.macKey'); +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return headerNameLowerCasedRecord[value] || value.toLowerCase() +} + +function parseHeaders (headers, obj = {}) { + // For H2 support + if (!Array.isArray(headers)) return headers + + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase() + let val = obj[key] + + if (!val) { + if (Array.isArray(headers[i + 1])) { + obj[key] = headers[i + 1].map(x => x.toString('utf8')) + } else { + obj[key] = headers[i + 1].toString('utf8') } - return (GenericCipher && !forceNative - ? new GenericCipherBinding(config) - : new GenericCipherNative(config)); + } else { + if (!Array.isArray(val)) { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) } } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') + } + + return obj } -function createDecipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); +function parseRawHeaders (headers) { + const ret = [] + let hasContentLength = false + let contentDispositionIdx = -1 - if (typeof config.inbound !== 'object' || config.inbound === null) - throw new Error('Invalid inbound'); + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString() + const val = headers[n + 1].toString('utf8') - const inbound = config.inbound; + if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + ret.push(key, val) + hasContentLength = true + } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = ret.push(key, val) - 1 + } else { + ret.push(key, val) + } + } - if (typeof inbound.onPayload !== 'function') - throw new Error('Invalid inbound.onPayload'); + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } - if (typeof inbound.decipherInfo !== 'object' - || inbound.decipherInfo === null) { - throw new Error('Invalid inbound.decipherInfo'); + return ret +} + +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} + +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') } - if (!Buffer.isBuffer(inbound.decipherKey) - || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { - throw new Error('Invalid inbound.decipherKey'); + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') } - if (inbound.decipherInfo.ivLen - && (!Buffer.isBuffer(inbound.decipherIV) - || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { - throw new Error('Invalid inbound.decipherIV'); + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') } - if (typeof inbound.seqno !== 'number' - || inbound.seqno < 0 - || inbound.seqno > MAX_SEQNO) { - throw new Error('Invalid inbound.seqno'); + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') } - const forceNative = !!inbound.forceNative; + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } - switch (inbound.decipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMDecipher && !forceNative - ? new AESGCMDecipherBinding(config) - : new AESGCMDecipherNative(config)); - case 'chacha20': - return (ChaChaPolyDecipher && !forceNative - ? new ChaChaPolyDecipherBinding(config) - : new ChaChaPolyDecipherNative(config)); - default: { - if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) - throw new Error('Invalid inbound.macInfo'); - if (!Buffer.isBuffer(inbound.macKey) - || inbound.macKey.length !== inbound.macInfo.len) { - throw new Error('Invalid inbound.macKey'); - } - return (GenericDecipher && !forceNative - ? new GenericDecipherBinding(config) - : new GenericDecipherNative(config)); + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') } } } -module.exports = { - CIPHER_INFO, - MAC_INFO, - bindingAvailable: !!binding, - init: (() => { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - try { - POLY1305_WASM_MODULE = await __nccwpck_require__(4989)(); - POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); - poly1305_auth = POLY1305_WASM_MODULE.cwrap( - 'poly1305_auth', - null, - ['number', 'array', 'number', 'array', 'number', 'array'] - ); - } catch (ex) { - return reject(ex); - } - resolve(); - }); - })(), - - NullCipher, - createCipher, - NullDecipher, - createDecipher, -}; +// A body is disturbed if it has been read from and it cannot +// be re-used without losing state or data. +function isDisturbed (body) { + return !!(body && ( + stream.isDisturbed + ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? + : body[kBodyUsed] || + body.readableDidRead || + (body._readableState && body._readableState.dataEmitted) || + isReadableAborted(body) + )) +} +function isErrored (body) { + return !!(body && ( + stream.isErrored + ? stream.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) +} -/***/ }), +function isReadable (body) { + return !!(body && ( + stream.isReadable + ? stream.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) +} -/***/ 4989: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} +async function * convertIterableToBuffer (iterable) { + for await (const chunk of iterable) { + yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + } +} -var createPoly1305 = (function() { - var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; - if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; - return ( -function(createPoly1305) { - createPoly1305 = createPoly1305 || {}; +let ReadableStream +function ReadableStreamFrom (iterable) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } + if (ReadableStream.from) { + return ReadableStream.from(convertIterableToBuffer(iterable)) + } -var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; -if(z)B=y?(__nccwpck_require__(1017).dirname)(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=__nccwpck_require__(7147));G||(G=__nccwpck_require__(1017));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=__nccwpck_require__(7147));G||(G=__nccwpck_require__(1017));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= -0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; -function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; -function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} -function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} -function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; -(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, -a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); -b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; -b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; -function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 { + controller.close() + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + controller.enqueue(new Uint8Array(buf)) + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + } + }, + 0 + ) +} +// The chunk should be a FormData instance and contains +// all the required methods. +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function throwIfAborted (signal) { + if (!signal) { return } + if (typeof signal.throwIfAborted === 'function') { + signal.throwIfAborted() + } else { + if (signal.aborted) { + // DOMException not available < v17.0.0 + const err = new Error('The operation was aborted') + err.name = 'AbortError' + throw err + } + } +} - return createPoly1305.ready +function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener) + return () => signal.removeListener('abort', listener) } -); -})(); -if (true) - module.exports = createPoly1305; -else {} +const hasToWellFormed = !!String.prototype.toWellFormed -/***/ }), +/** + * @param {string} val + */ +function toUSVString (val) { + if (hasToWellFormed) { + return `${val}`.toWellFormed() + } else if (nodeUtil.toUSVString) { + return nodeUtil.toUSVString(val) + } -/***/ 172: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return `${val}` +} -"use strict"; +// Parsed accordingly to RFC 9110 +// https://www.rfc-editor.org/rfc/rfc9110#field.content-range +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } + const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } + : null +} -const MESSAGE_HANDLERS = new Array(256); -[ - (__nccwpck_require__(4126).HANDLERS), - __nccwpck_require__(6475), -].forEach((handlers) => { - // eslint-disable-next-line prefer-const - for (let [type, handler] of Object.entries(handlers)) { - type = +type; - if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) - MESSAGE_HANDLERS[type] = handler; - } -}); +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true -module.exports = MESSAGE_HANDLERS; +module.exports = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString, + isReadableAborted, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + throwIfAborted, + addAbortListener, + parseRangeHeader, + nodeMajor, + nodeMinor, + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), + safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +} /***/ }), -/***/ 6475: +/***/ 4839: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const Dispatcher = __nccwpck_require__(412) const { - bufferSlice, - bufferParser, - doFatalError, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(9475); - -const { - CHANNEL_OPEN_FAILURE, - COMPAT, - MESSAGE, - TERMINAL_MODE, -} = __nccwpck_require__(6832); + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = __nccwpck_require__(8045) +const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(2785) -const { - parseKey, -} = __nccwpck_require__(2218); +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') -const TERMINAL_MODE_BY_VALUE = - Array.from(Object.entries(TERMINAL_MODE)) - .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); +class DispatcherBase extends Dispatcher { + constructor () { + super() -module.exports = { - // Transport layer protocol ================================================== - [MESSAGE.DISCONNECT]: (self, payload) => { - /* - byte SSH_MSG_DISCONNECT - uint32 reason code - string description in ISO-10646 UTF-8 encoding - string language tag - */ - bufferParser.init(payload, 1); - const reason = bufferParser.readUInt32BE(); - const desc = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] + } - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DISCONNECT packet' - ); - } + get destroyed () { + return this[kDestroyed] + } - self._debug && self._debug( - `Inbound: Received DISCONNECT (${reason}, "${desc}")` - ); + get closed () { + return this[kClosed] + } - const handler = self._handlers.DISCONNECT; - handler && handler(self, reason, desc); - }, - [MESSAGE.IGNORE]: (self, payload) => { - /* - byte SSH_MSG_IGNORE - string data - */ - self._debug && self._debug('Inbound: Received IGNORE'); - }, - [MESSAGE.UNIMPLEMENTED]: (self, payload) => { - /* - byte SSH_MSG_UNIMPLEMENTED - uint32 packet sequence number of rejected message - */ - bufferParser.init(payload, 1); - const seqno = bufferParser.readUInt32BE(); - bufferParser.clear(); + get interceptors () { + return this[kInterceptors] + } - if (seqno === undefined) { - return doFatalError( - self, - 'Inbound: Malformed UNIMPLEMENTED packet' - ); + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors][i] + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError('interceptor must be an function') + } + } } - self._debug - && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); - }, - [MESSAGE.DEBUG]: (self, payload) => { - /* - byte SSH_MSG_DEBUG - boolean always_display - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const display = bufferParser.readBool(); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); + this[kInterceptors] = newInterceptors + } - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DEBUG packet' - ); + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) } - self._debug && self._debug('Inbound: Received DEBUG'); - - const handler = self._handlers.DEBUG; - handler && handler(self, display, msg); - }, - [MESSAGE.SERVICE_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_SERVICE_REQUEST - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_REQUEST packet' - ); + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); - - const handler = self._handlers.SERVICE_REQUEST; - handler && handler(self, name); - }, - [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { - // S->C - /* - byte SSH_MSG_SERVICE_ACCEPT - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_ACCEPT packet' - ); + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return } - self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); - - const handler = self._handlers.SERVICE_ACCEPT; - handler && handler(self, name); - }, - - // User auth protocol -- generic ============================================= - [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_USERAUTH_REQUEST - string user name in ISO-10646 UTF-8 encoding [RFC3629] - string service name in US-ASCII - string method name in US-ASCII - .... method specific fields - */ - bufferParser.init(payload, 1); - const user = bufferParser.readString(true); - const service = bufferParser.readString(true); - const method = bufferParser.readString(true); - let methodData; - let methodDesc; - switch (method) { - case 'none': - methodData = null; - break; - case 'password': { - /* - boolean - string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] - [string new password] - */ - const isChange = bufferParser.readBool(); - if (isChange !== undefined) { - methodData = bufferParser.readString(true); - if (methodData !== undefined && isChange) { - const newPassword = bufferParser.readString(true); - if (newPassword !== undefined) - methodData = { oldPassword: methodData, newPassword }; - else - methodData = undefined; - } - } - break; - } - case 'publickey': { - /* - boolean - string public key algorithm name - string public key blob - [string signature] - */ - const hasSig = bufferParser.readBool(); - if (hasSig !== undefined) { - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - if (hasSig) { - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - - signature = sigSSHToASN1(signature, keyAlgo); - if (signature) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo, - key, - signature, - blob, - }; - } - } - } else { - methodData = { keyAlgo, key }; - methodDesc = 'publickey -- check'; - } - } - break; + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) } - case 'hostbased': { - /* - string public key algorithm for host key - string public host key and certificates for client host - string client host name expressed as the FQDN in US-ASCII - string user name on the client host in ISO-10646 UTF-8 encoding - [RFC3629] - string signature - */ - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - const localHostname = bufferParser.readString(true); - const localUsername = bufferParser.readString(true); + return + } - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } + this[kClosed] = true + this[kOnClosed].push(callback) - signature = sigSSHToASN1(signature, keyAlgo); - if (signature !== undefined) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo, - key, - signature, - blob, - localHostname, - localUsername, - }; - } - } - break; + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) } - case 'keyboard-interactive': - /* - string language tag (as defined in [RFC-3066]) - string submethods (ISO-10646 UTF-8) - */ - // Skip/ignore language field -- it's deprecated in RFC 4256 - bufferParser.skipString(); + } - methodData = bufferParser.readList(); - break; - default: - if (method !== undefined) - methodData = bufferParser.readRaw(); + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null } - bufferParser.clear(); - if (methodData === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_REQUEST packet' - ); + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }) + }) } - if (methodDesc === undefined) - methodDesc = method; + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - self._authsQueue.push(method); + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } - self._debug - && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); + if (!err) { + err = new ClientDestroyedError() + } - const handler = self._handlers.USERAUTH_REQUEST; - handler && handler(self, user, service, method, methodData); - }, - [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_FAILURE - name-list authentications that can continue - boolean partial success - */ - bufferParser.init(payload, 1); - const authMethods = bufferParser.readList(); - const partialSuccess = bufferParser.readBool(); - bufferParser.clear(); + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) - if (partialSuccess === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_FAILURE packet' - ); + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } } - self._debug - && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) + } - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_FAILURE; - handler && handler(self, authMethods, partialSuccess); - }, - [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_SUCCESS - */ - self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) + } - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_SUCCESS; - handler && handler(self); - }, - [MESSAGE.USERAUTH_BANNER]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_BANNER - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); + let dispatch = this[kDispatch].bind(this) + for (let i = this[kInterceptors].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors][i](dispatch) + } + this[kInterceptedDispatch] = dispatch + return dispatch(opts, handler) + } - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_BANNER packet' - ); + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') } - self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } - const handler = self._handlers.USERAUTH_BANNER; - handler && handler(self, msg); - }, + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } - // User auth protocol -- method-specific ===================================== - 60: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 60 without auth'); - return; + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err) + + return false } + } +} - switch (self._authsQueue[0]) { - case 'password': { - // S->C - /* - byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ - string prompt in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const prompt = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); +module.exports = DispatcherBase - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' - ); - } - self._debug - && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); +/***/ }), - const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; - handler && handler(self, prompt); - break; - } - case 'publickey': { - // S->C - /* - byte SSH_MSG_USERAUTH_PK_OK - string public key algorithm name from the request - string public key blob from the request - */ - bufferParser.init(payload, 1); - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - bufferParser.clear(); +/***/ 412: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (key === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PK_OK packet' - ); - } +"use strict"; - self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_PK_OK; - handler && handler(self, keyAlgo, key); - break; - } - case 'keyboard-interactive': { - // S->C - /* - byte SSH_MSG_USERAUTH_INFO_REQUEST - string name (ISO-10646 UTF-8) - string instruction (ISO-10646 UTF-8) - string language tag (as defined in [RFC-3066]) - int num-prompts - string prompt[1] (ISO-10646 UTF-8) - boolean echo[1] - ... - string prompt[num-prompts] (ISO-10646 UTF-8) - boolean echo[num-prompts] - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const instructions = bufferParser.readString(true); - bufferParser.readString(); // skip lang - const numPrompts = bufferParser.readUInt32BE(); - let prompts; - if (numPrompts !== undefined) { - prompts = new Array(numPrompts); - let i; - for (i = 0; i < numPrompts; ++i) { - const prompt = bufferParser.readString(true); - const echo = bufferParser.readBool(); - if (echo === undefined) - break; - prompts[i] = { prompt, echo }; - } - if (i !== numPrompts) - prompts = undefined; - } - bufferParser.clear(); +const EventEmitter = __nccwpck_require__(2361) - if (prompts === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' - ); - } +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } - self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); + close () { + throw new Error('not implemented') + } - const handler = self._handlers.USERAUTH_INFO_REQUEST; - handler && handler(self, name, instructions, prompts); - break; + destroy () { + throw new Error('not implemented') + } +} + +module.exports = Dispatcher + + +/***/ }), + +/***/ 1472: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Busboy = __nccwpck_require__(3438) +const util = __nccwpck_require__(3983) +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = __nccwpck_require__(2538) +const { FormData } = __nccwpck_require__(2015) +const { kState } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { DOMException, structuredClone } = __nccwpck_require__(1037) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) +const { kBodyUsed } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { isErrored } = __nccwpck_require__(3983) +const { isUint8Array, isArrayBuffer } = __nccwpck_require__(9830) +const { File: UndiciFile } = __nccwpck_require__(8511) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) + +let ReadableStream = globalThis.ReadableStream + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() + +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } + + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream. + stream = new ReadableStream({ + async pull (controller) { + controller.enqueue( + typeof source === 'string' ? textEncoder.encode(source) : source + ) + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: undefined + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength + } else { + hasUnknownSizeValue = true + } } - default: - self._debug - && self._debug('Inbound: Received unexpected payload type 60'); - } - }, - 61: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 61 without auth'); - return; } - /* - byte SSH_MSG_USERAUTH_INFO_RESPONSE - int num-responses - string response[1] (ISO-10646 UTF-8) - ... - string response[num-responses] (ISO-10646 UTF-8) - */ - if (self._authsQueue[0] !== 'keyboard-interactive') { - return doFatalError( - self, - 'Inbound: Received unexpected payload type 61' - ); + + const chunk = textEncoder.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null } - bufferParser.init(payload, 1); - const numResponses = bufferParser.readUInt32BE(); - let responses; - if (numResponses !== undefined) { - responses = new Array(numResponses); - let i; - for (i = 0; i < numResponses; ++i) { - const response = bufferParser.readString(true); - if (response === undefined) - break; - responses[i] = response; + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } } - if (i !== numResponses) - responses = undefined; } - bufferParser.clear(); - if (responses === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' - ); + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = 'multipart/form-data; boundary=' + boundary + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') } - self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } - const handler = self._handlers.USERAUTH_INFO_RESPONSE; - handler && handler(self, responses); - }, + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) + } - // Connection protocol -- generic ============================================ - [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_GLOBAL_REQUEST - string request name in US-ASCII only - boolean want reply - .... request-specific data follows - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (name) { - case 'tcpip-forward': - case 'cancel-tcpip-forward': { - /* - string address to bind (e.g., "0.0.0.0") - uint32 port number to bind - */ - const bindAddr = bufferParser.readString(true); - const bindPort = bufferParser.readUInt32BE(); - if (bindPort !== undefined) - data = { bindAddr, bindPort }; - break; - } - case 'streamlocal-forward@openssh.com': - case 'cancel-streamlocal-forward@openssh.com': { - /* - string socket path - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) - data = { socketPath }; - break; - } - case 'no-more-sessions@openssh.com': - data = null; - break; - case 'hostkeys-00@openssh.com': { - data = []; - while (bufferParser.avail() > 0) { - const keyRaw = bufferParser.readString(); - if (keyRaw === undefined) { - data = undefined; - break; - } - const key = parseKey(keyRaw); - if (!(key instanceof Error)) - data.push(key); + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + async pull (controller) { + const { value, done } = await iterator.next() + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + controller.enqueue(new Uint8Array(value)) } - break; } - default: - data = bufferParser.readRaw(); + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: undefined + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } + + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.') + // istanbul ignore next + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee() + const out2Clone = structuredClone(out2, { transfer: [out2] }) + // This, for whatever reasons, unrefs out2Clone which allows + // the process to exit by itself. + const [, finalClone] = out2Clone.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } +} + +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body + } else { + const stream = body.stream + + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') } - } - bufferParser.clear(); - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed GLOBAL_REQUEST packet' - ); + if (stream.locked) { + throw new TypeError('The stream is locked.') + } + + // Compat. + stream[kBodyUsed] = true + + yield * stream } + } +} - self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } +} - const handler = self._handlers.GLOBAL_REQUEST; - if (handler) - handler(self, name, wantReply, data); - else - self.requestFailure(); // Auto reject - }, - [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_SUCCESS - .... response specific data - */ - const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); +function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return specConsumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this) + + if (mimeType === 'failure') { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } - self._debug && self._debug('Inbound: REQUEST_SUCCESS'); + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, - const handler = self._handlers.REQUEST_SUCCESS; - handler && handler(self, data); - }, - [MESSAGE.REQUEST_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_FAILURE - */ - self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return specConsumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, - const handler = self._handlers.REQUEST_FAILURE; - handler && handler(self); - }, + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return specConsumeBody(this, utf8DecodeBytes, instance) + }, - // Connection protocol -- channel-related ==================================== - [MESSAGE.CHANNEL_OPEN]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN - string channel type in US-ASCII only - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - bufferParser.init(payload, 1); - const type = bufferParser.readString(true); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - let channelInfo; + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return specConsumeBody(this, parseJSONFromBytes, instance) + }, - switch (type) { - case 'forwarded-tcpip': // S->C - case 'direct-tcpip': { // C->S - /* - string address that was connected / host to connect - uint32 port that was connected / port to connect - string originator IP address - uint32 originator port - */ - const destIP = bufferParser.readString(true); - const destPort = bufferParser.readUInt32BE(); - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { destIP, destPort, srcIP, srcPort } - }; - } - break; - } - case 'forwarded-streamlocal@openssh.com': // S->C - case 'direct-streamlocal@openssh.com': { // C->S - /* - string socket path - string reserved for future use + async formData () { + webidl.brandCheck(this, instance) - (direct-streamlocal@openssh.com additionally has:) - uint32 reserved - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { socketPath } - }; + throwIfAborted(this[kState]) + + const contentType = this.headers.get('Content-Type') + + // If mimeType’s essence is "multipart/form-data", then: + if (/multipart\/form-data/.test(contentType)) { + const headers = {} + for (const [key, value] of this.headers) headers[key.toLowerCase()] = value + + const responseFormData = new FormData() + + let busboy + + try { + busboy = new Busboy({ + headers, + preservePath: true + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') } - break; - } - case 'x11': { // S->C - /* - string originator address (e.g., "192.168.7.38") - uint32 originator port - */ - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { srcIP, srcPort } - }; + + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = [] + + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' + + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') + + const end = base64chunk.length - base64chunk.length % 4 + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) + + base64chunk = base64chunk.slice(end) + }) + value.on('end', () => { + chunks.push(Buffer.from(base64chunk, 'base64')) + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } else { + value.on('data', (chunk) => { + chunks.push(chunk) + }) + value.on('end', () => { + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } + }) + + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve) + busboy.on('error', (err) => reject(new TypeError(err))) + }) + + if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) + busboy.end() + await busboyResolve + + return responseFormData + } else if (/application\/x-www-form-urlencoded/.test(contentType)) { + // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: + + // 1. Let entries be the result of parsing bytes. + let entries + try { + let text = '' + // application/x-www-form-urlencoded parser will keep the BOM. + // https://url.spec.whatwg.org/#concept-urlencoded-parser + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) + + for await (const chunk of consumeBody(this[kState].body)) { + if (!isUint8Array(chunk)) { + throw new TypeError('Expected Uint8Array chunk') + } + text += streamingDecoder.decode(chunk, { stream: true }) + } + text += streamingDecoder.decode() + entries = new URLSearchParams(text) + } catch (err) { + // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. + // 2. If entries is failure, then throw a TypeError. + throw Object.assign(new TypeError(), { cause: err }) } - break; + + // 3. Return a new FormData object whose entries are entries. + const formData = new FormData() + for (const [name, value] of entries) { + formData.append(name, value) + } + return formData + } else { + // Wait a tick before checking if the request has been aborted. + // Otherwise, a TypeError can be thrown when an AbortError should. + await Promise.resolve() + + throwIfAborted(this[kState]) + + // Otherwise, throw a TypeError. + throw webidl.errors.exception({ + header: `${instance.name}.formData`, + message: 'Could not parse content as FormData.' + }) } - default: - // Includes: - // 'session' (C->S) - // 'auth-agent@openssh.com' (S->C) - channelInfo = { - type, - sender, - window, - packetSize, - data: {} - }; } - bufferParser.clear(); + } - if (channelInfo === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN packet' - ); + return methods +} + +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ +async function specConsumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance) + + throwIfAborted(object[kState]) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') + } + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error) + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) } + } - self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(new Uint8Array()) + return promise.promise + } - const handler = self._handlers.CHANNEL_OPEN; - if (handler) { - handler(self, channelInfo); - } else { - self.channelOpenFail( - channelInfo.sender, - CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, - '', - '' - ); + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +// https://fetch.spec.whatwg.org/#body-unusable +function bodyUnusable (body) { + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) + + // 4. Return output. + return output +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} object + */ +function bodyMimeType (object) { + const { headersList } = object[kState] + const contentType = headersList.get('content-type') + + if (contentType === null) { + return 'failure' + } + + return parseMIMEType(contentType) +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody +} + + +/***/ }), + +/***/ 1037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(1267) + +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + +const nullBodyStatus = [101, 204, 205, 304] + +const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) + +// https://fetch.spec.whatwg.org/#block-bad-port +const badPorts = [ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', + '10080' +] + +const badPortsSet = new Set(badPorts) + +// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies +const referrerPolicy = [ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +] +const referrerPolicySet = new Set(referrerPolicy) + +const requestRedirect = ['follow', 'manual', 'error'] + +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) + +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + +const requestCredentials = ['omit', 'same-origin', 'include'] + +const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +] + +// https://fetch.spec.whatwg.org/#request-body-header-name +const requestBodyHeader = [ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' +] + +// https://fetch.spec.whatwg.org/#enumdef-requestduplex +const requestDuplex = [ + 'half' +] + +// http://fetch.spec.whatwg.org/#forbidden-method +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) + +const subresource = [ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +] +const subresourceSet = new Set(subresource) + +/** @type {globalThis['DOMException']} */ +const DOMException = globalThis.DOMException ?? (() => { + // DOMException was only made a global in Node v17.0.0, + // but fetch supports >= v16.8. + try { + atob('~') + } catch (err) { + return Object.getPrototypeOf(err).constructor + } +})() + +let channel + +/** @type {globalThis['structuredClone']} */ +const structuredClone = + globalThis.structuredClone ?? + // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js + // structuredClone was added in v17.0.0, but fetch supports v16.8 + function structuredClone (value, options = undefined) { + if (arguments.length === 0) { + throw new TypeError('missing argument') } - }, - [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION - uint32 recipient channel - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - // "The 'recipient channel' is the channel number given in the - // original open request, and 'sender channel' is the channel number - // allocated by the other side." - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); - bufferParser.clear(); - if (packetSize === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' - ); + if (!channel) { + channel = new MessageChannel() } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message + } - self._debug && self._debug( - `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` - ); +module.exports = { + DOMException, + structuredClone, + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet +} - const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; - if (handler) - handler(self, { recipient, sender, window, packetSize, data }); - }, - [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_FAILURE - uint32 recipient channel - uint32 reason code - string description in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const reason = bufferParser.readUInt32BE(); - const description = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' - ); - } +/***/ }), - self._debug - && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); +/***/ 685: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const handler = self._handlers.CHANNEL_OPEN_FAILURE; - handler && handler(self, recipient, reason, description); - }, - [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_WINDOW_ADJUST - uint32 recipient channel - uint32 bytes to add - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const bytesToAdd = bufferParser.readUInt32BE(); - bufferParser.clear(); +const assert = __nccwpck_require__(9491) +const { atob } = __nccwpck_require__(4300) +const { isomorphicDecode } = __nccwpck_require__(2538) - if (bytesToAdd === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' - ); - } +const encoder = new TextEncoder() - self._debug && self._debug( - `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` - ); +/** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ +const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ +const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line +/** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ +const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line - const handler = self._handlers.CHANNEL_WINDOW_ADJUST; - handler && handler(self, recipient, bytesToAdd); - }, - [MESSAGE.CHANNEL_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_DATA - uint32 recipient channel - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_DATA packet' - ); - } + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) - self._debug - && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); + // 3. Remove the leading "data:" string from input. + input = input.slice(5) - const handler = self._handlers.CHANNEL_DATA; - handler && handler(self, recipient, data); - }, - [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EXTENDED_DATA - uint32 recipient channel - uint32 data_type_code - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); + // 4. Let position point at the start of input. + const position = { position: 0 } - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' - ); - } + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) - self._debug && self._debug( - `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` - ); + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = removeASCIIWhitespace(mimeType, true, true) - const handler = self._handlers.CHANNEL_EXTENDED_DATA; - handler && handler(self, recipient, data, type); - }, - [MESSAGE.CHANNEL_EOF]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EOF - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EOF packet' - ); - } + // 8. Advance position by 1. + position.position++ - self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) - const handler = self._handlers.CHANNEL_EOF; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_CLOSE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_CLOSE packet' - ); + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' } - self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) - const handler = self._handlers.CHANNEL_CLOSE; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_REQUEST - uint32 recipient channel - string request type in US-ASCII characters only - boolean want reply - .... type-specific data follows - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (type) { - case 'exit-status': // S->C - /* - uint32 exit_status - */ - data = bufferParser.readUInt32BE(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'exit-signal': { // S->C - /* - string signal name (without the "SIG" prefix) - boolean core dumped - string error message in ISO-10646 UTF-8 encoding - string language tag - */ - let signal; - let coreDumped; - if (self._compatFlags & COMPAT.OLD_EXIT) { - /* - Instead of `signal name` and `core dumped`, we have just: - uint32 signal number - */ - const num = bufferParser.readUInt32BE(); - switch (num) { - case 1: - signal = 'HUP'; - break; - case 2: - signal = 'INT'; - break; - case 3: - signal = 'QUIT'; - break; - case 6: - signal = 'ABRT'; - break; - case 9: - signal = 'KILL'; - break; - case 14: - signal = 'ALRM'; - break; - case 15: - signal = 'TERM'; - break; - default: - if (num !== undefined) { - // Unknown or OS-specific - signal = `UNKNOWN (${num})`; - } - } - coreDumped = false; - } else { - signal = bufferParser.readString(true); - coreDumped = bufferParser.readBool(); - if (coreDumped === undefined) - signal = undefined; - } - const errorMessage = bufferParser.readString(true); - if (bufferParser.skipString() !== undefined) - data = { signal, coreDumped, errorMessage }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` - ); - break; - } - case 'pty-req': { // C->S - /* - string TERM environment variable value (e.g., vt100) - uint32 terminal width, characters (e.g., 80) - uint32 terminal height, rows (e.g., 24) - uint32 terminal width, pixels (e.g., 640) - uint32 terminal height, pixels (e.g., 480) - string encoded terminal modes - */ - const term = bufferParser.readString(true); - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - const modesBinary = bufferParser.readString(); - if (modesBinary !== undefined) { - bufferParser.init(modesBinary, 1); - let modes = {}; - while (bufferParser.avail()) { - const opcode = bufferParser.readByte(); - if (opcode === TERMINAL_MODE.TTY_OP_END) - break; - const name = TERMINAL_MODE_BY_VALUE[opcode]; - const value = bufferParser.readUInt32BE(); - if (opcode === undefined - || name === undefined - || value === undefined) { - modes = undefined; - break; - } - modes[name] = value; - } - if (modes !== undefined) - data = { term, cols, rows, width, height, modes }; - } - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'window-change': { // C->S - /* - uint32 terminal width, columns - uint32 terminal height, rows - uint32 terminal width, pixels - uint32 terminal height, pixels - */ - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - if (height !== undefined) - data = { cols, rows, width, height }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'x11-req': { // C->S - /* - boolean single connection - string x11 authentication protocol - string x11 authentication cookie - uint32 x11 screen number - */ - const single = bufferParser.readBool(); - const protocol = bufferParser.readString(true); - const cookie = bufferParser.readString(); - const screen = bufferParser.readUInt32BE(); - if (screen !== undefined) - data = { single, protocol, cookie, screen }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'env': { // C->S - /* - string variable name - string variable value - */ - const name = bufferParser.readString(true); - const value = bufferParser.readString(true); - if (value !== undefined) - data = { name, value }; - if (self._debug) { - self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` - + `${name}=${value})` - ); - } - break; - } - case 'shell': // C->S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - case 'exec': // C->S - /* - string command - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'subsystem': // C->S - /* - string subsystem name - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'signal': // C->S - /* - string signal name (without the "SIG" prefix) - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'xon-xoff': // C->S - /* - boolean client can do - */ - data = bufferParser.readBool(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'auth-agent-req@openssh.com': // C-S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - default: - data = (bufferParser.avail() ? bufferParser.readRaw() : null); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} + +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } + + const href = url.href + const hashLength = url.hash.length + + return hashLength === 0 ? href : href.substring(0, href.length - hashLength) +} + +// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] + + // 2. Advance position by 1. + position.position++ + } + + // 3. Return result. + return result +} + +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position + + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + // 1. Let output be an empty byte sequence. + /** @type {number[]} */ + const output = [] + + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) + ) { + output.push(0x25) + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) + const bytePoint = Number.parseInt(nextTwoBytes, 16) + + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) + + // 3. Skip the next two bytes in input. + i += 2 + } + } + + // 3. Return output. + return Uint8Array.from(output) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true) + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ } - bufferParser.clear(); - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_REQUEST packet' - ); + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break } - const handler = self._handlers.CHANNEL_REQUEST; - handler && handler(self, recipient, type, wantReply, data); - }, - [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_SUCCESS - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); + // 7. Let parameterValue be null. + let parameterValue = null - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_SUCCESS packet' - ); + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } } - self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } + } - const handler = self._handlers.CHANNEL_SUCCESS; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_FAILURE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); + // 12. Return mimeType. + return mimeType +} - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_FAILURE packet' - ); +// https://infra.spec.whatwg.org/#forgiving-base64-decode +/** @param {string} data */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line + + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (data.length % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + data = data.replace(/=?=$/, '') + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (data.length % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data)) { + return 'failure' + } + + const binary = atob(data) + const bytes = new Uint8Array(binary.length) + + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) + } + + return bytes +} + +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ +function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position + + // 2. Let value be the empty string. + let value = '' + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + + // 4. Advance position by 1. + position.position++ + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break } - self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] - const handler = self._handlers.CHANNEL_FAILURE; - handler && handler(self, recipient); - }, -}; + // 4. Advance position by 1. + position.position++ + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } -/***/ }), + // 2. Append the code point at position within input to value. + value += input[position.position] -/***/ 4126: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 3. Advance position by 1. + position.position++ -"use strict"; + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + // 2. Break. + break + } + } -const { - createDiffieHellman, - createDiffieHellmanGroup, - createECDH, - createHash, - createPublicKey, - diffieHellman, - generateKeyPairSync, - randomFillSync, -} = __nccwpck_require__(6113); + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } -const { Ber } = __nccwpck_require__(970); + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} -const { - COMPAT, - curve25519Supported, - DEFAULT_KEX, - DEFAULT_SERVER_HOST_KEY, - DEFAULT_CIPHER, - DEFAULT_MAC, - DEFAULT_COMPRESSION, - DISCONNECT_REASON, - MESSAGE, -} = __nccwpck_require__(6832); -const { - CIPHER_INFO, - createCipher, - createDecipher, - MAC_INFO, -} = __nccwpck_require__(5708); -const { parseDERKey } = __nccwpck_require__(2218); -const { - bufferFill, - bufferParser, - convertSignature, - doFatalError, - FastBuffer, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(9475); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = __nccwpck_require__(6715); +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType -let MESSAGE_HANDLERS; + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence -const GEX_MIN_BITS = 2048; // RFC 8270 -const GEX_MAX_BITS = 8192; // RFC 8270 + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' -const EMPTY_BUFFER = Buffer.alloc(0); + // 2. Append name to serialization. + serialization += name -// Client/Server -function kexinit(self) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ + // 3. Append U+003D (=) to serialization. + serialization += '=' - let payload; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - const entry = self._offer.lists.kex; - let kex = entry.array; - let found = false; - for (let i = 0; i < kex.length; ++i) { - if (kex[i].includes('group-exchange')) { - if (!found) { - found = true; - // Copy array lazily - kex = kex.slice(); + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value + } + + // 3. Return serialization. + return serialization +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} char + */ +function isHTTPWhiteSpace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === ' ' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + */ +function removeHTTPWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) +} + +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {string} char + */ +function isASCIIWhitespace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' +} + +/** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + */ +function removeASCIIWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) +} + +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} + + +/***/ }), + +/***/ 8511: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { Blob, File: NativeFile } = __nccwpck_require__(4300) +const { types } = __nccwpck_require__(3837) +const { kState } = __nccwpck_require__(5861) +const { isBlobLike } = __nccwpck_require__(2538) +const { webidl } = __nccwpck_require__(1744) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const encoder = new TextEncoder() + +class File extends Blob { + constructor (fileBits, fileName, options = {}) { + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) + + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // 2. Convert every character in t to ASCII lowercase. + let t = options.type + let d + + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) + + if (t === 'failure') { + t = '' + // eslint-disable-next-line no-labels + break substep } - kex.splice(i--, 1); + + t = serializeAMimeType(t).toLowerCase() } + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + d = options.lastModified } - if (found) { - let len = 1 + 16 + self._offer.totalSize + 1 + 4; - const newKexBuf = Buffer.from(kex.join(',')); - len -= (entry.buffer.length - newKexBuf.length); - const all = self._offer.lists.all; - const rest = new Uint8Array( - all.buffer, - all.byteOffset + 4 + entry.buffer.length, - all.length - (4 + entry.buffer.length) - ); + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. - payload = Buffer.allocUnsafe(len); - writeUInt32BE(payload, newKexBuf.length, 17); - payload.set(newKexBuf, 17 + 4); - payload.set(rest, 17 + 4 + newKexBuf.length); + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t } } - if (payload === undefined) { - payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); - self._offer.copyAllTo(payload, 17); + get name () { + webidl.brandCheck(this, File) + + return this[kState].name } - self._debug && self._debug('Outbound: Sending KEXINIT'); + get lastModified () { + webidl.brandCheck(this, File) - payload[0] = MESSAGE.KEXINIT; - randomFillSync(payload, 1, 16); + return this[kState].lastModified + } - // Zero-fill first_kex_packet_follows and reserved bytes - bufferFill(payload, 0, payload.length - 5); + get type () { + webidl.brandCheck(this, File) - self._kexinit = payload; + return this[kState].type + } +} - // Needed to correct the starting position in allocated "packets" when packets - // will be buffered due to active key exchange - self._packetRW.write.allocStart = 0; +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check - // TODO: only create single buffer and set _kexinit as slice of packet instead - { - const p = self._packetRW.write.allocStartKEX; - const packet = self._packetRW.write.alloc(payload.length, true); - packet.set(payload, p); - self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type + + // 2. Convert every character in t to ASCII lowercase. + // TODO + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now() + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } + + stream (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.stream(...args) + } + + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.arrayBuffer(...args) + } + + slice (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.slice(...args) + } + + text (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.text(...args) + } + + get size () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.size + } + + get type () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.type + } + + get name () { + webidl.brandCheck(this, FileLike) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, FileLike) + + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' } } -function handleKexInit(self, payload) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - const init = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - }; +Object.defineProperties(File.prototype, { + [Symbol.toStringTag]: { + value: 'File', + configurable: true + }, + name: kEnumerableProperty, + lastModified: kEnumerableProperty +}) - bufferParser.init(payload, 17); +webidl.converters.Blob = webidl.interfaceConverter(Blob) - if ((init.kex = bufferParser.readList()) === undefined - || (init.serverHostKey = bufferParser.readList()) === undefined - || (init.cs.cipher = bufferParser.readList()) === undefined - || (init.sc.cipher = bufferParser.readList()) === undefined - || (init.cs.mac = bufferParser.readList()) === undefined - || (init.sc.mac = bufferParser.readList()) === undefined - || (init.cs.compress = bufferParser.readList()) === undefined - || (init.sc.compress = bufferParser.readList()) === undefined - || (init.cs.lang = bufferParser.readList()) === undefined - || (init.sc.lang = bufferParser.readList()) === undefined) { - bufferParser.clear(); - return doFatalError( - self, - 'Received malformed KEXINIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); +webidl.converters.BlobPart = function (V, opts) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) + ) { + return webidl.converters.BufferSource(V, opts) + } } - const pos = bufferParser.pos(); - const firstFollows = (pos < payload.length && payload[pos] === 1); - bufferParser.clear(); + return webidl.converters.USVString(V, opts) +} - const local = self._offer; - const remote = init; +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.BlobPart +) - let localKex = local.lists.kex.array; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - let found = false; - for (let i = 0; i < localKex.length; ++i) { - if (localKex[i].indexOf('group-exchange') !== -1) { - if (!found) { - found = true; - // Copy array lazily - localKex = localKex.slice(); - } - localKex.splice(i--, 1); +// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag +webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ + { + key: 'lastModified', + converter: webidl.converters['long long'], + get defaultValue () { + return Date.now() + } + }, + { + key: 'type', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'endings', + converter: (value) => { + value = webidl.converters.DOMString(value) + value = value.toLowerCase() + + if (value !== 'native') { + value = 'transparent' + } + + return value + }, + defaultValue: 'transparent' + } +]) + +/** + * @see https://www.w3.org/TR/FileAPI/#process-blob-parts + * @param {(NodeJS.TypedArray|Blob|string)[]} parts + * @param {{ type: string, endings: string }} options + */ +function processBlobParts (parts, options) { + // 1. Let bytes be an empty sequence of bytes. + /** @type {NodeJS.TypedArray[]} */ + const bytes = [] + + // 2. For each element in parts: + for (const element of parts) { + // 1. If element is a USVString, run the following substeps: + if (typeof element === 'string') { + // 1. Let s be element. + let s = element + + // 2. If the endings member of options is "native", set s + // to the result of converting line endings to native + // of element. + if (options.endings === 'native') { + s = convertLineEndingsNative(s) + } + + // 3. Append the result of UTF-8 encoding s to bytes. + bytes.push(encoder.encode(s)) + } else if ( + types.isAnyArrayBuffer(element) || + types.isTypedArray(element) + ) { + // 2. If element is a BufferSource, get a copy of the + // bytes held by the buffer source, and append those + // bytes to bytes. + if (!element.buffer) { // ArrayBuffer + bytes.push(new Uint8Array(element)) + } else { + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ) } + } else if (isBlobLike(element)) { + // 3. If element is a Blob, append the bytes it represents + // to bytes. + bytes.push(element) } } - let clientList; - let serverList; - let i; - const debug = self._debug; + // 3. Return bytes. + return bytes +} - debug && debug('Inbound: Handshake in progress'); +/** + * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native + * @param {string} s + */ +function convertLineEndingsNative (s) { + // 1. Let native line ending be be the code point U+000A LF. + let nativeLineEnding = '\n' - // Key exchange method ======================================================= - debug && debug(`Handshake: (local) KEX method: ${localKex}`); - debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); - if (self._server) { - serverList = localKex; - clientList = remote.kex; - } else { - serverList = remote.kex; - clientList = localKex; + // 2. If the underlying platform’s conventions are to + // represent newlines as a carriage return and line feed + // sequence, set native line ending to the code point + // U+000D CR followed by the code point U+000A LF. + if (process.platform === 'win32') { + nativeLineEnding = '\r\n' } - // Check for agreeable key exchange algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching key exchange algorithm'); - return doFatalError( - self, - 'Handshake failed: no matching key exchange algorithm', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + return s.replace(/\r?\n/g, nativeLineEnding) +} + +// If this function is moved to ./util.js, some tools (such as +// rollup) will warn about circular dependencies. See: +// https://github.com/nodejs/undici/issues/1629 +function isFileLike (object) { + return ( + (NativeFile && object instanceof NativeFile) || + object instanceof File || ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) +} + +module.exports = { File, FileLike, isFileLike } + + +/***/ }), + +/***/ 2015: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(2538) +const { kState } = __nccwpck_require__(5861) +const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(8511) +const { webidl } = __nccwpck_require__(1744) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile + +// https://xhr.spec.whatwg.org/#formdata +class FormData { + constructor (form) { + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + + this[kState] = [] } - init.kex = clientList[i]; - debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); - if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { - // Ignore next inbound packet, it was a wrong first guess at KEX algorithm - self._skipNextInboundPacket = true; + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? webidl.converters.USVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) + + // 3. Append entry to this’s entry list. + this[kState].push(entry) } + delete (name) { + webidl.brandCheck(this, FormData) - // Server host key format ==================================================== - const localSrvHostKey = local.lists.serverHostKey.array; - debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); - debug && debug( - `Handshake: (remote) Host key format: ${remote.serverHostKey}` - ); - if (self._server) { - serverList = localSrvHostKey; - clientList = remote.serverHostKey; - } else { - serverList = remote.serverHostKey; - clientList = localSrvHostKey; + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) + + name = webidl.converters.USVString(name) + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this[kState] = this[kState].filter(entry => entry.name !== name) } - // Check for agreeable server host key format - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching host key format'); - return doFatalError( - self, - 'Handshake failed: no matching host key format', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + get (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) } - init.serverHostKey = clientList[i]; - debug && debug(`Handshake: Host key format: ${clientList[i]}`); + has (name) { + webidl.brandCheck(this, FormData) - // Client->Server cipher ===================================================== - const localCSCipher = local.lists.cs.cipher.array; - debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); - debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); - if (self._server) { - serverList = localCSCipher; - clientList = remote.cs.cipher; - } else { - serverList = remote.cs.cipher; - clientList = localCSCipher; + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) + + name = webidl.converters.USVString(name) + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 } - // Check for agreeable client->server cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S cipher'); - return doFatalError( - self, - 'Handshake failed: no matching C->S cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? toUSVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry) + } } - init.cs.cipher = clientList[i]; - debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); + entries () { + webidl.brandCheck(this, FormData) - // Server->Client cipher ===================================================== - const localSCCipher = local.lists.sc.cipher.array; - debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); - debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); - if (self._server) { - serverList = localSCCipher; - clientList = remote.sc.cipher; - } else { - serverList = remote.sc.cipher; - clientList = localSCCipher; + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) } - // Check for agreeable server->client cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C cipher'); - return doFatalError( - self, - 'Handshake failed: no matching S->C cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + keys () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key' + ) } - init.sc.cipher = clientList[i]; - debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); + values () { + webidl.brandCheck(this, FormData) - // Client->Server MAC ======================================================== - const localCSMAC = local.lists.cs.mac.array; - debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); - debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); - if (CIPHER_INFO[init.cs.cipher].authLen > 0) { - init.cs.mac = ''; - debug && debug('Handshake: C->S MAC: '); - } else { - if (self._server) { - serverList = localCSMAC; - clientList = remote.cs.mac; - } else { - serverList = remote.cs.mac; - clientList = localCSMAC; + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' + ) + } + + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) } - // Check for agreeable client->server hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S MAC'); - return doFatalError( - self, - 'Handshake failed: no matching C->S MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) } - init.cs.mac = clientList[i]; - debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); } +} +FormData.prototype[Symbol.iterator] = FormData.prototype.entries - // Server->Client MAC ======================================================== - const localSCMAC = local.lists.sc.mac.array; - debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); - debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); - if (CIPHER_INFO[init.sc.cipher].authLen > 0) { - init.sc.mac = ''; - debug && debug('Handshake: S->C MAC: '); +Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // "To convert a string into a scalar value string, replace any surrogates + // with U+FFFD." + // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end + name = Buffer.from(name).toString('utf8') + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + value = Buffer.from(value).toString('utf8') } else { - if (self._server) { - serverList = localSCMAC; - clientList = remote.sc.mac; - } else { - serverList = remote.sc.mac; - clientList = localSCMAC; + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }) } - // Check for agreeable server->client hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C MAC'); - return doFatalError( - self, - 'Handshake failed: no matching S->C MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + } + + value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile + ? new File([value], filename, options) + : new FileLike(value, filename, options) } - init.sc.mac = clientList[i]; - debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); } + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} - // Client->Server compression ================================================ - const localCSCompress = local.lists.cs.compress.array; - debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); - debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); - if (self._server) { - serverList = localCSCompress; - clientList = remote.cs.compress; - } else { - serverList = remote.cs.compress; - clientList = localCSCompress; +module.exports = { FormData } + + +/***/ }), + +/***/ 1246: +/***/ ((module) => { + +"use strict"; + + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return } - // Check for agreeable client->server compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S compression'); - return doFatalError( - self, - 'Handshake failed: no matching C->S compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) } - init.cs.compress = clientList[i]; - debug && debug(`Handshake: C->S compression: ${clientList[i]}`); + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} - // Server->Client compression ================================================ - const localSCCompress = local.lists.sc.compress.array; - debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); - debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); - if (self._server) { - serverList = localSCCompress; - clientList = remote.sc.compress; +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} + + +/***/ }), + +/***/ 554: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// https://github.com/Ethan-Arrowood/undici-fetch + + + +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const { kGuard } = __nccwpck_require__(5861) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const { + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = __nccwpck_require__(2538) +const { webidl } = __nccwpck_require__(1744) +const assert = __nccwpck_require__(9491) + +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') + +/** + * @param {number} code + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length + + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +} + +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i] + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]) + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object) + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]) + } } else { - serverList = remote.sc.compress; - clientList = localSCCompress; + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) } - // Check for agreeable server->client compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C compression'); - return doFatalError( - self, - 'Handshake failed: no matching S->C compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + */ +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) } - init.sc.compress = clientList[i]; - debug && debug(`Handshake: S->C compression: ${clientList[i]}`); - init.cs.lang = ''; - init.sc.lang = ''; + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (headers[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (headers[kGuard] === 'request-no-cors') { + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + } - // XXX: hack -- find a better way to do this - if (self._kex) { - if (!self._kexinit) { - // We received a rekey request, but we haven't sent a KEXINIT in response - // yet - kexinit(self); + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + return headers[kHeadersList].append(name, value) + + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers +} + +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]) + this[kHeadersSortedMap] = init[kHeadersSortedMap] + this.cookies = init.cookies === null ? null : [...init.cookies] + } else { + this[kHeadersMap] = new Map(init) + this[kHeadersSortedMap] = null } - self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); } - self._kex = createKeyExchange(init, self, payload); - self._kex.start(); -} + // https://fetch.spec.whatwg.org/#header-list-contains + contains (name) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + name = name.toLowerCase() -const createKeyExchange = (() => { - function convertToMpint(buf) { - let idx = 0; - let length = buf.length; - while (buf[idx] === 0x00) { - ++idx; - --length; + return this[kHeadersMap].has(name) + } + + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null + } + + // https://fetch.spec.whatwg.org/#concept-header-list-append + append (name, value) { + this[kHeadersSortedMap] = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = name.toLowerCase() + const exists = this[kHeadersMap].get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this[kHeadersMap].set(lowercaseName, { name, value }) } - let newBuf; - if (buf[idx] & 0x80) { - newBuf = Buffer.allocUnsafe(1 + length); - newBuf[0] = 0; - buf.copy(newBuf, 1, idx); - buf = newBuf; - } else if (length !== buf.length) { - newBuf = Buffer.allocUnsafe(length); - buf.copy(newBuf, 0, idx); - buf = newBuf; + + if (lowercaseName === 'set-cookie') { + this.cookies ??= [] + this.cookies.push(value) } - return buf; } - class KeyExchange { - constructor(negotiated, protocol, remoteKexinit) { - this._protocol = protocol; - - this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); - this.negotiated = negotiated; - this._step = 1; - this._public = null; - this._dh = null; - this._sentNEWKEYS = false; - this._receivedNEWKEYS = false; - this._finished = false; - this._hostVerified = false; + // https://fetch.spec.whatwg.org/#concept-header-list-set + set (name, value) { + this[kHeadersSortedMap] = null + const lowercaseName = name.toLowerCase() - // Data needed for initializing cipher/decipher/etc. - this._kexinit = protocol._kexinit; - this._remoteKexinit = remoteKexinit; - this._identRaw = protocol._identRaw; - this._remoteIdentRaw = protocol._remoteIdentRaw; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; + if (lowercaseName === 'set-cookie') { + this.cookies = [value] } - finish() { - if (this._finished) - return false; - this._finished = true; - const isServer = this._protocol._server; - const negotiated = this.negotiated; + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this[kHeadersMap].set(lowercaseName, { name, value }) + } - const pubKey = this.convertPublicKey(this._dhData); - let secret = this.computeSecret(this._dhData); - if (secret instanceof Error) { - secret.message = - `Error while computing DH secret (${this.type}): ${secret.message}`; - secret.level = 'handshake'; - return doFatalError( - this._protocol, - secret, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // https://fetch.spec.whatwg.org/#concept-header-list-delete + delete (name) { + this[kHeadersSortedMap] = null - const hash = createHash(this.hashName); - // V_C - hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); - // "V_S" - hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); - // "I_C" - hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); - // "I_S" - hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); - // "K_S" - const serverPublicHostKey = (isServer - ? this._hostKey.getPublicSSH() - : this._hostKey); - hashString(hash, serverPublicHostKey); + name = name.toLowerCase() - if (this.type === 'groupex') { - // Group exchange-specific - const params = this.getDHParams(); - const num = Buffer.allocUnsafe(4); - // min (uint32) - writeUInt32BE(num, this._minBits, 0); - hash.update(num); - // preferred (uint32) - writeUInt32BE(num, this._prefBits, 0); - hash.update(num); - // max (uint32) - writeUInt32BE(num, this._maxBits, 0); - hash.update(num); - // prime - hashString(hash, params.prime); - // generator - hashString(hash, params.generator); - } + if (name === 'set-cookie') { + this.cookies = null + } - // method-specific data sent by client - hashString(hash, (isServer ? pubKey : this.getPublicKey())); - // method-specific data sent by server - const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); - hashString(hash, serverPublicKey); - // shared secret ("K") - hashString(hash, secret); + this[kHeadersMap].delete(name) + } - // "H" - const exchangeHash = hash.digest(); + // https://fetch.spec.whatwg.org/#concept-header-list-get + get (name) { + const value = this[kHeadersMap].get(name.toLowerCase()) - if (!isServer) { - bufferParser.init(this._sig, 0); - const sigType = bufferParser.readString(true); + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return value === undefined ? null : value.value + } - if (!sigType) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] + } + } - if (sigType !== negotiated.serverHostKey) { - return doFatalError( - this._protocol, - `Wrong signature type: ${sigType}, ` - + `expected: ${negotiated.serverHostKey}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + get entries () { + const headers = {} - // "s" - let sigValue = bufferParser.readString(); + if (this[kHeadersMap].size) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value + } + } - bufferParser.clear(); + return headers + } +} - if (sigValue === undefined) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + constructor (init = undefined) { + if (init === kConstruct) { + return + } + this[kHeadersList] = new HeadersList() - if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { - return doFatalError( - this._protocol, - 'Malformed signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // The new Headers(init) constructor steps are: - let parsedHostKey; - { - bufferParser.init(this._hostKey, 0); - const name = bufferParser.readString(true); - const hostKey = this._hostKey.slice(bufferParser.pos()); - bufferParser.clear(); - parsedHostKey = parseDERKey(hostKey, name); - if (parsedHostKey instanceof Error) { - parsedHostKey.level = 'handshake'; - return doFatalError( - this._protocol, - parsedHostKey, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } + // 1. Set this’s guard to "none". + this[kGuard] = 'none' - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init) + fill(this, init) + } + } - this._protocol._debug - && this._protocol._debug('Verifying signature ...'); + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) - const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); - if (verified !== true) { - if (verified instanceof Error) { - this._protocol._debug && this._protocol._debug( - `Signature verification failed: ${verified.stack}` - ); - } else { - this._protocol._debug && this._protocol._debug( - 'Signature verification failed' - ); - } - return doFatalError( - this._protocol, - 'Handshake failed: signature verification failed', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug('Verified signature'); - } else { - // Server + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) - this._protocol._debug && this._protocol._debug( - 'Generating signature ...' - ); + return appendHeader(this, name, value) + } - let signature = this._hostKey.sign(exchangeHash, hashAlgo); - if (signature instanceof Error) { - return doFatalError( - this._protocol, - 'Handshake failed: signature generation failed for ' - + `${this._hostKey.type} host key: ${signature.message}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } - signature = convertSignature(signature, this._hostKey.type); - if (signature === false) { - return doFatalError( - this._protocol, - 'Handshake failed: signature conversion failed for ' - + `${this._hostKey.type} host key`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return + } - // Send KEX reply - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - const sigType = this.negotiated.serverHostKey; - const sigTypeLen = Buffer.byteLength(sigType); - const sigLen = 4 + sigTypeLen + 4 + signature.length; - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 - + 4 + serverPublicHostKey.length - + 4 + serverPublicKey.length - + 4 + sigLen, - true - ); + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this[kHeadersList].delete(name) + } - packet[p] = MESSAGE.KEXDH_REPLY; + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) - writeUInt32BE(packet, serverPublicHostKey.length, ++p); - packet.set(serverPublicHostKey, p += 4); + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) - writeUInt32BE(packet, - serverPublicKey.length, - p += serverPublicHostKey.length); - packet.set(serverPublicKey, p += 4); + name = webidl.converters.ByteString(name) - writeUInt32BE(packet, sigLen, p += serverPublicKey.length); + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.get', + value: name, + type: 'header name' + }) + } - writeUInt32BE(packet, sigTypeLen, p += 4); - packet.utf8Write(sigType, p += 4, sigTypeLen); + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) + } - writeUInt32BE(packet, signature.length, p += sigTypeLen); - packet.set(signature, p += 4); + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_REPLY'; - break; - case 'groupex': - type = 'KEXDH_GEX_REPLY'; - break; - default: - type = 'KEXECDH_REPLY'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - trySendNEWKEYS(this); + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) - const completeHandshake = () => { - if (!this.sessionID) - this.sessionID = exchangeHash; + name = webidl.converters.ByteString(name) - { - const newSecret = Buffer.allocUnsafe(4 + secret.length); - writeUInt32BE(newSecret, secret.length, 0); - newSecret.set(secret, 4); - secret = newSecret; - } + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.has', + value: name, + type: 'header name' + }) + } - // Initialize new ciphers, deciphers, etc. + // 2. Return true if this’s header list contains name; + // otherwise false. + return this[kHeadersList].contains(name) + } - const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; - const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) - const csIV = generateKEXVal(csCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'A'); - const scIV = generateKEXVal(scCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'B'); - const csKey = generateKEXVal(csCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'C'); - const scKey = generateKEXVal(scCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'D'); - let csMacInfo; - let csMacKey; - if (!csCipherInfo.authLen) { - csMacInfo = MAC_INFO[negotiated.cs.mac]; - csMacKey = generateKEXVal(csMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'E'); - } - let scMacInfo; - let scMacKey; - if (!scCipherInfo.authLen) { - scMacInfo = MAC_INFO[negotiated.sc.mac]; - scMacKey = generateKEXVal(scMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'F'); - } + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) - const config = { - inbound: { - onPayload: this._protocol._onPayload, - seqno: this._protocol._decipher.inSeqno, - decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), - decipherIV: (!isServer ? scIV : csIV), - decipherKey: (!isServer ? scKey : csKey), - macInfo: (!isServer ? scMacInfo : csMacInfo), - macKey: (!isServer ? scMacKey : csMacKey), - }, - outbound: { - onWrite: this._protocol._onWrite, - seqno: this._protocol._cipher.outSeqno, - cipherInfo: (isServer ? scCipherInfo : csCipherInfo), - cipherIV: (isServer ? scIV : csIV), - cipherKey: (isServer ? scKey : csKey), - macInfo: (isServer ? scMacInfo : csMacInfo), - macKey: (isServer ? scMacKey : csMacKey), - }, - }; - this._protocol._cipher && this._protocol._cipher.free(); - this._protocol._decipher && this._protocol._decipher.free(); - this._protocol._cipher = createCipher(config); - this._protocol._decipher = createDecipher(config); + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) - const rw = { - read: undefined, - write: undefined, - }; - switch (negotiated.cs.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication + // 1. Normalize value. + value = headerValueNormalize(value) - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value, + type: 'header value' + }) + } - if (isServer) - rw.read = new PacketReader(); - else - rw.write = new PacketWriter(this._protocol); - } - switch (negotiated.sc.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this[kHeadersList].set(name, value) + } - if (isServer) - rw.write = new PacketWriter(this._protocol); - else - rw.read = new PacketReader(); - } - this._protocol._packetRW.read.cleanup(); - this._protocol._packetRW.write.cleanup(); - this._protocol._packetRW = rw; + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) - // Cleanup/reset various state - this._public = null; - this._dh = null; - this._kexinit = this._protocol._kexinit = undefined; - this._remoteKexinit = undefined; - this._identRaw = undefined; - this._remoteIdentRaw = undefined; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. - this._protocol._onHandshakeComplete(negotiated); + const list = this[kHeadersList].cookies - return false; - }; - if (!isServer) - return completeHandshake(); - this.finish = completeHandshake; + if (list) { + return [...list] } - start() { - if (!this._protocol._server) { - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_INIT'; - break; - default: - type = 'KEXECDH_INIT'; - } - this._protocol._debug(`Outbound: Sending ${type}`); + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) + const cookies = this[kHeadersList].cookies + + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const [name, value] = names[i] + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]) } + } else { + // 2. Otherwise: - const pubKey = this.getPublicKey(); + // 1. Let value be the result of getting name from list. - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + pubKey.length, - true - ); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); + // 2. Assert: value is non-null. + assert(value !== null) + + // 3. Append (name, value) to headers. + headers.push([name, value]) } } - getPublicKey() { - this.generateKeys(); - const key = this._public; + this[kHeadersList][kHeadersSortedMap] = headers - if (key) - return this.convertPublicKey(key); + // 4. Return headers. + return headers + } + + keys () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key') } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - if (key[idx] & 0x80) { - newKey = Buffer.allocUnsafe(1 + len); - newKey[0] = 0; - key.copy(newKey, 1, idx); - return newKey; - } + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; + values () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'value') } - computeSecret(otherPublicKey) { - this.generateKeys(); - try { - return convertToMpint(this._dh.computeSecret(otherPublicKey)); - } catch (ex) { - return ex; - } + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } + + entries () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key+value') } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - // Server - if (type !== MESSAGE.KEXDH_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Init' - ); - /* - byte SSH_MSG_KEXDH_INIT - / SSH_MSG_KEX_ECDH_INIT - string - */ - bufferParser.init(payload, 1); - const dhData = bufferParser.readString(); - bufferParser.clear(); - if (dhData === undefined) { - return doFatalError( - this._protocol, - 'Received malformed KEX*_INIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - // Client public key - this._dhData = dhData; + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) + } - let hostKey = - this._protocol._hostKeys[this.negotiated.serverHostKey]; - if (Array.isArray(hostKey)) - hostKey = hostKey[0]; - this._hostKey = hostKey; + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers) - this.finish(); - } else { - // Client - if (type !== MESSAGE.KEXDH_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Reply' - ); - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - bufferParser.init(payload, 1); - let hostPubKey; - let dhData; - let sig; - if ((hostPubKey = bufferParser.readString()) === undefined - || (dhData = bufferParser.readString()) === undefined - || (sig = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEX*_REPLY', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) - // Check that the host public key type matches what was negotiated - // during KEXINIT swap - bufferParser.init(hostPubKey, 0); - const hostPubKeyType = bufferParser.readString(true); - bufferParser.clear(); - if (hostPubKeyType === undefined) { - return doFatalError( - this._protocol, - 'Received malformed host public key', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (hostPubKeyType !== this.negotiated.serverHostKey) { - // Check if we need to make an exception - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': - case 'rsa-sha2-512': - if (hostPubKeyType === 'ssh-rsa') - break; - // FALLTHROUGH - default: - return doFatalError( - this._protocol, - 'Host key does not match negotiated type', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." + ) + } - this._hostKey = hostPubKey; - this._dhData = dhData; - this._sig = sig; + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } - let checked = false; - let ret; - if (this._protocol._hostVerifier === undefined) { - ret = true; - this._protocol._debug && this._protocol._debug( - 'Host accepted by default (no verification)' - ); - } else { - ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { - if (checked) - return; - checked = true; - if (permitted === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - if (this._receivedNEWKEYS) - this.finish(); - else - trySendNEWKEYS(this); - }); - } - if (ret === undefined) { - // Async host verification - ++this._step; - return; - } - checked = true; - if (ret === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - trySendNEWKEYS(this); - } - ++this._step; - break; - case 2: - if (type !== MESSAGE.NEWKEYS) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Inbound: NEWKEYS' - ); - this._receivedNEWKEYS = true; - ++this._step; - if (this._protocol._server || this._hostVerified) - return this.finish(); + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) - // Signal to current decipher that we need to change to a new decipher - // for the next packet - return false; - default: - return doFatalError( - this._protocol, - `Received unexpected packet ${type} after NEWKEYS`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + return this[kHeadersList] + } +} + +Headers.prototype[Symbol.iterator] = Headers.prototype.entries + +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + keys: kEnumerableProperty, + values: kEnumerableProperty, + entries: kEnumerableProperty, + forEach: kEnumerableProperty, + [Symbol.iterator]: { enumerable: false }, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + } +}) + +webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) } + + return webidl.converters['record'](V) } - class Curve25519Exchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} - this.type = '25519'; - this.hashName = hashName; - this._keys = null; - } - generateKeys() { - if (!this._keys) - this._keys = generateKeyPairSync('x25519'); +module.exports = { + fill, + Headers, + HeadersList +} + + +/***/ }), + +/***/ 4881: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// https://github.com/Ethan-Arrowood/undici-fetch + + + +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = __nccwpck_require__(7823) +const { Headers } = __nccwpck_require__(554) +const { Request, makeRequest } = __nccwpck_require__(8359) +const zlib = __nccwpck_require__(9796) +const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme +} = __nccwpck_require__(2538) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const assert = __nccwpck_require__(9491) +const { safelyExtractBody } = __nccwpck_require__(1472) +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet, + DOMException +} = __nccwpck_require__(1037) +const { kHeadersList } = __nccwpck_require__(2785) +const EE = __nccwpck_require__(2361) +const { Readable, pipeline } = __nccwpck_require__(2781) +const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3983) +const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(685) +const { TransformStream } = __nccwpck_require__(5356) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { webidl } = __nccwpck_require__(1744) +const { STATUS_CODES } = __nccwpck_require__(3685) +const GET_OR_HEAD = ['GET', 'HEAD'] + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + // 2 terminated listeners get added per request, + // but only 1 gets removed. If there are 20 redirects, + // 21 listeners will be added. + // See https://github.com/nodejs/undici/issues/1711 + // TODO (fix): Find and fix root cause for leaked listener. + this.setMaxListeners(21) + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return } - getPublicKey() { - this.generateKeys(); - const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); - return key.slice(-32); // HACK: avoids parsing DER/BER header + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - if (key.length === 32) - return key; + // 1. Set controller’s state to "aborted". + this.state = 'aborted' - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') } - computeSecret(otherPublicKey) { - this.generateKeys(); - try { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.110'); // id-X25519 - asnWriter.endSequence(); + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(otherPublicKey.length); - otherPublicKey.copy(asnWriter._buf, - asnWriter._offset, - 0, - otherPublicKey.length); - asnWriter._offset += otherPublicKey.length; - asnWriter.endSequence(); - asnWriter.endSequence(); + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error - return convertToMpint(diffieHellman({ - privateKey: this._keys.privateKey, - publicKey: createPublicKey({ - key: asnWriter.buffer, - type: 'spki', - format: 'der', - }), - })); - } catch (ex) { - return ex; - } - } + this.connection?.destroy(error) + this.emit('terminated', error) } +} - class ECDHExchange extends KeyExchange { - constructor(curveName, hashName, ...args) { - super(...args); +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) - this.type = 'ecdh'; - this.curveName = curveName; - this.hashName = hashName; - } - generateKeys() { - if (!this._dh) { - this._dh = createECDH(this.curveName); - this._public = this._dh.generateKeys(); - } - } + // 1. Let p be a new promise. + const p = createDeferredPromise() + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject + + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise } - class DHGroupExchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); + // 3. Let request be requestObject’s request. + const request = requestObject[kState] - this.type = 'groupex'; - this.hashName = hashName; - this._prime = null; - this._generator = null; - this._minBits = GEX_MIN_BITS; - this._prefBits = dhEstimate(this.negotiated); - if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) - this._prefBits = Math.min(this._prefBits, 4096); - this._maxBits = GEX_MAX_BITS; - } - start() { - if (this._protocol._server) - return; - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_REQUEST' - ); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + 4 + 4, - true - ); - packet[p] = MESSAGE.KEXDH_GEX_REQUEST; - writeUInt32BE(packet, this._minBits, ++p); - writeUInt32BE(packet, this._prefBits, p += 4); - writeUInt32BE(packet, this._maxBits, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } + + // 7. Let responseObject be null. + let responseObject = null + + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null + + // 9. Let locallyAborted be false. + let locallyAborted = false + + // 10. Let controller be null. + let controller = null + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true + + // 2. Assert: controller is non-null. + assert(controller != null) + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason) } - generateKeys() { - if (!this._dh && this._prime && this._generator) { - this._dh = createDiffieHellman(this._prime, this._generator); - this._public = this._dh.generateKeys(); - } + ) + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch') + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() } - setDHParams(prime, generator) { - if (!Buffer.isBuffer(prime)) - throw new Error('Invalid prime value'); - if (!Buffer.isBuffer(generator)) - throw new Error('Invalid generator value'); - this._prime = prime; - this._generator = generator; + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return Promise.resolve() } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject( + Object.assign(new TypeError('fetch failed'), { cause: response.error }) + ) + return Promise.resolve() } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_REQUEST) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ` - + MESSAGE.KEXDH_GEX_REQUEST, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - // TODO: allow user implementation to provide safe prime and - // generator on demand to support group exchange on server side - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (type !== MESSAGE.KEXDH_GEX_GROUP) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new Response() + responseObject[kState] = response + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Group' - ); + // 5. Resolve p with responseObject. + p.resolve(responseObject) + } - /* - byte SSH_MSG_KEX_DH_GEX_GROUP - mpint p, safe prime - mpint g, generator for subgroup in GF(p) - */ - bufferParser.init(payload, 1); - let prime; - let gen; - if ((prime = bufferParser.readString()) === undefined - || (gen = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEXDH_GEX_GROUP', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) - // TODO: validate prime - this.setDHParams(prime, gen); - this.generateKeys(); - const pubkey = this.getPublicKey(); + // 14. Return p. + return p.promise +} - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_INIT' - ); +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); - packet[p] = MESSAGE.KEXDH_GEX_INIT; - writeUInt32BE(packet, pubkey.length, ++p); - packet.set(pubkey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } - ++this._step; - break; - case 2: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Init' - ); - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Reply' - ); - this._step = 1; - payload[0] = MESSAGE.KEXDH_REPLY; - this.parse = KeyExchange.prototype.parse; - this.parse(payload); + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { + if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { + performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) + } +} + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // Note: AbortSignal.reason was added in node v17.2.0 + // which would give us an undefined error to reject with. + // Remove this once node v16 is no longer supported. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 1. Reject promise with error. + p.reject(error) + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return } - } + throw err + }) } - class DHExchange extends KeyExchange { - constructor(groupName, hashName, ...args) { - super(...args); + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } - this.type = 'group'; - this.groupName = groupName; - this.hashName = hashName; - } - start() { - if (!this._protocol._server) { - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_INIT' - ); - const pubKey = this.getPublicKey(); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); + // 4. Let response be responseObject’s response. + const response = responseObject[kState] + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return } + throw err + }) + } +} + +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher // undici +}) { + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currenTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + // TODO: What if request.client is null? + request.origin = request.client?.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() } - generateKeys() { - if (!this._dh) { - this._dh = createDiffieHellmanGroup(this.groupName); - this._public = this._dh.generateKeys(); + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value) + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language')) { + request.headersList.append('accept-language', '*') + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } + + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO + } + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) + + // 17. Return fetchParam's controller + return fetchParams.controller +} + +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only') + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request) + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) } - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; + + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') } - } - } - return (negotiated, ...args) => { - if (typeof negotiated !== 'object' || negotiated === null) - throw new Error('Invalid negotiated argument'); - const kexType = negotiated.kex; - if (typeof kexType === 'string') { - args = [negotiated, ...args]; - switch (kexType) { - case 'curve25519-sha256': - case 'curve25519-sha256@libssh.org': - if (!curve25519Supported) - break; - return new Curve25519Exchange('sha256', ...args); + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } - case 'ecdh-sha2-nistp256': - return new ECDHExchange('prime256v1', 'sha256', ...args); - case 'ecdh-sha2-nistp384': - return new ECDHExchange('secp384r1', 'sha384', ...args); - case 'ecdh-sha2-nistp521': - return new ECDHExchange('secp521r1', 'sha512', ...args); + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' - case 'diffie-hellman-group1-sha1': - return new DHExchange('modp2', 'sha1', ...args); - case 'diffie-hellman-group14-sha1': - return new DHExchange('modp14', 'sha1', ...args); - case 'diffie-hellman-group14-sha256': - return new DHExchange('modp14', 'sha256', ...args); - case 'diffie-hellman-group15-sha512': - return new DHExchange('modp15', 'sha512', ...args); - case 'diffie-hellman-group16-sha512': - return new DHExchange('modp16', 'sha512', ...args); - case 'diffie-hellman-group17-sha512': - return new DHExchange('modp17', 'sha512', ...args); - case 'diffie-hellman-group18-sha512': - return new DHExchange('modp18', 'sha512', ...args); + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } - case 'diffie-hellman-group-exchange-sha1': - return new DHGroupExchange('sha1', ...args); - case 'diffie-hellman-group-exchange-sha256': - return new DHGroupExchange('sha256', ...args); + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') } - throw new Error(`Unsupported key exchange algorithm: ${kexType}`); - } - throw new Error(`Invalid key exchange type: ${kexType}`); - }; -})(); -const KexInit = (() => { - const KEX_PROPERTY_NAMES = [ - 'kex', - 'serverHostKey', - ['cs', 'cipher' ], - ['sc', 'cipher' ], - ['cs', 'mac' ], - ['sc', 'mac' ], - ['cs', 'compress' ], - ['sc', 'compress' ], - ['cs', 'lang' ], - ['sc', 'lang' ], - ]; - return class KexInit { - constructor(obj) { - if (typeof obj !== 'object' || obj === null) - throw new TypeError('Argument must be an object'); + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO - const lists = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' - all: undefined, - }; - let totalSize = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let base; - let val; - let desc; - let key; - if (typeof prop === 'string') { - base = lists; - val = obj[prop]; - desc = key = prop; - } else { - const parent = prop[0]; - base = lists[parent]; - key = prop[1]; - val = obj[parent][key]; - desc = `${parent}.${key}`; - } - const entry = { array: undefined, buffer: undefined }; - if (Buffer.isBuffer(val)) { - entry.array = ('' + val).split(','); - entry.buffer = val; - totalSize += 4 + val.length; - } else { - if (typeof val === 'string') - val = val.split(','); - if (Array.isArray(val)) { - entry.array = val; - entry.buffer = Buffer.from(val.join(',')); - } else { - throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); - } - totalSize += 4 + entry.buffer.length; - } - base[key] = entry; + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range') + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return } - const all = Buffer.allocUnsafe(totalSize); - lists.all = all; + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] - let allPos = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let data; - if (typeof prop === 'string') - data = lists[prop].buffer; - else - data = lists[prop[0]][prop[1]].buffer; - allPos = writeUInt32BE(all, data.length, allPos); - all.set(data, allPos); - allPos += data.length; - } + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } - this.totalSize = totalSize; - this.lists = lists; + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } +} + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) } - copyAllTo(buf, offset) { - const src = this.lists.all; - if (typeof offset !== 'number') - throw new TypeError(`Invalid offset value: ${typeof offset}`); - if (buf.length - offset < src.length) - throw new Error('Insufficient space to copy list'); - buf.set(src, offset); - return src.length; + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = (__nccwpck_require__(4300).resolveObjectURL) + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) + + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] + + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) + + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' + + // 7. Return a new response whose status message is `OK`, header list is + // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. + const response = makeResponse({ + statusText: 'OK', + headersList: [ + ['content-length', { name: 'Content-Length', value: length }], + ['content-type', { name: 'Content-Type', value: type }] + ] + }) + + response.body = body + + return Promise.resolve(response) } - }; -})(); + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) -const hashString = (() => { - const LEN = Buffer.allocUnsafe(4); - return (hash, buf) => { - writeUInt32BE(LEN, buf.length, 0); - hash.update(LEN); - hash.update(buf); - }; -})(); + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } -function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { - let ret; - if (len) { - let digest = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(char) - .update(sessionID) - .digest(); - while (digest.length < len) { - const chunk = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(digest) - .digest(); - const extended = Buffer.allocUnsafe(digest.length + chunk.length); - extended.set(digest, 0); - extended.set(chunk, digest.length); - digest = extended; + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) } - if (digest.length === len) - ret = digest; - else - ret = new FastBuffer(digest.buffer, digest.byteOffset, len); - } else { - ret = EMPTY_BUFFER; } - return ret; } -function onKEXPayload(state, payload) { - // XXX: move this to the Decipher implementations? - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) } +} - if (this._skipNextInboundPacket) { - this._skipNextInboundPacket = false; - return; +// https://fetch.spec.whatwg.org/#fetch-finale +function fetchFinale (fetchParams, response) { + // 1. If response is a network error, then: + if (response.type === 'error') { + // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». + response.urlList = [fetchParams.request.urlList[0]] + + // 2. Set response’s timing info to the result of creating an opaque timing + // info for fetchParams’s timing info. + response.timingInfo = createOpaqueTimingInfo({ + startTime: fetchParams.timingInfo.startTime + }) } - payload = this._packetRW.read.read(payload); + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true - const type = payload[0]; - switch (type) { - case MESSAGE.DISCONNECT: - case MESSAGE.IGNORE: - case MESSAGE.UNIMPLEMENTED: - case MESSAGE.DEBUG: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = __nccwpck_require__(172); - return MESSAGE_HANDLERS[type](this, payload); - case MESSAGE.KEXINIT: - if (!state.firstPacket) { - return doFatalError( - this, - 'Received extra KEXINIT during handshake', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + // If fetchParams’s process response end-of-body is not null, + // then queue a fetch task to run fetchParams’s process response + // end-of-body given response with fetchParams’s task destination. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + } + + // 3. If fetchParams’s process response is non-null, then queue a fetch task + // to run fetchParams’s process response given response, with fetchParams’s + // task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => fetchParams.processResponse(response)) + } + + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: + + // 1. Let transformStream be a new a TransformStream. + + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) + } + + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm + // and flushAlgorithm set to processResponseEndOfBody. + const transformStream = new TransformStream({ + start () {}, + transform: identityTransformAlgorithm, + flush: processResponseEndOfBody + }, { + size () { + return 1 } - state.firstPacket = false; - return handleKexInit(this, payload); - default: - if (type < 20 || type > 49) { - return doFatalError( - this, - `Received unexpected packet type ${type}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + }, { + size () { + return 1 } + }) + + // 4. Set response’s body to the result of piping response’s body through transformStream. + response.body = { stream: response.body.stream.pipeThrough(transformStream) } } - return this._kex.parse(payload); -} + // 6. If fetchParams’s process response consume body is non-null, then: + if (fetchParams.processResponseConsumeBody != null) { + // 1. Let processBody given nullOrBytes be this step: run fetchParams’s + // process response consume body given response and nullOrBytes. + const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) -function dhEstimate(neg) { - const csCipher = CIPHER_INFO[neg.cs.cipher]; - const scCipher = CIPHER_INFO[neg.sc.cipher]; - // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will - // also need to be considered when calculating `bits` - const bits = Math.max( - 0, - (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), - csCipher.blockLen, - csCipher.ivLen, - (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), - scCipher.blockLen, - scCipher.ivLen - ) * 8; - if (bits <= 112) - return 2048; - if (bits <= 128) - return 3072; - if (bits <= 192) - return 7680; - return 8192; + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) + + // 3. If response’s body is null, then queue a fetch task to run processBody + // given null, with fetchParams’s task destination. + if (response.body == null) { + queueMicrotask(() => processBody(null)) + } else { + // 4. Otherwise, fully read response’s body given processBody, processBodyError, + // and fetchParams’s task destination. + return fullyReadBody(response.body, processBody, processBodyError) + } + return Promise.resolve() + } } -function trySendNEWKEYS(kex) { - if (!kex._sentNEWKEYS) { - kex._protocol._debug && kex._protocol._debug( - 'Outbound: Sending NEWKEYS' - ); - const p = kex._protocol._packetRW.write.allocStartKEX; - const packet = kex._protocol._packetRW.write.alloc(1, true); - packet[p] = MESSAGE.NEWKEYS; - kex._protocol._cipher.encrypt( - kex._protocol._packetRW.write.finalize(packet, true) - ); - kex._sentNEWKEYS = true; +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let actualResponse be null. + let actualResponse = null + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy() + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response } -module.exports = { - KexInit, - kexinit, - onKEXPayload, - DEFAULT_KEXINIT: new KexInit({ - kex: DEFAULT_KEX, - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - }), - HANDLERS: { - [MESSAGE.KEXINIT]: handleKexInit, - }, -}; +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response -/***/ }), + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL -/***/ 2218: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) -"use strict"; -// TODO: -// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` -// * handle multi-line header values (OpenSSH)? -// * more thorough validation? + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } -const { - createDecipheriv, - createECDH, - createHash, - createHmac, - createSign, - createVerify, - getCiphers, - sign: sign_, - verify: verify_, -} = __nccwpck_require__(6113); -const supportedOpenSSLCiphers = getCiphers(); + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } -const { Ber } = __nccwpck_require__(970); -const bcrypt_pbkdf = (__nccwpck_require__(5447).pbkdf); + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 -const { CIPHER_INFO } = __nccwpck_require__(5708); -const { eddsaSupported, SUPPORTED_CIPHER } = __nccwpck_require__(6832); -const { - bufferSlice, - makeBufferParser, - readString, - readUInt32BE, - writeUInt32BE, -} = __nccwpck_require__(9475); + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } -const SYM_HASH_ALGO = Symbol('Hash Algorithm'); -const SYM_PRIV_PEM = Symbol('Private key PEM'); -const SYM_PUB_PEM = Symbol('Public key PEM'); -const SYM_PUB_SSH = Symbol('Public key SSH'); -const SYM_DECRYPTED = Symbol('Decrypted Key'); + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } -// Create OpenSSL cipher name -> SSH cipher name conversion table -const CIPHER_INFO_OPENSSL = Object.create(null); -{ - const keys = Object.keys(CIPHER_INFO); - for (let i = 0; i < keys.length; ++i) { - const cipherName = CIPHER_INFO[keys[i]].sslName; - if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) - continue; - CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) } -} -const binaryKeyParser = makeBufferParser(); + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null -function makePEM(type, data) { - data = data.base64Slice(0, data.length); - let formatted = data.replace(/.{64}/g, '$&\n'); - if (data.length & 63) - formatted += '\n'; - return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; -} + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) + } + } -function combineBuffers(buf1, buf2) { - const result = Buffer.allocUnsafe(buf1.length + buf2.length); - result.set(buf1, 0); - result.set(buf2, buf1.length); - return result; -} + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization') -function skipFields(buf, nfields) { - const bufLen = buf.length; - let pos = (buf._pos || 0); - for (let i = 0; i < nfields; ++i) { - const left = (bufLen - pos); - if (pos >= bufLen || left < 4) - return false; - const len = readUInt32BE(buf, pos); - if (left < 4 + len) - return false; - pos += 4 + len; + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') } - buf._pos = pos; - return true; -} -function genOpenSSLRSAPub(n, e) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption - // algorithm parameters (RSA has none) - asnWriter.writeNull(); - asnWriter.endSequence(); + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null) + request.body = safelyExtractBody(request.body.source)[0] + } - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.startSequence(); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo -function genOpenSSHRSAPub(n, e) { - const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-rsa', 4, 7); + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } - let i = 4 + 7; - writeUInt32BE(publicKey, e.length, i); - publicKey.set(e, i += 4); + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) - writeUInt32BE(publicKey, n.length, i += e.length); - publicKey.set(n, i + 4); + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) - return publicKey; -} + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request -const genOpenSSLRSAPriv = (() => { - function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.writeBuffer(d, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(dmp1, Ber.Integer); - asnWriter.writeBuffer(dmq1, Ber.Integer); - asnWriter.writeBuffer(iqmp, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest } - function bigIntFromBuffer(buf) { - return BigInt(`0x${buf.hexSlice(0, buf.length)}`); + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' } - function bigIntToBuffer(bn) { - let hex = bn.toString(16); - if ((hex.length & 1) !== 0) { - hex = `0${hex}`; + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent')) { + httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since') || + httpRequest.headersList.contains('if-none-match') || + httpRequest.headersList.contains('if-unmodified-since') || + httpRequest.headersList.contains('if-match') || + httpRequest.headersList.contains('if-range')) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control') + ) { + httpRequest.headersList.append('cache-control', 'max-age=0') + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma')) { + httpRequest.headersList.append('pragma', 'no-cache') + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control')) { + httpRequest.headersList.append('cache-control', 'no-cache') + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range')) { + httpRequest.headersList.append('accept-encoding', 'identity') + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding')) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') } else { - const sigbit = hex.charCodeAt(0); - // BER/DER integers require leading zero byte to denote a positive value - // when first byte >= 0x80 - if (sigbit === 56/* '8' */ - || sigbit === 57/* '9' */ - || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { - hex = `00${hex}`; - } + httpRequest.headersList.append('accept-encoding', 'gzip, deflate') } - return Buffer.from(hex, 'hex'); } - return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { - const bn_d = bigIntFromBuffer(d); - const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); - const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); - return makePEM('RSA PRIVATE', - genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); - }; -})(); + httpRequest.headersList.delete('host') -function genOpenSSLDSAPub(p, q, g, y) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa - // algorithm parameters - asnWriter.startSequence(); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); + // 20. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + // 2. If httpRequest’s header list does not contain `Authorization`, then: + // TODO: credentials + } - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication -function genOpenSSHDSAPub(p, q, g, y) { - const publicKey = Buffer.allocUnsafe( - 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length - ); + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-dss', 4, 7); + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } - let i = 4 + 7; - writeUInt32BE(publicKey, p.length, i); - publicKey.set(p, i += 4); + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache + } - writeUInt32BE(publicKey, q.length, i += p.length); - publicKey.set(q, i += 4); + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO - writeUInt32BE(publicKey, g.length, i += q.length); - publicKey.set(g, i += 4); + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.mode === 'only-if-cached') { + return makeNetworkError('only if cached') + } - writeUInt32BE(publicKey, y.length, i += g.length); - publicKey.set(y, i + 4); + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) - return publicKey; -} + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } -function genOpenSSLDSAPriv(p, q, g, y, x) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.writeBuffer(x, Ber.Integer); - asnWriter.endSequence(); - return makePEM('DSA PRIVATE', asnWriter.buffer); -} + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } -function genOpenSSLEdPub(pub) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response } -function genOpenSSHEdPub(pub) { - const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) - writeUInt32BE(publicKey, 11, 0); - publicKey.utf8Write('ssh-ed25519', 4, 11); + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err) { + if (!this.destroyed) { + this.destroyed = true + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) + } + } + } - writeUInt32BE(publicKey, pub.length, 15); - publicKey.set(pub, 19); + // 1. Let request be fetchParams’s request. + const request = fetchParams.request - return publicKey; -} + // 2. Let response be null. + let response = null -function genOpenSSLEdPriv(priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x00, Ber.Integer); + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null - // PrivateKey - asnWriter.startSequence(Ber.OctetString); - asnWriter.writeBuffer(priv, Ber.OctetString); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PRIVATE', asnWriter.buffer); -} + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } -function genOpenSSLECDSAPub(oid, Q) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey - // algorithm parameters (namedCurve) - asnWriter.writeOID(oid); - asnWriter.endSequence(); + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(Q.length); - asnWriter._buf.set(Q, asnWriter._offset); - asnWriter._offset += Q.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars -function genOpenSSHECDSAPub(oid, Q) { - let curveName; - switch (oid) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - curveName = 'nistp256'; - break; - case '1.3.132.0.34': - // secp384r1 - curveName = 'nistp384'; - break; - case '1.3.132.0.35': - // secp521r1 - curveName = 'nistp521'; - break; - default: - return; + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO } - const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); + // 9. Run these steps, but abort when the ongoing fetch is terminated: - writeUInt32BE(publicKey, 19, 0); - publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); + // 1. If connection is failure, then return a network error. - writeUInt32BE(publicKey, 8, 23); - publicKey.utf8Write(curveName, 27, 8); + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. - writeUInt32BE(publicKey, Q.length, 35); - publicKey.set(Q, 39); + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. - return publicKey; -} + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. -function genOpenSSLECDSAPriv(oid, pub, priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x01, Ber.Integer); - // privateKey - asnWriter.writeBuffer(priv, Ber.OctetString); - // parameters (optional) - asnWriter.startSequence(0xA0); - asnWriter.writeOID(oid); - asnWriter.endSequence(); - // publicKey (optional) - asnWriter.startSequence(0xA1); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('EC PRIVATE', asnWriter.buffer); -} + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: -function genOpenSSLECDSAPubFromPriv(curveName, priv) { - const tempECDH = createECDH(curveName); - tempECDH.setPrivateKey(priv); - return tempECDH.getPublicKey(); -} + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] -const BaseKey = { - sign: (() => { - if (typeof sign_ === 'function') { - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return sign_(algo, data, pem); - } catch (ex) { - return ex; - } - }; - } - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const signature = createSign(algo); - signature.update(data); - try { - return signature.sign(pem); - } catch (ex) { - return ex; - } - }; - })(), - verify: (() => { - if (typeof verify_ === 'function') { - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return verify_(algo, data, pem, signature); - } catch (ex) { - return ex; - } - }; - } - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const verifier = createVerify(algo); - verifier.update(data); - try { - return verifier.verify(pem, signature); - } catch (ex) { - return ex; - } - }; - })(), - isPrivateKey: function isPrivateKey() { - return (this[SYM_PRIV_PEM] !== null); - }, - getPrivatePEM: function getPrivatePEM() { - return this[SYM_PRIV_PEM]; - }, - getPublicPEM: function getPublicPEM() { - return this[SYM_PUB_PEM]; - }, - getPublicSSH: function getPublicSSH() { - return this[SYM_PUB_SSH]; - }, - equals: function equals(key) { - const parsed = parseKey(key); - if (parsed instanceof Error) - return false; - return ( - this.type === parsed.type - && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] - && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] - && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH] - ); - }, -}; + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). -function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; - OpenSSH_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let ret; - const data = Buffer.from(m[1], 'base64'); - if (data.length < 31) // magic (+ magic null term.) + minimum field lengths - return new Error('Malformed OpenSSH private key'); - const magic = data.utf8Slice(0, 15); - if (magic !== 'openssh-key-v1\0') - return new Error(`Unsupported OpenSSH key magic: ${magic}`); + // - Wait until all the headers are transmitted. - const cipherName = readString(data, 15, true); - if (cipherName === undefined) - return new Error('Malformed OpenSSH private key'); - if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) - return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. - const kdfName = readString(data, data._pos, true); - if (kdfName === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'none') { - if (cipherName === 'none') - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'bcrypt') - return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); - if (!passphrase) { - return new Error( - 'Encrypted private OpenSSH key detected, but no passphrase given' - ); - } - } else if (cipherName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. - let encInfo; - let cipherKey; - let cipherIV; - if (cipherName !== 'none') - encInfo = CIPHER_INFO[cipherName]; - const kdfOptions = readString(data, data._pos); - if (kdfOptions === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfOptions.length) { - switch (kdfName) { - case 'none': - return new Error('Malformed OpenSSH private key'); - case 'bcrypt': - /* - string salt - uint32 rounds - */ - const salt = readString(kdfOptions, 0); - if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) - return new Error('Malformed OpenSSH private key'); - const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); - const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); - const r = bcrypt_pbkdf(passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds); - if (r !== 0) - return new Error('Failed to generate information to decrypt key'); - cipherKey = bufferSlice(gen, 0, encInfo.keyLen); - cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); - break; + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return } - } else if (kdfName !== 'none') { - return new Error('Malformed OpenSSH private key'); + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) } - if (data._pos + 3 >= data.length) - return new Error('Malformed OpenSSH private key'); - const keyCount = readUInt32BE(data, data._pos); - data._pos += 4; + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } - if (keyCount > 0) { - // TODO: place sensible limit on max `keyCount` + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } - // Read public keys first - for (let i = 0; i < keyCount; ++i) { - const pubData = readString(data, data._pos); - if (pubData === undefined) - return new Error('Malformed OpenSSH private key'); - const type = readString(pubData, 0, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return } - let privBlob = readString(data, data._pos); - if (privBlob === undefined) - return new Error('Malformed OpenSSH private key'); + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } - if (cipherKey !== undefined) { - // Encrypted private key(s) - if (privBlob.length < encInfo.blockLen - || (privBlob.length % encInfo.blockLen) !== 0) { - return new Error('Malformed OpenSSH private key'); - } - try { - const options = { authTagLength: encInfo.authLen }; - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - cipherIV, - options); - if (encInfo.authLen > 0) { - if (data.length - data._pos < encInfo.authLen) - return new Error('Malformed OpenSSH private key'); - decipher.setAuthTag( - bufferSlice(data, data._pos, data._pos += encInfo.authLen) - ); - } - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) } + processEndOfBody() + } catch (err) { + processBodyError(err) } - // Nothing should we follow the private key(s), except a possible - // authentication tag for relevant ciphers - if (data._pos !== data.length) - return new Error('Malformed OpenSSH private key'); + })() + } - ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) } else { - ret = []; + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() + + response = makeResponse({ status, statusText, headersList }) } - if (ret instanceof Error) - return ret; - // This will need to change if/when OpenSSH ever starts storing multiple - // keys in their key files - return ret[0]; - }; + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() - function parseOpenSSHPrivKeys(data, nkeys, decrypted) { - const keys = []; - /* - uint32 checkint - uint32 checkint - string privatekey1 - string comment1 - string privatekey2 - string comment2 - ... - string privatekeyN - string commentN - char 1 - char 2 - char 3 - ... - char padlen % 255 - */ - if (data.length < 8) - return new Error('Malformed OpenSSH private key'); - const check1 = readUInt32BE(data, 0); - const check2 = readUInt32BE(data, 4); - if (check1 !== check2) { - if (decrypted) { - return new Error( - 'OpenSSH key integrity check failed -- bad passphrase?' - ); - } - return new Error('OpenSSH key integrity check failed'); + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) } - data._pos = 8; - let i; - let oid; - for (i = 0; i < nkeys; ++i) { - let algo; - let privPEM; - let pubPEM; - let pubSSH; - // The OpenSSH documentation for the key format actually lies, the - // entirety of the private key content is not contained with a string - // field, it's actually the literal contents of the private key, so to be - // able to find the end of the key data you need to know the layout/format - // of each key type ... - const type = readString(data, data._pos, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - switch (type) { - case 'ssh-rsa': { - /* - string n -- public - string e -- public - string d -- private - string iqmp -- private - string p -- private - string q -- private - */ - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH private key'); - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed OpenSSH private key'); - const d = readString(data, data._pos); - if (d === undefined) - return new Error('Malformed OpenSSH private key'); - const iqmp = readString(data, data._pos); - if (iqmp === undefined) - return new Error('Malformed OpenSSH private key'); - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); + return makeNetworkError(err) + } - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - /* - string p -- public - string q -- public - string g -- public - string y -- public - string x -- private - */ - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH private key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH private key'); - const x = readString(data, data._pos); - if (x === undefined) - return new Error('Malformed OpenSSH private key'); + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() + } - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - if (!eddsaSupported) - return new Error(`Unsupported OpenSSH private key type: ${type}`); - /* - * string public key - * string private key + public key - */ - const edpub = readString(data, data._pos); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH private key'); - const edpriv = readString(data, data._pos); - if (edpriv === undefined || edpriv.length !== 64) - return new Error('Malformed OpenSSH private key'); + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason) + } - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - /* - string curve name - string Q -- public - string d -- private - */ - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH private key'); - const ecpub = readString(data, data._pos); - if (ecpub === undefined) - return new Error('Malformed OpenSSH private key'); - const ecpriv = readString(data, data._pos); - if (ecpriv === undefined) - return new Error('Malformed OpenSSH private key'); + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to + // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } + + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller + }, + async pull (controller) { + await pullAlgorithm(controller) + }, + async cancel (reason) { + await cancelAlgorithm(reason) + } + }, + { + highWaterMark: 0, + size () { + return 1 + } + } + ) - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); - break; + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream } + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.on('terminated', onAborted) + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + let isFailure + try { + const { done, value } = await fetchParams.controller.next() + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true } - default: - return new Error(`Unsupported OpenSSH private key type: ${type}`); } - const privComment = readString(data, data._pos, true); - if (privComment === undefined) - return new Error('Malformed OpenSSH private key'); + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) - keys.push( - new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, - decrypted) - ); + finalizeResponse(fetchParams, response) + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } } - let cnt = 0; - for (i = data._pos; i < data.length; ++i) { - if (data[i] !== (++cnt % 255)) - return new Error('Malformed OpenSSH private key'); + } + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } } - return keys; + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() } -} + // 20. Return response. + return response -function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Old_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; - OpenSSH_Old_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let privBlob = Buffer.from(m[3], 'base64'); - let headers = m[2]; - let decrypted = false; - if (headers !== undefined) { - // encrypted key - headers = headers.split(/\r\n|\n/g); - for (let i = 0; i < headers.length; ++i) { - const header = headers[i]; - let sepIdx = header.indexOf(':'); - if (header.slice(0, sepIdx) === 'DEK-Info') { - const val = header.slice(sepIdx + 2); - sepIdx = val.indexOf(','); - if (sepIdx === -1) - continue; - const cipherName = val.slice(0, sepIdx).toLowerCase(); - if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort } - const encInfo = CIPHER_INFO_OPENSSL[cipherName]; - if (!encInfo) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); + }, + + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return } - const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); - if (cipherIV.length !== encInfo.ivLen) - return new Error('Malformed encrypted OpenSSH private key'); - if (!passphrase) { - return new Error( - 'Encrypted OpenSSH private key detected, but no passphrase given' - ); + + let codings = [] + let location = '' + + const headers = new Headers() + + // For H2, the headers are a plain JS object + // We distinguish between them and iterate accordingly + if (Array.isArray(headersList)) { + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()) + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers[kHeadersList].append(key, val) + } + } else { + const keys = Object.keys(headersList) + for (const key of keys) { + const val = headersList[key] + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers[kHeadersList].append(key, val) + } } - const ivSlice = bufferSlice(cipherIV, 0, 8); - let cipherKey = createHash('md5') - .update(passphrase) - .update(ivSlice) - .digest(); - while (cipherKey.length < encInfo.keyLen) { - cipherKey = combineBuffers( - cipherKey, - createHash('md5') - .update(cipherKey) - .update(passphrase) - .update(ivSlice) - .digest() - ); + + this.body = new Readable({ read: resume }) + + const decoders = [] + + const willFollow = request.redirect === 'follow' && + location && + redirectStatusSet.has(status) + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + for (const coding of codings) { + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'deflate') { + decoders.push(zlib.createInflate()) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress()) + } else { + decoders.length = 0 + break + } + } } - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - decrypted = true; - } catch (ex) { - return ex; + + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return } - } - } - } - let type; - let privPEM; - let pubPEM; - let pubSSH; - let algo; - let reader; - let errMsg = 'Malformed OpenSSH private key'; - if (decrypted) - errMsg += '. Bad passphrase?'; - switch (m[1]) { - case 'RSA': - type = 'ssh-rsa'; - privPEM = makePEM('RSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const n = reader.readString(Ber.Integer, true); - if (n === null) - return new Error(errMsg); - const e = reader.readString(Ber.Integer, true); - if (e === null) - return new Error(errMsg); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'DSA': - type = 'ssh-dss'; - privPEM = makePEM('DSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const p = reader.readString(Ber.Integer, true); - if (p === null) - return new Error(errMsg); - const q = reader.readString(Ber.Integer, true); - if (q === null) - return new Error(errMsg); - const g = reader.readString(Ber.Integer, true); - if (g === null) - return new Error(errMsg); - const y = reader.readString(Ber.Integer, true); - if (y === null) - return new Error(errMsg); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'EC': - let ecSSLName; - let ecPriv; - let ecOID; - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - ecPriv = reader.readString(Ber.OctetString, true); - reader.readByte(); // Skip "complex" context type byte - const offset = reader.readLength(); // Skip context length - if (offset !== null) { - reader._offset = offset; - ecOID = reader.readOID(); - if (ecOID === null) - return new Error(errMsg); - switch (ecOID) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - ecSSLName = 'prime256v1'; - type = 'ecdsa-sha2-nistp256'; - algo = 'sha256'; - break; - case '1.3.132.0.34': - // secp384r1 - ecSSLName = 'secp384r1'; - type = 'ecdsa-sha2-nistp384'; - algo = 'sha384'; - break; - case '1.3.132.0.35': - // secp521r1 - ecSSLName = 'secp521r1'; - type = 'ecdsa-sha2-nistp521'; - algo = 'sha512'; - break; - default: - return new Error(`Unsupported private key EC OID: ${ecOID}`); - } - } else { - return new Error(errMsg); + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) } - } catch { - return new Error(errMsg); + + fetchParams.controller.ended = true + + this.body.push(null) + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + this.body?.destroy(error) + + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } + + const headers = new Headers() + + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + + headers[kHeadersList].append(key, val) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }) + + return true } - privPEM = makePEM('EC PRIVATE', privBlob); - const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); - pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); - pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); - break; - } + } + )) + } +} - return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, - decrypted); - }; +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming } -function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -PPK_Private.prototype = BaseKey; -{ - const EMPTY_PASSPHRASE = Buffer.alloc(0); - const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - const PPK_PP1 = Buffer.from([0, 0, 0, 0]); - const PPK_PP2 = Buffer.from([0, 0, 0, 1]); - const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; - PPK_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = key type - // m[2] = encryption type - // m[3] = comment - // m[4] = base64-encoded public key data: - // for "ssh-rsa": - // string "ssh-rsa" - // mpint e (public exponent) - // mpint n (modulus) - // for "ssh-dss": - // string "ssh-dss" - // mpint p (modulus) - // mpint q (prime) - // mpint g (base number) - // mpint y (public key parameter: g^x mod p) - // m[5] = base64-encoded private key data: - // for "ssh-rsa": - // mpint d (private exponent) - // mpint p (prime 1) - // mpint q (prime 2) - // mpint iqmp ([inverse of q] mod p) - // for "ssh-dss": - // mpint x (private key parameter) - // m[6] = SHA1 HMAC over: - // string name of algorithm ("ssh-dss", "ssh-rsa") - // string encryption type - // string comment - // string public key data - // string private-plaintext (including the final padding) - const cipherName = m[2]; - const encrypted = (cipherName !== 'none'); - if (encrypted && !passphrase) { - return new Error( - 'Encrypted PPK private key detected, but no passphrase given' - ); - } +/***/ }), - let privBlob = Buffer.from(m[5], 'base64'); +/***/ 8359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (encrypted) { - const encInfo = CIPHER_INFO[cipherName]; - let cipherKey = combineBuffers( - createHash('sha1').update(PPK_PP1).update(passphrase).digest(), - createHash('sha1').update(PPK_PP2).update(passphrase).digest() - ); - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - PPK_IV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } - } +"use strict"; +/* globals AbortController */ - const type = m[1]; - const comment = m[3]; - const pubBlob = Buffer.from(m[4], 'base64'); - const mac = m[6]; - const typeLen = type.length; - const cipherNameLen = cipherName.length; - const commentLen = Buffer.byteLength(comment); - const pubLen = pubBlob.length; - const privLen = privBlob.length; - const macData = Buffer.allocUnsafe(4 + typeLen - + 4 + cipherNameLen - + 4 + commentLen - + 4 + pubLen - + 4 + privLen); - let p = 0; - writeUInt32BE(macData, typeLen, p); - macData.utf8Write(type, p += 4, typeLen); - writeUInt32BE(macData, cipherNameLen, p += typeLen); - macData.utf8Write(cipherName, p += 4, cipherNameLen); - writeUInt32BE(macData, commentLen, p += cipherNameLen); - macData.utf8Write(comment, p += 4, commentLen); - writeUInt32BE(macData, pubLen, p += commentLen); - macData.set(pubBlob, p += 4); - writeUInt32BE(macData, privLen, p += pubLen); - macData.set(privBlob, p + 4); +const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(1472) +const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(554) +const { FinalizationRegistry } = __nccwpck_require__(6436)() +const util = __nccwpck_require__(3983) +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer, + normalizeMethodRecord +} = __nccwpck_require__(2538) +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = __nccwpck_require__(1037) +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { URLSerializer } = __nccwpck_require__(685) +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(2361) + +let TransformStream = globalThis.TransformStream + +const kAbortController = Symbol('abortController') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) - if (!passphrase) - passphrase = EMPTY_PASSPHRASE; +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kConstruct) { + return + } - const calcMAC = createHmac( - 'sha1', - createHash('sha1') - .update('putty-private-key-file-mac-key') - .update(passphrase) - .digest() - ).update(macData).digest('hex'); + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) - if (calcMAC !== mac) { - if (encrypted) { - return new Error( - 'PPK private key integrity check failed -- bad passphrase?' - ); + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) + + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() } - return new Error('PPK private key integrity check failed'); } - let pubPEM; - let pubSSH; - let privPEM; - pubBlob._pos = 0; - skipFields(pubBlob, 1); // skip (duplicate) key type - switch (type) { - case 'ssh-rsa': { - const e = readString(pubBlob, pubBlob._pos); - if (e === undefined) - return new Error('Malformed PPK public key'); - const n = readString(pubBlob, pubBlob._pos); - if (n === undefined) - return new Error('Malformed PPK public key'); - const d = readString(privBlob, 0); - if (d === undefined) - return new Error('Malformed PPK private key'); - const p = readString(privBlob, privBlob._pos); - if (p === undefined) - return new Error('Malformed PPK private key'); - const q = readString(privBlob, privBlob._pos); - if (q === undefined) - return new Error('Malformed PPK private key'); - const iqmp = readString(privBlob, privBlob._pos); - if (iqmp === undefined) - return new Error('Malformed PPK private key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - break; + // 1. Let request be null. + let request = null + + // 2. Let fallbackMode be null. + let fallbackMode = null + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl + + // 4. Let signal be null. + let signal = null + + // 5. If input is a string, then: + if (typeof input === 'string') { + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) } - case 'ssh-dss': { - const p = readString(pubBlob, pubBlob._pos); - if (p === undefined) - return new Error('Malformed PPK public key'); - const q = readString(pubBlob, pubBlob._pos); - if (q === undefined) - return new Error('Malformed PPK public key'); - const g = readString(pubBlob, pubBlob._pos); - if (g === undefined) - return new Error('Malformed PPK public key'); - const y = readString(pubBlob, pubBlob._pos); - if (y === undefined) - return new Error('Malformed PPK public key'); - const x = readString(privBlob, 0); - if (x === undefined) - return new Error('Malformed PPK private key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - break; + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request) + + // 8. Set request to input’s request. + request = input[kState] + + // 9. Set signal to input’s signal. + signal = input[kSignal] } - return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', - encrypted); - }; -} + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin + // 8. Let window be "client". + let window = 'client' -function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -OpenSSH_Public.prototype = BaseKey; -{ - let regexp; - if (eddsaSupported) - regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - else - regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - OpenSSH_Public.parse = (str) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = full type - // m[2] = base type - // m[3] = base64-encoded public key - // m[4] = comment + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: this[kRealm].settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) - const fullType = m[1]; - const baseType = m[2]; - const data = Buffer.from(m[3], 'base64'); - const comment = (m[4] || ''); + const initHasKey = Object.keys(init).length !== 0 - const type = readString(data, data._pos, true); - if (type === undefined || type.indexOf(baseType) !== 0) - return new Error('Malformed OpenSSH public key'); + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } - return parseDER(data, baseType, comment, fullType); - }; -} + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false -function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -RFC4716_Public.prototype = BaseKey; -{ - const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; - const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; - const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; - const RE_HEADER_ENDS = /\\\r?\n/g; - RFC4716_Public.parse = (str) => { - let m = regexp.exec(str); - if (m === null) - return null; + // 4. Set request’s origin to "client". + request.origin = 'client' - const body = m[1]; - let dataStart = 0; - let comment = ''; + // 5. Set request’s referrer to "client" + request.referrer = 'client' - while (m = RE_HEADER.exec(body)) { - const headerName = m[1]; - const headerValue = m[2].replace(RE_HEADER_ENDS, ''); - if (headerValue.length > 1024) { - RE_HEADER.lastIndex = 0; - return new Error('Malformed RFC4716 public key'); - } + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' - dataStart = RE_HEADER.lastIndex; + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] - if (headerName.toLowerCase() === 'comment') { - comment = headerValue; - if (comment.length > 1 - && comment.charCodeAt(0) === 34/* '"' */ - && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { - comment = comment.slice(1, -1); + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) + ) { + request.referrer = 'client' + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer } } } - let data = body.slice(dataStart); - if (!RE_DATA.test(data)) - return new Error('Malformed RFC4716 public key'); - - data = Buffer.from(data, 'base64'); + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } - const type = readString(data, 0, true); - if (type === undefined) - return new Error('Malformed RFC4716 public key'); + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } - let pubPEM = null; - let pubSSH = null; - switch (type) { - case 'ssh-rsa': { - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed RFC4716 public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed RFC4716 public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed RFC4716 public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed RFC4716 public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - break; - } - default: - return new Error('Malformed RFC4716 public key'); + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) } - return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); - }; -} + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } -function parseDER(data, baseType, comment, fullType) { - if (!isSupportedKeyType(baseType)) - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } - let algo; - let oid; - let pubPEM = null; - let pubSSH = null; + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } - switch (baseType) { - case 'ssh-rsa': { - const e = readString(data, data._pos || 0); - if (e === undefined) - return new Error('Malformed OpenSSH public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - algo = 'sha1'; - break; + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect } - case 'ssh-dss': { - const p = readString(data, data._pos || 0); - if (p === undefined) - return new Error('Malformed OpenSSH public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - algo = 'sha1'; - break; + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) } - case 'ssh-ed25519': { - const edpub = readString(data, data._pos || 0); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - algo = null; - break; + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method + + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; + + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) } - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH public key'); - const ecpub = readString(data, data._pos || 0); - if (ecpub === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - break; - } - default: - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - } - return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); -} + // 3. Normalize method. + method = normalizeMethodRecord[method] ?? normalizeMethod(method) -function isSupportedKeyType(type) { - switch (type) { - case 'ssh-rsa': - case 'ssh-dss': - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': - return true; - case 'ssh-ed25519': - if (eddsaSupported) - return true; - // FALLTHROUGH - default: - return false; - } -} + // 4. Set request’s method to method. + request.method = method + } -function isParsedKey(val) { - if (!val) - return false; - return (typeof val[SYM_DECRYPTED] === 'boolean'); -} + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } -function parseKey(data, passphrase) { - if (isParsedKey(data)) - return data; + // 27. Set this’s request to request. + this[kState] = request - let origBuffer; - if (Buffer.isBuffer(data)) { - origBuffer = data; - data = data.utf8Slice(0, data.length).trim(); - } else if (typeof data === 'string') { - data = data.trim(); - } else { - return new Error('Key data must be a Buffer or string'); - } + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController() + this[kSignal] = ac.signal + this[kSignal][kRealm] = this[kRealm] - // eslint-disable-next-line eqeqeq - if (passphrase != undefined) { - if (typeof passphrase === 'string') - passphrase = Buffer.from(passphrase); - else if (!Buffer.isBuffer(passphrase)) - return new Error('Passphrase must be a string or Buffer when supplied'); - } + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } - let ret; + if (signal.aborted) { + ac.abort(signal.reason) + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac + + const acRef = new WeakRef(ac) + const abort = function () { + const ac = acRef.deref() + if (ac !== undefined) { + ac.abort(this.reason) + } + } - // First try as printable string format (e.g. PEM) + // Third-party AbortControllers may not work with these. + // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. + try { + // If the max amount of listeners is equal to the default, increase it + // This is only available in node >= v19.9.0 + if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(100, signal) + } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(100, signal) + } + } catch {} - // Private keys - if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = PPK_Private.parse(data, passphrase)) !== null) - return ret; + util.addAbortListener(signal, abort) + requestFinalizer.register(ac, { signal, abort }) + } + } - // Public keys - if ((ret = OpenSSH_Public.parse(data)) !== null) - return ret; - if ((ret = RFC4716_Public.parse(data)) !== null) - return ret; + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kHeadersList] = request.headersList + this[kHeaders][kGuard] = 'request' + this[kHeaders][kRealm] = this[kRealm] - // Finally try as a binary format if we were originally passed binary data - if (origBuffer) { - binaryKeyParser.init(origBuffer, 0); - const type = binaryKeyParser.readString(true); - if (type !== undefined) { - data = binaryKeyParser.readRaw(); - if (data !== undefined) { - ret = parseDER(data, type, '', type); - // Ignore potentially useless errors in case the data was not actually - // in the binary format - if (ret instanceof Error) - ret = null; + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) } + + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' } - binaryKeyParser.clear(); - } - if (ret) - return ret; + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = this[kHeaders][kHeadersList] + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) - return new Error('Unsupported key format'); -} + // 3. Empty this’s headers’s header list. + headersList.clear() -module.exports = { - isParsedKey, - isSupportedKeyType, - parseDERKey: (data, type) => parseDER(data, type, '', type), - parseKey, -}; + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const [key, val] of headers) { + headersList.append(key, val) + } + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers) + } + } + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null -/***/ }), + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } -/***/ 7609: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 35. Let initBody be null. + let initBody = null -"use strict"; + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { + this[kHeaders].append('content-type', contentType) + } + } -const assert = __nccwpck_require__(9491); -const { inspect } = __nccwpck_require__(3837); + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody -// Only use this for integers! Decimal numbers do not work with this function. -function addNumericalSeparator(val) { - let res = ''; - let i = val.length; - const start = val[0] === '-' ? 1 : 0; - for (; i >= start + 4; i -= 3) - res = `_${val.slice(i - 3, i)}${res}`; - return `${val.slice(0, i)}${res}`; -} + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } -function oneOf(expected, thing) { - assert(typeof thing === 'string', '`thing` has to be of type string'); - if (Array.isArray(expected)) { - const len = expected.length; - assert(len > 0, 'At least one expected value needs to be specified'); - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` - + expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true } - return `of ${thing} ${expected[0]}`; - } - return `of ${thing} ${String(expected)}`; -} + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody -exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { - constructor(message) { - super(); - Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } - const suffix = 'This is caused by either a bug in ssh2 ' - + 'or incorrect usage of ssh2 internals.\n' - + 'Please open an issue with this stack trace at ' - + 'https://github.com/mscdex/ssh2/issues\n'; + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = (__nccwpck_require__(5356).TransformStream) + } - this.message = (message === undefined ? suffix : `${message}\n${suffix}`); - } -}; + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } + } -const MAX_32BIT_INT = 2 ** 32; -const MAX_32BIT_BIGINT = (() => { - try { - return new Function('return 2n ** 32n')(); - } catch {} -})(); -exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { - constructor(str, range, input, replaceDefaultBoolean) { - super(); - Error.captureStackTrace(this, ERR_OUT_OF_RANGE); + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } - assert(range, 'Missing "range" argument'); - let msg = (replaceDefaultBoolean - ? str - : `The value of "${str}" is out of range.`); - let received; - if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === 'bigint') { - received = String(input); - if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) - received = addNumericalSeparator(received); - received += 'n'; - } else { - received = inspect(input); - } - msg += ` It must be ${range}. Received ${received}`; + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) - this.message = msg; + // The method getter steps are to return this’s request’s method. + return this[kState].method } -}; -class ERR_INVALID_ARG_TYPE extends TypeError { - constructor(name, expected, actual) { - super(); - Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) - assert(typeof name === 'string', `'name' must be a string`); + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && expected.startsWith('not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) - let msg; - if (name.endsWith(' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = (name.includes('.') ? 'property' : 'argument'); - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } - msg += `. Received type ${typeof actual}`; + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) - this.message = msg; + // The destination getter are to return this’s request’s destination. + return this[kState].destination } -} -exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; -exports.validateNumber = function validateNumber(value, name) { - if (typeof value !== 'number') - throw new ERR_INVALID_ARG_TYPE(name, 'number', value); -}; + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } -/***/ }), + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } -/***/ 9475: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } -"use strict"; + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } -const Ber = (__nccwpck_require__(970).Ber); + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) -let DISCONNECT_REASON; + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } -const FastBuffer = Buffer[Symbol.species]; -const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials + } -function readUInt32BE(buf, offset) { - return (buf[offset++] * 16777216) - + (buf[offset++] * 65536) - + (buf[offset++] * 256) - + buf[offset]; -} + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) -function bufferCopy(src, dest, srcStart, srcEnd, destStart) { - if (!destStart) - destStart = 0; - if (srcEnd > src.length) - srcEnd = src.length; - let nb = srcEnd - srcStart; - const destLeft = (dest.length - destStart); - if (nb > destLeft) - nb = destLeft; - dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), - destStart); - return nb; -} + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } -function bufferSlice(buf, start, end) { - if (end === undefined) - end = buf.length; - return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); -} + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) -function makeBufferParser() { - let pos = 0; - let buffer; + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } - const self = { - init: (buf, start) => { - buffer = buf; - pos = (typeof start === 'number' ? start : 0); - }, - pos: () => pos, - length: () => (buffer ? buffer.length : 0), - avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), - clear: () => { - buffer = undefined; - }, - readUInt32BE: () => { - if (!buffer || pos + 3 >= buffer.length) - return; - return (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - }, - readUInt64BE: (behavior) => { - if (!buffer || pos + 7 >= buffer.length) - return; - switch (behavior) { - case 'always': - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - case 'maybe': - if (buffer[pos] > 0x1F) - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - // FALLTHROUGH - default: - return (buffer[pos++] * 72057594037927940) - + (buffer[pos++] * 281474976710656) - + (buffer[pos++] * 1099511627776) - + (buffer[pos++] * 4294967296) - + (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - } - }, - skip: (n) => { - if (buffer && n > 0) - pos += n; - }, - skipString: () => { - const len = self.readUInt32BE(); - if (len === undefined) - return; - pos += len; - return (pos <= buffer.length ? len : undefined); - }, - readByte: () => { - if (buffer && pos < buffer.length) - return buffer[pos++]; - }, - readBool: () => { - if (buffer && pos < buffer.length) - return !!buffer[pos++]; - }, - readList: () => { - const list = self.readString(true); - if (list === undefined) - return; - return (list ? list.split(',') : []); - }, - readString: (dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } - const len = self.readUInt32BE(); - if (len === undefined) - return; + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) - if ((buffer.length - pos) < len - || (typeof maxLen === 'number' && len > maxLen)) { - return; - } + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, pos, pos += len); - return buffer.utf8Slice(pos, pos += len); - } - return bufferSlice(buffer, pos, pos += len); - }, - readRaw: (len) => { - if (!buffer) - return; - if (typeof len !== 'number') - return bufferSlice(buffer, pos, pos += (buffer.length - pos)); - if ((buffer.length - pos) >= len) - return bufferSlice(buffer, pos, pos += len); - }, - }; + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) - return self; -} + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } -function makeError(msg, level, fatal) { - const err = new Error(msg); - if (typeof level === 'boolean') { - fatal = level; - err.level = 'protocol'; - } else { - err.level = level || 'protocol'; + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-foward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation } - err.fatal = !!fatal; - return err; -} -function writeUInt32BE(buf, value, offset) { - buf[offset++] = (value >>> 24); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 8); - buf[offset++] = value; - return offset; -} + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) -const utilBufferParser = makeBufferParser(); + // The signal getter steps are to return this’s signal. + return this[kSignal] + } -module.exports = { - bufferCopy, - bufferSlice, - FastBuffer, - bufferFill: (buf, value, start, end) => { - return TypedArrayFill.call(buf, value, start, end); - }, - makeError, - doFatalError: (protocol, msg, level, reason) => { - let err; - if (DISCONNECT_REASON === undefined) - ({ DISCONNECT_REASON } = __nccwpck_require__(9475)); - if (msg instanceof Error) { - // doFatalError(protocol, err[, reason]) - err = msg; - if (typeof level !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - else - reason = level; - } else { - // doFatalError(protocol, msg[, level[, reason]]) - err = makeError(msg, level, true); - } - if (typeof reason !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - protocol.disconnect(reason); - protocol._destruct(); - protocol._onError(err); - return Infinity; - }, - readUInt32BE, - writeUInt32BE, - writeUInt32LE: (buf, value, offset) => { - buf[offset++] = value; - buf[offset++] = (value >>> 8); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 24); - return offset; - }, - makeBufferParser, - bufferParser: makeBufferParser(), - readString: (buffer, start, dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } + get body () { + webidl.brandCheck(this, Request) - if (start === undefined) - start = 0; + return this[kState].body ? this[kState].body.stream : null + } - const left = (buffer.length - start); - if (start < 0 || start >= buffer.length || left < 4) - return; + get bodyUsed () { + webidl.brandCheck(this, Request) - const len = readUInt32BE(buffer, start); - if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) - return; + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } - start += 4; - const end = start + len; - buffer._pos = end; + get duplex () { + webidl.brandCheck(this, Request) - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, start, end); - return buffer.utf8Slice(start, end); - } - return bufferSlice(buffer, start, end); - }, - sigSSHToASN1: (sig, type) => { - switch (type) { - case 'ssh-dss': { - if (sig.length > 40) - return sig; - // Change bare signature r and s values to ASN.1 BER values for OpenSSL - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - let r = sig.slice(0, 20); - let s = sig.slice(20); - if (r[0] & 0x80) { - const rNew = Buffer.allocUnsafe(21); - rNew[0] = 0x00; - r.copy(rNew, 1); - r = rNew; - } else if (r[0] === 0x00 && !(r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] & 0x80) { - const sNew = Buffer.allocUnsafe(21); - sNew[0] = 0x00; - s.copy(sNew, 1); - s = sNew; - } else if (s[0] === 0x00 && !(s[1] & 0x80)) { - s = s.slice(1); - } - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - utilBufferParser.init(sig, 0); - const r = utilBufferParser.readString(); - const s = utilBufferParser.readString(); - utilBufferParser.clear(); - if (r === undefined || s === undefined) - return; + return 'half' + } - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - default: - return sig; + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') } - }, - convertSignature: (signature, keyType) => { - switch (keyType) { - case 'ssh-dss': { - if (signature.length <= 40) - return signature; - // This is a quick and dirty way to get from BER encoded r and s that - // OpenSSL gives us, to just the bare values back to back (40 bytes - // total) like OpenSSH (and possibly others) are expecting - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - let r = asnReader.readString(Ber.Integer, true); - let s = asnReader.readString(Ber.Integer, true); - let rOffset = 0; - let sOffset = 0; - if (r.length < 20) { - const rNew = Buffer.allocUnsafe(20); - rNew.set(r, 1); - r = rNew; - r[0] = 0; - } - if (s.length < 20) { - const sNew = Buffer.allocUnsafe(20); - sNew.set(s, 1); - s = sNew; - s[0] = 0; + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + const clonedRequestObject = new Request(kConstruct) + clonedRequestObject[kState] = clonedRequest + clonedRequestObject[kRealm] = this[kRealm] + clonedRequestObject[kHeaders] = new Headers(kConstruct) + clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList + clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + util.addAbortListener( + this.signal, + () => { + ac.abort(this.signal.reason) } - if (r.length > 20 && r[0] === 0) - rOffset = 1; - if (s.length > 20 && s[0] === 0) - sOffset = 1; - const newSig = - Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); - bufferCopy(r, newSig, rOffset, r.length, 0); - bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); - return newSig; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - if (signature[0] === 0) - return signature; - // Convert SSH signature parameters to ASN.1 BER values for OpenSSL - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - const r = asnReader.readString(Ber.Integer, true); - const s = asnReader.readString(Ber.Integer, true); - if (r === null || s === null) - return; - const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); - writeUInt32BE(newSig, r.length, 0); - newSig.set(r, 4); - writeUInt32BE(newSig, s.length, 4 + r.length); - newSig.set(s, 4 + 4 + r.length); - return newSig; - } + ) } + clonedRequestObject[kSignal] = ac.signal - return signature; - }, - sendPacket: (proto, packet, bypass) => { - if (!bypass && proto._kexinit !== undefined) { - // We're currently in the middle of a handshake + // 4. Return clonedRequestObject. + return clonedRequestObject + } +} - if (proto._queue === undefined) - proto._queue = []; - proto._queue.push(packet); - proto._debug && proto._debug('Outbound: ... packet queued'); - return false; - } - proto._cipher.encrypt(packet); - return true; +mixinBody(Request) + +function makeRequest (init) { + // https://fetch.spec.whatwg.org/#requests + const request = { + method: 'GET', + localURLsOnly: false, + unsafeRequest: false, + body: null, + client: null, + reservedClient: null, + replacesClientId: '', + window: 'client', + keepalive: false, + serviceWorkers: 'all', + initiator: '', + destination: '', + priority: null, + origin: 'client', + policyContainer: 'client', + referrer: 'client', + referrerPolicy: '', + mode: 'no-cors', + useCORSPreflightFlag: false, + credentials: 'same-origin', + useCredentials: false, + cache: 'default', + redirect: 'follow', + integrity: '', + cryptoGraphicsNonceMetadata: '', + parserMetadata: '', + reloadNavigation: false, + historyNavigation: false, + userActivation: false, + taintedOrigin: false, + redirectCount: 0, + responseTainting: 'basic', + preventNoCacheCacheControlHeaderModification: false, + done: false, + timingAllowFailed: false, + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } + request.url = request.urlList[0] + return request +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body) + } + + // 3. Return newRequest. + return newRequest +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } +}) + +webidl.converters.Request = webidl.interfaceConverter( + Request +) + +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (V instanceof Request) { + return webidl.converters.Request(V) + } + + return webidl.converters.USVString(V) +} + +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) + +// https://fetch.spec.whatwg.org/#requestinit +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString }, -}; + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + } +]) + +module.exports = { Request, makeRequest } /***/ }), -/***/ 6715: +/***/ 7823: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { kMaxLength } = __nccwpck_require__(4300); +const { Headers, HeadersList, fill } = __nccwpck_require__(554) +const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(1472) +const util = __nccwpck_require__(3983) +const { kEnumerableProperty } = util const { - createInflate, - constants: { - DEFLATE, - INFLATE, - Z_DEFAULT_CHUNK, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_MEMLEVEL, - Z_DEFAULT_STRATEGY, - Z_DEFAULT_WINDOWBITS, - Z_PARTIAL_FLUSH, + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode +} = __nccwpck_require__(2538) +const { + redirectStatusSet, + nullBodyStatus, + DOMException +} = __nccwpck_require__(1037) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { FormData } = __nccwpck_require__(2015) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { URLSerializer } = __nccwpck_require__(685) +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { types } = __nccwpck_require__(3837) + +const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(5356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') + +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} } + + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = new Response() + responseObject[kState] = makeNetworkError() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const relevantRealm = { settingsObject: {} } + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'response' + responseObject[kHeaders][kRealm] = relevantRealm + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject } -} = __nccwpck_require__(9796); -const ZlibHandle = createInflate()._handle.constructor; -function processCallback() { - throw new Error('Should not get here'); -} + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + const relevantRealm = { settingsObject: {} } -function zlibOnError(message, errno, code) { - const self = this._owner; - // There is no way to cleanly recover. - // Continuing only obscures problems. + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) - const error = new Error(message); - error.errno = errno; - error.code = code; - self._err = error; -} + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) -function _close(engine) { - // Caller may invoke .close after a zlib error (which will null _handle). - if (!engine._handle) - return; + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, getGlobalOrigin()) + } catch (err) { + throw Object.assign(new TypeError('Failed to parse URL from ' + url), { + cause: err + }) + } - engine._handle.close(); - engine._handle = null; -} + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError('Invalid status code ' + status) + } -class Zlib { - constructor(mode) { - const windowBits = Z_DEFAULT_WINDOWBITS; - const level = Z_DEFAULT_COMPRESSION; - const memLevel = Z_DEFAULT_MEMLEVEL; - const strategy = Z_DEFAULT_STRATEGY; - const dictionary = undefined; + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm - this._err = undefined; - this._writeState = new Uint32Array(2); - this._chunkSize = Z_DEFAULT_CHUNK; - this._maxOutputLength = kMaxLength; - this._outBuffer = Buffer.allocUnsafe(this._chunkSize); - this._outOffset = 0; + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status - this._handle = new ZlibHandle(mode); - this._handle._owner = this; - this._handle.onerror = zlibOnError; - this._handle.init(windowBits, - level, - memLevel, - strategy, - this._writeState, - processCallback, - dictionary); + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) + + // 8. Return responseObject. + return responseObject } - writeSync(chunk, retChunks) { - const handle = this._handle; - if (!handle) - throw new Error('Invalid Zlib instance'); + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) + } - let availInBefore = chunk.length; - let availOutBefore = this._chunkSize - this._outOffset; - let inOff = 0; - let availOutAfter; - let availInAfter; + init = webidl.converters.ResponseInit(init) - let buffers; - let nread = 0; - const state = this._writeState; - let buffer = this._outBuffer; - let offset = this._outOffset; - const chunkSize = this._chunkSize; + // TODO + this[kRealm] = { settingsObject: {} } - while (true) { - handle.writeSync(Z_PARTIAL_FLUSH, - chunk, // in - inOff, // in_off - availInBefore, // in_len - buffer, // out - offset, // out_off - availOutBefore); // out_len - if (this._err) - throw this._err; + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) - availOutAfter = state[0]; - availInAfter = state[1]; + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kGuard] = 'response' + this[kHeaders][kHeadersList] = this[kState].headersList + this[kHeaders][kRealm] = this[kRealm] - const inDelta = availInBefore - availInAfter; - const have = availOutBefore - availOutAfter; + // 3. Let bodyWithType be null. + let bodyWithType = null - if (have > 0) { - const out = (offset === 0 && have === buffer.length - ? buffer - : buffer.slice(offset, offset + have)); - offset += have; - if (!buffers) - buffers = out; - else if (buffers.push === undefined) - buffers = [buffers, out]; - else - buffers.push(out); - nread += out.byteLength; + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } - if (nread > this._maxOutputLength) { - _close(this); - throw new Error( - `Output length exceeded maximum of ${this._maxOutputLength}` - ); - } - } else if (have !== 0) { - throw new Error('have should not go down'); - } + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } - // Exhausted the output buffer, or used all the input create a new one. - if (availOutAfter === 0 || offset >= chunkSize) { - availOutBefore = chunkSize; - offset = 0; - buffer = Buffer.allocUnsafe(chunkSize); - } + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) - if (availOutAfter === 0) { - // Not actually done. Need to reprocess. - // Also, update the availInBefore to the availInAfter value, - // so that if we have to hit it a third (fourth, etc.) time, - // it'll have the correct byte counts. - inOff += inDelta; - availInBefore = availInAfter; - } else { - break; - } + // The type getter steps are to return this’s response’s type. + return this[kState].type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) + + const urlList = this[kState].urlList + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + + if (url === null) { + return '' } - this._outBuffer = buffer; - this._outOffset = offset; + return URLSerializer(url, true) + } - if (nread === 0) - buffers = Buffer.alloc(0); + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) - if (retChunks) { - buffers.totalLen = nread; - return buffers; + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) + + // The status getter steps are to return this’s response’s status. + return this[kState].status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) + + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + get body () { + webidl.brandCheck(this, Response) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || (this.body && this.body.locked)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) } - if (buffers.push === undefined) - return buffers; + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) - const output = Buffer.allocUnsafe(nread); - for (let i = 0, p = 0; i < buffers.length; ++i) { - const buf = buffers[i]; - output.set(buf, p); - p += buf.length; + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + const clonedResponseObject = new Response() + clonedResponseObject[kState] = clonedResponse + clonedResponseObject[kRealm] = this[kRealm] + clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList + clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + return clonedResponseObject + } +} + +mixinBody(Response) + +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } +}) + +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) + +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body) + } + + // 4. Return newResponse. + return newResponse +} + +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList(), + urlList: init.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) +} + +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} + +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) +} + +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') } - return output; } -} -class ZlibPacketWriter { - constructor(protocol) { - this.allocStart = 0; - this.allocStartKEX = 0; - this._protocol = protocol; - this._zlib = new Zlib(DEFLATE); + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status } - cleanup() { - if (this._zlib) - _close(this._zlib); + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText } - alloc(payloadSize, force) { - return Buffer.allocUnsafe(payloadSize); + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kHeaders], init.headers) } - finalize(payload, force) { - if (this._protocol._kexinit === undefined || force) { - const output = this._zlib.writeSync(payload, true); - const packet = this._protocol._cipher.allocPacket(output.totalLen); - if (output.push === undefined) { - packet.set(output, 5); - } else { - for (let i = 0, p = 5; i < output.length; ++i) { - const chunk = output[i]; - packet.set(chunk, p); - p += chunk.length; - } - } - return packet; + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: 'Invalid response status code ' + response.status + }) + } + + // 2. Set response's body to body's body. + response[kState].body = body.body + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('Content-Type')) { + response[kState].headersList.append('content-type', body.type) } - return payload; } } -class PacketWriter { - constructor(protocol) { - this.allocStart = 5; - this.allocStartKEX = 5; - this._protocol = protocol; - } +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) - cleanup() {} +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) - alloc(payloadSize, force) { - if (this._protocol._kexinit === undefined || force) - return this._protocol._cipher.allocPacket(payloadSize); - return Buffer.allocUnsafe(payloadSize); +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) + +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) } - finalize(packet, force) { - return packet; + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) } -} -class ZlibPacketReader { - constructor() { - this._zlib = new Zlib(INFLATE); + if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { + return webidl.converters.BufferSource(V) } - cleanup() { - if (this._zlib) - _close(this._zlib); + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) } - read(data) { - return this._zlib.writeSync(data, false); + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) } + + return webidl.converters.DOMString(V) } -class PacketReader { - cleanup() {} +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) + } - read(data) { - return data; + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V } + + return webidl.converters.XMLHttpRequestBodyInit(V) } +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) + module.exports = { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -}; + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse +} /***/ }), -/***/ 2986: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5861: +/***/ ((module) => { "use strict"; -// TODO: -// * convert listenerCount() usage to emit() return value checking? -// * emit error when connection severed early (e.g. before handshake) -// * add '.connected' or similar property to connection objects to allow -// immediate connection status checking -const { Server: netServer } = __nccwpck_require__(1808); -const EventEmitter = __nccwpck_require__(2361); -const { listenerCount } = EventEmitter; +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') +} -const { - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = __nccwpck_require__(6832); -const { init: cryptoInit } = __nccwpck_require__(5708); -const { KexInit } = __nccwpck_require__(4126); -const { parseKey } = __nccwpck_require__(2218); -const Protocol = __nccwpck_require__(9031); -const { SFTP } = __nccwpck_require__(2026); -const { writeUInt32BE } = __nccwpck_require__(9475); -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = __nccwpck_require__(3204); +/***/ }), -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = __nccwpck_require__(834); +/***/ 2538: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const MAX_PENDING_AUTHS = 10; +"use strict"; -class AuthContext extends EventEmitter { - constructor(protocol, username, service, method, cb) { - super(); - this.username = this.user = username; - this.service = service; - this.method = method; - this._initialResponse = false; - this._finalResponse = false; - this._multistep = false; - this._cbfinal = (allowed, methodsLeft, isPartial) => { - if (!this._finalResponse) { - this._finalResponse = true; - cb(this, allowed, methodsLeft, isPartial); - } - }; - this._protocol = protocol; +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(1037) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { performance } = __nccwpck_require__(4074) +const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3983) +const assert = __nccwpck_require__(9491) +const { isUint8Array } = __nccwpck_require__(9830) + +let supportedHashes = [] + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto + +try { + crypto = __nccwpck_require__(6113) + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) +/* c8 ignore next 3 */ +} catch { +} + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null } - accept() { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(true); + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location') + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + location = new URL(location, responseURL(response)) } - reject(methodsLeft, isPartial) { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(false, methodsLeft, isPartial); + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment } -} + // 5. Return location. + return location +} -class KeyboardAuthContext extends AuthContext { - constructor(protocol, username, service, method, submethods, cb) { - super(protocol, username, service, method, cb); +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} - this._multistep = true; +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) - this._cb = undefined; - this._onInfoResponse = (responses) => { - const callback = this._cb; - if (callback) { - this._cb = undefined; - callback(responses); - } - }; - this.submethods = submethods; - this.on('abort', () => { - this._cb && this._cb(new Error('Authentication request aborted')); - }); + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' } - prompt(prompts, title, instructions, cb) { - if (!Array.isArray(prompts)) - prompts = [ prompts ]; + // 3. Return allowed. + return 'allowed' +} - if (typeof title === 'function') { - cb = title; - title = instructions = undefined; - } else if (typeof instructions === 'function') { - cb = instructions; - instructions = undefined; - } else if (typeof cb !== 'function') { - cb = undefined; - } +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} - for (let i = 0; i < prompts.length; ++i) { - if (typeof prompts[i] === 'string') { - prompts[i] = { - prompt: prompts[i], - echo: true - }; - } +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false } + } + return true +} - this._cb = cb; - this._initialResponse = true; +/** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + */ +function isTokenCharCode (c) { + switch (c) { + case 0x22: + case 0x28: + case 0x29: + case 0x2c: + case 0x2f: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x7b: + case 0x7d: + // DQUOTE and "(),/:;<=>?@[\]{}" + return false + default: + // VCHAR %x21-7E + return c >= 0x21 && c <= 0x7e + } +} - this._protocol.authInfoReq(title, instructions, prompts); +/** + * @param {string} characters + */ +function isValidHTTPToken (characters) { + if (characters.length === 0) { + return false } + for (let i = 0; i < characters.length; ++i) { + if (!isTokenCharCode(characters.charCodeAt(i))) { + return false + } + } + return true } -class PKAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); +/** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ +function isValidHeaderName (potentialValue) { + return isValidHTTPToken(potentialValue) +} - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + if ( + potentialValue.startsWith('\t') || + potentialValue.startsWith(' ') || + potentialValue.endsWith('\t') || + potentialValue.endsWith(' ') + ) { + return false } - accept() { - if (!this.signature) { - this._initialResponse = true; - this._protocol.authPKOK(this.key.algo, this.key.data); - } else { - AuthContext.prototype.accept.call(this); + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false + } + + return true +} + +// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = '' + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.has(token)) { + policy = token + break + } } } + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } } -class HostbasedAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - this.localHostname = pkInfo.localHostname; - this.localUsername = pkInfo.localUsername; +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} + +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} + +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header) + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} + +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. + let serializedOrigin = request.origin + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + if (serializedOrigin) { + request.headersList.append('origin', serializedOrigin) + } + + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } + + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin) + } } } -class PwdAuthContext extends AuthContext { - constructor(protocol, username, service, method, password, cb) { - super(protocol, username, service, method, cb); +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} - this.password = password; - this._changeCb = undefined; +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' } +} - requestChange(prompt, cb) { - if (this._changeCb) - throw new Error('Change request already in progress'); - if (typeof prompt !== 'string') - throw new Error('prompt argument must be a string'); - if (typeof cb !== 'function') - throw new Error('Callback argument must be a function'); - this._changeCb = cb; - this._protocol.authPasswdChg(prompt); +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy } } +// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer +function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy -class Session extends EventEmitter { - constructor(client, info, localChan) { - super(); + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) - this.type = 'session'; - this.subtype = undefined; - this.server = true; - this._ending = false; - this._channel = undefined; - this._chanInfo = { - type: 'session', - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' + // 2. Let environment be request’s client. + + let referrerSource = null + + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin() + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL } - }; + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin } } +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ +function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL) -class Server extends EventEmitter { - constructor(cfg, listener) { - super(); + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' + } - if (typeof cfg !== 'object' || cfg === null) - throw new Error('Missing configuration object'); + // 3. Set url’s username to the empty string. + url.username = '' - const hostKeys = Object.create(null); - const hostKeyAlgoOrder = []; + // 4. Set url’s password to the empty string. + url.password = '' - const hostKeys_ = cfg.hostKeys; - if (!Array.isArray(hostKeys_)) - throw new Error('hostKeys must be an array'); + // 5. Set url’s fragment to null. + url.hash = '' - const cfgAlgos = ( - typeof cfg.algorithms === 'object' && cfg.algorithms !== null - ? cfg.algorithms - : {} - ); + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' - const hostKeyAlgos = generateAlgorithmList( - cfgAlgos.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY - ); - for (let i = 0; i < hostKeys_.length; ++i) { - let privateKey; - if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') - privateKey = parseKey(hostKeys_[i]); - else - privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); + // 2. Set url’s query to null. + url.search = '' + } - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); + // 7. Return url. + return url +} - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } - if (privateKey.getPrivatePEM() === null) - throw new Error('privateKey value contains an invalid private key'); + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } - // Discard key if we already found a key of the same type - if (hostKeyAlgoOrder.includes(privateKey.type)) - continue; + // If scheme is data, return true + if (url.protocol === 'data:') return true - if (privateKey.type === 'ssh-rsa') { - // SSH supports multiple signature hashing algorithms for RSA, so we add - // the algorithms in the desired order - let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); - const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); - const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); - if (sha1Pos === -1) { - // Fall back to giving SHA1 the lowest priority - sha1Pos = Infinity; - } - [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { - if (pos === -1) - return; + // If file, return true + if (url.protocol === 'file:') return true - let type; - switch (pos) { - case sha1Pos: type = 'ssh-rsa'; break; - case sha256Pos: type = 'rsa-sha2-256'; break; - case sha512Pos: type = 'rsa-sha2-512'; break; - default: return; - } + return isOriginPotentiallyTrustworthy(url.origin) - // Store same RSA key under each hash algorithm name for convenience - hostKeys[type] = privateKey; + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false - hostKeyAlgoOrder.push(type); - }); + const originAsURL = new URL(origin) + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true + } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false + } +} + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ +function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } + + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) + + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } + + // 3. If response is not eligible for integrity validation, return false. + // TODO + + // 4. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata) + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) + + // 6. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo + + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2) } else { - hostKeys[privateKey.type] = privateKey; - hostKeyAlgoOrder.push(privateKey.type); + actualValue = actualValue.slice(0, -1) } } - const algorithms = { - kex: generateAlgorithmList(cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX), - serverHostKey: hostKeyAlgoOrder, - cs: { - cipher: generateAlgorithmList( - cfgAlgos.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER - ), - mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), - compress: generateAlgorithmList( - cfgAlgos.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION - ), - lang: [], - }, - sc: undefined, - }; - algorithms.sc = algorithms.cs; + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { + return true + } + } - if (typeof listener === 'function') - this.on('connection', listener); + // 7. Return false. + return false +} - const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); - const offer = new KexInit(algorithms); +// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options +// https://www.w3.org/TR/CSP2/#source-list-syntax +// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 +const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i - this._srv = new netServer((socket) => { - if (this._connections >= this.maxConnections) { - socket.destroy(); - return; - } - ++this._connections; - socket.once('close', () => { - --this._connections; - }); +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = [] - let debug; - if (origDebug) { - // Prepend debug output with a unique identifier in case there are - // multiple clients connected at the same time - const debugPrefix = `[${process.hrtime().join('.')}] `; - debug = (msg) => { - origDebug(`${debugPrefix}${msg}`); - }; - } + // 2. Let empty be equal to true. + let empty = true - // eslint-disable-next-line no-use-before-define - new Client(socket, hostKeys, ident, offer, debug, this, cfg); - }).on('error', (err) => { - this.emit('error', err); - }).on('listening', () => { - this.emit('listening'); - }).on('close', () => { - this.emit('close'); - }); - this._connections = 0; - this.maxConnections = Infinity; + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) + + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === undefined + ) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } + + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase() + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups) + } + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result +} + +/** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ +function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm } - injectSocket(socket) { - this._srv.emit('connection', socket); + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i] + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512' + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384' + } } + return algorithm +} - listen(...args) { - this._srv.listen(...args); - return this; +function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList } - address() { - return this._srv.address(); + let pos = 0 + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i] + } } - getConnections(cb) { - this._srv.getConnections(cb); - return this; + metadataList.length = pos + + return metadataList +} + +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * +* @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ +function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false + } + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } } - close(cb) { - this._srv.close(cb); - return this; + return true +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true } - ref() { - this._srv.ref(); - return this; + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true } - unref() { - this._srv.unref(); - return this; + // 3. Return false. + return false +} + +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) + + return { promise, resolve: res, reject: rej } +} + +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} + +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +const normalizeMethodRecord = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizeMethodRecord, null) + +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizeMethodRecord[method.toLowerCase()] ?? method +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') } + + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result } -Server.KEEPALIVE_CLIENT_INTERVAL = 15000; -Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) -class Client extends EventEmitter { - constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { - super(); +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {() => unknown[]} iterator + * @param {string} name name of the instance + * @param {'key'|'value'|'key+value'} kind + */ +function makeIterator (iterator, name, kind) { + const object = { + index: 0, + kind, + target: iterator + } - let exchanges = 0; - let acceptedAuthSvc = false; - let pendingAuths = []; - let authCtx; - let kaTimer; - let onPacket; - const unsentGlobalRequestsReplies = []; - this._sock = socket; - this._chanMgr = new ChannelManager(this); - this._debug = debug; - this.noMoreSessions = false; - this.authenticated = false; + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. - // Silence pre-header errors - function onClientPreHeaderError(err) {} - this.on('error', onClientPreHeaderError); + // 2. Let thisValue be the this value. - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from client: ${JSON.stringify(msg)}`); - }); + // 3. Let object be ? ToObject(thisValue). - const kaIntvl = ( - typeof srvCfg.keepaliveInterval === 'number' - && isFinite(srvCfg.keepaliveInterval) - && srvCfg.keepaliveInterval > 0 - ? srvCfg.keepaliveInterval - : ( - typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) - && Server.KEEPALIVE_CLIENT_INTERVAL > 0 - ? Server.KEEPALIVE_CLIENT_INTERVAL - : -1 - ) - ); - const kaCountMax = ( - typeof srvCfg.keepaliveCountMax === 'number' - && isFinite(srvCfg.keepaliveCountMax) - && srvCfg.keepaliveCountMax >= 0 - ? srvCfg.keepaliveCountMax - : ( - typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) - && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 - ? Server.KEEPALIVE_CLIENT_COUNT_MAX - : -1 - ) - ); - let kaCurCount = 0; - if (kaIntvl !== -1 && kaCountMax !== -1) { - this.once('ready', () => { - const onClose = () => { - clearInterval(kaTimer); - }; - this.on('close', onClose).on('end', onClose); - kaTimer = setInterval(() => { - if (++kaCurCount > kaCountMax) { - clearInterval(kaTimer); - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - this.end(); - } else { - // XXX: if the server ever starts sending real global requests to - // the client, we will need to add a dummy callback here to - // keep the correct reply order - proto.ping(); - } - }, kaIntvl); - }); - // TODO: re-verify keepalive behavior with OpenSSH - onPacket = () => { - kaTimer && kaTimer.refresh(); - kaCurCount = 0; - }; + // 4. If object is a platform object, then perform a security + // check, passing: + + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const { index, kind, target } = object + const values = target() + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { value: undefined, done: true } + } + + // 11. Let pair be the entry in values at index index. + const pair = values[index] + + // 12. Set object’s index to index + 1. + object.index = index + 1 + + // 13. Return the iterator result for pair and kind. + return iteratorResult(pair, kind) + }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". + [Symbol.toStringTag]: `${name} Iterator` + } + + // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. + Object.setPrototypeOf(i, esIteratorPrototype) + // esIteratorPrototype needs to be the prototype of i + // which is the prototype of an empty object. Yes, it's confusing. + return Object.setPrototypeOf({}, i) +} + +// https://webidl.spec.whatwg.org/#iterator-result +function iteratorResult (pair, kind) { + let result + + // 1. Let result be a value determined by the value of kind: + switch (kind) { + case 'key': { + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = pair[0] + break + } + case 'value': { + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = pair[1] + break + } + case 'key+value': { + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = pair + break } + } - const proto = this._protocol = new Protocol({ - server: true, - hostKeys, - ident, - offer, - onPacket, - greeting: srvCfg.greeting, - banner: srvCfg.banner, - onWrite: (data) => { - if (isWritable(socket)) - socket.write(data); - }, - onError: (err) => { - if (!proto._destruct) - socket.removeAllListeners('data'); - this.emit('error', err); - try { - socket.end(); - } catch {} - }, - onHeader: (header) => { - this.removeListener('error', onClientPreHeaderError); + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } +} - const info = { - ip: socket.remoteAddress, - family: socket.remoteFamily, - port: socket.remotePort, - header, - }; - if (!server.emit('connection', this, info)) { - // auto reject - proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); - socket.end(); - return; - } +/** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +async function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - if (++exchanges > 1) - this.emit('rekey'); - this.emit('handshake', negotiated); - }, - debug, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - socket.end(); - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from client + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody - // Do early reject in some cases to prevent wasteful channel - // allocation - if ((info.type === 'session' && this.noMoreSessions) - || !this.authenticated) { - const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - return proto.channelOpenFail(info.sender, reasonCode); - } + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError - let localChan = -1; - let reason; - let replied = false; + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader - let accept; - const reject = () => { - if (replied) - return; - replied = true; + try { + reader = body.stream.getReader() + } catch (e) { + errorSteps(e) + return + } - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + const result = await readAllBytes(reader) + successSteps(result) + } catch (e) { + errorSteps(e) + } +} - if (localChan !== -1) - this._chanMgr.remove(localChan); - proto.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = this._chanMgr.add(); +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (debug) { - debug('Automatic rejection of incoming channel open: ' - + 'no channels available'); - } - } +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } - return (localChan !== -1); - }; + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} - const data = info.data; - switch (info.type) { - case 'session': - if (listenerCount(this, 'session') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; +const MAXIMUM_ARGUMENT_LENGTH = 65535 - const instance = new Session(this, info, localChan); - this._chanMgr.update(localChan, instance); +/** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {number[]|Uint8Array} input + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); + if (input.length < MAXIMUM_ARGUMENT_LENGTH) { + return String.fromCharCode(...input) + } - return instance; - }; + return input.reduce((previous, current) => previous + String.fromCharCode(current), '') +} - this.emit('session', accept, reject); - return; - } - break; - case 'direct-tcpip': - if (listenerCount(this, 'tcpip') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed')) { + throw err + } + } +} - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; +/** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + for (let i = 0; i < input.length; i++) { + assert(input.charCodeAt(i) <= 0xFF) + } - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + */ +async function readAllBytes (reader) { + const bytes = [] + let byteLength = 0 - return stream; - }; + while (true) { + const { done, value: chunk } = await reader.read() - this.emit('tcpip', accept, reject, data); - return; - } - break; - case 'direct-streamlocal@openssh.com': - if (listenerCount(this, 'openssh.streamlocal') - && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; + if (done) { + // 1. Call successSteps with bytes. + return Buffer.concat(bytes, byteLength) + } - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + throw new TypeError('Received non-Uint8Array chunk') + } - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } +} - return stream; - }; +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object - this.emit('openssh.streamlocal', accept, reject, data); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (debug) { - debug('Automatic rejection of unsupported incoming channel open' - + ` type: ${info.type}`); - } - } + const protocol = url.protocol - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (debug) { - debug('Automatic rejection of unexpected incoming channel open' - + ` for: ${info.type}`); - } - } + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} - reject(); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; +/** + * @param {string|URL} url + */ +function urlHasHttpsScheme (url) { + if (typeof url === 'string') { + return url.startsWith('https:') + } - const chanInfo = { - type: channel.type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; + return url.protocol === 'https:' +} - const instance = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; + const protocol = url.protocol - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } + return protocol === 'http:' || protocol === 'https:' +} - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; +/** + * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. + */ +const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) - channel.incoming.window -= data.length; +module.exports = { + isAborted, + isCancelled, + createDeferredPromise, + ReadableStreamFrom, + toUSVString, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + makeIterator, + isValidHeaderName, + isValidHeaderValue, + hasOwn, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + isomorphicDecode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + normalizeMethodRecord, + parseMetadata +} - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - // NOOP -- should not be sent by client - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +/***/ }), - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } +/***/ 1744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; +"use strict"; - if (channel._waitWindow) { - channel._waitWindow = false; - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +const { types } = __nccwpck_require__(3837) +const { hasOwn, toUSVString } = __nccwpck_require__(2538) + +/** @type {import('../../types/webidl').Webidl} */ +const webidl = {} +webidl.converters = {} +webidl.util = {} +webidl.errors = {} + +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} + +webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of' + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.` + + return webidl.errors.exception({ + header: context.prefix, + message + }) +} + +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I, opts = undefined) { + if (opts?.strict !== false && !(V instanceof I)) { + throw new TypeError('Illegal invocation') + } else { + return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] + } +} - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + ...ctx + }) + } +} - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) +} - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const session = this._chanMgr.get(recipient); - if (typeof session !== 'object' || session === null) - return; + return 'Object' + } + } +} - let replied = false; - let accept; - let reject; +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { + let upperBound + let lowerBound - if (session.constructor !== Session) { - // normal Channel instance - if (wantReply) - proto.channelFailure(session.outgoing.id); - return; - } + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 - if (wantReply) { - // "real session" requests will have custom accept behaviors - if (type !== 'shell' - && type !== 'exec' - && type !== 'subsystem') { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: - proto.channelSuccess(session._chanInfo.outgoing.id); - }; - } + // 1. Let lowerBound be 0. + lowerBound = 0 - reject = () => { - if (replied || session._ending || session._channel) - return; - replied = true; + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: - proto.channelFailure(session._chanInfo.outgoing.id); - }; - } + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 - if (session._ending) { - reject && reject(); - return; - } + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 + } - switch (type) { - // "pre-real session start" requests - case 'env': - if (listenerCount(session, 'env')) { - session.emit('env', accept, reject, { - key: data.name, - val: data.value - }); - return; - } - break; - case 'pty-req': - if (listenerCount(session, 'pty')) { - session.emit('pty', accept, reject, data); - return; - } - break; - case 'window-change': - if (listenerCount(session, 'window-change')) - session.emit('window-change', accept, reject, data); - else - reject && reject(); - break; - case 'x11-req': - if (listenerCount(session, 'x11')) { - session.emit('x11', accept, reject, data); - return; - } - break; - // "post-real session start" requests - case 'signal': - if (listenerCount(session, 'signal')) { - session.emit('signal', accept, reject, { - name: data - }); - return; - } - break; - // XXX: is `auth-agent-req@openssh.com` really "post-real session - // start"? - case 'auth-agent-req@openssh.com': - if (listenerCount(session, 'auth-agent')) { - session.emit('auth-agent', accept, reject); - return; - } - break; - // "real session start" requests - case 'shell': - if (listenerCount(session, 'shell')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; + // 4. Let x be ? ToNumber(V). + let x = Number(V) - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } - const channel = new Channel( - this, session._chanInfo, { server: true } - ); + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${V} to an integer.` + }) + } - channel.subtype = session.subtype = type; - session._channel = channel; + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) - return channel; - }; + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } - session.emit('shell', accept, reject); - return; - } - break; - case 'exec': - if (listenerCount(session, 'exec')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; + // 4. Return x. + return x + } - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) - const channel = new Channel( - this, session._chanInfo, { server: true } - ); + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } - channel.subtype = session.subtype = type; - session._channel = channel; + // 3. Return x. + return x + } - return channel; - }; + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } - session.emit('exec', accept, reject, { - command: data - }); - return; - } - break; - case 'subsystem': { - let useSFTP = (data === 'sftp'); - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) - let instance; - if (useSFTP) { - instance = new SFTP(this, session._chanInfo, { - server: true, - debug, - }); - } else { - instance = new Channel( - this, session._chanInfo, { server: true } - ); - instance.subtype = - session.subtype = `${type}:${data}`; - } - session._channel = instance; + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } - return instance; - }; + // 12. Otherwise, return x. + return x +} - if (data === 'sftp') { - if (listenerCount(session, 'sftp')) { - session.emit('sftp', accept, reject); - return; - } - useSFTP = false; - } - if (listenerCount(session, 'subsystem')) { - session.emit('subsystem', accept, reject, { - name: data - }); - return; - } - break; - } - } - debug && debug( - `Automatic rejection of incoming channel request: ${type}` - ); - reject && reject(); - }, - CHANNEL_EOF: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) - if (channel.constructor === Session) { - if (!channel._ending) { - channel._ending = true; - channel.emit('eof'); - channel.emit('end'); - } - channel = channel._channel; - if (!channel) - return; - } + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; + // 3. Otherwise, return r. + return r +} - if (channel.readable) - channel.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: 'Sequence', + message: `Value of type ${webidl.util.Type(V)} is not an Object.` + }) + } - if (channel.constructor === Session) { - channel._ending = true; - channel.emit('close'); - channel = channel._channel; - if (!channel) - return; - } + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = V?.[Symbol.iterator]?.() + const seq = [] - onCHANNEL_CLOSE(this, recipient, channel); - }, - // Begin service/auth-related ========================================== - SERVICE_REQUEST: (p, service) => { - if (exchanges === 0 - || acceptedAuthSvc - || this.authenticated - || service !== 'ssh-userauth') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: 'Sequence', + message: 'Object is not an iterator.' + }) + } - acceptedAuthSvc = true; - proto.serviceAccept(service); - }, - USERAUTH_REQUEST: (p, username, service, method, methodData) => { - if (exchanges === 0 - || this.authenticated - || (authCtx - && (authCtx.username !== username - || authCtx.service !== service)) - // TODO: support hostbased auth - || (method !== 'password' - && method !== 'publickey' - && method !== 'hostbased' - && method !== 'keyboard-interactive' - && method !== 'none') - || pendingAuths.length === MAX_PENDING_AUTHS) { - proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); - socket.end(); - return; - } else if (service !== 'ssh-connection') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() - let ctx; - switch (method) { - case 'keyboard-interactive': - ctx = new KeyboardAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'publickey': - ctx = new PKAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'hostbased': - ctx = new HostbasedAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'password': - if (authCtx - && authCtx instanceof PwdAuthContext - && authCtx._changeCb) { - const cb = authCtx._changeCb; - authCtx._changeCb = undefined; - cb(methodData.newPassword); - return; - } - ctx = new PwdAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'none': - ctx = new AuthContext(proto, username, service, method, - onAuthDecide); - break; - } + if (done) { + break + } - if (authCtx) { - if (!authCtx._initialResponse) { - return pendingAuths.push(ctx); - } else if (authCtx._multistep && !authCtx._finalResponse) { - // RFC 4252 says to silently abort the current auth request if a - // new auth request comes in before the final response from an - // auth method that requires additional request/response exchanges - // -- this means keyboard-interactive for now ... - authCtx._cleanup && authCtx._cleanup(); - authCtx.emit('abort'); - } - } + seq.push(converter(value)) + } - authCtx = ctx; + return seq + } +} - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - }, - USERAUTH_INFO_RESPONSE: (p, responses) => { - if (authCtx && authCtx instanceof KeyboardAuthContext) - authCtx._onInfoResponse(responses); - }, - // End service/auth-related ============================================ - GLOBAL_REQUEST: (p, name, wantReply, data) => { - const reply = { - type: null, - buf: null - }; +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: 'Record', + message: `Value of type ${webidl.util.Type(O)} is not an Object.` + }) + } - function setReply(type, buf) { - reply.type = type; - reply.buf = buf; - sendReplies(); - } + // 2. Let result be a new empty instance of record. + const result = {} - if (wantReply) - unsentGlobalRequestsReplies.push(reply); + if (!types.isProxy(O)) { + // Object.keys only returns enumerable properties + const keys = Object.keys(O) - if ((name === 'tcpip-forward' - || name === 'cancel-tcpip-forward' - || name === 'no-more-sessions@openssh.com' - || name === 'streamlocal-forward@openssh.com' - || name === 'cancel-streamlocal-forward@openssh.com') - && listenerCount(this, 'request') - && this.authenticated) { - let accept; - let reject; + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) - if (wantReply) { - let replied = false; - accept = (chosenPort) => { - if (replied) - return; - replied = true; - let bufPort; - if (name === 'tcpip-forward' - && data.bindPort === 0 - && typeof chosenPort === 'number') { - bufPort = Buffer.allocUnsafe(4); - writeUInt32BE(bufPort, chosenPort, 0); - } - setReply('SUCCESS', bufPort); - }; - reject = () => { - if (replied) - return; - replied = true; - setReply('FAILURE'); - }; - } + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) - if (name === 'no-more-sessions@openssh.com') { - this.noMoreSessions = true; - accept && accept(); - return; - } + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } - this.emit('request', accept, reject, name, data); - } else if (wantReply) { - setReply('FAILURE'); - } - }, - }, - }); + // 5. Return result. + return result + } - socket.pause(); - cryptoInit.then(() => { - proto.start(); - socket.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - } - }); - socket.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - }); - socket.on('error', (err) => { - err.level = 'socket'; - this.emit('error', err); - }).once('end', () => { - debug && debug('Socket ended'); - proto.cleanup(); - this.emit('end'); - }).once('close', () => { - debug && debug('Socket closed'); - proto.cleanup(); - this.emit('close'); + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) - const err = new Error('No response from server'); + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) - // Simulate error for pending channels and close any open channels - this._chanMgr.cleanup(err); - }); + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) - const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { - if (authCtx === ctx && !this.authenticated) { - if (allowed) { - authCtx = undefined; - this.authenticated = true; - proto.authSuccess(); - pendingAuths = []; - this.emit('ready'); - } else { - proto.authFailure(methodsLeft, isPartial); - if (pendingAuths.length) { - authCtx = pendingAuths.pop(); - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - } - } - } - }; + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) - function sendReplies() { - while (unsentGlobalRequestsReplies.length > 0 - && unsentGlobalRequestsReplies[0].type) { - const reply = unsentGlobalRequestsReplies.shift(); - if (reply.type === 'SUCCESS') - proto.requestSuccess(reply.buf); - if (reply.type === 'FAILURE') - proto.requestFailure(); + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue } } + + // 5. Return result. + return result } +} - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); +webidl.interfaceConverter = function (i) { + return (V, opts = {}) => { + if (opts.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: i.name, + message: `Expected ${V} to be an instance of ${i.name}.` + }) } - return this; - } - x11(originAddr, originPort, cb) { - const opts = { originAddr, originPort }; - openChannel(this, 'x11', opts, cb); - return this; + return V } +} - forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { - const opts = { boundAddr, boundPort, remoteAddr, remotePort }; - openChannel(this, 'forwarded-tcpip', opts, cb); - return this; - } +webidl.dictionaryConverter = function (converters) { + return (dictionary) => { + const type = webidl.util.Type(dictionary) + const dict = {} - openssh_forwardOutStreamLocal(socketPath, cb) { - const opts = { socketPath }; - openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); - return this; - } + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } - rekey(cb) { - let error; + for (const options of converters) { + const { key, defaultValue, required, converter } = options - try { - this._protocol.rekey(); - } catch (ex) { - error = ex; - } + if (required === true) { + if (!hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key] + const hasDefault = hasOwn(options, 'defaultValue') + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value = value ?? defaultValue + } - // TODO: re-throw error if no callback? + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value) - if (typeof cb === 'function') { - if (error) - process.nextTick(cb, error); - else - this.once('rekey', cb); + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value + } } + + return dict } } +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V + } -function openChannel(self, type, opts, cb) { - // Ask the client to open a channel for some purpose (e.g. a forwarded TCP - // connection) - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; + return converter(V) + } +} - if (typeof opts === 'function') { - cb = opts; - opts = {}; +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, opts = {}) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts.legacyNullToEmptyString) { + return '' } - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw new TypeError('Could not convert argument of type symbol to string.') + } - const localChan = self._chanMgr.add(wrapper); + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) +} - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V) - switch (type) { - case 'forwarded-tcpip': - self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'x11': - self._protocol.x11(localChan, initWindow, maxPacket, opts); - break; - case 'forwarded-streamlocal@openssh.com': - self._protocol.openssh_forwardedStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) + } } -} -function compareNumbers(a, b) { - return a - b; + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x } -module.exports = Server; -module.exports.IncomingClient = Client; +// https://webidl.spec.whatwg.org/#es-USVString +webidl.converters.USVString = toUSVString +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V) -/***/ }), + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} -/***/ 834: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V +} -"use strict"; +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed') + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} -const { SFTP } = __nccwpck_require__(2026); +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned') -const MAX_CHANNEL = 2 ** 32 - 1; + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} -function onChannelOpenFailure(self, recipient, info, cb) { - self._chanMgr.remove(recipient); - if (typeof cb !== 'function') - return; +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned') - let err; - if (info instanceof Error) { - err = info; - } else if (typeof info === 'object' && info !== null) { - err = new Error(`(SSH) Channel open failure: ${info.description}`); - err.reason = info.reason; - } else { - err = new Error( - '(SSH) Channel open failure: server closed channel unexpectedly' - ); - err.reason = ''; - } + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} - cb(err); +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x } -function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { - if (typeof channel === 'function') { - // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when - // requesting to open a channel - onChannelOpenFailure(self, recipient, err, channel); - return; +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix: `${V}`, + argument: `${V}`, + types: ['ArrayBuffer'] + }) } - if (typeof channel !== 'object' || channel === null) - return; + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } - if (channel.incoming && channel.incoming.state === 'closed') - return; + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + // Note: resizable ArrayBuffers are currently a proposal. + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +webidl.converters.TypedArray = function (V, T, opts = {}) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix: `${T.name}`, + argument: `${V}`, + types: [T.name] + }) + } - self._chanMgr.remove(recipient); + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } - if (channel.server && channel.constructor.name === 'Session') - return; + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable array buffers are currently a proposal - channel.incoming.state = 'closed'; + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V +} - if (channel.readable) - channel.push(null); - if (channel.server) { - if (channel.stderr.writable) - channel.stderr.end(); - } else if (channel.stderr.readable) { - channel.stderr.push(null); +webidl.converters.DataView = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: 'DataView', + message: 'Object is not a DataView.' + }) } - if (channel.constructor !== SFTP - && (channel.outgoing.state === 'open' - || channel.outgoing.state === 'eof') - && !dead) { - channel.close(); + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) } - if (channel.outgoing.state === 'closing') - channel.outgoing.state = 'closed'; - const readState = channel._readableState; - const writeState = channel._writableState; - if (writeState && !writeState.ending && !writeState.finished && !dead) - channel.end(); + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable ArrayBuffers are currently a proposal - // Take care of any outstanding channel requests - const chanCallbacks = channel._callbacks; - channel._callbacks = []; - for (let i = 0; i < chanCallbacks.length; ++i) - chanCallbacks[i](true); + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V +} - if (channel.server) { - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - channel.emit('close'); - } else { - channel.once('end', () => channel.emit('close')); - } - } else { - let doClose; - switch (channel.type) { - case 'direct-streamlocal@openssh.com': - case 'direct-tcpip': - doClose = () => channel.emit('close'); - break; - default: { - // Align more with node child processes, where the close event gets - // the same arguments as the exit event - const exit = channel._exit; - doClose = () => { - if (exit.code === null) - channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); - else - channel.emit('close', exit.code); - }; - } - } - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - doClose(); - } else { - channel.once('end', doClose); - } +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, opts = {}) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, opts) + } - const errReadState = channel.stderr._readableState; - if (!channel.stderr.readable - || channel.stderr.destroyed - || (errReadState && errReadState.endEmitted)) { - channel.stderr.emit('close'); - } else { - channel.stderr.once('end', () => channel.stderr.emit('close')); - } + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor) } -} -class ChannelManager { - constructor(client) { - this._client = client; - this._channels = {}; - this._cur = -1; - this._count = 0; + if (types.isDataView(V)) { + return webidl.converters.DataView(V, opts) } - add(val) { - // Attempt to reserve an id - let id; - // Optimized paths - if (this._cur < MAX_CHANNEL) { - id = ++this._cur; - } else if (this._count === 0) { - // Revert and reset back to fast path once we no longer have any channels - // open - this._cur = 0; - id = 0; - } else { - // Slower lookup path + throw new TypeError(`Could not convert ${V} to a BufferSource.`) +} - // This path is triggered we have opened at least MAX_CHANNEL channels - // while having at least one channel open at any given time, so we have - // to search for a free id. - const channels = this._channels; - for (let i = 0; i < MAX_CHANNEL; ++i) { - if (channels[i] === undefined) { - id = i; - break; - } - } - } +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) - if (id === undefined) - return -1; +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) - this._channels[id] = (val || true); - ++this._count; +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) - return id; - } - update(id, val) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); +module.exports = { + webidl +} - if (val && this._channels[id]) - this._channels[id] = val; - } - get(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - return this._channels[id]; - } - remove(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); +/***/ }), - if (this._channels[id]) { - delete this._channels[id]; - if (this._count) - --this._count; - } +/***/ 4854: +/***/ ((module) => { + +"use strict"; + + +/** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ +function getEncoding (label) { + if (!label) { + return 'failure' } - cleanup(err) { - const channels = this._channels; - this._channels = {}; - this._cur = -1; - this._count = 0; - const chanIDs = Object.keys(channels); - const client = this._client; - for (let i = 0; i < chanIDs.length; ++i) { - const id = +chanIDs[i]; - const channel = channels[id]; - onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); - } + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' } } -const isRegExp = (() => { - const toString = Object.prototype.toString; - return (val) => toString.call(val) === '[object RegExp]'; -})(); +module.exports = { + getEncoding +} -function generateAlgorithmList(algoList, defaultList, supportedList) { - if (Array.isArray(algoList) && algoList.length > 0) { - // Exact list - for (let i = 0; i < algoList.length; ++i) { - if (supportedList.indexOf(algoList[i]) === -1) - throw new Error(`Unsupported algorithm: ${algoList[i]}`); + +/***/ }), + +/***/ 1446: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = __nccwpck_require__(7530) +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = __nccwpck_require__(9054) +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) + +class FileReader extends EventTarget { + constructor () { + super() + + this[kState] = 'empty' + this[kResult] = null + this[kError] = null + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null } - return algoList; } - if (typeof algoList === 'object' && algoList !== null) { - // Operations based on the default list - const keys = Object.keys(algoList); - let list = defaultList; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - let val = algoList[key]; - switch (key) { - case 'append': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const append = val[j]; - if (typeof append === 'string') { - if (!append || list.indexOf(append) !== -1) - continue; - if (supportedList.indexOf(append) === -1) - throw new Error(`Unsupported algorithm: ${append}`); - if (list === defaultList) - list = list.slice(); - list.push(append); - } else if (isRegExp(append)) { - for (let k = 0; k < supportedList.length; ++k) { - const algo = supportedList[k]; - if (append.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.push(algo); - } - } - } - } - } - break; - case 'prepend': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = val.length; j >= 0; --j) { - const prepend = val[j]; - if (typeof prepend === 'string') { - if (!prepend || list.indexOf(prepend) !== -1) - continue; - if (supportedList.indexOf(prepend) === -1) - throw new Error(`Unsupported algorithm: ${prepend}`); - if (list === defaultList) - list = list.slice(); - list.unshift(prepend); - } else if (isRegExp(prepend)) { - for (let k = supportedList.length; k >= 0; --k) { - const algo = supportedList[k]; - if (prepend.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.unshift(algo); - } - } - } - } - } - break; - case 'remove': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const search = val[j]; - if (typeof search === 'string') { - if (!search) - continue; - const idx = list.indexOf(search); - if (idx === -1) - continue; - if (list === defaultList) - list = list.slice(); - list.splice(idx, 1); - } else if (isRegExp(search)) { - for (let k = 0; k < list.length; ++k) { - if (search.test(list[k])) { - if (list === defaultList) - list = list.slice(); - list.splice(k, 1); - --k; - } - } - } - } - } - break; - } - } + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader) - return list; + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer') } - return defaultList; -} + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader) -module.exports = { - ChannelManager, - generateAlgorithmList, - onChannelOpenFailure, - onCHANNEL_CLOSE, - isWritable: (stream) => { - // XXX: hack to workaround regression in node - // See: https://github.com/nodejs/node/issues/36029 - return (stream - && stream.writable - && stream._readableState - && stream._readableState.ended === false); - }, -}; + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) + blob = webidl.converters.Blob(blob, { strict: false }) -/***/ }), + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString') + } -/***/ 4841: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader) -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) + blob = webidl.converters.Blob(blob, { strict: false }) + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding) + } -/**/ + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding) + } -var Buffer = (__nccwpck_require__(2279).Buffer); -/**/ + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader) -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL') } -}; -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null + return + } + + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done' + this[kResult] = null + } + + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true + + // 4. Terminate the algorithm for the read method being processed. + // TODO + + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) + + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) } } -}; -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader) -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader) + + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader) + + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; -StringDecoder.prototype.end = utf8End; + get onloadend () { + webidl.brandCheck(this, FileReader) -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; + return this[kEvents].loadend + } -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); + set onloadend (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend) + } + + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null + } } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} + get onerror () { + webidl.brandCheck(this, FileReader) -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; + return this[kEvents].error } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; + + set onerror (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error) + } + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null + } } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + + get onloadstart () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadstart + } + + set onloadstart (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart) + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null } - return nb; } - return 0; -} -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; + get onprogress () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].progress } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; + + set onprogress (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } + + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null } } -} -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); + get onload () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].load } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} + set onload (fn) { + webidl.brandCheck(this, FileReader) -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) + } -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null } - return r; } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); + get onabort () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].abort } - return r; -} -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; + set onabort (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort) + } + + if (typeof fn === 'function') { + this[kEvents].abort = fn + this.addEventListener('abort', fn) + } else { + this[kEvents].abort = null + } + } +} + +// https://w3c.github.io/FileAPI/#dom-filereader-empty +FileReader.EMPTY = FileReader.prototype.EMPTY = 0 +// https://w3c.github.io/FileAPI/#dom-filereader-loading +FileReader.LOADING = FileReader.prototype.LOADING = 1 +// https://w3c.github.io/FileAPI/#dom-filereader-done +FileReader.DONE = FileReader.prototype.DONE = 2 + +Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true } - return buf.toString('base64', i, buf.length - n); -} +}) -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); +module.exports = { + FileReader } -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} /***/ }), -/***/ 2279: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 5504: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(4300) -var Buffer = buffer.Buffer +"use strict"; -// 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) -} +const { webidl } = __nccwpck_require__(1744) -SafeBuffer.prototype = Object.create(Buffer.prototype) +const kState = Symbol('ProgressEvent state') -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') + super(type, eventInitDict) + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + } } - return Buffer(arg, encodingOrOffset, length) -} -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].lengthComputable } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) + + get loaded () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].loaded } - return buf -} -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + get total () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].total } - return Buffer(size) } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false } - return buffer.SlowBuffer(size) +]) + +module.exports = { + ProgressEvent } /***/ }), -/***/ 9318: +/***/ 9054: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') +} + + +/***/ }), + +/***/ 7530: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const os = __nccwpck_require__(2037); -const tty = __nccwpck_require__(6224); -const hasFlag = __nccwpck_require__(1621); -const {env} = process; +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = __nccwpck_require__(9054) +const { ProgressEvent } = __nccwpck_require__(5504) +const { getEncoding } = __nccwpck_require__(4854) +const { DOMException } = __nccwpck_require__(1037) +const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(685) +const { types } = __nccwpck_require__(3837) +const { StringDecoder } = __nccwpck_require__(1576) +const { btoa } = __nccwpck_require__(4300) + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; +/** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ +function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading' + + // 3. Set fr’s result to null. + fr[kResult] = null + + // 4. Set fr’s error to null. + fr[kError] = null + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream() + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader() + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = [] + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr) + }) + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value) + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now() + queueMicrotask(() => { + fireAProgressEvent('progress', fr) + }) + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read() + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName) + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr) + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Set fr’s error to error. + fr[kError] = error + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } + })() } -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } +/** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ +function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }) + + reader.dispatchEvent(event) } -function translateLevel(level) { - if (level === 0) { - return false; - } +/** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ +function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:' + + const parsed = parseMIMEType(mimeType || 'application/octet-stream') + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed) + } + + dataURL += ';base64,' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)) + } + + dataURL += btoa(decoder.end()) + + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure' + + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName) + } + + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType) + + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')) + } + } + + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8' + } + + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) + } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes) + + return sequence.buffer + } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = '' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + binaryString += decoder.write(chunk) + } + + binaryString += decoder.end() + + return binaryString + } + } } -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } +/** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ +function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue) - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes) - if (hasFlag('color=256')) { - return 2; - } + let slice = 0 - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding - const min = forceColor || 0; + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2 + } - if (env.TERM === 'dumb') { - return min; - } + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } + // 4. Return output. - return 1; - } + const sliced = bytes.slice(slice) + return new TextDecoder(encoding).decode(sliced) +} - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } +/** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ +function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue - return min; - } + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } + return null +} - if (env.COLORTERM === 'truecolor') { - return 3; - } +/** + * @param {Uint8Array[]} sequences + */ +function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0) - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + let offset = 0 - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } + return sequences.reduce((a, b) => { + a.set(b, offset) + offset += b.byteLength + return a + }, new Uint8Array(size)) +} - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +module.exports = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ('COLORTERM' in env) { - return 1; - } +/***/ }), - return min; +/***/ 1892: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = __nccwpck_require__(8045) +const Agent = __nccwpck_require__(7890) + +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) } -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) +} + +function getGlobalDispatcher () { + return globalThis[globalDispatcher] } module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; + setGlobalDispatcher, + getGlobalDispatcher +} + + +/***/ }), + +/***/ 6930: +/***/ ((module) => { + +"use strict"; -/***/ }), +module.exports = class DecoratorHandler { + constructor (handler) { + this.handler = handler + } -/***/ 366: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + onConnect (...args) { + return this.handler.onConnect(...args) + } -var chownr = __nccwpck_require__(9051) -var tar = __nccwpck_require__(2283) -var pump = __nccwpck_require__(8341) -var mkdirp = __nccwpck_require__(7614) -var fs = __nccwpck_require__(7147) -var path = __nccwpck_require__(1017) -var os = __nccwpck_require__(2037) + onError (...args) { + return this.handler.onError(...args) + } -var win32 = os.platform() === 'win32' + onUpgrade (...args) { + return this.handler.onUpgrade(...args) + } -var noop = function () {} + onHeaders (...args) { + return this.handler.onHeaders(...args) + } -var echo = function (name) { - return name -} + onData (...args) { + return this.handler.onData(...args) + } -var normalize = !win32 ? echo : function (name) { - return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_') + onComplete (...args) { + return this.handler.onComplete(...args) + } + + onBodySent (...args) { + return this.handler.onBodySent(...args) + } } -var statAll = function (fs, stat, cwd, ignore, entries, sort) { - var queue = entries || ['.'] - return function loop (callback) { - if (!queue.length) return callback() - var next = queue.shift() - var nextAbs = path.join(cwd, next) +/***/ }), - stat(nextAbs, function (err, stat) { - if (err) return callback(err) +/***/ 2860: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!stat.isDirectory()) return callback(null, next, stat) +"use strict"; - fs.readdir(nextAbs, function (err, files) { - if (err) return callback(err) - if (sort) files.sort() - for (var i = 0; i < files.length; i++) { - if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) - } +const util = __nccwpck_require__(3983) +const { kBodyUsed } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const EE = __nccwpck_require__(2361) - callback(null, next, stat) - }) - }) - } -} +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] -var strip = function (map, level) { - return function (header) { - header.name = header.name.split('/').slice(level).join('/') +const kBody = Symbol('body') - var linkname = header.linkname - if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { - header.linkname = linkname.split('/').slice(level).join('/') - } +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } - return map(header) + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] } } -exports.pack = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} +class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) - var strict = opts.strict !== false - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var pack = opts.pack || tar.pack() - var finish = opts.finish || noop + util.validateHandler(handler, opts.method, opts.upgrade) - if (opts.strip) map = strip(map, opts.strip) + this.dispatch = dispatch + this.location = null + this.abort = null + this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) + } } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) + + onConnect (abort) { + this.abort = abort + this.handler.onConnect(abort, { history: this.history }) } - var onsymlink = function (filename, header) { - xfs.readlink(path.join(cwd, filename), function (err, linkname) { - if (err) return pack.destroy(err) - header.linkname = normalize(linkname) - pack.entry(header, onnextentry) - }) + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket) } - var onstat = function (err, filename, stat) { - if (err) return pack.destroy(err) - if (!filename) { - if (opts.finalize !== false) pack.finalize() - return finish(pack) - } + onError (error) { + this.handler.onError(error) + } - if (stat.isSocket()) return onnextentry() // tar does not support sockets... + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers) - var header = { - name: normalize(filename), - mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, - mtime: stat.mtime, - size: stat.size, - type: 'file', - uid: stat.uid, - gid: stat.gid + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) } - if (stat.isDirectory()) { - header.size = 0 - header.type = 'directory' - header = map(header) || header - return pack.entry(header, onnextentry) + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) } - if (stat.isSymbolicLink()) { - header.size = 0 - header.type = 'symlink' - header = map(header) || header - return onsymlink(filename, header) + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.maxRedirections = 0 + this.opts.query = null + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + this.opts.body = null } + } - // TODO: add fifo etc... + onData (chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 - header = map(header) || header + TLDR: undici always ignores 3xx response bodies. - if (!stat.isFile()) { - if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) - return onnextentry() + Redirection is used to serve the requested resource from another URL, so it is assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. + + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. + + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitily chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + return this.handler.onData(chunk) } + } - var entry = pack.entry(header, onnextentry) - if (!entry) return + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 - var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header) + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. - rs.on('error', function (err) { // always forward errors on destroy - entry.destroy(err) - }) + See comment on onData method above for more detailed informations. + */ - pump(rs, entry) + this.location = null + this.abort = null + + this.dispatch(this.opts, this) + } else { + this.handler.onComplete(trailers) + } } - var onnextentry = function (err) { - if (err) return pack.destroy(err) - statNext(onstat) + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk) + } } +} - onnextentry() +function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } - return pack + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toString().toLowerCase() === 'location') { + return headers[i + 1] + } + } } -var head = function (list) { - return list.length ? list[list.length - 1] : null +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false } -var processGetuid = function () { - return process.getuid ? process.getuid() : -1 +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret } -var processUmask = function () { - return process.umask ? process.umask() : 0 -} +module.exports = RedirectHandler -exports.extract = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var own = opts.chown !== false && !win32 && processGetuid() === 0 - var extract = opts.extract || tar.extract() - var stack = [] - var now = new Date() - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var strict = opts.strict !== false +/***/ }), - if (opts.strip) map = strip(map, opts.strip) +/***/ 2286: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) - } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) +const assert = __nccwpck_require__(9491) + +const { kRetryHandlerDefaultRetry } = __nccwpck_require__(2785) +const { RequestRetryError } = __nccwpck_require__(8045) +const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3983) + +function calculateRetryAfterHeader (retryAfter) { + const current = Date.now() + const diff = new Date(retryAfter).getTime() - current + + return diff +} + +class RetryHandler { + constructor (opts, handlers) { + const { retryOptions, ...dispatchOpts } = opts + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes + } = retryOptions ?? {} + + this.dispatch = handlers.dispatch + this.handler = handlers.handler + this.opts = dispatchOpts + this.abort = null + this.aborted = false + this.retryOpts = { + retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1000, // 30s, + timeout: minTimeout ?? 500, // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + 'ECONNRESET', + 'ECONNREFUSED', + 'ENOTFOUND', + 'ENETDOWN', + 'ENETUNREACH', + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'EPIPE' + ] + } + + this.retryCount = 0 + this.start = 0 + this.end = null + this.etag = null + this.resume = null + + // Handle possible onConnect duplication + this.handler.onConnect(reason => { + this.aborted = true + if (this.abort) { + this.abort(reason) + } else { + this.reason = reason + } + }) } - var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry - var top - while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() - if (!top) return cb() - xfs.utimes(top[0], now, top[1], cb) + onRequestSent () { + if (this.handler.onRequestSent) { + this.handler.onRequestSent() + } } - var utimes = function (name, header, cb) { - if (opts.utimes === false) return cb() - - if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) - if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? + onUpgrade (statusCode, headers, socket) { + if (this.handler.onUpgrade) { + this.handler.onUpgrade(statusCode, headers, socket) + } + } - xfs.utimes(name, now, header.mtime, function (err) { - if (err) return cb(err) - utimesParent(name, cb) - }) + onConnect (abort) { + if (this.aborted) { + abort(this.reason) + } else { + this.abort = abort + } } - var chperm = function (name, header, cb) { - var link = header.type === 'symlink' + onBodySent (chunk) { + if (this.handler.onBodySent) return this.handler.onBodySent(chunk) + } - /* eslint-disable node/no-deprecated-api */ - var chmod = link ? xfs.lchmod : xfs.chmod - var chown = link ? xfs.lchown : xfs.chown - /* eslint-enable node/no-deprecated-api */ + static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { + const { statusCode, code, headers } = err + const { method, retryOptions } = opts + const { + maxRetries, + timeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions + let { counter, currentTimeout } = state - if (!chmod) return cb() + currentTimeout = + currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout - var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask - chmod(name, mode, function (err) { - if (err) return cb(err) - if (!own) return cb() - if (!chown) return cb() - chown(name, header.uid, header.gid, cb) - }) - } + // Any code that is not a Undici's originated and allowed to retry + if ( + code && + code !== 'UND_ERR_REQ_RETRY' && + code !== 'UND_ERR_SOCKET' && + !errorCodes.includes(code) + ) { + cb(err) + return + } - extract.on('entry', function (header, stream, next) { - header = map(header) || header - header.name = normalize(header.name) - var name = path.join(cwd, path.join('/', header.name)) + // If a set of method are provided and the current method is not in the list + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err) + return + } - if (ignore(name, header)) { - stream.resume() - return next() + // If a set of status code are provided and the current status code is not in the list + if ( + statusCode != null && + Array.isArray(statusCodes) && + !statusCodes.includes(statusCode) + ) { + cb(err) + return } - var stat = function (err) { - if (err) return next(err) - utimes(name, header, function (err) { - if (err) return next(err) - if (win32) return next() - chperm(name, header, next) - }) + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err) + return } - var onsymlink = function () { - if (win32) return next() // skip symlinks on win for now before it can be tested - xfs.unlink(name, function () { - xfs.symlink(header.linkname, name, stat) - }) + let retryAfterHeader = headers != null && headers['retry-after'] + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader) + retryAfterHeader = isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(retryAfterHeader) + : retryAfterHeader * 1e3 // Retry-After is in seconds } - var onlink = function () { - if (win32) return next() // skip links on win for now before it can be tested - xfs.unlink(name, function () { - var srcpath = path.join(cwd, path.join('/', header.linkname)) + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) - xfs.link(srcpath, name, function (err) { - if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { - stream = xfs.createReadStream(srcpath) - return onfile() - } + state.currentTimeout = retryTimeout - stat(err) + setTimeout(() => cb(null), retryTimeout) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = parseHeaders(rawHeaders) + + this.retryCount += 1 + + if (statusCode >= 300) { + this.abort( + new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount }) - }) + ) + return false } - var onfile = function () { - var ws = xfs.createWriteStream(name) - var rs = mapStream(stream, header) + // Checkpoint for resume from where we left it + if (this.resume != null) { + this.resume = null - ws.on('error', function (err) { // always forward errors on destroy - rs.destroy(err) - }) + if (statusCode !== 206) { + return true + } - pump(rs, ws, function (err) { - if (err) return next(err) - ws.on('close', stat) - }) - } + const contentRange = parseRangeHeader(headers['content-range']) + // If no content range + if (!contentRange) { + this.abort( + new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } - if (header.type === 'directory') { - stack.push([name, header.mtime]) - return mkdirfix(name, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, stat) - } + // Let's start with a weak etag check + if (this.etag != null && this.etag !== headers.etag) { + this.abort( + new RequestRetryError('ETag mismatch', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } - var dir = path.dirname(name) + const { start, size, end = size } = contentRange - validate(xfs, dir, path.join(cwd, '.'), function (err, valid) { - if (err) return next(err) - if (!valid) return next(new Error(dir + ' is not a valid path')) + assert(this.start === start, 'content-range mismatch') + assert(this.end == null || this.end === end, 'content-range mismatch') - mkdirfix(dir, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, function (err) { - if (err) return next(err) + this.resume = resume + return true + } - switch (header.type) { - case 'file': return onfile() - case 'link': return onlink() - case 'symlink': return onsymlink() + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']) + + if (range == null) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) } - if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) + const { start, size, end = size } = range - stream.resume() - next() - }) + assert( + start != null && Number.isFinite(start) && this.start !== start, + 'content-range mismatch' + ) + assert(Number.isFinite(start)) + assert( + end != null && Number.isFinite(end) && this.end !== end, + 'invalid content-length' + ) + + this.start = start + this.end = end + } + + // We make our best to checkpoint the body for further range headers + if (this.end == null) { + const contentLength = headers['content-length'] + this.end = contentLength != null ? Number(contentLength) : null + } + + assert(Number.isFinite(this.start)) + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) + + this.resume = resume + this.etag = headers.etag != null ? headers.etag : null + + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const err = new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount }) - }) - if (opts.finish) extract.on('finish', opts.finish) + this.abort(err) - return extract -} + return false + } -function validate (fs, name, root, cb) { - if (name === root) return cb(null, true) - fs.lstat(name, function (err, st) { - if (err && err.code !== 'ENOENT') return cb(err) - if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb) - cb(null, false) - }) -} + onData (chunk) { + this.start += chunk.length -function mkdirfix (name, opts, cb) { - mkdirp(name, { fs: opts.fs }, function (err, made) { - if (!err && made && opts.own) { - chownr(made, opts.uid, opts.gid, cb) - } else { - cb(err) + return this.handler.onData(chunk) + } + + onComplete (rawTrailers) { + this.retryCount = 0 + return this.handler.onComplete(rawTrailers) + } + + onError (err) { + if (this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) } - }) + + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + onRetry.bind(this) + ) + + function onRetry (err) { + if (err != null || this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + if (this.start !== 0) { + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + range: `bytes=${this.start}-${this.end ?? ''}` + } + } + } + + try { + this.dispatch(this.opts, this) + } catch (err) { + this.handler.onError(err) + } + } + } } +module.exports = RetryHandler + /***/ }), -/***/ 7882: +/***/ 8861: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(3837) -var bl = __nccwpck_require__(336) -var headers = __nccwpck_require__(8860) +"use strict"; -var Writable = (__nccwpck_require__(1642).Writable) -var PassThrough = (__nccwpck_require__(1642).PassThrough) -var noop = function () {} +const RedirectHandler = __nccwpck_require__(2860) -var overflow = function (size) { - size &= 511 - return size && 512 - size -} +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts -var emptyStream = function (self, offset) { - var s = new Source(self, offset) - s.end() - return s -} + if (!maxRedirections) { + return dispatch(opts, handler) + } -var mixinPax = function (header, pax) { - if (pax.path) header.name = pax.path - if (pax.linkpath) header.linkname = pax.linkpath - if (pax.size) header.size = parseInt(pax.size, 10) - header.pax = pax - return header + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } } -var Source = function (self, offset) { - this._parent = self - this.offset = offset - PassThrough.call(this, { autoDestroy: false }) +module.exports = createRedirectInterceptor + + +/***/ }), + +/***/ 953: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = __nccwpck_require__(1891); +// C headers +var ERROR; +(function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; +})(ERROR = exports.ERROR || (exports.ERROR = {})); +var TYPE; +(function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; +})(TYPE = exports.TYPE || (exports.TYPE = {})); +var FLAGS; +(function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; +})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); +var LENIENT_FLAGS; +(function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; +})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); +var METHODS; +(function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; +})(METHODS = exports.METHODS || (exports.METHODS = {})); +exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, +]; +exports.METHODS_ICE = [ + METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, +]; +exports.METHOD_MAP = utils_1.enumToMap(METHODS); +exports.H_METHOD_MAP = {}; +Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } +}); +var FINISH; +(function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; +})(FINISH = exports.FINISH || (exports.FINISH = {})); +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); +// All characters with 0x80 bit set to 1 +for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); +} +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +var HEADER_STATE; +(function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; +})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); +exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, +}; +//# sourceMappingURL=constants.js.map + +/***/ }), + +/***/ 1145: +/***/ ((module) => { + +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkBigGLAYwBjQGOAY8BkAGRAZIBkwGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwHLAcoBuAHJAbkByAG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAQDcAQtBACEQDMYBC0EOIRAMxQELQQ0hEAzEAQtBDyEQDMMBC0EQIRAMwgELQRMhEAzBAQtBFCEQDMABC0EVIRAMvwELQRYhEAy+AQtBFyEQDL0BC0EYIRAMvAELQRkhEAy7AQtBGiEQDLoBC0EbIRAMuQELQRwhEAy4AQtBCCEQDLcBC0EdIRAMtgELQSAhEAy1AQtBHyEQDLQBC0EHIRAMswELQSEhEAyyAQtBIiEQDLEBC0EeIRAMsAELQSMhEAyvAQtBEiEQDK4BC0ERIRAMrQELQSQhEAysAQtBJSEQDKsBC0EmIRAMqgELQSchEAypAQtBwwEhEAyoAQtBKSEQDKcBC0ErIRAMpgELQSwhEAylAQtBLSEQDKQBC0EuIRAMowELQS8hEAyiAQtBxAEhEAyhAQtBMCEQDKABC0E0IRAMnwELQQwhEAyeAQtBMSEQDJ0BC0EyIRAMnAELQTMhEAybAQtBOSEQDJoBC0E1IRAMmQELQcUBIRAMmAELQQshEAyXAQtBOiEQDJYBC0E2IRAMlQELQQohEAyUAQtBNyEQDJMBC0E4IRAMkgELQTwhEAyRAQtBOyEQDJABC0E9IRAMjwELQQkhEAyOAQtBKCEQDI0BC0E+IRAMjAELQT8hEAyLAQtBwAAhEAyKAQtBwQAhEAyJAQtBwgAhEAyIAQtBwwAhEAyHAQtBxAAhEAyGAQtBxQAhEAyFAQtBxgAhEAyEAQtBKiEQDIMBC0HHACEQDIIBC0HIACEQDIEBC0HJACEQDIABC0HKACEQDH8LQcsAIRAMfgtBzQAhEAx9C0HMACEQDHwLQc4AIRAMewtBzwAhEAx6C0HQACEQDHkLQdEAIRAMeAtB0gAhEAx3C0HTACEQDHYLQdQAIRAMdQtB1gAhEAx0C0HVACEQDHMLQQYhEAxyC0HXACEQDHELQQUhEAxwC0HYACEQDG8LQQQhEAxuC0HZACEQDG0LQdoAIRAMbAtB2wAhEAxrC0HcACEQDGoLQQMhEAxpC0HdACEQDGgLQd4AIRAMZwtB3wAhEAxmC0HhACEQDGULQeAAIRAMZAtB4gAhEAxjC0HjACEQDGILQQIhEAxhC0HkACEQDGALQeUAIRAMXwtB5gAhEAxeC0HnACEQDF0LQegAIRAMXAtB6QAhEAxbC0HqACEQDFoLQesAIRAMWQtB7AAhEAxYC0HtACEQDFcLQe4AIRAMVgtB7wAhEAxVC0HwACEQDFQLQfEAIRAMUwtB8gAhEAxSC0HzACEQDFELQfQAIRAMUAtB9QAhEAxPC0H2ACEQDE4LQfcAIRAMTQtB+AAhEAxMC0H5ACEQDEsLQfoAIRAMSgtB+wAhEAxJC0H8ACEQDEgLQf0AIRAMRwtB/gAhEAxGC0H/ACEQDEULQYABIRAMRAtBgQEhEAxDC0GCASEQDEILQYMBIRAMQQtBhAEhEAxAC0GFASEQDD8LQYYBIRAMPgtBhwEhEAw9C0GIASEQDDwLQYkBIRAMOwtBigEhEAw6C0GLASEQDDkLQYwBIRAMOAtBjQEhEAw3C0GOASEQDDYLQY8BIRAMNQtBkAEhEAw0C0GRASEQDDMLQZIBIRAMMgtBkwEhEAwxC0GUASEQDDALQZUBIRAMLwtBlgEhEAwuC0GXASEQDC0LQZgBIRAMLAtBmQEhEAwrC0GaASEQDCoLQZsBIRAMKQtBnAEhEAwoC0GdASEQDCcLQZ4BIRAMJgtBnwEhEAwlC0GgASEQDCQLQaEBIRAMIwtBogEhEAwiC0GjASEQDCELQaQBIRAMIAtBpQEhEAwfC0GmASEQDB4LQacBIRAMHQtBqAEhEAwcC0GpASEQDBsLQaoBIRAMGgtBqwEhEAwZC0GsASEQDBgLQa0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAdUB1gHXAdgB2QHaAdsB3AHdAd4B4AHhAeIB4wHkAeUB5gHnAegB6QHqAesB7AHtAe4B7wHwAfEB8gHzAZkCpAKwAv4C/gILIAEiBCACRw3zAUHdASEQDP8DCyABIhAgAkcN3QFBwwEhEAz+AwsgASIBIAJHDZABQfcAIRAM/QMLIAEiASACRw2GAUHvACEQDPwDCyABIgEgAkcNf0HqACEQDPsDCyABIgEgAkcNe0HoACEQDPoDCyABIgEgAkcNeEHmACEQDPkDCyABIgEgAkcNGkEYIRAM+AMLIAEiASACRw0UQRIhEAz3AwsgASIBIAJHDVlBxQAhEAz2AwsgASIBIAJHDUpBPyEQDPUDCyABIgEgAkcNSEE8IRAM9AMLIAEiASACRw1BQTEhEAzzAwsgAC0ALkEBRg3rAwyHAgsgACABIgEgAhDAgICAAEEBRw3mASAAQgA3AyAM5wELIAAgASIBIAIQtICAgAAiEA3nASABIQEM9QILAkAgASIBIAJHDQBBBiEQDPADCyAAIAFBAWoiASACELuAgIAAIhAN6AEgASEBDDELIABCADcDIEESIRAM1QMLIAEiECACRw0rQR0hEAztAwsCQCABIgEgAkYNACABQQFqIQFBECEQDNQDC0EHIRAM7AMLIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN5QFBCCEQDOsDCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEUIRAM0gMLQQkhEAzqAwsgASEBIAApAyBQDeQBIAEhAQzyAgsCQCABIgEgAkcNAEELIRAM6QMLIAAgAUEBaiIBIAIQtoCAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3mASABIQEMDQsgACABIgEgAhC6gICAACIQDecBIAEhAQzwAgsCQCABIgEgAkcNAEEPIRAM5QMLIAEtAAAiEEE7Rg0IIBBBDUcN6AEgAUEBaiEBDO8CCyAAIAEiASACELqAgIAAIhAN6AEgASEBDPICCwNAAkAgAS0AAEHwtYCAAGotAAAiEEEBRg0AIBBBAkcN6wEgACgCBCEQIABBADYCBCAAIBAgAUEBaiIBELmAgIAAIhAN6gEgASEBDPQCCyABQQFqIgEgAkcNAAtBEiEQDOIDCyAAIAEiASACELqAgIAAIhAN6QEgASEBDAoLIAEiASACRw0GQRshEAzgAwsCQCABIgEgAkcNAEEWIRAM4AMLIABBioCAgAA2AgggACABNgIEIAAgASACELiAgIAAIhAN6gEgASEBQSAhEAzGAwsCQCABIgEgAkYNAANAAkAgAS0AAEHwt4CAAGotAAAiEEECRg0AAkAgEEF/ag4E5QHsAQDrAewBCyABQQFqIQFBCCEQDMgDCyABQQFqIgEgAkcNAAtBFSEQDN8DC0EVIRAM3gMLA0ACQCABLQAAQfC5gIAAai0AACIQQQJGDQAgEEF/ag4E3gHsAeAB6wHsAQsgAUEBaiIBIAJHDQALQRghEAzdAwsCQCABIgEgAkYNACAAQYuAgIAANgIIIAAgATYCBCABIQFBByEQDMQDC0EZIRAM3AMLIAFBAWohAQwCCwJAIAEiFCACRw0AQRohEAzbAwsgFCEBAkAgFC0AAEFzag4U3QLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gIA7gILQQAhECAAQQA2AhwgAEGvi4CAADYCECAAQQI2AgwgACAUQQFqNgIUDNoDCwJAIAEtAAAiEEE7Rg0AIBBBDUcN6AEgAUEBaiEBDOUCCyABQQFqIQELQSIhEAy/AwsCQCABIhAgAkcNAEEcIRAM2AMLQgAhESAQIQEgEC0AAEFQag435wHmAQECAwQFBgcIAAAAAAAAAAkKCwwNDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADxAREhMUAAtBHiEQDL0DC0ICIREM5QELQgMhEQzkAQtCBCERDOMBC0IFIREM4gELQgYhEQzhAQtCByERDOABC0IIIREM3wELQgkhEQzeAQtCCiERDN0BC0ILIREM3AELQgwhEQzbAQtCDSERDNoBC0IOIREM2QELQg8hEQzYAQtCCiERDNcBC0ILIREM1gELQgwhEQzVAQtCDSERDNQBC0IOIREM0wELQg8hEQzSAQtCACERAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQLQAAQVBqDjflAeQBAAECAwQFBgfmAeYB5gHmAeYB5gHmAQgJCgsMDeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gEODxAREhPmAQtCAiERDOQBC0IDIREM4wELQgQhEQziAQtCBSERDOEBC0IGIREM4AELQgchEQzfAQtCCCERDN4BC0IJIREM3QELQgohEQzcAQtCCyERDNsBC0IMIREM2gELQg0hEQzZAQtCDiERDNgBC0IPIREM1wELQgohEQzWAQtCCyERDNUBC0IMIREM1AELQg0hEQzTAQtCDiERDNIBC0IPIREM0QELIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN0gFBHyEQDMADCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEkIRAMpwMLQSAhEAy/AwsgACABIhAgAhC+gICAAEF/ag4FtgEAxQIB0QHSAQtBESEQDKQDCyAAQQE6AC8gECEBDLsDCyABIgEgAkcN0gFBJCEQDLsDCyABIg0gAkcNHkHGACEQDLoDCyAAIAEiASACELKAgIAAIhAN1AEgASEBDLUBCyABIhAgAkcNJkHQACEQDLgDCwJAIAEiASACRw0AQSghEAy4AwsgAEEANgIEIABBjICAgAA2AgggACABIAEQsYCAgAAiEA3TASABIQEM2AELAkAgASIQIAJHDQBBKSEQDLcDCyAQLQAAIgFBIEYNFCABQQlHDdMBIBBBAWohAQwVCwJAIAEiASACRg0AIAFBAWohAQwXC0EqIRAMtQMLAkAgASIQIAJHDQBBKyEQDLUDCwJAIBAtAAAiAUEJRg0AIAFBIEcN1QELIAAtACxBCEYN0wEgECEBDJEDCwJAIAEiASACRw0AQSwhEAy0AwsgAS0AAEEKRw3VASABQQFqIQEMyQILIAEiDiACRw3VAUEvIRAMsgMLA0ACQCABLQAAIhBBIEYNAAJAIBBBdmoOBADcAdwBANoBCyABIQEM4AELIAFBAWoiASACRw0AC0ExIRAMsQMLQTIhECABIhQgAkYNsAMgAiAUayAAKAIAIgFqIRUgFCABa0EDaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfC7gIAAai0AAEcNAQJAIAFBA0cNAEEGIQEMlgMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLEDCyAAQQA2AgAgFCEBDNkBC0EzIRAgASIUIAJGDa8DIAIgFGsgACgCACIBaiEVIBQgAWtBCGohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUH0u4CAAGotAABHDQECQCABQQhHDQBBBSEBDJUDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAywAwsgAEEANgIAIBQhAQzYAQtBNCEQIAEiFCACRg2uAyACIBRrIAAoAgAiAWohFSAUIAFrQQVqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw0BAkAgAUEFRw0AQQchAQyUAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMrwMLIABBADYCACAUIQEM1wELAkAgASIBIAJGDQADQAJAIAEtAABBgL6AgABqLQAAIhBBAUYNACAQQQJGDQogASEBDN0BCyABQQFqIgEgAkcNAAtBMCEQDK4DC0EwIRAMrQMLAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AIBBBdmoOBNkB2gHaAdkB2gELIAFBAWoiASACRw0AC0E4IRAMrQMLQTghEAysAwsDQAJAIAEtAAAiEEEgRg0AIBBBCUcNAwsgAUEBaiIBIAJHDQALQTwhEAyrAwsDQAJAIAEtAAAiEEEgRg0AAkACQCAQQXZqDgTaAQEB2gEACyAQQSxGDdsBCyABIQEMBAsgAUEBaiIBIAJHDQALQT8hEAyqAwsgASEBDNsBC0HAACEQIAEiFCACRg2oAyACIBRrIAAoAgAiAWohFiAUIAFrQQZqIRcCQANAIBQtAABBIHIgAUGAwICAAGotAABHDQEgAUEGRg2OAyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAypAwsgAEEANgIAIBQhAQtBNiEQDI4DCwJAIAEiDyACRw0AQcEAIRAMpwMLIABBjICAgAA2AgggACAPNgIEIA8hASAALQAsQX9qDgTNAdUB1wHZAYcDCyABQQFqIQEMzAELAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgciAQIBBBv39qQf8BcUEaSRtB/wFxIhBBCUYNACAQQSBGDQACQAJAAkACQCAQQZ1/ag4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIRAMkQMLIAFBAWohAUEyIRAMkAMLIAFBAWohAUEzIRAMjwMLIAEhAQzQAQsgAUEBaiIBIAJHDQALQTUhEAylAwtBNSEQDKQDCwJAIAEiASACRg0AA0ACQCABLQAAQYC8gIAAai0AAEEBRg0AIAEhAQzTAQsgAUEBaiIBIAJHDQALQT0hEAykAwtBPSEQDKMDCyAAIAEiASACELCAgIAAIhAN1gEgASEBDAELIBBBAWohAQtBPCEQDIcDCwJAIAEiASACRw0AQcIAIRAMoAMLAkADQAJAIAEtAABBd2oOGAAC/gL+AoQD/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4CAP4CCyABQQFqIgEgAkcNAAtBwgAhEAygAwsgAUEBaiEBIAAtAC1BAXFFDb0BIAEhAQtBLCEQDIUDCyABIgEgAkcN0wFBxAAhEAydAwsDQAJAIAEtAABBkMCAgABqLQAAQQFGDQAgASEBDLcCCyABQQFqIgEgAkcNAAtBxQAhEAycAwsgDS0AACIQQSBGDbMBIBBBOkcNgQMgACgCBCEBIABBADYCBCAAIAEgDRCvgICAACIBDdABIA1BAWohAQyzAgtBxwAhECABIg0gAkYNmgMgAiANayAAKAIAIgFqIRYgDSABa0EFaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGQwoCAAGotAABHDYADIAFBBUYN9AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmgMLQcgAIRAgASINIAJGDZkDIAIgDWsgACgCACIBaiEWIA0gAWtBCWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBlsKAgABqLQAARw3/AgJAIAFBCUcNAEECIQEM9QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJkDCwJAIAEiDSACRw0AQckAIRAMmQMLAkACQCANLQAAIgFBIHIgASABQb9/akH/AXFBGkkbQf8BcUGSf2oOBwCAA4ADgAOAA4ADAYADCyANQQFqIQFBPiEQDIADCyANQQFqIQFBPyEQDP8CC0HKACEQIAEiDSACRg2XAyACIA1rIAAoAgAiAWohFiANIAFrQQFqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaDCgIAAai0AAEcN/QIgAUEBRg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyXAwtBywAhECABIg0gAkYNlgMgAiANayAAKAIAIgFqIRYgDSABa0EOaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGiwoCAAGotAABHDfwCIAFBDkYN8AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlgMLQcwAIRAgASINIAJGDZUDIAIgDWsgACgCACIBaiEWIA0gAWtBD2ohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBwMKAgABqLQAARw37AgJAIAFBD0cNAEEDIQEM8QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJUDC0HNACEQIAEiDSACRg2UAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQdDCgIAAai0AAEcN+gICQCABQQVHDQBBBCEBDPACCyABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyUAwsCQCABIg0gAkcNAEHOACEQDJQDCwJAAkACQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZ1/ag4TAP0C/QL9Av0C/QL9Av0C/QL9Av0C/QL9AgH9Av0C/QICA/0CCyANQQFqIQFBwQAhEAz9AgsgDUEBaiEBQcIAIRAM/AILIA1BAWohAUHDACEQDPsCCyANQQFqIQFBxAAhEAz6AgsCQCABIgEgAkYNACAAQY2AgIAANgIIIAAgATYCBCABIQFBxQAhEAz6AgtBzwAhEAySAwsgECEBAkACQCAQLQAAQXZqDgQBqAKoAgCoAgsgEEEBaiEBC0EnIRAM+AILAkAgASIBIAJHDQBB0QAhEAyRAwsCQCABLQAAQSBGDQAgASEBDI0BCyABQQFqIQEgAC0ALUEBcUUNxwEgASEBDIwBCyABIhcgAkcNyAFB0gAhEAyPAwtB0wAhECABIhQgAkYNjgMgAiAUayAAKAIAIgFqIRYgFCABa0EBaiEXA0AgFC0AACABQdbCgIAAai0AAEcNzAEgAUEBRg3HASABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAyOAwsCQCABIgEgAkcNAEHVACEQDI4DCyABLQAAQQpHDcwBIAFBAWohAQzHAQsCQCABIgEgAkcNAEHWACEQDI0DCwJAAkAgAS0AAEF2ag4EAM0BzQEBzQELIAFBAWohAQzHAQsgAUEBaiEBQcoAIRAM8wILIAAgASIBIAIQroCAgAAiEA3LASABIQFBzQAhEAzyAgsgAC0AKUEiRg2FAwymAgsCQCABIgEgAkcNAEHbACEQDIoDC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgAS0AAEFQag4K1AHTAQABAgMEBQYI1QELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMzAELQQkhEEEBIRRBACEXQQAhFgzLAQsCQCABIgEgAkcNAEHdACEQDIkDCyABLQAAQS5HDcwBIAFBAWohAQymAgsgASIBIAJHDcwBQd8AIRAMhwMLAkAgASIBIAJGDQAgAEGOgICAADYCCCAAIAE2AgQgASEBQdAAIRAM7gILQeAAIRAMhgMLQeEAIRAgASIBIAJGDYUDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHiwoCAAGotAABHDc0BIBRBA0YNzAEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhQMLQeIAIRAgASIBIAJGDYQDIAIgAWsgACgCACIUaiEWIAEgFGtBAmohFwNAIAEtAAAgFEHmwoCAAGotAABHDcwBIBRBAkYNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhAMLQeMAIRAgASIBIAJGDYMDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHpwoCAAGotAABHDcsBIBRBA0YNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMgwMLAkAgASIBIAJHDQBB5QAhEAyDAwsgACABQQFqIgEgAhCogICAACIQDc0BIAEhAUHWACEQDOkCCwJAIAEiASACRg0AA0ACQCABLQAAIhBBIEYNAAJAAkACQCAQQbh/ag4LAAHPAc8BzwHPAc8BzwHPAc8BAs8BCyABQQFqIQFB0gAhEAztAgsgAUEBaiEBQdMAIRAM7AILIAFBAWohAUHUACEQDOsCCyABQQFqIgEgAkcNAAtB5AAhEAyCAwtB5AAhEAyBAwsDQAJAIAEtAABB8MKAgABqLQAAIhBBAUYNACAQQX5qDgPPAdAB0QHSAQsgAUEBaiIBIAJHDQALQeYAIRAMgAMLAkAgASIBIAJGDQAgAUEBaiEBDAMLQecAIRAM/wILA0ACQCABLQAAQfDEgIAAai0AACIQQQFGDQACQCAQQX5qDgTSAdMB1AEA1QELIAEhAUHXACEQDOcCCyABQQFqIgEgAkcNAAtB6AAhEAz+AgsCQCABIgEgAkcNAEHpACEQDP4CCwJAIAEtAAAiEEF2ag4augHVAdUBvAHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHKAdUB1QEA0wELIAFBAWohAQtBBiEQDOMCCwNAAkAgAS0AAEHwxoCAAGotAABBAUYNACABIQEMngILIAFBAWoiASACRw0AC0HqACEQDPsCCwJAIAEiASACRg0AIAFBAWohAQwDC0HrACEQDPoCCwJAIAEiASACRw0AQewAIRAM+gILIAFBAWohAQwBCwJAIAEiASACRw0AQe0AIRAM+QILIAFBAWohAQtBBCEQDN4CCwJAIAEiFCACRw0AQe4AIRAM9wILIBQhAQJAAkACQCAULQAAQfDIgIAAai0AAEF/ag4H1AHVAdYBAJwCAQLXAQsgFEEBaiEBDAoLIBRBAWohAQzNAQtBACEQIABBADYCHCAAQZuSgIAANgIQIABBBzYCDCAAIBRBAWo2AhQM9gILAkADQAJAIAEtAABB8MiAgABqLQAAIhBBBEYNAAJAAkAgEEF/ag4H0gHTAdQB2QEABAHZAQsgASEBQdoAIRAM4AILIAFBAWohAUHcACEQDN8CCyABQQFqIgEgAkcNAAtB7wAhEAz2AgsgAUEBaiEBDMsBCwJAIAEiFCACRw0AQfAAIRAM9QILIBQtAABBL0cN1AEgFEEBaiEBDAYLAkAgASIUIAJHDQBB8QAhEAz0AgsCQCAULQAAIgFBL0cNACAUQQFqIQFB3QAhEAzbAgsgAUF2aiIEQRZLDdMBQQEgBHRBiYCAAnFFDdMBDMoCCwJAIAEiASACRg0AIAFBAWohAUHeACEQDNoCC0HyACEQDPICCwJAIAEiFCACRw0AQfQAIRAM8gILIBQhAQJAIBQtAABB8MyAgABqLQAAQX9qDgPJApQCANQBC0HhACEQDNgCCwJAIAEiFCACRg0AA0ACQCAULQAAQfDKgIAAai0AACIBQQNGDQACQCABQX9qDgLLAgDVAQsgFCEBQd8AIRAM2gILIBRBAWoiFCACRw0AC0HzACEQDPECC0HzACEQDPACCwJAIAEiASACRg0AIABBj4CAgAA2AgggACABNgIEIAEhAUHgACEQDNcCC0H1ACEQDO8CCwJAIAEiASACRw0AQfYAIRAM7wILIABBj4CAgAA2AgggACABNgIEIAEhAQtBAyEQDNQCCwNAIAEtAABBIEcNwwIgAUEBaiIBIAJHDQALQfcAIRAM7AILAkAgASIBIAJHDQBB+AAhEAzsAgsgAS0AAEEgRw3OASABQQFqIQEM7wELIAAgASIBIAIQrICAgAAiEA3OASABIQEMjgILAkAgASIEIAJHDQBB+gAhEAzqAgsgBC0AAEHMAEcN0QEgBEEBaiEBQRMhEAzPAQsCQCABIgQgAkcNAEH7ACEQDOkCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRADQCAELQAAIAFB8M6AgABqLQAARw3QASABQQVGDc4BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQfsAIRAM6AILAkAgASIEIAJHDQBB/AAhEAzoAgsCQAJAIAQtAABBvX9qDgwA0QHRAdEB0QHRAdEB0QHRAdEB0QEB0QELIARBAWohAUHmACEQDM8CCyAEQQFqIQFB5wAhEAzOAgsCQCABIgQgAkcNAEH9ACEQDOcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDc8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH9ACEQDOcCCyAAQQA2AgAgEEEBaiEBQRAhEAzMAQsCQCABIgQgAkcNAEH+ACEQDOYCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUH2zoCAAGotAABHDc4BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH+ACEQDOYCCyAAQQA2AgAgEEEBaiEBQRYhEAzLAQsCQCABIgQgAkcNAEH/ACEQDOUCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUH8zoCAAGotAABHDc0BIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH/ACEQDOUCCyAAQQA2AgAgEEEBaiEBQQUhEAzKAQsCQCABIgQgAkcNAEGAASEQDOQCCyAELQAAQdkARw3LASAEQQFqIQFBCCEQDMkBCwJAIAEiBCACRw0AQYEBIRAM4wILAkACQCAELQAAQbJ/ag4DAMwBAcwBCyAEQQFqIQFB6wAhEAzKAgsgBEEBaiEBQewAIRAMyQILAkAgASIEIAJHDQBBggEhEAziAgsCQAJAIAQtAABBuH9qDggAywHLAcsBywHLAcsBAcsBCyAEQQFqIQFB6gAhEAzJAgsgBEEBaiEBQe0AIRAMyAILAkAgASIEIAJHDQBBgwEhEAzhAgsgAiAEayAAKAIAIgFqIRAgBCABa0ECaiEUAkADQCAELQAAIAFBgM+AgABqLQAARw3JASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBA2AgBBgwEhEAzhAgtBACEQIABBADYCACAUQQFqIQEMxgELAkAgASIEIAJHDQBBhAEhEAzgAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBg8+AgABqLQAARw3IASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhAEhEAzgAgsgAEEANgIAIBBBAWohAUEjIRAMxQELAkAgASIEIAJHDQBBhQEhEAzfAgsCQAJAIAQtAABBtH9qDggAyAHIAcgByAHIAcgBAcgBCyAEQQFqIQFB7wAhEAzGAgsgBEEBaiEBQfAAIRAMxQILAkAgASIEIAJHDQBBhgEhEAzeAgsgBC0AAEHFAEcNxQEgBEEBaiEBDIMCCwJAIAEiBCACRw0AQYcBIRAM3QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQYjPgIAAai0AAEcNxQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYcBIRAM3QILIABBADYCACAQQQFqIQFBLSEQDMIBCwJAIAEiBCACRw0AQYgBIRAM3AILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNxAEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYgBIRAM3AILIABBADYCACAQQQFqIQFBKSEQDMEBCwJAIAEiASACRw0AQYkBIRAM2wILQQEhECABLQAAQd8ARw3AASABQQFqIQEMgQILAkAgASIEIAJHDQBBigEhEAzaAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQA0AgBC0AACABQYzPgIAAai0AAEcNwQEgAUEBRg2vAiABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGKASEQDNkCCwJAIAEiBCACRw0AQYsBIRAM2QILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQY7PgIAAai0AAEcNwQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYsBIRAM2QILIABBADYCACAQQQFqIQFBAiEQDL4BCwJAIAEiBCACRw0AQYwBIRAM2AILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNwAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYwBIRAM2AILIABBADYCACAQQQFqIQFBHyEQDL0BCwJAIAEiBCACRw0AQY0BIRAM1wILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNvwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY0BIRAM1wILIABBADYCACAQQQFqIQFBCSEQDLwBCwJAIAEiBCACRw0AQY4BIRAM1gILAkACQCAELQAAQbd/ag4HAL8BvwG/Ab8BvwEBvwELIARBAWohAUH4ACEQDL0CCyAEQQFqIQFB+QAhEAy8AgsCQCABIgQgAkcNAEGPASEQDNUCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGRz4CAAGotAABHDb0BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGPASEQDNUCCyAAQQA2AgAgEEEBaiEBQRghEAy6AQsCQCABIgQgAkcNAEGQASEQDNQCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUGXz4CAAGotAABHDbwBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGQASEQDNQCCyAAQQA2AgAgEEEBaiEBQRchEAy5AQsCQCABIgQgAkcNAEGRASEQDNMCCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUGaz4CAAGotAABHDbsBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGRASEQDNMCCyAAQQA2AgAgEEEBaiEBQRUhEAy4AQsCQCABIgQgAkcNAEGSASEQDNICCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGhz4CAAGotAABHDboBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGSASEQDNICCyAAQQA2AgAgEEEBaiEBQR4hEAy3AQsCQCABIgQgAkcNAEGTASEQDNECCyAELQAAQcwARw24ASAEQQFqIQFBCiEQDLYBCwJAIAQgAkcNAEGUASEQDNACCwJAAkAgBC0AAEG/f2oODwC5AbkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AQG5AQsgBEEBaiEBQf4AIRAMtwILIARBAWohAUH/ACEQDLYCCwJAIAQgAkcNAEGVASEQDM8CCwJAAkAgBC0AAEG/f2oOAwC4AQG4AQsgBEEBaiEBQf0AIRAMtgILIARBAWohBEGAASEQDLUCCwJAIAQgAkcNAEGWASEQDM4CCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUGnz4CAAGotAABHDbYBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGWASEQDM4CCyAAQQA2AgAgEEEBaiEBQQshEAyzAQsCQCAEIAJHDQBBlwEhEAzNAgsCQAJAAkACQCAELQAAQVNqDiMAuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AQG4AbgBuAG4AbgBArgBuAG4AQO4AQsgBEEBaiEBQfsAIRAMtgILIARBAWohAUH8ACEQDLUCCyAEQQFqIQRBgQEhEAy0AgsgBEEBaiEEQYIBIRAMswILAkAgBCACRw0AQZgBIRAMzAILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQanPgIAAai0AAEcNtAEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZgBIRAMzAILIABBADYCACAQQQFqIQFBGSEQDLEBCwJAIAQgAkcNAEGZASEQDMsCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGuz4CAAGotAABHDbMBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGZASEQDMsCCyAAQQA2AgAgEEEBaiEBQQYhEAywAQsCQCAEIAJHDQBBmgEhEAzKAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBtM+AgABqLQAARw2yASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmgEhEAzKAgsgAEEANgIAIBBBAWohAUEcIRAMrwELAkAgBCACRw0AQZsBIRAMyQILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbbPgIAAai0AAEcNsQEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZsBIRAMyQILIABBADYCACAQQQFqIQFBJyEQDK4BCwJAIAQgAkcNAEGcASEQDMgCCwJAAkAgBC0AAEGsf2oOAgABsQELIARBAWohBEGGASEQDK8CCyAEQQFqIQRBhwEhEAyuAgsCQCAEIAJHDQBBnQEhEAzHAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBuM+AgABqLQAARw2vASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBnQEhEAzHAgsgAEEANgIAIBBBAWohAUEmIRAMrAELAkAgBCACRw0AQZ4BIRAMxgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbrPgIAAai0AAEcNrgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ4BIRAMxgILIABBADYCACAQQQFqIQFBAyEQDKsBCwJAIAQgAkcNAEGfASEQDMUCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDa0BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGfASEQDMUCCyAAQQA2AgAgEEEBaiEBQQwhEAyqAQsCQCAEIAJHDQBBoAEhEAzEAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBvM+AgABqLQAARw2sASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBoAEhEAzEAgsgAEEANgIAIBBBAWohAUENIRAMqQELAkAgBCACRw0AQaEBIRAMwwILAkACQCAELQAAQbp/ag4LAKwBrAGsAawBrAGsAawBrAGsAQGsAQsgBEEBaiEEQYsBIRAMqgILIARBAWohBEGMASEQDKkCCwJAIAQgAkcNAEGiASEQDMICCyAELQAAQdAARw2pASAEQQFqIQQM6QELAkAgBCACRw0AQaMBIRAMwQILAkACQCAELQAAQbd/ag4HAaoBqgGqAaoBqgEAqgELIARBAWohBEGOASEQDKgCCyAEQQFqIQFBIiEQDKYBCwJAIAQgAkcNAEGkASEQDMACCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHAz4CAAGotAABHDagBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGkASEQDMACCyAAQQA2AgAgEEEBaiEBQR0hEAylAQsCQCAEIAJHDQBBpQEhEAy/AgsCQAJAIAQtAABBrn9qDgMAqAEBqAELIARBAWohBEGQASEQDKYCCyAEQQFqIQFBBCEQDKQBCwJAIAQgAkcNAEGmASEQDL4CCwJAAkACQAJAAkAgBC0AAEG/f2oOFQCqAaoBqgGqAaoBqgGqAaoBqgGqAQGqAaoBAqoBqgEDqgGqAQSqAQsgBEEBaiEEQYgBIRAMqAILIARBAWohBEGJASEQDKcCCyAEQQFqIQRBigEhEAymAgsgBEEBaiEEQY8BIRAMpQILIARBAWohBEGRASEQDKQCCwJAIAQgAkcNAEGnASEQDL0CCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDaUBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGnASEQDL0CCyAAQQA2AgAgEEEBaiEBQREhEAyiAQsCQCAEIAJHDQBBqAEhEAy8AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBws+AgABqLQAARw2kASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqAEhEAy8AgsgAEEANgIAIBBBAWohAUEsIRAMoQELAkAgBCACRw0AQakBIRAMuwILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQcXPgIAAai0AAEcNowEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQakBIRAMuwILIABBADYCACAQQQFqIQFBKyEQDKABCwJAIAQgAkcNAEGqASEQDLoCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHKz4CAAGotAABHDaIBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGqASEQDLoCCyAAQQA2AgAgEEEBaiEBQRQhEAyfAQsCQCAEIAJHDQBBqwEhEAy5AgsCQAJAAkACQCAELQAAQb5/ag4PAAECpAGkAaQBpAGkAaQBpAGkAaQBpAGkAQOkAQsgBEEBaiEEQZMBIRAMogILIARBAWohBEGUASEQDKECCyAEQQFqIQRBlQEhEAygAgsgBEEBaiEEQZYBIRAMnwILAkAgBCACRw0AQawBIRAMuAILIAQtAABBxQBHDZ8BIARBAWohBAzgAQsCQCAEIAJHDQBBrQEhEAy3AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBzc+AgABqLQAARw2fASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrQEhEAy3AgsgAEEANgIAIBBBAWohAUEOIRAMnAELAkAgBCACRw0AQa4BIRAMtgILIAQtAABB0ABHDZ0BIARBAWohAUElIRAMmwELAkAgBCACRw0AQa8BIRAMtQILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNnQEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQa8BIRAMtQILIABBADYCACAQQQFqIQFBKiEQDJoBCwJAIAQgAkcNAEGwASEQDLQCCwJAAkAgBC0AAEGrf2oOCwCdAZ0BnQGdAZ0BnQGdAZ0BnQEBnQELIARBAWohBEGaASEQDJsCCyAEQQFqIQRBmwEhEAyaAgsCQCAEIAJHDQBBsQEhEAyzAgsCQAJAIAQtAABBv39qDhQAnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBAZwBCyAEQQFqIQRBmQEhEAyaAgsgBEEBaiEEQZwBIRAMmQILAkAgBCACRw0AQbIBIRAMsgILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQdnPgIAAai0AAEcNmgEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbIBIRAMsgILIABBADYCACAQQQFqIQFBISEQDJcBCwJAIAQgAkcNAEGzASEQDLECCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUHdz4CAAGotAABHDZkBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGzASEQDLECCyAAQQA2AgAgEEEBaiEBQRohEAyWAQsCQCAEIAJHDQBBtAEhEAywAgsCQAJAAkAgBC0AAEG7f2oOEQCaAZoBmgGaAZoBmgGaAZoBmgEBmgGaAZoBmgGaAQKaAQsgBEEBaiEEQZ0BIRAMmAILIARBAWohBEGeASEQDJcCCyAEQQFqIQRBnwEhEAyWAgsCQCAEIAJHDQBBtQEhEAyvAgsgAiAEayAAKAIAIgFqIRQgBCABa0EFaiEQAkADQCAELQAAIAFB5M+AgABqLQAARw2XASABQQVGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtQEhEAyvAgsgAEEANgIAIBBBAWohAUEoIRAMlAELAkAgBCACRw0AQbYBIRAMrgILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQerPgIAAai0AAEcNlgEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbYBIRAMrgILIABBADYCACAQQQFqIQFBByEQDJMBCwJAIAQgAkcNAEG3ASEQDK0CCwJAAkAgBC0AAEG7f2oODgCWAZYBlgGWAZYBlgGWAZYBlgGWAZYBlgEBlgELIARBAWohBEGhASEQDJQCCyAEQQFqIQRBogEhEAyTAgsCQCAEIAJHDQBBuAEhEAysAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB7c+AgABqLQAARw2UASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuAEhEAysAgsgAEEANgIAIBBBAWohAUESIRAMkQELAkAgBCACRw0AQbkBIRAMqwILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNkwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbkBIRAMqwILIABBADYCACAQQQFqIQFBICEQDJABCwJAIAQgAkcNAEG6ASEQDKoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHyz4CAAGotAABHDZIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG6ASEQDKoCCyAAQQA2AgAgEEEBaiEBQQ8hEAyPAQsCQCAEIAJHDQBBuwEhEAypAgsCQAJAIAQtAABBt39qDgcAkgGSAZIBkgGSAQGSAQsgBEEBaiEEQaUBIRAMkAILIARBAWohBEGmASEQDI8CCwJAIAQgAkcNAEG8ASEQDKgCCyACIARrIAAoAgAiAWohFCAEIAFrQQdqIRACQANAIAQtAAAgAUH0z4CAAGotAABHDZABIAFBB0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG8ASEQDKgCCyAAQQA2AgAgEEEBaiEBQRshEAyNAQsCQCAEIAJHDQBBvQEhEAynAgsCQAJAAkAgBC0AAEG+f2oOEgCRAZEBkQGRAZEBkQGRAZEBkQEBkQGRAZEBkQGRAZEBApEBCyAEQQFqIQRBpAEhEAyPAgsgBEEBaiEEQacBIRAMjgILIARBAWohBEGoASEQDI0CCwJAIAQgAkcNAEG+ASEQDKYCCyAELQAAQc4ARw2NASAEQQFqIQQMzwELAkAgBCACRw0AQb8BIRAMpQILAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgBC0AAEG/f2oOFQABAgOcAQQFBpwBnAGcAQcICQoLnAEMDQ4PnAELIARBAWohAUHoACEQDJoCCyAEQQFqIQFB6QAhEAyZAgsgBEEBaiEBQe4AIRAMmAILIARBAWohAUHyACEQDJcCCyAEQQFqIQFB8wAhEAyWAgsgBEEBaiEBQfYAIRAMlQILIARBAWohAUH3ACEQDJQCCyAEQQFqIQFB+gAhEAyTAgsgBEEBaiEEQYMBIRAMkgILIARBAWohBEGEASEQDJECCyAEQQFqIQRBhQEhEAyQAgsgBEEBaiEEQZIBIRAMjwILIARBAWohBEGYASEQDI4CCyAEQQFqIQRBoAEhEAyNAgsgBEEBaiEEQaMBIRAMjAILIARBAWohBEGqASEQDIsCCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEGrASEQDIsCC0HAASEQDKMCCyAAIAUgAhCqgICAACIBDYsBIAUhAQxcCwJAIAYgAkYNACAGQQFqIQUMjQELQcIBIRAMoQILA0ACQCAQLQAAQXZqDgSMAQAAjwEACyAQQQFqIhAgAkcNAAtBwwEhEAygAgsCQCAHIAJGDQAgAEGRgICAADYCCCAAIAc2AgQgByEBQQEhEAyHAgtBxAEhEAyfAgsCQCAHIAJHDQBBxQEhEAyfAgsCQAJAIActAABBdmoOBAHOAc4BAM4BCyAHQQFqIQYMjQELIAdBAWohBQyJAQsCQCAHIAJHDQBBxgEhEAyeAgsCQAJAIActAABBdmoOFwGPAY8BAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAQCPAQsgB0EBaiEHC0GwASEQDIQCCwJAIAggAkcNAEHIASEQDJ0CCyAILQAAQSBHDY0BIABBADsBMiAIQQFqIQFBswEhEAyDAgsgASEXAkADQCAXIgcgAkYNASAHLQAAQVBqQf8BcSIQQQpPDcwBAkAgAC8BMiIUQZkzSw0AIAAgFEEKbCIUOwEyIBBB//8DcyAUQf7/A3FJDQAgB0EBaiEXIAAgFCAQaiIQOwEyIBBB//8DcUHoB0kNAQsLQQAhECAAQQA2AhwgAEHBiYCAADYCECAAQQ02AgwgACAHQQFqNgIUDJwCC0HHASEQDJsCCyAAIAggAhCugICAACIQRQ3KASAQQRVHDYwBIABByAE2AhwgACAINgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAyaAgsCQCAJIAJHDQBBzAEhEAyaAgtBACEUQQEhF0EBIRZBACEQAkACQAJAAkACQAJAAkACQAJAIAktAABBUGoOCpYBlQEAAQIDBAUGCJcBC0ECIRAMBgtBAyEQDAULQQQhEAwEC0EFIRAMAwtBBiEQDAILQQchEAwBC0EIIRALQQAhF0EAIRZBACEUDI4BC0EJIRBBASEUQQAhF0EAIRYMjQELAkAgCiACRw0AQc4BIRAMmQILIAotAABBLkcNjgEgCkEBaiEJDMoBCyALIAJHDY4BQdABIRAMlwILAkAgCyACRg0AIABBjoCAgAA2AgggACALNgIEQbcBIRAM/gELQdEBIRAMlgILAkAgBCACRw0AQdIBIRAMlgILIAIgBGsgACgCACIQaiEUIAQgEGtBBGohCwNAIAQtAAAgEEH8z4CAAGotAABHDY4BIBBBBEYN6QEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB0gEhEAyVAgsgACAMIAIQrICAgAAiAQ2NASAMIQEMuAELAkAgBCACRw0AQdQBIRAMlAILIAIgBGsgACgCACIQaiEUIAQgEGtBAWohDANAIAQtAAAgEEGB0ICAAGotAABHDY8BIBBBAUYNjgEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB1AEhEAyTAgsCQCAEIAJHDQBB1gEhEAyTAgsgAiAEayAAKAIAIhBqIRQgBCAQa0ECaiELA0AgBC0AACAQQYPQgIAAai0AAEcNjgEgEEECRg2QASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHWASEQDJICCwJAIAQgAkcNAEHXASEQDJICCwJAAkAgBC0AAEG7f2oOEACPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAY8BCyAEQQFqIQRBuwEhEAz5AQsgBEEBaiEEQbwBIRAM+AELAkAgBCACRw0AQdgBIRAMkQILIAQtAABByABHDYwBIARBAWohBAzEAQsCQCAEIAJGDQAgAEGQgICAADYCCCAAIAQ2AgRBvgEhEAz3AQtB2QEhEAyPAgsCQCAEIAJHDQBB2gEhEAyPAgsgBC0AAEHIAEYNwwEgAEEBOgAoDLkBCyAAQQI6AC8gACAEIAIQpoCAgAAiEA2NAUHCASEQDPQBCyAALQAoQX9qDgK3AbkBuAELA0ACQCAELQAAQXZqDgQAjgGOAQCOAQsgBEEBaiIEIAJHDQALQd0BIRAMiwILIABBADoALyAALQAtQQRxRQ2EAgsgAEEAOgAvIABBAToANCABIQEMjAELIBBBFUYN2gEgAEEANgIcIAAgATYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMiAILAkAgACAQIAIQtICAgAAiBA0AIBAhAQyBAgsCQCAEQRVHDQAgAEEDNgIcIAAgEDYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMiAILIABBADYCHCAAIBA2AhQgAEGnjoCAADYCECAAQRI2AgxBACEQDIcCCyAQQRVGDdYBIABBADYCHCAAIAE2AhQgAEHajYCAADYCECAAQRQ2AgxBACEQDIYCCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNjQEgAEEHNgIcIAAgEDYCFCAAIBQ2AgxBACEQDIUCCyAAIAAvATBBgAFyOwEwIAEhAQtBKiEQDOoBCyAQQRVGDdEBIABBADYCHCAAIAE2AhQgAEGDjICAADYCECAAQRM2AgxBACEQDIICCyAQQRVGDc8BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDIECCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyNAQsgAEEMNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDIACCyAQQRVGDcwBIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDP8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyMAQsgAEENNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDP4BCyAQQRVGDckBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDP0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyLAQsgAEEONgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPwBCyAAQQA2AhwgACABNgIUIABBwJWAgAA2AhAgAEECNgIMQQAhEAz7AQsgEEEVRg3FASAAQQA2AhwgACABNgIUIABBxoyAgAA2AhAgAEEjNgIMQQAhEAz6AQsgAEEQNgIcIAAgATYCFCAAIBA2AgxBACEQDPkBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQzxAQsgAEERNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPgBCyAQQRVGDcEBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPcBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyIAQsgAEETNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPYBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQztAQsgAEEUNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPUBCyAQQRVGDb0BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDPQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyGAQsgAEEWNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPMBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQt4CAgAAiBA0AIAFBAWohAQzpAQsgAEEXNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPIBCyAAQQA2AhwgACABNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzxAQtCASERCyAQQQFqIQECQCAAKQMgIhJC//////////8PVg0AIAAgEkIEhiARhDcDICABIQEMhAELIABBADYCHCAAIAE2AhQgAEGtiYCAADYCECAAQQw2AgxBACEQDO8BCyAAQQA2AhwgACAQNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzuAQsgACgCBCEXIABBADYCBCAQIBGnaiIWIQEgACAXIBAgFiAUGyIQELWAgIAAIhRFDXMgAEEFNgIcIAAgEDYCFCAAIBQ2AgxBACEQDO0BCyAAQQA2AhwgACAQNgIUIABBqpyAgAA2AhAgAEEPNgIMQQAhEAzsAQsgACAQIAIQtICAgAAiAQ0BIBAhAQtBDiEQDNEBCwJAIAFBFUcNACAAQQI2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAzqAQsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAM6QELIAFBAWohEAJAIAAvATAiAUGAAXFFDQACQCAAIBAgAhC7gICAACIBDQAgECEBDHALIAFBFUcNugEgAEEFNgIcIAAgEDYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAM6QELAkAgAUGgBHFBoARHDQAgAC0ALUECcQ0AIABBADYCHCAAIBA2AhQgAEGWk4CAADYCECAAQQQ2AgxBACEQDOkBCyAAIBAgAhC9gICAABogECEBAkACQAJAAkACQCAAIBAgAhCzgICAAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIABBAToALgsgACAALwEwQcAAcjsBMCAQIQELQSYhEAzRAQsgAEEjNgIcIAAgEDYCFCAAQaWWgIAANgIQIABBFTYCDEEAIRAM6QELIABBADYCHCAAIBA2AhQgAEHVi4CAADYCECAAQRE2AgxBACEQDOgBCyAALQAtQQFxRQ0BQcMBIRAMzgELAkAgDSACRg0AA0ACQCANLQAAQSBGDQAgDSEBDMQBCyANQQFqIg0gAkcNAAtBJSEQDOcBC0ElIRAM5gELIAAoAgQhBCAAQQA2AgQgACAEIA0Qr4CAgAAiBEUNrQEgAEEmNgIcIAAgBDYCDCAAIA1BAWo2AhRBACEQDOUBCyAQQRVGDasBIABBADYCHCAAIAE2AhQgAEH9jYCAADYCECAAQR02AgxBACEQDOQBCyAAQSc2AhwgACABNgIUIAAgEDYCDEEAIRAM4wELIBAhAUEBIRQCQAJAAkACQAJAAkACQCAALQAsQX5qDgcGBQUDAQIABQsgACAALwEwQQhyOwEwDAMLQQIhFAwBC0EEIRQLIABBAToALCAAIAAvATAgFHI7ATALIBAhAQtBKyEQDMoBCyAAQQA2AhwgACAQNgIUIABBq5KAgAA2AhAgAEELNgIMQQAhEAziAQsgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDEEAIRAM4QELIABBADoALCAQIQEMvQELIBAhAUEBIRQCQAJAAkACQAJAIAAtACxBe2oOBAMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0EpIRAMxQELIABBADYCHCAAIAE2AhQgAEHwlICAADYCECAAQQM2AgxBACEQDN0BCwJAIA4tAABBDUcNACAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA5BAWohAQx1CyAAQSw2AhwgACABNgIMIAAgDkEBajYCFEEAIRAM3QELIAAtAC1BAXFFDQFBxAEhEAzDAQsCQCAOIAJHDQBBLSEQDNwBCwJAAkADQAJAIA4tAABBdmoOBAIAAAMACyAOQQFqIg4gAkcNAAtBLSEQDN0BCyAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA4hAQx0CyAAQSw2AhwgACAONgIUIAAgATYCDEEAIRAM3AELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHMLIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzbAQsgACgCBCEEIABBADYCBCAAIAQgDhCxgICAACIEDaABIA4hAQzOAQsgEEEsRw0BIAFBAWohEEEBIQECQAJAAkACQAJAIAAtACxBe2oOBAMBAgQACyAQIQEMBAtBAiEBDAELQQQhAQsgAEEBOgAsIAAgAC8BMCABcjsBMCAQIQEMAQsgACAALwEwQQhyOwEwIBAhAQtBOSEQDL8BCyAAQQA6ACwgASEBC0E0IRAMvQELIAAgAC8BMEEgcjsBMCABIQEMAgsgACgCBCEEIABBADYCBAJAIAAgBCABELGAgIAAIgQNACABIQEMxwELIABBNzYCHCAAIAE2AhQgACAENgIMQQAhEAzUAQsgAEEIOgAsIAEhAQtBMCEQDLkBCwJAIAAtAChBAUYNACABIQEMBAsgAC0ALUEIcUUNkwEgASEBDAMLIAAtADBBIHENlAFBxQEhEAy3AQsCQCAPIAJGDQACQANAAkAgDy0AAEFQaiIBQf8BcUEKSQ0AIA8hAUE1IRAMugELIAApAyAiEUKZs+bMmbPmzBlWDQEgACARQgp+IhE3AyAgESABrUL/AYMiEkJ/hVYNASAAIBEgEnw3AyAgD0EBaiIPIAJHDQALQTkhEAzRAQsgACgCBCECIABBADYCBCAAIAIgD0EBaiIEELGAgIAAIgINlQEgBCEBDMMBC0E5IRAMzwELAkAgAC8BMCIBQQhxRQ0AIAAtAChBAUcNACAALQAtQQhxRQ2QAQsgACABQff7A3FBgARyOwEwIA8hAQtBNyEQDLQBCyAAIAAvATBBEHI7ATAMqwELIBBBFUYNiwEgAEEANgIcIAAgATYCFCAAQfCOgIAANgIQIABBHDYCDEEAIRAMywELIABBwwA2AhwgACABNgIMIAAgDUEBajYCFEEAIRAMygELAkAgAS0AAEE6Rw0AIAAoAgQhECAAQQA2AgQCQCAAIBAgARCvgICAACIQDQAgAUEBaiEBDGMLIABBwwA2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMygELIABBADYCHCAAIAE2AhQgAEGxkYCAADYCECAAQQo2AgxBACEQDMkBCyAAQQA2AhwgACABNgIUIABBoJmAgAA2AhAgAEEeNgIMQQAhEAzIAQsgAEEANgIACyAAQYASOwEqIAAgF0EBaiIBIAIQqICAgAAiEA0BIAEhAQtBxwAhEAysAQsgEEEVRw2DASAAQdEANgIcIAAgATYCFCAAQeOXgIAANgIQIABBFTYCDEEAIRAMxAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDF4LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMwwELIABBADYCHCAAIBQ2AhQgAEHBqICAADYCECAAQQc2AgwgAEEANgIAQQAhEAzCAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAzBAQtBACEQIABBADYCHCAAIAE2AhQgAEGAkYCAADYCECAAQQk2AgwMwAELIBBBFUYNfSAAQQA2AhwgACABNgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAy/AQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgAUEBaiEBAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBAJAIAAgECABEK2AgIAAIhANACABIQEMXAsgAEHYADYCHCAAIAE2AhQgACAQNgIMQQAhEAy+AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMrQELIABB2QA2AhwgACABNgIUIAAgBDYCDEEAIRAMvQELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKsBCyAAQdoANgIcIAAgATYCFCAAIAQ2AgxBACEQDLwBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQypAQsgAEHcADYCHCAAIAE2AhQgACAENgIMQQAhEAy7AQsCQCABLQAAQVBqIhBB/wFxQQpPDQAgACAQOgAqIAFBAWohAUHPACEQDKIBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQynAQsgAEHeADYCHCAAIAE2AhQgACAENgIMQQAhEAy6AQsgAEEANgIAIBdBAWohAQJAIAAtAClBI08NACABIQEMWQsgAEEANgIcIAAgATYCFCAAQdOJgIAANgIQIABBCDYCDEEAIRAMuQELIABBADYCAAtBACEQIABBADYCHCAAIAE2AhQgAEGQs4CAADYCECAAQQg2AgwMtwELIABBADYCACAXQQFqIQECQCAALQApQSFHDQAgASEBDFYLIABBADYCHCAAIAE2AhQgAEGbioCAADYCECAAQQg2AgxBACEQDLYBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKSIQQV1qQQtPDQAgASEBDFULAkAgEEEGSw0AQQEgEHRBygBxRQ0AIAEhAQxVC0EAIRAgAEEANgIcIAAgATYCFCAAQfeJgIAANgIQIABBCDYCDAy1AQsgEEEVRg1xIABBADYCHCAAIAE2AhQgAEG5jYCAADYCECAAQRo2AgxBACEQDLQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxUCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLMBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAAgEDoAKSAAKAIEIRAgAEEANgIEIAAgECABEKuAgIAAIhANVCABIQEMPgsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQfGbgIAANgIQIABBBjYCDAyXAQsgAUEVRg1QIABBADYCHCAAIAU2AhQgAEHwjICAADYCECAAQRs2AgxBACEQDJYBCyAAKAIEIQUgAEEANgIEIAAgBSAQEKmAgIAAIgUNASAQQQFqIQULQa0BIRAMewsgAEHBATYCHCAAIAU2AgwgACAQQQFqNgIUQQAhEAyTAQsgACgCBCEGIABBADYCBCAAIAYgEBCpgICAACIGDQEgEEEBaiEGC0GuASEQDHgLIABBwgE2AhwgACAGNgIMIAAgEEEBajYCFEEAIRAMkAELIABBADYCHCAAIAc2AhQgAEGXi4CAADYCECAAQQ02AgxBACEQDI8BCyAAQQA2AhwgACAINgIUIABB45CAgAA2AhAgAEEJNgIMQQAhEAyOAQsgAEEANgIcIAAgCDYCFCAAQZSNgIAANgIQIABBITYCDEEAIRAMjQELQQEhFkEAIRdBACEUQQEhEAsgACAQOgArIAlBAWohCAJAAkAgAC0ALUEQcQ0AAkACQAJAIAAtACoOAwEAAgQLIBZFDQMMAgsgFA0BDAILIBdFDQELIAAoAgQhECAAQQA2AgQgACAQIAgQrYCAgAAiEEUNPSAAQckBNgIcIAAgCDYCFCAAIBA2AgxBACEQDIwBCyAAKAIEIQQgAEEANgIEIAAgBCAIEK2AgIAAIgRFDXYgAEHKATYCHCAAIAg2AhQgACAENgIMQQAhEAyLAQsgACgCBCEEIABBADYCBCAAIAQgCRCtgICAACIERQ10IABBywE2AhwgACAJNgIUIAAgBDYCDEEAIRAMigELIAAoAgQhBCAAQQA2AgQgACAEIAoQrYCAgAAiBEUNciAAQc0BNgIcIAAgCjYCFCAAIAQ2AgxBACEQDIkBCwJAIAstAABBUGoiEEH/AXFBCk8NACAAIBA6ACogC0EBaiEKQbYBIRAMcAsgACgCBCEEIABBADYCBCAAIAQgCxCtgICAACIERQ1wIABBzwE2AhwgACALNgIUIAAgBDYCDEEAIRAMiAELIABBADYCHCAAIAQ2AhQgAEGQs4CAADYCECAAQQg2AgwgAEEANgIAQQAhEAyHAQsgAUEVRg0/IABBADYCHCAAIAw2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDIYBCyAAQYEEOwEoIAAoAgQhECAAQgA3AwAgACAQIAxBAWoiDBCrgICAACIQRQ04IABB0wE2AhwgACAMNgIUIAAgEDYCDEEAIRAMhQELIABBADYCAAtBACEQIABBADYCHCAAIAQ2AhQgAEHYm4CAADYCECAAQQg2AgwMgwELIAAoAgQhECAAQgA3AwAgACAQIAtBAWoiCxCrgICAACIQDQFBxgEhEAxpCyAAQQI6ACgMVQsgAEHVATYCHCAAIAs2AhQgACAQNgIMQQAhEAyAAQsgEEEVRg03IABBADYCHCAAIAQ2AhQgAEGkjICAADYCECAAQRA2AgxBACEQDH8LIAAtADRBAUcNNCAAIAQgAhC8gICAACIQRQ00IBBBFUcNNSAAQdwBNgIcIAAgBDYCFCAAQdWWgIAANgIQIABBFTYCDEEAIRAMfgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQMfQtBACEQDGMLQQIhEAxiC0ENIRAMYQtBDyEQDGALQSUhEAxfC0ETIRAMXgtBFSEQDF0LQRYhEAxcC0EXIRAMWwtBGCEQDFoLQRkhEAxZC0EaIRAMWAtBGyEQDFcLQRwhEAxWC0EdIRAMVQtBHyEQDFQLQSEhEAxTC0EjIRAMUgtBxgAhEAxRC0EuIRAMUAtBLyEQDE8LQTshEAxOC0E9IRAMTQtByAAhEAxMC0HJACEQDEsLQcsAIRAMSgtBzAAhEAxJC0HOACEQDEgLQdEAIRAMRwtB1QAhEAxGC0HYACEQDEULQdkAIRAMRAtB2wAhEAxDC0HkACEQDEILQeUAIRAMQQtB8QAhEAxAC0H0ACEQDD8LQY0BIRAMPgtBlwEhEAw9C0GpASEQDDwLQawBIRAMOwtBwAEhEAw6C0G5ASEQDDkLQa8BIRAMOAtBsQEhEAw3C0GyASEQDDYLQbQBIRAMNQtBtQEhEAw0C0G6ASEQDDMLQb0BIRAMMgtBvwEhEAwxC0HBASEQDDALIABBADYCHCAAIAQ2AhQgAEHpi4CAADYCECAAQR82AgxBACEQDEgLIABB2wE2AhwgACAENgIUIABB+paAgAA2AhAgAEEVNgIMQQAhEAxHCyAAQfgANgIcIAAgDDYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMRgsgAEHRADYCHCAAIAU2AhQgAEGwl4CAADYCECAAQRU2AgxBACEQDEULIABB+QA2AhwgACABNgIUIAAgEDYCDEEAIRAMRAsgAEH4ADYCHCAAIAE2AhQgAEHKmICAADYCECAAQRU2AgxBACEQDEMLIABB5AA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAxCCyAAQdcANgIcIAAgATYCFCAAQcmXgIAANgIQIABBFTYCDEEAIRAMQQsgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMQAsgAEHCADYCHCAAIAE2AhQgAEHjmICAADYCECAAQRU2AgxBACEQDD8LIABBADYCBCAAIA8gDxCxgICAACIERQ0BIABBOjYCHCAAIAQ2AgwgACAPQQFqNgIUQQAhEAw+CyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBEUNACAAQTs2AhwgACAENgIMIAAgAUEBajYCFEEAIRAMPgsgAUEBaiEBDC0LIA9BAWohAQwtCyAAQQA2AhwgACAPNgIUIABB5JKAgAA2AhAgAEEENgIMQQAhEAw7CyAAQTY2AhwgACAENgIUIAAgAjYCDEEAIRAMOgsgAEEuNgIcIAAgDjYCFCAAIAQ2AgxBACEQDDkLIABB0AA2AhwgACABNgIUIABBkZiAgAA2AhAgAEEVNgIMQQAhEAw4CyANQQFqIQEMLAsgAEEVNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMNgsgAEEbNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNQsgAEEPNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNAsgAEELNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMMwsgAEEaNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMgsgAEELNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMQsgAEEKNgIcIAAgATYCFCAAQeSWgIAANgIQIABBFTYCDEEAIRAMMAsgAEEeNgIcIAAgATYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAMLwsgAEEANgIcIAAgEDYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMLgsgAEEENgIcIAAgATYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMLQsgAEEANgIAIAtBAWohCwtBuAEhEAwSCyAAQQA2AgAgEEEBaiEBQfUAIRAMEQsgASEBAkAgAC0AKUEFRw0AQeMAIRAMEQtB4gAhEAwQC0EAIRAgAEEANgIcIABB5JGAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAwoCyAAQQA2AgAgF0EBaiEBQcAAIRAMDgtBASEBCyAAIAE6ACwgAEEANgIAIBdBAWohAQtBKCEQDAsLIAEhAQtBOCEQDAkLAkAgASIPIAJGDQADQAJAIA8tAABBgL6AgABqLQAAIgFBAUYNACABQQJHDQMgD0EBaiEBDAQLIA9BAWoiDyACRw0AC0E+IRAMIgtBPiEQDCELIABBADoALCAPIQEMAQtBCyEQDAYLQTohEAwFCyABQQFqIQFBLSEQDAQLIAAgAToALCAAQQA2AgAgFkEBaiEBQQwhEAwDCyAAQQA2AgAgF0EBaiEBQQohEAwCCyAAQQA2AgALIABBADoALCANIQFBCSEQDAALC0EAIRAgAEEANgIcIAAgCzYCFCAAQc2QgIAANgIQIABBCTYCDAwXC0EAIRAgAEEANgIcIAAgCjYCFCAAQemKgIAANgIQIABBCTYCDAwWC0EAIRAgAEEANgIcIAAgCTYCFCAAQbeQgIAANgIQIABBCTYCDAwVC0EAIRAgAEEANgIcIAAgCDYCFCAAQZyRgIAANgIQIABBCTYCDAwUC0EAIRAgAEEANgIcIAAgATYCFCAAQc2QgIAANgIQIABBCTYCDAwTC0EAIRAgAEEANgIcIAAgATYCFCAAQemKgIAANgIQIABBCTYCDAwSC0EAIRAgAEEANgIcIAAgATYCFCAAQbeQgIAANgIQIABBCTYCDAwRC0EAIRAgAEEANgIcIAAgATYCFCAAQZyRgIAANgIQIABBCTYCDAwQC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwPC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwOC0EAIRAgAEEANgIcIAAgATYCFCAAQcCSgIAANgIQIABBCzYCDAwNC0EAIRAgAEEANgIcIAAgATYCFCAAQZWJgIAANgIQIABBCzYCDAwMC0EAIRAgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDAwLC0EAIRAgAEEANgIcIAAgATYCFCAAQfuPgIAANgIQIABBCjYCDAwKC0EAIRAgAEEANgIcIAAgATYCFCAAQfGZgIAANgIQIABBAjYCDAwJC0EAIRAgAEEANgIcIAAgATYCFCAAQcSUgIAANgIQIABBAjYCDAwIC0EAIRAgAEEANgIcIAAgATYCFCAAQfKVgIAANgIQIABBAjYCDAwHCyAAQQI2AhwgACABNgIUIABBnJqAgAA2AhAgAEEWNgIMQQAhEAwGC0EBIRAMBQtB1AAhECABIgQgAkYNBCADQQhqIAAgBCACQdjCgIAAQQoQxYCAgAAgAygCDCEEIAMoAggOAwEEAgALEMqAgIAAAAsgAEEANgIcIABBtZqAgAA2AhAgAEEXNgIMIAAgBEEBajYCFEEAIRAMAgsgAEEANgIcIAAgBDYCFCAAQcqagIAANgIQIABBCTYCDEEAIRAMAQsCQCABIgQgAkcNAEEiIRAMAQsgAEGJgICAADYCCCAAIAQ2AgRBISEQCyADQRBqJICAgIAAIBALrwEBAn8gASgCACEGAkACQCACIANGDQAgBCAGaiEEIAYgA2ogAmshByACIAZBf3MgBWoiBmohBQNAAkAgAi0AACAELQAARg0AQQIhBAwDCwJAIAYNAEEAIQQgBSECDAMLIAZBf2ohBiAEQQFqIQQgAkEBaiICIANHDQALIAchBiADIQILIABBATYCACABIAY2AgAgACACNgIEDwsgAUEANgIAIAAgBDYCACAAIAI2AgQLCgAgABDHgICAAAvyNgELfyOAgICAAEEQayIBJICAgIAAAkBBACgCoNCAgAANAEEAEMuAgIAAQYDUhIAAayICQdkASQ0AQQAhAwJAQQAoAuDTgIAAIgQNAEEAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEIakFwcUHYqtWqBXMiBDYC4NOAgABBAEEANgL004CAAEEAQQA2AsTTgIAAC0EAIAI2AszTgIAAQQBBgNSEgAA2AsjTgIAAQQBBgNSEgAA2ApjQgIAAQQAgBDYCrNCAgABBAEF/NgKo0ICAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALQYDUhIAAQXhBgNSEgABrQQ9xQQBBgNSEgABBCGpBD3EbIgNqIgRBBGogAkFIaiIFIANrIgNBAXI2AgBBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAQYDUhIAAIAVqQTg2AgQLAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFLDQACQEEAKAKI0ICAACIGQRAgAEETakFwcSAAQQtJGyICQQN2IgR2IgNBA3FFDQACQAJAIANBAXEgBHJBAXMiBUEDdCIEQbDQgIAAaiIDIARBuNCAgABqKAIAIgQoAggiAkcNAEEAIAZBfiAFd3E2AojQgIAADAELIAMgAjYCCCACIAM2AgwLIARBCGohAyAEIAVBA3QiBUEDcjYCBCAEIAVqIgQgBCgCBEEBcjYCBAwMCyACQQAoApDQgIAAIgdNDQECQCADRQ0AAkACQCADIAR0QQIgBHQiA0EAIANrcnEiA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqIgRBA3QiA0Gw0ICAAGoiBSADQbjQgIAAaigCACIDKAIIIgBHDQBBACAGQX4gBHdxIgY2AojQgIAADAELIAUgADYCCCAAIAU2AgwLIAMgAkEDcjYCBCADIARBA3QiBGogBCACayIFNgIAIAMgAmoiACAFQQFyNgIEAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQQCQAJAIAZBASAHQQN2dCIIcQ0AQQAgBiAIcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCAENgIMIAIgBDYCCCAEIAI2AgwgBCAINgIICyADQQhqIQNBACAANgKc0ICAAEEAIAU2ApDQgIAADAwLQQAoAozQgIAAIglFDQEgCUEAIAlrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqQQJ0QbjSgIAAaigCACIAKAIEQXhxIAJrIQQgACEFAkADQAJAIAUoAhAiAw0AIAVBFGooAgAiA0UNAgsgAygCBEF4cSACayIFIAQgBSAESSIFGyEEIAMgACAFGyEAIAMhBQwACwsgACgCGCEKAkAgACgCDCIIIABGDQAgACgCCCIDQQAoApjQgIAASRogCCADNgIIIAMgCDYCDAwLCwJAIABBFGoiBSgCACIDDQAgACgCECIDRQ0DIABBEGohBQsDQCAFIQsgAyIIQRRqIgUoAgAiAw0AIAhBEGohBSAIKAIQIgMNAAsgC0EANgIADAoLQX8hAiAAQb9/Sw0AIABBE2oiA0FwcSECQQAoAozQgIAAIgdFDQBBACELAkAgAkGAAkkNAEEfIQsgAkH///8HSw0AIANBCHYiAyADQYD+P2pBEHZBCHEiA3QiBCAEQYDgH2pBEHZBBHEiBHQiBSAFQYCAD2pBEHZBAnEiBXRBD3YgAyAEciAFcmsiA0EBdCACIANBFWp2QQFxckEcaiELC0EAIAJrIQQCQAJAAkACQCALQQJ0QbjSgIAAaigCACIFDQBBACEDQQAhCAwBC0EAIQMgAkEAQRkgC0EBdmsgC0EfRht0IQBBACEIA0ACQCAFKAIEQXhxIAJrIgYgBE8NACAGIQQgBSEIIAYNAEEAIQQgBSEIIAUhAwwDCyADIAVBFGooAgAiBiAGIAUgAEEddkEEcWpBEGooAgAiBUYbIAMgBhshAyAAQQF0IQAgBQ0ACwsCQCADIAhyDQBBACEIQQIgC3QiA0EAIANrciAHcSIDRQ0DIANBACADa3FBf2oiAyADQQx2QRBxIgN2IgVBBXZBCHEiACADciAFIAB2IgNBAnZBBHEiBXIgAyAFdiIDQQF2QQJxIgVyIAMgBXYiA0EBdkEBcSIFciADIAV2akECdEG40oCAAGooAgAhAwsgA0UNAQsDQCADKAIEQXhxIAJrIgYgBEkhAAJAIAMoAhAiBQ0AIANBFGooAgAhBQsgBiAEIAAbIQQgAyAIIAAbIQggBSEDIAUNAAsLIAhFDQAgBEEAKAKQ0ICAACACa08NACAIKAIYIQsCQCAIKAIMIgAgCEYNACAIKAIIIgNBACgCmNCAgABJGiAAIAM2AgggAyAANgIMDAkLAkAgCEEUaiIFKAIAIgMNACAIKAIQIgNFDQMgCEEQaiEFCwNAIAUhBiADIgBBFGoiBSgCACIDDQAgAEEQaiEFIAAoAhAiAw0ACyAGQQA2AgAMCAsCQEEAKAKQ0ICAACIDIAJJDQBBACgCnNCAgAAhBAJAAkAgAyACayIFQRBJDQAgBCACaiIAIAVBAXI2AgRBACAFNgKQ0ICAAEEAIAA2ApzQgIAAIAQgA2ogBTYCACAEIAJBA3I2AgQMAQsgBCADQQNyNgIEIAQgA2oiAyADKAIEQQFyNgIEQQBBADYCnNCAgABBAEEANgKQ0ICAAAsgBEEIaiEDDAoLAkBBACgClNCAgAAiACACTQ0AQQAoAqDQgIAAIgMgAmoiBCAAIAJrIgVBAXI2AgRBACAFNgKU0ICAAEEAIAQ2AqDQgIAAIAMgAkEDcjYCBCADQQhqIQMMCgsCQAJAQQAoAuDTgIAARQ0AQQAoAujTgIAAIQQMAQtBAEJ/NwLs04CAAEEAQoCAhICAgMAANwLk04CAAEEAIAFBDGpBcHFB2KrVqgVzNgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgABBgIAEIQQLQQAhAwJAIAQgAkHHAGoiB2oiBkEAIARrIgtxIgggAksNAEEAQTA2AvjTgIAADAoLAkBBACgCwNOAgAAiA0UNAAJAQQAoArjTgIAAIgQgCGoiBSAETQ0AIAUgA00NAQtBACEDQQBBMDYC+NOAgAAMCgtBAC0AxNOAgABBBHENBAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQAJAIAMoAgAiBSAESw0AIAUgAygCBGogBEsNAwsgAygCCCIDDQALC0EAEMuAgIAAIgBBf0YNBSAIIQYCQEEAKALk04CAACIDQX9qIgQgAHFFDQAgCCAAayAEIABqQQAgA2txaiEGCyAGIAJNDQUgBkH+////B0sNBQJAQQAoAsDTgIAAIgNFDQBBACgCuNOAgAAiBCAGaiIFIARNDQYgBSADSw0GCyAGEMuAgIAAIgMgAEcNAQwHCyAGIABrIAtxIgZB/v///wdLDQQgBhDLgICAACIAIAMoAgAgAygCBGpGDQMgACEDCwJAIANBf0YNACACQcgAaiAGTQ0AAkAgByAGa0EAKALo04CAACIEakEAIARrcSIEQf7///8HTQ0AIAMhAAwHCwJAIAQQy4CAgABBf0YNACAEIAZqIQYgAyEADAcLQQAgBmsQy4CAgAAaDAQLIAMhACADQX9HDQUMAwtBACEIDAcLQQAhAAwFCyAAQX9HDQILQQBBACgCxNOAgABBBHI2AsTTgIAACyAIQf7///8HSw0BIAgQy4CAgAAhAEEAEMuAgIAAIQMgAEF/Rg0BIANBf0YNASAAIANPDQEgAyAAayIGIAJBOGpNDQELQQBBACgCuNOAgAAgBmoiAzYCuNOAgAACQCADQQAoArzTgIAATQ0AQQAgAzYCvNOAgAALAkACQAJAAkBBACgCoNCAgAAiBEUNAEHI04CAACEDA0AgACADKAIAIgUgAygCBCIIakYNAiADKAIIIgMNAAwDCwsCQAJAQQAoApjQgIAAIgNFDQAgACADTw0BC0EAIAA2ApjQgIAAC0EAIQNBACAGNgLM04CAAEEAIAA2AsjTgIAAQQBBfzYCqNCAgABBAEEAKALg04CAADYCrNCAgABBAEEANgLU04CAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgQgBkFIaiIFIANrIgNBAXI2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAIAAgBWpBODYCBAwCCyADLQAMQQhxDQAgBCAFSQ0AIAQgAE8NACAEQXggBGtBD3FBACAEQQhqQQ9xGyIFaiIAQQAoApTQgIAAIAZqIgsgBWsiBUEBcjYCBCADIAggBmo2AgRBAEEAKALw04CAADYCpNCAgABBACAFNgKU0ICAAEEAIAA2AqDQgIAAIAQgC2pBODYCBAwBCwJAIABBACgCmNCAgAAiCE8NAEEAIAA2ApjQgIAAIAAhCAsgACAGaiEFQcjTgIAAIQMCQAJAAkACQAJAAkACQANAIAMoAgAgBUYNASADKAIIIgMNAAwCCwsgAy0ADEEIcUUNAQtByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiIFIARLDQMLIAMoAgghAwwACwsgAyAANgIAIAMgAygCBCAGajYCBCAAQXggAGtBD3FBACAAQQhqQQ9xG2oiCyACQQNyNgIEIAVBeCAFa0EPcUEAIAVBCGpBD3EbaiIGIAsgAmoiAmshAwJAIAYgBEcNAEEAIAI2AqDQgIAAQQBBACgClNCAgAAgA2oiAzYClNCAgAAgAiADQQFyNgIEDAMLAkAgBkEAKAKc0ICAAEcNAEEAIAI2ApzQgIAAQQBBACgCkNCAgAAgA2oiAzYCkNCAgAAgAiADQQFyNgIEIAIgA2ogAzYCAAwDCwJAIAYoAgQiBEEDcUEBRw0AIARBeHEhBwJAAkAgBEH/AUsNACAGKAIIIgUgBEEDdiIIQQN0QbDQgIAAaiIARhoCQCAGKAIMIgQgBUcNAEEAQQAoAojQgIAAQX4gCHdxNgKI0ICAAAwCCyAEIABGGiAEIAU2AgggBSAENgIMDAELIAYoAhghCQJAAkAgBigCDCIAIAZGDQAgBigCCCIEIAhJGiAAIAQ2AgggBCAANgIMDAELAkAgBkEUaiIEKAIAIgUNACAGQRBqIgQoAgAiBQ0AQQAhAAwBCwNAIAQhCCAFIgBBFGoiBCgCACIFDQAgAEEQaiEEIAAoAhAiBQ0ACyAIQQA2AgALIAlFDQACQAJAIAYgBigCHCIFQQJ0QbjSgIAAaiIEKAIARw0AIAQgADYCACAADQFBAEEAKAKM0ICAAEF+IAV3cTYCjNCAgAAMAgsgCUEQQRQgCSgCECAGRhtqIAA2AgAgAEUNAQsgACAJNgIYAkAgBigCECIERQ0AIAAgBDYCECAEIAA2AhgLIAYoAhQiBEUNACAAQRRqIAQ2AgAgBCAANgIYCyAHIANqIQMgBiAHaiIGKAIEIQQLIAYgBEF+cTYCBCACIANqIAM2AgAgAiADQQFyNgIEAkAgA0H/AUsNACADQXhxQbDQgIAAaiEEAkACQEEAKAKI0ICAACIFQQEgA0EDdnQiA3ENAEEAIAUgA3I2AojQgIAAIAQhAwwBCyAEKAIIIQMLIAMgAjYCDCAEIAI2AgggAiAENgIMIAIgAzYCCAwDC0EfIQQCQCADQf///wdLDQAgA0EIdiIEIARBgP4/akEQdkEIcSIEdCIFIAVBgOAfakEQdkEEcSIFdCIAIABBgIAPakEQdkECcSIAdEEPdiAEIAVyIAByayIEQQF0IAMgBEEVanZBAXFyQRxqIQQLIAIgBDYCHCACQgA3AhAgBEECdEG40oCAAGohBQJAQQAoAozQgIAAIgBBASAEdCIIcQ0AIAUgAjYCAEEAIAAgCHI2AozQgIAAIAIgBTYCGCACIAI2AgggAiACNgIMDAMLIANBAEEZIARBAXZrIARBH0YbdCEEIAUoAgAhAANAIAAiBSgCBEF4cSADRg0CIARBHXYhACAEQQF0IQQgBSAAQQRxakEQaiIIKAIAIgANAAsgCCACNgIAIAIgBTYCGCACIAI2AgwgAiACNgIIDAILIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgsgBkFIaiIIIANrIgNBAXI2AgQgACAIakE4NgIEIAQgBUE3IAVrQQ9xQQAgBUFJakEPcRtqQUFqIgggCCAEQRBqSRsiCEEjNgIEQQBBACgC8NOAgAA2AqTQgIAAQQAgAzYClNCAgABBACALNgKg0ICAACAIQRBqQQApAtDTgIAANwIAIAhBACkCyNOAgAA3AghBACAIQQhqNgLQ04CAAEEAIAY2AszTgIAAQQAgADYCyNOAgABBAEEANgLU04CAACAIQSRqIQMDQCADQQc2AgAgA0EEaiIDIAVJDQALIAggBEYNAyAIIAgoAgRBfnE2AgQgCCAIIARrIgA2AgAgBCAAQQFyNgIEAkAgAEH/AUsNACAAQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgAEEDdnQiAHENAEEAIAUgAHI2AojQgIAAIAMhBQwBCyADKAIIIQULIAUgBDYCDCADIAQ2AgggBCADNgIMIAQgBTYCCAwEC0EfIQMCQCAAQf///wdLDQAgAEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCIIIAhBgIAPakEQdkECcSIIdEEPdiADIAVyIAhyayIDQQF0IAAgA0EVanZBAXFyQRxqIQMLIAQgAzYCHCAEQgA3AhAgA0ECdEG40oCAAGohBQJAQQAoAozQgIAAIghBASADdCIGcQ0AIAUgBDYCAEEAIAggBnI2AozQgIAAIAQgBTYCGCAEIAQ2AgggBCAENgIMDAQLIABBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhCANAIAgiBSgCBEF4cSAARg0DIANBHXYhCCADQQF0IQMgBSAIQQRxakEQaiIGKAIAIggNAAsgBiAENgIAIAQgBTYCGCAEIAQ2AgwgBCAENgIIDAMLIAUoAggiAyACNgIMIAUgAjYCCCACQQA2AhggAiAFNgIMIAIgAzYCCAsgC0EIaiEDDAULIAUoAggiAyAENgIMIAUgBDYCCCAEQQA2AhggBCAFNgIMIAQgAzYCCAtBACgClNCAgAAiAyACTQ0AQQAoAqDQgIAAIgQgAmoiBSADIAJrIgNBAXI2AgRBACADNgKU0ICAAEEAIAU2AqDQgIAAIAQgAkEDcjYCBCAEQQhqIQMMAwtBACEDQQBBMDYC+NOAgAAMAgsCQCALRQ0AAkACQCAIIAgoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAA2AgAgAA0BQQAgB0F+IAV3cSIHNgKM0ICAAAwCCyALQRBBFCALKAIQIAhGG2ogADYCACAARQ0BCyAAIAs2AhgCQCAIKAIQIgNFDQAgACADNgIQIAMgADYCGAsgCEEUaigCACIDRQ0AIABBFGogAzYCACADIAA2AhgLAkACQCAEQQ9LDQAgCCAEIAJqIgNBA3I2AgQgCCADaiIDIAMoAgRBAXI2AgQMAQsgCCACaiIAIARBAXI2AgQgCCACQQNyNgIEIAAgBGogBDYCAAJAIARB/wFLDQAgBEF4cUGw0ICAAGohAwJAAkBBACgCiNCAgAAiBUEBIARBA3Z0IgRxDQBBACAFIARyNgKI0ICAACADIQQMAQsgAygCCCEECyAEIAA2AgwgAyAANgIIIAAgAzYCDCAAIAQ2AggMAQtBHyEDAkAgBEH///8HSw0AIARBCHYiAyADQYD+P2pBEHZBCHEiA3QiBSAFQYDgH2pBEHZBBHEiBXQiAiACQYCAD2pBEHZBAnEiAnRBD3YgAyAFciACcmsiA0EBdCAEIANBFWp2QQFxckEcaiEDCyAAIAM2AhwgAEIANwIQIANBAnRBuNKAgABqIQUCQCAHQQEgA3QiAnENACAFIAA2AgBBACAHIAJyNgKM0ICAACAAIAU2AhggACAANgIIIAAgADYCDAwBCyAEQQBBGSADQQF2ayADQR9GG3QhAyAFKAIAIQICQANAIAIiBSgCBEF4cSAERg0BIANBHXYhAiADQQF0IQMgBSACQQRxakEQaiIGKAIAIgINAAsgBiAANgIAIAAgBTYCGCAAIAA2AgwgACAANgIIDAELIAUoAggiAyAANgIMIAUgADYCCCAAQQA2AhggACAFNgIMIAAgAzYCCAsgCEEIaiEDDAELAkAgCkUNAAJAAkAgACAAKAIcIgVBAnRBuNKAgABqIgMoAgBHDQAgAyAINgIAIAgNAUEAIAlBfiAFd3E2AozQgIAADAILIApBEEEUIAooAhAgAEYbaiAINgIAIAhFDQELIAggCjYCGAJAIAAoAhAiA0UNACAIIAM2AhAgAyAINgIYCyAAQRRqKAIAIgNFDQAgCEEUaiADNgIAIAMgCDYCGAsCQAJAIARBD0sNACAAIAQgAmoiA0EDcjYCBCAAIANqIgMgAygCBEEBcjYCBAwBCyAAIAJqIgUgBEEBcjYCBCAAIAJBA3I2AgQgBSAEaiAENgIAAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQMCQAJAQQEgB0EDdnQiCCAGcQ0AQQAgCCAGcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCADNgIMIAIgAzYCCCADIAI2AgwgAyAINgIIC0EAIAU2ApzQgIAAQQAgBDYCkNCAgAALIABBCGohAwsgAUEQaiSAgICAACADCwoAIAAQyYCAgAAL4g0BB38CQCAARQ0AIABBeGoiASAAQXxqKAIAIgJBeHEiAGohAwJAIAJBAXENACACQQNxRQ0BIAEgASgCACICayIBQQAoApjQgIAAIgRJDQEgAiAAaiEAAkAgAUEAKAKc0ICAAEYNAAJAIAJB/wFLDQAgASgCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgASgCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAwsgAiAGRhogAiAENgIIIAQgAjYCDAwCCyABKAIYIQcCQAJAIAEoAgwiBiABRg0AIAEoAggiAiAESRogBiACNgIIIAIgBjYCDAwBCwJAIAFBFGoiAigCACIEDQAgAUEQaiICKAIAIgQNAEEAIQYMAQsDQCACIQUgBCIGQRRqIgIoAgAiBA0AIAZBEGohAiAGKAIQIgQNAAsgBUEANgIACyAHRQ0BAkACQCABIAEoAhwiBEECdEG40oCAAGoiAigCAEcNACACIAY2AgAgBg0BQQBBACgCjNCAgABBfiAEd3E2AozQgIAADAMLIAdBEEEUIAcoAhAgAUYbaiAGNgIAIAZFDQILIAYgBzYCGAJAIAEoAhAiAkUNACAGIAI2AhAgAiAGNgIYCyABKAIUIgJFDQEgBkEUaiACNgIAIAIgBjYCGAwBCyADKAIEIgJBA3FBA0cNACADIAJBfnE2AgRBACAANgKQ0ICAACABIABqIAA2AgAgASAAQQFyNgIEDwsgASADTw0AIAMoAgQiAkEBcUUNAAJAAkAgAkECcQ0AAkAgA0EAKAKg0ICAAEcNAEEAIAE2AqDQgIAAQQBBACgClNCAgAAgAGoiADYClNCAgAAgASAAQQFyNgIEIAFBACgCnNCAgABHDQNBAEEANgKQ0ICAAEEAQQA2ApzQgIAADwsCQCADQQAoApzQgIAARw0AQQAgATYCnNCAgABBAEEAKAKQ0ICAACAAaiIANgKQ0ICAACABIABBAXI2AgQgASAAaiAANgIADwsgAkF4cSAAaiEAAkACQCACQf8BSw0AIAMoAggiBCACQQN2IgVBA3RBsNCAgABqIgZGGgJAIAMoAgwiAiAERw0AQQBBACgCiNCAgABBfiAFd3E2AojQgIAADAILIAIgBkYaIAIgBDYCCCAEIAI2AgwMAQsgAygCGCEHAkACQCADKAIMIgYgA0YNACADKAIIIgJBACgCmNCAgABJGiAGIAI2AgggAiAGNgIMDAELAkAgA0EUaiICKAIAIgQNACADQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQACQAJAIAMgAygCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAgsgB0EQQRQgBygCECADRhtqIAY2AgAgBkUNAQsgBiAHNgIYAkAgAygCECICRQ0AIAYgAjYCECACIAY2AhgLIAMoAhQiAkUNACAGQRRqIAI2AgAgAiAGNgIYCyABIABqIAA2AgAgASAAQQFyNgIEIAFBACgCnNCAgABHDQFBACAANgKQ0ICAAA8LIAMgAkF+cTYCBCABIABqIAA2AgAgASAAQQFyNgIECwJAIABB/wFLDQAgAEF4cUGw0ICAAGohAgJAAkBBACgCiNCAgAAiBEEBIABBA3Z0IgBxDQBBACAEIAByNgKI0ICAACACIQAMAQsgAigCCCEACyAAIAE2AgwgAiABNgIIIAEgAjYCDCABIAA2AggPC0EfIQICQCAAQf///wdLDQAgAEEIdiICIAJBgP4/akEQdkEIcSICdCIEIARBgOAfakEQdkEEcSIEdCIGIAZBgIAPakEQdkECcSIGdEEPdiACIARyIAZyayICQQF0IAAgAkEVanZBAXFyQRxqIQILIAEgAjYCHCABQgA3AhAgAkECdEG40oCAAGohBAJAAkBBACgCjNCAgAAiBkEBIAJ0IgNxDQAgBCABNgIAQQAgBiADcjYCjNCAgAAgASAENgIYIAEgATYCCCABIAE2AgwMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgBCgCACEGAkADQCAGIgQoAgRBeHEgAEYNASACQR12IQYgAkEBdCECIAQgBkEEcWpBEGoiAygCACIGDQALIAMgATYCACABIAQ2AhggASABNgIMIAEgATYCCAwBCyAEKAIIIgAgATYCDCAEIAE2AgggAUEANgIYIAEgBDYCDCABIAA2AggLQQBBACgCqNCAgABBf2oiAUF/IAEbNgKo0ICAAAsLBAAAAAtOAAJAIAANAD8AQRB0DwsCQCAAQf//A3ENACAAQX9MDQACQCAAQRB2QAAiAEF/Rw0AQQBBMDYC+NOAgABBfw8LIABBEHQPCxDKgICAAAAL8gICA38BfgJAIAJFDQAgACABOgAAIAIgAGoiA0F/aiABOgAAIAJBA0kNACAAIAE6AAIgACABOgABIANBfWogAToAACADQX5qIAE6AAAgAkEHSQ0AIAAgAToAAyADQXxqIAE6AAAgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIFayICQSBJDQAgAa1CgYCAgBB+IQYgAyAFaiEBA0AgASAGNwMYIAEgBjcDECABIAY3AwggASAGNwMAIAFBIGohASACQWBqIgJBH0sNAAsLIAALC45IAQBBgAgLhkgBAAAAAgAAAAMAAAAAAAAAAAAAAAQAAAAFAAAAAAAAAAAAAAAGAAAABwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEludmFsaWQgY2hhciBpbiB1cmwgcXVlcnkAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9ib2R5AENvbnRlbnQtTGVuZ3RoIG92ZXJmbG93AENodW5rIHNpemUgb3ZlcmZsb3cAUmVzcG9uc2Ugb3ZlcmZsb3cASW52YWxpZCBtZXRob2QgZm9yIEhUVFAveC54IHJlcXVlc3QASW52YWxpZCBtZXRob2QgZm9yIFJUU1AveC54IHJlcXVlc3QARXhwZWN0ZWQgU09VUkNFIG1ldGhvZCBmb3IgSUNFL3gueCByZXF1ZXN0AEludmFsaWQgY2hhciBpbiB1cmwgZnJhZ21lbnQgc3RhcnQARXhwZWN0ZWQgZG90AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fc3RhdHVzAEludmFsaWQgcmVzcG9uc2Ugc3RhdHVzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABEdXBsaWNhdGUgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyIGluIHVybCBwYXRoAENvbnRlbnQtTGVuZ3RoIGNhbid0IGJlIHByZXNlbnQgd2l0aCBUcmFuc2Zlci1FbmNvZGluZwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBzaXplAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX3ZhbHVlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgdmFsdWUATWlzc2luZyBleHBlY3RlZCBMRiBhZnRlciBoZWFkZXIgdmFsdWUASW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fbmFtZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIG5hbWUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAXhMAACYTAAAwEAAA8BcAAJ0TAAAVEgAAORcAAPASAAAKEAAAdRIAAK0SAACCEwAATxQAAH8QAACgFQAAIxQAAIkSAACLFAAATRUAANQRAADPFAAAEBgAAMkWAADcFgAAwREAAOAXAAC7FAAAdBQAAHwVAADlFAAACBcAAB8QAABlFQAAoxQAACgVAAACFQAAmRUAACwQAACLGQAATw8AANQOAABqEAAAzhAAAAIXAACJDgAAbhMAABwTAABmFAAAVhcAAMETAADNEwAAbBMAAGgXAABmFwAAXxcAACITAADODwAAaQ4AANgOAABjFgAAyxMAAKoOAAAoFwAAJhcAAMUTAABdFgAA6BEAAGcTAABlEwAA8hYAAHMTAAAdFwAA+RYAAPMRAADPDgAAzhUAAAwSAACzEQAApREAAGEQAAAyFwAAuxMAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIDAgICAgIAAAICAAICAAICAgICAgICAgIABAAAAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAACAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbG9zZWVlcC1hbGl2ZQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AAAAAAAAAAAAAAAAAAAByYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AAAAAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQIAAQMAAAAAAAAAAAAAAAAAAAAAAAAEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAQAAAgAAAAAAAAAAAAAAAAAAAAAAAAMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=' + + +/***/ }), + +/***/ 5627: +/***/ ((module) => { + +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCrLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AcsBygG4AckBuQHIAboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBANwBC0EAIRAMxgELQQ4hEAzFAQtBDSEQDMQBC0EPIRAMwwELQRAhEAzCAQtBEyEQDMEBC0EUIRAMwAELQRUhEAy/AQtBFiEQDL4BC0EXIRAMvQELQRghEAy8AQtBGSEQDLsBC0EaIRAMugELQRshEAy5AQtBHCEQDLgBC0EIIRAMtwELQR0hEAy2AQtBICEQDLUBC0EfIRAMtAELQQchEAyzAQtBISEQDLIBC0EiIRAMsQELQR4hEAywAQtBIyEQDK8BC0ESIRAMrgELQREhEAytAQtBJCEQDKwBC0ElIRAMqwELQSYhEAyqAQtBJyEQDKkBC0HDASEQDKgBC0EpIRAMpwELQSshEAymAQtBLCEQDKUBC0EtIRAMpAELQS4hEAyjAQtBLyEQDKIBC0HEASEQDKEBC0EwIRAMoAELQTQhEAyfAQtBDCEQDJ4BC0ExIRAMnQELQTIhEAycAQtBMyEQDJsBC0E5IRAMmgELQTUhEAyZAQtBxQEhEAyYAQtBCyEQDJcBC0E6IRAMlgELQTYhEAyVAQtBCiEQDJQBC0E3IRAMkwELQTghEAySAQtBPCEQDJEBC0E7IRAMkAELQT0hEAyPAQtBCSEQDI4BC0EoIRAMjQELQT4hEAyMAQtBPyEQDIsBC0HAACEQDIoBC0HBACEQDIkBC0HCACEQDIgBC0HDACEQDIcBC0HEACEQDIYBC0HFACEQDIUBC0HGACEQDIQBC0EqIRAMgwELQccAIRAMggELQcgAIRAMgQELQckAIRAMgAELQcoAIRAMfwtBywAhEAx+C0HNACEQDH0LQcwAIRAMfAtBzgAhEAx7C0HPACEQDHoLQdAAIRAMeQtB0QAhEAx4C0HSACEQDHcLQdMAIRAMdgtB1AAhEAx1C0HWACEQDHQLQdUAIRAMcwtBBiEQDHILQdcAIRAMcQtBBSEQDHALQdgAIRAMbwtBBCEQDG4LQdkAIRAMbQtB2gAhEAxsC0HbACEQDGsLQdwAIRAMagtBAyEQDGkLQd0AIRAMaAtB3gAhEAxnC0HfACEQDGYLQeEAIRAMZQtB4AAhEAxkC0HiACEQDGMLQeMAIRAMYgtBAiEQDGELQeQAIRAMYAtB5QAhEAxfC0HmACEQDF4LQecAIRAMXQtB6AAhEAxcC0HpACEQDFsLQeoAIRAMWgtB6wAhEAxZC0HsACEQDFgLQe0AIRAMVwtB7gAhEAxWC0HvACEQDFULQfAAIRAMVAtB8QAhEAxTC0HyACEQDFILQfMAIRAMUQtB9AAhEAxQC0H1ACEQDE8LQfYAIRAMTgtB9wAhEAxNC0H4ACEQDEwLQfkAIRAMSwtB+gAhEAxKC0H7ACEQDEkLQfwAIRAMSAtB/QAhEAxHC0H+ACEQDEYLQf8AIRAMRQtBgAEhEAxEC0GBASEQDEMLQYIBIRAMQgtBgwEhEAxBC0GEASEQDEALQYUBIRAMPwtBhgEhEAw+C0GHASEQDD0LQYgBIRAMPAtBiQEhEAw7C0GKASEQDDoLQYsBIRAMOQtBjAEhEAw4C0GNASEQDDcLQY4BIRAMNgtBjwEhEAw1C0GQASEQDDQLQZEBIRAMMwtBkgEhEAwyC0GTASEQDDELQZQBIRAMMAtBlQEhEAwvC0GWASEQDC4LQZcBIRAMLQtBmAEhEAwsC0GZASEQDCsLQZoBIRAMKgtBmwEhEAwpC0GcASEQDCgLQZ0BIRAMJwtBngEhEAwmC0GfASEQDCULQaABIRAMJAtBoQEhEAwjC0GiASEQDCILQaMBIRAMIQtBpAEhEAwgC0GlASEQDB8LQaYBIRAMHgtBpwEhEAwdC0GoASEQDBwLQakBIRAMGwtBqgEhEAwaC0GrASEQDBkLQawBIRAMGAtBrQEhEAwXC0GuASEQDBYLQQEhEAwVC0GvASEQDBQLQbABIRAMEwtBsQEhEAwSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB4fICEjJSg/QEFERUZHSElKS0xNT1BRUlPeA1dZW1xdYGJlZmdoaWprbG1vcHFyc3R1dnd4eXp7fH1+gAGCAYUBhgGHAYkBiwGMAY0BjgGPAZABkQGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwG4AbkBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgHHAcgByQHKAcsBzAHNAc4BzwHQAdEB0gHTAdQB1QHWAdcB2AHZAdoB2wHcAd0B3gHgAeEB4gHjAeQB5QHmAecB6AHpAeoB6wHsAe0B7gHvAfAB8QHyAfMBmQKkArAC/gL+AgsgASIEIAJHDfMBQd0BIRAM/wMLIAEiECACRw3dAUHDASEQDP4DCyABIgEgAkcNkAFB9wAhEAz9AwsgASIBIAJHDYYBQe8AIRAM/AMLIAEiASACRw1/QeoAIRAM+wMLIAEiASACRw17QegAIRAM+gMLIAEiASACRw14QeYAIRAM+QMLIAEiASACRw0aQRghEAz4AwsgASIBIAJHDRRBEiEQDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg0AIABBi4CAgAA2AgggACABNgIEIAEhAUEHIRAMxAMLQRkhEAzcAwsgAUEBaiEBDAILAkAgASIUIAJHDQBBGiEQDNsDCyAUIQECQCAULQAAQXNqDhTdAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAgDuAgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQM2gMLAkAgAS0AACIQQTtGDQAgEEENRw3oASABQQFqIQEM5QILIAFBAWohAQtBIiEQDL8DCwJAIAEiECACRw0AQRwhEAzYAwtCACERIBAhASAQLQAAQVBqDjfnAeYBAQIDBAUGBwgAAAAAAAAACQoLDA0OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPEBESExQAC0EeIRAMvQMLQgIhEQzlAQtCAyERDOQBC0IEIREM4wELQgUhEQziAQtCBiERDOEBC0IHIREM4AELQgghEQzfAQtCCSERDN4BC0IKIREM3QELQgshEQzcAQtCDCERDNsBC0INIREM2gELQg4hEQzZAQtCDyERDNgBC0IKIREM1wELQgshEQzWAQtCDCERDNUBC0INIREM1AELQg4hEQzTAQtCDyERDNIBC0IAIRECQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAtAABBUGoON+UB5AEAAQIDBAUGB+YB5gHmAeYB5gHmAeYBCAkKCwwN5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAQ4PEBESE+YBC0ICIREM5AELQgMhEQzjAQtCBCERDOIBC0IFIREM4QELQgYhEQzgAQtCByERDN8BC0IIIREM3gELQgkhEQzdAQtCCiERDNwBC0ILIREM2wELQgwhEQzaAQtCDSERDNkBC0IOIREM2AELQg8hEQzXAQtCCiERDNYBC0ILIREM1QELQgwhEQzUAQtCDSERDNMBC0IOIREM0gELQg8hEQzRAQsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3SAUEfIRAMwAMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQSQhEAynAwtBICEQDL8DCyAAIAEiECACEL6AgIAAQX9qDgW2AQDFAgHRAdIBC0ERIRAMpAMLIABBAToALyAQIQEMuwMLIAEiASACRw3SAUEkIRAMuwMLIAEiDSACRw0eQcYAIRAMugMLIAAgASIBIAIQsoCAgAAiEA3UASABIQEMtQELIAEiECACRw0mQdAAIRAMuAMLAkAgASIBIAJHDQBBKCEQDLgDCyAAQQA2AgQgAEGMgICAADYCCCAAIAEgARCxgICAACIQDdMBIAEhAQzYAQsCQCABIhAgAkcNAEEpIRAMtwMLIBAtAAAiAUEgRg0UIAFBCUcN0wEgEEEBaiEBDBULAkAgASIBIAJGDQAgAUEBaiEBDBcLQSohEAy1AwsCQCABIhAgAkcNAEErIRAMtQMLAkAgEC0AACIBQQlGDQAgAUEgRw3VAQsgAC0ALEEIRg3TASAQIQEMkQMLAkAgASIBIAJHDQBBLCEQDLQDCyABLQAAQQpHDdUBIAFBAWohAQzJAgsgASIOIAJHDdUBQS8hEAyyAwsDQAJAIAEtAAAiEEEgRg0AAkAgEEF2ag4EANwB3AEA2gELIAEhAQzgAQsgAUEBaiIBIAJHDQALQTEhEAyxAwtBMiEQIAEiFCACRg2wAyACIBRrIAAoAgAiAWohFSAUIAFrQQNqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB8LuAgABqLQAARw0BAkAgAUEDRw0AQQYhAQyWAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMsQMLIABBADYCACAUIQEM2QELQTMhECABIhQgAkYNrwMgAiAUayAAKAIAIgFqIRUgFCABa0EIaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfS7gIAAai0AAEcNAQJAIAFBCEcNAEEFIQEMlQMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLADCyAAQQA2AgAgFCEBDNgBC0E0IRAgASIUIAJGDa4DIAIgFGsgACgCACIBaiEVIBQgAWtBBWohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUHQwoCAAGotAABHDQECQCABQQVHDQBBByEBDJQDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAyvAwsgAEEANgIAIBQhAQzXAQsCQCABIgEgAkYNAANAAkAgAS0AAEGAvoCAAGotAAAiEEEBRg0AIBBBAkYNCiABIQEM3QELIAFBAWoiASACRw0AC0EwIRAMrgMLQTAhEAytAwsCQCABIgEgAkYNAANAAkAgAS0AACIQQSBGDQAgEEF2ag4E2QHaAdoB2QHaAQsgAUEBaiIBIAJHDQALQTghEAytAwtBOCEQDKwDCwNAAkAgAS0AACIQQSBGDQAgEEEJRw0DCyABQQFqIgEgAkcNAAtBPCEQDKsDCwNAAkAgAS0AACIQQSBGDQACQAJAIBBBdmoOBNoBAQHaAQALIBBBLEYN2wELIAEhAQwECyABQQFqIgEgAkcNAAtBPyEQDKoDCyABIQEM2wELQcAAIRAgASIUIAJGDagDIAIgFGsgACgCACIBaiEWIBQgAWtBBmohFwJAA0AgFC0AAEEgciABQYDAgIAAai0AAEcNASABQQZGDY4DIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADKkDCyAAQQA2AgAgFCEBC0E2IRAMjgMLAkAgASIPIAJHDQBBwQAhEAynAwsgAEGMgICAADYCCCAAIA82AgQgDyEBIAAtACxBf2oOBM0B1QHXAdkBhwMLIAFBAWohAQzMAQsCQCABIgEgAkYNAANAAkAgAS0AACIQQSByIBAgEEG/f2pB/wFxQRpJG0H/AXEiEEEJRg0AIBBBIEYNAAJAAkACQAJAIBBBnX9qDhMAAwMDAwMDAwEDAwMDAwMDAwMCAwsgAUEBaiEBQTEhEAyRAwsgAUEBaiEBQTIhEAyQAwsgAUEBaiEBQTMhEAyPAwsgASEBDNABCyABQQFqIgEgAkcNAAtBNSEQDKUDC0E1IRAMpAMLAkAgASIBIAJGDQADQAJAIAEtAABBgLyAgABqLQAAQQFGDQAgASEBDNMBCyABQQFqIgEgAkcNAAtBPSEQDKQDC0E9IRAMowMLIAAgASIBIAIQsICAgAAiEA3WASABIQEMAQsgEEEBaiEBC0E8IRAMhwMLAkAgASIBIAJHDQBBwgAhEAygAwsCQANAAkAgAS0AAEF3ag4YAAL+Av4ChAP+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gIA/gILIAFBAWoiASACRw0AC0HCACEQDKADCyABQQFqIQEgAC0ALUEBcUUNvQEgASEBC0EsIRAMhQMLIAEiASACRw3TAUHEACEQDJ0DCwNAAkAgAS0AAEGQwICAAGotAABBAUYNACABIQEMtwILIAFBAWoiASACRw0AC0HFACEQDJwDCyANLQAAIhBBIEYNswEgEEE6Rw2BAyAAKAIEIQEgAEEANgIEIAAgASANEK+AgIAAIgEN0AEgDUEBaiEBDLMCC0HHACEQIAEiDSACRg2aAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQZDCgIAAai0AAEcNgAMgAUEFRg30AiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyaAwtByAAhECABIg0gAkYNmQMgAiANayAAKAIAIgFqIRYgDSABa0EJaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGWwoCAAGotAABHDf8CAkAgAUEJRw0AQQIhAQz1AgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmQMLAkAgASINIAJHDQBByQAhEAyZAwsCQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZJ/ag4HAIADgAOAA4ADgAMBgAMLIA1BAWohAUE+IRAMgAMLIA1BAWohAUE/IRAM/wILQcoAIRAgASINIAJGDZcDIAIgDWsgACgCACIBaiEWIA0gAWtBAWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBoMKAgABqLQAARw39AiABQQFGDfACIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJcDC0HLACEQIAEiDSACRg2WAyACIA1rIAAoAgAiAWohFiANIAFrQQ5qIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaLCgIAAai0AAEcN/AIgAUEORg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyWAwtBzAAhECABIg0gAkYNlQMgAiANayAAKAIAIgFqIRYgDSABa0EPaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUHAwoCAAGotAABHDfsCAkAgAUEPRw0AQQMhAQzxAgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlQMLQc0AIRAgASINIAJGDZQDIAIgDWsgACgCACIBaiEWIA0gAWtBBWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw36AgJAIAFBBUcNAEEEIQEM8AILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJQDCwJAIAEiDSACRw0AQc4AIRAMlAMLAkACQAJAAkAgDS0AACIBQSByIAEgAUG/f2pB/wFxQRpJG0H/AXFBnX9qDhMA/QL9Av0C/QL9Av0C/QL9Av0C/QL9Av0CAf0C/QL9AgID/QILIA1BAWohAUHBACEQDP0CCyANQQFqIQFBwgAhEAz8AgsgDUEBaiEBQcMAIRAM+wILIA1BAWohAUHEACEQDPoCCwJAIAEiASACRg0AIABBjYCAgAA2AgggACABNgIEIAEhAUHFACEQDPoCC0HPACEQDJIDCyAQIQECQAJAIBAtAABBdmoOBAGoAqgCAKgCCyAQQQFqIQELQSchEAz4AgsCQCABIgEgAkcNAEHRACEQDJEDCwJAIAEtAABBIEYNACABIQEMjQELIAFBAWohASAALQAtQQFxRQ3HASABIQEMjAELIAEiFyACRw3IAUHSACEQDI8DC0HTACEQIAEiFCACRg2OAyACIBRrIAAoAgAiAWohFiAUIAFrQQFqIRcDQCAULQAAIAFB1sKAgABqLQAARw3MASABQQFGDccBIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADI4DCwJAIAEiASACRw0AQdUAIRAMjgMLIAEtAABBCkcNzAEgAUEBaiEBDMcBCwJAIAEiASACRw0AQdYAIRAMjQMLAkACQCABLQAAQXZqDgQAzQHNAQHNAQsgAUEBaiEBDMcBCyABQQFqIQFBygAhEAzzAgsgACABIgEgAhCugICAACIQDcsBIAEhAUHNACEQDPICCyAALQApQSJGDYUDDKYCCwJAIAEiASACRw0AQdsAIRAMigMLQQAhFEEBIRdBASEWQQAhEAJAAkACQAJAAkACQAJAAkACQCABLQAAQVBqDgrUAdMBAAECAwQFBgjVAQtBAiEQDAYLQQMhEAwFC0EEIRAMBAtBBSEQDAMLQQYhEAwCC0EHIRAMAQtBCCEQC0EAIRdBACEWQQAhFAzMAQtBCSEQQQEhFEEAIRdBACEWDMsBCwJAIAEiASACRw0AQd0AIRAMiQMLIAEtAABBLkcNzAEgAUEBaiEBDKYCCyABIgEgAkcNzAFB3wAhEAyHAwsCQCABIgEgAkYNACAAQY6AgIAANgIIIAAgATYCBCABIQFB0AAhEAzuAgtB4AAhEAyGAwtB4QAhECABIgEgAkYNhQMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQeLCgIAAai0AAEcNzQEgFEEDRg3MASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyFAwtB4gAhECABIgEgAkYNhAMgAiABayAAKAIAIhRqIRYgASAUa0ECaiEXA0AgAS0AACAUQebCgIAAai0AAEcNzAEgFEECRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyEAwtB4wAhECABIgEgAkYNgwMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQenCgIAAai0AAEcNywEgFEEDRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyDAwsCQCABIgEgAkcNAEHlACEQDIMDCyAAIAFBAWoiASACEKiAgIAAIhANzQEgASEBQdYAIRAM6QILAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AAkACQAJAIBBBuH9qDgsAAc8BzwHPAc8BzwHPAc8BzwECzwELIAFBAWohAUHSACEQDO0CCyABQQFqIQFB0wAhEAzsAgsgAUEBaiEBQdQAIRAM6wILIAFBAWoiASACRw0AC0HkACEQDIIDC0HkACEQDIEDCwNAAkAgAS0AAEHwwoCAAGotAAAiEEEBRg0AIBBBfmoOA88B0AHRAdIBCyABQQFqIgEgAkcNAAtB5gAhEAyAAwsCQCABIgEgAkYNACABQQFqIQEMAwtB5wAhEAz/AgsDQAJAIAEtAABB8MSAgABqLQAAIhBBAUYNAAJAIBBBfmoOBNIB0wHUAQDVAQsgASEBQdcAIRAM5wILIAFBAWoiASACRw0AC0HoACEQDP4CCwJAIAEiASACRw0AQekAIRAM/gILAkAgAS0AACIQQXZqDhq6AdUB1QG8AdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAcoB1QHVAQDTAQsgAUEBaiEBC0EGIRAM4wILA0ACQCABLQAAQfDGgIAAai0AAEEBRg0AIAEhAQyeAgsgAUEBaiIBIAJHDQALQeoAIRAM+wILAkAgASIBIAJGDQAgAUEBaiEBDAMLQesAIRAM+gILAkAgASIBIAJHDQBB7AAhEAz6AgsgAUEBaiEBDAELAkAgASIBIAJHDQBB7QAhEAz5AgsgAUEBaiEBC0EEIRAM3gILAkAgASIUIAJHDQBB7gAhEAz3AgsgFCEBAkACQAJAIBQtAABB8MiAgABqLQAAQX9qDgfUAdUB1gEAnAIBAtcBCyAUQQFqIQEMCgsgFEEBaiEBDM0BC0EAIRAgAEEANgIcIABBm5KAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAz2AgsCQANAAkAgAS0AAEHwyICAAGotAAAiEEEERg0AAkACQCAQQX9qDgfSAdMB1AHZAQAEAdkBCyABIQFB2gAhEAzgAgsgAUEBaiEBQdwAIRAM3wILIAFBAWoiASACRw0AC0HvACEQDPYCCyABQQFqIQEMywELAkAgASIUIAJHDQBB8AAhEAz1AgsgFC0AAEEvRw3UASAUQQFqIQEMBgsCQCABIhQgAkcNAEHxACEQDPQCCwJAIBQtAAAiAUEvRw0AIBRBAWohAUHdACEQDNsCCyABQXZqIgRBFksN0wFBASAEdEGJgIACcUUN0wEMygILAkAgASIBIAJGDQAgAUEBaiEBQd4AIRAM2gILQfIAIRAM8gILAkAgASIUIAJHDQBB9AAhEAzyAgsgFCEBAkAgFC0AAEHwzICAAGotAABBf2oOA8kClAIA1AELQeEAIRAM2AILAkAgASIUIAJGDQADQAJAIBQtAABB8MqAgABqLQAAIgFBA0YNAAJAIAFBf2oOAssCANUBCyAUIQFB3wAhEAzaAgsgFEEBaiIUIAJHDQALQfMAIRAM8QILQfMAIRAM8AILAkAgASIBIAJGDQAgAEGPgICAADYCCCAAIAE2AgQgASEBQeAAIRAM1wILQfUAIRAM7wILAkAgASIBIAJHDQBB9gAhEAzvAgsgAEGPgICAADYCCCAAIAE2AgQgASEBC0EDIRAM1AILA0AgAS0AAEEgRw3DAiABQQFqIgEgAkcNAAtB9wAhEAzsAgsCQCABIgEgAkcNAEH4ACEQDOwCCyABLQAAQSBHDc4BIAFBAWohAQzvAQsgACABIgEgAhCsgICAACIQDc4BIAEhAQyOAgsCQCABIgQgAkcNAEH6ACEQDOoCCyAELQAAQcwARw3RASAEQQFqIQFBEyEQDM8BCwJAIAEiBCACRw0AQfsAIRAM6QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEANAIAQtAAAgAUHwzoCAAGotAABHDdABIAFBBUYNzgEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBB+wAhEAzoAgsCQCABIgQgAkcNAEH8ACEQDOgCCwJAAkAgBC0AAEG9f2oODADRAdEB0QHRAdEB0QHRAdEB0QHRAQHRAQsgBEEBaiEBQeYAIRAMzwILIARBAWohAUHnACEQDM4CCwJAIAEiBCACRw0AQf0AIRAM5wILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNzwEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf0AIRAM5wILIABBADYCACAQQQFqIQFBECEQDMwBCwJAIAEiBCACRw0AQf4AIRAM5gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQfbOgIAAai0AAEcNzgEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf4AIRAM5gILIABBADYCACAQQQFqIQFBFiEQDMsBCwJAIAEiBCACRw0AQf8AIRAM5QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQfzOgIAAai0AAEcNzQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf8AIRAM5QILIABBADYCACAQQQFqIQFBBSEQDMoBCwJAIAEiBCACRw0AQYABIRAM5AILIAQtAABB2QBHDcsBIARBAWohAUEIIRAMyQELAkAgASIEIAJHDQBBgQEhEAzjAgsCQAJAIAQtAABBsn9qDgMAzAEBzAELIARBAWohAUHrACEQDMoCCyAEQQFqIQFB7AAhEAzJAgsCQCABIgQgAkcNAEGCASEQDOICCwJAAkAgBC0AAEG4f2oOCADLAcsBywHLAcsBywEBywELIARBAWohAUHqACEQDMkCCyAEQQFqIQFB7QAhEAzIAgsCQCABIgQgAkcNAEGDASEQDOECCyACIARrIAAoAgAiAWohECAEIAFrQQJqIRQCQANAIAQtAAAgAUGAz4CAAGotAABHDckBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgEDYCAEGDASEQDOECC0EAIRAgAEEANgIAIBRBAWohAQzGAQsCQCABIgQgAkcNAEGEASEQDOACCyACIARrIAAoAgAiAWohFCAEIAFrQQRqIRACQANAIAQtAAAgAUGDz4CAAGotAABHDcgBIAFBBEYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGEASEQDOACCyAAQQA2AgAgEEEBaiEBQSMhEAzFAQsCQCABIgQgAkcNAEGFASEQDN8CCwJAAkAgBC0AAEG0f2oOCADIAcgByAHIAcgByAEByAELIARBAWohAUHvACEQDMYCCyAEQQFqIQFB8AAhEAzFAgsCQCABIgQgAkcNAEGGASEQDN4CCyAELQAAQcUARw3FASAEQQFqIQEMgwILAkAgASIEIAJHDQBBhwEhEAzdAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBiM+AgABqLQAARw3FASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhwEhEAzdAgsgAEEANgIAIBBBAWohAUEtIRAMwgELAkAgASIEIAJHDQBBiAEhEAzcAgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw3EASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiAEhEAzcAgsgAEEANgIAIBBBAWohAUEpIRAMwQELAkAgASIBIAJHDQBBiQEhEAzbAgtBASEQIAEtAABB3wBHDcABIAFBAWohAQyBAgsCQCABIgQgAkcNAEGKASEQDNoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRADQCAELQAAIAFBjM+AgABqLQAARw3BASABQQFGDa8CIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYoBIRAM2QILAkAgASIEIAJHDQBBiwEhEAzZAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBjs+AgABqLQAARw3BASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiwEhEAzZAgsgAEEANgIAIBBBAWohAUECIRAMvgELAkAgASIEIAJHDQBBjAEhEAzYAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw3AASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjAEhEAzYAgsgAEEANgIAIBBBAWohAUEfIRAMvQELAkAgASIEIAJHDQBBjQEhEAzXAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8s+AgABqLQAARw2/ASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjQEhEAzXAgsgAEEANgIAIBBBAWohAUEJIRAMvAELAkAgASIEIAJHDQBBjgEhEAzWAgsCQAJAIAQtAABBt39qDgcAvwG/Ab8BvwG/AQG/AQsgBEEBaiEBQfgAIRAMvQILIARBAWohAUH5ACEQDLwCCwJAIAEiBCACRw0AQY8BIRAM1QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQZHPgIAAai0AAEcNvQEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY8BIRAM1QILIABBADYCACAQQQFqIQFBGCEQDLoBCwJAIAEiBCACRw0AQZABIRAM1AILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQZfPgIAAai0AAEcNvAEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZABIRAM1AILIABBADYCACAQQQFqIQFBFyEQDLkBCwJAIAEiBCACRw0AQZEBIRAM0wILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQZrPgIAAai0AAEcNuwEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZEBIRAM0wILIABBADYCACAQQQFqIQFBFSEQDLgBCwJAIAEiBCACRw0AQZIBIRAM0gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQaHPgIAAai0AAEcNugEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZIBIRAM0gILIABBADYCACAQQQFqIQFBHiEQDLcBCwJAIAEiBCACRw0AQZMBIRAM0QILIAQtAABBzABHDbgBIARBAWohAUEKIRAMtgELAkAgBCACRw0AQZQBIRAM0AILAkACQCAELQAAQb9/ag4PALkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AbkBAbkBCyAEQQFqIQFB/gAhEAy3AgsgBEEBaiEBQf8AIRAMtgILAkAgBCACRw0AQZUBIRAMzwILAkACQCAELQAAQb9/ag4DALgBAbgBCyAEQQFqIQFB/QAhEAy2AgsgBEEBaiEEQYABIRAMtQILAkAgBCACRw0AQZYBIRAMzgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQafPgIAAai0AAEcNtgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZYBIRAMzgILIABBADYCACAQQQFqIQFBCyEQDLMBCwJAIAQgAkcNAEGXASEQDM0CCwJAAkACQAJAIAQtAABBU2oOIwC4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBAbgBuAG4AbgBuAECuAG4AbgBA7gBCyAEQQFqIQFB+wAhEAy2AgsgBEEBaiEBQfwAIRAMtQILIARBAWohBEGBASEQDLQCCyAEQQFqIQRBggEhEAyzAgsCQCAEIAJHDQBBmAEhEAzMAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBqc+AgABqLQAARw20ASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmAEhEAzMAgsgAEEANgIAIBBBAWohAUEZIRAMsQELAkAgBCACRw0AQZkBIRAMywILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQa7PgIAAai0AAEcNswEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZkBIRAMywILIABBADYCACAQQQFqIQFBBiEQDLABCwJAIAQgAkcNAEGaASEQDMoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG0z4CAAGotAABHDbIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGaASEQDMoCCyAAQQA2AgAgEEEBaiEBQRwhEAyvAQsCQCAEIAJHDQBBmwEhEAzJAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBts+AgABqLQAARw2xASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmwEhEAzJAgsgAEEANgIAIBBBAWohAUEnIRAMrgELAkAgBCACRw0AQZwBIRAMyAILAkACQCAELQAAQax/ag4CAAGxAQsgBEEBaiEEQYYBIRAMrwILIARBAWohBEGHASEQDK4CCwJAIAQgAkcNAEGdASEQDMcCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG4z4CAAGotAABHDa8BIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGdASEQDMcCCyAAQQA2AgAgEEEBaiEBQSYhEAysAQsCQCAEIAJHDQBBngEhEAzGAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBus+AgABqLQAARw2uASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBngEhEAzGAgsgAEEANgIAIBBBAWohAUEDIRAMqwELAkAgBCACRw0AQZ8BIRAMxQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNrQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ8BIRAMxQILIABBADYCACAQQQFqIQFBDCEQDKoBCwJAIAQgAkcNAEGgASEQDMQCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUG8z4CAAGotAABHDawBIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGgASEQDMQCCyAAQQA2AgAgEEEBaiEBQQ0hEAypAQsCQCAEIAJHDQBBoQEhEAzDAgsCQAJAIAQtAABBun9qDgsArAGsAawBrAGsAawBrAGsAawBAawBCyAEQQFqIQRBiwEhEAyqAgsgBEEBaiEEQYwBIRAMqQILAkAgBCACRw0AQaIBIRAMwgILIAQtAABB0ABHDakBIARBAWohBAzpAQsCQCAEIAJHDQBBowEhEAzBAgsCQAJAIAQtAABBt39qDgcBqgGqAaoBqgGqAQCqAQsgBEEBaiEEQY4BIRAMqAILIARBAWohAUEiIRAMpgELAkAgBCACRw0AQaQBIRAMwAILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQcDPgIAAai0AAEcNqAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaQBIRAMwAILIABBADYCACAQQQFqIQFBHSEQDKUBCwJAIAQgAkcNAEGlASEQDL8CCwJAAkAgBC0AAEGuf2oOAwCoAQGoAQsgBEEBaiEEQZABIRAMpgILIARBAWohAUEEIRAMpAELAkAgBCACRw0AQaYBIRAMvgILAkACQAJAAkACQCAELQAAQb9/ag4VAKoBqgGqAaoBqgGqAaoBqgGqAaoBAaoBqgECqgGqAQOqAaoBBKoBCyAEQQFqIQRBiAEhEAyoAgsgBEEBaiEEQYkBIRAMpwILIARBAWohBEGKASEQDKYCCyAEQQFqIQRBjwEhEAylAgsgBEEBaiEEQZEBIRAMpAILAkAgBCACRw0AQacBIRAMvQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNpQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQacBIRAMvQILIABBADYCACAQQQFqIQFBESEQDKIBCwJAIAQgAkcNAEGoASEQDLwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHCz4CAAGotAABHDaQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGoASEQDLwCCyAAQQA2AgAgEEEBaiEBQSwhEAyhAQsCQCAEIAJHDQBBqQEhEAy7AgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBxc+AgABqLQAARw2jASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqQEhEAy7AgsgAEEANgIAIBBBAWohAUErIRAMoAELAkAgBCACRw0AQaoBIRAMugILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQcrPgIAAai0AAEcNogEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaoBIRAMugILIABBADYCACAQQQFqIQFBFCEQDJ8BCwJAIAQgAkcNAEGrASEQDLkCCwJAAkACQAJAIAQtAABBvn9qDg8AAQKkAaQBpAGkAaQBpAGkAaQBpAGkAaQBA6QBCyAEQQFqIQRBkwEhEAyiAgsgBEEBaiEEQZQBIRAMoQILIARBAWohBEGVASEQDKACCyAEQQFqIQRBlgEhEAyfAgsCQCAEIAJHDQBBrAEhEAy4AgsgBC0AAEHFAEcNnwEgBEEBaiEEDOABCwJAIAQgAkcNAEGtASEQDLcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHNz4CAAGotAABHDZ8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGtASEQDLcCCyAAQQA2AgAgEEEBaiEBQQ4hEAycAQsCQCAEIAJHDQBBrgEhEAy2AgsgBC0AAEHQAEcNnQEgBEEBaiEBQSUhEAybAQsCQCAEIAJHDQBBrwEhEAy1AgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw2dASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrwEhEAy1AgsgAEEANgIAIBBBAWohAUEqIRAMmgELAkAgBCACRw0AQbABIRAMtAILAkACQCAELQAAQat/ag4LAJ0BnQGdAZ0BnQGdAZ0BnQGdAQGdAQsgBEEBaiEEQZoBIRAMmwILIARBAWohBEGbASEQDJoCCwJAIAQgAkcNAEGxASEQDLMCCwJAAkAgBC0AAEG/f2oOFACcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAEBnAELIARBAWohBEGZASEQDJoCCyAEQQFqIQRBnAEhEAyZAgsCQCAEIAJHDQBBsgEhEAyyAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFB2c+AgABqLQAARw2aASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBsgEhEAyyAgsgAEEANgIAIBBBAWohAUEhIRAMlwELAkAgBCACRw0AQbMBIRAMsQILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQd3PgIAAai0AAEcNmQEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbMBIRAMsQILIABBADYCACAQQQFqIQFBGiEQDJYBCwJAIAQgAkcNAEG0ASEQDLACCwJAAkACQCAELQAAQbt/ag4RAJoBmgGaAZoBmgGaAZoBmgGaAQGaAZoBmgGaAZoBApoBCyAEQQFqIQRBnQEhEAyYAgsgBEEBaiEEQZ4BIRAMlwILIARBAWohBEGfASEQDJYCCwJAIAQgAkcNAEG1ASEQDK8CCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUHkz4CAAGotAABHDZcBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG1ASEQDK8CCyAAQQA2AgAgEEEBaiEBQSghEAyUAQsCQCAEIAJHDQBBtgEhEAyuAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB6s+AgABqLQAARw2WASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtgEhEAyuAgsgAEEANgIAIBBBAWohAUEHIRAMkwELAkAgBCACRw0AQbcBIRAMrQILAkACQCAELQAAQbt/ag4OAJYBlgGWAZYBlgGWAZYBlgGWAZYBlgGWAQGWAQsgBEEBaiEEQaEBIRAMlAILIARBAWohBEGiASEQDJMCCwJAIAQgAkcNAEG4ASEQDKwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDZQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG4ASEQDKwCCyAAQQA2AgAgEEEBaiEBQRIhEAyRAQsCQCAEIAJHDQBBuQEhEAyrAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw2TASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuQEhEAyrAgsgAEEANgIAIBBBAWohAUEgIRAMkAELAkAgBCACRw0AQboBIRAMqgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNkgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQboBIRAMqgILIABBADYCACAQQQFqIQFBDyEQDI8BCwJAIAQgAkcNAEG7ASEQDKkCCwJAAkAgBC0AAEG3f2oOBwCSAZIBkgGSAZIBAZIBCyAEQQFqIQRBpQEhEAyQAgsgBEEBaiEEQaYBIRAMjwILAkAgBCACRw0AQbwBIRAMqAILIAIgBGsgACgCACIBaiEUIAQgAWtBB2ohEAJAA0AgBC0AACABQfTPgIAAai0AAEcNkAEgAUEHRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbwBIRAMqAILIABBADYCACAQQQFqIQFBGyEQDI0BCwJAIAQgAkcNAEG9ASEQDKcCCwJAAkACQCAELQAAQb5/ag4SAJEBkQGRAZEBkQGRAZEBkQGRAQGRAZEBkQGRAZEBkQECkQELIARBAWohBEGkASEQDI8CCyAEQQFqIQRBpwEhEAyOAgsgBEEBaiEEQagBIRAMjQILAkAgBCACRw0AQb4BIRAMpgILIAQtAABBzgBHDY0BIARBAWohBAzPAQsCQCAEIAJHDQBBvwEhEAylAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAELQAAQb9/ag4VAAECA5wBBAUGnAGcAZwBBwgJCgucAQwNDg+cAQsgBEEBaiEBQegAIRAMmgILIARBAWohAUHpACEQDJkCCyAEQQFqIQFB7gAhEAyYAgsgBEEBaiEBQfIAIRAMlwILIARBAWohAUHzACEQDJYCCyAEQQFqIQFB9gAhEAyVAgsgBEEBaiEBQfcAIRAMlAILIARBAWohAUH6ACEQDJMCCyAEQQFqIQRBgwEhEAySAgsgBEEBaiEEQYQBIRAMkQILIARBAWohBEGFASEQDJACCyAEQQFqIQRBkgEhEAyPAgsgBEEBaiEEQZgBIRAMjgILIARBAWohBEGgASEQDI0CCyAEQQFqIQRBowEhEAyMAgsgBEEBaiEEQaoBIRAMiwILAkAgBCACRg0AIABBkICAgAA2AgggACAENgIEQasBIRAMiwILQcABIRAMowILIAAgBSACEKqAgIAAIgENiwEgBSEBDFwLAkAgBiACRg0AIAZBAWohBQyNAQtBwgEhEAyhAgsDQAJAIBAtAABBdmoOBIwBAACPAQALIBBBAWoiECACRw0AC0HDASEQDKACCwJAIAcgAkYNACAAQZGAgIAANgIIIAAgBzYCBCAHIQFBASEQDIcCC0HEASEQDJ8CCwJAIAcgAkcNAEHFASEQDJ8CCwJAAkAgBy0AAEF2ag4EAc4BzgEAzgELIAdBAWohBgyNAQsgB0EBaiEFDIkBCwJAIAcgAkcNAEHGASEQDJ4CCwJAAkAgBy0AAEF2ag4XAY8BjwEBjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAI8BCyAHQQFqIQcLQbABIRAMhAILAkAgCCACRw0AQcgBIRAMnQILIAgtAABBIEcNjQEgAEEAOwEyIAhBAWohAUGzASEQDIMCCyABIRcCQANAIBciByACRg0BIActAABBUGpB/wFxIhBBCk8NzAECQCAALwEyIhRBmTNLDQAgACAUQQpsIhQ7ATIgEEH//wNzIBRB/v8DcUkNACAHQQFqIRcgACAUIBBqIhA7ATIgEEH//wNxQegHSQ0BCwtBACEQIABBADYCHCAAQcGJgIAANgIQIABBDTYCDCAAIAdBAWo2AhQMnAILQccBIRAMmwILIAAgCCACEK6AgIAAIhBFDcoBIBBBFUcNjAEgAEHIATYCHCAAIAg2AhQgAEHJl4CAADYCECAAQRU2AgxBACEQDJoCCwJAIAkgAkcNAEHMASEQDJoCC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgCS0AAEFQag4KlgGVAQABAgMEBQYIlwELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMjgELQQkhEEEBIRRBACEXQQAhFgyNAQsCQCAKIAJHDQBBzgEhEAyZAgsgCi0AAEEuRw2OASAKQQFqIQkMygELIAsgAkcNjgFB0AEhEAyXAgsCQCALIAJGDQAgAEGOgICAADYCCCAAIAs2AgRBtwEhEAz+AQtB0QEhEAyWAgsCQCAEIAJHDQBB0gEhEAyWAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EEaiELA0AgBC0AACAQQfzPgIAAai0AAEcNjgEgEEEERg3pASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHSASEQDJUCCyAAIAwgAhCsgICAACIBDY0BIAwhAQy4AQsCQCAEIAJHDQBB1AEhEAyUAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EBaiEMA0AgBC0AACAQQYHQgIAAai0AAEcNjwEgEEEBRg2OASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHUASEQDJMCCwJAIAQgAkcNAEHWASEQDJMCCyACIARrIAAoAgAiEGohFCAEIBBrQQJqIQsDQCAELQAAIBBBg9CAgABqLQAARw2OASAQQQJGDZABIBBBAWohECAEQQFqIgQgAkcNAAsgACAUNgIAQdYBIRAMkgILAkAgBCACRw0AQdcBIRAMkgILAkACQCAELQAAQbt/ag4QAI8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwEBjwELIARBAWohBEG7ASEQDPkBCyAEQQFqIQRBvAEhEAz4AQsCQCAEIAJHDQBB2AEhEAyRAgsgBC0AAEHIAEcNjAEgBEEBaiEEDMQBCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEG+ASEQDPcBC0HZASEQDI8CCwJAIAQgAkcNAEHaASEQDI8CCyAELQAAQcgARg3DASAAQQE6ACgMuQELIABBAjoALyAAIAQgAhCmgICAACIQDY0BQcIBIRAM9AELIAAtAChBf2oOArcBuQG4AQsDQAJAIAQtAABBdmoOBACOAY4BAI4BCyAEQQFqIgQgAkcNAAtB3QEhEAyLAgsgAEEAOgAvIAAtAC1BBHFFDYQCCyAAQQA6AC8gAEEBOgA0IAEhAQyMAQsgEEEVRg3aASAAQQA2AhwgACABNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAyIAgsCQCAAIBAgAhC0gICAACIEDQAgECEBDIECCwJAIARBFUcNACAAQQM2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAyIAgsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMhwILIBBBFUYN1gEgAEEANgIcIAAgATYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMhgILIAAoAgQhFyAAQQA2AgQgECARp2oiFiEBIAAgFyAQIBYgFBsiEBC1gICAACIURQ2NASAAQQc2AhwgACAQNgIUIAAgFDYCDEEAIRAMhQILIAAgAC8BMEGAAXI7ATAgASEBC0EqIRAM6gELIBBBFUYN0QEgAEEANgIcIAAgATYCFCAAQYOMgIAANgIQIABBEzYCDEEAIRAMggILIBBBFUYNzwEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAMgQILIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDI0BCyAAQQw2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMgAILIBBBFUYNzAEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM/wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIwBCyAAQQ02AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/gELIBBBFUYNyQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM/QELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIsBCyAAQQ42AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/AELIABBADYCHCAAIAE2AhQgAEHAlYCAADYCECAAQQI2AgxBACEQDPsBCyAQQRVGDcUBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPoBCyAAQRA2AhwgACABNgIUIAAgEDYCDEEAIRAM+QELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDPEBCyAAQRE2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM+AELIBBBFUYNwQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM9wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIgBCyAAQRM2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM9gELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDO0BCyAAQRQ2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM9QELIBBBFUYNvQEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM9AELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIYBCyAAQRY2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM8wELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC3gICAACIEDQAgAUEBaiEBDOkBCyAAQRc2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM8gELIABBADYCHCAAIAE2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDPEBC0IBIRELIBBBAWohAQJAIAApAyAiEkL//////////w9WDQAgACASQgSGIBGENwMgIAEhAQyEAQsgAEEANgIcIAAgATYCFCAAQa2JgIAANgIQIABBDDYCDEEAIRAM7wELIABBADYCHCAAIBA2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDO4BCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNcyAAQQU2AhwgACAQNgIUIAAgFDYCDEEAIRAM7QELIABBADYCHCAAIBA2AhQgAEGqnICAADYCECAAQQ82AgxBACEQDOwBCyAAIBAgAhC0gICAACIBDQEgECEBC0EOIRAM0QELAkAgAUEVRw0AIABBAjYCHCAAIBA2AhQgAEGwmICAADYCECAAQRU2AgxBACEQDOoBCyAAQQA2AhwgACAQNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAzpAQsgAUEBaiEQAkAgAC8BMCIBQYABcUUNAAJAIAAgECACELuAgIAAIgENACAQIQEMcAsgAUEVRw26ASAAQQU2AhwgACAQNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAzpAQsCQCABQaAEcUGgBEcNACAALQAtQQJxDQAgAEEANgIcIAAgEDYCFCAAQZaTgIAANgIQIABBBDYCDEEAIRAM6QELIAAgECACEL2AgIAAGiAQIQECQAJAAkACQAJAIAAgECACELOAgIAADhYCAQAEBAQEBAQEBAQEBAQEBAQEBAQDBAsgAEEBOgAuCyAAIAAvATBBwAByOwEwIBAhAQtBJiEQDNEBCyAAQSM2AhwgACAQNgIUIABBpZaAgAA2AhAgAEEVNgIMQQAhEAzpAQsgAEEANgIcIAAgEDYCFCAAQdWLgIAANgIQIABBETYCDEEAIRAM6AELIAAtAC1BAXFFDQFBwwEhEAzOAQsCQCANIAJGDQADQAJAIA0tAABBIEYNACANIQEMxAELIA1BAWoiDSACRw0AC0ElIRAM5wELQSUhEAzmAQsgACgCBCEEIABBADYCBCAAIAQgDRCvgICAACIERQ2tASAAQSY2AhwgACAENgIMIAAgDUEBajYCFEEAIRAM5QELIBBBFUYNqwEgAEEANgIcIAAgATYCFCAAQf2NgIAANgIQIABBHTYCDEEAIRAM5AELIABBJzYCHCAAIAE2AhQgACAQNgIMQQAhEAzjAQsgECEBQQEhFAJAAkACQAJAAkACQAJAIAAtACxBfmoOBwYFBQMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0ErIRAMygELIABBADYCHCAAIBA2AhQgAEGrkoCAADYCECAAQQs2AgxBACEQDOIBCyAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMQQAhEAzhAQsgAEEAOgAsIBAhAQy9AQsgECEBQQEhFAJAAkACQAJAAkAgAC0ALEF7ag4EAwECAAULIAAgAC8BMEEIcjsBMAwDC0ECIRQMAQtBBCEUCyAAQQE6ACwgACAALwEwIBRyOwEwCyAQIQELQSkhEAzFAQsgAEEANgIcIAAgATYCFCAAQfCUgIAANgIQIABBAzYCDEEAIRAM3QELAkAgDi0AAEENRw0AIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHULIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzdAQsgAC0ALUEBcUUNAUHEASEQDMMBCwJAIA4gAkcNAEEtIRAM3AELAkACQANAAkAgDi0AAEF2ag4EAgAAAwALIA5BAWoiDiACRw0AC0EtIRAM3QELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDiEBDHQLIABBLDYCHCAAIA42AhQgACABNgIMQQAhEAzcAQsgACgCBCEBIABBADYCBAJAIAAgASAOELGAgIAAIgENACAOQQFqIQEMcwsgAEEsNgIcIAAgATYCDCAAIA5BAWo2AhRBACEQDNsBCyAAKAIEIQQgAEEANgIEIAAgBCAOELGAgIAAIgQNoAEgDiEBDM4BCyAQQSxHDQEgAUEBaiEQQQEhAQJAAkACQAJAAkAgAC0ALEF7ag4EAwECBAALIBAhAQwEC0ECIQEMAQtBBCEBCyAAQQE6ACwgACAALwEwIAFyOwEwIBAhAQwBCyAAIAAvATBBCHI7ATAgECEBC0E5IRAMvwELIABBADoALCABIQELQTQhEAy9AQsgACAALwEwQSByOwEwIAEhAQwCCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBA0AIAEhAQzHAQsgAEE3NgIcIAAgATYCFCAAIAQ2AgxBACEQDNQBCyAAQQg6ACwgASEBC0EwIRAMuQELAkAgAC0AKEEBRg0AIAEhAQwECyAALQAtQQhxRQ2TASABIQEMAwsgAC0AMEEgcQ2UAUHFASEQDLcBCwJAIA8gAkYNAAJAA0ACQCAPLQAAQVBqIgFB/wFxQQpJDQAgDyEBQTUhEAy6AQsgACkDICIRQpmz5syZs+bMGVYNASAAIBFCCn4iETcDICARIAGtQv8BgyISQn+FVg0BIAAgESASfDcDICAPQQFqIg8gAkcNAAtBOSEQDNEBCyAAKAIEIQIgAEEANgIEIAAgAiAPQQFqIgQQsYCAgAAiAg2VASAEIQEMwwELQTkhEAzPAQsCQCAALwEwIgFBCHFFDQAgAC0AKEEBRw0AIAAtAC1BCHFFDZABCyAAIAFB9/sDcUGABHI7ATAgDyEBC0E3IRAMtAELIAAgAC8BMEEQcjsBMAyrAQsgEEEVRg2LASAAQQA2AhwgACABNgIUIABB8I6AgAA2AhAgAEEcNgIMQQAhEAzLAQsgAEHDADYCHCAAIAE2AgwgACANQQFqNgIUQQAhEAzKAQsCQCABLQAAQTpHDQAgACgCBCEQIABBADYCBAJAIAAgECABEK+AgIAAIhANACABQQFqIQEMYwsgAEHDADYCHCAAIBA2AgwgACABQQFqNgIUQQAhEAzKAQsgAEEANgIcIAAgATYCFCAAQbGRgIAANgIQIABBCjYCDEEAIRAMyQELIABBADYCHCAAIAE2AhQgAEGgmYCAADYCECAAQR42AgxBACEQDMgBCyAAQQA2AgALIABBgBI7ASogACAXQQFqIgEgAhCogICAACIQDQEgASEBC0HHACEQDKwBCyAQQRVHDYMBIABB0QA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAzEAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAzDAQsgAEEANgIcIAAgFDYCFCAAQcGogIAANgIQIABBBzYCDCAAQQA2AgBBACEQDMIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxdCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDMEBC0EAIRAgAEEANgIcIAAgATYCFCAAQYCRgIAANgIQIABBCTYCDAzAAQsgEEEVRg19IABBADYCHCAAIAE2AhQgAEGUjYCAADYCECAAQSE2AgxBACEQDL8BC0EBIRZBACEXQQAhFEEBIRALIAAgEDoAKyABQQFqIQECQAJAIAAtAC1BEHENAAJAAkACQCAALQAqDgMBAAIECyAWRQ0DDAILIBQNAQwCCyAXRQ0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQrYCAgAAiEA0AIAEhAQxcCyAAQdgANgIcIAAgATYCFCAAIBA2AgxBACEQDL4BCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQytAQsgAEHZADYCHCAAIAE2AhQgACAENgIMQQAhEAy9AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMqwELIABB2gA2AhwgACABNgIUIAAgBDYCDEEAIRAMvAELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKkBCyAAQdwANgIcIAAgATYCFCAAIAQ2AgxBACEQDLsBCwJAIAEtAABBUGoiEEH/AXFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHSADYCHCAAIBQ2AhQgACABNgIMQQAhEAykAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHTADYCHCAAIBQ2AhQgACABNgIMQQAhEAyjAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMQwsgAEHlADYCHCAAIBQ2AhQgACABNgIMQQAhEAyiAQsgAEEANgIcIAAgFDYCFCAAQcOPgIAANgIQIABBBzYCDEEAIRAMoQELIABBADYCHCAAIAE2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKABC0EAIRAgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDAyfAQsgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDEEAIRAMngELIABBADYCHCAAIBQ2AhQgAEH+kYCAADYCECAAQQc2AgxBACEQDJ0BCyAAQQA2AhwgACABNgIUIABBjpuAgAA2AhAgAEEGNgIMQQAhEAycAQsgEEEVRg1XIABBADYCHCAAIAE2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDJsBCyAAQQA2AgAgEEEBaiEBQSQhEAsgACAQOgApIAAoAgQhECAAQQA2AgQgACAQIAEQq4CAgAAiEA1UIAEhAQw+CyAAQQA2AgALQQAhECAAQQA2AhwgACAENgIUIABB8ZuAgAA2AhAgAEEGNgIMDJcBCyABQRVGDVAgAEEANgIcIAAgBTYCFCAAQfCMgIAANgIQIABBGzYCDEEAIRAMlgELIAAoAgQhBSAAQQA2AgQgACAFIBAQqYCAgAAiBQ0BIBBBAWohBQtBrQEhEAx7CyAAQcEBNgIcIAAgBTYCDCAAIBBBAWo2AhRBACEQDJMBCyAAKAIEIQYgAEEANgIEIAAgBiAQEKmAgIAAIgYNASAQQQFqIQYLQa4BIRAMeAsgAEHCATYCHCAAIAY2AgwgACAQQQFqNgIUQQAhEAyQAQsgAEEANgIcIAAgBzYCFCAAQZeLgIAANgIQIABBDTYCDEEAIRAMjwELIABBADYCHCAAIAg2AhQgAEHjkICAADYCECAAQQk2AgxBACEQDI4BCyAAQQA2AhwgACAINgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAyNAQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgCUEBaiEIAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBCAAIBAgCBCtgICAACIQRQ09IABByQE2AhwgACAINgIUIAAgEDYCDEEAIRAMjAELIAAoAgQhBCAAQQA2AgQgACAEIAgQrYCAgAAiBEUNdiAAQcoBNgIcIAAgCDYCFCAAIAQ2AgxBACEQDIsBCyAAKAIEIQQgAEEANgIEIAAgBCAJEK2AgIAAIgRFDXQgAEHLATYCHCAAIAk2AhQgACAENgIMQQAhEAyKAQsgACgCBCEEIABBADYCBCAAIAQgChCtgICAACIERQ1yIABBzQE2AhwgACAKNgIUIAAgBDYCDEEAIRAMiQELAkAgCy0AAEFQaiIQQf8BcUEKTw0AIAAgEDoAKiALQQFqIQpBtgEhEAxwCyAAKAIEIQQgAEEANgIEIAAgBCALEK2AgIAAIgRFDXAgAEHPATYCHCAAIAs2AhQgACAENgIMQQAhEAyIAQsgAEEANgIcIAAgBDYCFCAAQZCzgIAANgIQIABBCDYCDCAAQQA2AgBBACEQDIcBCyABQRVGDT8gAEEANgIcIAAgDDYCFCAAQcyOgIAANgIQIABBIDYCDEEAIRAMhgELIABBgQQ7ASggACgCBCEQIABCADcDACAAIBAgDEEBaiIMEKuAgIAAIhBFDTggAEHTATYCHCAAIAw2AhQgACAQNgIMQQAhEAyFAQsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQdibgIAANgIQIABBCDYCDAyDAQsgACgCBCEQIABCADcDACAAIBAgC0EBaiILEKuAgIAAIhANAUHGASEQDGkLIABBAjoAKAxVCyAAQdUBNgIcIAAgCzYCFCAAIBA2AgxBACEQDIABCyAQQRVGDTcgAEEANgIcIAAgBDYCFCAAQaSMgIAANgIQIABBEDYCDEEAIRAMfwsgAC0ANEEBRw00IAAgBCACELyAgIAAIhBFDTQgEEEVRw01IABB3AE2AhwgACAENgIUIABB1ZaAgAA2AhAgAEEVNgIMQQAhEAx+C0EAIRAgAEEANgIcIABBr4uAgAA2AhAgAEECNgIMIAAgFEEBajYCFAx9C0EAIRAMYwtBAiEQDGILQQ0hEAxhC0EPIRAMYAtBJSEQDF8LQRMhEAxeC0EVIRAMXQtBFiEQDFwLQRchEAxbC0EYIRAMWgtBGSEQDFkLQRohEAxYC0EbIRAMVwtBHCEQDFYLQR0hEAxVC0EfIRAMVAtBISEQDFMLQSMhEAxSC0HGACEQDFELQS4hEAxQC0EvIRAMTwtBOyEQDE4LQT0hEAxNC0HIACEQDEwLQckAIRAMSwtBywAhEAxKC0HMACEQDEkLQc4AIRAMSAtB0QAhEAxHC0HVACEQDEYLQdgAIRAMRQtB2QAhEAxEC0HbACEQDEMLQeQAIRAMQgtB5QAhEAxBC0HxACEQDEALQfQAIRAMPwtBjQEhEAw+C0GXASEQDD0LQakBIRAMPAtBrAEhEAw7C0HAASEQDDoLQbkBIRAMOQtBrwEhEAw4C0GxASEQDDcLQbIBIRAMNgtBtAEhEAw1C0G1ASEQDDQLQboBIRAMMwtBvQEhEAwyC0G/ASEQDDELQcEBIRAMMAsgAEEANgIcIAAgBDYCFCAAQemLgIAANgIQIABBHzYCDEEAIRAMSAsgAEHbATYCHCAAIAQ2AhQgAEH6loCAADYCECAAQRU2AgxBACEQDEcLIABB+AA2AhwgACAMNgIUIABBypiAgAA2AhAgAEEVNgIMQQAhEAxGCyAAQdEANgIcIAAgBTYCFCAAQbCXgIAANgIQIABBFTYCDEEAIRAMRQsgAEH5ADYCHCAAIAE2AhQgACAQNgIMQQAhEAxECyAAQfgANgIcIAAgATYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMQwsgAEHkADYCHCAAIAE2AhQgAEHjl4CAADYCECAAQRU2AgxBACEQDEILIABB1wA2AhwgACABNgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAxBCyAAQQA2AhwgACABNgIUIABBuY2AgAA2AhAgAEEaNgIMQQAhEAxACyAAQcIANgIcIAAgATYCFCAAQeOYgIAANgIQIABBFTYCDEEAIRAMPwsgAEEANgIEIAAgDyAPELGAgIAAIgRFDQEgAEE6NgIcIAAgBDYCDCAAIA9BAWo2AhRBACEQDD4LIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCxgICAACIERQ0AIABBOzYCHCAAIAQ2AgwgACABQQFqNgIUQQAhEAw+CyABQQFqIQEMLQsgD0EBaiEBDC0LIABBADYCHCAAIA82AhQgAEHkkoCAADYCECAAQQQ2AgxBACEQDDsLIABBNjYCHCAAIAQ2AhQgACACNgIMQQAhEAw6CyAAQS42AhwgACAONgIUIAAgBDYCDEEAIRAMOQsgAEHQADYCHCAAIAE2AhQgAEGRmICAADYCECAAQRU2AgxBACEQDDgLIA1BAWohAQwsCyAAQRU2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAw2CyAAQRs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw1CyAAQQ82AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw0CyAAQQs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAwzCyAAQRo2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwyCyAAQQs2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwxCyAAQQo2AhwgACABNgIUIABB5JaAgAA2AhAgAEEVNgIMQQAhEAwwCyAAQR42AhwgACABNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAwvCyAAQQA2AhwgACAQNgIUIABB2o2AgAA2AhAgAEEUNgIMQQAhEAwuCyAAQQQ2AhwgACABNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAwtCyAAQQA2AgAgC0EBaiELC0G4ASEQDBILIABBADYCACAQQQFqIQFB9QAhEAwRCyABIQECQCAALQApQQVHDQBB4wAhEAwRC0HiACEQDBALQQAhECAAQQA2AhwgAEHkkYCAADYCECAAQQc2AgwgACAUQQFqNgIUDCgLIABBADYCACAXQQFqIQFBwAAhEAwOC0EBIQELIAAgAToALCAAQQA2AgAgF0EBaiEBC0EoIRAMCwsgASEBC0E4IRAMCQsCQCABIg8gAkYNAANAAkAgDy0AAEGAvoCAAGotAAAiAUEBRg0AIAFBAkcNAyAPQQFqIQEMBAsgD0EBaiIPIAJHDQALQT4hEAwiC0E+IRAMIQsgAEEAOgAsIA8hAQwBC0ELIRAMBgtBOiEQDAULIAFBAWohAUEtIRAMBAsgACABOgAsIABBADYCACAWQQFqIQFBDCEQDAMLIABBADYCACAXQQFqIQFBCiEQDAILIABBADYCAAsgAEEAOgAsIA0hAUEJIRAMAAsLQQAhECAAQQA2AhwgACALNgIUIABBzZCAgAA2AhAgAEEJNgIMDBcLQQAhECAAQQA2AhwgACAKNgIUIABB6YqAgAA2AhAgAEEJNgIMDBYLQQAhECAAQQA2AhwgACAJNgIUIABBt5CAgAA2AhAgAEEJNgIMDBULQQAhECAAQQA2AhwgACAINgIUIABBnJGAgAA2AhAgAEEJNgIMDBQLQQAhECAAQQA2AhwgACABNgIUIABBzZCAgAA2AhAgAEEJNgIMDBMLQQAhECAAQQA2AhwgACABNgIUIABB6YqAgAA2AhAgAEEJNgIMDBILQQAhECAAQQA2AhwgACABNgIUIABBt5CAgAA2AhAgAEEJNgIMDBELQQAhECAAQQA2AhwgACABNgIUIABBnJGAgAA2AhAgAEEJNgIMDBALQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA8LQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA4LQQAhECAAQQA2AhwgACABNgIUIABBwJKAgAA2AhAgAEELNgIMDA0LQQAhECAAQQA2AhwgACABNgIUIABBlYmAgAA2AhAgAEELNgIMDAwLQQAhECAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMDAsLQQAhECAAQQA2AhwgACABNgIUIABB+4+AgAA2AhAgAEEKNgIMDAoLQQAhECAAQQA2AhwgACABNgIUIABB8ZmAgAA2AhAgAEECNgIMDAkLQQAhECAAQQA2AhwgACABNgIUIABBxJSAgAA2AhAgAEECNgIMDAgLQQAhECAAQQA2AhwgACABNgIUIABB8pWAgAA2AhAgAEECNgIMDAcLIABBAjYCHCAAIAE2AhQgAEGcmoCAADYCECAAQRY2AgxBACEQDAYLQQEhEAwFC0HUACEQIAEiBCACRg0EIANBCGogACAEIAJB2MKAgABBChDFgICAACADKAIMIQQgAygCCA4DAQQCAAsQyoCAgAAACyAAQQA2AhwgAEG1moCAADYCECAAQRc2AgwgACAEQQFqNgIUQQAhEAwCCyAAQQA2AhwgACAENgIUIABBypqAgAA2AhAgAEEJNgIMQQAhEAwBCwJAIAEiBCACRw0AQSIhEAwBCyAAQYmAgIAANgIIIAAgBDYCBEEhIRALIANBEGokgICAgAAgEAuvAQECfyABKAIAIQYCQAJAIAIgA0YNACAEIAZqIQQgBiADaiACayEHIAIgBkF/cyAFaiIGaiEFA0ACQCACLQAAIAQtAABGDQBBAiEEDAMLAkAgBg0AQQAhBCAFIQIMAwsgBkF/aiEGIARBAWohBCACQQFqIgIgA0cNAAsgByEGIAMhAgsgAEEBNgIAIAEgBjYCACAAIAI2AgQPCyABQQA2AgAgACAENgIAIAAgAjYCBAsKACAAEMeAgIAAC/I2AQt/I4CAgIAAQRBrIgEkgICAgAACQEEAKAKg0ICAAA0AQQAQy4CAgABBgNSEgABrIgJB2QBJDQBBACEDAkBBACgC4NOAgAAiBA0AQQBCfzcC7NOAgABBAEKAgISAgIDAADcC5NOAgABBACABQQhqQXBxQdiq1aoFcyIENgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgAALQQAgAjYCzNOAgABBAEGA1ISAADYCyNOAgABBAEGA1ISAADYCmNCAgABBACAENgKs0ICAAEEAQX82AqjQgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAtBgNSEgABBeEGA1ISAAGtBD3FBAEGA1ISAAEEIakEPcRsiA2oiBEEEaiACQUhqIgUgA2siA0EBcjYCAEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgABBgNSEgAAgBWpBODYCBAsCQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHsAUsNAAJAQQAoAojQgIAAIgZBECAAQRNqQXBxIABBC0kbIgJBA3YiBHYiA0EDcUUNAAJAAkAgA0EBcSAEckEBcyIFQQN0IgRBsNCAgABqIgMgBEG40ICAAGooAgAiBCgCCCICRw0AQQAgBkF+IAV3cTYCiNCAgAAMAQsgAyACNgIIIAIgAzYCDAsgBEEIaiEDIAQgBUEDdCIFQQNyNgIEIAQgBWoiBCAEKAIEQQFyNgIEDAwLIAJBACgCkNCAgAAiB00NAQJAIANFDQACQAJAIAMgBHRBAiAEdCIDQQAgA2tycSIDQQAgA2txQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmoiBEEDdCIDQbDQgIAAaiIFIANBuNCAgABqKAIAIgMoAggiAEcNAEEAIAZBfiAEd3EiBjYCiNCAgAAMAQsgBSAANgIIIAAgBTYCDAsgAyACQQNyNgIEIAMgBEEDdCIEaiAEIAJrIgU2AgAgAyACaiIAIAVBAXI2AgQCQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhBAJAAkAgBkEBIAdBA3Z0IghxDQBBACAGIAhyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAQ2AgwgAiAENgIIIAQgAjYCDCAEIAg2AggLIANBCGohA0EAIAA2ApzQgIAAQQAgBTYCkNCAgAAMDAtBACgCjNCAgAAiCUUNASAJQQAgCWtxQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmpBAnRBuNKAgABqKAIAIgAoAgRBeHEgAmshBCAAIQUCQANAAkAgBSgCECIDDQAgBUEUaigCACIDRQ0CCyADKAIEQXhxIAJrIgUgBCAFIARJIgUbIQQgAyAAIAUbIQAgAyEFDAALCyAAKAIYIQoCQCAAKAIMIgggAEYNACAAKAIIIgNBACgCmNCAgABJGiAIIAM2AgggAyAINgIMDAsLAkAgAEEUaiIFKAIAIgMNACAAKAIQIgNFDQMgAEEQaiEFCwNAIAUhCyADIghBFGoiBSgCACIDDQAgCEEQaiEFIAgoAhAiAw0ACyALQQA2AgAMCgtBfyECIABBv39LDQAgAEETaiIDQXBxIQJBACgCjNCAgAAiB0UNAEEAIQsCQCACQYACSQ0AQR8hCyACQf///wdLDQAgA0EIdiIDIANBgP4/akEQdkEIcSIDdCIEIARBgOAfakEQdkEEcSIEdCIFIAVBgIAPakEQdkECcSIFdEEPdiADIARyIAVyayIDQQF0IAIgA0EVanZBAXFyQRxqIQsLQQAgAmshBAJAAkACQAJAIAtBAnRBuNKAgABqKAIAIgUNAEEAIQNBACEIDAELQQAhAyACQQBBGSALQQF2ayALQR9GG3QhAEEAIQgDQAJAIAUoAgRBeHEgAmsiBiAETw0AIAYhBCAFIQggBg0AQQAhBCAFIQggBSEDDAMLIAMgBUEUaigCACIGIAYgBSAAQR12QQRxakEQaigCACIFRhsgAyAGGyEDIABBAXQhACAFDQALCwJAIAMgCHINAEEAIQhBAiALdCIDQQAgA2tyIAdxIgNFDQMgA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBUEFdkEIcSIAIANyIAUgAHYiA0ECdkEEcSIFciADIAV2IgNBAXZBAnEiBXIgAyAFdiIDQQF2QQFxIgVyIAMgBXZqQQJ0QbjSgIAAaigCACEDCyADRQ0BCwNAIAMoAgRBeHEgAmsiBiAESSEAAkAgAygCECIFDQAgA0EUaigCACEFCyAGIAQgABshBCADIAggABshCCAFIQMgBQ0ACwsgCEUNACAEQQAoApDQgIAAIAJrTw0AIAgoAhghCwJAIAgoAgwiACAIRg0AIAgoAggiA0EAKAKY0ICAAEkaIAAgAzYCCCADIAA2AgwMCQsCQCAIQRRqIgUoAgAiAw0AIAgoAhAiA0UNAyAIQRBqIQULA0AgBSEGIAMiAEEUaiIFKAIAIgMNACAAQRBqIQUgACgCECIDDQALIAZBADYCAAwICwJAQQAoApDQgIAAIgMgAkkNAEEAKAKc0ICAACEEAkACQCADIAJrIgVBEEkNACAEIAJqIgAgBUEBcjYCBEEAIAU2ApDQgIAAQQAgADYCnNCAgAAgBCADaiAFNgIAIAQgAkEDcjYCBAwBCyAEIANBA3I2AgQgBCADaiIDIAMoAgRBAXI2AgRBAEEANgKc0ICAAEEAQQA2ApDQgIAACyAEQQhqIQMMCgsCQEEAKAKU0ICAACIAIAJNDQBBACgCoNCAgAAiAyACaiIEIAAgAmsiBUEBcjYCBEEAIAU2ApTQgIAAQQAgBDYCoNCAgAAgAyACQQNyNgIEIANBCGohAwwKCwJAAkBBACgC4NOAgABFDQBBACgC6NOAgAAhBAwBC0EAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEMakFwcUHYqtWqBXM2AuDTgIAAQQBBADYC9NOAgABBAEEANgLE04CAAEGAgAQhBAtBACEDAkAgBCACQccAaiIHaiIGQQAgBGsiC3EiCCACSw0AQQBBMDYC+NOAgAAMCgsCQEEAKALA04CAACIDRQ0AAkBBACgCuNOAgAAiBCAIaiIFIARNDQAgBSADTQ0BC0EAIQNBAEEwNgL404CAAAwKC0EALQDE04CAAEEEcQ0EAkACQAJAQQAoAqDQgIAAIgRFDQBByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiAESw0DCyADKAIIIgMNAAsLQQAQy4CAgAAiAEF/Rg0FIAghBgJAQQAoAuTTgIAAIgNBf2oiBCAAcUUNACAIIABrIAQgAGpBACADa3FqIQYLIAYgAk0NBSAGQf7///8HSw0FAkBBACgCwNOAgAAiA0UNAEEAKAK404CAACIEIAZqIgUgBE0NBiAFIANLDQYLIAYQy4CAgAAiAyAARw0BDAcLIAYgAGsgC3EiBkH+////B0sNBCAGEMuAgIAAIgAgAygCACADKAIEakYNAyAAIQMLAkAgA0F/Rg0AIAJByABqIAZNDQACQCAHIAZrQQAoAujTgIAAIgRqQQAgBGtxIgRB/v///wdNDQAgAyEADAcLAkAgBBDLgICAAEF/Rg0AIAQgBmohBiADIQAMBwtBACAGaxDLgICAABoMBAsgAyEAIANBf0cNBQwDC0EAIQgMBwtBACEADAULIABBf0cNAgtBAEEAKALE04CAAEEEcjYCxNOAgAALIAhB/v///wdLDQEgCBDLgICAACEAQQAQy4CAgAAhAyAAQX9GDQEgA0F/Rg0BIAAgA08NASADIABrIgYgAkE4ak0NAQtBAEEAKAK404CAACAGaiIDNgK404CAAAJAIANBACgCvNOAgABNDQBBACADNgK804CAAAsCQAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQCAAIAMoAgAiBSADKAIEIghqRg0CIAMoAggiAw0ADAMLCwJAAkBBACgCmNCAgAAiA0UNACAAIANPDQELQQAgADYCmNCAgAALQQAhA0EAIAY2AszTgIAAQQAgADYCyNOAgABBAEF/NgKo0ICAAEEAQQAoAuDTgIAANgKs0ICAAEEAQQA2AtTTgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiBCAGQUhqIgUgA2siA0EBcjYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgAAgACAFakE4NgIEDAILIAMtAAxBCHENACAEIAVJDQAgBCAATw0AIARBeCAEa0EPcUEAIARBCGpBD3EbIgVqIgBBACgClNCAgAAgBmoiCyAFayIFQQFyNgIEIAMgCCAGajYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAU2ApTQgIAAQQAgADYCoNCAgAAgBCALakE4NgIEDAELAkAgAEEAKAKY0ICAACIITw0AQQAgADYCmNCAgAAgACEICyAAIAZqIQVByNOAgAAhAwJAAkACQAJAAkACQAJAA0AgAygCACAFRg0BIAMoAggiAw0ADAILCyADLQAMQQhxRQ0BC0HI04CAACEDA0ACQCADKAIAIgUgBEsNACAFIAMoAgRqIgUgBEsNAwsgAygCCCEDDAALCyADIAA2AgAgAyADKAIEIAZqNgIEIABBeCAAa0EPcUEAIABBCGpBD3EbaiILIAJBA3I2AgQgBUF4IAVrQQ9xQQAgBUEIakEPcRtqIgYgCyACaiICayEDAkAgBiAERw0AQQAgAjYCoNCAgABBAEEAKAKU0ICAACADaiIDNgKU0ICAACACIANBAXI2AgQMAwsCQCAGQQAoApzQgIAARw0AQQAgAjYCnNCAgABBAEEAKAKQ0ICAACADaiIDNgKQ0ICAACACIANBAXI2AgQgAiADaiADNgIADAMLAkAgBigCBCIEQQNxQQFHDQAgBEF4cSEHAkACQCAEQf8BSw0AIAYoAggiBSAEQQN2IghBA3RBsNCAgABqIgBGGgJAIAYoAgwiBCAFRw0AQQBBACgCiNCAgABBfiAId3E2AojQgIAADAILIAQgAEYaIAQgBTYCCCAFIAQ2AgwMAQsgBigCGCEJAkACQCAGKAIMIgAgBkYNACAGKAIIIgQgCEkaIAAgBDYCCCAEIAA2AgwMAQsCQCAGQRRqIgQoAgAiBQ0AIAZBEGoiBCgCACIFDQBBACEADAELA0AgBCEIIAUiAEEUaiIEKAIAIgUNACAAQRBqIQQgACgCECIFDQALIAhBADYCAAsgCUUNAAJAAkAgBiAGKAIcIgVBAnRBuNKAgABqIgQoAgBHDQAgBCAANgIAIAANAUEAQQAoAozQgIAAQX4gBXdxNgKM0ICAAAwCCyAJQRBBFCAJKAIQIAZGG2ogADYCACAARQ0BCyAAIAk2AhgCQCAGKAIQIgRFDQAgACAENgIQIAQgADYCGAsgBigCFCIERQ0AIABBFGogBDYCACAEIAA2AhgLIAcgA2ohAyAGIAdqIgYoAgQhBAsgBiAEQX5xNgIEIAIgA2ogAzYCACACIANBAXI2AgQCQCADQf8BSw0AIANBeHFBsNCAgABqIQQCQAJAQQAoAojQgIAAIgVBASADQQN2dCIDcQ0AQQAgBSADcjYCiNCAgAAgBCEDDAELIAQoAgghAwsgAyACNgIMIAQgAjYCCCACIAQ2AgwgAiADNgIIDAMLQR8hBAJAIANB////B0sNACADQQh2IgQgBEGA/j9qQRB2QQhxIgR0IgUgBUGA4B9qQRB2QQRxIgV0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAQgBXIgAHJrIgRBAXQgAyAEQRVqdkEBcXJBHGohBAsgAiAENgIcIAJCADcCECAEQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiAEEBIAR0IghxDQAgBSACNgIAQQAgACAIcjYCjNCAgAAgAiAFNgIYIAIgAjYCCCACIAI2AgwMAwsgA0EAQRkgBEEBdmsgBEEfRht0IQQgBSgCACEAA0AgACIFKAIEQXhxIANGDQIgBEEddiEAIARBAXQhBCAFIABBBHFqQRBqIggoAgAiAA0ACyAIIAI2AgAgAiAFNgIYIAIgAjYCDCACIAI2AggMAgsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiCyAGQUhqIgggA2siA0EBcjYCBCAAIAhqQTg2AgQgBCAFQTcgBWtBD3FBACAFQUlqQQ9xG2pBQWoiCCAIIARBEGpJGyIIQSM2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAs2AqDQgIAAIAhBEGpBACkC0NOAgAA3AgAgCEEAKQLI04CAADcCCEEAIAhBCGo2AtDTgIAAQQAgBjYCzNOAgABBACAANgLI04CAAEEAQQA2AtTTgIAAIAhBJGohAwNAIANBBzYCACADQQRqIgMgBUkNAAsgCCAERg0DIAggCCgCBEF+cTYCBCAIIAggBGsiADYCACAEIABBAXI2AgQCQCAAQf8BSw0AIABBeHFBsNCAgABqIQMCQAJAQQAoAojQgIAAIgVBASAAQQN2dCIAcQ0AQQAgBSAAcjYCiNCAgAAgAyEFDAELIAMoAgghBQsgBSAENgIMIAMgBDYCCCAEIAM2AgwgBCAFNgIIDAQLQR8hAwJAIABB////B0sNACAAQQh2IgMgA0GA/j9qQRB2QQhxIgN0IgUgBUGA4B9qQRB2QQRxIgV0IgggCEGAgA9qQRB2QQJxIgh0QQ92IAMgBXIgCHJrIgNBAXQgACADQRVqdkEBcXJBHGohAwsgBCADNgIcIARCADcCECADQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiCEEBIAN0IgZxDQAgBSAENgIAQQAgCCAGcjYCjNCAgAAgBCAFNgIYIAQgBDYCCCAEIAQ2AgwMBAsgAEEAQRkgA0EBdmsgA0EfRht0IQMgBSgCACEIA0AgCCIFKAIEQXhxIABGDQMgA0EddiEIIANBAXQhAyAFIAhBBHFqQRBqIgYoAgAiCA0ACyAGIAQ2AgAgBCAFNgIYIAQgBDYCDCAEIAQ2AggMAwsgBSgCCCIDIAI2AgwgBSACNgIIIAJBADYCGCACIAU2AgwgAiADNgIICyALQQhqIQMMBQsgBSgCCCIDIAQ2AgwgBSAENgIIIARBADYCGCAEIAU2AgwgBCADNgIIC0EAKAKU0ICAACIDIAJNDQBBACgCoNCAgAAiBCACaiIFIAMgAmsiA0EBcjYCBEEAIAM2ApTQgIAAQQAgBTYCoNCAgAAgBCACQQNyNgIEIARBCGohAwwDC0EAIQNBAEEwNgL404CAAAwCCwJAIAtFDQACQAJAIAggCCgCHCIFQQJ0QbjSgIAAaiIDKAIARw0AIAMgADYCACAADQFBACAHQX4gBXdxIgc2AozQgIAADAILIAtBEEEUIAsoAhAgCEYbaiAANgIAIABFDQELIAAgCzYCGAJAIAgoAhAiA0UNACAAIAM2AhAgAyAANgIYCyAIQRRqKAIAIgNFDQAgAEEUaiADNgIAIAMgADYCGAsCQAJAIARBD0sNACAIIAQgAmoiA0EDcjYCBCAIIANqIgMgAygCBEEBcjYCBAwBCyAIIAJqIgAgBEEBcjYCBCAIIAJBA3I2AgQgACAEaiAENgIAAkAgBEH/AUsNACAEQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgBEEDdnQiBHENAEEAIAUgBHI2AojQgIAAIAMhBAwBCyADKAIIIQQLIAQgADYCDCADIAA2AgggACADNgIMIAAgBDYCCAwBC0EfIQMCQCAEQf///wdLDQAgBEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCICIAJBgIAPakEQdkECcSICdEEPdiADIAVyIAJyayIDQQF0IAQgA0EVanZBAXFyQRxqIQMLIAAgAzYCHCAAQgA3AhAgA0ECdEG40oCAAGohBQJAIAdBASADdCICcQ0AIAUgADYCAEEAIAcgAnI2AozQgIAAIAAgBTYCGCAAIAA2AgggACAANgIMDAELIARBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhAgJAA0AgAiIFKAIEQXhxIARGDQEgA0EddiECIANBAXQhAyAFIAJBBHFqQRBqIgYoAgAiAg0ACyAGIAA2AgAgACAFNgIYIAAgADYCDCAAIAA2AggMAQsgBSgCCCIDIAA2AgwgBSAANgIIIABBADYCGCAAIAU2AgwgACADNgIICyAIQQhqIQMMAQsCQCAKRQ0AAkACQCAAIAAoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAg2AgAgCA0BQQAgCUF+IAV3cTYCjNCAgAAMAgsgCkEQQRQgCigCECAARhtqIAg2AgAgCEUNAQsgCCAKNgIYAkAgACgCECIDRQ0AIAggAzYCECADIAg2AhgLIABBFGooAgAiA0UNACAIQRRqIAM2AgAgAyAINgIYCwJAAkAgBEEPSw0AIAAgBCACaiIDQQNyNgIEIAAgA2oiAyADKAIEQQFyNgIEDAELIAAgAmoiBSAEQQFyNgIEIAAgAkEDcjYCBCAFIARqIAQ2AgACQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhAwJAAkBBASAHQQN2dCIIIAZxDQBBACAIIAZyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAM2AgwgAiADNgIIIAMgAjYCDCADIAg2AggLQQAgBTYCnNCAgABBACAENgKQ0ICAAAsgAEEIaiEDCyABQRBqJICAgIAAIAMLCgAgABDJgICAAAviDQEHfwJAIABFDQAgAEF4aiIBIABBfGooAgAiAkF4cSIAaiEDAkAgAkEBcQ0AIAJBA3FFDQEgASABKAIAIgJrIgFBACgCmNCAgAAiBEkNASACIABqIQACQCABQQAoApzQgIAARg0AAkAgAkH/AUsNACABKAIIIgQgAkEDdiIFQQN0QbDQgIAAaiIGRhoCQCABKAIMIgIgBEcNAEEAQQAoAojQgIAAQX4gBXdxNgKI0ICAAAwDCyACIAZGGiACIAQ2AgggBCACNgIMDAILIAEoAhghBwJAAkAgASgCDCIGIAFGDQAgASgCCCICIARJGiAGIAI2AgggAiAGNgIMDAELAkAgAUEUaiICKAIAIgQNACABQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQECQAJAIAEgASgCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAwsgB0EQQRQgBygCECABRhtqIAY2AgAgBkUNAgsgBiAHNgIYAkAgASgCECICRQ0AIAYgAjYCECACIAY2AhgLIAEoAhQiAkUNASAGQRRqIAI2AgAgAiAGNgIYDAELIAMoAgQiAkEDcUEDRw0AIAMgAkF+cTYCBEEAIAA2ApDQgIAAIAEgAGogADYCACABIABBAXI2AgQPCyABIANPDQAgAygCBCICQQFxRQ0AAkACQCACQQJxDQACQCADQQAoAqDQgIAARw0AQQAgATYCoNCAgABBAEEAKAKU0ICAACAAaiIANgKU0ICAACABIABBAXI2AgQgAUEAKAKc0ICAAEcNA0EAQQA2ApDQgIAAQQBBADYCnNCAgAAPCwJAIANBACgCnNCAgABHDQBBACABNgKc0ICAAEEAQQAoApDQgIAAIABqIgA2ApDQgIAAIAEgAEEBcjYCBCABIABqIAA2AgAPCyACQXhxIABqIQACQAJAIAJB/wFLDQAgAygCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgAygCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAgsgAiAGRhogAiAENgIIIAQgAjYCDAwBCyADKAIYIQcCQAJAIAMoAgwiBiADRg0AIAMoAggiAkEAKAKY0ICAAEkaIAYgAjYCCCACIAY2AgwMAQsCQCADQRRqIgIoAgAiBA0AIANBEGoiAigCACIEDQBBACEGDAELA0AgAiEFIAQiBkEUaiICKAIAIgQNACAGQRBqIQIgBigCECIEDQALIAVBADYCAAsgB0UNAAJAAkAgAyADKAIcIgRBAnRBuNKAgABqIgIoAgBHDQAgAiAGNgIAIAYNAUEAQQAoAozQgIAAQX4gBHdxNgKM0ICAAAwCCyAHQRBBFCAHKAIQIANGG2ogBjYCACAGRQ0BCyAGIAc2AhgCQCADKAIQIgJFDQAgBiACNgIQIAIgBjYCGAsgAygCFCICRQ0AIAZBFGogAjYCACACIAY2AhgLIAEgAGogADYCACABIABBAXI2AgQgAUEAKAKc0ICAAEcNAUEAIAA2ApDQgIAADwsgAyACQX5xNgIEIAEgAGogADYCACABIABBAXI2AgQLAkAgAEH/AUsNACAAQXhxQbDQgIAAaiECAkACQEEAKAKI0ICAACIEQQEgAEEDdnQiAHENAEEAIAQgAHI2AojQgIAAIAIhAAwBCyACKAIIIQALIAAgATYCDCACIAE2AgggASACNgIMIAEgADYCCA8LQR8hAgJAIABB////B0sNACAAQQh2IgIgAkGA/j9qQRB2QQhxIgJ0IgQgBEGA4B9qQRB2QQRxIgR0IgYgBkGAgA9qQRB2QQJxIgZ0QQ92IAIgBHIgBnJrIgJBAXQgACACQRVqdkEBcXJBHGohAgsgASACNgIcIAFCADcCECACQQJ0QbjSgIAAaiEEAkACQEEAKAKM0ICAACIGQQEgAnQiA3ENACAEIAE2AgBBACAGIANyNgKM0ICAACABIAQ2AhggASABNgIIIAEgATYCDAwBCyAAQQBBGSACQQF2ayACQR9GG3QhAiAEKAIAIQYCQANAIAYiBCgCBEF4cSAARg0BIAJBHXYhBiACQQF0IQIgBCAGQQRxakEQaiIDKAIAIgYNAAsgAyABNgIAIAEgBDYCGCABIAE2AgwgASABNgIIDAELIAQoAggiACABNgIMIAQgATYCCCABQQA2AhggASAENgIMIAEgADYCCAtBAEEAKAKo0ICAAEF/aiIBQX8gARs2AqjQgIAACwsEAAAAC04AAkAgAA0APwBBEHQPCwJAIABB//8DcQ0AIABBf0wNAAJAIABBEHZAACIAQX9HDQBBAEEwNgL404CAAEF/DwsgAEEQdA8LEMqAgIAAAAvyAgIDfwF+AkAgAkUNACAAIAE6AAAgAiAAaiIDQX9qIAE6AAAgAkEDSQ0AIAAgAToAAiAAIAE6AAEgA0F9aiABOgAAIANBfmogAToAACACQQdJDQAgACABOgADIANBfGogAToAACACQQlJDQAgAEEAIABrQQNxIgRqIgMgAUH/AXFBgYKECGwiATYCACADIAIgBGtBfHEiBGoiAkF8aiABNgIAIARBCUkNACADIAE2AgggAyABNgIEIAJBeGogATYCACACQXRqIAE2AgAgBEEZSQ0AIAMgATYCGCADIAE2AhQgAyABNgIQIAMgATYCDCACQXBqIAE2AgAgAkFsaiABNgIAIAJBaGogATYCACACQWRqIAE2AgAgBCADQQRxQRhyIgVrIgJBIEkNACABrUKBgICAEH4hBiADIAVqIQEDQCABIAY3AxggASAGNwMQIAEgBjcDCCABIAY3AwAgAUEgaiEBIAJBYGoiAkEfSw0ACwsgAAsLjkgBAEGACAuGSAEAAAACAAAAAwAAAAAAAAAAAAAABAAAAAUAAAAAAAAAAAAAAAYAAAAHAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsb3NlZWVwLWFsaXZlAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgAAAAAAAAAAAAAAAAAAAHJhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KDQpTTQ0KDQpUVFAvQ0UvVFNQLwAAAAAAAAAAAAAAAAECAAEDAAAAAAAAAAAAAAAAAAAAAAAABAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQUBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAABAAACAAAAAAAAAAAAAAAAAAAAAAAAAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' + + +/***/ }), + +/***/ 1891: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.enumToMap = void 0; +function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; } +exports.enumToMap = enumToMap; +//# sourceMappingURL=utils.js.map -util.inherits(Source, PassThrough) +/***/ }), -Source.prototype.destroy = function (err) { - this._parent.destroy(err) +/***/ 6771: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { kClients } = __nccwpck_require__(2785) +const Agent = __nccwpck_require__(7890) +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = __nccwpck_require__(4347) +const MockClient = __nccwpck_require__(8687) +const MockPool = __nccwpck_require__(6193) +const { matchValue, buildMockOptions } = __nccwpck_require__(9323) +const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8045) +const Dispatcher = __nccwpck_require__(412) +const Pluralizer = __nccwpck_require__(8891) +const PendingInterceptorsFormatter = __nccwpck_require__(6823) + +class FakeWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value + } } -var Extract = function (opts) { - if (!(this instanceof Extract)) return new Extract(opts) - Writable.call(this, opts) +class MockAgent extends Dispatcher { + constructor (opts) { + super(opts) - opts = opts || {} + this[kNetConnect] = true + this[kIsMockActive] = true - this._offset = 0 - this._buffer = bl() - this._missing = 0 - this._partial = false - this._onparse = noop - this._header = null - this._stream = null - this._overflow = null - this._cb = null - this._locked = false - this._destroyed = false - this._pax = null - this._paxGlobal = null - this._gnuLongPath = null - this._gnuLongLinkPath = null + // Instantiate Agent and encapsulate + if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts && opts.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent - var self = this - var b = self._buffer + this[kClients] = agent[kClients] + this[kOptions] = buildMockOptions(opts) + } - var oncontinue = function () { - self._continue() + get (origin) { + let dispatcher = this[kMockAgentGet](origin) + + if (!dispatcher) { + dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + } + return dispatcher } - var onunlock = function (err) { - self._locked = false - if (err) return self.destroy(err) - if (!self._stream) oncontinue() + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + return this[kAgent].dispatch(opts, handler) } - var onstreamend = function () { - self._stream = null - var drain = overflow(self._header.size) - if (drain) self._parse(drain, ondrain) - else self._parse(512, onheader) - if (!self._locked) oncontinue() + async close () { + await this[kAgent].close() + this[kClients].clear() } - var ondrain = function () { - self._buffer.consume(overflow(self._header.size)) - self._parse(512, onheader) - oncontinue() + deactivate () { + this[kIsMockActive] = false } - var onpaxglobalheader = function () { - var size = self._header.size - self._paxGlobal = headers.decodePax(b.slice(0, size)) - b.consume(size) - onstreamend() + activate () { + this[kIsMockActive] = true + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } } - var onpaxheader = function () { - var size = self._header.size - self._pax = headers.decodePax(b.slice(0, size)) - if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax) - b.consume(size) - onstreamend() + disableNetConnect () { + this[kNetConnect] = false } - var ongnulongpath = function () { - var size = self._header.size - this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) - b.consume(size) - onstreamend() + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] } - var ongnulonglinkpath = function () { - var size = self._header.size - this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) - b.consume(size) - onstreamend() + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, new FakeWeakRef(dispatcher)) } - var onheader = function () { - var offset = self._offset - var header - try { - header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat) - } catch (err) { - self.emit('error', err) - } - b.consume(512) + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } - if (!header) { - self._parse(512, onheader) - oncontinue() - return - } - if (header.type === 'gnu-long-path') { - self._parse(header.size, ongnulongpath) - oncontinue() - return - } - if (header.type === 'gnu-long-link-path') { - self._parse(header.size, ongnulonglinkpath) - oncontinue() - return - } - if (header.type === 'pax-global-header') { - self._parse(header.size, onpaxglobalheader) - oncontinue() - return - } - if (header.type === 'pax-header') { - self._parse(header.size, onpaxheader) - oncontinue() - return + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const ref = this[kClients].get(origin) + if (ref) { + return ref.deref() } - if (self._gnuLongPath) { - header.name = self._gnuLongPath - self._gnuLongPath = null + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher } - if (self._gnuLongLinkPath) { - header.linkname = self._gnuLongLinkPath - self._gnuLongLinkPath = null + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { + const nonExplicitDispatcher = nonExplicitRef.deref() + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] + return dispatcher + } } + } - if (self._pax) { - self._header = header = mixinPax(header, self._pax) - self._pax = null - } + [kGetNetConnect] () { + return this[kNetConnect] + } - self._locked = true + pendingInterceptors () { + const mockAgentClients = this[kClients] - if (!header.size || header.type === 'directory') { - self._parse(512, onheader) - self.emit('entry', header, emptyStream(self, offset), onunlock) + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() + + if (pending.length === 0) { return } - self._stream = new Source(self, offset) + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) - self.emit('entry', header, self._stream, onunlock) - self._parse(header.size, onstreamend) - oncontinue() - } + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: - this._onheader = onheader - this._parse(512, onheader) +${pendingInterceptorsFormatter.format(pending)} +`.trim()) + } } -util.inherits(Extract, Writable) - -Extract.prototype.destroy = function (err) { - if (this._destroyed) return - this._destroyed = true +module.exports = MockAgent - if (err) this.emit('error', err) - this.emit('close') - if (this._stream) this._stream.emit('close') -} -Extract.prototype._parse = function (size, onparse) { - if (this._destroyed) return - this._offset += size - this._missing = size - if (onparse === this._onheader) this._partial = false - this._onparse = onparse -} +/***/ }), -Extract.prototype._continue = function () { - if (this._destroyed) return - var cb = this._cb - this._cb = noop - if (this._overflow) this._write(this._overflow, undefined, cb) - else cb() -} +/***/ 8687: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Extract.prototype._write = function (data, enc, cb) { - if (this._destroyed) return +"use strict"; - var s = this._stream - var b = this._buffer - var missing = this._missing - if (data.length) this._partial = true - // we do not reach end-of-chunk now. just forward it +const { promisify } = __nccwpck_require__(3837) +const Client = __nccwpck_require__(3598) +const { buildMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(4347) +const { MockInterceptor } = __nccwpck_require__(410) +const Symbols = __nccwpck_require__(2785) +const { InvalidArgumentError } = __nccwpck_require__(8045) - if (data.length < missing) { - this._missing -= data.length - this._overflow = null - if (s) return s.write(data, cb) - b.append(data) - return cb() - } +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + super(origin, opts) - // end-of-chunk. the parser should call cb. + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } - this._cb = cb - this._missing = 0 + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) - var overflow = null - if (data.length > missing) { - overflow = data.slice(missing) - data = data.slice(0, missing) + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] } - if (s) s.end(data) - else b.append(data) + get [Symbols.kConnected] () { + return this[kConnected] + } - this._overflow = overflow - this._onparse() -} + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } -Extract.prototype._final = function (cb) { - if (this._partial) return this.destroy(new Error('Unexpected end of data')) - cb() + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } } -module.exports = Extract +module.exports = MockClient /***/ }), -/***/ 8860: -/***/ ((__unused_webpack_module, exports) => { +/***/ 888: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var alloc = Buffer.alloc +"use strict"; -var ZEROS = '0000000000000000000' -var SEVENS = '7777777777777777777' -var ZERO_OFFSET = '0'.charCodeAt(0) -var USTAR_MAGIC = Buffer.from('ustar\x00', 'binary') -var USTAR_VER = Buffer.from('00', 'binary') -var GNU_MAGIC = Buffer.from('ustar\x20', 'binary') -var GNU_VER = Buffer.from('\x20\x00', 'binary') -var MASK = parseInt('7777', 8) -var MAGIC_OFFSET = 257 -var VERSION_OFFSET = 263 -var clamp = function (index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue - index = ~~index // Coerce to integer. - if (index >= len) return len - if (index >= 0) return index - index += len - if (index >= 0) return index - return 0 -} +const { UndiciError } = __nccwpck_require__(8045) -var toType = function (flag) { - switch (flag) { - case 0: - return 'file' - case 1: - return 'link' - case 2: - return 'symlink' - case 3: - return 'character-device' - case 4: - return 'block-device' - case 5: - return 'directory' - case 6: - return 'fifo' - case 7: - return 'contiguous-file' - case 72: - return 'pax-header' - case 55: - return 'pax-global-header' - case 27: - return 'gnu-long-link-path' - case 28: - case 30: - return 'gnu-long-path' +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, MockNotMatchedError) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' } +} - return null +module.exports = { + MockNotMatchedError } -var toTypeflag = function (flag) { - switch (flag) { - case 'file': - return 0 - case 'link': - return 1 - case 'symlink': - return 2 - case 'character-device': - return 3 - case 'block-device': - return 4 - case 'directory': - return 5 - case 'fifo': - return 6 - case 'contiguous-file': - return 7 - case 'pax-header': - return 72 + +/***/ }), + +/***/ 410: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = __nccwpck_require__(4347) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { buildURL } = __nccwpck_require__(3983) + +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch } - return 0 -} + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } -var indexOf = function (block, num, offset, end) { - for (; offset < end; offset++) { - if (block[offset] === num) return offset + this[kMockDispatch].delay = waitInMs + return this } - return end -} -var cksum = function (block) { - var sum = 8 * 32 - for (var i = 0; i < 148; i++) sum += block[i] - for (var j = 156; j < 512; j++) sum += block[j] - return sum -} + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } -var encodeOct = function (val, n) { - val = val.toString(8) - if (val.length > n) return SEVENS.slice(0, n) + ' ' - else return ZEROS.slice(0, n - val.length) + val + ' ' + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes + return this + } } -/* Copied from the node-tar repo and modified to meet - * tar-stream coding standard. - * - * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 +/** + * Defines an interceptor for a Mock */ -function parse256 (buf) { - // first byte MUST be either 80 or FF - // 80 for positive, FF for 2's comp - var positive - if (buf[0] === 0x80) positive = true - else if (buf[0] === 0xFF) positive = false - else return null +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } - // build up a base-256 tuple from the least sig to the highest - var tuple = [] - for (var i = buf.length - 1; i > 0; i--) { - var byte = buf[i] - if (positive) tuple.push(byte) - else tuple.push(0xFF - byte) + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false } - var sum = 0 - var l = tuple.length - for (i = 0; i < l; i++) { - sum += tuple[i] * Math.pow(256, i) + createMockScopeDispatchData (statusCode, data, responseOptions = {}) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } + + return { statusCode, data, headers, trailers } } - return positive ? sum : -1 * sum -} + validateReplyParameters (statusCode, data, responseOptions) { + if (typeof statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof data === 'undefined') { + throw new InvalidArgumentError('data must be defined') + } + if (typeof responseOptions !== 'object') { + throw new InvalidArgumentError('responseOptions must be an object') + } + } -var decodeOct = function (val, offset, length) { - val = val.slice(offset, offset + length) - offset = 0 + /** + * Mock an undici request with a defined reply. + */ + reply (replyData) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyData === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyData(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object') { + throw new InvalidArgumentError('reply options callback must return an object') + } - // If prefixed with 0x80 then parse as a base-256 integer - if (val[offset] & 0x80) { - return parse256(val) - } else { - // Older versions of tar can prefix with spaces - while (offset < val.length && val[offset] === 32) offset++ - var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) - while (offset < end && val[offset] === 0) offset++ - if (end === offset) return 0 - return parseInt(val.slice(offset, end).toString(), 8) + const { statusCode, data = '', responseOptions = {} } = resolvedData + this.validateReplyParameters(statusCode, data, responseOptions) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(statusCode, data, responseOptions) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const [statusCode, data = '', responseOptions = {}] = [...arguments] + this.validateReplyParameters(statusCode, data, responseOptions) + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) + return new MockScope(newMockDispatch) } -} -var decodeStr = function (val, offset, length, encoding) { - return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding) -} + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } -var addLength = function (str) { - var len = Buffer.byteLength(str) - var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 - if (len + digits >= Math.pow(10, digits)) digits++ + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) + return new MockScope(newMockDispatch) + } - return (len + digits) + str -} + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } -exports.decodeLongPath = function (buf, encoding) { - return decodeStr(buf, 0, buf.length, encoding) -} + this[kDefaultHeaders] = headers + return this + } -exports.encodePax = function (opts) { // TODO: encode more stuff in pax - var result = '' - if (opts.name) result += addLength(' path=' + opts.name + '\n') - if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') - var pax = opts.pax - if (pax) { - for (var key in pax) { - result += addLength(' ' + key + '=' + pax[key] + '\n') + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') } + + this[kDefaultTrailers] = trailers + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this } - return Buffer.from(result) } -exports.decodePax = function (buf) { - var result = {} +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope - while (buf.length) { - var i = 0 - while (i < buf.length && buf[i] !== 32) i++ - var len = parseInt(buf.slice(0, i).toString(), 10) - if (!len) return result - var b = buf.slice(i + 1, len - 1).toString() - var keyIndex = b.indexOf('=') - if (keyIndex === -1) return result - result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) +/***/ }), - buf = buf.slice(len) - } +/***/ 6193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return result -} +"use strict"; -exports.encode = function (opts) { - var buf = alloc(512) - var name = opts.name - var prefix = '' - if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' - if (Buffer.byteLength(name) !== name.length) return null // utf-8 +const { promisify } = __nccwpck_require__(3837) +const Pool = __nccwpck_require__(4634) +const { buildMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(4347) +const { MockInterceptor } = __nccwpck_require__(410) +const Symbols = __nccwpck_require__(2785) +const { InvalidArgumentError } = __nccwpck_require__(8045) - while (Buffer.byteLength(name) > 100) { - var i = name.indexOf('/') - if (i === -1) return null - prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) - name = name.slice(i + 1) +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] } - if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null - if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null + get [Symbols.kConnected] () { + return this[kConnected] + } - buf.write(name) - buf.write(encodeOct(opts.mode & MASK, 6), 100) - buf.write(encodeOct(opts.uid, 6), 108) - buf.write(encodeOct(opts.gid, 6), 116) - buf.write(encodeOct(opts.size, 11), 124) - buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } - buf[156] = ZERO_OFFSET + toTypeflag(opts.type) + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} - if (opts.linkname) buf.write(opts.linkname, 157) +module.exports = MockPool - USTAR_MAGIC.copy(buf, MAGIC_OFFSET) - USTAR_VER.copy(buf, VERSION_OFFSET) - if (opts.uname) buf.write(opts.uname, 265) - if (opts.gname) buf.write(opts.gname, 297) - buf.write(encodeOct(opts.devmajor || 0, 6), 329) - buf.write(encodeOct(opts.devminor || 0, 6), 337) - if (prefix) buf.write(prefix, 345) +/***/ }), - buf.write(encodeOct(cksum(buf), 6), 148) +/***/ 4347: +/***/ ((module) => { - return buf +"use strict"; + + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') } -exports.decode = function (buf, filenameEncoding, allowUnknownFormat) { - var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET - var name = decodeStr(buf, 0, 100, filenameEncoding) - var mode = decodeOct(buf, 100, 8) - var uid = decodeOct(buf, 108, 8) - var gid = decodeOct(buf, 116, 8) - var size = decodeOct(buf, 124, 12) - var mtime = decodeOct(buf, 136, 12) - var type = toType(typeflag) - var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) - var uname = decodeStr(buf, 265, 32) - var gname = decodeStr(buf, 297, 32) - var devmajor = decodeOct(buf, 329, 8) - var devminor = decodeOct(buf, 337, 8) +/***/ }), - var c = cksum(buf) +/***/ 9323: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // checksum is still initial value if header was null. - if (c === 8 * 32) return null +"use strict"; - // valid checksum - if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') - if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { - // ustar (posix) format. - // prepend prefix, if present. - if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name - } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && - GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { - // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and - // multi-volume tarballs. +const { MockNotMatchedError } = __nccwpck_require__(888) +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = __nccwpck_require__(4347) +const { buildURL, nop } = __nccwpck_require__(3983) +const { STATUS_CODES } = __nccwpck_require__(3685) +const { + types: { + isPromise + } +} = __nccwpck_require__(3837) + +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} + +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} + +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) } else { - if (!allowUnknownFormat) { - throw new Error('Invalid tar header: unknown format.') + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } +} + +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) +} + +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false } - // to support old tar versions that use trailing / to indicate dirs - if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) - return { - name, - mode, - uid, - gid, - size, - mtime: new Date(1000 * mtime), - type, - linkname, - uname, - gname, - devmajor, - devminor + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } } + return true } +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } -/***/ }), - -/***/ 2283: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const pathSegments = path.split('?') -exports.extract = __nccwpck_require__(7882) -exports.pack = __nccwpck_require__(4930) + if (pathSegments.length !== 2) { + return path + } + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} -/***/ }), +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} -/***/ 4930: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } +} -var constants = __nccwpck_require__(3186) -var eos = __nccwpck_require__(1205) -var inherits = __nccwpck_require__(4124) -var alloc = Buffer.alloc +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath -var Readable = (__nccwpck_require__(1642).Readable) -var Writable = (__nccwpck_require__(1642).Writable) -var StringDecoder = (__nccwpck_require__(1576).StringDecoder) + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } -var headers = __nccwpck_require__(8860) + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) + } -var DMODE = parseInt('755', 8) -var FMODE = parseInt('644', 8) + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) + } -var END_OF_TAR = alloc(1024) + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) + } -var noop = function () {} + return matchedMockDispatches[0] +} -var overflow = function (self, size) { - size &= 511 - if (size) self.push(END_OF_TAR.slice(0, 512 - size)) +function addMockDispatch (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch } -function modeToType (mode) { - switch (mode & constants.S_IFMT) { - case constants.S_IFBLK: return 'block-device' - case constants.S_IFCHR: return 'character-device' - case constants.S_IFDIR: return 'directory' - case constants.S_IFIFO: return 'fifo' - case constants.S_IFLNK: return 'symlink' +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) } - - return 'file' } -var Sink = function (to) { - Writable.call(this) - this.written = 0 - this._to = to - this._destroyed = false +function buildKey (opts) { + const { path, method, body, headers, query } = opts + return { + path, + method, + body, + headers, + query + } } -inherits(Sink, Writable) - -Sink.prototype._write = function (data, enc, cb) { - this.written += data.length - if (this._to.push(data)) return cb() - this._to._drain = cb +function generateKeyValues (data) { + return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ + ...keyValuePairs, + Buffer.from(`${key}`), + Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) + ], []) } -Sink.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' } -var LinkSink = function () { - Writable.call(this) - this.linkname = '' - this._decoder = new StringDecoder('utf-8') - this._destroyed = false +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') } -inherits(LinkSink, Writable) +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) -LinkSink.prototype._write = function (data, enc, cb) { - this.linkname += this._decoder.write(data) - cb() -} + mockDispatch.timesInvoked++ -LinkSink.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } -var Void = function () { - Writable.call(this) - this._destroyed = false -} + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch -inherits(Void, Writable) + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times -Void.prototype._write = function (data, enc, cb) { - cb(new Error('No body allowed for this entry')) + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)) + return + } + + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.abort = nop + handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData(Buffer.from(responseData)) + handler.onComplete(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true } -Void.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } } -var Pack = function (opts) { - if (!(this instanceof Pack)) return new Pack(opts) - Readable.call(this, opts) +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} - this._drain = noop - this._finalized = false - this._finalizing = false - this._destroyed = false - this._stream = null +function buildMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts + return mockOptions + } } -inherits(Pack, Readable) +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildMockOptions, + getHeaderByName +} -Pack.prototype.entry = function (header, buffer, callback) { - if (this._stream) throw new Error('already piping an entry') - if (this._finalized || this._destroyed) return - if (typeof buffer === 'function') { - callback = buffer - buffer = null - } +/***/ }), - if (!callback) callback = noop +/***/ 6823: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var self = this +"use strict"; - if (!header.size || header.type === 'symlink') header.size = 0 - if (!header.type) header.type = modeToType(header.mode) - if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE - if (!header.uid) header.uid = 0 - if (!header.gid) header.gid = 0 - if (!header.mtime) header.mtime = new Date() - if (typeof buffer === 'string') buffer = Buffer.from(buffer) - if (Buffer.isBuffer(buffer)) { - header.size = buffer.length - this._encode(header) - var ok = this.push(buffer) - overflow(self, header.size) - if (ok) process.nextTick(callback) - else this._drain = callback - return new Void() - } +const { Transform } = __nccwpck_require__(2781) +const { Console } = __nccwpck_require__(6206) - if (header.type === 'symlink' && !header.linkname) { - var linkSink = new LinkSink() - eos(linkSink, function (err) { - if (err) { // stream was closed - self.destroy() - return callback(err) +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) } - - header.linkname = linkSink.linkname - self._encode(header) - callback() }) - return linkSink + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) } - this._encode(header) + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? '✅' : '❌', + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) - if (header.type !== 'file' && header.type !== 'contiguous-file') { - process.nextTick(callback) - return new Void() + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() } +} - var sink = new Sink(this) - this._stream = sink +/***/ }), - eos(sink, function (err) { - self._stream = null +/***/ 8891: +/***/ ((module) => { - if (err) { // stream was closed - self.destroy() - return callback(err) - } +"use strict"; - if (sink.written !== header.size) { // corrupting tar - self.destroy() - return callback(new Error('size mismatch')) - } - overflow(self, header.size) - if (self._finalizing) self.finalize() - callback() - }) +const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' +} - return sink +const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' } -Pack.prototype.finalize = function () { - if (this._stream) { - this._finalizing = true - return +module.exports = class Pluralizer { + constructor (singular, plural) { + this.singular = singular + this.plural = plural } - if (this._finalized) return - this._finalized = true - this.push(END_OF_TAR) - this.push(null) + pluralize (count) { + const one = count === 1 + const keys = one ? singulars : plurals + const noun = one ? this.singular : this.plural + return { ...keys, count, noun } + } } -Pack.prototype.destroy = function (err) { - if (this._destroyed) return - this._destroyed = true - if (err) this.emit('error', err) - this.emit('close') - if (this._stream && this._stream.destroy) this._stream.destroy() -} +/***/ }), -Pack.prototype._encode = function (header) { - if (!header.pax) { - var buf = headers.encode(header) - if (buf) { - this.push(buf) - return - } +/***/ 8266: +/***/ ((module) => { + +"use strict"; +/* eslint-disable */ + + + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048; +const kMask = kSize - 1; + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | [empty] | <-- top | item | | item | +// | [empty] | | item | | item | +// | [empty] | | [empty] | <-- top top --> | [empty] | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | [empty] | | item | +// | [empty] | | item | +// | item | <-- bottom top --> | [empty] | +// | item | | [empty] | +// | [empty] | <-- top bottom --> | item | +// | [empty] | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; } - this._encodePax(header) -} -Pack.prototype._encodePax = function (header) { - var paxHeader = headers.encodePax({ - name: header.name, - linkname: header.linkname, - pax: header.pax - }) + isEmpty() { + return this.top === this.bottom; + } - var newHeader = { - name: 'PaxHeader', - mode: header.mode, - uid: header.uid, - gid: header.gid, - size: paxHeader.length, - mtime: header.mtime, - type: 'pax-header', - linkname: header.linkname && 'PaxHeader', - uname: header.uname, - gname: header.gname, - devmajor: header.devmajor, - devminor: header.devminor + isFull() { + return ((this.top + 1) & kMask) === this.bottom; } - this.push(headers.encode(newHeader)) - this.push(paxHeader) - overflow(this, paxHeader.length) + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } - newHeader.size = header.size - newHeader.type = header.type - this.push(headers.encode(newHeader)) + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } } -Pack.prototype._read = function (n) { - var drain = this._drain - this._drain = noop - drain() -} +module.exports = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } -module.exports = Pack + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } +}; /***/ }), -/***/ 4294: +/***/ 3198: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(4219); +"use strict"; -/***/ }), +const DispatcherBase = __nccwpck_require__(4839) +const FixedQueue = __nccwpck_require__(8266) +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(2785) +const PoolStats = __nccwpck_require__(9689) -/***/ 4219: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') +const kStats = Symbol('stats') -"use strict"; +class PoolBase extends DispatcherBase { + constructor () { + super() + this[kQueue] = new FixedQueue() + this[kClients] = [] + this[kQueued] = 0 -var net = __nccwpck_require__(1808); -var tls = __nccwpck_require__(4404); -var http = __nccwpck_require__(3685); -var https = __nccwpck_require__(5687); -var events = __nccwpck_require__(2361); -var assert = __nccwpck_require__(9491); -var util = __nccwpck_require__(3837); + const pool = this + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue] -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; + let needDrain = false + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + pool[kQueued]-- + needDrain = !this.dispatch(item.opts, item.handler) + } -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} + this[kNeedDrain] = needDrain -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false + pool.emit('drain', origin, [pool, ...targets]) + } -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]) + } + } -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]) + } + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err) + } -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err) + } - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } + this[kStats] = new PoolStats(this) + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } + + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } + + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); + return ret + } -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret + } - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret } - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); + get stats () { + return this[kStats] + } - function onFree() { - self.emit('free', socket, options); + async [kClose] () { + if (this[kQueue].isEmpty()) { + return Promise.all(this[kClients].map(c => c.close())) + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve + }) } + } - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) } - }); -}; -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); + return Promise.all(this[kClients].map(c => c.destroy(err))) + } - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; + + return !this[kNeedDrain] } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + process.nextTick(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]) + } + }) + } + + return this } - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) } +} - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} + + +/***/ }), + +/***/ 9689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(2785) +const kPool = Symbol('pool') + +class PoolStats { + constructor (pool) { + this[kPool] = pool } - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); + get connected () { + return this[kPool][kConnected] + } - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); + get free () { + return this[kPool][kFree] } - function onError(cause) { - connectReq.removeAllListeners(); + get pending () { + return this[kPool][kPending] + } - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); + get queued () { + return this[kPool][kQueued] } -}; -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; + get running () { + return this[kPool][kRunning] + } + + get size () { + return this[kPool][kSize] + } +} + +module.exports = PoolStats + + +/***/ }), + +/***/ 4634: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher +} = __nccwpck_require__(3198) +const Client = __nccwpck_require__(3598) +const { + InvalidArgumentError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { kUrl, kInterceptors } = __nccwpck_require__(2785) +const buildConnector = __nccwpck_require__(2067) + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + ...options + } = {}) { + super() + + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : [] + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2 } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory } - this.sockets.splice(pos, 1); - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); + [kGetDispatcher] () { + let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + + if (dispatcher) { + return dispatcher + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + } + + return dispatcher } -}; +} -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); +module.exports = Pool - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); + +/***/ }), + +/***/ 7858: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(2785) +const { URL } = __nccwpck_require__(7310) +const Agent = __nccwpck_require__(7890) +const Pool = __nccwpck_require__(4634) +const DispatcherBase = __nccwpck_require__(4839) +const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8045) +const buildConnector = __nccwpck_require__(2067) + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 } +function buildProxyOptions (opts) { + if (typeof opts === 'string') { + opts = { uri: opts } + } -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + return { + uri: opts.uri, + protocol: opts.protocol || 'https' } - return host; // for v0.11 or later } -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class ProxyAgent extends DispatcherBase { + constructor (opts) { + super(opts) + this[kProxy] = buildProxyOptions(opts) + this[kAgent] = new Agent(opts) + this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : [] + + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + + const resolvedUrl = new URL(opts.uri) + const { origin, port, host, username, password } = resolvedUrl + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } else if (username && password) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` + } + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + this[kClient] = clientFactory(resolvedUrl, { connect }) + this[kAgent] = new Agent({ + ...opts, + connect: async (opts, callback) => { + let requestedHost = opts.host + if (!opts.port) { + requestedHost += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedHost, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host + } + }) + if (statusCode !== 200) { + socket.on('error', () => {}).destroy() + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) + } + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + callback(err) } } - } + }) + } + + dispatch (opts, handler) { + const { host } = new URL(opts.origin) + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + return this[kAgent].dispatch( + { + ...opts, + headers: { + ...headers, + host + } + }, + handler + ) + } + + async [kClose] () { + await this[kAgent].close() + await this[kClient].close() + } + + async [kDestroy] () { + await this[kAgent].destroy() + await this[kClient].destroy() } - return target; } +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] } - console.error.apply(console, args); + + return headersPair + } + + return headers +} + +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') } -} else { - debug = function() {}; } -exports.debug = debug; // for test + +module.exports = ProxyAgent /***/ }), -/***/ 8729: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9459: +/***/ ((module) => { -(function(nacl) { -'use strict'; +"use strict"; -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; +let fastNow = Date.now() +let fastNowTimeout -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; +const fastTimers = [] -var _0 = new Uint8Array(16); -var _9 = new Uint8Array(32); _9[0] = 9; +function onTimeout () { + fastNow = Date.now() -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + let len = fastTimers.length + let idx = 0 + while (idx < len) { + const timer = fastTimers[idx] -function ts64(x, i, h, l) { - x[i] = (h >> 24) & 0xff; - x[i+1] = (h >> 16) & 0xff; - x[i+2] = (h >> 8) & 0xff; - x[i+3] = h & 0xff; - x[i+4] = (l >> 24) & 0xff; - x[i+5] = (l >> 16) & 0xff; - x[i+6] = (l >> 8) & 0xff; - x[i+7] = l & 0xff; -} + if (timer.state === 0) { + timer.state = fastNow + timer.delay + } else if (timer.state > 0 && fastNow >= timer.state) { + timer.state = -1 + timer.callback(timer.opaque) + } -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} + if (timer.state === -1) { + timer.state = -2 + if (idx !== len - 1) { + fastTimers[idx] = fastTimers.pop() + } else { + fastTimers.pop() + } + len -= 1 + } else { + idx += 1 + } + } -function crypto_verify_16(x, xi, y, yi) { - return vn(x,xi,y,yi,16); + if (fastTimers.length > 0) { + refreshTimeout() + } } -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); +function refreshTimeout () { + if (fastNowTimeout && fastNowTimeout.refresh) { + fastNowTimeout.refresh() + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTimeout, 1e3) + if (fastNowTimeout.unref) { + fastNowTimeout.unref() + } + } } -function core_salsa20(o, p, k, c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; +class Timeout { + constructor (callback, delay, opaque) { + this.callback = callback + this.delay = delay + this.opaque = opaque - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; + // -2 not in timer list + // -1 in timer list but inactive + // 0 in timer list waiting for time + // > 0 in timer list waiting for time to expire + this.state = -2 - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); + this.refresh() + } - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); + refresh () { + if (this.state === -2) { + fastTimers.push(this) + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + } - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); + this.state = 0 + } - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); + clear () { + this.state = -1 + } +} - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); +module.exports = { + setTimeout (callback, delay, opaque) { + return delay < 1e3 + ? setTimeout(callback, delay, opaque) + : new Timeout(callback, delay, opaque) + }, + clearTimeout (timeout) { + if (timeout instanceof Timeout) { + timeout.clear() + } else { + clearTimeout(timeout) + } + } +} - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); +/***/ }), - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } - x0 = x0 + j0 | 0; - x1 = x1 + j1 | 0; - x2 = x2 + j2 | 0; - x3 = x3 + j3 | 0; - x4 = x4 + j4 | 0; - x5 = x5 + j5 | 0; - x6 = x6 + j6 | 0; - x7 = x7 + j7 | 0; - x8 = x8 + j8 | 0; - x9 = x9 + j9 | 0; - x10 = x10 + j10 | 0; - x11 = x11 + j11 | 0; - x12 = x12 + j12 | 0; - x13 = x13 + j13 | 0; - x14 = x14 + j14 | 0; - x15 = x15 + j15 | 0; +/***/ 5354: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; +"use strict"; - o[ 4] = x1 >>> 0 & 0xff; - o[ 5] = x1 >>> 8 & 0xff; - o[ 6] = x1 >>> 16 & 0xff; - o[ 7] = x1 >>> 24 & 0xff; - o[ 8] = x2 >>> 0 & 0xff; - o[ 9] = x2 >>> 8 & 0xff; - o[10] = x2 >>> 16 & 0xff; - o[11] = x2 >>> 24 & 0xff; +const diagnosticsChannel = __nccwpck_require__(7643) +const { uid, states } = __nccwpck_require__(9188) +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose +} = __nccwpck_require__(7578) +const { fireEvent, failWebsocketConnection } = __nccwpck_require__(5515) +const { CloseEvent } = __nccwpck_require__(2611) +const { makeRequest } = __nccwpck_require__(8359) +const { fetching } = __nccwpck_require__(4881) +const { Headers } = __nccwpck_require__(554) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { kHeadersList } = __nccwpck_require__(2785) + +const channels = {} +channels.open = diagnosticsChannel.channel('undici:websocket:open') +channels.close = diagnosticsChannel.channel('undici:websocket:close') +channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = __nccwpck_require__(6113) +} catch { + +} + +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any) => void} onEstablish + * @param {Partial} options + */ +function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }) - o[12] = x3 >>> 0 & 0xff; - o[13] = x3 >>> 8 & 0xff; - o[14] = x3 >>> 16 & 0xff; - o[15] = x3 >>> 24 & 0xff; + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = new Headers(options.headers)[kHeadersList] + + request.headersList = headersList + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13') + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + // TODO: enable once permessage-deflate is supported + const permessageDeflate = '' // 'permessage-deflate; 15' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + // request.headersList.append('sec-websocket-extensions', permessageDeflate) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher ?? getGlobalDispatcher(), + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.') + return + } - o[16] = x4 >>> 0 & 0xff; - o[17] = x4 >>> 8 & 0xff; - o[18] = x4 >>> 16 & 0xff; - o[19] = x4 >>> 24 & 0xff; + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.') + return + } - o[20] = x5 >>> 0 & 0xff; - o[21] = x5 >>> 8 & 0xff; - o[22] = x5 >>> 16 & 0xff; - o[23] = x5 >>> 24 & 0xff; + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. - o[24] = x6 >>> 0 & 0xff; - o[25] = x6 >>> 8 & 0xff; - o[26] = x6 >>> 16 & 0xff; - o[27] = x6 >>> 24 & 0xff; + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') + return + } - o[28] = x7 >>> 0 & 0xff; - o[29] = x7 >>> 8 & 0xff; - o[30] = x7 >>> 16 & 0xff; - o[31] = x7 >>> 24 & 0xff; + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') + return + } - o[32] = x8 >>> 0 & 0xff; - o[33] = x8 >>> 8 & 0xff; - o[34] = x8 >>> 16 & 0xff; - o[35] = x8 >>> 24 & 0xff; + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } - o[36] = x9 >>> 0 & 0xff; - o[37] = x9 >>> 8 & 0xff; - o[38] = x9 >>> 16 & 0xff; - o[39] = x9 >>> 24 & 0xff; + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') - o[40] = x10 >>> 0 & 0xff; - o[41] = x10 >>> 8 & 0xff; - o[42] = x10 >>> 16 & 0xff; - o[43] = x10 >>> 24 & 0xff; + if (secExtension !== null && secExtension !== permessageDeflate) { + failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') + return + } - o[44] = x11 >>> 0 & 0xff; - o[45] = x11 >>> 8 & 0xff; - o[46] = x11 >>> 16 & 0xff; - o[47] = x11 >>> 24 & 0xff; + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') - o[48] = x12 >>> 0 & 0xff; - o[49] = x12 >>> 8 & 0xff; - o[50] = x12 >>> 16 & 0xff; - o[51] = x12 >>> 24 & 0xff; + if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') + return + } - o[52] = x13 >>> 0 & 0xff; - o[53] = x13 >>> 8 & 0xff; - o[54] = x13 >>> 16 & 0xff; - o[55] = x13 >>> 24 & 0xff; + response.socket.on('data', onSocketData) + response.socket.on('close', onSocketClose) + response.socket.on('error', onSocketError) - o[56] = x14 >>> 0 & 0xff; - o[57] = x14 >>> 8 & 0xff; - o[58] = x14 >>> 16 & 0xff; - o[59] = x14 >>> 24 & 0xff; + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }) + } - o[60] = x15 >>> 0 & 0xff; - o[61] = x15 >>> 8 & 0xff; - o[62] = x15 >>> 16 & 0xff; - o[63] = x15 >>> 24 & 0xff; + onEstablish(response) + } + }) + + return controller } -function core_hsalsa20(o,p,k,c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; +/** + * @param {Buffer} chunk + */ +function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause() + } +} - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ +function onSocketClose () { + const { ws } = this - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] && ws[kReceivedClose] - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); + let code = 1005 + let reason = '' - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); + const result = ws[kByteParser].closingInfo - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); + if (result) { + code = result.code ?? 1005 + reason = result.reason + } else if (!ws[kSentClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + } - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + fireEvent('close', ws, CloseEvent, { + wasClean, code, reason + }) - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }) } +} - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; +function onSocketError (error) { + const { ws } = this - o[ 4] = x5 >>> 0 & 0xff; - o[ 5] = x5 >>> 8 & 0xff; - o[ 6] = x5 >>> 16 & 0xff; - o[ 7] = x5 >>> 24 & 0xff; + ws[kReadyState] = states.CLOSING - o[ 8] = x10 >>> 0 & 0xff; - o[ 9] = x10 >>> 8 & 0xff; - o[10] = x10 >>> 16 & 0xff; - o[11] = x10 >>> 24 & 0xff; + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error) + } - o[12] = x15 >>> 0 & 0xff; - o[13] = x15 >>> 8 & 0xff; - o[14] = x15 >>> 16 & 0xff; - o[15] = x15 >>> 24 & 0xff; + this.destroy() +} - o[16] = x6 >>> 0 & 0xff; - o[17] = x6 >>> 8 & 0xff; - o[18] = x6 >>> 16 & 0xff; - o[19] = x6 >>> 24 & 0xff; +module.exports = { + establishWebSocketConnection +} - o[20] = x7 >>> 0 & 0xff; - o[21] = x7 >>> 8 & 0xff; - o[22] = x7 >>> 16 & 0xff; - o[23] = x7 >>> 24 & 0xff; - o[24] = x8 >>> 0 & 0xff; - o[25] = x8 >>> 8 & 0xff; - o[26] = x8 >>> 16 & 0xff; - o[27] = x8 >>> 24 & 0xff; +/***/ }), + +/***/ 9188: +/***/ ((module) => { + +"use strict"; + - o[28] = x9 >>> 0 & 0xff; - o[29] = x9 >>> 8 & 0xff; - o[30] = x9 >>> 16 & 0xff; - o[31] = x9 >>> 24 & 0xff; +// This is a Globally Unique Identifier unique used +// to validate that the endpoint accepts websocket +// connections. +// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false } -function crypto_core_salsa20(out,inp,k,c) { - core_salsa20(out,inp,k,c); +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 } -function crypto_core_hsalsa20(out,inp,k,c) { - core_hsalsa20(out,inp,k,c); +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA } -var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - // "expand 32-byte k" +const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 -function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - } - return 0; +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 } -function crypto_stream_salsa20(c,cpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = x[i]; - } - return 0; -} +const emptyBuffer = Buffer.allocUnsafe(0) -function crypto_stream(c,cpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20(c,cpos,d,sn,s); +module.exports = { + uid, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer } -function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); -} -/* -* Port of Andrew Moon's Poly1305-donna-16. Public domain. -* https://github.com/floodyberry/poly1305-donna -*/ +/***/ }), -var poly1305 = function(key) { - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.leftover = 0; - this.fin = 0; +/***/ 2611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var t0, t1, t2, t3, t4, t5, t6, t7; +"use strict"; - t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; - t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; - t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; - this.r[5] = ((t4 >>> 1)) & 0x1ffe; - t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; - t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - this.r[9] = ((t7 >>> 5)) & 0x007f; - this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; - this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; - this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; - this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; - this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; - this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; - this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; - this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; -}; +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const { MessagePort } = __nccwpck_require__(1267) -poly1305.prototype.blocks = function(m, mpos, bytes) { - var hibit = this.fin ? 0 : (1 << 11); - var t0, t1, t2, t3, t4, t5, t6, t7, c; - var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit - var h0 = this.h[0], - h1 = this.h[1], - h2 = this.h[2], - h3 = this.h[3], - h4 = this.h[4], - h5 = this.h[5], - h6 = this.h[6], - h7 = this.h[7], - h8 = this.h[8], - h9 = this.h[9]; + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) - var r0 = this.r[0], - r1 = this.r[1], - r2 = this.r[2], - r3 = this.r[3], - r4 = this.r[4], - r5 = this.r[5], - r6 = this.r[6], - r7 = this.r[7], - r8 = this.r[8], - r9 = this.r[9]; + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.MessageEventInit(eventInitDict) - while (bytes >= 16) { - t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; - t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; - t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; - h5 += ((t4 >>> 1)) & 0x1fff; - t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; - t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - h9 += ((t7 >>> 5)) | hibit; + super(type, eventInitDict) - c = 0; + this.#eventInit = eventInitDict + } - d0 = c; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h2 * (5 * r8); - d0 += h3 * (5 * r7); - d0 += h4 * (5 * r6); - c = (d0 >>> 13); d0 &= 0x1fff; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c += (d0 >>> 13); d0 &= 0x1fff; + get data () { + webidl.brandCheck(this, MessageEvent) - d1 = c; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h2 * (5 * r9); - d1 += h3 * (5 * r8); - d1 += h4 * (5 * r7); - c = (d1 >>> 13); d1 &= 0x1fff; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c += (d1 >>> 13); d1 &= 0x1fff; + return this.#eventInit.data + } - d2 = c; - d2 += h0 * r2; - d2 += h1 * r1; - d2 += h2 * r0; - d2 += h3 * (5 * r9); - d2 += h4 * (5 * r8); - c = (d2 >>> 13); d2 &= 0x1fff; - d2 += h5 * (5 * r7); - d2 += h6 * (5 * r6); - d2 += h7 * (5 * r5); - d2 += h8 * (5 * r4); - d2 += h9 * (5 * r3); - c += (d2 >>> 13); d2 &= 0x1fff; + get origin () { + webidl.brandCheck(this, MessageEvent) - d3 = c; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h2 * r1; - d3 += h3 * r0; - d3 += h4 * (5 * r9); - c = (d3 >>> 13); d3 &= 0x1fff; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c += (d3 >>> 13); d3 &= 0x1fff; + return this.#eventInit.origin + } - d4 = c; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h2 * r2; - d4 += h3 * r1; - d4 += h4 * r0; - c = (d4 >>> 13); d4 &= 0x1fff; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c += (d4 >>> 13); d4 &= 0x1fff; + get lastEventId () { + webidl.brandCheck(this, MessageEvent) - d5 = c; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h2 * r3; - d5 += h3 * r2; - d5 += h4 * r1; - c = (d5 >>> 13); d5 &= 0x1fff; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c += (d5 >>> 13); d5 &= 0x1fff; + return this.#eventInit.lastEventId + } - d6 = c; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h2 * r4; - d6 += h3 * r3; - d6 += h4 * r2; - c = (d6 >>> 13); d6 &= 0x1fff; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c += (d6 >>> 13); d6 &= 0x1fff; + get source () { + webidl.brandCheck(this, MessageEvent) - d7 = c; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h2 * r5; - d7 += h3 * r4; - d7 += h4 * r3; - c = (d7 >>> 13); d7 &= 0x1fff; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c += (d7 >>> 13); d7 &= 0x1fff; + return this.#eventInit.source + } - d8 = c; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h2 * r6; - d8 += h3 * r5; - d8 += h4 * r4; - c = (d8 >>> 13); d8 &= 0x1fff; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c += (d8 >>> 13); d8 &= 0x1fff; + get ports () { + webidl.brandCheck(this, MessageEvent) - d9 = c; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h2 * r7; - d9 += h3 * r6; - d9 += h4 * r5; - c = (d9 >>> 13); d9 &= 0x1fff; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c += (d9 >>> 13); d9 &= 0x1fff; + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) + } - c = (((c << 2) + c)) | 0; - c = (c + d0) | 0; - d0 = c & 0x1fff; - c = (c >>> 13); - d1 += c; + return this.#eventInit.ports + } - h0 = d0; - h1 = d1; - h2 = d2; - h3 = d3; - h4 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } +} - mpos += 16; - bytes -= 16; +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict } - this.h[0] = h0; - this.h[1] = h1; - this.h[2] = h2; - this.h[3] = h3; - this.h[4] = h4; - this.h[5] = h5; - this.h[6] = h6; - this.h[7] = h7; - this.h[8] = h8; - this.h[9] = h9; -}; -poly1305.prototype.finish = function(mac, macpos) { - var g = new Uint16Array(10); - var c, mask, f, i; + get wasClean () { + webidl.brandCheck(this, CloseEvent) - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); + return this.#eventInit.wasClean } - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - for (i = 2; i < 10; i++) { - this.h[i] += c; - c = this.h[i] >>> 13; - this.h[i] &= 0x1fff; + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code } - this.h[0] += (c * 5); - c = this.h[0] >>> 13; - this.h[0] &= 0x1fff; - this.h[1] += c; - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - this.h[2] += c; - g[0] = this.h[0] + 5; - c = g[0] >>> 13; - g[0] &= 0x1fff; - for (i = 1; i < 10; i++) { - g[i] = this.h[i] + c; - c = g[i] >>> 13; - g[i] &= 0x1fff; + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason } - g[9] -= (1 << 13); +} - mask = (c ^ 1) - 1; - for (i = 0; i < 10; i++) g[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit - this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; - this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; - this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; - this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; - this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; - this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; - this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; - this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + constructor (type, eventInitDict) { + webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) - f = this.h[0] + this.pad[0]; - this.h[0] = f & 0xffff; - for (i = 1; i < 8; i++) { - f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; - this.h[i] = f & 0xffff; + super(type, eventInitDict) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict } - mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; - mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; - mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; - mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; - mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; - mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; - mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; - mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; - mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; - mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; - mac[macpos+10] = (this.h[5] >>> 0) & 0xff; - mac[macpos+11] = (this.h[5] >>> 8) & 0xff; - mac[macpos+12] = (this.h[6] >>> 0) & 0xff; - mac[macpos+13] = (this.h[6] >>> 8) & 0xff; - mac[macpos+14] = (this.h[7] >>> 0) & 0xff; - mac[macpos+15] = (this.h[7] >>> 8) & 0xff; -}; + get message () { + webidl.brandCheck(this, ErrorEvent) -poly1305.prototype.update = function(m, mpos, bytes) { - var i, want; + return this.#eventInit.message + } - if (this.leftover) { - want = (16 - this.leftover); - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename } - if (bytes >= 16) { - want = bytes - (bytes % 16); - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno } - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno } -}; -function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s = new poly1305(k); - s.update(m, mpos, n); - s.finish(out, outpos); - return 0; -} + get error () { + webidl.brandCheck(this, ErrorEvent) -function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x,0,m,mpos,n,k); - return crypto_verify_16(h,hpos,x,0); + return this.#eventInit.error + } } -function crypto_secretbox(c,m,d,n,k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c,0,m,0,d,n,k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; -} +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) -function crypto_secretbox_open(m,c,d,n,k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x,0,32,n,k); - if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; - crypto_stream_xor(m,0,c,0,d,n,k); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; -} +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} +webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false } -} +] -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + get defaultValue () { + return [] } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'error', + converter: webidl.converters.any } -} +]) -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent } -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} +/***/ }), -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; -} +/***/ 5444: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { maxUnsigned16Bit } = __nccwpck_require__(9188) + +/** @type {import('crypto')} */ +let crypto +try { + crypto = __nccwpck_require__(6113) +} catch { -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; } -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + this.maskKey = crypto.randomBytes(4) + } - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; + createFrame (opcode) { + const bodyLength = this.frameData?.byteLength ?? 0 - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + const buffer = Buffer.allocUnsafe(bodyLength + offset) - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode -function S(o, a) { - M(o, a, a); -} + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = this.maskKey[0] + buffer[offset - 3] = this.maskKey[1] + buffer[offset - 2] = this.maskKey[2] + buffer[offset - 1] = this.maskKey[3] -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} + buffer[1] = payloadLength -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; + buffer[1] |= 0x80 // MASK + + // mask body + for (let i = 0; i < bodyLength; i++) { + buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] + } + + return buffer } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; } -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); +module.exports = { + WebsocketFrameSend } -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} -function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); -} +/***/ }), + +/***/ 1688: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; -var crypto_box_afternm = crypto_secretbox; -var crypto_box_open_afternm = crypto_secretbox_open; -function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); -} +const { Writable } = __nccwpck_require__(2781) +const diagnosticsChannel = __nccwpck_require__(7643) +const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(9188) +const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(7578) +const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(5515) +const { WebsocketFrameSend } = __nccwpck_require__(5444) -function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); -} +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; +const channels = {} +channels.ping = diagnosticsChannel.channel('undici:websocket:ping') +channels.pong = diagnosticsChannel.channel('undici:websocket:pong') -function crypto_hashblocks_hl(hh, hl, m, n) { - var wh = new Int32Array(16), wl = new Int32Array(16), - bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, - bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, - th, tl, i, j, h, l, a, b, c, d; +class ByteParser extends Writable { + #buffers = [] + #byteOffset = 0 - var ah0 = hh[0], - ah1 = hh[1], - ah2 = hh[2], - ah3 = hh[3], - ah4 = hh[4], - ah5 = hh[5], - ah6 = hh[6], - ah7 = hh[7], + #state = parserStates.INFO - al0 = hl[0], - al1 = hl[1], - al2 = hl[2], - al3 = hl[3], - al4 = hl[4], - al5 = hl[5], - al6 = hl[6], - al7 = hl[7]; + #info = {} + #fragments = [] - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) { - j = 8 * i + pos; - wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; - wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; - } - for (i = 0; i < 80; i++) { - bh0 = ah0; - bh1 = ah1; - bh2 = ah2; - bh3 = ah3; - bh4 = ah4; - bh5 = ah5; - bh6 = ah6; - bh7 = ah7; + constructor (ws) { + super() - bl0 = al0; - bl1 = al1; - bl2 = al2; - bl3 = al3; - bl4 = al4; - bl5 = al5; - bl6 = al6; - bl7 = al7; + this.ws = ws + } - // add - h = ah7; - l = al7; + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + this.run(callback) + } - // Sigma1 - h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); - l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (true) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + const buffer = this.consume(2) - // Ch - h = (ah4 & ah5) ^ (~ah4 & ah6); - l = (al4 & al5) ^ (~al4 & al6); + this.#info.fin = (buffer[0] & 0x80) !== 0 + this.#info.opcode = buffer[0] & 0x0F - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + // If we receive a fragmented message, we use the type of the first + // frame to parse the full message as binary/text, when it's terminated + this.#info.originalOpcode ??= this.#info.opcode - // K - h = K[i*2]; - l = K[i*2+1]; + this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') + return + } - // w - h = wh[i%16]; - l = wl[i%16]; + const payloadLength = buffer[1] & 0x7F - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + if (this.#info.fragmented && payloadLength > 125) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') + return + } else if ( + (this.#info.opcode === opcodes.PING || + this.#info.opcode === opcodes.PONG || + this.#info.opcode === opcodes.CLOSE) && + payloadLength > 125 + ) { + // Control frames can have a payload length of 125 bytes MAX + failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') + return + } else if (this.#info.opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') + return + } - th = c & 0xffff | d << 16; - tl = a & 0xffff | b << 16; + const body = this.consume(payloadLength) - // add - h = th; - l = tl; + this.#info.closeInfo = this.parseCloseBody(false, body) - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + if (!this.ws[kSentClose]) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + const body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + const closeFrame = new WebsocketFrameSend(body) - // Sigma0 - h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); - l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true + } + } + ) + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING + this.ws[kReceivedClose] = true - // Maj - h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); - l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + this.end() - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + return + } else if (this.#info.opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + const body = this.consume(payloadLength) - bh7 = (c & 0xffff) | (d << 16); - bl7 = (a & 0xffff) | (b << 16); + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body) - // add - h = bh3; - l = bl3; + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }) + } + } - h = th; - l = tl; + this.#state = parserStates.INFO - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } else if (this.#info.opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + const body = this.consume(payloadLength) - bh3 = (c & 0xffff) | (d << 16); - bl3 = (a & 0xffff) | (b << 16); + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }) + } - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; + const buffer = this.consume(2) - if (i%16 === 15) { - for (j = 0; j < 16; j++) { - // add - h = wh[j]; - l = wl[j]; + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) + + // 2^31 is the maxinimum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') + return + } - h = wh[(j+9)%16]; - l = wl[(j+9)%16]; + const lower = buffer.readUInt32BE(4) - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + this.#info.payloadLength = (upper << 8) + lower + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + // If there is still more data in this chunk that needs to be read + return callback() + } else if (this.#byteOffset >= this.#info.payloadLength) { + // If the server sent multiple frames in a single chunk - // sigma0 - th = wh[(j+1)%16]; - tl = wl[(j+1)%16]; - h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); - l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + const body = this.consume(this.#info.payloadLength) - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + this.#fragments.push(body) - // sigma1 - th = wh[(j+14)%16]; - tl = wl[(j+14)%16]; - h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); - l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + // If the frame is unfragmented, or a fragmented frame was terminated, + // a message was received + if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { + const fullMessage = Buffer.concat(this.#fragments) - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + this.#info = {} + this.#fragments.length = 0 + } - wh[j] = (c & 0xffff) | (d << 16); - wl[j] = (a & 0xffff) | (b << 16); + this.#state = parserStates.INFO } } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + break + } } + } - // add - h = ah0; - l = al0; + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer|null} + */ + consume (n) { + if (n > this.#byteOffset) { + return null + } else if (n === 0) { + return emptyBuffer + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length + return this.#buffers.shift() + } - h = hh[0]; - l = hl[0]; + const buffer = Buffer.allocUnsafe(n) + let offset = 0 - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + while (offset !== n) { + const next = this.#buffers[0] + const { length } = next - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += next.length + } + } - hh[0] = ah0 = (c & 0xffff) | (d << 16); - hl[0] = al0 = (a & 0xffff) | (b << 16); + this.#byteOffset -= n - h = ah1; - l = al1; + return buffer + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code - h = hh[1]; - l = hl[1]; + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + return { code } + } - hh[1] = ah1 = (c & 0xffff) | (d << 16); - hl[1] = al1 = (a & 0xffff) | (b << 16); + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) - h = ah2; - l = al2; + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + if (code !== undefined && !isValidStatusCode(code)) { + return null + } - h = hh[2]; - l = hl[2]; + try { + // TODO: optimize this + reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) + } catch { + return null + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + return { code, reason } + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + get closingInfo () { + return this.#info.closeInfo + } +} - hh[2] = ah2 = (c & 0xffff) | (d << 16); - hl[2] = al2 = (a & 0xffff) | (b << 16); +module.exports = { + ByteParser +} - h = ah3; - l = al3; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +/***/ }), - h = hh[3]; - l = hl[3]; +/***/ 7578: +/***/ ((module) => { - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +"use strict"; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[3] = ah3 = (c & 0xffff) | (d << 16); - hl[3] = al3 = (a & 0xffff) | (b << 16); +module.exports = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') +} - h = ah4; - l = al4; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +/***/ }), - h = hh[4]; - l = hl[4]; +/***/ 5515: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +"use strict"; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[4] = ah4 = (c & 0xffff) | (d << 16); - hl[4] = al4 = (a & 0xffff) | (b << 16); +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(7578) +const { states, opcodes } = __nccwpck_require__(9188) +const { MessageEvent, ErrorEvent } = __nccwpck_require__(2611) - h = ah5; - l = al5; +/* globals Blob */ - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +/** + * @param {import('./websocket').WebSocket} ws + */ +function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN +} - h = hh[5]; - l = hl[5]; +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING +} - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosed (ws) { + return ws[kReadyState] === states.CLOSED +} - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {EventInit | undefined} eventInitDict + */ +function fireEvent (e, target, eventConstructor = Event, eventInitDict) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. - hh[5] = ah5 = (c & 0xffff) | (d << 16); - hl[5] = al5 = (a & 0xffff) | (b << 16); + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap - h = ah6; - l = al6; + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) +} - h = hh[6]; - l = hl[6]; +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ +function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = new Uint8Array(data).buffer + } + } - hh[6] = ah6 = (c & 0xffff) | (d << 16); - hl[6] = al6 = (a & 0xffff) | (b << 16); + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, MessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }) +} - h = ah7; - l = al7; +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + for (const char of protocol) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || + code > 0x7E || + char === '(' || + char === ')' || + char === '<' || + char === '>' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' || + code === 32 || // SP + code === 9 // HT + ) { + return false + } + } - h = hh[7]; - l = hl[7]; + return true +} - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + return code >= 3000 && code <= 4999 +} - hh[7] = ah7 = (c & 0xffff) | (d << 16); - hl[7] = al7 = (a & 0xffff) | (b << 16); +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws - pos += 128; - n -= 128; + controller.abort() + + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() } - return n; + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }) + } } -function crypto_hash(out, m, n) { - var hh = new Int32Array(8), - hl = new Int32Array(8), - x = new Uint8Array(256), - i, b = n; +module.exports = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived +} - hh[0] = 0x6a09e667; - hh[1] = 0xbb67ae85; - hh[2] = 0x3c6ef372; - hh[3] = 0xa54ff53a; - hh[4] = 0x510e527f; - hh[5] = 0x9b05688c; - hh[6] = 0x1f83d9ab; - hh[7] = 0x5be0cd19; - hl[0] = 0xf3bcc908; - hl[1] = 0x84caa73b; - hl[2] = 0xfe94f82b; - hl[3] = 0x5f1d36f1; - hl[4] = 0xade682d1; - hl[5] = 0x2b3e6c1f; - hl[6] = 0xfb41bd6b; - hl[7] = 0x137e2179; +/***/ }), - crypto_hashblocks_hl(hh, hl, m, n); - n %= 128; +/***/ 4284: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; +"use strict"; - n = 256-128*(n<112?1:0); - x[n-9] = 0; - ts64(x, n-8, (b / 0x20000000) | 0, b << 3); - crypto_hashblocks_hl(hh, hl, x, n); - for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); +const { webidl } = __nccwpck_require__(1744) +const { DOMException } = __nccwpck_require__(1037) +const { URLSerializer } = __nccwpck_require__(685) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(9188) +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = __nccwpck_require__(7578) +const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(5515) +const { establishWebSocketConnection } = __nccwpck_require__(5354) +const { WebsocketFrameSend } = __nccwpck_require__(5444) +const { ByteParser } = __nccwpck_require__(1688) +const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3983) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { types } = __nccwpck_require__(3837) + +let experimentalWarned = false + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' - return 0; -} + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('WebSockets are experimental, expect them to change at any time.', { + code: 'UNDICI-WS' + }) + } - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} + url = webidl.converters.USVString(url) + protocols = options.protocols + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = getGlobalOrigin() + + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". + urlRecord.protocol = 'wss:' + } + + // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 9. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href) -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} + // 11. Let client be this's relevant settings object. -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} + // 12. Run this step in parallel: -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) -function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; + // The extensions attribute must initially return the empty string. - scalarbase(p, d); - pack(pk, p); + // The protocol attribute must initially return the empty string. - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob' + } -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, { clamp: true }) } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} + if (reason !== undefined) { + reason = webidl.converters.USVString(reason) + } -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; + let reasonByteLength = 0 - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason) - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); + // 3. Run the first matching steps from the following list: + if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { + // If this's ready state is CLOSING (2) or CLOSED (3) + // Do nothing. + } else if (!isEstablished(this)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(this, 'Connection was closed before it was established.') + this[kReadyState] = WebSocket.CLOSING + } else if (!isClosing(this)) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + socket.write(frame.createFrame(opcodes.CLOSE), (err) => { + if (!err) { + this[kSentClose] = true + } + }) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this[kReadyState] = states.CLOSING + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + this[kReadyState] = WebSocket.CLOSING } } - modL(sm.subarray(32), x); - return smlen; -} + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); + data = webidl.converters.WebSocketSendData(data) - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (this[kReadyState] === WebSocket.CONNECTING) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); + if (!isEstablished(this) || isClosing(this)) { + return + } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.TEXT) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + const ab = Buffer.from(data, data.byteOffset, data.byteLength) + + const frame = new WebsocketFrameSend(ab) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += ab.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= ab.byteLength + }) + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + const frame = new WebsocketFrameSend() + + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab) + frame.frameData = value + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + }) + } + } - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + get readyState () { + webidl.brandCheck(this, WebSocket) - M(r[3], r[0], r[1]); - return 0; -} + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) - mlen = -1; - if (n < 64) return -1; + return this.#bufferedAmount + } - if (unpackneg(q, pk)) return -1; + get url () { + webidl.brandCheck(this, WebSocket) - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); + get extensions () { + webidl.brandCheck(this, WebSocket) - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; + return this.#extensions } - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; -} - -var crypto_secretbox_KEYBYTES = 32, - crypto_secretbox_NONCEBYTES = 24, - crypto_secretbox_ZEROBYTES = 32, - crypto_secretbox_BOXZEROBYTES = 16, - crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_box_BEFORENMBYTES = 32, - crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, - crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, - crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32, - crypto_hash_BYTES = 64; + get protocol () { + webidl.brandCheck(this, WebSocket) -nacl.lowlevel = { - crypto_core_hsalsa20: crypto_core_hsalsa20, - crypto_stream_xor: crypto_stream_xor, - crypto_stream: crypto_stream, - crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, - crypto_stream_salsa20: crypto_stream_salsa20, - crypto_onetimeauth: crypto_onetimeauth, - crypto_onetimeauth_verify: crypto_onetimeauth_verify, - crypto_verify_16: crypto_verify_16, - crypto_verify_32: crypto_verify_32, - crypto_secretbox: crypto_secretbox, - crypto_secretbox_open: crypto_secretbox_open, - crypto_scalarmult: crypto_scalarmult, - crypto_scalarmult_base: crypto_scalarmult_base, - crypto_box_beforenm: crypto_box_beforenm, - crypto_box_afternm: crypto_box_afternm, - crypto_box: crypto_box, - crypto_box_open: crypto_box_open, - crypto_box_keypair: crypto_box_keypair, - crypto_hash: crypto_hash, - crypto_sign: crypto_sign, - crypto_sign_keypair: crypto_sign_keypair, - crypto_sign_open: crypto_sign_open, + return this.#protocol + } - crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, - crypto_sign_BYTES: crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, - crypto_hash_BYTES: crypto_hash_BYTES -}; + get onopen () { + webidl.brandCheck(this, WebSocket) -/* High-level API */ + return this.#events.open + } -function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); -} + set onopen (fn) { + webidl.brandCheck(this, WebSocket) -function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); -} + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } -function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') - throw new TypeError('unexpected type ' + t + ', use Uint8Array'); + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } } -} -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} + get onerror () { + webidl.brandCheck(this, WebSocket) -// TODO: Completely remove this in v0.15. -if (!nacl.util) { - nacl.util = {}; - nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { - throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); - }; -} + return this.#events.error + } -nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; -}; + set onerror (fn) { + webidl.brandCheck(this, WebSocket) -nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); -}; + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } -nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); -}; + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } -nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; -nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; -nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + get onclose () { + webidl.brandCheck(this, WebSocket) -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; + return this.#events.close + } -nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; -}; + set onclose (fn) { + webidl.brandCheck(this, WebSocket) -nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; -nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); -}; + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } -nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; -}; + get onmessage () { + webidl.brandCheck(this, WebSocket) -nacl.box.after = nacl.secretbox; + return this.#events.message + } -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); -}; + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) -nacl.box.open.after = nacl.secretbox.open; + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; + get binaryType () { + webidl.brandCheck(this, WebSocket) -nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; -nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; -nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; -nacl.box.nonceLength = crypto_box_NONCEBYTES; -nacl.box.overheadLength = nacl.secretbox.overheadLength; + return this[kBinaryType] + } -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; + set binaryType (type) { + webidl.brandCheck(this, WebSocket) -nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; -}; + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob' + } else { + this[kBinaryType] = type + } + } -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response + + const parser = new ByteParser(this) + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume() + }) -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; + response.socket.ws = this + this[kByteParser] = parser + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + } +} + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; +webidl.converters['DOMString or sequence'] = function (V) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; + return webidl.converters.DOMString(V) +} -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; -}; +// This implements the propsal made in https://github.com/whatwg/websockets/issues/42 +webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + get defaultValue () { + return [] + } + }, + { + key: 'dispatcher', + converter: (V) => V, + get defaultValue () { + return getGlobalDispatcher() + } + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } +]) -nacl.hash.hashLength = crypto_hash_BYTES; +webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return (vn(x, 0, y, 0, x.length) === 0) ? true : false; -}; + return { protocols: webidl.converters['DOMString or sequence'](V) } +} -nacl.setPRNG = function(fn) { - randombytes = fn; -}; +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (true) { - // Node.js. - crypto = __nccwpck_require__(6113); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); + if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { + return webidl.converters.BufferSource(V) } } -})(); -})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket +} /***/ }), @@ -75692,7 +97323,7 @@ function getUserAgent() { return navigator.userAgent; } - if (typeof process === "object" && "version" in process) { + if (typeof process === "object" && process.version !== undefined) { return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } @@ -75790,7 +97421,7 @@ var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); -var _nil = _interopRequireDefault(__nccwpck_require__(5350)); +var _nil = _interopRequireDefault(__nccwpck_require__(5332)); var _version = _interopRequireDefault(__nccwpck_require__(1595)); @@ -75834,7 +97465,7 @@ exports["default"] = _default; /***/ }), -/***/ 5350: +/***/ 5332: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -76441,48 +98072,72 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ApiClient = exports.CredentialFetchingError = void 0; +exports.ApiClient = exports.CredentialFetchingError = exports.JobDetailsFetchingError = void 0; const core = __importStar(__nccwpck_require__(2186)); -const axios_1 = __importDefault(__nccwpck_require__(6545)); +const httpClient = __importStar(__nccwpck_require__(6255)); +class JobDetailsFetchingError extends Error { +} +exports.JobDetailsFetchingError = JobDetailsFetchingError; class CredentialFetchingError extends Error { } exports.CredentialFetchingError = CredentialFetchingError; class ApiClient { - constructor(client, params) { + constructor(client, params, jobToken, credentialsToken) { this.client = client; this.params = params; + this.credentialsToken = credentialsToken; // We use a static unknown SHA when marking a job as complete from the action // to remain in parity with the existing runner. this.UnknownSha = { 'base-commit-sha': 'unknown' }; + this.jobToken = jobToken; + } + // Getter for jobToken + getJobToken() { + return this.jobToken; } getJobDetails() { return __awaiter(this, void 0, void 0, function* () { - const detailsURL = `/update_jobs/${this.params.jobId}/details`; - const res = yield this.client.get(detailsURL, { - headers: { Authorization: this.params.jobToken } - }); - if (res.status !== 200) { - throw new Error(`Unexpected status code: ${res.status}`); + const detailsURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/details`; + try { + const res = yield this.getJsonWithRetry(detailsURL, this.jobToken); + if (res.statusCode !== 200) { + throw new JobDetailsFetchingError(`fetching job details: unexpected status code: ${res.statusCode}: ${JSON.stringify(res.result)}`); + } + if (!res.result) { + throw new JobDetailsFetchingError(`fetching job details: missing response`); + } + return res.result.data.attributes; + } + catch (error) { + if (error instanceof JobDetailsFetchingError) { + throw error; + } + else if (error instanceof httpClient.HttpClientError) { + throw new JobDetailsFetchingError(`fetching job details: unexpected status code: ${error.statusCode}: ${error.message}`); + } + else if (error instanceof Error) { + throw new JobDetailsFetchingError(`fetching job details: ${error.name}: ${error.message}`); + } + throw error; } - return res.data.data.attributes; }); } getCredentials() { - var _a, _b; return __awaiter(this, void 0, void 0, function* () { - const credentialsURL = `/update_jobs/${this.params.jobId}/credentials`; + const credentialsURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/credentials`; try { - const res = yield this.client.get(credentialsURL, { - headers: { Authorization: this.params.credentialsToken } - }); + const res = yield this.getJsonWithRetry(credentialsURL, this.credentialsToken); + if (res.statusCode !== 200) { + throw new CredentialFetchingError(`fetching credentials: unexpected status code: ${res.statusCode}: ${JSON.stringify(res.result)}`); + } + if (!res.result) { + throw new CredentialFetchingError(`fetching credentials: missing response`); + } // Mask any secrets we've just retrieved from Actions logs - for (const credential of res.data.data.attributes.credentials) { + for (const credential of res.result.data.attributes.credentials) { if (credential.password) { core.setSecret(credential.password); } @@ -76490,41 +98145,73 @@ class ApiClient { core.setSecret(credential.token); } } - return res.data.data.attributes.credentials; + return res.result.data.attributes.credentials; } catch (error) { - if (axios_1.default.isAxiosError(error)) { - const err = error; - throw new CredentialFetchingError(`fetching credentials: received code ${(_a = err.response) === null || _a === void 0 ? void 0 : _a.status}: ${JSON.stringify((_b = err.response) === null || _b === void 0 ? void 0 : _b.data)}`); - } - else { + if (error instanceof CredentialFetchingError) { throw error; } + else if (error instanceof httpClient.HttpClientError) { + throw new CredentialFetchingError(`fetching credentials: unexpected status code: ${error.statusCode}: ${error.message}`); + } + else if (error instanceof Error) { + throw new CredentialFetchingError(`fetching credentials: ${error.name}: ${error.message}`); + } + throw error; } }); } reportJobError(error) { return __awaiter(this, void 0, void 0, function* () { - const recordErrorURL = `/update_jobs/${this.params.jobId}/record_update_job_error`; - const res = yield this.client.post(recordErrorURL, { data: error }, { - headers: { Authorization: this.params.jobToken } + const recordErrorURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/record_update_job_error`; + const res = yield this.client.postJson(recordErrorURL, { data: error }, { + ['Authorization']: this.jobToken }); - if (res.status !== 204) { - throw new Error(`Unexpected status code: ${res.status}`); + if (res.statusCode !== 204) { + throw new Error(`Unexpected status code: ${res.statusCode}`); } }); } markJobAsProcessed() { return __awaiter(this, void 0, void 0, function* () { - const markAsProcessedURL = `/update_jobs/${this.params.jobId}/mark_as_processed`; - const res = yield this.client.patch(markAsProcessedURL, { data: this.UnknownSha }, { - headers: { Authorization: this.params.jobToken } + const markAsProcessedURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/mark_as_processed`; + const res = yield this.client.patchJson(markAsProcessedURL, { data: this.UnknownSha }, { + ['Authorization']: this.jobToken }); - if (res.status !== 204) { - throw new Error(`Unexpected status code: ${res.status}`); + if (res.statusCode !== 204) { + throw new Error(`Unexpected status code: ${res.statusCode}`); } }); } + getJsonWithRetry(url, token) { + return __awaiter(this, void 0, void 0, function* () { + let attempt = 1; + const execute = () => __awaiter(this, void 0, void 0, function* () { + try { + return yield this.client.getJson(url, { + ['Authorization']: token + }); + } + catch (error) { + if (error instanceof httpClient.HttpClientError) { + if (error.statusCode >= 500 && error.statusCode <= 599) { + if (attempt >= 3) { + throw error; + } + core.warning(`Retrying failed request with status code: ${error.statusCode}`); + // exponential backoff + const delayMs = 1000 * Math.pow(2, attempt); + yield new Promise(resolve => setTimeout(resolve, delayMs)); + attempt++; + return execute(); + } + } + throw error; + } + }); + return execute(); + }); + } } exports.ApiClient = ApiClient; @@ -76576,11 +98263,12 @@ const utils_1 = __nccwpck_require__(1314); class ContainerRuntimeError extends Error { } exports.ContainerRuntimeError = ContainerRuntimeError; +const RWX_ALL = 0o777; exports.ContainerService = { storeInput(name, path, container, input) { return __awaiter(this, void 0, void 0, function* () { const tar = (0, tar_stream_1.pack)(); - tar.entry({ name }, JSON.stringify(input)); + tar.entry({ name, mode: RWX_ALL }, JSON.stringify(input)); tar.finalize(); yield container.putArchive(tar, { path }); }); @@ -76632,11 +98320,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.repositoryName = exports.PROXY_IMAGE_NAME = exports.UPDATER_IMAGE_NAME = void 0; +exports.digestName = exports.hasDigest = exports.repositoryName = exports.updaterImages = exports.updaterImageName = exports.PROXY_IMAGE_NAME = void 0; +// eslint-disable-next-line import/extensions const containers_json_1 = __importDefault(__nccwpck_require__(8708)); -exports.UPDATER_IMAGE_NAME = containers_json_1.default.updater; exports.PROXY_IMAGE_NAME = containers_json_1.default.proxy; -const imageNamePattern = '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))((:[a-zA-Z0-9._/-]+)|(@sha256:[a-zA-Z0-9]{64}))?$'; +function updaterImageName(packageManager) { + return containers_json_1.default[packageManager]; +} +exports.updaterImageName = updaterImageName; +const updaterRegex = /ghcr.io\/dependabot\/dependabot-updater-([\w+])/; +function updaterImages() { + return Object.values(containers_json_1.default).filter(image => image.match(updaterRegex)); +} +exports.updaterImages = updaterImages; +const imageNamePattern = '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))(:[a-zA-Z0-9._/-]+)?(?@sha256:[a-zA-Z0-9]{64})?$'; function repositoryName(imageName) { const match = imageName.match(imageNamePattern); if (match === null || match === void 0 ? void 0 : match.groups) { @@ -76647,236 +98344,34 @@ function repositoryName(imageName) { } } exports.repositoryName = repositoryName; - - -/***/ }), - -/***/ 2715: -/***/ (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 __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ImageService = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const dockerode_1 = __importDefault(__nccwpck_require__(4571)); -const endOfStream = (docker, stream) => __awaiter(void 0, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - docker.modem.followProgress(stream, (err) => err ? reject(err) : resolve(undefined)); - }); -}); -/** Fetch the configured updater image, if it isn't already available. */ -exports.ImageService = { - pull(imageName, force = false) { - return __awaiter(this, void 0, void 0, function* () { - /* - This method fetches images hosts on GitHub infrastructure. - - We expose the `fetch_image` utility method to allow us to pull in arbitrary images for unit tests. - */ - if (!(imageName.startsWith('ghcr.io/') || - imageName.startsWith('docker.pkg.github.com/'))) { - throw new Error('Only images distributed via docker.pkg.github.com or ghcr.io can be fetched'); - } - const docker = new dockerode_1.default(); - try { - const image = yield docker.getImage(imageName).inspect(); - if (!force) { - core.info(`Resolved ${imageName} to existing ${image.RepoDigests}`); - return; - } // else fallthrough to pull - } - catch (e) { - if (e instanceof Error && !e.message.includes('no such image')) { - throw e; - } // else fallthrough to pull - } - const auth = {}; // Images are public so not authentication info is required - yield this.fetchImage(imageName, auth, docker); - }); - }, - /* Retrieve the imageName using the auth details provided, if any */ - fetchImage(imageName, auth = {}, docker = new dockerode_1.default()) { - return __awaiter(this, void 0, void 0, function* () { - core.info(`Pulling image ${imageName}...`); - const stream = yield docker.pull(imageName, { authconfig: auth }); - yield endOfStream(docker, stream); - core.info(`Pulled image ${imageName}`); - }); - } -}; - - -/***/ }), - -/***/ 7063: -/***/ (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 __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.getJobParameters = exports.JobParameters = void 0; -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const core = __importStar(__nccwpck_require__(2186)); -const DYNAMIC = 'dynamic'; -const DEPENDABOT_ACTOR = 'dependabot[bot]'; -// JobParameters are the Action inputs required to execute the job -class JobParameters { - constructor(jobId, jobToken, credentialsToken, dependabotApiUrl, dependabotApiDockerUrl, workingDirectory) { - this.jobId = jobId; - this.jobToken = jobToken; - this.credentialsToken = credentialsToken; - this.dependabotApiUrl = dependabotApiUrl; - this.dependabotApiDockerUrl = dependabotApiDockerUrl; - this.workingDirectory = workingDirectory; - } -} -exports.JobParameters = JobParameters; -function getJobParameters(ctx) { - checkEnvironmentAndContext(ctx); - if (ctx.actor !== DEPENDABOT_ACTOR) { - core.warning('This workflow can only be triggered by Dependabot.'); - return null; - } - if (ctx.eventName === DYNAMIC) { - return fromWorkflowInputs(ctx); +function hasDigest(imageName) { + const match = imageName.match(imageNamePattern); + if (match === null || match === void 0 ? void 0 : match.groups) { + if (match === null || match === void 0 ? void 0 : match.groups['digest']) { + return true; + } + return false; } else { - core.warning(`Dependabot Updater Action does not support '${ctx.eventName}' events.`); - return null; + throw Error('invalid image name'); } } -exports.getJobParameters = getJobParameters; -function checkEnvironmentAndContext(ctx) { - let valid = true; - if (!ctx.actor) { - core.error('GITHUB_ACTOR is not defined'); - valid = false; - } - if (!ctx.eventName) { - core.error('GITHUB_EVENT_NAME is not defined'); - valid = false; - } - if (!process.env.GITHUB_WORKSPACE) { - core.error('GITHUB_WORKSPACE is not defined'); - valid = false; - } - if (!valid) { - throw new Error('Required Actions environment variables missing.'); +exports.hasDigest = hasDigest; +function digestName(imageName) { + const match = imageName.match(imageNamePattern); + if (match === null || match === void 0 ? void 0 : match.groups) { + return match.groups['repository'] + match.groups['digest']; } else { - return valid; - } -} -function fromWorkflowInputs(ctx) { - const evt = ctx.payload; - if (!evt.inputs) { - throw new Error('Event payload has no inputs'); - } - const dependabotApiDockerUrl = evt.inputs.dependabotApiDockerUrl || evt.inputs.dependabotApiUrl; - const workingDirectory = absoluteWorkingDirectory(evt.inputs.workingDirectory); - return new JobParameters(parseInt(evt.inputs.jobId, 10), evt.inputs.jobToken, evt.inputs.credentialsToken, evt.inputs.dependabotApiUrl, dependabotApiDockerUrl, workingDirectory); -} -function absoluteWorkingDirectory(workingDirectory) { - const workspace = process.env.GITHUB_WORKSPACE; - if (!workingDirectory) { - throw new Error('The workingDirectory input must not be blank.'); - } - if (!directoryExistsSync(workspace)) { - throw new Error('The GITHUB_WORKSPACE directory does not exist.'); - } - const fullPath = path_1.default.join(workspace, workingDirectory); - if (!directoryExistsSync(fullPath)) { - throw new Error(`The workingDirectory '${workingDirectory}' does not exist in GITHUB_WORKSPACE`); - } - return fullPath; -} -function directoryExistsSync(directoryPath) { - let stats; - try { - stats = fs_1.default.statSync(directoryPath); - return stats.isDirectory(); - } - catch (error) { - if (isNodeError(error) && error.code === 'ENOENT') { - return false; - } - else if (error instanceof Error) { - throw new Error(`Encountered an error when checking whether path '${directoryPath}' exists: ${error.message}`); - } + throw Error('invalid image name'); } - return false; -} -function isNodeError(error) { - return error instanceof Error; } +exports.digestName = digestName; /***/ }), -/***/ 399: +/***/ 2715: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -76917,10 +98412,238 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ImageService = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const dockerode_1 = __importDefault(__nccwpck_require__(4571)); +const endOfStream = (docker, stream) => __awaiter(void 0, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + docker.modem.followProgress(stream, (err) => err ? reject(err) : resolve(undefined)); + }); +}); +/** Fetch the configured updater image, if it isn't already available. */ +exports.ImageService = { + pull(imageName_1) { + return __awaiter(this, arguments, void 0, function* (imageName, force = false) { + /* + This method fetches images hosts on GitHub infrastructure. + + We expose the `fetch_image` utility method to allow us to pull in arbitrary images for unit tests. + */ + if (!(imageName.startsWith('ghcr.io/') || + imageName.startsWith('docker.pkg.github.com/'))) { + throw new Error('Only images distributed via docker.pkg.github.com or ghcr.io can be fetched'); + } + const docker = new dockerode_1.default(); + try { + const image = yield docker.getImage(imageName).inspect(); + if (!force) { + core.info(`Resolved ${imageName} to existing ${image.RepoDigests}`); + return; + } // else fallthrough to pull + } + catch (e) { + if (e instanceof Error && !e.message.includes('no such image')) { + throw e; + } // else fallthrough to pull + } + const auth = {}; // Images are public so not authentication info is required + yield this.fetchImage(imageName, auth, docker); + }); + }, + /* Retrieve the imageName using the auth details provided, if any */ + fetchImage(imageName_1) { + return __awaiter(this, arguments, void 0, function* (imageName, auth = {}, docker = new dockerode_1.default()) { + core.info(`Pulling image ${imageName}...`); + const stream = yield docker.pull(imageName, { authconfig: auth }); + yield endOfStream(docker, stream); + core.info(`Pulled image ${imageName}`); + }); + } +}; + + +/***/ }), + +/***/ 7063: +/***/ (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 __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.getJobParameters = exports.JobParameters = void 0; +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const core = __importStar(__nccwpck_require__(2186)); +const DYNAMIC = 'dynamic'; +const DEPENDABOT_ACTOR = 'dependabot[bot]'; +// JobParameters are the Action inputs required to execute the job +class JobParameters { + constructor(jobId, jobToken, credentialsToken, dependabotApiUrl, dependabotApiDockerUrl, updaterImage, workingDirectory) { + this.jobId = jobId; + this.jobToken = jobToken; + this.credentialsToken = credentialsToken; + this.dependabotApiUrl = dependabotApiUrl; + this.dependabotApiDockerUrl = dependabotApiDockerUrl; + this.updaterImage = updaterImage; + this.workingDirectory = workingDirectory; + } +} +exports.JobParameters = JobParameters; +function getJobParameters(ctx) { + checkEnvironmentAndContext(ctx); + if (ctx.actor !== DEPENDABOT_ACTOR) { + core.warning(`This workflow can only be triggered by Dependabot. Actor was '${ctx.actor}'.`); + return null; + } + if (process.env.GITHUB_TRIGGERING_ACTOR && + process.env.GITHUB_TRIGGERING_ACTOR !== DEPENDABOT_ACTOR) { + core.warning('Dependabot workflows cannot be re-run. Retrigger this update via Dependabot instead.'); + return null; + } + if (ctx.eventName === DYNAMIC) { + return fromWorkflowInputs(ctx); + } + else { + core.warning(`Dependabot Updater Action does not support '${ctx.eventName}' events.`); + return null; + } +} +exports.getJobParameters = getJobParameters; +function checkEnvironmentAndContext(ctx) { + let valid = true; + if (!ctx.actor) { + core.error('GITHUB_ACTOR is not defined'); + valid = false; + } + if (!ctx.eventName) { + core.error('GITHUB_EVENT_NAME is not defined'); + valid = false; + } + if (!process.env.GITHUB_WORKSPACE) { + core.error('GITHUB_WORKSPACE is not defined'); + valid = false; + } + if (!valid) { + throw new Error('Required Actions environment variables missing.'); + } + else { + return valid; + } +} +function fromWorkflowInputs(ctx) { + const evt = ctx.payload; + if (!evt.inputs) { + throw new Error('Event payload has no inputs'); + } + const dependabotApiDockerUrl = evt.inputs.dependabotApiDockerUrl || evt.inputs.dependabotApiUrl; + const workingDirectory = absoluteWorkingDirectory(evt.inputs.workingDirectory); + return new JobParameters(parseInt(evt.inputs.jobId, 10), evt.inputs.jobToken, evt.inputs.credentialsToken, evt.inputs.dependabotApiUrl, dependabotApiDockerUrl, evt.inputs.updaterImage, workingDirectory); +} +function absoluteWorkingDirectory(workingDirectory) { + const workspace = process.env.GITHUB_WORKSPACE; + if (!workingDirectory) { + throw new Error('The workingDirectory input must not be blank.'); + } + if (!directoryExistsSync(workspace)) { + throw new Error('The GITHUB_WORKSPACE directory does not exist.'); + } + const fullPath = path_1.default.join(workspace, workingDirectory); + if (!directoryExistsSync(fullPath)) { + throw new Error(`The workingDirectory '${workingDirectory}' does not exist in GITHUB_WORKSPACE`); + } + return fullPath; +} +function directoryExistsSync(directoryPath) { + let stats; + try { + stats = fs_1.default.statSync(directoryPath); + return stats.isDirectory(); + } + catch (error) { + if (isNodeError(error) && error.code === 'ENOENT') { + return false; + } + else if (error instanceof Error) { + throw new Error(`Encountered an error when checking whether path '${directoryPath}' exists: ${error.message}`); + } + } + return false; +} +function isNodeError(error) { + return error instanceof Error; +} + + +/***/ }), + +/***/ 399: +/***/ (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 __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.run = exports.DependabotErrorType = void 0; -const axios_1 = __importDefault(__nccwpck_require__(6545)); const core = __importStar(__nccwpck_require__(2186)); const github = __importStar(__nccwpck_require__(5438)); +const httpClient = __importStar(__nccwpck_require__(6255)); const api_client_1 = __nccwpck_require__(5707); const inputs_1 = __nccwpck_require__(7063); const image_service_1 = __nccwpck_require__(2715); @@ -76931,7 +98654,7 @@ var DependabotErrorType; DependabotErrorType["Unknown"] = "actions_workflow_unknown"; DependabotErrorType["Image"] = "actions_workflow_image"; DependabotErrorType["UpdateRun"] = "actions_workflow_updater"; -})(DependabotErrorType = exports.DependabotErrorType || (exports.DependabotErrorType = {})); +})(DependabotErrorType || (exports.DependabotErrorType = DependabotErrorType = {})); let jobId; function run(context) { return __awaiter(this, void 0, void 0, function* () { @@ -76945,22 +98668,41 @@ function run(context) { botSay('finished: nothing to do'); return; // TODO: This should be setNeutral in future } + // Use environment variables if set and not empty, otherwise use parameters. + // The param values of job token and credentials token are kept to support backwards compatibility. + const jobToken = process.env.GITHUB_DEPENDABOT_JOB_TOKEN || params.jobToken; + const credentialsToken = process.env.GITHUB_DEPENDABOT_CRED_TOKEN || params.credentialsToken; + // Validate jobToken and credentialsToken + if (!jobToken) { + const errorMessage = 'Github Dependabot job token is not set'; + botSay(`finished: ${errorMessage}`); + core.setFailed(errorMessage); + return; + } + if (!credentialsToken) { + const errorMessage = 'Github Dependabot credentials token is not set'; + botSay(`finished: ${errorMessage}`); + core.setFailed(errorMessage); + return; + } jobId = params.jobId; - core.setSecret(params.jobToken); - core.setSecret(params.credentialsToken); - const client = axios_1.default.create({ baseURL: params.dependabotApiUrl }); - const apiClient = new api_client_1.ApiClient(client, params); + core.setSecret(jobToken); + core.setSecret(credentialsToken); + const client = new httpClient.HttpClient('github/dependabot-action'); + const apiClient = new api_client_1.ApiClient(client, params, jobToken, credentialsToken); core.info('Fetching job details'); // If we fail to succeed in fetching the job details, we cannot be sure the job has entered a 'processing' state, - // so we do not try attempt to report back an exception if this fails and instead rely on the the workflow run + // so we do not try attempt to report back an exception if this fails and instead rely on the workflow run // webhook as it anticipates scenarios where jobs have failed while 'enqueued'. const details = yield apiClient.getJobDetails(); + // The dynamic workflow can specify which updater image to use. If it doesn't, fall back to the pinned version. + const updaterImage = params.updaterImage || (0, docker_tags_1.updaterImageName)(details['package-manager']); try { const credentials = yield apiClient.getCredentials(); - const updater = new updater_1.Updater(docker_tags_1.UPDATER_IMAGE_NAME, docker_tags_1.PROXY_IMAGE_NAME, apiClient, details, credentials, params.workingDirectory); + const updater = new updater_1.Updater(updaterImage, docker_tags_1.PROXY_IMAGE_NAME, apiClient, details, credentials, params.workingDirectory); core.startGroup('Pulling updater images'); try { - yield image_service_1.ImageService.pull(docker_tags_1.UPDATER_IMAGE_NAME); + yield image_service_1.ImageService.pull(updaterImage); yield image_service_1.ImageService.pull(docker_tags_1.PROXY_IMAGE_NAME); } catch (error) { @@ -76975,15 +98717,7 @@ function run(context) { yield updater.runUpdater(); } catch (error) { - // If we have encountered a UpdaterFetchError, the Updater will already have - // reported the error and marked the job as processed, so we only need to - // set an exit status. - if (error instanceof updater_1.UpdaterFetchError) { - setFailed('Dependabot was unable to retrieve the files required to perform the update', null); - botSay('finished: unable to fetch files'); - return; - } - else if (error instanceof Error) { + if (error instanceof Error) { yield failJob(apiClient, 'Dependabot encountered an error performing the update', error, DependabotErrorType.UpdateRun); return; } @@ -77014,8 +98748,8 @@ function run(context) { }); } exports.run = run; -function failJob(apiClient, message, error, errorType = DependabotErrorType.Unknown) { - return __awaiter(this, void 0, void 0, function* () { +function failJob(apiClient_1, message_1, error_1) { + return __awaiter(this, arguments, void 0, function* (apiClient, message, error, errorType = DependabotErrorType.Unknown) { yield apiClient.reportJobError({ 'error-type': errorType, 'error-details': { @@ -77038,7 +98772,7 @@ function setFailed(message, error) { } function dependabotJobHelp() { if (jobId) { - return `For more information see: ${dependabotJobUrl(jobId)} (write access required)`; + return `For more information see: ${dependabotJobUrl(jobId)} (write access to the repository is required to view the log)`; } else { return null; @@ -77102,7 +98836,6 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyBuilder = void 0; const fs_1 = __importDefault(__nccwpck_require__(7147)); const core = __importStar(__nccwpck_require__(2186)); -const crypto_1 = __importDefault(__nccwpck_require__(6113)); const container_service_1 = __nccwpck_require__(2429); const node_forge_1 = __nccwpck_require__(7655); const utils_1 = __nccwpck_require__(1314); @@ -77139,20 +98872,21 @@ const CERT_SUBJECT = [ } ]; class ProxyBuilder { - constructor(docker, proxyImage) { + constructor(docker, proxyImage, cachedMode) { this.docker = docker; this.proxyImage = proxyImage; + this.cachedMode = cachedMode; } - run(jobId, credentials) { + run(jobId, jobToken, dependabotApiUrl, credentials) { return __awaiter(this, void 0, void 0, function* () { const name = `dependabot-job-${jobId}-proxy`; - const config = this.buildProxyConfig(credentials, jobId); + const config = this.buildProxyConfig(credentials); const cert = config.ca.cert; const externalNetworkName = `dependabot-job-${jobId}-external-network`; const externalNetwork = yield this.ensureNetwork(externalNetworkName, false); const internalNetworkName = `dependabot-job-${jobId}-internal-network`; const internalNetwork = yield this.ensureNetwork(internalNetworkName, true); - const container = yield this.createContainer(jobId, name, externalNetwork, internalNetwork, internalNetworkName); + const container = yield this.createContainer(jobId, jobToken, dependabotApiUrl, name, externalNetwork, internalNetwork, internalNetworkName); yield container_service_1.ContainerService.storeInput(CONFIG_FILE_NAME, CONFIG_FILE_PATH, container, config); const customCAPath = this.customCAPath(); if (customCAPath) { @@ -77171,7 +98905,7 @@ class ProxyBuilder { if (containerInfo.State.Running === true) { const ipAddress = containerInfo.NetworkSettings.Networks[`${internalNetworkName}`] .IPAddress; - return `http://${config.proxy_auth.username}:${config.proxy_auth.password}@${ipAddress}:1080`; + return `http://${ipAddress}:1080`; } else { throw new Error("proxy container isn't running"); @@ -77186,14 +98920,13 @@ class ProxyBuilder { shutdown: () => __awaiter(this, void 0, void 0, function* () { yield container.stop(); yield container.remove(); - yield externalNetwork.remove(); - yield internalNetwork.remove(); + yield Promise.all([externalNetwork.remove(), internalNetwork.remove()]); }) }; }); } - ensureNetwork(name, internal = true) { - return __awaiter(this, void 0, void 0, function* () { + ensureNetwork(name_1) { + return __awaiter(this, arguments, void 0, function* (name, internal = true) { const networks = yield this.docker.listNetworks({ filters: JSON.stringify({ name: [name] }) }); @@ -77205,14 +98938,9 @@ class ProxyBuilder { } }); } - buildProxyConfig(credentials, jobId) { + buildProxyConfig(credentials) { const ca = this.generateCertificateAuthority(); - const password = crypto_1.default.randomBytes(20).toString('hex'); - const proxy_auth = { - username: `${jobId}`, - password - }; - const config = { all_credentials: credentials, ca, proxy_auth }; + const config = { all_credentials: credentials, ca }; return config; } generateCertificateAuthority() { @@ -77231,7 +98959,7 @@ class ProxyBuilder { const key = node_forge_1.pki.privateKeyToPem(keys.privateKey); return { cert: pem, key }; } - createContainer(jobId, containerName, externalNetwork, internalNetwork, internalNetworkName) { + createContainer(jobId, jobToken, dependabotApiUrl, containerName, externalNetwork, internalNetwork, internalNetworkName) { return __awaiter(this, void 0, void 0, function* () { const container = yield this.docker.createContainer({ Image: this.proxyImage, @@ -77242,7 +98970,10 @@ class ProxyBuilder { `http_proxy=${process.env.http_proxy || process.env.HTTP_PROXY || ''}`, `https_proxy=${process.env.https_proxy || process.env.HTTPS_PROXY || ''}`, `no_proxy=${process.env.no_proxy || process.env.NO_PROXY || ''}`, - `JOB_ID=${jobId}` + `JOB_ID=${jobId}`, + `JOB_TOKEN=${jobToken}`, + `PROXY_CACHE=${this.cachedMode ? 'true' : 'false'}`, + `DEPENDABOT_API_URL=${dependabotApiUrl}` ], Entrypoint: [ 'sh', @@ -77321,21 +99052,20 @@ const CA_CERT_INPUT_PATH = '/usr/local/share/ca-certificates'; const CA_CERT_FILENAME = 'dbot-ca.crt'; const UPDATER_MAX_MEMORY = 8 * 1024 * 1024 * 1024; // 8GB in bytes class UpdaterBuilder { - constructor(docker, jobParams, input, outputHostPath, proxy, repoHostPath, updaterImage) { + constructor(docker, jobParams, input, outputHostPath, proxy, updaterImage) { this.docker = docker; this.jobParams = jobParams; this.input = input; this.outputHostPath = outputHostPath; this.proxy = proxy; - this.repoHostPath = repoHostPath; this.updaterImage = updaterImage; } - run(containerName, updaterCommand) { + run(containerName) { return __awaiter(this, void 0, void 0, function* () { - const cmd = `(echo > /etc/ca-certificates.conf) &&\ - rm -Rf /usr/share/ca-certificates/ &&\ - /usr/sbin/update-ca-certificates &&\ - $DEPENDABOT_HOME/dependabot-updater/bin/run ${updaterCommand}`; + const cmd = `/usr/sbin/update-ca-certificates &&\ + mkdir -p ${JOB_OUTPUT_PATH} &&\ + $DEPENDABOT_HOME/dependabot-updater/bin/run fetch_files &&\ + $DEPENDABOT_HOME/dependabot-updater/bin/run update_files`; const proxyUrl = yield this.proxy.url(); const container = yield this.docker.createContainer({ Image: this.updaterImage, @@ -77345,7 +99075,7 @@ class UpdaterBuilder { Env: [ `GITHUB_ACTIONS=${process.env.GITHUB_ACTIONS}`, `DEPENDABOT_JOB_ID=${this.jobParams.jobId}`, - `DEPENDABOT_JOB_TOKEN=${this.jobParams.jobToken}`, + `DEPENDABOT_JOB_TOKEN=`, `DEPENDABOT_JOB_PATH=${JOB_INPUT_PATH}/${JOB_INPUT_FILENAME}`, `DEPENDABOT_OPEN_TIMEOUT_IN_SECONDS=15`, `DEPENDABOT_OUTPUT_PATH=${JOB_OUTPUT_PATH}/${JOB_OUTPUT_FILENAME}`, @@ -77356,22 +99086,18 @@ class UpdaterBuilder { `HTTP_PROXY=${proxyUrl}`, `https_proxy=${proxyUrl}`, `HTTPS_PROXY=${proxyUrl}`, - `ENABLE_CONNECTIVITY_CHECK=1` + `UPDATER_ONE_CONTAINER=1`, + `ENABLE_CONNECTIVITY_CHECK=${process.env.DEPENDABOT_ENABLE_CONNECTIVITY_CHECK || '1'}` ], - User: 'root', Cmd: ['sh', '-c', cmd], HostConfig: { Memory: UPDATER_MAX_MEMORY, - NetworkMode: this.proxy.networkName, - Binds: [ - `${this.outputHostPath}:${JOB_OUTPUT_PATH}:rw`, - `${this.repoHostPath}:${REPO_CONTENTS_PATH}:rw` - ] + NetworkMode: this.proxy.networkName } }); yield container_service_1.ContainerService.storeCert(CA_CERT_FILENAME, CA_CERT_INPUT_PATH, container, this.proxy.cert); yield container_service_1.ContainerService.storeInput(JOB_INPUT_FILENAME, JOB_INPUT_PATH, container, this.input); - core.info(`Created ${updaterCommand} container: ${container.id}`); + core.info(`Created container: ${container.id}`); return container; }); } @@ -77386,29 +99112,6 @@ exports.UpdaterBuilder = UpdaterBuilder; "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 __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -77422,22 +99125,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Updater = exports.UpdaterFetchError = void 0; -const core = __importStar(__nccwpck_require__(2186)); +exports.Updater = void 0; const dockerode_1 = __importDefault(__nccwpck_require__(4571)); const path_1 = __importDefault(__nccwpck_require__(1017)); const fs_1 = __importDefault(__nccwpck_require__(7147)); const container_service_1 = __nccwpck_require__(2429); -const utils_1 = __nccwpck_require__(1314); const proxy_1 = __nccwpck_require__(7364); const updater_builder_1 = __nccwpck_require__(1179); -class UpdaterFetchError extends Error { - constructor(msg) { - super(msg); - Object.setPrototypeOf(this, UpdaterFetchError.prototype); - } -} -exports.UpdaterFetchError = UpdaterFetchError; class Updater { constructor(updaterImage, proxyImage, apiClient, details, credentials, workingDirectory) { this.updaterImage = updaterImage; @@ -77455,14 +99149,15 @@ class Updater { */ runUpdater() { return __awaiter(this, void 0, void 0, function* () { + var _a; // Create required folders in the workingDirectory fs_1.default.mkdirSync(this.outputHostPath); - fs_1.default.mkdirSync(this.repoHostPath); - const proxy = yield new proxy_1.ProxyBuilder(this.docker, this.proxyImage).run(this.apiClient.params.jobId, this.credentials); + const cachedMode = ((_a = this.details.experiments) === null || _a === void 0 ? void 0 : _a.hasOwnProperty('proxy-cached')) === true; + const proxyBuilder = new proxy_1.ProxyBuilder(this.docker, this.proxyImage, cachedMode); + const proxy = yield proxyBuilder.run(this.apiClient.params.jobId, this.apiClient.getJobToken(), this.apiClient.params.dependabotApiUrl, this.credentials); yield proxy.container.start(); try { - const files = yield this.runFileFetcher(proxy); - yield this.runFileUpdater(proxy, files); + yield this.runUpdate(proxy); return true; } finally { @@ -77470,54 +99165,28 @@ class Updater { } }); } - runFileFetcher(proxy) { + runUpdate(proxy) { return __awaiter(this, void 0, void 0, function* () { - const name = `dependabot-job-${this.apiClient.params.jobId}-file-fetcher`; - const container = yield this.createContainer(proxy, name, 'fetch_files', { + const name = `dependabot-job-${this.apiClient.params.jobId}`; + const container = yield this.createContainer(proxy, name, { job: this.details }); yield container_service_1.ContainerService.run(container); - const outputPath = path_1.default.join(this.outputHostPath, 'output.json'); - if (!fs_1.default.existsSync(outputPath)) { - throw new UpdaterFetchError('No output.json created by the fetcher container'); - } - const fileFetcherSync = fs_1.default.readFileSync(outputPath).toString(); - const fileFetcherOutput = JSON.parse(fileFetcherSync); - const fetchedFiles = { - base_commit_sha: fileFetcherOutput.base_commit_sha, - base64_dependency_files: fileFetcherOutput.base64_dependency_files, - dependency_files: fileFetcherOutput.base64_dependency_files.map((file) => (0, utils_1.base64DecodeDependencyFile)(file)) - }; - return fetchedFiles; - }); - } - runFileUpdater(proxy, files) { - return __awaiter(this, void 0, void 0, function* () { - core.info(`Running update job ${this.apiClient.params.jobId}`); - const name = `dependabot-job-${this.apiClient.params.jobId}-updater`; - const containerInput = { - base_commit_sha: files.base_commit_sha, - base64_dependency_files: files.base64_dependency_files, - dependency_files: files.dependency_files, - job: this.details - }; - const container = yield this.createContainer(proxy, name, 'update_files', containerInput); - yield container_service_1.ContainerService.run(container); }); } - createContainer(proxy, containerName, updaterCommand, input) { + createContainer(proxy, containerName, input) { return __awaiter(this, void 0, void 0, function* () { - return new updater_builder_1.UpdaterBuilder(this.docker, this.apiClient.params, input, this.outputHostPath, proxy, this.repoHostPath, this.updaterImage).run(containerName, updaterCommand); + return new updater_builder_1.UpdaterBuilder(this.docker, this.apiClient.params, input, this.outputHostPath, proxy, this.updaterImage).run(containerName); }); } cleanup(proxy) { return __awaiter(this, void 0, void 0, function* () { yield proxy.shutdown(); if (fs_1.default.existsSync(this.outputHostPath)) { - fs_1.default.rmdirSync(this.outputHostPath, { recursive: true }); + fs_1.default.rmSync(this.outputHostPath, { recursive: true }); } if (fs_1.default.existsSync(this.repoHostPath)) { - fs_1.default.rmdirSync(this.repoHostPath, { recursive: true }); + fs_1.default.rmSync(this.repoHostPath, { recursive: true }); } }); } @@ -77581,19 +99250,19 @@ module.exports = require(__nccwpck_require__.ab + "lib/protocol/crypto/build/Rel /***/ }), -/***/ 2877: +/***/ 9491: /***/ ((module) => { -module.exports = eval("require")("encoding"); - +"use strict"; +module.exports = require("assert"); /***/ }), -/***/ 9491: +/***/ 852: /***/ ((module) => { "use strict"; -module.exports = require("assert"); +module.exports = require("async_hooks"); /***/ }), @@ -77613,6 +99282,14 @@ module.exports = require("child_process"); /***/ }), +/***/ 6206: +/***/ ((module) => { + +"use strict"; +module.exports = require("console"); + +/***/ }), + /***/ 2057: /***/ ((module) => { @@ -77629,6 +99306,14 @@ module.exports = require("crypto"); /***/ }), +/***/ 7643: +/***/ ((module) => { + +"use strict"; +module.exports = require("diagnostics_channel"); + +/***/ }), + /***/ 9523: /***/ ((module) => { @@ -77661,6 +99346,14 @@ module.exports = require("http"); /***/ }), +/***/ 5158: +/***/ ((module) => { + +"use strict"; +module.exports = require("http2"); + +/***/ }), + /***/ 5687: /***/ ((module) => { @@ -77677,6 +99370,30 @@ module.exports = require("net"); /***/ }), +/***/ 5673: +/***/ ((module) => { + +"use strict"; +module.exports = require("node:events"); + +/***/ }), + +/***/ 4492: +/***/ ((module) => { + +"use strict"; +module.exports = require("node:stream"); + +/***/ }), + +/***/ 7261: +/***/ ((module) => { + +"use strict"; +module.exports = require("node:util"); + +/***/ }), + /***/ 2037: /***/ ((module) => { @@ -77693,11 +99410,11 @@ module.exports = require("path"); /***/ }), -/***/ 5477: +/***/ 4074: /***/ ((module) => { "use strict"; -module.exports = require("punycode"); +module.exports = require("perf_hooks"); /***/ }), @@ -77717,6 +99434,14 @@ module.exports = require("stream"); /***/ }), +/***/ 5356: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream/web"); + +/***/ }), + /***/ 1576: /***/ ((module) => { @@ -77757,27 +99482,35 @@ module.exports = require("util"); /***/ }), -/***/ 9796: +/***/ 9830: /***/ ((module) => { "use strict"; -module.exports = require("zlib"); +module.exports = require("util/types"); /***/ }), -/***/ 8708: +/***/ 1267: +/***/ ((module) => { + +"use strict"; +module.exports = require("worker_threads"); + +/***/ }), + +/***/ 9796: /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"proxy":"ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy@sha256:4714e9c495d7af0a83347517703cf524e2793f58625e4285e323d5d890a7cfa4","updater":"ghcr.io/dependabot/dependabot-updater@sha256:85108a36530c8ee66027eb798b62aabe0b31d2972a902375ff9baf862777cb38"}'); +module.exports = require("zlib"); /***/ }), -/***/ 1907: +/***/ 8708: /***/ ((module) => { "use strict"; -module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]]'); +module.exports = JSON.parse('{"proxy":"ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy:v2.0.20241004183849@sha256:5e895b5edfaba72e99d0a19b43f386b18b65fc08a2d43af5aedd6360cda56842","bundler":"ghcr.io/dependabot/dependabot-updater-bundler:v2.0.20241107222650@sha256:3cf4cafa6016c78e372fb29cac35472ed261c57b084b326747429afee2199c1b","cargo":"ghcr.io/dependabot/dependabot-updater-cargo:v2.0.20241107222650@sha256:91f64f9e49c36fc5b683756997060565dff67c5e30a1d5588ade386d2a79c8ec","composer":"ghcr.io/dependabot/dependabot-updater-composer:v2.0.20241107222650@sha256:0fbb307c6e249c08498527b9c3ceb23b761dd9d55bcca2f74cd0ca81a8914740","pub":"ghcr.io/dependabot/dependabot-updater-pub:v2.0.20241107222650@sha256:ce2b994ba59765b847251036a7a66f7d32e6a7076ae455f80bb6bf8cad2f16fc","docker":"ghcr.io/dependabot/dependabot-updater-docker:v2.0.20241107222650@sha256:3d44776d7a87cc5fc4c9d61678b03d6efc388901702697e514ed70823b440aba","elm":"ghcr.io/dependabot/dependabot-updater-elm:v2.0.20241107222650@sha256:16e94bdb0144ef7398b66d81388d7eb437dd8f5b514171d13cb858cc171efa05","github_actions":"ghcr.io/dependabot/dependabot-updater-github-actions:v2.0.20241107222650@sha256:c58910178f005aecfbdc41e0610f76ded7a4c5dc333521a33b3d6985c2eb9dc0","submodules":"ghcr.io/dependabot/dependabot-updater-gitsubmodule:v2.0.20241107222650@sha256:2a6bc87850734c8e3116c7020d6681b49151e201c43a0b590288e812a0336023","go_modules":"ghcr.io/dependabot/dependabot-updater-gomod:v2.0.20241107222650@sha256:77980075afb1a74eae6f63764f1cb26fcd6e146c90ac91a9ed77db25da55a008","gradle":"ghcr.io/dependabot/dependabot-updater-gradle:v2.0.20241107222650@sha256:8108e23b0d3a76dacea69f3756c89a3d6d35bcca3c2f975a61c1bfde815d7ee9","maven":"ghcr.io/dependabot/dependabot-updater-maven:v2.0.20241107222650@sha256:eadf9c29977e411420ca3fa9bb89e79f0a49872a87c3cd718721714782144a0b","hex":"ghcr.io/dependabot/dependabot-updater-mix:v2.0.20241107222650@sha256:0460f703a613ff38dd2ad61ef7d079070f37cbbb14f57e764c9427a4ee46b831","nuget":"ghcr.io/dependabot/dependabot-updater-nuget:v2.0.20241107222650@sha256:d2f293e19cd21467c73d0d967febb865184f5059c8b40fa9d73cd05810267b10","npm_and_yarn":"ghcr.io/dependabot/dependabot-updater-npm:v2.0.20241107222650@sha256:f187a18dbf871c71124d59c970e551d76196384e8d266da70a9c8c6417cb88fc","pip":"ghcr.io/dependabot/dependabot-updater-pip:v2.0.20241107222650@sha256:3dc06304cabaa7839388fb7c87b2cfa7d3cddf6c648e810415b025f3498b084c","swift":"ghcr.io/dependabot/dependabot-updater-swift:v2.0.20241107141918@sha256:4935ce7bd14b783e4838a38e59c6e2eae25e0ca7b0a11cd779d04a064ba8b654","terraform":"ghcr.io/dependabot/dependabot-updater-terraform:v2.0.20241107222650@sha256:d28f3845ae8cf4cbf1ae0f8ea0622da31cd1035a0eda18a3229e125fba0d224c","devcontainers":"ghcr.io/dependabot/dependabot-updater-devcontainers:v2.0.20241107222650@sha256:5273198c7c9d2490c6c1147b0e79a7d5351a8fa6f4ad37fdfffe434b7b569c32"}'); /***/ }), @@ -77785,7 +99518,7 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"] /***/ ((module) => { "use strict"; -module.exports = {"i8":"1.6.0"}; +module.exports = {"i8":"1.15.0"}; /***/ }) diff --git a/dist/main/index.js.map b/dist/main/index.js.map index f74027d76..63e5553c8 100644 --- a/dist/main/index.js.map +++ b/dist/main/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5lBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxhBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxuCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnBA;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1WA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtHA;AACA;AACA;AACA;AACA;;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrIA;AACA;AACA;;;;;;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3iBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3YA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtKA;AACA;AACA;;;;;;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1dA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5jCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzyDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7jBA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChqDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClkCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACz5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACt+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/iCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/uCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5OA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3uCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/4DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3OA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzrIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3lFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzqGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnmCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1BA;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtSA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC79DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5hEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChsHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjkDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7rCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtyDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC18CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACt1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtSA;AACA;;;;;;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9PA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn1EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjBA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACzIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/BA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC7BA;AACA;;;;AEDA;AACA;AACA;AACA","sources":["../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/command.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/core.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/file-command.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/oidc-utils.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/path-utils.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/summary.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js","../webpack://dependabot-updater-action/./node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js","../webpack://dependabot-updater-action/./node_modules/@actions/github/lib/context.js","../webpack://dependabot-updater-action/./node_modules/@actions/github/lib/github.js","../webpack://dependabot-updater-action/./node_modules/@actions/github/lib/internal/utils.js","../webpack://dependabot-updater-action/./node_modules/@actions/github/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/@actions/http-client/index.js","../webpack://dependabot-updater-action/./node_modules/@actions/http-client/proxy.js","../webpack://dependabot-updater-action/./node_modules/@octokit/auth-token/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/@octokit/core/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/@octokit/endpoint/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/@octokit/graphql/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/@octokit/plugin-paginate-rest/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/@octokit/plugin-rest-endpoint-methods/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/@octokit/request-error/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/@octokit/request/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/errors.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/index.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/reader.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/types.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/ber/writer.js","../webpack://dependabot-updater-action/./node_modules/asn1/lib/index.js","../webpack://dependabot-updater-action/./node_modules/axios/index.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/adapters/http.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/adapters/xhr.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/axios.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/cancel/Cancel.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/cancel/CancelToken.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/cancel/isCancel.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/Axios.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/InterceptorManager.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/buildFullPath.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/createError.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/dispatchRequest.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/enhanceError.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/mergeConfig.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/settle.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/core/transformData.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/defaults.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/env/data.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/bind.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/buildURL.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/combineURLs.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/cookies.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/isAbsoluteURL.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/isAxiosError.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/isURLSameOrigin.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/normalizeHeaderName.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/parseHeaders.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/spread.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/helpers/validator.js","../webpack://dependabot-updater-action/./node_modules/axios/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/bcrypt-pbkdf/index.js","../webpack://dependabot-updater-action/./node_modules/before-after-hook/index.js","../webpack://dependabot-updater-action/./node_modules/before-after-hook/lib/add.js","../webpack://dependabot-updater-action/./node_modules/before-after-hook/lib/register.js","../webpack://dependabot-updater-action/./node_modules/before-after-hook/lib/remove.js","../webpack://dependabot-updater-action/./node_modules/bl/BufferList.js","../webpack://dependabot-updater-action/./node_modules/bl/bl.js","../webpack://dependabot-updater-action/./node_modules/chownr/chownr.js","../webpack://dependabot-updater-action/./node_modules/cpu-features/lib/index.js","../webpack://dependabot-updater-action/./node_modules/debug/src/browser.js","../webpack://dependabot-updater-action/./node_modules/debug/src/common.js","../webpack://dependabot-updater-action/./node_modules/debug/src/index.js","../webpack://dependabot-updater-action/./node_modules/debug/src/node.js","../webpack://dependabot-updater-action/./node_modules/deprecation/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/http.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/http_duplex.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/modem.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/ssh.js","../webpack://dependabot-updater-action/./node_modules/docker-modem/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/config.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/container.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/docker.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/exec.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/image.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/network.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/node.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/plugin.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/secret.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/service.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/task.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/util.js","../webpack://dependabot-updater-action/./node_modules/dockerode/lib/volume.js","../webpack://dependabot-updater-action/./node_modules/end-of-stream/index.js","../webpack://dependabot-updater-action/./node_modules/follow-redirects/debug.js","../webpack://dependabot-updater-action/./node_modules/follow-redirects/index.js","../webpack://dependabot-updater-action/./node_modules/fs-constants/index.js","../webpack://dependabot-updater-action/./node_modules/has-flag/index.js","../webpack://dependabot-updater-action/./node_modules/inherits/inherits.js","../webpack://dependabot-updater-action/./node_modules/inherits/inherits_browser.js","../webpack://dependabot-updater-action/./node_modules/is-plain-object/dist/is-plain-object.js","../webpack://dependabot-updater-action/./node_modules/mkdirp-classic/index.js","../webpack://dependabot-updater-action/./node_modules/ms/index.js","../webpack://dependabot-updater-action/./node_modules/node-fetch/lib/index.js","../webpack://dependabot-updater-action/./node_modules/node-fetch/node_modules/tr46/index.js","../webpack://dependabot-updater-action/./node_modules/node-fetch/node_modules/webidl-conversions/lib/index.js","../webpack://dependabot-updater-action/./node_modules/node-fetch/node_modules/whatwg-url/lib/URL-impl.js","../webpack://dependabot-updater-action/./node_modules/node-fetch/node_modules/whatwg-url/lib/URL.js","../webpack://dependabot-updater-action/./node_modules/node-fetch/node_modules/whatwg-url/lib/public-api.js","../webpack://dependabot-updater-action/./node_modules/node-fetch/node_modules/whatwg-url/lib/url-state-machine.js","../webpack://dependabot-updater-action/./node_modules/node-fetch/node_modules/whatwg-url/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/aes.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/aesCipherSuites.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/asn1-validator.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/asn1.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/baseN.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/cipher.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/cipherModes.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/des.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/ed25519.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/forge.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/hmac.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/index.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/jsbn.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/kem.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/log.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/md.all.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/md.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/md5.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/mgf.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/mgf1.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/oids.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pbe.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pbkdf2.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pem.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pkcs1.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pkcs12.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pkcs7.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pkcs7asn1.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pki.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/prime.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/prng.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/pss.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/random.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/rc2.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/rsa.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/sha1.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/sha256.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/sha512.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/ssh.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/tls.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/util.js","../webpack://dependabot-updater-action/./node_modules/node-forge/lib/x509.js","../webpack://dependabot-updater-action/./node_modules/once/once.js","../webpack://dependabot-updater-action/./node_modules/pump/index.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/errors.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_duplex.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_passthrough.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_readable.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_transform.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/_stream_writable.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/async_iterator.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/buffer_list.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/destroy.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/from.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/pipeline.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/state.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/lib/internal/streams/stream.js","../webpack://dependabot-updater-action/./node_modules/readable-stream/readable.js","../webpack://dependabot-updater-action/./node_modules/safer-buffer/safer.js","../webpack://dependabot-updater-action/./node_modules/split-ca/index.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/Channel.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/agent.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/client.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/http-agents.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/index.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/Protocol.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/SFTP.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/constants.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/crypto.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/crypto/poly1305.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/handlers.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/handlers.misc.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/kex.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/keyParser.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/node-fs-compat.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/utils.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/zlib.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/server.js","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/utils.js","../webpack://dependabot-updater-action/./node_modules/string_decoder/lib/string_decoder.js","../webpack://dependabot-updater-action/./node_modules/string_decoder/node_modules/safe-buffer/index.js","../webpack://dependabot-updater-action/./node_modules/supports-color/index.js","../webpack://dependabot-updater-action/./node_modules/tar-fs/index.js","../webpack://dependabot-updater-action/./node_modules/tar-stream/extract.js","../webpack://dependabot-updater-action/./node_modules/tar-stream/headers.js","../webpack://dependabot-updater-action/./node_modules/tar-stream/index.js","../webpack://dependabot-updater-action/./node_modules/tar-stream/pack.js","../webpack://dependabot-updater-action/./node_modules/tunnel/index.js","../webpack://dependabot-updater-action/./node_modules/tunnel/lib/tunnel.js","../webpack://dependabot-updater-action/./node_modules/tweetnacl/nacl-fast.js","../webpack://dependabot-updater-action/./node_modules/universal-user-agent/dist-node/index.js","../webpack://dependabot-updater-action/./node_modules/util-deprecate/node.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/index.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/md5.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/nil.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/parse.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/regex.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/rng.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/sha1.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/stringify.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v1.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v3.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v35.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v4.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/v5.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/validate.js","../webpack://dependabot-updater-action/./node_modules/uuid/dist/version.js","../webpack://dependabot-updater-action/./node_modules/wrappy/wrappy.js","../webpack://dependabot-updater-action/./src/api-client.ts","../webpack://dependabot-updater-action/./src/container-service.ts","../webpack://dependabot-updater-action/./src/docker-tags.ts","../webpack://dependabot-updater-action/./src/image-service.ts","../webpack://dependabot-updater-action/./src/inputs.ts","../webpack://dependabot-updater-action/./src/main.ts","../webpack://dependabot-updater-action/./src/proxy.ts","../webpack://dependabot-updater-action/./src/updater-builder.ts","../webpack://dependabot-updater-action/./src/updater.ts","../webpack://dependabot-updater-action/./src/utils.ts","../webpack://dependabot-updater-action/./node_modules/cpu-features/build/Release/cpufeatures.node","../webpack://dependabot-updater-action/./node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node","../webpack://dependabot-updater-action/./node_modules/@vercel/ncc/dist/ncc/@@notfound.js","../webpack://dependabot-updater-action/external node-commonjs \"assert\"","../webpack://dependabot-updater-action/external node-commonjs \"buffer\"","../webpack://dependabot-updater-action/external node-commonjs \"child_process\"","../webpack://dependabot-updater-action/external node-commonjs \"constants\"","../webpack://dependabot-updater-action/external node-commonjs \"crypto\"","../webpack://dependabot-updater-action/external node-commonjs \"dns\"","../webpack://dependabot-updater-action/external node-commonjs \"events\"","../webpack://dependabot-updater-action/external node-commonjs \"fs\"","../webpack://dependabot-updater-action/external node-commonjs \"http\"","../webpack://dependabot-updater-action/external node-commonjs \"https\"","../webpack://dependabot-updater-action/external node-commonjs \"net\"","../webpack://dependabot-updater-action/external node-commonjs \"os\"","../webpack://dependabot-updater-action/external node-commonjs \"path\"","../webpack://dependabot-updater-action/external node-commonjs \"punycode\"","../webpack://dependabot-updater-action/external node-commonjs \"querystring\"","../webpack://dependabot-updater-action/external node-commonjs \"stream\"","../webpack://dependabot-updater-action/external node-commonjs \"string_decoder\"","../webpack://dependabot-updater-action/external node-commonjs \"tls\"","../webpack://dependabot-updater-action/external node-commonjs \"tty\"","../webpack://dependabot-updater-action/external node-commonjs \"url\"","../webpack://dependabot-updater-action/external node-commonjs \"util\"","../webpack://dependabot-updater-action/external node-commonjs \"zlib\"","../webpack://dependabot-updater-action/webpack/bootstrap","../webpack://dependabot-updater-action/webpack/runtime/compat","../webpack://dependabot-updater-action/webpack/before-startup","../webpack://dependabot-updater-action/webpack/startup","../webpack://dependabot-updater-action/webpack/after-startup"],"sourcesContent":["\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issue = exports.issueCommand = void 0;\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\n/**\n * Commands\n *\n * Command Format:\n * ::name key=value,key=value::message\n *\n * Examples:\n * ::warning::This is the message\n * ::set-env name=MY_VAR::some value\n */\nfunction issueCommand(command, properties, message) {\n const cmd = new Command(command, properties, message);\n process.stdout.write(cmd.toString() + os.EOL);\n}\nexports.issueCommand = issueCommand;\nfunction issue(name, message = '') {\n issueCommand(name, {}, message);\n}\nexports.issue = issue;\nconst CMD_STRING = '::';\nclass Command {\n constructor(command, properties, message) {\n if (!command) {\n command = 'missing.command';\n }\n this.command = command;\n this.properties = properties;\n this.message = message;\n }\n toString() {\n let cmdStr = CMD_STRING + this.command;\n if (this.properties && Object.keys(this.properties).length > 0) {\n cmdStr += ' ';\n let first = true;\n for (const key in this.properties) {\n if (this.properties.hasOwnProperty(key)) {\n const val = this.properties[key];\n if (val) {\n if (first) {\n first = false;\n }\n else {\n cmdStr += ',';\n }\n cmdStr += `${key}=${escapeProperty(val)}`;\n }\n }\n }\n }\n cmdStr += `${CMD_STRING}${escapeData(this.message)}`;\n return cmdStr;\n }\n}\nfunction escapeData(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A');\n}\nfunction escapeProperty(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n}\n//# sourceMappingURL=command.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;\nconst command_1 = require(\"./command\");\nconst file_command_1 = require(\"./file-command\");\nconst utils_1 = require(\"./utils\");\nconst os = __importStar(require(\"os\"));\nconst path = __importStar(require(\"path\"));\nconst uuid_1 = require(\"uuid\");\nconst oidc_utils_1 = require(\"./oidc-utils\");\n/**\n * The code to exit an action\n */\nvar ExitCode;\n(function (ExitCode) {\n /**\n * A code indicating that the action was successful\n */\n ExitCode[ExitCode[\"Success\"] = 0] = \"Success\";\n /**\n * A code indicating that the action was a failure\n */\n ExitCode[ExitCode[\"Failure\"] = 1] = \"Failure\";\n})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));\n//-----------------------------------------------------------------------\n// Variables\n//-----------------------------------------------------------------------\n/**\n * Sets env variable for this action and future actions in the job\n * @param name the name of the variable to set\n * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction exportVariable(name, val) {\n const convertedVal = utils_1.toCommandValue(val);\n process.env[name] = convertedVal;\n const filePath = process.env['GITHUB_ENV'] || '';\n if (filePath) {\n const delimiter = `ghadelimiter_${uuid_1.v4()}`;\n // These should realistically never happen, but just in case someone finds a way to exploit uuid generation let's not allow keys or values that contain the delimiter.\n if (name.includes(delimiter)) {\n throw new Error(`Unexpected input: name should not contain the delimiter \"${delimiter}\"`);\n }\n if (convertedVal.includes(delimiter)) {\n throw new Error(`Unexpected input: value should not contain the delimiter \"${delimiter}\"`);\n }\n const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;\n file_command_1.issueCommand('ENV', commandValue);\n }\n else {\n command_1.issueCommand('set-env', { name }, convertedVal);\n }\n}\nexports.exportVariable = exportVariable;\n/**\n * Registers a secret which will get masked from logs\n * @param secret value of the secret\n */\nfunction setSecret(secret) {\n command_1.issueCommand('add-mask', {}, secret);\n}\nexports.setSecret = setSecret;\n/**\n * Prepends inputPath to the PATH (for this action and future actions)\n * @param inputPath\n */\nfunction addPath(inputPath) {\n const filePath = process.env['GITHUB_PATH'] || '';\n if (filePath) {\n file_command_1.issueCommand('PATH', inputPath);\n }\n else {\n command_1.issueCommand('add-path', {}, inputPath);\n }\n process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;\n}\nexports.addPath = addPath;\n/**\n * Gets the value of an input.\n * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.\n * Returns an empty string if the value is not defined.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string\n */\nfunction getInput(name, options) {\n const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';\n if (options && options.required && !val) {\n throw new Error(`Input required and not supplied: ${name}`);\n }\n if (options && options.trimWhitespace === false) {\n return val;\n }\n return val.trim();\n}\nexports.getInput = getInput;\n/**\n * Gets the values of an multiline input. Each value is also trimmed.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string[]\n *\n */\nfunction getMultilineInput(name, options) {\n const inputs = getInput(name, options)\n .split('\\n')\n .filter(x => x !== '');\n return inputs;\n}\nexports.getMultilineInput = getMultilineInput;\n/**\n * Gets the input value of the boolean type in the YAML 1.2 \"core schema\" specification.\n * Support boolean input list: `true | True | TRUE | false | False | FALSE` .\n * The return value is also in boolean type.\n * ref: https://yaml.org/spec/1.2/spec.html#id2804923\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns boolean\n */\nfunction getBooleanInput(name, options) {\n const trueValue = ['true', 'True', 'TRUE'];\n const falseValue = ['false', 'False', 'FALSE'];\n const val = getInput(name, options);\n if (trueValue.includes(val))\n return true;\n if (falseValue.includes(val))\n return false;\n throw new TypeError(`Input does not meet YAML 1.2 \"Core Schema\" specification: ${name}\\n` +\n `Support boolean input list: \\`true | True | TRUE | false | False | FALSE\\``);\n}\nexports.getBooleanInput = getBooleanInput;\n/**\n * Sets the value of an output.\n *\n * @param name name of the output to set\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setOutput(name, value) {\n process.stdout.write(os.EOL);\n command_1.issueCommand('set-output', { name }, value);\n}\nexports.setOutput = setOutput;\n/**\n * Enables or disables the echoing of commands into stdout for the rest of the step.\n * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.\n *\n */\nfunction setCommandEcho(enabled) {\n command_1.issue('echo', enabled ? 'on' : 'off');\n}\nexports.setCommandEcho = setCommandEcho;\n//-----------------------------------------------------------------------\n// Results\n//-----------------------------------------------------------------------\n/**\n * Sets the action status to failed.\n * When the action exits it will be with an exit code of 1\n * @param message add error issue message\n */\nfunction setFailed(message) {\n process.exitCode = ExitCode.Failure;\n error(message);\n}\nexports.setFailed = setFailed;\n//-----------------------------------------------------------------------\n// Logging Commands\n//-----------------------------------------------------------------------\n/**\n * Gets whether Actions Step Debug is on or not\n */\nfunction isDebug() {\n return process.env['RUNNER_DEBUG'] === '1';\n}\nexports.isDebug = isDebug;\n/**\n * Writes debug message to user log\n * @param message debug message\n */\nfunction debug(message) {\n command_1.issueCommand('debug', {}, message);\n}\nexports.debug = debug;\n/**\n * Adds an error issue\n * @param message error issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction error(message, properties = {}) {\n command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.error = error;\n/**\n * Adds a warning issue\n * @param message warning issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction warning(message, properties = {}) {\n command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.warning = warning;\n/**\n * Adds a notice issue\n * @param message notice issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction notice(message, properties = {}) {\n command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.notice = notice;\n/**\n * Writes info to log with console.log.\n * @param message info message\n */\nfunction info(message) {\n process.stdout.write(message + os.EOL);\n}\nexports.info = info;\n/**\n * Begin an output group.\n *\n * Output until the next `groupEnd` will be foldable in this group\n *\n * @param name The name of the output group\n */\nfunction startGroup(name) {\n command_1.issue('group', name);\n}\nexports.startGroup = startGroup;\n/**\n * End an output group.\n */\nfunction endGroup() {\n command_1.issue('endgroup');\n}\nexports.endGroup = endGroup;\n/**\n * Wrap an asynchronous function call in a group.\n *\n * Returns the same type as the function itself.\n *\n * @param name The name of the group\n * @param fn The function to wrap in the group\n */\nfunction group(name, fn) {\n return __awaiter(this, void 0, void 0, function* () {\n startGroup(name);\n let result;\n try {\n result = yield fn();\n }\n finally {\n endGroup();\n }\n return result;\n });\n}\nexports.group = group;\n//-----------------------------------------------------------------------\n// Wrapper action state\n//-----------------------------------------------------------------------\n/**\n * Saves state for current action, the state can only be retrieved by this action's post job execution.\n *\n * @param name name of the state to store\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction saveState(name, value) {\n command_1.issueCommand('save-state', { name }, value);\n}\nexports.saveState = saveState;\n/**\n * Gets the value of an state set by this action's main execution.\n *\n * @param name name of the state to get\n * @returns string\n */\nfunction getState(name) {\n return process.env[`STATE_${name}`] || '';\n}\nexports.getState = getState;\nfunction getIDToken(aud) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield oidc_utils_1.OidcClient.getIDToken(aud);\n });\n}\nexports.getIDToken = getIDToken;\n/**\n * Summary exports\n */\nvar summary_1 = require(\"./summary\");\nObject.defineProperty(exports, \"summary\", { enumerable: true, get: function () { return summary_1.summary; } });\n/**\n * @deprecated use core.summary\n */\nvar summary_2 = require(\"./summary\");\nObject.defineProperty(exports, \"markdownSummary\", { enumerable: true, get: function () { return summary_2.markdownSummary; } });\n/**\n * Path exports\n */\nvar path_utils_1 = require(\"./path-utils\");\nObject.defineProperty(exports, \"toPosixPath\", { enumerable: true, get: function () { return path_utils_1.toPosixPath; } });\nObject.defineProperty(exports, \"toWin32Path\", { enumerable: true, get: function () { return path_utils_1.toWin32Path; } });\nObject.defineProperty(exports, \"toPlatformPath\", { enumerable: true, get: function () { return path_utils_1.toPlatformPath; } });\n//# sourceMappingURL=core.js.map","\"use strict\";\n// For internal use, subject to change.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issueCommand = void 0;\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst fs = __importStar(require(\"fs\"));\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\nfunction issueCommand(command, message) {\n const filePath = process.env[`GITHUB_${command}`];\n if (!filePath) {\n throw new Error(`Unable to find environment variable for file command ${command}`);\n }\n if (!fs.existsSync(filePath)) {\n throw new Error(`Missing file at path: ${filePath}`);\n }\n fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {\n encoding: 'utf8'\n });\n}\nexports.issueCommand = issueCommand;\n//# sourceMappingURL=file-command.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OidcClient = void 0;\nconst http_client_1 = require(\"@actions/http-client\");\nconst auth_1 = require(\"@actions/http-client/lib/auth\");\nconst core_1 = require(\"./core\");\nclass OidcClient {\n static createHttpClient(allowRetry = true, maxRetry = 10) {\n const requestOptions = {\n allowRetries: allowRetry,\n maxRetries: maxRetry\n };\n return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);\n }\n static getRequestToken() {\n const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];\n if (!token) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');\n }\n return token;\n }\n static getIDTokenUrl() {\n const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];\n if (!runtimeUrl) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');\n }\n return runtimeUrl;\n }\n static getCall(id_token_url) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const httpclient = OidcClient.createHttpClient();\n const res = yield httpclient\n .getJson(id_token_url)\n .catch(error => {\n throw new Error(`Failed to get ID Token. \\n \n Error Code : ${error.statusCode}\\n \n Error Message: ${error.result.message}`);\n });\n const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;\n if (!id_token) {\n throw new Error('Response json body do not have ID Token field');\n }\n return id_token;\n });\n }\n static getIDToken(audience) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // New ID Token is requested from action service\n let id_token_url = OidcClient.getIDTokenUrl();\n if (audience) {\n const encodedAudience = encodeURIComponent(audience);\n id_token_url = `${id_token_url}&audience=${encodedAudience}`;\n }\n core_1.debug(`ID token url is ${id_token_url}`);\n const id_token = yield OidcClient.getCall(id_token_url);\n core_1.setSecret(id_token);\n return id_token;\n }\n catch (error) {\n throw new Error(`Error message: ${error.message}`);\n }\n });\n }\n}\nexports.OidcClient = OidcClient;\n//# sourceMappingURL=oidc-utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;\nconst path = __importStar(require(\"path\"));\n/**\n * toPosixPath converts the given path to the posix form. On Windows, \\\\ will be\n * replaced with /.\n *\n * @param pth. Path to transform.\n * @return string Posix path.\n */\nfunction toPosixPath(pth) {\n return pth.replace(/[\\\\]/g, '/');\n}\nexports.toPosixPath = toPosixPath;\n/**\n * toWin32Path converts the given path to the win32 form. On Linux, / will be\n * replaced with \\\\.\n *\n * @param pth. Path to transform.\n * @return string Win32 path.\n */\nfunction toWin32Path(pth) {\n return pth.replace(/[/]/g, '\\\\');\n}\nexports.toWin32Path = toWin32Path;\n/**\n * toPlatformPath converts the given path to a platform-specific path. It does\n * this by replacing instances of / and \\ with the platform-specific path\n * separator.\n *\n * @param pth The path to platformize.\n * @return string The platform-specific path.\n */\nfunction toPlatformPath(pth) {\n return pth.replace(/[/\\\\]/g, path.sep);\n}\nexports.toPlatformPath = toPlatformPath;\n//# sourceMappingURL=path-utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;\nconst os_1 = require(\"os\");\nconst fs_1 = require(\"fs\");\nconst { access, appendFile, writeFile } = fs_1.promises;\nexports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';\nexports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';\nclass Summary {\n constructor() {\n this._buffer = '';\n }\n /**\n * Finds the summary file path from the environment, rejects if env var is not found or file does not exist\n * Also checks r/w permissions.\n *\n * @returns step summary file path\n */\n filePath() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._filePath) {\n return this._filePath;\n }\n const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];\n if (!pathFromEnv) {\n throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);\n }\n try {\n yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);\n }\n catch (_a) {\n throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);\n }\n this._filePath = pathFromEnv;\n return this._filePath;\n });\n }\n /**\n * Wraps content in an HTML tag, adding any HTML attributes\n *\n * @param {string} tag HTML tag to wrap\n * @param {string | null} content content within the tag\n * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add\n *\n * @returns {string} content wrapped in HTML element\n */\n wrap(tag, content, attrs = {}) {\n const htmlAttrs = Object.entries(attrs)\n .map(([key, value]) => ` ${key}=\"${value}\"`)\n .join('');\n if (!content) {\n return `<${tag}${htmlAttrs}>`;\n }\n return `<${tag}${htmlAttrs}>${content}`;\n }\n /**\n * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.\n *\n * @param {SummaryWriteOptions} [options] (optional) options for write operation\n *\n * @returns {Promise} summary instance\n */\n write(options) {\n return __awaiter(this, void 0, void 0, function* () {\n const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);\n const filePath = yield this.filePath();\n const writeFunc = overwrite ? writeFile : appendFile;\n yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });\n return this.emptyBuffer();\n });\n }\n /**\n * Clears the summary buffer and wipes the summary file\n *\n * @returns {Summary} summary instance\n */\n clear() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.emptyBuffer().write({ overwrite: true });\n });\n }\n /**\n * Returns the current summary buffer as a string\n *\n * @returns {string} string of summary buffer\n */\n stringify() {\n return this._buffer;\n }\n /**\n * If the summary buffer is empty\n *\n * @returns {boolen} true if the buffer is empty\n */\n isEmptyBuffer() {\n return this._buffer.length === 0;\n }\n /**\n * Resets the summary buffer without writing to summary file\n *\n * @returns {Summary} summary instance\n */\n emptyBuffer() {\n this._buffer = '';\n return this;\n }\n /**\n * Adds raw text to the summary buffer\n *\n * @param {string} text content to add\n * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)\n *\n * @returns {Summary} summary instance\n */\n addRaw(text, addEOL = false) {\n this._buffer += text;\n return addEOL ? this.addEOL() : this;\n }\n /**\n * Adds the operating system-specific end-of-line marker to the buffer\n *\n * @returns {Summary} summary instance\n */\n addEOL() {\n return this.addRaw(os_1.EOL);\n }\n /**\n * Adds an HTML codeblock to the summary buffer\n *\n * @param {string} code content to render within fenced code block\n * @param {string} lang (optional) language to syntax highlight code\n *\n * @returns {Summary} summary instance\n */\n addCodeBlock(code, lang) {\n const attrs = Object.assign({}, (lang && { lang }));\n const element = this.wrap('pre', this.wrap('code', code), attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML list to the summary buffer\n *\n * @param {string[]} items list of items to render\n * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)\n *\n * @returns {Summary} summary instance\n */\n addList(items, ordered = false) {\n const tag = ordered ? 'ol' : 'ul';\n const listItems = items.map(item => this.wrap('li', item)).join('');\n const element = this.wrap(tag, listItems);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML table to the summary buffer\n *\n * @param {SummaryTableCell[]} rows table rows\n *\n * @returns {Summary} summary instance\n */\n addTable(rows) {\n const tableBody = rows\n .map(row => {\n const cells = row\n .map(cell => {\n if (typeof cell === 'string') {\n return this.wrap('td', cell);\n }\n const { header, data, colspan, rowspan } = cell;\n const tag = header ? 'th' : 'td';\n const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));\n return this.wrap(tag, data, attrs);\n })\n .join('');\n return this.wrap('tr', cells);\n })\n .join('');\n const element = this.wrap('table', tableBody);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds a collapsable HTML details element to the summary buffer\n *\n * @param {string} label text for the closed state\n * @param {string} content collapsable content\n *\n * @returns {Summary} summary instance\n */\n addDetails(label, content) {\n const element = this.wrap('details', this.wrap('summary', label) + content);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML image tag to the summary buffer\n *\n * @param {string} src path to the image you to embed\n * @param {string} alt text description of the image\n * @param {SummaryImageOptions} options (optional) addition image attributes\n *\n * @returns {Summary} summary instance\n */\n addImage(src, alt, options) {\n const { width, height } = options || {};\n const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));\n const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML section heading element\n *\n * @param {string} text heading text\n * @param {number | string} [level=1] (optional) the heading level, default: 1\n *\n * @returns {Summary} summary instance\n */\n addHeading(text, level) {\n const tag = `h${level}`;\n const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)\n ? tag\n : 'h1';\n const element = this.wrap(allowedTag, text);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML thematic break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addSeparator() {\n const element = this.wrap('hr', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML line break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addBreak() {\n const element = this.wrap('br', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML blockquote to the summary buffer\n *\n * @param {string} text quote text\n * @param {string} cite (optional) citation url\n *\n * @returns {Summary} summary instance\n */\n addQuote(text, cite) {\n const attrs = Object.assign({}, (cite && { cite }));\n const element = this.wrap('blockquote', text, attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML anchor tag to the summary buffer\n *\n * @param {string} text link text/content\n * @param {string} href hyperlink\n *\n * @returns {Summary} summary instance\n */\n addLink(text, href) {\n const element = this.wrap('a', text, { href });\n return this.addRaw(element).addEOL();\n }\n}\nconst _summary = new Summary();\n/**\n * @deprecated use `core.summary`\n */\nexports.markdownSummary = _summary;\nexports.summary = _summary;\n//# sourceMappingURL=summary.js.map","\"use strict\";\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toCommandProperties = exports.toCommandValue = void 0;\n/**\n * Sanitizes an input into a string so it can be passed into issueCommand safely\n * @param input input to sanitize into a string\n */\nfunction toCommandValue(input) {\n if (input === null || input === undefined) {\n return '';\n }\n else if (typeof input === 'string' || input instanceof String) {\n return input;\n }\n return JSON.stringify(input);\n}\nexports.toCommandValue = toCommandValue;\n/**\n *\n * @param annotationProperties\n * @returns The command properties to send with the actual annotation command\n * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646\n */\nfunction toCommandProperties(annotationProperties) {\n if (!Object.keys(annotationProperties).length) {\n return {};\n }\n return {\n title: annotationProperties.title,\n file: annotationProperties.file,\n line: annotationProperties.startLine,\n endLine: annotationProperties.endLine,\n col: annotationProperties.startColumn,\n endColumn: annotationProperties.endColumn\n };\n}\nexports.toCommandProperties = toCommandProperties;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;\nclass BasicCredentialHandler {\n constructor(username, password) {\n this.username = username;\n this.password = password;\n }\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BasicCredentialHandler = BasicCredentialHandler;\nclass BearerCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Bearer ${this.token}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BearerCredentialHandler = BearerCredentialHandler;\nclass PersonalAccessTokenCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;\n//# sourceMappingURL=auth.js.map","\"use strict\";\n/* eslint-disable @typescript-eslint/no-explicit-any */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;\nconst http = __importStar(require(\"http\"));\nconst https = __importStar(require(\"https\"));\nconst pm = __importStar(require(\"./proxy\"));\nconst tunnel = __importStar(require(\"tunnel\"));\nvar HttpCodes;\n(function (HttpCodes) {\n HttpCodes[HttpCodes[\"OK\"] = 200] = \"OK\";\n HttpCodes[HttpCodes[\"MultipleChoices\"] = 300] = \"MultipleChoices\";\n HttpCodes[HttpCodes[\"MovedPermanently\"] = 301] = \"MovedPermanently\";\n HttpCodes[HttpCodes[\"ResourceMoved\"] = 302] = \"ResourceMoved\";\n HttpCodes[HttpCodes[\"SeeOther\"] = 303] = \"SeeOther\";\n HttpCodes[HttpCodes[\"NotModified\"] = 304] = \"NotModified\";\n HttpCodes[HttpCodes[\"UseProxy\"] = 305] = \"UseProxy\";\n HttpCodes[HttpCodes[\"SwitchProxy\"] = 306] = \"SwitchProxy\";\n HttpCodes[HttpCodes[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n HttpCodes[HttpCodes[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n HttpCodes[HttpCodes[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpCodes[HttpCodes[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpCodes[HttpCodes[\"PaymentRequired\"] = 402] = \"PaymentRequired\";\n HttpCodes[HttpCodes[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpCodes[HttpCodes[\"NotFound\"] = 404] = \"NotFound\";\n HttpCodes[HttpCodes[\"MethodNotAllowed\"] = 405] = \"MethodNotAllowed\";\n HttpCodes[HttpCodes[\"NotAcceptable\"] = 406] = \"NotAcceptable\";\n HttpCodes[HttpCodes[\"ProxyAuthenticationRequired\"] = 407] = \"ProxyAuthenticationRequired\";\n HttpCodes[HttpCodes[\"RequestTimeout\"] = 408] = \"RequestTimeout\";\n HttpCodes[HttpCodes[\"Conflict\"] = 409] = \"Conflict\";\n HttpCodes[HttpCodes[\"Gone\"] = 410] = \"Gone\";\n HttpCodes[HttpCodes[\"TooManyRequests\"] = 429] = \"TooManyRequests\";\n HttpCodes[HttpCodes[\"InternalServerError\"] = 500] = \"InternalServerError\";\n HttpCodes[HttpCodes[\"NotImplemented\"] = 501] = \"NotImplemented\";\n HttpCodes[HttpCodes[\"BadGateway\"] = 502] = \"BadGateway\";\n HttpCodes[HttpCodes[\"ServiceUnavailable\"] = 503] = \"ServiceUnavailable\";\n HttpCodes[HttpCodes[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));\nvar Headers;\n(function (Headers) {\n Headers[\"Accept\"] = \"accept\";\n Headers[\"ContentType\"] = \"content-type\";\n})(Headers = exports.Headers || (exports.Headers = {}));\nvar MediaTypes;\n(function (MediaTypes) {\n MediaTypes[\"ApplicationJson\"] = \"application/json\";\n})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));\n/**\n * Returns the proxy URL, depending upon the supplied url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\nfunction getProxyUrl(serverUrl) {\n const proxyUrl = pm.getProxyUrl(new URL(serverUrl));\n return proxyUrl ? proxyUrl.href : '';\n}\nexports.getProxyUrl = getProxyUrl;\nconst HttpRedirectCodes = [\n HttpCodes.MovedPermanently,\n HttpCodes.ResourceMoved,\n HttpCodes.SeeOther,\n HttpCodes.TemporaryRedirect,\n HttpCodes.PermanentRedirect\n];\nconst HttpResponseRetryCodes = [\n HttpCodes.BadGateway,\n HttpCodes.ServiceUnavailable,\n HttpCodes.GatewayTimeout\n];\nconst RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];\nconst ExponentialBackoffCeiling = 10;\nconst ExponentialBackoffTimeSlice = 5;\nclass HttpClientError extends Error {\n constructor(message, statusCode) {\n super(message);\n this.name = 'HttpClientError';\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, HttpClientError.prototype);\n }\n}\nexports.HttpClientError = HttpClientError;\nclass HttpClientResponse {\n constructor(message) {\n this.message = message;\n }\n readBody() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n let output = Buffer.alloc(0);\n this.message.on('data', (chunk) => {\n output = Buffer.concat([output, chunk]);\n });\n this.message.on('end', () => {\n resolve(output.toString());\n });\n }));\n });\n }\n}\nexports.HttpClientResponse = HttpClientResponse;\nfunction isHttps(requestUrl) {\n const parsedUrl = new URL(requestUrl);\n return parsedUrl.protocol === 'https:';\n}\nexports.isHttps = isHttps;\nclass HttpClient {\n constructor(userAgent, handlers, requestOptions) {\n this._ignoreSslError = false;\n this._allowRedirects = true;\n this._allowRedirectDowngrade = false;\n this._maxRedirects = 50;\n this._allowRetries = false;\n this._maxRetries = 1;\n this._keepAlive = false;\n this._disposed = false;\n this.userAgent = userAgent;\n this.handlers = handlers || [];\n this.requestOptions = requestOptions;\n if (requestOptions) {\n if (requestOptions.ignoreSslError != null) {\n this._ignoreSslError = requestOptions.ignoreSslError;\n }\n this._socketTimeout = requestOptions.socketTimeout;\n if (requestOptions.allowRedirects != null) {\n this._allowRedirects = requestOptions.allowRedirects;\n }\n if (requestOptions.allowRedirectDowngrade != null) {\n this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;\n }\n if (requestOptions.maxRedirects != null) {\n this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);\n }\n if (requestOptions.keepAlive != null) {\n this._keepAlive = requestOptions.keepAlive;\n }\n if (requestOptions.allowRetries != null) {\n this._allowRetries = requestOptions.allowRetries;\n }\n if (requestOptions.maxRetries != null) {\n this._maxRetries = requestOptions.maxRetries;\n }\n }\n }\n options(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});\n });\n }\n get(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('GET', requestUrl, null, additionalHeaders || {});\n });\n }\n del(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('DELETE', requestUrl, null, additionalHeaders || {});\n });\n }\n post(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('POST', requestUrl, data, additionalHeaders || {});\n });\n }\n patch(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PATCH', requestUrl, data, additionalHeaders || {});\n });\n }\n put(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PUT', requestUrl, data, additionalHeaders || {});\n });\n }\n head(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('HEAD', requestUrl, null, additionalHeaders || {});\n });\n }\n sendStream(verb, requestUrl, stream, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request(verb, requestUrl, stream, additionalHeaders);\n });\n }\n /**\n * Gets a typed object from an endpoint\n * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise\n */\n getJson(requestUrl, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n const res = yield this.get(requestUrl, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n postJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.post(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n putJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.put(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n patchJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.patch(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n /**\n * Makes a raw http request.\n * All other methods such as get, post, patch, and request ultimately call this.\n * Prefer get, del, post and patch\n */\n request(verb, requestUrl, data, headers) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._disposed) {\n throw new Error('Client has already been disposed.');\n }\n const parsedUrl = new URL(requestUrl);\n let info = this._prepareRequest(verb, parsedUrl, headers);\n // Only perform retries on reads since writes may not be idempotent.\n const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)\n ? this._maxRetries + 1\n : 1;\n let numTries = 0;\n let response;\n do {\n response = yield this.requestRaw(info, data);\n // Check if it's an authentication challenge\n if (response &&\n response.message &&\n response.message.statusCode === HttpCodes.Unauthorized) {\n let authenticationHandler;\n for (const handler of this.handlers) {\n if (handler.canHandleAuthentication(response)) {\n authenticationHandler = handler;\n break;\n }\n }\n if (authenticationHandler) {\n return authenticationHandler.handleAuthentication(this, info, data);\n }\n else {\n // We have received an unauthorized response but have no handlers to handle it.\n // Let the response return to the caller.\n return response;\n }\n }\n let redirectsRemaining = this._maxRedirects;\n while (response.message.statusCode &&\n HttpRedirectCodes.includes(response.message.statusCode) &&\n this._allowRedirects &&\n redirectsRemaining > 0) {\n const redirectUrl = response.message.headers['location'];\n if (!redirectUrl) {\n // if there's no location to redirect to, we won't\n break;\n }\n const parsedRedirectUrl = new URL(redirectUrl);\n if (parsedUrl.protocol === 'https:' &&\n parsedUrl.protocol !== parsedRedirectUrl.protocol &&\n !this._allowRedirectDowngrade) {\n throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');\n }\n // we need to finish reading the response before reassigning response\n // which will leak the open socket.\n yield response.readBody();\n // strip authorization header if redirected to a different hostname\n if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {\n for (const header in headers) {\n // header names are case insensitive\n if (header.toLowerCase() === 'authorization') {\n delete headers[header];\n }\n }\n }\n // let's make the request with the new redirectUrl\n info = this._prepareRequest(verb, parsedRedirectUrl, headers);\n response = yield this.requestRaw(info, data);\n redirectsRemaining--;\n }\n if (!response.message.statusCode ||\n !HttpResponseRetryCodes.includes(response.message.statusCode)) {\n // If not a retry code, return immediately instead of retrying\n return response;\n }\n numTries += 1;\n if (numTries < maxTries) {\n yield response.readBody();\n yield this._performExponentialBackoff(numTries);\n }\n } while (numTries < maxTries);\n return response;\n });\n }\n /**\n * Needs to be called if keepAlive is set to true in request options.\n */\n dispose() {\n if (this._agent) {\n this._agent.destroy();\n }\n this._disposed = true;\n }\n /**\n * Raw request.\n * @param info\n * @param data\n */\n requestRaw(info, data) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n function callbackForResult(err, res) {\n if (err) {\n reject(err);\n }\n else if (!res) {\n // If `err` is not passed, then `res` must be passed.\n reject(new Error('Unknown error'));\n }\n else {\n resolve(res);\n }\n }\n this.requestRawWithCallback(info, data, callbackForResult);\n });\n });\n }\n /**\n * Raw request with callback.\n * @param info\n * @param data\n * @param onResult\n */\n requestRawWithCallback(info, data, onResult) {\n if (typeof data === 'string') {\n if (!info.options.headers) {\n info.options.headers = {};\n }\n info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');\n }\n let callbackCalled = false;\n function handleResult(err, res) {\n if (!callbackCalled) {\n callbackCalled = true;\n onResult(err, res);\n }\n }\n const req = info.httpModule.request(info.options, (msg) => {\n const res = new HttpClientResponse(msg);\n handleResult(undefined, res);\n });\n let socket;\n req.on('socket', sock => {\n socket = sock;\n });\n // If we ever get disconnected, we want the socket to timeout eventually\n req.setTimeout(this._socketTimeout || 3 * 60000, () => {\n if (socket) {\n socket.end();\n }\n handleResult(new Error(`Request timeout: ${info.options.path}`));\n });\n req.on('error', function (err) {\n // err has statusCode property\n // res should have headers\n handleResult(err);\n });\n if (data && typeof data === 'string') {\n req.write(data, 'utf8');\n }\n if (data && typeof data !== 'string') {\n data.on('close', function () {\n req.end();\n });\n data.pipe(req);\n }\n else {\n req.end();\n }\n }\n /**\n * Gets an http agent. This function is useful when you need an http agent that handles\n * routing through a proxy server - depending upon the url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\n getAgent(serverUrl) {\n const parsedUrl = new URL(serverUrl);\n return this._getAgent(parsedUrl);\n }\n _prepareRequest(method, requestUrl, headers) {\n const info = {};\n info.parsedUrl = requestUrl;\n const usingSsl = info.parsedUrl.protocol === 'https:';\n info.httpModule = usingSsl ? https : http;\n const defaultPort = usingSsl ? 443 : 80;\n info.options = {};\n info.options.host = info.parsedUrl.hostname;\n info.options.port = info.parsedUrl.port\n ? parseInt(info.parsedUrl.port)\n : defaultPort;\n info.options.path =\n (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');\n info.options.method = method;\n info.options.headers = this._mergeHeaders(headers);\n if (this.userAgent != null) {\n info.options.headers['user-agent'] = this.userAgent;\n }\n info.options.agent = this._getAgent(info.parsedUrl);\n // gives handlers an opportunity to participate\n if (this.handlers) {\n for (const handler of this.handlers) {\n handler.prepareRequest(info.options);\n }\n }\n return info;\n }\n _mergeHeaders(headers) {\n if (this.requestOptions && this.requestOptions.headers) {\n return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));\n }\n return lowercaseKeys(headers || {});\n }\n _getExistingOrDefaultHeader(additionalHeaders, header, _default) {\n let clientHeader;\n if (this.requestOptions && this.requestOptions.headers) {\n clientHeader = lowercaseKeys(this.requestOptions.headers)[header];\n }\n return additionalHeaders[header] || clientHeader || _default;\n }\n _getAgent(parsedUrl) {\n let agent;\n const proxyUrl = pm.getProxyUrl(parsedUrl);\n const useProxy = proxyUrl && proxyUrl.hostname;\n if (this._keepAlive && useProxy) {\n agent = this._proxyAgent;\n }\n if (this._keepAlive && !useProxy) {\n agent = this._agent;\n }\n // if agent is already assigned use that agent.\n if (agent) {\n return agent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n let maxSockets = 100;\n if (this.requestOptions) {\n maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;\n }\n // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.\n if (proxyUrl && proxyUrl.hostname) {\n const agentOptions = {\n maxSockets,\n keepAlive: this._keepAlive,\n proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {\n proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`\n })), { host: proxyUrl.hostname, port: proxyUrl.port })\n };\n let tunnelAgent;\n const overHttps = proxyUrl.protocol === 'https:';\n if (usingSsl) {\n tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;\n }\n else {\n tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;\n }\n agent = tunnelAgent(agentOptions);\n this._proxyAgent = agent;\n }\n // if reusing agent across request and tunneling agent isn't assigned create a new agent\n if (this._keepAlive && !agent) {\n const options = { keepAlive: this._keepAlive, maxSockets };\n agent = usingSsl ? new https.Agent(options) : new http.Agent(options);\n this._agent = agent;\n }\n // if not using private agent and tunnel agent isn't setup then use global agent\n if (!agent) {\n agent = usingSsl ? https.globalAgent : http.globalAgent;\n }\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n agent.options = Object.assign(agent.options || {}, {\n rejectUnauthorized: false\n });\n }\n return agent;\n }\n _performExponentialBackoff(retryNumber) {\n return __awaiter(this, void 0, void 0, function* () {\n retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);\n const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);\n return new Promise(resolve => setTimeout(() => resolve(), ms));\n });\n }\n _processResponse(res, options) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n const statusCode = res.message.statusCode || 0;\n const response = {\n statusCode,\n result: null,\n headers: {}\n };\n // not found leads to null obj returned\n if (statusCode === HttpCodes.NotFound) {\n resolve(response);\n }\n // get the result from the body\n function dateTimeDeserializer(key, value) {\n if (typeof value === 'string') {\n const a = new Date(value);\n if (!isNaN(a.valueOf())) {\n return a;\n }\n }\n return value;\n }\n let obj;\n let contents;\n try {\n contents = yield res.readBody();\n if (contents && contents.length > 0) {\n if (options && options.deserializeDates) {\n obj = JSON.parse(contents, dateTimeDeserializer);\n }\n else {\n obj = JSON.parse(contents);\n }\n response.result = obj;\n }\n response.headers = res.message.headers;\n }\n catch (err) {\n // Invalid resource (contents not json); leaving result obj null\n }\n // note that 3xx redirects are handled by the http layer.\n if (statusCode > 299) {\n let msg;\n // if exception/error in body, attempt to get better error\n if (obj && obj.message) {\n msg = obj.message;\n }\n else if (contents && contents.length > 0) {\n // it may be the case that the exception is in the body message as string\n msg = contents;\n }\n else {\n msg = `Failed request: (${statusCode})`;\n }\n const err = new HttpClientError(msg, statusCode);\n err.result = response.result;\n reject(err);\n }\n else {\n resolve(response);\n }\n }));\n });\n }\n}\nexports.HttpClient = HttpClient;\nconst lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.checkBypass = exports.getProxyUrl = void 0;\nfunction getProxyUrl(reqUrl) {\n const usingSsl = reqUrl.protocol === 'https:';\n if (checkBypass(reqUrl)) {\n return undefined;\n }\n const proxyVar = (() => {\n if (usingSsl) {\n return process.env['https_proxy'] || process.env['HTTPS_PROXY'];\n }\n else {\n return process.env['http_proxy'] || process.env['HTTP_PROXY'];\n }\n })();\n if (proxyVar) {\n return new URL(proxyVar);\n }\n else {\n return undefined;\n }\n}\nexports.getProxyUrl = getProxyUrl;\nfunction checkBypass(reqUrl) {\n if (!reqUrl.hostname) {\n return false;\n }\n const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';\n if (!noProxy) {\n return false;\n }\n // Determine the request port\n let reqPort;\n if (reqUrl.port) {\n reqPort = Number(reqUrl.port);\n }\n else if (reqUrl.protocol === 'http:') {\n reqPort = 80;\n }\n else if (reqUrl.protocol === 'https:') {\n reqPort = 443;\n }\n // Format the request hostname and hostname with port\n const upperReqHosts = [reqUrl.hostname.toUpperCase()];\n if (typeof reqPort === 'number') {\n upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);\n }\n // Compare request host against noproxy\n for (const upperNoProxyItem of noProxy\n .split(',')\n .map(x => x.trim().toUpperCase())\n .filter(x => x)) {\n if (upperReqHosts.some(x => x === upperNoProxyItem)) {\n return true;\n }\n }\n return false;\n}\nexports.checkBypass = checkBypass;\n//# sourceMappingURL=proxy.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Context = void 0;\nconst fs_1 = require(\"fs\");\nconst os_1 = require(\"os\");\nclass Context {\n /**\n * Hydrate the context from the environment\n */\n constructor() {\n var _a, _b, _c;\n this.payload = {};\n if (process.env.GITHUB_EVENT_PATH) {\n if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) {\n this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));\n }\n else {\n const path = process.env.GITHUB_EVENT_PATH;\n process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`);\n }\n }\n this.eventName = process.env.GITHUB_EVENT_NAME;\n this.sha = process.env.GITHUB_SHA;\n this.ref = process.env.GITHUB_REF;\n this.workflow = process.env.GITHUB_WORKFLOW;\n this.action = process.env.GITHUB_ACTION;\n this.actor = process.env.GITHUB_ACTOR;\n this.job = process.env.GITHUB_JOB;\n this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10);\n this.runId = parseInt(process.env.GITHUB_RUN_ID, 10);\n this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`;\n this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`;\n this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`;\n }\n get issue() {\n const payload = this.payload;\n return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number });\n }\n get repo() {\n if (process.env.GITHUB_REPOSITORY) {\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');\n return { owner, repo };\n }\n if (this.payload.repository) {\n return {\n owner: this.payload.repository.owner.login,\n repo: this.payload.repository.name\n };\n }\n throw new Error(\"context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'\");\n }\n}\nexports.Context = Context;\n//# sourceMappingURL=context.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokit = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst utils_1 = require(\"./utils\");\nexports.context = new Context.Context();\n/**\n * Returns a hydrated octokit ready to use for GitHub Actions\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokit(token, options) {\n return new utils_1.GitHub(utils_1.getOctokitOptions(token, options));\n}\nexports.getOctokit = getOctokit;\n//# sourceMappingURL=github.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0;\nconst httpClient = __importStar(require(\"@actions/http-client\"));\nfunction getAuthString(token, options) {\n if (!token && !options.auth) {\n throw new Error('Parameter token or opts.auth is required');\n }\n else if (token && options.auth) {\n throw new Error('Parameters token and opts.auth may not both be specified');\n }\n return typeof options.auth === 'string' ? options.auth : `token ${token}`;\n}\nexports.getAuthString = getAuthString;\nfunction getProxyAgent(destinationUrl) {\n const hc = new httpClient.HttpClient();\n return hc.getAgent(destinationUrl);\n}\nexports.getProxyAgent = getProxyAgent;\nfunction getApiBaseUrl() {\n return process.env['GITHUB_API_URL'] || 'https://api.github.com';\n}\nexports.getApiBaseUrl = getApiBaseUrl;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokitOptions = exports.GitHub = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst Utils = __importStar(require(\"./internal/utils\"));\n// octokit + plugins\nconst core_1 = require(\"@octokit/core\");\nconst plugin_rest_endpoint_methods_1 = require(\"@octokit/plugin-rest-endpoint-methods\");\nconst plugin_paginate_rest_1 = require(\"@octokit/plugin-paginate-rest\");\nexports.context = new Context.Context();\nconst baseUrl = Utils.getApiBaseUrl();\nconst defaults = {\n baseUrl,\n request: {\n agent: Utils.getProxyAgent(baseUrl)\n }\n};\nexports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults);\n/**\n * Convience function to correctly format Octokit Options to pass into the constructor.\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokitOptions(token, options) {\n const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller\n // Auth\n const auth = Utils.getAuthString(token, opts);\n if (auth) {\n opts.auth = auth;\n }\n return opts;\n}\nexports.getOctokitOptions = getOctokitOptions;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst http = require(\"http\");\nconst https = require(\"https\");\nconst pm = require(\"./proxy\");\nlet tunnel;\nvar HttpCodes;\n(function (HttpCodes) {\n HttpCodes[HttpCodes[\"OK\"] = 200] = \"OK\";\n HttpCodes[HttpCodes[\"MultipleChoices\"] = 300] = \"MultipleChoices\";\n HttpCodes[HttpCodes[\"MovedPermanently\"] = 301] = \"MovedPermanently\";\n HttpCodes[HttpCodes[\"ResourceMoved\"] = 302] = \"ResourceMoved\";\n HttpCodes[HttpCodes[\"SeeOther\"] = 303] = \"SeeOther\";\n HttpCodes[HttpCodes[\"NotModified\"] = 304] = \"NotModified\";\n HttpCodes[HttpCodes[\"UseProxy\"] = 305] = \"UseProxy\";\n HttpCodes[HttpCodes[\"SwitchProxy\"] = 306] = \"SwitchProxy\";\n HttpCodes[HttpCodes[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n HttpCodes[HttpCodes[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n HttpCodes[HttpCodes[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpCodes[HttpCodes[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpCodes[HttpCodes[\"PaymentRequired\"] = 402] = \"PaymentRequired\";\n HttpCodes[HttpCodes[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpCodes[HttpCodes[\"NotFound\"] = 404] = \"NotFound\";\n HttpCodes[HttpCodes[\"MethodNotAllowed\"] = 405] = \"MethodNotAllowed\";\n HttpCodes[HttpCodes[\"NotAcceptable\"] = 406] = \"NotAcceptable\";\n HttpCodes[HttpCodes[\"ProxyAuthenticationRequired\"] = 407] = \"ProxyAuthenticationRequired\";\n HttpCodes[HttpCodes[\"RequestTimeout\"] = 408] = \"RequestTimeout\";\n HttpCodes[HttpCodes[\"Conflict\"] = 409] = \"Conflict\";\n HttpCodes[HttpCodes[\"Gone\"] = 410] = \"Gone\";\n HttpCodes[HttpCodes[\"TooManyRequests\"] = 429] = \"TooManyRequests\";\n HttpCodes[HttpCodes[\"InternalServerError\"] = 500] = \"InternalServerError\";\n HttpCodes[HttpCodes[\"NotImplemented\"] = 501] = \"NotImplemented\";\n HttpCodes[HttpCodes[\"BadGateway\"] = 502] = \"BadGateway\";\n HttpCodes[HttpCodes[\"ServiceUnavailable\"] = 503] = \"ServiceUnavailable\";\n HttpCodes[HttpCodes[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));\nvar Headers;\n(function (Headers) {\n Headers[\"Accept\"] = \"accept\";\n Headers[\"ContentType\"] = \"content-type\";\n})(Headers = exports.Headers || (exports.Headers = {}));\nvar MediaTypes;\n(function (MediaTypes) {\n MediaTypes[\"ApplicationJson\"] = \"application/json\";\n})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));\n/**\n * Returns the proxy URL, depending upon the supplied url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\nfunction getProxyUrl(serverUrl) {\n let proxyUrl = pm.getProxyUrl(new URL(serverUrl));\n return proxyUrl ? proxyUrl.href : '';\n}\nexports.getProxyUrl = getProxyUrl;\nconst HttpRedirectCodes = [\n HttpCodes.MovedPermanently,\n HttpCodes.ResourceMoved,\n HttpCodes.SeeOther,\n HttpCodes.TemporaryRedirect,\n HttpCodes.PermanentRedirect\n];\nconst HttpResponseRetryCodes = [\n HttpCodes.BadGateway,\n HttpCodes.ServiceUnavailable,\n HttpCodes.GatewayTimeout\n];\nconst RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];\nconst ExponentialBackoffCeiling = 10;\nconst ExponentialBackoffTimeSlice = 5;\nclass HttpClientError extends Error {\n constructor(message, statusCode) {\n super(message);\n this.name = 'HttpClientError';\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, HttpClientError.prototype);\n }\n}\nexports.HttpClientError = HttpClientError;\nclass HttpClientResponse {\n constructor(message) {\n this.message = message;\n }\n readBody() {\n return new Promise(async (resolve, reject) => {\n let output = Buffer.alloc(0);\n this.message.on('data', (chunk) => {\n output = Buffer.concat([output, chunk]);\n });\n this.message.on('end', () => {\n resolve(output.toString());\n });\n });\n }\n}\nexports.HttpClientResponse = HttpClientResponse;\nfunction isHttps(requestUrl) {\n let parsedUrl = new URL(requestUrl);\n return parsedUrl.protocol === 'https:';\n}\nexports.isHttps = isHttps;\nclass HttpClient {\n constructor(userAgent, handlers, requestOptions) {\n this._ignoreSslError = false;\n this._allowRedirects = true;\n this._allowRedirectDowngrade = false;\n this._maxRedirects = 50;\n this._allowRetries = false;\n this._maxRetries = 1;\n this._keepAlive = false;\n this._disposed = false;\n this.userAgent = userAgent;\n this.handlers = handlers || [];\n this.requestOptions = requestOptions;\n if (requestOptions) {\n if (requestOptions.ignoreSslError != null) {\n this._ignoreSslError = requestOptions.ignoreSslError;\n }\n this._socketTimeout = requestOptions.socketTimeout;\n if (requestOptions.allowRedirects != null) {\n this._allowRedirects = requestOptions.allowRedirects;\n }\n if (requestOptions.allowRedirectDowngrade != null) {\n this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;\n }\n if (requestOptions.maxRedirects != null) {\n this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);\n }\n if (requestOptions.keepAlive != null) {\n this._keepAlive = requestOptions.keepAlive;\n }\n if (requestOptions.allowRetries != null) {\n this._allowRetries = requestOptions.allowRetries;\n }\n if (requestOptions.maxRetries != null) {\n this._maxRetries = requestOptions.maxRetries;\n }\n }\n }\n options(requestUrl, additionalHeaders) {\n return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});\n }\n get(requestUrl, additionalHeaders) {\n return this.request('GET', requestUrl, null, additionalHeaders || {});\n }\n del(requestUrl, additionalHeaders) {\n return this.request('DELETE', requestUrl, null, additionalHeaders || {});\n }\n post(requestUrl, data, additionalHeaders) {\n return this.request('POST', requestUrl, data, additionalHeaders || {});\n }\n patch(requestUrl, data, additionalHeaders) {\n return this.request('PATCH', requestUrl, data, additionalHeaders || {});\n }\n put(requestUrl, data, additionalHeaders) {\n return this.request('PUT', requestUrl, data, additionalHeaders || {});\n }\n head(requestUrl, additionalHeaders) {\n return this.request('HEAD', requestUrl, null, additionalHeaders || {});\n }\n sendStream(verb, requestUrl, stream, additionalHeaders) {\n return this.request(verb, requestUrl, stream, additionalHeaders);\n }\n /**\n * Gets a typed object from an endpoint\n * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise\n */\n async getJson(requestUrl, additionalHeaders = {}) {\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n let res = await this.get(requestUrl, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async postJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.post(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async putJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.put(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async patchJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.patch(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n /**\n * Makes a raw http request.\n * All other methods such as get, post, patch, and request ultimately call this.\n * Prefer get, del, post and patch\n */\n async request(verb, requestUrl, data, headers) {\n if (this._disposed) {\n throw new Error('Client has already been disposed.');\n }\n let parsedUrl = new URL(requestUrl);\n let info = this._prepareRequest(verb, parsedUrl, headers);\n // Only perform retries on reads since writes may not be idempotent.\n let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1\n ? this._maxRetries + 1\n : 1;\n let numTries = 0;\n let response;\n while (numTries < maxTries) {\n response = await this.requestRaw(info, data);\n // Check if it's an authentication challenge\n if (response &&\n response.message &&\n response.message.statusCode === HttpCodes.Unauthorized) {\n let authenticationHandler;\n for (let i = 0; i < this.handlers.length; i++) {\n if (this.handlers[i].canHandleAuthentication(response)) {\n authenticationHandler = this.handlers[i];\n break;\n }\n }\n if (authenticationHandler) {\n return authenticationHandler.handleAuthentication(this, info, data);\n }\n else {\n // We have received an unauthorized response but have no handlers to handle it.\n // Let the response return to the caller.\n return response;\n }\n }\n let redirectsRemaining = this._maxRedirects;\n while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&\n this._allowRedirects &&\n redirectsRemaining > 0) {\n const redirectUrl = response.message.headers['location'];\n if (!redirectUrl) {\n // if there's no location to redirect to, we won't\n break;\n }\n let parsedRedirectUrl = new URL(redirectUrl);\n if (parsedUrl.protocol == 'https:' &&\n parsedUrl.protocol != parsedRedirectUrl.protocol &&\n !this._allowRedirectDowngrade) {\n throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');\n }\n // we need to finish reading the response before reassigning response\n // which will leak the open socket.\n await response.readBody();\n // strip authorization header if redirected to a different hostname\n if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {\n for (let header in headers) {\n // header names are case insensitive\n if (header.toLowerCase() === 'authorization') {\n delete headers[header];\n }\n }\n }\n // let's make the request with the new redirectUrl\n info = this._prepareRequest(verb, parsedRedirectUrl, headers);\n response = await this.requestRaw(info, data);\n redirectsRemaining--;\n }\n if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {\n // If not a retry code, return immediately instead of retrying\n return response;\n }\n numTries += 1;\n if (numTries < maxTries) {\n await response.readBody();\n await this._performExponentialBackoff(numTries);\n }\n }\n return response;\n }\n /**\n * Needs to be called if keepAlive is set to true in request options.\n */\n dispose() {\n if (this._agent) {\n this._agent.destroy();\n }\n this._disposed = true;\n }\n /**\n * Raw request.\n * @param info\n * @param data\n */\n requestRaw(info, data) {\n return new Promise((resolve, reject) => {\n let callbackForResult = function (err, res) {\n if (err) {\n reject(err);\n }\n resolve(res);\n };\n this.requestRawWithCallback(info, data, callbackForResult);\n });\n }\n /**\n * Raw request with callback.\n * @param info\n * @param data\n * @param onResult\n */\n requestRawWithCallback(info, data, onResult) {\n let socket;\n if (typeof data === 'string') {\n info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');\n }\n let callbackCalled = false;\n let handleResult = (err, res) => {\n if (!callbackCalled) {\n callbackCalled = true;\n onResult(err, res);\n }\n };\n let req = info.httpModule.request(info.options, (msg) => {\n let res = new HttpClientResponse(msg);\n handleResult(null, res);\n });\n req.on('socket', sock => {\n socket = sock;\n });\n // If we ever get disconnected, we want the socket to timeout eventually\n req.setTimeout(this._socketTimeout || 3 * 60000, () => {\n if (socket) {\n socket.end();\n }\n handleResult(new Error('Request timeout: ' + info.options.path), null);\n });\n req.on('error', function (err) {\n // err has statusCode property\n // res should have headers\n handleResult(err, null);\n });\n if (data && typeof data === 'string') {\n req.write(data, 'utf8');\n }\n if (data && typeof data !== 'string') {\n data.on('close', function () {\n req.end();\n });\n data.pipe(req);\n }\n else {\n req.end();\n }\n }\n /**\n * Gets an http agent. This function is useful when you need an http agent that handles\n * routing through a proxy server - depending upon the url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\n getAgent(serverUrl) {\n let parsedUrl = new URL(serverUrl);\n return this._getAgent(parsedUrl);\n }\n _prepareRequest(method, requestUrl, headers) {\n const info = {};\n info.parsedUrl = requestUrl;\n const usingSsl = info.parsedUrl.protocol === 'https:';\n info.httpModule = usingSsl ? https : http;\n const defaultPort = usingSsl ? 443 : 80;\n info.options = {};\n info.options.host = info.parsedUrl.hostname;\n info.options.port = info.parsedUrl.port\n ? parseInt(info.parsedUrl.port)\n : defaultPort;\n info.options.path =\n (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');\n info.options.method = method;\n info.options.headers = this._mergeHeaders(headers);\n if (this.userAgent != null) {\n info.options.headers['user-agent'] = this.userAgent;\n }\n info.options.agent = this._getAgent(info.parsedUrl);\n // gives handlers an opportunity to participate\n if (this.handlers) {\n this.handlers.forEach(handler => {\n handler.prepareRequest(info.options);\n });\n }\n return info;\n }\n _mergeHeaders(headers) {\n const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n if (this.requestOptions && this.requestOptions.headers) {\n return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));\n }\n return lowercaseKeys(headers || {});\n }\n _getExistingOrDefaultHeader(additionalHeaders, header, _default) {\n const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n let clientHeader;\n if (this.requestOptions && this.requestOptions.headers) {\n clientHeader = lowercaseKeys(this.requestOptions.headers)[header];\n }\n return additionalHeaders[header] || clientHeader || _default;\n }\n _getAgent(parsedUrl) {\n let agent;\n let proxyUrl = pm.getProxyUrl(parsedUrl);\n let useProxy = proxyUrl && proxyUrl.hostname;\n if (this._keepAlive && useProxy) {\n agent = this._proxyAgent;\n }\n if (this._keepAlive && !useProxy) {\n agent = this._agent;\n }\n // if agent is already assigned use that agent.\n if (!!agent) {\n return agent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n let maxSockets = 100;\n if (!!this.requestOptions) {\n maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;\n }\n if (useProxy) {\n // If using proxy, need tunnel\n if (!tunnel) {\n tunnel = require('tunnel');\n }\n const agentOptions = {\n maxSockets: maxSockets,\n keepAlive: this._keepAlive,\n proxy: {\n ...((proxyUrl.username || proxyUrl.password) && {\n proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`\n }),\n host: proxyUrl.hostname,\n port: proxyUrl.port\n }\n };\n let tunnelAgent;\n const overHttps = proxyUrl.protocol === 'https:';\n if (usingSsl) {\n tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;\n }\n else {\n tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;\n }\n agent = tunnelAgent(agentOptions);\n this._proxyAgent = agent;\n }\n // if reusing agent across request and tunneling agent isn't assigned create a new agent\n if (this._keepAlive && !agent) {\n const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };\n agent = usingSsl ? new https.Agent(options) : new http.Agent(options);\n this._agent = agent;\n }\n // if not using private agent and tunnel agent isn't setup then use global agent\n if (!agent) {\n agent = usingSsl ? https.globalAgent : http.globalAgent;\n }\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n agent.options = Object.assign(agent.options || {}, {\n rejectUnauthorized: false\n });\n }\n return agent;\n }\n _performExponentialBackoff(retryNumber) {\n retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);\n const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);\n return new Promise(resolve => setTimeout(() => resolve(), ms));\n }\n static dateTimeDeserializer(key, value) {\n if (typeof value === 'string') {\n let a = new Date(value);\n if (!isNaN(a.valueOf())) {\n return a;\n }\n }\n return value;\n }\n async _processResponse(res, options) {\n return new Promise(async (resolve, reject) => {\n const statusCode = res.message.statusCode;\n const response = {\n statusCode: statusCode,\n result: null,\n headers: {}\n };\n // not found leads to null obj returned\n if (statusCode == HttpCodes.NotFound) {\n resolve(response);\n }\n let obj;\n let contents;\n // get the result from the body\n try {\n contents = await res.readBody();\n if (contents && contents.length > 0) {\n if (options && options.deserializeDates) {\n obj = JSON.parse(contents, HttpClient.dateTimeDeserializer);\n }\n else {\n obj = JSON.parse(contents);\n }\n response.result = obj;\n }\n response.headers = res.message.headers;\n }\n catch (err) {\n // Invalid resource (contents not json); leaving result obj null\n }\n // note that 3xx redirects are handled by the http layer.\n if (statusCode > 299) {\n let msg;\n // if exception/error in body, attempt to get better error\n if (obj && obj.message) {\n msg = obj.message;\n }\n else if (contents && contents.length > 0) {\n // it may be the case that the exception is in the body message as string\n msg = contents;\n }\n else {\n msg = 'Failed request: (' + statusCode + ')';\n }\n let err = new HttpClientError(msg, statusCode);\n err.result = response.result;\n reject(err);\n }\n else {\n resolve(response);\n }\n });\n }\n}\nexports.HttpClient = HttpClient;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction getProxyUrl(reqUrl) {\n let usingSsl = reqUrl.protocol === 'https:';\n let proxyUrl;\n if (checkBypass(reqUrl)) {\n return proxyUrl;\n }\n let proxyVar;\n if (usingSsl) {\n proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];\n }\n else {\n proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];\n }\n if (proxyVar) {\n proxyUrl = new URL(proxyVar);\n }\n return proxyUrl;\n}\nexports.getProxyUrl = getProxyUrl;\nfunction checkBypass(reqUrl) {\n if (!reqUrl.hostname) {\n return false;\n }\n let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';\n if (!noProxy) {\n return false;\n }\n // Determine the request port\n let reqPort;\n if (reqUrl.port) {\n reqPort = Number(reqUrl.port);\n }\n else if (reqUrl.protocol === 'http:') {\n reqPort = 80;\n }\n else if (reqUrl.protocol === 'https:') {\n reqPort = 443;\n }\n // Format the request hostname and hostname with port\n let upperReqHosts = [reqUrl.hostname.toUpperCase()];\n if (typeof reqPort === 'number') {\n upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);\n }\n // Compare request host against noproxy\n for (let upperNoProxyItem of noProxy\n .split(',')\n .map(x => x.trim().toUpperCase())\n .filter(x => x)) {\n if (upperReqHosts.some(x => x === upperNoProxyItem)) {\n return true;\n }\n }\n return false;\n}\nexports.checkBypass = checkBypass;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nasync function auth(token) {\n const tokenType = token.split(/\\./).length === 3 ? \"app\" : /^v\\d+\\./.test(token) ? \"installation\" : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType\n };\n}\n\n/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nfunction withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n\n return `token ${token}`;\n}\n\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n\nconst createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\n\nexports.createTokenAuth = createTokenAuth;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar universalUserAgent = require('universal-user-agent');\nvar beforeAfterHook = require('before-after-hook');\nvar request = require('@octokit/request');\nvar graphql = require('@octokit/graphql');\nvar authToken = require('@octokit/auth-token');\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}\n\nfunction _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = _objectWithoutPropertiesLoose(source, excluded);\n\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\nconst VERSION = \"3.4.0\";\n\nclass Octokit {\n constructor(options = {}) {\n const hook = new beforeAfterHook.Collection();\n const requestDefaults = {\n baseUrl: request.request.endpoint.DEFAULTS.baseUrl,\n headers: {},\n request: Object.assign({}, options.request, {\n // @ts-ignore internal usage only, no need to type\n hook: hook.bind(null, \"request\")\n }),\n mediaType: {\n previews: [],\n format: \"\"\n }\n }; // prepend default user agent with `options.userAgent` if set\n\n requestDefaults.headers[\"user-agent\"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(\" \");\n\n if (options.baseUrl) {\n requestDefaults.baseUrl = options.baseUrl;\n }\n\n if (options.previews) {\n requestDefaults.mediaType.previews = options.previews;\n }\n\n if (options.timeZone) {\n requestDefaults.headers[\"time-zone\"] = options.timeZone;\n }\n\n this.request = request.request.defaults(requestDefaults);\n this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults);\n this.log = Object.assign({\n debug: () => {},\n info: () => {},\n warn: console.warn.bind(console),\n error: console.error.bind(console)\n }, options.log);\n this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance\n // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered.\n // (2) If only `options.auth` is set, use the default token authentication strategy.\n // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.\n // TODO: type `options.auth` based on `options.authStrategy`.\n\n if (!options.authStrategy) {\n if (!options.auth) {\n // (1)\n this.auth = async () => ({\n type: \"unauthenticated\"\n });\n } else {\n // (2)\n const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\\_(ツ)_/¯\n\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n } else {\n const {\n authStrategy\n } = options,\n otherOptions = _objectWithoutProperties(options, [\"authStrategy\"]);\n\n const auth = authStrategy(Object.assign({\n request: this.request,\n log: this.log,\n // we pass the current octokit instance as well as its constructor options\n // to allow for authentication strategies that return a new octokit instance\n // that shares the same internal state as the current one. The original\n // requirement for this was the \"event-octokit\" authentication strategy\n // of https://github.com/probot/octokit-auth-probot.\n octokit: this,\n octokitOptions: otherOptions\n }, options.auth)); // @ts-ignore ¯\\_(ツ)_/¯\n\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n } // apply plugins\n // https://stackoverflow.com/a/16345172\n\n\n const classConstructor = this.constructor;\n classConstructor.plugins.forEach(plugin => {\n Object.assign(this, plugin(this, options));\n });\n }\n\n static defaults(defaults) {\n const OctokitWithDefaults = class extends this {\n constructor(...args) {\n const options = args[0] || {};\n\n if (typeof defaults === \"function\") {\n super(defaults(options));\n return;\n }\n\n super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {\n userAgent: `${options.userAgent} ${defaults.userAgent}`\n } : null));\n }\n\n };\n return OctokitWithDefaults;\n }\n /**\n * Attach a plugin (or many) to your Octokit instance.\n *\n * @example\n * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)\n */\n\n\n static plugin(...newPlugins) {\n var _a;\n\n const currentPlugins = this.plugins;\n const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a);\n return NewOctokit;\n }\n\n}\nOctokit.VERSION = VERSION;\nOctokit.plugins = [];\n\nexports.Octokit = Octokit;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar isPlainObject = require('is-plain-object');\nvar universalUserAgent = require('universal-user-agent');\n\nfunction lowercaseKeys(object) {\n if (!object) {\n return {};\n }\n\n return Object.keys(object).reduce((newObj, key) => {\n newObj[key.toLowerCase()] = object[key];\n return newObj;\n }, {});\n}\n\nfunction mergeDeep(defaults, options) {\n const result = Object.assign({}, defaults);\n Object.keys(options).forEach(key => {\n if (isPlainObject.isPlainObject(options[key])) {\n if (!(key in defaults)) Object.assign(result, {\n [key]: options[key]\n });else result[key] = mergeDeep(defaults[key], options[key]);\n } else {\n Object.assign(result, {\n [key]: options[key]\n });\n }\n });\n return result;\n}\n\nfunction removeUndefinedProperties(obj) {\n for (const key in obj) {\n if (obj[key] === undefined) {\n delete obj[key];\n }\n }\n\n return obj;\n}\n\nfunction merge(defaults, route, options) {\n if (typeof route === \"string\") {\n let [method, url] = route.split(\" \");\n options = Object.assign(url ? {\n method,\n url\n } : {\n url: method\n }, options);\n } else {\n options = Object.assign({}, route);\n } // lowercase header names before merging with defaults to avoid duplicates\n\n\n options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging\n\n removeUndefinedProperties(options);\n removeUndefinedProperties(options.headers);\n const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten\n\n if (defaults && defaults.mediaType.previews.length) {\n mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);\n }\n\n mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, \"\"));\n return mergedOptions;\n}\n\nfunction addQueryParameters(url, parameters) {\n const separator = /\\?/.test(url) ? \"&\" : \"?\";\n const names = Object.keys(parameters);\n\n if (names.length === 0) {\n return url;\n }\n\n return url + separator + names.map(name => {\n if (name === \"q\") {\n return \"q=\" + parameters.q.split(\"+\").map(encodeURIComponent).join(\"+\");\n }\n\n return `${name}=${encodeURIComponent(parameters[name])}`;\n }).join(\"&\");\n}\n\nconst urlVariableRegex = /\\{[^}]+\\}/g;\n\nfunction removeNonChars(variableName) {\n return variableName.replace(/^\\W+|\\W+$/g, \"\").split(/,/);\n}\n\nfunction extractUrlVariableNames(url) {\n const matches = url.match(urlVariableRegex);\n\n if (!matches) {\n return [];\n }\n\n return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);\n}\n\nfunction omit(object, keysToOmit) {\n return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {\n obj[key] = object[key];\n return obj;\n }, {});\n}\n\n// Based on https://github.com/bramstein/url-template, licensed under BSD\n// TODO: create separate package.\n//\n// Copyright (c) 2012-2014, Bram Stein\n// All rights reserved.\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. The name of the author may not be used to endorse or promote products\n// derived from this software without specific prior written permission.\n// THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/* istanbul ignore file */\nfunction encodeReserved(str) {\n return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {\n if (!/%[0-9A-Fa-f]/.test(part)) {\n part = encodeURI(part).replace(/%5B/g, \"[\").replace(/%5D/g, \"]\");\n }\n\n return part;\n }).join(\"\");\n}\n\nfunction encodeUnreserved(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\n\nfunction encodeValue(operator, value, key) {\n value = operator === \"+\" || operator === \"#\" ? encodeReserved(value) : encodeUnreserved(value);\n\n if (key) {\n return encodeUnreserved(key) + \"=\" + value;\n } else {\n return value;\n }\n}\n\nfunction isDefined(value) {\n return value !== undefined && value !== null;\n}\n\nfunction isKeyOperator(operator) {\n return operator === \";\" || operator === \"&\" || operator === \"?\";\n}\n\nfunction getValues(context, operator, key, modifier) {\n var value = context[key],\n result = [];\n\n if (isDefined(value) && value !== \"\") {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n value = value.toString();\n\n if (modifier && modifier !== \"*\") {\n value = value.substring(0, parseInt(modifier, 10));\n }\n\n result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : \"\"));\n } else {\n if (modifier === \"*\") {\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function (value) {\n result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : \"\"));\n });\n } else {\n Object.keys(value).forEach(function (k) {\n if (isDefined(value[k])) {\n result.push(encodeValue(operator, value[k], k));\n }\n });\n }\n } else {\n const tmp = [];\n\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function (value) {\n tmp.push(encodeValue(operator, value));\n });\n } else {\n Object.keys(value).forEach(function (k) {\n if (isDefined(value[k])) {\n tmp.push(encodeUnreserved(k));\n tmp.push(encodeValue(operator, value[k].toString()));\n }\n });\n }\n\n if (isKeyOperator(operator)) {\n result.push(encodeUnreserved(key) + \"=\" + tmp.join(\",\"));\n } else if (tmp.length !== 0) {\n result.push(tmp.join(\",\"));\n }\n }\n }\n } else {\n if (operator === \";\") {\n if (isDefined(value)) {\n result.push(encodeUnreserved(key));\n }\n } else if (value === \"\" && (operator === \"&\" || operator === \"?\")) {\n result.push(encodeUnreserved(key) + \"=\");\n } else if (value === \"\") {\n result.push(\"\");\n }\n }\n\n return result;\n}\n\nfunction parseUrl(template) {\n return {\n expand: expand.bind(null, template)\n };\n}\n\nfunction expand(template, context) {\n var operators = [\"+\", \"#\", \".\", \"/\", \";\", \"?\", \"&\"];\n return template.replace(/\\{([^\\{\\}]+)\\}|([^\\{\\}]+)/g, function (_, expression, literal) {\n if (expression) {\n let operator = \"\";\n const values = [];\n\n if (operators.indexOf(expression.charAt(0)) !== -1) {\n operator = expression.charAt(0);\n expression = expression.substr(1);\n }\n\n expression.split(/,/g).forEach(function (variable) {\n var tmp = /([^:\\*]*)(?::(\\d+)|(\\*))?/.exec(variable);\n values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));\n });\n\n if (operator && operator !== \"+\") {\n var separator = \",\";\n\n if (operator === \"?\") {\n separator = \"&\";\n } else if (operator !== \"#\") {\n separator = operator;\n }\n\n return (values.length !== 0 ? operator : \"\") + values.join(separator);\n } else {\n return values.join(\",\");\n }\n } else {\n return encodeReserved(literal);\n }\n });\n}\n\nfunction parse(options) {\n // https://fetch.spec.whatwg.org/#methods\n let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible\n\n let url = (options.url || \"/\").replace(/:([a-z]\\w+)/g, \"{$1}\");\n let headers = Object.assign({}, options.headers);\n let body;\n let parameters = omit(options, [\"method\", \"baseUrl\", \"url\", \"headers\", \"request\", \"mediaType\"]); // extract variable names from URL to calculate remaining variables later\n\n const urlVariableNames = extractUrlVariableNames(url);\n url = parseUrl(url).expand(parameters);\n\n if (!/^http/.test(url)) {\n url = options.baseUrl + url;\n }\n\n const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat(\"baseUrl\");\n const remainingParameters = omit(parameters, omittedParameters);\n const isBinaryRequest = /application\\/octet-stream/i.test(headers.accept);\n\n if (!isBinaryRequest) {\n if (options.mediaType.format) {\n // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw\n headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\\/vnd(\\.\\w+)(\\.v3)?(\\.\\w+)?(\\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(\",\");\n }\n\n if (options.mediaType.previews.length) {\n const previewsFromAcceptHeader = headers.accept.match(/[\\w-]+(?=-preview)/g) || [];\n headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {\n const format = options.mediaType.format ? `.${options.mediaType.format}` : \"+json\";\n return `application/vnd.github.${preview}-preview${format}`;\n }).join(\",\");\n }\n } // for GET/HEAD requests, set URL query parameters from remaining parameters\n // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters\n\n\n if ([\"GET\", \"HEAD\"].includes(method)) {\n url = addQueryParameters(url, remainingParameters);\n } else {\n if (\"data\" in remainingParameters) {\n body = remainingParameters.data;\n } else {\n if (Object.keys(remainingParameters).length) {\n body = remainingParameters;\n } else {\n headers[\"content-length\"] = 0;\n }\n }\n } // default content-type for JSON if body is set\n\n\n if (!headers[\"content-type\"] && typeof body !== \"undefined\") {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.\n // fetch does not allow to set `content-length` header, but we can set body to an empty string\n\n\n if ([\"PATCH\", \"PUT\"].includes(method) && typeof body === \"undefined\") {\n body = \"\";\n } // Only return body/request keys if present\n\n\n return Object.assign({\n method,\n url,\n headers\n }, typeof body !== \"undefined\" ? {\n body\n } : null, options.request ? {\n request: options.request\n } : null);\n}\n\nfunction endpointWithDefaults(defaults, route, options) {\n return parse(merge(defaults, route, options));\n}\n\nfunction withDefaults(oldDefaults, newDefaults) {\n const DEFAULTS = merge(oldDefaults, newDefaults);\n const endpoint = endpointWithDefaults.bind(null, DEFAULTS);\n return Object.assign(endpoint, {\n DEFAULTS,\n defaults: withDefaults.bind(null, DEFAULTS),\n merge: merge.bind(null, DEFAULTS),\n parse\n });\n}\n\nconst VERSION = \"6.0.11\";\n\nconst userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.\n// So we use RequestParameters and add method as additional required property.\n\nconst DEFAULTS = {\n method: \"GET\",\n baseUrl: \"https://api.github.com\",\n headers: {\n accept: \"application/vnd.github.v3+json\",\n \"user-agent\": userAgent\n },\n mediaType: {\n format: \"\",\n previews: []\n }\n};\n\nconst endpoint = withDefaults(null, DEFAULTS);\n\nexports.endpoint = endpoint;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar request = require('@octokit/request');\nvar universalUserAgent = require('universal-user-agent');\n\nconst VERSION = \"4.6.2\";\n\nclass GraphqlError extends Error {\n constructor(request, response) {\n const message = response.data.errors[0].message;\n super(message);\n Object.assign(this, response.data);\n Object.assign(this, {\n headers: response.headers\n });\n this.name = \"GraphqlError\";\n this.request = request; // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n}\n\nconst NON_VARIABLE_OPTIONS = [\"method\", \"baseUrl\", \"url\", \"headers\", \"request\", \"query\", \"mediaType\"];\nconst FORBIDDEN_VARIABLE_OPTIONS = [\"query\", \"method\", \"url\"];\nconst GHES_V3_SUFFIX_REGEX = /\\/api\\/v3\\/?$/;\nfunction graphql(request, query, options) {\n if (options) {\n if (typeof query === \"string\" && \"query\" in options) {\n return Promise.reject(new Error(`[@octokit/graphql] \"query\" cannot be used as variable name`));\n }\n\n for (const key in options) {\n if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;\n return Promise.reject(new Error(`[@octokit/graphql] \"${key}\" cannot be used as variable name`));\n }\n }\n\n const parsedOptions = typeof query === \"string\" ? Object.assign({\n query\n }, options) : query;\n const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {\n if (NON_VARIABLE_OPTIONS.includes(key)) {\n result[key] = parsedOptions[key];\n return result;\n }\n\n if (!result.variables) {\n result.variables = {};\n }\n\n result.variables[key] = parsedOptions[key];\n return result;\n }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix\n // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451\n\n const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;\n\n if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {\n requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, \"/api/graphql\");\n }\n\n return request(requestOptions).then(response => {\n if (response.data.errors) {\n const headers = {};\n\n for (const key of Object.keys(response.headers)) {\n headers[key] = response.headers[key];\n }\n\n throw new GraphqlError(requestOptions, {\n headers,\n data: response.data\n });\n }\n\n return response.data.data;\n });\n}\n\nfunction withDefaults(request$1, newDefaults) {\n const newRequest = request$1.defaults(newDefaults);\n\n const newApi = (query, options) => {\n return graphql(newRequest, query, options);\n };\n\n return Object.assign(newApi, {\n defaults: withDefaults.bind(null, newRequest),\n endpoint: request.request.endpoint\n });\n}\n\nconst graphql$1 = withDefaults(request.request, {\n headers: {\n \"user-agent\": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}`\n },\n method: \"POST\",\n url: \"/graphql\"\n});\nfunction withCustomRequest(customRequest) {\n return withDefaults(customRequest, {\n method: \"POST\",\n url: \"/graphql\"\n });\n}\n\nexports.graphql = graphql$1;\nexports.withCustomRequest = withCustomRequest;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst VERSION = \"2.13.3\";\n\n/**\n * Some “list” response that can be paginated have a different response structure\n *\n * They have a `total_count` key in the response (search also has `incomplete_results`,\n * /installation/repositories also has `repository_selection`), as well as a key with\n * the list of the items which name varies from endpoint to endpoint.\n *\n * Octokit normalizes these responses so that paginated results are always returned following\n * the same structure. One challenge is that if the list response has only one page, no Link\n * header is provided, so this header alone is not sufficient to check wether a response is\n * paginated or not.\n *\n * We check if a \"total_count\" key is present in the response data, but also make sure that\n * a \"url\" property is not, as the \"Get the combined status for a specific ref\" endpoint would\n * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref\n */\nfunction normalizePaginatedListResponse(response) {\n const responseNeedsNormalization = \"total_count\" in response.data && !(\"url\" in response.data);\n if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way\n // to retrieve the same information.\n\n const incompleteResults = response.data.incomplete_results;\n const repositorySelection = response.data.repository_selection;\n const totalCount = response.data.total_count;\n delete response.data.incomplete_results;\n delete response.data.repository_selection;\n delete response.data.total_count;\n const namespaceKey = Object.keys(response.data)[0];\n const data = response.data[namespaceKey];\n response.data = data;\n\n if (typeof incompleteResults !== \"undefined\") {\n response.data.incomplete_results = incompleteResults;\n }\n\n if (typeof repositorySelection !== \"undefined\") {\n response.data.repository_selection = repositorySelection;\n }\n\n response.data.total_count = totalCount;\n return response;\n}\n\nfunction iterator(octokit, route, parameters) {\n const options = typeof route === \"function\" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);\n const requestMethod = typeof route === \"function\" ? route : octokit.request;\n const method = options.method;\n const headers = options.headers;\n let url = options.url;\n return {\n [Symbol.asyncIterator]: () => ({\n async next() {\n if (!url) return {\n done: true\n };\n const response = await requestMethod({\n method,\n url,\n headers\n });\n const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format:\n // '; rel=\"next\", ; rel=\"last\"'\n // sets `url` to undefined if \"next\" URL is not present or `link` header is not set\n\n url = ((normalizedResponse.headers.link || \"\").match(/<([^>]+)>;\\s*rel=\"next\"/) || [])[1];\n return {\n value: normalizedResponse\n };\n }\n\n })\n };\n}\n\nfunction paginate(octokit, route, parameters, mapFn) {\n if (typeof parameters === \"function\") {\n mapFn = parameters;\n parameters = undefined;\n }\n\n return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn);\n}\n\nfunction gather(octokit, results, iterator, mapFn) {\n return iterator.next().then(result => {\n if (result.done) {\n return results;\n }\n\n let earlyExit = false;\n\n function done() {\n earlyExit = true;\n }\n\n results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data);\n\n if (earlyExit) {\n return results;\n }\n\n return gather(octokit, results, iterator, mapFn);\n });\n}\n\nconst composePaginateRest = Object.assign(paginate, {\n iterator\n});\n\nconst paginatingEndpoints = [\"GET /app/installations\", \"GET /applications/grants\", \"GET /authorizations\", \"GET /enterprises/{enterprise}/actions/permissions/organizations\", \"GET /enterprises/{enterprise}/actions/runner-groups\", \"GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations\", \"GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners\", \"GET /enterprises/{enterprise}/actions/runners\", \"GET /enterprises/{enterprise}/actions/runners/downloads\", \"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 /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/permissions/repositories\", \"GET /orgs/{org}/actions/runner-groups\", \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories\", \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners\", \"GET /orgs/{org}/actions/runners\", \"GET /orgs/{org}/actions/runners/downloads\", \"GET /orgs/{org}/actions/secrets\", \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\", \"GET /orgs/{org}/blocks\", \"GET /orgs/{org}/credential-authorizations\", \"GET /orgs/{org}/events\", \"GET /orgs/{org}/failed_invitations\", \"GET /orgs/{org}/hooks\", \"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}/migrations\", \"GET /orgs/{org}/migrations/{migration_id}/repositories\", \"GET /orgs/{org}/outside_collaborators\", \"GET /orgs/{org}/projects\", \"GET /orgs/{org}/public_members\", \"GET /orgs/{org}/repos\", \"GET /orgs/{org}/team-sync/groups\", \"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}/team-sync/group-mappings\", \"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/runners\", \"GET /repos/{owner}/{repo}/actions/runners/downloads\", \"GET /repos/{owner}/{repo}/actions/runs\", \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\", \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\", \"GET /repos/{owner}/{repo}/actions/secrets\", \"GET /repos/{owner}/{repo}/actions/workflows\", \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\", \"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}/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}/branches-where-head\", \"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}/statuses\", \"GET /repos/{owner}/{repo}/contributors\", \"GET /repos/{owner}/{repo}/deployments\", \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\", \"GET /repos/{owner}/{repo}/events\", \"GET /repos/{owner}/{repo}/forks\", \"GET /repos/{owner}/{repo}/git/matching-refs/{ref}\", \"GET /repos/{owner}/{repo}/hooks\", \"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}/requested_reviewers\", \"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}/secret-scanning/alerts\", \"GET /repos/{owner}/{repo}/stargazers\", \"GET /repos/{owner}/{repo}/subscribers\", \"GET /repos/{owner}/{repo}/tags\", \"GET /repos/{owner}/{repo}/teams\", \"GET /repositories\", \"GET /repositories/{repository_id}/environments/{environment_name}/secrets\", \"GET /scim/v2/enterprises/{enterprise}/Groups\", \"GET /scim/v2/enterprises/{enterprise}/Users\", \"GET /scim/v2/organizations/{org}/Users\", \"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}/team-sync/group-mappings\", \"GET /teams/{team_id}/teams\", \"GET /user/blocks\", \"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/public_emails\", \"GET /user/repos\", \"GET /user/repository_invitations\", \"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}/projects\", \"GET /users/{username}/received_events\", \"GET /users/{username}/received_events/public\", \"GET /users/{username}/repos\", \"GET /users/{username}/starred\", \"GET /users/{username}/subscriptions\"];\n\nfunction isPaginatingEndpoint(arg) {\n if (typeof arg === \"string\") {\n return paginatingEndpoints.includes(arg);\n } else {\n return false;\n }\n}\n\n/**\n * @param octokit Octokit instance\n * @param options Options passed to Octokit constructor\n */\n\nfunction paginateRest(octokit) {\n return {\n paginate: Object.assign(paginate.bind(null, octokit), {\n iterator: iterator.bind(null, octokit)\n })\n };\n}\npaginateRest.VERSION = VERSION;\n\nexports.composePaginateRest = composePaginateRest;\nexports.isPaginatingEndpoint = isPaginatingEndpoint;\nexports.paginateRest = paginateRest;\nexports.paginatingEndpoints = paginatingEndpoints;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (enumerableOnly) {\n symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n }\n\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nconst Endpoints = {\n actions: {\n addSelectedRepoToOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"],\n approveWorkflowRun: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve\"],\n cancelWorkflowRun: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel\"],\n createOrUpdateEnvironmentSecret: [\"PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"],\n createOrUpdateOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}\"],\n createOrUpdateRepoSecret: [\"PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n createRegistrationTokenForOrg: [\"POST /orgs/{org}/actions/runners/registration-token\"],\n createRegistrationTokenForRepo: [\"POST /repos/{owner}/{repo}/actions/runners/registration-token\"],\n createRemoveTokenForOrg: [\"POST /orgs/{org}/actions/runners/remove-token\"],\n createRemoveTokenForRepo: [\"POST /repos/{owner}/{repo}/actions/runners/remove-token\"],\n createWorkflowDispatch: [\"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches\"],\n deleteArtifact: [\"DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n deleteEnvironmentSecret: [\"DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"],\n deleteOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}\"],\n deleteRepoSecret: [\"DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n deleteSelfHostedRunnerFromOrg: [\"DELETE /orgs/{org}/actions/runners/{runner_id}\"],\n deleteSelfHostedRunnerFromRepo: [\"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}\"],\n deleteWorkflowRun: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n deleteWorkflowRunLogs: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"],\n disableSelectedRepositoryGithubActionsOrganization: [\"DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}\"],\n disableWorkflow: [\"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable\"],\n downloadArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}\"],\n downloadJobLogsForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs\"],\n downloadWorkflowRunLogs: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"],\n enableSelectedRepositoryGithubActionsOrganization: [\"PUT /orgs/{org}/actions/permissions/repositories/{repository_id}\"],\n enableWorkflow: [\"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable\"],\n getAllowedActionsOrganization: [\"GET /orgs/{org}/actions/permissions/selected-actions\"],\n getAllowedActionsRepository: [\"GET /repos/{owner}/{repo}/actions/permissions/selected-actions\"],\n getArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n getEnvironmentPublicKey: [\"GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key\"],\n getEnvironmentSecret: [\"GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"],\n getGithubActionsPermissionsOrganization: [\"GET /orgs/{org}/actions/permissions\"],\n getGithubActionsPermissionsRepository: [\"GET /repos/{owner}/{repo}/actions/permissions\"],\n getJobForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/actions/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}\"],\n getPendingDeploymentsForRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\"],\n getRepoPermissions: [\"GET /repos/{owner}/{repo}/actions/permissions\", {}, {\n renamed: [\"actions\", \"getGithubActionsPermissionsRepository\"]\n }],\n getRepoPublicKey: [\"GET /repos/{owner}/{repo}/actions/secrets/public-key\"],\n getRepoSecret: [\"GET /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n getReviewsForRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals\"],\n getSelfHostedRunnerForOrg: [\"GET /orgs/{org}/actions/runners/{runner_id}\"],\n getSelfHostedRunnerForRepo: [\"GET /repos/{owner}/{repo}/actions/runners/{runner_id}\"],\n getWorkflow: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}\"],\n getWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n getWorkflowRunUsage: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing\"],\n getWorkflowUsage: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing\"],\n listArtifactsForRepo: [\"GET /repos/{owner}/{repo}/actions/artifacts\"],\n listEnvironmentSecrets: [\"GET /repositories/{repository_id}/environments/{environment_name}/secrets\"],\n listJobsForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\"],\n listOrgSecrets: [\"GET /orgs/{org}/actions/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/actions/secrets\"],\n listRepoWorkflows: [\"GET /repos/{owner}/{repo}/actions/workflows\"],\n listRunnerApplicationsForOrg: [\"GET /orgs/{org}/actions/runners/downloads\"],\n listRunnerApplicationsForRepo: [\"GET /repos/{owner}/{repo}/actions/runners/downloads\"],\n listSelectedReposForOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\"],\n listSelectedRepositoriesEnabledGithubActionsOrganization: [\"GET /orgs/{org}/actions/permissions/repositories\"],\n listSelfHostedRunnersForOrg: [\"GET /orgs/{org}/actions/runners\"],\n listSelfHostedRunnersForRepo: [\"GET /repos/{owner}/{repo}/actions/runners\"],\n listWorkflowRunArtifacts: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\"],\n listWorkflowRuns: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\"],\n listWorkflowRunsForRepo: [\"GET /repos/{owner}/{repo}/actions/runs\"],\n reRunWorkflow: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun\"],\n removeSelectedRepoFromOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"],\n reviewPendingDeploymentsForRun: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\"],\n setAllowedActionsOrganization: [\"PUT /orgs/{org}/actions/permissions/selected-actions\"],\n setAllowedActionsRepository: [\"PUT /repos/{owner}/{repo}/actions/permissions/selected-actions\"],\n setGithubActionsPermissionsOrganization: [\"PUT /orgs/{org}/actions/permissions\"],\n setGithubActionsPermissionsRepository: [\"PUT /repos/{owner}/{repo}/actions/permissions\"],\n setSelectedReposForOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories\"],\n setSelectedRepositoriesEnabledGithubActionsOrganization: [\"PUT /orgs/{org}/actions/permissions/repositories\"]\n },\n activity: {\n checkRepoIsStarredByAuthenticatedUser: [\"GET /user/starred/{owner}/{repo}\"],\n deleteRepoSubscription: [\"DELETE /repos/{owner}/{repo}/subscription\"],\n deleteThreadSubscription: [\"DELETE /notifications/threads/{thread_id}/subscription\"],\n getFeeds: [\"GET /feeds\"],\n getRepoSubscription: [\"GET /repos/{owner}/{repo}/subscription\"],\n getThread: [\"GET /notifications/threads/{thread_id}\"],\n getThreadSubscriptionForAuthenticatedUser: [\"GET /notifications/threads/{thread_id}/subscription\"],\n listEventsForAuthenticatedUser: [\"GET /users/{username}/events\"],\n listNotificationsForAuthenticatedUser: [\"GET /notifications\"],\n listOrgEventsForAuthenticatedUser: [\"GET /users/{username}/events/orgs/{org}\"],\n listPublicEvents: [\"GET /events\"],\n listPublicEventsForRepoNetwork: [\"GET /networks/{owner}/{repo}/events\"],\n listPublicEventsForUser: [\"GET /users/{username}/events/public\"],\n listPublicOrgEvents: [\"GET /orgs/{org}/events\"],\n listReceivedEventsForUser: [\"GET /users/{username}/received_events\"],\n listReceivedPublicEventsForUser: [\"GET /users/{username}/received_events/public\"],\n listRepoEvents: [\"GET /repos/{owner}/{repo}/events\"],\n listRepoNotificationsForAuthenticatedUser: [\"GET /repos/{owner}/{repo}/notifications\"],\n listReposStarredByAuthenticatedUser: [\"GET /user/starred\"],\n listReposStarredByUser: [\"GET /users/{username}/starred\"],\n listReposWatchedByUser: [\"GET /users/{username}/subscriptions\"],\n listStargazersForRepo: [\"GET /repos/{owner}/{repo}/stargazers\"],\n listWatchedReposForAuthenticatedUser: [\"GET /user/subscriptions\"],\n listWatchersForRepo: [\"GET /repos/{owner}/{repo}/subscribers\"],\n markNotificationsAsRead: [\"PUT /notifications\"],\n markRepoNotificationsAsRead: [\"PUT /repos/{owner}/{repo}/notifications\"],\n markThreadAsRead: [\"PATCH /notifications/threads/{thread_id}\"],\n setRepoSubscription: [\"PUT /repos/{owner}/{repo}/subscription\"],\n setThreadSubscription: [\"PUT /notifications/threads/{thread_id}/subscription\"],\n starRepoForAuthenticatedUser: [\"PUT /user/starred/{owner}/{repo}\"],\n unstarRepoForAuthenticatedUser: [\"DELETE /user/starred/{owner}/{repo}\"]\n },\n apps: {\n addRepoToInstallation: [\"PUT /user/installations/{installation_id}/repositories/{repository_id}\"],\n checkToken: [\"POST /applications/{client_id}/token\"],\n createContentAttachment: [\"POST /content_references/{content_reference_id}/attachments\", {\n mediaType: {\n previews: [\"corsair\"]\n }\n }],\n createContentAttachmentForRepo: [\"POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments\", {\n mediaType: {\n previews: [\"corsair\"]\n }\n }],\n createFromManifest: [\"POST /app-manifests/{code}/conversions\"],\n createInstallationAccessToken: [\"POST /app/installations/{installation_id}/access_tokens\"],\n deleteAuthorization: [\"DELETE /applications/{client_id}/grant\"],\n deleteInstallation: [\"DELETE /app/installations/{installation_id}\"],\n deleteToken: [\"DELETE /applications/{client_id}/token\"],\n getAuthenticated: [\"GET /app\"],\n getBySlug: [\"GET /apps/{app_slug}\"],\n getInstallation: [\"GET /app/installations/{installation_id}\"],\n getOrgInstallation: [\"GET /orgs/{org}/installation\"],\n getRepoInstallation: [\"GET /repos/{owner}/{repo}/installation\"],\n getSubscriptionPlanForAccount: [\"GET /marketplace_listing/accounts/{account_id}\"],\n getSubscriptionPlanForAccountStubbed: [\"GET /marketplace_listing/stubbed/accounts/{account_id}\"],\n getUserInstallation: [\"GET /users/{username}/installation\"],\n getWebhookConfigForApp: [\"GET /app/hook/config\"],\n listAccountsForPlan: [\"GET /marketplace_listing/plans/{plan_id}/accounts\"],\n listAccountsForPlanStubbed: [\"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\"],\n listInstallationReposForAuthenticatedUser: [\"GET /user/installations/{installation_id}/repositories\"],\n listInstallations: [\"GET /app/installations\"],\n listInstallationsForAuthenticatedUser: [\"GET /user/installations\"],\n listPlans: [\"GET /marketplace_listing/plans\"],\n listPlansStubbed: [\"GET /marketplace_listing/stubbed/plans\"],\n listReposAccessibleToInstallation: [\"GET /installation/repositories\"],\n listSubscriptionsForAuthenticatedUser: [\"GET /user/marketplace_purchases\"],\n listSubscriptionsForAuthenticatedUserStubbed: [\"GET /user/marketplace_purchases/stubbed\"],\n removeRepoFromInstallation: [\"DELETE /user/installations/{installation_id}/repositories/{repository_id}\"],\n resetToken: [\"PATCH /applications/{client_id}/token\"],\n revokeInstallationAccessToken: [\"DELETE /installation/token\"],\n scopeToken: [\"POST /applications/{client_id}/token/scoped\"],\n suspendInstallation: [\"PUT /app/installations/{installation_id}/suspended\"],\n unsuspendInstallation: [\"DELETE /app/installations/{installation_id}/suspended\"],\n updateWebhookConfigForApp: [\"PATCH /app/hook/config\"]\n },\n billing: {\n getGithubActionsBillingOrg: [\"GET /orgs/{org}/settings/billing/actions\"],\n getGithubActionsBillingUser: [\"GET /users/{username}/settings/billing/actions\"],\n getGithubPackagesBillingOrg: [\"GET /orgs/{org}/settings/billing/packages\"],\n getGithubPackagesBillingUser: [\"GET /users/{username}/settings/billing/packages\"],\n getSharedStorageBillingOrg: [\"GET /orgs/{org}/settings/billing/shared-storage\"],\n getSharedStorageBillingUser: [\"GET /users/{username}/settings/billing/shared-storage\"]\n },\n checks: {\n create: [\"POST /repos/{owner}/{repo}/check-runs\"],\n createSuite: [\"POST /repos/{owner}/{repo}/check-suites\"],\n get: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}\"],\n getSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}\"],\n listAnnotations: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\"],\n listForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\"],\n listForSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\"],\n listSuitesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\"],\n rerequestSuite: [\"POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest\"],\n setSuitesPreferences: [\"PATCH /repos/{owner}/{repo}/check-suites/preferences\"],\n update: [\"PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}\"]\n },\n codeScanning: {\n deleteAnalysis: [\"DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}\"],\n getAlert: [\"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\", {}, {\n renamedParameters: {\n alert_id: \"alert_number\"\n }\n }],\n getAnalysis: [\"GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}\"],\n getSarif: [\"GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}\"],\n listAlertInstances: [\"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/code-scanning/alerts\"],\n listAlertsInstances: [\"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\", {}, {\n renamed: [\"codeScanning\", \"listAlertInstances\"]\n }],\n listRecentAnalyses: [\"GET /repos/{owner}/{repo}/code-scanning/analyses\"],\n updateAlert: [\"PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\"],\n uploadSarif: [\"POST /repos/{owner}/{repo}/code-scanning/sarifs\"]\n },\n codesOfConduct: {\n getAllCodesOfConduct: [\"GET /codes_of_conduct\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }],\n getConductCode: [\"GET /codes_of_conduct/{key}\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }],\n getForRepo: [\"GET /repos/{owner}/{repo}/community/code_of_conduct\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }]\n },\n emojis: {\n get: [\"GET /emojis\"]\n },\n enterpriseAdmin: {\n disableSelectedOrganizationGithubActionsEnterprise: [\"DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}\"],\n enableSelectedOrganizationGithubActionsEnterprise: [\"PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}\"],\n getAllowedActionsEnterprise: [\"GET /enterprises/{enterprise}/actions/permissions/selected-actions\"],\n getGithubActionsPermissionsEnterprise: [\"GET /enterprises/{enterprise}/actions/permissions\"],\n listSelectedOrganizationsEnabledGithubActionsEnterprise: [\"GET /enterprises/{enterprise}/actions/permissions/organizations\"],\n setAllowedActionsEnterprise: [\"PUT /enterprises/{enterprise}/actions/permissions/selected-actions\"],\n setGithubActionsPermissionsEnterprise: [\"PUT /enterprises/{enterprise}/actions/permissions\"],\n setSelectedOrganizationsEnabledGithubActionsEnterprise: [\"PUT /enterprises/{enterprise}/actions/permissions/organizations\"]\n },\n gists: {\n checkIsStarred: [\"GET /gists/{gist_id}/star\"],\n create: [\"POST /gists\"],\n createComment: [\"POST /gists/{gist_id}/comments\"],\n delete: [\"DELETE /gists/{gist_id}\"],\n deleteComment: [\"DELETE /gists/{gist_id}/comments/{comment_id}\"],\n fork: [\"POST /gists/{gist_id}/forks\"],\n get: [\"GET /gists/{gist_id}\"],\n getComment: [\"GET /gists/{gist_id}/comments/{comment_id}\"],\n getRevision: [\"GET /gists/{gist_id}/{sha}\"],\n list: [\"GET /gists\"],\n listComments: [\"GET /gists/{gist_id}/comments\"],\n listCommits: [\"GET /gists/{gist_id}/commits\"],\n listForUser: [\"GET /users/{username}/gists\"],\n listForks: [\"GET /gists/{gist_id}/forks\"],\n listPublic: [\"GET /gists/public\"],\n listStarred: [\"GET /gists/starred\"],\n star: [\"PUT /gists/{gist_id}/star\"],\n unstar: [\"DELETE /gists/{gist_id}/star\"],\n update: [\"PATCH /gists/{gist_id}\"],\n updateComment: [\"PATCH /gists/{gist_id}/comments/{comment_id}\"]\n },\n git: {\n createBlob: [\"POST /repos/{owner}/{repo}/git/blobs\"],\n createCommit: [\"POST /repos/{owner}/{repo}/git/commits\"],\n createRef: [\"POST /repos/{owner}/{repo}/git/refs\"],\n createTag: [\"POST /repos/{owner}/{repo}/git/tags\"],\n createTree: [\"POST /repos/{owner}/{repo}/git/trees\"],\n deleteRef: [\"DELETE /repos/{owner}/{repo}/git/refs/{ref}\"],\n getBlob: [\"GET /repos/{owner}/{repo}/git/blobs/{file_sha}\"],\n getCommit: [\"GET /repos/{owner}/{repo}/git/commits/{commit_sha}\"],\n getRef: [\"GET /repos/{owner}/{repo}/git/ref/{ref}\"],\n getTag: [\"GET /repos/{owner}/{repo}/git/tags/{tag_sha}\"],\n getTree: [\"GET /repos/{owner}/{repo}/git/trees/{tree_sha}\"],\n listMatchingRefs: [\"GET /repos/{owner}/{repo}/git/matching-refs/{ref}\"],\n updateRef: [\"PATCH /repos/{owner}/{repo}/git/refs/{ref}\"]\n },\n gitignore: {\n getAllTemplates: [\"GET /gitignore/templates\"],\n getTemplate: [\"GET /gitignore/templates/{name}\"]\n },\n interactions: {\n getRestrictionsForAuthenticatedUser: [\"GET /user/interaction-limits\"],\n getRestrictionsForOrg: [\"GET /orgs/{org}/interaction-limits\"],\n getRestrictionsForRepo: [\"GET /repos/{owner}/{repo}/interaction-limits\"],\n getRestrictionsForYourPublicRepos: [\"GET /user/interaction-limits\", {}, {\n renamed: [\"interactions\", \"getRestrictionsForAuthenticatedUser\"]\n }],\n removeRestrictionsForAuthenticatedUser: [\"DELETE /user/interaction-limits\"],\n removeRestrictionsForOrg: [\"DELETE /orgs/{org}/interaction-limits\"],\n removeRestrictionsForRepo: [\"DELETE /repos/{owner}/{repo}/interaction-limits\"],\n removeRestrictionsForYourPublicRepos: [\"DELETE /user/interaction-limits\", {}, {\n renamed: [\"interactions\", \"removeRestrictionsForAuthenticatedUser\"]\n }],\n setRestrictionsForAuthenticatedUser: [\"PUT /user/interaction-limits\"],\n setRestrictionsForOrg: [\"PUT /orgs/{org}/interaction-limits\"],\n setRestrictionsForRepo: [\"PUT /repos/{owner}/{repo}/interaction-limits\"],\n setRestrictionsForYourPublicRepos: [\"PUT /user/interaction-limits\", {}, {\n renamed: [\"interactions\", \"setRestrictionsForAuthenticatedUser\"]\n }]\n },\n issues: {\n addAssignees: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/assignees\"],\n addLabels: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n checkUserCanBeAssigned: [\"GET /repos/{owner}/{repo}/assignees/{assignee}\"],\n create: [\"POST /repos/{owner}/{repo}/issues\"],\n createComment: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n createLabel: [\"POST /repos/{owner}/{repo}/labels\"],\n createMilestone: [\"POST /repos/{owner}/{repo}/milestones\"],\n deleteComment: [\"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n deleteLabel: [\"DELETE /repos/{owner}/{repo}/labels/{name}\"],\n deleteMilestone: [\"DELETE /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n get: [\"GET /repos/{owner}/{repo}/issues/{issue_number}\"],\n getComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n getEvent: [\"GET /repos/{owner}/{repo}/issues/events/{event_id}\"],\n getLabel: [\"GET /repos/{owner}/{repo}/labels/{name}\"],\n getMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n list: [\"GET /issues\"],\n listAssignees: [\"GET /repos/{owner}/{repo}/assignees\"],\n listComments: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n listCommentsForRepo: [\"GET /repos/{owner}/{repo}/issues/comments\"],\n listEvents: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/events\"],\n listEventsForRepo: [\"GET /repos/{owner}/{repo}/issues/events\"],\n listEventsForTimeline: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\", {\n mediaType: {\n previews: [\"mockingbird\"]\n }\n }],\n listForAuthenticatedUser: [\"GET /user/issues\"],\n listForOrg: [\"GET /orgs/{org}/issues\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/issues\"],\n listLabelsForMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\"],\n listLabelsForRepo: [\"GET /repos/{owner}/{repo}/labels\"],\n listLabelsOnIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n listMilestones: [\"GET /repos/{owner}/{repo}/milestones\"],\n lock: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n removeAllLabels: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n removeAssignees: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees\"],\n removeLabel: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}\"],\n setLabels: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n unlock: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n update: [\"PATCH /repos/{owner}/{repo}/issues/{issue_number}\"],\n updateComment: [\"PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n updateLabel: [\"PATCH /repos/{owner}/{repo}/labels/{name}\"],\n updateMilestone: [\"PATCH /repos/{owner}/{repo}/milestones/{milestone_number}\"]\n },\n licenses: {\n get: [\"GET /licenses/{license}\"],\n getAllCommonlyUsed: [\"GET /licenses\"],\n getForRepo: [\"GET /repos/{owner}/{repo}/license\"]\n },\n markdown: {\n render: [\"POST /markdown\"],\n renderRaw: [\"POST /markdown/raw\", {\n headers: {\n \"content-type\": \"text/plain; charset=utf-8\"\n }\n }]\n },\n meta: {\n get: [\"GET /meta\"],\n getOctocat: [\"GET /octocat\"],\n getZen: [\"GET /zen\"],\n root: [\"GET /\"]\n },\n migrations: {\n cancelImport: [\"DELETE /repos/{owner}/{repo}/import\"],\n deleteArchiveForAuthenticatedUser: [\"DELETE /user/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n deleteArchiveForOrg: [\"DELETE /orgs/{org}/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n downloadArchiveForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getArchiveForAuthenticatedUser: [\"GET /user/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getCommitAuthors: [\"GET /repos/{owner}/{repo}/import/authors\"],\n getImportStatus: [\"GET /repos/{owner}/{repo}/import\"],\n getLargeFiles: [\"GET /repos/{owner}/{repo}/import/large_files\"],\n getStatusForAuthenticatedUser: [\"GET /user/migrations/{migration_id}\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getStatusForOrg: [\"GET /orgs/{org}/migrations/{migration_id}\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listForAuthenticatedUser: [\"GET /user/migrations\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listForOrg: [\"GET /orgs/{org}/migrations\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listReposForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/repositories\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listReposForUser: [\"GET /user/migrations/{migration_id}/repositories\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n mapCommitAuthor: [\"PATCH /repos/{owner}/{repo}/import/authors/{author_id}\"],\n setLfsPreference: [\"PATCH /repos/{owner}/{repo}/import/lfs\"],\n startForAuthenticatedUser: [\"POST /user/migrations\"],\n startForOrg: [\"POST /orgs/{org}/migrations\"],\n startImport: [\"PUT /repos/{owner}/{repo}/import\"],\n unlockRepoForAuthenticatedUser: [\"DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n unlockRepoForOrg: [\"DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n updateImport: [\"PATCH /repos/{owner}/{repo}/import\"]\n },\n orgs: {\n blockUser: [\"PUT /orgs/{org}/blocks/{username}\"],\n cancelInvitation: [\"DELETE /orgs/{org}/invitations/{invitation_id}\"],\n checkBlockedUser: [\"GET /orgs/{org}/blocks/{username}\"],\n checkMembershipForUser: [\"GET /orgs/{org}/members/{username}\"],\n checkPublicMembershipForUser: [\"GET /orgs/{org}/public_members/{username}\"],\n convertMemberToOutsideCollaborator: [\"PUT /orgs/{org}/outside_collaborators/{username}\"],\n createInvitation: [\"POST /orgs/{org}/invitations\"],\n createWebhook: [\"POST /orgs/{org}/hooks\"],\n deleteWebhook: [\"DELETE /orgs/{org}/hooks/{hook_id}\"],\n get: [\"GET /orgs/{org}\"],\n getMembershipForAuthenticatedUser: [\"GET /user/memberships/orgs/{org}\"],\n getMembershipForUser: [\"GET /orgs/{org}/memberships/{username}\"],\n getWebhook: [\"GET /orgs/{org}/hooks/{hook_id}\"],\n getWebhookConfigForOrg: [\"GET /orgs/{org}/hooks/{hook_id}/config\"],\n list: [\"GET /organizations\"],\n listAppInstallations: [\"GET /orgs/{org}/installations\"],\n listBlockedUsers: [\"GET /orgs/{org}/blocks\"],\n listFailedInvitations: [\"GET /orgs/{org}/failed_invitations\"],\n listForAuthenticatedUser: [\"GET /user/orgs\"],\n listForUser: [\"GET /users/{username}/orgs\"],\n listInvitationTeams: [\"GET /orgs/{org}/invitations/{invitation_id}/teams\"],\n listMembers: [\"GET /orgs/{org}/members\"],\n listMembershipsForAuthenticatedUser: [\"GET /user/memberships/orgs\"],\n listOutsideCollaborators: [\"GET /orgs/{org}/outside_collaborators\"],\n listPendingInvitations: [\"GET /orgs/{org}/invitations\"],\n listPublicMembers: [\"GET /orgs/{org}/public_members\"],\n listWebhooks: [\"GET /orgs/{org}/hooks\"],\n pingWebhook: [\"POST /orgs/{org}/hooks/{hook_id}/pings\"],\n removeMember: [\"DELETE /orgs/{org}/members/{username}\"],\n removeMembershipForUser: [\"DELETE /orgs/{org}/memberships/{username}\"],\n removeOutsideCollaborator: [\"DELETE /orgs/{org}/outside_collaborators/{username}\"],\n removePublicMembershipForAuthenticatedUser: [\"DELETE /orgs/{org}/public_members/{username}\"],\n setMembershipForUser: [\"PUT /orgs/{org}/memberships/{username}\"],\n setPublicMembershipForAuthenticatedUser: [\"PUT /orgs/{org}/public_members/{username}\"],\n unblockUser: [\"DELETE /orgs/{org}/blocks/{username}\"],\n update: [\"PATCH /orgs/{org}\"],\n updateMembershipForAuthenticatedUser: [\"PATCH /user/memberships/orgs/{org}\"],\n updateWebhook: [\"PATCH /orgs/{org}/hooks/{hook_id}\"],\n updateWebhookConfigForOrg: [\"PATCH /orgs/{org}/hooks/{hook_id}/config\"]\n },\n packages: {\n deletePackageForAuthenticatedUser: [\"DELETE /user/packages/{package_type}/{package_name}\"],\n deletePackageForOrg: [\"DELETE /orgs/{org}/packages/{package_type}/{package_name}\"],\n deletePackageVersionForAuthenticatedUser: [\"DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}\"],\n deletePackageVersionForOrg: [\"DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\"],\n getAllPackageVersionsForAPackageOwnedByAnOrg: [\"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\", {}, {\n renamed: [\"packages\", \"getAllPackageVersionsForPackageOwnedByOrg\"]\n }],\n getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [\"GET /user/packages/{package_type}/{package_name}/versions\", {}, {\n renamed: [\"packages\", \"getAllPackageVersionsForPackageOwnedByAuthenticatedUser\"]\n }],\n getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [\"GET /user/packages/{package_type}/{package_name}/versions\"],\n getAllPackageVersionsForPackageOwnedByOrg: [\"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\"],\n getAllPackageVersionsForPackageOwnedByUser: [\"GET /users/{username}/packages/{package_type}/{package_name}/versions\"],\n getPackageForAuthenticatedUser: [\"GET /user/packages/{package_type}/{package_name}\"],\n getPackageForOrganization: [\"GET /orgs/{org}/packages/{package_type}/{package_name}\"],\n getPackageForUser: [\"GET /users/{username}/packages/{package_type}/{package_name}\"],\n getPackageVersionForAuthenticatedUser: [\"GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}\"],\n getPackageVersionForOrganization: [\"GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\"],\n getPackageVersionForUser: [\"GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\"],\n restorePackageForAuthenticatedUser: [\"POST /user/packages/{package_type}/{package_name}/restore{?token}\"],\n restorePackageForOrg: [\"POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}\"],\n restorePackageVersionForAuthenticatedUser: [\"POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\"],\n restorePackageVersionForOrg: [\"POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\"]\n },\n projects: {\n addCollaborator: [\"PUT /projects/{project_id}/collaborators/{username}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createCard: [\"POST /projects/columns/{column_id}/cards\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createColumn: [\"POST /projects/{project_id}/columns\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForAuthenticatedUser: [\"POST /user/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForOrg: [\"POST /orgs/{org}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForRepo: [\"POST /repos/{owner}/{repo}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n delete: [\"DELETE /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n deleteCard: [\"DELETE /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n deleteColumn: [\"DELETE /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n get: [\"GET /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getCard: [\"GET /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getColumn: [\"GET /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getPermissionForUser: [\"GET /projects/{project_id}/collaborators/{username}/permission\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listCards: [\"GET /projects/columns/{column_id}/cards\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listCollaborators: [\"GET /projects/{project_id}/collaborators\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listColumns: [\"GET /projects/{project_id}/columns\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForOrg: [\"GET /orgs/{org}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForRepo: [\"GET /repos/{owner}/{repo}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForUser: [\"GET /users/{username}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n moveCard: [\"POST /projects/columns/cards/{card_id}/moves\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n moveColumn: [\"POST /projects/columns/{column_id}/moves\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n removeCollaborator: [\"DELETE /projects/{project_id}/collaborators/{username}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n update: [\"PATCH /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n updateCard: [\"PATCH /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n updateColumn: [\"PATCH /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }]\n },\n pulls: {\n checkIfMerged: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n create: [\"POST /repos/{owner}/{repo}/pulls\"],\n createReplyForReviewComment: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies\"],\n createReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n createReviewComment: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments\"],\n deletePendingReview: [\"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n deleteReviewComment: [\"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n dismissReview: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals\"],\n get: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}\"],\n getReview: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n getReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n list: [\"GET /repos/{owner}/{repo}/pulls\"],\n listCommentsForReview: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\"],\n listCommits: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\"],\n listFiles: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\"],\n listRequestedReviewers: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n listReviewComments: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\"],\n listReviewCommentsForRepo: [\"GET /repos/{owner}/{repo}/pulls/comments\"],\n listReviews: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n merge: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n removeRequestedReviewers: [\"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n requestReviewers: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n submitReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events\"],\n update: [\"PATCH /repos/{owner}/{repo}/pulls/{pull_number}\"],\n updateBranch: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch\", {\n mediaType: {\n previews: [\"lydian\"]\n }\n }],\n updateReview: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n updateReviewComment: [\"PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}\"]\n },\n rateLimit: {\n get: [\"GET /rate_limit\"]\n },\n reactions: {\n createForCommitComment: [\"POST /repos/{owner}/{repo}/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForIssue: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForIssueComment: [\"POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForPullRequestReviewComment: [\"POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForRelease: [\"POST /repos/{owner}/{repo}/releases/{release_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForTeamDiscussionCommentInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForTeamDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForIssue: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForIssueComment: [\"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForPullRequestComment: [\"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForTeamDiscussion: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForTeamDiscussionComment: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteLegacy: [\"DELETE /reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }, {\n deprecated: \"octokit.rest.reactions.deleteLegacy() is deprecated, see https://docs.github.com/rest/reference/reactions/#delete-a-reaction-legacy\"\n }],\n listForCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForIssueComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForPullRequestReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForTeamDiscussionCommentInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForTeamDiscussionInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }]\n },\n repos: {\n acceptInvitation: [\"PATCH /user/repository_invitations/{invitation_id}\"],\n addAppAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n addCollaborator: [\"PUT /repos/{owner}/{repo}/collaborators/{username}\"],\n addStatusCheckContexts: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n addTeamAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n addUserAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n checkCollaborator: [\"GET /repos/{owner}/{repo}/collaborators/{username}\"],\n checkVulnerabilityAlerts: [\"GET /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n compareCommits: [\"GET /repos/{owner}/{repo}/compare/{base}...{head}\"],\n compareCommitsWithBasehead: [\"GET /repos/{owner}/{repo}/compare/{basehead}\"],\n createCommitComment: [\"POST /repos/{owner}/{repo}/commits/{commit_sha}/comments\"],\n createCommitSignatureProtection: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n createCommitStatus: [\"POST /repos/{owner}/{repo}/statuses/{sha}\"],\n createDeployKey: [\"POST /repos/{owner}/{repo}/keys\"],\n createDeployment: [\"POST /repos/{owner}/{repo}/deployments\"],\n createDeploymentStatus: [\"POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"],\n createDispatchEvent: [\"POST /repos/{owner}/{repo}/dispatches\"],\n createForAuthenticatedUser: [\"POST /user/repos\"],\n createFork: [\"POST /repos/{owner}/{repo}/forks\"],\n createInOrg: [\"POST /orgs/{org}/repos\"],\n createOrUpdateEnvironment: [\"PUT /repos/{owner}/{repo}/environments/{environment_name}\"],\n createOrUpdateFileContents: [\"PUT /repos/{owner}/{repo}/contents/{path}\"],\n createPagesSite: [\"POST /repos/{owner}/{repo}/pages\", {\n mediaType: {\n previews: [\"switcheroo\"]\n }\n }],\n createRelease: [\"POST /repos/{owner}/{repo}/releases\"],\n createUsingTemplate: [\"POST /repos/{template_owner}/{template_repo}/generate\", {\n mediaType: {\n previews: [\"baptiste\"]\n }\n }],\n createWebhook: [\"POST /repos/{owner}/{repo}/hooks\"],\n declineInvitation: [\"DELETE /user/repository_invitations/{invitation_id}\"],\n delete: [\"DELETE /repos/{owner}/{repo}\"],\n deleteAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"],\n deleteAdminBranchProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n deleteAnEnvironment: [\"DELETE /repos/{owner}/{repo}/environments/{environment_name}\"],\n deleteBranchProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection\"],\n deleteCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}\"],\n deleteCommitSignatureProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n deleteDeployKey: [\"DELETE /repos/{owner}/{repo}/keys/{key_id}\"],\n deleteDeployment: [\"DELETE /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n deleteFile: [\"DELETE /repos/{owner}/{repo}/contents/{path}\"],\n deleteInvitation: [\"DELETE /repos/{owner}/{repo}/invitations/{invitation_id}\"],\n deletePagesSite: [\"DELETE /repos/{owner}/{repo}/pages\", {\n mediaType: {\n previews: [\"switcheroo\"]\n }\n }],\n deletePullRequestReviewProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n deleteRelease: [\"DELETE /repos/{owner}/{repo}/releases/{release_id}\"],\n deleteReleaseAsset: [\"DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n deleteWebhook: [\"DELETE /repos/{owner}/{repo}/hooks/{hook_id}\"],\n disableAutomatedSecurityFixes: [\"DELETE /repos/{owner}/{repo}/automated-security-fixes\", {\n mediaType: {\n previews: [\"london\"]\n }\n }],\n disableVulnerabilityAlerts: [\"DELETE /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n downloadArchive: [\"GET /repos/{owner}/{repo}/zipball/{ref}\", {}, {\n renamed: [\"repos\", \"downloadZipballArchive\"]\n }],\n downloadTarballArchive: [\"GET /repos/{owner}/{repo}/tarball/{ref}\"],\n downloadZipballArchive: [\"GET /repos/{owner}/{repo}/zipball/{ref}\"],\n enableAutomatedSecurityFixes: [\"PUT /repos/{owner}/{repo}/automated-security-fixes\", {\n mediaType: {\n previews: [\"london\"]\n }\n }],\n enableVulnerabilityAlerts: [\"PUT /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n get: [\"GET /repos/{owner}/{repo}\"],\n getAccessRestrictions: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"],\n getAdminBranchProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n getAllEnvironments: [\"GET /repos/{owner}/{repo}/environments\"],\n getAllStatusCheckContexts: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\"],\n getAllTopics: [\"GET /repos/{owner}/{repo}/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n getAppsWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\"],\n getBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}\"],\n getBranchProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection\"],\n getClones: [\"GET /repos/{owner}/{repo}/traffic/clones\"],\n getCodeFrequencyStats: [\"GET /repos/{owner}/{repo}/stats/code_frequency\"],\n getCollaboratorPermissionLevel: [\"GET /repos/{owner}/{repo}/collaborators/{username}/permission\"],\n getCombinedStatusForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/status\"],\n getCommit: [\"GET /repos/{owner}/{repo}/commits/{ref}\"],\n getCommitActivityStats: [\"GET /repos/{owner}/{repo}/stats/commit_activity\"],\n getCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}\"],\n getCommitSignatureProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n getCommunityProfileMetrics: [\"GET /repos/{owner}/{repo}/community/profile\"],\n getContent: [\"GET /repos/{owner}/{repo}/contents/{path}\"],\n getContributorsStats: [\"GET /repos/{owner}/{repo}/stats/contributors\"],\n getDeployKey: [\"GET /repos/{owner}/{repo}/keys/{key_id}\"],\n getDeployment: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n getDeploymentStatus: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}\"],\n getEnvironment: [\"GET /repos/{owner}/{repo}/environments/{environment_name}\"],\n getLatestPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/latest\"],\n getLatestRelease: [\"GET /repos/{owner}/{repo}/releases/latest\"],\n getPages: [\"GET /repos/{owner}/{repo}/pages\"],\n getPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/{build_id}\"],\n getPagesHealthCheck: [\"GET /repos/{owner}/{repo}/pages/health\"],\n getParticipationStats: [\"GET /repos/{owner}/{repo}/stats/participation\"],\n getPullRequestReviewProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n getPunchCardStats: [\"GET /repos/{owner}/{repo}/stats/punch_card\"],\n getReadme: [\"GET /repos/{owner}/{repo}/readme\"],\n getReadmeInDirectory: [\"GET /repos/{owner}/{repo}/readme/{dir}\"],\n getRelease: [\"GET /repos/{owner}/{repo}/releases/{release_id}\"],\n getReleaseAsset: [\"GET /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n getReleaseByTag: [\"GET /repos/{owner}/{repo}/releases/tags/{tag}\"],\n getStatusChecksProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n getTeamsWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\"],\n getTopPaths: [\"GET /repos/{owner}/{repo}/traffic/popular/paths\"],\n getTopReferrers: [\"GET /repos/{owner}/{repo}/traffic/popular/referrers\"],\n getUsersWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\"],\n getViews: [\"GET /repos/{owner}/{repo}/traffic/views\"],\n getWebhook: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}\"],\n getWebhookConfigForRepo: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}/config\"],\n listBranches: [\"GET /repos/{owner}/{repo}/branches\"],\n listBranchesForHeadCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head\", {\n mediaType: {\n previews: [\"groot\"]\n }\n }],\n listCollaborators: [\"GET /repos/{owner}/{repo}/collaborators\"],\n listCommentsForCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\"],\n listCommitCommentsForRepo: [\"GET /repos/{owner}/{repo}/comments\"],\n listCommitStatusesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/statuses\"],\n listCommits: [\"GET /repos/{owner}/{repo}/commits\"],\n listContributors: [\"GET /repos/{owner}/{repo}/contributors\"],\n listDeployKeys: [\"GET /repos/{owner}/{repo}/keys\"],\n listDeploymentStatuses: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"],\n listDeployments: [\"GET /repos/{owner}/{repo}/deployments\"],\n listForAuthenticatedUser: [\"GET /user/repos\"],\n listForOrg: [\"GET /orgs/{org}/repos\"],\n listForUser: [\"GET /users/{username}/repos\"],\n listForks: [\"GET /repos/{owner}/{repo}/forks\"],\n listInvitations: [\"GET /repos/{owner}/{repo}/invitations\"],\n listInvitationsForAuthenticatedUser: [\"GET /user/repository_invitations\"],\n listLanguages: [\"GET /repos/{owner}/{repo}/languages\"],\n listPagesBuilds: [\"GET /repos/{owner}/{repo}/pages/builds\"],\n listPublic: [\"GET /repositories\"],\n listPullRequestsAssociatedWithCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\", {\n mediaType: {\n previews: [\"groot\"]\n }\n }],\n listReleaseAssets: [\"GET /repos/{owner}/{repo}/releases/{release_id}/assets\"],\n listReleases: [\"GET /repos/{owner}/{repo}/releases\"],\n listTags: [\"GET /repos/{owner}/{repo}/tags\"],\n listTeams: [\"GET /repos/{owner}/{repo}/teams\"],\n listWebhooks: [\"GET /repos/{owner}/{repo}/hooks\"],\n merge: [\"POST /repos/{owner}/{repo}/merges\"],\n pingWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/pings\"],\n removeAppAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n removeCollaborator: [\"DELETE /repos/{owner}/{repo}/collaborators/{username}\"],\n removeStatusCheckContexts: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n removeStatusCheckProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n removeTeamAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n removeUserAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n renameBranch: [\"POST /repos/{owner}/{repo}/branches/{branch}/rename\"],\n replaceAllTopics: [\"PUT /repos/{owner}/{repo}/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n requestPagesBuild: [\"POST /repos/{owner}/{repo}/pages/builds\"],\n setAdminBranchProtection: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n setAppAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n setStatusCheckContexts: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n setTeamAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n setUserAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n testPushWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/tests\"],\n transfer: [\"POST /repos/{owner}/{repo}/transfer\"],\n update: [\"PATCH /repos/{owner}/{repo}\"],\n updateBranchProtection: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection\"],\n updateCommitComment: [\"PATCH /repos/{owner}/{repo}/comments/{comment_id}\"],\n updateInformationAboutPagesSite: [\"PUT /repos/{owner}/{repo}/pages\"],\n updateInvitation: [\"PATCH /repos/{owner}/{repo}/invitations/{invitation_id}\"],\n updatePullRequestReviewProtection: [\"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n updateRelease: [\"PATCH /repos/{owner}/{repo}/releases/{release_id}\"],\n updateReleaseAsset: [\"PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n updateStatusCheckPotection: [\"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\", {}, {\n renamed: [\"repos\", \"updateStatusCheckProtection\"]\n }],\n updateStatusCheckProtection: [\"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n updateWebhook: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}\"],\n updateWebhookConfigForRepo: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config\"],\n uploadReleaseAsset: [\"POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}\", {\n baseUrl: \"https://uploads.github.com\"\n }]\n },\n search: {\n code: [\"GET /search/code\"],\n commits: [\"GET /search/commits\", {\n mediaType: {\n previews: [\"cloak\"]\n }\n }],\n issuesAndPullRequests: [\"GET /search/issues\"],\n labels: [\"GET /search/labels\"],\n repos: [\"GET /search/repositories\"],\n topics: [\"GET /search/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n users: [\"GET /search/users\"]\n },\n secretScanning: {\n getAlert: [\"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/secret-scanning/alerts\"],\n updateAlert: [\"PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\"]\n },\n teams: {\n addOrUpdateMembershipForUserInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n addOrUpdateProjectPermissionsInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n addOrUpdateRepoPermissionsInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n checkPermissionsForProjectInOrg: [\"GET /orgs/{org}/teams/{team_slug}/projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n checkPermissionsForRepoInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n create: [\"POST /orgs/{org}/teams\"],\n createDiscussionCommentInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"],\n createDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions\"],\n deleteDiscussionCommentInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n deleteDiscussionInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n deleteInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}\"],\n getByName: [\"GET /orgs/{org}/teams/{team_slug}\"],\n getDiscussionCommentInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n getDiscussionInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n getMembershipForUserInOrg: [\"GET /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n list: [\"GET /orgs/{org}/teams\"],\n listChildInOrg: [\"GET /orgs/{org}/teams/{team_slug}/teams\"],\n listDiscussionCommentsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"],\n listDiscussionsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions\"],\n listForAuthenticatedUser: [\"GET /user/teams\"],\n listMembersInOrg: [\"GET /orgs/{org}/teams/{team_slug}/members\"],\n listPendingInvitationsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/invitations\"],\n listProjectsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listReposInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos\"],\n removeMembershipForUserInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n removeProjectInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}\"],\n removeRepoInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n updateDiscussionCommentInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n updateDiscussionInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n updateInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}\"]\n },\n users: {\n addEmailForAuthenticated: [\"POST /user/emails\"],\n block: [\"PUT /user/blocks/{username}\"],\n checkBlocked: [\"GET /user/blocks/{username}\"],\n checkFollowingForUser: [\"GET /users/{username}/following/{target_user}\"],\n checkPersonIsFollowedByAuthenticated: [\"GET /user/following/{username}\"],\n createGpgKeyForAuthenticated: [\"POST /user/gpg_keys\"],\n createPublicSshKeyForAuthenticated: [\"POST /user/keys\"],\n deleteEmailForAuthenticated: [\"DELETE /user/emails\"],\n deleteGpgKeyForAuthenticated: [\"DELETE /user/gpg_keys/{gpg_key_id}\"],\n deletePublicSshKeyForAuthenticated: [\"DELETE /user/keys/{key_id}\"],\n follow: [\"PUT /user/following/{username}\"],\n getAuthenticated: [\"GET /user\"],\n getByUsername: [\"GET /users/{username}\"],\n getContextForUser: [\"GET /users/{username}/hovercard\"],\n getGpgKeyForAuthenticated: [\"GET /user/gpg_keys/{gpg_key_id}\"],\n getPublicSshKeyForAuthenticated: [\"GET /user/keys/{key_id}\"],\n list: [\"GET /users\"],\n listBlockedByAuthenticated: [\"GET /user/blocks\"],\n listEmailsForAuthenticated: [\"GET /user/emails\"],\n listFollowedByAuthenticated: [\"GET /user/following\"],\n listFollowersForAuthenticatedUser: [\"GET /user/followers\"],\n listFollowersForUser: [\"GET /users/{username}/followers\"],\n listFollowingForUser: [\"GET /users/{username}/following\"],\n listGpgKeysForAuthenticated: [\"GET /user/gpg_keys\"],\n listGpgKeysForUser: [\"GET /users/{username}/gpg_keys\"],\n listPublicEmailsForAuthenticated: [\"GET /user/public_emails\"],\n listPublicKeysForUser: [\"GET /users/{username}/keys\"],\n listPublicSshKeysForAuthenticated: [\"GET /user/keys\"],\n setPrimaryEmailVisibilityForAuthenticated: [\"PATCH /user/email/visibility\"],\n unblock: [\"DELETE /user/blocks/{username}\"],\n unfollow: [\"DELETE /user/following/{username}\"],\n updateAuthenticated: [\"PATCH /user\"]\n }\n};\n\nconst VERSION = \"5.3.1\";\n\nfunction endpointsToMethods(octokit, endpointsMap) {\n const newMethods = {};\n\n for (const [scope, endpoints] of Object.entries(endpointsMap)) {\n for (const [methodName, endpoint] of Object.entries(endpoints)) {\n const [route, defaults, decorations] = endpoint;\n const [method, url] = route.split(/ /);\n const endpointDefaults = Object.assign({\n method,\n url\n }, defaults);\n\n if (!newMethods[scope]) {\n newMethods[scope] = {};\n }\n\n const scopeMethods = newMethods[scope];\n\n if (decorations) {\n scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations);\n continue;\n }\n\n scopeMethods[methodName] = octokit.request.defaults(endpointDefaults);\n }\n }\n\n return newMethods;\n}\n\nfunction decorate(octokit, scope, methodName, defaults, decorations) {\n const requestWithDefaults = octokit.request.defaults(defaults);\n /* istanbul ignore next */\n\n function withDecorations(...args) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData`\n\n if (decorations.mapToData) {\n options = Object.assign({}, options, {\n data: options[decorations.mapToData],\n [decorations.mapToData]: undefined\n });\n return requestWithDefaults(options);\n }\n\n if (decorations.renamed) {\n const [newScope, newMethodName] = decorations.renamed;\n octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`);\n }\n\n if (decorations.deprecated) {\n octokit.log.warn(decorations.deprecated);\n }\n\n if (decorations.renamedParameters) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n const options = requestWithDefaults.endpoint.merge(...args);\n\n for (const [name, alias] of Object.entries(decorations.renamedParameters)) {\n if (name in options) {\n octokit.log.warn(`\"${name}\" parameter is deprecated for \"octokit.${scope}.${methodName}()\". Use \"${alias}\" instead`);\n\n if (!(alias in options)) {\n options[alias] = options[name];\n }\n\n delete options[name];\n }\n }\n\n return requestWithDefaults(options);\n } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n\n\n return requestWithDefaults(...args);\n }\n\n return Object.assign(withDecorations, requestWithDefaults);\n}\n\nfunction restEndpointMethods(octokit) {\n const api = endpointsToMethods(octokit, Endpoints);\n return {\n rest: api\n };\n}\nrestEndpointMethods.VERSION = VERSION;\nfunction legacyRestEndpointMethods(octokit) {\n const api = endpointsToMethods(octokit, Endpoints);\n return _objectSpread2(_objectSpread2({}, api), {}, {\n rest: api\n });\n}\nlegacyRestEndpointMethods.VERSION = VERSION;\n\nexports.legacyRestEndpointMethods = legacyRestEndpointMethods;\nexports.restEndpointMethods = restEndpointMethods;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar deprecation = require('deprecation');\nvar once = _interopDefault(require('once'));\n\nconst logOnce = once(deprecation => console.warn(deprecation));\n/**\n * Error with extra properties to help with debugging\n */\n\nclass RequestError extends Error {\n constructor(message, statusCode, options) {\n super(message); // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = \"HttpError\";\n this.status = statusCode;\n Object.defineProperty(this, \"code\", {\n get() {\n logOnce(new deprecation.Deprecation(\"[@octokit/request-error] `error.code` is deprecated, use `error.status`.\"));\n return statusCode;\n }\n\n });\n this.headers = options.headers || {}; // redact request credentials without mutating original request options\n\n const requestCopy = Object.assign({}, options.request);\n\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(/ .*$/, \" [REDACTED]\")\n });\n }\n\n requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit\n // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications\n .replace(/\\bclient_secret=\\w+/g, \"client_secret=[REDACTED]\") // OAuth tokens can be passed as URL query parameters, although it is not recommended\n // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header\n .replace(/\\baccess_token=\\w+/g, \"access_token=[REDACTED]\");\n this.request = requestCopy;\n }\n\n}\n\nexports.RequestError = RequestError;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar endpoint = require('@octokit/endpoint');\nvar universalUserAgent = require('universal-user-agent');\nvar isPlainObject = require('is-plain-object');\nvar nodeFetch = _interopDefault(require('node-fetch'));\nvar requestError = require('@octokit/request-error');\n\nconst VERSION = \"5.4.15\";\n\nfunction getBufferResponse(response) {\n return response.arrayBuffer();\n}\n\nfunction fetchWrapper(requestOptions) {\n if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {\n requestOptions.body = JSON.stringify(requestOptions.body);\n }\n\n let headers = {};\n let status;\n let url;\n const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch;\n return fetch(requestOptions.url, Object.assign({\n method: requestOptions.method,\n body: requestOptions.body,\n headers: requestOptions.headers,\n redirect: requestOptions.redirect\n }, // `requestOptions.request.agent` type is incompatible\n // see https://github.com/octokit/types.ts/pull/264\n requestOptions.request)).then(response => {\n url = response.url;\n status = response.status;\n\n for (const keyAndValue of response.headers) {\n headers[keyAndValue[0]] = keyAndValue[1];\n }\n\n if (status === 204 || status === 205) {\n return;\n } // GitHub API returns 200 for HEAD requests\n\n\n if (requestOptions.method === \"HEAD\") {\n if (status < 400) {\n return;\n }\n\n throw new requestError.RequestError(response.statusText, status, {\n headers,\n request: requestOptions\n });\n }\n\n if (status === 304) {\n throw new requestError.RequestError(\"Not modified\", status, {\n headers,\n request: requestOptions\n });\n }\n\n if (status >= 400) {\n return response.text().then(message => {\n const error = new requestError.RequestError(message, status, {\n headers,\n request: requestOptions\n });\n\n try {\n let responseBody = JSON.parse(error.message);\n Object.assign(error, responseBody);\n let errors = responseBody.errors; // Assumption `errors` would always be in Array format\n\n error.message = error.message + \": \" + errors.map(JSON.stringify).join(\", \");\n } catch (e) {// ignore, see octokit/rest.js#684\n }\n\n throw error;\n });\n }\n\n const contentType = response.headers.get(\"content-type\");\n\n if (/application\\/json/.test(contentType)) {\n return response.json();\n }\n\n if (!contentType || /^text\\/|charset=utf-8$/.test(contentType)) {\n return response.text();\n }\n\n return getBufferResponse(response);\n }).then(data => {\n return {\n status,\n url,\n headers,\n data\n };\n }).catch(error => {\n if (error instanceof requestError.RequestError) {\n throw error;\n }\n\n throw new requestError.RequestError(error.message, 500, {\n headers,\n request: requestOptions\n });\n });\n}\n\nfunction withDefaults(oldEndpoint, newDefaults) {\n const endpoint = oldEndpoint.defaults(newDefaults);\n\n const newApi = function (route, parameters) {\n const endpointOptions = endpoint.merge(route, parameters);\n\n if (!endpointOptions.request || !endpointOptions.request.hook) {\n return fetchWrapper(endpoint.parse(endpointOptions));\n }\n\n const request = (route, parameters) => {\n return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));\n };\n\n Object.assign(request, {\n endpoint,\n defaults: withDefaults.bind(null, endpoint)\n });\n return endpointOptions.request.hook(request, endpointOptions);\n };\n\n return Object.assign(newApi, {\n endpoint,\n defaults: withDefaults.bind(null, endpoint)\n });\n}\n\nconst request = withDefaults(endpoint.endpoint, {\n headers: {\n \"user-agent\": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`\n }\n});\n\nexports.request = request;\n//# sourceMappingURL=index.js.map\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n\n newInvalidAsn1Error: function (msg) {\n var e = new Error();\n e.name = 'InvalidAsn1Error';\n e.message = msg || '';\n return e;\n }\n\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar errors = require('./errors');\nvar types = require('./types');\n\nvar Reader = require('./reader');\nvar Writer = require('./writer');\n\n\n// --- Exports\n\nmodule.exports = {\n\n Reader: Reader,\n\n Writer: Writer\n\n};\n\nfor (var t in types) {\n if (types.hasOwnProperty(t))\n module.exports[t] = types[t];\n}\nfor (var e in errors) {\n if (errors.hasOwnProperty(e))\n module.exports[e] = errors[e];\n}\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\n\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\n\n\n// --- API\n\nfunction Reader(data) {\n if (!data || !Buffer.isBuffer(data))\n throw new TypeError('data must be a node Buffer');\n\n this._buf = data;\n this._size = data.length;\n\n // These hold the \"current\" state\n this._len = 0;\n this._offset = 0;\n}\n\nObject.defineProperty(Reader.prototype, 'length', {\n enumerable: true,\n get: function () { return (this._len); }\n});\n\nObject.defineProperty(Reader.prototype, 'offset', {\n enumerable: true,\n get: function () { return (this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'remain', {\n get: function () { return (this._size - this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'buffer', {\n get: function () { return (this._buf.slice(this._offset)); }\n});\n\n\n/**\n * Reads a single byte and advances offset; you can pass in `true` to make this\n * a \"peek\" operation (i.e., get the byte, but don't advance the offset).\n *\n * @param {Boolean} peek true means don't move offset.\n * @return {Number} the next byte, null if not enough data.\n */\nReader.prototype.readByte = function (peek) {\n if (this._size - this._offset < 1)\n return null;\n\n var b = this._buf[this._offset] & 0xff;\n\n if (!peek)\n this._offset += 1;\n\n return b;\n};\n\n\nReader.prototype.peek = function () {\n return this.readByte(true);\n};\n\n\n/**\n * Reads a (potentially) variable length off the BER buffer. This call is\n * not really meant to be called directly, as callers have to manipulate\n * the internal buffer afterwards.\n *\n * As a result of this call, you can call `Reader.length`, until the\n * next thing called that does a readLength.\n *\n * @return {Number} the amount of offset to advance the buffer.\n * @throws {InvalidAsn1Error} on bad ASN.1\n */\nReader.prototype.readLength = function (offset) {\n if (offset === undefined)\n offset = this._offset;\n\n if (offset >= this._size)\n return null;\n\n var lenB = this._buf[offset++] & 0xff;\n if (lenB === null)\n return null;\n\n if ((lenB & 0x80) === 0x80) {\n lenB &= 0x7f;\n\n if (lenB === 0)\n throw newInvalidAsn1Error('Indefinite length not supported');\n\n if (lenB > 4)\n throw newInvalidAsn1Error('encoding too long');\n\n if (this._size - offset < lenB)\n return null;\n\n this._len = 0;\n for (var i = 0; i < lenB; i++)\n this._len = (this._len << 8) + (this._buf[offset++] & 0xff);\n\n } else {\n // Wasn't a variable length\n this._len = lenB;\n }\n\n return offset;\n};\n\n\n/**\n * Parses the next sequence in this BER buffer.\n *\n * To get the length of the sequence, call `Reader.length`.\n *\n * @return {Number} the sequence's tag.\n */\nReader.prototype.readSequence = function (tag) {\n var seq = this.peek();\n if (seq === null)\n return null;\n if (tag !== undefined && tag !== seq)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + seq.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n this._offset = o;\n return seq;\n};\n\n\nReader.prototype.readInt = function () {\n return this._readTag(ASN1.Integer);\n};\n\n\nReader.prototype.readBoolean = function () {\n return (this._readTag(ASN1.Boolean) === 0 ? false : true);\n};\n\n\nReader.prototype.readEnumeration = function () {\n return this._readTag(ASN1.Enumeration);\n};\n\n\nReader.prototype.readString = function (tag, retbuf) {\n if (!tag)\n tag = ASN1.OctetString;\n\n var b = this.peek();\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n\n if (o === null)\n return null;\n\n if (this.length > this._size - o)\n return null;\n\n this._offset = o;\n\n if (this.length === 0)\n return retbuf ? Buffer.alloc(0) : '';\n\n var str = this._buf.slice(this._offset, this._offset + this.length);\n this._offset += this.length;\n\n return retbuf ? str : str.toString('utf8');\n};\n\nReader.prototype.readOID = function (tag) {\n if (!tag)\n tag = ASN1.OID;\n\n var b = this.readString(tag, true);\n if (b === null)\n return null;\n\n var values = [];\n var value = 0;\n\n for (var i = 0; i < b.length; i++) {\n var byte = b[i] & 0xff;\n\n value <<= 7;\n value += byte & 0x7f;\n if ((byte & 0x80) === 0) {\n values.push(value);\n value = 0;\n }\n }\n\n value = values.shift();\n values.unshift(value % 40);\n values.unshift((value / 40) >> 0);\n\n return values.join('.');\n};\n\n\nReader.prototype._readTag = function (tag) {\n assert.ok(tag !== undefined);\n\n var b = this.peek();\n\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n if (this.length > 4)\n throw newInvalidAsn1Error('Integer too long: ' + this.length);\n\n if (this.length > this._size - o)\n return null;\n this._offset = o;\n\n var fb = this._buf[this._offset];\n var value = 0;\n\n for (var i = 0; i < this.length; i++) {\n value <<= 8;\n value |= (this._buf[this._offset++] & 0xff);\n }\n\n if ((fb & 0x80) === 0x80 && i !== 4)\n value -= (1 << (i * 8));\n\n return value >> 0;\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Reader;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n EOC: 0,\n Boolean: 1,\n Integer: 2,\n BitString: 3,\n OctetString: 4,\n Null: 5,\n OID: 6,\n ObjectDescriptor: 7,\n External: 8,\n Real: 9, // float\n Enumeration: 10,\n PDV: 11,\n Utf8String: 12,\n RelativeOID: 13,\n Sequence: 16,\n Set: 17,\n NumericString: 18,\n PrintableString: 19,\n T61String: 20,\n VideotexString: 21,\n IA5String: 22,\n UTCTime: 23,\n GeneralizedTime: 24,\n GraphicString: 25,\n VisibleString: 26,\n GeneralString: 28,\n UniversalString: 29,\n CharacterString: 30,\n BMPString: 31,\n Constructor: 32,\n Context: 128\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\nvar DEFAULT_OPTS = {\n size: 1024,\n growthFactor: 8\n};\n\n\n// --- Helpers\n\nfunction merge(from, to) {\n assert.ok(from);\n assert.equal(typeof (from), 'object');\n assert.ok(to);\n assert.equal(typeof (to), 'object');\n\n var keys = Object.getOwnPropertyNames(from);\n keys.forEach(function (key) {\n if (to[key])\n return;\n\n var value = Object.getOwnPropertyDescriptor(from, key);\n Object.defineProperty(to, key, value);\n });\n\n return to;\n}\n\n\n\n// --- API\n\nfunction Writer(options) {\n options = merge(DEFAULT_OPTS, options || {});\n\n this._buf = Buffer.alloc(options.size || 1024);\n this._size = this._buf.length;\n this._offset = 0;\n this._options = options;\n\n // A list of offsets in the buffer where we need to insert\n // sequence tag/len pairs.\n this._seq = [];\n}\n\nObject.defineProperty(Writer.prototype, 'buffer', {\n get: function () {\n if (this._seq.length)\n throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');\n\n return (this._buf.slice(0, this._offset));\n }\n});\n\nWriter.prototype.writeByte = function (b) {\n if (typeof (b) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(1);\n this._buf[this._offset++] = b;\n};\n\n\nWriter.prototype.writeInt = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Integer;\n\n var sz = 4;\n\n while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&\n (sz > 1)) {\n sz--;\n i <<= 8;\n }\n\n if (sz > 4)\n throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');\n\n this._ensure(2 + sz);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = sz;\n\n while (sz-- > 0) {\n this._buf[this._offset++] = ((i & 0xff000000) >>> 24);\n i <<= 8;\n }\n\n};\n\n\nWriter.prototype.writeNull = function () {\n this.writeByte(ASN1.Null);\n this.writeByte(0x00);\n};\n\n\nWriter.prototype.writeEnumeration = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Enumeration;\n\n return this.writeInt(i, tag);\n};\n\n\nWriter.prototype.writeBoolean = function (b, tag) {\n if (typeof (b) !== 'boolean')\n throw new TypeError('argument must be a Boolean');\n if (typeof (tag) !== 'number')\n tag = ASN1.Boolean;\n\n this._ensure(3);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = 0x01;\n this._buf[this._offset++] = b ? 0xff : 0x00;\n};\n\n\nWriter.prototype.writeString = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');\n if (typeof (tag) !== 'number')\n tag = ASN1.OctetString;\n\n var len = Buffer.byteLength(s);\n this.writeByte(tag);\n this.writeLength(len);\n if (len) {\n this._ensure(len);\n this._buf.write(s, this._offset);\n this._offset += len;\n }\n};\n\n\nWriter.prototype.writeBuffer = function (buf, tag) {\n if (typeof (tag) !== 'number')\n throw new TypeError('tag must be a number');\n if (!Buffer.isBuffer(buf))\n throw new TypeError('argument must be a buffer');\n\n this.writeByte(tag);\n this.writeLength(buf.length);\n this._ensure(buf.length);\n buf.copy(this._buf, this._offset, 0, buf.length);\n this._offset += buf.length;\n};\n\n\nWriter.prototype.writeStringArray = function (strings) {\n if ((!strings instanceof Array))\n throw new TypeError('argument must be an Array[String]');\n\n var self = this;\n strings.forEach(function (s) {\n self.writeString(s);\n });\n};\n\n// This is really to solve DER cases, but whatever for now\nWriter.prototype.writeOID = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string');\n if (typeof (tag) !== 'number')\n tag = ASN1.OID;\n\n if (!/^([0-9]+\\.){3,}[0-9]+$/.test(s))\n throw new Error('argument is not a valid OID string');\n\n function encodeOctet(bytes, octet) {\n if (octet < 128) {\n bytes.push(octet);\n } else if (octet < 16384) {\n bytes.push((octet >>> 7) | 0x80);\n bytes.push(octet & 0x7F);\n } else if (octet < 2097152) {\n bytes.push((octet >>> 14) | 0x80);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else if (octet < 268435456) {\n bytes.push((octet >>> 21) | 0x80);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else {\n bytes.push(((octet >>> 28) | 0x80) & 0xFF);\n bytes.push(((octet >>> 21) | 0x80) & 0xFF);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n }\n }\n\n var tmp = s.split('.');\n var bytes = [];\n bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));\n tmp.slice(2).forEach(function (b) {\n encodeOctet(bytes, parseInt(b, 10));\n });\n\n var self = this;\n this._ensure(2 + bytes.length);\n this.writeByte(tag);\n this.writeLength(bytes.length);\n bytes.forEach(function (b) {\n self.writeByte(b);\n });\n};\n\n\nWriter.prototype.writeLength = function (len) {\n if (typeof (len) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(4);\n\n if (len <= 0x7f) {\n this._buf[this._offset++] = len;\n } else if (len <= 0xff) {\n this._buf[this._offset++] = 0x81;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffff) {\n this._buf[this._offset++] = 0x82;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffffff) {\n this._buf[this._offset++] = 0x83;\n this._buf[this._offset++] = len >> 16;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else {\n throw newInvalidAsn1Error('Length too long (> 4 bytes)');\n }\n};\n\nWriter.prototype.startSequence = function (tag) {\n if (typeof (tag) !== 'number')\n tag = ASN1.Sequence | ASN1.Constructor;\n\n this.writeByte(tag);\n this._seq.push(this._offset);\n this._ensure(3);\n this._offset += 3;\n};\n\n\nWriter.prototype.endSequence = function () {\n var seq = this._seq.pop();\n var start = seq + 3;\n var len = this._offset - start;\n\n if (len <= 0x7f) {\n this._shift(start, len, -2);\n this._buf[seq] = len;\n } else if (len <= 0xff) {\n this._shift(start, len, -1);\n this._buf[seq] = 0x81;\n this._buf[seq + 1] = len;\n } else if (len <= 0xffff) {\n this._buf[seq] = 0x82;\n this._buf[seq + 1] = len >> 8;\n this._buf[seq + 2] = len;\n } else if (len <= 0xffffff) {\n this._shift(start, len, 1);\n this._buf[seq] = 0x83;\n this._buf[seq + 1] = len >> 16;\n this._buf[seq + 2] = len >> 8;\n this._buf[seq + 3] = len;\n } else {\n throw newInvalidAsn1Error('Sequence too long');\n }\n};\n\n\nWriter.prototype._shift = function (start, len, shift) {\n assert.ok(start !== undefined);\n assert.ok(len !== undefined);\n assert.ok(shift);\n\n this._buf.copy(this._buf, start + shift, start, start + len);\n this._offset += shift;\n};\n\nWriter.prototype._ensure = function (len) {\n assert.ok(len);\n\n if (this._size - this._offset < len) {\n var sz = this._size * this._options.growthFactor;\n if (sz - this._offset < len)\n sz += len;\n\n var buf = Buffer.alloc(sz);\n\n this._buf.copy(buf, 0, 0, this._offset);\n this._buf = buf;\n this._size = sz;\n }\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Writer;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n// If you have no idea what ASN.1 or BER is, see this:\n// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc\n\nvar Ber = require('./ber/index');\n\n\n\n// --- Exported API\n\nmodule.exports = {\n\n Ber: Ber,\n\n BerReader: Ber.Reader,\n\n BerWriter: Ber.Writer\n\n};\n","module.exports = require('./lib/axios');","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar buildFullPath = require('../core/buildFullPath');\nvar buildURL = require('./../helpers/buildURL');\nvar http = require('http');\nvar https = require('https');\nvar httpFollow = require('follow-redirects').http;\nvar httpsFollow = require('follow-redirects').https;\nvar url = require('url');\nvar zlib = require('zlib');\nvar VERSION = require('./../env/data').version;\nvar createError = require('../core/createError');\nvar enhanceError = require('../core/enhanceError');\nvar defaults = require('../defaults');\nvar Cancel = require('../cancel/Cancel');\n\nvar isHttps = /https:?/;\n\n/**\n *\n * @param {http.ClientRequestArgs} options\n * @param {AxiosProxyConfig} proxy\n * @param {string} location\n */\nfunction setProxy(options, proxy, location) {\n options.hostname = proxy.host;\n options.host = proxy.host;\n options.port = proxy.port;\n options.path = location;\n\n // Basic proxy authorization\n if (proxy.auth) {\n var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');\n options.headers['Proxy-Authorization'] = 'Basic ' + base64;\n }\n\n // If a proxy is used, any redirects must also pass through the proxy\n options.beforeRedirect = function beforeRedirect(redirection) {\n redirection.headers.host = redirection.host;\n setProxy(redirection, proxy, redirection.href);\n };\n}\n\n/*eslint consistent-return:0*/\nmodule.exports = function httpAdapter(config) {\n return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {\n var onCanceled;\n function done() {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', onCanceled);\n }\n }\n var resolve = function resolve(value) {\n done();\n resolvePromise(value);\n };\n var reject = function reject(value) {\n done();\n rejectPromise(value);\n };\n var data = config.data;\n var headers = config.headers;\n var headerNames = {};\n\n Object.keys(headers).forEach(function storeLowerName(name) {\n headerNames[name.toLowerCase()] = name;\n });\n\n // Set User-Agent (required by some servers)\n // See https://github.com/axios/axios/issues/69\n if ('user-agent' in headerNames) {\n // User-Agent is specified; handle case where no UA header is desired\n if (!headers[headerNames['user-agent']]) {\n delete headers[headerNames['user-agent']];\n }\n // Otherwise, use specified value\n } else {\n // Only set header if it hasn't been set in config\n headers['User-Agent'] = 'axios/' + VERSION;\n }\n\n if (data && !utils.isStream(data)) {\n if (Buffer.isBuffer(data)) {\n // Nothing to do...\n } else if (utils.isArrayBuffer(data)) {\n data = Buffer.from(new Uint8Array(data));\n } else if (utils.isString(data)) {\n data = Buffer.from(data, 'utf-8');\n } else {\n return reject(createError(\n 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',\n config\n ));\n }\n\n // Add Content-Length header if data exists\n if (!headerNames['content-length']) {\n headers['Content-Length'] = data.length;\n }\n }\n\n // HTTP basic authentication\n var auth = undefined;\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password || '';\n auth = username + ':' + password;\n }\n\n // Parse url\n var fullPath = buildFullPath(config.baseURL, config.url);\n var parsed = url.parse(fullPath);\n var protocol = parsed.protocol || 'http:';\n\n if (!auth && parsed.auth) {\n var urlAuth = parsed.auth.split(':');\n var urlUsername = urlAuth[0] || '';\n var urlPassword = urlAuth[1] || '';\n auth = urlUsername + ':' + urlPassword;\n }\n\n if (auth && headerNames.authorization) {\n delete headers[headerNames.authorization];\n }\n\n var isHttpsRequest = isHttps.test(protocol);\n var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;\n\n var options = {\n path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\\?/, ''),\n method: config.method.toUpperCase(),\n headers: headers,\n agent: agent,\n agents: { http: config.httpAgent, https: config.httpsAgent },\n auth: auth\n };\n\n if (config.socketPath) {\n options.socketPath = config.socketPath;\n } else {\n options.hostname = parsed.hostname;\n options.port = parsed.port;\n }\n\n var proxy = config.proxy;\n if (!proxy && proxy !== false) {\n var proxyEnv = protocol.slice(0, -1) + '_proxy';\n var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];\n if (proxyUrl) {\n var parsedProxyUrl = url.parse(proxyUrl);\n var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;\n var shouldProxy = true;\n\n if (noProxyEnv) {\n var noProxy = noProxyEnv.split(',').map(function trim(s) {\n return s.trim();\n });\n\n shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {\n if (!proxyElement) {\n return false;\n }\n if (proxyElement === '*') {\n return true;\n }\n if (proxyElement[0] === '.' &&\n parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {\n return true;\n }\n\n return parsed.hostname === proxyElement;\n });\n }\n\n if (shouldProxy) {\n proxy = {\n host: parsedProxyUrl.hostname,\n port: parsedProxyUrl.port,\n protocol: parsedProxyUrl.protocol\n };\n\n if (parsedProxyUrl.auth) {\n var proxyUrlAuth = parsedProxyUrl.auth.split(':');\n proxy.auth = {\n username: proxyUrlAuth[0],\n password: proxyUrlAuth[1]\n };\n }\n }\n }\n }\n\n if (proxy) {\n options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');\n setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);\n }\n\n var transport;\n var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);\n if (config.transport) {\n transport = config.transport;\n } else if (config.maxRedirects === 0) {\n transport = isHttpsProxy ? https : http;\n } else {\n if (config.maxRedirects) {\n options.maxRedirects = config.maxRedirects;\n }\n transport = isHttpsProxy ? httpsFollow : httpFollow;\n }\n\n if (config.maxBodyLength > -1) {\n options.maxBodyLength = config.maxBodyLength;\n }\n\n if (config.insecureHTTPParser) {\n options.insecureHTTPParser = config.insecureHTTPParser;\n }\n\n // Create the request\n var req = transport.request(options, function handleResponse(res) {\n if (req.aborted) return;\n\n // uncompress the response body transparently if required\n var stream = res;\n\n // return the last request in case of redirects\n var lastRequest = res.req || req;\n\n\n // if no content, is HEAD request or decompress disabled we should not decompress\n if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {\n switch (res.headers['content-encoding']) {\n /*eslint default-case:0*/\n case 'gzip':\n case 'compress':\n case 'deflate':\n // add the unzipper to the body stream processing pipeline\n stream = stream.pipe(zlib.createUnzip());\n\n // remove the content-encoding in order to not confuse downstream operations\n delete res.headers['content-encoding'];\n break;\n }\n }\n\n var response = {\n status: res.statusCode,\n statusText: res.statusMessage,\n headers: res.headers,\n config: config,\n request: lastRequest\n };\n\n if (config.responseType === 'stream') {\n response.data = stream;\n settle(resolve, reject, response);\n } else {\n var responseBuffer = [];\n var totalResponseBytes = 0;\n stream.on('data', function handleStreamData(chunk) {\n responseBuffer.push(chunk);\n totalResponseBytes += chunk.length;\n\n // make sure the content length is not over the maxContentLength if specified\n if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {\n stream.destroy();\n reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',\n config, null, lastRequest));\n }\n });\n\n stream.on('error', function handleStreamError(err) {\n if (req.aborted) return;\n reject(enhanceError(err, config, null, lastRequest));\n });\n\n stream.on('end', function handleStreamEnd() {\n var responseData = Buffer.concat(responseBuffer);\n if (config.responseType !== 'arraybuffer') {\n responseData = responseData.toString(config.responseEncoding);\n if (!config.responseEncoding || config.responseEncoding === 'utf8') {\n responseData = utils.stripBOM(responseData);\n }\n }\n\n response.data = responseData;\n settle(resolve, reject, response);\n });\n }\n });\n\n // Handle errors\n req.on('error', function handleRequestError(err) {\n if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return;\n reject(enhanceError(err, config, null, req));\n });\n\n // Handle request timeout\n if (config.timeout) {\n // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.\n var timeout = parseInt(config.timeout, 10);\n\n if (isNaN(timeout)) {\n reject(createError(\n 'error trying to parse `config.timeout` to int',\n config,\n 'ERR_PARSE_TIMEOUT',\n req\n ));\n\n return;\n }\n\n // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.\n // And timer callback will be fired, and abort() will be invoked before connection, then get \"socket hang up\" and code ECONNRESET.\n // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.\n // And then these socket which be hang up will devoring CPU little by little.\n // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.\n req.setTimeout(timeout, function handleRequestTimeout() {\n req.abort();\n var transitional = config.transitional || defaults.transitional;\n reject(createError(\n 'timeout of ' + timeout + 'ms exceeded',\n config,\n transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',\n req\n ));\n });\n }\n\n if (config.cancelToken || config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = function(cancel) {\n if (req.aborted) return;\n\n req.abort();\n reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);\n };\n\n config.cancelToken && config.cancelToken.subscribe(onCanceled);\n if (config.signal) {\n config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n\n // Send the request\n if (utils.isStream(data)) {\n data.on('error', function handleStreamError(err) {\n reject(enhanceError(err, config, null, req));\n }).pipe(req);\n } else {\n req.end(data);\n }\n });\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar createError = require('../core/createError');\nvar defaults = require('../defaults');\nvar Cancel = require('../cancel/Cancel');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n var onCanceled;\n function done() {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', onCanceled);\n }\n }\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';\n var transitional = config.transitional || defaults.transitional;\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(\n timeoutErrorMessage,\n config,\n transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken || config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = function(cancel) {\n if (!request) {\n return;\n }\n reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);\n request.abort();\n request = null;\n };\n\n config.cancelToken && config.cancelToken.subscribe(onCanceled);\n if (config.signal) {\n config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.Cancel = require('./cancel/Cancel');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\naxios.VERSION = require('./env/data').version;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n","'use strict';\n\nvar Cancel = require('./Cancel');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(function(cancel) {\n if (!token._listeners) return;\n\n var i;\n var l = token._listeners.length;\n\n for (i = 0; i < l; i++) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = function(onfulfilled) {\n var _resolve;\n // eslint-disable-next-line func-names\n var promise = new Promise(function(resolve) {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Subscribe to the cancel signal\n */\n\nCancelToken.prototype.subscribe = function subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n};\n\n/**\n * Unsubscribe from the cancel signal\n */\n\nCancelToken.prototype.unsubscribe = function unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n var index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = arguments[1] || {};\n config.url = arguments[0];\n } else {\n config = config || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\nvar enhanceError = require('./enhanceError');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\nvar Cancel = require('../cancel/Cancel');\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new Cancel('canceled');\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n };\n return error;\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(prop) {\n if (prop in config2) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n var mergeMap = {\n 'url': valueFromConfig2,\n 'method': valueFromConfig2,\n 'data': valueFromConfig2,\n 'baseURL': defaultToConfig2,\n 'transformRequest': defaultToConfig2,\n 'transformResponse': defaultToConfig2,\n 'paramsSerializer': defaultToConfig2,\n 'timeout': defaultToConfig2,\n 'timeoutMessage': defaultToConfig2,\n 'withCredentials': defaultToConfig2,\n 'adapter': defaultToConfig2,\n 'responseType': defaultToConfig2,\n 'xsrfCookieName': defaultToConfig2,\n 'xsrfHeaderName': defaultToConfig2,\n 'onUploadProgress': defaultToConfig2,\n 'onDownloadProgress': defaultToConfig2,\n 'decompress': defaultToConfig2,\n 'maxContentLength': defaultToConfig2,\n 'maxBodyLength': defaultToConfig2,\n 'transport': defaultToConfig2,\n 'httpAgent': defaultToConfig2,\n 'httpsAgent': defaultToConfig2,\n 'cancelToken': defaultToConfig2,\n 'socketPath': defaultToConfig2,\n 'responseEncoding': defaultToConfig2,\n 'validateStatus': mergeDirectKeys\n };\n\n utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {\n var merge = mergeMap[prop] || mergeDeepProperties;\n var configValue = merge(prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n};\n","'use strict';\n\nvar createError = require('./createError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('./../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\nvar enhanceError = require('./core/enhanceError');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n },\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional || defaults.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw enhanceError(e, this, 'E_JSON_PARSE');\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","module.exports = {\n \"version\": \"0.23.0\"\n};","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d\\+\\-\\.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return (typeof payload === 'object') && (payload.isAxiosError === true);\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\nvar VERSION = require('../env/data').version;\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')));\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new TypeError('option ' + opt + ' must be ' + result);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw Error('Unknown option ' + opt);\n }\n }\n}\n\nmodule.exports = {\n assertOptions: assertOptions,\n validators: validators\n};\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (toString.call(val) !== '[object Object]') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM\n};\n","'use strict';\n\nvar crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;\n\n/*\n * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a\n * result, it retains the original copyright and license. The two files are\n * under slightly different (but compatible) licenses, and are here combined in\n * one file.\n *\n * Credit for the actual porting work goes to:\n * Devi Mandiri \n */\n\n/*\n * The Blowfish portions are under the following license:\n *\n * Blowfish block cipher for OpenBSD\n * Copyright 1997 Niels Provos \n * All rights reserved.\n *\n * Implementation advice by David Mazieres .\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * The bcrypt_pbkdf portions are under the following license:\n *\n * Copyright (c) 2013 Ted Unangst \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n/*\n * Performance improvements (Javascript-specific):\n *\n * Copyright 2016, Joyent Inc\n * Author: Alex Wilson \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n// Ported from OpenBSD bcrypt_pbkdf.c v1.9\n\nvar BLF_J = 0;\n\nvar Blowfish = function() {\n this.S = [\n new Uint32Array([\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,\n 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,\n 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,\n 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,\n 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,\n 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,\n 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,\n 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,\n 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,\n 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,\n 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,\n 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,\n 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,\n 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,\n 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,\n 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,\n 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,\n 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,\n 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,\n 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,\n 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,\n 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,\n 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,\n 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,\n 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,\n 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,\n 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,\n 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,\n 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,\n 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,\n 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,\n 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,\n 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,\n 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,\n 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,\n 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,\n 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,\n 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,\n 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,\n 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,\n 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,\n 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,\n 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),\n new Uint32Array([\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,\n 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,\n 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,\n 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,\n 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,\n 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,\n 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,\n 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,\n 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,\n 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,\n 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,\n 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,\n 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,\n 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,\n 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,\n 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,\n 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,\n 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,\n 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,\n 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,\n 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,\n 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,\n 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,\n 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,\n 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,\n 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,\n 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,\n 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,\n 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,\n 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,\n 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,\n 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,\n 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,\n 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,\n 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,\n 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,\n 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,\n 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,\n 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,\n 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,\n 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,\n 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,\n 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),\n new Uint32Array([\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,\n 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,\n 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,\n 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,\n 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,\n 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,\n 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,\n 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,\n 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,\n 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,\n 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,\n 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,\n 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,\n 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,\n 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,\n 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,\n 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,\n 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,\n 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,\n 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,\n 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,\n 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,\n 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,\n 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,\n 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,\n 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,\n 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,\n 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,\n 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,\n 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,\n 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,\n 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,\n 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,\n 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,\n 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,\n 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,\n 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,\n 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,\n 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,\n 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,\n 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,\n 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,\n 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),\n new Uint32Array([\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,\n 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,\n 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,\n 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,\n 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,\n 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,\n 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,\n 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,\n 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,\n 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,\n 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,\n 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,\n 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,\n 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,\n 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,\n 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,\n 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,\n 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,\n 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,\n 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,\n 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,\n 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,\n 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,\n 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,\n 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,\n 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,\n 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,\n 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,\n 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,\n 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,\n 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,\n 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,\n 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,\n 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,\n 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,\n 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,\n 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,\n 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,\n 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,\n 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,\n 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,\n 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,\n 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])\n ];\n this.P = new Uint32Array([\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,\n 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,\n 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,\n 0x9216d5d9, 0x8979fb1b]);\n};\n\nfunction F(S, x8, i) {\n return (((S[0][x8[i+3]] +\n S[1][x8[i+2]]) ^\n S[2][x8[i+1]]) +\n S[3][x8[i]]);\n};\n\nBlowfish.prototype.encipher = function(x, x8) {\n if (x8 === undefined) {\n x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n }\n x[0] ^= this.P[0];\n for (var i = 1; i < 16; i += 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[17];\n x[1] = t;\n};\n\nBlowfish.prototype.decipher = function(x) {\n var x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n x[0] ^= this.P[17];\n for (var i = 16; i > 0; i -= 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[0];\n x[1] = t;\n};\n\nfunction stream2word(data, databytes){\n var i, temp = 0;\n for (i = 0; i < 4; i++, BLF_J++) {\n if (BLF_J >= databytes) BLF_J = 0;\n temp = (temp << 8) | data[BLF_J];\n }\n return temp;\n};\n\nBlowfish.prototype.expand0state = function(key, keybytes) {\n var d = new Uint32Array(2), i, k;\n var d8 = new Uint8Array(d.buffer);\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n BLF_J = 0;\n\n for (i = 0; i < 18; i += 2) {\n this.encipher(d, d8);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n this.encipher(d, d8);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n};\n\nBlowfish.prototype.expandstate = function(data, databytes, key, keybytes) {\n var d = new Uint32Array(2), i, k;\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n\n for (i = 0, BLF_J = 0; i < 18; i += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n BLF_J = 0;\n};\n\nBlowfish.prototype.enc = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.encipher(data.subarray(i*2));\n }\n};\n\nBlowfish.prototype.dec = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.decipher(data.subarray(i*2));\n }\n};\n\nvar BCRYPT_BLOCKS = 8,\n BCRYPT_HASHSIZE = 32;\n\nfunction bcrypt_hash(sha2pass, sha2salt, out) {\n var state = new Blowfish(),\n cdata = new Uint32Array(BCRYPT_BLOCKS), i,\n ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,\n 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,\n 105,116,101]); //\"OxychromaticBlowfishSwatDynamite\"\n\n state.expandstate(sha2salt, 64, sha2pass, 64);\n for (i = 0; i < 64; i++) {\n state.expand0state(sha2salt, 64);\n state.expand0state(sha2pass, 64);\n }\n\n for (i = 0; i < BCRYPT_BLOCKS; i++)\n cdata[i] = stream2word(ciphertext, ciphertext.byteLength);\n for (i = 0; i < 64; i++)\n state.enc(cdata, cdata.byteLength / 8);\n\n for (i = 0; i < BCRYPT_BLOCKS; i++) {\n out[4*i+3] = cdata[i] >>> 24;\n out[4*i+2] = cdata[i] >>> 16;\n out[4*i+1] = cdata[i] >>> 8;\n out[4*i+0] = cdata[i];\n }\n};\n\nfunction bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {\n var sha2pass = new Uint8Array(64),\n sha2salt = new Uint8Array(64),\n out = new Uint8Array(BCRYPT_HASHSIZE),\n tmpout = new Uint8Array(BCRYPT_HASHSIZE),\n countsalt = new Uint8Array(saltlen+4),\n i, j, amt, stride, dest, count,\n origkeylen = keylen;\n\n if (rounds < 1)\n return -1;\n if (passlen === 0 || saltlen === 0 || keylen === 0 ||\n keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))\n return -1;\n\n stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);\n amt = Math.floor((keylen + stride - 1) / stride);\n\n for (i = 0; i < saltlen; i++)\n countsalt[i] = salt[i];\n\n crypto_hash_sha512(sha2pass, pass, passlen);\n\n for (count = 1; keylen > 0; count++) {\n countsalt[saltlen+0] = count >>> 24;\n countsalt[saltlen+1] = count >>> 16;\n countsalt[saltlen+2] = count >>> 8;\n countsalt[saltlen+3] = count;\n\n crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (i = out.byteLength; i--;)\n out[i] = tmpout[i];\n\n for (i = 1; i < rounds; i++) {\n crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (j = 0; j < out.byteLength; j++)\n out[j] ^= tmpout[j];\n }\n\n amt = Math.min(amt, keylen);\n for (i = 0; i < amt; i++) {\n dest = i * stride + (count - 1);\n if (dest >= origkeylen)\n break;\n key[dest] = out[i];\n }\n keylen -= i;\n }\n\n return 0;\n};\n\nmodule.exports = {\n BLOCKS: BCRYPT_BLOCKS,\n HASHSIZE: BCRYPT_HASHSIZE,\n hash: bcrypt_hash,\n pbkdf: bcrypt_pbkdf\n};\n","var register = require('./lib/register')\nvar addHook = require('./lib/add')\nvar removeHook = require('./lib/remove')\n\n// bind with array of arguments: https://stackoverflow.com/a/21792913\nvar bind = Function.bind\nvar bindable = bind.bind(bind)\n\nfunction bindApi (hook, state, name) {\n var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state])\n hook.api = { remove: removeHookRef }\n hook.remove = removeHookRef\n\n ;['before', 'error', 'after', 'wrap'].forEach(function (kind) {\n var args = name ? [state, kind, name] : [state, kind]\n hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args)\n })\n}\n\nfunction HookSingular () {\n var singularHookName = 'h'\n var singularHookState = {\n registry: {}\n }\n var singularHook = register.bind(null, singularHookState, singularHookName)\n bindApi(singularHook, singularHookState, singularHookName)\n return singularHook\n}\n\nfunction HookCollection () {\n var state = {\n registry: {}\n }\n\n var hook = register.bind(null, state)\n bindApi(hook, state)\n\n return hook\n}\n\nvar collectionHookDeprecationMessageDisplayed = false\nfunction Hook () {\n if (!collectionHookDeprecationMessageDisplayed) {\n console.warn('[before-after-hook]: \"Hook()\" repurposing warning, use \"Hook.Collection()\". Read more: https://git.io/upgrade-before-after-hook-to-1.4')\n collectionHookDeprecationMessageDisplayed = true\n }\n return HookCollection()\n}\n\nHook.Singular = HookSingular.bind()\nHook.Collection = HookCollection.bind()\n\nmodule.exports = Hook\n// expose constructors as a named property for TypeScript\nmodule.exports.Hook = Hook\nmodule.exports.Singular = Hook.Singular\nmodule.exports.Collection = Hook.Collection\n","module.exports = addHook;\n\nfunction addHook(state, kind, name, hook) {\n var orig = hook;\n if (!state.registry[name]) {\n state.registry[name] = [];\n }\n\n if (kind === \"before\") {\n hook = function (method, options) {\n return Promise.resolve()\n .then(orig.bind(null, options))\n .then(method.bind(null, options));\n };\n }\n\n if (kind === \"after\") {\n hook = function (method, options) {\n var result;\n return Promise.resolve()\n .then(method.bind(null, options))\n .then(function (result_) {\n result = result_;\n return orig(result, options);\n })\n .then(function () {\n return result;\n });\n };\n }\n\n if (kind === \"error\") {\n hook = function (method, options) {\n return Promise.resolve()\n .then(method.bind(null, options))\n .catch(function (error) {\n return orig(error, options);\n });\n };\n }\n\n state.registry[name].push({\n hook: hook,\n orig: orig,\n });\n}\n","module.exports = register;\n\nfunction register(state, name, method, options) {\n if (typeof method !== \"function\") {\n throw new Error(\"method for before hook must be a function\");\n }\n\n if (!options) {\n options = {};\n }\n\n if (Array.isArray(name)) {\n return name.reverse().reduce(function (callback, name) {\n return register.bind(null, state, name, callback, options);\n }, method)();\n }\n\n return Promise.resolve().then(function () {\n if (!state.registry[name]) {\n return method(options);\n }\n\n return state.registry[name].reduce(function (method, registered) {\n return registered.hook.bind(null, method, options);\n }, method)();\n });\n}\n","module.exports = removeHook;\n\nfunction removeHook(state, name, method) {\n if (!state.registry[name]) {\n return;\n }\n\n var index = state.registry[name]\n .map(function (registered) {\n return registered.orig;\n })\n .indexOf(method);\n\n if (index === -1) {\n return;\n }\n\n state.registry[name].splice(index, 1);\n}\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst symbol = Symbol.for('BufferList')\n\nfunction BufferList (buf) {\n if (!(this instanceof BufferList)) {\n return new BufferList(buf)\n }\n\n BufferList._init.call(this, buf)\n}\n\nBufferList._init = function _init (buf) {\n Object.defineProperty(this, symbol, { value: true })\n\n this._bufs = []\n this.length = 0\n\n if (buf) {\n this.append(buf)\n }\n}\n\nBufferList.prototype._new = function _new (buf) {\n return new BufferList(buf)\n}\n\nBufferList.prototype._offset = function _offset (offset) {\n if (offset === 0) {\n return [0, 0]\n }\n\n let tot = 0\n\n for (let i = 0; i < this._bufs.length; i++) {\n const _t = tot + this._bufs[i].length\n if (offset < _t || i === this._bufs.length - 1) {\n return [i, offset - tot]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n const bufferId = blOffset[0]\n let offset = blOffset[1]\n\n for (let i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n\n return offset\n}\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n\n const offset = this._offset(index)\n\n return this._bufs[offset[0]][offset[1]]\n}\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start === 'number' && start < 0) {\n start += this.length\n }\n\n if (typeof end === 'number' && end < 0) {\n end += this.length\n }\n\n return this.copy(null, 0, start, end)\n}\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart !== 'number' || srcStart < 0) {\n srcStart = 0\n }\n\n if (typeof srcEnd !== 'number' || srcEnd > this.length) {\n srcEnd = this.length\n }\n\n if (srcStart >= this.length) {\n return dst || Buffer.alloc(0)\n }\n\n if (srcEnd <= 0) {\n return dst || Buffer.alloc(0)\n }\n\n const copy = !!dst\n const off = this._offset(srcStart)\n const len = srcEnd - srcStart\n let bytes = len\n let bufoff = (copy && dstStart) || 0\n let start = off[1]\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd === this.length) {\n if (!copy) {\n // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (let i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) {\n // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n }\n\n for (let i = off[0]; i < this._bufs.length; i++) {\n const l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start) {\n start = 0\n }\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0) {\n start += this.length\n }\n\n if (end < 0) {\n end += this.length\n }\n\n if (start === end) {\n return this._new()\n }\n\n const startOffset = this._offset(start)\n const endOffset = this._offset(end)\n const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] === 0) {\n buffers.pop()\n } else {\n buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])\n }\n\n if (startOffset[1] !== 0) {\n buffers[0] = buffers[0].slice(startOffset[1])\n }\n\n return this._new(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n\n return this\n}\n\nBufferList.prototype.duplicate = function duplicate () {\n const copy = this._new()\n\n for (let i = 0; i < this._bufs.length; i++) {\n copy.append(this._bufs[i])\n }\n\n return copy\n}\n\nBufferList.prototype.append = function append (buf) {\n if (buf == null) {\n return this\n }\n\n if (buf.buffer) {\n // append a view of the underlying ArrayBuffer\n this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))\n } else if (Array.isArray(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.append(buf[i])\n }\n } else if (this._isBufferList(buf)) {\n // unwrap argument into individual BufferLists\n for (let i = 0; i < buf._bufs.length; i++) {\n this.append(buf._bufs[i])\n }\n } else {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf === 'number') {\n buf = buf.toString()\n }\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (this._isBufferList(search)) {\n search = search.slice()\n } else if (Array.isArray(search.buffer)) {\n search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n const blOffset = this._offset(offset)\n let blIndex = blOffset[0] // index of which internal buffer we're working on\n let buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (; blIndex < this._bufs.length; blIndex++) {\n const buff = this._bufs[blIndex]\n\n while (buffOffset < buff.length) {\n const availableWindow = buff.length - buffOffset\n\n if (availableWindow >= search.length) {\n const nativeSearchResult = buff.indexOf(search, buffOffset)\n\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n const revOffset = this._reverseOffset([blIndex, buffOffset])\n\n if (this._match(revOffset, search)) {\n return revOffset\n }\n\n buffOffset++\n }\n }\n\n buffOffset = 0\n }\n\n return -1\n}\n\nBufferList.prototype._match = function (offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n\n for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {\n if (this.get(offset + searchOffset) !== search[searchOffset]) {\n return false\n }\n }\n return true\n}\n\n;(function () {\n const methods = {\n readDoubleBE: 8,\n readDoubleLE: 8,\n readFloatBE: 4,\n readFloatLE: 4,\n readInt32BE: 4,\n readInt32LE: 4,\n readUInt32BE: 4,\n readUInt32LE: 4,\n readInt16BE: 2,\n readInt16LE: 2,\n readUInt16BE: 2,\n readUInt16LE: 2,\n readInt8: 1,\n readUInt8: 1,\n readIntBE: null,\n readIntLE: null,\n readUIntBE: null,\n readUIntLE: null\n }\n\n for (const m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n } else {\n BufferList.prototype[m] = function (offset = 0) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n// Used internally by the class and also as an indicator of this object being\n// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser\n// environment because there could be multiple different copies of the\n// BufferList class and some `BufferList`s might be `BufferList`s.\nBufferList.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferList || BufferList.isBufferList(b)\n}\n\nBufferList.isBufferList = function isBufferList (b) {\n return b != null && b[symbol]\n}\n\nmodule.exports = BufferList\n","'use strict'\n\nconst DuplexStream = require('readable-stream').Duplex\nconst inherits = require('inherits')\nconst BufferList = require('./BufferList')\n\nfunction BufferListStream (callback) {\n if (!(this instanceof BufferListStream)) {\n return new BufferListStream(callback)\n }\n\n if (typeof callback === 'function') {\n this._callback = callback\n\n const piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n\n callback = null\n }\n\n BufferList._init.call(this, callback)\n DuplexStream.call(this)\n}\n\ninherits(BufferListStream, DuplexStream)\nObject.assign(BufferListStream.prototype, BufferList.prototype)\n\nBufferListStream.prototype._new = function _new (callback) {\n return new BufferListStream(callback)\n}\n\nBufferListStream.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback === 'function') {\n callback()\n }\n}\n\nBufferListStream.prototype._read = function _read (size) {\n if (!this.length) {\n return this.push(null)\n }\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\nBufferListStream.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\nBufferListStream.prototype._destroy = function _destroy (err, cb) {\n this._bufs.length = 0\n this.length = 0\n cb(err)\n}\n\nBufferListStream.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)\n}\n\nBufferListStream.isBufferList = BufferList.isBufferList\n\nmodule.exports = BufferListStream\nmodule.exports.BufferListStream = BufferListStream\nmodule.exports.BufferList = BufferList\n","'use strict'\nconst fs = require('fs')\nconst path = require('path')\n\n/* istanbul ignore next */\nconst LCHOWN = fs.lchown ? 'lchown' : 'chown'\n/* istanbul ignore next */\nconst LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync'\n\n/* istanbul ignore next */\nconst needEISDIRHandled = fs.lchown &&\n !process.version.match(/v1[1-9]+\\./) &&\n !process.version.match(/v10\\.[6-9]/)\n\nconst lchownSync = (path, uid, gid) => {\n try {\n return fs[LCHOWNSYNC](path, uid, gid)\n } catch (er) {\n if (er.code !== 'ENOENT')\n throw er\n }\n}\n\n/* istanbul ignore next */\nconst chownSync = (path, uid, gid) => {\n try {\n return fs.chownSync(path, uid, gid)\n } catch (er) {\n if (er.code !== 'ENOENT')\n throw er\n }\n}\n\n/* istanbul ignore next */\nconst handleEISDIR =\n needEISDIRHandled ? (path, uid, gid, cb) => er => {\n // Node prior to v10 had a very questionable implementation of\n // fs.lchown, which would always try to call fs.open on a directory\n // Fall back to fs.chown in those cases.\n if (!er || er.code !== 'EISDIR')\n cb(er)\n else\n fs.chown(path, uid, gid, cb)\n }\n : (_, __, ___, cb) => cb\n\n/* istanbul ignore next */\nconst handleEISDirSync =\n needEISDIRHandled ? (path, uid, gid) => {\n try {\n return lchownSync(path, uid, gid)\n } catch (er) {\n if (er.code !== 'EISDIR')\n throw er\n chownSync(path, uid, gid)\n }\n }\n : (path, uid, gid) => lchownSync(path, uid, gid)\n\n// fs.readdir could only accept an options object as of node v6\nconst nodeVersion = process.version\nlet readdir = (path, options, cb) => fs.readdir(path, options, cb)\nlet readdirSync = (path, options) => fs.readdirSync(path, options)\n/* istanbul ignore next */\nif (/^v4\\./.test(nodeVersion))\n readdir = (path, options, cb) => fs.readdir(path, cb)\n\nconst chown = (cpath, uid, gid, cb) => {\n fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => {\n // Skip ENOENT error\n cb(er && er.code !== 'ENOENT' ? er : null)\n }))\n}\n\nconst chownrKid = (p, child, uid, gid, cb) => {\n if (typeof child === 'string')\n return fs.lstat(path.resolve(p, child), (er, stats) => {\n // Skip ENOENT error\n if (er)\n return cb(er.code !== 'ENOENT' ? er : null)\n stats.name = child\n chownrKid(p, stats, uid, gid, cb)\n })\n\n if (child.isDirectory()) {\n chownr(path.resolve(p, child.name), uid, gid, er => {\n if (er)\n return cb(er)\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n })\n } else {\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n }\n}\n\n\nconst chownr = (p, uid, gid, cb) => {\n readdir(p, { withFileTypes: true }, (er, children) => {\n // any error other than ENOTDIR or ENOTSUP means it's not readable,\n // or doesn't exist. give up.\n if (er) {\n if (er.code === 'ENOENT')\n return cb()\n else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')\n return cb(er)\n }\n if (er || !children.length)\n return chown(p, uid, gid, cb)\n\n let len = children.length\n let errState = null\n const then = er => {\n if (errState)\n return\n if (er)\n return cb(errState = er)\n if (-- len === 0)\n return chown(p, uid, gid, cb)\n }\n\n children.forEach(child => chownrKid(p, child, uid, gid, then))\n })\n}\n\nconst chownrKidSync = (p, child, uid, gid) => {\n if (typeof child === 'string') {\n try {\n const stats = fs.lstatSync(path.resolve(p, child))\n stats.name = child\n child = stats\n } catch (er) {\n if (er.code === 'ENOENT')\n return\n else\n throw er\n }\n }\n\n if (child.isDirectory())\n chownrSync(path.resolve(p, child.name), uid, gid)\n\n handleEISDirSync(path.resolve(p, child.name), uid, gid)\n}\n\nconst chownrSync = (p, uid, gid) => {\n let children\n try {\n children = readdirSync(p, { withFileTypes: true })\n } catch (er) {\n if (er.code === 'ENOENT')\n return\n else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP')\n return handleEISDirSync(p, uid, gid)\n else\n throw er\n }\n\n if (children && children.length)\n children.forEach(child => chownrKidSync(p, child, uid, gid))\n\n return handleEISDirSync(p, uid, gid)\n}\n\nmodule.exports = chownr\nchownr.sync = chownrSync\n","const binding = require('../build/Release/cpufeatures.node');\n\nmodule.exports = binding.getCPUInfo;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nclass Deprecation extends Error {\n constructor(message) {\n super(message); // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = 'Deprecation';\n }\n\n}\n\nexports.Deprecation = Deprecation;\n","//Based on follow-redirects v0.0.x\n\nvar nativeHttps = require('https'),\n nativeHttp = require('http'),\n url = require('url'),\n utils = require('./utils');\n\nvar maxRedirects = module.exports.maxRedirects = 5;\n\nvar protocols = {\n https: nativeHttps,\n http: nativeHttp\n};\n\nfor (var protocol in protocols) {\n var h = function() {};\n h.prototype = protocols[protocol];\n h = new h();\n\n h.request = function(h) {\n return function(options, callback, redirectOptions) {\n\n redirectOptions = redirectOptions || {};\n\n var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects;\n\n var redirect = utils.extend({\n count: 0,\n max: max,\n clientRequest: null,\n userCallback: callback\n }, redirectOptions);\n\n if (redirect.count > redirect.max) {\n var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.');\n redirect.clientRequest.emit('error', err);\n return redirect.clientRequest;\n }\n\n redirect.count++;\n\n var reqUrl;\n if (typeof options === 'string') {\n reqUrl = options;\n } else {\n reqUrl = url.format(utils.extend({\n protocol: protocol\n }, options));\n }\n\n var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect));\n\n if (!redirect.clientRequest) redirect.clientRequest = clientRequest;\n\n function redirectCallback(reqUrl, redirect) {\n return function(res) {\n if (res.statusCode < 300 || res.statusCode > 399) {\n return redirect.userCallback(res);\n }\n\n if (!('location' in res.headers)) {\n return redirect.userCallback(res);\n }\n\n var redirectUrl = url.resolve(reqUrl, res.headers.location);\n\n var proto = url.parse(redirectUrl).protocol;\n proto = proto.substr(0, proto.length - 1);\n return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect);\n };\n }\n\n return clientRequest;\n };\n }(h);\n\n // see https://github.com/joyent/node/blob/master/lib/http.js#L1623\n h.get = function(h) {\n return function(options, cb, redirectOptions) {\n var req = h.request(options, cb, redirectOptions);\n req.end();\n return req;\n };\n }(h);\n\n module.exports[protocol] = h;\n}\n","module.exports = HttpDuplex;\n\nvar util = require('util'),\n stream = require('readable-stream');\n\nutil.inherits(HttpDuplex, stream.Duplex);\n\nfunction HttpDuplex(req, res, options) {\n var self = this;\n\n if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options);\n\n stream.Duplex.call(self, options);\n self._output = null;\n\n self.connect(req, res);\n}\n\nHttpDuplex.prototype.connect = function(req, res) {\n var self = this;\n self.req = req;\n self._output = res;\n self.emit('response', res);\n\n res.on('data', function(c) {\n if (!self.push(c)) self._output.pause();\n });\n res.on('end', function() {\n self.push(null);\n });\n};\n\nHttpDuplex.prototype._read = function(n) {\n if (this._output) this._output.resume();\n};\n\nHttpDuplex.prototype._write = function(chunk, encoding, cb) {\n this.req.write(chunk, encoding);\n cb();\n};\n\nHttpDuplex.prototype.end = function(chunk, encoding, cb) {\n this._output.socket.destroy();\n return this.req.end(chunk, encoding, cb);\n};\n\nHttpDuplex.prototype.destroy = function() {\n this.req.destroy();\n this._output.socket.destroy();\n};\n","var querystring = require('querystring'),\n http = require('./http'),\n fs = require('fs'),\n path = require('path'),\n url = require('url'),\n ssh = require('./ssh'),\n HttpDuplex = require('./http_duplex'),\n debug = require('debug')('modem'),\n utils = require('./utils'),\n util = require('util'),\n url = require('url'),\n splitca = require('split-ca'),\n isWin = require('os').type() === 'Windows_NT';\n\nvar defaultOpts = function () {\n var host;\n var opts = {};\n\n if (!process.env.DOCKER_HOST) {\n // Windows socket path: //./pipe/docker_engine ( Windows 10 )\n // Linux & Darwin socket path: /var/run/docker.sock\n opts.socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock';\n } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) {\n // Strip off unix://, fall back to default of /var/run/docker.sock if\n // unix:// was passed without a path\n opts.socketPath = process.env.DOCKER_HOST.substring(7) || '/var/run/docker.sock';\n } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) {\n // Strip off npipe://, fall back to default of //./pipe/docker_engine if\n // npipe:// was passed without a path\n opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine';\n } else {\n var hostStr = process.env.DOCKER_HOST;\n if (hostStr.indexOf('\\/\\/') < 0) {\n hostStr = 'tcp://' + hostStr;\n }\n try {\n host = new url.URL(hostStr);\n } catch (err) {\n throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234');\n }\n\n opts.port = host.port;\n\n if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') {\n opts.protocol = 'https';\n } else if (host.protocol === 'ssh:') {\n opts.protocol = 'ssh';\n opts.username = host.username;\n opts.sshOptions = {\n agent: process.env.SSH_AUTH_SOCK,\n }\n } else {\n opts.protocol = 'http';\n }\n\n opts.host = host.hostname;\n\n if (process.env.DOCKER_CERT_PATH) {\n opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem'));\n opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem'));\n opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem'));\n }\n\n if (process.env.DOCKER_CLIENT_TIMEOUT) {\n opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10);\n }\n }\n\n return opts;\n};\n\n\nvar Modem = function (options) {\n var optDefaults = defaultOpts();\n var opts = Object.assign({}, optDefaults, options);\n\n this.host = opts.host;\n\n if(!this.host) {\n this.socketPath = opts.socketPath;\n }\n\n this.port = opts.port;\n this.username = opts.username;\n this.password = opts.password;\n this.version = opts.version;\n this.key = opts.key;\n this.cert = opts.cert;\n this.ca = opts.ca;\n this.timeout = opts.timeout;\n this.connectionTimeout = opts.connectionTimeout;\n this.checkServerIdentity = opts.checkServerIdentity;\n this.agent = opts.agent;\n this.headers = opts.headers || {};\n this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions);\n //retrocompabitlity\n if(this.sshOptions.agentForward === undefined) {\n this.sshOptions.agentForward = opts.agentForward;\n }\n\n if (this.key && this.cert && this.ca) {\n this.protocol = 'https';\n }\n this.protocol = opts.protocol || this.protocol || 'http';\n};\n\nModem.prototype.dial = function (options, callback) {\n var opts, address, data;\n var self = this;\n\n if (options.options) {\n opts = options.options;\n }\n\n // Prevent credentials from showing up in URL\n if (opts && opts.authconfig) {\n delete opts.authconfig;\n }\n\n // Prevent abortsignal from showing up in the URL\n if (opts && opts.abortSignal) {\n delete opts.abortSignal;\n }\n\n if (this.version) {\n options.path = '/' + this.version + options.path;\n }\n\n if (this.host) {\n var parsed = url.parse(self.host);\n address = url.format({\n 'protocol': parsed.protocol || self.protocol,\n 'hostname': parsed.hostname || self.host,\n 'port': self.port\n });\n address = url.resolve(address, options.path);\n } else {\n address = options.path;\n }\n\n if (options.path.indexOf('?') !== -1) {\n if (opts && Object.keys(opts).length > 0) {\n address += this.buildQuerystring(opts._query || opts);\n } else {\n address = address.substring(0, address.length - 1);\n }\n }\n\n var optionsf = {\n path: address,\n method: options.method,\n headers: options.headers || Object.assign({}, self.headers),\n key: self.key,\n cert: self.cert,\n ca: self.ca\n };\n\n if (this.checkServerIdentity) {\n optionsf.checkServerIdentity = this.checkServerIdentity;\n }\n\n if (this.agent) {\n optionsf.agent = this.agent;\n }\n\n if (options.authconfig) {\n optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 ||\n Buffer.from(JSON.stringify(options.authconfig)).toString('base64');\n }\n\n if (options.registryconfig) {\n optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 ||\n Buffer.from(JSON.stringify(options.registryconfig)).toString('base64');\n }\n\n if (options.abortSignal) {\n optionsf.signal = options.abortSignal;\n }\n\n if (options.file) {\n if (typeof options.file === 'string') {\n data = fs.createReadStream(path.resolve(options.file));\n } else {\n data = options.file;\n }\n optionsf.headers['Content-Type'] = 'application/tar';\n } else if (opts && options.method === 'POST') {\n data = JSON.stringify(opts._body || opts);\n if (options.allowEmpty) {\n optionsf.headers['Content-Type'] = 'application/json';\n } else {\n if (data !== '{}' && data !== '\"\"') {\n optionsf.headers['Content-Type'] = 'application/json';\n } else {\n data = undefined;\n }\n }\n }\n\n if (typeof data === 'string') {\n optionsf.headers['Content-Length'] = Buffer.byteLength(data);\n } else if (Buffer.isBuffer(data) === true) {\n optionsf.headers['Content-Length'] = data.length;\n } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) {\n optionsf.headers['Transfer-Encoding'] = 'chunked';\n }\n\n if (options.hijack) {\n optionsf.headers.Connection = 'Upgrade';\n optionsf.headers.Upgrade = 'tcp';\n }\n\n if (this.socketPath) {\n optionsf.socketPath = this.socketPath;\n } else {\n var urlp = url.parse(address);\n optionsf.hostname = urlp.hostname;\n optionsf.port = urlp.port;\n optionsf.path = urlp.path;\n }\n\n this.buildRequest(optionsf, options, data, callback);\n};\n\nModem.prototype.buildRequest = function (options, context, data, callback) {\n var self = this;\n var connectionTimeoutTimer;\n\n var opts = self.protocol === 'ssh' ? Object.assign(options, {\n agent: ssh(Object.assign({}, self.sshOptions, {\n 'host': self.host,\n 'port': self.port,\n 'username': self.username,\n 'password': self.password,\n })),\n protocol: 'http:',\n }) : options;\n\n var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { });\n\n debug('Sending: %s', util.inspect(options, {\n showHidden: true,\n depth: null\n }));\n\n if (self.connectionTimeout) {\n connectionTimeoutTimer = setTimeout(function () {\n debug('Connection Timeout of %s ms exceeded', self.connectionTimeout);\n req.abort();\n }, self.connectionTimeout);\n }\n\n if (self.timeout) {\n req.on('socket', function (socket) {\n socket.setTimeout(self.timeout);\n socket.on('timeout', function () {\n debug('Timeout of %s ms exceeded', self.timeout);\n req.abort();\n });\n });\n }\n\n if (context.hijack === true) {\n clearTimeout(connectionTimeoutTimer);\n req.on('upgrade', function (res, sock, head) {\n return callback(null, sock);\n });\n }\n\n req.on('connect', function () {\n clearTimeout(connectionTimeoutTimer);\n });\n\n req.on('disconnect', function () {\n clearTimeout(connectionTimeoutTimer);\n });\n\n req.on('response', function (res) {\n clearTimeout(connectionTimeoutTimer);\n if (context.isStream === true) {\n self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback);\n } else {\n var chunks = [];\n res.on('data', function (chunk) {\n chunks.push(chunk);\n });\n\n res.on('end', function () {\n var buffer = Buffer.concat(chunks);\n var result = buffer.toString();\n\n debug('Received: %s', result);\n\n var json = utils.parseJSON(result) || buffer;\n self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback);\n });\n }\n });\n\n req.on('error', function (error) {\n clearTimeout(connectionTimeoutTimer);\n self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback);\n });\n\n if (typeof data === 'string' || Buffer.isBuffer(data)) {\n req.write(data);\n } else if (data) {\n data.on('error', function (error) {\n req.destroy(error);\n });\n data.pipe(req);\n }\n\n if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) {\n req.end();\n }\n};\n\nModem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) {\n if (err) return cb(err, null);\n\n if (statusCodes[res.statusCode] !== true) {\n getCause(isStream, res, json, function (err, cause) {\n var msg = new Error(\n '(HTTP code ' + res.statusCode + ') ' +\n (statusCodes[res.statusCode] || 'unexpected') + ' - ' +\n (cause.message || cause) + ' '\n );\n msg.reason = statusCodes[res.statusCode];\n msg.statusCode = res.statusCode;\n msg.json = json;\n cb(msg, null);\n });\n } else {\n if (openStdin) {\n cb(null, new HttpDuplex(req, res));\n } else if (isStream) {\n cb(null, res);\n } else {\n cb(null, json);\n }\n }\n\n function getCause(isStream, res, json, callback) {\n var chunks = '';\n if (isStream) {\n res.on('data', function (chunk) {\n chunks += chunk;\n });\n res.on('end', function () {\n callback(null, utils.parseJSON(chunks) || chunks);\n });\n } else {\n callback(null, json);\n }\n }\n};\n\nModem.prototype.demuxStream = function (stream, stdout, stderr) {\n var nextDataType = null;\n var nextDataLength = null;\n var buffer = Buffer.from('');\n function processData(data) {\n if (data) {\n buffer = Buffer.concat([buffer, data]);\n }\n if (!nextDataType) {\n if (buffer.length >= 8) {\n var header = bufferSlice(8);\n nextDataType = header.readUInt8(0);\n nextDataLength = header.readUInt32BE(4);\n // It's possible we got a \"data\" that contains multiple messages\n // Process the next one\n processData();\n }\n } else {\n if (buffer.length >= nextDataLength) {\n var content = bufferSlice(nextDataLength);\n if (nextDataType === 1) {\n stdout.write(content);\n } else {\n stderr.write(content);\n }\n nextDataType = null;\n // It's possible we got a \"data\" that contains multiple messages\n // Process the next one\n processData();\n }\n }\n }\n\n function bufferSlice(end) {\n var out = buffer.slice(0, end);\n buffer = Buffer.from(buffer.slice(end, buffer.length));\n return out;\n }\n\n stream.on('data', processData);\n};\n\nModem.prototype.followProgress = function (stream, onFinished, onProgress) {\n var buf = '';\n var output = [];\n var finished = false;\n\n stream.on('data', onStreamEvent);\n stream.on('error', onStreamError);\n stream.on('end', onStreamEnd);\n stream.on('close', onStreamEnd);\n\n function onStreamEvent(data) {\n buf += data.toString();\n pump();\n\n function pump() {\n var pos;\n while ((pos = buf.indexOf('\\n')) >= 0) {\n if (pos == 0) {\n buf = buf.slice(1);\n continue;\n }\n processLine(buf.slice(0, pos));\n buf = buf.slice(pos + 1);\n }\n }\n\n function processLine(line) {\n if (line[line.length - 1] == '\\r') line = line.substr(0, line.length - 1);\n if (line.length > 0) {\n var obj = JSON.parse(line);\n output.push(obj);\n if (onProgress) {\n onProgress(obj);\n }\n }\n }\n };\n\n function onStreamError(err) {\n finished = true;\n stream.removeListener('data', onStreamEvent);\n stream.removeListener('error', onStreamError);\n stream.removeListener('end', onStreamEnd);\n stream.removeListener('close', onStreamEnd);\n onFinished(err, output);\n }\n\n function onStreamEnd() {\n if(!finished) onFinished(null, output);\n finished = true;\n }\n};\n\nModem.prototype.buildQuerystring = function (opts) {\n var clone = {};\n\n // serialize map values as JSON strings, else querystring truncates.\n Object.keys(opts).map(function (key, i) {\n if (opts[key]\n && typeof opts[key] === 'object'\n && !Array.isArray(opts[key])\n // Ref: https://docs.docker.com/engine/api/v1.40/#operation/ImageBuild\n // > cachefrom (string) JSON array of images used for build cache resolution.\n || key === 'cachefrom'\n ) {\n clone[key] = JSON.stringify(opts[key]);\n } else {\n clone[key] = opts[key];\n }\n });\n\n return querystring.stringify(clone);\n};\n\nmodule.exports = Modem;\n","var Client = require('ssh2').Client,\n http = require('http');\n\nmodule.exports = function(opt) {\n var conn = new Client();\n var agent = new http.Agent();\n\n agent.createConnection = function(options, fn) {\n conn.once('ready', function() {\n conn.exec('docker system dial-stdio', function(err, stream) {\n if (err) {\n conn.end();\n agent.destroy();\n return;\n }\n\n fn(null, stream);\n\n stream.once('close', () => {\n conn.end();\n agent.destroy();\n });\n });\n }).connect(opt);\n\n conn.once('end', () => agent.destroy());\n };\n\n return agent;\n};\n","// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js\n\nvar arr = [];\nvar each = arr.forEach;\nvar slice = arr.slice;\n\nmodule.exports.extend = function(obj) {\n each.call(slice.call(arguments, 1), function(source) {\n if (source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\nmodule.exports.parseJSON = function(s) {\n try {\n return JSON.parse(s);\n } catch (e) {\n return null;\n }\n};\n","var util = require('./util');\n\n/**\n * Represents a config\n * @param {Object} modem docker-modem\n * @param {String} id Config's id\n */\nvar Config = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nConfig.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nConfig.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update a config.\n *\n * @param {object} opts\n * @param {function} callback\n */\nConfig.prototype.update = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id + '/update?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Removes the config\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nConfig.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id,\n method: 'DELETE',\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Config;\n","var extend = require('./util').extend,\n Exec = require('./exec'),\n util = require('./util');\n\n/**\n * Represents a Container\n * @param {Object} modem docker-modem\n * @param {String} id Container's ID\n */\nvar Container = function(modem, id) {\n this.modem = modem;\n this.id = id;\n\n this.defaultOptions = {\n top: {},\n start: {},\n commit: {},\n stop: {},\n pause: {},\n unpause: {},\n restart: {},\n resize: {},\n attach: {},\n remove: {},\n copy: {},\n kill: {},\n exec: {},\n rename: {},\n log: {},\n stats: {},\n getArchive: {},\n infoArchive: {},\n putArchive: {},\n update: {},\n wait: {}\n };\n};\n\nContainer.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if supplied will query Docker.\n * @return {Object} ID only and only if callback isn't supplied.\n */\nContainer.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Rename\n * @param {Object} opts Rename options\n * @param {Function} callback Callback\n */\nContainer.prototype.rename = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.rename);\n\n var optsf = {\n path: '/containers/' + this.id + '/rename?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update\n * @param {Object} opts Update options\n * @param {Function} callback Callback\n */\nContainer.prototype.update = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.update);\n\n var optsf = {\n path: '/containers/' + this.id + '/update',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Top\n * @param {Object} opts like 'ps_args' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.top = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.top);\n\n var optsf = {\n path: '/containers/' + this.id + '/top?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Containers changes\n * @param {Object} Options\n * @param {Function} callback Callback\n */\nContainer.prototype.changes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/changes',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Checkpoints list\n * @param {Object} opts List checkpoints options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.listCheckpoint = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Delete checkpoint\n * @param {Object} opts Delete checkpoint options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.deleteCheckpoint = function(checkpoint, opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Create checkpoint\n * @param {Object} opts Create checkpoint options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.createCheckpoint = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n allowEmpty: true,\n statusCodes: {\n 200: true, //unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Export\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback with the octet-stream.\n */\nContainer.prototype.export = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/export',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Start\n * @param {Object} opts Container start options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.start = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.start);\n\n var optsf = {\n path: '/containers/' + this.id + '/start?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 304: 'container already started',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Pause\n * @param {Object} opts Pause options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.pause = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.pause);\n\n var optsf = {\n path: '/containers/' + this.id + '/pause',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Unpause\n * @param {Object} opts Unpause options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.unpause = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.unpause);\n\n var optsf = {\n path: '/containers/' + this.id + '/unpause',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Setup an exec call to a running container\n *\n * @param {object} opts\n * @param {function} callback\n */\nContainer.prototype.exec = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.exec);\n\n var optsf = {\n path: '/containers/' + this.id + '/exec',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 409: 'container stopped/paused',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(new Exec(self.modem, data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, new Exec(self.modem, data.Id));\n });\n }\n};\n\n/**\n * Commit\n * @param {Object} opts Commit options like 'Hostname' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.commit = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.commit);\n\n args.opts.container = this.id;\n\n var optsf = {\n path: '/commit?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Stop\n * @param {Object} opts Container stop options, like 't' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.stop = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.stop);\n\n var optsf = {\n path: '/containers/' + this.id + '/stop?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 304: 'container already stopped',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Restart\n * @param {Object} opts Container restart options, like 't' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.restart = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.restart);\n\n var optsf = {\n path: '/containers/' + this.id + '/restart?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Kill\n * @param {Object} opts Container kill options, like 'signal' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.kill = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.kill);\n\n var optsf = {\n path: '/containers/' + this.id + '/kill?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container resize\n * @param {[type]} opts Resize options. (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.resize = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.resize);\n\n var optsf = {\n path: '/containers/' + this.id + '/resize?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Attach\n * @param {Object} opts Attach options, like 'logs' (optional)\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.attach = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.attach);\n\n var optsf = {\n path: '/containers/' + this.id + '/attach?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n hijack: args.opts.hijack,\n openStdin: args.opts.stdin,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, stream) {\n if (err) {\n return reject(err);\n }\n resolve(stream);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, stream) {\n args.callback(err, stream);\n });\n }\n};\n\n/**\n * Waits for a container to end.\n * @param {[type]} opts Container wait options, like condition. (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.wait = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.wait);\n\n var optsf = {\n path: '/containers/' + this.id + '/wait?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes a container\n * @param {Object} opts Remove options, like 'force' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.remove);\n\n var optsf = {\n path: '/containers/' + this.id + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Copy (WARNING: DEPRECATED since RAPI v1.20)\n * @param {Object} opts Copy options, like 'Resource' (optional)\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.copy = function(opts, callback) {\n var self = this;\n console.log('container.copy is deprecated since Docker v1.8.x');\n var args = util.processArgs(opts, callback, this.defaultOptions.copy);\n\n var optsf = {\n path: '/containers/' + this.id + '/copy',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * getArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.getArchive = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.getArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * infoArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.infoArchive = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'HEAD',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * putArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.putArchive = function(file, opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.putArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'PUT',\n file: file,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 403: 'client error, permission denied',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nContainer.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.log);\n\n var optsf = {\n path: '/containers/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container stats\n * @param {Object} opts Stats options. (optional)\n * @param {Function} callback Callback with data\n */\nContainer.prototype.stats = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.stats);\n var isStream = true;\n if (args.opts.stream === false) {\n isStream = false;\n }\n var optsf = {\n path: '/containers/' + this.id + '/stats?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: isStream,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Container;\n","var EventEmitter = require('events').EventEmitter,\n Modem = require('docker-modem'),\n tar = require('tar-fs'),\n zlib = require('zlib'),\n Container = require('./container'),\n Image = require('./image'),\n Volume = require('./volume'),\n Network = require('./network'),\n Service = require('./service'),\n Plugin = require('./plugin'),\n Secret = require('./secret'),\n Config = require('./config'),\n Task = require('./task'),\n Node = require('./node'),\n Exec = require('./exec'),\n util = require('./util'),\n extend = util.extend;\n\nvar Docker = function(opts) {\n if (!(this instanceof Docker)) return new Docker(opts);\n\n var plibrary = global.Promise;\n\n if (opts && opts.Promise) {\n plibrary = opts.Promise;\n\n if (Object.keys(opts).length === 1) {\n opts = undefined;\n }\n }\n\n this.modem = new Modem(opts);\n this.modem.Promise = plibrary;\n};\n\n/**\n * Creates a new container\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createContainer = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/containers/create?',\n method: 'POST',\n options: opts,\n authconfig: opts.authconfig,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 406: 'impossible to attach',\n 500: 'server error'\n }\n };\n\n delete opts.authconfig;\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getContainer(data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n callback(err, self.getContainer(data.Id));\n });\n }\n};\n\n/**\n * Creates a new image\n * @param {Object} auth Authentication (optional)\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createImage = function(auth, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (!callback && !opts) {\n opts = auth;\n auth = opts.authconfig;\n }\n\n var optsf = {\n path: '/images/create?',\n method: 'POST',\n options: opts,\n authconfig: auth,\n abortSignal: opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Load image\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.loadImage = function(file, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n\n var optsf = {\n path: '/images/load?',\n method: 'POST',\n options: opts,\n file: file,\n abortSignal: opts && opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Import image from a tar archive\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.importImage = function(file, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = undefined;\n }\n\n if (!opts)\n opts = {};\n\n opts.fromSrc = '-';\n\n var optsf = {\n path: '/images/create?',\n method: 'POST',\n options: opts,\n file: file,\n abortSignal: opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Verifies auth\n * @param {Object} opts Options\n * @param {Function} callback Callback\n */\nDocker.prototype.checkAuth = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/auth',\n method: 'POST',\n options: opts,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Builds an image\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.buildImage = function(file, opts, callback) {\n var self = this;\n\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n\n function build(file) {\n var optsf = {\n path: '/build?',\n method: 'POST',\n file: file,\n options: opts,\n abortSignal: opts && opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (opts) {\n if (opts.registryconfig) {\n optsf.registryconfig = optsf.options.registryconfig;\n delete optsf.options.registryconfig;\n }\n\n //undocumented?\n if (opts.authconfig) {\n optsf.authconfig = optsf.options.authconfig;\n delete optsf.options.authconfig;\n }\n }\n\n if (callback === undefined) {\n return new self.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n self.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n }\n\n if (file && file.context) {\n var pack = tar.pack(file.context, {\n entries: file.src\n });\n return build(pack.pipe(zlib.createGzip()));\n } else {\n return build(file);\n }\n};\n\n/**\n * Fetches a Container by ID\n * @param {String} id Container's ID\n */\nDocker.prototype.getContainer = function(id) {\n return new Container(this.modem, id);\n};\n\n/**\n * Fetches an Image by name\n * @param {String} name Image's name\n */\nDocker.prototype.getImage = function(name) {\n return new Image(this.modem, name);\n};\n\n/**\n * Fetches a Volume by name\n * @param {String} name Volume's name\n */\nDocker.prototype.getVolume = function(name) {\n return new Volume(this.modem, name);\n};\n\n/**\n * Fetches a Plugin by name\n * @param {String} name Volume's name\n */\nDocker.prototype.getPlugin = function(name, remote) {\n return new Plugin(this.modem, name, remote);\n};\n\n/**\n * Fetches a Service by id\n * @param {String} id Services's id\n */\nDocker.prototype.getService = function(id) {\n return new Service(this.modem, id);\n};\n\n/**\n * Fetches a Task by id\n * @param {String} id Task's id\n */\nDocker.prototype.getTask = function(id) {\n return new Task(this.modem, id);\n};\n\n/**\n * Fetches Node by id\n * @param {String} id Node's id\n */\nDocker.prototype.getNode = function(id) {\n return new Node(this.modem, id);\n};\n\n/**\n * Fetches a Network by id\n * @param {String} id network's id\n */\nDocker.prototype.getNetwork = function(id) {\n return new Network(this.modem, id);\n};\n\n/**\n * Fetches a Secret by id\n * @param {String} id network's id\n */\nDocker.prototype.getSecret = function(id) {\n return new Secret(this.modem, id);\n};\n\n/**\n * Fetches a Config by id\n * @param {String} id network's id\n */\nDocker.prototype.getConfig = function(id) {\n return new Config(this.modem, id);\n};\n\n/**\n * Fetches an Exec instance by ID\n * @param {String} id Exec instance's ID\n */\nDocker.prototype.getExec = function(id) {\n return new Exec(this.modem, id);\n};\n\n/**\n * Lists containers\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listContainers = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Get images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.getImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/get?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Services\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listServices = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Nodes\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listNodes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such node',\n 500: 'server error',\n 503: 'node is not part of a swarm',\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Tasks\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listTasks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/tasks?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new secret\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createSecret = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n var optsf = {\n path: '/secrets/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 406: 'server error or node is not part of a swarm',\n 409: 'name conflicts with an existing object',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getSecret(data.ID));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getSecret(data.ID));\n });\n }\n};\n\n\n/**\n * Creates a new config\n * @param {Object} opts Config options\n * @param {Function} callback Callback\n */\nDocker.prototype.createConfig = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n var optsf = {\n path: '/configs/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 406: 'server error or node is not part of a swarm',\n 409: 'name conflicts with an existing object',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getConfig(data.ID));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getConfig(data.ID));\n });\n }\n};\n\n\n/**\n * Lists secrets\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listSecrets = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists configs\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listConfigs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new plugin\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createPlugin = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/plugins/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getPlugin(args.opts.name));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getPlugin(args.opts.name));\n });\n }\n};\n\n\n/**\n * Lists plugins\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listPlugins = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune builder\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneBuilder = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/build/prune',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune containers\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneContainers = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune volumes\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneVolumes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune networks\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneNetworks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Creates a new volume\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createVolume = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/volumes/create?',\n method: 'POST',\n allowEmpty: true,\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getVolume(data.Name));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getVolume(data.Name));\n });\n }\n};\n\n/**\n * Creates a new service\n * @param {Object} auth\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createService = function(auth, opts, callback) {\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (!opts && !callback) {\n opts = auth;\n }\n\n\n var self = this;\n var optsf = {\n path: '/services/create',\n method: 'POST',\n options: opts,\n authconfig: auth,\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 500: 'server error'\n }\n };\n\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getService(data.ID || data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n callback(err, self.getService(data.ID || data.Id));\n });\n }\n};\n\n/**\n * Lists volumes\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listVolumes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new network\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createNetwork = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/networks/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'driver not found',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getNetwork(data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getNetwork(data.Id));\n });\n }\n};\n\n/**\n * Lists networks\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listNetworks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Search images\n * @param {Object} opts Options\n * @param {Function} callback Callback\n */\nDocker.prototype.searchImages = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/images/search?',\n method: 'GET',\n options: opts,\n authconfig: opts.authconfig,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Info\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback with info\n */\nDocker.prototype.info = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/info',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Version\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.version = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/version',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Ping\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.ping = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/_ping',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * SystemDf \tequivalent to system/df API Engine\n *\t\tget usage data information\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.df = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/system/df',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Events\n * @param {Object} opts Events options, like 'since' (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.getEvents = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/events?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Pull is a wrapper around createImage, parsing image's tags.\n * @param {String} repoTag Repository tag\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n * @param {Object} auth Authentication (optional)\n * @return {Object} Image\n */\nDocker.prototype.pull = function(repoTag, opts, callback, auth) {\n var args = util.processArgs(opts, callback);\n\n var imageSrc = util.parseRepositoryTag(repoTag);\n args.opts.fromImage = imageSrc.repository;\n args.opts.tag = imageSrc.tag || 'latest';\n\n var argsf = [args.opts, args.callback];\n if (auth) {\n argsf = [auth, args.opts, args.callback];\n }\n return this.createImage.apply(this, argsf);\n};\n\n/**\n * Like run command from Docker's CLI\n * @param {String} image Image name to be used.\n * @param {Array} cmd Command to run in array format.\n * @param {Object} streamo Output stream\n * @param {Object} createOptions Container create options (optional)\n * @param {Object} startOptions Container start options (optional)\n * @param {Function} callback Callback\n * @return {Object} EventEmitter\n */\nDocker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) {\n if (typeof arguments[arguments.length - 1] === 'function') {\n return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback);\n } else {\n return this.runPromise(image, cmd, streamo, createOptions, startOptions);\n }\n};\n\n\nDocker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) {\n if (!callback && typeof createOptions === 'function') {\n callback = createOptions;\n createOptions = {};\n startOptions = {};\n } else if (!callback && typeof startOptions === 'function') {\n callback = startOptions;\n startOptions = {};\n }\n\n var hub = new EventEmitter();\n\n function handler(err, container) {\n if (err) return callback(err, null, container);\n\n hub.emit('container', container);\n\n container.attach({\n stream: true,\n stdout: true,\n stderr: true\n }, function handler(err, stream) {\n if (err) return callback(err, null, container);\n\n hub.emit('stream', stream);\n\n if (streamo) {\n if (streamo instanceof Array) {\n stream.on('end', function() {\n try {\n streamo[0].end();\n } catch (e) {}\n try {\n streamo[1].end();\n } catch (e) {}\n });\n container.modem.demuxStream(stream, streamo[0], streamo[1]);\n } else {\n stream.setEncoding('utf8');\n stream.pipe(streamo, {\n end: true\n });\n }\n }\n\n container.start(startOptions, function(err, data) {\n if (err) return callback(err, data, container);\n hub.emit('start', container);\n\n container.wait(function(err, data) {\n hub.emit('data', data);\n callback(err, data, container);\n });\n });\n });\n }\n\n var optsc = {\n 'Hostname': '',\n 'User': '',\n 'AttachStdin': false,\n 'AttachStdout': true,\n 'AttachStderr': true,\n 'Tty': true,\n 'OpenStdin': false,\n 'StdinOnce': false,\n 'Env': null,\n 'Cmd': cmd,\n 'Image': image,\n 'Volumes': {},\n 'VolumesFrom': []\n };\n\n extend(optsc, createOptions);\n\n this.createContainer(optsc, handler);\n\n return hub;\n};\n\nDocker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) {\n var self = this;\n\n createOptions = createOptions || {};\n startOptions = startOptions || {};\n\n var optsc = {\n 'Hostname': '',\n 'User': '',\n 'AttachStdin': false,\n 'AttachStdout': true,\n 'AttachStderr': true,\n 'Tty': true,\n 'OpenStdin': false,\n 'StdinOnce': false,\n 'Env': null,\n 'Cmd': cmd,\n 'Image': image,\n 'Volumes': {},\n 'VolumesFrom': []\n };\n\n extend(optsc, createOptions);\n\n var containero;\n\n return new this.modem.Promise(function(resolve, reject) {\n self.createContainer(optsc).then(function(container) {\n containero = container;\n return container.attach({\n stream: true,\n stdout: true,\n stderr: true\n });\n }).then(function(stream) {\n if (streamo) {\n if (streamo instanceof Array) {\n stream.on('end', function() {\n try {\n streamo[0].end();\n } catch (e) {}\n try {\n streamo[1].end();\n } catch (e) {}\n });\n containero.modem.demuxStream(stream, streamo[0], streamo[1]);\n } else {\n stream.setEncoding('utf8');\n stream.pipe(streamo, {\n end: true\n });\n }\n }\n return containero.start(startOptions);\n }).then(function(data) {\n return containero.wait();\n }).then(function(data) {\n resolve([data, containero]);\n }).catch(function(err) {\n reject(err);\n });\n });\n};\n\n/**\n * Init swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmInit = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/init',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Join swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmJoin = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/join',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Leave swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmLeave = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/leave?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 406: 'node is not part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmUpdate = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/update?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Inspect a Swarm.\n * Warning: This method is not documented in the API\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.swarmInspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 406: 'This node is not a swarm manager',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nDocker.Container = Container;\nDocker.Image = Image;\nDocker.Volume = Volume;\nDocker.Network = Network;\nDocker.Service = Service;\nDocker.Plugin = Plugin;\nDocker.Secret = Secret;\nDocker.Task = Task;\nDocker.Node = Node;\nDocker.Exec = Exec;\n\nmodule.exports = Docker;\n","var util = require('./util');\n\n/**\n * Represents an Exec\n * @param {Object} modem docker-modem\n * @param {String} id Exec's ID\n */\nvar Exec = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nExec.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Start the exec call that was setup.\n *\n * @param {object} opts\n * @param {function} callback\n */\nExec.prototype.start = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/start',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n allowEmpty: true,\n hijack: args.opts.hijack,\n openStdin: args.opts.stdin,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such exec',\n 409: 'container stopped/paused',\n 500: 'container not running'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Resize the exec call that was setup.\n *\n * @param {object} opts\n * @param {function} callback\n */\nExec.prototype.resize = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/resize?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such exec',\n 500: 'container not running'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Get low-level information about the exec call.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nExec.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/json',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such exec',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Exec;\n","var util = require('./util');\n\n/**\n * Represents an image\n * @param {Object} modem docker-modem\n * @param {String} name Image's name\n */\nvar Image = function(modem, name) {\n this.modem = modem;\n this.name = name;\n};\n\nImage.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nImage.prototype.inspect = function(callback) {\n var self = this;\n\n var opts = {\n path: '/images/' + this.name + '/json',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Distribution\n * @param {Object} opts\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nImage.prototype.distribution = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n\n var fopts = {\n path: '/distribution/' + this.name + '/json',\n method: 'GET',\n statusCodes: {\n 200: true,\n 401: 'no such image',\n 500: 'server error'\n },\n authconfig: (args.opts) ? args.opts.authconfig : undefined\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(fopts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(fopts, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * History\n * @param {Function} callback Callback\n */\nImage.prototype.history = function(callback) {\n var self = this;\n var opts = {\n path: '/images/' + this.name + '/history',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Get\n * @param {Function} callback Callback with data stream.\n */\nImage.prototype.get = function(callback) {\n var self = this;\n var opts = {\n path: '/images/' + this.name + '/get',\n method: 'GET',\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Push\n * @param {Object} opts Push options, like 'registry' (optional)\n * @param {Function} callback Callback with stream.\n * @param {Object} auth Registry authentication\n */\nImage.prototype.push = function(opts, callback, auth) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var isStream = true;\n if (args.opts.stream === false) {\n isStream = false;\n }\n var optsf = {\n path: '/images/' + this.name + '/push?',\n method: 'POST',\n options: args.opts,\n authconfig: args.opts.authconfig || auth,\n abortSignal: args.opts.abortSignal,\n isStream: isStream,\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n delete optsf.options.authconfig;\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Tag\n * @param {Object} opts Tag options, like 'repo' (optional)\n * @param {Function} callback Callback\n */\nImage.prototype.tag = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/images/' + this.name + '/tag?',\n method: 'POST',\n options: opts,\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 400: 'bad parameter',\n 404: 'no such image',\n 409: 'conflict',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Removes the image\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nImage.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/' + this.name + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Image;\n","var util = require('./util');\n\n/**\n * Represents an network\n * @param {Object} modem docker-modem\n * @param {String} id Network's id\n */\nvar Network = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nNetwork.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Id only if callback isn't specified.\n */\nNetwork.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/networks/' + this.id + '?',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such network',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the network\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such network',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Connects a container to a network\n * @param {[Object]} opts Connect options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.connect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id + '/connect',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 404: 'network or container is not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Disconnects a container from a network\n * @param {[Object]} opts Disconnect options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.disconnect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id + '/disconnect',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 404: 'network or container is not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\n\nmodule.exports = Network;\n","var util = require('./util');\n\n/**\n * Represents an Node\n * @param {Object} modem docker-modem\n * @param {String} id Node's ID\n */\nvar Node = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nNode.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for Node details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nNode.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes/' + this.id,\n method: 'GET',\n abortSignal: args.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Update a node.\n *\n * @param {object} opts\n * @param {function} callback\n */\nNode.prototype.update = function(opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n }\n\n var optsf = {\n path: '/nodes/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 406: 'node is not part of a swarm',\n 500: 'server error'\n },\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n/**\n * Remove a Node.\n * Warning: This method is not documented in the API.\n *\n * @param {object} opts\n * @param {function} callback\n */\nNode.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes/' + this.id + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Node;\n","var util = require('./util');\n\n/**\n * Represents a plugin\n * @param {Object} modem docker-modem\n * @param {String} name Plugin's name\n */\nvar Plugin = function(modem, name, remote) {\n this.modem = modem;\n this.name = name;\n this.remote = remote || name;\n};\n\nPlugin.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nPlugin.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin is not installed',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the plugin\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin is not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * get privileges\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n * @return {Object} Name only if callback isn't specified.\n */\nPlugin.prototype.privileges = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/privileges?',\n method: 'GET',\n options: {\n 'remote': this.remote\n },\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Installs a new plugin\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nPlugin.prototype.pull = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n if(args.opts._query && !args.opts._query.name) {\n args.opts._query.name = this.name;\n }\n if(args.opts._query && !args.opts._query.remote) {\n args.opts._query.remote = this.remote;\n }\n\n var optsf = {\n path: '/plugins/pull?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n options: args.opts,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Enable\n * @param {Object} opts Plugin enable options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.enable = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/enable?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Disable\n * @param {Object} opts Plugin disable options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.disable = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/disable',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Push\n * @param {Object} opts Plugin push options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.push = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/push',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * COnfigure\n * @param {Object} opts Plugin configure options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.configure = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/set',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Upgrade plugin\n *\n * @param {object} auth\n * @param {object} opts\n * @param {function} callback\n */\nPlugin.prototype.upgrade = function(auth, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n }\n\n var optsf = {\n path: '/plugins/' + this.name + '/upgrade?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n authconfig: auth,\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Plugin;\n","var util = require('./util');\n\n/**\n * Represents a secret\n * @param {Object} modem docker-modem\n * @param {String} id Secret's id\n */\nvar Secret = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nSecret.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nSecret.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'secret not found',\n 406: 'node is not part of a swarm',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update a secret.\n *\n * @param {object} opts\n * @param {function} callback\n */\nSecret.prototype.update = function(opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n }\n\n var optsf = {\n path: '/secrets/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'secret not found',\n 500: 'server error'\n },\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n/**\n * Removes the secret\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nSecret.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'secret not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Secret;\n","var util = require('./util');\n\n/**\n * Represents an Service\n * @param {Object} modem docker-modem\n * @param {String} id Service's ID\n */\nvar Service = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nService.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for service details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nService.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Delete Service\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nService.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such service',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update service\n *\n * @param {object} auth\n * @param {object} opts\n * @param {function} callback\n */\nService.prototype.update = function(auth, opts, callback) {\n var self = this;\n if (!callback) {\n var t = typeof opts;\n if(t === 'function'){\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (t === 'undefined'){\n opts = auth;\n auth = opts.authconfig || undefined;\n }\n }\n\n var optsf = {\n path: '/services/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error'\n },\n authconfig: auth,\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n\n/**\n * Service logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nService.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, {});\n\n var optsf = {\n path: '/services/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Service;\n","var util = require('./util');\n\n/**\n * Represents an Task\n * @param {Object} modem docker-modem\n * @param {String} id Task's ID\n */\nvar Task = function(modem, id) {\n this.modem = modem;\n this.id = id;\n\n this.defaultOptions = {\n log: {}\n };\n};\n\nTask.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for Task details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nTask.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/tasks/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'unknown task',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Task logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nTask.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.log);\n\n var optsf = {\n path: '/tasks/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 101: true,\n 200: true,\n 404: 'no such container',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Task;\n","// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js\n\nvar arr = [];\nvar each = arr.forEach;\nvar slice = arr.slice;\n\nmodule.exports.extend = function(obj) {\n each.call(slice.call(arguments, 1), function(source) {\n if (source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\nmodule.exports.processArgs = function(opts, callback, defaultOpts) {\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n return {\n callback: callback,\n opts: module.exports.extend({}, defaultOpts, opts)\n };\n};\n\n\n/**\n * Parse the given repo tag name (as a string) and break it out into repo/tag pair.\n * // if given the input http://localhost:8080/woot:latest\n * {\n * repository: 'http://localhost:8080/woot',\n * tag: 'latest'\n * }\n * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest'\n * @return {Object} input parsed into the repo and tag.\n */\nmodule.exports.parseRepositoryTag = function(input) {\n var separatorPos;\n var digestPos = input.indexOf('@');\n var colonPos = input.lastIndexOf(':');\n // @ symbol is more important\n if (digestPos >= 0) {\n separatorPos = digestPos;\n } else if (colonPos >= 0) {\n separatorPos = colonPos;\n } else {\n // no colon nor @\n return {\n repository: input\n };\n }\n\n // last colon is either the tag (or part of a port designation)\n var tag = input.slice(separatorPos + 1);\n\n // if it contains a / its not a tag and is part of the url\n if (tag.indexOf('/') === -1) {\n return {\n repository: input.slice(0, separatorPos),\n tag: tag\n };\n }\n\n return {\n repository: input\n };\n};\n","var util = require('./util');\n\n/**\n * Represents a volume\n * @param {Object} modem docker-modem\n * @param {String} name Volume's name\n */\nvar Volume = function(modem, name) {\n this.modem = modem;\n this.name = name;\n};\n\nVolume.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nVolume.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/' + this.name,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such volume',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the volume\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nVolume.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/' + this.name,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 204: true,\n 404: 'no such volume',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Volume;\n","var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n","var debug;\n\nmodule.exports = function () {\n if (!debug) {\n try {\n /* eslint global-require: off */\n debug = require(\"debug\")(\"follow-redirects\");\n }\n catch (error) { /* */ }\n if (typeof debug !== \"function\") {\n debug = function () { /* */ };\n }\n }\n debug.apply(null, arguments);\n};\n","var url = require(\"url\");\nvar URL = url.URL;\nvar http = require(\"http\");\nvar https = require(\"https\");\nvar Writable = require(\"stream\").Writable;\nvar assert = require(\"assert\");\nvar debug = require(\"./debug\");\n\n// Create handlers that pass events from native requests\nvar events = [\"abort\", \"aborted\", \"connect\", \"error\", \"socket\", \"timeout\"];\nvar eventHandlers = Object.create(null);\nevents.forEach(function (event) {\n eventHandlers[event] = function (arg1, arg2, arg3) {\n this._redirectable.emit(event, arg1, arg2, arg3);\n };\n});\n\n// Error types with codes\nvar RedirectionError = createErrorType(\n \"ERR_FR_REDIRECTION_FAILURE\",\n \"Redirected request failed\"\n);\nvar TooManyRedirectsError = createErrorType(\n \"ERR_FR_TOO_MANY_REDIRECTS\",\n \"Maximum number of redirects exceeded\"\n);\nvar MaxBodyLengthExceededError = createErrorType(\n \"ERR_FR_MAX_BODY_LENGTH_EXCEEDED\",\n \"Request body larger than maxBodyLength limit\"\n);\nvar WriteAfterEndError = createErrorType(\n \"ERR_STREAM_WRITE_AFTER_END\",\n \"write after end\"\n);\n\n// An HTTP(S) request that can be redirected\nfunction RedirectableRequest(options, responseCallback) {\n // Initialize the request\n Writable.call(this);\n this._sanitizeOptions(options);\n this._options = options;\n this._ended = false;\n this._ending = false;\n this._redirectCount = 0;\n this._redirects = [];\n this._requestBodyLength = 0;\n this._requestBodyBuffers = [];\n\n // Attach a callback if passed\n if (responseCallback) {\n this.on(\"response\", responseCallback);\n }\n\n // React to responses of native requests\n var self = this;\n this._onNativeResponse = function (response) {\n self._processResponse(response);\n };\n\n // Perform the first request\n this._performRequest();\n}\nRedirectableRequest.prototype = Object.create(Writable.prototype);\n\nRedirectableRequest.prototype.abort = function () {\n abortRequest(this._currentRequest);\n this.emit(\"abort\");\n};\n\n// Writes buffered data to the current native request\nRedirectableRequest.prototype.write = function (data, encoding, callback) {\n // Writing is not allowed if end has been called\n if (this._ending) {\n throw new WriteAfterEndError();\n }\n\n // Validate input and shift parameters if necessary\n if (!(typeof data === \"string\" || typeof data === \"object\" && (\"length\" in data))) {\n throw new TypeError(\"data should be a string, Buffer or Uint8Array\");\n }\n if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n\n // Ignore empty buffers, since writing them doesn't invoke the callback\n // https://github.com/nodejs/node/issues/22066\n if (data.length === 0) {\n if (callback) {\n callback();\n }\n return;\n }\n // Only write when we don't exceed the maximum body length\n if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {\n this._requestBodyLength += data.length;\n this._requestBodyBuffers.push({ data: data, encoding: encoding });\n this._currentRequest.write(data, encoding, callback);\n }\n // Error when we exceed the maximum body length\n else {\n this.emit(\"error\", new MaxBodyLengthExceededError());\n this.abort();\n }\n};\n\n// Ends the current native request\nRedirectableRequest.prototype.end = function (data, encoding, callback) {\n // Shift parameters if necessary\n if (typeof data === \"function\") {\n callback = data;\n data = encoding = null;\n }\n else if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n\n // Write data if needed and end\n if (!data) {\n this._ended = this._ending = true;\n this._currentRequest.end(null, null, callback);\n }\n else {\n var self = this;\n var currentRequest = this._currentRequest;\n this.write(data, encoding, function () {\n self._ended = true;\n currentRequest.end(null, null, callback);\n });\n this._ending = true;\n }\n};\n\n// Sets a header value on the current native request\nRedirectableRequest.prototype.setHeader = function (name, value) {\n this._options.headers[name] = value;\n this._currentRequest.setHeader(name, value);\n};\n\n// Clears a header value on the current native request\nRedirectableRequest.prototype.removeHeader = function (name) {\n delete this._options.headers[name];\n this._currentRequest.removeHeader(name);\n};\n\n// Global timeout for all underlying requests\nRedirectableRequest.prototype.setTimeout = function (msecs, callback) {\n var self = this;\n\n // Destroys the socket on timeout\n function destroyOnTimeout(socket) {\n socket.setTimeout(msecs);\n socket.removeListener(\"timeout\", socket.destroy);\n socket.addListener(\"timeout\", socket.destroy);\n }\n\n // Sets up a timer to trigger a timeout event\n function startTimer(socket) {\n if (self._timeout) {\n clearTimeout(self._timeout);\n }\n self._timeout = setTimeout(function () {\n self.emit(\"timeout\");\n clearTimer();\n }, msecs);\n destroyOnTimeout(socket);\n }\n\n // Stops a timeout from triggering\n function clearTimer() {\n // Clear the timeout\n if (self._timeout) {\n clearTimeout(self._timeout);\n self._timeout = null;\n }\n\n // Clean up all attached listeners\n self.removeListener(\"abort\", clearTimer);\n self.removeListener(\"error\", clearTimer);\n self.removeListener(\"response\", clearTimer);\n if (callback) {\n self.removeListener(\"timeout\", callback);\n }\n if (!self.socket) {\n self._currentRequest.removeListener(\"socket\", startTimer);\n }\n }\n\n // Attach callback if passed\n if (callback) {\n this.on(\"timeout\", callback);\n }\n\n // Start the timer if or when the socket is opened\n if (this.socket) {\n startTimer(this.socket);\n }\n else {\n this._currentRequest.once(\"socket\", startTimer);\n }\n\n // Clean up on events\n this.on(\"socket\", destroyOnTimeout);\n this.on(\"abort\", clearTimer);\n this.on(\"error\", clearTimer);\n this.on(\"response\", clearTimer);\n\n return this;\n};\n\n// Proxy all other public ClientRequest methods\n[\n \"flushHeaders\", \"getHeader\",\n \"setNoDelay\", \"setSocketKeepAlive\",\n].forEach(function (method) {\n RedirectableRequest.prototype[method] = function (a, b) {\n return this._currentRequest[method](a, b);\n };\n});\n\n// Proxy all public ClientRequest properties\n[\"aborted\", \"connection\", \"socket\"].forEach(function (property) {\n Object.defineProperty(RedirectableRequest.prototype, property, {\n get: function () { return this._currentRequest[property]; },\n });\n});\n\nRedirectableRequest.prototype._sanitizeOptions = function (options) {\n // Ensure headers are always present\n if (!options.headers) {\n options.headers = {};\n }\n\n // Since http.request treats host as an alias of hostname,\n // but the url module interprets host as hostname plus port,\n // eliminate the host property to avoid confusion.\n if (options.host) {\n // Use hostname if set, because it has precedence\n if (!options.hostname) {\n options.hostname = options.host;\n }\n delete options.host;\n }\n\n // Complete the URL object when necessary\n if (!options.pathname && options.path) {\n var searchPos = options.path.indexOf(\"?\");\n if (searchPos < 0) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.substring(0, searchPos);\n options.search = options.path.substring(searchPos);\n }\n }\n};\n\n\n// Executes the next native request (initial or redirect)\nRedirectableRequest.prototype._performRequest = function () {\n // Load the native protocol\n var protocol = this._options.protocol;\n var nativeProtocol = this._options.nativeProtocols[protocol];\n if (!nativeProtocol) {\n this.emit(\"error\", new TypeError(\"Unsupported protocol \" + protocol));\n return;\n }\n\n // If specified, use the agent corresponding to the protocol\n // (HTTP and HTTPS use different types of agents)\n if (this._options.agents) {\n var scheme = protocol.substr(0, protocol.length - 1);\n this._options.agent = this._options.agents[scheme];\n }\n\n // Create the native request\n var request = this._currentRequest =\n nativeProtocol.request(this._options, this._onNativeResponse);\n this._currentUrl = url.format(this._options);\n\n // Set up event handlers\n request._redirectable = this;\n for (var e = 0; e < events.length; e++) {\n request.on(events[e], eventHandlers[events[e]]);\n }\n\n // End a redirected request\n // (The first request must be ended explicitly with RedirectableRequest#end)\n if (this._isRedirect) {\n // Write the request entity and end.\n var i = 0;\n var self = this;\n var buffers = this._requestBodyBuffers;\n (function writeNext(error) {\n // Only write if this request has not been redirected yet\n /* istanbul ignore else */\n if (request === self._currentRequest) {\n // Report any write errors\n /* istanbul ignore if */\n if (error) {\n self.emit(\"error\", error);\n }\n // Write the next buffer if there are still left\n else if (i < buffers.length) {\n var buffer = buffers[i++];\n /* istanbul ignore else */\n if (!request.finished) {\n request.write(buffer.data, buffer.encoding, writeNext);\n }\n }\n // End the request if `end` has been called on us\n else if (self._ended) {\n request.end();\n }\n }\n }());\n }\n};\n\n// Processes a response from the current native request\nRedirectableRequest.prototype._processResponse = function (response) {\n // Store the redirected response\n var statusCode = response.statusCode;\n if (this._options.trackRedirects) {\n this._redirects.push({\n url: this._currentUrl,\n headers: response.headers,\n statusCode: statusCode,\n });\n }\n\n // RFC7231§6.4: The 3xx (Redirection) class of status code indicates\n // that further action needs to be taken by the user agent in order to\n // fulfill the request. If a Location header field is provided,\n // the user agent MAY automatically redirect its request to the URI\n // referenced by the Location field value,\n // even if the specific status code is not understood.\n\n // If the response is not a redirect; return it as-is\n var location = response.headers.location;\n if (!location || this._options.followRedirects === false ||\n statusCode < 300 || statusCode >= 400) {\n response.responseUrl = this._currentUrl;\n response.redirects = this._redirects;\n this.emit(\"response\", response);\n\n // Clean up\n this._requestBodyBuffers = [];\n return;\n }\n\n // The response is a redirect, so abort the current request\n abortRequest(this._currentRequest);\n // Discard the remainder of the response to avoid waiting for data\n response.destroy();\n\n // RFC7231§6.4: A client SHOULD detect and intervene\n // in cyclical redirections (i.e., \"infinite\" redirection loops).\n if (++this._redirectCount > this._options.maxRedirects) {\n this.emit(\"error\", new TooManyRedirectsError());\n return;\n }\n\n // RFC7231§6.4: Automatic redirection needs to done with\n // care for methods not known to be safe, […]\n // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change\n // the request method from POST to GET for the subsequent request.\n if ((statusCode === 301 || statusCode === 302) && this._options.method === \"POST\" ||\n // RFC7231§6.4.4: The 303 (See Other) status code indicates that\n // the server is redirecting the user agent to a different resource […]\n // A user agent can perform a retrieval request targeting that URI\n // (a GET or HEAD request if using HTTP) […]\n (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {\n this._options.method = \"GET\";\n // Drop a possible entity and headers related to it\n this._requestBodyBuffers = [];\n removeMatchingHeaders(/^content-/i, this._options.headers);\n }\n\n // Drop the Host header, as the redirect might lead to a different host\n var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);\n\n // If the redirect is relative, carry over the host of the last request\n var currentUrlParts = url.parse(this._currentUrl);\n var currentHost = currentHostHeader || currentUrlParts.host;\n var currentUrl = /^\\w+:/.test(location) ? this._currentUrl :\n url.format(Object.assign(currentUrlParts, { host: currentHost }));\n\n // Determine the URL of the redirection\n var redirectUrl;\n try {\n redirectUrl = url.resolve(currentUrl, location);\n }\n catch (cause) {\n this.emit(\"error\", new RedirectionError(cause));\n return;\n }\n\n // Create the redirected request\n debug(\"redirecting to\", redirectUrl);\n this._isRedirect = true;\n var redirectUrlParts = url.parse(redirectUrl);\n Object.assign(this._options, redirectUrlParts);\n\n // Drop confidential headers when redirecting to a less secure protocol\n // or to a different domain that is not a superdomain\n if (redirectUrlParts.protocol !== currentUrlParts.protocol &&\n redirectUrlParts.protocol !== \"https:\" ||\n redirectUrlParts.host !== currentHost &&\n !isSubdomain(redirectUrlParts.host, currentHost)) {\n removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);\n }\n\n // Evaluate the beforeRedirect callback\n if (typeof this._options.beforeRedirect === \"function\") {\n var responseDetails = { headers: response.headers };\n try {\n this._options.beforeRedirect.call(null, this._options, responseDetails);\n }\n catch (err) {\n this.emit(\"error\", err);\n return;\n }\n this._sanitizeOptions(this._options);\n }\n\n // Perform the redirected request\n try {\n this._performRequest();\n }\n catch (cause) {\n this.emit(\"error\", new RedirectionError(cause));\n }\n};\n\n// Wraps the key/value object of protocols with redirect functionality\nfunction wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters\n if (typeof input === \"string\") {\n var urlStr = input;\n try {\n input = urlToOptions(new URL(urlStr));\n }\n catch (err) {\n /* istanbul ignore next */\n input = url.parse(urlStr);\n }\n }\n else if (URL && (input instanceof URL)) {\n input = urlToOptions(input);\n }\n else {\n callback = options;\n options = input;\n input = { protocol: protocol };\n }\n if (typeof options === \"function\") {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}\n\n/* istanbul ignore next */\nfunction noop() { /* empty */ }\n\n// from https://github.com/nodejs/node/blob/master/lib/internal/url.js\nfunction urlToOptions(urlObject) {\n var options = {\n protocol: urlObject.protocol,\n hostname: urlObject.hostname.startsWith(\"[\") ?\n /* istanbul ignore next */\n urlObject.hostname.slice(1, -1) :\n urlObject.hostname,\n hash: urlObject.hash,\n search: urlObject.search,\n pathname: urlObject.pathname,\n path: urlObject.pathname + urlObject.search,\n href: urlObject.href,\n };\n if (urlObject.port !== \"\") {\n options.port = Number(urlObject.port);\n }\n return options;\n}\n\nfunction removeMatchingHeaders(regex, headers) {\n var lastValue;\n for (var header in headers) {\n if (regex.test(header)) {\n lastValue = headers[header];\n delete headers[header];\n }\n }\n return (lastValue === null || typeof lastValue === \"undefined\") ?\n undefined : String(lastValue).trim();\n}\n\nfunction createErrorType(code, defaultMessage) {\n function CustomError(cause) {\n Error.captureStackTrace(this, this.constructor);\n if (!cause) {\n this.message = defaultMessage;\n }\n else {\n this.message = defaultMessage + \": \" + cause.message;\n this.cause = cause;\n }\n }\n CustomError.prototype = new Error();\n CustomError.prototype.constructor = CustomError;\n CustomError.prototype.name = \"Error [\" + code + \"]\";\n CustomError.prototype.code = code;\n return CustomError;\n}\n\nfunction abortRequest(request) {\n for (var e = 0; e < events.length; e++) {\n request.removeListener(events[e], eventHandlers[events[e]]);\n }\n request.on(\"error\", noop);\n request.abort();\n}\n\nfunction isSubdomain(subdomain, domain) {\n const dot = subdomain.length - domain.length - 1;\n return dot > 0 && subdomain[dot] === \".\" && subdomain.endsWith(domain);\n}\n\n// Exports\nmodule.exports = wrap({ http: http, https: https });\nmodule.exports.wrap = wrap;\n","module.exports = require('fs').constants || require('constants')\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nfunction isObject(o) {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n\nfunction isPlainObject(o) {\n var ctor,prot;\n\n if (isObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (ctor === undefined) return true;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\nexports.isPlainObject = isPlainObject;\n","var path = require('path');\nvar fs = require('fs');\nvar _0777 = parseInt('0777', 8);\n\nmodule.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;\n\nfunction mkdirP (p, opts, f, made) {\n if (typeof opts === 'function') {\n f = opts;\n opts = {};\n }\n else if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n \n var mode = opts.mode;\n var xfs = opts.fs || fs;\n \n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made) made = null;\n \n var cb = f || function () {};\n p = path.resolve(p);\n \n xfs.mkdir(p, mode, function (er) {\n if (!er) {\n made = made || p;\n return cb(null, made);\n }\n switch (er.code) {\n case 'ENOENT':\n mkdirP(path.dirname(p), opts, function (er, made) {\n if (er) cb(er, made);\n else mkdirP(p, opts, cb, made);\n });\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n xfs.stat(p, function (er2, stat) {\n // if the stat fails, then that's super weird.\n // let the original error be the failure reason.\n if (er2 || !stat.isDirectory()) cb(er, made)\n else cb(null, made);\n });\n break;\n }\n });\n}\n\nmkdirP.sync = function sync (p, opts, made) {\n if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n \n var mode = opts.mode;\n var xfs = opts.fs || fs;\n \n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made) made = null;\n\n p = path.resolve(p);\n\n try {\n xfs.mkdirSync(p, mode);\n made = made || p;\n }\n catch (err0) {\n switch (err0.code) {\n case 'ENOENT' :\n made = sync(path.dirname(p), opts, made);\n sync(p, opts, made);\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n var stat;\n try {\n stat = xfs.statSync(p);\n }\n catch (err1) {\n throw err0;\n }\n if (!stat.isDirectory()) throw err0;\n break;\n }\n }\n\n return made;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar Stream = _interopDefault(require('stream'));\nvar http = _interopDefault(require('http'));\nvar Url = _interopDefault(require('url'));\nvar whatwgUrl = _interopDefault(require('whatwg-url'));\nvar https = _interopDefault(require('https'));\nvar zlib = _interopDefault(require('zlib'));\n\n// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js\n\n// fix for \"Readable\" isn't a named export issue\nconst Readable = Stream.Readable;\n\nconst BUFFER = Symbol('buffer');\nconst TYPE = Symbol('type');\n\nclass Blob {\n\tconstructor() {\n\t\tthis[TYPE] = '';\n\n\t\tconst blobParts = arguments[0];\n\t\tconst options = arguments[1];\n\n\t\tconst buffers = [];\n\t\tlet size = 0;\n\n\t\tif (blobParts) {\n\t\t\tconst a = blobParts;\n\t\t\tconst length = Number(a.length);\n\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\tconst element = a[i];\n\t\t\t\tlet buffer;\n\t\t\t\tif (element instanceof Buffer) {\n\t\t\t\t\tbuffer = element;\n\t\t\t\t} else if (ArrayBuffer.isView(element)) {\n\t\t\t\t\tbuffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);\n\t\t\t\t} else if (element instanceof ArrayBuffer) {\n\t\t\t\t\tbuffer = Buffer.from(element);\n\t\t\t\t} else if (element instanceof Blob) {\n\t\t\t\t\tbuffer = element[BUFFER];\n\t\t\t\t} else {\n\t\t\t\t\tbuffer = Buffer.from(typeof element === 'string' ? element : String(element));\n\t\t\t\t}\n\t\t\t\tsize += buffer.length;\n\t\t\t\tbuffers.push(buffer);\n\t\t\t}\n\t\t}\n\n\t\tthis[BUFFER] = Buffer.concat(buffers);\n\n\t\tlet type = options && options.type !== undefined && String(options.type).toLowerCase();\n\t\tif (type && !/[^\\u0020-\\u007E]/.test(type)) {\n\t\t\tthis[TYPE] = type;\n\t\t}\n\t}\n\tget size() {\n\t\treturn this[BUFFER].length;\n\t}\n\tget type() {\n\t\treturn this[TYPE];\n\t}\n\ttext() {\n\t\treturn Promise.resolve(this[BUFFER].toString());\n\t}\n\tarrayBuffer() {\n\t\tconst buf = this[BUFFER];\n\t\tconst ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n\t\treturn Promise.resolve(ab);\n\t}\n\tstream() {\n\t\tconst readable = new Readable();\n\t\treadable._read = function () {};\n\t\treadable.push(this[BUFFER]);\n\t\treadable.push(null);\n\t\treturn readable;\n\t}\n\ttoString() {\n\t\treturn '[object Blob]';\n\t}\n\tslice() {\n\t\tconst size = this.size;\n\n\t\tconst start = arguments[0];\n\t\tconst end = arguments[1];\n\t\tlet relativeStart, relativeEnd;\n\t\tif (start === undefined) {\n\t\t\trelativeStart = 0;\n\t\t} else if (start < 0) {\n\t\t\trelativeStart = Math.max(size + start, 0);\n\t\t} else {\n\t\t\trelativeStart = Math.min(start, size);\n\t\t}\n\t\tif (end === undefined) {\n\t\t\trelativeEnd = size;\n\t\t} else if (end < 0) {\n\t\t\trelativeEnd = Math.max(size + end, 0);\n\t\t} else {\n\t\t\trelativeEnd = Math.min(end, size);\n\t\t}\n\t\tconst span = Math.max(relativeEnd - relativeStart, 0);\n\n\t\tconst buffer = this[BUFFER];\n\t\tconst slicedBuffer = buffer.slice(relativeStart, relativeStart + span);\n\t\tconst blob = new Blob([], { type: arguments[2] });\n\t\tblob[BUFFER] = slicedBuffer;\n\t\treturn blob;\n\t}\n}\n\nObject.defineProperties(Blob.prototype, {\n\tsize: { enumerable: true },\n\ttype: { enumerable: true },\n\tslice: { enumerable: true }\n});\n\nObject.defineProperty(Blob.prototype, Symbol.toStringTag, {\n\tvalue: 'Blob',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\n/**\n * fetch-error.js\n *\n * FetchError interface for operational errors\n */\n\n/**\n * Create FetchError instance\n *\n * @param String message Error message for human\n * @param String type Error type for machine\n * @param String systemError For Node.js system error\n * @return FetchError\n */\nfunction FetchError(message, type, systemError) {\n Error.call(this, message);\n\n this.message = message;\n this.type = type;\n\n // when err.type is `system`, err.code contains system error code\n if (systemError) {\n this.code = this.errno = systemError.code;\n }\n\n // hide custom error implementation details from end-users\n Error.captureStackTrace(this, this.constructor);\n}\n\nFetchError.prototype = Object.create(Error.prototype);\nFetchError.prototype.constructor = FetchError;\nFetchError.prototype.name = 'FetchError';\n\nlet convert;\ntry {\n\tconvert = require('encoding').convert;\n} catch (e) {}\n\nconst INTERNALS = Symbol('Body internals');\n\n// fix an issue where \"PassThrough\" isn't a named export for node <10\nconst PassThrough = Stream.PassThrough;\n\n/**\n * Body mixin\n *\n * Ref: https://fetch.spec.whatwg.org/#body\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nfunction Body(body) {\n\tvar _this = this;\n\n\tvar _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n\t _ref$size = _ref.size;\n\n\tlet size = _ref$size === undefined ? 0 : _ref$size;\n\tvar _ref$timeout = _ref.timeout;\n\tlet timeout = _ref$timeout === undefined ? 0 : _ref$timeout;\n\n\tif (body == null) {\n\t\t// body is undefined or null\n\t\tbody = null;\n\t} else if (isURLSearchParams(body)) {\n\t\t// body is a URLSearchParams\n\t\tbody = Buffer.from(body.toString());\n\t} else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {\n\t\t// body is ArrayBuffer\n\t\tbody = Buffer.from(body);\n\t} else if (ArrayBuffer.isView(body)) {\n\t\t// body is ArrayBufferView\n\t\tbody = Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n\t} else if (body instanceof Stream) ; else {\n\t\t// none of the above\n\t\t// coerce to string then buffer\n\t\tbody = Buffer.from(String(body));\n\t}\n\tthis[INTERNALS] = {\n\t\tbody,\n\t\tdisturbed: false,\n\t\terror: null\n\t};\n\tthis.size = size;\n\tthis.timeout = timeout;\n\n\tif (body instanceof Stream) {\n\t\tbody.on('error', function (err) {\n\t\t\tconst error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);\n\t\t\t_this[INTERNALS].error = error;\n\t\t});\n\t}\n}\n\nBody.prototype = {\n\tget body() {\n\t\treturn this[INTERNALS].body;\n\t},\n\n\tget bodyUsed() {\n\t\treturn this[INTERNALS].disturbed;\n\t},\n\n\t/**\n * Decode response as ArrayBuffer\n *\n * @return Promise\n */\n\tarrayBuffer() {\n\t\treturn consumeBody.call(this).then(function (buf) {\n\t\t\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n\t\t});\n\t},\n\n\t/**\n * Return raw response as Blob\n *\n * @return Promise\n */\n\tblob() {\n\t\tlet ct = this.headers && this.headers.get('content-type') || '';\n\t\treturn consumeBody.call(this).then(function (buf) {\n\t\t\treturn Object.assign(\n\t\t\t// Prevent copying\n\t\t\tnew Blob([], {\n\t\t\t\ttype: ct.toLowerCase()\n\t\t\t}), {\n\t\t\t\t[BUFFER]: buf\n\t\t\t});\n\t\t});\n\t},\n\n\t/**\n * Decode response as json\n *\n * @return Promise\n */\n\tjson() {\n\t\tvar _this2 = this;\n\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(buffer.toString());\n\t\t\t} catch (err) {\n\t\t\t\treturn Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));\n\t\t\t}\n\t\t});\n\t},\n\n\t/**\n * Decode response as text\n *\n * @return Promise\n */\n\ttext() {\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\treturn buffer.toString();\n\t\t});\n\t},\n\n\t/**\n * Decode response as buffer (non-spec api)\n *\n * @return Promise\n */\n\tbuffer() {\n\t\treturn consumeBody.call(this);\n\t},\n\n\t/**\n * Decode response as text, while automatically detecting the encoding and\n * trying to decode to UTF-8 (non-spec api)\n *\n * @return Promise\n */\n\ttextConverted() {\n\t\tvar _this3 = this;\n\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\treturn convertBody(buffer, _this3.headers);\n\t\t});\n\t}\n};\n\n// In browsers, all properties are enumerable.\nObject.defineProperties(Body.prototype, {\n\tbody: { enumerable: true },\n\tbodyUsed: { enumerable: true },\n\tarrayBuffer: { enumerable: true },\n\tblob: { enumerable: true },\n\tjson: { enumerable: true },\n\ttext: { enumerable: true }\n});\n\nBody.mixIn = function (proto) {\n\tfor (const name of Object.getOwnPropertyNames(Body.prototype)) {\n\t\t// istanbul ignore else: future proof\n\t\tif (!(name in proto)) {\n\t\t\tconst desc = Object.getOwnPropertyDescriptor(Body.prototype, name);\n\t\t\tObject.defineProperty(proto, name, desc);\n\t\t}\n\t}\n};\n\n/**\n * Consume and convert an entire Body to a Buffer.\n *\n * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body\n *\n * @return Promise\n */\nfunction consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}\n\n/**\n * Detect buffer encoding and convert to target encoding\n * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding\n *\n * @param Buffer buffer Incoming buffer\n * @param String encoding Target encoding\n * @return String\n */\nfunction convertBody(buffer, headers) {\n\tif (typeof convert !== 'function') {\n\t\tthrow new Error('The package `encoding` must be installed to use the textConverted() function');\n\t}\n\n\tconst ct = headers.get('content-type');\n\tlet charset = 'utf-8';\n\tlet res, str;\n\n\t// header\n\tif (ct) {\n\t\tres = /charset=([^;]*)/i.exec(ct);\n\t}\n\n\t// no charset in content type, peek at response body for at most 1024 bytes\n\tstr = buffer.slice(0, 1024).toString();\n\n\t// html5\n\tif (!res && str) {\n\t\tres = / 0 && arguments[0] !== undefined ? arguments[0] : undefined;\n\n\t\tthis[MAP] = Object.create(null);\n\n\t\tif (init instanceof Headers) {\n\t\t\tconst rawHeaders = init.raw();\n\t\t\tconst headerNames = Object.keys(rawHeaders);\n\n\t\t\tfor (const headerName of headerNames) {\n\t\t\t\tfor (const value of rawHeaders[headerName]) {\n\t\t\t\t\tthis.append(headerName, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\t// We don't worry about converting prop to ByteString here as append()\n\t\t// will handle it.\n\t\tif (init == null) ; else if (typeof init === 'object') {\n\t\t\tconst method = init[Symbol.iterator];\n\t\t\tif (method != null) {\n\t\t\t\tif (typeof method !== 'function') {\n\t\t\t\t\tthrow new TypeError('Header pairs must be iterable');\n\t\t\t\t}\n\n\t\t\t\t// sequence>\n\t\t\t\t// Note: per spec we have to first exhaust the lists then process them\n\t\t\t\tconst pairs = [];\n\t\t\t\tfor (const pair of init) {\n\t\t\t\t\tif (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {\n\t\t\t\t\t\tthrow new TypeError('Each header pair must be iterable');\n\t\t\t\t\t}\n\t\t\t\t\tpairs.push(Array.from(pair));\n\t\t\t\t}\n\n\t\t\t\tfor (const pair of pairs) {\n\t\t\t\t\tif (pair.length !== 2) {\n\t\t\t\t\t\tthrow new TypeError('Each header pair must be a name/value tuple');\n\t\t\t\t\t}\n\t\t\t\t\tthis.append(pair[0], pair[1]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// record\n\t\t\t\tfor (const key of Object.keys(init)) {\n\t\t\t\t\tconst value = init[key];\n\t\t\t\t\tthis.append(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new TypeError('Provided initializer must be an object');\n\t\t}\n\t}\n\n\t/**\n * Return combined header value given name\n *\n * @param String name Header name\n * @return Mixed\n */\n\tget(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key === undefined) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this[MAP][key].join(', ');\n\t}\n\n\t/**\n * Iterate over all headers\n *\n * @param Function callback Executed for each item with parameters (value, name, thisArg)\n * @param Boolean thisArg `this` context for callback function\n * @return Void\n */\n\tforEach(callback) {\n\t\tlet thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;\n\n\t\tlet pairs = getHeaders(this);\n\t\tlet i = 0;\n\t\twhile (i < pairs.length) {\n\t\t\tvar _pairs$i = pairs[i];\n\t\t\tconst name = _pairs$i[0],\n\t\t\t value = _pairs$i[1];\n\n\t\t\tcallback.call(thisArg, value, name, this);\n\t\t\tpairs = getHeaders(this);\n\t\t\ti++;\n\t\t}\n\t}\n\n\t/**\n * Overwrite header values given name\n *\n * @param String name Header name\n * @param String value Header value\n * @return Void\n */\n\tset(name, value) {\n\t\tname = `${name}`;\n\t\tvalue = `${value}`;\n\t\tvalidateName(name);\n\t\tvalidateValue(value);\n\t\tconst key = find(this[MAP], name);\n\t\tthis[MAP][key !== undefined ? key : name] = [value];\n\t}\n\n\t/**\n * Append a value onto existing header\n *\n * @param String name Header name\n * @param String value Header value\n * @return Void\n */\n\tappend(name, value) {\n\t\tname = `${name}`;\n\t\tvalue = `${value}`;\n\t\tvalidateName(name);\n\t\tvalidateValue(value);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key !== undefined) {\n\t\t\tthis[MAP][key].push(value);\n\t\t} else {\n\t\t\tthis[MAP][name] = [value];\n\t\t}\n\t}\n\n\t/**\n * Check for header name existence\n *\n * @param String name Header name\n * @return Boolean\n */\n\thas(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\treturn find(this[MAP], name) !== undefined;\n\t}\n\n\t/**\n * Delete all header values given name\n *\n * @param String name Header name\n * @return Void\n */\n\tdelete(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key !== undefined) {\n\t\t\tdelete this[MAP][key];\n\t\t}\n\t}\n\n\t/**\n * Return raw headers (non-spec api)\n *\n * @return Object\n */\n\traw() {\n\t\treturn this[MAP];\n\t}\n\n\t/**\n * Get an iterator on keys.\n *\n * @return Iterator\n */\n\tkeys() {\n\t\treturn createHeadersIterator(this, 'key');\n\t}\n\n\t/**\n * Get an iterator on values.\n *\n * @return Iterator\n */\n\tvalues() {\n\t\treturn createHeadersIterator(this, 'value');\n\t}\n\n\t/**\n * Get an iterator on entries.\n *\n * This is the default iterator of the Headers object.\n *\n * @return Iterator\n */\n\t[Symbol.iterator]() {\n\t\treturn createHeadersIterator(this, 'key+value');\n\t}\n}\nHeaders.prototype.entries = Headers.prototype[Symbol.iterator];\n\nObject.defineProperty(Headers.prototype, Symbol.toStringTag, {\n\tvalue: 'Headers',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nObject.defineProperties(Headers.prototype, {\n\tget: { enumerable: true },\n\tforEach: { enumerable: true },\n\tset: { enumerable: true },\n\tappend: { enumerable: true },\n\thas: { enumerable: true },\n\tdelete: { enumerable: true },\n\tkeys: { enumerable: true },\n\tvalues: { enumerable: true },\n\tentries: { enumerable: true }\n});\n\nfunction getHeaders(headers) {\n\tlet kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';\n\n\tconst keys = Object.keys(headers[MAP]).sort();\n\treturn keys.map(kind === 'key' ? function (k) {\n\t\treturn k.toLowerCase();\n\t} : kind === 'value' ? function (k) {\n\t\treturn headers[MAP][k].join(', ');\n\t} : function (k) {\n\t\treturn [k.toLowerCase(), headers[MAP][k].join(', ')];\n\t});\n}\n\nconst INTERNAL = Symbol('internal');\n\nfunction createHeadersIterator(target, kind) {\n\tconst iterator = Object.create(HeadersIteratorPrototype);\n\titerator[INTERNAL] = {\n\t\ttarget,\n\t\tkind,\n\t\tindex: 0\n\t};\n\treturn iterator;\n}\n\nconst HeadersIteratorPrototype = Object.setPrototypeOf({\n\tnext() {\n\t\t// istanbul ignore if\n\t\tif (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {\n\t\t\tthrow new TypeError('Value of `this` is not a HeadersIterator');\n\t\t}\n\n\t\tvar _INTERNAL = this[INTERNAL];\n\t\tconst target = _INTERNAL.target,\n\t\t kind = _INTERNAL.kind,\n\t\t index = _INTERNAL.index;\n\n\t\tconst values = getHeaders(target, kind);\n\t\tconst len = values.length;\n\t\tif (index >= len) {\n\t\t\treturn {\n\t\t\t\tvalue: undefined,\n\t\t\t\tdone: true\n\t\t\t};\n\t\t}\n\n\t\tthis[INTERNAL].index = index + 1;\n\n\t\treturn {\n\t\t\tvalue: values[index],\n\t\t\tdone: false\n\t\t};\n\t}\n}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));\n\nObject.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {\n\tvalue: 'HeadersIterator',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\n/**\n * Export the Headers object in a form that Node.js can consume.\n *\n * @param Headers headers\n * @return Object\n */\nfunction exportNodeCompatibleHeaders(headers) {\n\tconst obj = Object.assign({ __proto__: null }, headers[MAP]);\n\n\t// http.request() only supports string as Host header. This hack makes\n\t// specifying custom Host header possible.\n\tconst hostHeaderKey = find(headers[MAP], 'Host');\n\tif (hostHeaderKey !== undefined) {\n\t\tobj[hostHeaderKey] = obj[hostHeaderKey][0];\n\t}\n\n\treturn obj;\n}\n\n/**\n * Create a Headers object from an object of headers, ignoring those that do\n * not conform to HTTP grammar productions.\n *\n * @param Object obj Object of headers\n * @return Headers\n */\nfunction createHeadersLenient(obj) {\n\tconst headers = new Headers();\n\tfor (const name of Object.keys(obj)) {\n\t\tif (invalidTokenRegex.test(name)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (Array.isArray(obj[name])) {\n\t\t\tfor (const val of obj[name]) {\n\t\t\t\tif (invalidHeaderCharRegex.test(val)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (headers[MAP][name] === undefined) {\n\t\t\t\t\theaders[MAP][name] = [val];\n\t\t\t\t} else {\n\t\t\t\t\theaders[MAP][name].push(val);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (!invalidHeaderCharRegex.test(obj[name])) {\n\t\t\theaders[MAP][name] = [obj[name]];\n\t\t}\n\t}\n\treturn headers;\n}\n\nconst INTERNALS$1 = Symbol('Response internals');\n\n// fix an issue where \"STATUS_CODES\" aren't a named export for node <10\nconst STATUS_CODES = http.STATUS_CODES;\n\n/**\n * Response class\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nclass Response {\n\tconstructor() {\n\t\tlet body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n\t\tlet opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n\t\tBody.call(this, body, opts);\n\n\t\tconst status = opts.status || 200;\n\t\tconst headers = new Headers(opts.headers);\n\n\t\tif (body != null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(body);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tthis[INTERNALS$1] = {\n\t\t\turl: opts.url,\n\t\t\tstatus,\n\t\t\tstatusText: opts.statusText || STATUS_CODES[status],\n\t\t\theaders,\n\t\t\tcounter: opts.counter\n\t\t};\n\t}\n\n\tget url() {\n\t\treturn this[INTERNALS$1].url || '';\n\t}\n\n\tget status() {\n\t\treturn this[INTERNALS$1].status;\n\t}\n\n\t/**\n * Convenience property representing if the request ended normally\n */\n\tget ok() {\n\t\treturn this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;\n\t}\n\n\tget redirected() {\n\t\treturn this[INTERNALS$1].counter > 0;\n\t}\n\n\tget statusText() {\n\t\treturn this[INTERNALS$1].statusText;\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS$1].headers;\n\t}\n\n\t/**\n * Clone this response\n *\n * @return Response\n */\n\tclone() {\n\t\treturn new Response(clone(this), {\n\t\t\turl: this.url,\n\t\t\tstatus: this.status,\n\t\t\tstatusText: this.statusText,\n\t\t\theaders: this.headers,\n\t\t\tok: this.ok,\n\t\t\tredirected: this.redirected\n\t\t});\n\t}\n}\n\nBody.mixIn(Response.prototype);\n\nObject.defineProperties(Response.prototype, {\n\turl: { enumerable: true },\n\tstatus: { enumerable: true },\n\tok: { enumerable: true },\n\tredirected: { enumerable: true },\n\tstatusText: { enumerable: true },\n\theaders: { enumerable: true },\n\tclone: { enumerable: true }\n});\n\nObject.defineProperty(Response.prototype, Symbol.toStringTag, {\n\tvalue: 'Response',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nconst INTERNALS$2 = Symbol('Request internals');\nconst URL = Url.URL || whatwgUrl.URL;\n\n// fix an issue where \"format\", \"parse\" aren't a named export for node <10\nconst parse_url = Url.parse;\nconst format_url = Url.format;\n\n/**\n * Wrapper around `new URL` to handle arbitrary URLs\n *\n * @param {string} urlStr\n * @return {void}\n */\nfunction parseURL(urlStr) {\n\t/*\n \tCheck whether the URL is absolute or not\n \t\tScheme: https://tools.ietf.org/html/rfc3986#section-3.1\n \tAbsolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\n */\n\tif (/^[a-zA-Z][a-zA-Z\\d+\\-.]*:/.exec(urlStr)) {\n\t\turlStr = new URL(urlStr).toString();\n\t}\n\n\t// Fallback to old implementation for arbitrary URLs\n\treturn parse_url(urlStr);\n}\n\nconst streamDestructionSupported = 'destroy' in Stream.Readable.prototype;\n\n/**\n * Check if a value is an instance of Request.\n *\n * @param Mixed input\n * @return Boolean\n */\nfunction isRequest(input) {\n\treturn typeof input === 'object' && typeof input[INTERNALS$2] === 'object';\n}\n\nfunction isAbortSignal(signal) {\n\tconst proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);\n\treturn !!(proto && proto.constructor.name === 'AbortSignal');\n}\n\n/**\n * Request class\n *\n * @param Mixed input Url or Request instance\n * @param Object init Custom options\n * @return Void\n */\nclass Request {\n\tconstructor(input) {\n\t\tlet init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n\t\tlet parsedURL;\n\n\t\t// normalize input\n\t\tif (!isRequest(input)) {\n\t\t\tif (input && input.href) {\n\t\t\t\t// in order to support Node.js' Url objects; though WHATWG's URL objects\n\t\t\t\t// will fall into this branch also (since their `toString()` will return\n\t\t\t\t// `href` property anyway)\n\t\t\t\tparsedURL = parseURL(input.href);\n\t\t\t} else {\n\t\t\t\t// coerce input to a string before attempting to parse\n\t\t\t\tparsedURL = parseURL(`${input}`);\n\t\t\t}\n\t\t\tinput = {};\n\t\t} else {\n\t\t\tparsedURL = parseURL(input.url);\n\t\t}\n\n\t\tlet method = init.method || input.method || 'GET';\n\t\tmethod = method.toUpperCase();\n\n\t\tif ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {\n\t\t\tthrow new TypeError('Request with GET/HEAD method cannot have body');\n\t\t}\n\n\t\tlet inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;\n\n\t\tBody.call(this, inputBody, {\n\t\t\ttimeout: init.timeout || input.timeout || 0,\n\t\t\tsize: init.size || input.size || 0\n\t\t});\n\n\t\tconst headers = new Headers(init.headers || input.headers || {});\n\n\t\tif (inputBody != null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(inputBody);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tlet signal = isRequest(input) ? input.signal : null;\n\t\tif ('signal' in init) signal = init.signal;\n\n\t\tif (signal != null && !isAbortSignal(signal)) {\n\t\t\tthrow new TypeError('Expected signal to be an instanceof AbortSignal');\n\t\t}\n\n\t\tthis[INTERNALS$2] = {\n\t\t\tmethod,\n\t\t\tredirect: init.redirect || input.redirect || 'follow',\n\t\t\theaders,\n\t\t\tparsedURL,\n\t\t\tsignal\n\t\t};\n\n\t\t// node-fetch-only options\n\t\tthis.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;\n\t\tthis.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;\n\t\tthis.counter = init.counter || input.counter || 0;\n\t\tthis.agent = init.agent || input.agent;\n\t}\n\n\tget method() {\n\t\treturn this[INTERNALS$2].method;\n\t}\n\n\tget url() {\n\t\treturn format_url(this[INTERNALS$2].parsedURL);\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS$2].headers;\n\t}\n\n\tget redirect() {\n\t\treturn this[INTERNALS$2].redirect;\n\t}\n\n\tget signal() {\n\t\treturn this[INTERNALS$2].signal;\n\t}\n\n\t/**\n * Clone this request\n *\n * @return Request\n */\n\tclone() {\n\t\treturn new Request(this);\n\t}\n}\n\nBody.mixIn(Request.prototype);\n\nObject.defineProperty(Request.prototype, Symbol.toStringTag, {\n\tvalue: 'Request',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nObject.defineProperties(Request.prototype, {\n\tmethod: { enumerable: true },\n\turl: { enumerable: true },\n\theaders: { enumerable: true },\n\tredirect: { enumerable: true },\n\tclone: { enumerable: true },\n\tsignal: { enumerable: true }\n});\n\n/**\n * Convert a Request to Node.js http request options.\n *\n * @param Request A Request instance\n * @return Object The options object to be passed to http.request\n */\nfunction getNodeRequestOptions(request) {\n\tconst parsedURL = request[INTERNALS$2].parsedURL;\n\tconst headers = new Headers(request[INTERNALS$2].headers);\n\n\t// fetch step 1.3\n\tif (!headers.has('Accept')) {\n\t\theaders.set('Accept', '*/*');\n\t}\n\n\t// Basic fetch\n\tif (!parsedURL.protocol || !parsedURL.hostname) {\n\t\tthrow new TypeError('Only absolute URLs are supported');\n\t}\n\n\tif (!/^https?:$/.test(parsedURL.protocol)) {\n\t\tthrow new TypeError('Only HTTP(S) protocols are supported');\n\t}\n\n\tif (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {\n\t\tthrow new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');\n\t}\n\n\t// HTTP-network-or-cache fetch steps 2.4-2.7\n\tlet contentLengthValue = null;\n\tif (request.body == null && /^(POST|PUT)$/i.test(request.method)) {\n\t\tcontentLengthValue = '0';\n\t}\n\tif (request.body != null) {\n\t\tconst totalBytes = getTotalBytes(request);\n\t\tif (typeof totalBytes === 'number') {\n\t\t\tcontentLengthValue = String(totalBytes);\n\t\t}\n\t}\n\tif (contentLengthValue) {\n\t\theaders.set('Content-Length', contentLengthValue);\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.11\n\tif (!headers.has('User-Agent')) {\n\t\theaders.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.15\n\tif (request.compress && !headers.has('Accept-Encoding')) {\n\t\theaders.set('Accept-Encoding', 'gzip,deflate');\n\t}\n\n\tlet agent = request.agent;\n\tif (typeof agent === 'function') {\n\t\tagent = agent(parsedURL);\n\t}\n\n\tif (!headers.has('Connection') && !agent) {\n\t\theaders.set('Connection', 'close');\n\t}\n\n\t// HTTP-network fetch step 4.2\n\t// chunked encoding is handled by Node.js\n\n\treturn Object.assign({}, parsedURL, {\n\t\tmethod: request.method,\n\t\theaders: exportNodeCompatibleHeaders(headers),\n\t\tagent\n\t});\n}\n\n/**\n * abort-error.js\n *\n * AbortError interface for cancelled requests\n */\n\n/**\n * Create AbortError instance\n *\n * @param String message Error message for human\n * @return AbortError\n */\nfunction AbortError(message) {\n Error.call(this, message);\n\n this.type = 'aborted';\n this.message = message;\n\n // hide custom error implementation details from end-users\n Error.captureStackTrace(this, this.constructor);\n}\n\nAbortError.prototype = Object.create(Error.prototype);\nAbortError.prototype.constructor = AbortError;\nAbortError.prototype.name = 'AbortError';\n\nconst URL$1 = Url.URL || whatwgUrl.URL;\n\n// fix an issue where \"PassThrough\", \"resolve\" aren't a named export for node <10\nconst PassThrough$1 = Stream.PassThrough;\n\nconst isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {\n\tconst orig = new URL$1(original).hostname;\n\tconst dest = new URL$1(destination).hostname;\n\n\treturn orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);\n};\n\n/**\n * Fetch function\n *\n * @param Mixed url Absolute url or Request instance\n * @param Object opts Fetch options\n * @return Promise\n */\nfunction fetch(url, opts) {\n\n\t// allow custom promise\n\tif (!fetch.Promise) {\n\t\tthrow new Error('native promise missing, set fetch.Promise to your favorite alternative');\n\t}\n\n\tBody.Promise = fetch.Promise;\n\n\t// wrap http.request into fetch\n\treturn new fetch.Promise(function (resolve, reject) {\n\t\t// build request object\n\t\tconst request = new Request(url, opts);\n\t\tconst options = getNodeRequestOptions(request);\n\n\t\tconst send = (options.protocol === 'https:' ? https : http).request;\n\t\tconst signal = request.signal;\n\n\t\tlet response = null;\n\n\t\tconst abort = function abort() {\n\t\t\tlet error = new AbortError('The user aborted a request.');\n\t\t\treject(error);\n\t\t\tif (request.body && request.body instanceof Stream.Readable) {\n\t\t\t\trequest.body.destroy(error);\n\t\t\t}\n\t\t\tif (!response || !response.body) return;\n\t\t\tresponse.body.emit('error', error);\n\t\t};\n\n\t\tif (signal && signal.aborted) {\n\t\t\tabort();\n\t\t\treturn;\n\t\t}\n\n\t\tconst abortAndFinalize = function abortAndFinalize() {\n\t\t\tabort();\n\t\t\tfinalize();\n\t\t};\n\n\t\t// send request\n\t\tconst req = send(options);\n\t\tlet reqTimeout;\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', abortAndFinalize);\n\t\t}\n\n\t\tfunction finalize() {\n\t\t\treq.abort();\n\t\t\tif (signal) signal.removeEventListener('abort', abortAndFinalize);\n\t\t\tclearTimeout(reqTimeout);\n\t\t}\n\n\t\tif (request.timeout) {\n\t\t\treq.once('socket', function (socket) {\n\t\t\t\treqTimeout = setTimeout(function () {\n\t\t\t\t\treject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));\n\t\t\t\t\tfinalize();\n\t\t\t\t}, request.timeout);\n\t\t\t});\n\t\t}\n\n\t\treq.on('error', function (err) {\n\t\t\treject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));\n\t\t\tfinalize();\n\t\t});\n\n\t\treq.on('response', function (res) {\n\t\t\tclearTimeout(reqTimeout);\n\n\t\t\tconst headers = createHeadersLenient(res.headers);\n\n\t\t\t// HTTP fetch step 5\n\t\t\tif (fetch.isRedirect(res.statusCode)) {\n\t\t\t\t// HTTP fetch step 5.2\n\t\t\t\tconst location = headers.get('Location');\n\n\t\t\t\t// HTTP fetch step 5.3\n\t\t\t\tlet locationURL = null;\n\t\t\t\ttry {\n\t\t\t\t\tlocationURL = location === null ? null : new URL$1(location, request.url).toString();\n\t\t\t\t} catch (err) {\n\t\t\t\t\t// error here can only be invalid URL in Location: header\n\t\t\t\t\t// do not throw when options.redirect == manual\n\t\t\t\t\t// let the user extract the errorneous redirect URL\n\t\t\t\t\tif (request.redirect !== 'manual') {\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// HTTP fetch step 5.5\n\t\t\t\tswitch (request.redirect) {\n\t\t\t\t\tcase 'error':\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase 'manual':\n\t\t\t\t\t\t// node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.\n\t\t\t\t\t\tif (locationURL !== null) {\n\t\t\t\t\t\t\t// handle corrupted header\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\theaders.set('Location', locationURL);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t// istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request\n\t\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'follow':\n\t\t\t\t\t\t// HTTP-redirect fetch step 2\n\t\t\t\t\t\tif (locationURL === null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 5\n\t\t\t\t\t\tif (request.counter >= request.follow) {\n\t\t\t\t\t\t\treject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 6 (counter increment)\n\t\t\t\t\t\t// Create a new Request object.\n\t\t\t\t\t\tconst requestOpts = {\n\t\t\t\t\t\t\theaders: new Headers(request.headers),\n\t\t\t\t\t\t\tfollow: request.follow,\n\t\t\t\t\t\t\tcounter: request.counter + 1,\n\t\t\t\t\t\t\tagent: request.agent,\n\t\t\t\t\t\t\tcompress: request.compress,\n\t\t\t\t\t\t\tmethod: request.method,\n\t\t\t\t\t\t\tbody: request.body,\n\t\t\t\t\t\t\tsignal: request.signal,\n\t\t\t\t\t\t\ttimeout: request.timeout,\n\t\t\t\t\t\t\tsize: request.size\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tif (!isDomainOrSubdomain(request.url, locationURL)) {\n\t\t\t\t\t\t\tfor (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {\n\t\t\t\t\t\t\t\trequestOpts.headers.delete(name);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 9\n\t\t\t\t\t\tif (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {\n\t\t\t\t\t\t\treject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 11\n\t\t\t\t\t\tif (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {\n\t\t\t\t\t\t\trequestOpts.method = 'GET';\n\t\t\t\t\t\t\trequestOpts.body = undefined;\n\t\t\t\t\t\t\trequestOpts.headers.delete('content-length');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 15\n\t\t\t\t\t\tresolve(fetch(new Request(locationURL, requestOpts)));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// prepare response\n\t\t\tres.once('end', function () {\n\t\t\t\tif (signal) signal.removeEventListener('abort', abortAndFinalize);\n\t\t\t});\n\t\t\tlet body = res.pipe(new PassThrough$1());\n\n\t\t\tconst response_options = {\n\t\t\t\turl: request.url,\n\t\t\t\tstatus: res.statusCode,\n\t\t\t\tstatusText: res.statusMessage,\n\t\t\t\theaders: headers,\n\t\t\t\tsize: request.size,\n\t\t\t\ttimeout: request.timeout,\n\t\t\t\tcounter: request.counter\n\t\t\t};\n\n\t\t\t// HTTP-network fetch step 12.1.1.3\n\t\t\tconst codings = headers.get('Content-Encoding');\n\n\t\t\t// HTTP-network fetch step 12.1.1.4: handle content codings\n\n\t\t\t// in following scenarios we ignore compression support\n\t\t\t// 1. compression support is disabled\n\t\t\t// 2. HEAD request\n\t\t\t// 3. no Content-Encoding header\n\t\t\t// 4. no content response (204)\n\t\t\t// 5. content not modified response (304)\n\t\t\tif (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For Node v6+\n\t\t\t// Be less strict when decoding compressed responses, since sometimes\n\t\t\t// servers send slightly invalid responses that are still accepted\n\t\t\t// by common browsers.\n\t\t\t// Always using Z_SYNC_FLUSH is what cURL does.\n\t\t\tconst zlibOptions = {\n\t\t\t\tflush: zlib.Z_SYNC_FLUSH,\n\t\t\t\tfinishFlush: zlib.Z_SYNC_FLUSH\n\t\t\t};\n\n\t\t\t// for gzip\n\t\t\tif (codings == 'gzip' || codings == 'x-gzip') {\n\t\t\t\tbody = body.pipe(zlib.createGunzip(zlibOptions));\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// for deflate\n\t\t\tif (codings == 'deflate' || codings == 'x-deflate') {\n\t\t\t\t// handle the infamous raw deflate response from old servers\n\t\t\t\t// a hack for old IIS and Apache servers\n\t\t\t\tconst raw = res.pipe(new PassThrough$1());\n\t\t\t\traw.once('data', function (chunk) {\n\t\t\t\t\t// see http://stackoverflow.com/questions/37519828\n\t\t\t\t\tif ((chunk[0] & 0x0F) === 0x08) {\n\t\t\t\t\t\tbody = body.pipe(zlib.createInflate());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbody = body.pipe(zlib.createInflateRaw());\n\t\t\t\t\t}\n\t\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\t\tresolve(response);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// for br\n\t\t\tif (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {\n\t\t\t\tbody = body.pipe(zlib.createBrotliDecompress());\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// otherwise, use response as-is\n\t\t\tresponse = new Response(body, response_options);\n\t\t\tresolve(response);\n\t\t});\n\n\t\twriteToStream(req, request);\n\t});\n}\n/**\n * Redirect code matching\n *\n * @param Number code Status code\n * @return Boolean\n */\nfetch.isRedirect = function (code) {\n\treturn code === 301 || code === 302 || code === 303 || code === 307 || code === 308;\n};\n\n// expose Promise\nfetch.Promise = global.Promise;\n\nmodule.exports = exports = fetch;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = exports;\nexports.Headers = Headers;\nexports.Request = Request;\nexports.Response = Response;\nexports.FetchError = FetchError;\n","\"use strict\";\n\nvar punycode = require(\"punycode\");\nvar mappingTable = require(\"./lib/mappingTable.json\");\n\nvar PROCESSING_OPTIONS = {\n TRANSITIONAL: 0,\n NONTRANSITIONAL: 1\n};\n\nfunction normalize(str) { // fix bug in v8\n return str.split('\\u0000').map(function (s) { return s.normalize('NFC'); }).join('\\u0000');\n}\n\nfunction findStatus(val) {\n var start = 0;\n var end = mappingTable.length - 1;\n\n while (start <= end) {\n var mid = Math.floor((start + end) / 2);\n\n var target = mappingTable[mid];\n if (target[0][0] <= val && target[0][1] >= val) {\n return target;\n } else if (target[0][0] > val) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n }\n\n return null;\n}\n\nvar regexAstralSymbols = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n\nfunction countSymbols(string) {\n return string\n // replace every surrogate pair with a BMP symbol\n .replace(regexAstralSymbols, '_')\n // then get the length\n .length;\n}\n\nfunction mapChars(domain_name, useSTD3, processing_option) {\n var hasError = false;\n var processed = \"\";\n\n var len = countSymbols(domain_name);\n for (var i = 0; i < len; ++i) {\n var codePoint = domain_name.codePointAt(i);\n var status = findStatus(codePoint);\n\n switch (status[1]) {\n case \"disallowed\":\n hasError = true;\n processed += String.fromCodePoint(codePoint);\n break;\n case \"ignored\":\n break;\n case \"mapped\":\n processed += String.fromCodePoint.apply(String, status[2]);\n break;\n case \"deviation\":\n if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {\n processed += String.fromCodePoint.apply(String, status[2]);\n } else {\n processed += String.fromCodePoint(codePoint);\n }\n break;\n case \"valid\":\n processed += String.fromCodePoint(codePoint);\n break;\n case \"disallowed_STD3_mapped\":\n if (useSTD3) {\n hasError = true;\n processed += String.fromCodePoint(codePoint);\n } else {\n processed += String.fromCodePoint.apply(String, status[2]);\n }\n break;\n case \"disallowed_STD3_valid\":\n if (useSTD3) {\n hasError = true;\n }\n\n processed += String.fromCodePoint(codePoint);\n break;\n }\n }\n\n return {\n string: processed,\n error: hasError\n };\n}\n\nvar combiningMarksRegex = /[\\u0300-\\u036F\\u0483-\\u0489\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C00-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C81-\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D01-\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1AB0-\\u1ABE\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1CF8\\u1CF9\\u1DC0-\\u1DF5\\u1DFC-\\u1DFF\\u20D0-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F-\\uA672\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uA9E5\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B-\\uAA7D\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE2D]|\\uD800[\\uDDFD\\uDEE0\\uDF76-\\uDF7A]|\\uD802[\\uDE01-\\uDE03\\uDE05\\uDE06\\uDE0C-\\uDE0F\\uDE38-\\uDE3A\\uDE3F\\uDEE5\\uDEE6]|\\uD804[\\uDC00-\\uDC02\\uDC38-\\uDC46\\uDC7F-\\uDC82\\uDCB0-\\uDCBA\\uDD00-\\uDD02\\uDD27-\\uDD34\\uDD73\\uDD80-\\uDD82\\uDDB3-\\uDDC0\\uDE2C-\\uDE37\\uDEDF-\\uDEEA\\uDF01-\\uDF03\\uDF3C\\uDF3E-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF57\\uDF62\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDCB0-\\uDCC3\\uDDAF-\\uDDB5\\uDDB8-\\uDDC0\\uDE30-\\uDE40\\uDEAB-\\uDEB7]|\\uD81A[\\uDEF0-\\uDEF4\\uDF30-\\uDF36]|\\uD81B[\\uDF51-\\uDF7E\\uDF8F-\\uDF92]|\\uD82F[\\uDC9D\\uDC9E]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uDD82\\uDD85-\\uDD8B\\uDDAA-\\uDDAD\\uDE42-\\uDE44]|\\uD83A[\\uDCD0-\\uDCD6]|\\uDB40[\\uDD00-\\uDDEF]/;\n\nfunction validateLabel(label, processing_option) {\n if (label.substr(0, 4) === \"xn--\") {\n label = punycode.toUnicode(label);\n processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;\n }\n\n var error = false;\n\n if (normalize(label) !== label ||\n (label[3] === \"-\" && label[4] === \"-\") ||\n label[0] === \"-\" || label[label.length - 1] === \"-\" ||\n label.indexOf(\".\") !== -1 ||\n label.search(combiningMarksRegex) === 0) {\n error = true;\n }\n\n var len = countSymbols(label);\n for (var i = 0; i < len; ++i) {\n var status = findStatus(label.codePointAt(i));\n if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== \"valid\") ||\n (processing === PROCESSING_OPTIONS.NONTRANSITIONAL &&\n status[1] !== \"valid\" && status[1] !== \"deviation\")) {\n error = true;\n break;\n }\n }\n\n return {\n label: label,\n error: error\n };\n}\n\nfunction processing(domain_name, useSTD3, processing_option) {\n var result = mapChars(domain_name, useSTD3, processing_option);\n result.string = normalize(result.string);\n\n var labels = result.string.split(\".\");\n for (var i = 0; i < labels.length; ++i) {\n try {\n var validation = validateLabel(labels[i]);\n labels[i] = validation.label;\n result.error = result.error || validation.error;\n } catch(e) {\n result.error = true;\n }\n }\n\n return {\n string: labels.join(\".\"),\n error: result.error\n };\n}\n\nmodule.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {\n var result = processing(domain_name, useSTD3, processing_option);\n var labels = result.string.split(\".\");\n labels = labels.map(function(l) {\n try {\n return punycode.toASCII(l);\n } catch(e) {\n result.error = true;\n return l;\n }\n });\n\n if (verifyDnsLength) {\n var total = labels.slice(0, labels.length - 1).join(\".\").length;\n if (total.length > 253 || total.length === 0) {\n result.error = true;\n }\n\n for (var i=0; i < labels.length; ++i) {\n if (labels.length > 63 || labels.length === 0) {\n result.error = true;\n break;\n }\n }\n }\n\n if (result.error) return null;\n return labels.join(\".\");\n};\n\nmodule.exports.toUnicode = function(domain_name, useSTD3) {\n var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);\n\n return {\n domain: result.string,\n error: result.error\n };\n};\n\nmodule.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;\n","\"use strict\";\n\nvar conversions = {};\nmodule.exports = conversions;\n\nfunction sign(x) {\n return x < 0 ? -1 : 1;\n}\n\nfunction evenRound(x) {\n // Round x to the nearest integer, choosing the even integer if it lies halfway between two.\n if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor)\n return Math.floor(x);\n } else {\n return Math.round(x);\n }\n}\n\nfunction createNumberConversion(bitLength, typeOpts) {\n if (!typeOpts.unsigned) {\n --bitLength;\n }\n const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);\n const upperBound = Math.pow(2, bitLength) - 1;\n\n const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);\n const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);\n\n return function(V, opts) {\n if (!opts) opts = {};\n\n let x = +V;\n\n if (opts.enforceRange) {\n if (!Number.isFinite(x)) {\n throw new TypeError(\"Argument is not a finite number\");\n }\n\n x = sign(x) * Math.floor(Math.abs(x));\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(\"Argument is not in byte range\");\n }\n\n return x;\n }\n\n if (!isNaN(x) && opts.clamp) {\n x = evenRound(x);\n\n if (x < lowerBound) x = lowerBound;\n if (x > upperBound) x = upperBound;\n return x;\n }\n\n if (!Number.isFinite(x) || x === 0) {\n return 0;\n }\n\n x = sign(x) * Math.floor(Math.abs(x));\n x = x % moduloVal;\n\n if (!typeOpts.unsigned && x >= moduloBound) {\n return x - moduloVal;\n } else if (typeOpts.unsigned) {\n if (x < 0) {\n x += moduloVal;\n } else if (x === -0) { // don't return negative zero\n return 0;\n }\n }\n\n return x;\n }\n}\n\nconversions[\"void\"] = function () {\n return undefined;\n};\n\nconversions[\"boolean\"] = function (val) {\n return !!val;\n};\n\nconversions[\"byte\"] = createNumberConversion(8, { unsigned: false });\nconversions[\"octet\"] = createNumberConversion(8, { unsigned: true });\n\nconversions[\"short\"] = createNumberConversion(16, { unsigned: false });\nconversions[\"unsigned short\"] = createNumberConversion(16, { unsigned: true });\n\nconversions[\"long\"] = createNumberConversion(32, { unsigned: false });\nconversions[\"unsigned long\"] = createNumberConversion(32, { unsigned: true });\n\nconversions[\"long long\"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });\nconversions[\"unsigned long long\"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });\n\nconversions[\"double\"] = function (V) {\n const x = +V;\n\n if (!Number.isFinite(x)) {\n throw new TypeError(\"Argument is not a finite floating-point value\");\n }\n\n return x;\n};\n\nconversions[\"unrestricted double\"] = function (V) {\n const x = +V;\n\n if (isNaN(x)) {\n throw new TypeError(\"Argument is NaN\");\n }\n\n return x;\n};\n\n// not quite valid, but good enough for JS\nconversions[\"float\"] = conversions[\"double\"];\nconversions[\"unrestricted float\"] = conversions[\"unrestricted double\"];\n\nconversions[\"DOMString\"] = function (V, opts) {\n if (!opts) opts = {};\n\n if (opts.treatNullAsEmptyString && V === null) {\n return \"\";\n }\n\n return String(V);\n};\n\nconversions[\"ByteString\"] = function (V, opts) {\n const x = String(V);\n let c = undefined;\n for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) {\n if (c > 255) {\n throw new TypeError(\"Argument is not a valid bytestring\");\n }\n }\n\n return x;\n};\n\nconversions[\"USVString\"] = function (V) {\n const S = String(V);\n const n = S.length;\n const U = [];\n for (let i = 0; i < n; ++i) {\n const c = S.charCodeAt(i);\n if (c < 0xD800 || c > 0xDFFF) {\n U.push(String.fromCodePoint(c));\n } else if (0xDC00 <= c && c <= 0xDFFF) {\n U.push(String.fromCodePoint(0xFFFD));\n } else {\n if (i === n - 1) {\n U.push(String.fromCodePoint(0xFFFD));\n } else {\n const d = S.charCodeAt(i + 1);\n if (0xDC00 <= d && d <= 0xDFFF) {\n const a = c & 0x3FF;\n const b = d & 0x3FF;\n U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));\n ++i;\n } else {\n U.push(String.fromCodePoint(0xFFFD));\n }\n }\n }\n }\n\n return U.join('');\n};\n\nconversions[\"Date\"] = function (V, opts) {\n if (!(V instanceof Date)) {\n throw new TypeError(\"Argument is not a Date object\");\n }\n if (isNaN(V)) {\n return undefined;\n }\n\n return V;\n};\n\nconversions[\"RegExp\"] = function (V, opts) {\n if (!(V instanceof RegExp)) {\n V = new RegExp(V);\n }\n\n return V;\n};\n","\"use strict\";\nconst usm = require(\"./url-state-machine\");\n\nexports.implementation = class URLImpl {\n constructor(constructorArgs) {\n const url = constructorArgs[0];\n const base = constructorArgs[1];\n\n let parsedBase = null;\n if (base !== undefined) {\n parsedBase = usm.basicURLParse(base);\n if (parsedBase === \"failure\") {\n throw new TypeError(\"Invalid base URL\");\n }\n }\n\n const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });\n if (parsedURL === \"failure\") {\n throw new TypeError(\"Invalid URL\");\n }\n\n this._url = parsedURL;\n\n // TODO: query stuff\n }\n\n get href() {\n return usm.serializeURL(this._url);\n }\n\n set href(v) {\n const parsedURL = usm.basicURLParse(v);\n if (parsedURL === \"failure\") {\n throw new TypeError(\"Invalid URL\");\n }\n\n this._url = parsedURL;\n }\n\n get origin() {\n return usm.serializeURLOrigin(this._url);\n }\n\n get protocol() {\n return this._url.scheme + \":\";\n }\n\n set protocol(v) {\n usm.basicURLParse(v + \":\", { url: this._url, stateOverride: \"scheme start\" });\n }\n\n get username() {\n return this._url.username;\n }\n\n set username(v) {\n if (usm.cannotHaveAUsernamePasswordPort(this._url)) {\n return;\n }\n\n usm.setTheUsername(this._url, v);\n }\n\n get password() {\n return this._url.password;\n }\n\n set password(v) {\n if (usm.cannotHaveAUsernamePasswordPort(this._url)) {\n return;\n }\n\n usm.setThePassword(this._url, v);\n }\n\n get host() {\n const url = this._url;\n\n if (url.host === null) {\n return \"\";\n }\n\n if (url.port === null) {\n return usm.serializeHost(url.host);\n }\n\n return usm.serializeHost(url.host) + \":\" + usm.serializeInteger(url.port);\n }\n\n set host(v) {\n if (this._url.cannotBeABaseURL) {\n return;\n }\n\n usm.basicURLParse(v, { url: this._url, stateOverride: \"host\" });\n }\n\n get hostname() {\n if (this._url.host === null) {\n return \"\";\n }\n\n return usm.serializeHost(this._url.host);\n }\n\n set hostname(v) {\n if (this._url.cannotBeABaseURL) {\n return;\n }\n\n usm.basicURLParse(v, { url: this._url, stateOverride: \"hostname\" });\n }\n\n get port() {\n if (this._url.port === null) {\n return \"\";\n }\n\n return usm.serializeInteger(this._url.port);\n }\n\n set port(v) {\n if (usm.cannotHaveAUsernamePasswordPort(this._url)) {\n return;\n }\n\n if (v === \"\") {\n this._url.port = null;\n } else {\n usm.basicURLParse(v, { url: this._url, stateOverride: \"port\" });\n }\n }\n\n get pathname() {\n if (this._url.cannotBeABaseURL) {\n return this._url.path[0];\n }\n\n if (this._url.path.length === 0) {\n return \"\";\n }\n\n return \"/\" + this._url.path.join(\"/\");\n }\n\n set pathname(v) {\n if (this._url.cannotBeABaseURL) {\n return;\n }\n\n this._url.path = [];\n usm.basicURLParse(v, { url: this._url, stateOverride: \"path start\" });\n }\n\n get search() {\n if (this._url.query === null || this._url.query === \"\") {\n return \"\";\n }\n\n return \"?\" + this._url.query;\n }\n\n set search(v) {\n // TODO: query stuff\n\n const url = this._url;\n\n if (v === \"\") {\n url.query = null;\n return;\n }\n\n const input = v[0] === \"?\" ? v.substring(1) : v;\n url.query = \"\";\n usm.basicURLParse(input, { url, stateOverride: \"query\" });\n }\n\n get hash() {\n if (this._url.fragment === null || this._url.fragment === \"\") {\n return \"\";\n }\n\n return \"#\" + this._url.fragment;\n }\n\n set hash(v) {\n if (v === \"\") {\n this._url.fragment = null;\n return;\n }\n\n const input = v[0] === \"#\" ? v.substring(1) : v;\n this._url.fragment = \"\";\n usm.basicURLParse(input, { url: this._url, stateOverride: \"fragment\" });\n }\n\n toJSON() {\n return this.href;\n }\n};\n","\"use strict\";\n\nconst conversions = require(\"webidl-conversions\");\nconst utils = require(\"./utils.js\");\nconst Impl = require(\".//URL-impl.js\");\n\nconst impl = utils.implSymbol;\n\nfunction URL(url) {\n if (!this || this[impl] || !(this instanceof URL)) {\n throw new TypeError(\"Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.\");\n }\n if (arguments.length < 1) {\n throw new TypeError(\"Failed to construct 'URL': 1 argument required, but only \" + arguments.length + \" present.\");\n }\n const args = [];\n for (let i = 0; i < arguments.length && i < 2; ++i) {\n args[i] = arguments[i];\n }\n args[0] = conversions[\"USVString\"](args[0]);\n if (args[1] !== undefined) {\n args[1] = conversions[\"USVString\"](args[1]);\n }\n\n module.exports.setup(this, args);\n}\n\nURL.prototype.toJSON = function toJSON() {\n if (!this || !module.exports.is(this)) {\n throw new TypeError(\"Illegal invocation\");\n }\n const args = [];\n for (let i = 0; i < arguments.length && i < 0; ++i) {\n args[i] = arguments[i];\n }\n return this[impl].toJSON.apply(this[impl], args);\n};\nObject.defineProperty(URL.prototype, \"href\", {\n get() {\n return this[impl].href;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].href = V;\n },\n enumerable: true,\n configurable: true\n});\n\nURL.prototype.toString = function () {\n if (!this || !module.exports.is(this)) {\n throw new TypeError(\"Illegal invocation\");\n }\n return this.href;\n};\n\nObject.defineProperty(URL.prototype, \"origin\", {\n get() {\n return this[impl].origin;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"protocol\", {\n get() {\n return this[impl].protocol;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].protocol = V;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"username\", {\n get() {\n return this[impl].username;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].username = V;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"password\", {\n get() {\n return this[impl].password;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].password = V;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"host\", {\n get() {\n return this[impl].host;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].host = V;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"hostname\", {\n get() {\n return this[impl].hostname;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].hostname = V;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"port\", {\n get() {\n return this[impl].port;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].port = V;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"pathname\", {\n get() {\n return this[impl].pathname;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].pathname = V;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"search\", {\n get() {\n return this[impl].search;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].search = V;\n },\n enumerable: true,\n configurable: true\n});\n\nObject.defineProperty(URL.prototype, \"hash\", {\n get() {\n return this[impl].hash;\n },\n set(V) {\n V = conversions[\"USVString\"](V);\n this[impl].hash = V;\n },\n enumerable: true,\n configurable: true\n});\n\n\nmodule.exports = {\n is(obj) {\n return !!obj && obj[impl] instanceof Impl.implementation;\n },\n create(constructorArgs, privateData) {\n let obj = Object.create(URL.prototype);\n this.setup(obj, constructorArgs, privateData);\n return obj;\n },\n setup(obj, constructorArgs, privateData) {\n if (!privateData) privateData = {};\n privateData.wrapper = obj;\n\n obj[impl] = new Impl.implementation(constructorArgs, privateData);\n obj[impl][utils.wrapperSymbol] = obj;\n },\n interface: URL,\n expose: {\n Window: { URL: URL },\n Worker: { URL: URL }\n }\n};\n\n","\"use strict\";\n\nexports.URL = require(\"./URL\").interface;\nexports.serializeURL = require(\"./url-state-machine\").serializeURL;\nexports.serializeURLOrigin = require(\"./url-state-machine\").serializeURLOrigin;\nexports.basicURLParse = require(\"./url-state-machine\").basicURLParse;\nexports.setTheUsername = require(\"./url-state-machine\").setTheUsername;\nexports.setThePassword = require(\"./url-state-machine\").setThePassword;\nexports.serializeHost = require(\"./url-state-machine\").serializeHost;\nexports.serializeInteger = require(\"./url-state-machine\").serializeInteger;\nexports.parseURL = require(\"./url-state-machine\").parseURL;\n","\"use strict\";\r\nconst punycode = require(\"punycode\");\r\nconst tr46 = require(\"tr46\");\r\n\r\nconst specialSchemes = {\r\n ftp: 21,\r\n file: null,\r\n gopher: 70,\r\n http: 80,\r\n https: 443,\r\n ws: 80,\r\n wss: 443\r\n};\r\n\r\nconst failure = Symbol(\"failure\");\r\n\r\nfunction countSymbols(str) {\r\n return punycode.ucs2.decode(str).length;\r\n}\r\n\r\nfunction at(input, idx) {\r\n const c = input[idx];\r\n return isNaN(c) ? undefined : String.fromCodePoint(c);\r\n}\r\n\r\nfunction isASCIIDigit(c) {\r\n return c >= 0x30 && c <= 0x39;\r\n}\r\n\r\nfunction isASCIIAlpha(c) {\r\n return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);\r\n}\r\n\r\nfunction isASCIIAlphanumeric(c) {\r\n return isASCIIAlpha(c) || isASCIIDigit(c);\r\n}\r\n\r\nfunction isASCIIHex(c) {\r\n return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);\r\n}\r\n\r\nfunction isSingleDot(buffer) {\r\n return buffer === \".\" || buffer.toLowerCase() === \"%2e\";\r\n}\r\n\r\nfunction isDoubleDot(buffer) {\r\n buffer = buffer.toLowerCase();\r\n return buffer === \"..\" || buffer === \"%2e.\" || buffer === \".%2e\" || buffer === \"%2e%2e\";\r\n}\r\n\r\nfunction isWindowsDriveLetterCodePoints(cp1, cp2) {\r\n return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124);\r\n}\r\n\r\nfunction isWindowsDriveLetterString(string) {\r\n return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === \":\" || string[1] === \"|\");\r\n}\r\n\r\nfunction isNormalizedWindowsDriveLetterString(string) {\r\n return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === \":\";\r\n}\r\n\r\nfunction containsForbiddenHostCodePoint(string) {\r\n return string.search(/\\u0000|\\u0009|\\u000A|\\u000D|\\u0020|#|%|\\/|:|\\?|@|\\[|\\\\|\\]/) !== -1;\r\n}\r\n\r\nfunction containsForbiddenHostCodePointExcludingPercent(string) {\r\n return string.search(/\\u0000|\\u0009|\\u000A|\\u000D|\\u0020|#|\\/|:|\\?|@|\\[|\\\\|\\]/) !== -1;\r\n}\r\n\r\nfunction isSpecialScheme(scheme) {\r\n return specialSchemes[scheme] !== undefined;\r\n}\r\n\r\nfunction isSpecial(url) {\r\n return isSpecialScheme(url.scheme);\r\n}\r\n\r\nfunction defaultPort(scheme) {\r\n return specialSchemes[scheme];\r\n}\r\n\r\nfunction percentEncode(c) {\r\n let hex = c.toString(16).toUpperCase();\r\n if (hex.length === 1) {\r\n hex = \"0\" + hex;\r\n }\r\n\r\n return \"%\" + hex;\r\n}\r\n\r\nfunction utf8PercentEncode(c) {\r\n const buf = new Buffer(c);\r\n\r\n let str = \"\";\r\n\r\n for (let i = 0; i < buf.length; ++i) {\r\n str += percentEncode(buf[i]);\r\n }\r\n\r\n return str;\r\n}\r\n\r\nfunction utf8PercentDecode(str) {\r\n const input = new Buffer(str);\r\n const output = [];\r\n for (let i = 0; i < input.length; ++i) {\r\n if (input[i] !== 37) {\r\n output.push(input[i]);\r\n } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) {\r\n output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16));\r\n i += 2;\r\n } else {\r\n output.push(input[i]);\r\n }\r\n }\r\n return new Buffer(output).toString();\r\n}\r\n\r\nfunction isC0ControlPercentEncode(c) {\r\n return c <= 0x1F || c > 0x7E;\r\n}\r\n\r\nconst extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);\r\nfunction isPathPercentEncode(c) {\r\n return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c);\r\n}\r\n\r\nconst extraUserinfoPercentEncodeSet =\r\n new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);\r\nfunction isUserinfoPercentEncode(c) {\r\n return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);\r\n}\r\n\r\nfunction percentEncodeChar(c, encodeSetPredicate) {\r\n const cStr = String.fromCodePoint(c);\r\n\r\n if (encodeSetPredicate(c)) {\r\n return utf8PercentEncode(cStr);\r\n }\r\n\r\n return cStr;\r\n}\r\n\r\nfunction parseIPv4Number(input) {\r\n let R = 10;\r\n\r\n if (input.length >= 2 && input.charAt(0) === \"0\" && input.charAt(1).toLowerCase() === \"x\") {\r\n input = input.substring(2);\r\n R = 16;\r\n } else if (input.length >= 2 && input.charAt(0) === \"0\") {\r\n input = input.substring(1);\r\n R = 8;\r\n }\r\n\r\n if (input === \"\") {\r\n return 0;\r\n }\r\n\r\n const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/);\r\n if (regex.test(input)) {\r\n return failure;\r\n }\r\n\r\n return parseInt(input, R);\r\n}\r\n\r\nfunction parseIPv4(input) {\r\n const parts = input.split(\".\");\r\n if (parts[parts.length - 1] === \"\") {\r\n if (parts.length > 1) {\r\n parts.pop();\r\n }\r\n }\r\n\r\n if (parts.length > 4) {\r\n return input;\r\n }\r\n\r\n const numbers = [];\r\n for (const part of parts) {\r\n if (part === \"\") {\r\n return input;\r\n }\r\n const n = parseIPv4Number(part);\r\n if (n === failure) {\r\n return input;\r\n }\r\n\r\n numbers.push(n);\r\n }\r\n\r\n for (let i = 0; i < numbers.length - 1; ++i) {\r\n if (numbers[i] > 255) {\r\n return failure;\r\n }\r\n }\r\n if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {\r\n return failure;\r\n }\r\n\r\n let ipv4 = numbers.pop();\r\n let counter = 0;\r\n\r\n for (const n of numbers) {\r\n ipv4 += n * Math.pow(256, 3 - counter);\r\n ++counter;\r\n }\r\n\r\n return ipv4;\r\n}\r\n\r\nfunction serializeIPv4(address) {\r\n let output = \"\";\r\n let n = address;\r\n\r\n for (let i = 1; i <= 4; ++i) {\r\n output = String(n % 256) + output;\r\n if (i !== 4) {\r\n output = \".\" + output;\r\n }\r\n n = Math.floor(n / 256);\r\n }\r\n\r\n return output;\r\n}\r\n\r\nfunction parseIPv6(input) {\r\n const address = [0, 0, 0, 0, 0, 0, 0, 0];\r\n let pieceIndex = 0;\r\n let compress = null;\r\n let pointer = 0;\r\n\r\n input = punycode.ucs2.decode(input);\r\n\r\n if (input[pointer] === 58) {\r\n if (input[pointer + 1] !== 58) {\r\n return failure;\r\n }\r\n\r\n pointer += 2;\r\n ++pieceIndex;\r\n compress = pieceIndex;\r\n }\r\n\r\n while (pointer < input.length) {\r\n if (pieceIndex === 8) {\r\n return failure;\r\n }\r\n\r\n if (input[pointer] === 58) {\r\n if (compress !== null) {\r\n return failure;\r\n }\r\n ++pointer;\r\n ++pieceIndex;\r\n compress = pieceIndex;\r\n continue;\r\n }\r\n\r\n let value = 0;\r\n let length = 0;\r\n\r\n while (length < 4 && isASCIIHex(input[pointer])) {\r\n value = value * 0x10 + parseInt(at(input, pointer), 16);\r\n ++pointer;\r\n ++length;\r\n }\r\n\r\n if (input[pointer] === 46) {\r\n if (length === 0) {\r\n return failure;\r\n }\r\n\r\n pointer -= length;\r\n\r\n if (pieceIndex > 6) {\r\n return failure;\r\n }\r\n\r\n let numbersSeen = 0;\r\n\r\n while (input[pointer] !== undefined) {\r\n let ipv4Piece = null;\r\n\r\n if (numbersSeen > 0) {\r\n if (input[pointer] === 46 && numbersSeen < 4) {\r\n ++pointer;\r\n } else {\r\n return failure;\r\n }\r\n }\r\n\r\n if (!isASCIIDigit(input[pointer])) {\r\n return failure;\r\n }\r\n\r\n while (isASCIIDigit(input[pointer])) {\r\n const number = parseInt(at(input, pointer));\r\n if (ipv4Piece === null) {\r\n ipv4Piece = number;\r\n } else if (ipv4Piece === 0) {\r\n return failure;\r\n } else {\r\n ipv4Piece = ipv4Piece * 10 + number;\r\n }\r\n if (ipv4Piece > 255) {\r\n return failure;\r\n }\r\n ++pointer;\r\n }\r\n\r\n address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece;\r\n\r\n ++numbersSeen;\r\n\r\n if (numbersSeen === 2 || numbersSeen === 4) {\r\n ++pieceIndex;\r\n }\r\n }\r\n\r\n if (numbersSeen !== 4) {\r\n return failure;\r\n }\r\n\r\n break;\r\n } else if (input[pointer] === 58) {\r\n ++pointer;\r\n if (input[pointer] === undefined) {\r\n return failure;\r\n }\r\n } else if (input[pointer] !== undefined) {\r\n return failure;\r\n }\r\n\r\n address[pieceIndex] = value;\r\n ++pieceIndex;\r\n }\r\n\r\n if (compress !== null) {\r\n let swaps = pieceIndex - compress;\r\n pieceIndex = 7;\r\n while (pieceIndex !== 0 && swaps > 0) {\r\n const temp = address[compress + swaps - 1];\r\n address[compress + swaps - 1] = address[pieceIndex];\r\n address[pieceIndex] = temp;\r\n --pieceIndex;\r\n --swaps;\r\n }\r\n } else if (compress === null && pieceIndex !== 8) {\r\n return failure;\r\n }\r\n\r\n return address;\r\n}\r\n\r\nfunction serializeIPv6(address) {\r\n let output = \"\";\r\n const seqResult = findLongestZeroSequence(address);\r\n const compress = seqResult.idx;\r\n let ignore0 = false;\r\n\r\n for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {\r\n if (ignore0 && address[pieceIndex] === 0) {\r\n continue;\r\n } else if (ignore0) {\r\n ignore0 = false;\r\n }\r\n\r\n if (compress === pieceIndex) {\r\n const separator = pieceIndex === 0 ? \"::\" : \":\";\r\n output += separator;\r\n ignore0 = true;\r\n continue;\r\n }\r\n\r\n output += address[pieceIndex].toString(16);\r\n\r\n if (pieceIndex !== 7) {\r\n output += \":\";\r\n }\r\n }\r\n\r\n return output;\r\n}\r\n\r\nfunction parseHost(input, isSpecialArg) {\r\n if (input[0] === \"[\") {\r\n if (input[input.length - 1] !== \"]\") {\r\n return failure;\r\n }\r\n\r\n return parseIPv6(input.substring(1, input.length - 1));\r\n }\r\n\r\n if (!isSpecialArg) {\r\n return parseOpaqueHost(input);\r\n }\r\n\r\n const domain = utf8PercentDecode(input);\r\n const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false);\r\n if (asciiDomain === null) {\r\n return failure;\r\n }\r\n\r\n if (containsForbiddenHostCodePoint(asciiDomain)) {\r\n return failure;\r\n }\r\n\r\n const ipv4Host = parseIPv4(asciiDomain);\r\n if (typeof ipv4Host === \"number\" || ipv4Host === failure) {\r\n return ipv4Host;\r\n }\r\n\r\n return asciiDomain;\r\n}\r\n\r\nfunction parseOpaqueHost(input) {\r\n if (containsForbiddenHostCodePointExcludingPercent(input)) {\r\n return failure;\r\n }\r\n\r\n let output = \"\";\r\n const decoded = punycode.ucs2.decode(input);\r\n for (let i = 0; i < decoded.length; ++i) {\r\n output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);\r\n }\r\n return output;\r\n}\r\n\r\nfunction findLongestZeroSequence(arr) {\r\n let maxIdx = null;\r\n let maxLen = 1; // only find elements > 1\r\n let currStart = null;\r\n let currLen = 0;\r\n\r\n for (let i = 0; i < arr.length; ++i) {\r\n if (arr[i] !== 0) {\r\n if (currLen > maxLen) {\r\n maxIdx = currStart;\r\n maxLen = currLen;\r\n }\r\n\r\n currStart = null;\r\n currLen = 0;\r\n } else {\r\n if (currStart === null) {\r\n currStart = i;\r\n }\r\n ++currLen;\r\n }\r\n }\r\n\r\n // if trailing zeros\r\n if (currLen > maxLen) {\r\n maxIdx = currStart;\r\n maxLen = currLen;\r\n }\r\n\r\n return {\r\n idx: maxIdx,\r\n len: maxLen\r\n };\r\n}\r\n\r\nfunction serializeHost(host) {\r\n if (typeof host === \"number\") {\r\n return serializeIPv4(host);\r\n }\r\n\r\n // IPv6 serializer\r\n if (host instanceof Array) {\r\n return \"[\" + serializeIPv6(host) + \"]\";\r\n }\r\n\r\n return host;\r\n}\r\n\r\nfunction trimControlChars(url) {\r\n return url.replace(/^[\\u0000-\\u001F\\u0020]+|[\\u0000-\\u001F\\u0020]+$/g, \"\");\r\n}\r\n\r\nfunction trimTabAndNewline(url) {\r\n return url.replace(/\\u0009|\\u000A|\\u000D/g, \"\");\r\n}\r\n\r\nfunction shortenPath(url) {\r\n const path = url.path;\r\n if (path.length === 0) {\r\n return;\r\n }\r\n if (url.scheme === \"file\" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {\r\n return;\r\n }\r\n\r\n path.pop();\r\n}\r\n\r\nfunction includesCredentials(url) {\r\n return url.username !== \"\" || url.password !== \"\";\r\n}\r\n\r\nfunction cannotHaveAUsernamePasswordPort(url) {\r\n return url.host === null || url.host === \"\" || url.cannotBeABaseURL || url.scheme === \"file\";\r\n}\r\n\r\nfunction isNormalizedWindowsDriveLetter(string) {\r\n return /^[A-Za-z]:$/.test(string);\r\n}\r\n\r\nfunction URLStateMachine(input, base, encodingOverride, url, stateOverride) {\r\n this.pointer = 0;\r\n this.input = input;\r\n this.base = base || null;\r\n this.encodingOverride = encodingOverride || \"utf-8\";\r\n this.stateOverride = stateOverride;\r\n this.url = url;\r\n this.failure = false;\r\n this.parseError = false;\r\n\r\n if (!this.url) {\r\n this.url = {\r\n scheme: \"\",\r\n username: \"\",\r\n password: \"\",\r\n host: null,\r\n port: null,\r\n path: [],\r\n query: null,\r\n fragment: null,\r\n\r\n cannotBeABaseURL: false\r\n };\r\n\r\n const res = trimControlChars(this.input);\r\n if (res !== this.input) {\r\n this.parseError = true;\r\n }\r\n this.input = res;\r\n }\r\n\r\n const res = trimTabAndNewline(this.input);\r\n if (res !== this.input) {\r\n this.parseError = true;\r\n }\r\n this.input = res;\r\n\r\n this.state = stateOverride || \"scheme start\";\r\n\r\n this.buffer = \"\";\r\n this.atFlag = false;\r\n this.arrFlag = false;\r\n this.passwordTokenSeenFlag = false;\r\n\r\n this.input = punycode.ucs2.decode(this.input);\r\n\r\n for (; this.pointer <= this.input.length; ++this.pointer) {\r\n const c = this.input[this.pointer];\r\n const cStr = isNaN(c) ? undefined : String.fromCodePoint(c);\r\n\r\n // exec state machine\r\n const ret = this[\"parse \" + this.state](c, cStr);\r\n if (!ret) {\r\n break; // terminate algorithm\r\n } else if (ret === failure) {\r\n this.failure = true;\r\n break;\r\n }\r\n }\r\n}\r\n\r\nURLStateMachine.prototype[\"parse scheme start\"] = function parseSchemeStart(c, cStr) {\r\n if (isASCIIAlpha(c)) {\r\n this.buffer += cStr.toLowerCase();\r\n this.state = \"scheme\";\r\n } else if (!this.stateOverride) {\r\n this.state = \"no scheme\";\r\n --this.pointer;\r\n } else {\r\n this.parseError = true;\r\n return failure;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse scheme\"] = function parseScheme(c, cStr) {\r\n if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) {\r\n this.buffer += cStr.toLowerCase();\r\n } else if (c === 58) {\r\n if (this.stateOverride) {\r\n if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {\r\n return false;\r\n }\r\n\r\n if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {\r\n return false;\r\n }\r\n\r\n if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === \"file\") {\r\n return false;\r\n }\r\n\r\n if (this.url.scheme === \"file\" && (this.url.host === \"\" || this.url.host === null)) {\r\n return false;\r\n }\r\n }\r\n this.url.scheme = this.buffer;\r\n this.buffer = \"\";\r\n if (this.stateOverride) {\r\n return false;\r\n }\r\n if (this.url.scheme === \"file\") {\r\n if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {\r\n this.parseError = true;\r\n }\r\n this.state = \"file\";\r\n } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {\r\n this.state = \"special relative or authority\";\r\n } else if (isSpecial(this.url)) {\r\n this.state = \"special authority slashes\";\r\n } else if (this.input[this.pointer + 1] === 47) {\r\n this.state = \"path or authority\";\r\n ++this.pointer;\r\n } else {\r\n this.url.cannotBeABaseURL = true;\r\n this.url.path.push(\"\");\r\n this.state = \"cannot-be-a-base-URL path\";\r\n }\r\n } else if (!this.stateOverride) {\r\n this.buffer = \"\";\r\n this.state = \"no scheme\";\r\n this.pointer = -1;\r\n } else {\r\n this.parseError = true;\r\n return failure;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse no scheme\"] = function parseNoScheme(c) {\r\n if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) {\r\n return failure;\r\n } else if (this.base.cannotBeABaseURL && c === 35) {\r\n this.url.scheme = this.base.scheme;\r\n this.url.path = this.base.path.slice();\r\n this.url.query = this.base.query;\r\n this.url.fragment = \"\";\r\n this.url.cannotBeABaseURL = true;\r\n this.state = \"fragment\";\r\n } else if (this.base.scheme === \"file\") {\r\n this.state = \"file\";\r\n --this.pointer;\r\n } else {\r\n this.state = \"relative\";\r\n --this.pointer;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse special relative or authority\"] = function parseSpecialRelativeOrAuthority(c) {\r\n if (c === 47 && this.input[this.pointer + 1] === 47) {\r\n this.state = \"special authority ignore slashes\";\r\n ++this.pointer;\r\n } else {\r\n this.parseError = true;\r\n this.state = \"relative\";\r\n --this.pointer;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse path or authority\"] = function parsePathOrAuthority(c) {\r\n if (c === 47) {\r\n this.state = \"authority\";\r\n } else {\r\n this.state = \"path\";\r\n --this.pointer;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse relative\"] = function parseRelative(c) {\r\n this.url.scheme = this.base.scheme;\r\n if (isNaN(c)) {\r\n this.url.username = this.base.username;\r\n this.url.password = this.base.password;\r\n this.url.host = this.base.host;\r\n this.url.port = this.base.port;\r\n this.url.path = this.base.path.slice();\r\n this.url.query = this.base.query;\r\n } else if (c === 47) {\r\n this.state = \"relative slash\";\r\n } else if (c === 63) {\r\n this.url.username = this.base.username;\r\n this.url.password = this.base.password;\r\n this.url.host = this.base.host;\r\n this.url.port = this.base.port;\r\n this.url.path = this.base.path.slice();\r\n this.url.query = \"\";\r\n this.state = \"query\";\r\n } else if (c === 35) {\r\n this.url.username = this.base.username;\r\n this.url.password = this.base.password;\r\n this.url.host = this.base.host;\r\n this.url.port = this.base.port;\r\n this.url.path = this.base.path.slice();\r\n this.url.query = this.base.query;\r\n this.url.fragment = \"\";\r\n this.state = \"fragment\";\r\n } else if (isSpecial(this.url) && c === 92) {\r\n this.parseError = true;\r\n this.state = \"relative slash\";\r\n } else {\r\n this.url.username = this.base.username;\r\n this.url.password = this.base.password;\r\n this.url.host = this.base.host;\r\n this.url.port = this.base.port;\r\n this.url.path = this.base.path.slice(0, this.base.path.length - 1);\r\n\r\n this.state = \"path\";\r\n --this.pointer;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse relative slash\"] = function parseRelativeSlash(c) {\r\n if (isSpecial(this.url) && (c === 47 || c === 92)) {\r\n if (c === 92) {\r\n this.parseError = true;\r\n }\r\n this.state = \"special authority ignore slashes\";\r\n } else if (c === 47) {\r\n this.state = \"authority\";\r\n } else {\r\n this.url.username = this.base.username;\r\n this.url.password = this.base.password;\r\n this.url.host = this.base.host;\r\n this.url.port = this.base.port;\r\n this.state = \"path\";\r\n --this.pointer;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse special authority slashes\"] = function parseSpecialAuthoritySlashes(c) {\r\n if (c === 47 && this.input[this.pointer + 1] === 47) {\r\n this.state = \"special authority ignore slashes\";\r\n ++this.pointer;\r\n } else {\r\n this.parseError = true;\r\n this.state = \"special authority ignore slashes\";\r\n --this.pointer;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse special authority ignore slashes\"] = function parseSpecialAuthorityIgnoreSlashes(c) {\r\n if (c !== 47 && c !== 92) {\r\n this.state = \"authority\";\r\n --this.pointer;\r\n } else {\r\n this.parseError = true;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse authority\"] = function parseAuthority(c, cStr) {\r\n if (c === 64) {\r\n this.parseError = true;\r\n if (this.atFlag) {\r\n this.buffer = \"%40\" + this.buffer;\r\n }\r\n this.atFlag = true;\r\n\r\n // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars\r\n const len = countSymbols(this.buffer);\r\n for (let pointer = 0; pointer < len; ++pointer) {\r\n const codePoint = this.buffer.codePointAt(pointer);\r\n\r\n if (codePoint === 58 && !this.passwordTokenSeenFlag) {\r\n this.passwordTokenSeenFlag = true;\r\n continue;\r\n }\r\n const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);\r\n if (this.passwordTokenSeenFlag) {\r\n this.url.password += encodedCodePoints;\r\n } else {\r\n this.url.username += encodedCodePoints;\r\n }\r\n }\r\n this.buffer = \"\";\r\n } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||\r\n (isSpecial(this.url) && c === 92)) {\r\n if (this.atFlag && this.buffer === \"\") {\r\n this.parseError = true;\r\n return failure;\r\n }\r\n this.pointer -= countSymbols(this.buffer) + 1;\r\n this.buffer = \"\";\r\n this.state = \"host\";\r\n } else {\r\n this.buffer += cStr;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse hostname\"] =\r\nURLStateMachine.prototype[\"parse host\"] = function parseHostName(c, cStr) {\r\n if (this.stateOverride && this.url.scheme === \"file\") {\r\n --this.pointer;\r\n this.state = \"file host\";\r\n } else if (c === 58 && !this.arrFlag) {\r\n if (this.buffer === \"\") {\r\n this.parseError = true;\r\n return failure;\r\n }\r\n\r\n const host = parseHost(this.buffer, isSpecial(this.url));\r\n if (host === failure) {\r\n return failure;\r\n }\r\n\r\n this.url.host = host;\r\n this.buffer = \"\";\r\n this.state = \"port\";\r\n if (this.stateOverride === \"hostname\") {\r\n return false;\r\n }\r\n } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||\r\n (isSpecial(this.url) && c === 92)) {\r\n --this.pointer;\r\n if (isSpecial(this.url) && this.buffer === \"\") {\r\n this.parseError = true;\r\n return failure;\r\n } else if (this.stateOverride && this.buffer === \"\" &&\r\n (includesCredentials(this.url) || this.url.port !== null)) {\r\n this.parseError = true;\r\n return false;\r\n }\r\n\r\n const host = parseHost(this.buffer, isSpecial(this.url));\r\n if (host === failure) {\r\n return failure;\r\n }\r\n\r\n this.url.host = host;\r\n this.buffer = \"\";\r\n this.state = \"path start\";\r\n if (this.stateOverride) {\r\n return false;\r\n }\r\n } else {\r\n if (c === 91) {\r\n this.arrFlag = true;\r\n } else if (c === 93) {\r\n this.arrFlag = false;\r\n }\r\n this.buffer += cStr;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse port\"] = function parsePort(c, cStr) {\r\n if (isASCIIDigit(c)) {\r\n this.buffer += cStr;\r\n } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||\r\n (isSpecial(this.url) && c === 92) ||\r\n this.stateOverride) {\r\n if (this.buffer !== \"\") {\r\n const port = parseInt(this.buffer);\r\n if (port > Math.pow(2, 16) - 1) {\r\n this.parseError = true;\r\n return failure;\r\n }\r\n this.url.port = port === defaultPort(this.url.scheme) ? null : port;\r\n this.buffer = \"\";\r\n }\r\n if (this.stateOverride) {\r\n return false;\r\n }\r\n this.state = \"path start\";\r\n --this.pointer;\r\n } else {\r\n this.parseError = true;\r\n return failure;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nconst fileOtherwiseCodePoints = new Set([47, 92, 63, 35]);\r\n\r\nURLStateMachine.prototype[\"parse file\"] = function parseFile(c) {\r\n this.url.scheme = \"file\";\r\n\r\n if (c === 47 || c === 92) {\r\n if (c === 92) {\r\n this.parseError = true;\r\n }\r\n this.state = \"file slash\";\r\n } else if (this.base !== null && this.base.scheme === \"file\") {\r\n if (isNaN(c)) {\r\n this.url.host = this.base.host;\r\n this.url.path = this.base.path.slice();\r\n this.url.query = this.base.query;\r\n } else if (c === 63) {\r\n this.url.host = this.base.host;\r\n this.url.path = this.base.path.slice();\r\n this.url.query = \"\";\r\n this.state = \"query\";\r\n } else if (c === 35) {\r\n this.url.host = this.base.host;\r\n this.url.path = this.base.path.slice();\r\n this.url.query = this.base.query;\r\n this.url.fragment = \"\";\r\n this.state = \"fragment\";\r\n } else {\r\n if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points\r\n !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) ||\r\n (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points\r\n !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) {\r\n this.url.host = this.base.host;\r\n this.url.path = this.base.path.slice();\r\n shortenPath(this.url);\r\n } else {\r\n this.parseError = true;\r\n }\r\n\r\n this.state = \"path\";\r\n --this.pointer;\r\n }\r\n } else {\r\n this.state = \"path\";\r\n --this.pointer;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse file slash\"] = function parseFileSlash(c) {\r\n if (c === 47 || c === 92) {\r\n if (c === 92) {\r\n this.parseError = true;\r\n }\r\n this.state = \"file host\";\r\n } else {\r\n if (this.base !== null && this.base.scheme === \"file\") {\r\n if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {\r\n this.url.path.push(this.base.path[0]);\r\n } else {\r\n this.url.host = this.base.host;\r\n }\r\n }\r\n this.state = \"path\";\r\n --this.pointer;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse file host\"] = function parseFileHost(c, cStr) {\r\n if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) {\r\n --this.pointer;\r\n if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {\r\n this.parseError = true;\r\n this.state = \"path\";\r\n } else if (this.buffer === \"\") {\r\n this.url.host = \"\";\r\n if (this.stateOverride) {\r\n return false;\r\n }\r\n this.state = \"path start\";\r\n } else {\r\n let host = parseHost(this.buffer, isSpecial(this.url));\r\n if (host === failure) {\r\n return failure;\r\n }\r\n if (host === \"localhost\") {\r\n host = \"\";\r\n }\r\n this.url.host = host;\r\n\r\n if (this.stateOverride) {\r\n return false;\r\n }\r\n\r\n this.buffer = \"\";\r\n this.state = \"path start\";\r\n }\r\n } else {\r\n this.buffer += cStr;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse path start\"] = function parsePathStart(c) {\r\n if (isSpecial(this.url)) {\r\n if (c === 92) {\r\n this.parseError = true;\r\n }\r\n this.state = \"path\";\r\n\r\n if (c !== 47 && c !== 92) {\r\n --this.pointer;\r\n }\r\n } else if (!this.stateOverride && c === 63) {\r\n this.url.query = \"\";\r\n this.state = \"query\";\r\n } else if (!this.stateOverride && c === 35) {\r\n this.url.fragment = \"\";\r\n this.state = \"fragment\";\r\n } else if (c !== undefined) {\r\n this.state = \"path\";\r\n if (c !== 47) {\r\n --this.pointer;\r\n }\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse path\"] = function parsePath(c) {\r\n if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) ||\r\n (!this.stateOverride && (c === 63 || c === 35))) {\r\n if (isSpecial(this.url) && c === 92) {\r\n this.parseError = true;\r\n }\r\n\r\n if (isDoubleDot(this.buffer)) {\r\n shortenPath(this.url);\r\n if (c !== 47 && !(isSpecial(this.url) && c === 92)) {\r\n this.url.path.push(\"\");\r\n }\r\n } else if (isSingleDot(this.buffer) && c !== 47 &&\r\n !(isSpecial(this.url) && c === 92)) {\r\n this.url.path.push(\"\");\r\n } else if (!isSingleDot(this.buffer)) {\r\n if (this.url.scheme === \"file\" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {\r\n if (this.url.host !== \"\" && this.url.host !== null) {\r\n this.parseError = true;\r\n this.url.host = \"\";\r\n }\r\n this.buffer = this.buffer[0] + \":\";\r\n }\r\n this.url.path.push(this.buffer);\r\n }\r\n this.buffer = \"\";\r\n if (this.url.scheme === \"file\" && (c === undefined || c === 63 || c === 35)) {\r\n while (this.url.path.length > 1 && this.url.path[0] === \"\") {\r\n this.parseError = true;\r\n this.url.path.shift();\r\n }\r\n }\r\n if (c === 63) {\r\n this.url.query = \"\";\r\n this.state = \"query\";\r\n }\r\n if (c === 35) {\r\n this.url.fragment = \"\";\r\n this.state = \"fragment\";\r\n }\r\n } else {\r\n // TODO: If c is not a URL code point and not \"%\", parse error.\r\n\r\n if (c === 37 &&\r\n (!isASCIIHex(this.input[this.pointer + 1]) ||\r\n !isASCIIHex(this.input[this.pointer + 2]))) {\r\n this.parseError = true;\r\n }\r\n\r\n this.buffer += percentEncodeChar(c, isPathPercentEncode);\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse cannot-be-a-base-URL path\"] = function parseCannotBeABaseURLPath(c) {\r\n if (c === 63) {\r\n this.url.query = \"\";\r\n this.state = \"query\";\r\n } else if (c === 35) {\r\n this.url.fragment = \"\";\r\n this.state = \"fragment\";\r\n } else {\r\n // TODO: Add: not a URL code point\r\n if (!isNaN(c) && c !== 37) {\r\n this.parseError = true;\r\n }\r\n\r\n if (c === 37 &&\r\n (!isASCIIHex(this.input[this.pointer + 1]) ||\r\n !isASCIIHex(this.input[this.pointer + 2]))) {\r\n this.parseError = true;\r\n }\r\n\r\n if (!isNaN(c)) {\r\n this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode);\r\n }\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse query\"] = function parseQuery(c, cStr) {\r\n if (isNaN(c) || (!this.stateOverride && c === 35)) {\r\n if (!isSpecial(this.url) || this.url.scheme === \"ws\" || this.url.scheme === \"wss\") {\r\n this.encodingOverride = \"utf-8\";\r\n }\r\n\r\n const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead\r\n for (let i = 0; i < buffer.length; ++i) {\r\n if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 ||\r\n buffer[i] === 0x3C || buffer[i] === 0x3E) {\r\n this.url.query += percentEncode(buffer[i]);\r\n } else {\r\n this.url.query += String.fromCodePoint(buffer[i]);\r\n }\r\n }\r\n\r\n this.buffer = \"\";\r\n if (c === 35) {\r\n this.url.fragment = \"\";\r\n this.state = \"fragment\";\r\n }\r\n } else {\r\n // TODO: If c is not a URL code point and not \"%\", parse error.\r\n if (c === 37 &&\r\n (!isASCIIHex(this.input[this.pointer + 1]) ||\r\n !isASCIIHex(this.input[this.pointer + 2]))) {\r\n this.parseError = true;\r\n }\r\n\r\n this.buffer += cStr;\r\n }\r\n\r\n return true;\r\n};\r\n\r\nURLStateMachine.prototype[\"parse fragment\"] = function parseFragment(c) {\r\n if (isNaN(c)) { // do nothing\r\n } else if (c === 0x0) {\r\n this.parseError = true;\r\n } else {\r\n // TODO: If c is not a URL code point and not \"%\", parse error.\r\n if (c === 37 &&\r\n (!isASCIIHex(this.input[this.pointer + 1]) ||\r\n !isASCIIHex(this.input[this.pointer + 2]))) {\r\n this.parseError = true;\r\n }\r\n\r\n this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode);\r\n }\r\n\r\n return true;\r\n};\r\n\r\nfunction serializeURL(url, excludeFragment) {\r\n let output = url.scheme + \":\";\r\n if (url.host !== null) {\r\n output += \"//\";\r\n\r\n if (url.username !== \"\" || url.password !== \"\") {\r\n output += url.username;\r\n if (url.password !== \"\") {\r\n output += \":\" + url.password;\r\n }\r\n output += \"@\";\r\n }\r\n\r\n output += serializeHost(url.host);\r\n\r\n if (url.port !== null) {\r\n output += \":\" + url.port;\r\n }\r\n } else if (url.host === null && url.scheme === \"file\") {\r\n output += \"//\";\r\n }\r\n\r\n if (url.cannotBeABaseURL) {\r\n output += url.path[0];\r\n } else {\r\n for (const string of url.path) {\r\n output += \"/\" + string;\r\n }\r\n }\r\n\r\n if (url.query !== null) {\r\n output += \"?\" + url.query;\r\n }\r\n\r\n if (!excludeFragment && url.fragment !== null) {\r\n output += \"#\" + url.fragment;\r\n }\r\n\r\n return output;\r\n}\r\n\r\nfunction serializeOrigin(tuple) {\r\n let result = tuple.scheme + \"://\";\r\n result += serializeHost(tuple.host);\r\n\r\n if (tuple.port !== null) {\r\n result += \":\" + tuple.port;\r\n }\r\n\r\n return result;\r\n}\r\n\r\nmodule.exports.serializeURL = serializeURL;\r\n\r\nmodule.exports.serializeURLOrigin = function (url) {\r\n // https://url.spec.whatwg.org/#concept-url-origin\r\n switch (url.scheme) {\r\n case \"blob\":\r\n try {\r\n return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0]));\r\n } catch (e) {\r\n // serializing an opaque origin returns \"null\"\r\n return \"null\";\r\n }\r\n case \"ftp\":\r\n case \"gopher\":\r\n case \"http\":\r\n case \"https\":\r\n case \"ws\":\r\n case \"wss\":\r\n return serializeOrigin({\r\n scheme: url.scheme,\r\n host: url.host,\r\n port: url.port\r\n });\r\n case \"file\":\r\n // spec says \"exercise to the reader\", chrome says \"file://\"\r\n return \"file://\";\r\n default:\r\n // serializing an opaque origin returns \"null\"\r\n return \"null\";\r\n }\r\n};\r\n\r\nmodule.exports.basicURLParse = function (input, options) {\r\n if (options === undefined) {\r\n options = {};\r\n }\r\n\r\n const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);\r\n if (usm.failure) {\r\n return \"failure\";\r\n }\r\n\r\n return usm.url;\r\n};\r\n\r\nmodule.exports.setTheUsername = function (url, username) {\r\n url.username = \"\";\r\n const decoded = punycode.ucs2.decode(username);\r\n for (let i = 0; i < decoded.length; ++i) {\r\n url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode);\r\n }\r\n};\r\n\r\nmodule.exports.setThePassword = function (url, password) {\r\n url.password = \"\";\r\n const decoded = punycode.ucs2.decode(password);\r\n for (let i = 0; i < decoded.length; ++i) {\r\n url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode);\r\n }\r\n};\r\n\r\nmodule.exports.serializeHost = serializeHost;\r\n\r\nmodule.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;\r\n\r\nmodule.exports.serializeInteger = function (integer) {\r\n return String(integer);\r\n};\r\n\r\nmodule.exports.parseURL = function (input, options) {\r\n if (options === undefined) {\r\n options = {};\r\n }\r\n\r\n // We don't handle blobs, so this just delegates:\r\n return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });\r\n};\r\n","\"use strict\";\n\nmodule.exports.mixin = function mixin(target, source) {\n const keys = Object.getOwnPropertyNames(source);\n for (let i = 0; i < keys.length; ++i) {\n Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));\n }\n};\n\nmodule.exports.wrapperSymbol = Symbol(\"wrapper\");\nmodule.exports.implSymbol = Symbol(\"impl\");\n\nmodule.exports.wrapperForImpl = function (impl) {\n return impl[module.exports.wrapperSymbol];\n};\n\nmodule.exports.implForWrapper = function (wrapper) {\n return wrapper[module.exports.implSymbol];\n};\n\n","/**\n * Advanced Encryption Standard (AES) implementation.\n *\n * This implementation is based on the public domain library 'jscrypto' which\n * was written by:\n *\n * Emily Stark (estark@stanford.edu)\n * Mike Hamburg (mhamburg@stanford.edu)\n * Dan Boneh (dabo@cs.stanford.edu)\n *\n * Parts of this code are based on the OpenSSL implementation of AES:\n * http://www.openssl.org\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* AES API */\nmodule.exports = forge.aes = forge.aes || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new AES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the AES algorithm object.\n */\nforge.aes.Algorithm = function(name, mode) {\n if(!init) {\n initialize();\n }\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 16,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this AES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.aes.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = options.key;\n var tmp;\n\n /* Note: The key may be a string of bytes, an array of bytes, a byte\n buffer, or an array of 32-bit integers. If the key is in bytes, then\n it must be 16, 24, or 32 bytes in length. If it is in 32-bit\n integers, it must be 4, 6, or 8 integers long. */\n\n if(typeof key === 'string' &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key) &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key integer array into byte buffer\n tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // convert key byte buffer into 32-bit integer array\n if(!forge.util.isArray(key)) {\n tmp = key;\n key = [];\n\n // key lengths of 16, 24, 32 bytes allowed\n var len = tmp.length();\n if(len === 16 || len === 24 || len === 32) {\n len = len >>> 2;\n for(var i = 0; i < len; ++i) {\n key.push(tmp.getInt32());\n }\n }\n }\n\n // key must be an array of 32-bit integers by now\n if(!forge.util.isArray(key) ||\n !(key.length === 4 || key.length === 6 || key.length === 8)) {\n throw new Error('Invalid key parameter.');\n }\n\n // encryption operation is always used for these modes\n var mode = this.mode.name;\n var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);\n\n // do key expansion\n this._w = _expandKey(key, options.decrypt && !encryptOp);\n this._init = true;\n};\n\n/**\n * Expands a key. Typically only used for testing.\n *\n * @param key the symmetric key to expand, as an array of 32-bit words.\n * @param decrypt true to expand for decryption, false for encryption.\n *\n * @return the expanded key.\n */\nforge.aes._expandKey = function(key, decrypt) {\n if(!init) {\n initialize();\n }\n return _expandKey(key, decrypt);\n};\n\n/**\n * Updates a single block. Typically only used for testing.\n *\n * @param w the expanded key to use.\n * @param input an array of block-size 32-bit words.\n * @param output an array of block-size 32-bit words.\n * @param decrypt true to decrypt, false to encrypt.\n */\nforge.aes._updateBlock = _updateBlock;\n\n/** Register AES algorithms **/\n\nregisterAlgorithm('AES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('AES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('AES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('AES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('AES-CTR', forge.cipher.modes.ctr);\nregisterAlgorithm('AES-GCM', forge.cipher.modes.gcm);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.aes.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** AES implementation **/\n\nvar init = false; // not yet initialized\nvar Nb = 4; // number of words comprising the state (AES = 4)\nvar sbox; // non-linear substitution table used in key expansion\nvar isbox; // inversion of sbox\nvar rcon; // round constant word array\nvar mix; // mix-columns table\nvar imix; // inverse mix-columns table\n\n/**\n * Performs initialization, ie: precomputes tables to optimize for speed.\n *\n * One way to understand how AES works is to imagine that 'addition' and\n * 'multiplication' are interfaces that require certain mathematical\n * properties to hold true (ie: they are associative) but they might have\n * different implementations and produce different kinds of results ...\n * provided that their mathematical properties remain true. AES defines\n * its own methods of addition and multiplication but keeps some important\n * properties the same, ie: associativity and distributivity. The\n * explanation below tries to shed some light on how AES defines addition\n * and multiplication of bytes and 32-bit words in order to perform its\n * encryption and decryption algorithms.\n *\n * The basics:\n *\n * The AES algorithm views bytes as binary representations of polynomials\n * that have either 1 or 0 as the coefficients. It defines the addition\n * or subtraction of two bytes as the XOR operation. It also defines the\n * multiplication of two bytes as a finite field referred to as GF(2^8)\n * (Note: 'GF' means \"Galois Field\" which is a field that contains a finite\n * number of elements so GF(2^8) has 256 elements).\n *\n * This means that any two bytes can be represented as binary polynomials;\n * when they multiplied together and modularly reduced by an irreducible\n * polynomial of the 8th degree, the results are the field GF(2^8). The\n * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.\n * This multiplication is associative with 0x01 as the identity:\n *\n * (b * 0x01 = GF(b, 0x01) = b).\n *\n * The operation GF(b, 0x02) can be performed at the byte level by left\n * shifting b once and then XOR'ing it (to perform the modular reduction)\n * with 0x11b if b is >= 128. Repeated application of the multiplication\n * of 0x02 can be used to implement the multiplication of any two bytes.\n *\n * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can\n * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these\n * factors can each be multiplied by 0x57 and then added together. To do\n * the multiplication, values for 0x57 multiplied by each of these 3 factors\n * can be precomputed and stored in a table. To add them, the values from\n * the table are XOR'd together.\n *\n * AES also defines addition and multiplication of words, that is 4-byte\n * numbers represented as polynomials of 3 degrees where the coefficients\n * are the values of the bytes.\n *\n * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.\n *\n * Addition is performed by XOR'ing like powers of x. Multiplication\n * is performed in two steps, the first is an algebriac expansion as\n * you would do normally (where addition is XOR). But the result is\n * a polynomial larger than 3 degrees and thus it cannot fit in a word. So\n * next the result is modularly reduced by an AES-specific polynomial of\n * degree 4 which will always produce a polynomial of less than 4 degrees\n * such that it will fit in a word. In AES, this polynomial is x^4 + 1.\n *\n * The modular product of two polynomials 'a' and 'b' is thus:\n *\n * d(x) = d3x^3 + d2x^2 + d1x + d0\n * with\n * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)\n * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)\n * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)\n * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)\n *\n * As a matrix:\n *\n * [d0] = [a0 a3 a2 a1][b0]\n * [d1] [a1 a0 a3 a2][b1]\n * [d2] [a2 a1 a0 a3][b2]\n * [d3] [a3 a2 a1 a0][b3]\n *\n * Special polynomials defined by AES (0x02 == {02}):\n * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}\n * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.\n *\n * These polynomials are used in the MixColumns() and InverseMixColumns()\n * operations, respectively, to cause each element in the state to affect\n * the output (referred to as diffusing).\n *\n * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the\n * polynomial x3.\n *\n * The ShiftRows() method modifies the last 3 rows in the state (where\n * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.\n * The 1st byte in the second row is moved to the end of the row. The 1st\n * and 2nd bytes in the third row are moved to the end of the row. The 1st,\n * 2nd, and 3rd bytes are moved in the fourth row.\n *\n * More details on how AES arithmetic works:\n *\n * In the polynomial representation of binary numbers, XOR performs addition\n * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)\n * corresponds with the multiplication of polynomials modulo an irreducible\n * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply\n * polynomial 'a' with polynomial 'b' and then do a modular reduction by\n * an AES-specific irreducible polynomial of degree 8.\n *\n * A polynomial is irreducible if its only divisors are one and itself. For\n * the AES algorithm, this irreducible polynomial is:\n *\n * m(x) = x^8 + x^4 + x^3 + x + 1,\n *\n * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:\n * 100011011 = 283 = 0x11b.\n *\n * For example, GF(0x57, 0x83) = 0xc1 because\n *\n * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1\n * 0x85 = 131 = 10000101 = x^7 + x + 1\n *\n * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)\n * = x^13 + x^11 + x^9 + x^8 + x^7 +\n * x^7 + x^5 + x^3 + x^2 + x +\n * x^6 + x^4 + x^2 + x + 1\n * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y\n * y modulo (x^8 + x^4 + x^3 + x + 1)\n * = x^7 + x^6 + 1.\n *\n * The modular reduction by m(x) guarantees the result will be a binary\n * polynomial of less than degree 8, so that it can fit in a byte.\n *\n * The operation to multiply a binary polynomial b with x (the polynomial\n * x in binary representation is 00000010) is:\n *\n * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1\n *\n * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the\n * most significant bit is 0 in b) then the result is already reduced. If\n * it is 1, then we can reduce it by subtracting m(x) via an XOR.\n *\n * It follows that multiplication by x (00000010 or 0x02) can be implemented\n * by performing a left shift followed by a conditional bitwise XOR with\n * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by\n * higher powers of x can be implemented by repeated application of xtime().\n *\n * By adding intermediate results, multiplication by any constant can be\n * implemented. For instance:\n *\n * GF(0x57, 0x13) = 0xfe because:\n *\n * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)\n *\n * Note: We XOR with 0x11b instead of 0x1b because in javascript our\n * datatype for b can be larger than 1 byte, so a left shift will not\n * automatically eliminate bits that overflow a byte ... by XOR'ing the\n * overflow bit with 1 (the extra one from 0x11b) we zero it out.\n *\n * GF(0x57, 0x02) = xtime(0x57) = 0xae\n * GF(0x57, 0x04) = xtime(0xae) = 0x47\n * GF(0x57, 0x08) = xtime(0x47) = 0x8e\n * GF(0x57, 0x10) = xtime(0x8e) = 0x07\n *\n * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))\n *\n * And by the distributive property (since XOR is addition and GF() is\n * multiplication):\n *\n * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)\n * = 0x57 ^ 0xae ^ 0x07\n * = 0xfe.\n */\nfunction initialize() {\n init = true;\n\n /* Populate the Rcon table. These are the values given by\n [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)\n in the field of GF(2^8), where i starts at 1.\n\n rcon[0] = [0x00, 0x00, 0x00, 0x00]\n rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1\n rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2\n ...\n rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B\n rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36\n\n We only store the first byte because it is the only one used.\n */\n rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];\n\n // compute xtime table which maps i onto GF(i, 0x02)\n var xtime = new Array(256);\n for(var i = 0; i < 128; ++i) {\n xtime[i] = i << 1;\n xtime[i + 128] = (i + 128) << 1 ^ 0x11B;\n }\n\n // compute all other tables\n sbox = new Array(256);\n isbox = new Array(256);\n mix = new Array(4);\n imix = new Array(4);\n for(var i = 0; i < 4; ++i) {\n mix[i] = new Array(256);\n imix[i] = new Array(256);\n }\n var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;\n for(var i = 0; i < 256; ++i) {\n /* We need to generate the SubBytes() sbox and isbox tables so that\n we can perform byte substitutions. This requires us to traverse\n all of the elements in GF, find their multiplicative inverses,\n and apply to each the following affine transformation:\n\n bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^\n b(i + 7) mod 8 ^ ci\n for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the\n ith bit of a byte c with the value {63} or {01100011}.\n\n It is possible to traverse every possible value in a Galois field\n using what is referred to as a 'generator'. There are many\n generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully\n traverse GF we iterate 255 times, multiplying by our generator\n each time.\n\n On each iteration we can determine the multiplicative inverse for\n the current element.\n\n Suppose there is an element in GF 'e'. For a given generator 'g',\n e = g^x. The multiplicative inverse of e is g^(255 - x). It turns\n out that if use the inverse of a generator as another generator\n it will produce all of the corresponding multiplicative inverses\n at the same time. For this reason, we choose 5 as our inverse\n generator because it only requires 2 multiplies and 1 add and its\n inverse, 82, requires relatively few operations as well.\n\n In order to apply the affine transformation, the multiplicative\n inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a\n bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and\n 'x'. Then 's' is left shifted and the high bit of 's' is made the\n low bit. The resulting value is stored in 's'. Then 'x' is XOR'd\n with 's' and stored in 'x'. On each subsequent iteration the same\n operation is performed. When 4 iterations are complete, 'x' is\n XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.\n For example:\n\n s = 01000001\n x = 01000001\n\n iteration 1: s = 10000010, x ^= s\n iteration 2: s = 00000101, x ^= s\n iteration 3: s = 00001010, x ^= s\n iteration 4: s = 00010100, x ^= s\n x ^= 0x63\n\n This can be done with a loop where s = (s << 1) | (s >> 7). However,\n it can also be done by using a single 16-bit (in this case 32-bit)\n number 'sx'. Since XOR is an associative operation, we can set 'sx'\n to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.\n The most significant bits will flow into the high 8 bit positions\n and be correctly XOR'd with one another. All that remains will be\n to cycle the high 8 bits by XOR'ing them all with the lower 8 bits\n afterwards.\n\n At the same time we're populating sbox and isbox we can precompute\n the multiplication we'll need to do to do MixColumns() later.\n */\n\n // apply affine transformation\n sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);\n sx = (sx >> 8) ^ (sx & 255) ^ 0x63;\n\n // update tables\n sbox[e] = sx;\n isbox[sx] = e;\n\n /* Mixing columns is done using matrix multiplication. The columns\n that are to be mixed are each a single word in the current state.\n The state has Nb columns (4 columns). Therefore each column is a\n 4 byte word. So to mix the columns in a single column 'c' where\n its rows are r0, r1, r2, and r3, we use the following matrix\n multiplication:\n\n [2 3 1 1]*[r0,c]=[r'0,c]\n [1 2 3 1] [r1,c] [r'1,c]\n [1 1 2 3] [r2,c] [r'2,c]\n [3 1 1 2] [r3,c] [r'3,c]\n\n r0, r1, r2, and r3 are each 1 byte of one of the words in the\n state (a column). To do matrix multiplication for each mixed\n column c' we multiply the corresponding row from the left matrix\n with the corresponding column from the right matrix. In total, we\n get 4 equations:\n\n r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c\n r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c\n r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c\n r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c\n\n As usual, the multiplication is as previously defined and the\n addition is XOR. In order to optimize mixing columns we can store\n the multiplication results in tables. If you think of the whole\n column as a word (it might help to visualize by mentally rotating\n the equations above by counterclockwise 90 degrees) then you can\n see that it would be useful to map the multiplications performed on\n each byte (r0, r1, r2, r3) onto a word as well. For instance, we\n could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the\n highest 8 bits and 3*r0 in the lowest 8 bits (with the other two\n respectively in the middle). This means that a table can be\n constructed that uses r0 as an index to the word. We can do the\n same with r1, r2, and r3, creating a total of 4 tables.\n\n To construct a full c', we can just look up each byte of c in\n their respective tables and XOR the results together.\n\n Also, to build each table we only have to calculate the word\n for 2,1,1,3 for every byte ... which we can do on each iteration\n of this loop since we will iterate over every byte. After we have\n calculated 2,1,1,3 we can get the results for the other tables\n by cycling the byte at the end to the beginning. For instance\n we can take the result of table 2,1,1,3 and produce table 3,2,1,1\n by moving the right most byte to the left most position just like\n how you can imagine the 3 moved out of 2,1,1,3 and to the front\n to produce 3,2,1,1.\n\n There is another optimization in that the same multiples of\n the current element we need in order to advance our generator\n to the next iteration can be reused in performing the 2,1,1,3\n calculation. We also calculate the inverse mix column tables,\n with e,9,d,b being the inverse of 2,1,1,3.\n\n When we're done, and we need to actually mix columns, the first\n byte of each state word should be put through mix[0] (2,1,1,3),\n the second through mix[1] (3,2,1,1) and so forth. Then they should\n be XOR'd together to produce the fully mixed column.\n */\n\n // calculate mix and imix table values\n sx2 = xtime[sx];\n e2 = xtime[e];\n e4 = xtime[e2];\n e8 = xtime[e4];\n me =\n (sx2 << 24) ^ // 2\n (sx << 16) ^ // 1\n (sx << 8) ^ // 1\n (sx ^ sx2); // 3\n ime =\n (e2 ^ e4 ^ e8) << 24 ^ // E (14)\n (e ^ e8) << 16 ^ // 9\n (e ^ e4 ^ e8) << 8 ^ // D (13)\n (e ^ e2 ^ e8); // B (11)\n // produce each of the mix tables by rotating the 2,1,1,3 value\n for(var n = 0; n < 4; ++n) {\n mix[n][e] = me;\n imix[n][sx] = ime;\n // cycle the right most byte to the left most position\n // ie: 2,1,1,3 becomes 3,2,1,1\n me = me << 24 | me >>> 8;\n ime = ime << 24 | ime >>> 8;\n }\n\n // get next element and inverse\n if(e === 0) {\n // 1 is the inverse of 1\n e = ei = 1;\n } else {\n // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)\n // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)\n e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];\n ei ^= xtime[xtime[ei]];\n }\n }\n}\n\n/**\n * Generates a key schedule using the AES key expansion algorithm.\n *\n * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion\n * routine to generate a key schedule. The Key Expansion generates a total\n * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,\n * and each of the Nr rounds requires Nb words of key data. The resulting\n * key schedule consists of a linear array of 4-byte words, denoted [wi ],\n * with i in the range 0 <= i < Nb(Nr + 1).\n *\n * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)\n * AES-128 (Nb=4, Nk=4, Nr=10)\n * AES-192 (Nb=4, Nk=6, Nr=12)\n * AES-256 (Nb=4, Nk=8, Nr=14)\n * Note: Nr=Nk+6.\n *\n * Nb is the number of columns (32-bit words) comprising the State (or\n * number of bytes in a block). For AES, Nb=4.\n *\n * @param key the key to schedule (as an array of 32-bit words).\n * @param decrypt true to modify the key schedule to decrypt, false not to.\n *\n * @return the generated key schedule.\n */\nfunction _expandKey(key, decrypt) {\n // copy the key's words to initialize the key schedule\n var w = key.slice(0);\n\n /* RotWord() will rotate a word, moving the first byte to the last\n byte's position (shifting the other bytes left).\n\n We will be getting the value of Rcon at i / Nk. 'i' will iterate\n from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in\n a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from\n 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will\n increase by 1. We use a counter iNk to keep track of this.\n */\n\n // go through the rounds expanding the key\n var temp, iNk = 1;\n var Nk = w.length;\n var Nr1 = Nk + 6 + 1;\n var end = Nb * Nr1;\n for(var i = Nk; i < end; ++i) {\n temp = w[i - 1];\n if(i % Nk === 0) {\n // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]\n temp =\n sbox[temp >>> 16 & 255] << 24 ^\n sbox[temp >>> 8 & 255] << 16 ^\n sbox[temp & 255] << 8 ^\n sbox[temp >>> 24] ^ (rcon[iNk] << 24);\n iNk++;\n } else if(Nk > 6 && (i % Nk === 4)) {\n // temp = SubWord(temp)\n temp =\n sbox[temp >>> 24] << 24 ^\n sbox[temp >>> 16 & 255] << 16 ^\n sbox[temp >>> 8 & 255] << 8 ^\n sbox[temp & 255];\n }\n w[i] = w[i - Nk] ^ temp;\n }\n\n /* When we are updating a cipher block we always use the code path for\n encryption whether we are decrypting or not (to shorten code and\n simplify the generation of look up tables). However, because there\n are differences in the decryption algorithm, other than just swapping\n in different look up tables, we must transform our key schedule to\n account for these changes:\n\n 1. The decryption algorithm gets its key rounds in reverse order.\n 2. The decryption algorithm adds the round key before mixing columns\n instead of afterwards.\n\n We don't need to modify our key schedule to handle the first case,\n we can just traverse the key schedule in reverse order when decrypting.\n\n The second case requires a little work.\n\n The tables we built for performing rounds will take an input and then\n perform SubBytes() and MixColumns() or, for the decrypt version,\n InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires\n us to AddRoundKey() before InvMixColumns(). This means we'll need to\n apply some transformations to the round key to inverse-mix its columns\n so they'll be correct for moving AddRoundKey() to after the state has\n had its columns inverse-mixed.\n\n To inverse-mix the columns of the state when we're decrypting we use a\n lookup table that will apply InvSubBytes() and InvMixColumns() at the\n same time. However, the round key's bytes are not inverse-substituted\n in the decryption algorithm. To get around this problem, we can first\n substitute the bytes in the round key so that when we apply the\n transformation via the InvSubBytes()+InvMixColumns() table, it will\n undo our substitution leaving us with the original value that we\n want -- and then inverse-mix that value.\n\n This change will correctly alter our key schedule so that we can XOR\n each round key with our already transformed decryption state. This\n allows us to use the same code path as the encryption algorithm.\n\n We make one more change to the decryption key. Since the decryption\n algorithm runs in reverse from the encryption algorithm, we reverse\n the order of the round keys to avoid having to iterate over the key\n schedule backwards when running the encryption algorithm later in\n decryption mode. In addition to reversing the order of the round keys,\n we also swap each round key's 2nd and 4th rows. See the comments\n section where rounds are performed for more details about why this is\n done. These changes are done inline with the other substitution\n described above.\n */\n if(decrypt) {\n var tmp;\n var m0 = imix[0];\n var m1 = imix[1];\n var m2 = imix[2];\n var m3 = imix[3];\n var wnew = w.slice(0);\n end = w.length;\n for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {\n // do not sub the first or last round key (round keys are Nb\n // words) as no column mixing is performed before they are added,\n // but do change the key order\n if(i === 0 || i === (end - Nb)) {\n wnew[i] = w[wi];\n wnew[i + 1] = w[wi + 3];\n wnew[i + 2] = w[wi + 2];\n wnew[i + 3] = w[wi + 1];\n } else {\n // substitute each round key byte because the inverse-mix\n // table will inverse-substitute it (effectively cancel the\n // substitution because round key bytes aren't sub'd in\n // decryption mode) and swap indexes 3 and 1\n for(var n = 0; n < Nb; ++n) {\n tmp = w[wi + n];\n wnew[i + (3&-n)] =\n m0[sbox[tmp >>> 24]] ^\n m1[sbox[tmp >>> 16 & 255]] ^\n m2[sbox[tmp >>> 8 & 255]] ^\n m3[sbox[tmp & 255]];\n }\n }\n }\n w = wnew;\n }\n\n return w;\n}\n\n/**\n * Updates a single block (16 bytes) using AES. The update will either\n * encrypt or decrypt the block.\n *\n * @param w the key schedule.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(w, input, output, decrypt) {\n /*\n Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[0, Nb-1])\n for round = 1 step 1 to Nr-1\n SubBytes(state)\n ShiftRows(state)\n MixColumns(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n end for\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n out = state\n end\n\n InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n for round = Nr-1 step -1 downto 1\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n InvMixColumns(state)\n end for\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n out = state\n end\n */\n\n // Encrypt: AddRoundKey(state, w[0, Nb-1])\n // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n var Nr = w.length / 4 - 1;\n var m0, m1, m2, m3, sub;\n if(decrypt) {\n m0 = imix[0];\n m1 = imix[1];\n m2 = imix[2];\n m3 = imix[3];\n sub = isbox;\n } else {\n m0 = mix[0];\n m1 = mix[1];\n m2 = mix[2];\n m3 = mix[3];\n sub = sbox;\n }\n var a, b, c, d, a2, b2, c2;\n a = input[0] ^ w[0];\n b = input[decrypt ? 3 : 1] ^ w[1];\n c = input[2] ^ w[2];\n d = input[decrypt ? 1 : 3] ^ w[3];\n var i = 3;\n\n /* In order to share code we follow the encryption algorithm when both\n encrypting and decrypting. To account for the changes required in the\n decryption algorithm, we use different lookup tables when decrypting\n and use a modified key schedule to account for the difference in the\n order of transformations applied when performing rounds. We also get\n key rounds in reverse order (relative to encryption). */\n for(var round = 1; round < Nr; ++round) {\n /* As described above, we'll be using table lookups to perform the\n column mixing. Each column is stored as a word in the state (the\n array 'input' has one column as a word at each index). In order to\n mix a column, we perform these transformations on each row in c,\n which is 1 byte in each word. The new column for c0 is c'0:\n\n m0 m1 m2 m3\n r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0\n r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0\n r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0\n r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0\n\n So using mix tables where c0 is a word with r0 being its upper\n 8 bits and r3 being its lower 8 bits:\n\n m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]\n ...\n m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]\n\n Therefore to mix the columns in each word in the state we\n do the following (& 255 omitted for brevity):\n c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n\n However, before mixing, the algorithm requires us to perform\n ShiftRows(). The ShiftRows() transformation cyclically shifts the\n last 3 rows of the state over different offsets. The first row\n (r = 0) is not shifted.\n\n s'_r,c = s_r,(c + shift(r, Nb) mod Nb\n for 0 < r < 4 and 0 <= c < Nb and\n shift(1, 4) = 1\n shift(2, 4) = 2\n shift(3, 4) = 3.\n\n This causes the first byte in r = 1 to be moved to the end of\n the row, the first 2 bytes in r = 2 to be moved to the end of\n the row, the first 3 bytes in r = 3 to be moved to the end of\n the row:\n\n r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]\n r2: [c0 c1 c2 c3] [c2 c3 c0 c1]\n r3: [c0 c1 c2 c3] [c3 c0 c1 c2]\n\n We can make these substitutions inline with our column mixing to\n generate an updated set of equations to produce each word in the\n state (note the columns have changed positions):\n\n c0 c1 c2 c3 => c0 c1 c2 c3\n c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)\n c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)\n c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)\n\n Therefore:\n\n c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3\n c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3\n\n c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0\n c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0\n\n ... and so forth for c'2 and c'3. The important distinction is\n that the columns are cycling, with c0 being used with the m0\n map when calculating c0, but c1 being used with the m0 map when\n calculating c1 ... and so forth.\n\n When performing the inverse we transform the mirror image and\n skip the bottom row, instead of the top one, and move upwards:\n\n c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption\n c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)\n c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption\n c3 c2 c1 c0 c3 c2 c1 c0\n\n If you compare the resulting matrices for ShiftRows()+MixColumns()\n and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are\n different (in encrypt mode vs. decrypt mode). So in order to use\n the same code to handle both encryption and decryption, we will\n need to do some mapping.\n\n If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be\n a row number in the state, then the resulting matrix in encryption\n mode for applying the above transformations would be:\n\n r1: a b c d\n r2: b c d a\n r3: c d a b\n r4: d a b c\n\n If we did the same in decryption mode we would get:\n\n r1: a d c b\n r2: b a d c\n r3: c b a d\n r4: d c b a\n\n If instead we swap d and b (set b=c3 and d=c1), then we get:\n\n r1: a b c d\n r2: d a b c\n r3: c d a b\n r4: b c d a\n\n Now the 1st and 3rd rows are the same as the encryption matrix. All\n we need to do then to make the mapping exactly the same is to swap\n the 2nd and 4th rows when in decryption mode. To do this without\n having to do it on each iteration, we swapped the 2nd and 4th rows\n in the decryption key schedule. We also have to do the swap above\n when we first pull in the input and when we set the final output. */\n a2 =\n m0[a >>> 24] ^\n m1[b >>> 16 & 255] ^\n m2[c >>> 8 & 255] ^\n m3[d & 255] ^ w[++i];\n b2 =\n m0[b >>> 24] ^\n m1[c >>> 16 & 255] ^\n m2[d >>> 8 & 255] ^\n m3[a & 255] ^ w[++i];\n c2 =\n m0[c >>> 24] ^\n m1[d >>> 16 & 255] ^\n m2[a >>> 8 & 255] ^\n m3[b & 255] ^ w[++i];\n d =\n m0[d >>> 24] ^\n m1[a >>> 16 & 255] ^\n m2[b >>> 8 & 255] ^\n m3[c & 255] ^ w[++i];\n a = a2;\n b = b2;\n c = c2;\n }\n\n /*\n Encrypt:\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n\n Decrypt:\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n */\n // Note: rows are shifted inline\n output[0] =\n (sub[a >>> 24] << 24) ^\n (sub[b >>> 16 & 255] << 16) ^\n (sub[c >>> 8 & 255] << 8) ^\n (sub[d & 255]) ^ w[++i];\n output[decrypt ? 3 : 1] =\n (sub[b >>> 24] << 24) ^\n (sub[c >>> 16 & 255] << 16) ^\n (sub[d >>> 8 & 255] << 8) ^\n (sub[a & 255]) ^ w[++i];\n output[2] =\n (sub[c >>> 24] << 24) ^\n (sub[d >>> 16 & 255] << 16) ^\n (sub[a >>> 8 & 255] << 8) ^\n (sub[b & 255]) ^ w[++i];\n output[decrypt ? 1 : 3] =\n (sub[d >>> 24] << 24) ^\n (sub[a >>> 16 & 255] << 16) ^\n (sub[b >>> 8 & 255] << 8) ^\n (sub[c & 255]) ^ w[++i];\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('AES-', key);\n * forge.cipher.createDecipher('AES-', key);\n *\n * Creates a deprecated AES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key and iv may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param options the options to use.\n * key the symmetric key to use.\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'AES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * A Javascript implementation of AES Cipher Suites for TLS.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2015 Digital Bazaar, Inc.\n *\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./tls');\n\nvar tls = module.exports = forge.tls;\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = {\n id: [0x00, 0x2f],\n name: 'TLS_RSA_WITH_AES_128_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 16;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\ntls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = {\n id: [0x00, 0x35],\n name: 'TLS_RSA_WITH_AES_256_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 32;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\n\nfunction initConnectionState(state, c, sp) {\n var client = (c.entity === forge.tls.ConnectionEnd.client);\n\n // cipher setup\n state.read.cipherState = {\n init: false,\n cipher: forge.cipher.createDecipher('AES-CBC', client ?\n sp.keys.server_write_key : sp.keys.client_write_key),\n iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV\n };\n state.write.cipherState = {\n init: false,\n cipher: forge.cipher.createCipher('AES-CBC', client ?\n sp.keys.client_write_key : sp.keys.server_write_key),\n iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV\n };\n state.read.cipherFunction = decrypt_aes_cbc_sha1;\n state.write.cipherFunction = encrypt_aes_cbc_sha1;\n\n // MAC setup\n state.read.macLength = state.write.macLength = sp.mac_length;\n state.read.macFunction = state.write.macFunction = tls.hmac_sha1;\n}\n\n/**\n * Encrypts the TLSCompressed record into a TLSCipherText record using AES\n * in CBC mode.\n *\n * @param record the TLSCompressed record to encrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n // append MAC to fragment, update sequence number\n var mac = s.macFunction(s.macKey, s.sequenceNumber, record);\n record.fragment.putBytes(mac);\n s.updateSequenceNumber();\n\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use the pre-generated IV when initializing for TLS 1.0, otherwise use\n // the residue from the previous encryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n iv = forge.random.getBytesSync(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // TLS 1.1+ write IV into output\n if(record.version.minor >= tls.Versions.TLS_1_1.minor) {\n cipher.output.putBytes(iv);\n }\n\n // do encryption (default padding is appropriate)\n cipher.update(record.fragment);\n if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {\n // set record fragment to encrypted output\n record.fragment = cipher.output;\n record.length = record.fragment.length();\n rval = true;\n }\n\n return rval;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in encrypt mode.\n *\n * @param blockSize the block size.\n * @param input the input buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {\n /* The encrypted data length (TLSCiphertext.length) is one more than the sum\n of SecurityParameters.block_length, TLSCompressed.length,\n SecurityParameters.mac_length, and padding_length.\n\n The padding may be any length up to 255 bytes long, as long as it results in\n the TLSCiphertext.length being an integral multiple of the block length.\n Lengths longer than necessary might be desirable to frustrate attacks on a\n protocol based on analysis of the lengths of exchanged messages. Each uint8\n in the padding data vector must be filled with the padding length value.\n\n The padding length should be such that the total size of the\n GenericBlockCipher structure is a multiple of the cipher's block length.\n Legal values range from zero to 255, inclusive. This length specifies the\n length of the padding field exclusive of the padding_length field itself.\n\n This is slightly different from PKCS#7 because the padding value is 1\n less than the actual number of padding bytes if you include the\n padding_length uint8 itself as a padding byte. */\n if(!decrypt) {\n // get the number of padding bytes required to reach the blockSize and\n // subtract 1 for the padding value (to make room for the padding_length\n // uint8)\n var padding = blockSize - (input.length() % blockSize);\n input.fillWithByte(padding - 1, padding);\n }\n return true;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in decrypt mode.\n *\n * @param blockSize the block size.\n * @param output the output buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {\n var rval = true;\n if(decrypt) {\n /* The last byte in the output specifies the number of padding bytes not\n including itself. Each of the padding bytes has the same value as that\n last byte (known as the padding_length). Here we check all padding\n bytes to ensure they have the value of padding_length even if one of\n them is bad in order to ward-off timing attacks. */\n var len = output.length();\n var paddingLength = output.last();\n for(var i = len - 1 - paddingLength; i < len - 1; ++i) {\n rval = rval && (output.at(i) == paddingLength);\n }\n if(rval) {\n // trim off padding bytes and last padding length byte\n output.truncate(paddingLength + 1);\n }\n }\n return rval;\n}\n\n/**\n * Decrypts a TLSCipherText record into a TLSCompressed record using\n * AES in CBC mode.\n *\n * @param record the TLSCipherText record to decrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use pre-generated IV when initializing for TLS 1.0, otherwise use the\n // residue from the previous decryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n // that is appended to the record fragment\n iv = record.fragment.getBytes(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // do decryption\n cipher.update(record.fragment);\n rval = cipher.finish(decrypt_aes_cbc_sha1_padding);\n\n // even if decryption fails, keep going to minimize timing attacks\n\n // decrypted data:\n // first (len - 20) bytes = application data\n // last 20 bytes = MAC\n var macLen = s.macLength;\n\n // create a random MAC to check against should the mac length check fail\n // Note: do this regardless of the failure to keep timing consistent\n var mac = forge.random.getBytesSync(macLen);\n\n // get fragment and mac\n var len = cipher.output.length();\n if(len >= macLen) {\n record.fragment = cipher.output.getBytes(len - macLen);\n mac = cipher.output.getBytes(macLen);\n } else {\n // bad data, but get bytes anyway to try to keep timing consistent\n record.fragment = cipher.output.getBytes();\n }\n record.fragment = forge.util.createBuffer(record.fragment);\n record.length = record.fragment.length();\n\n // see if data integrity checks out, update sequence number\n var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record);\n s.updateSequenceNumber();\n rval = compareMacs(s.macKey, mac, mac2) && rval;\n return rval;\n}\n\n/**\n * Safely compare two MACs. This function will compare two MACs in a way\n * that protects against timing attacks.\n *\n * TODO: Expose elsewhere as a utility API.\n *\n * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/\n *\n * @param key the MAC key to use.\n * @param mac1 as a binary-encoded string of bytes.\n * @param mac2 as a binary-encoded string of bytes.\n *\n * @return true if the MACs are the same, false if not.\n */\nfunction compareMacs(key, mac1, mac2) {\n var hmac = forge.hmac.create();\n\n hmac.start('SHA1', key);\n hmac.update(mac1);\n mac1 = hmac.digest().getBytes();\n\n hmac.start(null, null);\n hmac.update(mac2);\n mac2 = hmac.digest().getBytes();\n\n return mac1 === mac2;\n}\n","/**\n * Copyright (c) 2019 Digital Bazaar, Inc.\n */\n\nvar forge = require('./forge');\nrequire('./asn1');\nvar asn1 = forge.asn1;\n\nexports.privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\nexports.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n },\n // capture group for ed25519PublicKey\n {\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n composed: true,\n captureBitStringValue: 'ed25519PublicKey'\n }\n // FIXME: this is capture group for rsaPublicKey, use it in this API or\n // discard?\n /* {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n } */\n ]\n};\n","/**\n * Javascript implementation of Abstract Syntax Notation Number One.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n *\n * An API for storing data using the Abstract Syntax Notation Number One\n * format using DER (Distinguished Encoding Rules) encoding. This encoding is\n * commonly used to store data for PKI, i.e. X.509 Certificates, and this\n * implementation exists for that purpose.\n *\n * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract\n * syntax of information without restricting the way the information is encoded\n * for transmission. It provides a standard that allows for open systems\n * communication. ASN.1 defines the syntax of information data and a number of\n * simple data types as well as a notation for describing them and specifying\n * values for them.\n *\n * The RSA algorithm creates public and private keys that are often stored in\n * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This\n * class provides the most basic functionality required to store and load DSA\n * keys that are encoded according to ASN.1.\n *\n * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)\n * and DER (Distinguished Encoding Rules). DER is just a subset of BER that\n * has stricter requirements for how data must be encoded.\n *\n * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)\n * and a byte array for the value of this ASN1 structure which may be data or a\n * list of ASN.1 structures.\n *\n * Each ASN.1 structure using BER is (Tag-Length-Value):\n *\n * | byte 0 | bytes X | bytes Y |\n * |--------|---------|----------\n * | tag | length | value |\n *\n * ASN.1 allows for tags to be of \"High-tag-number form\" which allows a tag to\n * be two or more octets, but that is not supported by this class. A tag is\n * only 1 byte. Bits 1-5 give the tag number (ie the data type within a\n * particular 'class'), 6 indicates whether or not the ASN.1 value is\n * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If\n * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,\n * then the class is APPLICATION. If only bit 8 is set, then the class is\n * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.\n * The tag numbers for the data types for the class UNIVERSAL are listed below:\n *\n * UNIVERSAL 0 Reserved for use by the encoding rules\n * UNIVERSAL 1 Boolean type\n * UNIVERSAL 2 Integer type\n * UNIVERSAL 3 Bitstring type\n * UNIVERSAL 4 Octetstring type\n * UNIVERSAL 5 Null type\n * UNIVERSAL 6 Object identifier type\n * UNIVERSAL 7 Object descriptor type\n * UNIVERSAL 8 External type and Instance-of type\n * UNIVERSAL 9 Real type\n * UNIVERSAL 10 Enumerated type\n * UNIVERSAL 11 Embedded-pdv type\n * UNIVERSAL 12 UTF8String type\n * UNIVERSAL 13 Relative object identifier type\n * UNIVERSAL 14-15 Reserved for future editions\n * UNIVERSAL 16 Sequence and Sequence-of types\n * UNIVERSAL 17 Set and Set-of types\n * UNIVERSAL 18-22, 25-30 Character string types\n * UNIVERSAL 23-24 Time types\n *\n * The length of an ASN.1 structure is specified after the tag identifier.\n * There is a definite form and an indefinite form. The indefinite form may\n * be used if the encoding is constructed and not all immediately available.\n * The indefinite form is encoded using a length byte with only the 8th bit\n * set. The end of the constructed object is marked using end-of-contents\n * octets (two zero bytes).\n *\n * The definite form looks like this:\n *\n * The length may take up 1 or more bytes, it depends on the length of the\n * value of the ASN.1 structure. DER encoding requires that if the ASN.1\n * structure has a value that has a length greater than 127, more than 1 byte\n * will be used to store its length, otherwise just one byte will be used.\n * This is strict.\n *\n * In the case that the length of the ASN.1 value is less than 127, 1 octet\n * (byte) is used to store the \"short form\" length. The 8th bit has a value of\n * 0 indicating the length is \"short form\" and not \"long form\" and bits 7-1\n * give the length of the data. (The 8th bit is the left-most, most significant\n * bit: also known as big endian or network format).\n *\n * In the case that the length of the ASN.1 value is greater than 127, 2 to\n * 127 octets (bytes) are used to store the \"long form\" length. The first\n * byte's 8th bit is set to 1 to indicate the length is \"long form.\" Bits 7-1\n * give the number of additional octets. All following octets are in base 256\n * with the most significant digit first (typical big-endian binary unsigned\n * integer storage). So, for instance, if the length of a value was 257, the\n * first byte would be set to:\n *\n * 10000010 = 130 = 0x82.\n *\n * This indicates there are 2 octets (base 256) for the length. The second and\n * third bytes (the octets just mentioned) would store the length in base 256:\n *\n * octet 2: 00000001 = 1 * 256^1 = 256\n * octet 3: 00000001 = 1 * 256^0 = 1\n * total = 257\n *\n * The algorithm for converting a js integer value of 257 to base-256 is:\n *\n * var value = 257;\n * var bytes = [];\n * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first\n * bytes[1] = value & 0xFF; // least significant byte last\n *\n * On the ASN.1 UNIVERSAL Object Identifier (OID) type:\n *\n * An OID can be written like: \"value1.value2.value3...valueN\"\n *\n * The DER encoding rules:\n *\n * The first byte has the value 40 * value1 + value2.\n * The following bytes, if any, encode the remaining values. Each value is\n * encoded in base 128, most significant digit first (big endian), with as\n * few digits as possible, and the most significant bit of each byte set\n * to 1 except the last in each value's encoding. For example: Given the\n * OID \"1.2.840.113549\", its DER encoding is (remember each byte except the\n * last one in each encoding is OR'd with 0x80):\n *\n * byte 1: 40 * 1 + 2 = 42 = 0x2A.\n * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648\n * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D\n *\n * The final value is: 0x2A864886F70D.\n * The full OID (including ASN.1 tag and length of 6 bytes) is:\n * 0x06062A864886F70D\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./oids');\n\n/* ASN.1 API */\nvar asn1 = module.exports = forge.asn1 = forge.asn1 || {};\n\n/**\n * ASN.1 classes.\n */\nasn1.Class = {\n UNIVERSAL: 0x00,\n APPLICATION: 0x40,\n CONTEXT_SPECIFIC: 0x80,\n PRIVATE: 0xC0\n};\n\n/**\n * ASN.1 types. Not all types are supported by this implementation, only\n * those necessary to implement a simple PKI are implemented.\n */\nasn1.Type = {\n NONE: 0,\n BOOLEAN: 1,\n INTEGER: 2,\n BITSTRING: 3,\n OCTETSTRING: 4,\n NULL: 5,\n OID: 6,\n ODESC: 7,\n EXTERNAL: 8,\n REAL: 9,\n ENUMERATED: 10,\n EMBEDDED: 11,\n UTF8: 12,\n ROID: 13,\n SEQUENCE: 16,\n SET: 17,\n PRINTABLESTRING: 19,\n IA5STRING: 22,\n UTCTIME: 23,\n GENERALIZEDTIME: 24,\n BMPSTRING: 30\n};\n\n/**\n * Creates a new asn1 object.\n *\n * @param tagClass the tag class for the object.\n * @param type the data type (tag number) for the object.\n * @param constructed true if the asn1 object is in constructed form.\n * @param value the value for the object, if it is not constructed.\n * @param [options] the options to use:\n * [bitStringContents] the plain BIT STRING content including padding\n * byte.\n *\n * @return the asn1 object.\n */\nasn1.create = function(tagClass, type, constructed, value, options) {\n /* An asn1 object has a tagClass, a type, a constructed flag, and a\n value. The value's type depends on the constructed flag. If\n constructed, it will contain a list of other asn1 objects. If not,\n it will contain the ASN.1 value as an array of bytes formatted\n according to the ASN.1 data type. */\n\n // remove undefined values\n if(forge.util.isArray(value)) {\n var tmp = [];\n for(var i = 0; i < value.length; ++i) {\n if(value[i] !== undefined) {\n tmp.push(value[i]);\n }\n }\n value = tmp;\n }\n\n var obj = {\n tagClass: tagClass,\n type: type,\n constructed: constructed,\n composed: constructed || forge.util.isArray(value),\n value: value\n };\n if(options && 'bitStringContents' in options) {\n // TODO: copy byte buffer if it's a buffer not a string\n obj.bitStringContents = options.bitStringContents;\n // TODO: add readonly flag to avoid this overhead\n // save copy to detect changes\n obj.original = asn1.copy(obj);\n }\n return obj;\n};\n\n/**\n * Copies an asn1 object.\n *\n * @param obj the asn1 object.\n * @param [options] copy options:\n * [excludeBitStringContents] true to not copy bitStringContents\n *\n * @return the a copy of the asn1 object.\n */\nasn1.copy = function(obj, options) {\n var copy;\n\n if(forge.util.isArray(obj)) {\n copy = [];\n for(var i = 0; i < obj.length; ++i) {\n copy.push(asn1.copy(obj[i], options));\n }\n return copy;\n }\n\n if(typeof obj === 'string') {\n // TODO: copy byte buffer if it's a buffer not a string\n return obj;\n }\n\n copy = {\n tagClass: obj.tagClass,\n type: obj.type,\n constructed: obj.constructed,\n composed: obj.composed,\n value: asn1.copy(obj.value, options)\n };\n if(options && !options.excludeBitStringContents) {\n // TODO: copy byte buffer if it's a buffer not a string\n copy.bitStringContents = obj.bitStringContents;\n }\n return copy;\n};\n\n/**\n * Compares asn1 objects for equality.\n *\n * Note this function does not run in constant time.\n *\n * @param obj1 the first asn1 object.\n * @param obj2 the second asn1 object.\n * @param [options] compare options:\n * [includeBitStringContents] true to compare bitStringContents\n *\n * @return true if the asn1 objects are equal.\n */\nasn1.equals = function(obj1, obj2, options) {\n if(forge.util.isArray(obj1)) {\n if(!forge.util.isArray(obj2)) {\n return false;\n }\n if(obj1.length !== obj2.length) {\n return false;\n }\n for(var i = 0; i < obj1.length; ++i) {\n if(!asn1.equals(obj1[i], obj2[i])) {\n return false;\n }\n }\n return true;\n }\n\n if(typeof obj1 !== typeof obj2) {\n return false;\n }\n\n if(typeof obj1 === 'string') {\n return obj1 === obj2;\n }\n\n var equal = obj1.tagClass === obj2.tagClass &&\n obj1.type === obj2.type &&\n obj1.constructed === obj2.constructed &&\n obj1.composed === obj2.composed &&\n asn1.equals(obj1.value, obj2.value);\n if(options && options.includeBitStringContents) {\n equal = equal && (obj1.bitStringContents === obj2.bitStringContents);\n }\n\n return equal;\n};\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param b the BER-encoded ASN.1 byte buffer, starting with the first\n * length byte.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nasn1.getBerValueLength = function(b) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n var b2 = b.getByte();\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n length = b.getInt((b2 & 0x7F) << 3);\n }\n return length;\n};\n\n/**\n * Check if the byte buffer has enough bytes. Throws an Error if not.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n * @param n the number of bytes the buffer must have.\n */\nfunction _checkBufferLength(bytes, remaining, n) {\n if(n > remaining) {\n var error = new Error('Too few bytes to parse DER.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = n;\n throw error;\n }\n}\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nvar _getValueLength = function(bytes, remaining) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n // fromDer already checked that this byte exists\n var b2 = bytes.getByte();\n remaining--;\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n var longFormBytes = b2 & 0x7F;\n _checkBufferLength(bytes, remaining, longFormBytes);\n length = bytes.getInt(longFormBytes << 3);\n }\n // FIXME: this will only happen for 32 bit getInt with high bit set\n if(length < 0) {\n throw new Error('Negative length: ' + length);\n }\n return length;\n};\n\n/**\n * Parses an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * @param [options] object with options or boolean strict flag\n * [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * [parseAllBytes] true to ensure all bytes are parsed\n * (default: true)\n * [decodeBitStrings] true to attempt to decode the content of\n * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that\n * without schema support to understand the data context this can\n * erroneously decode values that happen to be valid ASN.1. This\n * flag will be deprecated or removed as soon as schema support is\n * available. (default: true)\n *\n * @throws Will throw an error for various malformed input conditions.\n *\n * @return the parsed asn1 object.\n */\nasn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('parseAllBytes' in options)) {\n options.parseAllBytes = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var byteCount = bytes.length();\n var value = _fromDer(bytes, bytes.length(), 0, options);\n if(options.parseAllBytes && bytes.length() !== 0) {\n var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');\n error.byteCount = byteCount;\n error.remaining = bytes.length();\n throw error;\n }\n return value;\n};\n\n/**\n * Internal function to parse an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the number of bytes remaining for this chunk.\n * @param depth the current parsing depth.\n * @param options object with same options as fromDer().\n *\n * @return the parsed asn1 object.\n */\nfunction _fromDer(bytes, remaining, depth, options) {\n // temporary storage for consumption calculations\n var start;\n\n // minimum length for ASN.1 DER structure is 2\n _checkBufferLength(bytes, remaining, 2);\n\n // get the first byte\n var b1 = bytes.getByte();\n // consumed one byte\n remaining--;\n\n // get the tag class\n var tagClass = (b1 & 0xC0);\n\n // get the type (bits 1-5)\n var type = b1 & 0x1F;\n\n // get the variable value length and adjust remaining bytes\n start = bytes.length();\n var length = _getValueLength(bytes, remaining);\n remaining -= start - bytes.length();\n\n // ensure there are enough bytes to get the value\n if(length !== undefined && length > remaining) {\n if(options.strict) {\n var error = new Error('Too few bytes to read ASN.1 value.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = length;\n throw error;\n }\n // Note: be lenient with truncated values and use remaining state bytes\n length = remaining;\n }\n\n // value storage\n var value;\n // possible BIT STRING contents storage\n var bitStringContents;\n\n // constructed flag is bit 6 (32 = 0x20) of the first byte\n var constructed = ((b1 & 0x20) === 0x20);\n if(constructed) {\n // parse child asn1 objects from the value\n value = [];\n if(length === undefined) {\n // asn1 object of indefinite length, read until end tag\n for(;;) {\n _checkBufferLength(bytes, remaining, 2);\n if(bytes.bytes(2) === String.fromCharCode(0, 0)) {\n bytes.getBytes(2);\n remaining -= 2;\n break;\n }\n start = bytes.length();\n value.push(_fromDer(bytes, remaining, depth + 1, options));\n remaining -= start - bytes.length();\n }\n } else {\n // parsing asn1 object of definite length\n while(length > 0) {\n start = bytes.length();\n value.push(_fromDer(bytes, length, depth + 1, options));\n remaining -= start - bytes.length();\n length -= start - bytes.length();\n }\n }\n }\n\n // if a BIT STRING, save the contents including padding\n if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&\n type === asn1.Type.BITSTRING) {\n bitStringContents = bytes.bytes(length);\n }\n\n // determine if a non-constructed value should be decoded as a composed\n // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)\n // can be used this way.\n if(value === undefined && options.decodeBitStrings &&\n tagClass === asn1.Class.UNIVERSAL &&\n // FIXME: OCTET STRINGs not yet supported here\n // .. other parts of forge expect to decode OCTET STRINGs manually\n (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&\n length > 1) {\n // save read position\n var savedRead = bytes.read;\n var savedRemaining = remaining;\n var unused = 0;\n if(type === asn1.Type.BITSTRING) {\n /* The first octet gives the number of bits by which the length of the\n bit string is less than the next multiple of eight (this is called\n the \"number of unused bits\").\n\n The second and following octets give the value of the bit string\n converted to an octet string. */\n _checkBufferLength(bytes, remaining, 1);\n unused = bytes.getByte();\n remaining--;\n }\n // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs\n if(unused === 0) {\n try {\n // attempt to parse child asn1 object from the value\n // (stored in array to signal composed value)\n start = bytes.length();\n var subOptions = {\n // enforce strict mode to avoid parsing ASN.1 from plain data\n strict: true,\n decodeBitStrings: true\n };\n var composed = _fromDer(bytes, remaining, depth + 1, subOptions);\n var used = start - bytes.length();\n remaining -= used;\n if(type == asn1.Type.BITSTRING) {\n used++;\n }\n\n // if the data all decoded and the class indicates UNIVERSAL or\n // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object\n var tc = composed.tagClass;\n if(used === length &&\n (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {\n value = [composed];\n }\n } catch(ex) {\n }\n }\n if(value === undefined) {\n // restore read position\n bytes.read = savedRead;\n remaining = savedRemaining;\n }\n }\n\n if(value === undefined) {\n // asn1 not constructed or composed, get raw value\n // TODO: do DER to OID conversion and vice-versa in .toDer?\n\n if(length === undefined) {\n if(options.strict) {\n throw new Error('Non-constructed ASN.1 object of indefinite length.');\n }\n // be lenient and use remaining state bytes\n length = remaining;\n }\n\n if(type === asn1.Type.BMPSTRING) {\n value = '';\n for(; length > 0; length -= 2) {\n _checkBufferLength(bytes, remaining, 2);\n value += String.fromCharCode(bytes.getInt16());\n remaining -= 2;\n }\n } else {\n value = bytes.getBytes(length);\n remaining -= length;\n }\n }\n\n // add BIT STRING contents if available\n var asn1Options = bitStringContents === undefined ? null : {\n bitStringContents: bitStringContents\n };\n\n // create and return asn1 object\n return asn1.create(tagClass, type, constructed, value, asn1Options);\n}\n\n/**\n * Converts the given asn1 object to a buffer of bytes in DER format.\n *\n * @param asn1 the asn1 object to convert to bytes.\n *\n * @return the buffer of bytes.\n */\nasn1.toDer = function(obj) {\n var bytes = forge.util.createBuffer();\n\n // build the first byte\n var b1 = obj.tagClass | obj.type;\n\n // for storing the ASN.1 value\n var value = forge.util.createBuffer();\n\n // use BIT STRING contents if available and data not changed\n var useBitStringContents = false;\n if('bitStringContents' in obj) {\n useBitStringContents = true;\n if(obj.original) {\n useBitStringContents = asn1.equals(obj, obj.original);\n }\n }\n\n if(useBitStringContents) {\n value.putBytes(obj.bitStringContents);\n } else if(obj.composed) {\n // if composed, use each child asn1 object's DER bytes as value\n // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed\n // from other asn1 objects\n if(obj.constructed) {\n b1 |= 0x20;\n } else {\n // type is a bit string, add unused bits of 0x00\n value.putByte(0x00);\n }\n\n // add all of the child DER bytes together\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n value.putBuffer(asn1.toDer(obj.value[i]));\n }\n }\n } else {\n // use asn1.value directly\n if(obj.type === asn1.Type.BMPSTRING) {\n for(var i = 0; i < obj.value.length; ++i) {\n value.putInt16(obj.value.charCodeAt(i));\n }\n } else {\n // ensure integer is minimally-encoded\n // TODO: should all leading bytes be stripped vs just one?\n // .. ex '00 00 01' => '01'?\n if(obj.type === asn1.Type.INTEGER &&\n obj.value.length > 1 &&\n // leading 0x00 for positive integer\n ((obj.value.charCodeAt(0) === 0 &&\n (obj.value.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (obj.value.charCodeAt(0) === 0xFF &&\n (obj.value.charCodeAt(1) & 0x80) === 0x80))) {\n value.putBytes(obj.value.substr(1));\n } else {\n value.putBytes(obj.value);\n }\n }\n }\n\n // add tag byte\n bytes.putByte(b1);\n\n // use \"short form\" encoding\n if(value.length() <= 127) {\n // one byte describes the length\n // bit 8 = 0 and bits 7-1 = length\n bytes.putByte(value.length() & 0x7F);\n } else {\n // use \"long form\" encoding\n // 2 to 127 bytes describe the length\n // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes\n // other bytes: length in base 256, big-endian\n var len = value.length();\n var lenBytes = '';\n do {\n lenBytes += String.fromCharCode(len & 0xFF);\n len = len >>> 8;\n } while(len > 0);\n\n // set first byte to # bytes used to store the length and turn on\n // bit 8 to indicate long-form length is used\n bytes.putByte(lenBytes.length | 0x80);\n\n // concatenate length bytes in reverse since they were generated\n // little endian and we need big endian\n for(var i = lenBytes.length - 1; i >= 0; --i) {\n bytes.putByte(lenBytes.charCodeAt(i));\n }\n }\n\n // concatenate value bytes\n bytes.putBuffer(value);\n return bytes;\n};\n\n/**\n * Converts an OID dot-separated string to a byte buffer. The byte buffer\n * contains only the DER-encoded value, not any tag or length bytes.\n *\n * @param oid the OID dot-separated string.\n *\n * @return the byte buffer.\n */\nasn1.oidToDer = function(oid) {\n // split OID into individual values\n var values = oid.split('.');\n var bytes = forge.util.createBuffer();\n\n // first byte is 40 * value1 + value2\n bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var last, valueBytes, value, b;\n for(var i = 2; i < values.length; ++i) {\n // produce value bytes in reverse because we don't know how many\n // bytes it will take to store the value\n last = true;\n valueBytes = [];\n value = parseInt(values[i], 10);\n do {\n b = value & 0x7F;\n value = value >>> 7;\n // if value is not last, then turn on 8th bit\n if(!last) {\n b |= 0x80;\n }\n valueBytes.push(b);\n last = false;\n } while(value > 0);\n\n // add value bytes in reverse (needs to be in big endian)\n for(var n = valueBytes.length - 1; n >= 0; --n) {\n bytes.putByte(valueBytes[n]);\n }\n }\n\n return bytes;\n};\n\n/**\n * Converts a DER-encoded byte buffer to an OID dot-separated string. The\n * byte buffer should contain only the DER-encoded value, not any tag or\n * length bytes.\n *\n * @param bytes the byte buffer.\n *\n * @return the OID dot-separated string.\n */\nasn1.derToOid = function(bytes) {\n var oid;\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n // first byte is 40 * value1 + value2\n var b = bytes.getByte();\n oid = Math.floor(b / 40) + '.' + (b % 40);\n\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var value = 0;\n while(bytes.length() > 0) {\n b = bytes.getByte();\n value = value << 7;\n // not the last byte for the value\n if(b & 0x80) {\n value += b & 0x7F;\n } else {\n // last byte\n oid += '.' + (value + b);\n value = 0;\n }\n }\n\n return oid;\n};\n\n/**\n * Converts a UTCTime value to a date.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Parsing that structure hasn't been implemented yet.\n *\n * @param utc the UTCTime value to convert.\n *\n * @return the date.\n */\nasn1.utcTimeToDate = function(utc) {\n /* The following formats can be used:\n\n YYMMDDhhmmZ\n YYMMDDhhmm+hh'mm'\n YYMMDDhhmm-hh'mm'\n YYMMDDhhmmssZ\n YYMMDDhhmmss+hh'mm'\n YYMMDDhhmmss-hh'mm'\n\n Where:\n\n YY is the least significant two digits of the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n // if YY >= 50 use 19xx, if YY < 50 use 20xx\n var year = parseInt(utc.substr(0, 2), 10);\n year = (year >= 50) ? 1900 + year : 2000 + year;\n var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(utc.substr(4, 2), 10);\n var hh = parseInt(utc.substr(6, 2), 10);\n var mm = parseInt(utc.substr(8, 2), 10);\n var ss = 0;\n\n // not just YYMMDDhhmmZ\n if(utc.length > 11) {\n // get character after minutes\n var c = utc.charAt(10);\n var end = 10;\n\n // see if seconds are present\n if(c !== '+' && c !== '-') {\n // get seconds\n ss = parseInt(utc.substr(10, 2), 10);\n end += 2;\n }\n }\n\n // update date\n date.setUTCFullYear(year, MM, DD);\n date.setUTCHours(hh, mm, ss, 0);\n\n if(end) {\n // get +/- after end of time\n c = utc.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(utc.substr(end + 1, 2), 10);\n var mmoffset = parseInt(utc.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n var offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n date.setTime(+date - offset);\n } else {\n date.setTime(+date + offset);\n }\n }\n }\n\n return date;\n};\n\n/**\n * Converts a GeneralizedTime value to a date.\n *\n * @param gentime the GeneralizedTime value to convert.\n *\n * @return the date.\n */\nasn1.generalizedTimeToDate = function(gentime) {\n /* The following formats can be used:\n\n YYYYMMDDHHMMSS\n YYYYMMDDHHMMSS.fff\n YYYYMMDDHHMMSSZ\n YYYYMMDDHHMMSS.fffZ\n YYYYMMDDHHMMSS+hh'mm'\n YYYYMMDDHHMMSS.fff+hh'mm'\n YYYYMMDDHHMMSS-hh'mm'\n YYYYMMDDHHMMSS.fff-hh'mm'\n\n Where:\n\n YYYY is the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n .fff is the second fraction, accurate to three decimal places\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n var YYYY = parseInt(gentime.substr(0, 4), 10);\n var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(gentime.substr(6, 2), 10);\n var hh = parseInt(gentime.substr(8, 2), 10);\n var mm = parseInt(gentime.substr(10, 2), 10);\n var ss = parseInt(gentime.substr(12, 2), 10);\n var fff = 0;\n var offset = 0;\n var isUTC = false;\n\n if(gentime.charAt(gentime.length - 1) === 'Z') {\n isUTC = true;\n }\n\n var end = gentime.length - 5, c = gentime.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);\n var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n offset *= -1;\n }\n\n isUTC = true;\n }\n\n // check for second fraction\n if(gentime.charAt(14) === '.') {\n fff = parseFloat(gentime.substr(14), 10) * 1000;\n }\n\n if(isUTC) {\n date.setUTCFullYear(YYYY, MM, DD);\n date.setUTCHours(hh, mm, ss, fff);\n\n // apply offset\n date.setTime(+date + offset);\n } else {\n date.setFullYear(YYYY, MM, DD);\n date.setHours(hh, mm, ss, fff);\n }\n\n return date;\n};\n\n/**\n * Converts a date to a UTCTime value.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Converting to a GeneralizedTime hasn't been\n * implemented yet.\n *\n * @param date the date to convert.\n *\n * @return the UTCTime value.\n */\nasn1.dateToUtcTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYMMDDhhmmssZ\n var format = [];\n format.push(('' + date.getUTCFullYear()).substr(2));\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a date to a GeneralizedTime value.\n *\n * @param date the date to convert.\n *\n * @return the GeneralizedTime value as a string.\n */\nasn1.dateToGeneralizedTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYYYMMDDHHMMSSZ\n var format = [];\n format.push('' + date.getUTCFullYear());\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a javascript integer to a DER-encoded byte buffer to be used\n * as the value for an INTEGER type.\n *\n * @param x the integer.\n *\n * @return the byte buffer.\n */\nasn1.integerToDer = function(x) {\n var rval = forge.util.createBuffer();\n if(x >= -0x80 && x < 0x80) {\n return rval.putSignedInt(x, 8);\n }\n if(x >= -0x8000 && x < 0x8000) {\n return rval.putSignedInt(x, 16);\n }\n if(x >= -0x800000 && x < 0x800000) {\n return rval.putSignedInt(x, 24);\n }\n if(x >= -0x80000000 && x < 0x80000000) {\n return rval.putSignedInt(x, 32);\n }\n var error = new Error('Integer too large; max is 32-bits.');\n error.integer = x;\n throw error;\n};\n\n/**\n * Converts a DER-encoded byte buffer to a javascript integer. This is\n * typically used to decode the value of an INTEGER type.\n *\n * @param bytes the byte buffer.\n *\n * @return the integer.\n */\nasn1.derToInteger = function(bytes) {\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var n = bytes.length() * 8;\n if(n > 32) {\n throw new Error('Integer too large; max is 32-bits.');\n }\n return bytes.getSignedInt(n);\n};\n\n/**\n * Validates that the given ASN.1 object is at least a super set of the\n * given ASN.1 structure. Only tag classes and types are checked. An\n * optional map may also be provided to capture ASN.1 values while the\n * structure is checked.\n *\n * To capture an ASN.1 value, set an object in the validator's 'capture'\n * parameter to the key to use in the capture map. To capture the full\n * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including\n * the leading unused bits counter byte, specify 'captureBitStringContents'.\n * To capture BIT STRING bytes, without the leading unused bits counter byte,\n * specify 'captureBitStringValue'.\n *\n * Objects in the validator may set a field 'optional' to true to indicate\n * that it isn't necessary to pass validation.\n *\n * @param obj the ASN.1 object to validate.\n * @param v the ASN.1 structure validator.\n * @param capture an optional map to capture values in.\n * @param errors an optional array for storing validation errors.\n *\n * @return true on success, false on failure.\n */\nasn1.validate = function(obj, v, capture, errors) {\n var rval = false;\n\n // ensure tag class and type are the same if specified\n if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&\n (obj.type === v.type || typeof(v.type) === 'undefined')) {\n // ensure constructed flag is the same if specified\n if(obj.constructed === v.constructed ||\n typeof(v.constructed) === 'undefined') {\n rval = true;\n\n // handle sub values\n if(v.value && forge.util.isArray(v.value)) {\n var j = 0;\n for(var i = 0; rval && i < v.value.length; ++i) {\n rval = v.value[i].optional || false;\n if(obj.value[j]) {\n rval = asn1.validate(obj.value[j], v.value[i], capture, errors);\n if(rval) {\n ++j;\n } else if(v.value[i].optional) {\n rval = true;\n }\n }\n if(!rval && errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Tag class \"' + v.tagClass + '\", type \"' +\n v.type + '\" expected value length \"' +\n v.value.length + '\", got \"' +\n obj.value.length + '\"');\n }\n }\n }\n\n if(rval && capture) {\n if(v.capture) {\n capture[v.capture] = obj.value;\n }\n if(v.captureAsn1) {\n capture[v.captureAsn1] = obj;\n }\n if(v.captureBitStringContents && 'bitStringContents' in obj) {\n capture[v.captureBitStringContents] = obj.bitStringContents;\n }\n if(v.captureBitStringValue && 'bitStringContents' in obj) {\n var value;\n if(obj.bitStringContents.length < 2) {\n capture[v.captureBitStringValue] = '';\n } else {\n // FIXME: support unused bits with data shifting\n var unused = obj.bitStringContents.charCodeAt(0);\n if(unused !== 0) {\n throw new Error(\n 'captureBitStringValue only supported for zero unused bits');\n }\n capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);\n }\n }\n }\n } else if(errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected constructed \"' + v.constructed + '\", got \"' +\n obj.constructed + '\"');\n }\n } else if(errors) {\n if(obj.tagClass !== v.tagClass) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected tag class \"' + v.tagClass + '\", got \"' +\n obj.tagClass + '\"');\n }\n if(obj.type !== v.type) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected type \"' + v.type + '\", got \"' + obj.type + '\"');\n }\n }\n return rval;\n};\n\n// regex for testing for non-latin characters\nvar _nonLatinRegex = /[^\\\\u0000-\\\\u00ff]/;\n\n/**\n * Pretty prints an ASN.1 object to a string.\n *\n * @param obj the object to write out.\n * @param level the level in the tree.\n * @param indentation the indentation to use.\n *\n * @return the string.\n */\nasn1.prettyPrint = function(obj, level, indentation) {\n var rval = '';\n\n // set default level and indentation\n level = level || 0;\n indentation = indentation || 2;\n\n // start new line for deep levels\n if(level > 0) {\n rval += '\\n';\n }\n\n // create indent\n var indent = '';\n for(var i = 0; i < level * indentation; ++i) {\n indent += ' ';\n }\n\n // print class:type\n rval += indent + 'Tag: ';\n switch(obj.tagClass) {\n case asn1.Class.UNIVERSAL:\n rval += 'Universal:';\n break;\n case asn1.Class.APPLICATION:\n rval += 'Application:';\n break;\n case asn1.Class.CONTEXT_SPECIFIC:\n rval += 'Context-Specific:';\n break;\n case asn1.Class.PRIVATE:\n rval += 'Private:';\n break;\n }\n\n if(obj.tagClass === asn1.Class.UNIVERSAL) {\n rval += obj.type;\n\n // known types\n switch(obj.type) {\n case asn1.Type.NONE:\n rval += ' (None)';\n break;\n case asn1.Type.BOOLEAN:\n rval += ' (Boolean)';\n break;\n case asn1.Type.INTEGER:\n rval += ' (Integer)';\n break;\n case asn1.Type.BITSTRING:\n rval += ' (Bit string)';\n break;\n case asn1.Type.OCTETSTRING:\n rval += ' (Octet string)';\n break;\n case asn1.Type.NULL:\n rval += ' (Null)';\n break;\n case asn1.Type.OID:\n rval += ' (Object Identifier)';\n break;\n case asn1.Type.ODESC:\n rval += ' (Object Descriptor)';\n break;\n case asn1.Type.EXTERNAL:\n rval += ' (External or Instance of)';\n break;\n case asn1.Type.REAL:\n rval += ' (Real)';\n break;\n case asn1.Type.ENUMERATED:\n rval += ' (Enumerated)';\n break;\n case asn1.Type.EMBEDDED:\n rval += ' (Embedded PDV)';\n break;\n case asn1.Type.UTF8:\n rval += ' (UTF8)';\n break;\n case asn1.Type.ROID:\n rval += ' (Relative Object Identifier)';\n break;\n case asn1.Type.SEQUENCE:\n rval += ' (Sequence)';\n break;\n case asn1.Type.SET:\n rval += ' (Set)';\n break;\n case asn1.Type.PRINTABLESTRING:\n rval += ' (Printable String)';\n break;\n case asn1.Type.IA5String:\n rval += ' (IA5String (ASCII))';\n break;\n case asn1.Type.UTCTIME:\n rval += ' (UTC time)';\n break;\n case asn1.Type.GENERALIZEDTIME:\n rval += ' (Generalized time)';\n break;\n case asn1.Type.BMPSTRING:\n rval += ' (BMP String)';\n break;\n }\n } else {\n rval += obj.type;\n }\n\n rval += '\\n';\n rval += indent + 'Constructed: ' + obj.constructed + '\\n';\n\n if(obj.composed) {\n var subvalues = 0;\n var sub = '';\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n subvalues += 1;\n sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);\n if((i + 1) < obj.value.length) {\n sub += ',';\n }\n }\n }\n rval += indent + 'Sub values: ' + subvalues + sub;\n } else {\n rval += indent + 'Value: ';\n if(obj.type === asn1.Type.OID) {\n var oid = asn1.derToOid(obj.value);\n rval += oid;\n if(forge.pki && forge.pki.oids) {\n if(oid in forge.pki.oids) {\n rval += ' (' + forge.pki.oids[oid] + ') ';\n }\n }\n }\n if(obj.type === asn1.Type.INTEGER) {\n try {\n rval += asn1.derToInteger(obj.value);\n } catch(ex) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n }\n } else if(obj.type === asn1.Type.BITSTRING) {\n // TODO: shift bits as needed to display without padding\n if(obj.value.length > 1) {\n // remove unused bits field\n rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));\n } else {\n rval += '(none)';\n }\n // show unused bit count\n if(obj.value.length > 0) {\n var unused = obj.value.charCodeAt(0);\n if(unused == 1) {\n rval += ' (1 unused bit shown)';\n } else if(unused > 1) {\n rval += ' (' + unused + ' unused bits shown)';\n }\n }\n } else if(obj.type === asn1.Type.OCTETSTRING) {\n if(!_nonLatinRegex.test(obj.value)) {\n rval += '(' + obj.value + ') ';\n }\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.type === asn1.Type.UTF8) {\n try {\n rval += forge.util.decodeUtf8(obj.value);\n } catch(e) {\n if(e.message === 'URI malformed') {\n rval +=\n '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';\n } else {\n throw e;\n }\n }\n } else if(obj.type === asn1.Type.PRINTABLESTRING ||\n obj.type === asn1.Type.IA5String) {\n rval += obj.value;\n } else if(_nonLatinRegex.test(obj.value)) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.value.length === 0) {\n rval += '[null]';\n } else {\n rval += obj.value;\n }\n }\n\n return rval;\n};\n","/**\n * Base-N/Base-X encoding/decoding functions.\n *\n * Original implementation from base-x:\n * https://github.com/cryptocoinjs/base-x\n *\n * Which is MIT licensed:\n *\n * The MIT License (MIT)\n *\n * Copyright base-x contributors (c) 2016\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nvar api = {};\nmodule.exports = api;\n\n// baseN alphabet indexes\nvar _reverseAlphabets = {};\n\n/**\n * BaseN-encodes a Uint8Array using the given alphabet.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the baseN-encoded output string.\n */\napi.encode = function(input, alphabet, maxline) {\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n if(maxline !== undefined && typeof maxline !== 'number') {\n throw new TypeError('\"maxline\" must be a number.');\n }\n\n var output = '';\n\n if(!(input instanceof Uint8Array)) {\n // assume forge byte buffer\n output = _encodeWithByteBuffer(input, alphabet);\n } else {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length; ++i) {\n for(var j = 0, carry = input[i]; j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n // deal with leading zeros\n for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n }\n\n if(maxline) {\n var regex = new RegExp('.{1,' + maxline + '}', 'g');\n output = output.match(regex).join('\\r\\n');\n }\n\n return output;\n};\n\n/**\n * Decodes a baseN-encoded (using the given alphabet) string to a\n * Uint8Array.\n *\n * @param input the baseN-encoded input string.\n *\n * @return the Uint8Array.\n */\napi.decode = function(input, alphabet) {\n if(typeof input !== 'string') {\n throw new TypeError('\"input\" must be a string.');\n }\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n\n var table = _reverseAlphabets[alphabet];\n if(!table) {\n // compute reverse alphabet\n table = _reverseAlphabets[alphabet] = [];\n for(var i = 0; i < alphabet.length; ++i) {\n table[alphabet.charCodeAt(i)] = i;\n }\n }\n\n // remove whitespace characters\n input = input.replace(/\\s/g, '');\n\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var bytes = [0];\n for(var i = 0; i < input.length; i++) {\n var value = table[input.charCodeAt(i)];\n if(value === undefined) {\n return;\n }\n\n for(var j = 0, carry = value; j < bytes.length; ++j) {\n carry += bytes[j] * base;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while(carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // deal with leading zeros\n for(var k = 0; input[k] === first && k < input.length - 1; ++k) {\n bytes.push(0);\n }\n\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(bytes.reverse());\n }\n\n return new Uint8Array(bytes.reverse());\n};\n\nfunction _encodeWithByteBuffer(input, alphabet) {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length(); ++i) {\n for(var j = 0, carry = input.at(i); j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n var output = '';\n\n // deal with leading zeros\n for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n\n return output;\n}\n","/**\n * Cipher base API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nmodule.exports = forge.cipher = forge.cipher || {};\n\n// registered algorithms\nforge.cipher.algorithms = forge.cipher.algorithms || {};\n\n/**\n * Creates a cipher object that can be used to encrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createCipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: false\n });\n};\n\n/**\n * Creates a decipher object that can be used to decrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createDecipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: true\n });\n};\n\n/**\n * Registers an algorithm by name. If the name was already registered, the\n * algorithm API object will be overwritten.\n *\n * @param name the name of the algorithm.\n * @param algorithm the algorithm API object.\n */\nforge.cipher.registerAlgorithm = function(name, algorithm) {\n name = name.toUpperCase();\n forge.cipher.algorithms[name] = algorithm;\n};\n\n/**\n * Gets a registered algorithm by name.\n *\n * @param name the name of the algorithm.\n *\n * @return the algorithm, if found, null if not.\n */\nforge.cipher.getAlgorithm = function(name) {\n name = name.toUpperCase();\n if(name in forge.cipher.algorithms) {\n return forge.cipher.algorithms[name];\n }\n return null;\n};\n\nvar BlockCipher = forge.cipher.BlockCipher = function(options) {\n this.algorithm = options.algorithm;\n this.mode = this.algorithm.mode;\n this.blockSize = this.mode.blockSize;\n this._finish = false;\n this._input = null;\n this.output = null;\n this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;\n this._decrypt = options.decrypt;\n this.algorithm.initialize(options);\n};\n\n/**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array\n * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in\n * bytes, then it must be Nb (16) bytes in length. If the IV is given in as\n * 32-bit integers, then it must be 4 integers long.\n *\n * Note: an IV is not required or used in ECB mode.\n *\n * For GCM-mode, the IV must be given as a binary-encoded string of bytes or\n * a byte buffer. The number of bytes should be 12 (96 bits) as recommended\n * by NIST SP-800-38D but another length may be given.\n *\n * @param options the options to use:\n * iv the initialization vector to use as a binary-encoded string of\n * bytes, null to reuse the last ciphered block from a previous\n * update() (this \"residue\" method is for legacy support only).\n * additionalData additional authentication data as a binary-encoded\n * string of bytes, for 'GCM' mode, (default: none).\n * tagLength desired length of authentication tag, in bits, for\n * 'GCM' mode (0-128, default: 128).\n * tag the authentication tag to check if decrypting, as a\n * binary-encoded string of bytes.\n * output the output the buffer to write to, null to create one.\n */\nBlockCipher.prototype.start = function(options) {\n options = options || {};\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n opts.decrypt = this._decrypt;\n this._finish = false;\n this._input = forge.util.createBuffer();\n this.output = options.output || forge.util.createBuffer();\n this.mode.start(opts);\n};\n\n/**\n * Updates the next block according to the cipher mode.\n *\n * @param input the buffer to read from.\n */\nBlockCipher.prototype.update = function(input) {\n if(input) {\n // input given, so empty it into the input buffer\n this._input.putBuffer(input);\n }\n\n // do cipher operation until it needs more input and not finished\n while(!this._op.call(this.mode, this._input, this.output, this._finish) &&\n !this._finish) {}\n\n // free consumed memory from input buffer\n this._input.compact();\n};\n\n/**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use in CBC mode, null for default,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\nBlockCipher.prototype.finish = function(pad) {\n // backwards-compatibility w/deprecated padding API\n // Note: will overwrite padding functions even after another start() call\n if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {\n this.mode.pad = function(input) {\n return pad(this.blockSize, input, false);\n };\n this.mode.unpad = function(output) {\n return pad(this.blockSize, output, true);\n };\n }\n\n // build options for padding and afterFinish functions\n var options = {};\n options.decrypt = this._decrypt;\n\n // get # of bytes that won't fill a block\n options.overflow = this._input.length() % this.blockSize;\n\n if(!this._decrypt && this.mode.pad) {\n if(!this.mode.pad(this._input, options)) {\n return false;\n }\n }\n\n // do final update\n this._finish = true;\n this.update();\n\n if(this._decrypt && this.mode.unpad) {\n if(!this.mode.unpad(this.output, options)) {\n return false;\n }\n }\n\n if(this.mode.afterFinish) {\n if(!this.mode.afterFinish(this.output, options)) {\n return false;\n }\n }\n\n return true;\n};\n","/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n","/**\n * DES (Data Encryption Standard) implementation.\n *\n * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.\n * It is based on the BSD-licensed implementation by Paul Tero:\n *\n * Paul Tero, July 2001\n * http://www.tero.co.uk/des/\n *\n * Optimised for performance with large blocks by\n * Michael Hayworth, November 2001\n * http://www.netdealing.com\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* DES API */\nmodule.exports = forge.des = forge.des || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new DES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the DES algorithm object.\n */\nforge.des.Algorithm = function(name, mode) {\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 8,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this DES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.des.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = forge.util.createBuffer(options.key);\n if(this.name.indexOf('3DES') === 0) {\n if(key.length() !== 24) {\n throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);\n }\n }\n\n // do key expansion to 16 or 48 subkeys (single or triple DES)\n this._keys = _createKeys(key);\n this._init = true;\n};\n\n/** Register DES algorithms **/\n\nregisterAlgorithm('DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('DES-CTR', forge.cipher.modes.ctr);\n\nregisterAlgorithm('3DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('3DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('3DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('3DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('3DES-CTR', forge.cipher.modes.ctr);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.des.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** DES implementation **/\n\nvar spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\nvar spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\nvar spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\nvar spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\nvar spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\nvar spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\nvar spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\nvar spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n/**\n * Create necessary sub keys.\n *\n * @param key the 64-bit or 192-bit key.\n *\n * @return the expanded keys.\n */\nfunction _createKeys(key) {\n var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],\n pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],\n pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],\n pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],\n pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],\n pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],\n pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],\n pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],\n pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],\n pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],\n pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],\n pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],\n pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],\n pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];\n\n // how many iterations (1 for des, 3 for triple des)\n // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n var iterations = key.length() > 8 ? 3 : 1;\n\n // stores the return keys\n var keys = [];\n\n // now define the left shifts which need to be done\n var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n\n var n = 0, tmp;\n for(var j = 0; j < iterations; j++) {\n var left = key.getInt32();\n var right = key.getInt32();\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= tmp;\n left ^= (tmp << 2);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // right needs to be shifted and OR'd with last four bits of left\n tmp = (left << 8) | ((right >>> 20) & 0x000000f0);\n\n // left needs to be put upside down\n left = ((right << 24) | ((right << 8) & 0xff0000) |\n ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));\n right = tmp;\n\n // now go through and perform these shifts on the left and right keys\n for(var i = 0; i < shifts.length; ++i) {\n //shift the keys either one or two bits to the left\n if(shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n // now apply PC-2, in such a way that E is easier when encrypting or\n // decrypting this conversion will look like PC-2 except only the last 6\n // bits of each byte are used rather than 48 consecutive bits and the\n // order of lines will be according to how the S selection functions will\n // be applied: S2, S4, S6, S8, S1, S3, S5, S7\n var lefttmp = (\n pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |\n pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |\n pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |\n pc2bytes6[(left >>> 4) & 0xf]);\n var righttmp = (\n pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |\n pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |\n pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf]);\n tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;\n keys[n++] = lefttmp ^ tmp;\n keys[n++] = righttmp ^ (tmp << 16);\n }\n }\n\n return keys;\n}\n\n/**\n * Updates a single block (1 byte) using DES. The update will either\n * encrypt or decrypt the block.\n *\n * @param keys the expanded keys.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(keys, input, output, decrypt) {\n // set up loops for single or triple DES\n var iterations = keys.length === 32 ? 3 : 9;\n var looping;\n if(iterations === 3) {\n looping = decrypt ? [30, -2, -2] : [0, 32, 2];\n } else {\n looping = (decrypt ?\n [94, 62, -2, 32, 64, 2, 30, -2, -2] :\n [0, 32, 2, 62, 30, -2, 64, 96, 2]);\n }\n\n var tmp;\n\n var left = input[0];\n var right = input[1];\n\n // first each 64 bit chunk of the message must be permuted according to IP\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // rotate left 1 bit\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n for(var j = 0; j < iterations; j += 3) {\n var endloop = looping[j + 1];\n var loopinc = looping[j + 2];\n\n // now go through and perform the encryption or decryption\n for(var i = looping[j]; i != endloop; i += loopinc) {\n var right1 = right ^ keys[i];\n var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n\n // passing these bytes through the S selection functions\n tmp = left;\n left = right;\n right = tmp ^ (\n spfunction2[(right1 >>> 24) & 0x3f] |\n spfunction4[(right1 >>> 16) & 0x3f] |\n spfunction6[(right1 >>> 8) & 0x3f] |\n spfunction8[right1 & 0x3f] |\n spfunction1[(right2 >>> 24) & 0x3f] |\n spfunction3[(right2 >>> 16) & 0x3f] |\n spfunction5[(right2 >>> 8) & 0x3f] |\n spfunction7[right2 & 0x3f]);\n }\n // unreverse left and right\n tmp = left;\n left = right;\n right = tmp;\n }\n\n // rotate right 1 bit\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n // now perform IP-1, which is IP in the opposite direction\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n output[0] = left;\n output[1] = right;\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('DES-', key);\n * forge.cipher.createDecipher('DES-', key);\n *\n * Creates a deprecated DES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param options the options to use.\n * key the symmetric key to use (64 or 192 bits).\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'DES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * JavaScript implementation of Ed25519.\n *\n * Copyright (c) 2017-2019 Digital Bazaar, Inc.\n *\n * This implementation is based on the most excellent TweetNaCl which is\n * in the public domain. Many thanks to its contributors:\n *\n * https://github.com/dchest/tweetnacl-js\n */\nvar forge = require('./forge');\nrequire('./jsbn');\nrequire('./random');\nrequire('./sha512');\nrequire('./util');\nvar asn1Validator = require('./asn1-validator');\nvar publicKeyValidator = asn1Validator.publicKeyValidator;\nvar privateKeyValidator = asn1Validator.privateKeyValidator;\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar ByteBuffer = forge.util.ByteBuffer;\nvar NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer;\n\n/*\n * Ed25519 algorithms, see RFC 8032:\n * https://tools.ietf.org/html/rfc8032\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};\nvar ed25519 = forge.ed25519;\n\ned25519.constants = {};\ned25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;\ned25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;\ned25519.constants.SEED_BYTE_LENGTH = 32;\ned25519.constants.SIGN_BYTE_LENGTH = 64;\ned25519.constants.HASH_BYTE_LENGTH = 64;\n\ned25519.generateKeyPair = function(options) {\n options = options || {};\n var seed = options.seed;\n if(seed === undefined) {\n // generate seed\n seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);\n } else if(typeof seed === 'string') {\n if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {\n throw new TypeError(\n '\"seed\" must be ' + ed25519.constants.SEED_BYTE_LENGTH +\n ' bytes in length.');\n }\n } else if(!(seed instanceof Uint8Array)) {\n throw new TypeError(\n '\"seed\" must be a node.js Buffer, Uint8Array, or a binary string.');\n }\n\n seed = messageToNativeBuffer({message: seed, encoding: 'binary'});\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n for(var i = 0; i < 32; ++i) {\n sk[i] = seed[i];\n }\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, privateKey: sk};\n};\n\n/**\n * Converts a private key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a private key.\n *\n * @returns {Object} keyInfo - The key information.\n * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes.\n */\ned25519.privateKeyFromAsn1 = function(obj) {\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.privateKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var privateKey = capture.privateKey;\n // manually extract the private key bytes from nested octet string, see FIXME:\n // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542\n var privateKeyBytes = messageToNativeBuffer({\n message: forge.asn1.fromDer(privateKey).value,\n encoding: 'binary'\n });\n // TODO: RFC8410 specifies a format for encoding the public key bytes along\n // with the private key bytes. `publicKeyBytes` can be returned in the\n // future. https://tools.ietf.org/html/rfc8410#section-10.3\n return {privateKeyBytes: privateKeyBytes};\n};\n\n/**\n * Converts a public key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a public key.\n *\n * @return {Buffer|Uint8Array} - 32 public key bytes.\n */\ned25519.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.publicKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var publicKeyBytes = capture.ed25519PublicKey;\n if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new Error('Key length is invalid.');\n }\n return messageToNativeBuffer({\n message: publicKeyBytes,\n encoding: 'binary'\n });\n};\n\ned25519.publicKeyFromPrivateKey = function(options) {\n options = options || {};\n var privateKey = messageToNativeBuffer({\n message: options.privateKey, encoding: 'binary'\n });\n if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n for(var i = 0; i < pk.length; ++i) {\n pk[i] = privateKey[32 + i];\n }\n return pk;\n};\n\ned25519.sign = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n var privateKey = messageToNativeBuffer({\n message: options.privateKey,\n encoding: 'binary'\n });\n if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {\n var keyPair = ed25519.generateKeyPair({seed: privateKey});\n privateKey = keyPair.privateKey;\n } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.SEED_BYTE_LENGTH + ' or ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var signedMsg = new NativeBuffer(\n ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n crypto_sign(signedMsg, msg, msg.length, privateKey);\n\n var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);\n for(var i = 0; i < sig.length; ++i) {\n sig[i] = signedMsg[i];\n }\n return sig;\n};\n\ned25519.verify = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n if(options.signature === undefined) {\n throw new TypeError(\n '\"options.signature\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a binary string.');\n }\n var sig = messageToNativeBuffer({\n message: options.signature,\n encoding: 'binary'\n });\n if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.signature\" must have a byte length of ' +\n ed25519.constants.SIGN_BYTE_LENGTH);\n }\n var publicKey = messageToNativeBuffer({\n message: options.publicKey,\n encoding: 'binary'\n });\n if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.publicKey\" must have a byte length of ' +\n ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n }\n\n var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var i;\n for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) {\n sm[i] = sig[i];\n }\n for(i = 0; i < msg.length; ++i) {\n sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i];\n }\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nfunction messageToNativeBuffer(options) {\n var message = options.message;\n if(message instanceof Uint8Array || message instanceof NativeBuffer) {\n return message;\n }\n\n var encoding = options.encoding;\n if(message === undefined) {\n if(options.md) {\n // TODO: more rigorous validation that `md` is a MessageDigest\n message = options.md.digest().getBytes();\n encoding = 'binary';\n } else {\n throw new TypeError('\"options.message\" or \"options.md\" not specified.');\n }\n }\n\n if(typeof message === 'string' && !encoding) {\n throw new TypeError('\"options.encoding\" must be \"binary\" or \"utf8\".');\n }\n\n if(typeof message === 'string') {\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(message, encoding);\n }\n message = new ByteBuffer(message, encoding);\n } else if(!(message instanceof ByteBuffer)) {\n throw new TypeError(\n '\"options.message\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a string with \"options.encoding\" specifying its ' +\n 'encoding.');\n }\n\n // convert to native buffer\n var buffer = new NativeBuffer(message.length());\n for(var i = 0; i < buffer.length; ++i) {\n buffer[i] = message.at(i);\n }\n return buffer;\n}\n\nvar gf0 = gf();\nvar gf1 = gf([1]);\nvar D = gf([\n 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,\n 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);\nvar D2 = gf([\n 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,\n 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);\nvar X = gf([\n 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,\n 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);\nvar Y = gf([\n 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,\n 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);\nvar L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,\n 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\nvar I = gf([\n 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,\n 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\n// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`,\n// whichever is available, to improve performance\nfunction sha512(msg, msgLen) {\n // Note: `out` and `msg` are NativeBuffer\n var md = forge.md.sha512.create();\n var buffer = new ByteBuffer(msg);\n md.update(buffer.getBytes(msgLen), 'binary');\n var hash = md.digest().getBytes();\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(hash, 'binary');\n }\n var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);\n for(var i = 0; i < 64; ++i) {\n out[i] = hash.charCodeAt(i);\n }\n return out;\n}\n\nfunction crypto_sign_keypair(pk, sk) {\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for(i = 0; i < 32; ++i) {\n sk[i + 32] = pk[i];\n }\n return 0;\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for(i = 0; i < n; ++i) {\n sm[64 + i] = m[i];\n }\n for(i = 0; i < 32; ++i) {\n sm[32 + i] = d[32 + i];\n }\n\n var r = sha512(sm.subarray(32), n + 32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for(i = 32; i < 64; ++i) {\n sm[i] = sk[i];\n }\n var h = sha512(sm, n + 64);\n reduce(h);\n\n for(i = 32; i < 64; ++i) {\n x[i] = 0;\n }\n for(i = 0; i < 32; ++i) {\n x[i] = r[i];\n }\n for(i = 0; i < 32; ++i) {\n for(j = 0; j < 32; j++) {\n x[i + j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new NativeBuffer(32);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if(n < 64) {\n return -1;\n }\n\n if(unpackneg(q, pk)) {\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i];\n }\n for(i = 0; i < 32; ++i) {\n m[i + 32] = pk[i];\n }\n var h = sha512(m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if(crypto_verify_32(sm, 0, t, 0)) {\n for(i = 0; i < n; ++i) {\n m[i] = 0;\n }\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i + 64];\n }\n mlen = n;\n return mlen;\n}\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for(i = 63; i >= 32; --i) {\n carry = 0;\n for(j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for(j = 0; j < 32; ++j) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for(j = 0; j < 32; ++j) {\n x[j] -= carry * L[j];\n }\n for(i = 0; i < 32; ++i) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64);\n for(var i = 0; i < 64; ++i) {\n x[i] = r[i];\n r[i] = 0;\n }\n modL(r, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n for(var i = 0; i < 4; ++i) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for(i = 0; i < 16; ++i) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for(j = 0; j < 2; ++j) {\n m[0] = t[0] - 0xffed;\n for(i = 1; i < 15; ++i) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n M(r[0], r[0], I);\n }\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n return -1;\n }\n\n if(par25519(r[0]) === (p[31] >> 7)) {\n Z(r[0], gf0, r[0]);\n }\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for(i = 0; i < 16; ++i) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 250; a >= 0; --a) {\n S(c, c);\n if(a !== 1) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction neq25519(a, b) {\n var c = new NativeBuffer(32);\n var d = new NativeBuffer(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x, xi, y, yi, 32);\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i, d = 0;\n for(i = 0; i < n; ++i) {\n d |= x[xi + i] ^ y[yi + i];\n }\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction par25519(a) {\n var d = new NativeBuffer(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for(i = 255; i >= 0; --i) {\n b = (s[(i / 8)|0] >> (i & 7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction set25519(r, a) {\n var i;\n for(i = 0; i < 16; i++) {\n r[i] = a[i] | 0;\n }\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 253; a >= 0; --a) {\n S(c, c);\n if(a !== 2 && a !== 4) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for(i = 0; i < 16; ++i) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b - 1);\n for(var i = 0; i < 16; ++i) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction gf(init) {\n var i, r = new Float64Array(16);\n if(init) {\n for(i = 0; i < init.length; ++i) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\nfunction A(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction Z(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n","/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = {\n // default options\n options: {\n usePureJavaScript: false\n }\n};\n","/**\n * Hash-based Message Authentication Code implementation. Requires a message\n * digest object that can be obtained, for example, from forge.md.sha1 or\n * forge.md.md5.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\n/* HMAC API */\nvar hmac = module.exports = forge.hmac = forge.hmac || {};\n\n/**\n * Creates an HMAC object that uses the given message digest object.\n *\n * @return an HMAC object.\n */\nhmac.create = function() {\n // the hmac key to use\n var _key = null;\n\n // the message digest to use\n var _md = null;\n\n // the inner padding\n var _ipadding = null;\n\n // the outer padding\n var _opadding = null;\n\n // hmac context\n var ctx = {};\n\n /**\n * Starts or restarts the HMAC with the given key and message digest.\n *\n * @param md the message digest to use, null to reuse the previous one,\n * a string to use builtin 'sha1', 'md5', 'sha256'.\n * @param key the key to use as a string, array of bytes, byte buffer,\n * or null to reuse the previous key.\n */\n ctx.start = function(md, key) {\n if(md !== null) {\n if(typeof md === 'string') {\n // create builtin message digest\n md = md.toLowerCase();\n if(md in forge.md.algorithms) {\n _md = forge.md.algorithms[md].create();\n } else {\n throw new Error('Unknown hash algorithm \"' + md + '\"');\n }\n } else {\n // store message digest\n _md = md;\n }\n }\n\n if(key === null) {\n // reuse previous key\n key = _key;\n } else {\n if(typeof key === 'string') {\n // convert string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key)) {\n // convert byte array into byte buffer\n var tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // if key is longer than blocksize, hash it\n var keylen = key.length();\n if(keylen > _md.blockLength) {\n _md.start();\n _md.update(key.bytes());\n key = _md.digest();\n }\n\n // mix key into inner and outer padding\n // ipadding = [0x36 * blocksize] ^ key\n // opadding = [0x5C * blocksize] ^ key\n _ipadding = forge.util.createBuffer();\n _opadding = forge.util.createBuffer();\n keylen = key.length();\n for(var i = 0; i < keylen; ++i) {\n var tmp = key.at(i);\n _ipadding.putByte(0x36 ^ tmp);\n _opadding.putByte(0x5C ^ tmp);\n }\n\n // if key is shorter than blocksize, add additional padding\n if(keylen < _md.blockLength) {\n var tmp = _md.blockLength - keylen;\n for(var i = 0; i < tmp; ++i) {\n _ipadding.putByte(0x36);\n _opadding.putByte(0x5C);\n }\n }\n _key = key;\n _ipadding = _ipadding.bytes();\n _opadding = _opadding.bytes();\n }\n\n // digest is done like so: hash(opadding | hash(ipadding | message))\n\n // prepare to do inner hash\n // hash(ipadding | message)\n _md.start();\n _md.update(_ipadding);\n };\n\n /**\n * Updates the HMAC with the given message bytes.\n *\n * @param bytes the bytes to update with.\n */\n ctx.update = function(bytes) {\n _md.update(bytes);\n };\n\n /**\n * Produces the Message Authentication Code (MAC).\n *\n * @return a byte buffer containing the digest value.\n */\n ctx.getMac = function() {\n // digest is done like so: hash(opadding | hash(ipadding | message))\n // here we do the outer hashing\n var inner = _md.digest().bytes();\n _md.start();\n _md.update(_opadding);\n _md.update(inner);\n return _md.digest();\n };\n // alias for getMac\n ctx.digest = ctx.getMac;\n\n return ctx;\n};\n","/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = require('./forge');\nrequire('./aes');\nrequire('./aesCipherSuites');\nrequire('./asn1');\nrequire('./cipher');\nrequire('./des');\nrequire('./ed25519');\nrequire('./hmac');\nrequire('./kem');\nrequire('./log');\nrequire('./md.all');\nrequire('./mgf1');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./pkcs1');\nrequire('./pkcs12');\nrequire('./pkcs7');\nrequire('./pki');\nrequire('./prime');\nrequire('./prng');\nrequire('./pss');\nrequire('./random');\nrequire('./rc2');\nrequire('./ssh');\nrequire('./tls');\nrequire('./util');\n","// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n/*\nLicensing (LICENSE)\n-------------------\n\nThis software is covered under the following copyright:\n*/\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n/*\nAddress all questions regarding this license to:\n\n Tom Wu\n tjw@cs.Stanford.EDU\n*/\nvar forge = require('./forge');\n\nmodule.exports = forge.jsbn = forge.jsbn || {};\n\n// Bits per digit\nvar dbits;\n\n// JavaScript engine analysis\nvar canary = 0xdeadbeefcafe;\nvar j_lm = ((canary&0xffffff)==0xefcafe);\n\n// (public) Constructor\nfunction BigInteger(a,b,c) {\n this.data = [];\n if(a != null)\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\n else this.fromString(a,b);\n}\nforge.jsbn.BigInteger = BigInteger;\n\n// return new, unset BigInteger\nfunction nbi() { return new BigInteger(null); }\n\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i,x,w,j,c,n) {\n while(--n >= 0) {\n var v = x*this.data[i++]+w.data[j]+c;\n c = Math.floor(v/0x4000000);\n w.data[j++] = v&0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i,x,w,j,c,n) {\n var xl = x&0x7fff, xh = x>>15;\n while(--n >= 0) {\n var l = this.data[i]&0x7fff;\n var h = this.data[i++]>>15;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\n w.data[j++] = l&0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i,x,w,j,c,n) {\n var xl = x&0x3fff, xh = x>>14;\n while(--n >= 0) {\n var l = this.data[i]&0x3fff;\n var h = this.data[i++]>>14;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;\n c = (l>>28)+(m>>14)+xh*h;\n w.data[j++] = l&0xfffffff;\n }\n return c;\n}\n\n// node.js (no browser)\nif(typeof(navigator) === 'undefined')\n{\n BigInteger.prototype.am = am3;\n dbits = 28;\n} else if(j_lm && (navigator.appName == \"Microsoft Internet Explorer\")) {\n BigInteger.prototype.am = am2;\n dbits = 30;\n} else if(j_lm && (navigator.appName != \"Netscape\")) {\n BigInteger.prototype.am = am1;\n dbits = 26;\n} else { // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\n\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}\n\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = (x<0)?-1:0;\n if(x > 0) this.data[0] = x;\n else if(x < -1) this.data[0] = x+this.DV;\n else this.t = 0;\n}\n\n// return bigint initialized to value\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\n\n// (protected) set from string and radix\nfunction bnpFromString(s,b) {\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 256) k = 8; // byte array\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else { this.fromRadix(s,b); return; }\n this.t = 0;\n this.s = 0;\n var i = s.length, mi = false, sh = 0;\n while(--i >= 0) {\n var x = (k==8)?s[i]&0xff:intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\") mi = true;\n continue;\n }\n mi = false;\n if(sh == 0)\n this.data[this.t++] = x;\n else if(sh+k > this.DB) {\n this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));\n } else\n this.data[this.t-1] |= x<= this.DB) sh -= this.DB;\n }\n if(k == 8 && (s[0]&0x80) != 0) {\n this.s = -1;\n if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t;\n}\n\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if(this.s < 0) return \"-\"+this.negate().toString(b);\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else return this.toRadix(b);\n var km = (1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }\n while(i >= 0) {\n if(p < k) {\n d = (this.data[i]&((1<>(p+=this.DB-k);\n } else {\n d = (this.data[i]>>(p-=k))&km;\n if(p <= 0) { p += this.DB; --i; }\n }\n if(d > 0) m = true;\n if(m) r += int2char(d);\n }\n }\n return m?r:\"0\";\n}\n\n// (public) -this\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\n\n// (public) |this|\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\n\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n var r = this.s-a.s;\n if(r != 0) return r;\n var i = this.t;\n r = i-a.t;\n if(r != 0) return (this.s<0)?-r:r;\n while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;\n return 0;\n}\n\n// returns bit length of the integer x\nfunction nbits(x) {\n var r = 1, t;\n if((t=x>>>16) != 0) { x = t; r += 16; }\n if((t=x>>8) != 0) { x = t; r += 8; }\n if((t=x>>4) != 0) { x = t; r += 4; }\n if((t=x>>2) != 0) { x = t; r += 2; }\n if((t=x>>1) != 0) { x = t; r += 1; }\n return r;\n}\n\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if(this.t <= 0) return 0;\n return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));\n}\n\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n,r) {\n var i;\n for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];\n for(i = n-1; i >= 0; --i) r.data[i] = 0;\n r.t = this.t+n;\n r.s = this.s;\n}\n\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n,r) {\n for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];\n r.t = Math.max(this.t-n,0);\n r.s = this.s;\n}\n\n// (protected) r = this << n\nfunction bnpLShiftTo(n,r) {\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<= 0; --i) {\n r.data[i+ds+1] = (this.data[i]>>cbs)|c;\n c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0;\n r.data[ds] = c;\n r.t = this.t+ds+1;\n r.s = this.s;\n r.clamp();\n}\n\n// (protected) r = this >> n\nfunction bnpRShiftTo(n,r) {\n r.s = this.s;\n var ds = Math.floor(n/this.DB);\n if(ds >= this.t) { r.t = 0; return; }\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<>bs;\n for(var i = ds+1; i < this.t; ++i) {\n r.data[i-ds-1] |= (this.data[i]&bm)<>bs;\n }\n if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB;\n }\n if(a.t < this.t) {\n c -= a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n } else {\n c += this.s;\n while(i < a.t) {\n c -= a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = (c<0)?-1:0;\n if(c < -1) r.data[i++] = this.DV+c;\n else if(c > 0) r.data[i++] = c;\n r.t = i;\n r.clamp();\n}\n\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a,r) {\n var x = this.abs(), y = a.abs();\n var i = x.t;\n r.t = i+y.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);\n r.s = 0;\n r.clamp();\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\n}\n\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n var x = this.abs();\n var i = r.t = 2*x.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < x.t-1; ++i) {\n var c = x.am(i,x.data[i],r,2*i,0,1);\n if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\n r.data[i+x.t] -= x.DV;\n r.data[i+x.t+1] = 1;\n }\n }\n if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);\n r.s = 0;\n r.clamp();\n}\n\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m,q,r) {\n var pm = m.abs();\n if(pm.t <= 0) return;\n var pt = this.abs();\n if(pt.t < pm.t) {\n if(q != null) q.fromInt(0);\n if(r != null) this.copyTo(r);\n return;\n }\n if(r == null) r = nbi();\n var y = nbi(), ts = this.s, ms = m.s;\n var nsh = this.DB-nbits(pm.data[pm.t-1]);\t// normalize modulus\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }\n var ys = y.t;\n var y0 = y.data[ys-1];\n if(y0 == 0) return;\n var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0);\n var d1 = this.FV/yt, d2 = (1<= 0) {\n r.data[r.t++] = 1;\n r.subTo(t,r);\n }\n BigInteger.ONE.dlShiftTo(ys,t);\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\n while(y.t < ys) y.data[y.t++] = 0;\n while(--j >= 0) {\n // Estimate quotient digit\n var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);\n if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\n y.dlShiftTo(j,t);\n r.subTo(t,r);\n while(r.data[i] < --qd) r.subTo(t,r);\n }\n }\n if(q != null) {\n r.drShiftTo(ys,q);\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\n }\n r.t = ys;\n r.clamp();\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\n}\n\n// (public) this mod a\nfunction bnMod(a) {\n var r = nbi();\n this.abs().divRemTo(a,null,r);\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\n return r;\n}\n\n// Modular reduction using \"classic\" algorithm\nfunction Classic(m) { this.m = m; }\nfunction cConvert(x) {\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\n else return x;\n}\nfunction cRevert(x) { return x; }\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\nClassic.prototype.convert = cConvert;\nClassic.prototype.revert = cRevert;\nClassic.prototype.reduce = cReduce;\nClassic.prototype.mulTo = cMulTo;\nClassic.prototype.sqrTo = cSqrTo;\n\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if(this.t < 1) return 0;\n var x = this.data[0];\n if((x&1) == 0) return 0;\n var y = x&3;\t\t// y == 1/x mod 2^2\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return (y>0)?this.DV-y:-y;\n}\n\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp&0x7fff;\n this.mph = this.mp>>15;\n this.um = (1<<(m.DB-15))-1;\n this.mt2 = 2*m.t;\n}\n\n// xR mod m\nfunction montConvert(x) {\n var r = nbi();\n x.abs().dlShiftTo(this.m.t,r);\n r.divRemTo(this.m,null,r);\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\n return r;\n}\n\n// x/R mod m\nfunction montRevert(x) {\n var r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while(x.t <= this.mt2)\t// pad x so am has enough room later\n x.data[x.t++] = 0;\n for(var i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x.data[i]*mp mod DV\n var j = x.data[i]&0x7fff;\n var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i+this.m.t;\n x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);\n // propagate carry\n while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }\n }\n x.clamp();\n x.drShiftTo(this.m.t,x);\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n\n// (protected) true iff this is even\nfunction bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }\n\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\nfunction bnpExp(e,z) {\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\n g.copyTo(r);\n while(--i >= 0) {\n z.sqrTo(r,r2);\n if((e&(1< 0) z.mulTo(r2,g,r);\n else { var t = r; r = r2; r2 = t; }\n }\n return z.revert(r);\n}\n\n// (public) this^e % m, 0 <= e < 2^32\nfunction bnModPowInt(e,m) {\n var z;\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\n return this.exp(e,z);\n}\n\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.isEven = bnpIsEven;\nBigInteger.prototype.exp = bnpExp;\n\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.modPowInt = bnModPowInt;\n\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\n// jsbn2 lib\n\n//Copyright (c) 2005-2009 Tom Wu\n//All Rights Reserved.\n//See \"LICENSE\" for details (See jsbn.js for LICENSE).\n\n//Extended JavaScript BN functions, required for RSA private ops.\n\n//Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\n\n//(public)\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\n\n//(public) return value as integer\nfunction bnIntValue() {\nif(this.s < 0) {\n if(this.t == 1) return this.data[0]-this.DV;\n else if(this.t == 0) return -1;\n} else if(this.t == 1) return this.data[0];\nelse if(this.t == 0) return 0;\n// assumes 16 < DB < 32\nreturn ((this.data[1]&((1<<(32-this.DB))-1))<>24; }\n\n//(public) return value as short (assumes DB>=16)\nfunction bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }\n\n//(protected) return x s.t. r^x < DV\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\n\n//(public) 0 if this == 0, 1 if this > 0\nfunction bnSigNum() {\nif(this.s < 0) return -1;\nelse if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;\nelse return 1;\n}\n\n//(protected) convert to radix string\nfunction bnpToRadix(b) {\nif(b == null) b = 10;\nif(this.signum() == 0 || b < 2 || b > 36) return \"0\";\nvar cs = this.chunkSize(b);\nvar a = Math.pow(b,cs);\nvar d = nbv(a), y = nbi(), z = nbi(), r = \"\";\nthis.divRemTo(d,y,z);\nwhile(y.signum() > 0) {\n r = (a+z.intValue()).toString(b).substr(1) + r;\n y.divRemTo(d,y,z);\n}\nreturn z.intValue().toString(b) + r;\n}\n\n//(protected) convert from radix string\nfunction bnpFromRadix(s,b) {\nthis.fromInt(0);\nif(b == null) b = 10;\nvar cs = this.chunkSize(b);\nvar d = Math.pow(b,cs), mi = false, j = 0, w = 0;\nfor(var i = 0; i < s.length; ++i) {\n var x = intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\n continue;\n }\n w = b*w+x;\n if(++j >= cs) {\n this.dMultiply(d);\n this.dAddOffset(w,0);\n j = 0;\n w = 0;\n }\n}\nif(j > 0) {\n this.dMultiply(Math.pow(b,j));\n this.dAddOffset(w,0);\n}\nif(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n//(protected) alternate constructor\nfunction bnpFromNumber(a,b,c) {\nif(\"number\" == typeof b) {\n // new BigInteger(int,int,RNG)\n if(a < 2) this.fromInt(1);\n else {\n this.fromNumber(a,c);\n if(!this.testBit(a-1)) // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\n if(this.isEven()) this.dAddOffset(1,0); // force odd\n while(!this.isProbablePrime(b)) {\n this.dAddOffset(2,0);\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\n }\n }\n} else {\n // new BigInteger(int,RNG)\n var x = new Array(), t = a&7;\n x.length = (a>>3)+1;\n b.nextBytes(x);\n if(t > 0) x[0] &= ((1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)\n r[k++] = d|(this.s<<(this.DB-p));\n while(i >= 0) {\n if(p < 8) {\n d = (this.data[i]&((1<>(p+=this.DB-8);\n } else {\n d = (this.data[i]>>(p-=8))&0xff;\n if(p <= 0) { p += this.DB; --i; }\n }\n if((d&0x80) != 0) d |= -256;\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\n if(k > 0 || d != this.s) r[k++] = d;\n }\n}\nreturn r;\n}\n\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\n\n//(protected) r = this op a (bitwise)\nfunction bnpBitwiseTo(a,op,r) {\nvar i, f, m = Math.min(a.t,this.t);\nfor(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);\nif(a.t < this.t) {\n f = a.s&this.DM;\n for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);\n r.t = this.t;\n} else {\n f = this.s&this.DM;\n for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);\n r.t = a.t;\n}\nr.s = op(this.s,a.s);\nr.clamp();\n}\n\n//(public) this & a\nfunction op_and(x,y) { return x&y; }\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\n\n//(public) this | a\nfunction op_or(x,y) { return x|y; }\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\n\n//(public) this ^ a\nfunction op_xor(x,y) { return x^y; }\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\n\n//(public) this & ~a\nfunction op_andnot(x,y) { return x&~y; }\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\n\n//(public) ~this\nfunction bnNot() {\nvar r = nbi();\nfor(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];\nr.t = this.t;\nr.s = ~this.s;\nreturn r;\n}\n\n//(public) this << n\nfunction bnShiftLeft(n) {\nvar r = nbi();\nif(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\nreturn r;\n}\n\n//(public) this >> n\nfunction bnShiftRight(n) {\nvar r = nbi();\nif(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\nreturn r;\n}\n\n//return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x) {\nif(x == 0) return -1;\nvar r = 0;\nif((x&0xffff) == 0) { x >>= 16; r += 16; }\nif((x&0xff) == 0) { x >>= 8; r += 8; }\nif((x&0xf) == 0) { x >>= 4; r += 4; }\nif((x&3) == 0) { x >>= 2; r += 2; }\nif((x&1) == 0) ++r;\nreturn r;\n}\n\n//(public) returns index of lowest 1-bit (or -1 if none)\nfunction bnGetLowestSetBit() {\nfor(var i = 0; i < this.t; ++i)\n if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);\nif(this.s < 0) return this.t*this.DB;\nreturn -1;\n}\n\n//return number of 1 bits in x\nfunction cbit(x) {\nvar r = 0;\nwhile(x != 0) { x &= x-1; ++r; }\nreturn r;\n}\n\n//(public) return number of set bits\nfunction bnBitCount() {\nvar r = 0, x = this.s&this.DM;\nfor(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);\nreturn r;\n}\n\n//(public) true iff nth bit is set\nfunction bnTestBit(n) {\nvar j = Math.floor(n/this.DB);\nif(j >= this.t) return(this.s!=0);\nreturn((this.data[j]&(1<<(n%this.DB)))!=0);\n}\n\n//(protected) this op (1<>= this.DB;\n}\nif(a.t < this.t) {\n c += a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n} else {\n c += this.s;\n while(i < a.t) {\n c += a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += a.s;\n}\nr.s = (c<0)?-1:0;\nif(c > 0) r.data[i++] = c;\nelse if(c < -1) r.data[i++] = this.DV+c;\nr.t = i;\nr.clamp();\n}\n\n//(public) this + a\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\n\n//(public) this - a\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\n\n//(public) this * a\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\n\n//(public) this / a\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\n\n//(public) this % a\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\n\n//(public) [this/a,this%a]\nfunction bnDivideAndRemainder(a) {\nvar q = nbi(), r = nbi();\nthis.divRemTo(a,q,r);\nreturn new Array(q,r);\n}\n\n//(protected) this *= n, this >= 0, 1 < n < DV\nfunction bnpDMultiply(n) {\nthis.data[this.t] = this.am(0,n-1,this,0,0,this.t);\n++this.t;\nthis.clamp();\n}\n\n//(protected) this += n << w words, this >= 0\nfunction bnpDAddOffset(n,w) {\nif(n == 0) return;\nwhile(this.t <= w) this.data[this.t++] = 0;\nthis.data[w] += n;\nwhile(this.data[w] >= this.DV) {\n this.data[w] -= this.DV;\n if(++w >= this.t) this.data[this.t++] = 0;\n ++this.data[w];\n}\n}\n\n//A \"null\" reducer\nfunction NullExp() {}\nfunction nNop(x) { return x; }\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\nfunction nSqrTo(x,r) { x.squareTo(r); }\n\nNullExp.prototype.convert = nNop;\nNullExp.prototype.revert = nNop;\nNullExp.prototype.mulTo = nMulTo;\nNullExp.prototype.sqrTo = nSqrTo;\n\n//(public) this^e\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\n\n//(protected) r = lower n words of \"this * a\", a.t <= n\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyLowerTo(a,n,r) {\nvar i = Math.min(this.t+a.t,n);\nr.s = 0; // assumes a,this >= 0\nr.t = i;\nwhile(i > 0) r.data[--i] = 0;\nvar j;\nfor(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);\nfor(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);\nr.clamp();\n}\n\n//(protected) r = \"this * a\" without lower n words, n > 0\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyUpperTo(a,n,r) {\n--n;\nvar i = r.t = this.t+a.t-n;\nr.s = 0; // assumes a,this >= 0\nwhile(--i >= 0) r.data[i] = 0;\nfor(i = Math.max(n-this.t,0); i < a.t; ++i)\n r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);\nr.clamp();\nr.drShiftTo(1,r);\n}\n\n//Barrett modular reduction\nfunction Barrett(m) {\n// setup Barrett\nthis.r2 = nbi();\nthis.q3 = nbi();\nBigInteger.ONE.dlShiftTo(2*m.t,this.r2);\nthis.mu = this.r2.divide(m);\nthis.m = m;\n}\n\nfunction barrettConvert(x) {\nif(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\nelse if(x.compareTo(this.m) < 0) return x;\nelse { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\n}\n\nfunction barrettRevert(x) { return x; }\n\n//x = x mod m (HAC 14.42)\nfunction barrettReduce(x) {\nx.drShiftTo(this.m.t-1,this.r2);\nif(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\nthis.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\nthis.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\nwhile(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\nx.subTo(this.r2,x);\nwhile(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n//r = x^2 mod m; x != r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n//r = x*y mod m; x,y != r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nBarrett.prototype.convert = barrettConvert;\nBarrett.prototype.revert = barrettRevert;\nBarrett.prototype.reduce = barrettReduce;\nBarrett.prototype.mulTo = barrettMulTo;\nBarrett.prototype.sqrTo = barrettSqrTo;\n\n//(public) this^e % m (HAC 14.85)\nfunction bnModPow(e,m) {\nvar i = e.bitLength(), k, r = nbv(1), z;\nif(i <= 0) return r;\nelse if(i < 18) k = 1;\nelse if(i < 48) k = 3;\nelse if(i < 144) k = 4;\nelse if(i < 768) k = 5;\nelse k = 6;\nif(i < 8)\n z = new Classic(m);\nelse if(m.isEven())\n z = new Barrett(m);\nelse\n z = new Montgomery(m);\n\n// precomputation\nvar g = new Array(), n = 3, k1 = k-1, km = (1< 1) {\n var g2 = nbi();\n z.sqrTo(g[1],g2);\n while(n <= km) {\n g[n] = nbi();\n z.mulTo(g2,g[n-2],g[n]);\n n += 2;\n }\n}\n\nvar j = e.t-1, w, is1 = true, r2 = nbi(), t;\ni = nbits(e.data[j])-1;\nwhile(j >= 0) {\n if(i >= k1) w = (e.data[j]>>(i-k1))&km;\n else {\n w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);\n if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);\n }\n\n n = k;\n while((w&1) == 0) { w >>= 1; --n; }\n if((i -= n) < 0) { i += this.DB; --j; }\n if(is1) { // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n } else {\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\n z.mulTo(r2,g[w],r);\n }\n\n while(j >= 0 && (e.data[j]&(1< 0) {\n x.rShiftTo(g,x);\n y.rShiftTo(g,y);\n}\nwhile(x.signum() > 0) {\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\n if(x.compareTo(y) >= 0) {\n x.subTo(y,x);\n x.rShiftTo(1,x);\n } else {\n y.subTo(x,y);\n y.rShiftTo(1,y);\n }\n}\nif(g > 0) y.lShiftTo(g,y);\nreturn y;\n}\n\n//(protected) this % n, n < 2^26\nfunction bnpModInt(n) {\nif(n <= 0) return 0;\nvar d = this.DV%n, r = (this.s<0)?n-1:0;\nif(this.t > 0)\n if(d == 0) r = this.data[0]%n;\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;\nreturn r;\n}\n\n//(public) 1/this % m (HAC 14.61)\nfunction bnModInverse(m) {\nvar ac = m.isEven();\nif((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\nvar u = m.clone(), v = this.clone();\nvar a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\nwhile(u.signum() != 0) {\n while(u.isEven()) {\n u.rShiftTo(1,u);\n if(ac) {\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\n a.rShiftTo(1,a);\n } else if(!b.isEven()) b.subTo(m,b);\n b.rShiftTo(1,b);\n }\n while(v.isEven()) {\n v.rShiftTo(1,v);\n if(ac) {\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\n c.rShiftTo(1,c);\n } else if(!d.isEven()) d.subTo(m,d);\n d.rShiftTo(1,d);\n }\n if(u.compareTo(v) >= 0) {\n u.subTo(v,u);\n if(ac) a.subTo(c,a);\n b.subTo(d,b);\n } else {\n v.subTo(u,v);\n if(ac) c.subTo(a,c);\n d.subTo(b,d);\n }\n}\nif(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\nif(d.compareTo(m) >= 0) return d.subtract(m);\nif(d.signum() < 0) d.addTo(m,d); else return d;\nif(d.signum() < 0) return d.add(m); else return d;\n}\n\nvar lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\n\n//(public) test primality with certainty >= 1-.5^t\nfunction bnIsProbablePrime(t) {\nvar i, x = this.abs();\nif(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {\n for(i = 0; i < lowprimes.length; ++i)\n if(x.data[0] == lowprimes[i]) return true;\n return false;\n}\nif(x.isEven()) return false;\ni = 1;\nwhile(i < lowprimes.length) {\n var m = lowprimes[i], j = i+1;\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\n m = x.modInt(m);\n while(i < j) if(m%lowprimes[i++] == 0) return false;\n}\nreturn x.millerRabin(t);\n}\n\n//(protected) true if probably prime (HAC 4.24, Miller-Rabin)\nfunction bnpMillerRabin(t) {\nvar n1 = this.subtract(BigInteger.ONE);\nvar k = n1.getLowestSetBit();\nif(k <= 0) return false;\nvar r = n1.shiftRight(k);\nvar prng = bnGetPrng();\nvar a;\nfor(var i = 0; i < t; ++i) {\n // select witness 'a' at random from between 1 and n1\n do {\n a = new BigInteger(this.bitLength(), prng);\n }\n while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);\n var y = a.modPow(r,this);\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\n var j = 1;\n while(j++ < k && y.compareTo(n1) != 0) {\n y = y.modPowInt(2,this);\n if(y.compareTo(BigInteger.ONE) == 0) return false;\n }\n if(y.compareTo(n1) != 0) return false;\n }\n}\nreturn true;\n}\n\n// get pseudo random number generator\nfunction bnGetPrng() {\n // create prng with api that matches BigInteger secure random\n return {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n for(var i = 0; i < x.length; ++i) {\n x[i] = Math.floor(Math.random() * 0x0100);\n }\n }\n };\n}\n\n//protected\nBigInteger.prototype.chunkSize = bnpChunkSize;\nBigInteger.prototype.toRadix = bnpToRadix;\nBigInteger.prototype.fromRadix = bnpFromRadix;\nBigInteger.prototype.fromNumber = bnpFromNumber;\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\nBigInteger.prototype.changeBit = bnpChangeBit;\nBigInteger.prototype.addTo = bnpAddTo;\nBigInteger.prototype.dMultiply = bnpDMultiply;\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\nBigInteger.prototype.modInt = bnpModInt;\nBigInteger.prototype.millerRabin = bnpMillerRabin;\n\n//public\nBigInteger.prototype.clone = bnClone;\nBigInteger.prototype.intValue = bnIntValue;\nBigInteger.prototype.byteValue = bnByteValue;\nBigInteger.prototype.shortValue = bnShortValue;\nBigInteger.prototype.signum = bnSigNum;\nBigInteger.prototype.toByteArray = bnToByteArray;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.min = bnMin;\nBigInteger.prototype.max = bnMax;\nBigInteger.prototype.and = bnAnd;\nBigInteger.prototype.or = bnOr;\nBigInteger.prototype.xor = bnXor;\nBigInteger.prototype.andNot = bnAndNot;\nBigInteger.prototype.not = bnNot;\nBigInteger.prototype.shiftLeft = bnShiftLeft;\nBigInteger.prototype.shiftRight = bnShiftRight;\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\nBigInteger.prototype.bitCount = bnBitCount;\nBigInteger.prototype.testBit = bnTestBit;\nBigInteger.prototype.setBit = bnSetBit;\nBigInteger.prototype.clearBit = bnClearBit;\nBigInteger.prototype.flipBit = bnFlipBit;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.remainder = bnRemainder;\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\nBigInteger.prototype.modPow = bnModPow;\nBigInteger.prototype.modInverse = bnModInverse;\nBigInteger.prototype.pow = bnPow;\nBigInteger.prototype.gcd = bnGCD;\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\n\n//BigInteger interfaces not implemented in jsbn:\n\n//BigInteger(int signum, byte[] magnitude)\n//double doubleValue()\n//float floatValue()\n//int hashCode()\n//long longValue()\n//static BigInteger valueOf(long val)\n","/**\n * Javascript implementation of RSA-KEM.\n *\n * @author Lautaro Cozzani Rodriguez\n * @author Dave Longley\n *\n * Copyright (c) 2014 Lautaro Cozzani \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./jsbn');\n\nmodule.exports = forge.kem = forge.kem || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n/**\n * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2.\n */\nforge.kem.rsa = {};\n\n/**\n * Creates an RSA KEM API object for generating a secret asymmetric key.\n *\n * The symmetric key may be generated via a call to 'encrypt', which will\n * produce a ciphertext to be transmitted to the recipient and a key to be\n * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which\n * will produce the same secret key for the recipient to use to decrypt a\n * message that was encrypted with the secret key.\n *\n * @param kdf the KDF API to use (eg: new forge.kem.kdf1()).\n * @param options the options to use.\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n */\nforge.kem.rsa.create = function(kdf, options) {\n options = options || {};\n var prng = options.prng || forge.random;\n\n var kem = {};\n\n /**\n * Generates a secret key and its encapsulation.\n *\n * @param publicKey the RSA public key to encrypt with.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return an object with:\n * encapsulation: the ciphertext for generating the secret key, as a\n * binary-encoded string of bytes.\n * key: the secret key to use for encrypting a message.\n */\n kem.encrypt = function(publicKey, keyLength) {\n // generate a random r where 1 < r < n\n var byteLength = Math.ceil(publicKey.n.bitLength() / 8);\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(prng.getBytesSync(byteLength)),\n 16).mod(publicKey.n);\n } while(r.compareTo(BigInteger.ONE) <= 0);\n\n // prepend r with zeros\n r = forge.util.hexToBytes(r.toString(16));\n var zeros = byteLength - r.length;\n if(zeros > 0) {\n r = forge.util.fillString(String.fromCharCode(0), zeros) + r;\n }\n\n // encrypt the random\n var encapsulation = publicKey.encrypt(r, 'NONE');\n\n // generate the secret key\n var key = kdf.generate(r, keyLength);\n\n return {encapsulation: encapsulation, key: key};\n };\n\n /**\n * Decrypts an encapsulated secret key.\n *\n * @param privateKey the RSA private key to decrypt with.\n * @param encapsulation the ciphertext for generating the secret key, as\n * a binary-encoded string of bytes.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return the secret key as a binary-encoded string of bytes.\n */\n kem.decrypt = function(privateKey, encapsulation, keyLength) {\n // decrypt the encapsulation and generate the secret key\n var r = privateKey.decrypt(encapsulation, 'NONE');\n return kdf.generate(r, keyLength);\n };\n\n return kem;\n};\n\n// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API?\n\n/**\n * Creates a key derivation API object that implements KDF1 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF1 API object.\n */\nforge.kem.kdf1 = function(md, digestLength) {\n _createKDF(this, md, 0, digestLength || md.digestLength);\n};\n\n/**\n * Creates a key derivation API object that implements KDF2 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF2 API object.\n */\nforge.kem.kdf2 = function(md, digestLength) {\n _createKDF(this, md, 1, digestLength || md.digestLength);\n};\n\n/**\n * Creates a KDF1 or KDF2 API object.\n *\n * @param md the hash API to use.\n * @param counterStart the starting index for the counter.\n * @param digestLength the digest length to use.\n *\n * @return the KDF API object.\n */\nfunction _createKDF(kdf, md, counterStart, digestLength) {\n /**\n * Generate a key of the specified length.\n *\n * @param x the binary-encoded byte string to generate a key from.\n * @param length the number of bytes to generate (the size of the key).\n *\n * @return the key as a binary-encoded string.\n */\n kdf.generate = function(x, length) {\n var key = new forge.util.ByteBuffer();\n\n // run counter from counterStart to ceil(length / Hash.len)\n var k = Math.ceil(length / digestLength) + counterStart;\n\n var c = new forge.util.ByteBuffer();\n for(var i = counterStart; i < k; ++i) {\n // I2OSP(i, 4): convert counter to an octet string of 4 octets\n c.putInt32(i);\n\n // digest 'x' and the counter and add the result to the key\n md.start();\n md.update(x + c.getBytes());\n var hash = md.digest();\n key.putBytes(hash.getBytes(digestLength));\n }\n\n // truncate to the correct key length\n key.truncate(key.length() - length);\n return key.getBytes();\n };\n}\n","/**\n * Cross-browser support for logging in a web application.\n *\n * @author David I. Lehn \n *\n * Copyright (c) 2008-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n/* LOG API */\nmodule.exports = forge.log = forge.log || {};\n\n/**\n * Application logging system.\n *\n * Each logger level available as it's own function of the form:\n * forge.log.level(category, args...)\n * The category is an arbitrary string, and the args are the same as\n * Firebug's console.log API. By default the call will be output as:\n * 'LEVEL [category] , args[1], ...'\n * This enables proper % formatting via the first argument.\n * Each category is enabled by default but can be enabled or disabled with\n * the setCategoryEnabled() function.\n */\n// list of known levels\nforge.log.levels = [\n 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max'];\n// info on the levels indexed by name:\n// index: level index\n// name: uppercased display name\nvar sLevelInfo = {};\n// list of loggers\nvar sLoggers = [];\n/**\n * Standard console logger. If no console support is enabled this will\n * remain null. Check before using.\n */\nvar sConsoleLogger = null;\n\n// logger flags\n/**\n * Lock the level at the current value. Used in cases where user config may\n * set the level such that only critical messages are seen but more verbose\n * messages are needed for debugging or other purposes.\n */\nforge.log.LEVEL_LOCKED = (1 << 1);\n/**\n * Always call log function. By default, the logging system will check the\n * message level against logger.level before calling the log function. This\n * flag allows the function to do its own check.\n */\nforge.log.NO_LEVEL_CHECK = (1 << 2);\n/**\n * Perform message interpolation with the passed arguments. \"%\" style\n * fields in log messages will be replaced by arguments as needed. Some\n * loggers, such as Firebug, may do this automatically. The original log\n * message will be available as 'message' and the interpolated version will\n * be available as 'fullMessage'.\n */\nforge.log.INTERPOLATE = (1 << 3);\n\n// setup each log level\nfor(var i = 0; i < forge.log.levels.length; ++i) {\n var level = forge.log.levels[i];\n sLevelInfo[level] = {\n index: i,\n name: level.toUpperCase()\n };\n}\n\n/**\n * Message logger. Will dispatch a message to registered loggers as needed.\n *\n * @param message message object\n */\nforge.log.logMessage = function(message) {\n var messageLevelIndex = sLevelInfo[message.level].index;\n for(var i = 0; i < sLoggers.length; ++i) {\n var logger = sLoggers[i];\n if(logger.flags & forge.log.NO_LEVEL_CHECK) {\n logger.f(message);\n } else {\n // get logger level\n var loggerLevelIndex = sLevelInfo[logger.level].index;\n // check level\n if(messageLevelIndex <= loggerLevelIndex) {\n // message critical enough, call logger\n logger.f(logger, message);\n }\n }\n }\n};\n\n/**\n * Sets the 'standard' key on a message object to:\n * \"LEVEL [category] \" + message\n *\n * @param message a message log object\n */\nforge.log.prepareStandard = function(message) {\n if(!('standard' in message)) {\n message.standard =\n sLevelInfo[message.level].name +\n //' ' + +message.timestamp +\n ' [' + message.category + '] ' +\n message.message;\n }\n};\n\n/**\n * Sets the 'full' key on a message object to the original message\n * interpolated via % formatting with the message arguments.\n *\n * @param message a message log object.\n */\nforge.log.prepareFull = function(message) {\n if(!('full' in message)) {\n // copy args and insert message at the front\n var args = [message.message];\n args = args.concat([] || message['arguments']);\n // format the message\n message.full = forge.util.format.apply(this, args);\n }\n};\n\n/**\n * Applies both preparseStandard() and prepareFull() to a message object and\n * store result in 'standardFull'.\n *\n * @param message a message log object.\n */\nforge.log.prepareStandardFull = function(message) {\n if(!('standardFull' in message)) {\n // FIXME implement 'standardFull' logging\n forge.log.prepareStandard(message);\n message.standardFull = message.standard;\n }\n};\n\n// create log level functions\nif(true) {\n // levels for which we want functions\n var levels = ['error', 'warning', 'info', 'debug', 'verbose'];\n for(var i = 0; i < levels.length; ++i) {\n // wrap in a function to ensure proper level var is passed\n (function(level) {\n // create function for this level\n forge.log[level] = function(category, message/*, args...*/) {\n // convert arguments to real array, remove category and message\n var args = Array.prototype.slice.call(arguments).slice(2);\n // create message object\n // Note: interpolation and standard formatting is done lazily\n var msg = {\n timestamp: new Date(),\n level: level,\n category: category,\n message: message,\n 'arguments': args\n /*standard*/\n /*full*/\n /*fullMessage*/\n };\n // process this message\n forge.log.logMessage(msg);\n };\n })(levels[i]);\n }\n}\n\n/**\n * Creates a new logger with specified custom logging function.\n *\n * The logging function has a signature of:\n * function(logger, message)\n * logger: current logger\n * message: object:\n * level: level id\n * category: category\n * message: string message\n * arguments: Array of extra arguments\n * fullMessage: interpolated message and arguments if INTERPOLATE flag set\n *\n * @param logFunction a logging function which takes a log message object\n * as a parameter.\n *\n * @return a logger object.\n */\nforge.log.makeLogger = function(logFunction) {\n var logger = {\n flags: 0,\n f: logFunction\n };\n forge.log.setLevel(logger, 'none');\n return logger;\n};\n\n/**\n * Sets the current log level on a logger.\n *\n * @param logger the target logger.\n * @param level the new maximum log level as a string.\n *\n * @return true if set, false if not.\n */\nforge.log.setLevel = function(logger, level) {\n var rval = false;\n if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) {\n for(var i = 0; i < forge.log.levels.length; ++i) {\n var aValidLevel = forge.log.levels[i];\n if(level == aValidLevel) {\n // set level\n logger.level = level;\n rval = true;\n break;\n }\n }\n }\n\n return rval;\n};\n\n/**\n * Locks the log level at its current value.\n *\n * @param logger the target logger.\n * @param lock boolean lock value, default to true.\n */\nforge.log.lock = function(logger, lock) {\n if(typeof lock === 'undefined' || lock) {\n logger.flags |= forge.log.LEVEL_LOCKED;\n } else {\n logger.flags &= ~forge.log.LEVEL_LOCKED;\n }\n};\n\n/**\n * Adds a logger.\n *\n * @param logger the logger object.\n */\nforge.log.addLogger = function(logger) {\n sLoggers.push(logger);\n};\n\n// setup the console logger if possible, else create fake console.log\nif(typeof(console) !== 'undefined' && 'log' in console) {\n var logger;\n if(console.error && console.warn && console.info && console.debug) {\n // looks like Firebug-style logging is available\n // level handlers map\n var levelHandlers = {\n error: console.error,\n warning: console.warn,\n info: console.info,\n debug: console.debug,\n verbose: console.debug\n };\n var f = function(logger, message) {\n forge.log.prepareStandard(message);\n var handler = levelHandlers[message.level];\n // prepend standard message and concat args\n var args = [message.standard];\n args = args.concat(message['arguments'].slice());\n // apply to low-level console function\n handler.apply(console, args);\n };\n logger = forge.log.makeLogger(f);\n } else {\n // only appear to have basic console.log\n var f = function(logger, message) {\n forge.log.prepareStandardFull(message);\n console.log(message.standardFull);\n };\n logger = forge.log.makeLogger(f);\n }\n forge.log.setLevel(logger, 'debug');\n forge.log.addLogger(logger);\n sConsoleLogger = logger;\n} else {\n // define fake console.log to avoid potential script errors on\n // browsers that do not have console logging\n console = {\n log: function() {}\n };\n}\n\n/*\n * Check for logging control query vars in current URL.\n *\n * console.level=\n * Set's the console log level by name. Useful to override defaults and\n * allow more verbose logging before a user config is loaded.\n *\n * console.lock=\n * Lock the console log level at whatever level it is set at. This is run\n * after console.level is processed. Useful to force a level of verbosity\n * that could otherwise be limited by a user config.\n */\nif(sConsoleLogger !== null &&\n typeof window !== 'undefined' && window.location\n) {\n var query = new URL(window.location.href).searchParams;\n if(query.has('console.level')) {\n // set with last value\n forge.log.setLevel(\n sConsoleLogger, query.get('console.level').slice(-1)[0]);\n }\n if(query.has('console.lock')) {\n // set with last value\n var lock = query.get('console.lock').slice(-1)[0];\n if(lock == 'true') {\n forge.log.lock(sConsoleLogger);\n }\n }\n}\n\n// provide public access to console logger\nforge.log.consoleLogger = sConsoleLogger;\n","/**\n * Node.js module for all known Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nmodule.exports = require('./md');\n\nrequire('./md5');\nrequire('./sha1');\nrequire('./sha256');\nrequire('./sha512');\n","/**\n * Node.js module for Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nmodule.exports = forge.md = forge.md || {};\nforge.md.algorithms = forge.md.algorithms || {};\n","/**\n * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar md5 = module.exports = forge.md5 = forge.md5 || {};\nforge.md.md5 = forge.md.algorithms.md5 = md5;\n\n/**\n * Creates an MD5 message digest object.\n *\n * @return a message digest object.\n */\nmd5.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // MD5 state contains four 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(16);\n\n // message digest object\n var md = {\n algorithm: 'md5',\n blockLength: 64,\n digestLength: 16,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = (len[1] / 0x100000000) >>> 0;\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate MD5 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in little-endian order; since length\n // is stored in bytes we multiply by 8 and add carry\n var bits, carry = 0;\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n bits = md.fullMessageLength[i] * 8 + carry;\n carry = (bits / 0x100000000) >>> 0;\n finalBlock.putInt32Le(bits >>> 0);\n }\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32Le(s2.h0);\n rval.putInt32Le(s2.h1);\n rval.putInt32Le(s2.h2);\n rval.putInt32Le(s2.h3);\n return rval;\n };\n\n return md;\n};\n\n// padding, constant tables for calculating md5\nvar _padding = null;\nvar _g = null;\nvar _r = null;\nvar _k = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // g values\n _g = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12,\n 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2,\n 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9];\n\n // rounds table\n _r = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];\n\n // get the result of abs(sin(i + 1)) as a 32-bit integer\n _k = new Array(64);\n for(var i = 0; i < 64; ++i) {\n _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000);\n }\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates an MD5 state with the given byte buffer.\n *\n * @param s the MD5 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, f, r, i;\n var len = bytes.length();\n while(len >= 64) {\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32Le();\n f = d ^ (b & (c ^ d));\n t = (a + f + _k[i] + w[i]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 2\n for(; i < 32; ++i) {\n f = c ^ (d & (b ^ c));\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 3\n for(; i < 48; ++i) {\n f = b ^ c ^ d;\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 4\n for(; i < 64; ++i) {\n f = c ^ (b | ~d);\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Node.js module for Forge mask generation functions.\n *\n * @author Stefan Siegl\n *\n * Copyright 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./mgf1');\n\nmodule.exports = forge.mgf = forge.mgf || {};\nforge.mgf.mgf1 = forge.mgf1;\n","/**\n * Javascript implementation of mask generation function MGF1.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.mgf = forge.mgf || {};\nvar mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};\n\n/**\n * Creates a MGF1 mask generation function object.\n *\n * @param md the message digest API to use (eg: forge.md.sha1.create()).\n *\n * @return a mask generation function object.\n */\nmgf1.create = function(md) {\n var mgf = {\n /**\n * Generate mask of specified length.\n *\n * @param {String} seed The seed for mask generation.\n * @param maskLen Number of bytes to generate.\n * @return {String} The generated mask.\n */\n generate: function(seed, maskLen) {\n /* 2. Let T be the empty octet string. */\n var t = new forge.util.ByteBuffer();\n\n /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */\n var len = Math.ceil(maskLen / md.digestLength);\n for(var i = 0; i < len; i++) {\n /* a. Convert counter to an octet string C of length 4 octets */\n var c = new forge.util.ByteBuffer();\n c.putInt32(i);\n\n /* b. Concatenate the hash of the seed mgfSeed and C to the octet\n * string T: */\n md.start();\n md.update(seed + c.getBytes());\n t.putBuffer(md.digest());\n }\n\n /* Output the leading maskLen octets of T as the octet string mask. */\n t.truncate(t.length() - maskLen);\n return t.getBytes();\n }\n };\n\n return mgf;\n};\n","/**\n * Object IDs for ASN.1.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nforge.pki = forge.pki || {};\nvar oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};\n\n// set id to name mapping and name to id mapping\nfunction _IN(id, name) {\n oids[id] = name;\n oids[name] = id;\n}\n// set id to name mapping only\nfunction _I_(id, name) {\n oids[id] = name;\n}\n\n// algorithm OIDs\n_IN('1.2.840.113549.1.1.1', 'rsaEncryption');\n// Note: md2 & md4 not implemented\n//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');\n//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');\n_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');\n_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');\n_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');\n_IN('1.2.840.113549.1.1.8', 'mgf1');\n_IN('1.2.840.113549.1.1.9', 'pSpecified');\n_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');\n_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');\n_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');\n_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');\n// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519\n_IN('1.3.101.112', 'EdDSA25519');\n\n_IN('1.2.840.10040.4.3', 'dsa-with-sha1');\n\n_IN('1.3.14.3.2.7', 'desCBC');\n\n_IN('1.3.14.3.2.26', 'sha1');\n// Deprecated equivalent of sha1WithRSAEncryption\n_IN('1.3.14.3.2.29', 'sha1WithRSASignature');\n_IN('2.16.840.1.101.3.4.2.1', 'sha256');\n_IN('2.16.840.1.101.3.4.2.2', 'sha384');\n_IN('2.16.840.1.101.3.4.2.3', 'sha512');\n_IN('2.16.840.1.101.3.4.2.4', 'sha224');\n_IN('2.16.840.1.101.3.4.2.5', 'sha512-224');\n_IN('2.16.840.1.101.3.4.2.6', 'sha512-256');\n_IN('1.2.840.113549.2.2', 'md2');\n_IN('1.2.840.113549.2.5', 'md5');\n\n// pkcs#7 content types\n_IN('1.2.840.113549.1.7.1', 'data');\n_IN('1.2.840.113549.1.7.2', 'signedData');\n_IN('1.2.840.113549.1.7.3', 'envelopedData');\n_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');\n_IN('1.2.840.113549.1.7.5', 'digestedData');\n_IN('1.2.840.113549.1.7.6', 'encryptedData');\n\n// pkcs#9 oids\n_IN('1.2.840.113549.1.9.1', 'emailAddress');\n_IN('1.2.840.113549.1.9.2', 'unstructuredName');\n_IN('1.2.840.113549.1.9.3', 'contentType');\n_IN('1.2.840.113549.1.9.4', 'messageDigest');\n_IN('1.2.840.113549.1.9.5', 'signingTime');\n_IN('1.2.840.113549.1.9.6', 'counterSignature');\n_IN('1.2.840.113549.1.9.7', 'challengePassword');\n_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');\n_IN('1.2.840.113549.1.9.14', 'extensionRequest');\n\n_IN('1.2.840.113549.1.9.20', 'friendlyName');\n_IN('1.2.840.113549.1.9.21', 'localKeyId');\n_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');\n\n// pkcs#12 safe bags\n_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');\n_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');\n_IN('1.2.840.113549.1.12.10.1.3', 'certBag');\n_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');\n_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');\n_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');\n\n// password-based-encryption for pkcs#12\n_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');\n_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');\n\n_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');\n_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');\n_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');\n_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');\n\n// hmac OIDs\n_IN('1.2.840.113549.2.7', 'hmacWithSHA1');\n_IN('1.2.840.113549.2.8', 'hmacWithSHA224');\n_IN('1.2.840.113549.2.9', 'hmacWithSHA256');\n_IN('1.2.840.113549.2.10', 'hmacWithSHA384');\n_IN('1.2.840.113549.2.11', 'hmacWithSHA512');\n\n// symmetric key algorithm oids\n_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');\n_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');\n_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');\n_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');\n\n// certificate issuer/subject OIDs\n_IN('2.5.4.3', 'commonName');\n_IN('2.5.4.4', 'surname');\n_IN('2.5.4.5', 'serialNumber');\n_IN('2.5.4.6', 'countryName');\n_IN('2.5.4.7', 'localityName');\n_IN('2.5.4.8', 'stateOrProvinceName');\n_IN('2.5.4.9', 'streetAddress');\n_IN('2.5.4.10', 'organizationName');\n_IN('2.5.4.11', 'organizationalUnitName');\n_IN('2.5.4.12', 'title');\n_IN('2.5.4.13', 'description');\n_IN('2.5.4.15', 'businessCategory');\n_IN('2.5.4.17', 'postalCode');\n_IN('2.5.4.42', 'givenName');\n_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');\n_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');\n\n// X.509 extension OIDs\n_IN('2.16.840.1.113730.1.1', 'nsCertType');\n_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used\n_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35\n_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15\n_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32\n_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15\n_I_('2.5.29.5', 'policyMapping'); // deprecated use .33\n_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30\n_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17\n_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18\n_I_('2.5.29.9', 'subjectDirectoryAttributes');\n_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19\n_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30\n_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36\n_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19\n_IN('2.5.29.14', 'subjectKeyIdentifier');\n_IN('2.5.29.15', 'keyUsage');\n_I_('2.5.29.16', 'privateKeyUsagePeriod');\n_IN('2.5.29.17', 'subjectAltName');\n_IN('2.5.29.18', 'issuerAltName');\n_IN('2.5.29.19', 'basicConstraints');\n_I_('2.5.29.20', 'cRLNumber');\n_I_('2.5.29.21', 'cRLReason');\n_I_('2.5.29.22', 'expirationDate');\n_I_('2.5.29.23', 'instructionCode');\n_I_('2.5.29.24', 'invalidityDate');\n_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31\n_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28\n_I_('2.5.29.27', 'deltaCRLIndicator');\n_I_('2.5.29.28', 'issuingDistributionPoint');\n_I_('2.5.29.29', 'certificateIssuer');\n_I_('2.5.29.30', 'nameConstraints');\n_IN('2.5.29.31', 'cRLDistributionPoints');\n_IN('2.5.29.32', 'certificatePolicies');\n_I_('2.5.29.33', 'policyMappings');\n_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36\n_IN('2.5.29.35', 'authorityKeyIdentifier');\n_I_('2.5.29.36', 'policyConstraints');\n_IN('2.5.29.37', 'extKeyUsage');\n_I_('2.5.29.46', 'freshestCRL');\n_I_('2.5.29.54', 'inhibitAnyPolicy');\n\n// extKeyUsage purposes\n_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');\n_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');\n_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');\n_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');\n_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');\n_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');\n_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');\n","/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * An EncryptedPrivateKeyInfo:\n *\n * EncryptedPrivateKeyInfo ::= SEQUENCE {\n * encryptionAlgorithm EncryptionAlgorithmIdentifier,\n * encryptedData EncryptedData }\n *\n * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedData ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./oids');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./random');\nrequire('./rc2');\nrequire('./rsa');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Password-based encryption implementation. */\nvar pki = forge.pki = forge.pki || {};\nmodule.exports = pki.pbe = forge.pbe = forge.pbe || {};\nvar oids = pki.oids;\n\n// validator for an EncryptedPrivateKeyInfo structure\n// Note: Currently only works w/algorithm params\nvar encryptedPrivateKeyValidator = {\n name: 'EncryptedPrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encryptionOid'\n }, {\n name: 'AlgorithmIdentifier.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'encryptionParams'\n }]\n }, {\n // encryptedData\n name: 'EncryptedPrivateKeyInfo.encryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encryptedData'\n }]\n};\n\n// validator for a PBES2Algorithms structure\n// Note: Currently only works w/PBKDF2 + AES encryption schemes\nvar PBES2AlgorithmsValidator = {\n name: 'PBES2Algorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'kdfOid'\n }, {\n name: 'PBES2Algorithms.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.params.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'kdfSalt'\n }, {\n name: 'PBES2Algorithms.params.iterationCount',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'kdfIterationCount'\n }, {\n name: 'PBES2Algorithms.params.keyLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'keyLength'\n }, {\n // prf\n name: 'PBES2Algorithms.params.prf',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'PBES2Algorithms.params.prf.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'prfOid'\n }]\n }]\n }]\n }, {\n name: 'PBES2Algorithms.encryptionScheme',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.encryptionScheme.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encOid'\n }, {\n name: 'PBES2Algorithms.encryptionScheme.iv',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encIv'\n }]\n }]\n};\n\nvar pkcs12PbeParamsValidator = {\n name: 'pkcs-12PbeParams',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'pkcs-12PbeParams.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'salt'\n }, {\n name: 'pkcs-12PbeParams.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'iterations'\n }]\n};\n\n/**\n * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.\n *\n * PBES2Algorithms ALGORITHM-IDENTIFIER ::=\n * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}\n *\n * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}\n *\n * PBES2-params ::= SEQUENCE {\n * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n * }\n *\n * PBES2-KDFs ALGORITHM-IDENTIFIER ::=\n * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }\n *\n * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }\n *\n * PBKDF2-params ::= SEQUENCE {\n * salt CHOICE {\n * specified OCTET STRING,\n * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}\n * },\n * iterationCount INTEGER (1..MAX),\n * keyLength INTEGER (1..MAX) OPTIONAL,\n * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1\n * }\n *\n * @param obj the ASN.1 PrivateKeyInfo object.\n * @param password the password to encrypt with.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * prfAlgorithm the PRF message digest algorithm to use\n * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptPrivateKeyInfo = function(obj, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || 'aes128';\n options.prfAlgorithm = options.prfAlgorithm || 'sha1';\n\n // generate PBE params\n var salt = forge.random.getBytesSync(options.saltSize);\n var count = options.count;\n var countBytes = asn1.integerToDer(count);\n var dkLen;\n var encryptionAlgorithm;\n var encryptedData;\n if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {\n // do PBES2\n var ivLen, encOid, cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n dkLen = 16;\n ivLen = 16;\n encOid = oids['aes128-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n dkLen = 24;\n ivLen = 16;\n encOid = oids['aes192-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n dkLen = 32;\n ivLen = 16;\n encOid = oids['aes256-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'des':\n dkLen = 8;\n ivLen = 8;\n encOid = oids['desCBC'];\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // get PRF message digest\n var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();\n var md = prfAlgorithmToMessageDigest(prfAlgorithm);\n\n // encrypt private key using pbe SHA-1 and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = forge.random.getBytesSync(ivLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n // get PBKDF2-params\n var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // keyDerivationFunc\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),\n // PBKDF2-params\n params\n ]),\n // encryptionScheme\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(encOid).getBytes()),\n // iv\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)\n ])\n ])\n ]);\n } else if(options.algorithm === '3des') {\n // Do PKCS12 PBE\n dkLen = 24;\n\n var saltBytes = new forge.util.ByteBuffer(salt);\n var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);\n var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);\n var cipher = forge.des.createEncryptionCipher(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),\n // pkcs-12PbeParams\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ])\n ]);\n } else {\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // EncryptedPrivateKeyInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // encryptionAlgorithm\n encryptionAlgorithm,\n // encryptedData\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)\n ]);\n return rval;\n};\n\n/**\n * Decrypts a ASN.1 PrivateKeyInfo object.\n *\n * @param obj the ASN.1 EncryptedPrivateKeyInfo object.\n * @param password the password to decrypt with.\n *\n * @return the ASN.1 PrivateKeyInfo on success, null on failure.\n */\npki.decryptPrivateKeyInfo = function(obj, password) {\n var rval = null;\n\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // get cipher\n var oid = asn1.derToOid(capture.encryptionOid);\n var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);\n\n // get encrypted data\n var encrypted = forge.util.createBuffer(capture.encryptedData);\n\n cipher.update(encrypted);\n if(cipher.finish()) {\n rval = asn1.fromDer(cipher.output);\n }\n\n return rval;\n};\n\n/**\n * Converts a EncryptedPrivateKeyInfo to PEM format.\n *\n * @param epki the EncryptedPrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted encrypted private key.\n */\npki.encryptedPrivateKeyToPem = function(epki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'ENCRYPTED PRIVATE KEY',\n body: asn1.toDer(epki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption\n * is not performed.\n *\n * @param pem the EncryptedPrivateKeyInfo in PEM-format.\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptedPrivateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY') {\n var error = new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM header type is \"ENCRYPTED PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n return asn1.fromDer(msg.body);\n};\n\n/**\n * Encrypts an RSA private key. By default, the key will be wrapped in\n * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.\n * This is the standard, preferred way to encrypt a private key.\n *\n * To produce a non-standard PEM-encrypted private key that uses encapsulated\n * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL\n * private key encryption), set the 'legacy' option to true. Note: Using this\n * option will cause the iteration count to be forced to 1.\n *\n * Note: The 'des' algorithm is supported, but it is not considered to be\n * secure because it only uses a single 56-bit key. If possible, it is highly\n * recommended that a different algorithm be used.\n *\n * @param rsaKey the RSA key to encrypt.\n * @param password the password to use.\n * @param options:\n * algorithm: the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des', 'des').\n * count: the iteration count to use.\n * saltSize: the salt size to use.\n * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated\n * headers (DEK-Info) private key.\n *\n * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptRsaPrivateKey = function(rsaKey, password, options) {\n // standard PKCS#8\n options = options || {};\n if(!options.legacy) {\n // encrypt PrivateKeyInfo\n var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));\n rval = pki.encryptPrivateKeyInfo(rval, password, options);\n return pki.encryptedPrivateKeyToPem(rval);\n }\n\n // legacy non-PKCS#8\n var algorithm;\n var iv;\n var dkLen;\n var cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n algorithm = 'AES-128-CBC';\n dkLen = 16;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n algorithm = 'AES-192-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n algorithm = 'AES-256-CBC';\n dkLen = 32;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case '3des':\n algorithm = 'DES-EDE3-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n case 'des':\n algorithm = 'DES-CBC';\n dkLen = 8;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Could not encrypt RSA private key; unsupported ' +\n 'encryption algorithm \"' + options.algorithm + '\".');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // encrypt private key using OpenSSL legacy key derivation\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));\n cipher.finish();\n\n var msg = {\n type: 'RSA PRIVATE KEY',\n procType: {\n version: '4',\n type: 'ENCRYPTED'\n },\n dekInfo: {\n algorithm: algorithm,\n parameters: forge.util.bytesToHex(iv).toUpperCase()\n },\n body: cipher.output.getBytes()\n };\n return forge.pem.encode(msg);\n};\n\n/**\n * Decrypts an RSA private key.\n *\n * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.\n * @param password the password to use.\n *\n * @return the RSA key on success, null on failure.\n */\npki.decryptRsaPrivateKey = function(pem, password) {\n var rval = null;\n\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&\n msg.type !== 'PRIVATE KEY' &&\n msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM header type ' +\n 'is not \"ENCRYPTED PRIVATE KEY\", \"PRIVATE KEY\", or \"RSA PRIVATE KEY\".');\n error.headerType = error;\n throw error;\n }\n\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n var dkLen;\n var cipherFn;\n switch(msg.dekInfo.algorithm) {\n case 'DES-CBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'DES-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'AES-128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'RC2-40-CBC':\n dkLen = 5;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 40);\n };\n break;\n case 'RC2-64-CBC':\n dkLen = 8;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 64);\n };\n break;\n case 'RC2-128-CBC':\n dkLen = 16;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 128);\n };\n break;\n default:\n var error = new Error('Could not decrypt private key; unsupported ' +\n 'encryption algorithm \"' + msg.dekInfo.algorithm + '\".');\n error.algorithm = msg.dekInfo.algorithm;\n throw error;\n }\n\n // use OpenSSL legacy key derivation\n var iv = forge.util.hexToBytes(msg.dekInfo.parameters);\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(forge.util.createBuffer(msg.body));\n if(cipher.finish()) {\n rval = cipher.output.getBytes();\n } else {\n return rval;\n }\n } else {\n rval = msg.body;\n }\n\n if(msg.type === 'ENCRYPTED PRIVATE KEY') {\n rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);\n } else {\n // decryption already performed above\n rval = asn1.fromDer(rval);\n }\n\n if(rval !== null) {\n rval = pki.privateKeyFromAsn1(rval);\n }\n\n return rval;\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\npki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {\n var j, l;\n\n if(typeof md === 'undefined' || md === null) {\n if(!('sha1' in forge.md)) {\n throw new Error('\"sha1\" hash algorithm unavailable.');\n }\n md = forge.md.sha1.create();\n }\n\n var u = md.digestLength;\n var v = md.blockLength;\n var result = new forge.util.ByteBuffer();\n\n /* Convert password to Unicode byte buffer + trailing 0-byte. */\n var passBuf = new forge.util.ByteBuffer();\n if(password !== null && password !== undefined) {\n for(l = 0; l < password.length; l++) {\n passBuf.putInt16(password.charCodeAt(l));\n }\n passBuf.putInt16(0);\n }\n\n /* Length of salt and password in BYTES. */\n var p = passBuf.length();\n var s = salt.length();\n\n /* 1. Construct a string, D (the \"diversifier\"), by concatenating\n v copies of ID. */\n var D = new forge.util.ByteBuffer();\n D.fillWithByte(id, v);\n\n /* 2. Concatenate copies of the salt together to create a string S of length\n v * ceil(s / v) bytes (the final copy of the salt may be trunacted\n to create S).\n Note that if the salt is the empty string, then so is S. */\n var Slen = v * Math.ceil(s / v);\n var S = new forge.util.ByteBuffer();\n for(l = 0; l < Slen; l++) {\n S.putByte(salt.at(l % s));\n }\n\n /* 3. Concatenate copies of the password together to create a string P of\n length v * ceil(p / v) bytes (the final copy of the password may be\n truncated to create P).\n Note that if the password is the empty string, then so is P. */\n var Plen = v * Math.ceil(p / v);\n var P = new forge.util.ByteBuffer();\n for(l = 0; l < Plen; l++) {\n P.putByte(passBuf.at(l % p));\n }\n\n /* 4. Set I=S||P to be the concatenation of S and P. */\n var I = S;\n I.putBuffer(P);\n\n /* 5. Set c=ceil(n / u). */\n var c = Math.ceil(n / u);\n\n /* 6. For i=1, 2, ..., c, do the following: */\n for(var i = 1; i <= c; i++) {\n /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */\n var buf = new forge.util.ByteBuffer();\n buf.putBytes(D.bytes());\n buf.putBytes(I.bytes());\n for(var round = 0; round < iter; round++) {\n md.start();\n md.update(buf.getBytes());\n buf = md.digest();\n }\n\n /* b) Concatenate copies of Ai to create a string B of length v bytes (the\n final copy of Ai may be truncated to create B). */\n var B = new forge.util.ByteBuffer();\n for(l = 0; l < v; l++) {\n B.putByte(buf.at(l % u));\n }\n\n /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,\n where k=ceil(s / v) + ceil(p / v), modify I by setting\n Ij=(Ij+B+1) mod 2v for each j. */\n var k = Math.ceil(s / v) + Math.ceil(p / v);\n var Inew = new forge.util.ByteBuffer();\n for(j = 0; j < k; j++) {\n var chunk = new forge.util.ByteBuffer(I.getBytes(v));\n var x = 0x1ff;\n for(l = B.length() - 1; l >= 0; l--) {\n x = x >> 8;\n x += B.at(l) + chunk.at(l);\n chunk.setAt(l, x & 0xff);\n }\n Inew.putBuffer(chunk);\n }\n I = Inew;\n\n /* Add Ai to A. */\n result.putBuffer(buf);\n }\n\n result.truncate(result.length() - n);\n return result;\n};\n\n/**\n * Get new Forge cipher object instance.\n *\n * @param oid the OID (in string notation).\n * @param params the ASN.1 params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipher = function(oid, params, password) {\n switch(oid) {\n case pki.oids['pkcs5PBES2']:\n return pki.pbe.getCipherForPBES2(oid, params, password);\n\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n return pki.pbe.getCipherForPKCS12PBE(oid, params, password);\n\n default:\n var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');\n error.oid = oid;\n error.supportedOids = [\n 'pkcs5PBES2',\n 'pbeWithSHAAnd3-KeyTripleDES-CBC',\n 'pbewithSHAAnd40BitRC2-CBC'\n ];\n throw error;\n }\n};\n\n/**\n * Get new Forge cipher object instance according to PBES2 params block.\n *\n * The returned cipher instance is already started using the IV\n * from PBES2 parameter block.\n *\n * @param oid the PKCS#5 PBKDF2 OID (in string notation).\n * @param params the ASN.1 PBES2-params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipherForPBES2 = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // check oids\n oid = asn1.derToOid(capture.kdfOid);\n if(oid !== pki.oids['pkcs5PBKDF2']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported key derivation function OID.');\n error.oid = oid;\n error.supportedOids = ['pkcs5PBKDF2'];\n throw error;\n }\n oid = asn1.derToOid(capture.encOid);\n if(oid !== pki.oids['aes128-CBC'] &&\n oid !== pki.oids['aes192-CBC'] &&\n oid !== pki.oids['aes256-CBC'] &&\n oid !== pki.oids['des-EDE3-CBC'] &&\n oid !== pki.oids['desCBC']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported encryption scheme OID.');\n error.oid = oid;\n error.supportedOids = [\n 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];\n throw error;\n }\n\n // set PBE params\n var salt = capture.kdfSalt;\n var count = forge.util.createBuffer(capture.kdfIterationCount);\n count = count.getInt(count.length() << 3);\n var dkLen;\n var cipherFn;\n switch(pki.oids[oid]) {\n case 'aes128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'des-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'desCBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n\n // decrypt private key using pbe with chosen PRF and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = capture.encIv;\n var cipher = cipherFn(dk);\n cipher.start(iv);\n\n return cipher;\n};\n\n/**\n * Get new Forge cipher object instance for PKCS#12 PBE.\n *\n * The returned cipher instance is already started using the key & IV\n * derived from the provided password and PKCS#12 PBE salt.\n *\n * @param oid The PKCS#12 PBE OID (in string notation).\n * @param params The ASN.1 PKCS#12 PBE-params object.\n * @param password The password to decrypt with.\n *\n * @return the new cipher object instance.\n */\npki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n var salt = forge.util.createBuffer(capture.salt);\n var count = forge.util.createBuffer(capture.iterations);\n count = count.getInt(count.length() << 3);\n\n var dkLen, dIvLen, cipherFn;\n switch(oid) {\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n dkLen = 24;\n dIvLen = 8;\n cipherFn = forge.des.startDecrypting;\n break;\n\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n dkLen = 5;\n dIvLen = 8;\n cipherFn = function(key, iv) {\n var cipher = forge.rc2.createDecryptionCipher(key, 40);\n cipher.start(iv, null);\n return cipher;\n };\n break;\n\n default:\n var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');\n error.oid = oid;\n throw error;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);\n md.start();\n var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);\n\n return cipherFn(key, iv);\n};\n\n/**\n * OpenSSL's legacy key derivation function.\n *\n * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html\n *\n * @param password the password to derive the key from.\n * @param salt the salt to use, null for none.\n * @param dkLen the number of bytes needed for the derived key.\n * @param [options] the options to use:\n * [md] an optional message digest object to use.\n */\npki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {\n if(typeof md === 'undefined' || md === null) {\n if(!('md5' in forge.md)) {\n throw new Error('\"md5\" hash algorithm unavailable.');\n }\n md = forge.md.md5.create();\n }\n if(salt === null) {\n salt = '';\n }\n var digests = [hash(md, password + salt)];\n for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {\n digests.push(hash(md, digests[i - 1] + password + salt));\n }\n return digests.join('').substr(0, dkLen);\n};\n\nfunction hash(md, bytes) {\n return md.start().update(bytes).digest().getBytes();\n}\n\nfunction prfOidToMessageDigest(prfOid) {\n // get PRF algorithm, default to SHA-1\n var prfAlgorithm;\n if(!prfOid) {\n prfAlgorithm = 'hmacWithSHA1';\n } else {\n prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];\n if(!prfAlgorithm) {\n var error = new Error('Unsupported PRF OID.');\n error.oid = prfOid;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n }\n return prfAlgorithmToMessageDigest(prfAlgorithm);\n}\n\nfunction prfAlgorithmToMessageDigest(prfAlgorithm) {\n var factory = forge.md;\n switch(prfAlgorithm) {\n case 'hmacWithSHA224':\n factory = forge.md.sha512;\n case 'hmacWithSHA1':\n case 'hmacWithSHA256':\n case 'hmacWithSHA384':\n case 'hmacWithSHA512':\n prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();\n break;\n default:\n var error = new Error('Unsupported PRF algorithm.');\n error.algorithm = prfAlgorithm;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n if(!factory || !(prfAlgorithm in factory)) {\n throw new Error('Unknown hash algorithm: ' + prfAlgorithm);\n }\n return factory[prfAlgorithm].create();\n}\n\nfunction createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {\n var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ]);\n // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm\n if(prfAlgorithm !== 'hmacWithSHA1') {\n params.value.push(\n // key length\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(dkLen.toString(16))),\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n return params;\n}\n","/**\n * Password-Based Key-Derivation Function #2 implementation.\n *\n * See RFC 2898 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./hmac');\nrequire('./md');\nrequire('./util');\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = require('crypto');\n}\n\n/**\n * Derives a key from a password.\n *\n * @param p the password as a binary-encoded string of bytes.\n * @param s the salt as a binary-encoded string of bytes.\n * @param c the iteration count, a positive integer.\n * @param dkLen the intended length, in bytes, of the derived key,\n * (max: 2^32 - 1) * hash length of the PRF.\n * @param [md] the message digest (or algorithm identifier as a string) to use\n * in the PRF, defaults to SHA-1.\n * @param [callback(err, key)] presence triggers asynchronous version, called\n * once the operation completes.\n *\n * @return the derived key, as a binary-encoded string of bytes, for the\n * synchronous version (if no callback is specified).\n */\nmodule.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(\n p, s, c, dkLen, md, callback) {\n if(typeof md === 'function') {\n callback = md;\n md = null;\n }\n\n // use native implementation if possible and not disabled, note that\n // some node versions only support SHA-1, others allow digest to be changed\n if(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n crypto.pbkdf2 && (md === null || typeof md !== 'object') &&\n (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {\n if(typeof md !== 'string') {\n // default prf to SHA-1\n md = 'sha1';\n }\n p = Buffer.from(p, 'binary');\n s = Buffer.from(s, 'binary');\n if(!callback) {\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');\n }\n return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');\n }\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n\n if(typeof md === 'undefined' || md === null) {\n // default prf to SHA-1\n md = 'sha1';\n }\n if(typeof md === 'string') {\n if(!(md in forge.md.algorithms)) {\n throw new Error('Unknown hash algorithm: ' + md);\n }\n md = forge.md[md].create();\n }\n\n var hLen = md.digestLength;\n\n /* 1. If dkLen > (2^32 - 1) * hLen, output \"derived key too long\" and\n stop. */\n if(dkLen > (0xFFFFFFFF * hLen)) {\n var err = new Error('Derived key is too long.');\n if(callback) {\n return callback(err);\n }\n throw err;\n }\n\n /* 2. Let len be the number of hLen-octet blocks in the derived key,\n rounding up, and let r be the number of octets in the last\n block:\n\n len = CEIL(dkLen / hLen),\n r = dkLen - (len - 1) * hLen. */\n var len = Math.ceil(dkLen / hLen);\n var r = dkLen - (len - 1) * hLen;\n\n /* 3. For each block of the derived key apply the function F defined\n below to the password P, the salt S, the iteration count c, and\n the block index to compute the block:\n\n T_1 = F(P, S, c, 1),\n T_2 = F(P, S, c, 2),\n ...\n T_len = F(P, S, c, len),\n\n where the function F is defined as the exclusive-or sum of the\n first c iterates of the underlying pseudorandom function PRF\n applied to the password P and the concatenation of the salt S\n and the block index i:\n\n F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c\n\n where\n\n u_1 = PRF(P, S || INT(i)),\n u_2 = PRF(P, u_1),\n ...\n u_c = PRF(P, u_{c-1}).\n\n Here, INT(i) is a four-octet encoding of the integer i, most\n significant octet first. */\n var prf = forge.hmac.create();\n prf.start(md, p);\n var dk = '';\n var xor, u_c, u_c1;\n\n // sync version\n if(!callback) {\n for(var i = 1; i <= len; ++i) {\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n for(var j = 2; j <= c; ++j) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n }\n /* 5. Output the derived key DK. */\n return dk;\n }\n\n // async version\n var i = 1, j;\n function outer() {\n if(i > len) {\n // done\n return callback(null, dk);\n }\n\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n j = 2;\n inner();\n }\n\n function inner() {\n if(j <= c) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n ++j;\n return forge.util.setImmediate(inner);\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n\n ++i;\n outer();\n }\n\n outer();\n};\n","/**\n * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.\n *\n * See: RFC 1421.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n *\n * A Forge PEM object has the following fields:\n *\n * type: identifies the type of message (eg: \"RSA PRIVATE KEY\").\n *\n * procType: identifies the type of processing performed on the message,\n * it has two subfields: version and type, eg: 4,ENCRYPTED.\n *\n * contentDomain: identifies the type of content in the message, typically\n * only uses the value: \"RFC822\".\n *\n * dekInfo: identifies the message encryption algorithm and mode and includes\n * any parameters for the algorithm, it has two subfields: algorithm and\n * parameters, eg: DES-CBC,F8143EDE5960C597.\n *\n * headers: contains all other PEM encapsulated headers -- where order is\n * significant (for pairing data like recipient ID + key info).\n *\n * body: the binary-encoded body.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n// shortcut for pem API\nvar pem = module.exports = forge.pem = forge.pem || {};\n\n/**\n * Encodes (serializes) the given PEM object.\n *\n * @param msg the PEM message object to encode.\n * @param options the options to use:\n * maxline the maximum characters per line for the body, (default: 64).\n *\n * @return the PEM-formatted string.\n */\npem.encode = function(msg, options) {\n options = options || {};\n var rval = '-----BEGIN ' + msg.type + '-----\\r\\n';\n\n // encode special headers\n var header;\n if(msg.procType) {\n header = {\n name: 'Proc-Type',\n values: [String(msg.procType.version), msg.procType.type]\n };\n rval += foldHeader(header);\n }\n if(msg.contentDomain) {\n header = {name: 'Content-Domain', values: [msg.contentDomain]};\n rval += foldHeader(header);\n }\n if(msg.dekInfo) {\n header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};\n if(msg.dekInfo.parameters) {\n header.values.push(msg.dekInfo.parameters);\n }\n rval += foldHeader(header);\n }\n\n if(msg.headers) {\n // encode all other headers\n for(var i = 0; i < msg.headers.length; ++i) {\n rval += foldHeader(msg.headers[i]);\n }\n }\n\n // terminate header\n if(msg.procType) {\n rval += '\\r\\n';\n }\n\n // add body\n rval += forge.util.encode64(msg.body, options.maxline || 64) + '\\r\\n';\n\n rval += '-----END ' + msg.type + '-----\\r\\n';\n return rval;\n};\n\n/**\n * Decodes (deserializes) all PEM messages found in the given string.\n *\n * @param str the PEM-formatted string to decode.\n *\n * @return the PEM message objects in an array.\n */\npem.decode = function(str) {\n var rval = [];\n\n // split string into PEM messages (be lenient w/EOF on BEGIN line)\n var rMessage = /\\s*-----BEGIN ([A-Z0-9- ]+)-----\\r?\\n?([\\x21-\\x7e\\s]+?(?:\\r?\\n\\r?\\n))?([:A-Za-z0-9+\\/=\\s]+?)-----END \\1-----/g;\n var rHeader = /([\\x21-\\x7e]+):\\s*([\\x21-\\x7e\\s^:]+)/;\n var rCRLF = /\\r?\\n/;\n var match;\n while(true) {\n match = rMessage.exec(str);\n if(!match) {\n break;\n }\n\n // accept \"NEW CERTIFICATE REQUEST\" as \"CERTIFICATE REQUEST\"\n // https://datatracker.ietf.org/doc/html/rfc7468#section-7\n var type = match[1];\n if(type === 'NEW CERTIFICATE REQUEST') {\n type = 'CERTIFICATE REQUEST';\n }\n\n var msg = {\n type: type,\n procType: null,\n contentDomain: null,\n dekInfo: null,\n headers: [],\n body: forge.util.decode64(match[3])\n };\n rval.push(msg);\n\n // no headers\n if(!match[2]) {\n continue;\n }\n\n // parse headers\n var lines = match[2].split(rCRLF);\n var li = 0;\n while(match && li < lines.length) {\n // get line, trim any rhs whitespace\n var line = lines[li].replace(/\\s+$/, '');\n\n // RFC2822 unfold any following folded lines\n for(var nl = li + 1; nl < lines.length; ++nl) {\n var next = lines[nl];\n if(!/\\s/.test(next[0])) {\n break;\n }\n line += next;\n li = nl;\n }\n\n // parse header\n match = line.match(rHeader);\n if(match) {\n var header = {name: match[1], values: []};\n var values = match[2].split(',');\n for(var vi = 0; vi < values.length; ++vi) {\n header.values.push(ltrim(values[vi]));\n }\n\n // Proc-Type must be the first header\n if(!msg.procType) {\n if(header.name !== 'Proc-Type') {\n throw new Error('Invalid PEM formatted message. The first ' +\n 'encapsulated header must be \"Proc-Type\".');\n } else if(header.values.length !== 2) {\n throw new Error('Invalid PEM formatted message. The \"Proc-Type\" ' +\n 'header must have two subfields.');\n }\n msg.procType = {version: values[0], type: values[1]};\n } else if(!msg.contentDomain && header.name === 'Content-Domain') {\n // special-case Content-Domain\n msg.contentDomain = values[0] || '';\n } else if(!msg.dekInfo && header.name === 'DEK-Info') {\n // special-case DEK-Info\n if(header.values.length === 0) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must have at least one subfield.');\n }\n msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};\n } else {\n msg.headers.push(header);\n }\n }\n\n ++li;\n }\n\n if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must be present if \"Proc-Type\" is \"ENCRYPTED\".');\n }\n }\n\n if(rval.length === 0) {\n throw new Error('Invalid PEM formatted message.');\n }\n\n return rval;\n};\n\nfunction foldHeader(header) {\n var rval = header.name + ': ';\n\n // ensure values with CRLF are folded\n var values = [];\n var insertSpace = function(match, $1) {\n return ' ' + $1;\n };\n for(var i = 0; i < header.values.length; ++i) {\n values.push(header.values[i].replace(/^(\\S+\\r\\n)/, insertSpace));\n }\n rval += values.join(',') + '\\r\\n';\n\n // do folding\n var length = 0;\n var candidate = -1;\n for(var i = 0; i < rval.length; ++i, ++length) {\n if(length > 65 && candidate !== -1) {\n var insert = rval[candidate];\n if(insert === ',') {\n ++candidate;\n rval = rval.substr(0, candidate) + '\\r\\n ' + rval.substr(candidate);\n } else {\n rval = rval.substr(0, candidate) +\n '\\r\\n' + insert + rval.substr(candidate + 1);\n }\n length = (i - candidate - 1);\n candidate = -1;\n ++i;\n } else if(rval[i] === ' ' || rval[i] === '\\t' || rval[i] === ',') {\n candidate = i;\n }\n }\n\n return rval;\n}\n\nfunction ltrim(str) {\n return str.replace(/^\\s+/, '');\n}\n","/**\n * Partial implementation of PKCS#1 v2.2: RSA-OEAP\n *\n * Modified but based on the following MIT and BSD licensed code:\n *\n * https://github.com/kjur/jsjws/blob/master/rsa.js:\n *\n * The 'jsjws'(JSON Web Signature JavaScript Library) License\n *\n * Copyright (c) 2012 Kenji Urushima\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:\n *\n * RSAES-OAEP.js\n * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $\n * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)\n * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.\n * Contact: ellis@nukinetics.com\n * Distributed under the BSD License.\n *\n * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125\n *\n * @author Evan Jones (http://evanjones.ca/)\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./sha1');\n\n// shortcut for PKCS#1 API\nvar pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};\n\n/**\n * Encode the given RSAES-OAEP message (M) using key, with optional label (L)\n * and seed.\n *\n * This method does not perform RSA encryption, it only encodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param message the message to encode.\n * @param options the options to use:\n * label an optional label to use.\n * seed the seed to use.\n * md the message digest object to use, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the encoded message bytes.\n */\npkcs1.encode_rsa_oaep = function(key, message, options) {\n // parse arguments\n var label;\n var seed;\n var md;\n var mgf1Md;\n // legacy args (label, seed, md)\n if(typeof options === 'string') {\n label = options;\n seed = arguments[3] || undefined;\n md = arguments[4] || undefined;\n } else if(options) {\n label = options.label || undefined;\n seed = options.seed || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // default OAEP to SHA-1 message digest\n if(!md) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n // compute length in bytes and check output\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n var maxLength = keyLength - 2 * md.digestLength - 2;\n if(message.length > maxLength) {\n var error = new Error('RSAES-OAEP input message length is too long.');\n error.length = message.length;\n error.maxLength = maxLength;\n throw error;\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest();\n\n var PS = '';\n var PS_length = maxLength - message.length;\n for(var i = 0; i < PS_length; i++) {\n PS += '\\x00';\n }\n\n var DB = lHash.getBytes() + PS + '\\x01' + message;\n\n if(!seed) {\n seed = forge.random.getBytes(md.digestLength);\n } else if(seed.length !== md.digestLength) {\n var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +\n 'match the digest length.');\n error.seedLength = seed.length;\n error.digestLength = md.digestLength;\n throw error;\n }\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);\n\n // return encoded message\n return '\\x00' + maskedSeed + maskedDB;\n};\n\n/**\n * Decode the given RSAES-OAEP encoded message (EM) using key, with optional\n * label (L).\n *\n * This method does not perform RSA decryption, it only decodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param em the encoded message to decode.\n * @param options the options to use:\n * label an optional label to use.\n * md the message digest object to use for OAEP, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the decoded message bytes.\n */\npkcs1.decode_rsa_oaep = function(key, em, options) {\n // parse args\n var label;\n var md;\n var mgf1Md;\n // legacy args\n if(typeof options === 'string') {\n label = options;\n md = arguments[3] || undefined;\n } else if(options) {\n label = options.label || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // compute length in bytes\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n\n if(em.length !== keyLength) {\n var error = new Error('RSAES-OAEP encoded message length is invalid.');\n error.length = em.length;\n error.expectedLength = keyLength;\n throw error;\n }\n\n // default OAEP to SHA-1 message digest\n if(md === undefined) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n if(keyLength < 2 * md.digestLength + 2) {\n throw new Error('RSAES-OAEP key is too short for the hash function.');\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest().getBytes();\n\n // split the message into its parts\n var y = em.charAt(0);\n var maskedSeed = em.substring(1, md.digestLength + 1);\n var maskedDB = em.substring(1 + md.digestLength);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);\n\n var lHashPrime = db.substring(0, md.digestLength);\n\n // constant time check that all values match what is expected\n var error = (y !== '\\x00');\n\n // constant time check lHash vs lHashPrime\n for(var i = 0; i < md.digestLength; ++i) {\n error |= (lHash.charAt(i) !== lHashPrime.charAt(i));\n }\n\n // \"constant time\" find the 0x1 byte separating the padding (zeros) from the\n // message\n // TODO: It must be possible to do this in a better/smarter way?\n var in_ps = 1;\n var index = md.digestLength;\n for(var j = md.digestLength; j < db.length; j++) {\n var code = db.charCodeAt(j);\n\n var is_0 = (code & 0x1) ^ 0x1;\n\n // non-zero if not 0 or 1 in the ps section\n var error_mask = in_ps ? 0xfffe : 0x0000;\n error |= (code & error_mask);\n\n // latch in_ps to zero after we find 0x1\n in_ps = in_ps & is_0;\n index += in_ps;\n }\n\n if(error || db.charCodeAt(index) !== 0x1) {\n throw new Error('Invalid RSAES-OAEP padding.');\n }\n\n return db.substring(index + 1);\n};\n\nfunction rsa_mgf1(seed, maskLength, hash) {\n // default to SHA-1 message digest\n if(!hash) {\n hash = forge.md.sha1.create();\n }\n var t = '';\n var count = Math.ceil(maskLength / hash.digestLength);\n for(var i = 0; i < count; ++i) {\n var c = String.fromCharCode(\n (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);\n hash.start();\n hash.update(seed + c);\n t += hash.digest().getBytes();\n }\n return t.substring(0, maskLength);\n}\n","/**\n * Javascript implementation of PKCS#12.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#12 is as follows\n * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details)\n *\n * PFX ::= SEQUENCE {\n * version INTEGER {v3(3)}(v3,...),\n * authSafe ContentInfo,\n * macData MacData OPTIONAL\n * }\n *\n * MacData ::= SEQUENCE {\n * mac DigestInfo,\n * macSalt OCTET STRING,\n * iterations INTEGER DEFAULT 1\n * }\n * Note: The iterations default is for historical reasons and its use is\n * deprecated. A higher value, like 1024, is recommended.\n *\n * DigestInfo is defined in PKCS#7 as follows:\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of SHA1 there is none.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * Digest ::= OCTET STRING\n *\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * AuthenticatedSafe ::= SEQUENCE OF ContentInfo\n * -- Data if unencrypted\n * -- EncryptedData if password-encrypted\n * -- EnvelopedData if public key-encrypted\n *\n *\n * SafeContents ::= SEQUENCE OF SafeBag\n *\n * SafeBag ::= SEQUENCE {\n * bagId BAG-TYPE.&id ({PKCS12BagSet})\n * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),\n * bagAttributes SET OF PKCS12Attribute OPTIONAL\n * }\n *\n * PKCS12Attribute ::= SEQUENCE {\n * attrId ATTRIBUTE.&id ({PKCS12AttrSet}),\n * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})\n * } -- This type is compatible with the X.500 type 'Attribute'\n *\n * PKCS12AttrSet ATTRIBUTE ::= {\n * friendlyName | -- from PKCS #9\n * localKeyId, -- from PKCS #9\n * ... -- Other attributes are allowed\n * }\n *\n * CertBag ::= SEQUENCE {\n * certId BAG-TYPE.&id ({CertTypes}),\n * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})\n * }\n *\n * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}}\n * -- DER-encoded X.509 certificate stored in OCTET STRING\n *\n * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}}\n * -- Base64-encoded SDSI certificate stored in IA5String\n *\n * CertTypes BAG-TYPE ::= {\n * x509Certificate |\n * sdsiCertificate,\n * ... -- For future extensions\n * }\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./oids');\nrequire('./pkcs7asn1');\nrequire('./pbe');\nrequire('./random');\nrequire('./rsa');\nrequire('./sha1');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 & PKI API\nvar asn1 = forge.asn1;\nvar pki = forge.pki;\n\n// shortcut for PKCS#12 API\nvar p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {};\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // a ContentInfo\n constructed: true,\n value: [{\n name: 'ContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'content'\n }]\n};\n\nvar pfxValidator = {\n name: 'PFX',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PFX.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n },\n contentInfoValidator, {\n name: 'PFX.macData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'mac',\n value: [{\n name: 'PFX.macData.mac',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestInfo\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'macAlgorithm'\n }, {\n name: 'PFX.macData.mac.digestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'macAlgorithmParameters'\n }]\n }, {\n name: 'PFX.macData.mac.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macDigest'\n }]\n }, {\n name: 'PFX.macData.macSalt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macSalt'\n }, {\n name: 'PFX.macData.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'macIterations'\n }]\n }]\n};\n\nvar safeBagValidator = {\n name: 'SafeBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SafeBag.bagId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'bagId'\n }, {\n name: 'SafeBag.bagValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'bagValue'\n }, {\n name: 'SafeBag.bagAttributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n optional: true,\n capture: 'bagAttributes'\n }]\n};\n\nvar attributeValidator = {\n name: 'Attribute',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Attribute.attrId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'oid'\n }, {\n name: 'Attribute.attrValues',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n capture: 'values'\n }]\n};\n\nvar certBagValidator = {\n name: 'CertBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertBag.certId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certId'\n }, {\n name: 'CertBag.certValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n /* So far we only support X.509 certificates (which are wrapped in\n an OCTET STRING, hence hard code that here). */\n value: [{\n name: 'CertBag.certValue[0]',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.OCTETSTRING,\n constructed: false,\n capture: 'cert'\n }]\n }]\n};\n\n/**\n * Search SafeContents structure for bags with matching attributes.\n *\n * The search can optionally be narrowed by a certain bag type.\n *\n * @param safeContents the SafeContents structure to search in.\n * @param attrName the name of the attribute to compare against.\n * @param attrValue the attribute value to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of matching bags.\n */\nfunction _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {\n var result = [];\n\n for(var i = 0; i < safeContents.length; i++) {\n for(var j = 0; j < safeContents[i].safeBags.length; j++) {\n var bag = safeContents[i].safeBags[j];\n if(bagType !== undefined && bag.type !== bagType) {\n continue;\n }\n // only filter by bag type, no attribute specified\n if(attrName === null) {\n result.push(bag);\n continue;\n }\n if(bag.attributes[attrName] !== undefined &&\n bag.attributes[attrName].indexOf(attrValue) >= 0) {\n result.push(bag);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object.\n *\n * @param obj The PKCS#12 PFX in ASN.1 notation.\n * @param strict true to use strict DER decoding, false not to (default: true).\n * @param {String} password Password to decrypt with (optional).\n *\n * @return PKCS#12 PFX object.\n */\np12.pkcs12FromAsn1 = function(obj, strict, password) {\n // handle args\n if(typeof strict === 'string') {\n password = strict;\n strict = true;\n } else if(strict === undefined) {\n strict = true;\n }\n\n // validate PFX and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, pfxValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 PFX. ' +\n 'ASN.1 object is not an PKCS#12 PFX.');\n error.errors = error;\n throw error;\n }\n\n var pfx = {\n version: capture.version.charCodeAt(0),\n safeContents: [],\n\n /**\n * Gets bags with matching attributes.\n *\n * @param filter the attributes to filter by:\n * [localKeyId] the localKeyId to search for.\n * [localKeyIdHex] the localKeyId in hex to search for.\n * [friendlyName] the friendly name to search for.\n * [bagType] bag type to narrow each attribute search by.\n *\n * @return a map of attribute type to an array of matching bags or, if no\n * attribute was given but a bag type, the map key will be the\n * bag type.\n */\n getBags: function(filter) {\n var rval = {};\n\n var localKeyId;\n if('localKeyId' in filter) {\n localKeyId = filter.localKeyId;\n } else if('localKeyIdHex' in filter) {\n localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);\n }\n\n // filter on bagType only\n if(localKeyId === undefined && !('friendlyName' in filter) &&\n 'bagType' in filter) {\n rval[filter.bagType] = _getBagsByAttribute(\n pfx.safeContents, null, null, filter.bagType);\n }\n\n if(localKeyId !== undefined) {\n rval.localKeyId = _getBagsByAttribute(\n pfx.safeContents, 'localKeyId',\n localKeyId, filter.bagType);\n }\n if('friendlyName' in filter) {\n rval.friendlyName = _getBagsByAttribute(\n pfx.safeContents, 'friendlyName',\n filter.friendlyName, filter.bagType);\n }\n\n return rval;\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching friendlyName attribute.\n *\n * @param friendlyName the friendly name to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching friendlyName attribute.\n */\n getBagsByFriendlyName: function(friendlyName, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'friendlyName', friendlyName, bagType);\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching localKeyId attribute.\n *\n * @param localKeyId the localKeyId to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching localKeyId attribute.\n */\n getBagsByLocalKeyId: function(localKeyId, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'localKeyId', localKeyId, bagType);\n }\n };\n\n if(capture.version.charCodeAt(0) !== 3) {\n var error = new Error('PKCS#12 PFX of version other than 3 not supported.');\n error.version = capture.version.charCodeAt(0);\n throw error;\n }\n\n if(asn1.derToOid(capture.contentType) !== pki.oids.data) {\n var error = new Error('Only PKCS#12 PFX in password integrity mode supported.');\n error.oid = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n var data = capture.content.value[0];\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.');\n }\n data = _decodePkcs7Data(data);\n\n // check for MAC\n if(capture.mac) {\n var md = null;\n var macKeyBytes = 0;\n var macAlgorithm = asn1.derToOid(capture.macAlgorithm);\n switch(macAlgorithm) {\n case pki.oids.sha1:\n md = forge.md.sha1.create();\n macKeyBytes = 20;\n break;\n case pki.oids.sha256:\n md = forge.md.sha256.create();\n macKeyBytes = 32;\n break;\n case pki.oids.sha384:\n md = forge.md.sha384.create();\n macKeyBytes = 48;\n break;\n case pki.oids.sha512:\n md = forge.md.sha512.create();\n macKeyBytes = 64;\n break;\n case pki.oids.md5:\n md = forge.md.md5.create();\n macKeyBytes = 16;\n break;\n }\n if(md === null) {\n throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm);\n }\n\n // verify MAC (iterations default to 1)\n var macSalt = new forge.util.ByteBuffer(capture.macSalt);\n var macIterations = (('macIterations' in capture) ?\n parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1);\n var macKey = p12.generateKey(\n password, macSalt, 3, macIterations, macKeyBytes, md);\n var mac = forge.hmac.create();\n mac.start(md, macKey);\n mac.update(data.value);\n var macValue = mac.getMac();\n if(macValue.getBytes() !== capture.macDigest) {\n throw new Error('PKCS#12 MAC could not be verified. Invalid password?');\n }\n }\n\n _decodeAuthenticatedSafe(pfx, data.value, strict, password);\n return pfx;\n};\n\n/**\n * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines \"Data\" as an OCTET STRING,\n * but it is sometimes an OCTET STRING that is composed/constructed of chunks,\n * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This\n * function transforms this corner-case into the usual simple,\n * non-composed/constructed OCTET STRING.\n *\n * This function may be moved to ASN.1 at some point to better deal with\n * more BER-encoding issues, should they arise.\n *\n * @param data the ASN.1 Data object to transform.\n */\nfunction _decodePkcs7Data(data) {\n // handle special case of \"chunked\" data content: an octet string composed\n // of other octet strings\n if(data.composed || data.constructed) {\n var value = forge.util.createBuffer();\n for(var i = 0; i < data.value.length; ++i) {\n value.putBytes(data.value[i].value);\n }\n data.composed = data.constructed = false;\n data.value = value.getBytes();\n }\n return data;\n}\n\n/**\n * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object.\n *\n * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo.\n *\n * @param pfx The PKCS#12 PFX object to fill.\n * @param {String} authSafe BER-encoded AuthenticatedSafe.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n */\nfunction _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {\n authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */\n\n if(authSafe.tagClass !== asn1.Class.UNIVERSAL ||\n authSafe.type !== asn1.Type.SEQUENCE ||\n authSafe.constructed !== true) {\n throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' +\n 'SEQUENCE OF ContentInfo');\n }\n\n for(var i = 0; i < authSafe.value.length; i++) {\n var contentInfo = authSafe.value[i];\n\n // validate contentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var obj = {\n encrypted: false\n };\n var safeContents = null;\n var data = capture.content.value[0];\n switch(asn1.derToOid(capture.contentType)) {\n case pki.oids.data:\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.');\n }\n safeContents = _decodePkcs7Data(data).value;\n break;\n case pki.oids.encryptedData:\n safeContents = _decryptSafeContents(data, password);\n obj.encrypted = true;\n break;\n default:\n var error = new Error('Unsupported PKCS#12 contentType.');\n error.contentType = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n obj.safeBags = _decodeSafeContents(safeContents, strict, password);\n pfx.safeContents.push(obj);\n }\n}\n\n/**\n * Decrypt PKCS#7 EncryptedData structure.\n *\n * @param data ASN.1 encoded EncryptedContentInfo object.\n * @param password The user-provided password.\n *\n * @return The decrypted SafeContents (ASN.1 object).\n */\nfunction _decryptSafeContents(data, password) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(\n data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) {\n var error = new Error('Cannot read EncryptedContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.contentType);\n if(oid !== pki.oids.data) {\n var error = new Error(\n 'PKCS#12 EncryptedContentInfo ContentType is not Data.');\n error.oid = oid;\n throw error;\n }\n\n // get cipher\n oid = asn1.derToOid(capture.encAlgorithm);\n var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);\n\n // get encrypted data\n var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);\n var encrypted = forge.util.createBuffer(encryptedContentAsn1.value);\n\n cipher.update(encrypted);\n if(!cipher.finish()) {\n throw new Error('Failed to decrypt PKCS#12 SafeContents.');\n }\n\n return cipher.output.getBytes();\n}\n\n/**\n * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects.\n *\n * The safeContents is a BER-encoded SEQUENCE OF SafeBag.\n *\n * @param {String} safeContents BER-encoded safeContents.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n *\n * @return {Array} Array of Bag objects.\n */\nfunction _decodeSafeContents(safeContents, strict, password) {\n // if strict and no safe contents, return empty safes\n if(!strict && safeContents.length === 0) {\n return [];\n }\n\n // actually it's BER-encoded\n safeContents = asn1.fromDer(safeContents, strict);\n\n if(safeContents.tagClass !== asn1.Class.UNIVERSAL ||\n safeContents.type !== asn1.Type.SEQUENCE ||\n safeContents.constructed !== true) {\n throw new Error(\n 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.');\n }\n\n var res = [];\n for(var i = 0; i < safeContents.value.length; i++) {\n var safeBag = safeContents.value[i];\n\n // validate SafeBag and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) {\n var error = new Error('Cannot read SafeBag.');\n error.errors = errors;\n throw error;\n }\n\n /* Create bag object and push to result array. */\n var bag = {\n type: asn1.derToOid(capture.bagId),\n attributes: _decodeBagAttributes(capture.bagAttributes)\n };\n res.push(bag);\n\n var validator, decoder;\n var bagAsn1 = capture.bagValue.value[0];\n switch(bag.type) {\n case pki.oids.pkcs8ShroudedKeyBag:\n /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt.\n Afterwards we can handle it like a keyBag,\n which is a PrivateKeyInfo. */\n bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);\n if(bagAsn1 === null) {\n throw new Error(\n 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?');\n }\n\n /* fall through */\n case pki.oids.keyBag:\n /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our\n PKI module, hence we don't have to do validation/capturing here,\n just pass what we already got. */\n try {\n bag.key = pki.privateKeyFromAsn1(bagAsn1);\n } catch(e) {\n // ignore unknown key type, pass asn1 value\n bag.key = null;\n bag.asn1 = bagAsn1;\n }\n continue; /* Nothing more to do. */\n\n case pki.oids.certBag:\n /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates.\n Therefore put the SafeBag content through another validator to\n capture the fields. Afterwards check & store the results. */\n validator = certBagValidator;\n decoder = function() {\n if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {\n var error = new Error(\n 'Unsupported certificate type, only X.509 supported.');\n error.oid = asn1.derToOid(capture.certId);\n throw error;\n }\n\n // true=produce cert hash\n var certAsn1 = asn1.fromDer(capture.cert, strict);\n try {\n bag.cert = pki.certificateFromAsn1(certAsn1, true);\n } catch(e) {\n // ignore unknown cert type, pass asn1 value\n bag.cert = null;\n bag.asn1 = certAsn1;\n }\n };\n break;\n\n default:\n var error = new Error('Unsupported PKCS#12 SafeBag type.');\n error.oid = bag.type;\n throw error;\n }\n\n /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */\n if(validator !== undefined &&\n !asn1.validate(bagAsn1, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 ' + validator.name);\n error.errors = errors;\n throw error;\n }\n\n /* Call decoder function from above to store the results. */\n decoder();\n }\n\n return res;\n}\n\n/**\n * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object.\n *\n * @param attributes SET OF PKCS12Attribute (ASN.1 object).\n *\n * @return the decoded attributes.\n */\nfunction _decodeBagAttributes(attributes) {\n var decodedAttrs = {};\n\n if(attributes !== undefined) {\n for(var i = 0; i < attributes.length; ++i) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 BagAttribute.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.oid);\n if(pki.oids[oid] === undefined) {\n // unsupported attribute type, ignore.\n continue;\n }\n\n decodedAttrs[pki.oids[oid]] = [];\n for(var j = 0; j < capture.values.length; ++j) {\n decodedAttrs[pki.oids[oid]].push(capture.values[j].value);\n }\n }\n }\n\n return decodedAttrs;\n}\n\n/**\n * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a\n * password is provided then the private key will be encrypted.\n *\n * An entire certificate chain may also be included. To do this, pass\n * an array for the \"cert\" parameter where the first certificate is\n * the one that is paired with the private key and each subsequent one\n * verifies the previous one. The certificates may be in PEM format or\n * have been already parsed by Forge.\n *\n * @todo implement password-based-encryption for the whole package\n *\n * @param key the private key.\n * @param cert the certificate (may be an array of certificates in order\n * to specify a certificate chain).\n * @param password the password to use, null for none.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * useMac true to include a MAC, false not to, defaults to true.\n * localKeyId the local key ID to use, in hex.\n * friendlyName the friendly name to use.\n * generateLocalKeyId true to generate a random local key ID,\n * false not to, defaults to true.\n *\n * @return the PKCS#12 PFX ASN.1 object.\n */\np12.toPkcs12Asn1 = function(key, cert, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || options.encAlgorithm || 'aes128';\n if(!('useMac' in options)) {\n options.useMac = true;\n }\n if(!('localKeyId' in options)) {\n options.localKeyId = null;\n }\n if(!('generateLocalKeyId' in options)) {\n options.generateLocalKeyId = true;\n }\n\n var localKeyId = options.localKeyId;\n var bagAttrs;\n if(localKeyId !== null) {\n localKeyId = forge.util.hexToBytes(localKeyId);\n } else if(options.generateLocalKeyId) {\n // use SHA-1 of paired cert, if available\n if(cert) {\n var pairedCert = forge.util.isArray(cert) ? cert[0] : cert;\n if(typeof pairedCert === 'string') {\n pairedCert = pki.certificateFromPem(pairedCert);\n }\n var sha1 = forge.md.sha1.create();\n sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());\n localKeyId = sha1.digest().getBytes();\n } else {\n // FIXME: consider using SHA-1 of public key (which can be generated\n // from private key components), see: cert.generateSubjectKeyIdentifier\n // generate random bytes\n localKeyId = forge.random.getBytes(20);\n }\n }\n\n var attrs = [];\n if(localKeyId !== null) {\n attrs.push(\n // localKeyID\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.localKeyId).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n localKeyId)\n ])\n ]));\n }\n if('friendlyName' in options) {\n attrs.push(\n // friendlyName\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.friendlyName).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false,\n options.friendlyName)\n ])\n ]));\n }\n\n if(attrs.length > 0) {\n bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs);\n }\n\n // collect contents for AuthenticatedSafe\n var contents = [];\n\n // create safe bag(s) for certificate chain\n var chain = [];\n if(cert !== null) {\n if(forge.util.isArray(cert)) {\n chain = cert;\n } else {\n chain = [cert];\n }\n }\n\n var certSafeBags = [];\n for(var i = 0; i < chain.length; ++i) {\n // convert cert from PEM as necessary\n cert = chain[i];\n if(typeof cert === 'string') {\n cert = pki.certificateFromPem(cert);\n }\n\n // SafeBag\n var certBagAttrs = (i === 0) ? bagAttrs : undefined;\n var certAsn1 = pki.certificateToAsn1(cert);\n var certSafeBag =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.certBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // CertBag\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // certId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.x509Certificate).getBytes()),\n // certValue (x509Certificate)\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certAsn1).getBytes())\n ])])]),\n // bagAttributes (OPTIONAL)\n certBagAttrs\n ]);\n certSafeBags.push(certSafeBag);\n }\n\n if(certSafeBags.length > 0) {\n // SafeContents\n var certSafeContents = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags);\n\n // ContentInfo\n var certCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certSafeContents).getBytes())\n ])\n ]);\n contents.push(certCI);\n }\n\n // create safe contents for private key\n var keyBag = null;\n if(key !== null) {\n // SafeBag\n var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));\n if(password === null) {\n // no encryption\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.keyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // PrivateKeyInfo\n pkAsn1\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n } else {\n // encrypted PrivateKeyInfo\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // EncryptedPrivateKeyInfo\n pki.encryptPrivateKeyInfo(pkAsn1, password, options)\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n }\n\n // SafeContents\n var keySafeContents =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]);\n\n // ContentInfo\n var keyCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(keySafeContents).getBytes())\n ])\n ]);\n contents.push(keyCI);\n }\n\n // create AuthenticatedSafe by stringing together the contents\n var safe = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents);\n\n var macData;\n if(options.useMac) {\n // MacData\n var sha1 = forge.md.sha1.create();\n var macSalt = new forge.util.ByteBuffer(\n forge.random.getBytes(options.saltSize));\n var count = options.count;\n // 160-bit key\n var key = p12.generateKey(password, macSalt, 3, count, 20);\n var mac = forge.hmac.create();\n mac.start(sha1, key);\n mac.update(asn1.toDer(safe).getBytes());\n var macValue = mac.getMac();\n macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // mac DigestInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm = SHA-1\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.sha1).getBytes()),\n // parameters = Null\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // digest\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, macValue.getBytes())\n ]),\n // macSalt OCTET STRING\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()),\n // iterations INTEGER (XXX: Only support count < 65536)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(count).getBytes()\n )\n ]);\n }\n\n // PFX\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (3)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(3).getBytes()),\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(safe).getBytes())\n ])\n ]),\n macData\n ]);\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\np12.generateKey = forge.pbe.generatePkcs12Key;\n","/**\n * Javascript implementation of PKCS#7 v1.5.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n *\n * Currently this implementation only supports ContentType of EnvelopedData,\n * EncryptedData, or SignedData at the root level. The top level elements may\n * contain only a ContentInfo of ContentType Data, i.e. plain data. Further\n * nesting is not (yet) supported.\n *\n * The Forge validators for PKCS #7's ASN.1 structures are available from\n * a separate file pkcs7asn1.js, since those are referenced from other\n * PKCS standards like PKCS #12.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./oids');\nrequire('./pem');\nrequire('./pkcs7asn1');\nrequire('./random');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};\n\n/**\n * Converts a PKCS#7 message from PEM format.\n *\n * @param pem the PEM-formatted PKCS#7 message.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PKCS7') {\n var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +\n 'header type is not \"PKCS#7\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return p7.messageFromAsn1(obj);\n};\n\n/**\n * Converts a PKCS#7 message to PEM format.\n *\n * @param msg The PKCS#7 message object\n * @param maxline The maximum characters per line, defaults to 64.\n *\n * @return The PEM-formatted PKCS#7 message.\n */\np7.messageToPem = function(msg, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var pemObj = {\n type: 'PKCS7',\n body: asn1.toDer(msg.toAsn1()).getBytes()\n };\n return forge.pem.encode(pemObj, {maxline: maxline});\n};\n\n/**\n * Converts a PKCS#7 message from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a ContentInfo.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromAsn1 = function(obj) {\n // validate root level ContentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not an PKCS#7 ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var contentType = asn1.derToOid(capture.contentType);\n var msg;\n\n switch(contentType) {\n case forge.pki.oids.envelopedData:\n msg = p7.createEnvelopedData();\n break;\n\n case forge.pki.oids.encryptedData:\n msg = p7.createEncryptedData();\n break;\n\n case forge.pki.oids.signedData:\n msg = p7.createSignedData();\n break;\n\n default:\n throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +\n contentType + ' is not (yet) supported.');\n }\n\n msg.fromAsn1(capture.content.value[0]);\n return msg;\n};\n\np7.createSignedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.signedData,\n version: 1,\n certificates: [],\n crls: [],\n // TODO: add json-formatted signer stuff here?\n signers: [],\n // populated during sign()\n digestAlgorithmIdentifiers: [],\n contentInfo: null,\n signerInfos: [],\n\n fromAsn1: function(obj) {\n // validate SignedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.signedDataValidator);\n msg.certificates = [];\n msg.crls = [];\n msg.digestAlgorithmIdentifiers = [];\n msg.contentInfo = null;\n msg.signerInfos = [];\n\n if(msg.rawCapture.certificates) {\n var certs = msg.rawCapture.certificates.value;\n for(var i = 0; i < certs.length; ++i) {\n msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));\n }\n }\n\n // TODO: parse crls\n },\n\n toAsn1: function() {\n // degenerate case with no content\n if(!msg.contentInfo) {\n msg.sign();\n }\n\n var certs = [];\n for(var i = 0; i < msg.certificates.length; ++i) {\n certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));\n }\n\n var crls = [];\n // TODO: implement CRLs\n\n // [0] SignedData\n var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // DigestAlgorithmIdentifiers\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.digestAlgorithmIdentifiers),\n // ContentInfo\n msg.contentInfo\n ])\n ]);\n if(certs.length > 0) {\n // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));\n }\n if(crls.length > 0) {\n // [1] IMPLICIT CertificateRevocationLists OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));\n }\n // SignerInfos\n signedData.value[0].value.push(\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.signerInfos));\n\n // ContentInfo\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] SignedData\n signedData\n ]);\n },\n\n /**\n * Add (another) entity to list of signers.\n *\n * Note: If authenticatedAttributes are provided, then, per RFC 2315,\n * they must include at least two attributes: content type and\n * message digest. The message digest attribute value will be\n * auto-calculated during signing and will be ignored if provided.\n *\n * Here's an example of providing these two attributes:\n *\n * forge.pkcs7.createSignedData();\n * p7.addSigner({\n * issuer: cert.issuer.attributes,\n * serialNumber: cert.serialNumber,\n * key: privateKey,\n * digestAlgorithm: forge.pki.oids.sha1,\n * authenticatedAttributes: [{\n * type: forge.pki.oids.contentType,\n * value: forge.pki.oids.data\n * }, {\n * type: forge.pki.oids.messageDigest\n * }]\n * });\n *\n * TODO: Support [subjectKeyIdentifier] as signer's ID.\n *\n * @param signer the signer information:\n * key the signer's private key.\n * [certificate] a certificate containing the public key\n * associated with the signer's private key; use this option as\n * an alternative to specifying signer.issuer and\n * signer.serialNumber.\n * [issuer] the issuer attributes (eg: cert.issuer.attributes).\n * [serialNumber] the signer's certificate's serial number in\n * hexadecimal (eg: cert.serialNumber).\n * [digestAlgorithm] the message digest OID, as a string, to use\n * (eg: forge.pki.oids.sha1).\n * [authenticatedAttributes] an optional array of attributes\n * to also sign along with the content.\n */\n addSigner: function(signer) {\n var issuer = signer.issuer;\n var serialNumber = signer.serialNumber;\n if(signer.certificate) {\n var cert = signer.certificate;\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n issuer = cert.issuer.attributes;\n serialNumber = cert.serialNumber;\n }\n var key = signer.key;\n if(!key) {\n throw new Error(\n 'Could not add PKCS#7 signer; no private key specified.');\n }\n if(typeof key === 'string') {\n key = forge.pki.privateKeyFromPem(key);\n }\n\n // ensure OID known for digest algorithm\n var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;\n switch(digestAlgorithm) {\n case forge.pki.oids.sha1:\n case forge.pki.oids.sha256:\n case forge.pki.oids.sha384:\n case forge.pki.oids.sha512:\n case forge.pki.oids.md5:\n break;\n default:\n throw new Error(\n 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +\n digestAlgorithm);\n }\n\n // if authenticatedAttributes is present, then the attributes\n // must contain at least PKCS #9 content-type and message-digest\n var authenticatedAttributes = signer.authenticatedAttributes || [];\n if(authenticatedAttributes.length > 0) {\n var contentType = false;\n var messageDigest = false;\n for(var i = 0; i < authenticatedAttributes.length; ++i) {\n var attr = authenticatedAttributes[i];\n if(!contentType && attr.type === forge.pki.oids.contentType) {\n contentType = true;\n if(messageDigest) {\n break;\n }\n continue;\n }\n if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {\n messageDigest = true;\n if(contentType) {\n break;\n }\n continue;\n }\n }\n\n if(!contentType || !messageDigest) {\n throw new Error('Invalid signer.authenticatedAttributes. If ' +\n 'signer.authenticatedAttributes is specified, then it must ' +\n 'contain at least two attributes, PKCS #9 content-type and ' +\n 'PKCS #9 message-digest.');\n }\n }\n\n msg.signers.push({\n key: key,\n version: 1,\n issuer: issuer,\n serialNumber: serialNumber,\n digestAlgorithm: digestAlgorithm,\n signatureAlgorithm: forge.pki.oids.rsaEncryption,\n signature: null,\n authenticatedAttributes: authenticatedAttributes,\n unauthenticatedAttributes: []\n });\n },\n\n /**\n * Signs the content.\n * @param options Options to apply when signing:\n * [detached] boolean. If signing should be done in detached mode. Defaults to false.\n */\n sign: function(options) {\n options = options || {};\n // auto-generate content info\n if(typeof msg.content !== 'object' || msg.contentInfo === null) {\n // use Data ContentInfo\n msg.contentInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes())\n ]);\n\n // add actual content, if present\n if('content' in msg) {\n var content;\n if(msg.content instanceof forge.util.ByteBuffer) {\n content = msg.content.bytes();\n } else if(typeof msg.content === 'string') {\n content = forge.util.encodeUtf8(msg.content);\n }\n\n if (options.detached) {\n msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);\n } else {\n msg.contentInfo.value.push(\n // [0] EXPLICIT content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n content)\n ]));\n }\n }\n }\n\n // no signers, return early (degenerate case for certificate container)\n if(msg.signers.length === 0) {\n return;\n }\n\n // generate digest algorithm identifiers\n var mds = addDigestAlgorithmIds();\n\n // generate signerInfos\n addSignerInfos(mds);\n },\n\n verify: function() {\n throw new Error('PKCS#7 signature verification not yet implemented.');\n },\n\n /**\n * Add a certificate.\n *\n * @param cert the certificate to add.\n */\n addCertificate: function(cert) {\n // convert from PEM\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n msg.certificates.push(cert);\n },\n\n /**\n * Add a certificate revokation list.\n *\n * @param crl the certificate revokation list to add.\n */\n addCertificateRevokationList: function(crl) {\n throw new Error('PKCS#7 CRL support not yet implemented.');\n }\n };\n return msg;\n\n function addDigestAlgorithmIds() {\n var mds = {};\n\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n var oid = signer.digestAlgorithm;\n if(!(oid in mds)) {\n // content digest\n mds[oid] = forge.md[forge.pki.oids[oid]].create();\n }\n if(signer.authenticatedAttributes.length === 0) {\n // no custom attributes to digest; use content message digest\n signer.md = mds[oid];\n } else {\n // custom attributes to be digested; use own message digest\n // TODO: optimize to just copy message digest state if that\n // feature is ever supported with message digests\n signer.md = forge.md[forge.pki.oids[oid]].create();\n }\n }\n\n // add unique digest algorithm identifiers\n msg.digestAlgorithmIdentifiers = [];\n for(var oid in mds) {\n msg.digestAlgorithmIdentifiers.push(\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oid).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n\n return mds;\n }\n\n function addSignerInfos(mds) {\n var content;\n\n if (msg.detachedContent) {\n // Signature has been made in detached mode.\n content = msg.detachedContent;\n } else {\n // Note: ContentInfo is a SEQUENCE with 2 values, second value is\n // the content field and is optional for a ContentInfo but required here\n // since signers are present\n // get ContentInfo content\n content = msg.contentInfo.value[1];\n // skip [0] EXPLICIT content wrapper\n content = content.value[0];\n }\n\n if(!content) {\n throw new Error(\n 'Could not sign PKCS#7 message; there is no content to sign.');\n }\n\n // get ContentInfo content type\n var contentType = asn1.derToOid(msg.contentInfo.value[0].value);\n\n // serialize content\n var bytes = asn1.toDer(content);\n\n // skip identifier and length per RFC 2315 9.3\n // skip identifier (1 byte)\n bytes.getByte();\n // read and discard length bytes\n asn1.getBerValueLength(bytes);\n bytes = bytes.getBytes();\n\n // digest content DER value bytes\n for(var oid in mds) {\n mds[oid].start().update(bytes);\n }\n\n // sign content\n var signingTime = new Date();\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n\n if(signer.authenticatedAttributes.length === 0) {\n // if ContentInfo content type is not \"Data\", then\n // authenticatedAttributes must be present per RFC 2315\n if(contentType !== forge.pki.oids.data) {\n throw new Error(\n 'Invalid signer; authenticatedAttributes must be present ' +\n 'when the ContentInfo content type is not PKCS#7 Data.');\n }\n } else {\n // process authenticated attributes\n // [0] IMPLICIT\n signer.authenticatedAttributesAsn1 = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // per RFC 2315, attributes are to be digested using a SET container\n // not the above [0] IMPLICIT container\n var attrsAsn1 = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);\n\n for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {\n var attr = signer.authenticatedAttributes[ai];\n if(attr.type === forge.pki.oids.messageDigest) {\n // use content message digest as value\n attr.value = mds[signer.digestAlgorithm].digest();\n } else if(attr.type === forge.pki.oids.signingTime) {\n // auto-populate signing time if not already set\n if(!attr.value) {\n attr.value = signingTime;\n }\n }\n\n // convert to ASN.1 and push onto Attributes SET (for signing) and\n // onto authenticatedAttributesAsn1 to complete SignedData ASN.1\n // TODO: optimize away duplication\n attrsAsn1.value.push(_attributeToAsn1(attr));\n signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));\n }\n\n // DER-serialize and digest SET OF attributes only\n bytes = asn1.toDer(attrsAsn1).getBytes();\n signer.md.start().update(bytes);\n }\n\n // sign digest\n signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');\n }\n\n // add signer info\n msg.signerInfos = _signersToAsn1(msg.signers);\n }\n};\n\n/**\n * Creates an empty PKCS#7 message of type EncryptedData.\n *\n * @return the message.\n */\np7.createEncryptedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.encryptedData,\n version: 0,\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EncryptedData content block (in ASN.1 format)\n *\n * @param obj The ASN.1 representation of the EncryptedData content block\n */\n fromAsn1: function(obj) {\n // Validate EncryptedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);\n },\n\n /**\n * Decrypt encrypted content\n *\n * @param key The (symmetric) key as a byte buffer\n */\n decrypt: function(key) {\n if(key !== undefined) {\n msg.encryptedContent.key = key;\n }\n _decryptContent(msg);\n }\n };\n return msg;\n};\n\n/**\n * Creates an empty PKCS#7 message of type EnvelopedData.\n *\n * @return the message.\n */\np7.createEnvelopedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.envelopedData,\n version: 0,\n recipients: [],\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EnvelopedData content block (in ASN.1 format)\n *\n * @param obj the ASN.1 representation of the EnvelopedData content block.\n */\n fromAsn1: function(obj) {\n // validate EnvelopedData content block and capture data\n var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);\n msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);\n },\n\n toAsn1: function() {\n // ContentInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] EnvelopedData\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // RecipientInfos\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n _recipientsToAsn1(msg.recipients)),\n // EncryptedContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,\n _encryptedContentToAsn1(msg.encryptedContent))\n ])\n ])\n ]);\n },\n\n /**\n * Find recipient by X.509 certificate's issuer.\n *\n * @param cert the certificate with the issuer to look for.\n *\n * @return the recipient object.\n */\n findRecipient: function(cert) {\n var sAttr = cert.issuer.attributes;\n\n for(var i = 0; i < msg.recipients.length; ++i) {\n var r = msg.recipients[i];\n var rAttr = r.issuer;\n\n if(r.serialNumber !== cert.serialNumber) {\n continue;\n }\n\n if(rAttr.length !== sAttr.length) {\n continue;\n }\n\n var match = true;\n for(var j = 0; j < sAttr.length; ++j) {\n if(rAttr[j].type !== sAttr[j].type ||\n rAttr[j].value !== sAttr[j].value) {\n match = false;\n break;\n }\n }\n\n if(match) {\n return r;\n }\n }\n\n return null;\n },\n\n /**\n * Decrypt enveloped content\n *\n * @param recipient The recipient object related to the private key\n * @param privKey The (RSA) private key object\n */\n decrypt: function(recipient, privKey) {\n if(msg.encryptedContent.key === undefined && recipient !== undefined &&\n privKey !== undefined) {\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n case forge.pki.oids.desCBC:\n var key = privKey.decrypt(recipient.encryptedContent.content);\n msg.encryptedContent.key = forge.util.createBuffer(key);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, ' +\n 'OID ' + recipient.encryptedContent.algorithm);\n }\n }\n\n _decryptContent(msg);\n },\n\n /**\n * Add (another) entity to list of recipients.\n *\n * @param cert The certificate of the entity to add.\n */\n addRecipient: function(cert) {\n msg.recipients.push({\n version: 0,\n issuer: cert.issuer.attributes,\n serialNumber: cert.serialNumber,\n encryptedContent: {\n // We simply assume rsaEncryption here, since forge.pki only\n // supports RSA so far. If the PKI module supports other\n // ciphers one day, we need to modify this one as well.\n algorithm: forge.pki.oids.rsaEncryption,\n key: cert.publicKey\n }\n });\n },\n\n /**\n * Encrypt enveloped content.\n *\n * This function supports two optional arguments, cipher and key, which\n * can be used to influence symmetric encryption. Unless cipher is\n * provided, the cipher specified in encryptedContent.algorithm is used\n * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key\n * is (re-)used. If that one's not set, a random key will be generated\n * automatically.\n *\n * @param [key] The key to be used for symmetric encryption.\n * @param [cipher] The OID of the symmetric cipher to use.\n */\n encrypt: function(key, cipher) {\n // Part 1: Symmetric encryption\n if(msg.encryptedContent.content === undefined) {\n cipher = cipher || msg.encryptedContent.algorithm;\n key = key || msg.encryptedContent.key;\n\n var keyLen, ivLen, ciphFn;\n switch(cipher) {\n case forge.pki.oids['aes128-CBC']:\n keyLen = 16;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes192-CBC']:\n keyLen = 24;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes256-CBC']:\n keyLen = 32;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['des-EDE3-CBC']:\n keyLen = 24;\n ivLen = 8;\n ciphFn = forge.des.createEncryptionCipher;\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' + cipher);\n }\n\n if(key === undefined) {\n key = forge.util.createBuffer(forge.random.getBytes(keyLen));\n } else if(key.length() != keyLen) {\n throw new Error('Symmetric key has wrong length; ' +\n 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');\n }\n\n // Keep a copy of the key & IV in the object, so the caller can\n // use it for whatever reason.\n msg.encryptedContent.algorithm = cipher;\n msg.encryptedContent.key = key;\n msg.encryptedContent.parameter = forge.util.createBuffer(\n forge.random.getBytes(ivLen));\n\n var ciph = ciphFn(key);\n ciph.start(msg.encryptedContent.parameter.copy());\n ciph.update(msg.content);\n\n // The finish function does PKCS#7 padding by default, therefore\n // no action required by us.\n if(!ciph.finish()) {\n throw new Error('Symmetric encryption failed.');\n }\n\n msg.encryptedContent.content = ciph.output;\n }\n\n // Part 2: asymmetric encryption for each recipient\n for(var i = 0; i < msg.recipients.length; ++i) {\n var recipient = msg.recipients[i];\n\n // Nothing to do, encryption already done.\n if(recipient.encryptedContent.content !== undefined) {\n continue;\n }\n\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n recipient.encryptedContent.content =\n recipient.encryptedContent.key.encrypt(\n msg.encryptedContent.key.data);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, OID ' +\n recipient.encryptedContent.algorithm);\n }\n }\n }\n };\n return msg;\n};\n\n/**\n * Converts a single recipient from an ASN.1 object.\n *\n * @param obj the ASN.1 RecipientInfo.\n *\n * @return the recipient object.\n */\nfunction _recipientFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +\n 'ASN.1 object is not an PKCS#7 RecipientInfo.');\n error.errors = errors;\n throw error;\n }\n\n return {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n encryptedContent: {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: capture.encParameter ? capture.encParameter.value : undefined,\n content: capture.encKey\n }\n };\n}\n\n/**\n * Converts a single recipient object to an ASN.1 object.\n *\n * @param obj the recipient object.\n *\n * @return the ASN.1 RecipientInfo.\n */\nfunction _recipientToAsn1(obj) {\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // IssuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // Serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // KeyEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),\n // Parameter, force NULL, only RSA supported for now.\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // EncryptedKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n obj.encryptedContent.content)\n ]);\n}\n\n/**\n * Map a set of RecipientInfo ASN.1 objects to recipient objects.\n *\n * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).\n *\n * @return an array of recipient objects.\n */\nfunction _recipientsFromAsn1(infos) {\n var ret = [];\n for(var i = 0; i < infos.length; ++i) {\n ret.push(_recipientFromAsn1(infos[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of recipient objects to ASN.1 RecipientInfo objects.\n *\n * @param recipients an array of recipientInfo objects.\n *\n * @return an array of ASN.1 RecipientInfos.\n */\nfunction _recipientsToAsn1(recipients) {\n var ret = [];\n for(var i = 0; i < recipients.length; ++i) {\n ret.push(_recipientToAsn1(recipients[i]));\n }\n return ret;\n}\n\n/**\n * Converts a single signer from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a SignerInfo.\n *\n * @return the signer object.\n */\nfunction _signerFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 SignerInfo. ' +\n 'ASN.1 object is not an PKCS#7 SignerInfo.');\n error.errors = errors;\n throw error;\n }\n\n var rval = {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),\n signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),\n signature: capture.signature,\n authenticatedAttributes: [],\n unauthenticatedAttributes: []\n };\n\n // TODO: convert attributes\n var authenticatedAttributes = capture.authenticatedAttributes || [];\n var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];\n\n return rval;\n}\n\n/**\n * Converts a single signerInfo object to an ASN.1 object.\n *\n * @param obj the signerInfo object.\n *\n * @return the ASN.1 representation of a SignerInfo.\n */\nfunction _signerToAsn1(obj) {\n // SignerInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // issuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.digestAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]);\n\n // authenticatedAttributes (OPTIONAL)\n if(obj.authenticatedAttributesAsn1) {\n // add ASN.1 previously generated during signing\n rval.value.push(obj.authenticatedAttributesAsn1);\n }\n\n // digestEncryptionAlgorithm\n rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.signatureAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n\n // encryptedDigest\n rval.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));\n\n // unauthenticatedAttributes (OPTIONAL)\n if(obj.unauthenticatedAttributes.length > 0) {\n // [1] IMPLICIT\n var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);\n for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {\n var attr = obj.unauthenticatedAttributes[i];\n attrsAsn1.values.push(_attributeToAsn1(attr));\n }\n rval.value.push(attrsAsn1);\n }\n\n return rval;\n}\n\n/**\n * Map a set of SignerInfo ASN.1 objects to an array of signer objects.\n *\n * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).\n *\n * @return an array of signers objects.\n */\nfunction _signersFromAsn1(signerInfoAsn1s) {\n var ret = [];\n for(var i = 0; i < signerInfoAsn1s.length; ++i) {\n ret.push(_signerFromAsn1(signerInfoAsn1s[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of signer objects to ASN.1 objects.\n *\n * @param signers an array of signer objects.\n *\n * @return an array of ASN.1 SignerInfos.\n */\nfunction _signersToAsn1(signers) {\n var ret = [];\n for(var i = 0; i < signers.length; ++i) {\n ret.push(_signerToAsn1(signers[i]));\n }\n return ret;\n}\n\n/**\n * Convert an attribute object to an ASN.1 Attribute.\n *\n * @param attr the attribute object.\n *\n * @return the ASN.1 Attribute.\n */\nfunction _attributeToAsn1(attr) {\n var value;\n\n // TODO: generalize to support more attributes\n if(attr.type === forge.pki.oids.contentType) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.value).getBytes());\n } else if(attr.type === forge.pki.oids.messageDigest) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n attr.value.bytes());\n } else if(attr.type === forge.pki.oids.signingTime) {\n /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049\n (inclusive) MUST be encoded as UTCTime. Any dates with year values\n before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]\n UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST\n include seconds (i.e., times are YYMMDDHHMMSSZ), even where the\n number of seconds is zero. Midnight (GMT) must be represented as\n \"YYMMDD000000Z\". */\n // TODO: make these module-level constants\n var jan_1_1950 = new Date('1950-01-01T00:00:00Z');\n var jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n var date = attr.value;\n if(typeof date === 'string') {\n // try to parse date\n var timestamp = Date.parse(date);\n if(!isNaN(timestamp)) {\n date = new Date(timestamp);\n } else if(date.length === 13) {\n // YYMMDDHHMMSSZ (13 chars for UTCTime)\n date = asn1.utcTimeToDate(date);\n } else {\n // assume generalized time\n date = asn1.generalizedTimeToDate(date);\n }\n }\n\n if(date >= jan_1_1950 && date < jan_1_2050) {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n }\n\n // TODO: expose as common API call\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n value\n ])\n ]);\n}\n\n/**\n * Map messages encrypted content to ASN.1 objects.\n *\n * @param ec The encryptedContent object of the message.\n *\n * @return ASN.1 representation of the encryptedContent object (SEQUENCE).\n */\nfunction _encryptedContentToAsn1(ec) {\n return [\n // ContentType, always Data for the moment\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes()),\n // ContentEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ec.algorithm).getBytes()),\n // Parameters (IV)\n !ec.parameter ?\n undefined :\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.parameter.getBytes())\n ]),\n // [0] EncryptedContent\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.content.getBytes())\n ])\n ];\n}\n\n/**\n * Reads the \"common part\" of an PKCS#7 content block (in ASN.1 format)\n *\n * This function reads the \"common part\" of the PKCS#7 content blocks\n * EncryptedData and EnvelopedData, i.e. version number and symmetrically\n * encrypted content block.\n *\n * The result of the ASN.1 validate and capture process is returned\n * to allow the caller to extract further data, e.g. the list of recipients\n * in case of a EnvelopedData object.\n *\n * @param msg the PKCS#7 object to read the data to.\n * @param obj the ASN.1 representation of the content block.\n * @param validator the ASN.1 structure validator object to use.\n *\n * @return the value map captured by validator object.\n */\nfunction _fromAsn1(msg, obj, validator) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not a supported PKCS#7 message.');\n error.errors = error;\n throw error;\n }\n\n // Check contentType, so far we only support (raw) Data.\n var contentType = asn1.derToOid(capture.contentType);\n if(contentType !== forge.pki.oids.data) {\n throw new Error('Unsupported PKCS#7 message. ' +\n 'Only wrapped ContentType Data supported.');\n }\n\n if(capture.encryptedContent) {\n var content = '';\n if(forge.util.isArray(capture.encryptedContent)) {\n for(var i = 0; i < capture.encryptedContent.length; ++i) {\n if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting encrypted ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.encryptedContent[i].value;\n }\n } else {\n content = capture.encryptedContent;\n }\n msg.encryptedContent = {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: forge.util.createBuffer(capture.encParameter.value),\n content: forge.util.createBuffer(content)\n };\n }\n\n if(capture.content) {\n var content = '';\n if(forge.util.isArray(capture.content)) {\n for(var i = 0; i < capture.content.length; ++i) {\n if(capture.content[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.content[i].value;\n }\n } else {\n content = capture.content;\n }\n msg.content = forge.util.createBuffer(content);\n }\n\n msg.version = capture.version.charCodeAt(0);\n msg.rawCapture = capture;\n\n return capture;\n}\n\n/**\n * Decrypt the symmetrically encrypted content block of the PKCS#7 message.\n *\n * Decryption is skipped in case the PKCS#7 message object already has a\n * (decrypted) content attribute. The algorithm, key and cipher parameters\n * (probably the iv) are taken from the encryptedContent attribute of the\n * message object.\n *\n * @param The PKCS#7 message object.\n */\nfunction _decryptContent(msg) {\n if(msg.encryptedContent.key === undefined) {\n throw new Error('Symmetric key not available.');\n }\n\n if(msg.content === undefined) {\n var ciph;\n\n switch(msg.encryptedContent.algorithm) {\n case forge.pki.oids['aes128-CBC']:\n case forge.pki.oids['aes192-CBC']:\n case forge.pki.oids['aes256-CBC']:\n ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n case forge.pki.oids['desCBC']:\n case forge.pki.oids['des-EDE3-CBC']:\n ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' +\n msg.encryptedContent.algorithm);\n }\n ciph.start(msg.encryptedContent.parameter);\n ciph.update(msg.encryptedContent.content);\n\n if(!ciph.finish()) {\n throw new Error('Symmetric decryption failed.');\n }\n\n msg.content = ciph.output;\n }\n}\n","/**\n * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.\n *\n * @author Dave Longley\n * @author Stefan Siegl\n *\n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#7 is as follows\n * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):\n *\n * A PKCS#7 message consists of a ContentInfo on root level, which may\n * contain any number of further ContentInfo nested into it.\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * EnvelopedData ::= SEQUENCE {\n * version Version,\n * recipientInfos RecipientInfos,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * EncryptedData ::= SEQUENCE {\n * version Version,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)\n * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }\n *\n * SignedData ::= SEQUENCE {\n * version INTEGER,\n * digestAlgorithms DigestAlgorithmIdentifiers,\n * contentInfo ContentInfo,\n * certificates [0] IMPLICIT Certificates OPTIONAL,\n * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n * signerInfos SignerInfos\n * }\n *\n * SignerInfos ::= SET OF SignerInfo\n *\n * SignerInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * digestAlgorithm DigestAlgorithmIdentifier,\n * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,\n * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,\n * encryptedDigest EncryptedDigest,\n * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL\n * }\n *\n * EncryptedDigest ::= OCTET STRING\n *\n * Attributes ::= SET OF Attribute\n *\n * Attribute ::= SEQUENCE {\n * attrType OBJECT IDENTIFIER,\n * attrValues SET OF AttributeValue\n * }\n *\n * AttributeValue ::= ANY\n *\n * Version ::= INTEGER\n *\n * RecipientInfos ::= SET OF RecipientInfo\n *\n * EncryptedContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,\n * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL\n * }\n *\n * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of AES and DES3, there is only one,\n * the IV.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * EncryptedContent ::= OCTET STRING\n *\n * RecipientInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,\n * encryptedKey EncryptedKey\n * }\n *\n * IssuerAndSerialNumber ::= SEQUENCE {\n * issuer Name,\n * serialNumber CertificateSerialNumber\n * }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedKey ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./util');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};\nforge.pkcs7 = forge.pkcs7 || {};\nforge.pkcs7.asn1 = p7v;\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'ContentInfo.ContentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n captureAsn1: 'content'\n }]\n};\np7v.contentInfoValidator = contentInfoValidator;\n\nvar encryptedContentInfoValidator = {\n name: 'EncryptedContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'EncryptedContentInfo.encryptedContent',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n /* The PKCS#7 structure output by OpenSSL somewhat differs from what\n * other implementations do generate.\n *\n * OpenSSL generates a structure like this:\n * SEQUENCE {\n * ...\n * [0]\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n *\n * Whereas other implementations (and this PKCS#7 module) generate:\n * SEQUENCE {\n * ...\n * [0] {\n * OCTET STRING\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n * }\n *\n * In order to support both, we just capture the context specific\n * field here. The OCTET STRING bit is removed below.\n */\n capture: 'encryptedContent',\n captureAsn1: 'encryptedContentAsn1'\n }]\n};\n\np7v.envelopedDataValidator = {\n name: 'EnvelopedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EnvelopedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'EnvelopedData.RecipientInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'recipientInfos'\n }].concat(encryptedContentInfoValidator)\n};\n\np7v.encryptedDataValidator = {\n name: 'EncryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }].concat(encryptedContentInfoValidator)\n};\n\nvar signerValidator = {\n name: 'SignerInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false\n }, {\n name: 'SignerInfo.issuerAndSerialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.issuerAndSerialNumber.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'SignerInfo.issuerAndSerialNumber.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'SignerInfo.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'digestAlgorithm'\n }, {\n name: 'SignerInfo.digestAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'digestParameter',\n optional: true\n }]\n }, {\n name: 'SignerInfo.authenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'authenticatedAttributes'\n }, {\n name: 'SignerInfo.digestEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n capture: 'signatureAlgorithm'\n }, {\n name: 'SignerInfo.encryptedDigest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'signature'\n }, {\n name: 'SignerInfo.unauthenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n capture: 'unauthenticatedAttributes'\n }]\n};\n\np7v.signedDataValidator = {\n name: 'SignedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'SignedData.DigestAlgorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'digestAlgorithms'\n },\n contentInfoValidator,\n {\n name: 'SignedData.Certificates',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n optional: true,\n captureAsn1: 'certificates'\n }, {\n name: 'SignedData.CertificateRevocationLists',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n optional: true,\n captureAsn1: 'crls'\n }, {\n name: 'SignedData.SignerInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n capture: 'signerInfos',\n optional: true,\n value: [signerValidator]\n }]\n};\n\np7v.recipientInfoValidator = {\n name: 'RecipientInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'RecipientInfo.issuerAndSerial',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.issuerAndSerial.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'RecipientInfo.issuerAndSerial.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'encParameter',\n optional: true\n }]\n }, {\n name: 'RecipientInfo.encryptedKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encKey'\n }]\n};\n","/**\n * Javascript implementation of a basic Public Key Infrastructure, including\n * support for RSA public and private keys.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./oids');\nrequire('./pbe');\nrequire('./pem');\nrequire('./pbkdf2');\nrequire('./pkcs12');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.\n *\n * Converts PEM-formatted data to DER.\n *\n * @param pem the PEM-formatted data.\n *\n * @return the DER-formatted data.\n */\npki.pemToDer = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PEM to DER; PEM is encrypted.');\n }\n return forge.util.createBuffer(msg.body);\n};\n\n/**\n * Converts an RSA private key from PEM format.\n *\n * @param pem the PEM-formatted private key.\n *\n * @return the private key.\n */\npki.privateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM ' +\n 'header type is not \"PRIVATE KEY\" or \"RSA PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert private key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.privateKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA private key to PEM format.\n *\n * @param key the private key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PRIVATE KEY',\n body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PrivateKeyInfo to PEM format.\n *\n * @param pki the PrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyInfoToPem = function(pki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'PRIVATE KEY',\n body: asn1.toDer(pki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n","/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./jsbn');\nrequire('./random');\n\n(function() {\n\n// forge.prime already defined\nif(forge.prime) {\n module.exports = forge.prime;\n return;\n}\n\n/* PRIME API */\nvar prime = module.exports = forge.prime = forge.prime || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\nvar THIRTY = new BigInteger(null);\nTHIRTY.fromInt(30);\nvar op_or = function(x, y) {return x|y;};\n\n/**\n * Generates a random probable prime with the given number of bits.\n *\n * Alternative algorithms can be specified by name as a string or as an\n * object with custom options like so:\n *\n * {\n * name: 'PRIMEINC',\n * options: {\n * maxBlockTime: ,\n * millerRabinTests: ,\n * workerScript: ,\n * workers: .\n * workLoad: the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * }\n * }\n *\n * @param bits the number of bits for the prime number.\n * @param options the options to use.\n * [algorithm] the algorithm to use (default: 'PRIMEINC').\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n *\n * @return callback(err, num) called once the operation completes.\n */\nprime.generateProbablePrime = function(bits, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // default to PRIMEINC algorithm\n var algorithm = options.algorithm || 'PRIMEINC';\n if(typeof algorithm === 'string') {\n algorithm = {name: algorithm};\n }\n algorithm.options = algorithm.options || {};\n\n // create prng with api that matches BigInteger secure random\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n if(algorithm.name === 'PRIMEINC') {\n return primeincFindPrime(bits, rng, algorithm.options, callback);\n }\n\n throw new Error('Invalid prime generation algorithm: ' + algorithm.name);\n};\n\nfunction primeincFindPrime(bits, rng, options, callback) {\n if('workers' in options) {\n return primeincFindPrimeWithWorkers(bits, rng, options, callback);\n }\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n}\n\nfunction primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {\n // initialize random number\n var num = generateRandom(bits, rng);\n\n /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The\n number we are given is always aligned at 30k + 1. Each time the number is\n determined not to be prime we add to get to the next 'i', eg: if the number\n was at 30k + 1 we add 6. */\n var deltaIdx = 0;\n\n // get required number of MR tests\n var mrTests = getMillerRabinTests(num.bitLength());\n if('millerRabinTests' in options) {\n mrTests = options.millerRabinTests;\n }\n\n // find prime nearest to 'num' for maxBlockTime ms\n // 10 ms gives 5ms of leeway for other calculations before dropping\n // below 60fps (1000/60 == 16.67), but in reality, the number will\n // likely be higher due to an 'atomic' big int modPow\n var maxBlockTime = 10;\n if('maxBlockTime' in options) {\n maxBlockTime = options.maxBlockTime;\n }\n\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n}\n\nfunction _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {\n var start = +new Date();\n do {\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n // do primality test\n if(num.isProbablePrime(mrTests)) {\n return callback(null, num);\n }\n // get next potential prime\n num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));\n\n // keep trying later\n forge.util.setImmediate(function() {\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n });\n}\n\n// NOTE: This algorithm is indeterminate in nature because workers\n// run in parallel looking at different segments of numbers. Even if this\n// algorithm is run twice with the same input from a predictable RNG, it\n// may produce different outputs.\nfunction primeincFindPrimeWithWorkers(bits, rng, options, callback) {\n // web workers unavailable\n if(typeof Worker === 'undefined') {\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n }\n\n // initialize random number\n var num = generateRandom(bits, rng);\n\n // use web workers to generate keys\n var numWorkers = options.workers;\n var workLoad = options.workLoad || 100;\n var range = workLoad * 30 / 8;\n var workerScript = options.workerScript || 'forge/prime.worker.js';\n if(numWorkers === -1) {\n return forge.util.estimateCores(function(err, cores) {\n if(err) {\n // default to 2\n cores = 2;\n }\n numWorkers = cores - 1;\n generate();\n });\n }\n generate();\n\n function generate() {\n // require at least 1 worker\n numWorkers = Math.max(1, numWorkers);\n\n // TODO: consider optimizing by starting workers outside getPrime() ...\n // note that in order to clean up they will have to be made internally\n // asynchronous which may actually be slower\n\n // start workers immediately\n var workers = [];\n for(var i = 0; i < numWorkers; ++i) {\n // FIXME: fix path or use blob URLs\n workers[i] = new Worker(workerScript);\n }\n var running = numWorkers;\n\n // listen for requests from workers and assign ranges to find prime\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].addEventListener('message', workerMessage);\n }\n\n /* Note: The distribution of random numbers is unknown. Therefore, each\n web worker is continuously allocated a range of numbers to check for a\n random number until one is found.\n\n Every 30 numbers will be checked just 8 times, because prime numbers\n have the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)\n\n Therefore, if we want a web worker to run N checks before asking for\n a new range of numbers, each range must contain N*30/8 numbers.\n\n For 100 checks (workLoad), this is a range of 375. */\n\n var found = false;\n function workerMessage(e) {\n // ignore message, prime already found\n if(found) {\n return;\n }\n\n --running;\n var data = e.data;\n if(data.found) {\n // terminate all workers\n for(var i = 0; i < workers.length; ++i) {\n workers[i].terminate();\n }\n found = true;\n return callback(null, new BigInteger(data.prime, 16));\n }\n\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n\n // assign new range to check\n var hex = num.toString(16);\n\n // start prime search\n e.target.postMessage({\n hex: hex,\n workLoad: workLoad\n });\n\n num.dAddOffset(range, 0);\n }\n }\n}\n\n/**\n * Generates a random number using the given number of bits and RNG.\n *\n * @param bits the number of bits for the number.\n * @param rng the random number generator to use.\n *\n * @return the random number.\n */\nfunction generateRandom(bits, rng) {\n var num = new BigInteger(bits, rng);\n // force MSB set\n var bits1 = bits - 1;\n if(!num.testBit(bits1)) {\n num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);\n }\n // align number on 30k+1 boundary\n num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);\n return num;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n})();\n","/**\n * A javascript implementation of a cryptographically-secure\n * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed\n * here though the use of SHA-256 is not enforced; when generating an\n * a PRNG context, the hashing algorithm and block cipher used for\n * the generator are specified via a plugin.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = require('crypto');\n}\n\n/* PRNG API */\nvar prng = module.exports = forge.prng = forge.prng || {};\n\n/**\n * Creates a new PRNG context.\n *\n * A PRNG plugin must be passed in that will provide:\n *\n * 1. A function that initializes the key and seed of a PRNG context. It\n * will be given a 16 byte key and a 16 byte seed. Any key expansion\n * or transformation of the seed from a byte string into an array of\n * integers (or similar) should be performed.\n * 2. The cryptographic function used by the generator. It takes a key and\n * a seed.\n * 3. A seed increment function. It takes the seed and returns seed + 1.\n * 4. An api to create a message digest.\n *\n * For an example, see random.js.\n *\n * @param plugin the PRNG plugin to use.\n */\nprng.create = function(plugin) {\n var ctx = {\n plugin: plugin,\n key: null,\n seed: null,\n time: null,\n // number of reseeds so far\n reseeds: 0,\n // amount of data generated so far\n generated: 0,\n // no initial key bytes\n keyBytes: ''\n };\n\n // create 32 entropy pools (each is a message digest)\n var md = plugin.md;\n var pools = new Array(32);\n for(var i = 0; i < 32; ++i) {\n pools[i] = md.create();\n }\n ctx.pools = pools;\n\n // entropy pools are written to cyclically, starting at index 0\n ctx.pool = 0;\n\n /**\n * Generates random bytes. The bytes may be generated synchronously or\n * asynchronously. Web workers must use the asynchronous interface or\n * else the behavior is undefined.\n *\n * @param count the number of random bytes to generate.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return count random bytes as a string.\n */\n ctx.generate = function(count, callback) {\n // do synchronously\n if(!callback) {\n return ctx.generateSync(count);\n }\n\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n var b = forge.util.createBuffer();\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generate` call\n ctx.key = null;\n\n generate();\n\n function generate(err) {\n if(err) {\n return callback(err);\n }\n\n // sufficient bytes generated\n if(b.length() >= count) {\n return callback(null, b.getBytes(count));\n }\n\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n // prevent stack overflow\n return forge.util.nextTick(function() {\n _reseed(generate);\n });\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n\n forge.util.setImmediate(generate);\n }\n };\n\n /**\n * Generates random bytes synchronously.\n *\n * @param count the number of random bytes to generate.\n *\n * @return count random bytes as a string.\n */\n ctx.generateSync = function(count) {\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generateSync` call\n ctx.key = null;\n\n var b = forge.util.createBuffer();\n while(b.length() < count) {\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n _reseedSync();\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n }\n\n return b.getBytes(count);\n };\n\n /**\n * Private function that asynchronously reseeds a generator.\n *\n * @param callback(err) called once the operation completes.\n */\n function _reseed(callback) {\n if(ctx.pools[0].messageLength >= 32) {\n _seed();\n return callback();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.seedFile(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n ctx.collect(bytes);\n _seed();\n callback();\n });\n }\n\n /**\n * Private function that synchronously reseeds a generator.\n */\n function _reseedSync() {\n if(ctx.pools[0].messageLength >= 32) {\n return _seed();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.collect(ctx.seedFileSync(needed));\n _seed();\n }\n\n /**\n * Private function that seeds a generator once enough bytes are available.\n */\n function _seed() {\n // update reseed count\n ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;\n\n // goal is to update `key` via:\n // key = hash(key + s)\n // where 's' is all collected entropy from selected pools, then...\n\n // create a plugin-based message digest\n var md = ctx.plugin.md.create();\n\n // consume current key bytes\n md.update(ctx.keyBytes);\n\n // digest the entropy of pools whose index k meet the\n // condition 'n mod 2^k == 0' where n is the number of reseeds\n var _2powK = 1;\n for(var k = 0; k < 32; ++k) {\n if(ctx.reseeds % _2powK === 0) {\n md.update(ctx.pools[k].digest().getBytes());\n ctx.pools[k].start();\n }\n _2powK = _2powK << 1;\n }\n\n // get digest for key bytes\n ctx.keyBytes = md.digest().getBytes();\n\n // paranoid deviation from Fortuna:\n // update `seed` via `seed = hash(key)`\n // instead of initializing to zero once and only\n // ever incrementing it\n md.start();\n md.update(ctx.keyBytes);\n var seedBytes = md.digest().getBytes();\n\n // update state\n ctx.key = ctx.plugin.formatKey(ctx.keyBytes);\n ctx.seed = ctx.plugin.formatSeed(seedBytes);\n ctx.generated = 0;\n }\n\n /**\n * The built-in default seedFile. This seedFile is used when entropy\n * is needed immediately.\n *\n * @param needed the number of bytes that are needed.\n *\n * @return the random bytes.\n */\n function defaultSeedFile(needed) {\n // use window.crypto.getRandomValues strong source of entropy if available\n var getRandomValues = null;\n var globalScope = forge.util.globalScope;\n var _crypto = globalScope.crypto || globalScope.msCrypto;\n if(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n }\n\n var b = forge.util.createBuffer();\n if(getRandomValues) {\n while(b.length() < needed) {\n // max byte length is 65536 before QuotaExceededError is thrown\n // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues\n var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);\n var entropy = new Uint32Array(Math.floor(count));\n try {\n getRandomValues(entropy);\n for(var i = 0; i < entropy.length; ++i) {\n b.putInt32(entropy[i]);\n }\n } catch(e) {\n /* only ignore QuotaExceededError */\n if(!(typeof QuotaExceededError !== 'undefined' &&\n e instanceof QuotaExceededError)) {\n throw e;\n }\n }\n }\n }\n\n // be sad and add some weak random data\n if(b.length() < needed) {\n /* Draws from Park-Miller \"minimal standard\" 31 bit PRNG,\n implemented with David G. Carta's optimization: with 32 bit math\n and without division (Public Domain). */\n var hi, lo, next;\n var seed = Math.floor(Math.random() * 0x010000);\n while(b.length() < needed) {\n lo = 16807 * (seed & 0xFFFF);\n hi = 16807 * (seed >> 16);\n lo += (hi & 0x7FFF) << 16;\n lo += hi >> 15;\n lo = (lo & 0x7FFFFFFF) + (lo >> 31);\n seed = lo & 0xFFFFFFFF;\n\n // consume lower 3 bytes of seed\n for(var i = 0; i < 3; ++i) {\n // throw in more pseudo random\n next = seed >>> (i << 3);\n next ^= Math.floor(Math.random() * 0x0100);\n b.putByte(next & 0xFF);\n }\n }\n }\n\n return b.getBytes(needed);\n }\n // initialize seed file APIs\n if(_crypto) {\n // use nodejs async API\n ctx.seedFile = function(needed, callback) {\n _crypto.randomBytes(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n callback(null, bytes.toString());\n });\n };\n // use nodejs sync API\n ctx.seedFileSync = function(needed) {\n return _crypto.randomBytes(needed).toString();\n };\n } else {\n ctx.seedFile = function(needed, callback) {\n try {\n callback(null, defaultSeedFile(needed));\n } catch(e) {\n callback(e);\n }\n };\n ctx.seedFileSync = defaultSeedFile;\n }\n\n /**\n * Adds entropy to a prng ctx's accumulator.\n *\n * @param bytes the bytes of entropy as a string.\n */\n ctx.collect = function(bytes) {\n // iterate over pools distributing entropy cyclically\n var count = bytes.length;\n for(var i = 0; i < count; ++i) {\n ctx.pools[ctx.pool].update(bytes.substr(i, 1));\n ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;\n }\n };\n\n /**\n * Collects an integer of n bits.\n *\n * @param i the integer entropy.\n * @param n the number of bits in the integer.\n */\n ctx.collectInt = function(i, n) {\n var bytes = '';\n for(var x = 0; x < n; x += 8) {\n bytes += String.fromCharCode((i >> x) & 0xFF);\n }\n ctx.collect(bytes);\n };\n\n /**\n * Registers a Web Worker to receive immediate entropy from the main thread.\n * This method is required until Web Workers can access the native crypto\n * API. This method should be called twice for each created worker, once in\n * the main thread, and once in the worker itself.\n *\n * @param worker the worker to register.\n */\n ctx.registerWorker = function(worker) {\n // worker receives random bytes\n if(worker === self) {\n ctx.seedFile = function(needed, callback) {\n function listener(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n self.removeEventListener('message', listener);\n callback(data.forge.prng.err, data.forge.prng.bytes);\n }\n }\n self.addEventListener('message', listener);\n self.postMessage({forge: {prng: {needed: needed}}});\n };\n } else {\n // main thread sends random bytes upon request\n var listener = function(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n ctx.seedFile(data.forge.prng.needed, function(err, bytes) {\n worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});\n });\n }\n };\n // TODO: do we need to remove the event listener when the worker dies?\n worker.addEventListener('message', listener);\n }\n };\n\n return ctx;\n};\n","/**\n * Javascript implementation of PKCS#1 PSS signature padding.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./random');\nrequire('./util');\n\n// shortcut for PSS API\nvar pss = module.exports = forge.pss = forge.pss || {};\n\n/**\n * Creates a PSS signature scheme object.\n *\n * There are several ways to provide a salt for encoding:\n *\n * 1. Specify the saltLength only and the built-in PRNG will generate it.\n * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that\n * will be used.\n * 3. Specify the salt itself as a forge.util.ByteBuffer.\n *\n * @param options the options to use:\n * md the message digest object to use, a forge md instance.\n * mgf the mask generation function to use, a forge mgf instance.\n * [saltLength] the length of the salt in octets.\n * [prng] the pseudo-random number generator to use to produce a salt.\n * [salt] the salt to use when encoding.\n *\n * @return a signature scheme object.\n */\npss.create = function(options) {\n // backwards compatibility w/legacy args: hash, mgf, sLen\n if(arguments.length === 3) {\n options = {\n md: arguments[0],\n mgf: arguments[1],\n saltLength: arguments[2]\n };\n }\n\n var hash = options.md;\n var mgf = options.mgf;\n var hLen = hash.digestLength;\n\n var salt_ = options.salt || null;\n if(typeof salt_ === 'string') {\n // assume binary-encoded string\n salt_ = forge.util.createBuffer(salt_);\n }\n\n var sLen;\n if('saltLength' in options) {\n sLen = options.saltLength;\n } else if(salt_ !== null) {\n sLen = salt_.length();\n } else {\n throw new Error('Salt length not specified or specific salt not given.');\n }\n\n if(salt_ !== null && salt_.length() !== sLen) {\n throw new Error('Given salt length does not match length of given salt.');\n }\n\n var prng = options.prng || forge.random;\n\n var pssobj = {};\n\n /**\n * Encodes a PSS signature.\n *\n * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.\n *\n * @param md the message digest object with the hash to sign.\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return the encoded message as a binary-encoded string of length\n * ceil((modBits - 1) / 8).\n */\n pssobj.encode = function(md, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* 2. Let mHash = Hash(M), an octet string of length hLen. */\n var mHash = md.digest().getBytes();\n\n /* 3. If emLen < hLen + sLen + 2, output \"encoding error\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Message is too long to encrypt.');\n }\n\n /* 4. Generate a random octet string salt of length sLen; if sLen = 0,\n * then salt is the empty string. */\n var salt;\n if(salt_ === null) {\n salt = prng.getBytesSync(sLen);\n } else {\n salt = salt_.bytes();\n }\n\n /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 6. Let H = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h = hash.digest().getBytes();\n\n /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2\n * zero octets. The length of PS may be 0. */\n var ps = new forge.util.ByteBuffer();\n ps.fillWithByte(0, emLen - sLen - hLen - 2);\n\n /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length\n * emLen - hLen - 1. */\n ps.putByte(0x01);\n ps.putBytes(salt);\n var db = ps.getBytes();\n\n /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */\n var maskLen = emLen - hLen - 1;\n var dbMask = mgf.generate(h, maskLen);\n\n /* 10. Let maskedDB = DB \\xor dbMask. */\n var maskedDB = '';\n for(i = 0; i < maskLen; i++) {\n maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB to zero. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +\n maskedDB.substr(1);\n\n /* 12. Let EM = maskedDB || H || 0xbc.\n * 13. Output EM. */\n return maskedDB + h + String.fromCharCode(0xbc);\n };\n\n /**\n * Verifies a PSS signature.\n *\n * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.\n *\n * @param mHash the message digest hash, as a binary-encoded string, to\n * compare against the signature.\n * @param em the encoded message, as a binary-encoded string\n * (RSA decryption result).\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return true if the signature was verified, false if not.\n */\n pssobj.verify = function(mHash, em, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* c. Convert the message representative m to an encoded message EM\n * of length emLen = ceil((modBits - 1) / 8) octets, where modBits\n * is the length in bits of the RSA modulus n */\n em = em.substr(-emLen);\n\n /* 3. If emLen < hLen + sLen + 2, output \"inconsistent\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Inconsistent parameters to PSS signature verification.');\n }\n\n /* 4. If the rightmost octet of EM does not have hexadecimal value\n * 0xbc, output \"inconsistent\" and stop. */\n if(em.charCodeAt(emLen - 1) !== 0xbc) {\n throw new Error('Encoded message does not end in 0xBC.');\n }\n\n /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and\n * let H be the next hLen octets. */\n var maskLen = emLen - hLen - 1;\n var maskedDB = em.substr(0, maskLen);\n var h = em.substr(maskLen, hLen);\n\n /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB are not all equal to zero, output \"inconsistent\" and stop. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n if((maskedDB.charCodeAt(0) & mask) !== 0) {\n throw new Error('Bits beyond keysize not zero as expected.');\n }\n\n /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */\n var dbMask = mgf.generate(h, maskLen);\n\n /* 8. Let DB = maskedDB \\xor dbMask. */\n var db = '';\n for(i = 0; i < maskLen; i++) {\n db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet\n * in DB to zero. */\n db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);\n\n /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero\n * or if the octet at position emLen - hLen - sLen - 1 (the leftmost\n * position is \"position 1\") does not have hexadecimal value 0x01,\n * output \"inconsistent\" and stop. */\n var checkLen = emLen - hLen - sLen - 2;\n for(i = 0; i < checkLen; i++) {\n if(db.charCodeAt(i) !== 0x00) {\n throw new Error('Leftmost octets not zero as expected');\n }\n }\n\n if(db.charCodeAt(checkLen) !== 0x01) {\n throw new Error('Inconsistent PSS signature, 0x01 marker not found');\n }\n\n /* 11. Let salt be the last sLen octets of DB. */\n var salt = db.substr(-sLen);\n\n /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 13. Let H' = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h_ = hash.digest().getBytes();\n\n /* 14. If H = H', output \"consistent.\" Otherwise, output \"inconsistent.\" */\n return h === h_;\n };\n\n return pssobj;\n};\n","/**\n * An API for getting cryptographically-secure random bytes. The bytes are\n * generated using the Fortuna algorithm devised by Bruce Schneier and\n * Niels Ferguson.\n *\n * Getting strong random bytes is not yet easy to do in javascript. The only\n * truish random entropy that can be collected is from the mouse, keyboard, or\n * from timing with respect to page loads, etc. This generator makes a poor\n * attempt at providing random bytes when those sources haven't yet provided\n * enough entropy to initially seed or to reseed the PRNG.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./sha256');\nrequire('./prng');\nrequire('./util');\n\n(function() {\n\n// forge.random already defined\nif(forge.random && forge.random.getBytes) {\n module.exports = forge.random;\n return;\n}\n\n(function(jQuery) {\n\n// the default prng plugin, uses AES-128\nvar prng_aes = {};\nvar _prng_aes_output = new Array(4);\nvar _prng_aes_buffer = forge.util.createBuffer();\nprng_aes.formatKey = function(key) {\n // convert the key into 32-bit integers\n var tmp = forge.util.createBuffer(key);\n key = new Array(4);\n key[0] = tmp.getInt32();\n key[1] = tmp.getInt32();\n key[2] = tmp.getInt32();\n key[3] = tmp.getInt32();\n\n // return the expanded key\n return forge.aes._expandKey(key, false);\n};\nprng_aes.formatSeed = function(seed) {\n // convert seed into 32-bit integers\n var tmp = forge.util.createBuffer(seed);\n seed = new Array(4);\n seed[0] = tmp.getInt32();\n seed[1] = tmp.getInt32();\n seed[2] = tmp.getInt32();\n seed[3] = tmp.getInt32();\n return seed;\n};\nprng_aes.cipher = function(key, seed) {\n forge.aes._updateBlock(key, seed, _prng_aes_output, false);\n _prng_aes_buffer.putInt32(_prng_aes_output[0]);\n _prng_aes_buffer.putInt32(_prng_aes_output[1]);\n _prng_aes_buffer.putInt32(_prng_aes_output[2]);\n _prng_aes_buffer.putInt32(_prng_aes_output[3]);\n return _prng_aes_buffer.getBytes();\n};\nprng_aes.increment = function(seed) {\n // FIXME: do we care about carry or signed issues?\n ++seed[3];\n return seed;\n};\nprng_aes.md = forge.md.sha256;\n\n/**\n * Creates a new PRNG.\n */\nfunction spawnPrng() {\n var ctx = forge.prng.create(prng_aes);\n\n /**\n * Gets random bytes. If a native secure crypto API is unavailable, this\n * method tries to make the bytes more unpredictable by drawing from data that\n * can be collected from the user of the browser, eg: mouse movement.\n *\n * If a callback is given, this method will be called asynchronously.\n *\n * @param count the number of random bytes to get.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytes = function(count, callback) {\n return ctx.generate(count, callback);\n };\n\n /**\n * Gets random bytes asynchronously. If a native secure crypto API is\n * unavailable, this method tries to make the bytes more unpredictable by\n * drawing from data that can be collected from the user of the browser,\n * eg: mouse movement.\n *\n * @param count the number of random bytes to get.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytesSync = function(count) {\n return ctx.generate(count);\n };\n\n return ctx;\n}\n\n// create default prng context\nvar _ctx = spawnPrng();\n\n// add other sources of entropy only if window.crypto.getRandomValues is not\n// available -- otherwise this source will be automatically used by the prng\nvar getRandomValues = null;\nvar globalScope = forge.util.globalScope;\nvar _crypto = globalScope.crypto || globalScope.msCrypto;\nif(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n}\n\nif(forge.options.usePureJavaScript ||\n (!forge.util.isNodejs && !getRandomValues)) {\n // if this is a web worker, do not use weak entropy, instead register to\n // receive strong entropy asynchronously from the main thread\n if(typeof window === 'undefined' || window.document === undefined) {\n // FIXME:\n }\n\n // get load time entropy\n _ctx.collectInt(+new Date(), 32);\n\n // add some entropy from navigator object\n if(typeof(navigator) !== 'undefined') {\n var _navBytes = '';\n for(var key in navigator) {\n try {\n if(typeof(navigator[key]) == 'string') {\n _navBytes += navigator[key];\n }\n } catch(e) {\n /* Some navigator keys might not be accessible, e.g. the geolocation\n attribute throws an exception if touched in Mozilla chrome://\n context.\n\n Silently ignore this and just don't use this as a source of\n entropy. */\n }\n }\n _ctx.collect(_navBytes);\n _navBytes = null;\n }\n\n // add mouse and keyboard collectors if jquery is available\n if(jQuery) {\n // set up mouse entropy capture\n jQuery().mousemove(function(e) {\n // add mouse coords\n _ctx.collectInt(e.clientX, 16);\n _ctx.collectInt(e.clientY, 16);\n });\n\n // set up keyboard entropy capture\n jQuery().keypress(function(e) {\n _ctx.collectInt(e.charCode, 8);\n });\n }\n}\n\n/* Random API */\nif(!forge.random) {\n forge.random = _ctx;\n} else {\n // extend forge.random with _ctx\n for(var key in _ctx) {\n forge.random[key] = _ctx[key];\n }\n}\n\n// expose spawn PRNG\nforge.random.createInstance = spawnPrng;\n\nmodule.exports = forge.random;\n\n})(typeof(jQuery) !== 'undefined' ? jQuery : null);\n\n})();\n","/**\n * RC2 implementation.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n *\n * Information on the RC2 cipher is available from RFC #2268,\n * http://www.ietf.org/rfc/rfc2268.txt\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar piTable = [\n 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,\n 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,\n 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,\n 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,\n 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,\n 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,\n 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,\n 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,\n 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,\n 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,\n 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,\n 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,\n 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,\n 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,\n 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,\n 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad\n];\n\nvar s = [1, 2, 3, 5];\n\n/**\n * Rotate a word left by given number of bits.\n *\n * Bits that are shifted out on the left are put back in on the right\n * hand side.\n *\n * @param word The word to shift left.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar rol = function(word, bits) {\n return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));\n};\n\n/**\n * Rotate a word right by given number of bits.\n *\n * Bits that are shifted out on the right are put back in on the left\n * hand side.\n *\n * @param word The word to shift right.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar ror = function(word, bits) {\n return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);\n};\n\n/* RC2 API */\nmodule.exports = forge.rc2 = forge.rc2 || {};\n\n/**\n * Perform RC2 key expansion as per RFC #2268, section 2.\n *\n * @param key variable-length user key (between 1 and 128 bytes)\n * @param effKeyBits number of effective key bits (default: 128)\n * @return the expanded RC2 key (ByteBuffer of 128 bytes)\n */\nforge.rc2.expandKey = function(key, effKeyBits) {\n if(typeof key === 'string') {\n key = forge.util.createBuffer(key);\n }\n effKeyBits = effKeyBits || 128;\n\n /* introduce variables that match the names used in RFC #2268 */\n var L = key;\n var T = key.length();\n var T1 = effKeyBits;\n var T8 = Math.ceil(T1 / 8);\n var TM = 0xff >> (T1 & 0x07);\n var i;\n\n for(i = T; i < 128; i++) {\n L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);\n }\n\n L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);\n\n for(i = 127 - T8; i >= 0; i--) {\n L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);\n }\n\n return L;\n};\n\n/**\n * Creates a RC2 cipher object.\n *\n * @param key the symmetric key to use (as base for key generation).\n * @param bits the number of effective key bits.\n * @param encrypt false for decryption, true for encryption.\n *\n * @return the cipher.\n */\nvar createCipher = function(key, bits, encrypt) {\n var _finish = false, _input = null, _output = null, _iv = null;\n var mixRound, mashRound;\n var i, j, K = [];\n\n /* Expand key and fill into K[] Array */\n key = forge.rc2.expandKey(key, bits);\n for(i = 0; i < 64; i++) {\n K.push(key.getInt16Le());\n }\n\n if(encrypt) {\n /**\n * Perform one mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n R[i] = rol(R[i], s[i]);\n j++;\n }\n };\n\n /**\n * Perform one mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[R[(i + 3) % 4] & 63];\n }\n };\n } else {\n /**\n * Perform one r-mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] = ror(R[i], s[i]);\n R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n j--;\n }\n };\n\n /**\n * Perform one r-mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] -= K[R[(i + 3) % 4] & 63];\n }\n };\n }\n\n /**\n * Run the specified cipher execution plan.\n *\n * This function takes four words from the input buffer, applies the IV on\n * it (if requested) and runs the provided execution plan.\n *\n * The plan must be put together in form of a array of arrays. Where the\n * outer one is simply a list of steps to perform and the inner one needs\n * to have two elements: the first one telling how many rounds to perform,\n * the second one telling what to do (i.e. the function to call).\n *\n * @param {Array} plan The plan to execute.\n */\n var runPlan = function(plan) {\n var R = [];\n\n /* Get data from input buffer and fill the four words into R */\n for(i = 0; i < 4; i++) {\n var val = _input.getInt16Le();\n\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting, apply the IV first. */\n val ^= _iv.getInt16Le();\n } else {\n /* We're decryption, keep cipher text for next block. */\n _iv.putInt16Le(val);\n }\n }\n\n R.push(val & 0xffff);\n }\n\n /* Reset global \"j\" variable as per spec. */\n j = encrypt ? 0 : 63;\n\n /* Run execution plan. */\n for(var ptr = 0; ptr < plan.length; ptr++) {\n for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {\n plan[ptr][1](R);\n }\n }\n\n /* Write back result to output buffer. */\n for(i = 0; i < 4; i++) {\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting in CBC-mode, feed back encrypted bytes into\n IV buffer to carry it forward to next block. */\n _iv.putInt16Le(R[i]);\n } else {\n R[i] ^= _iv.getInt16Le();\n }\n }\n\n _output.putInt16Le(R[i]);\n }\n };\n\n /* Create cipher object */\n var cipher = null;\n cipher = {\n /**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * To use the cipher in CBC mode, iv may be given either as a string\n * of bytes, or as a byte buffer. For ECB mode, give null as iv.\n *\n * @param iv the initialization vector to use, null for ECB mode.\n * @param output the output the buffer to write to, null to create one.\n */\n start: function(iv, output) {\n if(iv) {\n /* CBC mode */\n if(typeof iv === 'string') {\n iv = forge.util.createBuffer(iv);\n }\n }\n\n _finish = false;\n _input = forge.util.createBuffer();\n _output = output || new forge.util.createBuffer();\n _iv = iv;\n\n cipher.output = _output;\n },\n\n /**\n * Updates the next block.\n *\n * @param input the buffer to read from.\n */\n update: function(input) {\n if(!_finish) {\n // not finishing, so fill the input buffer with more input\n _input.putBuffer(input);\n }\n\n while(_input.length() >= 8) {\n runPlan([\n [ 5, mixRound ],\n [ 1, mashRound ],\n [ 6, mixRound ],\n [ 1, mashRound ],\n [ 5, mixRound ]\n ]);\n }\n },\n\n /**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use, null for PKCS#7 padding,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\n finish: function(pad) {\n var rval = true;\n\n if(encrypt) {\n if(pad) {\n rval = pad(8, _input, !encrypt);\n } else {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (_input.length() === 8) ? 8 : (8 - _input.length());\n _input.fillWithByte(padding, padding);\n }\n }\n\n if(rval) {\n // do final update\n _finish = true;\n cipher.update();\n }\n\n if(!encrypt) {\n // check for error: input data not a multiple of block size\n rval = (_input.length() === 0);\n if(rval) {\n if(pad) {\n rval = pad(8, _output, !encrypt);\n } else {\n // ensure padding byte count is valid\n var len = _output.length();\n var count = _output.at(len - 1);\n\n if(count > len) {\n rval = false;\n } else {\n // trim off padding bytes\n _output.truncate(count);\n }\n }\n }\n }\n\n return rval;\n }\n };\n\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startEncrypting = function(key, iv, output) {\n var cipher = forge.rc2.createEncryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start encrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createEncryptionCipher = function(key, bits) {\n return createCipher(key, bits, true);\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startDecrypting = function(key, iv, output) {\n var cipher = forge.rc2.createDecryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start decrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createDecryptionCipher = function(key, bits) {\n return createCipher(key, bits, false);\n};\n","/**\n * Javascript implementation of basic RSA algorithms.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The only algorithm currently supported for PKI is RSA.\n *\n * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo\n * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier\n * and a subjectPublicKey of type bit string.\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of RSA, there aren't any.\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * For an RSA public key, the subjectPublicKey is:\n *\n * RSAPublicKey ::= SEQUENCE {\n * modulus INTEGER, -- n\n * publicExponent INTEGER -- e\n * }\n *\n * PrivateKeyInfo ::= SEQUENCE {\n * version Version,\n * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n * privateKey PrivateKey,\n * attributes [0] IMPLICIT Attributes OPTIONAL\n * }\n *\n * Version ::= INTEGER\n * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n * PrivateKey ::= OCTET STRING\n * Attributes ::= SET OF Attribute\n *\n * An RSA private key as the following structure:\n *\n * RSAPrivateKey ::= SEQUENCE {\n * version Version,\n * modulus INTEGER, -- n\n * publicExponent INTEGER, -- e\n * privateExponent INTEGER, -- d\n * prime1 INTEGER, -- p\n * prime2 INTEGER, -- q\n * exponent1 INTEGER, -- d mod (p-1)\n * exponent2 INTEGER, -- d mod (q-1)\n * coefficient INTEGER -- (inverse of q) mod p\n * }\n *\n * Version ::= INTEGER\n *\n * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./jsbn');\nrequire('./oids');\nrequire('./pkcs1');\nrequire('./prime');\nrequire('./random');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar _crypto = forge.util.isNodejs ? require('crypto') : null;\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for util API\nvar util = forge.util;\n\n/*\n * RSA encryption and decryption, see RFC 2313.\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};\nvar pki = forge.pki;\n\n// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\n\n// validator for a PrivateKeyInfo structure\nvar privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\n// validator for an RSA private key\nvar rsaPrivateKeyValidator = {\n // RSAPrivateKey\n name: 'RSAPrivateKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'RSAPrivateKey.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // modulus (n)\n name: 'RSAPrivateKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPrivateKey.publicExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPublicExponent'\n }, {\n // privateExponent (d)\n name: 'RSAPrivateKey.privateExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrivateExponent'\n }, {\n // prime1 (p)\n name: 'RSAPrivateKey.prime1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime1'\n }, {\n // prime2 (q)\n name: 'RSAPrivateKey.prime2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime2'\n }, {\n // exponent1 (d mod (p-1))\n name: 'RSAPrivateKey.exponent1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent1'\n }, {\n // exponent2 (d mod (q-1))\n name: 'RSAPrivateKey.exponent2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent2'\n }, {\n // coefficient ((inverse of q) mod p)\n name: 'RSAPrivateKey.coefficient',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyCoefficient'\n }]\n};\n\n// validator for an RSA public key\nvar rsaPublicKeyValidator = {\n // RSAPublicKey\n name: 'RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // modulus (n)\n name: 'RSAPublicKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPublicKey.exponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyExponent'\n }]\n};\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n }, {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n }]\n};\n\n// validator for a DigestInfo structure\nvar digestInfoValidator = {\n name: 'DigestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'algorithmIdentifier'\n }, {\n // NULL paramters\n name: 'DigestInfo.DigestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.NULL,\n constructed: false\n }]\n }, {\n // digest\n name: 'DigestInfo.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'digest'\n }]\n};\n\n/**\n * Wrap digest in DigestInfo object.\n *\n * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * @param md the message digest object with the hash to sign.\n *\n * @return the encoded message (ready for RSA encrytion)\n */\nvar emsaPkcs1v15encode = function(md) {\n // get the oid for the algorithm\n var oid;\n if(md.algorithm in pki.oids) {\n oid = pki.oids[md.algorithm];\n } else {\n var error = new Error('Unknown message digest algorithm.');\n error.algorithm = md.algorithm;\n throw error;\n }\n var oidBytes = asn1.oidToDer(oid).getBytes();\n\n // create the digest info\n var digestInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var digestAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));\n var digest = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, md.digest().getBytes());\n digestInfo.value.push(digestAlgorithm);\n digestInfo.value.push(digest);\n\n // encode digest info\n return asn1.toDer(digestInfo).getBytes();\n};\n\n/**\n * Performs x^c mod n (RSA encryption or decryption operation).\n *\n * @param x the number to raise and mod.\n * @param key the key to use.\n * @param pub true if the key is public, false if private.\n *\n * @return the result of x^c mod n.\n */\nvar _modPow = function(x, key, pub) {\n if(pub) {\n return x.modPow(key.e, key.n);\n }\n\n if(!key.p || !key.q) {\n // allow calculation without CRT params (slow)\n return x.modPow(key.d, key.n);\n }\n\n // pre-compute dP, dQ, and qInv if necessary\n if(!key.dP) {\n key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));\n }\n if(!key.dQ) {\n key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));\n }\n if(!key.qInv) {\n key.qInv = key.q.modInverse(key.p);\n }\n\n /* Chinese remainder theorem (CRT) states:\n\n Suppose n1, n2, ..., nk are positive integers which are pairwise\n coprime (n1 and n2 have no common factors other than 1). For any\n integers x1, x2, ..., xk there exists an integer x solving the\n system of simultaneous congruences (where ~= means modularly\n congruent so a ~= b mod n means a mod n = b mod n):\n\n x ~= x1 mod n1\n x ~= x2 mod n2\n ...\n x ~= xk mod nk\n\n This system of congruences has a single simultaneous solution x\n between 0 and n - 1. Furthermore, each xk solution and x itself\n is congruent modulo the product n = n1*n2*...*nk.\n So x1 mod n = x2 mod n = xk mod n = x mod n.\n\n The single simultaneous solution x can be solved with the following\n equation:\n\n x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.\n\n Where x is less than n, xi = x mod ni.\n\n For RSA we are only concerned with k = 2. The modulus n = pq, where\n p and q are coprime. The RSA decryption algorithm is:\n\n y = x^d mod n\n\n Given the above:\n\n x1 = x^d mod p\n r1 = n/p = q\n s1 = q^-1 mod p\n x2 = x^d mod q\n r2 = n/q = p\n s2 = p^-1 mod q\n\n So y = (x1r1s1 + x2r2s2) mod n\n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n\n\n According to Fermat's Little Theorem, if the modulus P is prime,\n for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.\n Since A is not divisible by P it follows that if:\n N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:\n\n A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort\n to calculate). In order to calculate x^d mod p more quickly the\n exponent d mod (p - 1) is stored in the RSA private key (the same\n is done for x^d mod q). These values are referred to as dP and dQ\n respectively. Therefore we now have:\n\n y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n\n\n Since we'll be reducing x^dP by modulo p (same for q) we can also\n reduce x by p (and q respectively) before hand. Therefore, let\n\n xp = ((x mod p)^dP mod p), and\n xq = ((x mod q)^dQ mod q), yielding:\n\n y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n\n\n This can be further reduced to a simple algorithm that only\n requires 1 inverse (the q inverse is used) to be used and stored.\n The algorithm is called Garner's algorithm. If qInv is the\n inverse of q, we simply calculate:\n\n y = (qInv*(xp - xq) mod p) * q + xq\n\n However, there are two further complications. First, we need to\n ensure that xp > xq to prevent signed BigIntegers from being used\n so we add p until this is true (since we will be mod'ing with\n p anyway). Then, there is a known timing attack on algorithms\n using the CRT. To mitigate this risk, \"cryptographic blinding\"\n should be used. This requires simply generating a random number r\n between 0 and n-1 and its inverse and multiplying x by r^e before\n calculating y and then multiplying y by r^-1 afterwards. Note that\n r must be coprime with n (gcd(r, n) === 1) in order to have an\n inverse.\n */\n\n // cryptographic blinding\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),\n 16);\n } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));\n x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);\n\n // calculate xp and xq\n var xp = x.mod(key.p).modPow(key.dP, key.p);\n var xq = x.mod(key.q).modPow(key.dQ, key.q);\n\n // xp must be larger than xq to avoid signed bit usage\n while(xp.compareTo(xq) < 0) {\n xp = xp.add(key.p);\n }\n\n // do last step\n var y = xp.subtract(xq)\n .multiply(key.qInv).mod(key.p)\n .multiply(key.q).add(xq);\n\n // remove effect of random for cryptographic blinding\n y = y.multiply(r.modInverse(key.n)).mod(key.n);\n\n return y;\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or\n * 'encrypt' on a public key object instead.\n *\n * Performs RSA encryption.\n *\n * The parameter bt controls whether to put padding bytes before the\n * message passed in. Set bt to either true or false to disable padding\n * completely (in order to handle e.g. EMSA-PSS encoding seperately before),\n * signaling whether the encryption operation is a public key operation\n * (i.e. encrypting data) or not, i.e. private key operation (data signing).\n *\n * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01\n * (for signing) or 0x02 (for encryption). The key operation mode (private\n * or public) is derived from this flag in that case).\n *\n * @param m the message to encrypt as a byte string.\n * @param key the RSA key to use.\n * @param bt for PKCS#1 v1.5 padding, the block type to use\n * (0x01 for private key, 0x02 for public),\n * to disable padding: true = public key, false = private key.\n *\n * @return the encrypted bytes as a string.\n */\npki.rsa.encrypt = function(m, key, bt) {\n var pub = bt;\n var eb;\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n if(bt !== false && bt !== true) {\n // legacy, default to PKCS#1 v1.5 padding\n pub = (bt === 0x02);\n eb = _encodePkcs1_v1_5(m, key, bt);\n } else {\n eb = forge.util.createBuffer();\n eb.putBytes(m);\n }\n\n // load encryption block as big integer 'x'\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var x = new BigInteger(eb.toHex(), 16);\n\n // do RSA encryption\n var y = _modPow(x, key, pub);\n\n // convert y into the encrypted data byte string, if y is shorter in\n // bytes than k, then prepend zero bytes to fill up ed\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var yhex = y.toString(16);\n var ed = forge.util.createBuffer();\n var zeros = k - Math.ceil(yhex.length / 2);\n while(zeros > 0) {\n ed.putByte(0x00);\n --zeros;\n }\n ed.putBytes(forge.util.hexToBytes(yhex));\n return ed.getBytes();\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or\n * 'verify' on a public key object instead.\n *\n * Performs RSA decryption.\n *\n * The parameter ml controls whether to apply PKCS#1 v1.5 padding\n * or not. Set ml = false to disable padding removal completely\n * (in order to handle e.g. EMSA-PSS later on) and simply pass back\n * the RSA encryption block.\n *\n * @param ed the encrypted data to decrypt in as a byte string.\n * @param key the RSA key to use.\n * @param pub true for a public key operation, false for private.\n * @param ml the message length, if known, false to disable padding.\n *\n * @return the decrypted message as a byte string.\n */\npki.rsa.decrypt = function(ed, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n // error if the length of the encrypted data ED is not k\n if(ed.length !== k) {\n var error = new Error('Encrypted message length is invalid.');\n error.length = ed.length;\n error.expected = k;\n throw error;\n }\n\n // convert encrypted data into a big integer\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);\n\n // y must be less than the modulus or it wasn't the result of\n // a previous mod operation (encryption) using that modulus\n if(y.compareTo(key.n) >= 0) {\n throw new Error('Encrypted message is invalid.');\n }\n\n // do RSA decryption\n var x = _modPow(y, key, pub);\n\n // create the encryption block, if x is shorter in bytes than k, then\n // prepend zero bytes to fill up eb\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var xhex = x.toString(16);\n var eb = forge.util.createBuffer();\n var zeros = k - Math.ceil(xhex.length / 2);\n while(zeros > 0) {\n eb.putByte(0x00);\n --zeros;\n }\n eb.putBytes(forge.util.hexToBytes(xhex));\n\n if(ml !== false) {\n // legacy, default to PKCS#1 v1.5 padding\n return _decodePkcs1_v1_5(eb.getBytes(), key, pub);\n }\n\n // return message\n return eb.getBytes();\n};\n\n/**\n * Creates an RSA key-pair generation state object. It is used to allow\n * key-generation to be performed in steps. It also allows for a UI to\n * display progress updates.\n *\n * @param bits the size for the private key in bits, defaults to 2048.\n * @param e the public exponent to use, defaults to 65537 (0x10001).\n * @param [options] the options to use.\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n * algorithm the algorithm to use (default: 'PRIMEINC').\n *\n * @return the state object to use to generate the key-pair.\n */\npki.rsa.createKeyPairGenerationState = function(bits, e, options) {\n // TODO: migrate step-based prime generation code to forge.prime\n\n // set default bits\n if(typeof(bits) === 'string') {\n bits = parseInt(bits, 10);\n }\n bits = bits || 2048;\n\n // create prng with api that matches BigInteger secure random\n options = options || {};\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n var algorithm = options.algorithm || 'PRIMEINC';\n\n // create PRIMEINC algorithm state\n var rval;\n if(algorithm === 'PRIMEINC') {\n rval = {\n algorithm: algorithm,\n state: 0,\n bits: bits,\n rng: rng,\n eInt: e || 65537,\n e: new BigInteger(null),\n p: null,\n q: null,\n qBits: bits >> 1,\n pBits: bits - (bits >> 1),\n pqState: 0,\n num: null,\n keys: null\n };\n rval.e.fromInt(rval.eInt);\n } else {\n throw new Error('Invalid key generation algorithm: ' + algorithm);\n }\n\n return rval;\n};\n\n/**\n * Attempts to runs the key-generation algorithm for at most n seconds\n * (approximately) using the given state. When key-generation has completed,\n * the keys will be stored in state.keys.\n *\n * To use this function to update a UI while generating a key or to prevent\n * causing browser lockups/warnings, set \"n\" to a value other than 0. A\n * simple pattern for generating a key and showing a progress indicator is:\n *\n * var state = pki.rsa.createKeyPairGenerationState(2048);\n * var step = function() {\n * // step key-generation, run algorithm for 100 ms, repeat\n * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {\n * setTimeout(step, 1);\n * } else {\n * // key-generation complete\n * // TODO: turn off progress indicator here\n * // TODO: use the generated key-pair in \"state.keys\"\n * }\n * };\n * // TODO: turn on progress indicator here\n * setTimeout(step, 0);\n *\n * @param state the state to use.\n * @param n the maximum number of milliseconds to run the algorithm for, 0\n * to run the algorithm to completion.\n *\n * @return true if the key-generation completed, false if not.\n */\npki.rsa.stepKeyPairGenerationState = function(state, n) {\n // set default algorithm if not set\n if(!('algorithm' in state)) {\n state.algorithm = 'PRIMEINC';\n }\n\n // TODO: migrate step-based prime generation code to forge.prime\n // TODO: abstract as PRIMEINC algorithm\n\n // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)\n // with some minor optimizations and designed to run in steps\n\n // local state vars\n var THIRTY = new BigInteger(null);\n THIRTY.fromInt(30);\n var deltaIdx = 0;\n var op_or = function(x, y) {return x | y;};\n\n // keep stepping until time limit is reached or done\n var t1 = +new Date();\n var t2;\n var total = 0;\n while(state.keys === null && (n <= 0 || total < n)) {\n // generate p or q\n if(state.state === 0) {\n /* Note: All primes are of the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i\n\n When we generate a random number, we always align it at 30k + 1. Each\n time the number is determined not to be prime we add to get to the\n next 'i', eg: if the number was at 30k + 1 we add 6. */\n var bits = (state.p === null) ? state.pBits : state.qBits;\n var bits1 = bits - 1;\n\n // get a random number\n if(state.pqState === 0) {\n state.num = new BigInteger(bits, state.rng);\n // force MSB set\n if(!state.num.testBit(bits1)) {\n state.num.bitwiseTo(\n BigInteger.ONE.shiftLeft(bits1), op_or, state.num);\n }\n // align number on 30k+1 boundary\n state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);\n deltaIdx = 0;\n\n ++state.pqState;\n } else if(state.pqState === 1) {\n // try to make the number a prime\n if(state.num.bitLength() > bits) {\n // overflow, try again\n state.pqState = 0;\n // do primality test\n } else if(state.num.isProbablePrime(\n _getMillerRabinTests(state.num.bitLength()))) {\n ++state.pqState;\n } else {\n // get next potential prime\n state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n }\n } else if(state.pqState === 2) {\n // ensure number is coprime with e\n state.pqState =\n (state.num.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) === 0) ? 3 : 0;\n } else if(state.pqState === 3) {\n // store p or q\n state.pqState = 0;\n if(state.p === null) {\n state.p = state.num;\n } else {\n state.q = state.num;\n }\n\n // advance state if both p and q are ready\n if(state.p !== null && state.q !== null) {\n ++state.state;\n }\n state.num = null;\n }\n } else if(state.state === 1) {\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n state.num = state.p;\n state.p = state.q;\n state.q = state.num;\n }\n ++state.state;\n } else if(state.state === 2) {\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n ++state.state;\n } else if(state.state === 3) {\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {\n // phi and e are coprime, advance\n ++state.state;\n } else {\n // phi and e aren't coprime, so generate a new p and q\n state.p = null;\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 4) {\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n\n // ensure n is right number of bits\n if(state.n.bitLength() === state.bits) {\n // success, advance\n ++state.state;\n } else {\n // failed, get new q\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 5) {\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n }\n\n // update timing\n t2 = +new Date();\n total += t2 - t1;\n t1 = t2;\n }\n\n return state.keys !== null;\n};\n\n/**\n * Generates an RSA public-private key pair in a single call.\n *\n * To generate a key-pair in steps (to allow for progress updates and to\n * prevent blocking or warnings in slow browsers) then use the key-pair\n * generation state functions.\n *\n * To generate a key-pair asynchronously (either through web-workers, if\n * available, or by breaking up the work on the main thread), pass a\n * callback function.\n *\n * @param [bits] the size for the private key in bits, defaults to 2048.\n * @param [e] the public exponent to use, defaults to 65537.\n * @param [options] options for key-pair generation, if given then 'bits'\n * and 'e' must *not* be given:\n * bits the size for the private key in bits, (default: 2048).\n * e the public exponent to use, (default: 65537 (0x10001)).\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\". Disables use of native APIs.\n * algorithm the algorithm to use (default: 'PRIMEINC').\n * @param [callback(err, keypair)] called once the operation completes.\n *\n * @return an object with privateKey and publicKey properties.\n */\npki.rsa.generateKeyPair = function(bits, e, options, callback) {\n // (bits), (options), (callback)\n if(arguments.length === 1) {\n if(typeof bits === 'object') {\n options = bits;\n bits = undefined;\n } else if(typeof bits === 'function') {\n callback = bits;\n bits = undefined;\n }\n } else if(arguments.length === 2) {\n // (bits, e), (bits, options), (bits, callback), (options, callback)\n if(typeof bits === 'number') {\n if(typeof e === 'function') {\n callback = e;\n e = undefined;\n } else if(typeof e !== 'number') {\n options = e;\n e = undefined;\n }\n } else {\n options = bits;\n callback = e;\n bits = undefined;\n e = undefined;\n }\n } else if(arguments.length === 3) {\n // (bits, e, options), (bits, e, callback), (bits, options, callback)\n if(typeof e === 'number') {\n if(typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n } else {\n callback = options;\n options = e;\n e = undefined;\n }\n }\n options = options || {};\n if(bits === undefined) {\n bits = options.bits || 2048;\n }\n if(e === undefined) {\n e = options.e || 0x10001;\n }\n\n // use native code if permitted, available, and parameters are acceptable\n if(!forge.options.usePureJavaScript && !options.prng &&\n bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {\n if(callback) {\n // try native async\n if(_detectNodeCrypto('generateKeyPair')) {\n return _crypto.generateKeyPair('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n }, function(err, pub, priv) {\n if(err) {\n return callback(err);\n }\n callback(null, {\n privateKey: pki.privateKeyFromPem(priv),\n publicKey: pki.publicKeyFromPem(pub)\n });\n });\n }\n if(_detectSubtleCrypto('generateKey') &&\n _detectSubtleCrypto('exportKey')) {\n // use standard native generateKey\n return util.globalScope.crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify'])\n .then(function(pair) {\n return util.globalScope.crypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n // avoiding catch(function(err) {...}) to support IE <= 8\n }).then(undefined, function(err) {\n callback(err);\n }).then(function(pkcs8) {\n if(pkcs8) {\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n }\n });\n }\n if(_detectSubtleMsCrypto('generateKey') &&\n _detectSubtleMsCrypto('exportKey')) {\n var genOp = util.globalScope.msCrypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify']);\n genOp.oncomplete = function(e) {\n var pair = e.target.result;\n var exportOp = util.globalScope.msCrypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n exportOp.oncomplete = function(e) {\n var pkcs8 = e.target.result;\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n };\n exportOp.onerror = function(err) {\n callback(err);\n };\n };\n genOp.onerror = function(err) {\n callback(err);\n };\n return;\n }\n } else {\n // try native sync\n if(_detectNodeCrypto('generateKeyPairSync')) {\n var keypair = _crypto.generateKeyPairSync('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n return {\n privateKey: pki.privateKeyFromPem(keypair.privateKey),\n publicKey: pki.publicKeyFromPem(keypair.publicKey)\n };\n }\n }\n }\n\n // use JavaScript implementation\n var state = pki.rsa.createKeyPairGenerationState(bits, e, options);\n if(!callback) {\n pki.rsa.stepKeyPairGenerationState(state, 0);\n return state.keys;\n }\n _generateKeyPair(state, options, callback);\n};\n\n/**\n * Sets an RSA public key from BigIntegers modulus and exponent.\n *\n * @param n the modulus.\n * @param e the exponent.\n *\n * @return the public key.\n */\npki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {\n var key = {\n n: n,\n e: e\n };\n\n /**\n * Encrypts the given data with this public key. Newer applications\n * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for\n * legacy applications.\n *\n * @param data the byte string to encrypt.\n * @param scheme the encryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA encryption,\n * an object with an 'encode' property set to a function\n * with the signature 'function(data, key)' that returns\n * a binary-encoded string representing the encoded data.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the encrypted byte string.\n */\n key.encrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {\n encode: function(m, key, pub) {\n return _encodePkcs1_v1_5(m, key, 0x02).getBytes();\n }\n };\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n encode: function(m, key) {\n return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {encode: function(e) {return e;}};\n } else if(typeof scheme === 'string') {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // do scheme-based encoding then rsa encryption\n var e = scheme.encode(data, key, true);\n return pki.rsa.encrypt(e, key, true);\n };\n\n /**\n * Verifies the given signature against the given digest.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the\n * signature is an OCTET STRING that holds a DigestInfo.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * To perform PSS signature verification, provide an instance\n * of Forge PSS object as the scheme parameter.\n *\n * @param digest the message digest hash to compare against the signature,\n * as a binary-encoded string.\n * @param signature the signature to verify, as a binary-encoded string.\n * @param scheme signature verification scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be expected, but\n * PKCS#1 v1.5 padding will still be used.\n * @param options optional verify options\n * _parseAllDigestBytes testing flag to control parsing of all\n * digest bytes. Unsupported and not for general usage.\n * (default: true)\n *\n * @return true if the signature was verified, false if not.\n */\n key.verify = function(digest, signature, scheme, options) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSASSA-PKCS1-V1_5';\n }\n if(options === undefined) {\n options = {\n _parseAllDigestBytes: true\n };\n }\n if(!('_parseAllDigestBytes' in options)) {\n options._parseAllDigestBytes = true;\n }\n\n if(scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d, {\n parseAllBytes: options._parseAllDigestBytes\n });\n\n // validate DigestInfo\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {\n var error = new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value.');\n error.errors = errors;\n throw error;\n }\n // check hash algorithm identifier\n // see PKCS1-v1-5DigestAlgorithms in RFC 8017\n // FIXME: add support to vaidator for strict value choices\n var oid = asn1.derToOid(capture.algorithmIdentifier);\n if(!(oid === forge.oids.md2 ||\n oid === forge.oids.md5 ||\n oid === forge.oids.sha1 ||\n oid === forge.oids.sha224 ||\n oid === forge.oids.sha256 ||\n oid === forge.oids.sha384 ||\n oid === forge.oids.sha512 ||\n oid === forge.oids['sha512-224'] ||\n oid === forge.oids['sha512-256'])) {\n var error = new Error(\n 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');\n error.oid = oid;\n throw error;\n }\n\n // compare the given digest to the decrypted one\n return digest === capture.digest;\n }\n };\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n return digest === d;\n }\n };\n }\n\n // do rsa decryption w/o any decoding, then verify -- which does decoding\n var d = pki.rsa.decrypt(signature, key, true, false);\n return scheme.verify(digest, d, key.n.bitLength());\n };\n\n return key;\n};\n\n/**\n * Sets an RSA private key from BigIntegers modulus, exponent, primes,\n * prime exponents, and modular multiplicative inverse.\n *\n * @param n the modulus.\n * @param e the public exponent.\n * @param d the private exponent ((inverse of e) mod n).\n * @param p the first prime.\n * @param q the second prime.\n * @param dP exponent1 (d mod (p-1)).\n * @param dQ exponent2 (d mod (q-1)).\n * @param qInv ((inverse of q) mod p)\n *\n * @return the private key.\n */\npki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(\n n, e, d, p, q, dP, dQ, qInv) {\n var key = {\n n: n,\n e: e,\n d: d,\n p: p,\n q: q,\n dP: dP,\n dQ: dQ,\n qInv: qInv\n };\n\n /**\n * Decrypts the given data with this private key. The decryption scheme\n * must match the one used to encrypt the data.\n *\n * @param data the byte string to decrypt.\n * @param scheme the decryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA decryption.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the decrypted byte string.\n */\n key.decrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n // do rsa decryption w/o any decoding\n var d = pki.rsa.decrypt(data, key, false, false);\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {decode: _decodePkcs1_v1_5};\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n decode: function(d, key) {\n return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {decode: function(d) {return d;}};\n } else {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // decode according to scheme\n return scheme.decode(d, key, false);\n };\n\n /**\n * Signs the given digest, producing a signature.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide\n * an instance of Forge PSS object as the scheme parameter.\n *\n * @param md the message digest object with the hash to sign.\n * @param scheme the signature scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be used but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return the signature as a byte string.\n */\n key.sign = function(md, scheme) {\n /* Note: The internal implementation of RSA operations is being\n transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy\n code like the use of an encoding block identifier 'bt' will eventually\n be removed. */\n\n // private key operation\n var bt = false;\n\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n }\n\n if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {encode: emsaPkcs1v15encode};\n bt = 0x01;\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {encode: function() {return md;}};\n bt = 0x01;\n }\n\n // encode and then encrypt\n var d = scheme.encode(md, key.n.bitLength());\n return pki.rsa.encrypt(d, key, bt);\n };\n\n return key;\n};\n\n/**\n * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.\n *\n * @param rsaKey the ASN.1 RSAPrivateKey.\n *\n * @return the ASN.1 PrivateKeyInfo.\n */\npki.wrapRsaPrivateKey = function(rsaKey) {\n // PrivateKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // privateKeyAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // PrivateKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(rsaKey).getBytes())\n ]);\n};\n\n/**\n * Converts a private key from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a PrivateKeyInfo containing an\n * RSAPrivateKey or an RSAPrivateKey.\n *\n * @return the private key.\n */\npki.privateKeyFromAsn1 = function(obj) {\n // get PrivateKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, privateKeyValidator, capture, errors)) {\n obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));\n }\n\n // get RSAPrivateKey\n capture = {};\n errors = [];\n if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read private key. ' +\n 'ASN.1 object does not contain an RSAPrivateKey.');\n error.errors = errors;\n throw error;\n }\n\n // Note: Version is currently ignored.\n // capture.privateKeyVersion\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n, e, d, p, q, dP, dQ, qInv;\n n = forge.util.createBuffer(capture.privateKeyModulus).toHex();\n e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();\n d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();\n p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();\n q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();\n dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();\n dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();\n qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();\n\n // set private key\n return pki.setRsaPrivateKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16),\n new BigInteger(d, 16),\n new BigInteger(p, 16),\n new BigInteger(q, 16),\n new BigInteger(dP, 16),\n new BigInteger(dQ, 16),\n new BigInteger(qInv, 16));\n};\n\n/**\n * Converts a private key to an ASN.1 RSAPrivateKey.\n *\n * @param key the private key.\n *\n * @return the ASN.1 representation of an RSAPrivateKey.\n */\npki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {\n // RSAPrivateKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0 = only 2 primes, 1 multiple primes)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e)),\n // privateExponent (d)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.d)),\n // privateKeyPrime1 (p)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.p)),\n // privateKeyPrime2 (q)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.q)),\n // privateKeyExponent1 (dP)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dP)),\n // privateKeyExponent2 (dQ)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dQ)),\n // coefficient (qInv)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.qInv))\n ]);\n};\n\n/**\n * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @return the public key.\n */\npki.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, publicKeyValidator, capture, errors)) {\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n var error = new Error('Cannot read public key. Unknown OID.');\n error.oid = oid;\n throw error;\n }\n obj = capture.rsaPublicKey;\n }\n\n // get RSA params\n errors = [];\n if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {\n var error = new Error('Cannot read public key. ' +\n 'ASN.1 object does not contain an RSAPublicKey.');\n error.errors = errors;\n throw error;\n }\n\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();\n var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();\n\n // set public key\n return pki.setRsaPublicKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16));\n};\n\n/**\n * Converts a public key to an ASN.1 SubjectPublicKeyInfo.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a SubjectPublicKeyInfo.\n */\npki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {\n // SubjectPublicKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // subjectPublicKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [\n pki.publicKeyToRSAPublicKey(key)\n ])\n ]);\n};\n\n/**\n * Converts a public key to an ASN.1 RSAPublicKey.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a RSAPublicKey.\n */\npki.publicKeyToRSAPublicKey = function(key) {\n // RSAPublicKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e))\n ]);\n};\n\n/**\n * Encodes a message using PKCS#1 v1.5 padding.\n *\n * @param m the message to encode.\n * @param key the RSA key to use.\n * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02\n * (for encryption).\n *\n * @return the padded byte buffer.\n */\nfunction _encodePkcs1_v1_5(m, key, bt) {\n var eb = forge.util.createBuffer();\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* use PKCS#1 v1.5 padding */\n if(m.length > (k - 11)) {\n var error = new Error('Message is too long for PKCS#1 v1.5 padding.');\n error.length = m.length;\n error.max = k - 11;\n throw error;\n }\n\n /* A block type BT, a padding string PS, and the data D shall be\n formatted into an octet string EB, the encryption block:\n\n EB = 00 || BT || PS || 00 || D\n\n The block type BT shall be a single octet indicating the structure of\n the encryption block. For this version of the document it shall have\n value 00, 01, or 02. For a private-key operation, the block type\n shall be 00 or 01. For a public-key operation, it shall be 02.\n\n The padding string PS shall consist of k-3-||D|| octets. For block\n type 00, the octets shall have value 00; for block type 01, they\n shall have value FF; and for block type 02, they shall be\n pseudorandomly generated and nonzero. This makes the length of the\n encryption block EB equal to k. */\n\n // build the encryption block\n eb.putByte(0x00);\n eb.putByte(bt);\n\n // create the padding\n var padNum = k - 3 - m.length;\n var padByte;\n // private key op\n if(bt === 0x00 || bt === 0x01) {\n padByte = (bt === 0x00) ? 0x00 : 0xFF;\n for(var i = 0; i < padNum; ++i) {\n eb.putByte(padByte);\n }\n } else {\n // public key op\n // pad with random non-zero values\n while(padNum > 0) {\n var numZeros = 0;\n var padBytes = forge.random.getBytes(padNum);\n for(var i = 0; i < padNum; ++i) {\n padByte = padBytes.charCodeAt(i);\n if(padByte === 0) {\n ++numZeros;\n } else {\n eb.putByte(padByte);\n }\n }\n padNum = numZeros;\n }\n }\n\n // zero followed by message\n eb.putByte(0x00);\n eb.putBytes(m);\n\n return eb;\n}\n\n/**\n * Decodes a message using PKCS#1 v1.5 padding.\n *\n * @param em the message to decode.\n * @param key the RSA key to use.\n * @param pub true if the key is a public key, false if it is private.\n * @param ml the message length, if specified.\n *\n * @return the decoded bytes.\n */\nfunction _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* It is an error if any of the following conditions occurs:\n\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer than eight octets\n or is inconsisent with the block type BT.\n 3. The decryption process is a public-key operation and the block\n type BT is not 00 or 01, or the decryption process is a\n private-key operation and the block type is not 02.\n */\n\n // parse the encryption block\n var eb = forge.util.createBuffer(em);\n var first = eb.getByte();\n var bt = eb.getByte();\n if(first !== 0x00 ||\n (pub && bt !== 0x00 && bt !== 0x01) ||\n (!pub && bt != 0x02) ||\n (pub && bt === 0x00 && typeof(ml) === 'undefined')) {\n throw new Error('Encryption block is invalid.');\n }\n\n var padNum = 0;\n if(bt === 0x00) {\n // check all padding bytes for 0x00\n padNum = k - 3 - ml;\n for(var i = 0; i < padNum; ++i) {\n if(eb.getByte() !== 0x00) {\n throw new Error('Encryption block is invalid.');\n }\n }\n } else if(bt === 0x01) {\n // find the first byte that isn't 0xFF, should be after all padding\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() !== 0xFF) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n } else if(bt === 0x02) {\n // look for 0x00 byte\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() === 0x00) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n }\n\n // zero must be 0x00 and padNum must be (k - 3 - message length)\n var zero = eb.getByte();\n if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {\n throw new Error('Encryption block is invalid.');\n }\n\n return eb.getBytes();\n}\n\n/**\n * Runs the key-generation algorithm asynchronously, either in the background\n * via Web Workers, or using the main thread and setImmediate.\n *\n * @param state the key-pair generation state.\n * @param [options] options for key-pair generation:\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2, -1 to use estimated cores minus one).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * @param callback(err, keypair) called once the operation completes.\n */\nfunction _generateKeyPair(state, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n var opts = {\n algorithm: {\n name: options.algorithm || 'PRIMEINC',\n options: {\n workers: options.workers || 2,\n workLoad: options.workLoad || 100,\n workerScript: options.workerScript\n }\n }\n };\n if('prng' in options) {\n opts.prng = options.prng;\n }\n\n generate();\n\n function generate() {\n // find p and then q (done in series to simplify)\n getPrime(state.pBits, function(err, num) {\n if(err) {\n return callback(err);\n }\n state.p = num;\n if(state.q !== null) {\n return finish(err, state.q);\n }\n getPrime(state.qBits, finish);\n });\n }\n\n function getPrime(bits, callback) {\n forge.prime.generateProbablePrime(bits, opts, callback);\n }\n\n function finish(err, num) {\n if(err) {\n return callback(err);\n }\n\n // set q\n state.q = num;\n\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n var tmp = state.p;\n state.p = state.q;\n state.q = tmp;\n }\n\n // ensure p is coprime with e\n if(state.p.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.p = null;\n generate();\n return;\n }\n\n // ensure q is coprime with e\n if(state.q.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {\n // phi and e aren't coprime, so generate a new p and q\n state.p = state.q = null;\n generate();\n return;\n }\n\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n if(state.n.bitLength() !== state.bits) {\n // failed, get new q\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n\n callback(null, state.keys);\n }\n}\n\n/**\n * Converts a positive BigInteger into 2's-complement big-endian bytes.\n *\n * @param b the big integer to convert.\n *\n * @return the bytes.\n */\nfunction _bnToBytes(b) {\n // prepend 0x00 if first byte >= 0x80\n var hex = b.toString(16);\n if(hex[0] >= '8') {\n hex = '00' + hex;\n }\n var bytes = forge.util.hexToBytes(hex);\n\n // ensure integer is minimally-encoded\n if(bytes.length > 1 &&\n // leading 0x00 for positive integer\n ((bytes.charCodeAt(0) === 0 &&\n (bytes.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (bytes.charCodeAt(0) === 0xFF &&\n (bytes.charCodeAt(1) & 0x80) === 0x80))) {\n return bytes.substr(1);\n }\n return bytes;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction _getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n/**\n * Performs feature detection on the Node crypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectNodeCrypto(fn) {\n return forge.util.isNodejs && typeof _crypto[fn] === 'function';\n}\n\n/**\n * Performs feature detection on the SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.crypto === 'object' &&\n typeof util.globalScope.crypto.subtle === 'object' &&\n typeof util.globalScope.crypto.subtle[fn] === 'function');\n}\n\n/**\n * Performs feature detection on the deprecated Microsoft Internet Explorer\n * outdated SubtleCrypto interface. This function should only be used after\n * checking for the modern, standard SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleMsCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.msCrypto === 'object' &&\n typeof util.globalScope.msCrypto.subtle === 'object' &&\n typeof util.globalScope.msCrypto.subtle[fn] === 'function');\n}\n\nfunction _intToUint8Array(x) {\n var bytes = forge.util.hexToBytes(x.toString(16));\n var buffer = new Uint8Array(bytes.length);\n for(var i = 0; i < bytes.length; ++i) {\n buffer[i] = bytes.charCodeAt(i);\n }\n return buffer;\n}\n\nfunction _privateKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error(\n 'Unsupported key algorithm \"' + jwk.kty + '\"; algorithm must be \"RSA\".');\n }\n return pki.setRsaPrivateKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e),\n _base64ToBigInt(jwk.d),\n _base64ToBigInt(jwk.p),\n _base64ToBigInt(jwk.q),\n _base64ToBigInt(jwk.dp),\n _base64ToBigInt(jwk.dq),\n _base64ToBigInt(jwk.qi));\n}\n\nfunction _publicKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error('Key algorithm must be \"RSA\".');\n }\n return pki.setRsaPublicKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e));\n}\n\nfunction _base64ToBigInt(b64) {\n return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);\n}\n","/**\n * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha1 = module.exports = forge.sha1 = forge.sha1 || {};\nforge.md.sha1 = forge.md.algorithms.sha1 = sha1;\n\n/**\n * Creates a SHA-1 message digest object.\n *\n * @return a message digest object.\n */\nsha1.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-1 state contains five 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(80);\n\n // message digest object\n var md = {\n algorithm: 'sha1',\n blockLength: 64,\n digestLength: 20,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-1 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n return rval;\n };\n\n return md;\n};\n\n// sha-1 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-1 state with the given byte buffer.\n *\n * @param s the SHA-1 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = bytes.getInt32();\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.\n *\n * See FIPS 180-2 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha256 = module.exports = forge.sha256 = forge.sha256 || {};\nforge.md.sha256 = forge.md.algorithms.sha256 = sha256;\n\n/**\n * Creates a SHA-256 message digest object.\n *\n * @return a message digest object.\n */\nsha256.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-256 state contains eight 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(64);\n\n // message digest object\n var md = {\n algorithm: 'sha256',\n blockLength: 64,\n digestLength: 32,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-256 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4,\n h5: _state.h5,\n h6: _state.h6,\n h7: _state.h7\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n rval.putInt32(s2.h5);\n rval.putInt32(s2.h6);\n rval.putInt32(s2.h7);\n return rval;\n };\n\n return md;\n};\n\n// sha-256 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // create K table for SHA-256\n _k = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-256 state with the given byte buffer.\n *\n * @param s the SHA-256 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n a = (t1 + t2) >>> 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n}\n","/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n *\n * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For\n * SHA-256 (block size 512 bits), see sha256.js.\n *\n * See FIPS 180-4 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha512 = module.exports = forge.sha512 = forge.sha512 || {};\n\n// SHA-512\nforge.md.sha512 = forge.md.algorithms.sha512 = sha512;\n\n// SHA-384\nvar sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};\nsha384.create = function() {\n return sha512.create('SHA-384');\n};\nforge.md.sha384 = forge.md.algorithms.sha384 = sha384;\n\n// SHA-512/256\nforge.sha512.sha256 = forge.sha512.sha256 || {\n create: function() {\n return sha512.create('SHA-512/256');\n }\n};\nforge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =\n forge.sha512.sha256;\n\n// SHA-512/224\nforge.sha512.sha224 = forge.sha512.sha224 || {\n create: function() {\n return sha512.create('SHA-512/224');\n }\n};\nforge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =\n forge.sha512.sha224;\n\n/**\n * Creates a SHA-2 message digest object.\n *\n * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,\n * SHA-512/256).\n *\n * @return a message digest object.\n */\nsha512.create = function(algorithm) {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n if(typeof algorithm === 'undefined') {\n algorithm = 'SHA-512';\n }\n\n if(!(algorithm in _states)) {\n throw new Error('Invalid SHA-512 algorithm: ' + algorithm);\n }\n\n // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)\n var _state = _states[algorithm];\n var _h = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for 64-bit word storage\n var _w = new Array(80);\n for(var wi = 0; wi < 80; ++wi) {\n _w[wi] = new Array(2);\n }\n\n // determine digest length by algorithm name (default)\n var digestLength = 64;\n switch(algorithm) {\n case 'SHA-384':\n digestLength = 48;\n break;\n case 'SHA-512/256':\n digestLength = 32;\n break;\n case 'SHA-512/224':\n digestLength = 28;\n break;\n }\n\n // message digest object\n var md = {\n // SHA-512 => sha512\n algorithm: algorithm.replace('-', '').toLowerCase(),\n blockLength: 128,\n digestLength: digestLength,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 16\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength128 for backwards-compatibility)\n md.fullMessageLength = md.messageLength128 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _h = new Array(_state.length);\n for(var i = 0; i < _state.length; ++i) {\n _h[i] = _state[i].slice(0);\n }\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_h, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-512 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 896 mod 1024. In other words,\n the data to be digested must be a multiple of 1024 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 16 bytes (128\n bits), that means that the last segment of the data must have 112 bytes\n (896 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 896 mod 1024 because\n 1024 - 128 = 896.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 896 mod 1024, then 1024 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var h = new Array(_h.length);\n for(var i = 0; i < _h.length; ++i) {\n h[i] = _h[i].slice(0);\n }\n _update(h, _w, finalBlock);\n var rval = forge.util.createBuffer();\n var hlen;\n if(algorithm === 'SHA-512') {\n hlen = h.length;\n } else if(algorithm === 'SHA-384') {\n hlen = h.length - 2;\n } else {\n hlen = h.length - 4;\n }\n for(var i = 0; i < hlen; ++i) {\n rval.putInt32(h[i][0]);\n if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {\n rval.putInt32(h[i][1]);\n }\n }\n return rval;\n };\n\n return md;\n};\n\n// sha-512 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n// initial hash states\nvar _states = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 128);\n\n // create K table for SHA-512\n _k = [\n [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],\n [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],\n [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],\n [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],\n [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],\n [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],\n [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],\n [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],\n [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],\n [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],\n [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],\n [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],\n [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],\n [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],\n [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],\n [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],\n [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],\n [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],\n [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],\n [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],\n [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],\n [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],\n [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],\n [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],\n [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],\n [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],\n [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],\n [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],\n [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],\n [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],\n [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],\n [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],\n [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],\n [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],\n [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],\n [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],\n [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],\n [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],\n [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],\n [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]\n ];\n\n // initial hash states\n _states = {};\n _states['SHA-512'] = [\n [0x6a09e667, 0xf3bcc908],\n [0xbb67ae85, 0x84caa73b],\n [0x3c6ef372, 0xfe94f82b],\n [0xa54ff53a, 0x5f1d36f1],\n [0x510e527f, 0xade682d1],\n [0x9b05688c, 0x2b3e6c1f],\n [0x1f83d9ab, 0xfb41bd6b],\n [0x5be0cd19, 0x137e2179]\n ];\n _states['SHA-384'] = [\n [0xcbbb9d5d, 0xc1059ed8],\n [0x629a292a, 0x367cd507],\n [0x9159015a, 0x3070dd17],\n [0x152fecd8, 0xf70e5939],\n [0x67332667, 0xffc00b31],\n [0x8eb44a87, 0x68581511],\n [0xdb0c2e0d, 0x64f98fa7],\n [0x47b5481d, 0xbefa4fa4]\n ];\n _states['SHA-512/256'] = [\n [0x22312194, 0xFC2BF72C],\n [0x9F555FA3, 0xC84C64C2],\n [0x2393B86B, 0x6F53B151],\n [0x96387719, 0x5940EABD],\n [0x96283EE2, 0xA88EFFE3],\n [0xBE5E1E25, 0x53863992],\n [0x2B0199FC, 0x2C85B8AA],\n [0x0EB72DDC, 0x81C52CA2]\n ];\n _states['SHA-512/224'] = [\n [0x8C3D37C8, 0x19544DA2],\n [0x73E19966, 0x89DCD4D6],\n [0x1DFAB7AE, 0x32FF9C82],\n [0x679DD514, 0x582F9FCF],\n [0x0F6D2B69, 0x7BD44DA8],\n [0x77E36F73, 0x04C48942],\n [0x3F9D85A8, 0x6A1D36C8],\n [0x1112E6AD, 0x91D692A1]\n ];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-512 state with the given byte buffer.\n *\n * @param s the SHA-512 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (128 byte) chunks\n var t1_hi, t1_lo;\n var t2_hi, t2_lo;\n var s0_hi, s0_lo;\n var s1_hi, s1_lo;\n var ch_hi, ch_lo;\n var maj_hi, maj_lo;\n var a_hi, a_lo;\n var b_hi, b_lo;\n var c_hi, c_lo;\n var d_hi, d_lo;\n var e_hi, e_lo;\n var f_hi, f_lo;\n var g_hi, g_lo;\n var h_hi, h_lo;\n var i, hi, lo, w2, w7, w15, w16;\n var len = bytes.length();\n while(len >= 128) {\n // the w array will be populated with sixteen 64-bit big-endian words\n // and then extended into 64 64-bit words according to SHA-512\n for(i = 0; i < 16; ++i) {\n w[i][0] = bytes.getInt32() >>> 0;\n w[i][1] = bytes.getInt32() >>> 0;\n }\n for(; i < 80; ++i) {\n // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)\n w2 = w[i - 2];\n hi = w2[0];\n lo = w2[1];\n\n // high bits\n t1_hi = (\n ((hi >>> 19) | (lo << 13)) ^ // ROTR 19\n ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)\n (hi >>> 6)) >>> 0; // SHR 6\n // low bits\n t1_lo = (\n ((hi << 13) | (lo >>> 19)) ^ // ROTR 19\n ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)\n ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6\n\n // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)\n w15 = w[i - 15];\n hi = w15[0];\n lo = w15[1];\n\n // high bits\n t2_hi = (\n ((hi >>> 1) | (lo << 31)) ^ // ROTR 1\n ((hi >>> 8) | (lo << 24)) ^ // ROTR 8\n (hi >>> 7)) >>> 0; // SHR 7\n // low bits\n t2_lo = (\n ((hi << 31) | (lo >>> 1)) ^ // ROTR 1\n ((hi << 24) | (lo >>> 8)) ^ // ROTR 8\n ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7\n\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)\n w7 = w[i - 7];\n w16 = w[i - 16];\n lo = (t1_lo + w7[1] + t2_lo + w16[1]);\n w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n w[i][1] = lo >>> 0;\n }\n\n // initialize hash value for this chunk\n a_hi = s[0][0];\n a_lo = s[0][1];\n b_hi = s[1][0];\n b_lo = s[1][1];\n c_hi = s[2][0];\n c_lo = s[2][1];\n d_hi = s[3][0];\n d_lo = s[3][1];\n e_hi = s[4][0];\n e_lo = s[4][1];\n f_hi = s[5][0];\n f_lo = s[5][1];\n g_hi = s[6][0];\n g_lo = s[6][1];\n h_hi = s[7][0];\n h_lo = s[7][1];\n\n // round function\n for(i = 0; i < 80; ++i) {\n // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)\n s1_hi = (\n ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14\n ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18\n ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)\n s1_lo = (\n ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14\n ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18\n ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)\n\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;\n ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;\n\n // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)\n s0_hi = (\n ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28\n ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)\n s0_lo = (\n ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28\n ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)\n\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;\n maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;\n\n // main algorithm\n // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)\n lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);\n t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n t1_lo = lo >>> 0;\n\n // t2 = s0 + maj modulo 2^64 (carry lo overflow)\n lo = s0_lo + maj_lo;\n t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n t2_lo = lo >>> 0;\n\n h_hi = g_hi;\n h_lo = g_lo;\n\n g_hi = f_hi;\n g_lo = f_lo;\n\n f_hi = e_hi;\n f_lo = e_lo;\n\n // e = (d + t1) modulo 2^64 (carry lo overflow)\n lo = d_lo + t1_lo;\n e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n e_lo = lo >>> 0;\n\n d_hi = c_hi;\n d_lo = c_lo;\n\n c_hi = b_hi;\n c_lo = b_lo;\n\n b_hi = a_hi;\n b_lo = a_lo;\n\n // a = (t1 + t2) modulo 2^64 (carry lo overflow)\n lo = t1_lo + t2_lo;\n a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n a_lo = lo >>> 0;\n }\n\n // update hash state (additional modulo 2^64)\n lo = s[0][1] + a_lo;\n s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[0][1] = lo >>> 0;\n\n lo = s[1][1] + b_lo;\n s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[1][1] = lo >>> 0;\n\n lo = s[2][1] + c_lo;\n s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[2][1] = lo >>> 0;\n\n lo = s[3][1] + d_lo;\n s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[3][1] = lo >>> 0;\n\n lo = s[4][1] + e_lo;\n s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[4][1] = lo >>> 0;\n\n lo = s[5][1] + f_lo;\n s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[5][1] = lo >>> 0;\n\n lo = s[6][1] + g_lo;\n s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[6][1] = lo >>> 0;\n\n lo = s[7][1] + h_lo;\n s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[7][1] = lo >>> 0;\n\n len -= 128;\n }\n}\n","/**\n * Functions to output keys in SSH-friendly formats.\n *\n * This is part of the Forge project which may be used under the terms of\n * either the BSD License or the GNU General Public License (GPL) Version 2.\n *\n * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE\n *\n * @author https://github.com/shellac\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./hmac');\nrequire('./md5');\nrequire('./sha1');\nrequire('./util');\n\nvar ssh = module.exports = forge.ssh = forge.ssh || {};\n\n/**\n * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file.\n *\n * @param privateKey the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n * @param comment a comment to include in the key file.\n *\n * @return the PPK file as a string.\n */\nssh.privateKeyToPutty = function(privateKey, passphrase, comment) {\n comment = comment || '';\n passphrase = passphrase || '';\n var algorithm = 'ssh-rsa';\n var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc';\n\n var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\\r\\n';\n ppk += 'Encryption: ' + encryptionAlgorithm + '\\r\\n';\n ppk += 'Comment: ' + comment + '\\r\\n';\n\n // public key into buffer for ppk\n var pubbuffer = forge.util.createBuffer();\n _addStringToBuffer(pubbuffer, algorithm);\n _addBigIntegerToBuffer(pubbuffer, privateKey.e);\n _addBigIntegerToBuffer(pubbuffer, privateKey.n);\n\n // write public key\n var pub = forge.util.encode64(pubbuffer.bytes(), 64);\n var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \\r\\n\n ppk += 'Public-Lines: ' + length + '\\r\\n';\n ppk += pub;\n\n // private key into a buffer\n var privbuffer = forge.util.createBuffer();\n _addBigIntegerToBuffer(privbuffer, privateKey.d);\n _addBigIntegerToBuffer(privbuffer, privateKey.p);\n _addBigIntegerToBuffer(privbuffer, privateKey.q);\n _addBigIntegerToBuffer(privbuffer, privateKey.qInv);\n\n // optionally encrypt the private key\n var priv;\n if(!passphrase) {\n // use the unencrypted buffer\n priv = forge.util.encode64(privbuffer.bytes(), 64);\n } else {\n // encrypt RSA key using passphrase\n var encLen = privbuffer.length() + 16 - 1;\n encLen -= encLen % 16;\n\n // pad private key with sha1-d data -- needs to be a multiple of 16\n var padding = _sha1(privbuffer.bytes());\n\n padding.truncate(padding.length() - encLen + privbuffer.length());\n privbuffer.putBuffer(padding);\n\n var aeskey = forge.util.createBuffer();\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x00', passphrase));\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x01', passphrase));\n\n // encrypt some bytes using CBC mode\n // key is 40 bytes, so truncate *by* 8 bytes\n var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC');\n cipher.start(forge.util.createBuffer().fillWithByte(0, 16));\n cipher.update(privbuffer.copy());\n cipher.finish();\n var encrypted = cipher.output;\n\n // Note: this appears to differ from Putty -- is forge wrong, or putty?\n // due to padding we finish as an exact multiple of 16\n encrypted.truncate(16); // all padding\n\n priv = forge.util.encode64(encrypted.bytes(), 64);\n }\n\n // output private key\n length = Math.floor(priv.length / 66) + 1; // 64 + \\r\\n\n ppk += '\\r\\nPrivate-Lines: ' + length + '\\r\\n';\n ppk += priv;\n\n // MAC\n var mackey = _sha1('putty-private-key-file-mac-key', passphrase);\n\n var macbuffer = forge.util.createBuffer();\n _addStringToBuffer(macbuffer, algorithm);\n _addStringToBuffer(macbuffer, encryptionAlgorithm);\n _addStringToBuffer(macbuffer, comment);\n macbuffer.putInt32(pubbuffer.length());\n macbuffer.putBuffer(pubbuffer);\n macbuffer.putInt32(privbuffer.length());\n macbuffer.putBuffer(privbuffer);\n\n var hmac = forge.hmac.create();\n hmac.start('sha1', mackey);\n hmac.update(macbuffer.bytes());\n\n ppk += '\\r\\nPrivate-MAC: ' + hmac.digest().toHex() + '\\r\\n';\n\n return ppk;\n};\n\n/**\n * Encodes a public RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param comment a comment.\n *\n * @return the public key in OpenSSH format.\n */\nssh.publicKeyToOpenSSH = function(key, comment) {\n var type = 'ssh-rsa';\n comment = comment || '';\n\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment;\n};\n\n/**\n * Encodes a private RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n *\n * @return the public key in OpenSSH format.\n */\nssh.privateKeyToOpenSSH = function(privateKey, passphrase) {\n if(!passphrase) {\n return forge.pki.privateKeyToPem(privateKey);\n }\n // OpenSSH private key is just a legacy format, it seems\n return forge.pki.encryptRsaPrivateKey(privateKey, passphrase,\n {legacy: true, algorithm: 'aes128'});\n};\n\n/**\n * Gets the SSH fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.md5).\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\nssh.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.md5.create();\n\n var type = 'ssh-rsa';\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n // hash public key bytes\n md.start();\n md.update(buffer.getBytes());\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a big integer.\n */\nfunction _addBigIntegerToBuffer(buffer, val) {\n var hexVal = val.toString(16);\n // ensure 2s complement +ve\n if(hexVal[0] >= '8') {\n hexVal = '00' + hexVal;\n }\n var bytes = forge.util.hexToBytes(hexVal);\n buffer.putInt32(bytes.length);\n buffer.putBytes(bytes);\n}\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a string.\n */\nfunction _addStringToBuffer(buffer, val) {\n buffer.putInt32(val.length);\n buffer.putString(val);\n}\n\n/**\n * Hashes the arguments into one value using SHA-1.\n *\n * @return the sha1 hash of the provided arguments.\n */\nfunction _sha1() {\n var sha = forge.md.sha1.create();\n var num = arguments.length;\n for (var i = 0; i < num; ++i) {\n sha.update(arguments[i]);\n }\n return sha.digest();\n}\n","/**\n * A Javascript implementation of Transport Layer Security (TLS).\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n *\n * The TLS Handshake Protocol involves the following steps:\n *\n * - Exchange hello messages to agree on algorithms, exchange random values,\n * and check for session resumption.\n *\n * - Exchange the necessary cryptographic parameters to allow the client and\n * server to agree on a premaster secret.\n *\n * - Exchange certificates and cryptographic information to allow the client\n * and server to authenticate themselves.\n *\n * - Generate a master secret from the premaster secret and exchanged random\n * values.\n *\n * - Provide security parameters to the record layer.\n *\n * - Allow the client and server to verify that their peer has calculated the\n * same security parameters and that the handshake occurred without tampering\n * by an attacker.\n *\n * Up to 4 different messages may be sent during a key exchange. The server\n * certificate, the server key exchange, the client certificate, and the\n * client key exchange.\n *\n * A typical handshake (from the client's perspective).\n *\n * 1. Client sends ClientHello.\n * 2. Client receives ServerHello.\n * 3. Client receives optional Certificate.\n * 4. Client receives optional ServerKeyExchange.\n * 5. Client receives ServerHelloDone.\n * 6. Client sends optional Certificate.\n * 7. Client sends ClientKeyExchange.\n * 8. Client sends optional CertificateVerify.\n * 9. Client sends ChangeCipherSpec.\n * 10. Client sends Finished.\n * 11. Client receives ChangeCipherSpec.\n * 12. Client receives Finished.\n * 13. Client sends/receives application data.\n *\n * To reuse an existing session:\n *\n * 1. Client sends ClientHello with session ID for reuse.\n * 2. Client receives ServerHello with same session ID if reusing.\n * 3. Client receives ChangeCipherSpec message if reusing.\n * 4. Client receives Finished.\n * 5. Client sends ChangeCipherSpec.\n * 6. Client sends Finished.\n *\n * Note: Client ignores HelloRequest if in the middle of a handshake.\n *\n * Record Layer:\n *\n * The record layer fragments information blocks into TLSPlaintext records\n * carrying data in chunks of 2^14 bytes or less. Client message boundaries are\n * not preserved in the record layer (i.e., multiple client messages of the\n * same ContentType MAY be coalesced into a single TLSPlaintext record, or a\n * single message MAY be fragmented across several records).\n *\n * struct {\n * uint8 major;\n * uint8 minor;\n * } ProtocolVersion;\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * opaque fragment[TLSPlaintext.length];\n * } TLSPlaintext;\n *\n * type:\n * The higher-level protocol used to process the enclosed fragment.\n *\n * version:\n * The version of the protocol being employed. TLS Version 1.2 uses version\n * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that\n * supports multiple versions of TLS may not know what version will be\n * employed before it receives the ServerHello.\n *\n * length:\n * The length (in bytes) of the following TLSPlaintext.fragment. The length\n * MUST NOT exceed 2^14 = 16384 bytes.\n *\n * fragment:\n * The application data. This data is transparent and treated as an\n * independent block to be dealt with by the higher-level protocol specified\n * by the type field.\n *\n * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or\n * ChangeCipherSpec content types. Zero-length fragments of Application data\n * MAY be sent as they are potentially useful as a traffic analysis\n * countermeasure.\n *\n * Note: Data of different TLS record layer content types MAY be interleaved.\n * Application data is generally of lower precedence for transmission than\n * other content types. However, records MUST be delivered to the network in\n * the same order as they are protected by the record layer. Recipients MUST\n * receive and process interleaved application layer traffic during handshakes\n * subsequent to the first one on a connection.\n *\n * struct {\n * ContentType type; // same as TLSPlaintext.type\n * ProtocolVersion version;// same as TLSPlaintext.version\n * uint16 length;\n * opaque fragment[TLSCompressed.length];\n * } TLSCompressed;\n *\n * length:\n * The length (in bytes) of the following TLSCompressed.fragment.\n * The length MUST NOT exceed 2^14 + 1024.\n *\n * fragment:\n * The compressed form of TLSPlaintext.fragment.\n *\n * Note: A CompressionMethod.null operation is an identity operation; no fields\n * are altered. In this implementation, since no compression is supported,\n * uncompressed records are always the same as compressed records.\n *\n * Encryption Information:\n *\n * The encryption and MAC functions translate a TLSCompressed structure into a\n * TLSCiphertext. The decryption functions reverse the process. The MAC of the\n * record also includes a sequence number so that missing, extra, or repeated\n * messages are detectable.\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * select (SecurityParameters.cipher_type) {\n * case stream: GenericStreamCipher;\n * case block: GenericBlockCipher;\n * case aead: GenericAEADCipher;\n * } fragment;\n * } TLSCiphertext;\n *\n * type:\n * The type field is identical to TLSCompressed.type.\n *\n * version:\n * The version field is identical to TLSCompressed.version.\n *\n * length:\n * The length (in bytes) of the following TLSCiphertext.fragment.\n * The length MUST NOT exceed 2^14 + 2048.\n *\n * fragment:\n * The encrypted form of TLSCompressed.fragment, with the MAC.\n *\n * Note: Only CBC Block Ciphers are supported by this implementation.\n *\n * The TLSCompressed.fragment structures are converted to/from block\n * TLSCiphertext.fragment structures.\n *\n * struct {\n * opaque IV[SecurityParameters.record_iv_length];\n * block-ciphered struct {\n * opaque content[TLSCompressed.length];\n * opaque MAC[SecurityParameters.mac_length];\n * uint8 padding[GenericBlockCipher.padding_length];\n * uint8 padding_length;\n * };\n * } GenericBlockCipher;\n *\n * The MAC is generated as described in Section 6.2.3.1.\n *\n * IV:\n * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be\n * unpredictable. Note that in versions of TLS prior to 1.1, there was no\n * IV field, and the last ciphertext block of the previous record (the \"CBC\n * residue\") was used as the IV. This was changed to prevent the attacks\n * described in [CBCATT]. For block ciphers, the IV length is of length\n * SecurityParameters.record_iv_length, which is equal to the\n * SecurityParameters.block_size.\n *\n * padding:\n * Padding that is added to force the length of the plaintext to be an\n * integral multiple of the block cipher's block length. The padding MAY be\n * any length up to 255 bytes, as long as it results in the\n * TLSCiphertext.length being an integral multiple of the block length.\n * Lengths longer than necessary might be desirable to frustrate attacks on\n * a protocol that are based on analysis of the lengths of exchanged\n * messages. Each uint8 in the padding data vector MUST be filled with the\n * padding length value. The receiver MUST check this padding and MUST use\n * the bad_record_mac alert to indicate padding errors.\n *\n * padding_length:\n * The padding length MUST be such that the total size of the\n * GenericBlockCipher structure is a multiple of the cipher's block length.\n * Legal values range from zero to 255, inclusive. This length specifies the\n * length of the padding field exclusive of the padding_length field itself.\n *\n * The encrypted data length (TLSCiphertext.length) is one more than the sum of\n * SecurityParameters.block_length, TLSCompressed.length,\n * SecurityParameters.mac_length, and padding_length.\n *\n * Example: If the block length is 8 bytes, the content length\n * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the\n * length before padding is 82 bytes (this does not include the IV. Thus, the\n * padding length modulo 8 must be equal to 6 in order to make the total length\n * an even multiple of 8 bytes (the block length). The padding length can be\n * 6, 14, 22, and so on, through 254. If the padding length were the minimum\n * necessary, 6, the padding would be 6 bytes, each containing the value 6.\n * Thus, the last 8 octets of the GenericBlockCipher before block encryption\n * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC.\n *\n * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical\n * that the entire plaintext of the record be known before any ciphertext is\n * transmitted. Otherwise, it is possible for the attacker to mount the attack\n * described in [CBCATT].\n *\n * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing\n * attack on CBC padding based on the time required to compute the MAC. In\n * order to defend against this attack, implementations MUST ensure that\n * record processing time is essentially the same whether or not the padding\n * is correct. In general, the best way to do this is to compute the MAC even\n * if the padding is incorrect, and only then reject the packet. For instance,\n * if the pad appears to be incorrect, the implementation might assume a\n * zero-length pad and then compute the MAC. This leaves a small timing\n * channel, since MAC performance depends, to some extent, on the size of the\n * data fragment, but it is not believed to be large enough to be exploitable,\n * due to the large block size of existing MACs and the small size of the\n * timing signal.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./md5');\nrequire('./pem');\nrequire('./pki');\nrequire('./random');\nrequire('./sha1');\nrequire('./util');\n\n/**\n * Generates pseudo random bytes by mixing the result of two hash functions,\n * MD5 and SHA-1.\n *\n * prf_TLS1(secret, label, seed) =\n * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);\n *\n * Each P_hash function functions as follows:\n *\n * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +\n * HMAC_hash(secret, A(2) + seed) +\n * HMAC_hash(secret, A(3) + seed) + ...\n * A() is defined as:\n * A(0) = seed\n * A(i) = HMAC_hash(secret, A(i-1))\n *\n * The '+' operator denotes concatenation.\n *\n * As many iterations A(N) as are needed are performed to generate enough\n * pseudo random byte output. If an iteration creates more data than is\n * necessary, then it is truncated.\n *\n * Therefore:\n * A(1) = HMAC_hash(secret, A(0))\n * = HMAC_hash(secret, seed)\n * A(2) = HMAC_hash(secret, A(1))\n * = HMAC_hash(secret, HMAC_hash(secret, seed))\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +\n * ...\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +\n * ...\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_TLS1 = function(secret, label, seed, length) {\n var rval = forge.util.createBuffer();\n\n /* For TLS 1.0, the secret is split in half, into two secrets of equal\n length. If the secret has an odd length then the last byte of the first\n half will be the same as the first byte of the second. The length of the\n two secrets is half of the secret rounded up. */\n var idx = (secret.length >> 1);\n var slen = idx + (secret.length & 1);\n var s1 = secret.substr(0, slen);\n var s2 = secret.substr(idx, slen);\n var ai = forge.util.createBuffer();\n var hmac = forge.hmac.create();\n seed = label + seed;\n\n // determine the number of iterations that must be performed to generate\n // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20\n var md5itr = Math.ceil(length / 16);\n var sha1itr = Math.ceil(length / 20);\n\n // do md5 iterations\n hmac.start('MD5', s1);\n var md5bytes = forge.util.createBuffer();\n ai.putBytes(seed);\n for(var i = 0; i < md5itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n md5bytes.putBuffer(hmac.digest());\n }\n\n // do sha1 iterations\n hmac.start('SHA1', s2);\n var sha1bytes = forge.util.createBuffer();\n ai.clear();\n ai.putBytes(seed);\n for(var i = 0; i < sha1itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n sha1bytes.putBuffer(hmac.digest());\n }\n\n // XOR the md5 bytes with the sha1 bytes\n rval.putBytes(forge.util.xorBytes(\n md5bytes.getBytes(), sha1bytes.getBytes(), length));\n\n return rval;\n};\n\n/**\n * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2.\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_sha256 = function(secret, label, seed, length) {\n // FIXME: implement me for TLS 1.2\n};\n\n/**\n * Gets a MAC for a record using the SHA-1 hash algorithm.\n *\n * @param key the mac key.\n * @param state the sequence number (array of two 32-bit integers).\n * @param record the record.\n *\n * @return the sha-1 hash (20 bytes) for the given record.\n */\nvar hmac_sha1 = function(key, seqNum, record) {\n /* MAC is computed like so:\n HMAC_hash(\n key, seqNum +\n TLSCompressed.type +\n TLSCompressed.version +\n TLSCompressed.length +\n TLSCompressed.fragment)\n */\n var hmac = forge.hmac.create();\n hmac.start('SHA1', key);\n var b = forge.util.createBuffer();\n b.putInt32(seqNum[0]);\n b.putInt32(seqNum[1]);\n b.putByte(record.type);\n b.putByte(record.version.major);\n b.putByte(record.version.minor);\n b.putInt16(record.length);\n b.putBytes(record.fragment.bytes());\n hmac.update(b.getBytes());\n return hmac.digest().getBytes();\n};\n\n/**\n * Compresses the TLSPlaintext record into a TLSCompressed record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSPlaintext record to compress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar deflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.deflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // deflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Decompresses the TLSCompressed record into a TLSPlaintext record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSCompressed record to decompress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar inflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.inflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // inflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Reads a TLS variable-length vector from a byte buffer.\n *\n * Variable-length vectors are defined by specifying a subrange of legal\n * lengths, inclusively, using the notation . When these are\n * encoded, the actual length precedes the vector's contents in the byte\n * stream. The length will be in the form of a number consuming as many bytes\n * as required to hold the vector's specified maximum (ceiling) length. A\n * variable-length vector with an actual length field of zero is referred to\n * as an empty vector.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n *\n * @return the resulting byte buffer.\n */\nvar readVector = function(b, lenBytes) {\n var len = 0;\n switch(lenBytes) {\n case 1:\n len = b.getByte();\n break;\n case 2:\n len = b.getInt16();\n break;\n case 3:\n len = b.getInt24();\n break;\n case 4:\n len = b.getInt32();\n break;\n }\n\n // read vector bytes into a new buffer\n return forge.util.createBuffer(b.getBytes(len));\n};\n\n/**\n * Writes a TLS variable-length vector to a byte buffer.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n * @param v the byte buffer vector.\n */\nvar writeVector = function(b, lenBytes, v) {\n // encode length at the start of the vector, where the number of bytes for\n // the length is the maximum number of bytes it would take to encode the\n // vector's ceiling\n b.putInt(v.length(), lenBytes << 3);\n b.putBuffer(v);\n};\n\n/**\n * The tls implementation.\n */\nvar tls = {};\n\n/**\n * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and\n * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time\n * of this implementation so TLS 1.0 was implemented instead.\n */\ntls.Versions = {\n TLS_1_0: {major: 3, minor: 1},\n TLS_1_1: {major: 3, minor: 2},\n TLS_1_2: {major: 3, minor: 3}\n};\ntls.SupportedVersions = [\n tls.Versions.TLS_1_1,\n tls.Versions.TLS_1_0\n];\ntls.Version = tls.SupportedVersions[0];\n\n/**\n * Maximum fragment size. True maximum is 16384, but we fragment before that\n * to allow for unusual small increases during compression.\n */\ntls.MaxFragment = 16384 - 1024;\n\n/**\n * Whether this entity is considered the \"client\" or \"server\".\n * enum { server, client } ConnectionEnd;\n */\ntls.ConnectionEnd = {\n server: 0,\n client: 1\n};\n\n/**\n * Pseudo-random function algorithm used to generate keys from the master\n * secret.\n * enum { tls_prf_sha256 } PRFAlgorithm;\n */\ntls.PRFAlgorithm = {\n tls_prf_sha256: 0\n};\n\n/**\n * Bulk encryption algorithms.\n * enum { null, rc4, des3, aes } BulkCipherAlgorithm;\n */\ntls.BulkCipherAlgorithm = {\n none: null,\n rc4: 0,\n des3: 1,\n aes: 2\n};\n\n/**\n * Cipher types.\n * enum { stream, block, aead } CipherType;\n */\ntls.CipherType = {\n stream: 0,\n block: 1,\n aead: 2\n};\n\n/**\n * MAC (Message Authentication Code) algorithms.\n * enum { null, hmac_md5, hmac_sha1, hmac_sha256,\n * hmac_sha384, hmac_sha512} MACAlgorithm;\n */\ntls.MACAlgorithm = {\n none: null,\n hmac_md5: 0,\n hmac_sha1: 1,\n hmac_sha256: 2,\n hmac_sha384: 3,\n hmac_sha512: 4\n};\n\n/**\n * Compression algorithms.\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n */\ntls.CompressionMethod = {\n none: 0,\n deflate: 1\n};\n\n/**\n * TLS record content types.\n * enum {\n * change_cipher_spec(20), alert(21), handshake(22),\n * application_data(23), (255)\n * } ContentType;\n */\ntls.ContentType = {\n change_cipher_spec: 20,\n alert: 21,\n handshake: 22,\n application_data: 23,\n heartbeat: 24\n};\n\n/**\n * TLS handshake types.\n * enum {\n * hello_request(0), client_hello(1), server_hello(2),\n * certificate(11), server_key_exchange (12),\n * certificate_request(13), server_hello_done(14),\n * certificate_verify(15), client_key_exchange(16),\n * finished(20), (255)\n * } HandshakeType;\n */\ntls.HandshakeType = {\n hello_request: 0,\n client_hello: 1,\n server_hello: 2,\n certificate: 11,\n server_key_exchange: 12,\n certificate_request: 13,\n server_hello_done: 14,\n certificate_verify: 15,\n client_key_exchange: 16,\n finished: 20\n};\n\n/**\n * TLS Alert Protocol.\n *\n * enum { warning(1), fatal(2), (255) } AlertLevel;\n *\n * enum {\n * close_notify(0),\n * unexpected_message(10),\n * bad_record_mac(20),\n * decryption_failed(21),\n * record_overflow(22),\n * decompression_failure(30),\n * handshake_failure(40),\n * bad_certificate(42),\n * unsupported_certificate(43),\n * certificate_revoked(44),\n * certificate_expired(45),\n * certificate_unknown(46),\n * illegal_parameter(47),\n * unknown_ca(48),\n * access_denied(49),\n * decode_error(50),\n * decrypt_error(51),\n * export_restriction(60),\n * protocol_version(70),\n * insufficient_security(71),\n * internal_error(80),\n * user_canceled(90),\n * no_renegotiation(100),\n * (255)\n * } AlertDescription;\n *\n * struct {\n * AlertLevel level;\n * AlertDescription description;\n * } Alert;\n */\ntls.Alert = {};\ntls.Alert.Level = {\n warning: 1,\n fatal: 2\n};\ntls.Alert.Description = {\n close_notify: 0,\n unexpected_message: 10,\n bad_record_mac: 20,\n decryption_failed: 21,\n record_overflow: 22,\n decompression_failure: 30,\n handshake_failure: 40,\n bad_certificate: 42,\n unsupported_certificate: 43,\n certificate_revoked: 44,\n certificate_expired: 45,\n certificate_unknown: 46,\n illegal_parameter: 47,\n unknown_ca: 48,\n access_denied: 49,\n decode_error: 50,\n decrypt_error: 51,\n export_restriction: 60,\n protocol_version: 70,\n insufficient_security: 71,\n internal_error: 80,\n user_canceled: 90,\n no_renegotiation: 100\n};\n\n/**\n * TLS Heartbeat Message types.\n * enum {\n * heartbeat_request(1),\n * heartbeat_response(2),\n * (255)\n * } HeartbeatMessageType;\n */\ntls.HeartbeatMessageType = {\n heartbeat_request: 1,\n heartbeat_response: 2\n};\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites = {};\n\n/**\n * Gets a supported cipher suite from its 2 byte ID.\n *\n * @param twoBytes two bytes in a string.\n *\n * @return the matching supported cipher suite or null.\n */\ntls.getCipherSuite = function(twoBytes) {\n var rval = null;\n for(var key in tls.CipherSuites) {\n var cs = tls.CipherSuites[key];\n if(cs.id[0] === twoBytes.charCodeAt(0) &&\n cs.id[1] === twoBytes.charCodeAt(1)) {\n rval = cs;\n break;\n }\n }\n return rval;\n};\n\n/**\n * Called when an unexpected record is encountered.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleUnexpected = function(c, record) {\n // if connection is client and closed, ignore unexpected messages\n var ignore = (!c.open && c.entity === tls.ConnectionEnd.client);\n if(!ignore) {\n c.error(c, {\n message: 'Unexpected message. Received TLS record out of order.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unexpected_message\n }\n });\n }\n};\n\n/**\n * Called when a client receives a HelloRequest record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleHelloRequest = function(c, record, length) {\n // ignore renegotiation requests from the server during a handshake, but\n // if handshaking, send a warning alert that renegotation is denied\n if(!c.handshaking && c.handshakes > 0) {\n // send alert warning\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.no_renegotiation\n }));\n tls.flush(c);\n }\n\n // continue\n c.process();\n};\n\n/**\n * Parses a hello message from a ClientHello or ServerHello record.\n *\n * @param record the record to parse.\n *\n * @return the parsed message.\n */\ntls.parseHelloMessage = function(c, record, length) {\n var msg = null;\n\n var client = (c.entity === tls.ConnectionEnd.client);\n\n // minimum of 38 bytes in message\n if(length < 38) {\n c.error(c, {\n message: client ?\n 'Invalid ServerHello message. Message too short.' :\n 'Invalid ClientHello message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else {\n // use 'remaining' to calculate # of remaining bytes in the message\n var b = record.fragment;\n var remaining = b.length();\n msg = {\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n random: forge.util.createBuffer(b.getBytes(32)),\n session_id: readVector(b, 1),\n extensions: []\n };\n if(client) {\n msg.cipher_suite = b.getBytes(2);\n msg.compression_method = b.getByte();\n } else {\n msg.cipher_suites = readVector(b, 2);\n msg.compression_methods = readVector(b, 1);\n }\n\n // read extensions if there are any bytes left in the message\n remaining = length - (remaining - b.length());\n if(remaining > 0) {\n // parse extensions\n var exts = readVector(b, 2);\n while(exts.length() > 0) {\n msg.extensions.push({\n type: [exts.getByte(), exts.getByte()],\n data: readVector(exts, 2)\n });\n }\n\n // TODO: make extension support modular\n if(!client) {\n for(var i = 0; i < msg.extensions.length; ++i) {\n var ext = msg.extensions[i];\n\n // support SNI extension\n if(ext.type[0] === 0x00 && ext.type[1] === 0x00) {\n // get server name list\n var snl = readVector(ext.data, 2);\n while(snl.length() > 0) {\n // read server name type\n var snType = snl.getByte();\n\n // only HostName type (0x00) is known, break out if\n // another type is detected\n if(snType !== 0x00) {\n break;\n }\n\n // add host name to server name list\n c.session.extensions.server_name.serverNameList.push(\n readVector(snl, 2).getBytes());\n }\n }\n }\n }\n }\n\n // version already set, do not allow version change\n if(c.session.version) {\n if(msg.version.major !== c.session.version.major ||\n msg.version.minor !== c.session.version.minor) {\n return c.error(c, {\n message: 'TLS version change is disallowed during renegotiation.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n // get the chosen (ServerHello) cipher suite\n if(client) {\n // FIXME: should be checking configured acceptable cipher suites\n c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);\n } else {\n // get a supported preferred (ClientHello) cipher suite\n // choose the first supported cipher suite\n var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());\n while(tmp.length() > 0) {\n // FIXME: should be checking configured acceptable suites\n // cipher suites take up 2 bytes\n c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));\n if(c.session.cipherSuite !== null) {\n break;\n }\n }\n }\n\n // cipher suite not supported\n if(c.session.cipherSuite === null) {\n return c.error(c, {\n message: 'No cipher suites in common.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n },\n cipherSuite: forge.util.bytesToHex(msg.cipher_suite)\n });\n }\n\n // TODO: handle compression methods\n if(client) {\n c.session.compressionMethod = msg.compression_method;\n } else {\n // no compression\n c.session.compressionMethod = tls.CompressionMethod.none;\n }\n }\n\n return msg;\n};\n\n/**\n * Creates security parameters for the given connection based on the given\n * hello message.\n *\n * @param c the TLS connection.\n * @param msg the hello message.\n */\ntls.createSecurityParameters = function(c, msg) {\n /* Note: security params are from TLS 1.2, some values like prf_algorithm\n are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is\n used. */\n\n // TODO: handle other options from server when more supported\n\n // get client and server randoms\n var client = (c.entity === tls.ConnectionEnd.client);\n var msgRandom = msg.random.bytes();\n var cRandom = client ? c.session.sp.client_random : msgRandom;\n var sRandom = client ? msgRandom : tls.createRandom().getBytes();\n\n // create new security parameters\n c.session.sp = {\n entity: c.entity,\n prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,\n bulk_cipher_algorithm: null,\n cipher_type: null,\n enc_key_length: null,\n block_length: null,\n fixed_iv_length: null,\n record_iv_length: null,\n mac_algorithm: null,\n mac_length: null,\n mac_key_length: null,\n compression_algorithm: c.session.compressionMethod,\n pre_master_secret: null,\n master_secret: null,\n client_random: cRandom,\n server_random: sRandom\n };\n};\n\n/**\n * Called when a client receives a ServerHello record.\n *\n * When a ServerHello message will be sent:\n * The server will send this message in response to a client hello message\n * when it was able to find an acceptable set of algorithms. If it cannot\n * find such a match, it will respond with a handshake failure alert.\n *\n * uint24 length;\n * struct {\n * ProtocolVersion server_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suite;\n * CompressionMethod compression_method;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ServerHello;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // ensure server version is compatible\n if(msg.version.minor <= c.version.minor) {\n c.version.minor = msg.version.minor;\n } else {\n return c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n\n // indicate session version has been set\n c.session.version = c.version;\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // if the session ID is not blank and matches the cached one, resume\n // the session\n if(sessionId.length > 0 && sessionId === c.session.id) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = SCC;\n c.session.resuming = true;\n\n // get new server random\n c.session.sp.server_random = msg.random.bytes();\n } else {\n // not resuming, expect a server Certificate message next\n c.expect = SCE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // set new session ID\n c.session.id = sessionId;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a ClientHello record.\n *\n * When a ClientHello message will be sent:\n * When a client first connects to a server it is required to send the\n * client hello as its first message. The client can also send a client\n * hello in response to a hello request or on its own initiative in order\n * to renegotiate the security parameters in an existing connection.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // see if the given session ID is in the cache\n var session = null;\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n if(session === null) {\n // session ID not found\n sessionId = '';\n } else if(session.version.major !== msg.version.major ||\n session.version.minor > msg.version.minor) {\n // if session version is incompatible with client version, do not resume\n session = null;\n sessionId = '';\n }\n }\n\n // no session found to resume, generate a new session ID\n if(sessionId.length === 0) {\n sessionId = forge.random.getBytes(32);\n }\n\n // update session\n c.session.id = sessionId;\n c.session.clientHelloVersion = msg.version;\n c.session.sp = {};\n if(session) {\n // use version and security parameters from resumed session\n c.version = c.session.version = session.version;\n c.session.sp = session.sp;\n } else {\n // use highest compatible minor version\n var version;\n for(var i = 1; i < tls.SupportedVersions.length; ++i) {\n version = tls.SupportedVersions[i];\n if(version.minor <= msg.version.minor) {\n break;\n }\n }\n c.version = {major: version.major, minor: version.minor};\n c.session.version = c.version;\n }\n\n // if a session is set, resume it\n if(session !== null) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = CCC;\n c.session.resuming = true;\n\n // get new client random\n c.session.sp.client_random = msg.random.bytes();\n } else {\n // not resuming, expect a Certificate or ClientKeyExchange\n c.expect = (c.verifyClient !== false) ? CCE : CKE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // connection now open\n c.open = true;\n\n // queue server hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHello(c)\n }));\n\n if(c.session.resuming) {\n // queue change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // queue finished\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n } else {\n // queue server certificate\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n }));\n\n if(!c.fail) {\n // queue server key exchange\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerKeyExchange(c)\n }));\n\n // request client certificate if set\n if(c.verifyClient !== false) {\n // queue certificate request\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateRequest(c)\n }));\n }\n\n // queue server hello done\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHelloDone(c)\n }));\n }\n }\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a Certificate record.\n *\n * When this message will be sent:\n * The server must send a certificate whenever the agreed-upon key exchange\n * method is not an anonymous one. This message will always immediately\n * follow the server hello message.\n *\n * Meaning of this message:\n * The certificate type must be appropriate for the selected cipher suite's\n * key exchange algorithm, and is generally an X.509v3 certificate. It must\n * contain a key which matches the key exchange method, as follows. Unless\n * otherwise specified, the signing algorithm for the certificate must be\n * the same as the algorithm for the certificate key. Unless otherwise\n * specified, the public key may be of any length.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n * struct {\n * ASN.1Cert certificate_list<1..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificate = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid Certificate message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n certificate_list: readVector(b, 3)\n };\n\n /* The sender's certificate will be first in the list (chain), each\n subsequent one that follows will certify the previous one, but root\n certificates (self-signed) that specify the certificate authority may\n be omitted under the assumption that clients must already possess it. */\n var cert, asn1;\n var certs = [];\n try {\n while(msg.certificate_list.length() > 0) {\n // each entry in msg.certificate_list is a vector with 3 len bytes\n cert = readVector(msg.certificate_list, 3);\n asn1 = forge.asn1.fromDer(cert);\n cert = forge.pki.certificateFromAsn1(asn1, true);\n certs.push(cert);\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not parse certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n\n // ensure at least 1 certificate was provided if in client-mode\n // or if verifyClient was set to true to require a certificate\n // (as opposed to 'optional')\n var client = (c.entity === tls.ConnectionEnd.client);\n if((client || c.verifyClient === true) && certs.length === 0) {\n // error, no certificate\n c.error(c, {\n message: client ?\n 'No server certificate provided.' :\n 'No client certificate provided.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else if(certs.length === 0) {\n // no certs to verify\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n } else {\n // save certificate in session\n if(client) {\n c.session.serverCertificate = certs[0];\n } else {\n c.session.clientCertificate = certs[0];\n }\n\n if(tls.verifyCertificateChain(c, certs)) {\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerKeyExchange record.\n *\n * When this message will be sent:\n * This message will be sent immediately after the server certificate\n * message (or the server hello message, if this is an anonymous\n * negotiation).\n *\n * The server key exchange message is sent by the server only when the\n * server certificate message (if sent) does not contain enough data to\n * allow the client to exchange a premaster secret.\n *\n * Meaning of this message:\n * This message conveys cryptographic information to allow the client to\n * communicate the premaster secret: either an RSA public key to encrypt\n * the premaster secret with, or a Diffie-Hellman public key with which the\n * client can complete a key exchange (with the result being the premaster\n * secret.)\n *\n * enum {\n * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa\n * } KeyExchangeAlgorithm;\n *\n * struct {\n * opaque dh_p<1..2^16-1>;\n * opaque dh_g<1..2^16-1>;\n * opaque dh_Ys<1..2^16-1>;\n * } ServerDHParams;\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case dh_anon:\n * ServerDHParams params;\n * case dhe_dss:\n * case dhe_rsa:\n * ServerDHParams params;\n * digitally-signed struct {\n * opaque client_random[32];\n * opaque server_random[32];\n * ServerDHParams params;\n * } signed_params;\n * case rsa:\n * case dh_dss:\n * case dh_rsa:\n * struct {};\n * };\n * } ServerKeyExchange;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length > 0 is invalid\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n // expect an optional CertificateRequest message next\n c.expect = SCR;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ClientKeyExchange record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length < 48 is invalid\n if(length < 48) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n enc_pre_master_secret: readVector(b, 2).getBytes()\n };\n\n // do rsa decryption\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.serverCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n\n if(privateKey === null) {\n return c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n\n try {\n // decrypt 48-byte pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);\n\n // ensure client hello version matches first 2 bytes\n var version = c.session.clientHelloVersion;\n if(version.major !== sp.pre_master_secret.charCodeAt(0) ||\n version.minor !== sp.pre_master_secret.charCodeAt(1)) {\n // error, do not send alert (see BLEI attack below)\n throw new Error('TLS version rollback attack detected.');\n }\n } catch(ex) {\n /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a\n TLS server which is using PKCS#1 encoded RSA, so instead of\n failing here, we generate 48 random bytes and use that as\n the pre-master secret. */\n sp.pre_master_secret = forge.random.getBytes(48);\n }\n\n // expect a CertificateVerify message if a Certificate was received that\n // does not have fixed Diffie-Hellman params, otherwise expect\n // ChangeCipherSpec\n c.expect = CCC;\n if(c.session.clientCertificate !== null) {\n // only RSA support, so expect CertificateVerify\n // TODO: support Diffie-Hellman\n c.expect = CCV;\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a CertificateRequest record.\n *\n * When this message will be sent:\n * A non-anonymous server can optionally request a certificate from the\n * client, if appropriate for the selected cipher suite. This message, if\n * sent, will immediately follow the Server Key Exchange message (if it is\n * sent; otherwise, the Server Certificate message).\n *\n * enum {\n * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),\n * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),\n * fortezza_dms_RESERVED(20), (255)\n * } ClientCertificateType;\n *\n * opaque DistinguishedName<1..2^16-1>;\n *\n * struct {\n * ClientCertificateType certificate_types<1..2^8-1>;\n * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>;\n * DistinguishedName certificate_authorities<0..2^16-1>;\n * } CertificateRequest;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateRequest = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid CertificateRequest. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // TODO: TLS 1.2+ has different format including\n // SignatureAndHashAlgorithm after cert types\n var b = record.fragment;\n var msg = {\n certificate_types: readVector(b, 1),\n certificate_authorities: readVector(b, 2)\n };\n\n // save certificate request in session\n c.session.certificateRequest = msg;\n\n // expect a ServerHelloDone message next\n c.expect = SHD;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a CertificateVerify record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateVerify = function(c, record, length) {\n if(length < 2) {\n return c.error(c, {\n message: 'Invalid CertificateVerify. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for CertificateVerify messages because\n // they must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n var msg = {\n signature: readVector(b, 2).getBytes()\n };\n\n // TODO: add support for DSA\n\n // generate data to verify\n var verify = forge.util.createBuffer();\n verify.putBuffer(c.session.md5.digest());\n verify.putBuffer(c.session.sha1.digest());\n verify = verify.getBytes();\n\n try {\n var cert = c.session.clientCertificate;\n /*b = forge.pki.rsa.decrypt(\n msg.signature, cert.publicKey, true, verify.length);\n if(b !== verify) {*/\n if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) {\n throw new Error('CertificateVerify signature does not match.');\n }\n\n // digest message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n } catch(ex) {\n return c.error(c, {\n message: 'Bad signature in CertificateVerify.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n }\n });\n }\n\n // expect ChangeCipherSpec\n c.expect = CCC;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerHelloDone record.\n *\n * When this message will be sent:\n * The server hello done message is sent by the server to indicate the end\n * of the server hello and associated messages. After sending this message\n * the server will wait for a client response.\n *\n * Meaning of this message:\n * This message means that the server is done sending messages to support\n * the key exchange, and the client can proceed with its phase of the key\n * exchange.\n *\n * Upon receipt of the server hello done message the client should verify\n * that the server provided a valid certificate if required and check that\n * the server hello parameters are acceptable.\n *\n * struct {} ServerHelloDone;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHelloDone = function(c, record, length) {\n // len must be 0 bytes\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid ServerHelloDone message. Invalid length.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.record_overflow\n }\n });\n }\n\n if(c.serverCertificate === null) {\n // no server certificate was provided\n var error = {\n message: 'No server certificate provided. Not enough security.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.insufficient_security\n }\n };\n\n // call application callback\n var depth = 0;\n var ret = c.verify(c, error.alert.description, depth, []);\n if(ret !== true) {\n // check for custom alert info\n if(ret || ret === 0) {\n // set custom message and alert description\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n } else if(typeof ret === 'number') {\n // set custom alert description\n error.alert.description = ret;\n }\n }\n\n // send error\n return c.error(c, error);\n }\n }\n\n // create client certificate message if requested\n if(c.session.certificateRequest !== null) {\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n });\n tls.queue(c, record);\n }\n\n // create client key exchange message\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientKeyExchange(c)\n });\n tls.queue(c, record);\n\n // expect no messages until the following callback has been called\n c.expect = SER;\n\n // create callback to handle client signature (for client-certs)\n var callback = function(c, signature) {\n if(c.session.certificateRequest !== null &&\n c.session.clientCertificate !== null) {\n // create certificate verify message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateVerify(c, signature)\n }));\n }\n\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n\n // expect a server ChangeCipherSpec message next\n c.expect = SCC;\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n };\n\n // if there is no certificate request or no client certificate, do\n // callback immediately\n if(c.session.certificateRequest === null ||\n c.session.clientCertificate === null) {\n return callback(c, null);\n }\n\n // otherwise get the client signature\n tls.getClientSignature(c, callback);\n};\n\n/**\n * Called when a ChangeCipherSpec record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleChangeCipherSpec = function(c, record) {\n if(record.fragment.getByte() !== 0x01) {\n return c.error(c, {\n message: 'Invalid ChangeCipherSpec message received.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // create pending state if:\n // 1. Resuming session in client mode OR\n // 2. NOT resuming session in server mode\n var client = (c.entity === tls.ConnectionEnd.client);\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n c.state.pending = tls.createConnectionState(c);\n }\n\n // change current read state to pending read state\n c.state.current.read = c.state.pending.read;\n\n // clear pending state if:\n // 1. NOT resuming session in client mode OR\n // 2. resuming a session in server mode\n if((!c.session.resuming && client) || (c.session.resuming && !client)) {\n c.state.pending = null;\n }\n\n // expect a Finished record next\n c.expect = client ? SFI : CFI;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Finished record is received.\n *\n * When this message will be sent:\n * A finished message is always sent immediately after a change\n * cipher spec message to verify that the key exchange and\n * authentication processes were successful. It is essential that a\n * change cipher spec message be received between the other\n * handshake messages and the Finished message.\n *\n * Meaning of this message:\n * The finished message is the first protected with the just-\n * negotiated algorithms, keys, and secrets. Recipients of finished\n * messages must verify that the contents are correct. Once a side\n * has sent its Finished message and received and validated the\n * Finished message from its peer, it may begin to send and receive\n * application data over the connection.\n *\n * struct {\n * opaque verify_data[verify_data_length];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, Hash(handshake_messages))\n * [0..verify_data_length-1];\n *\n * finished_label\n * For Finished messages sent by the client, the string\n * \"client finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * verify_data_length depends on the cipher suite. If it is not specified\n * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used\n * 12 bytes.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleFinished = function(c, record, length) {\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for Finished messages because they\n // must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n // message contains only verify_data\n var vd = record.fragment.getBytes();\n\n // ensure verify data is correct\n b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // set label based on entity type\n var client = (c.entity === tls.ConnectionEnd.client);\n var label = client ? 'server finished' : 'client finished';\n\n // TODO: determine prf function and verify length for TLS 1.2\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n if(b.getBytes() !== vd) {\n return c.error(c, {\n message: 'Invalid verify_data in Finished message.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decrypt_error\n }\n });\n }\n\n // digest finished message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n\n // resuming session as client or NOT resuming session as server\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // change current write state to pending write state, clear pending\n c.state.current.write = c.state.pending.write;\n c.state.pending = null;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n }\n\n // expect application data next\n c.expect = client ? SAD : CAD;\n\n // handshake complete\n c.handshaking = false;\n ++c.handshakes;\n\n // save access to peer certificate\n c.peerCertificate = client ?\n c.session.serverCertificate : c.session.clientCertificate;\n\n // send records\n tls.flush(c);\n\n // now connected\n c.isConnected = true;\n c.connected(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when an Alert record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleAlert = function(c, record) {\n // read alert\n var b = record.fragment;\n var alert = {\n level: b.getByte(),\n description: b.getByte()\n };\n\n // TODO: consider using a table?\n // get appropriate message\n var msg;\n switch(alert.description) {\n case tls.Alert.Description.close_notify:\n msg = 'Connection closed.';\n break;\n case tls.Alert.Description.unexpected_message:\n msg = 'Unexpected message.';\n break;\n case tls.Alert.Description.bad_record_mac:\n msg = 'Bad record MAC.';\n break;\n case tls.Alert.Description.decryption_failed:\n msg = 'Decryption failed.';\n break;\n case tls.Alert.Description.record_overflow:\n msg = 'Record overflow.';\n break;\n case tls.Alert.Description.decompression_failure:\n msg = 'Decompression failed.';\n break;\n case tls.Alert.Description.handshake_failure:\n msg = 'Handshake failure.';\n break;\n case tls.Alert.Description.bad_certificate:\n msg = 'Bad certificate.';\n break;\n case tls.Alert.Description.unsupported_certificate:\n msg = 'Unsupported certificate.';\n break;\n case tls.Alert.Description.certificate_revoked:\n msg = 'Certificate revoked.';\n break;\n case tls.Alert.Description.certificate_expired:\n msg = 'Certificate expired.';\n break;\n case tls.Alert.Description.certificate_unknown:\n msg = 'Certificate unknown.';\n break;\n case tls.Alert.Description.illegal_parameter:\n msg = 'Illegal parameter.';\n break;\n case tls.Alert.Description.unknown_ca:\n msg = 'Unknown certificate authority.';\n break;\n case tls.Alert.Description.access_denied:\n msg = 'Access denied.';\n break;\n case tls.Alert.Description.decode_error:\n msg = 'Decode error.';\n break;\n case tls.Alert.Description.decrypt_error:\n msg = 'Decrypt error.';\n break;\n case tls.Alert.Description.export_restriction:\n msg = 'Export restriction.';\n break;\n case tls.Alert.Description.protocol_version:\n msg = 'Unsupported protocol version.';\n break;\n case tls.Alert.Description.insufficient_security:\n msg = 'Insufficient security.';\n break;\n case tls.Alert.Description.internal_error:\n msg = 'Internal error.';\n break;\n case tls.Alert.Description.user_canceled:\n msg = 'User canceled.';\n break;\n case tls.Alert.Description.no_renegotiation:\n msg = 'Renegotiation not supported.';\n break;\n default:\n msg = 'Unknown error.';\n break;\n }\n\n // close connection on close_notify, not an error\n if(alert.description === tls.Alert.Description.close_notify) {\n return c.close();\n }\n\n // call error handler\n c.error(c, {\n message: msg,\n send: false,\n // origin is the opposite end\n origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client',\n alert: alert\n });\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Handshake record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHandshake = function(c, record) {\n // get the handshake type and message length\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt24();\n\n // see if the record fragment doesn't yet contain the full message\n if(length > b.length()) {\n // cache the record, clear its fragment, and reset the buffer read\n // pointer before the type and length were read\n c.fragmented = record;\n record.fragment = forge.util.createBuffer();\n b.read -= 4;\n\n // continue\n return c.process();\n }\n\n // full message now available, clear cache, reset read pointer to\n // before type and length\n c.fragmented = null;\n b.read -= 4;\n\n // save the handshake bytes for digestion after handler is found\n // (include type and length of handshake msg)\n var bytes = b.bytes(length + 4);\n\n // restore read pointer\n b.read += 4;\n\n // handle expected message\n if(type in hsTable[c.entity][c.expect]) {\n // initialize server session\n if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) {\n c.handshaking = true;\n c.session = {\n version: null,\n extensions: {\n server_name: {\n serverNameList: []\n }\n },\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n clientCertificate: null,\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n }\n\n /* Update handshake messages digest. Finished and CertificateVerify\n messages are not digested here. They can't be digested as part of\n the verify_data that they contain. These messages are manually\n digested in their handlers. HelloRequest messages are simply never\n included in the handshake message digest according to spec. */\n if(type !== tls.HandshakeType.hello_request &&\n type !== tls.HandshakeType.certificate_verify &&\n type !== tls.HandshakeType.finished) {\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n }\n\n // handle specific handshake type record\n hsTable[c.entity][c.expect][type](c, record, length);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n};\n\n/**\n * Called when an ApplicationData record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleApplicationData = function(c, record) {\n // buffer data, notify that its ready\n c.data.putBuffer(record.fragment);\n c.dataReady(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Heartbeat record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHeartbeat = function(c, record) {\n // get the heartbeat type and payload\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt16();\n var payload = b.getBytes(length);\n\n if(type === tls.HeartbeatMessageType.heartbeat_request) {\n // discard request during handshake or if length is too large\n if(c.handshaking || length > payload.length) {\n // continue\n return c.process();\n }\n // retransmit payload\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_response, payload)\n }));\n tls.flush(c);\n } else if(type === tls.HeartbeatMessageType.heartbeat_response) {\n // check payload against expected payload, discard heartbeat if no match\n if(payload !== c.expectedHeartbeatPayload) {\n // continue\n return c.process();\n }\n\n // notify that a valid heartbeat was received\n if(c.heartbeatReceived) {\n c.heartbeatReceived(c, forge.util.createBuffer(payload));\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * The transistional state tables for receiving TLS records. It maps the\n * current TLS engine state and a received record to a function to handle the\n * record and update the state.\n *\n * For instance, if the current state is SHE, then the TLS engine is expecting\n * a ServerHello record. Once a record is received, the handler function is\n * looked up using the state SHE and the record's content type.\n *\n * The resulting function will either be an error handler or a record handler.\n * The function will take whatever action is appropriate and update the state\n * for the next record.\n *\n * The states are all based on possible server record types. Note that the\n * client will never specifically expect to receive a HelloRequest or an alert\n * from the server so there is no state that reflects this. These messages may\n * occur at any time.\n *\n * There are two tables for mapping states because there is a second tier of\n * types for handshake messages. Once a record with a content type of handshake\n * is received, the handshake record handler will look up the handshake type in\n * the secondary map to get its appropriate handler.\n *\n * Valid message orders are as follows:\n *\n * =======================FULL HANDSHAKE======================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * Certificate*\n * ServerKeyExchange*\n * CertificateRequest*\n * <-------- ServerHelloDone\n * Certificate*\n * ClientKeyExchange\n * CertificateVerify*\n * [ChangeCipherSpec]\n * Finished -------->\n * [ChangeCipherSpec]\n * <-------- Finished\n * Application Data <-------> Application Data\n *\n * =====================SESSION RESUMPTION=====================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * [ChangeCipherSpec]\n * <-------- Finished\n * [ChangeCipherSpec]\n * Finished -------->\n * Application Data <-------> Application Data\n */\n// client expect states (indicate which records are expected to be received)\nvar SHE = 0; // rcv server hello\nvar SCE = 1; // rcv server certificate\nvar SKE = 2; // rcv server key exchange\nvar SCR = 3; // rcv certificate request\nvar SHD = 4; // rcv server hello done\nvar SCC = 5; // rcv change cipher spec\nvar SFI = 6; // rcv finished\nvar SAD = 7; // rcv application data\nvar SER = 8; // not expecting any messages at this point\n\n// server expect states\nvar CHE = 0; // rcv client hello\nvar CCE = 1; // rcv client certificate\nvar CKE = 2; // rcv client key exchange\nvar CCV = 3; // rcv certificate verify\nvar CCC = 4; // rcv change cipher spec\nvar CFI = 5; // rcv finished\nvar CAD = 6; // rcv application data\nvar CER = 7; // not expecting any messages at this point\n\n// map client current expect state and content type to function\nvar __ = tls.handleUnexpected;\nvar R0 = tls.handleChangeCipherSpec;\nvar R1 = tls.handleAlert;\nvar R2 = tls.handleHandshake;\nvar R3 = tls.handleApplicationData;\nvar R4 = tls.handleHeartbeat;\nvar ctTable = [];\nctTable[tls.ConnectionEnd.client] = [\n// CC,AL,HS,AD,HB\n/*SHE*/[__,R1,R2,__,R4],\n/*SCE*/[__,R1,R2,__,R4],\n/*SKE*/[__,R1,R2,__,R4],\n/*SCR*/[__,R1,R2,__,R4],\n/*SHD*/[__,R1,R2,__,R4],\n/*SCC*/[R0,R1,__,__,R4],\n/*SFI*/[__,R1,R2,__,R4],\n/*SAD*/[__,R1,R2,R3,R4],\n/*SER*/[__,R1,R2,__,R4]\n];\n\n// map server current expect state and content type to function\nctTable[tls.ConnectionEnd.server] = [\n// CC,AL,HS,AD\n/*CHE*/[__,R1,R2,__,R4],\n/*CCE*/[__,R1,R2,__,R4],\n/*CKE*/[__,R1,R2,__,R4],\n/*CCV*/[__,R1,R2,__,R4],\n/*CCC*/[R0,R1,__,__,R4],\n/*CFI*/[__,R1,R2,__,R4],\n/*CAD*/[__,R1,R2,R3,R4],\n/*CER*/[__,R1,R2,__,R4]\n];\n\n// map client current expect state and handshake type to function\nvar H0 = tls.handleHelloRequest;\nvar H1 = tls.handleServerHello;\nvar H2 = tls.handleCertificate;\nvar H3 = tls.handleServerKeyExchange;\nvar H4 = tls.handleCertificateRequest;\nvar H5 = tls.handleServerHelloDone;\nvar H6 = tls.handleFinished;\nvar hsTable = [];\nhsTable[tls.ConnectionEnd.client] = [\n// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI\n/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],\n/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],\n/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],\n/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],\n/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n// map server current expect state and handshake type to function\n// Note: CAD[CH] does not map to FB because renegotation is prohibited\nvar H7 = tls.handleClientHello;\nvar H8 = tls.handleClientKeyExchange;\nvar H9 = tls.handleCertificateVerify;\nhsTable[tls.ConnectionEnd.server] = [\n// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI\n/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],\n/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],\n/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],\n/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n/**\n * Generates the master_secret and keys using the given security parameters.\n *\n * The security parameters for a TLS connection state are defined as such:\n *\n * struct {\n * ConnectionEnd entity;\n * PRFAlgorithm prf_algorithm;\n * BulkCipherAlgorithm bulk_cipher_algorithm;\n * CipherType cipher_type;\n * uint8 enc_key_length;\n * uint8 block_length;\n * uint8 fixed_iv_length;\n * uint8 record_iv_length;\n * MACAlgorithm mac_algorithm;\n * uint8 mac_length;\n * uint8 mac_key_length;\n * CompressionMethod compression_algorithm;\n * opaque master_secret[48];\n * opaque client_random[32];\n * opaque server_random[32];\n * } SecurityParameters;\n *\n * Note that this definition is from TLS 1.2. In TLS 1.0 some of these\n * parameters are ignored because, for instance, the PRFAlgorithm is a\n * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0.\n *\n * The Record Protocol requires an algorithm to generate keys required by the\n * current connection state.\n *\n * The master secret is expanded into a sequence of secure bytes, which is then\n * split to a client write MAC key, a server write MAC key, a client write\n * encryption key, and a server write encryption key. In TLS 1.0 a client write\n * IV and server write IV are also generated. Each of these is generated from\n * the byte sequence in that order. Unused values are empty. In TLS 1.2, some\n * AEAD ciphers may additionally require a client write IV and a server write\n * IV (see Section 6.2.3.3).\n *\n * When keys, MAC keys, and IVs are generated, the master secret is used as an\n * entropy source.\n *\n * To generate the key material, compute:\n *\n * master_secret = PRF(pre_master_secret, \"master secret\",\n * ClientHello.random + ServerHello.random)\n *\n * key_block = PRF(SecurityParameters.master_secret,\n * \"key expansion\",\n * SecurityParameters.server_random +\n * SecurityParameters.client_random);\n *\n * until enough output has been generated. Then, the key_block is\n * partitioned as follows:\n *\n * client_write_MAC_key[SecurityParameters.mac_key_length]\n * server_write_MAC_key[SecurityParameters.mac_key_length]\n * client_write_key[SecurityParameters.enc_key_length]\n * server_write_key[SecurityParameters.enc_key_length]\n * client_write_IV[SecurityParameters.fixed_iv_length]\n * server_write_IV[SecurityParameters.fixed_iv_length]\n *\n * In TLS 1.2, the client_write_IV and server_write_IV are only generated for\n * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This\n * implementation uses TLS 1.0 so IVs are generated.\n *\n * Implementation note: The currently defined cipher suite which requires the\n * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32\n * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also\n * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material.\n *\n * @param c the connection.\n * @param sp the security parameters to use.\n *\n * @return the security keys.\n */\ntls.generateKeys = function(c, sp) {\n // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) &\n // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented\n // at present\n\n // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with\n // TLS 1.0 but we don't care right now because AES is better and we have\n // an implementation for it\n\n // TODO: TLS 1.2 implementation\n /*\n // determine the PRF\n var prf;\n switch(sp.prf_algorithm) {\n case tls.PRFAlgorithm.tls_prf_sha256:\n prf = prf_sha256;\n break;\n default:\n // should never happen\n throw new Error('Invalid PRF');\n }\n */\n\n // TLS 1.0/1.1 implementation\n var prf = prf_TLS1;\n\n // concatenate server and client random\n var random = sp.client_random + sp.server_random;\n\n // only create master secret if session is new\n if(!c.session.resuming) {\n // create master secret, clean up pre-master secret\n sp.master_secret = prf(\n sp.pre_master_secret, 'master secret', random, 48).bytes();\n sp.pre_master_secret = null;\n }\n\n // generate the amount of key material needed\n random = sp.server_random + sp.client_random;\n var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;\n\n // include IV for TLS/1.0\n var tls10 = (c.version.major === tls.Versions.TLS_1_0.major &&\n c.version.minor === tls.Versions.TLS_1_0.minor);\n if(tls10) {\n length += 2 * sp.fixed_iv_length;\n }\n var km = prf(sp.master_secret, 'key expansion', random, length);\n\n // split the key material into the MAC and encryption keys\n var rval = {\n client_write_MAC_key: km.getBytes(sp.mac_key_length),\n server_write_MAC_key: km.getBytes(sp.mac_key_length),\n client_write_key: km.getBytes(sp.enc_key_length),\n server_write_key: km.getBytes(sp.enc_key_length)\n };\n\n // include TLS 1.0 IVs\n if(tls10) {\n rval.client_write_IV = km.getBytes(sp.fixed_iv_length);\n rval.server_write_IV = km.getBytes(sp.fixed_iv_length);\n }\n\n return rval;\n};\n\n/**\n * Creates a new initialized TLS connection state. A connection state has\n * a read mode and a write mode.\n *\n * compression state:\n * The current state of the compression algorithm.\n *\n * cipher state:\n * The current state of the encryption algorithm. This will consist of the\n * scheduled key for that connection. For stream ciphers, this will also\n * contain whatever state information is necessary to allow the stream to\n * continue to encrypt or decrypt data.\n *\n * MAC key:\n * The MAC key for the connection.\n *\n * sequence number:\n * Each connection state contains a sequence number, which is maintained\n * separately for read and write states. The sequence number MUST be set to\n * zero whenever a connection state is made the active state. Sequence\n * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do\n * not wrap. If a TLS implementation would need to wrap a sequence number,\n * it must renegotiate instead. A sequence number is incremented after each\n * record: specifically, the first record transmitted under a particular\n * connection state MUST use sequence number 0.\n *\n * @param c the connection.\n *\n * @return the new initialized TLS connection state.\n */\ntls.createConnectionState = function(c) {\n var client = (c.entity === tls.ConnectionEnd.client);\n\n var createMode = function() {\n var mode = {\n // two 32-bit numbers, first is most significant\n sequenceNumber: [0, 0],\n macKey: null,\n macLength: 0,\n macFunction: null,\n cipherState: null,\n cipherFunction: function(record) {return true;},\n compressionState: null,\n compressFunction: function(record) {return true;},\n updateSequenceNumber: function() {\n if(mode.sequenceNumber[1] === 0xFFFFFFFF) {\n mode.sequenceNumber[1] = 0;\n ++mode.sequenceNumber[0];\n } else {\n ++mode.sequenceNumber[1];\n }\n }\n };\n return mode;\n };\n var state = {\n read: createMode(),\n write: createMode()\n };\n\n // update function in read mode will decrypt then decompress a record\n state.read.update = function(c, record) {\n if(!state.read.cipherFunction(record, state.read)) {\n c.error(c, {\n message: 'Could not decrypt record or bad MAC.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n // doesn't matter if decryption failed or MAC was\n // invalid, return the same error so as not to reveal\n // which one occurred\n description: tls.Alert.Description.bad_record_mac\n }\n });\n } else if(!state.read.compressFunction(c, record, state.read)) {\n c.error(c, {\n message: 'Could not decompress record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decompression_failure\n }\n });\n }\n return !c.fail;\n };\n\n // update function in write mode will compress then encrypt a record\n state.write.update = function(c, record) {\n if(!state.write.compressFunction(c, record, state.write)) {\n // error, but do not send alert since it would require\n // compression as well\n c.error(c, {\n message: 'Could not compress record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else if(!state.write.cipherFunction(record, state.write)) {\n // error, but do not send alert since it would require\n // encryption as well\n c.error(c, {\n message: 'Could not encrypt record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n return !c.fail;\n };\n\n // handle security parameters\n if(c.session) {\n var sp = c.session.sp;\n c.session.cipherSuite.initSecurityParameters(sp);\n\n // generate keys\n sp.keys = tls.generateKeys(c, sp);\n state.read.macKey = client ?\n sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;\n state.write.macKey = client ?\n sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;\n\n // cipher suite setup\n c.session.cipherSuite.initConnectionState(state, c, sp);\n\n // compression setup\n switch(sp.compression_algorithm) {\n case tls.CompressionMethod.none:\n break;\n case tls.CompressionMethod.deflate:\n state.read.compressFunction = inflate;\n state.write.compressFunction = deflate;\n break;\n default:\n throw new Error('Unsupported compression algorithm.');\n }\n }\n\n return state;\n};\n\n/**\n * Creates a Random structure.\n *\n * struct {\n * uint32 gmt_unix_time;\n * opaque random_bytes[28];\n * } Random;\n *\n * gmt_unix_time:\n * The current time and date in standard UNIX 32-bit format (seconds since\n * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according\n * to the sender's internal clock. Clocks are not required to be set\n * correctly by the basic TLS protocol; higher-level or application\n * protocols may define additional requirements. Note that, for historical\n * reasons, the data element is named using GMT, the predecessor of the\n * current worldwide time base, UTC.\n * random_bytes:\n * 28 bytes generated by a secure random number generator.\n *\n * @return the Random structure as a byte array.\n */\ntls.createRandom = function() {\n // get UTC milliseconds\n var d = new Date();\n var utc = +d + d.getTimezoneOffset() * 60000;\n var rval = forge.util.createBuffer();\n rval.putInt32(utc);\n rval.putBytes(forge.random.getBytes(28));\n return rval;\n};\n\n/**\n * Creates a TLS record with the given type and data.\n *\n * @param c the connection.\n * @param options:\n * type: the record type.\n * data: the plain text data in a byte buffer.\n *\n * @return the created record.\n */\ntls.createRecord = function(c, options) {\n if(!options.data) {\n return null;\n }\n var record = {\n type: options.type,\n version: {\n major: c.version.major,\n minor: c.version.minor\n },\n length: options.data.length(),\n fragment: options.data\n };\n return record;\n};\n\n/**\n * Creates a TLS alert record.\n *\n * @param c the connection.\n * @param alert:\n * level: the TLS alert level.\n * description: the TLS alert description.\n *\n * @return the created alert record.\n */\ntls.createAlert = function(c, alert) {\n var b = forge.util.createBuffer();\n b.putByte(alert.level);\n b.putByte(alert.description);\n return tls.createRecord(c, {\n type: tls.ContentType.alert,\n data: b\n });\n};\n\n/* The structure of a TLS handshake message.\n *\n * struct {\n * HandshakeType msg_type; // handshake type\n * uint24 length; // bytes in message\n * select(HandshakeType) {\n * case hello_request: HelloRequest;\n * case client_hello: ClientHello;\n * case server_hello: ServerHello;\n * case certificate: Certificate;\n * case server_key_exchange: ServerKeyExchange;\n * case certificate_request: CertificateRequest;\n * case server_hello_done: ServerHelloDone;\n * case certificate_verify: CertificateVerify;\n * case client_key_exchange: ClientKeyExchange;\n * case finished: Finished;\n * } body;\n * } Handshake;\n */\n\n/**\n * Creates a ClientHello message.\n *\n * opaque SessionID<0..32>;\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n * uint8 CipherSuite[2];\n *\n * struct {\n * ProtocolVersion client_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suites<2..2^16-2>;\n * CompressionMethod compression_methods<1..2^8-1>;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ClientHello;\n *\n * The extension format for extended client hellos and server hellos is:\n *\n * struct {\n * ExtensionType extension_type;\n * opaque extension_data<0..2^16-1>;\n * } Extension;\n *\n * Here:\n *\n * - \"extension_type\" identifies the particular extension type.\n * - \"extension_data\" contains information specific to the particular\n * extension type.\n *\n * The extension types defined in this document are:\n *\n * enum {\n * server_name(0), max_fragment_length(1),\n * client_certificate_url(2), trusted_ca_keys(3),\n * truncated_hmac(4), status_request(5), (65535)\n * } ExtensionType;\n *\n * @param c the connection.\n *\n * @return the ClientHello byte buffer.\n */\ntls.createClientHello = function(c) {\n // save hello version\n c.session.clientHelloVersion = {\n major: c.version.major,\n minor: c.version.minor\n };\n\n // create supported cipher suites\n var cipherSuites = forge.util.createBuffer();\n for(var i = 0; i < c.cipherSuites.length; ++i) {\n var cs = c.cipherSuites[i];\n cipherSuites.putByte(cs.id[0]);\n cipherSuites.putByte(cs.id[1]);\n }\n var cSuites = cipherSuites.length();\n\n // create supported compression methods, null always supported, but\n // also support deflate if connection has inflate and deflate methods\n var compressionMethods = forge.util.createBuffer();\n compressionMethods.putByte(tls.CompressionMethod.none);\n // FIXME: deflate support disabled until issues with raw deflate data\n // without zlib headers are resolved\n /*\n if(c.inflate !== null && c.deflate !== null) {\n compressionMethods.putByte(tls.CompressionMethod.deflate);\n }\n */\n var cMethods = compressionMethods.length();\n\n // create TLS SNI (server name indication) extension if virtual host\n // has been specified, see RFC 3546\n var extensions = forge.util.createBuffer();\n if(c.virtualHost) {\n // create extension struct\n var ext = forge.util.createBuffer();\n ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes)\n ext.putByte(0x00);\n\n /* In order to provide the server name, clients MAY include an\n * extension of type \"server_name\" in the (extended) client hello.\n * The \"extension_data\" field of this extension SHALL contain\n * \"ServerNameList\" where:\n *\n * struct {\n * NameType name_type;\n * select(name_type) {\n * case host_name: HostName;\n * } name;\n * } ServerName;\n *\n * enum {\n * host_name(0), (255)\n * } NameType;\n *\n * opaque HostName<1..2^16-1>;\n *\n * struct {\n * ServerName server_name_list<1..2^16-1>\n * } ServerNameList;\n */\n var serverName = forge.util.createBuffer();\n serverName.putByte(0x00); // type host_name\n writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost));\n\n // ServerNameList is in extension_data\n var snList = forge.util.createBuffer();\n writeVector(snList, 2, serverName);\n writeVector(ext, 2, snList);\n extensions.putBuffer(ext);\n }\n var extLength = extensions.length();\n if(extLength > 0) {\n // add extension vector length\n extLength += 2;\n }\n\n // determine length of the handshake message\n // cipher suites and compression methods size will need to be\n // updated if more get added to the list\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + cSuites + // cipher suites vector\n 1 + cMethods + // compression methods vector\n extLength; // extensions vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.client_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n writeVector(rval, 2, cipherSuites);\n writeVector(rval, 1, compressionMethods);\n if(extLength > 0) {\n writeVector(rval, 2, extensions);\n }\n return rval;\n};\n\n/**\n * Creates a ServerHello message.\n *\n * @param c the connection.\n *\n * @return the ServerHello byte buffer.\n */\ntls.createServerHello = function(c) {\n // determine length of the handshake message\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + // chosen cipher suite\n 1; // chosen compression method\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.server_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n rval.putByte(c.session.cipherSuite.id[0]);\n rval.putByte(c.session.cipherSuite.id[1]);\n rval.putByte(c.session.compressionMethod);\n return rval;\n};\n\n/**\n * Creates a Certificate message.\n *\n * When this message will be sent:\n * This is the first message the client can send after receiving a server\n * hello done message and the first message the server can send after\n * sending a ServerHello. This client message is only sent if the server\n * requests a certificate. If no suitable certificate is available, the\n * client should send a certificate message containing no certificates. If\n * client authentication is required by the server for the handshake to\n * continue, it may respond with a fatal handshake failure alert.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n *\n * struct {\n * ASN.1Cert certificate_list<0..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n *\n * @return the Certificate byte buffer.\n */\ntls.createCertificate = function(c) {\n // TODO: check certificate request to ensure types are supported\n\n // get a certificate (a certificate as a PEM string)\n var client = (c.entity === tls.ConnectionEnd.client);\n var cert = null;\n if(c.getCertificate) {\n var hint;\n if(client) {\n hint = c.session.certificateRequest;\n } else {\n hint = c.session.extensions.server_name.serverNameList;\n }\n cert = c.getCertificate(c, hint);\n }\n\n // buffer to hold certificate list\n var certList = forge.util.createBuffer();\n if(cert !== null) {\n try {\n // normalize cert to a chain of certificates\n if(!forge.util.isArray(cert)) {\n cert = [cert];\n }\n var asn1 = null;\n for(var i = 0; i < cert.length; ++i) {\n var msg = forge.pem.decode(cert[i])[0];\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error('Could not convert certificate from PEM; PEM ' +\n 'header type is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or ' +\n '\"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n var der = forge.util.createBuffer(msg.body);\n if(asn1 === null) {\n asn1 = forge.asn1.fromDer(der.bytes(), false);\n }\n\n // certificate entry is itself a vector with 3 length bytes\n var certBuffer = forge.util.createBuffer();\n writeVector(certBuffer, 3, der);\n\n // add cert vector to cert list vector\n certList.putBuffer(certBuffer);\n }\n\n // save certificate\n cert = forge.pki.certificateFromAsn1(asn1);\n if(client) {\n c.session.clientCertificate = cert;\n } else {\n c.session.serverCertificate = cert;\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not send certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n }\n\n // determine length of the handshake message\n var length = 3 + certList.length(); // cert list vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate);\n rval.putInt24(length);\n writeVector(rval, 3, certList);\n return rval;\n};\n\n/**\n * Creates a ClientKeyExchange message.\n *\n * When this message will be sent:\n * This message is always sent by the client. It will immediately follow the\n * client certificate message, if it is sent. Otherwise it will be the first\n * message sent by the client after it receives the server hello done\n * message.\n *\n * Meaning of this message:\n * With this message, the premaster secret is set, either though direct\n * transmission of the RSA-encrypted secret, or by the transmission of\n * Diffie-Hellman parameters which will allow each side to agree upon the\n * same premaster secret. When the key exchange method is DH_RSA or DH_DSS,\n * client certification has been requested, and the client was able to\n * respond with a certificate which contained a Diffie-Hellman public key\n * whose parameters (group and generator) matched those specified by the\n * server in its certificate, this message will not contain any data.\n *\n * Meaning of this message:\n * If RSA is being used for key agreement and authentication, the client\n * generates a 48-byte premaster secret, encrypts it using the public key\n * from the server's certificate or the temporary RSA key provided in a\n * server key exchange message, and sends the result in an encrypted\n * premaster secret message. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case rsa: EncryptedPreMasterSecret;\n * case diffie_hellman: ClientDiffieHellmanPublic;\n * } exchange_keys;\n * } ClientKeyExchange;\n *\n * struct {\n * ProtocolVersion client_version;\n * opaque random[46];\n * } PreMasterSecret;\n *\n * struct {\n * public-key-encrypted PreMasterSecret pre_master_secret;\n * } EncryptedPreMasterSecret;\n *\n * A public-key-encrypted element is encoded as a vector <0..2^16-1>.\n *\n * @param c the connection.\n *\n * @return the ClientKeyExchange byte buffer.\n */\ntls.createClientKeyExchange = function(c) {\n // create buffer to encrypt\n var b = forge.util.createBuffer();\n\n // add highest client-supported protocol to help server avoid version\n // rollback attacks\n b.putByte(c.session.clientHelloVersion.major);\n b.putByte(c.session.clientHelloVersion.minor);\n\n // generate and add 46 random bytes\n b.putBytes(forge.random.getBytes(46));\n\n // save pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = b.getBytes();\n\n // RSA-encrypt the pre-master secret\n var key = c.session.serverCertificate.publicKey;\n b = key.encrypt(sp.pre_master_secret);\n\n /* Note: The encrypted pre-master secret will be stored in a\n public-key-encrypted opaque vector that has the length prefixed using\n 2 bytes, so include those 2 bytes in the handshake message length. This\n is done as a minor optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = b.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_key_exchange);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(b.length);\n rval.putBytes(b);\n return rval;\n};\n\n/**\n * Creates a ServerKeyExchange message.\n *\n * @param c the connection.\n *\n * @return the ServerKeyExchange byte buffer.\n */\ntls.createServerKeyExchange = function(c) {\n // this implementation only supports RSA, no Diffie-Hellman support,\n // so this record is empty\n\n // determine length of the handshake message\n var length = 0;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n if(length > 0) {\n rval.putByte(tls.HandshakeType.server_key_exchange);\n rval.putInt24(length);\n }\n return rval;\n};\n\n/**\n * Gets the signed data used to verify a client-side certificate. See\n * tls.createCertificateVerify() for details.\n *\n * @param c the connection.\n * @param callback the callback to call once the signed data is ready.\n */\ntls.getClientSignature = function(c, callback) {\n // generate data to RSA encrypt\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n b = b.getBytes();\n\n // create default signing function as necessary\n c.getSignature = c.getSignature || function(c, b, callback) {\n // do rsa encryption, call callback\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.clientCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n if(privateKey === null) {\n c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else {\n b = privateKey.sign(b, null);\n }\n callback(c, b);\n };\n\n // get client signature\n c.getSignature(c, b, callback);\n};\n\n/**\n * Creates a CertificateVerify message.\n *\n * Meaning of this message:\n * This structure conveys the client's Diffie-Hellman public value\n * (Yc) if it was not already included in the client's certificate.\n * The encoding used for Yc is determined by the enumerated\n * PublicValueEncoding. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * When this message will be sent:\n * This message is used to provide explicit verification of a client\n * certificate. This message is only sent following a client\n * certificate that has signing capability (i.e. all certificates\n * except those containing fixed Diffie-Hellman parameters). When\n * sent, it will immediately follow the client key exchange message.\n *\n * struct {\n * Signature signature;\n * } CertificateVerify;\n *\n * CertificateVerify.signature.md5_hash\n * MD5(handshake_messages);\n *\n * Certificate.signature.sha_hash\n * SHA(handshake_messages);\n *\n * Here handshake_messages refers to all handshake messages sent or\n * received starting at client hello up to but not including this\n * message, including the type and length fields of the handshake\n * messages.\n *\n * select(SignatureAlgorithm) {\n * case anonymous: struct { };\n * case rsa:\n * digitally-signed struct {\n * opaque md5_hash[16];\n * opaque sha_hash[20];\n * };\n * case dsa:\n * digitally-signed struct {\n * opaque sha_hash[20];\n * };\n * } Signature;\n *\n * In digital signing, one-way hash functions are used as input for a\n * signing algorithm. A digitally-signed element is encoded as an opaque\n * vector <0..2^16-1>, where the length is specified by the signing\n * algorithm and key.\n *\n * In RSA signing, a 36-byte structure of two hashes (one SHA and one\n * MD5) is signed (encrypted with the private key). It is encoded with\n * PKCS #1 block type 0 or type 1 as described in [PKCS1].\n *\n * In DSS, the 20 bytes of the SHA hash are run directly through the\n * Digital Signing Algorithm with no additional hashing.\n *\n * @param c the connection.\n * @param signature the signature to include in the message.\n *\n * @return the CertificateVerify byte buffer.\n */\ntls.createCertificateVerify = function(c, signature) {\n /* Note: The signature will be stored in a \"digitally-signed\" opaque\n vector that has the length prefixed using 2 bytes, so include those\n 2 bytes in the handshake message length. This is done as a minor\n optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = signature.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_verify);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(signature.length);\n rval.putBytes(signature);\n return rval;\n};\n\n/**\n * Creates a CertificateRequest message.\n *\n * @param c the connection.\n *\n * @return the CertificateRequest byte buffer.\n */\ntls.createCertificateRequest = function(c) {\n // TODO: support other certificate types\n var certTypes = forge.util.createBuffer();\n\n // common RSA certificate type\n certTypes.putByte(0x01);\n\n // add distinguished names from CA store\n var cAs = forge.util.createBuffer();\n for(var key in c.caStore.certs) {\n var cert = c.caStore.certs[key];\n var dn = forge.pki.distinguishedNameToAsn1(cert.subject);\n var byteBuffer = forge.asn1.toDer(dn);\n cAs.putInt16(byteBuffer.length());\n cAs.putBuffer(byteBuffer);\n }\n\n // TODO: TLS 1.2+ has a different format\n\n // determine length of the handshake message\n var length =\n 1 + certTypes.length() +\n 2 + cAs.length();\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_request);\n rval.putInt24(length);\n writeVector(rval, 1, certTypes);\n writeVector(rval, 2, cAs);\n return rval;\n};\n\n/**\n * Creates a ServerHelloDone message.\n *\n * @param c the connection.\n *\n * @return the ServerHelloDone byte buffer.\n */\ntls.createServerHelloDone = function(c) {\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello_done);\n rval.putInt24(0);\n return rval;\n};\n\n/**\n * Creates a ChangeCipherSpec message.\n *\n * The change cipher spec protocol exists to signal transitions in\n * ciphering strategies. The protocol consists of a single message,\n * which is encrypted and compressed under the current (not the pending)\n * connection state. The message consists of a single byte of value 1.\n *\n * struct {\n * enum { change_cipher_spec(1), (255) } type;\n * } ChangeCipherSpec;\n *\n * @return the ChangeCipherSpec byte buffer.\n */\ntls.createChangeCipherSpec = function() {\n var rval = forge.util.createBuffer();\n rval.putByte(0x01);\n return rval;\n};\n\n/**\n * Creates a Finished message.\n *\n * struct {\n * opaque verify_data[12];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, MD5(handshake_messages) +\n * SHA-1(handshake_messages)) [0..11];\n *\n * finished_label\n * For Finished messages sent by the client, the string \"client\n * finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * handshake_messages\n * All of the data from all handshake messages up to but not\n * including this message. This is only data visible at the\n * handshake layer and does not include record layer headers.\n * This is the concatenation of all the Handshake structures as\n * defined in 7.4 exchanged thus far.\n *\n * @param c the connection.\n *\n * @return the Finished byte buffer.\n */\ntls.createFinished = function(c) {\n // generate verify_data\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // TODO: determine prf function and verify length for TLS 1.2\n var client = (c.entity === tls.ConnectionEnd.client);\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n var label = client ? 'client finished' : 'server finished';\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.finished);\n rval.putInt24(b.length());\n rval.putBuffer(b);\n return rval;\n};\n\n/**\n * Creates a HeartbeatMessage (See RFC 6520).\n *\n * struct {\n * HeartbeatMessageType type;\n * uint16 payload_length;\n * opaque payload[HeartbeatMessage.payload_length];\n * opaque padding[padding_length];\n * } HeartbeatMessage;\n *\n * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or\n * max_fragment_length when negotiated as defined in [RFC6066].\n *\n * type: The message type, either heartbeat_request or heartbeat_response.\n *\n * payload_length: The length of the payload.\n *\n * payload: The payload consists of arbitrary content.\n *\n * padding: The padding is random content that MUST be ignored by the\n * receiver. The length of a HeartbeatMessage is TLSPlaintext.length\n * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the\n * length of the type field is 1 byte, and the length of the\n * payload_length is 2. Therefore, the padding_length is\n * TLSPlaintext.length - payload_length - 3 for TLS and\n * DTLSPlaintext.length - payload_length - 3 for DTLS. The\n * padding_length MUST be at least 16.\n *\n * The sender of a HeartbeatMessage MUST use a random padding of at\n * least 16 bytes. The padding of a received HeartbeatMessage message\n * MUST be ignored.\n *\n * If the payload_length of a received HeartbeatMessage is too large,\n * the received HeartbeatMessage MUST be discarded silently.\n *\n * @param c the connection.\n * @param type the tls.HeartbeatMessageType.\n * @param payload the heartbeat data to send as the payload.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return the HeartbeatRequest byte buffer.\n */\ntls.createHeartbeat = function(type, payload, payloadLength) {\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(type); // heartbeat message type\n rval.putInt16(payloadLength); // payload length\n rval.putBytes(payload); // payload\n // padding\n var plaintextLength = rval.length();\n var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);\n rval.putBytes(forge.random.getBytes(paddingLength));\n return rval;\n};\n\n/**\n * Fragments, compresses, encrypts, and queues a record for delivery.\n *\n * @param c the connection.\n * @param record the record to queue.\n */\ntls.queue = function(c, record) {\n // error during record creation\n if(!record) {\n return;\n }\n\n if(record.fragment.length() === 0) {\n if(record.type === tls.ContentType.handshake ||\n record.type === tls.ContentType.alert ||\n record.type === tls.ContentType.change_cipher_spec) {\n // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent.\n return;\n }\n }\n\n // if the record is a handshake record, update handshake hashes\n if(record.type === tls.ContentType.handshake) {\n var bytes = record.fragment.bytes();\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n bytes = null;\n }\n\n // handle record fragmentation\n var records;\n if(record.fragment.length() <= tls.MaxFragment) {\n records = [record];\n } else {\n // fragment data as long as it is too long\n records = [];\n var data = record.fragment.bytes();\n while(data.length > tls.MaxFragment) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))\n }));\n data = data.slice(tls.MaxFragment);\n }\n // add last record\n if(data.length > 0) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data)\n }));\n }\n }\n\n // compress and encrypt all fragmented records\n for(var i = 0; i < records.length && !c.fail; ++i) {\n // update the record using current write state\n var rec = records[i];\n var s = c.state.current.write;\n if(s.update(c, rec)) {\n // store record\n c.records.push(rec);\n }\n }\n};\n\n/**\n * Flushes all queued records to the output buffer and calls the\n * tlsDataReady() handler on the given connection.\n *\n * @param c the connection.\n *\n * @return true on success, false on failure.\n */\ntls.flush = function(c) {\n for(var i = 0; i < c.records.length; ++i) {\n var record = c.records[i];\n\n // add record header and fragment\n c.tlsData.putByte(record.type);\n c.tlsData.putByte(record.version.major);\n c.tlsData.putByte(record.version.minor);\n c.tlsData.putInt16(record.fragment.length());\n c.tlsData.putBuffer(c.records[i].fragment);\n }\n c.records = [];\n return c.tlsDataReady(c);\n};\n\n/**\n * Maps a pki.certificateError to a tls.Alert.Description.\n *\n * @param error the error to map.\n *\n * @return the alert description.\n */\nvar _certErrorToAlertDesc = function(error) {\n switch(error) {\n case true:\n return true;\n case forge.pki.certificateError.bad_certificate:\n return tls.Alert.Description.bad_certificate;\n case forge.pki.certificateError.unsupported_certificate:\n return tls.Alert.Description.unsupported_certificate;\n case forge.pki.certificateError.certificate_revoked:\n return tls.Alert.Description.certificate_revoked;\n case forge.pki.certificateError.certificate_expired:\n return tls.Alert.Description.certificate_expired;\n case forge.pki.certificateError.certificate_unknown:\n return tls.Alert.Description.certificate_unknown;\n case forge.pki.certificateError.unknown_ca:\n return tls.Alert.Description.unknown_ca;\n default:\n return tls.Alert.Description.bad_certificate;\n }\n};\n\n/**\n * Maps a tls.Alert.Description to a pki.certificateError.\n *\n * @param desc the alert description.\n *\n * @return the certificate error.\n */\nvar _alertDescToCertError = function(desc) {\n switch(desc) {\n case true:\n return true;\n case tls.Alert.Description.bad_certificate:\n return forge.pki.certificateError.bad_certificate;\n case tls.Alert.Description.unsupported_certificate:\n return forge.pki.certificateError.unsupported_certificate;\n case tls.Alert.Description.certificate_revoked:\n return forge.pki.certificateError.certificate_revoked;\n case tls.Alert.Description.certificate_expired:\n return forge.pki.certificateError.certificate_expired;\n case tls.Alert.Description.certificate_unknown:\n return forge.pki.certificateError.certificate_unknown;\n case tls.Alert.Description.unknown_ca:\n return forge.pki.certificateError.unknown_ca;\n default:\n return forge.pki.certificateError.bad_certificate;\n }\n};\n\n/**\n * Verifies a certificate chain against the given connection's\n * Certificate Authority store.\n *\n * @param c the TLS connection.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end.\n *\n * @return true if successful, false if not.\n */\ntls.verifyCertificateChain = function(c, chain) {\n try {\n // Make a copy of c.verifyOptions so that we can modify options.verify\n // without modifying c.verifyOptions.\n var options = {};\n for (var key in c.verifyOptions) {\n options[key] = c.verifyOptions[key];\n }\n\n options.verify = function(vfd, depth, chain) {\n // convert pki.certificateError to tls alert description\n var desc = _certErrorToAlertDesc(vfd);\n\n // call application callback\n var ret = c.verify(c, vfd, depth, chain);\n if(ret !== true) {\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n // throw custom error\n var error = new Error('The application rejected the certificate.');\n error.send = true;\n error.alert = {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n };\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n throw error;\n }\n\n // convert tls alert description to pki.certificateError\n if(ret !== vfd) {\n ret = _alertDescToCertError(ret);\n }\n }\n\n return ret;\n };\n\n // verify chain\n forge.pki.verifyCertificateChain(c.caStore, chain, options);\n } catch(ex) {\n // build tls error if not already customized\n var err = ex;\n if(typeof err !== 'object' || forge.util.isArray(err)) {\n err = {\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(ex)\n }\n };\n }\n if(!('send' in err)) {\n err.send = true;\n }\n if(!('alert' in err)) {\n err.alert = {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(err.error)\n };\n }\n\n // send error\n c.error(c, err);\n }\n\n return !c.fail;\n};\n\n/**\n * Creates a new TLS session cache.\n *\n * @param cache optional map of session ID to cached session.\n * @param capacity the maximum size for the cache (default: 100).\n *\n * @return the new TLS session cache.\n */\ntls.createSessionCache = function(cache, capacity) {\n var rval = null;\n\n // assume input is already a session cache object\n if(cache && cache.getSession && cache.setSession && cache.order) {\n rval = cache;\n } else {\n // create cache\n rval = {};\n rval.cache = cache || {};\n rval.capacity = Math.max(capacity || 100, 1);\n rval.order = [];\n\n // store order for sessions, delete session overflow\n for(var key in cache) {\n if(rval.order.length <= capacity) {\n rval.order.push(key);\n } else {\n delete cache[key];\n }\n }\n\n // get a session from a session ID (or get any session)\n rval.getSession = function(sessionId) {\n var session = null;\n var key = null;\n\n // if session ID provided, use it\n if(sessionId) {\n key = forge.util.bytesToHex(sessionId);\n } else if(rval.order.length > 0) {\n // get first session from cache\n key = rval.order[0];\n }\n\n if(key !== null && key in rval.cache) {\n // get cached session and remove from cache\n session = rval.cache[key];\n delete rval.cache[key];\n for(var i in rval.order) {\n if(rval.order[i] === key) {\n rval.order.splice(i, 1);\n break;\n }\n }\n }\n\n return session;\n };\n\n // set a session in the cache\n rval.setSession = function(sessionId, session) {\n // remove session from cache if at capacity\n if(rval.order.length === rval.capacity) {\n var key = rval.order.shift();\n delete rval.cache[key];\n }\n // add session to cache\n var key = forge.util.bytesToHex(sessionId);\n rval.order.push(key);\n rval.cache[key] = session;\n };\n }\n\n return rval;\n};\n\n/**\n * Creates a new TLS connection.\n *\n * See public createConnection() docs for more details.\n *\n * @param options the options for this connection.\n *\n * @return the new TLS connection.\n */\ntls.createConnection = function(options) {\n var caStore = null;\n if(options.caStore) {\n // if CA store is an array, convert it to a CA store object\n if(forge.util.isArray(options.caStore)) {\n caStore = forge.pki.createCaStore(options.caStore);\n } else {\n caStore = options.caStore;\n }\n } else {\n // create empty CA store\n caStore = forge.pki.createCaStore();\n }\n\n // setup default cipher suites\n var cipherSuites = options.cipherSuites || null;\n if(cipherSuites === null) {\n cipherSuites = [];\n for(var key in tls.CipherSuites) {\n cipherSuites.push(tls.CipherSuites[key]);\n }\n }\n\n // set default entity\n var entity = (options.server || false) ?\n tls.ConnectionEnd.server : tls.ConnectionEnd.client;\n\n // create session cache if requested\n var sessionCache = options.sessionCache ?\n tls.createSessionCache(options.sessionCache) : null;\n\n // create TLS connection\n var c = {\n version: {major: tls.Version.major, minor: tls.Version.minor},\n entity: entity,\n sessionId: options.sessionId,\n caStore: caStore,\n sessionCache: sessionCache,\n cipherSuites: cipherSuites,\n connected: options.connected,\n virtualHost: options.virtualHost || null,\n verifyClient: options.verifyClient || false,\n verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},\n verifyOptions: options.verifyOptions || {},\n getCertificate: options.getCertificate || null,\n getPrivateKey: options.getPrivateKey || null,\n getSignature: options.getSignature || null,\n input: forge.util.createBuffer(),\n tlsData: forge.util.createBuffer(),\n data: forge.util.createBuffer(),\n tlsDataReady: options.tlsDataReady,\n dataReady: options.dataReady,\n heartbeatReceived: options.heartbeatReceived,\n closed: options.closed,\n error: function(c, ex) {\n // set origin if not set\n ex.origin = ex.origin ||\n ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server');\n\n // send TLS alert\n if(ex.send) {\n tls.queue(c, tls.createAlert(c, ex.alert));\n tls.flush(c);\n }\n\n // error is fatal by default\n var fatal = (ex.fatal !== false);\n if(fatal) {\n // set fail flag\n c.fail = true;\n }\n\n // call error handler first\n options.error(c, ex);\n\n if(fatal) {\n // fatal error, close connection, do not clear fail\n c.close(false);\n }\n },\n deflate: options.deflate || null,\n inflate: options.inflate || null\n };\n\n /**\n * Resets a closed TLS connection for reuse. Called in c.close().\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.reset = function(clearFail) {\n c.version = {major: tls.Version.major, minor: tls.Version.minor};\n c.record = null;\n c.session = null;\n c.peerCertificate = null;\n c.state = {\n pending: null,\n current: null\n };\n c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE;\n c.fragmented = null;\n c.records = [];\n c.open = false;\n c.handshakes = 0;\n c.handshaking = false;\n c.isConnected = false;\n c.fail = !(clearFail || typeof(clearFail) === 'undefined');\n c.input.clear();\n c.tlsData.clear();\n c.data.clear();\n c.state.current = tls.createConnectionState(c);\n };\n\n // do initial reset of connection\n c.reset();\n\n /**\n * Updates the current TLS engine state based on the given record.\n *\n * @param c the TLS connection.\n * @param record the TLS record to act on.\n */\n var _update = function(c, record) {\n // get record handler (align type in table by subtracting lowest)\n var aligned = record.type - tls.ContentType.change_cipher_spec;\n var handlers = ctTable[c.entity][c.expect];\n if(aligned in handlers) {\n handlers[aligned](c, record);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n };\n\n /**\n * Reads the record header and initializes the next record on the given\n * connection.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecordHeader = function(c) {\n var rval = 0;\n\n // get input buffer and its length\n var b = c.input;\n var len = b.length();\n\n // need at least 5 bytes to initialize a record\n if(len < 5) {\n rval = 5 - len;\n } else {\n // enough bytes for header\n // initialize record\n c.record = {\n type: b.getByte(),\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n length: b.getInt16(),\n fragment: forge.util.createBuffer(),\n ready: false\n };\n\n // check record version\n var compatibleVersion = (c.record.version.major === c.version.major);\n if(compatibleVersion && c.session && c.session.version) {\n // session version already set, require same minor version\n compatibleVersion = (c.record.version.minor === c.version.minor);\n }\n if(!compatibleVersion) {\n c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n return rval;\n };\n\n /**\n * Reads the next record's contents and appends its message to any\n * previously fragmented message.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecord = function(c) {\n var rval = 0;\n\n // ensure there is enough input data to get the entire record\n var b = c.input;\n var len = b.length();\n if(len < c.record.length) {\n // not enough data yet, return how much is required\n rval = c.record.length - len;\n } else {\n // there is enough data to parse the pending record\n // fill record fragment and compact input buffer\n c.record.fragment.putBytes(b.getBytes(c.record.length));\n b.compact();\n\n // update record using current read state\n var s = c.state.current.read;\n if(s.update(c, c.record)) {\n // see if there is a previously fragmented message that the\n // new record's message fragment should be appended to\n if(c.fragmented !== null) {\n // if the record type matches a previously fragmented\n // record, append the record fragment to it\n if(c.fragmented.type === c.record.type) {\n // concatenate record fragments\n c.fragmented.fragment.putBuffer(c.record.fragment);\n c.record = c.fragmented;\n } else {\n // error, invalid fragmented record\n c.error(c, {\n message: 'Invalid fragmented record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description:\n tls.Alert.Description.unexpected_message\n }\n });\n }\n }\n\n // record is now ready\n c.record.ready = true;\n }\n }\n\n return rval;\n };\n\n /**\n * Performs a handshake using the TLS Handshake Protocol, as a client.\n *\n * This method should only be called if the connection is in client mode.\n *\n * @param sessionId the session ID to use, null to start a new one.\n */\n c.handshake = function(sessionId) {\n // error to call this in non-client mode\n if(c.entity !== tls.ConnectionEnd.client) {\n // not fatal error\n c.error(c, {\n message: 'Cannot initiate handshake as a server.',\n fatal: false\n });\n } else if(c.handshaking) {\n // handshake is already in progress, fail but not fatal error\n c.error(c, {\n message: 'Handshake already in progress.',\n fatal: false\n });\n } else {\n // clear fail flag on reuse\n if(c.fail && !c.open && c.handshakes === 0) {\n c.fail = false;\n }\n\n // now handshaking\n c.handshaking = true;\n\n // default to blank (new session)\n sessionId = sessionId || '';\n\n // if a session ID was specified, try to find it in the cache\n var session = null;\n if(sessionId.length > 0) {\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n }\n\n // matching session not found in cache, clear session ID\n if(session === null) {\n sessionId = '';\n }\n }\n\n // no session given, grab a session from the cache, if available\n if(sessionId.length === 0 && c.sessionCache) {\n session = c.sessionCache.getSession();\n if(session !== null) {\n sessionId = session.id;\n }\n }\n\n // set up session\n c.session = {\n id: sessionId,\n version: null,\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n certificateRequest: null,\n clientCertificate: null,\n sp: {},\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n\n // use existing session information\n if(session) {\n // only update version on connection, session version not yet set\n c.version = session.version;\n c.session.sp = session.sp;\n }\n\n // generate new client random\n c.session.sp.client_random = tls.createRandom().getBytes();\n\n // connection now open\n c.open = true;\n\n // send hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientHello(c)\n }));\n tls.flush(c);\n }\n };\n\n /**\n * Called when TLS protocol data has been received from somewhere and should\n * be processed by the TLS engine.\n *\n * @param data the TLS protocol data, as a string, to process.\n *\n * @return 0 if the data could be processed, otherwise the number of bytes\n * required for data to be processed.\n */\n c.process = function(data) {\n var rval = 0;\n\n // buffer input data\n if(data) {\n c.input.putBytes(data);\n }\n\n // process next record if no failure, process will be called after\n // each record is handled (since handling can be asynchronous)\n if(!c.fail) {\n // reset record if ready and now empty\n if(c.record !== null &&\n c.record.ready && c.record.fragment.isEmpty()) {\n c.record = null;\n }\n\n // if there is no pending record, try to read record header\n if(c.record === null) {\n rval = _readRecordHeader(c);\n }\n\n // read the next record (if record not yet ready)\n if(!c.fail && c.record !== null && !c.record.ready) {\n rval = _readRecord(c);\n }\n\n // record ready to be handled, update engine state\n if(!c.fail && c.record !== null && c.record.ready) {\n _update(c, c.record);\n }\n }\n\n return rval;\n };\n\n /**\n * Requests that application data be packaged into a TLS record. The\n * tlsDataReady handler will be called when the TLS record(s) have been\n * prepared.\n *\n * @param data the application data, as a raw 'binary' encoded string, to\n * be sent; to send utf-16/utf-8 string data, use the return value\n * of util.encodeUtf8(str).\n *\n * @return true on success, false on failure.\n */\n c.prepare = function(data) {\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.application_data,\n data: forge.util.createBuffer(data)\n }));\n return tls.flush(c);\n };\n\n /**\n * Requests that a heartbeat request be packaged into a TLS record for\n * transmission. The tlsDataReady handler will be called when TLS record(s)\n * have been prepared.\n *\n * When a heartbeat response has been received, the heartbeatReceived\n * handler will be called with the matching payload. This handler can\n * be used to clear a retransmission timer, etc.\n *\n * @param payload the heartbeat data to send as the payload in the message.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return true on success, false on failure.\n */\n c.prepareHeartbeatRequest = function(payload, payloadLength) {\n if(payload instanceof forge.util.ByteBuffer) {\n payload = payload.bytes();\n }\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n c.expectedHeartbeatPayload = payload;\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)\n }));\n return tls.flush(c);\n };\n\n /**\n * Closes the connection (sends a close_notify alert).\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.close = function(clearFail) {\n // save session if connection didn't fail\n if(!c.fail && c.sessionCache && c.session) {\n // only need to preserve session ID, version, and security params\n var session = {\n id: c.session.id,\n version: c.session.version,\n sp: c.session.sp\n };\n session.sp.keys = null;\n c.sessionCache.setSession(session.id, session);\n }\n\n if(c.open) {\n // connection no longer open, clear input\n c.open = false;\n c.input.clear();\n\n // if connected or handshaking, send an alert\n if(c.isConnected || c.handshaking) {\n c.isConnected = c.handshaking = false;\n\n // send close_notify alert\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.close_notify\n }));\n tls.flush(c);\n }\n\n // call handler\n c.closed(c);\n }\n\n // reset TLS connection, do not clear fail flag\n c.reset(clearFail);\n };\n\n return c;\n};\n\n/* TLS API */\nmodule.exports = forge.tls = forge.tls || {};\n\n// expose non-functions\nfor(var key in tls) {\n if(typeof tls[key] !== 'function') {\n forge.tls[key] = tls[key];\n }\n}\n\n// expose prf_tls1 for testing\nforge.tls.prf_tls1 = prf_TLS1;\n\n// expose sha1 hmac method\nforge.tls.hmac_sha1 = hmac_sha1;\n\n// expose session cache creation\nforge.tls.createSessionCache = tls.createSessionCache;\n\n/**\n * Creates a new TLS connection. This does not make any assumptions about the\n * transport layer that TLS is working on top of, ie: it does not assume there\n * is a TCP/IP connection or establish one. A TLS connection is totally\n * abstracted away from the layer is runs on top of, it merely establishes a\n * secure channel between a client\" and a \"server\".\n *\n * A TLS connection contains 4 connection states: pending read and write, and\n * current read and write.\n *\n * At initialization, the current read and write states will be null. Only once\n * the security parameters have been set and the keys have been generated can\n * the pending states be converted into current states. Current states will be\n * updated for each record processed.\n *\n * A custom certificate verify callback may be provided to check information\n * like the common name on the server's certificate. It will be called for\n * every certificate in the chain. It has the following signature:\n *\n * variable func(c, certs, index, preVerify)\n * Where:\n * c The TLS connection\n * verified Set to true if certificate was verified, otherwise the alert\n * tls.Alert.Description for why the certificate failed.\n * depth The current index in the chain, where 0 is the server's cert.\n * certs The certificate chain, *NOTE* if the server was anonymous then\n * the chain will be empty.\n *\n * The function returns true on success and on failure either the appropriate\n * tls.Alert.Description or an object with 'alert' set to the appropriate\n * tls.Alert.Description and 'message' set to a custom error message. If true\n * is not returned then the connection will abort using, in order of\n * availability, first the returned alert description, second the preVerify\n * alert description, and lastly the default 'bad_certificate'.\n *\n * There are three callbacks that can be used to make use of client-side\n * certificates where each takes the TLS connection as the first parameter:\n *\n * getCertificate(conn, hint)\n * The second parameter is a hint as to which certificate should be\n * returned. If the connection entity is a client, then the hint will be\n * the CertificateRequest message from the server that is part of the\n * TLS protocol. If the connection entity is a server, then it will be\n * the servername list provided via an SNI extension the ClientHello, if\n * one was provided (empty array if not). The hint can be examined to\n * determine which certificate to use (advanced). Most implementations\n * will just return a certificate. The return value must be a\n * PEM-formatted certificate or an array of PEM-formatted certificates\n * that constitute a certificate chain, with the first in the array/chain\n * being the client's certificate.\n * getPrivateKey(conn, certificate)\n * The second parameter is an forge.pki X.509 certificate object that\n * is associated with the requested private key. The return value must\n * be a PEM-formatted private key.\n * getSignature(conn, bytes, callback)\n * This callback can be used instead of getPrivateKey if the private key\n * is not directly accessible in javascript or should not be. For\n * instance, a secure external web service could provide the signature\n * in exchange for appropriate credentials. The second parameter is a\n * string of bytes to be signed that are part of the TLS protocol. These\n * bytes are used to verify that the private key for the previously\n * provided client-side certificate is accessible to the client. The\n * callback is a function that takes 2 parameters, the TLS connection\n * and the RSA encrypted (signed) bytes as a string. This callback must\n * be called once the signature is ready.\n *\n * @param options the options for this connection:\n * server: true if the connection is server-side, false for client.\n * sessionId: a session ID to reuse, null for a new connection.\n * caStore: an array of certificates to trust.\n * sessionCache: a session cache to use.\n * cipherSuites: an optional array of cipher suites to use,\n * see tls.CipherSuites.\n * connected: function(conn) called when the first handshake completes.\n * virtualHost: the virtual server name to use in a TLS SNI extension.\n * verifyClient: true to require a client certificate in server mode,\n * 'optional' to request one, false not to (default: false).\n * verify: a handler used to custom verify certificates in the chain.\n * verifyOptions: an object with options for the certificate chain validation.\n * See documentation of pki.verifyCertificateChain for possible options.\n * verifyOptions.verify is ignored. If you wish to specify a verify handler\n * use the verify key.\n * getCertificate: an optional callback used to get a certificate or\n * a chain of certificates (as an array).\n * getPrivateKey: an optional callback used to get a private key.\n * getSignature: an optional callback used to get a signature.\n * tlsDataReady: function(conn) called when TLS protocol data has been\n * prepared and is ready to be used (typically sent over a socket\n * connection to its destination), read from conn.tlsData buffer.\n * dataReady: function(conn) called when application data has\n * been parsed from a TLS record and should be consumed by the\n * application, read from conn.data buffer.\n * closed: function(conn) called when the connection has been closed.\n * error: function(conn, error) called when there was an error.\n * deflate: function(inBytes) if provided, will deflate TLS records using\n * the deflate algorithm if the server supports it.\n * inflate: function(inBytes) if provided, will inflate TLS records using\n * the deflate algorithm if the server supports it.\n *\n * @return the new TLS connection.\n */\nforge.tls.createConnection = tls.createConnection;\n","/**\n * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nvar baseN = require('./baseN');\n\n/* Utilities API */\nvar util = module.exports = forge.util = forge.util || {};\n\n// define setImmediate and nextTick\n(function() {\n // use native nextTick (unless we're in webpack)\n // webpack (or better node-libs-browser polyfill) sets process.browser.\n // this way we can detect webpack properly\n if(typeof process !== 'undefined' && process.nextTick && !process.browser) {\n util.nextTick = process.nextTick;\n if(typeof setImmediate === 'function') {\n util.setImmediate = setImmediate;\n } else {\n // polyfill setImmediate with nextTick, older versions of node\n // (those w/o setImmediate) won't totally starve IO\n util.setImmediate = util.nextTick;\n }\n return;\n }\n\n // polyfill nextTick with native setImmediate\n if(typeof setImmediate === 'function') {\n util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };\n util.nextTick = function(callback) {\n return setImmediate(callback);\n };\n return;\n }\n\n /* Note: A polyfill upgrade pattern is used here to allow combining\n polyfills. For example, MutationObserver is fast, but blocks UI updates,\n so it needs to allow UI updates periodically, so it falls back on\n postMessage or setTimeout. */\n\n // polyfill with setTimeout\n util.setImmediate = function(callback) {\n setTimeout(callback, 0);\n };\n\n // upgrade polyfill to use postMessage\n if(typeof window !== 'undefined' &&\n typeof window.postMessage === 'function') {\n var msg = 'forge.setImmediate';\n var callbacks = [];\n util.setImmediate = function(callback) {\n callbacks.push(callback);\n // only send message when one hasn't been sent in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n window.postMessage(msg, '*');\n }\n };\n function handler(event) {\n if(event.source === window && event.data === msg) {\n event.stopPropagation();\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }\n }\n window.addEventListener('message', handler, true);\n }\n\n // upgrade polyfill to use MutationObserver\n if(typeof MutationObserver !== 'undefined') {\n // polyfill with MutationObserver\n var now = Date.now();\n var attr = true;\n var div = document.createElement('div');\n var callbacks = [];\n new MutationObserver(function() {\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }).observe(div, {attributes: true});\n var oldSetImmediate = util.setImmediate;\n util.setImmediate = function(callback) {\n if(Date.now() - now > 15) {\n now = Date.now();\n oldSetImmediate(callback);\n } else {\n callbacks.push(callback);\n // only trigger observer when it hasn't been triggered in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n div.setAttribute('a', attr = !attr);\n }\n }\n };\n }\n\n util.nextTick = util.setImmediate;\n})();\n\n// check if running under Node.js\nutil.isNodejs =\n typeof process !== 'undefined' && process.versions && process.versions.node;\n\n\n// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while\n// it will point to `window` in the main thread.\n// To remain compatible with older browsers, we fall back to 'window' if 'self'\n// is not available.\nutil.globalScope = (function() {\n if(util.isNodejs) {\n return global;\n }\n\n return typeof self === 'undefined' ? window : self;\n})();\n\n// define isArray\nutil.isArray = Array.isArray || function(x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// define isArrayBuffer\nutil.isArrayBuffer = function(x) {\n return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;\n};\n\n// define isArrayBufferView\nutil.isArrayBufferView = function(x) {\n return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;\n};\n\n/**\n * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for\n * algorithms where bit manipulation, JavaScript limitations, and/or algorithm\n * design only allow for byte operations of a limited size.\n *\n * @param n number of bits.\n *\n * Throw Error if n invalid.\n */\nfunction _checkBitsParam(n) {\n if(!(n === 8 || n === 16 || n === 24 || n === 32)) {\n throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);\n }\n}\n\n// TODO: set ByteBuffer to best available backing\nutil.ByteBuffer = ByteStringBuffer;\n\n/** Buffer w/BinaryString backing */\n\n/**\n * Constructor for a binary string backed byte buffer.\n *\n * @param [b] the bytes to wrap (either encoded as string, one byte per\n * character, or as an ArrayBuffer or Typed Array).\n */\nfunction ByteStringBuffer(b) {\n // TODO: update to match DataBuffer API\n\n // the data in this buffer\n this.data = '';\n // the pointer for reading from this buffer\n this.read = 0;\n\n if(typeof b === 'string') {\n this.data = b;\n } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {\n if(typeof Buffer !== 'undefined' && b instanceof Buffer) {\n this.data = b.toString('binary');\n } else {\n // convert native buffer to forge buffer\n // FIXME: support native buffers internally instead\n var arr = new Uint8Array(b);\n try {\n this.data = String.fromCharCode.apply(null, arr);\n } catch(e) {\n for(var i = 0; i < arr.length; ++i) {\n this.putByte(arr[i]);\n }\n }\n }\n } else if(b instanceof ByteStringBuffer ||\n (typeof b === 'object' && typeof b.data === 'string' &&\n typeof b.read === 'number')) {\n // copy existing buffer\n this.data = b.data;\n this.read = b.read;\n }\n\n // used for v8 optimization\n this._constructedStringLength = 0;\n}\nutil.ByteStringBuffer = ByteStringBuffer;\n\n/* Note: This is an optimization for V8-based browsers. When V8 concatenates\n a string, the strings are only joined logically using a \"cons string\" or\n \"constructed/concatenated string\". These containers keep references to one\n another and can result in very large memory usage. For example, if a 2MB\n string is constructed by concatenating 4 bytes together at a time, the\n memory usage will be ~44MB; so ~22x increase. The strings are only joined\n together when an operation requiring their joining takes place, such as\n substr(). This function is called when adding data to this buffer to ensure\n these types of strings are periodically joined to reduce the memory\n footprint. */\nvar _MAX_CONSTRUCTED_STRING_LENGTH = 4096;\nutil.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {\n this._constructedStringLength += x;\n if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {\n // this substr() should cause the constructed string to join\n this.data.substr(0, 1);\n this._constructedStringLength = 0;\n }\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.ByteStringBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.ByteStringBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putByte = function(b) {\n return this.putBytes(String.fromCharCode(b));\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.fillWithByte = function(b, n) {\n b = String.fromCharCode(b);\n var d = this.data;\n while(n > 0) {\n if(n & 1) {\n d += b;\n }\n n >>>= 1;\n if(n > 0) {\n b += b;\n }\n }\n this.data = d;\n this._optimizeConstructedString(n);\n return this;\n};\n\n/**\n * Puts bytes in this buffer.\n *\n * @param bytes the bytes (as a binary encoded string) to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n this._optimizeConstructedString(bytes.length);\n return this;\n};\n\n/**\n * Puts a UTF-16 encoded string into this buffer.\n *\n * @param str the string to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putString = function(str) {\n return this.putBytes(util.encodeUtf8(str));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 24 & 0xFF));\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n var bytes = '';\n do {\n n -= 8;\n bytes += String.fromCharCode((i >> n) & 0xFF);\n } while(n > 0);\n return this.putBytes(bytes);\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putSignedInt = function(i, n) {\n // putInt checks n\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBuffer = function(buffer) {\n return this.putBytes(buffer.getBytes());\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.getByte = function() {\n return this.data.charCodeAt(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 8 ^\n this.data.charCodeAt(this.read + 1));\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 16 ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16 ^\n this.data.charCodeAt(this.read + 3) << 24);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by ceil(n/8).\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.charCodeAt(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer. Note that the resulting string is binary encoded (in node.js this\n * encoding is referred to as `binary`, it is *not* `utf8`).\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.ByteStringBuffer.prototype.getBytes = function(count) {\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.ByteStringBuffer.prototype.bytes = function(count) {\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.at = function(i) {\n return this.data.charCodeAt(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.setAt = function(i, b) {\n this.data = this.data.substr(0, this.read + i) +\n String.fromCharCode(b) +\n this.data.substr(this.read + i + 1);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.ByteStringBuffer.prototype.last = function() {\n return this.data.charCodeAt(this.data.length - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.ByteStringBuffer.prototype.copy = function() {\n var c = util.createBuffer(this.data);\n c.read = this.read;\n return c;\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.compact = function() {\n if(this.read > 0) {\n this.data = this.data.slice(this.read);\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.clear = function() {\n this.data = '';\n this.read = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.truncate = function(count) {\n var len = Math.max(0, this.length() - count);\n this.data = this.data.substr(this.read, len);\n this.read = 0;\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.ByteStringBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a UTF-16 string (standard JavaScript string).\n *\n * @return a UTF-16 string.\n */\nutil.ByteStringBuffer.prototype.toString = function() {\n return util.decodeUtf8(this.bytes());\n};\n\n/** End Buffer w/BinaryString backing */\n\n/** Buffer w/UInt8Array backing */\n\n/**\n * FIXME: Experimental. Do not use yet.\n *\n * Constructor for an ArrayBuffer-backed byte buffer.\n *\n * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a\n * TypedArray.\n *\n * If a string is given, its encoding should be provided as an option,\n * otherwise it will default to 'binary'. A 'binary' string is encoded such\n * that each character is one byte in length and size.\n *\n * If an ArrayBuffer, DataView, or TypedArray is given, it will be used\n * *directly* without any copying. Note that, if a write to the buffer requires\n * more space, the buffer will allocate a new backing ArrayBuffer to\n * accommodate. The starting read and write offsets for the buffer may be\n * given as options.\n *\n * @param [b] the initial bytes for this buffer.\n * @param options the options to use:\n * [readOffset] the starting read offset to use (default: 0).\n * [writeOffset] the starting write offset to use (default: the\n * length of the first parameter).\n * [growSize] the minimum amount, in bytes, to grow the buffer by to\n * accommodate writes (default: 1024).\n * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the\n * first parameter, if it is a string (default: 'binary').\n */\nfunction DataBuffer(b, options) {\n // default options\n options = options || {};\n\n // pointers for read from/write to buffer\n this.read = options.readOffset || 0;\n this.growSize = options.growSize || 1024;\n\n var isArrayBuffer = util.isArrayBuffer(b);\n var isArrayBufferView = util.isArrayBufferView(b);\n if(isArrayBuffer || isArrayBufferView) {\n // use ArrayBuffer directly\n if(isArrayBuffer) {\n this.data = new DataView(b);\n } else {\n // TODO: adjust read/write offset based on the type of view\n // or specify that this must be done in the options ... that the\n // offsets are byte-based\n this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);\n }\n this.write = ('writeOffset' in options ?\n options.writeOffset : this.data.byteLength);\n return;\n }\n\n // initialize to empty array buffer and add any given bytes using putBytes\n this.data = new DataView(new ArrayBuffer(0));\n this.write = 0;\n\n if(b !== null && b !== undefined) {\n this.putBytes(b);\n }\n\n if('writeOffset' in options) {\n this.write = options.writeOffset;\n }\n}\nutil.DataBuffer = DataBuffer;\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.DataBuffer.prototype.length = function() {\n return this.write - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.DataBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Ensures this buffer has enough empty space to accommodate the given number\n * of bytes. An optional parameter may be given that indicates a minimum\n * amount to grow the buffer if necessary. If the parameter is not given,\n * the buffer will be grown by some previously-specified default amount\n * or heuristic.\n *\n * @param amount the number of bytes to accommodate.\n * @param [growSize] the minimum amount, in bytes, to grow the buffer by if\n * necessary.\n */\nutil.DataBuffer.prototype.accommodate = function(amount, growSize) {\n if(this.length() >= amount) {\n return this;\n }\n growSize = Math.max(growSize || this.growSize, amount);\n\n // grow buffer\n var src = new Uint8Array(\n this.data.buffer, this.data.byteOffset, this.data.byteLength);\n var dst = new Uint8Array(this.length() + growSize);\n dst.set(src);\n this.data = new DataView(dst.buffer);\n\n return this;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putByte = function(b) {\n this.accommodate(1);\n this.data.setUint8(this.write++, b);\n return this;\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.fillWithByte = function(b, n) {\n this.accommodate(n);\n for(var i = 0; i < n; ++i) {\n this.data.setUint8(b);\n }\n return this;\n};\n\n/**\n * Puts bytes in this buffer. The bytes may be given as a string, an\n * ArrayBuffer, a DataView, or a TypedArray.\n *\n * @param bytes the bytes to put.\n * @param [encoding] the encoding for the first parameter ('binary', 'utf8',\n * 'utf16', 'hex'), if it is a string (default: 'binary').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBytes = function(bytes, encoding) {\n if(util.isArrayBufferView(bytes)) {\n var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n var len = src.byteLength - src.byteOffset;\n this.accommodate(len);\n var dst = new Uint8Array(this.data.buffer, this.write);\n dst.set(src);\n this.write += len;\n return this;\n }\n\n if(util.isArrayBuffer(bytes)) {\n var src = new Uint8Array(bytes);\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(this.data.buffer);\n dst.set(src, this.write);\n this.write += src.byteLength;\n return this;\n }\n\n // bytes is a util.DataBuffer or equivalent\n if(bytes instanceof util.DataBuffer ||\n (typeof bytes === 'object' &&\n typeof bytes.read === 'number' && typeof bytes.write === 'number' &&\n util.isArrayBufferView(bytes.data))) {\n var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(bytes.data.byteLength, this.write);\n dst.set(src);\n this.write += src.byteLength;\n return this;\n }\n\n if(bytes instanceof util.ByteStringBuffer) {\n // copy binary string and process as the same as a string parameter below\n bytes = bytes.data;\n encoding = 'binary';\n }\n\n // string conversion\n encoding = encoding || 'binary';\n if(typeof bytes === 'string') {\n var view;\n\n // decode from string\n if(encoding === 'hex') {\n this.accommodate(Math.ceil(bytes.length / 2));\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.hex.decode(bytes, view, this.write);\n return this;\n }\n if(encoding === 'base64') {\n this.accommodate(Math.ceil(bytes.length / 4) * 3);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.base64.decode(bytes, view, this.write);\n return this;\n }\n\n // encode text as UTF-8 bytes\n if(encoding === 'utf8') {\n // encode as UTF-8 then decode string as raw binary\n bytes = util.encodeUtf8(bytes);\n encoding = 'binary';\n }\n\n // decode string as raw binary\n if(encoding === 'binary' || encoding === 'raw') {\n // one byte per character\n this.accommodate(bytes.length);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.raw.decode(view);\n return this;\n }\n\n // encode text as UTF-16 bytes\n if(encoding === 'utf16') {\n // two bytes per character\n this.accommodate(bytes.length * 2);\n view = new Uint16Array(this.data.buffer, this.write);\n this.write += util.text.utf16.encode(view);\n return this;\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n }\n\n throw Error('Invalid parameter: ' + bytes);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBuffer = function(buffer) {\n this.putBytes(buffer);\n buffer.clear();\n return this;\n};\n\n/**\n * Puts a string into this buffer.\n *\n * @param str the string to put.\n * @param [encoding] the encoding for the string (default: 'utf16').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putString = function(str) {\n return this.putBytes(str, 'utf16');\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16 = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24 = function(i) {\n this.accommodate(3);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32 = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16Le = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i, true);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24Le = function(i) {\n this.accommodate(3);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32Le = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i, true);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n do {\n n -= 8;\n this.data.setInt8(this.write++, (i >> n) & 0xFF);\n } while(n > 0);\n return this;\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putSignedInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.getByte = function() {\n return this.data.getInt8(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16 = function() {\n var rval = this.data.getInt16(this.read);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.getInt16(this.read) << 8 ^\n this.data.getInt8(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32 = function() {\n var rval = this.data.getInt32(this.read);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16Le = function() {\n var rval = this.data.getInt16(this.read, true);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.getInt8(this.read) ^\n this.data.getInt16(this.read + 1, true) << 8);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32Le = function() {\n var rval = this.data.getInt32(this.read, true);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.getInt8(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer.\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.DataBuffer.prototype.getBytes = function(count) {\n // TODO: deprecate this method, it is poorly named and\n // this.toString('binary') replaces it\n // add a toTypedArray()/toArrayBuffer() function\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.DataBuffer.prototype.bytes = function(count) {\n // TODO: deprecate this method, it is poorly named, add \"getString()\"\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.at = function(i) {\n return this.data.getUint8(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.setAt = function(i, b) {\n this.data.setUint8(i, b);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.DataBuffer.prototype.last = function() {\n return this.data.getUint8(this.write - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.DataBuffer.prototype.copy = function() {\n return new util.DataBuffer(this);\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.compact = function() {\n if(this.read > 0) {\n var src = new Uint8Array(this.data.buffer, this.read);\n var dst = new Uint8Array(src.byteLength);\n dst.set(src);\n this.data = new DataView(dst);\n this.write -= this.read;\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.clear = function() {\n this.data = new DataView(new ArrayBuffer(0));\n this.read = this.write = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.truncate = function(count) {\n this.write = Math.max(0, this.length() - count);\n this.read = Math.min(this.read, this.write);\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.DataBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.byteLength; ++i) {\n var b = this.data.getUint8(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a string, using the given encoding. If no\n * encoding is given, 'utf8' (UTF-8) is used.\n *\n * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',\n * 'base64' (default: 'utf8').\n *\n * @return a string representation of the bytes in this buffer.\n */\nutil.DataBuffer.prototype.toString = function(encoding) {\n var view = new Uint8Array(this.data, this.read, this.length());\n encoding = encoding || 'utf8';\n\n // encode to string\n if(encoding === 'binary' || encoding === 'raw') {\n return util.binary.raw.encode(view);\n }\n if(encoding === 'hex') {\n return util.binary.hex.encode(view);\n }\n if(encoding === 'base64') {\n return util.binary.base64.encode(view);\n }\n\n // decode to text\n if(encoding === 'utf8') {\n return util.text.utf8.decode(view);\n }\n if(encoding === 'utf16') {\n return util.text.utf16.decode(view);\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n};\n\n/** End Buffer w/UInt8Array backing */\n\n/**\n * Creates a buffer that stores bytes. A value may be given to populate the\n * buffer with data. This value can either be string of encoded bytes or a\n * regular string of characters. When passing a string of binary encoded\n * bytes, the encoding `raw` should be given. This is also the default. When\n * passing a string of characters, the encoding `utf8` should be given.\n *\n * @param [input] a string with encoded bytes to store in the buffer.\n * @param [encoding] (default: 'raw', other: 'utf8').\n */\nutil.createBuffer = function(input, encoding) {\n // TODO: deprecate, use new ByteBuffer() instead\n encoding = encoding || 'raw';\n if(input !== undefined && encoding === 'utf8') {\n input = util.encodeUtf8(input);\n }\n return new util.ByteBuffer(input);\n};\n\n/**\n * Fills a string with a particular value. If you want the string to be a byte\n * string, pass in String.fromCharCode(theByte).\n *\n * @param c the character to fill the string with, use String.fromCharCode\n * to fill the string with a byte value.\n * @param n the number of characters of value c to fill with.\n *\n * @return the filled string.\n */\nutil.fillString = function(c, n) {\n var s = '';\n while(n > 0) {\n if(n & 1) {\n s += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n return s;\n};\n\n/**\n * Performs a per byte XOR between two byte strings and returns the result as a\n * string of bytes.\n *\n * @param s1 first string of bytes.\n * @param s2 second string of bytes.\n * @param n the number of bytes to XOR.\n *\n * @return the XOR'd result.\n */\nutil.xorBytes = function(s1, s2, n) {\n var s3 = '';\n var b = '';\n var t = '';\n var i = 0;\n var c = 0;\n for(; n > 0; --n, ++i) {\n b = s1.charCodeAt(i) ^ s2.charCodeAt(i);\n if(c >= 10) {\n s3 += t;\n t = '';\n c = 0;\n }\n t += String.fromCharCode(b);\n ++c;\n }\n s3 += t;\n return s3;\n};\n\n/**\n * Converts a hex string into a 'binary' encoded string of bytes.\n *\n * @param hex the hexadecimal string to convert.\n *\n * @return the binary-encoded string of bytes.\n */\nutil.hexToBytes = function(hex) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.decode instead.\"\n var rval = '';\n var i = 0;\n if(hex.length & 1 == 1) {\n // odd number of characters, convert first character alone\n i = 1;\n rval += String.fromCharCode(parseInt(hex[0], 16));\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n }\n return rval;\n};\n\n/**\n * Converts a 'binary' encoded string of bytes to hex.\n *\n * @param bytes the byte string to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.bytesToHex = function(bytes) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.encode instead.\"\n return util.createBuffer(bytes).toHex();\n};\n\n/**\n * Converts an 32-bit integer to 4-big-endian byte string.\n *\n * @param i the integer.\n *\n * @return the byte string.\n */\nutil.int32ToBytes = function(i) {\n return (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n// base64 characters, reverse mapping\nvar _base64 =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar _base64Idx = [\n/*43 -43 = 0*/\n/*'+', 1, 2, 3,'/' */\n 62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n -1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n -1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\n// base58 characters (Bitcoin alphabet)\nvar _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Base64 encodes a 'binary' encoded string of bytes.\n *\n * @param input the binary encoded string of bytes to base64-encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output.\n */\nutil.encode64 = function(input, maxline) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.encode instead.\"\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Base64 decodes a string into a 'binary' encoded string of bytes.\n *\n * @param input the base64-encoded input.\n *\n * @return the binary encoded string.\n */\nutil.decode64 = function(input) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.decode instead.\"\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n var output = '';\n var enc1, enc2, enc3, enc4;\n var i = 0;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));\n if(enc4 !== 64) {\n // decoded 3 bytes\n output += String.fromCharCode(((enc3 & 3) << 6) | enc4);\n }\n }\n }\n\n return output;\n};\n\n/**\n * Encodes the given string of characters (a standard JavaScript\n * string) as a binary encoded string where the bytes represent\n * a UTF-8 encoded string of characters. Non-ASCII characters will be\n * encoded as multiple bytes according to UTF-8.\n *\n * @param str a standard string of characters to encode.\n *\n * @return the binary encoded string.\n */\nutil.encodeUtf8 = function(str) {\n return unescape(encodeURIComponent(str));\n};\n\n/**\n * Decodes a binary encoded string that contains bytes that\n * represent a UTF-8 encoded string of characters -- into a\n * string of characters (a standard JavaScript string).\n *\n * @param str the binary encoded string to decode.\n *\n * @return the resulting standard string of characters.\n */\nutil.decodeUtf8 = function(str) {\n return decodeURIComponent(escape(str));\n};\n\n// binary encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.binary = {\n raw: {},\n hex: {},\n base64: {},\n base58: {},\n baseN : {\n encode: baseN.encode,\n decode: baseN.decode\n }\n};\n\n/**\n * Encodes a Uint8Array as a binary-encoded string. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param bytes the Uint8Array to encode.\n *\n * @return the binary-encoded string.\n */\nutil.binary.raw.encode = function(bytes) {\n return String.fromCharCode.apply(null, bytes);\n};\n\n/**\n * Decodes a binary-encoded string to a Uint8Array. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param str the binary-encoded string to decode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.raw.decode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or\n * ByteBuffer as a string of hexadecimal characters.\n *\n * @param bytes the bytes to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.binary.hex.encode = util.bytesToHex;\n\n/**\n * Decodes a hex-encoded string to a Uint8Array.\n *\n * @param hex the hexadecimal string to convert.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.hex.decode = function(hex, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(hex.length / 2));\n }\n offset = offset || 0;\n var i = 0, j = offset;\n if(hex.length & 1) {\n // odd number of characters, convert first character alone\n i = 1;\n out[j++] = parseInt(hex[0], 16);\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n out[j++] = parseInt(hex.substr(i, 2), 16);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Base64-encodes a Uint8Array.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output string.\n */\nutil.binary.base64.encode = function(input, maxline) {\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.byteLength) {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Decodes a base64-encoded string to a Uint8Array.\n *\n * @param input the base64-encoded input string.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.base64.decode = function(input, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n }\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n offset = offset || 0;\n var enc1, enc2, enc3, enc4;\n var i = 0, j = offset;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n out[j++] = (enc1 << 2) | (enc2 >> 4);\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);\n if(enc4 !== 64) {\n // decoded 3 bytes\n out[j++] = ((enc3 & 3) << 6) | enc4;\n }\n }\n }\n\n // make sure result is the exact decoded length\n return output ? (j - offset) : out.subarray(0, j);\n};\n\n// add support for base58 encoding/decoding with Bitcoin alphabet\nutil.binary.base58.encode = function(input, maxline) {\n return util.binary.baseN.encode(input, _base58, maxline);\n};\nutil.binary.base58.decode = function(input, maxline) {\n return util.binary.baseN.decode(input, _base58, maxline);\n};\n\n// text encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.text = {\n utf8: {},\n utf16: {}\n};\n\n/**\n * Encodes the given string as UTF-8 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf8.encode = function(str, output, offset) {\n str = util.encodeUtf8(str);\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-8 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf8.decode = function(bytes) {\n return util.decodeUtf8(String.fromCharCode.apply(null, bytes));\n};\n\n/**\n * Encodes the given string as UTF-16 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf16.encode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length * 2);\n }\n var view = new Uint16Array(out.buffer);\n offset = offset || 0;\n var j = offset;\n var k = offset;\n for(var i = 0; i < str.length; ++i) {\n view[k++] = str.charCodeAt(i);\n j += 2;\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-16 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf16.decode = function(bytes) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n};\n\n/**\n * Deflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true to return only raw deflate data, false to include zlib\n * header and trailer.\n *\n * @return the deflated data as a string.\n */\nutil.deflate = function(api, bytes, raw) {\n bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);\n\n // strip zlib header and trailer if necessary\n if(raw) {\n // zlib header is 2 bytes (CMF,FLG) where FLG indicates that\n // there is a 4-byte DICT (alder-32) block before the data if\n // its 5th bit is set\n var start = 2;\n var flg = bytes.charCodeAt(1);\n if(flg & 0x20) {\n start = 6;\n }\n // zlib trailer is 4 bytes of adler-32\n bytes = bytes.substring(start, bytes.length - 4);\n }\n\n return bytes;\n};\n\n/**\n * Inflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true if the incoming data has no zlib header or trailer and is\n * raw DEFLATE data.\n *\n * @return the inflated data as a string, null on error.\n */\nutil.inflate = function(api, bytes, raw) {\n // TODO: add zlib header and trailer if necessary/possible\n var rval = api.inflate(util.encode64(bytes)).rval;\n return (rval === null) ? null : util.decode64(rval);\n};\n\n/**\n * Sets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param obj the storage object, null to remove.\n */\nvar _setStorageObject = function(api, id, obj) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n var rval;\n if(obj === null) {\n rval = api.removeItem(id);\n } else {\n // json-encode and base64-encode object\n obj = util.encode64(JSON.stringify(obj));\n rval = api.setItem(id, obj);\n }\n\n // handle potential flash error\n if(typeof(rval) !== 'undefined' && rval.rval !== true) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n};\n\n/**\n * Gets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n *\n * @return the storage object entry or null if none exists.\n */\nvar _getStorageObject = function(api, id) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n // get the existing entry\n var rval = api.getItem(id);\n\n /* Note: We check api.init because we can't do (api == localStorage)\n on IE because of \"Class doesn't support Automation\" exception. Only\n the flash api has an init method so this works too, but we need a\n better solution in the future. */\n\n // flash returns item wrapped in an object, handle special case\n if(api.init) {\n if(rval.rval === null) {\n if(rval.error) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n // no error, but also no item\n rval = null;\n } else {\n rval = rval.rval;\n }\n }\n\n // handle decoding\n if(rval !== null) {\n // base64-decode and json-decode data\n rval = JSON.parse(util.decode64(rval));\n }\n\n return rval;\n};\n\n/**\n * Stores an item in local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n */\nvar _setItem = function(api, id, key, data) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj === null) {\n // create a new storage object\n obj = {};\n }\n // update key\n obj[key] = data;\n\n // set storage object\n _setStorageObject(api, id, obj);\n};\n\n/**\n * Gets an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n *\n * @return the item.\n */\nvar _getItem = function(api, id, key) {\n // get storage object\n var rval = _getStorageObject(api, id);\n if(rval !== null) {\n // return data at key\n rval = (key in rval) ? rval[key] : null;\n }\n\n return rval;\n};\n\n/**\n * Removes an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n */\nvar _removeItem = function(api, id, key) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj !== null && key in obj) {\n // remove key\n delete obj[key];\n\n // see if entry has no keys remaining\n var empty = true;\n for(var prop in obj) {\n empty = false;\n break;\n }\n if(empty) {\n // remove entry entirely if no keys are left\n obj = null;\n }\n\n // set storage object\n _setStorageObject(api, id, obj);\n }\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n */\nvar _clearItems = function(api, id) {\n _setStorageObject(api, id, null);\n};\n\n/**\n * Calls a storage function.\n *\n * @param func the function to call.\n * @param args the arguments for the function.\n * @param location the location argument.\n *\n * @return the return value from the function.\n */\nvar _callStorageFunction = function(func, args, location) {\n var rval = null;\n\n // default storage types\n if(typeof(location) === 'undefined') {\n location = ['web', 'flash'];\n }\n\n // apply storage types in order of preference\n var type;\n var done = false;\n var exception = null;\n for(var idx in location) {\n type = location[idx];\n try {\n if(type === 'flash' || type === 'both') {\n if(args[0] === null) {\n throw new Error('Flash local storage not available.');\n }\n rval = func.apply(this, args);\n done = (type === 'flash');\n }\n if(type === 'web' || type === 'both') {\n args[0] = localStorage;\n rval = func.apply(this, args);\n done = true;\n }\n } catch(ex) {\n exception = ex;\n }\n if(done) {\n break;\n }\n }\n\n if(!done) {\n throw exception;\n }\n\n return rval;\n};\n\n/**\n * Stores an item on local disk.\n *\n * The available types of local storage include 'flash', 'web', and 'both'.\n *\n * The type 'flash' refers to flash local storage (SharedObject). In order\n * to use flash local storage, the 'api' parameter must be valid. The type\n * 'web' refers to WebStorage, if supported by the browser. The type 'both'\n * refers to storing using both 'flash' and 'web', not just one or the\n * other.\n *\n * The location array should list the storage types to use in order of\n * preference:\n *\n * ['flash']: flash only storage\n * ['web']: web only storage\n * ['both']: try to store in both\n * ['flash','web']: store in flash first, but if not available, 'web'\n * ['web','flash']: store in web first, but if not available, 'flash'\n *\n * The location array defaults to: ['web', 'flash']\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n * @param location an array with the preferred types of storage to use.\n */\nutil.setItem = function(api, id, key, data, location) {\n _callStorageFunction(_setItem, arguments, location);\n};\n\n/**\n * Gets an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n *\n * @return the item.\n */\nutil.getItem = function(api, id, key, location) {\n return _callStorageFunction(_getItem, arguments, location);\n};\n\n/**\n * Removes an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n */\nutil.removeItem = function(api, id, key, location) {\n _callStorageFunction(_removeItem, arguments, location);\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface if flash is available.\n * @param id the storage ID to use.\n * @param location an array with the preferred types of storage to use.\n */\nutil.clearItems = function(api, id, location) {\n _callStorageFunction(_clearItems, arguments, location);\n};\n\n/**\n * Check if an object is empty.\n *\n * Taken from:\n * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937\n *\n * @param object the object to check.\n */\nutil.isEmpty = function(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Format with simple printf-style interpolation.\n *\n * %%: literal '%'\n * %s,%o: convert next argument into a string.\n *\n * @param format the string to format.\n * @param ... arguments to interpolate into the format string.\n */\nutil.format = function(format) {\n var re = /%./g;\n // current match\n var match;\n // current part\n var part;\n // current arg index\n var argi = 0;\n // collected parts to recombine later\n var parts = [];\n // last index found\n var last = 0;\n // loop while matches remain\n while((match = re.exec(format))) {\n part = format.substring(last, re.lastIndex - 2);\n // don't add empty strings (ie, parts between %s%s)\n if(part.length > 0) {\n parts.push(part);\n }\n last = re.lastIndex;\n // switch on % code\n var code = match[0][1];\n switch(code) {\n case 's':\n case 'o':\n // check if enough arguments were given\n if(argi < arguments.length) {\n parts.push(arguments[argi++ + 1]);\n } else {\n parts.push('');\n }\n break;\n // FIXME: do proper formating for numbers, etc\n //case 'f':\n //case 'd':\n case '%':\n parts.push('%');\n break;\n default:\n parts.push('<%' + code + '?>');\n }\n }\n // add trailing part of format string\n parts.push(format.substring(last));\n return parts.join('');\n};\n\n/**\n * Formats a number.\n *\n * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/\n */\nutil.formatNumber = function(number, decimals, dec_point, thousands_sep) {\n // http://kevin.vanzonneveld.net\n // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n // + bugfix by: Michael White (http://crestidg.com)\n // + bugfix by: Benjamin Lupton\n // + bugfix by: Allan Jensen (http://www.winternet.no)\n // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // * example 1: number_format(1234.5678, 2, '.', '');\n // * returns 1: 1234.57\n\n var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;\n var d = dec_point === undefined ? ',' : dec_point;\n var t = thousands_sep === undefined ?\n '.' : thousands_sep, s = n < 0 ? '-' : '';\n var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';\n var j = (i.length > 3) ? i.length % 3 : 0;\n return s + (j ? i.substr(0, j) + t : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + t) +\n (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n};\n\n/**\n * Formats a byte size.\n *\n * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/\n */\nutil.formatSize = function(size) {\n if(size >= 1073741824) {\n size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';\n } else if(size >= 1048576) {\n size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';\n } else if(size >= 1024) {\n size = util.formatNumber(size / 1024, 0) + ' KiB';\n } else {\n size = util.formatNumber(size, 0) + ' bytes';\n }\n return size;\n};\n\n/**\n * Converts an IPv4 or IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv4 or IPv6 address to convert.\n *\n * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't\n * be parsed.\n */\nutil.bytesFromIP = function(ip) {\n if(ip.indexOf('.') !== -1) {\n return util.bytesFromIPv4(ip);\n }\n if(ip.indexOf(':') !== -1) {\n return util.bytesFromIPv6(ip);\n }\n return null;\n};\n\n/**\n * Converts an IPv4 string representation into bytes (in network order).\n *\n * @param ip the IPv4 address to convert.\n *\n * @return the 4-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv4 = function(ip) {\n ip = ip.split('.');\n if(ip.length !== 4) {\n return null;\n }\n var b = util.createBuffer();\n for(var i = 0; i < ip.length; ++i) {\n var num = parseInt(ip[i], 10);\n if(isNaN(num)) {\n return null;\n }\n b.putByte(num);\n }\n return b.getBytes();\n};\n\n/**\n * Converts an IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv6 address to convert.\n *\n * @return the 16-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv6 = function(ip) {\n var blanks = 0;\n ip = ip.split(':').filter(function(e) {\n if(e.length === 0) ++blanks;\n return true;\n });\n var zeros = (8 - ip.length + blanks) * 2;\n var b = util.createBuffer();\n for(var i = 0; i < 8; ++i) {\n if(!ip[i] || ip[i].length === 0) {\n b.fillWithByte(0, zeros);\n zeros = 0;\n continue;\n }\n var bytes = util.hexToBytes(ip[i]);\n if(bytes.length < 2) {\n b.putByte(0);\n }\n b.putBytes(bytes);\n }\n return b.getBytes();\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation or 16-bytes into\n * an IPv6 string representation. The bytes must be in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,\n * respectively, are given, otherwise null.\n */\nutil.bytesToIP = function(bytes) {\n if(bytes.length === 4) {\n return util.bytesToIPv4(bytes);\n }\n if(bytes.length === 16) {\n return util.bytesToIPv6(bytes);\n }\n return null;\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv4 = function(bytes) {\n if(bytes.length !== 4) {\n return null;\n }\n var ip = [];\n for(var i = 0; i < bytes.length; ++i) {\n ip.push(bytes.charCodeAt(i));\n }\n return ip.join('.');\n};\n\n/**\n * Converts 16-bytes into an IPv16 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv16 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv6 = function(bytes) {\n if(bytes.length !== 16) {\n return null;\n }\n var ip = [];\n var zeroGroups = [];\n var zeroMaxGroup = 0;\n for(var i = 0; i < bytes.length; i += 2) {\n var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);\n // canonicalize zero representation\n while(hex[0] === '0' && hex !== '0') {\n hex = hex.substr(1);\n }\n if(hex === '0') {\n var last = zeroGroups[zeroGroups.length - 1];\n var idx = ip.length;\n if(!last || idx !== last.end + 1) {\n zeroGroups.push({start: idx, end: idx});\n } else {\n last.end = idx;\n if((last.end - last.start) >\n (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {\n zeroMaxGroup = zeroGroups.length - 1;\n }\n }\n }\n ip.push(hex);\n }\n if(zeroGroups.length > 0) {\n var group = zeroGroups[zeroMaxGroup];\n // only shorten group of length > 0\n if(group.end - group.start > 0) {\n ip.splice(group.start, group.end - group.start + 1, '');\n if(group.start === 0) {\n ip.unshift('');\n }\n if(group.end === 7) {\n ip.push('');\n }\n }\n }\n return ip.join(':');\n};\n\n/**\n * Estimates the number of processes that can be run concurrently. If\n * creating Web Workers, keep in mind that the main JavaScript process needs\n * its own core.\n *\n * @param options the options to use:\n * update true to force an update (not use the cached value).\n * @param callback(err, max) called once the operation completes.\n */\nutil.estimateCores = function(options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n if('cores' in util && !options.update) {\n return callback(null, util.cores);\n }\n if(typeof navigator !== 'undefined' &&\n 'hardwareConcurrency' in navigator &&\n navigator.hardwareConcurrency > 0) {\n util.cores = navigator.hardwareConcurrency;\n return callback(null, util.cores);\n }\n if(typeof Worker === 'undefined') {\n // workers not available\n util.cores = 1;\n return callback(null, util.cores);\n }\n if(typeof Blob === 'undefined') {\n // can't estimate, default to 2\n util.cores = 2;\n return callback(null, util.cores);\n }\n\n // create worker concurrency estimation code as blob\n var blobUrl = URL.createObjectURL(new Blob(['(',\n function() {\n self.addEventListener('message', function(e) {\n // run worker for 4 ms\n var st = Date.now();\n var et = st + 4;\n while(Date.now() < et);\n self.postMessage({st: st, et: et});\n });\n }.toString(),\n ')()'], {type: 'application/javascript'}));\n\n // take 5 samples using 16 workers\n sample([], 5, 16);\n\n function sample(max, samples, numWorkers) {\n if(samples === 0) {\n // get overlap average\n var avg = Math.floor(max.reduce(function(avg, x) {\n return avg + x;\n }, 0) / max.length);\n util.cores = Math.max(1, avg);\n URL.revokeObjectURL(blobUrl);\n return callback(null, util.cores);\n }\n map(numWorkers, function(err, results) {\n max.push(reduce(numWorkers, results));\n sample(max, samples - 1, numWorkers);\n });\n }\n\n function map(numWorkers, callback) {\n var workers = [];\n var results = [];\n for(var i = 0; i < numWorkers; ++i) {\n var worker = new Worker(blobUrl);\n worker.addEventListener('message', function(e) {\n results.push(e.data);\n if(results.length === numWorkers) {\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].terminate();\n }\n callback(null, results);\n }\n });\n workers.push(worker);\n }\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].postMessage(i);\n }\n }\n\n function reduce(numWorkers, results) {\n // find overlapping time windows\n var overlaps = [];\n for(var n = 0; n < numWorkers; ++n) {\n var r1 = results[n];\n var overlap = overlaps[n] = [];\n for(var i = 0; i < numWorkers; ++i) {\n if(n === i) {\n continue;\n }\n var r2 = results[i];\n if((r1.st > r2.st && r1.st < r2.et) ||\n (r2.st > r1.st && r2.st < r1.et)) {\n overlap.push(i);\n }\n }\n }\n // get maximum overlaps ... don't include overlapping worker itself\n // as the main JS process was also being scheduled during the work and\n // would have to be subtracted from the estimate anyway\n return overlaps.reduce(function(max, overlap) {\n return Math.max(max, overlap.length);\n }, 0);\n }\n};\n","/**\n * Javascript implementation of X.509 and related components (such as\n * Certification Signing Requests) of a Public Key Infrastructure.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The ASN.1 representation of an X.509v3 certificate is as follows\n * (see RFC 2459):\n *\n * Certificate ::= SEQUENCE {\n * tbsCertificate TBSCertificate,\n * signatureAlgorithm AlgorithmIdentifier,\n * signatureValue BIT STRING\n * }\n *\n * TBSCertificate ::= SEQUENCE {\n * version [0] EXPLICIT Version DEFAULT v1,\n * serialNumber CertificateSerialNumber,\n * signature AlgorithmIdentifier,\n * issuer Name,\n * validity Validity,\n * subject Name,\n * subjectPublicKeyInfo SubjectPublicKeyInfo,\n * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * extensions [3] EXPLICIT Extensions OPTIONAL\n * -- If present, version shall be v3\n * }\n *\n * Version ::= INTEGER { v1(0), v2(1), v3(2) }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * Name ::= CHOICE {\n * // only one possible choice for now\n * RDNSequence\n * }\n *\n * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\n *\n * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue\n *\n * AttributeTypeAndValue ::= SEQUENCE {\n * type AttributeType,\n * value AttributeValue\n * }\n * AttributeType ::= OBJECT IDENTIFIER\n * AttributeValue ::= ANY DEFINED BY AttributeType\n *\n * Validity ::= SEQUENCE {\n * notBefore Time,\n * notAfter Time\n * }\n *\n * Time ::= CHOICE {\n * utcTime UTCTime,\n * generalTime GeneralizedTime\n * }\n *\n * UniqueIdentifier ::= BIT STRING\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension\n *\n * Extension ::= SEQUENCE {\n * extnID OBJECT IDENTIFIER,\n * critical BOOLEAN DEFAULT FALSE,\n * extnValue OCTET STRING\n * }\n *\n * The only key algorithm currently supported for PKI is RSA.\n *\n * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.\n *\n * PKCS#10 v1.7 describes certificate signing requests:\n *\n * CertificationRequestInfo:\n *\n * CertificationRequestInfo ::= SEQUENCE {\n * version INTEGER { v1(0) } (v1,...),\n * subject Name,\n * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},\n * attributes [0] Attributes{{ CRIAttributes }}\n * }\n *\n * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}\n *\n * CRIAttributes ATTRIBUTE ::= {\n * ... -- add any locally defined attributes here -- }\n *\n * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {\n * type ATTRIBUTE.&id({IOSet}),\n * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})\n * }\n *\n * CertificationRequest ::= SEQUENCE {\n * certificationRequestInfo CertificationRequestInfo,\n * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},\n * signature BIT STRING\n * }\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./mgf');\nrequire('./oids');\nrequire('./pem');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\nvar oids = pki.oids;\n\n// short name OID mappings\nvar _shortNames = {};\n_shortNames['CN'] = oids['commonName'];\n_shortNames['commonName'] = 'CN';\n_shortNames['C'] = oids['countryName'];\n_shortNames['countryName'] = 'C';\n_shortNames['L'] = oids['localityName'];\n_shortNames['localityName'] = 'L';\n_shortNames['ST'] = oids['stateOrProvinceName'];\n_shortNames['stateOrProvinceName'] = 'ST';\n_shortNames['O'] = oids['organizationName'];\n_shortNames['organizationName'] = 'O';\n_shortNames['OU'] = oids['organizationalUnitName'];\n_shortNames['organizationalUnitName'] = 'OU';\n_shortNames['E'] = oids['emailAddress'];\n_shortNames['emailAddress'] = 'E';\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator;\n\n// validator for an X.509v3 certificate\nvar x509CertificateValidator = {\n name: 'Certificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'tbsCertificate',\n value: [{\n name: 'Certificate.TBSCertificate.version',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.version.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certVersion'\n }]\n }, {\n name: 'Certificate.TBSCertificate.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certSerialNumber'\n }, {\n name: 'Certificate.TBSCertificate.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate.signature.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certinfoSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certinfoSignatureParams'\n }]\n }, {\n name: 'Certificate.TBSCertificate.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certIssuer'\n }, {\n name: 'Certificate.TBSCertificate.validity',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n // Note: UTC and generalized times may both appear so the capture\n // names are based on their detected order, the names used below\n // are only for the common case, which validity time really means\n // \"notBefore\" and which means \"notAfter\" will be determined by order\n value: [{\n // notBefore (Time) (UTC time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity1UTCTime'\n }, {\n // notBefore (Time) (generalized time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity2GeneralizedTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity3UTCTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity4GeneralizedTime'\n }]\n }, {\n // Name (subject) (RDNSequence)\n name: 'Certificate.TBSCertificate.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n // issuerUniqueID (optional)\n name: 'Certificate.TBSCertificate.issuerUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.issuerUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certIssuerUniqueId'\n }]\n }, {\n // subjectUniqueID (optional)\n name: 'Certificate.TBSCertificate.subjectUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.subjectUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certSubjectUniqueId'\n }]\n }, {\n // Extensions (optional)\n name: 'Certificate.TBSCertificate.extensions',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n constructed: true,\n captureAsn1: 'certExtensions',\n optional: true\n }]\n }, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'Certificate.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'Certificate.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certSignatureParams'\n }]\n }, {\n // SignatureValue\n name: 'Certificate.signatureValue',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'certSignature'\n }]\n};\n\nvar rsassaPssParameterValidator = {\n name: 'rsapss',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'hashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }, {\n name: 'rsapss.maskGenAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenOid'\n }, {\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenHashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }]\n }, {\n name: 'rsapss.saltLength',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n optional: true,\n value: [{\n name: 'rsapss.saltLength.saltLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'saltLength'\n }]\n }, {\n name: 'rsapss.trailerField',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n optional: true,\n value: [{\n name: 'rsapss.trailer.trailer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'trailer'\n }]\n }]\n};\n\n// validator for a CertificationRequestInfo structure\nvar certificationRequestInfoValidator = {\n name: 'CertificationRequestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfo',\n value: [{\n name: 'CertificationRequestInfo.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certificationRequestInfoVersion'\n }, {\n // Name (subject) (RDNSequence)\n name: 'CertificationRequestInfo.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfoSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'certificationRequestInfoAttributes',\n value: [{\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertificationRequestInfo.attributes.type',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false\n }, {\n name: 'CertificationRequestInfo.attributes.value',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true\n }]\n }]\n }]\n};\n\n// validator for a CertificationRequest structure\nvar certificationRequestValidator = {\n name: 'CertificationRequest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'csr',\n value: [\n certificationRequestInfoValidator, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'CertificationRequest.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'CertificationRequest.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'csrSignatureOid'\n }, {\n name: 'CertificationRequest.signatureAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'csrSignatureParams'\n }]\n }, {\n // signature\n name: 'CertificationRequest.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'csrSignature'\n }\n ]\n};\n\n/**\n * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName\n * sets into an array with objects that have type and value properties.\n *\n * @param rdn the RDNSequence to convert.\n * @param md a message digest to append type and value to if provided.\n */\npki.RDNAttributesAsArray = function(rdn, md) {\n var rval = [];\n\n // each value in 'rdn' in is a SET of RelativeDistinguishedName\n var set, attr, obj;\n for(var si = 0; si < rdn.value.length; ++si) {\n // get the RelativeDistinguishedName set\n set = rdn.value[si];\n\n // each value in the SET is an AttributeTypeAndValue sequence\n // containing first a type (an OID) and second a value (defined by\n // the OID)\n for(var i = 0; i < set.value.length; ++i) {\n obj = {};\n attr = set.value[i];\n obj.type = asn1.derToOid(attr.value[0].value);\n obj.value = attr.value[1].value;\n obj.valueTagClass = attr.value[1].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n if(md) {\n md.update(obj.type);\n md.update(obj.value);\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Converts ASN.1 CRIAttributes into an array with objects that have type and\n * value properties.\n *\n * @param attributes the CRIAttributes to convert.\n */\npki.CRIAttributesAsArray = function(attributes) {\n var rval = [];\n\n // each value in 'attributes' in is a SEQUENCE with an OID and a SET\n for(var si = 0; si < attributes.length; ++si) {\n // get the attribute sequence\n var seq = attributes[si];\n\n // each value in the SEQUENCE containing first a type (an OID) and\n // second a set of values (defined by the OID)\n var type = asn1.derToOid(seq.value[0].value);\n var values = seq.value[1].value;\n for(var vi = 0; vi < values.length; ++vi) {\n var obj = {};\n obj.type = type;\n obj.value = values[vi].value;\n obj.valueTagClass = values[vi].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n // parse extensions\n if(obj.type === oids.extensionRequest) {\n obj.extensions = [];\n for(var ei = 0; ei < obj.value.length; ++ei) {\n obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));\n }\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Gets an issuer or subject attribute from its name, type, or short name.\n *\n * @param obj the issuer or subject object.\n * @param options a short name string or an object with:\n * shortName the short name for the attribute.\n * name the name for the attribute.\n * type the type for the attribute.\n *\n * @return the attribute.\n */\nfunction _getAttribute(obj, options) {\n if(typeof options === 'string') {\n options = {shortName: options};\n }\n\n var rval = null;\n var attr;\n for(var i = 0; rval === null && i < obj.attributes.length; ++i) {\n attr = obj.attributes[i];\n if(options.type && options.type === attr.type) {\n rval = attr;\n } else if(options.name && options.name === attr.name) {\n rval = attr;\n } else if(options.shortName && options.shortName === attr.shortName) {\n rval = attr;\n }\n }\n return rval;\n}\n\n/**\n * Converts signature parameters from ASN.1 structure.\n *\n * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had\n * no parameters.\n *\n * RSASSA-PSS-params ::= SEQUENCE {\n * hashAlgorithm [0] HashAlgorithm DEFAULT\n * sha1Identifier,\n * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT\n * mgf1SHA1Identifier,\n * saltLength [2] INTEGER DEFAULT 20,\n * trailerField [3] INTEGER DEFAULT 1\n * }\n *\n * HashAlgorithm ::= AlgorithmIdentifier\n *\n * MaskGenAlgorithm ::= AlgorithmIdentifier\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * @param oid The OID specifying the signature algorithm\n * @param obj The ASN.1 structure holding the parameters\n * @param fillDefaults Whether to use return default values where omitted\n * @return signature parameter object\n */\nvar _readSignatureParameters = function(oid, obj, fillDefaults) {\n var params = {};\n\n if(oid !== oids['RSASSA-PSS']) {\n return params;\n }\n\n if(fillDefaults) {\n params = {\n hash: {\n algorithmOid: oids['sha1']\n },\n mgf: {\n algorithmOid: oids['mgf1'],\n hash: {\n algorithmOid: oids['sha1']\n }\n },\n saltLength: 20\n };\n }\n\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {\n var error = new Error('Cannot read RSASSA-PSS parameter block.');\n error.errors = errors;\n throw error;\n }\n\n if(capture.hashOid !== undefined) {\n params.hash = params.hash || {};\n params.hash.algorithmOid = asn1.derToOid(capture.hashOid);\n }\n\n if(capture.maskGenOid !== undefined) {\n params.mgf = params.mgf || {};\n params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);\n params.mgf.hash = params.mgf.hash || {};\n params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);\n }\n\n if(capture.saltLength !== undefined) {\n params.saltLength = capture.saltLength.charCodeAt(0);\n }\n\n return params;\n};\n\n/**\n * Create signature digest for OID.\n *\n * @param options\n * signatureOid: the OID specifying the signature algorithm.\n * type: a human readable type for error messages\n * @return a created md instance. throws if unknown oid.\n */\nvar _createSignatureDigest = function(options) {\n switch(oids[options.signatureOid]) {\n case 'sha1WithRSAEncryption':\n // deprecated alias\n case 'sha1WithRSASignature':\n return forge.md.sha1.create();\n case 'md5WithRSAEncryption':\n return forge.md.md5.create();\n case 'sha256WithRSAEncryption':\n return forge.md.sha256.create();\n case 'sha384WithRSAEncryption':\n return forge.md.sha384.create();\n case 'sha512WithRSAEncryption':\n return forge.md.sha512.create();\n case 'RSASSA-PSS':\n return forge.md.sha256.create();\n default:\n var error = new Error(\n 'Could not compute ' + options.type + ' digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = options.signatureOid;\n throw error;\n }\n};\n\n/**\n * Verify signature on certificate or CSR.\n *\n * @param options:\n * certificate the certificate or CSR to verify.\n * md the signature digest.\n * signature the signature\n * @return a created md instance. throws if unknown oid.\n */\nvar _verifySignature = function(options) {\n var cert = options.certificate;\n var scheme;\n\n switch(cert.signatureOid) {\n case oids.sha1WithRSAEncryption:\n // deprecated alias\n case oids.sha1WithRSASignature:\n /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = cert.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[cert.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = cert.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[cert.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported RSASSA-PSS hash function.');\n error.oid = cert.signatureParameters.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n scheme = forge.pss.create(\n forge.md[hash].create(), mgf, cert.signatureParameters.saltLength\n );\n break;\n }\n\n // verify signature on cert using public key\n return cert.publicKey.verify(\n options.md.digest().getBytes(), options.signature, scheme\n );\n};\n\n/**\n * Converts an X.509 certificate from PEM format.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. This will scan the TBSCertificate part of the ASN.1\n * object while it is converted so it doesn't need to be converted back\n * to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certificate.\n */\npki.certificateFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error(\n 'Could not convert certificate from PEM; PEM header type ' +\n 'is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or \"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error(\n 'Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificateFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts an X.509 certificate to PEM format.\n *\n * @param cert the certificate.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certificate.\n */\npki.certificateToPem = function(cert, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE',\n body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key from PEM format.\n *\n * @param pem the PEM-formatted public key.\n *\n * @return the public key.\n */\npki.publicKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {\n var error = new Error('Could not convert public key from PEM; PEM header ' +\n 'type is not \"PUBLIC KEY\" or \"RSA PUBLIC KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert public key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.publicKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key to PEM format (using an RSAPublicKey).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToRSAPublicKeyPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Gets a fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.sha1).\n * [type] the type of fingerprint, such as 'RSAPublicKey',\n * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\npki.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.sha1.create();\n var type = options.type || 'RSAPublicKey';\n\n var bytes;\n switch(type) {\n case 'RSAPublicKey':\n bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();\n break;\n case 'SubjectPublicKeyInfo':\n bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();\n break;\n default:\n throw new Error('Unknown fingerprint type \"' + options.type + '\".');\n }\n\n // hash public key bytes\n md.start();\n md.update(bytes);\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from PEM format.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. This will scan the CertificationRequestInfo part of\n * the ASN.1 object while it is converted so it doesn't need to be converted\n * back to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE REQUEST') {\n var error = new Error('Could not convert certification request from PEM; ' +\n 'PEM header type is not \"CERTIFICATE REQUEST\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certification request from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificationRequestFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) to PEM format.\n *\n * @param csr the certification request.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certification request.\n */\npki.certificationRequestToPem = function(csr, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE REQUEST',\n body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Creates an empty X.509v3 RSA certificate.\n *\n * @return the certificate.\n */\npki.createCertificate = function() {\n var cert = {};\n cert.version = 0x02;\n cert.serialNumber = '00';\n cert.signatureOid = null;\n cert.signature = null;\n cert.siginfo = {};\n cert.siginfo.algorithmOid = null;\n cert.validity = {};\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n\n cert.issuer = {};\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = [];\n cert.issuer.hash = null;\n\n cert.subject = {};\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = [];\n cert.subject.hash = null;\n\n cert.extensions = [];\n cert.publicKey = null;\n cert.md = null;\n\n /**\n * Sets the subject of this certificate.\n *\n * @param attrs the array of subject attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setSubject = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.subject.attributes = attrs;\n delete cert.subject.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.subject.uniqueId = uniqueId;\n }\n cert.subject.hash = null;\n };\n\n /**\n * Sets the issuer of this certificate.\n *\n * @param attrs the array of issuer attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setIssuer = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.issuer.attributes = attrs;\n delete cert.issuer.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.issuer.uniqueId = uniqueId;\n }\n cert.issuer.hash = null;\n };\n\n /**\n * Sets the extensions of this certificate.\n *\n * @param exts the array of extensions to use.\n */\n cert.setExtensions = function(exts) {\n for(var i = 0; i < exts.length; ++i) {\n _fillMissingExtensionFields(exts[i], {cert: cert});\n }\n // set new extensions\n cert.extensions = exts;\n };\n\n /**\n * Gets an extension by its name or id.\n *\n * @param options the name to use or an object with:\n * name the name to use.\n * id the id to use.\n *\n * @return the extension or null if not found.\n */\n cert.getExtension = function(options) {\n if(typeof options === 'string') {\n options = {name: options};\n }\n\n var rval = null;\n var ext;\n for(var i = 0; rval === null && i < cert.extensions.length; ++i) {\n ext = cert.extensions[i];\n if(options.id && ext.id === options.id) {\n rval = ext;\n } else if(options.name && ext.name === options.name) {\n rval = ext;\n }\n }\n return rval;\n };\n\n /**\n * Signs this certificate using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n cert.sign = function(key, md) {\n // TODO: get signature OID from private key\n cert.md = md || forge.md.sha1.create();\n var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = cert.md.algorithm;\n throw error;\n }\n cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;\n\n // get TBSCertificate, convert to DER\n cert.tbsCertificate = pki.getTBSCertificate(cert);\n var bytes = asn1.toDer(cert.tbsCertificate);\n\n // digest and sign\n cert.md.update(bytes.getBytes());\n cert.signature = key.sign(cert.md);\n };\n\n /**\n * Attempts verify the signature on the passed certificate using this\n * certificate's public key.\n *\n * @param child the certificate to verify.\n *\n * @return true if verified, false if not.\n */\n cert.verify = function(child) {\n var rval = false;\n\n if(!cert.issued(child)) {\n var issuer = child.issuer;\n var subject = cert.subject;\n var error = new Error(\n 'The parent certificate did not issue the given child ' +\n 'certificate; the child certificate\\'s issuer does not match the ' +\n 'parent\\'s subject.');\n error.expectedIssuer = subject.attributes;\n error.actualIssuer = issuer.attributes;\n throw error;\n }\n\n var md = child.md;\n if(md === null) {\n // create digest for OID signature types\n md = _createSignatureDigest({\n signatureOid: child.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);\n var bytes = asn1.toDer(tbsCertificate);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: cert, md: md, signature: child.signature\n });\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's issuer matches the passed\n * certificate's subject. Note that no signature check is performed.\n *\n * @param parent the certificate to check.\n *\n * @return true if this certificate's issuer matches the passed certificate's\n * subject.\n */\n cert.isIssuer = function(parent) {\n var rval = false;\n\n var i = cert.issuer;\n var s = parent.subject;\n\n // compare hashes if present\n if(i.hash && s.hash) {\n rval = (i.hash === s.hash);\n } else if(i.attributes.length === s.attributes.length) {\n // all attributes are the same so issuer matches subject\n rval = true;\n var iattr, sattr;\n for(var n = 0; rval && n < i.attributes.length; ++n) {\n iattr = i.attributes[n];\n sattr = s.attributes[n];\n if(iattr.type !== sattr.type || iattr.value !== sattr.value) {\n // attribute mismatch\n rval = false;\n }\n }\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's subject matches the issuer of the\n * given certificate). Note that not signature check is performed.\n *\n * @param child the certificate to check.\n *\n * @return true if this certificate's subject matches the passed\n * certificate's issuer.\n */\n cert.issued = function(child) {\n return child.isIssuer(cert);\n };\n\n /**\n * Generates the subjectKeyIdentifier for this certificate as byte buffer.\n *\n * @return the subjectKeyIdentifier for this certificate as byte buffer.\n */\n cert.generateSubjectKeyIdentifier = function() {\n /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:\n\n (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the\n value of the BIT STRING subjectPublicKey (excluding the tag,\n length, and number of unused bits).\n\n (2) The keyIdentifier is composed of a four bit type field with\n the value 0100 followed by the least significant 60 bits of the\n SHA-1 hash of the value of the BIT STRING subjectPublicKey\n (excluding the tag, length, and number of unused bit string bits).\n */\n\n // skipping the tag, length, and number of unused bits is the same\n // as just using the RSAPublicKey (for RSA keys, which are the\n // only ones supported)\n return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});\n };\n\n /**\n * Verifies the subjectKeyIdentifier extension value for this certificate\n * against its public key. If no extension is found, false will be\n * returned.\n *\n * @return true if verified, false if not.\n */\n cert.verifySubjectKeyIdentifier = function() {\n var oid = oids['subjectKeyIdentifier'];\n for(var i = 0; i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.id === oid) {\n var ski = cert.generateSubjectKeyIdentifier().getBytes();\n return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);\n }\n }\n return false;\n };\n\n return cert;\n};\n\n/**\n * Converts an X.509v3 RSA certificate from an ASN.1 object.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1\n * object needs to be scanned before the cert object is created.\n *\n * @param obj the asn1 representation of an X.509v3 RSA certificate.\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certificate.\n */\npki.certificateFromAsn1 = function(obj, computeHash) {\n // validate certificate and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {\n var error = new Error('Cannot read X.509 certificate. ' +\n 'ASN.1 object is not an X509v3 Certificate.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certificate\n var cert = pki.createCertificate();\n cert.version = capture.certVersion ?\n capture.certVersion.charCodeAt(0) : 0;\n var serial = forge.util.createBuffer(capture.certSerialNumber);\n cert.serialNumber = serial.toHex();\n cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);\n cert.signatureParameters = _readSignatureParameters(\n cert.signatureOid, capture.certSignatureParams, true);\n cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);\n cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,\n capture.certinfoSignatureParams, false);\n cert.signature = capture.certSignature;\n\n var validity = [];\n if(capture.certValidity1UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));\n }\n if(capture.certValidity2GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity2GeneralizedTime));\n }\n if(capture.certValidity3UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));\n }\n if(capture.certValidity4GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity4GeneralizedTime));\n }\n if(validity.length > 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; more ' +\n 'than two times were provided in the certificate.');\n }\n if(validity.length < 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; they ' +\n 'were not provided as either UTCTime or GeneralizedTime.');\n }\n cert.validity.notBefore = validity[0];\n cert.validity.notAfter = validity[1];\n\n // keep TBSCertificate to preserve signature when exporting\n cert.tbsCertificate = capture.tbsCertificate;\n\n if(computeHash) {\n // create digest for OID signature type\n cert.md = _createSignatureDigest({\n signatureOid: cert.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var bytes = asn1.toDer(cert.tbsCertificate);\n cert.md.update(bytes.getBytes());\n }\n\n // handle issuer, build issuer message digest\n var imd = forge.md.sha1.create();\n var ibytes = asn1.toDer(capture.certIssuer);\n imd.update(ibytes.getBytes());\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);\n if(capture.certIssuerUniqueId) {\n cert.issuer.uniqueId = capture.certIssuerUniqueId;\n }\n cert.issuer.hash = imd.digest().toHex();\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n var sbytes = asn1.toDer(capture.certSubject);\n smd.update(sbytes.getBytes());\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);\n if(capture.certSubjectUniqueId) {\n cert.subject.uniqueId = capture.certSubjectUniqueId;\n }\n cert.subject.hash = smd.digest().toHex();\n\n // handle extensions\n if(capture.certExtensions) {\n cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);\n } else {\n cert.extensions = [];\n }\n\n // convert RSA public key from ASN.1\n cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n return cert;\n};\n\n/**\n * Converts an ASN.1 extensions object (with extension sequences as its\n * values) into an array of extension objects with types and values.\n *\n * Supported extensions:\n *\n * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }\n * KeyUsage ::= BIT STRING {\n * digitalSignature (0),\n * nonRepudiation (1),\n * keyEncipherment (2),\n * dataEncipherment (3),\n * keyAgreement (4),\n * keyCertSign (5),\n * cRLSign (6),\n * encipherOnly (7),\n * decipherOnly (8)\n * }\n *\n * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }\n * BasicConstraints ::= SEQUENCE {\n * cA BOOLEAN DEFAULT FALSE,\n * pathLenConstraint INTEGER (0..MAX) OPTIONAL\n * }\n *\n * subjectAltName EXTENSION ::= {\n * SYNTAX GeneralNames\n * IDENTIFIED BY id-ce-subjectAltName\n * }\n *\n * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName\n *\n * GeneralName ::= CHOICE {\n * otherName [0] INSTANCE OF OTHER-NAME,\n * rfc822Name [1] IA5String,\n * dNSName [2] IA5String,\n * x400Address [3] ORAddress,\n * directoryName [4] Name,\n * ediPartyName [5] EDIPartyName,\n * uniformResourceIdentifier [6] IA5String,\n * IPAddress [7] OCTET STRING,\n * registeredID [8] OBJECT IDENTIFIER\n * }\n *\n * OTHER-NAME ::= TYPE-IDENTIFIER\n *\n * EDIPartyName ::= SEQUENCE {\n * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,\n * partyName [1] DirectoryString {ub-name}\n * }\n *\n * @param exts the extensions ASN.1 with extension sequences to parse.\n *\n * @return the array.\n */\npki.certificateExtensionsFromAsn1 = function(exts) {\n var rval = [];\n for(var i = 0; i < exts.value.length; ++i) {\n // get extension sequence\n var extseq = exts.value[i];\n for(var ei = 0; ei < extseq.value.length; ++ei) {\n rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));\n }\n }\n\n return rval;\n};\n\n/**\n * Parses a single certificate extension from ASN.1.\n *\n * @param ext the extension in ASN.1 format.\n *\n * @return the parsed extension as an object.\n */\npki.certificateExtensionFromAsn1 = function(ext) {\n // an extension has:\n // [0] extnID OBJECT IDENTIFIER\n // [1] critical BOOLEAN DEFAULT FALSE\n // [2] extnValue OCTET STRING\n var e = {};\n e.id = asn1.derToOid(ext.value[0].value);\n e.critical = false;\n if(ext.value[1].type === asn1.Type.BOOLEAN) {\n e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);\n e.value = ext.value[2].value;\n } else {\n e.value = ext.value[1].value;\n }\n // if the oid is known, get its name\n if(e.id in oids) {\n e.name = oids[e.id];\n\n // handle key usage\n if(e.name === 'keyUsage') {\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n var b3 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;\n }\n // set flags\n e.digitalSignature = (b2 & 0x80) === 0x80;\n e.nonRepudiation = (b2 & 0x40) === 0x40;\n e.keyEncipherment = (b2 & 0x20) === 0x20;\n e.dataEncipherment = (b2 & 0x10) === 0x10;\n e.keyAgreement = (b2 & 0x08) === 0x08;\n e.keyCertSign = (b2 & 0x04) === 0x04;\n e.cRLSign = (b2 & 0x02) === 0x02;\n e.encipherOnly = (b2 & 0x01) === 0x01;\n e.decipherOnly = (b3 & 0x80) === 0x80;\n } else if(e.name === 'basicConstraints') {\n // handle basic constraints\n // get value as SEQUENCE\n var ev = asn1.fromDer(e.value);\n // get cA BOOLEAN flag (defaults to false)\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {\n e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);\n } else {\n e.cA = false;\n }\n // get path length constraint\n var value = null;\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {\n value = ev.value[0].value;\n } else if(ev.value.length > 1) {\n value = ev.value[1].value;\n }\n if(value !== null) {\n e.pathLenConstraint = asn1.derToInteger(value);\n }\n } else if(e.name === 'extKeyUsage') {\n // handle extKeyUsage\n // value is a SEQUENCE of OIDs\n var ev = asn1.fromDer(e.value);\n for(var vi = 0; vi < ev.value.length; ++vi) {\n var oid = asn1.derToOid(ev.value[vi].value);\n if(oid in oids) {\n e[oids[oid]] = true;\n } else {\n e[oid] = true;\n }\n }\n } else if(e.name === 'nsCertType') {\n // handle nsCertType\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n }\n // set flags\n e.client = (b2 & 0x80) === 0x80;\n e.server = (b2 & 0x40) === 0x40;\n e.email = (b2 & 0x20) === 0x20;\n e.objsign = (b2 & 0x10) === 0x10;\n e.reserved = (b2 & 0x08) === 0x08;\n e.sslCA = (b2 & 0x04) === 0x04;\n e.emailCA = (b2 & 0x02) === 0x02;\n e.objCA = (b2 & 0x01) === 0x01;\n } else if(\n e.name === 'subjectAltName' ||\n e.name === 'issuerAltName') {\n // handle subjectAltName/issuerAltName\n e.altNames = [];\n\n // ev is a SYNTAX SEQUENCE\n var gn;\n var ev = asn1.fromDer(e.value);\n for(var n = 0; n < ev.value.length; ++n) {\n // get GeneralName\n gn = ev.value[n];\n\n var altName = {\n type: gn.type,\n value: gn.value\n };\n e.altNames.push(altName);\n\n // Note: Support for types 1,2,6,7,8\n switch(gn.type) {\n // rfc822Name\n case 1:\n // dNSName\n case 2:\n // uniformResourceIdentifier (URI)\n case 6:\n break;\n // IPAddress\n case 7:\n // convert to IPv4/IPv6 string representation\n altName.ip = forge.util.bytesToIP(gn.value);\n break;\n // registeredID\n case 8:\n altName.oid = asn1.derToOid(gn.value);\n break;\n default:\n // unsupported\n }\n }\n } else if(e.name === 'subjectKeyIdentifier') {\n // value is an OCTETSTRING w/the hash of the key-type specific\n // public key structure (eg: RSAPublicKey)\n var ev = asn1.fromDer(e.value);\n e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);\n }\n }\n return e;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the CertificationRequestInfo part of the\n * ASN.1 object needs to be scanned before the csr object is created.\n *\n * @param obj the asn1 representation of a PKCS#10 certification request (CSR).\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromAsn1 = function(obj, computeHash) {\n // validate certification request and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#10 certificate request. ' +\n 'ASN.1 object is not a PKCS#10 CertificationRequest.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certification request\n var csr = pki.createCertificationRequest();\n csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;\n csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.signatureParameters = _readSignatureParameters(\n csr.signatureOid, capture.csrSignatureParams, true);\n csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.siginfo.parameters = _readSignatureParameters(\n csr.siginfo.algorithmOid, capture.csrSignatureParams, false);\n csr.signature = capture.csrSignature;\n\n // keep CertificationRequestInfo to preserve signature when exporting\n csr.certificationRequestInfo = capture.certificationRequestInfo;\n\n if(computeHash) {\n // create digest for OID signature type\n csr.md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n csr.md.update(bytes.getBytes());\n }\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = pki.RDNAttributesAsArray(\n capture.certificationRequestInfoSubject, smd);\n csr.subject.hash = smd.digest().toHex();\n\n // convert RSA public key from ASN.1\n csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n // convert attributes from ASN.1\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.attributes = pki.CRIAttributesAsArray(\n capture.certificationRequestInfoAttributes || []);\n\n return csr;\n};\n\n/**\n * Creates an empty certification request (a CSR or certificate signing\n * request). Once created, its public key and attributes can be set and then\n * it can be signed.\n *\n * @return the empty certification request.\n */\npki.createCertificationRequest = function() {\n var csr = {};\n csr.version = 0x00;\n csr.signatureOid = null;\n csr.signature = null;\n csr.siginfo = {};\n csr.siginfo.algorithmOid = null;\n\n csr.subject = {};\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = [];\n csr.subject.hash = null;\n\n csr.publicKey = null;\n csr.attributes = [];\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.md = null;\n\n /**\n * Sets the subject of this certification request.\n *\n * @param attrs the array of subject attributes to use.\n */\n csr.setSubject = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.subject.attributes = attrs;\n csr.subject.hash = null;\n };\n\n /**\n * Sets the attributes of this certification request.\n *\n * @param attrs the array of attributes to use.\n */\n csr.setAttributes = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.attributes = attrs;\n };\n\n /**\n * Signs this certification request using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n csr.sign = function(key, md) {\n // TODO: get signature OID from private key\n csr.md = md || forge.md.sha1.create();\n var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = csr.md.algorithm;\n throw error;\n }\n csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;\n\n // get CertificationRequestInfo, convert to DER\n csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n\n // digest and sign\n csr.md.update(bytes.getBytes());\n csr.signature = key.sign(csr.md);\n };\n\n /**\n * Attempts verify the signature on the passed certification request using\n * its public key.\n *\n * A CSR that has been exported to a file in PEM format can be verified using\n * OpenSSL using this command:\n *\n * openssl req -in -verify -noout -text\n *\n * @return true if verified, false if not.\n */\n csr.verify = function() {\n var rval = false;\n\n var md = csr.md;\n if(md === null) {\n md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(cri);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: csr, md: md, signature: csr.signature\n });\n }\n\n return rval;\n };\n\n return csr;\n};\n\n/**\n * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.\n *\n * @param obj the subject or issuer (distinguished name).\n *\n * @return the ASN.1 RDNSequence.\n */\nfunction _dnToAsn1(obj) {\n // create an empty RDNSequence\n var rval = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // iterate over attributes\n var attr, set;\n var attrs = obj.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.PRINTABLESTRING;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n // FIXME: handle more encodings\n }\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n // AttributeValue\n asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)\n ])\n ]);\n rval.value.push(set);\n }\n\n return rval;\n}\n\n/**\n * Gets all printable attributes (typically of an issuer or subject) in a\n * simplified JSON format for display.\n *\n * @param attrs the attributes.\n *\n * @return the JSON for display.\n */\nfunction _getAttributesAsJson(attrs) {\n var rval = {};\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n if(attr.shortName && (\n attr.valueTagClass === asn1.Type.UTF8 ||\n attr.valueTagClass === asn1.Type.PRINTABLESTRING ||\n attr.valueTagClass === asn1.Type.IA5STRING)) {\n var value = attr.value;\n if(attr.valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(attr.value);\n }\n if(!(attr.shortName in rval)) {\n rval[attr.shortName] = value;\n } else if(forge.util.isArray(rval[attr.shortName])) {\n rval[attr.shortName].push(value);\n } else {\n rval[attr.shortName] = [rval[attr.shortName], value];\n }\n }\n }\n return rval;\n}\n\n/**\n * Fills in missing fields in attributes.\n *\n * @param attrs the attributes to fill missing fields in.\n */\nfunction _fillMissingFields(attrs) {\n var attr;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n\n // populate missing name\n if(typeof attr.name === 'undefined') {\n if(attr.type && attr.type in pki.oids) {\n attr.name = pki.oids[attr.type];\n } else if(attr.shortName && attr.shortName in _shortNames) {\n attr.name = pki.oids[_shortNames[attr.shortName]];\n }\n }\n\n // populate missing type (OID)\n if(typeof attr.type === 'undefined') {\n if(attr.name && attr.name in pki.oids) {\n attr.type = pki.oids[attr.name];\n } else {\n var error = new Error('Attribute type not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n\n // populate missing shortname\n if(typeof attr.shortName === 'undefined') {\n if(attr.name && attr.name in _shortNames) {\n attr.shortName = _shortNames[attr.name];\n }\n }\n\n // convert extensions to value\n if(attr.type === oids.extensionRequest) {\n attr.valueConstructed = true;\n attr.valueTagClass = asn1.Type.SEQUENCE;\n if(!attr.value && attr.extensions) {\n attr.value = [];\n for(var ei = 0; ei < attr.extensions.length; ++ei) {\n attr.value.push(pki.certificateExtensionToAsn1(\n _fillMissingExtensionFields(attr.extensions[ei])));\n }\n }\n }\n\n if(typeof attr.value === 'undefined') {\n var error = new Error('Attribute value not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n}\n\n/**\n * Fills in missing fields in certificate extensions.\n *\n * @param e the extension.\n * @param [options] the options to use.\n * [cert] the certificate the extensions are for.\n *\n * @return the extension.\n */\nfunction _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'nsComment' && options.cert) {\n // sanity check value is ASCII (req'd) and not too big\n if(!(/^[\\x00-\\x7F]*$/.test(e.comment)) ||\n (e.comment.length < 1) || (e.comment.length > 128)) {\n throw new Error('Invalid \"nsComment\" content.');\n }\n // IA5STRING opaque comment\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if(e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}\n\n/**\n * Convert signature parameters object to ASN.1\n *\n * @param {String} oid Signature algorithm OID\n * @param params The signature parametrs object\n * @return ASN.1 object representing signature parameters\n */\nfunction _signatureParametersToAsn1(oid, params) {\n switch(oid) {\n case oids['RSASSA-PSS']:\n var parts = [];\n\n if(params.hash.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]));\n }\n\n if(params.mgf.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ])\n ]));\n }\n\n if(params.saltLength !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(params.saltLength).getBytes())\n ]));\n }\n\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);\n\n default:\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');\n }\n}\n\n/**\n * Converts a certification request's attributes to an ASN.1 set of\n * CRIAttributes.\n *\n * @param csr certification request.\n *\n * @return the ASN.1 set of CRIAttributes.\n */\nfunction _CRIAttributesToAsn1(csr) {\n // create an empty context-specific container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // no attributes, return empty container\n if(csr.attributes.length === 0) {\n return rval;\n }\n\n // each attribute has a sequence with a type and a set of values\n var attrs = csr.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.UTF8;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n }\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n var valueConstructed = false;\n if('valueConstructed' in attr) {\n valueConstructed = attr.valueConstructed;\n }\n // FIXME: handle more encodings\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n asn1.create(\n asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)\n ])\n ]);\n rval.value.push(seq);\n }\n\n return rval;\n}\n\nvar jan_1_1950 = new Date('1950-01-01T00:00:00Z');\nvar jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n\n/**\n * Converts a Date object to ASN.1\n * Handles the different format before and after 1st January 2050\n *\n * @param date date object.\n *\n * @return the ASN.1 object representing the date.\n */\nfunction _dateToAsn1(date) {\n if(date >= jan_1_1950 && date < jan_1_2050) {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n}\n\n/**\n * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.\n *\n * @param cert the certificate.\n *\n * @return the asn1 TBSCertificate.\n */\npki.getTBSCertificate = function(cert) {\n // TBSCertificate\n var notBefore = _dateToAsn1(cert.validity.notBefore);\n var notAfter = _dateToAsn1(cert.validity.notAfter);\n var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // integer\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(cert.version).getBytes())\n ]),\n // serialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(cert.serialNumber)),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(\n cert.siginfo.algorithmOid, cert.siginfo.parameters)\n ]),\n // issuer\n _dnToAsn1(cert.issuer),\n // validity\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n notBefore,\n notAfter\n ]),\n // subject\n _dnToAsn1(cert.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(cert.publicKey)\n ]);\n\n if(cert.issuer.uniqueId) {\n // issuerUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.issuer.uniqueId\n )\n ])\n );\n }\n if(cert.subject.uniqueId) {\n // subjectUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.subject.uniqueId\n )\n ])\n );\n }\n\n if(cert.extensions.length > 0) {\n // extensions (optional)\n tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));\n }\n\n return tbs;\n};\n\n/**\n * Gets the ASN.1 CertificationRequestInfo part of a\n * PKCS#10 CertificationRequest.\n *\n * @param csr the certification request.\n *\n * @return the asn1 CertificationRequestInfo.\n */\npki.getCertificationRequestInfo = function(csr) {\n // CertificationRequestInfo\n var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(csr.version).getBytes()),\n // subject\n _dnToAsn1(csr.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(csr.publicKey),\n // attributes\n _CRIAttributesToAsn1(csr)\n ]);\n\n return cri;\n};\n\n/**\n * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.\n *\n * @param dn the DistinguishedName.\n *\n * @return the asn1 representation of a DistinguishedName.\n */\npki.distinguishedNameToAsn1 = function(dn) {\n return _dnToAsn1(dn);\n};\n\n/**\n * Converts an X.509v3 RSA certificate to an ASN.1 object.\n *\n * @param cert the certificate.\n *\n * @return the asn1 representation of an X.509v3 RSA certificate.\n */\npki.certificateToAsn1 = function(cert) {\n // prefer cached TBSCertificate over generating one\n var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // TBSCertificate\n tbsCertificate,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)\n ]),\n // SignatureValue\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + cert.signature)\n ]);\n};\n\n/**\n * Converts X.509v3 certificate extensions to ASN.1.\n *\n * @param exts the extensions to convert.\n *\n * @return the extensions in ASN.1 format.\n */\npki.certificateExtensionsToAsn1 = function(exts) {\n // create top-level extension container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);\n\n // create extension sequence (stores a sequence for each extension)\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n rval.value.push(seq);\n\n for(var i = 0; i < exts.length; ++i) {\n seq.value.push(pki.certificateExtensionToAsn1(exts[i]));\n }\n\n return rval;\n};\n\n/**\n * Converts a single certificate extension to ASN.1.\n *\n * @param ext the extension to convert.\n *\n * @return the extension in ASN.1 format.\n */\npki.certificateExtensionToAsn1 = function(ext) {\n // create a sequence for each extension\n var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // extnID (OID)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ext.id).getBytes()));\n\n // critical defaults to false\n if(ext.critical) {\n // critical BOOLEAN DEFAULT FALSE\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n\n var value = ext.value;\n if(typeof ext.value !== 'string') {\n // value is asn.1\n value = asn1.toDer(value).getBytes();\n }\n\n // extnValue (OCTET STRING)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));\n\n return extseq;\n};\n\n/**\n * Converts a PKCS#10 certification request to an ASN.1 object.\n *\n * @param csr the certification request.\n *\n * @return the asn1 representation of a certification request.\n */\npki.certificationRequestToAsn1 = function(csr) {\n // prefer cached CertificationRequestInfo over generating one\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // CertificationRequestInfo\n cri,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(csr.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)\n ]),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + csr.signature)\n ]);\n};\n\n/**\n * Creates a CA store.\n *\n * @param certs an optional array of certificate objects or PEM-formatted\n * certificate strings to add to the CA store.\n *\n * @return the CA store.\n */\npki.createCaStore = function(certs) {\n // create CA store\n var caStore = {\n // stored certificates\n certs: {}\n };\n\n /**\n * Gets the certificate that issued the passed certificate or its\n * 'parent'.\n *\n * @param cert the certificate to get the parent for.\n *\n * @return the parent certificate or null if none was found.\n */\n caStore.getIssuer = function(cert) {\n var rval = getBySubject(cert.issuer);\n\n // see if there are multiple matches\n /*if(forge.util.isArray(rval)) {\n // TODO: resolve multiple matches by checking\n // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.\n // FIXME: or alternatively do authority key mapping\n // if possible (X.509v1 certs can't work?)\n throw new Error('Resolving multiple issuer matches not implemented yet.');\n }*/\n\n return rval;\n };\n\n /**\n * Adds a trusted certificate to the store.\n *\n * @param cert the certificate to add as a trusted certificate (either a\n * pki.certificate object or a PEM-formatted certificate).\n */\n caStore.addCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n ensureSubjectHasHash(cert.subject);\n\n if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store\n if(cert.subject.hash in caStore.certs) {\n // subject hash already exists, append to array\n var tmp = caStore.certs[cert.subject.hash];\n if(!forge.util.isArray(tmp)) {\n tmp = [tmp];\n }\n tmp.push(cert);\n caStore.certs[cert.subject.hash] = tmp;\n } else {\n caStore.certs[cert.subject.hash] = cert;\n }\n }\n };\n\n /**\n * Checks to see if the given certificate is in the store.\n *\n * @param cert the certificate to check (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return true if the certificate is in the store, false if not.\n */\n caStore.hasCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n var match = getBySubject(cert.subject);\n if(!match) {\n return false;\n }\n if(!forge.util.isArray(match)) {\n match = [match];\n }\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n return true;\n }\n }\n return false;\n };\n\n /**\n * Lists all of the certificates kept in the store.\n *\n * @return an array of all of the pki.certificate objects in the store.\n */\n caStore.listAllCertificates = function() {\n var certList = [];\n\n for(var hash in caStore.certs) {\n if(caStore.certs.hasOwnProperty(hash)) {\n var value = caStore.certs[hash];\n if(!forge.util.isArray(value)) {\n certList.push(value);\n } else {\n for(var i = 0; i < value.length; ++i) {\n certList.push(value[i]);\n }\n }\n }\n }\n\n return certList;\n };\n\n /**\n * Removes a certificate from the store.\n *\n * @param cert the certificate to remove (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return the certificate that was removed or null if the certificate\n * wasn't in store.\n */\n caStore.removeCertificate = function(cert) {\n var result;\n\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n ensureSubjectHasHash(cert.subject);\n if(!caStore.hasCertificate(cert)) {\n return null;\n }\n\n var match = getBySubject(cert.subject);\n\n if(!forge.util.isArray(match)) {\n result = caStore.certs[cert.subject.hash];\n delete caStore.certs[cert.subject.hash];\n return result;\n }\n\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n result = match[i];\n match.splice(i, 1);\n }\n }\n if(match.length === 0) {\n delete caStore.certs[cert.subject.hash];\n }\n\n return result;\n };\n\n function getBySubject(subject) {\n ensureSubjectHasHash(subject);\n return caStore.certs[subject.hash] || null;\n }\n\n function ensureSubjectHasHash(subject) {\n // produce subject hash if it doesn't exist\n if(!subject.hash) {\n var md = forge.md.sha1.create();\n subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);\n subject.hash = md.digest().toHex();\n }\n }\n\n // auto-add passed in certs\n if(certs) {\n // parse PEM-formatted certificates as necessary\n for(var i = 0; i < certs.length; ++i) {\n var cert = certs[i];\n caStore.addCertificate(cert);\n }\n }\n\n return caStore;\n};\n\n/**\n * Certificate verification errors, based on TLS.\n */\npki.certificateError = {\n bad_certificate: 'forge.pki.BadCertificate',\n unsupported_certificate: 'forge.pki.UnsupportedCertificate',\n certificate_revoked: 'forge.pki.CertificateRevoked',\n certificate_expired: 'forge.pki.CertificateExpired',\n certificate_unknown: 'forge.pki.CertificateUnknown',\n unknown_ca: 'forge.pki.UnknownCertificateAuthority'\n};\n\n/**\n * Verifies a certificate chain against the given Certificate Authority store\n * with an optional custom verify callback.\n *\n * @param caStore a certificate store to verify against.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end (an array of certificates).\n * @param options a callback to be called for every certificate in the chain or\n * an object with:\n * verify a callback to be called for every certificate in the\n * chain\n * validityCheckDate the date against which the certificate\n * validity period should be checked. Pass null to not check\n * the validity period. By default, the current date is used.\n *\n * The verify callback has the following signature:\n *\n * verified - Set to true if certificate was verified, otherwise the\n * pki.certificateError for why the certificate failed.\n * depth - The current index in the chain, where 0 is the end point's cert.\n * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous\n * end point.\n *\n * The function returns true on success and on failure either the appropriate\n * pki.certificateError or an object with 'error' set to the appropriate\n * pki.certificateError and 'message' set to a custom error message.\n *\n * @return true if successful, error thrown if not.\n */\npki.verifyCertificateChain = function(caStore, chain, options) {\n /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate\n Section 6: Certification Path Validation\n See inline parentheticals related to this particular implementation.\n\n The primary goal of path validation is to verify the binding between\n a subject distinguished name or a subject alternative name and subject\n public key, as represented in the end entity certificate, based on the\n public key of the trust anchor. This requires obtaining a sequence of\n certificates that support that binding. That sequence should be provided\n in the passed 'chain'. The trust anchor should be in the given CA\n store. The 'end entity' certificate is the certificate provided by the\n end point (typically a server) and is the first in the chain.\n\n To meet this goal, the path validation process verifies, among other\n things, that a prospective certification path (a sequence of n\n certificates or a 'chain') satisfies the following conditions:\n\n (a) for all x in {1, ..., n-1}, the subject of certificate x is\n the issuer of certificate x+1;\n\n (b) certificate 1 is issued by the trust anchor;\n\n (c) certificate n is the certificate to be validated; and\n\n (d) for all x in {1, ..., n}, the certificate was valid at the\n time in question.\n\n Note that here 'n' is index 0 in the chain and 1 is the last certificate\n in the chain and it must be signed by a certificate in the connection's\n CA store.\n\n The path validation process also determines the set of certificate\n policies that are valid for this path, based on the certificate policies\n extension, policy mapping extension, policy constraints extension, and\n inhibit any-policy extension.\n\n Note: Policy mapping extension not supported (Not Required).\n\n Note: If the certificate has an unsupported critical extension, then it\n must be rejected.\n\n Note: A certificate is self-issued if the DNs that appear in the subject\n and issuer fields are identical and are not empty.\n\n The path validation algorithm assumes the following seven inputs are\n provided to the path processing logic. What this specific implementation\n will use is provided parenthetically:\n\n (a) a prospective certification path of length n (the 'chain')\n (b) the current date/time: ('now').\n (c) user-initial-policy-set: A set of certificate policy identifiers\n naming the policies that are acceptable to the certificate user.\n The user-initial-policy-set contains the special value any-policy\n if the user is not concerned about certificate policy\n (Not implemented. Any policy is accepted).\n (d) trust anchor information, describing a CA that serves as a trust\n anchor for the certification path. The trust anchor information\n includes:\n\n (1) the trusted issuer name,\n (2) the trusted public key algorithm,\n (3) the trusted public key, and\n (4) optionally, the trusted public key parameters associated\n with the public key.\n\n (Trust anchors are provided via certificates in the CA store).\n\n The trust anchor information may be provided to the path processing\n procedure in the form of a self-signed certificate. The trusted anchor\n information is trusted because it was delivered to the path processing\n procedure by some trustworthy out-of-band procedure. If the trusted\n public key algorithm requires parameters, then the parameters are\n provided along with the trusted public key (No parameters used in this\n implementation).\n\n (e) initial-policy-mapping-inhibit, which indicates if policy mapping is\n allowed in the certification path.\n (Not implemented, no policy checking)\n\n (f) initial-explicit-policy, which indicates if the path must be valid\n for at least one of the certificate policies in the user-initial-\n policy-set.\n (Not implemented, no policy checking)\n\n (g) initial-any-policy-inhibit, which indicates whether the\n anyPolicy OID should be processed if it is included in a\n certificate.\n (Not implemented, so any policy is valid provided that it is\n not marked as critical) */\n\n /* Basic Path Processing:\n\n For each certificate in the 'chain', the following is checked:\n\n 1. The certificate validity period includes the current time.\n 2. The certificate was signed by its parent (where the parent is either\n the next in the chain or from the CA store). Allow processing to\n continue to the next step if no parent is found but the certificate is\n in the CA store.\n 3. TODO: The certificate has not been revoked.\n 4. The certificate issuer name matches the parent's subject name.\n 5. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is within one of the permitted subtrees of X.500 distinguished names\n and that each of the alternative names in the subjectAltName extension\n (critical or non-critical) is within one of the permitted subtrees for\n that name type.\n 6. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is not within one of the excluded subtrees for X.500 distinguished\n names and none of the subjectAltName extension names are excluded for\n that name type.\n 7. The other steps in the algorithm for basic path processing involve\n handling the policy extension which is not presently supported in this\n implementation. Instead, if a critical policy extension is found, the\n certificate is rejected as not supported.\n 8. If the certificate is not the first or if its the only certificate in\n the chain (having no parent from the CA store or is self-signed) and it\n has a critical key usage extension, verify that the keyCertSign bit is\n set. If the key usage extension exists, verify that the basic\n constraints extension exists. If the basic constraints extension exists,\n verify that the cA flag is set. If pathLenConstraint is set, ensure that\n the number of certificates that precede in the chain (come earlier\n in the chain as implemented below), excluding the very first in the\n chain (typically the end-entity one), isn't greater than the\n pathLenConstraint. This constraint limits the number of intermediate\n CAs that may appear below a CA before only end-entity certificates\n may be issued. */\n\n // if a verify callback is passed as the third parameter, package it within\n // the options object. This is to support a legacy function signature that\n // expected the verify callback as the third parameter.\n if(typeof options === 'function') {\n options = {verify: options};\n }\n options = options || {};\n\n // copy cert chain references to another array to protect against changes\n // in verify callback\n chain = chain.slice(0);\n var certs = chain.slice(0);\n\n var validityCheckDate = options.validityCheckDate;\n // if no validityCheckDate is specified, default to the current date. Make\n // sure to maintain the value null because it indicates that the validity\n // period should not be checked.\n if(typeof validityCheckDate === 'undefined') {\n validityCheckDate = new Date();\n }\n\n // verify each cert in the chain using its parent, where the parent\n // is either the next in the chain or from the CA store\n var first = true;\n var error = null;\n var depth = 0;\n do {\n var cert = chain.shift();\n var parent = null;\n var selfSigned = false;\n\n if(validityCheckDate) {\n // 1. check valid time\n if(validityCheckDate < cert.validity.notBefore ||\n validityCheckDate > cert.validity.notAfter) {\n error = {\n message: 'Certificate is not valid yet or has expired.',\n error: pki.certificateError.certificate_expired,\n notBefore: cert.validity.notBefore,\n notAfter: cert.validity.notAfter,\n // TODO: we might want to reconsider renaming 'now' to\n // 'validityCheckDate' should this API be changed in the future.\n now: validityCheckDate\n };\n }\n }\n\n // 2. verify with parent from chain or CA store\n if(error === null) {\n parent = chain[0] || caStore.getIssuer(cert);\n if(parent === null) {\n // check for self-signed cert\n if(cert.isIssuer(cert)) {\n selfSigned = true;\n parent = cert;\n }\n }\n\n if(parent) {\n // FIXME: current CA store implementation might have multiple\n // certificates where the issuer can't be determined from the\n // certificate (happens rarely with, eg: old certificates) so normalize\n // by always putting parents into an array\n // TODO: there's may be an extreme degenerate case currently uncovered\n // where an old intermediate certificate seems to have a matching parent\n // but none of the parents actually verify ... but the intermediate\n // is in the CA and it should pass this check; needs investigation\n var parents = parent;\n if(!forge.util.isArray(parents)) {\n parents = [parents];\n }\n\n // try to verify with each possible parent (typically only one)\n var verified = false;\n while(!verified && parents.length > 0) {\n parent = parents.shift();\n try {\n verified = parent.verify(cert);\n } catch(ex) {\n // failure to verify, don't care why, try next one\n }\n }\n\n if(!verified) {\n error = {\n message: 'Certificate signature is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n\n if(error === null && (!parent || selfSigned) &&\n !caStore.hasCertificate(cert)) {\n // no parent issuer and certificate itself is not trusted\n error = {\n message: 'Certificate is not trusted.',\n error: pki.certificateError.unknown_ca\n };\n }\n }\n\n // TODO: 3. check revoked\n\n // 4. check for matching issuer/subject\n if(error === null && parent && !cert.isIssuer(parent)) {\n // parent is not issuer\n error = {\n message: 'Certificate issuer is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // 5. TODO: check names with permitted names tree\n\n // 6. TODO: check names against excluded names tree\n\n // 7. check for unsupported critical extensions\n if(error === null) {\n // supported extensions\n var se = {\n keyUsage: true,\n basicConstraints: true\n };\n for(var i = 0; error === null && i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.critical && !(ext.name in se)) {\n error = {\n message:\n 'Certificate has an unsupported critical extension.',\n error: pki.certificateError.unsupported_certificate\n };\n }\n }\n }\n\n // 8. check for CA if cert is not first or is the only certificate\n // remaining in chain with no parent or is self-signed\n if(error === null &&\n (!first || (chain.length === 0 && (!parent || selfSigned)))) {\n // first check keyUsage extension and then basic constraints\n var bcExt = cert.getExtension('basicConstraints');\n var keyUsageExt = cert.getExtension('keyUsage');\n if(keyUsageExt !== null) {\n // keyCertSign must be true and there must be a basic\n // constraints extension\n if(!keyUsageExt.keyCertSign || bcExt === null) {\n // bad certificate\n error = {\n message:\n 'Certificate keyUsage or basicConstraints conflict ' +\n 'or indicate that the certificate is not a CA. ' +\n 'If the certificate is the only one in the chain or ' +\n 'isn\\'t the first then the certificate must be a ' +\n 'valid CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n // basic constraints cA flag must be set\n if(error === null && bcExt !== null && !bcExt.cA) {\n // bad certificate\n error = {\n message:\n 'Certificate basicConstraints indicates the certificate ' +\n 'is not a CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n // if error is not null and keyUsage is available, then we know it\n // has keyCertSign and there is a basic constraints extension too,\n // which means we can check pathLenConstraint (if it exists)\n if(error === null && keyUsageExt !== null &&\n 'pathLenConstraint' in bcExt) {\n // pathLen is the maximum # of intermediate CA certs that can be\n // found between the current certificate and the end-entity (depth 0)\n // certificate; this number does not include the end-entity (depth 0,\n // last in the chain) even if it happens to be a CA certificate itself\n var pathLen = depth - 1;\n if(pathLen > bcExt.pathLenConstraint) {\n // pathLenConstraint violated, bad certificate\n error = {\n message:\n 'Certificate basicConstraints pathLenConstraint violated.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n }\n\n // call application callback\n var vfd = (error === null) ? true : error.error;\n var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;\n if(ret === true) {\n // clear any set error\n error = null;\n } else {\n // if passed basic tests, set default message and alert\n if(vfd === true) {\n error = {\n message: 'The application rejected the certificate.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // check for custom error info\n if(ret || ret === 0) {\n // set custom message and error\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.error) {\n error.error = ret.error;\n }\n } else if(typeof ret === 'string') {\n // set custom error\n error.error = ret;\n }\n }\n\n // throw error\n throw error;\n }\n\n // no longer first cert in chain\n first = false;\n ++depth;\n } while(chain.length > 0);\n\n return true;\n};\n","var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n","var once = require('once')\nvar eos = require('end-of-stream')\nvar fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes\n\nvar noop = function () {}\nvar ancient = /^v?\\.0/.test(process.version)\n\nvar isFn = function (fn) {\n return typeof fn === 'function'\n}\n\nvar isFS = function (stream) {\n if (!ancient) return false // newer node version do not need to care about fs is a special way\n if (!fs) return false // browser\n return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)\n}\n\nvar isRequest = function (stream) {\n return stream.setHeader && isFn(stream.abort)\n}\n\nvar destroyer = function (stream, reading, writing, callback) {\n callback = once(callback)\n\n var closed = false\n stream.on('close', function () {\n closed = true\n })\n\n eos(stream, {readable: reading, writable: writing}, function (err) {\n if (err) return callback(err)\n closed = true\n callback()\n })\n\n var destroyed = false\n return function (err) {\n if (closed) return\n if (destroyed) return\n destroyed = true\n\n if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks\n if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want\n\n if (isFn(stream.destroy)) return stream.destroy()\n\n callback(err || new Error('stream was destroyed'))\n }\n}\n\nvar call = function (fn) {\n fn()\n}\n\nvar pipe = function (from, to) {\n return from.pipe(to)\n}\n\nvar pump = function () {\n var streams = Array.prototype.slice.call(arguments)\n var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop\n\n if (Array.isArray(streams[0])) streams = streams[0]\n if (streams.length < 2) throw new Error('pump requires two streams per minimum')\n\n var error\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1\n var writing = i > 0\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err\n if (err) destroys.forEach(call)\n if (reading) return\n destroys.forEach(call)\n callback(error)\n })\n })\n\n return streams.reduce(pipe)\n}\n\nmodule.exports = pump\n","'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};","'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;","'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();","'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;","'use strict';\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;\n\nfunction from(Readable, iterable, opts) {\n var iterator;\n\n if (iterable && typeof iterable.next === 'function') {\n iterator = iterable;\n } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);\n\n var readable = new Readable(_objectSpread({\n objectMode: true\n }, opts)); // Reading boolean to protect against _read\n // being called before last iteration completion.\n\n var reading = false;\n\n readable._read = function () {\n if (!reading) {\n reading = true;\n next();\n }\n };\n\n function next() {\n return _next2.apply(this, arguments);\n }\n\n function _next2() {\n _next2 = _asyncToGenerator(function* () {\n try {\n var _ref = yield iterator.next(),\n value = _ref.value,\n done = _ref.done;\n\n if (done) {\n readable.push(null);\n } else if (readable.push((yield value))) {\n next();\n } else {\n reading = false;\n }\n } catch (err) {\n readable.destroy(err);\n }\n });\n return _next2.apply(this, arguments);\n }\n\n return readable;\n}\n\nmodule.exports = from;","// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\n\n var error;\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1;\n var writing = i > 0;\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err;\n if (err) destroys.forEach(call);\n if (reading) return;\n destroys.forEach(call);\n callback(error);\n });\n });\n return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;","'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};","module.exports = require('stream');\n","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n","/* eslint-disable node/no-deprecated-api */\n\n'use strict'\n\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\nvar safer = {}\n\nvar key\n\nfor (key in buffer) {\n if (!buffer.hasOwnProperty(key)) continue\n if (key === 'SlowBuffer' || key === 'Buffer') continue\n safer[key] = buffer[key]\n}\n\nvar Safer = safer.Buffer = {}\nfor (key in Buffer) {\n if (!Buffer.hasOwnProperty(key)) continue\n if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue\n Safer[key] = Buffer[key]\n}\n\nsafer.Buffer.prototype = Buffer.prototype\n\nif (!Safer.from || Safer.from === Uint8Array.from) {\n Safer.from = function (value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('The \"value\" argument must not be of type number. Received type ' + typeof value)\n }\n if (value && typeof value.length === 'undefined') {\n throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)\n }\n return Buffer(value, encodingOrOffset, length)\n }\n}\n\nif (!Safer.alloc) {\n Safer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('The \"size\" argument must be of type number. Received type ' + typeof size)\n }\n if (size < 0 || size >= 2 * (1 << 30)) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n var buf = Buffer(size)\n if (!fill || fill.length === 0) {\n buf.fill(0)\n } else if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n return buf\n }\n}\n\nif (!safer.kStringMaxLength) {\n try {\n safer.kStringMaxLength = process.binding('buffer').kStringMaxLength\n } catch (e) {\n // we can't determine kStringMaxLength in environments where process.binding\n // is unsupported, so let's not set it\n }\n}\n\nif (!safer.constants) {\n safer.constants = {\n MAX_LENGTH: safer.kMaxLength\n }\n if (safer.kStringMaxLength) {\n safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength\n }\n}\n\nmodule.exports = safer\n","var fs = require('fs');\n\nmodule.exports = function (filepath, split, encoding) {\n split = typeof split !== 'undefined' ? split : \"\\n\";\n encoding = typeof encoding !== 'undefined' ? encoding : \"utf8\";\n\n var ca = [];\n var chain = fs.readFileSync(filepath, encoding);\n if(chain.indexOf(\"-END CERTIFICATE-\") < 0 || chain.indexOf(\"-BEGIN CERTIFICATE-\") < 0){\n throw Error(\"File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'\");\n }\n chain = chain.split(split);\n var cert = [];\n var _i, _len;\n for (_i = 0, _len = chain.length; _i < _len; _i++) {\n var line = chain[_i];\n if (!(line.length !== 0)) {\n continue;\n }\n cert.push(line);\n if (line.match(/-END CERTIFICATE-/)) {\n ca.push(cert.join(split));\n cert = [];\n }\n }\n return ca;\n}\n","'use strict';\n\nconst {\n Duplex: DuplexStream,\n Readable: ReadableStream,\n Writable: WritableStream,\n} = require('stream');\n\nconst {\n CHANNEL_EXTENDED_DATATYPE: { STDERR },\n} = require('./protocol/constants.js');\nconst { bufferSlice } = require('./protocol/utils.js');\n\nconst PACKET_SIZE = 32 * 1024;\nconst MAX_WINDOW = 2 * 1024 * 1024;\nconst WINDOW_THRESHOLD = MAX_WINDOW / 2;\n\nclass ClientStderr extends ReadableStream {\n constructor(channel, streamOpts) {\n super(streamOpts);\n\n this._channel = channel;\n }\n _read(n) {\n if (this._channel._waitChanDrain) {\n this._channel._waitChanDrain = false;\n if (this._channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(this._channel);\n }\n }\n}\n\nclass ServerStderr extends WritableStream {\n constructor(channel) {\n super({ highWaterMark: MAX_WINDOW });\n\n this._channel = channel;\n }\n\n _write(data, encoding, cb) {\n const channel = this._channel;\n const protocol = channel._client._protocol;\n const outgoing = channel.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelExtData(id, data, STDERR);\n else\n protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR);\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n channel._waitWindow = true;\n if (p > 0)\n channel._chunkErr = bufferSlice(data, p, len);\n else\n channel._chunkErr = data;\n channel._chunkcbErr = cb;\n return;\n }\n\n cb();\n }\n}\n\nclass Channel extends DuplexStream {\n constructor(client, info, opts) {\n const streamOpts = {\n highWaterMark: MAX_WINDOW,\n allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)),\n emitClose: false,\n };\n super(streamOpts);\n this.allowHalfOpen = streamOpts.allowHalfOpen;\n\n const server = !!(opts && opts.server);\n\n this.server = server;\n this.type = info.type;\n this.subtype = undefined;\n\n /*\n incoming and outgoing contain these properties:\n {\n id: undefined,\n window: undefined,\n packetSize: undefined,\n state: 'closed'\n }\n */\n this.incoming = info.incoming;\n this.outgoing = info.outgoing;\n this._callbacks = [];\n\n this._client = client;\n this._hasX11 = false;\n this._exit = {\n code: undefined,\n signal: undefined,\n dump: undefined,\n desc: undefined,\n };\n\n this.stdin = this.stdout = this;\n\n if (server)\n this.stderr = new ServerStderr(this);\n else\n this.stderr = new ClientStderr(this, streamOpts);\n\n // Outgoing data\n this._waitWindow = false; // SSH-level backpressure\n\n // Incoming data\n this._waitChanDrain = false; // Channel Readable side backpressure\n\n this._chunk = undefined;\n this._chunkcb = undefined;\n this._chunkErr = undefined;\n this._chunkcbErr = undefined;\n\n this.on('finish', onFinish)\n .on('prefinish', onFinish); // For node v0.11+\n\n this.on('end', onEnd).on('close', onEnd);\n }\n\n _read(n) {\n if (this._waitChanDrain) {\n this._waitChanDrain = false;\n if (this.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(this);\n }\n }\n\n _write(data, encoding, cb) {\n const protocol = this._client._protocol;\n const outgoing = this.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelData(id, data);\n else\n protocol.channelData(id, bufferSlice(data, p, p + sliceLen));\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n this._waitWindow = true;\n if (p > 0)\n this._chunk = bufferSlice(data, p, len);\n else\n this._chunk = data;\n this._chunkcb = cb;\n return;\n }\n\n cb();\n }\n\n eof() {\n if (this.outgoing.state === 'open') {\n this.outgoing.state = 'eof';\n this._client._protocol.channelEOF(this.outgoing.id);\n }\n }\n\n close() {\n if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {\n this.outgoing.state = 'closing';\n this._client._protocol.channelClose(this.outgoing.id);\n }\n }\n\n destroy() {\n this.end();\n this.close();\n return this;\n }\n\n // Session type-specific methods =============================================\n setWindow(rows, cols, height, width) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && (this.subtype === 'shell' || this.subtype === 'exec')\n && this.writable\n && this.outgoing.state === 'open') {\n this._client._protocol.windowChange(this.outgoing.id,\n rows,\n cols,\n height,\n width);\n }\n }\n\n signal(signalName) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open') {\n this._client._protocol.signal(this.outgoing.id, signalName);\n }\n }\n\n exit(statusOrSignal, coreDumped, msg) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open') {\n if (typeof statusOrSignal === 'number') {\n this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal);\n } else {\n this._client._protocol.exitSignal(this.outgoing.id,\n statusOrSignal,\n coreDumped,\n msg);\n }\n }\n }\n\n}\n\nfunction onFinish() {\n this.eof();\n if (this.server || !this.allowHalfOpen)\n this.close();\n this.writable = false;\n}\n\nfunction onEnd() {\n this.readable = false;\n}\n\nfunction windowAdjust(self) {\n if (self.outgoing.state === 'closed')\n return;\n const amt = MAX_WINDOW - self.incoming.window;\n if (amt <= 0)\n return;\n self.incoming.window += amt;\n self._client._protocol.channelWindowAdjust(self.outgoing.id, amt);\n}\n\nmodule.exports = {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n};\n",null,"// TODO:\n// * add `.connected` or similar property to allow immediate connection\n// status checking\n// * add/improve debug output during user authentication phase\n'use strict';\n\nconst {\n createHash,\n getHashes,\n randomFillSync,\n} = require('crypto');\nconst { Socket } = require('net');\nconst { lookup: dnsLookup } = require('dns');\nconst EventEmitter = require('events');\nconst HASHES = getHashes();\n\nconst {\n COMPAT,\n CHANNEL_EXTENDED_DATATYPE: { STDERR },\n CHANNEL_OPEN_FAILURE,\n DEFAULT_CIPHER,\n DEFAULT_COMPRESSION,\n DEFAULT_KEX,\n DEFAULT_MAC,\n DEFAULT_SERVER_HOST_KEY,\n DISCONNECT_REASON,\n DISCONNECT_REASON_BY_VALUE,\n SUPPORTED_CIPHER,\n SUPPORTED_COMPRESSION,\n SUPPORTED_KEX,\n SUPPORTED_MAC,\n SUPPORTED_SERVER_HOST_KEY,\n} = require('./protocol/constants.js');\nconst { init: cryptoInit } = require('./protocol/crypto.js');\nconst Protocol = require('./protocol/Protocol.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst { SFTP } = require('./protocol/SFTP.js');\nconst {\n bufferCopy,\n makeBufferParser,\n makeError,\n readUInt32BE,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./protocol/utils.js');\n\nconst { AgentContext, createAgent, isAgent } = require('./agent.js');\nconst {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n} = require('./Channel.js');\nconst {\n ChannelManager,\n generateAlgorithmList,\n isWritable,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n} = require('./utils.js');\n\nconst bufferParser = makeBufferParser();\nconst sigParser = makeBufferParser();\nconst RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\\d)|(?:\\d{2,})/;\nconst noop = (err) => {};\n\nclass Client extends EventEmitter {\n constructor() {\n super();\n\n this.config = {\n host: undefined,\n port: undefined,\n localAddress: undefined,\n localPort: undefined,\n forceIPv4: undefined,\n forceIPv6: undefined,\n keepaliveCountMax: undefined,\n keepaliveInterval: undefined,\n readyTimeout: undefined,\n ident: undefined,\n\n username: undefined,\n password: undefined,\n privateKey: undefined,\n tryKeyboard: undefined,\n agent: undefined,\n allowAgentFwd: undefined,\n authHandler: undefined,\n\n hostHashAlgo: undefined,\n hostHashCb: undefined,\n strictVendor: undefined,\n debug: undefined\n };\n\n this._agent = undefined;\n this._readyTimeout = undefined;\n this._chanMgr = undefined;\n this._callbacks = undefined;\n this._forwarding = undefined;\n this._forwardingUnix = undefined;\n this._acceptX11 = undefined;\n this._agentFwdEnabled = undefined;\n this._remoteVer = undefined;\n\n this._protocol = undefined;\n this._sock = undefined;\n this._resetKA = undefined;\n }\n\n connect(cfg) {\n if (this._sock && isWritable(this._sock)) {\n this.once('close', () => {\n this.connect(cfg);\n });\n this.end();\n return this;\n }\n\n this.config.host = cfg.hostname || cfg.host || 'localhost';\n this.config.port = cfg.port || 22;\n this.config.localAddress = (typeof cfg.localAddress === 'string'\n ? cfg.localAddress\n : undefined);\n this.config.localPort = (typeof cfg.localPort === 'string'\n || typeof cfg.localPort === 'number'\n ? cfg.localPort\n : undefined);\n this.config.forceIPv4 = cfg.forceIPv4 || false;\n this.config.forceIPv6 = cfg.forceIPv6 || false;\n this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number'\n && cfg.keepaliveCountMax >= 0\n ? cfg.keepaliveCountMax\n : 3);\n this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number'\n && cfg.keepaliveInterval > 0\n ? cfg.keepaliveInterval\n : 0);\n this.config.readyTimeout = (typeof cfg.readyTimeout === 'number'\n && cfg.readyTimeout >= 0\n ? cfg.readyTimeout\n : 20000);\n this.config.ident = (typeof cfg.ident === 'string'\n || Buffer.isBuffer(cfg.ident)\n ? cfg.ident\n : undefined);\n\n const algorithms = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: [],\n },\n sc: undefined,\n };\n let allOfferDefaults = true;\n if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) {\n algorithms.kex = generateAlgorithmList(cfg.algorithms.kex,\n DEFAULT_KEX,\n SUPPORTED_KEX);\n if (algorithms.kex !== DEFAULT_KEX)\n allOfferDefaults = false;\n\n algorithms.serverHostKey =\n generateAlgorithmList(cfg.algorithms.serverHostKey,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY);\n if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY)\n allOfferDefaults = false;\n\n algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER);\n if (algorithms.cs.cipher !== DEFAULT_CIPHER)\n allOfferDefaults = false;\n\n algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac,\n DEFAULT_MAC,\n SUPPORTED_MAC);\n if (algorithms.cs.mac !== DEFAULT_MAC)\n allOfferDefaults = false;\n\n algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION);\n if (algorithms.cs.compress !== DEFAULT_COMPRESSION)\n allOfferDefaults = false;\n\n if (!allOfferDefaults)\n algorithms.sc = algorithms.cs;\n }\n\n if (typeof cfg.username === 'string')\n this.config.username = cfg.username;\n else if (typeof cfg.user === 'string')\n this.config.username = cfg.user;\n else\n throw new Error('Invalid username');\n\n this.config.password = (typeof cfg.password === 'string'\n ? cfg.password\n : undefined);\n this.config.privateKey = (typeof cfg.privateKey === 'string'\n || Buffer.isBuffer(cfg.privateKey)\n ? cfg.privateKey\n : undefined);\n this.config.localHostname = (typeof cfg.localHostname === 'string'\n ? cfg.localHostname\n : undefined);\n this.config.localUsername = (typeof cfg.localUsername === 'string'\n ? cfg.localUsername\n : undefined);\n this.config.tryKeyboard = (cfg.tryKeyboard === true);\n if (typeof cfg.agent === 'string' && cfg.agent.length)\n this.config.agent = createAgent(cfg.agent);\n else if (isAgent(cfg.agent))\n this.config.agent = cfg.agent;\n else\n this.config.agent = undefined;\n this.config.allowAgentFwd = (cfg.agentForward === true\n && this.config.agent !== undefined);\n let authHandler = this.config.authHandler = (\n typeof cfg.authHandler === 'function'\n || Array.isArray(cfg.authHandler)\n ? cfg.authHandler\n : undefined\n );\n\n this.config.strictVendor = (typeof cfg.strictVendor === 'boolean'\n ? cfg.strictVendor\n : true);\n\n const debug = this.config.debug = (typeof cfg.debug === 'function'\n ? cfg.debug\n : undefined);\n\n if (cfg.agentForward === true && !this.config.allowAgentFwd) {\n throw new Error(\n 'You must set a valid agent path to allow agent forwarding'\n );\n }\n\n let callbacks = this._callbacks = [];\n this._chanMgr = new ChannelManager(this);\n this._forwarding = {};\n this._forwardingUnix = {};\n this._acceptX11 = 0;\n this._agentFwdEnabled = false;\n this._agent = (this.config.agent ? this.config.agent : undefined);\n this._remoteVer = undefined;\n let privateKey;\n\n if (this.config.privateKey) {\n privateKey = parseKey(this.config.privateKey, cfg.passphrase);\n if (privateKey instanceof Error)\n throw new Error(`Cannot parse privateKey: ${privateKey.message}`);\n if (Array.isArray(privateKey)) {\n // OpenSSH's newer format only stores 1 key for now\n privateKey = privateKey[0];\n }\n if (privateKey.getPrivatePEM() === null) {\n throw new Error(\n 'privateKey value does not contain a (valid) private key'\n );\n }\n }\n\n let hostVerifier;\n if (typeof cfg.hostVerifier === 'function') {\n const hashCb = cfg.hostVerifier;\n let hasher;\n if (HASHES.indexOf(cfg.hostHash) !== -1) {\n // Default to old behavior of hashing on user's behalf\n hasher = createHash(cfg.hostHash);\n }\n hostVerifier = (key, verify) => {\n if (hasher) {\n hasher.update(key);\n key = hasher.digest('hex');\n }\n const ret = hashCb(key, verify);\n if (ret !== undefined)\n verify(ret);\n };\n }\n\n const sock = this._sock = (cfg.sock || new Socket());\n let ready = false;\n let sawHeader = false;\n if (this._protocol)\n this._protocol.cleanup();\n const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {\n debug(`Debug output from server: ${JSON.stringify(msg)}`);\n });\n const proto = this._protocol = new Protocol({\n ident: this.config.ident,\n offer: (allOfferDefaults ? undefined : algorithms),\n onWrite: (data) => {\n if (isWritable(sock))\n sock.write(data);\n },\n onError: (err) => {\n if (err.level === 'handshake')\n clearTimeout(this._readyTimeout);\n if (!proto._destruct)\n sock.removeAllListeners('data');\n this.emit('error', err);\n try {\n sock.end();\n } catch {}\n },\n onHeader: (header) => {\n sawHeader = true;\n this._remoteVer = header.versions.software;\n if (header.greeting)\n this.emit('greeting', header.greeting);\n },\n onHandshakeComplete: (negotiated) => {\n this.emit('handshake', negotiated);\n if (!ready) {\n ready = true;\n proto.service('ssh-userauth');\n }\n },\n debug,\n hostVerifier,\n messageHandlers: {\n DEBUG: DEBUG_HANDLER,\n DISCONNECT: (p, reason, desc) => {\n if (reason !== DISCONNECT_REASON.BY_APPLICATION) {\n if (!desc) {\n desc = DISCONNECT_REASON_BY_VALUE[reason];\n if (desc === undefined)\n desc = `Unexpected disconnection reason: ${reason}`;\n }\n const err = new Error(desc);\n err.code = reason;\n this.emit('error', err);\n }\n sock.end();\n },\n SERVICE_ACCEPT: (p, name) => {\n if (name === 'ssh-userauth')\n tryNextAuth();\n },\n USERAUTH_BANNER: (p, msg) => {\n this.emit('banner', msg);\n },\n USERAUTH_SUCCESS: (p) => {\n // Start keepalive mechanism\n resetKA();\n\n clearTimeout(this._readyTimeout);\n\n this.emit('ready');\n },\n USERAUTH_FAILURE: (p, authMethods, partialSuccess) => {\n if (curAuth.type === 'agent') {\n const pos = curAuth.agentCtx.pos();\n debug && debug(`Client: Agent key #${pos + 1} failed`);\n return tryNextAgentKey();\n }\n\n debug && debug(`Client: ${curAuth.type} auth failed`);\n\n curPartial = partialSuccess;\n curAuthsLeft = authMethods;\n tryNextAuth();\n },\n USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => {\n if (curAuth.type === 'password') {\n // TODO: support a `changePrompt()` on `curAuth` that defaults to\n // emitting 'change password' as before\n this.emit('change password', prompt, (newPassword) => {\n proto.authPassword(\n this.config.username,\n this.config.password,\n newPassword\n );\n });\n }\n },\n USERAUTH_PK_OK: (p) => {\n if (curAuth.type === 'agent') {\n const key = curAuth.agentCtx.currentKey();\n proto.authPK(curAuth.username, key, (buf, cb) => {\n curAuth.agentCtx.sign(key, buf, {}, (err, signed) => {\n if (err) {\n err.level = 'agent';\n this.emit('error', err);\n } else {\n return cb(signed);\n }\n\n tryNextAgentKey();\n });\n });\n } else if (curAuth.type === 'publickey') {\n proto.authPK(curAuth.username, curAuth.key, (buf, cb) => {\n const signature = curAuth.key.sign(buf);\n if (signature instanceof Error) {\n signature.message =\n `Error signing data with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n cb(signature);\n });\n }\n },\n USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => {\n if (curAuth.type === 'keyboard-interactive') {\n const nprompts = (Array.isArray(prompts) ? prompts.length : 0);\n if (nprompts === 0) {\n debug && debug(\n 'Client: Sending automatic USERAUTH_INFO_RESPONSE'\n );\n proto.authInfoRes();\n return;\n }\n // We sent a keyboard-interactive user authentication request and\n // now the server is sending us the prompts we need to present to\n // the user\n curAuth.prompt(\n name,\n instructions,\n '',\n prompts,\n (answers) => {\n proto.authInfoRes(answers);\n }\n );\n }\n },\n REQUEST_SUCCESS: (p, data) => {\n if (callbacks.length)\n callbacks.shift()(false, data);\n },\n REQUEST_FAILURE: (p) => {\n if (callbacks.length)\n callbacks.shift()(true);\n },\n GLOBAL_REQUEST: (p, name, wantReply, data) => {\n switch (name) {\n case 'hostkeys-00@openssh.com':\n // Automatically verify keys before passing to end user\n hostKeysProve(this, data, (err, keys) => {\n if (err)\n return;\n this.emit('hostkeys', keys);\n });\n if (wantReply)\n proto.requestSuccess();\n break;\n default:\n // Auto-reject all other global requests, this can be especially\n // useful if the server is sending us dummy keepalive global\n // requests\n if (wantReply)\n proto.requestFailure();\n }\n },\n CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from server, typically a forwarded TCP or\n // X11 connection\n onCHANNEL_OPEN(this, info);\n },\n CHANNEL_OPEN_CONFIRMATION: (p, info) => {\n const channel = this._chanMgr.get(info.recipient);\n if (typeof channel !== 'function')\n return;\n\n const isSFTP = (channel.type === 'sftp');\n const type = (isSFTP ? 'session' : channel.type);\n const chanInfo = {\n type,\n incoming: {\n id: info.recipient,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const instance = (\n isSFTP\n ? new SFTP(this, chanInfo, { debug })\n : new Channel(this, chanInfo)\n );\n this._chanMgr.update(info.recipient, instance);\n channel(undefined, instance);\n },\n CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },\n CHANNEL_DATA: (p, recipient, data) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n if (type !== STDERR)\n return;\n\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (!channel.stderr.push(data)) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },\n CHANNEL_SUCCESS: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n this._resetKA();\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(false);\n },\n CHANNEL_FAILURE: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n this._resetKA();\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },\n CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n const exit = channel._exit;\n if (exit.code !== undefined)\n return;\n switch (type) {\n case 'exit-status':\n channel.emit('exit', exit.code = data);\n return;\n case 'exit-signal':\n channel.emit('exit',\n exit.code = null,\n exit.signal = `SIG${data.signal}`,\n exit.dump = data.coreDumped,\n exit.desc = data.errorMessage);\n return;\n }\n\n // Keepalive request? OpenSSH will send one as a channel request if\n // there is a channel open\n\n if (wantReply)\n p.channelFailure(channel.outgoing.id);\n },\n CHANNEL_EOF: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.incoming.state !== 'open')\n return;\n channel.incoming.state = 'eof';\n\n if (channel.readable)\n channel.push(null);\n if (channel.stderr.readable)\n channel.stderr.push(null);\n },\n CHANNEL_CLOSE: (p, recipient) => {\n onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient));\n },\n },\n });\n\n sock.pause();\n\n // TODO: check keepalive implementation\n // Keepalive-related\n const kainterval = this.config.keepaliveInterval;\n const kacountmax = this.config.keepaliveCountMax;\n let kacount = 0;\n let katimer;\n const sendKA = () => {\n if (++kacount > kacountmax) {\n clearInterval(katimer);\n if (sock.readable) {\n const err = new Error('Keepalive timeout');\n err.level = 'client-timeout';\n this.emit('error', err);\n sock.destroy();\n }\n return;\n }\n if (isWritable(sock)) {\n // Append dummy callback to keep correct callback order\n callbacks.push(resetKA);\n proto.ping();\n } else {\n clearInterval(katimer);\n }\n };\n function resetKA() {\n if (kainterval > 0) {\n kacount = 0;\n clearInterval(katimer);\n if (isWritable(sock))\n katimer = setInterval(sendKA, kainterval);\n }\n }\n this._resetKA = resetKA;\n\n const onDone = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n if (wasConnected && !sawHeader) {\n const err =\n makeError('Connection lost before handshake', 'protocol', true);\n this.emit('error', err);\n }\n };\n })();\n const onConnect = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n\n wasConnected = true;\n debug && debug('Socket connected');\n this.emit('connect');\n\n cryptoInit.then(() => {\n proto.start();\n sock.on('data', (data) => {\n try {\n proto.parse(data, 0, data.length);\n } catch (ex) {\n this.emit('error', ex);\n try {\n if (isWritable(sock))\n sock.end();\n } catch {}\n }\n });\n\n // Drain stderr if we are connection hopping using an exec stream\n if (sock.stderr && typeof sock.stderr.resume === 'function')\n sock.stderr.resume();\n\n sock.resume();\n }).catch((err) => {\n this.emit('error', err);\n try {\n if (isWritable(sock))\n sock.end();\n } catch {}\n });\n };\n })();\n let wasConnected = false;\n sock.on('connect', onConnect)\n .on('timeout', () => {\n this.emit('timeout');\n }).on('error', (err) => {\n debug && debug(`Socket error: ${err.message}`);\n clearTimeout(this._readyTimeout);\n err.level = 'client-socket';\n this.emit('error', err);\n }).on('end', () => {\n debug && debug('Socket ended');\n onDone();\n proto.cleanup();\n clearTimeout(this._readyTimeout);\n clearInterval(katimer);\n this.emit('end');\n }).on('close', () => {\n debug && debug('Socket closed');\n onDone();\n proto.cleanup();\n clearTimeout(this._readyTimeout);\n clearInterval(katimer);\n this.emit('close');\n\n // Notify outstanding channel requests of disconnection ...\n const callbacks_ = callbacks;\n callbacks = this._callbacks = [];\n const err = new Error('No response from server');\n for (let i = 0; i < callbacks_.length; ++i)\n callbacks_[i](err);\n\n // Simulate error for any channels waiting to be opened\n this._chanMgr.cleanup(err);\n });\n\n // Begin authentication handling ===========================================\n let curAuth;\n let curPartial = null;\n let curAuthsLeft = null;\n const authsAllowed = ['none'];\n if (this.config.password !== undefined)\n authsAllowed.push('password');\n if (privateKey !== undefined)\n authsAllowed.push('publickey');\n if (this._agent !== undefined)\n authsAllowed.push('agent');\n if (this.config.tryKeyboard)\n authsAllowed.push('keyboard-interactive');\n if (privateKey !== undefined\n && this.config.localHostname !== undefined\n && this.config.localUsername !== undefined) {\n authsAllowed.push('hostbased');\n }\n\n if (Array.isArray(authHandler))\n authHandler = makeSimpleAuthHandler(authHandler);\n else if (typeof authHandler !== 'function')\n authHandler = makeSimpleAuthHandler(authsAllowed);\n\n let hasSentAuth = false;\n const doNextAuth = (nextAuth) => {\n if (hasSentAuth)\n return;\n hasSentAuth = true;\n\n if (nextAuth === false) {\n const err = new Error('All configured authentication methods failed');\n err.level = 'client-authentication';\n this.emit('error', err);\n this.end();\n return;\n }\n\n if (typeof nextAuth === 'string') {\n // Remain backwards compatible with original `authHandler()` usage,\n // which only supported passing names of next method to try using data\n // from the `connect()` config object\n\n const type = nextAuth;\n if (authsAllowed.indexOf(type) === -1)\n return skipAuth(`Authentication method not allowed: ${type}`);\n\n const username = this.config.username;\n switch (type) {\n case 'password':\n nextAuth = { type, username, password: this.config.password };\n break;\n case 'publickey':\n nextAuth = { type, username, key: privateKey };\n break;\n case 'hostbased':\n nextAuth = {\n type,\n username,\n key: privateKey,\n localHostname: this.config.localHostname,\n localUsername: this.config.localUsername,\n };\n break;\n case 'agent':\n nextAuth = {\n type,\n username,\n agentCtx: new AgentContext(this._agent),\n };\n break;\n case 'keyboard-interactive':\n nextAuth = {\n type,\n username,\n prompt: (...args) => this.emit('keyboard-interactive', ...args),\n };\n break;\n case 'none':\n nextAuth = { type, username };\n break;\n default:\n return skipAuth(\n `Skipping unsupported authentication method: ${nextAuth}`\n );\n }\n } else if (typeof nextAuth !== 'object' || nextAuth === null) {\n return skipAuth(\n `Skipping invalid authentication attempt: ${nextAuth}`\n );\n } else {\n const username = nextAuth.username;\n if (typeof username !== 'string') {\n return skipAuth(\n `Skipping invalid authentication attempt: ${nextAuth}`\n );\n }\n const type = nextAuth.type;\n switch (type) {\n case 'password': {\n const { password } = nextAuth;\n if (typeof password !== 'string' && !Buffer.isBuffer(password))\n return skipAuth('Skipping invalid password auth attempt');\n nextAuth = { type, username, password };\n break;\n }\n case 'publickey': {\n const key = parseKey(nextAuth.key, nextAuth.passphrase);\n if (key instanceof Error)\n return skipAuth('Skipping invalid key auth attempt');\n if (!key.isPrivateKey())\n return skipAuth('Skipping non-private key');\n nextAuth = { type, username, key };\n break;\n }\n case 'hostbased': {\n const { localHostname, localUsername } = nextAuth;\n const key = parseKey(nextAuth.key, nextAuth.passphrase);\n if (key instanceof Error\n || typeof localHostname !== 'string'\n || typeof localUsername !== 'string') {\n return skipAuth('Skipping invalid hostbased auth attempt');\n }\n if (!key.isPrivateKey())\n return skipAuth('Skipping non-private key');\n nextAuth = { type, username, key, localHostname, localUsername };\n break;\n }\n case 'agent': {\n let agent = nextAuth.agent;\n if (typeof agent === 'string' && agent.length) {\n agent = createAgent(agent);\n } else if (!isAgent(agent)) {\n return skipAuth(\n `Skipping invalid agent: ${nextAuth.agent}`\n );\n }\n nextAuth = { type, username, agentCtx: new AgentContext(agent) };\n break;\n }\n case 'keyboard-interactive': {\n const { prompt } = nextAuth;\n if (typeof prompt !== 'function') {\n return skipAuth(\n 'Skipping invalid keyboard-interactive auth attempt'\n );\n }\n nextAuth = { type, username, prompt };\n break;\n }\n case 'none':\n nextAuth = { type, username };\n break;\n default:\n return skipAuth(\n `Skipping unsupported authentication method: ${nextAuth}`\n );\n }\n }\n curAuth = nextAuth;\n\n // Begin authentication method's process\n try {\n const username = curAuth.username;\n switch (curAuth.type) {\n case 'password':\n proto.authPassword(username, curAuth.password);\n break;\n case 'publickey':\n proto.authPK(username, curAuth.key);\n break;\n case 'hostbased':\n proto.authHostbased(username,\n curAuth.key,\n curAuth.localHostname,\n curAuth.localUsername,\n (buf, cb) => {\n const signature = curAuth.key.sign(buf);\n if (signature instanceof Error) {\n signature.message =\n `Error while signing with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n\n cb(signature);\n });\n break;\n case 'agent':\n curAuth.agentCtx.init((err) => {\n if (err) {\n err.level = 'agent';\n this.emit('error', err);\n return tryNextAuth();\n }\n tryNextAgentKey();\n });\n break;\n case 'keyboard-interactive':\n proto.authKeyboard(username);\n break;\n case 'none':\n proto.authNone(username);\n break;\n }\n } finally {\n hasSentAuth = false;\n }\n };\n\n function skipAuth(msg) {\n debug && debug(msg);\n process.nextTick(tryNextAuth);\n }\n\n function tryNextAuth() {\n hasSentAuth = false;\n const auth = authHandler(curAuthsLeft, curPartial, doNextAuth);\n if (hasSentAuth || auth === undefined)\n return;\n doNextAuth(auth);\n }\n\n const tryNextAgentKey = () => {\n if (curAuth.type === 'agent') {\n const key = curAuth.agentCtx.nextKey();\n if (key === false) {\n debug && debug('Agent: No more keys left to try');\n debug && debug('Client: agent auth failed');\n tryNextAuth();\n } else {\n const pos = curAuth.agentCtx.pos();\n debug && debug(`Agent: Trying key #${pos + 1}`);\n proto.authPK(curAuth.username, key);\n }\n }\n };\n\n const startTimeout = () => {\n if (this.config.readyTimeout > 0) {\n this._readyTimeout = setTimeout(() => {\n const err = new Error('Timed out while waiting for handshake');\n err.level = 'client-timeout';\n this.emit('error', err);\n sock.destroy();\n }, this.config.readyTimeout);\n }\n };\n\n if (!cfg.sock) {\n let host = this.config.host;\n const forceIPv4 = this.config.forceIPv4;\n const forceIPv6 = this.config.forceIPv6;\n\n debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`);\n\n const doConnect = () => {\n startTimeout();\n sock.connect({\n host,\n port: this.config.port,\n localAddress: this.config.localAddress,\n localPort: this.config.localPort\n });\n sock.setNoDelay(true);\n sock.setMaxListeners(0);\n sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0);\n };\n\n if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) {\n doConnect();\n } else {\n dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => {\n if (err) {\n const type = (forceIPv4 ? 'IPv4' : 'IPv6');\n const error = new Error(\n `Error while looking up ${type} address for '${host}': ${err}`\n );\n clearTimeout(this._readyTimeout);\n error.level = 'client-dns';\n this.emit('error', error);\n this.emit('close');\n return;\n }\n host = address;\n doConnect();\n });\n }\n } else {\n // Custom socket passed in\n startTimeout();\n if (typeof sock.connecting === 'boolean') {\n // net.Socket\n\n if (!sock.connecting) {\n // Already connected\n onConnect();\n }\n } else {\n // Assume socket/stream is already \"connected\"\n onConnect();\n }\n }\n\n return this;\n }\n\n end() {\n if (this._sock && isWritable(this._sock)) {\n this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n this._sock.end();\n }\n return this;\n }\n\n destroy() {\n this._sock && isWritable(this._sock) && this._sock.destroy();\n return this;\n }\n\n exec(cmd, opts, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) };\n\n openChannel(this, 'session', extraOpts, (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n const todo = [];\n\n function reqCb(err) {\n if (err) {\n chan.close();\n cb(err);\n return;\n }\n if (todo.length)\n todo.shift()();\n }\n\n if (this.config.allowAgentFwd === true\n || (opts\n && opts.agentForward === true\n && this._agent !== undefined)) {\n todo.push(() => reqAgentFwd(chan, reqCb));\n }\n\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.env === 'object' && opts.env !== null)\n reqEnv(chan, opts.env);\n if ((typeof opts.pty === 'object' && opts.pty !== null)\n || opts.pty === true) {\n todo.push(() => reqPty(chan, opts.pty, reqCb));\n }\n if ((typeof opts.x11 === 'object' && opts.x11 !== null)\n || opts.x11 === 'number'\n || opts.x11 === true) {\n todo.push(() => reqX11(chan, opts.x11, reqCb));\n }\n }\n\n todo.push(() => reqExec(chan, cmd, opts, cb));\n todo.shift()();\n });\n\n return this;\n }\n\n shell(wndopts, opts, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof wndopts === 'function') {\n cb = wndopts;\n wndopts = opts = undefined;\n } else if (typeof opts === 'function') {\n cb = opts;\n opts = undefined;\n }\n if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) {\n opts = wndopts;\n wndopts = undefined;\n }\n\n openChannel(this, 'session', (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n const todo = [];\n\n function reqCb(err) {\n if (err) {\n chan.close();\n cb(err);\n return;\n }\n if (todo.length)\n todo.shift()();\n }\n\n if (this.config.allowAgentFwd === true\n || (opts\n && opts.agentForward === true\n && this._agent !== undefined)) {\n todo.push(() => reqAgentFwd(chan, reqCb));\n }\n\n if (wndopts !== false)\n todo.push(() => reqPty(chan, wndopts, reqCb));\n\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.env === 'object' && opts.env !== null)\n reqEnv(chan, opts.env);\n if ((typeof opts.x11 === 'object' && opts.x11 !== null)\n || opts.x11 === 'number'\n || opts.x11 === true) {\n todo.push(() => reqX11(chan, opts.x11, reqCb));\n }\n }\n\n todo.push(() => reqShell(chan, cb));\n todo.shift()();\n });\n\n return this;\n }\n\n subsys(name, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n openChannel(this, 'session', (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n reqSubsystem(chan, name, (err, stream) => {\n if (err) {\n cb(err);\n return;\n }\n\n cb(undefined, stream);\n });\n });\n\n return this;\n }\n\n forwardIn(bindAddr, bindPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request for the server to start forwarding TCP connections to us\n // on a particular address and port\n\n const wantReply = (typeof cb === 'function');\n\n if (wantReply) {\n this._callbacks.push((had_err, data) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${bindAddr}:${bindPort}`));\n return;\n }\n\n let realPort = bindPort;\n if (bindPort === 0 && data && data.length >= 4) {\n realPort = readUInt32BE(data, 0);\n if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG))\n bindPort = realPort;\n }\n\n this._forwarding[`${bindAddr}:${bindPort}`] = realPort;\n\n cb(undefined, realPort);\n });\n }\n\n this._protocol.tcpipForward(bindAddr, bindPort, wantReply);\n\n return this;\n }\n\n unforwardIn(bindAddr, bindPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request to stop forwarding us new connections for a particular\n // address and port\n\n const wantReply = (typeof cb === 'function');\n\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`));\n return;\n }\n\n delete this._forwarding[`${bindAddr}:${bindPort}`];\n\n cb();\n });\n }\n\n this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply);\n\n return this;\n }\n\n forwardOut(srcIP, srcPort, dstIP, dstPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request to forward a TCP connection to the server\n\n const cfg = {\n srcIP: srcIP,\n srcPort: srcPort,\n dstIP: dstIP,\n dstPort: dstPort\n };\n\n if (typeof cb !== 'function')\n cb = noop;\n\n openChannel(this, 'direct-tcpip', cfg, cb);\n\n return this;\n }\n\n openssh_noMoreSessions(cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to disable future sessions'));\n return;\n }\n\n cb();\n });\n }\n\n this._protocol.openssh_noMoreSessions(wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_forwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${socketPath}`));\n return;\n }\n this._forwardingUnix[socketPath] = true;\n cb();\n });\n }\n\n this._protocol.openssh_streamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_unforwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to unbind from ${socketPath}`));\n return;\n }\n delete this._forwardingUnix[socketPath];\n cb();\n });\n }\n\n this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_forwardOutStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof cb !== 'function')\n cb = noop;\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb);\n return this;\n }\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n sftp(cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n openChannel(this, 'sftp', (err, sftp) => {\n if (err) {\n cb(err);\n return;\n }\n\n reqSubsystem(sftp, 'sftp', (err, sftp_) => {\n if (err) {\n cb(err);\n return;\n }\n\n function removeListeners() {\n sftp.removeListener('ready', onReady);\n sftp.removeListener('error', onError);\n sftp.removeListener('exit', onExit);\n sftp.removeListener('close', onExit);\n }\n\n function onReady() {\n // TODO: do not remove exit/close in case remote end closes the\n // channel abruptly and we need to notify outstanding callbacks\n removeListeners();\n cb(undefined, sftp);\n }\n\n function onError(err) {\n removeListeners();\n cb(err);\n }\n\n function onExit(code, signal) {\n removeListeners();\n let msg;\n if (typeof code === 'number')\n msg = `Received exit code ${code} while establishing SFTP session`;\n else if (signal !== undefined)\n msg = `Received signal ${signal} while establishing SFTP session`;\n else\n msg = 'Received unexpected SFTP session termination';\n const err = new Error(msg);\n err.code = code;\n err.signal = signal;\n cb(err);\n }\n\n sftp.on('ready', onReady)\n .on('error', onError)\n .on('exit', onExit)\n .on('close', onExit);\n\n sftp._init();\n });\n });\n\n return this;\n }\n}\n\nfunction openChannel(self, type, opts, cb) {\n // Ask the server to open a channel for some purpose\n // (e.g. session (sftp, exec, shell), or forwarding a TCP connection\n const initWindow = MAX_WINDOW;\n const maxPacket = PACKET_SIZE;\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const wrapper = (err, stream) => {\n cb(err, stream);\n };\n wrapper.type = type;\n\n const localChan = self._chanMgr.add(wrapper);\n\n if (localChan === -1) {\n cb(new Error('No free channels available'));\n return;\n }\n\n switch (type) {\n case 'session':\n case 'sftp':\n self._protocol.session(localChan, initWindow, maxPacket);\n break;\n case 'direct-tcpip':\n self._protocol.directTcpip(localChan, initWindow, maxPacket, opts);\n break;\n case 'direct-streamlocal@openssh.com':\n self._protocol.openssh_directStreamLocal(\n localChan, initWindow, maxPacket, opts\n );\n break;\n default:\n throw new Error(`Unsupported channel type: ${type}`);\n }\n}\n\nfunction reqX11(chan, screen, cb) {\n // Asks server to start sending us X11 connections\n const cfg = {\n single: false,\n protocol: 'MIT-MAGIC-COOKIE-1',\n cookie: undefined,\n screen: 0\n };\n\n if (typeof screen === 'function') {\n cb = screen;\n } else if (typeof screen === 'object' && screen !== null) {\n if (typeof screen.single === 'boolean')\n cfg.single = screen.single;\n if (typeof screen.screen === 'number')\n cfg.screen = screen.screen;\n if (typeof screen.protocol === 'string')\n cfg.protocol = screen.protocol;\n if (typeof screen.cookie === 'string')\n cfg.cookie = screen.cookie;\n else if (Buffer.isBuffer(screen.cookie))\n cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length);\n }\n if (cfg.cookie === undefined)\n cfg.cookie = randomCookie();\n\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n if (wantReply)\n cb(new Error('Channel is not open'));\n return;\n }\n\n if (wantReply) {\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to request X11'));\n return;\n }\n\n chan._hasX11 = true;\n ++chan._client._acceptX11;\n chan.once('close', () => {\n if (chan._client._acceptX11)\n --chan._client._acceptX11;\n });\n\n cb();\n });\n }\n\n chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply);\n}\n\nfunction reqPty(chan, opts, cb) {\n let rows = 24;\n let cols = 80;\n let width = 640;\n let height = 480;\n let term = 'vt100';\n let modes = null;\n\n if (typeof opts === 'function') {\n cb = opts;\n } else if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.rows === 'number')\n rows = opts.rows;\n if (typeof opts.cols === 'number')\n cols = opts.cols;\n if (typeof opts.width === 'number')\n width = opts.width;\n if (typeof opts.height === 'number')\n height = opts.height;\n if (typeof opts.term === 'string')\n term = opts.term;\n if (typeof opts.modes === 'object')\n modes = opts.modes;\n }\n\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n if (wantReply)\n cb(new Error('Channel is not open'));\n return;\n }\n\n if (wantReply) {\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to request a pseudo-terminal'));\n return;\n }\n cb();\n });\n }\n\n chan._client._protocol.pty(chan.outgoing.id,\n rows,\n cols,\n height,\n width,\n term,\n modes,\n wantReply);\n}\n\nfunction reqAgentFwd(chan, cb) {\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n wantReply && cb(new Error('Channel is not open'));\n return;\n }\n if (chan._client._agentFwdEnabled) {\n wantReply && cb(false);\n return;\n }\n\n chan._client._agentFwdEnabled = true;\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n chan._client._agentFwdEnabled = false;\n if (wantReply) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to request agent forwarding'));\n }\n return;\n }\n\n if (wantReply)\n cb();\n });\n\n chan._client._protocol.openssh_agentForward(chan.outgoing.id, true);\n}\n\nfunction reqShell(chan, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to open shell'));\n return;\n }\n chan.subtype = 'shell';\n cb(undefined, chan);\n });\n\n chan._client._protocol.shell(chan.outgoing.id, true);\n}\n\nfunction reqExec(chan, cmd, opts, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to exec'));\n return;\n }\n chan.subtype = 'exec';\n chan.allowHalfOpen = (opts.allowHalfOpen !== false);\n cb(undefined, chan);\n });\n\n chan._client._protocol.exec(chan.outgoing.id, cmd, true);\n}\n\nfunction reqEnv(chan, env) {\n if (chan.outgoing.state !== 'open')\n return;\n\n const keys = Object.keys(env || {});\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n const val = env[key];\n chan._client._protocol.env(chan.outgoing.id, key, val, false);\n }\n}\n\nfunction reqSubsystem(chan, name, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to start subsystem: ${name}`));\n return;\n }\n chan.subtype = 'subsystem';\n cb(undefined, chan);\n });\n\n chan._client._protocol.subsystem(chan.outgoing.id, name, true);\n}\n\n// TODO: inline implementation into single call site\nfunction onCHANNEL_OPEN(self, info) {\n // The server is trying to open a channel with us, this is usually when\n // we asked the server to forward us connections on some port and now they\n // are asking us to accept/deny an incoming connection on their side\n\n let localChan = -1;\n let reason;\n\n const accept = () => {\n const chanInfo = {\n type: info.type,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const stream = new Channel(self, chanInfo);\n self._chanMgr.update(localChan, stream);\n\n self._protocol.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n return stream;\n };\n const reject = () => {\n if (reason === undefined) {\n if (localChan === -1)\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n else\n reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;\n }\n\n if (localChan !== -1)\n self._chanMgr.remove(localChan);\n\n self._protocol.channelOpenFail(info.sender, reason, '');\n };\n const reserveChannel = () => {\n localChan = self._chanMgr.add();\n\n if (localChan === -1) {\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of incoming channel open: '\n + 'no channels available'\n );\n }\n }\n\n return (localChan !== -1);\n };\n\n const data = info.data;\n switch (info.type) {\n case 'forwarded-tcpip': {\n const val = self._forwarding[`${data.destIP}:${data.destPort}`];\n if (val !== undefined && reserveChannel()) {\n if (data.destPort === 0)\n data.destPort = val;\n self.emit('tcp connection', data, accept, reject);\n return;\n }\n break;\n }\n case 'forwarded-streamlocal@openssh.com':\n if (self._forwardingUnix[data.socketPath] !== undefined\n && reserveChannel()) {\n self.emit('unix connection', data, accept, reject);\n return;\n }\n break;\n case 'auth-agent@openssh.com':\n if (self._agentFwdEnabled\n && typeof self._agent.getStream === 'function'\n && reserveChannel()) {\n self._agent.getStream((err, stream) => {\n if (err)\n return reject();\n\n const upstream = accept();\n upstream.pipe(stream).pipe(upstream);\n });\n return;\n }\n break;\n case 'x11':\n if (self._acceptX11 !== 0 && reserveChannel()) {\n self.emit('x11', data, accept, reject);\n return;\n }\n break;\n default:\n // Automatically reject any unsupported channel open requests\n reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of unsupported incoming channel open '\n + `type: ${info.type}`\n );\n }\n }\n\n if (reason === undefined) {\n reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of unexpected incoming channel open for: '\n + info.type\n );\n }\n }\n\n reject();\n}\n\nconst randomCookie = (() => {\n const buffer = Buffer.allocUnsafe(16);\n return () => {\n randomFillSync(buffer, 0, 16);\n return buffer.hexSlice(0, 16);\n };\n})();\n\nfunction makeSimpleAuthHandler(authList) {\n if (!Array.isArray(authList))\n throw new Error('authList must be an array');\n\n let a = 0;\n return (authsLeft, partialSuccess, cb) => {\n if (a === authList.length)\n return false;\n return authList[a++];\n };\n}\n\nfunction hostKeysProve(client, keys_, cb) {\n if (!client._sock || !isWritable(client._sock))\n return;\n\n if (typeof cb !== 'function')\n cb = noop;\n\n if (!Array.isArray(keys_))\n throw new TypeError('Invalid keys argument type');\n\n const keys = [];\n for (const key of keys_) {\n const parsed = parseKey(key);\n if (parsed instanceof Error)\n throw parsed;\n keys.push(parsed);\n }\n\n if (!client.config.strictVendor\n || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) {\n client._callbacks.push((had_err, data) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Server failed to prove supplied keys'));\n return;\n }\n\n // TODO: move all of this parsing/verifying logic out of the client?\n const ret = [];\n let keyIdx = 0;\n bufferParser.init(data, 0);\n while (bufferParser.avail()) {\n if (keyIdx === keys.length)\n break;\n const key = keys[keyIdx++];\n const keyPublic = key.getPublicSSH();\n\n const sigEntry = bufferParser.readString();\n sigParser.init(sigEntry, 0);\n const type = sigParser.readString(true);\n let value = sigParser.readString();\n\n let algo;\n if (type !== key.type) {\n if (key.type === 'ssh-rsa') {\n switch (type) {\n case 'rsa-sha2-256':\n algo = 'sha256';\n break;\n case 'rsa-sha2-512':\n algo = 'sha512';\n break;\n default:\n continue;\n }\n } else {\n continue;\n }\n }\n\n const sessionID = client._protocol._kex.sessionID;\n const verifyData = Buffer.allocUnsafe(\n 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length\n );\n let p = 0;\n writeUInt32BE(verifyData, 29, p);\n verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);\n writeUInt32BE(verifyData, sessionID.length, p += 29);\n bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4);\n writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length);\n bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4);\n\n if (!(value = sigSSHToASN1(value, type)))\n continue;\n if (key.verify(verifyData, value, algo) === true)\n ret.push(key);\n }\n sigParser.clear();\n bufferParser.clear();\n\n cb(null, ret);\n });\n\n client._protocol.openssh_hostKeysProve(keys);\n return;\n }\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n}\n\nmodule.exports = Client;\n","'use strict';\n\nconst { Agent: HttpAgent } = require('http');\nconst { Agent: HttpsAgent } = require('https');\nconst { connect: tlsConnect } = require('tls');\n\nlet Client;\n\nfor (const ctor of [HttpAgent, HttpsAgent]) {\n class SSHAgent extends ctor {\n constructor(connectCfg, agentOptions) {\n super(agentOptions);\n\n this._connectCfg = connectCfg;\n this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost';\n }\n\n createConnection(options, cb) {\n const srcIP = (options && options.localAddress) || this._defaultSrcIP;\n const srcPort = (options && options.localPort) || 0;\n const dstIP = options.host;\n const dstPort = options.port;\n\n if (Client === undefined)\n Client = require('./client.js');\n\n const client = new Client();\n let triedForward = false;\n client.on('ready', () => {\n client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => {\n triedForward = true;\n if (err) {\n client.end();\n return cb(err);\n }\n stream.once('close', () => client.end());\n cb(null, decorateStream(stream, ctor, options));\n });\n }).on('error', cb).on('close', () => {\n if (!triedForward)\n cb(new Error('Unexpected connection close'));\n }).connect(this._connectCfg);\n }\n }\n\n exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent;\n}\n\nfunction noop() {}\n\nfunction decorateStream(stream, ctor, options) {\n if (ctor === HttpAgent) {\n // HTTP\n stream.setKeepAlive = noop;\n stream.setNoDelay = noop;\n stream.setTimeout = noop;\n stream.ref = noop;\n stream.unref = noop;\n stream.destroySoon = stream.destroy;\n return stream;\n }\n\n // HTTPS\n options.socket = stream;\n const wrapped = tlsConnect(options);\n\n // This is a workaround for a regression in node v12.16.3+\n // https://github.com/nodejs/node/issues/35904\n const onClose = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n if (stream.isPaused())\n stream.resume();\n };\n })();\n // 'end' listener is needed because 'close' is not emitted in some scenarios\n // in node v12.x for some unknown reason\n wrapped.on('end', onClose).on('close', onClose);\n\n return wrapped;\n}\n","'use strict';\n\nconst {\n AgentProtocol,\n BaseAgent,\n createAgent,\n CygwinAgent,\n OpenSSHAgent,\n PageantAgent,\n} = require('./agent.js');\nconst {\n SSHTTPAgent: HTTPAgent,\n SSHTTPSAgent: HTTPSAgent,\n} = require('./http-agents.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst {\n flagsToString,\n OPEN_MODE,\n STATUS_CODE,\n stringToFlags,\n} = require('./protocol/SFTP.js');\n\nmodule.exports = {\n AgentProtocol,\n BaseAgent,\n createAgent,\n Client: require('./client.js'),\n CygwinAgent,\n HTTPAgent,\n HTTPSAgent,\n OpenSSHAgent,\n PageantAgent,\n Server: require('./server.js'),\n utils: {\n parseKey,\n sftp: {\n flagsToString,\n OPEN_MODE,\n STATUS_CODE,\n stringToFlags,\n },\n },\n};\n","/*\n TODO:\n * Replace `buffer._pos` usage in keyParser.js and elsewhere\n * Utilize optional \"writev\" support when writing packets from\n cipher.encrypt()\n * Built-in support for automatic re-keying, on by default\n * Revisit receiving unexpected/unknown packets\n * Error (fatal or otherwise) or ignore or pass on to user (in some or all\n cases)?\n * Including server/client check for single directional packet types?\n * Check packets for validity or bail as early as possible?\n * Automatic re-key every 2**31 packets after the last key exchange (sent or\n received), as suggested by RFC4344. OpenSSH currently does this.\n * Automatic re-key every so many blocks depending on cipher. RFC4344:\n Because of a birthday property of block ciphers and some modes of\n operation, implementations must be careful not to encrypt too many\n blocks with the same encryption key.\n\n Let L be the block length (in bits) of an SSH encryption method's\n block cipher (e.g., 128 for AES). If L is at least 128, then, after\n rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4)\n blocks before rekeying again. If L is at least 128, then SSH\n implementations should also attempt to force a rekey before receiving\n more than 2**(L/4) blocks. If L is less than 128 (which is the case\n for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then,\n although it may be too expensive to rekey every 2**(L/4) blocks, it\n is still advisable for SSH implementations to follow the original\n recommendation in [RFC4253]: rekey at least once for every gigabyte\n of transmitted data.\n\n Note that if L is less than or equal to 128, then the recommendation\n in this subsection supersedes the recommendation in Section 3.1. If\n an SSH implementation uses a block cipher with a larger block size\n (e.g., Rijndael with 256-bit blocks), then the recommendations in\n Section 3.1 may supersede the recommendations in this subsection\n (depending on the lengths of the packets).\n*/\n\n'use strict';\n\nconst { inspect } = require('util');\n\nconst { bindingAvailable, NullCipher, NullDecipher } = require('./crypto.js');\nconst {\n COMPAT_CHECKS,\n DISCONNECT_REASON,\n MESSAGE,\n SIGNALS,\n TERMINAL_MODE,\n} = require('./constants.js');\nconst {\n DEFAULT_KEXINIT,\n KexInit,\n kexinit,\n onKEXPayload,\n} = require('./kex.js');\nconst {\n parseKey,\n} = require('./keyParser.js');\nconst MESSAGE_HANDLERS = require('./handlers.js');\nconst {\n bufferCopy,\n bufferFill,\n bufferSlice,\n convertSignature,\n sendPacket,\n writeUInt32BE,\n} = require('./utils.js');\nconst {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n} = require('./zlib.js');\n\nconst MODULE_VER = require('../../package.json').version;\n\nconst VALID_DISCONNECT_REASONS = new Map(\n Object.values(DISCONNECT_REASON).map((n) => [n, 1])\n);\nconst IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`);\nconst IDENT = Buffer.from(`${IDENT_RAW}\\r\\n`);\nconst MAX_LINE_LEN = 8192;\nconst MAX_LINES = 1024;\nconst PING_PAYLOAD = Buffer.from([\n MESSAGE.GLOBAL_REQUEST,\n // \"keepalive@openssh.com\"\n 0, 0, 0, 21,\n 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115,\n 115, 104, 46, 99, 111, 109,\n // Request a reply\n 1,\n]);\nconst NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]);\n\nfunction noop() {}\n\n/*\n Inbound:\n * kexinit payload (needed only until exchange hash is generated)\n * raw ident\n * rekey packet queue\n * expected packet (implemented as separate _parse() function?)\n Outbound:\n * kexinit payload (needed only until exchange hash is generated)\n * rekey packet queue\n * kex secret (needed only until NEWKEYS)\n * exchange hash (needed only until NEWKEYS)\n * session ID (set to exchange hash from initial handshake)\n*/\nclass Protocol {\n constructor(config) {\n const onWrite = config.onWrite;\n if (typeof onWrite !== 'function')\n throw new Error('Missing onWrite function');\n this._onWrite = (data) => { onWrite(data); };\n\n const onError = config.onError;\n if (typeof onError !== 'function')\n throw new Error('Missing onError function');\n this._onError = (err) => { onError(err); };\n\n const debug = config.debug;\n this._debug = (typeof debug === 'function'\n ? (msg) => { debug(msg); }\n : undefined);\n\n const onHeader = config.onHeader;\n this._onHeader = (typeof onHeader === 'function'\n ? (...args) => { onHeader(...args); }\n : noop);\n\n const onPacket = config.onPacket;\n this._onPacket = (typeof onPacket === 'function'\n ? () => { onPacket(); }\n : noop);\n\n let onHandshakeComplete = config.onHandshakeComplete;\n if (typeof onHandshakeComplete !== 'function')\n onHandshakeComplete = noop;\n this._onHandshakeComplete = (...args) => {\n this._debug && this._debug('Handshake completed');\n\n // Process packets queued during a rekey where necessary\n const oldQueue = this._queue;\n if (oldQueue) {\n this._queue = undefined;\n this._debug && this._debug(\n `Draining outbound queue (${oldQueue.length}) ...`\n );\n for (let i = 0; i < oldQueue.length; ++i) {\n const data = oldQueue[i];\n // data === payload only\n\n // XXX: hacky\n let finalized = this._packetRW.write.finalize(data);\n if (finalized === data) {\n const packet = this._cipher.allocPacket(data.length);\n packet.set(data, 5);\n finalized = packet;\n }\n\n sendPacket(this, finalized);\n }\n this._debug && this._debug('... finished draining outbound queue');\n }\n\n onHandshakeComplete(...args);\n };\n this._queue = undefined;\n\n const messageHandlers = config.messageHandlers;\n if (typeof messageHandlers === 'object' && messageHandlers !== null)\n this._handlers = messageHandlers;\n else\n this._handlers = {};\n\n this._onPayload = onPayload.bind(this);\n\n this._server = !!config.server;\n this._banner = undefined;\n let greeting;\n if (this._server) {\n if (typeof config.hostKeys !== 'object' || config.hostKeys === null)\n throw new Error('Missing server host key(s)');\n this._hostKeys = config.hostKeys;\n\n // Greeting displayed before the ssh identification string is sent, this\n // is usually ignored by most clients\n if (typeof config.greeting === 'string' && config.greeting.length) {\n greeting = (config.greeting.slice(-2) === '\\r\\n'\n ? config.greeting\n : `${config.greeting}\\r\\n`);\n }\n\n // Banner shown after the handshake completes, but before user\n // authentication begins\n if (typeof config.banner === 'string' && config.banner.length) {\n this._banner = (config.banner.slice(-2) === '\\r\\n'\n ? config.banner\n : `${config.banner}\\r\\n`);\n }\n } else {\n this._hostKeys = undefined;\n }\n\n let offer = config.offer;\n if (typeof offer !== 'object' || offer === null)\n offer = DEFAULT_KEXINIT;\n else if (offer.constructor !== KexInit)\n offer = new KexInit(offer);\n this._kex = undefined;\n this._kexinit = undefined;\n this._offer = offer;\n this._cipher = new NullCipher(0, this._onWrite);\n this._decipher = undefined;\n this._skipNextInboundPacket = false;\n this._packetRW = {\n read: new PacketReader(),\n write: new PacketWriter(this),\n };\n this._hostVerifier = (!this._server\n && typeof config.hostVerifier === 'function'\n ? config.hostVerifier\n : undefined);\n\n this._parse = parseHeader;\n this._buffer = undefined;\n this._authsQueue = [];\n this._authenticated = false;\n this._remoteIdentRaw = undefined;\n let sentIdent;\n if (typeof config.ident === 'string') {\n this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`);\n\n sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2);\n sentIdent.set(this._identRaw, 0);\n sentIdent[sentIdent.length - 2] = 13; // '\\r'\n sentIdent[sentIdent.length - 1] = 10; // '\\n'\n } else if (Buffer.isBuffer(config.ident)) {\n const fullIdent = Buffer.allocUnsafe(8 + config.ident.length);\n fullIdent.latin1Write('SSH-2.0-', 0, 8);\n fullIdent.set(config.ident, 8);\n this._identRaw = fullIdent;\n\n sentIdent = Buffer.allocUnsafe(fullIdent.length + 2);\n sentIdent.set(fullIdent, 0);\n sentIdent[sentIdent.length - 2] = 13; // '\\r'\n sentIdent[sentIdent.length - 1] = 10; // '\\n'\n } else {\n this._identRaw = IDENT_RAW;\n sentIdent = IDENT;\n }\n this._compatFlags = 0;\n\n if (this._debug) {\n if (bindingAvailable)\n this._debug('Custom crypto binding available');\n else\n this._debug('Custom crypto binding not available');\n }\n\n this._debug && this._debug(\n `Local ident: ${inspect(this._identRaw.toString())}`\n );\n this.start = () => {\n this.start = undefined;\n if (greeting)\n this._onWrite(greeting);\n this._onWrite(sentIdent);\n };\n }\n _destruct(reason) {\n this._packetRW.read.cleanup();\n this._packetRW.write.cleanup();\n this._cipher && this._cipher.free();\n this._decipher && this._decipher.free();\n if (typeof reason !== 'string' || reason.length === 0)\n reason = 'fatal error';\n this.parse = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };\n this._onWrite = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };\n this._destruct = undefined;\n }\n cleanup() {\n this._destruct && this._destruct();\n }\n parse(chunk, i, len) {\n while (i < len)\n i = this._parse(chunk, i, len);\n }\n\n // Protocol message API\n\n // ===========================================================================\n // Common/Shared =============================================================\n // ===========================================================================\n\n // Global\n // ------\n disconnect(reason) {\n const pktLen = 1 + 4 + 4 + 4;\n // We don't use _packetRW.write.* here because we need to make sure that\n // we always get a full packet allocated because this message can be sent\n // at any time -- even during a key exchange\n let p = this._packetRW.write.allocStartKEX;\n const packet = this._packetRW.write.alloc(pktLen, true);\n const end = p + pktLen;\n\n if (!VALID_DISCONNECT_REASONS.has(reason))\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n\n packet[p] = MESSAGE.DISCONNECT;\n writeUInt32BE(packet, reason, ++p);\n packet.fill(0, p += 4, end);\n\n this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`);\n sendPacket(this, this._packetRW.write.finalize(packet, true), true);\n }\n ping() {\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(PING_PAYLOAD.length);\n\n packet.set(PING_PAYLOAD, p);\n\n this._debug && this._debug(\n 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n rekey() {\n if (this._kexinit === undefined) {\n this._debug && this._debug('Outbound: Initiated explicit rekey');\n this._queue = [];\n kexinit(this);\n } else {\n this._debug && this._debug('Outbound: Ignoring rekey during handshake');\n }\n }\n\n // 'ssh-connection' service-specific\n // ---------------------------------\n requestSuccess(data) {\n let p = this._packetRW.write.allocStart;\n let packet;\n if (Buffer.isBuffer(data)) {\n packet = this._packetRW.write.alloc(1 + data.length);\n\n packet[p] = MESSAGE.REQUEST_SUCCESS;\n\n packet.set(data, ++p);\n } else {\n packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.REQUEST_SUCCESS;\n }\n\n this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n requestFailure() {\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.REQUEST_FAILURE;\n\n this._debug && this._debug('Outbound: Sending REQUEST_FAILURE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelSuccess(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_SUCCESS;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelFailure(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_FAILURE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelEOF(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_EOF;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelClose(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_CLOSE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelWindowAdjust(chan, amount) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, amount, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelData(chan, data) {\n const isBuffer = Buffer.isBuffer(data);\n const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen);\n\n packet[p] = MESSAGE.CHANNEL_DATA;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, dataLen, p += 4);\n\n if (isBuffer)\n packet.set(data, p += 4);\n else\n packet.utf8Write(data, p += 4, dataLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelExtData(chan, data, type) {\n const isBuffer = Buffer.isBuffer(data);\n const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen);\n\n packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, type, p += 4);\n\n writeUInt32BE(packet, dataLen, p += 4);\n\n if (isBuffer)\n packet.set(data, p += 4);\n else\n packet.utf8Write(data, p += 4, dataLen);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelOpenConfirm(remote, local, initWindow, maxPacket) {\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION;\n\n writeUInt32BE(packet, remote, ++p);\n\n writeUInt32BE(packet, local, p += 4);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelOpenFail(remote, reason, desc) {\n if (typeof desc !== 'string')\n desc = '';\n\n const descLen = Buffer.byteLength(desc);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE;\n\n writeUInt32BE(packet, remote, ++p);\n\n writeUInt32BE(packet, reason, p += 4);\n\n writeUInt32BE(packet, descLen, p += 4);\n\n p += 4;\n if (descLen) {\n packet.utf8Write(desc, p, descLen);\n p += descLen;\n }\n\n writeUInt32BE(packet, 0, p); // Empty language tag\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // ===========================================================================\n // Client-specific ===========================================================\n // ===========================================================================\n\n // Global\n // ------\n service(name) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + nameLen);\n\n packet[p] = MESSAGE.SERVICE_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // 'ssh-userauth' service-specific\n // -------------------------------\n authPassword(username, password, newPassword) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n const passLen = Buffer.byteLength(password);\n const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen\n + (newPassword ? 4 + newPassLen : 0)\n );\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 8, p += 14);\n packet.utf8Write('password', p += 4, 8);\n\n packet[p += 8] = (newPassword ? 1 : 0);\n\n writeUInt32BE(packet, passLen, ++p);\n if (Buffer.isBuffer(password))\n bufferCopy(password, packet, 0, passLen, p += 4);\n else\n packet.utf8Write(password, p += 4, passLen);\n\n if (newPassword) {\n writeUInt32BE(packet, newPassLen, p += passLen);\n if (Buffer.isBuffer(newPassword))\n bufferCopy(newPassword, packet, 0, newPassLen, p += 4);\n else\n packet.utf8Write(newPassword, p += 4, newPassLen);\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (changed password)'\n );\n } else {\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (password)'\n );\n }\n\n this._authsQueue.push('password');\n\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authPK(username, pubKey, cbSign) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n pubKey = parseKey(pubKey);\n if (pubKey instanceof Error)\n throw new Error('Invalid key');\n\n const keyType = pubKey.type;\n pubKey = pubKey.getPublicSSH();\n\n const userLen = Buffer.byteLength(username);\n const algoLen = Buffer.byteLength(keyType);\n const pubKeyLen = pubKey.length;\n const sessionID = this._kex.sessionID;\n const sesLen = sessionID.length;\n const payloadLen =\n (cbSign ? 4 + sesLen : 0)\n + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen;\n let packet;\n let p;\n if (cbSign) {\n packet = Buffer.allocUnsafe(payloadLen);\n p = 0;\n writeUInt32BE(packet, sesLen, p);\n packet.set(sessionID, p += 4);\n p += sesLen;\n } else {\n packet = this._packetRW.write.alloc(payloadLen);\n p = this._packetRW.write.allocStart;\n }\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 9, p += 14);\n packet.utf8Write('publickey', p += 4, 9);\n\n packet[p += 9] = (cbSign ? 1 : 0);\n\n writeUInt32BE(packet, algoLen, ++p);\n packet.utf8Write(keyType, p += 4, algoLen);\n\n writeUInt32BE(packet, pubKeyLen, p += algoLen);\n packet.set(pubKey, p += 4);\n\n if (!cbSign) {\n this._authsQueue.push('publickey');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n return;\n }\n\n cbSign(packet, (signature) => {\n signature = convertSignature(signature, keyType);\n if (signature === false)\n throw new Error('Error while converting handshake signature');\n\n const sigLen = signature.length;\n p = this._packetRW.write.allocStart;\n packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4\n + 4 + algoLen + 4 + sigLen\n );\n\n // TODO: simply copy from original \"packet\" to new `packet` to avoid\n // having to write each individual field a second time?\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 9, p += 14);\n packet.utf8Write('publickey', p += 4, 9);\n\n packet[p += 9] = 1;\n\n writeUInt32BE(packet, algoLen, ++p);\n packet.utf8Write(keyType, p += 4, algoLen);\n\n writeUInt32BE(packet, pubKeyLen, p += algoLen);\n packet.set(pubKey, p += 4);\n\n writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen);\n\n writeUInt32BE(packet, algoLen, p += 4);\n packet.utf8Write(keyType, p += 4, algoLen);\n\n writeUInt32BE(packet, sigLen, p += algoLen);\n packet.set(signature, p += 4);\n\n // Servers shouldn't send packet type 60 in response to signed publickey\n // attempts, but if they do, interpret as type 60.\n this._authsQueue.push('publickey');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (publickey)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n });\n }\n authHostbased(username, pubKey, hostname, userlocal, cbSign) {\n // TODO: Make DRY by sharing similar code with authPK()\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n pubKey = parseKey(pubKey);\n if (pubKey instanceof Error)\n throw new Error('Invalid key');\n\n const keyType = pubKey.type;\n pubKey = pubKey.getPublicSSH();\n\n const userLen = Buffer.byteLength(username);\n const algoLen = Buffer.byteLength(keyType);\n const pubKeyLen = pubKey.length;\n const sessionID = this._kex.sessionID;\n const sesLen = sessionID.length;\n const hostnameLen = Buffer.byteLength(hostname);\n const userlocalLen = Buffer.byteLength(userlocal);\n const data = Buffer.allocUnsafe(\n 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen\n + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen\n );\n let p = 0;\n\n writeUInt32BE(data, sesLen, p);\n data.set(sessionID, p += 4);\n\n data[p += sesLen] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(data, userLen, ++p);\n data.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(data, 14, p += userLen);\n data.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(data, 9, p += 14);\n data.utf8Write('hostbased', p += 4, 9);\n\n writeUInt32BE(data, algoLen, p += 9);\n data.utf8Write(keyType, p += 4, algoLen);\n\n writeUInt32BE(data, pubKeyLen, p += algoLen);\n data.set(pubKey, p += 4);\n\n writeUInt32BE(data, hostnameLen, p += pubKeyLen);\n data.utf8Write(hostname, p += 4, hostnameLen);\n\n writeUInt32BE(data, userlocalLen, p += hostnameLen);\n data.utf8Write(userlocal, p += 4, userlocalLen);\n\n cbSign(data, (signature) => {\n signature = convertSignature(signature, keyType);\n if (!signature)\n throw new Error('Error while converting handshake signature');\n\n const sigLen = signature.length;\n const reqDataLen = (data.length - sesLen - 4);\n p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n reqDataLen + 4 + 4 + algoLen + 4 + sigLen\n );\n\n bufferCopy(data, packet, 4 + sesLen, data.length, p);\n\n writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen);\n writeUInt32BE(packet, algoLen, p += 4);\n packet.utf8Write(keyType, p += 4, algoLen);\n writeUInt32BE(packet, sigLen, p += algoLen);\n packet.set(signature, p += 4);\n\n this._authsQueue.push('hostbased');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (hostbased)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n });\n }\n authKeyboard(username) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4\n );\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 20, p += 14);\n packet.utf8Write('keyboard-interactive', p += 4, 20);\n\n writeUInt32BE(packet, 0, p += 20);\n\n writeUInt32BE(packet, 0, p += 4);\n\n this._authsQueue.push('keyboard-interactive');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authNone(username) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4);\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 4, p += 14);\n packet.utf8Write('none', p += 4, 4);\n\n this._authsQueue.push('none');\n\n this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authInfoRes(responses) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let responsesTotalLen = 0;\n let responseLens;\n\n if (responses) {\n responseLens = new Array(responses.length);\n for (let i = 0; i < responses.length; ++i) {\n const len = Buffer.byteLength(responses[i]);\n responseLens[i] = len;\n responsesTotalLen += 4 + len;\n }\n }\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen);\n\n packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE;\n\n if (responses) {\n writeUInt32BE(packet, responses.length, ++p);\n p += 4;\n for (let i = 0; i < responses.length; ++i) {\n const len = responseLens[i];\n writeUInt32BE(packet, len, p);\n p += 4;\n if (len) {\n packet.utf8Write(responses[i], p, len);\n p += len;\n }\n }\n } else {\n writeUInt32BE(packet, 0, ++p);\n }\n\n this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // 'ssh-connection' service-specific\n // ---------------------------------\n tcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 13, ++p);\n packet.utf8Write('tcpip-forward', p += 4, 13);\n\n packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n cancelTcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 20, ++p);\n packet.utf8Write('cancel-tcpip-forward', p += 4, 20);\n\n packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_streamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 31 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 31, ++p);\n packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31);\n\n packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_cancelStreamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 38 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 38, ++p);\n packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38);\n\n packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending GLOBAL_REQUEST '\n + '(cancel-streamlocal-forward@openssh.com)'\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n directTcpip(chan, initWindow, maxPacket, cfg) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const srcLen = Buffer.byteLength(cfg.srcIP);\n const dstLen = Buffer.byteLength(cfg.dstIP);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 12, ++p);\n packet.utf8Write('direct-tcpip', p += 4, 12);\n\n writeUInt32BE(packet, chan, p += 12);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, dstLen, p += 4);\n packet.utf8Write(cfg.dstIP, p += 4, dstLen);\n\n writeUInt32BE(packet, cfg.dstPort, p += dstLen);\n\n writeUInt32BE(packet, srcLen, p += 4);\n packet.utf8Write(cfg.srcIP, p += 4, srcLen);\n\n writeUInt32BE(packet, cfg.srcPort, p += srcLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const pathLen = Buffer.byteLength(cfg.socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 30, ++p);\n packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30);\n\n writeUInt32BE(packet, chan, p += 30);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, pathLen, p += 4);\n packet.utf8Write(cfg.socketPath, p += 4, pathLen);\n\n // zero-fill reserved fields (string and uint32)\n bufferFill(packet, 0, p += pathLen, p + 8);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_OPEN '\n + `(r:${chan}, direct-streamlocal@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_noMoreSessions(wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 28, ++p);\n packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28);\n\n packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n session(chan, initWindow, maxPacket) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 7, ++p);\n packet.utf8Write('session', p += 4, 7);\n\n writeUInt32BE(packet, chan, p += 7);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n windowChange(chan, rows, cols, height, width) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 13, p += 4);\n packet.utf8Write('window-change', p += 4, 13);\n\n packet[p += 13] = 0;\n\n writeUInt32BE(packet, cols, ++p);\n\n writeUInt32BE(packet, rows, p += 4);\n\n writeUInt32BE(packet, width, p += 4);\n\n writeUInt32BE(packet, height, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n pty(chan, rows, cols, height, width, term, modes, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n if (!term || !term.length)\n term = 'vt100';\n if (modes\n && !Buffer.isBuffer(modes)\n && !Array.isArray(modes)\n && typeof modes === 'object'\n && modes !== null) {\n modes = modesToBytes(modes);\n }\n if (!modes || !modes.length)\n modes = NO_TERMINAL_MODES_BUFFER;\n\n const termLen = term.length;\n const modesLen = modes.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 7, p += 4);\n packet.utf8Write('pty-req', p += 4, 7);\n\n packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, termLen, ++p);\n packet.utf8Write(term, p += 4, termLen);\n\n writeUInt32BE(packet, cols, p += termLen);\n\n writeUInt32BE(packet, rows, p += 4);\n\n writeUInt32BE(packet, width, p += 4);\n\n writeUInt32BE(packet, height, p += 4);\n\n writeUInt32BE(packet, modesLen, p += 4);\n p += 4;\n if (Array.isArray(modes)) {\n for (let i = 0; i < modesLen; ++i)\n packet[p++] = modes[i];\n } else if (Buffer.isBuffer(modes)) {\n packet.set(modes, p);\n }\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n shell(chan, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 5, p += 4);\n packet.utf8Write('shell', p += 4, 5);\n\n packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exec(chan, cmd, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const isBuf = Buffer.isBuffer(cmd);\n const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 4, p += 4);\n packet.utf8Write('exec', p += 4, 4);\n\n packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, cmdLen, ++p);\n if (isBuf)\n packet.set(cmd, p += 4);\n else\n packet.utf8Write(cmd, p += 4, cmdLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n signal(chan, signal) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const origSignal = signal;\n\n signal = signal.toUpperCase();\n if (signal.slice(0, 3) === 'SIG')\n signal = signal.slice(3);\n\n if (SIGNALS[signal] !== 1)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n const signalLen = signal.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 6 + 1 + 4 + signalLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 6, p += 4);\n packet.utf8Write('signal', p += 4, 6);\n\n packet[p += 6] = 0;\n\n writeUInt32BE(packet, signalLen, ++p);\n packet.utf8Write(signal, p += 4, signalLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n env(chan, key, val, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const keyLen = Buffer.byteLength(key);\n const isBuf = Buffer.isBuffer(val);\n const valLen = (isBuf ? val.length : Buffer.byteLength(val));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 3, p += 4);\n packet.utf8Write('env', p += 4, 3);\n\n packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, keyLen, ++p);\n packet.utf8Write(key, p += 4, keyLen);\n\n writeUInt32BE(packet, valLen, p += keyLen);\n if (isBuf)\n packet.set(val, p += 4);\n else\n packet.utf8Write(val, p += 4, valLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n x11Forward(chan, cfg, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const protocol = cfg.protocol;\n const cookie = cfg.cookie;\n const isBufProto = Buffer.isBuffer(protocol);\n const protoLen = (isBufProto\n ? protocol.length\n : Buffer.byteLength(protocol));\n const isBufCookie = Buffer.isBuffer(cookie);\n const cookieLen = (isBufCookie\n ? cookie.length\n : Buffer.byteLength(cookie));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 7, p += 4);\n packet.utf8Write('x11-req', p += 4, 7);\n\n packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n packet[++p] = (cfg.single ? 1 : 0);\n\n writeUInt32BE(packet, protoLen, ++p);\n if (isBufProto)\n packet.set(protocol, p += 4);\n else\n packet.utf8Write(protocol, p += 4, protoLen);\n\n writeUInt32BE(packet, cookieLen, p += protoLen);\n if (isBufCookie)\n packet.set(cookie, p += 4);\n else\n packet.latin1Write(cookie, p += 4, cookieLen);\n\n writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n subsystem(chan, name, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 9, p += 4);\n packet.utf8Write('subsystem', p += 4, 9);\n\n packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_agentForward(chan, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 26, p += 4);\n packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26);\n\n packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_REQUEST '\n + `(r:${chan}, auth-agent-req@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_hostKeysProve(keys) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let keysTotal = 0;\n const publicKeys = [];\n for (const key of keys) {\n const publicKey = key.getPublicSSH();\n keysTotal += 4 + publicKey.length;\n publicKeys.push(publicKey);\n }\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 29, ++p);\n packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);\n\n packet[p += 29] = 1; // want reply\n\n ++p;\n for (const buf of publicKeys) {\n writeUInt32BE(packet, buf.length, p);\n bufferCopy(buf, packet, 0, buf.length, p += 4);\n p += buf.length;\n }\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)'\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // ===========================================================================\n // Server-specific ===========================================================\n // ===========================================================================\n\n // Global\n // ------\n serviceAccept(svcName) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const svcNameLen = Buffer.byteLength(svcName);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen);\n\n packet[p] = MESSAGE.SERVICE_ACCEPT;\n\n writeUInt32BE(packet, svcNameLen, ++p);\n packet.utf8Write(svcName, p += 4, svcNameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n\n if (this._server && this._banner && svcName === 'ssh-userauth') {\n const banner = this._banner;\n this._banner = undefined; // Prevent banner from being displayed again\n const bannerLen = Buffer.byteLength(banner);\n p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4);\n\n packet[p] = MESSAGE.USERAUTH_BANNER;\n\n writeUInt32BE(packet, bannerLen, ++p);\n packet.utf8Write(banner, p += 4, bannerLen);\n\n writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag\n\n this._debug && this._debug('Outbound: Sending USERAUTH_BANNER');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n }\n // 'ssh-connection' service-specific\n forwardedTcpip(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const boundAddrLen = Buffer.byteLength(cfg.boundAddr);\n const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 15, ++p);\n packet.utf8Write('forwarded-tcpip', p += 4, 15);\n\n writeUInt32BE(packet, chan, p += 15);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, boundAddrLen, p += 4);\n packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen);\n\n writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen);\n\n writeUInt32BE(packet, remoteAddrLen, p += 4);\n packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen);\n\n writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n x11(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const addrLen = Buffer.byteLength(cfg.originAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 3, ++p);\n packet.utf8Write('x11', p += 4, 3);\n\n writeUInt32BE(packet, chan, p += 3);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, addrLen, p += 4);\n packet.utf8Write(cfg.originAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, cfg.originPort, p += addrLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_authAgent(chan, initWindow, maxPacket) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 22, ++p);\n packet.utf8Write('auth-agent@openssh.com', p += 4, 22);\n\n writeUInt32BE(packet, chan, p += 22);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const pathLen = Buffer.byteLength(cfg.socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 33, ++p);\n packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33);\n\n writeUInt32BE(packet, chan, p += 33);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, pathLen, p += 4);\n packet.utf8Write(cfg.socketPath, p += 4, pathLen);\n\n writeUInt32BE(packet, 0, p += pathLen);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_OPEN '\n + `(r:${chan}, forwarded-streamlocal@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exitStatus(chan, status) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n // Does not consume window space\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 11, p += 4);\n packet.utf8Write('exit-status', p += 4, 11);\n\n packet[p += 11] = 0;\n\n writeUInt32BE(packet, status, ++p);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exitSignal(chan, name, coreDumped, msg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n // Does not consume window space\n\n const origSignal = name;\n\n if (typeof origSignal !== 'string' || !origSignal)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n let signal = name.toUpperCase();\n if (signal.slice(0, 3) === 'SIG')\n signal = signal.slice(3);\n\n if (SIGNALS[signal] !== 1)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n const nameLen = Buffer.byteLength(signal);\n const msgLen = (msg ? Buffer.byteLength(msg) : 0);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 11, p += 4);\n packet.utf8Write('exit-signal', p += 4, 11);\n\n packet[p += 11] = 0;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(signal, p += 4, nameLen);\n\n packet[p += nameLen] = (coreDumped ? 1 : 0);\n\n writeUInt32BE(packet, msgLen, ++p);\n\n p += 4;\n if (msgLen) {\n packet.utf8Write(msg, p, msgLen);\n p += msgLen;\n }\n\n writeUInt32BE(packet, 0, p);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n // 'ssh-userauth' service-specific\n authFailure(authMethods, isPartial) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0)\n throw new Error('No auth in progress');\n\n let methods;\n\n if (typeof authMethods === 'boolean') {\n isPartial = authMethods;\n authMethods = undefined;\n }\n\n if (authMethods) {\n methods = [];\n for (let i = 0; i < authMethods.length; ++i) {\n if (authMethods[i].toLowerCase() === 'none')\n continue;\n methods.push(authMethods[i]);\n }\n methods = methods.join(',');\n } else {\n methods = '';\n }\n\n const methodsLen = methods.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1);\n\n packet[p] = MESSAGE.USERAUTH_FAILURE;\n\n writeUInt32BE(packet, methodsLen, ++p);\n packet.utf8Write(methods, p += 4, methodsLen);\n\n packet[p += methodsLen] = (isPartial === true ? 1 : 0);\n\n this._authsQueue.shift();\n\n this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authSuccess() {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0)\n throw new Error('No auth in progress');\n\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.USERAUTH_SUCCESS;\n\n this._authsQueue.shift();\n this._authenticated = true;\n\n this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS');\n sendPacket(this, this._packetRW.write.finalize(packet));\n\n if (this._kex.negotiated.cs.compress === 'zlib@openssh.com')\n this._packetRW.read = new ZlibPacketReader();\n if (this._kex.negotiated.sc.compress === 'zlib@openssh.com')\n this._packetRW.write = new ZlibPacketWriter(this);\n }\n authPKOK(keyAlgo, key) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey')\n throw new Error('\"publickey\" auth not in progress');\n\n // TODO: support parsed key for `key`\n\n const keyAlgoLen = Buffer.byteLength(keyAlgo);\n const keyLen = key.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen);\n\n packet[p] = MESSAGE.USERAUTH_PK_OK;\n\n writeUInt32BE(packet, keyAlgoLen, ++p);\n packet.utf8Write(keyAlgo, p += 4, keyAlgoLen);\n\n writeUInt32BE(packet, keyLen, p += keyAlgoLen);\n packet.set(key, p += 4);\n\n this._authsQueue.shift();\n\n this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authPasswdChg(prompt) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const promptLen = Buffer.byteLength(prompt);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4);\n\n packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ;\n\n writeUInt32BE(packet, promptLen, ++p);\n packet.utf8Write(prompt, p += 4, promptLen);\n\n writeUInt32BE(packet, 0, p += promptLen); // Empty language tag\n\n this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authInfoReq(name, instructions, prompts) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n let promptsLen = 0;\n const nameLen = name ? Buffer.byteLength(name) : 0;\n const instrLen = instructions ? Buffer.byteLength(instructions) : 0;\n\n for (let i = 0; i < prompts.length; ++i)\n promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1;\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen\n );\n\n packet[p] = MESSAGE.USERAUTH_INFO_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n p += 4;\n if (name) {\n packet.utf8Write(name, p, nameLen);\n p += nameLen;\n }\n\n writeUInt32BE(packet, instrLen, p);\n p += 4;\n if (instructions) {\n packet.utf8Write(instructions, p, instrLen);\n p += instrLen;\n }\n\n writeUInt32BE(packet, 0, p);\n\n writeUInt32BE(packet, prompts.length, p += 4);\n p += 4;\n for (let i = 0; i < prompts.length; ++i) {\n const prompt = prompts[i];\n const promptLen = Buffer.byteLength(prompt.prompt);\n\n writeUInt32BE(packet, promptLen, p);\n p += 4;\n if (promptLen) {\n packet.utf8Write(prompt.prompt, p, promptLen);\n p += promptLen;\n }\n packet[p++] = (prompt.echo ? 1 : 0);\n }\n\n this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n}\n\n// SSH-protoversion-softwareversion (SP comments) CR LF\nconst RE_IDENT = /^SSH-(2\\.0|1\\.99)-([^ ]+)(?: (.*))?$/;\n\n// TODO: optimize this by starting n bytes from the end of this._buffer instead\n// of the beginning\nfunction parseHeader(chunk, p, len) {\n let data;\n let chunkOffset;\n if (this._buffer) {\n data = Buffer.allocUnsafe(this._buffer.length + (len - p));\n data.set(this._buffer, 0);\n if (p === 0) {\n data.set(chunk, this._buffer.length);\n } else {\n data.set(new Uint8Array(chunk.buffer,\n chunk.byteOffset + p,\n (len - p)),\n this._buffer.length);\n }\n chunkOffset = this._buffer.length;\n p = 0;\n } else {\n data = chunk;\n chunkOffset = 0;\n }\n const op = p;\n let start = p;\n let end = p;\n let needNL = false;\n let lineLen = 0;\n let lines = 0;\n for (; p < data.length; ++p) {\n const ch = data[p];\n\n if (ch === 13 /* '\\r' */) {\n needNL = true;\n continue;\n }\n\n if (ch === 10 /* '\\n' */) {\n if (end > start\n && end - start > 4\n && data[start] === 83 /* 'S' */\n && data[start + 1] === 83 /* 'S' */\n && data[start + 2] === 72 /* 'H' */\n && data[start + 3] === 45 /* '-' */) {\n\n const full = data.latin1Slice(op, end + 1);\n const identRaw = (start === op ? full : full.slice(start - op));\n const m = RE_IDENT.exec(identRaw);\n if (!m)\n throw new Error('Invalid identification string');\n\n const header = {\n greeting: (start === op ? '' : full.slice(0, start - op)),\n identRaw,\n versions: {\n protocol: m[1],\n software: m[2],\n },\n comments: m[3]\n };\n\n // Needed during handshake\n this._remoteIdentRaw = Buffer.from(identRaw);\n\n this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`);\n this._compatFlags = getCompatFlags(header);\n\n this._buffer = undefined;\n this._decipher =\n new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true }));\n this._parse = parsePacket;\n\n this._onHeader(header);\n if (!this._destruct) {\n // We disconnected inside _onHeader\n return len;\n }\n\n kexinit(this);\n\n return p + 1 - chunkOffset;\n }\n\n // Only allow pre-ident greetings when we're a client\n if (this._server)\n throw new Error('Greetings from clients not permitted');\n\n if (++lines > MAX_LINES)\n throw new Error('Max greeting lines exceeded');\n\n needNL = false;\n start = p + 1;\n lineLen = 0;\n } else if (needNL) {\n throw new Error('Invalid header: expected newline');\n } else if (++lineLen >= MAX_LINE_LEN) {\n throw new Error('Header line too long');\n }\n\n end = p;\n }\n if (!this._buffer)\n this._buffer = bufferSlice(data, op);\n\n return p - chunkOffset;\n}\n\nfunction parsePacket(chunk, p, len) {\n return this._decipher.decrypt(chunk, p, len);\n}\n\nfunction onPayload(payload) {\n // XXX: move this to the Decipher implementations?\n\n this._onPacket();\n\n if (payload.length === 0) {\n this._debug && this._debug('Inbound: Skipping empty packet payload');\n return;\n }\n\n payload = this._packetRW.read.read(payload);\n\n const type = payload[0];\n if (type === MESSAGE.USERAUTH_SUCCESS\n && !this._server\n && !this._authenticated) {\n this._authenticated = true;\n if (this._kex.negotiated.cs.compress === 'zlib@openssh.com')\n this._packetRW.write = new ZlibPacketWriter(this);\n if (this._kex.negotiated.sc.compress === 'zlib@openssh.com')\n this._packetRW.read = new ZlibPacketReader();\n }\n const handler = MESSAGE_HANDLERS[type];\n if (handler === undefined) {\n this._debug && this._debug(`Inbound: Unsupported message type: ${type}`);\n return;\n }\n\n return handler(this, payload);\n}\n\nfunction getCompatFlags(header) {\n const software = header.versions.software;\n\n let flags = 0;\n\n for (const rule of COMPAT_CHECKS) {\n if (typeof rule[0] === 'string') {\n if (software === rule[0])\n flags |= rule[1];\n } else if (rule[0].test(software)) {\n flags |= rule[1];\n }\n }\n\n return flags;\n}\n\nfunction modesToBytes(modes) {\n const keys = Object.keys(modes);\n const bytes = Buffer.allocUnsafe((5 * keys.length) + 1);\n let b = 0;\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (key === 'TTY_OP_END')\n continue;\n\n const opcode = TERMINAL_MODE[key];\n if (opcode === undefined)\n continue;\n\n const val = modes[key];\n if (typeof val === 'number' && isFinite(val)) {\n bytes[b++] = opcode;\n bytes[b++] = val >>> 24;\n bytes[b++] = val >>> 16;\n bytes[b++] = val >>> 8;\n bytes[b++] = val;\n }\n }\n\n bytes[b++] = TERMINAL_MODE.TTY_OP_END;\n\n if (b < bytes.length)\n return bufferSlice(bytes, 0, b);\n\n return bytes;\n}\n\nmodule.exports = Protocol;\n","'use strict';\n\nconst EventEmitter = require('events');\nconst fs = require('fs');\nconst { constants } = fs;\nconst {\n Readable: ReadableStream,\n Writable: WritableStream\n} = require('stream');\nconst { inherits, isDate } = require('util');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst {\n bufferCopy,\n bufferSlice,\n makeBufferParser,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst ATTR = {\n SIZE: 0x00000001,\n UIDGID: 0x00000002,\n PERMISSIONS: 0x00000004,\n ACMODTIME: 0x00000008,\n EXTENDED: 0x80000000,\n};\n\n// Large enough to store all possible attributes\nconst ATTRS_BUF = Buffer.alloc(28);\n\nconst STATUS_CODE = {\n OK: 0,\n EOF: 1,\n NO_SUCH_FILE: 2,\n PERMISSION_DENIED: 3,\n FAILURE: 4,\n BAD_MESSAGE: 5,\n NO_CONNECTION: 6,\n CONNECTION_LOST: 7,\n OP_UNSUPPORTED: 8\n};\n\nconst VALID_STATUS_CODES = new Map(\n Object.values(STATUS_CODE).map((n) => [n, 1])\n);\n\nconst STATUS_CODE_STR = {\n [STATUS_CODE.OK]: 'No error',\n [STATUS_CODE.EOF]: 'End of file',\n [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory',\n [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied',\n [STATUS_CODE.FAILURE]: 'Failure',\n [STATUS_CODE.BAD_MESSAGE]: 'Bad message',\n [STATUS_CODE.NO_CONNECTION]: 'No connection',\n [STATUS_CODE.CONNECTION_LOST]: 'Connection lost',\n [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported',\n};\n\nconst REQUEST = {\n INIT: 1,\n OPEN: 3,\n CLOSE: 4,\n READ: 5,\n WRITE: 6,\n LSTAT: 7,\n FSTAT: 8,\n SETSTAT: 9,\n FSETSTAT: 10,\n OPENDIR: 11,\n READDIR: 12,\n REMOVE: 13,\n MKDIR: 14,\n RMDIR: 15,\n REALPATH: 16,\n STAT: 17,\n RENAME: 18,\n READLINK: 19,\n SYMLINK: 20,\n EXTENDED: 200\n};\n\nconst RESPONSE = {\n VERSION: 2,\n STATUS: 101,\n HANDLE: 102,\n DATA: 103,\n NAME: 104,\n ATTRS: 105,\n EXTENDED: 201\n};\n\nconst OPEN_MODE = {\n READ: 0x00000001,\n WRITE: 0x00000002,\n APPEND: 0x00000004,\n CREAT: 0x00000008,\n TRUNC: 0x00000010,\n EXCL: 0x00000020\n};\n\nconst PKT_RW_OVERHEAD = 2 * 1024;\nconst MAX_REQID = 2 ** 32 - 1;\nconst CLIENT_VERSION_BUFFER = Buffer.from([\n 0, 0, 0, 5 /* length */,\n REQUEST.INIT,\n 0, 0, 0, 3 /* version */\n]);\nconst SERVER_VERSION_BUFFER = Buffer.from([\n 0, 0, 0, 5 /* length */,\n RESPONSE.VERSION,\n 0, 0, 0, 3 /* version */\n]);\n\nconst RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/;\nconst OPENSSH_MAX_PKT_LEN = 256 * 1024;\n\nconst bufferParser = makeBufferParser();\n\nconst fakeStderr = {\n readable: false,\n writable: false,\n push: (data) => {},\n once: () => {},\n on: () => {},\n emit: () => {},\n end: () => {},\n};\n\nfunction noop() {}\n\n// Emulates enough of `Channel` to be able to be used as a drop-in replacement\n// in order to process incoming data with as little overhead as possible\nclass SFTP extends EventEmitter {\n constructor(client, chanInfo, cfg) {\n super();\n\n if (typeof cfg !== 'object' || !cfg)\n cfg = {};\n\n const remoteIdentRaw = client._protocol._remoteIdentRaw;\n\n this.server = !!cfg.server;\n this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);\n this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw));\n\n this._version = -1;\n this._extensions = {};\n this._biOpt = cfg.biOpt;\n this._pktLenBytes = 0;\n this._pktLen = 0;\n this._pktPos = 0;\n this._pktType = 0;\n this._pktData = undefined;\n this._writeReqid = -1;\n this._requests = {};\n this._maxInPktLen = OPENSSH_MAX_PKT_LEN;\n this._maxOutPktLen = 34000;\n this._maxReadLen =\n (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;\n this._maxWriteLen =\n (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;\n\n this.maxOpenHandles = undefined;\n\n // Channel compatibility\n this._client = client;\n this._protocol = client._protocol;\n this._callbacks = [];\n this._hasX11 = false;\n this._exit = {\n code: undefined,\n signal: undefined,\n dump: undefined,\n desc: undefined,\n };\n this._waitWindow = false; // SSH-level backpressure\n this._chunkcb = undefined;\n this._buffer = [];\n this.type = chanInfo.type;\n this.subtype = undefined;\n this.incoming = chanInfo.incoming;\n this.outgoing = chanInfo.outgoing;\n this.stderr = fakeStderr;\n this.readable = true;\n }\n\n // This handles incoming data to parse\n push(data) {\n if (data === null) {\n cleanupRequests(this);\n if (!this.readable)\n return;\n // No more incoming data from the remote side\n this.readable = false;\n this.emit('end');\n return;\n }\n /*\n uint32 length\n byte type\n byte[length - 1] data payload\n */\n let p = 0;\n\n while (p < data.length) {\n if (this._pktLenBytes < 4) {\n let nb = Math.min(4 - this._pktLenBytes, data.length - p);\n this._pktLenBytes += nb;\n\n while (nb--)\n this._pktLen = (this._pktLen << 8) + data[p++];\n\n if (this._pktLenBytes < 4)\n return;\n if (this._pktLen === 0)\n return doFatalSFTPError(this, 'Invalid packet length');\n if (this._pktLen > this._maxInPktLen) {\n const max = this._maxInPktLen;\n return doFatalSFTPError(\n this,\n `Packet length ${this._pktLen} exceeds max length of ${max}`\n );\n }\n if (p >= data.length)\n return;\n }\n if (this._pktPos < this._pktLen) {\n const nb = Math.min(this._pktLen - this._pktPos, data.length - p);\n if (p !== 0 || nb !== data.length) {\n if (nb === this._pktLen) {\n this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb);\n } else {\n if (!this._pkt)\n this._pkt = Buffer.allocUnsafe(this._pktLen);\n this._pkt.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._pktPos\n );\n }\n } else if (nb === this._pktLen) {\n this._pkt = data;\n } else {\n if (!this._pkt)\n this._pkt = Buffer.allocUnsafe(this._pktLen);\n this._pkt.set(data, this._pktPos);\n }\n p += nb;\n this._pktPos += nb;\n if (this._pktPos < this._pktLen)\n return;\n }\n\n const type = this._pkt[0];\n const payload = this._pkt;\n\n // Prepare for next packet\n this._pktLen = 0;\n this._pktLenBytes = 0;\n this._pkt = undefined;\n this._pktPos = 0;\n\n const handler = (this.server\n ? SERVER_HANDLERS[type]\n : CLIENT_HANDLERS[type]);\n if (!handler)\n return doFatalSFTPError(this, `Unknown packet type ${type}`);\n\n if (this._version === -1) {\n if (this.server) {\n if (type !== REQUEST.INIT)\n return doFatalSFTPError(this, `Expected INIT packet, got ${type}`);\n } else if (type !== RESPONSE.VERSION) {\n return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`);\n }\n }\n\n if (handler(this, payload) === false)\n return;\n }\n }\n\n end() {\n this.destroy();\n }\n destroy() {\n if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {\n this.outgoing.state = 'closing';\n this._protocol.channelClose(this.outgoing.id);\n }\n }\n _init() {\n this._init = noop;\n if (!this.server)\n sendOrBuffer(this, CLIENT_VERSION_BUFFER);\n }\n\n // ===========================================================================\n // Client-specific ===========================================================\n // ===========================================================================\n createReadStream(path, options) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n return new ReadStream(this, path, options);\n }\n createWriteStream(path, options) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n return new WriteStream(this, path, options);\n }\n open(path, flags_, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (typeof attrs === 'function') {\n cb = attrs;\n attrs = undefined;\n }\n\n const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_));\n if (flags === null)\n throw new Error(`Unknown flags string: ${flags_}`);\n\n let attrsFlags = 0;\n let attrsLen = 0;\n if (typeof attrs === 'string' || typeof attrs === 'number')\n attrs = { mode: attrs };\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n attrsFlags = attrs.flags;\n attrsLen = attrs.nb;\n }\n\n /*\n uint32 id\n string filename\n uint32 pflags\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.OPEN;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n writeUInt32BE(buf, attrsFlags, p += 4);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN`\n );\n }\n close(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.CLOSE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE`\n );\n }\n read(handle, buf, off, len, position, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n if (!Buffer.isBuffer(buf))\n throw new Error('buffer is not a Buffer');\n if (off >= buf.length)\n throw new Error('offset is out of bounds');\n if (off + len > buf.length)\n throw new Error('length extends beyond buffer');\n if (position === null)\n throw new Error('null position currently unsupported');\n\n read_(this, handle, buf, off, len, position, cb);\n }\n readData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.read(handle, buf, off, len, position, cb);\n }\n write(handle, buf, off, len, position, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n if (!Buffer.isBuffer(buf))\n throw new Error('buffer is not a Buffer');\n if (off > buf.length)\n throw new Error('offset is out of bounds');\n if (off + len > buf.length)\n throw new Error('length extends beyond buffer');\n if (position === null)\n throw new Error('null position currently unsupported');\n\n if (!len) {\n cb && process.nextTick(cb, undefined, 0);\n return;\n }\n\n const maxDataLen = this._maxWriteLen;\n const overflow = Math.max(len - maxDataLen, 0);\n const origPosition = position;\n\n if (overflow)\n len = maxDataLen;\n\n /*\n uint32 id\n string handle\n uint64 offset\n string data\n */\n const handleLen = handle.length;\n let p = 9;\n const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len);\n\n writeUInt32BE(out, out.length - 4, 0);\n out[4] = REQUEST.WRITE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(out, reqid, 5);\n\n writeUInt32BE(out, handleLen, p);\n out.set(handle, p += 4);\n p += handleLen;\n for (let i = 7; i >= 0; --i) {\n out[p + i] = position & 0xFF;\n position /= 256;\n }\n writeUInt32BE(out, len, p += 8);\n bufferCopy(buf, out, off, off + len, p += 4);\n\n this._requests[reqid] = {\n cb: (err) => {\n if (err) {\n if (typeof cb === 'function')\n cb(err);\n } else if (overflow) {\n this.write(handle,\n buf,\n off + len,\n overflow,\n origPosition + len,\n cb);\n } else if (typeof cb === 'function') {\n cb(undefined, off + len);\n }\n }\n };\n\n const isSent = sendOrBuffer(this, out);\n if (this._debug) {\n const how = (isSent ? 'Sent' : 'Buffered');\n this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`);\n }\n }\n writeData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.write(handle, buf, off, len, position, cb);\n }\n fastGet(remotePath, localPath, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n fastXfer(this, fs, remotePath, localPath, opts, cb);\n }\n fastPut(localPath, remotePath, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n fastXfer(fs, this, localPath, remotePath, opts, cb);\n }\n readFile(path, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, flag: 'r' };\n else if (!options)\n options = { encoding: null, flag: 'r' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n const encoding = options.encoding;\n if (encoding && !Buffer.isEncoding(encoding))\n throw new Error(`Unknown encoding: ${encoding}`);\n\n // First stat the file, so we know the size.\n let size;\n let buffer; // Single buffer with file data\n let buffers; // List for when size is unknown\n let pos = 0;\n let handle;\n\n // SFTPv3 does not support using -1 for read position, so we have to track\n // read position manually\n let bytesRead = 0;\n\n const flag = options.flag || 'r';\n\n const read = () => {\n if (size === 0) {\n buffer = Buffer.allocUnsafe(8192);\n this.read(handle, buffer, 0, 8192, bytesRead, afterRead);\n } else {\n this.read(handle, buffer, pos, size - pos, bytesRead, afterRead);\n }\n };\n\n const afterRead = (er, nbytes) => {\n let eof;\n if (er) {\n eof = (er.code === STATUS_CODE.EOF);\n if (!eof) {\n return this.close(handle, () => {\n return callback && callback(er);\n });\n }\n } else {\n eof = false;\n }\n\n if (eof || (size === 0 && nbytes === 0))\n return close();\n\n bytesRead += nbytes;\n pos += nbytes;\n if (size !== 0) {\n if (pos === size)\n close();\n else\n read();\n } else {\n // Unknown size, just read until we don't get bytes.\n buffers.push(bufferSlice(buffer, 0, nbytes));\n read();\n }\n };\n afterRead._wantEOFError = true;\n\n const close = () => {\n this.close(handle, (er) => {\n if (size === 0) {\n // Collect the data into the buffers list.\n buffer = Buffer.concat(buffers, pos);\n } else if (pos < size) {\n buffer = bufferSlice(buffer, 0, pos);\n }\n\n if (encoding)\n buffer = buffer.toString(encoding);\n return callback && callback(er, buffer);\n });\n };\n\n this.open(path, flag, 0o666, (er, handle_) => {\n if (er)\n return callback && callback(er);\n handle = handle_;\n\n const tryStat = (er, st) => {\n if (er) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.stat(path, (er_, st_) => {\n if (er_) {\n return this.close(handle, () => {\n callback && callback(er);\n });\n }\n tryStat(null, st_);\n });\n return;\n }\n\n size = st.size || 0;\n if (size === 0) {\n // The kernel lies about many files.\n // Go ahead and try to read some bytes.\n buffers = [];\n return read();\n }\n\n buffer = Buffer.allocUnsafe(size);\n read();\n };\n this.fstat(handle, tryStat);\n });\n }\n writeFile(path, data, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, mode: 0o666, flag: 'w' };\n else if (!options)\n options = { encoding: 'utf8', mode: 0o666, flag: 'w' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n if (options.encoding && !Buffer.isEncoding(options.encoding))\n throw new Error(`Unknown encoding: ${options.encoding}`);\n\n const flag = options.flag || 'w';\n this.open(path, flag, options.mode, (openErr, handle) => {\n if (openErr) {\n callback && callback(openErr);\n } else {\n const buffer = (Buffer.isBuffer(data)\n ? data\n : Buffer.from('' + data, options.encoding || 'utf8'));\n const position = (/a/.test(flag) ? null : 0);\n\n // SFTPv3 does not support the notion of 'current position'\n // (null position), so we just attempt to append to the end of the file\n // instead\n if (position === null) {\n const tryStat = (er, st) => {\n if (er) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.stat(path, (er_, st_) => {\n if (er_) {\n return this.close(handle, () => {\n callback && callback(er);\n });\n }\n tryStat(null, st_);\n });\n return;\n }\n writeAll(this, handle, buffer, 0, buffer.length, st.size, callback);\n };\n this.fstat(handle, tryStat);\n return;\n }\n writeAll(this, handle, buffer, 0, buffer.length, position, callback);\n }\n });\n }\n appendFile(path, data, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, mode: 0o666, flag: 'a' };\n else if (!options)\n options = { encoding: 'utf8', mode: 0o666, flag: 'a' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n if (!options.flag)\n options = Object.assign({ flag: 'a' }, options);\n this.writeFile(path, data, options, callback);\n }\n exists(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n this.stat(path, (err) => {\n cb && cb(err ? false : true);\n });\n }\n unlink(filename, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string filename\n */\n const fnameLen = Buffer.byteLength(filename);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.REMOVE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, fnameLen, p);\n buf.utf8Write(filename, p += 4, fnameLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE`\n );\n }\n rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RENAME;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, oldLen, p);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME`\n );\n }\n mkdir(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'function') {\n cb = attrs;\n attrs = undefined;\n }\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n }\n\n /*\n uint32 id\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.MKDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR`\n );\n }\n rmdir(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RMDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR`\n );\n }\n readdir(where, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof opts !== 'object' || opts === null)\n opts = {};\n\n const doFilter = (opts && opts.full ? false : true);\n\n if (!Buffer.isBuffer(where) && typeof where !== 'string')\n throw new Error('missing directory handle or path');\n\n if (typeof where === 'string') {\n const entries = [];\n let e = 0;\n\n const reread = (err, handle) => {\n if (err)\n return cb(err);\n\n this.readdir(handle, opts, (err, list) => {\n const eof = (err && err.code === STATUS_CODE.EOF);\n\n if (err && !eof)\n return this.close(handle, () => cb(err));\n\n if (eof) {\n return this.close(handle, (err) => {\n if (err)\n return cb(err);\n cb(undefined, entries);\n });\n }\n\n for (let i = 0; i < list.length; ++i, ++e)\n entries[e] = list[i];\n\n reread(undefined, handle);\n });\n };\n return this.opendir(where, reread);\n }\n\n /*\n uint32 id\n string handle\n */\n const handleLen = where.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.READDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(where, p += 4);\n\n this._requests[reqid] = {\n cb: (doFilter\n ? (err, list) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n\n for (let i = list.length - 1; i >= 0; --i) {\n if (list[i].filename === '.' || list[i].filename === '..')\n list.splice(i, 1);\n }\n\n cb(undefined, list);\n }\n : cb)\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR`\n );\n }\n fstat(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.FSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT`\n );\n }\n stat(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.STAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT`\n );\n }\n lstat(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.LSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT`\n );\n }\n opendir(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.OPENDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR`\n );\n }\n setstat(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.SETSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT`\n );\n }\n fsetstat(handle, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string handle\n ATTRS attrs\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.FSETSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n writeUInt32BE(buf, flags, p += handleLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT`\n );\n }\n futimes(handle, atime, mtime, cb) {\n return this.fsetstat(handle, {\n atime: toUnixTimestamp(atime),\n mtime: toUnixTimestamp(mtime)\n }, cb);\n }\n utimes(path, atime, mtime, cb) {\n return this.setstat(path, {\n atime: toUnixTimestamp(atime),\n mtime: toUnixTimestamp(mtime)\n }, cb);\n }\n fchown(handle, uid, gid, cb) {\n return this.fsetstat(handle, {\n uid: uid,\n gid: gid\n }, cb);\n }\n chown(path, uid, gid, cb) {\n return this.setstat(path, {\n uid: uid,\n gid: gid\n }, cb);\n }\n fchmod(handle, mode, cb) {\n return this.fsetstat(handle, {\n mode: mode\n }, cb);\n }\n chmod(path, mode, cb) {\n return this.setstat(path, {\n mode: mode\n }, cb);\n }\n readlink(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.READLINK;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing link info'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK`\n );\n }\n symlink(targetPath, linkPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string linkpath\n string targetpath\n */\n const linkLen = Buffer.byteLength(linkPath);\n const targetLen = Buffer.byteLength(targetPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.SYMLINK;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n if (this._isOpenSSH) {\n // OpenSSH has linkpath and targetpath positions switched\n writeUInt32BE(buf, targetLen, p);\n buf.utf8Write(targetPath, p += 4, targetLen);\n writeUInt32BE(buf, linkLen, p += targetLen);\n buf.utf8Write(linkPath, p += 4, linkLen);\n } else {\n writeUInt32BE(buf, linkLen, p);\n buf.utf8Write(linkPath, p += 4, linkLen);\n writeUInt32BE(buf, targetLen, p += linkLen);\n buf.utf8Write(targetPath, p += 4, targetLen);\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK`\n );\n }\n realpath(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.REALPATH;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing path info'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH`\n );\n }\n // extended requests\n ext_openssh_rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['posix-rename@openssh.com'];\n if (!ext || ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"posix-rename@openssh.com\"\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 24, p);\n buf.utf8Write('posix-rename@openssh.com', p += 4, 24);\n writeUInt32BE(buf, oldLen, p += 24);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`);\n }\n }\n ext_openssh_statvfs(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['statvfs@openssh.com'];\n if (!ext || ext !== '2')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"statvfs@openssh.com\"\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 19, p);\n buf.utf8Write('statvfs@openssh.com', p += 4, 19);\n writeUInt32BE(buf, pathLen, p += 19);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { extended: 'statvfs@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`);\n }\n }\n ext_openssh_fstatvfs(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['fstatvfs@openssh.com'];\n if (!ext || ext !== '2')\n throw new Error('Server does not support this extended request');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string \"fstatvfs@openssh.com\"\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('fstatvfs@openssh.com', p += 4, 20);\n writeUInt32BE(buf, handleLen, p += 20);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`);\n }\n }\n ext_openssh_hardlink(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['hardlink@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"hardlink@openssh.com\"\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('hardlink@openssh.com', p += 4, 20);\n writeUInt32BE(buf, oldLen, p += 20);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`);\n }\n }\n ext_openssh_fsync(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['fsync@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string \"fsync@openssh.com\"\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 17, p);\n buf.utf8Write('fsync@openssh.com', p += 4, 17);\n writeUInt32BE(buf, handleLen, p += 17);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com`\n );\n }\n ext_openssh_lsetstat(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['lsetstat@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string \"lsetstat@openssh.com\"\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('lsetstat@openssh.com', p += 4, 20);\n\n writeUInt32BE(buf, pathLen, p += 20);\n buf.utf8Write(path, p += 4, pathLen);\n\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`);\n }\n }\n ext_openssh_expandPath(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['expand-path@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"expand-path@openssh.com\"\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 23, p);\n buf.utf8Write('expand-path@openssh.com', p += 4, 23);\n\n writeUInt32BE(buf, pathLen, p += 20);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`);\n }\n }\n // ===========================================================================\n // Server-specific ===========================================================\n // ===========================================================================\n handle(reqid, handle) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n const handleLen = handle.length;\n\n if (handleLen > 256)\n throw new Error('handle too large (> 256 bytes)');\n\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.HANDLE;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n if (handleLen)\n buf.set(handle, p += 4);\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE`\n );\n }\n status(reqid, code, message) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!VALID_STATUS_CODES.has(code))\n throw new Error(`Bad status code: ${code}`);\n\n message || (message = '');\n\n const msgLen = Buffer.byteLength(message);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.STATUS;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, code, p);\n\n writeUInt32BE(buf, msgLen, p += 4);\n p += 4;\n if (msgLen) {\n buf.utf8Write(message, p, msgLen);\n p += msgLen;\n }\n\n writeUInt32BE(buf, 0, p); // Empty language tag\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS`\n );\n }\n data(reqid, data, encoding) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n const isBuffer = Buffer.isBuffer(data);\n\n if (!isBuffer && typeof data !== 'string')\n throw new Error('data is not a Buffer or string');\n\n let isUTF8;\n if (!isBuffer && !encoding) {\n encoding = undefined;\n isUTF8 = true;\n }\n\n const dataLen = (\n isBuffer\n ? data.length\n : Buffer.byteLength(data, encoding)\n );\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.DATA;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, dataLen, p);\n if (dataLen) {\n if (isBuffer)\n buf.set(data, p += 4);\n else if (isUTF8)\n buf.utf8Write(data, p += 4, dataLen);\n else\n buf.write(data, p += 4, dataLen, encoding);\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA`\n );\n }\n name(reqid, names) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!Array.isArray(names)) {\n if (typeof names !== 'object' || names === null)\n throw new Error('names is not an object or array');\n names = [ names ];\n }\n\n const count = names.length;\n let namesLen = 0;\n let nameAttrs;\n const attrs = [];\n\n for (let i = 0; i < count; ++i) {\n const name = names[i];\n const filename = (\n !name || !name.filename || typeof name.filename !== 'string'\n ? ''\n : name.filename\n );\n namesLen += 4 + Buffer.byteLength(filename);\n const longname = (\n !name || !name.longname || typeof name.longname !== 'string'\n ? ''\n : name.longname\n );\n namesLen += 4 + Buffer.byteLength(longname);\n\n if (typeof name.attrs === 'object' && name.attrs !== null) {\n nameAttrs = attrsToBytes(name.attrs);\n namesLen += 4 + nameAttrs.nb;\n\n if (nameAttrs.nb) {\n let bytes;\n\n if (nameAttrs.nb === ATTRS_BUF.length) {\n bytes = new Uint8Array(ATTRS_BUF);\n } else {\n bytes = new Uint8Array(nameAttrs.nb);\n bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0);\n }\n\n nameAttrs.bytes = bytes;\n }\n\n attrs.push(nameAttrs);\n } else {\n namesLen += 4;\n attrs.push(null);\n }\n }\n\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.NAME;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, count, p);\n\n p += 4;\n\n for (let i = 0; i < count; ++i) {\n const name = names[i];\n\n {\n const filename = (\n !name || !name.filename || typeof name.filename !== 'string'\n ? ''\n : name.filename\n );\n const len = Buffer.byteLength(filename);\n writeUInt32BE(buf, len, p);\n p += 4;\n if (len) {\n buf.utf8Write(filename, p, len);\n p += len;\n }\n }\n\n {\n const longname = (\n !name || !name.longname || typeof name.longname !== 'string'\n ? ''\n : name.longname\n );\n const len = Buffer.byteLength(longname);\n writeUInt32BE(buf, len, p);\n p += 4;\n if (len) {\n buf.utf8Write(longname, p, len);\n p += len;\n }\n }\n\n const attr = attrs[i];\n if (attr) {\n writeUInt32BE(buf, attr.flags, p);\n p += 4;\n if (attr.flags && attr.bytes) {\n buf.set(attr.bytes, p);\n p += attr.nb;\n }\n } else {\n writeUInt32BE(buf, 0, p);\n p += 4;\n }\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME`\n );\n }\n attrs(reqid, attrs) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (typeof attrs !== 'object' || attrs === null)\n throw new Error('attrs is not an object');\n\n attrs = attrsToBytes(attrs);\n const flags = attrs.flags;\n const attrsLen = attrs.nb;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.ATTRS;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, flags, p);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS`\n );\n }\n}\n\nfunction tryCreateBuffer(size) {\n try {\n return Buffer.allocUnsafe(size);\n } catch (ex) {\n return ex;\n }\n}\n\nfunction read_(self, handle, buf, off, len, position, cb, req_) {\n const maxDataLen = self._maxReadLen;\n const overflow = Math.max(len - maxDataLen, 0);\n\n if (overflow)\n len = maxDataLen;\n\n /*\n uint32 id\n string handle\n uint64 offset\n uint32 len\n */\n const handleLen = handle.length;\n let p = 9;\n let pos = position;\n const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4);\n\n writeUInt32BE(out, out.length - 4, 0);\n out[4] = REQUEST.READ;\n const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(out, reqid, 5);\n\n writeUInt32BE(out, handleLen, p);\n out.set(handle, p += 4);\n p += handleLen;\n for (let i = 7; i >= 0; --i) {\n out[p + i] = pos & 0xFF;\n pos /= 256;\n }\n writeUInt32BE(out, len, p += 8);\n\n if (typeof cb !== 'function')\n cb = noop;\n\n const req = (req_ || {\n nb: 0,\n position,\n off,\n origOff: off,\n len: undefined,\n overflow: undefined,\n cb: (err, data, nb) => {\n const len = req.len;\n const overflow = req.overflow;\n\n if (err) {\n if (cb._wantEOFError || err.code !== STATUS_CODE.EOF)\n return cb(err);\n } else if (nb > len) {\n return cb(new Error('Received more data than requested'));\n } else if (nb === len && overflow) {\n req.nb += nb;\n req.position += nb;\n req.off += nb;\n read_(self, handle, buf, req.off, overflow, req.position, cb, req);\n return;\n }\n\n if (req.origOff === 0 && buf.length === req.nb)\n data = buf;\n else\n data = bufferSlice(buf, req.origOff, req.origOff + req.nb);\n cb(undefined, req.nb + (nb || 0), data, req.position);\n },\n buffer: undefined,\n });\n\n req.len = len;\n req.overflow = overflow;\n\n // TODO: avoid creating multiple buffer slices when we need to re-call read_()\n // because of overflow\n req.buffer = bufferSlice(buf, off, off + len);\n\n self._requests[reqid] = req;\n\n const isBuffered = sendOrBuffer(self, out);\n self._debug && self._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ`\n );\n}\n\nfunction fastXfer(src, dst, srcPath, dstPath, opts, cb) {\n let concurrency = 64;\n let chunkSize = 32768;\n let onstep;\n let mode;\n let fileSize;\n\n if (typeof opts === 'function') {\n cb = opts;\n } else if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.concurrency === 'number'\n && opts.concurrency > 0\n && !isNaN(opts.concurrency)) {\n concurrency = opts.concurrency;\n }\n if (typeof opts.chunkSize === 'number'\n && opts.chunkSize > 0\n && !isNaN(opts.chunkSize)) {\n chunkSize = opts.chunkSize;\n }\n if (typeof opts.fileSize === 'number'\n && opts.fileSize > 0\n && !isNaN(opts.fileSize)) {\n fileSize = opts.fileSize;\n }\n if (typeof opts.step === 'function')\n onstep = opts.step;\n\n if (typeof opts.mode === 'string' || typeof opts.mode === 'number')\n mode = modeNum(opts.mode);\n }\n\n // Internal state variables\n let fsize;\n let pdst = 0;\n let total = 0;\n let hadError = false;\n let srcHandle;\n let dstHandle;\n let readbuf;\n let bufsize = chunkSize * concurrency;\n\n function onerror(err) {\n if (hadError)\n return;\n\n hadError = true;\n\n let left = 0;\n let cbfinal;\n\n if (srcHandle || dstHandle) {\n cbfinal = () => {\n if (--left === 0)\n cb(err);\n };\n if (srcHandle && (src === fs || src.outgoing.state === 'open'))\n ++left;\n if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))\n ++left;\n if (srcHandle && (src === fs || src.outgoing.state === 'open'))\n src.close(srcHandle, cbfinal);\n if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))\n dst.close(dstHandle, cbfinal);\n } else {\n cb(err);\n }\n }\n\n src.open(srcPath, 'r', (err, sourceHandle) => {\n if (err)\n return onerror(err);\n\n srcHandle = sourceHandle;\n\n if (fileSize === undefined)\n src.fstat(srcHandle, tryStat);\n else\n tryStat(null, { size: fileSize });\n\n function tryStat(err, attrs) {\n if (err) {\n if (src !== fs) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n src.stat(srcPath, (err_, attrs_) => {\n if (err_)\n return onerror(err);\n tryStat(null, attrs_);\n });\n return;\n }\n return onerror(err);\n }\n fsize = attrs.size;\n\n dst.open(dstPath, 'w', (err, destHandle) => {\n if (err)\n return onerror(err);\n\n dstHandle = destHandle;\n\n if (fsize <= 0)\n return onerror();\n\n // Use less memory where possible\n while (bufsize > fsize) {\n if (concurrency === 1) {\n bufsize = fsize;\n break;\n }\n bufsize -= chunkSize;\n --concurrency;\n }\n\n readbuf = tryCreateBuffer(bufsize);\n if (readbuf instanceof Error)\n return onerror(readbuf);\n\n if (mode !== undefined) {\n dst.fchmod(dstHandle, mode, function tryAgain(err) {\n if (err) {\n // Try chmod() for sftp servers that may not support fchmod()\n // for whatever reason\n dst.chmod(dstPath, mode, (err_) => tryAgain());\n return;\n }\n startReads();\n });\n } else {\n startReads();\n }\n\n function onread(err, nb, data, dstpos, datapos, origChunkLen) {\n if (err)\n return onerror(err);\n\n datapos = datapos || 0;\n\n dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb);\n\n function writeCb(err) {\n if (err)\n return onerror(err);\n\n total += nb;\n onstep && onstep(total, nb, fsize);\n\n if (nb < origChunkLen)\n return singleRead(datapos, dstpos + nb, origChunkLen - nb);\n\n if (total === fsize) {\n dst.close(dstHandle, (err) => {\n dstHandle = undefined;\n if (err)\n return onerror(err);\n src.close(srcHandle, (err) => {\n srcHandle = undefined;\n if (err)\n return onerror(err);\n cb();\n });\n });\n return;\n }\n\n if (pdst >= fsize)\n return;\n\n const chunk =\n (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);\n singleRead(datapos, pdst, chunk);\n pdst += chunk;\n }\n }\n\n function makeCb(psrc, pdst, chunk) {\n return (err, nb, data) => {\n onread(err, nb, data, pdst, psrc, chunk);\n };\n }\n\n function singleRead(psrc, pdst, chunk) {\n src.read(srcHandle,\n readbuf,\n psrc,\n chunk,\n pdst,\n makeCb(psrc, pdst, chunk));\n }\n\n function startReads() {\n let reads = 0;\n let psrc = 0;\n while (pdst < fsize && reads < concurrency) {\n const chunk =\n (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);\n singleRead(psrc, pdst, chunk);\n psrc += chunk;\n pdst += chunk;\n ++reads;\n }\n }\n });\n }\n });\n}\n\nfunction writeAll(sftp, handle, buffer, offset, length, position, callback_) {\n const callback = (typeof callback_ === 'function' ? callback_ : undefined);\n\n sftp.write(handle,\n buffer,\n offset,\n length,\n position,\n (writeErr, written) => {\n if (writeErr) {\n return sftp.close(handle, () => {\n callback && callback(writeErr);\n });\n }\n if (written === length) {\n sftp.close(handle, callback);\n } else {\n offset += written;\n length -= written;\n position += written;\n writeAll(sftp, handle, buffer, offset, length, position, callback);\n }\n });\n}\n\nclass Stats {\n constructor(initial) {\n this.mode = (initial && initial.mode);\n this.uid = (initial && initial.uid);\n this.gid = (initial && initial.gid);\n this.size = (initial && initial.size);\n this.atime = (initial && initial.atime);\n this.mtime = (initial && initial.mtime);\n this.extended = (initial && initial.extended);\n }\n isDirectory() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFDIR);\n }\n isFile() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFREG);\n }\n isBlockDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFBLK);\n }\n isCharacterDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFCHR);\n }\n isSymbolicLink() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFLNK);\n }\n isFIFO() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFIFO);\n }\n isSocket() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK);\n }\n}\n\nfunction attrsToBytes(attrs) {\n let flags = 0;\n let nb = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n if (typeof attrs.size === 'number') {\n flags |= ATTR.SIZE;\n const val = attrs.size;\n // Big Endian\n ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56\n ATTRS_BUF[nb++] = val / 281474976710656; // 2**48\n ATTRS_BUF[nb++] = val / 1099511627776; // 2**40\n ATTRS_BUF[nb++] = val / 4294967296; // 2**32\n ATTRS_BUF[nb++] = val / 16777216; // 2**24\n ATTRS_BUF[nb++] = val / 65536; // 2**16\n ATTRS_BUF[nb++] = val / 256; // 2**8\n ATTRS_BUF[nb++] = val;\n }\n if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') {\n flags |= ATTR.UIDGID;\n const uid = attrs.uid;\n const gid = attrs.gid;\n // Big Endian\n ATTRS_BUF[nb++] = uid >>> 24;\n ATTRS_BUF[nb++] = uid >>> 16;\n ATTRS_BUF[nb++] = uid >>> 8;\n ATTRS_BUF[nb++] = uid;\n ATTRS_BUF[nb++] = gid >>> 24;\n ATTRS_BUF[nb++] = gid >>> 16;\n ATTRS_BUF[nb++] = gid >>> 8;\n ATTRS_BUF[nb++] = gid;\n }\n if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') {\n const mode = modeNum(attrs.mode);\n flags |= ATTR.PERMISSIONS;\n // Big Endian\n ATTRS_BUF[nb++] = mode >>> 24;\n ATTRS_BUF[nb++] = mode >>> 16;\n ATTRS_BUF[nb++] = mode >>> 8;\n ATTRS_BUF[nb++] = mode;\n }\n if ((typeof attrs.atime === 'number' || isDate(attrs.atime))\n && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) {\n const atime = toUnixTimestamp(attrs.atime);\n const mtime = toUnixTimestamp(attrs.mtime);\n\n flags |= ATTR.ACMODTIME;\n // Big Endian\n ATTRS_BUF[nb++] = atime >>> 24;\n ATTRS_BUF[nb++] = atime >>> 16;\n ATTRS_BUF[nb++] = atime >>> 8;\n ATTRS_BUF[nb++] = atime;\n ATTRS_BUF[nb++] = mtime >>> 24;\n ATTRS_BUF[nb++] = mtime >>> 16;\n ATTRS_BUF[nb++] = mtime >>> 8;\n ATTRS_BUF[nb++] = mtime;\n }\n // TODO: extended attributes\n }\n\n return { flags, nb };\n}\n\nfunction toUnixTimestamp(time) {\n // eslint-disable-next-line no-self-compare\n if (typeof time === 'number' && time === time) // Valid, non-NaN number\n return time;\n if (isDate(time))\n return parseInt(time.getTime() / 1000, 10);\n throw new Error(`Cannot parse time: ${time}`);\n}\n\nfunction modeNum(mode) {\n // eslint-disable-next-line no-self-compare\n if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number\n return mode;\n if (typeof mode === 'string')\n return modeNum(parseInt(mode, 8));\n throw new Error(`Cannot parse mode: ${mode}`);\n}\n\nconst stringFlagMap = {\n 'r': OPEN_MODE.READ,\n 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE,\n 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE,\n 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL\n};\n\nfunction stringToFlags(str) {\n const flags = stringFlagMap[str];\n return (flags !== undefined ? flags : null);\n}\n\nconst flagsToString = (() => {\n const stringFlagMapKeys = Object.keys(stringFlagMap);\n return (flags) => {\n for (let i = 0; i < stringFlagMapKeys.length; ++i) {\n const key = stringFlagMapKeys[i];\n if (stringFlagMap[key] === flags)\n return key;\n }\n return null;\n };\n})();\n\nfunction readAttrs(biOpt) {\n /*\n uint32 flags\n uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE\n uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID\n uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID\n uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS\n uint32 atime present only if flag SSH_FILEXFER_ACMODTIME\n uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME\n uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED\n string extended_type\n string extended_data\n ... more extended data (extended_type - extended_data pairs),\n so that number of pairs equals extended_count\n */\n const flags = bufferParser.readUInt32BE();\n if (flags === undefined)\n return;\n\n const attrs = new Stats();\n if (flags & ATTR.SIZE) {\n const size = bufferParser.readUInt64BE(biOpt);\n if (size === undefined)\n return;\n attrs.size = size;\n }\n\n if (flags & ATTR.UIDGID) {\n const uid = bufferParser.readUInt32BE();\n const gid = bufferParser.readUInt32BE();\n if (gid === undefined)\n return;\n attrs.uid = uid;\n attrs.gid = gid;\n }\n\n if (flags & ATTR.PERMISSIONS) {\n const mode = bufferParser.readUInt32BE();\n if (mode === undefined)\n return;\n attrs.mode = mode;\n }\n\n if (flags & ATTR.ACMODTIME) {\n const atime = bufferParser.readUInt32BE();\n const mtime = bufferParser.readUInt32BE();\n if (mtime === undefined)\n return;\n attrs.atime = atime;\n attrs.mtime = mtime;\n }\n\n if (flags & ATTR.EXTENDED) {\n const count = bufferParser.readUInt32BE();\n if (count === undefined)\n return;\n const extended = {};\n for (let i = 0; i < count; ++i) {\n const type = bufferParser.readString(true);\n const data = bufferParser.readString();\n if (data === undefined)\n return;\n extended[type] = data;\n }\n attrs.extended = extended;\n }\n\n return attrs;\n}\n\nfunction sendOrBuffer(sftp, payload) {\n const ret = tryWritePayload(sftp, payload);\n if (ret !== undefined) {\n sftp._buffer.push(ret);\n return false;\n }\n return true;\n}\n\nfunction tryWritePayload(sftp, payload) {\n const outgoing = sftp.outgoing;\n if (outgoing.state !== 'open')\n return;\n\n if (outgoing.window === 0) {\n sftp._waitWindow = true; // XXX: Unnecessary?\n return payload;\n }\n\n let ret;\n const len = payload.length;\n let p = 0;\n\n while (len - p > 0 && outgoing.window > 0) {\n const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize);\n outgoing.window -= actualLen;\n if (outgoing.window === 0) {\n sftp._waitWindow = true;\n sftp._chunkcb = drainBuffer;\n }\n\n if (p === 0 && actualLen === len) {\n sftp._protocol.channelData(sftp.outgoing.id, payload);\n } else {\n sftp._protocol.channelData(sftp.outgoing.id,\n bufferSlice(payload, p, p + actualLen));\n }\n\n p += actualLen;\n }\n\n if (len - p > 0) {\n if (p > 0)\n ret = bufferSlice(payload, p, len);\n else\n ret = payload; // XXX: should never get here?\n }\n\n return ret;\n}\n\nfunction drainBuffer() {\n this._chunkcb = undefined;\n const buffer = this._buffer;\n let i = 0;\n while (i < buffer.length) {\n const payload = buffer[i];\n const ret = tryWritePayload(this, payload);\n if (ret !== undefined) {\n if (ret !== payload)\n buffer[i] = ret;\n if (i > 0)\n this._buffer = buffer.slice(i);\n return;\n }\n ++i;\n }\n if (i > 0)\n this._buffer = [];\n}\n\nfunction doFatalSFTPError(sftp, msg, noDebug) {\n const err = new Error(msg);\n err.level = 'sftp-protocol';\n if (!noDebug && sftp._debug)\n sftp._debug(`SFTP: Inbound: ${msg}`);\n sftp.emit('error', err);\n sftp.destroy();\n cleanupRequests(sftp);\n return false;\n}\n\nfunction cleanupRequests(sftp) {\n const keys = Object.keys(sftp._requests);\n if (keys.length === 0)\n return;\n\n const reqs = sftp._requests;\n sftp._requests = {};\n const err = new Error('No response from server');\n for (let i = 0; i < keys.length; ++i) {\n const req = reqs[keys[i]];\n if (typeof req.cb === 'function')\n req.cb(err);\n }\n}\n\nfunction requestLimits(sftp, cb) {\n /*\n uint32 id\n string \"limits@openssh.com\"\n */\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 18, p);\n buf.utf8Write('limits@openssh.com', p += 4, 18);\n\n sftp._requests[reqid] = { extended: 'limits@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(sftp, buf);\n if (sftp._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`);\n }\n}\n\nconst CLIENT_HANDLERS = {\n [RESPONSE.VERSION]: (sftp, payload) => {\n if (sftp._version !== -1)\n return doFatalSFTPError(sftp, 'Duplicate VERSION packet');\n\n const extensions = {};\n\n /*\n uint32 version\n \n */\n bufferParser.init(payload, 1);\n let version = bufferParser.readUInt32BE();\n while (bufferParser.avail()) {\n const extName = bufferParser.readString(true);\n const extData = bufferParser.readString(true);\n if (extData === undefined) {\n version = undefined;\n break;\n }\n extensions[extName] = extData;\n }\n bufferParser.clear();\n\n if (version === undefined)\n return doFatalSFTPError(sftp, 'Malformed VERSION packet');\n\n if (sftp._debug) {\n const names = Object.keys(extensions);\n if (names.length) {\n sftp._debug(\n `SFTP: Inbound: Received VERSION (v${version}, exts:${names})`\n );\n } else {\n sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`);\n }\n }\n\n sftp._version = version;\n sftp._extensions = extensions;\n\n if (extensions['limits@openssh.com'] === '1') {\n return requestLimits(sftp, (err, limits) => {\n if (!err) {\n if (limits.maxPktLen > 0)\n sftp._maxOutPktLen = limits.maxPktLen;\n if (limits.maxReadLen > 0)\n sftp._maxReadLen = limits.maxReadLen;\n if (limits.maxWriteLen > 0)\n sftp._maxWriteLen = limits.maxWriteLen;\n sftp.maxOpenHandles = (\n limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity\n );\n }\n sftp.emit('ready');\n });\n }\n\n sftp.emit('ready');\n },\n [RESPONSE.STATUS]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n uint32 error/status code\n string error message (ISO-10646 UTF-8)\n string language tag\n */\n const errorCode = bufferParser.readUInt32BE();\n const errorMsg = bufferParser.readString(true);\n bufferParser.clear();\n\n // Note: we avoid checking that the error message and language tag are in\n // the packet because there are some broken implementations that incorrectly\n // omit them. The language tag in general was never really used amongst ssh\n // implementations, so in the case of a missing error message we just\n // default to something sensible.\n\n if (sftp._debug) {\n const jsonMsg = JSON.stringify(errorMsg);\n sftp._debug(\n `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})`\n );\n }\n const req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n if (req && typeof req.cb === 'function') {\n if (errorCode === STATUS_CODE.OK) {\n req.cb();\n return;\n }\n const err = new Error(errorMsg\n || STATUS_CODE_STR[errorCode]\n || 'Unknown status');\n err.code = errorCode;\n req.cb(err);\n }\n },\n [RESPONSE.HANDLE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined) {\n if (reqID !== undefined)\n delete sftp._requests[reqID];\n return doFatalSFTPError(sftp, 'Malformed HANDLE packet');\n }\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`);\n\n const req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n if (req && typeof req.cb === 'function')\n req.cb(undefined, handle);\n },\n [RESPONSE.DATA]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n string data\n */\n if (req && typeof req.cb === 'function') {\n if (req.buffer) {\n // We have already pre-allocated space to store the data\n\n const nb = bufferParser.readString(req.buffer);\n bufferParser.clear();\n\n if (nb !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`\n );\n req.cb(undefined, req.buffer, nb);\n return;\n }\n } else {\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})`\n );\n req.cb(undefined, data);\n return;\n }\n }\n } else {\n const nb = bufferParser.skipString();\n bufferParser.clear();\n if (nb !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`\n );\n return;\n }\n }\n\n return doFatalSFTPError(sftp, 'Malformed DATA packet');\n },\n [RESPONSE.NAME]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n uint32 count\n repeats count times:\n string filename\n string longname\n ATTRS attrs\n */\n const count = bufferParser.readUInt32BE();\n if (count !== undefined) {\n let names = [];\n for (let i = 0; i < count; ++i) {\n // We are going to assume UTF-8 for filenames despite the SFTPv3\n // spec not specifying an encoding because the specs for newer\n // versions of the protocol all explicitly specify UTF-8 for\n // filenames\n const filename = bufferParser.readString(true);\n\n // `longname` only exists in SFTPv3 and since it typically will\n // contain the filename, we assume it is also UTF-8\n const longname = bufferParser.readString(true);\n\n const attrs = readAttrs(sftp._biOpt);\n if (attrs === undefined) {\n names = undefined;\n break;\n }\n names.push({ filename, longname, attrs });\n }\n if (names !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})`\n );\n bufferParser.clear();\n if (req && typeof req.cb === 'function')\n req.cb(undefined, names);\n return;\n }\n }\n\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed NAME packet');\n },\n [RESPONSE.ATTRS]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n ATTRS attrs\n */\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n if (attrs !== undefined) {\n sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`);\n if (req && typeof req.cb === 'function')\n req.cb(undefined, attrs);\n return;\n }\n\n return doFatalSFTPError(sftp, 'Malformed ATTRS packet');\n },\n [RESPONSE.EXTENDED]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n if (reqID !== undefined) {\n const req = sftp._requests[reqID];\n if (req) {\n delete sftp._requests[reqID];\n switch (req.extended) {\n case 'statvfs@openssh.com':\n case 'fstatvfs@openssh.com': {\n /*\n uint64 f_bsize // file system block size\n uint64 f_frsize // fundamental fs block size\n uint64 f_blocks // number of blocks (unit f_frsize)\n uint64 f_bfree // free blocks in file system\n uint64 f_bavail // free blocks for non-root\n uint64 f_files // total file inodes\n uint64 f_ffree // free file inodes\n uint64 f_favail // free file inodes for to non-root\n uint64 f_fsid // file system id\n uint64 f_flag // bit mask of f_flag values\n uint64 f_namemax // maximum filename length\n */\n const biOpt = sftp._biOpt;\n const stats = {\n f_bsize: bufferParser.readUInt64BE(biOpt),\n f_frsize: bufferParser.readUInt64BE(biOpt),\n f_blocks: bufferParser.readUInt64BE(biOpt),\n f_bfree: bufferParser.readUInt64BE(biOpt),\n f_bavail: bufferParser.readUInt64BE(biOpt),\n f_files: bufferParser.readUInt64BE(biOpt),\n f_ffree: bufferParser.readUInt64BE(biOpt),\n f_favail: bufferParser.readUInt64BE(biOpt),\n f_sid: bufferParser.readUInt64BE(biOpt),\n f_flag: bufferParser.readUInt64BE(biOpt),\n f_namemax: bufferParser.readUInt64BE(biOpt),\n };\n if (stats.f_namemax === undefined)\n break;\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, stats);\n return;\n }\n case 'limits@openssh.com': {\n /*\n uint64 max-packet-length\n uint64 max-read-length\n uint64 max-write-length\n uint64 max-open-handles\n */\n const limits = {\n maxPktLen: bufferParser.readUInt64BE(),\n maxReadLen: bufferParser.readUInt64BE(),\n maxWriteLen: bufferParser.readUInt64BE(),\n maxOpenHandles: bufferParser.readUInt64BE(),\n };\n if (limits.maxOpenHandles === undefined)\n break;\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, limits);\n return;\n }\n default:\n // Unknown extended request\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`\n );\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb();\n return;\n }\n } else {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`\n );\n bufferParser.clear();\n return;\n }\n }\n\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet');\n },\n};\nconst SERVER_HANDLERS = {\n [REQUEST.INIT]: (sftp, payload) => {\n if (sftp._version !== -1)\n return doFatalSFTPError(sftp, 'Duplicate INIT packet');\n\n const extensions = {};\n\n /*\n uint32 version\n \n */\n bufferParser.init(payload, 1);\n let version = bufferParser.readUInt32BE();\n while (bufferParser.avail()) {\n const extName = bufferParser.readString(true);\n const extData = bufferParser.readString(true);\n if (extData === undefined) {\n version = undefined;\n break;\n }\n extensions[extName] = extData;\n }\n bufferParser.clear();\n\n if (version === undefined)\n return doFatalSFTPError(sftp, 'Malformed INIT packet');\n\n if (sftp._debug) {\n const names = Object.keys(extensions);\n if (names.length) {\n sftp._debug(\n `SFTP: Inbound: Received INIT (v${version}, exts:${names})`\n );\n } else {\n sftp._debug(`SFTP: Inbound: Received INIT (v${version})`);\n }\n }\n\n sendOrBuffer(sftp, SERVER_VERSION_BUFFER);\n\n sftp._version = version;\n sftp._extensions = extensions;\n sftp.emit('ready');\n },\n [REQUEST.OPEN]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string filename\n uint32 pflags\n ATTRS attrs\n */\n const filename = bufferParser.readString(true);\n const pflags = bufferParser.readUInt32BE();\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed OPEN packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`);\n\n if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.CLOSE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed CLOSE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`);\n\n if (!sftp.emit('CLOSE', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READ]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n uint64 offset\n uint32 len\n */\n const handle = bufferParser.readString();\n const offset = bufferParser.readUInt64BE(sftp._biOpt);\n const len = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (len === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed READ packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`);\n\n if (!sftp.emit('READ', reqID, handle, offset, len)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.WRITE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n uint64 offset\n string data\n */\n const handle = bufferParser.readString();\n const offset = bufferParser.readUInt64BE(sftp._biOpt);\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed WRITE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`);\n\n if (!sftp.emit('WRITE', reqID, handle, offset, data)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.LSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed LSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`);\n\n if (!sftp.emit('LSTAT', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.FSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed FSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`);\n\n if (!sftp.emit('FSTAT', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.SETSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n ATTRS attrs\n */\n const path = bufferParser.readString(true);\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed SETSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`);\n\n if (!sftp.emit('SETSTAT', reqID, path, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.FSETSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n ATTRS attrs\n */\n const handle = bufferParser.readString();\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received FSETSTAT (id:${reqID})`\n );\n\n if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.OPENDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed OPENDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`);\n\n if (!sftp.emit('OPENDIR', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed READDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`);\n\n if (!sftp.emit('READDIR', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.REMOVE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed REMOVE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`);\n\n if (!sftp.emit('REMOVE', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.MKDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n ATTRS attrs\n */\n const path = bufferParser.readString(true);\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed MKDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`);\n\n if (!sftp.emit('MKDIR', reqID, path, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.RMDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed RMDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`);\n\n if (!sftp.emit('RMDIR', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.REALPATH]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed REALPATH packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received REALPATH (id:${reqID})`\n );\n\n if (!sftp.emit('REALPATH', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.STAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed STAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`);\n\n if (!sftp.emit('STAT', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.RENAME]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string oldpath\n string newpath\n */\n const oldPath = bufferParser.readString(true);\n const newPath = bufferParser.readString(true);\n bufferParser.clear();\n\n if (newPath === undefined)\n return doFatalSFTPError(sftp, 'Malformed RENAME packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`);\n\n if (!sftp.emit('RENAME', reqID, oldPath, newPath)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READLINK]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed READLINK packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received READLINK (id:${reqID})`\n );\n\n if (!sftp.emit('READLINK', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.SYMLINK]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string linkpath\n string targetpath\n */\n const linkPath = bufferParser.readString(true);\n const targetPath = bufferParser.readString(true);\n bufferParser.clear();\n\n if (targetPath === undefined)\n return doFatalSFTPError(sftp, 'Malformed SYMLINK packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`);\n\n let handled;\n if (sftp._isOpenSSH) {\n // OpenSSH has linkpath and targetpath positions switched\n handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath);\n } else {\n handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath);\n }\n if (!handled) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.EXTENDED]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string extended-request\n ... any request-specific data ...\n */\n const extName = bufferParser.readString(true);\n if (extName === undefined) {\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed EXTENDED packet');\n }\n\n let extData;\n if (bufferParser.avail())\n extData = bufferParser.readRaw();\n bufferParser.clear();\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED (id:${reqID})`\n );\n\n if (!sftp.emit('EXTENDED', reqID, extName, extData)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n};\n\n// =============================================================================\n// ReadStream/WriteStream-related ==============================================\n// =============================================================================\nconst {\n ERR_INVALID_ARG_TYPE,\n ERR_OUT_OF_RANGE,\n validateNumber\n} = require('./node-fs-compat');\n\nconst kMinPoolSpace = 128;\n\nlet pool;\n// It can happen that we expect to read a large chunk of data, and reserve\n// a large chunk of the pool accordingly, but the read() call only filled\n// a portion of it. If a concurrently executing read() then uses the same pool,\n// the \"reserved\" portion cannot be used, so we allow it to be re-used as a\n// new pool later.\nconst poolFragments = [];\n\nfunction allocNewPool(poolSize) {\n if (poolFragments.length > 0)\n pool = poolFragments.pop();\n else\n pool = Buffer.allocUnsafe(poolSize);\n pool.used = 0;\n}\n\n// Check the `this.start` and `this.end` of stream.\nfunction checkPosition(pos, name) {\n if (!Number.isSafeInteger(pos)) {\n validateNumber(pos, name);\n if (!Number.isInteger(pos))\n throw new ERR_OUT_OF_RANGE(name, 'an integer', pos);\n throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);\n }\n if (pos < 0)\n throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);\n}\n\nfunction roundUpToMultipleOf8(n) {\n return (n + 7) & ~7; // Align to 8 byte boundary.\n}\n\nfunction ReadStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // A little bit bigger buffer and water marks by default\n if (options.highWaterMark === undefined)\n options.highWaterMark = 64 * 1024;\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n options.autoDestroy = false; // Node 14 major change.\n\n ReadableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'r' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.end = options.end;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesRead = 0;\n this.closed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (this.end === undefined) {\n this.end = Infinity;\n } else if (this.end !== Infinity) {\n checkPosition(this.end, 'end');\n\n if (this.start !== undefined && this.start > this.end) {\n throw new ERR_OUT_OF_RANGE(\n 'start',\n `<= \"end\" (here: ${this.end})`,\n this.start\n );\n }\n }\n\n this.on('end', function() {\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}\ninherits(ReadStream, ReadableStream);\n\nReadStream.prototype.open = function() {\n if (this._opening)\n return;\n\n this._opening = true;\n\n this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {\n this._opening = false;\n\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n\n this.handle = handle;\n this.emit('open', handle);\n this.emit('ready');\n // Start the flow of data.\n this.read();\n });\n};\n\nReadStream.prototype._read = function(n) {\n if (!Buffer.isBuffer(this.handle))\n return this.once('open', () => this._read(n));\n\n // XXX: safe to remove this?\n if (this.destroyed)\n return;\n\n if (!pool || pool.length - pool.used < kMinPoolSpace) {\n // Discard the old pool.\n allocNewPool(this.readableHighWaterMark\n || this._readableState.highWaterMark);\n }\n\n // Grab another reference to the pool in the case that while we're\n // in the thread pool another read() finishes up the pool, and\n // allocates a new one.\n const thisPool = pool;\n let toRead = Math.min(pool.length - pool.used, n);\n const start = pool.used;\n\n if (this.end !== undefined)\n toRead = Math.min(this.end - this.pos + 1, toRead);\n\n // Already read everything we were supposed to read!\n // treat as EOF.\n if (toRead <= 0)\n return this.push(null);\n\n // the actual read.\n this.sftp.read(this.handle,\n pool,\n pool.used,\n toRead,\n this.pos,\n (er, bytesRead) => {\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n let b = null;\n\n // Now that we know how much data we have actually read, re-wind the\n // 'used' field if we can, and otherwise allow the remainder of our\n // reservation to be used as a new pool later.\n if (start + toRead === thisPool.used && thisPool === pool) {\n thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead);\n } else {\n // Round down to the next lowest multiple of 8 to ensure the new pool\n // fragment start and end positions are aligned to an 8 byte boundary.\n const alignedEnd = (start + toRead) & ~7;\n const alignedStart = roundUpToMultipleOf8(start + bytesRead);\n if (alignedEnd - alignedStart >= kMinPoolSpace)\n poolFragments.push(thisPool.slice(alignedStart, alignedEnd));\n }\n\n if (bytesRead > 0) {\n this.bytesRead += bytesRead;\n b = thisPool.slice(start, start + bytesRead);\n }\n\n // Move the pool positions, and internal position for reading.\n this.pos += bytesRead;\n\n this.push(b);\n });\n\n pool.used = roundUpToMultipleOf8(pool.used + toRead);\n};\n\nReadStream.prototype._destroy = function(err, cb) {\n if (this._opening && !Buffer.isBuffer(this.handle)) {\n this.once('open', closeStream.bind(null, this, cb, err));\n return;\n }\n\n closeStream(this, cb, err);\n this.handle = null;\n this._opening = false;\n};\n\nfunction closeStream(stream, cb, err) {\n if (!stream.handle)\n return onclose();\n\n stream.sftp.close(stream.handle, onclose);\n\n function onclose(er) {\n er = er || err;\n cb(er);\n stream.closed = true;\n if (!er)\n stream.emit('close');\n }\n}\n\nReadStream.prototype.close = function(cb) {\n this.destroy(null, cb);\n};\n\nObject.defineProperty(ReadStream.prototype, 'pending', {\n get() {\n return this.handle === null;\n },\n configurable: true\n});\n\n// TODO: add `concurrency` setting to allow more than one in-flight WRITE\n// request to server to improve throughput\nfunction WriteStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n options.autoDestroy = false; // Node 14 major change.\n\n WritableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'w' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesWritten = 0;\n this.closed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (options.encoding)\n this.setDefaultEncoding(options.encoding);\n\n // Node v6.x only\n this.on('finish', function() {\n if (this._writableState.finalCalled)\n return;\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}\ninherits(WriteStream, WritableStream);\n\nWriteStream.prototype._final = function(cb) {\n if (this.autoClose)\n this.destroy();\n cb();\n};\n\nWriteStream.prototype.open = function() {\n if (this._opening)\n return;\n\n this._opening = true;\n\n this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {\n this._opening = false;\n\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n\n this.handle = handle;\n\n const tryAgain = (err) => {\n if (err) {\n // Try chmod() for sftp servers that may not support fchmod() for\n // whatever reason\n this.sftp.chmod(this.path, this.mode, (err_) => tryAgain());\n return;\n }\n\n // SFTPv3 requires absolute offsets, no matter the open flag used\n if (this.flags[0] === 'a') {\n const tryStat = (err, st) => {\n if (err) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.sftp.stat(this.path, (err_, st_) => {\n if (err_) {\n this.destroy();\n this.emit('error', err);\n return;\n }\n tryStat(null, st_);\n });\n return;\n }\n\n this.pos = st.size;\n this.emit('open', handle);\n this.emit('ready');\n };\n\n this.sftp.fstat(handle, tryStat);\n return;\n }\n\n this.emit('open', handle);\n this.emit('ready');\n };\n\n this.sftp.fchmod(handle, this.mode, tryAgain);\n });\n};\n\nWriteStream.prototype._write = function(data, encoding, cb) {\n if (!Buffer.isBuffer(data)) {\n const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data);\n return this.emit('error', err);\n }\n\n if (!Buffer.isBuffer(this.handle)) {\n return this.once('open', function() {\n this._write(data, encoding, cb);\n });\n }\n\n this.sftp.write(this.handle,\n data,\n 0,\n data.length,\n this.pos,\n (er, bytes) => {\n if (er) {\n if (this.autoClose)\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n cb();\n });\n\n this.pos += data.length;\n};\n\nWriteStream.prototype._writev = function(data, cb) {\n if (!Buffer.isBuffer(this.handle)) {\n return this.once('open', function() {\n this._writev(data, cb);\n });\n }\n\n const sftp = this.sftp;\n const handle = this.handle;\n let writesLeft = data.length;\n\n const onwrite = (er, bytes) => {\n if (er) {\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n if (--writesLeft === 0)\n cb();\n };\n\n // TODO: try to combine chunks to reduce number of requests to the server?\n for (let i = 0; i < data.length; ++i) {\n const chunk = data[i].chunk;\n\n sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite);\n this.pos += chunk.length;\n }\n};\n\nif (typeof WritableStream.prototype.destroy !== 'function')\n WriteStream.prototype.destroy = ReadStream.prototype.destroy;\n\nWriteStream.prototype._destroy = ReadStream.prototype._destroy;\nWriteStream.prototype.close = function(cb) {\n if (cb) {\n if (this.closed) {\n process.nextTick(cb);\n return;\n }\n this.on('close', cb);\n }\n\n // If we are not autoClosing, we should call\n // destroy on 'finish'.\n if (!this.autoClose)\n this.on('finish', this.destroy.bind(this));\n\n this.end();\n};\n\n// There is no shutdown() for files.\nWriteStream.prototype.destroySoon = WriteStream.prototype.end;\n\nObject.defineProperty(WriteStream.prototype, 'pending', {\n get() {\n return this.handle === null;\n },\n configurable: true\n});\n// =============================================================================\n\nmodule.exports = {\n flagsToString,\n OPEN_MODE,\n SFTP,\n Stats,\n STATUS_CODE,\n stringToFlags,\n};\n","'use strict';\n\nconst crypto = require('crypto');\n\nlet cpuInfo;\ntry {\n cpuInfo = require('cpu-features')();\n} catch {}\n\nconst { bindingAvailable } = require('./crypto.js');\n\nconst eddsaSupported = (() => {\n if (typeof crypto.sign === 'function'\n && typeof crypto.verify === 'function') {\n const key =\n '-----BEGIN PRIVATE KEY-----\\r\\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD'\n + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\\r\\n-----END PRIVATE KEY-----';\n const data = Buffer.from('a');\n let sig;\n let verified;\n try {\n sig = crypto.sign(null, data, key);\n verified = crypto.verify(null, data, key, sig);\n } catch {}\n return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true);\n }\n\n return false;\n})();\n\nconst curve25519Supported = (typeof crypto.diffieHellman === 'function'\n && typeof crypto.generateKeyPairSync === 'function'\n && typeof crypto.createPublicKey === 'function');\n\nconst DEFAULT_KEX = [\n // https://tools.ietf.org/html/rfc5656#section-10.1\n 'ecdh-sha2-nistp256',\n 'ecdh-sha2-nistp384',\n 'ecdh-sha2-nistp521',\n\n // https://tools.ietf.org/html/rfc4419#section-4\n 'diffie-hellman-group-exchange-sha256',\n\n // https://tools.ietf.org/html/rfc8268\n 'diffie-hellman-group14-sha256',\n 'diffie-hellman-group15-sha512',\n 'diffie-hellman-group16-sha512',\n 'diffie-hellman-group17-sha512',\n 'diffie-hellman-group18-sha512',\n];\nif (curve25519Supported) {\n DEFAULT_KEX.unshift('curve25519-sha256');\n DEFAULT_KEX.unshift('curve25519-sha256@libssh.org');\n}\nconst SUPPORTED_KEX = DEFAULT_KEX.concat([\n // https://tools.ietf.org/html/rfc4419#section-4\n 'diffie-hellman-group-exchange-sha1',\n\n 'diffie-hellman-group14-sha1', // REQUIRED\n 'diffie-hellman-group1-sha1', // REQUIRED\n]);\n\n\nconst DEFAULT_SERVER_HOST_KEY = [\n 'ecdsa-sha2-nistp256',\n 'ecdsa-sha2-nistp384',\n 'ecdsa-sha2-nistp521',\n 'rsa-sha2-512', // RFC 8332\n 'rsa-sha2-256', // RFC 8332\n 'ssh-rsa',\n];\nif (eddsaSupported)\n DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519');\nconst SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([\n 'ssh-dss',\n]);\n\n\nconst DEFAULT_CIPHER = [\n // http://tools.ietf.org/html/rfc5647\n 'aes128-gcm@openssh.com',\n 'aes256-gcm@openssh.com',\n\n // http://tools.ietf.org/html/rfc4344#section-4\n 'aes128-ctr',\n 'aes192-ctr',\n 'aes256-ctr',\n];\nif (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) {\n // We know for sure the CPU does not support AES acceleration\n if (bindingAvailable)\n DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com');\n else\n DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com');\n} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') {\n // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers\n // seem to outperform it on x86, but it seems to be faster than CTR ciphers\n DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com');\n} else {\n DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com');\n}\nconst SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([\n 'aes256-cbc',\n 'aes192-cbc',\n 'aes128-cbc',\n 'blowfish-cbc',\n '3des-cbc',\n 'aes128-gcm',\n 'aes256-gcm',\n\n // http://tools.ietf.org/html/rfc4345#section-4:\n 'arcfour256',\n 'arcfour128',\n\n 'cast128-cbc',\n 'arcfour',\n]);\n\n\nconst DEFAULT_MAC = [\n 'hmac-sha2-256-etm@openssh.com',\n 'hmac-sha2-512-etm@openssh.com',\n 'hmac-sha1-etm@openssh.com',\n 'hmac-sha2-256',\n 'hmac-sha2-512',\n 'hmac-sha1',\n];\nconst SUPPORTED_MAC = DEFAULT_MAC.concat([\n 'hmac-md5',\n 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256\n 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512\n 'hmac-ripemd160',\n 'hmac-sha1-96', // first 96 bits of HMAC-SHA1\n 'hmac-md5-96', // first 96 bits of HMAC-MD5\n]);\n\nconst DEFAULT_COMPRESSION = [\n 'none',\n 'zlib@openssh.com', // ZLIB (LZ77) compression, except\n // compression/decompression does not start until after\n // successful user authentication\n 'zlib', // ZLIB (LZ77) compression\n];\nconst SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([\n]);\n\n\nconst COMPAT = {\n BAD_DHGEX: 1 << 0,\n OLD_EXIT: 1 << 1,\n DYN_RPORT_BUG: 1 << 2,\n BUG_DHGEX_LARGE: 1 << 3,\n};\n\nmodule.exports = {\n MESSAGE: {\n // Transport layer protocol -- generic (1-19)\n DISCONNECT: 1,\n IGNORE: 2,\n UNIMPLEMENTED: 3,\n DEBUG: 4,\n SERVICE_REQUEST: 5,\n SERVICE_ACCEPT: 6,\n\n // Transport layer protocol -- algorithm negotiation (20-29)\n KEXINIT: 20,\n NEWKEYS: 21,\n\n // Transport layer protocol -- key exchange method-specific (30-49)\n KEXDH_INIT: 30,\n KEXDH_REPLY: 31,\n\n KEXDH_GEX_GROUP: 31,\n KEXDH_GEX_INIT: 32,\n KEXDH_GEX_REPLY: 33,\n KEXDH_GEX_REQUEST: 34,\n\n KEXECDH_INIT: 30,\n KEXECDH_REPLY: 31,\n\n // User auth protocol -- generic (50-59)\n USERAUTH_REQUEST: 50,\n USERAUTH_FAILURE: 51,\n USERAUTH_SUCCESS: 52,\n USERAUTH_BANNER: 53,\n\n // User auth protocol -- user auth method-specific (60-79)\n USERAUTH_PASSWD_CHANGEREQ: 60,\n\n USERAUTH_PK_OK: 60,\n\n USERAUTH_INFO_REQUEST: 60,\n USERAUTH_INFO_RESPONSE: 61,\n\n // Connection protocol -- generic (80-89)\n GLOBAL_REQUEST: 80,\n REQUEST_SUCCESS: 81,\n REQUEST_FAILURE: 82,\n\n // Connection protocol -- channel-related (90-127)\n CHANNEL_OPEN: 90,\n CHANNEL_OPEN_CONFIRMATION: 91,\n CHANNEL_OPEN_FAILURE: 92,\n CHANNEL_WINDOW_ADJUST: 93,\n CHANNEL_DATA: 94,\n CHANNEL_EXTENDED_DATA: 95,\n CHANNEL_EOF: 96,\n CHANNEL_CLOSE: 97,\n CHANNEL_REQUEST: 98,\n CHANNEL_SUCCESS: 99,\n CHANNEL_FAILURE: 100\n\n // Reserved for client protocols (128-191)\n\n // Local extensions (192-155)\n },\n DISCONNECT_REASON: {\n HOST_NOT_ALLOWED_TO_CONNECT: 1,\n PROTOCOL_ERROR: 2,\n KEY_EXCHANGE_FAILED: 3,\n RESERVED: 4,\n MAC_ERROR: 5,\n COMPRESSION_ERROR: 6,\n SERVICE_NOT_AVAILABLE: 7,\n PROTOCOL_VERSION_NOT_SUPPORTED: 8,\n HOST_KEY_NOT_VERIFIABLE: 9,\n CONNECTION_LOST: 10,\n BY_APPLICATION: 11,\n TOO_MANY_CONNECTIONS: 12,\n AUTH_CANCELED_BY_USER: 13,\n NO_MORE_AUTH_METHODS_AVAILABLE: 14,\n ILLEGAL_USER_NAME: 15,\n },\n DISCONNECT_REASON_STR: undefined,\n CHANNEL_OPEN_FAILURE: {\n ADMINISTRATIVELY_PROHIBITED: 1,\n CONNECT_FAILED: 2,\n UNKNOWN_CHANNEL_TYPE: 3,\n RESOURCE_SHORTAGE: 4\n },\n TERMINAL_MODE: {\n TTY_OP_END: 0, // Indicates end of options.\n VINTR: 1, // Interrupt character; 255 if none. Similarly for the\n // other characters. Not all of these characters are\n // supported on all systems.\n VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX\n // systems).\n VERASE: 3, // Erase the character to left of the cursor.\n VKILL: 4, // Kill the current input line.\n VEOF: 5, // End-of-file character (sends EOF from the\n // terminal).\n VEOL: 6, // End-of-line character in addition to carriage\n // return and/or linefeed.\n VEOL2: 7, // Additional end-of-line character.\n VSTART: 8, // Continues paused output (normally control-Q).\n VSTOP: 9, // Pauses output (normally control-S).\n VSUSP: 10, // Suspends the current program.\n VDSUSP: 11, // Another suspend character.\n VREPRINT: 12, // Reprints the current input line.\n VWERASE: 13, // Erases a word left of cursor.\n VLNEXT: 14, // Enter the next character typed literally, even if\n // it is a special character\n VFLUSH: 15, // Character to flush output.\n VSWTCH: 16, // Switch to a different shell layer.\n VSTATUS: 17, // Prints system status line (load, command, pid,\n // etc).\n VDISCARD: 18, // Toggles the flushing of terminal output.\n IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0\n // if this flag is FALSE, and 1 if it is TRUE.\n PARMRK: 31, // Mark parity and framing errors.\n INPCK: 32, // Enable checking of parity errors.\n ISTRIP: 33, // Strip 8th bit off characters.\n INLCR: 34, // Map NL into CR on input.\n IGNCR: 35, // Ignore CR on input.\n ICRNL: 36, // Map CR to NL on input.\n IUCLC: 37, // Translate uppercase characters to lowercase.\n IXON: 38, // Enable output flow control.\n IXANY: 39, // Any char will restart after stop.\n IXOFF: 40, // Enable input flow control.\n IMAXBEL: 41, // Ring bell on input queue full.\n ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP.\n ICANON: 51, // Canonicalize input lines.\n XCASE: 52, // Enable input and output of uppercase characters by\n // preceding their lowercase equivalents with \"\\\".\n ECHO: 53, // Enable echoing.\n ECHOE: 54, // Visually erase chars.\n ECHOK: 55, // Kill character discards current line.\n ECHONL: 56, // Echo NL even if ECHO is off.\n NOFLSH: 57, // Don't flush after interrupt.\n TOSTOP: 58, // Stop background jobs from output.\n IEXTEN: 59, // Enable extensions.\n ECHOCTL: 60, // Echo control characters as ^(Char).\n ECHOKE: 61, // Visual erase for line kill.\n PENDIN: 62, // Retype pending input.\n OPOST: 70, // Enable output processing.\n OLCUC: 71, // Convert lowercase to uppercase.\n ONLCR: 72, // Map NL to CR-NL.\n OCRNL: 73, // Translate carriage return to newline (output).\n ONOCR: 74, // Translate newline to carriage return-newline\n // (output).\n ONLRET: 75, // Newline performs a carriage return (output).\n CS7: 90, // 7 bit mode.\n CS8: 91, // 8 bit mode.\n PARENB: 92, // Parity enable.\n PARODD: 93, // Odd parity, else even.\n TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second.\n TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second.\n },\n CHANNEL_EXTENDED_DATATYPE: {\n STDERR: 1,\n },\n\n SIGNALS: [\n 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1',\n 'USR2', 'KILL', 'PIPE'\n ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}),\n\n COMPAT,\n COMPAT_CHECKS: [\n [ 'Cisco-1.25', COMPAT.BAD_DHGEX ],\n [ /^Cisco-1\\./, COMPAT.BUG_DHGEX_LARGE ],\n [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations\n [ /^OpenSSH_5\\.\\d+/, COMPAT.DYN_RPORT_BUG ],\n ],\n\n // KEX proposal-related\n DEFAULT_KEX,\n SUPPORTED_KEX,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER,\n DEFAULT_MAC,\n SUPPORTED_MAC,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION,\n\n curve25519Supported,\n eddsaSupported,\n};\n\nmodule.exports.DISCONNECT_REASON_BY_VALUE =\n Array.from(Object.entries(module.exports.DISCONNECT_REASON))\n .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {});\n","// TODO:\n// * make max packet size configurable\n// * if decompression is enabled, use `._packet` in decipher instances as\n// input to (sync) zlib inflater with appropriate offset and length to\n// avoid an additional copy of payload data before inflation\n// * factor decompression status into packet length checks\n'use strict';\n\nconst {\n createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual\n} = require('crypto');\n\nconst { readUInt32BE, writeUInt32BE } = require('./utils.js');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst MAX_SEQNO = 2 ** 32 - 1;\nconst EMPTY_BUFFER = Buffer.alloc(0);\nconst BUF_INT = Buffer.alloc(4);\nconst DISCARD_CACHE = new Map();\nconst MAX_PACKET_SIZE = 35000;\n\nlet binding;\nlet AESGCMCipher;\nlet ChaChaPolyCipher;\nlet GenericCipher;\nlet AESGCMDecipher;\nlet ChaChaPolyDecipher;\nlet GenericDecipher;\ntry {\n binding = require('./crypto/build/Release/sshcrypto.node');\n ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher,\n AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding);\n} catch {}\n\nconst CIPHER_STREAM = 1 << 0;\nconst CIPHER_INFO = (() => {\n function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) {\n return {\n sslName,\n blockLen,\n keyLen,\n ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM)\n ? ivLen\n : blockLen),\n authLen,\n discardLen,\n stream: !!(flags & CIPHER_STREAM),\n };\n }\n\n return {\n 'chacha20-poly1305@openssh.com':\n info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM),\n\n 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM),\n 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM),\n 'aes128-gcm@openssh.com':\n info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM),\n 'aes256-gcm@openssh.com':\n info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM),\n\n 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0),\n 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0),\n 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0),\n 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0),\n '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0),\n 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0),\n 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0),\n 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0),\n\n 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM),\n 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM),\n 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM),\n '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM),\n 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM),\n 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM),\n\n /* The \"arcfour128\" algorithm is the RC4 cipher, as described in\n [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream\n generated by the cipher MUST be discarded, and the first byte of the\n first encrypted packet MUST be encrypted using the 1537th byte of\n keystream.\n\n -- http://tools.ietf.org/html/rfc4345#section-4 */\n 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM),\n };\n})();\n\nconst MAC_INFO = (() => {\n function info(sslName, len, actualLen, isETM) {\n return {\n sslName,\n len,\n actualLen,\n isETM,\n };\n }\n\n return {\n 'hmac-md5': info('md5', 16, 16, false),\n 'hmac-md5-96': info('md5', 16, 12, false),\n 'hmac-ripemd160': info('ripemd160', 20, 20, false),\n 'hmac-sha1': info('sha1', 20, 20, false),\n 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true),\n 'hmac-sha1-96': info('sha1', 20, 12, false),\n 'hmac-sha2-256': info('sha256', 32, 32, false),\n 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true),\n 'hmac-sha2-256-96': info('sha256', 32, 12, false),\n 'hmac-sha2-512': info('sha512', 64, 64, false),\n 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true),\n 'hmac-sha2-512-96': info('sha512', 64, 12, false),\n };\n})();\n\n\n// Should only_be used during the initial handshake\nclass NullCipher {\n constructor(seqno, onWrite) {\n this.outSeqno = seqno;\n this._onWrite = onWrite;\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - (pktLen & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nconst POLY1305_ZEROS = Buffer.alloc(32);\nconst POLY1305_OUT_COMPUTE = Buffer.alloc(16);\nlet POLY1305_WASM_MODULE;\nlet POLY1305_RESULT_MALLOC;\nlet poly1305_auth;\nclass ChaChaPolyCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encKeyMain = enc.cipherKey.slice(0, 32);\n this._encKeyPktLen = enc.cipherKey.slice(32);\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - ((pktLen - 4) & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Generate Poly1305 key\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12);\n const polyKey =\n createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE)\n .update(POLY1305_ZEROS);\n\n // Encrypt packet length\n const pktLenEnc =\n createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE)\n .update(packet.slice(0, 4));\n this._onWrite(pktLenEnc);\n\n // Encrypt rest of packet\n POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian)\n const payloadEnc =\n createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE)\n .update(packet.slice(4));\n this._onWrite(payloadEnc);\n\n // Calculate Poly1305 MAC\n poly1305_auth(POLY1305_RESULT_MALLOC,\n pktLenEnc,\n pktLenEnc.length,\n payloadEnc,\n payloadEnc.length,\n polyKey);\n const mac = Buffer.allocUnsafe(16);\n mac.set(\n new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer,\n POLY1305_RESULT_MALLOC,\n 16),\n 0\n );\n this._onWrite(mac);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass ChaChaPolyCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._instance = new ChaChaPolyCipher(enc.cipherKey);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - ((pktLen - 4) & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet, this.outSeqno);\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass AESGCMCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encSSLName = enc.cipherInfo.sslName;\n this._encKey = enc.cipherKey;\n this._encIV = enc.cipherIV;\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 16 - ((pktLen - 4) & (16 - 1));\n if (padLen < 4)\n padLen += 16;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV);\n cipher.setAutoPadding(false);\n\n const lenData = packet.slice(0, 4);\n cipher.setAAD(lenData);\n this._onWrite(lenData);\n\n // Encrypt pad length, payload, and padding\n const encrypted = cipher.update(packet.slice(4));\n this._onWrite(encrypted);\n const final = cipher.final();\n // XXX: final.length === 0 always?\n if (final.length)\n this._onWrite(final);\n\n // Generate MAC\n const tag = cipher.getAuthTag();\n this._onWrite(tag);\n\n // Increment counter in IV by 1 for next packet\n ivIncrement(this._encIV);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass AESGCMCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._instance = new AESGCMCipher(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 16 - ((pktLen - 4) & (16 - 1));\n if (padLen < 4)\n padLen += 16;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet);\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass GenericCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encBlockLen = enc.cipherInfo.blockLen;\n this._cipherInstance = createCipheriv(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV);\n this._macSSLName = enc.macInfo.sslName;\n this._macKey = enc.macKey;\n this._macActualLen = enc.macInfo.actualLen;\n this._macETM = enc.macInfo.isETM;\n this._aadLen = (this._macETM ? 4 : 0);\n this._dead = false;\n\n const discardLen = enc.cipherInfo.discardLen;\n if (discardLen) {\n let discard = DISCARD_CACHE.get(discardLen);\n if (discard === undefined) {\n discard = Buffer.alloc(discardLen);\n DISCARD_CACHE.set(discardLen, discard);\n }\n this._cipherInstance.update(discard);\n }\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n const blockLen = this._encBlockLen;\n\n let pktLen = 4 + 1 + payloadLen;\n let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1));\n if (padLen < 4)\n padLen += blockLen;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n let mac;\n if (this._macETM) {\n // Encrypt pad length, payload, and padding\n const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4);\n const encrypted = this._cipherInstance.update(\n new Uint8Array(packet.buffer,\n packet.byteOffset + 4,\n packet.length - 4)\n );\n\n this._onWrite(lenBytes);\n this._onWrite(encrypted);\n\n // TODO: look into storing seqno as 4-byte buffer and incrementing like we\n // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time\n mac = createHmac(this._macSSLName, this._macKey);\n writeUInt32BE(BUF_INT, this.outSeqno, 0);\n mac.update(BUF_INT);\n mac.update(lenBytes);\n mac.update(encrypted);\n } else {\n // Encrypt length field, pad length, payload, and padding\n const encrypted = this._cipherInstance.update(packet);\n this._onWrite(encrypted);\n\n // TODO: look into storing seqno as 4-byte buffer and incrementing like we\n // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time\n mac = createHmac(this._macSSLName, this._macKey);\n writeUInt32BE(BUF_INT, this.outSeqno, 0);\n mac.update(BUF_INT);\n mac.update(packet);\n }\n\n let digest = mac.digest();\n if (digest.length > this._macActualLen)\n digest = digest.slice(0, this._macActualLen);\n this._onWrite(digest);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass GenericCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encBlockLen = enc.cipherInfo.blockLen;\n this._macLen = enc.macInfo.len;\n this._macActualLen = enc.macInfo.actualLen;\n this._aadLen = (enc.macInfo.isETM ? 4 : 0);\n this._instance = new GenericCipher(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV,\n enc.macInfo.sslName,\n enc.macKey,\n enc.macInfo.isETM);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n const blockLen = this._encBlockLen;\n\n let pktLen = 4 + 1 + payloadLen;\n let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1));\n if (padLen < 4)\n padLen += blockLen;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + this._macLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet, this.outSeqno);\n\n if (this._macActualLen < this._macLen) {\n packet = new FastBuffer(packet.buffer,\n packet.byteOffset,\n (packet.length\n - (this._macLen - this._macActualLen)));\n }\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass NullDecipher {\n constructor(seqno, onPayload) {\n this.inSeqno = seqno;\n this._onPayload = onPayload;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n while (p < dataLen) {\n // Read packet length\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n\n if (this._lenBytes < 4)\n return;\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (4 + this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._packetPos < this._len) {\n const nb = Math.min(this._len - this._packetPos, dataLen - p);\n let chunk;\n if (p !== 0 || nb !== dataLen)\n chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n chunk = data;\n if (nb === this._len) {\n this._packet = chunk;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(chunk, this._packetPos);\n }\n p += nb;\n this._packetPos += nb;\n if (this._packetPos < this._len)\n return;\n }\n\n const payload = (!this._packet\n ? EMPTY_BUFFER\n : new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length\n - this._packet[0] - 1));\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass ChaChaPolyDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decKeyMain = dec.decipherKey.slice(0, 32);\n this._decKeyPktLen = dec.decipherKey.slice(32);\n this._len = 0;\n this._lenBuf = Buffer.alloc(4);\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(16);\n this._calcMac = Buffer.allocUnsafe(16);\n this._macPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length\n if (this._lenPos < 4) {\n let nb = Math.min(4 - this._lenPos, dataLen - p);\n while (nb--)\n this._lenBuf[this._lenPos++] = data[p++];\n if (this._lenPos < 4)\n return;\n\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);\n\n const decLenBytes =\n createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE)\n .update(this._lenBuf);\n this._len = readUInt32BE(decLenBytes, 0);\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read Poly1305 MAC\n {\n const nb = Math.min(16 - this._macPos, dataLen - p);\n // TODO: avoid copying if entire MAC is in current chunk\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < 16)\n return;\n }\n\n // Generate Poly1305 key\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);\n const polyKey =\n createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE)\n .update(POLY1305_ZEROS);\n\n // Calculate and compare Poly1305 MACs\n poly1305_auth(POLY1305_RESULT_MALLOC,\n this._lenBuf,\n 4,\n this._packet,\n this._packet.length,\n polyKey);\n\n this._calcMac.set(\n new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer,\n POLY1305_RESULT_MALLOC,\n 16),\n 0\n );\n if (!timingSafeEqual(this._calcMac, this._mac))\n throw new Error('Invalid MAC');\n\n // Decrypt packet\n POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian)\n const packet =\n createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE)\n .update(this._packet);\n\n const payload = new FastBuffer(packet.buffer,\n packet.byteOffset + 1,\n packet.length - packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass ChaChaPolyDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new ChaChaPolyDecipher(dec.decipherKey);\n this._len = 0;\n this._lenBuf = Buffer.alloc(4);\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(16);\n this._macPos = 0;\n }\n free() {\n this._instance.free();\n }\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length\n if (this._lenPos < 4) {\n let nb = Math.min(4 - this._lenPos, dataLen - p);\n while (nb--)\n this._lenBuf[this._lenPos++] = data[p++];\n if (this._lenPos < 4)\n return;\n\n this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno);\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read Poly1305 MAC\n {\n const nb = Math.min(16 - this._macPos, dataLen - p);\n // TODO: avoid copying if entire MAC is in current chunk\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < 16)\n return;\n }\n\n this._instance.decrypt(this._packet, this._mac, this.inSeqno);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass AESGCMDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decipherInstance = null;\n this._decipherSSLName = dec.decipherInfo.sslName;\n this._decipherKey = dec.decipherKey;\n this._decipherIV = dec.decipherIV;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._tag = Buffer.allocUnsafe(16);\n this._tagPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length (unencrypted, but AAD)\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n if (this._lenBytes < 4)\n return;\n\n if ((this._len + 20) > MAX_PACKET_SIZE\n || this._len < 16\n || (this._len & 15) !== 0) {\n throw new Error('Bad packet length');\n }\n\n this._decipherInstance = createDecipheriv(\n this._decipherSSLName,\n this._decipherKey,\n this._decipherIV\n );\n this._decipherInstance.setAutoPadding(false);\n this._decipherInstance.setAAD(intToBytes(this._len));\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let decrypted;\n if (p !== 0 || nb !== dataLen) {\n decrypted = this._decipherInstance.update(\n new Uint8Array(data.buffer, data.byteOffset + p, nb)\n );\n } else {\n decrypted = this._decipherInstance.update(data);\n }\n if (decrypted.length) {\n if (nb === this._len) {\n this._packet = decrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(decrypted, this._packetPos);\n }\n this._packetPos += decrypted.length;\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read authentication tag\n {\n const nb = Math.min(16 - this._tagPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._tag.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._tagPos\n );\n } else {\n this._tag.set(data, this._tagPos);\n }\n p += nb;\n this._tagPos += nb;\n if (this._tagPos < 16)\n return;\n }\n\n {\n // Verify authentication tag\n this._decipherInstance.setAuthTag(this._tag);\n\n const decrypted = this._decipherInstance.final();\n\n // XXX: this should never output any data since stream ciphers always\n // return data from .update() and block ciphers must end on a multiple\n // of the block length, which would have caused an exception to be\n // thrown if the total input was not...\n if (decrypted.length) {\n if (this._packet)\n this._packet.set(decrypted, this._packetPos);\n else\n this._packet = decrypted;\n }\n }\n\n const payload = (!this._packet\n ? EMPTY_BUFFER\n : new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length\n - this._packet[0] - 1));\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n ivIncrement(this._decipherIV);\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._tagPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass AESGCMDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new AESGCMDecipher(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV);\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._pktLen = 0;\n this._tag = Buffer.allocUnsafe(16);\n this._tagPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length (unencrypted, but AAD)\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n if (this._lenBytes < 4)\n return;\n\n if ((this._len + 20) > MAX_PACKET_SIZE\n || this._len < 16\n || (this._len & 15) !== 0) {\n throw new Error(`Bad packet length: ${this._len}`);\n }\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read authentication tag\n {\n const nb = Math.min(16 - this._tagPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._tag.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._tagPos\n );\n } else {\n this._tag.set(data, this._tagPos);\n }\n p += nb;\n this._tagPos += nb;\n if (this._tagPos < 16)\n return;\n }\n\n this._instance.decrypt(this._packet, this._len, this._tag);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._pktLen = 0;\n this._tagPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\n// TODO: test incremental .update()s vs. copying to _packet and doing a single\n// .update() after entire packet read -- a single .update() would allow\n// verifying MAC before decrypting for ETM MACs\nclass GenericDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV);\n this._decipherInstance.setAutoPadding(false);\n this._block = Buffer.allocUnsafe(\n dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen\n );\n this._blockSize = dec.decipherInfo.blockLen;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen);\n this._macPos = 0;\n this._macSSLName = dec.macInfo.sslName;\n this._macKey = dec.macKey;\n this._macActualLen = dec.macInfo.actualLen;\n this._macETM = dec.macInfo.isETM;\n this._macInstance = null;\n\n const discardLen = dec.decipherInfo.discardLen;\n if (discardLen) {\n let discard = DISCARD_CACHE.get(discardLen);\n if (discard === undefined) {\n discard = Buffer.alloc(discardLen);\n DISCARD_CACHE.set(discardLen, discard);\n }\n this._decipherInstance.update(discard);\n }\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read first encrypted block\n if (this._blockPos < this._block.length) {\n const nb = Math.min(this._block.length - this._blockPos, dataLen - p);\n if (p !== 0 || nb !== dataLen || nb < data.length) {\n this._block.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._blockPos\n );\n } else {\n this._block.set(data, this._blockPos);\n }\n\n p += nb;\n this._blockPos += nb;\n if (this._blockPos < this._block.length)\n return;\n\n let decrypted;\n let need;\n if (this._macETM) {\n this._len = need = readUInt32BE(this._block, 0);\n } else {\n // Decrypt first block to get packet length\n decrypted = this._decipherInstance.update(this._block);\n this._len = readUInt32BE(decrypted, 0);\n need = 4 + this._len - this._blockSize;\n }\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 5\n || (need & (this._blockSize - 1)) !== 0) {\n throw new Error('Bad packet length');\n }\n\n // Create MAC up front to calculate in parallel with decryption\n this._macInstance = createHmac(this._macSSLName, this._macKey);\n\n writeUInt32BE(BUF_INT, this.inSeqno, 0);\n this._macInstance.update(BUF_INT);\n if (this._macETM) {\n this._macInstance.update(this._block);\n } else {\n this._macInstance.update(new Uint8Array(decrypted.buffer,\n decrypted.byteOffset,\n 4));\n this._pktLen = decrypted.length - 4;\n this._packetPos = this._pktLen;\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(\n new Uint8Array(decrypted.buffer,\n decrypted.byteOffset + 4,\n this._packetPos),\n 0\n );\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (this._macETM)\n this._macInstance.update(encrypted);\n const decrypted = this._decipherInstance.update(encrypted);\n if (decrypted.length) {\n if (nb === this._len) {\n this._packet = decrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(decrypted, this._packetPos);\n }\n this._packetPos += decrypted.length;\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read MAC\n {\n const nb = Math.min(this._macActualLen - this._macPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < this._macActualLen)\n return;\n }\n\n // Verify MAC\n if (!this._macETM)\n this._macInstance.update(this._packet);\n let calculated = this._macInstance.digest();\n if (this._macActualLen < calculated.length) {\n calculated = new Uint8Array(calculated.buffer,\n calculated.byteOffset,\n this._macActualLen);\n }\n if (!timingSafeEquals(calculated, this._mac))\n throw new Error('Invalid MAC');\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._macPos = 0;\n this._macInstance = null;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass GenericDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new GenericDecipher(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV,\n dec.macInfo.sslName,\n dec.macKey,\n dec.macInfo.isETM,\n dec.macInfo.actualLen);\n this._block = Buffer.allocUnsafe(\n dec.macInfo.isETM || dec.decipherInfo.stream\n ? 4\n : dec.decipherInfo.blockLen\n );\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen);\n this._macPos = 0;\n this._macActualLen = dec.macInfo.actualLen;\n this._macETM = dec.macInfo.isETM;\n }\n free() {\n this._instance.free();\n }\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read first encrypted block\n if (this._blockPos < this._block.length) {\n const nb = Math.min(this._block.length - this._blockPos, dataLen - p);\n if (p !== 0 || nb !== dataLen || nb < data.length) {\n this._block.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._blockPos\n );\n } else {\n this._block.set(data, this._blockPos);\n }\n\n p += nb;\n this._blockPos += nb;\n if (this._blockPos < this._block.length)\n return;\n\n let need;\n if (this._macETM) {\n this._len = need = readUInt32BE(this._block, 0);\n } else {\n // Decrypt first block to get packet length\n this._instance.decryptBlock(this._block);\n this._len = readUInt32BE(this._block, 0);\n need = 4 + this._len - this._block.length;\n }\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 5\n || (need & (this._block.length - 1)) !== 0) {\n throw new Error('Bad packet length');\n }\n\n if (!this._macETM) {\n this._pktLen = (this._block.length - 4);\n if (this._pktLen) {\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(\n new Uint8Array(this._block.buffer,\n this._block.byteOffset + 4,\n this._pktLen),\n 0\n );\n }\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read MAC\n {\n const nb = Math.min(this._macActualLen - this._macPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < this._macActualLen)\n return;\n }\n\n // Decrypt and verify MAC\n this._instance.decrypt(this._packet,\n this.inSeqno,\n this._block,\n this._mac);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n this._macInstance = null;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\n// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV\nfunction ivIncrement(iv) {\n // eslint-disable-next-line no-unused-expressions\n ++iv[11] >>> 8\n && ++iv[10] >>> 8\n && ++iv[9] >>> 8\n && ++iv[8] >>> 8\n && ++iv[7] >>> 8\n && ++iv[6] >>> 8\n && ++iv[5] >>> 8\n && ++iv[4] >>> 8;\n}\n\nconst intToBytes = (() => {\n const ret = Buffer.alloc(4);\n return (n) => {\n ret[0] = (n >>> 24);\n ret[1] = (n >>> 16);\n ret[2] = (n >>> 8);\n ret[3] = n;\n return ret;\n };\n})();\n\nfunction timingSafeEquals(a, b) {\n if (a.length !== b.length) {\n timingSafeEqual(a, a);\n return false;\n }\n return timingSafeEqual(a, b);\n}\n\nfunction createCipher(config) {\n if (typeof config !== 'object' || config === null)\n throw new Error('Invalid config');\n\n if (typeof config.outbound !== 'object' || config.outbound === null)\n throw new Error('Invalid outbound');\n\n const outbound = config.outbound;\n\n if (typeof outbound.onWrite !== 'function')\n throw new Error('Invalid outbound.onWrite');\n\n if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null)\n throw new Error('Invalid outbound.cipherInfo');\n\n if (!Buffer.isBuffer(outbound.cipherKey)\n || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) {\n throw new Error('Invalid outbound.cipherKey');\n }\n\n if (outbound.cipherInfo.ivLen\n && (!Buffer.isBuffer(outbound.cipherIV)\n || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) {\n throw new Error('Invalid outbound.cipherIV');\n }\n\n if (typeof outbound.seqno !== 'number'\n || outbound.seqno < 0\n || outbound.seqno > MAX_SEQNO) {\n throw new Error('Invalid outbound.seqno');\n }\n\n const forceNative = !!outbound.forceNative;\n\n switch (outbound.cipherInfo.sslName) {\n case 'aes-128-gcm':\n case 'aes-256-gcm':\n return (AESGCMCipher && !forceNative\n ? new AESGCMCipherBinding(config)\n : new AESGCMCipherNative(config));\n case 'chacha20':\n return (ChaChaPolyCipher && !forceNative\n ? new ChaChaPolyCipherBinding(config)\n : new ChaChaPolyCipherNative(config));\n default: {\n if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null)\n throw new Error('Invalid outbound.macInfo');\n if (!Buffer.isBuffer(outbound.macKey)\n || outbound.macKey.length !== outbound.macInfo.len) {\n throw new Error('Invalid outbound.macKey');\n }\n return (GenericCipher && !forceNative\n ? new GenericCipherBinding(config)\n : new GenericCipherNative(config));\n }\n }\n}\n\nfunction createDecipher(config) {\n if (typeof config !== 'object' || config === null)\n throw new Error('Invalid config');\n\n if (typeof config.inbound !== 'object' || config.inbound === null)\n throw new Error('Invalid inbound');\n\n const inbound = config.inbound;\n\n if (typeof inbound.onPayload !== 'function')\n throw new Error('Invalid inbound.onPayload');\n\n if (typeof inbound.decipherInfo !== 'object'\n || inbound.decipherInfo === null) {\n throw new Error('Invalid inbound.decipherInfo');\n }\n\n if (!Buffer.isBuffer(inbound.decipherKey)\n || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) {\n throw new Error('Invalid inbound.decipherKey');\n }\n\n if (inbound.decipherInfo.ivLen\n && (!Buffer.isBuffer(inbound.decipherIV)\n || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) {\n throw new Error('Invalid inbound.decipherIV');\n }\n\n if (typeof inbound.seqno !== 'number'\n || inbound.seqno < 0\n || inbound.seqno > MAX_SEQNO) {\n throw new Error('Invalid inbound.seqno');\n }\n\n const forceNative = !!inbound.forceNative;\n\n switch (inbound.decipherInfo.sslName) {\n case 'aes-128-gcm':\n case 'aes-256-gcm':\n return (AESGCMDecipher && !forceNative\n ? new AESGCMDecipherBinding(config)\n : new AESGCMDecipherNative(config));\n case 'chacha20':\n return (ChaChaPolyDecipher && !forceNative\n ? new ChaChaPolyDecipherBinding(config)\n : new ChaChaPolyDecipherNative(config));\n default: {\n if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null)\n throw new Error('Invalid inbound.macInfo');\n if (!Buffer.isBuffer(inbound.macKey)\n || inbound.macKey.length !== inbound.macInfo.len) {\n throw new Error('Invalid inbound.macKey');\n }\n return (GenericDecipher && !forceNative\n ? new GenericDecipherBinding(config)\n : new GenericDecipherNative(config));\n }\n }\n}\n\nmodule.exports = {\n CIPHER_INFO,\n MAC_INFO,\n bindingAvailable: !!binding,\n init: (() => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n POLY1305_WASM_MODULE = await require('./crypto/poly1305.js')();\n POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16);\n poly1305_auth = POLY1305_WASM_MODULE.cwrap(\n 'poly1305_auth',\n null,\n ['number', 'array', 'number', 'array', 'number', 'array']\n );\n } catch (ex) {\n return reject(ex);\n }\n resolve();\n });\n })(),\n\n NullCipher,\n createCipher,\n NullDecipher,\n createDecipher,\n};\n","\nvar createPoly1305 = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;\n return (\nfunction(createPoly1305) {\n createPoly1305 = createPoly1305 || {};\n\n\nvar b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x=\"object\"===typeof window,y=\"function\"===typeof importScripts,z=\"object\"===typeof process&&\"object\"===typeof process.versions&&\"string\"===typeof process.versions.node,B=\"\",C,D,E,F,G;\nif(z)B=y?require(\"path\").dirname(B)+\"/\":__dirname+\"/\",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=require(\"fs\"));G||(G=require(\"path\"));a=G.normalize(a);return F.readFileSync(a,c?null:\"utf8\")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=require(\"fs\"));G||(G=require(\"path\"));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]=\n0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g=\"\";else g=\"boolean\"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea=\"undefined\"!==typeof TextDecoder?new TextDecoder(\"utf8\"):void 0,ha,Q,P;\nfunction ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={};\nfunction K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError(\"abort(\"+a+\"). Build with -s ASSERTIONS=1 for more info.\");r(a);throw a;}var V=\"data:application/octet-stream;base64,\",W;W=\"data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==\";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw\"both async and sync fetching of the wasm failed\";}catch(d){K(d)}}\nfunction qa(){if(!J&&(x||y)){if(\"function\"===typeof fetch&&!W.startsWith(\"file://\"))return fetch(W,{credentials:\"same-origin\"}).then(function(a){if(!a.ok)throw\"failed to load wasm binary file at '\"+W+\"'\";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})}\nfunction X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}};\n(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I(\"failed to asynchronously prepare wasm: \"+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e,\na)}catch(f){return I(\"Module.instantiateWasm callback failed with error: \"+f),!1}(function(){return J||\"function\"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith(\"file://\")||\"function\"!==typeof fetch?d(c):fetch(W,{credentials:\"same-origin\"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I(\"wasm streaming compile failed: \"+l);I(\"falling back to ArrayBuffer instantiation\");return d(c)})})})().catch(r);return{}})();\nb.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)};\nb._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return\"number\"===l});return\"string\"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)};\nfunction Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for(\"function\"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 {\n // eslint-disable-next-line prefer-const\n for (let [type, handler] of Object.entries(handlers)) {\n type = +type;\n if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length)\n MESSAGE_HANDLERS[type] = handler;\n }\n});\n\nmodule.exports = MESSAGE_HANDLERS;\n","'use strict';\n\nconst {\n bufferSlice,\n bufferParser,\n doFatalError,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst {\n CHANNEL_OPEN_FAILURE,\n COMPAT,\n MESSAGE,\n TERMINAL_MODE,\n} = require('./constants.js');\n\nconst {\n parseKey,\n} = require('./keyParser.js');\n\nconst TERMINAL_MODE_BY_VALUE =\n Array.from(Object.entries(TERMINAL_MODE))\n .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});\n\nmodule.exports = {\n // Transport layer protocol ==================================================\n [MESSAGE.DISCONNECT]: (self, payload) => {\n /*\n byte SSH_MSG_DISCONNECT\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding\n string language tag\n */\n bufferParser.init(payload, 1);\n const reason = bufferParser.readUInt32BE();\n const desc = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed DISCONNECT packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: Received DISCONNECT (${reason}, \"${desc}\")`\n );\n\n const handler = self._handlers.DISCONNECT;\n handler && handler(self, reason, desc);\n },\n [MESSAGE.IGNORE]: (self, payload) => {\n /*\n byte SSH_MSG_IGNORE\n string data\n */\n self._debug && self._debug('Inbound: Received IGNORE');\n },\n [MESSAGE.UNIMPLEMENTED]: (self, payload) => {\n /*\n byte SSH_MSG_UNIMPLEMENTED\n uint32 packet sequence number of rejected message\n */\n bufferParser.init(payload, 1);\n const seqno = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (seqno === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed UNIMPLEMENTED packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`);\n },\n [MESSAGE.DEBUG]: (self, payload) => {\n /*\n byte SSH_MSG_DEBUG\n boolean always_display\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const display = bufferParser.readBool();\n const msg = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed DEBUG packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received DEBUG');\n\n const handler = self._handlers.DEBUG;\n handler && handler(self, display, msg);\n },\n [MESSAGE.SERVICE_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_SERVICE_REQUEST\n string service name\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n bufferParser.clear();\n\n if (name === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed SERVICE_REQUEST packet'\n );\n }\n\n self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`);\n\n const handler = self._handlers.SERVICE_REQUEST;\n handler && handler(self, name);\n },\n [MESSAGE.SERVICE_ACCEPT]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_SERVICE_ACCEPT\n string service name\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n bufferParser.clear();\n\n if (name === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed SERVICE_ACCEPT packet'\n );\n }\n\n self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`);\n\n const handler = self._handlers.SERVICE_ACCEPT;\n handler && handler(self, name);\n },\n\n // User auth protocol -- generic =============================================\n [MESSAGE.USERAUTH_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_USERAUTH_REQUEST\n string user name in ISO-10646 UTF-8 encoding [RFC3629]\n string service name in US-ASCII\n string method name in US-ASCII\n .... method specific fields\n */\n bufferParser.init(payload, 1);\n const user = bufferParser.readString(true);\n const service = bufferParser.readString(true);\n const method = bufferParser.readString(true);\n let methodData;\n let methodDesc;\n switch (method) {\n case 'none':\n methodData = null;\n break;\n case 'password': {\n /*\n boolean \n string plaintext password in ISO-10646 UTF-8 encoding [RFC3629]\n [string new password]\n */\n const isChange = bufferParser.readBool();\n if (isChange !== undefined) {\n methodData = bufferParser.readString(true);\n if (methodData !== undefined && isChange) {\n const newPassword = bufferParser.readString(true);\n if (newPassword !== undefined)\n methodData = { oldPassword: methodData, newPassword };\n else\n methodData = undefined;\n }\n }\n break;\n }\n case 'publickey': {\n /*\n boolean \n string public key algorithm name\n string public key blob\n [string signature]\n */\n const hasSig = bufferParser.readBool();\n if (hasSig !== undefined) {\n const keyAlgo = bufferParser.readString(true);\n const key = bufferParser.readString();\n if (hasSig) {\n const blobEnd = bufferParser.pos();\n let signature = bufferParser.readString();\n if (signature !== undefined) {\n if (signature.length > (4 + keyAlgo.length + 4)\n && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) {\n // Skip algoLen + algo + sigLen\n signature = bufferSlice(signature, 4 + keyAlgo.length + 4);\n }\n\n signature = sigSSHToASN1(signature, keyAlgo);\n if (signature) {\n const sessionID = self._kex.sessionID;\n const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd);\n writeUInt32BE(blob, sessionID.length, 0);\n blob.set(sessionID, 4);\n blob.set(\n new Uint8Array(payload.buffer, payload.byteOffset, blobEnd),\n 4 + sessionID.length\n );\n methodData = {\n keyAlgo,\n key,\n signature,\n blob,\n };\n }\n }\n } else {\n methodData = { keyAlgo, key };\n methodDesc = 'publickey -- check';\n }\n }\n break;\n }\n case 'hostbased': {\n /*\n string public key algorithm for host key\n string public host key and certificates for client host\n string client host name expressed as the FQDN in US-ASCII\n string user name on the client host in ISO-10646 UTF-8 encoding\n [RFC3629]\n string signature\n */\n const keyAlgo = bufferParser.readString(true);\n const key = bufferParser.readString();\n const localHostname = bufferParser.readString(true);\n const localUsername = bufferParser.readString(true);\n\n const blobEnd = bufferParser.pos();\n let signature = bufferParser.readString();\n if (signature !== undefined) {\n if (signature.length > (4 + keyAlgo.length + 4)\n && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) {\n // Skip algoLen + algo + sigLen\n signature = bufferSlice(signature, 4 + keyAlgo.length + 4);\n }\n\n signature = sigSSHToASN1(signature, keyAlgo);\n if (signature !== undefined) {\n const sessionID = self._kex.sessionID;\n const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd);\n writeUInt32BE(blob, sessionID.length, 0);\n blob.set(sessionID, 4);\n blob.set(\n new Uint8Array(payload.buffer, payload.byteOffset, blobEnd),\n 4 + sessionID.length\n );\n methodData = {\n keyAlgo,\n key,\n signature,\n blob,\n localHostname,\n localUsername,\n };\n }\n }\n break;\n }\n case 'keyboard-interactive':\n /*\n string language tag (as defined in [RFC-3066])\n string submethods (ISO-10646 UTF-8)\n */\n // Skip/ignore language field -- it's deprecated in RFC 4256\n bufferParser.skipString();\n\n methodData = bufferParser.readList();\n break;\n default:\n if (method !== undefined)\n methodData = bufferParser.readRaw();\n }\n bufferParser.clear();\n\n if (methodData === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_REQUEST packet'\n );\n }\n\n if (methodDesc === undefined)\n methodDesc = method;\n\n self._authsQueue.push(method);\n\n self._debug\n && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`);\n\n const handler = self._handlers.USERAUTH_REQUEST;\n handler && handler(self, user, service, method, methodData);\n },\n [MESSAGE.USERAUTH_FAILURE]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_FAILURE\n name-list authentications that can continue\n boolean partial success\n */\n bufferParser.init(payload, 1);\n const authMethods = bufferParser.readList();\n const partialSuccess = bufferParser.readBool();\n bufferParser.clear();\n\n if (partialSuccess === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_FAILURE packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`);\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_FAILURE;\n handler && handler(self, authMethods, partialSuccess);\n },\n [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_SUCCESS\n */\n self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS');\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_SUCCESS;\n handler && handler(self);\n },\n [MESSAGE.USERAUTH_BANNER]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_BANNER\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const msg = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_BANNER packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_BANNER');\n\n const handler = self._handlers.USERAUTH_BANNER;\n handler && handler(self, msg);\n },\n\n // User auth protocol -- method-specific =====================================\n 60: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 60 without auth');\n return;\n }\n\n switch (self._authsQueue[0]) {\n case 'password': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ\n string prompt in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const prompt = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet'\n );\n }\n\n self._debug\n && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ');\n\n const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ;\n handler && handler(self, prompt);\n break;\n }\n case 'publickey': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_PK_OK\n string public key algorithm name from the request\n string public key blob from the request\n */\n bufferParser.init(payload, 1);\n const keyAlgo = bufferParser.readString(true);\n const key = bufferParser.readString();\n bufferParser.clear();\n\n if (key === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_PK_OK packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_PK_OK');\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_PK_OK;\n handler && handler(self, keyAlgo, key);\n break;\n }\n case 'keyboard-interactive': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_INFO_REQUEST\n string name (ISO-10646 UTF-8)\n string instruction (ISO-10646 UTF-8)\n string language tag (as defined in [RFC-3066])\n int num-prompts\n string prompt[1] (ISO-10646 UTF-8)\n boolean echo[1]\n ...\n string prompt[num-prompts] (ISO-10646 UTF-8)\n boolean echo[num-prompts]\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n const instructions = bufferParser.readString(true);\n bufferParser.readString(); // skip lang\n const numPrompts = bufferParser.readUInt32BE();\n let prompts;\n if (numPrompts !== undefined) {\n prompts = new Array(numPrompts);\n let i;\n for (i = 0; i < numPrompts; ++i) {\n const prompt = bufferParser.readString(true);\n const echo = bufferParser.readBool();\n if (echo === undefined)\n break;\n prompts[i] = { prompt, echo };\n }\n if (i !== numPrompts)\n prompts = undefined;\n }\n bufferParser.clear();\n\n if (prompts === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_REQUEST packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST');\n\n const handler = self._handlers.USERAUTH_INFO_REQUEST;\n handler && handler(self, name, instructions, prompts);\n break;\n }\n default:\n self._debug\n && self._debug('Inbound: Received unexpected payload type 60');\n }\n },\n 61: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 61 without auth');\n return;\n }\n /*\n byte SSH_MSG_USERAUTH_INFO_RESPONSE\n int num-responses\n string response[1] (ISO-10646 UTF-8)\n ...\n string response[num-responses] (ISO-10646 UTF-8)\n */\n if (self._authsQueue[0] !== 'keyboard-interactive') {\n return doFatalError(\n self,\n 'Inbound: Received unexpected payload type 61'\n );\n }\n bufferParser.init(payload, 1);\n const numResponses = bufferParser.readUInt32BE();\n let responses;\n if (numResponses !== undefined) {\n responses = new Array(numResponses);\n let i;\n for (i = 0; i < numResponses; ++i) {\n const response = bufferParser.readString(true);\n if (response === undefined)\n break;\n responses[i] = response;\n }\n if (i !== numResponses)\n responses = undefined;\n }\n bufferParser.clear();\n\n if (responses === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE');\n\n const handler = self._handlers.USERAUTH_INFO_RESPONSE;\n handler && handler(self, responses);\n },\n\n // Connection protocol -- generic ============================================\n [MESSAGE.GLOBAL_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_GLOBAL_REQUEST\n string request name in US-ASCII only\n boolean want reply\n .... request-specific data follows\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n const wantReply = bufferParser.readBool();\n let data;\n if (wantReply !== undefined) {\n switch (name) {\n case 'tcpip-forward':\n case 'cancel-tcpip-forward': {\n /*\n string address to bind (e.g., \"0.0.0.0\")\n uint32 port number to bind\n */\n const bindAddr = bufferParser.readString(true);\n const bindPort = bufferParser.readUInt32BE();\n if (bindPort !== undefined)\n data = { bindAddr, bindPort };\n break;\n }\n case 'streamlocal-forward@openssh.com':\n case 'cancel-streamlocal-forward@openssh.com': {\n /*\n string socket path\n */\n const socketPath = bufferParser.readString(true);\n if (socketPath !== undefined)\n data = { socketPath };\n break;\n }\n case 'no-more-sessions@openssh.com':\n data = null;\n break;\n case 'hostkeys-00@openssh.com': {\n data = [];\n while (bufferParser.avail() > 0) {\n const keyRaw = bufferParser.readString();\n if (keyRaw === undefined) {\n data = undefined;\n break;\n }\n const key = parseKey(keyRaw);\n if (!(key instanceof Error))\n data.push(key);\n }\n break;\n }\n default:\n data = bufferParser.readRaw();\n }\n }\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed GLOBAL_REQUEST packet'\n );\n }\n\n self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`);\n\n const handler = self._handlers.GLOBAL_REQUEST;\n if (handler)\n handler(self, name, wantReply, data);\n else\n self.requestFailure(); // Auto reject\n },\n [MESSAGE.REQUEST_SUCCESS]: (self, payload) => {\n /*\n byte SSH_MSG_REQUEST_SUCCESS\n .... response specific data\n */\n const data = (payload.length > 1 ? bufferSlice(payload, 1) : null);\n\n self._debug && self._debug('Inbound: REQUEST_SUCCESS');\n\n const handler = self._handlers.REQUEST_SUCCESS;\n handler && handler(self, data);\n },\n [MESSAGE.REQUEST_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_REQUEST_FAILURE\n */\n self._debug && self._debug('Inbound: Received REQUEST_FAILURE');\n\n const handler = self._handlers.REQUEST_FAILURE;\n handler && handler(self);\n },\n\n // Connection protocol -- channel-related ====================================\n [MESSAGE.CHANNEL_OPEN]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN\n string channel type in US-ASCII only\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n .... channel type specific data follows\n */\n bufferParser.init(payload, 1);\n const type = bufferParser.readString(true);\n const sender = bufferParser.readUInt32BE();\n const window = bufferParser.readUInt32BE();\n const packetSize = bufferParser.readUInt32BE();\n let channelInfo;\n\n switch (type) {\n case 'forwarded-tcpip': // S->C\n case 'direct-tcpip': { // C->S\n /*\n string address that was connected / host to connect\n uint32 port that was connected / port to connect\n string originator IP address\n uint32 originator port\n */\n const destIP = bufferParser.readString(true);\n const destPort = bufferParser.readUInt32BE();\n const srcIP = bufferParser.readString(true);\n const srcPort = bufferParser.readUInt32BE();\n if (srcPort !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { destIP, destPort, srcIP, srcPort }\n };\n }\n break;\n }\n case 'forwarded-streamlocal@openssh.com': // S->C\n case 'direct-streamlocal@openssh.com': { // C->S\n /*\n string socket path\n string reserved for future use\n\n (direct-streamlocal@openssh.com additionally has:)\n uint32 reserved\n */\n const socketPath = bufferParser.readString(true);\n if (socketPath !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { socketPath }\n };\n }\n break;\n }\n case 'x11': { // S->C\n /*\n string originator address (e.g., \"192.168.7.38\")\n uint32 originator port\n */\n const srcIP = bufferParser.readString(true);\n const srcPort = bufferParser.readUInt32BE();\n if (srcPort !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { srcIP, srcPort }\n };\n }\n break;\n }\n default:\n // Includes:\n // 'session' (C->S)\n // 'auth-agent@openssh.com' (S->C)\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: {}\n };\n }\n bufferParser.clear();\n\n if (channelInfo === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`);\n\n const handler = self._handlers.CHANNEL_OPEN;\n if (handler) {\n handler(self, channelInfo);\n } else {\n self.channelOpenFail(\n channelInfo.sender,\n CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED,\n '',\n ''\n );\n }\n },\n [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION\n uint32 recipient channel\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n .... channel type specific data follows\n */\n // \"The 'recipient channel' is the channel number given in the\n // original open request, and 'sender channel' is the channel number\n // allocated by the other side.\"\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const sender = bufferParser.readUInt32BE();\n const window = bufferParser.readUInt32BE();\n const packetSize = bufferParser.readUInt32BE();\n const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined);\n bufferParser.clear();\n\n if (packetSize === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})`\n );\n\n const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION;\n if (handler)\n handler(self, { recipient, sender, window, packetSize, data });\n },\n [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN_FAILURE\n uint32 recipient channel\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const reason = bufferParser.readUInt32BE();\n const description = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_OPEN_FAILURE;\n handler && handler(self, recipient, reason, description);\n },\n [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_WINDOW_ADJUST\n uint32 recipient channel\n uint32 bytes to add\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const bytesToAdd = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (bytesToAdd === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})`\n );\n\n const handler = self._handlers.CHANNEL_WINDOW_ADJUST;\n handler && handler(self, recipient, bytesToAdd);\n },\n [MESSAGE.CHANNEL_DATA]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_DATA\n uint32 recipient channel\n string data\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_DATA packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`);\n\n const handler = self._handlers.CHANNEL_DATA;\n handler && handler(self, recipient, data);\n },\n [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_EXTENDED_DATA\n uint32 recipient channel\n uint32 data_type_code\n string data\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const type = bufferParser.readUInt32BE();\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})`\n );\n\n const handler = self._handlers.CHANNEL_EXTENDED_DATA;\n handler && handler(self, recipient, data, type);\n },\n [MESSAGE.CHANNEL_EOF]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_EOF\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_EOF packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_EOF;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_CLOSE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_CLOSE\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_CLOSE packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_CLOSE;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_REQUEST\n uint32 recipient channel\n string request type in US-ASCII characters only\n boolean want reply\n .... type-specific data follows\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const type = bufferParser.readString(true);\n const wantReply = bufferParser.readBool();\n let data;\n if (wantReply !== undefined) {\n switch (type) {\n case 'exit-status': // S->C\n /*\n uint32 exit_status\n */\n data = bufferParser.readUInt32BE();\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'exit-signal': { // S->C\n /*\n string signal name (without the \"SIG\" prefix)\n boolean core dumped\n string error message in ISO-10646 UTF-8 encoding\n string language tag\n */\n let signal;\n let coreDumped;\n if (self._compatFlags & COMPAT.OLD_EXIT) {\n /*\n Instead of `signal name` and `core dumped`, we have just:\n uint32 signal number\n */\n const num = bufferParser.readUInt32BE();\n switch (num) {\n case 1:\n signal = 'HUP';\n break;\n case 2:\n signal = 'INT';\n break;\n case 3:\n signal = 'QUIT';\n break;\n case 6:\n signal = 'ABRT';\n break;\n case 9:\n signal = 'KILL';\n break;\n case 14:\n signal = 'ALRM';\n break;\n case 15:\n signal = 'TERM';\n break;\n default:\n if (num !== undefined) {\n // Unknown or OS-specific\n signal = `UNKNOWN (${num})`;\n }\n }\n coreDumped = false;\n } else {\n signal = bufferParser.readString(true);\n coreDumped = bufferParser.readBool();\n if (coreDumped === undefined)\n signal = undefined;\n }\n const errorMessage = bufferParser.readString(true);\n if (bufferParser.skipString() !== undefined)\n data = { signal, coreDumped, errorMessage };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})`\n );\n break;\n }\n case 'pty-req': { // C->S\n /*\n string TERM environment variable value (e.g., vt100)\n uint32 terminal width, characters (e.g., 80)\n uint32 terminal height, rows (e.g., 24)\n uint32 terminal width, pixels (e.g., 640)\n uint32 terminal height, pixels (e.g., 480)\n string encoded terminal modes\n */\n const term = bufferParser.readString(true);\n const cols = bufferParser.readUInt32BE();\n const rows = bufferParser.readUInt32BE();\n const width = bufferParser.readUInt32BE();\n const height = bufferParser.readUInt32BE();\n const modesBinary = bufferParser.readString();\n if (modesBinary !== undefined) {\n bufferParser.init(modesBinary, 1);\n let modes = {};\n while (bufferParser.avail()) {\n const opcode = bufferParser.readByte();\n if (opcode === TERMINAL_MODE.TTY_OP_END)\n break;\n const name = TERMINAL_MODE_BY_VALUE[opcode];\n const value = bufferParser.readUInt32BE();\n if (opcode === undefined\n || name === undefined\n || value === undefined) {\n modes = undefined;\n break;\n }\n modes[name] = value;\n }\n if (modes !== undefined)\n data = { term, cols, rows, width, height, modes };\n }\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'window-change': { // C->S\n /*\n uint32 terminal width, columns\n uint32 terminal height, rows\n uint32 terminal width, pixels\n uint32 terminal height, pixels\n */\n const cols = bufferParser.readUInt32BE();\n const rows = bufferParser.readUInt32BE();\n const width = bufferParser.readUInt32BE();\n const height = bufferParser.readUInt32BE();\n if (height !== undefined)\n data = { cols, rows, width, height };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'x11-req': { // C->S\n /*\n boolean single connection\n string x11 authentication protocol\n string x11 authentication cookie\n uint32 x11 screen number\n */\n const single = bufferParser.readBool();\n const protocol = bufferParser.readString(true);\n const cookie = bufferParser.readString();\n const screen = bufferParser.readUInt32BE();\n if (screen !== undefined)\n data = { single, protocol, cookie, screen };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'env': { // C->S\n /*\n string variable name\n string variable value\n */\n const name = bufferParser.readString(true);\n const value = bufferParser.readString(true);\n if (value !== undefined)\n data = { name, value };\n if (self._debug) {\n self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: `\n + `${name}=${value})`\n );\n }\n break;\n }\n case 'shell': // C->S\n data = null; // No extra data\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n case 'exec': // C->S\n /*\n string command\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'subsystem': // C->S\n /*\n string subsystem name\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'signal': // C->S\n /*\n string signal name (without the \"SIG\" prefix)\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'xon-xoff': // C->S\n /*\n boolean client can do\n */\n data = bufferParser.readBool();\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'auth-agent-req@openssh.com': // C-S\n data = null; // No extra data\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n default:\n data = (bufferParser.avail() ? bufferParser.readRaw() : null);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n }\n }\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_REQUEST packet'\n );\n }\n\n const handler = self._handlers.CHANNEL_REQUEST;\n handler && handler(self, recipient, type, wantReply, data);\n },\n [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_SUCCESS\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_SUCCESS packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_SUCCESS;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_FAILURE\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_FAILURE packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_FAILURE;\n handler && handler(self, recipient);\n },\n};\n","'use strict';\n\nconst {\n createDiffieHellman,\n createDiffieHellmanGroup,\n createECDH,\n createHash,\n createPublicKey,\n diffieHellman,\n generateKeyPairSync,\n randomFillSync,\n} = require('crypto');\n\nconst { Ber } = require('asn1');\n\nconst {\n COMPAT,\n curve25519Supported,\n DEFAULT_KEX,\n DEFAULT_SERVER_HOST_KEY,\n DEFAULT_CIPHER,\n DEFAULT_MAC,\n DEFAULT_COMPRESSION,\n DISCONNECT_REASON,\n MESSAGE,\n} = require('./constants.js');\nconst {\n CIPHER_INFO,\n createCipher,\n createDecipher,\n MAC_INFO,\n} = require('./crypto.js');\nconst { parseDERKey } = require('./keyParser.js');\nconst {\n bufferFill,\n bufferParser,\n convertSignature,\n doFatalError,\n FastBuffer,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./utils.js');\nconst {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n} = require('./zlib.js');\n\nlet MESSAGE_HANDLERS;\n\nconst GEX_MIN_BITS = 2048; // RFC 8270\nconst GEX_MAX_BITS = 8192; // RFC 8270\n\nconst EMPTY_BUFFER = Buffer.alloc(0);\n\n// Client/Server\nfunction kexinit(self) {\n /*\n byte SSH_MSG_KEXINIT\n byte[16] cookie (random bytes)\n name-list kex_algorithms\n name-list server_host_key_algorithms\n name-list encryption_algorithms_client_to_server\n name-list encryption_algorithms_server_to_client\n name-list mac_algorithms_client_to_server\n name-list mac_algorithms_server_to_client\n name-list compression_algorithms_client_to_server\n name-list compression_algorithms_server_to_client\n name-list languages_client_to_server\n name-list languages_server_to_client\n boolean first_kex_packet_follows\n uint32 0 (reserved for future extension)\n */\n\n let payload;\n if (self._compatFlags & COMPAT.BAD_DHGEX) {\n const entry = self._offer.lists.kex;\n let kex = entry.array;\n let found = false;\n for (let i = 0; i < kex.length; ++i) {\n if (kex[i].includes('group-exchange')) {\n if (!found) {\n found = true;\n // Copy array lazily\n kex = kex.slice();\n }\n kex.splice(i--, 1);\n }\n }\n if (found) {\n let len = 1 + 16 + self._offer.totalSize + 1 + 4;\n const newKexBuf = Buffer.from(kex.join(','));\n len -= (entry.buffer.length - newKexBuf.length);\n\n const all = self._offer.lists.all;\n const rest = new Uint8Array(\n all.buffer,\n all.byteOffset + 4 + entry.buffer.length,\n all.length - (4 + entry.buffer.length)\n );\n\n payload = Buffer.allocUnsafe(len);\n writeUInt32BE(payload, newKexBuf.length, 17);\n payload.set(newKexBuf, 17 + 4);\n payload.set(rest, 17 + 4 + newKexBuf.length);\n }\n }\n\n if (payload === undefined) {\n payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4);\n self._offer.copyAllTo(payload, 17);\n }\n\n self._debug && self._debug('Outbound: Sending KEXINIT');\n\n payload[0] = MESSAGE.KEXINIT;\n randomFillSync(payload, 1, 16);\n\n // Zero-fill first_kex_packet_follows and reserved bytes\n bufferFill(payload, 0, payload.length - 5);\n\n self._kexinit = payload;\n\n // Needed to correct the starting position in allocated \"packets\" when packets\n // will be buffered due to active key exchange\n self._packetRW.write.allocStart = 0;\n\n // TODO: only create single buffer and set _kexinit as slice of packet instead\n {\n const p = self._packetRW.write.allocStartKEX;\n const packet = self._packetRW.write.alloc(payload.length, true);\n packet.set(payload, p);\n self._cipher.encrypt(self._packetRW.write.finalize(packet, true));\n }\n}\n\nfunction handleKexInit(self, payload) {\n /*\n byte SSH_MSG_KEXINIT\n byte[16] cookie (random bytes)\n name-list kex_algorithms\n name-list server_host_key_algorithms\n name-list encryption_algorithms_client_to_server\n name-list encryption_algorithms_server_to_client\n name-list mac_algorithms_client_to_server\n name-list mac_algorithms_server_to_client\n name-list compression_algorithms_client_to_server\n name-list compression_algorithms_server_to_client\n name-list languages_client_to_server\n name-list languages_server_to_client\n boolean first_kex_packet_follows\n uint32 0 (reserved for future extension)\n */\n const init = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n sc: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n };\n\n bufferParser.init(payload, 17);\n\n if ((init.kex = bufferParser.readList()) === undefined\n || (init.serverHostKey = bufferParser.readList()) === undefined\n || (init.cs.cipher = bufferParser.readList()) === undefined\n || (init.sc.cipher = bufferParser.readList()) === undefined\n || (init.cs.mac = bufferParser.readList()) === undefined\n || (init.sc.mac = bufferParser.readList()) === undefined\n || (init.cs.compress = bufferParser.readList()) === undefined\n || (init.sc.compress = bufferParser.readList()) === undefined\n || (init.cs.lang = bufferParser.readList()) === undefined\n || (init.sc.lang = bufferParser.readList()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n self,\n 'Received malformed KEXINIT',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n const pos = bufferParser.pos();\n const firstFollows = (pos < payload.length && payload[pos] === 1);\n bufferParser.clear();\n\n const local = self._offer;\n const remote = init;\n\n let localKex = local.lists.kex.array;\n if (self._compatFlags & COMPAT.BAD_DHGEX) {\n let found = false;\n for (let i = 0; i < localKex.length; ++i) {\n if (localKex[i].indexOf('group-exchange') !== -1) {\n if (!found) {\n found = true;\n // Copy array lazily\n localKex = localKex.slice();\n }\n localKex.splice(i--, 1);\n }\n }\n }\n\n let clientList;\n let serverList;\n let i;\n const debug = self._debug;\n\n debug && debug('Inbound: Handshake in progress');\n\n // Key exchange method =======================================================\n debug && debug(`Handshake: (local) KEX method: ${localKex}`);\n debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`);\n if (self._server) {\n serverList = localKex;\n clientList = remote.kex;\n } else {\n serverList = remote.kex;\n clientList = localKex;\n }\n // Check for agreeable key exchange algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching key exchange algorithm');\n return doFatalError(\n self,\n 'Handshake failed: no matching key exchange algorithm',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.kex = clientList[i];\n debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`);\n if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) {\n // Ignore next inbound packet, it was a wrong first guess at KEX algorithm\n self._skipNextInboundPacket = true;\n }\n\n\n // Server host key format ====================================================\n const localSrvHostKey = local.lists.serverHostKey.array;\n debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`);\n debug && debug(\n `Handshake: (remote) Host key format: ${remote.serverHostKey}`\n );\n if (self._server) {\n serverList = localSrvHostKey;\n clientList = remote.serverHostKey;\n } else {\n serverList = remote.serverHostKey;\n clientList = localSrvHostKey;\n }\n // Check for agreeable server host key format\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching host key format');\n return doFatalError(\n self,\n 'Handshake failed: no matching host key format',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.serverHostKey = clientList[i];\n debug && debug(`Handshake: Host key format: ${clientList[i]}`);\n\n\n // Client->Server cipher =====================================================\n const localCSCipher = local.lists.cs.cipher.array;\n debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`);\n debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`);\n if (self._server) {\n serverList = localCSCipher;\n clientList = remote.cs.cipher;\n } else {\n serverList = remote.cs.cipher;\n clientList = localCSCipher;\n }\n // Check for agreeable client->server cipher\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S cipher');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S cipher',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.cipher = clientList[i];\n debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`);\n\n\n // Server->Client cipher =====================================================\n const localSCCipher = local.lists.sc.cipher.array;\n debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`);\n debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`);\n if (self._server) {\n serverList = localSCCipher;\n clientList = remote.sc.cipher;\n } else {\n serverList = remote.sc.cipher;\n clientList = localSCCipher;\n }\n // Check for agreeable server->client cipher\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C cipher');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C cipher',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.cipher = clientList[i];\n debug && debug(`Handshake: S->C cipher: ${clientList[i]}`);\n\n\n // Client->Server MAC ========================================================\n const localCSMAC = local.lists.cs.mac.array;\n debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`);\n debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`);\n if (CIPHER_INFO[init.cs.cipher].authLen > 0) {\n init.cs.mac = '';\n debug && debug('Handshake: C->S MAC: ');\n } else {\n if (self._server) {\n serverList = localCSMAC;\n clientList = remote.cs.mac;\n } else {\n serverList = remote.cs.mac;\n clientList = localCSMAC;\n }\n // Check for agreeable client->server hmac algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S MAC');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S MAC',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.mac = clientList[i];\n debug && debug(`Handshake: C->S MAC: ${clientList[i]}`);\n }\n\n\n // Server->Client MAC ========================================================\n const localSCMAC = local.lists.sc.mac.array;\n debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`);\n debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`);\n if (CIPHER_INFO[init.sc.cipher].authLen > 0) {\n init.sc.mac = '';\n debug && debug('Handshake: S->C MAC: ');\n } else {\n if (self._server) {\n serverList = localSCMAC;\n clientList = remote.sc.mac;\n } else {\n serverList = remote.sc.mac;\n clientList = localSCMAC;\n }\n // Check for agreeable server->client hmac algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C MAC');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C MAC',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.mac = clientList[i];\n debug && debug(`Handshake: S->C MAC: ${clientList[i]}`);\n }\n\n\n // Client->Server compression ================================================\n const localCSCompress = local.lists.cs.compress.array;\n debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`);\n debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`);\n if (self._server) {\n serverList = localCSCompress;\n clientList = remote.cs.compress;\n } else {\n serverList = remote.cs.compress;\n clientList = localCSCompress;\n }\n // Check for agreeable client->server compression algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S compression');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S compression',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.compress = clientList[i];\n debug && debug(`Handshake: C->S compression: ${clientList[i]}`);\n\n\n // Server->Client compression ================================================\n const localSCCompress = local.lists.sc.compress.array;\n debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`);\n debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`);\n if (self._server) {\n serverList = localSCCompress;\n clientList = remote.sc.compress;\n } else {\n serverList = remote.sc.compress;\n clientList = localSCCompress;\n }\n // Check for agreeable server->client compression algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C compression');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C compression',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.compress = clientList[i];\n debug && debug(`Handshake: S->C compression: ${clientList[i]}`);\n\n init.cs.lang = '';\n init.sc.lang = '';\n\n // XXX: hack -- find a better way to do this\n if (self._kex) {\n if (!self._kexinit) {\n // We received a rekey request, but we haven't sent a KEXINIT in response\n // yet\n kexinit(self);\n }\n self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false });\n }\n\n self._kex = createKeyExchange(init, self, payload);\n self._kex.start();\n}\n\nconst createKeyExchange = (() => {\n function convertToMpint(buf) {\n let idx = 0;\n let length = buf.length;\n while (buf[idx] === 0x00) {\n ++idx;\n --length;\n }\n let newBuf;\n if (buf[idx] & 0x80) {\n newBuf = Buffer.allocUnsafe(1 + length);\n newBuf[0] = 0;\n buf.copy(newBuf, 1, idx);\n buf = newBuf;\n } else if (length !== buf.length) {\n newBuf = Buffer.allocUnsafe(length);\n buf.copy(newBuf, 0, idx);\n buf = newBuf;\n }\n return buf;\n }\n\n class KeyExchange {\n constructor(negotiated, protocol, remoteKexinit) {\n this._protocol = protocol;\n\n this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined);\n this.negotiated = negotiated;\n this._step = 1;\n this._public = null;\n this._dh = null;\n this._sentNEWKEYS = false;\n this._receivedNEWKEYS = false;\n this._finished = false;\n this._hostVerified = false;\n\n // Data needed for initializing cipher/decipher/etc.\n this._kexinit = protocol._kexinit;\n this._remoteKexinit = remoteKexinit;\n this._identRaw = protocol._identRaw;\n this._remoteIdentRaw = protocol._remoteIdentRaw;\n this._hostKey = undefined;\n this._dhData = undefined;\n this._sig = undefined;\n }\n finish() {\n if (this._finished)\n return false;\n this._finished = true;\n\n const isServer = this._protocol._server;\n const negotiated = this.negotiated;\n\n const pubKey = this.convertPublicKey(this._dhData);\n let secret = this.computeSecret(this._dhData);\n if (secret instanceof Error) {\n secret.message =\n `Error while computing DH secret (${this.type}): ${secret.message}`;\n secret.level = 'handshake';\n return doFatalError(\n this._protocol,\n secret,\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n const hash = createHash(this.hashName);\n // V_C\n hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw));\n // \"V_S\"\n hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw));\n // \"I_C\"\n hashString(hash, (isServer ? this._remoteKexinit : this._kexinit));\n // \"I_S\"\n hashString(hash, (isServer ? this._kexinit : this._remoteKexinit));\n // \"K_S\"\n const serverPublicHostKey = (isServer\n ? this._hostKey.getPublicSSH()\n : this._hostKey);\n hashString(hash, serverPublicHostKey);\n\n if (this.type === 'groupex') {\n // Group exchange-specific\n const params = this.getDHParams();\n const num = Buffer.allocUnsafe(4);\n // min (uint32)\n writeUInt32BE(num, this._minBits, 0);\n hash.update(num);\n // preferred (uint32)\n writeUInt32BE(num, this._prefBits, 0);\n hash.update(num);\n // max (uint32)\n writeUInt32BE(num, this._maxBits, 0);\n hash.update(num);\n // prime\n hashString(hash, params.prime);\n // generator\n hashString(hash, params.generator);\n }\n\n // method-specific data sent by client\n hashString(hash, (isServer ? pubKey : this.getPublicKey()));\n // method-specific data sent by server\n const serverPublicKey = (isServer ? this.getPublicKey() : pubKey);\n hashString(hash, serverPublicKey);\n // shared secret (\"K\")\n hashString(hash, secret);\n\n // \"H\"\n const exchangeHash = hash.digest();\n\n if (!isServer) {\n bufferParser.init(this._sig, 0);\n const sigType = bufferParser.readString(true);\n\n if (!sigType) {\n return doFatalError(\n this._protocol,\n 'Malformed packet while reading signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (sigType !== negotiated.serverHostKey) {\n return doFatalError(\n this._protocol,\n `Wrong signature type: ${sigType}, `\n + `expected: ${negotiated.serverHostKey}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // \"s\"\n let sigValue = bufferParser.readString();\n\n bufferParser.clear();\n\n if (sigValue === undefined) {\n return doFatalError(\n this._protocol,\n 'Malformed packet while reading signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (!(sigValue = sigSSHToASN1(sigValue, sigType))) {\n return doFatalError(\n this._protocol,\n 'Malformed signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n let parsedHostKey;\n {\n bufferParser.init(this._hostKey, 0);\n const name = bufferParser.readString(true);\n const hostKey = this._hostKey.slice(bufferParser.pos());\n bufferParser.clear();\n parsedHostKey = parseDERKey(hostKey, name);\n if (parsedHostKey instanceof Error) {\n parsedHostKey.level = 'handshake';\n return doFatalError(\n this._protocol,\n parsedHostKey,\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n let hashAlgo;\n // Check if we need to override the default hash algorithm\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256': hashAlgo = 'sha256'; break;\n case 'rsa-sha2-512': hashAlgo = 'sha512'; break;\n }\n\n this._protocol._debug\n && this._protocol._debug('Verifying signature ...');\n\n const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo);\n if (verified !== true) {\n if (verified instanceof Error) {\n this._protocol._debug && this._protocol._debug(\n `Signature verification failed: ${verified.stack}`\n );\n } else {\n this._protocol._debug && this._protocol._debug(\n 'Signature verification failed'\n );\n }\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature verification failed',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug('Verified signature');\n } else {\n // Server\n\n let hashAlgo;\n // Check if we need to override the default hash algorithm\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256': hashAlgo = 'sha256'; break;\n case 'rsa-sha2-512': hashAlgo = 'sha512'; break;\n }\n\n this._protocol._debug && this._protocol._debug(\n 'Generating signature ...'\n );\n\n let signature = this._hostKey.sign(exchangeHash, hashAlgo);\n if (signature instanceof Error) {\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature generation failed for '\n + `${this._hostKey.type} host key: ${signature.message}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n signature = convertSignature(signature, this._hostKey.type);\n if (signature === false) {\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature conversion failed for '\n + `${this._hostKey.type} host key`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // Send KEX reply\n /*\n byte SSH_MSG_KEXDH_REPLY\n / SSH_MSG_KEX_DH_GEX_REPLY\n / SSH_MSG_KEX_ECDH_REPLY\n string server public host key and certificates (K_S)\n string \n string signature of H\n */\n const sigType = this.negotiated.serverHostKey;\n const sigTypeLen = Buffer.byteLength(sigType);\n const sigLen = 4 + sigTypeLen + 4 + signature.length;\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1\n + 4 + serverPublicHostKey.length\n + 4 + serverPublicKey.length\n + 4 + sigLen,\n true\n );\n\n packet[p] = MESSAGE.KEXDH_REPLY;\n\n writeUInt32BE(packet, serverPublicHostKey.length, ++p);\n packet.set(serverPublicHostKey, p += 4);\n\n writeUInt32BE(packet,\n serverPublicKey.length,\n p += serverPublicHostKey.length);\n packet.set(serverPublicKey, p += 4);\n\n writeUInt32BE(packet, sigLen, p += serverPublicKey.length);\n\n writeUInt32BE(packet, sigTypeLen, p += 4);\n packet.utf8Write(sigType, p += 4, sigTypeLen);\n\n writeUInt32BE(packet, signature.length, p += sigTypeLen);\n packet.set(signature, p += 4);\n\n if (this._protocol._debug) {\n let type;\n switch (this.type) {\n case 'group':\n type = 'KEXDH_REPLY';\n break;\n case 'groupex':\n type = 'KEXDH_GEX_REPLY';\n break;\n default:\n type = 'KEXECDH_REPLY';\n }\n this._protocol._debug(`Outbound: Sending ${type}`);\n }\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n trySendNEWKEYS(this);\n\n const completeHandshake = () => {\n if (!this.sessionID)\n this.sessionID = exchangeHash;\n\n {\n const newSecret = Buffer.allocUnsafe(4 + secret.length);\n writeUInt32BE(newSecret, secret.length, 0);\n newSecret.set(secret, 4);\n secret = newSecret;\n }\n\n // Initialize new ciphers, deciphers, etc.\n\n const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher];\n const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher];\n\n const csIV = generateKEXVal(csCipherInfo.ivLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'A');\n const scIV = generateKEXVal(scCipherInfo.ivLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'B');\n const csKey = generateKEXVal(csCipherInfo.keyLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'C');\n const scKey = generateKEXVal(scCipherInfo.keyLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'D');\n let csMacInfo;\n let csMacKey;\n if (!csCipherInfo.authLen) {\n csMacInfo = MAC_INFO[negotiated.cs.mac];\n csMacKey = generateKEXVal(csMacInfo.len,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'E');\n }\n let scMacInfo;\n let scMacKey;\n if (!scCipherInfo.authLen) {\n scMacInfo = MAC_INFO[negotiated.sc.mac];\n scMacKey = generateKEXVal(scMacInfo.len,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'F');\n }\n\n const config = {\n inbound: {\n onPayload: this._protocol._onPayload,\n seqno: this._protocol._decipher.inSeqno,\n decipherInfo: (!isServer ? scCipherInfo : csCipherInfo),\n decipherIV: (!isServer ? scIV : csIV),\n decipherKey: (!isServer ? scKey : csKey),\n macInfo: (!isServer ? scMacInfo : csMacInfo),\n macKey: (!isServer ? scMacKey : csMacKey),\n },\n outbound: {\n onWrite: this._protocol._onWrite,\n seqno: this._protocol._cipher.outSeqno,\n cipherInfo: (isServer ? scCipherInfo : csCipherInfo),\n cipherIV: (isServer ? scIV : csIV),\n cipherKey: (isServer ? scKey : csKey),\n macInfo: (isServer ? scMacInfo : csMacInfo),\n macKey: (isServer ? scMacKey : csMacKey),\n },\n };\n this._protocol._cipher && this._protocol._cipher.free();\n this._protocol._decipher && this._protocol._decipher.free();\n this._protocol._cipher = createCipher(config);\n this._protocol._decipher = createDecipher(config);\n\n const rw = {\n read: undefined,\n write: undefined,\n };\n switch (negotiated.cs.compress) {\n case 'zlib': // starts immediately\n if (isServer)\n rw.read = new ZlibPacketReader();\n else\n rw.write = new ZlibPacketWriter(this._protocol);\n break;\n case 'zlib@openssh.com':\n // Starts after successful user authentication\n\n if (this._protocol._authenticated) {\n // If a rekey happens and this compression method is selected and\n // we already authenticated successfully, we need to start\n // immediately instead\n if (isServer)\n rw.read = new ZlibPacketReader();\n else\n rw.write = new ZlibPacketWriter(this._protocol);\n break;\n }\n // FALLTHROUGH\n default:\n // none -- never any compression/decompression\n\n if (isServer)\n rw.read = new PacketReader();\n else\n rw.write = new PacketWriter(this._protocol);\n }\n switch (negotiated.sc.compress) {\n case 'zlib': // starts immediately\n if (isServer)\n rw.write = new ZlibPacketWriter(this._protocol);\n else\n rw.read = new ZlibPacketReader();\n break;\n case 'zlib@openssh.com':\n // Starts after successful user authentication\n\n if (this._protocol._authenticated) {\n // If a rekey happens and this compression method is selected and\n // we already authenticated successfully, we need to start\n // immediately instead\n if (isServer)\n rw.write = new ZlibPacketWriter(this._protocol);\n else\n rw.read = new ZlibPacketReader();\n break;\n }\n // FALLTHROUGH\n default:\n // none -- never any compression/decompression\n\n if (isServer)\n rw.write = new PacketWriter(this._protocol);\n else\n rw.read = new PacketReader();\n }\n this._protocol._packetRW.read.cleanup();\n this._protocol._packetRW.write.cleanup();\n this._protocol._packetRW = rw;\n\n // Cleanup/reset various state\n this._public = null;\n this._dh = null;\n this._kexinit = this._protocol._kexinit = undefined;\n this._remoteKexinit = undefined;\n this._identRaw = undefined;\n this._remoteIdentRaw = undefined;\n this._hostKey = undefined;\n this._dhData = undefined;\n this._sig = undefined;\n\n this._protocol._onHandshakeComplete(negotiated);\n\n return false;\n };\n if (!isServer)\n return completeHandshake();\n this.finish = completeHandshake;\n }\n\n start() {\n if (!this._protocol._server) {\n if (this._protocol._debug) {\n let type;\n switch (this.type) {\n case 'group':\n type = 'KEXDH_INIT';\n break;\n default:\n type = 'KEXECDH_INIT';\n }\n this._protocol._debug(`Outbound: Sending ${type}`);\n }\n\n const pubKey = this.getPublicKey();\n\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1 + 4 + pubKey.length,\n true\n );\n packet[p] = MESSAGE.KEXDH_INIT;\n writeUInt32BE(packet, pubKey.length, ++p);\n packet.set(pubKey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n }\n getPublicKey() {\n this.generateKeys();\n\n const key = this._public;\n\n if (key)\n return this.convertPublicKey(key);\n }\n convertPublicKey(key) {\n let newKey;\n let idx = 0;\n let len = key.length;\n while (key[idx] === 0x00) {\n ++idx;\n --len;\n }\n\n if (key[idx] & 0x80) {\n newKey = Buffer.allocUnsafe(1 + len);\n newKey[0] = 0;\n key.copy(newKey, 1, idx);\n return newKey;\n }\n\n if (len !== key.length) {\n newKey = Buffer.allocUnsafe(len);\n key.copy(newKey, 0, idx);\n key = newKey;\n }\n return key;\n }\n computeSecret(otherPublicKey) {\n this.generateKeys();\n\n try {\n return convertToMpint(this._dh.computeSecret(otherPublicKey));\n } catch (ex) {\n return ex;\n }\n }\n parse(payload) {\n const type = payload[0];\n switch (this._step) {\n case 1:\n if (this._protocol._server) {\n // Server\n if (type !== MESSAGE.KEXDH_INIT) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH Init'\n );\n /*\n byte SSH_MSG_KEXDH_INIT\n / SSH_MSG_KEX_ECDH_INIT\n string \n */\n bufferParser.init(payload, 1);\n const dhData = bufferParser.readString();\n bufferParser.clear();\n if (dhData === undefined) {\n return doFatalError(\n this._protocol,\n 'Received malformed KEX*_INIT',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // Client public key\n this._dhData = dhData;\n\n let hostKey =\n this._protocol._hostKeys[this.negotiated.serverHostKey];\n if (Array.isArray(hostKey))\n hostKey = hostKey[0];\n this._hostKey = hostKey;\n\n this.finish();\n } else {\n // Client\n if (type !== MESSAGE.KEXDH_REPLY) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH Reply'\n );\n /*\n byte SSH_MSG_KEXDH_REPLY\n / SSH_MSG_KEX_DH_GEX_REPLY\n / SSH_MSG_KEX_ECDH_REPLY\n string server public host key and certificates (K_S)\n string \n string signature of H\n */\n bufferParser.init(payload, 1);\n let hostPubKey;\n let dhData;\n let sig;\n if ((hostPubKey = bufferParser.readString()) === undefined\n || (dhData = bufferParser.readString()) === undefined\n || (sig = bufferParser.readString()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n this._protocol,\n 'Received malformed KEX*_REPLY',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n bufferParser.clear();\n\n // Check that the host public key type matches what was negotiated\n // during KEXINIT swap\n bufferParser.init(hostPubKey, 0);\n const hostPubKeyType = bufferParser.readString(true);\n bufferParser.clear();\n if (hostPubKeyType === undefined) {\n return doFatalError(\n this._protocol,\n 'Received malformed host public key',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n if (hostPubKeyType !== this.negotiated.serverHostKey) {\n // Check if we need to make an exception\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256':\n case 'rsa-sha2-512':\n if (hostPubKeyType === 'ssh-rsa')\n break;\n // FALLTHROUGH\n default:\n return doFatalError(\n this._protocol,\n 'Host key does not match negotiated type',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n this._hostKey = hostPubKey;\n this._dhData = dhData;\n this._sig = sig;\n\n let checked = false;\n let ret;\n if (this._protocol._hostVerifier === undefined) {\n ret = true;\n this._protocol._debug && this._protocol._debug(\n 'Host accepted by default (no verification)'\n );\n } else {\n ret = this._protocol._hostVerifier(hostPubKey, (permitted) => {\n if (checked)\n return;\n checked = true;\n if (permitted === false) {\n this._protocol._debug && this._protocol._debug(\n 'Host denied (verification failed)'\n );\n return doFatalError(\n this._protocol,\n 'Host denied (verification failed)',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Host accepted (verified)'\n );\n this._hostVerified = true;\n if (this._receivedNEWKEYS)\n this.finish();\n else\n trySendNEWKEYS(this);\n });\n }\n if (ret === undefined) {\n // Async host verification\n ++this._step;\n return;\n }\n checked = true;\n if (ret === false) {\n this._protocol._debug && this._protocol._debug(\n 'Host denied (verification failed)'\n );\n return doFatalError(\n this._protocol,\n 'Host denied (verification failed)',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Host accepted (verified)'\n );\n this._hostVerified = true;\n trySendNEWKEYS(this);\n }\n ++this._step;\n break;\n case 2:\n if (type !== MESSAGE.NEWKEYS) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Inbound: NEWKEYS'\n );\n this._receivedNEWKEYS = true;\n ++this._step;\n if (this._protocol._server || this._hostVerified)\n return this.finish();\n\n // Signal to current decipher that we need to change to a new decipher\n // for the next packet\n return false;\n default:\n return doFatalError(\n this._protocol,\n `Received unexpected packet ${type} after NEWKEYS`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n }\n\n class Curve25519Exchange extends KeyExchange {\n constructor(hashName, ...args) {\n super(...args);\n\n this.type = '25519';\n this.hashName = hashName;\n this._keys = null;\n }\n generateKeys() {\n if (!this._keys)\n this._keys = generateKeyPairSync('x25519');\n }\n getPublicKey() {\n this.generateKeys();\n\n const key = this._keys.publicKey.export({ type: 'spki', format: 'der' });\n return key.slice(-32); // HACK: avoids parsing DER/BER header\n }\n convertPublicKey(key) {\n let newKey;\n let idx = 0;\n let len = key.length;\n while (key[idx] === 0x00) {\n ++idx;\n --len;\n }\n\n if (key.length === 32)\n return key;\n\n if (len !== key.length) {\n newKey = Buffer.allocUnsafe(len);\n key.copy(newKey, 0, idx);\n key = newKey;\n }\n return key;\n }\n computeSecret(otherPublicKey) {\n this.generateKeys();\n\n try {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.110'); // id-X25519\n asnWriter.endSequence();\n\n // PublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(otherPublicKey.length);\n otherPublicKey.copy(asnWriter._buf,\n asnWriter._offset,\n 0,\n otherPublicKey.length);\n asnWriter._offset += otherPublicKey.length;\n asnWriter.endSequence();\n asnWriter.endSequence();\n\n return convertToMpint(diffieHellman({\n privateKey: this._keys.privateKey,\n publicKey: createPublicKey({\n key: asnWriter.buffer,\n type: 'spki',\n format: 'der',\n }),\n }));\n } catch (ex) {\n return ex;\n }\n }\n }\n\n class ECDHExchange extends KeyExchange {\n constructor(curveName, hashName, ...args) {\n super(...args);\n\n this.type = 'ecdh';\n this.curveName = curveName;\n this.hashName = hashName;\n }\n generateKeys() {\n if (!this._dh) {\n this._dh = createECDH(this.curveName);\n this._public = this._dh.generateKeys();\n }\n }\n }\n\n class DHGroupExchange extends KeyExchange {\n constructor(hashName, ...args) {\n super(...args);\n\n this.type = 'groupex';\n this.hashName = hashName;\n this._prime = null;\n this._generator = null;\n this._minBits = GEX_MIN_BITS;\n this._prefBits = dhEstimate(this.negotiated);\n if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE)\n this._prefBits = Math.min(this._prefBits, 4096);\n this._maxBits = GEX_MAX_BITS;\n }\n start() {\n if (this._protocol._server)\n return;\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_GEX_REQUEST'\n );\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1 + 4 + 4 + 4,\n true\n );\n packet[p] = MESSAGE.KEXDH_GEX_REQUEST;\n writeUInt32BE(packet, this._minBits, ++p);\n writeUInt32BE(packet, this._prefBits, p += 4);\n writeUInt32BE(packet, this._maxBits, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n generateKeys() {\n if (!this._dh && this._prime && this._generator) {\n this._dh = createDiffieHellman(this._prime, this._generator);\n this._public = this._dh.generateKeys();\n }\n }\n setDHParams(prime, generator) {\n if (!Buffer.isBuffer(prime))\n throw new Error('Invalid prime value');\n if (!Buffer.isBuffer(generator))\n throw new Error('Invalid generator value');\n this._prime = prime;\n this._generator = generator;\n }\n getDHParams() {\n if (this._dh) {\n return {\n prime: convertToMpint(this._dh.getPrime()),\n generator: convertToMpint(this._dh.getGenerator()),\n };\n }\n }\n parse(payload) {\n const type = payload[0];\n switch (this._step) {\n case 1:\n if (this._protocol._server) {\n if (type !== MESSAGE.KEXDH_GEX_REQUEST) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of `\n + MESSAGE.KEXDH_GEX_REQUEST,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n // TODO: allow user implementation to provide safe prime and\n // generator on demand to support group exchange on server side\n return doFatalError(\n this._protocol,\n 'Group exchange not implemented for server',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (type !== MESSAGE.KEXDH_GEX_GROUP) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Group'\n );\n\n /*\n byte SSH_MSG_KEX_DH_GEX_GROUP\n mpint p, safe prime\n mpint g, generator for subgroup in GF(p)\n */\n bufferParser.init(payload, 1);\n let prime;\n let gen;\n if ((prime = bufferParser.readString()) === undefined\n || (gen = bufferParser.readString()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n this._protocol,\n 'Received malformed KEXDH_GEX_GROUP',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n bufferParser.clear();\n\n // TODO: validate prime\n this.setDHParams(prime, gen);\n this.generateKeys();\n const pubkey = this.getPublicKey();\n\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_GEX_INIT'\n );\n\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet =\n this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true);\n packet[p] = MESSAGE.KEXDH_GEX_INIT;\n writeUInt32BE(packet, pubkey.length, ++p);\n packet.set(pubkey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n\n ++this._step;\n break;\n case 2:\n if (this._protocol._server) {\n if (type !== MESSAGE.KEXDH_GEX_INIT) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Init'\n );\n return doFatalError(\n this._protocol,\n 'Group exchange not implemented for server',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n } else if (type !== MESSAGE.KEXDH_GEX_REPLY) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Reply'\n );\n this._step = 1;\n payload[0] = MESSAGE.KEXDH_REPLY;\n this.parse = KeyExchange.prototype.parse;\n this.parse(payload);\n }\n }\n }\n\n class DHExchange extends KeyExchange {\n constructor(groupName, hashName, ...args) {\n super(...args);\n\n this.type = 'group';\n this.groupName = groupName;\n this.hashName = hashName;\n }\n start() {\n if (!this._protocol._server) {\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_INIT'\n );\n const pubKey = this.getPublicKey();\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet =\n this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true);\n packet[p] = MESSAGE.KEXDH_INIT;\n writeUInt32BE(packet, pubKey.length, ++p);\n packet.set(pubKey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n }\n generateKeys() {\n if (!this._dh) {\n this._dh = createDiffieHellmanGroup(this.groupName);\n this._public = this._dh.generateKeys();\n }\n }\n getDHParams() {\n if (this._dh) {\n return {\n prime: convertToMpint(this._dh.getPrime()),\n generator: convertToMpint(this._dh.getGenerator()),\n };\n }\n }\n }\n\n return (negotiated, ...args) => {\n if (typeof negotiated !== 'object' || negotiated === null)\n throw new Error('Invalid negotiated argument');\n const kexType = negotiated.kex;\n if (typeof kexType === 'string') {\n args = [negotiated, ...args];\n switch (kexType) {\n case 'curve25519-sha256':\n case 'curve25519-sha256@libssh.org':\n if (!curve25519Supported)\n break;\n return new Curve25519Exchange('sha256', ...args);\n\n case 'ecdh-sha2-nistp256':\n return new ECDHExchange('prime256v1', 'sha256', ...args);\n case 'ecdh-sha2-nistp384':\n return new ECDHExchange('secp384r1', 'sha384', ...args);\n case 'ecdh-sha2-nistp521':\n return new ECDHExchange('secp521r1', 'sha512', ...args);\n\n case 'diffie-hellman-group1-sha1':\n return new DHExchange('modp2', 'sha1', ...args);\n case 'diffie-hellman-group14-sha1':\n return new DHExchange('modp14', 'sha1', ...args);\n case 'diffie-hellman-group14-sha256':\n return new DHExchange('modp14', 'sha256', ...args);\n case 'diffie-hellman-group15-sha512':\n return new DHExchange('modp15', 'sha512', ...args);\n case 'diffie-hellman-group16-sha512':\n return new DHExchange('modp16', 'sha512', ...args);\n case 'diffie-hellman-group17-sha512':\n return new DHExchange('modp17', 'sha512', ...args);\n case 'diffie-hellman-group18-sha512':\n return new DHExchange('modp18', 'sha512', ...args);\n\n case 'diffie-hellman-group-exchange-sha1':\n return new DHGroupExchange('sha1', ...args);\n case 'diffie-hellman-group-exchange-sha256':\n return new DHGroupExchange('sha256', ...args);\n }\n throw new Error(`Unsupported key exchange algorithm: ${kexType}`);\n }\n throw new Error(`Invalid key exchange type: ${kexType}`);\n };\n})();\n\nconst KexInit = (() => {\n const KEX_PROPERTY_NAMES = [\n 'kex',\n 'serverHostKey',\n ['cs', 'cipher' ],\n ['sc', 'cipher' ],\n ['cs', 'mac' ],\n ['sc', 'mac' ],\n ['cs', 'compress' ],\n ['sc', 'compress' ],\n ['cs', 'lang' ],\n ['sc', 'lang' ],\n ];\n return class KexInit {\n constructor(obj) {\n if (typeof obj !== 'object' || obj === null)\n throw new TypeError('Argument must be an object');\n\n const lists = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n sc: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n\n all: undefined,\n };\n let totalSize = 0;\n for (const prop of KEX_PROPERTY_NAMES) {\n let base;\n let val;\n let desc;\n let key;\n if (typeof prop === 'string') {\n base = lists;\n val = obj[prop];\n desc = key = prop;\n } else {\n const parent = prop[0];\n base = lists[parent];\n key = prop[1];\n val = obj[parent][key];\n desc = `${parent}.${key}`;\n }\n const entry = { array: undefined, buffer: undefined };\n if (Buffer.isBuffer(val)) {\n entry.array = ('' + val).split(',');\n entry.buffer = val;\n totalSize += 4 + val.length;\n } else {\n if (typeof val === 'string')\n val = val.split(',');\n if (Array.isArray(val)) {\n entry.array = val;\n entry.buffer = Buffer.from(val.join(','));\n } else {\n throw new TypeError(`Invalid \\`${desc}\\` type: ${typeof val}`);\n }\n totalSize += 4 + entry.buffer.length;\n }\n base[key] = entry;\n }\n\n const all = Buffer.allocUnsafe(totalSize);\n lists.all = all;\n\n let allPos = 0;\n for (const prop of KEX_PROPERTY_NAMES) {\n let data;\n if (typeof prop === 'string')\n data = lists[prop].buffer;\n else\n data = lists[prop[0]][prop[1]].buffer;\n allPos = writeUInt32BE(all, data.length, allPos);\n all.set(data, allPos);\n allPos += data.length;\n }\n\n this.totalSize = totalSize;\n this.lists = lists;\n }\n copyAllTo(buf, offset) {\n const src = this.lists.all;\n if (typeof offset !== 'number')\n throw new TypeError(`Invalid offset value: ${typeof offset}`);\n if (buf.length - offset < src.length)\n throw new Error('Insufficient space to copy list');\n buf.set(src, offset);\n return src.length;\n }\n };\n})();\n\nconst hashString = (() => {\n const LEN = Buffer.allocUnsafe(4);\n return (hash, buf) => {\n writeUInt32BE(LEN, buf.length, 0);\n hash.update(LEN);\n hash.update(buf);\n };\n})();\n\nfunction generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) {\n let ret;\n if (len) {\n let digest = createHash(hashName)\n .update(secret)\n .update(exchangeHash)\n .update(char)\n .update(sessionID)\n .digest();\n while (digest.length < len) {\n const chunk = createHash(hashName)\n .update(secret)\n .update(exchangeHash)\n .update(digest)\n .digest();\n const extended = Buffer.allocUnsafe(digest.length + chunk.length);\n extended.set(digest, 0);\n extended.set(chunk, digest.length);\n digest = extended;\n }\n if (digest.length === len)\n ret = digest;\n else\n ret = new FastBuffer(digest.buffer, digest.byteOffset, len);\n } else {\n ret = EMPTY_BUFFER;\n }\n return ret;\n}\n\nfunction onKEXPayload(state, payload) {\n // XXX: move this to the Decipher implementations?\n if (payload.length === 0) {\n this._debug && this._debug('Inbound: Skipping empty packet payload');\n return;\n }\n\n if (this._skipNextInboundPacket) {\n this._skipNextInboundPacket = false;\n return;\n }\n\n payload = this._packetRW.read.read(payload);\n\n const type = payload[0];\n switch (type) {\n case MESSAGE.DISCONNECT:\n case MESSAGE.IGNORE:\n case MESSAGE.UNIMPLEMENTED:\n case MESSAGE.DEBUG:\n if (!MESSAGE_HANDLERS)\n MESSAGE_HANDLERS = require('./handlers.js');\n return MESSAGE_HANDLERS[type](this, payload);\n case MESSAGE.KEXINIT:\n if (!state.firstPacket) {\n return doFatalError(\n this,\n 'Received extra KEXINIT during handshake',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n state.firstPacket = false;\n return handleKexInit(this, payload);\n default:\n if (type < 20 || type > 49) {\n return doFatalError(\n this,\n `Received unexpected packet type ${type}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n return this._kex.parse(payload);\n}\n\nfunction dhEstimate(neg) {\n const csCipher = CIPHER_INFO[neg.cs.cipher];\n const scCipher = CIPHER_INFO[neg.sc.cipher];\n // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will\n // also need to be considered when calculating `bits`\n const bits = Math.max(\n 0,\n (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen),\n csCipher.blockLen,\n csCipher.ivLen,\n (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen),\n scCipher.blockLen,\n scCipher.ivLen\n ) * 8;\n if (bits <= 112)\n return 2048;\n if (bits <= 128)\n return 3072;\n if (bits <= 192)\n return 7680;\n return 8192;\n}\n\nfunction trySendNEWKEYS(kex) {\n if (!kex._sentNEWKEYS) {\n kex._protocol._debug && kex._protocol._debug(\n 'Outbound: Sending NEWKEYS'\n );\n const p = kex._protocol._packetRW.write.allocStartKEX;\n const packet = kex._protocol._packetRW.write.alloc(1, true);\n packet[p] = MESSAGE.NEWKEYS;\n kex._protocol._cipher.encrypt(\n kex._protocol._packetRW.write.finalize(packet, true)\n );\n kex._sentNEWKEYS = true;\n }\n}\n\nmodule.exports = {\n KexInit,\n kexinit,\n onKEXPayload,\n DEFAULT_KEXINIT: new KexInit({\n kex: DEFAULT_KEX,\n serverHostKey: DEFAULT_SERVER_HOST_KEY,\n cs: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n sc: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n }),\n HANDLERS: {\n [MESSAGE.KEXINIT]: handleKexInit,\n },\n};\n","// TODO:\n// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()`\n// * handle multi-line header values (OpenSSH)?\n// * more thorough validation?\n'use strict';\n\nconst {\n createDecipheriv,\n createECDH,\n createHash,\n createHmac,\n createSign,\n createVerify,\n getCiphers,\n sign: sign_,\n verify: verify_,\n} = require('crypto');\nconst supportedOpenSSLCiphers = getCiphers();\n\nconst { Ber } = require('asn1');\nconst bcrypt_pbkdf = require('bcrypt-pbkdf').pbkdf;\n\nconst { CIPHER_INFO } = require('./crypto.js');\nconst { eddsaSupported, SUPPORTED_CIPHER } = require('./constants.js');\nconst {\n bufferSlice,\n makeBufferParser,\n readString,\n readUInt32BE,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst SYM_HASH_ALGO = Symbol('Hash Algorithm');\nconst SYM_PRIV_PEM = Symbol('Private key PEM');\nconst SYM_PUB_PEM = Symbol('Public key PEM');\nconst SYM_PUB_SSH = Symbol('Public key SSH');\nconst SYM_DECRYPTED = Symbol('Decrypted Key');\n\n// Create OpenSSL cipher name -> SSH cipher name conversion table\nconst CIPHER_INFO_OPENSSL = Object.create(null);\n{\n const keys = Object.keys(CIPHER_INFO);\n for (let i = 0; i < keys.length; ++i) {\n const cipherName = CIPHER_INFO[keys[i]].sslName;\n if (!cipherName || CIPHER_INFO_OPENSSL[cipherName])\n continue;\n CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]];\n }\n}\n\nconst binaryKeyParser = makeBufferParser();\n\nfunction makePEM(type, data) {\n data = data.base64Slice(0, data.length);\n let formatted = data.replace(/.{64}/g, '$&\\n');\n if (data.length & 63)\n formatted += '\\n';\n return `-----BEGIN ${type} KEY-----\\n${formatted}-----END ${type} KEY-----`;\n}\n\nfunction combineBuffers(buf1, buf2) {\n const result = Buffer.allocUnsafe(buf1.length + buf2.length);\n result.set(buf1, 0);\n result.set(buf2, buf1.length);\n return result;\n}\n\nfunction skipFields(buf, nfields) {\n const bufLen = buf.length;\n let pos = (buf._pos || 0);\n for (let i = 0; i < nfields; ++i) {\n const left = (bufLen - pos);\n if (pos >= bufLen || left < 4)\n return false;\n const len = readUInt32BE(buf, pos);\n if (left < 4 + len)\n return false;\n pos += 4 + len;\n }\n buf._pos = pos;\n return true;\n}\n\nfunction genOpenSSLRSAPub(n, e) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption\n // algorithm parameters (RSA has none)\n asnWriter.writeNull();\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n asnWriter.startSequence();\n asnWriter.writeBuffer(n, Ber.Integer);\n asnWriter.writeBuffer(e, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHRSAPub(n, e) {\n const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length);\n\n writeUInt32BE(publicKey, 7, 0);\n publicKey.utf8Write('ssh-rsa', 4, 7);\n\n let i = 4 + 7;\n writeUInt32BE(publicKey, e.length, i);\n publicKey.set(e, i += 4);\n\n writeUInt32BE(publicKey, n.length, i += e.length);\n publicKey.set(n, i + 4);\n\n return publicKey;\n}\n\nconst genOpenSSLRSAPriv = (() => {\n function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeInt(0x00, Ber.Integer);\n asnWriter.writeBuffer(n, Ber.Integer);\n asnWriter.writeBuffer(e, Ber.Integer);\n asnWriter.writeBuffer(d, Ber.Integer);\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(dmp1, Ber.Integer);\n asnWriter.writeBuffer(dmq1, Ber.Integer);\n asnWriter.writeBuffer(iqmp, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n\n function bigIntFromBuffer(buf) {\n return BigInt(`0x${buf.hexSlice(0, buf.length)}`);\n }\n\n function bigIntToBuffer(bn) {\n let hex = bn.toString(16);\n if ((hex.length & 1) !== 0) {\n hex = `0${hex}`;\n } else {\n const sigbit = hex.charCodeAt(0);\n // BER/DER integers require leading zero byte to denote a positive value\n // when first byte >= 0x80\n if (sigbit === 56/* '8' */\n || sigbit === 57/* '9' */\n || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) {\n hex = `00${hex}`;\n }\n }\n return Buffer.from(hex, 'hex');\n }\n\n return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) {\n const bn_d = bigIntFromBuffer(d);\n const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n));\n const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n));\n return makePEM('RSA PRIVATE',\n genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp));\n };\n})();\n\nfunction genOpenSSLDSAPub(p, q, g, y) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa\n // algorithm parameters\n asnWriter.startSequence();\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(g, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n asnWriter.writeBuffer(y, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHDSAPub(p, q, g, y) {\n const publicKey = Buffer.allocUnsafe(\n 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length\n );\n\n writeUInt32BE(publicKey, 7, 0);\n publicKey.utf8Write('ssh-dss', 4, 7);\n\n let i = 4 + 7;\n writeUInt32BE(publicKey, p.length, i);\n publicKey.set(p, i += 4);\n\n writeUInt32BE(publicKey, q.length, i += p.length);\n publicKey.set(q, i += 4);\n\n writeUInt32BE(publicKey, g.length, i += q.length);\n publicKey.set(g, i += 4);\n\n writeUInt32BE(publicKey, y.length, i += g.length);\n publicKey.set(y, i + 4);\n\n return publicKey;\n}\n\nfunction genOpenSSLDSAPriv(p, q, g, y, x) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeInt(0x00, Ber.Integer);\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(g, Ber.Integer);\n asnWriter.writeBuffer(y, Ber.Integer);\n asnWriter.writeBuffer(x, Ber.Integer);\n asnWriter.endSequence();\n return makePEM('DSA PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLEdPub(pub) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.112'); // id-Ed25519\n asnWriter.endSequence();\n\n // PublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(pub.length);\n asnWriter._buf.set(pub, asnWriter._offset);\n asnWriter._offset += pub.length;\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHEdPub(pub) {\n const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length);\n\n writeUInt32BE(publicKey, 11, 0);\n publicKey.utf8Write('ssh-ed25519', 4, 11);\n\n writeUInt32BE(publicKey, pub.length, 15);\n publicKey.set(pub, 19);\n\n return publicKey;\n}\n\nfunction genOpenSSLEdPriv(priv) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // version\n asnWriter.writeInt(0x00, Ber.Integer);\n\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.112'); // id-Ed25519\n asnWriter.endSequence();\n\n // PrivateKey\n asnWriter.startSequence(Ber.OctetString);\n asnWriter.writeBuffer(priv, Ber.OctetString);\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLECDSAPub(oid, Q) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey\n // algorithm parameters (namedCurve)\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(Q.length);\n asnWriter._buf.set(Q, asnWriter._offset);\n asnWriter._offset += Q.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHECDSAPub(oid, Q) {\n let curveName;\n switch (oid) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n curveName = 'nistp256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n curveName = 'nistp384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n curveName = 'nistp521';\n break;\n default:\n return;\n }\n\n const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length);\n\n writeUInt32BE(publicKey, 19, 0);\n publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19);\n\n writeUInt32BE(publicKey, 8, 23);\n publicKey.utf8Write(curveName, 27, 8);\n\n writeUInt32BE(publicKey, Q.length, 35);\n publicKey.set(Q, 39);\n\n return publicKey;\n}\n\nfunction genOpenSSLECDSAPriv(oid, pub, priv) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // version\n asnWriter.writeInt(0x01, Ber.Integer);\n // privateKey\n asnWriter.writeBuffer(priv, Ber.OctetString);\n // parameters (optional)\n asnWriter.startSequence(0xA0);\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n // publicKey (optional)\n asnWriter.startSequence(0xA1);\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(pub.length);\n asnWriter._buf.set(pub, asnWriter._offset);\n asnWriter._offset += pub.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('EC PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLECDSAPubFromPriv(curveName, priv) {\n const tempECDH = createECDH(curveName);\n tempECDH.setPrivateKey(priv);\n return tempECDH.getPublicKey();\n}\n\nconst BaseKey = {\n sign: (() => {\n if (typeof sign_ === 'function') {\n return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return sign_(algo, data, pem);\n } catch (ex) {\n return ex;\n }\n };\n }\n return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n const signature = createSign(algo);\n signature.update(data);\n try {\n return signature.sign(pem);\n } catch (ex) {\n return ex;\n }\n };\n })(),\n verify: (() => {\n if (typeof verify_ === 'function') {\n return function verify(data, signature, algo) {\n const pem = this[SYM_PUB_PEM];\n if (pem === null)\n return new Error('No public key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return verify_(algo, data, pem, signature);\n } catch (ex) {\n return ex;\n }\n };\n }\n return function verify(data, signature, algo) {\n const pem = this[SYM_PUB_PEM];\n if (pem === null)\n return new Error('No public key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n const verifier = createVerify(algo);\n verifier.update(data);\n try {\n return verifier.verify(pem, signature);\n } catch (ex) {\n return ex;\n }\n };\n })(),\n isPrivateKey: function isPrivateKey() {\n return (this[SYM_PRIV_PEM] !== null);\n },\n getPrivatePEM: function getPrivatePEM() {\n return this[SYM_PRIV_PEM];\n },\n getPublicPEM: function getPublicPEM() {\n return this[SYM_PUB_PEM];\n },\n getPublicSSH: function getPublicSSH() {\n return this[SYM_PUB_SSH];\n },\n equals: function equals(key) {\n const parsed = parseKey(key);\n if (parsed instanceof Error)\n return false;\n return (\n this.type === parsed.type\n && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM]\n && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM]\n && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH]\n );\n },\n};\n\n\nfunction OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo,\n decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nOpenSSH_Private.prototype = BaseKey;\n{\n const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\\r\\n|\\n)([\\s\\S]+)(?:\\r\\n|\\n)-----END OPENSSH PRIVATE KEY-----$/;\n OpenSSH_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n let ret;\n const data = Buffer.from(m[1], 'base64');\n if (data.length < 31) // magic (+ magic null term.) + minimum field lengths\n return new Error('Malformed OpenSSH private key');\n const magic = data.utf8Slice(0, 15);\n if (magic !== 'openssh-key-v1\\0')\n return new Error(`Unsupported OpenSSH key magic: ${magic}`);\n\n const cipherName = readString(data, 15, true);\n if (cipherName === undefined)\n return new Error('Malformed OpenSSH private key');\n if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1)\n return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`);\n\n const kdfName = readString(data, data._pos, true);\n if (kdfName === undefined)\n return new Error('Malformed OpenSSH private key');\n if (kdfName !== 'none') {\n if (cipherName === 'none')\n return new Error('Malformed OpenSSH private key');\n if (kdfName !== 'bcrypt')\n return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`);\n if (!passphrase) {\n return new Error(\n 'Encrypted private OpenSSH key detected, but no passphrase given'\n );\n }\n } else if (cipherName !== 'none') {\n return new Error('Malformed OpenSSH private key');\n }\n\n let encInfo;\n let cipherKey;\n let cipherIV;\n if (cipherName !== 'none')\n encInfo = CIPHER_INFO[cipherName];\n const kdfOptions = readString(data, data._pos);\n if (kdfOptions === undefined)\n return new Error('Malformed OpenSSH private key');\n if (kdfOptions.length) {\n switch (kdfName) {\n case 'none':\n return new Error('Malformed OpenSSH private key');\n case 'bcrypt':\n /*\n string salt\n uint32 rounds\n */\n const salt = readString(kdfOptions, 0);\n if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length)\n return new Error('Malformed OpenSSH private key');\n const rounds = readUInt32BE(kdfOptions, kdfOptions._pos);\n const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen);\n const r = bcrypt_pbkdf(passphrase,\n passphrase.length,\n salt,\n salt.length,\n gen,\n gen.length,\n rounds);\n if (r !== 0)\n return new Error('Failed to generate information to decrypt key');\n cipherKey = bufferSlice(gen, 0, encInfo.keyLen);\n cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length);\n break;\n }\n } else if (kdfName !== 'none') {\n return new Error('Malformed OpenSSH private key');\n }\n\n if (data._pos + 3 >= data.length)\n return new Error('Malformed OpenSSH private key');\n const keyCount = readUInt32BE(data, data._pos);\n data._pos += 4;\n\n if (keyCount > 0) {\n // TODO: place sensible limit on max `keyCount`\n\n // Read public keys first\n for (let i = 0; i < keyCount; ++i) {\n const pubData = readString(data, data._pos);\n if (pubData === undefined)\n return new Error('Malformed OpenSSH private key');\n const type = readString(pubData, 0, true);\n if (type === undefined)\n return new Error('Malformed OpenSSH private key');\n }\n\n let privBlob = readString(data, data._pos);\n if (privBlob === undefined)\n return new Error('Malformed OpenSSH private key');\n\n if (cipherKey !== undefined) {\n // Encrypted private key(s)\n if (privBlob.length < encInfo.blockLen\n || (privBlob.length % encInfo.blockLen) !== 0) {\n return new Error('Malformed OpenSSH private key');\n }\n try {\n const options = { authTagLength: encInfo.authLen };\n const decipher = createDecipheriv(encInfo.sslName,\n cipherKey,\n cipherIV,\n options);\n if (encInfo.authLen > 0) {\n if (data.length - data._pos < encInfo.authLen)\n return new Error('Malformed OpenSSH private key');\n decipher.setAuthTag(\n bufferSlice(data, data._pos, data._pos += encInfo.authLen)\n );\n }\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n } catch (ex) {\n return ex;\n }\n }\n // Nothing should we follow the private key(s), except a possible\n // authentication tag for relevant ciphers\n if (data._pos !== data.length)\n return new Error('Malformed OpenSSH private key');\n\n ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined);\n } else {\n ret = [];\n }\n if (ret instanceof Error)\n return ret;\n // This will need to change if/when OpenSSH ever starts storing multiple\n // keys in their key files\n return ret[0];\n };\n\n function parseOpenSSHPrivKeys(data, nkeys, decrypted) {\n const keys = [];\n /*\n uint32 checkint\n uint32 checkint\n string privatekey1\n string comment1\n string privatekey2\n string comment2\n ...\n string privatekeyN\n string commentN\n char 1\n char 2\n char 3\n ...\n char padlen % 255\n */\n if (data.length < 8)\n return new Error('Malformed OpenSSH private key');\n const check1 = readUInt32BE(data, 0);\n const check2 = readUInt32BE(data, 4);\n if (check1 !== check2) {\n if (decrypted) {\n return new Error(\n 'OpenSSH key integrity check failed -- bad passphrase?'\n );\n }\n return new Error('OpenSSH key integrity check failed');\n }\n data._pos = 8;\n let i;\n let oid;\n for (i = 0; i < nkeys; ++i) {\n let algo;\n let privPEM;\n let pubPEM;\n let pubSSH;\n // The OpenSSH documentation for the key format actually lies, the\n // entirety of the private key content is not contained with a string\n // field, it's actually the literal contents of the private key, so to be\n // able to find the end of the key data you need to know the layout/format\n // of each key type ...\n const type = readString(data, data._pos, true);\n if (type === undefined)\n return new Error('Malformed OpenSSH private key');\n\n switch (type) {\n case 'ssh-rsa': {\n /*\n string n -- public\n string e -- public\n string d -- private\n string iqmp -- private\n string p -- private\n string q -- private\n */\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed OpenSSH private key');\n const e = readString(data, data._pos);\n if (e === undefined)\n return new Error('Malformed OpenSSH private key');\n const d = readString(data, data._pos);\n if (d === undefined)\n return new Error('Malformed OpenSSH private key');\n const iqmp = readString(data, data._pos);\n if (iqmp === undefined)\n return new Error('Malformed OpenSSH private key');\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed OpenSSH private key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q);\n algo = 'sha1';\n break;\n }\n case 'ssh-dss': {\n /*\n string p -- public\n string q -- public\n string g -- public\n string y -- public\n string x -- private\n */\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed OpenSSH private key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH private key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed OpenSSH private key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed OpenSSH private key');\n const x = readString(data, data._pos);\n if (x === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n privPEM = genOpenSSLDSAPriv(p, q, g, y, x);\n algo = 'sha1';\n break;\n }\n case 'ssh-ed25519': {\n if (!eddsaSupported)\n return new Error(`Unsupported OpenSSH private key type: ${type}`);\n /*\n * string public key\n * string private key + public key\n */\n const edpub = readString(data, data._pos);\n if (edpub === undefined || edpub.length !== 32)\n return new Error('Malformed OpenSSH private key');\n const edpriv = readString(data, data._pos);\n if (edpriv === undefined || edpriv.length !== 64)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLEdPub(edpub);\n pubSSH = genOpenSSHEdPub(edpub);\n privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32));\n algo = null;\n break;\n }\n case 'ecdsa-sha2-nistp256':\n algo = 'sha256';\n oid = '1.2.840.10045.3.1.7';\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp384':\n if (algo === undefined) {\n algo = 'sha384';\n oid = '1.3.132.0.34';\n }\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp521': {\n if (algo === undefined) {\n algo = 'sha512';\n oid = '1.3.132.0.35';\n }\n /*\n string curve name\n string Q -- public\n string d -- private\n */\n // TODO: validate curve name against type\n if (!skipFields(data, 1)) // Skip curve name\n return new Error('Malformed OpenSSH private key');\n const ecpub = readString(data, data._pos);\n if (ecpub === undefined)\n return new Error('Malformed OpenSSH private key');\n const ecpriv = readString(data, data._pos);\n if (ecpriv === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLECDSAPub(oid, ecpub);\n pubSSH = genOpenSSHECDSAPub(oid, ecpub);\n privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv);\n break;\n }\n default:\n return new Error(`Unsupported OpenSSH private key type: ${type}`);\n }\n\n const privComment = readString(data, data._pos, true);\n if (privComment === undefined)\n return new Error('Malformed OpenSSH private key');\n\n keys.push(\n new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo,\n decrypted)\n );\n }\n let cnt = 0;\n for (i = data._pos; i < data.length; ++i) {\n if (data[i] !== (++cnt % 255))\n return new Error('Malformed OpenSSH private key');\n }\n\n return keys;\n }\n}\n\n\nfunction OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo,\n decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nOpenSSH_Old_Private.prototype = BaseKey;\n{\n const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\\r\\n|\\n)((?:[^:]+:\\s*[\\S].*(?:\\r\\n|\\n))*)([\\s\\S]+)(?:\\r\\n|\\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/;\n OpenSSH_Old_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n let privBlob = Buffer.from(m[3], 'base64');\n let headers = m[2];\n let decrypted = false;\n if (headers !== undefined) {\n // encrypted key\n headers = headers.split(/\\r\\n|\\n/g);\n for (let i = 0; i < headers.length; ++i) {\n const header = headers[i];\n let sepIdx = header.indexOf(':');\n if (header.slice(0, sepIdx) === 'DEK-Info') {\n const val = header.slice(sepIdx + 2);\n sepIdx = val.indexOf(',');\n if (sepIdx === -1)\n continue;\n const cipherName = val.slice(0, sepIdx).toLowerCase();\n if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) {\n return new Error(\n `Cipher (${cipherName}) not supported `\n + 'for encrypted OpenSSH private key'\n );\n }\n const encInfo = CIPHER_INFO_OPENSSL[cipherName];\n if (!encInfo) {\n return new Error(\n `Cipher (${cipherName}) not supported `\n + 'for encrypted OpenSSH private key'\n );\n }\n const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex');\n if (cipherIV.length !== encInfo.ivLen)\n return new Error('Malformed encrypted OpenSSH private key');\n if (!passphrase) {\n return new Error(\n 'Encrypted OpenSSH private key detected, but no passphrase given'\n );\n }\n const ivSlice = bufferSlice(cipherIV, 0, 8);\n let cipherKey = createHash('md5')\n .update(passphrase)\n .update(ivSlice)\n .digest();\n while (cipherKey.length < encInfo.keyLen) {\n cipherKey = combineBuffers(\n cipherKey,\n createHash('md5')\n .update(cipherKey)\n .update(passphrase)\n .update(ivSlice)\n .digest()\n );\n }\n if (cipherKey.length > encInfo.keyLen)\n cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen);\n try {\n const decipher = createDecipheriv(cipherName, cipherKey, cipherIV);\n decipher.setAutoPadding(false);\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n decrypted = true;\n } catch (ex) {\n return ex;\n }\n }\n }\n }\n\n let type;\n let privPEM;\n let pubPEM;\n let pubSSH;\n let algo;\n let reader;\n let errMsg = 'Malformed OpenSSH private key';\n if (decrypted)\n errMsg += '. Bad passphrase?';\n switch (m[1]) {\n case 'RSA':\n type = 'ssh-rsa';\n privPEM = makePEM('RSA PRIVATE', privBlob);\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n const n = reader.readString(Ber.Integer, true);\n if (n === null)\n return new Error(errMsg);\n const e = reader.readString(Ber.Integer, true);\n if (e === null)\n return new Error(errMsg);\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n } catch {\n return new Error(errMsg);\n }\n algo = 'sha1';\n break;\n case 'DSA':\n type = 'ssh-dss';\n privPEM = makePEM('DSA PRIVATE', privBlob);\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n const p = reader.readString(Ber.Integer, true);\n if (p === null)\n return new Error(errMsg);\n const q = reader.readString(Ber.Integer, true);\n if (q === null)\n return new Error(errMsg);\n const g = reader.readString(Ber.Integer, true);\n if (g === null)\n return new Error(errMsg);\n const y = reader.readString(Ber.Integer, true);\n if (y === null)\n return new Error(errMsg);\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n } catch {\n return new Error(errMsg);\n }\n algo = 'sha1';\n break;\n case 'EC':\n let ecSSLName;\n let ecPriv;\n let ecOID;\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n ecPriv = reader.readString(Ber.OctetString, true);\n reader.readByte(); // Skip \"complex\" context type byte\n const offset = reader.readLength(); // Skip context length\n if (offset !== null) {\n reader._offset = offset;\n ecOID = reader.readOID();\n if (ecOID === null)\n return new Error(errMsg);\n switch (ecOID) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n ecSSLName = 'prime256v1';\n type = 'ecdsa-sha2-nistp256';\n algo = 'sha256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n ecSSLName = 'secp384r1';\n type = 'ecdsa-sha2-nistp384';\n algo = 'sha384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n ecSSLName = 'secp521r1';\n type = 'ecdsa-sha2-nistp521';\n algo = 'sha512';\n break;\n default:\n return new Error(`Unsupported private key EC OID: ${ecOID}`);\n }\n } else {\n return new Error(errMsg);\n }\n } catch {\n return new Error(errMsg);\n }\n privPEM = makePEM('EC PRIVATE', privBlob);\n const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv);\n pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob);\n pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob);\n break;\n }\n\n return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo,\n decrypted);\n };\n}\n\n\nfunction PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nPPK_Private.prototype = BaseKey;\n{\n const EMPTY_PASSPHRASE = Buffer.alloc(0);\n const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n const PPK_PP1 = Buffer.from([0, 0, 0, 0]);\n const PPK_PP2 = Buffer.from([0, 0, 0, 1]);\n const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\\r?\\nEncryption: (aes256-cbc|none)\\r?\\nComment: ([^\\r\\n]*)\\r?\\nPublic-Lines: \\d+\\r?\\n([\\s\\S]+?)\\r?\\nPrivate-Lines: \\d+\\r?\\n([\\s\\S]+?)\\r?\\nPrivate-MAC: ([^\\r\\n]+)/;\n PPK_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n // m[1] = key type\n // m[2] = encryption type\n // m[3] = comment\n // m[4] = base64-encoded public key data:\n // for \"ssh-rsa\":\n // string \"ssh-rsa\"\n // mpint e (public exponent)\n // mpint n (modulus)\n // for \"ssh-dss\":\n // string \"ssh-dss\"\n // mpint p (modulus)\n // mpint q (prime)\n // mpint g (base number)\n // mpint y (public key parameter: g^x mod p)\n // m[5] = base64-encoded private key data:\n // for \"ssh-rsa\":\n // mpint d (private exponent)\n // mpint p (prime 1)\n // mpint q (prime 2)\n // mpint iqmp ([inverse of q] mod p)\n // for \"ssh-dss\":\n // mpint x (private key parameter)\n // m[6] = SHA1 HMAC over:\n // string name of algorithm (\"ssh-dss\", \"ssh-rsa\")\n // string encryption type\n // string comment\n // string public key data\n // string private-plaintext (including the final padding)\n const cipherName = m[2];\n const encrypted = (cipherName !== 'none');\n if (encrypted && !passphrase) {\n return new Error(\n 'Encrypted PPK private key detected, but no passphrase given'\n );\n }\n\n let privBlob = Buffer.from(m[5], 'base64');\n\n if (encrypted) {\n const encInfo = CIPHER_INFO[cipherName];\n let cipherKey = combineBuffers(\n createHash('sha1').update(PPK_PP1).update(passphrase).digest(),\n createHash('sha1').update(PPK_PP2).update(passphrase).digest()\n );\n if (cipherKey.length > encInfo.keyLen)\n cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen);\n try {\n const decipher = createDecipheriv(encInfo.sslName,\n cipherKey,\n PPK_IV);\n decipher.setAutoPadding(false);\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n } catch (ex) {\n return ex;\n }\n }\n\n const type = m[1];\n const comment = m[3];\n const pubBlob = Buffer.from(m[4], 'base64');\n\n const mac = m[6];\n const typeLen = type.length;\n const cipherNameLen = cipherName.length;\n const commentLen = Buffer.byteLength(comment);\n const pubLen = pubBlob.length;\n const privLen = privBlob.length;\n const macData = Buffer.allocUnsafe(4 + typeLen\n + 4 + cipherNameLen\n + 4 + commentLen\n + 4 + pubLen\n + 4 + privLen);\n let p = 0;\n\n writeUInt32BE(macData, typeLen, p);\n macData.utf8Write(type, p += 4, typeLen);\n writeUInt32BE(macData, cipherNameLen, p += typeLen);\n macData.utf8Write(cipherName, p += 4, cipherNameLen);\n writeUInt32BE(macData, commentLen, p += cipherNameLen);\n macData.utf8Write(comment, p += 4, commentLen);\n writeUInt32BE(macData, pubLen, p += commentLen);\n macData.set(pubBlob, p += 4);\n writeUInt32BE(macData, privLen, p += pubLen);\n macData.set(privBlob, p + 4);\n\n if (!passphrase)\n passphrase = EMPTY_PASSPHRASE;\n\n const calcMAC = createHmac(\n 'sha1',\n createHash('sha1')\n .update('putty-private-key-file-mac-key')\n .update(passphrase)\n .digest()\n ).update(macData).digest('hex');\n\n if (calcMAC !== mac) {\n if (encrypted) {\n return new Error(\n 'PPK private key integrity check failed -- bad passphrase?'\n );\n }\n return new Error('PPK private key integrity check failed');\n }\n\n let pubPEM;\n let pubSSH;\n let privPEM;\n pubBlob._pos = 0;\n skipFields(pubBlob, 1); // skip (duplicate) key type\n switch (type) {\n case 'ssh-rsa': {\n const e = readString(pubBlob, pubBlob._pos);\n if (e === undefined)\n return new Error('Malformed PPK public key');\n const n = readString(pubBlob, pubBlob._pos);\n if (n === undefined)\n return new Error('Malformed PPK public key');\n const d = readString(privBlob, 0);\n if (d === undefined)\n return new Error('Malformed PPK private key');\n const p = readString(privBlob, privBlob._pos);\n if (p === undefined)\n return new Error('Malformed PPK private key');\n const q = readString(privBlob, privBlob._pos);\n if (q === undefined)\n return new Error('Malformed PPK private key');\n const iqmp = readString(privBlob, privBlob._pos);\n if (iqmp === undefined)\n return new Error('Malformed PPK private key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q);\n break;\n }\n case 'ssh-dss': {\n const p = readString(pubBlob, pubBlob._pos);\n if (p === undefined)\n return new Error('Malformed PPK public key');\n const q = readString(pubBlob, pubBlob._pos);\n if (q === undefined)\n return new Error('Malformed PPK public key');\n const g = readString(pubBlob, pubBlob._pos);\n if (g === undefined)\n return new Error('Malformed PPK public key');\n const y = readString(pubBlob, pubBlob._pos);\n if (y === undefined)\n return new Error('Malformed PPK public key');\n const x = readString(privBlob, 0);\n if (x === undefined)\n return new Error('Malformed PPK private key');\n\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n privPEM = genOpenSSLDSAPriv(p, q, g, y, x);\n break;\n }\n }\n\n return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1',\n encrypted);\n };\n}\n\n\nfunction OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = null;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = false;\n}\nOpenSSH_Public.prototype = BaseKey;\n{\n let regexp;\n if (eddsaSupported)\n regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\\s+([\\S].*)?)$/;\n else\n regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\\s+([\\S].*)?)$/;\n OpenSSH_Public.parse = (str) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n // m[1] = full type\n // m[2] = base type\n // m[3] = base64-encoded public key\n // m[4] = comment\n\n const fullType = m[1];\n const baseType = m[2];\n const data = Buffer.from(m[3], 'base64');\n const comment = (m[4] || '');\n\n const type = readString(data, data._pos, true);\n if (type === undefined || type.indexOf(baseType) !== 0)\n return new Error('Malformed OpenSSH public key');\n\n return parseDER(data, baseType, comment, fullType);\n };\n}\n\n\nfunction RFC4716_Public(type, comment, pubPEM, pubSSH, algo) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = null;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = false;\n}\nRFC4716_Public.prototype = BaseKey;\n{\n const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\\r?\\n)((?:.{0,72}\\r?\\n)+)---- END SSH2 PUBLIC KEY ----$/;\n const RE_DATA = /^[A-Z0-9a-z/+=\\r\\n]+$/;\n const RE_HEADER = /^([\\x21-\\x39\\x3B-\\x7E]{1,64}): ((?:[^\\\\]*\\\\\\r?\\n)*[^\\r\\n]+)\\r?\\n/gm;\n const RE_HEADER_ENDS = /\\\\\\r?\\n/g;\n RFC4716_Public.parse = (str) => {\n let m = regexp.exec(str);\n if (m === null)\n return null;\n\n const body = m[1];\n let dataStart = 0;\n let comment = '';\n\n while (m = RE_HEADER.exec(body)) {\n const headerName = m[1];\n const headerValue = m[2].replace(RE_HEADER_ENDS, '');\n if (headerValue.length > 1024) {\n RE_HEADER.lastIndex = 0;\n return new Error('Malformed RFC4716 public key');\n }\n\n dataStart = RE_HEADER.lastIndex;\n\n if (headerName.toLowerCase() === 'comment') {\n comment = headerValue;\n if (comment.length > 1\n && comment.charCodeAt(0) === 34/* '\"' */\n && comment.charCodeAt(comment.length - 1) === 34/* '\"' */) {\n comment = comment.slice(1, -1);\n }\n }\n }\n\n let data = body.slice(dataStart);\n if (!RE_DATA.test(data))\n return new Error('Malformed RFC4716 public key');\n\n data = Buffer.from(data, 'base64');\n\n const type = readString(data, 0, true);\n if (type === undefined)\n return new Error('Malformed RFC4716 public key');\n\n let pubPEM = null;\n let pubSSH = null;\n switch (type) {\n case 'ssh-rsa': {\n const e = readString(data, data._pos);\n if (e === undefined)\n return new Error('Malformed RFC4716 public key');\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed RFC4716 public key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n break;\n }\n case 'ssh-dss': {\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed RFC4716 public key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed RFC4716 public key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed RFC4716 public key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed RFC4716 public key');\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n break;\n }\n default:\n return new Error('Malformed RFC4716 public key');\n }\n\n return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1');\n };\n}\n\n\nfunction parseDER(data, baseType, comment, fullType) {\n if (!isSupportedKeyType(baseType))\n return new Error(`Unsupported OpenSSH public key type: ${baseType}`);\n\n let algo;\n let oid;\n let pubPEM = null;\n let pubSSH = null;\n\n switch (baseType) {\n case 'ssh-rsa': {\n const e = readString(data, data._pos || 0);\n if (e === undefined)\n return new Error('Malformed OpenSSH public key');\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n algo = 'sha1';\n break;\n }\n case 'ssh-dss': {\n const p = readString(data, data._pos || 0);\n if (p === undefined)\n return new Error('Malformed OpenSSH public key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH public key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed OpenSSH public key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n algo = 'sha1';\n break;\n }\n case 'ssh-ed25519': {\n const edpub = readString(data, data._pos || 0);\n if (edpub === undefined || edpub.length !== 32)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLEdPub(edpub);\n pubSSH = genOpenSSHEdPub(edpub);\n algo = null;\n break;\n }\n case 'ecdsa-sha2-nistp256':\n algo = 'sha256';\n oid = '1.2.840.10045.3.1.7';\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp384':\n if (algo === undefined) {\n algo = 'sha384';\n oid = '1.3.132.0.34';\n }\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp521': {\n if (algo === undefined) {\n algo = 'sha512';\n oid = '1.3.132.0.35';\n }\n // TODO: validate curve name against type\n if (!skipFields(data, 1)) // Skip curve name\n return new Error('Malformed OpenSSH public key');\n const ecpub = readString(data, data._pos || 0);\n if (ecpub === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLECDSAPub(oid, ecpub);\n pubSSH = genOpenSSHECDSAPub(oid, ecpub);\n break;\n }\n default:\n return new Error(`Unsupported OpenSSH public key type: ${baseType}`);\n }\n\n return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo);\n}\n\nfunction isSupportedKeyType(type) {\n switch (type) {\n case 'ssh-rsa':\n case 'ssh-dss':\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521':\n return true;\n case 'ssh-ed25519':\n if (eddsaSupported)\n return true;\n // FALLTHROUGH\n default:\n return false;\n }\n}\n\nfunction isParsedKey(val) {\n if (!val)\n return false;\n return (typeof val[SYM_DECRYPTED] === 'boolean');\n}\n\nfunction parseKey(data, passphrase) {\n if (isParsedKey(data))\n return data;\n\n let origBuffer;\n if (Buffer.isBuffer(data)) {\n origBuffer = data;\n data = data.utf8Slice(0, data.length).trim();\n } else if (typeof data === 'string') {\n data = data.trim();\n } else {\n return new Error('Key data must be a Buffer or string');\n }\n\n // eslint-disable-next-line eqeqeq\n if (passphrase != undefined) {\n if (typeof passphrase === 'string')\n passphrase = Buffer.from(passphrase);\n else if (!Buffer.isBuffer(passphrase))\n return new Error('Passphrase must be a string or Buffer when supplied');\n }\n\n let ret;\n\n // First try as printable string format (e.g. PEM)\n\n // Private keys\n if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null)\n return ret;\n if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null)\n return ret;\n if ((ret = PPK_Private.parse(data, passphrase)) !== null)\n return ret;\n\n // Public keys\n if ((ret = OpenSSH_Public.parse(data)) !== null)\n return ret;\n if ((ret = RFC4716_Public.parse(data)) !== null)\n return ret;\n\n // Finally try as a binary format if we were originally passed binary data\n if (origBuffer) {\n binaryKeyParser.init(origBuffer, 0);\n const type = binaryKeyParser.readString(true);\n if (type !== undefined) {\n data = binaryKeyParser.readRaw();\n if (data !== undefined) {\n ret = parseDER(data, type, '', type);\n // Ignore potentially useless errors in case the data was not actually\n // in the binary format\n if (ret instanceof Error)\n ret = null;\n }\n }\n binaryKeyParser.clear();\n }\n\n if (ret)\n return ret;\n\n return new Error('Unsupported key format');\n}\n\nmodule.exports = {\n isParsedKey,\n isSupportedKeyType,\n parseDERKey: (data, type) => parseDER(data, type, '', type),\n parseKey,\n};\n","'use strict';\n\nconst assert = require('assert');\nconst { inspect } = require('util');\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n let res = '';\n let i = val.length;\n const start = val[0] === '-' ? 1 : 0;\n for (; i >= start + 4; i -= 3)\n res = `_${val.slice(i - 3, i)}${res}`;\n return `${val.slice(0, i)}${res}`;\n}\n\nfunction oneOf(expected, thing) {\n assert(typeof thing === 'string', '`thing` has to be of type string');\n if (Array.isArray(expected)) {\n const len = expected.length;\n assert(len > 0, 'At least one expected value needs to be specified');\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or `\n + expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n }\n return `of ${thing} ${expected[0]}`;\n }\n return `of ${thing} ${String(expected)}`;\n}\n\n\nexports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error {\n constructor(message) {\n super();\n Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION);\n\n const suffix = 'This is caused by either a bug in ssh2 '\n + 'or incorrect usage of ssh2 internals.\\n'\n + 'Please open an issue with this stack trace at '\n + 'https://github.com/mscdex/ssh2/issues\\n';\n\n this.message = (message === undefined ? suffix : `${message}\\n${suffix}`);\n }\n};\n\nconst MAX_32BIT_INT = 2 ** 32;\nconst MAX_32BIT_BIGINT = (() => {\n try {\n return new Function('return 2n ** 32n')();\n } catch {}\n})();\nexports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError {\n constructor(str, range, input, replaceDefaultBoolean) {\n super();\n Error.captureStackTrace(this, ERR_OUT_OF_RANGE);\n\n assert(range, 'Missing \"range\" argument');\n let msg = (replaceDefaultBoolean\n ? str\n : `The value of \"${str}\" is out of range.`);\n let received;\n if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) {\n received = addNumericalSeparator(String(input));\n } else if (typeof input === 'bigint') {\n received = String(input);\n if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT)\n received = addNumericalSeparator(received);\n received += 'n';\n } else {\n received = inspect(input);\n }\n msg += ` It must be ${range}. Received ${received}`;\n\n this.message = msg;\n }\n};\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super();\n Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE);\n\n assert(typeof name === 'string', `'name' must be a string`);\n\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && expected.startsWith('not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (name.endsWith(' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = (name.includes('.') ? 'property' : 'argument');\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n\n this.message = msg;\n }\n}\nexports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE;\n\nexports.validateNumber = function validateNumber(value, name) {\n if (typeof value !== 'number')\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value);\n};\n","'use strict';\n\nconst Ber = require('asn1').Ber;\n\nlet DISCONNECT_REASON;\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill;\n\nfunction readUInt32BE(buf, offset) {\n return (buf[offset++] * 16777216)\n + (buf[offset++] * 65536)\n + (buf[offset++] * 256)\n + buf[offset];\n}\n\nfunction bufferCopy(src, dest, srcStart, srcEnd, destStart) {\n if (!destStart)\n destStart = 0;\n if (srcEnd > src.length)\n srcEnd = src.length;\n let nb = srcEnd - srcStart;\n const destLeft = (dest.length - destStart);\n if (nb > destLeft)\n nb = destLeft;\n dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb),\n destStart);\n return nb;\n}\n\nfunction bufferSlice(buf, start, end) {\n if (end === undefined)\n end = buf.length;\n return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start);\n}\n\nfunction makeBufferParser() {\n let pos = 0;\n let buffer;\n\n const self = {\n init: (buf, start) => {\n buffer = buf;\n pos = (typeof start === 'number' ? start : 0);\n },\n pos: () => pos,\n length: () => (buffer ? buffer.length : 0),\n avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0),\n clear: () => {\n buffer = undefined;\n },\n readUInt32BE: () => {\n if (!buffer || pos + 3 >= buffer.length)\n return;\n return (buffer[pos++] * 16777216)\n + (buffer[pos++] * 65536)\n + (buffer[pos++] * 256)\n + buffer[pos++];\n },\n readUInt64BE: (behavior) => {\n if (!buffer || pos + 7 >= buffer.length)\n return;\n switch (behavior) {\n case 'always':\n return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`);\n case 'maybe':\n if (buffer[pos] > 0x1F)\n return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`);\n // FALLTHROUGH\n default:\n return (buffer[pos++] * 72057594037927940)\n + (buffer[pos++] * 281474976710656)\n + (buffer[pos++] * 1099511627776)\n + (buffer[pos++] * 4294967296)\n + (buffer[pos++] * 16777216)\n + (buffer[pos++] * 65536)\n + (buffer[pos++] * 256)\n + buffer[pos++];\n }\n },\n skip: (n) => {\n if (buffer && n > 0)\n pos += n;\n },\n skipString: () => {\n const len = self.readUInt32BE();\n if (len === undefined)\n return;\n pos += len;\n return (pos <= buffer.length ? len : undefined);\n },\n readByte: () => {\n if (buffer && pos < buffer.length)\n return buffer[pos++];\n },\n readBool: () => {\n if (buffer && pos < buffer.length)\n return !!buffer[pos++];\n },\n readList: () => {\n const list = self.readString(true);\n if (list === undefined)\n return;\n return (list ? list.split(',') : []);\n },\n readString: (dest, maxLen) => {\n if (typeof dest === 'number') {\n maxLen = dest;\n dest = undefined;\n }\n\n const len = self.readUInt32BE();\n if (len === undefined)\n return;\n\n if ((buffer.length - pos) < len\n || (typeof maxLen === 'number' && len > maxLen)) {\n return;\n }\n\n if (dest) {\n if (Buffer.isBuffer(dest))\n return bufferCopy(buffer, dest, pos, pos += len);\n return buffer.utf8Slice(pos, pos += len);\n }\n return bufferSlice(buffer, pos, pos += len);\n },\n readRaw: (len) => {\n if (!buffer)\n return;\n if (typeof len !== 'number')\n return bufferSlice(buffer, pos, pos += (buffer.length - pos));\n if ((buffer.length - pos) >= len)\n return bufferSlice(buffer, pos, pos += len);\n },\n };\n\n return self;\n}\n\nfunction makeError(msg, level, fatal) {\n const err = new Error(msg);\n if (typeof level === 'boolean') {\n fatal = level;\n err.level = 'protocol';\n } else {\n err.level = level || 'protocol';\n }\n err.fatal = !!fatal;\n return err;\n}\n\nfunction writeUInt32BE(buf, value, offset) {\n buf[offset++] = (value >>> 24);\n buf[offset++] = (value >>> 16);\n buf[offset++] = (value >>> 8);\n buf[offset++] = value;\n return offset;\n}\n\nconst utilBufferParser = makeBufferParser();\n\nmodule.exports = {\n bufferCopy,\n bufferSlice,\n FastBuffer,\n bufferFill: (buf, value, start, end) => {\n return TypedArrayFill.call(buf, value, start, end);\n },\n makeError,\n doFatalError: (protocol, msg, level, reason) => {\n let err;\n if (DISCONNECT_REASON === undefined)\n ({ DISCONNECT_REASON } = require('./utils.js'));\n if (msg instanceof Error) {\n // doFatalError(protocol, err[, reason])\n err = msg;\n if (typeof level !== 'number')\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n else\n reason = level;\n } else {\n // doFatalError(protocol, msg[, level[, reason]])\n err = makeError(msg, level, true);\n }\n if (typeof reason !== 'number')\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n protocol.disconnect(reason);\n protocol._destruct();\n protocol._onError(err);\n return Infinity;\n },\n readUInt32BE,\n writeUInt32BE,\n writeUInt32LE: (buf, value, offset) => {\n buf[offset++] = value;\n buf[offset++] = (value >>> 8);\n buf[offset++] = (value >>> 16);\n buf[offset++] = (value >>> 24);\n return offset;\n },\n makeBufferParser,\n bufferParser: makeBufferParser(),\n readString: (buffer, start, dest, maxLen) => {\n if (typeof dest === 'number') {\n maxLen = dest;\n dest = undefined;\n }\n\n if (start === undefined)\n start = 0;\n\n const left = (buffer.length - start);\n if (start < 0 || start >= buffer.length || left < 4)\n return;\n\n const len = readUInt32BE(buffer, start);\n if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen))\n return;\n\n start += 4;\n const end = start + len;\n buffer._pos = end;\n\n if (dest) {\n if (Buffer.isBuffer(dest))\n return bufferCopy(buffer, dest, start, end);\n return buffer.utf8Slice(start, end);\n }\n return bufferSlice(buffer, start, end);\n },\n sigSSHToASN1: (sig, type) => {\n switch (type) {\n case 'ssh-dss': {\n if (sig.length > 40)\n return sig;\n // Change bare signature r and s values to ASN.1 BER values for OpenSSL\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n let r = sig.slice(0, 20);\n let s = sig.slice(20);\n if (r[0] & 0x80) {\n const rNew = Buffer.allocUnsafe(21);\n rNew[0] = 0x00;\n r.copy(rNew, 1);\n r = rNew;\n } else if (r[0] === 0x00 && !(r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] & 0x80) {\n const sNew = Buffer.allocUnsafe(21);\n sNew[0] = 0x00;\n s.copy(sNew, 1);\n s = sNew;\n } else if (s[0] === 0x00 && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n asnWriter.writeBuffer(r, Ber.Integer);\n asnWriter.writeBuffer(s, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521': {\n utilBufferParser.init(sig, 0);\n const r = utilBufferParser.readString();\n const s = utilBufferParser.readString();\n utilBufferParser.clear();\n if (r === undefined || s === undefined)\n return;\n\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeBuffer(r, Ber.Integer);\n asnWriter.writeBuffer(s, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n default:\n return sig;\n }\n },\n convertSignature: (signature, keyType) => {\n switch (keyType) {\n case 'ssh-dss': {\n if (signature.length <= 40)\n return signature;\n // This is a quick and dirty way to get from BER encoded r and s that\n // OpenSSL gives us, to just the bare values back to back (40 bytes\n // total) like OpenSSH (and possibly others) are expecting\n const asnReader = new Ber.Reader(signature);\n asnReader.readSequence();\n let r = asnReader.readString(Ber.Integer, true);\n let s = asnReader.readString(Ber.Integer, true);\n let rOffset = 0;\n let sOffset = 0;\n if (r.length < 20) {\n const rNew = Buffer.allocUnsafe(20);\n rNew.set(r, 1);\n r = rNew;\n r[0] = 0;\n }\n if (s.length < 20) {\n const sNew = Buffer.allocUnsafe(20);\n sNew.set(s, 1);\n s = sNew;\n s[0] = 0;\n }\n if (r.length > 20 && r[0] === 0)\n rOffset = 1;\n if (s.length > 20 && s[0] === 0)\n sOffset = 1;\n const newSig =\n Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset));\n bufferCopy(r, newSig, rOffset, r.length, 0);\n bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset);\n return newSig;\n }\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521': {\n if (signature[0] === 0)\n return signature;\n // Convert SSH signature parameters to ASN.1 BER values for OpenSSL\n const asnReader = new Ber.Reader(signature);\n asnReader.readSequence();\n const r = asnReader.readString(Ber.Integer, true);\n const s = asnReader.readString(Ber.Integer, true);\n if (r === null || s === null)\n return;\n const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length);\n writeUInt32BE(newSig, r.length, 0);\n newSig.set(r, 4);\n writeUInt32BE(newSig, s.length, 4 + r.length);\n newSig.set(s, 4 + 4 + r.length);\n return newSig;\n }\n }\n\n return signature;\n },\n sendPacket: (proto, packet, bypass) => {\n if (!bypass && proto._kexinit !== undefined) {\n // We're currently in the middle of a handshake\n\n if (proto._queue === undefined)\n proto._queue = [];\n proto._queue.push(packet);\n proto._debug && proto._debug('Outbound: ... packet queued');\n return false;\n }\n proto._cipher.encrypt(packet);\n return true;\n },\n};\n","'use strict';\n\nconst { kMaxLength } = require('buffer');\nconst {\n createInflate,\n constants: {\n DEFLATE,\n INFLATE,\n Z_DEFAULT_CHUNK,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_MEMLEVEL,\n Z_DEFAULT_STRATEGY,\n Z_DEFAULT_WINDOWBITS,\n Z_PARTIAL_FLUSH,\n }\n} = require('zlib');\nconst ZlibHandle = createInflate()._handle.constructor;\n\nfunction processCallback() {\n throw new Error('Should not get here');\n}\n\nfunction zlibOnError(message, errno, code) {\n const self = this._owner;\n // There is no way to cleanly recover.\n // Continuing only obscures problems.\n\n const error = new Error(message);\n error.errno = errno;\n error.code = code;\n self._err = error;\n}\n\nfunction _close(engine) {\n // Caller may invoke .close after a zlib error (which will null _handle).\n if (!engine._handle)\n return;\n\n engine._handle.close();\n engine._handle = null;\n}\n\nclass Zlib {\n constructor(mode) {\n const windowBits = Z_DEFAULT_WINDOWBITS;\n const level = Z_DEFAULT_COMPRESSION;\n const memLevel = Z_DEFAULT_MEMLEVEL;\n const strategy = Z_DEFAULT_STRATEGY;\n const dictionary = undefined;\n\n this._err = undefined;\n this._writeState = new Uint32Array(2);\n this._chunkSize = Z_DEFAULT_CHUNK;\n this._maxOutputLength = kMaxLength;\n this._outBuffer = Buffer.allocUnsafe(this._chunkSize);\n this._outOffset = 0;\n\n this._handle = new ZlibHandle(mode);\n this._handle._owner = this;\n this._handle.onerror = zlibOnError;\n this._handle.init(windowBits,\n level,\n memLevel,\n strategy,\n this._writeState,\n processCallback,\n dictionary);\n }\n\n writeSync(chunk, retChunks) {\n const handle = this._handle;\n if (!handle)\n throw new Error('Invalid Zlib instance');\n\n let availInBefore = chunk.length;\n let availOutBefore = this._chunkSize - this._outOffset;\n let inOff = 0;\n let availOutAfter;\n let availInAfter;\n\n let buffers;\n let nread = 0;\n const state = this._writeState;\n let buffer = this._outBuffer;\n let offset = this._outOffset;\n const chunkSize = this._chunkSize;\n\n while (true) {\n handle.writeSync(Z_PARTIAL_FLUSH,\n chunk, // in\n inOff, // in_off\n availInBefore, // in_len\n buffer, // out\n offset, // out_off\n availOutBefore); // out_len\n if (this._err)\n throw this._err;\n\n availOutAfter = state[0];\n availInAfter = state[1];\n\n const inDelta = availInBefore - availInAfter;\n const have = availOutBefore - availOutAfter;\n\n if (have > 0) {\n const out = (offset === 0 && have === buffer.length\n ? buffer\n : buffer.slice(offset, offset + have));\n offset += have;\n if (!buffers)\n buffers = out;\n else if (buffers.push === undefined)\n buffers = [buffers, out];\n else\n buffers.push(out);\n nread += out.byteLength;\n\n if (nread > this._maxOutputLength) {\n _close(this);\n throw new Error(\n `Output length exceeded maximum of ${this._maxOutputLength}`\n );\n }\n } else if (have !== 0) {\n throw new Error('have should not go down');\n }\n\n // Exhausted the output buffer, or used all the input create a new one.\n if (availOutAfter === 0 || offset >= chunkSize) {\n availOutBefore = chunkSize;\n offset = 0;\n buffer = Buffer.allocUnsafe(chunkSize);\n }\n\n if (availOutAfter === 0) {\n // Not actually done. Need to reprocess.\n // Also, update the availInBefore to the availInAfter value,\n // so that if we have to hit it a third (fourth, etc.) time,\n // it'll have the correct byte counts.\n inOff += inDelta;\n availInBefore = availInAfter;\n } else {\n break;\n }\n }\n\n this._outBuffer = buffer;\n this._outOffset = offset;\n\n if (nread === 0)\n buffers = Buffer.alloc(0);\n\n if (retChunks) {\n buffers.totalLen = nread;\n return buffers;\n }\n\n if (buffers.push === undefined)\n return buffers;\n\n const output = Buffer.allocUnsafe(nread);\n for (let i = 0, p = 0; i < buffers.length; ++i) {\n const buf = buffers[i];\n output.set(buf, p);\n p += buf.length;\n }\n return output;\n }\n}\n\nclass ZlibPacketWriter {\n constructor(protocol) {\n this.allocStart = 0;\n this.allocStartKEX = 0;\n this._protocol = protocol;\n this._zlib = new Zlib(DEFLATE);\n }\n\n cleanup() {\n if (this._zlib)\n _close(this._zlib);\n }\n\n alloc(payloadSize, force) {\n return Buffer.allocUnsafe(payloadSize);\n }\n\n finalize(payload, force) {\n if (this._protocol._kexinit === undefined || force) {\n const output = this._zlib.writeSync(payload, true);\n const packet = this._protocol._cipher.allocPacket(output.totalLen);\n if (output.push === undefined) {\n packet.set(output, 5);\n } else {\n for (let i = 0, p = 5; i < output.length; ++i) {\n const chunk = output[i];\n packet.set(chunk, p);\n p += chunk.length;\n }\n }\n return packet;\n }\n return payload;\n }\n}\n\nclass PacketWriter {\n constructor(protocol) {\n this.allocStart = 5;\n this.allocStartKEX = 5;\n this._protocol = protocol;\n }\n\n cleanup() {}\n\n alloc(payloadSize, force) {\n if (this._protocol._kexinit === undefined || force)\n return this._protocol._cipher.allocPacket(payloadSize);\n return Buffer.allocUnsafe(payloadSize);\n }\n\n finalize(packet, force) {\n return packet;\n }\n}\n\nclass ZlibPacketReader {\n constructor() {\n this._zlib = new Zlib(INFLATE);\n }\n\n cleanup() {\n if (this._zlib)\n _close(this._zlib);\n }\n\n read(data) {\n return this._zlib.writeSync(data, false);\n }\n}\n\nclass PacketReader {\n cleanup() {}\n\n read(data) {\n return data;\n }\n}\n\nmodule.exports = {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n};\n","// TODO:\n// * convert listenerCount() usage to emit() return value checking?\n// * emit error when connection severed early (e.g. before handshake)\n// * add '.connected' or similar property to connection objects to allow\n// immediate connection status checking\n'use strict';\n\nconst { Server: netServer } = require('net');\nconst EventEmitter = require('events');\nconst { listenerCount } = EventEmitter;\n\nconst {\n CHANNEL_OPEN_FAILURE,\n DEFAULT_CIPHER,\n DEFAULT_COMPRESSION,\n DEFAULT_KEX,\n DEFAULT_MAC,\n DEFAULT_SERVER_HOST_KEY,\n DISCONNECT_REASON,\n DISCONNECT_REASON_BY_VALUE,\n SUPPORTED_CIPHER,\n SUPPORTED_COMPRESSION,\n SUPPORTED_KEX,\n SUPPORTED_MAC,\n SUPPORTED_SERVER_HOST_KEY,\n} = require('./protocol/constants.js');\nconst { init: cryptoInit } = require('./protocol/crypto.js');\nconst { KexInit } = require('./protocol/kex.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst Protocol = require('./protocol/Protocol.js');\nconst { SFTP } = require('./protocol/SFTP.js');\nconst { writeUInt32BE } = require('./protocol/utils.js');\n\nconst {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n} = require('./Channel.js');\n\nconst {\n ChannelManager,\n generateAlgorithmList,\n isWritable,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n} = require('./utils.js');\n\nconst MAX_PENDING_AUTHS = 10;\n\nclass AuthContext extends EventEmitter {\n constructor(protocol, username, service, method, cb) {\n super();\n\n this.username = this.user = username;\n this.service = service;\n this.method = method;\n this._initialResponse = false;\n this._finalResponse = false;\n this._multistep = false;\n this._cbfinal = (allowed, methodsLeft, isPartial) => {\n if (!this._finalResponse) {\n this._finalResponse = true;\n cb(this, allowed, methodsLeft, isPartial);\n }\n };\n this._protocol = protocol;\n }\n\n accept() {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(true);\n }\n reject(methodsLeft, isPartial) {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(false, methodsLeft, isPartial);\n }\n}\n\n\nclass KeyboardAuthContext extends AuthContext {\n constructor(protocol, username, service, method, submethods, cb) {\n super(protocol, username, service, method, cb);\n\n this._multistep = true;\n\n this._cb = undefined;\n this._onInfoResponse = (responses) => {\n const callback = this._cb;\n if (callback) {\n this._cb = undefined;\n callback(responses);\n }\n };\n this.submethods = submethods;\n this.on('abort', () => {\n this._cb && this._cb(new Error('Authentication request aborted'));\n });\n }\n\n prompt(prompts, title, instructions, cb) {\n if (!Array.isArray(prompts))\n prompts = [ prompts ];\n\n if (typeof title === 'function') {\n cb = title;\n title = instructions = undefined;\n } else if (typeof instructions === 'function') {\n cb = instructions;\n instructions = undefined;\n } else if (typeof cb !== 'function') {\n cb = undefined;\n }\n\n for (let i = 0; i < prompts.length; ++i) {\n if (typeof prompts[i] === 'string') {\n prompts[i] = {\n prompt: prompts[i],\n echo: true\n };\n }\n }\n\n this._cb = cb;\n this._initialResponse = true;\n\n this._protocol.authInfoReq(title, instructions, prompts);\n }\n}\n\nclass PKAuthContext extends AuthContext {\n constructor(protocol, username, service, method, pkInfo, cb) {\n super(protocol, username, service, method, cb);\n\n this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };\n this.signature = pkInfo.signature;\n this.blob = pkInfo.blob;\n }\n\n accept() {\n if (!this.signature) {\n this._initialResponse = true;\n this._protocol.authPKOK(this.key.algo, this.key.data);\n } else {\n AuthContext.prototype.accept.call(this);\n }\n }\n}\n\nclass HostbasedAuthContext extends AuthContext {\n constructor(protocol, username, service, method, pkInfo, cb) {\n super(protocol, username, service, method, cb);\n\n this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };\n this.signature = pkInfo.signature;\n this.blob = pkInfo.blob;\n this.localHostname = pkInfo.localHostname;\n this.localUsername = pkInfo.localUsername;\n }\n}\n\nclass PwdAuthContext extends AuthContext {\n constructor(protocol, username, service, method, password, cb) {\n super(protocol, username, service, method, cb);\n\n this.password = password;\n this._changeCb = undefined;\n }\n\n requestChange(prompt, cb) {\n if (this._changeCb)\n throw new Error('Change request already in progress');\n if (typeof prompt !== 'string')\n throw new Error('prompt argument must be a string');\n if (typeof cb !== 'function')\n throw new Error('Callback argument must be a function');\n this._changeCb = cb;\n this._protocol.authPasswdChg(prompt);\n }\n}\n\n\nclass Session extends EventEmitter {\n constructor(client, info, localChan) {\n super();\n\n this.type = 'session';\n this.subtype = undefined;\n this.server = true;\n this._ending = false;\n this._channel = undefined;\n this._chanInfo = {\n type: 'session',\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n }\n}\n\n\nclass Server extends EventEmitter {\n constructor(cfg, listener) {\n super();\n\n if (typeof cfg !== 'object' || cfg === null)\n throw new Error('Missing configuration object');\n\n const hostKeys = Object.create(null);\n const hostKeyAlgoOrder = [];\n\n const hostKeys_ = cfg.hostKeys;\n if (!Array.isArray(hostKeys_))\n throw new Error('hostKeys must be an array');\n\n const cfgAlgos = (\n typeof cfg.algorithms === 'object' && cfg.algorithms !== null\n ? cfg.algorithms\n : {}\n );\n\n const hostKeyAlgos = generateAlgorithmList(\n cfgAlgos.serverHostKey,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY\n );\n for (let i = 0; i < hostKeys_.length; ++i) {\n let privateKey;\n if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string')\n privateKey = parseKey(hostKeys_[i]);\n else\n privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase);\n\n if (privateKey instanceof Error)\n throw new Error(`Cannot parse privateKey: ${privateKey.message}`);\n\n if (Array.isArray(privateKey)) {\n // OpenSSH's newer format only stores 1 key for now\n privateKey = privateKey[0];\n }\n\n if (privateKey.getPrivatePEM() === null)\n throw new Error('privateKey value contains an invalid private key');\n\n // Discard key if we already found a key of the same type\n if (hostKeyAlgoOrder.includes(privateKey.type))\n continue;\n\n if (privateKey.type === 'ssh-rsa') {\n // SSH supports multiple signature hashing algorithms for RSA, so we add\n // the algorithms in the desired order\n let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa');\n const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256');\n const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512');\n if (sha1Pos === -1) {\n // Fall back to giving SHA1 the lowest priority\n sha1Pos = Infinity;\n }\n [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => {\n if (pos === -1)\n return;\n\n let type;\n switch (pos) {\n case sha1Pos: type = 'ssh-rsa'; break;\n case sha256Pos: type = 'rsa-sha2-256'; break;\n case sha512Pos: type = 'rsa-sha2-512'; break;\n default: return;\n }\n\n // Store same RSA key under each hash algorithm name for convenience\n hostKeys[type] = privateKey;\n\n hostKeyAlgoOrder.push(type);\n });\n } else {\n hostKeys[privateKey.type] = privateKey;\n hostKeyAlgoOrder.push(privateKey.type);\n }\n }\n\n const algorithms = {\n kex: generateAlgorithmList(cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX),\n serverHostKey: hostKeyAlgoOrder,\n cs: {\n cipher: generateAlgorithmList(\n cfgAlgos.cipher,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER\n ),\n mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC),\n compress: generateAlgorithmList(\n cfgAlgos.compress,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION\n ),\n lang: [],\n },\n sc: undefined,\n };\n algorithms.sc = algorithms.cs;\n\n if (typeof listener === 'function')\n this.on('connection', listener);\n\n const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);\n const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined);\n const offer = new KexInit(algorithms);\n\n this._srv = new netServer((socket) => {\n if (this._connections >= this.maxConnections) {\n socket.destroy();\n return;\n }\n ++this._connections;\n socket.once('close', () => {\n --this._connections;\n });\n\n let debug;\n if (origDebug) {\n // Prepend debug output with a unique identifier in case there are\n // multiple clients connected at the same time\n const debugPrefix = `[${process.hrtime().join('.')}] `;\n debug = (msg) => {\n origDebug(`${debugPrefix}${msg}`);\n };\n }\n\n // eslint-disable-next-line no-use-before-define\n new Client(socket, hostKeys, ident, offer, debug, this, cfg);\n }).on('error', (err) => {\n this.emit('error', err);\n }).on('listening', () => {\n this.emit('listening');\n }).on('close', () => {\n this.emit('close');\n });\n this._connections = 0;\n this.maxConnections = Infinity;\n }\n\n injectSocket(socket) {\n this._srv.emit('connection', socket);\n }\n\n listen(...args) {\n this._srv.listen(...args);\n return this;\n }\n\n address() {\n return this._srv.address();\n }\n\n getConnections(cb) {\n this._srv.getConnections(cb);\n return this;\n }\n\n close(cb) {\n this._srv.close(cb);\n return this;\n }\n\n ref() {\n this._srv.ref();\n return this;\n }\n\n unref() {\n this._srv.unref();\n return this;\n }\n}\nServer.KEEPALIVE_CLIENT_INTERVAL = 15000;\nServer.KEEPALIVE_CLIENT_COUNT_MAX = 3;\n\n\nclass Client extends EventEmitter {\n constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) {\n super();\n\n let exchanges = 0;\n let acceptedAuthSvc = false;\n let pendingAuths = [];\n let authCtx;\n let kaTimer;\n let onPacket;\n const unsentGlobalRequestsReplies = [];\n this._sock = socket;\n this._chanMgr = new ChannelManager(this);\n this._debug = debug;\n this.noMoreSessions = false;\n this.authenticated = false;\n\n // Silence pre-header errors\n function onClientPreHeaderError(err) {}\n this.on('error', onClientPreHeaderError);\n\n const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {\n debug(`Debug output from client: ${JSON.stringify(msg)}`);\n });\n\n const kaIntvl = (\n typeof srvCfg.keepaliveInterval === 'number'\n && isFinite(srvCfg.keepaliveInterval)\n && srvCfg.keepaliveInterval > 0\n ? srvCfg.keepaliveInterval\n : (\n typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number'\n && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL)\n && Server.KEEPALIVE_CLIENT_INTERVAL > 0\n ? Server.KEEPALIVE_CLIENT_INTERVAL\n : -1\n )\n );\n const kaCountMax = (\n typeof srvCfg.keepaliveCountMax === 'number'\n && isFinite(srvCfg.keepaliveCountMax)\n && srvCfg.keepaliveCountMax >= 0\n ? srvCfg.keepaliveCountMax\n : (\n typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number'\n && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX)\n && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0\n ? Server.KEEPALIVE_CLIENT_COUNT_MAX\n : -1\n )\n );\n let kaCurCount = 0;\n if (kaIntvl !== -1 && kaCountMax !== -1) {\n this.once('ready', () => {\n const onClose = () => {\n clearInterval(kaTimer);\n };\n this.on('close', onClose).on('end', onClose);\n kaTimer = setInterval(() => {\n if (++kaCurCount > kaCountMax) {\n clearInterval(kaTimer);\n const err = new Error('Keepalive timeout');\n err.level = 'client-timeout';\n this.emit('error', err);\n this.end();\n } else {\n // XXX: if the server ever starts sending real global requests to\n // the client, we will need to add a dummy callback here to\n // keep the correct reply order\n proto.ping();\n }\n }, kaIntvl);\n });\n // TODO: re-verify keepalive behavior with OpenSSH\n onPacket = () => {\n kaTimer && kaTimer.refresh();\n kaCurCount = 0;\n };\n }\n\n const proto = this._protocol = new Protocol({\n server: true,\n hostKeys,\n ident,\n offer,\n onPacket,\n greeting: srvCfg.greeting,\n banner: srvCfg.banner,\n onWrite: (data) => {\n if (isWritable(socket))\n socket.write(data);\n },\n onError: (err) => {\n if (!proto._destruct)\n socket.removeAllListeners('data');\n this.emit('error', err);\n try {\n socket.end();\n } catch {}\n },\n onHeader: (header) => {\n this.removeListener('error', onClientPreHeaderError);\n\n const info = {\n ip: socket.remoteAddress,\n family: socket.remoteFamily,\n port: socket.remotePort,\n header,\n };\n if (!server.emit('connection', this, info)) {\n // auto reject\n proto.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n socket.end();\n return;\n }\n\n if (header.greeting)\n this.emit('greeting', header.greeting);\n },\n onHandshakeComplete: (negotiated) => {\n if (++exchanges > 1)\n this.emit('rekey');\n this.emit('handshake', negotiated);\n },\n debug,\n messageHandlers: {\n DEBUG: DEBUG_HANDLER,\n DISCONNECT: (p, reason, desc) => {\n if (reason !== DISCONNECT_REASON.BY_APPLICATION) {\n if (!desc) {\n desc = DISCONNECT_REASON_BY_VALUE[reason];\n if (desc === undefined)\n desc = `Unexpected disconnection reason: ${reason}`;\n }\n const err = new Error(desc);\n err.code = reason;\n this.emit('error', err);\n }\n socket.end();\n },\n CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from client\n\n // Do early reject in some cases to prevent wasteful channel\n // allocation\n if ((info.type === 'session' && this.noMoreSessions)\n || !this.authenticated) {\n const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n return proto.channelOpenFail(info.sender, reasonCode);\n }\n\n let localChan = -1;\n let reason;\n let replied = false;\n\n let accept;\n const reject = () => {\n if (replied)\n return;\n replied = true;\n\n if (reason === undefined) {\n if (localChan === -1)\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n else\n reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;\n }\n\n if (localChan !== -1)\n this._chanMgr.remove(localChan);\n proto.channelOpenFail(info.sender, reason, '');\n };\n const reserveChannel = () => {\n localChan = this._chanMgr.add();\n\n if (localChan === -1) {\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n if (debug) {\n debug('Automatic rejection of incoming channel open: '\n + 'no channels available');\n }\n }\n\n return (localChan !== -1);\n };\n\n const data = info.data;\n switch (info.type) {\n case 'session':\n if (listenerCount(this, 'session') && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const instance = new Session(this, info, localChan);\n this._chanMgr.update(localChan, instance);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return instance;\n };\n\n this.emit('session', accept, reject);\n return;\n }\n break;\n case 'direct-tcpip':\n if (listenerCount(this, 'tcpip') && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const chanInfo = {\n type: undefined,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const stream = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(localChan, stream);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return stream;\n };\n\n this.emit('tcpip', accept, reject, data);\n return;\n }\n break;\n case 'direct-streamlocal@openssh.com':\n if (listenerCount(this, 'openssh.streamlocal')\n && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const chanInfo = {\n type: undefined,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const stream = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(localChan, stream);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return stream;\n };\n\n this.emit('openssh.streamlocal', accept, reject, data);\n return;\n }\n break;\n default:\n // Automatically reject any unsupported channel open requests\n reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;\n if (debug) {\n debug('Automatic rejection of unsupported incoming channel open'\n + ` type: ${info.type}`);\n }\n }\n\n if (reason === undefined) {\n reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n if (debug) {\n debug('Automatic rejection of unexpected incoming channel open'\n + ` for: ${info.type}`);\n }\n }\n\n reject();\n },\n CHANNEL_OPEN_CONFIRMATION: (p, info) => {\n const channel = this._chanMgr.get(info.recipient);\n if (typeof channel !== 'function')\n return;\n\n const chanInfo = {\n type: channel.type,\n incoming: {\n id: info.recipient,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const instance = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(info.recipient, instance);\n channel(undefined, instance);\n },\n CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },\n CHANNEL_DATA: (p, recipient, data) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n // NOOP -- should not be sent by client\n },\n CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },\n CHANNEL_SUCCESS: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(false);\n },\n CHANNEL_FAILURE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },\n CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {\n const session = this._chanMgr.get(recipient);\n if (typeof session !== 'object' || session === null)\n return;\n\n let replied = false;\n let accept;\n let reject;\n\n if (session.constructor !== Session) {\n // normal Channel instance\n if (wantReply)\n proto.channelFailure(session.outgoing.id);\n return;\n }\n\n if (wantReply) {\n // \"real session\" requests will have custom accept behaviors\n if (type !== 'shell'\n && type !== 'exec'\n && type !== 'subsystem') {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n proto.channelSuccess(session._chanInfo.outgoing.id);\n };\n }\n\n reject = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n proto.channelFailure(session._chanInfo.outgoing.id);\n };\n }\n\n if (session._ending) {\n reject && reject();\n return;\n }\n\n switch (type) {\n // \"pre-real session start\" requests\n case 'env':\n if (listenerCount(session, 'env')) {\n session.emit('env', accept, reject, {\n key: data.name,\n val: data.value\n });\n return;\n }\n break;\n case 'pty-req':\n if (listenerCount(session, 'pty')) {\n session.emit('pty', accept, reject, data);\n return;\n }\n break;\n case 'window-change':\n if (listenerCount(session, 'window-change'))\n session.emit('window-change', accept, reject, data);\n else\n reject && reject();\n break;\n case 'x11-req':\n if (listenerCount(session, 'x11')) {\n session.emit('x11', accept, reject, data);\n return;\n }\n break;\n // \"post-real session start\" requests\n case 'signal':\n if (listenerCount(session, 'signal')) {\n session.emit('signal', accept, reject, {\n name: data\n });\n return;\n }\n break;\n // XXX: is `auth-agent-req@openssh.com` really \"post-real session\n // start\"?\n case 'auth-agent-req@openssh.com':\n if (listenerCount(session, 'auth-agent')) {\n session.emit('auth-agent', accept, reject);\n return;\n }\n break;\n // \"real session start\" requests\n case 'shell':\n if (listenerCount(session, 'shell')) {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n const channel = new Channel(\n this, session._chanInfo, { server: true }\n );\n\n channel.subtype = session.subtype = type;\n session._channel = channel;\n\n return channel;\n };\n\n session.emit('shell', accept, reject);\n return;\n }\n break;\n case 'exec':\n if (listenerCount(session, 'exec')) {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n const channel = new Channel(\n this, session._chanInfo, { server: true }\n );\n\n channel.subtype = session.subtype = type;\n session._channel = channel;\n\n return channel;\n };\n\n session.emit('exec', accept, reject, {\n command: data\n });\n return;\n }\n break;\n case 'subsystem': {\n let useSFTP = (data === 'sftp');\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n let instance;\n if (useSFTP) {\n instance = new SFTP(this, session._chanInfo, {\n server: true,\n debug,\n });\n } else {\n instance = new Channel(\n this, session._chanInfo, { server: true }\n );\n instance.subtype =\n session.subtype = `${type}:${data}`;\n }\n session._channel = instance;\n\n return instance;\n };\n\n if (data === 'sftp') {\n if (listenerCount(session, 'sftp')) {\n session.emit('sftp', accept, reject);\n return;\n }\n useSFTP = false;\n }\n if (listenerCount(session, 'subsystem')) {\n session.emit('subsystem', accept, reject, {\n name: data\n });\n return;\n }\n break;\n }\n }\n debug && debug(\n `Automatic rejection of incoming channel request: ${type}`\n );\n reject && reject();\n },\n CHANNEL_EOF: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n if (!channel._ending) {\n channel._ending = true;\n channel.emit('eof');\n channel.emit('end');\n }\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel.incoming.state !== 'open')\n return;\n channel.incoming.state = 'eof';\n\n if (channel.readable)\n channel.push(null);\n },\n CHANNEL_CLOSE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel._ending = true;\n channel.emit('close');\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n onCHANNEL_CLOSE(this, recipient, channel);\n },\n // Begin service/auth-related ==========================================\n SERVICE_REQUEST: (p, service) => {\n if (exchanges === 0\n || acceptedAuthSvc\n || this.authenticated\n || service !== 'ssh-userauth') {\n proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);\n socket.end();\n return;\n }\n\n acceptedAuthSvc = true;\n proto.serviceAccept(service);\n },\n USERAUTH_REQUEST: (p, username, service, method, methodData) => {\n if (exchanges === 0\n || this.authenticated\n || (authCtx\n && (authCtx.username !== username\n || authCtx.service !== service))\n // TODO: support hostbased auth\n || (method !== 'password'\n && method !== 'publickey'\n && method !== 'hostbased'\n && method !== 'keyboard-interactive'\n && method !== 'none')\n || pendingAuths.length === MAX_PENDING_AUTHS) {\n proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR);\n socket.end();\n return;\n } else if (service !== 'ssh-connection') {\n proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);\n socket.end();\n return;\n }\n\n let ctx;\n switch (method) {\n case 'keyboard-interactive':\n ctx = new KeyboardAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'publickey':\n ctx = new PKAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'hostbased':\n ctx = new HostbasedAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'password':\n if (authCtx\n && authCtx instanceof PwdAuthContext\n && authCtx._changeCb) {\n const cb = authCtx._changeCb;\n authCtx._changeCb = undefined;\n cb(methodData.newPassword);\n return;\n }\n ctx = new PwdAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'none':\n ctx = new AuthContext(proto, username, service, method,\n onAuthDecide);\n break;\n }\n\n if (authCtx) {\n if (!authCtx._initialResponse) {\n return pendingAuths.push(ctx);\n } else if (authCtx._multistep && !authCtx._finalResponse) {\n // RFC 4252 says to silently abort the current auth request if a\n // new auth request comes in before the final response from an\n // auth method that requires additional request/response exchanges\n // -- this means keyboard-interactive for now ...\n authCtx._cleanup && authCtx._cleanup();\n authCtx.emit('abort');\n }\n }\n\n authCtx = ctx;\n\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n },\n USERAUTH_INFO_RESPONSE: (p, responses) => {\n if (authCtx && authCtx instanceof KeyboardAuthContext)\n authCtx._onInfoResponse(responses);\n },\n // End service/auth-related ============================================\n GLOBAL_REQUEST: (p, name, wantReply, data) => {\n const reply = {\n type: null,\n buf: null\n };\n\n function setReply(type, buf) {\n reply.type = type;\n reply.buf = buf;\n sendReplies();\n }\n\n if (wantReply)\n unsentGlobalRequestsReplies.push(reply);\n\n if ((name === 'tcpip-forward'\n || name === 'cancel-tcpip-forward'\n || name === 'no-more-sessions@openssh.com'\n || name === 'streamlocal-forward@openssh.com'\n || name === 'cancel-streamlocal-forward@openssh.com')\n && listenerCount(this, 'request')\n && this.authenticated) {\n let accept;\n let reject;\n\n if (wantReply) {\n let replied = false;\n accept = (chosenPort) => {\n if (replied)\n return;\n replied = true;\n let bufPort;\n if (name === 'tcpip-forward'\n && data.bindPort === 0\n && typeof chosenPort === 'number') {\n bufPort = Buffer.allocUnsafe(4);\n writeUInt32BE(bufPort, chosenPort, 0);\n }\n setReply('SUCCESS', bufPort);\n };\n reject = () => {\n if (replied)\n return;\n replied = true;\n setReply('FAILURE');\n };\n }\n\n if (name === 'no-more-sessions@openssh.com') {\n this.noMoreSessions = true;\n accept && accept();\n return;\n }\n\n this.emit('request', accept, reject, name, data);\n } else if (wantReply) {\n setReply('FAILURE');\n }\n },\n },\n });\n\n socket.pause();\n cryptoInit.then(() => {\n proto.start();\n socket.on('data', (data) => {\n try {\n proto.parse(data, 0, data.length);\n } catch (ex) {\n this.emit('error', ex);\n try {\n if (isWritable(socket))\n socket.end();\n } catch {}\n }\n });\n socket.resume();\n }).catch((err) => {\n this.emit('error', err);\n try {\n if (isWritable(socket))\n socket.end();\n } catch {}\n });\n socket.on('error', (err) => {\n err.level = 'socket';\n this.emit('error', err);\n }).once('end', () => {\n debug && debug('Socket ended');\n proto.cleanup();\n this.emit('end');\n }).once('close', () => {\n debug && debug('Socket closed');\n proto.cleanup();\n this.emit('close');\n\n const err = new Error('No response from server');\n\n // Simulate error for pending channels and close any open channels\n this._chanMgr.cleanup(err);\n });\n\n const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => {\n if (authCtx === ctx && !this.authenticated) {\n if (allowed) {\n authCtx = undefined;\n this.authenticated = true;\n proto.authSuccess();\n pendingAuths = [];\n this.emit('ready');\n } else {\n proto.authFailure(methodsLeft, isPartial);\n if (pendingAuths.length) {\n authCtx = pendingAuths.pop();\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n }\n }\n }\n };\n\n function sendReplies() {\n while (unsentGlobalRequestsReplies.length > 0\n && unsentGlobalRequestsReplies[0].type) {\n const reply = unsentGlobalRequestsReplies.shift();\n if (reply.type === 'SUCCESS')\n proto.requestSuccess(reply.buf);\n if (reply.type === 'FAILURE')\n proto.requestFailure();\n }\n }\n }\n\n end() {\n if (this._sock && isWritable(this._sock)) {\n this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n this._sock.end();\n }\n return this;\n }\n\n x11(originAddr, originPort, cb) {\n const opts = { originAddr, originPort };\n openChannel(this, 'x11', opts, cb);\n return this;\n }\n\n forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) {\n const opts = { boundAddr, boundPort, remoteAddr, remotePort };\n openChannel(this, 'forwarded-tcpip', opts, cb);\n return this;\n }\n\n openssh_forwardOutStreamLocal(socketPath, cb) {\n const opts = { socketPath };\n openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb);\n return this;\n }\n\n rekey(cb) {\n let error;\n\n try {\n this._protocol.rekey();\n } catch (ex) {\n error = ex;\n }\n\n // TODO: re-throw error if no callback?\n\n if (typeof cb === 'function') {\n if (error)\n process.nextTick(cb, error);\n else\n this.once('rekey', cb);\n }\n }\n}\n\n\nfunction openChannel(self, type, opts, cb) {\n // Ask the client to open a channel for some purpose (e.g. a forwarded TCP\n // connection)\n const initWindow = MAX_WINDOW;\n const maxPacket = PACKET_SIZE;\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const wrapper = (err, stream) => {\n cb(err, stream);\n };\n wrapper.type = type;\n\n const localChan = self._chanMgr.add(wrapper);\n\n if (localChan === -1) {\n cb(new Error('No free channels available'));\n return;\n }\n\n switch (type) {\n case 'forwarded-tcpip':\n self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts);\n break;\n case 'x11':\n self._protocol.x11(localChan, initWindow, maxPacket, opts);\n break;\n case 'forwarded-streamlocal@openssh.com':\n self._protocol.openssh_forwardedStreamLocal(\n localChan, initWindow, maxPacket, opts\n );\n break;\n default:\n throw new Error(`Unsupported channel type: ${type}`);\n }\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nmodule.exports = Server;\nmodule.exports.IncomingClient = Client;\n","'use strict';\n\nconst { SFTP } = require('./protocol/SFTP.js');\n\nconst MAX_CHANNEL = 2 ** 32 - 1;\n\nfunction onChannelOpenFailure(self, recipient, info, cb) {\n self._chanMgr.remove(recipient);\n if (typeof cb !== 'function')\n return;\n\n let err;\n if (info instanceof Error) {\n err = info;\n } else if (typeof info === 'object' && info !== null) {\n err = new Error(`(SSH) Channel open failure: ${info.description}`);\n err.reason = info.reason;\n } else {\n err = new Error(\n '(SSH) Channel open failure: server closed channel unexpectedly'\n );\n err.reason = '';\n }\n\n cb(err);\n}\n\nfunction onCHANNEL_CLOSE(self, recipient, channel, err, dead) {\n if (typeof channel === 'function') {\n // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when\n // requesting to open a channel\n onChannelOpenFailure(self, recipient, err, channel);\n return;\n }\n\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.incoming && channel.incoming.state === 'closed')\n return;\n\n self._chanMgr.remove(recipient);\n\n if (channel.server && channel.constructor.name === 'Session')\n return;\n\n channel.incoming.state = 'closed';\n\n if (channel.readable)\n channel.push(null);\n if (channel.server) {\n if (channel.stderr.writable)\n channel.stderr.end();\n } else if (channel.stderr.readable) {\n channel.stderr.push(null);\n }\n\n if (channel.constructor !== SFTP\n && (channel.outgoing.state === 'open'\n || channel.outgoing.state === 'eof')\n && !dead) {\n channel.close();\n }\n if (channel.outgoing.state === 'closing')\n channel.outgoing.state = 'closed';\n\n const readState = channel._readableState;\n const writeState = channel._writableState;\n if (writeState && !writeState.ending && !writeState.finished && !dead)\n channel.end();\n\n // Take care of any outstanding channel requests\n const chanCallbacks = channel._callbacks;\n channel._callbacks = [];\n for (let i = 0; i < chanCallbacks.length; ++i)\n chanCallbacks[i](true);\n\n if (channel.server) {\n if (!channel.readable\n || channel.destroyed\n || (readState && readState.endEmitted)) {\n channel.emit('close');\n } else {\n channel.once('end', () => channel.emit('close'));\n }\n } else {\n let doClose;\n switch (channel.type) {\n case 'direct-streamlocal@openssh.com':\n case 'direct-tcpip':\n doClose = () => channel.emit('close');\n break;\n default: {\n // Align more with node child processes, where the close event gets\n // the same arguments as the exit event\n const exit = channel._exit;\n doClose = () => {\n if (exit.code === null)\n channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc);\n else\n channel.emit('close', exit.code);\n };\n }\n }\n if (!channel.readable\n || channel.destroyed\n || (readState && readState.endEmitted)) {\n doClose();\n } else {\n channel.once('end', doClose);\n }\n\n const errReadState = channel.stderr._readableState;\n if (!channel.stderr.readable\n || channel.stderr.destroyed\n || (errReadState && errReadState.endEmitted)) {\n channel.stderr.emit('close');\n } else {\n channel.stderr.once('end', () => channel.stderr.emit('close'));\n }\n }\n}\n\nclass ChannelManager {\n constructor(client) {\n this._client = client;\n this._channels = {};\n this._cur = -1;\n this._count = 0;\n }\n add(val) {\n // Attempt to reserve an id\n\n let id;\n // Optimized paths\n if (this._cur < MAX_CHANNEL) {\n id = ++this._cur;\n } else if (this._count === 0) {\n // Revert and reset back to fast path once we no longer have any channels\n // open\n this._cur = 0;\n id = 0;\n } else {\n // Slower lookup path\n\n // This path is triggered we have opened at least MAX_CHANNEL channels\n // while having at least one channel open at any given time, so we have\n // to search for a free id.\n const channels = this._channels;\n for (let i = 0; i < MAX_CHANNEL; ++i) {\n if (channels[i] === undefined) {\n id = i;\n break;\n }\n }\n }\n\n if (id === undefined)\n return -1;\n\n this._channels[id] = (val || true);\n ++this._count;\n\n return id;\n }\n update(id, val) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n if (val && this._channels[id])\n this._channels[id] = val;\n }\n get(id) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n return this._channels[id];\n }\n remove(id) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n if (this._channels[id]) {\n delete this._channels[id];\n if (this._count)\n --this._count;\n }\n }\n cleanup(err) {\n const channels = this._channels;\n this._channels = {};\n this._cur = -1;\n this._count = 0;\n\n const chanIDs = Object.keys(channels);\n const client = this._client;\n for (let i = 0; i < chanIDs.length; ++i) {\n const id = +chanIDs[i];\n const channel = channels[id];\n onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true);\n }\n }\n}\n\nconst isRegExp = (() => {\n const toString = Object.prototype.toString;\n return (val) => toString.call(val) === '[object RegExp]';\n})();\n\nfunction generateAlgorithmList(algoList, defaultList, supportedList) {\n if (Array.isArray(algoList) && algoList.length > 0) {\n // Exact list\n for (let i = 0; i < algoList.length; ++i) {\n if (supportedList.indexOf(algoList[i]) === -1)\n throw new Error(`Unsupported algorithm: ${algoList[i]}`);\n }\n return algoList;\n }\n\n if (typeof algoList === 'object' && algoList !== null) {\n // Operations based on the default list\n const keys = Object.keys(algoList);\n let list = defaultList;\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n let val = algoList[key];\n switch (key) {\n case 'append':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = 0; j < val.length; ++j) {\n const append = val[j];\n if (typeof append === 'string') {\n if (!append || list.indexOf(append) !== -1)\n continue;\n if (supportedList.indexOf(append) === -1)\n throw new Error(`Unsupported algorithm: ${append}`);\n if (list === defaultList)\n list = list.slice();\n list.push(append);\n } else if (isRegExp(append)) {\n for (let k = 0; k < supportedList.length; ++k) {\n const algo = supportedList[k];\n if (append.test(algo)) {\n if (list.indexOf(algo) !== -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.push(algo);\n }\n }\n }\n }\n }\n break;\n case 'prepend':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = val.length; j >= 0; --j) {\n const prepend = val[j];\n if (typeof prepend === 'string') {\n if (!prepend || list.indexOf(prepend) !== -1)\n continue;\n if (supportedList.indexOf(prepend) === -1)\n throw new Error(`Unsupported algorithm: ${prepend}`);\n if (list === defaultList)\n list = list.slice();\n list.unshift(prepend);\n } else if (isRegExp(prepend)) {\n for (let k = supportedList.length; k >= 0; --k) {\n const algo = supportedList[k];\n if (prepend.test(algo)) {\n if (list.indexOf(algo) !== -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.unshift(algo);\n }\n }\n }\n }\n }\n break;\n case 'remove':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = 0; j < val.length; ++j) {\n const search = val[j];\n if (typeof search === 'string') {\n if (!search)\n continue;\n const idx = list.indexOf(search);\n if (idx === -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.splice(idx, 1);\n } else if (isRegExp(search)) {\n for (let k = 0; k < list.length; ++k) {\n if (search.test(list[k])) {\n if (list === defaultList)\n list = list.slice();\n list.splice(k, 1);\n --k;\n }\n }\n }\n }\n }\n break;\n }\n }\n\n return list;\n }\n\n return defaultList;\n}\n\nmodule.exports = {\n ChannelManager,\n generateAlgorithmList,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n isWritable: (stream) => {\n // XXX: hack to workaround regression in node\n // See: https://github.com/nodejs/node/issues/36029\n return (stream\n && stream.writable\n && stream._readableState\n && stream._readableState.ended === false);\n },\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","var chownr = require('chownr')\nvar tar = require('tar-stream')\nvar pump = require('pump')\nvar mkdirp = require('mkdirp-classic')\nvar fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\nvar win32 = os.platform() === 'win32'\n\nvar noop = function () {}\n\nvar echo = function (name) {\n return name\n}\n\nvar normalize = !win32 ? echo : function (name) {\n return name.replace(/\\\\/g, '/').replace(/[:?<>|]/g, '_')\n}\n\nvar statAll = function (fs, stat, cwd, ignore, entries, sort) {\n var queue = entries || ['.']\n\n return function loop (callback) {\n if (!queue.length) return callback()\n var next = queue.shift()\n var nextAbs = path.join(cwd, next)\n\n stat(nextAbs, function (err, stat) {\n if (err) return callback(err)\n\n if (!stat.isDirectory()) return callback(null, next, stat)\n\n fs.readdir(nextAbs, function (err, files) {\n if (err) return callback(err)\n\n if (sort) files.sort()\n for (var i = 0; i < files.length; i++) {\n if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))\n }\n\n callback(null, next, stat)\n })\n })\n }\n}\n\nvar strip = function (map, level) {\n return function (header) {\n header.name = header.name.split('/').slice(level).join('/')\n\n var linkname = header.linkname\n if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {\n header.linkname = linkname.split('/').slice(level).join('/')\n }\n\n return map(header)\n }\n}\n\nexports.pack = function (cwd, opts) {\n if (!cwd) cwd = '.'\n if (!opts) opts = {}\n\n var xfs = opts.fs || fs\n var ignore = opts.ignore || opts.filter || noop\n var map = opts.map || noop\n var mapStream = opts.mapStream || echo\n var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)\n var strict = opts.strict !== false\n var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()\n var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0\n var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0\n var pack = opts.pack || tar.pack()\n var finish = opts.finish || noop\n\n if (opts.strip) map = strip(map, opts.strip)\n\n if (opts.readable) {\n dmode |= parseInt(555, 8)\n fmode |= parseInt(444, 8)\n }\n if (opts.writable) {\n dmode |= parseInt(333, 8)\n fmode |= parseInt(222, 8)\n }\n\n var onsymlink = function (filename, header) {\n xfs.readlink(path.join(cwd, filename), function (err, linkname) {\n if (err) return pack.destroy(err)\n header.linkname = normalize(linkname)\n pack.entry(header, onnextentry)\n })\n }\n\n var onstat = function (err, filename, stat) {\n if (err) return pack.destroy(err)\n if (!filename) {\n if (opts.finalize !== false) pack.finalize()\n return finish(pack)\n }\n\n if (stat.isSocket()) return onnextentry() // tar does not support sockets...\n\n var header = {\n name: normalize(filename),\n mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,\n mtime: stat.mtime,\n size: stat.size,\n type: 'file',\n uid: stat.uid,\n gid: stat.gid\n }\n\n if (stat.isDirectory()) {\n header.size = 0\n header.type = 'directory'\n header = map(header) || header\n return pack.entry(header, onnextentry)\n }\n\n if (stat.isSymbolicLink()) {\n header.size = 0\n header.type = 'symlink'\n header = map(header) || header\n return onsymlink(filename, header)\n }\n\n // TODO: add fifo etc...\n\n header = map(header) || header\n\n if (!stat.isFile()) {\n if (strict) return pack.destroy(new Error('unsupported type for ' + filename))\n return onnextentry()\n }\n\n var entry = pack.entry(header, onnextentry)\n if (!entry) return\n\n var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)\n\n rs.on('error', function (err) { // always forward errors on destroy\n entry.destroy(err)\n })\n\n pump(rs, entry)\n }\n\n var onnextentry = function (err) {\n if (err) return pack.destroy(err)\n statNext(onstat)\n }\n\n onnextentry()\n\n return pack\n}\n\nvar head = function (list) {\n return list.length ? list[list.length - 1] : null\n}\n\nvar processGetuid = function () {\n return process.getuid ? process.getuid() : -1\n}\n\nvar processUmask = function () {\n return process.umask ? process.umask() : 0\n}\n\nexports.extract = function (cwd, opts) {\n if (!cwd) cwd = '.'\n if (!opts) opts = {}\n\n var xfs = opts.fs || fs\n var ignore = opts.ignore || opts.filter || noop\n var map = opts.map || noop\n var mapStream = opts.mapStream || echo\n var own = opts.chown !== false && !win32 && processGetuid() === 0\n var extract = opts.extract || tar.extract()\n var stack = []\n var now = new Date()\n var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()\n var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0\n var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0\n var strict = opts.strict !== false\n\n if (opts.strip) map = strip(map, opts.strip)\n\n if (opts.readable) {\n dmode |= parseInt(555, 8)\n fmode |= parseInt(444, 8)\n }\n if (opts.writable) {\n dmode |= parseInt(333, 8)\n fmode |= parseInt(222, 8)\n }\n\n var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry\n var top\n while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()\n if (!top) return cb()\n xfs.utimes(top[0], now, top[1], cb)\n }\n\n var utimes = function (name, header, cb) {\n if (opts.utimes === false) return cb()\n\n if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)\n if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?\n\n xfs.utimes(name, now, header.mtime, function (err) {\n if (err) return cb(err)\n utimesParent(name, cb)\n })\n }\n\n var chperm = function (name, header, cb) {\n var link = header.type === 'symlink'\n\n /* eslint-disable node/no-deprecated-api */\n var chmod = link ? xfs.lchmod : xfs.chmod\n var chown = link ? xfs.lchown : xfs.chown\n /* eslint-enable node/no-deprecated-api */\n\n if (!chmod) return cb()\n\n var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask\n chmod(name, mode, function (err) {\n if (err) return cb(err)\n if (!own) return cb()\n if (!chown) return cb()\n chown(name, header.uid, header.gid, cb)\n })\n }\n\n extract.on('entry', function (header, stream, next) {\n header = map(header) || header\n header.name = normalize(header.name)\n var name = path.join(cwd, path.join('/', header.name))\n\n if (ignore(name, header)) {\n stream.resume()\n return next()\n }\n\n var stat = function (err) {\n if (err) return next(err)\n utimes(name, header, function (err) {\n if (err) return next(err)\n if (win32) return next()\n chperm(name, header, next)\n })\n }\n\n var onsymlink = function () {\n if (win32) return next() // skip symlinks on win for now before it can be tested\n xfs.unlink(name, function () {\n xfs.symlink(header.linkname, name, stat)\n })\n }\n\n var onlink = function () {\n if (win32) return next() // skip links on win for now before it can be tested\n xfs.unlink(name, function () {\n var srcpath = path.join(cwd, path.join('/', header.linkname))\n\n xfs.link(srcpath, name, function (err) {\n if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {\n stream = xfs.createReadStream(srcpath)\n return onfile()\n }\n\n stat(err)\n })\n })\n }\n\n var onfile = function () {\n var ws = xfs.createWriteStream(name)\n var rs = mapStream(stream, header)\n\n ws.on('error', function (err) { // always forward errors on destroy\n rs.destroy(err)\n })\n\n pump(rs, ws, function (err) {\n if (err) return next(err)\n ws.on('close', stat)\n })\n }\n\n if (header.type === 'directory') {\n stack.push([name, header.mtime])\n return mkdirfix(name, {\n fs: xfs, own: own, uid: header.uid, gid: header.gid\n }, stat)\n }\n\n var dir = path.dirname(name)\n\n validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {\n if (err) return next(err)\n if (!valid) return next(new Error(dir + ' is not a valid path'))\n\n mkdirfix(dir, {\n fs: xfs, own: own, uid: header.uid, gid: header.gid\n }, function (err) {\n if (err) return next(err)\n\n switch (header.type) {\n case 'file': return onfile()\n case 'link': return onlink()\n case 'symlink': return onsymlink()\n }\n\n if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))\n\n stream.resume()\n next()\n })\n })\n })\n\n if (opts.finish) extract.on('finish', opts.finish)\n\n return extract\n}\n\nfunction validate (fs, name, root, cb) {\n if (name === root) return cb(null, true)\n fs.lstat(name, function (err, st) {\n if (err && err.code !== 'ENOENT') return cb(err)\n if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)\n cb(null, false)\n })\n}\n\nfunction mkdirfix (name, opts, cb) {\n mkdirp(name, { fs: opts.fs }, function (err, made) {\n if (!err && made && opts.own) {\n chownr(made, opts.uid, opts.gid, cb)\n } else {\n cb(err)\n }\n })\n}\n","var util = require('util')\nvar bl = require('bl')\nvar headers = require('./headers')\n\nvar Writable = require('readable-stream').Writable\nvar PassThrough = require('readable-stream').PassThrough\n\nvar noop = function () {}\n\nvar overflow = function (size) {\n size &= 511\n return size && 512 - size\n}\n\nvar emptyStream = function (self, offset) {\n var s = new Source(self, offset)\n s.end()\n return s\n}\n\nvar mixinPax = function (header, pax) {\n if (pax.path) header.name = pax.path\n if (pax.linkpath) header.linkname = pax.linkpath\n if (pax.size) header.size = parseInt(pax.size, 10)\n header.pax = pax\n return header\n}\n\nvar Source = function (self, offset) {\n this._parent = self\n this.offset = offset\n PassThrough.call(this, { autoDestroy: false })\n}\n\nutil.inherits(Source, PassThrough)\n\nSource.prototype.destroy = function (err) {\n this._parent.destroy(err)\n}\n\nvar Extract = function (opts) {\n if (!(this instanceof Extract)) return new Extract(opts)\n Writable.call(this, opts)\n\n opts = opts || {}\n\n this._offset = 0\n this._buffer = bl()\n this._missing = 0\n this._partial = false\n this._onparse = noop\n this._header = null\n this._stream = null\n this._overflow = null\n this._cb = null\n this._locked = false\n this._destroyed = false\n this._pax = null\n this._paxGlobal = null\n this._gnuLongPath = null\n this._gnuLongLinkPath = null\n\n var self = this\n var b = self._buffer\n\n var oncontinue = function () {\n self._continue()\n }\n\n var onunlock = function (err) {\n self._locked = false\n if (err) return self.destroy(err)\n if (!self._stream) oncontinue()\n }\n\n var onstreamend = function () {\n self._stream = null\n var drain = overflow(self._header.size)\n if (drain) self._parse(drain, ondrain)\n else self._parse(512, onheader)\n if (!self._locked) oncontinue()\n }\n\n var ondrain = function () {\n self._buffer.consume(overflow(self._header.size))\n self._parse(512, onheader)\n oncontinue()\n }\n\n var onpaxglobalheader = function () {\n var size = self._header.size\n self._paxGlobal = headers.decodePax(b.slice(0, size))\n b.consume(size)\n onstreamend()\n }\n\n var onpaxheader = function () {\n var size = self._header.size\n self._pax = headers.decodePax(b.slice(0, size))\n if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulongpath = function () {\n var size = self._header.size\n this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulonglinkpath = function () {\n var size = self._header.size\n this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var onheader = function () {\n var offset = self._offset\n var header\n try {\n header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat)\n } catch (err) {\n self.emit('error', err)\n }\n b.consume(512)\n\n if (!header) {\n self._parse(512, onheader)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-path') {\n self._parse(header.size, ongnulongpath)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-link-path') {\n self._parse(header.size, ongnulonglinkpath)\n oncontinue()\n return\n }\n if (header.type === 'pax-global-header') {\n self._parse(header.size, onpaxglobalheader)\n oncontinue()\n return\n }\n if (header.type === 'pax-header') {\n self._parse(header.size, onpaxheader)\n oncontinue()\n return\n }\n\n if (self._gnuLongPath) {\n header.name = self._gnuLongPath\n self._gnuLongPath = null\n }\n\n if (self._gnuLongLinkPath) {\n header.linkname = self._gnuLongLinkPath\n self._gnuLongLinkPath = null\n }\n\n if (self._pax) {\n self._header = header = mixinPax(header, self._pax)\n self._pax = null\n }\n\n self._locked = true\n\n if (!header.size || header.type === 'directory') {\n self._parse(512, onheader)\n self.emit('entry', header, emptyStream(self, offset), onunlock)\n return\n }\n\n self._stream = new Source(self, offset)\n\n self.emit('entry', header, self._stream, onunlock)\n self._parse(header.size, onstreamend)\n oncontinue()\n }\n\n this._onheader = onheader\n this._parse(512, onheader)\n}\n\nutil.inherits(Extract, Writable)\n\nExtract.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream) this._stream.emit('close')\n}\n\nExtract.prototype._parse = function (size, onparse) {\n if (this._destroyed) return\n this._offset += size\n this._missing = size\n if (onparse === this._onheader) this._partial = false\n this._onparse = onparse\n}\n\nExtract.prototype._continue = function () {\n if (this._destroyed) return\n var cb = this._cb\n this._cb = noop\n if (this._overflow) this._write(this._overflow, undefined, cb)\n else cb()\n}\n\nExtract.prototype._write = function (data, enc, cb) {\n if (this._destroyed) return\n\n var s = this._stream\n var b = this._buffer\n var missing = this._missing\n if (data.length) this._partial = true\n\n // we do not reach end-of-chunk now. just forward it\n\n if (data.length < missing) {\n this._missing -= data.length\n this._overflow = null\n if (s) return s.write(data, cb)\n b.append(data)\n return cb()\n }\n\n // end-of-chunk. the parser should call cb.\n\n this._cb = cb\n this._missing = 0\n\n var overflow = null\n if (data.length > missing) {\n overflow = data.slice(missing)\n data = data.slice(0, missing)\n }\n\n if (s) s.end(data)\n else b.append(data)\n\n this._overflow = overflow\n this._onparse()\n}\n\nExtract.prototype._final = function (cb) {\n if (this._partial) return this.destroy(new Error('Unexpected end of data'))\n cb()\n}\n\nmodule.exports = Extract\n","var alloc = Buffer.alloc\n\nvar ZEROS = '0000000000000000000'\nvar SEVENS = '7777777777777777777'\nvar ZERO_OFFSET = '0'.charCodeAt(0)\nvar USTAR_MAGIC = Buffer.from('ustar\\x00', 'binary')\nvar USTAR_VER = Buffer.from('00', 'binary')\nvar GNU_MAGIC = Buffer.from('ustar\\x20', 'binary')\nvar GNU_VER = Buffer.from('\\x20\\x00', 'binary')\nvar MASK = parseInt('7777', 8)\nvar MAGIC_OFFSET = 257\nvar VERSION_OFFSET = 263\n\nvar clamp = function (index, len, defaultValue) {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nvar toType = function (flag) {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n }\n\n return null\n}\n\nvar toTypeflag = function (flag) {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n }\n\n return 0\n}\n\nvar indexOf = function (block, num, offset, end) {\n for (; offset < end; offset++) {\n if (block[offset] === num) return offset\n }\n return end\n}\n\nvar cksum = function (block) {\n var sum = 8 * 32\n for (var i = 0; i < 148; i++) sum += block[i]\n for (var j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nvar encodeOct = function (val, n) {\n val = val.toString(8)\n if (val.length > n) return SEVENS.slice(0, n) + ' '\n else return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n var positive\n if (buf[0] === 0x80) positive = true\n else if (buf[0] === 0xFF) positive = false\n else return null\n\n // build up a base-256 tuple from the least sig to the highest\n var tuple = []\n for (var i = buf.length - 1; i > 0; i--) {\n var byte = buf[i]\n if (positive) tuple.push(byte)\n else tuple.push(0xFF - byte)\n }\n\n var sum = 0\n var l = tuple.length\n for (i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nvar decodeOct = function (val, offset, length) {\n val = val.slice(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if (val[offset] & 0x80) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val[offset] === 32) offset++\n var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n while (offset < end && val[offset] === 0) offset++\n if (end === offset) return 0\n return parseInt(val.slice(offset, end).toString(), 8)\n }\n}\n\nvar decodeStr = function (val, offset, length, encoding) {\n return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding)\n}\n\nvar addLength = function (str) {\n var len = Buffer.byteLength(str)\n var digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n if (len + digits >= Math.pow(10, digits)) digits++\n\n return (len + digits) + str\n}\n\nexports.decodeLongPath = function (buf, encoding) {\n return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function (opts) { // TODO: encode more stuff in pax\n var result = ''\n if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n var pax = opts.pax\n if (pax) {\n for (var key in pax) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n return Buffer.from(result)\n}\n\nexports.decodePax = function (buf) {\n var result = {}\n\n while (buf.length) {\n var i = 0\n while (i < buf.length && buf[i] !== 32) i++\n var len = parseInt(buf.slice(0, i).toString(), 10)\n if (!len) return result\n\n var b = buf.slice(i + 1, len - 1).toString()\n var keyIndex = b.indexOf('=')\n if (keyIndex === -1) return result\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n buf = buf.slice(len)\n }\n\n return result\n}\n\nexports.encode = function (opts) {\n var buf = alloc(512)\n var name = opts.name\n var prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n if (Buffer.byteLength(name) !== name.length) return null // utf-8\n\n while (Buffer.byteLength(name) > 100) {\n var i = name.indexOf('/')\n if (i === -1) return null\n prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null\n if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null\n\n buf.write(name)\n buf.write(encodeOct(opts.mode & MASK, 6), 100)\n buf.write(encodeOct(opts.uid, 6), 108)\n buf.write(encodeOct(opts.gid, 6), 116)\n buf.write(encodeOct(opts.size, 11), 124)\n buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname) buf.write(opts.linkname, 157)\n\n USTAR_MAGIC.copy(buf, MAGIC_OFFSET)\n USTAR_VER.copy(buf, VERSION_OFFSET)\n if (opts.uname) buf.write(opts.uname, 265)\n if (opts.gname) buf.write(opts.gname, 297)\n buf.write(encodeOct(opts.devmajor || 0, 6), 329)\n buf.write(encodeOct(opts.devminor || 0, 6), 337)\n\n if (prefix) buf.write(prefix, 345)\n\n buf.write(encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n\nexports.decode = function (buf, filenameEncoding, allowUnknownFormat) {\n var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n var name = decodeStr(buf, 0, 100, filenameEncoding)\n var mode = decodeOct(buf, 100, 8)\n var uid = decodeOct(buf, 108, 8)\n var gid = decodeOct(buf, 116, 8)\n var size = decodeOct(buf, 124, 12)\n var mtime = decodeOct(buf, 136, 12)\n var type = toType(typeflag)\n var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n var uname = decodeStr(buf, 265, 32)\n var gname = decodeStr(buf, 297, 32)\n var devmajor = decodeOct(buf, 329, 8)\n var devminor = decodeOct(buf, 337, 8)\n\n var c = cksum(buf)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) return null\n\n // valid checksum\n if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 &&\n GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n if (!allowUnknownFormat) {\n throw new Error('Invalid tar header: unknown format.')\n }\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * mtime),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor\n }\n}\n","exports.extract = require('./extract')\nexports.pack = require('./pack')\n","var constants = require('fs-constants')\nvar eos = require('end-of-stream')\nvar inherits = require('inherits')\nvar alloc = Buffer.alloc\n\nvar Readable = require('readable-stream').Readable\nvar Writable = require('readable-stream').Writable\nvar StringDecoder = require('string_decoder').StringDecoder\n\nvar headers = require('./headers')\n\nvar DMODE = parseInt('755', 8)\nvar FMODE = parseInt('644', 8)\n\nvar END_OF_TAR = alloc(1024)\n\nvar noop = function () {}\n\nvar overflow = function (self, size) {\n size &= 511\n if (size) self.push(END_OF_TAR.slice(0, 512 - size))\n}\n\nfunction modeToType (mode) {\n switch (mode & constants.S_IFMT) {\n case constants.S_IFBLK: return 'block-device'\n case constants.S_IFCHR: return 'character-device'\n case constants.S_IFDIR: return 'directory'\n case constants.S_IFIFO: return 'fifo'\n case constants.S_IFLNK: return 'symlink'\n }\n\n return 'file'\n}\n\nvar Sink = function (to) {\n Writable.call(this)\n this.written = 0\n this._to = to\n this._destroyed = false\n}\n\ninherits(Sink, Writable)\n\nSink.prototype._write = function (data, enc, cb) {\n this.written += data.length\n if (this._to.push(data)) return cb()\n this._to._drain = cb\n}\n\nSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar LinkSink = function () {\n Writable.call(this)\n this.linkname = ''\n this._decoder = new StringDecoder('utf-8')\n this._destroyed = false\n}\n\ninherits(LinkSink, Writable)\n\nLinkSink.prototype._write = function (data, enc, cb) {\n this.linkname += this._decoder.write(data)\n cb()\n}\n\nLinkSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Void = function () {\n Writable.call(this)\n this._destroyed = false\n}\n\ninherits(Void, Writable)\n\nVoid.prototype._write = function (data, enc, cb) {\n cb(new Error('No body allowed for this entry'))\n}\n\nVoid.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Pack = function (opts) {\n if (!(this instanceof Pack)) return new Pack(opts)\n Readable.call(this, opts)\n\n this._drain = noop\n this._finalized = false\n this._finalizing = false\n this._destroyed = false\n this._stream = null\n}\n\ninherits(Pack, Readable)\n\nPack.prototype.entry = function (header, buffer, callback) {\n if (this._stream) throw new Error('already piping an entry')\n if (this._finalized || this._destroyed) return\n\n if (typeof buffer === 'function') {\n callback = buffer\n buffer = null\n }\n\n if (!callback) callback = noop\n\n var self = this\n\n if (!header.size || header.type === 'symlink') header.size = 0\n if (!header.type) header.type = modeToType(header.mode)\n if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n if (!header.uid) header.uid = 0\n if (!header.gid) header.gid = 0\n if (!header.mtime) header.mtime = new Date()\n\n if (typeof buffer === 'string') buffer = Buffer.from(buffer)\n if (Buffer.isBuffer(buffer)) {\n header.size = buffer.length\n this._encode(header)\n var ok = this.push(buffer)\n overflow(self, header.size)\n if (ok) process.nextTick(callback)\n else this._drain = callback\n return new Void()\n }\n\n if (header.type === 'symlink' && !header.linkname) {\n var linkSink = new LinkSink()\n eos(linkSink, function (err) {\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n header.linkname = linkSink.linkname\n self._encode(header)\n callback()\n })\n\n return linkSink\n }\n\n this._encode(header)\n\n if (header.type !== 'file' && header.type !== 'contiguous-file') {\n process.nextTick(callback)\n return new Void()\n }\n\n var sink = new Sink(this)\n\n this._stream = sink\n\n eos(sink, function (err) {\n self._stream = null\n\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n if (sink.written !== header.size) { // corrupting tar\n self.destroy()\n return callback(new Error('size mismatch'))\n }\n\n overflow(self, header.size)\n if (self._finalizing) self.finalize()\n callback()\n })\n\n return sink\n}\n\nPack.prototype.finalize = function () {\n if (this._stream) {\n this._finalizing = true\n return\n }\n\n if (this._finalized) return\n this._finalized = true\n this.push(END_OF_TAR)\n this.push(null)\n}\n\nPack.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream && this._stream.destroy) this._stream.destroy()\n}\n\nPack.prototype._encode = function (header) {\n if (!header.pax) {\n var buf = headers.encode(header)\n if (buf) {\n this.push(buf)\n return\n }\n }\n this._encodePax(header)\n}\n\nPack.prototype._encodePax = function (header) {\n var paxHeader = headers.encodePax({\n name: header.name,\n linkname: header.linkname,\n pax: header.pax\n })\n\n var newHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.length,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname && 'PaxHeader',\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n this.push(headers.encode(newHeader))\n this.push(paxHeader)\n overflow(this, paxHeader.length)\n\n newHeader.size = header.size\n newHeader.type = header.type\n this.push(headers.encode(newHeader))\n}\n\nPack.prototype._read = function (n) {\n var drain = this._drain\n this._drain = noop\n drain()\n}\n\nmodule.exports = Pack\n","module.exports = require('./lib/tunnel');\n","'use strict';\n\nvar net = require('net');\nvar tls = require('tls');\nvar http = require('http');\nvar https = require('https');\nvar events = require('events');\nvar assert = require('assert');\nvar util = require('util');\n\n\nexports.httpOverHttp = httpOverHttp;\nexports.httpsOverHttp = httpsOverHttp;\nexports.httpOverHttps = httpOverHttps;\nexports.httpsOverHttps = httpsOverHttps;\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n return agent;\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n return agent;\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this;\n self.options = options || {};\n self.proxyOptions = self.options.proxy || {};\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;\n self.requests = [];\n self.sockets = [];\n\n self.on('free', function onFree(socket, host, port, localAddress) {\n var options = toOptions(host, port, localAddress);\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i];\n if (pending.host === options.host && pending.port === options.port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1);\n pending.request.onSocket(socket);\n return;\n }\n }\n socket.destroy();\n self.removeSocket(socket);\n });\n}\nutil.inherits(TunnelingAgent, events.EventEmitter);\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {\n var self = this;\n var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push(options);\n return;\n }\n\n // If we are under maxSockets create a new one.\n self.createSocket(options, function(socket) {\n socket.on('free', onFree);\n socket.on('close', onCloseOrRemove);\n socket.on('agentRemove', onCloseOrRemove);\n req.onSocket(socket);\n\n function onFree() {\n self.emit('free', socket, options);\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket);\n socket.removeListener('free', onFree);\n socket.removeListener('close', onCloseOrRemove);\n socket.removeListener('agentRemove', onCloseOrRemove);\n }\n });\n};\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this;\n var placeholder = {};\n self.sockets.push(placeholder);\n\n var connectOptions = mergeOptions({}, self.proxyOptions, {\n method: 'CONNECT',\n path: options.host + ':' + options.port,\n agent: false,\n headers: {\n host: options.host + ':' + options.port\n }\n });\n if (options.localAddress) {\n connectOptions.localAddress = options.localAddress;\n }\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {};\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n new Buffer(connectOptions.proxyAuth).toString('base64');\n }\n\n debug('making CONNECT request');\n var connectReq = self.request(connectOptions);\n connectReq.useChunkedEncodingByDefault = false; // for v0.6\n connectReq.once('response', onResponse); // for v0.6\n connectReq.once('upgrade', onUpgrade); // for v0.6\n connectReq.once('connect', onConnect); // for v0.7 or later\n connectReq.once('error', onError);\n connectReq.end();\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true;\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head);\n });\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners();\n socket.removeAllListeners();\n\n if (res.statusCode !== 200) {\n debug('tunneling socket could not be established, statusCode=%d',\n res.statusCode);\n socket.destroy();\n var error = new Error('tunneling socket could not be established, ' +\n 'statusCode=' + res.statusCode);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n if (head.length > 0) {\n debug('got illegal response body from proxy');\n socket.destroy();\n var error = new Error('got illegal response body from proxy');\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n debug('tunneling connection has established');\n self.sockets[self.sockets.indexOf(placeholder)] = socket;\n return cb(socket);\n }\n\n function onError(cause) {\n connectReq.removeAllListeners();\n\n debug('tunneling socket could not be established, cause=%s\\n',\n cause.message, cause.stack);\n var error = new Error('tunneling socket could not be established, ' +\n 'cause=' + cause.message);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n }\n};\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) {\n return;\n }\n this.sockets.splice(pos, 1);\n\n var pending = this.requests.shift();\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createSocket(pending, function(socket) {\n pending.request.onSocket(socket);\n });\n }\n};\n\nfunction createSecureSocket(options, cb) {\n var self = this;\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n var hostHeader = options.request.getHeader('host');\n var tlsOptions = mergeOptions({}, self.options, {\n socket: socket,\n servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host\n });\n\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, tlsOptions);\n self.sockets[self.sockets.indexOf(socket)] = secureSocket;\n cb(secureSocket);\n });\n}\n\n\nfunction toOptions(host, port, localAddress) {\n if (typeof host === 'string') { // since v0.10\n return {\n host: host,\n port: port,\n localAddress: localAddress\n };\n }\n return host; // for v0.11 or later\n}\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i];\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides);\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j];\n if (overrides[k] !== undefined) {\n target[k] = overrides[k];\n }\n }\n }\n }\n return target;\n}\n\n\nvar debug;\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments);\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0];\n } else {\n args.unshift('TUNNEL:');\n }\n console.error.apply(console, args);\n }\n} else {\n debug = function() {};\n}\nexports.debug = debug; // for test\n","(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _0 = new Uint8Array(16);\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_16(x, xi, y, yi) {\n return vn(x,xi,y,yi,16);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction core_salsa20(o, p, k, c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n x0 = x0 + j0 | 0;\n x1 = x1 + j1 | 0;\n x2 = x2 + j2 | 0;\n x3 = x3 + j3 | 0;\n x4 = x4 + j4 | 0;\n x5 = x5 + j5 | 0;\n x6 = x6 + j6 | 0;\n x7 = x7 + j7 | 0;\n x8 = x8 + j8 | 0;\n x9 = x9 + j9 | 0;\n x10 = x10 + j10 | 0;\n x11 = x11 + j11 | 0;\n x12 = x12 + j12 | 0;\n x13 = x13 + j13 | 0;\n x14 = x14 + j14 | 0;\n x15 = x15 + j15 | 0;\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x1 >>> 0 & 0xff;\n o[ 5] = x1 >>> 8 & 0xff;\n o[ 6] = x1 >>> 16 & 0xff;\n o[ 7] = x1 >>> 24 & 0xff;\n\n o[ 8] = x2 >>> 0 & 0xff;\n o[ 9] = x2 >>> 8 & 0xff;\n o[10] = x2 >>> 16 & 0xff;\n o[11] = x2 >>> 24 & 0xff;\n\n o[12] = x3 >>> 0 & 0xff;\n o[13] = x3 >>> 8 & 0xff;\n o[14] = x3 >>> 16 & 0xff;\n o[15] = x3 >>> 24 & 0xff;\n\n o[16] = x4 >>> 0 & 0xff;\n o[17] = x4 >>> 8 & 0xff;\n o[18] = x4 >>> 16 & 0xff;\n o[19] = x4 >>> 24 & 0xff;\n\n o[20] = x5 >>> 0 & 0xff;\n o[21] = x5 >>> 8 & 0xff;\n o[22] = x5 >>> 16 & 0xff;\n o[23] = x5 >>> 24 & 0xff;\n\n o[24] = x6 >>> 0 & 0xff;\n o[25] = x6 >>> 8 & 0xff;\n o[26] = x6 >>> 16 & 0xff;\n o[27] = x6 >>> 24 & 0xff;\n\n o[28] = x7 >>> 0 & 0xff;\n o[29] = x7 >>> 8 & 0xff;\n o[30] = x7 >>> 16 & 0xff;\n o[31] = x7 >>> 24 & 0xff;\n\n o[32] = x8 >>> 0 & 0xff;\n o[33] = x8 >>> 8 & 0xff;\n o[34] = x8 >>> 16 & 0xff;\n o[35] = x8 >>> 24 & 0xff;\n\n o[36] = x9 >>> 0 & 0xff;\n o[37] = x9 >>> 8 & 0xff;\n o[38] = x9 >>> 16 & 0xff;\n o[39] = x9 >>> 24 & 0xff;\n\n o[40] = x10 >>> 0 & 0xff;\n o[41] = x10 >>> 8 & 0xff;\n o[42] = x10 >>> 16 & 0xff;\n o[43] = x10 >>> 24 & 0xff;\n\n o[44] = x11 >>> 0 & 0xff;\n o[45] = x11 >>> 8 & 0xff;\n o[46] = x11 >>> 16 & 0xff;\n o[47] = x11 >>> 24 & 0xff;\n\n o[48] = x12 >>> 0 & 0xff;\n o[49] = x12 >>> 8 & 0xff;\n o[50] = x12 >>> 16 & 0xff;\n o[51] = x12 >>> 24 & 0xff;\n\n o[52] = x13 >>> 0 & 0xff;\n o[53] = x13 >>> 8 & 0xff;\n o[54] = x13 >>> 16 & 0xff;\n o[55] = x13 >>> 24 & 0xff;\n\n o[56] = x14 >>> 0 & 0xff;\n o[57] = x14 >>> 8 & 0xff;\n o[58] = x14 >>> 16 & 0xff;\n o[59] = x14 >>> 24 & 0xff;\n\n o[60] = x15 >>> 0 & 0xff;\n o[61] = x15 >>> 8 & 0xff;\n o[62] = x15 >>> 16 & 0xff;\n o[63] = x15 >>> 24 & 0xff;\n}\n\nfunction core_hsalsa20(o,p,k,c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x5 >>> 0 & 0xff;\n o[ 5] = x5 >>> 8 & 0xff;\n o[ 6] = x5 >>> 16 & 0xff;\n o[ 7] = x5 >>> 24 & 0xff;\n\n o[ 8] = x10 >>> 0 & 0xff;\n o[ 9] = x10 >>> 8 & 0xff;\n o[10] = x10 >>> 16 & 0xff;\n o[11] = x10 >>> 24 & 0xff;\n\n o[12] = x15 >>> 0 & 0xff;\n o[13] = x15 >>> 8 & 0xff;\n o[14] = x15 >>> 16 & 0xff;\n o[15] = x15 >>> 24 & 0xff;\n\n o[16] = x6 >>> 0 & 0xff;\n o[17] = x6 >>> 8 & 0xff;\n o[18] = x6 >>> 16 & 0xff;\n o[19] = x6 >>> 24 & 0xff;\n\n o[20] = x7 >>> 0 & 0xff;\n o[21] = x7 >>> 8 & 0xff;\n o[22] = x7 >>> 16 & 0xff;\n o[23] = x7 >>> 24 & 0xff;\n\n o[24] = x8 >>> 0 & 0xff;\n o[25] = x8 >>> 8 & 0xff;\n o[26] = x8 >>> 16 & 0xff;\n o[27] = x8 >>> 24 & 0xff;\n\n o[28] = x9 >>> 0 & 0xff;\n o[29] = x9 >>> 8 & 0xff;\n o[30] = x9 >>> 16 & 0xff;\n o[31] = x9 >>> 24 & 0xff;\n}\n\nfunction crypto_core_salsa20(out,inp,k,c) {\n core_salsa20(out,inp,k,c);\n}\n\nfunction crypto_core_hsalsa20(out,inp,k,c) {\n core_hsalsa20(out,inp,k,c);\n}\n\nvar sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);\n // \"expand 32-byte k\"\n\nfunction crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n mpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n }\n return 0;\n}\n\nfunction crypto_stream_salsa20(c,cpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = x[i];\n }\n return 0;\n}\n\nfunction crypto_stream(c,cpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20(c,cpos,d,sn,s);\n}\n\nfunction crypto_stream_xor(c,cpos,m,mpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);\n}\n\n/*\n* Port of Andrew Moon's Poly1305-donna-16. Public domain.\n* https://github.com/floodyberry/poly1305-donna\n*/\n\nvar poly1305 = function(key) {\n this.buffer = new Uint8Array(16);\n this.r = new Uint16Array(10);\n this.h = new Uint16Array(10);\n this.pad = new Uint16Array(8);\n this.leftover = 0;\n this.fin = 0;\n\n var t0, t1, t2, t3, t4, t5, t6, t7;\n\n t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;\n t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = ((t4 >>> 1)) & 0x1ffe;\n t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = ((t7 >>> 5)) & 0x007f;\n\n this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;\n this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;\n this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;\n this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;\n this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;\n this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;\n this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;\n this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;\n};\n\npoly1305.prototype.blocks = function(m, mpos, bytes) {\n var hibit = this.fin ? 0 : (1 << 11);\n var t0, t1, t2, t3, t4, t5, t6, t7, c;\n var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;\n\n var h0 = this.h[0],\n h1 = this.h[1],\n h2 = this.h[2],\n h3 = this.h[3],\n h4 = this.h[4],\n h5 = this.h[5],\n h6 = this.h[6],\n h7 = this.h[7],\n h8 = this.h[8],\n h9 = this.h[9];\n\n var r0 = this.r[0],\n r1 = this.r[1],\n r2 = this.r[2],\n r3 = this.r[3],\n r4 = this.r[4],\n r5 = this.r[5],\n r6 = this.r[6],\n r7 = this.r[7],\n r8 = this.r[8],\n r9 = this.r[9];\n\n while (bytes >= 16) {\n t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;\n t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n c = 0;\n\n d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this.h[0] = h0;\n this.h[1] = h1;\n this.h[2] = h2;\n this.h[3] = h3;\n this.h[4] = h4;\n this.h[5] = h5;\n this.h[6] = h6;\n this.h[7] = h7;\n this.h[8] = h8;\n this.h[9] = h9;\n};\n\npoly1305.prototype.finish = function(mac, macpos) {\n var g = new Uint16Array(10);\n var c, mask, f, i;\n\n if (this.leftover) {\n i = this.leftover;\n this.buffer[i++] = 1;\n for (; i < 16; i++) this.buffer[i] = 0;\n this.fin = 1;\n this.blocks(this.buffer, 0, 16);\n }\n\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this.h[i] += c;\n c = this.h[i] >>> 13;\n this.h[i] &= 0x1fff;\n }\n this.h[0] += (c * 5);\n c = this.h[0] >>> 13;\n this.h[0] &= 0x1fff;\n this.h[1] += c;\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n this.h[2] += c;\n\n g[0] = this.h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this.h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];\n\n this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;\n this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;\n this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;\n this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;\n this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;\n this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;\n this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;\n this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;\n\n f = this.h[0] + this.pad[0];\n this.h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;\n this.h[i] = f & 0xffff;\n }\n\n mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;\n mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;\n mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;\n mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;\n mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;\n mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;\n mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;\n mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;\n mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;\n mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;\n mac[macpos+10] = (this.h[5] >>> 0) & 0xff;\n mac[macpos+11] = (this.h[5] >>> 8) & 0xff;\n mac[macpos+12] = (this.h[6] >>> 0) & 0xff;\n mac[macpos+13] = (this.h[6] >>> 8) & 0xff;\n mac[macpos+14] = (this.h[7] >>> 0) & 0xff;\n mac[macpos+15] = (this.h[7] >>> 8) & 0xff;\n};\n\npoly1305.prototype.update = function(m, mpos, bytes) {\n var i, want;\n\n if (this.leftover) {\n want = (16 - this.leftover);\n if (want > bytes)\n want = bytes;\n for (i = 0; i < want; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n bytes -= want;\n mpos += want;\n this.leftover += want;\n if (this.leftover < 16)\n return;\n this.blocks(this.buffer, 0, 16);\n this.leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this.blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (i = 0; i < bytes; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n this.leftover += bytes;\n }\n};\n\nfunction crypto_onetimeauth(out, outpos, m, mpos, n, k) {\n var s = new poly1305(k);\n s.update(m, mpos, n);\n s.finish(out, outpos);\n return 0;\n}\n\nfunction crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {\n var x = new Uint8Array(16);\n crypto_onetimeauth(x,0,m,mpos,n,k);\n return crypto_verify_16(h,hpos,x,0);\n}\n\nfunction crypto_secretbox(c,m,d,n,k) {\n var i;\n if (d < 32) return -1;\n crypto_stream_xor(c,0,m,0,d,n,k);\n crypto_onetimeauth(c, 16, c, 32, d - 32, c);\n for (i = 0; i < 16; i++) c[i] = 0;\n return 0;\n}\n\nfunction crypto_secretbox_open(m,c,d,n,k) {\n var i;\n var x = new Uint8Array(32);\n if (d < 32) return -1;\n crypto_stream(x,0,32,n,k);\n if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;\n crypto_stream_xor(m,0,c,0,d,n,k);\n for (i = 0; i < 32; i++) m[i] = 0;\n return 0;\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction crypto_box_beforenm(k, y, x) {\n var s = new Uint8Array(32);\n crypto_scalarmult(s, x, y);\n return crypto_core_hsalsa20(k, _0, s, sigma);\n}\n\nvar crypto_box_afternm = crypto_secretbox;\nvar crypto_box_open_afternm = crypto_secretbox_open;\n\nfunction crypto_box(c, m, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_afternm(c, m, d, n, k);\n}\n\nfunction crypto_box_open(m, c, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_open_afternm(m, c, d, n, k);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n mlen = n;\n return mlen;\n}\n\nvar crypto_secretbox_KEYBYTES = 32,\n crypto_secretbox_NONCEBYTES = 24,\n crypto_secretbox_ZEROBYTES = 32,\n crypto_secretbox_BOXZEROBYTES = 16,\n crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_box_BEFORENMBYTES = 32,\n crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,\n crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,\n crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32,\n crypto_hash_BYTES = 64;\n\nnacl.lowlevel = {\n crypto_core_hsalsa20: crypto_core_hsalsa20,\n crypto_stream_xor: crypto_stream_xor,\n crypto_stream: crypto_stream,\n crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,\n crypto_stream_salsa20: crypto_stream_salsa20,\n crypto_onetimeauth: crypto_onetimeauth,\n crypto_onetimeauth_verify: crypto_onetimeauth_verify,\n crypto_verify_16: crypto_verify_16,\n crypto_verify_32: crypto_verify_32,\n crypto_secretbox: crypto_secretbox,\n crypto_secretbox_open: crypto_secretbox_open,\n crypto_scalarmult: crypto_scalarmult,\n crypto_scalarmult_base: crypto_scalarmult_base,\n crypto_box_beforenm: crypto_box_beforenm,\n crypto_box_afternm: crypto_box_afternm,\n crypto_box: crypto_box,\n crypto_box_open: crypto_box_open,\n crypto_box_keypair: crypto_box_keypair,\n crypto_hash: crypto_hash,\n crypto_sign: crypto_sign,\n crypto_sign_keypair: crypto_sign_keypair,\n crypto_sign_open: crypto_sign_open,\n\n crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,\n crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,\n crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,\n crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,\n crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,\n crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,\n crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,\n crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,\n crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,\n crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,\n crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,\n crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,\n crypto_sign_BYTES: crypto_sign_BYTES,\n crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,\n crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,\n crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,\n crypto_hash_BYTES: crypto_hash_BYTES\n};\n\n/* High-level API */\n\nfunction checkLengths(k, n) {\n if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');\n if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');\n}\n\nfunction checkBoxLengths(pk, sk) {\n if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');\n if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');\n}\n\nfunction checkArrayTypes() {\n var t, i;\n for (i = 0; i < arguments.length; i++) {\n if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')\n throw new TypeError('unexpected type ' + t + ', use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\n// TODO: Completely remove this in v0.15.\nif (!nacl.util) {\n nacl.util = {};\n nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() {\n throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');\n };\n}\n\nnacl.randomBytes = function(n) {\n var b = new Uint8Array(n);\n randombytes(b, n);\n return b;\n};\n\nnacl.secretbox = function(msg, nonce, key) {\n checkArrayTypes(msg, nonce, key);\n checkLengths(key, nonce);\n var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);\n var c = new Uint8Array(m.length);\n for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];\n crypto_secretbox(c, m, m.length, nonce, key);\n return c.subarray(crypto_secretbox_BOXZEROBYTES);\n};\n\nnacl.secretbox.open = function(box, nonce, key) {\n checkArrayTypes(box, nonce, key);\n checkLengths(key, nonce);\n var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);\n var m = new Uint8Array(c.length);\n for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];\n if (c.length < 32) return false;\n if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false;\n return m.subarray(crypto_secretbox_ZEROBYTES);\n};\n\nnacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;\nnacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;\nnacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.scalarMult.base = function(n) {\n checkArrayTypes(n);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult_base(q, n);\n return q;\n};\n\nnacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;\nnacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;\n\nnacl.box = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox(msg, nonce, k);\n};\n\nnacl.box.before = function(publicKey, secretKey) {\n checkArrayTypes(publicKey, secretKey);\n checkBoxLengths(publicKey, secretKey);\n var k = new Uint8Array(crypto_box_BEFORENMBYTES);\n crypto_box_beforenm(k, publicKey, secretKey);\n return k;\n};\n\nnacl.box.after = nacl.secretbox;\n\nnacl.box.open = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox.open(msg, nonce, k);\n};\n\nnacl.box.open.after = nacl.secretbox.open;\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;\nnacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;\nnacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;\nnacl.box.nonceLength = crypto_box_NONCEBYTES;\nnacl.box.overheadLength = nacl.secretbox.overheadLength;\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.open = function(signedMsg, publicKey) {\n if (arguments.length !== 2)\n throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');\n checkArrayTypes(signedMsg, publicKey);\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var tmp = new Uint8Array(signedMsg.length);\n var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);\n if (mlen < 0) return null;\n var m = new Uint8Array(mlen);\n for (var i = 0; i < m.length; i++) m[i] = tmp[i];\n return m;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;\nnacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;\nnacl.sign.seedLength = crypto_sign_SEEDBYTES;\nnacl.sign.signatureLength = crypto_sign_BYTES;\n\nnacl.hash = function(msg) {\n checkArrayTypes(msg);\n var h = new Uint8Array(crypto_hash_BYTES);\n crypto_hash(h, msg, msg.length);\n return h;\n};\n\nnacl.hash.hashLength = crypto_hash_BYTES;\n\nnacl.verify = function(x, y) {\n checkArrayTypes(x, y);\n // Zero length arguments are considered not equal.\n if (x.length === 0 || y.length === 0) return false;\n if (x.length !== y.length) return false;\n return (vn(x, 0, y, 0, x.length) === 0) ? true : false;\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && \"version\" in process) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;\n }\n\n return \"\";\n}\n\nexports.getUserAgent = getUserAgent;\n//# sourceMappingURL=index.js.map\n","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\n\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\n\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\n\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\n\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\n\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\n\nvar _version = _interopRequireDefault(require(\"./version.js\"));\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction md5(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return _crypto.default.createHash('md5').update(bytes).digest();\n}\n\nvar _default = md5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = '00000000-0000-0000-0000-000000000000';\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nvar _default = parse;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\n\nfunction rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n _crypto.default.randomFillSync(rnds8Pool);\n\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return _crypto.default.createHash('sha1').update(bytes).digest();\n}\n\nvar _default = sha1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nvar _default = stringify;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\nlet _nodeId;\n\nlet _clockseq; // Previous uuid creation time\n\n\nlet _lastMSecs = 0;\nlet _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node || _nodeId;\n let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || (0, _stringify.default)(b);\n}\n\nvar _default = v1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = v3;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = _default;\nexports.URL = exports.DNS = void 0;\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nconst DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexports.DNS = DNS;\nconst URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexports.URL = URL;\n\nfunction _default(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.default)(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction v4(options, buf, offset) {\n options = options || {};\n\n const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.default)(rnds);\n}\n\nvar _default = v4;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = v5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\n\nvar _default = validate;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nvar _default = version;\nexports.default = _default;","// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ApiClient = exports.CredentialFetchingError = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst axios_1 = __importDefault(require(\"axios\"));\nclass CredentialFetchingError extends Error {\n}\nexports.CredentialFetchingError = CredentialFetchingError;\nclass ApiClient {\n constructor(client, params) {\n this.client = client;\n this.params = params;\n // We use a static unknown SHA when marking a job as complete from the action\n // to remain in parity with the existing runner.\n this.UnknownSha = {\n 'base-commit-sha': 'unknown'\n };\n }\n getJobDetails() {\n return __awaiter(this, void 0, void 0, function* () {\n const detailsURL = `/update_jobs/${this.params.jobId}/details`;\n const res = yield this.client.get(detailsURL, {\n headers: { Authorization: this.params.jobToken }\n });\n if (res.status !== 200) {\n throw new Error(`Unexpected status code: ${res.status}`);\n }\n return res.data.data.attributes;\n });\n }\n getCredentials() {\n var _a, _b;\n return __awaiter(this, void 0, void 0, function* () {\n const credentialsURL = `/update_jobs/${this.params.jobId}/credentials`;\n try {\n const res = yield this.client.get(credentialsURL, {\n headers: { Authorization: this.params.credentialsToken }\n });\n // Mask any secrets we've just retrieved from Actions logs\n for (const credential of res.data.data.attributes.credentials) {\n if (credential.password) {\n core.setSecret(credential.password);\n }\n if (credential.token) {\n core.setSecret(credential.token);\n }\n }\n return res.data.data.attributes.credentials;\n }\n catch (error) {\n if (axios_1.default.isAxiosError(error)) {\n const err = error;\n throw new CredentialFetchingError(`fetching credentials: received code ${(_a = err.response) === null || _a === void 0 ? void 0 : _a.status}: ${JSON.stringify((_b = err.response) === null || _b === void 0 ? void 0 : _b.data)}`);\n }\n else {\n throw error;\n }\n }\n });\n }\n reportJobError(error) {\n return __awaiter(this, void 0, void 0, function* () {\n const recordErrorURL = `/update_jobs/${this.params.jobId}/record_update_job_error`;\n const res = yield this.client.post(recordErrorURL, { data: error }, {\n headers: { Authorization: this.params.jobToken }\n });\n if (res.status !== 204) {\n throw new Error(`Unexpected status code: ${res.status}`);\n }\n });\n }\n markJobAsProcessed() {\n return __awaiter(this, void 0, void 0, function* () {\n const markAsProcessedURL = `/update_jobs/${this.params.jobId}/mark_as_processed`;\n const res = yield this.client.patch(markAsProcessedURL, { data: this.UnknownSha }, {\n headers: { Authorization: this.params.jobToken }\n });\n if (res.status !== 204) {\n throw new Error(`Unexpected status code: ${res.status}`);\n }\n });\n }\n}\nexports.ApiClient = ApiClient;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ContainerService = exports.ContainerRuntimeError = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst tar_stream_1 = require(\"tar-stream\");\nconst utils_1 = require(\"./utils\");\nclass ContainerRuntimeError extends Error {\n}\nexports.ContainerRuntimeError = ContainerRuntimeError;\nexports.ContainerService = {\n storeInput(name, path, container, input) {\n return __awaiter(this, void 0, void 0, function* () {\n const tar = (0, tar_stream_1.pack)();\n tar.entry({ name }, JSON.stringify(input));\n tar.finalize();\n yield container.putArchive(tar, { path });\n });\n },\n storeCert(name, path, container, cert) {\n return __awaiter(this, void 0, void 0, function* () {\n const tar = (0, tar_stream_1.pack)();\n tar.entry({ name }, cert);\n tar.finalize();\n yield container.putArchive(tar, { path });\n });\n },\n run(container) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const stream = yield container.attach({\n stream: true,\n stdout: true,\n stderr: true\n });\n container.modem.demuxStream(stream, (0, utils_1.outStream)('updater'), (0, utils_1.errStream)('updater'));\n yield container.start();\n const outcome = yield container.wait();\n if (outcome.StatusCode === 0) {\n return true;\n }\n else {\n core.info(`Failure running container ${container.id}`);\n throw new ContainerRuntimeError('The updater encountered one or more errors.');\n }\n }\n finally {\n yield container.remove({ v: true });\n core.info(`Cleaned up container ${container.id}`);\n }\n });\n }\n};\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.repositoryName = exports.PROXY_IMAGE_NAME = exports.UPDATER_IMAGE_NAME = void 0;\nconst containers_json_1 = __importDefault(require(\"../docker/containers.json\"));\nexports.UPDATER_IMAGE_NAME = containers_json_1.default.updater;\nexports.PROXY_IMAGE_NAME = containers_json_1.default.proxy;\nconst imageNamePattern = '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))((:[a-zA-Z0-9._/-]+)|(@sha256:[a-zA-Z0-9]{64}))?$';\nfunction repositoryName(imageName) {\n const match = imageName.match(imageNamePattern);\n if (match === null || match === void 0 ? void 0 : match.groups) {\n return match.groups['repository'];\n }\n else {\n throw Error('invalid image name');\n }\n}\nexports.repositoryName = repositoryName;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ImageService = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst dockerode_1 = __importDefault(require(\"dockerode\"));\nconst endOfStream = (docker, stream) => __awaiter(void 0, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n docker.modem.followProgress(stream, (err) => err ? reject(err) : resolve(undefined));\n });\n});\n/** Fetch the configured updater image, if it isn't already available. */\nexports.ImageService = {\n pull(imageName, force = false) {\n return __awaiter(this, void 0, void 0, function* () {\n /*\n This method fetches images hosts on GitHub infrastructure.\n \n We expose the `fetch_image` utility method to allow us to pull in arbitrary images for unit tests.\n */\n if (!(imageName.startsWith('ghcr.io/') ||\n imageName.startsWith('docker.pkg.github.com/'))) {\n throw new Error('Only images distributed via docker.pkg.github.com or ghcr.io can be fetched');\n }\n const docker = new dockerode_1.default();\n try {\n const image = yield docker.getImage(imageName).inspect();\n if (!force) {\n core.info(`Resolved ${imageName} to existing ${image.RepoDigests}`);\n return;\n } // else fallthrough to pull\n }\n catch (e) {\n if (e instanceof Error && !e.message.includes('no such image')) {\n throw e;\n } // else fallthrough to pull\n }\n const auth = {}; // Images are public so not authentication info is required\n yield this.fetchImage(imageName, auth, docker);\n });\n },\n /* Retrieve the imageName using the auth details provided, if any */\n fetchImage(imageName, auth = {}, docker = new dockerode_1.default()) {\n return __awaiter(this, void 0, void 0, function* () {\n core.info(`Pulling image ${imageName}...`);\n const stream = yield docker.pull(imageName, { authconfig: auth });\n yield endOfStream(docker, stream);\n core.info(`Pulled image ${imageName}`);\n });\n }\n};\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getJobParameters = exports.JobParameters = void 0;\nconst fs_1 = __importDefault(require(\"fs\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst core = __importStar(require(\"@actions/core\"));\nconst DYNAMIC = 'dynamic';\nconst DEPENDABOT_ACTOR = 'dependabot[bot]';\n// JobParameters are the Action inputs required to execute the job\nclass JobParameters {\n constructor(jobId, jobToken, credentialsToken, dependabotApiUrl, dependabotApiDockerUrl, workingDirectory) {\n this.jobId = jobId;\n this.jobToken = jobToken;\n this.credentialsToken = credentialsToken;\n this.dependabotApiUrl = dependabotApiUrl;\n this.dependabotApiDockerUrl = dependabotApiDockerUrl;\n this.workingDirectory = workingDirectory;\n }\n}\nexports.JobParameters = JobParameters;\nfunction getJobParameters(ctx) {\n checkEnvironmentAndContext(ctx);\n if (ctx.actor !== DEPENDABOT_ACTOR) {\n core.warning('This workflow can only be triggered by Dependabot.');\n return null;\n }\n if (ctx.eventName === DYNAMIC) {\n return fromWorkflowInputs(ctx);\n }\n else {\n core.warning(`Dependabot Updater Action does not support '${ctx.eventName}' events.`);\n return null;\n }\n}\nexports.getJobParameters = getJobParameters;\nfunction checkEnvironmentAndContext(ctx) {\n let valid = true;\n if (!ctx.actor) {\n core.error('GITHUB_ACTOR is not defined');\n valid = false;\n }\n if (!ctx.eventName) {\n core.error('GITHUB_EVENT_NAME is not defined');\n valid = false;\n }\n if (!process.env.GITHUB_WORKSPACE) {\n core.error('GITHUB_WORKSPACE is not defined');\n valid = false;\n }\n if (!valid) {\n throw new Error('Required Actions environment variables missing.');\n }\n else {\n return valid;\n }\n}\nfunction fromWorkflowInputs(ctx) {\n const evt = ctx.payload;\n if (!evt.inputs) {\n throw new Error('Event payload has no inputs');\n }\n const dependabotApiDockerUrl = evt.inputs.dependabotApiDockerUrl || evt.inputs.dependabotApiUrl;\n const workingDirectory = absoluteWorkingDirectory(evt.inputs.workingDirectory);\n return new JobParameters(parseInt(evt.inputs.jobId, 10), evt.inputs.jobToken, evt.inputs.credentialsToken, evt.inputs.dependabotApiUrl, dependabotApiDockerUrl, workingDirectory);\n}\nfunction absoluteWorkingDirectory(workingDirectory) {\n const workspace = process.env.GITHUB_WORKSPACE;\n if (!workingDirectory) {\n throw new Error('The workingDirectory input must not be blank.');\n }\n if (!directoryExistsSync(workspace)) {\n throw new Error('The GITHUB_WORKSPACE directory does not exist.');\n }\n const fullPath = path_1.default.join(workspace, workingDirectory);\n if (!directoryExistsSync(fullPath)) {\n throw new Error(`The workingDirectory '${workingDirectory}' does not exist in GITHUB_WORKSPACE`);\n }\n return fullPath;\n}\nfunction directoryExistsSync(directoryPath) {\n let stats;\n try {\n stats = fs_1.default.statSync(directoryPath);\n return stats.isDirectory();\n }\n catch (error) {\n if (isNodeError(error) && error.code === 'ENOENT') {\n return false;\n }\n else if (error instanceof Error) {\n throw new Error(`Encountered an error when checking whether path '${directoryPath}' exists: ${error.message}`);\n }\n }\n return false;\n}\nfunction isNodeError(error) {\n return error instanceof Error;\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.run = exports.DependabotErrorType = void 0;\nconst axios_1 = __importDefault(require(\"axios\"));\nconst core = __importStar(require(\"@actions/core\"));\nconst github = __importStar(require(\"@actions/github\"));\nconst api_client_1 = require(\"./api-client\");\nconst inputs_1 = require(\"./inputs\");\nconst image_service_1 = require(\"./image-service\");\nconst docker_tags_1 = require(\"./docker-tags\");\nconst updater_1 = require(\"./updater\");\nvar DependabotErrorType;\n(function (DependabotErrorType) {\n DependabotErrorType[\"Unknown\"] = \"actions_workflow_unknown\";\n DependabotErrorType[\"Image\"] = \"actions_workflow_image\";\n DependabotErrorType[\"UpdateRun\"] = \"actions_workflow_updater\";\n})(DependabotErrorType = exports.DependabotErrorType || (exports.DependabotErrorType = {}));\nlet jobId;\nfunction run(context) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n botSay('starting update');\n // Retrieve JobParameters from the Actions environment\n const params = (0, inputs_1.getJobParameters)(context);\n // The parameters will be null if the Action environment\n // is not a valid Dependabot-triggered dynamic event.\n if (params === null) {\n botSay('finished: nothing to do');\n return; // TODO: This should be setNeutral in future\n }\n jobId = params.jobId;\n core.setSecret(params.jobToken);\n core.setSecret(params.credentialsToken);\n const client = axios_1.default.create({ baseURL: params.dependabotApiUrl });\n const apiClient = new api_client_1.ApiClient(client, params);\n core.info('Fetching job details');\n // If we fail to succeed in fetching the job details, we cannot be sure the job has entered a 'processing' state,\n // so we do not try attempt to report back an exception if this fails and instead rely on the the workflow run\n // webhook as it anticipates scenarios where jobs have failed while 'enqueued'.\n const details = yield apiClient.getJobDetails();\n try {\n const credentials = yield apiClient.getCredentials();\n const updater = new updater_1.Updater(docker_tags_1.UPDATER_IMAGE_NAME, docker_tags_1.PROXY_IMAGE_NAME, apiClient, details, credentials, params.workingDirectory);\n core.startGroup('Pulling updater images');\n try {\n yield image_service_1.ImageService.pull(docker_tags_1.UPDATER_IMAGE_NAME);\n yield image_service_1.ImageService.pull(docker_tags_1.PROXY_IMAGE_NAME);\n }\n catch (error) {\n if (error instanceof Error) {\n yield failJob(apiClient, 'Error fetching updater images', error, DependabotErrorType.Image);\n return;\n }\n }\n core.endGroup();\n try {\n core.info('Starting update process');\n yield updater.runUpdater();\n }\n catch (error) {\n // If we have encountered a UpdaterFetchError, the Updater will already have\n // reported the error and marked the job as processed, so we only need to\n // set an exit status.\n if (error instanceof updater_1.UpdaterFetchError) {\n setFailed('Dependabot was unable to retrieve the files required to perform the update', null);\n botSay('finished: unable to fetch files');\n return;\n }\n else if (error instanceof Error) {\n yield failJob(apiClient, 'Dependabot encountered an error performing the update', error, DependabotErrorType.UpdateRun);\n return;\n }\n }\n botSay('finished');\n }\n catch (error) {\n if (error instanceof api_client_1.CredentialFetchingError) {\n yield failJob(apiClient, 'Dependabot was unable to retrieve job credentials', error, DependabotErrorType.UpdateRun);\n }\n else if (error instanceof Error) {\n yield failJob(apiClient, 'Dependabot was unable to start the update', error);\n }\n return;\n }\n }\n catch (error) {\n if (error instanceof Error) {\n // If we've reached this point, we do not have a viable\n // API client to report back to Dependabot API.\n //\n // We output the raw error in the Action logs and defer\n // to workflow_run monitoring to detect the job failure.\n setFailed('Dependabot encountered an unexpected problem', error);\n botSay('finished: unexpected error');\n }\n }\n });\n}\nexports.run = run;\nfunction failJob(apiClient, message, error, errorType = DependabotErrorType.Unknown) {\n return __awaiter(this, void 0, void 0, function* () {\n yield apiClient.reportJobError({\n 'error-type': errorType,\n 'error-details': {\n 'action-error': error.message\n }\n });\n yield apiClient.markJobAsProcessed();\n setFailed(message, error);\n botSay('finished: error reported to Dependabot');\n });\n}\nfunction botSay(message) {\n core.info(`🤖 ~ ${message} ~`);\n}\nfunction setFailed(message, error) {\n if (jobId) {\n message = [message, error, dependabotJobHelp()].filter(Boolean).join('\\n\\n');\n }\n core.setFailed(message);\n}\nfunction dependabotJobHelp() {\n if (jobId) {\n return `For more information see: ${dependabotJobUrl(jobId)} (write access required)`;\n }\n else {\n return null;\n }\n}\nfunction dependabotJobUrl(id) {\n const url_parts = [\n process.env.GITHUB_SERVER_URL,\n process.env.GITHUB_REPOSITORY,\n 'network/updates',\n id\n ];\n return url_parts.filter(Boolean).join('/');\n}\nrun(github.context);\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProxyBuilder = void 0;\nconst fs_1 = __importDefault(require(\"fs\"));\nconst core = __importStar(require(\"@actions/core\"));\nconst crypto_1 = __importDefault(require(\"crypto\"));\nconst container_service_1 = require(\"./container-service\");\nconst node_forge_1 = require(\"node-forge\");\nconst utils_1 = require(\"./utils\");\nconst KEY_SIZE = 2048;\nconst KEY_EXPIRY_YEARS = 2;\nconst CONFIG_FILE_PATH = '/';\nconst CONFIG_FILE_NAME = 'config.json';\nconst CA_CERT_INPUT_PATH = '/usr/local/share/ca-certificates';\nconst CUSTOM_CA_CERT_NAME = 'custom-ca-cert.crt';\nconst CERT_SUBJECT = [\n {\n name: 'commonName',\n value: 'Dependabot Internal CA'\n },\n {\n name: 'organizationName',\n value: 'GitHub ic.'\n },\n {\n shortName: 'OU',\n value: 'Dependabot'\n },\n {\n name: 'countryName',\n value: 'US'\n },\n {\n shortName: 'ST',\n value: 'California'\n },\n {\n name: 'localityName',\n value: 'San Francisco'\n }\n];\nclass ProxyBuilder {\n constructor(docker, proxyImage) {\n this.docker = docker;\n this.proxyImage = proxyImage;\n }\n run(jobId, credentials) {\n return __awaiter(this, void 0, void 0, function* () {\n const name = `dependabot-job-${jobId}-proxy`;\n const config = this.buildProxyConfig(credentials, jobId);\n const cert = config.ca.cert;\n const externalNetworkName = `dependabot-job-${jobId}-external-network`;\n const externalNetwork = yield this.ensureNetwork(externalNetworkName, false);\n const internalNetworkName = `dependabot-job-${jobId}-internal-network`;\n const internalNetwork = yield this.ensureNetwork(internalNetworkName, true);\n const container = yield this.createContainer(jobId, name, externalNetwork, internalNetwork, internalNetworkName);\n yield container_service_1.ContainerService.storeInput(CONFIG_FILE_NAME, CONFIG_FILE_PATH, container, config);\n const customCAPath = this.customCAPath();\n if (customCAPath) {\n core.info('Detected custom CA certificate, adding to proxy');\n const customCert = fs_1.default.readFileSync(customCAPath, 'utf8').toString();\n yield container_service_1.ContainerService.storeCert(CUSTOM_CA_CERT_NAME, CA_CERT_INPUT_PATH, container, customCert);\n }\n const stream = yield container.attach({\n stream: true,\n stdout: true,\n stderr: true\n });\n container.modem.demuxStream(stream, (0, utils_1.outStream)(' proxy'), (0, utils_1.errStream)(' proxy'));\n const url = () => __awaiter(this, void 0, void 0, function* () {\n const containerInfo = yield container.inspect();\n if (containerInfo.State.Running === true) {\n const ipAddress = containerInfo.NetworkSettings.Networks[`${internalNetworkName}`]\n .IPAddress;\n return `http://${config.proxy_auth.username}:${config.proxy_auth.password}@${ipAddress}:1080`;\n }\n else {\n throw new Error(\"proxy container isn't running\");\n }\n });\n return {\n container,\n network: internalNetwork,\n networkName: internalNetworkName,\n url,\n cert,\n shutdown: () => __awaiter(this, void 0, void 0, function* () {\n yield container.stop();\n yield container.remove();\n yield externalNetwork.remove();\n yield internalNetwork.remove();\n })\n };\n });\n }\n ensureNetwork(name, internal = true) {\n return __awaiter(this, void 0, void 0, function* () {\n const networks = yield this.docker.listNetworks({\n filters: JSON.stringify({ name: [name] })\n });\n if (networks.length > 0) {\n return this.docker.getNetwork(networks[0].Id);\n }\n else {\n return yield this.docker.createNetwork({ Name: name, Internal: internal });\n }\n });\n }\n buildProxyConfig(credentials, jobId) {\n const ca = this.generateCertificateAuthority();\n const password = crypto_1.default.randomBytes(20).toString('hex');\n const proxy_auth = {\n username: `${jobId}`,\n password\n };\n const config = { all_credentials: credentials, ca, proxy_auth };\n return config;\n }\n generateCertificateAuthority() {\n const keys = node_forge_1.pki.rsa.generateKeyPair(KEY_SIZE);\n const cert = node_forge_1.pki.createCertificate();\n cert.publicKey = keys.publicKey;\n cert.serialNumber = '01';\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + KEY_EXPIRY_YEARS);\n cert.setSubject(CERT_SUBJECT);\n cert.setIssuer(CERT_SUBJECT);\n cert.setExtensions([{ name: 'basicConstraints', cA: true }]);\n cert.sign(keys.privateKey);\n const pem = node_forge_1.pki.certificateToPem(cert);\n const key = node_forge_1.pki.privateKeyToPem(keys.privateKey);\n return { cert: pem, key };\n }\n createContainer(jobId, containerName, externalNetwork, internalNetwork, internalNetworkName) {\n return __awaiter(this, void 0, void 0, function* () {\n const container = yield this.docker.createContainer({\n Image: this.proxyImage,\n name: containerName,\n AttachStdout: true,\n AttachStderr: true,\n Env: [\n `http_proxy=${process.env.http_proxy || process.env.HTTP_PROXY || ''}`,\n `https_proxy=${process.env.https_proxy || process.env.HTTPS_PROXY || ''}`,\n `no_proxy=${process.env.no_proxy || process.env.NO_PROXY || ''}`,\n `JOB_ID=${jobId}`\n ],\n Entrypoint: [\n 'sh',\n '-c',\n '/usr/sbin/update-ca-certificates && /update-job-proxy'\n ],\n HostConfig: {\n NetworkMode: internalNetworkName\n }\n });\n yield externalNetwork.connect({ Container: container.id });\n core.info(`Created proxy container: ${container.id}`);\n return container;\n });\n }\n customCAPath() {\n if ('CUSTOM_CA_PATH' in process.env) {\n return process.env.CUSTOM_CA_PATH;\n }\n // default to node.js configuration\n return process.env.NODE_EXTRA_CA_CERTS;\n }\n}\nexports.ProxyBuilder = ProxyBuilder;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UpdaterBuilder = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst container_service_1 = require(\"./container-service\");\nconst JOB_OUTPUT_FILENAME = 'output.json';\nconst JOB_OUTPUT_PATH = '/home/dependabot/dependabot-updater/output';\nconst JOB_INPUT_FILENAME = 'job.json';\nconst JOB_INPUT_PATH = `/home/dependabot/dependabot-updater`;\nconst REPO_CONTENTS_PATH = '/home/dependabot/dependabot-updater/repo';\nconst CA_CERT_INPUT_PATH = '/usr/local/share/ca-certificates';\nconst CA_CERT_FILENAME = 'dbot-ca.crt';\nconst UPDATER_MAX_MEMORY = 8 * 1024 * 1024 * 1024; // 8GB in bytes\nclass UpdaterBuilder {\n constructor(docker, jobParams, input, outputHostPath, proxy, repoHostPath, updaterImage) {\n this.docker = docker;\n this.jobParams = jobParams;\n this.input = input;\n this.outputHostPath = outputHostPath;\n this.proxy = proxy;\n this.repoHostPath = repoHostPath;\n this.updaterImage = updaterImage;\n }\n run(containerName, updaterCommand) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = `(echo > /etc/ca-certificates.conf) &&\\\n rm -Rf /usr/share/ca-certificates/ &&\\\n /usr/sbin/update-ca-certificates &&\\\n $DEPENDABOT_HOME/dependabot-updater/bin/run ${updaterCommand}`;\n const proxyUrl = yield this.proxy.url();\n const container = yield this.docker.createContainer({\n Image: this.updaterImage,\n name: containerName,\n AttachStdout: true,\n AttachStderr: true,\n Env: [\n `GITHUB_ACTIONS=${process.env.GITHUB_ACTIONS}`,\n `DEPENDABOT_JOB_ID=${this.jobParams.jobId}`,\n `DEPENDABOT_JOB_TOKEN=${this.jobParams.jobToken}`,\n `DEPENDABOT_JOB_PATH=${JOB_INPUT_PATH}/${JOB_INPUT_FILENAME}`,\n `DEPENDABOT_OPEN_TIMEOUT_IN_SECONDS=15`,\n `DEPENDABOT_OUTPUT_PATH=${JOB_OUTPUT_PATH}/${JOB_OUTPUT_FILENAME}`,\n `DEPENDABOT_REPO_CONTENTS_PATH=${REPO_CONTENTS_PATH}`,\n `DEPENDABOT_API_URL=${this.jobParams.dependabotApiDockerUrl}`,\n `SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt`,\n `http_proxy=${proxyUrl}`,\n `HTTP_PROXY=${proxyUrl}`,\n `https_proxy=${proxyUrl}`,\n `HTTPS_PROXY=${proxyUrl}`,\n `ENABLE_CONNECTIVITY_CHECK=1`\n ],\n User: 'root',\n Cmd: ['sh', '-c', cmd],\n HostConfig: {\n Memory: UPDATER_MAX_MEMORY,\n NetworkMode: this.proxy.networkName,\n Binds: [\n `${this.outputHostPath}:${JOB_OUTPUT_PATH}:rw`,\n `${this.repoHostPath}:${REPO_CONTENTS_PATH}:rw`\n ]\n }\n });\n yield container_service_1.ContainerService.storeCert(CA_CERT_FILENAME, CA_CERT_INPUT_PATH, container, this.proxy.cert);\n yield container_service_1.ContainerService.storeInput(JOB_INPUT_FILENAME, JOB_INPUT_PATH, container, this.input);\n core.info(`Created ${updaterCommand} container: ${container.id}`);\n return container;\n });\n }\n}\nexports.UpdaterBuilder = UpdaterBuilder;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Updater = exports.UpdaterFetchError = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst dockerode_1 = __importDefault(require(\"dockerode\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst fs_1 = __importDefault(require(\"fs\"));\nconst container_service_1 = require(\"./container-service\");\nconst utils_1 = require(\"./utils\");\nconst proxy_1 = require(\"./proxy\");\nconst updater_builder_1 = require(\"./updater-builder\");\nclass UpdaterFetchError extends Error {\n constructor(msg) {\n super(msg);\n Object.setPrototypeOf(this, UpdaterFetchError.prototype);\n }\n}\nexports.UpdaterFetchError = UpdaterFetchError;\nclass Updater {\n constructor(updaterImage, proxyImage, apiClient, details, credentials, workingDirectory) {\n this.updaterImage = updaterImage;\n this.proxyImage = proxyImage;\n this.apiClient = apiClient;\n this.details = details;\n this.credentials = credentials;\n this.workingDirectory = workingDirectory;\n this.docker = new dockerode_1.default();\n this.outputHostPath = path_1.default.join(workingDirectory, 'output');\n this.repoHostPath = path_1.default.join(workingDirectory, 'repo');\n }\n /**\n * Execute an update job and report the result to Dependabot API.\n */\n runUpdater() {\n return __awaiter(this, void 0, void 0, function* () {\n // Create required folders in the workingDirectory\n fs_1.default.mkdirSync(this.outputHostPath);\n fs_1.default.mkdirSync(this.repoHostPath);\n const proxy = yield new proxy_1.ProxyBuilder(this.docker, this.proxyImage).run(this.apiClient.params.jobId, this.credentials);\n yield proxy.container.start();\n try {\n const files = yield this.runFileFetcher(proxy);\n yield this.runFileUpdater(proxy, files);\n return true;\n }\n finally {\n yield this.cleanup(proxy);\n }\n });\n }\n runFileFetcher(proxy) {\n return __awaiter(this, void 0, void 0, function* () {\n const name = `dependabot-job-${this.apiClient.params.jobId}-file-fetcher`;\n const container = yield this.createContainer(proxy, name, 'fetch_files', {\n job: this.details\n });\n yield container_service_1.ContainerService.run(container);\n const outputPath = path_1.default.join(this.outputHostPath, 'output.json');\n if (!fs_1.default.existsSync(outputPath)) {\n throw new UpdaterFetchError('No output.json created by the fetcher container');\n }\n const fileFetcherSync = fs_1.default.readFileSync(outputPath).toString();\n const fileFetcherOutput = JSON.parse(fileFetcherSync);\n const fetchedFiles = {\n base_commit_sha: fileFetcherOutput.base_commit_sha,\n base64_dependency_files: fileFetcherOutput.base64_dependency_files,\n dependency_files: fileFetcherOutput.base64_dependency_files.map((file) => (0, utils_1.base64DecodeDependencyFile)(file))\n };\n return fetchedFiles;\n });\n }\n runFileUpdater(proxy, files) {\n return __awaiter(this, void 0, void 0, function* () {\n core.info(`Running update job ${this.apiClient.params.jobId}`);\n const name = `dependabot-job-${this.apiClient.params.jobId}-updater`;\n const containerInput = {\n base_commit_sha: files.base_commit_sha,\n base64_dependency_files: files.base64_dependency_files,\n dependency_files: files.dependency_files,\n job: this.details\n };\n const container = yield this.createContainer(proxy, name, 'update_files', containerInput);\n yield container_service_1.ContainerService.run(container);\n });\n }\n createContainer(proxy, containerName, updaterCommand, input) {\n return __awaiter(this, void 0, void 0, function* () {\n return new updater_builder_1.UpdaterBuilder(this.docker, this.apiClient.params, input, this.outputHostPath, proxy, this.repoHostPath, this.updaterImage).run(containerName, updaterCommand);\n });\n }\n cleanup(proxy) {\n return __awaiter(this, void 0, void 0, function* () {\n yield proxy.shutdown();\n if (fs_1.default.existsSync(this.outputHostPath)) {\n fs_1.default.rmdirSync(this.outputHostPath, { recursive: true });\n }\n if (fs_1.default.existsSync(this.repoHostPath)) {\n fs_1.default.rmdirSync(this.repoHostPath, { recursive: true });\n }\n });\n }\n}\nexports.Updater = Updater;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.errStream = exports.outStream = exports.base64DecodeDependencyFile = void 0;\nconst stream_1 = __importDefault(require(\"stream\"));\nconst base64Decode = (str) => Buffer.from(str, 'base64').toString('binary');\nconst base64DecodeDependencyFile = (file) => {\n const fileCopy = JSON.parse(JSON.stringify(file));\n fileCopy.content = base64Decode(fileCopy.content);\n return fileCopy;\n};\nexports.base64DecodeDependencyFile = base64DecodeDependencyFile;\nconst outStream = (prefix) => {\n return new stream_1.default.Writable({\n write(chunk, _, next) {\n process.stderr.write(`${prefix} | ${chunk.toString()}`);\n next();\n }\n });\n};\nexports.outStream = outStream;\nconst errStream = (prefix) => {\n return new stream_1.default.Writable({\n write(chunk, _, next) {\n process.stderr.write(`${prefix} | ${chunk.toString()}`);\n next();\n }\n });\n};\nexports.errStream = errStream;\n","module.exports = __non_webpack_require__(__webpack_require__.ab + \"build/Release/cpufeatures.node\")","module.exports = __non_webpack_require__(__webpack_require__.ab + \"lib/protocol/crypto/build/Release/sshcrypto.node\")",null,"module.exports = require(\"assert\");","module.exports = require(\"buffer\");","module.exports = require(\"child_process\");","module.exports = require(\"constants\");","module.exports = require(\"crypto\");","module.exports = require(\"dns\");","module.exports = require(\"events\");","module.exports = require(\"fs\");","module.exports = require(\"http\");","module.exports = require(\"https\");","module.exports = require(\"net\");","module.exports = require(\"os\");","module.exports = require(\"path\");","module.exports = require(\"punycode\");","module.exports = require(\"querystring\");","module.exports = require(\"stream\");","module.exports = require(\"string_decoder\");","module.exports = require(\"tls\");","module.exports = require(\"tty\");","module.exports = require(\"url\");","module.exports = require(\"util\");","module.exports = require(\"zlib\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\tvar threw = true;\n\ttry {\n\t\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\t\tthrew = false;\n\t} finally {\n\t\tif(threw) delete __webpack_module_cache__[moduleId];\n\t}\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","\nif (typeof __webpack_require__ !== 'undefined') __webpack_require__.ab = __dirname + \"/\";","","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(399);\n",""],"names":[],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"index.js","mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3oBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1WA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjnEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3iBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtKA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACniBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5jCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvyDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7CA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClkCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACz5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACt+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/iCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/uCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5OA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3uCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC55DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3OA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzrIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3lFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzqGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjFA;AACA;AACA;;;;;;;;ACFA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnmCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1BA;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtSA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9lEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvlEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn9HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjkDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpwCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC38CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn2CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7jCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3YA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtSA;AACA;;;;;;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChUA;AACA;;;;;;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9RA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACn1EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC3NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACr0BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/IA;AACA;AACA;AACA;AACA;;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1uEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACzgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5lBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5kBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnmEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACj7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1jBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACroBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrRA;;;;;;;;ACAA;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC5LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACxEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACvMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChoBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjBA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC9KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACjIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACrLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;ACzMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/BA;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC7BA;AACA;;;;AEDA;AACA;AACA;AACA","sources":[".././node_modules/@actions/core/lib/command.js",".././node_modules/@actions/core/lib/core.js",".././node_modules/@actions/core/lib/file-command.js",".././node_modules/@actions/core/lib/oidc-utils.js",".././node_modules/@actions/core/lib/path-utils.js",".././node_modules/@actions/core/lib/summary.js",".././node_modules/@actions/core/lib/utils.js",".././node_modules/@actions/github/lib/context.js",".././node_modules/@actions/github/lib/github.js",".././node_modules/@actions/github/lib/internal/utils.js",".././node_modules/@actions/github/lib/utils.js",".././node_modules/@actions/http-client/lib/auth.js",".././node_modules/@actions/http-client/lib/index.js",".././node_modules/@actions/http-client/lib/proxy.js",".././node_modules/@balena/dockerignore/ignore.js",".././node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js",".././node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js",".././node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js",".././node_modules/@fastify/busboy/deps/streamsearch/sbmh.js",".././node_modules/@fastify/busboy/lib/main.js",".././node_modules/@fastify/busboy/lib/types/multipart.js",".././node_modules/@fastify/busboy/lib/types/urlencoded.js",".././node_modules/@fastify/busboy/lib/utils/Decoder.js",".././node_modules/@fastify/busboy/lib/utils/basename.js",".././node_modules/@fastify/busboy/lib/utils/decodeText.js",".././node_modules/@fastify/busboy/lib/utils/getLimit.js",".././node_modules/@fastify/busboy/lib/utils/parseParams.js",".././node_modules/@octokit/auth-token/dist-node/index.js",".././node_modules/@octokit/core/dist-node/index.js",".././node_modules/@octokit/endpoint/dist-node/index.js",".././node_modules/@octokit/graphql/dist-node/index.js",".././node_modules/@octokit/plugin-paginate-rest/dist-node/index.js",".././node_modules/@octokit/plugin-rest-endpoint-methods/dist-node/index.js",".././node_modules/@octokit/request-error/dist-node/index.js",".././node_modules/@octokit/request/dist-node/index.js",".././node_modules/asn1/lib/ber/errors.js",".././node_modules/asn1/lib/ber/index.js",".././node_modules/asn1/lib/ber/reader.js",".././node_modules/asn1/lib/ber/types.js",".././node_modules/asn1/lib/ber/writer.js",".././node_modules/asn1/lib/index.js",".././node_modules/b4a/index.js",".././node_modules/bcrypt-pbkdf/index.js",".././node_modules/before-after-hook/index.js",".././node_modules/before-after-hook/lib/add.js",".././node_modules/before-after-hook/lib/register.js",".././node_modules/before-after-hook/lib/remove.js",".././node_modules/chownr/chownr.js",".././node_modules/cpu-features/lib/index.js",".././node_modules/debug/src/browser.js",".././node_modules/debug/src/common.js",".././node_modules/debug/src/index.js",".././node_modules/debug/src/node.js",".././node_modules/deprecation/dist-node/index.js",".././node_modules/docker-modem/lib/http.js",".././node_modules/docker-modem/lib/http_duplex.js",".././node_modules/docker-modem/lib/modem.js",".././node_modules/docker-modem/lib/ssh.js",".././node_modules/docker-modem/lib/utils.js",".././node_modules/dockerode/lib/config.js",".././node_modules/dockerode/lib/container.js",".././node_modules/dockerode/lib/docker.js",".././node_modules/dockerode/lib/exec.js",".././node_modules/dockerode/lib/image.js",".././node_modules/dockerode/lib/network.js",".././node_modules/dockerode/lib/node.js",".././node_modules/dockerode/lib/plugin.js",".././node_modules/dockerode/lib/secret.js",".././node_modules/dockerode/lib/service.js",".././node_modules/dockerode/lib/task.js",".././node_modules/dockerode/lib/util.js",".././node_modules/dockerode/lib/volume.js",".././node_modules/end-of-stream/index.js",".././node_modules/fast-fifo/fixed-size.js",".././node_modules/fast-fifo/index.js",".././node_modules/fs-constants/index.js",".././node_modules/has-flag/index.js",".././node_modules/inherits/inherits.js",".././node_modules/inherits/inherits_browser.js",".././node_modules/mkdirp-classic/index.js",".././node_modules/ms/index.js",".././node_modules/node-forge/lib/aes.js",".././node_modules/node-forge/lib/aesCipherSuites.js",".././node_modules/node-forge/lib/asn1-validator.js",".././node_modules/node-forge/lib/asn1.js",".././node_modules/node-forge/lib/baseN.js",".././node_modules/node-forge/lib/cipher.js",".././node_modules/node-forge/lib/cipherModes.js",".././node_modules/node-forge/lib/des.js",".././node_modules/node-forge/lib/ed25519.js",".././node_modules/node-forge/lib/forge.js",".././node_modules/node-forge/lib/hmac.js",".././node_modules/node-forge/lib/index.js",".././node_modules/node-forge/lib/jsbn.js",".././node_modules/node-forge/lib/kem.js",".././node_modules/node-forge/lib/log.js",".././node_modules/node-forge/lib/md.all.js",".././node_modules/node-forge/lib/md.js",".././node_modules/node-forge/lib/md5.js",".././node_modules/node-forge/lib/mgf.js",".././node_modules/node-forge/lib/mgf1.js",".././node_modules/node-forge/lib/oids.js",".././node_modules/node-forge/lib/pbe.js",".././node_modules/node-forge/lib/pbkdf2.js",".././node_modules/node-forge/lib/pem.js",".././node_modules/node-forge/lib/pkcs1.js",".././node_modules/node-forge/lib/pkcs12.js",".././node_modules/node-forge/lib/pkcs7.js",".././node_modules/node-forge/lib/pkcs7asn1.js",".././node_modules/node-forge/lib/pki.js",".././node_modules/node-forge/lib/prime.js",".././node_modules/node-forge/lib/prng.js",".././node_modules/node-forge/lib/pss.js",".././node_modules/node-forge/lib/random.js",".././node_modules/node-forge/lib/rc2.js",".././node_modules/node-forge/lib/rsa.js",".././node_modules/node-forge/lib/sha1.js",".././node_modules/node-forge/lib/sha256.js",".././node_modules/node-forge/lib/sha512.js",".././node_modules/node-forge/lib/ssh.js",".././node_modules/node-forge/lib/tls.js",".././node_modules/node-forge/lib/util.js",".././node_modules/node-forge/lib/x509.js",".././node_modules/once/once.js",".././node_modules/pump/index.js",".././node_modules/queue-tick/process-next-tick.js",".././node_modules/queue-tick/queue-microtask.js",".././node_modules/readable-stream/errors.js",".././node_modules/readable-stream/lib/_stream_duplex.js",".././node_modules/readable-stream/lib/_stream_passthrough.js",".././node_modules/readable-stream/lib/_stream_readable.js",".././node_modules/readable-stream/lib/_stream_transform.js",".././node_modules/readable-stream/lib/_stream_writable.js",".././node_modules/readable-stream/lib/internal/streams/async_iterator.js",".././node_modules/readable-stream/lib/internal/streams/buffer_list.js",".././node_modules/readable-stream/lib/internal/streams/destroy.js",".././node_modules/readable-stream/lib/internal/streams/end-of-stream.js",".././node_modules/readable-stream/lib/internal/streams/from.js",".././node_modules/readable-stream/lib/internal/streams/pipeline.js",".././node_modules/readable-stream/lib/internal/streams/state.js",".././node_modules/readable-stream/lib/internal/streams/stream.js",".././node_modules/readable-stream/readable.js",".././node_modules/safer-buffer/safer.js",".././node_modules/split-ca/index.js",".././node_modules/ssh2/lib/Channel.js",".././node_modules/ssh2/lib/agent.js",".././node_modules/ssh2/lib/client.js",".././node_modules/ssh2/lib/http-agents.js",".././node_modules/ssh2/lib/index.js",".././node_modules/ssh2/lib/keygen.js",".././node_modules/ssh2/lib/protocol/Protocol.js",".././node_modules/ssh2/lib/protocol/SFTP.js",".././node_modules/ssh2/lib/protocol/constants.js",".././node_modules/ssh2/lib/protocol/crypto.js",".././node_modules/ssh2/lib/protocol/crypto/poly1305.js",".././node_modules/ssh2/lib/protocol/handlers.js",".././node_modules/ssh2/lib/protocol/handlers.misc.js",".././node_modules/ssh2/lib/protocol/kex.js",".././node_modules/ssh2/lib/protocol/keyParser.js",".././node_modules/ssh2/lib/protocol/node-fs-compat.js",".././node_modules/ssh2/lib/protocol/utils.js",".././node_modules/ssh2/lib/protocol/zlib.js",".././node_modules/ssh2/lib/server.js",".././node_modules/ssh2/lib/utils.js",".././node_modules/streamx/index.js",".././node_modules/string_decoder/lib/string_decoder.js",".././node_modules/string_decoder/node_modules/safe-buffer/index.js",".././node_modules/supports-color/index.js",".././node_modules/tar-fs/index.js",".././node_modules/tar-fs/node_modules/bl/BufferList.js",".././node_modules/tar-fs/node_modules/bl/bl.js",".././node_modules/tar-fs/node_modules/tar-stream/extract.js",".././node_modules/tar-fs/node_modules/tar-stream/headers.js",".././node_modules/tar-fs/node_modules/tar-stream/index.js",".././node_modules/tar-fs/node_modules/tar-stream/pack.js",".././node_modules/tar-stream/constants.js",".././node_modules/tar-stream/extract.js",".././node_modules/tar-stream/headers.js",".././node_modules/tar-stream/index.js",".././node_modules/tar-stream/pack.js",".././node_modules/tunnel/index.js",".././node_modules/tunnel/lib/tunnel.js",".././node_modules/tweetnacl/nacl-fast.js",".././node_modules/undici/index.js",".././node_modules/undici/lib/agent.js",".././node_modules/undici/lib/api/abort-signal.js",".././node_modules/undici/lib/api/api-connect.js",".././node_modules/undici/lib/api/api-pipeline.js",".././node_modules/undici/lib/api/api-request.js",".././node_modules/undici/lib/api/api-stream.js",".././node_modules/undici/lib/api/api-upgrade.js",".././node_modules/undici/lib/api/index.js",".././node_modules/undici/lib/api/readable.js",".././node_modules/undici/lib/api/util.js",".././node_modules/undici/lib/balanced-pool.js",".././node_modules/undici/lib/cache/cache.js",".././node_modules/undici/lib/cache/cachestorage.js",".././node_modules/undici/lib/cache/symbols.js",".././node_modules/undici/lib/cache/util.js",".././node_modules/undici/lib/client.js",".././node_modules/undici/lib/compat/dispatcher-weakref.js",".././node_modules/undici/lib/cookies/constants.js",".././node_modules/undici/lib/cookies/index.js",".././node_modules/undici/lib/cookies/parse.js",".././node_modules/undici/lib/cookies/util.js",".././node_modules/undici/lib/core/connect.js",".././node_modules/undici/lib/core/constants.js",".././node_modules/undici/lib/core/errors.js",".././node_modules/undici/lib/core/request.js",".././node_modules/undici/lib/core/symbols.js",".././node_modules/undici/lib/core/util.js",".././node_modules/undici/lib/dispatcher-base.js",".././node_modules/undici/lib/dispatcher.js",".././node_modules/undici/lib/fetch/body.js",".././node_modules/undici/lib/fetch/constants.js",".././node_modules/undici/lib/fetch/dataURL.js",".././node_modules/undici/lib/fetch/file.js",".././node_modules/undici/lib/fetch/formdata.js",".././node_modules/undici/lib/fetch/global.js",".././node_modules/undici/lib/fetch/headers.js",".././node_modules/undici/lib/fetch/index.js",".././node_modules/undici/lib/fetch/request.js",".././node_modules/undici/lib/fetch/response.js",".././node_modules/undici/lib/fetch/symbols.js",".././node_modules/undici/lib/fetch/util.js",".././node_modules/undici/lib/fetch/webidl.js",".././node_modules/undici/lib/fileapi/encoding.js",".././node_modules/undici/lib/fileapi/filereader.js",".././node_modules/undici/lib/fileapi/progressevent.js",".././node_modules/undici/lib/fileapi/symbols.js",".././node_modules/undici/lib/fileapi/util.js",".././node_modules/undici/lib/global.js",".././node_modules/undici/lib/handler/DecoratorHandler.js",".././node_modules/undici/lib/handler/RedirectHandler.js",".././node_modules/undici/lib/handler/RetryHandler.js",".././node_modules/undici/lib/interceptor/redirectInterceptor.js",".././node_modules/undici/lib/llhttp/constants.js",".././node_modules/undici/lib/llhttp/llhttp-wasm.js",".././node_modules/undici/lib/llhttp/llhttp_simd-wasm.js",".././node_modules/undici/lib/llhttp/utils.js",".././node_modules/undici/lib/mock/mock-agent.js",".././node_modules/undici/lib/mock/mock-client.js",".././node_modules/undici/lib/mock/mock-errors.js",".././node_modules/undici/lib/mock/mock-interceptor.js",".././node_modules/undici/lib/mock/mock-pool.js",".././node_modules/undici/lib/mock/mock-symbols.js",".././node_modules/undici/lib/mock/mock-utils.js",".././node_modules/undici/lib/mock/pending-interceptors-formatter.js",".././node_modules/undici/lib/mock/pluralizer.js",".././node_modules/undici/lib/node/fixed-queue.js",".././node_modules/undici/lib/pool-base.js",".././node_modules/undici/lib/pool-stats.js",".././node_modules/undici/lib/pool.js",".././node_modules/undici/lib/proxy-agent.js",".././node_modules/undici/lib/timers.js",".././node_modules/undici/lib/websocket/connection.js",".././node_modules/undici/lib/websocket/constants.js",".././node_modules/undici/lib/websocket/events.js",".././node_modules/undici/lib/websocket/frame.js",".././node_modules/undici/lib/websocket/receiver.js",".././node_modules/undici/lib/websocket/symbols.js",".././node_modules/undici/lib/websocket/util.js",".././node_modules/undici/lib/websocket/websocket.js",".././node_modules/universal-user-agent/dist-node/index.js",".././node_modules/util-deprecate/node.js",".././node_modules/uuid/dist/index.js",".././node_modules/uuid/dist/md5.js",".././node_modules/uuid/dist/nil.js",".././node_modules/uuid/dist/parse.js",".././node_modules/uuid/dist/regex.js",".././node_modules/uuid/dist/rng.js",".././node_modules/uuid/dist/sha1.js",".././node_modules/uuid/dist/stringify.js",".././node_modules/uuid/dist/v1.js",".././node_modules/uuid/dist/v3.js",".././node_modules/uuid/dist/v35.js",".././node_modules/uuid/dist/v4.js",".././node_modules/uuid/dist/v5.js",".././node_modules/uuid/dist/validate.js",".././node_modules/uuid/dist/version.js",".././node_modules/wrappy/wrappy.js",".././src/api-client.ts",".././src/container-service.ts",".././src/docker-tags.ts",".././src/image-service.ts",".././src/inputs.ts",".././src/main.ts",".././src/proxy.ts",".././src/updater-builder.ts",".././src/updater.ts",".././src/utils.ts",".././node_modules/cpu-features/build/Release/cpufeatures.node",".././node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node","../external node-commonjs \"assert\"","../external node-commonjs \"async_hooks\"","../external node-commonjs \"buffer\"","../external node-commonjs \"child_process\"","../external node-commonjs \"console\"","../external node-commonjs \"constants\"","../external node-commonjs \"crypto\"","../external node-commonjs \"diagnostics_channel\"","../external node-commonjs \"dns\"","../external node-commonjs \"events\"","../external node-commonjs \"fs\"","../external node-commonjs \"http\"","../external node-commonjs \"http2\"","../external node-commonjs \"https\"","../external node-commonjs \"net\"","../external node-commonjs \"node:events\"","../external node-commonjs \"node:stream\"","../external node-commonjs \"node:util\"","../external node-commonjs \"os\"","../external node-commonjs \"path\"","../external node-commonjs \"perf_hooks\"","../external node-commonjs \"querystring\"","../external node-commonjs \"stream\"","../external node-commonjs \"stream/web\"","../external node-commonjs \"string_decoder\"","../external node-commonjs \"tls\"","../external node-commonjs \"tty\"","../external node-commonjs \"url\"","../external node-commonjs \"util\"","../external node-commonjs \"util/types\"","../external node-commonjs \"worker_threads\"","../external node-commonjs \"zlib\"","../webpack/bootstrap","../webpack/runtime/compat","../webpack/before-startup","../webpack/startup","../webpack/after-startup"],"sourcesContent":["\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issue = exports.issueCommand = void 0;\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\n/**\n * Commands\n *\n * Command Format:\n * ::name key=value,key=value::message\n *\n * Examples:\n * ::warning::This is the message\n * ::set-env name=MY_VAR::some value\n */\nfunction issueCommand(command, properties, message) {\n const cmd = new Command(command, properties, message);\n process.stdout.write(cmd.toString() + os.EOL);\n}\nexports.issueCommand = issueCommand;\nfunction issue(name, message = '') {\n issueCommand(name, {}, message);\n}\nexports.issue = issue;\nconst CMD_STRING = '::';\nclass Command {\n constructor(command, properties, message) {\n if (!command) {\n command = 'missing.command';\n }\n this.command = command;\n this.properties = properties;\n this.message = message;\n }\n toString() {\n let cmdStr = CMD_STRING + this.command;\n if (this.properties && Object.keys(this.properties).length > 0) {\n cmdStr += ' ';\n let first = true;\n for (const key in this.properties) {\n if (this.properties.hasOwnProperty(key)) {\n const val = this.properties[key];\n if (val) {\n if (first) {\n first = false;\n }\n else {\n cmdStr += ',';\n }\n cmdStr += `${key}=${escapeProperty(val)}`;\n }\n }\n }\n }\n cmdStr += `${CMD_STRING}${escapeData(this.message)}`;\n return cmdStr;\n }\n}\nfunction escapeData(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A');\n}\nfunction escapeProperty(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n}\n//# sourceMappingURL=command.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;\nconst command_1 = require(\"./command\");\nconst file_command_1 = require(\"./file-command\");\nconst utils_1 = require(\"./utils\");\nconst os = __importStar(require(\"os\"));\nconst path = __importStar(require(\"path\"));\nconst oidc_utils_1 = require(\"./oidc-utils\");\n/**\n * The code to exit an action\n */\nvar ExitCode;\n(function (ExitCode) {\n /**\n * A code indicating that the action was successful\n */\n ExitCode[ExitCode[\"Success\"] = 0] = \"Success\";\n /**\n * A code indicating that the action was a failure\n */\n ExitCode[ExitCode[\"Failure\"] = 1] = \"Failure\";\n})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));\n//-----------------------------------------------------------------------\n// Variables\n//-----------------------------------------------------------------------\n/**\n * Sets env variable for this action and future actions in the job\n * @param name the name of the variable to set\n * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction exportVariable(name, val) {\n const convertedVal = utils_1.toCommandValue(val);\n process.env[name] = convertedVal;\n const filePath = process.env['GITHUB_ENV'] || '';\n if (filePath) {\n return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val));\n }\n command_1.issueCommand('set-env', { name }, convertedVal);\n}\nexports.exportVariable = exportVariable;\n/**\n * Registers a secret which will get masked from logs\n * @param secret value of the secret\n */\nfunction setSecret(secret) {\n command_1.issueCommand('add-mask', {}, secret);\n}\nexports.setSecret = setSecret;\n/**\n * Prepends inputPath to the PATH (for this action and future actions)\n * @param inputPath\n */\nfunction addPath(inputPath) {\n const filePath = process.env['GITHUB_PATH'] || '';\n if (filePath) {\n file_command_1.issueFileCommand('PATH', inputPath);\n }\n else {\n command_1.issueCommand('add-path', {}, inputPath);\n }\n process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;\n}\nexports.addPath = addPath;\n/**\n * Gets the value of an input.\n * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.\n * Returns an empty string if the value is not defined.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string\n */\nfunction getInput(name, options) {\n const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';\n if (options && options.required && !val) {\n throw new Error(`Input required and not supplied: ${name}`);\n }\n if (options && options.trimWhitespace === false) {\n return val;\n }\n return val.trim();\n}\nexports.getInput = getInput;\n/**\n * Gets the values of an multiline input. Each value is also trimmed.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string[]\n *\n */\nfunction getMultilineInput(name, options) {\n const inputs = getInput(name, options)\n .split('\\n')\n .filter(x => x !== '');\n if (options && options.trimWhitespace === false) {\n return inputs;\n }\n return inputs.map(input => input.trim());\n}\nexports.getMultilineInput = getMultilineInput;\n/**\n * Gets the input value of the boolean type in the YAML 1.2 \"core schema\" specification.\n * Support boolean input list: `true | True | TRUE | false | False | FALSE` .\n * The return value is also in boolean type.\n * ref: https://yaml.org/spec/1.2/spec.html#id2804923\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns boolean\n */\nfunction getBooleanInput(name, options) {\n const trueValue = ['true', 'True', 'TRUE'];\n const falseValue = ['false', 'False', 'FALSE'];\n const val = getInput(name, options);\n if (trueValue.includes(val))\n return true;\n if (falseValue.includes(val))\n return false;\n throw new TypeError(`Input does not meet YAML 1.2 \"Core Schema\" specification: ${name}\\n` +\n `Support boolean input list: \\`true | True | TRUE | false | False | FALSE\\``);\n}\nexports.getBooleanInput = getBooleanInput;\n/**\n * Sets the value of an output.\n *\n * @param name name of the output to set\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setOutput(name, value) {\n const filePath = process.env['GITHUB_OUTPUT'] || '';\n if (filePath) {\n return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value));\n }\n process.stdout.write(os.EOL);\n command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value));\n}\nexports.setOutput = setOutput;\n/**\n * Enables or disables the echoing of commands into stdout for the rest of the step.\n * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.\n *\n */\nfunction setCommandEcho(enabled) {\n command_1.issue('echo', enabled ? 'on' : 'off');\n}\nexports.setCommandEcho = setCommandEcho;\n//-----------------------------------------------------------------------\n// Results\n//-----------------------------------------------------------------------\n/**\n * Sets the action status to failed.\n * When the action exits it will be with an exit code of 1\n * @param message add error issue message\n */\nfunction setFailed(message) {\n process.exitCode = ExitCode.Failure;\n error(message);\n}\nexports.setFailed = setFailed;\n//-----------------------------------------------------------------------\n// Logging Commands\n//-----------------------------------------------------------------------\n/**\n * Gets whether Actions Step Debug is on or not\n */\nfunction isDebug() {\n return process.env['RUNNER_DEBUG'] === '1';\n}\nexports.isDebug = isDebug;\n/**\n * Writes debug message to user log\n * @param message debug message\n */\nfunction debug(message) {\n command_1.issueCommand('debug', {}, message);\n}\nexports.debug = debug;\n/**\n * Adds an error issue\n * @param message error issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction error(message, properties = {}) {\n command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.error = error;\n/**\n * Adds a warning issue\n * @param message warning issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction warning(message, properties = {}) {\n command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.warning = warning;\n/**\n * Adds a notice issue\n * @param message notice issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction notice(message, properties = {}) {\n command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);\n}\nexports.notice = notice;\n/**\n * Writes info to log with console.log.\n * @param message info message\n */\nfunction info(message) {\n process.stdout.write(message + os.EOL);\n}\nexports.info = info;\n/**\n * Begin an output group.\n *\n * Output until the next `groupEnd` will be foldable in this group\n *\n * @param name The name of the output group\n */\nfunction startGroup(name) {\n command_1.issue('group', name);\n}\nexports.startGroup = startGroup;\n/**\n * End an output group.\n */\nfunction endGroup() {\n command_1.issue('endgroup');\n}\nexports.endGroup = endGroup;\n/**\n * Wrap an asynchronous function call in a group.\n *\n * Returns the same type as the function itself.\n *\n * @param name The name of the group\n * @param fn The function to wrap in the group\n */\nfunction group(name, fn) {\n return __awaiter(this, void 0, void 0, function* () {\n startGroup(name);\n let result;\n try {\n result = yield fn();\n }\n finally {\n endGroup();\n }\n return result;\n });\n}\nexports.group = group;\n//-----------------------------------------------------------------------\n// Wrapper action state\n//-----------------------------------------------------------------------\n/**\n * Saves state for current action, the state can only be retrieved by this action's post job execution.\n *\n * @param name name of the state to store\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction saveState(name, value) {\n const filePath = process.env['GITHUB_STATE'] || '';\n if (filePath) {\n return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value));\n }\n command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value));\n}\nexports.saveState = saveState;\n/**\n * Gets the value of an state set by this action's main execution.\n *\n * @param name name of the state to get\n * @returns string\n */\nfunction getState(name) {\n return process.env[`STATE_${name}`] || '';\n}\nexports.getState = getState;\nfunction getIDToken(aud) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield oidc_utils_1.OidcClient.getIDToken(aud);\n });\n}\nexports.getIDToken = getIDToken;\n/**\n * Summary exports\n */\nvar summary_1 = require(\"./summary\");\nObject.defineProperty(exports, \"summary\", { enumerable: true, get: function () { return summary_1.summary; } });\n/**\n * @deprecated use core.summary\n */\nvar summary_2 = require(\"./summary\");\nObject.defineProperty(exports, \"markdownSummary\", { enumerable: true, get: function () { return summary_2.markdownSummary; } });\n/**\n * Path exports\n */\nvar path_utils_1 = require(\"./path-utils\");\nObject.defineProperty(exports, \"toPosixPath\", { enumerable: true, get: function () { return path_utils_1.toPosixPath; } });\nObject.defineProperty(exports, \"toWin32Path\", { enumerable: true, get: function () { return path_utils_1.toWin32Path; } });\nObject.defineProperty(exports, \"toPlatformPath\", { enumerable: true, get: function () { return path_utils_1.toPlatformPath; } });\n//# sourceMappingURL=core.js.map","\"use strict\";\n// For internal use, subject to change.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.prepareKeyValueMessage = exports.issueFileCommand = void 0;\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst fs = __importStar(require(\"fs\"));\nconst os = __importStar(require(\"os\"));\nconst uuid_1 = require(\"uuid\");\nconst utils_1 = require(\"./utils\");\nfunction issueFileCommand(command, message) {\n const filePath = process.env[`GITHUB_${command}`];\n if (!filePath) {\n throw new Error(`Unable to find environment variable for file command ${command}`);\n }\n if (!fs.existsSync(filePath)) {\n throw new Error(`Missing file at path: ${filePath}`);\n }\n fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {\n encoding: 'utf8'\n });\n}\nexports.issueFileCommand = issueFileCommand;\nfunction prepareKeyValueMessage(key, value) {\n const delimiter = `ghadelimiter_${uuid_1.v4()}`;\n const convertedValue = utils_1.toCommandValue(value);\n // These should realistically never happen, but just in case someone finds a\n // way to exploit uuid generation let's not allow keys or values that contain\n // the delimiter.\n if (key.includes(delimiter)) {\n throw new Error(`Unexpected input: name should not contain the delimiter \"${delimiter}\"`);\n }\n if (convertedValue.includes(delimiter)) {\n throw new Error(`Unexpected input: value should not contain the delimiter \"${delimiter}\"`);\n }\n return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;\n}\nexports.prepareKeyValueMessage = prepareKeyValueMessage;\n//# sourceMappingURL=file-command.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OidcClient = void 0;\nconst http_client_1 = require(\"@actions/http-client\");\nconst auth_1 = require(\"@actions/http-client/lib/auth\");\nconst core_1 = require(\"./core\");\nclass OidcClient {\n static createHttpClient(allowRetry = true, maxRetry = 10) {\n const requestOptions = {\n allowRetries: allowRetry,\n maxRetries: maxRetry\n };\n return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);\n }\n static getRequestToken() {\n const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];\n if (!token) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');\n }\n return token;\n }\n static getIDTokenUrl() {\n const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];\n if (!runtimeUrl) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');\n }\n return runtimeUrl;\n }\n static getCall(id_token_url) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const httpclient = OidcClient.createHttpClient();\n const res = yield httpclient\n .getJson(id_token_url)\n .catch(error => {\n throw new Error(`Failed to get ID Token. \\n \n Error Code : ${error.statusCode}\\n \n Error Message: ${error.message}`);\n });\n const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;\n if (!id_token) {\n throw new Error('Response json body do not have ID Token field');\n }\n return id_token;\n });\n }\n static getIDToken(audience) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // New ID Token is requested from action service\n let id_token_url = OidcClient.getIDTokenUrl();\n if (audience) {\n const encodedAudience = encodeURIComponent(audience);\n id_token_url = `${id_token_url}&audience=${encodedAudience}`;\n }\n core_1.debug(`ID token url is ${id_token_url}`);\n const id_token = yield OidcClient.getCall(id_token_url);\n core_1.setSecret(id_token);\n return id_token;\n }\n catch (error) {\n throw new Error(`Error message: ${error.message}`);\n }\n });\n }\n}\nexports.OidcClient = OidcClient;\n//# sourceMappingURL=oidc-utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;\nconst path = __importStar(require(\"path\"));\n/**\n * toPosixPath converts the given path to the posix form. On Windows, \\\\ will be\n * replaced with /.\n *\n * @param pth. Path to transform.\n * @return string Posix path.\n */\nfunction toPosixPath(pth) {\n return pth.replace(/[\\\\]/g, '/');\n}\nexports.toPosixPath = toPosixPath;\n/**\n * toWin32Path converts the given path to the win32 form. On Linux, / will be\n * replaced with \\\\.\n *\n * @param pth. Path to transform.\n * @return string Win32 path.\n */\nfunction toWin32Path(pth) {\n return pth.replace(/[/]/g, '\\\\');\n}\nexports.toWin32Path = toWin32Path;\n/**\n * toPlatformPath converts the given path to a platform-specific path. It does\n * this by replacing instances of / and \\ with the platform-specific path\n * separator.\n *\n * @param pth The path to platformize.\n * @return string The platform-specific path.\n */\nfunction toPlatformPath(pth) {\n return pth.replace(/[/\\\\]/g, path.sep);\n}\nexports.toPlatformPath = toPlatformPath;\n//# sourceMappingURL=path-utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;\nconst os_1 = require(\"os\");\nconst fs_1 = require(\"fs\");\nconst { access, appendFile, writeFile } = fs_1.promises;\nexports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';\nexports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';\nclass Summary {\n constructor() {\n this._buffer = '';\n }\n /**\n * Finds the summary file path from the environment, rejects if env var is not found or file does not exist\n * Also checks r/w permissions.\n *\n * @returns step summary file path\n */\n filePath() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._filePath) {\n return this._filePath;\n }\n const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];\n if (!pathFromEnv) {\n throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);\n }\n try {\n yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);\n }\n catch (_a) {\n throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);\n }\n this._filePath = pathFromEnv;\n return this._filePath;\n });\n }\n /**\n * Wraps content in an HTML tag, adding any HTML attributes\n *\n * @param {string} tag HTML tag to wrap\n * @param {string | null} content content within the tag\n * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add\n *\n * @returns {string} content wrapped in HTML element\n */\n wrap(tag, content, attrs = {}) {\n const htmlAttrs = Object.entries(attrs)\n .map(([key, value]) => ` ${key}=\"${value}\"`)\n .join('');\n if (!content) {\n return `<${tag}${htmlAttrs}>`;\n }\n return `<${tag}${htmlAttrs}>${content}`;\n }\n /**\n * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.\n *\n * @param {SummaryWriteOptions} [options] (optional) options for write operation\n *\n * @returns {Promise} summary instance\n */\n write(options) {\n return __awaiter(this, void 0, void 0, function* () {\n const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);\n const filePath = yield this.filePath();\n const writeFunc = overwrite ? writeFile : appendFile;\n yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });\n return this.emptyBuffer();\n });\n }\n /**\n * Clears the summary buffer and wipes the summary file\n *\n * @returns {Summary} summary instance\n */\n clear() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.emptyBuffer().write({ overwrite: true });\n });\n }\n /**\n * Returns the current summary buffer as a string\n *\n * @returns {string} string of summary buffer\n */\n stringify() {\n return this._buffer;\n }\n /**\n * If the summary buffer is empty\n *\n * @returns {boolen} true if the buffer is empty\n */\n isEmptyBuffer() {\n return this._buffer.length === 0;\n }\n /**\n * Resets the summary buffer without writing to summary file\n *\n * @returns {Summary} summary instance\n */\n emptyBuffer() {\n this._buffer = '';\n return this;\n }\n /**\n * Adds raw text to the summary buffer\n *\n * @param {string} text content to add\n * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)\n *\n * @returns {Summary} summary instance\n */\n addRaw(text, addEOL = false) {\n this._buffer += text;\n return addEOL ? this.addEOL() : this;\n }\n /**\n * Adds the operating system-specific end-of-line marker to the buffer\n *\n * @returns {Summary} summary instance\n */\n addEOL() {\n return this.addRaw(os_1.EOL);\n }\n /**\n * Adds an HTML codeblock to the summary buffer\n *\n * @param {string} code content to render within fenced code block\n * @param {string} lang (optional) language to syntax highlight code\n *\n * @returns {Summary} summary instance\n */\n addCodeBlock(code, lang) {\n const attrs = Object.assign({}, (lang && { lang }));\n const element = this.wrap('pre', this.wrap('code', code), attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML list to the summary buffer\n *\n * @param {string[]} items list of items to render\n * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)\n *\n * @returns {Summary} summary instance\n */\n addList(items, ordered = false) {\n const tag = ordered ? 'ol' : 'ul';\n const listItems = items.map(item => this.wrap('li', item)).join('');\n const element = this.wrap(tag, listItems);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML table to the summary buffer\n *\n * @param {SummaryTableCell[]} rows table rows\n *\n * @returns {Summary} summary instance\n */\n addTable(rows) {\n const tableBody = rows\n .map(row => {\n const cells = row\n .map(cell => {\n if (typeof cell === 'string') {\n return this.wrap('td', cell);\n }\n const { header, data, colspan, rowspan } = cell;\n const tag = header ? 'th' : 'td';\n const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));\n return this.wrap(tag, data, attrs);\n })\n .join('');\n return this.wrap('tr', cells);\n })\n .join('');\n const element = this.wrap('table', tableBody);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds a collapsable HTML details element to the summary buffer\n *\n * @param {string} label text for the closed state\n * @param {string} content collapsable content\n *\n * @returns {Summary} summary instance\n */\n addDetails(label, content) {\n const element = this.wrap('details', this.wrap('summary', label) + content);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML image tag to the summary buffer\n *\n * @param {string} src path to the image you to embed\n * @param {string} alt text description of the image\n * @param {SummaryImageOptions} options (optional) addition image attributes\n *\n * @returns {Summary} summary instance\n */\n addImage(src, alt, options) {\n const { width, height } = options || {};\n const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));\n const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML section heading element\n *\n * @param {string} text heading text\n * @param {number | string} [level=1] (optional) the heading level, default: 1\n *\n * @returns {Summary} summary instance\n */\n addHeading(text, level) {\n const tag = `h${level}`;\n const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)\n ? tag\n : 'h1';\n const element = this.wrap(allowedTag, text);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML thematic break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addSeparator() {\n const element = this.wrap('hr', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML line break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addBreak() {\n const element = this.wrap('br', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML blockquote to the summary buffer\n *\n * @param {string} text quote text\n * @param {string} cite (optional) citation url\n *\n * @returns {Summary} summary instance\n */\n addQuote(text, cite) {\n const attrs = Object.assign({}, (cite && { cite }));\n const element = this.wrap('blockquote', text, attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML anchor tag to the summary buffer\n *\n * @param {string} text link text/content\n * @param {string} href hyperlink\n *\n * @returns {Summary} summary instance\n */\n addLink(text, href) {\n const element = this.wrap('a', text, { href });\n return this.addRaw(element).addEOL();\n }\n}\nconst _summary = new Summary();\n/**\n * @deprecated use `core.summary`\n */\nexports.markdownSummary = _summary;\nexports.summary = _summary;\n//# sourceMappingURL=summary.js.map","\"use strict\";\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toCommandProperties = exports.toCommandValue = void 0;\n/**\n * Sanitizes an input into a string so it can be passed into issueCommand safely\n * @param input input to sanitize into a string\n */\nfunction toCommandValue(input) {\n if (input === null || input === undefined) {\n return '';\n }\n else if (typeof input === 'string' || input instanceof String) {\n return input;\n }\n return JSON.stringify(input);\n}\nexports.toCommandValue = toCommandValue;\n/**\n *\n * @param annotationProperties\n * @returns The command properties to send with the actual annotation command\n * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646\n */\nfunction toCommandProperties(annotationProperties) {\n if (!Object.keys(annotationProperties).length) {\n return {};\n }\n return {\n title: annotationProperties.title,\n file: annotationProperties.file,\n line: annotationProperties.startLine,\n endLine: annotationProperties.endLine,\n col: annotationProperties.startColumn,\n endColumn: annotationProperties.endColumn\n };\n}\nexports.toCommandProperties = toCommandProperties;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Context = void 0;\nconst fs_1 = require(\"fs\");\nconst os_1 = require(\"os\");\nclass Context {\n /**\n * Hydrate the context from the environment\n */\n constructor() {\n var _a, _b, _c;\n this.payload = {};\n if (process.env.GITHUB_EVENT_PATH) {\n if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) {\n this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));\n }\n else {\n const path = process.env.GITHUB_EVENT_PATH;\n process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`);\n }\n }\n this.eventName = process.env.GITHUB_EVENT_NAME;\n this.sha = process.env.GITHUB_SHA;\n this.ref = process.env.GITHUB_REF;\n this.workflow = process.env.GITHUB_WORKFLOW;\n this.action = process.env.GITHUB_ACTION;\n this.actor = process.env.GITHUB_ACTOR;\n this.job = process.env.GITHUB_JOB;\n this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10);\n this.runId = parseInt(process.env.GITHUB_RUN_ID, 10);\n this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`;\n this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`;\n this.graphqlUrl =\n (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`;\n }\n get issue() {\n const payload = this.payload;\n return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number });\n }\n get repo() {\n if (process.env.GITHUB_REPOSITORY) {\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');\n return { owner, repo };\n }\n if (this.payload.repository) {\n return {\n owner: this.payload.repository.owner.login,\n repo: this.payload.repository.name\n };\n }\n throw new Error(\"context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'\");\n }\n}\nexports.Context = Context;\n//# sourceMappingURL=context.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokit = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst utils_1 = require(\"./utils\");\nexports.context = new Context.Context();\n/**\n * Returns a hydrated octokit ready to use for GitHub Actions\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokit(token, options, ...additionalPlugins) {\n const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins);\n return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options));\n}\nexports.getOctokit = getOctokit;\n//# sourceMappingURL=github.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0;\nconst httpClient = __importStar(require(\"@actions/http-client\"));\nconst undici_1 = require(\"undici\");\nfunction getAuthString(token, options) {\n if (!token && !options.auth) {\n throw new Error('Parameter token or opts.auth is required');\n }\n else if (token && options.auth) {\n throw new Error('Parameters token and opts.auth may not both be specified');\n }\n return typeof options.auth === 'string' ? options.auth : `token ${token}`;\n}\nexports.getAuthString = getAuthString;\nfunction getProxyAgent(destinationUrl) {\n const hc = new httpClient.HttpClient();\n return hc.getAgent(destinationUrl);\n}\nexports.getProxyAgent = getProxyAgent;\nfunction getProxyAgentDispatcher(destinationUrl) {\n const hc = new httpClient.HttpClient();\n return hc.getAgentDispatcher(destinationUrl);\n}\nexports.getProxyAgentDispatcher = getProxyAgentDispatcher;\nfunction getProxyFetch(destinationUrl) {\n const httpDispatcher = getProxyAgentDispatcher(destinationUrl);\n const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () {\n return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher }));\n });\n return proxyFetch;\n}\nexports.getProxyFetch = getProxyFetch;\nfunction getApiBaseUrl() {\n return process.env['GITHUB_API_URL'] || 'https://api.github.com';\n}\nexports.getApiBaseUrl = getApiBaseUrl;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst Utils = __importStar(require(\"./internal/utils\"));\n// octokit + plugins\nconst core_1 = require(\"@octokit/core\");\nconst plugin_rest_endpoint_methods_1 = require(\"@octokit/plugin-rest-endpoint-methods\");\nconst plugin_paginate_rest_1 = require(\"@octokit/plugin-paginate-rest\");\nexports.context = new Context.Context();\nconst baseUrl = Utils.getApiBaseUrl();\nexports.defaults = {\n baseUrl,\n request: {\n agent: Utils.getProxyAgent(baseUrl),\n fetch: Utils.getProxyFetch(baseUrl)\n }\n};\nexports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults);\n/**\n * Convience function to correctly format Octokit Options to pass into the constructor.\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokitOptions(token, options) {\n const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller\n // Auth\n const auth = Utils.getAuthString(token, opts);\n if (auth) {\n opts.auth = auth;\n }\n return opts;\n}\nexports.getOctokitOptions = getOctokitOptions;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;\nclass BasicCredentialHandler {\n constructor(username, password) {\n this.username = username;\n this.password = password;\n }\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BasicCredentialHandler = BasicCredentialHandler;\nclass BearerCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Bearer ${this.token}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BearerCredentialHandler = BearerCredentialHandler;\nclass PersonalAccessTokenCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;\n//# sourceMappingURL=auth.js.map","\"use strict\";\n/* eslint-disable @typescript-eslint/no-explicit-any */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;\nconst http = __importStar(require(\"http\"));\nconst https = __importStar(require(\"https\"));\nconst pm = __importStar(require(\"./proxy\"));\nconst tunnel = __importStar(require(\"tunnel\"));\nconst undici_1 = require(\"undici\");\nvar HttpCodes;\n(function (HttpCodes) {\n HttpCodes[HttpCodes[\"OK\"] = 200] = \"OK\";\n HttpCodes[HttpCodes[\"MultipleChoices\"] = 300] = \"MultipleChoices\";\n HttpCodes[HttpCodes[\"MovedPermanently\"] = 301] = \"MovedPermanently\";\n HttpCodes[HttpCodes[\"ResourceMoved\"] = 302] = \"ResourceMoved\";\n HttpCodes[HttpCodes[\"SeeOther\"] = 303] = \"SeeOther\";\n HttpCodes[HttpCodes[\"NotModified\"] = 304] = \"NotModified\";\n HttpCodes[HttpCodes[\"UseProxy\"] = 305] = \"UseProxy\";\n HttpCodes[HttpCodes[\"SwitchProxy\"] = 306] = \"SwitchProxy\";\n HttpCodes[HttpCodes[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n HttpCodes[HttpCodes[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n HttpCodes[HttpCodes[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpCodes[HttpCodes[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpCodes[HttpCodes[\"PaymentRequired\"] = 402] = \"PaymentRequired\";\n HttpCodes[HttpCodes[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpCodes[HttpCodes[\"NotFound\"] = 404] = \"NotFound\";\n HttpCodes[HttpCodes[\"MethodNotAllowed\"] = 405] = \"MethodNotAllowed\";\n HttpCodes[HttpCodes[\"NotAcceptable\"] = 406] = \"NotAcceptable\";\n HttpCodes[HttpCodes[\"ProxyAuthenticationRequired\"] = 407] = \"ProxyAuthenticationRequired\";\n HttpCodes[HttpCodes[\"RequestTimeout\"] = 408] = \"RequestTimeout\";\n HttpCodes[HttpCodes[\"Conflict\"] = 409] = \"Conflict\";\n HttpCodes[HttpCodes[\"Gone\"] = 410] = \"Gone\";\n HttpCodes[HttpCodes[\"TooManyRequests\"] = 429] = \"TooManyRequests\";\n HttpCodes[HttpCodes[\"InternalServerError\"] = 500] = \"InternalServerError\";\n HttpCodes[HttpCodes[\"NotImplemented\"] = 501] = \"NotImplemented\";\n HttpCodes[HttpCodes[\"BadGateway\"] = 502] = \"BadGateway\";\n HttpCodes[HttpCodes[\"ServiceUnavailable\"] = 503] = \"ServiceUnavailable\";\n HttpCodes[HttpCodes[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n})(HttpCodes || (exports.HttpCodes = HttpCodes = {}));\nvar Headers;\n(function (Headers) {\n Headers[\"Accept\"] = \"accept\";\n Headers[\"ContentType\"] = \"content-type\";\n})(Headers || (exports.Headers = Headers = {}));\nvar MediaTypes;\n(function (MediaTypes) {\n MediaTypes[\"ApplicationJson\"] = \"application/json\";\n})(MediaTypes || (exports.MediaTypes = MediaTypes = {}));\n/**\n * Returns the proxy URL, depending upon the supplied url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\nfunction getProxyUrl(serverUrl) {\n const proxyUrl = pm.getProxyUrl(new URL(serverUrl));\n return proxyUrl ? proxyUrl.href : '';\n}\nexports.getProxyUrl = getProxyUrl;\nconst HttpRedirectCodes = [\n HttpCodes.MovedPermanently,\n HttpCodes.ResourceMoved,\n HttpCodes.SeeOther,\n HttpCodes.TemporaryRedirect,\n HttpCodes.PermanentRedirect\n];\nconst HttpResponseRetryCodes = [\n HttpCodes.BadGateway,\n HttpCodes.ServiceUnavailable,\n HttpCodes.GatewayTimeout\n];\nconst RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];\nconst ExponentialBackoffCeiling = 10;\nconst ExponentialBackoffTimeSlice = 5;\nclass HttpClientError extends Error {\n constructor(message, statusCode) {\n super(message);\n this.name = 'HttpClientError';\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, HttpClientError.prototype);\n }\n}\nexports.HttpClientError = HttpClientError;\nclass HttpClientResponse {\n constructor(message) {\n this.message = message;\n }\n readBody() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n let output = Buffer.alloc(0);\n this.message.on('data', (chunk) => {\n output = Buffer.concat([output, chunk]);\n });\n this.message.on('end', () => {\n resolve(output.toString());\n });\n }));\n });\n }\n readBodyBuffer() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n const chunks = [];\n this.message.on('data', (chunk) => {\n chunks.push(chunk);\n });\n this.message.on('end', () => {\n resolve(Buffer.concat(chunks));\n });\n }));\n });\n }\n}\nexports.HttpClientResponse = HttpClientResponse;\nfunction isHttps(requestUrl) {\n const parsedUrl = new URL(requestUrl);\n return parsedUrl.protocol === 'https:';\n}\nexports.isHttps = isHttps;\nclass HttpClient {\n constructor(userAgent, handlers, requestOptions) {\n this._ignoreSslError = false;\n this._allowRedirects = true;\n this._allowRedirectDowngrade = false;\n this._maxRedirects = 50;\n this._allowRetries = false;\n this._maxRetries = 1;\n this._keepAlive = false;\n this._disposed = false;\n this.userAgent = userAgent;\n this.handlers = handlers || [];\n this.requestOptions = requestOptions;\n if (requestOptions) {\n if (requestOptions.ignoreSslError != null) {\n this._ignoreSslError = requestOptions.ignoreSslError;\n }\n this._socketTimeout = requestOptions.socketTimeout;\n if (requestOptions.allowRedirects != null) {\n this._allowRedirects = requestOptions.allowRedirects;\n }\n if (requestOptions.allowRedirectDowngrade != null) {\n this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;\n }\n if (requestOptions.maxRedirects != null) {\n this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);\n }\n if (requestOptions.keepAlive != null) {\n this._keepAlive = requestOptions.keepAlive;\n }\n if (requestOptions.allowRetries != null) {\n this._allowRetries = requestOptions.allowRetries;\n }\n if (requestOptions.maxRetries != null) {\n this._maxRetries = requestOptions.maxRetries;\n }\n }\n }\n options(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});\n });\n }\n get(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('GET', requestUrl, null, additionalHeaders || {});\n });\n }\n del(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('DELETE', requestUrl, null, additionalHeaders || {});\n });\n }\n post(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('POST', requestUrl, data, additionalHeaders || {});\n });\n }\n patch(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PATCH', requestUrl, data, additionalHeaders || {});\n });\n }\n put(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PUT', requestUrl, data, additionalHeaders || {});\n });\n }\n head(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('HEAD', requestUrl, null, additionalHeaders || {});\n });\n }\n sendStream(verb, requestUrl, stream, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request(verb, requestUrl, stream, additionalHeaders);\n });\n }\n /**\n * Gets a typed object from an endpoint\n * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise\n */\n getJson(requestUrl, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n const res = yield this.get(requestUrl, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n postJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.post(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n putJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.put(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n patchJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.patch(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n /**\n * Makes a raw http request.\n * All other methods such as get, post, patch, and request ultimately call this.\n * Prefer get, del, post and patch\n */\n request(verb, requestUrl, data, headers) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._disposed) {\n throw new Error('Client has already been disposed.');\n }\n const parsedUrl = new URL(requestUrl);\n let info = this._prepareRequest(verb, parsedUrl, headers);\n // Only perform retries on reads since writes may not be idempotent.\n const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)\n ? this._maxRetries + 1\n : 1;\n let numTries = 0;\n let response;\n do {\n response = yield this.requestRaw(info, data);\n // Check if it's an authentication challenge\n if (response &&\n response.message &&\n response.message.statusCode === HttpCodes.Unauthorized) {\n let authenticationHandler;\n for (const handler of this.handlers) {\n if (handler.canHandleAuthentication(response)) {\n authenticationHandler = handler;\n break;\n }\n }\n if (authenticationHandler) {\n return authenticationHandler.handleAuthentication(this, info, data);\n }\n else {\n // We have received an unauthorized response but have no handlers to handle it.\n // Let the response return to the caller.\n return response;\n }\n }\n let redirectsRemaining = this._maxRedirects;\n while (response.message.statusCode &&\n HttpRedirectCodes.includes(response.message.statusCode) &&\n this._allowRedirects &&\n redirectsRemaining > 0) {\n const redirectUrl = response.message.headers['location'];\n if (!redirectUrl) {\n // if there's no location to redirect to, we won't\n break;\n }\n const parsedRedirectUrl = new URL(redirectUrl);\n if (parsedUrl.protocol === 'https:' &&\n parsedUrl.protocol !== parsedRedirectUrl.protocol &&\n !this._allowRedirectDowngrade) {\n throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');\n }\n // we need to finish reading the response before reassigning response\n // which will leak the open socket.\n yield response.readBody();\n // strip authorization header if redirected to a different hostname\n if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {\n for (const header in headers) {\n // header names are case insensitive\n if (header.toLowerCase() === 'authorization') {\n delete headers[header];\n }\n }\n }\n // let's make the request with the new redirectUrl\n info = this._prepareRequest(verb, parsedRedirectUrl, headers);\n response = yield this.requestRaw(info, data);\n redirectsRemaining--;\n }\n if (!response.message.statusCode ||\n !HttpResponseRetryCodes.includes(response.message.statusCode)) {\n // If not a retry code, return immediately instead of retrying\n return response;\n }\n numTries += 1;\n if (numTries < maxTries) {\n yield response.readBody();\n yield this._performExponentialBackoff(numTries);\n }\n } while (numTries < maxTries);\n return response;\n });\n }\n /**\n * Needs to be called if keepAlive is set to true in request options.\n */\n dispose() {\n if (this._agent) {\n this._agent.destroy();\n }\n this._disposed = true;\n }\n /**\n * Raw request.\n * @param info\n * @param data\n */\n requestRaw(info, data) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n function callbackForResult(err, res) {\n if (err) {\n reject(err);\n }\n else if (!res) {\n // If `err` is not passed, then `res` must be passed.\n reject(new Error('Unknown error'));\n }\n else {\n resolve(res);\n }\n }\n this.requestRawWithCallback(info, data, callbackForResult);\n });\n });\n }\n /**\n * Raw request with callback.\n * @param info\n * @param data\n * @param onResult\n */\n requestRawWithCallback(info, data, onResult) {\n if (typeof data === 'string') {\n if (!info.options.headers) {\n info.options.headers = {};\n }\n info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');\n }\n let callbackCalled = false;\n function handleResult(err, res) {\n if (!callbackCalled) {\n callbackCalled = true;\n onResult(err, res);\n }\n }\n const req = info.httpModule.request(info.options, (msg) => {\n const res = new HttpClientResponse(msg);\n handleResult(undefined, res);\n });\n let socket;\n req.on('socket', sock => {\n socket = sock;\n });\n // If we ever get disconnected, we want the socket to timeout eventually\n req.setTimeout(this._socketTimeout || 3 * 60000, () => {\n if (socket) {\n socket.end();\n }\n handleResult(new Error(`Request timeout: ${info.options.path}`));\n });\n req.on('error', function (err) {\n // err has statusCode property\n // res should have headers\n handleResult(err);\n });\n if (data && typeof data === 'string') {\n req.write(data, 'utf8');\n }\n if (data && typeof data !== 'string') {\n data.on('close', function () {\n req.end();\n });\n data.pipe(req);\n }\n else {\n req.end();\n }\n }\n /**\n * Gets an http agent. This function is useful when you need an http agent that handles\n * routing through a proxy server - depending upon the url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\n getAgent(serverUrl) {\n const parsedUrl = new URL(serverUrl);\n return this._getAgent(parsedUrl);\n }\n getAgentDispatcher(serverUrl) {\n const parsedUrl = new URL(serverUrl);\n const proxyUrl = pm.getProxyUrl(parsedUrl);\n const useProxy = proxyUrl && proxyUrl.hostname;\n if (!useProxy) {\n return;\n }\n return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);\n }\n _prepareRequest(method, requestUrl, headers) {\n const info = {};\n info.parsedUrl = requestUrl;\n const usingSsl = info.parsedUrl.protocol === 'https:';\n info.httpModule = usingSsl ? https : http;\n const defaultPort = usingSsl ? 443 : 80;\n info.options = {};\n info.options.host = info.parsedUrl.hostname;\n info.options.port = info.parsedUrl.port\n ? parseInt(info.parsedUrl.port)\n : defaultPort;\n info.options.path =\n (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');\n info.options.method = method;\n info.options.headers = this._mergeHeaders(headers);\n if (this.userAgent != null) {\n info.options.headers['user-agent'] = this.userAgent;\n }\n info.options.agent = this._getAgent(info.parsedUrl);\n // gives handlers an opportunity to participate\n if (this.handlers) {\n for (const handler of this.handlers) {\n handler.prepareRequest(info.options);\n }\n }\n return info;\n }\n _mergeHeaders(headers) {\n if (this.requestOptions && this.requestOptions.headers) {\n return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));\n }\n return lowercaseKeys(headers || {});\n }\n _getExistingOrDefaultHeader(additionalHeaders, header, _default) {\n let clientHeader;\n if (this.requestOptions && this.requestOptions.headers) {\n clientHeader = lowercaseKeys(this.requestOptions.headers)[header];\n }\n return additionalHeaders[header] || clientHeader || _default;\n }\n _getAgent(parsedUrl) {\n let agent;\n const proxyUrl = pm.getProxyUrl(parsedUrl);\n const useProxy = proxyUrl && proxyUrl.hostname;\n if (this._keepAlive && useProxy) {\n agent = this._proxyAgent;\n }\n if (!useProxy) {\n agent = this._agent;\n }\n // if agent is already assigned use that agent.\n if (agent) {\n return agent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n let maxSockets = 100;\n if (this.requestOptions) {\n maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;\n }\n // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.\n if (proxyUrl && proxyUrl.hostname) {\n const agentOptions = {\n maxSockets,\n keepAlive: this._keepAlive,\n proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {\n proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`\n })), { host: proxyUrl.hostname, port: proxyUrl.port })\n };\n let tunnelAgent;\n const overHttps = proxyUrl.protocol === 'https:';\n if (usingSsl) {\n tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;\n }\n else {\n tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;\n }\n agent = tunnelAgent(agentOptions);\n this._proxyAgent = agent;\n }\n // if tunneling agent isn't assigned create a new agent\n if (!agent) {\n const options = { keepAlive: this._keepAlive, maxSockets };\n agent = usingSsl ? new https.Agent(options) : new http.Agent(options);\n this._agent = agent;\n }\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n agent.options = Object.assign(agent.options || {}, {\n rejectUnauthorized: false\n });\n }\n return agent;\n }\n _getProxyAgentDispatcher(parsedUrl, proxyUrl) {\n let proxyAgent;\n if (this._keepAlive) {\n proxyAgent = this._proxyAgentDispatcher;\n }\n // if agent is already assigned use that agent.\n if (proxyAgent) {\n return proxyAgent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {\n token: `${proxyUrl.username}:${proxyUrl.password}`\n })));\n this._proxyAgentDispatcher = proxyAgent;\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {\n rejectUnauthorized: false\n });\n }\n return proxyAgent;\n }\n _performExponentialBackoff(retryNumber) {\n return __awaiter(this, void 0, void 0, function* () {\n retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);\n const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);\n return new Promise(resolve => setTimeout(() => resolve(), ms));\n });\n }\n _processResponse(res, options) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n const statusCode = res.message.statusCode || 0;\n const response = {\n statusCode,\n result: null,\n headers: {}\n };\n // not found leads to null obj returned\n if (statusCode === HttpCodes.NotFound) {\n resolve(response);\n }\n // get the result from the body\n function dateTimeDeserializer(key, value) {\n if (typeof value === 'string') {\n const a = new Date(value);\n if (!isNaN(a.valueOf())) {\n return a;\n }\n }\n return value;\n }\n let obj;\n let contents;\n try {\n contents = yield res.readBody();\n if (contents && contents.length > 0) {\n if (options && options.deserializeDates) {\n obj = JSON.parse(contents, dateTimeDeserializer);\n }\n else {\n obj = JSON.parse(contents);\n }\n response.result = obj;\n }\n response.headers = res.message.headers;\n }\n catch (err) {\n // Invalid resource (contents not json); leaving result obj null\n }\n // note that 3xx redirects are handled by the http layer.\n if (statusCode > 299) {\n let msg;\n // if exception/error in body, attempt to get better error\n if (obj && obj.message) {\n msg = obj.message;\n }\n else if (contents && contents.length > 0) {\n // it may be the case that the exception is in the body message as string\n msg = contents;\n }\n else {\n msg = `Failed request: (${statusCode})`;\n }\n const err = new HttpClientError(msg, statusCode);\n err.result = response.result;\n reject(err);\n }\n else {\n resolve(response);\n }\n }));\n });\n }\n}\nexports.HttpClient = HttpClient;\nconst lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.checkBypass = exports.getProxyUrl = void 0;\nfunction getProxyUrl(reqUrl) {\n const usingSsl = reqUrl.protocol === 'https:';\n if (checkBypass(reqUrl)) {\n return undefined;\n }\n const proxyVar = (() => {\n if (usingSsl) {\n return process.env['https_proxy'] || process.env['HTTPS_PROXY'];\n }\n else {\n return process.env['http_proxy'] || process.env['HTTP_PROXY'];\n }\n })();\n if (proxyVar) {\n try {\n return new URL(proxyVar);\n }\n catch (_a) {\n if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))\n return new URL(`http://${proxyVar}`);\n }\n }\n else {\n return undefined;\n }\n}\nexports.getProxyUrl = getProxyUrl;\nfunction checkBypass(reqUrl) {\n if (!reqUrl.hostname) {\n return false;\n }\n const reqHost = reqUrl.hostname;\n if (isLoopbackAddress(reqHost)) {\n return true;\n }\n const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';\n if (!noProxy) {\n return false;\n }\n // Determine the request port\n let reqPort;\n if (reqUrl.port) {\n reqPort = Number(reqUrl.port);\n }\n else if (reqUrl.protocol === 'http:') {\n reqPort = 80;\n }\n else if (reqUrl.protocol === 'https:') {\n reqPort = 443;\n }\n // Format the request hostname and hostname with port\n const upperReqHosts = [reqUrl.hostname.toUpperCase()];\n if (typeof reqPort === 'number') {\n upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);\n }\n // Compare request host against noproxy\n for (const upperNoProxyItem of noProxy\n .split(',')\n .map(x => x.trim().toUpperCase())\n .filter(x => x)) {\n if (upperNoProxyItem === '*' ||\n upperReqHosts.some(x => x === upperNoProxyItem ||\n x.endsWith(`.${upperNoProxyItem}`) ||\n (upperNoProxyItem.startsWith('.') &&\n x.endsWith(`${upperNoProxyItem}`)))) {\n return true;\n }\n }\n return false;\n}\nexports.checkBypass = checkBypass;\nfunction isLoopbackAddress(host) {\n const hostLower = host.toLowerCase();\n return (hostLower === 'localhost' ||\n hostLower.startsWith('127.') ||\n hostLower.startsWith('[::1]') ||\n hostLower.startsWith('[0:0:0:0:0:0:0:1]'));\n}\n//# sourceMappingURL=proxy.js.map","'use strict';\n/**\n * @license\n * Copyright 2020 Balena Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * ------------------------------------------------------------------------\n *\n * Copyright 2018 Zeit, Inc.\n * Licensed under the MIT License. See file LICENSE.md for a full copy.\n *\n * ------------------------------------------------------------------------\n */\n\n/**\n * This module implements the [dockerignore\n * spec](https://docs.docker.com/engine/reference/builder/#dockerignore-file),\n * closely following Docker's (Moby) Golang implementation:\n * https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go\n * https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go\n * https://github.com/moby/moby/blob/v19.03.8/pkg/archive/archive.go#L825\n *\n * Something the spec is not clear about, but we discovered by reading source code\n * and testing against the \"docker build\" command, is the handling of backslashes and\n * forward slashes as path separators and escape characters in the .dockerignore file\n * across platforms including Windows, Linux and macOS:\n *\n * * On Linux and macOS, only forward slashes can be used as path separators in the\n * .dockerignore file, and the backslash works as an escape character.\n * * On Windows, both forward slashes and backslashes are allowed as path separators\n * in the .dockerignore file, and the backslash is not used as an escape character.\n *\n * This is consistent with how Windows works generally: both forward slashes and\n * backslashes are accepted as path separators by the cmd.exe Command Prompt or\n * PowerShell, and by library functions like the Golang filepath.Clean or the\n * Node.js path.normalize.\n *\n * Similarly, path strings provided to the IgnoreBase.ignores() and IgnoreBase.filter()\n * methods can use either forward slashes or backslashes as path separators on Windows,\n * but only forward slashes are accepted as path separators on Linux and macOS.\n */\n\nconst path = require('path');\n\nconst factory = options => new IgnoreBase(options); // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L538-L539\n// Fixes typescript module import\n\n\nfactory.default = factory;\nmodule.exports = factory;\n\nfunction make_array(subject) {\n return Array.isArray(subject) ? subject : [subject];\n}\n\nconst REGEX_TRAILING_SLASH = /(?<=.)\\/$/;\nconst REGEX_TRAILING_BACKSLASH = /(?<=.)\\\\$/;\nconst REGEX_TRAILING_PATH_SEP = path.sep === '\\\\' ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH;\nconst KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('dockerignore') : 'dockerignore'; // An implementation of Go's filepath.Clean\n// https://golang.org/pkg/path/filepath/#Clean\n// https://github.com/golang/go/blob/master/src/path/filepath/path.go\n// Note that, like Go, on Windows this function converts forward slashes\n// to backslashes.\n\nfunction cleanPath(file) {\n return path.normalize(file).replace(REGEX_TRAILING_PATH_SEP, '');\n} // Javascript port of Golang's filepath.ToSlash\n// https://golang.org/pkg/path/filepath/#ToSlash\n// https://github.com/golang/go/blob/master/src/path/filepath/path.go\n// Convert any OS-specific path separator to '/'. Backslash is converted\n// to forward slash on Windows, but not on Linux/macOS.\n// Note that both forward slashes and backslashes are valid path separators on\n// Windows. As a result, code such as `pattern.split(path.sep).join('/')` fails\n// on Windows when forward slashes are used as path separators.\n\n\nfunction toSlash(file) {\n if (path.sep === '/') {\n return file;\n }\n\n return file.replace(/\\\\/g, '/');\n} // Javascript port of Golang's filepath.FromSlash\n// https://github.com/golang/go/blob/master/src/path/filepath/path.go\n\n\nfunction fromSlash(file) {\n if (path.sep === '/') {\n return file;\n }\n\n return file.replace(/\\//g, path.sep);\n}\n\nclass IgnoreBase {\n constructor({\n // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L372\n ignorecase = true\n } = {}) {\n this._rules = [];\n this._ignorecase = ignorecase;\n this[KEY_IGNORE] = true;\n\n this._initCache();\n }\n\n _initCache() {\n this._cache = {};\n } // @param {Array.|string|Ignore} pattern\n\n\n add(pattern) {\n this._added = false;\n\n if (typeof pattern === 'string') {\n pattern = pattern.split(/\\r?\\n/g);\n }\n\n make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,\n // making the behavior changed.\n\n if (this._added) {\n this._initCache();\n }\n\n return this;\n } // legacy\n\n\n addPattern(pattern) {\n return this.add(pattern);\n }\n\n _addPattern(pattern) {\n // https://github.com/kaelzhang/node-ignore/issues/32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules);\n this._added = true;\n return;\n }\n\n if (this._checkPattern(pattern)) {\n const rule = this._createRule(pattern.trim());\n\n if (rule !== null) {\n this._added = true;\n\n this._rules.push(rule);\n }\n }\n }\n\n _checkPattern(pattern) {\n // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L34-L40\n return pattern && typeof pattern === 'string' && pattern.indexOf('#') !== 0 && pattern.trim() !== \"\";\n }\n\n filter(paths) {\n return make_array(paths).filter(path => this._filter(path));\n }\n\n createFilter() {\n return path => this._filter(path);\n }\n\n ignores(path) {\n return !this._filter(path);\n } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L41-L53\n // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L29-L55\n\n\n _createRule(pattern) {\n const origin = pattern;\n let negative = false; // > An optional prefix \"!\" which negates the pattern;\n // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L43-L46\n\n if (pattern[0] === '!') {\n negative = true;\n pattern = pattern.substring(1).trim();\n } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L47-L53\n\n\n if (pattern.length > 0) {\n pattern = cleanPath(pattern);\n pattern = toSlash(pattern);\n\n if (pattern.length > 1 && pattern[0] === '/') {\n pattern = pattern.slice(1);\n }\n } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L54-L55\n\n\n if (negative) {\n pattern = '!' + pattern;\n } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L30\n\n\n pattern = pattern.trim();\n\n if (pattern === \"\") {\n return null;\n } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L34\n // convert forward slashes to backslashes on Windows\n\n\n pattern = cleanPath(pattern); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L36-L42\n\n if (pattern[0] === '!') {\n if (pattern.length === 1) {\n return null;\n }\n\n negative = true;\n pattern = pattern.substring(1);\n } else {\n negative = false;\n }\n\n return {\n origin,\n pattern,\n // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L54\n dirs: pattern.split(path.sep),\n negative\n };\n } // @returns `Boolean` true if the `path` is NOT ignored\n\n\n _filter(path) {\n if (!path) {\n return false;\n }\n\n if (path in this._cache) {\n return this._cache[path];\n }\n\n return this._cache[path] = this._test(path);\n } // @returns {Boolean} true if a file is NOT ignored\n // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L62\n\n\n _test(file) {\n file = fromSlash(file); // equivalent to golang filepath.Dir() https://golang.org/src/path/filepath/path.go\n\n const parentPath = cleanPath(path.dirname(file));\n const parentPathDirs = parentPath.split(path.sep);\n let matched = false;\n\n this._rules.forEach(rule => {\n let match = this._match(file, rule); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L80\n\n\n if (!match && parentPath !== \".\") {\n // Check to see if the pattern matches one of our parent dirs.\n if (rule.dirs.includes('**')) {\n // Ah shucks! We have to test every possible parent path that has \n // a number of dirs _n_ where \n // `rule.dirs.filter(doubleStar).length <= _n_ <= parentPathDirs.length`\n // since the ** can imply any number of directories including 0\n for (let i = rule.dirs.filter(x => x !== '**').length; i <= parentPathDirs.length; i++) {\n match = match || this._match(parentPathDirs.slice(0, i).join(path.sep), rule);\n }\n } else if (rule.dirs.length <= parentPathDirs.length) {\n // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L83\n match = this._match(parentPathDirs.slice(0, rule.dirs.length).join(path.sep), rule);\n }\n }\n\n if (match) {\n matched = !rule.negative;\n }\n });\n\n return !matched;\n } // @returns {Boolean} true if a file is matched by a rule\n\n\n _match(file, rule) {\n return this._compile(rule).regexp.test(file);\n } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L139\n\n\n _compile(rule) {\n if (rule.regexp) {\n return rule;\n }\n\n let regStr = '^'; // Go through the pattern and convert it to a regexp.\n\n let escapedSlash = path.sep === '\\\\' ? '\\\\\\\\' : path.sep;\n\n for (let i = 0; i < rule.pattern.length; i++) {\n const ch = rule.pattern[i];\n\n if (ch === '*') {\n if (rule.pattern[i + 1] === '*') {\n // is some flavor of \"**\"\n i++; // Treat **/ as ** so eat the \"/\"\n\n if (rule.pattern[i + 1] === path.sep) {\n i++;\n }\n\n if (rule.pattern[i + 1] === undefined) {\n // is \"**EOF\" - to align with .gitignore just accept all\n regStr += \".*\";\n } else {\n // is \"**\"\n // Note that this allows for any # of /'s (even 0) because\n // the .* will eat everything, even /'s\n regStr += `(.*${escapedSlash})?`;\n }\n } else {\n // is \"*\" so map it to anything but \"/\"\n regStr += `[^${escapedSlash}]*`;\n }\n } else if (ch === '?') {\n // \"?\" is any char except \"/\"\n regStr += `[^${escapedSlash}]`;\n } else if (ch === '.' || ch === '$') {\n // Escape some regexp special chars that have no meaning\n // in golang's filepath.Match\n regStr += `\\\\${ch}`;\n } else if (ch === '\\\\') {\n // escape next char. Note that a trailing \\ in the pattern\n // will be left alone (but need to escape it)\n if (path.sep === '\\\\') {\n // On windows map \"\\\" to \"\\\\\", meaning an escaped backslash,\n // and then just continue because filepath.Match on\n // Windows doesn't allow escaping at all\n regStr += escapedSlash;\n continue;\n }\n\n if (rule.pattern[i + 1] !== undefined) {\n regStr += '\\\\' + rule.pattern[i + 1];\n i++;\n } else {\n regStr += '\\\\';\n }\n } else {\n regStr += ch;\n }\n }\n\n regStr += \"$\";\n rule.regexp = new RegExp(regStr, this._ignorecase ? 'i' : '');\n return rule;\n }\n\n}\n","'use strict'\n\nconst WritableStream = require('node:stream').Writable\nconst inherits = require('node:util').inherits\n\nconst StreamSearch = require('../../streamsearch/sbmh')\n\nconst PartStream = require('./PartStream')\nconst HeaderParser = require('./HeaderParser')\n\nconst DASH = 45\nconst B_ONEDASH = Buffer.from('-')\nconst B_CRLF = Buffer.from('\\r\\n')\nconst EMPTY_FN = function () {}\n\nfunction Dicer (cfg) {\n if (!(this instanceof Dicer)) { return new Dicer(cfg) }\n WritableStream.call(this, cfg)\n\n if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }\n\n if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }\n\n this._headerFirst = cfg.headerFirst\n\n this._dashes = 0\n this._parts = 0\n this._finished = false\n this._realFinish = false\n this._isPreamble = true\n this._justMatched = false\n this._firstWrite = true\n this._inHeader = true\n this._part = undefined\n this._cb = undefined\n this._ignoreData = false\n this._partOpts = { highWaterMark: cfg.partHwm }\n this._pause = false\n\n const self = this\n this._hparser = new HeaderParser(cfg)\n this._hparser.on('header', function (header) {\n self._inHeader = false\n self._part.emit('header', header)\n })\n}\ninherits(Dicer, WritableStream)\n\nDicer.prototype.emit = function (ev) {\n if (ev === 'finish' && !this._realFinish) {\n if (!this._finished) {\n const self = this\n process.nextTick(function () {\n self.emit('error', new Error('Unexpected end of multipart data'))\n if (self._part && !self._ignoreData) {\n const type = (self._isPreamble ? 'Preamble' : 'Part')\n self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))\n self._part.push(null)\n process.nextTick(function () {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n })\n return\n }\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n })\n }\n } else { WritableStream.prototype.emit.apply(this, arguments) }\n}\n\nDicer.prototype._write = function (data, encoding, cb) {\n // ignore unexpected data (e.g. extra trailer data after finished)\n if (!this._hparser && !this._bparser) { return cb() }\n\n if (this._headerFirst && this._isPreamble) {\n if (!this._part) {\n this._part = new PartStream(this._partOpts)\n if (this._events.preamble) { this.emit('preamble', this._part) } else { this._ignore() }\n }\n const r = this._hparser.push(data)\n if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }\n }\n\n // allows for \"easier\" testing\n if (this._firstWrite) {\n this._bparser.push(B_CRLF)\n this._firstWrite = false\n }\n\n this._bparser.push(data)\n\n if (this._pause) { this._cb = cb } else { cb() }\n}\n\nDicer.prototype.reset = function () {\n this._part = undefined\n this._bparser = undefined\n this._hparser = undefined\n}\n\nDicer.prototype.setBoundary = function (boundary) {\n const self = this\n this._bparser = new StreamSearch('\\r\\n--' + boundary)\n this._bparser.on('info', function (isMatch, data, start, end) {\n self._oninfo(isMatch, data, start, end)\n })\n}\n\nDicer.prototype._ignore = function () {\n if (this._part && !this._ignoreData) {\n this._ignoreData = true\n this._part.on('error', EMPTY_FN)\n // we must perform some kind of read on the stream even though we are\n // ignoring the data, otherwise node's Readable stream will not emit 'end'\n // after pushing null to the stream\n this._part.resume()\n }\n}\n\nDicer.prototype._oninfo = function (isMatch, data, start, end) {\n let buf; const self = this; let i = 0; let r; let shouldWriteMore = true\n\n if (!this._part && this._justMatched && data) {\n while (this._dashes < 2 && (start + i) < end) {\n if (data[start + i] === DASH) {\n ++i\n ++this._dashes\n } else {\n if (this._dashes) { buf = B_ONEDASH }\n this._dashes = 0\n break\n }\n }\n if (this._dashes === 2) {\n if ((start + i) < end && this._events.trailer) { this.emit('trailer', data.slice(start + i, end)) }\n this.reset()\n this._finished = true\n // no more parts will be added\n if (self._parts === 0) {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n }\n }\n if (this._dashes) { return }\n }\n if (this._justMatched) { this._justMatched = false }\n if (!this._part) {\n this._part = new PartStream(this._partOpts)\n this._part._read = function (n) {\n self._unpause()\n }\n 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() }\n if (!this._isPreamble) { this._inHeader = true }\n }\n if (data && start < end && !this._ignoreData) {\n if (this._isPreamble || !this._inHeader) {\n if (buf) { shouldWriteMore = this._part.push(buf) }\n shouldWriteMore = this._part.push(data.slice(start, end))\n if (!shouldWriteMore) { this._pause = true }\n } else if (!this._isPreamble && this._inHeader) {\n if (buf) { this._hparser.push(buf) }\n r = this._hparser.push(data.slice(start, end))\n if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }\n }\n }\n if (isMatch) {\n this._hparser.reset()\n if (this._isPreamble) { this._isPreamble = false } else {\n if (start !== end) {\n ++this._parts\n this._part.on('end', function () {\n if (--self._parts === 0) {\n if (self._finished) {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n } else {\n self._unpause()\n }\n }\n })\n }\n }\n this._part.push(null)\n this._part = undefined\n this._ignoreData = false\n this._justMatched = true\n this._dashes = 0\n }\n}\n\nDicer.prototype._unpause = function () {\n if (!this._pause) { return }\n\n this._pause = false\n if (this._cb) {\n const cb = this._cb\n this._cb = undefined\n cb()\n }\n}\n\nmodule.exports = Dicer\n","'use strict'\n\nconst EventEmitter = require('node:events').EventEmitter\nconst inherits = require('node:util').inherits\nconst getLimit = require('../../../lib/utils/getLimit')\n\nconst StreamSearch = require('../../streamsearch/sbmh')\n\nconst B_DCRLF = Buffer.from('\\r\\n\\r\\n')\nconst RE_CRLF = /\\r\\n/g\nconst RE_HDR = /^([^:]+):[ \\t]?([\\x00-\\xFF]+)?$/ // eslint-disable-line no-control-regex\n\nfunction HeaderParser (cfg) {\n EventEmitter.call(this)\n\n cfg = cfg || {}\n const self = this\n this.nread = 0\n this.maxed = false\n this.npairs = 0\n this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)\n this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)\n this.buffer = ''\n this.header = {}\n this.finished = false\n this.ss = new StreamSearch(B_DCRLF)\n this.ss.on('info', function (isMatch, data, start, end) {\n if (data && !self.maxed) {\n if (self.nread + end - start >= self.maxHeaderSize) {\n end = self.maxHeaderSize - self.nread + start\n self.nread = self.maxHeaderSize\n self.maxed = true\n } else { self.nread += (end - start) }\n\n self.buffer += data.toString('binary', start, end)\n }\n if (isMatch) { self._finish() }\n })\n}\ninherits(HeaderParser, EventEmitter)\n\nHeaderParser.prototype.push = function (data) {\n const r = this.ss.push(data)\n if (this.finished) { return r }\n}\n\nHeaderParser.prototype.reset = function () {\n this.finished = false\n this.buffer = ''\n this.header = {}\n this.ss.reset()\n}\n\nHeaderParser.prototype._finish = function () {\n if (this.buffer) { this._parseHeader() }\n this.ss.matches = this.ss.maxMatches\n const header = this.header\n this.header = {}\n this.buffer = ''\n this.finished = true\n this.nread = this.npairs = 0\n this.maxed = false\n this.emit('header', header)\n}\n\nHeaderParser.prototype._parseHeader = function () {\n if (this.npairs === this.maxHeaderPairs) { return }\n\n const lines = this.buffer.split(RE_CRLF)\n const len = lines.length\n let m, h\n\n for (var i = 0; i < len; ++i) { // eslint-disable-line no-var\n if (lines[i].length === 0) { continue }\n if (lines[i][0] === '\\t' || lines[i][0] === ' ') {\n // folded header content\n // RFC2822 says to just remove the CRLF and not the whitespace following\n // it, so we follow the RFC and include the leading whitespace ...\n if (h) {\n this.header[h][this.header[h].length - 1] += lines[i]\n continue\n }\n }\n\n const posColon = lines[i].indexOf(':')\n if (\n posColon === -1 ||\n posColon === 0\n ) {\n return\n }\n m = RE_HDR.exec(lines[i])\n h = m[1].toLowerCase()\n this.header[h] = this.header[h] || []\n this.header[h].push((m[2] || ''))\n if (++this.npairs === this.maxHeaderPairs) { break }\n }\n}\n\nmodule.exports = HeaderParser\n","'use strict'\n\nconst inherits = require('node:util').inherits\nconst ReadableStream = require('node:stream').Readable\n\nfunction PartStream (opts) {\n ReadableStream.call(this, opts)\n}\ninherits(PartStream, ReadableStream)\n\nPartStream.prototype._read = function (n) {}\n\nmodule.exports = PartStream\n","'use strict'\n\n/**\n * Copyright Brian White. All rights reserved.\n *\n * @see https://github.com/mscdex/streamsearch\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation\n * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool\n */\nconst EventEmitter = require('node:events').EventEmitter\nconst inherits = require('node:util').inherits\n\nfunction SBMH (needle) {\n if (typeof needle === 'string') {\n needle = Buffer.from(needle)\n }\n\n if (!Buffer.isBuffer(needle)) {\n throw new TypeError('The needle has to be a String or a Buffer.')\n }\n\n const needleLength = needle.length\n\n if (needleLength === 0) {\n throw new Error('The needle cannot be an empty String/Buffer.')\n }\n\n if (needleLength > 256) {\n throw new Error('The needle cannot have a length bigger than 256.')\n }\n\n this.maxMatches = Infinity\n this.matches = 0\n\n this._occ = new Array(256)\n .fill(needleLength) // Initialize occurrence table.\n this._lookbehind_size = 0\n this._needle = needle\n this._bufpos = 0\n\n this._lookbehind = Buffer.alloc(needleLength)\n\n // Populate occurrence table with analysis of the needle,\n // ignoring last letter.\n for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var\n this._occ[needle[i]] = needleLength - 1 - i\n }\n}\ninherits(SBMH, EventEmitter)\n\nSBMH.prototype.reset = function () {\n this._lookbehind_size = 0\n this.matches = 0\n this._bufpos = 0\n}\n\nSBMH.prototype.push = function (chunk, pos) {\n if (!Buffer.isBuffer(chunk)) {\n chunk = Buffer.from(chunk, 'binary')\n }\n const chlen = chunk.length\n this._bufpos = pos || 0\n let r\n while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }\n return r\n}\n\nSBMH.prototype._sbmh_feed = function (data) {\n const len = data.length\n const needle = this._needle\n const needleLength = needle.length\n const lastNeedleChar = needle[needleLength - 1]\n\n // Positive: points to a position in `data`\n // pos == 3 points to data[3]\n // Negative: points to a position in the lookbehind buffer\n // pos == -2 points to lookbehind[lookbehind_size - 2]\n let pos = -this._lookbehind_size\n let ch\n\n if (pos < 0) {\n // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool\n // search with character lookup code that considers both the\n // lookbehind buffer and the current round's haystack data.\n //\n // Loop until\n // there is a match.\n // or until\n // we've moved past the position that requires the\n // lookbehind buffer. In this case we switch to the\n // optimized loop.\n // or until\n // the character to look at lies outside the haystack.\n while (pos < 0 && pos <= len - needleLength) {\n ch = this._sbmh_lookup_char(data, pos + needleLength - 1)\n\n if (\n ch === lastNeedleChar &&\n this._sbmh_memcmp(data, pos, needleLength - 1)\n ) {\n this._lookbehind_size = 0\n ++this.matches\n this.emit('info', true)\n\n return (this._bufpos = pos + needleLength)\n }\n pos += this._occ[ch]\n }\n\n // No match.\n\n if (pos < 0) {\n // There's too few data for Boyer-Moore-Horspool to run,\n // so let's use a different algorithm to skip as much as\n // we can.\n // Forward pos until\n // the trailing part of lookbehind + data\n // looks like the beginning of the needle\n // or until\n // pos == 0\n while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }\n }\n\n if (pos >= 0) {\n // Discard lookbehind buffer.\n this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)\n this._lookbehind_size = 0\n } else {\n // Cut off part of the lookbehind buffer that has\n // been processed and append the entire haystack\n // into it.\n const bytesToCutOff = this._lookbehind_size + pos\n if (bytesToCutOff > 0) {\n // The cut off data is guaranteed not to contain the needle.\n this.emit('info', false, this._lookbehind, 0, bytesToCutOff)\n }\n\n this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,\n this._lookbehind_size - bytesToCutOff)\n this._lookbehind_size -= bytesToCutOff\n\n data.copy(this._lookbehind, this._lookbehind_size)\n this._lookbehind_size += len\n\n this._bufpos = len\n return len\n }\n }\n\n pos += (pos >= 0) * this._bufpos\n\n // Lookbehind buffer is now empty. We only need to check if the\n // needle is in the haystack.\n if (data.indexOf(needle, pos) !== -1) {\n pos = data.indexOf(needle, pos)\n ++this.matches\n if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }\n\n return (this._bufpos = pos + needleLength)\n } else {\n pos = len - needleLength\n }\n\n // There was no match. If there's trailing haystack data that we cannot\n // match yet using the Boyer-Moore-Horspool algorithm (because the trailing\n // data is less than the needle size) then match using a modified\n // algorithm that starts matching from the beginning instead of the end.\n // Whatever trailing data is left after running this algorithm is added to\n // the lookbehind buffer.\n while (\n pos < len &&\n (\n data[pos] !== needle[0] ||\n (\n (Buffer.compare(\n data.subarray(pos, pos + len - pos),\n needle.subarray(0, len - pos)\n ) !== 0)\n )\n )\n ) {\n ++pos\n }\n if (pos < len) {\n data.copy(this._lookbehind, 0, pos, pos + (len - pos))\n this._lookbehind_size = len - pos\n }\n\n // Everything until pos is guaranteed not to contain needle data.\n if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }\n\n this._bufpos = len\n return len\n}\n\nSBMH.prototype._sbmh_lookup_char = function (data, pos) {\n return (pos < 0)\n ? this._lookbehind[this._lookbehind_size + pos]\n : data[pos]\n}\n\nSBMH.prototype._sbmh_memcmp = function (data, pos, len) {\n for (var i = 0; i < len; ++i) { // eslint-disable-line no-var\n if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }\n }\n return true\n}\n\nmodule.exports = SBMH\n","'use strict'\n\nconst WritableStream = require('node:stream').Writable\nconst { inherits } = require('node:util')\nconst Dicer = require('../deps/dicer/lib/Dicer')\n\nconst MultipartParser = require('./types/multipart')\nconst UrlencodedParser = require('./types/urlencoded')\nconst parseParams = require('./utils/parseParams')\n\nfunction Busboy (opts) {\n if (!(this instanceof Busboy)) { return new Busboy(opts) }\n\n if (typeof opts !== 'object') {\n throw new TypeError('Busboy expected an options-Object.')\n }\n if (typeof opts.headers !== 'object') {\n throw new TypeError('Busboy expected an options-Object with headers-attribute.')\n }\n if (typeof opts.headers['content-type'] !== 'string') {\n throw new TypeError('Missing Content-Type-header.')\n }\n\n const {\n headers,\n ...streamOptions\n } = opts\n\n this.opts = {\n autoDestroy: false,\n ...streamOptions\n }\n WritableStream.call(this, this.opts)\n\n this._done = false\n this._parser = this.getParserByHeaders(headers)\n this._finished = false\n}\ninherits(Busboy, WritableStream)\n\nBusboy.prototype.emit = function (ev) {\n if (ev === 'finish') {\n if (!this._done) {\n this._parser?.end()\n return\n } else if (this._finished) {\n return\n }\n this._finished = true\n }\n WritableStream.prototype.emit.apply(this, arguments)\n}\n\nBusboy.prototype.getParserByHeaders = function (headers) {\n const parsed = parseParams(headers['content-type'])\n\n const cfg = {\n defCharset: this.opts.defCharset,\n fileHwm: this.opts.fileHwm,\n headers,\n highWaterMark: this.opts.highWaterMark,\n isPartAFile: this.opts.isPartAFile,\n limits: this.opts.limits,\n parsedConType: parsed,\n preservePath: this.opts.preservePath\n }\n\n if (MultipartParser.detect.test(parsed[0])) {\n return new MultipartParser(this, cfg)\n }\n if (UrlencodedParser.detect.test(parsed[0])) {\n return new UrlencodedParser(this, cfg)\n }\n throw new Error('Unsupported Content-Type.')\n}\n\nBusboy.prototype._write = function (chunk, encoding, cb) {\n this._parser.write(chunk, cb)\n}\n\nmodule.exports = Busboy\nmodule.exports.default = Busboy\nmodule.exports.Busboy = Busboy\n\nmodule.exports.Dicer = Dicer\n","'use strict'\n\n// TODO:\n// * support 1 nested multipart level\n// (see second multipart example here:\n// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)\n// * support limits.fieldNameSize\n// -- this will require modifications to utils.parseParams\n\nconst { Readable } = require('node:stream')\nconst { inherits } = require('node:util')\n\nconst Dicer = require('../../deps/dicer/lib/Dicer')\n\nconst parseParams = require('../utils/parseParams')\nconst decodeText = require('../utils/decodeText')\nconst basename = require('../utils/basename')\nconst getLimit = require('../utils/getLimit')\n\nconst RE_BOUNDARY = /^boundary$/i\nconst RE_FIELD = /^form-data$/i\nconst RE_CHARSET = /^charset$/i\nconst RE_FILENAME = /^filename$/i\nconst RE_NAME = /^name$/i\n\nMultipart.detect = /^multipart\\/form-data/i\nfunction Multipart (boy, cfg) {\n let i\n let len\n const self = this\n let boundary\n const limits = cfg.limits\n const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))\n const parsedConType = cfg.parsedConType || []\n const defCharset = cfg.defCharset || 'utf8'\n const preservePath = cfg.preservePath\n const fileOpts = { highWaterMark: cfg.fileHwm }\n\n for (i = 0, len = parsedConType.length; i < len; ++i) {\n if (Array.isArray(parsedConType[i]) &&\n RE_BOUNDARY.test(parsedConType[i][0])) {\n boundary = parsedConType[i][1]\n break\n }\n }\n\n function checkFinished () {\n if (nends === 0 && finished && !boy._done) {\n finished = false\n self.end()\n }\n }\n\n if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }\n\n const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)\n const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)\n const filesLimit = getLimit(limits, 'files', Infinity)\n const fieldsLimit = getLimit(limits, 'fields', Infinity)\n const partsLimit = getLimit(limits, 'parts', Infinity)\n const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)\n const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)\n\n let nfiles = 0\n let nfields = 0\n let nends = 0\n let curFile\n let curField\n let finished = false\n\n this._needDrain = false\n this._pause = false\n this._cb = undefined\n this._nparts = 0\n this._boy = boy\n\n const parserCfg = {\n boundary,\n maxHeaderPairs: headerPairsLimit,\n maxHeaderSize: headerSizeLimit,\n partHwm: fileOpts.highWaterMark,\n highWaterMark: cfg.highWaterMark\n }\n\n this.parser = new Dicer(parserCfg)\n this.parser.on('drain', function () {\n self._needDrain = false\n if (self._cb && !self._pause) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n }).on('part', function onPart (part) {\n if (++self._nparts > partsLimit) {\n self.parser.removeListener('part', onPart)\n self.parser.on('part', skipPart)\n boy.hitPartsLimit = true\n boy.emit('partsLimit')\n return skipPart(part)\n }\n\n // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let\n // us emit 'end' early since we know the part has ended if we are already\n // seeing the next part\n if (curField) {\n const field = curField\n field.emit('end')\n field.removeAllListeners('end')\n }\n\n part.on('header', function (header) {\n let contype\n let fieldname\n let parsed\n let charset\n let encoding\n let filename\n let nsize = 0\n\n if (header['content-type']) {\n parsed = parseParams(header['content-type'][0])\n if (parsed[0]) {\n contype = parsed[0].toLowerCase()\n for (i = 0, len = parsed.length; i < len; ++i) {\n if (RE_CHARSET.test(parsed[i][0])) {\n charset = parsed[i][1].toLowerCase()\n break\n }\n }\n }\n }\n\n if (contype === undefined) { contype = 'text/plain' }\n if (charset === undefined) { charset = defCharset }\n\n if (header['content-disposition']) {\n parsed = parseParams(header['content-disposition'][0])\n if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }\n for (i = 0, len = parsed.length; i < len; ++i) {\n if (RE_NAME.test(parsed[i][0])) {\n fieldname = parsed[i][1]\n } else if (RE_FILENAME.test(parsed[i][0])) {\n filename = parsed[i][1]\n if (!preservePath) { filename = basename(filename) }\n }\n }\n } else { return skipPart(part) }\n\n if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }\n\n let onData,\n onEnd\n\n if (isPartAFile(fieldname, contype, filename)) {\n // file/binary field\n if (nfiles === filesLimit) {\n if (!boy.hitFilesLimit) {\n boy.hitFilesLimit = true\n boy.emit('filesLimit')\n }\n return skipPart(part)\n }\n\n ++nfiles\n\n if (!boy._events.file) {\n self.parser._ignore()\n return\n }\n\n ++nends\n const file = new FileStream(fileOpts)\n curFile = file\n file.on('end', function () {\n --nends\n self._pause = false\n checkFinished()\n if (self._cb && !self._needDrain) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n })\n file._read = function (n) {\n if (!self._pause) { return }\n self._pause = false\n if (self._cb && !self._needDrain) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n }\n boy.emit('file', fieldname, file, filename, encoding, contype)\n\n onData = function (data) {\n if ((nsize += data.length) > fileSizeLimit) {\n const extralen = fileSizeLimit - nsize + data.length\n if (extralen > 0) { file.push(data.slice(0, extralen)) }\n file.truncated = true\n file.bytesRead = fileSizeLimit\n part.removeAllListeners('data')\n file.emit('limit')\n return\n } else if (!file.push(data)) { self._pause = true }\n\n file.bytesRead = nsize\n }\n\n onEnd = function () {\n curFile = undefined\n file.push(null)\n }\n } else {\n // non-file field\n if (nfields === fieldsLimit) {\n if (!boy.hitFieldsLimit) {\n boy.hitFieldsLimit = true\n boy.emit('fieldsLimit')\n }\n return skipPart(part)\n }\n\n ++nfields\n ++nends\n let buffer = ''\n let truncated = false\n curField = part\n\n onData = function (data) {\n if ((nsize += data.length) > fieldSizeLimit) {\n const extralen = (fieldSizeLimit - (nsize - data.length))\n buffer += data.toString('binary', 0, extralen)\n truncated = true\n part.removeAllListeners('data')\n } else { buffer += data.toString('binary') }\n }\n\n onEnd = function () {\n curField = undefined\n if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }\n boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)\n --nends\n checkFinished()\n }\n }\n\n /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become\n broken. Streams2/streams3 is a huge black box of confusion, but\n somehow overriding the sync state seems to fix things again (and still\n seems to work for previous node versions).\n */\n part._readableState.sync = false\n\n part.on('data', onData)\n part.on('end', onEnd)\n }).on('error', function (err) {\n if (curFile) { curFile.emit('error', err) }\n })\n }).on('error', function (err) {\n boy.emit('error', err)\n }).on('finish', function () {\n finished = true\n checkFinished()\n })\n}\n\nMultipart.prototype.write = function (chunk, cb) {\n const r = this.parser.write(chunk)\n if (r && !this._pause) {\n cb()\n } else {\n this._needDrain = !r\n this._cb = cb\n }\n}\n\nMultipart.prototype.end = function () {\n const self = this\n\n if (self.parser.writable) {\n self.parser.end()\n } else if (!self._boy._done) {\n process.nextTick(function () {\n self._boy._done = true\n self._boy.emit('finish')\n })\n }\n}\n\nfunction skipPart (part) {\n part.resume()\n}\n\nfunction FileStream (opts) {\n Readable.call(this, opts)\n\n this.bytesRead = 0\n\n this.truncated = false\n}\n\ninherits(FileStream, Readable)\n\nFileStream.prototype._read = function (n) {}\n\nmodule.exports = Multipart\n","'use strict'\n\nconst Decoder = require('../utils/Decoder')\nconst decodeText = require('../utils/decodeText')\nconst getLimit = require('../utils/getLimit')\n\nconst RE_CHARSET = /^charset$/i\n\nUrlEncoded.detect = /^application\\/x-www-form-urlencoded/i\nfunction UrlEncoded (boy, cfg) {\n const limits = cfg.limits\n const parsedConType = cfg.parsedConType\n this.boy = boy\n\n this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)\n this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)\n this.fieldsLimit = getLimit(limits, 'fields', Infinity)\n\n let charset\n for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var\n if (Array.isArray(parsedConType[i]) &&\n RE_CHARSET.test(parsedConType[i][0])) {\n charset = parsedConType[i][1].toLowerCase()\n break\n }\n }\n\n if (charset === undefined) { charset = cfg.defCharset || 'utf8' }\n\n this.decoder = new Decoder()\n this.charset = charset\n this._fields = 0\n this._state = 'key'\n this._checkingBytes = true\n this._bytesKey = 0\n this._bytesVal = 0\n this._key = ''\n this._val = ''\n this._keyTrunc = false\n this._valTrunc = false\n this._hitLimit = false\n}\n\nUrlEncoded.prototype.write = function (data, cb) {\n if (this._fields === this.fieldsLimit) {\n if (!this.boy.hitFieldsLimit) {\n this.boy.hitFieldsLimit = true\n this.boy.emit('fieldsLimit')\n }\n return cb()\n }\n\n let idxeq; let idxamp; let i; let p = 0; const len = data.length\n\n while (p < len) {\n if (this._state === 'key') {\n idxeq = idxamp = undefined\n for (i = p; i < len; ++i) {\n if (!this._checkingBytes) { ++p }\n if (data[i] === 0x3D/* = */) {\n idxeq = i\n break\n } else if (data[i] === 0x26/* & */) {\n idxamp = i\n break\n }\n if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {\n this._hitLimit = true\n break\n } else if (this._checkingBytes) { ++this._bytesKey }\n }\n\n if (idxeq !== undefined) {\n // key with assignment\n if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }\n this._state = 'val'\n\n this._hitLimit = false\n this._checkingBytes = true\n this._val = ''\n this._bytesVal = 0\n this._valTrunc = false\n this.decoder.reset()\n\n p = idxeq + 1\n } else if (idxamp !== undefined) {\n // key with no assignment\n ++this._fields\n let key; const keyTrunc = this._keyTrunc\n if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }\n\n this._hitLimit = false\n this._checkingBytes = true\n this._key = ''\n this._bytesKey = 0\n this._keyTrunc = false\n this.decoder.reset()\n\n if (key.length) {\n this.boy.emit('field', decodeText(key, 'binary', this.charset),\n '',\n keyTrunc,\n false)\n }\n\n p = idxamp + 1\n if (this._fields === this.fieldsLimit) { return cb() }\n } else if (this._hitLimit) {\n // we may not have hit the actual limit if there are encoded bytes...\n if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }\n p = i\n if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {\n // yep, we actually did hit the limit\n this._checkingBytes = false\n this._keyTrunc = true\n }\n } else {\n if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }\n p = len\n }\n } else {\n idxamp = undefined\n for (i = p; i < len; ++i) {\n if (!this._checkingBytes) { ++p }\n if (data[i] === 0x26/* & */) {\n idxamp = i\n break\n }\n if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {\n this._hitLimit = true\n break\n } else if (this._checkingBytes) { ++this._bytesVal }\n }\n\n if (idxamp !== undefined) {\n ++this._fields\n if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n decodeText(this._val, 'binary', this.charset),\n this._keyTrunc,\n this._valTrunc)\n this._state = 'key'\n\n this._hitLimit = false\n this._checkingBytes = true\n this._key = ''\n this._bytesKey = 0\n this._keyTrunc = false\n this.decoder.reset()\n\n p = idxamp + 1\n if (this._fields === this.fieldsLimit) { return cb() }\n } else if (this._hitLimit) {\n // we may not have hit the actual limit if there are encoded bytes...\n if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }\n p = i\n if ((this._val === '' && this.fieldSizeLimit === 0) ||\n (this._bytesVal = this._val.length) === this.fieldSizeLimit) {\n // yep, we actually did hit the limit\n this._checkingBytes = false\n this._valTrunc = true\n }\n } else {\n if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }\n p = len\n }\n }\n }\n cb()\n}\n\nUrlEncoded.prototype.end = function () {\n if (this.boy._done) { return }\n\n if (this._state === 'key' && this._key.length > 0) {\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n '',\n this._keyTrunc,\n false)\n } else if (this._state === 'val') {\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n decodeText(this._val, 'binary', this.charset),\n this._keyTrunc,\n this._valTrunc)\n }\n this.boy._done = true\n this.boy.emit('finish')\n}\n\nmodule.exports = UrlEncoded\n","'use strict'\n\nconst RE_PLUS = /\\+/g\n\nconst HEX = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n]\n\nfunction Decoder () {\n this.buffer = undefined\n}\nDecoder.prototype.write = function (str) {\n // Replace '+' with ' ' before decoding\n str = str.replace(RE_PLUS, ' ')\n let res = ''\n let i = 0; let p = 0; const len = str.length\n for (; i < len; ++i) {\n if (this.buffer !== undefined) {\n if (!HEX[str.charCodeAt(i)]) {\n res += '%' + this.buffer\n this.buffer = undefined\n --i // retry character\n } else {\n this.buffer += str[i]\n ++p\n if (this.buffer.length === 2) {\n res += String.fromCharCode(parseInt(this.buffer, 16))\n this.buffer = undefined\n }\n }\n } else if (str[i] === '%') {\n if (i > p) {\n res += str.substring(p, i)\n p = i\n }\n this.buffer = ''\n ++p\n }\n }\n if (p < len && this.buffer === undefined) { res += str.substring(p) }\n return res\n}\nDecoder.prototype.reset = function () {\n this.buffer = undefined\n}\n\nmodule.exports = Decoder\n","'use strict'\n\nmodule.exports = function basename (path) {\n if (typeof path !== 'string') { return '' }\n for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var\n switch (path.charCodeAt(i)) {\n case 0x2F: // '/'\n case 0x5C: // '\\'\n path = path.slice(i + 1)\n return (path === '..' || path === '.' ? '' : path)\n }\n }\n return (path === '..' || path === '.' ? '' : path)\n}\n","'use strict'\n\n// Node has always utf-8\nconst utf8Decoder = new TextDecoder('utf-8')\nconst textDecoders = new Map([\n ['utf-8', utf8Decoder],\n ['utf8', utf8Decoder]\n])\n\nfunction decodeText (text, textEncoding, destEncoding) {\n if (text) {\n if (textDecoders.has(destEncoding)) {\n try {\n return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))\n } catch (e) { }\n } else {\n try {\n textDecoders.set(destEncoding, new TextDecoder(destEncoding))\n return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))\n } catch (e) { }\n }\n }\n return text\n}\n\nmodule.exports = decodeText\n","'use strict'\n\nmodule.exports = function getLimit (limits, name, defaultLimit) {\n if (\n !limits ||\n limits[name] === undefined ||\n limits[name] === null\n ) { return defaultLimit }\n\n if (\n typeof limits[name] !== 'number' ||\n isNaN(limits[name])\n ) { throw new TypeError('Limit ' + name + ' is not a valid number') }\n\n return limits[name]\n}\n","'use strict'\n\nconst decodeText = require('./decodeText')\n\nconst RE_ENCODED = /%([a-fA-F0-9]{2})/g\n\nfunction encodedReplacer (match, byte) {\n return String.fromCharCode(parseInt(byte, 16))\n}\n\nfunction parseParams (str) {\n const res = []\n let state = 'key'\n let charset = ''\n let inquote = false\n let escaping = false\n let p = 0\n let tmp = ''\n\n for (var i = 0, len = str.length; i < len; ++i) { // eslint-disable-line no-var\n const char = str[i]\n if (char === '\\\\' && inquote) {\n if (escaping) { escaping = false } else {\n escaping = true\n continue\n }\n } else if (char === '\"') {\n if (!escaping) {\n if (inquote) {\n inquote = false\n state = 'key'\n } else { inquote = true }\n continue\n } else { escaping = false }\n } else {\n if (escaping && inquote) { tmp += '\\\\' }\n escaping = false\n if ((state === 'charset' || state === 'lang') && char === \"'\") {\n if (state === 'charset') {\n state = 'lang'\n charset = tmp.substring(1)\n } else { state = 'value' }\n tmp = ''\n continue\n } else if (state === 'key' &&\n (char === '*' || char === '=') &&\n res.length) {\n if (char === '*') { state = 'charset' } else { state = 'value' }\n res[p] = [tmp, undefined]\n tmp = ''\n continue\n } else if (!inquote && char === ';') {\n state = 'key'\n if (charset) {\n if (tmp.length) {\n tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),\n 'binary',\n charset)\n }\n charset = ''\n } else if (tmp.length) {\n tmp = decodeText(tmp, 'binary', 'utf8')\n }\n if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }\n tmp = ''\n ++p\n continue\n } else if (!inquote && (char === ' ' || char === '\\t')) { continue }\n }\n tmp += char\n }\n if (charset && tmp.length) {\n tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),\n 'binary',\n charset)\n } else if (tmp) {\n tmp = decodeText(tmp, 'binary', 'utf8')\n }\n\n if (res[p] === undefined) {\n if (tmp) { res[p] = tmp }\n } else { res[p][1] = tmp }\n\n return res\n}\n\nmodule.exports = parseParams\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n createTokenAuth: () => createTokenAuth\n});\nmodule.exports = __toCommonJS(dist_src_exports);\n\n// pkg/dist-src/auth.js\nvar REGEX_IS_INSTALLATION_LEGACY = /^v1\\./;\nvar REGEX_IS_INSTALLATION = /^ghs_/;\nvar REGEX_IS_USER_TO_SERVER = /^ghu_/;\nasync function auth(token) {\n const isApp = token.split(/\\./).length === 3;\n const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);\n const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);\n const tokenType = isApp ? \"app\" : isInstallation ? \"installation\" : isUserToServer ? \"user-to-server\" : \"oauth\";\n return {\n type: \"token\",\n token,\n tokenType\n };\n}\n\n// pkg/dist-src/with-authorization-prefix.js\nfunction withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n\n// pkg/dist-src/hook.js\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(\n route,\n parameters\n );\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n\n// pkg/dist-src/index.js\nvar createTokenAuth = function createTokenAuth2(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\n \"[@octokit/auth-token] Token passed to createTokenAuth is not a string\"\n );\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n createTokenAuth\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n Octokit: () => Octokit\n});\nmodule.exports = __toCommonJS(dist_src_exports);\nvar import_universal_user_agent = require(\"universal-user-agent\");\nvar import_before_after_hook = require(\"before-after-hook\");\nvar import_request = require(\"@octokit/request\");\nvar import_graphql = require(\"@octokit/graphql\");\nvar import_auth_token = require(\"@octokit/auth-token\");\n\n// pkg/dist-src/version.js\nvar VERSION = \"5.2.0\";\n\n// pkg/dist-src/index.js\nvar noop = () => {\n};\nvar consoleWarn = console.warn.bind(console);\nvar consoleError = console.error.bind(console);\nvar userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;\nvar Octokit = class {\n static {\n this.VERSION = VERSION;\n }\n static defaults(defaults) {\n const OctokitWithDefaults = class extends this {\n constructor(...args) {\n const options = args[0] || {};\n if (typeof defaults === \"function\") {\n super(defaults(options));\n return;\n }\n super(\n Object.assign(\n {},\n defaults,\n options,\n options.userAgent && defaults.userAgent ? {\n userAgent: `${options.userAgent} ${defaults.userAgent}`\n } : null\n )\n );\n }\n };\n return OctokitWithDefaults;\n }\n static {\n this.plugins = [];\n }\n /**\n * Attach a plugin (or many) to your Octokit instance.\n *\n * @example\n * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)\n */\n static plugin(...newPlugins) {\n const currentPlugins = this.plugins;\n const NewOctokit = class extends this {\n static {\n this.plugins = currentPlugins.concat(\n newPlugins.filter((plugin) => !currentPlugins.includes(plugin))\n );\n }\n };\n return NewOctokit;\n }\n constructor(options = {}) {\n const hook = new import_before_after_hook.Collection();\n const requestDefaults = {\n baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl,\n headers: {},\n request: Object.assign({}, options.request, {\n // @ts-ignore internal usage only, no need to type\n hook: hook.bind(null, \"request\")\n }),\n mediaType: {\n previews: [],\n format: \"\"\n }\n };\n requestDefaults.headers[\"user-agent\"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;\n if (options.baseUrl) {\n requestDefaults.baseUrl = options.baseUrl;\n }\n if (options.previews) {\n requestDefaults.mediaType.previews = options.previews;\n }\n if (options.timeZone) {\n requestDefaults.headers[\"time-zone\"] = options.timeZone;\n }\n this.request = import_request.request.defaults(requestDefaults);\n this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults);\n this.log = Object.assign(\n {\n debug: noop,\n info: noop,\n warn: consoleWarn,\n error: consoleError\n },\n options.log\n );\n this.hook = hook;\n if (!options.authStrategy) {\n if (!options.auth) {\n this.auth = async () => ({\n type: \"unauthenticated\"\n });\n } else {\n const auth = (0, import_auth_token.createTokenAuth)(options.auth);\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n } else {\n const { authStrategy, ...otherOptions } = options;\n const auth = authStrategy(\n Object.assign(\n {\n request: this.request,\n log: this.log,\n // we pass the current octokit instance as well as its constructor options\n // to allow for authentication strategies that return a new octokit instance\n // that shares the same internal state as the current one. The original\n // requirement for this was the \"event-octokit\" authentication strategy\n // of https://github.com/probot/octokit-auth-probot.\n octokit: this,\n octokitOptions: otherOptions\n },\n options.auth\n )\n );\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n const classConstructor = this.constructor;\n for (let i = 0; i < classConstructor.plugins.length; ++i) {\n Object.assign(this, classConstructor.plugins[i](this, options));\n }\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Octokit\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n endpoint: () => endpoint\n});\nmodule.exports = __toCommonJS(dist_src_exports);\n\n// pkg/dist-src/defaults.js\nvar import_universal_user_agent = require(\"universal-user-agent\");\n\n// pkg/dist-src/version.js\nvar VERSION = \"9.0.5\";\n\n// pkg/dist-src/defaults.js\nvar userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;\nvar DEFAULTS = {\n method: \"GET\",\n baseUrl: \"https://api.github.com\",\n headers: {\n accept: \"application/vnd.github.v3+json\",\n \"user-agent\": userAgent\n },\n mediaType: {\n format: \"\"\n }\n};\n\n// pkg/dist-src/util/lowercase-keys.js\nfunction lowercaseKeys(object) {\n if (!object) {\n return {};\n }\n return Object.keys(object).reduce((newObj, key) => {\n newObj[key.toLowerCase()] = object[key];\n return newObj;\n }, {});\n}\n\n// pkg/dist-src/util/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null)\n return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\")\n return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null)\n return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/util/merge-deep.js\nfunction mergeDeep(defaults, options) {\n const result = Object.assign({}, defaults);\n Object.keys(options).forEach((key) => {\n if (isPlainObject(options[key])) {\n if (!(key in defaults))\n Object.assign(result, { [key]: options[key] });\n else\n result[key] = mergeDeep(defaults[key], options[key]);\n } else {\n Object.assign(result, { [key]: options[key] });\n }\n });\n return result;\n}\n\n// pkg/dist-src/util/remove-undefined-properties.js\nfunction removeUndefinedProperties(obj) {\n for (const key in obj) {\n if (obj[key] === void 0) {\n delete obj[key];\n }\n }\n return obj;\n}\n\n// pkg/dist-src/merge.js\nfunction merge(defaults, route, options) {\n if (typeof route === \"string\") {\n let [method, url] = route.split(\" \");\n options = Object.assign(url ? { method, url } : { url: method }, options);\n } else {\n options = Object.assign({}, route);\n }\n options.headers = lowercaseKeys(options.headers);\n removeUndefinedProperties(options);\n removeUndefinedProperties(options.headers);\n const mergedOptions = mergeDeep(defaults || {}, options);\n if (options.url === \"/graphql\") {\n if (defaults && defaults.mediaType.previews?.length) {\n mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(\n (preview) => !mergedOptions.mediaType.previews.includes(preview)\n ).concat(mergedOptions.mediaType.previews);\n }\n mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, \"\"));\n }\n return mergedOptions;\n}\n\n// pkg/dist-src/util/add-query-parameters.js\nfunction addQueryParameters(url, parameters) {\n const separator = /\\?/.test(url) ? \"&\" : \"?\";\n const names = Object.keys(parameters);\n if (names.length === 0) {\n return url;\n }\n return url + separator + names.map((name) => {\n if (name === \"q\") {\n return \"q=\" + parameters.q.split(\"+\").map(encodeURIComponent).join(\"+\");\n }\n return `${name}=${encodeURIComponent(parameters[name])}`;\n }).join(\"&\");\n}\n\n// pkg/dist-src/util/extract-url-variable-names.js\nvar urlVariableRegex = /\\{[^}]+\\}/g;\nfunction removeNonChars(variableName) {\n return variableName.replace(/^\\W+|\\W+$/g, \"\").split(/,/);\n}\nfunction extractUrlVariableNames(url) {\n const matches = url.match(urlVariableRegex);\n if (!matches) {\n return [];\n }\n return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);\n}\n\n// pkg/dist-src/util/omit.js\nfunction omit(object, keysToOmit) {\n const result = { __proto__: null };\n for (const key of Object.keys(object)) {\n if (keysToOmit.indexOf(key) === -1) {\n result[key] = object[key];\n }\n }\n return result;\n}\n\n// pkg/dist-src/util/url-template.js\nfunction encodeReserved(str) {\n return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {\n if (!/%[0-9A-Fa-f]/.test(part)) {\n part = encodeURI(part).replace(/%5B/g, \"[\").replace(/%5D/g, \"]\");\n }\n return part;\n }).join(\"\");\n}\nfunction encodeUnreserved(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\nfunction encodeValue(operator, value, key) {\n value = operator === \"+\" || operator === \"#\" ? encodeReserved(value) : encodeUnreserved(value);\n if (key) {\n return encodeUnreserved(key) + \"=\" + value;\n } else {\n return value;\n }\n}\nfunction isDefined(value) {\n return value !== void 0 && value !== null;\n}\nfunction isKeyOperator(operator) {\n return operator === \";\" || operator === \"&\" || operator === \"?\";\n}\nfunction getValues(context, operator, key, modifier) {\n var value = context[key], result = [];\n if (isDefined(value) && value !== \"\") {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n value = value.toString();\n if (modifier && modifier !== \"*\") {\n value = value.substring(0, parseInt(modifier, 10));\n }\n result.push(\n encodeValue(operator, value, isKeyOperator(operator) ? key : \"\")\n );\n } else {\n if (modifier === \"*\") {\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n result.push(\n encodeValue(operator, value2, isKeyOperator(operator) ? key : \"\")\n );\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n result.push(encodeValue(operator, value[k], k));\n }\n });\n }\n } else {\n const tmp = [];\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n tmp.push(encodeValue(operator, value2));\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n tmp.push(encodeUnreserved(k));\n tmp.push(encodeValue(operator, value[k].toString()));\n }\n });\n }\n if (isKeyOperator(operator)) {\n result.push(encodeUnreserved(key) + \"=\" + tmp.join(\",\"));\n } else if (tmp.length !== 0) {\n result.push(tmp.join(\",\"));\n }\n }\n }\n } else {\n if (operator === \";\") {\n if (isDefined(value)) {\n result.push(encodeUnreserved(key));\n }\n } else if (value === \"\" && (operator === \"&\" || operator === \"?\")) {\n result.push(encodeUnreserved(key) + \"=\");\n } else if (value === \"\") {\n result.push(\"\");\n }\n }\n return result;\n}\nfunction parseUrl(template) {\n return {\n expand: expand.bind(null, template)\n };\n}\nfunction expand(template, context) {\n var operators = [\"+\", \"#\", \".\", \"/\", \";\", \"?\", \"&\"];\n template = template.replace(\n /\\{([^\\{\\}]+)\\}|([^\\{\\}]+)/g,\n function(_, expression, literal) {\n if (expression) {\n let operator = \"\";\n const values = [];\n if (operators.indexOf(expression.charAt(0)) !== -1) {\n operator = expression.charAt(0);\n expression = expression.substr(1);\n }\n expression.split(/,/g).forEach(function(variable) {\n var tmp = /([^:\\*]*)(?::(\\d+)|(\\*))?/.exec(variable);\n values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));\n });\n if (operator && operator !== \"+\") {\n var separator = \",\";\n if (operator === \"?\") {\n separator = \"&\";\n } else if (operator !== \"#\") {\n separator = operator;\n }\n return (values.length !== 0 ? operator : \"\") + values.join(separator);\n } else {\n return values.join(\",\");\n }\n } else {\n return encodeReserved(literal);\n }\n }\n );\n if (template === \"/\") {\n return template;\n } else {\n return template.replace(/\\/$/, \"\");\n }\n}\n\n// pkg/dist-src/parse.js\nfunction parse(options) {\n let method = options.method.toUpperCase();\n let url = (options.url || \"/\").replace(/:([a-z]\\w+)/g, \"{$1}\");\n let headers = Object.assign({}, options.headers);\n let body;\n let parameters = omit(options, [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"mediaType\"\n ]);\n const urlVariableNames = extractUrlVariableNames(url);\n url = parseUrl(url).expand(parameters);\n if (!/^http/.test(url)) {\n url = options.baseUrl + url;\n }\n const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat(\"baseUrl\");\n const remainingParameters = omit(parameters, omittedParameters);\n const isBinaryRequest = /application\\/octet-stream/i.test(headers.accept);\n if (!isBinaryRequest) {\n if (options.mediaType.format) {\n headers.accept = headers.accept.split(/,/).map(\n (format) => format.replace(\n /application\\/vnd(\\.\\w+)(\\.v3)?(\\.\\w+)?(\\+json)?$/,\n `application/vnd$1$2.${options.mediaType.format}`\n )\n ).join(\",\");\n }\n if (url.endsWith(\"/graphql\")) {\n if (options.mediaType.previews?.length) {\n const previewsFromAcceptHeader = headers.accept.match(/[\\w-]+(?=-preview)/g) || [];\n headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {\n const format = options.mediaType.format ? `.${options.mediaType.format}` : \"+json\";\n return `application/vnd.github.${preview}-preview${format}`;\n }).join(\",\");\n }\n }\n }\n if ([\"GET\", \"HEAD\"].includes(method)) {\n url = addQueryParameters(url, remainingParameters);\n } else {\n if (\"data\" in remainingParameters) {\n body = remainingParameters.data;\n } else {\n if (Object.keys(remainingParameters).length) {\n body = remainingParameters;\n }\n }\n }\n if (!headers[\"content-type\"] && typeof body !== \"undefined\") {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n }\n if ([\"PATCH\", \"PUT\"].includes(method) && typeof body === \"undefined\") {\n body = \"\";\n }\n return Object.assign(\n { method, url, headers },\n typeof body !== \"undefined\" ? { body } : null,\n options.request ? { request: options.request } : null\n );\n}\n\n// pkg/dist-src/endpoint-with-defaults.js\nfunction endpointWithDefaults(defaults, route, options) {\n return parse(merge(defaults, route, options));\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldDefaults, newDefaults) {\n const DEFAULTS2 = merge(oldDefaults, newDefaults);\n const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);\n return Object.assign(endpoint2, {\n DEFAULTS: DEFAULTS2,\n defaults: withDefaults.bind(null, DEFAULTS2),\n merge: merge.bind(null, DEFAULTS2),\n parse\n });\n}\n\n// pkg/dist-src/index.js\nvar endpoint = withDefaults(null, DEFAULTS);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n endpoint\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n GraphqlResponseError: () => GraphqlResponseError,\n graphql: () => graphql2,\n withCustomRequest: () => withCustomRequest\n});\nmodule.exports = __toCommonJS(dist_src_exports);\nvar import_request3 = require(\"@octokit/request\");\nvar import_universal_user_agent = require(\"universal-user-agent\");\n\n// pkg/dist-src/version.js\nvar VERSION = \"7.1.0\";\n\n// pkg/dist-src/with-defaults.js\nvar import_request2 = require(\"@octokit/request\");\n\n// pkg/dist-src/graphql.js\nvar import_request = require(\"@octokit/request\");\n\n// pkg/dist-src/error.js\nfunction _buildMessageForResponseErrors(data) {\n return `Request failed due to following response errors:\n` + data.errors.map((e) => ` - ${e.message}`).join(\"\\n\");\n}\nvar GraphqlResponseError = class extends Error {\n constructor(request2, headers, response) {\n super(_buildMessageForResponseErrors(response));\n this.request = request2;\n this.headers = headers;\n this.response = response;\n this.name = \"GraphqlResponseError\";\n this.errors = response.errors;\n this.data = response.data;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n};\n\n// pkg/dist-src/graphql.js\nvar NON_VARIABLE_OPTIONS = [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"query\",\n \"mediaType\"\n];\nvar FORBIDDEN_VARIABLE_OPTIONS = [\"query\", \"method\", \"url\"];\nvar GHES_V3_SUFFIX_REGEX = /\\/api\\/v3\\/?$/;\nfunction graphql(request2, query, options) {\n if (options) {\n if (typeof query === \"string\" && \"query\" in options) {\n return Promise.reject(\n new Error(`[@octokit/graphql] \"query\" cannot be used as variable name`)\n );\n }\n for (const key in options) {\n if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))\n continue;\n return Promise.reject(\n new Error(\n `[@octokit/graphql] \"${key}\" cannot be used as variable name`\n )\n );\n }\n }\n const parsedOptions = typeof query === \"string\" ? Object.assign({ query }, options) : query;\n const requestOptions = Object.keys(\n parsedOptions\n ).reduce((result, key) => {\n if (NON_VARIABLE_OPTIONS.includes(key)) {\n result[key] = parsedOptions[key];\n return result;\n }\n if (!result.variables) {\n result.variables = {};\n }\n result.variables[key] = parsedOptions[key];\n return result;\n }, {});\n const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;\n if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {\n requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, \"/api/graphql\");\n }\n return request2(requestOptions).then((response) => {\n if (response.data.errors) {\n const headers = {};\n for (const key of Object.keys(response.headers)) {\n headers[key] = response.headers[key];\n }\n throw new GraphqlResponseError(\n requestOptions,\n headers,\n response.data\n );\n }\n return response.data.data;\n });\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(request2, newDefaults) {\n const newRequest = request2.defaults(newDefaults);\n const newApi = (query, options) => {\n return graphql(newRequest, query, options);\n };\n return Object.assign(newApi, {\n defaults: withDefaults.bind(null, newRequest),\n endpoint: newRequest.endpoint\n });\n}\n\n// pkg/dist-src/index.js\nvar graphql2 = withDefaults(import_request3.request, {\n headers: {\n \"user-agent\": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`\n },\n method: \"POST\",\n url: \"/graphql\"\n});\nfunction withCustomRequest(customRequest) {\n return withDefaults(customRequest, {\n method: \"POST\",\n url: \"/graphql\"\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n GraphqlResponseError,\n graphql,\n withCustomRequest\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n composePaginateRest: () => composePaginateRest,\n isPaginatingEndpoint: () => isPaginatingEndpoint,\n paginateRest: () => paginateRest,\n paginatingEndpoints: () => paginatingEndpoints\n});\nmodule.exports = __toCommonJS(dist_src_exports);\n\n// pkg/dist-src/version.js\nvar VERSION = \"9.2.1\";\n\n// pkg/dist-src/normalize-paginated-list-response.js\nfunction normalizePaginatedListResponse(response) {\n if (!response.data) {\n return {\n ...response,\n data: []\n };\n }\n const responseNeedsNormalization = \"total_count\" in response.data && !(\"url\" in response.data);\n if (!responseNeedsNormalization)\n return response;\n const incompleteResults = response.data.incomplete_results;\n const repositorySelection = response.data.repository_selection;\n const totalCount = response.data.total_count;\n delete response.data.incomplete_results;\n delete response.data.repository_selection;\n delete response.data.total_count;\n const namespaceKey = Object.keys(response.data)[0];\n const data = response.data[namespaceKey];\n response.data = data;\n if (typeof incompleteResults !== \"undefined\") {\n response.data.incomplete_results = incompleteResults;\n }\n if (typeof repositorySelection !== \"undefined\") {\n response.data.repository_selection = repositorySelection;\n }\n response.data.total_count = totalCount;\n return response;\n}\n\n// pkg/dist-src/iterator.js\nfunction iterator(octokit, route, parameters) {\n const options = typeof route === \"function\" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);\n const requestMethod = typeof route === \"function\" ? route : octokit.request;\n const method = options.method;\n const headers = options.headers;\n let url = options.url;\n return {\n [Symbol.asyncIterator]: () => ({\n async next() {\n if (!url)\n return { done: true };\n try {\n const response = await requestMethod({ method, url, headers });\n const normalizedResponse = normalizePaginatedListResponse(response);\n url = ((normalizedResponse.headers.link || \"\").match(\n /<([^>]+)>;\\s*rel=\"next\"/\n ) || [])[1];\n return { value: normalizedResponse };\n } catch (error) {\n if (error.status !== 409)\n throw error;\n url = \"\";\n return {\n value: {\n status: 200,\n headers: {},\n data: []\n }\n };\n }\n }\n })\n };\n}\n\n// pkg/dist-src/paginate.js\nfunction paginate(octokit, route, parameters, mapFn) {\n if (typeof parameters === \"function\") {\n mapFn = parameters;\n parameters = void 0;\n }\n return gather(\n octokit,\n [],\n iterator(octokit, route, parameters)[Symbol.asyncIterator](),\n mapFn\n );\n}\nfunction gather(octokit, results, iterator2, mapFn) {\n return iterator2.next().then((result) => {\n if (result.done) {\n return results;\n }\n let earlyExit = false;\n function done() {\n earlyExit = true;\n }\n results = results.concat(\n mapFn ? mapFn(result.value, done) : result.value.data\n );\n if (earlyExit) {\n return results;\n }\n return gather(octokit, results, iterator2, mapFn);\n });\n}\n\n// pkg/dist-src/compose-paginate.js\nvar composePaginateRest = Object.assign(paginate, {\n iterator\n});\n\n// pkg/dist-src/generated/paginating-endpoints.js\nvar paginatingEndpoints = [\n \"GET /advisories\",\n \"GET /app/hook/deliveries\",\n \"GET /app/installation-requests\",\n \"GET /app/installations\",\n \"GET /assignments/{assignment_id}/accepted_assignments\",\n \"GET /classrooms\",\n \"GET /classrooms/{classroom_id}/assignments\",\n \"GET /enterprises/{enterprise}/dependabot/alerts\",\n \"GET /enterprises/{enterprise}/secret-scanning/alerts\",\n \"GET /events\",\n \"GET /gists\",\n \"GET /gists/public\",\n \"GET /gists/starred\",\n \"GET /gists/{gist_id}/comments\",\n \"GET /gists/{gist_id}/commits\",\n \"GET /gists/{gist_id}/forks\",\n \"GET /installation/repositories\",\n \"GET /issues\",\n \"GET /licenses\",\n \"GET /marketplace_listing/plans\",\n \"GET /marketplace_listing/plans/{plan_id}/accounts\",\n \"GET /marketplace_listing/stubbed/plans\",\n \"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\",\n \"GET /networks/{owner}/{repo}/events\",\n \"GET /notifications\",\n \"GET /organizations\",\n \"GET /orgs/{org}/actions/cache/usage-by-repository\",\n \"GET /orgs/{org}/actions/permissions/repositories\",\n \"GET /orgs/{org}/actions/runners\",\n \"GET /orgs/{org}/actions/secrets\",\n \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/actions/variables\",\n \"GET /orgs/{org}/actions/variables/{name}/repositories\",\n \"GET /orgs/{org}/blocks\",\n \"GET /orgs/{org}/code-scanning/alerts\",\n \"GET /orgs/{org}/codespaces\",\n \"GET /orgs/{org}/codespaces/secrets\",\n \"GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/copilot/billing/seats\",\n \"GET /orgs/{org}/dependabot/alerts\",\n \"GET /orgs/{org}/dependabot/secrets\",\n \"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/events\",\n \"GET /orgs/{org}/failed_invitations\",\n \"GET /orgs/{org}/hooks\",\n \"GET /orgs/{org}/hooks/{hook_id}/deliveries\",\n \"GET /orgs/{org}/installations\",\n \"GET /orgs/{org}/invitations\",\n \"GET /orgs/{org}/invitations/{invitation_id}/teams\",\n \"GET /orgs/{org}/issues\",\n \"GET /orgs/{org}/members\",\n \"GET /orgs/{org}/members/{username}/codespaces\",\n \"GET /orgs/{org}/migrations\",\n \"GET /orgs/{org}/migrations/{migration_id}/repositories\",\n \"GET /orgs/{org}/organization-roles/{role_id}/teams\",\n \"GET /orgs/{org}/organization-roles/{role_id}/users\",\n \"GET /orgs/{org}/outside_collaborators\",\n \"GET /orgs/{org}/packages\",\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n \"GET /orgs/{org}/personal-access-token-requests\",\n \"GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories\",\n \"GET /orgs/{org}/personal-access-tokens\",\n \"GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories\",\n \"GET /orgs/{org}/projects\",\n \"GET /orgs/{org}/properties/values\",\n \"GET /orgs/{org}/public_members\",\n \"GET /orgs/{org}/repos\",\n \"GET /orgs/{org}/rulesets\",\n \"GET /orgs/{org}/rulesets/rule-suites\",\n \"GET /orgs/{org}/secret-scanning/alerts\",\n \"GET /orgs/{org}/security-advisories\",\n \"GET /orgs/{org}/teams\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\",\n \"GET /orgs/{org}/teams/{team_slug}/invitations\",\n \"GET /orgs/{org}/teams/{team_slug}/members\",\n \"GET /orgs/{org}/teams/{team_slug}/projects\",\n \"GET /orgs/{org}/teams/{team_slug}/repos\",\n \"GET /orgs/{org}/teams/{team_slug}/teams\",\n \"GET /projects/columns/{column_id}/cards\",\n \"GET /projects/{project_id}/collaborators\",\n \"GET /projects/{project_id}/columns\",\n \"GET /repos/{owner}/{repo}/actions/artifacts\",\n \"GET /repos/{owner}/{repo}/actions/caches\",\n \"GET /repos/{owner}/{repo}/actions/organization-secrets\",\n \"GET /repos/{owner}/{repo}/actions/organization-variables\",\n \"GET /repos/{owner}/{repo}/actions/runners\",\n \"GET /repos/{owner}/{repo}/actions/runs\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\",\n \"GET /repos/{owner}/{repo}/actions/secrets\",\n \"GET /repos/{owner}/{repo}/actions/variables\",\n \"GET /repos/{owner}/{repo}/actions/workflows\",\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\",\n \"GET /repos/{owner}/{repo}/activity\",\n \"GET /repos/{owner}/{repo}/assignees\",\n \"GET /repos/{owner}/{repo}/branches\",\n \"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\",\n \"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\",\n \"GET /repos/{owner}/{repo}/code-scanning/alerts\",\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n \"GET /repos/{owner}/{repo}/code-scanning/analyses\",\n \"GET /repos/{owner}/{repo}/codespaces\",\n \"GET /repos/{owner}/{repo}/codespaces/devcontainers\",\n \"GET /repos/{owner}/{repo}/codespaces/secrets\",\n \"GET /repos/{owner}/{repo}/collaborators\",\n \"GET /repos/{owner}/{repo}/comments\",\n \"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/commits\",\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/status\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/statuses\",\n \"GET /repos/{owner}/{repo}/contributors\",\n \"GET /repos/{owner}/{repo}/dependabot/alerts\",\n \"GET /repos/{owner}/{repo}/dependabot/secrets\",\n \"GET /repos/{owner}/{repo}/deployments\",\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\",\n \"GET /repos/{owner}/{repo}/environments\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps\",\n \"GET /repos/{owner}/{repo}/events\",\n \"GET /repos/{owner}/{repo}/forks\",\n \"GET /repos/{owner}/{repo}/hooks\",\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries\",\n \"GET /repos/{owner}/{repo}/invitations\",\n \"GET /repos/{owner}/{repo}/issues\",\n \"GET /repos/{owner}/{repo}/issues/comments\",\n \"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/issues/events\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/events\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\",\n \"GET /repos/{owner}/{repo}/keys\",\n \"GET /repos/{owner}/{repo}/labels\",\n \"GET /repos/{owner}/{repo}/milestones\",\n \"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\",\n \"GET /repos/{owner}/{repo}/notifications\",\n \"GET /repos/{owner}/{repo}/pages/builds\",\n \"GET /repos/{owner}/{repo}/projects\",\n \"GET /repos/{owner}/{repo}/pulls\",\n \"GET /repos/{owner}/{repo}/pulls/comments\",\n \"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\",\n \"GET /repos/{owner}/{repo}/releases\",\n \"GET /repos/{owner}/{repo}/releases/{release_id}/assets\",\n \"GET /repos/{owner}/{repo}/releases/{release_id}/reactions\",\n \"GET /repos/{owner}/{repo}/rules/branches/{branch}\",\n \"GET /repos/{owner}/{repo}/rulesets\",\n \"GET /repos/{owner}/{repo}/rulesets/rule-suites\",\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts\",\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations\",\n \"GET /repos/{owner}/{repo}/security-advisories\",\n \"GET /repos/{owner}/{repo}/stargazers\",\n \"GET /repos/{owner}/{repo}/subscribers\",\n \"GET /repos/{owner}/{repo}/tags\",\n \"GET /repos/{owner}/{repo}/teams\",\n \"GET /repos/{owner}/{repo}/topics\",\n \"GET /repositories\",\n \"GET /repositories/{repository_id}/environments/{environment_name}/secrets\",\n \"GET /repositories/{repository_id}/environments/{environment_name}/variables\",\n \"GET /search/code\",\n \"GET /search/commits\",\n \"GET /search/issues\",\n \"GET /search/labels\",\n \"GET /search/repositories\",\n \"GET /search/topics\",\n \"GET /search/users\",\n \"GET /teams/{team_id}/discussions\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/comments\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/reactions\",\n \"GET /teams/{team_id}/invitations\",\n \"GET /teams/{team_id}/members\",\n \"GET /teams/{team_id}/projects\",\n \"GET /teams/{team_id}/repos\",\n \"GET /teams/{team_id}/teams\",\n \"GET /user/blocks\",\n \"GET /user/codespaces\",\n \"GET /user/codespaces/secrets\",\n \"GET /user/emails\",\n \"GET /user/followers\",\n \"GET /user/following\",\n \"GET /user/gpg_keys\",\n \"GET /user/installations\",\n \"GET /user/installations/{installation_id}/repositories\",\n \"GET /user/issues\",\n \"GET /user/keys\",\n \"GET /user/marketplace_purchases\",\n \"GET /user/marketplace_purchases/stubbed\",\n \"GET /user/memberships/orgs\",\n \"GET /user/migrations\",\n \"GET /user/migrations/{migration_id}/repositories\",\n \"GET /user/orgs\",\n \"GET /user/packages\",\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n \"GET /user/public_emails\",\n \"GET /user/repos\",\n \"GET /user/repository_invitations\",\n \"GET /user/social_accounts\",\n \"GET /user/ssh_signing_keys\",\n \"GET /user/starred\",\n \"GET /user/subscriptions\",\n \"GET /user/teams\",\n \"GET /users\",\n \"GET /users/{username}/events\",\n \"GET /users/{username}/events/orgs/{org}\",\n \"GET /users/{username}/events/public\",\n \"GET /users/{username}/followers\",\n \"GET /users/{username}/following\",\n \"GET /users/{username}/gists\",\n \"GET /users/{username}/gpg_keys\",\n \"GET /users/{username}/keys\",\n \"GET /users/{username}/orgs\",\n \"GET /users/{username}/packages\",\n \"GET /users/{username}/projects\",\n \"GET /users/{username}/received_events\",\n \"GET /users/{username}/received_events/public\",\n \"GET /users/{username}/repos\",\n \"GET /users/{username}/social_accounts\",\n \"GET /users/{username}/ssh_signing_keys\",\n \"GET /users/{username}/starred\",\n \"GET /users/{username}/subscriptions\"\n];\n\n// pkg/dist-src/paginating-endpoints.js\nfunction isPaginatingEndpoint(arg) {\n if (typeof arg === \"string\") {\n return paginatingEndpoints.includes(arg);\n } else {\n return false;\n }\n}\n\n// pkg/dist-src/index.js\nfunction paginateRest(octokit) {\n return {\n paginate: Object.assign(paginate.bind(null, octokit), {\n iterator: iterator.bind(null, octokit)\n })\n };\n}\npaginateRest.VERSION = VERSION;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n composePaginateRest,\n isPaginatingEndpoint,\n paginateRest,\n paginatingEndpoints\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n legacyRestEndpointMethods: () => legacyRestEndpointMethods,\n restEndpointMethods: () => restEndpointMethods\n});\nmodule.exports = __toCommonJS(dist_src_exports);\n\n// pkg/dist-src/version.js\nvar VERSION = \"10.4.1\";\n\n// pkg/dist-src/generated/endpoints.js\nvar Endpoints = {\n actions: {\n addCustomLabelsToSelfHostedRunnerForOrg: [\n \"POST /orgs/{org}/actions/runners/{runner_id}/labels\"\n ],\n addCustomLabelsToSelfHostedRunnerForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\"\n ],\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n addSelectedRepoToOrgVariable: [\n \"PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}\"\n ],\n approveWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve\"\n ],\n cancelWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel\"\n ],\n createEnvironmentVariable: [\n \"POST /repositories/{repository_id}/environments/{environment_name}/variables\"\n ],\n createOrUpdateEnvironmentSecret: [\n \"PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"\n ],\n createOrUpdateOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}\"],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}\"\n ],\n createOrgVariable: [\"POST /orgs/{org}/actions/variables\"],\n createRegistrationTokenForOrg: [\n \"POST /orgs/{org}/actions/runners/registration-token\"\n ],\n createRegistrationTokenForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/registration-token\"\n ],\n createRemoveTokenForOrg: [\"POST /orgs/{org}/actions/runners/remove-token\"],\n createRemoveTokenForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/remove-token\"\n ],\n createRepoVariable: [\"POST /repos/{owner}/{repo}/actions/variables\"],\n createWorkflowDispatch: [\n \"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches\"\n ],\n deleteActionsCacheById: [\n \"DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}\"\n ],\n deleteActionsCacheByKey: [\n \"DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}\"\n ],\n deleteArtifact: [\n \"DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"\n ],\n deleteEnvironmentSecret: [\n \"DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"\n ],\n deleteEnvironmentVariable: [\n \"DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}\"\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}\"],\n deleteOrgVariable: [\"DELETE /orgs/{org}/actions/variables/{name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}\"\n ],\n deleteRepoVariable: [\n \"DELETE /repos/{owner}/{repo}/actions/variables/{name}\"\n ],\n deleteSelfHostedRunnerFromOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}\"\n ],\n deleteSelfHostedRunnerFromRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}\"\n ],\n deleteWorkflowRun: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n deleteWorkflowRunLogs: [\n \"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"\n ],\n disableSelectedRepositoryGithubActionsOrganization: [\n \"DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}\"\n ],\n disableWorkflow: [\n \"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable\"\n ],\n downloadArtifact: [\n \"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}\"\n ],\n downloadJobLogsForWorkflowRun: [\n \"GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs\"\n ],\n downloadWorkflowRunAttemptLogs: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs\"\n ],\n downloadWorkflowRunLogs: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"\n ],\n enableSelectedRepositoryGithubActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/repositories/{repository_id}\"\n ],\n enableWorkflow: [\n \"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable\"\n ],\n forceCancelWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel\"\n ],\n generateRunnerJitconfigForOrg: [\n \"POST /orgs/{org}/actions/runners/generate-jitconfig\"\n ],\n generateRunnerJitconfigForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig\"\n ],\n getActionsCacheList: [\"GET /repos/{owner}/{repo}/actions/caches\"],\n getActionsCacheUsage: [\"GET /repos/{owner}/{repo}/actions/cache/usage\"],\n getActionsCacheUsageByRepoForOrg: [\n \"GET /orgs/{org}/actions/cache/usage-by-repository\"\n ],\n getActionsCacheUsageForOrg: [\"GET /orgs/{org}/actions/cache/usage\"],\n getAllowedActionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/selected-actions\"\n ],\n getAllowedActionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/selected-actions\"\n ],\n getArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n getCustomOidcSubClaimForRepo: [\n \"GET /repos/{owner}/{repo}/actions/oidc/customization/sub\"\n ],\n getEnvironmentPublicKey: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key\"\n ],\n getEnvironmentSecret: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"\n ],\n getEnvironmentVariable: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}\"\n ],\n getGithubActionsDefaultWorkflowPermissionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/workflow\"\n ],\n getGithubActionsDefaultWorkflowPermissionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/workflow\"\n ],\n getGithubActionsPermissionsOrganization: [\n \"GET /orgs/{org}/actions/permissions\"\n ],\n getGithubActionsPermissionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions\"\n ],\n getJobForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/actions/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}\"],\n getOrgVariable: [\"GET /orgs/{org}/actions/variables/{name}\"],\n getPendingDeploymentsForRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\"\n ],\n getRepoPermissions: [\n \"GET /repos/{owner}/{repo}/actions/permissions\",\n {},\n { renamed: [\"actions\", \"getGithubActionsPermissionsRepository\"] }\n ],\n getRepoPublicKey: [\"GET /repos/{owner}/{repo}/actions/secrets/public-key\"],\n getRepoSecret: [\"GET /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n getRepoVariable: [\"GET /repos/{owner}/{repo}/actions/variables/{name}\"],\n getReviewsForRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals\"\n ],\n getSelfHostedRunnerForOrg: [\"GET /orgs/{org}/actions/runners/{runner_id}\"],\n getSelfHostedRunnerForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/{runner_id}\"\n ],\n getWorkflow: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}\"],\n getWorkflowAccessToRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/access\"\n ],\n getWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n getWorkflowRunAttempt: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}\"\n ],\n getWorkflowRunUsage: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing\"\n ],\n getWorkflowUsage: [\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing\"\n ],\n listArtifactsForRepo: [\"GET /repos/{owner}/{repo}/actions/artifacts\"],\n listEnvironmentSecrets: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/secrets\"\n ],\n listEnvironmentVariables: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/variables\"\n ],\n listJobsForWorkflowRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\"\n ],\n listJobsForWorkflowRunAttempt: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs\"\n ],\n listLabelsForSelfHostedRunnerForOrg: [\n \"GET /orgs/{org}/actions/runners/{runner_id}/labels\"\n ],\n listLabelsForSelfHostedRunnerForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\"\n ],\n listOrgSecrets: [\"GET /orgs/{org}/actions/secrets\"],\n listOrgVariables: [\"GET /orgs/{org}/actions/variables\"],\n listRepoOrganizationSecrets: [\n \"GET /repos/{owner}/{repo}/actions/organization-secrets\"\n ],\n listRepoOrganizationVariables: [\n \"GET /repos/{owner}/{repo}/actions/organization-variables\"\n ],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/actions/secrets\"],\n listRepoVariables: [\"GET /repos/{owner}/{repo}/actions/variables\"],\n listRepoWorkflows: [\"GET /repos/{owner}/{repo}/actions/workflows\"],\n listRunnerApplicationsForOrg: [\"GET /orgs/{org}/actions/runners/downloads\"],\n listRunnerApplicationsForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/downloads\"\n ],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\"\n ],\n listSelectedReposForOrgVariable: [\n \"GET /orgs/{org}/actions/variables/{name}/repositories\"\n ],\n listSelectedRepositoriesEnabledGithubActionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/repositories\"\n ],\n listSelfHostedRunnersForOrg: [\"GET /orgs/{org}/actions/runners\"],\n listSelfHostedRunnersForRepo: [\"GET /repos/{owner}/{repo}/actions/runners\"],\n listWorkflowRunArtifacts: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\"\n ],\n listWorkflowRuns: [\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\"\n ],\n listWorkflowRunsForRepo: [\"GET /repos/{owner}/{repo}/actions/runs\"],\n reRunJobForWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun\"\n ],\n reRunWorkflow: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun\"],\n reRunWorkflowFailedJobs: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs\"\n ],\n removeAllCustomLabelsFromSelfHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}/labels\"\n ],\n removeAllCustomLabelsFromSelfHostedRunnerForRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\"\n ],\n removeCustomLabelFromSelfHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}\"\n ],\n removeCustomLabelFromSelfHostedRunnerForRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}\"\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n removeSelectedRepoFromOrgVariable: [\n \"DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}\"\n ],\n reviewCustomGatesForRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule\"\n ],\n reviewPendingDeploymentsForRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\"\n ],\n setAllowedActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/selected-actions\"\n ],\n setAllowedActionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/selected-actions\"\n ],\n setCustomLabelsForSelfHostedRunnerForOrg: [\n \"PUT /orgs/{org}/actions/runners/{runner_id}/labels\"\n ],\n setCustomLabelsForSelfHostedRunnerForRepo: [\n \"PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\"\n ],\n setCustomOidcSubClaimForRepo: [\n \"PUT /repos/{owner}/{repo}/actions/oidc/customization/sub\"\n ],\n setGithubActionsDefaultWorkflowPermissionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/workflow\"\n ],\n setGithubActionsDefaultWorkflowPermissionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/workflow\"\n ],\n setGithubActionsPermissionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions\"\n ],\n setGithubActionsPermissionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions\"\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories\"\n ],\n setSelectedReposForOrgVariable: [\n \"PUT /orgs/{org}/actions/variables/{name}/repositories\"\n ],\n setSelectedRepositoriesEnabledGithubActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/repositories\"\n ],\n setWorkflowAccessToRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/access\"\n ],\n updateEnvironmentVariable: [\n \"PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}\"\n ],\n updateOrgVariable: [\"PATCH /orgs/{org}/actions/variables/{name}\"],\n updateRepoVariable: [\n \"PATCH /repos/{owner}/{repo}/actions/variables/{name}\"\n ]\n },\n activity: {\n checkRepoIsStarredByAuthenticatedUser: [\"GET /user/starred/{owner}/{repo}\"],\n deleteRepoSubscription: [\"DELETE /repos/{owner}/{repo}/subscription\"],\n deleteThreadSubscription: [\n \"DELETE /notifications/threads/{thread_id}/subscription\"\n ],\n getFeeds: [\"GET /feeds\"],\n getRepoSubscription: [\"GET /repos/{owner}/{repo}/subscription\"],\n getThread: [\"GET /notifications/threads/{thread_id}\"],\n getThreadSubscriptionForAuthenticatedUser: [\n \"GET /notifications/threads/{thread_id}/subscription\"\n ],\n listEventsForAuthenticatedUser: [\"GET /users/{username}/events\"],\n listNotificationsForAuthenticatedUser: [\"GET /notifications\"],\n listOrgEventsForAuthenticatedUser: [\n \"GET /users/{username}/events/orgs/{org}\"\n ],\n listPublicEvents: [\"GET /events\"],\n listPublicEventsForRepoNetwork: [\"GET /networks/{owner}/{repo}/events\"],\n listPublicEventsForUser: [\"GET /users/{username}/events/public\"],\n listPublicOrgEvents: [\"GET /orgs/{org}/events\"],\n listReceivedEventsForUser: [\"GET /users/{username}/received_events\"],\n listReceivedPublicEventsForUser: [\n \"GET /users/{username}/received_events/public\"\n ],\n listRepoEvents: [\"GET /repos/{owner}/{repo}/events\"],\n listRepoNotificationsForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/notifications\"\n ],\n listReposStarredByAuthenticatedUser: [\"GET /user/starred\"],\n listReposStarredByUser: [\"GET /users/{username}/starred\"],\n listReposWatchedByUser: [\"GET /users/{username}/subscriptions\"],\n listStargazersForRepo: [\"GET /repos/{owner}/{repo}/stargazers\"],\n listWatchedReposForAuthenticatedUser: [\"GET /user/subscriptions\"],\n listWatchersForRepo: [\"GET /repos/{owner}/{repo}/subscribers\"],\n markNotificationsAsRead: [\"PUT /notifications\"],\n markRepoNotificationsAsRead: [\"PUT /repos/{owner}/{repo}/notifications\"],\n markThreadAsDone: [\"DELETE /notifications/threads/{thread_id}\"],\n markThreadAsRead: [\"PATCH /notifications/threads/{thread_id}\"],\n setRepoSubscription: [\"PUT /repos/{owner}/{repo}/subscription\"],\n setThreadSubscription: [\n \"PUT /notifications/threads/{thread_id}/subscription\"\n ],\n starRepoForAuthenticatedUser: [\"PUT /user/starred/{owner}/{repo}\"],\n unstarRepoForAuthenticatedUser: [\"DELETE /user/starred/{owner}/{repo}\"]\n },\n apps: {\n addRepoToInstallation: [\n \"PUT /user/installations/{installation_id}/repositories/{repository_id}\",\n {},\n { renamed: [\"apps\", \"addRepoToInstallationForAuthenticatedUser\"] }\n ],\n addRepoToInstallationForAuthenticatedUser: [\n \"PUT /user/installations/{installation_id}/repositories/{repository_id}\"\n ],\n checkToken: [\"POST /applications/{client_id}/token\"],\n createFromManifest: [\"POST /app-manifests/{code}/conversions\"],\n createInstallationAccessToken: [\n \"POST /app/installations/{installation_id}/access_tokens\"\n ],\n deleteAuthorization: [\"DELETE /applications/{client_id}/grant\"],\n deleteInstallation: [\"DELETE /app/installations/{installation_id}\"],\n deleteToken: [\"DELETE /applications/{client_id}/token\"],\n getAuthenticated: [\"GET /app\"],\n getBySlug: [\"GET /apps/{app_slug}\"],\n getInstallation: [\"GET /app/installations/{installation_id}\"],\n getOrgInstallation: [\"GET /orgs/{org}/installation\"],\n getRepoInstallation: [\"GET /repos/{owner}/{repo}/installation\"],\n getSubscriptionPlanForAccount: [\n \"GET /marketplace_listing/accounts/{account_id}\"\n ],\n getSubscriptionPlanForAccountStubbed: [\n \"GET /marketplace_listing/stubbed/accounts/{account_id}\"\n ],\n getUserInstallation: [\"GET /users/{username}/installation\"],\n getWebhookConfigForApp: [\"GET /app/hook/config\"],\n getWebhookDelivery: [\"GET /app/hook/deliveries/{delivery_id}\"],\n listAccountsForPlan: [\"GET /marketplace_listing/plans/{plan_id}/accounts\"],\n listAccountsForPlanStubbed: [\n \"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\"\n ],\n listInstallationReposForAuthenticatedUser: [\n \"GET /user/installations/{installation_id}/repositories\"\n ],\n listInstallationRequestsForAuthenticatedApp: [\n \"GET /app/installation-requests\"\n ],\n listInstallations: [\"GET /app/installations\"],\n listInstallationsForAuthenticatedUser: [\"GET /user/installations\"],\n listPlans: [\"GET /marketplace_listing/plans\"],\n listPlansStubbed: [\"GET /marketplace_listing/stubbed/plans\"],\n listReposAccessibleToInstallation: [\"GET /installation/repositories\"],\n listSubscriptionsForAuthenticatedUser: [\"GET /user/marketplace_purchases\"],\n listSubscriptionsForAuthenticatedUserStubbed: [\n \"GET /user/marketplace_purchases/stubbed\"\n ],\n listWebhookDeliveries: [\"GET /app/hook/deliveries\"],\n redeliverWebhookDelivery: [\n \"POST /app/hook/deliveries/{delivery_id}/attempts\"\n ],\n removeRepoFromInstallation: [\n \"DELETE /user/installations/{installation_id}/repositories/{repository_id}\",\n {},\n { renamed: [\"apps\", \"removeRepoFromInstallationForAuthenticatedUser\"] }\n ],\n removeRepoFromInstallationForAuthenticatedUser: [\n \"DELETE /user/installations/{installation_id}/repositories/{repository_id}\"\n ],\n resetToken: [\"PATCH /applications/{client_id}/token\"],\n revokeInstallationAccessToken: [\"DELETE /installation/token\"],\n scopeToken: [\"POST /applications/{client_id}/token/scoped\"],\n suspendInstallation: [\"PUT /app/installations/{installation_id}/suspended\"],\n unsuspendInstallation: [\n \"DELETE /app/installations/{installation_id}/suspended\"\n ],\n updateWebhookConfigForApp: [\"PATCH /app/hook/config\"]\n },\n billing: {\n getGithubActionsBillingOrg: [\"GET /orgs/{org}/settings/billing/actions\"],\n getGithubActionsBillingUser: [\n \"GET /users/{username}/settings/billing/actions\"\n ],\n getGithubPackagesBillingOrg: [\"GET /orgs/{org}/settings/billing/packages\"],\n getGithubPackagesBillingUser: [\n \"GET /users/{username}/settings/billing/packages\"\n ],\n getSharedStorageBillingOrg: [\n \"GET /orgs/{org}/settings/billing/shared-storage\"\n ],\n getSharedStorageBillingUser: [\n \"GET /users/{username}/settings/billing/shared-storage\"\n ]\n },\n checks: {\n create: [\"POST /repos/{owner}/{repo}/check-runs\"],\n createSuite: [\"POST /repos/{owner}/{repo}/check-suites\"],\n get: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}\"],\n getSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}\"],\n listAnnotations: [\n \"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\"\n ],\n listForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\"],\n listForSuite: [\n \"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\"\n ],\n listSuitesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\"],\n rerequestRun: [\n \"POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest\"\n ],\n rerequestSuite: [\n \"POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest\"\n ],\n setSuitesPreferences: [\n \"PATCH /repos/{owner}/{repo}/check-suites/preferences\"\n ],\n update: [\"PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}\"]\n },\n codeScanning: {\n deleteAnalysis: [\n \"DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}\"\n ],\n getAlert: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\",\n {},\n { renamedParameters: { alert_id: \"alert_number\" } }\n ],\n getAnalysis: [\n \"GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}\"\n ],\n getCodeqlDatabase: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}\"\n ],\n getDefaultSetup: [\"GET /repos/{owner}/{repo}/code-scanning/default-setup\"],\n getSarif: [\"GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}\"],\n listAlertInstances: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\"\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/code-scanning/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/code-scanning/alerts\"],\n listAlertsInstances: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n {},\n { renamed: [\"codeScanning\", \"listAlertInstances\"] }\n ],\n listCodeqlDatabases: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/databases\"\n ],\n listRecentAnalyses: [\"GET /repos/{owner}/{repo}/code-scanning/analyses\"],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\"\n ],\n updateDefaultSetup: [\n \"PATCH /repos/{owner}/{repo}/code-scanning/default-setup\"\n ],\n uploadSarif: [\"POST /repos/{owner}/{repo}/code-scanning/sarifs\"]\n },\n codesOfConduct: {\n getAllCodesOfConduct: [\"GET /codes_of_conduct\"],\n getConductCode: [\"GET /codes_of_conduct/{key}\"]\n },\n codespaces: {\n addRepositoryForSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n checkPermissionsForDevcontainer: [\n \"GET /repos/{owner}/{repo}/codespaces/permissions_check\"\n ],\n codespaceMachinesForAuthenticatedUser: [\n \"GET /user/codespaces/{codespace_name}/machines\"\n ],\n createForAuthenticatedUser: [\"POST /user/codespaces\"],\n createOrUpdateOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}\"\n ],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\"\n ],\n createOrUpdateSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}\"\n ],\n createWithPrForAuthenticatedUser: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces\"\n ],\n createWithRepoForAuthenticatedUser: [\n \"POST /repos/{owner}/{repo}/codespaces\"\n ],\n deleteForAuthenticatedUser: [\"DELETE /user/codespaces/{codespace_name}\"],\n deleteFromOrganization: [\n \"DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}\"\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/codespaces/secrets/{secret_name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\"\n ],\n deleteSecretForAuthenticatedUser: [\n \"DELETE /user/codespaces/secrets/{secret_name}\"\n ],\n exportForAuthenticatedUser: [\n \"POST /user/codespaces/{codespace_name}/exports\"\n ],\n getCodespacesForUserInOrg: [\n \"GET /orgs/{org}/members/{username}/codespaces\"\n ],\n getExportDetailsForAuthenticatedUser: [\n \"GET /user/codespaces/{codespace_name}/exports/{export_id}\"\n ],\n getForAuthenticatedUser: [\"GET /user/codespaces/{codespace_name}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/codespaces/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/codespaces/secrets/{secret_name}\"],\n getPublicKeyForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/public-key\"\n ],\n getRepoPublicKey: [\n \"GET /repos/{owner}/{repo}/codespaces/secrets/public-key\"\n ],\n getRepoSecret: [\n \"GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\"\n ],\n getSecretForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/{secret_name}\"\n ],\n listDevcontainersInRepositoryForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/devcontainers\"\n ],\n listForAuthenticatedUser: [\"GET /user/codespaces\"],\n listInOrganization: [\n \"GET /orgs/{org}/codespaces\",\n {},\n { renamedParameters: { org_id: \"org\" } }\n ],\n listInRepositoryForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces\"\n ],\n listOrgSecrets: [\"GET /orgs/{org}/codespaces/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/codespaces/secrets\"],\n listRepositoriesForSecretForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/{secret_name}/repositories\"\n ],\n listSecretsForAuthenticatedUser: [\"GET /user/codespaces/secrets\"],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories\"\n ],\n preFlightWithRepoForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/new\"\n ],\n publishForAuthenticatedUser: [\n \"POST /user/codespaces/{codespace_name}/publish\"\n ],\n removeRepositoryForSecretForAuthenticatedUser: [\n \"DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n repoMachinesForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/machines\"\n ],\n setRepositoriesForSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}/repositories\"\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories\"\n ],\n startForAuthenticatedUser: [\"POST /user/codespaces/{codespace_name}/start\"],\n stopForAuthenticatedUser: [\"POST /user/codespaces/{codespace_name}/stop\"],\n stopInOrganization: [\n \"POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop\"\n ],\n updateForAuthenticatedUser: [\"PATCH /user/codespaces/{codespace_name}\"]\n },\n copilot: {\n addCopilotSeatsForTeams: [\n \"POST /orgs/{org}/copilot/billing/selected_teams\"\n ],\n addCopilotSeatsForUsers: [\n \"POST /orgs/{org}/copilot/billing/selected_users\"\n ],\n cancelCopilotSeatAssignmentForTeams: [\n \"DELETE /orgs/{org}/copilot/billing/selected_teams\"\n ],\n cancelCopilotSeatAssignmentForUsers: [\n \"DELETE /orgs/{org}/copilot/billing/selected_users\"\n ],\n getCopilotOrganizationDetails: [\"GET /orgs/{org}/copilot/billing\"],\n getCopilotSeatDetailsForUser: [\n \"GET /orgs/{org}/members/{username}/copilot\"\n ],\n listCopilotSeats: [\"GET /orgs/{org}/copilot/billing/seats\"]\n },\n dependabot: {\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n createOrUpdateOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}\"\n ],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\"\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/dependabot/secrets/{secret_name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\"\n ],\n getAlert: [\"GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/dependabot/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/dependabot/secrets/{secret_name}\"],\n getRepoPublicKey: [\n \"GET /repos/{owner}/{repo}/dependabot/secrets/public-key\"\n ],\n getRepoSecret: [\n \"GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\"\n ],\n listAlertsForEnterprise: [\n \"GET /enterprises/{enterprise}/dependabot/alerts\"\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/dependabot/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/dependabot/alerts\"],\n listOrgSecrets: [\"GET /orgs/{org}/dependabot/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/dependabot/secrets\"],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories\"\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories\"\n ],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}\"\n ]\n },\n dependencyGraph: {\n createRepositorySnapshot: [\n \"POST /repos/{owner}/{repo}/dependency-graph/snapshots\"\n ],\n diffRange: [\n \"GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}\"\n ],\n exportSbom: [\"GET /repos/{owner}/{repo}/dependency-graph/sbom\"]\n },\n emojis: { get: [\"GET /emojis\"] },\n gists: {\n checkIsStarred: [\"GET /gists/{gist_id}/star\"],\n create: [\"POST /gists\"],\n createComment: [\"POST /gists/{gist_id}/comments\"],\n delete: [\"DELETE /gists/{gist_id}\"],\n deleteComment: [\"DELETE /gists/{gist_id}/comments/{comment_id}\"],\n fork: [\"POST /gists/{gist_id}/forks\"],\n get: [\"GET /gists/{gist_id}\"],\n getComment: [\"GET /gists/{gist_id}/comments/{comment_id}\"],\n getRevision: [\"GET /gists/{gist_id}/{sha}\"],\n list: [\"GET /gists\"],\n listComments: [\"GET /gists/{gist_id}/comments\"],\n listCommits: [\"GET /gists/{gist_id}/commits\"],\n listForUser: [\"GET /users/{username}/gists\"],\n listForks: [\"GET /gists/{gist_id}/forks\"],\n listPublic: [\"GET /gists/public\"],\n listStarred: [\"GET /gists/starred\"],\n star: [\"PUT /gists/{gist_id}/star\"],\n unstar: [\"DELETE /gists/{gist_id}/star\"],\n update: [\"PATCH /gists/{gist_id}\"],\n updateComment: [\"PATCH /gists/{gist_id}/comments/{comment_id}\"]\n },\n git: {\n createBlob: [\"POST /repos/{owner}/{repo}/git/blobs\"],\n createCommit: [\"POST /repos/{owner}/{repo}/git/commits\"],\n createRef: [\"POST /repos/{owner}/{repo}/git/refs\"],\n createTag: [\"POST /repos/{owner}/{repo}/git/tags\"],\n createTree: [\"POST /repos/{owner}/{repo}/git/trees\"],\n deleteRef: [\"DELETE /repos/{owner}/{repo}/git/refs/{ref}\"],\n getBlob: [\"GET /repos/{owner}/{repo}/git/blobs/{file_sha}\"],\n getCommit: [\"GET /repos/{owner}/{repo}/git/commits/{commit_sha}\"],\n getRef: [\"GET /repos/{owner}/{repo}/git/ref/{ref}\"],\n getTag: [\"GET /repos/{owner}/{repo}/git/tags/{tag_sha}\"],\n getTree: [\"GET /repos/{owner}/{repo}/git/trees/{tree_sha}\"],\n listMatchingRefs: [\"GET /repos/{owner}/{repo}/git/matching-refs/{ref}\"],\n updateRef: [\"PATCH /repos/{owner}/{repo}/git/refs/{ref}\"]\n },\n gitignore: {\n getAllTemplates: [\"GET /gitignore/templates\"],\n getTemplate: [\"GET /gitignore/templates/{name}\"]\n },\n interactions: {\n getRestrictionsForAuthenticatedUser: [\"GET /user/interaction-limits\"],\n getRestrictionsForOrg: [\"GET /orgs/{org}/interaction-limits\"],\n getRestrictionsForRepo: [\"GET /repos/{owner}/{repo}/interaction-limits\"],\n getRestrictionsForYourPublicRepos: [\n \"GET /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"getRestrictionsForAuthenticatedUser\"] }\n ],\n removeRestrictionsForAuthenticatedUser: [\"DELETE /user/interaction-limits\"],\n removeRestrictionsForOrg: [\"DELETE /orgs/{org}/interaction-limits\"],\n removeRestrictionsForRepo: [\n \"DELETE /repos/{owner}/{repo}/interaction-limits\"\n ],\n removeRestrictionsForYourPublicRepos: [\n \"DELETE /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"removeRestrictionsForAuthenticatedUser\"] }\n ],\n setRestrictionsForAuthenticatedUser: [\"PUT /user/interaction-limits\"],\n setRestrictionsForOrg: [\"PUT /orgs/{org}/interaction-limits\"],\n setRestrictionsForRepo: [\"PUT /repos/{owner}/{repo}/interaction-limits\"],\n setRestrictionsForYourPublicRepos: [\n \"PUT /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"setRestrictionsForAuthenticatedUser\"] }\n ]\n },\n issues: {\n addAssignees: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/assignees\"\n ],\n addLabels: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n checkUserCanBeAssigned: [\"GET /repos/{owner}/{repo}/assignees/{assignee}\"],\n checkUserCanBeAssignedToIssue: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}\"\n ],\n create: [\"POST /repos/{owner}/{repo}/issues\"],\n createComment: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/comments\"\n ],\n createLabel: [\"POST /repos/{owner}/{repo}/labels\"],\n createMilestone: [\"POST /repos/{owner}/{repo}/milestones\"],\n deleteComment: [\n \"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}\"\n ],\n deleteLabel: [\"DELETE /repos/{owner}/{repo}/labels/{name}\"],\n deleteMilestone: [\n \"DELETE /repos/{owner}/{repo}/milestones/{milestone_number}\"\n ],\n get: [\"GET /repos/{owner}/{repo}/issues/{issue_number}\"],\n getComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n getEvent: [\"GET /repos/{owner}/{repo}/issues/events/{event_id}\"],\n getLabel: [\"GET /repos/{owner}/{repo}/labels/{name}\"],\n getMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n list: [\"GET /issues\"],\n listAssignees: [\"GET /repos/{owner}/{repo}/assignees\"],\n listComments: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n listCommentsForRepo: [\"GET /repos/{owner}/{repo}/issues/comments\"],\n listEvents: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/events\"],\n listEventsForRepo: [\"GET /repos/{owner}/{repo}/issues/events\"],\n listEventsForTimeline: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\"\n ],\n listForAuthenticatedUser: [\"GET /user/issues\"],\n listForOrg: [\"GET /orgs/{org}/issues\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/issues\"],\n listLabelsForMilestone: [\n \"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\"\n ],\n listLabelsForRepo: [\"GET /repos/{owner}/{repo}/labels\"],\n listLabelsOnIssue: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\"\n ],\n listMilestones: [\"GET /repos/{owner}/{repo}/milestones\"],\n lock: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n removeAllLabels: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels\"\n ],\n removeAssignees: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees\"\n ],\n removeLabel: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}\"\n ],\n setLabels: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n unlock: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n update: [\"PATCH /repos/{owner}/{repo}/issues/{issue_number}\"],\n updateComment: [\"PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n updateLabel: [\"PATCH /repos/{owner}/{repo}/labels/{name}\"],\n updateMilestone: [\n \"PATCH /repos/{owner}/{repo}/milestones/{milestone_number}\"\n ]\n },\n licenses: {\n get: [\"GET /licenses/{license}\"],\n getAllCommonlyUsed: [\"GET /licenses\"],\n getForRepo: [\"GET /repos/{owner}/{repo}/license\"]\n },\n markdown: {\n render: [\"POST /markdown\"],\n renderRaw: [\n \"POST /markdown/raw\",\n { headers: { \"content-type\": \"text/plain; charset=utf-8\" } }\n ]\n },\n meta: {\n get: [\"GET /meta\"],\n getAllVersions: [\"GET /versions\"],\n getOctocat: [\"GET /octocat\"],\n getZen: [\"GET /zen\"],\n root: [\"GET /\"]\n },\n migrations: {\n cancelImport: [\n \"DELETE /repos/{owner}/{repo}/import\",\n {},\n {\n deprecated: \"octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import\"\n }\n ],\n deleteArchiveForAuthenticatedUser: [\n \"DELETE /user/migrations/{migration_id}/archive\"\n ],\n deleteArchiveForOrg: [\n \"DELETE /orgs/{org}/migrations/{migration_id}/archive\"\n ],\n downloadArchiveForOrg: [\n \"GET /orgs/{org}/migrations/{migration_id}/archive\"\n ],\n getArchiveForAuthenticatedUser: [\n \"GET /user/migrations/{migration_id}/archive\"\n ],\n getCommitAuthors: [\n \"GET /repos/{owner}/{repo}/import/authors\",\n {},\n {\n deprecated: \"octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors\"\n }\n ],\n getImportStatus: [\n \"GET /repos/{owner}/{repo}/import\",\n {},\n {\n deprecated: \"octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status\"\n }\n ],\n getLargeFiles: [\n \"GET /repos/{owner}/{repo}/import/large_files\",\n {},\n {\n deprecated: \"octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files\"\n }\n ],\n getStatusForAuthenticatedUser: [\"GET /user/migrations/{migration_id}\"],\n getStatusForOrg: [\"GET /orgs/{org}/migrations/{migration_id}\"],\n listForAuthenticatedUser: [\"GET /user/migrations\"],\n listForOrg: [\"GET /orgs/{org}/migrations\"],\n listReposForAuthenticatedUser: [\n \"GET /user/migrations/{migration_id}/repositories\"\n ],\n listReposForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/repositories\"],\n listReposForUser: [\n \"GET /user/migrations/{migration_id}/repositories\",\n {},\n { renamed: [\"migrations\", \"listReposForAuthenticatedUser\"] }\n ],\n mapCommitAuthor: [\n \"PATCH /repos/{owner}/{repo}/import/authors/{author_id}\",\n {},\n {\n deprecated: \"octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author\"\n }\n ],\n setLfsPreference: [\n \"PATCH /repos/{owner}/{repo}/import/lfs\",\n {},\n {\n deprecated: \"octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference\"\n }\n ],\n startForAuthenticatedUser: [\"POST /user/migrations\"],\n startForOrg: [\"POST /orgs/{org}/migrations\"],\n startImport: [\n \"PUT /repos/{owner}/{repo}/import\",\n {},\n {\n deprecated: \"octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import\"\n }\n ],\n unlockRepoForAuthenticatedUser: [\n \"DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock\"\n ],\n unlockRepoForOrg: [\n \"DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock\"\n ],\n updateImport: [\n \"PATCH /repos/{owner}/{repo}/import\",\n {},\n {\n deprecated: \"octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import\"\n }\n ]\n },\n oidc: {\n getOidcCustomSubTemplateForOrg: [\n \"GET /orgs/{org}/actions/oidc/customization/sub\"\n ],\n updateOidcCustomSubTemplateForOrg: [\n \"PUT /orgs/{org}/actions/oidc/customization/sub\"\n ]\n },\n orgs: {\n addSecurityManagerTeam: [\n \"PUT /orgs/{org}/security-managers/teams/{team_slug}\"\n ],\n assignTeamToOrgRole: [\n \"PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}\"\n ],\n assignUserToOrgRole: [\n \"PUT /orgs/{org}/organization-roles/users/{username}/{role_id}\"\n ],\n blockUser: [\"PUT /orgs/{org}/blocks/{username}\"],\n cancelInvitation: [\"DELETE /orgs/{org}/invitations/{invitation_id}\"],\n checkBlockedUser: [\"GET /orgs/{org}/blocks/{username}\"],\n checkMembershipForUser: [\"GET /orgs/{org}/members/{username}\"],\n checkPublicMembershipForUser: [\"GET /orgs/{org}/public_members/{username}\"],\n convertMemberToOutsideCollaborator: [\n \"PUT /orgs/{org}/outside_collaborators/{username}\"\n ],\n createCustomOrganizationRole: [\"POST /orgs/{org}/organization-roles\"],\n createInvitation: [\"POST /orgs/{org}/invitations\"],\n createOrUpdateCustomProperties: [\"PATCH /orgs/{org}/properties/schema\"],\n createOrUpdateCustomPropertiesValuesForRepos: [\n \"PATCH /orgs/{org}/properties/values\"\n ],\n createOrUpdateCustomProperty: [\n \"PUT /orgs/{org}/properties/schema/{custom_property_name}\"\n ],\n createWebhook: [\"POST /orgs/{org}/hooks\"],\n delete: [\"DELETE /orgs/{org}\"],\n deleteCustomOrganizationRole: [\n \"DELETE /orgs/{org}/organization-roles/{role_id}\"\n ],\n deleteWebhook: [\"DELETE /orgs/{org}/hooks/{hook_id}\"],\n enableOrDisableSecurityProductOnAllOrgRepos: [\n \"POST /orgs/{org}/{security_product}/{enablement}\"\n ],\n get: [\"GET /orgs/{org}\"],\n getAllCustomProperties: [\"GET /orgs/{org}/properties/schema\"],\n getCustomProperty: [\n \"GET /orgs/{org}/properties/schema/{custom_property_name}\"\n ],\n getMembershipForAuthenticatedUser: [\"GET /user/memberships/orgs/{org}\"],\n getMembershipForUser: [\"GET /orgs/{org}/memberships/{username}\"],\n getOrgRole: [\"GET /orgs/{org}/organization-roles/{role_id}\"],\n getWebhook: [\"GET /orgs/{org}/hooks/{hook_id}\"],\n getWebhookConfigForOrg: [\"GET /orgs/{org}/hooks/{hook_id}/config\"],\n getWebhookDelivery: [\n \"GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}\"\n ],\n list: [\"GET /organizations\"],\n listAppInstallations: [\"GET /orgs/{org}/installations\"],\n listBlockedUsers: [\"GET /orgs/{org}/blocks\"],\n listCustomPropertiesValuesForRepos: [\"GET /orgs/{org}/properties/values\"],\n listFailedInvitations: [\"GET /orgs/{org}/failed_invitations\"],\n listForAuthenticatedUser: [\"GET /user/orgs\"],\n listForUser: [\"GET /users/{username}/orgs\"],\n listInvitationTeams: [\"GET /orgs/{org}/invitations/{invitation_id}/teams\"],\n listMembers: [\"GET /orgs/{org}/members\"],\n listMembershipsForAuthenticatedUser: [\"GET /user/memberships/orgs\"],\n listOrgRoleTeams: [\"GET /orgs/{org}/organization-roles/{role_id}/teams\"],\n listOrgRoleUsers: [\"GET /orgs/{org}/organization-roles/{role_id}/users\"],\n listOrgRoles: [\"GET /orgs/{org}/organization-roles\"],\n listOrganizationFineGrainedPermissions: [\n \"GET /orgs/{org}/organization-fine-grained-permissions\"\n ],\n listOutsideCollaborators: [\"GET /orgs/{org}/outside_collaborators\"],\n listPatGrantRepositories: [\n \"GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories\"\n ],\n listPatGrantRequestRepositories: [\n \"GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories\"\n ],\n listPatGrantRequests: [\"GET /orgs/{org}/personal-access-token-requests\"],\n listPatGrants: [\"GET /orgs/{org}/personal-access-tokens\"],\n listPendingInvitations: [\"GET /orgs/{org}/invitations\"],\n listPublicMembers: [\"GET /orgs/{org}/public_members\"],\n listSecurityManagerTeams: [\"GET /orgs/{org}/security-managers\"],\n listWebhookDeliveries: [\"GET /orgs/{org}/hooks/{hook_id}/deliveries\"],\n listWebhooks: [\"GET /orgs/{org}/hooks\"],\n patchCustomOrganizationRole: [\n \"PATCH /orgs/{org}/organization-roles/{role_id}\"\n ],\n pingWebhook: [\"POST /orgs/{org}/hooks/{hook_id}/pings\"],\n redeliverWebhookDelivery: [\n \"POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts\"\n ],\n removeCustomProperty: [\n \"DELETE /orgs/{org}/properties/schema/{custom_property_name}\"\n ],\n removeMember: [\"DELETE /orgs/{org}/members/{username}\"],\n removeMembershipForUser: [\"DELETE /orgs/{org}/memberships/{username}\"],\n removeOutsideCollaborator: [\n \"DELETE /orgs/{org}/outside_collaborators/{username}\"\n ],\n removePublicMembershipForAuthenticatedUser: [\n \"DELETE /orgs/{org}/public_members/{username}\"\n ],\n removeSecurityManagerTeam: [\n \"DELETE /orgs/{org}/security-managers/teams/{team_slug}\"\n ],\n reviewPatGrantRequest: [\n \"POST /orgs/{org}/personal-access-token-requests/{pat_request_id}\"\n ],\n reviewPatGrantRequestsInBulk: [\n \"POST /orgs/{org}/personal-access-token-requests\"\n ],\n revokeAllOrgRolesTeam: [\n \"DELETE /orgs/{org}/organization-roles/teams/{team_slug}\"\n ],\n revokeAllOrgRolesUser: [\n \"DELETE /orgs/{org}/organization-roles/users/{username}\"\n ],\n revokeOrgRoleTeam: [\n \"DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}\"\n ],\n revokeOrgRoleUser: [\n \"DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}\"\n ],\n setMembershipForUser: [\"PUT /orgs/{org}/memberships/{username}\"],\n setPublicMembershipForAuthenticatedUser: [\n \"PUT /orgs/{org}/public_members/{username}\"\n ],\n unblockUser: [\"DELETE /orgs/{org}/blocks/{username}\"],\n update: [\"PATCH /orgs/{org}\"],\n updateMembershipForAuthenticatedUser: [\n \"PATCH /user/memberships/orgs/{org}\"\n ],\n updatePatAccess: [\"POST /orgs/{org}/personal-access-tokens/{pat_id}\"],\n updatePatAccesses: [\"POST /orgs/{org}/personal-access-tokens\"],\n updateWebhook: [\"PATCH /orgs/{org}/hooks/{hook_id}\"],\n updateWebhookConfigForOrg: [\"PATCH /orgs/{org}/hooks/{hook_id}/config\"]\n },\n packages: {\n deletePackageForAuthenticatedUser: [\n \"DELETE /user/packages/{package_type}/{package_name}\"\n ],\n deletePackageForOrg: [\n \"DELETE /orgs/{org}/packages/{package_type}/{package_name}\"\n ],\n deletePackageForUser: [\n \"DELETE /users/{username}/packages/{package_type}/{package_name}\"\n ],\n deletePackageVersionForAuthenticatedUser: [\n \"DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n deletePackageVersionForOrg: [\n \"DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n deletePackageVersionForUser: [\n \"DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n getAllPackageVersionsForAPackageOwnedByAnOrg: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n {},\n { renamed: [\"packages\", \"getAllPackageVersionsForPackageOwnedByOrg\"] }\n ],\n getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n {},\n {\n renamed: [\n \"packages\",\n \"getAllPackageVersionsForPackageOwnedByAuthenticatedUser\"\n ]\n }\n ],\n getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions\"\n ],\n getAllPackageVersionsForPackageOwnedByOrg: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\"\n ],\n getAllPackageVersionsForPackageOwnedByUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}/versions\"\n ],\n getPackageForAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}\"\n ],\n getPackageForOrganization: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}\"\n ],\n getPackageForUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}\"\n ],\n getPackageVersionForAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n getPackageVersionForOrganization: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n getPackageVersionForUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n listDockerMigrationConflictingPackagesForAuthenticatedUser: [\n \"GET /user/docker/conflicts\"\n ],\n listDockerMigrationConflictingPackagesForOrganization: [\n \"GET /orgs/{org}/docker/conflicts\"\n ],\n listDockerMigrationConflictingPackagesForUser: [\n \"GET /users/{username}/docker/conflicts\"\n ],\n listPackagesForAuthenticatedUser: [\"GET /user/packages\"],\n listPackagesForOrganization: [\"GET /orgs/{org}/packages\"],\n listPackagesForUser: [\"GET /users/{username}/packages\"],\n restorePackageForAuthenticatedUser: [\n \"POST /user/packages/{package_type}/{package_name}/restore{?token}\"\n ],\n restorePackageForOrg: [\n \"POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}\"\n ],\n restorePackageForUser: [\n \"POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}\"\n ],\n restorePackageVersionForAuthenticatedUser: [\n \"POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\"\n ],\n restorePackageVersionForOrg: [\n \"POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\"\n ],\n restorePackageVersionForUser: [\n \"POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\"\n ]\n },\n projects: {\n addCollaborator: [\"PUT /projects/{project_id}/collaborators/{username}\"],\n createCard: [\"POST /projects/columns/{column_id}/cards\"],\n createColumn: [\"POST /projects/{project_id}/columns\"],\n createForAuthenticatedUser: [\"POST /user/projects\"],\n createForOrg: [\"POST /orgs/{org}/projects\"],\n createForRepo: [\"POST /repos/{owner}/{repo}/projects\"],\n delete: [\"DELETE /projects/{project_id}\"],\n deleteCard: [\"DELETE /projects/columns/cards/{card_id}\"],\n deleteColumn: [\"DELETE /projects/columns/{column_id}\"],\n get: [\"GET /projects/{project_id}\"],\n getCard: [\"GET /projects/columns/cards/{card_id}\"],\n getColumn: [\"GET /projects/columns/{column_id}\"],\n getPermissionForUser: [\n \"GET /projects/{project_id}/collaborators/{username}/permission\"\n ],\n listCards: [\"GET /projects/columns/{column_id}/cards\"],\n listCollaborators: [\"GET /projects/{project_id}/collaborators\"],\n listColumns: [\"GET /projects/{project_id}/columns\"],\n listForOrg: [\"GET /orgs/{org}/projects\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/projects\"],\n listForUser: [\"GET /users/{username}/projects\"],\n moveCard: [\"POST /projects/columns/cards/{card_id}/moves\"],\n moveColumn: [\"POST /projects/columns/{column_id}/moves\"],\n removeCollaborator: [\n \"DELETE /projects/{project_id}/collaborators/{username}\"\n ],\n update: [\"PATCH /projects/{project_id}\"],\n updateCard: [\"PATCH /projects/columns/cards/{card_id}\"],\n updateColumn: [\"PATCH /projects/columns/{column_id}\"]\n },\n pulls: {\n checkIfMerged: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n create: [\"POST /repos/{owner}/{repo}/pulls\"],\n createReplyForReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies\"\n ],\n createReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n createReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments\"\n ],\n deletePendingReview: [\n \"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"\n ],\n deleteReviewComment: [\n \"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}\"\n ],\n dismissReview: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals\"\n ],\n get: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}\"],\n getReview: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"\n ],\n getReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n list: [\"GET /repos/{owner}/{repo}/pulls\"],\n listCommentsForReview: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\"\n ],\n listCommits: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\"],\n listFiles: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\"],\n listRequestedReviewers: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"\n ],\n listReviewComments: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\"\n ],\n listReviewCommentsForRepo: [\"GET /repos/{owner}/{repo}/pulls/comments\"],\n listReviews: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n merge: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n removeRequestedReviewers: [\n \"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"\n ],\n requestReviewers: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"\n ],\n submitReview: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events\"\n ],\n update: [\"PATCH /repos/{owner}/{repo}/pulls/{pull_number}\"],\n updateBranch: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch\"\n ],\n updateReview: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"\n ],\n updateReviewComment: [\n \"PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}\"\n ]\n },\n rateLimit: { get: [\"GET /rate_limit\"] },\n reactions: {\n createForCommitComment: [\n \"POST /repos/{owner}/{repo}/comments/{comment_id}/reactions\"\n ],\n createForIssue: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/reactions\"\n ],\n createForIssueComment: [\n \"POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\"\n ],\n createForPullRequestReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\"\n ],\n createForRelease: [\n \"POST /repos/{owner}/{repo}/releases/{release_id}/reactions\"\n ],\n createForTeamDiscussionCommentInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\"\n ],\n createForTeamDiscussionInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\"\n ],\n deleteForCommitComment: [\n \"DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}\"\n ],\n deleteForIssue: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}\"\n ],\n deleteForIssueComment: [\n \"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}\"\n ],\n deleteForPullRequestComment: [\n \"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}\"\n ],\n deleteForRelease: [\n \"DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}\"\n ],\n deleteForTeamDiscussion: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}\"\n ],\n deleteForTeamDiscussionComment: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}\"\n ],\n listForCommitComment: [\n \"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\"\n ],\n listForIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\"],\n listForIssueComment: [\n \"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\"\n ],\n listForPullRequestReviewComment: [\n \"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\"\n ],\n listForRelease: [\n \"GET /repos/{owner}/{repo}/releases/{release_id}/reactions\"\n ],\n listForTeamDiscussionCommentInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\"\n ],\n listForTeamDiscussionInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\"\n ]\n },\n repos: {\n acceptInvitation: [\n \"PATCH /user/repository_invitations/{invitation_id}\",\n {},\n { renamed: [\"repos\", \"acceptInvitationForAuthenticatedUser\"] }\n ],\n acceptInvitationForAuthenticatedUser: [\n \"PATCH /user/repository_invitations/{invitation_id}\"\n ],\n addAppAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" }\n ],\n addCollaborator: [\"PUT /repos/{owner}/{repo}/collaborators/{username}\"],\n addStatusCheckContexts: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" }\n ],\n addTeamAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" }\n ],\n addUserAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" }\n ],\n cancelPagesDeployment: [\n \"POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel\"\n ],\n checkAutomatedSecurityFixes: [\n \"GET /repos/{owner}/{repo}/automated-security-fixes\"\n ],\n checkCollaborator: [\"GET /repos/{owner}/{repo}/collaborators/{username}\"],\n checkVulnerabilityAlerts: [\n \"GET /repos/{owner}/{repo}/vulnerability-alerts\"\n ],\n codeownersErrors: [\"GET /repos/{owner}/{repo}/codeowners/errors\"],\n compareCommits: [\"GET /repos/{owner}/{repo}/compare/{base}...{head}\"],\n compareCommitsWithBasehead: [\n \"GET /repos/{owner}/{repo}/compare/{basehead}\"\n ],\n createAutolink: [\"POST /repos/{owner}/{repo}/autolinks\"],\n createCommitComment: [\n \"POST /repos/{owner}/{repo}/commits/{commit_sha}/comments\"\n ],\n createCommitSignatureProtection: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\"\n ],\n createCommitStatus: [\"POST /repos/{owner}/{repo}/statuses/{sha}\"],\n createDeployKey: [\"POST /repos/{owner}/{repo}/keys\"],\n createDeployment: [\"POST /repos/{owner}/{repo}/deployments\"],\n createDeploymentBranchPolicy: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\"\n ],\n createDeploymentProtectionRule: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules\"\n ],\n createDeploymentStatus: [\n \"POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"\n ],\n createDispatchEvent: [\"POST /repos/{owner}/{repo}/dispatches\"],\n createForAuthenticatedUser: [\"POST /user/repos\"],\n createFork: [\"POST /repos/{owner}/{repo}/forks\"],\n createInOrg: [\"POST /orgs/{org}/repos\"],\n createOrUpdateCustomPropertiesValues: [\n \"PATCH /repos/{owner}/{repo}/properties/values\"\n ],\n createOrUpdateEnvironment: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}\"\n ],\n createOrUpdateFileContents: [\"PUT /repos/{owner}/{repo}/contents/{path}\"],\n createOrgRuleset: [\"POST /orgs/{org}/rulesets\"],\n createPagesDeployment: [\"POST /repos/{owner}/{repo}/pages/deployments\"],\n createPagesSite: [\"POST /repos/{owner}/{repo}/pages\"],\n createRelease: [\"POST /repos/{owner}/{repo}/releases\"],\n createRepoRuleset: [\"POST /repos/{owner}/{repo}/rulesets\"],\n createTagProtection: [\"POST /repos/{owner}/{repo}/tags/protection\"],\n createUsingTemplate: [\n \"POST /repos/{template_owner}/{template_repo}/generate\"\n ],\n createWebhook: [\"POST /repos/{owner}/{repo}/hooks\"],\n declineInvitation: [\n \"DELETE /user/repository_invitations/{invitation_id}\",\n {},\n { renamed: [\"repos\", \"declineInvitationForAuthenticatedUser\"] }\n ],\n declineInvitationForAuthenticatedUser: [\n \"DELETE /user/repository_invitations/{invitation_id}\"\n ],\n delete: [\"DELETE /repos/{owner}/{repo}\"],\n deleteAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"\n ],\n deleteAdminBranchProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"\n ],\n deleteAnEnvironment: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}\"\n ],\n deleteAutolink: [\"DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}\"],\n deleteBranchProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection\"\n ],\n deleteCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}\"],\n deleteCommitSignatureProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\"\n ],\n deleteDeployKey: [\"DELETE /repos/{owner}/{repo}/keys/{key_id}\"],\n deleteDeployment: [\n \"DELETE /repos/{owner}/{repo}/deployments/{deployment_id}\"\n ],\n deleteDeploymentBranchPolicy: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\"\n ],\n deleteFile: [\"DELETE /repos/{owner}/{repo}/contents/{path}\"],\n deleteInvitation: [\n \"DELETE /repos/{owner}/{repo}/invitations/{invitation_id}\"\n ],\n deleteOrgRuleset: [\"DELETE /orgs/{org}/rulesets/{ruleset_id}\"],\n deletePagesSite: [\"DELETE /repos/{owner}/{repo}/pages\"],\n deletePullRequestReviewProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"\n ],\n deleteRelease: [\"DELETE /repos/{owner}/{repo}/releases/{release_id}\"],\n deleteReleaseAsset: [\n \"DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}\"\n ],\n deleteRepoRuleset: [\"DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n deleteTagProtection: [\n \"DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}\"\n ],\n deleteWebhook: [\"DELETE /repos/{owner}/{repo}/hooks/{hook_id}\"],\n disableAutomatedSecurityFixes: [\n \"DELETE /repos/{owner}/{repo}/automated-security-fixes\"\n ],\n disableDeploymentProtectionRule: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}\"\n ],\n disablePrivateVulnerabilityReporting: [\n \"DELETE /repos/{owner}/{repo}/private-vulnerability-reporting\"\n ],\n disableVulnerabilityAlerts: [\n \"DELETE /repos/{owner}/{repo}/vulnerability-alerts\"\n ],\n downloadArchive: [\n \"GET /repos/{owner}/{repo}/zipball/{ref}\",\n {},\n { renamed: [\"repos\", \"downloadZipballArchive\"] }\n ],\n downloadTarballArchive: [\"GET /repos/{owner}/{repo}/tarball/{ref}\"],\n downloadZipballArchive: [\"GET /repos/{owner}/{repo}/zipball/{ref}\"],\n enableAutomatedSecurityFixes: [\n \"PUT /repos/{owner}/{repo}/automated-security-fixes\"\n ],\n enablePrivateVulnerabilityReporting: [\n \"PUT /repos/{owner}/{repo}/private-vulnerability-reporting\"\n ],\n enableVulnerabilityAlerts: [\n \"PUT /repos/{owner}/{repo}/vulnerability-alerts\"\n ],\n generateReleaseNotes: [\n \"POST /repos/{owner}/{repo}/releases/generate-notes\"\n ],\n get: [\"GET /repos/{owner}/{repo}\"],\n getAccessRestrictions: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"\n ],\n getAdminBranchProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"\n ],\n getAllDeploymentProtectionRules: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules\"\n ],\n getAllEnvironments: [\"GET /repos/{owner}/{repo}/environments\"],\n getAllStatusCheckContexts: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\"\n ],\n getAllTopics: [\"GET /repos/{owner}/{repo}/topics\"],\n getAppsWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\"\n ],\n getAutolink: [\"GET /repos/{owner}/{repo}/autolinks/{autolink_id}\"],\n getBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}\"],\n getBranchProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection\"\n ],\n getBranchRules: [\"GET /repos/{owner}/{repo}/rules/branches/{branch}\"],\n getClones: [\"GET /repos/{owner}/{repo}/traffic/clones\"],\n getCodeFrequencyStats: [\"GET /repos/{owner}/{repo}/stats/code_frequency\"],\n getCollaboratorPermissionLevel: [\n \"GET /repos/{owner}/{repo}/collaborators/{username}/permission\"\n ],\n getCombinedStatusForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/status\"],\n getCommit: [\"GET /repos/{owner}/{repo}/commits/{ref}\"],\n getCommitActivityStats: [\"GET /repos/{owner}/{repo}/stats/commit_activity\"],\n getCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}\"],\n getCommitSignatureProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\"\n ],\n getCommunityProfileMetrics: [\"GET /repos/{owner}/{repo}/community/profile\"],\n getContent: [\"GET /repos/{owner}/{repo}/contents/{path}\"],\n getContributorsStats: [\"GET /repos/{owner}/{repo}/stats/contributors\"],\n getCustomDeploymentProtectionRule: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}\"\n ],\n getCustomPropertiesValues: [\"GET /repos/{owner}/{repo}/properties/values\"],\n getDeployKey: [\"GET /repos/{owner}/{repo}/keys/{key_id}\"],\n getDeployment: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n getDeploymentBranchPolicy: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\"\n ],\n getDeploymentStatus: [\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}\"\n ],\n getEnvironment: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}\"\n ],\n getLatestPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/latest\"],\n getLatestRelease: [\"GET /repos/{owner}/{repo}/releases/latest\"],\n getOrgRuleSuite: [\"GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}\"],\n getOrgRuleSuites: [\"GET /orgs/{org}/rulesets/rule-suites\"],\n getOrgRuleset: [\"GET /orgs/{org}/rulesets/{ruleset_id}\"],\n getOrgRulesets: [\"GET /orgs/{org}/rulesets\"],\n getPages: [\"GET /repos/{owner}/{repo}/pages\"],\n getPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/{build_id}\"],\n getPagesDeployment: [\n \"GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}\"\n ],\n getPagesHealthCheck: [\"GET /repos/{owner}/{repo}/pages/health\"],\n getParticipationStats: [\"GET /repos/{owner}/{repo}/stats/participation\"],\n getPullRequestReviewProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"\n ],\n getPunchCardStats: [\"GET /repos/{owner}/{repo}/stats/punch_card\"],\n getReadme: [\"GET /repos/{owner}/{repo}/readme\"],\n getReadmeInDirectory: [\"GET /repos/{owner}/{repo}/readme/{dir}\"],\n getRelease: [\"GET /repos/{owner}/{repo}/releases/{release_id}\"],\n getReleaseAsset: [\"GET /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n getReleaseByTag: [\"GET /repos/{owner}/{repo}/releases/tags/{tag}\"],\n getRepoRuleSuite: [\n \"GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}\"\n ],\n getRepoRuleSuites: [\"GET /repos/{owner}/{repo}/rulesets/rule-suites\"],\n getRepoRuleset: [\"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n getRepoRulesets: [\"GET /repos/{owner}/{repo}/rulesets\"],\n getStatusChecksProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"\n ],\n getTeamsWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\"\n ],\n getTopPaths: [\"GET /repos/{owner}/{repo}/traffic/popular/paths\"],\n getTopReferrers: [\"GET /repos/{owner}/{repo}/traffic/popular/referrers\"],\n getUsersWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\"\n ],\n getViews: [\"GET /repos/{owner}/{repo}/traffic/views\"],\n getWebhook: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}\"],\n getWebhookConfigForRepo: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/config\"\n ],\n getWebhookDelivery: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}\"\n ],\n listActivities: [\"GET /repos/{owner}/{repo}/activity\"],\n listAutolinks: [\"GET /repos/{owner}/{repo}/autolinks\"],\n listBranches: [\"GET /repos/{owner}/{repo}/branches\"],\n listBranchesForHeadCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head\"\n ],\n listCollaborators: [\"GET /repos/{owner}/{repo}/collaborators\"],\n listCommentsForCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\"\n ],\n listCommitCommentsForRepo: [\"GET /repos/{owner}/{repo}/comments\"],\n listCommitStatusesForRef: [\n \"GET /repos/{owner}/{repo}/commits/{ref}/statuses\"\n ],\n listCommits: [\"GET /repos/{owner}/{repo}/commits\"],\n listContributors: [\"GET /repos/{owner}/{repo}/contributors\"],\n listCustomDeploymentRuleIntegrations: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps\"\n ],\n listDeployKeys: [\"GET /repos/{owner}/{repo}/keys\"],\n listDeploymentBranchPolicies: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\"\n ],\n listDeploymentStatuses: [\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"\n ],\n listDeployments: [\"GET /repos/{owner}/{repo}/deployments\"],\n listForAuthenticatedUser: [\"GET /user/repos\"],\n listForOrg: [\"GET /orgs/{org}/repos\"],\n listForUser: [\"GET /users/{username}/repos\"],\n listForks: [\"GET /repos/{owner}/{repo}/forks\"],\n listInvitations: [\"GET /repos/{owner}/{repo}/invitations\"],\n listInvitationsForAuthenticatedUser: [\"GET /user/repository_invitations\"],\n listLanguages: [\"GET /repos/{owner}/{repo}/languages\"],\n listPagesBuilds: [\"GET /repos/{owner}/{repo}/pages/builds\"],\n listPublic: [\"GET /repositories\"],\n listPullRequestsAssociatedWithCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\"\n ],\n listReleaseAssets: [\n \"GET /repos/{owner}/{repo}/releases/{release_id}/assets\"\n ],\n listReleases: [\"GET /repos/{owner}/{repo}/releases\"],\n listTagProtection: [\"GET /repos/{owner}/{repo}/tags/protection\"],\n listTags: [\"GET /repos/{owner}/{repo}/tags\"],\n listTeams: [\"GET /repos/{owner}/{repo}/teams\"],\n listWebhookDeliveries: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries\"\n ],\n listWebhooks: [\"GET /repos/{owner}/{repo}/hooks\"],\n merge: [\"POST /repos/{owner}/{repo}/merges\"],\n mergeUpstream: [\"POST /repos/{owner}/{repo}/merge-upstream\"],\n pingWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/pings\"],\n redeliverWebhookDelivery: [\n \"POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts\"\n ],\n removeAppAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" }\n ],\n removeCollaborator: [\n \"DELETE /repos/{owner}/{repo}/collaborators/{username}\"\n ],\n removeStatusCheckContexts: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" }\n ],\n removeStatusCheckProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"\n ],\n removeTeamAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" }\n ],\n removeUserAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" }\n ],\n renameBranch: [\"POST /repos/{owner}/{repo}/branches/{branch}/rename\"],\n replaceAllTopics: [\"PUT /repos/{owner}/{repo}/topics\"],\n requestPagesBuild: [\"POST /repos/{owner}/{repo}/pages/builds\"],\n setAdminBranchProtection: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"\n ],\n setAppAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" }\n ],\n setStatusCheckContexts: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" }\n ],\n setTeamAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" }\n ],\n setUserAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" }\n ],\n testPushWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/tests\"],\n transfer: [\"POST /repos/{owner}/{repo}/transfer\"],\n update: [\"PATCH /repos/{owner}/{repo}\"],\n updateBranchProtection: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection\"\n ],\n updateCommitComment: [\"PATCH /repos/{owner}/{repo}/comments/{comment_id}\"],\n updateDeploymentBranchPolicy: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\"\n ],\n updateInformationAboutPagesSite: [\"PUT /repos/{owner}/{repo}/pages\"],\n updateInvitation: [\n \"PATCH /repos/{owner}/{repo}/invitations/{invitation_id}\"\n ],\n updateOrgRuleset: [\"PUT /orgs/{org}/rulesets/{ruleset_id}\"],\n updatePullRequestReviewProtection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"\n ],\n updateRelease: [\"PATCH /repos/{owner}/{repo}/releases/{release_id}\"],\n updateReleaseAsset: [\n \"PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}\"\n ],\n updateRepoRuleset: [\"PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n updateStatusCheckPotection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n {},\n { renamed: [\"repos\", \"updateStatusCheckProtection\"] }\n ],\n updateStatusCheckProtection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"\n ],\n updateWebhook: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}\"],\n updateWebhookConfigForRepo: [\n \"PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config\"\n ],\n uploadReleaseAsset: [\n \"POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}\",\n { baseUrl: \"https://uploads.github.com\" }\n ]\n },\n search: {\n code: [\"GET /search/code\"],\n commits: [\"GET /search/commits\"],\n issuesAndPullRequests: [\"GET /search/issues\"],\n labels: [\"GET /search/labels\"],\n repos: [\"GET /search/repositories\"],\n topics: [\"GET /search/topics\"],\n users: [\"GET /search/users\"]\n },\n secretScanning: {\n getAlert: [\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\"\n ],\n listAlertsForEnterprise: [\n \"GET /enterprises/{enterprise}/secret-scanning/alerts\"\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/secret-scanning/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/secret-scanning/alerts\"],\n listLocationsForAlert: [\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations\"\n ],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\"\n ]\n },\n securityAdvisories: {\n createFork: [\n \"POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks\"\n ],\n createPrivateVulnerabilityReport: [\n \"POST /repos/{owner}/{repo}/security-advisories/reports\"\n ],\n createRepositoryAdvisory: [\n \"POST /repos/{owner}/{repo}/security-advisories\"\n ],\n createRepositoryAdvisoryCveRequest: [\n \"POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve\"\n ],\n getGlobalAdvisory: [\"GET /advisories/{ghsa_id}\"],\n getRepositoryAdvisory: [\n \"GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}\"\n ],\n listGlobalAdvisories: [\"GET /advisories\"],\n listOrgRepositoryAdvisories: [\"GET /orgs/{org}/security-advisories\"],\n listRepositoryAdvisories: [\"GET /repos/{owner}/{repo}/security-advisories\"],\n updateRepositoryAdvisory: [\n \"PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}\"\n ]\n },\n teams: {\n addOrUpdateMembershipForUserInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/memberships/{username}\"\n ],\n addOrUpdateProjectPermissionsInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}\"\n ],\n addOrUpdateRepoPermissionsInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"\n ],\n checkPermissionsForProjectInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/projects/{project_id}\"\n ],\n checkPermissionsForRepoInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"\n ],\n create: [\"POST /orgs/{org}/teams\"],\n createDiscussionCommentInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"\n ],\n createDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions\"],\n deleteDiscussionCommentInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"\n ],\n deleteDiscussionInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"\n ],\n deleteInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}\"],\n getByName: [\"GET /orgs/{org}/teams/{team_slug}\"],\n getDiscussionCommentInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"\n ],\n getDiscussionInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"\n ],\n getMembershipForUserInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/memberships/{username}\"\n ],\n list: [\"GET /orgs/{org}/teams\"],\n listChildInOrg: [\"GET /orgs/{org}/teams/{team_slug}/teams\"],\n listDiscussionCommentsInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"\n ],\n listDiscussionsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions\"],\n listForAuthenticatedUser: [\"GET /user/teams\"],\n listMembersInOrg: [\"GET /orgs/{org}/teams/{team_slug}/members\"],\n listPendingInvitationsInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/invitations\"\n ],\n listProjectsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/projects\"],\n listReposInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos\"],\n removeMembershipForUserInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}\"\n ],\n removeProjectInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}\"\n ],\n removeRepoInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"\n ],\n updateDiscussionCommentInOrg: [\n \"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"\n ],\n updateDiscussionInOrg: [\n \"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"\n ],\n updateInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}\"]\n },\n users: {\n addEmailForAuthenticated: [\n \"POST /user/emails\",\n {},\n { renamed: [\"users\", \"addEmailForAuthenticatedUser\"] }\n ],\n addEmailForAuthenticatedUser: [\"POST /user/emails\"],\n addSocialAccountForAuthenticatedUser: [\"POST /user/social_accounts\"],\n block: [\"PUT /user/blocks/{username}\"],\n checkBlocked: [\"GET /user/blocks/{username}\"],\n checkFollowingForUser: [\"GET /users/{username}/following/{target_user}\"],\n checkPersonIsFollowedByAuthenticated: [\"GET /user/following/{username}\"],\n createGpgKeyForAuthenticated: [\n \"POST /user/gpg_keys\",\n {},\n { renamed: [\"users\", \"createGpgKeyForAuthenticatedUser\"] }\n ],\n createGpgKeyForAuthenticatedUser: [\"POST /user/gpg_keys\"],\n createPublicSshKeyForAuthenticated: [\n \"POST /user/keys\",\n {},\n { renamed: [\"users\", \"createPublicSshKeyForAuthenticatedUser\"] }\n ],\n createPublicSshKeyForAuthenticatedUser: [\"POST /user/keys\"],\n createSshSigningKeyForAuthenticatedUser: [\"POST /user/ssh_signing_keys\"],\n deleteEmailForAuthenticated: [\n \"DELETE /user/emails\",\n {},\n { renamed: [\"users\", \"deleteEmailForAuthenticatedUser\"] }\n ],\n deleteEmailForAuthenticatedUser: [\"DELETE /user/emails\"],\n deleteGpgKeyForAuthenticated: [\n \"DELETE /user/gpg_keys/{gpg_key_id}\",\n {},\n { renamed: [\"users\", \"deleteGpgKeyForAuthenticatedUser\"] }\n ],\n deleteGpgKeyForAuthenticatedUser: [\"DELETE /user/gpg_keys/{gpg_key_id}\"],\n deletePublicSshKeyForAuthenticated: [\n \"DELETE /user/keys/{key_id}\",\n {},\n { renamed: [\"users\", \"deletePublicSshKeyForAuthenticatedUser\"] }\n ],\n deletePublicSshKeyForAuthenticatedUser: [\"DELETE /user/keys/{key_id}\"],\n deleteSocialAccountForAuthenticatedUser: [\"DELETE /user/social_accounts\"],\n deleteSshSigningKeyForAuthenticatedUser: [\n \"DELETE /user/ssh_signing_keys/{ssh_signing_key_id}\"\n ],\n follow: [\"PUT /user/following/{username}\"],\n getAuthenticated: [\"GET /user\"],\n getByUsername: [\"GET /users/{username}\"],\n getContextForUser: [\"GET /users/{username}/hovercard\"],\n getGpgKeyForAuthenticated: [\n \"GET /user/gpg_keys/{gpg_key_id}\",\n {},\n { renamed: [\"users\", \"getGpgKeyForAuthenticatedUser\"] }\n ],\n getGpgKeyForAuthenticatedUser: [\"GET /user/gpg_keys/{gpg_key_id}\"],\n getPublicSshKeyForAuthenticated: [\n \"GET /user/keys/{key_id}\",\n {},\n { renamed: [\"users\", \"getPublicSshKeyForAuthenticatedUser\"] }\n ],\n getPublicSshKeyForAuthenticatedUser: [\"GET /user/keys/{key_id}\"],\n getSshSigningKeyForAuthenticatedUser: [\n \"GET /user/ssh_signing_keys/{ssh_signing_key_id}\"\n ],\n list: [\"GET /users\"],\n listBlockedByAuthenticated: [\n \"GET /user/blocks\",\n {},\n { renamed: [\"users\", \"listBlockedByAuthenticatedUser\"] }\n ],\n listBlockedByAuthenticatedUser: [\"GET /user/blocks\"],\n listEmailsForAuthenticated: [\n \"GET /user/emails\",\n {},\n { renamed: [\"users\", \"listEmailsForAuthenticatedUser\"] }\n ],\n listEmailsForAuthenticatedUser: [\"GET /user/emails\"],\n listFollowedByAuthenticated: [\n \"GET /user/following\",\n {},\n { renamed: [\"users\", \"listFollowedByAuthenticatedUser\"] }\n ],\n listFollowedByAuthenticatedUser: [\"GET /user/following\"],\n listFollowersForAuthenticatedUser: [\"GET /user/followers\"],\n listFollowersForUser: [\"GET /users/{username}/followers\"],\n listFollowingForUser: [\"GET /users/{username}/following\"],\n listGpgKeysForAuthenticated: [\n \"GET /user/gpg_keys\",\n {},\n { renamed: [\"users\", \"listGpgKeysForAuthenticatedUser\"] }\n ],\n listGpgKeysForAuthenticatedUser: [\"GET /user/gpg_keys\"],\n listGpgKeysForUser: [\"GET /users/{username}/gpg_keys\"],\n listPublicEmailsForAuthenticated: [\n \"GET /user/public_emails\",\n {},\n { renamed: [\"users\", \"listPublicEmailsForAuthenticatedUser\"] }\n ],\n listPublicEmailsForAuthenticatedUser: [\"GET /user/public_emails\"],\n listPublicKeysForUser: [\"GET /users/{username}/keys\"],\n listPublicSshKeysForAuthenticated: [\n \"GET /user/keys\",\n {},\n { renamed: [\"users\", \"listPublicSshKeysForAuthenticatedUser\"] }\n ],\n listPublicSshKeysForAuthenticatedUser: [\"GET /user/keys\"],\n listSocialAccountsForAuthenticatedUser: [\"GET /user/social_accounts\"],\n listSocialAccountsForUser: [\"GET /users/{username}/social_accounts\"],\n listSshSigningKeysForAuthenticatedUser: [\"GET /user/ssh_signing_keys\"],\n listSshSigningKeysForUser: [\"GET /users/{username}/ssh_signing_keys\"],\n setPrimaryEmailVisibilityForAuthenticated: [\n \"PATCH /user/email/visibility\",\n {},\n { renamed: [\"users\", \"setPrimaryEmailVisibilityForAuthenticatedUser\"] }\n ],\n setPrimaryEmailVisibilityForAuthenticatedUser: [\n \"PATCH /user/email/visibility\"\n ],\n unblock: [\"DELETE /user/blocks/{username}\"],\n unfollow: [\"DELETE /user/following/{username}\"],\n updateAuthenticated: [\"PATCH /user\"]\n }\n};\nvar endpoints_default = Endpoints;\n\n// pkg/dist-src/endpoints-to-methods.js\nvar endpointMethodsMap = /* @__PURE__ */ new Map();\nfor (const [scope, endpoints] of Object.entries(endpoints_default)) {\n for (const [methodName, endpoint] of Object.entries(endpoints)) {\n const [route, defaults, decorations] = endpoint;\n const [method, url] = route.split(/ /);\n const endpointDefaults = Object.assign(\n {\n method,\n url\n },\n defaults\n );\n if (!endpointMethodsMap.has(scope)) {\n endpointMethodsMap.set(scope, /* @__PURE__ */ new Map());\n }\n endpointMethodsMap.get(scope).set(methodName, {\n scope,\n methodName,\n endpointDefaults,\n decorations\n });\n }\n}\nvar handler = {\n has({ scope }, methodName) {\n return endpointMethodsMap.get(scope).has(methodName);\n },\n getOwnPropertyDescriptor(target, methodName) {\n return {\n value: this.get(target, methodName),\n // ensures method is in the cache\n configurable: true,\n writable: true,\n enumerable: true\n };\n },\n defineProperty(target, methodName, descriptor) {\n Object.defineProperty(target.cache, methodName, descriptor);\n return true;\n },\n deleteProperty(target, methodName) {\n delete target.cache[methodName];\n return true;\n },\n ownKeys({ scope }) {\n return [...endpointMethodsMap.get(scope).keys()];\n },\n set(target, methodName, value) {\n return target.cache[methodName] = value;\n },\n get({ octokit, scope, cache }, methodName) {\n if (cache[methodName]) {\n return cache[methodName];\n }\n const method = endpointMethodsMap.get(scope).get(methodName);\n if (!method) {\n return void 0;\n }\n const { endpointDefaults, decorations } = method;\n if (decorations) {\n cache[methodName] = decorate(\n octokit,\n scope,\n methodName,\n endpointDefaults,\n decorations\n );\n } else {\n cache[methodName] = octokit.request.defaults(endpointDefaults);\n }\n return cache[methodName];\n }\n};\nfunction endpointsToMethods(octokit) {\n const newMethods = {};\n for (const scope of endpointMethodsMap.keys()) {\n newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);\n }\n return newMethods;\n}\nfunction decorate(octokit, scope, methodName, defaults, decorations) {\n const requestWithDefaults = octokit.request.defaults(defaults);\n function withDecorations(...args) {\n let options = requestWithDefaults.endpoint.merge(...args);\n if (decorations.mapToData) {\n options = Object.assign({}, options, {\n data: options[decorations.mapToData],\n [decorations.mapToData]: void 0\n });\n return requestWithDefaults(options);\n }\n if (decorations.renamed) {\n const [newScope, newMethodName] = decorations.renamed;\n octokit.log.warn(\n `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`\n );\n }\n if (decorations.deprecated) {\n octokit.log.warn(decorations.deprecated);\n }\n if (decorations.renamedParameters) {\n const options2 = requestWithDefaults.endpoint.merge(...args);\n for (const [name, alias] of Object.entries(\n decorations.renamedParameters\n )) {\n if (name in options2) {\n octokit.log.warn(\n `\"${name}\" parameter is deprecated for \"octokit.${scope}.${methodName}()\". Use \"${alias}\" instead`\n );\n if (!(alias in options2)) {\n options2[alias] = options2[name];\n }\n delete options2[name];\n }\n }\n return requestWithDefaults(options2);\n }\n return requestWithDefaults(...args);\n }\n return Object.assign(withDecorations, requestWithDefaults);\n}\n\n// pkg/dist-src/index.js\nfunction restEndpointMethods(octokit) {\n const api = endpointsToMethods(octokit);\n return {\n rest: api\n };\n}\nrestEndpointMethods.VERSION = VERSION;\nfunction legacyRestEndpointMethods(octokit) {\n const api = endpointsToMethods(octokit);\n return {\n ...api,\n rest: api\n };\n}\nlegacyRestEndpointMethods.VERSION = VERSION;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n legacyRestEndpointMethods,\n restEndpointMethods\n});\n","\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n RequestError: () => RequestError\n});\nmodule.exports = __toCommonJS(dist_src_exports);\nvar import_deprecation = require(\"deprecation\");\nvar import_once = __toESM(require(\"once\"));\nvar logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation));\nvar logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation));\nvar RequestError = class extends Error {\n constructor(message, statusCode, options) {\n super(message);\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = \"HttpError\";\n this.status = statusCode;\n let headers;\n if (\"headers\" in options && typeof options.headers !== \"undefined\") {\n headers = options.headers;\n }\n if (\"response\" in options) {\n this.response = options.response;\n headers = options.response.headers;\n }\n const requestCopy = Object.assign({}, options.request);\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(\n / .*$/,\n \" [REDACTED]\"\n )\n });\n }\n requestCopy.url = requestCopy.url.replace(/\\bclient_secret=\\w+/g, \"client_secret=[REDACTED]\").replace(/\\baccess_token=\\w+/g, \"access_token=[REDACTED]\");\n this.request = requestCopy;\n Object.defineProperty(this, \"code\", {\n get() {\n logOnceCode(\n new import_deprecation.Deprecation(\n \"[@octokit/request-error] `error.code` is deprecated, use `error.status`.\"\n )\n );\n return statusCode;\n }\n });\n Object.defineProperty(this, \"headers\", {\n get() {\n logOnceHeaders(\n new import_deprecation.Deprecation(\n \"[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.\"\n )\n );\n return headers || {};\n }\n });\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n RequestError\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n request: () => request\n});\nmodule.exports = __toCommonJS(dist_src_exports);\nvar import_endpoint = require(\"@octokit/endpoint\");\nvar import_universal_user_agent = require(\"universal-user-agent\");\n\n// pkg/dist-src/version.js\nvar VERSION = \"8.4.0\";\n\n// pkg/dist-src/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null)\n return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\")\n return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null)\n return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/fetch-wrapper.js\nvar import_request_error = require(\"@octokit/request-error\");\n\n// pkg/dist-src/get-buffer-response.js\nfunction getBufferResponse(response) {\n return response.arrayBuffer();\n}\n\n// pkg/dist-src/fetch-wrapper.js\nfunction fetchWrapper(requestOptions) {\n var _a, _b, _c, _d;\n const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;\n const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false;\n if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {\n requestOptions.body = JSON.stringify(requestOptions.body);\n }\n let headers = {};\n let status;\n let url;\n let { fetch } = globalThis;\n if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) {\n fetch = requestOptions.request.fetch;\n }\n if (!fetch) {\n throw new Error(\n \"fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing\"\n );\n }\n return fetch(requestOptions.url, {\n method: requestOptions.method,\n body: requestOptions.body,\n redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect,\n headers: requestOptions.headers,\n signal: (_d = requestOptions.request) == null ? void 0 : _d.signal,\n // duplex must be set if request.body is ReadableStream or Async Iterables.\n // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.\n ...requestOptions.body && { duplex: \"half\" }\n }).then(async (response) => {\n url = response.url;\n status = response.status;\n for (const keyAndValue of response.headers) {\n headers[keyAndValue[0]] = keyAndValue[1];\n }\n if (\"deprecation\" in headers) {\n const matches = headers.link && headers.link.match(/<([^>]+)>; rel=\"deprecation\"/);\n const deprecationLink = matches && matches.pop();\n log.warn(\n `[@octokit/request] \"${requestOptions.method} ${requestOptions.url}\" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : \"\"}`\n );\n }\n if (status === 204 || status === 205) {\n return;\n }\n if (requestOptions.method === \"HEAD\") {\n if (status < 400) {\n return;\n }\n throw new import_request_error.RequestError(response.statusText, status, {\n response: {\n url,\n status,\n headers,\n data: void 0\n },\n request: requestOptions\n });\n }\n if (status === 304) {\n throw new import_request_error.RequestError(\"Not modified\", status, {\n response: {\n url,\n status,\n headers,\n data: await getResponseData(response)\n },\n request: requestOptions\n });\n }\n if (status >= 400) {\n const data = await getResponseData(response);\n const error = new import_request_error.RequestError(toErrorMessage(data), status, {\n response: {\n url,\n status,\n headers,\n data\n },\n request: requestOptions\n });\n throw error;\n }\n return parseSuccessResponseBody ? await getResponseData(response) : response.body;\n }).then((data) => {\n return {\n status,\n url,\n headers,\n data\n };\n }).catch((error) => {\n if (error instanceof import_request_error.RequestError)\n throw error;\n else if (error.name === \"AbortError\")\n throw error;\n let message = error.message;\n if (error.name === \"TypeError\" && \"cause\" in error) {\n if (error.cause instanceof Error) {\n message = error.cause.message;\n } else if (typeof error.cause === \"string\") {\n message = error.cause;\n }\n }\n throw new import_request_error.RequestError(message, 500, {\n request: requestOptions\n });\n });\n}\nasync function getResponseData(response) {\n const contentType = response.headers.get(\"content-type\");\n if (/application\\/json/.test(contentType)) {\n return response.json().catch(() => response.text()).catch(() => \"\");\n }\n if (!contentType || /^text\\/|charset=utf-8$/.test(contentType)) {\n return response.text();\n }\n return getBufferResponse(response);\n}\nfunction toErrorMessage(data) {\n if (typeof data === \"string\")\n return data;\n let suffix;\n if (\"documentation_url\" in data) {\n suffix = ` - ${data.documentation_url}`;\n } else {\n suffix = \"\";\n }\n if (\"message\" in data) {\n if (Array.isArray(data.errors)) {\n return `${data.message}: ${data.errors.map(JSON.stringify).join(\", \")}${suffix}`;\n }\n return `${data.message}${suffix}`;\n }\n return `Unknown error: ${JSON.stringify(data)}`;\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldEndpoint, newDefaults) {\n const endpoint2 = oldEndpoint.defaults(newDefaults);\n const newApi = function(route, parameters) {\n const endpointOptions = endpoint2.merge(route, parameters);\n if (!endpointOptions.request || !endpointOptions.request.hook) {\n return fetchWrapper(endpoint2.parse(endpointOptions));\n }\n const request2 = (route2, parameters2) => {\n return fetchWrapper(\n endpoint2.parse(endpoint2.merge(route2, parameters2))\n );\n };\n Object.assign(request2, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n return endpointOptions.request.hook(request2, endpointOptions);\n };\n return Object.assign(newApi, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n}\n\n// pkg/dist-src/index.js\nvar request = withDefaults(import_endpoint.endpoint, {\n headers: {\n \"user-agent\": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`\n }\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n request\n});\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n\n newInvalidAsn1Error: function (msg) {\n var e = new Error();\n e.name = 'InvalidAsn1Error';\n e.message = msg || '';\n return e;\n }\n\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar errors = require('./errors');\nvar types = require('./types');\n\nvar Reader = require('./reader');\nvar Writer = require('./writer');\n\n\n// --- Exports\n\nmodule.exports = {\n\n Reader: Reader,\n\n Writer: Writer\n\n};\n\nfor (var t in types) {\n if (types.hasOwnProperty(t))\n module.exports[t] = types[t];\n}\nfor (var e in errors) {\n if (errors.hasOwnProperty(e))\n module.exports[e] = errors[e];\n}\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\n\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\n\n\n// --- API\n\nfunction Reader(data) {\n if (!data || !Buffer.isBuffer(data))\n throw new TypeError('data must be a node Buffer');\n\n this._buf = data;\n this._size = data.length;\n\n // These hold the \"current\" state\n this._len = 0;\n this._offset = 0;\n}\n\nObject.defineProperty(Reader.prototype, 'length', {\n enumerable: true,\n get: function () { return (this._len); }\n});\n\nObject.defineProperty(Reader.prototype, 'offset', {\n enumerable: true,\n get: function () { return (this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'remain', {\n get: function () { return (this._size - this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'buffer', {\n get: function () { return (this._buf.slice(this._offset)); }\n});\n\n\n/**\n * Reads a single byte and advances offset; you can pass in `true` to make this\n * a \"peek\" operation (i.e., get the byte, but don't advance the offset).\n *\n * @param {Boolean} peek true means don't move offset.\n * @return {Number} the next byte, null if not enough data.\n */\nReader.prototype.readByte = function (peek) {\n if (this._size - this._offset < 1)\n return null;\n\n var b = this._buf[this._offset] & 0xff;\n\n if (!peek)\n this._offset += 1;\n\n return b;\n};\n\n\nReader.prototype.peek = function () {\n return this.readByte(true);\n};\n\n\n/**\n * Reads a (potentially) variable length off the BER buffer. This call is\n * not really meant to be called directly, as callers have to manipulate\n * the internal buffer afterwards.\n *\n * As a result of this call, you can call `Reader.length`, until the\n * next thing called that does a readLength.\n *\n * @return {Number} the amount of offset to advance the buffer.\n * @throws {InvalidAsn1Error} on bad ASN.1\n */\nReader.prototype.readLength = function (offset) {\n if (offset === undefined)\n offset = this._offset;\n\n if (offset >= this._size)\n return null;\n\n var lenB = this._buf[offset++] & 0xff;\n if (lenB === null)\n return null;\n\n if ((lenB & 0x80) === 0x80) {\n lenB &= 0x7f;\n\n if (lenB === 0)\n throw newInvalidAsn1Error('Indefinite length not supported');\n\n if (lenB > 4)\n throw newInvalidAsn1Error('encoding too long');\n\n if (this._size - offset < lenB)\n return null;\n\n this._len = 0;\n for (var i = 0; i < lenB; i++)\n this._len = (this._len << 8) + (this._buf[offset++] & 0xff);\n\n } else {\n // Wasn't a variable length\n this._len = lenB;\n }\n\n return offset;\n};\n\n\n/**\n * Parses the next sequence in this BER buffer.\n *\n * To get the length of the sequence, call `Reader.length`.\n *\n * @return {Number} the sequence's tag.\n */\nReader.prototype.readSequence = function (tag) {\n var seq = this.peek();\n if (seq === null)\n return null;\n if (tag !== undefined && tag !== seq)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + seq.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n this._offset = o;\n return seq;\n};\n\n\nReader.prototype.readInt = function () {\n return this._readTag(ASN1.Integer);\n};\n\n\nReader.prototype.readBoolean = function () {\n return (this._readTag(ASN1.Boolean) === 0 ? false : true);\n};\n\n\nReader.prototype.readEnumeration = function () {\n return this._readTag(ASN1.Enumeration);\n};\n\n\nReader.prototype.readString = function (tag, retbuf) {\n if (!tag)\n tag = ASN1.OctetString;\n\n var b = this.peek();\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n\n if (o === null)\n return null;\n\n if (this.length > this._size - o)\n return null;\n\n this._offset = o;\n\n if (this.length === 0)\n return retbuf ? Buffer.alloc(0) : '';\n\n var str = this._buf.slice(this._offset, this._offset + this.length);\n this._offset += this.length;\n\n return retbuf ? str : str.toString('utf8');\n};\n\nReader.prototype.readOID = function (tag) {\n if (!tag)\n tag = ASN1.OID;\n\n var b = this.readString(tag, true);\n if (b === null)\n return null;\n\n var values = [];\n var value = 0;\n\n for (var i = 0; i < b.length; i++) {\n var byte = b[i] & 0xff;\n\n value <<= 7;\n value += byte & 0x7f;\n if ((byte & 0x80) === 0) {\n values.push(value);\n value = 0;\n }\n }\n\n value = values.shift();\n values.unshift(value % 40);\n values.unshift((value / 40) >> 0);\n\n return values.join('.');\n};\n\n\nReader.prototype._readTag = function (tag) {\n assert.ok(tag !== undefined);\n\n var b = this.peek();\n\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n if (this.length > 4)\n throw newInvalidAsn1Error('Integer too long: ' + this.length);\n\n if (this.length > this._size - o)\n return null;\n this._offset = o;\n\n var fb = this._buf[this._offset];\n var value = 0;\n\n for (var i = 0; i < this.length; i++) {\n value <<= 8;\n value |= (this._buf[this._offset++] & 0xff);\n }\n\n if ((fb & 0x80) === 0x80 && i !== 4)\n value -= (1 << (i * 8));\n\n return value >> 0;\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Reader;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n EOC: 0,\n Boolean: 1,\n Integer: 2,\n BitString: 3,\n OctetString: 4,\n Null: 5,\n OID: 6,\n ObjectDescriptor: 7,\n External: 8,\n Real: 9, // float\n Enumeration: 10,\n PDV: 11,\n Utf8String: 12,\n RelativeOID: 13,\n Sequence: 16,\n Set: 17,\n NumericString: 18,\n PrintableString: 19,\n T61String: 20,\n VideotexString: 21,\n IA5String: 22,\n UTCTime: 23,\n GeneralizedTime: 24,\n GraphicString: 25,\n VisibleString: 26,\n GeneralString: 28,\n UniversalString: 29,\n CharacterString: 30,\n BMPString: 31,\n Constructor: 32,\n Context: 128\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\nvar DEFAULT_OPTS = {\n size: 1024,\n growthFactor: 8\n};\n\n\n// --- Helpers\n\nfunction merge(from, to) {\n assert.ok(from);\n assert.equal(typeof (from), 'object');\n assert.ok(to);\n assert.equal(typeof (to), 'object');\n\n var keys = Object.getOwnPropertyNames(from);\n keys.forEach(function (key) {\n if (to[key])\n return;\n\n var value = Object.getOwnPropertyDescriptor(from, key);\n Object.defineProperty(to, key, value);\n });\n\n return to;\n}\n\n\n\n// --- API\n\nfunction Writer(options) {\n options = merge(DEFAULT_OPTS, options || {});\n\n this._buf = Buffer.alloc(options.size || 1024);\n this._size = this._buf.length;\n this._offset = 0;\n this._options = options;\n\n // A list of offsets in the buffer where we need to insert\n // sequence tag/len pairs.\n this._seq = [];\n}\n\nObject.defineProperty(Writer.prototype, 'buffer', {\n get: function () {\n if (this._seq.length)\n throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');\n\n return (this._buf.slice(0, this._offset));\n }\n});\n\nWriter.prototype.writeByte = function (b) {\n if (typeof (b) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(1);\n this._buf[this._offset++] = b;\n};\n\n\nWriter.prototype.writeInt = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Integer;\n\n var sz = 4;\n\n while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&\n (sz > 1)) {\n sz--;\n i <<= 8;\n }\n\n if (sz > 4)\n throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');\n\n this._ensure(2 + sz);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = sz;\n\n while (sz-- > 0) {\n this._buf[this._offset++] = ((i & 0xff000000) >>> 24);\n i <<= 8;\n }\n\n};\n\n\nWriter.prototype.writeNull = function () {\n this.writeByte(ASN1.Null);\n this.writeByte(0x00);\n};\n\n\nWriter.prototype.writeEnumeration = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Enumeration;\n\n return this.writeInt(i, tag);\n};\n\n\nWriter.prototype.writeBoolean = function (b, tag) {\n if (typeof (b) !== 'boolean')\n throw new TypeError('argument must be a Boolean');\n if (typeof (tag) !== 'number')\n tag = ASN1.Boolean;\n\n this._ensure(3);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = 0x01;\n this._buf[this._offset++] = b ? 0xff : 0x00;\n};\n\n\nWriter.prototype.writeString = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');\n if (typeof (tag) !== 'number')\n tag = ASN1.OctetString;\n\n var len = Buffer.byteLength(s);\n this.writeByte(tag);\n this.writeLength(len);\n if (len) {\n this._ensure(len);\n this._buf.write(s, this._offset);\n this._offset += len;\n }\n};\n\n\nWriter.prototype.writeBuffer = function (buf, tag) {\n if (typeof (tag) !== 'number')\n throw new TypeError('tag must be a number');\n if (!Buffer.isBuffer(buf))\n throw new TypeError('argument must be a buffer');\n\n this.writeByte(tag);\n this.writeLength(buf.length);\n this._ensure(buf.length);\n buf.copy(this._buf, this._offset, 0, buf.length);\n this._offset += buf.length;\n};\n\n\nWriter.prototype.writeStringArray = function (strings) {\n if ((!strings instanceof Array))\n throw new TypeError('argument must be an Array[String]');\n\n var self = this;\n strings.forEach(function (s) {\n self.writeString(s);\n });\n};\n\n// This is really to solve DER cases, but whatever for now\nWriter.prototype.writeOID = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string');\n if (typeof (tag) !== 'number')\n tag = ASN1.OID;\n\n if (!/^([0-9]+\\.){3,}[0-9]+$/.test(s))\n throw new Error('argument is not a valid OID string');\n\n function encodeOctet(bytes, octet) {\n if (octet < 128) {\n bytes.push(octet);\n } else if (octet < 16384) {\n bytes.push((octet >>> 7) | 0x80);\n bytes.push(octet & 0x7F);\n } else if (octet < 2097152) {\n bytes.push((octet >>> 14) | 0x80);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else if (octet < 268435456) {\n bytes.push((octet >>> 21) | 0x80);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else {\n bytes.push(((octet >>> 28) | 0x80) & 0xFF);\n bytes.push(((octet >>> 21) | 0x80) & 0xFF);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n }\n }\n\n var tmp = s.split('.');\n var bytes = [];\n bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));\n tmp.slice(2).forEach(function (b) {\n encodeOctet(bytes, parseInt(b, 10));\n });\n\n var self = this;\n this._ensure(2 + bytes.length);\n this.writeByte(tag);\n this.writeLength(bytes.length);\n bytes.forEach(function (b) {\n self.writeByte(b);\n });\n};\n\n\nWriter.prototype.writeLength = function (len) {\n if (typeof (len) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(4);\n\n if (len <= 0x7f) {\n this._buf[this._offset++] = len;\n } else if (len <= 0xff) {\n this._buf[this._offset++] = 0x81;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffff) {\n this._buf[this._offset++] = 0x82;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffffff) {\n this._buf[this._offset++] = 0x83;\n this._buf[this._offset++] = len >> 16;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else {\n throw newInvalidAsn1Error('Length too long (> 4 bytes)');\n }\n};\n\nWriter.prototype.startSequence = function (tag) {\n if (typeof (tag) !== 'number')\n tag = ASN1.Sequence | ASN1.Constructor;\n\n this.writeByte(tag);\n this._seq.push(this._offset);\n this._ensure(3);\n this._offset += 3;\n};\n\n\nWriter.prototype.endSequence = function () {\n var seq = this._seq.pop();\n var start = seq + 3;\n var len = this._offset - start;\n\n if (len <= 0x7f) {\n this._shift(start, len, -2);\n this._buf[seq] = len;\n } else if (len <= 0xff) {\n this._shift(start, len, -1);\n this._buf[seq] = 0x81;\n this._buf[seq + 1] = len;\n } else if (len <= 0xffff) {\n this._buf[seq] = 0x82;\n this._buf[seq + 1] = len >> 8;\n this._buf[seq + 2] = len;\n } else if (len <= 0xffffff) {\n this._shift(start, len, 1);\n this._buf[seq] = 0x83;\n this._buf[seq + 1] = len >> 16;\n this._buf[seq + 2] = len >> 8;\n this._buf[seq + 3] = len;\n } else {\n throw newInvalidAsn1Error('Sequence too long');\n }\n};\n\n\nWriter.prototype._shift = function (start, len, shift) {\n assert.ok(start !== undefined);\n assert.ok(len !== undefined);\n assert.ok(shift);\n\n this._buf.copy(this._buf, start + shift, start, start + len);\n this._offset += shift;\n};\n\nWriter.prototype._ensure = function (len) {\n assert.ok(len);\n\n if (this._size - this._offset < len) {\n var sz = this._size * this._options.growthFactor;\n if (sz - this._offset < len)\n sz += len;\n\n var buf = Buffer.alloc(sz);\n\n this._buf.copy(buf, 0, 0, this._offset);\n this._buf = buf;\n this._size = sz;\n }\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Writer;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n// If you have no idea what ASN.1 or BER is, see this:\n// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc\n\nvar Ber = require('./ber/index');\n\n\n\n// --- Exported API\n\nmodule.exports = {\n\n Ber: Ber,\n\n BerReader: Ber.Reader,\n\n BerWriter: Ber.Writer\n\n};\n","function isBuffer (value) {\n return Buffer.isBuffer(value) || value instanceof Uint8Array\n}\n\nfunction isEncoding (encoding) {\n return Buffer.isEncoding(encoding)\n}\n\nfunction alloc (size, fill, encoding) {\n return Buffer.alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n return Buffer.allocUnsafe(size)\n}\n\nfunction allocUnsafeSlow (size) {\n return Buffer.allocUnsafeSlow(size)\n}\n\nfunction byteLength (string, encoding) {\n return Buffer.byteLength(string, encoding)\n}\n\nfunction compare (a, b) {\n return Buffer.compare(a, b)\n}\n\nfunction concat (buffers, totalLength) {\n return Buffer.concat(buffers, totalLength)\n}\n\nfunction copy (source, target, targetStart, start, end) {\n return toBuffer(source).copy(target, targetStart, start, end)\n}\n\nfunction equals (a, b) {\n return toBuffer(a).equals(b)\n}\n\nfunction fill (buffer, value, offset, end, encoding) {\n return toBuffer(buffer).fill(value, offset, end, encoding)\n}\n\nfunction from (value, encodingOrOffset, length) {\n return Buffer.from(value, encodingOrOffset, length)\n}\n\nfunction includes (buffer, value, byteOffset, encoding) {\n return toBuffer(buffer).includes(value, byteOffset, encoding)\n}\n\nfunction indexOf (buffer, value, byfeOffset, encoding) {\n return toBuffer(buffer).indexOf(value, byfeOffset, encoding)\n}\n\nfunction lastIndexOf (buffer, value, byteOffset, encoding) {\n return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)\n}\n\nfunction swap16 (buffer) {\n return toBuffer(buffer).swap16()\n}\n\nfunction swap32 (buffer) {\n return toBuffer(buffer).swap32()\n}\n\nfunction swap64 (buffer) {\n return toBuffer(buffer).swap64()\n}\n\nfunction toBuffer (buffer) {\n if (Buffer.isBuffer(buffer)) return buffer\n return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n}\n\nfunction toString (buffer, encoding, start, end) {\n return toBuffer(buffer).toString(encoding, start, end)\n}\n\nfunction write (buffer, string, offset, length, encoding) {\n return toBuffer(buffer).write(string, offset, length, encoding)\n}\n\nfunction writeDoubleLE (buffer, value, offset) {\n return toBuffer(buffer).writeDoubleLE(value, offset)\n}\n\nfunction writeFloatLE (buffer, value, offset) {\n return toBuffer(buffer).writeFloatLE(value, offset)\n}\n\nfunction writeUInt32LE (buffer, value, offset) {\n return toBuffer(buffer).writeUInt32LE(value, offset)\n}\n\nfunction writeInt32LE (buffer, value, offset) {\n return toBuffer(buffer).writeInt32LE(value, offset)\n}\n\nfunction readDoubleLE (buffer, offset) {\n return toBuffer(buffer).readDoubleLE(offset)\n}\n\nfunction readFloatLE (buffer, offset) {\n return toBuffer(buffer).readFloatLE(offset)\n}\n\nfunction readUInt32LE (buffer, offset) {\n return toBuffer(buffer).readUInt32LE(offset)\n}\n\nfunction readInt32LE (buffer, offset) {\n return toBuffer(buffer).readInt32LE(offset)\n}\n\nmodule.exports = {\n isBuffer,\n isEncoding,\n alloc,\n allocUnsafe,\n allocUnsafeSlow,\n byteLength,\n compare,\n concat,\n copy,\n equals,\n fill,\n from,\n includes,\n indexOf,\n lastIndexOf,\n swap16,\n swap32,\n swap64,\n toBuffer,\n toString,\n write,\n writeDoubleLE,\n writeFloatLE,\n writeUInt32LE,\n writeInt32LE,\n readDoubleLE,\n readFloatLE,\n readUInt32LE,\n readInt32LE\n}\n","'use strict';\n\nvar crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;\n\n/*\n * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a\n * result, it retains the original copyright and license. The two files are\n * under slightly different (but compatible) licenses, and are here combined in\n * one file.\n *\n * Credit for the actual porting work goes to:\n * Devi Mandiri \n */\n\n/*\n * The Blowfish portions are under the following license:\n *\n * Blowfish block cipher for OpenBSD\n * Copyright 1997 Niels Provos \n * All rights reserved.\n *\n * Implementation advice by David Mazieres .\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * The bcrypt_pbkdf portions are under the following license:\n *\n * Copyright (c) 2013 Ted Unangst \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n/*\n * Performance improvements (Javascript-specific):\n *\n * Copyright 2016, Joyent Inc\n * Author: Alex Wilson \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n// Ported from OpenBSD bcrypt_pbkdf.c v1.9\n\nvar BLF_J = 0;\n\nvar Blowfish = function() {\n this.S = [\n new Uint32Array([\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,\n 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,\n 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,\n 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,\n 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,\n 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,\n 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,\n 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,\n 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,\n 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,\n 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,\n 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,\n 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,\n 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,\n 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,\n 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,\n 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,\n 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,\n 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,\n 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,\n 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,\n 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,\n 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,\n 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,\n 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,\n 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,\n 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,\n 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,\n 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,\n 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,\n 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,\n 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,\n 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,\n 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,\n 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,\n 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,\n 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,\n 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,\n 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,\n 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,\n 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,\n 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,\n 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),\n new Uint32Array([\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,\n 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,\n 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,\n 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,\n 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,\n 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,\n 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,\n 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,\n 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,\n 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,\n 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,\n 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,\n 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,\n 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,\n 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,\n 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,\n 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,\n 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,\n 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,\n 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,\n 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,\n 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,\n 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,\n 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,\n 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,\n 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,\n 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,\n 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,\n 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,\n 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,\n 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,\n 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,\n 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,\n 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,\n 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,\n 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,\n 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,\n 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,\n 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,\n 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,\n 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,\n 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,\n 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),\n new Uint32Array([\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,\n 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,\n 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,\n 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,\n 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,\n 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,\n 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,\n 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,\n 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,\n 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,\n 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,\n 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,\n 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,\n 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,\n 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,\n 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,\n 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,\n 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,\n 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,\n 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,\n 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,\n 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,\n 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,\n 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,\n 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,\n 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,\n 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,\n 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,\n 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,\n 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,\n 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,\n 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,\n 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,\n 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,\n 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,\n 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,\n 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,\n 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,\n 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,\n 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,\n 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,\n 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,\n 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),\n new Uint32Array([\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,\n 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,\n 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,\n 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,\n 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,\n 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,\n 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,\n 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,\n 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,\n 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,\n 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,\n 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,\n 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,\n 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,\n 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,\n 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,\n 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,\n 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,\n 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,\n 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,\n 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,\n 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,\n 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,\n 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,\n 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,\n 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,\n 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,\n 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,\n 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,\n 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,\n 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,\n 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,\n 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,\n 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,\n 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,\n 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,\n 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,\n 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,\n 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,\n 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,\n 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,\n 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,\n 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])\n ];\n this.P = new Uint32Array([\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,\n 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,\n 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,\n 0x9216d5d9, 0x8979fb1b]);\n};\n\nfunction F(S, x8, i) {\n return (((S[0][x8[i+3]] +\n S[1][x8[i+2]]) ^\n S[2][x8[i+1]]) +\n S[3][x8[i]]);\n};\n\nBlowfish.prototype.encipher = function(x, x8) {\n if (x8 === undefined) {\n x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n }\n x[0] ^= this.P[0];\n for (var i = 1; i < 16; i += 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[17];\n x[1] = t;\n};\n\nBlowfish.prototype.decipher = function(x) {\n var x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n x[0] ^= this.P[17];\n for (var i = 16; i > 0; i -= 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[0];\n x[1] = t;\n};\n\nfunction stream2word(data, databytes){\n var i, temp = 0;\n for (i = 0; i < 4; i++, BLF_J++) {\n if (BLF_J >= databytes) BLF_J = 0;\n temp = (temp << 8) | data[BLF_J];\n }\n return temp;\n};\n\nBlowfish.prototype.expand0state = function(key, keybytes) {\n var d = new Uint32Array(2), i, k;\n var d8 = new Uint8Array(d.buffer);\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n BLF_J = 0;\n\n for (i = 0; i < 18; i += 2) {\n this.encipher(d, d8);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n this.encipher(d, d8);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n};\n\nBlowfish.prototype.expandstate = function(data, databytes, key, keybytes) {\n var d = new Uint32Array(2), i, k;\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n\n for (i = 0, BLF_J = 0; i < 18; i += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n BLF_J = 0;\n};\n\nBlowfish.prototype.enc = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.encipher(data.subarray(i*2));\n }\n};\n\nBlowfish.prototype.dec = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.decipher(data.subarray(i*2));\n }\n};\n\nvar BCRYPT_BLOCKS = 8,\n BCRYPT_HASHSIZE = 32;\n\nfunction bcrypt_hash(sha2pass, sha2salt, out) {\n var state = new Blowfish(),\n cdata = new Uint32Array(BCRYPT_BLOCKS), i,\n ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,\n 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,\n 105,116,101]); //\"OxychromaticBlowfishSwatDynamite\"\n\n state.expandstate(sha2salt, 64, sha2pass, 64);\n for (i = 0; i < 64; i++) {\n state.expand0state(sha2salt, 64);\n state.expand0state(sha2pass, 64);\n }\n\n for (i = 0; i < BCRYPT_BLOCKS; i++)\n cdata[i] = stream2word(ciphertext, ciphertext.byteLength);\n for (i = 0; i < 64; i++)\n state.enc(cdata, cdata.byteLength / 8);\n\n for (i = 0; i < BCRYPT_BLOCKS; i++) {\n out[4*i+3] = cdata[i] >>> 24;\n out[4*i+2] = cdata[i] >>> 16;\n out[4*i+1] = cdata[i] >>> 8;\n out[4*i+0] = cdata[i];\n }\n};\n\nfunction bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {\n var sha2pass = new Uint8Array(64),\n sha2salt = new Uint8Array(64),\n out = new Uint8Array(BCRYPT_HASHSIZE),\n tmpout = new Uint8Array(BCRYPT_HASHSIZE),\n countsalt = new Uint8Array(saltlen+4),\n i, j, amt, stride, dest, count,\n origkeylen = keylen;\n\n if (rounds < 1)\n return -1;\n if (passlen === 0 || saltlen === 0 || keylen === 0 ||\n keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))\n return -1;\n\n stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);\n amt = Math.floor((keylen + stride - 1) / stride);\n\n for (i = 0; i < saltlen; i++)\n countsalt[i] = salt[i];\n\n crypto_hash_sha512(sha2pass, pass, passlen);\n\n for (count = 1; keylen > 0; count++) {\n countsalt[saltlen+0] = count >>> 24;\n countsalt[saltlen+1] = count >>> 16;\n countsalt[saltlen+2] = count >>> 8;\n countsalt[saltlen+3] = count;\n\n crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (i = out.byteLength; i--;)\n out[i] = tmpout[i];\n\n for (i = 1; i < rounds; i++) {\n crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (j = 0; j < out.byteLength; j++)\n out[j] ^= tmpout[j];\n }\n\n amt = Math.min(amt, keylen);\n for (i = 0; i < amt; i++) {\n dest = i * stride + (count - 1);\n if (dest >= origkeylen)\n break;\n key[dest] = out[i];\n }\n keylen -= i;\n }\n\n return 0;\n};\n\nmodule.exports = {\n BLOCKS: BCRYPT_BLOCKS,\n HASHSIZE: BCRYPT_HASHSIZE,\n hash: bcrypt_hash,\n pbkdf: bcrypt_pbkdf\n};\n","var register = require(\"./lib/register\");\nvar addHook = require(\"./lib/add\");\nvar removeHook = require(\"./lib/remove\");\n\n// bind with array of arguments: https://stackoverflow.com/a/21792913\nvar bind = Function.bind;\nvar bindable = bind.bind(bind);\n\nfunction bindApi(hook, state, name) {\n var removeHookRef = bindable(removeHook, null).apply(\n null,\n name ? [state, name] : [state]\n );\n hook.api = { remove: removeHookRef };\n hook.remove = removeHookRef;\n [\"before\", \"error\", \"after\", \"wrap\"].forEach(function (kind) {\n var args = name ? [state, kind, name] : [state, kind];\n hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);\n });\n}\n\nfunction HookSingular() {\n var singularHookName = \"h\";\n var singularHookState = {\n registry: {},\n };\n var singularHook = register.bind(null, singularHookState, singularHookName);\n bindApi(singularHook, singularHookState, singularHookName);\n return singularHook;\n}\n\nfunction HookCollection() {\n var state = {\n registry: {},\n };\n\n var hook = register.bind(null, state);\n bindApi(hook, state);\n\n return hook;\n}\n\nvar collectionHookDeprecationMessageDisplayed = false;\nfunction Hook() {\n if (!collectionHookDeprecationMessageDisplayed) {\n console.warn(\n '[before-after-hook]: \"Hook()\" repurposing warning, use \"Hook.Collection()\". Read more: https://git.io/upgrade-before-after-hook-to-1.4'\n );\n collectionHookDeprecationMessageDisplayed = true;\n }\n return HookCollection();\n}\n\nHook.Singular = HookSingular.bind();\nHook.Collection = HookCollection.bind();\n\nmodule.exports = Hook;\n// expose constructors as a named property for TypeScript\nmodule.exports.Hook = Hook;\nmodule.exports.Singular = Hook.Singular;\nmodule.exports.Collection = Hook.Collection;\n","module.exports = addHook;\n\nfunction addHook(state, kind, name, hook) {\n var orig = hook;\n if (!state.registry[name]) {\n state.registry[name] = [];\n }\n\n if (kind === \"before\") {\n hook = function (method, options) {\n return Promise.resolve()\n .then(orig.bind(null, options))\n .then(method.bind(null, options));\n };\n }\n\n if (kind === \"after\") {\n hook = function (method, options) {\n var result;\n return Promise.resolve()\n .then(method.bind(null, options))\n .then(function (result_) {\n result = result_;\n return orig(result, options);\n })\n .then(function () {\n return result;\n });\n };\n }\n\n if (kind === \"error\") {\n hook = function (method, options) {\n return Promise.resolve()\n .then(method.bind(null, options))\n .catch(function (error) {\n return orig(error, options);\n });\n };\n }\n\n state.registry[name].push({\n hook: hook,\n orig: orig,\n });\n}\n","module.exports = register;\n\nfunction register(state, name, method, options) {\n if (typeof method !== \"function\") {\n throw new Error(\"method for before hook must be a function\");\n }\n\n if (!options) {\n options = {};\n }\n\n if (Array.isArray(name)) {\n return name.reverse().reduce(function (callback, name) {\n return register.bind(null, state, name, callback, options);\n }, method)();\n }\n\n return Promise.resolve().then(function () {\n if (!state.registry[name]) {\n return method(options);\n }\n\n return state.registry[name].reduce(function (method, registered) {\n return registered.hook.bind(null, method, options);\n }, method)();\n });\n}\n","module.exports = removeHook;\n\nfunction removeHook(state, name, method) {\n if (!state.registry[name]) {\n return;\n }\n\n var index = state.registry[name]\n .map(function (registered) {\n return registered.orig;\n })\n .indexOf(method);\n\n if (index === -1) {\n return;\n }\n\n state.registry[name].splice(index, 1);\n}\n","'use strict'\nconst fs = require('fs')\nconst path = require('path')\n\n/* istanbul ignore next */\nconst LCHOWN = fs.lchown ? 'lchown' : 'chown'\n/* istanbul ignore next */\nconst LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync'\n\n/* istanbul ignore next */\nconst needEISDIRHandled = fs.lchown &&\n !process.version.match(/v1[1-9]+\\./) &&\n !process.version.match(/v10\\.[6-9]/)\n\nconst lchownSync = (path, uid, gid) => {\n try {\n return fs[LCHOWNSYNC](path, uid, gid)\n } catch (er) {\n if (er.code !== 'ENOENT')\n throw er\n }\n}\n\n/* istanbul ignore next */\nconst chownSync = (path, uid, gid) => {\n try {\n return fs.chownSync(path, uid, gid)\n } catch (er) {\n if (er.code !== 'ENOENT')\n throw er\n }\n}\n\n/* istanbul ignore next */\nconst handleEISDIR =\n needEISDIRHandled ? (path, uid, gid, cb) => er => {\n // Node prior to v10 had a very questionable implementation of\n // fs.lchown, which would always try to call fs.open on a directory\n // Fall back to fs.chown in those cases.\n if (!er || er.code !== 'EISDIR')\n cb(er)\n else\n fs.chown(path, uid, gid, cb)\n }\n : (_, __, ___, cb) => cb\n\n/* istanbul ignore next */\nconst handleEISDirSync =\n needEISDIRHandled ? (path, uid, gid) => {\n try {\n return lchownSync(path, uid, gid)\n } catch (er) {\n if (er.code !== 'EISDIR')\n throw er\n chownSync(path, uid, gid)\n }\n }\n : (path, uid, gid) => lchownSync(path, uid, gid)\n\n// fs.readdir could only accept an options object as of node v6\nconst nodeVersion = process.version\nlet readdir = (path, options, cb) => fs.readdir(path, options, cb)\nlet readdirSync = (path, options) => fs.readdirSync(path, options)\n/* istanbul ignore next */\nif (/^v4\\./.test(nodeVersion))\n readdir = (path, options, cb) => fs.readdir(path, cb)\n\nconst chown = (cpath, uid, gid, cb) => {\n fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => {\n // Skip ENOENT error\n cb(er && er.code !== 'ENOENT' ? er : null)\n }))\n}\n\nconst chownrKid = (p, child, uid, gid, cb) => {\n if (typeof child === 'string')\n return fs.lstat(path.resolve(p, child), (er, stats) => {\n // Skip ENOENT error\n if (er)\n return cb(er.code !== 'ENOENT' ? er : null)\n stats.name = child\n chownrKid(p, stats, uid, gid, cb)\n })\n\n if (child.isDirectory()) {\n chownr(path.resolve(p, child.name), uid, gid, er => {\n if (er)\n return cb(er)\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n })\n } else {\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n }\n}\n\n\nconst chownr = (p, uid, gid, cb) => {\n readdir(p, { withFileTypes: true }, (er, children) => {\n // any error other than ENOTDIR or ENOTSUP means it's not readable,\n // or doesn't exist. give up.\n if (er) {\n if (er.code === 'ENOENT')\n return cb()\n else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')\n return cb(er)\n }\n if (er || !children.length)\n return chown(p, uid, gid, cb)\n\n let len = children.length\n let errState = null\n const then = er => {\n if (errState)\n return\n if (er)\n return cb(errState = er)\n if (-- len === 0)\n return chown(p, uid, gid, cb)\n }\n\n children.forEach(child => chownrKid(p, child, uid, gid, then))\n })\n}\n\nconst chownrKidSync = (p, child, uid, gid) => {\n if (typeof child === 'string') {\n try {\n const stats = fs.lstatSync(path.resolve(p, child))\n stats.name = child\n child = stats\n } catch (er) {\n if (er.code === 'ENOENT')\n return\n else\n throw er\n }\n }\n\n if (child.isDirectory())\n chownrSync(path.resolve(p, child.name), uid, gid)\n\n handleEISDirSync(path.resolve(p, child.name), uid, gid)\n}\n\nconst chownrSync = (p, uid, gid) => {\n let children\n try {\n children = readdirSync(p, { withFileTypes: true })\n } catch (er) {\n if (er.code === 'ENOENT')\n return\n else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP')\n return handleEISDirSync(p, uid, gid)\n else\n throw er\n }\n\n if (children && children.length)\n children.forEach(child => chownrKidSync(p, child, uid, gid))\n\n return handleEISDirSync(p, uid, gid)\n}\n\nmodule.exports = chownr\nchownr.sync = chownrSync\n","'use strict';\n\nconst binding = require('../build/Release/cpufeatures.node');\n\nmodule.exports = binding.getCPUInfo;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nclass Deprecation extends Error {\n constructor(message) {\n super(message); // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = 'Deprecation';\n }\n\n}\n\nexports.Deprecation = Deprecation;\n","//Based on follow-redirects v0.0.x\n\nvar nativeHttps = require('https'),\n nativeHttp = require('http'),\n url = require('url'),\n utils = require('./utils');\n\nvar maxRedirects = module.exports.maxRedirects = 5;\n\nvar protocols = {\n https: nativeHttps,\n http: nativeHttp\n};\n\nfor (var protocol in protocols) {\n var h = function() {};\n h.prototype = protocols[protocol];\n h = new h();\n\n h.request = function(h) {\n return function(options, callback, redirectOptions) {\n\n redirectOptions = redirectOptions || {};\n\n var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects;\n\n var redirect = utils.extend({\n count: 0,\n max: max,\n clientRequest: null,\n userCallback: callback\n }, redirectOptions);\n\n if (redirect.count > redirect.max) {\n var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.');\n redirect.clientRequest.emit('error', err);\n return redirect.clientRequest;\n }\n\n redirect.count++;\n\n var reqUrl;\n if (typeof options === 'string') {\n reqUrl = options;\n } else {\n reqUrl = url.format(utils.extend({\n protocol: protocol\n }, options));\n }\n\n var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect));\n\n if (!redirect.clientRequest) redirect.clientRequest = clientRequest;\n\n function redirectCallback(reqUrl, redirect) {\n return function(res) {\n if (res.statusCode < 300 || res.statusCode > 399) {\n return redirect.userCallback(res);\n }\n\n if (!('location' in res.headers)) {\n return redirect.userCallback(res);\n }\n\n var redirectUrl = url.resolve(reqUrl, res.headers.location);\n\n var proto = url.parse(redirectUrl).protocol;\n proto = proto.substr(0, proto.length - 1);\n return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect);\n };\n }\n\n return clientRequest;\n };\n }(h);\n\n // see https://github.com/joyent/node/blob/master/lib/http.js#L1623\n h.get = function(h) {\n return function(options, cb, redirectOptions) {\n var req = h.request(options, cb, redirectOptions);\n req.end();\n return req;\n };\n }(h);\n\n module.exports[protocol] = h;\n}\n","module.exports = HttpDuplex;\n\nvar util = require('util'),\n stream = require('readable-stream');\n\nutil.inherits(HttpDuplex, stream.Duplex);\n\nfunction HttpDuplex(req, res, options) {\n var self = this;\n\n if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options);\n\n stream.Duplex.call(self, options);\n self._output = null;\n\n self.connect(req, res);\n}\n\nHttpDuplex.prototype.connect = function(req, res) {\n var self = this;\n self.req = req;\n self._output = res;\n self.emit('response', res);\n\n res.on('data', function(c) {\n if (!self.push(c)) self._output.pause();\n });\n res.on('end', function() {\n self.push(null);\n });\n};\n\nHttpDuplex.prototype._read = function(n) {\n if (this._output) this._output.resume();\n};\n\nHttpDuplex.prototype._write = function(chunk, encoding, cb) {\n this.req.write(chunk, encoding);\n cb();\n};\n\nHttpDuplex.prototype.end = function(chunk, encoding, cb) {\n this._output.socket.destroySoon();\n return this.req.end(chunk, encoding, cb);\n};\n\nHttpDuplex.prototype.destroy = function() {\n this.req.destroy();\n this._output.socket.destroy();\n};\n\nHttpDuplex.prototype.destroySoon = function() {\n this.req.destroy();\n this._output.socket.destroy();\n};\n","var querystring = require('querystring'),\n http = require('./http'),\n fs = require('fs'),\n path = require('path'),\n url = require('url'),\n ssh = require('./ssh'),\n HttpDuplex = require('./http_duplex'),\n debug = require('debug')('modem'),\n utils = require('./utils'),\n util = require('util'),\n splitca = require('split-ca'),\n os = require('os'),\n isWin = os.type() === 'Windows_NT',\n stream = require('stream');\n\nvar defaultOpts = function () {\n var host;\n var opts = {};\n\n if (!process.env.DOCKER_HOST) {\n // Windows socket path: //./pipe/docker_engine ( Windows 10 )\n // Linux & Darwin socket path is /var/run/docker.sock when running system-wide,\n // or $HOME/.docker/run/docker.sock in new Docker Desktop installs.\n opts.socketPath = isWin ? '//./pipe/docker_engine' : findDefaultUnixSocket;\n } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) {\n // Strip off unix://, fall back to default if unix:// was passed without a path\n opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket;\n } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) {\n // Strip off npipe://, fall back to default of //./pipe/docker_engine if\n // npipe:// was passed without a path\n opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine';\n } else {\n var hostStr = process.env.DOCKER_HOST;\n if (hostStr.indexOf('\\/\\/') < 0) {\n hostStr = 'tcp://' + hostStr;\n }\n try {\n host = new url.URL(hostStr);\n } catch (err) {\n throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234');\n }\n\n opts.port = host.port;\n\n if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') {\n opts.protocol = 'https';\n } else if (host.protocol === 'ssh:') {\n opts.protocol = 'ssh';\n opts.username = host.username;\n opts.sshOptions = {\n agent: process.env.SSH_AUTH_SOCK,\n }\n } else {\n opts.protocol = 'http';\n }\n\n if (process.env.DOCKER_PATH_PREFIX) {\n opts.pathPrefix = process.env.DOCKER_PATH_PREFIX;\n }\n else {\n opts.pathPrefix = '/';\n }\n\n opts.host = host.hostname;\n\n if (process.env.DOCKER_CERT_PATH) {\n opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem'));\n opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem'));\n opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem'));\n }\n\n if (process.env.DOCKER_CLIENT_TIMEOUT) {\n opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10);\n }\n }\n\n return opts;\n};\n\nvar findDefaultUnixSocket = function () {\n return new Promise(function (resolve) {\n var userDockerSocket = path.join(os.homedir(), '.docker', 'run', 'docker.sock');\n fs.access(userDockerSocket, function (err) {\n if (err) resolve('/var/run/docker.sock');\n else resolve(userDockerSocket);\n })\n });\n}\n\n\nvar Modem = function (options) {\n var optDefaults = defaultOpts();\n var opts = Object.assign({}, optDefaults, options);\n\n this.host = opts.host;\n\n if (!this.host) {\n this.socketPath = opts.socketPath;\n }\n\n this.port = opts.port;\n this.pathPrefix = opts.pathPrefix;\n this.username = opts.username;\n this.password = opts.password;\n this.version = opts.version;\n this.key = opts.key;\n this.cert = opts.cert;\n this.ca = opts.ca;\n this.timeout = opts.timeout;\n this.connectionTimeout = opts.connectionTimeout;\n this.checkServerIdentity = opts.checkServerIdentity;\n this.agent = opts.agent;\n this.headers = opts.headers || {};\n this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions);\n //retrocompabitlity\n if (this.sshOptions.agentForward === undefined) {\n this.sshOptions.agentForward = opts.agentForward;\n }\n\n if (this.key && this.cert && this.ca) {\n this.protocol = 'https';\n }\n this.protocol = opts.protocol || this.protocol || 'http';\n};\n\nModem.prototype.dial = function (options, callback) {\n var opts, address, data;\n\n if (options.options) {\n opts = options.options;\n }\n\n // Prevent credentials from showing up in URL\n if (opts && opts.authconfig) {\n delete opts.authconfig;\n }\n\n // Prevent abortsignal from showing up in the URL\n if (opts && opts.abortSignal) {\n delete opts.abortSignal;\n }\n\n if (this.version) {\n options.path = '/' + this.version + options.path;\n }\n\n if (this.host) {\n var parsed = url.parse(this.host);\n address = url.format({\n protocol: parsed.protocol || this.protocol,\n hostname: parsed.hostname || this.host,\n port: this.port,\n pathname: parsed.pathname || this.pathPrefix,\n });\n address = url.resolve(address, options.path);\n } else {\n address = options.path;\n }\n\n if (options.path.indexOf('?') !== -1) {\n if (opts && Object.keys(opts).length > 0) {\n address += this.buildQuerystring(opts._query || opts);\n } else {\n address = address.substring(0, address.length - 1);\n }\n }\n\n var optionsf = {\n path: address,\n method: options.method,\n headers: options.headers || Object.assign({}, this.headers),\n key: this.key,\n cert: this.cert,\n ca: this.ca\n };\n\n\n if (this.checkServerIdentity) {\n optionsf.checkServerIdentity = this.checkServerIdentity;\n }\n\n if (this.agent) {\n optionsf.agent = this.agent;\n }\n\n if (options.authconfig) {\n optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 ||\n Buffer.from(JSON.stringify(options.authconfig)).toString('base64').replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n }\n\n if (options.registryconfig) {\n optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 ||\n Buffer.from(JSON.stringify(options.registryconfig)).toString('base64');\n }\n\n if (options.abortSignal) {\n optionsf.signal = options.abortSignal;\n }\n\n if (options.file) {\n if (typeof options.file === 'string') {\n data = fs.createReadStream(path.resolve(options.file));\n } else {\n data = options.file;\n }\n optionsf.headers['Content-Type'] = 'application/tar';\n } else if (opts && options.method === 'POST') {\n data = JSON.stringify(opts._body || opts);\n if (options.allowEmpty) {\n optionsf.headers['Content-Type'] = 'application/json';\n } else {\n if (data !== '{}' && data !== '\"\"') {\n optionsf.headers['Content-Type'] = 'application/json';\n } else {\n data = undefined;\n }\n }\n }\n\n if (typeof data === 'string') {\n optionsf.headers['Content-Length'] = Buffer.byteLength(data);\n } else if (Buffer.isBuffer(data) === true) {\n optionsf.headers['Content-Length'] = data.length;\n } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) {\n optionsf.headers['Transfer-Encoding'] = 'chunked';\n }\n\n if (options.hijack) {\n optionsf.headers.Connection = 'Upgrade';\n optionsf.headers.Upgrade = 'tcp';\n }\n\n if (this.socketPath) {\n // SocketPath may be a function that can return a promise:\n this.getSocketPath().then((socketPath) => {\n optionsf.socketPath = socketPath;\n this.buildRequest(optionsf, options, data, callback);\n });\n } else {\n var urlp = url.parse(address);\n optionsf.hostname = urlp.hostname;\n optionsf.port = urlp.port;\n optionsf.path = urlp.path;\n\n this.buildRequest(optionsf, options, data, callback);\n }\n};\n\nModem.prototype.getSocketPath = function () {\n if (!this.socketPath) return;\n if (this.socketPathCache) return Promise.resolve(this.socketPathCache);\n\n var socketPathValue = typeof this.socketPath === 'function'\n ? this.socketPath() : this.socketPath;\n\n this.socketPathCache = socketPathValue;\n\n return Promise.resolve(socketPathValue);\n}\n\nModem.prototype.buildRequest = function (options, context, data, callback) {\n var self = this;\n var connectionTimeoutTimer;\n var finished = false;\n\n var opts = self.protocol === 'ssh' ? Object.assign(options, {\n agent: ssh(Object.assign({}, self.sshOptions, {\n 'host': self.host,\n 'port': self.port,\n 'username': self.username,\n 'password': self.password,\n })),\n protocol: 'http:',\n }) : options;\n\n var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { });\n\n debug('Sending: %s', util.inspect(options, {\n showHidden: true,\n depth: null\n }));\n\n if (self.connectionTimeout) {\n connectionTimeoutTimer = setTimeout(function () {\n debug('Connection Timeout of %s ms exceeded', self.connectionTimeout);\n req.abort();\n }, self.connectionTimeout);\n }\n\n if (self.timeout) {\n req.on('socket', function (socket) {\n socket.setTimeout(self.timeout);\n socket.on('timeout', function () {\n debug('Timeout of %s ms exceeded', self.timeout);\n req.abort();\n });\n });\n }\n\n if (context.hijack === true) {\n clearTimeout(connectionTimeoutTimer);\n req.on('upgrade', function (res, sock, head) {\n if (finished === false) {\n finished = true;\n return callback(null, sock);\n }\n });\n }\n\n req.on('connect', function () {\n clearTimeout(connectionTimeoutTimer);\n });\n\n req.on('disconnect', function () {\n clearTimeout(connectionTimeoutTimer);\n });\n\n req.on('response', function (res) {\n clearTimeout(connectionTimeoutTimer);\n if (context.isStream === true) {\n if (finished === false) {\n finished = true;\n self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback);\n }\n } else {\n // The native 'request' method only handles aborting during the request lifecycle not the response lifecycle.\n // We need to make the response stream abortable so that it's destroyed with an error on abort and then\n // it triggers the request 'error' event\n if (options.signal != null) {\n stream.addAbortSignal(options.signal, res)\n }\n var chunks = [];\n res.on('data', function (chunk) {\n chunks.push(chunk);\n });\n\n res.on('end', function () {\n var buffer = Buffer.concat(chunks);\n var result = buffer.toString();\n\n debug('Received: %s', result);\n\n var json = utils.parseJSON(result) || buffer;\n if (finished === false) {\n finished = true;\n self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback);\n }\n });\n }\n });\n\n req.on('error', function (error) {\n clearTimeout(connectionTimeoutTimer);\n if (finished === false) {\n finished = true;\n self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback);\n }\n });\n\n if (typeof data === 'string' || Buffer.isBuffer(data)) {\n req.write(data);\n } else if (data) {\n data.on('error', function (error) {\n req.destroy(error);\n });\n data.pipe(req);\n }\n\n if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) {\n req.end();\n }\n};\n\nModem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) {\n if (err) return cb(err, null);\n\n if (statusCodes[res.statusCode] !== true) {\n getCause(isStream, res, json, function (err, cause) {\n if (err) {\n return cb(err, null);\n }\n var msg = new Error(\n '(HTTP code ' + res.statusCode + ') ' +\n (statusCodes[res.statusCode] || 'unexpected') + ' - ' +\n (cause.message || cause) + ' '\n );\n msg.reason = statusCodes[res.statusCode];\n msg.statusCode = res.statusCode;\n msg.json = json;\n cb(msg, null);\n });\n } else {\n if (openStdin) {\n cb(null, new HttpDuplex(req, res));\n } else if (isStream) {\n cb(null, res);\n } else {\n cb(null, json);\n }\n }\n\n function getCause(isStream, res, json, callback) {\n var chunks = '';\n var done = false;\n\n if (isStream) {\n res.on('data', function (chunk) {\n chunks += chunk;\n });\n res.on('error', function (err) {\n handler(err, null);\n });\n res.on('end', function () {\n handler(null, utils.parseJSON(chunks) || chunks)\n });\n } else {\n callback(null, json);\n }\n\n function handler(err, data) {\n if (done === false) {\n if (err) {\n callback(err);\n } else {\n callback(null, data);\n }\n }\n done = true;\n }\n }\n};\n\nModem.prototype.demuxStream = function (streama, stdout, stderr) {\n var nextDataType = null;\n var nextDataLength = null;\n var buffer = Buffer.from('');\n function processData(data) {\n if (data) {\n buffer = Buffer.concat([buffer, data]);\n }\n if (!nextDataType) {\n if (buffer.length >= 8) {\n var header = bufferSlice(8);\n nextDataType = header.readUInt8(0);\n nextDataLength = header.readUInt32BE(4);\n // It's possible we got a \"data\" that contains multiple messages\n // Process the next one\n processData();\n }\n } else {\n if (buffer.length >= nextDataLength) {\n var content = bufferSlice(nextDataLength);\n if (nextDataType === 1) {\n stdout.write(content);\n } else {\n stderr.write(content);\n }\n nextDataType = null;\n // It's possible we got a \"data\" that contains multiple messages\n // Process the next one\n processData();\n }\n }\n }\n\n function bufferSlice(end) {\n var out = buffer.subarray(0, end);\n buffer = Buffer.from(buffer.subarray(end, buffer.length));\n return out;\n }\n\n streama.on('data', processData);\n};\n\nModem.prototype.followProgress = function (streama, onFinished, onProgress) {\n var buf = '';\n var output = [];\n var finished = false;\n\n streama.on('data', onStreamEvent);\n streama.on('error', onStreamError);\n streama.on('end', onStreamEnd);\n streama.on('close', onStreamEnd);\n\n function onStreamEvent(data) {\n buf += data.toString();\n pump();\n\n function pump() {\n var pos;\n while ((pos = buf.indexOf('\\n')) >= 0) {\n if (pos == 0) {\n buf = buf.slice(1);\n continue;\n }\n processLine(buf.slice(0, pos));\n buf = buf.slice(pos + 1);\n }\n }\n\n function processLine(line) {\n if (line[line.length - 1] == '\\r') line = line.substr(0, line.length - 1);\n if (line.length > 0) {\n var obj = JSON.parse(line);\n output.push(obj);\n if (onProgress) {\n onProgress(obj);\n }\n }\n }\n };\n\n function onStreamError(err) {\n finished = true;\n streama.removeListener('data', onStreamEvent);\n streama.removeListener('error', onStreamError);\n streama.removeListener('end', onStreamEnd);\n streama.removeListener('close', onStreamEnd);\n onFinished(err, output);\n }\n\n function onStreamEnd() {\n if (!finished) onFinished(null, output);\n finished = true;\n }\n};\n\nModem.prototype.buildQuerystring = function (opts) {\n var clone = {};\n\n // serialize map and array values as JSON strings, else querystring truncates.\n // 't' and 'extrahosts' can be arrays but need special treatment so that they're\n // passed as multiple qs parameters instead of JSON values.\n Object.keys(opts).map(function (key, i) {\n if (opts[key]\n && typeof opts[key] === 'object'\n && !['t', 'extrahosts'].includes(key)\n ) {\n clone[key] = JSON.stringify(opts[key]);\n } else {\n clone[key] = opts[key];\n }\n });\n\n return querystring.stringify(clone);\n};\n\nmodule.exports = Modem;\n","var Client = require('ssh2').Client,\n http = require('http');\n\nmodule.exports = function (opt) {\n var conn = new Client();\n var agent = new http.Agent();\n\n agent.createConnection = function (options, fn) {\n try {\n conn.once('ready', function () {\n conn.exec('docker system dial-stdio', function (err, stream) {\n if (err) {\n handleError(err);\n }\n\n fn(null, stream);\n \n stream.addListener('error', (err) => {\n handleError(err);\n });\n stream.once('close', () => {\n conn.end();\n agent.destroy();\n });\n });\n }).on('error', (err) => {\n handleError(err);\n })\n .connect(opt);\n conn.once('end', () => agent.destroy());\n \n } catch (err) {\n handleError(err);\n }\n };\n\n function handleError(err) {\n conn.end();\n agent.destroy();\n throw err;\n }\n\n return agent;\n};\n","// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js\n\nvar arr = [];\nvar each = arr.forEach;\nvar slice = arr.slice;\n\nmodule.exports.extend = function(obj) {\n each.call(slice.call(arguments, 1), function(source) {\n if (source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\nmodule.exports.parseJSON = function(s) {\n try {\n return JSON.parse(s);\n } catch (e) {\n return null;\n }\n};\n","var util = require('./util');\n\n/**\n * Represents a config\n * @param {Object} modem docker-modem\n * @param {String} id Config's id\n */\nvar Config = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nConfig.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nConfig.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update a config.\n *\n * @param {object} opts\n * @param {function} callback\n */\nConfig.prototype.update = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id + '/update?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Removes the config\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nConfig.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'config not found',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Config;\n","var extend = require('./util').extend,\n Exec = require('./exec'),\n util = require('./util');\n\n/**\n * Represents a Container\n * @param {Object} modem docker-modem\n * @param {String} id Container's ID\n */\nvar Container = function(modem, id) {\n this.modem = modem;\n this.id = id;\n\n this.defaultOptions = {\n top: {},\n start: {},\n commit: {},\n stop: {},\n pause: {},\n unpause: {},\n restart: {},\n resize: {},\n attach: {},\n remove: {},\n copy: {},\n kill: {},\n exec: {},\n rename: {},\n log: {},\n stats: {},\n getArchive: {},\n infoArchive: {},\n putArchive: {},\n update: {},\n wait: {}\n };\n};\n\nContainer.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if supplied will query Docker.\n * @return {Object} ID only and only if callback isn't supplied.\n */\nContainer.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Rename\n * @param {Object} opts Rename options\n * @param {Function} callback Callback\n */\nContainer.prototype.rename = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.rename);\n\n var optsf = {\n path: '/containers/' + this.id + '/rename?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update\n * @param {Object} opts Update options\n * @param {Function} callback Callback\n */\nContainer.prototype.update = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.update);\n\n var optsf = {\n path: '/containers/' + this.id + '/update',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Top\n * @param {Object} opts like 'ps_args' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.top = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.top);\n\n var optsf = {\n path: '/containers/' + this.id + '/top?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Containers changes\n * @param {Object} Options\n * @param {Function} callback Callback\n */\nContainer.prototype.changes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/changes',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Checkpoints list\n * @param {Object} opts List checkpoints options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.listCheckpoint = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Delete checkpoint\n * @param {Object} opts Delete checkpoint options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.deleteCheckpoint = function(checkpoint, opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Create checkpoint\n * @param {Object} opts Create checkpoint options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.createCheckpoint = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/checkpoints',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n allowEmpty: true,\n statusCodes: {\n 200: true, //unofficial, but proxies may return it\n 201: true,\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Export\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback with the octet-stream.\n */\nContainer.prototype.export = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/' + this.id + '/export',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Start\n * @param {Object} opts Container start options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.start = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.start);\n\n var optsf = {\n path: '/containers/' + this.id + '/start?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 304: 'container already started',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Pause\n * @param {Object} opts Pause options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.pause = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.pause);\n\n var optsf = {\n path: '/containers/' + this.id + '/pause',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Unpause\n * @param {Object} opts Unpause options (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.unpause = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.unpause);\n\n var optsf = {\n path: '/containers/' + this.id + '/unpause',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Setup an exec call to a running container\n *\n * @param {object} opts\n * @param {function} callback\n */\nContainer.prototype.exec = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.exec);\n\n var optsf = {\n path: '/containers/' + this.id + '/exec',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 409: 'container stopped/paused',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(new Exec(self.modem, data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, new Exec(self.modem, data.Id));\n });\n }\n};\n\n/**\n * Commit\n * @param {Object} opts Commit options like 'Hostname' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.commit = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.commit);\n\n args.opts.container = this.id;\n\n var optsf = {\n path: '/commit?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Stop\n * @param {Object} opts Container stop options, like 't' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.stop = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.stop);\n\n var optsf = {\n path: '/containers/' + this.id + '/stop?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 304: 'container already stopped',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Restart\n * @param {Object} opts Container restart options, like 't' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.restart = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.restart);\n\n var optsf = {\n path: '/containers/' + this.id + '/restart?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Kill\n * @param {Object} opts Container kill options, like 'signal' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.kill = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.kill);\n\n var optsf = {\n path: '/containers/' + this.id + '/kill?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container resize\n * @param {[type]} opts Resize options. (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.resize = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.resize);\n\n var optsf = {\n path: '/containers/' + this.id + '/resize?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Attach\n * @param {Object} opts Attach options, like 'logs' (optional)\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.attach = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.attach);\n\n var optsf = {\n path: '/containers/' + this.id + '/attach?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n hijack: args.opts.hijack,\n openStdin: args.opts.stdin,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, stream) {\n if (err) {\n return reject(err);\n }\n resolve(stream);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, stream) {\n args.callback(err, stream);\n });\n }\n};\n\n/**\n * Waits for a container to end.\n * @param {[type]} opts Container wait options, like condition. (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.wait = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.wait);\n\n var optsf = {\n path: '/containers/' + this.id + '/wait?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes a container\n * @param {Object} opts Remove options, like 'force' (optional)\n * @param {Function} callback Callback\n */\nContainer.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.remove);\n\n var optsf = {\n path: '/containers/' + this.id + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Copy (WARNING: DEPRECATED since RAPI v1.20)\n * @param {Object} opts Copy options, like 'Resource' (optional)\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.copy = function(opts, callback) {\n var self = this;\n console.log('container.copy is deprecated since Docker v1.8.x');\n var args = util.processArgs(opts, callback, this.defaultOptions.copy);\n\n var optsf = {\n path: '/containers/' + this.id + '/copy',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * getArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.getArchive = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.getArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * infoArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.infoArchive = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'HEAD',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * putArchive\n * @param {Object} opts Archive options, like 'path'\n * @param {Function} callback Callback with stream.\n */\nContainer.prototype.putArchive = function(file, opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.putArchive);\n\n var optsf = {\n path: '/containers/' + this.id + '/archive?',\n method: 'PUT',\n file: file,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'client error, bad parameters',\n 403: 'client error, permission denied',\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nContainer.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.log);\n\n var optsf = {\n path: '/containers/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Container stats\n * @param {Object} opts Stats options. (optional)\n * @param {Function} callback Callback with data\n */\nContainer.prototype.stats = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.stats);\n var isStream = true;\n if (args.opts.stream === false) {\n isStream = false;\n }\n var optsf = {\n path: '/containers/' + this.id + '/stats?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: isStream,\n statusCodes: {\n 200: true,\n 404: 'no such container',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Container;\n","var EventEmitter = require('events').EventEmitter,\n Modem = require('docker-modem'),\n Container = require('./container'),\n Image = require('./image'),\n Volume = require('./volume'),\n Network = require('./network'),\n Service = require('./service'),\n Plugin = require('./plugin'),\n Secret = require('./secret'),\n Config = require('./config'),\n Task = require('./task'),\n Node = require('./node'),\n Exec = require('./exec'),\n util = require('./util'),\n extend = util.extend;\n\nvar Docker = function(opts) {\n if (!(this instanceof Docker)) return new Docker(opts);\n\n var plibrary = global.Promise;\n\n if (opts && opts.Promise) {\n plibrary = opts.Promise;\n\n if (Object.keys(opts).length === 1) {\n opts = undefined;\n }\n }\n\n if (opts && opts.modem) {\n this.modem = opts.modem;\n } else {\n this.modem = new Modem(opts);\n }\n this.modem.Promise = plibrary;\n};\n\n/**\n * Creates a new container\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createContainer = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/containers/create?',\n method: 'POST',\n options: opts,\n authconfig: opts.authconfig,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 400: 'bad parameter',\n 404: 'no such container',\n 406: 'impossible to attach',\n 500: 'server error'\n }\n };\n\n delete opts.authconfig;\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getContainer(data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n callback(err, self.getContainer(data.Id));\n });\n }\n};\n\n/**\n * Creates a new image\n * @param {Object} auth Authentication (optional)\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createImage = function(auth, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (!callback && !opts) {\n opts = auth;\n auth = opts.authconfig;\n }\n\n var optsf = {\n path: '/images/create?',\n method: 'POST',\n options: opts,\n authconfig: auth,\n abortSignal: opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Load image\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.loadImage = function(file, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n\n var optsf = {\n path: '/images/load?',\n method: 'POST',\n options: opts,\n file: file,\n abortSignal: opts && opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Import image from a tar archive\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.importImage = function(file, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = undefined;\n }\n\n if (!opts)\n opts = {};\n\n opts.fromSrc = '-';\n\n var optsf = {\n path: '/images/create?',\n method: 'POST',\n options: opts,\n file: file,\n abortSignal: opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Verifies auth\n * @param {Object} opts Options\n * @param {Function} callback Callback\n */\nDocker.prototype.checkAuth = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/auth',\n method: 'POST',\n options: opts,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Builds an image\n * @param {String} file File\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.buildImage = function(file, opts, callback) {\n var self = this;\n\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n\n var optsf = {\n path: '/build?',\n method: 'POST',\n file: undefined,\n options: opts,\n abortSignal: opts && opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (opts) {\n if (opts.registryconfig) {\n optsf.registryconfig = optsf.options.registryconfig;\n delete optsf.options.registryconfig;\n }\n\n //undocumented?\n if (opts.authconfig) {\n optsf.authconfig = optsf.options.authconfig;\n delete optsf.options.authconfig;\n }\n }\n\n if (callback === undefined) {\n return new self.modem.Promise(function(resolve, reject) {\n util.prepareBuildContext(file, (ctx) => {\n optsf.file = ctx;\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n });\n } else {\n util.prepareBuildContext(file, (ctx) => {\n optsf.file = ctx;\n self.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n })\n }\n};\n\n/**\n * Fetches a Container by ID\n * @param {String} id Container's ID\n */\nDocker.prototype.getContainer = function(id) {\n return new Container(this.modem, id);\n};\n\n/**\n * Fetches an Image by name\n * @param {String} name Image's name\n */\nDocker.prototype.getImage = function(name) {\n return new Image(this.modem, name);\n};\n\n/**\n * Fetches a Volume by name\n * @param {String} name Volume's name\n */\nDocker.prototype.getVolume = function(name) {\n return new Volume(this.modem, name);\n};\n\n/**\n * Fetches a Plugin by name\n * @param {String} name Volume's name\n */\nDocker.prototype.getPlugin = function(name, remote) {\n return new Plugin(this.modem, name, remote);\n};\n\n/**\n * Fetches a Service by id\n * @param {String} id Services's id\n */\nDocker.prototype.getService = function(id) {\n return new Service(this.modem, id);\n};\n\n/**\n * Fetches a Task by id\n * @param {String} id Task's id\n */\nDocker.prototype.getTask = function(id) {\n return new Task(this.modem, id);\n};\n\n/**\n * Fetches Node by id\n * @param {String} id Node's id\n */\nDocker.prototype.getNode = function(id) {\n return new Node(this.modem, id);\n};\n\n/**\n * Fetches a Network by id\n * @param {String} id network's id\n */\nDocker.prototype.getNetwork = function(id) {\n return new Network(this.modem, id);\n};\n\n/**\n * Fetches a Secret by id\n * @param {String} id network's id\n */\nDocker.prototype.getSecret = function(id) {\n return new Secret(this.modem, id);\n};\n\n/**\n * Fetches a Config by id\n * @param {String} id network's id\n */\nDocker.prototype.getConfig = function(id) {\n return new Config(this.modem, id);\n};\n\n/**\n * Fetches an Exec instance by ID\n * @param {String} id Exec instance's ID\n */\nDocker.prototype.getExec = function(id) {\n return new Exec(this.modem, id);\n};\n\n/**\n * Lists containers\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listContainers = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/json?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Get images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.getImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/get?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Services\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listServices = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Nodes\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listNodes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 404: 'no such node',\n 500: 'server error',\n 503: 'node is not part of a swarm',\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists Tasks\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listTasks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/tasks?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new secret\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createSecret = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n var optsf = {\n path: '/secrets/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 406: 'server error or node is not part of a swarm',\n 409: 'name conflicts with an existing object',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getSecret(data.ID));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getSecret(data.ID));\n });\n }\n};\n\n\n/**\n * Creates a new config\n * @param {Object} opts Config options\n * @param {Function} callback Callback\n */\nDocker.prototype.createConfig = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n var optsf = {\n path: '/configs/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 406: 'server error or node is not part of a swarm',\n 409: 'name conflicts with an existing object',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getConfig(data.ID));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getConfig(data.ID));\n });\n }\n};\n\n\n/**\n * Lists secrets\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listSecrets = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Lists configs\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listConfigs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/configs?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new plugin\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createPlugin = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/plugins/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getPlugin(args.opts.name));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getPlugin(args.opts.name));\n });\n }\n};\n\n\n/**\n * Lists plugins\n * @param {Object} opts\n * @param {Function} callback Callback\n */\nDocker.prototype.listPlugins = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune images\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneImages = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune builder\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneBuilder = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/build/prune',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune containers\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneContainers = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/containers/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune volumes\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneVolumes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Prune networks\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.pruneNetworks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/prune?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Creates a new volume\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createVolume = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/volumes/create?',\n method: 'POST',\n allowEmpty: true,\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getVolume(data.Name));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getVolume(data.Name));\n });\n }\n};\n\n/**\n * Creates a new service\n * @param {Object} auth\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createService = function(auth, opts, callback) {\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (!opts && !callback) {\n opts = auth;\n }\n\n\n var self = this;\n var optsf = {\n path: '/services/create',\n method: 'POST',\n options: opts,\n authconfig: auth,\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 500: 'server error'\n }\n };\n\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getService(data.ID || data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return callback(err, data);\n callback(err, self.getService(data.ID || data.Id));\n });\n }\n};\n\n/**\n * Lists volumes\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listVolumes = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Creates a new network\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nDocker.prototype.createNetwork = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var optsf = {\n path: '/networks/create?',\n method: 'POST',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 404: 'driver not found',\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(self.getNetwork(data.Id));\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, self.getNetwork(data.Id));\n });\n }\n};\n\n/**\n * Lists networks\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.listNetworks = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Search images\n * @param {Object} opts Options\n * @param {Function} callback Callback\n */\nDocker.prototype.searchImages = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/images/search?',\n method: 'GET',\n options: opts,\n authconfig: opts.authconfig,\n abortSignal: opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Info\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback with info\n */\nDocker.prototype.info = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/info',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Version\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.version = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/version',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Ping\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.ping = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/_ping',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * SystemDf \tequivalent to system/df API Engine\n *\t\tget usage data information\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.df = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/system/df',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Events\n * @param {Object} opts Events options, like 'since' (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.getEvents = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/events?',\n method: 'GET',\n options: args.opts,\n abortSignal: args.opts.abortSignal,\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Pull is a wrapper around createImage, parsing image's tags.\n * @param {String} repoTag Repository tag\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n * @param {Object} auth Authentication (optional)\n * @return {Object} Image\n */\nDocker.prototype.pull = function(repoTag, opts, callback, auth) {\n var args = util.processArgs(opts, callback);\n\n var imageSrc = util.parseRepositoryTag(repoTag);\n args.opts.fromImage = imageSrc.repository;\n args.opts.tag = imageSrc.tag || 'latest';\n\n var argsf = [args.opts, args.callback];\n if (auth) {\n argsf = [auth, args.opts, args.callback];\n }\n return this.createImage.apply(this, argsf);\n};\n\n/**\n * Like run command from Docker's CLI\n * @param {String} image Image name to be used.\n * @param {Array} cmd Command to run in array format.\n * @param {Object} streamo Output stream\n * @param {Object} createOptions Container create options (optional)\n * @param {Object} startOptions Container start options (optional)\n * @param {Function} callback Callback\n * @return {Object} EventEmitter\n */\nDocker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) {\n if (typeof arguments[arguments.length - 1] === 'function') {\n return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback);\n } else {\n return this.runPromise(image, cmd, streamo, createOptions, startOptions);\n }\n};\n\n\nDocker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) {\n if (!callback && typeof createOptions === 'function') {\n callback = createOptions;\n createOptions = {};\n startOptions = {};\n } else if (!callback && typeof startOptions === 'function') {\n callback = startOptions;\n startOptions = {};\n }\n\n var hub = new EventEmitter();\n\n function handler(err, container) {\n if (err) return callback(err, null, container);\n\n hub.emit('container', container);\n\n container.attach({\n stream: true,\n stdout: true,\n stderr: true\n }, function handler(err, stream) {\n if (err) return callback(err, null, container);\n\n hub.emit('stream', stream);\n\n if (streamo) {\n if (streamo instanceof Array) {\n stream.on('end', function() {\n try {\n streamo[0].end();\n } catch (e) {}\n try {\n streamo[1].end();\n } catch (e) {}\n });\n container.modem.demuxStream(stream, streamo[0], streamo[1]);\n } else {\n stream.setEncoding('utf8');\n stream.pipe(streamo, {\n end: true\n });\n }\n }\n\n container.start(startOptions, function(err, data) {\n if (err) return callback(err, data, container);\n hub.emit('start', container);\n\n container.wait(function(err, data) {\n hub.emit('data', data);\n callback(err, data, container);\n });\n });\n });\n }\n\n var optsc = {\n 'Hostname': '',\n 'User': '',\n 'AttachStdin': false,\n 'AttachStdout': true,\n 'AttachStderr': true,\n 'Tty': true,\n 'OpenStdin': false,\n 'StdinOnce': false,\n 'Env': null,\n 'Cmd': cmd,\n 'Image': image,\n 'Volumes': {},\n 'VolumesFrom': []\n };\n\n extend(optsc, createOptions);\n\n this.createContainer(optsc, handler);\n\n return hub;\n};\n\nDocker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) {\n var self = this;\n\n createOptions = createOptions || {};\n startOptions = startOptions || {};\n\n var optsc = {\n 'Hostname': '',\n 'User': '',\n 'AttachStdin': false,\n 'AttachStdout': true,\n 'AttachStderr': true,\n 'Tty': true,\n 'OpenStdin': false,\n 'StdinOnce': false,\n 'Env': null,\n 'Cmd': cmd,\n 'Image': image,\n 'Volumes': {},\n 'VolumesFrom': []\n };\n\n extend(optsc, createOptions);\n\n var containero;\n\n return new this.modem.Promise(function(resolve, reject) {\n self.createContainer(optsc).then(function(container) {\n containero = container;\n return container.attach({\n stream: true,\n stdout: true,\n stderr: true\n });\n }).then(function(stream) {\n if (streamo) {\n if (streamo instanceof Array) {\n stream.on('end', function() {\n try {\n streamo[0].end();\n } catch (e) {}\n try {\n streamo[1].end();\n } catch (e) {}\n });\n containero.modem.demuxStream(stream, streamo[0], streamo[1]);\n } else {\n stream.setEncoding('utf8');\n stream.pipe(streamo, {\n end: true\n });\n }\n }\n return containero.start(startOptions);\n }).then(function(data) {\n return containero.wait();\n }).then(function(data) {\n resolve([data, containero]);\n }).catch(function(err) {\n reject(err);\n });\n });\n};\n\n/**\n * Init swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmInit = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/init',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Join swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmJoin = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/join',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Leave swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmLeave = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/leave?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 406: 'node is not part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update swarm.\n *\n * @param {object} opts\n * @param {function} callback\n */\nDocker.prototype.swarmUpdate = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm/update?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 400: 'bad parameter',\n 406: 'node is already part of a Swarm'\n },\n options: args.opts\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Inspect a Swarm.\n * Warning: This method is not documented in the API\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n */\nDocker.prototype.swarmInspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/swarm',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 406: 'This node is not a swarm manager',\n 500: 'server error'\n }\n };\n\n if (args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nDocker.Container = Container;\nDocker.Image = Image;\nDocker.Volume = Volume;\nDocker.Network = Network;\nDocker.Service = Service;\nDocker.Plugin = Plugin;\nDocker.Secret = Secret;\nDocker.Task = Task;\nDocker.Node = Node;\nDocker.Exec = Exec;\n\nmodule.exports = Docker;\n","var util = require('./util');\n\n/**\n * Represents an Exec\n * @param {Object} modem docker-modem\n * @param {String} id Exec's ID\n */\nvar Exec = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nExec.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Start the exec call that was setup.\n *\n * @param {object} opts\n * @param {function} callback\n */\nExec.prototype.start = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/start',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n allowEmpty: true,\n hijack: args.opts.hijack,\n openStdin: args.opts.stdin,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such exec',\n 409: 'container stopped/paused',\n 500: 'container not running'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Resize the exec call that was setup.\n *\n * @param {object} opts\n * @param {function} callback\n */\nExec.prototype.resize = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/resize?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such exec',\n 500: 'container not running'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Get low-level information about the exec call.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nExec.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/exec/' + this.id + '/json',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such exec',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Exec;\n","var util = require('./util');\n\n/**\n * Represents an image\n * @param {Object} modem docker-modem\n * @param {String} name Image's name\n */\nvar Image = function(modem, name) {\n this.modem = modem;\n this.name = name;\n};\n\nImage.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nImage.prototype.inspect = function(callback) {\n var self = this;\n\n var opts = {\n path: '/images/' + this.name + '/json',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Distribution\n * @param {Object} opts\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nImage.prototype.distribution = function(opts, callback) {\n var args = util.processArgs(opts, callback);\n var self = this;\n\n var fopts = {\n path: '/distribution/' + this.name + '/json',\n method: 'GET',\n statusCodes: {\n 200: true,\n 401: 'no such image',\n 500: 'server error'\n },\n authconfig: (args.opts) ? args.opts.authconfig : undefined\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(fopts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(fopts, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * History\n * @param {Function} callback Callback\n */\nImage.prototype.history = function(callback) {\n var self = this;\n var opts = {\n path: '/images/' + this.name + '/history',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Get\n * @param {Function} callback Callback with data stream.\n */\nImage.prototype.get = function(callback) {\n var self = this;\n var opts = {\n path: '/images/' + this.name + '/get',\n method: 'GET',\n isStream: true,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n if (err) return callback(err, data);\n callback(err, data);\n });\n }\n};\n\n/**\n * Push\n * @param {Object} opts Push options, like 'registry' (optional)\n * @param {Function} callback Callback with stream.\n * @param {Object} auth Registry authentication\n */\nImage.prototype.push = function(opts, callback, auth) {\n var self = this;\n var args = util.processArgs(opts, callback);\n var isStream = true;\n if (args.opts.stream === false) {\n isStream = false;\n }\n var optsf = {\n path: '/images/' + this.name + '/push?',\n method: 'POST',\n options: args.opts,\n authconfig: args.opts.authconfig || auth,\n abortSignal: args.opts.abortSignal,\n isStream: isStream,\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 500: 'server error'\n }\n };\n\n delete optsf.options.authconfig;\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Tag\n * @param {Object} opts Tag options, like 'repo' (optional)\n * @param {Function} callback Callback\n */\nImage.prototype.tag = function(opts, callback) {\n var self = this;\n var optsf = {\n path: '/images/' + this.name + '/tag?',\n method: 'POST',\n options: opts,\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 201: true,\n 400: 'bad parameter',\n 404: 'no such image',\n 409: 'conflict',\n 500: 'server error'\n }\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n/**\n * Removes the image\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nImage.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/images/' + this.name + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such image',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Image;\n","var util = require('./util');\n\n/**\n * Represents an network\n * @param {Object} modem docker-modem\n * @param {String} id Network's id\n */\nvar Network = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nNetwork.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Id only if callback isn't specified.\n */\nNetwork.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var opts = {\n path: '/networks/' + this.id + '?',\n method: 'GET',\n statusCodes: {\n 200: true,\n 404: 'no such network',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(opts, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(opts, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the network\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such network',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Connects a container to a network\n * @param {[Object]} opts Connect options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.connect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id + '/connect',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 404: 'network or container is not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Disconnects a container from a network\n * @param {[Object]} opts Disconnect options (optional)\n * @param {Function} callback Callback\n */\nNetwork.prototype.disconnect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/networks/' + this.id + '/disconnect',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 201: true,\n 404: 'network or container is not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\n\nmodule.exports = Network;\n","var util = require('./util');\n\n/**\n * Represents an Node\n * @param {Object} modem docker-modem\n * @param {String} id Node's ID\n */\nvar Node = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nNode.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for Node details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nNode.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Update a node.\n *\n * @param {object} opts\n * @param {function} callback\n */\nNode.prototype.update = function(opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n }\n\n var optsf = {\n path: '/nodes/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 406: 'node is not part of a swarm',\n 500: 'server error'\n },\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n/**\n * Remove a Node.\n * Warning: This method is not documented in the API.\n *\n * @param {object} opts\n * @param {function} callback\n */\nNode.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/nodes/' + this.id + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such node',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Node;\n","var util = require('./util');\n\n/**\n * Represents a plugin\n * @param {Object} modem docker-modem\n * @param {String} name Plugin's name\n */\nvar Plugin = function(modem, name, remote) {\n this.modem = modem;\n this.name = name;\n this.remote = remote || name;\n};\n\nPlugin.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n *\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nPlugin.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin is not installed',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the plugin\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '?',\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin is not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n if (err) return args.callback(err, data);\n args.callback(err, data);\n });\n }\n};\n\n/**\n * get privileges\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback\n * @return {Object} Name only if callback isn't specified.\n */\nPlugin.prototype.privileges = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/privileges?',\n method: 'GET',\n options: {\n 'remote': this.remote\n },\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Installs a new plugin\n * @param {Object} opts Create options\n * @param {Function} callback Callback\n */\nPlugin.prototype.pull = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n if(args.opts._query && !args.opts._query.name) {\n args.opts._query.name = this.name;\n }\n if(args.opts._query && !args.opts._query.remote) {\n args.opts._query.remote = this.remote;\n }\n\n var optsf = {\n path: '/plugins/pull?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n isStream: true,\n options: args.opts,\n statusCodes: {\n 200: true, // unofficial, but proxies may return it\n 204: true,\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Enable\n * @param {Object} opts Plugin enable options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.enable = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/enable?',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Disable\n * @param {Object} opts Plugin disable options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.disable = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/disable',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Push\n * @param {Object} opts Plugin push options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.push = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/push',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * COnfigure\n * @param {Object} opts Plugin configure options (optional)\n * @param {Function} callback Callback\n */\nPlugin.prototype.configure = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/plugins/' + this.name + '/set',\n method: 'POST',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n/**\n * Upgrade plugin\n *\n * @param {object} auth\n * @param {object} opts\n * @param {function} callback\n */\nPlugin.prototype.upgrade = function(auth, opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n }\n\n var optsf = {\n path: '/plugins/' + this.name + '/upgrade?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'plugin not installed',\n 500: 'server error'\n },\n authconfig: auth,\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Plugin;\n","var util = require('./util');\n\n/**\n * Represents a secret\n * @param {Object} modem docker-modem\n * @param {String} id Secret's id\n */\nvar Secret = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nSecret.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nSecret.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'secret not found',\n 406: 'node is not part of a swarm',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update a secret.\n *\n * @param {object} opts\n * @param {function} callback\n */\nSecret.prototype.update = function(opts, callback) {\n var self = this;\n if (!callback && typeof opts === 'function') {\n callback = opts;\n }\n\n var optsf = {\n path: '/secrets/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'secret not found',\n 500: 'server error'\n },\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n/**\n * Removes the secret\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nSecret.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/secrets/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'secret not found',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Secret;\n","var util = require('./util');\n\n/**\n * Represents an Service\n * @param {Object} modem docker-modem\n * @param {String} id Service's ID\n */\nvar Service = function(modem, id) {\n this.modem = modem;\n this.id = id;\n};\n\nService.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for service details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nService.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Delete Service\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nService.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/services/' + this.id,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 204: true,\n 404: 'no such service',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Update service\n *\n * @param {object} auth\n * @param {object} opts\n * @param {function} callback\n */\nService.prototype.update = function(auth, opts, callback) {\n var self = this;\n if (!callback) {\n var t = typeof opts;\n if(t === 'function'){\n callback = opts;\n opts = auth;\n auth = opts.authconfig || undefined;\n } else if (t === 'undefined'){\n opts = auth;\n auth = opts.authconfig || undefined;\n }\n }\n\n var optsf = {\n path: '/services/' + this.id + '/update?',\n method: 'POST',\n abortSignal: opts && opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error'\n },\n authconfig: auth,\n options: opts\n };\n\n if(callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n callback(err, data);\n });\n }\n};\n\n\n\n/**\n * Service logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nService.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, {});\n\n var optsf = {\n path: '/services/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 200: true,\n 404: 'no such service',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\n\nmodule.exports = Service;\n","var util = require('./util');\n\n/**\n * Represents an Task\n * @param {Object} modem docker-modem\n * @param {String} id Task's ID\n */\nvar Task = function(modem, id) {\n this.modem = modem;\n this.id = id;\n\n this.defaultOptions = {\n log: {}\n };\n};\n\nTask.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Query Docker for Task details.\n *\n * @param {Object} opts Options (optional)\n * @param {function} callback\n */\nTask.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/tasks/' + this.id,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'unknown task',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Task logs\n * @param {Object} opts Logs options. (optional)\n * @param {Function} callback Callback with data\n */\nTask.prototype.logs = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback, this.defaultOptions.log);\n\n var optsf = {\n path: '/tasks/' + this.id + '/logs?',\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n isStream: args.opts.follow || false,\n statusCodes: {\n 101: true,\n 200: true,\n 404: 'no such container',\n 500: 'server error',\n 503: 'node is not part of a swarm'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n\nmodule.exports = Task;\n","var DockerIgnore = require('@balena/dockerignore');\nvar fs = require('fs');\nvar path = require('path');\nvar tar = require('tar-fs');\nvar zlib = require('zlib');\n\n// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js\n\nvar arr = [];\nvar each = arr.forEach;\nvar slice = arr.slice;\n\nmodule.exports.extend = function(obj) {\n each.call(slice.call(arguments, 1), function(source) {\n if (source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\nmodule.exports.processArgs = function(opts, callback, defaultOpts) {\n if (!callback && typeof opts === 'function') {\n callback = opts;\n opts = null;\n }\n return {\n callback: callback,\n opts: module.exports.extend({}, defaultOpts, opts)\n };\n};\n\n\n/**\n * Parse the given repo tag name (as a string) and break it out into repo/tag pair.\n * // if given the input http://localhost:8080/woot:latest\n * {\n * repository: 'http://localhost:8080/woot',\n * tag: 'latest'\n * }\n * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest'\n * @return {Object} input parsed into the repo and tag.\n */\nmodule.exports.parseRepositoryTag = function(input) {\n var separatorPos;\n var digestPos = input.indexOf('@');\n var colonPos = input.lastIndexOf(':');\n // @ symbol is more important\n if (digestPos >= 0) {\n separatorPos = digestPos;\n } else if (colonPos >= 0) {\n separatorPos = colonPos;\n } else {\n // no colon nor @\n return {\n repository: input\n };\n }\n\n // last colon is either the tag (or part of a port designation)\n var tag = input.slice(separatorPos + 1);\n\n // if it contains a / its not a tag and is part of the url\n if (tag.indexOf('/') === -1) {\n return {\n repository: input.slice(0, separatorPos),\n tag: tag\n };\n }\n\n return {\n repository: input\n };\n};\n\n\nmodule.exports.prepareBuildContext = function(file, next) {\n if (file && file.context) {\n fs.readFile(path.join(file.context, '.dockerignore'), (err, data) => {\n let ignoreFn;\n let filterFn;\n\n if (!err) {\n const dockerIgnore = DockerIgnore({ ignorecase: false }).add(data.toString());\n\n filterFn = dockerIgnore.createFilter();\n ignoreFn = (path) => {\n return !filterFn(path);\n }\n }\n\n const entries = file.src.slice() || []\n\n const pack = tar.pack(file.context, {\n entries: filterFn ? entries.filter(filterFn) : entries,\n ignore: ignoreFn // Only works on directories\n });\n\n next(pack.pipe(zlib.createGzip()));\n })\n } else {\n next(file);\n }\n}\n","var util = require('./util');\n\n/**\n * Represents a volume\n * @param {Object} modem docker-modem\n * @param {String} name Volume's name\n */\nvar Volume = function(modem, name) {\n this.modem = modem;\n this.name = name;\n};\n\nVolume.prototype[require('util').inspect.custom] = function() { return this; };\n\n/**\n * Inspect\n * @param {Object} opts Options (optional)\n * @param {Function} callback Callback, if specified Docker will be queried.\n * @return {Object} Name only if callback isn't specified.\n */\nVolume.prototype.inspect = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/' + this.name,\n method: 'GET',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 200: true,\n 404: 'no such volume',\n 500: 'server error'\n }\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\n/**\n * Removes the volume\n * @param {[Object]} opts Remove options (optional)\n * @param {Function} callback Callback\n */\nVolume.prototype.remove = function(opts, callback) {\n var self = this;\n var args = util.processArgs(opts, callback);\n\n var optsf = {\n path: '/volumes/' + this.name,\n method: 'DELETE',\n abortSignal: args.opts.abortSignal,\n statusCodes: {\n 204: true,\n 404: 'no such volume',\n 409: 'conflict',\n 500: 'server error'\n },\n options: args.opts\n };\n\n if(args.callback === undefined) {\n return new this.modem.Promise(function(resolve, reject) {\n self.modem.dial(optsf, function(err, data) {\n if (err) {\n return reject(err);\n }\n resolve(data);\n });\n });\n } else {\n this.modem.dial(optsf, function(err, data) {\n args.callback(err, data);\n });\n }\n};\n\nmodule.exports = Volume;\n","var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n","module.exports = class FixedFIFO {\n constructor (hwm) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')\n this.buffer = new Array(hwm)\n this.mask = hwm - 1\n this.top = 0\n this.btm = 0\n this.next = null\n }\n\n clear () {\n this.top = this.btm = 0\n this.next = null\n this.buffer.fill(undefined)\n }\n\n push (data) {\n if (this.buffer[this.top] !== undefined) return false\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n return true\n }\n\n shift () {\n const last = this.buffer[this.btm]\n if (last === undefined) return undefined\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n peek () {\n return this.buffer[this.btm]\n }\n\n isEmpty () {\n return this.buffer[this.btm] === undefined\n }\n}\n","const FixedFIFO = require('./fixed-size')\n\nmodule.exports = class FastFIFO {\n constructor (hwm) {\n this.hwm = hwm || 16\n this.head = new FixedFIFO(this.hwm)\n this.tail = this.head\n this.length = 0\n }\n\n clear () {\n this.head = this.tail\n this.head.clear()\n this.length = 0\n }\n\n push (val) {\n this.length++\n if (!this.head.push(val)) {\n const prev = this.head\n this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)\n this.head.push(val)\n }\n }\n\n shift () {\n if (this.length !== 0) this.length--\n const val = this.tail.shift()\n if (val === undefined && this.tail.next) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n return this.tail.shift()\n }\n\n return val\n }\n\n peek () {\n return this.tail.peek()\n }\n\n isEmpty () {\n return this.head.isEmpty()\n }\n}\n","module.exports = require('fs').constants || require('constants')\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","var path = require('path');\nvar fs = require('fs');\nvar _0777 = parseInt('0777', 8);\n\nmodule.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;\n\nfunction mkdirP (p, opts, f, made) {\n if (typeof opts === 'function') {\n f = opts;\n opts = {};\n }\n else if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n \n var mode = opts.mode;\n var xfs = opts.fs || fs;\n \n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made) made = null;\n \n var cb = f || function () {};\n p = path.resolve(p);\n \n xfs.mkdir(p, mode, function (er) {\n if (!er) {\n made = made || p;\n return cb(null, made);\n }\n switch (er.code) {\n case 'ENOENT':\n mkdirP(path.dirname(p), opts, function (er, made) {\n if (er) cb(er, made);\n else mkdirP(p, opts, cb, made);\n });\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n xfs.stat(p, function (er2, stat) {\n // if the stat fails, then that's super weird.\n // let the original error be the failure reason.\n if (er2 || !stat.isDirectory()) cb(er, made)\n else cb(null, made);\n });\n break;\n }\n });\n}\n\nmkdirP.sync = function sync (p, opts, made) {\n if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n \n var mode = opts.mode;\n var xfs = opts.fs || fs;\n \n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made) made = null;\n\n p = path.resolve(p);\n\n try {\n xfs.mkdirSync(p, mode);\n made = made || p;\n }\n catch (err0) {\n switch (err0.code) {\n case 'ENOENT' :\n made = sync(path.dirname(p), opts, made);\n sync(p, opts, made);\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n var stat;\n try {\n stat = xfs.statSync(p);\n }\n catch (err1) {\n throw err0;\n }\n if (!stat.isDirectory()) throw err0;\n break;\n }\n }\n\n return made;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","/**\n * Advanced Encryption Standard (AES) implementation.\n *\n * This implementation is based on the public domain library 'jscrypto' which\n * was written by:\n *\n * Emily Stark (estark@stanford.edu)\n * Mike Hamburg (mhamburg@stanford.edu)\n * Dan Boneh (dabo@cs.stanford.edu)\n *\n * Parts of this code are based on the OpenSSL implementation of AES:\n * http://www.openssl.org\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* AES API */\nmodule.exports = forge.aes = forge.aes || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new AES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the AES algorithm object.\n */\nforge.aes.Algorithm = function(name, mode) {\n if(!init) {\n initialize();\n }\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 16,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this AES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.aes.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = options.key;\n var tmp;\n\n /* Note: The key may be a string of bytes, an array of bytes, a byte\n buffer, or an array of 32-bit integers. If the key is in bytes, then\n it must be 16, 24, or 32 bytes in length. If it is in 32-bit\n integers, it must be 4, 6, or 8 integers long. */\n\n if(typeof key === 'string' &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key) &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key integer array into byte buffer\n tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // convert key byte buffer into 32-bit integer array\n if(!forge.util.isArray(key)) {\n tmp = key;\n key = [];\n\n // key lengths of 16, 24, 32 bytes allowed\n var len = tmp.length();\n if(len === 16 || len === 24 || len === 32) {\n len = len >>> 2;\n for(var i = 0; i < len; ++i) {\n key.push(tmp.getInt32());\n }\n }\n }\n\n // key must be an array of 32-bit integers by now\n if(!forge.util.isArray(key) ||\n !(key.length === 4 || key.length === 6 || key.length === 8)) {\n throw new Error('Invalid key parameter.');\n }\n\n // encryption operation is always used for these modes\n var mode = this.mode.name;\n var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);\n\n // do key expansion\n this._w = _expandKey(key, options.decrypt && !encryptOp);\n this._init = true;\n};\n\n/**\n * Expands a key. Typically only used for testing.\n *\n * @param key the symmetric key to expand, as an array of 32-bit words.\n * @param decrypt true to expand for decryption, false for encryption.\n *\n * @return the expanded key.\n */\nforge.aes._expandKey = function(key, decrypt) {\n if(!init) {\n initialize();\n }\n return _expandKey(key, decrypt);\n};\n\n/**\n * Updates a single block. Typically only used for testing.\n *\n * @param w the expanded key to use.\n * @param input an array of block-size 32-bit words.\n * @param output an array of block-size 32-bit words.\n * @param decrypt true to decrypt, false to encrypt.\n */\nforge.aes._updateBlock = _updateBlock;\n\n/** Register AES algorithms **/\n\nregisterAlgorithm('AES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('AES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('AES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('AES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('AES-CTR', forge.cipher.modes.ctr);\nregisterAlgorithm('AES-GCM', forge.cipher.modes.gcm);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.aes.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** AES implementation **/\n\nvar init = false; // not yet initialized\nvar Nb = 4; // number of words comprising the state (AES = 4)\nvar sbox; // non-linear substitution table used in key expansion\nvar isbox; // inversion of sbox\nvar rcon; // round constant word array\nvar mix; // mix-columns table\nvar imix; // inverse mix-columns table\n\n/**\n * Performs initialization, ie: precomputes tables to optimize for speed.\n *\n * One way to understand how AES works is to imagine that 'addition' and\n * 'multiplication' are interfaces that require certain mathematical\n * properties to hold true (ie: they are associative) but they might have\n * different implementations and produce different kinds of results ...\n * provided that their mathematical properties remain true. AES defines\n * its own methods of addition and multiplication but keeps some important\n * properties the same, ie: associativity and distributivity. The\n * explanation below tries to shed some light on how AES defines addition\n * and multiplication of bytes and 32-bit words in order to perform its\n * encryption and decryption algorithms.\n *\n * The basics:\n *\n * The AES algorithm views bytes as binary representations of polynomials\n * that have either 1 or 0 as the coefficients. It defines the addition\n * or subtraction of two bytes as the XOR operation. It also defines the\n * multiplication of two bytes as a finite field referred to as GF(2^8)\n * (Note: 'GF' means \"Galois Field\" which is a field that contains a finite\n * number of elements so GF(2^8) has 256 elements).\n *\n * This means that any two bytes can be represented as binary polynomials;\n * when they multiplied together and modularly reduced by an irreducible\n * polynomial of the 8th degree, the results are the field GF(2^8). The\n * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.\n * This multiplication is associative with 0x01 as the identity:\n *\n * (b * 0x01 = GF(b, 0x01) = b).\n *\n * The operation GF(b, 0x02) can be performed at the byte level by left\n * shifting b once and then XOR'ing it (to perform the modular reduction)\n * with 0x11b if b is >= 128. Repeated application of the multiplication\n * of 0x02 can be used to implement the multiplication of any two bytes.\n *\n * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can\n * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these\n * factors can each be multiplied by 0x57 and then added together. To do\n * the multiplication, values for 0x57 multiplied by each of these 3 factors\n * can be precomputed and stored in a table. To add them, the values from\n * the table are XOR'd together.\n *\n * AES also defines addition and multiplication of words, that is 4-byte\n * numbers represented as polynomials of 3 degrees where the coefficients\n * are the values of the bytes.\n *\n * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.\n *\n * Addition is performed by XOR'ing like powers of x. Multiplication\n * is performed in two steps, the first is an algebriac expansion as\n * you would do normally (where addition is XOR). But the result is\n * a polynomial larger than 3 degrees and thus it cannot fit in a word. So\n * next the result is modularly reduced by an AES-specific polynomial of\n * degree 4 which will always produce a polynomial of less than 4 degrees\n * such that it will fit in a word. In AES, this polynomial is x^4 + 1.\n *\n * The modular product of two polynomials 'a' and 'b' is thus:\n *\n * d(x) = d3x^3 + d2x^2 + d1x + d0\n * with\n * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)\n * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)\n * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)\n * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)\n *\n * As a matrix:\n *\n * [d0] = [a0 a3 a2 a1][b0]\n * [d1] [a1 a0 a3 a2][b1]\n * [d2] [a2 a1 a0 a3][b2]\n * [d3] [a3 a2 a1 a0][b3]\n *\n * Special polynomials defined by AES (0x02 == {02}):\n * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}\n * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.\n *\n * These polynomials are used in the MixColumns() and InverseMixColumns()\n * operations, respectively, to cause each element in the state to affect\n * the output (referred to as diffusing).\n *\n * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the\n * polynomial x3.\n *\n * The ShiftRows() method modifies the last 3 rows in the state (where\n * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.\n * The 1st byte in the second row is moved to the end of the row. The 1st\n * and 2nd bytes in the third row are moved to the end of the row. The 1st,\n * 2nd, and 3rd bytes are moved in the fourth row.\n *\n * More details on how AES arithmetic works:\n *\n * In the polynomial representation of binary numbers, XOR performs addition\n * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)\n * corresponds with the multiplication of polynomials modulo an irreducible\n * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply\n * polynomial 'a' with polynomial 'b' and then do a modular reduction by\n * an AES-specific irreducible polynomial of degree 8.\n *\n * A polynomial is irreducible if its only divisors are one and itself. For\n * the AES algorithm, this irreducible polynomial is:\n *\n * m(x) = x^8 + x^4 + x^3 + x + 1,\n *\n * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:\n * 100011011 = 283 = 0x11b.\n *\n * For example, GF(0x57, 0x83) = 0xc1 because\n *\n * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1\n * 0x85 = 131 = 10000101 = x^7 + x + 1\n *\n * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)\n * = x^13 + x^11 + x^9 + x^8 + x^7 +\n * x^7 + x^5 + x^3 + x^2 + x +\n * x^6 + x^4 + x^2 + x + 1\n * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y\n * y modulo (x^8 + x^4 + x^3 + x + 1)\n * = x^7 + x^6 + 1.\n *\n * The modular reduction by m(x) guarantees the result will be a binary\n * polynomial of less than degree 8, so that it can fit in a byte.\n *\n * The operation to multiply a binary polynomial b with x (the polynomial\n * x in binary representation is 00000010) is:\n *\n * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1\n *\n * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the\n * most significant bit is 0 in b) then the result is already reduced. If\n * it is 1, then we can reduce it by subtracting m(x) via an XOR.\n *\n * It follows that multiplication by x (00000010 or 0x02) can be implemented\n * by performing a left shift followed by a conditional bitwise XOR with\n * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by\n * higher powers of x can be implemented by repeated application of xtime().\n *\n * By adding intermediate results, multiplication by any constant can be\n * implemented. For instance:\n *\n * GF(0x57, 0x13) = 0xfe because:\n *\n * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)\n *\n * Note: We XOR with 0x11b instead of 0x1b because in javascript our\n * datatype for b can be larger than 1 byte, so a left shift will not\n * automatically eliminate bits that overflow a byte ... by XOR'ing the\n * overflow bit with 1 (the extra one from 0x11b) we zero it out.\n *\n * GF(0x57, 0x02) = xtime(0x57) = 0xae\n * GF(0x57, 0x04) = xtime(0xae) = 0x47\n * GF(0x57, 0x08) = xtime(0x47) = 0x8e\n * GF(0x57, 0x10) = xtime(0x8e) = 0x07\n *\n * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))\n *\n * And by the distributive property (since XOR is addition and GF() is\n * multiplication):\n *\n * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)\n * = 0x57 ^ 0xae ^ 0x07\n * = 0xfe.\n */\nfunction initialize() {\n init = true;\n\n /* Populate the Rcon table. These are the values given by\n [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)\n in the field of GF(2^8), where i starts at 1.\n\n rcon[0] = [0x00, 0x00, 0x00, 0x00]\n rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1\n rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2\n ...\n rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B\n rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36\n\n We only store the first byte because it is the only one used.\n */\n rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];\n\n // compute xtime table which maps i onto GF(i, 0x02)\n var xtime = new Array(256);\n for(var i = 0; i < 128; ++i) {\n xtime[i] = i << 1;\n xtime[i + 128] = (i + 128) << 1 ^ 0x11B;\n }\n\n // compute all other tables\n sbox = new Array(256);\n isbox = new Array(256);\n mix = new Array(4);\n imix = new Array(4);\n for(var i = 0; i < 4; ++i) {\n mix[i] = new Array(256);\n imix[i] = new Array(256);\n }\n var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;\n for(var i = 0; i < 256; ++i) {\n /* We need to generate the SubBytes() sbox and isbox tables so that\n we can perform byte substitutions. This requires us to traverse\n all of the elements in GF, find their multiplicative inverses,\n and apply to each the following affine transformation:\n\n bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^\n b(i + 7) mod 8 ^ ci\n for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the\n ith bit of a byte c with the value {63} or {01100011}.\n\n It is possible to traverse every possible value in a Galois field\n using what is referred to as a 'generator'. There are many\n generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully\n traverse GF we iterate 255 times, multiplying by our generator\n each time.\n\n On each iteration we can determine the multiplicative inverse for\n the current element.\n\n Suppose there is an element in GF 'e'. For a given generator 'g',\n e = g^x. The multiplicative inverse of e is g^(255 - x). It turns\n out that if use the inverse of a generator as another generator\n it will produce all of the corresponding multiplicative inverses\n at the same time. For this reason, we choose 5 as our inverse\n generator because it only requires 2 multiplies and 1 add and its\n inverse, 82, requires relatively few operations as well.\n\n In order to apply the affine transformation, the multiplicative\n inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a\n bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and\n 'x'. Then 's' is left shifted and the high bit of 's' is made the\n low bit. The resulting value is stored in 's'. Then 'x' is XOR'd\n with 's' and stored in 'x'. On each subsequent iteration the same\n operation is performed. When 4 iterations are complete, 'x' is\n XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.\n For example:\n\n s = 01000001\n x = 01000001\n\n iteration 1: s = 10000010, x ^= s\n iteration 2: s = 00000101, x ^= s\n iteration 3: s = 00001010, x ^= s\n iteration 4: s = 00010100, x ^= s\n x ^= 0x63\n\n This can be done with a loop where s = (s << 1) | (s >> 7). However,\n it can also be done by using a single 16-bit (in this case 32-bit)\n number 'sx'. Since XOR is an associative operation, we can set 'sx'\n to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.\n The most significant bits will flow into the high 8 bit positions\n and be correctly XOR'd with one another. All that remains will be\n to cycle the high 8 bits by XOR'ing them all with the lower 8 bits\n afterwards.\n\n At the same time we're populating sbox and isbox we can precompute\n the multiplication we'll need to do to do MixColumns() later.\n */\n\n // apply affine transformation\n sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);\n sx = (sx >> 8) ^ (sx & 255) ^ 0x63;\n\n // update tables\n sbox[e] = sx;\n isbox[sx] = e;\n\n /* Mixing columns is done using matrix multiplication. The columns\n that are to be mixed are each a single word in the current state.\n The state has Nb columns (4 columns). Therefore each column is a\n 4 byte word. So to mix the columns in a single column 'c' where\n its rows are r0, r1, r2, and r3, we use the following matrix\n multiplication:\n\n [2 3 1 1]*[r0,c]=[r'0,c]\n [1 2 3 1] [r1,c] [r'1,c]\n [1 1 2 3] [r2,c] [r'2,c]\n [3 1 1 2] [r3,c] [r'3,c]\n\n r0, r1, r2, and r3 are each 1 byte of one of the words in the\n state (a column). To do matrix multiplication for each mixed\n column c' we multiply the corresponding row from the left matrix\n with the corresponding column from the right matrix. In total, we\n get 4 equations:\n\n r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c\n r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c\n r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c\n r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c\n\n As usual, the multiplication is as previously defined and the\n addition is XOR. In order to optimize mixing columns we can store\n the multiplication results in tables. If you think of the whole\n column as a word (it might help to visualize by mentally rotating\n the equations above by counterclockwise 90 degrees) then you can\n see that it would be useful to map the multiplications performed on\n each byte (r0, r1, r2, r3) onto a word as well. For instance, we\n could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the\n highest 8 bits and 3*r0 in the lowest 8 bits (with the other two\n respectively in the middle). This means that a table can be\n constructed that uses r0 as an index to the word. We can do the\n same with r1, r2, and r3, creating a total of 4 tables.\n\n To construct a full c', we can just look up each byte of c in\n their respective tables and XOR the results together.\n\n Also, to build each table we only have to calculate the word\n for 2,1,1,3 for every byte ... which we can do on each iteration\n of this loop since we will iterate over every byte. After we have\n calculated 2,1,1,3 we can get the results for the other tables\n by cycling the byte at the end to the beginning. For instance\n we can take the result of table 2,1,1,3 and produce table 3,2,1,1\n by moving the right most byte to the left most position just like\n how you can imagine the 3 moved out of 2,1,1,3 and to the front\n to produce 3,2,1,1.\n\n There is another optimization in that the same multiples of\n the current element we need in order to advance our generator\n to the next iteration can be reused in performing the 2,1,1,3\n calculation. We also calculate the inverse mix column tables,\n with e,9,d,b being the inverse of 2,1,1,3.\n\n When we're done, and we need to actually mix columns, the first\n byte of each state word should be put through mix[0] (2,1,1,3),\n the second through mix[1] (3,2,1,1) and so forth. Then they should\n be XOR'd together to produce the fully mixed column.\n */\n\n // calculate mix and imix table values\n sx2 = xtime[sx];\n e2 = xtime[e];\n e4 = xtime[e2];\n e8 = xtime[e4];\n me =\n (sx2 << 24) ^ // 2\n (sx << 16) ^ // 1\n (sx << 8) ^ // 1\n (sx ^ sx2); // 3\n ime =\n (e2 ^ e4 ^ e8) << 24 ^ // E (14)\n (e ^ e8) << 16 ^ // 9\n (e ^ e4 ^ e8) << 8 ^ // D (13)\n (e ^ e2 ^ e8); // B (11)\n // produce each of the mix tables by rotating the 2,1,1,3 value\n for(var n = 0; n < 4; ++n) {\n mix[n][e] = me;\n imix[n][sx] = ime;\n // cycle the right most byte to the left most position\n // ie: 2,1,1,3 becomes 3,2,1,1\n me = me << 24 | me >>> 8;\n ime = ime << 24 | ime >>> 8;\n }\n\n // get next element and inverse\n if(e === 0) {\n // 1 is the inverse of 1\n e = ei = 1;\n } else {\n // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)\n // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)\n e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];\n ei ^= xtime[xtime[ei]];\n }\n }\n}\n\n/**\n * Generates a key schedule using the AES key expansion algorithm.\n *\n * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion\n * routine to generate a key schedule. The Key Expansion generates a total\n * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,\n * and each of the Nr rounds requires Nb words of key data. The resulting\n * key schedule consists of a linear array of 4-byte words, denoted [wi ],\n * with i in the range 0 <= i < Nb(Nr + 1).\n *\n * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)\n * AES-128 (Nb=4, Nk=4, Nr=10)\n * AES-192 (Nb=4, Nk=6, Nr=12)\n * AES-256 (Nb=4, Nk=8, Nr=14)\n * Note: Nr=Nk+6.\n *\n * Nb is the number of columns (32-bit words) comprising the State (or\n * number of bytes in a block). For AES, Nb=4.\n *\n * @param key the key to schedule (as an array of 32-bit words).\n * @param decrypt true to modify the key schedule to decrypt, false not to.\n *\n * @return the generated key schedule.\n */\nfunction _expandKey(key, decrypt) {\n // copy the key's words to initialize the key schedule\n var w = key.slice(0);\n\n /* RotWord() will rotate a word, moving the first byte to the last\n byte's position (shifting the other bytes left).\n\n We will be getting the value of Rcon at i / Nk. 'i' will iterate\n from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in\n a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from\n 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will\n increase by 1. We use a counter iNk to keep track of this.\n */\n\n // go through the rounds expanding the key\n var temp, iNk = 1;\n var Nk = w.length;\n var Nr1 = Nk + 6 + 1;\n var end = Nb * Nr1;\n for(var i = Nk; i < end; ++i) {\n temp = w[i - 1];\n if(i % Nk === 0) {\n // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]\n temp =\n sbox[temp >>> 16 & 255] << 24 ^\n sbox[temp >>> 8 & 255] << 16 ^\n sbox[temp & 255] << 8 ^\n sbox[temp >>> 24] ^ (rcon[iNk] << 24);\n iNk++;\n } else if(Nk > 6 && (i % Nk === 4)) {\n // temp = SubWord(temp)\n temp =\n sbox[temp >>> 24] << 24 ^\n sbox[temp >>> 16 & 255] << 16 ^\n sbox[temp >>> 8 & 255] << 8 ^\n sbox[temp & 255];\n }\n w[i] = w[i - Nk] ^ temp;\n }\n\n /* When we are updating a cipher block we always use the code path for\n encryption whether we are decrypting or not (to shorten code and\n simplify the generation of look up tables). However, because there\n are differences in the decryption algorithm, other than just swapping\n in different look up tables, we must transform our key schedule to\n account for these changes:\n\n 1. The decryption algorithm gets its key rounds in reverse order.\n 2. The decryption algorithm adds the round key before mixing columns\n instead of afterwards.\n\n We don't need to modify our key schedule to handle the first case,\n we can just traverse the key schedule in reverse order when decrypting.\n\n The second case requires a little work.\n\n The tables we built for performing rounds will take an input and then\n perform SubBytes() and MixColumns() or, for the decrypt version,\n InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires\n us to AddRoundKey() before InvMixColumns(). This means we'll need to\n apply some transformations to the round key to inverse-mix its columns\n so they'll be correct for moving AddRoundKey() to after the state has\n had its columns inverse-mixed.\n\n To inverse-mix the columns of the state when we're decrypting we use a\n lookup table that will apply InvSubBytes() and InvMixColumns() at the\n same time. However, the round key's bytes are not inverse-substituted\n in the decryption algorithm. To get around this problem, we can first\n substitute the bytes in the round key so that when we apply the\n transformation via the InvSubBytes()+InvMixColumns() table, it will\n undo our substitution leaving us with the original value that we\n want -- and then inverse-mix that value.\n\n This change will correctly alter our key schedule so that we can XOR\n each round key with our already transformed decryption state. This\n allows us to use the same code path as the encryption algorithm.\n\n We make one more change to the decryption key. Since the decryption\n algorithm runs in reverse from the encryption algorithm, we reverse\n the order of the round keys to avoid having to iterate over the key\n schedule backwards when running the encryption algorithm later in\n decryption mode. In addition to reversing the order of the round keys,\n we also swap each round key's 2nd and 4th rows. See the comments\n section where rounds are performed for more details about why this is\n done. These changes are done inline with the other substitution\n described above.\n */\n if(decrypt) {\n var tmp;\n var m0 = imix[0];\n var m1 = imix[1];\n var m2 = imix[2];\n var m3 = imix[3];\n var wnew = w.slice(0);\n end = w.length;\n for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {\n // do not sub the first or last round key (round keys are Nb\n // words) as no column mixing is performed before they are added,\n // but do change the key order\n if(i === 0 || i === (end - Nb)) {\n wnew[i] = w[wi];\n wnew[i + 1] = w[wi + 3];\n wnew[i + 2] = w[wi + 2];\n wnew[i + 3] = w[wi + 1];\n } else {\n // substitute each round key byte because the inverse-mix\n // table will inverse-substitute it (effectively cancel the\n // substitution because round key bytes aren't sub'd in\n // decryption mode) and swap indexes 3 and 1\n for(var n = 0; n < Nb; ++n) {\n tmp = w[wi + n];\n wnew[i + (3&-n)] =\n m0[sbox[tmp >>> 24]] ^\n m1[sbox[tmp >>> 16 & 255]] ^\n m2[sbox[tmp >>> 8 & 255]] ^\n m3[sbox[tmp & 255]];\n }\n }\n }\n w = wnew;\n }\n\n return w;\n}\n\n/**\n * Updates a single block (16 bytes) using AES. The update will either\n * encrypt or decrypt the block.\n *\n * @param w the key schedule.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(w, input, output, decrypt) {\n /*\n Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[0, Nb-1])\n for round = 1 step 1 to Nr-1\n SubBytes(state)\n ShiftRows(state)\n MixColumns(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n end for\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n out = state\n end\n\n InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n for round = Nr-1 step -1 downto 1\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n InvMixColumns(state)\n end for\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n out = state\n end\n */\n\n // Encrypt: AddRoundKey(state, w[0, Nb-1])\n // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n var Nr = w.length / 4 - 1;\n var m0, m1, m2, m3, sub;\n if(decrypt) {\n m0 = imix[0];\n m1 = imix[1];\n m2 = imix[2];\n m3 = imix[3];\n sub = isbox;\n } else {\n m0 = mix[0];\n m1 = mix[1];\n m2 = mix[2];\n m3 = mix[3];\n sub = sbox;\n }\n var a, b, c, d, a2, b2, c2;\n a = input[0] ^ w[0];\n b = input[decrypt ? 3 : 1] ^ w[1];\n c = input[2] ^ w[2];\n d = input[decrypt ? 1 : 3] ^ w[3];\n var i = 3;\n\n /* In order to share code we follow the encryption algorithm when both\n encrypting and decrypting. To account for the changes required in the\n decryption algorithm, we use different lookup tables when decrypting\n and use a modified key schedule to account for the difference in the\n order of transformations applied when performing rounds. We also get\n key rounds in reverse order (relative to encryption). */\n for(var round = 1; round < Nr; ++round) {\n /* As described above, we'll be using table lookups to perform the\n column mixing. Each column is stored as a word in the state (the\n array 'input' has one column as a word at each index). In order to\n mix a column, we perform these transformations on each row in c,\n which is 1 byte in each word. The new column for c0 is c'0:\n\n m0 m1 m2 m3\n r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0\n r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0\n r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0\n r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0\n\n So using mix tables where c0 is a word with r0 being its upper\n 8 bits and r3 being its lower 8 bits:\n\n m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]\n ...\n m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]\n\n Therefore to mix the columns in each word in the state we\n do the following (& 255 omitted for brevity):\n c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n\n However, before mixing, the algorithm requires us to perform\n ShiftRows(). The ShiftRows() transformation cyclically shifts the\n last 3 rows of the state over different offsets. The first row\n (r = 0) is not shifted.\n\n s'_r,c = s_r,(c + shift(r, Nb) mod Nb\n for 0 < r < 4 and 0 <= c < Nb and\n shift(1, 4) = 1\n shift(2, 4) = 2\n shift(3, 4) = 3.\n\n This causes the first byte in r = 1 to be moved to the end of\n the row, the first 2 bytes in r = 2 to be moved to the end of\n the row, the first 3 bytes in r = 3 to be moved to the end of\n the row:\n\n r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]\n r2: [c0 c1 c2 c3] [c2 c3 c0 c1]\n r3: [c0 c1 c2 c3] [c3 c0 c1 c2]\n\n We can make these substitutions inline with our column mixing to\n generate an updated set of equations to produce each word in the\n state (note the columns have changed positions):\n\n c0 c1 c2 c3 => c0 c1 c2 c3\n c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)\n c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)\n c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)\n\n Therefore:\n\n c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3\n c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3\n\n c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0\n c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0\n\n ... and so forth for c'2 and c'3. The important distinction is\n that the columns are cycling, with c0 being used with the m0\n map when calculating c0, but c1 being used with the m0 map when\n calculating c1 ... and so forth.\n\n When performing the inverse we transform the mirror image and\n skip the bottom row, instead of the top one, and move upwards:\n\n c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption\n c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)\n c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption\n c3 c2 c1 c0 c3 c2 c1 c0\n\n If you compare the resulting matrices for ShiftRows()+MixColumns()\n and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are\n different (in encrypt mode vs. decrypt mode). So in order to use\n the same code to handle both encryption and decryption, we will\n need to do some mapping.\n\n If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be\n a row number in the state, then the resulting matrix in encryption\n mode for applying the above transformations would be:\n\n r1: a b c d\n r2: b c d a\n r3: c d a b\n r4: d a b c\n\n If we did the same in decryption mode we would get:\n\n r1: a d c b\n r2: b a d c\n r3: c b a d\n r4: d c b a\n\n If instead we swap d and b (set b=c3 and d=c1), then we get:\n\n r1: a b c d\n r2: d a b c\n r3: c d a b\n r4: b c d a\n\n Now the 1st and 3rd rows are the same as the encryption matrix. All\n we need to do then to make the mapping exactly the same is to swap\n the 2nd and 4th rows when in decryption mode. To do this without\n having to do it on each iteration, we swapped the 2nd and 4th rows\n in the decryption key schedule. We also have to do the swap above\n when we first pull in the input and when we set the final output. */\n a2 =\n m0[a >>> 24] ^\n m1[b >>> 16 & 255] ^\n m2[c >>> 8 & 255] ^\n m3[d & 255] ^ w[++i];\n b2 =\n m0[b >>> 24] ^\n m1[c >>> 16 & 255] ^\n m2[d >>> 8 & 255] ^\n m3[a & 255] ^ w[++i];\n c2 =\n m0[c >>> 24] ^\n m1[d >>> 16 & 255] ^\n m2[a >>> 8 & 255] ^\n m3[b & 255] ^ w[++i];\n d =\n m0[d >>> 24] ^\n m1[a >>> 16 & 255] ^\n m2[b >>> 8 & 255] ^\n m3[c & 255] ^ w[++i];\n a = a2;\n b = b2;\n c = c2;\n }\n\n /*\n Encrypt:\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n\n Decrypt:\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n */\n // Note: rows are shifted inline\n output[0] =\n (sub[a >>> 24] << 24) ^\n (sub[b >>> 16 & 255] << 16) ^\n (sub[c >>> 8 & 255] << 8) ^\n (sub[d & 255]) ^ w[++i];\n output[decrypt ? 3 : 1] =\n (sub[b >>> 24] << 24) ^\n (sub[c >>> 16 & 255] << 16) ^\n (sub[d >>> 8 & 255] << 8) ^\n (sub[a & 255]) ^ w[++i];\n output[2] =\n (sub[c >>> 24] << 24) ^\n (sub[d >>> 16 & 255] << 16) ^\n (sub[a >>> 8 & 255] << 8) ^\n (sub[b & 255]) ^ w[++i];\n output[decrypt ? 1 : 3] =\n (sub[d >>> 24] << 24) ^\n (sub[a >>> 16 & 255] << 16) ^\n (sub[b >>> 8 & 255] << 8) ^\n (sub[c & 255]) ^ w[++i];\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('AES-', key);\n * forge.cipher.createDecipher('AES-', key);\n *\n * Creates a deprecated AES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key and iv may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param options the options to use.\n * key the symmetric key to use.\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'AES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * A Javascript implementation of AES Cipher Suites for TLS.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2015 Digital Bazaar, Inc.\n *\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./tls');\n\nvar tls = module.exports = forge.tls;\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = {\n id: [0x00, 0x2f],\n name: 'TLS_RSA_WITH_AES_128_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 16;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\ntls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = {\n id: [0x00, 0x35],\n name: 'TLS_RSA_WITH_AES_256_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 32;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\n\nfunction initConnectionState(state, c, sp) {\n var client = (c.entity === forge.tls.ConnectionEnd.client);\n\n // cipher setup\n state.read.cipherState = {\n init: false,\n cipher: forge.cipher.createDecipher('AES-CBC', client ?\n sp.keys.server_write_key : sp.keys.client_write_key),\n iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV\n };\n state.write.cipherState = {\n init: false,\n cipher: forge.cipher.createCipher('AES-CBC', client ?\n sp.keys.client_write_key : sp.keys.server_write_key),\n iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV\n };\n state.read.cipherFunction = decrypt_aes_cbc_sha1;\n state.write.cipherFunction = encrypt_aes_cbc_sha1;\n\n // MAC setup\n state.read.macLength = state.write.macLength = sp.mac_length;\n state.read.macFunction = state.write.macFunction = tls.hmac_sha1;\n}\n\n/**\n * Encrypts the TLSCompressed record into a TLSCipherText record using AES\n * in CBC mode.\n *\n * @param record the TLSCompressed record to encrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n // append MAC to fragment, update sequence number\n var mac = s.macFunction(s.macKey, s.sequenceNumber, record);\n record.fragment.putBytes(mac);\n s.updateSequenceNumber();\n\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use the pre-generated IV when initializing for TLS 1.0, otherwise use\n // the residue from the previous encryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n iv = forge.random.getBytesSync(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // TLS 1.1+ write IV into output\n if(record.version.minor >= tls.Versions.TLS_1_1.minor) {\n cipher.output.putBytes(iv);\n }\n\n // do encryption (default padding is appropriate)\n cipher.update(record.fragment);\n if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {\n // set record fragment to encrypted output\n record.fragment = cipher.output;\n record.length = record.fragment.length();\n rval = true;\n }\n\n return rval;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in encrypt mode.\n *\n * @param blockSize the block size.\n * @param input the input buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {\n /* The encrypted data length (TLSCiphertext.length) is one more than the sum\n of SecurityParameters.block_length, TLSCompressed.length,\n SecurityParameters.mac_length, and padding_length.\n\n The padding may be any length up to 255 bytes long, as long as it results in\n the TLSCiphertext.length being an integral multiple of the block length.\n Lengths longer than necessary might be desirable to frustrate attacks on a\n protocol based on analysis of the lengths of exchanged messages. Each uint8\n in the padding data vector must be filled with the padding length value.\n\n The padding length should be such that the total size of the\n GenericBlockCipher structure is a multiple of the cipher's block length.\n Legal values range from zero to 255, inclusive. This length specifies the\n length of the padding field exclusive of the padding_length field itself.\n\n This is slightly different from PKCS#7 because the padding value is 1\n less than the actual number of padding bytes if you include the\n padding_length uint8 itself as a padding byte. */\n if(!decrypt) {\n // get the number of padding bytes required to reach the blockSize and\n // subtract 1 for the padding value (to make room for the padding_length\n // uint8)\n var padding = blockSize - (input.length() % blockSize);\n input.fillWithByte(padding - 1, padding);\n }\n return true;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in decrypt mode.\n *\n * @param blockSize the block size.\n * @param output the output buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {\n var rval = true;\n if(decrypt) {\n /* The last byte in the output specifies the number of padding bytes not\n including itself. Each of the padding bytes has the same value as that\n last byte (known as the padding_length). Here we check all padding\n bytes to ensure they have the value of padding_length even if one of\n them is bad in order to ward-off timing attacks. */\n var len = output.length();\n var paddingLength = output.last();\n for(var i = len - 1 - paddingLength; i < len - 1; ++i) {\n rval = rval && (output.at(i) == paddingLength);\n }\n if(rval) {\n // trim off padding bytes and last padding length byte\n output.truncate(paddingLength + 1);\n }\n }\n return rval;\n}\n\n/**\n * Decrypts a TLSCipherText record into a TLSCompressed record using\n * AES in CBC mode.\n *\n * @param record the TLSCipherText record to decrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use pre-generated IV when initializing for TLS 1.0, otherwise use the\n // residue from the previous decryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n // that is appended to the record fragment\n iv = record.fragment.getBytes(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // do decryption\n cipher.update(record.fragment);\n rval = cipher.finish(decrypt_aes_cbc_sha1_padding);\n\n // even if decryption fails, keep going to minimize timing attacks\n\n // decrypted data:\n // first (len - 20) bytes = application data\n // last 20 bytes = MAC\n var macLen = s.macLength;\n\n // create a random MAC to check against should the mac length check fail\n // Note: do this regardless of the failure to keep timing consistent\n var mac = forge.random.getBytesSync(macLen);\n\n // get fragment and mac\n var len = cipher.output.length();\n if(len >= macLen) {\n record.fragment = cipher.output.getBytes(len - macLen);\n mac = cipher.output.getBytes(macLen);\n } else {\n // bad data, but get bytes anyway to try to keep timing consistent\n record.fragment = cipher.output.getBytes();\n }\n record.fragment = forge.util.createBuffer(record.fragment);\n record.length = record.fragment.length();\n\n // see if data integrity checks out, update sequence number\n var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record);\n s.updateSequenceNumber();\n rval = compareMacs(s.macKey, mac, mac2) && rval;\n return rval;\n}\n\n/**\n * Safely compare two MACs. This function will compare two MACs in a way\n * that protects against timing attacks.\n *\n * TODO: Expose elsewhere as a utility API.\n *\n * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/\n *\n * @param key the MAC key to use.\n * @param mac1 as a binary-encoded string of bytes.\n * @param mac2 as a binary-encoded string of bytes.\n *\n * @return true if the MACs are the same, false if not.\n */\nfunction compareMacs(key, mac1, mac2) {\n var hmac = forge.hmac.create();\n\n hmac.start('SHA1', key);\n hmac.update(mac1);\n mac1 = hmac.digest().getBytes();\n\n hmac.start(null, null);\n hmac.update(mac2);\n mac2 = hmac.digest().getBytes();\n\n return mac1 === mac2;\n}\n","/**\n * Copyright (c) 2019 Digital Bazaar, Inc.\n */\n\nvar forge = require('./forge');\nrequire('./asn1');\nvar asn1 = forge.asn1;\n\nexports.privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\nexports.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n },\n // capture group for ed25519PublicKey\n {\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n composed: true,\n captureBitStringValue: 'ed25519PublicKey'\n }\n // FIXME: this is capture group for rsaPublicKey, use it in this API or\n // discard?\n /* {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n } */\n ]\n};\n","/**\n * Javascript implementation of Abstract Syntax Notation Number One.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n *\n * An API for storing data using the Abstract Syntax Notation Number One\n * format using DER (Distinguished Encoding Rules) encoding. This encoding is\n * commonly used to store data for PKI, i.e. X.509 Certificates, and this\n * implementation exists for that purpose.\n *\n * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract\n * syntax of information without restricting the way the information is encoded\n * for transmission. It provides a standard that allows for open systems\n * communication. ASN.1 defines the syntax of information data and a number of\n * simple data types as well as a notation for describing them and specifying\n * values for them.\n *\n * The RSA algorithm creates public and private keys that are often stored in\n * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This\n * class provides the most basic functionality required to store and load DSA\n * keys that are encoded according to ASN.1.\n *\n * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)\n * and DER (Distinguished Encoding Rules). DER is just a subset of BER that\n * has stricter requirements for how data must be encoded.\n *\n * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)\n * and a byte array for the value of this ASN1 structure which may be data or a\n * list of ASN.1 structures.\n *\n * Each ASN.1 structure using BER is (Tag-Length-Value):\n *\n * | byte 0 | bytes X | bytes Y |\n * |--------|---------|----------\n * | tag | length | value |\n *\n * ASN.1 allows for tags to be of \"High-tag-number form\" which allows a tag to\n * be two or more octets, but that is not supported by this class. A tag is\n * only 1 byte. Bits 1-5 give the tag number (ie the data type within a\n * particular 'class'), 6 indicates whether or not the ASN.1 value is\n * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If\n * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,\n * then the class is APPLICATION. If only bit 8 is set, then the class is\n * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.\n * The tag numbers for the data types for the class UNIVERSAL are listed below:\n *\n * UNIVERSAL 0 Reserved for use by the encoding rules\n * UNIVERSAL 1 Boolean type\n * UNIVERSAL 2 Integer type\n * UNIVERSAL 3 Bitstring type\n * UNIVERSAL 4 Octetstring type\n * UNIVERSAL 5 Null type\n * UNIVERSAL 6 Object identifier type\n * UNIVERSAL 7 Object descriptor type\n * UNIVERSAL 8 External type and Instance-of type\n * UNIVERSAL 9 Real type\n * UNIVERSAL 10 Enumerated type\n * UNIVERSAL 11 Embedded-pdv type\n * UNIVERSAL 12 UTF8String type\n * UNIVERSAL 13 Relative object identifier type\n * UNIVERSAL 14-15 Reserved for future editions\n * UNIVERSAL 16 Sequence and Sequence-of types\n * UNIVERSAL 17 Set and Set-of types\n * UNIVERSAL 18-22, 25-30 Character string types\n * UNIVERSAL 23-24 Time types\n *\n * The length of an ASN.1 structure is specified after the tag identifier.\n * There is a definite form and an indefinite form. The indefinite form may\n * be used if the encoding is constructed and not all immediately available.\n * The indefinite form is encoded using a length byte with only the 8th bit\n * set. The end of the constructed object is marked using end-of-contents\n * octets (two zero bytes).\n *\n * The definite form looks like this:\n *\n * The length may take up 1 or more bytes, it depends on the length of the\n * value of the ASN.1 structure. DER encoding requires that if the ASN.1\n * structure has a value that has a length greater than 127, more than 1 byte\n * will be used to store its length, otherwise just one byte will be used.\n * This is strict.\n *\n * In the case that the length of the ASN.1 value is less than 127, 1 octet\n * (byte) is used to store the \"short form\" length. The 8th bit has a value of\n * 0 indicating the length is \"short form\" and not \"long form\" and bits 7-1\n * give the length of the data. (The 8th bit is the left-most, most significant\n * bit: also known as big endian or network format).\n *\n * In the case that the length of the ASN.1 value is greater than 127, 2 to\n * 127 octets (bytes) are used to store the \"long form\" length. The first\n * byte's 8th bit is set to 1 to indicate the length is \"long form.\" Bits 7-1\n * give the number of additional octets. All following octets are in base 256\n * with the most significant digit first (typical big-endian binary unsigned\n * integer storage). So, for instance, if the length of a value was 257, the\n * first byte would be set to:\n *\n * 10000010 = 130 = 0x82.\n *\n * This indicates there are 2 octets (base 256) for the length. The second and\n * third bytes (the octets just mentioned) would store the length in base 256:\n *\n * octet 2: 00000001 = 1 * 256^1 = 256\n * octet 3: 00000001 = 1 * 256^0 = 1\n * total = 257\n *\n * The algorithm for converting a js integer value of 257 to base-256 is:\n *\n * var value = 257;\n * var bytes = [];\n * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first\n * bytes[1] = value & 0xFF; // least significant byte last\n *\n * On the ASN.1 UNIVERSAL Object Identifier (OID) type:\n *\n * An OID can be written like: \"value1.value2.value3...valueN\"\n *\n * The DER encoding rules:\n *\n * The first byte has the value 40 * value1 + value2.\n * The following bytes, if any, encode the remaining values. Each value is\n * encoded in base 128, most significant digit first (big endian), with as\n * few digits as possible, and the most significant bit of each byte set\n * to 1 except the last in each value's encoding. For example: Given the\n * OID \"1.2.840.113549\", its DER encoding is (remember each byte except the\n * last one in each encoding is OR'd with 0x80):\n *\n * byte 1: 40 * 1 + 2 = 42 = 0x2A.\n * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648\n * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D\n *\n * The final value is: 0x2A864886F70D.\n * The full OID (including ASN.1 tag and length of 6 bytes) is:\n * 0x06062A864886F70D\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./oids');\n\n/* ASN.1 API */\nvar asn1 = module.exports = forge.asn1 = forge.asn1 || {};\n\n/**\n * ASN.1 classes.\n */\nasn1.Class = {\n UNIVERSAL: 0x00,\n APPLICATION: 0x40,\n CONTEXT_SPECIFIC: 0x80,\n PRIVATE: 0xC0\n};\n\n/**\n * ASN.1 types. Not all types are supported by this implementation, only\n * those necessary to implement a simple PKI are implemented.\n */\nasn1.Type = {\n NONE: 0,\n BOOLEAN: 1,\n INTEGER: 2,\n BITSTRING: 3,\n OCTETSTRING: 4,\n NULL: 5,\n OID: 6,\n ODESC: 7,\n EXTERNAL: 8,\n REAL: 9,\n ENUMERATED: 10,\n EMBEDDED: 11,\n UTF8: 12,\n ROID: 13,\n SEQUENCE: 16,\n SET: 17,\n PRINTABLESTRING: 19,\n IA5STRING: 22,\n UTCTIME: 23,\n GENERALIZEDTIME: 24,\n BMPSTRING: 30\n};\n\n/**\n * Creates a new asn1 object.\n *\n * @param tagClass the tag class for the object.\n * @param type the data type (tag number) for the object.\n * @param constructed true if the asn1 object is in constructed form.\n * @param value the value for the object, if it is not constructed.\n * @param [options] the options to use:\n * [bitStringContents] the plain BIT STRING content including padding\n * byte.\n *\n * @return the asn1 object.\n */\nasn1.create = function(tagClass, type, constructed, value, options) {\n /* An asn1 object has a tagClass, a type, a constructed flag, and a\n value. The value's type depends on the constructed flag. If\n constructed, it will contain a list of other asn1 objects. If not,\n it will contain the ASN.1 value as an array of bytes formatted\n according to the ASN.1 data type. */\n\n // remove undefined values\n if(forge.util.isArray(value)) {\n var tmp = [];\n for(var i = 0; i < value.length; ++i) {\n if(value[i] !== undefined) {\n tmp.push(value[i]);\n }\n }\n value = tmp;\n }\n\n var obj = {\n tagClass: tagClass,\n type: type,\n constructed: constructed,\n composed: constructed || forge.util.isArray(value),\n value: value\n };\n if(options && 'bitStringContents' in options) {\n // TODO: copy byte buffer if it's a buffer not a string\n obj.bitStringContents = options.bitStringContents;\n // TODO: add readonly flag to avoid this overhead\n // save copy to detect changes\n obj.original = asn1.copy(obj);\n }\n return obj;\n};\n\n/**\n * Copies an asn1 object.\n *\n * @param obj the asn1 object.\n * @param [options] copy options:\n * [excludeBitStringContents] true to not copy bitStringContents\n *\n * @return the a copy of the asn1 object.\n */\nasn1.copy = function(obj, options) {\n var copy;\n\n if(forge.util.isArray(obj)) {\n copy = [];\n for(var i = 0; i < obj.length; ++i) {\n copy.push(asn1.copy(obj[i], options));\n }\n return copy;\n }\n\n if(typeof obj === 'string') {\n // TODO: copy byte buffer if it's a buffer not a string\n return obj;\n }\n\n copy = {\n tagClass: obj.tagClass,\n type: obj.type,\n constructed: obj.constructed,\n composed: obj.composed,\n value: asn1.copy(obj.value, options)\n };\n if(options && !options.excludeBitStringContents) {\n // TODO: copy byte buffer if it's a buffer not a string\n copy.bitStringContents = obj.bitStringContents;\n }\n return copy;\n};\n\n/**\n * Compares asn1 objects for equality.\n *\n * Note this function does not run in constant time.\n *\n * @param obj1 the first asn1 object.\n * @param obj2 the second asn1 object.\n * @param [options] compare options:\n * [includeBitStringContents] true to compare bitStringContents\n *\n * @return true if the asn1 objects are equal.\n */\nasn1.equals = function(obj1, obj2, options) {\n if(forge.util.isArray(obj1)) {\n if(!forge.util.isArray(obj2)) {\n return false;\n }\n if(obj1.length !== obj2.length) {\n return false;\n }\n for(var i = 0; i < obj1.length; ++i) {\n if(!asn1.equals(obj1[i], obj2[i])) {\n return false;\n }\n }\n return true;\n }\n\n if(typeof obj1 !== typeof obj2) {\n return false;\n }\n\n if(typeof obj1 === 'string') {\n return obj1 === obj2;\n }\n\n var equal = obj1.tagClass === obj2.tagClass &&\n obj1.type === obj2.type &&\n obj1.constructed === obj2.constructed &&\n obj1.composed === obj2.composed &&\n asn1.equals(obj1.value, obj2.value);\n if(options && options.includeBitStringContents) {\n equal = equal && (obj1.bitStringContents === obj2.bitStringContents);\n }\n\n return equal;\n};\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param b the BER-encoded ASN.1 byte buffer, starting with the first\n * length byte.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nasn1.getBerValueLength = function(b) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n var b2 = b.getByte();\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n length = b.getInt((b2 & 0x7F) << 3);\n }\n return length;\n};\n\n/**\n * Check if the byte buffer has enough bytes. Throws an Error if not.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n * @param n the number of bytes the buffer must have.\n */\nfunction _checkBufferLength(bytes, remaining, n) {\n if(n > remaining) {\n var error = new Error('Too few bytes to parse DER.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = n;\n throw error;\n }\n}\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nvar _getValueLength = function(bytes, remaining) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n // fromDer already checked that this byte exists\n var b2 = bytes.getByte();\n remaining--;\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n var longFormBytes = b2 & 0x7F;\n _checkBufferLength(bytes, remaining, longFormBytes);\n length = bytes.getInt(longFormBytes << 3);\n }\n // FIXME: this will only happen for 32 bit getInt with high bit set\n if(length < 0) {\n throw new Error('Negative length: ' + length);\n }\n return length;\n};\n\n/**\n * Parses an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * @param [options] object with options or boolean strict flag\n * [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * [parseAllBytes] true to ensure all bytes are parsed\n * (default: true)\n * [decodeBitStrings] true to attempt to decode the content of\n * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that\n * without schema support to understand the data context this can\n * erroneously decode values that happen to be valid ASN.1. This\n * flag will be deprecated or removed as soon as schema support is\n * available. (default: true)\n *\n * @throws Will throw an error for various malformed input conditions.\n *\n * @return the parsed asn1 object.\n */\nasn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('parseAllBytes' in options)) {\n options.parseAllBytes = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var byteCount = bytes.length();\n var value = _fromDer(bytes, bytes.length(), 0, options);\n if(options.parseAllBytes && bytes.length() !== 0) {\n var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');\n error.byteCount = byteCount;\n error.remaining = bytes.length();\n throw error;\n }\n return value;\n};\n\n/**\n * Internal function to parse an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the number of bytes remaining for this chunk.\n * @param depth the current parsing depth.\n * @param options object with same options as fromDer().\n *\n * @return the parsed asn1 object.\n */\nfunction _fromDer(bytes, remaining, depth, options) {\n // temporary storage for consumption calculations\n var start;\n\n // minimum length for ASN.1 DER structure is 2\n _checkBufferLength(bytes, remaining, 2);\n\n // get the first byte\n var b1 = bytes.getByte();\n // consumed one byte\n remaining--;\n\n // get the tag class\n var tagClass = (b1 & 0xC0);\n\n // get the type (bits 1-5)\n var type = b1 & 0x1F;\n\n // get the variable value length and adjust remaining bytes\n start = bytes.length();\n var length = _getValueLength(bytes, remaining);\n remaining -= start - bytes.length();\n\n // ensure there are enough bytes to get the value\n if(length !== undefined && length > remaining) {\n if(options.strict) {\n var error = new Error('Too few bytes to read ASN.1 value.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = length;\n throw error;\n }\n // Note: be lenient with truncated values and use remaining state bytes\n length = remaining;\n }\n\n // value storage\n var value;\n // possible BIT STRING contents storage\n var bitStringContents;\n\n // constructed flag is bit 6 (32 = 0x20) of the first byte\n var constructed = ((b1 & 0x20) === 0x20);\n if(constructed) {\n // parse child asn1 objects from the value\n value = [];\n if(length === undefined) {\n // asn1 object of indefinite length, read until end tag\n for(;;) {\n _checkBufferLength(bytes, remaining, 2);\n if(bytes.bytes(2) === String.fromCharCode(0, 0)) {\n bytes.getBytes(2);\n remaining -= 2;\n break;\n }\n start = bytes.length();\n value.push(_fromDer(bytes, remaining, depth + 1, options));\n remaining -= start - bytes.length();\n }\n } else {\n // parsing asn1 object of definite length\n while(length > 0) {\n start = bytes.length();\n value.push(_fromDer(bytes, length, depth + 1, options));\n remaining -= start - bytes.length();\n length -= start - bytes.length();\n }\n }\n }\n\n // if a BIT STRING, save the contents including padding\n if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&\n type === asn1.Type.BITSTRING) {\n bitStringContents = bytes.bytes(length);\n }\n\n // determine if a non-constructed value should be decoded as a composed\n // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)\n // can be used this way.\n if(value === undefined && options.decodeBitStrings &&\n tagClass === asn1.Class.UNIVERSAL &&\n // FIXME: OCTET STRINGs not yet supported here\n // .. other parts of forge expect to decode OCTET STRINGs manually\n (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&\n length > 1) {\n // save read position\n var savedRead = bytes.read;\n var savedRemaining = remaining;\n var unused = 0;\n if(type === asn1.Type.BITSTRING) {\n /* The first octet gives the number of bits by which the length of the\n bit string is less than the next multiple of eight (this is called\n the \"number of unused bits\").\n\n The second and following octets give the value of the bit string\n converted to an octet string. */\n _checkBufferLength(bytes, remaining, 1);\n unused = bytes.getByte();\n remaining--;\n }\n // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs\n if(unused === 0) {\n try {\n // attempt to parse child asn1 object from the value\n // (stored in array to signal composed value)\n start = bytes.length();\n var subOptions = {\n // enforce strict mode to avoid parsing ASN.1 from plain data\n strict: true,\n decodeBitStrings: true\n };\n var composed = _fromDer(bytes, remaining, depth + 1, subOptions);\n var used = start - bytes.length();\n remaining -= used;\n if(type == asn1.Type.BITSTRING) {\n used++;\n }\n\n // if the data all decoded and the class indicates UNIVERSAL or\n // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object\n var tc = composed.tagClass;\n if(used === length &&\n (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {\n value = [composed];\n }\n } catch(ex) {\n }\n }\n if(value === undefined) {\n // restore read position\n bytes.read = savedRead;\n remaining = savedRemaining;\n }\n }\n\n if(value === undefined) {\n // asn1 not constructed or composed, get raw value\n // TODO: do DER to OID conversion and vice-versa in .toDer?\n\n if(length === undefined) {\n if(options.strict) {\n throw new Error('Non-constructed ASN.1 object of indefinite length.');\n }\n // be lenient and use remaining state bytes\n length = remaining;\n }\n\n if(type === asn1.Type.BMPSTRING) {\n value = '';\n for(; length > 0; length -= 2) {\n _checkBufferLength(bytes, remaining, 2);\n value += String.fromCharCode(bytes.getInt16());\n remaining -= 2;\n }\n } else {\n value = bytes.getBytes(length);\n remaining -= length;\n }\n }\n\n // add BIT STRING contents if available\n var asn1Options = bitStringContents === undefined ? null : {\n bitStringContents: bitStringContents\n };\n\n // create and return asn1 object\n return asn1.create(tagClass, type, constructed, value, asn1Options);\n}\n\n/**\n * Converts the given asn1 object to a buffer of bytes in DER format.\n *\n * @param asn1 the asn1 object to convert to bytes.\n *\n * @return the buffer of bytes.\n */\nasn1.toDer = function(obj) {\n var bytes = forge.util.createBuffer();\n\n // build the first byte\n var b1 = obj.tagClass | obj.type;\n\n // for storing the ASN.1 value\n var value = forge.util.createBuffer();\n\n // use BIT STRING contents if available and data not changed\n var useBitStringContents = false;\n if('bitStringContents' in obj) {\n useBitStringContents = true;\n if(obj.original) {\n useBitStringContents = asn1.equals(obj, obj.original);\n }\n }\n\n if(useBitStringContents) {\n value.putBytes(obj.bitStringContents);\n } else if(obj.composed) {\n // if composed, use each child asn1 object's DER bytes as value\n // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed\n // from other asn1 objects\n if(obj.constructed) {\n b1 |= 0x20;\n } else {\n // type is a bit string, add unused bits of 0x00\n value.putByte(0x00);\n }\n\n // add all of the child DER bytes together\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n value.putBuffer(asn1.toDer(obj.value[i]));\n }\n }\n } else {\n // use asn1.value directly\n if(obj.type === asn1.Type.BMPSTRING) {\n for(var i = 0; i < obj.value.length; ++i) {\n value.putInt16(obj.value.charCodeAt(i));\n }\n } else {\n // ensure integer is minimally-encoded\n // TODO: should all leading bytes be stripped vs just one?\n // .. ex '00 00 01' => '01'?\n if(obj.type === asn1.Type.INTEGER &&\n obj.value.length > 1 &&\n // leading 0x00 for positive integer\n ((obj.value.charCodeAt(0) === 0 &&\n (obj.value.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (obj.value.charCodeAt(0) === 0xFF &&\n (obj.value.charCodeAt(1) & 0x80) === 0x80))) {\n value.putBytes(obj.value.substr(1));\n } else {\n value.putBytes(obj.value);\n }\n }\n }\n\n // add tag byte\n bytes.putByte(b1);\n\n // use \"short form\" encoding\n if(value.length() <= 127) {\n // one byte describes the length\n // bit 8 = 0 and bits 7-1 = length\n bytes.putByte(value.length() & 0x7F);\n } else {\n // use \"long form\" encoding\n // 2 to 127 bytes describe the length\n // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes\n // other bytes: length in base 256, big-endian\n var len = value.length();\n var lenBytes = '';\n do {\n lenBytes += String.fromCharCode(len & 0xFF);\n len = len >>> 8;\n } while(len > 0);\n\n // set first byte to # bytes used to store the length and turn on\n // bit 8 to indicate long-form length is used\n bytes.putByte(lenBytes.length | 0x80);\n\n // concatenate length bytes in reverse since they were generated\n // little endian and we need big endian\n for(var i = lenBytes.length - 1; i >= 0; --i) {\n bytes.putByte(lenBytes.charCodeAt(i));\n }\n }\n\n // concatenate value bytes\n bytes.putBuffer(value);\n return bytes;\n};\n\n/**\n * Converts an OID dot-separated string to a byte buffer. The byte buffer\n * contains only the DER-encoded value, not any tag or length bytes.\n *\n * @param oid the OID dot-separated string.\n *\n * @return the byte buffer.\n */\nasn1.oidToDer = function(oid) {\n // split OID into individual values\n var values = oid.split('.');\n var bytes = forge.util.createBuffer();\n\n // first byte is 40 * value1 + value2\n bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var last, valueBytes, value, b;\n for(var i = 2; i < values.length; ++i) {\n // produce value bytes in reverse because we don't know how many\n // bytes it will take to store the value\n last = true;\n valueBytes = [];\n value = parseInt(values[i], 10);\n do {\n b = value & 0x7F;\n value = value >>> 7;\n // if value is not last, then turn on 8th bit\n if(!last) {\n b |= 0x80;\n }\n valueBytes.push(b);\n last = false;\n } while(value > 0);\n\n // add value bytes in reverse (needs to be in big endian)\n for(var n = valueBytes.length - 1; n >= 0; --n) {\n bytes.putByte(valueBytes[n]);\n }\n }\n\n return bytes;\n};\n\n/**\n * Converts a DER-encoded byte buffer to an OID dot-separated string. The\n * byte buffer should contain only the DER-encoded value, not any tag or\n * length bytes.\n *\n * @param bytes the byte buffer.\n *\n * @return the OID dot-separated string.\n */\nasn1.derToOid = function(bytes) {\n var oid;\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n // first byte is 40 * value1 + value2\n var b = bytes.getByte();\n oid = Math.floor(b / 40) + '.' + (b % 40);\n\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var value = 0;\n while(bytes.length() > 0) {\n b = bytes.getByte();\n value = value << 7;\n // not the last byte for the value\n if(b & 0x80) {\n value += b & 0x7F;\n } else {\n // last byte\n oid += '.' + (value + b);\n value = 0;\n }\n }\n\n return oid;\n};\n\n/**\n * Converts a UTCTime value to a date.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Parsing that structure hasn't been implemented yet.\n *\n * @param utc the UTCTime value to convert.\n *\n * @return the date.\n */\nasn1.utcTimeToDate = function(utc) {\n /* The following formats can be used:\n\n YYMMDDhhmmZ\n YYMMDDhhmm+hh'mm'\n YYMMDDhhmm-hh'mm'\n YYMMDDhhmmssZ\n YYMMDDhhmmss+hh'mm'\n YYMMDDhhmmss-hh'mm'\n\n Where:\n\n YY is the least significant two digits of the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n // if YY >= 50 use 19xx, if YY < 50 use 20xx\n var year = parseInt(utc.substr(0, 2), 10);\n year = (year >= 50) ? 1900 + year : 2000 + year;\n var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(utc.substr(4, 2), 10);\n var hh = parseInt(utc.substr(6, 2), 10);\n var mm = parseInt(utc.substr(8, 2), 10);\n var ss = 0;\n\n // not just YYMMDDhhmmZ\n if(utc.length > 11) {\n // get character after minutes\n var c = utc.charAt(10);\n var end = 10;\n\n // see if seconds are present\n if(c !== '+' && c !== '-') {\n // get seconds\n ss = parseInt(utc.substr(10, 2), 10);\n end += 2;\n }\n }\n\n // update date\n date.setUTCFullYear(year, MM, DD);\n date.setUTCHours(hh, mm, ss, 0);\n\n if(end) {\n // get +/- after end of time\n c = utc.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(utc.substr(end + 1, 2), 10);\n var mmoffset = parseInt(utc.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n var offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n date.setTime(+date - offset);\n } else {\n date.setTime(+date + offset);\n }\n }\n }\n\n return date;\n};\n\n/**\n * Converts a GeneralizedTime value to a date.\n *\n * @param gentime the GeneralizedTime value to convert.\n *\n * @return the date.\n */\nasn1.generalizedTimeToDate = function(gentime) {\n /* The following formats can be used:\n\n YYYYMMDDHHMMSS\n YYYYMMDDHHMMSS.fff\n YYYYMMDDHHMMSSZ\n YYYYMMDDHHMMSS.fffZ\n YYYYMMDDHHMMSS+hh'mm'\n YYYYMMDDHHMMSS.fff+hh'mm'\n YYYYMMDDHHMMSS-hh'mm'\n YYYYMMDDHHMMSS.fff-hh'mm'\n\n Where:\n\n YYYY is the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n .fff is the second fraction, accurate to three decimal places\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n var YYYY = parseInt(gentime.substr(0, 4), 10);\n var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(gentime.substr(6, 2), 10);\n var hh = parseInt(gentime.substr(8, 2), 10);\n var mm = parseInt(gentime.substr(10, 2), 10);\n var ss = parseInt(gentime.substr(12, 2), 10);\n var fff = 0;\n var offset = 0;\n var isUTC = false;\n\n if(gentime.charAt(gentime.length - 1) === 'Z') {\n isUTC = true;\n }\n\n var end = gentime.length - 5, c = gentime.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);\n var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n offset *= -1;\n }\n\n isUTC = true;\n }\n\n // check for second fraction\n if(gentime.charAt(14) === '.') {\n fff = parseFloat(gentime.substr(14), 10) * 1000;\n }\n\n if(isUTC) {\n date.setUTCFullYear(YYYY, MM, DD);\n date.setUTCHours(hh, mm, ss, fff);\n\n // apply offset\n date.setTime(+date + offset);\n } else {\n date.setFullYear(YYYY, MM, DD);\n date.setHours(hh, mm, ss, fff);\n }\n\n return date;\n};\n\n/**\n * Converts a date to a UTCTime value.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Converting to a GeneralizedTime hasn't been\n * implemented yet.\n *\n * @param date the date to convert.\n *\n * @return the UTCTime value.\n */\nasn1.dateToUtcTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYMMDDhhmmssZ\n var format = [];\n format.push(('' + date.getUTCFullYear()).substr(2));\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a date to a GeneralizedTime value.\n *\n * @param date the date to convert.\n *\n * @return the GeneralizedTime value as a string.\n */\nasn1.dateToGeneralizedTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYYYMMDDHHMMSSZ\n var format = [];\n format.push('' + date.getUTCFullYear());\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a javascript integer to a DER-encoded byte buffer to be used\n * as the value for an INTEGER type.\n *\n * @param x the integer.\n *\n * @return the byte buffer.\n */\nasn1.integerToDer = function(x) {\n var rval = forge.util.createBuffer();\n if(x >= -0x80 && x < 0x80) {\n return rval.putSignedInt(x, 8);\n }\n if(x >= -0x8000 && x < 0x8000) {\n return rval.putSignedInt(x, 16);\n }\n if(x >= -0x800000 && x < 0x800000) {\n return rval.putSignedInt(x, 24);\n }\n if(x >= -0x80000000 && x < 0x80000000) {\n return rval.putSignedInt(x, 32);\n }\n var error = new Error('Integer too large; max is 32-bits.');\n error.integer = x;\n throw error;\n};\n\n/**\n * Converts a DER-encoded byte buffer to a javascript integer. This is\n * typically used to decode the value of an INTEGER type.\n *\n * @param bytes the byte buffer.\n *\n * @return the integer.\n */\nasn1.derToInteger = function(bytes) {\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var n = bytes.length() * 8;\n if(n > 32) {\n throw new Error('Integer too large; max is 32-bits.');\n }\n return bytes.getSignedInt(n);\n};\n\n/**\n * Validates that the given ASN.1 object is at least a super set of the\n * given ASN.1 structure. Only tag classes and types are checked. An\n * optional map may also be provided to capture ASN.1 values while the\n * structure is checked.\n *\n * To capture an ASN.1 value, set an object in the validator's 'capture'\n * parameter to the key to use in the capture map. To capture the full\n * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including\n * the leading unused bits counter byte, specify 'captureBitStringContents'.\n * To capture BIT STRING bytes, without the leading unused bits counter byte,\n * specify 'captureBitStringValue'.\n *\n * Objects in the validator may set a field 'optional' to true to indicate\n * that it isn't necessary to pass validation.\n *\n * @param obj the ASN.1 object to validate.\n * @param v the ASN.1 structure validator.\n * @param capture an optional map to capture values in.\n * @param errors an optional array for storing validation errors.\n *\n * @return true on success, false on failure.\n */\nasn1.validate = function(obj, v, capture, errors) {\n var rval = false;\n\n // ensure tag class and type are the same if specified\n if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&\n (obj.type === v.type || typeof(v.type) === 'undefined')) {\n // ensure constructed flag is the same if specified\n if(obj.constructed === v.constructed ||\n typeof(v.constructed) === 'undefined') {\n rval = true;\n\n // handle sub values\n if(v.value && forge.util.isArray(v.value)) {\n var j = 0;\n for(var i = 0; rval && i < v.value.length; ++i) {\n rval = v.value[i].optional || false;\n if(obj.value[j]) {\n rval = asn1.validate(obj.value[j], v.value[i], capture, errors);\n if(rval) {\n ++j;\n } else if(v.value[i].optional) {\n rval = true;\n }\n }\n if(!rval && errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Tag class \"' + v.tagClass + '\", type \"' +\n v.type + '\" expected value length \"' +\n v.value.length + '\", got \"' +\n obj.value.length + '\"');\n }\n }\n }\n\n if(rval && capture) {\n if(v.capture) {\n capture[v.capture] = obj.value;\n }\n if(v.captureAsn1) {\n capture[v.captureAsn1] = obj;\n }\n if(v.captureBitStringContents && 'bitStringContents' in obj) {\n capture[v.captureBitStringContents] = obj.bitStringContents;\n }\n if(v.captureBitStringValue && 'bitStringContents' in obj) {\n var value;\n if(obj.bitStringContents.length < 2) {\n capture[v.captureBitStringValue] = '';\n } else {\n // FIXME: support unused bits with data shifting\n var unused = obj.bitStringContents.charCodeAt(0);\n if(unused !== 0) {\n throw new Error(\n 'captureBitStringValue only supported for zero unused bits');\n }\n capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);\n }\n }\n }\n } else if(errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected constructed \"' + v.constructed + '\", got \"' +\n obj.constructed + '\"');\n }\n } else if(errors) {\n if(obj.tagClass !== v.tagClass) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected tag class \"' + v.tagClass + '\", got \"' +\n obj.tagClass + '\"');\n }\n if(obj.type !== v.type) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected type \"' + v.type + '\", got \"' + obj.type + '\"');\n }\n }\n return rval;\n};\n\n// regex for testing for non-latin characters\nvar _nonLatinRegex = /[^\\\\u0000-\\\\u00ff]/;\n\n/**\n * Pretty prints an ASN.1 object to a string.\n *\n * @param obj the object to write out.\n * @param level the level in the tree.\n * @param indentation the indentation to use.\n *\n * @return the string.\n */\nasn1.prettyPrint = function(obj, level, indentation) {\n var rval = '';\n\n // set default level and indentation\n level = level || 0;\n indentation = indentation || 2;\n\n // start new line for deep levels\n if(level > 0) {\n rval += '\\n';\n }\n\n // create indent\n var indent = '';\n for(var i = 0; i < level * indentation; ++i) {\n indent += ' ';\n }\n\n // print class:type\n rval += indent + 'Tag: ';\n switch(obj.tagClass) {\n case asn1.Class.UNIVERSAL:\n rval += 'Universal:';\n break;\n case asn1.Class.APPLICATION:\n rval += 'Application:';\n break;\n case asn1.Class.CONTEXT_SPECIFIC:\n rval += 'Context-Specific:';\n break;\n case asn1.Class.PRIVATE:\n rval += 'Private:';\n break;\n }\n\n if(obj.tagClass === asn1.Class.UNIVERSAL) {\n rval += obj.type;\n\n // known types\n switch(obj.type) {\n case asn1.Type.NONE:\n rval += ' (None)';\n break;\n case asn1.Type.BOOLEAN:\n rval += ' (Boolean)';\n break;\n case asn1.Type.INTEGER:\n rval += ' (Integer)';\n break;\n case asn1.Type.BITSTRING:\n rval += ' (Bit string)';\n break;\n case asn1.Type.OCTETSTRING:\n rval += ' (Octet string)';\n break;\n case asn1.Type.NULL:\n rval += ' (Null)';\n break;\n case asn1.Type.OID:\n rval += ' (Object Identifier)';\n break;\n case asn1.Type.ODESC:\n rval += ' (Object Descriptor)';\n break;\n case asn1.Type.EXTERNAL:\n rval += ' (External or Instance of)';\n break;\n case asn1.Type.REAL:\n rval += ' (Real)';\n break;\n case asn1.Type.ENUMERATED:\n rval += ' (Enumerated)';\n break;\n case asn1.Type.EMBEDDED:\n rval += ' (Embedded PDV)';\n break;\n case asn1.Type.UTF8:\n rval += ' (UTF8)';\n break;\n case asn1.Type.ROID:\n rval += ' (Relative Object Identifier)';\n break;\n case asn1.Type.SEQUENCE:\n rval += ' (Sequence)';\n break;\n case asn1.Type.SET:\n rval += ' (Set)';\n break;\n case asn1.Type.PRINTABLESTRING:\n rval += ' (Printable String)';\n break;\n case asn1.Type.IA5String:\n rval += ' (IA5String (ASCII))';\n break;\n case asn1.Type.UTCTIME:\n rval += ' (UTC time)';\n break;\n case asn1.Type.GENERALIZEDTIME:\n rval += ' (Generalized time)';\n break;\n case asn1.Type.BMPSTRING:\n rval += ' (BMP String)';\n break;\n }\n } else {\n rval += obj.type;\n }\n\n rval += '\\n';\n rval += indent + 'Constructed: ' + obj.constructed + '\\n';\n\n if(obj.composed) {\n var subvalues = 0;\n var sub = '';\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n subvalues += 1;\n sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);\n if((i + 1) < obj.value.length) {\n sub += ',';\n }\n }\n }\n rval += indent + 'Sub values: ' + subvalues + sub;\n } else {\n rval += indent + 'Value: ';\n if(obj.type === asn1.Type.OID) {\n var oid = asn1.derToOid(obj.value);\n rval += oid;\n if(forge.pki && forge.pki.oids) {\n if(oid in forge.pki.oids) {\n rval += ' (' + forge.pki.oids[oid] + ') ';\n }\n }\n }\n if(obj.type === asn1.Type.INTEGER) {\n try {\n rval += asn1.derToInteger(obj.value);\n } catch(ex) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n }\n } else if(obj.type === asn1.Type.BITSTRING) {\n // TODO: shift bits as needed to display without padding\n if(obj.value.length > 1) {\n // remove unused bits field\n rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));\n } else {\n rval += '(none)';\n }\n // show unused bit count\n if(obj.value.length > 0) {\n var unused = obj.value.charCodeAt(0);\n if(unused == 1) {\n rval += ' (1 unused bit shown)';\n } else if(unused > 1) {\n rval += ' (' + unused + ' unused bits shown)';\n }\n }\n } else if(obj.type === asn1.Type.OCTETSTRING) {\n if(!_nonLatinRegex.test(obj.value)) {\n rval += '(' + obj.value + ') ';\n }\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.type === asn1.Type.UTF8) {\n try {\n rval += forge.util.decodeUtf8(obj.value);\n } catch(e) {\n if(e.message === 'URI malformed') {\n rval +=\n '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';\n } else {\n throw e;\n }\n }\n } else if(obj.type === asn1.Type.PRINTABLESTRING ||\n obj.type === asn1.Type.IA5String) {\n rval += obj.value;\n } else if(_nonLatinRegex.test(obj.value)) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.value.length === 0) {\n rval += '[null]';\n } else {\n rval += obj.value;\n }\n }\n\n return rval;\n};\n","/**\n * Base-N/Base-X encoding/decoding functions.\n *\n * Original implementation from base-x:\n * https://github.com/cryptocoinjs/base-x\n *\n * Which is MIT licensed:\n *\n * The MIT License (MIT)\n *\n * Copyright base-x contributors (c) 2016\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nvar api = {};\nmodule.exports = api;\n\n// baseN alphabet indexes\nvar _reverseAlphabets = {};\n\n/**\n * BaseN-encodes a Uint8Array using the given alphabet.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the baseN-encoded output string.\n */\napi.encode = function(input, alphabet, maxline) {\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n if(maxline !== undefined && typeof maxline !== 'number') {\n throw new TypeError('\"maxline\" must be a number.');\n }\n\n var output = '';\n\n if(!(input instanceof Uint8Array)) {\n // assume forge byte buffer\n output = _encodeWithByteBuffer(input, alphabet);\n } else {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length; ++i) {\n for(var j = 0, carry = input[i]; j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n // deal with leading zeros\n for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n }\n\n if(maxline) {\n var regex = new RegExp('.{1,' + maxline + '}', 'g');\n output = output.match(regex).join('\\r\\n');\n }\n\n return output;\n};\n\n/**\n * Decodes a baseN-encoded (using the given alphabet) string to a\n * Uint8Array.\n *\n * @param input the baseN-encoded input string.\n *\n * @return the Uint8Array.\n */\napi.decode = function(input, alphabet) {\n if(typeof input !== 'string') {\n throw new TypeError('\"input\" must be a string.');\n }\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n\n var table = _reverseAlphabets[alphabet];\n if(!table) {\n // compute reverse alphabet\n table = _reverseAlphabets[alphabet] = [];\n for(var i = 0; i < alphabet.length; ++i) {\n table[alphabet.charCodeAt(i)] = i;\n }\n }\n\n // remove whitespace characters\n input = input.replace(/\\s/g, '');\n\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var bytes = [0];\n for(var i = 0; i < input.length; i++) {\n var value = table[input.charCodeAt(i)];\n if(value === undefined) {\n return;\n }\n\n for(var j = 0, carry = value; j < bytes.length; ++j) {\n carry += bytes[j] * base;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while(carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // deal with leading zeros\n for(var k = 0; input[k] === first && k < input.length - 1; ++k) {\n bytes.push(0);\n }\n\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(bytes.reverse());\n }\n\n return new Uint8Array(bytes.reverse());\n};\n\nfunction _encodeWithByteBuffer(input, alphabet) {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length(); ++i) {\n for(var j = 0, carry = input.at(i); j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n var output = '';\n\n // deal with leading zeros\n for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n\n return output;\n}\n","/**\n * Cipher base API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nmodule.exports = forge.cipher = forge.cipher || {};\n\n// registered algorithms\nforge.cipher.algorithms = forge.cipher.algorithms || {};\n\n/**\n * Creates a cipher object that can be used to encrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createCipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: false\n });\n};\n\n/**\n * Creates a decipher object that can be used to decrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createDecipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: true\n });\n};\n\n/**\n * Registers an algorithm by name. If the name was already registered, the\n * algorithm API object will be overwritten.\n *\n * @param name the name of the algorithm.\n * @param algorithm the algorithm API object.\n */\nforge.cipher.registerAlgorithm = function(name, algorithm) {\n name = name.toUpperCase();\n forge.cipher.algorithms[name] = algorithm;\n};\n\n/**\n * Gets a registered algorithm by name.\n *\n * @param name the name of the algorithm.\n *\n * @return the algorithm, if found, null if not.\n */\nforge.cipher.getAlgorithm = function(name) {\n name = name.toUpperCase();\n if(name in forge.cipher.algorithms) {\n return forge.cipher.algorithms[name];\n }\n return null;\n};\n\nvar BlockCipher = forge.cipher.BlockCipher = function(options) {\n this.algorithm = options.algorithm;\n this.mode = this.algorithm.mode;\n this.blockSize = this.mode.blockSize;\n this._finish = false;\n this._input = null;\n this.output = null;\n this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;\n this._decrypt = options.decrypt;\n this.algorithm.initialize(options);\n};\n\n/**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array\n * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in\n * bytes, then it must be Nb (16) bytes in length. If the IV is given in as\n * 32-bit integers, then it must be 4 integers long.\n *\n * Note: an IV is not required or used in ECB mode.\n *\n * For GCM-mode, the IV must be given as a binary-encoded string of bytes or\n * a byte buffer. The number of bytes should be 12 (96 bits) as recommended\n * by NIST SP-800-38D but another length may be given.\n *\n * @param options the options to use:\n * iv the initialization vector to use as a binary-encoded string of\n * bytes, null to reuse the last ciphered block from a previous\n * update() (this \"residue\" method is for legacy support only).\n * additionalData additional authentication data as a binary-encoded\n * string of bytes, for 'GCM' mode, (default: none).\n * tagLength desired length of authentication tag, in bits, for\n * 'GCM' mode (0-128, default: 128).\n * tag the authentication tag to check if decrypting, as a\n * binary-encoded string of bytes.\n * output the output the buffer to write to, null to create one.\n */\nBlockCipher.prototype.start = function(options) {\n options = options || {};\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n opts.decrypt = this._decrypt;\n this._finish = false;\n this._input = forge.util.createBuffer();\n this.output = options.output || forge.util.createBuffer();\n this.mode.start(opts);\n};\n\n/**\n * Updates the next block according to the cipher mode.\n *\n * @param input the buffer to read from.\n */\nBlockCipher.prototype.update = function(input) {\n if(input) {\n // input given, so empty it into the input buffer\n this._input.putBuffer(input);\n }\n\n // do cipher operation until it needs more input and not finished\n while(!this._op.call(this.mode, this._input, this.output, this._finish) &&\n !this._finish) {}\n\n // free consumed memory from input buffer\n this._input.compact();\n};\n\n/**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use in CBC mode, null for default,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\nBlockCipher.prototype.finish = function(pad) {\n // backwards-compatibility w/deprecated padding API\n // Note: will overwrite padding functions even after another start() call\n if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {\n this.mode.pad = function(input) {\n return pad(this.blockSize, input, false);\n };\n this.mode.unpad = function(output) {\n return pad(this.blockSize, output, true);\n };\n }\n\n // build options for padding and afterFinish functions\n var options = {};\n options.decrypt = this._decrypt;\n\n // get # of bytes that won't fill a block\n options.overflow = this._input.length() % this.blockSize;\n\n if(!this._decrypt && this.mode.pad) {\n if(!this.mode.pad(this._input, options)) {\n return false;\n }\n }\n\n // do final update\n this._finish = true;\n this.update();\n\n if(this._decrypt && this.mode.unpad) {\n if(!this.mode.unpad(this.output, options)) {\n return false;\n }\n }\n\n if(this.mode.afterFinish) {\n if(!this.mode.afterFinish(this.output, options)) {\n return false;\n }\n }\n\n return true;\n};\n","/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n","/**\n * DES (Data Encryption Standard) implementation.\n *\n * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.\n * It is based on the BSD-licensed implementation by Paul Tero:\n *\n * Paul Tero, July 2001\n * http://www.tero.co.uk/des/\n *\n * Optimised for performance with large blocks by\n * Michael Hayworth, November 2001\n * http://www.netdealing.com\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* DES API */\nmodule.exports = forge.des = forge.des || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new DES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the DES algorithm object.\n */\nforge.des.Algorithm = function(name, mode) {\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 8,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this DES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.des.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = forge.util.createBuffer(options.key);\n if(this.name.indexOf('3DES') === 0) {\n if(key.length() !== 24) {\n throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);\n }\n }\n\n // do key expansion to 16 or 48 subkeys (single or triple DES)\n this._keys = _createKeys(key);\n this._init = true;\n};\n\n/** Register DES algorithms **/\n\nregisterAlgorithm('DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('DES-CTR', forge.cipher.modes.ctr);\n\nregisterAlgorithm('3DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('3DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('3DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('3DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('3DES-CTR', forge.cipher.modes.ctr);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.des.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** DES implementation **/\n\nvar spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\nvar spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\nvar spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\nvar spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\nvar spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\nvar spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\nvar spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\nvar spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n/**\n * Create necessary sub keys.\n *\n * @param key the 64-bit or 192-bit key.\n *\n * @return the expanded keys.\n */\nfunction _createKeys(key) {\n var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],\n pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],\n pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],\n pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],\n pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],\n pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],\n pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],\n pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],\n pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],\n pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],\n pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],\n pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],\n pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],\n pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];\n\n // how many iterations (1 for des, 3 for triple des)\n // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n var iterations = key.length() > 8 ? 3 : 1;\n\n // stores the return keys\n var keys = [];\n\n // now define the left shifts which need to be done\n var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n\n var n = 0, tmp;\n for(var j = 0; j < iterations; j++) {\n var left = key.getInt32();\n var right = key.getInt32();\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= tmp;\n left ^= (tmp << 2);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // right needs to be shifted and OR'd with last four bits of left\n tmp = (left << 8) | ((right >>> 20) & 0x000000f0);\n\n // left needs to be put upside down\n left = ((right << 24) | ((right << 8) & 0xff0000) |\n ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));\n right = tmp;\n\n // now go through and perform these shifts on the left and right keys\n for(var i = 0; i < shifts.length; ++i) {\n //shift the keys either one or two bits to the left\n if(shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n // now apply PC-2, in such a way that E is easier when encrypting or\n // decrypting this conversion will look like PC-2 except only the last 6\n // bits of each byte are used rather than 48 consecutive bits and the\n // order of lines will be according to how the S selection functions will\n // be applied: S2, S4, S6, S8, S1, S3, S5, S7\n var lefttmp = (\n pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |\n pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |\n pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |\n pc2bytes6[(left >>> 4) & 0xf]);\n var righttmp = (\n pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |\n pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |\n pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf]);\n tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;\n keys[n++] = lefttmp ^ tmp;\n keys[n++] = righttmp ^ (tmp << 16);\n }\n }\n\n return keys;\n}\n\n/**\n * Updates a single block (1 byte) using DES. The update will either\n * encrypt or decrypt the block.\n *\n * @param keys the expanded keys.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(keys, input, output, decrypt) {\n // set up loops for single or triple DES\n var iterations = keys.length === 32 ? 3 : 9;\n var looping;\n if(iterations === 3) {\n looping = decrypt ? [30, -2, -2] : [0, 32, 2];\n } else {\n looping = (decrypt ?\n [94, 62, -2, 32, 64, 2, 30, -2, -2] :\n [0, 32, 2, 62, 30, -2, 64, 96, 2]);\n }\n\n var tmp;\n\n var left = input[0];\n var right = input[1];\n\n // first each 64 bit chunk of the message must be permuted according to IP\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // rotate left 1 bit\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n for(var j = 0; j < iterations; j += 3) {\n var endloop = looping[j + 1];\n var loopinc = looping[j + 2];\n\n // now go through and perform the encryption or decryption\n for(var i = looping[j]; i != endloop; i += loopinc) {\n var right1 = right ^ keys[i];\n var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n\n // passing these bytes through the S selection functions\n tmp = left;\n left = right;\n right = tmp ^ (\n spfunction2[(right1 >>> 24) & 0x3f] |\n spfunction4[(right1 >>> 16) & 0x3f] |\n spfunction6[(right1 >>> 8) & 0x3f] |\n spfunction8[right1 & 0x3f] |\n spfunction1[(right2 >>> 24) & 0x3f] |\n spfunction3[(right2 >>> 16) & 0x3f] |\n spfunction5[(right2 >>> 8) & 0x3f] |\n spfunction7[right2 & 0x3f]);\n }\n // unreverse left and right\n tmp = left;\n left = right;\n right = tmp;\n }\n\n // rotate right 1 bit\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n // now perform IP-1, which is IP in the opposite direction\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n output[0] = left;\n output[1] = right;\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('DES-', key);\n * forge.cipher.createDecipher('DES-', key);\n *\n * Creates a deprecated DES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param options the options to use.\n * key the symmetric key to use (64 or 192 bits).\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'DES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * JavaScript implementation of Ed25519.\n *\n * Copyright (c) 2017-2019 Digital Bazaar, Inc.\n *\n * This implementation is based on the most excellent TweetNaCl which is\n * in the public domain. Many thanks to its contributors:\n *\n * https://github.com/dchest/tweetnacl-js\n */\nvar forge = require('./forge');\nrequire('./jsbn');\nrequire('./random');\nrequire('./sha512');\nrequire('./util');\nvar asn1Validator = require('./asn1-validator');\nvar publicKeyValidator = asn1Validator.publicKeyValidator;\nvar privateKeyValidator = asn1Validator.privateKeyValidator;\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar ByteBuffer = forge.util.ByteBuffer;\nvar NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer;\n\n/*\n * Ed25519 algorithms, see RFC 8032:\n * https://tools.ietf.org/html/rfc8032\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};\nvar ed25519 = forge.ed25519;\n\ned25519.constants = {};\ned25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;\ned25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;\ned25519.constants.SEED_BYTE_LENGTH = 32;\ned25519.constants.SIGN_BYTE_LENGTH = 64;\ned25519.constants.HASH_BYTE_LENGTH = 64;\n\ned25519.generateKeyPair = function(options) {\n options = options || {};\n var seed = options.seed;\n if(seed === undefined) {\n // generate seed\n seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);\n } else if(typeof seed === 'string') {\n if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {\n throw new TypeError(\n '\"seed\" must be ' + ed25519.constants.SEED_BYTE_LENGTH +\n ' bytes in length.');\n }\n } else if(!(seed instanceof Uint8Array)) {\n throw new TypeError(\n '\"seed\" must be a node.js Buffer, Uint8Array, or a binary string.');\n }\n\n seed = messageToNativeBuffer({message: seed, encoding: 'binary'});\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n for(var i = 0; i < 32; ++i) {\n sk[i] = seed[i];\n }\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, privateKey: sk};\n};\n\n/**\n * Converts a private key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a private key.\n *\n * @returns {Object} keyInfo - The key information.\n * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes.\n */\ned25519.privateKeyFromAsn1 = function(obj) {\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.privateKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var privateKey = capture.privateKey;\n // manually extract the private key bytes from nested octet string, see FIXME:\n // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542\n var privateKeyBytes = messageToNativeBuffer({\n message: forge.asn1.fromDer(privateKey).value,\n encoding: 'binary'\n });\n // TODO: RFC8410 specifies a format for encoding the public key bytes along\n // with the private key bytes. `publicKeyBytes` can be returned in the\n // future. https://tools.ietf.org/html/rfc8410#section-10.3\n return {privateKeyBytes: privateKeyBytes};\n};\n\n/**\n * Converts a public key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a public key.\n *\n * @return {Buffer|Uint8Array} - 32 public key bytes.\n */\ned25519.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.publicKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var publicKeyBytes = capture.ed25519PublicKey;\n if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new Error('Key length is invalid.');\n }\n return messageToNativeBuffer({\n message: publicKeyBytes,\n encoding: 'binary'\n });\n};\n\ned25519.publicKeyFromPrivateKey = function(options) {\n options = options || {};\n var privateKey = messageToNativeBuffer({\n message: options.privateKey, encoding: 'binary'\n });\n if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n for(var i = 0; i < pk.length; ++i) {\n pk[i] = privateKey[32 + i];\n }\n return pk;\n};\n\ned25519.sign = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n var privateKey = messageToNativeBuffer({\n message: options.privateKey,\n encoding: 'binary'\n });\n if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {\n var keyPair = ed25519.generateKeyPair({seed: privateKey});\n privateKey = keyPair.privateKey;\n } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.SEED_BYTE_LENGTH + ' or ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var signedMsg = new NativeBuffer(\n ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n crypto_sign(signedMsg, msg, msg.length, privateKey);\n\n var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);\n for(var i = 0; i < sig.length; ++i) {\n sig[i] = signedMsg[i];\n }\n return sig;\n};\n\ned25519.verify = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n if(options.signature === undefined) {\n throw new TypeError(\n '\"options.signature\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a binary string.');\n }\n var sig = messageToNativeBuffer({\n message: options.signature,\n encoding: 'binary'\n });\n if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.signature\" must have a byte length of ' +\n ed25519.constants.SIGN_BYTE_LENGTH);\n }\n var publicKey = messageToNativeBuffer({\n message: options.publicKey,\n encoding: 'binary'\n });\n if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.publicKey\" must have a byte length of ' +\n ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n }\n\n var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var i;\n for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) {\n sm[i] = sig[i];\n }\n for(i = 0; i < msg.length; ++i) {\n sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i];\n }\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nfunction messageToNativeBuffer(options) {\n var message = options.message;\n if(message instanceof Uint8Array || message instanceof NativeBuffer) {\n return message;\n }\n\n var encoding = options.encoding;\n if(message === undefined) {\n if(options.md) {\n // TODO: more rigorous validation that `md` is a MessageDigest\n message = options.md.digest().getBytes();\n encoding = 'binary';\n } else {\n throw new TypeError('\"options.message\" or \"options.md\" not specified.');\n }\n }\n\n if(typeof message === 'string' && !encoding) {\n throw new TypeError('\"options.encoding\" must be \"binary\" or \"utf8\".');\n }\n\n if(typeof message === 'string') {\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(message, encoding);\n }\n message = new ByteBuffer(message, encoding);\n } else if(!(message instanceof ByteBuffer)) {\n throw new TypeError(\n '\"options.message\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a string with \"options.encoding\" specifying its ' +\n 'encoding.');\n }\n\n // convert to native buffer\n var buffer = new NativeBuffer(message.length());\n for(var i = 0; i < buffer.length; ++i) {\n buffer[i] = message.at(i);\n }\n return buffer;\n}\n\nvar gf0 = gf();\nvar gf1 = gf([1]);\nvar D = gf([\n 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,\n 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);\nvar D2 = gf([\n 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,\n 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);\nvar X = gf([\n 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,\n 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);\nvar Y = gf([\n 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,\n 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);\nvar L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,\n 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\nvar I = gf([\n 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,\n 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\n// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`,\n// whichever is available, to improve performance\nfunction sha512(msg, msgLen) {\n // Note: `out` and `msg` are NativeBuffer\n var md = forge.md.sha512.create();\n var buffer = new ByteBuffer(msg);\n md.update(buffer.getBytes(msgLen), 'binary');\n var hash = md.digest().getBytes();\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(hash, 'binary');\n }\n var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);\n for(var i = 0; i < 64; ++i) {\n out[i] = hash.charCodeAt(i);\n }\n return out;\n}\n\nfunction crypto_sign_keypair(pk, sk) {\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for(i = 0; i < 32; ++i) {\n sk[i + 32] = pk[i];\n }\n return 0;\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for(i = 0; i < n; ++i) {\n sm[64 + i] = m[i];\n }\n for(i = 0; i < 32; ++i) {\n sm[32 + i] = d[32 + i];\n }\n\n var r = sha512(sm.subarray(32), n + 32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for(i = 32; i < 64; ++i) {\n sm[i] = sk[i];\n }\n var h = sha512(sm, n + 64);\n reduce(h);\n\n for(i = 32; i < 64; ++i) {\n x[i] = 0;\n }\n for(i = 0; i < 32; ++i) {\n x[i] = r[i];\n }\n for(i = 0; i < 32; ++i) {\n for(j = 0; j < 32; j++) {\n x[i + j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new NativeBuffer(32);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if(n < 64) {\n return -1;\n }\n\n if(unpackneg(q, pk)) {\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i];\n }\n for(i = 0; i < 32; ++i) {\n m[i + 32] = pk[i];\n }\n var h = sha512(m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if(crypto_verify_32(sm, 0, t, 0)) {\n for(i = 0; i < n; ++i) {\n m[i] = 0;\n }\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i + 64];\n }\n mlen = n;\n return mlen;\n}\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for(i = 63; i >= 32; --i) {\n carry = 0;\n for(j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for(j = 0; j < 32; ++j) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for(j = 0; j < 32; ++j) {\n x[j] -= carry * L[j];\n }\n for(i = 0; i < 32; ++i) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64);\n for(var i = 0; i < 64; ++i) {\n x[i] = r[i];\n r[i] = 0;\n }\n modL(r, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n for(var i = 0; i < 4; ++i) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for(i = 0; i < 16; ++i) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for(j = 0; j < 2; ++j) {\n m[0] = t[0] - 0xffed;\n for(i = 1; i < 15; ++i) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n M(r[0], r[0], I);\n }\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n return -1;\n }\n\n if(par25519(r[0]) === (p[31] >> 7)) {\n Z(r[0], gf0, r[0]);\n }\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for(i = 0; i < 16; ++i) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 250; a >= 0; --a) {\n S(c, c);\n if(a !== 1) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction neq25519(a, b) {\n var c = new NativeBuffer(32);\n var d = new NativeBuffer(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x, xi, y, yi, 32);\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i, d = 0;\n for(i = 0; i < n; ++i) {\n d |= x[xi + i] ^ y[yi + i];\n }\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction par25519(a) {\n var d = new NativeBuffer(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for(i = 255; i >= 0; --i) {\n b = (s[(i / 8)|0] >> (i & 7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction set25519(r, a) {\n var i;\n for(i = 0; i < 16; i++) {\n r[i] = a[i] | 0;\n }\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 253; a >= 0; --a) {\n S(c, c);\n if(a !== 2 && a !== 4) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for(i = 0; i < 16; ++i) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b - 1);\n for(var i = 0; i < 16; ++i) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction gf(init) {\n var i, r = new Float64Array(16);\n if(init) {\n for(i = 0; i < init.length; ++i) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\nfunction A(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction Z(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n","/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = {\n // default options\n options: {\n usePureJavaScript: false\n }\n};\n","/**\n * Hash-based Message Authentication Code implementation. Requires a message\n * digest object that can be obtained, for example, from forge.md.sha1 or\n * forge.md.md5.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\n/* HMAC API */\nvar hmac = module.exports = forge.hmac = forge.hmac || {};\n\n/**\n * Creates an HMAC object that uses the given message digest object.\n *\n * @return an HMAC object.\n */\nhmac.create = function() {\n // the hmac key to use\n var _key = null;\n\n // the message digest to use\n var _md = null;\n\n // the inner padding\n var _ipadding = null;\n\n // the outer padding\n var _opadding = null;\n\n // hmac context\n var ctx = {};\n\n /**\n * Starts or restarts the HMAC with the given key and message digest.\n *\n * @param md the message digest to use, null to reuse the previous one,\n * a string to use builtin 'sha1', 'md5', 'sha256'.\n * @param key the key to use as a string, array of bytes, byte buffer,\n * or null to reuse the previous key.\n */\n ctx.start = function(md, key) {\n if(md !== null) {\n if(typeof md === 'string') {\n // create builtin message digest\n md = md.toLowerCase();\n if(md in forge.md.algorithms) {\n _md = forge.md.algorithms[md].create();\n } else {\n throw new Error('Unknown hash algorithm \"' + md + '\"');\n }\n } else {\n // store message digest\n _md = md;\n }\n }\n\n if(key === null) {\n // reuse previous key\n key = _key;\n } else {\n if(typeof key === 'string') {\n // convert string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key)) {\n // convert byte array into byte buffer\n var tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // if key is longer than blocksize, hash it\n var keylen = key.length();\n if(keylen > _md.blockLength) {\n _md.start();\n _md.update(key.bytes());\n key = _md.digest();\n }\n\n // mix key into inner and outer padding\n // ipadding = [0x36 * blocksize] ^ key\n // opadding = [0x5C * blocksize] ^ key\n _ipadding = forge.util.createBuffer();\n _opadding = forge.util.createBuffer();\n keylen = key.length();\n for(var i = 0; i < keylen; ++i) {\n var tmp = key.at(i);\n _ipadding.putByte(0x36 ^ tmp);\n _opadding.putByte(0x5C ^ tmp);\n }\n\n // if key is shorter than blocksize, add additional padding\n if(keylen < _md.blockLength) {\n var tmp = _md.blockLength - keylen;\n for(var i = 0; i < tmp; ++i) {\n _ipadding.putByte(0x36);\n _opadding.putByte(0x5C);\n }\n }\n _key = key;\n _ipadding = _ipadding.bytes();\n _opadding = _opadding.bytes();\n }\n\n // digest is done like so: hash(opadding | hash(ipadding | message))\n\n // prepare to do inner hash\n // hash(ipadding | message)\n _md.start();\n _md.update(_ipadding);\n };\n\n /**\n * Updates the HMAC with the given message bytes.\n *\n * @param bytes the bytes to update with.\n */\n ctx.update = function(bytes) {\n _md.update(bytes);\n };\n\n /**\n * Produces the Message Authentication Code (MAC).\n *\n * @return a byte buffer containing the digest value.\n */\n ctx.getMac = function() {\n // digest is done like so: hash(opadding | hash(ipadding | message))\n // here we do the outer hashing\n var inner = _md.digest().bytes();\n _md.start();\n _md.update(_opadding);\n _md.update(inner);\n return _md.digest();\n };\n // alias for getMac\n ctx.digest = ctx.getMac;\n\n return ctx;\n};\n","/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = require('./forge');\nrequire('./aes');\nrequire('./aesCipherSuites');\nrequire('./asn1');\nrequire('./cipher');\nrequire('./des');\nrequire('./ed25519');\nrequire('./hmac');\nrequire('./kem');\nrequire('./log');\nrequire('./md.all');\nrequire('./mgf1');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./pkcs1');\nrequire('./pkcs12');\nrequire('./pkcs7');\nrequire('./pki');\nrequire('./prime');\nrequire('./prng');\nrequire('./pss');\nrequire('./random');\nrequire('./rc2');\nrequire('./ssh');\nrequire('./tls');\nrequire('./util');\n","// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n/*\nLicensing (LICENSE)\n-------------------\n\nThis software is covered under the following copyright:\n*/\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n/*\nAddress all questions regarding this license to:\n\n Tom Wu\n tjw@cs.Stanford.EDU\n*/\nvar forge = require('./forge');\n\nmodule.exports = forge.jsbn = forge.jsbn || {};\n\n// Bits per digit\nvar dbits;\n\n// JavaScript engine analysis\nvar canary = 0xdeadbeefcafe;\nvar j_lm = ((canary&0xffffff)==0xefcafe);\n\n// (public) Constructor\nfunction BigInteger(a,b,c) {\n this.data = [];\n if(a != null)\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\n else this.fromString(a,b);\n}\nforge.jsbn.BigInteger = BigInteger;\n\n// return new, unset BigInteger\nfunction nbi() { return new BigInteger(null); }\n\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i,x,w,j,c,n) {\n while(--n >= 0) {\n var v = x*this.data[i++]+w.data[j]+c;\n c = Math.floor(v/0x4000000);\n w.data[j++] = v&0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i,x,w,j,c,n) {\n var xl = x&0x7fff, xh = x>>15;\n while(--n >= 0) {\n var l = this.data[i]&0x7fff;\n var h = this.data[i++]>>15;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\n w.data[j++] = l&0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i,x,w,j,c,n) {\n var xl = x&0x3fff, xh = x>>14;\n while(--n >= 0) {\n var l = this.data[i]&0x3fff;\n var h = this.data[i++]>>14;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;\n c = (l>>28)+(m>>14)+xh*h;\n w.data[j++] = l&0xfffffff;\n }\n return c;\n}\n\n// node.js (no browser)\nif(typeof(navigator) === 'undefined')\n{\n BigInteger.prototype.am = am3;\n dbits = 28;\n} else if(j_lm && (navigator.appName == \"Microsoft Internet Explorer\")) {\n BigInteger.prototype.am = am2;\n dbits = 30;\n} else if(j_lm && (navigator.appName != \"Netscape\")) {\n BigInteger.prototype.am = am1;\n dbits = 26;\n} else { // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\n\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}\n\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = (x<0)?-1:0;\n if(x > 0) this.data[0] = x;\n else if(x < -1) this.data[0] = x+this.DV;\n else this.t = 0;\n}\n\n// return bigint initialized to value\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\n\n// (protected) set from string and radix\nfunction bnpFromString(s,b) {\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 256) k = 8; // byte array\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else { this.fromRadix(s,b); return; }\n this.t = 0;\n this.s = 0;\n var i = s.length, mi = false, sh = 0;\n while(--i >= 0) {\n var x = (k==8)?s[i]&0xff:intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\") mi = true;\n continue;\n }\n mi = false;\n if(sh == 0)\n this.data[this.t++] = x;\n else if(sh+k > this.DB) {\n this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));\n } else\n this.data[this.t-1] |= x<= this.DB) sh -= this.DB;\n }\n if(k == 8 && (s[0]&0x80) != 0) {\n this.s = -1;\n if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t;\n}\n\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if(this.s < 0) return \"-\"+this.negate().toString(b);\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else return this.toRadix(b);\n var km = (1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }\n while(i >= 0) {\n if(p < k) {\n d = (this.data[i]&((1<>(p+=this.DB-k);\n } else {\n d = (this.data[i]>>(p-=k))&km;\n if(p <= 0) { p += this.DB; --i; }\n }\n if(d > 0) m = true;\n if(m) r += int2char(d);\n }\n }\n return m?r:\"0\";\n}\n\n// (public) -this\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\n\n// (public) |this|\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\n\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n var r = this.s-a.s;\n if(r != 0) return r;\n var i = this.t;\n r = i-a.t;\n if(r != 0) return (this.s<0)?-r:r;\n while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;\n return 0;\n}\n\n// returns bit length of the integer x\nfunction nbits(x) {\n var r = 1, t;\n if((t=x>>>16) != 0) { x = t; r += 16; }\n if((t=x>>8) != 0) { x = t; r += 8; }\n if((t=x>>4) != 0) { x = t; r += 4; }\n if((t=x>>2) != 0) { x = t; r += 2; }\n if((t=x>>1) != 0) { x = t; r += 1; }\n return r;\n}\n\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if(this.t <= 0) return 0;\n return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));\n}\n\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n,r) {\n var i;\n for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];\n for(i = n-1; i >= 0; --i) r.data[i] = 0;\n r.t = this.t+n;\n r.s = this.s;\n}\n\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n,r) {\n for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];\n r.t = Math.max(this.t-n,0);\n r.s = this.s;\n}\n\n// (protected) r = this << n\nfunction bnpLShiftTo(n,r) {\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<= 0; --i) {\n r.data[i+ds+1] = (this.data[i]>>cbs)|c;\n c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0;\n r.data[ds] = c;\n r.t = this.t+ds+1;\n r.s = this.s;\n r.clamp();\n}\n\n// (protected) r = this >> n\nfunction bnpRShiftTo(n,r) {\n r.s = this.s;\n var ds = Math.floor(n/this.DB);\n if(ds >= this.t) { r.t = 0; return; }\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<>bs;\n for(var i = ds+1; i < this.t; ++i) {\n r.data[i-ds-1] |= (this.data[i]&bm)<>bs;\n }\n if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB;\n }\n if(a.t < this.t) {\n c -= a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n } else {\n c += this.s;\n while(i < a.t) {\n c -= a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = (c<0)?-1:0;\n if(c < -1) r.data[i++] = this.DV+c;\n else if(c > 0) r.data[i++] = c;\n r.t = i;\n r.clamp();\n}\n\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a,r) {\n var x = this.abs(), y = a.abs();\n var i = x.t;\n r.t = i+y.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);\n r.s = 0;\n r.clamp();\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\n}\n\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n var x = this.abs();\n var i = r.t = 2*x.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < x.t-1; ++i) {\n var c = x.am(i,x.data[i],r,2*i,0,1);\n if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\n r.data[i+x.t] -= x.DV;\n r.data[i+x.t+1] = 1;\n }\n }\n if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);\n r.s = 0;\n r.clamp();\n}\n\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m,q,r) {\n var pm = m.abs();\n if(pm.t <= 0) return;\n var pt = this.abs();\n if(pt.t < pm.t) {\n if(q != null) q.fromInt(0);\n if(r != null) this.copyTo(r);\n return;\n }\n if(r == null) r = nbi();\n var y = nbi(), ts = this.s, ms = m.s;\n var nsh = this.DB-nbits(pm.data[pm.t-1]);\t// normalize modulus\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }\n var ys = y.t;\n var y0 = y.data[ys-1];\n if(y0 == 0) return;\n var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0);\n var d1 = this.FV/yt, d2 = (1<= 0) {\n r.data[r.t++] = 1;\n r.subTo(t,r);\n }\n BigInteger.ONE.dlShiftTo(ys,t);\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\n while(y.t < ys) y.data[y.t++] = 0;\n while(--j >= 0) {\n // Estimate quotient digit\n var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);\n if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\n y.dlShiftTo(j,t);\n r.subTo(t,r);\n while(r.data[i] < --qd) r.subTo(t,r);\n }\n }\n if(q != null) {\n r.drShiftTo(ys,q);\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\n }\n r.t = ys;\n r.clamp();\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\n}\n\n// (public) this mod a\nfunction bnMod(a) {\n var r = nbi();\n this.abs().divRemTo(a,null,r);\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\n return r;\n}\n\n// Modular reduction using \"classic\" algorithm\nfunction Classic(m) { this.m = m; }\nfunction cConvert(x) {\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\n else return x;\n}\nfunction cRevert(x) { return x; }\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\nClassic.prototype.convert = cConvert;\nClassic.prototype.revert = cRevert;\nClassic.prototype.reduce = cReduce;\nClassic.prototype.mulTo = cMulTo;\nClassic.prototype.sqrTo = cSqrTo;\n\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if(this.t < 1) return 0;\n var x = this.data[0];\n if((x&1) == 0) return 0;\n var y = x&3;\t\t// y == 1/x mod 2^2\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return (y>0)?this.DV-y:-y;\n}\n\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp&0x7fff;\n this.mph = this.mp>>15;\n this.um = (1<<(m.DB-15))-1;\n this.mt2 = 2*m.t;\n}\n\n// xR mod m\nfunction montConvert(x) {\n var r = nbi();\n x.abs().dlShiftTo(this.m.t,r);\n r.divRemTo(this.m,null,r);\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\n return r;\n}\n\n// x/R mod m\nfunction montRevert(x) {\n var r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while(x.t <= this.mt2)\t// pad x so am has enough room later\n x.data[x.t++] = 0;\n for(var i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x.data[i]*mp mod DV\n var j = x.data[i]&0x7fff;\n var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i+this.m.t;\n x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);\n // propagate carry\n while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }\n }\n x.clamp();\n x.drShiftTo(this.m.t,x);\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n\n// (protected) true iff this is even\nfunction bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }\n\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\nfunction bnpExp(e,z) {\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\n g.copyTo(r);\n while(--i >= 0) {\n z.sqrTo(r,r2);\n if((e&(1< 0) z.mulTo(r2,g,r);\n else { var t = r; r = r2; r2 = t; }\n }\n return z.revert(r);\n}\n\n// (public) this^e % m, 0 <= e < 2^32\nfunction bnModPowInt(e,m) {\n var z;\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\n return this.exp(e,z);\n}\n\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.isEven = bnpIsEven;\nBigInteger.prototype.exp = bnpExp;\n\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.modPowInt = bnModPowInt;\n\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\n// jsbn2 lib\n\n//Copyright (c) 2005-2009 Tom Wu\n//All Rights Reserved.\n//See \"LICENSE\" for details (See jsbn.js for LICENSE).\n\n//Extended JavaScript BN functions, required for RSA private ops.\n\n//Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\n\n//(public)\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\n\n//(public) return value as integer\nfunction bnIntValue() {\nif(this.s < 0) {\n if(this.t == 1) return this.data[0]-this.DV;\n else if(this.t == 0) return -1;\n} else if(this.t == 1) return this.data[0];\nelse if(this.t == 0) return 0;\n// assumes 16 < DB < 32\nreturn ((this.data[1]&((1<<(32-this.DB))-1))<>24; }\n\n//(public) return value as short (assumes DB>=16)\nfunction bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }\n\n//(protected) return x s.t. r^x < DV\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\n\n//(public) 0 if this == 0, 1 if this > 0\nfunction bnSigNum() {\nif(this.s < 0) return -1;\nelse if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;\nelse return 1;\n}\n\n//(protected) convert to radix string\nfunction bnpToRadix(b) {\nif(b == null) b = 10;\nif(this.signum() == 0 || b < 2 || b > 36) return \"0\";\nvar cs = this.chunkSize(b);\nvar a = Math.pow(b,cs);\nvar d = nbv(a), y = nbi(), z = nbi(), r = \"\";\nthis.divRemTo(d,y,z);\nwhile(y.signum() > 0) {\n r = (a+z.intValue()).toString(b).substr(1) + r;\n y.divRemTo(d,y,z);\n}\nreturn z.intValue().toString(b) + r;\n}\n\n//(protected) convert from radix string\nfunction bnpFromRadix(s,b) {\nthis.fromInt(0);\nif(b == null) b = 10;\nvar cs = this.chunkSize(b);\nvar d = Math.pow(b,cs), mi = false, j = 0, w = 0;\nfor(var i = 0; i < s.length; ++i) {\n var x = intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\n continue;\n }\n w = b*w+x;\n if(++j >= cs) {\n this.dMultiply(d);\n this.dAddOffset(w,0);\n j = 0;\n w = 0;\n }\n}\nif(j > 0) {\n this.dMultiply(Math.pow(b,j));\n this.dAddOffset(w,0);\n}\nif(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n//(protected) alternate constructor\nfunction bnpFromNumber(a,b,c) {\nif(\"number\" == typeof b) {\n // new BigInteger(int,int,RNG)\n if(a < 2) this.fromInt(1);\n else {\n this.fromNumber(a,c);\n if(!this.testBit(a-1)) // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\n if(this.isEven()) this.dAddOffset(1,0); // force odd\n while(!this.isProbablePrime(b)) {\n this.dAddOffset(2,0);\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\n }\n }\n} else {\n // new BigInteger(int,RNG)\n var x = new Array(), t = a&7;\n x.length = (a>>3)+1;\n b.nextBytes(x);\n if(t > 0) x[0] &= ((1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)\n r[k++] = d|(this.s<<(this.DB-p));\n while(i >= 0) {\n if(p < 8) {\n d = (this.data[i]&((1<>(p+=this.DB-8);\n } else {\n d = (this.data[i]>>(p-=8))&0xff;\n if(p <= 0) { p += this.DB; --i; }\n }\n if((d&0x80) != 0) d |= -256;\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\n if(k > 0 || d != this.s) r[k++] = d;\n }\n}\nreturn r;\n}\n\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\n\n//(protected) r = this op a (bitwise)\nfunction bnpBitwiseTo(a,op,r) {\nvar i, f, m = Math.min(a.t,this.t);\nfor(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);\nif(a.t < this.t) {\n f = a.s&this.DM;\n for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);\n r.t = this.t;\n} else {\n f = this.s&this.DM;\n for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);\n r.t = a.t;\n}\nr.s = op(this.s,a.s);\nr.clamp();\n}\n\n//(public) this & a\nfunction op_and(x,y) { return x&y; }\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\n\n//(public) this | a\nfunction op_or(x,y) { return x|y; }\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\n\n//(public) this ^ a\nfunction op_xor(x,y) { return x^y; }\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\n\n//(public) this & ~a\nfunction op_andnot(x,y) { return x&~y; }\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\n\n//(public) ~this\nfunction bnNot() {\nvar r = nbi();\nfor(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];\nr.t = this.t;\nr.s = ~this.s;\nreturn r;\n}\n\n//(public) this << n\nfunction bnShiftLeft(n) {\nvar r = nbi();\nif(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\nreturn r;\n}\n\n//(public) this >> n\nfunction bnShiftRight(n) {\nvar r = nbi();\nif(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\nreturn r;\n}\n\n//return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x) {\nif(x == 0) return -1;\nvar r = 0;\nif((x&0xffff) == 0) { x >>= 16; r += 16; }\nif((x&0xff) == 0) { x >>= 8; r += 8; }\nif((x&0xf) == 0) { x >>= 4; r += 4; }\nif((x&3) == 0) { x >>= 2; r += 2; }\nif((x&1) == 0) ++r;\nreturn r;\n}\n\n//(public) returns index of lowest 1-bit (or -1 if none)\nfunction bnGetLowestSetBit() {\nfor(var i = 0; i < this.t; ++i)\n if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);\nif(this.s < 0) return this.t*this.DB;\nreturn -1;\n}\n\n//return number of 1 bits in x\nfunction cbit(x) {\nvar r = 0;\nwhile(x != 0) { x &= x-1; ++r; }\nreturn r;\n}\n\n//(public) return number of set bits\nfunction bnBitCount() {\nvar r = 0, x = this.s&this.DM;\nfor(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);\nreturn r;\n}\n\n//(public) true iff nth bit is set\nfunction bnTestBit(n) {\nvar j = Math.floor(n/this.DB);\nif(j >= this.t) return(this.s!=0);\nreturn((this.data[j]&(1<<(n%this.DB)))!=0);\n}\n\n//(protected) this op (1<>= this.DB;\n}\nif(a.t < this.t) {\n c += a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n} else {\n c += this.s;\n while(i < a.t) {\n c += a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += a.s;\n}\nr.s = (c<0)?-1:0;\nif(c > 0) r.data[i++] = c;\nelse if(c < -1) r.data[i++] = this.DV+c;\nr.t = i;\nr.clamp();\n}\n\n//(public) this + a\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\n\n//(public) this - a\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\n\n//(public) this * a\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\n\n//(public) this / a\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\n\n//(public) this % a\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\n\n//(public) [this/a,this%a]\nfunction bnDivideAndRemainder(a) {\nvar q = nbi(), r = nbi();\nthis.divRemTo(a,q,r);\nreturn new Array(q,r);\n}\n\n//(protected) this *= n, this >= 0, 1 < n < DV\nfunction bnpDMultiply(n) {\nthis.data[this.t] = this.am(0,n-1,this,0,0,this.t);\n++this.t;\nthis.clamp();\n}\n\n//(protected) this += n << w words, this >= 0\nfunction bnpDAddOffset(n,w) {\nif(n == 0) return;\nwhile(this.t <= w) this.data[this.t++] = 0;\nthis.data[w] += n;\nwhile(this.data[w] >= this.DV) {\n this.data[w] -= this.DV;\n if(++w >= this.t) this.data[this.t++] = 0;\n ++this.data[w];\n}\n}\n\n//A \"null\" reducer\nfunction NullExp() {}\nfunction nNop(x) { return x; }\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\nfunction nSqrTo(x,r) { x.squareTo(r); }\n\nNullExp.prototype.convert = nNop;\nNullExp.prototype.revert = nNop;\nNullExp.prototype.mulTo = nMulTo;\nNullExp.prototype.sqrTo = nSqrTo;\n\n//(public) this^e\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\n\n//(protected) r = lower n words of \"this * a\", a.t <= n\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyLowerTo(a,n,r) {\nvar i = Math.min(this.t+a.t,n);\nr.s = 0; // assumes a,this >= 0\nr.t = i;\nwhile(i > 0) r.data[--i] = 0;\nvar j;\nfor(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);\nfor(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);\nr.clamp();\n}\n\n//(protected) r = \"this * a\" without lower n words, n > 0\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyUpperTo(a,n,r) {\n--n;\nvar i = r.t = this.t+a.t-n;\nr.s = 0; // assumes a,this >= 0\nwhile(--i >= 0) r.data[i] = 0;\nfor(i = Math.max(n-this.t,0); i < a.t; ++i)\n r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);\nr.clamp();\nr.drShiftTo(1,r);\n}\n\n//Barrett modular reduction\nfunction Barrett(m) {\n// setup Barrett\nthis.r2 = nbi();\nthis.q3 = nbi();\nBigInteger.ONE.dlShiftTo(2*m.t,this.r2);\nthis.mu = this.r2.divide(m);\nthis.m = m;\n}\n\nfunction barrettConvert(x) {\nif(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\nelse if(x.compareTo(this.m) < 0) return x;\nelse { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\n}\n\nfunction barrettRevert(x) { return x; }\n\n//x = x mod m (HAC 14.42)\nfunction barrettReduce(x) {\nx.drShiftTo(this.m.t-1,this.r2);\nif(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\nthis.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\nthis.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\nwhile(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\nx.subTo(this.r2,x);\nwhile(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n//r = x^2 mod m; x != r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n//r = x*y mod m; x,y != r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nBarrett.prototype.convert = barrettConvert;\nBarrett.prototype.revert = barrettRevert;\nBarrett.prototype.reduce = barrettReduce;\nBarrett.prototype.mulTo = barrettMulTo;\nBarrett.prototype.sqrTo = barrettSqrTo;\n\n//(public) this^e % m (HAC 14.85)\nfunction bnModPow(e,m) {\nvar i = e.bitLength(), k, r = nbv(1), z;\nif(i <= 0) return r;\nelse if(i < 18) k = 1;\nelse if(i < 48) k = 3;\nelse if(i < 144) k = 4;\nelse if(i < 768) k = 5;\nelse k = 6;\nif(i < 8)\n z = new Classic(m);\nelse if(m.isEven())\n z = new Barrett(m);\nelse\n z = new Montgomery(m);\n\n// precomputation\nvar g = new Array(), n = 3, k1 = k-1, km = (1< 1) {\n var g2 = nbi();\n z.sqrTo(g[1],g2);\n while(n <= km) {\n g[n] = nbi();\n z.mulTo(g2,g[n-2],g[n]);\n n += 2;\n }\n}\n\nvar j = e.t-1, w, is1 = true, r2 = nbi(), t;\ni = nbits(e.data[j])-1;\nwhile(j >= 0) {\n if(i >= k1) w = (e.data[j]>>(i-k1))&km;\n else {\n w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);\n if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);\n }\n\n n = k;\n while((w&1) == 0) { w >>= 1; --n; }\n if((i -= n) < 0) { i += this.DB; --j; }\n if(is1) { // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n } else {\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\n z.mulTo(r2,g[w],r);\n }\n\n while(j >= 0 && (e.data[j]&(1< 0) {\n x.rShiftTo(g,x);\n y.rShiftTo(g,y);\n}\nwhile(x.signum() > 0) {\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\n if(x.compareTo(y) >= 0) {\n x.subTo(y,x);\n x.rShiftTo(1,x);\n } else {\n y.subTo(x,y);\n y.rShiftTo(1,y);\n }\n}\nif(g > 0) y.lShiftTo(g,y);\nreturn y;\n}\n\n//(protected) this % n, n < 2^26\nfunction bnpModInt(n) {\nif(n <= 0) return 0;\nvar d = this.DV%n, r = (this.s<0)?n-1:0;\nif(this.t > 0)\n if(d == 0) r = this.data[0]%n;\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;\nreturn r;\n}\n\n//(public) 1/this % m (HAC 14.61)\nfunction bnModInverse(m) {\nvar ac = m.isEven();\nif((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\nvar u = m.clone(), v = this.clone();\nvar a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\nwhile(u.signum() != 0) {\n while(u.isEven()) {\n u.rShiftTo(1,u);\n if(ac) {\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\n a.rShiftTo(1,a);\n } else if(!b.isEven()) b.subTo(m,b);\n b.rShiftTo(1,b);\n }\n while(v.isEven()) {\n v.rShiftTo(1,v);\n if(ac) {\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\n c.rShiftTo(1,c);\n } else if(!d.isEven()) d.subTo(m,d);\n d.rShiftTo(1,d);\n }\n if(u.compareTo(v) >= 0) {\n u.subTo(v,u);\n if(ac) a.subTo(c,a);\n b.subTo(d,b);\n } else {\n v.subTo(u,v);\n if(ac) c.subTo(a,c);\n d.subTo(b,d);\n }\n}\nif(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\nif(d.compareTo(m) >= 0) return d.subtract(m);\nif(d.signum() < 0) d.addTo(m,d); else return d;\nif(d.signum() < 0) return d.add(m); else return d;\n}\n\nvar lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\n\n//(public) test primality with certainty >= 1-.5^t\nfunction bnIsProbablePrime(t) {\nvar i, x = this.abs();\nif(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {\n for(i = 0; i < lowprimes.length; ++i)\n if(x.data[0] == lowprimes[i]) return true;\n return false;\n}\nif(x.isEven()) return false;\ni = 1;\nwhile(i < lowprimes.length) {\n var m = lowprimes[i], j = i+1;\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\n m = x.modInt(m);\n while(i < j) if(m%lowprimes[i++] == 0) return false;\n}\nreturn x.millerRabin(t);\n}\n\n//(protected) true if probably prime (HAC 4.24, Miller-Rabin)\nfunction bnpMillerRabin(t) {\nvar n1 = this.subtract(BigInteger.ONE);\nvar k = n1.getLowestSetBit();\nif(k <= 0) return false;\nvar r = n1.shiftRight(k);\nvar prng = bnGetPrng();\nvar a;\nfor(var i = 0; i < t; ++i) {\n // select witness 'a' at random from between 1 and n1\n do {\n a = new BigInteger(this.bitLength(), prng);\n }\n while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);\n var y = a.modPow(r,this);\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\n var j = 1;\n while(j++ < k && y.compareTo(n1) != 0) {\n y = y.modPowInt(2,this);\n if(y.compareTo(BigInteger.ONE) == 0) return false;\n }\n if(y.compareTo(n1) != 0) return false;\n }\n}\nreturn true;\n}\n\n// get pseudo random number generator\nfunction bnGetPrng() {\n // create prng with api that matches BigInteger secure random\n return {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n for(var i = 0; i < x.length; ++i) {\n x[i] = Math.floor(Math.random() * 0x0100);\n }\n }\n };\n}\n\n//protected\nBigInteger.prototype.chunkSize = bnpChunkSize;\nBigInteger.prototype.toRadix = bnpToRadix;\nBigInteger.prototype.fromRadix = bnpFromRadix;\nBigInteger.prototype.fromNumber = bnpFromNumber;\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\nBigInteger.prototype.changeBit = bnpChangeBit;\nBigInteger.prototype.addTo = bnpAddTo;\nBigInteger.prototype.dMultiply = bnpDMultiply;\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\nBigInteger.prototype.modInt = bnpModInt;\nBigInteger.prototype.millerRabin = bnpMillerRabin;\n\n//public\nBigInteger.prototype.clone = bnClone;\nBigInteger.prototype.intValue = bnIntValue;\nBigInteger.prototype.byteValue = bnByteValue;\nBigInteger.prototype.shortValue = bnShortValue;\nBigInteger.prototype.signum = bnSigNum;\nBigInteger.prototype.toByteArray = bnToByteArray;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.min = bnMin;\nBigInteger.prototype.max = bnMax;\nBigInteger.prototype.and = bnAnd;\nBigInteger.prototype.or = bnOr;\nBigInteger.prototype.xor = bnXor;\nBigInteger.prototype.andNot = bnAndNot;\nBigInteger.prototype.not = bnNot;\nBigInteger.prototype.shiftLeft = bnShiftLeft;\nBigInteger.prototype.shiftRight = bnShiftRight;\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\nBigInteger.prototype.bitCount = bnBitCount;\nBigInteger.prototype.testBit = bnTestBit;\nBigInteger.prototype.setBit = bnSetBit;\nBigInteger.prototype.clearBit = bnClearBit;\nBigInteger.prototype.flipBit = bnFlipBit;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.remainder = bnRemainder;\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\nBigInteger.prototype.modPow = bnModPow;\nBigInteger.prototype.modInverse = bnModInverse;\nBigInteger.prototype.pow = bnPow;\nBigInteger.prototype.gcd = bnGCD;\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\n\n//BigInteger interfaces not implemented in jsbn:\n\n//BigInteger(int signum, byte[] magnitude)\n//double doubleValue()\n//float floatValue()\n//int hashCode()\n//long longValue()\n//static BigInteger valueOf(long val)\n","/**\n * Javascript implementation of RSA-KEM.\n *\n * @author Lautaro Cozzani Rodriguez\n * @author Dave Longley\n *\n * Copyright (c) 2014 Lautaro Cozzani \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./jsbn');\n\nmodule.exports = forge.kem = forge.kem || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n/**\n * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2.\n */\nforge.kem.rsa = {};\n\n/**\n * Creates an RSA KEM API object for generating a secret asymmetric key.\n *\n * The symmetric key may be generated via a call to 'encrypt', which will\n * produce a ciphertext to be transmitted to the recipient and a key to be\n * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which\n * will produce the same secret key for the recipient to use to decrypt a\n * message that was encrypted with the secret key.\n *\n * @param kdf the KDF API to use (eg: new forge.kem.kdf1()).\n * @param options the options to use.\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n */\nforge.kem.rsa.create = function(kdf, options) {\n options = options || {};\n var prng = options.prng || forge.random;\n\n var kem = {};\n\n /**\n * Generates a secret key and its encapsulation.\n *\n * @param publicKey the RSA public key to encrypt with.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return an object with:\n * encapsulation: the ciphertext for generating the secret key, as a\n * binary-encoded string of bytes.\n * key: the secret key to use for encrypting a message.\n */\n kem.encrypt = function(publicKey, keyLength) {\n // generate a random r where 1 < r < n\n var byteLength = Math.ceil(publicKey.n.bitLength() / 8);\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(prng.getBytesSync(byteLength)),\n 16).mod(publicKey.n);\n } while(r.compareTo(BigInteger.ONE) <= 0);\n\n // prepend r with zeros\n r = forge.util.hexToBytes(r.toString(16));\n var zeros = byteLength - r.length;\n if(zeros > 0) {\n r = forge.util.fillString(String.fromCharCode(0), zeros) + r;\n }\n\n // encrypt the random\n var encapsulation = publicKey.encrypt(r, 'NONE');\n\n // generate the secret key\n var key = kdf.generate(r, keyLength);\n\n return {encapsulation: encapsulation, key: key};\n };\n\n /**\n * Decrypts an encapsulated secret key.\n *\n * @param privateKey the RSA private key to decrypt with.\n * @param encapsulation the ciphertext for generating the secret key, as\n * a binary-encoded string of bytes.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return the secret key as a binary-encoded string of bytes.\n */\n kem.decrypt = function(privateKey, encapsulation, keyLength) {\n // decrypt the encapsulation and generate the secret key\n var r = privateKey.decrypt(encapsulation, 'NONE');\n return kdf.generate(r, keyLength);\n };\n\n return kem;\n};\n\n// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API?\n\n/**\n * Creates a key derivation API object that implements KDF1 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF1 API object.\n */\nforge.kem.kdf1 = function(md, digestLength) {\n _createKDF(this, md, 0, digestLength || md.digestLength);\n};\n\n/**\n * Creates a key derivation API object that implements KDF2 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF2 API object.\n */\nforge.kem.kdf2 = function(md, digestLength) {\n _createKDF(this, md, 1, digestLength || md.digestLength);\n};\n\n/**\n * Creates a KDF1 or KDF2 API object.\n *\n * @param md the hash API to use.\n * @param counterStart the starting index for the counter.\n * @param digestLength the digest length to use.\n *\n * @return the KDF API object.\n */\nfunction _createKDF(kdf, md, counterStart, digestLength) {\n /**\n * Generate a key of the specified length.\n *\n * @param x the binary-encoded byte string to generate a key from.\n * @param length the number of bytes to generate (the size of the key).\n *\n * @return the key as a binary-encoded string.\n */\n kdf.generate = function(x, length) {\n var key = new forge.util.ByteBuffer();\n\n // run counter from counterStart to ceil(length / Hash.len)\n var k = Math.ceil(length / digestLength) + counterStart;\n\n var c = new forge.util.ByteBuffer();\n for(var i = counterStart; i < k; ++i) {\n // I2OSP(i, 4): convert counter to an octet string of 4 octets\n c.putInt32(i);\n\n // digest 'x' and the counter and add the result to the key\n md.start();\n md.update(x + c.getBytes());\n var hash = md.digest();\n key.putBytes(hash.getBytes(digestLength));\n }\n\n // truncate to the correct key length\n key.truncate(key.length() - length);\n return key.getBytes();\n };\n}\n","/**\n * Cross-browser support for logging in a web application.\n *\n * @author David I. Lehn \n *\n * Copyright (c) 2008-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n/* LOG API */\nmodule.exports = forge.log = forge.log || {};\n\n/**\n * Application logging system.\n *\n * Each logger level available as it's own function of the form:\n * forge.log.level(category, args...)\n * The category is an arbitrary string, and the args are the same as\n * Firebug's console.log API. By default the call will be output as:\n * 'LEVEL [category] , args[1], ...'\n * This enables proper % formatting via the first argument.\n * Each category is enabled by default but can be enabled or disabled with\n * the setCategoryEnabled() function.\n */\n// list of known levels\nforge.log.levels = [\n 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max'];\n// info on the levels indexed by name:\n// index: level index\n// name: uppercased display name\nvar sLevelInfo = {};\n// list of loggers\nvar sLoggers = [];\n/**\n * Standard console logger. If no console support is enabled this will\n * remain null. Check before using.\n */\nvar sConsoleLogger = null;\n\n// logger flags\n/**\n * Lock the level at the current value. Used in cases where user config may\n * set the level such that only critical messages are seen but more verbose\n * messages are needed for debugging or other purposes.\n */\nforge.log.LEVEL_LOCKED = (1 << 1);\n/**\n * Always call log function. By default, the logging system will check the\n * message level against logger.level before calling the log function. This\n * flag allows the function to do its own check.\n */\nforge.log.NO_LEVEL_CHECK = (1 << 2);\n/**\n * Perform message interpolation with the passed arguments. \"%\" style\n * fields in log messages will be replaced by arguments as needed. Some\n * loggers, such as Firebug, may do this automatically. The original log\n * message will be available as 'message' and the interpolated version will\n * be available as 'fullMessage'.\n */\nforge.log.INTERPOLATE = (1 << 3);\n\n// setup each log level\nfor(var i = 0; i < forge.log.levels.length; ++i) {\n var level = forge.log.levels[i];\n sLevelInfo[level] = {\n index: i,\n name: level.toUpperCase()\n };\n}\n\n/**\n * Message logger. Will dispatch a message to registered loggers as needed.\n *\n * @param message message object\n */\nforge.log.logMessage = function(message) {\n var messageLevelIndex = sLevelInfo[message.level].index;\n for(var i = 0; i < sLoggers.length; ++i) {\n var logger = sLoggers[i];\n if(logger.flags & forge.log.NO_LEVEL_CHECK) {\n logger.f(message);\n } else {\n // get logger level\n var loggerLevelIndex = sLevelInfo[logger.level].index;\n // check level\n if(messageLevelIndex <= loggerLevelIndex) {\n // message critical enough, call logger\n logger.f(logger, message);\n }\n }\n }\n};\n\n/**\n * Sets the 'standard' key on a message object to:\n * \"LEVEL [category] \" + message\n *\n * @param message a message log object\n */\nforge.log.prepareStandard = function(message) {\n if(!('standard' in message)) {\n message.standard =\n sLevelInfo[message.level].name +\n //' ' + +message.timestamp +\n ' [' + message.category + '] ' +\n message.message;\n }\n};\n\n/**\n * Sets the 'full' key on a message object to the original message\n * interpolated via % formatting with the message arguments.\n *\n * @param message a message log object.\n */\nforge.log.prepareFull = function(message) {\n if(!('full' in message)) {\n // copy args and insert message at the front\n var args = [message.message];\n args = args.concat([] || message['arguments']);\n // format the message\n message.full = forge.util.format.apply(this, args);\n }\n};\n\n/**\n * Applies both preparseStandard() and prepareFull() to a message object and\n * store result in 'standardFull'.\n *\n * @param message a message log object.\n */\nforge.log.prepareStandardFull = function(message) {\n if(!('standardFull' in message)) {\n // FIXME implement 'standardFull' logging\n forge.log.prepareStandard(message);\n message.standardFull = message.standard;\n }\n};\n\n// create log level functions\nif(true) {\n // levels for which we want functions\n var levels = ['error', 'warning', 'info', 'debug', 'verbose'];\n for(var i = 0; i < levels.length; ++i) {\n // wrap in a function to ensure proper level var is passed\n (function(level) {\n // create function for this level\n forge.log[level] = function(category, message/*, args...*/) {\n // convert arguments to real array, remove category and message\n var args = Array.prototype.slice.call(arguments).slice(2);\n // create message object\n // Note: interpolation and standard formatting is done lazily\n var msg = {\n timestamp: new Date(),\n level: level,\n category: category,\n message: message,\n 'arguments': args\n /*standard*/\n /*full*/\n /*fullMessage*/\n };\n // process this message\n forge.log.logMessage(msg);\n };\n })(levels[i]);\n }\n}\n\n/**\n * Creates a new logger with specified custom logging function.\n *\n * The logging function has a signature of:\n * function(logger, message)\n * logger: current logger\n * message: object:\n * level: level id\n * category: category\n * message: string message\n * arguments: Array of extra arguments\n * fullMessage: interpolated message and arguments if INTERPOLATE flag set\n *\n * @param logFunction a logging function which takes a log message object\n * as a parameter.\n *\n * @return a logger object.\n */\nforge.log.makeLogger = function(logFunction) {\n var logger = {\n flags: 0,\n f: logFunction\n };\n forge.log.setLevel(logger, 'none');\n return logger;\n};\n\n/**\n * Sets the current log level on a logger.\n *\n * @param logger the target logger.\n * @param level the new maximum log level as a string.\n *\n * @return true if set, false if not.\n */\nforge.log.setLevel = function(logger, level) {\n var rval = false;\n if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) {\n for(var i = 0; i < forge.log.levels.length; ++i) {\n var aValidLevel = forge.log.levels[i];\n if(level == aValidLevel) {\n // set level\n logger.level = level;\n rval = true;\n break;\n }\n }\n }\n\n return rval;\n};\n\n/**\n * Locks the log level at its current value.\n *\n * @param logger the target logger.\n * @param lock boolean lock value, default to true.\n */\nforge.log.lock = function(logger, lock) {\n if(typeof lock === 'undefined' || lock) {\n logger.flags |= forge.log.LEVEL_LOCKED;\n } else {\n logger.flags &= ~forge.log.LEVEL_LOCKED;\n }\n};\n\n/**\n * Adds a logger.\n *\n * @param logger the logger object.\n */\nforge.log.addLogger = function(logger) {\n sLoggers.push(logger);\n};\n\n// setup the console logger if possible, else create fake console.log\nif(typeof(console) !== 'undefined' && 'log' in console) {\n var logger;\n if(console.error && console.warn && console.info && console.debug) {\n // looks like Firebug-style logging is available\n // level handlers map\n var levelHandlers = {\n error: console.error,\n warning: console.warn,\n info: console.info,\n debug: console.debug,\n verbose: console.debug\n };\n var f = function(logger, message) {\n forge.log.prepareStandard(message);\n var handler = levelHandlers[message.level];\n // prepend standard message and concat args\n var args = [message.standard];\n args = args.concat(message['arguments'].slice());\n // apply to low-level console function\n handler.apply(console, args);\n };\n logger = forge.log.makeLogger(f);\n } else {\n // only appear to have basic console.log\n var f = function(logger, message) {\n forge.log.prepareStandardFull(message);\n console.log(message.standardFull);\n };\n logger = forge.log.makeLogger(f);\n }\n forge.log.setLevel(logger, 'debug');\n forge.log.addLogger(logger);\n sConsoleLogger = logger;\n} else {\n // define fake console.log to avoid potential script errors on\n // browsers that do not have console logging\n console = {\n log: function() {}\n };\n}\n\n/*\n * Check for logging control query vars in current URL.\n *\n * console.level=\n * Set's the console log level by name. Useful to override defaults and\n * allow more verbose logging before a user config is loaded.\n *\n * console.lock=\n * Lock the console log level at whatever level it is set at. This is run\n * after console.level is processed. Useful to force a level of verbosity\n * that could otherwise be limited by a user config.\n */\nif(sConsoleLogger !== null &&\n typeof window !== 'undefined' && window.location\n) {\n var query = new URL(window.location.href).searchParams;\n if(query.has('console.level')) {\n // set with last value\n forge.log.setLevel(\n sConsoleLogger, query.get('console.level').slice(-1)[0]);\n }\n if(query.has('console.lock')) {\n // set with last value\n var lock = query.get('console.lock').slice(-1)[0];\n if(lock == 'true') {\n forge.log.lock(sConsoleLogger);\n }\n }\n}\n\n// provide public access to console logger\nforge.log.consoleLogger = sConsoleLogger;\n","/**\n * Node.js module for all known Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nmodule.exports = require('./md');\n\nrequire('./md5');\nrequire('./sha1');\nrequire('./sha256');\nrequire('./sha512');\n","/**\n * Node.js module for Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nmodule.exports = forge.md = forge.md || {};\nforge.md.algorithms = forge.md.algorithms || {};\n","/**\n * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar md5 = module.exports = forge.md5 = forge.md5 || {};\nforge.md.md5 = forge.md.algorithms.md5 = md5;\n\n/**\n * Creates an MD5 message digest object.\n *\n * @return a message digest object.\n */\nmd5.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // MD5 state contains four 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(16);\n\n // message digest object\n var md = {\n algorithm: 'md5',\n blockLength: 64,\n digestLength: 16,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = (len[1] / 0x100000000) >>> 0;\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate MD5 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in little-endian order; since length\n // is stored in bytes we multiply by 8 and add carry\n var bits, carry = 0;\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n bits = md.fullMessageLength[i] * 8 + carry;\n carry = (bits / 0x100000000) >>> 0;\n finalBlock.putInt32Le(bits >>> 0);\n }\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32Le(s2.h0);\n rval.putInt32Le(s2.h1);\n rval.putInt32Le(s2.h2);\n rval.putInt32Le(s2.h3);\n return rval;\n };\n\n return md;\n};\n\n// padding, constant tables for calculating md5\nvar _padding = null;\nvar _g = null;\nvar _r = null;\nvar _k = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // g values\n _g = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12,\n 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2,\n 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9];\n\n // rounds table\n _r = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];\n\n // get the result of abs(sin(i + 1)) as a 32-bit integer\n _k = new Array(64);\n for(var i = 0; i < 64; ++i) {\n _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000);\n }\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates an MD5 state with the given byte buffer.\n *\n * @param s the MD5 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, f, r, i;\n var len = bytes.length();\n while(len >= 64) {\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32Le();\n f = d ^ (b & (c ^ d));\n t = (a + f + _k[i] + w[i]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 2\n for(; i < 32; ++i) {\n f = c ^ (d & (b ^ c));\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 3\n for(; i < 48; ++i) {\n f = b ^ c ^ d;\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 4\n for(; i < 64; ++i) {\n f = c ^ (b | ~d);\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Node.js module for Forge mask generation functions.\n *\n * @author Stefan Siegl\n *\n * Copyright 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./mgf1');\n\nmodule.exports = forge.mgf = forge.mgf || {};\nforge.mgf.mgf1 = forge.mgf1;\n","/**\n * Javascript implementation of mask generation function MGF1.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.mgf = forge.mgf || {};\nvar mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};\n\n/**\n * Creates a MGF1 mask generation function object.\n *\n * @param md the message digest API to use (eg: forge.md.sha1.create()).\n *\n * @return a mask generation function object.\n */\nmgf1.create = function(md) {\n var mgf = {\n /**\n * Generate mask of specified length.\n *\n * @param {String} seed The seed for mask generation.\n * @param maskLen Number of bytes to generate.\n * @return {String} The generated mask.\n */\n generate: function(seed, maskLen) {\n /* 2. Let T be the empty octet string. */\n var t = new forge.util.ByteBuffer();\n\n /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */\n var len = Math.ceil(maskLen / md.digestLength);\n for(var i = 0; i < len; i++) {\n /* a. Convert counter to an octet string C of length 4 octets */\n var c = new forge.util.ByteBuffer();\n c.putInt32(i);\n\n /* b. Concatenate the hash of the seed mgfSeed and C to the octet\n * string T: */\n md.start();\n md.update(seed + c.getBytes());\n t.putBuffer(md.digest());\n }\n\n /* Output the leading maskLen octets of T as the octet string mask. */\n t.truncate(t.length() - maskLen);\n return t.getBytes();\n }\n };\n\n return mgf;\n};\n","/**\n * Object IDs for ASN.1.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nforge.pki = forge.pki || {};\nvar oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};\n\n// set id to name mapping and name to id mapping\nfunction _IN(id, name) {\n oids[id] = name;\n oids[name] = id;\n}\n// set id to name mapping only\nfunction _I_(id, name) {\n oids[id] = name;\n}\n\n// algorithm OIDs\n_IN('1.2.840.113549.1.1.1', 'rsaEncryption');\n// Note: md2 & md4 not implemented\n//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');\n//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');\n_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');\n_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');\n_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');\n_IN('1.2.840.113549.1.1.8', 'mgf1');\n_IN('1.2.840.113549.1.1.9', 'pSpecified');\n_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');\n_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');\n_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');\n_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');\n// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519\n_IN('1.3.101.112', 'EdDSA25519');\n\n_IN('1.2.840.10040.4.3', 'dsa-with-sha1');\n\n_IN('1.3.14.3.2.7', 'desCBC');\n\n_IN('1.3.14.3.2.26', 'sha1');\n// Deprecated equivalent of sha1WithRSAEncryption\n_IN('1.3.14.3.2.29', 'sha1WithRSASignature');\n_IN('2.16.840.1.101.3.4.2.1', 'sha256');\n_IN('2.16.840.1.101.3.4.2.2', 'sha384');\n_IN('2.16.840.1.101.3.4.2.3', 'sha512');\n_IN('2.16.840.1.101.3.4.2.4', 'sha224');\n_IN('2.16.840.1.101.3.4.2.5', 'sha512-224');\n_IN('2.16.840.1.101.3.4.2.6', 'sha512-256');\n_IN('1.2.840.113549.2.2', 'md2');\n_IN('1.2.840.113549.2.5', 'md5');\n\n// pkcs#7 content types\n_IN('1.2.840.113549.1.7.1', 'data');\n_IN('1.2.840.113549.1.7.2', 'signedData');\n_IN('1.2.840.113549.1.7.3', 'envelopedData');\n_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');\n_IN('1.2.840.113549.1.7.5', 'digestedData');\n_IN('1.2.840.113549.1.7.6', 'encryptedData');\n\n// pkcs#9 oids\n_IN('1.2.840.113549.1.9.1', 'emailAddress');\n_IN('1.2.840.113549.1.9.2', 'unstructuredName');\n_IN('1.2.840.113549.1.9.3', 'contentType');\n_IN('1.2.840.113549.1.9.4', 'messageDigest');\n_IN('1.2.840.113549.1.9.5', 'signingTime');\n_IN('1.2.840.113549.1.9.6', 'counterSignature');\n_IN('1.2.840.113549.1.9.7', 'challengePassword');\n_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');\n_IN('1.2.840.113549.1.9.14', 'extensionRequest');\n\n_IN('1.2.840.113549.1.9.20', 'friendlyName');\n_IN('1.2.840.113549.1.9.21', 'localKeyId');\n_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');\n\n// pkcs#12 safe bags\n_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');\n_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');\n_IN('1.2.840.113549.1.12.10.1.3', 'certBag');\n_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');\n_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');\n_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');\n\n// password-based-encryption for pkcs#12\n_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');\n_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');\n\n_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');\n_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');\n_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');\n_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');\n\n// hmac OIDs\n_IN('1.2.840.113549.2.7', 'hmacWithSHA1');\n_IN('1.2.840.113549.2.8', 'hmacWithSHA224');\n_IN('1.2.840.113549.2.9', 'hmacWithSHA256');\n_IN('1.2.840.113549.2.10', 'hmacWithSHA384');\n_IN('1.2.840.113549.2.11', 'hmacWithSHA512');\n\n// symmetric key algorithm oids\n_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');\n_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');\n_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');\n_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');\n\n// certificate issuer/subject OIDs\n_IN('2.5.4.3', 'commonName');\n_IN('2.5.4.4', 'surname');\n_IN('2.5.4.5', 'serialNumber');\n_IN('2.5.4.6', 'countryName');\n_IN('2.5.4.7', 'localityName');\n_IN('2.5.4.8', 'stateOrProvinceName');\n_IN('2.5.4.9', 'streetAddress');\n_IN('2.5.4.10', 'organizationName');\n_IN('2.5.4.11', 'organizationalUnitName');\n_IN('2.5.4.12', 'title');\n_IN('2.5.4.13', 'description');\n_IN('2.5.4.15', 'businessCategory');\n_IN('2.5.4.17', 'postalCode');\n_IN('2.5.4.42', 'givenName');\n_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');\n_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');\n\n// X.509 extension OIDs\n_IN('2.16.840.1.113730.1.1', 'nsCertType');\n_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used\n_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35\n_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15\n_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32\n_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15\n_I_('2.5.29.5', 'policyMapping'); // deprecated use .33\n_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30\n_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17\n_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18\n_I_('2.5.29.9', 'subjectDirectoryAttributes');\n_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19\n_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30\n_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36\n_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19\n_IN('2.5.29.14', 'subjectKeyIdentifier');\n_IN('2.5.29.15', 'keyUsage');\n_I_('2.5.29.16', 'privateKeyUsagePeriod');\n_IN('2.5.29.17', 'subjectAltName');\n_IN('2.5.29.18', 'issuerAltName');\n_IN('2.5.29.19', 'basicConstraints');\n_I_('2.5.29.20', 'cRLNumber');\n_I_('2.5.29.21', 'cRLReason');\n_I_('2.5.29.22', 'expirationDate');\n_I_('2.5.29.23', 'instructionCode');\n_I_('2.5.29.24', 'invalidityDate');\n_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31\n_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28\n_I_('2.5.29.27', 'deltaCRLIndicator');\n_I_('2.5.29.28', 'issuingDistributionPoint');\n_I_('2.5.29.29', 'certificateIssuer');\n_I_('2.5.29.30', 'nameConstraints');\n_IN('2.5.29.31', 'cRLDistributionPoints');\n_IN('2.5.29.32', 'certificatePolicies');\n_I_('2.5.29.33', 'policyMappings');\n_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36\n_IN('2.5.29.35', 'authorityKeyIdentifier');\n_I_('2.5.29.36', 'policyConstraints');\n_IN('2.5.29.37', 'extKeyUsage');\n_I_('2.5.29.46', 'freshestCRL');\n_I_('2.5.29.54', 'inhibitAnyPolicy');\n\n// extKeyUsage purposes\n_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');\n_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');\n_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');\n_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');\n_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');\n_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');\n_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');\n","/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * An EncryptedPrivateKeyInfo:\n *\n * EncryptedPrivateKeyInfo ::= SEQUENCE {\n * encryptionAlgorithm EncryptionAlgorithmIdentifier,\n * encryptedData EncryptedData }\n *\n * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedData ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./oids');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./random');\nrequire('./rc2');\nrequire('./rsa');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Password-based encryption implementation. */\nvar pki = forge.pki = forge.pki || {};\nmodule.exports = pki.pbe = forge.pbe = forge.pbe || {};\nvar oids = pki.oids;\n\n// validator for an EncryptedPrivateKeyInfo structure\n// Note: Currently only works w/algorithm params\nvar encryptedPrivateKeyValidator = {\n name: 'EncryptedPrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encryptionOid'\n }, {\n name: 'AlgorithmIdentifier.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'encryptionParams'\n }]\n }, {\n // encryptedData\n name: 'EncryptedPrivateKeyInfo.encryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encryptedData'\n }]\n};\n\n// validator for a PBES2Algorithms structure\n// Note: Currently only works w/PBKDF2 + AES encryption schemes\nvar PBES2AlgorithmsValidator = {\n name: 'PBES2Algorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'kdfOid'\n }, {\n name: 'PBES2Algorithms.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.params.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'kdfSalt'\n }, {\n name: 'PBES2Algorithms.params.iterationCount',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'kdfIterationCount'\n }, {\n name: 'PBES2Algorithms.params.keyLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'keyLength'\n }, {\n // prf\n name: 'PBES2Algorithms.params.prf',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'PBES2Algorithms.params.prf.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'prfOid'\n }]\n }]\n }]\n }, {\n name: 'PBES2Algorithms.encryptionScheme',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.encryptionScheme.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encOid'\n }, {\n name: 'PBES2Algorithms.encryptionScheme.iv',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encIv'\n }]\n }]\n};\n\nvar pkcs12PbeParamsValidator = {\n name: 'pkcs-12PbeParams',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'pkcs-12PbeParams.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'salt'\n }, {\n name: 'pkcs-12PbeParams.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'iterations'\n }]\n};\n\n/**\n * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.\n *\n * PBES2Algorithms ALGORITHM-IDENTIFIER ::=\n * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}\n *\n * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}\n *\n * PBES2-params ::= SEQUENCE {\n * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n * }\n *\n * PBES2-KDFs ALGORITHM-IDENTIFIER ::=\n * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }\n *\n * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }\n *\n * PBKDF2-params ::= SEQUENCE {\n * salt CHOICE {\n * specified OCTET STRING,\n * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}\n * },\n * iterationCount INTEGER (1..MAX),\n * keyLength INTEGER (1..MAX) OPTIONAL,\n * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1\n * }\n *\n * @param obj the ASN.1 PrivateKeyInfo object.\n * @param password the password to encrypt with.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * prfAlgorithm the PRF message digest algorithm to use\n * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptPrivateKeyInfo = function(obj, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || 'aes128';\n options.prfAlgorithm = options.prfAlgorithm || 'sha1';\n\n // generate PBE params\n var salt = forge.random.getBytesSync(options.saltSize);\n var count = options.count;\n var countBytes = asn1.integerToDer(count);\n var dkLen;\n var encryptionAlgorithm;\n var encryptedData;\n if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {\n // do PBES2\n var ivLen, encOid, cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n dkLen = 16;\n ivLen = 16;\n encOid = oids['aes128-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n dkLen = 24;\n ivLen = 16;\n encOid = oids['aes192-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n dkLen = 32;\n ivLen = 16;\n encOid = oids['aes256-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'des':\n dkLen = 8;\n ivLen = 8;\n encOid = oids['desCBC'];\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // get PRF message digest\n var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();\n var md = prfAlgorithmToMessageDigest(prfAlgorithm);\n\n // encrypt private key using pbe SHA-1 and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = forge.random.getBytesSync(ivLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n // get PBKDF2-params\n var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // keyDerivationFunc\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),\n // PBKDF2-params\n params\n ]),\n // encryptionScheme\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(encOid).getBytes()),\n // iv\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)\n ])\n ])\n ]);\n } else if(options.algorithm === '3des') {\n // Do PKCS12 PBE\n dkLen = 24;\n\n var saltBytes = new forge.util.ByteBuffer(salt);\n var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);\n var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);\n var cipher = forge.des.createEncryptionCipher(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),\n // pkcs-12PbeParams\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ])\n ]);\n } else {\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // EncryptedPrivateKeyInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // encryptionAlgorithm\n encryptionAlgorithm,\n // encryptedData\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)\n ]);\n return rval;\n};\n\n/**\n * Decrypts a ASN.1 PrivateKeyInfo object.\n *\n * @param obj the ASN.1 EncryptedPrivateKeyInfo object.\n * @param password the password to decrypt with.\n *\n * @return the ASN.1 PrivateKeyInfo on success, null on failure.\n */\npki.decryptPrivateKeyInfo = function(obj, password) {\n var rval = null;\n\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // get cipher\n var oid = asn1.derToOid(capture.encryptionOid);\n var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);\n\n // get encrypted data\n var encrypted = forge.util.createBuffer(capture.encryptedData);\n\n cipher.update(encrypted);\n if(cipher.finish()) {\n rval = asn1.fromDer(cipher.output);\n }\n\n return rval;\n};\n\n/**\n * Converts a EncryptedPrivateKeyInfo to PEM format.\n *\n * @param epki the EncryptedPrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted encrypted private key.\n */\npki.encryptedPrivateKeyToPem = function(epki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'ENCRYPTED PRIVATE KEY',\n body: asn1.toDer(epki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption\n * is not performed.\n *\n * @param pem the EncryptedPrivateKeyInfo in PEM-format.\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptedPrivateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY') {\n var error = new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM header type is \"ENCRYPTED PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n return asn1.fromDer(msg.body);\n};\n\n/**\n * Encrypts an RSA private key. By default, the key will be wrapped in\n * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.\n * This is the standard, preferred way to encrypt a private key.\n *\n * To produce a non-standard PEM-encrypted private key that uses encapsulated\n * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL\n * private key encryption), set the 'legacy' option to true. Note: Using this\n * option will cause the iteration count to be forced to 1.\n *\n * Note: The 'des' algorithm is supported, but it is not considered to be\n * secure because it only uses a single 56-bit key. If possible, it is highly\n * recommended that a different algorithm be used.\n *\n * @param rsaKey the RSA key to encrypt.\n * @param password the password to use.\n * @param options:\n * algorithm: the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des', 'des').\n * count: the iteration count to use.\n * saltSize: the salt size to use.\n * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated\n * headers (DEK-Info) private key.\n *\n * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptRsaPrivateKey = function(rsaKey, password, options) {\n // standard PKCS#8\n options = options || {};\n if(!options.legacy) {\n // encrypt PrivateKeyInfo\n var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));\n rval = pki.encryptPrivateKeyInfo(rval, password, options);\n return pki.encryptedPrivateKeyToPem(rval);\n }\n\n // legacy non-PKCS#8\n var algorithm;\n var iv;\n var dkLen;\n var cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n algorithm = 'AES-128-CBC';\n dkLen = 16;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n algorithm = 'AES-192-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n algorithm = 'AES-256-CBC';\n dkLen = 32;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case '3des':\n algorithm = 'DES-EDE3-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n case 'des':\n algorithm = 'DES-CBC';\n dkLen = 8;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Could not encrypt RSA private key; unsupported ' +\n 'encryption algorithm \"' + options.algorithm + '\".');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // encrypt private key using OpenSSL legacy key derivation\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));\n cipher.finish();\n\n var msg = {\n type: 'RSA PRIVATE KEY',\n procType: {\n version: '4',\n type: 'ENCRYPTED'\n },\n dekInfo: {\n algorithm: algorithm,\n parameters: forge.util.bytesToHex(iv).toUpperCase()\n },\n body: cipher.output.getBytes()\n };\n return forge.pem.encode(msg);\n};\n\n/**\n * Decrypts an RSA private key.\n *\n * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.\n * @param password the password to use.\n *\n * @return the RSA key on success, null on failure.\n */\npki.decryptRsaPrivateKey = function(pem, password) {\n var rval = null;\n\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&\n msg.type !== 'PRIVATE KEY' &&\n msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM header type ' +\n 'is not \"ENCRYPTED PRIVATE KEY\", \"PRIVATE KEY\", or \"RSA PRIVATE KEY\".');\n error.headerType = error;\n throw error;\n }\n\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n var dkLen;\n var cipherFn;\n switch(msg.dekInfo.algorithm) {\n case 'DES-CBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'DES-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'AES-128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'RC2-40-CBC':\n dkLen = 5;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 40);\n };\n break;\n case 'RC2-64-CBC':\n dkLen = 8;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 64);\n };\n break;\n case 'RC2-128-CBC':\n dkLen = 16;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 128);\n };\n break;\n default:\n var error = new Error('Could not decrypt private key; unsupported ' +\n 'encryption algorithm \"' + msg.dekInfo.algorithm + '\".');\n error.algorithm = msg.dekInfo.algorithm;\n throw error;\n }\n\n // use OpenSSL legacy key derivation\n var iv = forge.util.hexToBytes(msg.dekInfo.parameters);\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(forge.util.createBuffer(msg.body));\n if(cipher.finish()) {\n rval = cipher.output.getBytes();\n } else {\n return rval;\n }\n } else {\n rval = msg.body;\n }\n\n if(msg.type === 'ENCRYPTED PRIVATE KEY') {\n rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);\n } else {\n // decryption already performed above\n rval = asn1.fromDer(rval);\n }\n\n if(rval !== null) {\n rval = pki.privateKeyFromAsn1(rval);\n }\n\n return rval;\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\npki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {\n var j, l;\n\n if(typeof md === 'undefined' || md === null) {\n if(!('sha1' in forge.md)) {\n throw new Error('\"sha1\" hash algorithm unavailable.');\n }\n md = forge.md.sha1.create();\n }\n\n var u = md.digestLength;\n var v = md.blockLength;\n var result = new forge.util.ByteBuffer();\n\n /* Convert password to Unicode byte buffer + trailing 0-byte. */\n var passBuf = new forge.util.ByteBuffer();\n if(password !== null && password !== undefined) {\n for(l = 0; l < password.length; l++) {\n passBuf.putInt16(password.charCodeAt(l));\n }\n passBuf.putInt16(0);\n }\n\n /* Length of salt and password in BYTES. */\n var p = passBuf.length();\n var s = salt.length();\n\n /* 1. Construct a string, D (the \"diversifier\"), by concatenating\n v copies of ID. */\n var D = new forge.util.ByteBuffer();\n D.fillWithByte(id, v);\n\n /* 2. Concatenate copies of the salt together to create a string S of length\n v * ceil(s / v) bytes (the final copy of the salt may be trunacted\n to create S).\n Note that if the salt is the empty string, then so is S. */\n var Slen = v * Math.ceil(s / v);\n var S = new forge.util.ByteBuffer();\n for(l = 0; l < Slen; l++) {\n S.putByte(salt.at(l % s));\n }\n\n /* 3. Concatenate copies of the password together to create a string P of\n length v * ceil(p / v) bytes (the final copy of the password may be\n truncated to create P).\n Note that if the password is the empty string, then so is P. */\n var Plen = v * Math.ceil(p / v);\n var P = new forge.util.ByteBuffer();\n for(l = 0; l < Plen; l++) {\n P.putByte(passBuf.at(l % p));\n }\n\n /* 4. Set I=S||P to be the concatenation of S and P. */\n var I = S;\n I.putBuffer(P);\n\n /* 5. Set c=ceil(n / u). */\n var c = Math.ceil(n / u);\n\n /* 6. For i=1, 2, ..., c, do the following: */\n for(var i = 1; i <= c; i++) {\n /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */\n var buf = new forge.util.ByteBuffer();\n buf.putBytes(D.bytes());\n buf.putBytes(I.bytes());\n for(var round = 0; round < iter; round++) {\n md.start();\n md.update(buf.getBytes());\n buf = md.digest();\n }\n\n /* b) Concatenate copies of Ai to create a string B of length v bytes (the\n final copy of Ai may be truncated to create B). */\n var B = new forge.util.ByteBuffer();\n for(l = 0; l < v; l++) {\n B.putByte(buf.at(l % u));\n }\n\n /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,\n where k=ceil(s / v) + ceil(p / v), modify I by setting\n Ij=(Ij+B+1) mod 2v for each j. */\n var k = Math.ceil(s / v) + Math.ceil(p / v);\n var Inew = new forge.util.ByteBuffer();\n for(j = 0; j < k; j++) {\n var chunk = new forge.util.ByteBuffer(I.getBytes(v));\n var x = 0x1ff;\n for(l = B.length() - 1; l >= 0; l--) {\n x = x >> 8;\n x += B.at(l) + chunk.at(l);\n chunk.setAt(l, x & 0xff);\n }\n Inew.putBuffer(chunk);\n }\n I = Inew;\n\n /* Add Ai to A. */\n result.putBuffer(buf);\n }\n\n result.truncate(result.length() - n);\n return result;\n};\n\n/**\n * Get new Forge cipher object instance.\n *\n * @param oid the OID (in string notation).\n * @param params the ASN.1 params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipher = function(oid, params, password) {\n switch(oid) {\n case pki.oids['pkcs5PBES2']:\n return pki.pbe.getCipherForPBES2(oid, params, password);\n\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n return pki.pbe.getCipherForPKCS12PBE(oid, params, password);\n\n default:\n var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');\n error.oid = oid;\n error.supportedOids = [\n 'pkcs5PBES2',\n 'pbeWithSHAAnd3-KeyTripleDES-CBC',\n 'pbewithSHAAnd40BitRC2-CBC'\n ];\n throw error;\n }\n};\n\n/**\n * Get new Forge cipher object instance according to PBES2 params block.\n *\n * The returned cipher instance is already started using the IV\n * from PBES2 parameter block.\n *\n * @param oid the PKCS#5 PBKDF2 OID (in string notation).\n * @param params the ASN.1 PBES2-params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipherForPBES2 = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // check oids\n oid = asn1.derToOid(capture.kdfOid);\n if(oid !== pki.oids['pkcs5PBKDF2']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported key derivation function OID.');\n error.oid = oid;\n error.supportedOids = ['pkcs5PBKDF2'];\n throw error;\n }\n oid = asn1.derToOid(capture.encOid);\n if(oid !== pki.oids['aes128-CBC'] &&\n oid !== pki.oids['aes192-CBC'] &&\n oid !== pki.oids['aes256-CBC'] &&\n oid !== pki.oids['des-EDE3-CBC'] &&\n oid !== pki.oids['desCBC']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported encryption scheme OID.');\n error.oid = oid;\n error.supportedOids = [\n 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];\n throw error;\n }\n\n // set PBE params\n var salt = capture.kdfSalt;\n var count = forge.util.createBuffer(capture.kdfIterationCount);\n count = count.getInt(count.length() << 3);\n var dkLen;\n var cipherFn;\n switch(pki.oids[oid]) {\n case 'aes128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'des-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'desCBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n\n // decrypt private key using pbe with chosen PRF and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = capture.encIv;\n var cipher = cipherFn(dk);\n cipher.start(iv);\n\n return cipher;\n};\n\n/**\n * Get new Forge cipher object instance for PKCS#12 PBE.\n *\n * The returned cipher instance is already started using the key & IV\n * derived from the provided password and PKCS#12 PBE salt.\n *\n * @param oid The PKCS#12 PBE OID (in string notation).\n * @param params The ASN.1 PKCS#12 PBE-params object.\n * @param password The password to decrypt with.\n *\n * @return the new cipher object instance.\n */\npki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n var salt = forge.util.createBuffer(capture.salt);\n var count = forge.util.createBuffer(capture.iterations);\n count = count.getInt(count.length() << 3);\n\n var dkLen, dIvLen, cipherFn;\n switch(oid) {\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n dkLen = 24;\n dIvLen = 8;\n cipherFn = forge.des.startDecrypting;\n break;\n\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n dkLen = 5;\n dIvLen = 8;\n cipherFn = function(key, iv) {\n var cipher = forge.rc2.createDecryptionCipher(key, 40);\n cipher.start(iv, null);\n return cipher;\n };\n break;\n\n default:\n var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');\n error.oid = oid;\n throw error;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);\n md.start();\n var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);\n\n return cipherFn(key, iv);\n};\n\n/**\n * OpenSSL's legacy key derivation function.\n *\n * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html\n *\n * @param password the password to derive the key from.\n * @param salt the salt to use, null for none.\n * @param dkLen the number of bytes needed for the derived key.\n * @param [options] the options to use:\n * [md] an optional message digest object to use.\n */\npki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {\n if(typeof md === 'undefined' || md === null) {\n if(!('md5' in forge.md)) {\n throw new Error('\"md5\" hash algorithm unavailable.');\n }\n md = forge.md.md5.create();\n }\n if(salt === null) {\n salt = '';\n }\n var digests = [hash(md, password + salt)];\n for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {\n digests.push(hash(md, digests[i - 1] + password + salt));\n }\n return digests.join('').substr(0, dkLen);\n};\n\nfunction hash(md, bytes) {\n return md.start().update(bytes).digest().getBytes();\n}\n\nfunction prfOidToMessageDigest(prfOid) {\n // get PRF algorithm, default to SHA-1\n var prfAlgorithm;\n if(!prfOid) {\n prfAlgorithm = 'hmacWithSHA1';\n } else {\n prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];\n if(!prfAlgorithm) {\n var error = new Error('Unsupported PRF OID.');\n error.oid = prfOid;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n }\n return prfAlgorithmToMessageDigest(prfAlgorithm);\n}\n\nfunction prfAlgorithmToMessageDigest(prfAlgorithm) {\n var factory = forge.md;\n switch(prfAlgorithm) {\n case 'hmacWithSHA224':\n factory = forge.md.sha512;\n case 'hmacWithSHA1':\n case 'hmacWithSHA256':\n case 'hmacWithSHA384':\n case 'hmacWithSHA512':\n prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();\n break;\n default:\n var error = new Error('Unsupported PRF algorithm.');\n error.algorithm = prfAlgorithm;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n if(!factory || !(prfAlgorithm in factory)) {\n throw new Error('Unknown hash algorithm: ' + prfAlgorithm);\n }\n return factory[prfAlgorithm].create();\n}\n\nfunction createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {\n var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ]);\n // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm\n if(prfAlgorithm !== 'hmacWithSHA1') {\n params.value.push(\n // key length\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(dkLen.toString(16))),\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n return params;\n}\n","/**\n * Password-Based Key-Derivation Function #2 implementation.\n *\n * See RFC 2898 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./hmac');\nrequire('./md');\nrequire('./util');\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = require('crypto');\n}\n\n/**\n * Derives a key from a password.\n *\n * @param p the password as a binary-encoded string of bytes.\n * @param s the salt as a binary-encoded string of bytes.\n * @param c the iteration count, a positive integer.\n * @param dkLen the intended length, in bytes, of the derived key,\n * (max: 2^32 - 1) * hash length of the PRF.\n * @param [md] the message digest (or algorithm identifier as a string) to use\n * in the PRF, defaults to SHA-1.\n * @param [callback(err, key)] presence triggers asynchronous version, called\n * once the operation completes.\n *\n * @return the derived key, as a binary-encoded string of bytes, for the\n * synchronous version (if no callback is specified).\n */\nmodule.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(\n p, s, c, dkLen, md, callback) {\n if(typeof md === 'function') {\n callback = md;\n md = null;\n }\n\n // use native implementation if possible and not disabled, note that\n // some node versions only support SHA-1, others allow digest to be changed\n if(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n crypto.pbkdf2 && (md === null || typeof md !== 'object') &&\n (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {\n if(typeof md !== 'string') {\n // default prf to SHA-1\n md = 'sha1';\n }\n p = Buffer.from(p, 'binary');\n s = Buffer.from(s, 'binary');\n if(!callback) {\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');\n }\n return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');\n }\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n\n if(typeof md === 'undefined' || md === null) {\n // default prf to SHA-1\n md = 'sha1';\n }\n if(typeof md === 'string') {\n if(!(md in forge.md.algorithms)) {\n throw new Error('Unknown hash algorithm: ' + md);\n }\n md = forge.md[md].create();\n }\n\n var hLen = md.digestLength;\n\n /* 1. If dkLen > (2^32 - 1) * hLen, output \"derived key too long\" and\n stop. */\n if(dkLen > (0xFFFFFFFF * hLen)) {\n var err = new Error('Derived key is too long.');\n if(callback) {\n return callback(err);\n }\n throw err;\n }\n\n /* 2. Let len be the number of hLen-octet blocks in the derived key,\n rounding up, and let r be the number of octets in the last\n block:\n\n len = CEIL(dkLen / hLen),\n r = dkLen - (len - 1) * hLen. */\n var len = Math.ceil(dkLen / hLen);\n var r = dkLen - (len - 1) * hLen;\n\n /* 3. For each block of the derived key apply the function F defined\n below to the password P, the salt S, the iteration count c, and\n the block index to compute the block:\n\n T_1 = F(P, S, c, 1),\n T_2 = F(P, S, c, 2),\n ...\n T_len = F(P, S, c, len),\n\n where the function F is defined as the exclusive-or sum of the\n first c iterates of the underlying pseudorandom function PRF\n applied to the password P and the concatenation of the salt S\n and the block index i:\n\n F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c\n\n where\n\n u_1 = PRF(P, S || INT(i)),\n u_2 = PRF(P, u_1),\n ...\n u_c = PRF(P, u_{c-1}).\n\n Here, INT(i) is a four-octet encoding of the integer i, most\n significant octet first. */\n var prf = forge.hmac.create();\n prf.start(md, p);\n var dk = '';\n var xor, u_c, u_c1;\n\n // sync version\n if(!callback) {\n for(var i = 1; i <= len; ++i) {\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n for(var j = 2; j <= c; ++j) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n }\n /* 5. Output the derived key DK. */\n return dk;\n }\n\n // async version\n var i = 1, j;\n function outer() {\n if(i > len) {\n // done\n return callback(null, dk);\n }\n\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n j = 2;\n inner();\n }\n\n function inner() {\n if(j <= c) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n ++j;\n return forge.util.setImmediate(inner);\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n\n ++i;\n outer();\n }\n\n outer();\n};\n","/**\n * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.\n *\n * See: RFC 1421.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n *\n * A Forge PEM object has the following fields:\n *\n * type: identifies the type of message (eg: \"RSA PRIVATE KEY\").\n *\n * procType: identifies the type of processing performed on the message,\n * it has two subfields: version and type, eg: 4,ENCRYPTED.\n *\n * contentDomain: identifies the type of content in the message, typically\n * only uses the value: \"RFC822\".\n *\n * dekInfo: identifies the message encryption algorithm and mode and includes\n * any parameters for the algorithm, it has two subfields: algorithm and\n * parameters, eg: DES-CBC,F8143EDE5960C597.\n *\n * headers: contains all other PEM encapsulated headers -- where order is\n * significant (for pairing data like recipient ID + key info).\n *\n * body: the binary-encoded body.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n// shortcut for pem API\nvar pem = module.exports = forge.pem = forge.pem || {};\n\n/**\n * Encodes (serializes) the given PEM object.\n *\n * @param msg the PEM message object to encode.\n * @param options the options to use:\n * maxline the maximum characters per line for the body, (default: 64).\n *\n * @return the PEM-formatted string.\n */\npem.encode = function(msg, options) {\n options = options || {};\n var rval = '-----BEGIN ' + msg.type + '-----\\r\\n';\n\n // encode special headers\n var header;\n if(msg.procType) {\n header = {\n name: 'Proc-Type',\n values: [String(msg.procType.version), msg.procType.type]\n };\n rval += foldHeader(header);\n }\n if(msg.contentDomain) {\n header = {name: 'Content-Domain', values: [msg.contentDomain]};\n rval += foldHeader(header);\n }\n if(msg.dekInfo) {\n header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};\n if(msg.dekInfo.parameters) {\n header.values.push(msg.dekInfo.parameters);\n }\n rval += foldHeader(header);\n }\n\n if(msg.headers) {\n // encode all other headers\n for(var i = 0; i < msg.headers.length; ++i) {\n rval += foldHeader(msg.headers[i]);\n }\n }\n\n // terminate header\n if(msg.procType) {\n rval += '\\r\\n';\n }\n\n // add body\n rval += forge.util.encode64(msg.body, options.maxline || 64) + '\\r\\n';\n\n rval += '-----END ' + msg.type + '-----\\r\\n';\n return rval;\n};\n\n/**\n * Decodes (deserializes) all PEM messages found in the given string.\n *\n * @param str the PEM-formatted string to decode.\n *\n * @return the PEM message objects in an array.\n */\npem.decode = function(str) {\n var rval = [];\n\n // split string into PEM messages (be lenient w/EOF on BEGIN line)\n var rMessage = /\\s*-----BEGIN ([A-Z0-9- ]+)-----\\r?\\n?([\\x21-\\x7e\\s]+?(?:\\r?\\n\\r?\\n))?([:A-Za-z0-9+\\/=\\s]+?)-----END \\1-----/g;\n var rHeader = /([\\x21-\\x7e]+):\\s*([\\x21-\\x7e\\s^:]+)/;\n var rCRLF = /\\r?\\n/;\n var match;\n while(true) {\n match = rMessage.exec(str);\n if(!match) {\n break;\n }\n\n // accept \"NEW CERTIFICATE REQUEST\" as \"CERTIFICATE REQUEST\"\n // https://datatracker.ietf.org/doc/html/rfc7468#section-7\n var type = match[1];\n if(type === 'NEW CERTIFICATE REQUEST') {\n type = 'CERTIFICATE REQUEST';\n }\n\n var msg = {\n type: type,\n procType: null,\n contentDomain: null,\n dekInfo: null,\n headers: [],\n body: forge.util.decode64(match[3])\n };\n rval.push(msg);\n\n // no headers\n if(!match[2]) {\n continue;\n }\n\n // parse headers\n var lines = match[2].split(rCRLF);\n var li = 0;\n while(match && li < lines.length) {\n // get line, trim any rhs whitespace\n var line = lines[li].replace(/\\s+$/, '');\n\n // RFC2822 unfold any following folded lines\n for(var nl = li + 1; nl < lines.length; ++nl) {\n var next = lines[nl];\n if(!/\\s/.test(next[0])) {\n break;\n }\n line += next;\n li = nl;\n }\n\n // parse header\n match = line.match(rHeader);\n if(match) {\n var header = {name: match[1], values: []};\n var values = match[2].split(',');\n for(var vi = 0; vi < values.length; ++vi) {\n header.values.push(ltrim(values[vi]));\n }\n\n // Proc-Type must be the first header\n if(!msg.procType) {\n if(header.name !== 'Proc-Type') {\n throw new Error('Invalid PEM formatted message. The first ' +\n 'encapsulated header must be \"Proc-Type\".');\n } else if(header.values.length !== 2) {\n throw new Error('Invalid PEM formatted message. The \"Proc-Type\" ' +\n 'header must have two subfields.');\n }\n msg.procType = {version: values[0], type: values[1]};\n } else if(!msg.contentDomain && header.name === 'Content-Domain') {\n // special-case Content-Domain\n msg.contentDomain = values[0] || '';\n } else if(!msg.dekInfo && header.name === 'DEK-Info') {\n // special-case DEK-Info\n if(header.values.length === 0) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must have at least one subfield.');\n }\n msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};\n } else {\n msg.headers.push(header);\n }\n }\n\n ++li;\n }\n\n if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must be present if \"Proc-Type\" is \"ENCRYPTED\".');\n }\n }\n\n if(rval.length === 0) {\n throw new Error('Invalid PEM formatted message.');\n }\n\n return rval;\n};\n\nfunction foldHeader(header) {\n var rval = header.name + ': ';\n\n // ensure values with CRLF are folded\n var values = [];\n var insertSpace = function(match, $1) {\n return ' ' + $1;\n };\n for(var i = 0; i < header.values.length; ++i) {\n values.push(header.values[i].replace(/^(\\S+\\r\\n)/, insertSpace));\n }\n rval += values.join(',') + '\\r\\n';\n\n // do folding\n var length = 0;\n var candidate = -1;\n for(var i = 0; i < rval.length; ++i, ++length) {\n if(length > 65 && candidate !== -1) {\n var insert = rval[candidate];\n if(insert === ',') {\n ++candidate;\n rval = rval.substr(0, candidate) + '\\r\\n ' + rval.substr(candidate);\n } else {\n rval = rval.substr(0, candidate) +\n '\\r\\n' + insert + rval.substr(candidate + 1);\n }\n length = (i - candidate - 1);\n candidate = -1;\n ++i;\n } else if(rval[i] === ' ' || rval[i] === '\\t' || rval[i] === ',') {\n candidate = i;\n }\n }\n\n return rval;\n}\n\nfunction ltrim(str) {\n return str.replace(/^\\s+/, '');\n}\n","/**\n * Partial implementation of PKCS#1 v2.2: RSA-OEAP\n *\n * Modified but based on the following MIT and BSD licensed code:\n *\n * https://github.com/kjur/jsjws/blob/master/rsa.js:\n *\n * The 'jsjws'(JSON Web Signature JavaScript Library) License\n *\n * Copyright (c) 2012 Kenji Urushima\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:\n *\n * RSAES-OAEP.js\n * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $\n * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)\n * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.\n * Contact: ellis@nukinetics.com\n * Distributed under the BSD License.\n *\n * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125\n *\n * @author Evan Jones (http://evanjones.ca/)\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./sha1');\n\n// shortcut for PKCS#1 API\nvar pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};\n\n/**\n * Encode the given RSAES-OAEP message (M) using key, with optional label (L)\n * and seed.\n *\n * This method does not perform RSA encryption, it only encodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param message the message to encode.\n * @param options the options to use:\n * label an optional label to use.\n * seed the seed to use.\n * md the message digest object to use, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the encoded message bytes.\n */\npkcs1.encode_rsa_oaep = function(key, message, options) {\n // parse arguments\n var label;\n var seed;\n var md;\n var mgf1Md;\n // legacy args (label, seed, md)\n if(typeof options === 'string') {\n label = options;\n seed = arguments[3] || undefined;\n md = arguments[4] || undefined;\n } else if(options) {\n label = options.label || undefined;\n seed = options.seed || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // default OAEP to SHA-1 message digest\n if(!md) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n // compute length in bytes and check output\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n var maxLength = keyLength - 2 * md.digestLength - 2;\n if(message.length > maxLength) {\n var error = new Error('RSAES-OAEP input message length is too long.');\n error.length = message.length;\n error.maxLength = maxLength;\n throw error;\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest();\n\n var PS = '';\n var PS_length = maxLength - message.length;\n for(var i = 0; i < PS_length; i++) {\n PS += '\\x00';\n }\n\n var DB = lHash.getBytes() + PS + '\\x01' + message;\n\n if(!seed) {\n seed = forge.random.getBytes(md.digestLength);\n } else if(seed.length !== md.digestLength) {\n var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +\n 'match the digest length.');\n error.seedLength = seed.length;\n error.digestLength = md.digestLength;\n throw error;\n }\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);\n\n // return encoded message\n return '\\x00' + maskedSeed + maskedDB;\n};\n\n/**\n * Decode the given RSAES-OAEP encoded message (EM) using key, with optional\n * label (L).\n *\n * This method does not perform RSA decryption, it only decodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param em the encoded message to decode.\n * @param options the options to use:\n * label an optional label to use.\n * md the message digest object to use for OAEP, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the decoded message bytes.\n */\npkcs1.decode_rsa_oaep = function(key, em, options) {\n // parse args\n var label;\n var md;\n var mgf1Md;\n // legacy args\n if(typeof options === 'string') {\n label = options;\n md = arguments[3] || undefined;\n } else if(options) {\n label = options.label || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // compute length in bytes\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n\n if(em.length !== keyLength) {\n var error = new Error('RSAES-OAEP encoded message length is invalid.');\n error.length = em.length;\n error.expectedLength = keyLength;\n throw error;\n }\n\n // default OAEP to SHA-1 message digest\n if(md === undefined) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n if(keyLength < 2 * md.digestLength + 2) {\n throw new Error('RSAES-OAEP key is too short for the hash function.');\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest().getBytes();\n\n // split the message into its parts\n var y = em.charAt(0);\n var maskedSeed = em.substring(1, md.digestLength + 1);\n var maskedDB = em.substring(1 + md.digestLength);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);\n\n var lHashPrime = db.substring(0, md.digestLength);\n\n // constant time check that all values match what is expected\n var error = (y !== '\\x00');\n\n // constant time check lHash vs lHashPrime\n for(var i = 0; i < md.digestLength; ++i) {\n error |= (lHash.charAt(i) !== lHashPrime.charAt(i));\n }\n\n // \"constant time\" find the 0x1 byte separating the padding (zeros) from the\n // message\n // TODO: It must be possible to do this in a better/smarter way?\n var in_ps = 1;\n var index = md.digestLength;\n for(var j = md.digestLength; j < db.length; j++) {\n var code = db.charCodeAt(j);\n\n var is_0 = (code & 0x1) ^ 0x1;\n\n // non-zero if not 0 or 1 in the ps section\n var error_mask = in_ps ? 0xfffe : 0x0000;\n error |= (code & error_mask);\n\n // latch in_ps to zero after we find 0x1\n in_ps = in_ps & is_0;\n index += in_ps;\n }\n\n if(error || db.charCodeAt(index) !== 0x1) {\n throw new Error('Invalid RSAES-OAEP padding.');\n }\n\n return db.substring(index + 1);\n};\n\nfunction rsa_mgf1(seed, maskLength, hash) {\n // default to SHA-1 message digest\n if(!hash) {\n hash = forge.md.sha1.create();\n }\n var t = '';\n var count = Math.ceil(maskLength / hash.digestLength);\n for(var i = 0; i < count; ++i) {\n var c = String.fromCharCode(\n (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);\n hash.start();\n hash.update(seed + c);\n t += hash.digest().getBytes();\n }\n return t.substring(0, maskLength);\n}\n","/**\n * Javascript implementation of PKCS#12.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#12 is as follows\n * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details)\n *\n * PFX ::= SEQUENCE {\n * version INTEGER {v3(3)}(v3,...),\n * authSafe ContentInfo,\n * macData MacData OPTIONAL\n * }\n *\n * MacData ::= SEQUENCE {\n * mac DigestInfo,\n * macSalt OCTET STRING,\n * iterations INTEGER DEFAULT 1\n * }\n * Note: The iterations default is for historical reasons and its use is\n * deprecated. A higher value, like 1024, is recommended.\n *\n * DigestInfo is defined in PKCS#7 as follows:\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of SHA1 there is none.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * Digest ::= OCTET STRING\n *\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * AuthenticatedSafe ::= SEQUENCE OF ContentInfo\n * -- Data if unencrypted\n * -- EncryptedData if password-encrypted\n * -- EnvelopedData if public key-encrypted\n *\n *\n * SafeContents ::= SEQUENCE OF SafeBag\n *\n * SafeBag ::= SEQUENCE {\n * bagId BAG-TYPE.&id ({PKCS12BagSet})\n * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),\n * bagAttributes SET OF PKCS12Attribute OPTIONAL\n * }\n *\n * PKCS12Attribute ::= SEQUENCE {\n * attrId ATTRIBUTE.&id ({PKCS12AttrSet}),\n * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})\n * } -- This type is compatible with the X.500 type 'Attribute'\n *\n * PKCS12AttrSet ATTRIBUTE ::= {\n * friendlyName | -- from PKCS #9\n * localKeyId, -- from PKCS #9\n * ... -- Other attributes are allowed\n * }\n *\n * CertBag ::= SEQUENCE {\n * certId BAG-TYPE.&id ({CertTypes}),\n * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})\n * }\n *\n * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}}\n * -- DER-encoded X.509 certificate stored in OCTET STRING\n *\n * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}}\n * -- Base64-encoded SDSI certificate stored in IA5String\n *\n * CertTypes BAG-TYPE ::= {\n * x509Certificate |\n * sdsiCertificate,\n * ... -- For future extensions\n * }\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./oids');\nrequire('./pkcs7asn1');\nrequire('./pbe');\nrequire('./random');\nrequire('./rsa');\nrequire('./sha1');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 & PKI API\nvar asn1 = forge.asn1;\nvar pki = forge.pki;\n\n// shortcut for PKCS#12 API\nvar p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {};\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // a ContentInfo\n constructed: true,\n value: [{\n name: 'ContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'content'\n }]\n};\n\nvar pfxValidator = {\n name: 'PFX',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PFX.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n },\n contentInfoValidator, {\n name: 'PFX.macData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'mac',\n value: [{\n name: 'PFX.macData.mac',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestInfo\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'macAlgorithm'\n }, {\n name: 'PFX.macData.mac.digestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'macAlgorithmParameters'\n }]\n }, {\n name: 'PFX.macData.mac.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macDigest'\n }]\n }, {\n name: 'PFX.macData.macSalt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macSalt'\n }, {\n name: 'PFX.macData.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'macIterations'\n }]\n }]\n};\n\nvar safeBagValidator = {\n name: 'SafeBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SafeBag.bagId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'bagId'\n }, {\n name: 'SafeBag.bagValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'bagValue'\n }, {\n name: 'SafeBag.bagAttributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n optional: true,\n capture: 'bagAttributes'\n }]\n};\n\nvar attributeValidator = {\n name: 'Attribute',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Attribute.attrId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'oid'\n }, {\n name: 'Attribute.attrValues',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n capture: 'values'\n }]\n};\n\nvar certBagValidator = {\n name: 'CertBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertBag.certId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certId'\n }, {\n name: 'CertBag.certValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n /* So far we only support X.509 certificates (which are wrapped in\n an OCTET STRING, hence hard code that here). */\n value: [{\n name: 'CertBag.certValue[0]',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.OCTETSTRING,\n constructed: false,\n capture: 'cert'\n }]\n }]\n};\n\n/**\n * Search SafeContents structure for bags with matching attributes.\n *\n * The search can optionally be narrowed by a certain bag type.\n *\n * @param safeContents the SafeContents structure to search in.\n * @param attrName the name of the attribute to compare against.\n * @param attrValue the attribute value to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of matching bags.\n */\nfunction _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {\n var result = [];\n\n for(var i = 0; i < safeContents.length; i++) {\n for(var j = 0; j < safeContents[i].safeBags.length; j++) {\n var bag = safeContents[i].safeBags[j];\n if(bagType !== undefined && bag.type !== bagType) {\n continue;\n }\n // only filter by bag type, no attribute specified\n if(attrName === null) {\n result.push(bag);\n continue;\n }\n if(bag.attributes[attrName] !== undefined &&\n bag.attributes[attrName].indexOf(attrValue) >= 0) {\n result.push(bag);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object.\n *\n * @param obj The PKCS#12 PFX in ASN.1 notation.\n * @param strict true to use strict DER decoding, false not to (default: true).\n * @param {String} password Password to decrypt with (optional).\n *\n * @return PKCS#12 PFX object.\n */\np12.pkcs12FromAsn1 = function(obj, strict, password) {\n // handle args\n if(typeof strict === 'string') {\n password = strict;\n strict = true;\n } else if(strict === undefined) {\n strict = true;\n }\n\n // validate PFX and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, pfxValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 PFX. ' +\n 'ASN.1 object is not an PKCS#12 PFX.');\n error.errors = error;\n throw error;\n }\n\n var pfx = {\n version: capture.version.charCodeAt(0),\n safeContents: [],\n\n /**\n * Gets bags with matching attributes.\n *\n * @param filter the attributes to filter by:\n * [localKeyId] the localKeyId to search for.\n * [localKeyIdHex] the localKeyId in hex to search for.\n * [friendlyName] the friendly name to search for.\n * [bagType] bag type to narrow each attribute search by.\n *\n * @return a map of attribute type to an array of matching bags or, if no\n * attribute was given but a bag type, the map key will be the\n * bag type.\n */\n getBags: function(filter) {\n var rval = {};\n\n var localKeyId;\n if('localKeyId' in filter) {\n localKeyId = filter.localKeyId;\n } else if('localKeyIdHex' in filter) {\n localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);\n }\n\n // filter on bagType only\n if(localKeyId === undefined && !('friendlyName' in filter) &&\n 'bagType' in filter) {\n rval[filter.bagType] = _getBagsByAttribute(\n pfx.safeContents, null, null, filter.bagType);\n }\n\n if(localKeyId !== undefined) {\n rval.localKeyId = _getBagsByAttribute(\n pfx.safeContents, 'localKeyId',\n localKeyId, filter.bagType);\n }\n if('friendlyName' in filter) {\n rval.friendlyName = _getBagsByAttribute(\n pfx.safeContents, 'friendlyName',\n filter.friendlyName, filter.bagType);\n }\n\n return rval;\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching friendlyName attribute.\n *\n * @param friendlyName the friendly name to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching friendlyName attribute.\n */\n getBagsByFriendlyName: function(friendlyName, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'friendlyName', friendlyName, bagType);\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching localKeyId attribute.\n *\n * @param localKeyId the localKeyId to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching localKeyId attribute.\n */\n getBagsByLocalKeyId: function(localKeyId, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'localKeyId', localKeyId, bagType);\n }\n };\n\n if(capture.version.charCodeAt(0) !== 3) {\n var error = new Error('PKCS#12 PFX of version other than 3 not supported.');\n error.version = capture.version.charCodeAt(0);\n throw error;\n }\n\n if(asn1.derToOid(capture.contentType) !== pki.oids.data) {\n var error = new Error('Only PKCS#12 PFX in password integrity mode supported.');\n error.oid = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n var data = capture.content.value[0];\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.');\n }\n data = _decodePkcs7Data(data);\n\n // check for MAC\n if(capture.mac) {\n var md = null;\n var macKeyBytes = 0;\n var macAlgorithm = asn1.derToOid(capture.macAlgorithm);\n switch(macAlgorithm) {\n case pki.oids.sha1:\n md = forge.md.sha1.create();\n macKeyBytes = 20;\n break;\n case pki.oids.sha256:\n md = forge.md.sha256.create();\n macKeyBytes = 32;\n break;\n case pki.oids.sha384:\n md = forge.md.sha384.create();\n macKeyBytes = 48;\n break;\n case pki.oids.sha512:\n md = forge.md.sha512.create();\n macKeyBytes = 64;\n break;\n case pki.oids.md5:\n md = forge.md.md5.create();\n macKeyBytes = 16;\n break;\n }\n if(md === null) {\n throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm);\n }\n\n // verify MAC (iterations default to 1)\n var macSalt = new forge.util.ByteBuffer(capture.macSalt);\n var macIterations = (('macIterations' in capture) ?\n parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1);\n var macKey = p12.generateKey(\n password, macSalt, 3, macIterations, macKeyBytes, md);\n var mac = forge.hmac.create();\n mac.start(md, macKey);\n mac.update(data.value);\n var macValue = mac.getMac();\n if(macValue.getBytes() !== capture.macDigest) {\n throw new Error('PKCS#12 MAC could not be verified. Invalid password?');\n }\n }\n\n _decodeAuthenticatedSafe(pfx, data.value, strict, password);\n return pfx;\n};\n\n/**\n * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines \"Data\" as an OCTET STRING,\n * but it is sometimes an OCTET STRING that is composed/constructed of chunks,\n * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This\n * function transforms this corner-case into the usual simple,\n * non-composed/constructed OCTET STRING.\n *\n * This function may be moved to ASN.1 at some point to better deal with\n * more BER-encoding issues, should they arise.\n *\n * @param data the ASN.1 Data object to transform.\n */\nfunction _decodePkcs7Data(data) {\n // handle special case of \"chunked\" data content: an octet string composed\n // of other octet strings\n if(data.composed || data.constructed) {\n var value = forge.util.createBuffer();\n for(var i = 0; i < data.value.length; ++i) {\n value.putBytes(data.value[i].value);\n }\n data.composed = data.constructed = false;\n data.value = value.getBytes();\n }\n return data;\n}\n\n/**\n * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object.\n *\n * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo.\n *\n * @param pfx The PKCS#12 PFX object to fill.\n * @param {String} authSafe BER-encoded AuthenticatedSafe.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n */\nfunction _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {\n authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */\n\n if(authSafe.tagClass !== asn1.Class.UNIVERSAL ||\n authSafe.type !== asn1.Type.SEQUENCE ||\n authSafe.constructed !== true) {\n throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' +\n 'SEQUENCE OF ContentInfo');\n }\n\n for(var i = 0; i < authSafe.value.length; i++) {\n var contentInfo = authSafe.value[i];\n\n // validate contentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var obj = {\n encrypted: false\n };\n var safeContents = null;\n var data = capture.content.value[0];\n switch(asn1.derToOid(capture.contentType)) {\n case pki.oids.data:\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.');\n }\n safeContents = _decodePkcs7Data(data).value;\n break;\n case pki.oids.encryptedData:\n safeContents = _decryptSafeContents(data, password);\n obj.encrypted = true;\n break;\n default:\n var error = new Error('Unsupported PKCS#12 contentType.');\n error.contentType = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n obj.safeBags = _decodeSafeContents(safeContents, strict, password);\n pfx.safeContents.push(obj);\n }\n}\n\n/**\n * Decrypt PKCS#7 EncryptedData structure.\n *\n * @param data ASN.1 encoded EncryptedContentInfo object.\n * @param password The user-provided password.\n *\n * @return The decrypted SafeContents (ASN.1 object).\n */\nfunction _decryptSafeContents(data, password) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(\n data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) {\n var error = new Error('Cannot read EncryptedContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.contentType);\n if(oid !== pki.oids.data) {\n var error = new Error(\n 'PKCS#12 EncryptedContentInfo ContentType is not Data.');\n error.oid = oid;\n throw error;\n }\n\n // get cipher\n oid = asn1.derToOid(capture.encAlgorithm);\n var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);\n\n // get encrypted data\n var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);\n var encrypted = forge.util.createBuffer(encryptedContentAsn1.value);\n\n cipher.update(encrypted);\n if(!cipher.finish()) {\n throw new Error('Failed to decrypt PKCS#12 SafeContents.');\n }\n\n return cipher.output.getBytes();\n}\n\n/**\n * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects.\n *\n * The safeContents is a BER-encoded SEQUENCE OF SafeBag.\n *\n * @param {String} safeContents BER-encoded safeContents.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n *\n * @return {Array} Array of Bag objects.\n */\nfunction _decodeSafeContents(safeContents, strict, password) {\n // if strict and no safe contents, return empty safes\n if(!strict && safeContents.length === 0) {\n return [];\n }\n\n // actually it's BER-encoded\n safeContents = asn1.fromDer(safeContents, strict);\n\n if(safeContents.tagClass !== asn1.Class.UNIVERSAL ||\n safeContents.type !== asn1.Type.SEQUENCE ||\n safeContents.constructed !== true) {\n throw new Error(\n 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.');\n }\n\n var res = [];\n for(var i = 0; i < safeContents.value.length; i++) {\n var safeBag = safeContents.value[i];\n\n // validate SafeBag and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) {\n var error = new Error('Cannot read SafeBag.');\n error.errors = errors;\n throw error;\n }\n\n /* Create bag object and push to result array. */\n var bag = {\n type: asn1.derToOid(capture.bagId),\n attributes: _decodeBagAttributes(capture.bagAttributes)\n };\n res.push(bag);\n\n var validator, decoder;\n var bagAsn1 = capture.bagValue.value[0];\n switch(bag.type) {\n case pki.oids.pkcs8ShroudedKeyBag:\n /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt.\n Afterwards we can handle it like a keyBag,\n which is a PrivateKeyInfo. */\n bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);\n if(bagAsn1 === null) {\n throw new Error(\n 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?');\n }\n\n /* fall through */\n case pki.oids.keyBag:\n /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our\n PKI module, hence we don't have to do validation/capturing here,\n just pass what we already got. */\n try {\n bag.key = pki.privateKeyFromAsn1(bagAsn1);\n } catch(e) {\n // ignore unknown key type, pass asn1 value\n bag.key = null;\n bag.asn1 = bagAsn1;\n }\n continue; /* Nothing more to do. */\n\n case pki.oids.certBag:\n /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates.\n Therefore put the SafeBag content through another validator to\n capture the fields. Afterwards check & store the results. */\n validator = certBagValidator;\n decoder = function() {\n if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {\n var error = new Error(\n 'Unsupported certificate type, only X.509 supported.');\n error.oid = asn1.derToOid(capture.certId);\n throw error;\n }\n\n // true=produce cert hash\n var certAsn1 = asn1.fromDer(capture.cert, strict);\n try {\n bag.cert = pki.certificateFromAsn1(certAsn1, true);\n } catch(e) {\n // ignore unknown cert type, pass asn1 value\n bag.cert = null;\n bag.asn1 = certAsn1;\n }\n };\n break;\n\n default:\n var error = new Error('Unsupported PKCS#12 SafeBag type.');\n error.oid = bag.type;\n throw error;\n }\n\n /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */\n if(validator !== undefined &&\n !asn1.validate(bagAsn1, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 ' + validator.name);\n error.errors = errors;\n throw error;\n }\n\n /* Call decoder function from above to store the results. */\n decoder();\n }\n\n return res;\n}\n\n/**\n * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object.\n *\n * @param attributes SET OF PKCS12Attribute (ASN.1 object).\n *\n * @return the decoded attributes.\n */\nfunction _decodeBagAttributes(attributes) {\n var decodedAttrs = {};\n\n if(attributes !== undefined) {\n for(var i = 0; i < attributes.length; ++i) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 BagAttribute.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.oid);\n if(pki.oids[oid] === undefined) {\n // unsupported attribute type, ignore.\n continue;\n }\n\n decodedAttrs[pki.oids[oid]] = [];\n for(var j = 0; j < capture.values.length; ++j) {\n decodedAttrs[pki.oids[oid]].push(capture.values[j].value);\n }\n }\n }\n\n return decodedAttrs;\n}\n\n/**\n * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a\n * password is provided then the private key will be encrypted.\n *\n * An entire certificate chain may also be included. To do this, pass\n * an array for the \"cert\" parameter where the first certificate is\n * the one that is paired with the private key and each subsequent one\n * verifies the previous one. The certificates may be in PEM format or\n * have been already parsed by Forge.\n *\n * @todo implement password-based-encryption for the whole package\n *\n * @param key the private key.\n * @param cert the certificate (may be an array of certificates in order\n * to specify a certificate chain).\n * @param password the password to use, null for none.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * useMac true to include a MAC, false not to, defaults to true.\n * localKeyId the local key ID to use, in hex.\n * friendlyName the friendly name to use.\n * generateLocalKeyId true to generate a random local key ID,\n * false not to, defaults to true.\n *\n * @return the PKCS#12 PFX ASN.1 object.\n */\np12.toPkcs12Asn1 = function(key, cert, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || options.encAlgorithm || 'aes128';\n if(!('useMac' in options)) {\n options.useMac = true;\n }\n if(!('localKeyId' in options)) {\n options.localKeyId = null;\n }\n if(!('generateLocalKeyId' in options)) {\n options.generateLocalKeyId = true;\n }\n\n var localKeyId = options.localKeyId;\n var bagAttrs;\n if(localKeyId !== null) {\n localKeyId = forge.util.hexToBytes(localKeyId);\n } else if(options.generateLocalKeyId) {\n // use SHA-1 of paired cert, if available\n if(cert) {\n var pairedCert = forge.util.isArray(cert) ? cert[0] : cert;\n if(typeof pairedCert === 'string') {\n pairedCert = pki.certificateFromPem(pairedCert);\n }\n var sha1 = forge.md.sha1.create();\n sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());\n localKeyId = sha1.digest().getBytes();\n } else {\n // FIXME: consider using SHA-1 of public key (which can be generated\n // from private key components), see: cert.generateSubjectKeyIdentifier\n // generate random bytes\n localKeyId = forge.random.getBytes(20);\n }\n }\n\n var attrs = [];\n if(localKeyId !== null) {\n attrs.push(\n // localKeyID\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.localKeyId).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n localKeyId)\n ])\n ]));\n }\n if('friendlyName' in options) {\n attrs.push(\n // friendlyName\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.friendlyName).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false,\n options.friendlyName)\n ])\n ]));\n }\n\n if(attrs.length > 0) {\n bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs);\n }\n\n // collect contents for AuthenticatedSafe\n var contents = [];\n\n // create safe bag(s) for certificate chain\n var chain = [];\n if(cert !== null) {\n if(forge.util.isArray(cert)) {\n chain = cert;\n } else {\n chain = [cert];\n }\n }\n\n var certSafeBags = [];\n for(var i = 0; i < chain.length; ++i) {\n // convert cert from PEM as necessary\n cert = chain[i];\n if(typeof cert === 'string') {\n cert = pki.certificateFromPem(cert);\n }\n\n // SafeBag\n var certBagAttrs = (i === 0) ? bagAttrs : undefined;\n var certAsn1 = pki.certificateToAsn1(cert);\n var certSafeBag =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.certBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // CertBag\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // certId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.x509Certificate).getBytes()),\n // certValue (x509Certificate)\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certAsn1).getBytes())\n ])])]),\n // bagAttributes (OPTIONAL)\n certBagAttrs\n ]);\n certSafeBags.push(certSafeBag);\n }\n\n if(certSafeBags.length > 0) {\n // SafeContents\n var certSafeContents = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags);\n\n // ContentInfo\n var certCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certSafeContents).getBytes())\n ])\n ]);\n contents.push(certCI);\n }\n\n // create safe contents for private key\n var keyBag = null;\n if(key !== null) {\n // SafeBag\n var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));\n if(password === null) {\n // no encryption\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.keyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // PrivateKeyInfo\n pkAsn1\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n } else {\n // encrypted PrivateKeyInfo\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // EncryptedPrivateKeyInfo\n pki.encryptPrivateKeyInfo(pkAsn1, password, options)\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n }\n\n // SafeContents\n var keySafeContents =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]);\n\n // ContentInfo\n var keyCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(keySafeContents).getBytes())\n ])\n ]);\n contents.push(keyCI);\n }\n\n // create AuthenticatedSafe by stringing together the contents\n var safe = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents);\n\n var macData;\n if(options.useMac) {\n // MacData\n var sha1 = forge.md.sha1.create();\n var macSalt = new forge.util.ByteBuffer(\n forge.random.getBytes(options.saltSize));\n var count = options.count;\n // 160-bit key\n var key = p12.generateKey(password, macSalt, 3, count, 20);\n var mac = forge.hmac.create();\n mac.start(sha1, key);\n mac.update(asn1.toDer(safe).getBytes());\n var macValue = mac.getMac();\n macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // mac DigestInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm = SHA-1\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.sha1).getBytes()),\n // parameters = Null\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // digest\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, macValue.getBytes())\n ]),\n // macSalt OCTET STRING\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()),\n // iterations INTEGER (XXX: Only support count < 65536)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(count).getBytes()\n )\n ]);\n }\n\n // PFX\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (3)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(3).getBytes()),\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(safe).getBytes())\n ])\n ]),\n macData\n ]);\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\np12.generateKey = forge.pbe.generatePkcs12Key;\n","/**\n * Javascript implementation of PKCS#7 v1.5.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n *\n * Currently this implementation only supports ContentType of EnvelopedData,\n * EncryptedData, or SignedData at the root level. The top level elements may\n * contain only a ContentInfo of ContentType Data, i.e. plain data. Further\n * nesting is not (yet) supported.\n *\n * The Forge validators for PKCS #7's ASN.1 structures are available from\n * a separate file pkcs7asn1.js, since those are referenced from other\n * PKCS standards like PKCS #12.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./oids');\nrequire('./pem');\nrequire('./pkcs7asn1');\nrequire('./random');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};\n\n/**\n * Converts a PKCS#7 message from PEM format.\n *\n * @param pem the PEM-formatted PKCS#7 message.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PKCS7') {\n var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +\n 'header type is not \"PKCS#7\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return p7.messageFromAsn1(obj);\n};\n\n/**\n * Converts a PKCS#7 message to PEM format.\n *\n * @param msg The PKCS#7 message object\n * @param maxline The maximum characters per line, defaults to 64.\n *\n * @return The PEM-formatted PKCS#7 message.\n */\np7.messageToPem = function(msg, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var pemObj = {\n type: 'PKCS7',\n body: asn1.toDer(msg.toAsn1()).getBytes()\n };\n return forge.pem.encode(pemObj, {maxline: maxline});\n};\n\n/**\n * Converts a PKCS#7 message from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a ContentInfo.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromAsn1 = function(obj) {\n // validate root level ContentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not an PKCS#7 ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var contentType = asn1.derToOid(capture.contentType);\n var msg;\n\n switch(contentType) {\n case forge.pki.oids.envelopedData:\n msg = p7.createEnvelopedData();\n break;\n\n case forge.pki.oids.encryptedData:\n msg = p7.createEncryptedData();\n break;\n\n case forge.pki.oids.signedData:\n msg = p7.createSignedData();\n break;\n\n default:\n throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +\n contentType + ' is not (yet) supported.');\n }\n\n msg.fromAsn1(capture.content.value[0]);\n return msg;\n};\n\np7.createSignedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.signedData,\n version: 1,\n certificates: [],\n crls: [],\n // TODO: add json-formatted signer stuff here?\n signers: [],\n // populated during sign()\n digestAlgorithmIdentifiers: [],\n contentInfo: null,\n signerInfos: [],\n\n fromAsn1: function(obj) {\n // validate SignedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.signedDataValidator);\n msg.certificates = [];\n msg.crls = [];\n msg.digestAlgorithmIdentifiers = [];\n msg.contentInfo = null;\n msg.signerInfos = [];\n\n if(msg.rawCapture.certificates) {\n var certs = msg.rawCapture.certificates.value;\n for(var i = 0; i < certs.length; ++i) {\n msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));\n }\n }\n\n // TODO: parse crls\n },\n\n toAsn1: function() {\n // degenerate case with no content\n if(!msg.contentInfo) {\n msg.sign();\n }\n\n var certs = [];\n for(var i = 0; i < msg.certificates.length; ++i) {\n certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));\n }\n\n var crls = [];\n // TODO: implement CRLs\n\n // [0] SignedData\n var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // DigestAlgorithmIdentifiers\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.digestAlgorithmIdentifiers),\n // ContentInfo\n msg.contentInfo\n ])\n ]);\n if(certs.length > 0) {\n // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));\n }\n if(crls.length > 0) {\n // [1] IMPLICIT CertificateRevocationLists OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));\n }\n // SignerInfos\n signedData.value[0].value.push(\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.signerInfos));\n\n // ContentInfo\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] SignedData\n signedData\n ]);\n },\n\n /**\n * Add (another) entity to list of signers.\n *\n * Note: If authenticatedAttributes are provided, then, per RFC 2315,\n * they must include at least two attributes: content type and\n * message digest. The message digest attribute value will be\n * auto-calculated during signing and will be ignored if provided.\n *\n * Here's an example of providing these two attributes:\n *\n * forge.pkcs7.createSignedData();\n * p7.addSigner({\n * issuer: cert.issuer.attributes,\n * serialNumber: cert.serialNumber,\n * key: privateKey,\n * digestAlgorithm: forge.pki.oids.sha1,\n * authenticatedAttributes: [{\n * type: forge.pki.oids.contentType,\n * value: forge.pki.oids.data\n * }, {\n * type: forge.pki.oids.messageDigest\n * }]\n * });\n *\n * TODO: Support [subjectKeyIdentifier] as signer's ID.\n *\n * @param signer the signer information:\n * key the signer's private key.\n * [certificate] a certificate containing the public key\n * associated with the signer's private key; use this option as\n * an alternative to specifying signer.issuer and\n * signer.serialNumber.\n * [issuer] the issuer attributes (eg: cert.issuer.attributes).\n * [serialNumber] the signer's certificate's serial number in\n * hexadecimal (eg: cert.serialNumber).\n * [digestAlgorithm] the message digest OID, as a string, to use\n * (eg: forge.pki.oids.sha1).\n * [authenticatedAttributes] an optional array of attributes\n * to also sign along with the content.\n */\n addSigner: function(signer) {\n var issuer = signer.issuer;\n var serialNumber = signer.serialNumber;\n if(signer.certificate) {\n var cert = signer.certificate;\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n issuer = cert.issuer.attributes;\n serialNumber = cert.serialNumber;\n }\n var key = signer.key;\n if(!key) {\n throw new Error(\n 'Could not add PKCS#7 signer; no private key specified.');\n }\n if(typeof key === 'string') {\n key = forge.pki.privateKeyFromPem(key);\n }\n\n // ensure OID known for digest algorithm\n var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;\n switch(digestAlgorithm) {\n case forge.pki.oids.sha1:\n case forge.pki.oids.sha256:\n case forge.pki.oids.sha384:\n case forge.pki.oids.sha512:\n case forge.pki.oids.md5:\n break;\n default:\n throw new Error(\n 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +\n digestAlgorithm);\n }\n\n // if authenticatedAttributes is present, then the attributes\n // must contain at least PKCS #9 content-type and message-digest\n var authenticatedAttributes = signer.authenticatedAttributes || [];\n if(authenticatedAttributes.length > 0) {\n var contentType = false;\n var messageDigest = false;\n for(var i = 0; i < authenticatedAttributes.length; ++i) {\n var attr = authenticatedAttributes[i];\n if(!contentType && attr.type === forge.pki.oids.contentType) {\n contentType = true;\n if(messageDigest) {\n break;\n }\n continue;\n }\n if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {\n messageDigest = true;\n if(contentType) {\n break;\n }\n continue;\n }\n }\n\n if(!contentType || !messageDigest) {\n throw new Error('Invalid signer.authenticatedAttributes. If ' +\n 'signer.authenticatedAttributes is specified, then it must ' +\n 'contain at least two attributes, PKCS #9 content-type and ' +\n 'PKCS #9 message-digest.');\n }\n }\n\n msg.signers.push({\n key: key,\n version: 1,\n issuer: issuer,\n serialNumber: serialNumber,\n digestAlgorithm: digestAlgorithm,\n signatureAlgorithm: forge.pki.oids.rsaEncryption,\n signature: null,\n authenticatedAttributes: authenticatedAttributes,\n unauthenticatedAttributes: []\n });\n },\n\n /**\n * Signs the content.\n * @param options Options to apply when signing:\n * [detached] boolean. If signing should be done in detached mode. Defaults to false.\n */\n sign: function(options) {\n options = options || {};\n // auto-generate content info\n if(typeof msg.content !== 'object' || msg.contentInfo === null) {\n // use Data ContentInfo\n msg.contentInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes())\n ]);\n\n // add actual content, if present\n if('content' in msg) {\n var content;\n if(msg.content instanceof forge.util.ByteBuffer) {\n content = msg.content.bytes();\n } else if(typeof msg.content === 'string') {\n content = forge.util.encodeUtf8(msg.content);\n }\n\n if (options.detached) {\n msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);\n } else {\n msg.contentInfo.value.push(\n // [0] EXPLICIT content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n content)\n ]));\n }\n }\n }\n\n // no signers, return early (degenerate case for certificate container)\n if(msg.signers.length === 0) {\n return;\n }\n\n // generate digest algorithm identifiers\n var mds = addDigestAlgorithmIds();\n\n // generate signerInfos\n addSignerInfos(mds);\n },\n\n verify: function() {\n throw new Error('PKCS#7 signature verification not yet implemented.');\n },\n\n /**\n * Add a certificate.\n *\n * @param cert the certificate to add.\n */\n addCertificate: function(cert) {\n // convert from PEM\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n msg.certificates.push(cert);\n },\n\n /**\n * Add a certificate revokation list.\n *\n * @param crl the certificate revokation list to add.\n */\n addCertificateRevokationList: function(crl) {\n throw new Error('PKCS#7 CRL support not yet implemented.');\n }\n };\n return msg;\n\n function addDigestAlgorithmIds() {\n var mds = {};\n\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n var oid = signer.digestAlgorithm;\n if(!(oid in mds)) {\n // content digest\n mds[oid] = forge.md[forge.pki.oids[oid]].create();\n }\n if(signer.authenticatedAttributes.length === 0) {\n // no custom attributes to digest; use content message digest\n signer.md = mds[oid];\n } else {\n // custom attributes to be digested; use own message digest\n // TODO: optimize to just copy message digest state if that\n // feature is ever supported with message digests\n signer.md = forge.md[forge.pki.oids[oid]].create();\n }\n }\n\n // add unique digest algorithm identifiers\n msg.digestAlgorithmIdentifiers = [];\n for(var oid in mds) {\n msg.digestAlgorithmIdentifiers.push(\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oid).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n\n return mds;\n }\n\n function addSignerInfos(mds) {\n var content;\n\n if (msg.detachedContent) {\n // Signature has been made in detached mode.\n content = msg.detachedContent;\n } else {\n // Note: ContentInfo is a SEQUENCE with 2 values, second value is\n // the content field and is optional for a ContentInfo but required here\n // since signers are present\n // get ContentInfo content\n content = msg.contentInfo.value[1];\n // skip [0] EXPLICIT content wrapper\n content = content.value[0];\n }\n\n if(!content) {\n throw new Error(\n 'Could not sign PKCS#7 message; there is no content to sign.');\n }\n\n // get ContentInfo content type\n var contentType = asn1.derToOid(msg.contentInfo.value[0].value);\n\n // serialize content\n var bytes = asn1.toDer(content);\n\n // skip identifier and length per RFC 2315 9.3\n // skip identifier (1 byte)\n bytes.getByte();\n // read and discard length bytes\n asn1.getBerValueLength(bytes);\n bytes = bytes.getBytes();\n\n // digest content DER value bytes\n for(var oid in mds) {\n mds[oid].start().update(bytes);\n }\n\n // sign content\n var signingTime = new Date();\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n\n if(signer.authenticatedAttributes.length === 0) {\n // if ContentInfo content type is not \"Data\", then\n // authenticatedAttributes must be present per RFC 2315\n if(contentType !== forge.pki.oids.data) {\n throw new Error(\n 'Invalid signer; authenticatedAttributes must be present ' +\n 'when the ContentInfo content type is not PKCS#7 Data.');\n }\n } else {\n // process authenticated attributes\n // [0] IMPLICIT\n signer.authenticatedAttributesAsn1 = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // per RFC 2315, attributes are to be digested using a SET container\n // not the above [0] IMPLICIT container\n var attrsAsn1 = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);\n\n for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {\n var attr = signer.authenticatedAttributes[ai];\n if(attr.type === forge.pki.oids.messageDigest) {\n // use content message digest as value\n attr.value = mds[signer.digestAlgorithm].digest();\n } else if(attr.type === forge.pki.oids.signingTime) {\n // auto-populate signing time if not already set\n if(!attr.value) {\n attr.value = signingTime;\n }\n }\n\n // convert to ASN.1 and push onto Attributes SET (for signing) and\n // onto authenticatedAttributesAsn1 to complete SignedData ASN.1\n // TODO: optimize away duplication\n attrsAsn1.value.push(_attributeToAsn1(attr));\n signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));\n }\n\n // DER-serialize and digest SET OF attributes only\n bytes = asn1.toDer(attrsAsn1).getBytes();\n signer.md.start().update(bytes);\n }\n\n // sign digest\n signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');\n }\n\n // add signer info\n msg.signerInfos = _signersToAsn1(msg.signers);\n }\n};\n\n/**\n * Creates an empty PKCS#7 message of type EncryptedData.\n *\n * @return the message.\n */\np7.createEncryptedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.encryptedData,\n version: 0,\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EncryptedData content block (in ASN.1 format)\n *\n * @param obj The ASN.1 representation of the EncryptedData content block\n */\n fromAsn1: function(obj) {\n // Validate EncryptedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);\n },\n\n /**\n * Decrypt encrypted content\n *\n * @param key The (symmetric) key as a byte buffer\n */\n decrypt: function(key) {\n if(key !== undefined) {\n msg.encryptedContent.key = key;\n }\n _decryptContent(msg);\n }\n };\n return msg;\n};\n\n/**\n * Creates an empty PKCS#7 message of type EnvelopedData.\n *\n * @return the message.\n */\np7.createEnvelopedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.envelopedData,\n version: 0,\n recipients: [],\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EnvelopedData content block (in ASN.1 format)\n *\n * @param obj the ASN.1 representation of the EnvelopedData content block.\n */\n fromAsn1: function(obj) {\n // validate EnvelopedData content block and capture data\n var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);\n msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);\n },\n\n toAsn1: function() {\n // ContentInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] EnvelopedData\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // RecipientInfos\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n _recipientsToAsn1(msg.recipients)),\n // EncryptedContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,\n _encryptedContentToAsn1(msg.encryptedContent))\n ])\n ])\n ]);\n },\n\n /**\n * Find recipient by X.509 certificate's issuer.\n *\n * @param cert the certificate with the issuer to look for.\n *\n * @return the recipient object.\n */\n findRecipient: function(cert) {\n var sAttr = cert.issuer.attributes;\n\n for(var i = 0; i < msg.recipients.length; ++i) {\n var r = msg.recipients[i];\n var rAttr = r.issuer;\n\n if(r.serialNumber !== cert.serialNumber) {\n continue;\n }\n\n if(rAttr.length !== sAttr.length) {\n continue;\n }\n\n var match = true;\n for(var j = 0; j < sAttr.length; ++j) {\n if(rAttr[j].type !== sAttr[j].type ||\n rAttr[j].value !== sAttr[j].value) {\n match = false;\n break;\n }\n }\n\n if(match) {\n return r;\n }\n }\n\n return null;\n },\n\n /**\n * Decrypt enveloped content\n *\n * @param recipient The recipient object related to the private key\n * @param privKey The (RSA) private key object\n */\n decrypt: function(recipient, privKey) {\n if(msg.encryptedContent.key === undefined && recipient !== undefined &&\n privKey !== undefined) {\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n case forge.pki.oids.desCBC:\n var key = privKey.decrypt(recipient.encryptedContent.content);\n msg.encryptedContent.key = forge.util.createBuffer(key);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, ' +\n 'OID ' + recipient.encryptedContent.algorithm);\n }\n }\n\n _decryptContent(msg);\n },\n\n /**\n * Add (another) entity to list of recipients.\n *\n * @param cert The certificate of the entity to add.\n */\n addRecipient: function(cert) {\n msg.recipients.push({\n version: 0,\n issuer: cert.issuer.attributes,\n serialNumber: cert.serialNumber,\n encryptedContent: {\n // We simply assume rsaEncryption here, since forge.pki only\n // supports RSA so far. If the PKI module supports other\n // ciphers one day, we need to modify this one as well.\n algorithm: forge.pki.oids.rsaEncryption,\n key: cert.publicKey\n }\n });\n },\n\n /**\n * Encrypt enveloped content.\n *\n * This function supports two optional arguments, cipher and key, which\n * can be used to influence symmetric encryption. Unless cipher is\n * provided, the cipher specified in encryptedContent.algorithm is used\n * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key\n * is (re-)used. If that one's not set, a random key will be generated\n * automatically.\n *\n * @param [key] The key to be used for symmetric encryption.\n * @param [cipher] The OID of the symmetric cipher to use.\n */\n encrypt: function(key, cipher) {\n // Part 1: Symmetric encryption\n if(msg.encryptedContent.content === undefined) {\n cipher = cipher || msg.encryptedContent.algorithm;\n key = key || msg.encryptedContent.key;\n\n var keyLen, ivLen, ciphFn;\n switch(cipher) {\n case forge.pki.oids['aes128-CBC']:\n keyLen = 16;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes192-CBC']:\n keyLen = 24;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes256-CBC']:\n keyLen = 32;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['des-EDE3-CBC']:\n keyLen = 24;\n ivLen = 8;\n ciphFn = forge.des.createEncryptionCipher;\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' + cipher);\n }\n\n if(key === undefined) {\n key = forge.util.createBuffer(forge.random.getBytes(keyLen));\n } else if(key.length() != keyLen) {\n throw new Error('Symmetric key has wrong length; ' +\n 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');\n }\n\n // Keep a copy of the key & IV in the object, so the caller can\n // use it for whatever reason.\n msg.encryptedContent.algorithm = cipher;\n msg.encryptedContent.key = key;\n msg.encryptedContent.parameter = forge.util.createBuffer(\n forge.random.getBytes(ivLen));\n\n var ciph = ciphFn(key);\n ciph.start(msg.encryptedContent.parameter.copy());\n ciph.update(msg.content);\n\n // The finish function does PKCS#7 padding by default, therefore\n // no action required by us.\n if(!ciph.finish()) {\n throw new Error('Symmetric encryption failed.');\n }\n\n msg.encryptedContent.content = ciph.output;\n }\n\n // Part 2: asymmetric encryption for each recipient\n for(var i = 0; i < msg.recipients.length; ++i) {\n var recipient = msg.recipients[i];\n\n // Nothing to do, encryption already done.\n if(recipient.encryptedContent.content !== undefined) {\n continue;\n }\n\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n recipient.encryptedContent.content =\n recipient.encryptedContent.key.encrypt(\n msg.encryptedContent.key.data);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, OID ' +\n recipient.encryptedContent.algorithm);\n }\n }\n }\n };\n return msg;\n};\n\n/**\n * Converts a single recipient from an ASN.1 object.\n *\n * @param obj the ASN.1 RecipientInfo.\n *\n * @return the recipient object.\n */\nfunction _recipientFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +\n 'ASN.1 object is not an PKCS#7 RecipientInfo.');\n error.errors = errors;\n throw error;\n }\n\n return {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n encryptedContent: {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: capture.encParameter ? capture.encParameter.value : undefined,\n content: capture.encKey\n }\n };\n}\n\n/**\n * Converts a single recipient object to an ASN.1 object.\n *\n * @param obj the recipient object.\n *\n * @return the ASN.1 RecipientInfo.\n */\nfunction _recipientToAsn1(obj) {\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // IssuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // Serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // KeyEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),\n // Parameter, force NULL, only RSA supported for now.\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // EncryptedKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n obj.encryptedContent.content)\n ]);\n}\n\n/**\n * Map a set of RecipientInfo ASN.1 objects to recipient objects.\n *\n * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).\n *\n * @return an array of recipient objects.\n */\nfunction _recipientsFromAsn1(infos) {\n var ret = [];\n for(var i = 0; i < infos.length; ++i) {\n ret.push(_recipientFromAsn1(infos[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of recipient objects to ASN.1 RecipientInfo objects.\n *\n * @param recipients an array of recipientInfo objects.\n *\n * @return an array of ASN.1 RecipientInfos.\n */\nfunction _recipientsToAsn1(recipients) {\n var ret = [];\n for(var i = 0; i < recipients.length; ++i) {\n ret.push(_recipientToAsn1(recipients[i]));\n }\n return ret;\n}\n\n/**\n * Converts a single signer from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a SignerInfo.\n *\n * @return the signer object.\n */\nfunction _signerFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 SignerInfo. ' +\n 'ASN.1 object is not an PKCS#7 SignerInfo.');\n error.errors = errors;\n throw error;\n }\n\n var rval = {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),\n signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),\n signature: capture.signature,\n authenticatedAttributes: [],\n unauthenticatedAttributes: []\n };\n\n // TODO: convert attributes\n var authenticatedAttributes = capture.authenticatedAttributes || [];\n var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];\n\n return rval;\n}\n\n/**\n * Converts a single signerInfo object to an ASN.1 object.\n *\n * @param obj the signerInfo object.\n *\n * @return the ASN.1 representation of a SignerInfo.\n */\nfunction _signerToAsn1(obj) {\n // SignerInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // issuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.digestAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]);\n\n // authenticatedAttributes (OPTIONAL)\n if(obj.authenticatedAttributesAsn1) {\n // add ASN.1 previously generated during signing\n rval.value.push(obj.authenticatedAttributesAsn1);\n }\n\n // digestEncryptionAlgorithm\n rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.signatureAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n\n // encryptedDigest\n rval.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));\n\n // unauthenticatedAttributes (OPTIONAL)\n if(obj.unauthenticatedAttributes.length > 0) {\n // [1] IMPLICIT\n var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);\n for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {\n var attr = obj.unauthenticatedAttributes[i];\n attrsAsn1.values.push(_attributeToAsn1(attr));\n }\n rval.value.push(attrsAsn1);\n }\n\n return rval;\n}\n\n/**\n * Map a set of SignerInfo ASN.1 objects to an array of signer objects.\n *\n * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).\n *\n * @return an array of signers objects.\n */\nfunction _signersFromAsn1(signerInfoAsn1s) {\n var ret = [];\n for(var i = 0; i < signerInfoAsn1s.length; ++i) {\n ret.push(_signerFromAsn1(signerInfoAsn1s[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of signer objects to ASN.1 objects.\n *\n * @param signers an array of signer objects.\n *\n * @return an array of ASN.1 SignerInfos.\n */\nfunction _signersToAsn1(signers) {\n var ret = [];\n for(var i = 0; i < signers.length; ++i) {\n ret.push(_signerToAsn1(signers[i]));\n }\n return ret;\n}\n\n/**\n * Convert an attribute object to an ASN.1 Attribute.\n *\n * @param attr the attribute object.\n *\n * @return the ASN.1 Attribute.\n */\nfunction _attributeToAsn1(attr) {\n var value;\n\n // TODO: generalize to support more attributes\n if(attr.type === forge.pki.oids.contentType) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.value).getBytes());\n } else if(attr.type === forge.pki.oids.messageDigest) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n attr.value.bytes());\n } else if(attr.type === forge.pki.oids.signingTime) {\n /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049\n (inclusive) MUST be encoded as UTCTime. Any dates with year values\n before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]\n UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST\n include seconds (i.e., times are YYMMDDHHMMSSZ), even where the\n number of seconds is zero. Midnight (GMT) must be represented as\n \"YYMMDD000000Z\". */\n // TODO: make these module-level constants\n var jan_1_1950 = new Date('1950-01-01T00:00:00Z');\n var jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n var date = attr.value;\n if(typeof date === 'string') {\n // try to parse date\n var timestamp = Date.parse(date);\n if(!isNaN(timestamp)) {\n date = new Date(timestamp);\n } else if(date.length === 13) {\n // YYMMDDHHMMSSZ (13 chars for UTCTime)\n date = asn1.utcTimeToDate(date);\n } else {\n // assume generalized time\n date = asn1.generalizedTimeToDate(date);\n }\n }\n\n if(date >= jan_1_1950 && date < jan_1_2050) {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n }\n\n // TODO: expose as common API call\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n value\n ])\n ]);\n}\n\n/**\n * Map messages encrypted content to ASN.1 objects.\n *\n * @param ec The encryptedContent object of the message.\n *\n * @return ASN.1 representation of the encryptedContent object (SEQUENCE).\n */\nfunction _encryptedContentToAsn1(ec) {\n return [\n // ContentType, always Data for the moment\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes()),\n // ContentEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ec.algorithm).getBytes()),\n // Parameters (IV)\n !ec.parameter ?\n undefined :\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.parameter.getBytes())\n ]),\n // [0] EncryptedContent\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.content.getBytes())\n ])\n ];\n}\n\n/**\n * Reads the \"common part\" of an PKCS#7 content block (in ASN.1 format)\n *\n * This function reads the \"common part\" of the PKCS#7 content blocks\n * EncryptedData and EnvelopedData, i.e. version number and symmetrically\n * encrypted content block.\n *\n * The result of the ASN.1 validate and capture process is returned\n * to allow the caller to extract further data, e.g. the list of recipients\n * in case of a EnvelopedData object.\n *\n * @param msg the PKCS#7 object to read the data to.\n * @param obj the ASN.1 representation of the content block.\n * @param validator the ASN.1 structure validator object to use.\n *\n * @return the value map captured by validator object.\n */\nfunction _fromAsn1(msg, obj, validator) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not a supported PKCS#7 message.');\n error.errors = error;\n throw error;\n }\n\n // Check contentType, so far we only support (raw) Data.\n var contentType = asn1.derToOid(capture.contentType);\n if(contentType !== forge.pki.oids.data) {\n throw new Error('Unsupported PKCS#7 message. ' +\n 'Only wrapped ContentType Data supported.');\n }\n\n if(capture.encryptedContent) {\n var content = '';\n if(forge.util.isArray(capture.encryptedContent)) {\n for(var i = 0; i < capture.encryptedContent.length; ++i) {\n if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting encrypted ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.encryptedContent[i].value;\n }\n } else {\n content = capture.encryptedContent;\n }\n msg.encryptedContent = {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: forge.util.createBuffer(capture.encParameter.value),\n content: forge.util.createBuffer(content)\n };\n }\n\n if(capture.content) {\n var content = '';\n if(forge.util.isArray(capture.content)) {\n for(var i = 0; i < capture.content.length; ++i) {\n if(capture.content[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.content[i].value;\n }\n } else {\n content = capture.content;\n }\n msg.content = forge.util.createBuffer(content);\n }\n\n msg.version = capture.version.charCodeAt(0);\n msg.rawCapture = capture;\n\n return capture;\n}\n\n/**\n * Decrypt the symmetrically encrypted content block of the PKCS#7 message.\n *\n * Decryption is skipped in case the PKCS#7 message object already has a\n * (decrypted) content attribute. The algorithm, key and cipher parameters\n * (probably the iv) are taken from the encryptedContent attribute of the\n * message object.\n *\n * @param The PKCS#7 message object.\n */\nfunction _decryptContent(msg) {\n if(msg.encryptedContent.key === undefined) {\n throw new Error('Symmetric key not available.');\n }\n\n if(msg.content === undefined) {\n var ciph;\n\n switch(msg.encryptedContent.algorithm) {\n case forge.pki.oids['aes128-CBC']:\n case forge.pki.oids['aes192-CBC']:\n case forge.pki.oids['aes256-CBC']:\n ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n case forge.pki.oids['desCBC']:\n case forge.pki.oids['des-EDE3-CBC']:\n ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' +\n msg.encryptedContent.algorithm);\n }\n ciph.start(msg.encryptedContent.parameter);\n ciph.update(msg.encryptedContent.content);\n\n if(!ciph.finish()) {\n throw new Error('Symmetric decryption failed.');\n }\n\n msg.content = ciph.output;\n }\n}\n","/**\n * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.\n *\n * @author Dave Longley\n * @author Stefan Siegl\n *\n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#7 is as follows\n * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):\n *\n * A PKCS#7 message consists of a ContentInfo on root level, which may\n * contain any number of further ContentInfo nested into it.\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * EnvelopedData ::= SEQUENCE {\n * version Version,\n * recipientInfos RecipientInfos,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * EncryptedData ::= SEQUENCE {\n * version Version,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)\n * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }\n *\n * SignedData ::= SEQUENCE {\n * version INTEGER,\n * digestAlgorithms DigestAlgorithmIdentifiers,\n * contentInfo ContentInfo,\n * certificates [0] IMPLICIT Certificates OPTIONAL,\n * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n * signerInfos SignerInfos\n * }\n *\n * SignerInfos ::= SET OF SignerInfo\n *\n * SignerInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * digestAlgorithm DigestAlgorithmIdentifier,\n * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,\n * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,\n * encryptedDigest EncryptedDigest,\n * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL\n * }\n *\n * EncryptedDigest ::= OCTET STRING\n *\n * Attributes ::= SET OF Attribute\n *\n * Attribute ::= SEQUENCE {\n * attrType OBJECT IDENTIFIER,\n * attrValues SET OF AttributeValue\n * }\n *\n * AttributeValue ::= ANY\n *\n * Version ::= INTEGER\n *\n * RecipientInfos ::= SET OF RecipientInfo\n *\n * EncryptedContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,\n * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL\n * }\n *\n * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of AES and DES3, there is only one,\n * the IV.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * EncryptedContent ::= OCTET STRING\n *\n * RecipientInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,\n * encryptedKey EncryptedKey\n * }\n *\n * IssuerAndSerialNumber ::= SEQUENCE {\n * issuer Name,\n * serialNumber CertificateSerialNumber\n * }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedKey ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./util');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};\nforge.pkcs7 = forge.pkcs7 || {};\nforge.pkcs7.asn1 = p7v;\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'ContentInfo.ContentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n captureAsn1: 'content'\n }]\n};\np7v.contentInfoValidator = contentInfoValidator;\n\nvar encryptedContentInfoValidator = {\n name: 'EncryptedContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'EncryptedContentInfo.encryptedContent',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n /* The PKCS#7 structure output by OpenSSL somewhat differs from what\n * other implementations do generate.\n *\n * OpenSSL generates a structure like this:\n * SEQUENCE {\n * ...\n * [0]\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n *\n * Whereas other implementations (and this PKCS#7 module) generate:\n * SEQUENCE {\n * ...\n * [0] {\n * OCTET STRING\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n * }\n *\n * In order to support both, we just capture the context specific\n * field here. The OCTET STRING bit is removed below.\n */\n capture: 'encryptedContent',\n captureAsn1: 'encryptedContentAsn1'\n }]\n};\n\np7v.envelopedDataValidator = {\n name: 'EnvelopedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EnvelopedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'EnvelopedData.RecipientInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'recipientInfos'\n }].concat(encryptedContentInfoValidator)\n};\n\np7v.encryptedDataValidator = {\n name: 'EncryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }].concat(encryptedContentInfoValidator)\n};\n\nvar signerValidator = {\n name: 'SignerInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false\n }, {\n name: 'SignerInfo.issuerAndSerialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.issuerAndSerialNumber.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'SignerInfo.issuerAndSerialNumber.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'SignerInfo.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'digestAlgorithm'\n }, {\n name: 'SignerInfo.digestAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'digestParameter',\n optional: true\n }]\n }, {\n name: 'SignerInfo.authenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'authenticatedAttributes'\n }, {\n name: 'SignerInfo.digestEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n capture: 'signatureAlgorithm'\n }, {\n name: 'SignerInfo.encryptedDigest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'signature'\n }, {\n name: 'SignerInfo.unauthenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n capture: 'unauthenticatedAttributes'\n }]\n};\n\np7v.signedDataValidator = {\n name: 'SignedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'SignedData.DigestAlgorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'digestAlgorithms'\n },\n contentInfoValidator,\n {\n name: 'SignedData.Certificates',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n optional: true,\n captureAsn1: 'certificates'\n }, {\n name: 'SignedData.CertificateRevocationLists',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n optional: true,\n captureAsn1: 'crls'\n }, {\n name: 'SignedData.SignerInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n capture: 'signerInfos',\n optional: true,\n value: [signerValidator]\n }]\n};\n\np7v.recipientInfoValidator = {\n name: 'RecipientInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'RecipientInfo.issuerAndSerial',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.issuerAndSerial.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'RecipientInfo.issuerAndSerial.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'encParameter',\n optional: true\n }]\n }, {\n name: 'RecipientInfo.encryptedKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encKey'\n }]\n};\n","/**\n * Javascript implementation of a basic Public Key Infrastructure, including\n * support for RSA public and private keys.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./oids');\nrequire('./pbe');\nrequire('./pem');\nrequire('./pbkdf2');\nrequire('./pkcs12');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.\n *\n * Converts PEM-formatted data to DER.\n *\n * @param pem the PEM-formatted data.\n *\n * @return the DER-formatted data.\n */\npki.pemToDer = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PEM to DER; PEM is encrypted.');\n }\n return forge.util.createBuffer(msg.body);\n};\n\n/**\n * Converts an RSA private key from PEM format.\n *\n * @param pem the PEM-formatted private key.\n *\n * @return the private key.\n */\npki.privateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM ' +\n 'header type is not \"PRIVATE KEY\" or \"RSA PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert private key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.privateKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA private key to PEM format.\n *\n * @param key the private key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PRIVATE KEY',\n body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PrivateKeyInfo to PEM format.\n *\n * @param pki the PrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyInfoToPem = function(pki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'PRIVATE KEY',\n body: asn1.toDer(pki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n","/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./jsbn');\nrequire('./random');\n\n(function() {\n\n// forge.prime already defined\nif(forge.prime) {\n module.exports = forge.prime;\n return;\n}\n\n/* PRIME API */\nvar prime = module.exports = forge.prime = forge.prime || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\nvar THIRTY = new BigInteger(null);\nTHIRTY.fromInt(30);\nvar op_or = function(x, y) {return x|y;};\n\n/**\n * Generates a random probable prime with the given number of bits.\n *\n * Alternative algorithms can be specified by name as a string or as an\n * object with custom options like so:\n *\n * {\n * name: 'PRIMEINC',\n * options: {\n * maxBlockTime: ,\n * millerRabinTests: ,\n * workerScript: ,\n * workers: .\n * workLoad: the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * }\n * }\n *\n * @param bits the number of bits for the prime number.\n * @param options the options to use.\n * [algorithm] the algorithm to use (default: 'PRIMEINC').\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n *\n * @return callback(err, num) called once the operation completes.\n */\nprime.generateProbablePrime = function(bits, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // default to PRIMEINC algorithm\n var algorithm = options.algorithm || 'PRIMEINC';\n if(typeof algorithm === 'string') {\n algorithm = {name: algorithm};\n }\n algorithm.options = algorithm.options || {};\n\n // create prng with api that matches BigInteger secure random\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n if(algorithm.name === 'PRIMEINC') {\n return primeincFindPrime(bits, rng, algorithm.options, callback);\n }\n\n throw new Error('Invalid prime generation algorithm: ' + algorithm.name);\n};\n\nfunction primeincFindPrime(bits, rng, options, callback) {\n if('workers' in options) {\n return primeincFindPrimeWithWorkers(bits, rng, options, callback);\n }\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n}\n\nfunction primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {\n // initialize random number\n var num = generateRandom(bits, rng);\n\n /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The\n number we are given is always aligned at 30k + 1. Each time the number is\n determined not to be prime we add to get to the next 'i', eg: if the number\n was at 30k + 1 we add 6. */\n var deltaIdx = 0;\n\n // get required number of MR tests\n var mrTests = getMillerRabinTests(num.bitLength());\n if('millerRabinTests' in options) {\n mrTests = options.millerRabinTests;\n }\n\n // find prime nearest to 'num' for maxBlockTime ms\n // 10 ms gives 5ms of leeway for other calculations before dropping\n // below 60fps (1000/60 == 16.67), but in reality, the number will\n // likely be higher due to an 'atomic' big int modPow\n var maxBlockTime = 10;\n if('maxBlockTime' in options) {\n maxBlockTime = options.maxBlockTime;\n }\n\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n}\n\nfunction _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {\n var start = +new Date();\n do {\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n // do primality test\n if(num.isProbablePrime(mrTests)) {\n return callback(null, num);\n }\n // get next potential prime\n num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));\n\n // keep trying later\n forge.util.setImmediate(function() {\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n });\n}\n\n// NOTE: This algorithm is indeterminate in nature because workers\n// run in parallel looking at different segments of numbers. Even if this\n// algorithm is run twice with the same input from a predictable RNG, it\n// may produce different outputs.\nfunction primeincFindPrimeWithWorkers(bits, rng, options, callback) {\n // web workers unavailable\n if(typeof Worker === 'undefined') {\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n }\n\n // initialize random number\n var num = generateRandom(bits, rng);\n\n // use web workers to generate keys\n var numWorkers = options.workers;\n var workLoad = options.workLoad || 100;\n var range = workLoad * 30 / 8;\n var workerScript = options.workerScript || 'forge/prime.worker.js';\n if(numWorkers === -1) {\n return forge.util.estimateCores(function(err, cores) {\n if(err) {\n // default to 2\n cores = 2;\n }\n numWorkers = cores - 1;\n generate();\n });\n }\n generate();\n\n function generate() {\n // require at least 1 worker\n numWorkers = Math.max(1, numWorkers);\n\n // TODO: consider optimizing by starting workers outside getPrime() ...\n // note that in order to clean up they will have to be made internally\n // asynchronous which may actually be slower\n\n // start workers immediately\n var workers = [];\n for(var i = 0; i < numWorkers; ++i) {\n // FIXME: fix path or use blob URLs\n workers[i] = new Worker(workerScript);\n }\n var running = numWorkers;\n\n // listen for requests from workers and assign ranges to find prime\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].addEventListener('message', workerMessage);\n }\n\n /* Note: The distribution of random numbers is unknown. Therefore, each\n web worker is continuously allocated a range of numbers to check for a\n random number until one is found.\n\n Every 30 numbers will be checked just 8 times, because prime numbers\n have the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)\n\n Therefore, if we want a web worker to run N checks before asking for\n a new range of numbers, each range must contain N*30/8 numbers.\n\n For 100 checks (workLoad), this is a range of 375. */\n\n var found = false;\n function workerMessage(e) {\n // ignore message, prime already found\n if(found) {\n return;\n }\n\n --running;\n var data = e.data;\n if(data.found) {\n // terminate all workers\n for(var i = 0; i < workers.length; ++i) {\n workers[i].terminate();\n }\n found = true;\n return callback(null, new BigInteger(data.prime, 16));\n }\n\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n\n // assign new range to check\n var hex = num.toString(16);\n\n // start prime search\n e.target.postMessage({\n hex: hex,\n workLoad: workLoad\n });\n\n num.dAddOffset(range, 0);\n }\n }\n}\n\n/**\n * Generates a random number using the given number of bits and RNG.\n *\n * @param bits the number of bits for the number.\n * @param rng the random number generator to use.\n *\n * @return the random number.\n */\nfunction generateRandom(bits, rng) {\n var num = new BigInteger(bits, rng);\n // force MSB set\n var bits1 = bits - 1;\n if(!num.testBit(bits1)) {\n num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);\n }\n // align number on 30k+1 boundary\n num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);\n return num;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n})();\n","/**\n * A javascript implementation of a cryptographically-secure\n * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed\n * here though the use of SHA-256 is not enforced; when generating an\n * a PRNG context, the hashing algorithm and block cipher used for\n * the generator are specified via a plugin.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = require('crypto');\n}\n\n/* PRNG API */\nvar prng = module.exports = forge.prng = forge.prng || {};\n\n/**\n * Creates a new PRNG context.\n *\n * A PRNG plugin must be passed in that will provide:\n *\n * 1. A function that initializes the key and seed of a PRNG context. It\n * will be given a 16 byte key and a 16 byte seed. Any key expansion\n * or transformation of the seed from a byte string into an array of\n * integers (or similar) should be performed.\n * 2. The cryptographic function used by the generator. It takes a key and\n * a seed.\n * 3. A seed increment function. It takes the seed and returns seed + 1.\n * 4. An api to create a message digest.\n *\n * For an example, see random.js.\n *\n * @param plugin the PRNG plugin to use.\n */\nprng.create = function(plugin) {\n var ctx = {\n plugin: plugin,\n key: null,\n seed: null,\n time: null,\n // number of reseeds so far\n reseeds: 0,\n // amount of data generated so far\n generated: 0,\n // no initial key bytes\n keyBytes: ''\n };\n\n // create 32 entropy pools (each is a message digest)\n var md = plugin.md;\n var pools = new Array(32);\n for(var i = 0; i < 32; ++i) {\n pools[i] = md.create();\n }\n ctx.pools = pools;\n\n // entropy pools are written to cyclically, starting at index 0\n ctx.pool = 0;\n\n /**\n * Generates random bytes. The bytes may be generated synchronously or\n * asynchronously. Web workers must use the asynchronous interface or\n * else the behavior is undefined.\n *\n * @param count the number of random bytes to generate.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return count random bytes as a string.\n */\n ctx.generate = function(count, callback) {\n // do synchronously\n if(!callback) {\n return ctx.generateSync(count);\n }\n\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n var b = forge.util.createBuffer();\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generate` call\n ctx.key = null;\n\n generate();\n\n function generate(err) {\n if(err) {\n return callback(err);\n }\n\n // sufficient bytes generated\n if(b.length() >= count) {\n return callback(null, b.getBytes(count));\n }\n\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n // prevent stack overflow\n return forge.util.nextTick(function() {\n _reseed(generate);\n });\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n\n forge.util.setImmediate(generate);\n }\n };\n\n /**\n * Generates random bytes synchronously.\n *\n * @param count the number of random bytes to generate.\n *\n * @return count random bytes as a string.\n */\n ctx.generateSync = function(count) {\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generateSync` call\n ctx.key = null;\n\n var b = forge.util.createBuffer();\n while(b.length() < count) {\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n _reseedSync();\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n }\n\n return b.getBytes(count);\n };\n\n /**\n * Private function that asynchronously reseeds a generator.\n *\n * @param callback(err) called once the operation completes.\n */\n function _reseed(callback) {\n if(ctx.pools[0].messageLength >= 32) {\n _seed();\n return callback();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.seedFile(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n ctx.collect(bytes);\n _seed();\n callback();\n });\n }\n\n /**\n * Private function that synchronously reseeds a generator.\n */\n function _reseedSync() {\n if(ctx.pools[0].messageLength >= 32) {\n return _seed();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.collect(ctx.seedFileSync(needed));\n _seed();\n }\n\n /**\n * Private function that seeds a generator once enough bytes are available.\n */\n function _seed() {\n // update reseed count\n ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;\n\n // goal is to update `key` via:\n // key = hash(key + s)\n // where 's' is all collected entropy from selected pools, then...\n\n // create a plugin-based message digest\n var md = ctx.plugin.md.create();\n\n // consume current key bytes\n md.update(ctx.keyBytes);\n\n // digest the entropy of pools whose index k meet the\n // condition 'n mod 2^k == 0' where n is the number of reseeds\n var _2powK = 1;\n for(var k = 0; k < 32; ++k) {\n if(ctx.reseeds % _2powK === 0) {\n md.update(ctx.pools[k].digest().getBytes());\n ctx.pools[k].start();\n }\n _2powK = _2powK << 1;\n }\n\n // get digest for key bytes\n ctx.keyBytes = md.digest().getBytes();\n\n // paranoid deviation from Fortuna:\n // update `seed` via `seed = hash(key)`\n // instead of initializing to zero once and only\n // ever incrementing it\n md.start();\n md.update(ctx.keyBytes);\n var seedBytes = md.digest().getBytes();\n\n // update state\n ctx.key = ctx.plugin.formatKey(ctx.keyBytes);\n ctx.seed = ctx.plugin.formatSeed(seedBytes);\n ctx.generated = 0;\n }\n\n /**\n * The built-in default seedFile. This seedFile is used when entropy\n * is needed immediately.\n *\n * @param needed the number of bytes that are needed.\n *\n * @return the random bytes.\n */\n function defaultSeedFile(needed) {\n // use window.crypto.getRandomValues strong source of entropy if available\n var getRandomValues = null;\n var globalScope = forge.util.globalScope;\n var _crypto = globalScope.crypto || globalScope.msCrypto;\n if(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n }\n\n var b = forge.util.createBuffer();\n if(getRandomValues) {\n while(b.length() < needed) {\n // max byte length is 65536 before QuotaExceededError is thrown\n // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues\n var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);\n var entropy = new Uint32Array(Math.floor(count));\n try {\n getRandomValues(entropy);\n for(var i = 0; i < entropy.length; ++i) {\n b.putInt32(entropy[i]);\n }\n } catch(e) {\n /* only ignore QuotaExceededError */\n if(!(typeof QuotaExceededError !== 'undefined' &&\n e instanceof QuotaExceededError)) {\n throw e;\n }\n }\n }\n }\n\n // be sad and add some weak random data\n if(b.length() < needed) {\n /* Draws from Park-Miller \"minimal standard\" 31 bit PRNG,\n implemented with David G. Carta's optimization: with 32 bit math\n and without division (Public Domain). */\n var hi, lo, next;\n var seed = Math.floor(Math.random() * 0x010000);\n while(b.length() < needed) {\n lo = 16807 * (seed & 0xFFFF);\n hi = 16807 * (seed >> 16);\n lo += (hi & 0x7FFF) << 16;\n lo += hi >> 15;\n lo = (lo & 0x7FFFFFFF) + (lo >> 31);\n seed = lo & 0xFFFFFFFF;\n\n // consume lower 3 bytes of seed\n for(var i = 0; i < 3; ++i) {\n // throw in more pseudo random\n next = seed >>> (i << 3);\n next ^= Math.floor(Math.random() * 0x0100);\n b.putByte(next & 0xFF);\n }\n }\n }\n\n return b.getBytes(needed);\n }\n // initialize seed file APIs\n if(_crypto) {\n // use nodejs async API\n ctx.seedFile = function(needed, callback) {\n _crypto.randomBytes(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n callback(null, bytes.toString());\n });\n };\n // use nodejs sync API\n ctx.seedFileSync = function(needed) {\n return _crypto.randomBytes(needed).toString();\n };\n } else {\n ctx.seedFile = function(needed, callback) {\n try {\n callback(null, defaultSeedFile(needed));\n } catch(e) {\n callback(e);\n }\n };\n ctx.seedFileSync = defaultSeedFile;\n }\n\n /**\n * Adds entropy to a prng ctx's accumulator.\n *\n * @param bytes the bytes of entropy as a string.\n */\n ctx.collect = function(bytes) {\n // iterate over pools distributing entropy cyclically\n var count = bytes.length;\n for(var i = 0; i < count; ++i) {\n ctx.pools[ctx.pool].update(bytes.substr(i, 1));\n ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;\n }\n };\n\n /**\n * Collects an integer of n bits.\n *\n * @param i the integer entropy.\n * @param n the number of bits in the integer.\n */\n ctx.collectInt = function(i, n) {\n var bytes = '';\n for(var x = 0; x < n; x += 8) {\n bytes += String.fromCharCode((i >> x) & 0xFF);\n }\n ctx.collect(bytes);\n };\n\n /**\n * Registers a Web Worker to receive immediate entropy from the main thread.\n * This method is required until Web Workers can access the native crypto\n * API. This method should be called twice for each created worker, once in\n * the main thread, and once in the worker itself.\n *\n * @param worker the worker to register.\n */\n ctx.registerWorker = function(worker) {\n // worker receives random bytes\n if(worker === self) {\n ctx.seedFile = function(needed, callback) {\n function listener(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n self.removeEventListener('message', listener);\n callback(data.forge.prng.err, data.forge.prng.bytes);\n }\n }\n self.addEventListener('message', listener);\n self.postMessage({forge: {prng: {needed: needed}}});\n };\n } else {\n // main thread sends random bytes upon request\n var listener = function(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n ctx.seedFile(data.forge.prng.needed, function(err, bytes) {\n worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});\n });\n }\n };\n // TODO: do we need to remove the event listener when the worker dies?\n worker.addEventListener('message', listener);\n }\n };\n\n return ctx;\n};\n","/**\n * Javascript implementation of PKCS#1 PSS signature padding.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./random');\nrequire('./util');\n\n// shortcut for PSS API\nvar pss = module.exports = forge.pss = forge.pss || {};\n\n/**\n * Creates a PSS signature scheme object.\n *\n * There are several ways to provide a salt for encoding:\n *\n * 1. Specify the saltLength only and the built-in PRNG will generate it.\n * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that\n * will be used.\n * 3. Specify the salt itself as a forge.util.ByteBuffer.\n *\n * @param options the options to use:\n * md the message digest object to use, a forge md instance.\n * mgf the mask generation function to use, a forge mgf instance.\n * [saltLength] the length of the salt in octets.\n * [prng] the pseudo-random number generator to use to produce a salt.\n * [salt] the salt to use when encoding.\n *\n * @return a signature scheme object.\n */\npss.create = function(options) {\n // backwards compatibility w/legacy args: hash, mgf, sLen\n if(arguments.length === 3) {\n options = {\n md: arguments[0],\n mgf: arguments[1],\n saltLength: arguments[2]\n };\n }\n\n var hash = options.md;\n var mgf = options.mgf;\n var hLen = hash.digestLength;\n\n var salt_ = options.salt || null;\n if(typeof salt_ === 'string') {\n // assume binary-encoded string\n salt_ = forge.util.createBuffer(salt_);\n }\n\n var sLen;\n if('saltLength' in options) {\n sLen = options.saltLength;\n } else if(salt_ !== null) {\n sLen = salt_.length();\n } else {\n throw new Error('Salt length not specified or specific salt not given.');\n }\n\n if(salt_ !== null && salt_.length() !== sLen) {\n throw new Error('Given salt length does not match length of given salt.');\n }\n\n var prng = options.prng || forge.random;\n\n var pssobj = {};\n\n /**\n * Encodes a PSS signature.\n *\n * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.\n *\n * @param md the message digest object with the hash to sign.\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return the encoded message as a binary-encoded string of length\n * ceil((modBits - 1) / 8).\n */\n pssobj.encode = function(md, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* 2. Let mHash = Hash(M), an octet string of length hLen. */\n var mHash = md.digest().getBytes();\n\n /* 3. If emLen < hLen + sLen + 2, output \"encoding error\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Message is too long to encrypt.');\n }\n\n /* 4. Generate a random octet string salt of length sLen; if sLen = 0,\n * then salt is the empty string. */\n var salt;\n if(salt_ === null) {\n salt = prng.getBytesSync(sLen);\n } else {\n salt = salt_.bytes();\n }\n\n /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 6. Let H = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h = hash.digest().getBytes();\n\n /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2\n * zero octets. The length of PS may be 0. */\n var ps = new forge.util.ByteBuffer();\n ps.fillWithByte(0, emLen - sLen - hLen - 2);\n\n /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length\n * emLen - hLen - 1. */\n ps.putByte(0x01);\n ps.putBytes(salt);\n var db = ps.getBytes();\n\n /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */\n var maskLen = emLen - hLen - 1;\n var dbMask = mgf.generate(h, maskLen);\n\n /* 10. Let maskedDB = DB \\xor dbMask. */\n var maskedDB = '';\n for(i = 0; i < maskLen; i++) {\n maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB to zero. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +\n maskedDB.substr(1);\n\n /* 12. Let EM = maskedDB || H || 0xbc.\n * 13. Output EM. */\n return maskedDB + h + String.fromCharCode(0xbc);\n };\n\n /**\n * Verifies a PSS signature.\n *\n * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.\n *\n * @param mHash the message digest hash, as a binary-encoded string, to\n * compare against the signature.\n * @param em the encoded message, as a binary-encoded string\n * (RSA decryption result).\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return true if the signature was verified, false if not.\n */\n pssobj.verify = function(mHash, em, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* c. Convert the message representative m to an encoded message EM\n * of length emLen = ceil((modBits - 1) / 8) octets, where modBits\n * is the length in bits of the RSA modulus n */\n em = em.substr(-emLen);\n\n /* 3. If emLen < hLen + sLen + 2, output \"inconsistent\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Inconsistent parameters to PSS signature verification.');\n }\n\n /* 4. If the rightmost octet of EM does not have hexadecimal value\n * 0xbc, output \"inconsistent\" and stop. */\n if(em.charCodeAt(emLen - 1) !== 0xbc) {\n throw new Error('Encoded message does not end in 0xBC.');\n }\n\n /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and\n * let H be the next hLen octets. */\n var maskLen = emLen - hLen - 1;\n var maskedDB = em.substr(0, maskLen);\n var h = em.substr(maskLen, hLen);\n\n /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB are not all equal to zero, output \"inconsistent\" and stop. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n if((maskedDB.charCodeAt(0) & mask) !== 0) {\n throw new Error('Bits beyond keysize not zero as expected.');\n }\n\n /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */\n var dbMask = mgf.generate(h, maskLen);\n\n /* 8. Let DB = maskedDB \\xor dbMask. */\n var db = '';\n for(i = 0; i < maskLen; i++) {\n db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet\n * in DB to zero. */\n db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);\n\n /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero\n * or if the octet at position emLen - hLen - sLen - 1 (the leftmost\n * position is \"position 1\") does not have hexadecimal value 0x01,\n * output \"inconsistent\" and stop. */\n var checkLen = emLen - hLen - sLen - 2;\n for(i = 0; i < checkLen; i++) {\n if(db.charCodeAt(i) !== 0x00) {\n throw new Error('Leftmost octets not zero as expected');\n }\n }\n\n if(db.charCodeAt(checkLen) !== 0x01) {\n throw new Error('Inconsistent PSS signature, 0x01 marker not found');\n }\n\n /* 11. Let salt be the last sLen octets of DB. */\n var salt = db.substr(-sLen);\n\n /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 13. Let H' = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h_ = hash.digest().getBytes();\n\n /* 14. If H = H', output \"consistent.\" Otherwise, output \"inconsistent.\" */\n return h === h_;\n };\n\n return pssobj;\n};\n","/**\n * An API for getting cryptographically-secure random bytes. The bytes are\n * generated using the Fortuna algorithm devised by Bruce Schneier and\n * Niels Ferguson.\n *\n * Getting strong random bytes is not yet easy to do in javascript. The only\n * truish random entropy that can be collected is from the mouse, keyboard, or\n * from timing with respect to page loads, etc. This generator makes a poor\n * attempt at providing random bytes when those sources haven't yet provided\n * enough entropy to initially seed or to reseed the PRNG.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./sha256');\nrequire('./prng');\nrequire('./util');\n\n(function() {\n\n// forge.random already defined\nif(forge.random && forge.random.getBytes) {\n module.exports = forge.random;\n return;\n}\n\n(function(jQuery) {\n\n// the default prng plugin, uses AES-128\nvar prng_aes = {};\nvar _prng_aes_output = new Array(4);\nvar _prng_aes_buffer = forge.util.createBuffer();\nprng_aes.formatKey = function(key) {\n // convert the key into 32-bit integers\n var tmp = forge.util.createBuffer(key);\n key = new Array(4);\n key[0] = tmp.getInt32();\n key[1] = tmp.getInt32();\n key[2] = tmp.getInt32();\n key[3] = tmp.getInt32();\n\n // return the expanded key\n return forge.aes._expandKey(key, false);\n};\nprng_aes.formatSeed = function(seed) {\n // convert seed into 32-bit integers\n var tmp = forge.util.createBuffer(seed);\n seed = new Array(4);\n seed[0] = tmp.getInt32();\n seed[1] = tmp.getInt32();\n seed[2] = tmp.getInt32();\n seed[3] = tmp.getInt32();\n return seed;\n};\nprng_aes.cipher = function(key, seed) {\n forge.aes._updateBlock(key, seed, _prng_aes_output, false);\n _prng_aes_buffer.putInt32(_prng_aes_output[0]);\n _prng_aes_buffer.putInt32(_prng_aes_output[1]);\n _prng_aes_buffer.putInt32(_prng_aes_output[2]);\n _prng_aes_buffer.putInt32(_prng_aes_output[3]);\n return _prng_aes_buffer.getBytes();\n};\nprng_aes.increment = function(seed) {\n // FIXME: do we care about carry or signed issues?\n ++seed[3];\n return seed;\n};\nprng_aes.md = forge.md.sha256;\n\n/**\n * Creates a new PRNG.\n */\nfunction spawnPrng() {\n var ctx = forge.prng.create(prng_aes);\n\n /**\n * Gets random bytes. If a native secure crypto API is unavailable, this\n * method tries to make the bytes more unpredictable by drawing from data that\n * can be collected from the user of the browser, eg: mouse movement.\n *\n * If a callback is given, this method will be called asynchronously.\n *\n * @param count the number of random bytes to get.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytes = function(count, callback) {\n return ctx.generate(count, callback);\n };\n\n /**\n * Gets random bytes asynchronously. If a native secure crypto API is\n * unavailable, this method tries to make the bytes more unpredictable by\n * drawing from data that can be collected from the user of the browser,\n * eg: mouse movement.\n *\n * @param count the number of random bytes to get.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytesSync = function(count) {\n return ctx.generate(count);\n };\n\n return ctx;\n}\n\n// create default prng context\nvar _ctx = spawnPrng();\n\n// add other sources of entropy only if window.crypto.getRandomValues is not\n// available -- otherwise this source will be automatically used by the prng\nvar getRandomValues = null;\nvar globalScope = forge.util.globalScope;\nvar _crypto = globalScope.crypto || globalScope.msCrypto;\nif(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n}\n\nif(forge.options.usePureJavaScript ||\n (!forge.util.isNodejs && !getRandomValues)) {\n // if this is a web worker, do not use weak entropy, instead register to\n // receive strong entropy asynchronously from the main thread\n if(typeof window === 'undefined' || window.document === undefined) {\n // FIXME:\n }\n\n // get load time entropy\n _ctx.collectInt(+new Date(), 32);\n\n // add some entropy from navigator object\n if(typeof(navigator) !== 'undefined') {\n var _navBytes = '';\n for(var key in navigator) {\n try {\n if(typeof(navigator[key]) == 'string') {\n _navBytes += navigator[key];\n }\n } catch(e) {\n /* Some navigator keys might not be accessible, e.g. the geolocation\n attribute throws an exception if touched in Mozilla chrome://\n context.\n\n Silently ignore this and just don't use this as a source of\n entropy. */\n }\n }\n _ctx.collect(_navBytes);\n _navBytes = null;\n }\n\n // add mouse and keyboard collectors if jquery is available\n if(jQuery) {\n // set up mouse entropy capture\n jQuery().mousemove(function(e) {\n // add mouse coords\n _ctx.collectInt(e.clientX, 16);\n _ctx.collectInt(e.clientY, 16);\n });\n\n // set up keyboard entropy capture\n jQuery().keypress(function(e) {\n _ctx.collectInt(e.charCode, 8);\n });\n }\n}\n\n/* Random API */\nif(!forge.random) {\n forge.random = _ctx;\n} else {\n // extend forge.random with _ctx\n for(var key in _ctx) {\n forge.random[key] = _ctx[key];\n }\n}\n\n// expose spawn PRNG\nforge.random.createInstance = spawnPrng;\n\nmodule.exports = forge.random;\n\n})(typeof(jQuery) !== 'undefined' ? jQuery : null);\n\n})();\n","/**\n * RC2 implementation.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n *\n * Information on the RC2 cipher is available from RFC #2268,\n * http://www.ietf.org/rfc/rfc2268.txt\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar piTable = [\n 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,\n 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,\n 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,\n 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,\n 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,\n 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,\n 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,\n 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,\n 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,\n 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,\n 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,\n 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,\n 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,\n 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,\n 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,\n 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad\n];\n\nvar s = [1, 2, 3, 5];\n\n/**\n * Rotate a word left by given number of bits.\n *\n * Bits that are shifted out on the left are put back in on the right\n * hand side.\n *\n * @param word The word to shift left.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar rol = function(word, bits) {\n return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));\n};\n\n/**\n * Rotate a word right by given number of bits.\n *\n * Bits that are shifted out on the right are put back in on the left\n * hand side.\n *\n * @param word The word to shift right.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar ror = function(word, bits) {\n return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);\n};\n\n/* RC2 API */\nmodule.exports = forge.rc2 = forge.rc2 || {};\n\n/**\n * Perform RC2 key expansion as per RFC #2268, section 2.\n *\n * @param key variable-length user key (between 1 and 128 bytes)\n * @param effKeyBits number of effective key bits (default: 128)\n * @return the expanded RC2 key (ByteBuffer of 128 bytes)\n */\nforge.rc2.expandKey = function(key, effKeyBits) {\n if(typeof key === 'string') {\n key = forge.util.createBuffer(key);\n }\n effKeyBits = effKeyBits || 128;\n\n /* introduce variables that match the names used in RFC #2268 */\n var L = key;\n var T = key.length();\n var T1 = effKeyBits;\n var T8 = Math.ceil(T1 / 8);\n var TM = 0xff >> (T1 & 0x07);\n var i;\n\n for(i = T; i < 128; i++) {\n L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);\n }\n\n L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);\n\n for(i = 127 - T8; i >= 0; i--) {\n L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);\n }\n\n return L;\n};\n\n/**\n * Creates a RC2 cipher object.\n *\n * @param key the symmetric key to use (as base for key generation).\n * @param bits the number of effective key bits.\n * @param encrypt false for decryption, true for encryption.\n *\n * @return the cipher.\n */\nvar createCipher = function(key, bits, encrypt) {\n var _finish = false, _input = null, _output = null, _iv = null;\n var mixRound, mashRound;\n var i, j, K = [];\n\n /* Expand key and fill into K[] Array */\n key = forge.rc2.expandKey(key, bits);\n for(i = 0; i < 64; i++) {\n K.push(key.getInt16Le());\n }\n\n if(encrypt) {\n /**\n * Perform one mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n R[i] = rol(R[i], s[i]);\n j++;\n }\n };\n\n /**\n * Perform one mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[R[(i + 3) % 4] & 63];\n }\n };\n } else {\n /**\n * Perform one r-mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] = ror(R[i], s[i]);\n R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n j--;\n }\n };\n\n /**\n * Perform one r-mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] -= K[R[(i + 3) % 4] & 63];\n }\n };\n }\n\n /**\n * Run the specified cipher execution plan.\n *\n * This function takes four words from the input buffer, applies the IV on\n * it (if requested) and runs the provided execution plan.\n *\n * The plan must be put together in form of a array of arrays. Where the\n * outer one is simply a list of steps to perform and the inner one needs\n * to have two elements: the first one telling how many rounds to perform,\n * the second one telling what to do (i.e. the function to call).\n *\n * @param {Array} plan The plan to execute.\n */\n var runPlan = function(plan) {\n var R = [];\n\n /* Get data from input buffer and fill the four words into R */\n for(i = 0; i < 4; i++) {\n var val = _input.getInt16Le();\n\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting, apply the IV first. */\n val ^= _iv.getInt16Le();\n } else {\n /* We're decryption, keep cipher text for next block. */\n _iv.putInt16Le(val);\n }\n }\n\n R.push(val & 0xffff);\n }\n\n /* Reset global \"j\" variable as per spec. */\n j = encrypt ? 0 : 63;\n\n /* Run execution plan. */\n for(var ptr = 0; ptr < plan.length; ptr++) {\n for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {\n plan[ptr][1](R);\n }\n }\n\n /* Write back result to output buffer. */\n for(i = 0; i < 4; i++) {\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting in CBC-mode, feed back encrypted bytes into\n IV buffer to carry it forward to next block. */\n _iv.putInt16Le(R[i]);\n } else {\n R[i] ^= _iv.getInt16Le();\n }\n }\n\n _output.putInt16Le(R[i]);\n }\n };\n\n /* Create cipher object */\n var cipher = null;\n cipher = {\n /**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * To use the cipher in CBC mode, iv may be given either as a string\n * of bytes, or as a byte buffer. For ECB mode, give null as iv.\n *\n * @param iv the initialization vector to use, null for ECB mode.\n * @param output the output the buffer to write to, null to create one.\n */\n start: function(iv, output) {\n if(iv) {\n /* CBC mode */\n if(typeof iv === 'string') {\n iv = forge.util.createBuffer(iv);\n }\n }\n\n _finish = false;\n _input = forge.util.createBuffer();\n _output = output || new forge.util.createBuffer();\n _iv = iv;\n\n cipher.output = _output;\n },\n\n /**\n * Updates the next block.\n *\n * @param input the buffer to read from.\n */\n update: function(input) {\n if(!_finish) {\n // not finishing, so fill the input buffer with more input\n _input.putBuffer(input);\n }\n\n while(_input.length() >= 8) {\n runPlan([\n [ 5, mixRound ],\n [ 1, mashRound ],\n [ 6, mixRound ],\n [ 1, mashRound ],\n [ 5, mixRound ]\n ]);\n }\n },\n\n /**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use, null for PKCS#7 padding,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\n finish: function(pad) {\n var rval = true;\n\n if(encrypt) {\n if(pad) {\n rval = pad(8, _input, !encrypt);\n } else {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (_input.length() === 8) ? 8 : (8 - _input.length());\n _input.fillWithByte(padding, padding);\n }\n }\n\n if(rval) {\n // do final update\n _finish = true;\n cipher.update();\n }\n\n if(!encrypt) {\n // check for error: input data not a multiple of block size\n rval = (_input.length() === 0);\n if(rval) {\n if(pad) {\n rval = pad(8, _output, !encrypt);\n } else {\n // ensure padding byte count is valid\n var len = _output.length();\n var count = _output.at(len - 1);\n\n if(count > len) {\n rval = false;\n } else {\n // trim off padding bytes\n _output.truncate(count);\n }\n }\n }\n }\n\n return rval;\n }\n };\n\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startEncrypting = function(key, iv, output) {\n var cipher = forge.rc2.createEncryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start encrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createEncryptionCipher = function(key, bits) {\n return createCipher(key, bits, true);\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startDecrypting = function(key, iv, output) {\n var cipher = forge.rc2.createDecryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start decrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createDecryptionCipher = function(key, bits) {\n return createCipher(key, bits, false);\n};\n","/**\n * Javascript implementation of basic RSA algorithms.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The only algorithm currently supported for PKI is RSA.\n *\n * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo\n * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier\n * and a subjectPublicKey of type bit string.\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of RSA, there aren't any.\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * For an RSA public key, the subjectPublicKey is:\n *\n * RSAPublicKey ::= SEQUENCE {\n * modulus INTEGER, -- n\n * publicExponent INTEGER -- e\n * }\n *\n * PrivateKeyInfo ::= SEQUENCE {\n * version Version,\n * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n * privateKey PrivateKey,\n * attributes [0] IMPLICIT Attributes OPTIONAL\n * }\n *\n * Version ::= INTEGER\n * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n * PrivateKey ::= OCTET STRING\n * Attributes ::= SET OF Attribute\n *\n * An RSA private key as the following structure:\n *\n * RSAPrivateKey ::= SEQUENCE {\n * version Version,\n * modulus INTEGER, -- n\n * publicExponent INTEGER, -- e\n * privateExponent INTEGER, -- d\n * prime1 INTEGER, -- p\n * prime2 INTEGER, -- q\n * exponent1 INTEGER, -- d mod (p-1)\n * exponent2 INTEGER, -- d mod (q-1)\n * coefficient INTEGER -- (inverse of q) mod p\n * }\n *\n * Version ::= INTEGER\n *\n * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./jsbn');\nrequire('./oids');\nrequire('./pkcs1');\nrequire('./prime');\nrequire('./random');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar _crypto = forge.util.isNodejs ? require('crypto') : null;\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for util API\nvar util = forge.util;\n\n/*\n * RSA encryption and decryption, see RFC 2313.\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};\nvar pki = forge.pki;\n\n// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\n\n// validator for a PrivateKeyInfo structure\nvar privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\n// validator for an RSA private key\nvar rsaPrivateKeyValidator = {\n // RSAPrivateKey\n name: 'RSAPrivateKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'RSAPrivateKey.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // modulus (n)\n name: 'RSAPrivateKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPrivateKey.publicExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPublicExponent'\n }, {\n // privateExponent (d)\n name: 'RSAPrivateKey.privateExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrivateExponent'\n }, {\n // prime1 (p)\n name: 'RSAPrivateKey.prime1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime1'\n }, {\n // prime2 (q)\n name: 'RSAPrivateKey.prime2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime2'\n }, {\n // exponent1 (d mod (p-1))\n name: 'RSAPrivateKey.exponent1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent1'\n }, {\n // exponent2 (d mod (q-1))\n name: 'RSAPrivateKey.exponent2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent2'\n }, {\n // coefficient ((inverse of q) mod p)\n name: 'RSAPrivateKey.coefficient',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyCoefficient'\n }]\n};\n\n// validator for an RSA public key\nvar rsaPublicKeyValidator = {\n // RSAPublicKey\n name: 'RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // modulus (n)\n name: 'RSAPublicKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPublicKey.exponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyExponent'\n }]\n};\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n }, {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n }]\n};\n\n// validator for a DigestInfo structure\nvar digestInfoValidator = {\n name: 'DigestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'algorithmIdentifier'\n }, {\n // NULL paramters\n name: 'DigestInfo.DigestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.NULL,\n // captured only to check existence for md2 and md5\n capture: 'parameters',\n optional: true,\n constructed: false\n }]\n }, {\n // digest\n name: 'DigestInfo.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'digest'\n }]\n};\n\n/**\n * Wrap digest in DigestInfo object.\n *\n * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * @param md the message digest object with the hash to sign.\n *\n * @return the encoded message (ready for RSA encrytion)\n */\nvar emsaPkcs1v15encode = function(md) {\n // get the oid for the algorithm\n var oid;\n if(md.algorithm in pki.oids) {\n oid = pki.oids[md.algorithm];\n } else {\n var error = new Error('Unknown message digest algorithm.');\n error.algorithm = md.algorithm;\n throw error;\n }\n var oidBytes = asn1.oidToDer(oid).getBytes();\n\n // create the digest info\n var digestInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var digestAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));\n var digest = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, md.digest().getBytes());\n digestInfo.value.push(digestAlgorithm);\n digestInfo.value.push(digest);\n\n // encode digest info\n return asn1.toDer(digestInfo).getBytes();\n};\n\n/**\n * Performs x^c mod n (RSA encryption or decryption operation).\n *\n * @param x the number to raise and mod.\n * @param key the key to use.\n * @param pub true if the key is public, false if private.\n *\n * @return the result of x^c mod n.\n */\nvar _modPow = function(x, key, pub) {\n if(pub) {\n return x.modPow(key.e, key.n);\n }\n\n if(!key.p || !key.q) {\n // allow calculation without CRT params (slow)\n return x.modPow(key.d, key.n);\n }\n\n // pre-compute dP, dQ, and qInv if necessary\n if(!key.dP) {\n key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));\n }\n if(!key.dQ) {\n key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));\n }\n if(!key.qInv) {\n key.qInv = key.q.modInverse(key.p);\n }\n\n /* Chinese remainder theorem (CRT) states:\n\n Suppose n1, n2, ..., nk are positive integers which are pairwise\n coprime (n1 and n2 have no common factors other than 1). For any\n integers x1, x2, ..., xk there exists an integer x solving the\n system of simultaneous congruences (where ~= means modularly\n congruent so a ~= b mod n means a mod n = b mod n):\n\n x ~= x1 mod n1\n x ~= x2 mod n2\n ...\n x ~= xk mod nk\n\n This system of congruences has a single simultaneous solution x\n between 0 and n - 1. Furthermore, each xk solution and x itself\n is congruent modulo the product n = n1*n2*...*nk.\n So x1 mod n = x2 mod n = xk mod n = x mod n.\n\n The single simultaneous solution x can be solved with the following\n equation:\n\n x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.\n\n Where x is less than n, xi = x mod ni.\n\n For RSA we are only concerned with k = 2. The modulus n = pq, where\n p and q are coprime. The RSA decryption algorithm is:\n\n y = x^d mod n\n\n Given the above:\n\n x1 = x^d mod p\n r1 = n/p = q\n s1 = q^-1 mod p\n x2 = x^d mod q\n r2 = n/q = p\n s2 = p^-1 mod q\n\n So y = (x1r1s1 + x2r2s2) mod n\n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n\n\n According to Fermat's Little Theorem, if the modulus P is prime,\n for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.\n Since A is not divisible by P it follows that if:\n N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:\n\n A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort\n to calculate). In order to calculate x^d mod p more quickly the\n exponent d mod (p - 1) is stored in the RSA private key (the same\n is done for x^d mod q). These values are referred to as dP and dQ\n respectively. Therefore we now have:\n\n y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n\n\n Since we'll be reducing x^dP by modulo p (same for q) we can also\n reduce x by p (and q respectively) before hand. Therefore, let\n\n xp = ((x mod p)^dP mod p), and\n xq = ((x mod q)^dQ mod q), yielding:\n\n y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n\n\n This can be further reduced to a simple algorithm that only\n requires 1 inverse (the q inverse is used) to be used and stored.\n The algorithm is called Garner's algorithm. If qInv is the\n inverse of q, we simply calculate:\n\n y = (qInv*(xp - xq) mod p) * q + xq\n\n However, there are two further complications. First, we need to\n ensure that xp > xq to prevent signed BigIntegers from being used\n so we add p until this is true (since we will be mod'ing with\n p anyway). Then, there is a known timing attack on algorithms\n using the CRT. To mitigate this risk, \"cryptographic blinding\"\n should be used. This requires simply generating a random number r\n between 0 and n-1 and its inverse and multiplying x by r^e before\n calculating y and then multiplying y by r^-1 afterwards. Note that\n r must be coprime with n (gcd(r, n) === 1) in order to have an\n inverse.\n */\n\n // cryptographic blinding\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),\n 16);\n } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));\n x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);\n\n // calculate xp and xq\n var xp = x.mod(key.p).modPow(key.dP, key.p);\n var xq = x.mod(key.q).modPow(key.dQ, key.q);\n\n // xp must be larger than xq to avoid signed bit usage\n while(xp.compareTo(xq) < 0) {\n xp = xp.add(key.p);\n }\n\n // do last step\n var y = xp.subtract(xq)\n .multiply(key.qInv).mod(key.p)\n .multiply(key.q).add(xq);\n\n // remove effect of random for cryptographic blinding\n y = y.multiply(r.modInverse(key.n)).mod(key.n);\n\n return y;\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or\n * 'encrypt' on a public key object instead.\n *\n * Performs RSA encryption.\n *\n * The parameter bt controls whether to put padding bytes before the\n * message passed in. Set bt to either true or false to disable padding\n * completely (in order to handle e.g. EMSA-PSS encoding seperately before),\n * signaling whether the encryption operation is a public key operation\n * (i.e. encrypting data) or not, i.e. private key operation (data signing).\n *\n * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01\n * (for signing) or 0x02 (for encryption). The key operation mode (private\n * or public) is derived from this flag in that case).\n *\n * @param m the message to encrypt as a byte string.\n * @param key the RSA key to use.\n * @param bt for PKCS#1 v1.5 padding, the block type to use\n * (0x01 for private key, 0x02 for public),\n * to disable padding: true = public key, false = private key.\n *\n * @return the encrypted bytes as a string.\n */\npki.rsa.encrypt = function(m, key, bt) {\n var pub = bt;\n var eb;\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n if(bt !== false && bt !== true) {\n // legacy, default to PKCS#1 v1.5 padding\n pub = (bt === 0x02);\n eb = _encodePkcs1_v1_5(m, key, bt);\n } else {\n eb = forge.util.createBuffer();\n eb.putBytes(m);\n }\n\n // load encryption block as big integer 'x'\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var x = new BigInteger(eb.toHex(), 16);\n\n // do RSA encryption\n var y = _modPow(x, key, pub);\n\n // convert y into the encrypted data byte string, if y is shorter in\n // bytes than k, then prepend zero bytes to fill up ed\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var yhex = y.toString(16);\n var ed = forge.util.createBuffer();\n var zeros = k - Math.ceil(yhex.length / 2);\n while(zeros > 0) {\n ed.putByte(0x00);\n --zeros;\n }\n ed.putBytes(forge.util.hexToBytes(yhex));\n return ed.getBytes();\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or\n * 'verify' on a public key object instead.\n *\n * Performs RSA decryption.\n *\n * The parameter ml controls whether to apply PKCS#1 v1.5 padding\n * or not. Set ml = false to disable padding removal completely\n * (in order to handle e.g. EMSA-PSS later on) and simply pass back\n * the RSA encryption block.\n *\n * @param ed the encrypted data to decrypt in as a byte string.\n * @param key the RSA key to use.\n * @param pub true for a public key operation, false for private.\n * @param ml the message length, if known, false to disable padding.\n *\n * @return the decrypted message as a byte string.\n */\npki.rsa.decrypt = function(ed, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n // error if the length of the encrypted data ED is not k\n if(ed.length !== k) {\n var error = new Error('Encrypted message length is invalid.');\n error.length = ed.length;\n error.expected = k;\n throw error;\n }\n\n // convert encrypted data into a big integer\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);\n\n // y must be less than the modulus or it wasn't the result of\n // a previous mod operation (encryption) using that modulus\n if(y.compareTo(key.n) >= 0) {\n throw new Error('Encrypted message is invalid.');\n }\n\n // do RSA decryption\n var x = _modPow(y, key, pub);\n\n // create the encryption block, if x is shorter in bytes than k, then\n // prepend zero bytes to fill up eb\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var xhex = x.toString(16);\n var eb = forge.util.createBuffer();\n var zeros = k - Math.ceil(xhex.length / 2);\n while(zeros > 0) {\n eb.putByte(0x00);\n --zeros;\n }\n eb.putBytes(forge.util.hexToBytes(xhex));\n\n if(ml !== false) {\n // legacy, default to PKCS#1 v1.5 padding\n return _decodePkcs1_v1_5(eb.getBytes(), key, pub);\n }\n\n // return message\n return eb.getBytes();\n};\n\n/**\n * Creates an RSA key-pair generation state object. It is used to allow\n * key-generation to be performed in steps. It also allows for a UI to\n * display progress updates.\n *\n * @param bits the size for the private key in bits, defaults to 2048.\n * @param e the public exponent to use, defaults to 65537 (0x10001).\n * @param [options] the options to use.\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n * algorithm the algorithm to use (default: 'PRIMEINC').\n *\n * @return the state object to use to generate the key-pair.\n */\npki.rsa.createKeyPairGenerationState = function(bits, e, options) {\n // TODO: migrate step-based prime generation code to forge.prime\n\n // set default bits\n if(typeof(bits) === 'string') {\n bits = parseInt(bits, 10);\n }\n bits = bits || 2048;\n\n // create prng with api that matches BigInteger secure random\n options = options || {};\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n var algorithm = options.algorithm || 'PRIMEINC';\n\n // create PRIMEINC algorithm state\n var rval;\n if(algorithm === 'PRIMEINC') {\n rval = {\n algorithm: algorithm,\n state: 0,\n bits: bits,\n rng: rng,\n eInt: e || 65537,\n e: new BigInteger(null),\n p: null,\n q: null,\n qBits: bits >> 1,\n pBits: bits - (bits >> 1),\n pqState: 0,\n num: null,\n keys: null\n };\n rval.e.fromInt(rval.eInt);\n } else {\n throw new Error('Invalid key generation algorithm: ' + algorithm);\n }\n\n return rval;\n};\n\n/**\n * Attempts to runs the key-generation algorithm for at most n seconds\n * (approximately) using the given state. When key-generation has completed,\n * the keys will be stored in state.keys.\n *\n * To use this function to update a UI while generating a key or to prevent\n * causing browser lockups/warnings, set \"n\" to a value other than 0. A\n * simple pattern for generating a key and showing a progress indicator is:\n *\n * var state = pki.rsa.createKeyPairGenerationState(2048);\n * var step = function() {\n * // step key-generation, run algorithm for 100 ms, repeat\n * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {\n * setTimeout(step, 1);\n * } else {\n * // key-generation complete\n * // TODO: turn off progress indicator here\n * // TODO: use the generated key-pair in \"state.keys\"\n * }\n * };\n * // TODO: turn on progress indicator here\n * setTimeout(step, 0);\n *\n * @param state the state to use.\n * @param n the maximum number of milliseconds to run the algorithm for, 0\n * to run the algorithm to completion.\n *\n * @return true if the key-generation completed, false if not.\n */\npki.rsa.stepKeyPairGenerationState = function(state, n) {\n // set default algorithm if not set\n if(!('algorithm' in state)) {\n state.algorithm = 'PRIMEINC';\n }\n\n // TODO: migrate step-based prime generation code to forge.prime\n // TODO: abstract as PRIMEINC algorithm\n\n // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)\n // with some minor optimizations and designed to run in steps\n\n // local state vars\n var THIRTY = new BigInteger(null);\n THIRTY.fromInt(30);\n var deltaIdx = 0;\n var op_or = function(x, y) {return x | y;};\n\n // keep stepping until time limit is reached or done\n var t1 = +new Date();\n var t2;\n var total = 0;\n while(state.keys === null && (n <= 0 || total < n)) {\n // generate p or q\n if(state.state === 0) {\n /* Note: All primes are of the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i\n\n When we generate a random number, we always align it at 30k + 1. Each\n time the number is determined not to be prime we add to get to the\n next 'i', eg: if the number was at 30k + 1 we add 6. */\n var bits = (state.p === null) ? state.pBits : state.qBits;\n var bits1 = bits - 1;\n\n // get a random number\n if(state.pqState === 0) {\n state.num = new BigInteger(bits, state.rng);\n // force MSB set\n if(!state.num.testBit(bits1)) {\n state.num.bitwiseTo(\n BigInteger.ONE.shiftLeft(bits1), op_or, state.num);\n }\n // align number on 30k+1 boundary\n state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);\n deltaIdx = 0;\n\n ++state.pqState;\n } else if(state.pqState === 1) {\n // try to make the number a prime\n if(state.num.bitLength() > bits) {\n // overflow, try again\n state.pqState = 0;\n // do primality test\n } else if(state.num.isProbablePrime(\n _getMillerRabinTests(state.num.bitLength()))) {\n ++state.pqState;\n } else {\n // get next potential prime\n state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n }\n } else if(state.pqState === 2) {\n // ensure number is coprime with e\n state.pqState =\n (state.num.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) === 0) ? 3 : 0;\n } else if(state.pqState === 3) {\n // store p or q\n state.pqState = 0;\n if(state.p === null) {\n state.p = state.num;\n } else {\n state.q = state.num;\n }\n\n // advance state if both p and q are ready\n if(state.p !== null && state.q !== null) {\n ++state.state;\n }\n state.num = null;\n }\n } else if(state.state === 1) {\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n state.num = state.p;\n state.p = state.q;\n state.q = state.num;\n }\n ++state.state;\n } else if(state.state === 2) {\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n ++state.state;\n } else if(state.state === 3) {\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {\n // phi and e are coprime, advance\n ++state.state;\n } else {\n // phi and e aren't coprime, so generate a new p and q\n state.p = null;\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 4) {\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n\n // ensure n is right number of bits\n if(state.n.bitLength() === state.bits) {\n // success, advance\n ++state.state;\n } else {\n // failed, get new q\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 5) {\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n }\n\n // update timing\n t2 = +new Date();\n total += t2 - t1;\n t1 = t2;\n }\n\n return state.keys !== null;\n};\n\n/**\n * Generates an RSA public-private key pair in a single call.\n *\n * To generate a key-pair in steps (to allow for progress updates and to\n * prevent blocking or warnings in slow browsers) then use the key-pair\n * generation state functions.\n *\n * To generate a key-pair asynchronously (either through web-workers, if\n * available, or by breaking up the work on the main thread), pass a\n * callback function.\n *\n * @param [bits] the size for the private key in bits, defaults to 2048.\n * @param [e] the public exponent to use, defaults to 65537.\n * @param [options] options for key-pair generation, if given then 'bits'\n * and 'e' must *not* be given:\n * bits the size for the private key in bits, (default: 2048).\n * e the public exponent to use, (default: 65537 (0x10001)).\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\". Disables use of native APIs.\n * algorithm the algorithm to use (default: 'PRIMEINC').\n * @param [callback(err, keypair)] called once the operation completes.\n *\n * @return an object with privateKey and publicKey properties.\n */\npki.rsa.generateKeyPair = function(bits, e, options, callback) {\n // (bits), (options), (callback)\n if(arguments.length === 1) {\n if(typeof bits === 'object') {\n options = bits;\n bits = undefined;\n } else if(typeof bits === 'function') {\n callback = bits;\n bits = undefined;\n }\n } else if(arguments.length === 2) {\n // (bits, e), (bits, options), (bits, callback), (options, callback)\n if(typeof bits === 'number') {\n if(typeof e === 'function') {\n callback = e;\n e = undefined;\n } else if(typeof e !== 'number') {\n options = e;\n e = undefined;\n }\n } else {\n options = bits;\n callback = e;\n bits = undefined;\n e = undefined;\n }\n } else if(arguments.length === 3) {\n // (bits, e, options), (bits, e, callback), (bits, options, callback)\n if(typeof e === 'number') {\n if(typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n } else {\n callback = options;\n options = e;\n e = undefined;\n }\n }\n options = options || {};\n if(bits === undefined) {\n bits = options.bits || 2048;\n }\n if(e === undefined) {\n e = options.e || 0x10001;\n }\n\n // use native code if permitted, available, and parameters are acceptable\n if(!forge.options.usePureJavaScript && !options.prng &&\n bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {\n if(callback) {\n // try native async\n if(_detectNodeCrypto('generateKeyPair')) {\n return _crypto.generateKeyPair('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n }, function(err, pub, priv) {\n if(err) {\n return callback(err);\n }\n callback(null, {\n privateKey: pki.privateKeyFromPem(priv),\n publicKey: pki.publicKeyFromPem(pub)\n });\n });\n }\n if(_detectSubtleCrypto('generateKey') &&\n _detectSubtleCrypto('exportKey')) {\n // use standard native generateKey\n return util.globalScope.crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify'])\n .then(function(pair) {\n return util.globalScope.crypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n // avoiding catch(function(err) {...}) to support IE <= 8\n }).then(undefined, function(err) {\n callback(err);\n }).then(function(pkcs8) {\n if(pkcs8) {\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n }\n });\n }\n if(_detectSubtleMsCrypto('generateKey') &&\n _detectSubtleMsCrypto('exportKey')) {\n var genOp = util.globalScope.msCrypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify']);\n genOp.oncomplete = function(e) {\n var pair = e.target.result;\n var exportOp = util.globalScope.msCrypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n exportOp.oncomplete = function(e) {\n var pkcs8 = e.target.result;\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n };\n exportOp.onerror = function(err) {\n callback(err);\n };\n };\n genOp.onerror = function(err) {\n callback(err);\n };\n return;\n }\n } else {\n // try native sync\n if(_detectNodeCrypto('generateKeyPairSync')) {\n var keypair = _crypto.generateKeyPairSync('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n return {\n privateKey: pki.privateKeyFromPem(keypair.privateKey),\n publicKey: pki.publicKeyFromPem(keypair.publicKey)\n };\n }\n }\n }\n\n // use JavaScript implementation\n var state = pki.rsa.createKeyPairGenerationState(bits, e, options);\n if(!callback) {\n pki.rsa.stepKeyPairGenerationState(state, 0);\n return state.keys;\n }\n _generateKeyPair(state, options, callback);\n};\n\n/**\n * Sets an RSA public key from BigIntegers modulus and exponent.\n *\n * @param n the modulus.\n * @param e the exponent.\n *\n * @return the public key.\n */\npki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {\n var key = {\n n: n,\n e: e\n };\n\n /**\n * Encrypts the given data with this public key. Newer applications\n * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for\n * legacy applications.\n *\n * @param data the byte string to encrypt.\n * @param scheme the encryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA encryption,\n * an object with an 'encode' property set to a function\n * with the signature 'function(data, key)' that returns\n * a binary-encoded string representing the encoded data.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the encrypted byte string.\n */\n key.encrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {\n encode: function(m, key, pub) {\n return _encodePkcs1_v1_5(m, key, 0x02).getBytes();\n }\n };\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n encode: function(m, key) {\n return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {encode: function(e) {return e;}};\n } else if(typeof scheme === 'string') {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // do scheme-based encoding then rsa encryption\n var e = scheme.encode(data, key, true);\n return pki.rsa.encrypt(e, key, true);\n };\n\n /**\n * Verifies the given signature against the given digest.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the\n * signature is an OCTET STRING that holds a DigestInfo.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * To perform PSS signature verification, provide an instance\n * of Forge PSS object as the scheme parameter.\n *\n * @param digest the message digest hash to compare against the signature,\n * as a binary-encoded string.\n * @param signature the signature to verify, as a binary-encoded string.\n * @param scheme signature verification scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be expected, but\n * PKCS#1 v1.5 padding will still be used.\n * @param options optional verify options\n * _parseAllDigestBytes testing flag to control parsing of all\n * digest bytes. Unsupported and not for general usage.\n * (default: true)\n *\n * @return true if the signature was verified, false if not.\n */\n key.verify = function(digest, signature, scheme, options) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSASSA-PKCS1-V1_5';\n }\n if(options === undefined) {\n options = {\n _parseAllDigestBytes: true\n };\n }\n if(!('_parseAllDigestBytes' in options)) {\n options._parseAllDigestBytes = true;\n }\n\n if(scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d, {\n parseAllBytes: options._parseAllDigestBytes\n });\n\n // validate DigestInfo\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {\n var error = new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value.');\n error.errors = errors;\n throw error;\n }\n // check hash algorithm identifier\n // see PKCS1-v1-5DigestAlgorithms in RFC 8017\n // FIXME: add support to vaidator for strict value choices\n var oid = asn1.derToOid(capture.algorithmIdentifier);\n if(!(oid === forge.oids.md2 ||\n oid === forge.oids.md5 ||\n oid === forge.oids.sha1 ||\n oid === forge.oids.sha224 ||\n oid === forge.oids.sha256 ||\n oid === forge.oids.sha384 ||\n oid === forge.oids.sha512 ||\n oid === forge.oids['sha512-224'] ||\n oid === forge.oids['sha512-256'])) {\n var error = new Error(\n 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');\n error.oid = oid;\n throw error;\n }\n\n // special check for md2 and md5 that NULL parameters exist\n if(oid === forge.oids.md2 || oid === forge.oids.md5) {\n if(!('parameters' in capture)) {\n throw new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value. ' +\n 'Missing algorithm identifer NULL parameters.');\n }\n }\n\n // compare the given digest to the decrypted one\n return digest === capture.digest;\n }\n };\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n return digest === d;\n }\n };\n }\n\n // do rsa decryption w/o any decoding, then verify -- which does decoding\n var d = pki.rsa.decrypt(signature, key, true, false);\n return scheme.verify(digest, d, key.n.bitLength());\n };\n\n return key;\n};\n\n/**\n * Sets an RSA private key from BigIntegers modulus, exponent, primes,\n * prime exponents, and modular multiplicative inverse.\n *\n * @param n the modulus.\n * @param e the public exponent.\n * @param d the private exponent ((inverse of e) mod n).\n * @param p the first prime.\n * @param q the second prime.\n * @param dP exponent1 (d mod (p-1)).\n * @param dQ exponent2 (d mod (q-1)).\n * @param qInv ((inverse of q) mod p)\n *\n * @return the private key.\n */\npki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(\n n, e, d, p, q, dP, dQ, qInv) {\n var key = {\n n: n,\n e: e,\n d: d,\n p: p,\n q: q,\n dP: dP,\n dQ: dQ,\n qInv: qInv\n };\n\n /**\n * Decrypts the given data with this private key. The decryption scheme\n * must match the one used to encrypt the data.\n *\n * @param data the byte string to decrypt.\n * @param scheme the decryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA decryption.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the decrypted byte string.\n */\n key.decrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n // do rsa decryption w/o any decoding\n var d = pki.rsa.decrypt(data, key, false, false);\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {decode: _decodePkcs1_v1_5};\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n decode: function(d, key) {\n return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {decode: function(d) {return d;}};\n } else {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // decode according to scheme\n return scheme.decode(d, key, false);\n };\n\n /**\n * Signs the given digest, producing a signature.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide\n * an instance of Forge PSS object as the scheme parameter.\n *\n * @param md the message digest object with the hash to sign.\n * @param scheme the signature scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be used but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return the signature as a byte string.\n */\n key.sign = function(md, scheme) {\n /* Note: The internal implementation of RSA operations is being\n transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy\n code like the use of an encoding block identifier 'bt' will eventually\n be removed. */\n\n // private key operation\n var bt = false;\n\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n }\n\n if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {encode: emsaPkcs1v15encode};\n bt = 0x01;\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {encode: function() {return md;}};\n bt = 0x01;\n }\n\n // encode and then encrypt\n var d = scheme.encode(md, key.n.bitLength());\n return pki.rsa.encrypt(d, key, bt);\n };\n\n return key;\n};\n\n/**\n * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.\n *\n * @param rsaKey the ASN.1 RSAPrivateKey.\n *\n * @return the ASN.1 PrivateKeyInfo.\n */\npki.wrapRsaPrivateKey = function(rsaKey) {\n // PrivateKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // privateKeyAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // PrivateKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(rsaKey).getBytes())\n ]);\n};\n\n/**\n * Converts a private key from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a PrivateKeyInfo containing an\n * RSAPrivateKey or an RSAPrivateKey.\n *\n * @return the private key.\n */\npki.privateKeyFromAsn1 = function(obj) {\n // get PrivateKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, privateKeyValidator, capture, errors)) {\n obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));\n }\n\n // get RSAPrivateKey\n capture = {};\n errors = [];\n if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read private key. ' +\n 'ASN.1 object does not contain an RSAPrivateKey.');\n error.errors = errors;\n throw error;\n }\n\n // Note: Version is currently ignored.\n // capture.privateKeyVersion\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n, e, d, p, q, dP, dQ, qInv;\n n = forge.util.createBuffer(capture.privateKeyModulus).toHex();\n e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();\n d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();\n p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();\n q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();\n dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();\n dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();\n qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();\n\n // set private key\n return pki.setRsaPrivateKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16),\n new BigInteger(d, 16),\n new BigInteger(p, 16),\n new BigInteger(q, 16),\n new BigInteger(dP, 16),\n new BigInteger(dQ, 16),\n new BigInteger(qInv, 16));\n};\n\n/**\n * Converts a private key to an ASN.1 RSAPrivateKey.\n *\n * @param key the private key.\n *\n * @return the ASN.1 representation of an RSAPrivateKey.\n */\npki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {\n // RSAPrivateKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0 = only 2 primes, 1 multiple primes)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e)),\n // privateExponent (d)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.d)),\n // privateKeyPrime1 (p)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.p)),\n // privateKeyPrime2 (q)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.q)),\n // privateKeyExponent1 (dP)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dP)),\n // privateKeyExponent2 (dQ)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dQ)),\n // coefficient (qInv)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.qInv))\n ]);\n};\n\n/**\n * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @return the public key.\n */\npki.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, publicKeyValidator, capture, errors)) {\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n var error = new Error('Cannot read public key. Unknown OID.');\n error.oid = oid;\n throw error;\n }\n obj = capture.rsaPublicKey;\n }\n\n // get RSA params\n errors = [];\n if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {\n var error = new Error('Cannot read public key. ' +\n 'ASN.1 object does not contain an RSAPublicKey.');\n error.errors = errors;\n throw error;\n }\n\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();\n var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();\n\n // set public key\n return pki.setRsaPublicKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16));\n};\n\n/**\n * Converts a public key to an ASN.1 SubjectPublicKeyInfo.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a SubjectPublicKeyInfo.\n */\npki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {\n // SubjectPublicKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // subjectPublicKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [\n pki.publicKeyToRSAPublicKey(key)\n ])\n ]);\n};\n\n/**\n * Converts a public key to an ASN.1 RSAPublicKey.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a RSAPublicKey.\n */\npki.publicKeyToRSAPublicKey = function(key) {\n // RSAPublicKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e))\n ]);\n};\n\n/**\n * Encodes a message using PKCS#1 v1.5 padding.\n *\n * @param m the message to encode.\n * @param key the RSA key to use.\n * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02\n * (for encryption).\n *\n * @return the padded byte buffer.\n */\nfunction _encodePkcs1_v1_5(m, key, bt) {\n var eb = forge.util.createBuffer();\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* use PKCS#1 v1.5 padding */\n if(m.length > (k - 11)) {\n var error = new Error('Message is too long for PKCS#1 v1.5 padding.');\n error.length = m.length;\n error.max = k - 11;\n throw error;\n }\n\n /* A block type BT, a padding string PS, and the data D shall be\n formatted into an octet string EB, the encryption block:\n\n EB = 00 || BT || PS || 00 || D\n\n The block type BT shall be a single octet indicating the structure of\n the encryption block. For this version of the document it shall have\n value 00, 01, or 02. For a private-key operation, the block type\n shall be 00 or 01. For a public-key operation, it shall be 02.\n\n The padding string PS shall consist of k-3-||D|| octets. For block\n type 00, the octets shall have value 00; for block type 01, they\n shall have value FF; and for block type 02, they shall be\n pseudorandomly generated and nonzero. This makes the length of the\n encryption block EB equal to k. */\n\n // build the encryption block\n eb.putByte(0x00);\n eb.putByte(bt);\n\n // create the padding\n var padNum = k - 3 - m.length;\n var padByte;\n // private key op\n if(bt === 0x00 || bt === 0x01) {\n padByte = (bt === 0x00) ? 0x00 : 0xFF;\n for(var i = 0; i < padNum; ++i) {\n eb.putByte(padByte);\n }\n } else {\n // public key op\n // pad with random non-zero values\n while(padNum > 0) {\n var numZeros = 0;\n var padBytes = forge.random.getBytes(padNum);\n for(var i = 0; i < padNum; ++i) {\n padByte = padBytes.charCodeAt(i);\n if(padByte === 0) {\n ++numZeros;\n } else {\n eb.putByte(padByte);\n }\n }\n padNum = numZeros;\n }\n }\n\n // zero followed by message\n eb.putByte(0x00);\n eb.putBytes(m);\n\n return eb;\n}\n\n/**\n * Decodes a message using PKCS#1 v1.5 padding.\n *\n * @param em the message to decode.\n * @param key the RSA key to use.\n * @param pub true if the key is a public key, false if it is private.\n * @param ml the message length, if specified.\n *\n * @return the decoded bytes.\n */\nfunction _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* It is an error if any of the following conditions occurs:\n\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer than eight octets\n or is inconsisent with the block type BT.\n 3. The decryption process is a public-key operation and the block\n type BT is not 00 or 01, or the decryption process is a\n private-key operation and the block type is not 02.\n */\n\n // parse the encryption block\n var eb = forge.util.createBuffer(em);\n var first = eb.getByte();\n var bt = eb.getByte();\n if(first !== 0x00 ||\n (pub && bt !== 0x00 && bt !== 0x01) ||\n (!pub && bt != 0x02) ||\n (pub && bt === 0x00 && typeof(ml) === 'undefined')) {\n throw new Error('Encryption block is invalid.');\n }\n\n var padNum = 0;\n if(bt === 0x00) {\n // check all padding bytes for 0x00\n padNum = k - 3 - ml;\n for(var i = 0; i < padNum; ++i) {\n if(eb.getByte() !== 0x00) {\n throw new Error('Encryption block is invalid.');\n }\n }\n } else if(bt === 0x01) {\n // find the first byte that isn't 0xFF, should be after all padding\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() !== 0xFF) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n } else if(bt === 0x02) {\n // look for 0x00 byte\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() === 0x00) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n }\n\n // zero must be 0x00 and padNum must be (k - 3 - message length)\n var zero = eb.getByte();\n if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {\n throw new Error('Encryption block is invalid.');\n }\n\n return eb.getBytes();\n}\n\n/**\n * Runs the key-generation algorithm asynchronously, either in the background\n * via Web Workers, or using the main thread and setImmediate.\n *\n * @param state the key-pair generation state.\n * @param [options] options for key-pair generation:\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2, -1 to use estimated cores minus one).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * @param callback(err, keypair) called once the operation completes.\n */\nfunction _generateKeyPair(state, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n var opts = {\n algorithm: {\n name: options.algorithm || 'PRIMEINC',\n options: {\n workers: options.workers || 2,\n workLoad: options.workLoad || 100,\n workerScript: options.workerScript\n }\n }\n };\n if('prng' in options) {\n opts.prng = options.prng;\n }\n\n generate();\n\n function generate() {\n // find p and then q (done in series to simplify)\n getPrime(state.pBits, function(err, num) {\n if(err) {\n return callback(err);\n }\n state.p = num;\n if(state.q !== null) {\n return finish(err, state.q);\n }\n getPrime(state.qBits, finish);\n });\n }\n\n function getPrime(bits, callback) {\n forge.prime.generateProbablePrime(bits, opts, callback);\n }\n\n function finish(err, num) {\n if(err) {\n return callback(err);\n }\n\n // set q\n state.q = num;\n\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n var tmp = state.p;\n state.p = state.q;\n state.q = tmp;\n }\n\n // ensure p is coprime with e\n if(state.p.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.p = null;\n generate();\n return;\n }\n\n // ensure q is coprime with e\n if(state.q.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {\n // phi and e aren't coprime, so generate a new p and q\n state.p = state.q = null;\n generate();\n return;\n }\n\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n if(state.n.bitLength() !== state.bits) {\n // failed, get new q\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n\n callback(null, state.keys);\n }\n}\n\n/**\n * Converts a positive BigInteger into 2's-complement big-endian bytes.\n *\n * @param b the big integer to convert.\n *\n * @return the bytes.\n */\nfunction _bnToBytes(b) {\n // prepend 0x00 if first byte >= 0x80\n var hex = b.toString(16);\n if(hex[0] >= '8') {\n hex = '00' + hex;\n }\n var bytes = forge.util.hexToBytes(hex);\n\n // ensure integer is minimally-encoded\n if(bytes.length > 1 &&\n // leading 0x00 for positive integer\n ((bytes.charCodeAt(0) === 0 &&\n (bytes.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (bytes.charCodeAt(0) === 0xFF &&\n (bytes.charCodeAt(1) & 0x80) === 0x80))) {\n return bytes.substr(1);\n }\n return bytes;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction _getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n/**\n * Performs feature detection on the Node crypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectNodeCrypto(fn) {\n return forge.util.isNodejs && typeof _crypto[fn] === 'function';\n}\n\n/**\n * Performs feature detection on the SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.crypto === 'object' &&\n typeof util.globalScope.crypto.subtle === 'object' &&\n typeof util.globalScope.crypto.subtle[fn] === 'function');\n}\n\n/**\n * Performs feature detection on the deprecated Microsoft Internet Explorer\n * outdated SubtleCrypto interface. This function should only be used after\n * checking for the modern, standard SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleMsCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.msCrypto === 'object' &&\n typeof util.globalScope.msCrypto.subtle === 'object' &&\n typeof util.globalScope.msCrypto.subtle[fn] === 'function');\n}\n\nfunction _intToUint8Array(x) {\n var bytes = forge.util.hexToBytes(x.toString(16));\n var buffer = new Uint8Array(bytes.length);\n for(var i = 0; i < bytes.length; ++i) {\n buffer[i] = bytes.charCodeAt(i);\n }\n return buffer;\n}\n\nfunction _privateKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error(\n 'Unsupported key algorithm \"' + jwk.kty + '\"; algorithm must be \"RSA\".');\n }\n return pki.setRsaPrivateKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e),\n _base64ToBigInt(jwk.d),\n _base64ToBigInt(jwk.p),\n _base64ToBigInt(jwk.q),\n _base64ToBigInt(jwk.dp),\n _base64ToBigInt(jwk.dq),\n _base64ToBigInt(jwk.qi));\n}\n\nfunction _publicKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error('Key algorithm must be \"RSA\".');\n }\n return pki.setRsaPublicKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e));\n}\n\nfunction _base64ToBigInt(b64) {\n return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);\n}\n","/**\n * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha1 = module.exports = forge.sha1 = forge.sha1 || {};\nforge.md.sha1 = forge.md.algorithms.sha1 = sha1;\n\n/**\n * Creates a SHA-1 message digest object.\n *\n * @return a message digest object.\n */\nsha1.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-1 state contains five 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(80);\n\n // message digest object\n var md = {\n algorithm: 'sha1',\n blockLength: 64,\n digestLength: 20,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-1 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n return rval;\n };\n\n return md;\n};\n\n// sha-1 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-1 state with the given byte buffer.\n *\n * @param s the SHA-1 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = bytes.getInt32();\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.\n *\n * See FIPS 180-2 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha256 = module.exports = forge.sha256 = forge.sha256 || {};\nforge.md.sha256 = forge.md.algorithms.sha256 = sha256;\n\n/**\n * Creates a SHA-256 message digest object.\n *\n * @return a message digest object.\n */\nsha256.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-256 state contains eight 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(64);\n\n // message digest object\n var md = {\n algorithm: 'sha256',\n blockLength: 64,\n digestLength: 32,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-256 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4,\n h5: _state.h5,\n h6: _state.h6,\n h7: _state.h7\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n rval.putInt32(s2.h5);\n rval.putInt32(s2.h6);\n rval.putInt32(s2.h7);\n return rval;\n };\n\n return md;\n};\n\n// sha-256 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // create K table for SHA-256\n _k = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-256 state with the given byte buffer.\n *\n * @param s the SHA-256 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n a = (t1 + t2) >>> 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n}\n","/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n *\n * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For\n * SHA-256 (block size 512 bits), see sha256.js.\n *\n * See FIPS 180-4 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha512 = module.exports = forge.sha512 = forge.sha512 || {};\n\n// SHA-512\nforge.md.sha512 = forge.md.algorithms.sha512 = sha512;\n\n// SHA-384\nvar sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};\nsha384.create = function() {\n return sha512.create('SHA-384');\n};\nforge.md.sha384 = forge.md.algorithms.sha384 = sha384;\n\n// SHA-512/256\nforge.sha512.sha256 = forge.sha512.sha256 || {\n create: function() {\n return sha512.create('SHA-512/256');\n }\n};\nforge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =\n forge.sha512.sha256;\n\n// SHA-512/224\nforge.sha512.sha224 = forge.sha512.sha224 || {\n create: function() {\n return sha512.create('SHA-512/224');\n }\n};\nforge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =\n forge.sha512.sha224;\n\n/**\n * Creates a SHA-2 message digest object.\n *\n * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,\n * SHA-512/256).\n *\n * @return a message digest object.\n */\nsha512.create = function(algorithm) {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n if(typeof algorithm === 'undefined') {\n algorithm = 'SHA-512';\n }\n\n if(!(algorithm in _states)) {\n throw new Error('Invalid SHA-512 algorithm: ' + algorithm);\n }\n\n // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)\n var _state = _states[algorithm];\n var _h = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for 64-bit word storage\n var _w = new Array(80);\n for(var wi = 0; wi < 80; ++wi) {\n _w[wi] = new Array(2);\n }\n\n // determine digest length by algorithm name (default)\n var digestLength = 64;\n switch(algorithm) {\n case 'SHA-384':\n digestLength = 48;\n break;\n case 'SHA-512/256':\n digestLength = 32;\n break;\n case 'SHA-512/224':\n digestLength = 28;\n break;\n }\n\n // message digest object\n var md = {\n // SHA-512 => sha512\n algorithm: algorithm.replace('-', '').toLowerCase(),\n blockLength: 128,\n digestLength: digestLength,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 16\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength128 for backwards-compatibility)\n md.fullMessageLength = md.messageLength128 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _h = new Array(_state.length);\n for(var i = 0; i < _state.length; ++i) {\n _h[i] = _state[i].slice(0);\n }\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_h, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-512 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 896 mod 1024. In other words,\n the data to be digested must be a multiple of 1024 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 16 bytes (128\n bits), that means that the last segment of the data must have 112 bytes\n (896 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 896 mod 1024 because\n 1024 - 128 = 896.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 896 mod 1024, then 1024 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var h = new Array(_h.length);\n for(var i = 0; i < _h.length; ++i) {\n h[i] = _h[i].slice(0);\n }\n _update(h, _w, finalBlock);\n var rval = forge.util.createBuffer();\n var hlen;\n if(algorithm === 'SHA-512') {\n hlen = h.length;\n } else if(algorithm === 'SHA-384') {\n hlen = h.length - 2;\n } else {\n hlen = h.length - 4;\n }\n for(var i = 0; i < hlen; ++i) {\n rval.putInt32(h[i][0]);\n if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {\n rval.putInt32(h[i][1]);\n }\n }\n return rval;\n };\n\n return md;\n};\n\n// sha-512 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n// initial hash states\nvar _states = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 128);\n\n // create K table for SHA-512\n _k = [\n [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],\n [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],\n [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],\n [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],\n [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],\n [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],\n [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],\n [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],\n [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],\n [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],\n [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],\n [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],\n [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],\n [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],\n [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],\n [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],\n [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],\n [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],\n [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],\n [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],\n [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],\n [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],\n [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],\n [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],\n [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],\n [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],\n [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],\n [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],\n [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],\n [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],\n [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],\n [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],\n [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],\n [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],\n [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],\n [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],\n [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],\n [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],\n [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],\n [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]\n ];\n\n // initial hash states\n _states = {};\n _states['SHA-512'] = [\n [0x6a09e667, 0xf3bcc908],\n [0xbb67ae85, 0x84caa73b],\n [0x3c6ef372, 0xfe94f82b],\n [0xa54ff53a, 0x5f1d36f1],\n [0x510e527f, 0xade682d1],\n [0x9b05688c, 0x2b3e6c1f],\n [0x1f83d9ab, 0xfb41bd6b],\n [0x5be0cd19, 0x137e2179]\n ];\n _states['SHA-384'] = [\n [0xcbbb9d5d, 0xc1059ed8],\n [0x629a292a, 0x367cd507],\n [0x9159015a, 0x3070dd17],\n [0x152fecd8, 0xf70e5939],\n [0x67332667, 0xffc00b31],\n [0x8eb44a87, 0x68581511],\n [0xdb0c2e0d, 0x64f98fa7],\n [0x47b5481d, 0xbefa4fa4]\n ];\n _states['SHA-512/256'] = [\n [0x22312194, 0xFC2BF72C],\n [0x9F555FA3, 0xC84C64C2],\n [0x2393B86B, 0x6F53B151],\n [0x96387719, 0x5940EABD],\n [0x96283EE2, 0xA88EFFE3],\n [0xBE5E1E25, 0x53863992],\n [0x2B0199FC, 0x2C85B8AA],\n [0x0EB72DDC, 0x81C52CA2]\n ];\n _states['SHA-512/224'] = [\n [0x8C3D37C8, 0x19544DA2],\n [0x73E19966, 0x89DCD4D6],\n [0x1DFAB7AE, 0x32FF9C82],\n [0x679DD514, 0x582F9FCF],\n [0x0F6D2B69, 0x7BD44DA8],\n [0x77E36F73, 0x04C48942],\n [0x3F9D85A8, 0x6A1D36C8],\n [0x1112E6AD, 0x91D692A1]\n ];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-512 state with the given byte buffer.\n *\n * @param s the SHA-512 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (128 byte) chunks\n var t1_hi, t1_lo;\n var t2_hi, t2_lo;\n var s0_hi, s0_lo;\n var s1_hi, s1_lo;\n var ch_hi, ch_lo;\n var maj_hi, maj_lo;\n var a_hi, a_lo;\n var b_hi, b_lo;\n var c_hi, c_lo;\n var d_hi, d_lo;\n var e_hi, e_lo;\n var f_hi, f_lo;\n var g_hi, g_lo;\n var h_hi, h_lo;\n var i, hi, lo, w2, w7, w15, w16;\n var len = bytes.length();\n while(len >= 128) {\n // the w array will be populated with sixteen 64-bit big-endian words\n // and then extended into 64 64-bit words according to SHA-512\n for(i = 0; i < 16; ++i) {\n w[i][0] = bytes.getInt32() >>> 0;\n w[i][1] = bytes.getInt32() >>> 0;\n }\n for(; i < 80; ++i) {\n // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)\n w2 = w[i - 2];\n hi = w2[0];\n lo = w2[1];\n\n // high bits\n t1_hi = (\n ((hi >>> 19) | (lo << 13)) ^ // ROTR 19\n ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)\n (hi >>> 6)) >>> 0; // SHR 6\n // low bits\n t1_lo = (\n ((hi << 13) | (lo >>> 19)) ^ // ROTR 19\n ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)\n ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6\n\n // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)\n w15 = w[i - 15];\n hi = w15[0];\n lo = w15[1];\n\n // high bits\n t2_hi = (\n ((hi >>> 1) | (lo << 31)) ^ // ROTR 1\n ((hi >>> 8) | (lo << 24)) ^ // ROTR 8\n (hi >>> 7)) >>> 0; // SHR 7\n // low bits\n t2_lo = (\n ((hi << 31) | (lo >>> 1)) ^ // ROTR 1\n ((hi << 24) | (lo >>> 8)) ^ // ROTR 8\n ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7\n\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)\n w7 = w[i - 7];\n w16 = w[i - 16];\n lo = (t1_lo + w7[1] + t2_lo + w16[1]);\n w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n w[i][1] = lo >>> 0;\n }\n\n // initialize hash value for this chunk\n a_hi = s[0][0];\n a_lo = s[0][1];\n b_hi = s[1][0];\n b_lo = s[1][1];\n c_hi = s[2][0];\n c_lo = s[2][1];\n d_hi = s[3][0];\n d_lo = s[3][1];\n e_hi = s[4][0];\n e_lo = s[4][1];\n f_hi = s[5][0];\n f_lo = s[5][1];\n g_hi = s[6][0];\n g_lo = s[6][1];\n h_hi = s[7][0];\n h_lo = s[7][1];\n\n // round function\n for(i = 0; i < 80; ++i) {\n // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)\n s1_hi = (\n ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14\n ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18\n ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)\n s1_lo = (\n ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14\n ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18\n ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)\n\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;\n ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;\n\n // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)\n s0_hi = (\n ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28\n ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)\n s0_lo = (\n ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28\n ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)\n\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;\n maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;\n\n // main algorithm\n // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)\n lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);\n t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n t1_lo = lo >>> 0;\n\n // t2 = s0 + maj modulo 2^64 (carry lo overflow)\n lo = s0_lo + maj_lo;\n t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n t2_lo = lo >>> 0;\n\n h_hi = g_hi;\n h_lo = g_lo;\n\n g_hi = f_hi;\n g_lo = f_lo;\n\n f_hi = e_hi;\n f_lo = e_lo;\n\n // e = (d + t1) modulo 2^64 (carry lo overflow)\n lo = d_lo + t1_lo;\n e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n e_lo = lo >>> 0;\n\n d_hi = c_hi;\n d_lo = c_lo;\n\n c_hi = b_hi;\n c_lo = b_lo;\n\n b_hi = a_hi;\n b_lo = a_lo;\n\n // a = (t1 + t2) modulo 2^64 (carry lo overflow)\n lo = t1_lo + t2_lo;\n a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n a_lo = lo >>> 0;\n }\n\n // update hash state (additional modulo 2^64)\n lo = s[0][1] + a_lo;\n s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[0][1] = lo >>> 0;\n\n lo = s[1][1] + b_lo;\n s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[1][1] = lo >>> 0;\n\n lo = s[2][1] + c_lo;\n s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[2][1] = lo >>> 0;\n\n lo = s[3][1] + d_lo;\n s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[3][1] = lo >>> 0;\n\n lo = s[4][1] + e_lo;\n s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[4][1] = lo >>> 0;\n\n lo = s[5][1] + f_lo;\n s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[5][1] = lo >>> 0;\n\n lo = s[6][1] + g_lo;\n s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[6][1] = lo >>> 0;\n\n lo = s[7][1] + h_lo;\n s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[7][1] = lo >>> 0;\n\n len -= 128;\n }\n}\n","/**\n * Functions to output keys in SSH-friendly formats.\n *\n * This is part of the Forge project which may be used under the terms of\n * either the BSD License or the GNU General Public License (GPL) Version 2.\n *\n * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE\n *\n * @author https://github.com/shellac\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./hmac');\nrequire('./md5');\nrequire('./sha1');\nrequire('./util');\n\nvar ssh = module.exports = forge.ssh = forge.ssh || {};\n\n/**\n * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file.\n *\n * @param privateKey the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n * @param comment a comment to include in the key file.\n *\n * @return the PPK file as a string.\n */\nssh.privateKeyToPutty = function(privateKey, passphrase, comment) {\n comment = comment || '';\n passphrase = passphrase || '';\n var algorithm = 'ssh-rsa';\n var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc';\n\n var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\\r\\n';\n ppk += 'Encryption: ' + encryptionAlgorithm + '\\r\\n';\n ppk += 'Comment: ' + comment + '\\r\\n';\n\n // public key into buffer for ppk\n var pubbuffer = forge.util.createBuffer();\n _addStringToBuffer(pubbuffer, algorithm);\n _addBigIntegerToBuffer(pubbuffer, privateKey.e);\n _addBigIntegerToBuffer(pubbuffer, privateKey.n);\n\n // write public key\n var pub = forge.util.encode64(pubbuffer.bytes(), 64);\n var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \\r\\n\n ppk += 'Public-Lines: ' + length + '\\r\\n';\n ppk += pub;\n\n // private key into a buffer\n var privbuffer = forge.util.createBuffer();\n _addBigIntegerToBuffer(privbuffer, privateKey.d);\n _addBigIntegerToBuffer(privbuffer, privateKey.p);\n _addBigIntegerToBuffer(privbuffer, privateKey.q);\n _addBigIntegerToBuffer(privbuffer, privateKey.qInv);\n\n // optionally encrypt the private key\n var priv;\n if(!passphrase) {\n // use the unencrypted buffer\n priv = forge.util.encode64(privbuffer.bytes(), 64);\n } else {\n // encrypt RSA key using passphrase\n var encLen = privbuffer.length() + 16 - 1;\n encLen -= encLen % 16;\n\n // pad private key with sha1-d data -- needs to be a multiple of 16\n var padding = _sha1(privbuffer.bytes());\n\n padding.truncate(padding.length() - encLen + privbuffer.length());\n privbuffer.putBuffer(padding);\n\n var aeskey = forge.util.createBuffer();\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x00', passphrase));\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x01', passphrase));\n\n // encrypt some bytes using CBC mode\n // key is 40 bytes, so truncate *by* 8 bytes\n var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC');\n cipher.start(forge.util.createBuffer().fillWithByte(0, 16));\n cipher.update(privbuffer.copy());\n cipher.finish();\n var encrypted = cipher.output;\n\n // Note: this appears to differ from Putty -- is forge wrong, or putty?\n // due to padding we finish as an exact multiple of 16\n encrypted.truncate(16); // all padding\n\n priv = forge.util.encode64(encrypted.bytes(), 64);\n }\n\n // output private key\n length = Math.floor(priv.length / 66) + 1; // 64 + \\r\\n\n ppk += '\\r\\nPrivate-Lines: ' + length + '\\r\\n';\n ppk += priv;\n\n // MAC\n var mackey = _sha1('putty-private-key-file-mac-key', passphrase);\n\n var macbuffer = forge.util.createBuffer();\n _addStringToBuffer(macbuffer, algorithm);\n _addStringToBuffer(macbuffer, encryptionAlgorithm);\n _addStringToBuffer(macbuffer, comment);\n macbuffer.putInt32(pubbuffer.length());\n macbuffer.putBuffer(pubbuffer);\n macbuffer.putInt32(privbuffer.length());\n macbuffer.putBuffer(privbuffer);\n\n var hmac = forge.hmac.create();\n hmac.start('sha1', mackey);\n hmac.update(macbuffer.bytes());\n\n ppk += '\\r\\nPrivate-MAC: ' + hmac.digest().toHex() + '\\r\\n';\n\n return ppk;\n};\n\n/**\n * Encodes a public RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param comment a comment.\n *\n * @return the public key in OpenSSH format.\n */\nssh.publicKeyToOpenSSH = function(key, comment) {\n var type = 'ssh-rsa';\n comment = comment || '';\n\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment;\n};\n\n/**\n * Encodes a private RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n *\n * @return the public key in OpenSSH format.\n */\nssh.privateKeyToOpenSSH = function(privateKey, passphrase) {\n if(!passphrase) {\n return forge.pki.privateKeyToPem(privateKey);\n }\n // OpenSSH private key is just a legacy format, it seems\n return forge.pki.encryptRsaPrivateKey(privateKey, passphrase,\n {legacy: true, algorithm: 'aes128'});\n};\n\n/**\n * Gets the SSH fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.md5).\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\nssh.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.md5.create();\n\n var type = 'ssh-rsa';\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n // hash public key bytes\n md.start();\n md.update(buffer.getBytes());\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a big integer.\n */\nfunction _addBigIntegerToBuffer(buffer, val) {\n var hexVal = val.toString(16);\n // ensure 2s complement +ve\n if(hexVal[0] >= '8') {\n hexVal = '00' + hexVal;\n }\n var bytes = forge.util.hexToBytes(hexVal);\n buffer.putInt32(bytes.length);\n buffer.putBytes(bytes);\n}\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a string.\n */\nfunction _addStringToBuffer(buffer, val) {\n buffer.putInt32(val.length);\n buffer.putString(val);\n}\n\n/**\n * Hashes the arguments into one value using SHA-1.\n *\n * @return the sha1 hash of the provided arguments.\n */\nfunction _sha1() {\n var sha = forge.md.sha1.create();\n var num = arguments.length;\n for (var i = 0; i < num; ++i) {\n sha.update(arguments[i]);\n }\n return sha.digest();\n}\n","/**\n * A Javascript implementation of Transport Layer Security (TLS).\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n *\n * The TLS Handshake Protocol involves the following steps:\n *\n * - Exchange hello messages to agree on algorithms, exchange random values,\n * and check for session resumption.\n *\n * - Exchange the necessary cryptographic parameters to allow the client and\n * server to agree on a premaster secret.\n *\n * - Exchange certificates and cryptographic information to allow the client\n * and server to authenticate themselves.\n *\n * - Generate a master secret from the premaster secret and exchanged random\n * values.\n *\n * - Provide security parameters to the record layer.\n *\n * - Allow the client and server to verify that their peer has calculated the\n * same security parameters and that the handshake occurred without tampering\n * by an attacker.\n *\n * Up to 4 different messages may be sent during a key exchange. The server\n * certificate, the server key exchange, the client certificate, and the\n * client key exchange.\n *\n * A typical handshake (from the client's perspective).\n *\n * 1. Client sends ClientHello.\n * 2. Client receives ServerHello.\n * 3. Client receives optional Certificate.\n * 4. Client receives optional ServerKeyExchange.\n * 5. Client receives ServerHelloDone.\n * 6. Client sends optional Certificate.\n * 7. Client sends ClientKeyExchange.\n * 8. Client sends optional CertificateVerify.\n * 9. Client sends ChangeCipherSpec.\n * 10. Client sends Finished.\n * 11. Client receives ChangeCipherSpec.\n * 12. Client receives Finished.\n * 13. Client sends/receives application data.\n *\n * To reuse an existing session:\n *\n * 1. Client sends ClientHello with session ID for reuse.\n * 2. Client receives ServerHello with same session ID if reusing.\n * 3. Client receives ChangeCipherSpec message if reusing.\n * 4. Client receives Finished.\n * 5. Client sends ChangeCipherSpec.\n * 6. Client sends Finished.\n *\n * Note: Client ignores HelloRequest if in the middle of a handshake.\n *\n * Record Layer:\n *\n * The record layer fragments information blocks into TLSPlaintext records\n * carrying data in chunks of 2^14 bytes or less. Client message boundaries are\n * not preserved in the record layer (i.e., multiple client messages of the\n * same ContentType MAY be coalesced into a single TLSPlaintext record, or a\n * single message MAY be fragmented across several records).\n *\n * struct {\n * uint8 major;\n * uint8 minor;\n * } ProtocolVersion;\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * opaque fragment[TLSPlaintext.length];\n * } TLSPlaintext;\n *\n * type:\n * The higher-level protocol used to process the enclosed fragment.\n *\n * version:\n * The version of the protocol being employed. TLS Version 1.2 uses version\n * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that\n * supports multiple versions of TLS may not know what version will be\n * employed before it receives the ServerHello.\n *\n * length:\n * The length (in bytes) of the following TLSPlaintext.fragment. The length\n * MUST NOT exceed 2^14 = 16384 bytes.\n *\n * fragment:\n * The application data. This data is transparent and treated as an\n * independent block to be dealt with by the higher-level protocol specified\n * by the type field.\n *\n * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or\n * ChangeCipherSpec content types. Zero-length fragments of Application data\n * MAY be sent as they are potentially useful as a traffic analysis\n * countermeasure.\n *\n * Note: Data of different TLS record layer content types MAY be interleaved.\n * Application data is generally of lower precedence for transmission than\n * other content types. However, records MUST be delivered to the network in\n * the same order as they are protected by the record layer. Recipients MUST\n * receive and process interleaved application layer traffic during handshakes\n * subsequent to the first one on a connection.\n *\n * struct {\n * ContentType type; // same as TLSPlaintext.type\n * ProtocolVersion version;// same as TLSPlaintext.version\n * uint16 length;\n * opaque fragment[TLSCompressed.length];\n * } TLSCompressed;\n *\n * length:\n * The length (in bytes) of the following TLSCompressed.fragment.\n * The length MUST NOT exceed 2^14 + 1024.\n *\n * fragment:\n * The compressed form of TLSPlaintext.fragment.\n *\n * Note: A CompressionMethod.null operation is an identity operation; no fields\n * are altered. In this implementation, since no compression is supported,\n * uncompressed records are always the same as compressed records.\n *\n * Encryption Information:\n *\n * The encryption and MAC functions translate a TLSCompressed structure into a\n * TLSCiphertext. The decryption functions reverse the process. The MAC of the\n * record also includes a sequence number so that missing, extra, or repeated\n * messages are detectable.\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * select (SecurityParameters.cipher_type) {\n * case stream: GenericStreamCipher;\n * case block: GenericBlockCipher;\n * case aead: GenericAEADCipher;\n * } fragment;\n * } TLSCiphertext;\n *\n * type:\n * The type field is identical to TLSCompressed.type.\n *\n * version:\n * The version field is identical to TLSCompressed.version.\n *\n * length:\n * The length (in bytes) of the following TLSCiphertext.fragment.\n * The length MUST NOT exceed 2^14 + 2048.\n *\n * fragment:\n * The encrypted form of TLSCompressed.fragment, with the MAC.\n *\n * Note: Only CBC Block Ciphers are supported by this implementation.\n *\n * The TLSCompressed.fragment structures are converted to/from block\n * TLSCiphertext.fragment structures.\n *\n * struct {\n * opaque IV[SecurityParameters.record_iv_length];\n * block-ciphered struct {\n * opaque content[TLSCompressed.length];\n * opaque MAC[SecurityParameters.mac_length];\n * uint8 padding[GenericBlockCipher.padding_length];\n * uint8 padding_length;\n * };\n * } GenericBlockCipher;\n *\n * The MAC is generated as described in Section 6.2.3.1.\n *\n * IV:\n * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be\n * unpredictable. Note that in versions of TLS prior to 1.1, there was no\n * IV field, and the last ciphertext block of the previous record (the \"CBC\n * residue\") was used as the IV. This was changed to prevent the attacks\n * described in [CBCATT]. For block ciphers, the IV length is of length\n * SecurityParameters.record_iv_length, which is equal to the\n * SecurityParameters.block_size.\n *\n * padding:\n * Padding that is added to force the length of the plaintext to be an\n * integral multiple of the block cipher's block length. The padding MAY be\n * any length up to 255 bytes, as long as it results in the\n * TLSCiphertext.length being an integral multiple of the block length.\n * Lengths longer than necessary might be desirable to frustrate attacks on\n * a protocol that are based on analysis of the lengths of exchanged\n * messages. Each uint8 in the padding data vector MUST be filled with the\n * padding length value. The receiver MUST check this padding and MUST use\n * the bad_record_mac alert to indicate padding errors.\n *\n * padding_length:\n * The padding length MUST be such that the total size of the\n * GenericBlockCipher structure is a multiple of the cipher's block length.\n * Legal values range from zero to 255, inclusive. This length specifies the\n * length of the padding field exclusive of the padding_length field itself.\n *\n * The encrypted data length (TLSCiphertext.length) is one more than the sum of\n * SecurityParameters.block_length, TLSCompressed.length,\n * SecurityParameters.mac_length, and padding_length.\n *\n * Example: If the block length is 8 bytes, the content length\n * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the\n * length before padding is 82 bytes (this does not include the IV. Thus, the\n * padding length modulo 8 must be equal to 6 in order to make the total length\n * an even multiple of 8 bytes (the block length). The padding length can be\n * 6, 14, 22, and so on, through 254. If the padding length were the minimum\n * necessary, 6, the padding would be 6 bytes, each containing the value 6.\n * Thus, the last 8 octets of the GenericBlockCipher before block encryption\n * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC.\n *\n * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical\n * that the entire plaintext of the record be known before any ciphertext is\n * transmitted. Otherwise, it is possible for the attacker to mount the attack\n * described in [CBCATT].\n *\n * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing\n * attack on CBC padding based on the time required to compute the MAC. In\n * order to defend against this attack, implementations MUST ensure that\n * record processing time is essentially the same whether or not the padding\n * is correct. In general, the best way to do this is to compute the MAC even\n * if the padding is incorrect, and only then reject the packet. For instance,\n * if the pad appears to be incorrect, the implementation might assume a\n * zero-length pad and then compute the MAC. This leaves a small timing\n * channel, since MAC performance depends, to some extent, on the size of the\n * data fragment, but it is not believed to be large enough to be exploitable,\n * due to the large block size of existing MACs and the small size of the\n * timing signal.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./md5');\nrequire('./pem');\nrequire('./pki');\nrequire('./random');\nrequire('./sha1');\nrequire('./util');\n\n/**\n * Generates pseudo random bytes by mixing the result of two hash functions,\n * MD5 and SHA-1.\n *\n * prf_TLS1(secret, label, seed) =\n * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);\n *\n * Each P_hash function functions as follows:\n *\n * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +\n * HMAC_hash(secret, A(2) + seed) +\n * HMAC_hash(secret, A(3) + seed) + ...\n * A() is defined as:\n * A(0) = seed\n * A(i) = HMAC_hash(secret, A(i-1))\n *\n * The '+' operator denotes concatenation.\n *\n * As many iterations A(N) as are needed are performed to generate enough\n * pseudo random byte output. If an iteration creates more data than is\n * necessary, then it is truncated.\n *\n * Therefore:\n * A(1) = HMAC_hash(secret, A(0))\n * = HMAC_hash(secret, seed)\n * A(2) = HMAC_hash(secret, A(1))\n * = HMAC_hash(secret, HMAC_hash(secret, seed))\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +\n * ...\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +\n * ...\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_TLS1 = function(secret, label, seed, length) {\n var rval = forge.util.createBuffer();\n\n /* For TLS 1.0, the secret is split in half, into two secrets of equal\n length. If the secret has an odd length then the last byte of the first\n half will be the same as the first byte of the second. The length of the\n two secrets is half of the secret rounded up. */\n var idx = (secret.length >> 1);\n var slen = idx + (secret.length & 1);\n var s1 = secret.substr(0, slen);\n var s2 = secret.substr(idx, slen);\n var ai = forge.util.createBuffer();\n var hmac = forge.hmac.create();\n seed = label + seed;\n\n // determine the number of iterations that must be performed to generate\n // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20\n var md5itr = Math.ceil(length / 16);\n var sha1itr = Math.ceil(length / 20);\n\n // do md5 iterations\n hmac.start('MD5', s1);\n var md5bytes = forge.util.createBuffer();\n ai.putBytes(seed);\n for(var i = 0; i < md5itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n md5bytes.putBuffer(hmac.digest());\n }\n\n // do sha1 iterations\n hmac.start('SHA1', s2);\n var sha1bytes = forge.util.createBuffer();\n ai.clear();\n ai.putBytes(seed);\n for(var i = 0; i < sha1itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n sha1bytes.putBuffer(hmac.digest());\n }\n\n // XOR the md5 bytes with the sha1 bytes\n rval.putBytes(forge.util.xorBytes(\n md5bytes.getBytes(), sha1bytes.getBytes(), length));\n\n return rval;\n};\n\n/**\n * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2.\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_sha256 = function(secret, label, seed, length) {\n // FIXME: implement me for TLS 1.2\n};\n\n/**\n * Gets a MAC for a record using the SHA-1 hash algorithm.\n *\n * @param key the mac key.\n * @param state the sequence number (array of two 32-bit integers).\n * @param record the record.\n *\n * @return the sha-1 hash (20 bytes) for the given record.\n */\nvar hmac_sha1 = function(key, seqNum, record) {\n /* MAC is computed like so:\n HMAC_hash(\n key, seqNum +\n TLSCompressed.type +\n TLSCompressed.version +\n TLSCompressed.length +\n TLSCompressed.fragment)\n */\n var hmac = forge.hmac.create();\n hmac.start('SHA1', key);\n var b = forge.util.createBuffer();\n b.putInt32(seqNum[0]);\n b.putInt32(seqNum[1]);\n b.putByte(record.type);\n b.putByte(record.version.major);\n b.putByte(record.version.minor);\n b.putInt16(record.length);\n b.putBytes(record.fragment.bytes());\n hmac.update(b.getBytes());\n return hmac.digest().getBytes();\n};\n\n/**\n * Compresses the TLSPlaintext record into a TLSCompressed record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSPlaintext record to compress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar deflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.deflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // deflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Decompresses the TLSCompressed record into a TLSPlaintext record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSCompressed record to decompress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar inflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.inflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // inflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Reads a TLS variable-length vector from a byte buffer.\n *\n * Variable-length vectors are defined by specifying a subrange of legal\n * lengths, inclusively, using the notation . When these are\n * encoded, the actual length precedes the vector's contents in the byte\n * stream. The length will be in the form of a number consuming as many bytes\n * as required to hold the vector's specified maximum (ceiling) length. A\n * variable-length vector with an actual length field of zero is referred to\n * as an empty vector.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n *\n * @return the resulting byte buffer.\n */\nvar readVector = function(b, lenBytes) {\n var len = 0;\n switch(lenBytes) {\n case 1:\n len = b.getByte();\n break;\n case 2:\n len = b.getInt16();\n break;\n case 3:\n len = b.getInt24();\n break;\n case 4:\n len = b.getInt32();\n break;\n }\n\n // read vector bytes into a new buffer\n return forge.util.createBuffer(b.getBytes(len));\n};\n\n/**\n * Writes a TLS variable-length vector to a byte buffer.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n * @param v the byte buffer vector.\n */\nvar writeVector = function(b, lenBytes, v) {\n // encode length at the start of the vector, where the number of bytes for\n // the length is the maximum number of bytes it would take to encode the\n // vector's ceiling\n b.putInt(v.length(), lenBytes << 3);\n b.putBuffer(v);\n};\n\n/**\n * The tls implementation.\n */\nvar tls = {};\n\n/**\n * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and\n * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time\n * of this implementation so TLS 1.0 was implemented instead.\n */\ntls.Versions = {\n TLS_1_0: {major: 3, minor: 1},\n TLS_1_1: {major: 3, minor: 2},\n TLS_1_2: {major: 3, minor: 3}\n};\ntls.SupportedVersions = [\n tls.Versions.TLS_1_1,\n tls.Versions.TLS_1_0\n];\ntls.Version = tls.SupportedVersions[0];\n\n/**\n * Maximum fragment size. True maximum is 16384, but we fragment before that\n * to allow for unusual small increases during compression.\n */\ntls.MaxFragment = 16384 - 1024;\n\n/**\n * Whether this entity is considered the \"client\" or \"server\".\n * enum { server, client } ConnectionEnd;\n */\ntls.ConnectionEnd = {\n server: 0,\n client: 1\n};\n\n/**\n * Pseudo-random function algorithm used to generate keys from the master\n * secret.\n * enum { tls_prf_sha256 } PRFAlgorithm;\n */\ntls.PRFAlgorithm = {\n tls_prf_sha256: 0\n};\n\n/**\n * Bulk encryption algorithms.\n * enum { null, rc4, des3, aes } BulkCipherAlgorithm;\n */\ntls.BulkCipherAlgorithm = {\n none: null,\n rc4: 0,\n des3: 1,\n aes: 2\n};\n\n/**\n * Cipher types.\n * enum { stream, block, aead } CipherType;\n */\ntls.CipherType = {\n stream: 0,\n block: 1,\n aead: 2\n};\n\n/**\n * MAC (Message Authentication Code) algorithms.\n * enum { null, hmac_md5, hmac_sha1, hmac_sha256,\n * hmac_sha384, hmac_sha512} MACAlgorithm;\n */\ntls.MACAlgorithm = {\n none: null,\n hmac_md5: 0,\n hmac_sha1: 1,\n hmac_sha256: 2,\n hmac_sha384: 3,\n hmac_sha512: 4\n};\n\n/**\n * Compression algorithms.\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n */\ntls.CompressionMethod = {\n none: 0,\n deflate: 1\n};\n\n/**\n * TLS record content types.\n * enum {\n * change_cipher_spec(20), alert(21), handshake(22),\n * application_data(23), (255)\n * } ContentType;\n */\ntls.ContentType = {\n change_cipher_spec: 20,\n alert: 21,\n handshake: 22,\n application_data: 23,\n heartbeat: 24\n};\n\n/**\n * TLS handshake types.\n * enum {\n * hello_request(0), client_hello(1), server_hello(2),\n * certificate(11), server_key_exchange (12),\n * certificate_request(13), server_hello_done(14),\n * certificate_verify(15), client_key_exchange(16),\n * finished(20), (255)\n * } HandshakeType;\n */\ntls.HandshakeType = {\n hello_request: 0,\n client_hello: 1,\n server_hello: 2,\n certificate: 11,\n server_key_exchange: 12,\n certificate_request: 13,\n server_hello_done: 14,\n certificate_verify: 15,\n client_key_exchange: 16,\n finished: 20\n};\n\n/**\n * TLS Alert Protocol.\n *\n * enum { warning(1), fatal(2), (255) } AlertLevel;\n *\n * enum {\n * close_notify(0),\n * unexpected_message(10),\n * bad_record_mac(20),\n * decryption_failed(21),\n * record_overflow(22),\n * decompression_failure(30),\n * handshake_failure(40),\n * bad_certificate(42),\n * unsupported_certificate(43),\n * certificate_revoked(44),\n * certificate_expired(45),\n * certificate_unknown(46),\n * illegal_parameter(47),\n * unknown_ca(48),\n * access_denied(49),\n * decode_error(50),\n * decrypt_error(51),\n * export_restriction(60),\n * protocol_version(70),\n * insufficient_security(71),\n * internal_error(80),\n * user_canceled(90),\n * no_renegotiation(100),\n * (255)\n * } AlertDescription;\n *\n * struct {\n * AlertLevel level;\n * AlertDescription description;\n * } Alert;\n */\ntls.Alert = {};\ntls.Alert.Level = {\n warning: 1,\n fatal: 2\n};\ntls.Alert.Description = {\n close_notify: 0,\n unexpected_message: 10,\n bad_record_mac: 20,\n decryption_failed: 21,\n record_overflow: 22,\n decompression_failure: 30,\n handshake_failure: 40,\n bad_certificate: 42,\n unsupported_certificate: 43,\n certificate_revoked: 44,\n certificate_expired: 45,\n certificate_unknown: 46,\n illegal_parameter: 47,\n unknown_ca: 48,\n access_denied: 49,\n decode_error: 50,\n decrypt_error: 51,\n export_restriction: 60,\n protocol_version: 70,\n insufficient_security: 71,\n internal_error: 80,\n user_canceled: 90,\n no_renegotiation: 100\n};\n\n/**\n * TLS Heartbeat Message types.\n * enum {\n * heartbeat_request(1),\n * heartbeat_response(2),\n * (255)\n * } HeartbeatMessageType;\n */\ntls.HeartbeatMessageType = {\n heartbeat_request: 1,\n heartbeat_response: 2\n};\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites = {};\n\n/**\n * Gets a supported cipher suite from its 2 byte ID.\n *\n * @param twoBytes two bytes in a string.\n *\n * @return the matching supported cipher suite or null.\n */\ntls.getCipherSuite = function(twoBytes) {\n var rval = null;\n for(var key in tls.CipherSuites) {\n var cs = tls.CipherSuites[key];\n if(cs.id[0] === twoBytes.charCodeAt(0) &&\n cs.id[1] === twoBytes.charCodeAt(1)) {\n rval = cs;\n break;\n }\n }\n return rval;\n};\n\n/**\n * Called when an unexpected record is encountered.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleUnexpected = function(c, record) {\n // if connection is client and closed, ignore unexpected messages\n var ignore = (!c.open && c.entity === tls.ConnectionEnd.client);\n if(!ignore) {\n c.error(c, {\n message: 'Unexpected message. Received TLS record out of order.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unexpected_message\n }\n });\n }\n};\n\n/**\n * Called when a client receives a HelloRequest record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleHelloRequest = function(c, record, length) {\n // ignore renegotiation requests from the server during a handshake, but\n // if handshaking, send a warning alert that renegotation is denied\n if(!c.handshaking && c.handshakes > 0) {\n // send alert warning\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.no_renegotiation\n }));\n tls.flush(c);\n }\n\n // continue\n c.process();\n};\n\n/**\n * Parses a hello message from a ClientHello or ServerHello record.\n *\n * @param record the record to parse.\n *\n * @return the parsed message.\n */\ntls.parseHelloMessage = function(c, record, length) {\n var msg = null;\n\n var client = (c.entity === tls.ConnectionEnd.client);\n\n // minimum of 38 bytes in message\n if(length < 38) {\n c.error(c, {\n message: client ?\n 'Invalid ServerHello message. Message too short.' :\n 'Invalid ClientHello message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else {\n // use 'remaining' to calculate # of remaining bytes in the message\n var b = record.fragment;\n var remaining = b.length();\n msg = {\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n random: forge.util.createBuffer(b.getBytes(32)),\n session_id: readVector(b, 1),\n extensions: []\n };\n if(client) {\n msg.cipher_suite = b.getBytes(2);\n msg.compression_method = b.getByte();\n } else {\n msg.cipher_suites = readVector(b, 2);\n msg.compression_methods = readVector(b, 1);\n }\n\n // read extensions if there are any bytes left in the message\n remaining = length - (remaining - b.length());\n if(remaining > 0) {\n // parse extensions\n var exts = readVector(b, 2);\n while(exts.length() > 0) {\n msg.extensions.push({\n type: [exts.getByte(), exts.getByte()],\n data: readVector(exts, 2)\n });\n }\n\n // TODO: make extension support modular\n if(!client) {\n for(var i = 0; i < msg.extensions.length; ++i) {\n var ext = msg.extensions[i];\n\n // support SNI extension\n if(ext.type[0] === 0x00 && ext.type[1] === 0x00) {\n // get server name list\n var snl = readVector(ext.data, 2);\n while(snl.length() > 0) {\n // read server name type\n var snType = snl.getByte();\n\n // only HostName type (0x00) is known, break out if\n // another type is detected\n if(snType !== 0x00) {\n break;\n }\n\n // add host name to server name list\n c.session.extensions.server_name.serverNameList.push(\n readVector(snl, 2).getBytes());\n }\n }\n }\n }\n }\n\n // version already set, do not allow version change\n if(c.session.version) {\n if(msg.version.major !== c.session.version.major ||\n msg.version.minor !== c.session.version.minor) {\n return c.error(c, {\n message: 'TLS version change is disallowed during renegotiation.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n // get the chosen (ServerHello) cipher suite\n if(client) {\n // FIXME: should be checking configured acceptable cipher suites\n c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);\n } else {\n // get a supported preferred (ClientHello) cipher suite\n // choose the first supported cipher suite\n var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());\n while(tmp.length() > 0) {\n // FIXME: should be checking configured acceptable suites\n // cipher suites take up 2 bytes\n c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));\n if(c.session.cipherSuite !== null) {\n break;\n }\n }\n }\n\n // cipher suite not supported\n if(c.session.cipherSuite === null) {\n return c.error(c, {\n message: 'No cipher suites in common.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n },\n cipherSuite: forge.util.bytesToHex(msg.cipher_suite)\n });\n }\n\n // TODO: handle compression methods\n if(client) {\n c.session.compressionMethod = msg.compression_method;\n } else {\n // no compression\n c.session.compressionMethod = tls.CompressionMethod.none;\n }\n }\n\n return msg;\n};\n\n/**\n * Creates security parameters for the given connection based on the given\n * hello message.\n *\n * @param c the TLS connection.\n * @param msg the hello message.\n */\ntls.createSecurityParameters = function(c, msg) {\n /* Note: security params are from TLS 1.2, some values like prf_algorithm\n are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is\n used. */\n\n // TODO: handle other options from server when more supported\n\n // get client and server randoms\n var client = (c.entity === tls.ConnectionEnd.client);\n var msgRandom = msg.random.bytes();\n var cRandom = client ? c.session.sp.client_random : msgRandom;\n var sRandom = client ? msgRandom : tls.createRandom().getBytes();\n\n // create new security parameters\n c.session.sp = {\n entity: c.entity,\n prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,\n bulk_cipher_algorithm: null,\n cipher_type: null,\n enc_key_length: null,\n block_length: null,\n fixed_iv_length: null,\n record_iv_length: null,\n mac_algorithm: null,\n mac_length: null,\n mac_key_length: null,\n compression_algorithm: c.session.compressionMethod,\n pre_master_secret: null,\n master_secret: null,\n client_random: cRandom,\n server_random: sRandom\n };\n};\n\n/**\n * Called when a client receives a ServerHello record.\n *\n * When a ServerHello message will be sent:\n * The server will send this message in response to a client hello message\n * when it was able to find an acceptable set of algorithms. If it cannot\n * find such a match, it will respond with a handshake failure alert.\n *\n * uint24 length;\n * struct {\n * ProtocolVersion server_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suite;\n * CompressionMethod compression_method;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ServerHello;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // ensure server version is compatible\n if(msg.version.minor <= c.version.minor) {\n c.version.minor = msg.version.minor;\n } else {\n return c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n\n // indicate session version has been set\n c.session.version = c.version;\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // if the session ID is not blank and matches the cached one, resume\n // the session\n if(sessionId.length > 0 && sessionId === c.session.id) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = SCC;\n c.session.resuming = true;\n\n // get new server random\n c.session.sp.server_random = msg.random.bytes();\n } else {\n // not resuming, expect a server Certificate message next\n c.expect = SCE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // set new session ID\n c.session.id = sessionId;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a ClientHello record.\n *\n * When a ClientHello message will be sent:\n * When a client first connects to a server it is required to send the\n * client hello as its first message. The client can also send a client\n * hello in response to a hello request or on its own initiative in order\n * to renegotiate the security parameters in an existing connection.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // see if the given session ID is in the cache\n var session = null;\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n if(session === null) {\n // session ID not found\n sessionId = '';\n } else if(session.version.major !== msg.version.major ||\n session.version.minor > msg.version.minor) {\n // if session version is incompatible with client version, do not resume\n session = null;\n sessionId = '';\n }\n }\n\n // no session found to resume, generate a new session ID\n if(sessionId.length === 0) {\n sessionId = forge.random.getBytes(32);\n }\n\n // update session\n c.session.id = sessionId;\n c.session.clientHelloVersion = msg.version;\n c.session.sp = {};\n if(session) {\n // use version and security parameters from resumed session\n c.version = c.session.version = session.version;\n c.session.sp = session.sp;\n } else {\n // use highest compatible minor version\n var version;\n for(var i = 1; i < tls.SupportedVersions.length; ++i) {\n version = tls.SupportedVersions[i];\n if(version.minor <= msg.version.minor) {\n break;\n }\n }\n c.version = {major: version.major, minor: version.minor};\n c.session.version = c.version;\n }\n\n // if a session is set, resume it\n if(session !== null) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = CCC;\n c.session.resuming = true;\n\n // get new client random\n c.session.sp.client_random = msg.random.bytes();\n } else {\n // not resuming, expect a Certificate or ClientKeyExchange\n c.expect = (c.verifyClient !== false) ? CCE : CKE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // connection now open\n c.open = true;\n\n // queue server hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHello(c)\n }));\n\n if(c.session.resuming) {\n // queue change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // queue finished\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n } else {\n // queue server certificate\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n }));\n\n if(!c.fail) {\n // queue server key exchange\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerKeyExchange(c)\n }));\n\n // request client certificate if set\n if(c.verifyClient !== false) {\n // queue certificate request\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateRequest(c)\n }));\n }\n\n // queue server hello done\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHelloDone(c)\n }));\n }\n }\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a Certificate record.\n *\n * When this message will be sent:\n * The server must send a certificate whenever the agreed-upon key exchange\n * method is not an anonymous one. This message will always immediately\n * follow the server hello message.\n *\n * Meaning of this message:\n * The certificate type must be appropriate for the selected cipher suite's\n * key exchange algorithm, and is generally an X.509v3 certificate. It must\n * contain a key which matches the key exchange method, as follows. Unless\n * otherwise specified, the signing algorithm for the certificate must be\n * the same as the algorithm for the certificate key. Unless otherwise\n * specified, the public key may be of any length.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n * struct {\n * ASN.1Cert certificate_list<1..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificate = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid Certificate message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n certificate_list: readVector(b, 3)\n };\n\n /* The sender's certificate will be first in the list (chain), each\n subsequent one that follows will certify the previous one, but root\n certificates (self-signed) that specify the certificate authority may\n be omitted under the assumption that clients must already possess it. */\n var cert, asn1;\n var certs = [];\n try {\n while(msg.certificate_list.length() > 0) {\n // each entry in msg.certificate_list is a vector with 3 len bytes\n cert = readVector(msg.certificate_list, 3);\n asn1 = forge.asn1.fromDer(cert);\n cert = forge.pki.certificateFromAsn1(asn1, true);\n certs.push(cert);\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not parse certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n\n // ensure at least 1 certificate was provided if in client-mode\n // or if verifyClient was set to true to require a certificate\n // (as opposed to 'optional')\n var client = (c.entity === tls.ConnectionEnd.client);\n if((client || c.verifyClient === true) && certs.length === 0) {\n // error, no certificate\n c.error(c, {\n message: client ?\n 'No server certificate provided.' :\n 'No client certificate provided.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else if(certs.length === 0) {\n // no certs to verify\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n } else {\n // save certificate in session\n if(client) {\n c.session.serverCertificate = certs[0];\n } else {\n c.session.clientCertificate = certs[0];\n }\n\n if(tls.verifyCertificateChain(c, certs)) {\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerKeyExchange record.\n *\n * When this message will be sent:\n * This message will be sent immediately after the server certificate\n * message (or the server hello message, if this is an anonymous\n * negotiation).\n *\n * The server key exchange message is sent by the server only when the\n * server certificate message (if sent) does not contain enough data to\n * allow the client to exchange a premaster secret.\n *\n * Meaning of this message:\n * This message conveys cryptographic information to allow the client to\n * communicate the premaster secret: either an RSA public key to encrypt\n * the premaster secret with, or a Diffie-Hellman public key with which the\n * client can complete a key exchange (with the result being the premaster\n * secret.)\n *\n * enum {\n * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa\n * } KeyExchangeAlgorithm;\n *\n * struct {\n * opaque dh_p<1..2^16-1>;\n * opaque dh_g<1..2^16-1>;\n * opaque dh_Ys<1..2^16-1>;\n * } ServerDHParams;\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case dh_anon:\n * ServerDHParams params;\n * case dhe_dss:\n * case dhe_rsa:\n * ServerDHParams params;\n * digitally-signed struct {\n * opaque client_random[32];\n * opaque server_random[32];\n * ServerDHParams params;\n * } signed_params;\n * case rsa:\n * case dh_dss:\n * case dh_rsa:\n * struct {};\n * };\n * } ServerKeyExchange;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length > 0 is invalid\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n // expect an optional CertificateRequest message next\n c.expect = SCR;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ClientKeyExchange record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length < 48 is invalid\n if(length < 48) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n enc_pre_master_secret: readVector(b, 2).getBytes()\n };\n\n // do rsa decryption\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.serverCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n\n if(privateKey === null) {\n return c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n\n try {\n // decrypt 48-byte pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);\n\n // ensure client hello version matches first 2 bytes\n var version = c.session.clientHelloVersion;\n if(version.major !== sp.pre_master_secret.charCodeAt(0) ||\n version.minor !== sp.pre_master_secret.charCodeAt(1)) {\n // error, do not send alert (see BLEI attack below)\n throw new Error('TLS version rollback attack detected.');\n }\n } catch(ex) {\n /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a\n TLS server which is using PKCS#1 encoded RSA, so instead of\n failing here, we generate 48 random bytes and use that as\n the pre-master secret. */\n sp.pre_master_secret = forge.random.getBytes(48);\n }\n\n // expect a CertificateVerify message if a Certificate was received that\n // does not have fixed Diffie-Hellman params, otherwise expect\n // ChangeCipherSpec\n c.expect = CCC;\n if(c.session.clientCertificate !== null) {\n // only RSA support, so expect CertificateVerify\n // TODO: support Diffie-Hellman\n c.expect = CCV;\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a CertificateRequest record.\n *\n * When this message will be sent:\n * A non-anonymous server can optionally request a certificate from the\n * client, if appropriate for the selected cipher suite. This message, if\n * sent, will immediately follow the Server Key Exchange message (if it is\n * sent; otherwise, the Server Certificate message).\n *\n * enum {\n * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),\n * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),\n * fortezza_dms_RESERVED(20), (255)\n * } ClientCertificateType;\n *\n * opaque DistinguishedName<1..2^16-1>;\n *\n * struct {\n * ClientCertificateType certificate_types<1..2^8-1>;\n * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>;\n * DistinguishedName certificate_authorities<0..2^16-1>;\n * } CertificateRequest;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateRequest = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid CertificateRequest. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // TODO: TLS 1.2+ has different format including\n // SignatureAndHashAlgorithm after cert types\n var b = record.fragment;\n var msg = {\n certificate_types: readVector(b, 1),\n certificate_authorities: readVector(b, 2)\n };\n\n // save certificate request in session\n c.session.certificateRequest = msg;\n\n // expect a ServerHelloDone message next\n c.expect = SHD;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a CertificateVerify record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateVerify = function(c, record, length) {\n if(length < 2) {\n return c.error(c, {\n message: 'Invalid CertificateVerify. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for CertificateVerify messages because\n // they must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n var msg = {\n signature: readVector(b, 2).getBytes()\n };\n\n // TODO: add support for DSA\n\n // generate data to verify\n var verify = forge.util.createBuffer();\n verify.putBuffer(c.session.md5.digest());\n verify.putBuffer(c.session.sha1.digest());\n verify = verify.getBytes();\n\n try {\n var cert = c.session.clientCertificate;\n /*b = forge.pki.rsa.decrypt(\n msg.signature, cert.publicKey, true, verify.length);\n if(b !== verify) {*/\n if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) {\n throw new Error('CertificateVerify signature does not match.');\n }\n\n // digest message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n } catch(ex) {\n return c.error(c, {\n message: 'Bad signature in CertificateVerify.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n }\n });\n }\n\n // expect ChangeCipherSpec\n c.expect = CCC;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerHelloDone record.\n *\n * When this message will be sent:\n * The server hello done message is sent by the server to indicate the end\n * of the server hello and associated messages. After sending this message\n * the server will wait for a client response.\n *\n * Meaning of this message:\n * This message means that the server is done sending messages to support\n * the key exchange, and the client can proceed with its phase of the key\n * exchange.\n *\n * Upon receipt of the server hello done message the client should verify\n * that the server provided a valid certificate if required and check that\n * the server hello parameters are acceptable.\n *\n * struct {} ServerHelloDone;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHelloDone = function(c, record, length) {\n // len must be 0 bytes\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid ServerHelloDone message. Invalid length.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.record_overflow\n }\n });\n }\n\n if(c.serverCertificate === null) {\n // no server certificate was provided\n var error = {\n message: 'No server certificate provided. Not enough security.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.insufficient_security\n }\n };\n\n // call application callback\n var depth = 0;\n var ret = c.verify(c, error.alert.description, depth, []);\n if(ret !== true) {\n // check for custom alert info\n if(ret || ret === 0) {\n // set custom message and alert description\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n } else if(typeof ret === 'number') {\n // set custom alert description\n error.alert.description = ret;\n }\n }\n\n // send error\n return c.error(c, error);\n }\n }\n\n // create client certificate message if requested\n if(c.session.certificateRequest !== null) {\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n });\n tls.queue(c, record);\n }\n\n // create client key exchange message\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientKeyExchange(c)\n });\n tls.queue(c, record);\n\n // expect no messages until the following callback has been called\n c.expect = SER;\n\n // create callback to handle client signature (for client-certs)\n var callback = function(c, signature) {\n if(c.session.certificateRequest !== null &&\n c.session.clientCertificate !== null) {\n // create certificate verify message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateVerify(c, signature)\n }));\n }\n\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n\n // expect a server ChangeCipherSpec message next\n c.expect = SCC;\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n };\n\n // if there is no certificate request or no client certificate, do\n // callback immediately\n if(c.session.certificateRequest === null ||\n c.session.clientCertificate === null) {\n return callback(c, null);\n }\n\n // otherwise get the client signature\n tls.getClientSignature(c, callback);\n};\n\n/**\n * Called when a ChangeCipherSpec record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleChangeCipherSpec = function(c, record) {\n if(record.fragment.getByte() !== 0x01) {\n return c.error(c, {\n message: 'Invalid ChangeCipherSpec message received.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // create pending state if:\n // 1. Resuming session in client mode OR\n // 2. NOT resuming session in server mode\n var client = (c.entity === tls.ConnectionEnd.client);\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n c.state.pending = tls.createConnectionState(c);\n }\n\n // change current read state to pending read state\n c.state.current.read = c.state.pending.read;\n\n // clear pending state if:\n // 1. NOT resuming session in client mode OR\n // 2. resuming a session in server mode\n if((!c.session.resuming && client) || (c.session.resuming && !client)) {\n c.state.pending = null;\n }\n\n // expect a Finished record next\n c.expect = client ? SFI : CFI;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Finished record is received.\n *\n * When this message will be sent:\n * A finished message is always sent immediately after a change\n * cipher spec message to verify that the key exchange and\n * authentication processes were successful. It is essential that a\n * change cipher spec message be received between the other\n * handshake messages and the Finished message.\n *\n * Meaning of this message:\n * The finished message is the first protected with the just-\n * negotiated algorithms, keys, and secrets. Recipients of finished\n * messages must verify that the contents are correct. Once a side\n * has sent its Finished message and received and validated the\n * Finished message from its peer, it may begin to send and receive\n * application data over the connection.\n *\n * struct {\n * opaque verify_data[verify_data_length];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, Hash(handshake_messages))\n * [0..verify_data_length-1];\n *\n * finished_label\n * For Finished messages sent by the client, the string\n * \"client finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * verify_data_length depends on the cipher suite. If it is not specified\n * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used\n * 12 bytes.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleFinished = function(c, record, length) {\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for Finished messages because they\n // must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n // message contains only verify_data\n var vd = record.fragment.getBytes();\n\n // ensure verify data is correct\n b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // set label based on entity type\n var client = (c.entity === tls.ConnectionEnd.client);\n var label = client ? 'server finished' : 'client finished';\n\n // TODO: determine prf function and verify length for TLS 1.2\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n if(b.getBytes() !== vd) {\n return c.error(c, {\n message: 'Invalid verify_data in Finished message.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decrypt_error\n }\n });\n }\n\n // digest finished message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n\n // resuming session as client or NOT resuming session as server\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // change current write state to pending write state, clear pending\n c.state.current.write = c.state.pending.write;\n c.state.pending = null;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n }\n\n // expect application data next\n c.expect = client ? SAD : CAD;\n\n // handshake complete\n c.handshaking = false;\n ++c.handshakes;\n\n // save access to peer certificate\n c.peerCertificate = client ?\n c.session.serverCertificate : c.session.clientCertificate;\n\n // send records\n tls.flush(c);\n\n // now connected\n c.isConnected = true;\n c.connected(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when an Alert record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleAlert = function(c, record) {\n // read alert\n var b = record.fragment;\n var alert = {\n level: b.getByte(),\n description: b.getByte()\n };\n\n // TODO: consider using a table?\n // get appropriate message\n var msg;\n switch(alert.description) {\n case tls.Alert.Description.close_notify:\n msg = 'Connection closed.';\n break;\n case tls.Alert.Description.unexpected_message:\n msg = 'Unexpected message.';\n break;\n case tls.Alert.Description.bad_record_mac:\n msg = 'Bad record MAC.';\n break;\n case tls.Alert.Description.decryption_failed:\n msg = 'Decryption failed.';\n break;\n case tls.Alert.Description.record_overflow:\n msg = 'Record overflow.';\n break;\n case tls.Alert.Description.decompression_failure:\n msg = 'Decompression failed.';\n break;\n case tls.Alert.Description.handshake_failure:\n msg = 'Handshake failure.';\n break;\n case tls.Alert.Description.bad_certificate:\n msg = 'Bad certificate.';\n break;\n case tls.Alert.Description.unsupported_certificate:\n msg = 'Unsupported certificate.';\n break;\n case tls.Alert.Description.certificate_revoked:\n msg = 'Certificate revoked.';\n break;\n case tls.Alert.Description.certificate_expired:\n msg = 'Certificate expired.';\n break;\n case tls.Alert.Description.certificate_unknown:\n msg = 'Certificate unknown.';\n break;\n case tls.Alert.Description.illegal_parameter:\n msg = 'Illegal parameter.';\n break;\n case tls.Alert.Description.unknown_ca:\n msg = 'Unknown certificate authority.';\n break;\n case tls.Alert.Description.access_denied:\n msg = 'Access denied.';\n break;\n case tls.Alert.Description.decode_error:\n msg = 'Decode error.';\n break;\n case tls.Alert.Description.decrypt_error:\n msg = 'Decrypt error.';\n break;\n case tls.Alert.Description.export_restriction:\n msg = 'Export restriction.';\n break;\n case tls.Alert.Description.protocol_version:\n msg = 'Unsupported protocol version.';\n break;\n case tls.Alert.Description.insufficient_security:\n msg = 'Insufficient security.';\n break;\n case tls.Alert.Description.internal_error:\n msg = 'Internal error.';\n break;\n case tls.Alert.Description.user_canceled:\n msg = 'User canceled.';\n break;\n case tls.Alert.Description.no_renegotiation:\n msg = 'Renegotiation not supported.';\n break;\n default:\n msg = 'Unknown error.';\n break;\n }\n\n // close connection on close_notify, not an error\n if(alert.description === tls.Alert.Description.close_notify) {\n return c.close();\n }\n\n // call error handler\n c.error(c, {\n message: msg,\n send: false,\n // origin is the opposite end\n origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client',\n alert: alert\n });\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Handshake record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHandshake = function(c, record) {\n // get the handshake type and message length\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt24();\n\n // see if the record fragment doesn't yet contain the full message\n if(length > b.length()) {\n // cache the record, clear its fragment, and reset the buffer read\n // pointer before the type and length were read\n c.fragmented = record;\n record.fragment = forge.util.createBuffer();\n b.read -= 4;\n\n // continue\n return c.process();\n }\n\n // full message now available, clear cache, reset read pointer to\n // before type and length\n c.fragmented = null;\n b.read -= 4;\n\n // save the handshake bytes for digestion after handler is found\n // (include type and length of handshake msg)\n var bytes = b.bytes(length + 4);\n\n // restore read pointer\n b.read += 4;\n\n // handle expected message\n if(type in hsTable[c.entity][c.expect]) {\n // initialize server session\n if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) {\n c.handshaking = true;\n c.session = {\n version: null,\n extensions: {\n server_name: {\n serverNameList: []\n }\n },\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n clientCertificate: null,\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n }\n\n /* Update handshake messages digest. Finished and CertificateVerify\n messages are not digested here. They can't be digested as part of\n the verify_data that they contain. These messages are manually\n digested in their handlers. HelloRequest messages are simply never\n included in the handshake message digest according to spec. */\n if(type !== tls.HandshakeType.hello_request &&\n type !== tls.HandshakeType.certificate_verify &&\n type !== tls.HandshakeType.finished) {\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n }\n\n // handle specific handshake type record\n hsTable[c.entity][c.expect][type](c, record, length);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n};\n\n/**\n * Called when an ApplicationData record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleApplicationData = function(c, record) {\n // buffer data, notify that its ready\n c.data.putBuffer(record.fragment);\n c.dataReady(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Heartbeat record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHeartbeat = function(c, record) {\n // get the heartbeat type and payload\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt16();\n var payload = b.getBytes(length);\n\n if(type === tls.HeartbeatMessageType.heartbeat_request) {\n // discard request during handshake or if length is too large\n if(c.handshaking || length > payload.length) {\n // continue\n return c.process();\n }\n // retransmit payload\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_response, payload)\n }));\n tls.flush(c);\n } else if(type === tls.HeartbeatMessageType.heartbeat_response) {\n // check payload against expected payload, discard heartbeat if no match\n if(payload !== c.expectedHeartbeatPayload) {\n // continue\n return c.process();\n }\n\n // notify that a valid heartbeat was received\n if(c.heartbeatReceived) {\n c.heartbeatReceived(c, forge.util.createBuffer(payload));\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * The transistional state tables for receiving TLS records. It maps the\n * current TLS engine state and a received record to a function to handle the\n * record and update the state.\n *\n * For instance, if the current state is SHE, then the TLS engine is expecting\n * a ServerHello record. Once a record is received, the handler function is\n * looked up using the state SHE and the record's content type.\n *\n * The resulting function will either be an error handler or a record handler.\n * The function will take whatever action is appropriate and update the state\n * for the next record.\n *\n * The states are all based on possible server record types. Note that the\n * client will never specifically expect to receive a HelloRequest or an alert\n * from the server so there is no state that reflects this. These messages may\n * occur at any time.\n *\n * There are two tables for mapping states because there is a second tier of\n * types for handshake messages. Once a record with a content type of handshake\n * is received, the handshake record handler will look up the handshake type in\n * the secondary map to get its appropriate handler.\n *\n * Valid message orders are as follows:\n *\n * =======================FULL HANDSHAKE======================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * Certificate*\n * ServerKeyExchange*\n * CertificateRequest*\n * <-------- ServerHelloDone\n * Certificate*\n * ClientKeyExchange\n * CertificateVerify*\n * [ChangeCipherSpec]\n * Finished -------->\n * [ChangeCipherSpec]\n * <-------- Finished\n * Application Data <-------> Application Data\n *\n * =====================SESSION RESUMPTION=====================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * [ChangeCipherSpec]\n * <-------- Finished\n * [ChangeCipherSpec]\n * Finished -------->\n * Application Data <-------> Application Data\n */\n// client expect states (indicate which records are expected to be received)\nvar SHE = 0; // rcv server hello\nvar SCE = 1; // rcv server certificate\nvar SKE = 2; // rcv server key exchange\nvar SCR = 3; // rcv certificate request\nvar SHD = 4; // rcv server hello done\nvar SCC = 5; // rcv change cipher spec\nvar SFI = 6; // rcv finished\nvar SAD = 7; // rcv application data\nvar SER = 8; // not expecting any messages at this point\n\n// server expect states\nvar CHE = 0; // rcv client hello\nvar CCE = 1; // rcv client certificate\nvar CKE = 2; // rcv client key exchange\nvar CCV = 3; // rcv certificate verify\nvar CCC = 4; // rcv change cipher spec\nvar CFI = 5; // rcv finished\nvar CAD = 6; // rcv application data\nvar CER = 7; // not expecting any messages at this point\n\n// map client current expect state and content type to function\nvar __ = tls.handleUnexpected;\nvar R0 = tls.handleChangeCipherSpec;\nvar R1 = tls.handleAlert;\nvar R2 = tls.handleHandshake;\nvar R3 = tls.handleApplicationData;\nvar R4 = tls.handleHeartbeat;\nvar ctTable = [];\nctTable[tls.ConnectionEnd.client] = [\n// CC,AL,HS,AD,HB\n/*SHE*/[__,R1,R2,__,R4],\n/*SCE*/[__,R1,R2,__,R4],\n/*SKE*/[__,R1,R2,__,R4],\n/*SCR*/[__,R1,R2,__,R4],\n/*SHD*/[__,R1,R2,__,R4],\n/*SCC*/[R0,R1,__,__,R4],\n/*SFI*/[__,R1,R2,__,R4],\n/*SAD*/[__,R1,R2,R3,R4],\n/*SER*/[__,R1,R2,__,R4]\n];\n\n// map server current expect state and content type to function\nctTable[tls.ConnectionEnd.server] = [\n// CC,AL,HS,AD\n/*CHE*/[__,R1,R2,__,R4],\n/*CCE*/[__,R1,R2,__,R4],\n/*CKE*/[__,R1,R2,__,R4],\n/*CCV*/[__,R1,R2,__,R4],\n/*CCC*/[R0,R1,__,__,R4],\n/*CFI*/[__,R1,R2,__,R4],\n/*CAD*/[__,R1,R2,R3,R4],\n/*CER*/[__,R1,R2,__,R4]\n];\n\n// map client current expect state and handshake type to function\nvar H0 = tls.handleHelloRequest;\nvar H1 = tls.handleServerHello;\nvar H2 = tls.handleCertificate;\nvar H3 = tls.handleServerKeyExchange;\nvar H4 = tls.handleCertificateRequest;\nvar H5 = tls.handleServerHelloDone;\nvar H6 = tls.handleFinished;\nvar hsTable = [];\nhsTable[tls.ConnectionEnd.client] = [\n// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI\n/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],\n/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],\n/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],\n/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],\n/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n// map server current expect state and handshake type to function\n// Note: CAD[CH] does not map to FB because renegotation is prohibited\nvar H7 = tls.handleClientHello;\nvar H8 = tls.handleClientKeyExchange;\nvar H9 = tls.handleCertificateVerify;\nhsTable[tls.ConnectionEnd.server] = [\n// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI\n/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],\n/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],\n/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],\n/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n/**\n * Generates the master_secret and keys using the given security parameters.\n *\n * The security parameters for a TLS connection state are defined as such:\n *\n * struct {\n * ConnectionEnd entity;\n * PRFAlgorithm prf_algorithm;\n * BulkCipherAlgorithm bulk_cipher_algorithm;\n * CipherType cipher_type;\n * uint8 enc_key_length;\n * uint8 block_length;\n * uint8 fixed_iv_length;\n * uint8 record_iv_length;\n * MACAlgorithm mac_algorithm;\n * uint8 mac_length;\n * uint8 mac_key_length;\n * CompressionMethod compression_algorithm;\n * opaque master_secret[48];\n * opaque client_random[32];\n * opaque server_random[32];\n * } SecurityParameters;\n *\n * Note that this definition is from TLS 1.2. In TLS 1.0 some of these\n * parameters are ignored because, for instance, the PRFAlgorithm is a\n * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0.\n *\n * The Record Protocol requires an algorithm to generate keys required by the\n * current connection state.\n *\n * The master secret is expanded into a sequence of secure bytes, which is then\n * split to a client write MAC key, a server write MAC key, a client write\n * encryption key, and a server write encryption key. In TLS 1.0 a client write\n * IV and server write IV are also generated. Each of these is generated from\n * the byte sequence in that order. Unused values are empty. In TLS 1.2, some\n * AEAD ciphers may additionally require a client write IV and a server write\n * IV (see Section 6.2.3.3).\n *\n * When keys, MAC keys, and IVs are generated, the master secret is used as an\n * entropy source.\n *\n * To generate the key material, compute:\n *\n * master_secret = PRF(pre_master_secret, \"master secret\",\n * ClientHello.random + ServerHello.random)\n *\n * key_block = PRF(SecurityParameters.master_secret,\n * \"key expansion\",\n * SecurityParameters.server_random +\n * SecurityParameters.client_random);\n *\n * until enough output has been generated. Then, the key_block is\n * partitioned as follows:\n *\n * client_write_MAC_key[SecurityParameters.mac_key_length]\n * server_write_MAC_key[SecurityParameters.mac_key_length]\n * client_write_key[SecurityParameters.enc_key_length]\n * server_write_key[SecurityParameters.enc_key_length]\n * client_write_IV[SecurityParameters.fixed_iv_length]\n * server_write_IV[SecurityParameters.fixed_iv_length]\n *\n * In TLS 1.2, the client_write_IV and server_write_IV are only generated for\n * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This\n * implementation uses TLS 1.0 so IVs are generated.\n *\n * Implementation note: The currently defined cipher suite which requires the\n * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32\n * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also\n * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material.\n *\n * @param c the connection.\n * @param sp the security parameters to use.\n *\n * @return the security keys.\n */\ntls.generateKeys = function(c, sp) {\n // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) &\n // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented\n // at present\n\n // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with\n // TLS 1.0 but we don't care right now because AES is better and we have\n // an implementation for it\n\n // TODO: TLS 1.2 implementation\n /*\n // determine the PRF\n var prf;\n switch(sp.prf_algorithm) {\n case tls.PRFAlgorithm.tls_prf_sha256:\n prf = prf_sha256;\n break;\n default:\n // should never happen\n throw new Error('Invalid PRF');\n }\n */\n\n // TLS 1.0/1.1 implementation\n var prf = prf_TLS1;\n\n // concatenate server and client random\n var random = sp.client_random + sp.server_random;\n\n // only create master secret if session is new\n if(!c.session.resuming) {\n // create master secret, clean up pre-master secret\n sp.master_secret = prf(\n sp.pre_master_secret, 'master secret', random, 48).bytes();\n sp.pre_master_secret = null;\n }\n\n // generate the amount of key material needed\n random = sp.server_random + sp.client_random;\n var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;\n\n // include IV for TLS/1.0\n var tls10 = (c.version.major === tls.Versions.TLS_1_0.major &&\n c.version.minor === tls.Versions.TLS_1_0.minor);\n if(tls10) {\n length += 2 * sp.fixed_iv_length;\n }\n var km = prf(sp.master_secret, 'key expansion', random, length);\n\n // split the key material into the MAC and encryption keys\n var rval = {\n client_write_MAC_key: km.getBytes(sp.mac_key_length),\n server_write_MAC_key: km.getBytes(sp.mac_key_length),\n client_write_key: km.getBytes(sp.enc_key_length),\n server_write_key: km.getBytes(sp.enc_key_length)\n };\n\n // include TLS 1.0 IVs\n if(tls10) {\n rval.client_write_IV = km.getBytes(sp.fixed_iv_length);\n rval.server_write_IV = km.getBytes(sp.fixed_iv_length);\n }\n\n return rval;\n};\n\n/**\n * Creates a new initialized TLS connection state. A connection state has\n * a read mode and a write mode.\n *\n * compression state:\n * The current state of the compression algorithm.\n *\n * cipher state:\n * The current state of the encryption algorithm. This will consist of the\n * scheduled key for that connection. For stream ciphers, this will also\n * contain whatever state information is necessary to allow the stream to\n * continue to encrypt or decrypt data.\n *\n * MAC key:\n * The MAC key for the connection.\n *\n * sequence number:\n * Each connection state contains a sequence number, which is maintained\n * separately for read and write states. The sequence number MUST be set to\n * zero whenever a connection state is made the active state. Sequence\n * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do\n * not wrap. If a TLS implementation would need to wrap a sequence number,\n * it must renegotiate instead. A sequence number is incremented after each\n * record: specifically, the first record transmitted under a particular\n * connection state MUST use sequence number 0.\n *\n * @param c the connection.\n *\n * @return the new initialized TLS connection state.\n */\ntls.createConnectionState = function(c) {\n var client = (c.entity === tls.ConnectionEnd.client);\n\n var createMode = function() {\n var mode = {\n // two 32-bit numbers, first is most significant\n sequenceNumber: [0, 0],\n macKey: null,\n macLength: 0,\n macFunction: null,\n cipherState: null,\n cipherFunction: function(record) {return true;},\n compressionState: null,\n compressFunction: function(record) {return true;},\n updateSequenceNumber: function() {\n if(mode.sequenceNumber[1] === 0xFFFFFFFF) {\n mode.sequenceNumber[1] = 0;\n ++mode.sequenceNumber[0];\n } else {\n ++mode.sequenceNumber[1];\n }\n }\n };\n return mode;\n };\n var state = {\n read: createMode(),\n write: createMode()\n };\n\n // update function in read mode will decrypt then decompress a record\n state.read.update = function(c, record) {\n if(!state.read.cipherFunction(record, state.read)) {\n c.error(c, {\n message: 'Could not decrypt record or bad MAC.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n // doesn't matter if decryption failed or MAC was\n // invalid, return the same error so as not to reveal\n // which one occurred\n description: tls.Alert.Description.bad_record_mac\n }\n });\n } else if(!state.read.compressFunction(c, record, state.read)) {\n c.error(c, {\n message: 'Could not decompress record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decompression_failure\n }\n });\n }\n return !c.fail;\n };\n\n // update function in write mode will compress then encrypt a record\n state.write.update = function(c, record) {\n if(!state.write.compressFunction(c, record, state.write)) {\n // error, but do not send alert since it would require\n // compression as well\n c.error(c, {\n message: 'Could not compress record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else if(!state.write.cipherFunction(record, state.write)) {\n // error, but do not send alert since it would require\n // encryption as well\n c.error(c, {\n message: 'Could not encrypt record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n return !c.fail;\n };\n\n // handle security parameters\n if(c.session) {\n var sp = c.session.sp;\n c.session.cipherSuite.initSecurityParameters(sp);\n\n // generate keys\n sp.keys = tls.generateKeys(c, sp);\n state.read.macKey = client ?\n sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;\n state.write.macKey = client ?\n sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;\n\n // cipher suite setup\n c.session.cipherSuite.initConnectionState(state, c, sp);\n\n // compression setup\n switch(sp.compression_algorithm) {\n case tls.CompressionMethod.none:\n break;\n case tls.CompressionMethod.deflate:\n state.read.compressFunction = inflate;\n state.write.compressFunction = deflate;\n break;\n default:\n throw new Error('Unsupported compression algorithm.');\n }\n }\n\n return state;\n};\n\n/**\n * Creates a Random structure.\n *\n * struct {\n * uint32 gmt_unix_time;\n * opaque random_bytes[28];\n * } Random;\n *\n * gmt_unix_time:\n * The current time and date in standard UNIX 32-bit format (seconds since\n * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according\n * to the sender's internal clock. Clocks are not required to be set\n * correctly by the basic TLS protocol; higher-level or application\n * protocols may define additional requirements. Note that, for historical\n * reasons, the data element is named using GMT, the predecessor of the\n * current worldwide time base, UTC.\n * random_bytes:\n * 28 bytes generated by a secure random number generator.\n *\n * @return the Random structure as a byte array.\n */\ntls.createRandom = function() {\n // get UTC milliseconds\n var d = new Date();\n var utc = +d + d.getTimezoneOffset() * 60000;\n var rval = forge.util.createBuffer();\n rval.putInt32(utc);\n rval.putBytes(forge.random.getBytes(28));\n return rval;\n};\n\n/**\n * Creates a TLS record with the given type and data.\n *\n * @param c the connection.\n * @param options:\n * type: the record type.\n * data: the plain text data in a byte buffer.\n *\n * @return the created record.\n */\ntls.createRecord = function(c, options) {\n if(!options.data) {\n return null;\n }\n var record = {\n type: options.type,\n version: {\n major: c.version.major,\n minor: c.version.minor\n },\n length: options.data.length(),\n fragment: options.data\n };\n return record;\n};\n\n/**\n * Creates a TLS alert record.\n *\n * @param c the connection.\n * @param alert:\n * level: the TLS alert level.\n * description: the TLS alert description.\n *\n * @return the created alert record.\n */\ntls.createAlert = function(c, alert) {\n var b = forge.util.createBuffer();\n b.putByte(alert.level);\n b.putByte(alert.description);\n return tls.createRecord(c, {\n type: tls.ContentType.alert,\n data: b\n });\n};\n\n/* The structure of a TLS handshake message.\n *\n * struct {\n * HandshakeType msg_type; // handshake type\n * uint24 length; // bytes in message\n * select(HandshakeType) {\n * case hello_request: HelloRequest;\n * case client_hello: ClientHello;\n * case server_hello: ServerHello;\n * case certificate: Certificate;\n * case server_key_exchange: ServerKeyExchange;\n * case certificate_request: CertificateRequest;\n * case server_hello_done: ServerHelloDone;\n * case certificate_verify: CertificateVerify;\n * case client_key_exchange: ClientKeyExchange;\n * case finished: Finished;\n * } body;\n * } Handshake;\n */\n\n/**\n * Creates a ClientHello message.\n *\n * opaque SessionID<0..32>;\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n * uint8 CipherSuite[2];\n *\n * struct {\n * ProtocolVersion client_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suites<2..2^16-2>;\n * CompressionMethod compression_methods<1..2^8-1>;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ClientHello;\n *\n * The extension format for extended client hellos and server hellos is:\n *\n * struct {\n * ExtensionType extension_type;\n * opaque extension_data<0..2^16-1>;\n * } Extension;\n *\n * Here:\n *\n * - \"extension_type\" identifies the particular extension type.\n * - \"extension_data\" contains information specific to the particular\n * extension type.\n *\n * The extension types defined in this document are:\n *\n * enum {\n * server_name(0), max_fragment_length(1),\n * client_certificate_url(2), trusted_ca_keys(3),\n * truncated_hmac(4), status_request(5), (65535)\n * } ExtensionType;\n *\n * @param c the connection.\n *\n * @return the ClientHello byte buffer.\n */\ntls.createClientHello = function(c) {\n // save hello version\n c.session.clientHelloVersion = {\n major: c.version.major,\n minor: c.version.minor\n };\n\n // create supported cipher suites\n var cipherSuites = forge.util.createBuffer();\n for(var i = 0; i < c.cipherSuites.length; ++i) {\n var cs = c.cipherSuites[i];\n cipherSuites.putByte(cs.id[0]);\n cipherSuites.putByte(cs.id[1]);\n }\n var cSuites = cipherSuites.length();\n\n // create supported compression methods, null always supported, but\n // also support deflate if connection has inflate and deflate methods\n var compressionMethods = forge.util.createBuffer();\n compressionMethods.putByte(tls.CompressionMethod.none);\n // FIXME: deflate support disabled until issues with raw deflate data\n // without zlib headers are resolved\n /*\n if(c.inflate !== null && c.deflate !== null) {\n compressionMethods.putByte(tls.CompressionMethod.deflate);\n }\n */\n var cMethods = compressionMethods.length();\n\n // create TLS SNI (server name indication) extension if virtual host\n // has been specified, see RFC 3546\n var extensions = forge.util.createBuffer();\n if(c.virtualHost) {\n // create extension struct\n var ext = forge.util.createBuffer();\n ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes)\n ext.putByte(0x00);\n\n /* In order to provide the server name, clients MAY include an\n * extension of type \"server_name\" in the (extended) client hello.\n * The \"extension_data\" field of this extension SHALL contain\n * \"ServerNameList\" where:\n *\n * struct {\n * NameType name_type;\n * select(name_type) {\n * case host_name: HostName;\n * } name;\n * } ServerName;\n *\n * enum {\n * host_name(0), (255)\n * } NameType;\n *\n * opaque HostName<1..2^16-1>;\n *\n * struct {\n * ServerName server_name_list<1..2^16-1>\n * } ServerNameList;\n */\n var serverName = forge.util.createBuffer();\n serverName.putByte(0x00); // type host_name\n writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost));\n\n // ServerNameList is in extension_data\n var snList = forge.util.createBuffer();\n writeVector(snList, 2, serverName);\n writeVector(ext, 2, snList);\n extensions.putBuffer(ext);\n }\n var extLength = extensions.length();\n if(extLength > 0) {\n // add extension vector length\n extLength += 2;\n }\n\n // determine length of the handshake message\n // cipher suites and compression methods size will need to be\n // updated if more get added to the list\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + cSuites + // cipher suites vector\n 1 + cMethods + // compression methods vector\n extLength; // extensions vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.client_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n writeVector(rval, 2, cipherSuites);\n writeVector(rval, 1, compressionMethods);\n if(extLength > 0) {\n writeVector(rval, 2, extensions);\n }\n return rval;\n};\n\n/**\n * Creates a ServerHello message.\n *\n * @param c the connection.\n *\n * @return the ServerHello byte buffer.\n */\ntls.createServerHello = function(c) {\n // determine length of the handshake message\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + // chosen cipher suite\n 1; // chosen compression method\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.server_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n rval.putByte(c.session.cipherSuite.id[0]);\n rval.putByte(c.session.cipherSuite.id[1]);\n rval.putByte(c.session.compressionMethod);\n return rval;\n};\n\n/**\n * Creates a Certificate message.\n *\n * When this message will be sent:\n * This is the first message the client can send after receiving a server\n * hello done message and the first message the server can send after\n * sending a ServerHello. This client message is only sent if the server\n * requests a certificate. If no suitable certificate is available, the\n * client should send a certificate message containing no certificates. If\n * client authentication is required by the server for the handshake to\n * continue, it may respond with a fatal handshake failure alert.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n *\n * struct {\n * ASN.1Cert certificate_list<0..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n *\n * @return the Certificate byte buffer.\n */\ntls.createCertificate = function(c) {\n // TODO: check certificate request to ensure types are supported\n\n // get a certificate (a certificate as a PEM string)\n var client = (c.entity === tls.ConnectionEnd.client);\n var cert = null;\n if(c.getCertificate) {\n var hint;\n if(client) {\n hint = c.session.certificateRequest;\n } else {\n hint = c.session.extensions.server_name.serverNameList;\n }\n cert = c.getCertificate(c, hint);\n }\n\n // buffer to hold certificate list\n var certList = forge.util.createBuffer();\n if(cert !== null) {\n try {\n // normalize cert to a chain of certificates\n if(!forge.util.isArray(cert)) {\n cert = [cert];\n }\n var asn1 = null;\n for(var i = 0; i < cert.length; ++i) {\n var msg = forge.pem.decode(cert[i])[0];\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error('Could not convert certificate from PEM; PEM ' +\n 'header type is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or ' +\n '\"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n var der = forge.util.createBuffer(msg.body);\n if(asn1 === null) {\n asn1 = forge.asn1.fromDer(der.bytes(), false);\n }\n\n // certificate entry is itself a vector with 3 length bytes\n var certBuffer = forge.util.createBuffer();\n writeVector(certBuffer, 3, der);\n\n // add cert vector to cert list vector\n certList.putBuffer(certBuffer);\n }\n\n // save certificate\n cert = forge.pki.certificateFromAsn1(asn1);\n if(client) {\n c.session.clientCertificate = cert;\n } else {\n c.session.serverCertificate = cert;\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not send certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n }\n\n // determine length of the handshake message\n var length = 3 + certList.length(); // cert list vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate);\n rval.putInt24(length);\n writeVector(rval, 3, certList);\n return rval;\n};\n\n/**\n * Creates a ClientKeyExchange message.\n *\n * When this message will be sent:\n * This message is always sent by the client. It will immediately follow the\n * client certificate message, if it is sent. Otherwise it will be the first\n * message sent by the client after it receives the server hello done\n * message.\n *\n * Meaning of this message:\n * With this message, the premaster secret is set, either though direct\n * transmission of the RSA-encrypted secret, or by the transmission of\n * Diffie-Hellman parameters which will allow each side to agree upon the\n * same premaster secret. When the key exchange method is DH_RSA or DH_DSS,\n * client certification has been requested, and the client was able to\n * respond with a certificate which contained a Diffie-Hellman public key\n * whose parameters (group and generator) matched those specified by the\n * server in its certificate, this message will not contain any data.\n *\n * Meaning of this message:\n * If RSA is being used for key agreement and authentication, the client\n * generates a 48-byte premaster secret, encrypts it using the public key\n * from the server's certificate or the temporary RSA key provided in a\n * server key exchange message, and sends the result in an encrypted\n * premaster secret message. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case rsa: EncryptedPreMasterSecret;\n * case diffie_hellman: ClientDiffieHellmanPublic;\n * } exchange_keys;\n * } ClientKeyExchange;\n *\n * struct {\n * ProtocolVersion client_version;\n * opaque random[46];\n * } PreMasterSecret;\n *\n * struct {\n * public-key-encrypted PreMasterSecret pre_master_secret;\n * } EncryptedPreMasterSecret;\n *\n * A public-key-encrypted element is encoded as a vector <0..2^16-1>.\n *\n * @param c the connection.\n *\n * @return the ClientKeyExchange byte buffer.\n */\ntls.createClientKeyExchange = function(c) {\n // create buffer to encrypt\n var b = forge.util.createBuffer();\n\n // add highest client-supported protocol to help server avoid version\n // rollback attacks\n b.putByte(c.session.clientHelloVersion.major);\n b.putByte(c.session.clientHelloVersion.minor);\n\n // generate and add 46 random bytes\n b.putBytes(forge.random.getBytes(46));\n\n // save pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = b.getBytes();\n\n // RSA-encrypt the pre-master secret\n var key = c.session.serverCertificate.publicKey;\n b = key.encrypt(sp.pre_master_secret);\n\n /* Note: The encrypted pre-master secret will be stored in a\n public-key-encrypted opaque vector that has the length prefixed using\n 2 bytes, so include those 2 bytes in the handshake message length. This\n is done as a minor optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = b.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_key_exchange);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(b.length);\n rval.putBytes(b);\n return rval;\n};\n\n/**\n * Creates a ServerKeyExchange message.\n *\n * @param c the connection.\n *\n * @return the ServerKeyExchange byte buffer.\n */\ntls.createServerKeyExchange = function(c) {\n // this implementation only supports RSA, no Diffie-Hellman support,\n // so this record is empty\n\n // determine length of the handshake message\n var length = 0;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n if(length > 0) {\n rval.putByte(tls.HandshakeType.server_key_exchange);\n rval.putInt24(length);\n }\n return rval;\n};\n\n/**\n * Gets the signed data used to verify a client-side certificate. See\n * tls.createCertificateVerify() for details.\n *\n * @param c the connection.\n * @param callback the callback to call once the signed data is ready.\n */\ntls.getClientSignature = function(c, callback) {\n // generate data to RSA encrypt\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n b = b.getBytes();\n\n // create default signing function as necessary\n c.getSignature = c.getSignature || function(c, b, callback) {\n // do rsa encryption, call callback\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.clientCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n if(privateKey === null) {\n c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else {\n b = privateKey.sign(b, null);\n }\n callback(c, b);\n };\n\n // get client signature\n c.getSignature(c, b, callback);\n};\n\n/**\n * Creates a CertificateVerify message.\n *\n * Meaning of this message:\n * This structure conveys the client's Diffie-Hellman public value\n * (Yc) if it was not already included in the client's certificate.\n * The encoding used for Yc is determined by the enumerated\n * PublicValueEncoding. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * When this message will be sent:\n * This message is used to provide explicit verification of a client\n * certificate. This message is only sent following a client\n * certificate that has signing capability (i.e. all certificates\n * except those containing fixed Diffie-Hellman parameters). When\n * sent, it will immediately follow the client key exchange message.\n *\n * struct {\n * Signature signature;\n * } CertificateVerify;\n *\n * CertificateVerify.signature.md5_hash\n * MD5(handshake_messages);\n *\n * Certificate.signature.sha_hash\n * SHA(handshake_messages);\n *\n * Here handshake_messages refers to all handshake messages sent or\n * received starting at client hello up to but not including this\n * message, including the type and length fields of the handshake\n * messages.\n *\n * select(SignatureAlgorithm) {\n * case anonymous: struct { };\n * case rsa:\n * digitally-signed struct {\n * opaque md5_hash[16];\n * opaque sha_hash[20];\n * };\n * case dsa:\n * digitally-signed struct {\n * opaque sha_hash[20];\n * };\n * } Signature;\n *\n * In digital signing, one-way hash functions are used as input for a\n * signing algorithm. A digitally-signed element is encoded as an opaque\n * vector <0..2^16-1>, where the length is specified by the signing\n * algorithm and key.\n *\n * In RSA signing, a 36-byte structure of two hashes (one SHA and one\n * MD5) is signed (encrypted with the private key). It is encoded with\n * PKCS #1 block type 0 or type 1 as described in [PKCS1].\n *\n * In DSS, the 20 bytes of the SHA hash are run directly through the\n * Digital Signing Algorithm with no additional hashing.\n *\n * @param c the connection.\n * @param signature the signature to include in the message.\n *\n * @return the CertificateVerify byte buffer.\n */\ntls.createCertificateVerify = function(c, signature) {\n /* Note: The signature will be stored in a \"digitally-signed\" opaque\n vector that has the length prefixed using 2 bytes, so include those\n 2 bytes in the handshake message length. This is done as a minor\n optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = signature.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_verify);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(signature.length);\n rval.putBytes(signature);\n return rval;\n};\n\n/**\n * Creates a CertificateRequest message.\n *\n * @param c the connection.\n *\n * @return the CertificateRequest byte buffer.\n */\ntls.createCertificateRequest = function(c) {\n // TODO: support other certificate types\n var certTypes = forge.util.createBuffer();\n\n // common RSA certificate type\n certTypes.putByte(0x01);\n\n // add distinguished names from CA store\n var cAs = forge.util.createBuffer();\n for(var key in c.caStore.certs) {\n var cert = c.caStore.certs[key];\n var dn = forge.pki.distinguishedNameToAsn1(cert.subject);\n var byteBuffer = forge.asn1.toDer(dn);\n cAs.putInt16(byteBuffer.length());\n cAs.putBuffer(byteBuffer);\n }\n\n // TODO: TLS 1.2+ has a different format\n\n // determine length of the handshake message\n var length =\n 1 + certTypes.length() +\n 2 + cAs.length();\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_request);\n rval.putInt24(length);\n writeVector(rval, 1, certTypes);\n writeVector(rval, 2, cAs);\n return rval;\n};\n\n/**\n * Creates a ServerHelloDone message.\n *\n * @param c the connection.\n *\n * @return the ServerHelloDone byte buffer.\n */\ntls.createServerHelloDone = function(c) {\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello_done);\n rval.putInt24(0);\n return rval;\n};\n\n/**\n * Creates a ChangeCipherSpec message.\n *\n * The change cipher spec protocol exists to signal transitions in\n * ciphering strategies. The protocol consists of a single message,\n * which is encrypted and compressed under the current (not the pending)\n * connection state. The message consists of a single byte of value 1.\n *\n * struct {\n * enum { change_cipher_spec(1), (255) } type;\n * } ChangeCipherSpec;\n *\n * @return the ChangeCipherSpec byte buffer.\n */\ntls.createChangeCipherSpec = function() {\n var rval = forge.util.createBuffer();\n rval.putByte(0x01);\n return rval;\n};\n\n/**\n * Creates a Finished message.\n *\n * struct {\n * opaque verify_data[12];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, MD5(handshake_messages) +\n * SHA-1(handshake_messages)) [0..11];\n *\n * finished_label\n * For Finished messages sent by the client, the string \"client\n * finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * handshake_messages\n * All of the data from all handshake messages up to but not\n * including this message. This is only data visible at the\n * handshake layer and does not include record layer headers.\n * This is the concatenation of all the Handshake structures as\n * defined in 7.4 exchanged thus far.\n *\n * @param c the connection.\n *\n * @return the Finished byte buffer.\n */\ntls.createFinished = function(c) {\n // generate verify_data\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // TODO: determine prf function and verify length for TLS 1.2\n var client = (c.entity === tls.ConnectionEnd.client);\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n var label = client ? 'client finished' : 'server finished';\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.finished);\n rval.putInt24(b.length());\n rval.putBuffer(b);\n return rval;\n};\n\n/**\n * Creates a HeartbeatMessage (See RFC 6520).\n *\n * struct {\n * HeartbeatMessageType type;\n * uint16 payload_length;\n * opaque payload[HeartbeatMessage.payload_length];\n * opaque padding[padding_length];\n * } HeartbeatMessage;\n *\n * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or\n * max_fragment_length when negotiated as defined in [RFC6066].\n *\n * type: The message type, either heartbeat_request or heartbeat_response.\n *\n * payload_length: The length of the payload.\n *\n * payload: The payload consists of arbitrary content.\n *\n * padding: The padding is random content that MUST be ignored by the\n * receiver. The length of a HeartbeatMessage is TLSPlaintext.length\n * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the\n * length of the type field is 1 byte, and the length of the\n * payload_length is 2. Therefore, the padding_length is\n * TLSPlaintext.length - payload_length - 3 for TLS and\n * DTLSPlaintext.length - payload_length - 3 for DTLS. The\n * padding_length MUST be at least 16.\n *\n * The sender of a HeartbeatMessage MUST use a random padding of at\n * least 16 bytes. The padding of a received HeartbeatMessage message\n * MUST be ignored.\n *\n * If the payload_length of a received HeartbeatMessage is too large,\n * the received HeartbeatMessage MUST be discarded silently.\n *\n * @param c the connection.\n * @param type the tls.HeartbeatMessageType.\n * @param payload the heartbeat data to send as the payload.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return the HeartbeatRequest byte buffer.\n */\ntls.createHeartbeat = function(type, payload, payloadLength) {\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(type); // heartbeat message type\n rval.putInt16(payloadLength); // payload length\n rval.putBytes(payload); // payload\n // padding\n var plaintextLength = rval.length();\n var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);\n rval.putBytes(forge.random.getBytes(paddingLength));\n return rval;\n};\n\n/**\n * Fragments, compresses, encrypts, and queues a record for delivery.\n *\n * @param c the connection.\n * @param record the record to queue.\n */\ntls.queue = function(c, record) {\n // error during record creation\n if(!record) {\n return;\n }\n\n if(record.fragment.length() === 0) {\n if(record.type === tls.ContentType.handshake ||\n record.type === tls.ContentType.alert ||\n record.type === tls.ContentType.change_cipher_spec) {\n // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent.\n return;\n }\n }\n\n // if the record is a handshake record, update handshake hashes\n if(record.type === tls.ContentType.handshake) {\n var bytes = record.fragment.bytes();\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n bytes = null;\n }\n\n // handle record fragmentation\n var records;\n if(record.fragment.length() <= tls.MaxFragment) {\n records = [record];\n } else {\n // fragment data as long as it is too long\n records = [];\n var data = record.fragment.bytes();\n while(data.length > tls.MaxFragment) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))\n }));\n data = data.slice(tls.MaxFragment);\n }\n // add last record\n if(data.length > 0) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data)\n }));\n }\n }\n\n // compress and encrypt all fragmented records\n for(var i = 0; i < records.length && !c.fail; ++i) {\n // update the record using current write state\n var rec = records[i];\n var s = c.state.current.write;\n if(s.update(c, rec)) {\n // store record\n c.records.push(rec);\n }\n }\n};\n\n/**\n * Flushes all queued records to the output buffer and calls the\n * tlsDataReady() handler on the given connection.\n *\n * @param c the connection.\n *\n * @return true on success, false on failure.\n */\ntls.flush = function(c) {\n for(var i = 0; i < c.records.length; ++i) {\n var record = c.records[i];\n\n // add record header and fragment\n c.tlsData.putByte(record.type);\n c.tlsData.putByte(record.version.major);\n c.tlsData.putByte(record.version.minor);\n c.tlsData.putInt16(record.fragment.length());\n c.tlsData.putBuffer(c.records[i].fragment);\n }\n c.records = [];\n return c.tlsDataReady(c);\n};\n\n/**\n * Maps a pki.certificateError to a tls.Alert.Description.\n *\n * @param error the error to map.\n *\n * @return the alert description.\n */\nvar _certErrorToAlertDesc = function(error) {\n switch(error) {\n case true:\n return true;\n case forge.pki.certificateError.bad_certificate:\n return tls.Alert.Description.bad_certificate;\n case forge.pki.certificateError.unsupported_certificate:\n return tls.Alert.Description.unsupported_certificate;\n case forge.pki.certificateError.certificate_revoked:\n return tls.Alert.Description.certificate_revoked;\n case forge.pki.certificateError.certificate_expired:\n return tls.Alert.Description.certificate_expired;\n case forge.pki.certificateError.certificate_unknown:\n return tls.Alert.Description.certificate_unknown;\n case forge.pki.certificateError.unknown_ca:\n return tls.Alert.Description.unknown_ca;\n default:\n return tls.Alert.Description.bad_certificate;\n }\n};\n\n/**\n * Maps a tls.Alert.Description to a pki.certificateError.\n *\n * @param desc the alert description.\n *\n * @return the certificate error.\n */\nvar _alertDescToCertError = function(desc) {\n switch(desc) {\n case true:\n return true;\n case tls.Alert.Description.bad_certificate:\n return forge.pki.certificateError.bad_certificate;\n case tls.Alert.Description.unsupported_certificate:\n return forge.pki.certificateError.unsupported_certificate;\n case tls.Alert.Description.certificate_revoked:\n return forge.pki.certificateError.certificate_revoked;\n case tls.Alert.Description.certificate_expired:\n return forge.pki.certificateError.certificate_expired;\n case tls.Alert.Description.certificate_unknown:\n return forge.pki.certificateError.certificate_unknown;\n case tls.Alert.Description.unknown_ca:\n return forge.pki.certificateError.unknown_ca;\n default:\n return forge.pki.certificateError.bad_certificate;\n }\n};\n\n/**\n * Verifies a certificate chain against the given connection's\n * Certificate Authority store.\n *\n * @param c the TLS connection.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end.\n *\n * @return true if successful, false if not.\n */\ntls.verifyCertificateChain = function(c, chain) {\n try {\n // Make a copy of c.verifyOptions so that we can modify options.verify\n // without modifying c.verifyOptions.\n var options = {};\n for (var key in c.verifyOptions) {\n options[key] = c.verifyOptions[key];\n }\n\n options.verify = function(vfd, depth, chain) {\n // convert pki.certificateError to tls alert description\n var desc = _certErrorToAlertDesc(vfd);\n\n // call application callback\n var ret = c.verify(c, vfd, depth, chain);\n if(ret !== true) {\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n // throw custom error\n var error = new Error('The application rejected the certificate.');\n error.send = true;\n error.alert = {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n };\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n throw error;\n }\n\n // convert tls alert description to pki.certificateError\n if(ret !== vfd) {\n ret = _alertDescToCertError(ret);\n }\n }\n\n return ret;\n };\n\n // verify chain\n forge.pki.verifyCertificateChain(c.caStore, chain, options);\n } catch(ex) {\n // build tls error if not already customized\n var err = ex;\n if(typeof err !== 'object' || forge.util.isArray(err)) {\n err = {\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(ex)\n }\n };\n }\n if(!('send' in err)) {\n err.send = true;\n }\n if(!('alert' in err)) {\n err.alert = {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(err.error)\n };\n }\n\n // send error\n c.error(c, err);\n }\n\n return !c.fail;\n};\n\n/**\n * Creates a new TLS session cache.\n *\n * @param cache optional map of session ID to cached session.\n * @param capacity the maximum size for the cache (default: 100).\n *\n * @return the new TLS session cache.\n */\ntls.createSessionCache = function(cache, capacity) {\n var rval = null;\n\n // assume input is already a session cache object\n if(cache && cache.getSession && cache.setSession && cache.order) {\n rval = cache;\n } else {\n // create cache\n rval = {};\n rval.cache = cache || {};\n rval.capacity = Math.max(capacity || 100, 1);\n rval.order = [];\n\n // store order for sessions, delete session overflow\n for(var key in cache) {\n if(rval.order.length <= capacity) {\n rval.order.push(key);\n } else {\n delete cache[key];\n }\n }\n\n // get a session from a session ID (or get any session)\n rval.getSession = function(sessionId) {\n var session = null;\n var key = null;\n\n // if session ID provided, use it\n if(sessionId) {\n key = forge.util.bytesToHex(sessionId);\n } else if(rval.order.length > 0) {\n // get first session from cache\n key = rval.order[0];\n }\n\n if(key !== null && key in rval.cache) {\n // get cached session and remove from cache\n session = rval.cache[key];\n delete rval.cache[key];\n for(var i in rval.order) {\n if(rval.order[i] === key) {\n rval.order.splice(i, 1);\n break;\n }\n }\n }\n\n return session;\n };\n\n // set a session in the cache\n rval.setSession = function(sessionId, session) {\n // remove session from cache if at capacity\n if(rval.order.length === rval.capacity) {\n var key = rval.order.shift();\n delete rval.cache[key];\n }\n // add session to cache\n var key = forge.util.bytesToHex(sessionId);\n rval.order.push(key);\n rval.cache[key] = session;\n };\n }\n\n return rval;\n};\n\n/**\n * Creates a new TLS connection.\n *\n * See public createConnection() docs for more details.\n *\n * @param options the options for this connection.\n *\n * @return the new TLS connection.\n */\ntls.createConnection = function(options) {\n var caStore = null;\n if(options.caStore) {\n // if CA store is an array, convert it to a CA store object\n if(forge.util.isArray(options.caStore)) {\n caStore = forge.pki.createCaStore(options.caStore);\n } else {\n caStore = options.caStore;\n }\n } else {\n // create empty CA store\n caStore = forge.pki.createCaStore();\n }\n\n // setup default cipher suites\n var cipherSuites = options.cipherSuites || null;\n if(cipherSuites === null) {\n cipherSuites = [];\n for(var key in tls.CipherSuites) {\n cipherSuites.push(tls.CipherSuites[key]);\n }\n }\n\n // set default entity\n var entity = (options.server || false) ?\n tls.ConnectionEnd.server : tls.ConnectionEnd.client;\n\n // create session cache if requested\n var sessionCache = options.sessionCache ?\n tls.createSessionCache(options.sessionCache) : null;\n\n // create TLS connection\n var c = {\n version: {major: tls.Version.major, minor: tls.Version.minor},\n entity: entity,\n sessionId: options.sessionId,\n caStore: caStore,\n sessionCache: sessionCache,\n cipherSuites: cipherSuites,\n connected: options.connected,\n virtualHost: options.virtualHost || null,\n verifyClient: options.verifyClient || false,\n verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},\n verifyOptions: options.verifyOptions || {},\n getCertificate: options.getCertificate || null,\n getPrivateKey: options.getPrivateKey || null,\n getSignature: options.getSignature || null,\n input: forge.util.createBuffer(),\n tlsData: forge.util.createBuffer(),\n data: forge.util.createBuffer(),\n tlsDataReady: options.tlsDataReady,\n dataReady: options.dataReady,\n heartbeatReceived: options.heartbeatReceived,\n closed: options.closed,\n error: function(c, ex) {\n // set origin if not set\n ex.origin = ex.origin ||\n ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server');\n\n // send TLS alert\n if(ex.send) {\n tls.queue(c, tls.createAlert(c, ex.alert));\n tls.flush(c);\n }\n\n // error is fatal by default\n var fatal = (ex.fatal !== false);\n if(fatal) {\n // set fail flag\n c.fail = true;\n }\n\n // call error handler first\n options.error(c, ex);\n\n if(fatal) {\n // fatal error, close connection, do not clear fail\n c.close(false);\n }\n },\n deflate: options.deflate || null,\n inflate: options.inflate || null\n };\n\n /**\n * Resets a closed TLS connection for reuse. Called in c.close().\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.reset = function(clearFail) {\n c.version = {major: tls.Version.major, minor: tls.Version.minor};\n c.record = null;\n c.session = null;\n c.peerCertificate = null;\n c.state = {\n pending: null,\n current: null\n };\n c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE;\n c.fragmented = null;\n c.records = [];\n c.open = false;\n c.handshakes = 0;\n c.handshaking = false;\n c.isConnected = false;\n c.fail = !(clearFail || typeof(clearFail) === 'undefined');\n c.input.clear();\n c.tlsData.clear();\n c.data.clear();\n c.state.current = tls.createConnectionState(c);\n };\n\n // do initial reset of connection\n c.reset();\n\n /**\n * Updates the current TLS engine state based on the given record.\n *\n * @param c the TLS connection.\n * @param record the TLS record to act on.\n */\n var _update = function(c, record) {\n // get record handler (align type in table by subtracting lowest)\n var aligned = record.type - tls.ContentType.change_cipher_spec;\n var handlers = ctTable[c.entity][c.expect];\n if(aligned in handlers) {\n handlers[aligned](c, record);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n };\n\n /**\n * Reads the record header and initializes the next record on the given\n * connection.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecordHeader = function(c) {\n var rval = 0;\n\n // get input buffer and its length\n var b = c.input;\n var len = b.length();\n\n // need at least 5 bytes to initialize a record\n if(len < 5) {\n rval = 5 - len;\n } else {\n // enough bytes for header\n // initialize record\n c.record = {\n type: b.getByte(),\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n length: b.getInt16(),\n fragment: forge.util.createBuffer(),\n ready: false\n };\n\n // check record version\n var compatibleVersion = (c.record.version.major === c.version.major);\n if(compatibleVersion && c.session && c.session.version) {\n // session version already set, require same minor version\n compatibleVersion = (c.record.version.minor === c.version.minor);\n }\n if(!compatibleVersion) {\n c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n return rval;\n };\n\n /**\n * Reads the next record's contents and appends its message to any\n * previously fragmented message.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecord = function(c) {\n var rval = 0;\n\n // ensure there is enough input data to get the entire record\n var b = c.input;\n var len = b.length();\n if(len < c.record.length) {\n // not enough data yet, return how much is required\n rval = c.record.length - len;\n } else {\n // there is enough data to parse the pending record\n // fill record fragment and compact input buffer\n c.record.fragment.putBytes(b.getBytes(c.record.length));\n b.compact();\n\n // update record using current read state\n var s = c.state.current.read;\n if(s.update(c, c.record)) {\n // see if there is a previously fragmented message that the\n // new record's message fragment should be appended to\n if(c.fragmented !== null) {\n // if the record type matches a previously fragmented\n // record, append the record fragment to it\n if(c.fragmented.type === c.record.type) {\n // concatenate record fragments\n c.fragmented.fragment.putBuffer(c.record.fragment);\n c.record = c.fragmented;\n } else {\n // error, invalid fragmented record\n c.error(c, {\n message: 'Invalid fragmented record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description:\n tls.Alert.Description.unexpected_message\n }\n });\n }\n }\n\n // record is now ready\n c.record.ready = true;\n }\n }\n\n return rval;\n };\n\n /**\n * Performs a handshake using the TLS Handshake Protocol, as a client.\n *\n * This method should only be called if the connection is in client mode.\n *\n * @param sessionId the session ID to use, null to start a new one.\n */\n c.handshake = function(sessionId) {\n // error to call this in non-client mode\n if(c.entity !== tls.ConnectionEnd.client) {\n // not fatal error\n c.error(c, {\n message: 'Cannot initiate handshake as a server.',\n fatal: false\n });\n } else if(c.handshaking) {\n // handshake is already in progress, fail but not fatal error\n c.error(c, {\n message: 'Handshake already in progress.',\n fatal: false\n });\n } else {\n // clear fail flag on reuse\n if(c.fail && !c.open && c.handshakes === 0) {\n c.fail = false;\n }\n\n // now handshaking\n c.handshaking = true;\n\n // default to blank (new session)\n sessionId = sessionId || '';\n\n // if a session ID was specified, try to find it in the cache\n var session = null;\n if(sessionId.length > 0) {\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n }\n\n // matching session not found in cache, clear session ID\n if(session === null) {\n sessionId = '';\n }\n }\n\n // no session given, grab a session from the cache, if available\n if(sessionId.length === 0 && c.sessionCache) {\n session = c.sessionCache.getSession();\n if(session !== null) {\n sessionId = session.id;\n }\n }\n\n // set up session\n c.session = {\n id: sessionId,\n version: null,\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n certificateRequest: null,\n clientCertificate: null,\n sp: {},\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n\n // use existing session information\n if(session) {\n // only update version on connection, session version not yet set\n c.version = session.version;\n c.session.sp = session.sp;\n }\n\n // generate new client random\n c.session.sp.client_random = tls.createRandom().getBytes();\n\n // connection now open\n c.open = true;\n\n // send hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientHello(c)\n }));\n tls.flush(c);\n }\n };\n\n /**\n * Called when TLS protocol data has been received from somewhere and should\n * be processed by the TLS engine.\n *\n * @param data the TLS protocol data, as a string, to process.\n *\n * @return 0 if the data could be processed, otherwise the number of bytes\n * required for data to be processed.\n */\n c.process = function(data) {\n var rval = 0;\n\n // buffer input data\n if(data) {\n c.input.putBytes(data);\n }\n\n // process next record if no failure, process will be called after\n // each record is handled (since handling can be asynchronous)\n if(!c.fail) {\n // reset record if ready and now empty\n if(c.record !== null &&\n c.record.ready && c.record.fragment.isEmpty()) {\n c.record = null;\n }\n\n // if there is no pending record, try to read record header\n if(c.record === null) {\n rval = _readRecordHeader(c);\n }\n\n // read the next record (if record not yet ready)\n if(!c.fail && c.record !== null && !c.record.ready) {\n rval = _readRecord(c);\n }\n\n // record ready to be handled, update engine state\n if(!c.fail && c.record !== null && c.record.ready) {\n _update(c, c.record);\n }\n }\n\n return rval;\n };\n\n /**\n * Requests that application data be packaged into a TLS record. The\n * tlsDataReady handler will be called when the TLS record(s) have been\n * prepared.\n *\n * @param data the application data, as a raw 'binary' encoded string, to\n * be sent; to send utf-16/utf-8 string data, use the return value\n * of util.encodeUtf8(str).\n *\n * @return true on success, false on failure.\n */\n c.prepare = function(data) {\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.application_data,\n data: forge.util.createBuffer(data)\n }));\n return tls.flush(c);\n };\n\n /**\n * Requests that a heartbeat request be packaged into a TLS record for\n * transmission. The tlsDataReady handler will be called when TLS record(s)\n * have been prepared.\n *\n * When a heartbeat response has been received, the heartbeatReceived\n * handler will be called with the matching payload. This handler can\n * be used to clear a retransmission timer, etc.\n *\n * @param payload the heartbeat data to send as the payload in the message.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return true on success, false on failure.\n */\n c.prepareHeartbeatRequest = function(payload, payloadLength) {\n if(payload instanceof forge.util.ByteBuffer) {\n payload = payload.bytes();\n }\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n c.expectedHeartbeatPayload = payload;\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)\n }));\n return tls.flush(c);\n };\n\n /**\n * Closes the connection (sends a close_notify alert).\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.close = function(clearFail) {\n // save session if connection didn't fail\n if(!c.fail && c.sessionCache && c.session) {\n // only need to preserve session ID, version, and security params\n var session = {\n id: c.session.id,\n version: c.session.version,\n sp: c.session.sp\n };\n session.sp.keys = null;\n c.sessionCache.setSession(session.id, session);\n }\n\n if(c.open) {\n // connection no longer open, clear input\n c.open = false;\n c.input.clear();\n\n // if connected or handshaking, send an alert\n if(c.isConnected || c.handshaking) {\n c.isConnected = c.handshaking = false;\n\n // send close_notify alert\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.close_notify\n }));\n tls.flush(c);\n }\n\n // call handler\n c.closed(c);\n }\n\n // reset TLS connection, do not clear fail flag\n c.reset(clearFail);\n };\n\n return c;\n};\n\n/* TLS API */\nmodule.exports = forge.tls = forge.tls || {};\n\n// expose non-functions\nfor(var key in tls) {\n if(typeof tls[key] !== 'function') {\n forge.tls[key] = tls[key];\n }\n}\n\n// expose prf_tls1 for testing\nforge.tls.prf_tls1 = prf_TLS1;\n\n// expose sha1 hmac method\nforge.tls.hmac_sha1 = hmac_sha1;\n\n// expose session cache creation\nforge.tls.createSessionCache = tls.createSessionCache;\n\n/**\n * Creates a new TLS connection. This does not make any assumptions about the\n * transport layer that TLS is working on top of, ie: it does not assume there\n * is a TCP/IP connection or establish one. A TLS connection is totally\n * abstracted away from the layer is runs on top of, it merely establishes a\n * secure channel between a client\" and a \"server\".\n *\n * A TLS connection contains 4 connection states: pending read and write, and\n * current read and write.\n *\n * At initialization, the current read and write states will be null. Only once\n * the security parameters have been set and the keys have been generated can\n * the pending states be converted into current states. Current states will be\n * updated for each record processed.\n *\n * A custom certificate verify callback may be provided to check information\n * like the common name on the server's certificate. It will be called for\n * every certificate in the chain. It has the following signature:\n *\n * variable func(c, certs, index, preVerify)\n * Where:\n * c The TLS connection\n * verified Set to true if certificate was verified, otherwise the alert\n * tls.Alert.Description for why the certificate failed.\n * depth The current index in the chain, where 0 is the server's cert.\n * certs The certificate chain, *NOTE* if the server was anonymous then\n * the chain will be empty.\n *\n * The function returns true on success and on failure either the appropriate\n * tls.Alert.Description or an object with 'alert' set to the appropriate\n * tls.Alert.Description and 'message' set to a custom error message. If true\n * is not returned then the connection will abort using, in order of\n * availability, first the returned alert description, second the preVerify\n * alert description, and lastly the default 'bad_certificate'.\n *\n * There are three callbacks that can be used to make use of client-side\n * certificates where each takes the TLS connection as the first parameter:\n *\n * getCertificate(conn, hint)\n * The second parameter is a hint as to which certificate should be\n * returned. If the connection entity is a client, then the hint will be\n * the CertificateRequest message from the server that is part of the\n * TLS protocol. If the connection entity is a server, then it will be\n * the servername list provided via an SNI extension the ClientHello, if\n * one was provided (empty array if not). The hint can be examined to\n * determine which certificate to use (advanced). Most implementations\n * will just return a certificate. The return value must be a\n * PEM-formatted certificate or an array of PEM-formatted certificates\n * that constitute a certificate chain, with the first in the array/chain\n * being the client's certificate.\n * getPrivateKey(conn, certificate)\n * The second parameter is an forge.pki X.509 certificate object that\n * is associated with the requested private key. The return value must\n * be a PEM-formatted private key.\n * getSignature(conn, bytes, callback)\n * This callback can be used instead of getPrivateKey if the private key\n * is not directly accessible in javascript or should not be. For\n * instance, a secure external web service could provide the signature\n * in exchange for appropriate credentials. The second parameter is a\n * string of bytes to be signed that are part of the TLS protocol. These\n * bytes are used to verify that the private key for the previously\n * provided client-side certificate is accessible to the client. The\n * callback is a function that takes 2 parameters, the TLS connection\n * and the RSA encrypted (signed) bytes as a string. This callback must\n * be called once the signature is ready.\n *\n * @param options the options for this connection:\n * server: true if the connection is server-side, false for client.\n * sessionId: a session ID to reuse, null for a new connection.\n * caStore: an array of certificates to trust.\n * sessionCache: a session cache to use.\n * cipherSuites: an optional array of cipher suites to use,\n * see tls.CipherSuites.\n * connected: function(conn) called when the first handshake completes.\n * virtualHost: the virtual server name to use in a TLS SNI extension.\n * verifyClient: true to require a client certificate in server mode,\n * 'optional' to request one, false not to (default: false).\n * verify: a handler used to custom verify certificates in the chain.\n * verifyOptions: an object with options for the certificate chain validation.\n * See documentation of pki.verifyCertificateChain for possible options.\n * verifyOptions.verify is ignored. If you wish to specify a verify handler\n * use the verify key.\n * getCertificate: an optional callback used to get a certificate or\n * a chain of certificates (as an array).\n * getPrivateKey: an optional callback used to get a private key.\n * getSignature: an optional callback used to get a signature.\n * tlsDataReady: function(conn) called when TLS protocol data has been\n * prepared and is ready to be used (typically sent over a socket\n * connection to its destination), read from conn.tlsData buffer.\n * dataReady: function(conn) called when application data has\n * been parsed from a TLS record and should be consumed by the\n * application, read from conn.data buffer.\n * closed: function(conn) called when the connection has been closed.\n * error: function(conn, error) called when there was an error.\n * deflate: function(inBytes) if provided, will deflate TLS records using\n * the deflate algorithm if the server supports it.\n * inflate: function(inBytes) if provided, will inflate TLS records using\n * the deflate algorithm if the server supports it.\n *\n * @return the new TLS connection.\n */\nforge.tls.createConnection = tls.createConnection;\n","/**\n * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nvar baseN = require('./baseN');\n\n/* Utilities API */\nvar util = module.exports = forge.util = forge.util || {};\n\n// define setImmediate and nextTick\n(function() {\n // use native nextTick (unless we're in webpack)\n // webpack (or better node-libs-browser polyfill) sets process.browser.\n // this way we can detect webpack properly\n if(typeof process !== 'undefined' && process.nextTick && !process.browser) {\n util.nextTick = process.nextTick;\n if(typeof setImmediate === 'function') {\n util.setImmediate = setImmediate;\n } else {\n // polyfill setImmediate with nextTick, older versions of node\n // (those w/o setImmediate) won't totally starve IO\n util.setImmediate = util.nextTick;\n }\n return;\n }\n\n // polyfill nextTick with native setImmediate\n if(typeof setImmediate === 'function') {\n util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };\n util.nextTick = function(callback) {\n return setImmediate(callback);\n };\n return;\n }\n\n /* Note: A polyfill upgrade pattern is used here to allow combining\n polyfills. For example, MutationObserver is fast, but blocks UI updates,\n so it needs to allow UI updates periodically, so it falls back on\n postMessage or setTimeout. */\n\n // polyfill with setTimeout\n util.setImmediate = function(callback) {\n setTimeout(callback, 0);\n };\n\n // upgrade polyfill to use postMessage\n if(typeof window !== 'undefined' &&\n typeof window.postMessage === 'function') {\n var msg = 'forge.setImmediate';\n var callbacks = [];\n util.setImmediate = function(callback) {\n callbacks.push(callback);\n // only send message when one hasn't been sent in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n window.postMessage(msg, '*');\n }\n };\n function handler(event) {\n if(event.source === window && event.data === msg) {\n event.stopPropagation();\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }\n }\n window.addEventListener('message', handler, true);\n }\n\n // upgrade polyfill to use MutationObserver\n if(typeof MutationObserver !== 'undefined') {\n // polyfill with MutationObserver\n var now = Date.now();\n var attr = true;\n var div = document.createElement('div');\n var callbacks = [];\n new MutationObserver(function() {\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }).observe(div, {attributes: true});\n var oldSetImmediate = util.setImmediate;\n util.setImmediate = function(callback) {\n if(Date.now() - now > 15) {\n now = Date.now();\n oldSetImmediate(callback);\n } else {\n callbacks.push(callback);\n // only trigger observer when it hasn't been triggered in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n div.setAttribute('a', attr = !attr);\n }\n }\n };\n }\n\n util.nextTick = util.setImmediate;\n})();\n\n// check if running under Node.js\nutil.isNodejs =\n typeof process !== 'undefined' && process.versions && process.versions.node;\n\n\n// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while\n// it will point to `window` in the main thread.\n// To remain compatible with older browsers, we fall back to 'window' if 'self'\n// is not available.\nutil.globalScope = (function() {\n if(util.isNodejs) {\n return global;\n }\n\n return typeof self === 'undefined' ? window : self;\n})();\n\n// define isArray\nutil.isArray = Array.isArray || function(x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// define isArrayBuffer\nutil.isArrayBuffer = function(x) {\n return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;\n};\n\n// define isArrayBufferView\nutil.isArrayBufferView = function(x) {\n return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;\n};\n\n/**\n * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for\n * algorithms where bit manipulation, JavaScript limitations, and/or algorithm\n * design only allow for byte operations of a limited size.\n *\n * @param n number of bits.\n *\n * Throw Error if n invalid.\n */\nfunction _checkBitsParam(n) {\n if(!(n === 8 || n === 16 || n === 24 || n === 32)) {\n throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);\n }\n}\n\n// TODO: set ByteBuffer to best available backing\nutil.ByteBuffer = ByteStringBuffer;\n\n/** Buffer w/BinaryString backing */\n\n/**\n * Constructor for a binary string backed byte buffer.\n *\n * @param [b] the bytes to wrap (either encoded as string, one byte per\n * character, or as an ArrayBuffer or Typed Array).\n */\nfunction ByteStringBuffer(b) {\n // TODO: update to match DataBuffer API\n\n // the data in this buffer\n this.data = '';\n // the pointer for reading from this buffer\n this.read = 0;\n\n if(typeof b === 'string') {\n this.data = b;\n } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {\n if(typeof Buffer !== 'undefined' && b instanceof Buffer) {\n this.data = b.toString('binary');\n } else {\n // convert native buffer to forge buffer\n // FIXME: support native buffers internally instead\n var arr = new Uint8Array(b);\n try {\n this.data = String.fromCharCode.apply(null, arr);\n } catch(e) {\n for(var i = 0; i < arr.length; ++i) {\n this.putByte(arr[i]);\n }\n }\n }\n } else if(b instanceof ByteStringBuffer ||\n (typeof b === 'object' && typeof b.data === 'string' &&\n typeof b.read === 'number')) {\n // copy existing buffer\n this.data = b.data;\n this.read = b.read;\n }\n\n // used for v8 optimization\n this._constructedStringLength = 0;\n}\nutil.ByteStringBuffer = ByteStringBuffer;\n\n/* Note: This is an optimization for V8-based browsers. When V8 concatenates\n a string, the strings are only joined logically using a \"cons string\" or\n \"constructed/concatenated string\". These containers keep references to one\n another and can result in very large memory usage. For example, if a 2MB\n string is constructed by concatenating 4 bytes together at a time, the\n memory usage will be ~44MB; so ~22x increase. The strings are only joined\n together when an operation requiring their joining takes place, such as\n substr(). This function is called when adding data to this buffer to ensure\n these types of strings are periodically joined to reduce the memory\n footprint. */\nvar _MAX_CONSTRUCTED_STRING_LENGTH = 4096;\nutil.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {\n this._constructedStringLength += x;\n if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {\n // this substr() should cause the constructed string to join\n this.data.substr(0, 1);\n this._constructedStringLength = 0;\n }\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.ByteStringBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.ByteStringBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putByte = function(b) {\n return this.putBytes(String.fromCharCode(b));\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.fillWithByte = function(b, n) {\n b = String.fromCharCode(b);\n var d = this.data;\n while(n > 0) {\n if(n & 1) {\n d += b;\n }\n n >>>= 1;\n if(n > 0) {\n b += b;\n }\n }\n this.data = d;\n this._optimizeConstructedString(n);\n return this;\n};\n\n/**\n * Puts bytes in this buffer.\n *\n * @param bytes the bytes (as a binary encoded string) to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n this._optimizeConstructedString(bytes.length);\n return this;\n};\n\n/**\n * Puts a UTF-16 encoded string into this buffer.\n *\n * @param str the string to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putString = function(str) {\n return this.putBytes(util.encodeUtf8(str));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 24 & 0xFF));\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n var bytes = '';\n do {\n n -= 8;\n bytes += String.fromCharCode((i >> n) & 0xFF);\n } while(n > 0);\n return this.putBytes(bytes);\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putSignedInt = function(i, n) {\n // putInt checks n\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBuffer = function(buffer) {\n return this.putBytes(buffer.getBytes());\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.getByte = function() {\n return this.data.charCodeAt(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 8 ^\n this.data.charCodeAt(this.read + 1));\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 16 ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16 ^\n this.data.charCodeAt(this.read + 3) << 24);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by ceil(n/8).\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.charCodeAt(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer. Note that the resulting string is binary encoded (in node.js this\n * encoding is referred to as `binary`, it is *not* `utf8`).\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.ByteStringBuffer.prototype.getBytes = function(count) {\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.ByteStringBuffer.prototype.bytes = function(count) {\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.at = function(i) {\n return this.data.charCodeAt(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.setAt = function(i, b) {\n this.data = this.data.substr(0, this.read + i) +\n String.fromCharCode(b) +\n this.data.substr(this.read + i + 1);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.ByteStringBuffer.prototype.last = function() {\n return this.data.charCodeAt(this.data.length - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.ByteStringBuffer.prototype.copy = function() {\n var c = util.createBuffer(this.data);\n c.read = this.read;\n return c;\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.compact = function() {\n if(this.read > 0) {\n this.data = this.data.slice(this.read);\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.clear = function() {\n this.data = '';\n this.read = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.truncate = function(count) {\n var len = Math.max(0, this.length() - count);\n this.data = this.data.substr(this.read, len);\n this.read = 0;\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.ByteStringBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a UTF-16 string (standard JavaScript string).\n *\n * @return a UTF-16 string.\n */\nutil.ByteStringBuffer.prototype.toString = function() {\n return util.decodeUtf8(this.bytes());\n};\n\n/** End Buffer w/BinaryString backing */\n\n/** Buffer w/UInt8Array backing */\n\n/**\n * FIXME: Experimental. Do not use yet.\n *\n * Constructor for an ArrayBuffer-backed byte buffer.\n *\n * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a\n * TypedArray.\n *\n * If a string is given, its encoding should be provided as an option,\n * otherwise it will default to 'binary'. A 'binary' string is encoded such\n * that each character is one byte in length and size.\n *\n * If an ArrayBuffer, DataView, or TypedArray is given, it will be used\n * *directly* without any copying. Note that, if a write to the buffer requires\n * more space, the buffer will allocate a new backing ArrayBuffer to\n * accommodate. The starting read and write offsets for the buffer may be\n * given as options.\n *\n * @param [b] the initial bytes for this buffer.\n * @param options the options to use:\n * [readOffset] the starting read offset to use (default: 0).\n * [writeOffset] the starting write offset to use (default: the\n * length of the first parameter).\n * [growSize] the minimum amount, in bytes, to grow the buffer by to\n * accommodate writes (default: 1024).\n * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the\n * first parameter, if it is a string (default: 'binary').\n */\nfunction DataBuffer(b, options) {\n // default options\n options = options || {};\n\n // pointers for read from/write to buffer\n this.read = options.readOffset || 0;\n this.growSize = options.growSize || 1024;\n\n var isArrayBuffer = util.isArrayBuffer(b);\n var isArrayBufferView = util.isArrayBufferView(b);\n if(isArrayBuffer || isArrayBufferView) {\n // use ArrayBuffer directly\n if(isArrayBuffer) {\n this.data = new DataView(b);\n } else {\n // TODO: adjust read/write offset based on the type of view\n // or specify that this must be done in the options ... that the\n // offsets are byte-based\n this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);\n }\n this.write = ('writeOffset' in options ?\n options.writeOffset : this.data.byteLength);\n return;\n }\n\n // initialize to empty array buffer and add any given bytes using putBytes\n this.data = new DataView(new ArrayBuffer(0));\n this.write = 0;\n\n if(b !== null && b !== undefined) {\n this.putBytes(b);\n }\n\n if('writeOffset' in options) {\n this.write = options.writeOffset;\n }\n}\nutil.DataBuffer = DataBuffer;\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.DataBuffer.prototype.length = function() {\n return this.write - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.DataBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Ensures this buffer has enough empty space to accommodate the given number\n * of bytes. An optional parameter may be given that indicates a minimum\n * amount to grow the buffer if necessary. If the parameter is not given,\n * the buffer will be grown by some previously-specified default amount\n * or heuristic.\n *\n * @param amount the number of bytes to accommodate.\n * @param [growSize] the minimum amount, in bytes, to grow the buffer by if\n * necessary.\n */\nutil.DataBuffer.prototype.accommodate = function(amount, growSize) {\n if(this.length() >= amount) {\n return this;\n }\n growSize = Math.max(growSize || this.growSize, amount);\n\n // grow buffer\n var src = new Uint8Array(\n this.data.buffer, this.data.byteOffset, this.data.byteLength);\n var dst = new Uint8Array(this.length() + growSize);\n dst.set(src);\n this.data = new DataView(dst.buffer);\n\n return this;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putByte = function(b) {\n this.accommodate(1);\n this.data.setUint8(this.write++, b);\n return this;\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.fillWithByte = function(b, n) {\n this.accommodate(n);\n for(var i = 0; i < n; ++i) {\n this.data.setUint8(b);\n }\n return this;\n};\n\n/**\n * Puts bytes in this buffer. The bytes may be given as a string, an\n * ArrayBuffer, a DataView, or a TypedArray.\n *\n * @param bytes the bytes to put.\n * @param [encoding] the encoding for the first parameter ('binary', 'utf8',\n * 'utf16', 'hex'), if it is a string (default: 'binary').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBytes = function(bytes, encoding) {\n if(util.isArrayBufferView(bytes)) {\n var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n var len = src.byteLength - src.byteOffset;\n this.accommodate(len);\n var dst = new Uint8Array(this.data.buffer, this.write);\n dst.set(src);\n this.write += len;\n return this;\n }\n\n if(util.isArrayBuffer(bytes)) {\n var src = new Uint8Array(bytes);\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(this.data.buffer);\n dst.set(src, this.write);\n this.write += src.byteLength;\n return this;\n }\n\n // bytes is a util.DataBuffer or equivalent\n if(bytes instanceof util.DataBuffer ||\n (typeof bytes === 'object' &&\n typeof bytes.read === 'number' && typeof bytes.write === 'number' &&\n util.isArrayBufferView(bytes.data))) {\n var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(bytes.data.byteLength, this.write);\n dst.set(src);\n this.write += src.byteLength;\n return this;\n }\n\n if(bytes instanceof util.ByteStringBuffer) {\n // copy binary string and process as the same as a string parameter below\n bytes = bytes.data;\n encoding = 'binary';\n }\n\n // string conversion\n encoding = encoding || 'binary';\n if(typeof bytes === 'string') {\n var view;\n\n // decode from string\n if(encoding === 'hex') {\n this.accommodate(Math.ceil(bytes.length / 2));\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.hex.decode(bytes, view, this.write);\n return this;\n }\n if(encoding === 'base64') {\n this.accommodate(Math.ceil(bytes.length / 4) * 3);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.base64.decode(bytes, view, this.write);\n return this;\n }\n\n // encode text as UTF-8 bytes\n if(encoding === 'utf8') {\n // encode as UTF-8 then decode string as raw binary\n bytes = util.encodeUtf8(bytes);\n encoding = 'binary';\n }\n\n // decode string as raw binary\n if(encoding === 'binary' || encoding === 'raw') {\n // one byte per character\n this.accommodate(bytes.length);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.raw.decode(view);\n return this;\n }\n\n // encode text as UTF-16 bytes\n if(encoding === 'utf16') {\n // two bytes per character\n this.accommodate(bytes.length * 2);\n view = new Uint16Array(this.data.buffer, this.write);\n this.write += util.text.utf16.encode(view);\n return this;\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n }\n\n throw Error('Invalid parameter: ' + bytes);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBuffer = function(buffer) {\n this.putBytes(buffer);\n buffer.clear();\n return this;\n};\n\n/**\n * Puts a string into this buffer.\n *\n * @param str the string to put.\n * @param [encoding] the encoding for the string (default: 'utf16').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putString = function(str) {\n return this.putBytes(str, 'utf16');\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16 = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24 = function(i) {\n this.accommodate(3);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32 = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16Le = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i, true);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24Le = function(i) {\n this.accommodate(3);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32Le = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i, true);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n do {\n n -= 8;\n this.data.setInt8(this.write++, (i >> n) & 0xFF);\n } while(n > 0);\n return this;\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putSignedInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.getByte = function() {\n return this.data.getInt8(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16 = function() {\n var rval = this.data.getInt16(this.read);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.getInt16(this.read) << 8 ^\n this.data.getInt8(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32 = function() {\n var rval = this.data.getInt32(this.read);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16Le = function() {\n var rval = this.data.getInt16(this.read, true);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.getInt8(this.read) ^\n this.data.getInt16(this.read + 1, true) << 8);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32Le = function() {\n var rval = this.data.getInt32(this.read, true);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.getInt8(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer.\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.DataBuffer.prototype.getBytes = function(count) {\n // TODO: deprecate this method, it is poorly named and\n // this.toString('binary') replaces it\n // add a toTypedArray()/toArrayBuffer() function\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.DataBuffer.prototype.bytes = function(count) {\n // TODO: deprecate this method, it is poorly named, add \"getString()\"\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.at = function(i) {\n return this.data.getUint8(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.setAt = function(i, b) {\n this.data.setUint8(i, b);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.DataBuffer.prototype.last = function() {\n return this.data.getUint8(this.write - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.DataBuffer.prototype.copy = function() {\n return new util.DataBuffer(this);\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.compact = function() {\n if(this.read > 0) {\n var src = new Uint8Array(this.data.buffer, this.read);\n var dst = new Uint8Array(src.byteLength);\n dst.set(src);\n this.data = new DataView(dst);\n this.write -= this.read;\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.clear = function() {\n this.data = new DataView(new ArrayBuffer(0));\n this.read = this.write = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.truncate = function(count) {\n this.write = Math.max(0, this.length() - count);\n this.read = Math.min(this.read, this.write);\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.DataBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.byteLength; ++i) {\n var b = this.data.getUint8(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a string, using the given encoding. If no\n * encoding is given, 'utf8' (UTF-8) is used.\n *\n * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',\n * 'base64' (default: 'utf8').\n *\n * @return a string representation of the bytes in this buffer.\n */\nutil.DataBuffer.prototype.toString = function(encoding) {\n var view = new Uint8Array(this.data, this.read, this.length());\n encoding = encoding || 'utf8';\n\n // encode to string\n if(encoding === 'binary' || encoding === 'raw') {\n return util.binary.raw.encode(view);\n }\n if(encoding === 'hex') {\n return util.binary.hex.encode(view);\n }\n if(encoding === 'base64') {\n return util.binary.base64.encode(view);\n }\n\n // decode to text\n if(encoding === 'utf8') {\n return util.text.utf8.decode(view);\n }\n if(encoding === 'utf16') {\n return util.text.utf16.decode(view);\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n};\n\n/** End Buffer w/UInt8Array backing */\n\n/**\n * Creates a buffer that stores bytes. A value may be given to populate the\n * buffer with data. This value can either be string of encoded bytes or a\n * regular string of characters. When passing a string of binary encoded\n * bytes, the encoding `raw` should be given. This is also the default. When\n * passing a string of characters, the encoding `utf8` should be given.\n *\n * @param [input] a string with encoded bytes to store in the buffer.\n * @param [encoding] (default: 'raw', other: 'utf8').\n */\nutil.createBuffer = function(input, encoding) {\n // TODO: deprecate, use new ByteBuffer() instead\n encoding = encoding || 'raw';\n if(input !== undefined && encoding === 'utf8') {\n input = util.encodeUtf8(input);\n }\n return new util.ByteBuffer(input);\n};\n\n/**\n * Fills a string with a particular value. If you want the string to be a byte\n * string, pass in String.fromCharCode(theByte).\n *\n * @param c the character to fill the string with, use String.fromCharCode\n * to fill the string with a byte value.\n * @param n the number of characters of value c to fill with.\n *\n * @return the filled string.\n */\nutil.fillString = function(c, n) {\n var s = '';\n while(n > 0) {\n if(n & 1) {\n s += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n return s;\n};\n\n/**\n * Performs a per byte XOR between two byte strings and returns the result as a\n * string of bytes.\n *\n * @param s1 first string of bytes.\n * @param s2 second string of bytes.\n * @param n the number of bytes to XOR.\n *\n * @return the XOR'd result.\n */\nutil.xorBytes = function(s1, s2, n) {\n var s3 = '';\n var b = '';\n var t = '';\n var i = 0;\n var c = 0;\n for(; n > 0; --n, ++i) {\n b = s1.charCodeAt(i) ^ s2.charCodeAt(i);\n if(c >= 10) {\n s3 += t;\n t = '';\n c = 0;\n }\n t += String.fromCharCode(b);\n ++c;\n }\n s3 += t;\n return s3;\n};\n\n/**\n * Converts a hex string into a 'binary' encoded string of bytes.\n *\n * @param hex the hexadecimal string to convert.\n *\n * @return the binary-encoded string of bytes.\n */\nutil.hexToBytes = function(hex) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.decode instead.\"\n var rval = '';\n var i = 0;\n if(hex.length & 1 == 1) {\n // odd number of characters, convert first character alone\n i = 1;\n rval += String.fromCharCode(parseInt(hex[0], 16));\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n }\n return rval;\n};\n\n/**\n * Converts a 'binary' encoded string of bytes to hex.\n *\n * @param bytes the byte string to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.bytesToHex = function(bytes) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.encode instead.\"\n return util.createBuffer(bytes).toHex();\n};\n\n/**\n * Converts an 32-bit integer to 4-big-endian byte string.\n *\n * @param i the integer.\n *\n * @return the byte string.\n */\nutil.int32ToBytes = function(i) {\n return (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n// base64 characters, reverse mapping\nvar _base64 =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar _base64Idx = [\n/*43 -43 = 0*/\n/*'+', 1, 2, 3,'/' */\n 62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n -1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n -1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\n// base58 characters (Bitcoin alphabet)\nvar _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Base64 encodes a 'binary' encoded string of bytes.\n *\n * @param input the binary encoded string of bytes to base64-encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output.\n */\nutil.encode64 = function(input, maxline) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.encode instead.\"\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Base64 decodes a string into a 'binary' encoded string of bytes.\n *\n * @param input the base64-encoded input.\n *\n * @return the binary encoded string.\n */\nutil.decode64 = function(input) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.decode instead.\"\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n var output = '';\n var enc1, enc2, enc3, enc4;\n var i = 0;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));\n if(enc4 !== 64) {\n // decoded 3 bytes\n output += String.fromCharCode(((enc3 & 3) << 6) | enc4);\n }\n }\n }\n\n return output;\n};\n\n/**\n * Encodes the given string of characters (a standard JavaScript\n * string) as a binary encoded string where the bytes represent\n * a UTF-8 encoded string of characters. Non-ASCII characters will be\n * encoded as multiple bytes according to UTF-8.\n *\n * @param str a standard string of characters to encode.\n *\n * @return the binary encoded string.\n */\nutil.encodeUtf8 = function(str) {\n return unescape(encodeURIComponent(str));\n};\n\n/**\n * Decodes a binary encoded string that contains bytes that\n * represent a UTF-8 encoded string of characters -- into a\n * string of characters (a standard JavaScript string).\n *\n * @param str the binary encoded string to decode.\n *\n * @return the resulting standard string of characters.\n */\nutil.decodeUtf8 = function(str) {\n return decodeURIComponent(escape(str));\n};\n\n// binary encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.binary = {\n raw: {},\n hex: {},\n base64: {},\n base58: {},\n baseN : {\n encode: baseN.encode,\n decode: baseN.decode\n }\n};\n\n/**\n * Encodes a Uint8Array as a binary-encoded string. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param bytes the Uint8Array to encode.\n *\n * @return the binary-encoded string.\n */\nutil.binary.raw.encode = function(bytes) {\n return String.fromCharCode.apply(null, bytes);\n};\n\n/**\n * Decodes a binary-encoded string to a Uint8Array. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param str the binary-encoded string to decode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.raw.decode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or\n * ByteBuffer as a string of hexadecimal characters.\n *\n * @param bytes the bytes to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.binary.hex.encode = util.bytesToHex;\n\n/**\n * Decodes a hex-encoded string to a Uint8Array.\n *\n * @param hex the hexadecimal string to convert.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.hex.decode = function(hex, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(hex.length / 2));\n }\n offset = offset || 0;\n var i = 0, j = offset;\n if(hex.length & 1) {\n // odd number of characters, convert first character alone\n i = 1;\n out[j++] = parseInt(hex[0], 16);\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n out[j++] = parseInt(hex.substr(i, 2), 16);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Base64-encodes a Uint8Array.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output string.\n */\nutil.binary.base64.encode = function(input, maxline) {\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.byteLength) {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Decodes a base64-encoded string to a Uint8Array.\n *\n * @param input the base64-encoded input string.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.base64.decode = function(input, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n }\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n offset = offset || 0;\n var enc1, enc2, enc3, enc4;\n var i = 0, j = offset;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n out[j++] = (enc1 << 2) | (enc2 >> 4);\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);\n if(enc4 !== 64) {\n // decoded 3 bytes\n out[j++] = ((enc3 & 3) << 6) | enc4;\n }\n }\n }\n\n // make sure result is the exact decoded length\n return output ? (j - offset) : out.subarray(0, j);\n};\n\n// add support for base58 encoding/decoding with Bitcoin alphabet\nutil.binary.base58.encode = function(input, maxline) {\n return util.binary.baseN.encode(input, _base58, maxline);\n};\nutil.binary.base58.decode = function(input, maxline) {\n return util.binary.baseN.decode(input, _base58, maxline);\n};\n\n// text encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.text = {\n utf8: {},\n utf16: {}\n};\n\n/**\n * Encodes the given string as UTF-8 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf8.encode = function(str, output, offset) {\n str = util.encodeUtf8(str);\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-8 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf8.decode = function(bytes) {\n return util.decodeUtf8(String.fromCharCode.apply(null, bytes));\n};\n\n/**\n * Encodes the given string as UTF-16 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf16.encode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length * 2);\n }\n var view = new Uint16Array(out.buffer);\n offset = offset || 0;\n var j = offset;\n var k = offset;\n for(var i = 0; i < str.length; ++i) {\n view[k++] = str.charCodeAt(i);\n j += 2;\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-16 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf16.decode = function(bytes) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n};\n\n/**\n * Deflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true to return only raw deflate data, false to include zlib\n * header and trailer.\n *\n * @return the deflated data as a string.\n */\nutil.deflate = function(api, bytes, raw) {\n bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);\n\n // strip zlib header and trailer if necessary\n if(raw) {\n // zlib header is 2 bytes (CMF,FLG) where FLG indicates that\n // there is a 4-byte DICT (alder-32) block before the data if\n // its 5th bit is set\n var start = 2;\n var flg = bytes.charCodeAt(1);\n if(flg & 0x20) {\n start = 6;\n }\n // zlib trailer is 4 bytes of adler-32\n bytes = bytes.substring(start, bytes.length - 4);\n }\n\n return bytes;\n};\n\n/**\n * Inflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true if the incoming data has no zlib header or trailer and is\n * raw DEFLATE data.\n *\n * @return the inflated data as a string, null on error.\n */\nutil.inflate = function(api, bytes, raw) {\n // TODO: add zlib header and trailer if necessary/possible\n var rval = api.inflate(util.encode64(bytes)).rval;\n return (rval === null) ? null : util.decode64(rval);\n};\n\n/**\n * Sets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param obj the storage object, null to remove.\n */\nvar _setStorageObject = function(api, id, obj) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n var rval;\n if(obj === null) {\n rval = api.removeItem(id);\n } else {\n // json-encode and base64-encode object\n obj = util.encode64(JSON.stringify(obj));\n rval = api.setItem(id, obj);\n }\n\n // handle potential flash error\n if(typeof(rval) !== 'undefined' && rval.rval !== true) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n};\n\n/**\n * Gets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n *\n * @return the storage object entry or null if none exists.\n */\nvar _getStorageObject = function(api, id) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n // get the existing entry\n var rval = api.getItem(id);\n\n /* Note: We check api.init because we can't do (api == localStorage)\n on IE because of \"Class doesn't support Automation\" exception. Only\n the flash api has an init method so this works too, but we need a\n better solution in the future. */\n\n // flash returns item wrapped in an object, handle special case\n if(api.init) {\n if(rval.rval === null) {\n if(rval.error) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n // no error, but also no item\n rval = null;\n } else {\n rval = rval.rval;\n }\n }\n\n // handle decoding\n if(rval !== null) {\n // base64-decode and json-decode data\n rval = JSON.parse(util.decode64(rval));\n }\n\n return rval;\n};\n\n/**\n * Stores an item in local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n */\nvar _setItem = function(api, id, key, data) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj === null) {\n // create a new storage object\n obj = {};\n }\n // update key\n obj[key] = data;\n\n // set storage object\n _setStorageObject(api, id, obj);\n};\n\n/**\n * Gets an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n *\n * @return the item.\n */\nvar _getItem = function(api, id, key) {\n // get storage object\n var rval = _getStorageObject(api, id);\n if(rval !== null) {\n // return data at key\n rval = (key in rval) ? rval[key] : null;\n }\n\n return rval;\n};\n\n/**\n * Removes an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n */\nvar _removeItem = function(api, id, key) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj !== null && key in obj) {\n // remove key\n delete obj[key];\n\n // see if entry has no keys remaining\n var empty = true;\n for(var prop in obj) {\n empty = false;\n break;\n }\n if(empty) {\n // remove entry entirely if no keys are left\n obj = null;\n }\n\n // set storage object\n _setStorageObject(api, id, obj);\n }\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n */\nvar _clearItems = function(api, id) {\n _setStorageObject(api, id, null);\n};\n\n/**\n * Calls a storage function.\n *\n * @param func the function to call.\n * @param args the arguments for the function.\n * @param location the location argument.\n *\n * @return the return value from the function.\n */\nvar _callStorageFunction = function(func, args, location) {\n var rval = null;\n\n // default storage types\n if(typeof(location) === 'undefined') {\n location = ['web', 'flash'];\n }\n\n // apply storage types in order of preference\n var type;\n var done = false;\n var exception = null;\n for(var idx in location) {\n type = location[idx];\n try {\n if(type === 'flash' || type === 'both') {\n if(args[0] === null) {\n throw new Error('Flash local storage not available.');\n }\n rval = func.apply(this, args);\n done = (type === 'flash');\n }\n if(type === 'web' || type === 'both') {\n args[0] = localStorage;\n rval = func.apply(this, args);\n done = true;\n }\n } catch(ex) {\n exception = ex;\n }\n if(done) {\n break;\n }\n }\n\n if(!done) {\n throw exception;\n }\n\n return rval;\n};\n\n/**\n * Stores an item on local disk.\n *\n * The available types of local storage include 'flash', 'web', and 'both'.\n *\n * The type 'flash' refers to flash local storage (SharedObject). In order\n * to use flash local storage, the 'api' parameter must be valid. The type\n * 'web' refers to WebStorage, if supported by the browser. The type 'both'\n * refers to storing using both 'flash' and 'web', not just one or the\n * other.\n *\n * The location array should list the storage types to use in order of\n * preference:\n *\n * ['flash']: flash only storage\n * ['web']: web only storage\n * ['both']: try to store in both\n * ['flash','web']: store in flash first, but if not available, 'web'\n * ['web','flash']: store in web first, but if not available, 'flash'\n *\n * The location array defaults to: ['web', 'flash']\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n * @param location an array with the preferred types of storage to use.\n */\nutil.setItem = function(api, id, key, data, location) {\n _callStorageFunction(_setItem, arguments, location);\n};\n\n/**\n * Gets an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n *\n * @return the item.\n */\nutil.getItem = function(api, id, key, location) {\n return _callStorageFunction(_getItem, arguments, location);\n};\n\n/**\n * Removes an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n */\nutil.removeItem = function(api, id, key, location) {\n _callStorageFunction(_removeItem, arguments, location);\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface if flash is available.\n * @param id the storage ID to use.\n * @param location an array with the preferred types of storage to use.\n */\nutil.clearItems = function(api, id, location) {\n _callStorageFunction(_clearItems, arguments, location);\n};\n\n/**\n * Check if an object is empty.\n *\n * Taken from:\n * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937\n *\n * @param object the object to check.\n */\nutil.isEmpty = function(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Format with simple printf-style interpolation.\n *\n * %%: literal '%'\n * %s,%o: convert next argument into a string.\n *\n * @param format the string to format.\n * @param ... arguments to interpolate into the format string.\n */\nutil.format = function(format) {\n var re = /%./g;\n // current match\n var match;\n // current part\n var part;\n // current arg index\n var argi = 0;\n // collected parts to recombine later\n var parts = [];\n // last index found\n var last = 0;\n // loop while matches remain\n while((match = re.exec(format))) {\n part = format.substring(last, re.lastIndex - 2);\n // don't add empty strings (ie, parts between %s%s)\n if(part.length > 0) {\n parts.push(part);\n }\n last = re.lastIndex;\n // switch on % code\n var code = match[0][1];\n switch(code) {\n case 's':\n case 'o':\n // check if enough arguments were given\n if(argi < arguments.length) {\n parts.push(arguments[argi++ + 1]);\n } else {\n parts.push('');\n }\n break;\n // FIXME: do proper formating for numbers, etc\n //case 'f':\n //case 'd':\n case '%':\n parts.push('%');\n break;\n default:\n parts.push('<%' + code + '?>');\n }\n }\n // add trailing part of format string\n parts.push(format.substring(last));\n return parts.join('');\n};\n\n/**\n * Formats a number.\n *\n * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/\n */\nutil.formatNumber = function(number, decimals, dec_point, thousands_sep) {\n // http://kevin.vanzonneveld.net\n // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n // + bugfix by: Michael White (http://crestidg.com)\n // + bugfix by: Benjamin Lupton\n // + bugfix by: Allan Jensen (http://www.winternet.no)\n // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // * example 1: number_format(1234.5678, 2, '.', '');\n // * returns 1: 1234.57\n\n var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;\n var d = dec_point === undefined ? ',' : dec_point;\n var t = thousands_sep === undefined ?\n '.' : thousands_sep, s = n < 0 ? '-' : '';\n var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';\n var j = (i.length > 3) ? i.length % 3 : 0;\n return s + (j ? i.substr(0, j) + t : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + t) +\n (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n};\n\n/**\n * Formats a byte size.\n *\n * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/\n */\nutil.formatSize = function(size) {\n if(size >= 1073741824) {\n size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';\n } else if(size >= 1048576) {\n size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';\n } else if(size >= 1024) {\n size = util.formatNumber(size / 1024, 0) + ' KiB';\n } else {\n size = util.formatNumber(size, 0) + ' bytes';\n }\n return size;\n};\n\n/**\n * Converts an IPv4 or IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv4 or IPv6 address to convert.\n *\n * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't\n * be parsed.\n */\nutil.bytesFromIP = function(ip) {\n if(ip.indexOf('.') !== -1) {\n return util.bytesFromIPv4(ip);\n }\n if(ip.indexOf(':') !== -1) {\n return util.bytesFromIPv6(ip);\n }\n return null;\n};\n\n/**\n * Converts an IPv4 string representation into bytes (in network order).\n *\n * @param ip the IPv4 address to convert.\n *\n * @return the 4-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv4 = function(ip) {\n ip = ip.split('.');\n if(ip.length !== 4) {\n return null;\n }\n var b = util.createBuffer();\n for(var i = 0; i < ip.length; ++i) {\n var num = parseInt(ip[i], 10);\n if(isNaN(num)) {\n return null;\n }\n b.putByte(num);\n }\n return b.getBytes();\n};\n\n/**\n * Converts an IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv6 address to convert.\n *\n * @return the 16-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv6 = function(ip) {\n var blanks = 0;\n ip = ip.split(':').filter(function(e) {\n if(e.length === 0) ++blanks;\n return true;\n });\n var zeros = (8 - ip.length + blanks) * 2;\n var b = util.createBuffer();\n for(var i = 0; i < 8; ++i) {\n if(!ip[i] || ip[i].length === 0) {\n b.fillWithByte(0, zeros);\n zeros = 0;\n continue;\n }\n var bytes = util.hexToBytes(ip[i]);\n if(bytes.length < 2) {\n b.putByte(0);\n }\n b.putBytes(bytes);\n }\n return b.getBytes();\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation or 16-bytes into\n * an IPv6 string representation. The bytes must be in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,\n * respectively, are given, otherwise null.\n */\nutil.bytesToIP = function(bytes) {\n if(bytes.length === 4) {\n return util.bytesToIPv4(bytes);\n }\n if(bytes.length === 16) {\n return util.bytesToIPv6(bytes);\n }\n return null;\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv4 = function(bytes) {\n if(bytes.length !== 4) {\n return null;\n }\n var ip = [];\n for(var i = 0; i < bytes.length; ++i) {\n ip.push(bytes.charCodeAt(i));\n }\n return ip.join('.');\n};\n\n/**\n * Converts 16-bytes into an IPv16 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv16 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv6 = function(bytes) {\n if(bytes.length !== 16) {\n return null;\n }\n var ip = [];\n var zeroGroups = [];\n var zeroMaxGroup = 0;\n for(var i = 0; i < bytes.length; i += 2) {\n var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);\n // canonicalize zero representation\n while(hex[0] === '0' && hex !== '0') {\n hex = hex.substr(1);\n }\n if(hex === '0') {\n var last = zeroGroups[zeroGroups.length - 1];\n var idx = ip.length;\n if(!last || idx !== last.end + 1) {\n zeroGroups.push({start: idx, end: idx});\n } else {\n last.end = idx;\n if((last.end - last.start) >\n (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {\n zeroMaxGroup = zeroGroups.length - 1;\n }\n }\n }\n ip.push(hex);\n }\n if(zeroGroups.length > 0) {\n var group = zeroGroups[zeroMaxGroup];\n // only shorten group of length > 0\n if(group.end - group.start > 0) {\n ip.splice(group.start, group.end - group.start + 1, '');\n if(group.start === 0) {\n ip.unshift('');\n }\n if(group.end === 7) {\n ip.push('');\n }\n }\n }\n return ip.join(':');\n};\n\n/**\n * Estimates the number of processes that can be run concurrently. If\n * creating Web Workers, keep in mind that the main JavaScript process needs\n * its own core.\n *\n * @param options the options to use:\n * update true to force an update (not use the cached value).\n * @param callback(err, max) called once the operation completes.\n */\nutil.estimateCores = function(options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n if('cores' in util && !options.update) {\n return callback(null, util.cores);\n }\n if(typeof navigator !== 'undefined' &&\n 'hardwareConcurrency' in navigator &&\n navigator.hardwareConcurrency > 0) {\n util.cores = navigator.hardwareConcurrency;\n return callback(null, util.cores);\n }\n if(typeof Worker === 'undefined') {\n // workers not available\n util.cores = 1;\n return callback(null, util.cores);\n }\n if(typeof Blob === 'undefined') {\n // can't estimate, default to 2\n util.cores = 2;\n return callback(null, util.cores);\n }\n\n // create worker concurrency estimation code as blob\n var blobUrl = URL.createObjectURL(new Blob(['(',\n function() {\n self.addEventListener('message', function(e) {\n // run worker for 4 ms\n var st = Date.now();\n var et = st + 4;\n while(Date.now() < et);\n self.postMessage({st: st, et: et});\n });\n }.toString(),\n ')()'], {type: 'application/javascript'}));\n\n // take 5 samples using 16 workers\n sample([], 5, 16);\n\n function sample(max, samples, numWorkers) {\n if(samples === 0) {\n // get overlap average\n var avg = Math.floor(max.reduce(function(avg, x) {\n return avg + x;\n }, 0) / max.length);\n util.cores = Math.max(1, avg);\n URL.revokeObjectURL(blobUrl);\n return callback(null, util.cores);\n }\n map(numWorkers, function(err, results) {\n max.push(reduce(numWorkers, results));\n sample(max, samples - 1, numWorkers);\n });\n }\n\n function map(numWorkers, callback) {\n var workers = [];\n var results = [];\n for(var i = 0; i < numWorkers; ++i) {\n var worker = new Worker(blobUrl);\n worker.addEventListener('message', function(e) {\n results.push(e.data);\n if(results.length === numWorkers) {\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].terminate();\n }\n callback(null, results);\n }\n });\n workers.push(worker);\n }\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].postMessage(i);\n }\n }\n\n function reduce(numWorkers, results) {\n // find overlapping time windows\n var overlaps = [];\n for(var n = 0; n < numWorkers; ++n) {\n var r1 = results[n];\n var overlap = overlaps[n] = [];\n for(var i = 0; i < numWorkers; ++i) {\n if(n === i) {\n continue;\n }\n var r2 = results[i];\n if((r1.st > r2.st && r1.st < r2.et) ||\n (r2.st > r1.st && r2.st < r1.et)) {\n overlap.push(i);\n }\n }\n }\n // get maximum overlaps ... don't include overlapping worker itself\n // as the main JS process was also being scheduled during the work and\n // would have to be subtracted from the estimate anyway\n return overlaps.reduce(function(max, overlap) {\n return Math.max(max, overlap.length);\n }, 0);\n }\n};\n","/**\n * Javascript implementation of X.509 and related components (such as\n * Certification Signing Requests) of a Public Key Infrastructure.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The ASN.1 representation of an X.509v3 certificate is as follows\n * (see RFC 2459):\n *\n * Certificate ::= SEQUENCE {\n * tbsCertificate TBSCertificate,\n * signatureAlgorithm AlgorithmIdentifier,\n * signatureValue BIT STRING\n * }\n *\n * TBSCertificate ::= SEQUENCE {\n * version [0] EXPLICIT Version DEFAULT v1,\n * serialNumber CertificateSerialNumber,\n * signature AlgorithmIdentifier,\n * issuer Name,\n * validity Validity,\n * subject Name,\n * subjectPublicKeyInfo SubjectPublicKeyInfo,\n * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * extensions [3] EXPLICIT Extensions OPTIONAL\n * -- If present, version shall be v3\n * }\n *\n * Version ::= INTEGER { v1(0), v2(1), v3(2) }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * Name ::= CHOICE {\n * // only one possible choice for now\n * RDNSequence\n * }\n *\n * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\n *\n * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue\n *\n * AttributeTypeAndValue ::= SEQUENCE {\n * type AttributeType,\n * value AttributeValue\n * }\n * AttributeType ::= OBJECT IDENTIFIER\n * AttributeValue ::= ANY DEFINED BY AttributeType\n *\n * Validity ::= SEQUENCE {\n * notBefore Time,\n * notAfter Time\n * }\n *\n * Time ::= CHOICE {\n * utcTime UTCTime,\n * generalTime GeneralizedTime\n * }\n *\n * UniqueIdentifier ::= BIT STRING\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension\n *\n * Extension ::= SEQUENCE {\n * extnID OBJECT IDENTIFIER,\n * critical BOOLEAN DEFAULT FALSE,\n * extnValue OCTET STRING\n * }\n *\n * The only key algorithm currently supported for PKI is RSA.\n *\n * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.\n *\n * PKCS#10 v1.7 describes certificate signing requests:\n *\n * CertificationRequestInfo:\n *\n * CertificationRequestInfo ::= SEQUENCE {\n * version INTEGER { v1(0) } (v1,...),\n * subject Name,\n * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},\n * attributes [0] Attributes{{ CRIAttributes }}\n * }\n *\n * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}\n *\n * CRIAttributes ATTRIBUTE ::= {\n * ... -- add any locally defined attributes here -- }\n *\n * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {\n * type ATTRIBUTE.&id({IOSet}),\n * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})\n * }\n *\n * CertificationRequest ::= SEQUENCE {\n * certificationRequestInfo CertificationRequestInfo,\n * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},\n * signature BIT STRING\n * }\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./mgf');\nrequire('./oids');\nrequire('./pem');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\nvar oids = pki.oids;\n\n// short name OID mappings\nvar _shortNames = {};\n_shortNames['CN'] = oids['commonName'];\n_shortNames['commonName'] = 'CN';\n_shortNames['C'] = oids['countryName'];\n_shortNames['countryName'] = 'C';\n_shortNames['L'] = oids['localityName'];\n_shortNames['localityName'] = 'L';\n_shortNames['ST'] = oids['stateOrProvinceName'];\n_shortNames['stateOrProvinceName'] = 'ST';\n_shortNames['O'] = oids['organizationName'];\n_shortNames['organizationName'] = 'O';\n_shortNames['OU'] = oids['organizationalUnitName'];\n_shortNames['organizationalUnitName'] = 'OU';\n_shortNames['E'] = oids['emailAddress'];\n_shortNames['emailAddress'] = 'E';\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator;\n\n// validator for an X.509v3 certificate\nvar x509CertificateValidator = {\n name: 'Certificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'tbsCertificate',\n value: [{\n name: 'Certificate.TBSCertificate.version',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.version.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certVersion'\n }]\n }, {\n name: 'Certificate.TBSCertificate.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certSerialNumber'\n }, {\n name: 'Certificate.TBSCertificate.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate.signature.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certinfoSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certinfoSignatureParams'\n }]\n }, {\n name: 'Certificate.TBSCertificate.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certIssuer'\n }, {\n name: 'Certificate.TBSCertificate.validity',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n // Note: UTC and generalized times may both appear so the capture\n // names are based on their detected order, the names used below\n // are only for the common case, which validity time really means\n // \"notBefore\" and which means \"notAfter\" will be determined by order\n value: [{\n // notBefore (Time) (UTC time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity1UTCTime'\n }, {\n // notBefore (Time) (generalized time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity2GeneralizedTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity3UTCTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity4GeneralizedTime'\n }]\n }, {\n // Name (subject) (RDNSequence)\n name: 'Certificate.TBSCertificate.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n // issuerUniqueID (optional)\n name: 'Certificate.TBSCertificate.issuerUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.issuerUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certIssuerUniqueId'\n }]\n }, {\n // subjectUniqueID (optional)\n name: 'Certificate.TBSCertificate.subjectUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.subjectUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certSubjectUniqueId'\n }]\n }, {\n // Extensions (optional)\n name: 'Certificate.TBSCertificate.extensions',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n constructed: true,\n captureAsn1: 'certExtensions',\n optional: true\n }]\n }, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'Certificate.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'Certificate.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certSignatureParams'\n }]\n }, {\n // SignatureValue\n name: 'Certificate.signatureValue',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'certSignature'\n }]\n};\n\nvar rsassaPssParameterValidator = {\n name: 'rsapss',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'hashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }, {\n name: 'rsapss.maskGenAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenOid'\n }, {\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenHashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }]\n }, {\n name: 'rsapss.saltLength',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n optional: true,\n value: [{\n name: 'rsapss.saltLength.saltLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'saltLength'\n }]\n }, {\n name: 'rsapss.trailerField',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n optional: true,\n value: [{\n name: 'rsapss.trailer.trailer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'trailer'\n }]\n }]\n};\n\n// validator for a CertificationRequestInfo structure\nvar certificationRequestInfoValidator = {\n name: 'CertificationRequestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfo',\n value: [{\n name: 'CertificationRequestInfo.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certificationRequestInfoVersion'\n }, {\n // Name (subject) (RDNSequence)\n name: 'CertificationRequestInfo.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfoSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'certificationRequestInfoAttributes',\n value: [{\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertificationRequestInfo.attributes.type',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false\n }, {\n name: 'CertificationRequestInfo.attributes.value',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true\n }]\n }]\n }]\n};\n\n// validator for a CertificationRequest structure\nvar certificationRequestValidator = {\n name: 'CertificationRequest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'csr',\n value: [\n certificationRequestInfoValidator, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'CertificationRequest.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'CertificationRequest.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'csrSignatureOid'\n }, {\n name: 'CertificationRequest.signatureAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'csrSignatureParams'\n }]\n }, {\n // signature\n name: 'CertificationRequest.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'csrSignature'\n }\n ]\n};\n\n/**\n * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName\n * sets into an array with objects that have type and value properties.\n *\n * @param rdn the RDNSequence to convert.\n * @param md a message digest to append type and value to if provided.\n */\npki.RDNAttributesAsArray = function(rdn, md) {\n var rval = [];\n\n // each value in 'rdn' in is a SET of RelativeDistinguishedName\n var set, attr, obj;\n for(var si = 0; si < rdn.value.length; ++si) {\n // get the RelativeDistinguishedName set\n set = rdn.value[si];\n\n // each value in the SET is an AttributeTypeAndValue sequence\n // containing first a type (an OID) and second a value (defined by\n // the OID)\n for(var i = 0; i < set.value.length; ++i) {\n obj = {};\n attr = set.value[i];\n obj.type = asn1.derToOid(attr.value[0].value);\n obj.value = attr.value[1].value;\n obj.valueTagClass = attr.value[1].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n if(md) {\n md.update(obj.type);\n md.update(obj.value);\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Converts ASN.1 CRIAttributes into an array with objects that have type and\n * value properties.\n *\n * @param attributes the CRIAttributes to convert.\n */\npki.CRIAttributesAsArray = function(attributes) {\n var rval = [];\n\n // each value in 'attributes' in is a SEQUENCE with an OID and a SET\n for(var si = 0; si < attributes.length; ++si) {\n // get the attribute sequence\n var seq = attributes[si];\n\n // each value in the SEQUENCE containing first a type (an OID) and\n // second a set of values (defined by the OID)\n var type = asn1.derToOid(seq.value[0].value);\n var values = seq.value[1].value;\n for(var vi = 0; vi < values.length; ++vi) {\n var obj = {};\n obj.type = type;\n obj.value = values[vi].value;\n obj.valueTagClass = values[vi].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n // parse extensions\n if(obj.type === oids.extensionRequest) {\n obj.extensions = [];\n for(var ei = 0; ei < obj.value.length; ++ei) {\n obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));\n }\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Gets an issuer or subject attribute from its name, type, or short name.\n *\n * @param obj the issuer or subject object.\n * @param options a short name string or an object with:\n * shortName the short name for the attribute.\n * name the name for the attribute.\n * type the type for the attribute.\n *\n * @return the attribute.\n */\nfunction _getAttribute(obj, options) {\n if(typeof options === 'string') {\n options = {shortName: options};\n }\n\n var rval = null;\n var attr;\n for(var i = 0; rval === null && i < obj.attributes.length; ++i) {\n attr = obj.attributes[i];\n if(options.type && options.type === attr.type) {\n rval = attr;\n } else if(options.name && options.name === attr.name) {\n rval = attr;\n } else if(options.shortName && options.shortName === attr.shortName) {\n rval = attr;\n }\n }\n return rval;\n}\n\n/**\n * Converts signature parameters from ASN.1 structure.\n *\n * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had\n * no parameters.\n *\n * RSASSA-PSS-params ::= SEQUENCE {\n * hashAlgorithm [0] HashAlgorithm DEFAULT\n * sha1Identifier,\n * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT\n * mgf1SHA1Identifier,\n * saltLength [2] INTEGER DEFAULT 20,\n * trailerField [3] INTEGER DEFAULT 1\n * }\n *\n * HashAlgorithm ::= AlgorithmIdentifier\n *\n * MaskGenAlgorithm ::= AlgorithmIdentifier\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * @param oid The OID specifying the signature algorithm\n * @param obj The ASN.1 structure holding the parameters\n * @param fillDefaults Whether to use return default values where omitted\n * @return signature parameter object\n */\nvar _readSignatureParameters = function(oid, obj, fillDefaults) {\n var params = {};\n\n if(oid !== oids['RSASSA-PSS']) {\n return params;\n }\n\n if(fillDefaults) {\n params = {\n hash: {\n algorithmOid: oids['sha1']\n },\n mgf: {\n algorithmOid: oids['mgf1'],\n hash: {\n algorithmOid: oids['sha1']\n }\n },\n saltLength: 20\n };\n }\n\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {\n var error = new Error('Cannot read RSASSA-PSS parameter block.');\n error.errors = errors;\n throw error;\n }\n\n if(capture.hashOid !== undefined) {\n params.hash = params.hash || {};\n params.hash.algorithmOid = asn1.derToOid(capture.hashOid);\n }\n\n if(capture.maskGenOid !== undefined) {\n params.mgf = params.mgf || {};\n params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);\n params.mgf.hash = params.mgf.hash || {};\n params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);\n }\n\n if(capture.saltLength !== undefined) {\n params.saltLength = capture.saltLength.charCodeAt(0);\n }\n\n return params;\n};\n\n/**\n * Create signature digest for OID.\n *\n * @param options\n * signatureOid: the OID specifying the signature algorithm.\n * type: a human readable type for error messages\n * @return a created md instance. throws if unknown oid.\n */\nvar _createSignatureDigest = function(options) {\n switch(oids[options.signatureOid]) {\n case 'sha1WithRSAEncryption':\n // deprecated alias\n case 'sha1WithRSASignature':\n return forge.md.sha1.create();\n case 'md5WithRSAEncryption':\n return forge.md.md5.create();\n case 'sha256WithRSAEncryption':\n return forge.md.sha256.create();\n case 'sha384WithRSAEncryption':\n return forge.md.sha384.create();\n case 'sha512WithRSAEncryption':\n return forge.md.sha512.create();\n case 'RSASSA-PSS':\n return forge.md.sha256.create();\n default:\n var error = new Error(\n 'Could not compute ' + options.type + ' digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = options.signatureOid;\n throw error;\n }\n};\n\n/**\n * Verify signature on certificate or CSR.\n *\n * @param options:\n * certificate the certificate or CSR to verify.\n * md the signature digest.\n * signature the signature\n * @return a created md instance. throws if unknown oid.\n */\nvar _verifySignature = function(options) {\n var cert = options.certificate;\n var scheme;\n\n switch(cert.signatureOid) {\n case oids.sha1WithRSAEncryption:\n // deprecated alias\n case oids.sha1WithRSASignature:\n /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = cert.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[cert.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = cert.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[cert.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported RSASSA-PSS hash function.');\n error.oid = cert.signatureParameters.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n scheme = forge.pss.create(\n forge.md[hash].create(), mgf, cert.signatureParameters.saltLength\n );\n break;\n }\n\n // verify signature on cert using public key\n return cert.publicKey.verify(\n options.md.digest().getBytes(), options.signature, scheme\n );\n};\n\n/**\n * Converts an X.509 certificate from PEM format.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. This will scan the TBSCertificate part of the ASN.1\n * object while it is converted so it doesn't need to be converted back\n * to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certificate.\n */\npki.certificateFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error(\n 'Could not convert certificate from PEM; PEM header type ' +\n 'is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or \"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error(\n 'Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificateFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts an X.509 certificate to PEM format.\n *\n * @param cert the certificate.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certificate.\n */\npki.certificateToPem = function(cert, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE',\n body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key from PEM format.\n *\n * @param pem the PEM-formatted public key.\n *\n * @return the public key.\n */\npki.publicKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {\n var error = new Error('Could not convert public key from PEM; PEM header ' +\n 'type is not \"PUBLIC KEY\" or \"RSA PUBLIC KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert public key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.publicKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key to PEM format (using an RSAPublicKey).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToRSAPublicKeyPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Gets a fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.sha1).\n * [type] the type of fingerprint, such as 'RSAPublicKey',\n * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\npki.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.sha1.create();\n var type = options.type || 'RSAPublicKey';\n\n var bytes;\n switch(type) {\n case 'RSAPublicKey':\n bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();\n break;\n case 'SubjectPublicKeyInfo':\n bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();\n break;\n default:\n throw new Error('Unknown fingerprint type \"' + options.type + '\".');\n }\n\n // hash public key bytes\n md.start();\n md.update(bytes);\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from PEM format.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. This will scan the CertificationRequestInfo part of\n * the ASN.1 object while it is converted so it doesn't need to be converted\n * back to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE REQUEST') {\n var error = new Error('Could not convert certification request from PEM; ' +\n 'PEM header type is not \"CERTIFICATE REQUEST\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certification request from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificationRequestFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) to PEM format.\n *\n * @param csr the certification request.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certification request.\n */\npki.certificationRequestToPem = function(csr, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE REQUEST',\n body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Creates an empty X.509v3 RSA certificate.\n *\n * @return the certificate.\n */\npki.createCertificate = function() {\n var cert = {};\n cert.version = 0x02;\n cert.serialNumber = '00';\n cert.signatureOid = null;\n cert.signature = null;\n cert.siginfo = {};\n cert.siginfo.algorithmOid = null;\n cert.validity = {};\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n\n cert.issuer = {};\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = [];\n cert.issuer.hash = null;\n\n cert.subject = {};\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = [];\n cert.subject.hash = null;\n\n cert.extensions = [];\n cert.publicKey = null;\n cert.md = null;\n\n /**\n * Sets the subject of this certificate.\n *\n * @param attrs the array of subject attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setSubject = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.subject.attributes = attrs;\n delete cert.subject.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.subject.uniqueId = uniqueId;\n }\n cert.subject.hash = null;\n };\n\n /**\n * Sets the issuer of this certificate.\n *\n * @param attrs the array of issuer attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setIssuer = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.issuer.attributes = attrs;\n delete cert.issuer.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.issuer.uniqueId = uniqueId;\n }\n cert.issuer.hash = null;\n };\n\n /**\n * Sets the extensions of this certificate.\n *\n * @param exts the array of extensions to use.\n */\n cert.setExtensions = function(exts) {\n for(var i = 0; i < exts.length; ++i) {\n _fillMissingExtensionFields(exts[i], {cert: cert});\n }\n // set new extensions\n cert.extensions = exts;\n };\n\n /**\n * Gets an extension by its name or id.\n *\n * @param options the name to use or an object with:\n * name the name to use.\n * id the id to use.\n *\n * @return the extension or null if not found.\n */\n cert.getExtension = function(options) {\n if(typeof options === 'string') {\n options = {name: options};\n }\n\n var rval = null;\n var ext;\n for(var i = 0; rval === null && i < cert.extensions.length; ++i) {\n ext = cert.extensions[i];\n if(options.id && ext.id === options.id) {\n rval = ext;\n } else if(options.name && ext.name === options.name) {\n rval = ext;\n }\n }\n return rval;\n };\n\n /**\n * Signs this certificate using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n cert.sign = function(key, md) {\n // TODO: get signature OID from private key\n cert.md = md || forge.md.sha1.create();\n var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = cert.md.algorithm;\n throw error;\n }\n cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;\n\n // get TBSCertificate, convert to DER\n cert.tbsCertificate = pki.getTBSCertificate(cert);\n var bytes = asn1.toDer(cert.tbsCertificate);\n\n // digest and sign\n cert.md.update(bytes.getBytes());\n cert.signature = key.sign(cert.md);\n };\n\n /**\n * Attempts verify the signature on the passed certificate using this\n * certificate's public key.\n *\n * @param child the certificate to verify.\n *\n * @return true if verified, false if not.\n */\n cert.verify = function(child) {\n var rval = false;\n\n if(!cert.issued(child)) {\n var issuer = child.issuer;\n var subject = cert.subject;\n var error = new Error(\n 'The parent certificate did not issue the given child ' +\n 'certificate; the child certificate\\'s issuer does not match the ' +\n 'parent\\'s subject.');\n error.expectedIssuer = subject.attributes;\n error.actualIssuer = issuer.attributes;\n throw error;\n }\n\n var md = child.md;\n if(md === null) {\n // create digest for OID signature types\n md = _createSignatureDigest({\n signatureOid: child.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);\n var bytes = asn1.toDer(tbsCertificate);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: cert, md: md, signature: child.signature\n });\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's issuer matches the passed\n * certificate's subject. Note that no signature check is performed.\n *\n * @param parent the certificate to check.\n *\n * @return true if this certificate's issuer matches the passed certificate's\n * subject.\n */\n cert.isIssuer = function(parent) {\n var rval = false;\n\n var i = cert.issuer;\n var s = parent.subject;\n\n // compare hashes if present\n if(i.hash && s.hash) {\n rval = (i.hash === s.hash);\n } else if(i.attributes.length === s.attributes.length) {\n // all attributes are the same so issuer matches subject\n rval = true;\n var iattr, sattr;\n for(var n = 0; rval && n < i.attributes.length; ++n) {\n iattr = i.attributes[n];\n sattr = s.attributes[n];\n if(iattr.type !== sattr.type || iattr.value !== sattr.value) {\n // attribute mismatch\n rval = false;\n }\n }\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's subject matches the issuer of the\n * given certificate). Note that not signature check is performed.\n *\n * @param child the certificate to check.\n *\n * @return true if this certificate's subject matches the passed\n * certificate's issuer.\n */\n cert.issued = function(child) {\n return child.isIssuer(cert);\n };\n\n /**\n * Generates the subjectKeyIdentifier for this certificate as byte buffer.\n *\n * @return the subjectKeyIdentifier for this certificate as byte buffer.\n */\n cert.generateSubjectKeyIdentifier = function() {\n /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:\n\n (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the\n value of the BIT STRING subjectPublicKey (excluding the tag,\n length, and number of unused bits).\n\n (2) The keyIdentifier is composed of a four bit type field with\n the value 0100 followed by the least significant 60 bits of the\n SHA-1 hash of the value of the BIT STRING subjectPublicKey\n (excluding the tag, length, and number of unused bit string bits).\n */\n\n // skipping the tag, length, and number of unused bits is the same\n // as just using the RSAPublicKey (for RSA keys, which are the\n // only ones supported)\n return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});\n };\n\n /**\n * Verifies the subjectKeyIdentifier extension value for this certificate\n * against its public key. If no extension is found, false will be\n * returned.\n *\n * @return true if verified, false if not.\n */\n cert.verifySubjectKeyIdentifier = function() {\n var oid = oids['subjectKeyIdentifier'];\n for(var i = 0; i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.id === oid) {\n var ski = cert.generateSubjectKeyIdentifier().getBytes();\n return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);\n }\n }\n return false;\n };\n\n return cert;\n};\n\n/**\n * Converts an X.509v3 RSA certificate from an ASN.1 object.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1\n * object needs to be scanned before the cert object is created.\n *\n * @param obj the asn1 representation of an X.509v3 RSA certificate.\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certificate.\n */\npki.certificateFromAsn1 = function(obj, computeHash) {\n // validate certificate and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {\n var error = new Error('Cannot read X.509 certificate. ' +\n 'ASN.1 object is not an X509v3 Certificate.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certificate\n var cert = pki.createCertificate();\n cert.version = capture.certVersion ?\n capture.certVersion.charCodeAt(0) : 0;\n var serial = forge.util.createBuffer(capture.certSerialNumber);\n cert.serialNumber = serial.toHex();\n cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);\n cert.signatureParameters = _readSignatureParameters(\n cert.signatureOid, capture.certSignatureParams, true);\n cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);\n cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,\n capture.certinfoSignatureParams, false);\n cert.signature = capture.certSignature;\n\n var validity = [];\n if(capture.certValidity1UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));\n }\n if(capture.certValidity2GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity2GeneralizedTime));\n }\n if(capture.certValidity3UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));\n }\n if(capture.certValidity4GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity4GeneralizedTime));\n }\n if(validity.length > 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; more ' +\n 'than two times were provided in the certificate.');\n }\n if(validity.length < 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; they ' +\n 'were not provided as either UTCTime or GeneralizedTime.');\n }\n cert.validity.notBefore = validity[0];\n cert.validity.notAfter = validity[1];\n\n // keep TBSCertificate to preserve signature when exporting\n cert.tbsCertificate = capture.tbsCertificate;\n\n if(computeHash) {\n // create digest for OID signature type\n cert.md = _createSignatureDigest({\n signatureOid: cert.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var bytes = asn1.toDer(cert.tbsCertificate);\n cert.md.update(bytes.getBytes());\n }\n\n // handle issuer, build issuer message digest\n var imd = forge.md.sha1.create();\n var ibytes = asn1.toDer(capture.certIssuer);\n imd.update(ibytes.getBytes());\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);\n if(capture.certIssuerUniqueId) {\n cert.issuer.uniqueId = capture.certIssuerUniqueId;\n }\n cert.issuer.hash = imd.digest().toHex();\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n var sbytes = asn1.toDer(capture.certSubject);\n smd.update(sbytes.getBytes());\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);\n if(capture.certSubjectUniqueId) {\n cert.subject.uniqueId = capture.certSubjectUniqueId;\n }\n cert.subject.hash = smd.digest().toHex();\n\n // handle extensions\n if(capture.certExtensions) {\n cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);\n } else {\n cert.extensions = [];\n }\n\n // convert RSA public key from ASN.1\n cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n return cert;\n};\n\n/**\n * Converts an ASN.1 extensions object (with extension sequences as its\n * values) into an array of extension objects with types and values.\n *\n * Supported extensions:\n *\n * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }\n * KeyUsage ::= BIT STRING {\n * digitalSignature (0),\n * nonRepudiation (1),\n * keyEncipherment (2),\n * dataEncipherment (3),\n * keyAgreement (4),\n * keyCertSign (5),\n * cRLSign (6),\n * encipherOnly (7),\n * decipherOnly (8)\n * }\n *\n * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }\n * BasicConstraints ::= SEQUENCE {\n * cA BOOLEAN DEFAULT FALSE,\n * pathLenConstraint INTEGER (0..MAX) OPTIONAL\n * }\n *\n * subjectAltName EXTENSION ::= {\n * SYNTAX GeneralNames\n * IDENTIFIED BY id-ce-subjectAltName\n * }\n *\n * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName\n *\n * GeneralName ::= CHOICE {\n * otherName [0] INSTANCE OF OTHER-NAME,\n * rfc822Name [1] IA5String,\n * dNSName [2] IA5String,\n * x400Address [3] ORAddress,\n * directoryName [4] Name,\n * ediPartyName [5] EDIPartyName,\n * uniformResourceIdentifier [6] IA5String,\n * IPAddress [7] OCTET STRING,\n * registeredID [8] OBJECT IDENTIFIER\n * }\n *\n * OTHER-NAME ::= TYPE-IDENTIFIER\n *\n * EDIPartyName ::= SEQUENCE {\n * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,\n * partyName [1] DirectoryString {ub-name}\n * }\n *\n * @param exts the extensions ASN.1 with extension sequences to parse.\n *\n * @return the array.\n */\npki.certificateExtensionsFromAsn1 = function(exts) {\n var rval = [];\n for(var i = 0; i < exts.value.length; ++i) {\n // get extension sequence\n var extseq = exts.value[i];\n for(var ei = 0; ei < extseq.value.length; ++ei) {\n rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));\n }\n }\n\n return rval;\n};\n\n/**\n * Parses a single certificate extension from ASN.1.\n *\n * @param ext the extension in ASN.1 format.\n *\n * @return the parsed extension as an object.\n */\npki.certificateExtensionFromAsn1 = function(ext) {\n // an extension has:\n // [0] extnID OBJECT IDENTIFIER\n // [1] critical BOOLEAN DEFAULT FALSE\n // [2] extnValue OCTET STRING\n var e = {};\n e.id = asn1.derToOid(ext.value[0].value);\n e.critical = false;\n if(ext.value[1].type === asn1.Type.BOOLEAN) {\n e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);\n e.value = ext.value[2].value;\n } else {\n e.value = ext.value[1].value;\n }\n // if the oid is known, get its name\n if(e.id in oids) {\n e.name = oids[e.id];\n\n // handle key usage\n if(e.name === 'keyUsage') {\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n var b3 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;\n }\n // set flags\n e.digitalSignature = (b2 & 0x80) === 0x80;\n e.nonRepudiation = (b2 & 0x40) === 0x40;\n e.keyEncipherment = (b2 & 0x20) === 0x20;\n e.dataEncipherment = (b2 & 0x10) === 0x10;\n e.keyAgreement = (b2 & 0x08) === 0x08;\n e.keyCertSign = (b2 & 0x04) === 0x04;\n e.cRLSign = (b2 & 0x02) === 0x02;\n e.encipherOnly = (b2 & 0x01) === 0x01;\n e.decipherOnly = (b3 & 0x80) === 0x80;\n } else if(e.name === 'basicConstraints') {\n // handle basic constraints\n // get value as SEQUENCE\n var ev = asn1.fromDer(e.value);\n // get cA BOOLEAN flag (defaults to false)\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {\n e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);\n } else {\n e.cA = false;\n }\n // get path length constraint\n var value = null;\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {\n value = ev.value[0].value;\n } else if(ev.value.length > 1) {\n value = ev.value[1].value;\n }\n if(value !== null) {\n e.pathLenConstraint = asn1.derToInteger(value);\n }\n } else if(e.name === 'extKeyUsage') {\n // handle extKeyUsage\n // value is a SEQUENCE of OIDs\n var ev = asn1.fromDer(e.value);\n for(var vi = 0; vi < ev.value.length; ++vi) {\n var oid = asn1.derToOid(ev.value[vi].value);\n if(oid in oids) {\n e[oids[oid]] = true;\n } else {\n e[oid] = true;\n }\n }\n } else if(e.name === 'nsCertType') {\n // handle nsCertType\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n }\n // set flags\n e.client = (b2 & 0x80) === 0x80;\n e.server = (b2 & 0x40) === 0x40;\n e.email = (b2 & 0x20) === 0x20;\n e.objsign = (b2 & 0x10) === 0x10;\n e.reserved = (b2 & 0x08) === 0x08;\n e.sslCA = (b2 & 0x04) === 0x04;\n e.emailCA = (b2 & 0x02) === 0x02;\n e.objCA = (b2 & 0x01) === 0x01;\n } else if(\n e.name === 'subjectAltName' ||\n e.name === 'issuerAltName') {\n // handle subjectAltName/issuerAltName\n e.altNames = [];\n\n // ev is a SYNTAX SEQUENCE\n var gn;\n var ev = asn1.fromDer(e.value);\n for(var n = 0; n < ev.value.length; ++n) {\n // get GeneralName\n gn = ev.value[n];\n\n var altName = {\n type: gn.type,\n value: gn.value\n };\n e.altNames.push(altName);\n\n // Note: Support for types 1,2,6,7,8\n switch(gn.type) {\n // rfc822Name\n case 1:\n // dNSName\n case 2:\n // uniformResourceIdentifier (URI)\n case 6:\n break;\n // IPAddress\n case 7:\n // convert to IPv4/IPv6 string representation\n altName.ip = forge.util.bytesToIP(gn.value);\n break;\n // registeredID\n case 8:\n altName.oid = asn1.derToOid(gn.value);\n break;\n default:\n // unsupported\n }\n }\n } else if(e.name === 'subjectKeyIdentifier') {\n // value is an OCTETSTRING w/the hash of the key-type specific\n // public key structure (eg: RSAPublicKey)\n var ev = asn1.fromDer(e.value);\n e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);\n }\n }\n return e;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the CertificationRequestInfo part of the\n * ASN.1 object needs to be scanned before the csr object is created.\n *\n * @param obj the asn1 representation of a PKCS#10 certification request (CSR).\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromAsn1 = function(obj, computeHash) {\n // validate certification request and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#10 certificate request. ' +\n 'ASN.1 object is not a PKCS#10 CertificationRequest.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certification request\n var csr = pki.createCertificationRequest();\n csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;\n csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.signatureParameters = _readSignatureParameters(\n csr.signatureOid, capture.csrSignatureParams, true);\n csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.siginfo.parameters = _readSignatureParameters(\n csr.siginfo.algorithmOid, capture.csrSignatureParams, false);\n csr.signature = capture.csrSignature;\n\n // keep CertificationRequestInfo to preserve signature when exporting\n csr.certificationRequestInfo = capture.certificationRequestInfo;\n\n if(computeHash) {\n // create digest for OID signature type\n csr.md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n csr.md.update(bytes.getBytes());\n }\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = pki.RDNAttributesAsArray(\n capture.certificationRequestInfoSubject, smd);\n csr.subject.hash = smd.digest().toHex();\n\n // convert RSA public key from ASN.1\n csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n // convert attributes from ASN.1\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.attributes = pki.CRIAttributesAsArray(\n capture.certificationRequestInfoAttributes || []);\n\n return csr;\n};\n\n/**\n * Creates an empty certification request (a CSR or certificate signing\n * request). Once created, its public key and attributes can be set and then\n * it can be signed.\n *\n * @return the empty certification request.\n */\npki.createCertificationRequest = function() {\n var csr = {};\n csr.version = 0x00;\n csr.signatureOid = null;\n csr.signature = null;\n csr.siginfo = {};\n csr.siginfo.algorithmOid = null;\n\n csr.subject = {};\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = [];\n csr.subject.hash = null;\n\n csr.publicKey = null;\n csr.attributes = [];\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.md = null;\n\n /**\n * Sets the subject of this certification request.\n *\n * @param attrs the array of subject attributes to use.\n */\n csr.setSubject = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.subject.attributes = attrs;\n csr.subject.hash = null;\n };\n\n /**\n * Sets the attributes of this certification request.\n *\n * @param attrs the array of attributes to use.\n */\n csr.setAttributes = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.attributes = attrs;\n };\n\n /**\n * Signs this certification request using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n csr.sign = function(key, md) {\n // TODO: get signature OID from private key\n csr.md = md || forge.md.sha1.create();\n var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = csr.md.algorithm;\n throw error;\n }\n csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;\n\n // get CertificationRequestInfo, convert to DER\n csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n\n // digest and sign\n csr.md.update(bytes.getBytes());\n csr.signature = key.sign(csr.md);\n };\n\n /**\n * Attempts verify the signature on the passed certification request using\n * its public key.\n *\n * A CSR that has been exported to a file in PEM format can be verified using\n * OpenSSL using this command:\n *\n * openssl req -in -verify -noout -text\n *\n * @return true if verified, false if not.\n */\n csr.verify = function() {\n var rval = false;\n\n var md = csr.md;\n if(md === null) {\n md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(cri);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: csr, md: md, signature: csr.signature\n });\n }\n\n return rval;\n };\n\n return csr;\n};\n\n/**\n * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.\n *\n * @param obj the subject or issuer (distinguished name).\n *\n * @return the ASN.1 RDNSequence.\n */\nfunction _dnToAsn1(obj) {\n // create an empty RDNSequence\n var rval = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // iterate over attributes\n var attr, set;\n var attrs = obj.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.PRINTABLESTRING;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n // FIXME: handle more encodings\n }\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n // AttributeValue\n asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)\n ])\n ]);\n rval.value.push(set);\n }\n\n return rval;\n}\n\n/**\n * Gets all printable attributes (typically of an issuer or subject) in a\n * simplified JSON format for display.\n *\n * @param attrs the attributes.\n *\n * @return the JSON for display.\n */\nfunction _getAttributesAsJson(attrs) {\n var rval = {};\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n if(attr.shortName && (\n attr.valueTagClass === asn1.Type.UTF8 ||\n attr.valueTagClass === asn1.Type.PRINTABLESTRING ||\n attr.valueTagClass === asn1.Type.IA5STRING)) {\n var value = attr.value;\n if(attr.valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(attr.value);\n }\n if(!(attr.shortName in rval)) {\n rval[attr.shortName] = value;\n } else if(forge.util.isArray(rval[attr.shortName])) {\n rval[attr.shortName].push(value);\n } else {\n rval[attr.shortName] = [rval[attr.shortName], value];\n }\n }\n }\n return rval;\n}\n\n/**\n * Fills in missing fields in attributes.\n *\n * @param attrs the attributes to fill missing fields in.\n */\nfunction _fillMissingFields(attrs) {\n var attr;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n\n // populate missing name\n if(typeof attr.name === 'undefined') {\n if(attr.type && attr.type in pki.oids) {\n attr.name = pki.oids[attr.type];\n } else if(attr.shortName && attr.shortName in _shortNames) {\n attr.name = pki.oids[_shortNames[attr.shortName]];\n }\n }\n\n // populate missing type (OID)\n if(typeof attr.type === 'undefined') {\n if(attr.name && attr.name in pki.oids) {\n attr.type = pki.oids[attr.name];\n } else {\n var error = new Error('Attribute type not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n\n // populate missing shortname\n if(typeof attr.shortName === 'undefined') {\n if(attr.name && attr.name in _shortNames) {\n attr.shortName = _shortNames[attr.name];\n }\n }\n\n // convert extensions to value\n if(attr.type === oids.extensionRequest) {\n attr.valueConstructed = true;\n attr.valueTagClass = asn1.Type.SEQUENCE;\n if(!attr.value && attr.extensions) {\n attr.value = [];\n for(var ei = 0; ei < attr.extensions.length; ++ei) {\n attr.value.push(pki.certificateExtensionToAsn1(\n _fillMissingExtensionFields(attr.extensions[ei])));\n }\n }\n }\n\n if(typeof attr.value === 'undefined') {\n var error = new Error('Attribute value not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n}\n\n/**\n * Fills in missing fields in certificate extensions.\n *\n * @param e the extension.\n * @param [options] the options to use.\n * [cert] the certificate the extensions are for.\n *\n * @return the extension.\n */\nfunction _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'nsComment' && options.cert) {\n // sanity check value is ASCII (req'd) and not too big\n if(!(/^[\\x00-\\x7F]*$/.test(e.comment)) ||\n (e.comment.length < 1) || (e.comment.length > 128)) {\n throw new Error('Invalid \"nsComment\" content.');\n }\n // IA5STRING opaque comment\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if(e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}\n\n/**\n * Convert signature parameters object to ASN.1\n *\n * @param {String} oid Signature algorithm OID\n * @param params The signature parametrs object\n * @return ASN.1 object representing signature parameters\n */\nfunction _signatureParametersToAsn1(oid, params) {\n switch(oid) {\n case oids['RSASSA-PSS']:\n var parts = [];\n\n if(params.hash.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]));\n }\n\n if(params.mgf.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ])\n ]));\n }\n\n if(params.saltLength !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(params.saltLength).getBytes())\n ]));\n }\n\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);\n\n default:\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');\n }\n}\n\n/**\n * Converts a certification request's attributes to an ASN.1 set of\n * CRIAttributes.\n *\n * @param csr certification request.\n *\n * @return the ASN.1 set of CRIAttributes.\n */\nfunction _CRIAttributesToAsn1(csr) {\n // create an empty context-specific container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // no attributes, return empty container\n if(csr.attributes.length === 0) {\n return rval;\n }\n\n // each attribute has a sequence with a type and a set of values\n var attrs = csr.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.UTF8;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n }\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n var valueConstructed = false;\n if('valueConstructed' in attr) {\n valueConstructed = attr.valueConstructed;\n }\n // FIXME: handle more encodings\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n asn1.create(\n asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)\n ])\n ]);\n rval.value.push(seq);\n }\n\n return rval;\n}\n\nvar jan_1_1950 = new Date('1950-01-01T00:00:00Z');\nvar jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n\n/**\n * Converts a Date object to ASN.1\n * Handles the different format before and after 1st January 2050\n *\n * @param date date object.\n *\n * @return the ASN.1 object representing the date.\n */\nfunction _dateToAsn1(date) {\n if(date >= jan_1_1950 && date < jan_1_2050) {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n}\n\n/**\n * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.\n *\n * @param cert the certificate.\n *\n * @return the asn1 TBSCertificate.\n */\npki.getTBSCertificate = function(cert) {\n // TBSCertificate\n var notBefore = _dateToAsn1(cert.validity.notBefore);\n var notAfter = _dateToAsn1(cert.validity.notAfter);\n var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // integer\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(cert.version).getBytes())\n ]),\n // serialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(cert.serialNumber)),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(\n cert.siginfo.algorithmOid, cert.siginfo.parameters)\n ]),\n // issuer\n _dnToAsn1(cert.issuer),\n // validity\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n notBefore,\n notAfter\n ]),\n // subject\n _dnToAsn1(cert.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(cert.publicKey)\n ]);\n\n if(cert.issuer.uniqueId) {\n // issuerUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.issuer.uniqueId\n )\n ])\n );\n }\n if(cert.subject.uniqueId) {\n // subjectUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.subject.uniqueId\n )\n ])\n );\n }\n\n if(cert.extensions.length > 0) {\n // extensions (optional)\n tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));\n }\n\n return tbs;\n};\n\n/**\n * Gets the ASN.1 CertificationRequestInfo part of a\n * PKCS#10 CertificationRequest.\n *\n * @param csr the certification request.\n *\n * @return the asn1 CertificationRequestInfo.\n */\npki.getCertificationRequestInfo = function(csr) {\n // CertificationRequestInfo\n var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(csr.version).getBytes()),\n // subject\n _dnToAsn1(csr.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(csr.publicKey),\n // attributes\n _CRIAttributesToAsn1(csr)\n ]);\n\n return cri;\n};\n\n/**\n * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.\n *\n * @param dn the DistinguishedName.\n *\n * @return the asn1 representation of a DistinguishedName.\n */\npki.distinguishedNameToAsn1 = function(dn) {\n return _dnToAsn1(dn);\n};\n\n/**\n * Converts an X.509v3 RSA certificate to an ASN.1 object.\n *\n * @param cert the certificate.\n *\n * @return the asn1 representation of an X.509v3 RSA certificate.\n */\npki.certificateToAsn1 = function(cert) {\n // prefer cached TBSCertificate over generating one\n var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // TBSCertificate\n tbsCertificate,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)\n ]),\n // SignatureValue\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + cert.signature)\n ]);\n};\n\n/**\n * Converts X.509v3 certificate extensions to ASN.1.\n *\n * @param exts the extensions to convert.\n *\n * @return the extensions in ASN.1 format.\n */\npki.certificateExtensionsToAsn1 = function(exts) {\n // create top-level extension container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);\n\n // create extension sequence (stores a sequence for each extension)\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n rval.value.push(seq);\n\n for(var i = 0; i < exts.length; ++i) {\n seq.value.push(pki.certificateExtensionToAsn1(exts[i]));\n }\n\n return rval;\n};\n\n/**\n * Converts a single certificate extension to ASN.1.\n *\n * @param ext the extension to convert.\n *\n * @return the extension in ASN.1 format.\n */\npki.certificateExtensionToAsn1 = function(ext) {\n // create a sequence for each extension\n var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // extnID (OID)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ext.id).getBytes()));\n\n // critical defaults to false\n if(ext.critical) {\n // critical BOOLEAN DEFAULT FALSE\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n\n var value = ext.value;\n if(typeof ext.value !== 'string') {\n // value is asn.1\n value = asn1.toDer(value).getBytes();\n }\n\n // extnValue (OCTET STRING)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));\n\n return extseq;\n};\n\n/**\n * Converts a PKCS#10 certification request to an ASN.1 object.\n *\n * @param csr the certification request.\n *\n * @return the asn1 representation of a certification request.\n */\npki.certificationRequestToAsn1 = function(csr) {\n // prefer cached CertificationRequestInfo over generating one\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // CertificationRequestInfo\n cri,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(csr.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)\n ]),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + csr.signature)\n ]);\n};\n\n/**\n * Creates a CA store.\n *\n * @param certs an optional array of certificate objects or PEM-formatted\n * certificate strings to add to the CA store.\n *\n * @return the CA store.\n */\npki.createCaStore = function(certs) {\n // create CA store\n var caStore = {\n // stored certificates\n certs: {}\n };\n\n /**\n * Gets the certificate that issued the passed certificate or its\n * 'parent'.\n *\n * @param cert the certificate to get the parent for.\n *\n * @return the parent certificate or null if none was found.\n */\n caStore.getIssuer = function(cert) {\n var rval = getBySubject(cert.issuer);\n\n // see if there are multiple matches\n /*if(forge.util.isArray(rval)) {\n // TODO: resolve multiple matches by checking\n // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.\n // FIXME: or alternatively do authority key mapping\n // if possible (X.509v1 certs can't work?)\n throw new Error('Resolving multiple issuer matches not implemented yet.');\n }*/\n\n return rval;\n };\n\n /**\n * Adds a trusted certificate to the store.\n *\n * @param cert the certificate to add as a trusted certificate (either a\n * pki.certificate object or a PEM-formatted certificate).\n */\n caStore.addCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n ensureSubjectHasHash(cert.subject);\n\n if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store\n if(cert.subject.hash in caStore.certs) {\n // subject hash already exists, append to array\n var tmp = caStore.certs[cert.subject.hash];\n if(!forge.util.isArray(tmp)) {\n tmp = [tmp];\n }\n tmp.push(cert);\n caStore.certs[cert.subject.hash] = tmp;\n } else {\n caStore.certs[cert.subject.hash] = cert;\n }\n }\n };\n\n /**\n * Checks to see if the given certificate is in the store.\n *\n * @param cert the certificate to check (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return true if the certificate is in the store, false if not.\n */\n caStore.hasCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n var match = getBySubject(cert.subject);\n if(!match) {\n return false;\n }\n if(!forge.util.isArray(match)) {\n match = [match];\n }\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n return true;\n }\n }\n return false;\n };\n\n /**\n * Lists all of the certificates kept in the store.\n *\n * @return an array of all of the pki.certificate objects in the store.\n */\n caStore.listAllCertificates = function() {\n var certList = [];\n\n for(var hash in caStore.certs) {\n if(caStore.certs.hasOwnProperty(hash)) {\n var value = caStore.certs[hash];\n if(!forge.util.isArray(value)) {\n certList.push(value);\n } else {\n for(var i = 0; i < value.length; ++i) {\n certList.push(value[i]);\n }\n }\n }\n }\n\n return certList;\n };\n\n /**\n * Removes a certificate from the store.\n *\n * @param cert the certificate to remove (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return the certificate that was removed or null if the certificate\n * wasn't in store.\n */\n caStore.removeCertificate = function(cert) {\n var result;\n\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n ensureSubjectHasHash(cert.subject);\n if(!caStore.hasCertificate(cert)) {\n return null;\n }\n\n var match = getBySubject(cert.subject);\n\n if(!forge.util.isArray(match)) {\n result = caStore.certs[cert.subject.hash];\n delete caStore.certs[cert.subject.hash];\n return result;\n }\n\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n result = match[i];\n match.splice(i, 1);\n }\n }\n if(match.length === 0) {\n delete caStore.certs[cert.subject.hash];\n }\n\n return result;\n };\n\n function getBySubject(subject) {\n ensureSubjectHasHash(subject);\n return caStore.certs[subject.hash] || null;\n }\n\n function ensureSubjectHasHash(subject) {\n // produce subject hash if it doesn't exist\n if(!subject.hash) {\n var md = forge.md.sha1.create();\n subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);\n subject.hash = md.digest().toHex();\n }\n }\n\n // auto-add passed in certs\n if(certs) {\n // parse PEM-formatted certificates as necessary\n for(var i = 0; i < certs.length; ++i) {\n var cert = certs[i];\n caStore.addCertificate(cert);\n }\n }\n\n return caStore;\n};\n\n/**\n * Certificate verification errors, based on TLS.\n */\npki.certificateError = {\n bad_certificate: 'forge.pki.BadCertificate',\n unsupported_certificate: 'forge.pki.UnsupportedCertificate',\n certificate_revoked: 'forge.pki.CertificateRevoked',\n certificate_expired: 'forge.pki.CertificateExpired',\n certificate_unknown: 'forge.pki.CertificateUnknown',\n unknown_ca: 'forge.pki.UnknownCertificateAuthority'\n};\n\n/**\n * Verifies a certificate chain against the given Certificate Authority store\n * with an optional custom verify callback.\n *\n * @param caStore a certificate store to verify against.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end (an array of certificates).\n * @param options a callback to be called for every certificate in the chain or\n * an object with:\n * verify a callback to be called for every certificate in the\n * chain\n * validityCheckDate the date against which the certificate\n * validity period should be checked. Pass null to not check\n * the validity period. By default, the current date is used.\n *\n * The verify callback has the following signature:\n *\n * verified - Set to true if certificate was verified, otherwise the\n * pki.certificateError for why the certificate failed.\n * depth - The current index in the chain, where 0 is the end point's cert.\n * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous\n * end point.\n *\n * The function returns true on success and on failure either the appropriate\n * pki.certificateError or an object with 'error' set to the appropriate\n * pki.certificateError and 'message' set to a custom error message.\n *\n * @return true if successful, error thrown if not.\n */\npki.verifyCertificateChain = function(caStore, chain, options) {\n /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate\n Section 6: Certification Path Validation\n See inline parentheticals related to this particular implementation.\n\n The primary goal of path validation is to verify the binding between\n a subject distinguished name or a subject alternative name and subject\n public key, as represented in the end entity certificate, based on the\n public key of the trust anchor. This requires obtaining a sequence of\n certificates that support that binding. That sequence should be provided\n in the passed 'chain'. The trust anchor should be in the given CA\n store. The 'end entity' certificate is the certificate provided by the\n end point (typically a server) and is the first in the chain.\n\n To meet this goal, the path validation process verifies, among other\n things, that a prospective certification path (a sequence of n\n certificates or a 'chain') satisfies the following conditions:\n\n (a) for all x in {1, ..., n-1}, the subject of certificate x is\n the issuer of certificate x+1;\n\n (b) certificate 1 is issued by the trust anchor;\n\n (c) certificate n is the certificate to be validated; and\n\n (d) for all x in {1, ..., n}, the certificate was valid at the\n time in question.\n\n Note that here 'n' is index 0 in the chain and 1 is the last certificate\n in the chain and it must be signed by a certificate in the connection's\n CA store.\n\n The path validation process also determines the set of certificate\n policies that are valid for this path, based on the certificate policies\n extension, policy mapping extension, policy constraints extension, and\n inhibit any-policy extension.\n\n Note: Policy mapping extension not supported (Not Required).\n\n Note: If the certificate has an unsupported critical extension, then it\n must be rejected.\n\n Note: A certificate is self-issued if the DNs that appear in the subject\n and issuer fields are identical and are not empty.\n\n The path validation algorithm assumes the following seven inputs are\n provided to the path processing logic. What this specific implementation\n will use is provided parenthetically:\n\n (a) a prospective certification path of length n (the 'chain')\n (b) the current date/time: ('now').\n (c) user-initial-policy-set: A set of certificate policy identifiers\n naming the policies that are acceptable to the certificate user.\n The user-initial-policy-set contains the special value any-policy\n if the user is not concerned about certificate policy\n (Not implemented. Any policy is accepted).\n (d) trust anchor information, describing a CA that serves as a trust\n anchor for the certification path. The trust anchor information\n includes:\n\n (1) the trusted issuer name,\n (2) the trusted public key algorithm,\n (3) the trusted public key, and\n (4) optionally, the trusted public key parameters associated\n with the public key.\n\n (Trust anchors are provided via certificates in the CA store).\n\n The trust anchor information may be provided to the path processing\n procedure in the form of a self-signed certificate. The trusted anchor\n information is trusted because it was delivered to the path processing\n procedure by some trustworthy out-of-band procedure. If the trusted\n public key algorithm requires parameters, then the parameters are\n provided along with the trusted public key (No parameters used in this\n implementation).\n\n (e) initial-policy-mapping-inhibit, which indicates if policy mapping is\n allowed in the certification path.\n (Not implemented, no policy checking)\n\n (f) initial-explicit-policy, which indicates if the path must be valid\n for at least one of the certificate policies in the user-initial-\n policy-set.\n (Not implemented, no policy checking)\n\n (g) initial-any-policy-inhibit, which indicates whether the\n anyPolicy OID should be processed if it is included in a\n certificate.\n (Not implemented, so any policy is valid provided that it is\n not marked as critical) */\n\n /* Basic Path Processing:\n\n For each certificate in the 'chain', the following is checked:\n\n 1. The certificate validity period includes the current time.\n 2. The certificate was signed by its parent (where the parent is either\n the next in the chain or from the CA store). Allow processing to\n continue to the next step if no parent is found but the certificate is\n in the CA store.\n 3. TODO: The certificate has not been revoked.\n 4. The certificate issuer name matches the parent's subject name.\n 5. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is within one of the permitted subtrees of X.500 distinguished names\n and that each of the alternative names in the subjectAltName extension\n (critical or non-critical) is within one of the permitted subtrees for\n that name type.\n 6. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is not within one of the excluded subtrees for X.500 distinguished\n names and none of the subjectAltName extension names are excluded for\n that name type.\n 7. The other steps in the algorithm for basic path processing involve\n handling the policy extension which is not presently supported in this\n implementation. Instead, if a critical policy extension is found, the\n certificate is rejected as not supported.\n 8. If the certificate is not the first or if its the only certificate in\n the chain (having no parent from the CA store or is self-signed) and it\n has a critical key usage extension, verify that the keyCertSign bit is\n set. If the key usage extension exists, verify that the basic\n constraints extension exists. If the basic constraints extension exists,\n verify that the cA flag is set. If pathLenConstraint is set, ensure that\n the number of certificates that precede in the chain (come earlier\n in the chain as implemented below), excluding the very first in the\n chain (typically the end-entity one), isn't greater than the\n pathLenConstraint. This constraint limits the number of intermediate\n CAs that may appear below a CA before only end-entity certificates\n may be issued. */\n\n // if a verify callback is passed as the third parameter, package it within\n // the options object. This is to support a legacy function signature that\n // expected the verify callback as the third parameter.\n if(typeof options === 'function') {\n options = {verify: options};\n }\n options = options || {};\n\n // copy cert chain references to another array to protect against changes\n // in verify callback\n chain = chain.slice(0);\n var certs = chain.slice(0);\n\n var validityCheckDate = options.validityCheckDate;\n // if no validityCheckDate is specified, default to the current date. Make\n // sure to maintain the value null because it indicates that the validity\n // period should not be checked.\n if(typeof validityCheckDate === 'undefined') {\n validityCheckDate = new Date();\n }\n\n // verify each cert in the chain using its parent, where the parent\n // is either the next in the chain or from the CA store\n var first = true;\n var error = null;\n var depth = 0;\n do {\n var cert = chain.shift();\n var parent = null;\n var selfSigned = false;\n\n if(validityCheckDate) {\n // 1. check valid time\n if(validityCheckDate < cert.validity.notBefore ||\n validityCheckDate > cert.validity.notAfter) {\n error = {\n message: 'Certificate is not valid yet or has expired.',\n error: pki.certificateError.certificate_expired,\n notBefore: cert.validity.notBefore,\n notAfter: cert.validity.notAfter,\n // TODO: we might want to reconsider renaming 'now' to\n // 'validityCheckDate' should this API be changed in the future.\n now: validityCheckDate\n };\n }\n }\n\n // 2. verify with parent from chain or CA store\n if(error === null) {\n parent = chain[0] || caStore.getIssuer(cert);\n if(parent === null) {\n // check for self-signed cert\n if(cert.isIssuer(cert)) {\n selfSigned = true;\n parent = cert;\n }\n }\n\n if(parent) {\n // FIXME: current CA store implementation might have multiple\n // certificates where the issuer can't be determined from the\n // certificate (happens rarely with, eg: old certificates) so normalize\n // by always putting parents into an array\n // TODO: there's may be an extreme degenerate case currently uncovered\n // where an old intermediate certificate seems to have a matching parent\n // but none of the parents actually verify ... but the intermediate\n // is in the CA and it should pass this check; needs investigation\n var parents = parent;\n if(!forge.util.isArray(parents)) {\n parents = [parents];\n }\n\n // try to verify with each possible parent (typically only one)\n var verified = false;\n while(!verified && parents.length > 0) {\n parent = parents.shift();\n try {\n verified = parent.verify(cert);\n } catch(ex) {\n // failure to verify, don't care why, try next one\n }\n }\n\n if(!verified) {\n error = {\n message: 'Certificate signature is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n\n if(error === null && (!parent || selfSigned) &&\n !caStore.hasCertificate(cert)) {\n // no parent issuer and certificate itself is not trusted\n error = {\n message: 'Certificate is not trusted.',\n error: pki.certificateError.unknown_ca\n };\n }\n }\n\n // TODO: 3. check revoked\n\n // 4. check for matching issuer/subject\n if(error === null && parent && !cert.isIssuer(parent)) {\n // parent is not issuer\n error = {\n message: 'Certificate issuer is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // 5. TODO: check names with permitted names tree\n\n // 6. TODO: check names against excluded names tree\n\n // 7. check for unsupported critical extensions\n if(error === null) {\n // supported extensions\n var se = {\n keyUsage: true,\n basicConstraints: true\n };\n for(var i = 0; error === null && i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.critical && !(ext.name in se)) {\n error = {\n message:\n 'Certificate has an unsupported critical extension.',\n error: pki.certificateError.unsupported_certificate\n };\n }\n }\n }\n\n // 8. check for CA if cert is not first or is the only certificate\n // remaining in chain with no parent or is self-signed\n if(error === null &&\n (!first || (chain.length === 0 && (!parent || selfSigned)))) {\n // first check keyUsage extension and then basic constraints\n var bcExt = cert.getExtension('basicConstraints');\n var keyUsageExt = cert.getExtension('keyUsage');\n if(keyUsageExt !== null) {\n // keyCertSign must be true and there must be a basic\n // constraints extension\n if(!keyUsageExt.keyCertSign || bcExt === null) {\n // bad certificate\n error = {\n message:\n 'Certificate keyUsage or basicConstraints conflict ' +\n 'or indicate that the certificate is not a CA. ' +\n 'If the certificate is the only one in the chain or ' +\n 'isn\\'t the first then the certificate must be a ' +\n 'valid CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n // basic constraints cA flag must be set\n if(error === null && bcExt !== null && !bcExt.cA) {\n // bad certificate\n error = {\n message:\n 'Certificate basicConstraints indicates the certificate ' +\n 'is not a CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n // if error is not null and keyUsage is available, then we know it\n // has keyCertSign and there is a basic constraints extension too,\n // which means we can check pathLenConstraint (if it exists)\n if(error === null && keyUsageExt !== null &&\n 'pathLenConstraint' in bcExt) {\n // pathLen is the maximum # of intermediate CA certs that can be\n // found between the current certificate and the end-entity (depth 0)\n // certificate; this number does not include the end-entity (depth 0,\n // last in the chain) even if it happens to be a CA certificate itself\n var pathLen = depth - 1;\n if(pathLen > bcExt.pathLenConstraint) {\n // pathLenConstraint violated, bad certificate\n error = {\n message:\n 'Certificate basicConstraints pathLenConstraint violated.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n }\n\n // call application callback\n var vfd = (error === null) ? true : error.error;\n var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;\n if(ret === true) {\n // clear any set error\n error = null;\n } else {\n // if passed basic tests, set default message and alert\n if(vfd === true) {\n error = {\n message: 'The application rejected the certificate.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // check for custom error info\n if(ret || ret === 0) {\n // set custom message and error\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.error) {\n error.error = ret.error;\n }\n } else if(typeof ret === 'string') {\n // set custom error\n error.error = ret;\n }\n }\n\n // throw error\n throw error;\n }\n\n // no longer first cert in chain\n first = false;\n ++depth;\n } while(chain.length > 0);\n\n return true;\n};\n","var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n","var once = require('once')\nvar eos = require('end-of-stream')\nvar fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes\n\nvar noop = function () {}\nvar ancient = /^v?\\.0/.test(process.version)\n\nvar isFn = function (fn) {\n return typeof fn === 'function'\n}\n\nvar isFS = function (stream) {\n if (!ancient) return false // newer node version do not need to care about fs is a special way\n if (!fs) return false // browser\n return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)\n}\n\nvar isRequest = function (stream) {\n return stream.setHeader && isFn(stream.abort)\n}\n\nvar destroyer = function (stream, reading, writing, callback) {\n callback = once(callback)\n\n var closed = false\n stream.on('close', function () {\n closed = true\n })\n\n eos(stream, {readable: reading, writable: writing}, function (err) {\n if (err) return callback(err)\n closed = true\n callback()\n })\n\n var destroyed = false\n return function (err) {\n if (closed) return\n if (destroyed) return\n destroyed = true\n\n if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks\n if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want\n\n if (isFn(stream.destroy)) return stream.destroy()\n\n callback(err || new Error('stream was destroyed'))\n }\n}\n\nvar call = function (fn) {\n fn()\n}\n\nvar pipe = function (from, to) {\n return from.pipe(to)\n}\n\nvar pump = function () {\n var streams = Array.prototype.slice.call(arguments)\n var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop\n\n if (Array.isArray(streams[0])) streams = streams[0]\n if (streams.length < 2) throw new Error('pump requires two streams per minimum')\n\n var error\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1\n var writing = i > 0\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err\n if (err) destroys.forEach(call)\n if (reading) return\n destroys.forEach(call)\n callback(error)\n })\n })\n\n return streams.reduce(pipe)\n}\n\nmodule.exports = pump\n","module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')\n ? process.nextTick.bind(process)\n : require('./queue-microtask')\n","module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)\n","'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};","'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;","'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();","'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;","'use strict';\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;\n\nfunction from(Readable, iterable, opts) {\n var iterator;\n\n if (iterable && typeof iterable.next === 'function') {\n iterator = iterable;\n } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);\n\n var readable = new Readable(_objectSpread({\n objectMode: true\n }, opts)); // Reading boolean to protect against _read\n // being called before last iteration completion.\n\n var reading = false;\n\n readable._read = function () {\n if (!reading) {\n reading = true;\n next();\n }\n };\n\n function next() {\n return _next2.apply(this, arguments);\n }\n\n function _next2() {\n _next2 = _asyncToGenerator(function* () {\n try {\n var _ref = yield iterator.next(),\n value = _ref.value,\n done = _ref.done;\n\n if (done) {\n readable.push(null);\n } else if (readable.push((yield value))) {\n next();\n } else {\n reading = false;\n }\n } catch (err) {\n readable.destroy(err);\n }\n });\n return _next2.apply(this, arguments);\n }\n\n return readable;\n}\n\nmodule.exports = from;","// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\n\n var error;\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1;\n var writing = i > 0;\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err;\n if (err) destroys.forEach(call);\n if (reading) return;\n destroys.forEach(call);\n callback(error);\n });\n });\n return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;","'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};","module.exports = require('stream');\n","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n","/* eslint-disable node/no-deprecated-api */\n\n'use strict'\n\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\nvar safer = {}\n\nvar key\n\nfor (key in buffer) {\n if (!buffer.hasOwnProperty(key)) continue\n if (key === 'SlowBuffer' || key === 'Buffer') continue\n safer[key] = buffer[key]\n}\n\nvar Safer = safer.Buffer = {}\nfor (key in Buffer) {\n if (!Buffer.hasOwnProperty(key)) continue\n if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue\n Safer[key] = Buffer[key]\n}\n\nsafer.Buffer.prototype = Buffer.prototype\n\nif (!Safer.from || Safer.from === Uint8Array.from) {\n Safer.from = function (value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('The \"value\" argument must not be of type number. Received type ' + typeof value)\n }\n if (value && typeof value.length === 'undefined') {\n throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)\n }\n return Buffer(value, encodingOrOffset, length)\n }\n}\n\nif (!Safer.alloc) {\n Safer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('The \"size\" argument must be of type number. Received type ' + typeof size)\n }\n if (size < 0 || size >= 2 * (1 << 30)) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n var buf = Buffer(size)\n if (!fill || fill.length === 0) {\n buf.fill(0)\n } else if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n return buf\n }\n}\n\nif (!safer.kStringMaxLength) {\n try {\n safer.kStringMaxLength = process.binding('buffer').kStringMaxLength\n } catch (e) {\n // we can't determine kStringMaxLength in environments where process.binding\n // is unsupported, so let's not set it\n }\n}\n\nif (!safer.constants) {\n safer.constants = {\n MAX_LENGTH: safer.kMaxLength\n }\n if (safer.kStringMaxLength) {\n safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength\n }\n}\n\nmodule.exports = safer\n","var fs = require('fs');\n\nmodule.exports = function (filepath, split, encoding) {\n split = typeof split !== 'undefined' ? split : \"\\n\";\n encoding = typeof encoding !== 'undefined' ? encoding : \"utf8\";\n\n var ca = [];\n var chain = fs.readFileSync(filepath, encoding);\n if(chain.indexOf(\"-END CERTIFICATE-\") < 0 || chain.indexOf(\"-BEGIN CERTIFICATE-\") < 0){\n throw Error(\"File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'\");\n }\n chain = chain.split(split);\n var cert = [];\n var _i, _len;\n for (_i = 0, _len = chain.length; _i < _len; _i++) {\n var line = chain[_i];\n if (!(line.length !== 0)) {\n continue;\n }\n cert.push(line);\n if (line.match(/-END CERTIFICATE-/)) {\n ca.push(cert.join(split));\n cert = [];\n }\n }\n return ca;\n}\n","'use strict';\n\nconst {\n Duplex: DuplexStream,\n Readable: ReadableStream,\n Writable: WritableStream,\n} = require('stream');\n\nconst {\n CHANNEL_EXTENDED_DATATYPE: { STDERR },\n} = require('./protocol/constants.js');\nconst { bufferSlice } = require('./protocol/utils.js');\n\nconst PACKET_SIZE = 32 * 1024;\nconst MAX_WINDOW = 2 * 1024 * 1024;\nconst WINDOW_THRESHOLD = MAX_WINDOW / 2;\n\nclass ClientStderr extends ReadableStream {\n constructor(channel, streamOpts) {\n super(streamOpts);\n\n this._channel = channel;\n }\n _read(n) {\n if (this._channel._waitChanDrain) {\n this._channel._waitChanDrain = false;\n if (this._channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(this._channel);\n }\n }\n}\n\nclass ServerStderr extends WritableStream {\n constructor(channel) {\n super({ highWaterMark: MAX_WINDOW });\n\n this._channel = channel;\n }\n\n _write(data, encoding, cb) {\n const channel = this._channel;\n const protocol = channel._client._protocol;\n const outgoing = channel.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelExtData(id, data, STDERR);\n else\n protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR);\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n channel._waitWindow = true;\n if (p > 0)\n channel._chunkErr = bufferSlice(data, p, len);\n else\n channel._chunkErr = data;\n channel._chunkcbErr = cb;\n return;\n }\n\n cb();\n }\n}\n\nclass Channel extends DuplexStream {\n constructor(client, info, opts) {\n const streamOpts = {\n highWaterMark: MAX_WINDOW,\n allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)),\n emitClose: false,\n };\n super(streamOpts);\n this.allowHalfOpen = streamOpts.allowHalfOpen;\n\n const server = !!(opts && opts.server);\n\n this.server = server;\n this.type = info.type;\n this.subtype = undefined;\n\n /*\n incoming and outgoing contain these properties:\n {\n id: undefined,\n window: undefined,\n packetSize: undefined,\n state: 'closed'\n }\n */\n this.incoming = info.incoming;\n this.outgoing = info.outgoing;\n this._callbacks = [];\n\n this._client = client;\n this._hasX11 = false;\n this._exit = {\n code: undefined,\n signal: undefined,\n dump: undefined,\n desc: undefined,\n };\n\n this.stdin = this.stdout = this;\n\n if (server)\n this.stderr = new ServerStderr(this);\n else\n this.stderr = new ClientStderr(this, streamOpts);\n\n // Outgoing data\n this._waitWindow = false; // SSH-level backpressure\n\n // Incoming data\n this._waitChanDrain = false; // Channel Readable side backpressure\n\n this._chunk = undefined;\n this._chunkcb = undefined;\n this._chunkErr = undefined;\n this._chunkcbErr = undefined;\n\n this.on('finish', onFinish)\n .on('prefinish', onFinish); // For node v0.11+\n\n this.on('end', onEnd).on('close', onEnd);\n }\n\n _read(n) {\n if (this._waitChanDrain) {\n this._waitChanDrain = false;\n if (this.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(this);\n }\n }\n\n _write(data, encoding, cb) {\n const protocol = this._client._protocol;\n const outgoing = this.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelData(id, data);\n else\n protocol.channelData(id, bufferSlice(data, p, p + sliceLen));\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n this._waitWindow = true;\n if (p > 0)\n this._chunk = bufferSlice(data, p, len);\n else\n this._chunk = data;\n this._chunkcb = cb;\n return;\n }\n\n cb();\n }\n\n eof() {\n if (this.outgoing.state === 'open') {\n this.outgoing.state = 'eof';\n this._client._protocol.channelEOF(this.outgoing.id);\n }\n }\n\n close() {\n if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {\n this.outgoing.state = 'closing';\n this._client._protocol.channelClose(this.outgoing.id);\n }\n }\n\n destroy() {\n this.end();\n this.close();\n return this;\n }\n\n // Session type-specific methods =============================================\n setWindow(rows, cols, height, width) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && (this.subtype === 'shell' || this.subtype === 'exec')\n && this.writable\n && this.outgoing.state === 'open') {\n this._client._protocol.windowChange(this.outgoing.id,\n rows,\n cols,\n height,\n width);\n }\n }\n\n signal(signalName) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open') {\n this._client._protocol.signal(this.outgoing.id, signalName);\n }\n }\n\n exit(statusOrSignal, coreDumped, msg) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open') {\n if (typeof statusOrSignal === 'number') {\n this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal);\n } else {\n this._client._protocol.exitSignal(this.outgoing.id,\n statusOrSignal,\n coreDumped,\n msg);\n }\n }\n }\n\n}\n\nfunction onFinish() {\n this.eof();\n if (this.server || !this.allowHalfOpen)\n this.close();\n this.writable = false;\n}\n\nfunction onEnd() {\n this.readable = false;\n}\n\nfunction windowAdjust(self) {\n if (self.outgoing.state === 'closed')\n return;\n const amt = MAX_WINDOW - self.incoming.window;\n if (amt <= 0)\n return;\n self.incoming.window += amt;\n self._client._protocol.channelWindowAdjust(self.outgoing.id, amt);\n}\n\nmodule.exports = {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n};\n",null,"// TODO:\n// * add `.connected` or similar property to allow immediate connection\n// status checking\n// * add/improve debug output during user authentication phase\n'use strict';\n\nconst {\n createHash,\n getHashes,\n randomFillSync,\n} = require('crypto');\nconst { Socket } = require('net');\nconst { lookup: dnsLookup } = require('dns');\nconst EventEmitter = require('events');\nconst HASHES = getHashes();\n\nconst {\n COMPAT,\n CHANNEL_EXTENDED_DATATYPE: { STDERR },\n CHANNEL_OPEN_FAILURE,\n DEFAULT_CIPHER,\n DEFAULT_COMPRESSION,\n DEFAULT_KEX,\n DEFAULT_MAC,\n DEFAULT_SERVER_HOST_KEY,\n DISCONNECT_REASON,\n DISCONNECT_REASON_BY_VALUE,\n SUPPORTED_CIPHER,\n SUPPORTED_COMPRESSION,\n SUPPORTED_KEX,\n SUPPORTED_MAC,\n SUPPORTED_SERVER_HOST_KEY,\n} = require('./protocol/constants.js');\nconst { init: cryptoInit } = require('./protocol/crypto.js');\nconst Protocol = require('./protocol/Protocol.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst { SFTP } = require('./protocol/SFTP.js');\nconst {\n bufferCopy,\n makeBufferParser,\n makeError,\n readUInt32BE,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./protocol/utils.js');\n\nconst { AgentContext, createAgent, isAgent } = require('./agent.js');\nconst {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n} = require('./Channel.js');\nconst {\n ChannelManager,\n generateAlgorithmList,\n isWritable,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n} = require('./utils.js');\n\nconst bufferParser = makeBufferParser();\nconst sigParser = makeBufferParser();\nconst RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\\d)|(?:\\d{2,})/;\nconst noop = (err) => {};\n\nclass Client extends EventEmitter {\n constructor() {\n super();\n\n this.config = {\n host: undefined,\n port: undefined,\n localAddress: undefined,\n localPort: undefined,\n forceIPv4: undefined,\n forceIPv6: undefined,\n keepaliveCountMax: undefined,\n keepaliveInterval: undefined,\n readyTimeout: undefined,\n ident: undefined,\n\n username: undefined,\n password: undefined,\n privateKey: undefined,\n tryKeyboard: undefined,\n agent: undefined,\n allowAgentFwd: undefined,\n authHandler: undefined,\n\n hostHashAlgo: undefined,\n hostHashCb: undefined,\n strictVendor: undefined,\n debug: undefined\n };\n\n this._agent = undefined;\n this._readyTimeout = undefined;\n this._chanMgr = undefined;\n this._callbacks = undefined;\n this._forwarding = undefined;\n this._forwardingUnix = undefined;\n this._acceptX11 = undefined;\n this._agentFwdEnabled = undefined;\n this._remoteVer = undefined;\n\n this._protocol = undefined;\n this._sock = undefined;\n this._resetKA = undefined;\n }\n\n connect(cfg) {\n if (this._sock && isWritable(this._sock)) {\n this.once('close', () => {\n this.connect(cfg);\n });\n this.end();\n return this;\n }\n\n this.config.host = cfg.hostname || cfg.host || 'localhost';\n this.config.port = cfg.port || 22;\n this.config.localAddress = (typeof cfg.localAddress === 'string'\n ? cfg.localAddress\n : undefined);\n this.config.localPort = (typeof cfg.localPort === 'string'\n || typeof cfg.localPort === 'number'\n ? cfg.localPort\n : undefined);\n this.config.forceIPv4 = cfg.forceIPv4 || false;\n this.config.forceIPv6 = cfg.forceIPv6 || false;\n this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number'\n && cfg.keepaliveCountMax >= 0\n ? cfg.keepaliveCountMax\n : 3);\n this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number'\n && cfg.keepaliveInterval > 0\n ? cfg.keepaliveInterval\n : 0);\n this.config.readyTimeout = (typeof cfg.readyTimeout === 'number'\n && cfg.readyTimeout >= 0\n ? cfg.readyTimeout\n : 20000);\n this.config.ident = (typeof cfg.ident === 'string'\n || Buffer.isBuffer(cfg.ident)\n ? cfg.ident\n : undefined);\n\n const algorithms = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: [],\n },\n sc: undefined,\n };\n let allOfferDefaults = true;\n if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) {\n algorithms.kex = generateAlgorithmList(cfg.algorithms.kex,\n DEFAULT_KEX,\n SUPPORTED_KEX);\n if (algorithms.kex !== DEFAULT_KEX)\n allOfferDefaults = false;\n\n algorithms.serverHostKey =\n generateAlgorithmList(cfg.algorithms.serverHostKey,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY);\n if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY)\n allOfferDefaults = false;\n\n algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER);\n if (algorithms.cs.cipher !== DEFAULT_CIPHER)\n allOfferDefaults = false;\n\n algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac,\n DEFAULT_MAC,\n SUPPORTED_MAC);\n if (algorithms.cs.mac !== DEFAULT_MAC)\n allOfferDefaults = false;\n\n algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION);\n if (algorithms.cs.compress !== DEFAULT_COMPRESSION)\n allOfferDefaults = false;\n\n if (!allOfferDefaults)\n algorithms.sc = algorithms.cs;\n }\n\n if (typeof cfg.username === 'string')\n this.config.username = cfg.username;\n else if (typeof cfg.user === 'string')\n this.config.username = cfg.user;\n else\n throw new Error('Invalid username');\n\n this.config.password = (typeof cfg.password === 'string'\n ? cfg.password\n : undefined);\n this.config.privateKey = (typeof cfg.privateKey === 'string'\n || Buffer.isBuffer(cfg.privateKey)\n ? cfg.privateKey\n : undefined);\n this.config.localHostname = (typeof cfg.localHostname === 'string'\n ? cfg.localHostname\n : undefined);\n this.config.localUsername = (typeof cfg.localUsername === 'string'\n ? cfg.localUsername\n : undefined);\n this.config.tryKeyboard = (cfg.tryKeyboard === true);\n if (typeof cfg.agent === 'string' && cfg.agent.length)\n this.config.agent = createAgent(cfg.agent);\n else if (isAgent(cfg.agent))\n this.config.agent = cfg.agent;\n else\n this.config.agent = undefined;\n this.config.allowAgentFwd = (cfg.agentForward === true\n && this.config.agent !== undefined);\n let authHandler = this.config.authHandler = (\n typeof cfg.authHandler === 'function'\n || Array.isArray(cfg.authHandler)\n ? cfg.authHandler\n : undefined\n );\n\n this.config.strictVendor = (typeof cfg.strictVendor === 'boolean'\n ? cfg.strictVendor\n : true);\n\n const debug = this.config.debug = (typeof cfg.debug === 'function'\n ? cfg.debug\n : undefined);\n\n if (cfg.agentForward === true && !this.config.allowAgentFwd) {\n throw new Error(\n 'You must set a valid agent path to allow agent forwarding'\n );\n }\n\n let callbacks = this._callbacks = [];\n this._chanMgr = new ChannelManager(this);\n this._forwarding = {};\n this._forwardingUnix = {};\n this._acceptX11 = 0;\n this._agentFwdEnabled = false;\n this._agent = (this.config.agent ? this.config.agent : undefined);\n this._remoteVer = undefined;\n let privateKey;\n\n if (this.config.privateKey) {\n privateKey = parseKey(this.config.privateKey, cfg.passphrase);\n if (privateKey instanceof Error)\n throw new Error(`Cannot parse privateKey: ${privateKey.message}`);\n if (Array.isArray(privateKey)) {\n // OpenSSH's newer format only stores 1 key for now\n privateKey = privateKey[0];\n }\n if (privateKey.getPrivatePEM() === null) {\n throw new Error(\n 'privateKey value does not contain a (valid) private key'\n );\n }\n }\n\n let hostVerifier;\n if (typeof cfg.hostVerifier === 'function') {\n const hashCb = cfg.hostVerifier;\n let hasher;\n if (HASHES.indexOf(cfg.hostHash) !== -1) {\n // Default to old behavior of hashing on user's behalf\n hasher = createHash(cfg.hostHash);\n }\n hostVerifier = (key, verify) => {\n if (hasher) {\n hasher.update(key);\n key = hasher.digest('hex');\n }\n const ret = hashCb(key, verify);\n if (ret !== undefined)\n verify(ret);\n };\n }\n\n const sock = this._sock = (cfg.sock || new Socket());\n let ready = false;\n let sawHeader = false;\n if (this._protocol)\n this._protocol.cleanup();\n const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {\n debug(`Debug output from server: ${JSON.stringify(msg)}`);\n });\n let serverSigAlgs;\n const proto = this._protocol = new Protocol({\n ident: this.config.ident,\n offer: (allOfferDefaults ? undefined : algorithms),\n onWrite: (data) => {\n if (isWritable(sock))\n sock.write(data);\n },\n onError: (err) => {\n if (err.level === 'handshake')\n clearTimeout(this._readyTimeout);\n if (!proto._destruct)\n sock.removeAllListeners('data');\n this.emit('error', err);\n try {\n sock.end();\n } catch {}\n },\n onHeader: (header) => {\n sawHeader = true;\n this._remoteVer = header.versions.software;\n if (header.greeting)\n this.emit('greeting', header.greeting);\n },\n onHandshakeComplete: (negotiated) => {\n this.emit('handshake', negotiated);\n if (!ready) {\n ready = true;\n proto.service('ssh-userauth');\n }\n },\n debug,\n hostVerifier,\n messageHandlers: {\n DEBUG: DEBUG_HANDLER,\n DISCONNECT: (p, reason, desc) => {\n if (reason !== DISCONNECT_REASON.BY_APPLICATION) {\n if (!desc) {\n desc = DISCONNECT_REASON_BY_VALUE[reason];\n if (desc === undefined)\n desc = `Unexpected disconnection reason: ${reason}`;\n }\n const err = new Error(desc);\n err.code = reason;\n this.emit('error', err);\n }\n sock.end();\n },\n SERVICE_ACCEPT: (p, name) => {\n if (name === 'ssh-userauth')\n tryNextAuth();\n },\n EXT_INFO: (p, exts) => {\n if (serverSigAlgs === undefined) {\n for (const ext of exts) {\n if (ext.name === 'server-sig-algs') {\n serverSigAlgs = ext.algs;\n return;\n }\n }\n serverSigAlgs = null;\n }\n },\n USERAUTH_BANNER: (p, msg) => {\n this.emit('banner', msg);\n },\n USERAUTH_SUCCESS: (p) => {\n // Start keepalive mechanism\n resetKA();\n\n clearTimeout(this._readyTimeout);\n\n this.emit('ready');\n },\n USERAUTH_FAILURE: (p, authMethods, partialSuccess) => {\n // For key-based authentication, check if we should retry the current\n // key with a different algorithm first\n if (curAuth.keyAlgos) {\n const oldKeyAlgo = curAuth.keyAlgos[0][0];\n if (debug)\n debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`);\n curAuth.keyAlgos.shift();\n if (curAuth.keyAlgos.length) {\n const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0];\n switch (curAuth.type) {\n case 'agent':\n proto.authPK(\n curAuth.username,\n curAuth.agentCtx.currentKey(),\n keyAlgo\n );\n return;\n case 'publickey':\n proto.authPK(curAuth.username, curAuth.key, keyAlgo);\n return;\n case 'hostbased':\n proto.authHostbased(curAuth.username,\n curAuth.key,\n curAuth.localHostname,\n curAuth.localUsername,\n keyAlgo,\n (buf, cb) => {\n const signature = curAuth.key.sign(buf, hashAlgo);\n if (signature instanceof Error) {\n signature.message =\n `Error while signing with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n\n cb(signature);\n });\n return;\n }\n } else {\n curAuth.keyAlgos = undefined;\n }\n }\n\n if (curAuth.type === 'agent') {\n const pos = curAuth.agentCtx.pos();\n debug && debug(`Client: Agent key #${pos + 1} failed`);\n return tryNextAgentKey();\n }\n\n debug && debug(`Client: ${curAuth.type} auth failed`);\n\n curPartial = partialSuccess;\n curAuthsLeft = authMethods;\n tryNextAuth();\n },\n USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => {\n if (curAuth.type === 'password') {\n // TODO: support a `changePrompt()` on `curAuth` that defaults to\n // emitting 'change password' as before\n this.emit('change password', prompt, (newPassword) => {\n proto.authPassword(\n this.config.username,\n this.config.password,\n newPassword\n );\n });\n }\n },\n USERAUTH_PK_OK: (p) => {\n let keyAlgo;\n let hashAlgo;\n if (curAuth.keyAlgos)\n [keyAlgo, hashAlgo] = curAuth.keyAlgos[0];\n if (curAuth.type === 'agent') {\n const key = curAuth.agentCtx.currentKey();\n proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => {\n const opts = { hash: hashAlgo };\n curAuth.agentCtx.sign(key, buf, opts, (err, signed) => {\n if (err) {\n err.level = 'agent';\n this.emit('error', err);\n } else {\n return cb(signed);\n }\n\n tryNextAgentKey();\n });\n });\n } else if (curAuth.type === 'publickey') {\n proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => {\n const signature = curAuth.key.sign(buf, hashAlgo);\n if (signature instanceof Error) {\n signature.message =\n `Error signing data with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n cb(signature);\n });\n }\n },\n USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => {\n if (curAuth.type === 'keyboard-interactive') {\n const nprompts = (Array.isArray(prompts) ? prompts.length : 0);\n if (nprompts === 0) {\n debug && debug(\n 'Client: Sending automatic USERAUTH_INFO_RESPONSE'\n );\n proto.authInfoRes();\n return;\n }\n // We sent a keyboard-interactive user authentication request and\n // now the server is sending us the prompts we need to present to\n // the user\n curAuth.prompt(\n name,\n instructions,\n '',\n prompts,\n (answers) => {\n proto.authInfoRes(answers);\n }\n );\n }\n },\n REQUEST_SUCCESS: (p, data) => {\n if (callbacks.length)\n callbacks.shift()(false, data);\n },\n REQUEST_FAILURE: (p) => {\n if (callbacks.length)\n callbacks.shift()(true);\n },\n GLOBAL_REQUEST: (p, name, wantReply, data) => {\n switch (name) {\n case 'hostkeys-00@openssh.com':\n // Automatically verify keys before passing to end user\n hostKeysProve(this, data, (err, keys) => {\n if (err)\n return;\n this.emit('hostkeys', keys);\n });\n if (wantReply)\n proto.requestSuccess();\n break;\n default:\n // Auto-reject all other global requests, this can be especially\n // useful if the server is sending us dummy keepalive global\n // requests\n if (wantReply)\n proto.requestFailure();\n }\n },\n CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from server, typically a forwarded TCP or\n // X11 connection\n onCHANNEL_OPEN(this, info);\n },\n CHANNEL_OPEN_CONFIRMATION: (p, info) => {\n const channel = this._chanMgr.get(info.recipient);\n if (typeof channel !== 'function')\n return;\n\n const isSFTP = (channel.type === 'sftp');\n const type = (isSFTP ? 'session' : channel.type);\n const chanInfo = {\n type,\n incoming: {\n id: info.recipient,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const instance = (\n isSFTP\n ? new SFTP(this, chanInfo, { debug })\n : new Channel(this, chanInfo)\n );\n this._chanMgr.update(info.recipient, instance);\n channel(undefined, instance);\n },\n CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },\n CHANNEL_DATA: (p, recipient, data) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n if (type !== STDERR)\n return;\n\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (!channel.stderr.push(data)) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },\n CHANNEL_SUCCESS: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n this._resetKA();\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(false);\n },\n CHANNEL_FAILURE: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n this._resetKA();\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },\n CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n const exit = channel._exit;\n if (exit.code !== undefined)\n return;\n switch (type) {\n case 'exit-status':\n channel.emit('exit', exit.code = data);\n return;\n case 'exit-signal':\n channel.emit('exit',\n exit.code = null,\n exit.signal = `SIG${data.signal}`,\n exit.dump = data.coreDumped,\n exit.desc = data.errorMessage);\n return;\n }\n\n // Keepalive request? OpenSSH will send one as a channel request if\n // there is a channel open\n\n if (wantReply)\n p.channelFailure(channel.outgoing.id);\n },\n CHANNEL_EOF: (p, recipient) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.incoming.state !== 'open')\n return;\n channel.incoming.state = 'eof';\n\n if (channel.readable)\n channel.push(null);\n if (channel.stderr.readable)\n channel.stderr.push(null);\n },\n CHANNEL_CLOSE: (p, recipient) => {\n onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient));\n },\n },\n });\n\n sock.pause();\n\n // TODO: check keepalive implementation\n // Keepalive-related\n const kainterval = this.config.keepaliveInterval;\n const kacountmax = this.config.keepaliveCountMax;\n let kacount = 0;\n let katimer;\n const sendKA = () => {\n if (++kacount > kacountmax) {\n clearInterval(katimer);\n if (sock.readable) {\n const err = new Error('Keepalive timeout');\n err.level = 'client-timeout';\n this.emit('error', err);\n sock.destroy();\n }\n return;\n }\n if (isWritable(sock)) {\n // Append dummy callback to keep correct callback order\n callbacks.push(resetKA);\n proto.ping();\n } else {\n clearInterval(katimer);\n }\n };\n function resetKA() {\n if (kainterval > 0) {\n kacount = 0;\n clearInterval(katimer);\n if (isWritable(sock))\n katimer = setInterval(sendKA, kainterval);\n }\n }\n this._resetKA = resetKA;\n\n const onDone = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n if (wasConnected && !sawHeader) {\n const err =\n makeError('Connection lost before handshake', 'protocol', true);\n this.emit('error', err);\n }\n };\n })();\n const onConnect = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n\n wasConnected = true;\n debug && debug('Socket connected');\n this.emit('connect');\n\n cryptoInit.then(() => {\n proto.start();\n sock.on('data', (data) => {\n try {\n proto.parse(data, 0, data.length);\n } catch (ex) {\n this.emit('error', ex);\n try {\n if (isWritable(sock))\n sock.end();\n } catch {}\n }\n });\n\n // Drain stderr if we are connection hopping using an exec stream\n if (sock.stderr && typeof sock.stderr.resume === 'function')\n sock.stderr.resume();\n\n sock.resume();\n }).catch((err) => {\n this.emit('error', err);\n try {\n if (isWritable(sock))\n sock.end();\n } catch {}\n });\n };\n })();\n let wasConnected = false;\n sock.on('connect', onConnect)\n .on('timeout', () => {\n this.emit('timeout');\n }).on('error', (err) => {\n debug && debug(`Socket error: ${err.message}`);\n clearTimeout(this._readyTimeout);\n err.level = 'client-socket';\n this.emit('error', err);\n }).on('end', () => {\n debug && debug('Socket ended');\n onDone();\n proto.cleanup();\n clearTimeout(this._readyTimeout);\n clearInterval(katimer);\n this.emit('end');\n }).on('close', () => {\n debug && debug('Socket closed');\n onDone();\n proto.cleanup();\n clearTimeout(this._readyTimeout);\n clearInterval(katimer);\n this.emit('close');\n\n // Notify outstanding channel requests of disconnection ...\n const callbacks_ = callbacks;\n callbacks = this._callbacks = [];\n const err = new Error('No response from server');\n for (let i = 0; i < callbacks_.length; ++i)\n callbacks_[i](err);\n\n // Simulate error for any channels waiting to be opened\n this._chanMgr.cleanup(err);\n });\n\n // Begin authentication handling ===========================================\n let curAuth;\n let curPartial = null;\n let curAuthsLeft = null;\n const authsAllowed = ['none'];\n if (this.config.password !== undefined)\n authsAllowed.push('password');\n if (privateKey !== undefined)\n authsAllowed.push('publickey');\n if (this._agent !== undefined)\n authsAllowed.push('agent');\n if (this.config.tryKeyboard)\n authsAllowed.push('keyboard-interactive');\n if (privateKey !== undefined\n && this.config.localHostname !== undefined\n && this.config.localUsername !== undefined) {\n authsAllowed.push('hostbased');\n }\n\n if (Array.isArray(authHandler))\n authHandler = makeSimpleAuthHandler(authHandler);\n else if (typeof authHandler !== 'function')\n authHandler = makeSimpleAuthHandler(authsAllowed);\n\n let hasSentAuth = false;\n const doNextAuth = (nextAuth) => {\n if (hasSentAuth)\n return;\n hasSentAuth = true;\n\n if (nextAuth === false) {\n const err = new Error('All configured authentication methods failed');\n err.level = 'client-authentication';\n this.emit('error', err);\n this.end();\n return;\n }\n\n if (typeof nextAuth === 'string') {\n // Remain backwards compatible with original `authHandler()` usage,\n // which only supported passing names of next method to try using data\n // from the `connect()` config object\n\n const type = nextAuth;\n if (authsAllowed.indexOf(type) === -1)\n return skipAuth(`Authentication method not allowed: ${type}`);\n\n const username = this.config.username;\n switch (type) {\n case 'password':\n nextAuth = { type, username, password: this.config.password };\n break;\n case 'publickey':\n nextAuth = { type, username, key: privateKey };\n break;\n case 'hostbased':\n nextAuth = {\n type,\n username,\n key: privateKey,\n localHostname: this.config.localHostname,\n localUsername: this.config.localUsername,\n };\n break;\n case 'agent':\n nextAuth = {\n type,\n username,\n agentCtx: new AgentContext(this._agent),\n };\n break;\n case 'keyboard-interactive':\n nextAuth = {\n type,\n username,\n prompt: (...args) => this.emit('keyboard-interactive', ...args),\n };\n break;\n case 'none':\n nextAuth = { type, username };\n break;\n default:\n return skipAuth(\n `Skipping unsupported authentication method: ${nextAuth}`\n );\n }\n } else if (typeof nextAuth !== 'object' || nextAuth === null) {\n return skipAuth(\n `Skipping invalid authentication attempt: ${nextAuth}`\n );\n } else {\n const username = nextAuth.username;\n if (typeof username !== 'string') {\n return skipAuth(\n `Skipping invalid authentication attempt: ${nextAuth}`\n );\n }\n const type = nextAuth.type;\n switch (type) {\n case 'password': {\n const { password } = nextAuth;\n if (typeof password !== 'string' && !Buffer.isBuffer(password))\n return skipAuth('Skipping invalid password auth attempt');\n nextAuth = { type, username, password };\n break;\n }\n case 'publickey': {\n const key = parseKey(nextAuth.key, nextAuth.passphrase);\n if (key instanceof Error)\n return skipAuth('Skipping invalid key auth attempt');\n if (!key.isPrivateKey())\n return skipAuth('Skipping non-private key');\n nextAuth = { type, username, key };\n break;\n }\n case 'hostbased': {\n const { localHostname, localUsername } = nextAuth;\n const key = parseKey(nextAuth.key, nextAuth.passphrase);\n if (key instanceof Error\n || typeof localHostname !== 'string'\n || typeof localUsername !== 'string') {\n return skipAuth('Skipping invalid hostbased auth attempt');\n }\n if (!key.isPrivateKey())\n return skipAuth('Skipping non-private key');\n nextAuth = { type, username, key, localHostname, localUsername };\n break;\n }\n case 'agent': {\n let agent = nextAuth.agent;\n if (typeof agent === 'string' && agent.length) {\n agent = createAgent(agent);\n } else if (!isAgent(agent)) {\n return skipAuth(\n `Skipping invalid agent: ${nextAuth.agent}`\n );\n }\n nextAuth = { type, username, agentCtx: new AgentContext(agent) };\n break;\n }\n case 'keyboard-interactive': {\n const { prompt } = nextAuth;\n if (typeof prompt !== 'function') {\n return skipAuth(\n 'Skipping invalid keyboard-interactive auth attempt'\n );\n }\n nextAuth = { type, username, prompt };\n break;\n }\n case 'none':\n nextAuth = { type, username };\n break;\n default:\n return skipAuth(\n `Skipping unsupported authentication method: ${nextAuth}`\n );\n }\n }\n curAuth = nextAuth;\n\n // Begin authentication method's process\n try {\n const username = curAuth.username;\n switch (curAuth.type) {\n case 'password':\n proto.authPassword(username, curAuth.password);\n break;\n case 'publickey': {\n let keyAlgo;\n curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs);\n if (curAuth.keyAlgos) {\n if (curAuth.keyAlgos.length) {\n keyAlgo = curAuth.keyAlgos[0][0];\n } else {\n return skipAuth(\n 'Skipping key authentication (no mutual hash algorithm)'\n );\n }\n }\n proto.authPK(username, curAuth.key, keyAlgo);\n break;\n }\n case 'hostbased': {\n let keyAlgo;\n let hashAlgo;\n curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs);\n if (curAuth.keyAlgos) {\n if (curAuth.keyAlgos.length) {\n [keyAlgo, hashAlgo] = curAuth.keyAlgos[0];\n } else {\n return skipAuth(\n 'Skipping hostbased authentication (no mutual hash algorithm)'\n );\n }\n }\n\n proto.authHostbased(username,\n curAuth.key,\n curAuth.localHostname,\n curAuth.localUsername,\n keyAlgo,\n (buf, cb) => {\n const signature = curAuth.key.sign(buf, hashAlgo);\n if (signature instanceof Error) {\n signature.message =\n `Error while signing with key: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n\n cb(signature);\n });\n break;\n }\n case 'agent':\n curAuth.agentCtx.init((err) => {\n if (err) {\n err.level = 'agent';\n this.emit('error', err);\n return tryNextAuth();\n }\n tryNextAgentKey();\n });\n break;\n case 'keyboard-interactive':\n proto.authKeyboard(username);\n break;\n case 'none':\n proto.authNone(username);\n break;\n }\n } finally {\n hasSentAuth = false;\n }\n };\n\n function skipAuth(msg) {\n debug && debug(msg);\n process.nextTick(tryNextAuth);\n }\n\n function tryNextAuth() {\n hasSentAuth = false;\n const auth = authHandler(curAuthsLeft, curPartial, doNextAuth);\n if (hasSentAuth || auth === undefined)\n return;\n doNextAuth(auth);\n }\n\n const tryNextAgentKey = () => {\n if (curAuth.type === 'agent') {\n const key = curAuth.agentCtx.nextKey();\n if (key === false) {\n debug && debug('Agent: No more keys left to try');\n debug && debug('Client: agent auth failed');\n tryNextAuth();\n } else {\n const pos = curAuth.agentCtx.pos();\n let keyAlgo;\n curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs);\n if (curAuth.keyAlgos) {\n if (curAuth.keyAlgos.length) {\n keyAlgo = curAuth.keyAlgos[0][0];\n } else {\n debug && debug(\n `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)`\n );\n tryNextAgentKey();\n return;\n }\n }\n debug && debug(`Agent: Trying key #${pos + 1}`);\n proto.authPK(curAuth.username, key, keyAlgo);\n }\n }\n };\n\n const startTimeout = () => {\n if (this.config.readyTimeout > 0) {\n this._readyTimeout = setTimeout(() => {\n const err = new Error('Timed out while waiting for handshake');\n err.level = 'client-timeout';\n this.emit('error', err);\n sock.destroy();\n }, this.config.readyTimeout);\n }\n };\n\n if (!cfg.sock) {\n let host = this.config.host;\n const forceIPv4 = this.config.forceIPv4;\n const forceIPv6 = this.config.forceIPv6;\n\n debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`);\n\n const doConnect = () => {\n startTimeout();\n sock.connect({\n host,\n port: this.config.port,\n localAddress: this.config.localAddress,\n localPort: this.config.localPort\n });\n sock.setMaxListeners(0);\n sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0);\n };\n\n if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) {\n doConnect();\n } else {\n dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => {\n if (err) {\n const type = (forceIPv4 ? 'IPv4' : 'IPv6');\n const error = new Error(\n `Error while looking up ${type} address for '${host}': ${err}`\n );\n clearTimeout(this._readyTimeout);\n error.level = 'client-dns';\n this.emit('error', error);\n this.emit('close');\n return;\n }\n host = address;\n doConnect();\n });\n }\n } else {\n // Custom socket passed in\n startTimeout();\n if (typeof sock.connecting === 'boolean') {\n // net.Socket\n\n if (!sock.connecting) {\n // Already connected\n onConnect();\n }\n } else {\n // Assume socket/stream is already \"connected\"\n onConnect();\n }\n }\n\n return this;\n }\n\n end() {\n if (this._sock && isWritable(this._sock)) {\n this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n this._sock.end();\n }\n return this;\n }\n\n destroy() {\n this._sock && isWritable(this._sock) && this._sock.destroy();\n return this;\n }\n\n exec(cmd, opts, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) };\n\n openChannel(this, 'session', extraOpts, (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n const todo = [];\n\n function reqCb(err) {\n if (err) {\n chan.close();\n cb(err);\n return;\n }\n if (todo.length)\n todo.shift()();\n }\n\n if (this.config.allowAgentFwd === true\n || (opts\n && opts.agentForward === true\n && this._agent !== undefined)) {\n todo.push(() => reqAgentFwd(chan, reqCb));\n }\n\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.env === 'object' && opts.env !== null)\n reqEnv(chan, opts.env);\n if ((typeof opts.pty === 'object' && opts.pty !== null)\n || opts.pty === true) {\n todo.push(() => reqPty(chan, opts.pty, reqCb));\n }\n if ((typeof opts.x11 === 'object' && opts.x11 !== null)\n || opts.x11 === 'number'\n || opts.x11 === true) {\n todo.push(() => reqX11(chan, opts.x11, reqCb));\n }\n }\n\n todo.push(() => reqExec(chan, cmd, opts, cb));\n todo.shift()();\n });\n\n return this;\n }\n\n shell(wndopts, opts, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof wndopts === 'function') {\n cb = wndopts;\n wndopts = opts = undefined;\n } else if (typeof opts === 'function') {\n cb = opts;\n opts = undefined;\n }\n if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) {\n opts = wndopts;\n wndopts = undefined;\n }\n\n openChannel(this, 'session', (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n const todo = [];\n\n function reqCb(err) {\n if (err) {\n chan.close();\n cb(err);\n return;\n }\n if (todo.length)\n todo.shift()();\n }\n\n if (this.config.allowAgentFwd === true\n || (opts\n && opts.agentForward === true\n && this._agent !== undefined)) {\n todo.push(() => reqAgentFwd(chan, reqCb));\n }\n\n if (wndopts !== false)\n todo.push(() => reqPty(chan, wndopts, reqCb));\n\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.env === 'object' && opts.env !== null)\n reqEnv(chan, opts.env);\n if ((typeof opts.x11 === 'object' && opts.x11 !== null)\n || opts.x11 === 'number'\n || opts.x11 === true) {\n todo.push(() => reqX11(chan, opts.x11, reqCb));\n }\n }\n\n todo.push(() => reqShell(chan, cb));\n todo.shift()();\n });\n\n return this;\n }\n\n subsys(name, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n openChannel(this, 'session', (err, chan) => {\n if (err) {\n cb(err);\n return;\n }\n\n reqSubsystem(chan, name, (err, stream) => {\n if (err) {\n cb(err);\n return;\n }\n\n cb(undefined, stream);\n });\n });\n\n return this;\n }\n\n forwardIn(bindAddr, bindPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request for the server to start forwarding TCP connections to us\n // on a particular address and port\n\n const wantReply = (typeof cb === 'function');\n\n if (wantReply) {\n this._callbacks.push((had_err, data) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${bindAddr}:${bindPort}`));\n return;\n }\n\n let realPort = bindPort;\n if (bindPort === 0 && data && data.length >= 4) {\n realPort = readUInt32BE(data, 0);\n if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG))\n bindPort = realPort;\n }\n\n this._forwarding[`${bindAddr}:${bindPort}`] = realPort;\n\n cb(undefined, realPort);\n });\n }\n\n this._protocol.tcpipForward(bindAddr, bindPort, wantReply);\n\n return this;\n }\n\n unforwardIn(bindAddr, bindPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request to stop forwarding us new connections for a particular\n // address and port\n\n const wantReply = (typeof cb === 'function');\n\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`));\n return;\n }\n\n delete this._forwarding[`${bindAddr}:${bindPort}`];\n\n cb();\n });\n }\n\n this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply);\n\n return this;\n }\n\n forwardOut(srcIP, srcPort, dstIP, dstPort, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n // Send a request to forward a TCP connection to the server\n\n const cfg = {\n srcIP: srcIP,\n srcPort: srcPort,\n dstIP: dstIP,\n dstPort: dstPort\n };\n\n if (typeof cb !== 'function')\n cb = noop;\n\n openChannel(this, 'direct-tcpip', cfg, cb);\n\n return this;\n }\n\n openssh_noMoreSessions(cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to disable future sessions'));\n return;\n }\n\n cb();\n });\n }\n\n this._protocol.openssh_noMoreSessions(wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_forwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${socketPath}`));\n return;\n }\n this._forwardingUnix[socketPath] = true;\n cb();\n });\n }\n\n this._protocol.openssh_streamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_unforwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to unbind from ${socketPath}`));\n return;\n }\n delete this._forwardingUnix[socketPath];\n cb();\n });\n }\n\n this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n openssh_forwardOutStreamLocal(socketPath, cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n if (typeof cb !== 'function')\n cb = noop;\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb);\n return this;\n }\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }\n\n sftp(cb) {\n if (!this._sock || !isWritable(this._sock))\n throw new Error('Not connected');\n\n openChannel(this, 'sftp', (err, sftp) => {\n if (err) {\n cb(err);\n return;\n }\n\n reqSubsystem(sftp, 'sftp', (err, sftp_) => {\n if (err) {\n cb(err);\n return;\n }\n\n function removeListeners() {\n sftp.removeListener('ready', onReady);\n sftp.removeListener('error', onError);\n sftp.removeListener('exit', onExit);\n sftp.removeListener('close', onExit);\n }\n\n function onReady() {\n // TODO: do not remove exit/close in case remote end closes the\n // channel abruptly and we need to notify outstanding callbacks\n removeListeners();\n cb(undefined, sftp);\n }\n\n function onError(err) {\n removeListeners();\n cb(err);\n }\n\n function onExit(code, signal) {\n removeListeners();\n let msg;\n if (typeof code === 'number')\n msg = `Received exit code ${code} while establishing SFTP session`;\n else if (signal !== undefined)\n msg = `Received signal ${signal} while establishing SFTP session`;\n else\n msg = 'Received unexpected SFTP session termination';\n const err = new Error(msg);\n err.code = code;\n err.signal = signal;\n cb(err);\n }\n\n sftp.on('ready', onReady)\n .on('error', onError)\n .on('exit', onExit)\n .on('close', onExit);\n\n sftp._init();\n });\n });\n\n return this;\n }\n\n setNoDelay(noDelay) {\n if (this._sock && typeof this._sock.setNoDelay === 'function')\n this._sock.setNoDelay(noDelay);\n\n return this;\n }\n}\n\nfunction openChannel(self, type, opts, cb) {\n // Ask the server to open a channel for some purpose\n // (e.g. session (sftp, exec, shell), or forwarding a TCP connection\n const initWindow = MAX_WINDOW;\n const maxPacket = PACKET_SIZE;\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const wrapper = (err, stream) => {\n cb(err, stream);\n };\n wrapper.type = type;\n\n const localChan = self._chanMgr.add(wrapper);\n\n if (localChan === -1) {\n cb(new Error('No free channels available'));\n return;\n }\n\n switch (type) {\n case 'session':\n case 'sftp':\n self._protocol.session(localChan, initWindow, maxPacket);\n break;\n case 'direct-tcpip':\n self._protocol.directTcpip(localChan, initWindow, maxPacket, opts);\n break;\n case 'direct-streamlocal@openssh.com':\n self._protocol.openssh_directStreamLocal(\n localChan, initWindow, maxPacket, opts\n );\n break;\n default:\n throw new Error(`Unsupported channel type: ${type}`);\n }\n}\n\nfunction reqX11(chan, screen, cb) {\n // Asks server to start sending us X11 connections\n const cfg = {\n single: false,\n protocol: 'MIT-MAGIC-COOKIE-1',\n cookie: undefined,\n screen: 0\n };\n\n if (typeof screen === 'function') {\n cb = screen;\n } else if (typeof screen === 'object' && screen !== null) {\n if (typeof screen.single === 'boolean')\n cfg.single = screen.single;\n if (typeof screen.screen === 'number')\n cfg.screen = screen.screen;\n if (typeof screen.protocol === 'string')\n cfg.protocol = screen.protocol;\n if (typeof screen.cookie === 'string')\n cfg.cookie = screen.cookie;\n else if (Buffer.isBuffer(screen.cookie))\n cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length);\n }\n if (cfg.cookie === undefined)\n cfg.cookie = randomCookie();\n\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n if (wantReply)\n cb(new Error('Channel is not open'));\n return;\n }\n\n if (wantReply) {\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to request X11'));\n return;\n }\n\n chan._hasX11 = true;\n ++chan._client._acceptX11;\n chan.once('close', () => {\n if (chan._client._acceptX11)\n --chan._client._acceptX11;\n });\n\n cb();\n });\n }\n\n chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply);\n}\n\nfunction reqPty(chan, opts, cb) {\n let rows = 24;\n let cols = 80;\n let width = 640;\n let height = 480;\n let term = 'vt100';\n let modes = null;\n\n if (typeof opts === 'function') {\n cb = opts;\n } else if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.rows === 'number')\n rows = opts.rows;\n if (typeof opts.cols === 'number')\n cols = opts.cols;\n if (typeof opts.width === 'number')\n width = opts.width;\n if (typeof opts.height === 'number')\n height = opts.height;\n if (typeof opts.term === 'string')\n term = opts.term;\n if (typeof opts.modes === 'object')\n modes = opts.modes;\n }\n\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n if (wantReply)\n cb(new Error('Channel is not open'));\n return;\n }\n\n if (wantReply) {\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to request a pseudo-terminal'));\n return;\n }\n cb();\n });\n }\n\n chan._client._protocol.pty(chan.outgoing.id,\n rows,\n cols,\n height,\n width,\n term,\n modes,\n wantReply);\n}\n\nfunction reqAgentFwd(chan, cb) {\n const wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n wantReply && cb(new Error('Channel is not open'));\n return;\n }\n if (chan._client._agentFwdEnabled) {\n wantReply && cb(false);\n return;\n }\n\n chan._client._agentFwdEnabled = true;\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n chan._client._agentFwdEnabled = false;\n if (wantReply) {\n cb(had_err !== true\n ? had_err\n : new Error('Unable to request agent forwarding'));\n }\n return;\n }\n\n if (wantReply)\n cb();\n });\n\n chan._client._protocol.openssh_agentForward(chan.outgoing.id, true);\n}\n\nfunction reqShell(chan, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to open shell'));\n return;\n }\n chan.subtype = 'shell';\n cb(undefined, chan);\n });\n\n chan._client._protocol.shell(chan.outgoing.id, true);\n}\n\nfunction reqExec(chan, cmd, opts, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true ? had_err : new Error('Unable to exec'));\n return;\n }\n chan.subtype = 'exec';\n chan.allowHalfOpen = (opts.allowHalfOpen !== false);\n cb(undefined, chan);\n });\n\n chan._client._protocol.exec(chan.outgoing.id, cmd, true);\n}\n\nfunction reqEnv(chan, env) {\n if (chan.outgoing.state !== 'open')\n return;\n\n const keys = Object.keys(env || {});\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n const val = env[key];\n chan._client._protocol.env(chan.outgoing.id, key, val, false);\n }\n}\n\nfunction reqSubsystem(chan, name, cb) {\n if (chan.outgoing.state !== 'open') {\n cb(new Error('Channel is not open'));\n return;\n }\n\n chan._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to start subsystem: ${name}`));\n return;\n }\n chan.subtype = 'subsystem';\n cb(undefined, chan);\n });\n\n chan._client._protocol.subsystem(chan.outgoing.id, name, true);\n}\n\n// TODO: inline implementation into single call site\nfunction onCHANNEL_OPEN(self, info) {\n // The server is trying to open a channel with us, this is usually when\n // we asked the server to forward us connections on some port and now they\n // are asking us to accept/deny an incoming connection on their side\n\n let localChan = -1;\n let reason;\n\n const accept = () => {\n const chanInfo = {\n type: info.type,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const stream = new Channel(self, chanInfo);\n self._chanMgr.update(localChan, stream);\n\n self._protocol.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n return stream;\n };\n const reject = () => {\n if (reason === undefined) {\n if (localChan === -1)\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n else\n reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;\n }\n\n if (localChan !== -1)\n self._chanMgr.remove(localChan);\n\n self._protocol.channelOpenFail(info.sender, reason, '');\n };\n const reserveChannel = () => {\n localChan = self._chanMgr.add();\n\n if (localChan === -1) {\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of incoming channel open: '\n + 'no channels available'\n );\n }\n }\n\n return (localChan !== -1);\n };\n\n const data = info.data;\n switch (info.type) {\n case 'forwarded-tcpip': {\n const val = self._forwarding[`${data.destIP}:${data.destPort}`];\n if (val !== undefined && reserveChannel()) {\n if (data.destPort === 0)\n data.destPort = val;\n self.emit('tcp connection', data, accept, reject);\n return;\n }\n break;\n }\n case 'forwarded-streamlocal@openssh.com':\n if (self._forwardingUnix[data.socketPath] !== undefined\n && reserveChannel()) {\n self.emit('unix connection', data, accept, reject);\n return;\n }\n break;\n case 'auth-agent@openssh.com':\n if (self._agentFwdEnabled\n && typeof self._agent.getStream === 'function'\n && reserveChannel()) {\n self._agent.getStream((err, stream) => {\n if (err)\n return reject();\n\n const upstream = accept();\n upstream.pipe(stream).pipe(upstream);\n });\n return;\n }\n break;\n case 'x11':\n if (self._acceptX11 !== 0 && reserveChannel()) {\n self.emit('x11', data, accept, reject);\n return;\n }\n break;\n default:\n // Automatically reject any unsupported channel open requests\n reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of unsupported incoming channel open '\n + `type: ${info.type}`\n );\n }\n }\n\n if (reason === undefined) {\n reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n if (self.config.debug) {\n self.config.debug(\n 'Client: Automatic rejection of unexpected incoming channel open for: '\n + info.type\n );\n }\n }\n\n reject();\n}\n\nconst randomCookie = (() => {\n const buffer = Buffer.allocUnsafe(16);\n return () => {\n randomFillSync(buffer, 0, 16);\n return buffer.hexSlice(0, 16);\n };\n})();\n\nfunction makeSimpleAuthHandler(authList) {\n if (!Array.isArray(authList))\n throw new Error('authList must be an array');\n\n let a = 0;\n return (authsLeft, partialSuccess, cb) => {\n if (a === authList.length)\n return false;\n return authList[a++];\n };\n}\n\nfunction hostKeysProve(client, keys_, cb) {\n if (!client._sock || !isWritable(client._sock))\n return;\n\n if (typeof cb !== 'function')\n cb = noop;\n\n if (!Array.isArray(keys_))\n throw new TypeError('Invalid keys argument type');\n\n const keys = [];\n for (const key of keys_) {\n const parsed = parseKey(key);\n if (parsed instanceof Error)\n throw parsed;\n keys.push(parsed);\n }\n\n if (!client.config.strictVendor\n || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) {\n client._callbacks.push((had_err, data) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error('Server failed to prove supplied keys'));\n return;\n }\n\n // TODO: move all of this parsing/verifying logic out of the client?\n const ret = [];\n let keyIdx = 0;\n bufferParser.init(data, 0);\n while (bufferParser.avail()) {\n if (keyIdx === keys.length)\n break;\n const key = keys[keyIdx++];\n const keyPublic = key.getPublicSSH();\n\n const sigEntry = bufferParser.readString();\n sigParser.init(sigEntry, 0);\n const type = sigParser.readString(true);\n let value = sigParser.readString();\n\n let algo;\n if (type !== key.type) {\n if (key.type === 'ssh-rsa') {\n switch (type) {\n case 'rsa-sha2-256':\n algo = 'sha256';\n break;\n case 'rsa-sha2-512':\n algo = 'sha512';\n break;\n default:\n continue;\n }\n } else {\n continue;\n }\n }\n\n const sessionID = client._protocol._kex.sessionID;\n const verifyData = Buffer.allocUnsafe(\n 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length\n );\n let p = 0;\n writeUInt32BE(verifyData, 29, p);\n verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);\n writeUInt32BE(verifyData, sessionID.length, p += 29);\n bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4);\n writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length);\n bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4);\n\n if (!(value = sigSSHToASN1(value, type)))\n continue;\n if (key.verify(verifyData, value, algo) === true)\n ret.push(key);\n }\n sigParser.clear();\n bufferParser.clear();\n\n cb(null, ret);\n });\n\n client._protocol.openssh_hostKeysProve(keys);\n return;\n }\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n}\n\nfunction getKeyAlgos(client, key, serverSigAlgs) {\n switch (key.type) {\n case 'ssh-rsa':\n if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) {\n if (!Array.isArray(serverSigAlgs))\n serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512'];\n else\n serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512', ...serverSigAlgs];\n }\n if (Array.isArray(serverSigAlgs)) {\n if (serverSigAlgs.indexOf('rsa-sha2-256') !== -1)\n return [['rsa-sha2-256', 'sha256']];\n if (serverSigAlgs.indexOf('rsa-sha2-512') !== -1)\n return [['rsa-sha2-512', 'sha512']];\n if (serverSigAlgs.indexOf('ssh-rsa') === -1)\n return [];\n }\n return [['ssh-rsa', 'sha1']];\n }\n}\n\nmodule.exports = Client;\n","'use strict';\n\nconst { Agent: HttpAgent } = require('http');\nconst { Agent: HttpsAgent } = require('https');\nconst { connect: tlsConnect } = require('tls');\n\nlet Client;\n\nfor (const ctor of [HttpAgent, HttpsAgent]) {\n class SSHAgent extends ctor {\n constructor(connectCfg, agentOptions) {\n super(agentOptions);\n\n this._connectCfg = connectCfg;\n this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost';\n }\n\n createConnection(options, cb) {\n const srcIP = (options && options.localAddress) || this._defaultSrcIP;\n const srcPort = (options && options.localPort) || 0;\n const dstIP = options.host;\n const dstPort = options.port;\n\n if (Client === undefined)\n Client = require('./client.js');\n\n const client = new Client();\n let triedForward = false;\n client.on('ready', () => {\n client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => {\n triedForward = true;\n if (err) {\n client.end();\n return cb(err);\n }\n stream.once('close', () => client.end());\n cb(null, decorateStream(stream, ctor, options));\n });\n }).on('error', cb).on('close', () => {\n if (!triedForward)\n cb(new Error('Unexpected connection close'));\n }).connect(this._connectCfg);\n }\n }\n\n exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent;\n}\n\nfunction noop() {}\n\nfunction decorateStream(stream, ctor, options) {\n if (ctor === HttpAgent) {\n // HTTP\n stream.setKeepAlive = noop;\n stream.setNoDelay = noop;\n stream.setTimeout = noop;\n stream.ref = noop;\n stream.unref = noop;\n stream.destroySoon = stream.destroy;\n return stream;\n }\n\n // HTTPS\n options.socket = stream;\n const wrapped = tlsConnect(options);\n\n // This is a workaround for a regression in node v12.16.3+\n // https://github.com/nodejs/node/issues/35904\n const onClose = (() => {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n if (stream.isPaused())\n stream.resume();\n };\n })();\n // 'end' listener is needed because 'close' is not emitted in some scenarios\n // in node v12.x for some unknown reason\n wrapped.on('end', onClose).on('close', onClose);\n\n return wrapped;\n}\n","'use strict';\n\nconst {\n AgentProtocol,\n BaseAgent,\n createAgent,\n CygwinAgent,\n OpenSSHAgent,\n PageantAgent,\n} = require('./agent.js');\nconst {\n SSHTTPAgent: HTTPAgent,\n SSHTTPSAgent: HTTPSAgent,\n} = require('./http-agents.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst {\n flagsToString,\n OPEN_MODE,\n STATUS_CODE,\n stringToFlags,\n} = require('./protocol/SFTP.js');\n\nmodule.exports = {\n AgentProtocol,\n BaseAgent,\n createAgent,\n Client: require('./client.js'),\n CygwinAgent,\n HTTPAgent,\n HTTPSAgent,\n OpenSSHAgent,\n PageantAgent,\n Server: require('./server.js'),\n utils: {\n parseKey,\n ...require('./keygen.js'),\n sftp: {\n flagsToString,\n OPEN_MODE,\n STATUS_CODE,\n stringToFlags,\n },\n },\n};\n","'use strict';\n\nconst {\n createCipheriv,\n generateKeyPair: generateKeyPair_,\n generateKeyPairSync: generateKeyPairSync_,\n getCurves,\n randomBytes,\n} = require('crypto');\n\nconst { Ber } = require('asn1');\nconst bcrypt_pbkdf = require('bcrypt-pbkdf').pbkdf;\n\nconst { CIPHER_INFO } = require('./protocol/crypto.js');\n\nconst SALT_LEN = 16;\nconst DEFAULT_ROUNDS = 16;\n\nconst curves = getCurves();\nconst ciphers = new Map(Object.entries(CIPHER_INFO));\n\nfunction makeArgs(type, opts) {\n if (typeof type !== 'string')\n throw new TypeError('Key type must be a string');\n\n const publicKeyEncoding = { type: 'spki', format: 'der' };\n const privateKeyEncoding = { type: 'pkcs8', format: 'der' };\n\n switch (type.toLowerCase()) {\n case 'rsa': {\n if (typeof opts !== 'object' || opts === null)\n throw new TypeError('Missing options object for RSA key');\n const modulusLength = opts.bits;\n if (!Number.isInteger(modulusLength))\n throw new TypeError('RSA bits must be an integer');\n if (modulusLength <= 0 || modulusLength > 16384)\n throw new RangeError('RSA bits must be non-zero and <= 16384');\n return ['rsa', { modulusLength, publicKeyEncoding, privateKeyEncoding }];\n }\n case 'ecdsa': {\n if (typeof opts !== 'object' || opts === null)\n throw new TypeError('Missing options object for ECDSA key');\n if (!Number.isInteger(opts.bits))\n throw new TypeError('ECDSA bits must be an integer');\n let namedCurve;\n switch (opts.bits) {\n case 256:\n namedCurve = 'prime256v1';\n break;\n case 384:\n namedCurve = 'secp384r1';\n break;\n case 521:\n namedCurve = 'secp521r1';\n break;\n default:\n throw new Error('ECDSA bits must be 256, 384, or 521');\n }\n if (!curves.includes(namedCurve))\n throw new Error('Unsupported ECDSA bits value');\n return ['ec', { namedCurve, publicKeyEncoding, privateKeyEncoding }];\n }\n case 'ed25519':\n return ['ed25519', { publicKeyEncoding, privateKeyEncoding }];\n default:\n throw new Error(`Unsupported key type: ${type}`);\n }\n}\n\nfunction parseDERs(keyType, pub, priv) {\n switch (keyType) {\n case 'rsa': {\n // Note: we don't need to parse the public key since the PKCS8 private key\n // already includes the public key parameters\n\n // Parse private key\n let reader = new Ber.Reader(priv);\n reader.readSequence();\n\n // - Version\n if (reader.readInt() !== 0)\n throw new Error('Unsupported version in RSA private key');\n\n // - Algorithm\n reader.readSequence();\n if (reader.readOID() !== '1.2.840.113549.1.1.1')\n throw new Error('Bad RSA private OID');\n // - Algorithm parameters (RSA has none)\n if (reader.readByte() !== Ber.Null)\n throw new Error('Malformed RSA private key (expected null)');\n if (reader.readByte() !== 0x00) {\n throw new Error(\n 'Malformed RSA private key (expected zero-length null)'\n );\n }\n\n reader = new Ber.Reader(reader.readString(Ber.OctetString, true));\n reader.readSequence();\n if (reader.readInt() !== 0)\n throw new Error('Unsupported version in RSA private key');\n const n = reader.readString(Ber.Integer, true);\n const e = reader.readString(Ber.Integer, true);\n const d = reader.readString(Ber.Integer, true);\n const p = reader.readString(Ber.Integer, true);\n const q = reader.readString(Ber.Integer, true);\n reader.readString(Ber.Integer, true); // dmp1\n reader.readString(Ber.Integer, true); // dmq1\n const iqmp = reader.readString(Ber.Integer, true);\n\n /*\n OpenSSH RSA private key:\n string \"ssh-rsa\"\n string n -- public\n string e -- public\n string d -- private\n string iqmp -- private\n string p -- private\n string q -- private\n */\n const keyName = Buffer.from('ssh-rsa');\n const privBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + n.length\n + 4 + e.length\n + 4 + d.length\n + 4 + iqmp.length\n + 4 + p.length\n + 4 + q.length\n );\n let pos = 0;\n\n privBuf.writeUInt32BE(keyName.length, pos += 0);\n privBuf.set(keyName, pos += 4);\n privBuf.writeUInt32BE(n.length, pos += keyName.length);\n privBuf.set(n, pos += 4);\n privBuf.writeUInt32BE(e.length, pos += n.length);\n privBuf.set(e, pos += 4);\n privBuf.writeUInt32BE(d.length, pos += e.length);\n privBuf.set(d, pos += 4);\n privBuf.writeUInt32BE(iqmp.length, pos += d.length);\n privBuf.set(iqmp, pos += 4);\n privBuf.writeUInt32BE(p.length, pos += iqmp.length);\n privBuf.set(p, pos += 4);\n privBuf.writeUInt32BE(q.length, pos += p.length);\n privBuf.set(q, pos += 4);\n\n /*\n OpenSSH RSA public key:\n string \"ssh-rsa\"\n string e -- public\n string n -- public\n */\n const pubBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + e.length\n + 4 + n.length\n );\n pos = 0;\n\n pubBuf.writeUInt32BE(keyName.length, pos += 0);\n pubBuf.set(keyName, pos += 4);\n pubBuf.writeUInt32BE(e.length, pos += keyName.length);\n pubBuf.set(e, pos += 4);\n pubBuf.writeUInt32BE(n.length, pos += e.length);\n pubBuf.set(n, pos += 4);\n\n return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf };\n }\n case 'ec': {\n // Parse public key\n let reader = new Ber.Reader(pub);\n reader.readSequence();\n\n reader.readSequence();\n if (reader.readOID() !== '1.2.840.10045.2.1')\n throw new Error('Bad ECDSA public OID');\n // Skip curve OID, we'll get it from the private key\n reader.readOID();\n let pubBin = reader.readString(Ber.BitString, true);\n {\n // Remove leading zero bytes\n let i = 0;\n for (; i < pubBin.length && pubBin[i] === 0x00; ++i);\n if (i > 0)\n pubBin = pubBin.slice(i);\n }\n\n // Parse private key\n reader = new Ber.Reader(priv);\n reader.readSequence();\n\n // - Version\n if (reader.readInt() !== 0)\n throw new Error('Unsupported version in ECDSA private key');\n\n reader.readSequence();\n if (reader.readOID() !== '1.2.840.10045.2.1')\n throw new Error('Bad ECDSA private OID');\n const curveOID = reader.readOID();\n let sshCurveName;\n switch (curveOID) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n sshCurveName = 'nistp256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n sshCurveName = 'nistp384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n sshCurveName = 'nistp521';\n break;\n default:\n throw new Error('Unsupported curve in ECDSA private key');\n }\n\n reader = new Ber.Reader(reader.readString(Ber.OctetString, true));\n reader.readSequence();\n\n // - Version\n if (reader.readInt() !== 1)\n throw new Error('Unsupported version in ECDSA private key');\n\n // Add leading zero byte to prevent negative bignum in private key\n const privBin = Buffer.concat([\n Buffer.from([0x00]),\n reader.readString(Ber.OctetString, true)\n ]);\n\n /*\n OpenSSH ECDSA private key:\n string \"ecdsa-sha2-\"\n string curve name\n string Q -- public\n string d -- private\n */\n const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`);\n sshCurveName = Buffer.from(sshCurveName);\n const privBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + sshCurveName.length\n + 4 + pubBin.length\n + 4 + privBin.length\n );\n let pos = 0;\n\n privBuf.writeUInt32BE(keyName.length, pos += 0);\n privBuf.set(keyName, pos += 4);\n privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length);\n privBuf.set(sshCurveName, pos += 4);\n privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length);\n privBuf.set(pubBin, pos += 4);\n privBuf.writeUInt32BE(privBin.length, pos += pubBin.length);\n privBuf.set(privBin, pos += 4);\n\n /*\n OpenSSH ECDSA public key:\n string \"ecdsa-sha2-\"\n string curve name\n string Q -- public\n */\n const pubBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + sshCurveName.length\n + 4 + pubBin.length\n );\n pos = 0;\n\n pubBuf.writeUInt32BE(keyName.length, pos += 0);\n pubBuf.set(keyName, pos += 4);\n pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length);\n pubBuf.set(sshCurveName, pos += 4);\n pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length);\n pubBuf.set(pubBin, pos += 4);\n\n return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf };\n }\n case 'ed25519': {\n // Parse public key\n let reader = new Ber.Reader(pub);\n reader.readSequence();\n\n // - Algorithm\n reader.readSequence();\n if (reader.readOID() !== '1.3.101.112')\n throw new Error('Bad ED25519 public OID');\n // - Attributes (absent for ED25519)\n\n let pubBin = reader.readString(Ber.BitString, true);\n {\n // Remove leading zero bytes\n let i = 0;\n for (; i < pubBin.length && pubBin[i] === 0x00; ++i);\n if (i > 0)\n pubBin = pubBin.slice(i);\n }\n\n // Parse private key\n reader = new Ber.Reader(priv);\n reader.readSequence();\n\n // - Version\n if (reader.readInt() !== 0)\n throw new Error('Unsupported version in ED25519 private key');\n\n // - Algorithm\n reader.readSequence();\n if (reader.readOID() !== '1.3.101.112')\n throw new Error('Bad ED25519 private OID');\n // - Attributes (absent)\n\n reader = new Ber.Reader(reader.readString(Ber.OctetString, true));\n const privBin = reader.readString(Ber.OctetString, true);\n\n /*\n OpenSSH ed25519 private key:\n string \"ssh-ed25519\"\n string public key\n string private key + public key\n */\n const keyName = Buffer.from('ssh-ed25519');\n const privBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + pubBin.length\n + 4 + (privBin.length + pubBin.length)\n );\n let pos = 0;\n\n privBuf.writeUInt32BE(keyName.length, pos += 0);\n privBuf.set(keyName, pos += 4);\n privBuf.writeUInt32BE(pubBin.length, pos += keyName.length);\n privBuf.set(pubBin, pos += 4);\n privBuf.writeUInt32BE(\n privBin.length + pubBin.length,\n pos += pubBin.length\n );\n privBuf.set(privBin, pos += 4);\n privBuf.set(pubBin, pos += privBin.length);\n\n /*\n OpenSSH ed25519 public key:\n string \"ssh-ed25519\"\n string public key\n */\n const pubBuf = Buffer.allocUnsafe(\n 4 + keyName.length\n + 4 + pubBin.length\n );\n pos = 0;\n\n pubBuf.writeUInt32BE(keyName.length, pos += 0);\n pubBuf.set(keyName, pos += 4);\n pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length);\n pubBuf.set(pubBin, pos += 4);\n\n return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf };\n }\n }\n}\n\nfunction convertKeys(keyType, pub, priv, opts) {\n let format = 'new';\n let encrypted;\n let comment = '';\n if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.comment === 'string' && opts.comment)\n comment = opts.comment;\n if (typeof opts.format === 'string' && opts.format)\n format = opts.format;\n if (opts.passphrase) {\n let passphrase;\n if (typeof opts.passphrase === 'string')\n passphrase = Buffer.from(opts.passphrase);\n else if (Buffer.isBuffer(opts.passphrase))\n passphrase = opts.passphrase;\n else\n throw new Error('Invalid passphrase');\n\n if (opts.cipher === undefined)\n throw new Error('Missing cipher name');\n const cipher = ciphers.get(opts.cipher);\n if (cipher === undefined)\n throw new Error('Invalid cipher name');\n\n if (format === 'new') {\n let rounds = DEFAULT_ROUNDS;\n if (opts.rounds !== undefined) {\n if (!Number.isInteger(opts.rounds))\n throw new TypeError('rounds must be an integer');\n if (opts.rounds > 0)\n rounds = opts.rounds;\n }\n\n const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen);\n const salt = randomBytes(SALT_LEN);\n const r = bcrypt_pbkdf(\n passphrase,\n passphrase.length,\n salt,\n salt.length,\n gen,\n gen.length,\n rounds\n );\n if (r !== 0)\n return new Error('Failed to generate information to encrypt key');\n\n /*\n string salt\n uint32 rounds\n */\n const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4);\n {\n let pos = 0;\n kdfOptions.writeUInt32BE(salt.length, pos += 0);\n kdfOptions.set(salt, pos += 4);\n kdfOptions.writeUInt32BE(rounds, pos += salt.length);\n }\n\n encrypted = {\n cipher,\n cipherName: opts.cipher,\n kdfName: 'bcrypt',\n kdfOptions,\n key: gen.slice(0, cipher.keyLen),\n iv: gen.slice(cipher.keyLen),\n };\n }\n }\n }\n\n switch (format) {\n case 'new': {\n let privateB64 = '-----BEGIN OPENSSH PRIVATE KEY-----\\n';\n let publicB64;\n /*\n byte[] \"openssh-key-v1\\0\"\n string ciphername\n string kdfname\n string kdfoptions\n uint32 number of keys N\n string publickey1\n string encrypted, padded list of private keys\n uint32 checkint\n uint32 checkint\n byte[] privatekey1\n string comment1\n byte 1\n byte 2\n byte 3\n ...\n byte padlen % 255\n */\n const cipherName = Buffer.from(encrypted ? encrypted.cipherName : 'none');\n const kdfName = Buffer.from(encrypted ? encrypted.kdfName : 'none');\n const kdfOptions = (encrypted ? encrypted.kdfOptions : Buffer.alloc(0));\n const blockLen = (encrypted ? encrypted.cipher.blockLen : 8);\n\n const parsed = parseDERs(keyType, pub, priv);\n\n const checkInt = randomBytes(4);\n const commentBin = Buffer.from(comment);\n const privBlobLen = (4 + 4 + parsed.priv.length + 4 + commentBin.length);\n let padding = [];\n for (let i = 1; ((privBlobLen + padding.length) % blockLen); ++i)\n padding.push(i & 0xFF);\n padding = Buffer.from(padding);\n\n let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length);\n let extra;\n {\n let pos = 0;\n privBlob.set(checkInt, pos += 0);\n privBlob.set(checkInt, pos += 4);\n privBlob.set(parsed.priv, pos += 4);\n privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length);\n privBlob.set(commentBin, pos += 4);\n privBlob.set(padding, pos += commentBin.length);\n }\n\n if (encrypted) {\n const options = { authTagLength: encrypted.cipher.authLen };\n const cipher = createCipheriv(\n encrypted.cipher.sslName,\n encrypted.key,\n encrypted.iv,\n options\n );\n cipher.setAutoPadding(false);\n privBlob = Buffer.concat([ cipher.update(privBlob), cipher.final() ]);\n if (encrypted.cipher.authLen > 0)\n extra = cipher.getAuthTag();\n else\n extra = Buffer.alloc(0);\n encrypted.key.fill(0);\n encrypted.iv.fill(0);\n } else {\n extra = Buffer.alloc(0);\n }\n\n const magicBytes = Buffer.from('openssh-key-v1\\0');\n const privBin = Buffer.allocUnsafe(\n magicBytes.length\n + 4 + cipherName.length\n + 4 + kdfName.length\n + 4 + kdfOptions.length\n + 4\n + 4 + parsed.pub.length\n + 4 + privBlob.length\n + extra.length\n );\n {\n let pos = 0;\n privBin.set(magicBytes, pos += 0);\n privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length);\n privBin.set(cipherName, pos += 4);\n privBin.writeUInt32BE(kdfName.length, pos += cipherName.length);\n privBin.set(kdfName, pos += 4);\n privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length);\n privBin.set(kdfOptions, pos += 4);\n privBin.writeUInt32BE(1, pos += kdfOptions.length);\n privBin.writeUInt32BE(parsed.pub.length, pos += 4);\n privBin.set(parsed.pub, pos += 4);\n privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length);\n privBin.set(privBlob, pos += 4);\n privBin.set(extra, pos += privBlob.length);\n }\n\n {\n const b64 = privBin.base64Slice(0, privBin.length);\n let formatted = b64.replace(/.{64}/g, '$&\\n');\n if (b64.length & 63)\n formatted += '\\n';\n privateB64 += formatted;\n }\n\n {\n const b64 = parsed.pub.base64Slice(0, parsed.pub.length);\n publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ''}`;\n }\n\n privateB64 += '-----END OPENSSH PRIVATE KEY-----\\n';\n return {\n private: privateB64,\n public: publicB64,\n };\n }\n default:\n throw new Error('Invalid output key format');\n }\n}\n\nfunction noop() {}\n\nmodule.exports = {\n generateKeyPair: (keyType, opts, cb) => {\n if (typeof opts === 'function') {\n cb = opts;\n opts = undefined;\n }\n if (typeof cb !== 'function')\n cb = noop;\n const args = makeArgs(keyType, opts);\n generateKeyPair_(...args, (err, pub, priv) => {\n if (err)\n return cb(err);\n let ret;\n try {\n ret = convertKeys(args[0], pub, priv, opts);\n } catch (ex) {\n return cb(ex);\n }\n cb(null, ret);\n });\n },\n generateKeyPairSync: (keyType, opts) => {\n const args = makeArgs(keyType, opts);\n const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args);\n return convertKeys(args[0], pub, priv, opts);\n }\n};\n","/*\n TODO:\n * Replace `buffer._pos` usage in keyParser.js and elsewhere\n * Utilize optional \"writev\" support when writing packets from\n cipher.encrypt()\n * Built-in support for automatic re-keying, on by default\n * Revisit receiving unexpected/unknown packets\n * Error (fatal or otherwise) or ignore or pass on to user (in some or all\n cases)?\n * Including server/client check for single directional packet types?\n * Check packets for validity or bail as early as possible?\n * Automatic re-key every 2**31 packets after the last key exchange (sent or\n received), as suggested by RFC4344. OpenSSH currently does this.\n * Automatic re-key every so many blocks depending on cipher. RFC4344:\n Because of a birthday property of block ciphers and some modes of\n operation, implementations must be careful not to encrypt too many\n blocks with the same encryption key.\n\n Let L be the block length (in bits) of an SSH encryption method's\n block cipher (e.g., 128 for AES). If L is at least 128, then, after\n rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4)\n blocks before rekeying again. If L is at least 128, then SSH\n implementations should also attempt to force a rekey before receiving\n more than 2**(L/4) blocks. If L is less than 128 (which is the case\n for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then,\n although it may be too expensive to rekey every 2**(L/4) blocks, it\n is still advisable for SSH implementations to follow the original\n recommendation in [RFC4253]: rekey at least once for every gigabyte\n of transmitted data.\n\n Note that if L is less than or equal to 128, then the recommendation\n in this subsection supersedes the recommendation in Section 3.1. If\n an SSH implementation uses a block cipher with a larger block size\n (e.g., Rijndael with 256-bit blocks), then the recommendations in\n Section 3.1 may supersede the recommendations in this subsection\n (depending on the lengths of the packets).\n*/\n\n'use strict';\n\nconst { inspect } = require('util');\n\nconst { bindingAvailable, NullCipher, NullDecipher } = require('./crypto.js');\nconst {\n COMPAT_CHECKS,\n DISCONNECT_REASON,\n eddsaSupported,\n MESSAGE,\n SIGNALS,\n TERMINAL_MODE,\n} = require('./constants.js');\nconst {\n DEFAULT_KEXINIT_CLIENT,\n DEFAULT_KEXINIT_SERVER,\n KexInit,\n kexinit,\n onKEXPayload,\n} = require('./kex.js');\nconst {\n parseKey,\n} = require('./keyParser.js');\nconst MESSAGE_HANDLERS = require('./handlers.js');\nconst {\n bufferCopy,\n bufferFill,\n bufferSlice,\n convertSignature,\n sendPacket,\n writeUInt32BE,\n} = require('./utils.js');\nconst {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n} = require('./zlib.js');\n\nconst MODULE_VER = require('../../package.json').version;\n\nconst VALID_DISCONNECT_REASONS = new Map(\n Object.values(DISCONNECT_REASON).map((n) => [n, 1])\n);\nconst IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`);\nconst IDENT = Buffer.from(`${IDENT_RAW}\\r\\n`);\nconst MAX_LINE_LEN = 8192;\nconst MAX_LINES = 1024;\nconst PING_PAYLOAD = Buffer.from([\n MESSAGE.GLOBAL_REQUEST,\n // \"keepalive@openssh.com\"\n 0, 0, 0, 21,\n 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115,\n 115, 104, 46, 99, 111, 109,\n // Request a reply\n 1,\n]);\nconst NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]);\n\nfunction noop() {}\n\n/*\n Inbound:\n * kexinit payload (needed only until exchange hash is generated)\n * raw ident\n * rekey packet queue\n * expected packet (implemented as separate _parse() function?)\n Outbound:\n * kexinit payload (needed only until exchange hash is generated)\n * rekey packet queue\n * kex secret (needed only until NEWKEYS)\n * exchange hash (needed only until NEWKEYS)\n * session ID (set to exchange hash from initial handshake)\n*/\nclass Protocol {\n constructor(config) {\n const onWrite = config.onWrite;\n if (typeof onWrite !== 'function')\n throw new Error('Missing onWrite function');\n this._onWrite = (data) => { onWrite(data); };\n\n const onError = config.onError;\n if (typeof onError !== 'function')\n throw new Error('Missing onError function');\n this._onError = (err) => { onError(err); };\n\n const debug = config.debug;\n this._debug = (typeof debug === 'function'\n ? (msg) => { debug(msg); }\n : undefined);\n\n const onHeader = config.onHeader;\n this._onHeader = (typeof onHeader === 'function'\n ? (...args) => { onHeader(...args); }\n : noop);\n\n const onPacket = config.onPacket;\n this._onPacket = (typeof onPacket === 'function'\n ? () => { onPacket(); }\n : noop);\n\n let onHandshakeComplete = config.onHandshakeComplete;\n if (typeof onHandshakeComplete !== 'function')\n onHandshakeComplete = noop;\n let firstHandshake;\n this._onHandshakeComplete = (...args) => {\n this._debug && this._debug('Handshake completed');\n if (firstHandshake === undefined)\n firstHandshake = true;\n else\n firstHandshake = false;\n\n // Process packets queued during a rekey where necessary\n const oldQueue = this._queue;\n if (oldQueue) {\n this._queue = undefined;\n this._debug && this._debug(\n `Draining outbound queue (${oldQueue.length}) ...`\n );\n for (let i = 0; i < oldQueue.length; ++i) {\n const data = oldQueue[i];\n // data === payload only\n\n // XXX: hacky\n let finalized = this._packetRW.write.finalize(data);\n if (finalized === data) {\n const packet = this._cipher.allocPacket(data.length);\n packet.set(data, 5);\n finalized = packet;\n }\n\n sendPacket(this, finalized);\n }\n this._debug && this._debug('... finished draining outbound queue');\n }\n\n if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled)\n sendExtInfo(this);\n\n onHandshakeComplete(...args);\n };\n this._queue = undefined;\n\n const messageHandlers = config.messageHandlers;\n if (typeof messageHandlers === 'object' && messageHandlers !== null)\n this._handlers = messageHandlers;\n else\n this._handlers = {};\n\n this._onPayload = onPayload.bind(this);\n\n this._server = !!config.server;\n this._banner = undefined;\n let greeting;\n if (this._server) {\n if (typeof config.hostKeys !== 'object' || config.hostKeys === null)\n throw new Error('Missing server host key(s)');\n this._hostKeys = config.hostKeys;\n\n // Greeting displayed before the ssh identification string is sent, this\n // is usually ignored by most clients\n if (typeof config.greeting === 'string' && config.greeting.length) {\n greeting = (config.greeting.slice(-2) === '\\r\\n'\n ? config.greeting\n : `${config.greeting}\\r\\n`);\n }\n\n // Banner shown after the handshake completes, but before user\n // authentication begins\n if (typeof config.banner === 'string' && config.banner.length) {\n this._banner = (config.banner.slice(-2) === '\\r\\n'\n ? config.banner\n : `${config.banner}\\r\\n`);\n }\n } else {\n this._hostKeys = undefined;\n }\n\n let offer = config.offer;\n if (typeof offer !== 'object' || offer === null) {\n offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT);\n } else if (offer.constructor !== KexInit) {\n if (this._server) {\n offer.kex = offer.kex.concat(['kex-strict-s-v00@openssh.com']);\n } else {\n offer.kex = offer.kex.concat([\n 'ext-info-c',\n 'kex-strict-c-v00@openssh.com',\n ]);\n }\n offer = new KexInit(offer);\n }\n this._kex = undefined;\n this._strictMode = undefined;\n this._kexinit = undefined;\n this._offer = offer;\n this._cipher = new NullCipher(0, this._onWrite);\n this._decipher = undefined;\n this._skipNextInboundPacket = false;\n this._packetRW = {\n read: new PacketReader(),\n write: new PacketWriter(this),\n };\n this._hostVerifier = (!this._server\n && typeof config.hostVerifier === 'function'\n ? config.hostVerifier\n : undefined);\n\n this._parse = parseHeader;\n this._buffer = undefined;\n this._authsQueue = [];\n this._authenticated = false;\n this._remoteIdentRaw = undefined;\n let sentIdent;\n if (typeof config.ident === 'string') {\n this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`);\n\n sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2);\n sentIdent.set(this._identRaw, 0);\n sentIdent[sentIdent.length - 2] = 13; // '\\r'\n sentIdent[sentIdent.length - 1] = 10; // '\\n'\n } else if (Buffer.isBuffer(config.ident)) {\n const fullIdent = Buffer.allocUnsafe(8 + config.ident.length);\n fullIdent.latin1Write('SSH-2.0-', 0, 8);\n fullIdent.set(config.ident, 8);\n this._identRaw = fullIdent;\n\n sentIdent = Buffer.allocUnsafe(fullIdent.length + 2);\n sentIdent.set(fullIdent, 0);\n sentIdent[sentIdent.length - 2] = 13; // '\\r'\n sentIdent[sentIdent.length - 1] = 10; // '\\n'\n } else {\n this._identRaw = IDENT_RAW;\n sentIdent = IDENT;\n }\n this._compatFlags = 0;\n\n if (this._debug) {\n if (bindingAvailable)\n this._debug('Custom crypto binding available');\n else\n this._debug('Custom crypto binding not available');\n }\n\n this._debug && this._debug(\n `Local ident: ${inspect(this._identRaw.toString())}`\n );\n this.start = () => {\n this.start = undefined;\n if (greeting)\n this._onWrite(greeting);\n this._onWrite(sentIdent);\n };\n }\n _destruct(reason) {\n this._packetRW.read.cleanup();\n this._packetRW.write.cleanup();\n this._cipher && this._cipher.free();\n this._decipher && this._decipher.free();\n if (typeof reason !== 'string' || reason.length === 0)\n reason = 'fatal error';\n this.parse = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };\n this._onWrite = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };\n this._destruct = undefined;\n }\n cleanup() {\n this._destruct && this._destruct();\n }\n parse(chunk, i, len) {\n while (i < len)\n i = this._parse(chunk, i, len);\n }\n\n // Protocol message API\n\n // ===========================================================================\n // Common/Shared =============================================================\n // ===========================================================================\n\n // Global\n // ------\n disconnect(reason) {\n const pktLen = 1 + 4 + 4 + 4;\n // We don't use _packetRW.write.* here because we need to make sure that\n // we always get a full packet allocated because this message can be sent\n // at any time -- even during a key exchange\n let p = this._packetRW.write.allocStartKEX;\n const packet = this._packetRW.write.alloc(pktLen, true);\n const end = p + pktLen;\n\n if (!VALID_DISCONNECT_REASONS.has(reason))\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n\n packet[p] = MESSAGE.DISCONNECT;\n writeUInt32BE(packet, reason, ++p);\n packet.fill(0, p += 4, end);\n\n this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`);\n sendPacket(this, this._packetRW.write.finalize(packet, true), true);\n }\n ping() {\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(PING_PAYLOAD.length);\n\n packet.set(PING_PAYLOAD, p);\n\n this._debug && this._debug(\n 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n rekey() {\n if (this._kexinit === undefined) {\n this._debug && this._debug('Outbound: Initiated explicit rekey');\n this._queue = [];\n kexinit(this);\n } else {\n this._debug && this._debug('Outbound: Ignoring rekey during handshake');\n }\n }\n\n // 'ssh-connection' service-specific\n // ---------------------------------\n requestSuccess(data) {\n let p = this._packetRW.write.allocStart;\n let packet;\n if (Buffer.isBuffer(data)) {\n packet = this._packetRW.write.alloc(1 + data.length);\n\n packet[p] = MESSAGE.REQUEST_SUCCESS;\n\n packet.set(data, ++p);\n } else {\n packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.REQUEST_SUCCESS;\n }\n\n this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n requestFailure() {\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.REQUEST_FAILURE;\n\n this._debug && this._debug('Outbound: Sending REQUEST_FAILURE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelSuccess(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_SUCCESS;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelFailure(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_FAILURE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelEOF(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_EOF;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelClose(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_CLOSE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelWindowAdjust(chan, amount) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, amount, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelData(chan, data) {\n const isBuffer = Buffer.isBuffer(data);\n const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen);\n\n packet[p] = MESSAGE.CHANNEL_DATA;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, dataLen, p += 4);\n\n if (isBuffer)\n packet.set(data, p += 4);\n else\n packet.utf8Write(data, p += 4, dataLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelExtData(chan, data, type) {\n const isBuffer = Buffer.isBuffer(data);\n const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen);\n\n packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, type, p += 4);\n\n writeUInt32BE(packet, dataLen, p += 4);\n\n if (isBuffer)\n packet.set(data, p += 4);\n else\n packet.utf8Write(data, p += 4, dataLen);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelOpenConfirm(remote, local, initWindow, maxPacket) {\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION;\n\n writeUInt32BE(packet, remote, ++p);\n\n writeUInt32BE(packet, local, p += 4);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n channelOpenFail(remote, reason, desc) {\n if (typeof desc !== 'string')\n desc = '';\n\n const descLen = Buffer.byteLength(desc);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE;\n\n writeUInt32BE(packet, remote, ++p);\n\n writeUInt32BE(packet, reason, p += 4);\n\n writeUInt32BE(packet, descLen, p += 4);\n\n p += 4;\n if (descLen) {\n packet.utf8Write(desc, p, descLen);\n p += descLen;\n }\n\n writeUInt32BE(packet, 0, p); // Empty language tag\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // ===========================================================================\n // Client-specific ===========================================================\n // ===========================================================================\n\n // Global\n // ------\n service(name) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + nameLen);\n\n packet[p] = MESSAGE.SERVICE_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // 'ssh-userauth' service-specific\n // -------------------------------\n authPassword(username, password, newPassword) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n const passLen = Buffer.byteLength(password);\n const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen\n + (newPassword ? 4 + newPassLen : 0)\n );\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 8, p += 14);\n packet.utf8Write('password', p += 4, 8);\n\n packet[p += 8] = (newPassword ? 1 : 0);\n\n writeUInt32BE(packet, passLen, ++p);\n if (Buffer.isBuffer(password))\n bufferCopy(password, packet, 0, passLen, p += 4);\n else\n packet.utf8Write(password, p += 4, passLen);\n\n if (newPassword) {\n writeUInt32BE(packet, newPassLen, p += passLen);\n if (Buffer.isBuffer(newPassword))\n bufferCopy(newPassword, packet, 0, newPassLen, p += 4);\n else\n packet.utf8Write(newPassword, p += 4, newPassLen);\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (changed password)'\n );\n } else {\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (password)'\n );\n }\n\n this._authsQueue.push('password');\n\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authPK(username, pubKey, keyAlgo, cbSign) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n pubKey = parseKey(pubKey);\n if (pubKey instanceof Error)\n throw new Error('Invalid key');\n\n const keyType = pubKey.type;\n pubKey = pubKey.getPublicSSH();\n\n if (typeof keyAlgo === 'function') {\n cbSign = keyAlgo;\n keyAlgo = undefined;\n }\n if (!keyAlgo)\n keyAlgo = keyType;\n\n const userLen = Buffer.byteLength(username);\n const algoLen = Buffer.byteLength(keyAlgo);\n const pubKeyLen = pubKey.length;\n const sessionID = this._kex.sessionID;\n const sesLen = sessionID.length;\n const payloadLen =\n (cbSign ? 4 + sesLen : 0)\n + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen;\n let packet;\n let p;\n if (cbSign) {\n packet = Buffer.allocUnsafe(payloadLen);\n p = 0;\n writeUInt32BE(packet, sesLen, p);\n packet.set(sessionID, p += 4);\n p += sesLen;\n } else {\n packet = this._packetRW.write.alloc(payloadLen);\n p = this._packetRW.write.allocStart;\n }\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 9, p += 14);\n packet.utf8Write('publickey', p += 4, 9);\n\n packet[p += 9] = (cbSign ? 1 : 0);\n\n writeUInt32BE(packet, algoLen, ++p);\n packet.utf8Write(keyAlgo, p += 4, algoLen);\n\n writeUInt32BE(packet, pubKeyLen, p += algoLen);\n packet.set(pubKey, p += 4);\n\n if (!cbSign) {\n this._authsQueue.push('publickey');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n return;\n }\n\n cbSign(packet, (signature) => {\n signature = convertSignature(signature, keyType);\n if (signature === false)\n throw new Error('Error while converting handshake signature');\n\n const sigLen = signature.length;\n p = this._packetRW.write.allocStart;\n packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4\n + 4 + algoLen + 4 + sigLen\n );\n\n // TODO: simply copy from original \"packet\" to new `packet` to avoid\n // having to write each individual field a second time?\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 9, p += 14);\n packet.utf8Write('publickey', p += 4, 9);\n\n packet[p += 9] = 1;\n\n writeUInt32BE(packet, algoLen, ++p);\n packet.utf8Write(keyAlgo, p += 4, algoLen);\n\n writeUInt32BE(packet, pubKeyLen, p += algoLen);\n packet.set(pubKey, p += 4);\n\n writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen);\n\n writeUInt32BE(packet, algoLen, p += 4);\n packet.utf8Write(keyAlgo, p += 4, algoLen);\n\n writeUInt32BE(packet, sigLen, p += algoLen);\n packet.set(signature, p += 4);\n\n // Servers shouldn't send packet type 60 in response to signed publickey\n // attempts, but if they do, interpret as type 60.\n this._authsQueue.push('publickey');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (publickey)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n });\n }\n authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) {\n // TODO: Make DRY by sharing similar code with authPK()\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n pubKey = parseKey(pubKey);\n if (pubKey instanceof Error)\n throw new Error('Invalid key');\n\n const keyType = pubKey.type;\n pubKey = pubKey.getPublicSSH();\n\n if (typeof keyAlgo === 'function') {\n cbSign = keyAlgo;\n keyAlgo = undefined;\n }\n if (!keyAlgo)\n keyAlgo = keyType;\n\n const userLen = Buffer.byteLength(username);\n const algoLen = Buffer.byteLength(keyAlgo);\n const pubKeyLen = pubKey.length;\n const sessionID = this._kex.sessionID;\n const sesLen = sessionID.length;\n const hostnameLen = Buffer.byteLength(hostname);\n const userlocalLen = Buffer.byteLength(userlocal);\n const data = Buffer.allocUnsafe(\n 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen\n + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen\n );\n let p = 0;\n\n writeUInt32BE(data, sesLen, p);\n data.set(sessionID, p += 4);\n\n data[p += sesLen] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(data, userLen, ++p);\n data.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(data, 14, p += userLen);\n data.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(data, 9, p += 14);\n data.utf8Write('hostbased', p += 4, 9);\n\n writeUInt32BE(data, algoLen, p += 9);\n data.utf8Write(keyAlgo, p += 4, algoLen);\n\n writeUInt32BE(data, pubKeyLen, p += algoLen);\n data.set(pubKey, p += 4);\n\n writeUInt32BE(data, hostnameLen, p += pubKeyLen);\n data.utf8Write(hostname, p += 4, hostnameLen);\n\n writeUInt32BE(data, userlocalLen, p += hostnameLen);\n data.utf8Write(userlocal, p += 4, userlocalLen);\n\n cbSign(data, (signature) => {\n signature = convertSignature(signature, keyType);\n if (!signature)\n throw new Error('Error while converting handshake signature');\n\n const sigLen = signature.length;\n const reqDataLen = (data.length - sesLen - 4);\n p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n reqDataLen + 4 + 4 + algoLen + 4 + sigLen\n );\n\n bufferCopy(data, packet, 4 + sesLen, data.length, p);\n\n writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen);\n writeUInt32BE(packet, algoLen, p += 4);\n packet.utf8Write(keyAlgo, p += 4, algoLen);\n writeUInt32BE(packet, sigLen, p += algoLen);\n packet.set(signature, p += 4);\n\n this._authsQueue.push('hostbased');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (hostbased)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n });\n }\n authKeyboard(username) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4\n );\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 20, p += 14);\n packet.utf8Write('keyboard-interactive', p += 4, 20);\n\n writeUInt32BE(packet, 0, p += 20);\n\n writeUInt32BE(packet, 0, p += 4);\n\n this._authsQueue.push('keyboard-interactive');\n\n this._debug && this._debug(\n 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authNone(username) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const userLen = Buffer.byteLength(username);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4);\n\n packet[p] = MESSAGE.USERAUTH_REQUEST;\n\n writeUInt32BE(packet, userLen, ++p);\n packet.utf8Write(username, p += 4, userLen);\n\n writeUInt32BE(packet, 14, p += userLen);\n packet.utf8Write('ssh-connection', p += 4, 14);\n\n writeUInt32BE(packet, 4, p += 14);\n packet.utf8Write('none', p += 4, 4);\n\n this._authsQueue.push('none');\n\n this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authInfoRes(responses) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let responsesTotalLen = 0;\n let responseLens;\n\n if (responses) {\n responseLens = new Array(responses.length);\n for (let i = 0; i < responses.length; ++i) {\n const len = Buffer.byteLength(responses[i]);\n responseLens[i] = len;\n responsesTotalLen += 4 + len;\n }\n }\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen);\n\n packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE;\n\n if (responses) {\n writeUInt32BE(packet, responses.length, ++p);\n p += 4;\n for (let i = 0; i < responses.length; ++i) {\n const len = responseLens[i];\n writeUInt32BE(packet, len, p);\n p += 4;\n if (len) {\n packet.utf8Write(responses[i], p, len);\n p += len;\n }\n }\n } else {\n writeUInt32BE(packet, 0, ++p);\n }\n\n this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // 'ssh-connection' service-specific\n // ---------------------------------\n tcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 13, ++p);\n packet.utf8Write('tcpip-forward', p += 4, 13);\n\n packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n cancelTcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 20, ++p);\n packet.utf8Write('cancel-tcpip-forward', p += 4, 20);\n\n packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_streamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 31 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 31, ++p);\n packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31);\n\n packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_cancelStreamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 38 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 38, ++p);\n packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38);\n\n packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending GLOBAL_REQUEST '\n + '(cancel-streamlocal-forward@openssh.com)'\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n directTcpip(chan, initWindow, maxPacket, cfg) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const srcLen = Buffer.byteLength(cfg.srcIP);\n const dstLen = Buffer.byteLength(cfg.dstIP);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 12, ++p);\n packet.utf8Write('direct-tcpip', p += 4, 12);\n\n writeUInt32BE(packet, chan, p += 12);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, dstLen, p += 4);\n packet.utf8Write(cfg.dstIP, p += 4, dstLen);\n\n writeUInt32BE(packet, cfg.dstPort, p += dstLen);\n\n writeUInt32BE(packet, srcLen, p += 4);\n packet.utf8Write(cfg.srcIP, p += 4, srcLen);\n\n writeUInt32BE(packet, cfg.srcPort, p += srcLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const pathLen = Buffer.byteLength(cfg.socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 30, ++p);\n packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30);\n\n writeUInt32BE(packet, chan, p += 30);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, pathLen, p += 4);\n packet.utf8Write(cfg.socketPath, p += 4, pathLen);\n\n // zero-fill reserved fields (string and uint32)\n bufferFill(packet, 0, p += pathLen, p + 8);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_OPEN '\n + `(r:${chan}, direct-streamlocal@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_noMoreSessions(wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 28, ++p);\n packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28);\n\n packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n session(chan, initWindow, maxPacket) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 7, ++p);\n packet.utf8Write('session', p += 4, 7);\n\n writeUInt32BE(packet, chan, p += 7);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n windowChange(chan, rows, cols, height, width) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 13, p += 4);\n packet.utf8Write('window-change', p += 4, 13);\n\n packet[p += 13] = 0;\n\n writeUInt32BE(packet, cols, ++p);\n\n writeUInt32BE(packet, rows, p += 4);\n\n writeUInt32BE(packet, width, p += 4);\n\n writeUInt32BE(packet, height, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n pty(chan, rows, cols, height, width, term, modes, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n if (!term || !term.length)\n term = 'vt100';\n if (modes\n && !Buffer.isBuffer(modes)\n && !Array.isArray(modes)\n && typeof modes === 'object'\n && modes !== null) {\n modes = modesToBytes(modes);\n }\n if (!modes || !modes.length)\n modes = NO_TERMINAL_MODES_BUFFER;\n\n const termLen = term.length;\n const modesLen = modes.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 7, p += 4);\n packet.utf8Write('pty-req', p += 4, 7);\n\n packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, termLen, ++p);\n packet.utf8Write(term, p += 4, termLen);\n\n writeUInt32BE(packet, cols, p += termLen);\n\n writeUInt32BE(packet, rows, p += 4);\n\n writeUInt32BE(packet, width, p += 4);\n\n writeUInt32BE(packet, height, p += 4);\n\n writeUInt32BE(packet, modesLen, p += 4);\n p += 4;\n if (Array.isArray(modes)) {\n for (let i = 0; i < modesLen; ++i)\n packet[p++] = modes[i];\n } else if (Buffer.isBuffer(modes)) {\n packet.set(modes, p);\n }\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n shell(chan, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 5, p += 4);\n packet.utf8Write('shell', p += 4, 5);\n\n packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exec(chan, cmd, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const isBuf = Buffer.isBuffer(cmd);\n const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 4, p += 4);\n packet.utf8Write('exec', p += 4, 4);\n\n packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, cmdLen, ++p);\n if (isBuf)\n packet.set(cmd, p += 4);\n else\n packet.utf8Write(cmd, p += 4, cmdLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n signal(chan, signal) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const origSignal = signal;\n\n signal = signal.toUpperCase();\n if (signal.slice(0, 3) === 'SIG')\n signal = signal.slice(3);\n\n if (SIGNALS[signal] !== 1)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n const signalLen = signal.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 6 + 1 + 4 + signalLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 6, p += 4);\n packet.utf8Write('signal', p += 4, 6);\n\n packet[p += 6] = 0;\n\n writeUInt32BE(packet, signalLen, ++p);\n packet.utf8Write(signal, p += 4, signalLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n env(chan, key, val, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const keyLen = Buffer.byteLength(key);\n const isBuf = Buffer.isBuffer(val);\n const valLen = (isBuf ? val.length : Buffer.byteLength(val));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 3, p += 4);\n packet.utf8Write('env', p += 4, 3);\n\n packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, keyLen, ++p);\n packet.utf8Write(key, p += 4, keyLen);\n\n writeUInt32BE(packet, valLen, p += keyLen);\n if (isBuf)\n packet.set(val, p += 4);\n else\n packet.utf8Write(val, p += 4, valLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n x11Forward(chan, cfg, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n const protocol = cfg.protocol;\n const cookie = cfg.cookie;\n const isBufProto = Buffer.isBuffer(protocol);\n const protoLen = (isBufProto\n ? protocol.length\n : Buffer.byteLength(protocol));\n const isBufCookie = Buffer.isBuffer(cookie);\n const cookieLen = (isBufCookie\n ? cookie.length\n : Buffer.byteLength(cookie));\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 7, p += 4);\n packet.utf8Write('x11-req', p += 4, 7);\n\n packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n packet[++p] = (cfg.single ? 1 : 0);\n\n writeUInt32BE(packet, protoLen, ++p);\n if (isBufProto)\n packet.set(protocol, p += 4);\n else\n packet.utf8Write(protocol, p += 4, protoLen);\n\n writeUInt32BE(packet, cookieLen, p += protoLen);\n if (isBufCookie)\n packet.set(cookie, p += 4);\n else\n packet.latin1Write(cookie, p += 4, cookieLen);\n\n writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen);\n\n this._debug\n && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n subsystem(chan, name, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 9, p += 4);\n packet.utf8Write('subsystem', p += 4, 9);\n\n packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_agentForward(chan, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 26, p += 4);\n packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26);\n\n packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_REQUEST '\n + `(r:${chan}, auth-agent-req@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_hostKeysProve(keys) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n let keysTotal = 0;\n const publicKeys = [];\n for (const key of keys) {\n const publicKey = key.getPublicSSH();\n keysTotal += 4 + publicKey.length;\n publicKeys.push(publicKey);\n }\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 29, ++p);\n packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);\n\n packet[p += 29] = 1; // want reply\n\n ++p;\n for (const buf of publicKeys) {\n writeUInt32BE(packet, buf.length, p);\n bufferCopy(buf, packet, 0, buf.length, p += 4);\n p += buf.length;\n }\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)'\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n\n // ===========================================================================\n // Server-specific ===========================================================\n // ===========================================================================\n\n // Global\n // ------\n serviceAccept(svcName) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const svcNameLen = Buffer.byteLength(svcName);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen);\n\n packet[p] = MESSAGE.SERVICE_ACCEPT;\n\n writeUInt32BE(packet, svcNameLen, ++p);\n packet.utf8Write(svcName, p += 4, svcNameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n\n if (this._server && this._banner && svcName === 'ssh-userauth') {\n const banner = this._banner;\n this._banner = undefined; // Prevent banner from being displayed again\n const bannerLen = Buffer.byteLength(banner);\n p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4);\n\n packet[p] = MESSAGE.USERAUTH_BANNER;\n\n writeUInt32BE(packet, bannerLen, ++p);\n packet.utf8Write(banner, p += 4, bannerLen);\n\n writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag\n\n this._debug && this._debug('Outbound: Sending USERAUTH_BANNER');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n }\n // 'ssh-connection' service-specific\n forwardedTcpip(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const boundAddrLen = Buffer.byteLength(cfg.boundAddr);\n const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 15, ++p);\n packet.utf8Write('forwarded-tcpip', p += 4, 15);\n\n writeUInt32BE(packet, chan, p += 15);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, boundAddrLen, p += 4);\n packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen);\n\n writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen);\n\n writeUInt32BE(packet, remoteAddrLen, p += 4);\n packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen);\n\n writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n x11(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const addrLen = Buffer.byteLength(cfg.originAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 3, ++p);\n packet.utf8Write('x11', p += 4, 3);\n\n writeUInt32BE(packet, chan, p += 3);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, addrLen, p += 4);\n packet.utf8Write(cfg.originAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, cfg.originPort, p += addrLen);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_authAgent(chan, initWindow, maxPacket) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4);\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 22, ++p);\n packet.utf8Write('auth-agent@openssh.com', p += 4, 22);\n\n writeUInt32BE(packet, chan, p += 22);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const pathLen = Buffer.byteLength(cfg.socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_OPEN;\n\n writeUInt32BE(packet, 33, ++p);\n packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33);\n\n writeUInt32BE(packet, chan, p += 33);\n\n writeUInt32BE(packet, initWindow, p += 4);\n\n writeUInt32BE(packet, maxPacket, p += 4);\n\n writeUInt32BE(packet, pathLen, p += 4);\n packet.utf8Write(cfg.socketPath, p += 4, pathLen);\n\n writeUInt32BE(packet, 0, p += pathLen);\n\n if (this._debug) {\n this._debug(\n 'Outbound: Sending CHANNEL_OPEN '\n + `(r:${chan}, forwarded-streamlocal@openssh.com)`\n );\n }\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exitStatus(chan, status) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n // Does not consume window space\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 11, p += 4);\n packet.utf8Write('exit-status', p += 4, 11);\n\n packet[p += 11] = 0;\n\n writeUInt32BE(packet, status, ++p);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n exitSignal(chan, name, coreDumped, msg) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n // Does not consume window space\n\n const origSignal = name;\n\n if (typeof origSignal !== 'string' || !origSignal)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n let signal = name.toUpperCase();\n if (signal.slice(0, 3) === 'SIG')\n signal = signal.slice(3);\n\n if (SIGNALS[signal] !== 1)\n throw new Error(`Invalid signal: ${origSignal}`);\n\n const nameLen = Buffer.byteLength(signal);\n const msgLen = (msg ? Buffer.byteLength(msg) : 0);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4\n );\n\n packet[p] = MESSAGE.CHANNEL_REQUEST;\n\n writeUInt32BE(packet, chan, ++p);\n\n writeUInt32BE(packet, 11, p += 4);\n packet.utf8Write('exit-signal', p += 4, 11);\n\n packet[p += 11] = 0;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(signal, p += 4, nameLen);\n\n packet[p += nameLen] = (coreDumped ? 1 : 0);\n\n writeUInt32BE(packet, msgLen, ++p);\n\n p += 4;\n if (msgLen) {\n packet.utf8Write(msg, p, msgLen);\n p += msgLen;\n }\n\n writeUInt32BE(packet, 0, p);\n\n this._debug && this._debug(\n `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})`\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n // 'ssh-userauth' service-specific\n authFailure(authMethods, isPartial) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0)\n throw new Error('No auth in progress');\n\n let methods;\n\n if (typeof authMethods === 'boolean') {\n isPartial = authMethods;\n authMethods = undefined;\n }\n\n if (authMethods) {\n methods = [];\n for (let i = 0; i < authMethods.length; ++i) {\n if (authMethods[i].toLowerCase() === 'none')\n continue;\n methods.push(authMethods[i]);\n }\n methods = methods.join(',');\n } else {\n methods = '';\n }\n\n const methodsLen = methods.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1);\n\n packet[p] = MESSAGE.USERAUTH_FAILURE;\n\n writeUInt32BE(packet, methodsLen, ++p);\n packet.utf8Write(methods, p += 4, methodsLen);\n\n packet[p += methodsLen] = (isPartial === true ? 1 : 0);\n\n this._authsQueue.shift();\n\n this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authSuccess() {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0)\n throw new Error('No auth in progress');\n\n const p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1);\n\n packet[p] = MESSAGE.USERAUTH_SUCCESS;\n\n this._authsQueue.shift();\n this._authenticated = true;\n\n this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS');\n sendPacket(this, this._packetRW.write.finalize(packet));\n\n if (this._kex.negotiated.cs.compress === 'zlib@openssh.com')\n this._packetRW.read = new ZlibPacketReader();\n if (this._kex.negotiated.sc.compress === 'zlib@openssh.com')\n this._packetRW.write = new ZlibPacketWriter(this);\n }\n authPKOK(keyAlgo, key) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey')\n throw new Error('\"publickey\" auth not in progress');\n\n // TODO: support parsed key for `key`\n\n const keyAlgoLen = Buffer.byteLength(keyAlgo);\n const keyLen = key.length;\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen);\n\n packet[p] = MESSAGE.USERAUTH_PK_OK;\n\n writeUInt32BE(packet, keyAlgoLen, ++p);\n packet.utf8Write(keyAlgo, p += 4, keyAlgoLen);\n\n writeUInt32BE(packet, keyLen, p += keyAlgoLen);\n packet.set(key, p += 4);\n\n this._authsQueue.shift();\n\n this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authPasswdChg(prompt) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n const promptLen = Buffer.byteLength(prompt);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4);\n\n packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ;\n\n writeUInt32BE(packet, promptLen, ++p);\n packet.utf8Write(prompt, p += 4, promptLen);\n\n writeUInt32BE(packet, 0, p += promptLen); // Empty language tag\n\n this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n authInfoReq(name, instructions, prompts) {\n if (!this._server)\n throw new Error('Server-only method called in client mode');\n\n let promptsLen = 0;\n const nameLen = name ? Buffer.byteLength(name) : 0;\n const instrLen = instructions ? Buffer.byteLength(instructions) : 0;\n\n for (let i = 0; i < prompts.length; ++i)\n promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1;\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen\n );\n\n packet[p] = MESSAGE.USERAUTH_INFO_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n p += 4;\n if (name) {\n packet.utf8Write(name, p, nameLen);\n p += nameLen;\n }\n\n writeUInt32BE(packet, instrLen, p);\n p += 4;\n if (instructions) {\n packet.utf8Write(instructions, p, instrLen);\n p += instrLen;\n }\n\n writeUInt32BE(packet, 0, p);\n\n writeUInt32BE(packet, prompts.length, p += 4);\n p += 4;\n for (let i = 0; i < prompts.length; ++i) {\n const prompt = prompts[i];\n const promptLen = Buffer.byteLength(prompt.prompt);\n\n writeUInt32BE(packet, promptLen, p);\n p += 4;\n if (promptLen) {\n packet.utf8Write(prompt.prompt, p, promptLen);\n p += promptLen;\n }\n packet[p++] = (prompt.echo ? 1 : 0);\n }\n\n this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }\n}\n\n// SSH-protoversion-softwareversion (SP comments) CR LF\nconst RE_IDENT = /^SSH-(2\\.0|1\\.99)-([^ ]+)(?: (.*))?$/;\n\n// TODO: optimize this by starting n bytes from the end of this._buffer instead\n// of the beginning\nfunction parseHeader(chunk, p, len) {\n let data;\n let chunkOffset;\n if (this._buffer) {\n data = Buffer.allocUnsafe(this._buffer.length + (len - p));\n data.set(this._buffer, 0);\n if (p === 0) {\n data.set(chunk, this._buffer.length);\n } else {\n data.set(new Uint8Array(chunk.buffer,\n chunk.byteOffset + p,\n (len - p)),\n this._buffer.length);\n }\n chunkOffset = this._buffer.length;\n p = 0;\n } else {\n data = chunk;\n chunkOffset = 0;\n }\n const op = p;\n let start = p;\n let end = p;\n let needNL = false;\n let lineLen = 0;\n let lines = 0;\n for (; p < data.length; ++p) {\n const ch = data[p];\n\n if (ch === 13 /* '\\r' */) {\n needNL = true;\n continue;\n }\n\n if (ch === 10 /* '\\n' */) {\n if (end > start\n && end - start > 4\n && data[start] === 83 /* 'S' */\n && data[start + 1] === 83 /* 'S' */\n && data[start + 2] === 72 /* 'H' */\n && data[start + 3] === 45 /* '-' */) {\n\n const full = data.latin1Slice(op, end + 1);\n const identRaw = (start === op ? full : full.slice(start - op));\n const m = RE_IDENT.exec(identRaw);\n if (!m)\n throw new Error('Invalid identification string');\n\n const header = {\n greeting: (start === op ? '' : full.slice(0, start - op)),\n identRaw,\n versions: {\n protocol: m[1],\n software: m[2],\n },\n comments: m[3]\n };\n\n // Needed during handshake\n this._remoteIdentRaw = Buffer.from(identRaw);\n\n this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`);\n this._compatFlags = getCompatFlags(header);\n\n this._buffer = undefined;\n this._decipher =\n new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true }));\n this._parse = parsePacket;\n\n this._onHeader(header);\n if (!this._destruct) {\n // We disconnected inside _onHeader\n return len;\n }\n\n kexinit(this);\n\n return p + 1 - chunkOffset;\n }\n\n // Only allow pre-ident greetings when we're a client\n if (this._server)\n throw new Error('Greetings from clients not permitted');\n\n if (++lines > MAX_LINES)\n throw new Error('Max greeting lines exceeded');\n\n needNL = false;\n start = p + 1;\n lineLen = 0;\n } else if (needNL) {\n throw new Error('Invalid header: expected newline');\n } else if (++lineLen >= MAX_LINE_LEN) {\n throw new Error('Header line too long');\n }\n\n end = p;\n }\n if (!this._buffer)\n this._buffer = bufferSlice(data, op);\n\n return p - chunkOffset;\n}\n\nfunction parsePacket(chunk, p, len) {\n return this._decipher.decrypt(chunk, p, len);\n}\n\nfunction onPayload(payload) {\n // XXX: move this to the Decipher implementations?\n\n this._onPacket();\n\n if (payload.length === 0) {\n this._debug && this._debug('Inbound: Skipping empty packet payload');\n return;\n }\n\n payload = this._packetRW.read.read(payload);\n\n const type = payload[0];\n if (type === MESSAGE.USERAUTH_SUCCESS\n && !this._server\n && !this._authenticated) {\n this._authenticated = true;\n if (this._kex.negotiated.cs.compress === 'zlib@openssh.com')\n this._packetRW.write = new ZlibPacketWriter(this);\n if (this._kex.negotiated.sc.compress === 'zlib@openssh.com')\n this._packetRW.read = new ZlibPacketReader();\n }\n const handler = MESSAGE_HANDLERS[type];\n if (handler === undefined) {\n this._debug && this._debug(`Inbound: Unsupported message type: ${type}`);\n return;\n }\n\n return handler(this, payload);\n}\n\nfunction getCompatFlags(header) {\n const software = header.versions.software;\n\n let flags = 0;\n\n for (const rule of COMPAT_CHECKS) {\n if (typeof rule[0] === 'string') {\n if (software === rule[0])\n flags |= rule[1];\n } else if (rule[0].test(software)) {\n flags |= rule[1];\n }\n }\n\n return flags;\n}\n\nfunction modesToBytes(modes) {\n const keys = Object.keys(modes);\n const bytes = Buffer.allocUnsafe((5 * keys.length) + 1);\n let b = 0;\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (key === 'TTY_OP_END')\n continue;\n\n const opcode = TERMINAL_MODE[key];\n if (opcode === undefined)\n continue;\n\n const val = modes[key];\n if (typeof val === 'number' && isFinite(val)) {\n bytes[b++] = opcode;\n bytes[b++] = val >>> 24;\n bytes[b++] = val >>> 16;\n bytes[b++] = val >>> 8;\n bytes[b++] = val;\n }\n }\n\n bytes[b++] = TERMINAL_MODE.TTY_OP_END;\n\n if (b < bytes.length)\n return bufferSlice(bytes, 0, b);\n\n return bytes;\n}\n\nfunction sendExtInfo(proto) {\n let serverSigAlgs =\n 'ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521'\n + 'rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss';\n if (eddsaSupported)\n serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`;\n const algsLen = Buffer.byteLength(serverSigAlgs);\n\n let p = proto._packetRW.write.allocStart;\n const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen);\n\n packet[p] = MESSAGE.EXT_INFO;\n\n writeUInt32BE(packet, 1, ++p);\n\n writeUInt32BE(packet, 15, p += 4);\n packet.utf8Write('server-sig-algs', p += 4, 15);\n\n writeUInt32BE(packet, algsLen, p += 15);\n packet.utf8Write(serverSigAlgs, p += 4, algsLen);\n\n proto._debug && proto._debug('Outbound: Sending EXT_INFO');\n sendPacket(proto, proto._packetRW.write.finalize(packet));\n}\n\nmodule.exports = Protocol;\n","'use strict';\n\nconst EventEmitter = require('events');\nconst fs = require('fs');\nconst { constants } = fs;\nconst {\n Readable: ReadableStream,\n Writable: WritableStream\n} = require('stream');\nconst { inherits, isDate } = require('util');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst {\n bufferCopy,\n bufferSlice,\n makeBufferParser,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst ATTR = {\n SIZE: 0x00000001,\n UIDGID: 0x00000002,\n PERMISSIONS: 0x00000004,\n ACMODTIME: 0x00000008,\n EXTENDED: 0x80000000,\n};\n\n// Large enough to store all possible attributes\nconst ATTRS_BUF = Buffer.alloc(28);\n\nconst STATUS_CODE = {\n OK: 0,\n EOF: 1,\n NO_SUCH_FILE: 2,\n PERMISSION_DENIED: 3,\n FAILURE: 4,\n BAD_MESSAGE: 5,\n NO_CONNECTION: 6,\n CONNECTION_LOST: 7,\n OP_UNSUPPORTED: 8\n};\n\nconst VALID_STATUS_CODES = new Map(\n Object.values(STATUS_CODE).map((n) => [n, 1])\n);\n\nconst STATUS_CODE_STR = {\n [STATUS_CODE.OK]: 'No error',\n [STATUS_CODE.EOF]: 'End of file',\n [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory',\n [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied',\n [STATUS_CODE.FAILURE]: 'Failure',\n [STATUS_CODE.BAD_MESSAGE]: 'Bad message',\n [STATUS_CODE.NO_CONNECTION]: 'No connection',\n [STATUS_CODE.CONNECTION_LOST]: 'Connection lost',\n [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported',\n};\n\nconst REQUEST = {\n INIT: 1,\n OPEN: 3,\n CLOSE: 4,\n READ: 5,\n WRITE: 6,\n LSTAT: 7,\n FSTAT: 8,\n SETSTAT: 9,\n FSETSTAT: 10,\n OPENDIR: 11,\n READDIR: 12,\n REMOVE: 13,\n MKDIR: 14,\n RMDIR: 15,\n REALPATH: 16,\n STAT: 17,\n RENAME: 18,\n READLINK: 19,\n SYMLINK: 20,\n EXTENDED: 200\n};\n\nconst RESPONSE = {\n VERSION: 2,\n STATUS: 101,\n HANDLE: 102,\n DATA: 103,\n NAME: 104,\n ATTRS: 105,\n EXTENDED: 201\n};\n\nconst OPEN_MODE = {\n READ: 0x00000001,\n WRITE: 0x00000002,\n APPEND: 0x00000004,\n CREAT: 0x00000008,\n TRUNC: 0x00000010,\n EXCL: 0x00000020\n};\n\nconst PKT_RW_OVERHEAD = 2 * 1024;\nconst MAX_REQID = 2 ** 32 - 1;\nconst CLIENT_VERSION_BUFFER = Buffer.from([\n 0, 0, 0, 5 /* length */,\n REQUEST.INIT,\n 0, 0, 0, 3 /* version */\n]);\nconst SERVER_VERSION_BUFFER = Buffer.from([\n 0, 0, 0, 5 /* length */,\n RESPONSE.VERSION,\n 0, 0, 0, 3 /* version */\n]);\n\nconst RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/;\nconst OPENSSH_MAX_PKT_LEN = 256 * 1024;\n\nconst bufferParser = makeBufferParser();\n\nconst fakeStderr = {\n readable: false,\n writable: false,\n push: (data) => {},\n once: () => {},\n on: () => {},\n emit: () => {},\n end: () => {},\n};\n\nfunction noop() {}\n\n// Emulates enough of `Channel` to be able to be used as a drop-in replacement\n// in order to process incoming data with as little overhead as possible\nclass SFTP extends EventEmitter {\n constructor(client, chanInfo, cfg) {\n super();\n\n if (typeof cfg !== 'object' || !cfg)\n cfg = {};\n\n const remoteIdentRaw = client._protocol._remoteIdentRaw;\n\n this.server = !!cfg.server;\n this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);\n this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw));\n\n this._version = -1;\n this._extensions = {};\n this._biOpt = cfg.biOpt;\n this._pktLenBytes = 0;\n this._pktLen = 0;\n this._pktPos = 0;\n this._pktType = 0;\n this._pktData = undefined;\n this._writeReqid = -1;\n this._requests = {};\n this._maxInPktLen = OPENSSH_MAX_PKT_LEN;\n this._maxOutPktLen = 34000;\n this._maxReadLen =\n (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;\n this._maxWriteLen =\n (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;\n\n this.maxOpenHandles = undefined;\n\n // Channel compatibility\n this._client = client;\n this._protocol = client._protocol;\n this._callbacks = [];\n this._hasX11 = false;\n this._exit = {\n code: undefined,\n signal: undefined,\n dump: undefined,\n desc: undefined,\n };\n this._waitWindow = false; // SSH-level backpressure\n this._chunkcb = undefined;\n this._buffer = [];\n this.type = chanInfo.type;\n this.subtype = undefined;\n this.incoming = chanInfo.incoming;\n this.outgoing = chanInfo.outgoing;\n this.stderr = fakeStderr;\n this.readable = true;\n }\n\n // This handles incoming data to parse\n push(data) {\n if (data === null) {\n cleanupRequests(this);\n if (!this.readable)\n return;\n // No more incoming data from the remote side\n this.readable = false;\n this.emit('end');\n return;\n }\n /*\n uint32 length\n byte type\n byte[length - 1] data payload\n */\n let p = 0;\n\n while (p < data.length) {\n if (this._pktLenBytes < 4) {\n let nb = Math.min(4 - this._pktLenBytes, data.length - p);\n this._pktLenBytes += nb;\n\n while (nb--)\n this._pktLen = (this._pktLen << 8) + data[p++];\n\n if (this._pktLenBytes < 4)\n return;\n if (this._pktLen === 0)\n return doFatalSFTPError(this, 'Invalid packet length');\n if (this._pktLen > this._maxInPktLen) {\n const max = this._maxInPktLen;\n return doFatalSFTPError(\n this,\n `Packet length ${this._pktLen} exceeds max length of ${max}`\n );\n }\n if (p >= data.length)\n return;\n }\n if (this._pktPos < this._pktLen) {\n const nb = Math.min(this._pktLen - this._pktPos, data.length - p);\n if (p !== 0 || nb !== data.length) {\n if (nb === this._pktLen) {\n this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb);\n } else {\n if (!this._pkt)\n this._pkt = Buffer.allocUnsafe(this._pktLen);\n this._pkt.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._pktPos\n );\n }\n } else if (nb === this._pktLen) {\n this._pkt = data;\n } else {\n if (!this._pkt)\n this._pkt = Buffer.allocUnsafe(this._pktLen);\n this._pkt.set(data, this._pktPos);\n }\n p += nb;\n this._pktPos += nb;\n if (this._pktPos < this._pktLen)\n return;\n }\n\n const type = this._pkt[0];\n const payload = this._pkt;\n\n // Prepare for next packet\n this._pktLen = 0;\n this._pktLenBytes = 0;\n this._pkt = undefined;\n this._pktPos = 0;\n\n const handler = (this.server\n ? SERVER_HANDLERS[type]\n : CLIENT_HANDLERS[type]);\n if (!handler)\n return doFatalSFTPError(this, `Unknown packet type ${type}`);\n\n if (this._version === -1) {\n if (this.server) {\n if (type !== REQUEST.INIT)\n return doFatalSFTPError(this, `Expected INIT packet, got ${type}`);\n } else if (type !== RESPONSE.VERSION) {\n return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`);\n }\n }\n\n if (handler(this, payload) === false)\n return;\n }\n }\n\n end() {\n this.destroy();\n }\n destroy() {\n if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {\n this.outgoing.state = 'closing';\n this._protocol.channelClose(this.outgoing.id);\n }\n }\n _init() {\n this._init = noop;\n if (!this.server)\n sendOrBuffer(this, CLIENT_VERSION_BUFFER);\n }\n\n // ===========================================================================\n // Client-specific ===========================================================\n // ===========================================================================\n createReadStream(path, options) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n return new ReadStream(this, path, options);\n }\n createWriteStream(path, options) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n return new WriteStream(this, path, options);\n }\n open(path, flags_, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (typeof attrs === 'function') {\n cb = attrs;\n attrs = undefined;\n }\n\n const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_));\n if (flags === null)\n throw new Error(`Unknown flags string: ${flags_}`);\n\n let attrsFlags = 0;\n let attrsLen = 0;\n if (typeof attrs === 'string' || typeof attrs === 'number')\n attrs = { mode: attrs };\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n attrsFlags = attrs.flags;\n attrsLen = attrs.nb;\n }\n\n /*\n uint32 id\n string filename\n uint32 pflags\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.OPEN;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n writeUInt32BE(buf, attrsFlags, p += 4);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN`\n );\n }\n close(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.CLOSE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE`\n );\n }\n read(handle, buf, off, len, position, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n if (!Buffer.isBuffer(buf))\n throw new Error('buffer is not a Buffer');\n if (off >= buf.length)\n throw new Error('offset is out of bounds');\n if (off + len > buf.length)\n throw new Error('length extends beyond buffer');\n if (position === null)\n throw new Error('null position currently unsupported');\n\n read_(this, handle, buf, off, len, position, cb);\n }\n readData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.read(handle, buf, off, len, position, cb);\n }\n write(handle, buf, off, len, position, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n if (!Buffer.isBuffer(buf))\n throw new Error('buffer is not a Buffer');\n if (off > buf.length)\n throw new Error('offset is out of bounds');\n if (off + len > buf.length)\n throw new Error('length extends beyond buffer');\n if (position === null)\n throw new Error('null position currently unsupported');\n\n if (!len) {\n cb && process.nextTick(cb, undefined, 0);\n return;\n }\n\n const maxDataLen = this._maxWriteLen;\n const overflow = Math.max(len - maxDataLen, 0);\n const origPosition = position;\n\n if (overflow)\n len = maxDataLen;\n\n /*\n uint32 id\n string handle\n uint64 offset\n string data\n */\n const handleLen = handle.length;\n let p = 9;\n const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len);\n\n writeUInt32BE(out, out.length - 4, 0);\n out[4] = REQUEST.WRITE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(out, reqid, 5);\n\n writeUInt32BE(out, handleLen, p);\n out.set(handle, p += 4);\n p += handleLen;\n for (let i = 7; i >= 0; --i) {\n out[p + i] = position & 0xFF;\n position /= 256;\n }\n writeUInt32BE(out, len, p += 8);\n bufferCopy(buf, out, off, off + len, p += 4);\n\n this._requests[reqid] = {\n cb: (err) => {\n if (err) {\n if (typeof cb === 'function')\n cb(err);\n } else if (overflow) {\n this.write(handle,\n buf,\n off + len,\n overflow,\n origPosition + len,\n cb);\n } else if (typeof cb === 'function') {\n cb(undefined, off + len);\n }\n }\n };\n\n const isSent = sendOrBuffer(this, out);\n if (this._debug) {\n const how = (isSent ? 'Sent' : 'Buffered');\n this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`);\n }\n }\n writeData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.write(handle, buf, off, len, position, cb);\n }\n fastGet(remotePath, localPath, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n fastXfer(this, fs, remotePath, localPath, opts, cb);\n }\n fastPut(localPath, remotePath, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n fastXfer(fs, this, localPath, remotePath, opts, cb);\n }\n readFile(path, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, flag: 'r' };\n else if (!options)\n options = { encoding: null, flag: 'r' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n const encoding = options.encoding;\n if (encoding && !Buffer.isEncoding(encoding))\n throw new Error(`Unknown encoding: ${encoding}`);\n\n // First stat the file, so we know the size.\n let size;\n let buffer; // Single buffer with file data\n let buffers; // List for when size is unknown\n let pos = 0;\n let handle;\n\n // SFTPv3 does not support using -1 for read position, so we have to track\n // read position manually\n let bytesRead = 0;\n\n const flag = options.flag || 'r';\n\n const read = () => {\n if (size === 0) {\n buffer = Buffer.allocUnsafe(8192);\n this.read(handle, buffer, 0, 8192, bytesRead, afterRead);\n } else {\n this.read(handle, buffer, pos, size - pos, bytesRead, afterRead);\n }\n };\n\n const afterRead = (er, nbytes) => {\n let eof;\n if (er) {\n eof = (er.code === STATUS_CODE.EOF);\n if (!eof) {\n return this.close(handle, () => {\n return callback && callback(er);\n });\n }\n } else {\n eof = false;\n }\n\n if (eof || (size === 0 && nbytes === 0))\n return close();\n\n bytesRead += nbytes;\n pos += nbytes;\n if (size !== 0) {\n if (pos === size)\n close();\n else\n read();\n } else {\n // Unknown size, just read until we don't get bytes.\n buffers.push(bufferSlice(buffer, 0, nbytes));\n read();\n }\n };\n afterRead._wantEOFError = true;\n\n const close = () => {\n this.close(handle, (er) => {\n if (size === 0) {\n // Collect the data into the buffers list.\n buffer = Buffer.concat(buffers, pos);\n } else if (pos < size) {\n buffer = bufferSlice(buffer, 0, pos);\n }\n\n if (encoding)\n buffer = buffer.toString(encoding);\n return callback && callback(er, buffer);\n });\n };\n\n this.open(path, flag, 0o666, (er, handle_) => {\n if (er)\n return callback && callback(er);\n handle = handle_;\n\n const tryStat = (er, st) => {\n if (er) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.stat(path, (er_, st_) => {\n if (er_) {\n return this.close(handle, () => {\n callback && callback(er);\n });\n }\n tryStat(null, st_);\n });\n return;\n }\n\n size = st.size || 0;\n if (size === 0) {\n // The kernel lies about many files.\n // Go ahead and try to read some bytes.\n buffers = [];\n return read();\n }\n\n buffer = Buffer.allocUnsafe(size);\n read();\n };\n this.fstat(handle, tryStat);\n });\n }\n writeFile(path, data, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, mode: 0o666, flag: 'w' };\n else if (!options)\n options = { encoding: 'utf8', mode: 0o666, flag: 'w' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n if (options.encoding && !Buffer.isEncoding(options.encoding))\n throw new Error(`Unknown encoding: ${options.encoding}`);\n\n const flag = options.flag || 'w';\n this.open(path, flag, options.mode, (openErr, handle) => {\n if (openErr) {\n callback && callback(openErr);\n } else {\n const buffer = (Buffer.isBuffer(data)\n ? data\n : Buffer.from('' + data, options.encoding || 'utf8'));\n const position = (/a/.test(flag) ? null : 0);\n\n // SFTPv3 does not support the notion of 'current position'\n // (null position), so we just attempt to append to the end of the file\n // instead\n if (position === null) {\n const tryStat = (er, st) => {\n if (er) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.stat(path, (er_, st_) => {\n if (er_) {\n return this.close(handle, () => {\n callback && callback(er);\n });\n }\n tryStat(null, st_);\n });\n return;\n }\n writeAll(this, handle, buffer, 0, buffer.length, st.size, callback);\n };\n this.fstat(handle, tryStat);\n return;\n }\n writeAll(this, handle, buffer, 0, buffer.length, position, callback);\n }\n });\n }\n appendFile(path, data, options, callback_) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let callback;\n if (typeof callback_ === 'function') {\n callback = callback_;\n } else if (typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n\n if (typeof options === 'string')\n options = { encoding: options, mode: 0o666, flag: 'a' };\n else if (!options)\n options = { encoding: 'utf8', mode: 0o666, flag: 'a' };\n else if (typeof options !== 'object')\n throw new TypeError('Bad arguments');\n\n if (!options.flag)\n options = Object.assign({ flag: 'a' }, options);\n this.writeFile(path, data, options, callback);\n }\n exists(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n this.stat(path, (err) => {\n cb && cb(err ? false : true);\n });\n }\n unlink(filename, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string filename\n */\n const fnameLen = Buffer.byteLength(filename);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.REMOVE;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, fnameLen, p);\n buf.utf8Write(filename, p += 4, fnameLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE`\n );\n }\n rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RENAME;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, oldLen, p);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME`\n );\n }\n mkdir(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'function') {\n cb = attrs;\n attrs = undefined;\n }\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n }\n\n /*\n uint32 id\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.MKDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR`\n );\n }\n rmdir(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RMDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR`\n );\n }\n readdir(where, opts, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof opts !== 'object' || opts === null)\n opts = {};\n\n const doFilter = (opts && opts.full ? false : true);\n\n if (!Buffer.isBuffer(where) && typeof where !== 'string')\n throw new Error('missing directory handle or path');\n\n if (typeof where === 'string') {\n const entries = [];\n let e = 0;\n\n const reread = (err, handle) => {\n if (err)\n return cb(err);\n\n this.readdir(handle, opts, (err, list) => {\n const eof = (err && err.code === STATUS_CODE.EOF);\n\n if (err && !eof)\n return this.close(handle, () => cb(err));\n\n if (eof) {\n return this.close(handle, (err) => {\n if (err)\n return cb(err);\n cb(undefined, entries);\n });\n }\n\n for (let i = 0; i < list.length; ++i, ++e)\n entries[e] = list[i];\n\n reread(undefined, handle);\n });\n };\n return this.opendir(where, reread);\n }\n\n /*\n uint32 id\n string handle\n */\n const handleLen = where.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.READDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(where, p += 4);\n\n this._requests[reqid] = {\n cb: (doFilter\n ? (err, list) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n\n for (let i = list.length - 1; i >= 0; --i) {\n if (list[i].filename === '.' || list[i].filename === '..')\n list.splice(i, 1);\n }\n\n cb(undefined, list);\n }\n : cb)\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR`\n );\n }\n fstat(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.FSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT`\n );\n }\n stat(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.STAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT`\n );\n }\n lstat(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.LSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT`\n );\n }\n opendir(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.OPENDIR;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR`\n );\n }\n setstat(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.SETSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT`\n );\n }\n fsetstat(handle, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string handle\n ATTRS attrs\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.FSETSTAT;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n buf.set(handle, p += 4);\n writeUInt32BE(buf, flags, p += handleLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT`\n );\n }\n futimes(handle, atime, mtime, cb) {\n return this.fsetstat(handle, {\n atime: toUnixTimestamp(atime),\n mtime: toUnixTimestamp(mtime)\n }, cb);\n }\n utimes(path, atime, mtime, cb) {\n return this.setstat(path, {\n atime: toUnixTimestamp(atime),\n mtime: toUnixTimestamp(mtime)\n }, cb);\n }\n fchown(handle, uid, gid, cb) {\n return this.fsetstat(handle, {\n uid: uid,\n gid: gid\n }, cb);\n }\n chown(path, uid, gid, cb) {\n return this.setstat(path, {\n uid: uid,\n gid: gid\n }, cb);\n }\n fchmod(handle, mode, cb) {\n return this.fsetstat(handle, {\n mode: mode\n }, cb);\n }\n chmod(path, mode, cb) {\n return this.setstat(path, {\n mode: mode\n }, cb);\n }\n readlink(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.READLINK;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing link info'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK`\n );\n }\n symlink(targetPath, linkPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string linkpath\n string targetpath\n */\n const linkLen = Buffer.byteLength(linkPath);\n const targetLen = Buffer.byteLength(targetPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.SYMLINK;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n if (this._isOpenSSH) {\n // OpenSSH has linkpath and targetpath positions switched\n writeUInt32BE(buf, targetLen, p);\n buf.utf8Write(targetPath, p += 4, targetLen);\n writeUInt32BE(buf, linkLen, p += targetLen);\n buf.utf8Write(linkPath, p += 4, linkLen);\n } else {\n writeUInt32BE(buf, linkLen, p);\n buf.utf8Write(linkPath, p += 4, linkLen);\n writeUInt32BE(buf, targetLen, p += linkLen);\n buf.utf8Write(targetPath, p += 4, targetLen);\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK`\n );\n }\n realpath(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.REALPATH;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, pathLen, p);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing path info'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH`\n );\n }\n // extended requests\n ext_openssh_rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['posix-rename@openssh.com'];\n if (!ext || ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"posix-rename@openssh.com\"\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 24, p);\n buf.utf8Write('posix-rename@openssh.com', p += 4, 24);\n writeUInt32BE(buf, oldLen, p += 24);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`);\n }\n }\n ext_openssh_statvfs(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['statvfs@openssh.com'];\n if (!ext || ext !== '2')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"statvfs@openssh.com\"\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 19, p);\n buf.utf8Write('statvfs@openssh.com', p += 4, 19);\n writeUInt32BE(buf, pathLen, p += 19);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = { extended: 'statvfs@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`);\n }\n }\n ext_openssh_fstatvfs(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['fstatvfs@openssh.com'];\n if (!ext || ext !== '2')\n throw new Error('Server does not support this extended request');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string \"fstatvfs@openssh.com\"\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('fstatvfs@openssh.com', p += 4, 20);\n writeUInt32BE(buf, handleLen, p += 20);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`);\n }\n }\n ext_openssh_hardlink(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['hardlink@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"hardlink@openssh.com\"\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('hardlink@openssh.com', p += 4, 20);\n writeUInt32BE(buf, oldLen, p += 20);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`);\n }\n }\n ext_openssh_fsync(handle, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['fsync@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n /*\n uint32 id\n string \"fsync@openssh.com\"\n string handle\n */\n const handleLen = handle.length;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 17, p);\n buf.utf8Write('fsync@openssh.com', p += 4, 17);\n writeUInt32BE(buf, handleLen, p += 17);\n buf.set(handle, p += 4);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com`\n );\n }\n ext_openssh_lsetstat(path, attrs, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['lsetstat@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n let flags = 0;\n let attrsLen = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n attrs = attrsToBytes(attrs);\n flags = attrs.flags;\n attrsLen = attrs.nb;\n } else if (typeof attrs === 'function') {\n cb = attrs;\n }\n\n /*\n uint32 id\n string \"lsetstat@openssh.com\"\n string path\n ATTRS attrs\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf =\n Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 20, p);\n buf.utf8Write('lsetstat@openssh.com', p += 4, 20);\n\n writeUInt32BE(buf, pathLen, p += 20);\n buf.utf8Write(path, p += 4, pathLen);\n\n writeUInt32BE(buf, flags, p += pathLen);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`);\n }\n }\n ext_openssh_expandPath(path, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['expand-path@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n /*\n uint32 id\n string \"expand-path@openssh.com\"\n string path\n */\n const pathLen = Buffer.byteLength(path);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 23, p);\n buf.utf8Write('expand-path@openssh.com', p += 4, 23);\n\n writeUInt32BE(buf, pathLen, p += 20);\n buf.utf8Write(path, p += 4, pathLen);\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing expanded path'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`);\n }\n }\n ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['copy-data'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n if (!Buffer.isBuffer(srcHandle))\n throw new Error('Source handle is not a Buffer');\n\n if (!Buffer.isBuffer(dstHandle))\n throw new Error('Destination handle is not a Buffer');\n\n /*\n uint32 id\n string \"copy-data\"\n string read-from-handle\n uint64 read-from-offset\n uint64 read-data-length\n string write-to-handle\n uint64 write-to-offset\n */\n let p = 0;\n const buf = Buffer.allocUnsafe(\n 4 + 1\n + 4\n + 4 + 9\n + 4 + srcHandle.length\n + 8\n + 8\n + 4 + dstHandle.length\n + 8\n );\n\n writeUInt32BE(buf, buf.length - 4, p);\n p += 4;\n\n buf[p] = REQUEST.EXTENDED;\n ++p;\n\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, p);\n p += 4;\n\n writeUInt32BE(buf, 9, p);\n p += 4;\n buf.utf8Write('copy-data', p, 9);\n p += 9;\n\n writeUInt32BE(buf, srcHandle.length, p);\n p += 4;\n buf.set(srcHandle, p);\n p += srcHandle.length;\n\n for (let i = 7; i >= 0; --i) {\n buf[p + i] = srcOffset & 0xFF;\n srcOffset /= 256;\n }\n p += 8;\n\n for (let i = 7; i >= 0; --i) {\n buf[p + i] = len & 0xFF;\n len /= 256;\n }\n p += 8;\n\n writeUInt32BE(buf, dstHandle.length, p);\n p += 4;\n buf.set(dstHandle, p);\n p += dstHandle.length;\n\n for (let i = 7; i >= 0; --i) {\n buf[p + i] = dstOffset & 0xFF;\n dstOffset /= 256;\n }\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} copy-data`);\n }\n }\n ext_home_dir(username, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['home-directory'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n if (typeof username !== 'string')\n throw new TypeError('username is not a string');\n\n /*\n uint32 id\n string \"home-directory\"\n string username\n */\n let p = 0;\n const usernameLen = Buffer.byteLength(username);\n const buf = Buffer.allocUnsafe(\n 4 + 1\n + 4\n + 4 + 14\n + 4 + usernameLen\n );\n\n writeUInt32BE(buf, buf.length - 4, p);\n p += 4;\n\n buf[p] = REQUEST.EXTENDED;\n ++p;\n\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, p);\n p += 4;\n\n writeUInt32BE(buf, 14, p);\n p += 4;\n buf.utf8Write('home-directory', p, 14);\n p += 14;\n\n writeUInt32BE(buf, usernameLen, p);\n p += 4;\n buf.utf8Write(username, p, usernameLen);\n p += usernameLen;\n\n this._requests[reqid] = {\n cb: (err, names) => {\n if (typeof cb !== 'function')\n return;\n if (err)\n return cb(err);\n if (!names || !names.length)\n return cb(new Error('Response missing home directory'));\n cb(undefined, names[0].filename);\n }\n };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} home-directory`);\n }\n }\n ext_users_groups(uids, gids, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n const ext = this._extensions['users-groups-by-id@openssh.com'];\n if (ext !== '1')\n throw new Error('Server does not support this extended request');\n\n if (!Array.isArray(uids))\n throw new TypeError('uids is not an array');\n for (const val of uids) {\n if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1))\n throw new Error('uid values must all be 32-bit unsigned integers');\n }\n if (!Array.isArray(gids))\n throw new TypeError('gids is not an array');\n for (const val of gids) {\n if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1))\n throw new Error('gid values must all be 32-bit unsigned integers');\n }\n\n /*\n uint32 id\n string \"users-groups-by-id@openssh.com\"\n string uids\n uint32 uid1\n ...\n string gids\n uint32 gid1\n ...\n */\n let p = 0;\n const buf = Buffer.allocUnsafe(\n 4 + 1\n + 4\n + 4 + 30\n + 4 + (4 * uids.length)\n + 4 + (4 * gids.length)\n );\n\n writeUInt32BE(buf, buf.length - 4, p);\n p += 4;\n\n buf[p] = REQUEST.EXTENDED;\n ++p;\n\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, p);\n p += 4;\n\n writeUInt32BE(buf, 30, p);\n p += 4;\n buf.utf8Write('users-groups-by-id@openssh.com', p, 30);\n p += 30;\n\n writeUInt32BE(buf, 4 * uids.length, p);\n p += 4;\n for (const val of uids) {\n writeUInt32BE(buf, val, p);\n p += 4;\n }\n\n writeUInt32BE(buf, 4 * gids.length, p);\n p += 4;\n for (const val of gids) {\n writeUInt32BE(buf, val, p);\n p += 4;\n }\n\n this._requests[reqid] = { extended: 'users-groups-by-id@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n if (this._debug) {\n const status = (isBuffered ? 'Buffered' : 'Sending');\n this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`);\n }\n }\n // ===========================================================================\n // Server-specific ===========================================================\n // ===========================================================================\n handle(reqid, handle) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!Buffer.isBuffer(handle))\n throw new Error('handle is not a Buffer');\n\n const handleLen = handle.length;\n\n if (handleLen > 256)\n throw new Error('handle too large (> 256 bytes)');\n\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.HANDLE;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, handleLen, p);\n if (handleLen)\n buf.set(handle, p += 4);\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE`\n );\n }\n status(reqid, code, message) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!VALID_STATUS_CODES.has(code))\n throw new Error(`Bad status code: ${code}`);\n\n message || (message = '');\n\n const msgLen = Buffer.byteLength(message);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.STATUS;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, code, p);\n\n writeUInt32BE(buf, msgLen, p += 4);\n p += 4;\n if (msgLen) {\n buf.utf8Write(message, p, msgLen);\n p += msgLen;\n }\n\n writeUInt32BE(buf, 0, p); // Empty language tag\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS`\n );\n }\n data(reqid, data, encoding) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n const isBuffer = Buffer.isBuffer(data);\n\n if (!isBuffer && typeof data !== 'string')\n throw new Error('data is not a Buffer or string');\n\n let isUTF8;\n if (!isBuffer && !encoding) {\n encoding = undefined;\n isUTF8 = true;\n }\n\n const dataLen = (\n isBuffer\n ? data.length\n : Buffer.byteLength(data, encoding)\n );\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.DATA;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, dataLen, p);\n if (dataLen) {\n if (isBuffer)\n buf.set(data, p += 4);\n else if (isUTF8)\n buf.utf8Write(data, p += 4, dataLen);\n else\n buf.write(data, p += 4, dataLen, encoding);\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA`\n );\n }\n name(reqid, names) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (!Array.isArray(names)) {\n if (typeof names !== 'object' || names === null)\n throw new Error('names is not an object or array');\n names = [ names ];\n }\n\n const count = names.length;\n let namesLen = 0;\n let nameAttrs;\n const attrs = [];\n\n for (let i = 0; i < count; ++i) {\n const name = names[i];\n const filename = (\n !name || !name.filename || typeof name.filename !== 'string'\n ? ''\n : name.filename\n );\n namesLen += 4 + Buffer.byteLength(filename);\n const longname = (\n !name || !name.longname || typeof name.longname !== 'string'\n ? ''\n : name.longname\n );\n namesLen += 4 + Buffer.byteLength(longname);\n\n if (typeof name.attrs === 'object' && name.attrs !== null) {\n nameAttrs = attrsToBytes(name.attrs);\n namesLen += 4 + nameAttrs.nb;\n\n if (nameAttrs.nb) {\n let bytes;\n\n if (nameAttrs.nb === ATTRS_BUF.length) {\n bytes = new Uint8Array(ATTRS_BUF);\n } else {\n bytes = new Uint8Array(nameAttrs.nb);\n bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0);\n }\n\n nameAttrs.bytes = bytes;\n }\n\n attrs.push(nameAttrs);\n } else {\n namesLen += 4;\n attrs.push(null);\n }\n }\n\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.NAME;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, count, p);\n\n p += 4;\n\n for (let i = 0; i < count; ++i) {\n const name = names[i];\n\n {\n const filename = (\n !name || !name.filename || typeof name.filename !== 'string'\n ? ''\n : name.filename\n );\n const len = Buffer.byteLength(filename);\n writeUInt32BE(buf, len, p);\n p += 4;\n if (len) {\n buf.utf8Write(filename, p, len);\n p += len;\n }\n }\n\n {\n const longname = (\n !name || !name.longname || typeof name.longname !== 'string'\n ? ''\n : name.longname\n );\n const len = Buffer.byteLength(longname);\n writeUInt32BE(buf, len, p);\n p += 4;\n if (len) {\n buf.utf8Write(longname, p, len);\n p += len;\n }\n }\n\n const attr = attrs[i];\n if (attr) {\n writeUInt32BE(buf, attr.flags, p);\n p += 4;\n if (attr.flags && attr.bytes) {\n buf.set(attr.bytes, p);\n p += attr.nb;\n }\n } else {\n writeUInt32BE(buf, 0, p);\n p += 4;\n }\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME`\n );\n }\n attrs(reqid, attrs) {\n if (!this.server)\n throw new Error('Server-only method called in client mode');\n\n if (typeof attrs !== 'object' || attrs === null)\n throw new Error('attrs is not an object');\n\n attrs = attrsToBytes(attrs);\n const flags = attrs.flags;\n const attrsLen = attrs.nb;\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = RESPONSE.ATTRS;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, flags, p);\n if (attrsLen) {\n p += 4;\n\n if (attrsLen === ATTRS_BUF.length)\n buf.set(ATTRS_BUF, p);\n else\n bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);\n\n p += attrsLen;\n }\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS`\n );\n }\n}\n\nfunction tryCreateBuffer(size) {\n try {\n return Buffer.allocUnsafe(size);\n } catch (ex) {\n return ex;\n }\n}\n\nfunction read_(self, handle, buf, off, len, position, cb, req_) {\n const maxDataLen = self._maxReadLen;\n const overflow = Math.max(len - maxDataLen, 0);\n\n if (overflow)\n len = maxDataLen;\n\n /*\n uint32 id\n string handle\n uint64 offset\n uint32 len\n */\n const handleLen = handle.length;\n let p = 9;\n let pos = position;\n const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4);\n\n writeUInt32BE(out, out.length - 4, 0);\n out[4] = REQUEST.READ;\n const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(out, reqid, 5);\n\n writeUInt32BE(out, handleLen, p);\n out.set(handle, p += 4);\n p += handleLen;\n for (let i = 7; i >= 0; --i) {\n out[p + i] = pos & 0xFF;\n pos /= 256;\n }\n writeUInt32BE(out, len, p += 8);\n\n if (typeof cb !== 'function')\n cb = noop;\n\n const req = (req_ || {\n nb: 0,\n position,\n off,\n origOff: off,\n len: undefined,\n overflow: undefined,\n cb: (err, data, nb) => {\n const len = req.len;\n const overflow = req.overflow;\n\n if (err) {\n if (cb._wantEOFError || err.code !== STATUS_CODE.EOF)\n return cb(err);\n } else if (nb > len) {\n return cb(new Error('Received more data than requested'));\n } else if (nb === len && overflow) {\n req.nb += nb;\n req.position += nb;\n req.off += nb;\n read_(self, handle, buf, req.off, overflow, req.position, cb, req);\n return;\n }\n\n nb = (nb || 0);\n if (req.origOff === 0 && buf.length === req.nb)\n data = buf;\n else\n data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb);\n cb(undefined, req.nb + nb, data, req.position);\n },\n buffer: undefined,\n });\n\n req.len = len;\n req.overflow = overflow;\n\n // TODO: avoid creating multiple buffer slices when we need to re-call read_()\n // because of overflow\n req.buffer = bufferSlice(buf, off, off + len);\n\n self._requests[reqid] = req;\n\n const isBuffered = sendOrBuffer(self, out);\n self._debug && self._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ`\n );\n}\n\nfunction fastXfer(src, dst, srcPath, dstPath, opts, cb) {\n let concurrency = 64;\n let chunkSize = 32768;\n let onstep;\n let mode;\n let fileSize;\n\n if (typeof opts === 'function') {\n cb = opts;\n } else if (typeof opts === 'object' && opts !== null) {\n if (typeof opts.concurrency === 'number'\n && opts.concurrency > 0\n && !isNaN(opts.concurrency)) {\n concurrency = opts.concurrency;\n }\n if (typeof opts.chunkSize === 'number'\n && opts.chunkSize > 0\n && !isNaN(opts.chunkSize)) {\n chunkSize = opts.chunkSize;\n }\n if (typeof opts.fileSize === 'number'\n && opts.fileSize > 0\n && !isNaN(opts.fileSize)) {\n fileSize = opts.fileSize;\n }\n if (typeof opts.step === 'function')\n onstep = opts.step;\n\n if (typeof opts.mode === 'string' || typeof opts.mode === 'number')\n mode = modeNum(opts.mode);\n }\n\n // Internal state variables\n let fsize;\n let pdst = 0;\n let total = 0;\n let hadError = false;\n let srcHandle;\n let dstHandle;\n let readbuf;\n let bufsize = chunkSize * concurrency;\n\n function onerror(err) {\n if (hadError)\n return;\n\n hadError = true;\n\n let left = 0;\n let cbfinal;\n\n if (srcHandle || dstHandle) {\n cbfinal = () => {\n if (--left === 0)\n cb(err);\n };\n if (srcHandle && (src === fs || src.outgoing.state === 'open'))\n ++left;\n if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))\n ++left;\n if (srcHandle && (src === fs || src.outgoing.state === 'open'))\n src.close(srcHandle, cbfinal);\n if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))\n dst.close(dstHandle, cbfinal);\n } else {\n cb(err);\n }\n }\n\n src.open(srcPath, 'r', (err, sourceHandle) => {\n if (err)\n return onerror(err);\n\n srcHandle = sourceHandle;\n\n if (fileSize === undefined)\n src.fstat(srcHandle, tryStat);\n else\n tryStat(null, { size: fileSize });\n\n function tryStat(err, attrs) {\n if (err) {\n if (src !== fs) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n src.stat(srcPath, (err_, attrs_) => {\n if (err_)\n return onerror(err);\n tryStat(null, attrs_);\n });\n return;\n }\n return onerror(err);\n }\n fsize = attrs.size;\n\n dst.open(dstPath, 'w', (err, destHandle) => {\n if (err)\n return onerror(err);\n\n dstHandle = destHandle;\n\n if (fsize <= 0)\n return onerror();\n\n // Use less memory where possible\n while (bufsize > fsize) {\n if (concurrency === 1) {\n bufsize = fsize;\n break;\n }\n bufsize -= chunkSize;\n --concurrency;\n }\n\n readbuf = tryCreateBuffer(bufsize);\n if (readbuf instanceof Error)\n return onerror(readbuf);\n\n if (mode !== undefined) {\n dst.fchmod(dstHandle, mode, function tryAgain(err) {\n if (err) {\n // Try chmod() for sftp servers that may not support fchmod()\n // for whatever reason\n dst.chmod(dstPath, mode, (err_) => tryAgain());\n return;\n }\n startReads();\n });\n } else {\n startReads();\n }\n\n function onread(err, nb, data, dstpos, datapos, origChunkLen) {\n if (err)\n return onerror(err);\n\n datapos = datapos || 0;\n\n dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb);\n\n function writeCb(err) {\n if (err)\n return onerror(err);\n\n total += nb;\n onstep && onstep(total, nb, fsize);\n\n if (nb < origChunkLen)\n return singleRead(datapos, dstpos + nb, origChunkLen - nb);\n\n if (total === fsize) {\n dst.close(dstHandle, (err) => {\n dstHandle = undefined;\n if (err)\n return onerror(err);\n src.close(srcHandle, (err) => {\n srcHandle = undefined;\n if (err)\n return onerror(err);\n cb();\n });\n });\n return;\n }\n\n if (pdst >= fsize)\n return;\n\n const chunk =\n (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);\n singleRead(datapos, pdst, chunk);\n pdst += chunk;\n }\n }\n\n function makeCb(psrc, pdst, chunk) {\n return (err, nb, data) => {\n onread(err, nb, data, pdst, psrc, chunk);\n };\n }\n\n function singleRead(psrc, pdst, chunk) {\n src.read(srcHandle,\n readbuf,\n psrc,\n chunk,\n pdst,\n makeCb(psrc, pdst, chunk));\n }\n\n function startReads() {\n let reads = 0;\n let psrc = 0;\n while (pdst < fsize && reads < concurrency) {\n const chunk =\n (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);\n singleRead(psrc, pdst, chunk);\n psrc += chunk;\n pdst += chunk;\n ++reads;\n }\n }\n });\n }\n });\n}\n\nfunction writeAll(sftp, handle, buffer, offset, length, position, callback_) {\n const callback = (typeof callback_ === 'function' ? callback_ : undefined);\n\n sftp.write(handle,\n buffer,\n offset,\n length,\n position,\n (writeErr, written) => {\n if (writeErr) {\n return sftp.close(handle, () => {\n callback && callback(writeErr);\n });\n }\n if (written === length) {\n sftp.close(handle, callback);\n } else {\n offset += written;\n length -= written;\n position += written;\n writeAll(sftp, handle, buffer, offset, length, position, callback);\n }\n });\n}\n\nclass Stats {\n constructor(initial) {\n this.mode = (initial && initial.mode);\n this.uid = (initial && initial.uid);\n this.gid = (initial && initial.gid);\n this.size = (initial && initial.size);\n this.atime = (initial && initial.atime);\n this.mtime = (initial && initial.mtime);\n this.extended = (initial && initial.extended);\n }\n isDirectory() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFDIR);\n }\n isFile() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFREG);\n }\n isBlockDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFBLK);\n }\n isCharacterDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFCHR);\n }\n isSymbolicLink() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFLNK);\n }\n isFIFO() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFIFO);\n }\n isSocket() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK);\n }\n}\n\nfunction attrsToBytes(attrs) {\n let flags = 0;\n let nb = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n if (typeof attrs.size === 'number') {\n flags |= ATTR.SIZE;\n const val = attrs.size;\n // Big Endian\n ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56\n ATTRS_BUF[nb++] = val / 281474976710656; // 2**48\n ATTRS_BUF[nb++] = val / 1099511627776; // 2**40\n ATTRS_BUF[nb++] = val / 4294967296; // 2**32\n ATTRS_BUF[nb++] = val / 16777216; // 2**24\n ATTRS_BUF[nb++] = val / 65536; // 2**16\n ATTRS_BUF[nb++] = val / 256; // 2**8\n ATTRS_BUF[nb++] = val;\n }\n if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') {\n flags |= ATTR.UIDGID;\n const uid = attrs.uid;\n const gid = attrs.gid;\n // Big Endian\n ATTRS_BUF[nb++] = uid >>> 24;\n ATTRS_BUF[nb++] = uid >>> 16;\n ATTRS_BUF[nb++] = uid >>> 8;\n ATTRS_BUF[nb++] = uid;\n ATTRS_BUF[nb++] = gid >>> 24;\n ATTRS_BUF[nb++] = gid >>> 16;\n ATTRS_BUF[nb++] = gid >>> 8;\n ATTRS_BUF[nb++] = gid;\n }\n if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') {\n const mode = modeNum(attrs.mode);\n flags |= ATTR.PERMISSIONS;\n // Big Endian\n ATTRS_BUF[nb++] = mode >>> 24;\n ATTRS_BUF[nb++] = mode >>> 16;\n ATTRS_BUF[nb++] = mode >>> 8;\n ATTRS_BUF[nb++] = mode;\n }\n if ((typeof attrs.atime === 'number' || isDate(attrs.atime))\n && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) {\n const atime = toUnixTimestamp(attrs.atime);\n const mtime = toUnixTimestamp(attrs.mtime);\n\n flags |= ATTR.ACMODTIME;\n // Big Endian\n ATTRS_BUF[nb++] = atime >>> 24;\n ATTRS_BUF[nb++] = atime >>> 16;\n ATTRS_BUF[nb++] = atime >>> 8;\n ATTRS_BUF[nb++] = atime;\n ATTRS_BUF[nb++] = mtime >>> 24;\n ATTRS_BUF[nb++] = mtime >>> 16;\n ATTRS_BUF[nb++] = mtime >>> 8;\n ATTRS_BUF[nb++] = mtime;\n }\n // TODO: extended attributes\n }\n\n return { flags, nb };\n}\n\nfunction toUnixTimestamp(time) {\n // eslint-disable-next-line no-self-compare\n if (typeof time === 'number' && time === time) // Valid, non-NaN number\n return time;\n if (isDate(time))\n return parseInt(time.getTime() / 1000, 10);\n throw new Error(`Cannot parse time: ${time}`);\n}\n\nfunction modeNum(mode) {\n // eslint-disable-next-line no-self-compare\n if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number\n return mode;\n if (typeof mode === 'string')\n return modeNum(parseInt(mode, 8));\n throw new Error(`Cannot parse mode: ${mode}`);\n}\n\nconst stringFlagMap = {\n 'r': OPEN_MODE.READ,\n 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE,\n 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE,\n 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,\n 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,\n 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL,\n 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE\n | OPEN_MODE.EXCL\n};\n\nfunction stringToFlags(str) {\n const flags = stringFlagMap[str];\n return (flags !== undefined ? flags : null);\n}\n\nconst flagsToString = (() => {\n const stringFlagMapKeys = Object.keys(stringFlagMap);\n return (flags) => {\n for (let i = 0; i < stringFlagMapKeys.length; ++i) {\n const key = stringFlagMapKeys[i];\n if (stringFlagMap[key] === flags)\n return key;\n }\n return null;\n };\n})();\n\nfunction readAttrs(biOpt) {\n /*\n uint32 flags\n uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE\n uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID\n uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID\n uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS\n uint32 atime present only if flag SSH_FILEXFER_ACMODTIME\n uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME\n uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED\n string extended_type\n string extended_data\n ... more extended data (extended_type - extended_data pairs),\n so that number of pairs equals extended_count\n */\n const flags = bufferParser.readUInt32BE();\n if (flags === undefined)\n return;\n\n const attrs = new Stats();\n if (flags & ATTR.SIZE) {\n const size = bufferParser.readUInt64BE(biOpt);\n if (size === undefined)\n return;\n attrs.size = size;\n }\n\n if (flags & ATTR.UIDGID) {\n const uid = bufferParser.readUInt32BE();\n const gid = bufferParser.readUInt32BE();\n if (gid === undefined)\n return;\n attrs.uid = uid;\n attrs.gid = gid;\n }\n\n if (flags & ATTR.PERMISSIONS) {\n const mode = bufferParser.readUInt32BE();\n if (mode === undefined)\n return;\n attrs.mode = mode;\n }\n\n if (flags & ATTR.ACMODTIME) {\n const atime = bufferParser.readUInt32BE();\n const mtime = bufferParser.readUInt32BE();\n if (mtime === undefined)\n return;\n attrs.atime = atime;\n attrs.mtime = mtime;\n }\n\n if (flags & ATTR.EXTENDED) {\n const count = bufferParser.readUInt32BE();\n if (count === undefined)\n return;\n const extended = {};\n for (let i = 0; i < count; ++i) {\n const type = bufferParser.readString(true);\n const data = bufferParser.readString();\n if (data === undefined)\n return;\n extended[type] = data;\n }\n attrs.extended = extended;\n }\n\n return attrs;\n}\n\nfunction sendOrBuffer(sftp, payload) {\n const ret = tryWritePayload(sftp, payload);\n if (ret !== undefined) {\n sftp._buffer.push(ret);\n return false;\n }\n return true;\n}\n\nfunction tryWritePayload(sftp, payload) {\n const outgoing = sftp.outgoing;\n if (outgoing.state !== 'open')\n return;\n\n if (outgoing.window === 0) {\n sftp._waitWindow = true;\n sftp._chunkcb = drainBuffer;\n return payload;\n }\n\n let ret;\n const len = payload.length;\n let p = 0;\n\n while (len - p > 0 && outgoing.window > 0) {\n const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize);\n outgoing.window -= actualLen;\n if (outgoing.window === 0) {\n sftp._waitWindow = true;\n sftp._chunkcb = drainBuffer;\n }\n\n if (p === 0 && actualLen === len) {\n sftp._protocol.channelData(sftp.outgoing.id, payload);\n } else {\n sftp._protocol.channelData(sftp.outgoing.id,\n bufferSlice(payload, p, p + actualLen));\n }\n\n p += actualLen;\n }\n\n if (len - p > 0) {\n if (p > 0)\n ret = bufferSlice(payload, p, len);\n else\n ret = payload; // XXX: should never get here?\n }\n\n return ret;\n}\n\nfunction drainBuffer() {\n this._chunkcb = undefined;\n const buffer = this._buffer;\n let i = 0;\n while (i < buffer.length) {\n const payload = buffer[i];\n const ret = tryWritePayload(this, payload);\n if (ret !== undefined) {\n if (ret !== payload)\n buffer[i] = ret;\n if (i > 0)\n this._buffer = buffer.slice(i);\n return;\n }\n ++i;\n }\n if (i > 0)\n this._buffer = [];\n}\n\nfunction doFatalSFTPError(sftp, msg, noDebug) {\n const err = new Error(msg);\n err.level = 'sftp-protocol';\n if (!noDebug && sftp._debug)\n sftp._debug(`SFTP: Inbound: ${msg}`);\n sftp.emit('error', err);\n sftp.destroy();\n cleanupRequests(sftp);\n return false;\n}\n\nfunction cleanupRequests(sftp) {\n const keys = Object.keys(sftp._requests);\n if (keys.length === 0)\n return;\n\n const reqs = sftp._requests;\n sftp._requests = {};\n const err = new Error('No response from server');\n for (let i = 0; i < keys.length; ++i) {\n const req = reqs[keys[i]];\n if (typeof req.cb === 'function')\n req.cb(err);\n }\n}\n\nfunction requestLimits(sftp, cb) {\n /*\n uint32 id\n string \"limits@openssh.com\"\n */\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.EXTENDED;\n const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, 18, p);\n buf.utf8Write('limits@openssh.com', p += 4, 18);\n\n sftp._requests[reqid] = { extended: 'limits@openssh.com', cb };\n\n const isBuffered = sendOrBuffer(sftp, buf);\n if (sftp._debug) {\n const which = (isBuffered ? 'Buffered' : 'Sending');\n sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`);\n }\n}\n\nconst CLIENT_HANDLERS = {\n [RESPONSE.VERSION]: (sftp, payload) => {\n if (sftp._version !== -1)\n return doFatalSFTPError(sftp, 'Duplicate VERSION packet');\n\n const extensions = {};\n\n /*\n uint32 version\n \n */\n bufferParser.init(payload, 1);\n let version = bufferParser.readUInt32BE();\n while (bufferParser.avail()) {\n const extName = bufferParser.readString(true);\n const extData = bufferParser.readString(true);\n if (extData === undefined) {\n version = undefined;\n break;\n }\n extensions[extName] = extData;\n }\n bufferParser.clear();\n\n if (version === undefined)\n return doFatalSFTPError(sftp, 'Malformed VERSION packet');\n\n if (sftp._debug) {\n const names = Object.keys(extensions);\n if (names.length) {\n sftp._debug(\n `SFTP: Inbound: Received VERSION (v${version}, exts:${names})`\n );\n } else {\n sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`);\n }\n }\n\n sftp._version = version;\n sftp._extensions = extensions;\n\n if (extensions['limits@openssh.com'] === '1') {\n return requestLimits(sftp, (err, limits) => {\n if (!err) {\n if (limits.maxPktLen > 0)\n sftp._maxOutPktLen = limits.maxPktLen;\n if (limits.maxReadLen > 0)\n sftp._maxReadLen = limits.maxReadLen;\n if (limits.maxWriteLen > 0)\n sftp._maxWriteLen = limits.maxWriteLen;\n sftp.maxOpenHandles = (\n limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity\n );\n }\n sftp.emit('ready');\n });\n }\n\n sftp.emit('ready');\n },\n [RESPONSE.STATUS]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n uint32 error/status code\n string error message (ISO-10646 UTF-8)\n string language tag\n */\n const errorCode = bufferParser.readUInt32BE();\n const errorMsg = bufferParser.readString(true);\n bufferParser.clear();\n\n // Note: we avoid checking that the error message and language tag are in\n // the packet because there are some broken implementations that incorrectly\n // omit them. The language tag in general was never really used amongst ssh\n // implementations, so in the case of a missing error message we just\n // default to something sensible.\n\n if (sftp._debug) {\n const jsonMsg = JSON.stringify(errorMsg);\n sftp._debug(\n `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})`\n );\n }\n const req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n if (req && typeof req.cb === 'function') {\n if (errorCode === STATUS_CODE.OK) {\n req.cb();\n return;\n }\n const err = new Error(errorMsg\n || STATUS_CODE_STR[errorCode]\n || 'Unknown status');\n err.code = errorCode;\n req.cb(err);\n }\n },\n [RESPONSE.HANDLE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined) {\n if (reqID !== undefined)\n delete sftp._requests[reqID];\n return doFatalSFTPError(sftp, 'Malformed HANDLE packet');\n }\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`);\n\n const req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n if (req && typeof req.cb === 'function')\n req.cb(undefined, handle);\n },\n [RESPONSE.DATA]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n string data\n */\n if (req && typeof req.cb === 'function') {\n if (req.buffer) {\n // We have already pre-allocated space to store the data\n\n const nb = bufferParser.readString(req.buffer);\n bufferParser.clear();\n\n if (nb !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`\n );\n req.cb(undefined, req.buffer, nb);\n return;\n }\n } else {\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})`\n );\n req.cb(undefined, data);\n return;\n }\n }\n } else {\n const nb = bufferParser.skipString();\n bufferParser.clear();\n if (nb !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`\n );\n return;\n }\n }\n\n return doFatalSFTPError(sftp, 'Malformed DATA packet');\n },\n [RESPONSE.NAME]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n uint32 count\n repeats count times:\n string filename\n string longname\n ATTRS attrs\n */\n const count = bufferParser.readUInt32BE();\n if (count !== undefined) {\n let names = [];\n for (let i = 0; i < count; ++i) {\n // We are going to assume UTF-8 for filenames despite the SFTPv3\n // spec not specifying an encoding because the specs for newer\n // versions of the protocol all explicitly specify UTF-8 for\n // filenames\n const filename = bufferParser.readString(true);\n\n // `longname` only exists in SFTPv3 and since it typically will\n // contain the filename, we assume it is also UTF-8\n const longname = bufferParser.readString(true);\n\n const attrs = readAttrs(sftp._biOpt);\n if (attrs === undefined) {\n names = undefined;\n break;\n }\n names.push({ filename, longname, attrs });\n }\n if (names !== undefined) {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})`\n );\n bufferParser.clear();\n if (req && typeof req.cb === 'function')\n req.cb(undefined, names);\n return;\n }\n }\n\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed NAME packet');\n },\n [RESPONSE.ATTRS]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n let req;\n if (reqID !== undefined) {\n req = sftp._requests[reqID];\n delete sftp._requests[reqID];\n }\n /*\n ATTRS attrs\n */\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n if (attrs !== undefined) {\n sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`);\n if (req && typeof req.cb === 'function')\n req.cb(undefined, attrs);\n return;\n }\n\n return doFatalSFTPError(sftp, 'Malformed ATTRS packet');\n },\n [RESPONSE.EXTENDED]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n if (reqID !== undefined) {\n const req = sftp._requests[reqID];\n if (req) {\n delete sftp._requests[reqID];\n switch (req.extended) {\n case 'statvfs@openssh.com':\n case 'fstatvfs@openssh.com': {\n /*\n uint64 f_bsize // file system block size\n uint64 f_frsize // fundamental fs block size\n uint64 f_blocks // number of blocks (unit f_frsize)\n uint64 f_bfree // free blocks in file system\n uint64 f_bavail // free blocks for non-root\n uint64 f_files // total file inodes\n uint64 f_ffree // free file inodes\n uint64 f_favail // free file inodes for to non-root\n uint64 f_fsid // file system id\n uint64 f_flag // bit mask of f_flag values\n uint64 f_namemax // maximum filename length\n */\n const biOpt = sftp._biOpt;\n const stats = {\n f_bsize: bufferParser.readUInt64BE(biOpt),\n f_frsize: bufferParser.readUInt64BE(biOpt),\n f_blocks: bufferParser.readUInt64BE(biOpt),\n f_bfree: bufferParser.readUInt64BE(biOpt),\n f_bavail: bufferParser.readUInt64BE(biOpt),\n f_files: bufferParser.readUInt64BE(biOpt),\n f_ffree: bufferParser.readUInt64BE(biOpt),\n f_favail: bufferParser.readUInt64BE(biOpt),\n f_sid: bufferParser.readUInt64BE(biOpt),\n f_flag: bufferParser.readUInt64BE(biOpt),\n f_namemax: bufferParser.readUInt64BE(biOpt),\n };\n if (stats.f_namemax === undefined)\n break;\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, stats);\n return;\n }\n case 'limits@openssh.com': {\n /*\n uint64 max-packet-length\n uint64 max-read-length\n uint64 max-write-length\n uint64 max-open-handles\n */\n const limits = {\n maxPktLen: bufferParser.readUInt64BE(),\n maxReadLen: bufferParser.readUInt64BE(),\n maxWriteLen: bufferParser.readUInt64BE(),\n maxOpenHandles: bufferParser.readUInt64BE(),\n };\n if (limits.maxOpenHandles === undefined)\n break;\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, limits);\n return;\n }\n case 'users-groups-by-id@openssh.com': {\n /*\n string usernames\n string username1\n ...\n string groupnames\n string groupname1\n ...\n */\n const usernameCount = bufferParser.readUInt32BE();\n if (usernameCount === undefined)\n break;\n const usernames = new Array(usernameCount);\n for (let i = 0; i < usernames.length; ++i)\n usernames[i] = bufferParser.readString(true);\n\n const groupnameCount = bufferParser.readUInt32BE();\n if (groupnameCount === undefined)\n break;\n const groupnames = new Array(groupnameCount);\n for (let i = 0; i < groupnames.length; ++i)\n groupnames[i] = bufferParser.readString(true);\n if (groupnames.length > 0\n && groupnames[groupnames.length - 1] === undefined) {\n break;\n }\n\n if (sftp._debug) {\n sftp._debug(\n 'SFTP: Inbound: Received EXTENDED_REPLY '\n + `(id:${reqID}, ${req.extended})`\n );\n }\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb(undefined, usernames, groupnames);\n return;\n }\n default:\n // Unknown extended request\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`\n );\n bufferParser.clear();\n if (typeof req.cb === 'function')\n req.cb();\n return;\n }\n } else {\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`\n );\n bufferParser.clear();\n return;\n }\n }\n\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet');\n },\n};\nconst SERVER_HANDLERS = {\n [REQUEST.INIT]: (sftp, payload) => {\n if (sftp._version !== -1)\n return doFatalSFTPError(sftp, 'Duplicate INIT packet');\n\n const extensions = {};\n\n /*\n uint32 version\n \n */\n bufferParser.init(payload, 1);\n let version = bufferParser.readUInt32BE();\n while (bufferParser.avail()) {\n const extName = bufferParser.readString(true);\n const extData = bufferParser.readString(true);\n if (extData === undefined) {\n version = undefined;\n break;\n }\n extensions[extName] = extData;\n }\n bufferParser.clear();\n\n if (version === undefined)\n return doFatalSFTPError(sftp, 'Malformed INIT packet');\n\n if (sftp._debug) {\n const names = Object.keys(extensions);\n if (names.length) {\n sftp._debug(\n `SFTP: Inbound: Received INIT (v${version}, exts:${names})`\n );\n } else {\n sftp._debug(`SFTP: Inbound: Received INIT (v${version})`);\n }\n }\n\n sendOrBuffer(sftp, SERVER_VERSION_BUFFER);\n\n sftp._version = version;\n sftp._extensions = extensions;\n sftp.emit('ready');\n },\n [REQUEST.OPEN]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string filename\n uint32 pflags\n ATTRS attrs\n */\n const filename = bufferParser.readString(true);\n const pflags = bufferParser.readUInt32BE();\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed OPEN packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`);\n\n if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.CLOSE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed CLOSE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`);\n\n if (!sftp.emit('CLOSE', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READ]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n uint64 offset\n uint32 len\n */\n const handle = bufferParser.readString();\n const offset = bufferParser.readUInt64BE(sftp._biOpt);\n const len = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (len === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed READ packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`);\n\n if (!sftp.emit('READ', reqID, handle, offset, len)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.WRITE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n uint64 offset\n string data\n */\n const handle = bufferParser.readString();\n const offset = bufferParser.readUInt64BE(sftp._biOpt);\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed WRITE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`);\n\n if (!sftp.emit('WRITE', reqID, handle, offset, data)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.LSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed LSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`);\n\n if (!sftp.emit('LSTAT', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.FSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed FSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`);\n\n if (!sftp.emit('FSTAT', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.SETSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n ATTRS attrs\n */\n const path = bufferParser.readString(true);\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed SETSTAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`);\n\n if (!sftp.emit('SETSTAT', reqID, path, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.FSETSTAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n ATTRS attrs\n */\n const handle = bufferParser.readString();\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received FSETSTAT (id:${reqID})`\n );\n\n if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.OPENDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed OPENDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`);\n\n if (!sftp.emit('OPENDIR', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string handle\n */\n const handle = bufferParser.readString();\n bufferParser.clear();\n\n if (handle === undefined || handle.length > 256)\n return doFatalSFTPError(sftp, 'Malformed READDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`);\n\n if (!sftp.emit('READDIR', reqID, handle)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.REMOVE]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed REMOVE packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`);\n\n if (!sftp.emit('REMOVE', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.MKDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n ATTRS attrs\n */\n const path = bufferParser.readString(true);\n const attrs = readAttrs(sftp._biOpt);\n bufferParser.clear();\n\n if (attrs === undefined)\n return doFatalSFTPError(sftp, 'Malformed MKDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`);\n\n if (!sftp.emit('MKDIR', reqID, path, attrs)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.RMDIR]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed RMDIR packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`);\n\n if (!sftp.emit('RMDIR', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.REALPATH]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed REALPATH packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received REALPATH (id:${reqID})`\n );\n\n if (!sftp.emit('REALPATH', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.STAT]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed STAT packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`);\n\n if (!sftp.emit('STAT', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.RENAME]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string oldpath\n string newpath\n */\n const oldPath = bufferParser.readString(true);\n const newPath = bufferParser.readString(true);\n bufferParser.clear();\n\n if (newPath === undefined)\n return doFatalSFTPError(sftp, 'Malformed RENAME packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`);\n\n if (!sftp.emit('RENAME', reqID, oldPath, newPath)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.READLINK]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string path\n */\n const path = bufferParser.readString(true);\n bufferParser.clear();\n\n if (path === undefined)\n return doFatalSFTPError(sftp, 'Malformed READLINK packet');\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received READLINK (id:${reqID})`\n );\n\n if (!sftp.emit('READLINK', reqID, path)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.SYMLINK]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string linkpath\n string targetpath\n */\n const linkPath = bufferParser.readString(true);\n const targetPath = bufferParser.readString(true);\n bufferParser.clear();\n\n if (targetPath === undefined)\n return doFatalSFTPError(sftp, 'Malformed SYMLINK packet');\n\n sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`);\n\n let handled;\n if (sftp._isOpenSSH) {\n // OpenSSH has linkpath and targetpath positions switched\n handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath);\n } else {\n handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath);\n }\n if (!handled) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n [REQUEST.EXTENDED]: (sftp, payload) => {\n bufferParser.init(payload, 1);\n const reqID = bufferParser.readUInt32BE();\n /*\n string extended-request\n ... any request-specific data ...\n */\n const extName = bufferParser.readString(true);\n if (extName === undefined) {\n bufferParser.clear();\n return doFatalSFTPError(sftp, 'Malformed EXTENDED packet');\n }\n\n let extData;\n if (bufferParser.avail())\n extData = bufferParser.readRaw();\n bufferParser.clear();\n\n sftp._debug && sftp._debug(\n `SFTP: Inbound: Received EXTENDED (id:${reqID})`\n );\n\n if (!sftp.emit('EXTENDED', reqID, extName, extData)) {\n // Automatically reject request if no handler for request type\n sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);\n }\n },\n};\n\n// =============================================================================\n// ReadStream/WriteStream-related ==============================================\n// =============================================================================\nconst {\n ERR_INVALID_ARG_TYPE,\n ERR_OUT_OF_RANGE,\n validateNumber\n} = require('./node-fs-compat');\n\nconst kMinPoolSpace = 128;\n\nlet pool;\n// It can happen that we expect to read a large chunk of data, and reserve\n// a large chunk of the pool accordingly, but the read() call only filled\n// a portion of it. If a concurrently executing read() then uses the same pool,\n// the \"reserved\" portion cannot be used, so we allow it to be re-used as a\n// new pool later.\nconst poolFragments = [];\n\nfunction allocNewPool(poolSize) {\n if (poolFragments.length > 0)\n pool = poolFragments.pop();\n else\n pool = Buffer.allocUnsafe(poolSize);\n pool.used = 0;\n}\n\n// Check the `this.start` and `this.end` of stream.\nfunction checkPosition(pos, name) {\n if (!Number.isSafeInteger(pos)) {\n validateNumber(pos, name);\n if (!Number.isInteger(pos))\n throw new ERR_OUT_OF_RANGE(name, 'an integer', pos);\n throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);\n }\n if (pos < 0)\n throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);\n}\n\nfunction roundUpToMultipleOf8(n) {\n return (n + 7) & ~7; // Align to 8 byte boundary.\n}\n\nfunction ReadStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // A little bit bigger buffer and water marks by default\n if (options.highWaterMark === undefined)\n options.highWaterMark = 64 * 1024;\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n options.autoDestroy = false; // Node 14 major change.\n\n ReadableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'r' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.end = options.end;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesRead = 0;\n this.isClosed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (this.end === undefined) {\n this.end = Infinity;\n } else if (this.end !== Infinity) {\n checkPosition(this.end, 'end');\n\n if (this.start !== undefined && this.start > this.end) {\n throw new ERR_OUT_OF_RANGE(\n 'start',\n `<= \"end\" (here: ${this.end})`,\n this.start\n );\n }\n }\n\n this.on('end', function() {\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}\ninherits(ReadStream, ReadableStream);\n\nReadStream.prototype.open = function() {\n if (this._opening)\n return;\n\n this._opening = true;\n\n this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {\n this._opening = false;\n\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n\n this.handle = handle;\n this.emit('open', handle);\n this.emit('ready');\n // Start the flow of data.\n this.read();\n });\n};\n\nReadStream.prototype._read = function(n) {\n if (!Buffer.isBuffer(this.handle))\n return this.once('open', () => this._read(n));\n\n // XXX: safe to remove this?\n if (this.destroyed)\n return;\n\n if (!pool || pool.length - pool.used < kMinPoolSpace) {\n // Discard the old pool.\n allocNewPool(this.readableHighWaterMark\n || this._readableState.highWaterMark);\n }\n\n // Grab another reference to the pool in the case that while we're\n // in the thread pool another read() finishes up the pool, and\n // allocates a new one.\n const thisPool = pool;\n let toRead = Math.min(pool.length - pool.used, n);\n const start = pool.used;\n\n if (this.end !== undefined)\n toRead = Math.min(this.end - this.pos + 1, toRead);\n\n // Already read everything we were supposed to read!\n // treat as EOF.\n if (toRead <= 0)\n return this.push(null);\n\n // the actual read.\n this.sftp.read(this.handle,\n pool,\n pool.used,\n toRead,\n this.pos,\n (er, bytesRead) => {\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n let b = null;\n\n // Now that we know how much data we have actually read, re-wind the\n // 'used' field if we can, and otherwise allow the remainder of our\n // reservation to be used as a new pool later.\n if (start + toRead === thisPool.used && thisPool === pool) {\n thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead);\n } else {\n // Round down to the next lowest multiple of 8 to ensure the new pool\n // fragment start and end positions are aligned to an 8 byte boundary.\n const alignedEnd = (start + toRead) & ~7;\n const alignedStart = roundUpToMultipleOf8(start + bytesRead);\n if (alignedEnd - alignedStart >= kMinPoolSpace)\n poolFragments.push(thisPool.slice(alignedStart, alignedEnd));\n }\n\n if (bytesRead > 0) {\n this.bytesRead += bytesRead;\n b = thisPool.slice(start, start + bytesRead);\n }\n\n // Move the pool positions, and internal position for reading.\n this.pos += bytesRead;\n\n this.push(b);\n });\n\n pool.used = roundUpToMultipleOf8(pool.used + toRead);\n};\n\nReadStream.prototype._destroy = function(err, cb) {\n if (this._opening && !Buffer.isBuffer(this.handle)) {\n this.once('open', closeStream.bind(null, this, cb, err));\n return;\n }\n\n closeStream(this, cb, err);\n this.handle = null;\n this._opening = false;\n};\n\nfunction closeStream(stream, cb, err) {\n if (!stream.handle)\n return onclose();\n\n stream.sftp.close(stream.handle, onclose);\n\n function onclose(er) {\n er = er || err;\n cb(er);\n stream.isClosed = true;\n if (!er)\n stream.emit('close');\n }\n}\n\nReadStream.prototype.close = function(cb) {\n this.destroy(null, cb);\n};\n\nObject.defineProperty(ReadStream.prototype, 'pending', {\n get() {\n return this.handle === null;\n },\n configurable: true\n});\n\n// TODO: add `concurrency` setting to allow more than one in-flight WRITE\n// request to server to improve throughput\nfunction WriteStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n options.autoDestroy = false; // Node 14 major change.\n\n WritableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'w' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesWritten = 0;\n this.isClosed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (options.encoding)\n this.setDefaultEncoding(options.encoding);\n\n // Node v6.x only\n this.on('finish', function() {\n if (this._writableState.finalCalled)\n return;\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}\ninherits(WriteStream, WritableStream);\n\nWriteStream.prototype._final = function(cb) {\n if (this.autoClose)\n this.destroy();\n cb();\n};\n\nWriteStream.prototype.open = function() {\n if (this._opening)\n return;\n\n this._opening = true;\n\n this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {\n this._opening = false;\n\n if (er) {\n this.emit('error', er);\n if (this.autoClose)\n this.destroy();\n return;\n }\n\n this.handle = handle;\n\n const tryAgain = (err) => {\n if (err) {\n // Try chmod() for sftp servers that may not support fchmod() for\n // whatever reason\n this.sftp.chmod(this.path, this.mode, (err_) => tryAgain());\n return;\n }\n\n // SFTPv3 requires absolute offsets, no matter the open flag used\n if (this.flags[0] === 'a') {\n const tryStat = (err, st) => {\n if (err) {\n // Try stat() for sftp servers that may not support fstat() for\n // whatever reason\n this.sftp.stat(this.path, (err_, st_) => {\n if (err_) {\n this.destroy();\n this.emit('error', err);\n return;\n }\n tryStat(null, st_);\n });\n return;\n }\n\n this.pos = st.size;\n this.emit('open', handle);\n this.emit('ready');\n };\n\n this.sftp.fstat(handle, tryStat);\n return;\n }\n\n this.emit('open', handle);\n this.emit('ready');\n };\n\n this.sftp.fchmod(handle, this.mode, tryAgain);\n });\n};\n\nWriteStream.prototype._write = function(data, encoding, cb) {\n if (!Buffer.isBuffer(data)) {\n const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data);\n return this.emit('error', err);\n }\n\n if (!Buffer.isBuffer(this.handle)) {\n return this.once('open', function() {\n this._write(data, encoding, cb);\n });\n }\n\n this.sftp.write(this.handle,\n data,\n 0,\n data.length,\n this.pos,\n (er, bytes) => {\n if (er) {\n if (this.autoClose)\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n cb();\n });\n\n this.pos += data.length;\n};\n\nWriteStream.prototype._writev = function(data, cb) {\n if (!Buffer.isBuffer(this.handle)) {\n return this.once('open', function() {\n this._writev(data, cb);\n });\n }\n\n const sftp = this.sftp;\n const handle = this.handle;\n let writesLeft = data.length;\n\n const onwrite = (er, bytes) => {\n if (er) {\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n if (--writesLeft === 0)\n cb();\n };\n\n // TODO: try to combine chunks to reduce number of requests to the server?\n for (let i = 0; i < data.length; ++i) {\n const chunk = data[i].chunk;\n\n sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite);\n this.pos += chunk.length;\n }\n};\n\nif (typeof WritableStream.prototype.destroy !== 'function')\n WriteStream.prototype.destroy = ReadStream.prototype.destroy;\n\nWriteStream.prototype._destroy = ReadStream.prototype._destroy;\nWriteStream.prototype.close = function(cb) {\n if (cb) {\n if (this.isClosed) {\n process.nextTick(cb);\n return;\n }\n this.on('close', cb);\n }\n\n // If we are not autoClosing, we should call\n // destroy on 'finish'.\n if (!this.autoClose)\n this.on('finish', this.destroy.bind(this));\n\n this.end();\n};\n\n// There is no shutdown() for files.\nWriteStream.prototype.destroySoon = WriteStream.prototype.end;\n\nObject.defineProperty(WriteStream.prototype, 'pending', {\n get() {\n return this.handle === null;\n },\n configurable: true\n});\n// =============================================================================\n\nmodule.exports = {\n flagsToString,\n OPEN_MODE,\n SFTP,\n Stats,\n STATUS_CODE,\n stringToFlags,\n};\n","'use strict';\n\nconst crypto = require('crypto');\n\nlet cpuInfo;\ntry {\n cpuInfo = require('cpu-features')();\n} catch {}\n\nconst { bindingAvailable, CIPHER_INFO, MAC_INFO } = require('./crypto.js');\n\nconst eddsaSupported = (() => {\n if (typeof crypto.sign === 'function'\n && typeof crypto.verify === 'function') {\n const key =\n '-----BEGIN PRIVATE KEY-----\\r\\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD'\n + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\\r\\n-----END PRIVATE KEY-----';\n const data = Buffer.from('a');\n let sig;\n let verified;\n try {\n sig = crypto.sign(null, data, key);\n verified = crypto.verify(null, data, key, sig);\n } catch {}\n return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true);\n }\n\n return false;\n})();\n\nconst curve25519Supported = (typeof crypto.diffieHellman === 'function'\n && typeof crypto.generateKeyPairSync === 'function'\n && typeof crypto.createPublicKey === 'function');\n\nconst DEFAULT_KEX = [\n // https://tools.ietf.org/html/rfc5656#section-10.1\n 'ecdh-sha2-nistp256',\n 'ecdh-sha2-nistp384',\n 'ecdh-sha2-nistp521',\n\n // https://tools.ietf.org/html/rfc4419#section-4\n 'diffie-hellman-group-exchange-sha256',\n\n // https://tools.ietf.org/html/rfc8268\n 'diffie-hellman-group14-sha256',\n 'diffie-hellman-group15-sha512',\n 'diffie-hellman-group16-sha512',\n 'diffie-hellman-group17-sha512',\n 'diffie-hellman-group18-sha512',\n];\nif (curve25519Supported) {\n DEFAULT_KEX.unshift('curve25519-sha256');\n DEFAULT_KEX.unshift('curve25519-sha256@libssh.org');\n}\nconst SUPPORTED_KEX = DEFAULT_KEX.concat([\n // https://tools.ietf.org/html/rfc4419#section-4\n 'diffie-hellman-group-exchange-sha1',\n\n 'diffie-hellman-group14-sha1', // REQUIRED\n 'diffie-hellman-group1-sha1', // REQUIRED\n]);\n\n\nconst DEFAULT_SERVER_HOST_KEY = [\n 'ecdsa-sha2-nistp256',\n 'ecdsa-sha2-nistp384',\n 'ecdsa-sha2-nistp521',\n 'rsa-sha2-512', // RFC 8332\n 'rsa-sha2-256', // RFC 8332\n 'ssh-rsa',\n];\nif (eddsaSupported)\n DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519');\nconst SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([\n 'ssh-dss',\n]);\n\n\nconst canUseCipher = (() => {\n const ciphers = crypto.getCiphers();\n return (name) => ciphers.includes(CIPHER_INFO[name].sslName);\n})();\nlet DEFAULT_CIPHER = [\n // http://tools.ietf.org/html/rfc5647\n 'aes128-gcm@openssh.com',\n 'aes256-gcm@openssh.com',\n\n // http://tools.ietf.org/html/rfc4344#section-4\n 'aes128-ctr',\n 'aes192-ctr',\n 'aes256-ctr',\n];\nif (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) {\n // We know for sure the CPU does not support AES acceleration\n if (bindingAvailable)\n DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com');\n else\n DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com');\n} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') {\n // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers\n // seem to outperform it on x86, but it seems to be faster than CTR ciphers\n DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com');\n} else {\n DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com');\n}\nDEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher);\nconst SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([\n 'aes256-cbc',\n 'aes192-cbc',\n 'aes128-cbc',\n 'blowfish-cbc',\n '3des-cbc',\n 'aes128-gcm',\n 'aes256-gcm',\n\n // http://tools.ietf.org/html/rfc4345#section-4:\n 'arcfour256',\n 'arcfour128',\n\n 'cast128-cbc',\n 'arcfour',\n].filter(canUseCipher));\n\n\nconst canUseMAC = (() => {\n const hashes = crypto.getHashes();\n return (name) => hashes.includes(MAC_INFO[name].sslName);\n})();\nconst DEFAULT_MAC = [\n 'hmac-sha2-256-etm@openssh.com',\n 'hmac-sha2-512-etm@openssh.com',\n 'hmac-sha1-etm@openssh.com',\n 'hmac-sha2-256',\n 'hmac-sha2-512',\n 'hmac-sha1',\n].filter(canUseMAC);\nconst SUPPORTED_MAC = DEFAULT_MAC.concat([\n 'hmac-md5',\n 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256\n 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512\n 'hmac-ripemd160',\n 'hmac-sha1-96', // first 96 bits of HMAC-SHA1\n 'hmac-md5-96', // first 96 bits of HMAC-MD5\n].filter(canUseMAC));\n\nconst DEFAULT_COMPRESSION = [\n 'none',\n 'zlib@openssh.com', // ZLIB (LZ77) compression, except\n // compression/decompression does not start until after\n // successful user authentication\n 'zlib', // ZLIB (LZ77) compression\n];\nconst SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([\n]);\n\n\nconst COMPAT = {\n BAD_DHGEX: 1 << 0,\n OLD_EXIT: 1 << 1,\n DYN_RPORT_BUG: 1 << 2,\n BUG_DHGEX_LARGE: 1 << 3,\n IMPLY_RSA_SHA2_SIGALGS: 1 << 4,\n};\n\nmodule.exports = {\n MESSAGE: {\n // Transport layer protocol -- generic (1-19)\n DISCONNECT: 1,\n IGNORE: 2,\n UNIMPLEMENTED: 3,\n DEBUG: 4,\n SERVICE_REQUEST: 5,\n SERVICE_ACCEPT: 6,\n EXT_INFO: 7, // RFC 8308\n\n // Transport layer protocol -- algorithm negotiation (20-29)\n KEXINIT: 20,\n NEWKEYS: 21,\n\n // Transport layer protocol -- key exchange method-specific (30-49)\n KEXDH_INIT: 30,\n KEXDH_REPLY: 31,\n\n KEXDH_GEX_GROUP: 31,\n KEXDH_GEX_INIT: 32,\n KEXDH_GEX_REPLY: 33,\n KEXDH_GEX_REQUEST: 34,\n\n KEXECDH_INIT: 30,\n KEXECDH_REPLY: 31,\n\n // User auth protocol -- generic (50-59)\n USERAUTH_REQUEST: 50,\n USERAUTH_FAILURE: 51,\n USERAUTH_SUCCESS: 52,\n USERAUTH_BANNER: 53,\n\n // User auth protocol -- user auth method-specific (60-79)\n USERAUTH_PASSWD_CHANGEREQ: 60,\n\n USERAUTH_PK_OK: 60,\n\n USERAUTH_INFO_REQUEST: 60,\n USERAUTH_INFO_RESPONSE: 61,\n\n // Connection protocol -- generic (80-89)\n GLOBAL_REQUEST: 80,\n REQUEST_SUCCESS: 81,\n REQUEST_FAILURE: 82,\n\n // Connection protocol -- channel-related (90-127)\n CHANNEL_OPEN: 90,\n CHANNEL_OPEN_CONFIRMATION: 91,\n CHANNEL_OPEN_FAILURE: 92,\n CHANNEL_WINDOW_ADJUST: 93,\n CHANNEL_DATA: 94,\n CHANNEL_EXTENDED_DATA: 95,\n CHANNEL_EOF: 96,\n CHANNEL_CLOSE: 97,\n CHANNEL_REQUEST: 98,\n CHANNEL_SUCCESS: 99,\n CHANNEL_FAILURE: 100\n\n // Reserved for client protocols (128-191)\n\n // Local extensions (192-155)\n },\n DISCONNECT_REASON: {\n HOST_NOT_ALLOWED_TO_CONNECT: 1,\n PROTOCOL_ERROR: 2,\n KEY_EXCHANGE_FAILED: 3,\n RESERVED: 4,\n MAC_ERROR: 5,\n COMPRESSION_ERROR: 6,\n SERVICE_NOT_AVAILABLE: 7,\n PROTOCOL_VERSION_NOT_SUPPORTED: 8,\n HOST_KEY_NOT_VERIFIABLE: 9,\n CONNECTION_LOST: 10,\n BY_APPLICATION: 11,\n TOO_MANY_CONNECTIONS: 12,\n AUTH_CANCELED_BY_USER: 13,\n NO_MORE_AUTH_METHODS_AVAILABLE: 14,\n ILLEGAL_USER_NAME: 15,\n },\n DISCONNECT_REASON_STR: undefined,\n CHANNEL_OPEN_FAILURE: {\n ADMINISTRATIVELY_PROHIBITED: 1,\n CONNECT_FAILED: 2,\n UNKNOWN_CHANNEL_TYPE: 3,\n RESOURCE_SHORTAGE: 4\n },\n TERMINAL_MODE: {\n TTY_OP_END: 0, // Indicates end of options.\n VINTR: 1, // Interrupt character; 255 if none. Similarly for the\n // other characters. Not all of these characters are\n // supported on all systems.\n VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX\n // systems).\n VERASE: 3, // Erase the character to left of the cursor.\n VKILL: 4, // Kill the current input line.\n VEOF: 5, // End-of-file character (sends EOF from the\n // terminal).\n VEOL: 6, // End-of-line character in addition to carriage\n // return and/or linefeed.\n VEOL2: 7, // Additional end-of-line character.\n VSTART: 8, // Continues paused output (normally control-Q).\n VSTOP: 9, // Pauses output (normally control-S).\n VSUSP: 10, // Suspends the current program.\n VDSUSP: 11, // Another suspend character.\n VREPRINT: 12, // Reprints the current input line.\n VWERASE: 13, // Erases a word left of cursor.\n VLNEXT: 14, // Enter the next character typed literally, even if\n // it is a special character\n VFLUSH: 15, // Character to flush output.\n VSWTCH: 16, // Switch to a different shell layer.\n VSTATUS: 17, // Prints system status line (load, command, pid,\n // etc).\n VDISCARD: 18, // Toggles the flushing of terminal output.\n IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0\n // if this flag is FALSE, and 1 if it is TRUE.\n PARMRK: 31, // Mark parity and framing errors.\n INPCK: 32, // Enable checking of parity errors.\n ISTRIP: 33, // Strip 8th bit off characters.\n INLCR: 34, // Map NL into CR on input.\n IGNCR: 35, // Ignore CR on input.\n ICRNL: 36, // Map CR to NL on input.\n IUCLC: 37, // Translate uppercase characters to lowercase.\n IXON: 38, // Enable output flow control.\n IXANY: 39, // Any char will restart after stop.\n IXOFF: 40, // Enable input flow control.\n IMAXBEL: 41, // Ring bell on input queue full.\n ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP.\n ICANON: 51, // Canonicalize input lines.\n XCASE: 52, // Enable input and output of uppercase characters by\n // preceding their lowercase equivalents with \"\\\".\n ECHO: 53, // Enable echoing.\n ECHOE: 54, // Visually erase chars.\n ECHOK: 55, // Kill character discards current line.\n ECHONL: 56, // Echo NL even if ECHO is off.\n NOFLSH: 57, // Don't flush after interrupt.\n TOSTOP: 58, // Stop background jobs from output.\n IEXTEN: 59, // Enable extensions.\n ECHOCTL: 60, // Echo control characters as ^(Char).\n ECHOKE: 61, // Visual erase for line kill.\n PENDIN: 62, // Retype pending input.\n OPOST: 70, // Enable output processing.\n OLCUC: 71, // Convert lowercase to uppercase.\n ONLCR: 72, // Map NL to CR-NL.\n OCRNL: 73, // Translate carriage return to newline (output).\n ONOCR: 74, // Translate newline to carriage return-newline\n // (output).\n ONLRET: 75, // Newline performs a carriage return (output).\n CS7: 90, // 7 bit mode.\n CS8: 91, // 8 bit mode.\n PARENB: 92, // Parity enable.\n PARODD: 93, // Odd parity, else even.\n TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second.\n TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second.\n },\n CHANNEL_EXTENDED_DATATYPE: {\n STDERR: 1,\n },\n\n SIGNALS: [\n 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1',\n 'USR2', 'KILL', 'PIPE'\n ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}),\n\n COMPAT,\n COMPAT_CHECKS: [\n [ 'Cisco-1.25', COMPAT.BAD_DHGEX ],\n [ /^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE ],\n [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations\n [ /^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG ],\n [ /^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS ],\n ],\n\n // KEX proposal-related\n DEFAULT_KEX,\n SUPPORTED_KEX,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER,\n DEFAULT_MAC,\n SUPPORTED_MAC,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION,\n\n curve25519Supported,\n eddsaSupported,\n};\n\nmodule.exports.DISCONNECT_REASON_BY_VALUE =\n Array.from(Object.entries(module.exports.DISCONNECT_REASON))\n .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {});\n","// TODO:\n// * make max packet size configurable\n// * if decompression is enabled, use `._packet` in decipher instances as\n// input to (sync) zlib inflater with appropriate offset and length to\n// avoid an additional copy of payload data before inflation\n// * factor decompression status into packet length checks\n'use strict';\n\nconst {\n createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual\n} = require('crypto');\n\nconst { readUInt32BE, writeUInt32BE } = require('./utils.js');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst MAX_SEQNO = 2 ** 32 - 1;\nconst EMPTY_BUFFER = Buffer.alloc(0);\nconst BUF_INT = Buffer.alloc(4);\nconst DISCARD_CACHE = new Map();\nconst MAX_PACKET_SIZE = 35000;\n\nlet binding;\nlet AESGCMCipher;\nlet ChaChaPolyCipher;\nlet GenericCipher;\nlet AESGCMDecipher;\nlet ChaChaPolyDecipher;\nlet GenericDecipher;\ntry {\n binding = require('./crypto/build/Release/sshcrypto.node');\n ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher,\n AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding);\n} catch {}\n\nconst CIPHER_STREAM = 1 << 0;\nconst CIPHER_INFO = (() => {\n function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) {\n return {\n sslName,\n blockLen,\n keyLen,\n ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM)\n ? ivLen\n : blockLen),\n authLen,\n discardLen,\n stream: !!(flags & CIPHER_STREAM),\n };\n }\n\n return {\n 'chacha20-poly1305@openssh.com':\n info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM),\n\n 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM),\n 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM),\n 'aes128-gcm@openssh.com':\n info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM),\n 'aes256-gcm@openssh.com':\n info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM),\n\n 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0),\n 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0),\n 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0),\n 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0),\n '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0),\n 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0),\n 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0),\n 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0),\n\n 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM),\n 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM),\n 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM),\n '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM),\n 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM),\n 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM),\n\n /* The \"arcfour128\" algorithm is the RC4 cipher, as described in\n [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream\n generated by the cipher MUST be discarded, and the first byte of the\n first encrypted packet MUST be encrypted using the 1537th byte of\n keystream.\n\n -- http://tools.ietf.org/html/rfc4345#section-4 */\n 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM),\n 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM),\n };\n})();\n\nconst MAC_INFO = (() => {\n function info(sslName, len, actualLen, isETM) {\n return {\n sslName,\n len,\n actualLen,\n isETM,\n };\n }\n\n return {\n 'hmac-md5': info('md5', 16, 16, false),\n 'hmac-md5-96': info('md5', 16, 12, false),\n 'hmac-ripemd160': info('ripemd160', 20, 20, false),\n 'hmac-sha1': info('sha1', 20, 20, false),\n 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true),\n 'hmac-sha1-96': info('sha1', 20, 12, false),\n 'hmac-sha2-256': info('sha256', 32, 32, false),\n 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true),\n 'hmac-sha2-256-96': info('sha256', 32, 12, false),\n 'hmac-sha2-512': info('sha512', 64, 64, false),\n 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true),\n 'hmac-sha2-512-96': info('sha512', 64, 12, false),\n };\n})();\n\n\n// Should only_be used during the initial handshake\nclass NullCipher {\n constructor(seqno, onWrite) {\n this.outSeqno = seqno;\n this._onWrite = onWrite;\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - (pktLen & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nconst POLY1305_ZEROS = Buffer.alloc(32);\nconst POLY1305_OUT_COMPUTE = Buffer.alloc(16);\nlet POLY1305_WASM_MODULE;\nlet POLY1305_RESULT_MALLOC;\nlet poly1305_auth;\nclass ChaChaPolyCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encKeyMain = enc.cipherKey.slice(0, 32);\n this._encKeyPktLen = enc.cipherKey.slice(32);\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - ((pktLen - 4) & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Generate Poly1305 key\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12);\n const polyKey =\n createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE)\n .update(POLY1305_ZEROS);\n\n // Encrypt packet length\n const pktLenEnc =\n createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE)\n .update(packet.slice(0, 4));\n this._onWrite(pktLenEnc);\n\n // Encrypt rest of packet\n POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian)\n const payloadEnc =\n createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE)\n .update(packet.slice(4));\n this._onWrite(payloadEnc);\n\n // Calculate Poly1305 MAC\n poly1305_auth(POLY1305_RESULT_MALLOC,\n pktLenEnc,\n pktLenEnc.length,\n payloadEnc,\n payloadEnc.length,\n polyKey);\n const mac = Buffer.allocUnsafe(16);\n mac.set(\n new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer,\n POLY1305_RESULT_MALLOC,\n 16),\n 0\n );\n this._onWrite(mac);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass ChaChaPolyCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._instance = new ChaChaPolyCipher(enc.cipherKey);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 8 - ((pktLen - 4) & (8 - 1));\n if (padLen < 4)\n padLen += 8;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet, this.outSeqno);\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass AESGCMCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encSSLName = enc.cipherInfo.sslName;\n this._encKey = enc.cipherKey;\n this._encIV = enc.cipherIV;\n this._dead = false;\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 16 - ((pktLen - 4) & (16 - 1));\n if (padLen < 4)\n padLen += 16;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV);\n cipher.setAutoPadding(false);\n\n const lenData = packet.slice(0, 4);\n cipher.setAAD(lenData);\n this._onWrite(lenData);\n\n // Encrypt pad length, payload, and padding\n const encrypted = cipher.update(packet.slice(4));\n this._onWrite(encrypted);\n const final = cipher.final();\n // XXX: final.length === 0 always?\n if (final.length)\n this._onWrite(final);\n\n // Generate MAC\n const tag = cipher.getAuthTag();\n this._onWrite(tag);\n\n // Increment counter in IV by 1 for next packet\n ivIncrement(this._encIV);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass AESGCMCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._instance = new AESGCMCipher(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n let pktLen = 4 + 1 + payloadLen;\n let padLen = 16 - ((pktLen - 4) & (16 - 1));\n if (padLen < 4)\n padLen += 16;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet);\n\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass GenericCipherNative {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encBlockLen = enc.cipherInfo.blockLen;\n this._cipherInstance = createCipheriv(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV);\n this._macSSLName = enc.macInfo.sslName;\n this._macKey = enc.macKey;\n this._macActualLen = enc.macInfo.actualLen;\n this._macETM = enc.macInfo.isETM;\n this._aadLen = (this._macETM ? 4 : 0);\n this._dead = false;\n\n const discardLen = enc.cipherInfo.discardLen;\n if (discardLen) {\n let discard = DISCARD_CACHE.get(discardLen);\n if (discard === undefined) {\n discard = Buffer.alloc(discardLen);\n DISCARD_CACHE.set(discardLen, discard);\n }\n this._cipherInstance.update(discard);\n }\n }\n free() {\n this._dead = true;\n }\n allocPacket(payloadLen) {\n const blockLen = this._encBlockLen;\n\n let pktLen = 4 + 1 + payloadLen;\n let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1));\n if (padLen < 4)\n padLen += blockLen;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n let mac;\n if (this._macETM) {\n // Encrypt pad length, payload, and padding\n const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4);\n const encrypted = this._cipherInstance.update(\n new Uint8Array(packet.buffer,\n packet.byteOffset + 4,\n packet.length - 4)\n );\n\n this._onWrite(lenBytes);\n this._onWrite(encrypted);\n\n // TODO: look into storing seqno as 4-byte buffer and incrementing like we\n // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time\n mac = createHmac(this._macSSLName, this._macKey);\n writeUInt32BE(BUF_INT, this.outSeqno, 0);\n mac.update(BUF_INT);\n mac.update(lenBytes);\n mac.update(encrypted);\n } else {\n // Encrypt length field, pad length, payload, and padding\n const encrypted = this._cipherInstance.update(packet);\n this._onWrite(encrypted);\n\n // TODO: look into storing seqno as 4-byte buffer and incrementing like we\n // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time\n mac = createHmac(this._macSSLName, this._macKey);\n writeUInt32BE(BUF_INT, this.outSeqno, 0);\n mac.update(BUF_INT);\n mac.update(packet);\n }\n\n let digest = mac.digest();\n if (digest.length > this._macActualLen)\n digest = digest.slice(0, this._macActualLen);\n this._onWrite(digest);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\nclass GenericCipherBinding {\n constructor(config) {\n const enc = config.outbound;\n this.outSeqno = enc.seqno;\n this._onWrite = enc.onWrite;\n this._encBlockLen = enc.cipherInfo.blockLen;\n this._macLen = enc.macInfo.len;\n this._macActualLen = enc.macInfo.actualLen;\n this._aadLen = (enc.macInfo.isETM ? 4 : 0);\n this._instance = new GenericCipher(enc.cipherInfo.sslName,\n enc.cipherKey,\n enc.cipherIV,\n enc.macInfo.sslName,\n enc.macKey,\n enc.macInfo.isETM);\n this._dead = false;\n }\n free() {\n this._dead = true;\n this._instance.free();\n }\n allocPacket(payloadLen) {\n const blockLen = this._encBlockLen;\n\n let pktLen = 4 + 1 + payloadLen;\n let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1));\n if (padLen < 4)\n padLen += blockLen;\n pktLen += padLen;\n\n const packet = Buffer.allocUnsafe(pktLen + this._macLen);\n\n writeUInt32BE(packet, pktLen - 4, 0);\n packet[4] = padLen;\n\n randomFillSync(packet, 5 + payloadLen, padLen);\n\n return packet;\n }\n encrypt(packet) {\n // `packet` === unencrypted packet\n\n if (this._dead)\n return;\n\n // Encrypts in-place\n this._instance.encrypt(packet, this.outSeqno);\n\n if (this._macActualLen < this._macLen) {\n packet = new FastBuffer(packet.buffer,\n packet.byteOffset,\n (packet.length\n - (this._macLen - this._macActualLen)));\n }\n this._onWrite(packet);\n\n this.outSeqno = (this.outSeqno + 1) >>> 0;\n }\n}\n\n\nclass NullDecipher {\n constructor(seqno, onPayload) {\n this.inSeqno = seqno;\n this._onPayload = onPayload;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n while (p < dataLen) {\n // Read packet length\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n\n if (this._lenBytes < 4)\n return;\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (4 + this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._packetPos < this._len) {\n const nb = Math.min(this._len - this._packetPos, dataLen - p);\n let chunk;\n if (p !== 0 || nb !== dataLen)\n chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n chunk = data;\n if (nb === this._len) {\n this._packet = chunk;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(chunk, this._packetPos);\n }\n p += nb;\n this._packetPos += nb;\n if (this._packetPos < this._len)\n return;\n }\n\n const payload = (!this._packet\n ? EMPTY_BUFFER\n : new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length\n - this._packet[0] - 1));\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass ChaChaPolyDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decKeyMain = dec.decipherKey.slice(0, 32);\n this._decKeyPktLen = dec.decipherKey.slice(32);\n this._len = 0;\n this._lenBuf = Buffer.alloc(4);\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(16);\n this._calcMac = Buffer.allocUnsafe(16);\n this._macPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length\n if (this._lenPos < 4) {\n let nb = Math.min(4 - this._lenPos, dataLen - p);\n while (nb--)\n this._lenBuf[this._lenPos++] = data[p++];\n if (this._lenPos < 4)\n return;\n\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);\n\n const decLenBytes =\n createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE)\n .update(this._lenBuf);\n this._len = readUInt32BE(decLenBytes, 0);\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read Poly1305 MAC\n {\n const nb = Math.min(16 - this._macPos, dataLen - p);\n // TODO: avoid copying if entire MAC is in current chunk\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < 16)\n return;\n }\n\n // Generate Poly1305 key\n POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)\n writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);\n const polyKey =\n createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE)\n .update(POLY1305_ZEROS);\n\n // Calculate and compare Poly1305 MACs\n poly1305_auth(POLY1305_RESULT_MALLOC,\n this._lenBuf,\n 4,\n this._packet,\n this._packet.length,\n polyKey);\n\n this._calcMac.set(\n new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer,\n POLY1305_RESULT_MALLOC,\n 16),\n 0\n );\n if (!timingSafeEqual(this._calcMac, this._mac))\n throw new Error('Invalid MAC');\n\n // Decrypt packet\n POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian)\n const packet =\n createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE)\n .update(this._packet);\n\n const payload = new FastBuffer(packet.buffer,\n packet.byteOffset + 1,\n packet.length - packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass ChaChaPolyDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new ChaChaPolyDecipher(dec.decipherKey);\n this._len = 0;\n this._lenBuf = Buffer.alloc(4);\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(16);\n this._macPos = 0;\n }\n free() {\n this._instance.free();\n }\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length\n if (this._lenPos < 4) {\n let nb = Math.min(4 - this._lenPos, dataLen - p);\n while (nb--)\n this._lenBuf[this._lenPos++] = data[p++];\n if (this._lenPos < 4)\n return;\n\n this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno);\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 8\n || (this._len & 7) !== 0) {\n throw new Error('Bad packet length');\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read Poly1305 MAC\n {\n const nb = Math.min(16 - this._macPos, dataLen - p);\n // TODO: avoid copying if entire MAC is in current chunk\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < 16)\n return;\n }\n\n this._instance.decrypt(this._packet, this._mac, this.inSeqno);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenPos = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass AESGCMDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decipherInstance = null;\n this._decipherSSLName = dec.decipherInfo.sslName;\n this._decipherKey = dec.decipherKey;\n this._decipherIV = dec.decipherIV;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._tag = Buffer.allocUnsafe(16);\n this._tagPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length (unencrypted, but AAD)\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n if (this._lenBytes < 4)\n return;\n\n if ((this._len + 20) > MAX_PACKET_SIZE\n || this._len < 16\n || (this._len & 15) !== 0) {\n throw new Error('Bad packet length');\n }\n\n this._decipherInstance = createDecipheriv(\n this._decipherSSLName,\n this._decipherKey,\n this._decipherIV\n );\n this._decipherInstance.setAutoPadding(false);\n this._decipherInstance.setAAD(intToBytes(this._len));\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let decrypted;\n if (p !== 0 || nb !== dataLen) {\n decrypted = this._decipherInstance.update(\n new Uint8Array(data.buffer, data.byteOffset + p, nb)\n );\n } else {\n decrypted = this._decipherInstance.update(data);\n }\n if (decrypted.length) {\n if (nb === this._len) {\n this._packet = decrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(decrypted, this._packetPos);\n }\n this._packetPos += decrypted.length;\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read authentication tag\n {\n const nb = Math.min(16 - this._tagPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._tag.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._tagPos\n );\n } else {\n this._tag.set(data, this._tagPos);\n }\n p += nb;\n this._tagPos += nb;\n if (this._tagPos < 16)\n return;\n }\n\n {\n // Verify authentication tag\n this._decipherInstance.setAuthTag(this._tag);\n\n const decrypted = this._decipherInstance.final();\n\n // XXX: this should never output any data since stream ciphers always\n // return data from .update() and block ciphers must end on a multiple\n // of the block length, which would have caused an exception to be\n // thrown if the total input was not...\n if (decrypted.length) {\n if (this._packet)\n this._packet.set(decrypted, this._packetPos);\n else\n this._packet = decrypted;\n }\n }\n\n const payload = (!this._packet\n ? EMPTY_BUFFER\n : new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length\n - this._packet[0] - 1));\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n ivIncrement(this._decipherIV);\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._tagPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass AESGCMDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new AESGCMDecipher(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV);\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._pktLen = 0;\n this._tag = Buffer.allocUnsafe(16);\n this._tagPos = 0;\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read packet length (unencrypted, but AAD)\n if (this._lenBytes < 4) {\n let nb = Math.min(4 - this._lenBytes, dataLen - p);\n this._lenBytes += nb;\n while (nb--)\n this._len = (this._len << 8) + data[p++];\n if (this._lenBytes < 4)\n return;\n\n if ((this._len + 20) > MAX_PACKET_SIZE\n || this._len < 16\n || (this._len & 15) !== 0) {\n throw new Error(`Bad packet length: ${this._len}`);\n }\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n if (p >= dataLen)\n return;\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read authentication tag\n {\n const nb = Math.min(16 - this._tagPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._tag.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._tagPos\n );\n } else {\n this._tag.set(data, this._tagPos);\n }\n p += nb;\n this._tagPos += nb;\n if (this._tagPos < 16)\n return;\n }\n\n this._instance.decrypt(this._packet, this._len, this._tag);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._len = 0;\n this._lenBytes = 0;\n this._packet = null;\n this._pktLen = 0;\n this._tagPos = 0;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\n// TODO: test incremental .update()s vs. copying to _packet and doing a single\n// .update() after entire packet read -- a single .update() would allow\n// verifying MAC before decrypting for ETM MACs\nclass GenericDecipherNative {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV);\n this._decipherInstance.setAutoPadding(false);\n this._block = Buffer.allocUnsafe(\n dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen\n );\n this._blockSize = dec.decipherInfo.blockLen;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen);\n this._macPos = 0;\n this._macSSLName = dec.macInfo.sslName;\n this._macKey = dec.macKey;\n this._macActualLen = dec.macInfo.actualLen;\n this._macETM = dec.macInfo.isETM;\n this._macInstance = null;\n\n const discardLen = dec.decipherInfo.discardLen;\n if (discardLen) {\n let discard = DISCARD_CACHE.get(discardLen);\n if (discard === undefined) {\n discard = Buffer.alloc(discardLen);\n DISCARD_CACHE.set(discardLen, discard);\n }\n this._decipherInstance.update(discard);\n }\n }\n free() {}\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read first encrypted block\n if (this._blockPos < this._block.length) {\n const nb = Math.min(this._block.length - this._blockPos, dataLen - p);\n if (p !== 0 || nb !== dataLen || nb < data.length) {\n this._block.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._blockPos\n );\n } else {\n this._block.set(data, this._blockPos);\n }\n\n p += nb;\n this._blockPos += nb;\n if (this._blockPos < this._block.length)\n return;\n\n let decrypted;\n let need;\n if (this._macETM) {\n this._len = need = readUInt32BE(this._block, 0);\n } else {\n // Decrypt first block to get packet length\n decrypted = this._decipherInstance.update(this._block);\n this._len = readUInt32BE(decrypted, 0);\n need = 4 + this._len - this._blockSize;\n }\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 5\n || (need & (this._blockSize - 1)) !== 0) {\n throw new Error('Bad packet length');\n }\n\n // Create MAC up front to calculate in parallel with decryption\n this._macInstance = createHmac(this._macSSLName, this._macKey);\n\n writeUInt32BE(BUF_INT, this.inSeqno, 0);\n this._macInstance.update(BUF_INT);\n if (this._macETM) {\n this._macInstance.update(this._block);\n } else {\n this._macInstance.update(new Uint8Array(decrypted.buffer,\n decrypted.byteOffset,\n 4));\n this._pktLen = decrypted.length - 4;\n this._packetPos = this._pktLen;\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(\n new Uint8Array(decrypted.buffer,\n decrypted.byteOffset + 4,\n this._packetPos),\n 0\n );\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (this._macETM)\n this._macInstance.update(encrypted);\n const decrypted = this._decipherInstance.update(encrypted);\n if (decrypted.length) {\n if (nb === this._len) {\n this._packet = decrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(decrypted, this._packetPos);\n }\n this._packetPos += decrypted.length;\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read MAC\n {\n const nb = Math.min(this._macActualLen - this._macPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < this._macActualLen)\n return;\n }\n\n // Verify MAC\n if (!this._macETM)\n this._macInstance.update(this._packet);\n let calculated = this._macInstance.digest();\n if (this._macActualLen < calculated.length) {\n calculated = new Uint8Array(calculated.buffer,\n calculated.byteOffset,\n this._macActualLen);\n }\n if (!timingSafeEquals(calculated, this._mac))\n throw new Error('Invalid MAC');\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._packetPos = 0;\n this._pktLen = 0;\n this._macPos = 0;\n this._macInstance = null;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\nclass GenericDecipherBinding {\n constructor(config) {\n const dec = config.inbound;\n this.inSeqno = dec.seqno;\n this._onPayload = dec.onPayload;\n this._instance = new GenericDecipher(dec.decipherInfo.sslName,\n dec.decipherKey,\n dec.decipherIV,\n dec.macInfo.sslName,\n dec.macKey,\n dec.macInfo.isETM,\n dec.macInfo.actualLen);\n this._block = Buffer.allocUnsafe(\n dec.macInfo.isETM || dec.decipherInfo.stream\n ? 4\n : dec.decipherInfo.blockLen\n );\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._pktLen = 0;\n this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen);\n this._macPos = 0;\n this._macActualLen = dec.macInfo.actualLen;\n this._macETM = dec.macInfo.isETM;\n }\n free() {\n this._instance.free();\n }\n decrypt(data, p, dataLen) {\n // `data` === encrypted data\n\n while (p < dataLen) {\n // Read first encrypted block\n if (this._blockPos < this._block.length) {\n const nb = Math.min(this._block.length - this._blockPos, dataLen - p);\n if (p !== 0 || nb !== dataLen || nb < data.length) {\n this._block.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._blockPos\n );\n } else {\n this._block.set(data, this._blockPos);\n }\n\n p += nb;\n this._blockPos += nb;\n if (this._blockPos < this._block.length)\n return;\n\n let need;\n if (this._macETM) {\n this._len = need = readUInt32BE(this._block, 0);\n } else {\n // Decrypt first block to get packet length\n this._instance.decryptBlock(this._block);\n this._len = readUInt32BE(this._block, 0);\n need = 4 + this._len - this._block.length;\n }\n\n if (this._len > MAX_PACKET_SIZE\n || this._len < 5\n || (need & (this._block.length - 1)) !== 0) {\n throw new Error('Bad packet length');\n }\n\n if (!this._macETM) {\n this._pktLen = (this._block.length - 4);\n if (this._pktLen) {\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(\n new Uint8Array(this._block.buffer,\n this._block.byteOffset + 4,\n this._pktLen),\n 0\n );\n }\n }\n\n if (p >= dataLen)\n return;\n }\n\n // Read padding length, payload, and padding\n if (this._pktLen < this._len) {\n const nb = Math.min(this._len - this._pktLen, dataLen - p);\n let encrypted;\n if (p !== 0 || nb !== dataLen)\n encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);\n else\n encrypted = data;\n if (nb === this._len) {\n this._packet = encrypted;\n } else {\n if (!this._packet)\n this._packet = Buffer.allocUnsafe(this._len);\n this._packet.set(encrypted, this._pktLen);\n }\n p += nb;\n this._pktLen += nb;\n if (this._pktLen < this._len || p >= dataLen)\n return;\n }\n\n // Read MAC\n {\n const nb = Math.min(this._macActualLen - this._macPos, dataLen - p);\n if (p !== 0 || nb !== dataLen) {\n this._mac.set(\n new Uint8Array(data.buffer, data.byteOffset + p, nb),\n this._macPos\n );\n } else {\n this._mac.set(data, this._macPos);\n }\n p += nb;\n this._macPos += nb;\n if (this._macPos < this._macActualLen)\n return;\n }\n\n // Decrypt and verify MAC\n this._instance.decrypt(this._packet,\n this.inSeqno,\n this._block,\n this._mac);\n\n const payload = new FastBuffer(this._packet.buffer,\n this._packet.byteOffset + 1,\n this._packet.length - this._packet[0] - 1);\n\n // Prepare for next packet\n this.inSeqno = (this.inSeqno + 1) >>> 0;\n this._blockPos = 0;\n this._len = 0;\n this._packet = null;\n this._pktLen = 0;\n this._macPos = 0;\n this._macInstance = null;\n\n {\n const ret = this._onPayload(payload);\n if (ret !== undefined)\n return (ret === false ? p : ret);\n }\n }\n }\n}\n\n// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV\nfunction ivIncrement(iv) {\n // eslint-disable-next-line no-unused-expressions\n ++iv[11] >>> 8\n && ++iv[10] >>> 8\n && ++iv[9] >>> 8\n && ++iv[8] >>> 8\n && ++iv[7] >>> 8\n && ++iv[6] >>> 8\n && ++iv[5] >>> 8\n && ++iv[4] >>> 8;\n}\n\nconst intToBytes = (() => {\n const ret = Buffer.alloc(4);\n return (n) => {\n ret[0] = (n >>> 24);\n ret[1] = (n >>> 16);\n ret[2] = (n >>> 8);\n ret[3] = n;\n return ret;\n };\n})();\n\nfunction timingSafeEquals(a, b) {\n if (a.length !== b.length) {\n timingSafeEqual(a, a);\n return false;\n }\n return timingSafeEqual(a, b);\n}\n\nfunction createCipher(config) {\n if (typeof config !== 'object' || config === null)\n throw new Error('Invalid config');\n\n if (typeof config.outbound !== 'object' || config.outbound === null)\n throw new Error('Invalid outbound');\n\n const outbound = config.outbound;\n\n if (typeof outbound.onWrite !== 'function')\n throw new Error('Invalid outbound.onWrite');\n\n if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null)\n throw new Error('Invalid outbound.cipherInfo');\n\n if (!Buffer.isBuffer(outbound.cipherKey)\n || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) {\n throw new Error('Invalid outbound.cipherKey');\n }\n\n if (outbound.cipherInfo.ivLen\n && (!Buffer.isBuffer(outbound.cipherIV)\n || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) {\n throw new Error('Invalid outbound.cipherIV');\n }\n\n if (typeof outbound.seqno !== 'number'\n || outbound.seqno < 0\n || outbound.seqno > MAX_SEQNO) {\n throw new Error('Invalid outbound.seqno');\n }\n\n const forceNative = !!outbound.forceNative;\n\n switch (outbound.cipherInfo.sslName) {\n case 'aes-128-gcm':\n case 'aes-256-gcm':\n return (AESGCMCipher && !forceNative\n ? new AESGCMCipherBinding(config)\n : new AESGCMCipherNative(config));\n case 'chacha20':\n return (ChaChaPolyCipher && !forceNative\n ? new ChaChaPolyCipherBinding(config)\n : new ChaChaPolyCipherNative(config));\n default: {\n if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null)\n throw new Error('Invalid outbound.macInfo');\n if (!Buffer.isBuffer(outbound.macKey)\n || outbound.macKey.length !== outbound.macInfo.len) {\n throw new Error('Invalid outbound.macKey');\n }\n return (GenericCipher && !forceNative\n ? new GenericCipherBinding(config)\n : new GenericCipherNative(config));\n }\n }\n}\n\nfunction createDecipher(config) {\n if (typeof config !== 'object' || config === null)\n throw new Error('Invalid config');\n\n if (typeof config.inbound !== 'object' || config.inbound === null)\n throw new Error('Invalid inbound');\n\n const inbound = config.inbound;\n\n if (typeof inbound.onPayload !== 'function')\n throw new Error('Invalid inbound.onPayload');\n\n if (typeof inbound.decipherInfo !== 'object'\n || inbound.decipherInfo === null) {\n throw new Error('Invalid inbound.decipherInfo');\n }\n\n if (!Buffer.isBuffer(inbound.decipherKey)\n || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) {\n throw new Error('Invalid inbound.decipherKey');\n }\n\n if (inbound.decipherInfo.ivLen\n && (!Buffer.isBuffer(inbound.decipherIV)\n || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) {\n throw new Error('Invalid inbound.decipherIV');\n }\n\n if (typeof inbound.seqno !== 'number'\n || inbound.seqno < 0\n || inbound.seqno > MAX_SEQNO) {\n throw new Error('Invalid inbound.seqno');\n }\n\n const forceNative = !!inbound.forceNative;\n\n switch (inbound.decipherInfo.sslName) {\n case 'aes-128-gcm':\n case 'aes-256-gcm':\n return (AESGCMDecipher && !forceNative\n ? new AESGCMDecipherBinding(config)\n : new AESGCMDecipherNative(config));\n case 'chacha20':\n return (ChaChaPolyDecipher && !forceNative\n ? new ChaChaPolyDecipherBinding(config)\n : new ChaChaPolyDecipherNative(config));\n default: {\n if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null)\n throw new Error('Invalid inbound.macInfo');\n if (!Buffer.isBuffer(inbound.macKey)\n || inbound.macKey.length !== inbound.macInfo.len) {\n throw new Error('Invalid inbound.macKey');\n }\n return (GenericDecipher && !forceNative\n ? new GenericDecipherBinding(config)\n : new GenericDecipherNative(config));\n }\n }\n}\n\nmodule.exports = {\n CIPHER_INFO,\n MAC_INFO,\n bindingAvailable: !!binding,\n init: (() => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n POLY1305_WASM_MODULE = await require('./crypto/poly1305.js')();\n POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16);\n poly1305_auth = POLY1305_WASM_MODULE.cwrap(\n 'poly1305_auth',\n null,\n ['number', 'array', 'number', 'array', 'number', 'array']\n );\n } catch (ex) {\n return reject(ex);\n }\n resolve();\n });\n })(),\n\n NullCipher,\n createCipher,\n NullDecipher,\n createDecipher,\n};\n","\nvar createPoly1305 = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;\n return (\nfunction(createPoly1305) {\n createPoly1305 = createPoly1305 || {};\n\n\nvar b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x=\"object\"===typeof window,y=\"function\"===typeof importScripts,z=\"object\"===typeof process&&\"object\"===typeof process.versions&&\"string\"===typeof process.versions.node,B=\"\",C,D,E,F,G;\nif(z)B=y?require(\"path\").dirname(B)+\"/\":__dirname+\"/\",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=require(\"fs\"));G||(G=require(\"path\"));a=G.normalize(a);return F.readFileSync(a,c?null:\"utf8\")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=require(\"fs\"));G||(G=require(\"path\"));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]=\n0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g=\"\";else g=\"boolean\"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea=\"undefined\"!==typeof TextDecoder?new TextDecoder(\"utf8\"):void 0,ha,Q,P;\nfunction ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={};\nfunction K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError(\"abort(\"+a+\"). Build with -s ASSERTIONS=1 for more info.\");r(a);throw a;}var V=\"data:application/octet-stream;base64,\",W;W=\"data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==\";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw\"both async and sync fetching of the wasm failed\";}catch(d){K(d)}}\nfunction qa(){if(!J&&(x||y)){if(\"function\"===typeof fetch&&!W.startsWith(\"file://\"))return fetch(W,{credentials:\"same-origin\"}).then(function(a){if(!a.ok)throw\"failed to load wasm binary file at '\"+W+\"'\";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})}\nfunction X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}};\n(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I(\"failed to asynchronously prepare wasm: \"+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e,\na)}catch(f){return I(\"Module.instantiateWasm callback failed with error: \"+f),!1}(function(){return J||\"function\"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith(\"file://\")||\"function\"!==typeof fetch?d(c):fetch(W,{credentials:\"same-origin\"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I(\"wasm streaming compile failed: \"+l);I(\"falling back to ArrayBuffer instantiation\");return d(c)})})})().catch(r);return{}})();\nb.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)};\nb._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return\"number\"===l});return\"string\"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)};\nfunction Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for(\"function\"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 {\n // eslint-disable-next-line prefer-const\n for (let [type, handler] of Object.entries(handlers)) {\n type = +type;\n if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length)\n MESSAGE_HANDLERS[type] = handler;\n }\n});\n\nmodule.exports = MESSAGE_HANDLERS;\n","'use strict';\n\nconst {\n bufferSlice,\n bufferParser,\n doFatalError,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst {\n CHANNEL_OPEN_FAILURE,\n COMPAT,\n MESSAGE,\n TERMINAL_MODE,\n} = require('./constants.js');\n\nconst {\n parseKey,\n} = require('./keyParser.js');\n\nconst TERMINAL_MODE_BY_VALUE =\n Array.from(Object.entries(TERMINAL_MODE))\n .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});\n\nmodule.exports = {\n // Transport layer protocol ==================================================\n [MESSAGE.DISCONNECT]: (self, payload) => {\n /*\n byte SSH_MSG_DISCONNECT\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding\n string language tag\n */\n bufferParser.init(payload, 1);\n const reason = bufferParser.readUInt32BE();\n const desc = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed DISCONNECT packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: Received DISCONNECT (${reason}, \"${desc}\")`\n );\n\n const handler = self._handlers.DISCONNECT;\n handler && handler(self, reason, desc);\n },\n [MESSAGE.IGNORE]: (self, payload) => {\n /*\n byte SSH_MSG_IGNORE\n string data\n */\n self._debug && self._debug('Inbound: Received IGNORE');\n },\n [MESSAGE.UNIMPLEMENTED]: (self, payload) => {\n /*\n byte SSH_MSG_UNIMPLEMENTED\n uint32 packet sequence number of rejected message\n */\n bufferParser.init(payload, 1);\n const seqno = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (seqno === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed UNIMPLEMENTED packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`);\n },\n [MESSAGE.DEBUG]: (self, payload) => {\n /*\n byte SSH_MSG_DEBUG\n boolean always_display\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const display = bufferParser.readBool();\n const msg = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed DEBUG packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received DEBUG');\n\n const handler = self._handlers.DEBUG;\n handler && handler(self, display, msg);\n },\n [MESSAGE.SERVICE_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_SERVICE_REQUEST\n string service name\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n bufferParser.clear();\n\n if (name === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed SERVICE_REQUEST packet'\n );\n }\n\n self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`);\n\n const handler = self._handlers.SERVICE_REQUEST;\n handler && handler(self, name);\n },\n [MESSAGE.SERVICE_ACCEPT]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_SERVICE_ACCEPT\n string service name\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n bufferParser.clear();\n\n if (name === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed SERVICE_ACCEPT packet'\n );\n }\n\n self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`);\n\n const handler = self._handlers.SERVICE_ACCEPT;\n handler && handler(self, name);\n },\n [MESSAGE.EXT_INFO]: (self, payload) => {\n /*\n byte SSH_MSG_EXT_INFO\n uint32 nr-extensions\n repeat the following 2 fields \"nr-extensions\" times:\n string extension-name\n string extension-value (binary)\n */\n bufferParser.init(payload, 1);\n const numExts = bufferParser.readUInt32BE();\n let exts;\n if (numExts !== undefined) {\n exts = [];\n for (let i = 0; i < numExts; ++i) {\n const name = bufferParser.readString(true);\n const data = bufferParser.readString();\n if (data !== undefined) {\n switch (name) {\n case 'server-sig-algs': {\n const algs = data.latin1Slice(0, data.length).split(',');\n exts.push({ name, algs });\n continue;\n }\n default:\n continue;\n }\n }\n // Malformed\n exts = undefined;\n break;\n }\n }\n bufferParser.clear();\n\n if (exts === undefined)\n return doFatalError(self, 'Inbound: Malformed EXT_INFO packet');\n\n self._debug && self._debug('Inbound: Received EXT_INFO');\n\n const handler = self._handlers.EXT_INFO;\n handler && handler(self, exts);\n },\n\n // User auth protocol -- generic =============================================\n [MESSAGE.USERAUTH_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_USERAUTH_REQUEST\n string user name in ISO-10646 UTF-8 encoding [RFC3629]\n string service name in US-ASCII\n string method name in US-ASCII\n .... method specific fields\n */\n bufferParser.init(payload, 1);\n const user = bufferParser.readString(true);\n const service = bufferParser.readString(true);\n const method = bufferParser.readString(true);\n let methodData;\n let methodDesc;\n switch (method) {\n case 'none':\n methodData = null;\n break;\n case 'password': {\n /*\n boolean \n string plaintext password in ISO-10646 UTF-8 encoding [RFC3629]\n [string new password]\n */\n const isChange = bufferParser.readBool();\n if (isChange !== undefined) {\n methodData = bufferParser.readString(true);\n if (methodData !== undefined && isChange) {\n const newPassword = bufferParser.readString(true);\n if (newPassword !== undefined)\n methodData = { oldPassword: methodData, newPassword };\n else\n methodData = undefined;\n }\n }\n break;\n }\n case 'publickey': {\n /*\n boolean \n string public key algorithm name\n string public key blob\n [string signature]\n */\n const hasSig = bufferParser.readBool();\n if (hasSig !== undefined) {\n const keyAlgo = bufferParser.readString(true);\n let realKeyAlgo = keyAlgo;\n const key = bufferParser.readString();\n\n let hashAlgo;\n switch (keyAlgo) {\n case 'rsa-sha2-256':\n realKeyAlgo = 'ssh-rsa';\n hashAlgo = 'sha256';\n break;\n case 'rsa-sha2-512':\n realKeyAlgo = 'ssh-rsa';\n hashAlgo = 'sha512';\n break;\n }\n\n if (hasSig) {\n const blobEnd = bufferParser.pos();\n let signature = bufferParser.readString();\n if (signature !== undefined) {\n if (signature.length > (4 + keyAlgo.length + 4)\n && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) {\n // Skip algoLen + algo + sigLen\n signature = bufferSlice(signature, 4 + keyAlgo.length + 4);\n }\n\n signature = sigSSHToASN1(signature, realKeyAlgo);\n if (signature) {\n const sessionID = self._kex.sessionID;\n const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd);\n writeUInt32BE(blob, sessionID.length, 0);\n blob.set(sessionID, 4);\n blob.set(\n new Uint8Array(payload.buffer, payload.byteOffset, blobEnd),\n 4 + sessionID.length\n );\n methodData = {\n keyAlgo: realKeyAlgo,\n key,\n signature,\n blob,\n hashAlgo,\n };\n }\n }\n } else {\n methodData = { keyAlgo: realKeyAlgo, key, hashAlgo };\n methodDesc = 'publickey -- check';\n }\n }\n break;\n }\n case 'hostbased': {\n /*\n string public key algorithm for host key\n string public host key and certificates for client host\n string client host name expressed as the FQDN in US-ASCII\n string user name on the client host in ISO-10646 UTF-8 encoding\n [RFC3629]\n string signature\n */\n const keyAlgo = bufferParser.readString(true);\n let realKeyAlgo = keyAlgo;\n const key = bufferParser.readString();\n const localHostname = bufferParser.readString(true);\n const localUsername = bufferParser.readString(true);\n\n let hashAlgo;\n switch (keyAlgo) {\n case 'rsa-sha2-256':\n realKeyAlgo = 'ssh-rsa';\n hashAlgo = 'sha256';\n break;\n case 'rsa-sha2-512':\n realKeyAlgo = 'ssh-rsa';\n hashAlgo = 'sha512';\n break;\n }\n\n const blobEnd = bufferParser.pos();\n let signature = bufferParser.readString();\n if (signature !== undefined) {\n if (signature.length > (4 + keyAlgo.length + 4)\n && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) {\n // Skip algoLen + algo + sigLen\n signature = bufferSlice(signature, 4 + keyAlgo.length + 4);\n }\n\n signature = sigSSHToASN1(signature, realKeyAlgo);\n if (signature !== undefined) {\n const sessionID = self._kex.sessionID;\n const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd);\n writeUInt32BE(blob, sessionID.length, 0);\n blob.set(sessionID, 4);\n blob.set(\n new Uint8Array(payload.buffer, payload.byteOffset, blobEnd),\n 4 + sessionID.length\n );\n methodData = {\n keyAlgo: realKeyAlgo,\n key,\n signature,\n blob,\n localHostname,\n localUsername,\n hashAlgo\n };\n }\n }\n break;\n }\n case 'keyboard-interactive':\n /*\n string language tag (as defined in [RFC-3066])\n string submethods (ISO-10646 UTF-8)\n */\n // Skip/ignore language field -- it's deprecated in RFC 4256\n bufferParser.skipString();\n\n methodData = bufferParser.readList();\n break;\n default:\n if (method !== undefined)\n methodData = bufferParser.readRaw();\n }\n bufferParser.clear();\n\n if (methodData === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_REQUEST packet'\n );\n }\n\n if (methodDesc === undefined)\n methodDesc = method;\n\n self._authsQueue.push(method);\n\n self._debug\n && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`);\n\n const handler = self._handlers.USERAUTH_REQUEST;\n handler && handler(self, user, service, method, methodData);\n },\n [MESSAGE.USERAUTH_FAILURE]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_FAILURE\n name-list authentications that can continue\n boolean partial success\n */\n bufferParser.init(payload, 1);\n const authMethods = bufferParser.readList();\n const partialSuccess = bufferParser.readBool();\n bufferParser.clear();\n\n if (partialSuccess === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_FAILURE packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`);\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_FAILURE;\n handler && handler(self, authMethods, partialSuccess);\n },\n [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_SUCCESS\n */\n self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS');\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_SUCCESS;\n handler && handler(self);\n },\n [MESSAGE.USERAUTH_BANNER]: (self, payload) => {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_BANNER\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const msg = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_BANNER packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_BANNER');\n\n const handler = self._handlers.USERAUTH_BANNER;\n handler && handler(self, msg);\n },\n\n // User auth protocol -- method-specific =====================================\n 60: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 60 without auth');\n return;\n }\n\n switch (self._authsQueue[0]) {\n case 'password': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ\n string prompt in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const prompt = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet'\n );\n }\n\n self._debug\n && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ');\n\n const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ;\n handler && handler(self, prompt);\n break;\n }\n case 'publickey': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_PK_OK\n string public key algorithm name from the request\n string public key blob from the request\n */\n bufferParser.init(payload, 1);\n const keyAlgo = bufferParser.readString(true);\n const key = bufferParser.readString();\n bufferParser.clear();\n\n if (key === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_PK_OK packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_PK_OK');\n\n self._authsQueue.shift();\n const handler = self._handlers.USERAUTH_PK_OK;\n handler && handler(self, keyAlgo, key);\n break;\n }\n case 'keyboard-interactive': {\n // S->C\n /*\n byte SSH_MSG_USERAUTH_INFO_REQUEST\n string name (ISO-10646 UTF-8)\n string instruction (ISO-10646 UTF-8)\n string language tag (as defined in [RFC-3066])\n int num-prompts\n string prompt[1] (ISO-10646 UTF-8)\n boolean echo[1]\n ...\n string prompt[num-prompts] (ISO-10646 UTF-8)\n boolean echo[num-prompts]\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n const instructions = bufferParser.readString(true);\n bufferParser.readString(); // skip lang\n const numPrompts = bufferParser.readUInt32BE();\n let prompts;\n if (numPrompts !== undefined) {\n prompts = new Array(numPrompts);\n let i;\n for (i = 0; i < numPrompts; ++i) {\n const prompt = bufferParser.readString(true);\n const echo = bufferParser.readBool();\n if (echo === undefined)\n break;\n prompts[i] = { prompt, echo };\n }\n if (i !== numPrompts)\n prompts = undefined;\n }\n bufferParser.clear();\n\n if (prompts === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_REQUEST packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST');\n\n const handler = self._handlers.USERAUTH_INFO_REQUEST;\n handler && handler(self, name, instructions, prompts);\n break;\n }\n default:\n self._debug\n && self._debug('Inbound: Received unexpected payload type 60');\n }\n },\n 61: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 61 without auth');\n return;\n }\n /*\n byte SSH_MSG_USERAUTH_INFO_RESPONSE\n int num-responses\n string response[1] (ISO-10646 UTF-8)\n ...\n string response[num-responses] (ISO-10646 UTF-8)\n */\n if (self._authsQueue[0] !== 'keyboard-interactive') {\n return doFatalError(\n self,\n 'Inbound: Received unexpected payload type 61'\n );\n }\n bufferParser.init(payload, 1);\n const numResponses = bufferParser.readUInt32BE();\n let responses;\n if (numResponses !== undefined) {\n responses = new Array(numResponses);\n let i;\n for (i = 0; i < numResponses; ++i) {\n const response = bufferParser.readString(true);\n if (response === undefined)\n break;\n responses[i] = response;\n }\n if (i !== numResponses)\n responses = undefined;\n }\n bufferParser.clear();\n\n if (responses === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE');\n\n const handler = self._handlers.USERAUTH_INFO_RESPONSE;\n handler && handler(self, responses);\n },\n\n // Connection protocol -- generic ============================================\n [MESSAGE.GLOBAL_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_GLOBAL_REQUEST\n string request name in US-ASCII only\n boolean want reply\n .... request-specific data follows\n */\n bufferParser.init(payload, 1);\n const name = bufferParser.readString(true);\n const wantReply = bufferParser.readBool();\n let data;\n if (wantReply !== undefined) {\n switch (name) {\n case 'tcpip-forward':\n case 'cancel-tcpip-forward': {\n /*\n string address to bind (e.g., \"0.0.0.0\")\n uint32 port number to bind\n */\n const bindAddr = bufferParser.readString(true);\n const bindPort = bufferParser.readUInt32BE();\n if (bindPort !== undefined)\n data = { bindAddr, bindPort };\n break;\n }\n case 'streamlocal-forward@openssh.com':\n case 'cancel-streamlocal-forward@openssh.com': {\n /*\n string socket path\n */\n const socketPath = bufferParser.readString(true);\n if (socketPath !== undefined)\n data = { socketPath };\n break;\n }\n case 'no-more-sessions@openssh.com':\n data = null;\n break;\n case 'hostkeys-00@openssh.com': {\n data = [];\n while (bufferParser.avail() > 0) {\n const keyRaw = bufferParser.readString();\n if (keyRaw === undefined) {\n data = undefined;\n break;\n }\n const key = parseKey(keyRaw);\n if (!(key instanceof Error))\n data.push(key);\n }\n break;\n }\n default:\n data = bufferParser.readRaw();\n }\n }\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed GLOBAL_REQUEST packet'\n );\n }\n\n self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`);\n\n const handler = self._handlers.GLOBAL_REQUEST;\n if (handler)\n handler(self, name, wantReply, data);\n else\n self.requestFailure(); // Auto reject\n },\n [MESSAGE.REQUEST_SUCCESS]: (self, payload) => {\n /*\n byte SSH_MSG_REQUEST_SUCCESS\n .... response specific data\n */\n const data = (payload.length > 1 ? bufferSlice(payload, 1) : null);\n\n self._debug && self._debug('Inbound: REQUEST_SUCCESS');\n\n const handler = self._handlers.REQUEST_SUCCESS;\n handler && handler(self, data);\n },\n [MESSAGE.REQUEST_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_REQUEST_FAILURE\n */\n self._debug && self._debug('Inbound: Received REQUEST_FAILURE');\n\n const handler = self._handlers.REQUEST_FAILURE;\n handler && handler(self);\n },\n\n // Connection protocol -- channel-related ====================================\n [MESSAGE.CHANNEL_OPEN]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN\n string channel type in US-ASCII only\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n .... channel type specific data follows\n */\n bufferParser.init(payload, 1);\n const type = bufferParser.readString(true);\n const sender = bufferParser.readUInt32BE();\n const window = bufferParser.readUInt32BE();\n const packetSize = bufferParser.readUInt32BE();\n let channelInfo;\n\n switch (type) {\n case 'forwarded-tcpip': // S->C\n case 'direct-tcpip': { // C->S\n /*\n string address that was connected / host to connect\n uint32 port that was connected / port to connect\n string originator IP address\n uint32 originator port\n */\n const destIP = bufferParser.readString(true);\n const destPort = bufferParser.readUInt32BE();\n const srcIP = bufferParser.readString(true);\n const srcPort = bufferParser.readUInt32BE();\n if (srcPort !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { destIP, destPort, srcIP, srcPort }\n };\n }\n break;\n }\n case 'forwarded-streamlocal@openssh.com': // S->C\n case 'direct-streamlocal@openssh.com': { // C->S\n /*\n string socket path\n string reserved for future use\n\n (direct-streamlocal@openssh.com additionally has:)\n uint32 reserved\n */\n const socketPath = bufferParser.readString(true);\n if (socketPath !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { socketPath }\n };\n }\n break;\n }\n case 'x11': { // S->C\n /*\n string originator address (e.g., \"192.168.7.38\")\n uint32 originator port\n */\n const srcIP = bufferParser.readString(true);\n const srcPort = bufferParser.readUInt32BE();\n if (srcPort !== undefined) {\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: { srcIP, srcPort }\n };\n }\n break;\n }\n default:\n // Includes:\n // 'session' (C->S)\n // 'auth-agent@openssh.com' (S->C)\n channelInfo = {\n type,\n sender,\n window,\n packetSize,\n data: {}\n };\n }\n bufferParser.clear();\n\n if (channelInfo === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`);\n\n const handler = self._handlers.CHANNEL_OPEN;\n if (handler) {\n handler(self, channelInfo);\n } else {\n self.channelOpenFail(\n channelInfo.sender,\n CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED,\n '',\n ''\n );\n }\n },\n [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION\n uint32 recipient channel\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n .... channel type specific data follows\n */\n // \"The 'recipient channel' is the channel number given in the\n // original open request, and 'sender channel' is the channel number\n // allocated by the other side.\"\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const sender = bufferParser.readUInt32BE();\n const window = bufferParser.readUInt32BE();\n const packetSize = bufferParser.readUInt32BE();\n const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined);\n bufferParser.clear();\n\n if (packetSize === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})`\n );\n\n const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION;\n if (handler)\n handler(self, { recipient, sender, window, packetSize, data });\n },\n [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_OPEN_FAILURE\n uint32 recipient channel\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const reason = bufferParser.readUInt32BE();\n const description = bufferParser.readString(true);\n const lang = bufferParser.readString();\n bufferParser.clear();\n\n if (lang === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_OPEN_FAILURE;\n handler && handler(self, recipient, reason, description);\n },\n [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_WINDOW_ADJUST\n uint32 recipient channel\n uint32 bytes to add\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const bytesToAdd = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (bytesToAdd === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})`\n );\n\n const handler = self._handlers.CHANNEL_WINDOW_ADJUST;\n handler && handler(self, recipient, bytesToAdd);\n },\n [MESSAGE.CHANNEL_DATA]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_DATA\n uint32 recipient channel\n string data\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_DATA packet'\n );\n }\n\n self._debug\n && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`);\n\n const handler = self._handlers.CHANNEL_DATA;\n handler && handler(self, recipient, data);\n },\n [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_EXTENDED_DATA\n uint32 recipient channel\n uint32 data_type_code\n string data\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const type = bufferParser.readUInt32BE();\n const data = bufferParser.readString();\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet'\n );\n }\n\n self._debug && self._debug(\n `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})`\n );\n\n const handler = self._handlers.CHANNEL_EXTENDED_DATA;\n handler && handler(self, recipient, data, type);\n },\n [MESSAGE.CHANNEL_EOF]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_EOF\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_EOF packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_EOF;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_CLOSE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_CLOSE\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_CLOSE packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_CLOSE;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_REQUEST]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_REQUEST\n uint32 recipient channel\n string request type in US-ASCII characters only\n boolean want reply\n .... type-specific data follows\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n const type = bufferParser.readString(true);\n const wantReply = bufferParser.readBool();\n let data;\n if (wantReply !== undefined) {\n switch (type) {\n case 'exit-status': // S->C\n /*\n uint32 exit_status\n */\n data = bufferParser.readUInt32BE();\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'exit-signal': { // S->C\n /*\n string signal name (without the \"SIG\" prefix)\n boolean core dumped\n string error message in ISO-10646 UTF-8 encoding\n string language tag\n */\n let signal;\n let coreDumped;\n if (self._compatFlags & COMPAT.OLD_EXIT) {\n /*\n Instead of `signal name` and `core dumped`, we have just:\n uint32 signal number\n */\n const num = bufferParser.readUInt32BE();\n switch (num) {\n case 1:\n signal = 'HUP';\n break;\n case 2:\n signal = 'INT';\n break;\n case 3:\n signal = 'QUIT';\n break;\n case 6:\n signal = 'ABRT';\n break;\n case 9:\n signal = 'KILL';\n break;\n case 14:\n signal = 'ALRM';\n break;\n case 15:\n signal = 'TERM';\n break;\n default:\n if (num !== undefined) {\n // Unknown or OS-specific\n signal = `UNKNOWN (${num})`;\n }\n }\n coreDumped = false;\n } else {\n signal = bufferParser.readString(true);\n coreDumped = bufferParser.readBool();\n if (coreDumped === undefined)\n signal = undefined;\n }\n const errorMessage = bufferParser.readString(true);\n if (bufferParser.skipString() !== undefined)\n data = { signal, coreDumped, errorMessage };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})`\n );\n break;\n }\n case 'pty-req': { // C->S\n /*\n string TERM environment variable value (e.g., vt100)\n uint32 terminal width, characters (e.g., 80)\n uint32 terminal height, rows (e.g., 24)\n uint32 terminal width, pixels (e.g., 640)\n uint32 terminal height, pixels (e.g., 480)\n string encoded terminal modes\n */\n const term = bufferParser.readString(true);\n const cols = bufferParser.readUInt32BE();\n const rows = bufferParser.readUInt32BE();\n const width = bufferParser.readUInt32BE();\n const height = bufferParser.readUInt32BE();\n const modesBinary = bufferParser.readString();\n if (modesBinary !== undefined) {\n bufferParser.init(modesBinary, 1);\n let modes = {};\n while (bufferParser.avail()) {\n const opcode = bufferParser.readByte();\n if (opcode === TERMINAL_MODE.TTY_OP_END)\n break;\n const name = TERMINAL_MODE_BY_VALUE[opcode];\n const value = bufferParser.readUInt32BE();\n if (opcode === undefined\n || name === undefined\n || value === undefined) {\n modes = undefined;\n break;\n }\n modes[name] = value;\n }\n if (modes !== undefined)\n data = { term, cols, rows, width, height, modes };\n }\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'window-change': { // C->S\n /*\n uint32 terminal width, columns\n uint32 terminal height, rows\n uint32 terminal width, pixels\n uint32 terminal height, pixels\n */\n const cols = bufferParser.readUInt32BE();\n const rows = bufferParser.readUInt32BE();\n const width = bufferParser.readUInt32BE();\n const height = bufferParser.readUInt32BE();\n if (height !== undefined)\n data = { cols, rows, width, height };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'x11-req': { // C->S\n /*\n boolean single connection\n string x11 authentication protocol\n string x11 authentication cookie\n uint32 x11 screen number\n */\n const single = bufferParser.readBool();\n const protocol = bufferParser.readString(true);\n const cookie = bufferParser.readString();\n const screen = bufferParser.readUInt32BE();\n if (screen !== undefined)\n data = { single, protocol, cookie, screen };\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n }\n case 'env': { // C->S\n /*\n string variable name\n string variable value\n */\n const name = bufferParser.readString(true);\n const value = bufferParser.readString(true);\n if (value !== undefined)\n data = { name, value };\n if (self._debug) {\n self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: `\n + `${name}=${value})`\n );\n }\n break;\n }\n case 'shell': // C->S\n data = null; // No extra data\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n case 'exec': // C->S\n /*\n string command\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'subsystem': // C->S\n /*\n string subsystem name\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'signal': // C->S\n /*\n string signal name (without the \"SIG\" prefix)\n */\n data = bufferParser.readString(true);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'xon-xoff': // C->S\n /*\n boolean client can do\n */\n data = bufferParser.readBool();\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})`\n );\n break;\n case 'auth-agent-req@openssh.com': // C-S\n data = null; // No extra data\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n break;\n default:\n data = (bufferParser.avail() ? bufferParser.readRaw() : null);\n self._debug && self._debug(\n `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})`\n );\n }\n }\n bufferParser.clear();\n\n if (data === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_REQUEST packet'\n );\n }\n\n const handler = self._handlers.CHANNEL_REQUEST;\n handler && handler(self, recipient, type, wantReply, data);\n },\n [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_SUCCESS\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_SUCCESS packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_SUCCESS;\n handler && handler(self, recipient);\n },\n [MESSAGE.CHANNEL_FAILURE]: (self, payload) => {\n /*\n byte SSH_MSG_CHANNEL_FAILURE\n uint32 recipient channel\n */\n bufferParser.init(payload, 1);\n const recipient = bufferParser.readUInt32BE();\n bufferParser.clear();\n\n if (recipient === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed CHANNEL_FAILURE packet'\n );\n }\n\n self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`);\n\n const handler = self._handlers.CHANNEL_FAILURE;\n handler && handler(self, recipient);\n },\n};\n","'use strict';\n\nconst {\n createDiffieHellman,\n createDiffieHellmanGroup,\n createECDH,\n createHash,\n createPublicKey,\n diffieHellman,\n generateKeyPairSync,\n randomFillSync,\n} = require('crypto');\n\nconst { Ber } = require('asn1');\n\nconst {\n COMPAT,\n curve25519Supported,\n DEFAULT_KEX,\n DEFAULT_SERVER_HOST_KEY,\n DEFAULT_CIPHER,\n DEFAULT_MAC,\n DEFAULT_COMPRESSION,\n DISCONNECT_REASON,\n MESSAGE,\n} = require('./constants.js');\nconst {\n CIPHER_INFO,\n createCipher,\n createDecipher,\n MAC_INFO,\n} = require('./crypto.js');\nconst { parseDERKey } = require('./keyParser.js');\nconst {\n bufferFill,\n bufferParser,\n convertSignature,\n doFatalError,\n FastBuffer,\n sigSSHToASN1,\n writeUInt32BE,\n} = require('./utils.js');\nconst {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n} = require('./zlib.js');\n\nlet MESSAGE_HANDLERS;\n\nconst GEX_MIN_BITS = 2048; // RFC 8270\nconst GEX_MAX_BITS = 8192; // RFC 8270\n\nconst EMPTY_BUFFER = Buffer.alloc(0);\n\n// Client/Server\nfunction kexinit(self) {\n /*\n byte SSH_MSG_KEXINIT\n byte[16] cookie (random bytes)\n name-list kex_algorithms\n name-list server_host_key_algorithms\n name-list encryption_algorithms_client_to_server\n name-list encryption_algorithms_server_to_client\n name-list mac_algorithms_client_to_server\n name-list mac_algorithms_server_to_client\n name-list compression_algorithms_client_to_server\n name-list compression_algorithms_server_to_client\n name-list languages_client_to_server\n name-list languages_server_to_client\n boolean first_kex_packet_follows\n uint32 0 (reserved for future extension)\n */\n\n let payload;\n if (self._compatFlags & COMPAT.BAD_DHGEX) {\n const entry = self._offer.lists.kex;\n let kex = entry.array;\n let found = false;\n for (let i = 0; i < kex.length; ++i) {\n if (kex[i].includes('group-exchange')) {\n if (!found) {\n found = true;\n // Copy array lazily\n kex = kex.slice();\n }\n kex.splice(i--, 1);\n }\n }\n if (found) {\n let len = 1 + 16 + self._offer.totalSize + 1 + 4;\n const newKexBuf = Buffer.from(kex.join(','));\n len -= (entry.buffer.length - newKexBuf.length);\n\n const all = self._offer.lists.all;\n const rest = new Uint8Array(\n all.buffer,\n all.byteOffset + 4 + entry.buffer.length,\n all.length - (4 + entry.buffer.length)\n );\n\n payload = Buffer.allocUnsafe(len);\n writeUInt32BE(payload, newKexBuf.length, 17);\n payload.set(newKexBuf, 17 + 4);\n payload.set(rest, 17 + 4 + newKexBuf.length);\n }\n }\n\n if (payload === undefined) {\n payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4);\n self._offer.copyAllTo(payload, 17);\n }\n\n self._debug && self._debug('Outbound: Sending KEXINIT');\n\n payload[0] = MESSAGE.KEXINIT;\n randomFillSync(payload, 1, 16);\n\n // Zero-fill first_kex_packet_follows and reserved bytes\n bufferFill(payload, 0, payload.length - 5);\n\n self._kexinit = payload;\n\n // Needed to correct the starting position in allocated \"packets\" when packets\n // will be buffered due to active key exchange\n self._packetRW.write.allocStart = 0;\n\n // TODO: only create single buffer and set _kexinit as slice of packet instead\n {\n const p = self._packetRW.write.allocStartKEX;\n const packet = self._packetRW.write.alloc(payload.length, true);\n packet.set(payload, p);\n self._cipher.encrypt(self._packetRW.write.finalize(packet, true));\n }\n}\n\nfunction handleKexInit(self, payload) {\n /*\n byte SSH_MSG_KEXINIT\n byte[16] cookie (random bytes)\n name-list kex_algorithms\n name-list server_host_key_algorithms\n name-list encryption_algorithms_client_to_server\n name-list encryption_algorithms_server_to_client\n name-list mac_algorithms_client_to_server\n name-list mac_algorithms_server_to_client\n name-list compression_algorithms_client_to_server\n name-list compression_algorithms_server_to_client\n name-list languages_client_to_server\n name-list languages_server_to_client\n boolean first_kex_packet_follows\n uint32 0 (reserved for future extension)\n */\n const init = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n sc: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n };\n\n bufferParser.init(payload, 17);\n\n if ((init.kex = bufferParser.readList()) === undefined\n || (init.serverHostKey = bufferParser.readList()) === undefined\n || (init.cs.cipher = bufferParser.readList()) === undefined\n || (init.sc.cipher = bufferParser.readList()) === undefined\n || (init.cs.mac = bufferParser.readList()) === undefined\n || (init.sc.mac = bufferParser.readList()) === undefined\n || (init.cs.compress = bufferParser.readList()) === undefined\n || (init.sc.compress = bufferParser.readList()) === undefined\n || (init.cs.lang = bufferParser.readList()) === undefined\n || (init.sc.lang = bufferParser.readList()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n self,\n 'Received malformed KEXINIT',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n const pos = bufferParser.pos();\n const firstFollows = (pos < payload.length && payload[pos] === 1);\n bufferParser.clear();\n\n const local = self._offer;\n const remote = init;\n\n let localKex = local.lists.kex.array;\n if (self._compatFlags & COMPAT.BAD_DHGEX) {\n let found = false;\n for (let i = 0; i < localKex.length; ++i) {\n if (localKex[i].indexOf('group-exchange') !== -1) {\n if (!found) {\n found = true;\n // Copy array lazily\n localKex = localKex.slice();\n }\n localKex.splice(i--, 1);\n }\n }\n }\n\n let clientList;\n let serverList;\n let i;\n const debug = self._debug;\n\n debug && debug('Inbound: Handshake in progress');\n\n // Key exchange method =======================================================\n debug && debug(`Handshake: (local) KEX method: ${localKex}`);\n debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`);\n let remoteExtInfoEnabled;\n if (self._server) {\n serverList = localKex;\n clientList = remote.kex;\n remoteExtInfoEnabled = (clientList.indexOf('ext-info-c') !== -1);\n } else {\n serverList = remote.kex;\n clientList = localKex;\n remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1);\n }\n if (self._strictMode === undefined) {\n if (self._server) {\n self._strictMode =\n (clientList.indexOf('kex-strict-c-v00@openssh.com') !== -1);\n } else {\n self._strictMode =\n (serverList.indexOf('kex-strict-s-v00@openssh.com') !== -1);\n }\n // Note: We check for seqno of 1 instead of 0 since we increment before\n // calling the packet handler\n if (self._strictMode) {\n debug && debug('Handshake: strict KEX mode enabled');\n if (self._decipher.inSeqno !== 1) {\n if (debug)\n debug('Handshake: KEXINIT not first packet in strict KEX mode');\n return doFatalError(\n self,\n 'Handshake failed: KEXINIT not first packet in strict KEX mode',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n }\n // Check for agreeable key exchange algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: no matching key exchange algorithm');\n return doFatalError(\n self,\n 'Handshake failed: no matching key exchange algorithm',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.kex = clientList[i];\n debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`);\n if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) {\n // Ignore next inbound packet, it was a wrong first guess at KEX algorithm\n self._skipNextInboundPacket = true;\n }\n\n\n // Server host key format ====================================================\n const localSrvHostKey = local.lists.serverHostKey.array;\n debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`);\n debug && debug(\n `Handshake: (remote) Host key format: ${remote.serverHostKey}`\n );\n if (self._server) {\n serverList = localSrvHostKey;\n clientList = remote.serverHostKey;\n } else {\n serverList = remote.serverHostKey;\n clientList = localSrvHostKey;\n }\n // Check for agreeable server host key format\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching host key format');\n return doFatalError(\n self,\n 'Handshake failed: no matching host key format',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.serverHostKey = clientList[i];\n debug && debug(`Handshake: Host key format: ${clientList[i]}`);\n\n\n // Client->Server cipher =====================================================\n const localCSCipher = local.lists.cs.cipher.array;\n debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`);\n debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`);\n if (self._server) {\n serverList = localCSCipher;\n clientList = remote.cs.cipher;\n } else {\n serverList = remote.cs.cipher;\n clientList = localCSCipher;\n }\n // Check for agreeable client->server cipher\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S cipher');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S cipher',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.cipher = clientList[i];\n debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`);\n\n\n // Server->Client cipher =====================================================\n const localSCCipher = local.lists.sc.cipher.array;\n debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`);\n debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`);\n if (self._server) {\n serverList = localSCCipher;\n clientList = remote.sc.cipher;\n } else {\n serverList = remote.sc.cipher;\n clientList = localSCCipher;\n }\n // Check for agreeable server->client cipher\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C cipher');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C cipher',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.cipher = clientList[i];\n debug && debug(`Handshake: S->C cipher: ${clientList[i]}`);\n\n\n // Client->Server MAC ========================================================\n const localCSMAC = local.lists.cs.mac.array;\n debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`);\n debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`);\n if (CIPHER_INFO[init.cs.cipher].authLen > 0) {\n init.cs.mac = '';\n debug && debug('Handshake: C->S MAC: ');\n } else {\n if (self._server) {\n serverList = localCSMAC;\n clientList = remote.cs.mac;\n } else {\n serverList = remote.cs.mac;\n clientList = localCSMAC;\n }\n // Check for agreeable client->server hmac algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S MAC');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S MAC',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.mac = clientList[i];\n debug && debug(`Handshake: C->S MAC: ${clientList[i]}`);\n }\n\n\n // Server->Client MAC ========================================================\n const localSCMAC = local.lists.sc.mac.array;\n debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`);\n debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`);\n if (CIPHER_INFO[init.sc.cipher].authLen > 0) {\n init.sc.mac = '';\n debug && debug('Handshake: S->C MAC: ');\n } else {\n if (self._server) {\n serverList = localSCMAC;\n clientList = remote.sc.mac;\n } else {\n serverList = remote.sc.mac;\n clientList = localSCMAC;\n }\n // Check for agreeable server->client hmac algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C MAC');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C MAC',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.mac = clientList[i];\n debug && debug(`Handshake: S->C MAC: ${clientList[i]}`);\n }\n\n\n // Client->Server compression ================================================\n const localCSCompress = local.lists.cs.compress.array;\n debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`);\n debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`);\n if (self._server) {\n serverList = localCSCompress;\n clientList = remote.cs.compress;\n } else {\n serverList = remote.cs.compress;\n clientList = localCSCompress;\n }\n // Check for agreeable client->server compression algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching C->S compression');\n return doFatalError(\n self,\n 'Handshake failed: no matching C->S compression',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.cs.compress = clientList[i];\n debug && debug(`Handshake: C->S compression: ${clientList[i]}`);\n\n\n // Server->Client compression ================================================\n const localSCCompress = local.lists.sc.compress.array;\n debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`);\n debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`);\n if (self._server) {\n serverList = localSCCompress;\n clientList = remote.sc.compress;\n } else {\n serverList = remote.sc.compress;\n clientList = localSCCompress;\n }\n // Check for agreeable server->client compression algorithm\n for (i = 0;\n i < clientList.length && serverList.indexOf(clientList[i]) === -1;\n ++i);\n if (i === clientList.length) {\n // No suitable match found!\n debug && debug('Handshake: No matching S->C compression');\n return doFatalError(\n self,\n 'Handshake failed: no matching S->C compression',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n init.sc.compress = clientList[i];\n debug && debug(`Handshake: S->C compression: ${clientList[i]}`);\n\n init.cs.lang = '';\n init.sc.lang = '';\n\n // XXX: hack -- find a better way to do this\n if (self._kex) {\n if (!self._kexinit) {\n // We received a rekey request, but we haven't sent a KEXINIT in response\n // yet\n kexinit(self);\n }\n self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false });\n }\n\n self._kex = createKeyExchange(init, self, payload);\n self._kex.remoteExtInfoEnabled = remoteExtInfoEnabled;\n self._kex.start();\n}\n\nconst createKeyExchange = (() => {\n function convertToMpint(buf) {\n let idx = 0;\n let length = buf.length;\n while (buf[idx] === 0x00) {\n ++idx;\n --length;\n }\n let newBuf;\n if (buf[idx] & 0x80) {\n newBuf = Buffer.allocUnsafe(1 + length);\n newBuf[0] = 0;\n buf.copy(newBuf, 1, idx);\n buf = newBuf;\n } else if (length !== buf.length) {\n newBuf = Buffer.allocUnsafe(length);\n buf.copy(newBuf, 0, idx);\n buf = newBuf;\n }\n return buf;\n }\n\n class KeyExchange {\n constructor(negotiated, protocol, remoteKexinit) {\n this._protocol = protocol;\n\n this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined);\n this.negotiated = negotiated;\n this.remoteExtInfoEnabled = false;\n this._step = 1;\n this._public = null;\n this._dh = null;\n this._sentNEWKEYS = false;\n this._receivedNEWKEYS = false;\n this._finished = false;\n this._hostVerified = false;\n\n // Data needed for initializing cipher/decipher/etc.\n this._kexinit = protocol._kexinit;\n this._remoteKexinit = remoteKexinit;\n this._identRaw = protocol._identRaw;\n this._remoteIdentRaw = protocol._remoteIdentRaw;\n this._hostKey = undefined;\n this._dhData = undefined;\n this._sig = undefined;\n }\n finish(scOnly) {\n if (this._finished)\n return false;\n this._finished = true;\n\n const isServer = this._protocol._server;\n const negotiated = this.negotiated;\n\n const pubKey = this.convertPublicKey(this._dhData);\n let secret = this.computeSecret(this._dhData);\n if (secret instanceof Error) {\n secret.message =\n `Error while computing DH secret (${this.type}): ${secret.message}`;\n secret.level = 'handshake';\n return doFatalError(\n this._protocol,\n secret,\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n const hash = createHash(this.hashName);\n // V_C\n hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw));\n // \"V_S\"\n hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw));\n // \"I_C\"\n hashString(hash, (isServer ? this._remoteKexinit : this._kexinit));\n // \"I_S\"\n hashString(hash, (isServer ? this._kexinit : this._remoteKexinit));\n // \"K_S\"\n const serverPublicHostKey = (isServer\n ? this._hostKey.getPublicSSH()\n : this._hostKey);\n hashString(hash, serverPublicHostKey);\n\n if (this.type === 'groupex') {\n // Group exchange-specific\n const params = this.getDHParams();\n const num = Buffer.allocUnsafe(4);\n // min (uint32)\n writeUInt32BE(num, this._minBits, 0);\n hash.update(num);\n // preferred (uint32)\n writeUInt32BE(num, this._prefBits, 0);\n hash.update(num);\n // max (uint32)\n writeUInt32BE(num, this._maxBits, 0);\n hash.update(num);\n // prime\n hashString(hash, params.prime);\n // generator\n hashString(hash, params.generator);\n }\n\n // method-specific data sent by client\n hashString(hash, (isServer ? pubKey : this.getPublicKey()));\n // method-specific data sent by server\n const serverPublicKey = (isServer ? this.getPublicKey() : pubKey);\n hashString(hash, serverPublicKey);\n // shared secret (\"K\")\n hashString(hash, secret);\n\n // \"H\"\n const exchangeHash = hash.digest();\n\n if (!isServer) {\n bufferParser.init(this._sig, 0);\n const sigType = bufferParser.readString(true);\n\n if (!sigType) {\n return doFatalError(\n this._protocol,\n 'Malformed packet while reading signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (sigType !== negotiated.serverHostKey) {\n return doFatalError(\n this._protocol,\n `Wrong signature type: ${sigType}, `\n + `expected: ${negotiated.serverHostKey}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // \"s\"\n let sigValue = bufferParser.readString();\n\n bufferParser.clear();\n\n if (sigValue === undefined) {\n return doFatalError(\n this._protocol,\n 'Malformed packet while reading signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (!(sigValue = sigSSHToASN1(sigValue, sigType))) {\n return doFatalError(\n this._protocol,\n 'Malformed signature',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n let parsedHostKey;\n {\n bufferParser.init(this._hostKey, 0);\n const name = bufferParser.readString(true);\n const hostKey = this._hostKey.slice(bufferParser.pos());\n bufferParser.clear();\n parsedHostKey = parseDERKey(hostKey, name);\n if (parsedHostKey instanceof Error) {\n parsedHostKey.level = 'handshake';\n return doFatalError(\n this._protocol,\n parsedHostKey,\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n let hashAlgo;\n // Check if we need to override the default hash algorithm\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256': hashAlgo = 'sha256'; break;\n case 'rsa-sha2-512': hashAlgo = 'sha512'; break;\n }\n\n this._protocol._debug\n && this._protocol._debug('Verifying signature ...');\n\n const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo);\n if (verified !== true) {\n if (verified instanceof Error) {\n this._protocol._debug && this._protocol._debug(\n `Signature verification failed: ${verified.stack}`\n );\n } else {\n this._protocol._debug && this._protocol._debug(\n 'Signature verification failed'\n );\n }\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature verification failed',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug('Verified signature');\n } else {\n // Server\n\n let hashAlgo;\n // Check if we need to override the default hash algorithm\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256': hashAlgo = 'sha256'; break;\n case 'rsa-sha2-512': hashAlgo = 'sha512'; break;\n }\n\n this._protocol._debug && this._protocol._debug(\n 'Generating signature ...'\n );\n\n let signature = this._hostKey.sign(exchangeHash, hashAlgo);\n if (signature instanceof Error) {\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature generation failed for '\n + `${this._hostKey.type} host key: ${signature.message}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n signature = convertSignature(signature, this._hostKey.type);\n if (signature === false) {\n return doFatalError(\n this._protocol,\n 'Handshake failed: signature conversion failed for '\n + `${this._hostKey.type} host key`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // Send KEX reply\n /*\n byte SSH_MSG_KEXDH_REPLY\n / SSH_MSG_KEX_DH_GEX_REPLY\n / SSH_MSG_KEX_ECDH_REPLY\n string server public host key and certificates (K_S)\n string \n string signature of H\n */\n const sigType = this.negotiated.serverHostKey;\n const sigTypeLen = Buffer.byteLength(sigType);\n const sigLen = 4 + sigTypeLen + 4 + signature.length;\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1\n + 4 + serverPublicHostKey.length\n + 4 + serverPublicKey.length\n + 4 + sigLen,\n true\n );\n\n packet[p] = MESSAGE.KEXDH_REPLY;\n\n writeUInt32BE(packet, serverPublicHostKey.length, ++p);\n packet.set(serverPublicHostKey, p += 4);\n\n writeUInt32BE(packet,\n serverPublicKey.length,\n p += serverPublicHostKey.length);\n packet.set(serverPublicKey, p += 4);\n\n writeUInt32BE(packet, sigLen, p += serverPublicKey.length);\n\n writeUInt32BE(packet, sigTypeLen, p += 4);\n packet.utf8Write(sigType, p += 4, sigTypeLen);\n\n writeUInt32BE(packet, signature.length, p += sigTypeLen);\n packet.set(signature, p += 4);\n\n if (this._protocol._debug) {\n let type;\n switch (this.type) {\n case 'group':\n type = 'KEXDH_REPLY';\n break;\n case 'groupex':\n type = 'KEXDH_GEX_REPLY';\n break;\n default:\n type = 'KEXECDH_REPLY';\n }\n this._protocol._debug(`Outbound: Sending ${type}`);\n }\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n\n if (isServer || !scOnly)\n trySendNEWKEYS(this);\n\n let hsCipherConfig;\n let hsWrite;\n const completeHandshake = (partial) => {\n if (hsCipherConfig) {\n trySendNEWKEYS(this);\n hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno;\n this._protocol._cipher.free();\n this._protocol._cipher = createCipher(hsCipherConfig);\n this._protocol._packetRW.write = hsWrite;\n hsCipherConfig = undefined;\n hsWrite = undefined;\n this._protocol._onHandshakeComplete(negotiated);\n\n return false;\n }\n\n if (!this.sessionID)\n this.sessionID = exchangeHash;\n\n {\n const newSecret = Buffer.allocUnsafe(4 + secret.length);\n writeUInt32BE(newSecret, secret.length, 0);\n newSecret.set(secret, 4);\n secret = newSecret;\n }\n\n // Initialize new ciphers, deciphers, etc.\n\n const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher];\n const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher];\n\n const csIV = generateKEXVal(csCipherInfo.ivLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'A');\n const scIV = generateKEXVal(scCipherInfo.ivLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'B');\n const csKey = generateKEXVal(csCipherInfo.keyLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'C');\n const scKey = generateKEXVal(scCipherInfo.keyLen,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'D');\n let csMacInfo;\n let csMacKey;\n if (!csCipherInfo.authLen) {\n csMacInfo = MAC_INFO[negotiated.cs.mac];\n csMacKey = generateKEXVal(csMacInfo.len,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'E');\n }\n let scMacInfo;\n let scMacKey;\n if (!scCipherInfo.authLen) {\n scMacInfo = MAC_INFO[negotiated.sc.mac];\n scMacKey = generateKEXVal(scMacInfo.len,\n this.hashName,\n secret,\n exchangeHash,\n this.sessionID,\n 'F');\n }\n\n const config = {\n inbound: {\n onPayload: this._protocol._onPayload,\n seqno: this._protocol._decipher.inSeqno,\n decipherInfo: (!isServer ? scCipherInfo : csCipherInfo),\n decipherIV: (!isServer ? scIV : csIV),\n decipherKey: (!isServer ? scKey : csKey),\n macInfo: (!isServer ? scMacInfo : csMacInfo),\n macKey: (!isServer ? scMacKey : csMacKey),\n },\n outbound: {\n onWrite: this._protocol._onWrite,\n seqno: this._protocol._cipher.outSeqno,\n cipherInfo: (isServer ? scCipherInfo : csCipherInfo),\n cipherIV: (isServer ? scIV : csIV),\n cipherKey: (isServer ? scKey : csKey),\n macInfo: (isServer ? scMacInfo : csMacInfo),\n macKey: (isServer ? scMacKey : csMacKey),\n },\n };\n this._protocol._decipher.free();\n hsCipherConfig = config;\n this._protocol._decipher = createDecipher(config);\n\n const rw = {\n read: undefined,\n write: undefined,\n };\n switch (negotiated.cs.compress) {\n case 'zlib': // starts immediately\n if (isServer)\n rw.read = new ZlibPacketReader();\n else\n rw.write = new ZlibPacketWriter(this._protocol);\n break;\n case 'zlib@openssh.com':\n // Starts after successful user authentication\n\n if (this._protocol._authenticated) {\n // If a rekey happens and this compression method is selected and\n // we already authenticated successfully, we need to start\n // immediately instead\n if (isServer)\n rw.read = new ZlibPacketReader();\n else\n rw.write = new ZlibPacketWriter(this._protocol);\n break;\n }\n // FALLTHROUGH\n default:\n // none -- never any compression/decompression\n\n if (isServer)\n rw.read = new PacketReader();\n else\n rw.write = new PacketWriter(this._protocol);\n }\n switch (negotiated.sc.compress) {\n case 'zlib': // starts immediately\n if (isServer)\n rw.write = new ZlibPacketWriter(this._protocol);\n else\n rw.read = new ZlibPacketReader();\n break;\n case 'zlib@openssh.com':\n // Starts after successful user authentication\n\n if (this._protocol._authenticated) {\n // If a rekey happens and this compression method is selected and\n // we already authenticated successfully, we need to start\n // immediately instead\n if (isServer)\n rw.write = new ZlibPacketWriter(this._protocol);\n else\n rw.read = new ZlibPacketReader();\n break;\n }\n // FALLTHROUGH\n default:\n // none -- never any compression/decompression\n\n if (isServer)\n rw.write = new PacketWriter(this._protocol);\n else\n rw.read = new PacketReader();\n }\n this._protocol._packetRW.read.cleanup();\n this._protocol._packetRW.write.cleanup();\n this._protocol._packetRW.read = rw.read;\n hsWrite = rw.write;\n\n // Cleanup/reset various state\n this._public = null;\n this._dh = null;\n this._kexinit = this._protocol._kexinit = undefined;\n this._remoteKexinit = undefined;\n this._identRaw = undefined;\n this._remoteIdentRaw = undefined;\n this._hostKey = undefined;\n this._dhData = undefined;\n this._sig = undefined;\n\n if (!partial)\n return completeHandshake();\n return false;\n };\n\n if (isServer || scOnly)\n this.finish = completeHandshake;\n\n if (!isServer)\n return completeHandshake(scOnly);\n }\n\n start() {\n if (!this._protocol._server) {\n if (this._protocol._debug) {\n let type;\n switch (this.type) {\n case 'group':\n type = 'KEXDH_INIT';\n break;\n default:\n type = 'KEXECDH_INIT';\n }\n this._protocol._debug(`Outbound: Sending ${type}`);\n }\n\n const pubKey = this.getPublicKey();\n\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1 + 4 + pubKey.length,\n true\n );\n packet[p] = MESSAGE.KEXDH_INIT;\n writeUInt32BE(packet, pubKey.length, ++p);\n packet.set(pubKey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n }\n getPublicKey() {\n this.generateKeys();\n\n const key = this._public;\n\n if (key)\n return this.convertPublicKey(key);\n }\n convertPublicKey(key) {\n let newKey;\n let idx = 0;\n let len = key.length;\n while (key[idx] === 0x00) {\n ++idx;\n --len;\n }\n\n if (key[idx] & 0x80) {\n newKey = Buffer.allocUnsafe(1 + len);\n newKey[0] = 0;\n key.copy(newKey, 1, idx);\n return newKey;\n }\n\n if (len !== key.length) {\n newKey = Buffer.allocUnsafe(len);\n key.copy(newKey, 0, idx);\n key = newKey;\n }\n return key;\n }\n computeSecret(otherPublicKey) {\n this.generateKeys();\n\n try {\n return convertToMpint(this._dh.computeSecret(otherPublicKey));\n } catch (ex) {\n return ex;\n }\n }\n parse(payload) {\n const type = payload[0];\n switch (this._step) {\n case 1:\n if (this._protocol._server) {\n // Server\n if (type !== MESSAGE.KEXDH_INIT) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH Init'\n );\n /*\n byte SSH_MSG_KEXDH_INIT\n / SSH_MSG_KEX_ECDH_INIT\n string \n */\n bufferParser.init(payload, 1);\n const dhData = bufferParser.readString();\n bufferParser.clear();\n if (dhData === undefined) {\n return doFatalError(\n this._protocol,\n 'Received malformed KEX*_INIT',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n // Client public key\n this._dhData = dhData;\n\n let hostKey =\n this._protocol._hostKeys[this.negotiated.serverHostKey];\n if (Array.isArray(hostKey))\n hostKey = hostKey[0];\n this._hostKey = hostKey;\n\n this.finish();\n } else {\n // Client\n if (type !== MESSAGE.KEXDH_REPLY) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH Reply'\n );\n /*\n byte SSH_MSG_KEXDH_REPLY\n / SSH_MSG_KEX_DH_GEX_REPLY\n / SSH_MSG_KEX_ECDH_REPLY\n string server public host key and certificates (K_S)\n string \n string signature of H\n */\n bufferParser.init(payload, 1);\n let hostPubKey;\n let dhData;\n let sig;\n if ((hostPubKey = bufferParser.readString()) === undefined\n || (dhData = bufferParser.readString()) === undefined\n || (sig = bufferParser.readString()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n this._protocol,\n 'Received malformed KEX*_REPLY',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n bufferParser.clear();\n\n // Check that the host public key type matches what was negotiated\n // during KEXINIT swap\n bufferParser.init(hostPubKey, 0);\n const hostPubKeyType = bufferParser.readString(true);\n bufferParser.clear();\n if (hostPubKeyType === undefined) {\n return doFatalError(\n this._protocol,\n 'Received malformed host public key',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n if (hostPubKeyType !== this.negotiated.serverHostKey) {\n // Check if we need to make an exception\n switch (this.negotiated.serverHostKey) {\n case 'rsa-sha2-256':\n case 'rsa-sha2-512':\n if (hostPubKeyType === 'ssh-rsa')\n break;\n // FALLTHROUGH\n default:\n return doFatalError(\n this._protocol,\n 'Host key does not match negotiated type',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n this._hostKey = hostPubKey;\n this._dhData = dhData;\n this._sig = sig;\n\n let checked = false;\n let ret;\n if (this._protocol._hostVerifier === undefined) {\n ret = true;\n this._protocol._debug && this._protocol._debug(\n 'Host accepted by default (no verification)'\n );\n } else {\n ret = this._protocol._hostVerifier(hostPubKey, (permitted) => {\n if (checked)\n return;\n checked = true;\n if (permitted === false) {\n this._protocol._debug && this._protocol._debug(\n 'Host denied (verification failed)'\n );\n return doFatalError(\n this._protocol,\n 'Host denied (verification failed)',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Host accepted (verified)'\n );\n this._hostVerified = true;\n if (this._receivedNEWKEYS)\n this.finish();\n else\n trySendNEWKEYS(this);\n });\n }\n if (ret === undefined) {\n // Async host verification\n ++this._step;\n return;\n }\n checked = true;\n if (ret === false) {\n this._protocol._debug && this._protocol._debug(\n 'Host denied (verification failed)'\n );\n return doFatalError(\n this._protocol,\n 'Host denied (verification failed)',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Host accepted (verified)'\n );\n this._hostVerified = true;\n trySendNEWKEYS(this);\n }\n ++this._step;\n break;\n case 2:\n if (type !== MESSAGE.NEWKEYS) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Inbound: NEWKEYS'\n );\n this._receivedNEWKEYS = true;\n if (this._protocol._strictMode)\n this._protocol._decipher.inSeqno = 0;\n ++this._step;\n\n return this.finish(!this._protocol._server && !this._hostVerified);\n default:\n return doFatalError(\n this._protocol,\n `Received unexpected packet ${type} after NEWKEYS`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n }\n\n class Curve25519Exchange extends KeyExchange {\n constructor(hashName, ...args) {\n super(...args);\n\n this.type = '25519';\n this.hashName = hashName;\n this._keys = null;\n }\n generateKeys() {\n if (!this._keys)\n this._keys = generateKeyPairSync('x25519');\n }\n getPublicKey() {\n this.generateKeys();\n\n const key = this._keys.publicKey.export({ type: 'spki', format: 'der' });\n return key.slice(-32); // HACK: avoids parsing DER/BER header\n }\n convertPublicKey(key) {\n let newKey;\n let idx = 0;\n let len = key.length;\n while (key[idx] === 0x00) {\n ++idx;\n --len;\n }\n\n if (key.length === 32)\n return key;\n\n if (len !== key.length) {\n newKey = Buffer.allocUnsafe(len);\n key.copy(newKey, 0, idx);\n key = newKey;\n }\n return key;\n }\n computeSecret(otherPublicKey) {\n this.generateKeys();\n\n try {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.110'); // id-X25519\n asnWriter.endSequence();\n\n // PublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(otherPublicKey.length);\n otherPublicKey.copy(asnWriter._buf,\n asnWriter._offset,\n 0,\n otherPublicKey.length);\n asnWriter._offset += otherPublicKey.length;\n asnWriter.endSequence();\n asnWriter.endSequence();\n\n return convertToMpint(diffieHellman({\n privateKey: this._keys.privateKey,\n publicKey: createPublicKey({\n key: asnWriter.buffer,\n type: 'spki',\n format: 'der',\n }),\n }));\n } catch (ex) {\n return ex;\n }\n }\n }\n\n class ECDHExchange extends KeyExchange {\n constructor(curveName, hashName, ...args) {\n super(...args);\n\n this.type = 'ecdh';\n this.curveName = curveName;\n this.hashName = hashName;\n }\n generateKeys() {\n if (!this._dh) {\n this._dh = createECDH(this.curveName);\n this._public = this._dh.generateKeys();\n }\n }\n }\n\n class DHGroupExchange extends KeyExchange {\n constructor(hashName, ...args) {\n super(...args);\n\n this.type = 'groupex';\n this.hashName = hashName;\n this._prime = null;\n this._generator = null;\n this._minBits = GEX_MIN_BITS;\n this._prefBits = dhEstimate(this.negotiated);\n if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE)\n this._prefBits = Math.min(this._prefBits, 4096);\n this._maxBits = GEX_MAX_BITS;\n }\n start() {\n if (this._protocol._server)\n return;\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_GEX_REQUEST'\n );\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet = this._protocol._packetRW.write.alloc(\n 1 + 4 + 4 + 4,\n true\n );\n packet[p] = MESSAGE.KEXDH_GEX_REQUEST;\n writeUInt32BE(packet, this._minBits, ++p);\n writeUInt32BE(packet, this._prefBits, p += 4);\n writeUInt32BE(packet, this._maxBits, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n generateKeys() {\n if (!this._dh && this._prime && this._generator) {\n this._dh = createDiffieHellman(this._prime, this._generator);\n this._public = this._dh.generateKeys();\n }\n }\n setDHParams(prime, generator) {\n if (!Buffer.isBuffer(prime))\n throw new Error('Invalid prime value');\n if (!Buffer.isBuffer(generator))\n throw new Error('Invalid generator value');\n this._prime = prime;\n this._generator = generator;\n }\n getDHParams() {\n if (this._dh) {\n return {\n prime: convertToMpint(this._dh.getPrime()),\n generator: convertToMpint(this._dh.getGenerator()),\n };\n }\n }\n parse(payload) {\n const type = payload[0];\n switch (this._step) {\n case 1: {\n if (this._protocol._server) {\n if (type !== MESSAGE.KEXDH_GEX_REQUEST) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of `\n + MESSAGE.KEXDH_GEX_REQUEST,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n // TODO: allow user implementation to provide safe prime and\n // generator on demand to support group exchange on server side\n return doFatalError(\n this._protocol,\n 'Group exchange not implemented for server',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n if (type !== MESSAGE.KEXDH_GEX_GROUP) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Group'\n );\n\n /*\n byte SSH_MSG_KEX_DH_GEX_GROUP\n mpint p, safe prime\n mpint g, generator for subgroup in GF(p)\n */\n bufferParser.init(payload, 1);\n let prime;\n let gen;\n if ((prime = bufferParser.readString()) === undefined\n || (gen = bufferParser.readString()) === undefined) {\n bufferParser.clear();\n return doFatalError(\n this._protocol,\n 'Received malformed KEXDH_GEX_GROUP',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n bufferParser.clear();\n\n // TODO: validate prime\n this.setDHParams(prime, gen);\n this.generateKeys();\n const pubkey = this.getPublicKey();\n\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_GEX_INIT'\n );\n\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet =\n this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true);\n packet[p] = MESSAGE.KEXDH_GEX_INIT;\n writeUInt32BE(packet, pubkey.length, ++p);\n packet.set(pubkey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n\n ++this._step;\n break;\n }\n case 2:\n if (this._protocol._server) {\n if (type !== MESSAGE.KEXDH_GEX_INIT) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Init'\n );\n return doFatalError(\n this._protocol,\n 'Group exchange not implemented for server',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n } else if (type !== MESSAGE.KEXDH_GEX_REPLY) {\n return doFatalError(\n this._protocol,\n `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n this._protocol._debug && this._protocol._debug(\n 'Received DH GEX Reply'\n );\n this._step = 1;\n payload[0] = MESSAGE.KEXDH_REPLY;\n this.parse = KeyExchange.prototype.parse;\n this.parse(payload);\n }\n }\n }\n\n class DHExchange extends KeyExchange {\n constructor(groupName, hashName, ...args) {\n super(...args);\n\n this.type = 'group';\n this.groupName = groupName;\n this.hashName = hashName;\n }\n start() {\n if (!this._protocol._server) {\n this._protocol._debug && this._protocol._debug(\n 'Outbound: Sending KEXDH_INIT'\n );\n const pubKey = this.getPublicKey();\n let p = this._protocol._packetRW.write.allocStartKEX;\n const packet =\n this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true);\n packet[p] = MESSAGE.KEXDH_INIT;\n writeUInt32BE(packet, pubKey.length, ++p);\n packet.set(pubKey, p += 4);\n this._protocol._cipher.encrypt(\n this._protocol._packetRW.write.finalize(packet, true)\n );\n }\n }\n generateKeys() {\n if (!this._dh) {\n this._dh = createDiffieHellmanGroup(this.groupName);\n this._public = this._dh.generateKeys();\n }\n }\n getDHParams() {\n if (this._dh) {\n return {\n prime: convertToMpint(this._dh.getPrime()),\n generator: convertToMpint(this._dh.getGenerator()),\n };\n }\n }\n }\n\n return (negotiated, ...args) => {\n if (typeof negotiated !== 'object' || negotiated === null)\n throw new Error('Invalid negotiated argument');\n const kexType = negotiated.kex;\n if (typeof kexType === 'string') {\n args = [negotiated, ...args];\n switch (kexType) {\n case 'curve25519-sha256':\n case 'curve25519-sha256@libssh.org':\n if (!curve25519Supported)\n break;\n return new Curve25519Exchange('sha256', ...args);\n\n case 'ecdh-sha2-nistp256':\n return new ECDHExchange('prime256v1', 'sha256', ...args);\n case 'ecdh-sha2-nistp384':\n return new ECDHExchange('secp384r1', 'sha384', ...args);\n case 'ecdh-sha2-nistp521':\n return new ECDHExchange('secp521r1', 'sha512', ...args);\n\n case 'diffie-hellman-group1-sha1':\n return new DHExchange('modp2', 'sha1', ...args);\n case 'diffie-hellman-group14-sha1':\n return new DHExchange('modp14', 'sha1', ...args);\n case 'diffie-hellman-group14-sha256':\n return new DHExchange('modp14', 'sha256', ...args);\n case 'diffie-hellman-group15-sha512':\n return new DHExchange('modp15', 'sha512', ...args);\n case 'diffie-hellman-group16-sha512':\n return new DHExchange('modp16', 'sha512', ...args);\n case 'diffie-hellman-group17-sha512':\n return new DHExchange('modp17', 'sha512', ...args);\n case 'diffie-hellman-group18-sha512':\n return new DHExchange('modp18', 'sha512', ...args);\n\n case 'diffie-hellman-group-exchange-sha1':\n return new DHGroupExchange('sha1', ...args);\n case 'diffie-hellman-group-exchange-sha256':\n return new DHGroupExchange('sha256', ...args);\n }\n throw new Error(`Unsupported key exchange algorithm: ${kexType}`);\n }\n throw new Error(`Invalid key exchange type: ${kexType}`);\n };\n})();\n\nconst KexInit = (() => {\n const KEX_PROPERTY_NAMES = [\n 'kex',\n 'serverHostKey',\n ['cs', 'cipher' ],\n ['sc', 'cipher' ],\n ['cs', 'mac' ],\n ['sc', 'mac' ],\n ['cs', 'compress' ],\n ['sc', 'compress' ],\n ['cs', 'lang' ],\n ['sc', 'lang' ],\n ];\n return class KexInit {\n constructor(obj) {\n if (typeof obj !== 'object' || obj === null)\n throw new TypeError('Argument must be an object');\n\n const lists = {\n kex: undefined,\n serverHostKey: undefined,\n cs: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n sc: {\n cipher: undefined,\n mac: undefined,\n compress: undefined,\n lang: undefined,\n },\n\n all: undefined,\n };\n let totalSize = 0;\n for (const prop of KEX_PROPERTY_NAMES) {\n let base;\n let val;\n let desc;\n let key;\n if (typeof prop === 'string') {\n base = lists;\n val = obj[prop];\n desc = key = prop;\n } else {\n const parent = prop[0];\n base = lists[parent];\n key = prop[1];\n val = obj[parent][key];\n desc = `${parent}.${key}`;\n }\n const entry = { array: undefined, buffer: undefined };\n if (Buffer.isBuffer(val)) {\n entry.array = ('' + val).split(',');\n entry.buffer = val;\n totalSize += 4 + val.length;\n } else {\n if (typeof val === 'string')\n val = val.split(',');\n if (Array.isArray(val)) {\n entry.array = val;\n entry.buffer = Buffer.from(val.join(','));\n } else {\n throw new TypeError(`Invalid \\`${desc}\\` type: ${typeof val}`);\n }\n totalSize += 4 + entry.buffer.length;\n }\n base[key] = entry;\n }\n\n const all = Buffer.allocUnsafe(totalSize);\n lists.all = all;\n\n let allPos = 0;\n for (const prop of KEX_PROPERTY_NAMES) {\n let data;\n if (typeof prop === 'string')\n data = lists[prop].buffer;\n else\n data = lists[prop[0]][prop[1]].buffer;\n allPos = writeUInt32BE(all, data.length, allPos);\n all.set(data, allPos);\n allPos += data.length;\n }\n\n this.totalSize = totalSize;\n this.lists = lists;\n }\n copyAllTo(buf, offset) {\n const src = this.lists.all;\n if (typeof offset !== 'number')\n throw new TypeError(`Invalid offset value: ${typeof offset}`);\n if (buf.length - offset < src.length)\n throw new Error('Insufficient space to copy list');\n buf.set(src, offset);\n return src.length;\n }\n };\n})();\n\nconst hashString = (() => {\n const LEN = Buffer.allocUnsafe(4);\n return (hash, buf) => {\n writeUInt32BE(LEN, buf.length, 0);\n hash.update(LEN);\n hash.update(buf);\n };\n})();\n\nfunction generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) {\n let ret;\n if (len) {\n let digest = createHash(hashName)\n .update(secret)\n .update(exchangeHash)\n .update(char)\n .update(sessionID)\n .digest();\n while (digest.length < len) {\n const chunk = createHash(hashName)\n .update(secret)\n .update(exchangeHash)\n .update(digest)\n .digest();\n const extended = Buffer.allocUnsafe(digest.length + chunk.length);\n extended.set(digest, 0);\n extended.set(chunk, digest.length);\n digest = extended;\n }\n if (digest.length === len)\n ret = digest;\n else\n ret = new FastBuffer(digest.buffer, digest.byteOffset, len);\n } else {\n ret = EMPTY_BUFFER;\n }\n return ret;\n}\n\nfunction onKEXPayload(state, payload) {\n // XXX: move this to the Decipher implementations?\n if (payload.length === 0) {\n this._debug && this._debug('Inbound: Skipping empty packet payload');\n return;\n }\n\n if (this._skipNextInboundPacket) {\n this._skipNextInboundPacket = false;\n return;\n }\n\n payload = this._packetRW.read.read(payload);\n\n const type = payload[0];\n\n if (!this._strictMode) {\n switch (type) {\n case MESSAGE.IGNORE:\n case MESSAGE.UNIMPLEMENTED:\n case MESSAGE.DEBUG:\n if (!MESSAGE_HANDLERS)\n MESSAGE_HANDLERS = require('./handlers.js');\n return MESSAGE_HANDLERS[type](this, payload);\n }\n }\n\n switch (type) {\n case MESSAGE.DISCONNECT:\n if (!MESSAGE_HANDLERS)\n MESSAGE_HANDLERS = require('./handlers.js');\n return MESSAGE_HANDLERS[type](this, payload);\n case MESSAGE.KEXINIT:\n if (!state.firstPacket) {\n return doFatalError(\n this,\n 'Received extra KEXINIT during handshake',\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n state.firstPacket = false;\n return handleKexInit(this, payload);\n default:\n // Ensure packet is either an algorithm negotiation or KEX\n // algorithm-specific packet\n if (type < 20 || type > 49) {\n return doFatalError(\n this,\n `Received unexpected packet type ${type}`,\n 'handshake',\n DISCONNECT_REASON.KEY_EXCHANGE_FAILED\n );\n }\n }\n\n return this._kex.parse(payload);\n}\n\nfunction dhEstimate(neg) {\n const csCipher = CIPHER_INFO[neg.cs.cipher];\n const scCipher = CIPHER_INFO[neg.sc.cipher];\n // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will\n // also need to be considered when calculating `bits`\n const bits = Math.max(\n 0,\n (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen),\n csCipher.blockLen,\n csCipher.ivLen,\n (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen),\n scCipher.blockLen,\n scCipher.ivLen\n ) * 8;\n if (bits <= 112)\n return 2048;\n if (bits <= 128)\n return 3072;\n if (bits <= 192)\n return 7680;\n return 8192;\n}\n\nfunction trySendNEWKEYS(kex) {\n if (!kex._sentNEWKEYS) {\n kex._protocol._debug && kex._protocol._debug(\n 'Outbound: Sending NEWKEYS'\n );\n const p = kex._protocol._packetRW.write.allocStartKEX;\n const packet = kex._protocol._packetRW.write.alloc(1, true);\n packet[p] = MESSAGE.NEWKEYS;\n kex._protocol._cipher.encrypt(\n kex._protocol._packetRW.write.finalize(packet, true)\n );\n kex._sentNEWKEYS = true;\n if (kex._protocol._strictMode)\n kex._protocol._cipher.outSeqno = 0;\n }\n}\n\nmodule.exports = {\n KexInit,\n kexinit,\n onKEXPayload,\n DEFAULT_KEXINIT_CLIENT: new KexInit({\n kex: DEFAULT_KEX.concat(['ext-info-c', 'kex-strict-c-v00@openssh.com']),\n serverHostKey: DEFAULT_SERVER_HOST_KEY,\n cs: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n sc: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n }),\n DEFAULT_KEXINIT_SERVER: new KexInit({\n kex: DEFAULT_KEX.concat(['kex-strict-s-v00@openssh.com']),\n serverHostKey: DEFAULT_SERVER_HOST_KEY,\n cs: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n sc: {\n cipher: DEFAULT_CIPHER,\n mac: DEFAULT_MAC,\n compress: DEFAULT_COMPRESSION,\n lang: [],\n },\n }),\n HANDLERS: {\n [MESSAGE.KEXINIT]: handleKexInit,\n },\n};\n","// TODO:\n// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()`\n// * handle multi-line header values (OpenSSH)?\n// * more thorough validation?\n'use strict';\n\nconst {\n createDecipheriv,\n createECDH,\n createHash,\n createHmac,\n createSign,\n createVerify,\n getCiphers,\n sign: sign_,\n verify: verify_,\n} = require('crypto');\nconst supportedOpenSSLCiphers = getCiphers();\n\nconst { Ber } = require('asn1');\nconst bcrypt_pbkdf = require('bcrypt-pbkdf').pbkdf;\n\nconst { CIPHER_INFO } = require('./crypto.js');\nconst { eddsaSupported, SUPPORTED_CIPHER } = require('./constants.js');\nconst {\n bufferSlice,\n makeBufferParser,\n readString,\n readUInt32BE,\n writeUInt32BE,\n} = require('./utils.js');\n\nconst SYM_HASH_ALGO = Symbol('Hash Algorithm');\nconst SYM_PRIV_PEM = Symbol('Private key PEM');\nconst SYM_PUB_PEM = Symbol('Public key PEM');\nconst SYM_PUB_SSH = Symbol('Public key SSH');\nconst SYM_DECRYPTED = Symbol('Decrypted Key');\n\n// Create OpenSSL cipher name -> SSH cipher name conversion table\nconst CIPHER_INFO_OPENSSL = Object.create(null);\n{\n const keys = Object.keys(CIPHER_INFO);\n for (let i = 0; i < keys.length; ++i) {\n const cipherName = CIPHER_INFO[keys[i]].sslName;\n if (!cipherName || CIPHER_INFO_OPENSSL[cipherName])\n continue;\n CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]];\n }\n}\n\nconst binaryKeyParser = makeBufferParser();\n\nfunction makePEM(type, data) {\n data = data.base64Slice(0, data.length);\n let formatted = data.replace(/.{64}/g, '$&\\n');\n if (data.length & 63)\n formatted += '\\n';\n return `-----BEGIN ${type} KEY-----\\n${formatted}-----END ${type} KEY-----`;\n}\n\nfunction combineBuffers(buf1, buf2) {\n const result = Buffer.allocUnsafe(buf1.length + buf2.length);\n result.set(buf1, 0);\n result.set(buf2, buf1.length);\n return result;\n}\n\nfunction skipFields(buf, nfields) {\n const bufLen = buf.length;\n let pos = (buf._pos || 0);\n for (let i = 0; i < nfields; ++i) {\n const left = (bufLen - pos);\n if (pos >= bufLen || left < 4)\n return false;\n const len = readUInt32BE(buf, pos);\n if (left < 4 + len)\n return false;\n pos += 4 + len;\n }\n buf._pos = pos;\n return true;\n}\n\nfunction genOpenSSLRSAPub(n, e) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption\n // algorithm parameters (RSA has none)\n asnWriter.writeNull();\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n asnWriter.startSequence();\n asnWriter.writeBuffer(n, Ber.Integer);\n asnWriter.writeBuffer(e, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHRSAPub(n, e) {\n const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length);\n\n writeUInt32BE(publicKey, 7, 0);\n publicKey.utf8Write('ssh-rsa', 4, 7);\n\n let i = 4 + 7;\n writeUInt32BE(publicKey, e.length, i);\n publicKey.set(e, i += 4);\n\n writeUInt32BE(publicKey, n.length, i += e.length);\n publicKey.set(n, i + 4);\n\n return publicKey;\n}\n\nconst genOpenSSLRSAPriv = (() => {\n function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeInt(0x00, Ber.Integer);\n asnWriter.writeBuffer(n, Ber.Integer);\n asnWriter.writeBuffer(e, Ber.Integer);\n asnWriter.writeBuffer(d, Ber.Integer);\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(dmp1, Ber.Integer);\n asnWriter.writeBuffer(dmq1, Ber.Integer);\n asnWriter.writeBuffer(iqmp, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n\n function bigIntFromBuffer(buf) {\n return BigInt(`0x${buf.hexSlice(0, buf.length)}`);\n }\n\n function bigIntToBuffer(bn) {\n let hex = bn.toString(16);\n if ((hex.length & 1) !== 0) {\n hex = `0${hex}`;\n } else {\n const sigbit = hex.charCodeAt(0);\n // BER/DER integers require leading zero byte to denote a positive value\n // when first byte >= 0x80\n if (sigbit === 56/* '8' */\n || sigbit === 57/* '9' */\n || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) {\n hex = `00${hex}`;\n }\n }\n return Buffer.from(hex, 'hex');\n }\n\n return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) {\n const bn_d = bigIntFromBuffer(d);\n const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n));\n const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n));\n return makePEM('RSA PRIVATE',\n genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp));\n };\n})();\n\nfunction genOpenSSLDSAPub(p, q, g, y) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa\n // algorithm parameters\n asnWriter.startSequence();\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(g, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n asnWriter.writeBuffer(y, Ber.Integer);\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHDSAPub(p, q, g, y) {\n const publicKey = Buffer.allocUnsafe(\n 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length\n );\n\n writeUInt32BE(publicKey, 7, 0);\n publicKey.utf8Write('ssh-dss', 4, 7);\n\n let i = 4 + 7;\n writeUInt32BE(publicKey, p.length, i);\n publicKey.set(p, i += 4);\n\n writeUInt32BE(publicKey, q.length, i += p.length);\n publicKey.set(q, i += 4);\n\n writeUInt32BE(publicKey, g.length, i += q.length);\n publicKey.set(g, i += 4);\n\n writeUInt32BE(publicKey, y.length, i += g.length);\n publicKey.set(y, i + 4);\n\n return publicKey;\n}\n\nfunction genOpenSSLDSAPriv(p, q, g, y, x) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeInt(0x00, Ber.Integer);\n asnWriter.writeBuffer(p, Ber.Integer);\n asnWriter.writeBuffer(q, Ber.Integer);\n asnWriter.writeBuffer(g, Ber.Integer);\n asnWriter.writeBuffer(y, Ber.Integer);\n asnWriter.writeBuffer(x, Ber.Integer);\n asnWriter.endSequence();\n return makePEM('DSA PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLEdPub(pub) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.112'); // id-Ed25519\n asnWriter.endSequence();\n\n // PublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(pub.length);\n asnWriter._buf.set(pub, asnWriter._offset);\n asnWriter._offset += pub.length;\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHEdPub(pub) {\n const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length);\n\n writeUInt32BE(publicKey, 11, 0);\n publicKey.utf8Write('ssh-ed25519', 4, 11);\n\n writeUInt32BE(publicKey, pub.length, 15);\n publicKey.set(pub, 19);\n\n return publicKey;\n}\n\nfunction genOpenSSLEdPriv(priv) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // version\n asnWriter.writeInt(0x00, Ber.Integer);\n\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.3.101.112'); // id-Ed25519\n asnWriter.endSequence();\n\n // PrivateKey\n asnWriter.startSequence(Ber.OctetString);\n asnWriter.writeBuffer(priv, Ber.OctetString);\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLECDSAPub(oid, Q) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey\n // algorithm parameters (namedCurve)\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(Q.length);\n asnWriter._buf.set(Q, asnWriter._offset);\n asnWriter._offset += Q.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}\n\nfunction genOpenSSHECDSAPub(oid, Q) {\n let curveName;\n switch (oid) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n curveName = 'nistp256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n curveName = 'nistp384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n curveName = 'nistp521';\n break;\n default:\n return;\n }\n\n const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length);\n\n writeUInt32BE(publicKey, 19, 0);\n publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19);\n\n writeUInt32BE(publicKey, 8, 23);\n publicKey.utf8Write(curveName, 27, 8);\n\n writeUInt32BE(publicKey, Q.length, 35);\n publicKey.set(Q, 39);\n\n return publicKey;\n}\n\nfunction genOpenSSLECDSAPriv(oid, pub, priv) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // version\n asnWriter.writeInt(0x01, Ber.Integer);\n // privateKey\n asnWriter.writeBuffer(priv, Ber.OctetString);\n // parameters (optional)\n asnWriter.startSequence(0xA0);\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n // publicKey (optional)\n asnWriter.startSequence(0xA1);\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(pub.length);\n asnWriter._buf.set(pub, asnWriter._offset);\n asnWriter._offset += pub.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('EC PRIVATE', asnWriter.buffer);\n}\n\nfunction genOpenSSLECDSAPubFromPriv(curveName, priv) {\n const tempECDH = createECDH(curveName);\n tempECDH.setPrivateKey(priv);\n return tempECDH.getPublicKey();\n}\n\nconst BaseKey = {\n sign: (() => {\n if (typeof sign_ === 'function') {\n return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return sign_(algo, data, pem);\n } catch (ex) {\n return ex;\n }\n };\n }\n return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n const signature = createSign(algo);\n signature.update(data);\n try {\n return signature.sign(pem);\n } catch (ex) {\n return ex;\n }\n };\n })(),\n verify: (() => {\n if (typeof verify_ === 'function') {\n return function verify(data, signature, algo) {\n const pem = this[SYM_PUB_PEM];\n if (pem === null)\n return new Error('No public key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return verify_(algo, data, pem, signature);\n } catch (ex) {\n return ex;\n }\n };\n }\n return function verify(data, signature, algo) {\n const pem = this[SYM_PUB_PEM];\n if (pem === null)\n return new Error('No public key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n const verifier = createVerify(algo);\n verifier.update(data);\n try {\n return verifier.verify(pem, signature);\n } catch (ex) {\n return ex;\n }\n };\n })(),\n isPrivateKey: function isPrivateKey() {\n return (this[SYM_PRIV_PEM] !== null);\n },\n getPrivatePEM: function getPrivatePEM() {\n return this[SYM_PRIV_PEM];\n },\n getPublicPEM: function getPublicPEM() {\n return this[SYM_PUB_PEM];\n },\n getPublicSSH: function getPublicSSH() {\n return this[SYM_PUB_SSH];\n },\n equals: function equals(key) {\n const parsed = parseKey(key);\n if (parsed instanceof Error)\n return false;\n return (\n this.type === parsed.type\n && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM]\n && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM]\n && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH]\n );\n },\n};\n\n\nfunction OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo,\n decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nOpenSSH_Private.prototype = BaseKey;\n{\n const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\\r\\n|\\n)([\\s\\S]+)(?:\\r\\n|\\n)-----END OPENSSH PRIVATE KEY-----$/;\n OpenSSH_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n let ret;\n const data = Buffer.from(m[1], 'base64');\n if (data.length < 31) // magic (+ magic null term.) + minimum field lengths\n return new Error('Malformed OpenSSH private key');\n const magic = data.utf8Slice(0, 15);\n if (magic !== 'openssh-key-v1\\0')\n return new Error(`Unsupported OpenSSH key magic: ${magic}`);\n\n const cipherName = readString(data, 15, true);\n if (cipherName === undefined)\n return new Error('Malformed OpenSSH private key');\n if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1)\n return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`);\n\n const kdfName = readString(data, data._pos, true);\n if (kdfName === undefined)\n return new Error('Malformed OpenSSH private key');\n if (kdfName !== 'none') {\n if (cipherName === 'none')\n return new Error('Malformed OpenSSH private key');\n if (kdfName !== 'bcrypt')\n return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`);\n if (!passphrase) {\n return new Error(\n 'Encrypted private OpenSSH key detected, but no passphrase given'\n );\n }\n } else if (cipherName !== 'none') {\n return new Error('Malformed OpenSSH private key');\n }\n\n let encInfo;\n let cipherKey;\n let cipherIV;\n if (cipherName !== 'none')\n encInfo = CIPHER_INFO[cipherName];\n const kdfOptions = readString(data, data._pos);\n if (kdfOptions === undefined)\n return new Error('Malformed OpenSSH private key');\n if (kdfOptions.length) {\n switch (kdfName) {\n case 'none':\n return new Error('Malformed OpenSSH private key');\n case 'bcrypt': {\n /*\n string salt\n uint32 rounds\n */\n const salt = readString(kdfOptions, 0);\n if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length)\n return new Error('Malformed OpenSSH private key');\n const rounds = readUInt32BE(kdfOptions, kdfOptions._pos);\n const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen);\n const r = bcrypt_pbkdf(passphrase,\n passphrase.length,\n salt,\n salt.length,\n gen,\n gen.length,\n rounds);\n if (r !== 0)\n return new Error('Failed to generate information to decrypt key');\n cipherKey = bufferSlice(gen, 0, encInfo.keyLen);\n cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length);\n break;\n }\n }\n } else if (kdfName !== 'none') {\n return new Error('Malformed OpenSSH private key');\n }\n\n if (data._pos + 3 >= data.length)\n return new Error('Malformed OpenSSH private key');\n const keyCount = readUInt32BE(data, data._pos);\n data._pos += 4;\n\n if (keyCount > 0) {\n // TODO: place sensible limit on max `keyCount`\n\n // Read public keys first\n for (let i = 0; i < keyCount; ++i) {\n const pubData = readString(data, data._pos);\n if (pubData === undefined)\n return new Error('Malformed OpenSSH private key');\n const type = readString(pubData, 0, true);\n if (type === undefined)\n return new Error('Malformed OpenSSH private key');\n }\n\n let privBlob = readString(data, data._pos);\n if (privBlob === undefined)\n return new Error('Malformed OpenSSH private key');\n\n if (cipherKey !== undefined) {\n // Encrypted private key(s)\n if (privBlob.length < encInfo.blockLen\n || (privBlob.length % encInfo.blockLen) !== 0) {\n return new Error('Malformed OpenSSH private key');\n }\n try {\n const options = { authTagLength: encInfo.authLen };\n const decipher = createDecipheriv(encInfo.sslName,\n cipherKey,\n cipherIV,\n options);\n decipher.setAutoPadding(false);\n if (encInfo.authLen > 0) {\n if (data.length - data._pos < encInfo.authLen)\n return new Error('Malformed OpenSSH private key');\n decipher.setAuthTag(\n bufferSlice(data, data._pos, data._pos += encInfo.authLen)\n );\n }\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n } catch (ex) {\n return ex;\n }\n }\n // Nothing should we follow the private key(s), except a possible\n // authentication tag for relevant ciphers\n if (data._pos !== data.length)\n return new Error('Malformed OpenSSH private key');\n\n ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined);\n } else {\n ret = [];\n }\n if (ret instanceof Error)\n return ret;\n // This will need to change if/when OpenSSH ever starts storing multiple\n // keys in their key files\n return ret[0];\n };\n\n function parseOpenSSHPrivKeys(data, nkeys, decrypted) {\n const keys = [];\n /*\n uint32 checkint\n uint32 checkint\n string privatekey1\n string comment1\n string privatekey2\n string comment2\n ...\n string privatekeyN\n string commentN\n char 1\n char 2\n char 3\n ...\n char padlen % 255\n */\n if (data.length < 8)\n return new Error('Malformed OpenSSH private key');\n const check1 = readUInt32BE(data, 0);\n const check2 = readUInt32BE(data, 4);\n if (check1 !== check2) {\n if (decrypted) {\n return new Error(\n 'OpenSSH key integrity check failed -- bad passphrase?'\n );\n }\n return new Error('OpenSSH key integrity check failed');\n }\n data._pos = 8;\n let i;\n let oid;\n for (i = 0; i < nkeys; ++i) {\n let algo;\n let privPEM;\n let pubPEM;\n let pubSSH;\n // The OpenSSH documentation for the key format actually lies, the\n // entirety of the private key content is not contained with a string\n // field, it's actually the literal contents of the private key, so to be\n // able to find the end of the key data you need to know the layout/format\n // of each key type ...\n const type = readString(data, data._pos, true);\n if (type === undefined)\n return new Error('Malformed OpenSSH private key');\n\n switch (type) {\n case 'ssh-rsa': {\n /*\n string n -- public\n string e -- public\n string d -- private\n string iqmp -- private\n string p -- private\n string q -- private\n */\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed OpenSSH private key');\n const e = readString(data, data._pos);\n if (e === undefined)\n return new Error('Malformed OpenSSH private key');\n const d = readString(data, data._pos);\n if (d === undefined)\n return new Error('Malformed OpenSSH private key');\n const iqmp = readString(data, data._pos);\n if (iqmp === undefined)\n return new Error('Malformed OpenSSH private key');\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed OpenSSH private key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q);\n algo = 'sha1';\n break;\n }\n case 'ssh-dss': {\n /*\n string p -- public\n string q -- public\n string g -- public\n string y -- public\n string x -- private\n */\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed OpenSSH private key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH private key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed OpenSSH private key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed OpenSSH private key');\n const x = readString(data, data._pos);\n if (x === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n privPEM = genOpenSSLDSAPriv(p, q, g, y, x);\n algo = 'sha1';\n break;\n }\n case 'ssh-ed25519': {\n if (!eddsaSupported)\n return new Error(`Unsupported OpenSSH private key type: ${type}`);\n /*\n * string public key\n * string private key + public key\n */\n const edpub = readString(data, data._pos);\n if (edpub === undefined || edpub.length !== 32)\n return new Error('Malformed OpenSSH private key');\n const edpriv = readString(data, data._pos);\n if (edpriv === undefined || edpriv.length !== 64)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLEdPub(edpub);\n pubSSH = genOpenSSHEdPub(edpub);\n privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32));\n algo = null;\n break;\n }\n case 'ecdsa-sha2-nistp256':\n algo = 'sha256';\n oid = '1.2.840.10045.3.1.7';\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp384':\n if (algo === undefined) {\n algo = 'sha384';\n oid = '1.3.132.0.34';\n }\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp521': {\n if (algo === undefined) {\n algo = 'sha512';\n oid = '1.3.132.0.35';\n }\n /*\n string curve name\n string Q -- public\n string d -- private\n */\n // TODO: validate curve name against type\n if (!skipFields(data, 1)) // Skip curve name\n return new Error('Malformed OpenSSH private key');\n const ecpub = readString(data, data._pos);\n if (ecpub === undefined)\n return new Error('Malformed OpenSSH private key');\n const ecpriv = readString(data, data._pos);\n if (ecpriv === undefined)\n return new Error('Malformed OpenSSH private key');\n\n pubPEM = genOpenSSLECDSAPub(oid, ecpub);\n pubSSH = genOpenSSHECDSAPub(oid, ecpub);\n privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv);\n break;\n }\n default:\n return new Error(`Unsupported OpenSSH private key type: ${type}`);\n }\n\n const privComment = readString(data, data._pos, true);\n if (privComment === undefined)\n return new Error('Malformed OpenSSH private key');\n\n keys.push(\n new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo,\n decrypted)\n );\n }\n let cnt = 0;\n for (i = data._pos; i < data.length; ++i) {\n if (data[i] !== (++cnt % 255))\n return new Error('Malformed OpenSSH private key');\n }\n\n return keys;\n }\n}\n\n\nfunction OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo,\n decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nOpenSSH_Old_Private.prototype = BaseKey;\n{\n const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\\r\\n|\\n)((?:[^:]+:\\s*[\\S].*(?:\\r\\n|\\n))*)([\\s\\S]+)(?:\\r\\n|\\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/;\n OpenSSH_Old_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n let privBlob = Buffer.from(m[3], 'base64');\n let headers = m[2];\n let decrypted = false;\n if (headers !== undefined) {\n // encrypted key\n headers = headers.split(/\\r\\n|\\n/g);\n for (let i = 0; i < headers.length; ++i) {\n const header = headers[i];\n let sepIdx = header.indexOf(':');\n if (header.slice(0, sepIdx) === 'DEK-Info') {\n const val = header.slice(sepIdx + 2);\n sepIdx = val.indexOf(',');\n if (sepIdx === -1)\n continue;\n const cipherName = val.slice(0, sepIdx).toLowerCase();\n if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) {\n return new Error(\n `Cipher (${cipherName}) not supported `\n + 'for encrypted OpenSSH private key'\n );\n }\n const encInfo = CIPHER_INFO_OPENSSL[cipherName];\n if (!encInfo) {\n return new Error(\n `Cipher (${cipherName}) not supported `\n + 'for encrypted OpenSSH private key'\n );\n }\n const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex');\n if (cipherIV.length !== encInfo.ivLen)\n return new Error('Malformed encrypted OpenSSH private key');\n if (!passphrase) {\n return new Error(\n 'Encrypted OpenSSH private key detected, but no passphrase given'\n );\n }\n const ivSlice = bufferSlice(cipherIV, 0, 8);\n let cipherKey = createHash('md5')\n .update(passphrase)\n .update(ivSlice)\n .digest();\n while (cipherKey.length < encInfo.keyLen) {\n cipherKey = combineBuffers(\n cipherKey,\n createHash('md5')\n .update(cipherKey)\n .update(passphrase)\n .update(ivSlice)\n .digest()\n );\n }\n if (cipherKey.length > encInfo.keyLen)\n cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen);\n try {\n const decipher = createDecipheriv(cipherName, cipherKey, cipherIV);\n decipher.setAutoPadding(false);\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n decrypted = true;\n } catch (ex) {\n return ex;\n }\n }\n }\n }\n\n let type;\n let privPEM;\n let pubPEM;\n let pubSSH;\n let algo;\n let reader;\n let errMsg = 'Malformed OpenSSH private key';\n if (decrypted)\n errMsg += '. Bad passphrase?';\n switch (m[1]) {\n case 'RSA':\n type = 'ssh-rsa';\n privPEM = makePEM('RSA PRIVATE', privBlob);\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n const n = reader.readString(Ber.Integer, true);\n if (n === null)\n return new Error(errMsg);\n const e = reader.readString(Ber.Integer, true);\n if (e === null)\n return new Error(errMsg);\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n } catch {\n return new Error(errMsg);\n }\n algo = 'sha1';\n break;\n case 'DSA':\n type = 'ssh-dss';\n privPEM = makePEM('DSA PRIVATE', privBlob);\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n const p = reader.readString(Ber.Integer, true);\n if (p === null)\n return new Error(errMsg);\n const q = reader.readString(Ber.Integer, true);\n if (q === null)\n return new Error(errMsg);\n const g = reader.readString(Ber.Integer, true);\n if (g === null)\n return new Error(errMsg);\n const y = reader.readString(Ber.Integer, true);\n if (y === null)\n return new Error(errMsg);\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n } catch {\n return new Error(errMsg);\n }\n algo = 'sha1';\n break;\n case 'EC': {\n let ecSSLName;\n let ecPriv;\n let ecOID;\n try {\n reader = new Ber.Reader(privBlob);\n reader.readSequence();\n reader.readInt(); // skip version\n ecPriv = reader.readString(Ber.OctetString, true);\n reader.readByte(); // Skip \"complex\" context type byte\n const offset = reader.readLength(); // Skip context length\n if (offset !== null) {\n reader._offset = offset;\n ecOID = reader.readOID();\n if (ecOID === null)\n return new Error(errMsg);\n switch (ecOID) {\n case '1.2.840.10045.3.1.7':\n // prime256v1/secp256r1\n ecSSLName = 'prime256v1';\n type = 'ecdsa-sha2-nistp256';\n algo = 'sha256';\n break;\n case '1.3.132.0.34':\n // secp384r1\n ecSSLName = 'secp384r1';\n type = 'ecdsa-sha2-nistp384';\n algo = 'sha384';\n break;\n case '1.3.132.0.35':\n // secp521r1\n ecSSLName = 'secp521r1';\n type = 'ecdsa-sha2-nistp521';\n algo = 'sha512';\n break;\n default:\n return new Error(`Unsupported private key EC OID: ${ecOID}`);\n }\n } else {\n return new Error(errMsg);\n }\n } catch {\n return new Error(errMsg);\n }\n privPEM = makePEM('EC PRIVATE', privBlob);\n const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv);\n pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob);\n pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob);\n break;\n }\n }\n\n return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo,\n decrypted);\n };\n}\n\n\nfunction PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = privPEM;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = decrypted;\n}\nPPK_Private.prototype = BaseKey;\n{\n const EMPTY_PASSPHRASE = Buffer.alloc(0);\n const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n const PPK_PP1 = Buffer.from([0, 0, 0, 0]);\n const PPK_PP2 = Buffer.from([0, 0, 0, 1]);\n const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\\r?\\nEncryption: (aes256-cbc|none)\\r?\\nComment: ([^\\r\\n]*)\\r?\\nPublic-Lines: \\d+\\r?\\n([\\s\\S]+?)\\r?\\nPrivate-Lines: \\d+\\r?\\n([\\s\\S]+?)\\r?\\nPrivate-MAC: ([^\\r\\n]+)/;\n PPK_Private.parse = (str, passphrase) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n // m[1] = key type\n // m[2] = encryption type\n // m[3] = comment\n // m[4] = base64-encoded public key data:\n // for \"ssh-rsa\":\n // string \"ssh-rsa\"\n // mpint e (public exponent)\n // mpint n (modulus)\n // for \"ssh-dss\":\n // string \"ssh-dss\"\n // mpint p (modulus)\n // mpint q (prime)\n // mpint g (base number)\n // mpint y (public key parameter: g^x mod p)\n // m[5] = base64-encoded private key data:\n // for \"ssh-rsa\":\n // mpint d (private exponent)\n // mpint p (prime 1)\n // mpint q (prime 2)\n // mpint iqmp ([inverse of q] mod p)\n // for \"ssh-dss\":\n // mpint x (private key parameter)\n // m[6] = SHA1 HMAC over:\n // string name of algorithm (\"ssh-dss\", \"ssh-rsa\")\n // string encryption type\n // string comment\n // string public key data\n // string private-plaintext (including the final padding)\n const cipherName = m[2];\n const encrypted = (cipherName !== 'none');\n if (encrypted && !passphrase) {\n return new Error(\n 'Encrypted PPK private key detected, but no passphrase given'\n );\n }\n\n let privBlob = Buffer.from(m[5], 'base64');\n\n if (encrypted) {\n const encInfo = CIPHER_INFO[cipherName];\n let cipherKey = combineBuffers(\n createHash('sha1').update(PPK_PP1).update(passphrase).digest(),\n createHash('sha1').update(PPK_PP2).update(passphrase).digest()\n );\n if (cipherKey.length > encInfo.keyLen)\n cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen);\n try {\n const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV);\n decipher.setAutoPadding(false);\n privBlob = combineBuffers(decipher.update(privBlob),\n decipher.final());\n } catch (ex) {\n return ex;\n }\n }\n\n const type = m[1];\n const comment = m[3];\n const pubBlob = Buffer.from(m[4], 'base64');\n\n const mac = m[6];\n const typeLen = type.length;\n const cipherNameLen = cipherName.length;\n const commentLen = Buffer.byteLength(comment);\n const pubLen = pubBlob.length;\n const privLen = privBlob.length;\n const macData = Buffer.allocUnsafe(4 + typeLen\n + 4 + cipherNameLen\n + 4 + commentLen\n + 4 + pubLen\n + 4 + privLen);\n let p = 0;\n\n writeUInt32BE(macData, typeLen, p);\n macData.utf8Write(type, p += 4, typeLen);\n writeUInt32BE(macData, cipherNameLen, p += typeLen);\n macData.utf8Write(cipherName, p += 4, cipherNameLen);\n writeUInt32BE(macData, commentLen, p += cipherNameLen);\n macData.utf8Write(comment, p += 4, commentLen);\n writeUInt32BE(macData, pubLen, p += commentLen);\n macData.set(pubBlob, p += 4);\n writeUInt32BE(macData, privLen, p += pubLen);\n macData.set(privBlob, p + 4);\n\n if (!passphrase)\n passphrase = EMPTY_PASSPHRASE;\n\n const calcMAC = createHmac(\n 'sha1',\n createHash('sha1')\n .update('putty-private-key-file-mac-key')\n .update(passphrase)\n .digest()\n ).update(macData).digest('hex');\n\n if (calcMAC !== mac) {\n if (encrypted) {\n return new Error(\n 'PPK private key integrity check failed -- bad passphrase?'\n );\n }\n return new Error('PPK private key integrity check failed');\n }\n\n let pubPEM;\n let pubSSH;\n let privPEM;\n pubBlob._pos = 0;\n skipFields(pubBlob, 1); // skip (duplicate) key type\n switch (type) {\n case 'ssh-rsa': {\n const e = readString(pubBlob, pubBlob._pos);\n if (e === undefined)\n return new Error('Malformed PPK public key');\n const n = readString(pubBlob, pubBlob._pos);\n if (n === undefined)\n return new Error('Malformed PPK public key');\n const d = readString(privBlob, 0);\n if (d === undefined)\n return new Error('Malformed PPK private key');\n const p = readString(privBlob, privBlob._pos);\n if (p === undefined)\n return new Error('Malformed PPK private key');\n const q = readString(privBlob, privBlob._pos);\n if (q === undefined)\n return new Error('Malformed PPK private key');\n const iqmp = readString(privBlob, privBlob._pos);\n if (iqmp === undefined)\n return new Error('Malformed PPK private key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q);\n break;\n }\n case 'ssh-dss': {\n const p = readString(pubBlob, pubBlob._pos);\n if (p === undefined)\n return new Error('Malformed PPK public key');\n const q = readString(pubBlob, pubBlob._pos);\n if (q === undefined)\n return new Error('Malformed PPK public key');\n const g = readString(pubBlob, pubBlob._pos);\n if (g === undefined)\n return new Error('Malformed PPK public key');\n const y = readString(pubBlob, pubBlob._pos);\n if (y === undefined)\n return new Error('Malformed PPK public key');\n const x = readString(privBlob, 0);\n if (x === undefined)\n return new Error('Malformed PPK private key');\n\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n privPEM = genOpenSSLDSAPriv(p, q, g, y, x);\n break;\n }\n }\n\n return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1',\n encrypted);\n };\n}\n\n\nfunction OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = null;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = false;\n}\nOpenSSH_Public.prototype = BaseKey;\n{\n let regexp;\n if (eddsaSupported)\n regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\\s+([\\S].*)?)$/;\n else\n regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\\s+([\\S].*)?)$/;\n OpenSSH_Public.parse = (str) => {\n const m = regexp.exec(str);\n if (m === null)\n return null;\n // m[1] = full type\n // m[2] = base type\n // m[3] = base64-encoded public key\n // m[4] = comment\n\n const fullType = m[1];\n const baseType = m[2];\n const data = Buffer.from(m[3], 'base64');\n const comment = (m[4] || '');\n\n const type = readString(data, data._pos, true);\n if (type === undefined || type.indexOf(baseType) !== 0)\n return new Error('Malformed OpenSSH public key');\n\n return parseDER(data, baseType, comment, fullType);\n };\n}\n\n\nfunction RFC4716_Public(type, comment, pubPEM, pubSSH, algo) {\n this.type = type;\n this.comment = comment;\n this[SYM_PRIV_PEM] = null;\n this[SYM_PUB_PEM] = pubPEM;\n this[SYM_PUB_SSH] = pubSSH;\n this[SYM_HASH_ALGO] = algo;\n this[SYM_DECRYPTED] = false;\n}\nRFC4716_Public.prototype = BaseKey;\n{\n const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\\r?\\n)((?:.{0,72}\\r?\\n)+)---- END SSH2 PUBLIC KEY ----$/;\n const RE_DATA = /^[A-Z0-9a-z/+=\\r\\n]+$/;\n const RE_HEADER = /^([\\x21-\\x39\\x3B-\\x7E]{1,64}): ((?:[^\\\\]*\\\\\\r?\\n)*[^\\r\\n]+)\\r?\\n/gm;\n const RE_HEADER_ENDS = /\\\\\\r?\\n/g;\n RFC4716_Public.parse = (str) => {\n let m = regexp.exec(str);\n if (m === null)\n return null;\n\n const body = m[1];\n let dataStart = 0;\n let comment = '';\n\n while (m = RE_HEADER.exec(body)) {\n const headerName = m[1];\n const headerValue = m[2].replace(RE_HEADER_ENDS, '');\n if (headerValue.length > 1024) {\n RE_HEADER.lastIndex = 0;\n return new Error('Malformed RFC4716 public key');\n }\n\n dataStart = RE_HEADER.lastIndex;\n\n if (headerName.toLowerCase() === 'comment') {\n comment = headerValue;\n if (comment.length > 1\n && comment.charCodeAt(0) === 34/* '\"' */\n && comment.charCodeAt(comment.length - 1) === 34/* '\"' */) {\n comment = comment.slice(1, -1);\n }\n }\n }\n\n let data = body.slice(dataStart);\n if (!RE_DATA.test(data))\n return new Error('Malformed RFC4716 public key');\n\n data = Buffer.from(data, 'base64');\n\n const type = readString(data, 0, true);\n if (type === undefined)\n return new Error('Malformed RFC4716 public key');\n\n let pubPEM = null;\n let pubSSH = null;\n switch (type) {\n case 'ssh-rsa': {\n const e = readString(data, data._pos);\n if (e === undefined)\n return new Error('Malformed RFC4716 public key');\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed RFC4716 public key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n break;\n }\n case 'ssh-dss': {\n const p = readString(data, data._pos);\n if (p === undefined)\n return new Error('Malformed RFC4716 public key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed RFC4716 public key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed RFC4716 public key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed RFC4716 public key');\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n break;\n }\n default:\n return new Error('Malformed RFC4716 public key');\n }\n\n return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1');\n };\n}\n\n\nfunction parseDER(data, baseType, comment, fullType) {\n if (!isSupportedKeyType(baseType))\n return new Error(`Unsupported OpenSSH public key type: ${baseType}`);\n\n let algo;\n let oid;\n let pubPEM = null;\n let pubSSH = null;\n\n switch (baseType) {\n case 'ssh-rsa': {\n const e = readString(data, data._pos || 0);\n if (e === undefined)\n return new Error('Malformed OpenSSH public key');\n const n = readString(data, data._pos);\n if (n === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLRSAPub(n, e);\n pubSSH = genOpenSSHRSAPub(n, e);\n algo = 'sha1';\n break;\n }\n case 'ssh-dss': {\n const p = readString(data, data._pos || 0);\n if (p === undefined)\n return new Error('Malformed OpenSSH public key');\n const q = readString(data, data._pos);\n if (q === undefined)\n return new Error('Malformed OpenSSH public key');\n const g = readString(data, data._pos);\n if (g === undefined)\n return new Error('Malformed OpenSSH public key');\n const y = readString(data, data._pos);\n if (y === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLDSAPub(p, q, g, y);\n pubSSH = genOpenSSHDSAPub(p, q, g, y);\n algo = 'sha1';\n break;\n }\n case 'ssh-ed25519': {\n const edpub = readString(data, data._pos || 0);\n if (edpub === undefined || edpub.length !== 32)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLEdPub(edpub);\n pubSSH = genOpenSSHEdPub(edpub);\n algo = null;\n break;\n }\n case 'ecdsa-sha2-nistp256':\n algo = 'sha256';\n oid = '1.2.840.10045.3.1.7';\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp384':\n if (algo === undefined) {\n algo = 'sha384';\n oid = '1.3.132.0.34';\n }\n // FALLTHROUGH\n case 'ecdsa-sha2-nistp521': {\n if (algo === undefined) {\n algo = 'sha512';\n oid = '1.3.132.0.35';\n }\n // TODO: validate curve name against type\n if (!skipFields(data, 1)) // Skip curve name\n return new Error('Malformed OpenSSH public key');\n const ecpub = readString(data, data._pos || 0);\n if (ecpub === undefined)\n return new Error('Malformed OpenSSH public key');\n pubPEM = genOpenSSLECDSAPub(oid, ecpub);\n pubSSH = genOpenSSHECDSAPub(oid, ecpub);\n break;\n }\n default:\n return new Error(`Unsupported OpenSSH public key type: ${baseType}`);\n }\n\n return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo);\n}\n\nfunction isSupportedKeyType(type) {\n switch (type) {\n case 'ssh-rsa':\n case 'ssh-dss':\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521':\n return true;\n case 'ssh-ed25519':\n if (eddsaSupported)\n return true;\n // FALLTHROUGH\n default:\n return false;\n }\n}\n\nfunction isParsedKey(val) {\n if (!val)\n return false;\n return (typeof val[SYM_DECRYPTED] === 'boolean');\n}\n\nfunction parseKey(data, passphrase) {\n if (isParsedKey(data))\n return data;\n\n let origBuffer;\n if (Buffer.isBuffer(data)) {\n origBuffer = data;\n data = data.utf8Slice(0, data.length).trim();\n } else if (typeof data === 'string') {\n data = data.trim();\n } else {\n return new Error('Key data must be a Buffer or string');\n }\n\n // eslint-disable-next-line eqeqeq\n if (passphrase != undefined) {\n if (typeof passphrase === 'string')\n passphrase = Buffer.from(passphrase);\n else if (!Buffer.isBuffer(passphrase))\n return new Error('Passphrase must be a string or Buffer when supplied');\n }\n\n let ret;\n\n // First try as printable string format (e.g. PEM)\n\n // Private keys\n if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null)\n return ret;\n if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null)\n return ret;\n if ((ret = PPK_Private.parse(data, passphrase)) !== null)\n return ret;\n\n // Public keys\n if ((ret = OpenSSH_Public.parse(data)) !== null)\n return ret;\n if ((ret = RFC4716_Public.parse(data)) !== null)\n return ret;\n\n // Finally try as a binary format if we were originally passed binary data\n if (origBuffer) {\n binaryKeyParser.init(origBuffer, 0);\n const type = binaryKeyParser.readString(true);\n if (type !== undefined) {\n data = binaryKeyParser.readRaw();\n if (data !== undefined) {\n ret = parseDER(data, type, '', type);\n // Ignore potentially useless errors in case the data was not actually\n // in the binary format\n if (ret instanceof Error)\n ret = null;\n }\n }\n binaryKeyParser.clear();\n }\n\n if (ret)\n return ret;\n\n return new Error('Unsupported key format');\n}\n\nmodule.exports = {\n isParsedKey,\n isSupportedKeyType,\n parseDERKey: (data, type) => parseDER(data, type, '', type),\n parseKey,\n};\n","'use strict';\n\nconst assert = require('assert');\nconst { inspect } = require('util');\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n let res = '';\n let i = val.length;\n const start = val[0] === '-' ? 1 : 0;\n for (; i >= start + 4; i -= 3)\n res = `_${val.slice(i - 3, i)}${res}`;\n return `${val.slice(0, i)}${res}`;\n}\n\nfunction oneOf(expected, thing) {\n assert(typeof thing === 'string', '`thing` has to be of type string');\n if (Array.isArray(expected)) {\n const len = expected.length;\n assert(len > 0, 'At least one expected value needs to be specified');\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or `\n + expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n }\n return `of ${thing} ${expected[0]}`;\n }\n return `of ${thing} ${String(expected)}`;\n}\n\n\nexports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error {\n constructor(message) {\n super();\n Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION);\n\n const suffix = 'This is caused by either a bug in ssh2 '\n + 'or incorrect usage of ssh2 internals.\\n'\n + 'Please open an issue with this stack trace at '\n + 'https://github.com/mscdex/ssh2/issues\\n';\n\n this.message = (message === undefined ? suffix : `${message}\\n${suffix}`);\n }\n};\n\nconst MAX_32BIT_INT = 2 ** 32;\nconst MAX_32BIT_BIGINT = (() => {\n try {\n return new Function('return 2n ** 32n')();\n } catch {}\n})();\nexports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError {\n constructor(str, range, input, replaceDefaultBoolean) {\n super();\n Error.captureStackTrace(this, ERR_OUT_OF_RANGE);\n\n assert(range, 'Missing \"range\" argument');\n let msg = (replaceDefaultBoolean\n ? str\n : `The value of \"${str}\" is out of range.`);\n let received;\n if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) {\n received = addNumericalSeparator(String(input));\n } else if (typeof input === 'bigint') {\n received = String(input);\n if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT)\n received = addNumericalSeparator(received);\n received += 'n';\n } else {\n received = inspect(input);\n }\n msg += ` It must be ${range}. Received ${received}`;\n\n this.message = msg;\n }\n};\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super();\n Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE);\n\n assert(typeof name === 'string', `'name' must be a string`);\n\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && expected.startsWith('not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (name.endsWith(' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = (name.includes('.') ? 'property' : 'argument');\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n\n this.message = msg;\n }\n}\nexports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE;\n\nexports.validateNumber = function validateNumber(value, name) {\n if (typeof value !== 'number')\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value);\n};\n","'use strict';\n\nconst Ber = require('asn1').Ber;\n\nlet DISCONNECT_REASON;\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill;\n\nfunction readUInt32BE(buf, offset) {\n return (buf[offset++] * 16777216)\n + (buf[offset++] * 65536)\n + (buf[offset++] * 256)\n + buf[offset];\n}\n\nfunction bufferCopy(src, dest, srcStart, srcEnd, destStart) {\n if (!destStart)\n destStart = 0;\n if (srcEnd > src.length)\n srcEnd = src.length;\n let nb = srcEnd - srcStart;\n const destLeft = (dest.length - destStart);\n if (nb > destLeft)\n nb = destLeft;\n dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb),\n destStart);\n return nb;\n}\n\nfunction bufferSlice(buf, start, end) {\n if (end === undefined)\n end = buf.length;\n return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start);\n}\n\nfunction makeBufferParser() {\n let pos = 0;\n let buffer;\n\n const self = {\n init: (buf, start) => {\n buffer = buf;\n pos = (typeof start === 'number' ? start : 0);\n },\n pos: () => pos,\n length: () => (buffer ? buffer.length : 0),\n avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0),\n clear: () => {\n buffer = undefined;\n },\n readUInt32BE: () => {\n if (!buffer || pos + 3 >= buffer.length)\n return;\n return (buffer[pos++] * 16777216)\n + (buffer[pos++] * 65536)\n + (buffer[pos++] * 256)\n + buffer[pos++];\n },\n readUInt64BE: (behavior) => {\n if (!buffer || pos + 7 >= buffer.length)\n return;\n switch (behavior) {\n case 'always':\n return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`);\n case 'maybe':\n if (buffer[pos] > 0x1F)\n return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`);\n // FALLTHROUGH\n default:\n return (buffer[pos++] * 72057594037927940)\n + (buffer[pos++] * 281474976710656)\n + (buffer[pos++] * 1099511627776)\n + (buffer[pos++] * 4294967296)\n + (buffer[pos++] * 16777216)\n + (buffer[pos++] * 65536)\n + (buffer[pos++] * 256)\n + buffer[pos++];\n }\n },\n skip: (n) => {\n if (buffer && n > 0)\n pos += n;\n },\n skipString: () => {\n const len = self.readUInt32BE();\n if (len === undefined)\n return;\n pos += len;\n return (pos <= buffer.length ? len : undefined);\n },\n readByte: () => {\n if (buffer && pos < buffer.length)\n return buffer[pos++];\n },\n readBool: () => {\n if (buffer && pos < buffer.length)\n return !!buffer[pos++];\n },\n readList: () => {\n const list = self.readString(true);\n if (list === undefined)\n return;\n return (list ? list.split(',') : []);\n },\n readString: (dest, maxLen) => {\n if (typeof dest === 'number') {\n maxLen = dest;\n dest = undefined;\n }\n\n const len = self.readUInt32BE();\n if (len === undefined)\n return;\n\n if ((buffer.length - pos) < len\n || (typeof maxLen === 'number' && len > maxLen)) {\n return;\n }\n\n if (dest) {\n if (Buffer.isBuffer(dest))\n return bufferCopy(buffer, dest, pos, pos += len);\n return buffer.utf8Slice(pos, pos += len);\n }\n return bufferSlice(buffer, pos, pos += len);\n },\n readRaw: (len) => {\n if (!buffer)\n return;\n if (typeof len !== 'number')\n return bufferSlice(buffer, pos, pos += (buffer.length - pos));\n if ((buffer.length - pos) >= len)\n return bufferSlice(buffer, pos, pos += len);\n },\n };\n\n return self;\n}\n\nfunction makeError(msg, level, fatal) {\n const err = new Error(msg);\n if (typeof level === 'boolean') {\n fatal = level;\n err.level = 'protocol';\n } else {\n err.level = level || 'protocol';\n }\n err.fatal = !!fatal;\n return err;\n}\n\nfunction writeUInt32BE(buf, value, offset) {\n buf[offset++] = (value >>> 24);\n buf[offset++] = (value >>> 16);\n buf[offset++] = (value >>> 8);\n buf[offset++] = value;\n return offset;\n}\n\nconst utilBufferParser = makeBufferParser();\n\nmodule.exports = {\n bufferCopy,\n bufferSlice,\n FastBuffer,\n bufferFill: (buf, value, start, end) => {\n return TypedArrayFill.call(buf, value, start, end);\n },\n makeError,\n doFatalError: (protocol, msg, level, reason) => {\n let err;\n if (DISCONNECT_REASON === undefined)\n ({ DISCONNECT_REASON } = require('./constants.js'));\n if (msg instanceof Error) {\n // doFatalError(protocol, err[, reason])\n err = msg;\n if (typeof level !== 'number')\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n else\n reason = level;\n } else {\n // doFatalError(protocol, msg[, level[, reason]])\n err = makeError(msg, level, true);\n }\n if (typeof reason !== 'number')\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n protocol.disconnect(reason);\n protocol._destruct();\n protocol._onError(err);\n return Infinity;\n },\n readUInt32BE,\n writeUInt32BE,\n writeUInt32LE: (buf, value, offset) => {\n buf[offset++] = value;\n buf[offset++] = (value >>> 8);\n buf[offset++] = (value >>> 16);\n buf[offset++] = (value >>> 24);\n return offset;\n },\n makeBufferParser,\n bufferParser: makeBufferParser(),\n readString: (buffer, start, dest, maxLen) => {\n if (typeof dest === 'number') {\n maxLen = dest;\n dest = undefined;\n }\n\n if (start === undefined)\n start = 0;\n\n const left = (buffer.length - start);\n if (start < 0 || start >= buffer.length || left < 4)\n return;\n\n const len = readUInt32BE(buffer, start);\n if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen))\n return;\n\n start += 4;\n const end = start + len;\n buffer._pos = end;\n\n if (dest) {\n if (Buffer.isBuffer(dest))\n return bufferCopy(buffer, dest, start, end);\n return buffer.utf8Slice(start, end);\n }\n return bufferSlice(buffer, start, end);\n },\n sigSSHToASN1: (sig, type) => {\n switch (type) {\n case 'ssh-dss': {\n if (sig.length > 40)\n return sig;\n // Change bare signature r and s values to ASN.1 BER values for OpenSSL\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n let r = sig.slice(0, 20);\n let s = sig.slice(20);\n if (r[0] & 0x80) {\n const rNew = Buffer.allocUnsafe(21);\n rNew[0] = 0x00;\n r.copy(rNew, 1);\n r = rNew;\n } else if (r[0] === 0x00 && !(r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] & 0x80) {\n const sNew = Buffer.allocUnsafe(21);\n sNew[0] = 0x00;\n s.copy(sNew, 1);\n s = sNew;\n } else if (s[0] === 0x00 && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n asnWriter.writeBuffer(r, Ber.Integer);\n asnWriter.writeBuffer(s, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521': {\n utilBufferParser.init(sig, 0);\n const r = utilBufferParser.readString();\n const s = utilBufferParser.readString();\n utilBufferParser.clear();\n if (r === undefined || s === undefined)\n return;\n\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n asnWriter.writeBuffer(r, Ber.Integer);\n asnWriter.writeBuffer(s, Ber.Integer);\n asnWriter.endSequence();\n return asnWriter.buffer;\n }\n default:\n return sig;\n }\n },\n convertSignature: (signature, keyType) => {\n switch (keyType) {\n case 'ssh-dss': {\n if (signature.length <= 40)\n return signature;\n // This is a quick and dirty way to get from BER encoded r and s that\n // OpenSSL gives us, to just the bare values back to back (40 bytes\n // total) like OpenSSH (and possibly others) are expecting\n const asnReader = new Ber.Reader(signature);\n asnReader.readSequence();\n let r = asnReader.readString(Ber.Integer, true);\n let s = asnReader.readString(Ber.Integer, true);\n let rOffset = 0;\n let sOffset = 0;\n if (r.length < 20) {\n const rNew = Buffer.allocUnsafe(20);\n rNew.set(r, 1);\n r = rNew;\n r[0] = 0;\n }\n if (s.length < 20) {\n const sNew = Buffer.allocUnsafe(20);\n sNew.set(s, 1);\n s = sNew;\n s[0] = 0;\n }\n if (r.length > 20 && r[0] === 0)\n rOffset = 1;\n if (s.length > 20 && s[0] === 0)\n sOffset = 1;\n const newSig =\n Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset));\n bufferCopy(r, newSig, rOffset, r.length, 0);\n bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset);\n return newSig;\n }\n case 'ecdsa-sha2-nistp256':\n case 'ecdsa-sha2-nistp384':\n case 'ecdsa-sha2-nistp521': {\n if (signature[0] === 0)\n return signature;\n // Convert SSH signature parameters to ASN.1 BER values for OpenSSL\n const asnReader = new Ber.Reader(signature);\n asnReader.readSequence();\n const r = asnReader.readString(Ber.Integer, true);\n const s = asnReader.readString(Ber.Integer, true);\n if (r === null || s === null)\n return;\n const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length);\n writeUInt32BE(newSig, r.length, 0);\n newSig.set(r, 4);\n writeUInt32BE(newSig, s.length, 4 + r.length);\n newSig.set(s, 4 + 4 + r.length);\n return newSig;\n }\n }\n\n return signature;\n },\n sendPacket: (proto, packet, bypass) => {\n if (!bypass && proto._kexinit !== undefined) {\n // We're currently in the middle of a handshake\n\n if (proto._queue === undefined)\n proto._queue = [];\n proto._queue.push(packet);\n proto._debug && proto._debug('Outbound: ... packet queued');\n return false;\n }\n proto._cipher.encrypt(packet);\n return true;\n },\n};\n","'use strict';\n\nconst { kMaxLength } = require('buffer');\nconst {\n createInflate,\n constants: {\n DEFLATE,\n INFLATE,\n Z_DEFAULT_CHUNK,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_MEMLEVEL,\n Z_DEFAULT_STRATEGY,\n Z_DEFAULT_WINDOWBITS,\n Z_PARTIAL_FLUSH,\n }\n} = require('zlib');\nconst ZlibHandle = createInflate()._handle.constructor;\n\nfunction processCallback() {\n throw new Error('Should not get here');\n}\n\nfunction zlibOnError(message, errno, code) {\n const self = this._owner;\n // There is no way to cleanly recover.\n // Continuing only obscures problems.\n\n const error = new Error(message);\n error.errno = errno;\n error.code = code;\n self._err = error;\n}\n\nfunction _close(engine) {\n // Caller may invoke .close after a zlib error (which will null _handle).\n if (!engine._handle)\n return;\n\n engine._handle.close();\n engine._handle = null;\n}\n\nclass Zlib {\n constructor(mode) {\n const windowBits = Z_DEFAULT_WINDOWBITS;\n const level = Z_DEFAULT_COMPRESSION;\n const memLevel = Z_DEFAULT_MEMLEVEL;\n const strategy = Z_DEFAULT_STRATEGY;\n const dictionary = undefined;\n\n this._err = undefined;\n this._writeState = new Uint32Array(2);\n this._chunkSize = Z_DEFAULT_CHUNK;\n this._maxOutputLength = kMaxLength;\n this._outBuffer = Buffer.allocUnsafe(this._chunkSize);\n this._outOffset = 0;\n\n this._handle = new ZlibHandle(mode);\n this._handle._owner = this;\n this._handle.onerror = zlibOnError;\n this._handle.init(windowBits,\n level,\n memLevel,\n strategy,\n this._writeState,\n processCallback,\n dictionary);\n }\n\n writeSync(chunk, retChunks) {\n const handle = this._handle;\n if (!handle)\n throw new Error('Invalid Zlib instance');\n\n let availInBefore = chunk.length;\n let availOutBefore = this._chunkSize - this._outOffset;\n let inOff = 0;\n let availOutAfter;\n let availInAfter;\n\n let buffers;\n let nread = 0;\n const state = this._writeState;\n let buffer = this._outBuffer;\n let offset = this._outOffset;\n const chunkSize = this._chunkSize;\n\n while (true) {\n handle.writeSync(Z_PARTIAL_FLUSH,\n chunk, // in\n inOff, // in_off\n availInBefore, // in_len\n buffer, // out\n offset, // out_off\n availOutBefore); // out_len\n if (this._err)\n throw this._err;\n\n availOutAfter = state[0];\n availInAfter = state[1];\n\n const inDelta = availInBefore - availInAfter;\n const have = availOutBefore - availOutAfter;\n\n if (have > 0) {\n const out = (offset === 0 && have === buffer.length\n ? buffer\n : buffer.slice(offset, offset + have));\n offset += have;\n if (!buffers)\n buffers = out;\n else if (buffers.push === undefined)\n buffers = [buffers, out];\n else\n buffers.push(out);\n nread += out.byteLength;\n\n if (nread > this._maxOutputLength) {\n _close(this);\n throw new Error(\n `Output length exceeded maximum of ${this._maxOutputLength}`\n );\n }\n } else if (have !== 0) {\n throw new Error('have should not go down');\n }\n\n // Exhausted the output buffer, or used all the input create a new one.\n if (availOutAfter === 0 || offset >= chunkSize) {\n availOutBefore = chunkSize;\n offset = 0;\n buffer = Buffer.allocUnsafe(chunkSize);\n }\n\n if (availOutAfter === 0) {\n // Not actually done. Need to reprocess.\n // Also, update the availInBefore to the availInAfter value,\n // so that if we have to hit it a third (fourth, etc.) time,\n // it'll have the correct byte counts.\n inOff += inDelta;\n availInBefore = availInAfter;\n } else {\n break;\n }\n }\n\n this._outBuffer = buffer;\n this._outOffset = offset;\n\n if (nread === 0)\n buffers = Buffer.alloc(0);\n\n if (retChunks) {\n buffers.totalLen = nread;\n return buffers;\n }\n\n if (buffers.push === undefined)\n return buffers;\n\n const output = Buffer.allocUnsafe(nread);\n for (let i = 0, p = 0; i < buffers.length; ++i) {\n const buf = buffers[i];\n output.set(buf, p);\n p += buf.length;\n }\n return output;\n }\n}\n\nclass ZlibPacketWriter {\n constructor(protocol) {\n this.allocStart = 0;\n this.allocStartKEX = 0;\n this._protocol = protocol;\n this._zlib = new Zlib(DEFLATE);\n }\n\n cleanup() {\n if (this._zlib)\n _close(this._zlib);\n }\n\n alloc(payloadSize, force) {\n return Buffer.allocUnsafe(payloadSize);\n }\n\n finalize(payload, force) {\n if (this._protocol._kexinit === undefined || force) {\n const output = this._zlib.writeSync(payload, true);\n const packet = this._protocol._cipher.allocPacket(output.totalLen);\n if (output.push === undefined) {\n packet.set(output, 5);\n } else {\n for (let i = 0, p = 5; i < output.length; ++i) {\n const chunk = output[i];\n packet.set(chunk, p);\n p += chunk.length;\n }\n }\n return packet;\n }\n return payload;\n }\n}\n\nclass PacketWriter {\n constructor(protocol) {\n this.allocStart = 5;\n this.allocStartKEX = 5;\n this._protocol = protocol;\n }\n\n cleanup() {}\n\n alloc(payloadSize, force) {\n if (this._protocol._kexinit === undefined || force)\n return this._protocol._cipher.allocPacket(payloadSize);\n return Buffer.allocUnsafe(payloadSize);\n }\n\n finalize(packet, force) {\n return packet;\n }\n}\n\nclass ZlibPacketReader {\n constructor() {\n this._zlib = new Zlib(INFLATE);\n }\n\n cleanup() {\n if (this._zlib)\n _close(this._zlib);\n }\n\n read(data) {\n return this._zlib.writeSync(data, false);\n }\n}\n\nclass PacketReader {\n cleanup() {}\n\n read(data) {\n return data;\n }\n}\n\nmodule.exports = {\n PacketReader,\n PacketWriter,\n ZlibPacketReader,\n ZlibPacketWriter,\n};\n","// TODO:\n// * convert listenerCount() usage to emit() return value checking?\n// * emit error when connection severed early (e.g. before handshake)\n// * add '.connected' or similar property to connection objects to allow\n// immediate connection status checking\n'use strict';\n\nconst { Server: netServer } = require('net');\nconst EventEmitter = require('events');\nconst { listenerCount } = EventEmitter;\n\nconst {\n CHANNEL_OPEN_FAILURE,\n DEFAULT_CIPHER,\n DEFAULT_COMPRESSION,\n DEFAULT_KEX,\n DEFAULT_MAC,\n DEFAULT_SERVER_HOST_KEY,\n DISCONNECT_REASON,\n DISCONNECT_REASON_BY_VALUE,\n SUPPORTED_CIPHER,\n SUPPORTED_COMPRESSION,\n SUPPORTED_KEX,\n SUPPORTED_MAC,\n SUPPORTED_SERVER_HOST_KEY,\n} = require('./protocol/constants.js');\nconst { init: cryptoInit } = require('./protocol/crypto.js');\nconst { KexInit } = require('./protocol/kex.js');\nconst { parseKey } = require('./protocol/keyParser.js');\nconst Protocol = require('./protocol/Protocol.js');\nconst { SFTP } = require('./protocol/SFTP.js');\nconst { writeUInt32BE } = require('./protocol/utils.js');\n\nconst {\n Channel,\n MAX_WINDOW,\n PACKET_SIZE,\n windowAdjust,\n WINDOW_THRESHOLD,\n} = require('./Channel.js');\n\nconst {\n ChannelManager,\n generateAlgorithmList,\n isWritable,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n} = require('./utils.js');\n\nconst MAX_PENDING_AUTHS = 10;\n\nclass AuthContext extends EventEmitter {\n constructor(protocol, username, service, method, cb) {\n super();\n\n this.username = this.user = username;\n this.service = service;\n this.method = method;\n this._initialResponse = false;\n this._finalResponse = false;\n this._multistep = false;\n this._cbfinal = (allowed, methodsLeft, isPartial) => {\n if (!this._finalResponse) {\n this._finalResponse = true;\n cb(this, allowed, methodsLeft, isPartial);\n }\n };\n this._protocol = protocol;\n }\n\n accept() {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(true);\n }\n reject(methodsLeft, isPartial) {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(false, methodsLeft, isPartial);\n }\n}\n\n\nclass KeyboardAuthContext extends AuthContext {\n constructor(protocol, username, service, method, submethods, cb) {\n super(protocol, username, service, method, cb);\n\n this._multistep = true;\n\n this._cb = undefined;\n this._onInfoResponse = (responses) => {\n const callback = this._cb;\n if (callback) {\n this._cb = undefined;\n callback(responses);\n }\n };\n this.submethods = submethods;\n this.on('abort', () => {\n this._cb && this._cb(new Error('Authentication request aborted'));\n });\n }\n\n prompt(prompts, title, instructions, cb) {\n if (!Array.isArray(prompts))\n prompts = [ prompts ];\n\n if (typeof title === 'function') {\n cb = title;\n title = instructions = undefined;\n } else if (typeof instructions === 'function') {\n cb = instructions;\n instructions = undefined;\n } else if (typeof cb !== 'function') {\n cb = undefined;\n }\n\n for (let i = 0; i < prompts.length; ++i) {\n if (typeof prompts[i] === 'string') {\n prompts[i] = {\n prompt: prompts[i],\n echo: true\n };\n }\n }\n\n this._cb = cb;\n this._initialResponse = true;\n\n this._protocol.authInfoReq(title, instructions, prompts);\n }\n}\n\nclass PKAuthContext extends AuthContext {\n constructor(protocol, username, service, method, pkInfo, cb) {\n super(protocol, username, service, method, cb);\n\n this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };\n this.hashAlgo = pkInfo.hashAlgo;\n this.signature = pkInfo.signature;\n this.blob = pkInfo.blob;\n }\n\n accept() {\n if (!this.signature) {\n this._initialResponse = true;\n this._protocol.authPKOK(this.key.algo, this.key.data);\n } else {\n AuthContext.prototype.accept.call(this);\n }\n }\n}\n\nclass HostbasedAuthContext extends AuthContext {\n constructor(protocol, username, service, method, pkInfo, cb) {\n super(protocol, username, service, method, cb);\n\n this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };\n this.hashAlgo = pkInfo.hashAlgo;\n this.signature = pkInfo.signature;\n this.blob = pkInfo.blob;\n this.localHostname = pkInfo.localHostname;\n this.localUsername = pkInfo.localUsername;\n }\n}\n\nclass PwdAuthContext extends AuthContext {\n constructor(protocol, username, service, method, password, cb) {\n super(protocol, username, service, method, cb);\n\n this.password = password;\n this._changeCb = undefined;\n }\n\n requestChange(prompt, cb) {\n if (this._changeCb)\n throw new Error('Change request already in progress');\n if (typeof prompt !== 'string')\n throw new Error('prompt argument must be a string');\n if (typeof cb !== 'function')\n throw new Error('Callback argument must be a function');\n this._changeCb = cb;\n this._protocol.authPasswdChg(prompt);\n }\n}\n\n\nclass Session extends EventEmitter {\n constructor(client, info, localChan) {\n super();\n\n this.type = 'session';\n this.subtype = undefined;\n this.server = true;\n this._ending = false;\n this._channel = undefined;\n this._chanInfo = {\n type: 'session',\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n }\n}\n\n\nclass Server extends EventEmitter {\n constructor(cfg, listener) {\n super();\n\n if (typeof cfg !== 'object' || cfg === null)\n throw new Error('Missing configuration object');\n\n const hostKeys = Object.create(null);\n const hostKeyAlgoOrder = [];\n\n const hostKeys_ = cfg.hostKeys;\n if (!Array.isArray(hostKeys_))\n throw new Error('hostKeys must be an array');\n\n const cfgAlgos = (\n typeof cfg.algorithms === 'object' && cfg.algorithms !== null\n ? cfg.algorithms\n : {}\n );\n\n const hostKeyAlgos = generateAlgorithmList(\n cfgAlgos.serverHostKey,\n DEFAULT_SERVER_HOST_KEY,\n SUPPORTED_SERVER_HOST_KEY\n );\n for (let i = 0; i < hostKeys_.length; ++i) {\n let privateKey;\n if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string')\n privateKey = parseKey(hostKeys_[i]);\n else\n privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase);\n\n if (privateKey instanceof Error)\n throw new Error(`Cannot parse privateKey: ${privateKey.message}`);\n\n if (Array.isArray(privateKey)) {\n // OpenSSH's newer format only stores 1 key for now\n privateKey = privateKey[0];\n }\n\n if (privateKey.getPrivatePEM() === null)\n throw new Error('privateKey value contains an invalid private key');\n\n // Discard key if we already found a key of the same type\n if (hostKeyAlgoOrder.includes(privateKey.type))\n continue;\n\n if (privateKey.type === 'ssh-rsa') {\n // SSH supports multiple signature hashing algorithms for RSA, so we add\n // the algorithms in the desired order\n let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa');\n const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256');\n const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512');\n if (sha1Pos === -1) {\n // Fall back to giving SHA1 the lowest priority\n sha1Pos = Infinity;\n }\n [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => {\n if (pos === -1)\n return;\n\n let type;\n switch (pos) {\n case sha1Pos: type = 'ssh-rsa'; break;\n case sha256Pos: type = 'rsa-sha2-256'; break;\n case sha512Pos: type = 'rsa-sha2-512'; break;\n default: return;\n }\n\n // Store same RSA key under each hash algorithm name for convenience\n hostKeys[type] = privateKey;\n\n hostKeyAlgoOrder.push(type);\n });\n } else {\n hostKeys[privateKey.type] = privateKey;\n hostKeyAlgoOrder.push(privateKey.type);\n }\n }\n\n const algorithms = {\n kex: generateAlgorithmList(\n cfgAlgos.kex,\n DEFAULT_KEX,\n SUPPORTED_KEX\n ).concat(['kex-strict-s-v00@openssh.com']),\n serverHostKey: hostKeyAlgoOrder,\n cs: {\n cipher: generateAlgorithmList(\n cfgAlgos.cipher,\n DEFAULT_CIPHER,\n SUPPORTED_CIPHER\n ),\n mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC),\n compress: generateAlgorithmList(\n cfgAlgos.compress,\n DEFAULT_COMPRESSION,\n SUPPORTED_COMPRESSION\n ),\n lang: [],\n },\n sc: undefined,\n };\n algorithms.sc = algorithms.cs;\n\n if (typeof listener === 'function')\n this.on('connection', listener);\n\n const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);\n const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined);\n const offer = new KexInit(algorithms);\n\n this._srv = new netServer((socket) => {\n if (this._connections >= this.maxConnections) {\n socket.destroy();\n return;\n }\n ++this._connections;\n socket.once('close', () => {\n --this._connections;\n });\n\n let debug;\n if (origDebug) {\n // Prepend debug output with a unique identifier in case there are\n // multiple clients connected at the same time\n const debugPrefix = `[${process.hrtime().join('.')}] `;\n debug = (msg) => {\n origDebug(`${debugPrefix}${msg}`);\n };\n }\n\n // eslint-disable-next-line no-use-before-define\n new Client(socket, hostKeys, ident, offer, debug, this, cfg);\n }).on('error', (err) => {\n this.emit('error', err);\n }).on('listening', () => {\n this.emit('listening');\n }).on('close', () => {\n this.emit('close');\n });\n this._connections = 0;\n this.maxConnections = Infinity;\n }\n\n injectSocket(socket) {\n this._srv.emit('connection', socket);\n }\n\n listen(...args) {\n this._srv.listen(...args);\n return this;\n }\n\n address() {\n return this._srv.address();\n }\n\n getConnections(cb) {\n this._srv.getConnections(cb);\n return this;\n }\n\n close(cb) {\n this._srv.close(cb);\n return this;\n }\n\n ref() {\n this._srv.ref();\n return this;\n }\n\n unref() {\n this._srv.unref();\n return this;\n }\n}\nServer.KEEPALIVE_CLIENT_INTERVAL = 15000;\nServer.KEEPALIVE_CLIENT_COUNT_MAX = 3;\n\n\nclass Client extends EventEmitter {\n constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) {\n super();\n\n let exchanges = 0;\n let acceptedAuthSvc = false;\n let pendingAuths = [];\n let authCtx;\n let kaTimer;\n let onPacket;\n const unsentGlobalRequestsReplies = [];\n this._sock = socket;\n this._chanMgr = new ChannelManager(this);\n this._debug = debug;\n this.noMoreSessions = false;\n this.authenticated = false;\n\n // Silence pre-header errors\n function onClientPreHeaderError(err) {}\n this.on('error', onClientPreHeaderError);\n\n const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {\n debug(`Debug output from client: ${JSON.stringify(msg)}`);\n });\n\n const kaIntvl = (\n typeof srvCfg.keepaliveInterval === 'number'\n && isFinite(srvCfg.keepaliveInterval)\n && srvCfg.keepaliveInterval > 0\n ? srvCfg.keepaliveInterval\n : (\n typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number'\n && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL)\n && Server.KEEPALIVE_CLIENT_INTERVAL > 0\n ? Server.KEEPALIVE_CLIENT_INTERVAL\n : -1\n )\n );\n const kaCountMax = (\n typeof srvCfg.keepaliveCountMax === 'number'\n && isFinite(srvCfg.keepaliveCountMax)\n && srvCfg.keepaliveCountMax >= 0\n ? srvCfg.keepaliveCountMax\n : (\n typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number'\n && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX)\n && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0\n ? Server.KEEPALIVE_CLIENT_COUNT_MAX\n : -1\n )\n );\n let kaCurCount = 0;\n if (kaIntvl !== -1 && kaCountMax !== -1) {\n this.once('ready', () => {\n const onClose = () => {\n clearInterval(kaTimer);\n };\n this.on('close', onClose).on('end', onClose);\n kaTimer = setInterval(() => {\n if (++kaCurCount > kaCountMax) {\n clearInterval(kaTimer);\n const err = new Error('Keepalive timeout');\n err.level = 'client-timeout';\n this.emit('error', err);\n this.end();\n } else {\n // XXX: if the server ever starts sending real global requests to\n // the client, we will need to add a dummy callback here to\n // keep the correct reply order\n proto.ping();\n }\n }, kaIntvl);\n });\n // TODO: re-verify keepalive behavior with OpenSSH\n onPacket = () => {\n kaTimer && kaTimer.refresh();\n kaCurCount = 0;\n };\n }\n\n const proto = this._protocol = new Protocol({\n server: true,\n hostKeys,\n ident,\n offer,\n onPacket,\n greeting: srvCfg.greeting,\n banner: srvCfg.banner,\n onWrite: (data) => {\n if (isWritable(socket))\n socket.write(data);\n },\n onError: (err) => {\n if (!proto._destruct)\n socket.removeAllListeners('data');\n this.emit('error', err);\n try {\n socket.end();\n } catch {}\n },\n onHeader: (header) => {\n this.removeListener('error', onClientPreHeaderError);\n\n const info = {\n ip: socket.remoteAddress,\n family: socket.remoteFamily,\n port: socket.remotePort,\n header,\n };\n if (!server.emit('connection', this, info)) {\n // auto reject\n proto.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n socket.end();\n return;\n }\n\n if (header.greeting)\n this.emit('greeting', header.greeting);\n },\n onHandshakeComplete: (negotiated) => {\n if (++exchanges > 1)\n this.emit('rekey');\n this.emit('handshake', negotiated);\n },\n debug,\n messageHandlers: {\n DEBUG: DEBUG_HANDLER,\n DISCONNECT: (p, reason, desc) => {\n if (reason !== DISCONNECT_REASON.BY_APPLICATION) {\n if (!desc) {\n desc = DISCONNECT_REASON_BY_VALUE[reason];\n if (desc === undefined)\n desc = `Unexpected disconnection reason: ${reason}`;\n }\n const err = new Error(desc);\n err.code = reason;\n this.emit('error', err);\n }\n socket.end();\n },\n CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from client\n\n // Do early reject in some cases to prevent wasteful channel\n // allocation\n if ((info.type === 'session' && this.noMoreSessions)\n || !this.authenticated) {\n const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n return proto.channelOpenFail(info.sender, reasonCode);\n }\n\n let localChan = -1;\n let reason;\n let replied = false;\n\n let accept;\n const reject = () => {\n if (replied)\n return;\n replied = true;\n\n if (reason === undefined) {\n if (localChan === -1)\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n else\n reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;\n }\n\n if (localChan !== -1)\n this._chanMgr.remove(localChan);\n proto.channelOpenFail(info.sender, reason, '');\n };\n const reserveChannel = () => {\n localChan = this._chanMgr.add();\n\n if (localChan === -1) {\n reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;\n if (debug) {\n debug('Automatic rejection of incoming channel open: '\n + 'no channels available');\n }\n }\n\n return (localChan !== -1);\n };\n\n const data = info.data;\n switch (info.type) {\n case 'session':\n if (listenerCount(this, 'session') && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const instance = new Session(this, info, localChan);\n this._chanMgr.update(localChan, instance);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return instance;\n };\n\n this.emit('session', accept, reject);\n return;\n }\n break;\n case 'direct-tcpip':\n if (listenerCount(this, 'tcpip') && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const chanInfo = {\n type: undefined,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const stream = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(localChan, stream);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return stream;\n };\n\n this.emit('tcpip', accept, reject, data);\n return;\n }\n break;\n case 'direct-streamlocal@openssh.com':\n if (listenerCount(this, 'openssh.streamlocal')\n && reserveChannel()) {\n accept = () => {\n if (replied)\n return;\n replied = true;\n\n const chanInfo = {\n type: undefined,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const stream = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(localChan, stream);\n\n proto.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n\n return stream;\n };\n\n this.emit('openssh.streamlocal', accept, reject, data);\n return;\n }\n break;\n default:\n // Automatically reject any unsupported channel open requests\n reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;\n if (debug) {\n debug('Automatic rejection of unsupported incoming channel open'\n + ` type: ${info.type}`);\n }\n }\n\n if (reason === undefined) {\n reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;\n if (debug) {\n debug('Automatic rejection of unexpected incoming channel open'\n + ` for: ${info.type}`);\n }\n }\n\n reject();\n },\n CHANNEL_OPEN_CONFIRMATION: (p, info) => {\n const channel = this._chanMgr.get(info.recipient);\n if (typeof channel !== 'function')\n return;\n\n const chanInfo = {\n type: channel.type,\n incoming: {\n id: info.recipient,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n\n const instance = new Channel(this, chanInfo, { server: true });\n this._chanMgr.update(info.recipient, instance);\n channel(undefined, instance);\n },\n CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },\n CHANNEL_DATA: (p, recipient, data) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },\n CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n // NOOP -- should not be sent by client\n },\n CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },\n CHANNEL_SUCCESS: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(false);\n },\n CHANNEL_FAILURE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },\n CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {\n const session = this._chanMgr.get(recipient);\n if (typeof session !== 'object' || session === null)\n return;\n\n let replied = false;\n let accept;\n let reject;\n\n if (session.constructor !== Session) {\n // normal Channel instance\n if (wantReply)\n proto.channelFailure(session.outgoing.id);\n return;\n }\n\n if (wantReply) {\n // \"real session\" requests will have custom accept behaviors\n if (type !== 'shell'\n && type !== 'exec'\n && type !== 'subsystem') {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n proto.channelSuccess(session._chanInfo.outgoing.id);\n };\n }\n\n reject = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n proto.channelFailure(session._chanInfo.outgoing.id);\n };\n }\n\n if (session._ending) {\n reject && reject();\n return;\n }\n\n switch (type) {\n // \"pre-real session start\" requests\n case 'env':\n if (listenerCount(session, 'env')) {\n session.emit('env', accept, reject, {\n key: data.name,\n val: data.value\n });\n return;\n }\n break;\n case 'pty-req':\n if (listenerCount(session, 'pty')) {\n session.emit('pty', accept, reject, data);\n return;\n }\n break;\n case 'window-change':\n if (listenerCount(session, 'window-change'))\n session.emit('window-change', accept, reject, data);\n else\n reject && reject();\n break;\n case 'x11-req':\n if (listenerCount(session, 'x11')) {\n session.emit('x11', accept, reject, data);\n return;\n }\n break;\n // \"post-real session start\" requests\n case 'signal':\n if (listenerCount(session, 'signal')) {\n session.emit('signal', accept, reject, {\n name: data\n });\n return;\n }\n break;\n // XXX: is `auth-agent-req@openssh.com` really \"post-real session\n // start\"?\n case 'auth-agent-req@openssh.com':\n if (listenerCount(session, 'auth-agent')) {\n session.emit('auth-agent', accept, reject);\n return;\n }\n break;\n // \"real session start\" requests\n case 'shell':\n if (listenerCount(session, 'shell')) {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n const channel = new Channel(\n this, session._chanInfo, { server: true }\n );\n\n channel.subtype = session.subtype = type;\n session._channel = channel;\n\n return channel;\n };\n\n session.emit('shell', accept, reject);\n return;\n }\n break;\n case 'exec':\n if (listenerCount(session, 'exec')) {\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n const channel = new Channel(\n this, session._chanInfo, { server: true }\n );\n\n channel.subtype = session.subtype = type;\n session._channel = channel;\n\n return channel;\n };\n\n session.emit('exec', accept, reject, {\n command: data\n });\n return;\n }\n break;\n case 'subsystem': {\n let useSFTP = (data === 'sftp');\n accept = () => {\n if (replied || session._ending || session._channel)\n return;\n replied = true;\n\n if (wantReply)\n proto.channelSuccess(session._chanInfo.outgoing.id);\n\n let instance;\n if (useSFTP) {\n instance = new SFTP(this, session._chanInfo, {\n server: true,\n debug,\n });\n } else {\n instance = new Channel(\n this, session._chanInfo, { server: true }\n );\n instance.subtype =\n session.subtype = `${type}:${data}`;\n }\n session._channel = instance;\n\n return instance;\n };\n\n if (data === 'sftp') {\n if (listenerCount(session, 'sftp')) {\n session.emit('sftp', accept, reject);\n return;\n }\n useSFTP = false;\n }\n if (listenerCount(session, 'subsystem')) {\n session.emit('subsystem', accept, reject, {\n name: data\n });\n return;\n }\n break;\n }\n }\n debug && debug(\n `Automatic rejection of incoming channel request: ${type}`\n );\n reject && reject();\n },\n CHANNEL_EOF: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n if (!channel._ending) {\n channel._ending = true;\n channel.emit('eof');\n channel.emit('end');\n }\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel.incoming.state !== 'open')\n return;\n channel.incoming.state = 'eof';\n\n if (channel.readable)\n channel.push(null);\n },\n CHANNEL_CLOSE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel._ending = true;\n channel.emit('close');\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n onCHANNEL_CLOSE(this, recipient, channel);\n },\n // Begin service/auth-related ==========================================\n SERVICE_REQUEST: (p, service) => {\n if (exchanges === 0\n || acceptedAuthSvc\n || this.authenticated\n || service !== 'ssh-userauth') {\n proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);\n socket.end();\n return;\n }\n\n acceptedAuthSvc = true;\n proto.serviceAccept(service);\n },\n USERAUTH_REQUEST: (p, username, service, method, methodData) => {\n if (exchanges === 0\n || this.authenticated\n || (authCtx\n && (authCtx.username !== username\n || authCtx.service !== service))\n // TODO: support hostbased auth\n || (method !== 'password'\n && method !== 'publickey'\n && method !== 'hostbased'\n && method !== 'keyboard-interactive'\n && method !== 'none')\n || pendingAuths.length === MAX_PENDING_AUTHS) {\n proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR);\n socket.end();\n return;\n } else if (service !== 'ssh-connection') {\n proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);\n socket.end();\n return;\n }\n\n let ctx;\n switch (method) {\n case 'keyboard-interactive':\n ctx = new KeyboardAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'publickey':\n ctx = new PKAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'hostbased':\n ctx = new HostbasedAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'password':\n if (authCtx\n && authCtx instanceof PwdAuthContext\n && authCtx._changeCb) {\n const cb = authCtx._changeCb;\n authCtx._changeCb = undefined;\n cb(methodData.newPassword);\n return;\n }\n ctx = new PwdAuthContext(proto, username, service, method,\n methodData, onAuthDecide);\n break;\n case 'none':\n ctx = new AuthContext(proto, username, service, method,\n onAuthDecide);\n break;\n }\n\n if (authCtx) {\n if (!authCtx._initialResponse) {\n return pendingAuths.push(ctx);\n } else if (authCtx._multistep && !authCtx._finalResponse) {\n // RFC 4252 says to silently abort the current auth request if a\n // new auth request comes in before the final response from an\n // auth method that requires additional request/response exchanges\n // -- this means keyboard-interactive for now ...\n authCtx._cleanup && authCtx._cleanup();\n authCtx.emit('abort');\n }\n }\n\n authCtx = ctx;\n\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n },\n USERAUTH_INFO_RESPONSE: (p, responses) => {\n if (authCtx && authCtx instanceof KeyboardAuthContext)\n authCtx._onInfoResponse(responses);\n },\n // End service/auth-related ============================================\n GLOBAL_REQUEST: (p, name, wantReply, data) => {\n const reply = {\n type: null,\n buf: null\n };\n\n function setReply(type, buf) {\n reply.type = type;\n reply.buf = buf;\n sendReplies();\n }\n\n if (wantReply)\n unsentGlobalRequestsReplies.push(reply);\n\n if ((name === 'tcpip-forward'\n || name === 'cancel-tcpip-forward'\n || name === 'no-more-sessions@openssh.com'\n || name === 'streamlocal-forward@openssh.com'\n || name === 'cancel-streamlocal-forward@openssh.com')\n && listenerCount(this, 'request')\n && this.authenticated) {\n let accept;\n let reject;\n\n if (wantReply) {\n let replied = false;\n accept = (chosenPort) => {\n if (replied)\n return;\n replied = true;\n let bufPort;\n if (name === 'tcpip-forward'\n && data.bindPort === 0\n && typeof chosenPort === 'number') {\n bufPort = Buffer.allocUnsafe(4);\n writeUInt32BE(bufPort, chosenPort, 0);\n }\n setReply('SUCCESS', bufPort);\n };\n reject = () => {\n if (replied)\n return;\n replied = true;\n setReply('FAILURE');\n };\n }\n\n if (name === 'no-more-sessions@openssh.com') {\n this.noMoreSessions = true;\n accept && accept();\n return;\n }\n\n this.emit('request', accept, reject, name, data);\n } else if (wantReply) {\n setReply('FAILURE');\n }\n },\n },\n });\n\n socket.pause();\n cryptoInit.then(() => {\n proto.start();\n socket.on('data', (data) => {\n try {\n proto.parse(data, 0, data.length);\n } catch (ex) {\n this.emit('error', ex);\n try {\n if (isWritable(socket))\n socket.end();\n } catch {}\n }\n });\n socket.resume();\n }).catch((err) => {\n this.emit('error', err);\n try {\n if (isWritable(socket))\n socket.end();\n } catch {}\n });\n socket.on('error', (err) => {\n err.level = 'socket';\n this.emit('error', err);\n }).once('end', () => {\n debug && debug('Socket ended');\n proto.cleanup();\n this.emit('end');\n }).once('close', () => {\n debug && debug('Socket closed');\n proto.cleanup();\n this.emit('close');\n\n const err = new Error('No response from server');\n\n // Simulate error for pending channels and close any open channels\n this._chanMgr.cleanup(err);\n });\n\n const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => {\n if (authCtx === ctx && !this.authenticated) {\n if (allowed) {\n authCtx = undefined;\n this.authenticated = true;\n proto.authSuccess();\n pendingAuths = [];\n this.emit('ready');\n } else {\n proto.authFailure(methodsLeft, isPartial);\n if (pendingAuths.length) {\n authCtx = pendingAuths.pop();\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n }\n }\n }\n };\n\n function sendReplies() {\n while (unsentGlobalRequestsReplies.length > 0\n && unsentGlobalRequestsReplies[0].type) {\n const reply = unsentGlobalRequestsReplies.shift();\n if (reply.type === 'SUCCESS')\n proto.requestSuccess(reply.buf);\n if (reply.type === 'FAILURE')\n proto.requestFailure();\n }\n }\n }\n\n end() {\n if (this._sock && isWritable(this._sock)) {\n this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);\n this._sock.end();\n }\n return this;\n }\n\n x11(originAddr, originPort, cb) {\n const opts = { originAddr, originPort };\n openChannel(this, 'x11', opts, cb);\n return this;\n }\n\n forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) {\n const opts = { boundAddr, boundPort, remoteAddr, remotePort };\n openChannel(this, 'forwarded-tcpip', opts, cb);\n return this;\n }\n\n openssh_forwardOutStreamLocal(socketPath, cb) {\n const opts = { socketPath };\n openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb);\n return this;\n }\n\n rekey(cb) {\n let error;\n\n try {\n this._protocol.rekey();\n } catch (ex) {\n error = ex;\n }\n\n // TODO: re-throw error if no callback?\n\n if (typeof cb === 'function') {\n if (error)\n process.nextTick(cb, error);\n else\n this.once('rekey', cb);\n }\n }\n\n setNoDelay(noDelay) {\n if (this._sock && typeof this._sock.setNoDelay === 'function')\n this._sock.setNoDelay(noDelay);\n\n return this;\n }\n}\n\n\nfunction openChannel(self, type, opts, cb) {\n // Ask the client to open a channel for some purpose (e.g. a forwarded TCP\n // connection)\n const initWindow = MAX_WINDOW;\n const maxPacket = PACKET_SIZE;\n\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n\n const wrapper = (err, stream) => {\n cb(err, stream);\n };\n wrapper.type = type;\n\n const localChan = self._chanMgr.add(wrapper);\n\n if (localChan === -1) {\n cb(new Error('No free channels available'));\n return;\n }\n\n switch (type) {\n case 'forwarded-tcpip':\n self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts);\n break;\n case 'x11':\n self._protocol.x11(localChan, initWindow, maxPacket, opts);\n break;\n case 'forwarded-streamlocal@openssh.com':\n self._protocol.openssh_forwardedStreamLocal(\n localChan, initWindow, maxPacket, opts\n );\n break;\n default:\n throw new Error(`Unsupported channel type: ${type}`);\n }\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nmodule.exports = Server;\nmodule.exports.IncomingClient = Client;\n","'use strict';\n\nconst { SFTP } = require('./protocol/SFTP.js');\n\nconst MAX_CHANNEL = 2 ** 32 - 1;\n\nfunction onChannelOpenFailure(self, recipient, info, cb) {\n self._chanMgr.remove(recipient);\n if (typeof cb !== 'function')\n return;\n\n let err;\n if (info instanceof Error) {\n err = info;\n } else if (typeof info === 'object' && info !== null) {\n err = new Error(`(SSH) Channel open failure: ${info.description}`);\n err.reason = info.reason;\n } else {\n err = new Error(\n '(SSH) Channel open failure: server closed channel unexpectedly'\n );\n err.reason = '';\n }\n\n cb(err);\n}\n\nfunction onCHANNEL_CLOSE(self, recipient, channel, err, dead) {\n if (typeof channel === 'function') {\n // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when\n // requesting to open a channel\n onChannelOpenFailure(self, recipient, err, channel);\n return;\n }\n\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.incoming && channel.incoming.state === 'closed')\n return;\n\n self._chanMgr.remove(recipient);\n\n if (channel.server && channel.constructor.name === 'Session')\n return;\n\n channel.incoming.state = 'closed';\n\n if (channel.readable)\n channel.push(null);\n if (channel.server) {\n if (channel.stderr.writable)\n channel.stderr.end();\n } else if (channel.stderr.readable) {\n channel.stderr.push(null);\n }\n\n if (channel.constructor !== SFTP\n && (channel.outgoing.state === 'open'\n || channel.outgoing.state === 'eof')\n && !dead) {\n channel.close();\n }\n if (channel.outgoing.state === 'closing')\n channel.outgoing.state = 'closed';\n\n const readState = channel._readableState;\n const writeState = channel._writableState;\n if (writeState && !writeState.ending && !writeState.finished && !dead)\n channel.end();\n\n // Take care of any outstanding channel requests\n const chanCallbacks = channel._callbacks;\n channel._callbacks = [];\n for (let i = 0; i < chanCallbacks.length; ++i)\n chanCallbacks[i](true);\n\n if (channel.server) {\n if (!channel.readable\n || channel.destroyed\n || (readState && readState.endEmitted)) {\n channel.emit('close');\n } else {\n channel.once('end', () => channel.emit('close'));\n }\n } else {\n let doClose;\n switch (channel.type) {\n case 'direct-streamlocal@openssh.com':\n case 'direct-tcpip':\n doClose = () => channel.emit('close');\n break;\n default: {\n // Align more with node child processes, where the close event gets\n // the same arguments as the exit event\n const exit = channel._exit;\n doClose = () => {\n if (exit.code === null)\n channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc);\n else\n channel.emit('close', exit.code);\n };\n }\n }\n if (!channel.readable\n || channel.destroyed\n || (readState && readState.endEmitted)) {\n doClose();\n } else {\n channel.once('end', doClose);\n }\n\n const errReadState = channel.stderr._readableState;\n if (!channel.stderr.readable\n || channel.stderr.destroyed\n || (errReadState && errReadState.endEmitted)) {\n channel.stderr.emit('close');\n } else {\n channel.stderr.once('end', () => channel.stderr.emit('close'));\n }\n }\n}\n\nclass ChannelManager {\n constructor(client) {\n this._client = client;\n this._channels = {};\n this._cur = -1;\n this._count = 0;\n }\n add(val) {\n // Attempt to reserve an id\n\n let id;\n // Optimized paths\n if (this._cur < MAX_CHANNEL) {\n id = ++this._cur;\n } else if (this._count === 0) {\n // Revert and reset back to fast path once we no longer have any channels\n // open\n this._cur = 0;\n id = 0;\n } else {\n // Slower lookup path\n\n // This path is triggered we have opened at least MAX_CHANNEL channels\n // while having at least one channel open at any given time, so we have\n // to search for a free id.\n const channels = this._channels;\n for (let i = 0; i < MAX_CHANNEL; ++i) {\n if (channels[i] === undefined) {\n id = i;\n break;\n }\n }\n }\n\n if (id === undefined)\n return -1;\n\n this._channels[id] = (val || true);\n ++this._count;\n\n return id;\n }\n update(id, val) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n if (val && this._channels[id])\n this._channels[id] = val;\n }\n get(id) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n return this._channels[id];\n }\n remove(id) {\n if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id))\n throw new Error(`Invalid channel id: ${id}`);\n\n if (this._channels[id]) {\n delete this._channels[id];\n if (this._count)\n --this._count;\n }\n }\n cleanup(err) {\n const channels = this._channels;\n this._channels = {};\n this._cur = -1;\n this._count = 0;\n\n const chanIDs = Object.keys(channels);\n const client = this._client;\n for (let i = 0; i < chanIDs.length; ++i) {\n const id = +chanIDs[i];\n const channel = channels[id];\n onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true);\n }\n }\n}\n\nconst isRegExp = (() => {\n const toString = Object.prototype.toString;\n return (val) => toString.call(val) === '[object RegExp]';\n})();\n\nfunction generateAlgorithmList(algoList, defaultList, supportedList) {\n if (Array.isArray(algoList) && algoList.length > 0) {\n // Exact list\n for (let i = 0; i < algoList.length; ++i) {\n if (supportedList.indexOf(algoList[i]) === -1)\n throw new Error(`Unsupported algorithm: ${algoList[i]}`);\n }\n return algoList;\n }\n\n if (typeof algoList === 'object' && algoList !== null) {\n // Operations based on the default list\n const keys = Object.keys(algoList);\n let list = defaultList;\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n let val = algoList[key];\n switch (key) {\n case 'append':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = 0; j < val.length; ++j) {\n const append = val[j];\n if (typeof append === 'string') {\n if (!append || list.indexOf(append) !== -1)\n continue;\n if (supportedList.indexOf(append) === -1)\n throw new Error(`Unsupported algorithm: ${append}`);\n if (list === defaultList)\n list = list.slice();\n list.push(append);\n } else if (isRegExp(append)) {\n for (let k = 0; k < supportedList.length; ++k) {\n const algo = supportedList[k];\n if (append.test(algo)) {\n if (list.indexOf(algo) !== -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.push(algo);\n }\n }\n }\n }\n }\n break;\n case 'prepend':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = val.length; j >= 0; --j) {\n const prepend = val[j];\n if (typeof prepend === 'string') {\n if (!prepend || list.indexOf(prepend) !== -1)\n continue;\n if (supportedList.indexOf(prepend) === -1)\n throw new Error(`Unsupported algorithm: ${prepend}`);\n if (list === defaultList)\n list = list.slice();\n list.unshift(prepend);\n } else if (isRegExp(prepend)) {\n for (let k = supportedList.length; k >= 0; --k) {\n const algo = supportedList[k];\n if (prepend.test(algo)) {\n if (list.indexOf(algo) !== -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.unshift(algo);\n }\n }\n }\n }\n }\n break;\n case 'remove':\n if (!Array.isArray(val))\n val = [val];\n if (Array.isArray(val)) {\n for (let j = 0; j < val.length; ++j) {\n const search = val[j];\n if (typeof search === 'string') {\n if (!search)\n continue;\n const idx = list.indexOf(search);\n if (idx === -1)\n continue;\n if (list === defaultList)\n list = list.slice();\n list.splice(idx, 1);\n } else if (isRegExp(search)) {\n for (let k = 0; k < list.length; ++k) {\n if (search.test(list[k])) {\n if (list === defaultList)\n list = list.slice();\n list.splice(k, 1);\n --k;\n }\n }\n }\n }\n }\n break;\n }\n }\n\n return list;\n }\n\n return defaultList;\n}\n\nmodule.exports = {\n ChannelManager,\n generateAlgorithmList,\n onChannelOpenFailure,\n onCHANNEL_CLOSE,\n isWritable: (stream) => {\n // XXX: hack to workaround regression in node\n // See: https://github.com/nodejs/node/issues/36029\n return (stream\n && stream.writable\n && stream._readableState\n && stream._readableState.ended === false);\n },\n};\n","const { EventEmitter } = require('events')\nconst STREAM_DESTROYED = new Error('Stream was destroyed')\nconst PREMATURE_CLOSE = new Error('Premature close')\n\nconst queueTick = require('queue-tick')\nconst FIFO = require('fast-fifo')\n\n/* eslint-disable no-multi-spaces */\n\n// 27 bits used total (4 from shared, 13 from read, and 10 from write)\nconst MAX = ((1 << 27) - 1)\n\n// Shared state\nconst OPENING = 0b0001\nconst PREDESTROYING = 0b0010\nconst DESTROYING = 0b0100\nconst DESTROYED = 0b1000\n\nconst NOT_OPENING = MAX ^ OPENING\nconst NOT_PREDESTROYING = MAX ^ PREDESTROYING\n\n// Read state (4 bit offset from shared state)\nconst READ_ACTIVE = 0b0000000000001 << 4\nconst READ_UPDATING = 0b0000000000010 << 4\nconst READ_PRIMARY = 0b0000000000100 << 4\nconst READ_QUEUED = 0b0000000001000 << 4\nconst READ_RESUMED = 0b0000000010000 << 4\nconst READ_PIPE_DRAINED = 0b0000000100000 << 4\nconst READ_ENDING = 0b0000001000000 << 4\nconst READ_EMIT_DATA = 0b0000010000000 << 4\nconst READ_EMIT_READABLE = 0b0000100000000 << 4\nconst READ_EMITTED_READABLE = 0b0001000000000 << 4\nconst READ_DONE = 0b0010000000000 << 4\nconst READ_NEXT_TICK = 0b0100000000000 << 4\nconst READ_NEEDS_PUSH = 0b1000000000000 << 4\n\n// Combined read state\nconst READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED\nconst READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH\nconst READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE\nconst READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED\n\nconst READ_NOT_ACTIVE = MAX ^ READ_ACTIVE\nconst READ_NON_PRIMARY = MAX ^ READ_PRIMARY\nconst READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)\nconst READ_PUSHED = MAX ^ READ_NEEDS_PUSH\nconst READ_PAUSED = MAX ^ READ_RESUMED\nconst READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)\nconst READ_NOT_ENDING = MAX ^ READ_ENDING\nconst READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING\nconst READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK\nconst READ_NOT_UPDATING = MAX ^ READ_UPDATING\n\n// Write state (17 bit offset, 4 bit offset from shared state and 13 from read state)\nconst WRITE_ACTIVE = 0b0000000001 << 17\nconst WRITE_UPDATING = 0b0000000010 << 17\nconst WRITE_PRIMARY = 0b0000000100 << 17\nconst WRITE_QUEUED = 0b0000001000 << 17\nconst WRITE_UNDRAINED = 0b0000010000 << 17\nconst WRITE_DONE = 0b0000100000 << 17\nconst WRITE_EMIT_DRAIN = 0b0001000000 << 17\nconst WRITE_NEXT_TICK = 0b0010000000 << 17\nconst WRITE_WRITING = 0b0100000000 << 17\nconst WRITE_FINISHING = 0b1000000000 << 17\n\nconst WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)\nconst WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY\nconst WRITE_NOT_FINISHING = MAX ^ WRITE_FINISHING\nconst WRITE_DRAINED = MAX ^ WRITE_UNDRAINED\nconst WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED\nconst WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK\nconst WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING\n\n// Combined shared state\nconst ACTIVE = READ_ACTIVE | WRITE_ACTIVE\nconst NOT_ACTIVE = MAX ^ ACTIVE\nconst DONE = READ_DONE | WRITE_DONE\nconst DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING\nconst OPEN_STATUS = DESTROY_STATUS | OPENING\nconst AUTO_DESTROY = DESTROY_STATUS | DONE\nconst NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY\nconst ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK\nconst TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE\nconst IS_OPENING = OPEN_STATUS | TICKING\n\n// Combined shared state and read state\nconst READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE\nconst READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED\nconst READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED\nconst READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE\nconst SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH\nconst READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE\nconst READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY\n\n// Combined write state\nconst WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE\nconst WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED\nconst WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE\nconst WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE\nconst WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED\nconst WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE\nconst WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING\nconst WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE\nconst WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE\nconst WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY\n\nconst asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')\n\nclass WritableState {\n constructor (stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {\n this.stream = stream\n this.queue = new FIFO()\n this.highWaterMark = highWaterMark\n this.buffered = 0\n this.error = null\n this.pipeline = null\n this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr\n this.byteLength = byteLengthWritable || byteLength || defaultByteLength\n this.map = mapWritable || map\n this.afterWrite = afterWrite.bind(this)\n this.afterUpdateNextTick = updateWriteNT.bind(this)\n }\n\n get ended () {\n return (this.stream._duplexState & WRITE_DONE) !== 0\n }\n\n push (data) {\n if (this.map !== null) data = this.map(data)\n\n this.buffered += this.byteLength(data)\n this.queue.push(data)\n\n if (this.buffered < this.highWaterMark) {\n this.stream._duplexState |= WRITE_QUEUED\n return true\n }\n\n this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED\n return false\n }\n\n shift () {\n const data = this.queue.shift()\n\n this.buffered -= this.byteLength(data)\n if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED\n\n return data\n }\n\n end (data) {\n if (typeof data === 'function') this.stream.once('finish', data)\n else if (data !== undefined && data !== null) this.push(data)\n this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY\n }\n\n autoBatch (data, cb) {\n const buffer = []\n const stream = this.stream\n\n buffer.push(data)\n while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {\n buffer.push(stream._writableState.shift())\n }\n\n if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)\n stream._writev(buffer, cb)\n }\n\n update () {\n const stream = this.stream\n\n stream._duplexState |= WRITE_UPDATING\n\n do {\n while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {\n const data = this.shift()\n stream._duplexState |= WRITE_ACTIVE_AND_WRITING\n stream._write(data, this.afterWrite)\n }\n\n if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()\n } while (this.continueUpdate() === true)\n\n stream._duplexState &= WRITE_NOT_UPDATING\n }\n\n updateNonPrimary () {\n const stream = this.stream\n\n if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {\n stream._duplexState = (stream._duplexState | WRITE_ACTIVE) & WRITE_NOT_FINISHING\n stream._final(afterFinal.bind(this))\n return\n }\n\n if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {\n if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {\n stream._duplexState |= ACTIVE\n stream._destroy(afterDestroy.bind(this))\n }\n return\n }\n\n if ((stream._duplexState & IS_OPENING) === OPENING) {\n stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING\n stream._open(afterOpen.bind(this))\n }\n }\n\n continueUpdate () {\n if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false\n this.stream._duplexState &= WRITE_NOT_NEXT_TICK\n return true\n }\n\n updateCallback () {\n if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update()\n else this.updateNextTick()\n }\n\n updateNextTick () {\n if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return\n this.stream._duplexState |= WRITE_NEXT_TICK\n if ((this.stream._duplexState & WRITE_UPDATING) === 0) queueTick(this.afterUpdateNextTick)\n }\n}\n\nclass ReadableState {\n constructor (stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {\n this.stream = stream\n this.queue = new FIFO()\n this.highWaterMark = highWaterMark\n this.buffered = 0\n this.error = null\n this.pipeline = null\n this.byteLength = byteLengthReadable || byteLength || defaultByteLength\n this.map = mapReadable || map\n this.pipeTo = null\n this.afterRead = afterRead.bind(this)\n this.afterUpdateNextTick = updateReadNT.bind(this)\n }\n\n get ended () {\n return (this.stream._duplexState & READ_DONE) !== 0\n }\n\n pipe (pipeTo, cb) {\n if (this.pipeTo !== null) throw new Error('Can only pipe to one destination')\n if (typeof cb !== 'function') cb = null\n\n this.stream._duplexState |= READ_PIPE_DRAINED\n this.pipeTo = pipeTo\n this.pipeline = new Pipeline(this.stream, pipeTo, cb)\n\n if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes\n\n if (isStreamx(pipeTo)) {\n pipeTo._writableState.pipeline = this.pipeline\n if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes\n pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself\n } else {\n const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)\n const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg\n pipeTo.on('error', onerror)\n pipeTo.on('close', onclose)\n pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))\n }\n\n pipeTo.on('drain', afterDrain.bind(this))\n this.stream.emit('piping', pipeTo)\n pipeTo.emit('pipe', this.stream)\n }\n\n push (data) {\n const stream = this.stream\n\n if (data === null) {\n this.highWaterMark = 0\n stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED\n return false\n }\n\n if (this.map !== null) data = this.map(data)\n this.buffered += this.byteLength(data)\n this.queue.push(data)\n\n stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED\n\n return this.buffered < this.highWaterMark\n }\n\n shift () {\n const data = this.queue.shift()\n\n this.buffered -= this.byteLength(data)\n if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED\n return data\n }\n\n unshift (data) {\n const pending = [this.map !== null ? this.map(data) : data]\n while (this.buffered > 0) pending.push(this.shift())\n\n for (let i = 0; i < pending.length - 1; i++) {\n const data = pending[i]\n this.buffered += this.byteLength(data)\n this.queue.push(data)\n }\n\n this.push(pending[pending.length - 1])\n }\n\n read () {\n const stream = this.stream\n\n if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {\n const data = this.shift()\n if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED\n if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)\n return data\n }\n\n return null\n }\n\n drain () {\n const stream = this.stream\n\n while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {\n const data = this.shift()\n if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED\n if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)\n }\n }\n\n update () {\n const stream = this.stream\n\n stream._duplexState |= READ_UPDATING\n\n do {\n this.drain()\n\n while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === 0) {\n stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH\n stream._read(this.afterRead)\n this.drain()\n }\n\n if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {\n stream._duplexState |= READ_EMITTED_READABLE\n stream.emit('readable')\n }\n\n if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()\n } while (this.continueUpdate() === true)\n\n stream._duplexState &= READ_NOT_UPDATING\n }\n\n updateNonPrimary () {\n const stream = this.stream\n\n if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {\n stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING\n stream.emit('end')\n if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING\n if (this.pipeTo !== null) this.pipeTo.end()\n }\n\n if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {\n if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {\n stream._duplexState |= ACTIVE\n stream._destroy(afterDestroy.bind(this))\n }\n return\n }\n\n if ((stream._duplexState & IS_OPENING) === OPENING) {\n stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING\n stream._open(afterOpen.bind(this))\n }\n }\n\n continueUpdate () {\n if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false\n this.stream._duplexState &= READ_NOT_NEXT_TICK\n return true\n }\n\n updateCallback () {\n if ((this.stream._readableState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update()\n else this.updateNextTick()\n }\n\n updateNextTick () {\n if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return\n this.stream._duplexState |= READ_NEXT_TICK\n if ((this.stream._duplexState & READ_UPDATING) === 0) queueTick(this.afterUpdateNextTick)\n }\n}\n\nclass TransformState {\n constructor (stream) {\n this.data = null\n this.afterTransform = afterTransform.bind(stream)\n this.afterFinal = null\n }\n}\n\nclass Pipeline {\n constructor (src, dst, cb) {\n this.from = src\n this.to = dst\n this.afterPipe = cb\n this.error = null\n this.pipeToFinished = false\n }\n\n finished () {\n this.pipeToFinished = true\n }\n\n done (stream, err) {\n if (err) this.error = err\n\n if (stream === this.to) {\n this.to = null\n\n if (this.from !== null) {\n if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {\n this.from.destroy(this.error || new Error('Writable stream closed prematurely'))\n }\n return\n }\n }\n\n if (stream === this.from) {\n this.from = null\n\n if (this.to !== null) {\n if ((stream._duplexState & READ_DONE) === 0) {\n this.to.destroy(this.error || new Error('Readable stream closed before ending'))\n }\n return\n }\n }\n\n if (this.afterPipe !== null) this.afterPipe(this.error)\n this.to = this.from = this.afterPipe = null\n }\n}\n\nfunction afterDrain () {\n this.stream._duplexState |= READ_PIPE_DRAINED\n this.updateCallback()\n}\n\nfunction afterFinal (err) {\n const stream = this.stream\n if (err) stream.destroy(err)\n if ((stream._duplexState & DESTROY_STATUS) === 0) {\n stream._duplexState |= WRITE_DONE\n stream.emit('finish')\n }\n if ((stream._duplexState & AUTO_DESTROY) === DONE) {\n stream._duplexState |= DESTROYING\n }\n\n stream._duplexState &= WRITE_NOT_ACTIVE\n\n // no need to wait the extra tick here, so we short circuit that\n if ((stream._duplexState & WRITE_UPDATING) === 0) this.update()\n else this.updateNextTick()\n}\n\nfunction afterDestroy (err) {\n const stream = this.stream\n\n if (!err && this.error !== STREAM_DESTROYED) err = this.error\n if (err) stream.emit('error', err)\n stream._duplexState |= DESTROYED\n stream.emit('close')\n\n const rs = stream._readableState\n const ws = stream._writableState\n\n if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err)\n\n if (ws !== null) {\n while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false)\n if (ws.pipeline !== null) ws.pipeline.done(stream, err)\n }\n}\n\nfunction afterWrite (err) {\n const stream = this.stream\n\n if (err) stream.destroy(err)\n stream._duplexState &= WRITE_NOT_ACTIVE\n\n if (this.drains !== null) tickDrains(this.drains)\n\n if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {\n stream._duplexState &= WRITE_DRAINED\n if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {\n stream.emit('drain')\n }\n }\n\n this.updateCallback()\n}\n\nfunction afterRead (err) {\n if (err) this.stream.destroy(err)\n this.stream._duplexState &= READ_NOT_ACTIVE\n this.updateCallback()\n}\n\nfunction updateReadNT () {\n if ((this.stream._duplexState & READ_UPDATING) === 0) {\n this.stream._duplexState &= READ_NOT_NEXT_TICK\n this.update()\n }\n}\n\nfunction updateWriteNT () {\n if ((this.stream._duplexState & WRITE_UPDATING) === 0) {\n this.stream._duplexState &= WRITE_NOT_NEXT_TICK\n this.update()\n }\n}\n\nfunction tickDrains (drains) {\n for (let i = 0; i < drains.length; i++) {\n // drains.writes are monotonic, so if one is 0 its always the first one\n if (--drains[i].writes === 0) {\n drains.shift().resolve(true)\n i--\n }\n }\n}\n\nfunction afterOpen (err) {\n const stream = this.stream\n\n if (err) stream.destroy(err)\n\n if ((stream._duplexState & DESTROYING) === 0) {\n if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY\n if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY\n stream.emit('open')\n }\n\n stream._duplexState &= NOT_ACTIVE\n\n if (stream._writableState !== null) {\n stream._writableState.updateCallback()\n }\n\n if (stream._readableState !== null) {\n stream._readableState.updateCallback()\n }\n}\n\nfunction afterTransform (err, data) {\n if (data !== undefined && data !== null) this.push(data)\n this._writableState.afterWrite(err)\n}\n\nclass Stream extends EventEmitter {\n constructor (opts) {\n super()\n\n this._duplexState = 0\n this._readableState = null\n this._writableState = null\n\n if (opts) {\n if (opts.open) this._open = opts.open\n if (opts.destroy) this._destroy = opts.destroy\n if (opts.predestroy) this._predestroy = opts.predestroy\n if (opts.signal) {\n opts.signal.addEventListener('abort', abort.bind(this))\n }\n }\n }\n\n _open (cb) {\n cb(null)\n }\n\n _destroy (cb) {\n cb(null)\n }\n\n _predestroy () {\n // does nothing\n }\n\n get readable () {\n return this._readableState !== null ? true : undefined\n }\n\n get writable () {\n return this._writableState !== null ? true : undefined\n }\n\n get destroyed () {\n return (this._duplexState & DESTROYED) !== 0\n }\n\n get destroying () {\n return (this._duplexState & DESTROY_STATUS) !== 0\n }\n\n destroy (err) {\n if ((this._duplexState & DESTROY_STATUS) === 0) {\n if (!err) err = STREAM_DESTROYED\n this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY\n\n if (this._readableState !== null) {\n this._readableState.highWaterMark = 0\n this._readableState.error = err\n }\n if (this._writableState !== null) {\n this._writableState.highWaterMark = 0\n this._writableState.error = err\n }\n\n this._duplexState |= PREDESTROYING\n this._predestroy()\n this._duplexState &= NOT_PREDESTROYING\n\n if (this._readableState !== null) this._readableState.updateNextTick()\n if (this._writableState !== null) this._writableState.updateNextTick()\n }\n }\n\n on (name, fn) {\n if (this._readableState !== null) {\n if (name === 'data') {\n this._duplexState |= (READ_EMIT_DATA | READ_RESUMED)\n this._readableState.updateNextTick()\n }\n if (name === 'readable') {\n this._duplexState |= READ_EMIT_READABLE\n this._readableState.updateNextTick()\n }\n }\n\n if (this._writableState !== null) {\n if (name === 'drain') {\n this._duplexState |= WRITE_EMIT_DRAIN\n this._writableState.updateNextTick()\n }\n }\n\n return super.on(name, fn)\n }\n}\n\nclass Readable extends Stream {\n constructor (opts) {\n super(opts)\n\n this._duplexState |= OPENING | WRITE_DONE\n this._readableState = new ReadableState(this, opts)\n\n if (opts) {\n if (opts.read) this._read = opts.read\n if (opts.eagerOpen) this._readableState.updateNextTick()\n }\n }\n\n _read (cb) {\n cb(null)\n }\n\n pipe (dest, cb) {\n this._readableState.updateNextTick()\n this._readableState.pipe(dest, cb)\n return dest\n }\n\n read () {\n this._readableState.updateNextTick()\n return this._readableState.read()\n }\n\n push (data) {\n this._readableState.updateNextTick()\n return this._readableState.push(data)\n }\n\n unshift (data) {\n this._readableState.updateNextTick()\n return this._readableState.unshift(data)\n }\n\n resume () {\n this._duplexState |= READ_RESUMED\n this._readableState.updateNextTick()\n return this\n }\n\n pause () {\n this._duplexState &= READ_PAUSED\n return this\n }\n\n static _fromAsyncIterator (ite, opts) {\n let destroy\n\n const rs = new Readable({\n ...opts,\n read (cb) {\n ite.next().then(push).then(cb.bind(null, null)).catch(cb)\n },\n predestroy () {\n destroy = ite.return()\n },\n destroy (cb) {\n if (!destroy) return cb(null)\n destroy.then(cb.bind(null, null)).catch(cb)\n }\n })\n\n return rs\n\n function push (data) {\n if (data.done) rs.push(null)\n else rs.push(data.value)\n }\n }\n\n static from (data, opts) {\n if (isReadStreamx(data)) return data\n if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)\n if (!Array.isArray(data)) data = data === undefined ? [] : [data]\n\n let i = 0\n return new Readable({\n ...opts,\n read (cb) {\n this.push(i === data.length ? null : data[i++])\n cb(null)\n }\n })\n }\n\n static isBackpressured (rs) {\n return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark\n }\n\n static isPaused (rs) {\n return (rs._duplexState & READ_RESUMED) === 0\n }\n\n [asyncIterator] () {\n const stream = this\n\n let error = null\n let promiseResolve = null\n let promiseReject = null\n\n this.on('error', (err) => { error = err })\n this.on('readable', onreadable)\n this.on('close', onclose)\n\n return {\n [asyncIterator] () {\n return this\n },\n next () {\n return new Promise(function (resolve, reject) {\n promiseResolve = resolve\n promiseReject = reject\n const data = stream.read()\n if (data !== null) ondata(data)\n else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)\n })\n },\n return () {\n return destroy(null)\n },\n throw (err) {\n return destroy(err)\n }\n }\n\n function onreadable () {\n if (promiseResolve !== null) ondata(stream.read())\n }\n\n function onclose () {\n if (promiseResolve !== null) ondata(null)\n }\n\n function ondata (data) {\n if (promiseReject === null) return\n if (error) promiseReject(error)\n else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED)\n else promiseResolve({ value: data, done: data === null })\n promiseReject = promiseResolve = null\n }\n\n function destroy (err) {\n stream.destroy(err)\n return new Promise((resolve, reject) => {\n if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })\n stream.once('close', function () {\n if (err) reject(err)\n else resolve({ value: undefined, done: true })\n })\n })\n }\n }\n}\n\nclass Writable extends Stream {\n constructor (opts) {\n super(opts)\n\n this._duplexState |= OPENING | READ_DONE\n this._writableState = new WritableState(this, opts)\n\n if (opts) {\n if (opts.writev) this._writev = opts.writev\n if (opts.write) this._write = opts.write\n if (opts.final) this._final = opts.final\n if (opts.eagerOpen) this._writableState.updateNextTick()\n }\n }\n\n _writev (batch, cb) {\n cb(null)\n }\n\n _write (data, cb) {\n this._writableState.autoBatch(data, cb)\n }\n\n _final (cb) {\n cb(null)\n }\n\n static isBackpressured (ws) {\n return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0\n }\n\n static drained (ws) {\n if (ws.destroyed) return Promise.resolve(false)\n const state = ws._writableState\n const writes = state.queue.length + ((ws._duplexState & WRITE_WRITING) ? 1 : 0)\n if (writes === 0) return Promise.resolve(true)\n if (state.drains === null) state.drains = []\n return new Promise((resolve) => {\n state.drains.push({ writes, resolve })\n })\n }\n\n write (data) {\n this._writableState.updateNextTick()\n return this._writableState.push(data)\n }\n\n end (data) {\n this._writableState.updateNextTick()\n this._writableState.end(data)\n return this\n }\n}\n\nclass Duplex extends Readable { // and Writable\n constructor (opts) {\n super(opts)\n\n this._duplexState = OPENING\n this._writableState = new WritableState(this, opts)\n\n if (opts) {\n if (opts.writev) this._writev = opts.writev\n if (opts.write) this._write = opts.write\n if (opts.final) this._final = opts.final\n }\n }\n\n _writev (batch, cb) {\n cb(null)\n }\n\n _write (data, cb) {\n this._writableState.autoBatch(data, cb)\n }\n\n _final (cb) {\n cb(null)\n }\n\n write (data) {\n this._writableState.updateNextTick()\n return this._writableState.push(data)\n }\n\n end (data) {\n this._writableState.updateNextTick()\n this._writableState.end(data)\n return this\n }\n}\n\nclass Transform extends Duplex {\n constructor (opts) {\n super(opts)\n this._transformState = new TransformState(this)\n\n if (opts) {\n if (opts.transform) this._transform = opts.transform\n if (opts.flush) this._flush = opts.flush\n }\n }\n\n _write (data, cb) {\n if (this._readableState.buffered >= this._readableState.highWaterMark) {\n this._transformState.data = data\n } else {\n this._transform(data, this._transformState.afterTransform)\n }\n }\n\n _read (cb) {\n if (this._transformState.data !== null) {\n const data = this._transformState.data\n this._transformState.data = null\n cb(null)\n this._transform(data, this._transformState.afterTransform)\n } else {\n cb(null)\n }\n }\n\n _transform (data, cb) {\n cb(null, data)\n }\n\n _flush (cb) {\n cb(null)\n }\n\n _final (cb) {\n this._transformState.afterFinal = cb\n this._flush(transformAfterFlush.bind(this))\n }\n}\n\nclass PassThrough extends Transform {}\n\nfunction transformAfterFlush (err, data) {\n const cb = this._transformState.afterFinal\n if (err) return cb(err)\n if (data !== null && data !== undefined) this.push(data)\n this.push(null)\n cb(null)\n}\n\nfunction pipelinePromise (...streams) {\n return new Promise((resolve, reject) => {\n return pipeline(...streams, (err) => {\n if (err) return reject(err)\n resolve()\n })\n })\n}\n\nfunction pipeline (stream, ...streams) {\n const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]\n const done = (all.length && typeof all[all.length - 1] === 'function') ? all.pop() : null\n\n if (all.length < 2) throw new Error('Pipeline requires at least 2 streams')\n\n let src = all[0]\n let dest = null\n let error = null\n\n for (let i = 1; i < all.length; i++) {\n dest = all[i]\n\n if (isStreamx(src)) {\n src.pipe(dest, onerror)\n } else {\n errorHandle(src, true, i > 1, onerror)\n src.pipe(dest)\n }\n\n src = dest\n }\n\n if (done) {\n let fin = false\n\n const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)\n\n dest.on('error', (err) => {\n if (error === null) error = err\n })\n\n dest.on('finish', () => {\n fin = true\n if (!autoDestroy) done(error)\n })\n\n if (autoDestroy) {\n dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE)))\n }\n }\n\n return dest\n\n function errorHandle (s, rd, wr, onerror) {\n s.on('error', onerror)\n s.on('close', onclose)\n\n function onclose () {\n if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE)\n if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE)\n }\n }\n\n function onerror (err) {\n if (!err || error) return\n error = err\n\n for (const s of all) {\n s.destroy(err)\n }\n }\n}\n\nfunction isStream (stream) {\n return !!stream._readableState || !!stream._writableState\n}\n\nfunction isStreamx (stream) {\n return typeof stream._duplexState === 'number' && isStream(stream)\n}\n\nfunction getStreamError (stream) {\n const err = (stream._readableState && stream._readableState.error) || (stream._writableState && stream._writableState.error)\n return err === STREAM_DESTROYED ? null : err // only explicit errors\n}\n\nfunction isReadStreamx (stream) {\n return isStreamx(stream) && stream.readable\n}\n\nfunction isTypedArray (data) {\n return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'\n}\n\nfunction defaultByteLength (data) {\n return isTypedArray(data) ? data.byteLength : 1024\n}\n\nfunction noop () {}\n\nfunction abort () {\n this.destroy(new Error('Stream aborted.'))\n}\n\nmodule.exports = {\n pipeline,\n pipelinePromise,\n isStream,\n isStreamx,\n getStreamError,\n Stream,\n Writable,\n Readable,\n Duplex,\n Transform,\n // Export PassThrough for compatibility with Node.js core's stream module\n PassThrough\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","var chownr = require('chownr')\nvar tar = require('tar-stream')\nvar pump = require('pump')\nvar mkdirp = require('mkdirp-classic')\nvar fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\nvar win32 = os.platform() === 'win32'\n\nvar noop = function () {}\n\nvar echo = function (name) {\n return name\n}\n\nvar normalize = !win32 ? echo : function (name) {\n return name.replace(/\\\\/g, '/').replace(/[:?<>|]/g, '_')\n}\n\nvar statAll = function (fs, stat, cwd, ignore, entries, sort) {\n var queue = entries || ['.']\n\n return function loop (callback) {\n if (!queue.length) return callback()\n var next = queue.shift()\n var nextAbs = path.join(cwd, next)\n\n stat(nextAbs, function (err, stat) {\n if (err) return callback(err)\n\n if (!stat.isDirectory()) return callback(null, next, stat)\n\n fs.readdir(nextAbs, function (err, files) {\n if (err) return callback(err)\n\n if (sort) files.sort()\n for (var i = 0; i < files.length; i++) {\n if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))\n }\n\n callback(null, next, stat)\n })\n })\n }\n}\n\nvar strip = function (map, level) {\n return function (header) {\n header.name = header.name.split('/').slice(level).join('/')\n\n var linkname = header.linkname\n if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {\n header.linkname = linkname.split('/').slice(level).join('/')\n }\n\n return map(header)\n }\n}\n\nexports.pack = function (cwd, opts) {\n if (!cwd) cwd = '.'\n if (!opts) opts = {}\n\n var xfs = opts.fs || fs\n var ignore = opts.ignore || opts.filter || noop\n var map = opts.map || noop\n var mapStream = opts.mapStream || echo\n var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)\n var strict = opts.strict !== false\n var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()\n var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0\n var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0\n var pack = opts.pack || tar.pack()\n var finish = opts.finish || noop\n\n if (opts.strip) map = strip(map, opts.strip)\n\n if (opts.readable) {\n dmode |= parseInt(555, 8)\n fmode |= parseInt(444, 8)\n }\n if (opts.writable) {\n dmode |= parseInt(333, 8)\n fmode |= parseInt(222, 8)\n }\n\n var onsymlink = function (filename, header) {\n xfs.readlink(path.join(cwd, filename), function (err, linkname) {\n if (err) return pack.destroy(err)\n header.linkname = normalize(linkname)\n pack.entry(header, onnextentry)\n })\n }\n\n var onstat = function (err, filename, stat) {\n if (err) return pack.destroy(err)\n if (!filename) {\n if (opts.finalize !== false) pack.finalize()\n return finish(pack)\n }\n\n if (stat.isSocket()) return onnextentry() // tar does not support sockets...\n\n var header = {\n name: normalize(filename),\n mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,\n mtime: stat.mtime,\n size: stat.size,\n type: 'file',\n uid: stat.uid,\n gid: stat.gid\n }\n\n if (stat.isDirectory()) {\n header.size = 0\n header.type = 'directory'\n header = map(header) || header\n return pack.entry(header, onnextentry)\n }\n\n if (stat.isSymbolicLink()) {\n header.size = 0\n header.type = 'symlink'\n header = map(header) || header\n return onsymlink(filename, header)\n }\n\n // TODO: add fifo etc...\n\n header = map(header) || header\n\n if (!stat.isFile()) {\n if (strict) return pack.destroy(new Error('unsupported type for ' + filename))\n return onnextentry()\n }\n\n var entry = pack.entry(header, onnextentry)\n if (!entry) return\n\n var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)\n\n rs.on('error', function (err) { // always forward errors on destroy\n entry.destroy(err)\n })\n\n pump(rs, entry)\n }\n\n var onnextentry = function (err) {\n if (err) return pack.destroy(err)\n statNext(onstat)\n }\n\n onnextentry()\n\n return pack\n}\n\nvar head = function (list) {\n return list.length ? list[list.length - 1] : null\n}\n\nvar processGetuid = function () {\n return process.getuid ? process.getuid() : -1\n}\n\nvar processUmask = function () {\n return process.umask ? process.umask() : 0\n}\n\nexports.extract = function (cwd, opts) {\n if (!cwd) cwd = '.'\n if (!opts) opts = {}\n\n var xfs = opts.fs || fs\n var ignore = opts.ignore || opts.filter || noop\n var map = opts.map || noop\n var mapStream = opts.mapStream || echo\n var own = opts.chown !== false && !win32 && processGetuid() === 0\n var extract = opts.extract || tar.extract()\n var stack = []\n var now = new Date()\n var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()\n var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0\n var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0\n var strict = opts.strict !== false\n\n if (opts.strip) map = strip(map, opts.strip)\n\n if (opts.readable) {\n dmode |= parseInt(555, 8)\n fmode |= parseInt(444, 8)\n }\n if (opts.writable) {\n dmode |= parseInt(333, 8)\n fmode |= parseInt(222, 8)\n }\n\n var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry\n var top\n while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()\n if (!top) return cb()\n xfs.utimes(top[0], now, top[1], cb)\n }\n\n var utimes = function (name, header, cb) {\n if (opts.utimes === false) return cb()\n\n if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)\n if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?\n\n xfs.utimes(name, now, header.mtime, function (err) {\n if (err) return cb(err)\n utimesParent(name, cb)\n })\n }\n\n var chperm = function (name, header, cb) {\n var link = header.type === 'symlink'\n\n /* eslint-disable node/no-deprecated-api */\n var chmod = link ? xfs.lchmod : xfs.chmod\n var chown = link ? xfs.lchown : xfs.chown\n /* eslint-enable node/no-deprecated-api */\n\n if (!chmod) return cb()\n\n var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask\n chmod(name, mode, function (err) {\n if (err) return cb(err)\n if (!own) return cb()\n if (!chown) return cb()\n chown(name, header.uid, header.gid, cb)\n })\n }\n\n extract.on('entry', function (header, stream, next) {\n header = map(header) || header\n header.name = normalize(header.name)\n var name = path.join(cwd, path.join('/', header.name))\n\n if (ignore(name, header)) {\n stream.resume()\n return next()\n }\n\n var stat = function (err) {\n if (err) return next(err)\n utimes(name, header, function (err) {\n if (err) return next(err)\n if (win32) return next()\n chperm(name, header, next)\n })\n }\n\n var onsymlink = function () {\n if (win32) return next() // skip symlinks on win for now before it can be tested\n xfs.unlink(name, function () {\n xfs.symlink(header.linkname, name, stat)\n })\n }\n\n var onlink = function () {\n if (win32) return next() // skip links on win for now before it can be tested\n xfs.unlink(name, function () {\n var srcpath = path.join(cwd, path.join('/', header.linkname))\n\n xfs.link(srcpath, name, function (err) {\n if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {\n stream = xfs.createReadStream(srcpath)\n return onfile()\n }\n\n stat(err)\n })\n })\n }\n\n var onfile = function () {\n var ws = xfs.createWriteStream(name)\n var rs = mapStream(stream, header)\n\n ws.on('error', function (err) { // always forward errors on destroy\n rs.destroy(err)\n })\n\n pump(rs, ws, function (err) {\n if (err) return next(err)\n ws.on('close', stat)\n })\n }\n\n if (header.type === 'directory') {\n stack.push([name, header.mtime])\n return mkdirfix(name, {\n fs: xfs, own: own, uid: header.uid, gid: header.gid\n }, stat)\n }\n\n var dir = path.dirname(name)\n\n validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {\n if (err) return next(err)\n if (!valid) return next(new Error(dir + ' is not a valid path'))\n\n mkdirfix(dir, {\n fs: xfs, own: own, uid: header.uid, gid: header.gid\n }, function (err) {\n if (err) return next(err)\n\n switch (header.type) {\n case 'file': return onfile()\n case 'link': return onlink()\n case 'symlink': return onsymlink()\n }\n\n if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))\n\n stream.resume()\n next()\n })\n })\n })\n\n if (opts.finish) extract.on('finish', opts.finish)\n\n return extract\n}\n\nfunction validate (fs, name, root, cb) {\n if (name === root) return cb(null, true)\n fs.lstat(name, function (err, st) {\n if (err && err.code !== 'ENOENT') return cb(err)\n if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)\n cb(null, false)\n })\n}\n\nfunction mkdirfix (name, opts, cb) {\n mkdirp(name, { fs: opts.fs }, function (err, made) {\n if (!err && made && opts.own) {\n chownr(made, opts.uid, opts.gid, cb)\n } else {\n cb(err)\n }\n })\n}\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst symbol = Symbol.for('BufferList')\n\nfunction BufferList (buf) {\n if (!(this instanceof BufferList)) {\n return new BufferList(buf)\n }\n\n BufferList._init.call(this, buf)\n}\n\nBufferList._init = function _init (buf) {\n Object.defineProperty(this, symbol, { value: true })\n\n this._bufs = []\n this.length = 0\n\n if (buf) {\n this.append(buf)\n }\n}\n\nBufferList.prototype._new = function _new (buf) {\n return new BufferList(buf)\n}\n\nBufferList.prototype._offset = function _offset (offset) {\n if (offset === 0) {\n return [0, 0]\n }\n\n let tot = 0\n\n for (let i = 0; i < this._bufs.length; i++) {\n const _t = tot + this._bufs[i].length\n if (offset < _t || i === this._bufs.length - 1) {\n return [i, offset - tot]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n const bufferId = blOffset[0]\n let offset = blOffset[1]\n\n for (let i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n\n return offset\n}\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n\n const offset = this._offset(index)\n\n return this._bufs[offset[0]][offset[1]]\n}\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start === 'number' && start < 0) {\n start += this.length\n }\n\n if (typeof end === 'number' && end < 0) {\n end += this.length\n }\n\n return this.copy(null, 0, start, end)\n}\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart !== 'number' || srcStart < 0) {\n srcStart = 0\n }\n\n if (typeof srcEnd !== 'number' || srcEnd > this.length) {\n srcEnd = this.length\n }\n\n if (srcStart >= this.length) {\n return dst || Buffer.alloc(0)\n }\n\n if (srcEnd <= 0) {\n return dst || Buffer.alloc(0)\n }\n\n const copy = !!dst\n const off = this._offset(srcStart)\n const len = srcEnd - srcStart\n let bytes = len\n let bufoff = (copy && dstStart) || 0\n let start = off[1]\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd === this.length) {\n if (!copy) {\n // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (let i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) {\n // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n }\n\n for (let i = off[0]; i < this._bufs.length; i++) {\n const l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start) {\n start = 0\n }\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0) {\n start += this.length\n }\n\n if (end < 0) {\n end += this.length\n }\n\n if (start === end) {\n return this._new()\n }\n\n const startOffset = this._offset(start)\n const endOffset = this._offset(end)\n const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] === 0) {\n buffers.pop()\n } else {\n buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])\n }\n\n if (startOffset[1] !== 0) {\n buffers[0] = buffers[0].slice(startOffset[1])\n }\n\n return this._new(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n\n return this\n}\n\nBufferList.prototype.duplicate = function duplicate () {\n const copy = this._new()\n\n for (let i = 0; i < this._bufs.length; i++) {\n copy.append(this._bufs[i])\n }\n\n return copy\n}\n\nBufferList.prototype.append = function append (buf) {\n if (buf == null) {\n return this\n }\n\n if (buf.buffer) {\n // append a view of the underlying ArrayBuffer\n this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))\n } else if (Array.isArray(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.append(buf[i])\n }\n } else if (this._isBufferList(buf)) {\n // unwrap argument into individual BufferLists\n for (let i = 0; i < buf._bufs.length; i++) {\n this.append(buf._bufs[i])\n }\n } else {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf === 'number') {\n buf = buf.toString()\n }\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (this._isBufferList(search)) {\n search = search.slice()\n } else if (Array.isArray(search.buffer)) {\n search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n const blOffset = this._offset(offset)\n let blIndex = blOffset[0] // index of which internal buffer we're working on\n let buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (; blIndex < this._bufs.length; blIndex++) {\n const buff = this._bufs[blIndex]\n\n while (buffOffset < buff.length) {\n const availableWindow = buff.length - buffOffset\n\n if (availableWindow >= search.length) {\n const nativeSearchResult = buff.indexOf(search, buffOffset)\n\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n const revOffset = this._reverseOffset([blIndex, buffOffset])\n\n if (this._match(revOffset, search)) {\n return revOffset\n }\n\n buffOffset++\n }\n }\n\n buffOffset = 0\n }\n\n return -1\n}\n\nBufferList.prototype._match = function (offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n\n for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {\n if (this.get(offset + searchOffset) !== search[searchOffset]) {\n return false\n }\n }\n return true\n}\n\n;(function () {\n const methods = {\n readDoubleBE: 8,\n readDoubleLE: 8,\n readFloatBE: 4,\n readFloatLE: 4,\n readInt32BE: 4,\n readInt32LE: 4,\n readUInt32BE: 4,\n readUInt32LE: 4,\n readInt16BE: 2,\n readInt16LE: 2,\n readUInt16BE: 2,\n readUInt16LE: 2,\n readInt8: 1,\n readUInt8: 1,\n readIntBE: null,\n readIntLE: null,\n readUIntBE: null,\n readUIntLE: null\n }\n\n for (const m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n } else {\n BufferList.prototype[m] = function (offset = 0) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n// Used internally by the class and also as an indicator of this object being\n// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser\n// environment because there could be multiple different copies of the\n// BufferList class and some `BufferList`s might be `BufferList`s.\nBufferList.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferList || BufferList.isBufferList(b)\n}\n\nBufferList.isBufferList = function isBufferList (b) {\n return b != null && b[symbol]\n}\n\nmodule.exports = BufferList\n","'use strict'\n\nconst DuplexStream = require('readable-stream').Duplex\nconst inherits = require('inherits')\nconst BufferList = require('./BufferList')\n\nfunction BufferListStream (callback) {\n if (!(this instanceof BufferListStream)) {\n return new BufferListStream(callback)\n }\n\n if (typeof callback === 'function') {\n this._callback = callback\n\n const piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n\n callback = null\n }\n\n BufferList._init.call(this, callback)\n DuplexStream.call(this)\n}\n\ninherits(BufferListStream, DuplexStream)\nObject.assign(BufferListStream.prototype, BufferList.prototype)\n\nBufferListStream.prototype._new = function _new (callback) {\n return new BufferListStream(callback)\n}\n\nBufferListStream.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback === 'function') {\n callback()\n }\n}\n\nBufferListStream.prototype._read = function _read (size) {\n if (!this.length) {\n return this.push(null)\n }\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\nBufferListStream.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\nBufferListStream.prototype._destroy = function _destroy (err, cb) {\n this._bufs.length = 0\n this.length = 0\n cb(err)\n}\n\nBufferListStream.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)\n}\n\nBufferListStream.isBufferList = BufferList.isBufferList\n\nmodule.exports = BufferListStream\nmodule.exports.BufferListStream = BufferListStream\nmodule.exports.BufferList = BufferList\n","var util = require('util')\nvar bl = require('bl')\nvar headers = require('./headers')\n\nvar Writable = require('readable-stream').Writable\nvar PassThrough = require('readable-stream').PassThrough\n\nvar noop = function () {}\n\nvar overflow = function (size) {\n size &= 511\n return size && 512 - size\n}\n\nvar emptyStream = function (self, offset) {\n var s = new Source(self, offset)\n s.end()\n return s\n}\n\nvar mixinPax = function (header, pax) {\n if (pax.path) header.name = pax.path\n if (pax.linkpath) header.linkname = pax.linkpath\n if (pax.size) header.size = parseInt(pax.size, 10)\n header.pax = pax\n return header\n}\n\nvar Source = function (self, offset) {\n this._parent = self\n this.offset = offset\n PassThrough.call(this, { autoDestroy: false })\n}\n\nutil.inherits(Source, PassThrough)\n\nSource.prototype.destroy = function (err) {\n this._parent.destroy(err)\n}\n\nvar Extract = function (opts) {\n if (!(this instanceof Extract)) return new Extract(opts)\n Writable.call(this, opts)\n\n opts = opts || {}\n\n this._offset = 0\n this._buffer = bl()\n this._missing = 0\n this._partial = false\n this._onparse = noop\n this._header = null\n this._stream = null\n this._overflow = null\n this._cb = null\n this._locked = false\n this._destroyed = false\n this._pax = null\n this._paxGlobal = null\n this._gnuLongPath = null\n this._gnuLongLinkPath = null\n\n var self = this\n var b = self._buffer\n\n var oncontinue = function () {\n self._continue()\n }\n\n var onunlock = function (err) {\n self._locked = false\n if (err) return self.destroy(err)\n if (!self._stream) oncontinue()\n }\n\n var onstreamend = function () {\n self._stream = null\n var drain = overflow(self._header.size)\n if (drain) self._parse(drain, ondrain)\n else self._parse(512, onheader)\n if (!self._locked) oncontinue()\n }\n\n var ondrain = function () {\n self._buffer.consume(overflow(self._header.size))\n self._parse(512, onheader)\n oncontinue()\n }\n\n var onpaxglobalheader = function () {\n var size = self._header.size\n self._paxGlobal = headers.decodePax(b.slice(0, size))\n b.consume(size)\n onstreamend()\n }\n\n var onpaxheader = function () {\n var size = self._header.size\n self._pax = headers.decodePax(b.slice(0, size))\n if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulongpath = function () {\n var size = self._header.size\n this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulonglinkpath = function () {\n var size = self._header.size\n this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var onheader = function () {\n var offset = self._offset\n var header\n try {\n header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat)\n } catch (err) {\n self.emit('error', err)\n }\n b.consume(512)\n\n if (!header) {\n self._parse(512, onheader)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-path') {\n self._parse(header.size, ongnulongpath)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-link-path') {\n self._parse(header.size, ongnulonglinkpath)\n oncontinue()\n return\n }\n if (header.type === 'pax-global-header') {\n self._parse(header.size, onpaxglobalheader)\n oncontinue()\n return\n }\n if (header.type === 'pax-header') {\n self._parse(header.size, onpaxheader)\n oncontinue()\n return\n }\n\n if (self._gnuLongPath) {\n header.name = self._gnuLongPath\n self._gnuLongPath = null\n }\n\n if (self._gnuLongLinkPath) {\n header.linkname = self._gnuLongLinkPath\n self._gnuLongLinkPath = null\n }\n\n if (self._pax) {\n self._header = header = mixinPax(header, self._pax)\n self._pax = null\n }\n\n self._locked = true\n\n if (!header.size || header.type === 'directory') {\n self._parse(512, onheader)\n self.emit('entry', header, emptyStream(self, offset), onunlock)\n return\n }\n\n self._stream = new Source(self, offset)\n\n self.emit('entry', header, self._stream, onunlock)\n self._parse(header.size, onstreamend)\n oncontinue()\n }\n\n this._onheader = onheader\n this._parse(512, onheader)\n}\n\nutil.inherits(Extract, Writable)\n\nExtract.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream) this._stream.emit('close')\n}\n\nExtract.prototype._parse = function (size, onparse) {\n if (this._destroyed) return\n this._offset += size\n this._missing = size\n if (onparse === this._onheader) this._partial = false\n this._onparse = onparse\n}\n\nExtract.prototype._continue = function () {\n if (this._destroyed) return\n var cb = this._cb\n this._cb = noop\n if (this._overflow) this._write(this._overflow, undefined, cb)\n else cb()\n}\n\nExtract.prototype._write = function (data, enc, cb) {\n if (this._destroyed) return\n\n var s = this._stream\n var b = this._buffer\n var missing = this._missing\n if (data.length) this._partial = true\n\n // we do not reach end-of-chunk now. just forward it\n\n if (data.length < missing) {\n this._missing -= data.length\n this._overflow = null\n if (s) return s.write(data, cb)\n b.append(data)\n return cb()\n }\n\n // end-of-chunk. the parser should call cb.\n\n this._cb = cb\n this._missing = 0\n\n var overflow = null\n if (data.length > missing) {\n overflow = data.slice(missing)\n data = data.slice(0, missing)\n }\n\n if (s) s.end(data)\n else b.append(data)\n\n this._overflow = overflow\n this._onparse()\n}\n\nExtract.prototype._final = function (cb) {\n if (this._partial) return this.destroy(new Error('Unexpected end of data'))\n cb()\n}\n\nmodule.exports = Extract\n","var alloc = Buffer.alloc\n\nvar ZEROS = '0000000000000000000'\nvar SEVENS = '7777777777777777777'\nvar ZERO_OFFSET = '0'.charCodeAt(0)\nvar USTAR_MAGIC = Buffer.from('ustar\\x00', 'binary')\nvar USTAR_VER = Buffer.from('00', 'binary')\nvar GNU_MAGIC = Buffer.from('ustar\\x20', 'binary')\nvar GNU_VER = Buffer.from('\\x20\\x00', 'binary')\nvar MASK = parseInt('7777', 8)\nvar MAGIC_OFFSET = 257\nvar VERSION_OFFSET = 263\n\nvar clamp = function (index, len, defaultValue) {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nvar toType = function (flag) {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n }\n\n return null\n}\n\nvar toTypeflag = function (flag) {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n }\n\n return 0\n}\n\nvar indexOf = function (block, num, offset, end) {\n for (; offset < end; offset++) {\n if (block[offset] === num) return offset\n }\n return end\n}\n\nvar cksum = function (block) {\n var sum = 8 * 32\n for (var i = 0; i < 148; i++) sum += block[i]\n for (var j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nvar encodeOct = function (val, n) {\n val = val.toString(8)\n if (val.length > n) return SEVENS.slice(0, n) + ' '\n else return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n var positive\n if (buf[0] === 0x80) positive = true\n else if (buf[0] === 0xFF) positive = false\n else return null\n\n // build up a base-256 tuple from the least sig to the highest\n var tuple = []\n for (var i = buf.length - 1; i > 0; i--) {\n var byte = buf[i]\n if (positive) tuple.push(byte)\n else tuple.push(0xFF - byte)\n }\n\n var sum = 0\n var l = tuple.length\n for (i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nvar decodeOct = function (val, offset, length) {\n val = val.slice(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if (val[offset] & 0x80) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val[offset] === 32) offset++\n var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n while (offset < end && val[offset] === 0) offset++\n if (end === offset) return 0\n return parseInt(val.slice(offset, end).toString(), 8)\n }\n}\n\nvar decodeStr = function (val, offset, length, encoding) {\n return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding)\n}\n\nvar addLength = function (str) {\n var len = Buffer.byteLength(str)\n var digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n if (len + digits >= Math.pow(10, digits)) digits++\n\n return (len + digits) + str\n}\n\nexports.decodeLongPath = function (buf, encoding) {\n return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function (opts) { // TODO: encode more stuff in pax\n var result = ''\n if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n var pax = opts.pax\n if (pax) {\n for (var key in pax) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n return Buffer.from(result)\n}\n\nexports.decodePax = function (buf) {\n var result = {}\n\n while (buf.length) {\n var i = 0\n while (i < buf.length && buf[i] !== 32) i++\n var len = parseInt(buf.slice(0, i).toString(), 10)\n if (!len) return result\n\n var b = buf.slice(i + 1, len - 1).toString()\n var keyIndex = b.indexOf('=')\n if (keyIndex === -1) return result\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n buf = buf.slice(len)\n }\n\n return result\n}\n\nexports.encode = function (opts) {\n var buf = alloc(512)\n var name = opts.name\n var prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n if (Buffer.byteLength(name) !== name.length) return null // utf-8\n\n while (Buffer.byteLength(name) > 100) {\n var i = name.indexOf('/')\n if (i === -1) return null\n prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null\n if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null\n\n buf.write(name)\n buf.write(encodeOct(opts.mode & MASK, 6), 100)\n buf.write(encodeOct(opts.uid, 6), 108)\n buf.write(encodeOct(opts.gid, 6), 116)\n buf.write(encodeOct(opts.size, 11), 124)\n buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname) buf.write(opts.linkname, 157)\n\n USTAR_MAGIC.copy(buf, MAGIC_OFFSET)\n USTAR_VER.copy(buf, VERSION_OFFSET)\n if (opts.uname) buf.write(opts.uname, 265)\n if (opts.gname) buf.write(opts.gname, 297)\n buf.write(encodeOct(opts.devmajor || 0, 6), 329)\n buf.write(encodeOct(opts.devminor || 0, 6), 337)\n\n if (prefix) buf.write(prefix, 345)\n\n buf.write(encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n\nexports.decode = function (buf, filenameEncoding, allowUnknownFormat) {\n var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n var name = decodeStr(buf, 0, 100, filenameEncoding)\n var mode = decodeOct(buf, 100, 8)\n var uid = decodeOct(buf, 108, 8)\n var gid = decodeOct(buf, 116, 8)\n var size = decodeOct(buf, 124, 12)\n var mtime = decodeOct(buf, 136, 12)\n var type = toType(typeflag)\n var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n var uname = decodeStr(buf, 265, 32)\n var gname = decodeStr(buf, 297, 32)\n var devmajor = decodeOct(buf, 329, 8)\n var devminor = decodeOct(buf, 337, 8)\n\n var c = cksum(buf)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) return null\n\n // valid checksum\n if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 &&\n GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n if (!allowUnknownFormat) {\n throw new Error('Invalid tar header: unknown format.')\n }\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * mtime),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor\n }\n}\n","exports.extract = require('./extract')\nexports.pack = require('./pack')\n","var constants = require('fs-constants')\nvar eos = require('end-of-stream')\nvar inherits = require('inherits')\nvar alloc = Buffer.alloc\n\nvar Readable = require('readable-stream').Readable\nvar Writable = require('readable-stream').Writable\nvar StringDecoder = require('string_decoder').StringDecoder\n\nvar headers = require('./headers')\n\nvar DMODE = parseInt('755', 8)\nvar FMODE = parseInt('644', 8)\n\nvar END_OF_TAR = alloc(1024)\n\nvar noop = function () {}\n\nvar overflow = function (self, size) {\n size &= 511\n if (size) self.push(END_OF_TAR.slice(0, 512 - size))\n}\n\nfunction modeToType (mode) {\n switch (mode & constants.S_IFMT) {\n case constants.S_IFBLK: return 'block-device'\n case constants.S_IFCHR: return 'character-device'\n case constants.S_IFDIR: return 'directory'\n case constants.S_IFIFO: return 'fifo'\n case constants.S_IFLNK: return 'symlink'\n }\n\n return 'file'\n}\n\nvar Sink = function (to) {\n Writable.call(this)\n this.written = 0\n this._to = to\n this._destroyed = false\n}\n\ninherits(Sink, Writable)\n\nSink.prototype._write = function (data, enc, cb) {\n this.written += data.length\n if (this._to.push(data)) return cb()\n this._to._drain = cb\n}\n\nSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar LinkSink = function () {\n Writable.call(this)\n this.linkname = ''\n this._decoder = new StringDecoder('utf-8')\n this._destroyed = false\n}\n\ninherits(LinkSink, Writable)\n\nLinkSink.prototype._write = function (data, enc, cb) {\n this.linkname += this._decoder.write(data)\n cb()\n}\n\nLinkSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Void = function () {\n Writable.call(this)\n this._destroyed = false\n}\n\ninherits(Void, Writable)\n\nVoid.prototype._write = function (data, enc, cb) {\n cb(new Error('No body allowed for this entry'))\n}\n\nVoid.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Pack = function (opts) {\n if (!(this instanceof Pack)) return new Pack(opts)\n Readable.call(this, opts)\n\n this._drain = noop\n this._finalized = false\n this._finalizing = false\n this._destroyed = false\n this._stream = null\n}\n\ninherits(Pack, Readable)\n\nPack.prototype.entry = function (header, buffer, callback) {\n if (this._stream) throw new Error('already piping an entry')\n if (this._finalized || this._destroyed) return\n\n if (typeof buffer === 'function') {\n callback = buffer\n buffer = null\n }\n\n if (!callback) callback = noop\n\n var self = this\n\n if (!header.size || header.type === 'symlink') header.size = 0\n if (!header.type) header.type = modeToType(header.mode)\n if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n if (!header.uid) header.uid = 0\n if (!header.gid) header.gid = 0\n if (!header.mtime) header.mtime = new Date()\n\n if (typeof buffer === 'string') buffer = Buffer.from(buffer)\n if (Buffer.isBuffer(buffer)) {\n header.size = buffer.length\n this._encode(header)\n var ok = this.push(buffer)\n overflow(self, header.size)\n if (ok) process.nextTick(callback)\n else this._drain = callback\n return new Void()\n }\n\n if (header.type === 'symlink' && !header.linkname) {\n var linkSink = new LinkSink()\n eos(linkSink, function (err) {\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n header.linkname = linkSink.linkname\n self._encode(header)\n callback()\n })\n\n return linkSink\n }\n\n this._encode(header)\n\n if (header.type !== 'file' && header.type !== 'contiguous-file') {\n process.nextTick(callback)\n return new Void()\n }\n\n var sink = new Sink(this)\n\n this._stream = sink\n\n eos(sink, function (err) {\n self._stream = null\n\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n if (sink.written !== header.size) { // corrupting tar\n self.destroy()\n return callback(new Error('size mismatch'))\n }\n\n overflow(self, header.size)\n if (self._finalizing) self.finalize()\n callback()\n })\n\n return sink\n}\n\nPack.prototype.finalize = function () {\n if (this._stream) {\n this._finalizing = true\n return\n }\n\n if (this._finalized) return\n this._finalized = true\n this.push(END_OF_TAR)\n this.push(null)\n}\n\nPack.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream && this._stream.destroy) this._stream.destroy()\n}\n\nPack.prototype._encode = function (header) {\n if (!header.pax) {\n var buf = headers.encode(header)\n if (buf) {\n this.push(buf)\n return\n }\n }\n this._encodePax(header)\n}\n\nPack.prototype._encodePax = function (header) {\n var paxHeader = headers.encodePax({\n name: header.name,\n linkname: header.linkname,\n pax: header.pax\n })\n\n var newHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.length,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname && 'PaxHeader',\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n this.push(headers.encode(newHeader))\n this.push(paxHeader)\n overflow(this, paxHeader.length)\n\n newHeader.size = header.size\n newHeader.type = header.type\n this.push(headers.encode(newHeader))\n}\n\nPack.prototype._read = function (n) {\n var drain = this._drain\n this._drain = noop\n drain()\n}\n\nmodule.exports = Pack\n","const constants = { // just for envs without fs\n S_IFMT: 61440,\n S_IFDIR: 16384,\n S_IFCHR: 8192,\n S_IFBLK: 24576,\n S_IFIFO: 4096,\n S_IFLNK: 40960\n}\n\ntry {\n module.exports = require('fs').constants || constants\n} catch {\n module.exports = constants\n}\n","const { Writable, Readable, getStreamError } = require('streamx')\nconst FIFO = require('fast-fifo')\nconst b4a = require('b4a')\nconst headers = require('./headers')\n\nconst EMPTY = b4a.alloc(0)\n\nclass BufferList {\n constructor () {\n this.buffered = 0\n this.shifted = 0\n this.queue = new FIFO()\n\n this._offset = 0\n }\n\n push (buffer) {\n this.buffered += buffer.byteLength\n this.queue.push(buffer)\n }\n\n shiftFirst (size) {\n return this._buffered === 0 ? null : this._next(size)\n }\n\n shift (size) {\n if (size > this.buffered) return null\n if (size === 0) return EMPTY\n\n let chunk = this._next(size)\n\n if (size === chunk.byteLength) return chunk // likely case\n\n const chunks = [chunk]\n\n while ((size -= chunk.byteLength) > 0) {\n chunk = this._next(size)\n chunks.push(chunk)\n }\n\n return b4a.concat(chunks)\n }\n\n _next (size) {\n const buf = this.queue.peek()\n const rem = buf.byteLength - this._offset\n\n if (size >= rem) {\n const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf\n this.queue.shift()\n this._offset = 0\n this.buffered -= rem\n this.shifted += rem\n return sub\n }\n\n this.buffered -= size\n this.shifted += size\n\n return buf.subarray(this._offset, (this._offset += size))\n }\n}\n\nclass Source extends Readable {\n constructor (self, header, offset) {\n super()\n\n this.header = header\n this.offset = offset\n\n this._parent = self\n }\n\n _read (cb) {\n if (this.header.size === 0) {\n this.push(null)\n }\n if (this._parent._stream === this) {\n this._parent._update()\n }\n cb(null)\n }\n\n _predestroy () {\n this._parent.destroy(getStreamError(this))\n }\n\n _detach () {\n if (this._parent._stream === this) {\n this._parent._stream = null\n this._parent._missing = overflow(this.header.size)\n this._parent._update()\n }\n }\n\n _destroy (cb) {\n this._detach()\n cb(null)\n }\n}\n\nclass Extract extends Writable {\n constructor (opts) {\n super(opts)\n\n if (!opts) opts = {}\n\n this._buffer = new BufferList()\n this._offset = 0\n this._header = null\n this._stream = null\n this._missing = 0\n this._longHeader = false\n this._callback = noop\n this._locked = false\n this._finished = false\n this._pax = null\n this._paxGlobal = null\n this._gnuLongPath = null\n this._gnuLongLinkPath = null\n this._filenameEncoding = opts.filenameEncoding || 'utf-8'\n this._allowUnknownFormat = !!opts.allowUnknownFormat\n this._unlockBound = this._unlock.bind(this)\n }\n\n _unlock (err) {\n this._locked = false\n\n if (err) {\n this.destroy(err)\n this._continueWrite(err)\n return\n }\n\n this._update()\n }\n\n _consumeHeader () {\n if (this._locked) return false\n\n this._offset = this._buffer.shifted\n\n try {\n this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat)\n } catch (err) {\n this._continueWrite(err)\n return false\n }\n\n if (!this._header) return true\n\n switch (this._header.type) {\n case 'gnu-long-path':\n case 'gnu-long-link-path':\n case 'pax-global-header':\n case 'pax-header':\n this._longHeader = true\n this._missing = this._header.size\n return true\n }\n\n this._locked = true\n this._applyLongHeaders()\n\n if (this._header.size === 0 || this._header.type === 'directory') {\n this.emit('entry', this._header, this._createStream(), this._unlockBound)\n return true\n }\n\n this._stream = this._createStream()\n this._missing = this._header.size\n\n this.emit('entry', this._header, this._stream, this._unlockBound)\n return true\n }\n\n _applyLongHeaders () {\n if (this._gnuLongPath) {\n this._header.name = this._gnuLongPath\n this._gnuLongPath = null\n }\n\n if (this._gnuLongLinkPath) {\n this._header.linkname = this._gnuLongLinkPath\n this._gnuLongLinkPath = null\n }\n\n if (this._pax) {\n if (this._pax.path) this._header.name = this._pax.path\n if (this._pax.linkpath) this._header.linkname = this._pax.linkpath\n if (this._pax.size) this._header.size = parseInt(this._pax.size, 10)\n this._header.pax = this._pax\n this._pax = null\n }\n }\n\n _decodeLongHeader (buf) {\n switch (this._header.type) {\n case 'gnu-long-path':\n this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding)\n break\n case 'gnu-long-link-path':\n this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding)\n break\n case 'pax-global-header':\n this._paxGlobal = headers.decodePax(buf)\n break\n case 'pax-header':\n this._pax = this._paxGlobal === null\n ? headers.decodePax(buf)\n : Object.assign({}, this._paxGlobal, headers.decodePax(buf))\n break\n }\n }\n\n _consumeLongHeader () {\n this._longHeader = false\n this._missing = overflow(this._header.size)\n\n const buf = this._buffer.shift(this._header.size)\n\n try {\n this._decodeLongHeader(buf)\n } catch (err) {\n this._continueWrite(err)\n return false\n }\n\n return true\n }\n\n _consumeStream () {\n const buf = this._buffer.shiftFirst(this._missing)\n if (buf === null) return false\n\n this._missing -= buf.byteLength\n const drained = this._stream.push(buf)\n\n if (this._missing === 0) {\n this._stream.push(null)\n if (drained) this._stream._detach()\n return drained && this._locked === false\n }\n\n return drained\n }\n\n _createStream () {\n return new Source(this, this._header, this._offset)\n }\n\n _update () {\n while (this._buffer.buffered > 0 && !this.destroying) {\n if (this._missing > 0) {\n if (this._stream !== null) {\n if (this._consumeStream() === false) return\n continue\n }\n\n if (this._longHeader === true) {\n if (this._missing > this._buffer.buffered) break\n if (this._consumeLongHeader() === false) return false\n continue\n }\n\n const ignore = this._buffer.shiftFirst(this._missing)\n if (ignore !== null) this._missing -= ignore.byteLength\n continue\n }\n\n if (this._buffer.buffered < 512) break\n if (this._stream !== null || this._consumeHeader() === false) return\n }\n\n this._continueWrite(null)\n }\n\n _continueWrite (err) {\n const cb = this._callback\n this._callback = noop\n cb(err)\n }\n\n _write (data, cb) {\n this._callback = cb\n this._buffer.push(data)\n this._update()\n }\n\n _final (cb) {\n this._finished = this._missing === 0 && this._buffer.buffered === 0\n cb(this._finished ? null : new Error('Unexpected end of data'))\n }\n\n _predestroy () {\n this._continueWrite(null)\n }\n\n _destroy (cb) {\n if (this._stream) this._stream.destroy(getStreamError(this))\n cb(null)\n }\n\n [Symbol.asyncIterator] () {\n let error = null\n\n let promiseResolve = null\n let promiseReject = null\n\n let entryStream = null\n let entryCallback = null\n\n const extract = this\n\n this.on('entry', onentry)\n this.on('error', (err) => { error = err })\n this.on('close', onclose)\n\n return {\n [Symbol.asyncIterator] () {\n return this\n },\n next () {\n return new Promise(onnext)\n },\n return () {\n return destroy(null)\n },\n throw (err) {\n return destroy(err)\n }\n }\n\n function consumeCallback (err) {\n if (!entryCallback) return\n const cb = entryCallback\n entryCallback = null\n cb(err)\n }\n\n function onnext (resolve, reject) {\n if (error) {\n return reject(error)\n }\n\n if (entryStream) {\n resolve({ value: entryStream, done: false })\n entryStream = null\n return\n }\n\n promiseResolve = resolve\n promiseReject = reject\n\n consumeCallback(null)\n\n if (extract._finished && promiseResolve) {\n promiseResolve({ value: undefined, done: true })\n promiseResolve = promiseReject = null\n }\n }\n\n function onentry (header, stream, callback) {\n entryCallback = callback\n stream.on('error', noop) // no way around this due to tick sillyness\n\n if (promiseResolve) {\n promiseResolve({ value: stream, done: false })\n promiseResolve = promiseReject = null\n } else {\n entryStream = stream\n }\n }\n\n function onclose () {\n consumeCallback(error)\n if (!promiseResolve) return\n if (error) promiseReject(error)\n else promiseResolve({ value: undefined, done: true })\n promiseResolve = promiseReject = null\n }\n\n function destroy (err) {\n extract.destroy(err)\n consumeCallback(err)\n return new Promise((resolve, reject) => {\n if (extract.destroyed) return resolve({ value: undefined, done: true })\n extract.once('close', function () {\n if (err) reject(err)\n else resolve({ value: undefined, done: true })\n })\n })\n }\n }\n}\n\nmodule.exports = function extract (opts) {\n return new Extract(opts)\n}\n\nfunction noop () {}\n\nfunction overflow (size) {\n size &= 511\n return size && 512 - size\n}\n","const b4a = require('b4a')\n\nconst ZEROS = '0000000000000000000'\nconst SEVENS = '7777777777777777777'\nconst ZERO_OFFSET = '0'.charCodeAt(0)\nconst USTAR_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x00]) // ustar\\x00\nconst USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET])\nconst GNU_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x20]) // ustar\\x20\nconst GNU_VER = b4a.from([0x20, 0x00])\nconst MASK = 0o7777\nconst MAGIC_OFFSET = 257\nconst VERSION_OFFSET = 263\n\nexports.decodeLongPath = function decodeLongPath (buf, encoding) {\n return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function encodePax (opts) { // TODO: encode more stuff in pax\n let result = ''\n if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n const pax = opts.pax\n if (pax) {\n for (const key in pax) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n return b4a.from(result)\n}\n\nexports.decodePax = function decodePax (buf) {\n const result = {}\n\n while (buf.length) {\n let i = 0\n while (i < buf.length && buf[i] !== 32) i++\n const len = parseInt(b4a.toString(buf.subarray(0, i)), 10)\n if (!len) return result\n\n const b = b4a.toString(buf.subarray(i + 1, len - 1))\n const keyIndex = b.indexOf('=')\n if (keyIndex === -1) return result\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n buf = buf.subarray(len)\n }\n\n return result\n}\n\nexports.encode = function encode (opts) {\n const buf = b4a.alloc(512)\n let name = opts.name\n let prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n if (b4a.byteLength(name) !== name.length) return null // utf-8\n\n while (b4a.byteLength(name) > 100) {\n const i = name.indexOf('/')\n if (i === -1) return null\n prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null\n if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null\n\n b4a.write(buf, name)\n b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100)\n b4a.write(buf, encodeOct(opts.uid, 6), 108)\n b4a.write(buf, encodeOct(opts.gid, 6), 116)\n encodeSize(opts.size, buf, 124)\n b4a.write(buf, encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname) b4a.write(buf, opts.linkname, 157)\n\n b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET)\n b4a.copy(USTAR_VER, buf, VERSION_OFFSET)\n if (opts.uname) b4a.write(buf, opts.uname, 265)\n if (opts.gname) b4a.write(buf, opts.gname, 297)\n b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329)\n b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337)\n\n if (prefix) b4a.write(buf, prefix, 345)\n\n b4a.write(buf, encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n\nexports.decode = function decode (buf, filenameEncoding, allowUnknownFormat) {\n let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n let name = decodeStr(buf, 0, 100, filenameEncoding)\n const mode = decodeOct(buf, 100, 8)\n const uid = decodeOct(buf, 108, 8)\n const gid = decodeOct(buf, 116, 8)\n const size = decodeOct(buf, 124, 12)\n const mtime = decodeOct(buf, 136, 12)\n const type = toType(typeflag)\n const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n const uname = decodeStr(buf, 265, 32)\n const gname = decodeStr(buf, 297, 32)\n const devmajor = decodeOct(buf, 329, 8)\n const devminor = decodeOct(buf, 337, 8)\n\n const c = cksum(buf)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) return null\n\n // valid checksum\n if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n if (isUSTAR(buf)) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n } else if (isGNU(buf)) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n if (!allowUnknownFormat) {\n throw new Error('Invalid tar header: unknown format.')\n }\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * mtime),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor,\n pax: null\n }\n}\n\nfunction isUSTAR (buf) {\n return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6))\n}\n\nfunction isGNU (buf) {\n return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) &&\n b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2))\n}\n\nfunction clamp (index, len, defaultValue) {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nfunction toType (flag) {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n }\n\n return null\n}\n\nfunction toTypeflag (flag) {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n }\n\n return 0\n}\n\nfunction indexOf (block, num, offset, end) {\n for (; offset < end; offset++) {\n if (block[offset] === num) return offset\n }\n return end\n}\n\nfunction cksum (block) {\n let sum = 8 * 32\n for (let i = 0; i < 148; i++) sum += block[i]\n for (let j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nfunction encodeOct (val, n) {\n val = val.toString(8)\n if (val.length > n) return SEVENS.slice(0, n) + ' '\n return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\nfunction encodeSizeBin (num, buf, off) {\n buf[off] = 0x80\n for (let i = 11; i > 0; i--) {\n buf[off + i] = num & 0xff\n num = Math.floor(num / 0x100)\n }\n}\n\nfunction encodeSize (num, buf, off) {\n if (num.toString(8).length > 11) {\n encodeSizeBin(num, buf, off)\n } else {\n b4a.write(buf, encodeOct(num, 11), off)\n }\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n let positive\n if (buf[0] === 0x80) positive = true\n else if (buf[0] === 0xFF) positive = false\n else return null\n\n // build up a base-256 tuple from the least sig to the highest\n const tuple = []\n let i\n for (i = buf.length - 1; i > 0; i--) {\n const byte = buf[i]\n if (positive) tuple.push(byte)\n else tuple.push(0xFF - byte)\n }\n\n let sum = 0\n const l = tuple.length\n for (i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nfunction decodeOct (val, offset, length) {\n val = val.subarray(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if (val[offset] & 0x80) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val[offset] === 32) offset++\n const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n while (offset < end && val[offset] === 0) offset++\n if (end === offset) return 0\n return parseInt(b4a.toString(val.subarray(offset, end)), 8)\n }\n}\n\nfunction decodeStr (val, offset, length, encoding) {\n return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding)\n}\n\nfunction addLength (str) {\n const len = b4a.byteLength(str)\n let digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n if (len + digits >= Math.pow(10, digits)) digits++\n\n return (len + digits) + str\n}\n","exports.extract = require('./extract')\nexports.pack = require('./pack')\n","const { Readable, Writable, getStreamError } = require('streamx')\nconst b4a = require('b4a')\n\nconst constants = require('./constants')\nconst headers = require('./headers')\n\nconst DMODE = 0o755\nconst FMODE = 0o644\n\nconst END_OF_TAR = b4a.alloc(1024)\n\nclass Sink extends Writable {\n constructor (pack, header, callback) {\n super({ mapWritable, eagerOpen: true })\n\n this.written = 0\n this.header = header\n\n this._callback = callback\n this._linkname = null\n this._isLinkname = header.type === 'symlink' && !header.linkname\n this._isVoid = header.type !== 'file' && header.type !== 'contiguous-file'\n this._finished = false\n this._pack = pack\n this._openCallback = null\n\n if (this._pack._stream === null) this._pack._stream = this\n else this._pack._pending.push(this)\n }\n\n _open (cb) {\n this._openCallback = cb\n if (this._pack._stream === this) this._continueOpen()\n }\n\n _continuePack (err) {\n if (this._callback === null) return\n\n const callback = this._callback\n this._callback = null\n\n callback(err)\n }\n\n _continueOpen () {\n if (this._pack._stream === null) this._pack._stream = this\n\n const cb = this._openCallback\n this._openCallback = null\n if (cb === null) return\n\n if (this._pack.destroying) return cb(new Error('pack stream destroyed'))\n if (this._pack._finalized) return cb(new Error('pack stream is already finalized'))\n\n this._pack._stream = this\n\n if (!this._isLinkname) {\n this._pack._encode(this.header)\n }\n\n if (this._isVoid) {\n this._finish()\n this._continuePack(null)\n }\n\n cb(null)\n }\n\n _write (data, cb) {\n if (this._isLinkname) {\n this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data\n return cb(null)\n }\n\n if (this._isVoid) {\n if (data.byteLength > 0) {\n return cb(new Error('No body allowed for this entry'))\n }\n return cb()\n }\n\n this.written += data.byteLength\n if (this._pack.push(data)) return cb()\n this._pack._drain = cb\n }\n\n _finish () {\n if (this._finished) return\n this._finished = true\n\n if (this._isLinkname) {\n this.header.linkname = this._linkname ? b4a.toString(this._linkname, 'utf-8') : ''\n this._pack._encode(this.header)\n }\n\n overflow(this._pack, this.header.size)\n\n this._pack._done(this)\n }\n\n _final (cb) {\n if (this.written !== this.header.size) { // corrupting tar\n return cb(new Error('Size mismatch'))\n }\n\n this._finish()\n cb(null)\n }\n\n _getError () {\n return getStreamError(this) || new Error('tar entry destroyed')\n }\n\n _predestroy () {\n this._pack.destroy(this._getError())\n }\n\n _destroy (cb) {\n this._pack._done(this)\n\n this._continuePack(this._finished ? null : this._getError())\n\n cb()\n }\n}\n\nclass Pack extends Readable {\n constructor (opts) {\n super(opts)\n this._drain = noop\n this._finalized = false\n this._finalizing = false\n this._pending = []\n this._stream = null\n }\n\n entry (header, buffer, callback) {\n if (this._finalized || this.destroying) throw new Error('already finalized or destroyed')\n\n if (typeof buffer === 'function') {\n callback = buffer\n buffer = null\n }\n\n if (!callback) callback = noop\n\n if (!header.size || header.type === 'symlink') header.size = 0\n if (!header.type) header.type = modeToType(header.mode)\n if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n if (!header.uid) header.uid = 0\n if (!header.gid) header.gid = 0\n if (!header.mtime) header.mtime = new Date()\n\n if (typeof buffer === 'string') buffer = b4a.from(buffer)\n\n const sink = new Sink(this, header, callback)\n\n if (b4a.isBuffer(buffer)) {\n header.size = buffer.byteLength\n sink.write(buffer)\n sink.end()\n return sink\n }\n\n if (sink._isVoid) {\n return sink\n }\n\n return sink\n }\n\n finalize () {\n if (this._stream || this._pending.length > 0) {\n this._finalizing = true\n return\n }\n\n if (this._finalized) return\n this._finalized = true\n\n this.push(END_OF_TAR)\n this.push(null)\n }\n\n _done (stream) {\n if (stream !== this._stream) return\n\n this._stream = null\n\n if (this._finalizing) this.finalize()\n if (this._pending.length) this._pending.shift()._continueOpen()\n }\n\n _encode (header) {\n if (!header.pax) {\n const buf = headers.encode(header)\n if (buf) {\n this.push(buf)\n return\n }\n }\n this._encodePax(header)\n }\n\n _encodePax (header) {\n const paxHeader = headers.encodePax({\n name: header.name,\n linkname: header.linkname,\n pax: header.pax\n })\n\n const newHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.byteLength,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname && 'PaxHeader',\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n this.push(headers.encode(newHeader))\n this.push(paxHeader)\n overflow(this, paxHeader.byteLength)\n\n newHeader.size = header.size\n newHeader.type = header.type\n this.push(headers.encode(newHeader))\n }\n\n _doDrain () {\n const drain = this._drain\n this._drain = noop\n drain()\n }\n\n _predestroy () {\n const err = getStreamError(this)\n\n if (this._stream) this._stream.destroy(err)\n\n while (this._pending.length) {\n const stream = this._pending.shift()\n stream.destroy(err)\n stream._continueOpen()\n }\n\n this._doDrain()\n }\n\n _read (cb) {\n this._doDrain()\n cb()\n }\n}\n\nmodule.exports = function pack (opts) {\n return new Pack(opts)\n}\n\nfunction modeToType (mode) {\n switch (mode & constants.S_IFMT) {\n case constants.S_IFBLK: return 'block-device'\n case constants.S_IFCHR: return 'character-device'\n case constants.S_IFDIR: return 'directory'\n case constants.S_IFIFO: return 'fifo'\n case constants.S_IFLNK: return 'symlink'\n }\n\n return 'file'\n}\n\nfunction noop () {}\n\nfunction overflow (self, size) {\n size &= 511\n if (size) self.push(END_OF_TAR.subarray(0, 512 - size))\n}\n\nfunction mapWritable (buf) {\n return b4a.isBuffer(buf) ? buf : b4a.from(buf)\n}\n","module.exports = require('./lib/tunnel');\n","'use strict';\n\nvar net = require('net');\nvar tls = require('tls');\nvar http = require('http');\nvar https = require('https');\nvar events = require('events');\nvar assert = require('assert');\nvar util = require('util');\n\n\nexports.httpOverHttp = httpOverHttp;\nexports.httpsOverHttp = httpsOverHttp;\nexports.httpOverHttps = httpOverHttps;\nexports.httpsOverHttps = httpsOverHttps;\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n return agent;\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n return agent;\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this;\n self.options = options || {};\n self.proxyOptions = self.options.proxy || {};\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;\n self.requests = [];\n self.sockets = [];\n\n self.on('free', function onFree(socket, host, port, localAddress) {\n var options = toOptions(host, port, localAddress);\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i];\n if (pending.host === options.host && pending.port === options.port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1);\n pending.request.onSocket(socket);\n return;\n }\n }\n socket.destroy();\n self.removeSocket(socket);\n });\n}\nutil.inherits(TunnelingAgent, events.EventEmitter);\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {\n var self = this;\n var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push(options);\n return;\n }\n\n // If we are under maxSockets create a new one.\n self.createSocket(options, function(socket) {\n socket.on('free', onFree);\n socket.on('close', onCloseOrRemove);\n socket.on('agentRemove', onCloseOrRemove);\n req.onSocket(socket);\n\n function onFree() {\n self.emit('free', socket, options);\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket);\n socket.removeListener('free', onFree);\n socket.removeListener('close', onCloseOrRemove);\n socket.removeListener('agentRemove', onCloseOrRemove);\n }\n });\n};\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this;\n var placeholder = {};\n self.sockets.push(placeholder);\n\n var connectOptions = mergeOptions({}, self.proxyOptions, {\n method: 'CONNECT',\n path: options.host + ':' + options.port,\n agent: false,\n headers: {\n host: options.host + ':' + options.port\n }\n });\n if (options.localAddress) {\n connectOptions.localAddress = options.localAddress;\n }\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {};\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n new Buffer(connectOptions.proxyAuth).toString('base64');\n }\n\n debug('making CONNECT request');\n var connectReq = self.request(connectOptions);\n connectReq.useChunkedEncodingByDefault = false; // for v0.6\n connectReq.once('response', onResponse); // for v0.6\n connectReq.once('upgrade', onUpgrade); // for v0.6\n connectReq.once('connect', onConnect); // for v0.7 or later\n connectReq.once('error', onError);\n connectReq.end();\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true;\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head);\n });\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners();\n socket.removeAllListeners();\n\n if (res.statusCode !== 200) {\n debug('tunneling socket could not be established, statusCode=%d',\n res.statusCode);\n socket.destroy();\n var error = new Error('tunneling socket could not be established, ' +\n 'statusCode=' + res.statusCode);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n if (head.length > 0) {\n debug('got illegal response body from proxy');\n socket.destroy();\n var error = new Error('got illegal response body from proxy');\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n debug('tunneling connection has established');\n self.sockets[self.sockets.indexOf(placeholder)] = socket;\n return cb(socket);\n }\n\n function onError(cause) {\n connectReq.removeAllListeners();\n\n debug('tunneling socket could not be established, cause=%s\\n',\n cause.message, cause.stack);\n var error = new Error('tunneling socket could not be established, ' +\n 'cause=' + cause.message);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n }\n};\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) {\n return;\n }\n this.sockets.splice(pos, 1);\n\n var pending = this.requests.shift();\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createSocket(pending, function(socket) {\n pending.request.onSocket(socket);\n });\n }\n};\n\nfunction createSecureSocket(options, cb) {\n var self = this;\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n var hostHeader = options.request.getHeader('host');\n var tlsOptions = mergeOptions({}, self.options, {\n socket: socket,\n servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host\n });\n\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, tlsOptions);\n self.sockets[self.sockets.indexOf(socket)] = secureSocket;\n cb(secureSocket);\n });\n}\n\n\nfunction toOptions(host, port, localAddress) {\n if (typeof host === 'string') { // since v0.10\n return {\n host: host,\n port: port,\n localAddress: localAddress\n };\n }\n return host; // for v0.11 or later\n}\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i];\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides);\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j];\n if (overrides[k] !== undefined) {\n target[k] = overrides[k];\n }\n }\n }\n }\n return target;\n}\n\n\nvar debug;\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments);\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0];\n } else {\n args.unshift('TUNNEL:');\n }\n console.error.apply(console, args);\n }\n} else {\n debug = function() {};\n}\nexports.debug = debug; // for test\n","(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _0 = new Uint8Array(16);\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_16(x, xi, y, yi) {\n return vn(x,xi,y,yi,16);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction core_salsa20(o, p, k, c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n x0 = x0 + j0 | 0;\n x1 = x1 + j1 | 0;\n x2 = x2 + j2 | 0;\n x3 = x3 + j3 | 0;\n x4 = x4 + j4 | 0;\n x5 = x5 + j5 | 0;\n x6 = x6 + j6 | 0;\n x7 = x7 + j7 | 0;\n x8 = x8 + j8 | 0;\n x9 = x9 + j9 | 0;\n x10 = x10 + j10 | 0;\n x11 = x11 + j11 | 0;\n x12 = x12 + j12 | 0;\n x13 = x13 + j13 | 0;\n x14 = x14 + j14 | 0;\n x15 = x15 + j15 | 0;\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x1 >>> 0 & 0xff;\n o[ 5] = x1 >>> 8 & 0xff;\n o[ 6] = x1 >>> 16 & 0xff;\n o[ 7] = x1 >>> 24 & 0xff;\n\n o[ 8] = x2 >>> 0 & 0xff;\n o[ 9] = x2 >>> 8 & 0xff;\n o[10] = x2 >>> 16 & 0xff;\n o[11] = x2 >>> 24 & 0xff;\n\n o[12] = x3 >>> 0 & 0xff;\n o[13] = x3 >>> 8 & 0xff;\n o[14] = x3 >>> 16 & 0xff;\n o[15] = x3 >>> 24 & 0xff;\n\n o[16] = x4 >>> 0 & 0xff;\n o[17] = x4 >>> 8 & 0xff;\n o[18] = x4 >>> 16 & 0xff;\n o[19] = x4 >>> 24 & 0xff;\n\n o[20] = x5 >>> 0 & 0xff;\n o[21] = x5 >>> 8 & 0xff;\n o[22] = x5 >>> 16 & 0xff;\n o[23] = x5 >>> 24 & 0xff;\n\n o[24] = x6 >>> 0 & 0xff;\n o[25] = x6 >>> 8 & 0xff;\n o[26] = x6 >>> 16 & 0xff;\n o[27] = x6 >>> 24 & 0xff;\n\n o[28] = x7 >>> 0 & 0xff;\n o[29] = x7 >>> 8 & 0xff;\n o[30] = x7 >>> 16 & 0xff;\n o[31] = x7 >>> 24 & 0xff;\n\n o[32] = x8 >>> 0 & 0xff;\n o[33] = x8 >>> 8 & 0xff;\n o[34] = x8 >>> 16 & 0xff;\n o[35] = x8 >>> 24 & 0xff;\n\n o[36] = x9 >>> 0 & 0xff;\n o[37] = x9 >>> 8 & 0xff;\n o[38] = x9 >>> 16 & 0xff;\n o[39] = x9 >>> 24 & 0xff;\n\n o[40] = x10 >>> 0 & 0xff;\n o[41] = x10 >>> 8 & 0xff;\n o[42] = x10 >>> 16 & 0xff;\n o[43] = x10 >>> 24 & 0xff;\n\n o[44] = x11 >>> 0 & 0xff;\n o[45] = x11 >>> 8 & 0xff;\n o[46] = x11 >>> 16 & 0xff;\n o[47] = x11 >>> 24 & 0xff;\n\n o[48] = x12 >>> 0 & 0xff;\n o[49] = x12 >>> 8 & 0xff;\n o[50] = x12 >>> 16 & 0xff;\n o[51] = x12 >>> 24 & 0xff;\n\n o[52] = x13 >>> 0 & 0xff;\n o[53] = x13 >>> 8 & 0xff;\n o[54] = x13 >>> 16 & 0xff;\n o[55] = x13 >>> 24 & 0xff;\n\n o[56] = x14 >>> 0 & 0xff;\n o[57] = x14 >>> 8 & 0xff;\n o[58] = x14 >>> 16 & 0xff;\n o[59] = x14 >>> 24 & 0xff;\n\n o[60] = x15 >>> 0 & 0xff;\n o[61] = x15 >>> 8 & 0xff;\n o[62] = x15 >>> 16 & 0xff;\n o[63] = x15 >>> 24 & 0xff;\n}\n\nfunction core_hsalsa20(o,p,k,c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x5 >>> 0 & 0xff;\n o[ 5] = x5 >>> 8 & 0xff;\n o[ 6] = x5 >>> 16 & 0xff;\n o[ 7] = x5 >>> 24 & 0xff;\n\n o[ 8] = x10 >>> 0 & 0xff;\n o[ 9] = x10 >>> 8 & 0xff;\n o[10] = x10 >>> 16 & 0xff;\n o[11] = x10 >>> 24 & 0xff;\n\n o[12] = x15 >>> 0 & 0xff;\n o[13] = x15 >>> 8 & 0xff;\n o[14] = x15 >>> 16 & 0xff;\n o[15] = x15 >>> 24 & 0xff;\n\n o[16] = x6 >>> 0 & 0xff;\n o[17] = x6 >>> 8 & 0xff;\n o[18] = x6 >>> 16 & 0xff;\n o[19] = x6 >>> 24 & 0xff;\n\n o[20] = x7 >>> 0 & 0xff;\n o[21] = x7 >>> 8 & 0xff;\n o[22] = x7 >>> 16 & 0xff;\n o[23] = x7 >>> 24 & 0xff;\n\n o[24] = x8 >>> 0 & 0xff;\n o[25] = x8 >>> 8 & 0xff;\n o[26] = x8 >>> 16 & 0xff;\n o[27] = x8 >>> 24 & 0xff;\n\n o[28] = x9 >>> 0 & 0xff;\n o[29] = x9 >>> 8 & 0xff;\n o[30] = x9 >>> 16 & 0xff;\n o[31] = x9 >>> 24 & 0xff;\n}\n\nfunction crypto_core_salsa20(out,inp,k,c) {\n core_salsa20(out,inp,k,c);\n}\n\nfunction crypto_core_hsalsa20(out,inp,k,c) {\n core_hsalsa20(out,inp,k,c);\n}\n\nvar sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);\n // \"expand 32-byte k\"\n\nfunction crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n mpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n }\n return 0;\n}\n\nfunction crypto_stream_salsa20(c,cpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = x[i];\n }\n return 0;\n}\n\nfunction crypto_stream(c,cpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20(c,cpos,d,sn,s);\n}\n\nfunction crypto_stream_xor(c,cpos,m,mpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);\n}\n\n/*\n* Port of Andrew Moon's Poly1305-donna-16. Public domain.\n* https://github.com/floodyberry/poly1305-donna\n*/\n\nvar poly1305 = function(key) {\n this.buffer = new Uint8Array(16);\n this.r = new Uint16Array(10);\n this.h = new Uint16Array(10);\n this.pad = new Uint16Array(8);\n this.leftover = 0;\n this.fin = 0;\n\n var t0, t1, t2, t3, t4, t5, t6, t7;\n\n t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;\n t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = ((t4 >>> 1)) & 0x1ffe;\n t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = ((t7 >>> 5)) & 0x007f;\n\n this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;\n this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;\n this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;\n this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;\n this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;\n this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;\n this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;\n this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;\n};\n\npoly1305.prototype.blocks = function(m, mpos, bytes) {\n var hibit = this.fin ? 0 : (1 << 11);\n var t0, t1, t2, t3, t4, t5, t6, t7, c;\n var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;\n\n var h0 = this.h[0],\n h1 = this.h[1],\n h2 = this.h[2],\n h3 = this.h[3],\n h4 = this.h[4],\n h5 = this.h[5],\n h6 = this.h[6],\n h7 = this.h[7],\n h8 = this.h[8],\n h9 = this.h[9];\n\n var r0 = this.r[0],\n r1 = this.r[1],\n r2 = this.r[2],\n r3 = this.r[3],\n r4 = this.r[4],\n r5 = this.r[5],\n r6 = this.r[6],\n r7 = this.r[7],\n r8 = this.r[8],\n r9 = this.r[9];\n\n while (bytes >= 16) {\n t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;\n t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n c = 0;\n\n d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this.h[0] = h0;\n this.h[1] = h1;\n this.h[2] = h2;\n this.h[3] = h3;\n this.h[4] = h4;\n this.h[5] = h5;\n this.h[6] = h6;\n this.h[7] = h7;\n this.h[8] = h8;\n this.h[9] = h9;\n};\n\npoly1305.prototype.finish = function(mac, macpos) {\n var g = new Uint16Array(10);\n var c, mask, f, i;\n\n if (this.leftover) {\n i = this.leftover;\n this.buffer[i++] = 1;\n for (; i < 16; i++) this.buffer[i] = 0;\n this.fin = 1;\n this.blocks(this.buffer, 0, 16);\n }\n\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this.h[i] += c;\n c = this.h[i] >>> 13;\n this.h[i] &= 0x1fff;\n }\n this.h[0] += (c * 5);\n c = this.h[0] >>> 13;\n this.h[0] &= 0x1fff;\n this.h[1] += c;\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n this.h[2] += c;\n\n g[0] = this.h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this.h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];\n\n this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;\n this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;\n this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;\n this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;\n this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;\n this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;\n this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;\n this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;\n\n f = this.h[0] + this.pad[0];\n this.h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;\n this.h[i] = f & 0xffff;\n }\n\n mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;\n mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;\n mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;\n mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;\n mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;\n mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;\n mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;\n mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;\n mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;\n mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;\n mac[macpos+10] = (this.h[5] >>> 0) & 0xff;\n mac[macpos+11] = (this.h[5] >>> 8) & 0xff;\n mac[macpos+12] = (this.h[6] >>> 0) & 0xff;\n mac[macpos+13] = (this.h[6] >>> 8) & 0xff;\n mac[macpos+14] = (this.h[7] >>> 0) & 0xff;\n mac[macpos+15] = (this.h[7] >>> 8) & 0xff;\n};\n\npoly1305.prototype.update = function(m, mpos, bytes) {\n var i, want;\n\n if (this.leftover) {\n want = (16 - this.leftover);\n if (want > bytes)\n want = bytes;\n for (i = 0; i < want; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n bytes -= want;\n mpos += want;\n this.leftover += want;\n if (this.leftover < 16)\n return;\n this.blocks(this.buffer, 0, 16);\n this.leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this.blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (i = 0; i < bytes; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n this.leftover += bytes;\n }\n};\n\nfunction crypto_onetimeauth(out, outpos, m, mpos, n, k) {\n var s = new poly1305(k);\n s.update(m, mpos, n);\n s.finish(out, outpos);\n return 0;\n}\n\nfunction crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {\n var x = new Uint8Array(16);\n crypto_onetimeauth(x,0,m,mpos,n,k);\n return crypto_verify_16(h,hpos,x,0);\n}\n\nfunction crypto_secretbox(c,m,d,n,k) {\n var i;\n if (d < 32) return -1;\n crypto_stream_xor(c,0,m,0,d,n,k);\n crypto_onetimeauth(c, 16, c, 32, d - 32, c);\n for (i = 0; i < 16; i++) c[i] = 0;\n return 0;\n}\n\nfunction crypto_secretbox_open(m,c,d,n,k) {\n var i;\n var x = new Uint8Array(32);\n if (d < 32) return -1;\n crypto_stream(x,0,32,n,k);\n if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;\n crypto_stream_xor(m,0,c,0,d,n,k);\n for (i = 0; i < 32; i++) m[i] = 0;\n return 0;\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction crypto_box_beforenm(k, y, x) {\n var s = new Uint8Array(32);\n crypto_scalarmult(s, x, y);\n return crypto_core_hsalsa20(k, _0, s, sigma);\n}\n\nvar crypto_box_afternm = crypto_secretbox;\nvar crypto_box_open_afternm = crypto_secretbox_open;\n\nfunction crypto_box(c, m, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_afternm(c, m, d, n, k);\n}\n\nfunction crypto_box_open(m, c, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_open_afternm(m, c, d, n, k);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n mlen = n;\n return mlen;\n}\n\nvar crypto_secretbox_KEYBYTES = 32,\n crypto_secretbox_NONCEBYTES = 24,\n crypto_secretbox_ZEROBYTES = 32,\n crypto_secretbox_BOXZEROBYTES = 16,\n crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_box_BEFORENMBYTES = 32,\n crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,\n crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,\n crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32,\n crypto_hash_BYTES = 64;\n\nnacl.lowlevel = {\n crypto_core_hsalsa20: crypto_core_hsalsa20,\n crypto_stream_xor: crypto_stream_xor,\n crypto_stream: crypto_stream,\n crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,\n crypto_stream_salsa20: crypto_stream_salsa20,\n crypto_onetimeauth: crypto_onetimeauth,\n crypto_onetimeauth_verify: crypto_onetimeauth_verify,\n crypto_verify_16: crypto_verify_16,\n crypto_verify_32: crypto_verify_32,\n crypto_secretbox: crypto_secretbox,\n crypto_secretbox_open: crypto_secretbox_open,\n crypto_scalarmult: crypto_scalarmult,\n crypto_scalarmult_base: crypto_scalarmult_base,\n crypto_box_beforenm: crypto_box_beforenm,\n crypto_box_afternm: crypto_box_afternm,\n crypto_box: crypto_box,\n crypto_box_open: crypto_box_open,\n crypto_box_keypair: crypto_box_keypair,\n crypto_hash: crypto_hash,\n crypto_sign: crypto_sign,\n crypto_sign_keypair: crypto_sign_keypair,\n crypto_sign_open: crypto_sign_open,\n\n crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,\n crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,\n crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,\n crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,\n crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,\n crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,\n crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,\n crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,\n crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,\n crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,\n crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,\n crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,\n crypto_sign_BYTES: crypto_sign_BYTES,\n crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,\n crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,\n crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,\n crypto_hash_BYTES: crypto_hash_BYTES\n};\n\n/* High-level API */\n\nfunction checkLengths(k, n) {\n if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');\n if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');\n}\n\nfunction checkBoxLengths(pk, sk) {\n if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');\n if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');\n}\n\nfunction checkArrayTypes() {\n var t, i;\n for (i = 0; i < arguments.length; i++) {\n if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')\n throw new TypeError('unexpected type ' + t + ', use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\n// TODO: Completely remove this in v0.15.\nif (!nacl.util) {\n nacl.util = {};\n nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() {\n throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');\n };\n}\n\nnacl.randomBytes = function(n) {\n var b = new Uint8Array(n);\n randombytes(b, n);\n return b;\n};\n\nnacl.secretbox = function(msg, nonce, key) {\n checkArrayTypes(msg, nonce, key);\n checkLengths(key, nonce);\n var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);\n var c = new Uint8Array(m.length);\n for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];\n crypto_secretbox(c, m, m.length, nonce, key);\n return c.subarray(crypto_secretbox_BOXZEROBYTES);\n};\n\nnacl.secretbox.open = function(box, nonce, key) {\n checkArrayTypes(box, nonce, key);\n checkLengths(key, nonce);\n var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);\n var m = new Uint8Array(c.length);\n for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];\n if (c.length < 32) return false;\n if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false;\n return m.subarray(crypto_secretbox_ZEROBYTES);\n};\n\nnacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;\nnacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;\nnacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.scalarMult.base = function(n) {\n checkArrayTypes(n);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult_base(q, n);\n return q;\n};\n\nnacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;\nnacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;\n\nnacl.box = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox(msg, nonce, k);\n};\n\nnacl.box.before = function(publicKey, secretKey) {\n checkArrayTypes(publicKey, secretKey);\n checkBoxLengths(publicKey, secretKey);\n var k = new Uint8Array(crypto_box_BEFORENMBYTES);\n crypto_box_beforenm(k, publicKey, secretKey);\n return k;\n};\n\nnacl.box.after = nacl.secretbox;\n\nnacl.box.open = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox.open(msg, nonce, k);\n};\n\nnacl.box.open.after = nacl.secretbox.open;\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;\nnacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;\nnacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;\nnacl.box.nonceLength = crypto_box_NONCEBYTES;\nnacl.box.overheadLength = nacl.secretbox.overheadLength;\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.open = function(signedMsg, publicKey) {\n if (arguments.length !== 2)\n throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');\n checkArrayTypes(signedMsg, publicKey);\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var tmp = new Uint8Array(signedMsg.length);\n var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);\n if (mlen < 0) return null;\n var m = new Uint8Array(mlen);\n for (var i = 0; i < m.length; i++) m[i] = tmp[i];\n return m;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;\nnacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;\nnacl.sign.seedLength = crypto_sign_SEEDBYTES;\nnacl.sign.signatureLength = crypto_sign_BYTES;\n\nnacl.hash = function(msg) {\n checkArrayTypes(msg);\n var h = new Uint8Array(crypto_hash_BYTES);\n crypto_hash(h, msg, msg.length);\n return h;\n};\n\nnacl.hash.hashLength = crypto_hash_BYTES;\n\nnacl.verify = function(x, y) {\n checkArrayTypes(x, y);\n // Zero length arguments are considered not equal.\n if (x.length === 0 || y.length === 0) return false;\n if (x.length !== y.length) return false;\n return (vn(x, 0, y, 0, x.length) === 0) ? true : false;\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","'use strict'\n\nconst Client = require('./lib/client')\nconst Dispatcher = require('./lib/dispatcher')\nconst errors = require('./lib/core/errors')\nconst Pool = require('./lib/pool')\nconst BalancedPool = require('./lib/balanced-pool')\nconst Agent = require('./lib/agent')\nconst util = require('./lib/core/util')\nconst { InvalidArgumentError } = errors\nconst api = require('./lib/api')\nconst buildConnector = require('./lib/core/connect')\nconst MockClient = require('./lib/mock/mock-client')\nconst MockAgent = require('./lib/mock/mock-agent')\nconst MockPool = require('./lib/mock/mock-pool')\nconst mockErrors = require('./lib/mock/mock-errors')\nconst ProxyAgent = require('./lib/proxy-agent')\nconst RetryHandler = require('./lib/handler/RetryHandler')\nconst { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')\nconst DecoratorHandler = require('./lib/handler/DecoratorHandler')\nconst RedirectHandler = require('./lib/handler/RedirectHandler')\nconst createRedirectInterceptor = require('./lib/interceptor/redirectInterceptor')\n\nlet hasCrypto\ntry {\n require('crypto')\n hasCrypto = true\n} catch {\n hasCrypto = false\n}\n\nObject.assign(Dispatcher.prototype, api)\n\nmodule.exports.Dispatcher = Dispatcher\nmodule.exports.Client = Client\nmodule.exports.Pool = Pool\nmodule.exports.BalancedPool = BalancedPool\nmodule.exports.Agent = Agent\nmodule.exports.ProxyAgent = ProxyAgent\nmodule.exports.RetryHandler = RetryHandler\n\nmodule.exports.DecoratorHandler = DecoratorHandler\nmodule.exports.RedirectHandler = RedirectHandler\nmodule.exports.createRedirectInterceptor = createRedirectInterceptor\n\nmodule.exports.buildConnector = buildConnector\nmodule.exports.errors = errors\n\nfunction makeDispatcher (fn) {\n return (url, opts, handler) => {\n if (typeof opts === 'function') {\n handler = opts\n opts = null\n }\n\n if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {\n throw new InvalidArgumentError('invalid url')\n }\n\n if (opts != null && typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (opts && opts.path != null) {\n if (typeof opts.path !== 'string') {\n throw new InvalidArgumentError('invalid opts.path')\n }\n\n let path = opts.path\n if (!opts.path.startsWith('/')) {\n path = `/${path}`\n }\n\n url = new URL(util.parseOrigin(url).origin + path)\n } else {\n if (!opts) {\n opts = typeof url === 'object' ? url : {}\n }\n\n url = util.parseURL(url)\n }\n\n const { agent, dispatcher = getGlobalDispatcher() } = opts\n\n if (agent) {\n throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')\n }\n\n return fn.call(dispatcher, {\n ...opts,\n origin: url.origin,\n path: url.search ? `${url.pathname}${url.search}` : url.pathname,\n method: opts.method || (opts.body ? 'PUT' : 'GET')\n }, handler)\n }\n}\n\nmodule.exports.setGlobalDispatcher = setGlobalDispatcher\nmodule.exports.getGlobalDispatcher = getGlobalDispatcher\n\nif (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {\n let fetchImpl = null\n module.exports.fetch = async function fetch (resource) {\n if (!fetchImpl) {\n fetchImpl = require('./lib/fetch').fetch\n }\n\n try {\n return await fetchImpl(...arguments)\n } catch (err) {\n if (typeof err === 'object') {\n Error.captureStackTrace(err, this)\n }\n\n throw err\n }\n }\n module.exports.Headers = require('./lib/fetch/headers').Headers\n module.exports.Response = require('./lib/fetch/response').Response\n module.exports.Request = require('./lib/fetch/request').Request\n module.exports.FormData = require('./lib/fetch/formdata').FormData\n module.exports.File = require('./lib/fetch/file').File\n module.exports.FileReader = require('./lib/fileapi/filereader').FileReader\n\n const { setGlobalOrigin, getGlobalOrigin } = require('./lib/fetch/global')\n\n module.exports.setGlobalOrigin = setGlobalOrigin\n module.exports.getGlobalOrigin = getGlobalOrigin\n\n const { CacheStorage } = require('./lib/cache/cachestorage')\n const { kConstruct } = require('./lib/cache/symbols')\n\n // Cache & CacheStorage are tightly coupled with fetch. Even if it may run\n // in an older version of Node, it doesn't have any use without fetch.\n module.exports.caches = new CacheStorage(kConstruct)\n}\n\nif (util.nodeMajor >= 16) {\n const { deleteCookie, getCookies, getSetCookies, setCookie } = require('./lib/cookies')\n\n module.exports.deleteCookie = deleteCookie\n module.exports.getCookies = getCookies\n module.exports.getSetCookies = getSetCookies\n module.exports.setCookie = setCookie\n\n const { parseMIMEType, serializeAMimeType } = require('./lib/fetch/dataURL')\n\n module.exports.parseMIMEType = parseMIMEType\n module.exports.serializeAMimeType = serializeAMimeType\n}\n\nif (util.nodeMajor >= 18 && hasCrypto) {\n const { WebSocket } = require('./lib/websocket/websocket')\n\n module.exports.WebSocket = WebSocket\n}\n\nmodule.exports.request = makeDispatcher(api.request)\nmodule.exports.stream = makeDispatcher(api.stream)\nmodule.exports.pipeline = makeDispatcher(api.pipeline)\nmodule.exports.connect = makeDispatcher(api.connect)\nmodule.exports.upgrade = makeDispatcher(api.upgrade)\n\nmodule.exports.MockClient = MockClient\nmodule.exports.MockPool = MockPool\nmodule.exports.MockAgent = MockAgent\nmodule.exports.mockErrors = mockErrors\n","'use strict'\n\nconst { InvalidArgumentError } = require('./core/errors')\nconst { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('./core/symbols')\nconst DispatcherBase = require('./dispatcher-base')\nconst Pool = require('./pool')\nconst Client = require('./client')\nconst util = require('./core/util')\nconst createRedirectInterceptor = require('./interceptor/redirectInterceptor')\nconst { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')()\n\nconst kOnConnect = Symbol('onConnect')\nconst kOnDisconnect = Symbol('onDisconnect')\nconst kOnConnectionError = Symbol('onConnectionError')\nconst kMaxRedirections = Symbol('maxRedirections')\nconst kOnDrain = Symbol('onDrain')\nconst kFactory = Symbol('factory')\nconst kFinalizer = Symbol('finalizer')\nconst kOptions = Symbol('options')\n\nfunction defaultFactory (origin, opts) {\n return opts && opts.connections === 1\n ? new Client(origin, opts)\n : new Pool(origin, opts)\n}\n\nclass Agent extends DispatcherBase {\n constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {\n super()\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n if (connect && typeof connect !== 'function') {\n connect = { ...connect }\n }\n\n this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)\n ? options.interceptors.Agent\n : [createRedirectInterceptor({ maxRedirections })]\n\n this[kOptions] = { ...util.deepClone(options), connect }\n this[kOptions].interceptors = options.interceptors\n ? { ...options.interceptors }\n : undefined\n this[kMaxRedirections] = maxRedirections\n this[kFactory] = factory\n this[kClients] = new Map()\n this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {\n const ref = this[kClients].get(key)\n if (ref !== undefined && ref.deref() === undefined) {\n this[kClients].delete(key)\n }\n })\n\n const agent = this\n\n this[kOnDrain] = (origin, targets) => {\n agent.emit('drain', origin, [agent, ...targets])\n }\n\n this[kOnConnect] = (origin, targets) => {\n agent.emit('connect', origin, [agent, ...targets])\n }\n\n this[kOnDisconnect] = (origin, targets, err) => {\n agent.emit('disconnect', origin, [agent, ...targets], err)\n }\n\n this[kOnConnectionError] = (origin, targets, err) => {\n agent.emit('connectionError', origin, [agent, ...targets], err)\n }\n }\n\n get [kRunning] () {\n let ret = 0\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore next: gc is undeterministic */\n if (client) {\n ret += client[kRunning]\n }\n }\n return ret\n }\n\n [kDispatch] (opts, handler) {\n let key\n if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {\n key = String(opts.origin)\n } else {\n throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')\n }\n\n const ref = this[kClients].get(key)\n\n let dispatcher = ref ? ref.deref() : null\n if (!dispatcher) {\n dispatcher = this[kFactory](opts.origin, this[kOptions])\n .on('drain', this[kOnDrain])\n .on('connect', this[kOnConnect])\n .on('disconnect', this[kOnDisconnect])\n .on('connectionError', this[kOnConnectionError])\n\n this[kClients].set(key, new WeakRef(dispatcher))\n this[kFinalizer].register(dispatcher, key)\n }\n\n return dispatcher.dispatch(opts, handler)\n }\n\n async [kClose] () {\n const closePromises = []\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore else: gc is undeterministic */\n if (client) {\n closePromises.push(client.close())\n }\n }\n\n await Promise.all(closePromises)\n }\n\n async [kDestroy] (err) {\n const destroyPromises = []\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore else: gc is undeterministic */\n if (client) {\n destroyPromises.push(client.destroy(err))\n }\n }\n\n await Promise.all(destroyPromises)\n }\n}\n\nmodule.exports = Agent\n","const { addAbortListener } = require('../core/util')\nconst { RequestAbortedError } = require('../core/errors')\n\nconst kListener = Symbol('kListener')\nconst kSignal = Symbol('kSignal')\n\nfunction abort (self) {\n if (self.abort) {\n self.abort()\n } else {\n self.onError(new RequestAbortedError())\n }\n}\n\nfunction addSignal (self, signal) {\n self[kSignal] = null\n self[kListener] = null\n\n if (!signal) {\n return\n }\n\n if (signal.aborted) {\n abort(self)\n return\n }\n\n self[kSignal] = signal\n self[kListener] = () => {\n abort(self)\n }\n\n addAbortListener(self[kSignal], self[kListener])\n}\n\nfunction removeSignal (self) {\n if (!self[kSignal]) {\n return\n }\n\n if ('removeEventListener' in self[kSignal]) {\n self[kSignal].removeEventListener('abort', self[kListener])\n } else {\n self[kSignal].removeListener('abort', self[kListener])\n }\n\n self[kSignal] = null\n self[kListener] = null\n}\n\nmodule.exports = {\n addSignal,\n removeSignal\n}\n","'use strict'\n\nconst { AsyncResource } = require('async_hooks')\nconst { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors')\nconst util = require('../core/util')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass ConnectHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n const { signal, opaque, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n super('UNDICI_CONNECT')\n\n this.opaque = opaque || null\n this.responseHeaders = responseHeaders || null\n this.callback = callback\n this.abort = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders () {\n throw new SocketError('bad connect', null)\n }\n\n onUpgrade (statusCode, rawHeaders, socket) {\n const { callback, opaque, context } = this\n\n removeSignal(this)\n\n this.callback = null\n\n let headers = rawHeaders\n // Indicates is an HTTP2Session\n if (headers != null) {\n headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n }\n\n this.runInAsyncScope(callback, null, null, {\n statusCode,\n headers,\n socket,\n opaque,\n context\n })\n }\n\n onError (err) {\n const { callback, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n }\n}\n\nfunction connect (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n connect.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n const connectHandler = new ConnectHandler(opts, callback)\n this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = connect\n","'use strict'\n\nconst {\n Readable,\n Duplex,\n PassThrough\n} = require('stream')\nconst {\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\nconst assert = require('assert')\n\nconst kResume = Symbol('resume')\n\nclass PipelineRequest extends Readable {\n constructor () {\n super({ autoDestroy: true })\n\n this[kResume] = null\n }\n\n _read () {\n const { [kResume]: resume } = this\n\n if (resume) {\n this[kResume] = null\n resume()\n }\n }\n\n _destroy (err, callback) {\n this._read()\n\n callback(err)\n }\n}\n\nclass PipelineResponse extends Readable {\n constructor (resume) {\n super({ autoDestroy: true })\n this[kResume] = resume\n }\n\n _read () {\n this[kResume]()\n }\n\n _destroy (err, callback) {\n if (!err && !this._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n callback(err)\n }\n}\n\nclass PipelineHandler extends AsyncResource {\n constructor (opts, handler) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof handler !== 'function') {\n throw new InvalidArgumentError('invalid handler')\n }\n\n const { signal, method, opaque, onInfo, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_PIPELINE')\n\n this.opaque = opaque || null\n this.responseHeaders = responseHeaders || null\n this.handler = handler\n this.abort = null\n this.context = null\n this.onInfo = onInfo || null\n\n this.req = new PipelineRequest().on('error', util.nop)\n\n this.ret = new Duplex({\n readableObjectMode: opts.objectMode,\n autoDestroy: true,\n read: () => {\n const { body } = this\n\n if (body && body.resume) {\n body.resume()\n }\n },\n write: (chunk, encoding, callback) => {\n const { req } = this\n\n if (req.push(chunk, encoding) || req._readableState.destroyed) {\n callback()\n } else {\n req[kResume] = callback\n }\n },\n destroy: (err, callback) => {\n const { body, req, res, ret, abort } = this\n\n if (!err && !ret._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n if (abort && err) {\n abort()\n }\n\n util.destroy(body, err)\n util.destroy(req, err)\n util.destroy(res, err)\n\n removeSignal(this)\n\n callback(err)\n }\n }).on('prefinish', () => {\n const { req } = this\n\n // Node < 15 does not call _final in same tick.\n req.push(null)\n })\n\n this.res = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n const { ret, res } = this\n\n assert(!res, 'pipeline cannot be retried')\n\n if (ret.destroyed) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume) {\n const { opaque, handler, context } = this\n\n if (statusCode < 200) {\n if (this.onInfo) {\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n this.res = new PipelineResponse(resume)\n\n let body\n try {\n this.handler = null\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n body = this.runInAsyncScope(handler, null, {\n statusCode,\n headers,\n opaque,\n body: this.res,\n context\n })\n } catch (err) {\n this.res.on('error', util.nop)\n throw err\n }\n\n if (!body || typeof body.on !== 'function') {\n throw new InvalidReturnValueError('expected Readable')\n }\n\n body\n .on('data', (chunk) => {\n const { ret, body } = this\n\n if (!ret.push(chunk) && body.pause) {\n body.pause()\n }\n })\n .on('error', (err) => {\n const { ret } = this\n\n util.destroy(ret, err)\n })\n .on('end', () => {\n const { ret } = this\n\n ret.push(null)\n })\n .on('close', () => {\n const { ret } = this\n\n if (!ret._readableState.ended) {\n util.destroy(ret, new RequestAbortedError())\n }\n })\n\n this.body = body\n }\n\n onData (chunk) {\n const { res } = this\n return res.push(chunk)\n }\n\n onComplete (trailers) {\n const { res } = this\n res.push(null)\n }\n\n onError (err) {\n const { ret } = this\n this.handler = null\n util.destroy(ret, err)\n }\n}\n\nfunction pipeline (opts, handler) {\n try {\n const pipelineHandler = new PipelineHandler(opts, handler)\n this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)\n return pipelineHandler.ret\n } catch (err) {\n return new PassThrough().destroy(err)\n }\n}\n\nmodule.exports = pipeline\n","'use strict'\n\nconst Readable = require('./readable')\nconst {\n InvalidArgumentError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { getResolveErrorBodyCallback } = require('./util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass RequestHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts\n\n try {\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {\n throw new InvalidArgumentError('invalid highWaterMark')\n }\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_REQUEST')\n } catch (err) {\n if (util.isStream(body)) {\n util.destroy(body.on('error', util.nop), err)\n }\n throw err\n }\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.callback = callback\n this.res = null\n this.abort = null\n this.body = body\n this.trailers = {}\n this.context = null\n this.onInfo = onInfo || null\n this.throwOnError = throwOnError\n this.highWaterMark = highWaterMark\n\n if (util.isStream(body)) {\n body.on('error', (err) => {\n this.onError(err)\n })\n }\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this\n\n const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n\n if (statusCode < 200) {\n if (this.onInfo) {\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers\n const contentType = parsedHeaders['content-type']\n const body = new Readable({ resume, abort, contentType, highWaterMark })\n\n this.callback = null\n this.res = body\n if (callback !== null) {\n if (this.throwOnError && statusCode >= 400) {\n this.runInAsyncScope(getResolveErrorBodyCallback, null,\n { callback, body, contentType, statusCode, statusMessage, headers }\n )\n } else {\n this.runInAsyncScope(callback, null, null, {\n statusCode,\n headers,\n trailers: this.trailers,\n opaque,\n body,\n context\n })\n }\n }\n }\n\n onData (chunk) {\n const { res } = this\n return res.push(chunk)\n }\n\n onComplete (trailers) {\n const { res } = this\n\n removeSignal(this)\n\n util.parseHeaders(trailers, this.trailers)\n\n res.push(null)\n }\n\n onError (err) {\n const { res, callback, body, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n // TODO: Does this need queueMicrotask?\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n\n if (res) {\n this.res = null\n // Ensure all queued handlers are invoked before destroying res.\n queueMicrotask(() => {\n util.destroy(res, err)\n })\n }\n\n if (body) {\n this.body = null\n util.destroy(body, err)\n }\n }\n}\n\nfunction request (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n request.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n this.dispatch(opts, new RequestHandler(opts, callback))\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = request\nmodule.exports.RequestHandler = RequestHandler\n","'use strict'\n\nconst { finished, PassThrough } = require('stream')\nconst {\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { getResolveErrorBodyCallback } = require('./util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass StreamHandler extends AsyncResource {\n constructor (opts, factory, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts\n\n try {\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('invalid factory')\n }\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_STREAM')\n } catch (err) {\n if (util.isStream(body)) {\n util.destroy(body.on('error', util.nop), err)\n }\n throw err\n }\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.factory = factory\n this.callback = callback\n this.res = null\n this.abort = null\n this.context = null\n this.trailers = null\n this.body = body\n this.onInfo = onInfo || null\n this.throwOnError = throwOnError || false\n\n if (util.isStream(body)) {\n body.on('error', (err) => {\n this.onError(err)\n })\n }\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const { factory, opaque, context, callback, responseHeaders } = this\n\n const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n\n if (statusCode < 200) {\n if (this.onInfo) {\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n this.factory = null\n\n let res\n\n if (this.throwOnError && statusCode >= 400) {\n const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers\n const contentType = parsedHeaders['content-type']\n res = new PassThrough()\n\n this.callback = null\n this.runInAsyncScope(getResolveErrorBodyCallback, null,\n { callback, body: res, contentType, statusCode, statusMessage, headers }\n )\n } else {\n if (factory === null) {\n return\n }\n\n res = this.runInAsyncScope(factory, null, {\n statusCode,\n headers,\n opaque,\n context\n })\n\n if (\n !res ||\n typeof res.write !== 'function' ||\n typeof res.end !== 'function' ||\n typeof res.on !== 'function'\n ) {\n throw new InvalidReturnValueError('expected Writable')\n }\n\n // TODO: Avoid finished. It registers an unnecessary amount of listeners.\n finished(res, { readable: false }, (err) => {\n const { callback, res, opaque, trailers, abort } = this\n\n this.res = null\n if (err || !res.readable) {\n util.destroy(res, err)\n }\n\n this.callback = null\n this.runInAsyncScope(callback, null, err || null, { opaque, trailers })\n\n if (err) {\n abort()\n }\n })\n }\n\n res.on('drain', resume)\n\n this.res = res\n\n const needDrain = res.writableNeedDrain !== undefined\n ? res.writableNeedDrain\n : res._writableState && res._writableState.needDrain\n\n return needDrain !== true\n }\n\n onData (chunk) {\n const { res } = this\n\n return res ? res.write(chunk) : true\n }\n\n onComplete (trailers) {\n const { res } = this\n\n removeSignal(this)\n\n if (!res) {\n return\n }\n\n this.trailers = util.parseHeaders(trailers)\n\n res.end()\n }\n\n onError (err) {\n const { res, callback, opaque, body } = this\n\n removeSignal(this)\n\n this.factory = null\n\n if (res) {\n this.res = null\n util.destroy(res, err)\n } else if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n\n if (body) {\n this.body = null\n util.destroy(body, err)\n }\n }\n}\n\nfunction stream (opts, factory, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n stream.call(this, opts, factory, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n this.dispatch(opts, new StreamHandler(opts, factory, callback))\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = stream\n","'use strict'\n\nconst { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors')\nconst { AsyncResource } = require('async_hooks')\nconst util = require('../core/util')\nconst { addSignal, removeSignal } = require('./abort-signal')\nconst assert = require('assert')\n\nclass UpgradeHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n const { signal, opaque, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n super('UNDICI_UPGRADE')\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.callback = callback\n this.abort = null\n this.context = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = null\n }\n\n onHeaders () {\n throw new SocketError('bad upgrade', null)\n }\n\n onUpgrade (statusCode, rawHeaders, socket) {\n const { callback, opaque, context } = this\n\n assert.strictEqual(statusCode, 101)\n\n removeSignal(this)\n\n this.callback = null\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n this.runInAsyncScope(callback, null, null, {\n headers,\n socket,\n opaque,\n context\n })\n }\n\n onError (err) {\n const { callback, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n }\n}\n\nfunction upgrade (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n upgrade.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n const upgradeHandler = new UpgradeHandler(opts, callback)\n this.dispatch({\n ...opts,\n method: opts.method || 'GET',\n upgrade: opts.protocol || 'Websocket'\n }, upgradeHandler)\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = upgrade\n","'use strict'\n\nmodule.exports.request = require('./api-request')\nmodule.exports.stream = require('./api-stream')\nmodule.exports.pipeline = require('./api-pipeline')\nmodule.exports.upgrade = require('./api-upgrade')\nmodule.exports.connect = require('./api-connect')\n","// Ported from https://github.com/nodejs/undici/pull/907\n\n'use strict'\n\nconst assert = require('assert')\nconst { Readable } = require('stream')\nconst { RequestAbortedError, NotSupportedError, InvalidArgumentError } = require('../core/errors')\nconst util = require('../core/util')\nconst { ReadableStreamFrom, toUSVString } = require('../core/util')\n\nlet Blob\n\nconst kConsume = Symbol('kConsume')\nconst kReading = Symbol('kReading')\nconst kBody = Symbol('kBody')\nconst kAbort = Symbol('abort')\nconst kContentType = Symbol('kContentType')\n\nconst noop = () => {}\n\nmodule.exports = class BodyReadable extends Readable {\n constructor ({\n resume,\n abort,\n contentType = '',\n highWaterMark = 64 * 1024 // Same as nodejs fs streams.\n }) {\n super({\n autoDestroy: true,\n read: resume,\n highWaterMark\n })\n\n this._readableState.dataEmitted = false\n\n this[kAbort] = abort\n this[kConsume] = null\n this[kBody] = null\n this[kContentType] = contentType\n\n // Is stream being consumed through Readable API?\n // This is an optimization so that we avoid checking\n // for 'data' and 'readable' listeners in the hot path\n // inside push().\n this[kReading] = false\n }\n\n destroy (err) {\n if (this.destroyed) {\n // Node < 16\n return this\n }\n\n if (!err && !this._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n if (err) {\n this[kAbort]()\n }\n\n return super.destroy(err)\n }\n\n emit (ev, ...args) {\n if (ev === 'data') {\n // Node < 16.7\n this._readableState.dataEmitted = true\n } else if (ev === 'error') {\n // Node < 16\n this._readableState.errorEmitted = true\n }\n return super.emit(ev, ...args)\n }\n\n on (ev, ...args) {\n if (ev === 'data' || ev === 'readable') {\n this[kReading] = true\n }\n return super.on(ev, ...args)\n }\n\n addListener (ev, ...args) {\n return this.on(ev, ...args)\n }\n\n off (ev, ...args) {\n const ret = super.off(ev, ...args)\n if (ev === 'data' || ev === 'readable') {\n this[kReading] = (\n this.listenerCount('data') > 0 ||\n this.listenerCount('readable') > 0\n )\n }\n return ret\n }\n\n removeListener (ev, ...args) {\n return this.off(ev, ...args)\n }\n\n push (chunk) {\n if (this[kConsume] && chunk !== null && this.readableLength === 0) {\n consumePush(this[kConsume], chunk)\n return this[kReading] ? super.push(chunk) : true\n }\n return super.push(chunk)\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-text\n async text () {\n return consume(this, 'text')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-json\n async json () {\n return consume(this, 'json')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-blob\n async blob () {\n return consume(this, 'blob')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-arraybuffer\n async arrayBuffer () {\n return consume(this, 'arrayBuffer')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-formdata\n async formData () {\n // TODO: Implement.\n throw new NotSupportedError()\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-bodyused\n get bodyUsed () {\n return util.isDisturbed(this)\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-body\n get body () {\n if (!this[kBody]) {\n this[kBody] = ReadableStreamFrom(this)\n if (this[kConsume]) {\n // TODO: Is this the best way to force a lock?\n this[kBody].getReader() // Ensure stream is locked.\n assert(this[kBody].locked)\n }\n }\n return this[kBody]\n }\n\n dump (opts) {\n let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144\n const signal = opts && opts.signal\n\n if (signal) {\n try {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n throw new InvalidArgumentError('signal must be an AbortSignal')\n }\n util.throwIfAborted(signal)\n } catch (err) {\n return Promise.reject(err)\n }\n }\n\n if (this.closed) {\n return Promise.resolve(null)\n }\n\n return new Promise((resolve, reject) => {\n const signalListenerCleanup = signal\n ? util.addAbortListener(signal, () => {\n this.destroy()\n })\n : noop\n\n this\n .on('close', function () {\n signalListenerCleanup()\n if (signal && signal.aborted) {\n reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))\n } else {\n resolve(null)\n }\n })\n .on('error', noop)\n .on('data', function (chunk) {\n limit -= chunk.length\n if (limit <= 0) {\n this.destroy()\n }\n })\n .resume()\n })\n }\n}\n\n// https://streams.spec.whatwg.org/#readablestream-locked\nfunction isLocked (self) {\n // Consume is an implicit lock.\n return (self[kBody] && self[kBody].locked === true) || self[kConsume]\n}\n\n// https://fetch.spec.whatwg.org/#body-unusable\nfunction isUnusable (self) {\n return util.isDisturbed(self) || isLocked(self)\n}\n\nasync function consume (stream, type) {\n if (isUnusable(stream)) {\n throw new TypeError('unusable')\n }\n\n assert(!stream[kConsume])\n\n return new Promise((resolve, reject) => {\n stream[kConsume] = {\n type,\n stream,\n resolve,\n reject,\n length: 0,\n body: []\n }\n\n stream\n .on('error', function (err) {\n consumeFinish(this[kConsume], err)\n })\n .on('close', function () {\n if (this[kConsume].body !== null) {\n consumeFinish(this[kConsume], new RequestAbortedError())\n }\n })\n\n process.nextTick(consumeStart, stream[kConsume])\n })\n}\n\nfunction consumeStart (consume) {\n if (consume.body === null) {\n return\n }\n\n const { _readableState: state } = consume.stream\n\n for (const chunk of state.buffer) {\n consumePush(consume, chunk)\n }\n\n if (state.endEmitted) {\n consumeEnd(this[kConsume])\n } else {\n consume.stream.on('end', function () {\n consumeEnd(this[kConsume])\n })\n }\n\n consume.stream.resume()\n\n while (consume.stream.read() != null) {\n // Loop\n }\n}\n\nfunction consumeEnd (consume) {\n const { type, body, resolve, stream, length } = consume\n\n try {\n if (type === 'text') {\n resolve(toUSVString(Buffer.concat(body)))\n } else if (type === 'json') {\n resolve(JSON.parse(Buffer.concat(body)))\n } else if (type === 'arrayBuffer') {\n const dst = new Uint8Array(length)\n\n let pos = 0\n for (const buf of body) {\n dst.set(buf, pos)\n pos += buf.byteLength\n }\n\n resolve(dst.buffer)\n } else if (type === 'blob') {\n if (!Blob) {\n Blob = require('buffer').Blob\n }\n resolve(new Blob(body, { type: stream[kContentType] }))\n }\n\n consumeFinish(consume)\n } catch (err) {\n stream.destroy(err)\n }\n}\n\nfunction consumePush (consume, chunk) {\n consume.length += chunk.length\n consume.body.push(chunk)\n}\n\nfunction consumeFinish (consume, err) {\n if (consume.body === null) {\n return\n }\n\n if (err) {\n consume.reject(err)\n } else {\n consume.resolve()\n }\n\n consume.type = null\n consume.stream = null\n consume.resolve = null\n consume.reject = null\n consume.length = 0\n consume.body = null\n}\n","const assert = require('assert')\nconst {\n ResponseStatusCodeError\n} = require('../core/errors')\nconst { toUSVString } = require('../core/util')\n\nasync function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {\n assert(body)\n\n let chunks = []\n let limit = 0\n\n for await (const chunk of body) {\n chunks.push(chunk)\n limit += chunk.length\n if (limit > 128 * 1024) {\n chunks = null\n break\n }\n }\n\n if (statusCode === 204 || !contentType || !chunks) {\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))\n return\n }\n\n try {\n if (contentType.startsWith('application/json')) {\n const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))\n return\n }\n\n if (contentType.startsWith('text/')) {\n const payload = toUSVString(Buffer.concat(chunks))\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))\n return\n }\n } catch (err) {\n // Process in a fallback if error\n }\n\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))\n}\n\nmodule.exports = { getResolveErrorBodyCallback }\n","'use strict'\n\nconst {\n BalancedPoolMissingUpstreamError,\n InvalidArgumentError\n} = require('./core/errors')\nconst {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kRemoveClient,\n kGetDispatcher\n} = require('./pool-base')\nconst Pool = require('./pool')\nconst { kUrl, kInterceptors } = require('./core/symbols')\nconst { parseOrigin } = require('./core/util')\nconst kFactory = Symbol('factory')\n\nconst kOptions = Symbol('options')\nconst kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')\nconst kCurrentWeight = Symbol('kCurrentWeight')\nconst kIndex = Symbol('kIndex')\nconst kWeight = Symbol('kWeight')\nconst kMaxWeightPerServer = Symbol('kMaxWeightPerServer')\nconst kErrorPenalty = Symbol('kErrorPenalty')\n\nfunction getGreatestCommonDivisor (a, b) {\n if (b === 0) return a\n return getGreatestCommonDivisor(b, a % b)\n}\n\nfunction defaultFactory (origin, opts) {\n return new Pool(origin, opts)\n}\n\nclass BalancedPool extends PoolBase {\n constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {\n super()\n\n this[kOptions] = opts\n this[kIndex] = -1\n this[kCurrentWeight] = 0\n\n this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100\n this[kErrorPenalty] = this[kOptions].errorPenalty || 15\n\n if (!Array.isArray(upstreams)) {\n upstreams = [upstreams]\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)\n ? opts.interceptors.BalancedPool\n : []\n this[kFactory] = factory\n\n for (const upstream of upstreams) {\n this.addUpstream(upstream)\n }\n this._updateBalancedPoolStats()\n }\n\n addUpstream (upstream) {\n const upstreamOrigin = parseOrigin(upstream).origin\n\n if (this[kClients].find((pool) => (\n pool[kUrl].origin === upstreamOrigin &&\n pool.closed !== true &&\n pool.destroyed !== true\n ))) {\n return this\n }\n const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))\n\n this[kAddClient](pool)\n pool.on('connect', () => {\n pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])\n })\n\n pool.on('connectionError', () => {\n pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])\n this._updateBalancedPoolStats()\n })\n\n pool.on('disconnect', (...args) => {\n const err = args[2]\n if (err && err.code === 'UND_ERR_SOCKET') {\n // decrease the weight of the pool.\n pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])\n this._updateBalancedPoolStats()\n }\n })\n\n for (const client of this[kClients]) {\n client[kWeight] = this[kMaxWeightPerServer]\n }\n\n this._updateBalancedPoolStats()\n\n return this\n }\n\n _updateBalancedPoolStats () {\n this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)\n }\n\n removeUpstream (upstream) {\n const upstreamOrigin = parseOrigin(upstream).origin\n\n const pool = this[kClients].find((pool) => (\n pool[kUrl].origin === upstreamOrigin &&\n pool.closed !== true &&\n pool.destroyed !== true\n ))\n\n if (pool) {\n this[kRemoveClient](pool)\n }\n\n return this\n }\n\n get upstreams () {\n return this[kClients]\n .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)\n .map((p) => p[kUrl].origin)\n }\n\n [kGetDispatcher] () {\n // We validate that pools is greater than 0,\n // otherwise we would have to wait until an upstream\n // is added, which might never happen.\n if (this[kClients].length === 0) {\n throw new BalancedPoolMissingUpstreamError()\n }\n\n const dispatcher = this[kClients].find(dispatcher => (\n !dispatcher[kNeedDrain] &&\n dispatcher.closed !== true &&\n dispatcher.destroyed !== true\n ))\n\n if (!dispatcher) {\n return\n }\n\n const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)\n\n if (allClientsBusy) {\n return\n }\n\n let counter = 0\n\n let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])\n\n while (counter++ < this[kClients].length) {\n this[kIndex] = (this[kIndex] + 1) % this[kClients].length\n const pool = this[kClients][this[kIndex]]\n\n // find pool index with the largest weight\n if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {\n maxWeightIndex = this[kIndex]\n }\n\n // decrease the current weight every `this[kClients].length`.\n if (this[kIndex] === 0) {\n // Set the current weight to the next lower weight.\n this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]\n\n if (this[kCurrentWeight] <= 0) {\n this[kCurrentWeight] = this[kMaxWeightPerServer]\n }\n }\n if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {\n return pool\n }\n }\n\n this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]\n this[kIndex] = maxWeightIndex\n return this[kClients][maxWeightIndex]\n }\n}\n\nmodule.exports = BalancedPool\n","'use strict'\n\nconst { kConstruct } = require('./symbols')\nconst { urlEquals, fieldValues: getFieldValues } = require('./util')\nconst { kEnumerableProperty, isDisturbed } = require('../core/util')\nconst { kHeadersList } = require('../core/symbols')\nconst { webidl } = require('../fetch/webidl')\nconst { Response, cloneResponse } = require('../fetch/response')\nconst { Request } = require('../fetch/request')\nconst { kState, kHeaders, kGuard, kRealm } = require('../fetch/symbols')\nconst { fetching } = require('../fetch/index')\nconst { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util')\nconst assert = require('assert')\nconst { getGlobalDispatcher } = require('../global')\n\n/**\n * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation\n * @typedef {Object} CacheBatchOperation\n * @property {'delete' | 'put'} type\n * @property {any} request\n * @property {any} response\n * @property {import('../../types/cache').CacheQueryOptions} options\n */\n\n/**\n * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list\n * @typedef {[any, any][]} requestResponseList\n */\n\nclass Cache {\n /**\n * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list\n * @type {requestResponseList}\n */\n #relevantRequestResponseList\n\n constructor () {\n if (arguments[0] !== kConstruct) {\n webidl.illegalConstructor()\n }\n\n this.#relevantRequestResponseList = arguments[1]\n }\n\n async match (request, options = {}) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })\n\n request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n const p = await this.matchAll(request, options)\n\n if (p.length === 0) {\n return\n }\n\n return p[0]\n }\n\n async matchAll (request = undefined, options = {}) {\n webidl.brandCheck(this, Cache)\n\n if (request !== undefined) request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n // 1.\n let r = null\n\n // 2.\n if (request !== undefined) {\n if (request instanceof Request) {\n // 2.1.1\n r = request[kState]\n\n // 2.1.2\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return []\n }\n } else if (typeof request === 'string') {\n // 2.2.1\n r = new Request(request)[kState]\n }\n }\n\n // 5.\n // 5.1\n const responses = []\n\n // 5.2\n if (request === undefined) {\n // 5.2.1\n for (const requestResponse of this.#relevantRequestResponseList) {\n responses.push(requestResponse[1])\n }\n } else { // 5.3\n // 5.3.1\n const requestResponses = this.#queryCache(r, options)\n\n // 5.3.2\n for (const requestResponse of requestResponses) {\n responses.push(requestResponse[1])\n }\n }\n\n // 5.4\n // We don't implement CORs so we don't need to loop over the responses, yay!\n\n // 5.5.1\n const responseList = []\n\n // 5.5.2\n for (const response of responses) {\n // 5.5.2.1\n const responseObject = new Response(response.body?.source ?? null)\n const body = responseObject[kState].body\n responseObject[kState] = response\n responseObject[kState].body = body\n responseObject[kHeaders][kHeadersList] = response.headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n\n responseList.push(responseObject)\n }\n\n // 6.\n return Object.freeze(responseList)\n }\n\n async add (request) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })\n\n request = webidl.converters.RequestInfo(request)\n\n // 1.\n const requests = [request]\n\n // 2.\n const responseArrayPromise = this.addAll(requests)\n\n // 3.\n return await responseArrayPromise\n }\n\n async addAll (requests) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })\n\n requests = webidl.converters['sequence'](requests)\n\n // 1.\n const responsePromises = []\n\n // 2.\n const requestList = []\n\n // 3.\n for (const request of requests) {\n if (typeof request === 'string') {\n continue\n }\n\n // 3.1\n const r = request[kState]\n\n // 3.2\n if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Expected http/s scheme when method is not GET.'\n })\n }\n }\n\n // 4.\n /** @type {ReturnType[]} */\n const fetchControllers = []\n\n // 5.\n for (const request of requests) {\n // 5.1\n const r = new Request(request)[kState]\n\n // 5.2\n if (!urlIsHttpHttpsScheme(r.url)) {\n throw webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Expected http/s scheme.'\n })\n }\n\n // 5.4\n r.initiator = 'fetch'\n r.destination = 'subresource'\n\n // 5.5\n requestList.push(r)\n\n // 5.6\n const responsePromise = createDeferredPromise()\n\n // 5.7\n fetchControllers.push(fetching({\n request: r,\n dispatcher: getGlobalDispatcher(),\n processResponse (response) {\n // 1.\n if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {\n responsePromise.reject(webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Received an invalid status code or the request failed.'\n }))\n } else if (response.headersList.contains('vary')) { // 2.\n // 2.1\n const fieldValues = getFieldValues(response.headersList.get('vary'))\n\n // 2.2\n for (const fieldValue of fieldValues) {\n // 2.2.1\n if (fieldValue === '*') {\n responsePromise.reject(webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'invalid vary field value'\n }))\n\n for (const controller of fetchControllers) {\n controller.abort()\n }\n\n return\n }\n }\n }\n },\n processResponseEndOfBody (response) {\n // 1.\n if (response.aborted) {\n responsePromise.reject(new DOMException('aborted', 'AbortError'))\n return\n }\n\n // 2.\n responsePromise.resolve(response)\n }\n }))\n\n // 5.8\n responsePromises.push(responsePromise.promise)\n }\n\n // 6.\n const p = Promise.all(responsePromises)\n\n // 7.\n const responses = await p\n\n // 7.1\n const operations = []\n\n // 7.2\n let index = 0\n\n // 7.3\n for (const response of responses) {\n // 7.3.1\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'put', // 7.3.2\n request: requestList[index], // 7.3.3\n response // 7.3.4\n }\n\n operations.push(operation) // 7.3.5\n\n index++ // 7.3.6\n }\n\n // 7.5\n const cacheJobPromise = createDeferredPromise()\n\n // 7.6.1\n let errorData = null\n\n // 7.6.2\n try {\n this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n // 7.6.3\n queueMicrotask(() => {\n // 7.6.3.1\n if (errorData === null) {\n cacheJobPromise.resolve(undefined)\n } else {\n // 7.6.3.2\n cacheJobPromise.reject(errorData)\n }\n })\n\n // 7.7\n return cacheJobPromise.promise\n }\n\n async put (request, response) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })\n\n request = webidl.converters.RequestInfo(request)\n response = webidl.converters.Response(response)\n\n // 1.\n let innerRequest = null\n\n // 2.\n if (request instanceof Request) {\n innerRequest = request[kState]\n } else { // 3.\n innerRequest = new Request(request)[kState]\n }\n\n // 4.\n if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Expected an http/s scheme when method is not GET'\n })\n }\n\n // 5.\n const innerResponse = response[kState]\n\n // 6.\n if (innerResponse.status === 206) {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Got 206 status'\n })\n }\n\n // 7.\n if (innerResponse.headersList.contains('vary')) {\n // 7.1.\n const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))\n\n // 7.2.\n for (const fieldValue of fieldValues) {\n // 7.2.1\n if (fieldValue === '*') {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Got * vary field value'\n })\n }\n }\n }\n\n // 8.\n if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Response body is locked or disturbed'\n })\n }\n\n // 9.\n const clonedResponse = cloneResponse(innerResponse)\n\n // 10.\n const bodyReadPromise = createDeferredPromise()\n\n // 11.\n if (innerResponse.body != null) {\n // 11.1\n const stream = innerResponse.body.stream\n\n // 11.2\n const reader = stream.getReader()\n\n // 11.3\n readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)\n } else {\n bodyReadPromise.resolve(undefined)\n }\n\n // 12.\n /** @type {CacheBatchOperation[]} */\n const operations = []\n\n // 13.\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'put', // 14.\n request: innerRequest, // 15.\n response: clonedResponse // 16.\n }\n\n // 17.\n operations.push(operation)\n\n // 19.\n const bytes = await bodyReadPromise.promise\n\n if (clonedResponse.body != null) {\n clonedResponse.body.source = bytes\n }\n\n // 19.1\n const cacheJobPromise = createDeferredPromise()\n\n // 19.2.1\n let errorData = null\n\n // 19.2.2\n try {\n this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n // 19.2.3\n queueMicrotask(() => {\n // 19.2.3.1\n if (errorData === null) {\n cacheJobPromise.resolve()\n } else { // 19.2.3.2\n cacheJobPromise.reject(errorData)\n }\n })\n\n return cacheJobPromise.promise\n }\n\n async delete (request, options = {}) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })\n\n request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n /**\n * @type {Request}\n */\n let r = null\n\n if (request instanceof Request) {\n r = request[kState]\n\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return false\n }\n } else {\n assert(typeof request === 'string')\n\n r = new Request(request)[kState]\n }\n\n /** @type {CacheBatchOperation[]} */\n const operations = []\n\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'delete',\n request: r,\n options\n }\n\n operations.push(operation)\n\n const cacheJobPromise = createDeferredPromise()\n\n let errorData = null\n let requestResponses\n\n try {\n requestResponses = this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n queueMicrotask(() => {\n if (errorData === null) {\n cacheJobPromise.resolve(!!requestResponses?.length)\n } else {\n cacheJobPromise.reject(errorData)\n }\n })\n\n return cacheJobPromise.promise\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys\n * @param {any} request\n * @param {import('../../types/cache').CacheQueryOptions} options\n * @returns {readonly Request[]}\n */\n async keys (request = undefined, options = {}) {\n webidl.brandCheck(this, Cache)\n\n if (request !== undefined) request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n // 1.\n let r = null\n\n // 2.\n if (request !== undefined) {\n // 2.1\n if (request instanceof Request) {\n // 2.1.1\n r = request[kState]\n\n // 2.1.2\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return []\n }\n } else if (typeof request === 'string') { // 2.2\n r = new Request(request)[kState]\n }\n }\n\n // 4.\n const promise = createDeferredPromise()\n\n // 5.\n // 5.1\n const requests = []\n\n // 5.2\n if (request === undefined) {\n // 5.2.1\n for (const requestResponse of this.#relevantRequestResponseList) {\n // 5.2.1.1\n requests.push(requestResponse[0])\n }\n } else { // 5.3\n // 5.3.1\n const requestResponses = this.#queryCache(r, options)\n\n // 5.3.2\n for (const requestResponse of requestResponses) {\n // 5.3.2.1\n requests.push(requestResponse[0])\n }\n }\n\n // 5.4\n queueMicrotask(() => {\n // 5.4.1\n const requestList = []\n\n // 5.4.2\n for (const request of requests) {\n const requestObject = new Request('https://a')\n requestObject[kState] = request\n requestObject[kHeaders][kHeadersList] = request.headersList\n requestObject[kHeaders][kGuard] = 'immutable'\n requestObject[kRealm] = request.client\n\n // 5.4.2.1\n requestList.push(requestObject)\n }\n\n // 5.4.3\n promise.resolve(Object.freeze(requestList))\n })\n\n return promise.promise\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm\n * @param {CacheBatchOperation[]} operations\n * @returns {requestResponseList}\n */\n #batchCacheOperations (operations) {\n // 1.\n const cache = this.#relevantRequestResponseList\n\n // 2.\n const backupCache = [...cache]\n\n // 3.\n const addedItems = []\n\n // 4.1\n const resultList = []\n\n try {\n // 4.2\n for (const operation of operations) {\n // 4.2.1\n if (operation.type !== 'delete' && operation.type !== 'put') {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'operation type does not match \"delete\" or \"put\"'\n })\n }\n\n // 4.2.2\n if (operation.type === 'delete' && operation.response != null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'delete operation should not have an associated response'\n })\n }\n\n // 4.2.3\n if (this.#queryCache(operation.request, operation.options, addedItems).length) {\n throw new DOMException('???', 'InvalidStateError')\n }\n\n // 4.2.4\n let requestResponses\n\n // 4.2.5\n if (operation.type === 'delete') {\n // 4.2.5.1\n requestResponses = this.#queryCache(operation.request, operation.options)\n\n // TODO: the spec is wrong, this is needed to pass WPTs\n if (requestResponses.length === 0) {\n return []\n }\n\n // 4.2.5.2\n for (const requestResponse of requestResponses) {\n const idx = cache.indexOf(requestResponse)\n assert(idx !== -1)\n\n // 4.2.5.2.1\n cache.splice(idx, 1)\n }\n } else if (operation.type === 'put') { // 4.2.6\n // 4.2.6.1\n if (operation.response == null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'put operation should have an associated response'\n })\n }\n\n // 4.2.6.2\n const r = operation.request\n\n // 4.2.6.3\n if (!urlIsHttpHttpsScheme(r.url)) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'expected http or https scheme'\n })\n }\n\n // 4.2.6.4\n if (r.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'not get method'\n })\n }\n\n // 4.2.6.5\n if (operation.options != null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'options must not be defined'\n })\n }\n\n // 4.2.6.6\n requestResponses = this.#queryCache(operation.request)\n\n // 4.2.6.7\n for (const requestResponse of requestResponses) {\n const idx = cache.indexOf(requestResponse)\n assert(idx !== -1)\n\n // 4.2.6.7.1\n cache.splice(idx, 1)\n }\n\n // 4.2.6.8\n cache.push([operation.request, operation.response])\n\n // 4.2.6.10\n addedItems.push([operation.request, operation.response])\n }\n\n // 4.2.7\n resultList.push([operation.request, operation.response])\n }\n\n // 4.3\n return resultList\n } catch (e) { // 5.\n // 5.1\n this.#relevantRequestResponseList.length = 0\n\n // 5.2\n this.#relevantRequestResponseList = backupCache\n\n // 5.3\n throw e\n }\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#query-cache\n * @param {any} requestQuery\n * @param {import('../../types/cache').CacheQueryOptions} options\n * @param {requestResponseList} targetStorage\n * @returns {requestResponseList}\n */\n #queryCache (requestQuery, options, targetStorage) {\n /** @type {requestResponseList} */\n const resultList = []\n\n const storage = targetStorage ?? this.#relevantRequestResponseList\n\n for (const requestResponse of storage) {\n const [cachedRequest, cachedResponse] = requestResponse\n if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {\n resultList.push(requestResponse)\n }\n }\n\n return resultList\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm\n * @param {any} requestQuery\n * @param {any} request\n * @param {any | null} response\n * @param {import('../../types/cache').CacheQueryOptions | undefined} options\n * @returns {boolean}\n */\n #requestMatchesCachedItem (requestQuery, request, response = null, options) {\n // if (options?.ignoreMethod === false && request.method === 'GET') {\n // return false\n // }\n\n const queryURL = new URL(requestQuery.url)\n\n const cachedURL = new URL(request.url)\n\n if (options?.ignoreSearch) {\n cachedURL.search = ''\n\n queryURL.search = ''\n }\n\n if (!urlEquals(queryURL, cachedURL, true)) {\n return false\n }\n\n if (\n response == null ||\n options?.ignoreVary ||\n !response.headersList.contains('vary')\n ) {\n return true\n }\n\n const fieldValues = getFieldValues(response.headersList.get('vary'))\n\n for (const fieldValue of fieldValues) {\n if (fieldValue === '*') {\n return false\n }\n\n const requestValue = request.headersList.get(fieldValue)\n const queryValue = requestQuery.headersList.get(fieldValue)\n\n // If one has the header and the other doesn't, or one has\n // a different value than the other, return false\n if (requestValue !== queryValue) {\n return false\n }\n }\n\n return true\n }\n}\n\nObject.defineProperties(Cache.prototype, {\n [Symbol.toStringTag]: {\n value: 'Cache',\n configurable: true\n },\n match: kEnumerableProperty,\n matchAll: kEnumerableProperty,\n add: kEnumerableProperty,\n addAll: kEnumerableProperty,\n put: kEnumerableProperty,\n delete: kEnumerableProperty,\n keys: kEnumerableProperty\n})\n\nconst cacheQueryOptionConverters = [\n {\n key: 'ignoreSearch',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'ignoreMethod',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'ignoreVary',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n]\n\nwebidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)\n\nwebidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([\n ...cacheQueryOptionConverters,\n {\n key: 'cacheName',\n converter: webidl.converters.DOMString\n }\n])\n\nwebidl.converters.Response = webidl.interfaceConverter(Response)\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.RequestInfo\n)\n\nmodule.exports = {\n Cache\n}\n","'use strict'\n\nconst { kConstruct } = require('./symbols')\nconst { Cache } = require('./cache')\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\n\nclass CacheStorage {\n /**\n * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map\n * @type {Map}\n */\n async has (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n // 2.1.1\n // 2.2\n return this.#caches.has(cacheName)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open\n * @param {string} cacheName\n * @returns {Promise}\n */\n async open (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n // 2.1\n if (this.#caches.has(cacheName)) {\n // await caches.open('v1') !== await caches.open('v1')\n\n // 2.1.1\n const cache = this.#caches.get(cacheName)\n\n // 2.1.1.1\n return new Cache(kConstruct, cache)\n }\n\n // 2.2\n const cache = []\n\n // 2.3\n this.#caches.set(cacheName, cache)\n\n // 2.4\n return new Cache(kConstruct, cache)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete\n * @param {string} cacheName\n * @returns {Promise}\n */\n async delete (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n return this.#caches.delete(cacheName)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys\n * @returns {string[]}\n */\n async keys () {\n webidl.brandCheck(this, CacheStorage)\n\n // 2.1\n const keys = this.#caches.keys()\n\n // 2.2\n return [...keys]\n }\n}\n\nObject.defineProperties(CacheStorage.prototype, {\n [Symbol.toStringTag]: {\n value: 'CacheStorage',\n configurable: true\n },\n match: kEnumerableProperty,\n has: kEnumerableProperty,\n open: kEnumerableProperty,\n delete: kEnumerableProperty,\n keys: kEnumerableProperty\n})\n\nmodule.exports = {\n CacheStorage\n}\n","'use strict'\n\nmodule.exports = {\n kConstruct: require('../core/symbols').kConstruct\n}\n","'use strict'\n\nconst assert = require('assert')\nconst { URLSerializer } = require('../fetch/dataURL')\nconst { isValidHeaderName } = require('../fetch/util')\n\n/**\n * @see https://url.spec.whatwg.org/#concept-url-equals\n * @param {URL} A\n * @param {URL} B\n * @param {boolean | undefined} excludeFragment\n * @returns {boolean}\n */\nfunction urlEquals (A, B, excludeFragment = false) {\n const serializedA = URLSerializer(A, excludeFragment)\n\n const serializedB = URLSerializer(B, excludeFragment)\n\n return serializedA === serializedB\n}\n\n/**\n * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262\n * @param {string} header\n */\nfunction fieldValues (header) {\n assert(header !== null)\n\n const values = []\n\n for (let value of header.split(',')) {\n value = value.trim()\n\n if (!value.length) {\n continue\n } else if (!isValidHeaderName(value)) {\n continue\n }\n\n values.push(value)\n }\n\n return values\n}\n\nmodule.exports = {\n urlEquals,\n fieldValues\n}\n","// @ts-check\n\n'use strict'\n\n/* global WebAssembly */\n\nconst assert = require('assert')\nconst net = require('net')\nconst http = require('http')\nconst { pipeline } = require('stream')\nconst util = require('./core/util')\nconst timers = require('./timers')\nconst Request = require('./core/request')\nconst DispatcherBase = require('./dispatcher-base')\nconst {\n RequestContentLengthMismatchError,\n ResponseContentLengthMismatchError,\n InvalidArgumentError,\n RequestAbortedError,\n HeadersTimeoutError,\n HeadersOverflowError,\n SocketError,\n InformationalError,\n BodyTimeoutError,\n HTTPParserError,\n ResponseExceededMaxSizeError,\n ClientDestroyedError\n} = require('./core/errors')\nconst buildConnector = require('./core/connect')\nconst {\n kUrl,\n kReset,\n kServerName,\n kClient,\n kBusy,\n kParser,\n kConnect,\n kBlocking,\n kResuming,\n kRunning,\n kPending,\n kSize,\n kWriting,\n kQueue,\n kConnected,\n kConnecting,\n kNeedDrain,\n kNoRef,\n kKeepAliveDefaultTimeout,\n kHostHeader,\n kPendingIdx,\n kRunningIdx,\n kError,\n kPipelining,\n kSocket,\n kKeepAliveTimeoutValue,\n kMaxHeadersSize,\n kKeepAliveMaxTimeout,\n kKeepAliveTimeoutThreshold,\n kHeadersTimeout,\n kBodyTimeout,\n kStrictContentLength,\n kConnector,\n kMaxRedirections,\n kMaxRequests,\n kCounter,\n kClose,\n kDestroy,\n kDispatch,\n kInterceptors,\n kLocalAddress,\n kMaxResponseSize,\n kHTTPConnVersion,\n // HTTP2\n kHost,\n kHTTP2Session,\n kHTTP2SessionState,\n kHTTP2BuildRequest,\n kHTTP2CopyHeaders,\n kHTTP1BuildRequest\n} = require('./core/symbols')\n\n/** @type {import('http2')} */\nlet http2\ntry {\n http2 = require('http2')\n} catch {\n // @ts-ignore\n http2 = { constants: {} }\n}\n\nconst {\n constants: {\n HTTP2_HEADER_AUTHORITY,\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_SCHEME,\n HTTP2_HEADER_CONTENT_LENGTH,\n HTTP2_HEADER_EXPECT,\n HTTP2_HEADER_STATUS\n }\n} = http2\n\n// Experimental\nlet h2ExperimentalWarned = false\n\nconst FastBuffer = Buffer[Symbol.species]\n\nconst kClosedResolve = Symbol('kClosedResolve')\n\nconst channels = {}\n\ntry {\n const diagnosticsChannel = require('diagnostics_channel')\n channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')\n channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')\n channels.connectError = diagnosticsChannel.channel('undici:client:connectError')\n channels.connected = diagnosticsChannel.channel('undici:client:connected')\n} catch {\n channels.sendHeaders = { hasSubscribers: false }\n channels.beforeConnect = { hasSubscribers: false }\n channels.connectError = { hasSubscribers: false }\n channels.connected = { hasSubscribers: false }\n}\n\n/**\n * @type {import('../types/client').default}\n */\nclass Client extends DispatcherBase {\n /**\n *\n * @param {string|URL} url\n * @param {import('../types/client').Client.Options} options\n */\n constructor (url, {\n interceptors,\n maxHeaderSize,\n headersTimeout,\n socketTimeout,\n requestTimeout,\n connectTimeout,\n bodyTimeout,\n idleTimeout,\n keepAlive,\n keepAliveTimeout,\n maxKeepAliveTimeout,\n keepAliveMaxTimeout,\n keepAliveTimeoutThreshold,\n socketPath,\n pipelining,\n tls,\n strictContentLength,\n maxCachedSessions,\n maxRedirections,\n connect,\n maxRequestsPerClient,\n localAddress,\n maxResponseSize,\n autoSelectFamily,\n autoSelectFamilyAttemptTimeout,\n // h2\n allowH2,\n maxConcurrentStreams\n } = {}) {\n super()\n\n if (keepAlive !== undefined) {\n throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')\n }\n\n if (socketTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')\n }\n\n if (requestTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')\n }\n\n if (idleTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')\n }\n\n if (maxKeepAliveTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')\n }\n\n if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {\n throw new InvalidArgumentError('invalid maxHeaderSize')\n }\n\n if (socketPath != null && typeof socketPath !== 'string') {\n throw new InvalidArgumentError('invalid socketPath')\n }\n\n if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {\n throw new InvalidArgumentError('invalid connectTimeout')\n }\n\n if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {\n throw new InvalidArgumentError('invalid keepAliveTimeout')\n }\n\n if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {\n throw new InvalidArgumentError('invalid keepAliveMaxTimeout')\n }\n\n if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {\n throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')\n }\n\n if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {\n throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')\n }\n\n if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {\n throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {\n throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')\n }\n\n if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {\n throw new InvalidArgumentError('localAddress must be valid string IP address')\n }\n\n if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {\n throw new InvalidArgumentError('maxResponseSize must be a positive number')\n }\n\n if (\n autoSelectFamilyAttemptTimeout != null &&\n (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)\n ) {\n throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')\n }\n\n // h2\n if (allowH2 != null && typeof allowH2 !== 'boolean') {\n throw new InvalidArgumentError('allowH2 must be a valid boolean value')\n }\n\n if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {\n throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')\n }\n\n if (typeof connect !== 'function') {\n connect = buildConnector({\n ...tls,\n maxCachedSessions,\n allowH2,\n socketPath,\n timeout: connectTimeout,\n ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),\n ...connect\n })\n }\n\n this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)\n ? interceptors.Client\n : [createRedirectInterceptor({ maxRedirections })]\n this[kUrl] = util.parseOrigin(url)\n this[kConnector] = connect\n this[kSocket] = null\n this[kPipelining] = pipelining != null ? pipelining : 1\n this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize\n this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout\n this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout\n this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold\n this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]\n this[kServerName] = null\n this[kLocalAddress] = localAddress != null ? localAddress : null\n this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming\n this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming\n this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\\r\\n`\n this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3\n this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3\n this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength\n this[kMaxRedirections] = maxRedirections\n this[kMaxRequests] = maxRequestsPerClient\n this[kClosedResolve] = null\n this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1\n this[kHTTPConnVersion] = 'h1'\n\n // HTTP/2\n this[kHTTP2Session] = null\n this[kHTTP2SessionState] = !allowH2\n ? null\n : {\n // streams: null, // Fixed queue of streams - For future support of `push`\n openStreams: 0, // Keep track of them to decide wether or not unref the session\n maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server\n }\n this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`\n\n // kQueue is built up of 3 sections separated by\n // the kRunningIdx and kPendingIdx indices.\n // | complete | running | pending |\n // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length\n // kRunningIdx points to the first running element.\n // kPendingIdx points to the first pending element.\n // This implements a fast queue with an amortized\n // time of O(1).\n\n this[kQueue] = []\n this[kRunningIdx] = 0\n this[kPendingIdx] = 0\n }\n\n get pipelining () {\n return this[kPipelining]\n }\n\n set pipelining (value) {\n this[kPipelining] = value\n resume(this, true)\n }\n\n get [kPending] () {\n return this[kQueue].length - this[kPendingIdx]\n }\n\n get [kRunning] () {\n return this[kPendingIdx] - this[kRunningIdx]\n }\n\n get [kSize] () {\n return this[kQueue].length - this[kRunningIdx]\n }\n\n get [kConnected] () {\n return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed\n }\n\n get [kBusy] () {\n const socket = this[kSocket]\n return (\n (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||\n (this[kSize] >= (this[kPipelining] || 1)) ||\n this[kPending] > 0\n )\n }\n\n /* istanbul ignore: only used for test */\n [kConnect] (cb) {\n connect(this)\n this.once('connect', cb)\n }\n\n [kDispatch] (opts, handler) {\n const origin = opts.origin || this[kUrl].origin\n\n const request = this[kHTTPConnVersion] === 'h2'\n ? Request[kHTTP2BuildRequest](origin, opts, handler)\n : Request[kHTTP1BuildRequest](origin, opts, handler)\n\n this[kQueue].push(request)\n if (this[kResuming]) {\n // Do nothing.\n } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {\n // Wait a tick in case stream/iterator is ended in the same tick.\n this[kResuming] = 1\n process.nextTick(resume, this)\n } else {\n resume(this, true)\n }\n\n if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {\n this[kNeedDrain] = 2\n }\n\n return this[kNeedDrain] < 2\n }\n\n async [kClose] () {\n // TODO: for H2 we need to gracefully flush the remaining enqueued\n // request and close each stream.\n return new Promise((resolve) => {\n if (!this[kSize]) {\n resolve(null)\n } else {\n this[kClosedResolve] = resolve\n }\n })\n }\n\n async [kDestroy] (err) {\n return new Promise((resolve) => {\n const requests = this[kQueue].splice(this[kPendingIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(this, request, err)\n }\n\n const callback = () => {\n if (this[kClosedResolve]) {\n // TODO (fix): Should we error here with ClientDestroyedError?\n this[kClosedResolve]()\n this[kClosedResolve] = null\n }\n resolve()\n }\n\n if (this[kHTTP2Session] != null) {\n util.destroy(this[kHTTP2Session], err)\n this[kHTTP2Session] = null\n this[kHTTP2SessionState] = null\n }\n\n if (!this[kSocket]) {\n queueMicrotask(callback)\n } else {\n util.destroy(this[kSocket].on('close', callback), err)\n }\n\n resume(this)\n })\n }\n}\n\nfunction onHttp2SessionError (err) {\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n this[kSocket][kError] = err\n\n onError(this[kClient], err)\n}\n\nfunction onHttp2FrameError (type, code, id) {\n const err = new InformationalError(`HTTP/2: \"frameError\" received - type ${type}, code ${code}`)\n\n if (id === 0) {\n this[kSocket][kError] = err\n onError(this[kClient], err)\n }\n}\n\nfunction onHttp2SessionEnd () {\n util.destroy(this, new SocketError('other side closed'))\n util.destroy(this[kSocket], new SocketError('other side closed'))\n}\n\nfunction onHTTP2GoAway (code) {\n const client = this[kClient]\n const err = new InformationalError(`HTTP/2: \"GOAWAY\" frame received with code ${code}`)\n client[kSocket] = null\n client[kHTTP2Session] = null\n\n if (client.destroyed) {\n assert(this[kPending] === 0)\n\n // Fail entire queue.\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(this, request, err)\n }\n } else if (client[kRunning] > 0) {\n // Fail head of pipeline.\n const request = client[kQueue][client[kRunningIdx]]\n client[kQueue][client[kRunningIdx]++] = null\n\n errorRequest(client, request, err)\n }\n\n client[kPendingIdx] = client[kRunningIdx]\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect',\n client[kUrl],\n [client],\n err\n )\n\n resume(client)\n}\n\nconst constants = require('./llhttp/constants')\nconst createRedirectInterceptor = require('./interceptor/redirectInterceptor')\nconst EMPTY_BUF = Buffer.alloc(0)\n\nasync function lazyllhttp () {\n const llhttpWasmData = process.env.JEST_WORKER_ID ? require('./llhttp/llhttp-wasm.js') : undefined\n\n let mod\n try {\n mod = await WebAssembly.compile(Buffer.from(require('./llhttp/llhttp_simd-wasm.js'), 'base64'))\n } catch (e) {\n /* istanbul ignore next */\n\n // We could check if the error was caused by the simd option not\n // being enabled, but the occurring of this other error\n // * https://github.com/emscripten-core/emscripten/issues/11495\n // got me to remove that check to avoid breaking Node 12.\n mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || require('./llhttp/llhttp-wasm.js'), 'base64'))\n }\n\n return await WebAssembly.instantiate(mod, {\n env: {\n /* eslint-disable camelcase */\n\n wasm_on_url: (p, at, len) => {\n /* istanbul ignore next */\n return 0\n },\n wasm_on_status: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_message_begin: (p) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onMessageBegin() || 0\n },\n wasm_on_header_field: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_header_value: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0\n },\n wasm_on_body: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_message_complete: (p) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onMessageComplete() || 0\n }\n\n /* eslint-enable camelcase */\n }\n })\n}\n\nlet llhttpInstance = null\nlet llhttpPromise = lazyllhttp()\nllhttpPromise.catch()\n\nlet currentParser = null\nlet currentBufferRef = null\nlet currentBufferSize = 0\nlet currentBufferPtr = null\n\nconst TIMEOUT_HEADERS = 1\nconst TIMEOUT_BODY = 2\nconst TIMEOUT_IDLE = 3\n\nclass Parser {\n constructor (client, socket, { exports }) {\n assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)\n\n this.llhttp = exports\n this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)\n this.client = client\n this.socket = socket\n this.timeout = null\n this.timeoutValue = null\n this.timeoutType = null\n this.statusCode = null\n this.statusText = ''\n this.upgrade = false\n this.headers = []\n this.headersSize = 0\n this.headersMaxSize = client[kMaxHeadersSize]\n this.shouldKeepAlive = false\n this.paused = false\n this.resume = this.resume.bind(this)\n\n this.bytesRead = 0\n\n this.keepAlive = ''\n this.contentLength = ''\n this.connection = ''\n this.maxResponseSize = client[kMaxResponseSize]\n }\n\n setTimeout (value, type) {\n this.timeoutType = type\n if (value !== this.timeoutValue) {\n timers.clearTimeout(this.timeout)\n if (value) {\n this.timeout = timers.setTimeout(onParserTimeout, value, this)\n // istanbul ignore else: only for jest\n if (this.timeout.unref) {\n this.timeout.unref()\n }\n } else {\n this.timeout = null\n }\n this.timeoutValue = value\n } else if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n }\n\n resume () {\n if (this.socket.destroyed || !this.paused) {\n return\n }\n\n assert(this.ptr != null)\n assert(currentParser == null)\n\n this.llhttp.llhttp_resume(this.ptr)\n\n assert(this.timeoutType === TIMEOUT_BODY)\n if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n this.paused = false\n this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.\n this.readMore()\n }\n\n readMore () {\n while (!this.paused && this.ptr) {\n const chunk = this.socket.read()\n if (chunk === null) {\n break\n }\n this.execute(chunk)\n }\n }\n\n execute (data) {\n assert(this.ptr != null)\n assert(currentParser == null)\n assert(!this.paused)\n\n const { socket, llhttp } = this\n\n if (data.length > currentBufferSize) {\n if (currentBufferPtr) {\n llhttp.free(currentBufferPtr)\n }\n currentBufferSize = Math.ceil(data.length / 4096) * 4096\n currentBufferPtr = llhttp.malloc(currentBufferSize)\n }\n\n new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)\n\n // Call `execute` on the wasm parser.\n // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,\n // and finally the length of bytes to parse.\n // The return value is an error code or `constants.ERROR.OK`.\n try {\n let ret\n\n try {\n currentBufferRef = data\n currentParser = this\n ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)\n /* eslint-disable-next-line no-useless-catch */\n } catch (err) {\n /* istanbul ignore next: difficult to make a test case for */\n throw err\n } finally {\n currentParser = null\n currentBufferRef = null\n }\n\n const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr\n\n if (ret === constants.ERROR.PAUSED_UPGRADE) {\n this.onUpgrade(data.slice(offset))\n } else if (ret === constants.ERROR.PAUSED) {\n this.paused = true\n socket.unshift(data.slice(offset))\n } else if (ret !== constants.ERROR.OK) {\n const ptr = llhttp.llhttp_get_error_reason(this.ptr)\n let message = ''\n /* istanbul ignore else: difficult to make a test case for */\n if (ptr) {\n const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)\n message =\n 'Response does not match the HTTP/1.1 protocol (' +\n Buffer.from(llhttp.memory.buffer, ptr, len).toString() +\n ')'\n }\n throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))\n }\n } catch (err) {\n util.destroy(socket, err)\n }\n }\n\n destroy () {\n assert(this.ptr != null)\n assert(currentParser == null)\n\n this.llhttp.llhttp_free(this.ptr)\n this.ptr = null\n\n timers.clearTimeout(this.timeout)\n this.timeout = null\n this.timeoutValue = null\n this.timeoutType = null\n\n this.paused = false\n }\n\n onStatus (buf) {\n this.statusText = buf.toString()\n }\n\n onMessageBegin () {\n const { socket, client } = this\n\n /* istanbul ignore next: difficult to make a test case for */\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n if (!request) {\n return -1\n }\n }\n\n onHeaderField (buf) {\n const len = this.headers.length\n\n if ((len & 1) === 0) {\n this.headers.push(buf)\n } else {\n this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])\n }\n\n this.trackHeader(buf.length)\n }\n\n onHeaderValue (buf) {\n let len = this.headers.length\n\n if ((len & 1) === 1) {\n this.headers.push(buf)\n len += 1\n } else {\n this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])\n }\n\n const key = this.headers[len - 2]\n if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {\n this.keepAlive += buf.toString()\n } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {\n this.connection += buf.toString()\n } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {\n this.contentLength += buf.toString()\n }\n\n this.trackHeader(buf.length)\n }\n\n trackHeader (len) {\n this.headersSize += len\n if (this.headersSize >= this.headersMaxSize) {\n util.destroy(this.socket, new HeadersOverflowError())\n }\n }\n\n onUpgrade (head) {\n const { upgrade, client, socket, headers, statusCode } = this\n\n assert(upgrade)\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert(!socket.destroyed)\n assert(socket === client[kSocket])\n assert(!this.paused)\n assert(request.upgrade || request.method === 'CONNECT')\n\n this.statusCode = null\n this.statusText = ''\n this.shouldKeepAlive = null\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n socket.unshift(head)\n\n socket[kParser].destroy()\n socket[kParser] = null\n\n socket[kClient] = null\n socket[kError] = null\n socket\n .removeListener('error', onSocketError)\n .removeListener('readable', onSocketReadable)\n .removeListener('end', onSocketEnd)\n .removeListener('close', onSocketClose)\n\n client[kSocket] = null\n client[kQueue][client[kRunningIdx]++] = null\n client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))\n\n try {\n request.onUpgrade(statusCode, headers, socket)\n } catch (err) {\n util.destroy(socket, err)\n }\n\n resume(client)\n }\n\n onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {\n const { client, socket, headers, statusText } = this\n\n /* istanbul ignore next: difficult to make a test case for */\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n\n /* istanbul ignore next: difficult to make a test case for */\n if (!request) {\n return -1\n }\n\n assert(!this.upgrade)\n assert(this.statusCode < 200)\n\n if (statusCode === 100) {\n util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))\n return -1\n }\n\n /* this can only happen if server is misbehaving */\n if (upgrade && !request.upgrade) {\n util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))\n return -1\n }\n\n assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)\n\n this.statusCode = statusCode\n this.shouldKeepAlive = (\n shouldKeepAlive ||\n // Override llhttp value which does not allow keepAlive for HEAD.\n (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')\n )\n\n if (this.statusCode >= 200) {\n const bodyTimeout = request.bodyTimeout != null\n ? request.bodyTimeout\n : client[kBodyTimeout]\n this.setTimeout(bodyTimeout, TIMEOUT_BODY)\n } else if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n if (request.method === 'CONNECT') {\n assert(client[kRunning] === 1)\n this.upgrade = true\n return 2\n }\n\n if (upgrade) {\n assert(client[kRunning] === 1)\n this.upgrade = true\n return 2\n }\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n if (this.shouldKeepAlive && client[kPipelining]) {\n const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null\n\n if (keepAliveTimeout != null) {\n const timeout = Math.min(\n keepAliveTimeout - client[kKeepAliveTimeoutThreshold],\n client[kKeepAliveMaxTimeout]\n )\n if (timeout <= 0) {\n socket[kReset] = true\n } else {\n client[kKeepAliveTimeoutValue] = timeout\n }\n } else {\n client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]\n }\n } else {\n // Stop more requests from being dispatched.\n socket[kReset] = true\n }\n\n const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false\n\n if (request.aborted) {\n return -1\n }\n\n if (request.method === 'HEAD') {\n return 1\n }\n\n if (statusCode < 200) {\n return 1\n }\n\n if (socket[kBlocking]) {\n socket[kBlocking] = false\n resume(client)\n }\n\n return pause ? constants.ERROR.PAUSED : 0\n }\n\n onBody (buf) {\n const { client, socket, statusCode, maxResponseSize } = this\n\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert.strictEqual(this.timeoutType, TIMEOUT_BODY)\n if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n assert(statusCode >= 200)\n\n if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {\n util.destroy(socket, new ResponseExceededMaxSizeError())\n return -1\n }\n\n this.bytesRead += buf.length\n\n if (request.onData(buf) === false) {\n return constants.ERROR.PAUSED\n }\n }\n\n onMessageComplete () {\n const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this\n\n if (socket.destroyed && (!statusCode || shouldKeepAlive)) {\n return -1\n }\n\n if (upgrade) {\n return\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert(statusCode >= 100)\n\n this.statusCode = null\n this.statusText = ''\n this.bytesRead = 0\n this.contentLength = ''\n this.keepAlive = ''\n this.connection = ''\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n if (statusCode < 200) {\n return\n }\n\n /* istanbul ignore next: should be handled by llhttp? */\n if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {\n util.destroy(socket, new ResponseContentLengthMismatchError())\n return -1\n }\n\n request.onComplete(headers)\n\n client[kQueue][client[kRunningIdx]++] = null\n\n if (socket[kWriting]) {\n assert.strictEqual(client[kRunning], 0)\n // Response completed before request.\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (!shouldKeepAlive) {\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (socket[kReset] && client[kRunning] === 0) {\n // Destroy socket once all requests have completed.\n // The request at the tail of the pipeline is the one\n // that requested reset and no further requests should\n // have been queued since then.\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (client[kPipelining] === 1) {\n // We must wait a full event loop cycle to reuse this socket to make sure\n // that non-spec compliant servers are not closing the connection even if they\n // said they won't.\n setImmediate(resume, client)\n } else {\n resume(client)\n }\n }\n}\n\nfunction onParserTimeout (parser) {\n const { socket, timeoutType, client } = parser\n\n /* istanbul ignore else */\n if (timeoutType === TIMEOUT_HEADERS) {\n if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {\n assert(!parser.paused, 'cannot be paused while waiting for headers')\n util.destroy(socket, new HeadersTimeoutError())\n }\n } else if (timeoutType === TIMEOUT_BODY) {\n if (!parser.paused) {\n util.destroy(socket, new BodyTimeoutError())\n }\n } else if (timeoutType === TIMEOUT_IDLE) {\n assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])\n util.destroy(socket, new InformationalError('socket idle timeout'))\n }\n}\n\nfunction onSocketReadable () {\n const { [kParser]: parser } = this\n if (parser) {\n parser.readMore()\n }\n}\n\nfunction onSocketError (err) {\n const { [kClient]: client, [kParser]: parser } = this\n\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n if (client[kHTTPConnVersion] !== 'h2') {\n // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded\n // to the user.\n if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so for as a valid response.\n parser.onMessageComplete()\n return\n }\n }\n\n this[kError] = err\n\n onError(this[kClient], err)\n}\n\nfunction onError (client, err) {\n if (\n client[kRunning] === 0 &&\n err.code !== 'UND_ERR_INFO' &&\n err.code !== 'UND_ERR_SOCKET'\n ) {\n // Error is not caused by running request and not a recoverable\n // socket error.\n\n assert(client[kPendingIdx] === client[kRunningIdx])\n\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(client, request, err)\n }\n assert(client[kSize] === 0)\n }\n}\n\nfunction onSocketEnd () {\n const { [kParser]: parser, [kClient]: client } = this\n\n if (client[kHTTPConnVersion] !== 'h2') {\n if (parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so far as a valid response.\n parser.onMessageComplete()\n return\n }\n }\n\n util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))\n}\n\nfunction onSocketClose () {\n const { [kClient]: client, [kParser]: parser } = this\n\n if (client[kHTTPConnVersion] === 'h1' && parser) {\n if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so far as a valid response.\n parser.onMessageComplete()\n }\n\n this[kParser].destroy()\n this[kParser] = null\n }\n\n const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))\n\n client[kSocket] = null\n\n if (client.destroyed) {\n assert(client[kPending] === 0)\n\n // Fail entire queue.\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(client, request, err)\n }\n } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {\n // Fail head of pipeline.\n const request = client[kQueue][client[kRunningIdx]]\n client[kQueue][client[kRunningIdx]++] = null\n\n errorRequest(client, request, err)\n }\n\n client[kPendingIdx] = client[kRunningIdx]\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect', client[kUrl], [client], err)\n\n resume(client)\n}\n\nasync function connect (client) {\n assert(!client[kConnecting])\n assert(!client[kSocket])\n\n let { host, hostname, protocol, port } = client[kUrl]\n\n // Resolve ipv6\n if (hostname[0] === '[') {\n const idx = hostname.indexOf(']')\n\n assert(idx !== -1)\n const ip = hostname.substring(1, idx)\n\n assert(net.isIP(ip))\n hostname = ip\n }\n\n client[kConnecting] = true\n\n if (channels.beforeConnect.hasSubscribers) {\n channels.beforeConnect.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector]\n })\n }\n\n try {\n const socket = await new Promise((resolve, reject) => {\n client[kConnector]({\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n }, (err, socket) => {\n if (err) {\n reject(err)\n } else {\n resolve(socket)\n }\n })\n })\n\n if (client.destroyed) {\n util.destroy(socket.on('error', () => {}), new ClientDestroyedError())\n return\n }\n\n client[kConnecting] = false\n\n assert(socket)\n\n const isH2 = socket.alpnProtocol === 'h2'\n if (isH2) {\n if (!h2ExperimentalWarned) {\n h2ExperimentalWarned = true\n process.emitWarning('H2 support is experimental, expect them to change at any time.', {\n code: 'UNDICI-H2'\n })\n }\n\n const session = http2.connect(client[kUrl], {\n createConnection: () => socket,\n peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams\n })\n\n client[kHTTPConnVersion] = 'h2'\n session[kClient] = client\n session[kSocket] = socket\n session.on('error', onHttp2SessionError)\n session.on('frameError', onHttp2FrameError)\n session.on('end', onHttp2SessionEnd)\n session.on('goaway', onHTTP2GoAway)\n session.on('close', onSocketClose)\n session.unref()\n\n client[kHTTP2Session] = session\n socket[kHTTP2Session] = session\n } else {\n if (!llhttpInstance) {\n llhttpInstance = await llhttpPromise\n llhttpPromise = null\n }\n\n socket[kNoRef] = false\n socket[kWriting] = false\n socket[kReset] = false\n socket[kBlocking] = false\n socket[kParser] = new Parser(client, socket, llhttpInstance)\n }\n\n socket[kCounter] = 0\n socket[kMaxRequests] = client[kMaxRequests]\n socket[kClient] = client\n socket[kError] = null\n\n socket\n .on('error', onSocketError)\n .on('readable', onSocketReadable)\n .on('end', onSocketEnd)\n .on('close', onSocketClose)\n\n client[kSocket] = socket\n\n if (channels.connected.hasSubscribers) {\n channels.connected.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector],\n socket\n })\n }\n client.emit('connect', client[kUrl], [client])\n } catch (err) {\n if (client.destroyed) {\n return\n }\n\n client[kConnecting] = false\n\n if (channels.connectError.hasSubscribers) {\n channels.connectError.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector],\n error: err\n })\n }\n\n if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {\n assert(client[kRunning] === 0)\n while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {\n const request = client[kQueue][client[kPendingIdx]++]\n errorRequest(client, request, err)\n }\n } else {\n onError(client, err)\n }\n\n client.emit('connectionError', client[kUrl], [client], err)\n }\n\n resume(client)\n}\n\nfunction emitDrain (client) {\n client[kNeedDrain] = 0\n client.emit('drain', client[kUrl], [client])\n}\n\nfunction resume (client, sync) {\n if (client[kResuming] === 2) {\n return\n }\n\n client[kResuming] = 2\n\n _resume(client, sync)\n client[kResuming] = 0\n\n if (client[kRunningIdx] > 256) {\n client[kQueue].splice(0, client[kRunningIdx])\n client[kPendingIdx] -= client[kRunningIdx]\n client[kRunningIdx] = 0\n }\n}\n\nfunction _resume (client, sync) {\n while (true) {\n if (client.destroyed) {\n assert(client[kPending] === 0)\n return\n }\n\n if (client[kClosedResolve] && !client[kSize]) {\n client[kClosedResolve]()\n client[kClosedResolve] = null\n return\n }\n\n const socket = client[kSocket]\n\n if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {\n if (client[kSize] === 0) {\n if (!socket[kNoRef] && socket.unref) {\n socket.unref()\n socket[kNoRef] = true\n }\n } else if (socket[kNoRef] && socket.ref) {\n socket.ref()\n socket[kNoRef] = false\n }\n\n if (client[kSize] === 0) {\n if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {\n socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)\n }\n } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {\n if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {\n const request = client[kQueue][client[kRunningIdx]]\n const headersTimeout = request.headersTimeout != null\n ? request.headersTimeout\n : client[kHeadersTimeout]\n socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)\n }\n }\n }\n\n if (client[kBusy]) {\n client[kNeedDrain] = 2\n } else if (client[kNeedDrain] === 2) {\n if (sync) {\n client[kNeedDrain] = 1\n process.nextTick(emitDrain, client)\n } else {\n emitDrain(client)\n }\n continue\n }\n\n if (client[kPending] === 0) {\n return\n }\n\n if (client[kRunning] >= (client[kPipelining] || 1)) {\n return\n }\n\n const request = client[kQueue][client[kPendingIdx]]\n\n if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {\n if (client[kRunning] > 0) {\n return\n }\n\n client[kServerName] = request.servername\n\n if (socket && socket.servername !== request.servername) {\n util.destroy(socket, new InformationalError('servername changed'))\n return\n }\n }\n\n if (client[kConnecting]) {\n return\n }\n\n if (!socket && !client[kHTTP2Session]) {\n connect(client)\n return\n }\n\n if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {\n return\n }\n\n if (client[kRunning] > 0 && !request.idempotent) {\n // Non-idempotent request cannot be retried.\n // Ensure that no other requests are inflight and\n // could cause failure.\n return\n }\n\n if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {\n // Don't dispatch an upgrade until all preceding requests have completed.\n // A misbehaving server might upgrade the connection before all pipelined\n // request has completed.\n return\n }\n\n if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&\n (util.isStream(request.body) || util.isAsyncIterable(request.body))) {\n // Request with stream or iterator body can error while other requests\n // are inflight and indirectly error those as well.\n // Ensure this doesn't happen by waiting for inflight\n // to complete before dispatching.\n\n // Request with stream or iterator body cannot be retried.\n // Ensure that no other requests are inflight and\n // could cause failure.\n return\n }\n\n if (!request.aborted && write(client, request)) {\n client[kPendingIdx]++\n } else {\n client[kQueue].splice(client[kPendingIdx], 1)\n }\n }\n}\n\n// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2\nfunction shouldSendContentLength (method) {\n return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'\n}\n\nfunction write (client, request) {\n if (client[kHTTPConnVersion] === 'h2') {\n writeH2(client, client[kHTTP2Session], request)\n return\n }\n\n const { body, method, path, host, upgrade, headers, blocking, reset } = request\n\n // https://tools.ietf.org/html/rfc7231#section-4.3.1\n // https://tools.ietf.org/html/rfc7231#section-4.3.2\n // https://tools.ietf.org/html/rfc7231#section-4.3.5\n\n // Sending a payload body on a request that does not\n // expect it can cause undefined behavior on some\n // servers and corrupt connection state. Do not\n // re-use the connection for further requests.\n\n const expectsPayload = (\n method === 'PUT' ||\n method === 'POST' ||\n method === 'PATCH'\n )\n\n if (body && typeof body.read === 'function') {\n // Try to read EOF in order to get length.\n body.read(0)\n }\n\n const bodyLength = util.bodyLength(body)\n\n let contentLength = bodyLength\n\n if (contentLength === null) {\n contentLength = request.contentLength\n }\n\n if (contentLength === 0 && !expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD NOT send a Content-Length header field when\n // the request message does not contain a payload body and the method\n // semantics do not anticipate such a body.\n\n contentLength = null\n }\n\n // https://github.com/nodejs/undici/issues/2046\n // A user agent may send a Content-Length header with 0 value, this should be allowed.\n if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {\n if (client[kStrictContentLength]) {\n errorRequest(client, request, new RequestContentLengthMismatchError())\n return false\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n const socket = client[kSocket]\n\n try {\n request.onConnect((err) => {\n if (request.aborted || request.completed) {\n return\n }\n\n errorRequest(client, request, err || new RequestAbortedError())\n\n util.destroy(socket, new InformationalError('aborted'))\n })\n } catch (err) {\n errorRequest(client, request, err)\n }\n\n if (request.aborted) {\n return false\n }\n\n if (method === 'HEAD') {\n // https://github.com/mcollina/undici/issues/258\n // Close after a HEAD request to interop with misbehaving servers\n // that may send a body in the response.\n\n socket[kReset] = true\n }\n\n if (upgrade || method === 'CONNECT') {\n // On CONNECT or upgrade, block pipeline from dispatching further\n // requests on this connection.\n\n socket[kReset] = true\n }\n\n if (reset != null) {\n socket[kReset] = reset\n }\n\n if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {\n socket[kReset] = true\n }\n\n if (blocking) {\n socket[kBlocking] = true\n }\n\n let header = `${method} ${path} HTTP/1.1\\r\\n`\n\n if (typeof host === 'string') {\n header += `host: ${host}\\r\\n`\n } else {\n header += client[kHostHeader]\n }\n\n if (upgrade) {\n header += `connection: upgrade\\r\\nupgrade: ${upgrade}\\r\\n`\n } else if (client[kPipelining] && !socket[kReset]) {\n header += 'connection: keep-alive\\r\\n'\n } else {\n header += 'connection: close\\r\\n'\n }\n\n if (headers) {\n header += headers\n }\n\n if (channels.sendHeaders.hasSubscribers) {\n channels.sendHeaders.publish({ request, headers: header, socket })\n }\n\n /* istanbul ignore else: assertion */\n if (!body || bodyLength === 0) {\n if (contentLength === 0) {\n socket.write(`${header}content-length: 0\\r\\n\\r\\n`, 'latin1')\n } else {\n assert(contentLength === null, 'no body must not have content length')\n socket.write(`${header}\\r\\n`, 'latin1')\n }\n request.onRequestSent()\n } else if (util.isBuffer(body)) {\n assert(contentLength === body.byteLength, 'buffer body must have content length')\n\n socket.cork()\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n socket.write(body)\n socket.uncork()\n request.onBodySent(body)\n request.onRequestSent()\n if (!expectsPayload) {\n socket[kReset] = true\n }\n } else if (util.isBlobLike(body)) {\n if (typeof body.stream === 'function') {\n writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })\n } else {\n writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })\n }\n } else if (util.isStream(body)) {\n writeStream({ body, client, request, socket, contentLength, header, expectsPayload })\n } else if (util.isIterable(body)) {\n writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })\n } else {\n assert(false)\n }\n\n return true\n}\n\nfunction writeH2 (client, session, request) {\n const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request\n\n let headers\n if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())\n else headers = reqHeaders\n\n if (upgrade) {\n errorRequest(client, request, new Error('Upgrade not supported for H2'))\n return false\n }\n\n try {\n // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?\n request.onConnect((err) => {\n if (request.aborted || request.completed) {\n return\n }\n\n errorRequest(client, request, err || new RequestAbortedError())\n })\n } catch (err) {\n errorRequest(client, request, err)\n }\n\n if (request.aborted) {\n return false\n }\n\n /** @type {import('node:http2').ClientHttp2Stream} */\n let stream\n const h2State = client[kHTTP2SessionState]\n\n headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]\n headers[HTTP2_HEADER_METHOD] = method\n\n if (method === 'CONNECT') {\n session.ref()\n // we are already connected, streams are pending, first request\n // will create a new stream. We trigger a request to create the stream and wait until\n // `ready` event is triggered\n // We disabled endStream to allow the user to write to the stream\n stream = session.request(headers, { endStream: false, signal })\n\n if (stream.id && !stream.pending) {\n request.onUpgrade(null, null, stream)\n ++h2State.openStreams\n } else {\n stream.once('ready', () => {\n request.onUpgrade(null, null, stream)\n ++h2State.openStreams\n })\n }\n\n stream.once('close', () => {\n h2State.openStreams -= 1\n // TODO(HTTP/2): unref only if current streams count is 0\n if (h2State.openStreams === 0) session.unref()\n })\n\n return true\n }\n\n // https://tools.ietf.org/html/rfc7540#section-8.3\n // :path and :scheme headers must be omited when sending CONNECT\n\n headers[HTTP2_HEADER_PATH] = path\n headers[HTTP2_HEADER_SCHEME] = 'https'\n\n // https://tools.ietf.org/html/rfc7231#section-4.3.1\n // https://tools.ietf.org/html/rfc7231#section-4.3.2\n // https://tools.ietf.org/html/rfc7231#section-4.3.5\n\n // Sending a payload body on a request that does not\n // expect it can cause undefined behavior on some\n // servers and corrupt connection state. Do not\n // re-use the connection for further requests.\n\n const expectsPayload = (\n method === 'PUT' ||\n method === 'POST' ||\n method === 'PATCH'\n )\n\n if (body && typeof body.read === 'function') {\n // Try to read EOF in order to get length.\n body.read(0)\n }\n\n let contentLength = util.bodyLength(body)\n\n if (contentLength == null) {\n contentLength = request.contentLength\n }\n\n if (contentLength === 0 || !expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD NOT send a Content-Length header field when\n // the request message does not contain a payload body and the method\n // semantics do not anticipate such a body.\n\n contentLength = null\n }\n\n // https://github.com/nodejs/undici/issues/2046\n // A user agent may send a Content-Length header with 0 value, this should be allowed.\n if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {\n if (client[kStrictContentLength]) {\n errorRequest(client, request, new RequestContentLengthMismatchError())\n return false\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n if (contentLength != null) {\n assert(body, 'no body must not have content length')\n headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`\n }\n\n session.ref()\n\n const shouldEndStream = method === 'GET' || method === 'HEAD'\n if (expectContinue) {\n headers[HTTP2_HEADER_EXPECT] = '100-continue'\n stream = session.request(headers, { endStream: shouldEndStream, signal })\n\n stream.once('continue', writeBodyH2)\n } else {\n stream = session.request(headers, {\n endStream: shouldEndStream,\n signal\n })\n writeBodyH2()\n }\n\n // Increment counter as we have new several streams open\n ++h2State.openStreams\n\n stream.once('response', headers => {\n const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers\n\n if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {\n stream.pause()\n }\n })\n\n stream.once('end', () => {\n request.onComplete([])\n })\n\n stream.on('data', (chunk) => {\n if (request.onData(chunk) === false) {\n stream.pause()\n }\n })\n\n stream.once('close', () => {\n h2State.openStreams -= 1\n // TODO(HTTP/2): unref only if current streams count is 0\n if (h2State.openStreams === 0) {\n session.unref()\n }\n })\n\n stream.once('error', function (err) {\n if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {\n h2State.streams -= 1\n util.destroy(stream, err)\n }\n })\n\n stream.once('frameError', (type, code) => {\n const err = new InformationalError(`HTTP/2: \"frameError\" received - type ${type}, code ${code}`)\n errorRequest(client, request, err)\n\n if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {\n h2State.streams -= 1\n util.destroy(stream, err)\n }\n })\n\n // stream.on('aborted', () => {\n // // TODO(HTTP/2): Support aborted\n // })\n\n // stream.on('timeout', () => {\n // // TODO(HTTP/2): Support timeout\n // })\n\n // stream.on('push', headers => {\n // // TODO(HTTP/2): Suppor push\n // })\n\n // stream.on('trailers', headers => {\n // // TODO(HTTP/2): Support trailers\n // })\n\n return true\n\n function writeBodyH2 () {\n /* istanbul ignore else: assertion */\n if (!body) {\n request.onRequestSent()\n } else if (util.isBuffer(body)) {\n assert(contentLength === body.byteLength, 'buffer body must have content length')\n stream.cork()\n stream.write(body)\n stream.uncork()\n stream.end()\n request.onBodySent(body)\n request.onRequestSent()\n } else if (util.isBlobLike(body)) {\n if (typeof body.stream === 'function') {\n writeIterable({\n client,\n request,\n contentLength,\n h2stream: stream,\n expectsPayload,\n body: body.stream(),\n socket: client[kSocket],\n header: ''\n })\n } else {\n writeBlob({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n h2stream: stream,\n header: '',\n socket: client[kSocket]\n })\n }\n } else if (util.isStream(body)) {\n writeStream({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n socket: client[kSocket],\n h2stream: stream,\n header: ''\n })\n } else if (util.isIterable(body)) {\n writeIterable({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n header: '',\n h2stream: stream,\n socket: client[kSocket]\n })\n } else {\n assert(false)\n }\n }\n}\n\nfunction writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')\n\n if (client[kHTTPConnVersion] === 'h2') {\n // For HTTP/2, is enough to pipe the stream\n const pipe = pipeline(\n body,\n h2stream,\n (err) => {\n if (err) {\n util.destroy(body, err)\n util.destroy(h2stream, err)\n } else {\n request.onRequestSent()\n }\n }\n )\n\n pipe.on('data', onPipeData)\n pipe.once('end', () => {\n pipe.removeListener('data', onPipeData)\n util.destroy(pipe)\n })\n\n function onPipeData (chunk) {\n request.onBodySent(chunk)\n }\n\n return\n }\n\n let finished = false\n\n const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })\n\n const onData = function (chunk) {\n if (finished) {\n return\n }\n\n try {\n if (!writer.write(chunk) && this.pause) {\n this.pause()\n }\n } catch (err) {\n util.destroy(this, err)\n }\n }\n const onDrain = function () {\n if (finished) {\n return\n }\n\n if (body.resume) {\n body.resume()\n }\n }\n const onAbort = function () {\n if (finished) {\n return\n }\n const err = new RequestAbortedError()\n queueMicrotask(() => onFinished(err))\n }\n const onFinished = function (err) {\n if (finished) {\n return\n }\n\n finished = true\n\n assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))\n\n socket\n .off('drain', onDrain)\n .off('error', onFinished)\n\n body\n .removeListener('data', onData)\n .removeListener('end', onFinished)\n .removeListener('error', onFinished)\n .removeListener('close', onAbort)\n\n if (!err) {\n try {\n writer.end()\n } catch (er) {\n err = er\n }\n }\n\n writer.destroy(err)\n\n if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {\n util.destroy(body, err)\n } else {\n util.destroy(body)\n }\n }\n\n body\n .on('data', onData)\n .on('end', onFinished)\n .on('error', onFinished)\n .on('close', onAbort)\n\n if (body.resume) {\n body.resume()\n }\n\n socket\n .on('drain', onDrain)\n .on('error', onFinished)\n}\n\nasync function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength === body.size, 'blob body must have content length')\n\n const isH2 = client[kHTTPConnVersion] === 'h2'\n try {\n if (contentLength != null && contentLength !== body.size) {\n throw new RequestContentLengthMismatchError()\n }\n\n const buffer = Buffer.from(await body.arrayBuffer())\n\n if (isH2) {\n h2stream.cork()\n h2stream.write(buffer)\n h2stream.uncork()\n } else {\n socket.cork()\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n socket.write(buffer)\n socket.uncork()\n }\n\n request.onBodySent(buffer)\n request.onRequestSent()\n\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n resume(client)\n } catch (err) {\n util.destroy(isH2 ? h2stream : socket, err)\n }\n}\n\nasync function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')\n\n let callback = null\n function onDrain () {\n if (callback) {\n const cb = callback\n callback = null\n cb()\n }\n }\n\n const waitForDrain = () => new Promise((resolve, reject) => {\n assert(callback === null)\n\n if (socket[kError]) {\n reject(socket[kError])\n } else {\n callback = resolve\n }\n })\n\n if (client[kHTTPConnVersion] === 'h2') {\n h2stream\n .on('close', onDrain)\n .on('drain', onDrain)\n\n try {\n // It's up to the user to somehow abort the async iterable.\n for await (const chunk of body) {\n if (socket[kError]) {\n throw socket[kError]\n }\n\n const res = h2stream.write(chunk)\n request.onBodySent(chunk)\n if (!res) {\n await waitForDrain()\n }\n }\n } catch (err) {\n h2stream.destroy(err)\n } finally {\n request.onRequestSent()\n h2stream.end()\n h2stream\n .off('close', onDrain)\n .off('drain', onDrain)\n }\n\n return\n }\n\n socket\n .on('close', onDrain)\n .on('drain', onDrain)\n\n const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })\n try {\n // It's up to the user to somehow abort the async iterable.\n for await (const chunk of body) {\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (!writer.write(chunk)) {\n await waitForDrain()\n }\n }\n\n writer.end()\n } catch (err) {\n writer.destroy(err)\n } finally {\n socket\n .off('close', onDrain)\n .off('drain', onDrain)\n }\n}\n\nclass AsyncWriter {\n constructor ({ socket, request, contentLength, client, expectsPayload, header }) {\n this.socket = socket\n this.request = request\n this.contentLength = contentLength\n this.client = client\n this.bytesWritten = 0\n this.expectsPayload = expectsPayload\n this.header = header\n\n socket[kWriting] = true\n }\n\n write (chunk) {\n const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this\n\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (socket.destroyed) {\n return false\n }\n\n const len = Buffer.byteLength(chunk)\n if (!len) {\n return true\n }\n\n // We should defer writing chunks.\n if (contentLength !== null && bytesWritten + len > contentLength) {\n if (client[kStrictContentLength]) {\n throw new RequestContentLengthMismatchError()\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n socket.cork()\n\n if (bytesWritten === 0) {\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n if (contentLength === null) {\n socket.write(`${header}transfer-encoding: chunked\\r\\n`, 'latin1')\n } else {\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n }\n }\n\n if (contentLength === null) {\n socket.write(`\\r\\n${len.toString(16)}\\r\\n`, 'latin1')\n }\n\n this.bytesWritten += len\n\n const ret = socket.write(chunk)\n\n socket.uncork()\n\n request.onBodySent(chunk)\n\n if (!ret) {\n if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {\n // istanbul ignore else: only for jest\n if (socket[kParser].timeout.refresh) {\n socket[kParser].timeout.refresh()\n }\n }\n }\n\n return ret\n }\n\n end () {\n const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this\n request.onRequestSent()\n\n socket[kWriting] = false\n\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (socket.destroyed) {\n return\n }\n\n if (bytesWritten === 0) {\n if (expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD send a Content-Length in a request message when\n // no Transfer-Encoding is sent and the request method defines a meaning\n // for an enclosed payload body.\n\n socket.write(`${header}content-length: 0\\r\\n\\r\\n`, 'latin1')\n } else {\n socket.write(`${header}\\r\\n`, 'latin1')\n }\n } else if (contentLength === null) {\n socket.write('\\r\\n0\\r\\n\\r\\n', 'latin1')\n }\n\n if (contentLength !== null && bytesWritten !== contentLength) {\n if (client[kStrictContentLength]) {\n throw new RequestContentLengthMismatchError()\n } else {\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n }\n\n if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {\n // istanbul ignore else: only for jest\n if (socket[kParser].timeout.refresh) {\n socket[kParser].timeout.refresh()\n }\n }\n\n resume(client)\n }\n\n destroy (err) {\n const { socket, client } = this\n\n socket[kWriting] = false\n\n if (err) {\n assert(client[kRunning] <= 1, 'pipeline should only contain this request')\n util.destroy(socket, err)\n }\n }\n}\n\nfunction errorRequest (client, request, err) {\n try {\n request.onError(err)\n assert(request.aborted)\n } catch (err) {\n client.emit('error', err)\n }\n}\n\nmodule.exports = Client\n","'use strict'\n\n/* istanbul ignore file: only for Node 12 */\n\nconst { kConnected, kSize } = require('../core/symbols')\n\nclass CompatWeakRef {\n constructor (value) {\n this.value = value\n }\n\n deref () {\n return this.value[kConnected] === 0 && this.value[kSize] === 0\n ? undefined\n : this.value\n }\n}\n\nclass CompatFinalizer {\n constructor (finalizer) {\n this.finalizer = finalizer\n }\n\n register (dispatcher, key) {\n if (dispatcher.on) {\n dispatcher.on('disconnect', () => {\n if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {\n this.finalizer(key)\n }\n })\n }\n }\n}\n\nmodule.exports = function () {\n // FIXME: remove workaround when the Node bug is fixed\n // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308\n if (process.env.NODE_V8_COVERAGE) {\n return {\n WeakRef: CompatWeakRef,\n FinalizationRegistry: CompatFinalizer\n }\n }\n return {\n WeakRef: global.WeakRef || CompatWeakRef,\n FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer\n }\n}\n","'use strict'\n\n// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size\nconst maxAttributeValueSize = 1024\n\n// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size\nconst maxNameValuePairSize = 4096\n\nmodule.exports = {\n maxAttributeValueSize,\n maxNameValuePairSize\n}\n","'use strict'\n\nconst { parseSetCookie } = require('./parse')\nconst { stringify, getHeadersList } = require('./util')\nconst { webidl } = require('../fetch/webidl')\nconst { Headers } = require('../fetch/headers')\n\n/**\n * @typedef {Object} Cookie\n * @property {string} name\n * @property {string} value\n * @property {Date|number|undefined} expires\n * @property {number|undefined} maxAge\n * @property {string|undefined} domain\n * @property {string|undefined} path\n * @property {boolean|undefined} secure\n * @property {boolean|undefined} httpOnly\n * @property {'Strict'|'Lax'|'None'} sameSite\n * @property {string[]} unparsed\n */\n\n/**\n * @param {Headers} headers\n * @returns {Record}\n */\nfunction getCookies (headers) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const cookie = headers.get('cookie')\n const out = {}\n\n if (!cookie) {\n return out\n }\n\n for (const piece of cookie.split(';')) {\n const [name, ...value] = piece.split('=')\n\n out[name.trim()] = value.join('=')\n }\n\n return out\n}\n\n/**\n * @param {Headers} headers\n * @param {string} name\n * @param {{ path?: string, domain?: string }|undefined} attributes\n * @returns {void}\n */\nfunction deleteCookie (headers, name, attributes) {\n webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n name = webidl.converters.DOMString(name)\n attributes = webidl.converters.DeleteCookieAttributes(attributes)\n\n // Matches behavior of\n // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278\n setCookie(headers, {\n name,\n value: '',\n expires: new Date(0),\n ...attributes\n })\n}\n\n/**\n * @param {Headers} headers\n * @returns {Cookie[]}\n */\nfunction getSetCookies (headers) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const cookies = getHeadersList(headers).cookies\n\n if (!cookies) {\n return []\n }\n\n // In older versions of undici, cookies is a list of name:value.\n return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))\n}\n\n/**\n * @param {Headers} headers\n * @param {Cookie} cookie\n * @returns {void}\n */\nfunction setCookie (headers, cookie) {\n webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n cookie = webidl.converters.Cookie(cookie)\n\n const str = stringify(cookie)\n\n if (str) {\n headers.append('Set-Cookie', stringify(cookie))\n }\n}\n\nwebidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'path',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'domain',\n defaultValue: null\n }\n])\n\nwebidl.converters.Cookie = webidl.dictionaryConverter([\n {\n converter: webidl.converters.DOMString,\n key: 'name'\n },\n {\n converter: webidl.converters.DOMString,\n key: 'value'\n },\n {\n converter: webidl.nullableConverter((value) => {\n if (typeof value === 'number') {\n return webidl.converters['unsigned long long'](value)\n }\n\n return new Date(value)\n }),\n key: 'expires',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters['long long']),\n key: 'maxAge',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'domain',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'path',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.boolean),\n key: 'secure',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.boolean),\n key: 'httpOnly',\n defaultValue: null\n },\n {\n converter: webidl.converters.USVString,\n key: 'sameSite',\n allowedValues: ['Strict', 'Lax', 'None']\n },\n {\n converter: webidl.sequenceConverter(webidl.converters.DOMString),\n key: 'unparsed',\n defaultValue: []\n }\n])\n\nmodule.exports = {\n getCookies,\n deleteCookie,\n getSetCookies,\n setCookie\n}\n","'use strict'\n\nconst { maxNameValuePairSize, maxAttributeValueSize } = require('./constants')\nconst { isCTLExcludingHtab } = require('./util')\nconst { collectASequenceOfCodePointsFast } = require('../fetch/dataURL')\nconst assert = require('assert')\n\n/**\n * @description Parses the field-value attributes of a set-cookie header string.\n * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4\n * @param {string} header\n * @returns if the header is invalid, null will be returned\n */\nfunction parseSetCookie (header) {\n // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F\n // character (CTL characters excluding HTAB): Abort these steps and\n // ignore the set-cookie-string entirely.\n if (isCTLExcludingHtab(header)) {\n return null\n }\n\n let nameValuePair = ''\n let unparsedAttributes = ''\n let name = ''\n let value = ''\n\n // 2. If the set-cookie-string contains a %x3B (\";\") character:\n if (header.includes(';')) {\n // 1. The name-value-pair string consists of the characters up to,\n // but not including, the first %x3B (\";\"), and the unparsed-\n // attributes consist of the remainder of the set-cookie-string\n // (including the %x3B (\";\") in question).\n const position = { position: 0 }\n\n nameValuePair = collectASequenceOfCodePointsFast(';', header, position)\n unparsedAttributes = header.slice(position.position)\n } else {\n // Otherwise:\n\n // 1. The name-value-pair string consists of all the characters\n // contained in the set-cookie-string, and the unparsed-\n // attributes is the empty string.\n nameValuePair = header\n }\n\n // 3. If the name-value-pair string lacks a %x3D (\"=\") character, then\n // the name string is empty, and the value string is the value of\n // name-value-pair.\n if (!nameValuePair.includes('=')) {\n value = nameValuePair\n } else {\n // Otherwise, the name string consists of the characters up to, but\n // not including, the first %x3D (\"=\") character, and the (possibly\n // empty) value string consists of the characters after the first\n // %x3D (\"=\") character.\n const position = { position: 0 }\n name = collectASequenceOfCodePointsFast(\n '=',\n nameValuePair,\n position\n )\n value = nameValuePair.slice(position.position + 1)\n }\n\n // 4. Remove any leading or trailing WSP characters from the name\n // string and the value string.\n name = name.trim()\n value = value.trim()\n\n // 5. If the sum of the lengths of the name string and the value string\n // is more than 4096 octets, abort these steps and ignore the set-\n // cookie-string entirely.\n if (name.length + value.length > maxNameValuePairSize) {\n return null\n }\n\n // 6. The cookie-name is the name string, and the cookie-value is the\n // value string.\n return {\n name, value, ...parseUnparsedAttributes(unparsedAttributes)\n }\n}\n\n/**\n * Parses the remaining attributes of a set-cookie header\n * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4\n * @param {string} unparsedAttributes\n * @param {[Object.]={}} cookieAttributeList\n */\nfunction parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {\n // 1. If the unparsed-attributes string is empty, skip the rest of\n // these steps.\n if (unparsedAttributes.length === 0) {\n return cookieAttributeList\n }\n\n // 2. Discard the first character of the unparsed-attributes (which\n // will be a %x3B (\";\") character).\n assert(unparsedAttributes[0] === ';')\n unparsedAttributes = unparsedAttributes.slice(1)\n\n let cookieAv = ''\n\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n if (unparsedAttributes.includes(';')) {\n // 1. Consume the characters of the unparsed-attributes up to, but\n // not including, the first %x3B (\";\") character.\n cookieAv = collectASequenceOfCodePointsFast(\n ';',\n unparsedAttributes,\n { position: 0 }\n )\n unparsedAttributes = unparsedAttributes.slice(cookieAv.length)\n } else {\n // Otherwise:\n\n // 1. Consume the remainder of the unparsed-attributes.\n cookieAv = unparsedAttributes\n unparsedAttributes = ''\n }\n\n // Let the cookie-av string be the characters consumed in this step.\n\n let attributeName = ''\n let attributeValue = ''\n\n // 4. If the cookie-av string contains a %x3D (\"=\") character:\n if (cookieAv.includes('=')) {\n // 1. The (possibly empty) attribute-name string consists of the\n // characters up to, but not including, the first %x3D (\"=\")\n // character, and the (possibly empty) attribute-value string\n // consists of the characters after the first %x3D (\"=\")\n // character.\n const position = { position: 0 }\n\n attributeName = collectASequenceOfCodePointsFast(\n '=',\n cookieAv,\n position\n )\n attributeValue = cookieAv.slice(position.position + 1)\n } else {\n // Otherwise:\n\n // 1. The attribute-name string consists of the entire cookie-av\n // string, and the attribute-value string is empty.\n attributeName = cookieAv\n }\n\n // 5. Remove any leading or trailing WSP characters from the attribute-\n // name string and the attribute-value string.\n attributeName = attributeName.trim()\n attributeValue = attributeValue.trim()\n\n // 6. If the attribute-value is longer than 1024 octets, ignore the\n // cookie-av string and return to Step 1 of this algorithm.\n if (attributeValue.length > maxAttributeValueSize) {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 7. Process the attribute-name and attribute-value according to the\n // requirements in the following subsections. (Notice that\n // attributes with unrecognized attribute-names are ignored.)\n const attributeNameLowercase = attributeName.toLowerCase()\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1\n // If the attribute-name case-insensitively matches the string\n // \"Expires\", the user agent MUST process the cookie-av as follows.\n if (attributeNameLowercase === 'expires') {\n // 1. Let the expiry-time be the result of parsing the attribute-value\n // as cookie-date (see Section 5.1.1).\n const expiryTime = new Date(attributeValue)\n\n // 2. If the attribute-value failed to parse as a cookie date, ignore\n // the cookie-av.\n\n cookieAttributeList.expires = expiryTime\n } else if (attributeNameLowercase === 'max-age') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2\n // If the attribute-name case-insensitively matches the string \"Max-\n // Age\", the user agent MUST process the cookie-av as follows.\n\n // 1. If the first character of the attribute-value is not a DIGIT or a\n // \"-\" character, ignore the cookie-av.\n const charCode = attributeValue.charCodeAt(0)\n\n if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 2. If the remainder of attribute-value contains a non-DIGIT\n // character, ignore the cookie-av.\n if (!/^\\d+$/.test(attributeValue)) {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 3. Let delta-seconds be the attribute-value converted to an integer.\n const deltaSeconds = Number(attributeValue)\n\n // 4. Let cookie-age-limit be the maximum age of the cookie (which\n // SHOULD be 400 days or less, see Section 4.1.2.2).\n\n // 5. Set delta-seconds to the smaller of its present value and cookie-\n // age-limit.\n // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)\n\n // 6. If delta-seconds is less than or equal to zero (0), let expiry-\n // time be the earliest representable date and time. Otherwise, let\n // the expiry-time be the current date and time plus delta-seconds\n // seconds.\n // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds\n\n // 7. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Max-Age and an attribute-value of expiry-time.\n cookieAttributeList.maxAge = deltaSeconds\n } else if (attributeNameLowercase === 'domain') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3\n // If the attribute-name case-insensitively matches the string \"Domain\",\n // the user agent MUST process the cookie-av as follows.\n\n // 1. Let cookie-domain be the attribute-value.\n let cookieDomain = attributeValue\n\n // 2. If cookie-domain starts with %x2E (\".\"), let cookie-domain be\n // cookie-domain without its leading %x2E (\".\").\n if (cookieDomain[0] === '.') {\n cookieDomain = cookieDomain.slice(1)\n }\n\n // 3. Convert the cookie-domain to lower case.\n cookieDomain = cookieDomain.toLowerCase()\n\n // 4. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Domain and an attribute-value of cookie-domain.\n cookieAttributeList.domain = cookieDomain\n } else if (attributeNameLowercase === 'path') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4\n // If the attribute-name case-insensitively matches the string \"Path\",\n // the user agent MUST process the cookie-av as follows.\n\n // 1. If the attribute-value is empty or if the first character of the\n // attribute-value is not %x2F (\"/\"):\n let cookiePath = ''\n if (attributeValue.length === 0 || attributeValue[0] !== '/') {\n // 1. Let cookie-path be the default-path.\n cookiePath = '/'\n } else {\n // Otherwise:\n\n // 1. Let cookie-path be the attribute-value.\n cookiePath = attributeValue\n }\n\n // 2. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Path and an attribute-value of cookie-path.\n cookieAttributeList.path = cookiePath\n } else if (attributeNameLowercase === 'secure') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5\n // If the attribute-name case-insensitively matches the string \"Secure\",\n // the user agent MUST append an attribute to the cookie-attribute-list\n // with an attribute-name of Secure and an empty attribute-value.\n\n cookieAttributeList.secure = true\n } else if (attributeNameLowercase === 'httponly') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6\n // If the attribute-name case-insensitively matches the string\n // \"HttpOnly\", the user agent MUST append an attribute to the cookie-\n // attribute-list with an attribute-name of HttpOnly and an empty\n // attribute-value.\n\n cookieAttributeList.httpOnly = true\n } else if (attributeNameLowercase === 'samesite') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7\n // If the attribute-name case-insensitively matches the string\n // \"SameSite\", the user agent MUST process the cookie-av as follows:\n\n // 1. Let enforcement be \"Default\".\n let enforcement = 'Default'\n\n const attributeValueLowercase = attributeValue.toLowerCase()\n // 2. If cookie-av's attribute-value is a case-insensitive match for\n // \"None\", set enforcement to \"None\".\n if (attributeValueLowercase.includes('none')) {\n enforcement = 'None'\n }\n\n // 3. If cookie-av's attribute-value is a case-insensitive match for\n // \"Strict\", set enforcement to \"Strict\".\n if (attributeValueLowercase.includes('strict')) {\n enforcement = 'Strict'\n }\n\n // 4. If cookie-av's attribute-value is a case-insensitive match for\n // \"Lax\", set enforcement to \"Lax\".\n if (attributeValueLowercase.includes('lax')) {\n enforcement = 'Lax'\n }\n\n // 5. Append an attribute to the cookie-attribute-list with an\n // attribute-name of \"SameSite\" and an attribute-value of\n // enforcement.\n cookieAttributeList.sameSite = enforcement\n } else {\n cookieAttributeList.unparsed ??= []\n\n cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)\n }\n\n // 8. Return to Step 1 of this algorithm.\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n}\n\nmodule.exports = {\n parseSetCookie,\n parseUnparsedAttributes\n}\n","'use strict'\n\nconst assert = require('assert')\nconst { kHeadersList } = require('../core/symbols')\n\nfunction isCTLExcludingHtab (value) {\n if (value.length === 0) {\n return false\n }\n\n for (const char of value) {\n const code = char.charCodeAt(0)\n\n if (\n (code >= 0x00 || code <= 0x08) ||\n (code >= 0x0A || code <= 0x1F) ||\n code === 0x7F\n ) {\n return false\n }\n }\n}\n\n/**\n CHAR = \n token = 1*\n separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n | \",\" | \";\" | \":\" | \"\\\" | <\">\n | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n | \"{\" | \"}\" | SP | HT\n * @param {string} name\n */\nfunction validateCookieName (name) {\n for (const char of name) {\n const code = char.charCodeAt(0)\n\n if (\n (code <= 0x20 || code > 0x7F) ||\n char === '(' ||\n char === ')' ||\n char === '>' ||\n char === '<' ||\n char === '@' ||\n char === ',' ||\n char === ';' ||\n char === ':' ||\n char === '\\\\' ||\n char === '\"' ||\n char === '/' ||\n char === '[' ||\n char === ']' ||\n char === '?' ||\n char === '=' ||\n char === '{' ||\n char === '}'\n ) {\n throw new Error('Invalid cookie name')\n }\n }\n}\n\n/**\n cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n ; US-ASCII characters excluding CTLs,\n ; whitespace DQUOTE, comma, semicolon,\n ; and backslash\n * @param {string} value\n */\nfunction validateCookieValue (value) {\n for (const char of value) {\n const code = char.charCodeAt(0)\n\n if (\n code < 0x21 || // exclude CTLs (0-31)\n code === 0x22 ||\n code === 0x2C ||\n code === 0x3B ||\n code === 0x5C ||\n code > 0x7E // non-ascii\n ) {\n throw new Error('Invalid header value')\n }\n }\n}\n\n/**\n * path-value = \n * @param {string} path\n */\nfunction validateCookiePath (path) {\n for (const char of path) {\n const code = char.charCodeAt(0)\n\n if (code < 0x21 || char === ';') {\n throw new Error('Invalid cookie path')\n }\n }\n}\n\n/**\n * I have no idea why these values aren't allowed to be honest,\n * but Deno tests these. - Khafra\n * @param {string} domain\n */\nfunction validateCookieDomain (domain) {\n if (\n domain.startsWith('-') ||\n domain.endsWith('.') ||\n domain.endsWith('-')\n ) {\n throw new Error('Invalid cookie domain')\n }\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1\n * @param {number|Date} date\n IMF-fixdate = day-name \",\" SP date1 SP time-of-day SP GMT\n ; fixed length/zone/capitalization subset of the format\n ; see Section 3.3 of [RFC5322]\n\n day-name = %x4D.6F.6E ; \"Mon\", case-sensitive\n / %x54.75.65 ; \"Tue\", case-sensitive\n / %x57.65.64 ; \"Wed\", case-sensitive\n / %x54.68.75 ; \"Thu\", case-sensitive\n / %x46.72.69 ; \"Fri\", case-sensitive\n / %x53.61.74 ; \"Sat\", case-sensitive\n / %x53.75.6E ; \"Sun\", case-sensitive\n date1 = day SP month SP year\n ; e.g., 02 Jun 1982\n\n day = 2DIGIT\n month = %x4A.61.6E ; \"Jan\", case-sensitive\n / %x46.65.62 ; \"Feb\", case-sensitive\n / %x4D.61.72 ; \"Mar\", case-sensitive\n / %x41.70.72 ; \"Apr\", case-sensitive\n / %x4D.61.79 ; \"May\", case-sensitive\n / %x4A.75.6E ; \"Jun\", case-sensitive\n / %x4A.75.6C ; \"Jul\", case-sensitive\n / %x41.75.67 ; \"Aug\", case-sensitive\n / %x53.65.70 ; \"Sep\", case-sensitive\n / %x4F.63.74 ; \"Oct\", case-sensitive\n / %x4E.6F.76 ; \"Nov\", case-sensitive\n / %x44.65.63 ; \"Dec\", case-sensitive\n year = 4DIGIT\n\n GMT = %x47.4D.54 ; \"GMT\", case-sensitive\n\n time-of-day = hour \":\" minute \":\" second\n ; 00:00:00 - 23:59:60 (leap second)\n\n hour = 2DIGIT\n minute = 2DIGIT\n second = 2DIGIT\n */\nfunction toIMFDate (date) {\n if (typeof date === 'number') {\n date = new Date(date)\n }\n\n const days = [\n 'Sun', 'Mon', 'Tue', 'Wed',\n 'Thu', 'Fri', 'Sat'\n ]\n\n const months = [\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'\n ]\n\n const dayName = days[date.getUTCDay()]\n const day = date.getUTCDate().toString().padStart(2, '0')\n const month = months[date.getUTCMonth()]\n const year = date.getUTCFullYear()\n const hour = date.getUTCHours().toString().padStart(2, '0')\n const minute = date.getUTCMinutes().toString().padStart(2, '0')\n const second = date.getUTCSeconds().toString().padStart(2, '0')\n\n return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`\n}\n\n/**\n max-age-av = \"Max-Age=\" non-zero-digit *DIGIT\n ; In practice, both expires-av and max-age-av\n ; are limited to dates representable by the\n ; user agent.\n * @param {number} maxAge\n */\nfunction validateCookieMaxAge (maxAge) {\n if (maxAge < 0) {\n throw new Error('Invalid cookie max-age')\n }\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1\n * @param {import('./index').Cookie} cookie\n */\nfunction stringify (cookie) {\n if (cookie.name.length === 0) {\n return null\n }\n\n validateCookieName(cookie.name)\n validateCookieValue(cookie.value)\n\n const out = [`${cookie.name}=${cookie.value}`]\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2\n if (cookie.name.startsWith('__Secure-')) {\n cookie.secure = true\n }\n\n if (cookie.name.startsWith('__Host-')) {\n cookie.secure = true\n cookie.domain = null\n cookie.path = '/'\n }\n\n if (cookie.secure) {\n out.push('Secure')\n }\n\n if (cookie.httpOnly) {\n out.push('HttpOnly')\n }\n\n if (typeof cookie.maxAge === 'number') {\n validateCookieMaxAge(cookie.maxAge)\n out.push(`Max-Age=${cookie.maxAge}`)\n }\n\n if (cookie.domain) {\n validateCookieDomain(cookie.domain)\n out.push(`Domain=${cookie.domain}`)\n }\n\n if (cookie.path) {\n validateCookiePath(cookie.path)\n out.push(`Path=${cookie.path}`)\n }\n\n if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {\n out.push(`Expires=${toIMFDate(cookie.expires)}`)\n }\n\n if (cookie.sameSite) {\n out.push(`SameSite=${cookie.sameSite}`)\n }\n\n for (const part of cookie.unparsed) {\n if (!part.includes('=')) {\n throw new Error('Invalid unparsed')\n }\n\n const [key, ...value] = part.split('=')\n\n out.push(`${key.trim()}=${value.join('=')}`)\n }\n\n return out.join('; ')\n}\n\nlet kHeadersListNode\n\nfunction getHeadersList (headers) {\n if (headers[kHeadersList]) {\n return headers[kHeadersList]\n }\n\n if (!kHeadersListNode) {\n kHeadersListNode = Object.getOwnPropertySymbols(headers).find(\n (symbol) => symbol.description === 'headers list'\n )\n\n assert(kHeadersListNode, 'Headers cannot be parsed')\n }\n\n const headersList = headers[kHeadersListNode]\n assert(headersList)\n\n return headersList\n}\n\nmodule.exports = {\n isCTLExcludingHtab,\n stringify,\n getHeadersList\n}\n","'use strict'\n\nconst net = require('net')\nconst assert = require('assert')\nconst util = require('./util')\nconst { InvalidArgumentError, ConnectTimeoutError } = require('./errors')\n\nlet tls // include tls conditionally since it is not always available\n\n// TODO: session re-use does not wait for the first\n// connection to resolve the session and might therefore\n// resolve the same servername multiple times even when\n// re-use is enabled.\n\nlet SessionCache\n// FIXME: remove workaround when the Node bug is fixed\n// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308\nif (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {\n SessionCache = class WeakSessionCache {\n constructor (maxCachedSessions) {\n this._maxCachedSessions = maxCachedSessions\n this._sessionCache = new Map()\n this._sessionRegistry = new global.FinalizationRegistry((key) => {\n if (this._sessionCache.size < this._maxCachedSessions) {\n return\n }\n\n const ref = this._sessionCache.get(key)\n if (ref !== undefined && ref.deref() === undefined) {\n this._sessionCache.delete(key)\n }\n })\n }\n\n get (sessionKey) {\n const ref = this._sessionCache.get(sessionKey)\n return ref ? ref.deref() : null\n }\n\n set (sessionKey, session) {\n if (this._maxCachedSessions === 0) {\n return\n }\n\n this._sessionCache.set(sessionKey, new WeakRef(session))\n this._sessionRegistry.register(session, sessionKey)\n }\n }\n} else {\n SessionCache = class SimpleSessionCache {\n constructor (maxCachedSessions) {\n this._maxCachedSessions = maxCachedSessions\n this._sessionCache = new Map()\n }\n\n get (sessionKey) {\n return this._sessionCache.get(sessionKey)\n }\n\n set (sessionKey, session) {\n if (this._maxCachedSessions === 0) {\n return\n }\n\n if (this._sessionCache.size >= this._maxCachedSessions) {\n // remove the oldest session\n const { value: oldestKey } = this._sessionCache.keys().next()\n this._sessionCache.delete(oldestKey)\n }\n\n this._sessionCache.set(sessionKey, session)\n }\n }\n}\n\nfunction buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {\n if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {\n throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')\n }\n\n const options = { path: socketPath, ...opts }\n const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)\n timeout = timeout == null ? 10e3 : timeout\n allowH2 = allowH2 != null ? allowH2 : false\n return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {\n let socket\n if (protocol === 'https:') {\n if (!tls) {\n tls = require('tls')\n }\n servername = servername || options.servername || util.getServerName(host) || null\n\n const sessionKey = servername || hostname\n const session = sessionCache.get(sessionKey) || null\n\n assert(sessionKey)\n\n socket = tls.connect({\n highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...\n ...options,\n servername,\n session,\n localAddress,\n // TODO(HTTP/2): Add support for h2c\n ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],\n socket: httpSocket, // upgrade socket connection\n port: port || 443,\n host: hostname\n })\n\n socket\n .on('session', function (session) {\n // TODO (fix): Can a session become invalid once established? Don't think so?\n sessionCache.set(sessionKey, session)\n })\n } else {\n assert(!httpSocket, 'httpSocket can only be sent on TLS update')\n socket = net.connect({\n highWaterMark: 64 * 1024, // Same as nodejs fs streams.\n ...options,\n localAddress,\n port: port || 80,\n host: hostname\n })\n }\n\n // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket\n if (options.keepAlive == null || options.keepAlive) {\n const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay\n socket.setKeepAlive(true, keepAliveInitialDelay)\n }\n\n const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)\n\n socket\n .setNoDelay(true)\n .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {\n cancelTimeout()\n\n if (callback) {\n const cb = callback\n callback = null\n cb(null, this)\n }\n })\n .on('error', function (err) {\n cancelTimeout()\n\n if (callback) {\n const cb = callback\n callback = null\n cb(err)\n }\n })\n\n return socket\n }\n}\n\nfunction setupTimeout (onConnectTimeout, timeout) {\n if (!timeout) {\n return () => {}\n }\n\n let s1 = null\n let s2 = null\n const timeoutId = setTimeout(() => {\n // setImmediate is added to make sure that we priotorise socket error events over timeouts\n s1 = setImmediate(() => {\n if (process.platform === 'win32') {\n // Windows needs an extra setImmediate probably due to implementation differences in the socket logic\n s2 = setImmediate(() => onConnectTimeout())\n } else {\n onConnectTimeout()\n }\n })\n }, timeout)\n return () => {\n clearTimeout(timeoutId)\n clearImmediate(s1)\n clearImmediate(s2)\n }\n}\n\nfunction onConnectTimeout (socket) {\n util.destroy(socket, new ConnectTimeoutError())\n}\n\nmodule.exports = buildConnector\n","'use strict'\n\n/** @type {Record} */\nconst headerNameLowerCasedRecord = {}\n\n// https://developer.mozilla.org/docs/Web/HTTP/Headers\nconst wellknownHeaderNames = [\n 'Accept',\n 'Accept-Encoding',\n 'Accept-Language',\n 'Accept-Ranges',\n 'Access-Control-Allow-Credentials',\n 'Access-Control-Allow-Headers',\n 'Access-Control-Allow-Methods',\n 'Access-Control-Allow-Origin',\n 'Access-Control-Expose-Headers',\n 'Access-Control-Max-Age',\n 'Access-Control-Request-Headers',\n 'Access-Control-Request-Method',\n 'Age',\n 'Allow',\n 'Alt-Svc',\n 'Alt-Used',\n 'Authorization',\n 'Cache-Control',\n 'Clear-Site-Data',\n 'Connection',\n 'Content-Disposition',\n 'Content-Encoding',\n 'Content-Language',\n 'Content-Length',\n 'Content-Location',\n 'Content-Range',\n 'Content-Security-Policy',\n 'Content-Security-Policy-Report-Only',\n 'Content-Type',\n 'Cookie',\n 'Cross-Origin-Embedder-Policy',\n 'Cross-Origin-Opener-Policy',\n 'Cross-Origin-Resource-Policy',\n 'Date',\n 'Device-Memory',\n 'Downlink',\n 'ECT',\n 'ETag',\n 'Expect',\n 'Expect-CT',\n 'Expires',\n 'Forwarded',\n 'From',\n 'Host',\n 'If-Match',\n 'If-Modified-Since',\n 'If-None-Match',\n 'If-Range',\n 'If-Unmodified-Since',\n 'Keep-Alive',\n 'Last-Modified',\n 'Link',\n 'Location',\n 'Max-Forwards',\n 'Origin',\n 'Permissions-Policy',\n 'Pragma',\n 'Proxy-Authenticate',\n 'Proxy-Authorization',\n 'RTT',\n 'Range',\n 'Referer',\n 'Referrer-Policy',\n 'Refresh',\n 'Retry-After',\n 'Sec-WebSocket-Accept',\n 'Sec-WebSocket-Extensions',\n 'Sec-WebSocket-Key',\n 'Sec-WebSocket-Protocol',\n 'Sec-WebSocket-Version',\n 'Server',\n 'Server-Timing',\n 'Service-Worker-Allowed',\n 'Service-Worker-Navigation-Preload',\n 'Set-Cookie',\n 'SourceMap',\n 'Strict-Transport-Security',\n 'Supports-Loading-Mode',\n 'TE',\n 'Timing-Allow-Origin',\n 'Trailer',\n 'Transfer-Encoding',\n 'Upgrade',\n 'Upgrade-Insecure-Requests',\n 'User-Agent',\n 'Vary',\n 'Via',\n 'WWW-Authenticate',\n 'X-Content-Type-Options',\n 'X-DNS-Prefetch-Control',\n 'X-Frame-Options',\n 'X-Permitted-Cross-Domain-Policies',\n 'X-Powered-By',\n 'X-Requested-With',\n 'X-XSS-Protection'\n]\n\nfor (let i = 0; i < wellknownHeaderNames.length; ++i) {\n const key = wellknownHeaderNames[i]\n const lowerCasedKey = key.toLowerCase()\n headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =\n lowerCasedKey\n}\n\n// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.\nObject.setPrototypeOf(headerNameLowerCasedRecord, null)\n\nmodule.exports = {\n wellknownHeaderNames,\n headerNameLowerCasedRecord\n}\n","'use strict'\n\nclass UndiciError extends Error {\n constructor (message) {\n super(message)\n this.name = 'UndiciError'\n this.code = 'UND_ERR'\n }\n}\n\nclass ConnectTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ConnectTimeoutError)\n this.name = 'ConnectTimeoutError'\n this.message = message || 'Connect Timeout Error'\n this.code = 'UND_ERR_CONNECT_TIMEOUT'\n }\n}\n\nclass HeadersTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, HeadersTimeoutError)\n this.name = 'HeadersTimeoutError'\n this.message = message || 'Headers Timeout Error'\n this.code = 'UND_ERR_HEADERS_TIMEOUT'\n }\n}\n\nclass HeadersOverflowError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, HeadersOverflowError)\n this.name = 'HeadersOverflowError'\n this.message = message || 'Headers Overflow Error'\n this.code = 'UND_ERR_HEADERS_OVERFLOW'\n }\n}\n\nclass BodyTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, BodyTimeoutError)\n this.name = 'BodyTimeoutError'\n this.message = message || 'Body Timeout Error'\n this.code = 'UND_ERR_BODY_TIMEOUT'\n }\n}\n\nclass ResponseStatusCodeError extends UndiciError {\n constructor (message, statusCode, headers, body) {\n super(message)\n Error.captureStackTrace(this, ResponseStatusCodeError)\n this.name = 'ResponseStatusCodeError'\n this.message = message || 'Response Status Code Error'\n this.code = 'UND_ERR_RESPONSE_STATUS_CODE'\n this.body = body\n this.status = statusCode\n this.statusCode = statusCode\n this.headers = headers\n }\n}\n\nclass InvalidArgumentError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InvalidArgumentError)\n this.name = 'InvalidArgumentError'\n this.message = message || 'Invalid Argument Error'\n this.code = 'UND_ERR_INVALID_ARG'\n }\n}\n\nclass InvalidReturnValueError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InvalidReturnValueError)\n this.name = 'InvalidReturnValueError'\n this.message = message || 'Invalid Return Value Error'\n this.code = 'UND_ERR_INVALID_RETURN_VALUE'\n }\n}\n\nclass RequestAbortedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, RequestAbortedError)\n this.name = 'AbortError'\n this.message = message || 'Request aborted'\n this.code = 'UND_ERR_ABORTED'\n }\n}\n\nclass InformationalError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InformationalError)\n this.name = 'InformationalError'\n this.message = message || 'Request information'\n this.code = 'UND_ERR_INFO'\n }\n}\n\nclass RequestContentLengthMismatchError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, RequestContentLengthMismatchError)\n this.name = 'RequestContentLengthMismatchError'\n this.message = message || 'Request body length does not match content-length header'\n this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'\n }\n}\n\nclass ResponseContentLengthMismatchError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ResponseContentLengthMismatchError)\n this.name = 'ResponseContentLengthMismatchError'\n this.message = message || 'Response body length does not match content-length header'\n this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'\n }\n}\n\nclass ClientDestroyedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ClientDestroyedError)\n this.name = 'ClientDestroyedError'\n this.message = message || 'The client is destroyed'\n this.code = 'UND_ERR_DESTROYED'\n }\n}\n\nclass ClientClosedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ClientClosedError)\n this.name = 'ClientClosedError'\n this.message = message || 'The client is closed'\n this.code = 'UND_ERR_CLOSED'\n }\n}\n\nclass SocketError extends UndiciError {\n constructor (message, socket) {\n super(message)\n Error.captureStackTrace(this, SocketError)\n this.name = 'SocketError'\n this.message = message || 'Socket error'\n this.code = 'UND_ERR_SOCKET'\n this.socket = socket\n }\n}\n\nclass NotSupportedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, NotSupportedError)\n this.name = 'NotSupportedError'\n this.message = message || 'Not supported error'\n this.code = 'UND_ERR_NOT_SUPPORTED'\n }\n}\n\nclass BalancedPoolMissingUpstreamError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, NotSupportedError)\n this.name = 'MissingUpstreamError'\n this.message = message || 'No upstream has been added to the BalancedPool'\n this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'\n }\n}\n\nclass HTTPParserError extends Error {\n constructor (message, code, data) {\n super(message)\n Error.captureStackTrace(this, HTTPParserError)\n this.name = 'HTTPParserError'\n this.code = code ? `HPE_${code}` : undefined\n this.data = data ? data.toString() : undefined\n }\n}\n\nclass ResponseExceededMaxSizeError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ResponseExceededMaxSizeError)\n this.name = 'ResponseExceededMaxSizeError'\n this.message = message || 'Response content exceeded max size'\n this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'\n }\n}\n\nclass RequestRetryError extends UndiciError {\n constructor (message, code, { headers, data }) {\n super(message)\n Error.captureStackTrace(this, RequestRetryError)\n this.name = 'RequestRetryError'\n this.message = message || 'Request retry error'\n this.code = 'UND_ERR_REQ_RETRY'\n this.statusCode = code\n this.data = data\n this.headers = headers\n }\n}\n\nmodule.exports = {\n HTTPParserError,\n UndiciError,\n HeadersTimeoutError,\n HeadersOverflowError,\n BodyTimeoutError,\n RequestContentLengthMismatchError,\n ConnectTimeoutError,\n ResponseStatusCodeError,\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError,\n ClientDestroyedError,\n ClientClosedError,\n InformationalError,\n SocketError,\n NotSupportedError,\n ResponseContentLengthMismatchError,\n BalancedPoolMissingUpstreamError,\n ResponseExceededMaxSizeError,\n RequestRetryError\n}\n","'use strict'\n\nconst {\n InvalidArgumentError,\n NotSupportedError\n} = require('./errors')\nconst assert = require('assert')\nconst { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = require('./symbols')\nconst util = require('./util')\n\n// tokenRegExp and headerCharRegex have been lifted from\n// https://github.com/nodejs/node/blob/main/lib/_http_common.js\n\n/**\n * Verifies that the given val is a valid HTTP token\n * per the rules defined in RFC 7230\n * See https://tools.ietf.org/html/rfc7230#section-3.2.6\n */\nconst tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/\n\n/**\n * Matches if val contains an invalid field-vchar\n * field-value = *( field-content / obs-fold )\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n */\nconst headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/\n\n// Verifies that a given path is valid does not contain control chars \\x00 to \\x20\nconst invalidPathRegex = /[^\\u0021-\\u00ff]/\n\nconst kHandler = Symbol('handler')\n\nconst channels = {}\n\nlet extractBody\n\ntry {\n const diagnosticsChannel = require('diagnostics_channel')\n channels.create = diagnosticsChannel.channel('undici:request:create')\n channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')\n channels.headers = diagnosticsChannel.channel('undici:request:headers')\n channels.trailers = diagnosticsChannel.channel('undici:request:trailers')\n channels.error = diagnosticsChannel.channel('undici:request:error')\n} catch {\n channels.create = { hasSubscribers: false }\n channels.bodySent = { hasSubscribers: false }\n channels.headers = { hasSubscribers: false }\n channels.trailers = { hasSubscribers: false }\n channels.error = { hasSubscribers: false }\n}\n\nclass Request {\n constructor (origin, {\n path,\n method,\n body,\n headers,\n query,\n idempotent,\n blocking,\n upgrade,\n headersTimeout,\n bodyTimeout,\n reset,\n throwOnError,\n expectContinue\n }, handler) {\n if (typeof path !== 'string') {\n throw new InvalidArgumentError('path must be a string')\n } else if (\n path[0] !== '/' &&\n !(path.startsWith('http://') || path.startsWith('https://')) &&\n method !== 'CONNECT'\n ) {\n throw new InvalidArgumentError('path must be an absolute URL or start with a slash')\n } else if (invalidPathRegex.exec(path) !== null) {\n throw new InvalidArgumentError('invalid request path')\n }\n\n if (typeof method !== 'string') {\n throw new InvalidArgumentError('method must be a string')\n } else if (tokenRegExp.exec(method) === null) {\n throw new InvalidArgumentError('invalid request method')\n }\n\n if (upgrade && typeof upgrade !== 'string') {\n throw new InvalidArgumentError('upgrade must be a string')\n }\n\n if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {\n throw new InvalidArgumentError('invalid headersTimeout')\n }\n\n if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {\n throw new InvalidArgumentError('invalid bodyTimeout')\n }\n\n if (reset != null && typeof reset !== 'boolean') {\n throw new InvalidArgumentError('invalid reset')\n }\n\n if (expectContinue != null && typeof expectContinue !== 'boolean') {\n throw new InvalidArgumentError('invalid expectContinue')\n }\n\n this.headersTimeout = headersTimeout\n\n this.bodyTimeout = bodyTimeout\n\n this.throwOnError = throwOnError === true\n\n this.method = method\n\n this.abort = null\n\n if (body == null) {\n this.body = null\n } else if (util.isStream(body)) {\n this.body = body\n\n const rState = this.body._readableState\n if (!rState || !rState.autoDestroy) {\n this.endHandler = function autoDestroy () {\n util.destroy(this)\n }\n this.body.on('end', this.endHandler)\n }\n\n this.errorHandler = err => {\n if (this.abort) {\n this.abort(err)\n } else {\n this.error = err\n }\n }\n this.body.on('error', this.errorHandler)\n } else if (util.isBuffer(body)) {\n this.body = body.byteLength ? body : null\n } else if (ArrayBuffer.isView(body)) {\n this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null\n } else if (body instanceof ArrayBuffer) {\n this.body = body.byteLength ? Buffer.from(body) : null\n } else if (typeof body === 'string') {\n this.body = body.length ? Buffer.from(body) : null\n } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {\n this.body = body\n } else {\n throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')\n }\n\n this.completed = false\n\n this.aborted = false\n\n this.upgrade = upgrade || null\n\n this.path = query ? util.buildURL(path, query) : path\n\n this.origin = origin\n\n this.idempotent = idempotent == null\n ? method === 'HEAD' || method === 'GET'\n : idempotent\n\n this.blocking = blocking == null ? false : blocking\n\n this.reset = reset == null ? null : reset\n\n this.host = null\n\n this.contentLength = null\n\n this.contentType = null\n\n this.headers = ''\n\n // Only for H2\n this.expectContinue = expectContinue != null ? expectContinue : false\n\n if (Array.isArray(headers)) {\n if (headers.length % 2 !== 0) {\n throw new InvalidArgumentError('headers array must be even')\n }\n for (let i = 0; i < headers.length; i += 2) {\n processHeader(this, headers[i], headers[i + 1])\n }\n } else if (headers && typeof headers === 'object') {\n const keys = Object.keys(headers)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n processHeader(this, key, headers[key])\n }\n } else if (headers != null) {\n throw new InvalidArgumentError('headers must be an object or an array')\n }\n\n if (util.isFormDataLike(this.body)) {\n if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {\n throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')\n }\n\n if (!extractBody) {\n extractBody = require('../fetch/body.js').extractBody\n }\n\n const [bodyStream, contentType] = extractBody(body)\n if (this.contentType == null) {\n this.contentType = contentType\n this.headers += `content-type: ${contentType}\\r\\n`\n }\n this.body = bodyStream.stream\n this.contentLength = bodyStream.length\n } else if (util.isBlobLike(body) && this.contentType == null && body.type) {\n this.contentType = body.type\n this.headers += `content-type: ${body.type}\\r\\n`\n }\n\n util.validateHandler(handler, method, upgrade)\n\n this.servername = util.getServerName(this.host)\n\n this[kHandler] = handler\n\n if (channels.create.hasSubscribers) {\n channels.create.publish({ request: this })\n }\n }\n\n onBodySent (chunk) {\n if (this[kHandler].onBodySent) {\n try {\n return this[kHandler].onBodySent(chunk)\n } catch (err) {\n this.abort(err)\n }\n }\n }\n\n onRequestSent () {\n if (channels.bodySent.hasSubscribers) {\n channels.bodySent.publish({ request: this })\n }\n\n if (this[kHandler].onRequestSent) {\n try {\n return this[kHandler].onRequestSent()\n } catch (err) {\n this.abort(err)\n }\n }\n }\n\n onConnect (abort) {\n assert(!this.aborted)\n assert(!this.completed)\n\n if (this.error) {\n abort(this.error)\n } else {\n this.abort = abort\n return this[kHandler].onConnect(abort)\n }\n }\n\n onHeaders (statusCode, headers, resume, statusText) {\n assert(!this.aborted)\n assert(!this.completed)\n\n if (channels.headers.hasSubscribers) {\n channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })\n }\n\n try {\n return this[kHandler].onHeaders(statusCode, headers, resume, statusText)\n } catch (err) {\n this.abort(err)\n }\n }\n\n onData (chunk) {\n assert(!this.aborted)\n assert(!this.completed)\n\n try {\n return this[kHandler].onData(chunk)\n } catch (err) {\n this.abort(err)\n return false\n }\n }\n\n onUpgrade (statusCode, headers, socket) {\n assert(!this.aborted)\n assert(!this.completed)\n\n return this[kHandler].onUpgrade(statusCode, headers, socket)\n }\n\n onComplete (trailers) {\n this.onFinally()\n\n assert(!this.aborted)\n\n this.completed = true\n if (channels.trailers.hasSubscribers) {\n channels.trailers.publish({ request: this, trailers })\n }\n\n try {\n return this[kHandler].onComplete(trailers)\n } catch (err) {\n // TODO (fix): This might be a bad idea?\n this.onError(err)\n }\n }\n\n onError (error) {\n this.onFinally()\n\n if (channels.error.hasSubscribers) {\n channels.error.publish({ request: this, error })\n }\n\n if (this.aborted) {\n return\n }\n this.aborted = true\n\n return this[kHandler].onError(error)\n }\n\n onFinally () {\n if (this.errorHandler) {\n this.body.off('error', this.errorHandler)\n this.errorHandler = null\n }\n\n if (this.endHandler) {\n this.body.off('end', this.endHandler)\n this.endHandler = null\n }\n }\n\n // TODO: adjust to support H2\n addHeader (key, value) {\n processHeader(this, key, value)\n return this\n }\n\n static [kHTTP1BuildRequest] (origin, opts, handler) {\n // TODO: Migrate header parsing here, to make Requests\n // HTTP agnostic\n return new Request(origin, opts, handler)\n }\n\n static [kHTTP2BuildRequest] (origin, opts, handler) {\n const headers = opts.headers\n opts = { ...opts, headers: null }\n\n const request = new Request(origin, opts, handler)\n\n request.headers = {}\n\n if (Array.isArray(headers)) {\n if (headers.length % 2 !== 0) {\n throw new InvalidArgumentError('headers array must be even')\n }\n for (let i = 0; i < headers.length; i += 2) {\n processHeader(request, headers[i], headers[i + 1], true)\n }\n } else if (headers && typeof headers === 'object') {\n const keys = Object.keys(headers)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n processHeader(request, key, headers[key], true)\n }\n } else if (headers != null) {\n throw new InvalidArgumentError('headers must be an object or an array')\n }\n\n return request\n }\n\n static [kHTTP2CopyHeaders] (raw) {\n const rawHeaders = raw.split('\\r\\n')\n const headers = {}\n\n for (const header of rawHeaders) {\n const [key, value] = header.split(': ')\n\n if (value == null || value.length === 0) continue\n\n if (headers[key]) headers[key] += `,${value}`\n else headers[key] = value\n }\n\n return headers\n }\n}\n\nfunction processHeaderValue (key, val, skipAppend) {\n if (val && typeof val === 'object') {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n\n val = val != null ? `${val}` : ''\n\n if (headerCharRegex.exec(val) !== null) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n\n return skipAppend ? val : `${key}: ${val}\\r\\n`\n}\n\nfunction processHeader (request, key, val, skipAppend = false) {\n if (val && (typeof val === 'object' && !Array.isArray(val))) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n } else if (val === undefined) {\n return\n }\n\n if (\n request.host === null &&\n key.length === 4 &&\n key.toLowerCase() === 'host'\n ) {\n if (headerCharRegex.exec(val) !== null) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n // Consumed by Client\n request.host = val\n } else if (\n request.contentLength === null &&\n key.length === 14 &&\n key.toLowerCase() === 'content-length'\n ) {\n request.contentLength = parseInt(val, 10)\n if (!Number.isFinite(request.contentLength)) {\n throw new InvalidArgumentError('invalid content-length header')\n }\n } else if (\n request.contentType === null &&\n key.length === 12 &&\n key.toLowerCase() === 'content-type'\n ) {\n request.contentType = val\n if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)\n else request.headers += processHeaderValue(key, val)\n } else if (\n key.length === 17 &&\n key.toLowerCase() === 'transfer-encoding'\n ) {\n throw new InvalidArgumentError('invalid transfer-encoding header')\n } else if (\n key.length === 10 &&\n key.toLowerCase() === 'connection'\n ) {\n const value = typeof val === 'string' ? val.toLowerCase() : null\n if (value !== 'close' && value !== 'keep-alive') {\n throw new InvalidArgumentError('invalid connection header')\n } else if (value === 'close') {\n request.reset = true\n }\n } else if (\n key.length === 10 &&\n key.toLowerCase() === 'keep-alive'\n ) {\n throw new InvalidArgumentError('invalid keep-alive header')\n } else if (\n key.length === 7 &&\n key.toLowerCase() === 'upgrade'\n ) {\n throw new InvalidArgumentError('invalid upgrade header')\n } else if (\n key.length === 6 &&\n key.toLowerCase() === 'expect'\n ) {\n throw new NotSupportedError('expect header not supported')\n } else if (tokenRegExp.exec(key) === null) {\n throw new InvalidArgumentError('invalid header key')\n } else {\n if (Array.isArray(val)) {\n for (let i = 0; i < val.length; i++) {\n if (skipAppend) {\n if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`\n else request.headers[key] = processHeaderValue(key, val[i], skipAppend)\n } else {\n request.headers += processHeaderValue(key, val[i])\n }\n }\n } else {\n if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)\n else request.headers += processHeaderValue(key, val)\n }\n }\n}\n\nmodule.exports = Request\n","module.exports = {\n kClose: Symbol('close'),\n kDestroy: Symbol('destroy'),\n kDispatch: Symbol('dispatch'),\n kUrl: Symbol('url'),\n kWriting: Symbol('writing'),\n kResuming: Symbol('resuming'),\n kQueue: Symbol('queue'),\n kConnect: Symbol('connect'),\n kConnecting: Symbol('connecting'),\n kHeadersList: Symbol('headers list'),\n kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),\n kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),\n kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),\n kKeepAliveTimeoutValue: Symbol('keep alive timeout'),\n kKeepAlive: Symbol('keep alive'),\n kHeadersTimeout: Symbol('headers timeout'),\n kBodyTimeout: Symbol('body timeout'),\n kServerName: Symbol('server name'),\n kLocalAddress: Symbol('local address'),\n kHost: Symbol('host'),\n kNoRef: Symbol('no ref'),\n kBodyUsed: Symbol('used'),\n kRunning: Symbol('running'),\n kBlocking: Symbol('blocking'),\n kPending: Symbol('pending'),\n kSize: Symbol('size'),\n kBusy: Symbol('busy'),\n kQueued: Symbol('queued'),\n kFree: Symbol('free'),\n kConnected: Symbol('connected'),\n kClosed: Symbol('closed'),\n kNeedDrain: Symbol('need drain'),\n kReset: Symbol('reset'),\n kDestroyed: Symbol.for('nodejs.stream.destroyed'),\n kMaxHeadersSize: Symbol('max headers size'),\n kRunningIdx: Symbol('running index'),\n kPendingIdx: Symbol('pending index'),\n kError: Symbol('error'),\n kClients: Symbol('clients'),\n kClient: Symbol('client'),\n kParser: Symbol('parser'),\n kOnDestroyed: Symbol('destroy callbacks'),\n kPipelining: Symbol('pipelining'),\n kSocket: Symbol('socket'),\n kHostHeader: Symbol('host header'),\n kConnector: Symbol('connector'),\n kStrictContentLength: Symbol('strict content length'),\n kMaxRedirections: Symbol('maxRedirections'),\n kMaxRequests: Symbol('maxRequestsPerClient'),\n kProxy: Symbol('proxy agent options'),\n kCounter: Symbol('socket request counter'),\n kInterceptors: Symbol('dispatch interceptors'),\n kMaxResponseSize: Symbol('max response size'),\n kHTTP2Session: Symbol('http2Session'),\n kHTTP2SessionState: Symbol('http2Session state'),\n kHTTP2BuildRequest: Symbol('http2 build request'),\n kHTTP1BuildRequest: Symbol('http1 build request'),\n kHTTP2CopyHeaders: Symbol('http2 copy headers'),\n kHTTPConnVersion: Symbol('http connection version'),\n kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),\n kConstruct: Symbol('constructable')\n}\n","'use strict'\n\nconst assert = require('assert')\nconst { kDestroyed, kBodyUsed } = require('./symbols')\nconst { IncomingMessage } = require('http')\nconst stream = require('stream')\nconst net = require('net')\nconst { InvalidArgumentError } = require('./errors')\nconst { Blob } = require('buffer')\nconst nodeUtil = require('util')\nconst { stringify } = require('querystring')\nconst { headerNameLowerCasedRecord } = require('./constants')\n\nconst [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))\n\nfunction nop () {}\n\nfunction isStream (obj) {\n return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'\n}\n\n// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)\nfunction isBlobLike (object) {\n return (Blob && object instanceof Blob) || (\n object &&\n typeof object === 'object' &&\n (typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function') &&\n /^(Blob|File)$/.test(object[Symbol.toStringTag])\n )\n}\n\nfunction buildURL (url, queryParams) {\n if (url.includes('?') || url.includes('#')) {\n throw new Error('Query params cannot be passed when url already contains \"?\" or \"#\".')\n }\n\n const stringified = stringify(queryParams)\n\n if (stringified) {\n url += '?' + stringified\n }\n\n return url\n}\n\nfunction parseURL (url) {\n if (typeof url === 'string') {\n url = new URL(url)\n\n if (!/^https?:/.test(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n return url\n }\n\n if (!url || typeof url !== 'object') {\n throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')\n }\n\n if (!/^https?:/.test(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n if (!(url instanceof URL)) {\n if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {\n throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')\n }\n\n if (url.path != null && typeof url.path !== 'string') {\n throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')\n }\n\n if (url.pathname != null && typeof url.pathname !== 'string') {\n throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')\n }\n\n if (url.hostname != null && typeof url.hostname !== 'string') {\n throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')\n }\n\n if (url.origin != null && typeof url.origin !== 'string') {\n throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')\n }\n\n const port = url.port != null\n ? url.port\n : (url.protocol === 'https:' ? 443 : 80)\n let origin = url.origin != null\n ? url.origin\n : `${url.protocol}//${url.hostname}:${port}`\n let path = url.path != null\n ? url.path\n : `${url.pathname || ''}${url.search || ''}`\n\n if (origin.endsWith('/')) {\n origin = origin.substring(0, origin.length - 1)\n }\n\n if (path && !path.startsWith('/')) {\n path = `/${path}`\n }\n // new URL(path, origin) is unsafe when `path` contains an absolute URL\n // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:\n // If first parameter is a relative URL, second param is required, and will be used as the base URL.\n // If first parameter is an absolute URL, a given second param will be ignored.\n url = new URL(origin + path)\n }\n\n return url\n}\n\nfunction parseOrigin (url) {\n url = parseURL(url)\n\n if (url.pathname !== '/' || url.search || url.hash) {\n throw new InvalidArgumentError('invalid url')\n }\n\n return url\n}\n\nfunction getHostname (host) {\n if (host[0] === '[') {\n const idx = host.indexOf(']')\n\n assert(idx !== -1)\n return host.substring(1, idx)\n }\n\n const idx = host.indexOf(':')\n if (idx === -1) return host\n\n return host.substring(0, idx)\n}\n\n// IP addresses are not valid server names per RFC6066\n// > Currently, the only server names supported are DNS hostnames\nfunction getServerName (host) {\n if (!host) {\n return null\n }\n\n assert.strictEqual(typeof host, 'string')\n\n const servername = getHostname(host)\n if (net.isIP(servername)) {\n return ''\n }\n\n return servername\n}\n\nfunction deepClone (obj) {\n return JSON.parse(JSON.stringify(obj))\n}\n\nfunction isAsyncIterable (obj) {\n return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')\n}\n\nfunction isIterable (obj) {\n return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))\n}\n\nfunction bodyLength (body) {\n if (body == null) {\n return 0\n } else if (isStream(body)) {\n const state = body._readableState\n return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)\n ? state.length\n : null\n } else if (isBlobLike(body)) {\n return body.size != null ? body.size : null\n } else if (isBuffer(body)) {\n return body.byteLength\n }\n\n return null\n}\n\nfunction isDestroyed (stream) {\n return !stream || !!(stream.destroyed || stream[kDestroyed])\n}\n\nfunction isReadableAborted (stream) {\n const state = stream && stream._readableState\n return isDestroyed(stream) && state && !state.endEmitted\n}\n\nfunction destroy (stream, err) {\n if (stream == null || !isStream(stream) || isDestroyed(stream)) {\n return\n }\n\n if (typeof stream.destroy === 'function') {\n if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {\n // See: https://github.com/nodejs/node/pull/38505/files\n stream.socket = null\n }\n\n stream.destroy(err)\n } else if (err) {\n process.nextTick((stream, err) => {\n stream.emit('error', err)\n }, stream, err)\n }\n\n if (stream.destroyed !== true) {\n stream[kDestroyed] = true\n }\n}\n\nconst KEEPALIVE_TIMEOUT_EXPR = /timeout=(\\d+)/\nfunction parseKeepAliveTimeout (val) {\n const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)\n return m ? parseInt(m[1], 10) * 1000 : null\n}\n\n/**\n * Retrieves a header name and returns its lowercase value.\n * @param {string | Buffer} value Header name\n * @returns {string}\n */\nfunction headerNameToString (value) {\n return headerNameLowerCasedRecord[value] || value.toLowerCase()\n}\n\nfunction parseHeaders (headers, obj = {}) {\n // For H2 support\n if (!Array.isArray(headers)) return headers\n\n for (let i = 0; i < headers.length; i += 2) {\n const key = headers[i].toString().toLowerCase()\n let val = obj[key]\n\n if (!val) {\n if (Array.isArray(headers[i + 1])) {\n obj[key] = headers[i + 1].map(x => x.toString('utf8'))\n } else {\n obj[key] = headers[i + 1].toString('utf8')\n }\n } else {\n if (!Array.isArray(val)) {\n val = [val]\n obj[key] = val\n }\n val.push(headers[i + 1].toString('utf8'))\n }\n }\n\n // See https://github.com/nodejs/node/pull/46528\n if ('content-length' in obj && 'content-disposition' in obj) {\n obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')\n }\n\n return obj\n}\n\nfunction parseRawHeaders (headers) {\n const ret = []\n let hasContentLength = false\n let contentDispositionIdx = -1\n\n for (let n = 0; n < headers.length; n += 2) {\n const key = headers[n + 0].toString()\n const val = headers[n + 1].toString('utf8')\n\n if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {\n ret.push(key, val)\n hasContentLength = true\n } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {\n contentDispositionIdx = ret.push(key, val) - 1\n } else {\n ret.push(key, val)\n }\n }\n\n // See https://github.com/nodejs/node/pull/46528\n if (hasContentLength && contentDispositionIdx !== -1) {\n ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')\n }\n\n return ret\n}\n\nfunction isBuffer (buffer) {\n // See, https://github.com/mcollina/undici/pull/319\n return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)\n}\n\nfunction validateHandler (handler, method, upgrade) {\n if (!handler || typeof handler !== 'object') {\n throw new InvalidArgumentError('handler must be an object')\n }\n\n if (typeof handler.onConnect !== 'function') {\n throw new InvalidArgumentError('invalid onConnect method')\n }\n\n if (typeof handler.onError !== 'function') {\n throw new InvalidArgumentError('invalid onError method')\n }\n\n if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {\n throw new InvalidArgumentError('invalid onBodySent method')\n }\n\n if (upgrade || method === 'CONNECT') {\n if (typeof handler.onUpgrade !== 'function') {\n throw new InvalidArgumentError('invalid onUpgrade method')\n }\n } else {\n if (typeof handler.onHeaders !== 'function') {\n throw new InvalidArgumentError('invalid onHeaders method')\n }\n\n if (typeof handler.onData !== 'function') {\n throw new InvalidArgumentError('invalid onData method')\n }\n\n if (typeof handler.onComplete !== 'function') {\n throw new InvalidArgumentError('invalid onComplete method')\n }\n }\n}\n\n// A body is disturbed if it has been read from and it cannot\n// be re-used without losing state or data.\nfunction isDisturbed (body) {\n return !!(body && (\n stream.isDisturbed\n ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?\n : body[kBodyUsed] ||\n body.readableDidRead ||\n (body._readableState && body._readableState.dataEmitted) ||\n isReadableAborted(body)\n ))\n}\n\nfunction isErrored (body) {\n return !!(body && (\n stream.isErrored\n ? stream.isErrored(body)\n : /state: 'errored'/.test(nodeUtil.inspect(body)\n )))\n}\n\nfunction isReadable (body) {\n return !!(body && (\n stream.isReadable\n ? stream.isReadable(body)\n : /state: 'readable'/.test(nodeUtil.inspect(body)\n )))\n}\n\nfunction getSocketInfo (socket) {\n return {\n localAddress: socket.localAddress,\n localPort: socket.localPort,\n remoteAddress: socket.remoteAddress,\n remotePort: socket.remotePort,\n remoteFamily: socket.remoteFamily,\n timeout: socket.timeout,\n bytesWritten: socket.bytesWritten,\n bytesRead: socket.bytesRead\n }\n}\n\nasync function * convertIterableToBuffer (iterable) {\n for await (const chunk of iterable) {\n yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n }\n}\n\nlet ReadableStream\nfunction ReadableStreamFrom (iterable) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n if (ReadableStream.from) {\n return ReadableStream.from(convertIterableToBuffer(iterable))\n }\n\n let iterator\n return new ReadableStream(\n {\n async start () {\n iterator = iterable[Symbol.asyncIterator]()\n },\n async pull (controller) {\n const { done, value } = await iterator.next()\n if (done) {\n queueMicrotask(() => {\n controller.close()\n })\n } else {\n const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)\n controller.enqueue(new Uint8Array(buf))\n }\n return controller.desiredSize > 0\n },\n async cancel (reason) {\n await iterator.return()\n }\n },\n 0\n )\n}\n\n// The chunk should be a FormData instance and contains\n// all the required methods.\nfunction isFormDataLike (object) {\n return (\n object &&\n typeof object === 'object' &&\n typeof object.append === 'function' &&\n typeof object.delete === 'function' &&\n typeof object.get === 'function' &&\n typeof object.getAll === 'function' &&\n typeof object.has === 'function' &&\n typeof object.set === 'function' &&\n object[Symbol.toStringTag] === 'FormData'\n )\n}\n\nfunction throwIfAborted (signal) {\n if (!signal) { return }\n if (typeof signal.throwIfAborted === 'function') {\n signal.throwIfAborted()\n } else {\n if (signal.aborted) {\n // DOMException not available < v17.0.0\n const err = new Error('The operation was aborted')\n err.name = 'AbortError'\n throw err\n }\n }\n}\n\nfunction addAbortListener (signal, listener) {\n if ('addEventListener' in signal) {\n signal.addEventListener('abort', listener, { once: true })\n return () => signal.removeEventListener('abort', listener)\n }\n signal.addListener('abort', listener)\n return () => signal.removeListener('abort', listener)\n}\n\nconst hasToWellFormed = !!String.prototype.toWellFormed\n\n/**\n * @param {string} val\n */\nfunction toUSVString (val) {\n if (hasToWellFormed) {\n return `${val}`.toWellFormed()\n } else if (nodeUtil.toUSVString) {\n return nodeUtil.toUSVString(val)\n }\n\n return `${val}`\n}\n\n// Parsed accordingly to RFC 9110\n// https://www.rfc-editor.org/rfc/rfc9110#field.content-range\nfunction parseRangeHeader (range) {\n if (range == null || range === '') return { start: 0, end: null, size: null }\n\n const m = range ? range.match(/^bytes (\\d+)-(\\d+)\\/(\\d+)?$/) : null\n return m\n ? {\n start: parseInt(m[1]),\n end: m[2] ? parseInt(m[2]) : null,\n size: m[3] ? parseInt(m[3]) : null\n }\n : null\n}\n\nconst kEnumerableProperty = Object.create(null)\nkEnumerableProperty.enumerable = true\n\nmodule.exports = {\n kEnumerableProperty,\n nop,\n isDisturbed,\n isErrored,\n isReadable,\n toUSVString,\n isReadableAborted,\n isBlobLike,\n parseOrigin,\n parseURL,\n getServerName,\n isStream,\n isIterable,\n isAsyncIterable,\n isDestroyed,\n headerNameToString,\n parseRawHeaders,\n parseHeaders,\n parseKeepAliveTimeout,\n destroy,\n bodyLength,\n deepClone,\n ReadableStreamFrom,\n isBuffer,\n validateHandler,\n getSocketInfo,\n isFormDataLike,\n buildURL,\n throwIfAborted,\n addAbortListener,\n parseRangeHeader,\n nodeMajor,\n nodeMinor,\n nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),\n safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']\n}\n","'use strict'\n\nconst Dispatcher = require('./dispatcher')\nconst {\n ClientDestroyedError,\n ClientClosedError,\n InvalidArgumentError\n} = require('./core/errors')\nconst { kDestroy, kClose, kDispatch, kInterceptors } = require('./core/symbols')\n\nconst kDestroyed = Symbol('destroyed')\nconst kClosed = Symbol('closed')\nconst kOnDestroyed = Symbol('onDestroyed')\nconst kOnClosed = Symbol('onClosed')\nconst kInterceptedDispatch = Symbol('Intercepted Dispatch')\n\nclass DispatcherBase extends Dispatcher {\n constructor () {\n super()\n\n this[kDestroyed] = false\n this[kOnDestroyed] = null\n this[kClosed] = false\n this[kOnClosed] = []\n }\n\n get destroyed () {\n return this[kDestroyed]\n }\n\n get closed () {\n return this[kClosed]\n }\n\n get interceptors () {\n return this[kInterceptors]\n }\n\n set interceptors (newInterceptors) {\n if (newInterceptors) {\n for (let i = newInterceptors.length - 1; i >= 0; i--) {\n const interceptor = this[kInterceptors][i]\n if (typeof interceptor !== 'function') {\n throw new InvalidArgumentError('interceptor must be an function')\n }\n }\n }\n\n this[kInterceptors] = newInterceptors\n }\n\n close (callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n this.close((err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (this[kDestroyed]) {\n queueMicrotask(() => callback(new ClientDestroyedError(), null))\n return\n }\n\n if (this[kClosed]) {\n if (this[kOnClosed]) {\n this[kOnClosed].push(callback)\n } else {\n queueMicrotask(() => callback(null, null))\n }\n return\n }\n\n this[kClosed] = true\n this[kOnClosed].push(callback)\n\n const onClosed = () => {\n const callbacks = this[kOnClosed]\n this[kOnClosed] = null\n for (let i = 0; i < callbacks.length; i++) {\n callbacks[i](null, null)\n }\n }\n\n // Should not error.\n this[kClose]()\n .then(() => this.destroy())\n .then(() => {\n queueMicrotask(onClosed)\n })\n }\n\n destroy (err, callback) {\n if (typeof err === 'function') {\n callback = err\n err = null\n }\n\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n this.destroy(err, (err, data) => {\n return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)\n })\n })\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (this[kDestroyed]) {\n if (this[kOnDestroyed]) {\n this[kOnDestroyed].push(callback)\n } else {\n queueMicrotask(() => callback(null, null))\n }\n return\n }\n\n if (!err) {\n err = new ClientDestroyedError()\n }\n\n this[kDestroyed] = true\n this[kOnDestroyed] = this[kOnDestroyed] || []\n this[kOnDestroyed].push(callback)\n\n const onDestroyed = () => {\n const callbacks = this[kOnDestroyed]\n this[kOnDestroyed] = null\n for (let i = 0; i < callbacks.length; i++) {\n callbacks[i](null, null)\n }\n }\n\n // Should not error.\n this[kDestroy](err).then(() => {\n queueMicrotask(onDestroyed)\n })\n }\n\n [kInterceptedDispatch] (opts, handler) {\n if (!this[kInterceptors] || this[kInterceptors].length === 0) {\n this[kInterceptedDispatch] = this[kDispatch]\n return this[kDispatch](opts, handler)\n }\n\n let dispatch = this[kDispatch].bind(this)\n for (let i = this[kInterceptors].length - 1; i >= 0; i--) {\n dispatch = this[kInterceptors][i](dispatch)\n }\n this[kInterceptedDispatch] = dispatch\n return dispatch(opts, handler)\n }\n\n dispatch (opts, handler) {\n if (!handler || typeof handler !== 'object') {\n throw new InvalidArgumentError('handler must be an object')\n }\n\n try {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('opts must be an object.')\n }\n\n if (this[kDestroyed] || this[kOnDestroyed]) {\n throw new ClientDestroyedError()\n }\n\n if (this[kClosed]) {\n throw new ClientClosedError()\n }\n\n return this[kInterceptedDispatch](opts, handler)\n } catch (err) {\n if (typeof handler.onError !== 'function') {\n throw new InvalidArgumentError('invalid onError method')\n }\n\n handler.onError(err)\n\n return false\n }\n }\n}\n\nmodule.exports = DispatcherBase\n","'use strict'\n\nconst EventEmitter = require('events')\n\nclass Dispatcher extends EventEmitter {\n dispatch () {\n throw new Error('not implemented')\n }\n\n close () {\n throw new Error('not implemented')\n }\n\n destroy () {\n throw new Error('not implemented')\n }\n}\n\nmodule.exports = Dispatcher\n","'use strict'\n\nconst Busboy = require('@fastify/busboy')\nconst util = require('../core/util')\nconst {\n ReadableStreamFrom,\n isBlobLike,\n isReadableStreamLike,\n readableStreamClose,\n createDeferredPromise,\n fullyReadBody\n} = require('./util')\nconst { FormData } = require('./formdata')\nconst { kState } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { DOMException, structuredClone } = require('./constants')\nconst { Blob, File: NativeFile } = require('buffer')\nconst { kBodyUsed } = require('../core/symbols')\nconst assert = require('assert')\nconst { isErrored } = require('../core/util')\nconst { isUint8Array, isArrayBuffer } = require('util/types')\nconst { File: UndiciFile } = require('./file')\nconst { parseMIMEType, serializeAMimeType } = require('./dataURL')\n\nlet ReadableStream = globalThis.ReadableStream\n\n/** @type {globalThis['File']} */\nconst File = NativeFile ?? UndiciFile\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\n// https://fetch.spec.whatwg.org/#concept-bodyinit-extract\nfunction extractBody (object, keepalive = false) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n // 1. Let stream be null.\n let stream = null\n\n // 2. If object is a ReadableStream object, then set stream to object.\n if (object instanceof ReadableStream) {\n stream = object\n } else if (isBlobLike(object)) {\n // 3. Otherwise, if object is a Blob object, set stream to the\n // result of running object’s get stream.\n stream = object.stream()\n } else {\n // 4. Otherwise, set stream to a new ReadableStream object, and set\n // up stream.\n stream = new ReadableStream({\n async pull (controller) {\n controller.enqueue(\n typeof source === 'string' ? textEncoder.encode(source) : source\n )\n queueMicrotask(() => readableStreamClose(controller))\n },\n start () {},\n type: undefined\n })\n }\n\n // 5. Assert: stream is a ReadableStream object.\n assert(isReadableStreamLike(stream))\n\n // 6. Let action be null.\n let action = null\n\n // 7. Let source be null.\n let source = null\n\n // 8. Let length be null.\n let length = null\n\n // 9. Let type be null.\n let type = null\n\n // 10. Switch on object:\n if (typeof object === 'string') {\n // Set source to the UTF-8 encoding of object.\n // Note: setting source to a Uint8Array here breaks some mocking assumptions.\n source = object\n\n // Set type to `text/plain;charset=UTF-8`.\n type = 'text/plain;charset=UTF-8'\n } else if (object instanceof URLSearchParams) {\n // URLSearchParams\n\n // spec says to run application/x-www-form-urlencoded on body.list\n // this is implemented in Node.js as apart of an URLSearchParams instance toString method\n // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490\n // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100\n\n // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.\n source = object.toString()\n\n // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.\n type = 'application/x-www-form-urlencoded;charset=UTF-8'\n } else if (isArrayBuffer(object)) {\n // BufferSource/ArrayBuffer\n\n // Set source to a copy of the bytes held by object.\n source = new Uint8Array(object.slice())\n } else if (ArrayBuffer.isView(object)) {\n // BufferSource/ArrayBufferView\n\n // Set source to a copy of the bytes held by object.\n source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))\n } else if (util.isFormDataLike(object)) {\n const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`\n const prefix = `--${boundary}\\r\\nContent-Disposition: form-data`\n\n /*! formdata-polyfill. MIT License. Jimmy Wärting */\n const escape = (str) =>\n str.replace(/\\n/g, '%0A').replace(/\\r/g, '%0D').replace(/\"/g, '%22')\n const normalizeLinefeeds = (value) => value.replace(/\\r?\\n|\\r/g, '\\r\\n')\n\n // Set action to this step: run the multipart/form-data\n // encoding algorithm, with object’s entry list and UTF-8.\n // - This ensures that the body is immutable and can't be changed afterwords\n // - That the content-length is calculated in advance.\n // - And that all parts are pre-encoded and ready to be sent.\n\n const blobParts = []\n const rn = new Uint8Array([13, 10]) // '\\r\\n'\n length = 0\n let hasUnknownSizeValue = false\n\n for (const [name, value] of object) {\n if (typeof value === 'string') {\n const chunk = textEncoder.encode(prefix +\n `; name=\"${escape(normalizeLinefeeds(name))}\"` +\n `\\r\\n\\r\\n${normalizeLinefeeds(value)}\\r\\n`)\n blobParts.push(chunk)\n length += chunk.byteLength\n } else {\n const chunk = textEncoder.encode(`${prefix}; name=\"${escape(normalizeLinefeeds(name))}\"` +\n (value.name ? `; filename=\"${escape(value.name)}\"` : '') + '\\r\\n' +\n `Content-Type: ${\n value.type || 'application/octet-stream'\n }\\r\\n\\r\\n`)\n blobParts.push(chunk, value, rn)\n if (typeof value.size === 'number') {\n length += chunk.byteLength + value.size + rn.byteLength\n } else {\n hasUnknownSizeValue = true\n }\n }\n }\n\n const chunk = textEncoder.encode(`--${boundary}--`)\n blobParts.push(chunk)\n length += chunk.byteLength\n if (hasUnknownSizeValue) {\n length = null\n }\n\n // Set source to object.\n source = object\n\n action = async function * () {\n for (const part of blobParts) {\n if (part.stream) {\n yield * part.stream()\n } else {\n yield part\n }\n }\n }\n\n // Set type to `multipart/form-data; boundary=`,\n // followed by the multipart/form-data boundary string generated\n // by the multipart/form-data encoding algorithm.\n type = 'multipart/form-data; boundary=' + boundary\n } else if (isBlobLike(object)) {\n // Blob\n\n // Set source to object.\n source = object\n\n // Set length to object’s size.\n length = object.size\n\n // If object’s type attribute is not the empty byte sequence, set\n // type to its value.\n if (object.type) {\n type = object.type\n }\n } else if (typeof object[Symbol.asyncIterator] === 'function') {\n // If keepalive is true, then throw a TypeError.\n if (keepalive) {\n throw new TypeError('keepalive')\n }\n\n // If object is disturbed or locked, then throw a TypeError.\n if (util.isDisturbed(object) || object.locked) {\n throw new TypeError(\n 'Response body object should not be disturbed or locked'\n )\n }\n\n stream =\n object instanceof ReadableStream ? object : ReadableStreamFrom(object)\n }\n\n // 11. If source is a byte sequence, then set action to a\n // step that returns source and length to source’s length.\n if (typeof source === 'string' || util.isBuffer(source)) {\n length = Buffer.byteLength(source)\n }\n\n // 12. If action is non-null, then run these steps in in parallel:\n if (action != null) {\n // Run action.\n let iterator\n stream = new ReadableStream({\n async start () {\n iterator = action(object)[Symbol.asyncIterator]()\n },\n async pull (controller) {\n const { value, done } = await iterator.next()\n if (done) {\n // When running action is done, close stream.\n queueMicrotask(() => {\n controller.close()\n })\n } else {\n // Whenever one or more bytes are available and stream is not errored,\n // enqueue a Uint8Array wrapping an ArrayBuffer containing the available\n // bytes into stream.\n if (!isErrored(stream)) {\n controller.enqueue(new Uint8Array(value))\n }\n }\n return controller.desiredSize > 0\n },\n async cancel (reason) {\n await iterator.return()\n },\n type: undefined\n })\n }\n\n // 13. Let body be a body whose stream is stream, source is source,\n // and length is length.\n const body = { stream, source, length }\n\n // 14. Return (body, type).\n return [body, type]\n}\n\n// https://fetch.spec.whatwg.org/#bodyinit-safely-extract\nfunction safelyExtractBody (object, keepalive = false) {\n if (!ReadableStream) {\n // istanbul ignore next\n ReadableStream = require('stream/web').ReadableStream\n }\n\n // To safely extract a body and a `Content-Type` value from\n // a byte sequence or BodyInit object object, run these steps:\n\n // 1. If object is a ReadableStream object, then:\n if (object instanceof ReadableStream) {\n // Assert: object is neither disturbed nor locked.\n // istanbul ignore next\n assert(!util.isDisturbed(object), 'The body has already been consumed.')\n // istanbul ignore next\n assert(!object.locked, 'The stream is locked.')\n }\n\n // 2. Return the results of extracting object.\n return extractBody(object, keepalive)\n}\n\nfunction cloneBody (body) {\n // To clone a body body, run these steps:\n\n // https://fetch.spec.whatwg.org/#concept-body-clone\n\n // 1. Let « out1, out2 » be the result of teeing body’s stream.\n const [out1, out2] = body.stream.tee()\n const out2Clone = structuredClone(out2, { transfer: [out2] })\n // This, for whatever reasons, unrefs out2Clone which allows\n // the process to exit by itself.\n const [, finalClone] = out2Clone.tee()\n\n // 2. Set body’s stream to out1.\n body.stream = out1\n\n // 3. Return a body whose stream is out2 and other members are copied from body.\n return {\n stream: finalClone,\n length: body.length,\n source: body.source\n }\n}\n\nasync function * consumeBody (body) {\n if (body) {\n if (isUint8Array(body)) {\n yield body\n } else {\n const stream = body.stream\n\n if (util.isDisturbed(stream)) {\n throw new TypeError('The body has already been consumed.')\n }\n\n if (stream.locked) {\n throw new TypeError('The stream is locked.')\n }\n\n // Compat.\n stream[kBodyUsed] = true\n\n yield * stream\n }\n }\n}\n\nfunction throwIfAborted (state) {\n if (state.aborted) {\n throw new DOMException('The operation was aborted.', 'AbortError')\n }\n}\n\nfunction bodyMixinMethods (instance) {\n const methods = {\n blob () {\n // The blob() method steps are to return the result of\n // running consume body with this and the following step\n // given a byte sequence bytes: return a Blob whose\n // contents are bytes and whose type attribute is this’s\n // MIME type.\n return specConsumeBody(this, (bytes) => {\n let mimeType = bodyMimeType(this)\n\n if (mimeType === 'failure') {\n mimeType = ''\n } else if (mimeType) {\n mimeType = serializeAMimeType(mimeType)\n }\n\n // Return a Blob whose contents are bytes and type attribute\n // is mimeType.\n return new Blob([bytes], { type: mimeType })\n }, instance)\n },\n\n arrayBuffer () {\n // The arrayBuffer() method steps are to return the result\n // of running consume body with this and the following step\n // given a byte sequence bytes: return a new ArrayBuffer\n // whose contents are bytes.\n return specConsumeBody(this, (bytes) => {\n return new Uint8Array(bytes).buffer\n }, instance)\n },\n\n text () {\n // The text() method steps are to return the result of running\n // consume body with this and UTF-8 decode.\n return specConsumeBody(this, utf8DecodeBytes, instance)\n },\n\n json () {\n // The json() method steps are to return the result of running\n // consume body with this and parse JSON from bytes.\n return specConsumeBody(this, parseJSONFromBytes, instance)\n },\n\n async formData () {\n webidl.brandCheck(this, instance)\n\n throwIfAborted(this[kState])\n\n const contentType = this.headers.get('Content-Type')\n\n // If mimeType’s essence is \"multipart/form-data\", then:\n if (/multipart\\/form-data/.test(contentType)) {\n const headers = {}\n for (const [key, value] of this.headers) headers[key.toLowerCase()] = value\n\n const responseFormData = new FormData()\n\n let busboy\n\n try {\n busboy = new Busboy({\n headers,\n preservePath: true\n })\n } catch (err) {\n throw new DOMException(`${err}`, 'AbortError')\n }\n\n busboy.on('field', (name, value) => {\n responseFormData.append(name, value)\n })\n busboy.on('file', (name, value, filename, encoding, mimeType) => {\n const chunks = []\n\n if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {\n let base64chunk = ''\n\n value.on('data', (chunk) => {\n base64chunk += chunk.toString().replace(/[\\r\\n]/gm, '')\n\n const end = base64chunk.length - base64chunk.length % 4\n chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))\n\n base64chunk = base64chunk.slice(end)\n })\n value.on('end', () => {\n chunks.push(Buffer.from(base64chunk, 'base64'))\n responseFormData.append(name, new File(chunks, filename, { type: mimeType }))\n })\n } else {\n value.on('data', (chunk) => {\n chunks.push(chunk)\n })\n value.on('end', () => {\n responseFormData.append(name, new File(chunks, filename, { type: mimeType }))\n })\n }\n })\n\n const busboyResolve = new Promise((resolve, reject) => {\n busboy.on('finish', resolve)\n busboy.on('error', (err) => reject(new TypeError(err)))\n })\n\n if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)\n busboy.end()\n await busboyResolve\n\n return responseFormData\n } else if (/application\\/x-www-form-urlencoded/.test(contentType)) {\n // Otherwise, if mimeType’s essence is \"application/x-www-form-urlencoded\", then:\n\n // 1. Let entries be the result of parsing bytes.\n let entries\n try {\n let text = ''\n // application/x-www-form-urlencoded parser will keep the BOM.\n // https://url.spec.whatwg.org/#concept-urlencoded-parser\n // Note that streaming decoder is stateful and cannot be reused\n const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })\n\n for await (const chunk of consumeBody(this[kState].body)) {\n if (!isUint8Array(chunk)) {\n throw new TypeError('Expected Uint8Array chunk')\n }\n text += streamingDecoder.decode(chunk, { stream: true })\n }\n text += streamingDecoder.decode()\n entries = new URLSearchParams(text)\n } catch (err) {\n // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.\n // 2. If entries is failure, then throw a TypeError.\n throw Object.assign(new TypeError(), { cause: err })\n }\n\n // 3. Return a new FormData object whose entries are entries.\n const formData = new FormData()\n for (const [name, value] of entries) {\n formData.append(name, value)\n }\n return formData\n } else {\n // Wait a tick before checking if the request has been aborted.\n // Otherwise, a TypeError can be thrown when an AbortError should.\n await Promise.resolve()\n\n throwIfAborted(this[kState])\n\n // Otherwise, throw a TypeError.\n throw webidl.errors.exception({\n header: `${instance.name}.formData`,\n message: 'Could not parse content as FormData.'\n })\n }\n }\n }\n\n return methods\n}\n\nfunction mixinBody (prototype) {\n Object.assign(prototype.prototype, bodyMixinMethods(prototype))\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-body-consume-body\n * @param {Response|Request} object\n * @param {(value: unknown) => unknown} convertBytesToJSValue\n * @param {Response|Request} instance\n */\nasync function specConsumeBody (object, convertBytesToJSValue, instance) {\n webidl.brandCheck(object, instance)\n\n throwIfAborted(object[kState])\n\n // 1. If object is unusable, then return a promise rejected\n // with a TypeError.\n if (bodyUnusable(object[kState].body)) {\n throw new TypeError('Body is unusable')\n }\n\n // 2. Let promise be a new promise.\n const promise = createDeferredPromise()\n\n // 3. Let errorSteps given error be to reject promise with error.\n const errorSteps = (error) => promise.reject(error)\n\n // 4. Let successSteps given a byte sequence data be to resolve\n // promise with the result of running convertBytesToJSValue\n // with data. If that threw an exception, then run errorSteps\n // with that exception.\n const successSteps = (data) => {\n try {\n promise.resolve(convertBytesToJSValue(data))\n } catch (e) {\n errorSteps(e)\n }\n }\n\n // 5. If object’s body is null, then run successSteps with an\n // empty byte sequence.\n if (object[kState].body == null) {\n successSteps(new Uint8Array())\n return promise.promise\n }\n\n // 6. Otherwise, fully read object’s body given successSteps,\n // errorSteps, and object’s relevant global object.\n await fullyReadBody(object[kState].body, successSteps, errorSteps)\n\n // 7. Return promise.\n return promise.promise\n}\n\n// https://fetch.spec.whatwg.org/#body-unusable\nfunction bodyUnusable (body) {\n // An object including the Body interface mixin is\n // said to be unusable if its body is non-null and\n // its body’s stream is disturbed or locked.\n return body != null && (body.stream.locked || util.isDisturbed(body.stream))\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#utf-8-decode\n * @param {Buffer} buffer\n */\nfunction utf8DecodeBytes (buffer) {\n if (buffer.length === 0) {\n return ''\n }\n\n // 1. Let buffer be the result of peeking three bytes from\n // ioQueue, converted to a byte sequence.\n\n // 2. If buffer is 0xEF 0xBB 0xBF, then read three\n // bytes from ioQueue. (Do nothing with those bytes.)\n if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {\n buffer = buffer.subarray(3)\n }\n\n // 3. Process a queue with an instance of UTF-8’s\n // decoder, ioQueue, output, and \"replacement\".\n const output = textDecoder.decode(buffer)\n\n // 4. Return output.\n return output\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value\n * @param {Uint8Array} bytes\n */\nfunction parseJSONFromBytes (bytes) {\n return JSON.parse(utf8DecodeBytes(bytes))\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-body-mime-type\n * @param {import('./response').Response|import('./request').Request} object\n */\nfunction bodyMimeType (object) {\n const { headersList } = object[kState]\n const contentType = headersList.get('content-type')\n\n if (contentType === null) {\n return 'failure'\n }\n\n return parseMIMEType(contentType)\n}\n\nmodule.exports = {\n extractBody,\n safelyExtractBody,\n cloneBody,\n mixinBody\n}\n","'use strict'\n\nconst { MessageChannel, receiveMessageOnPort } = require('worker_threads')\n\nconst corsSafeListedMethods = ['GET', 'HEAD', 'POST']\nconst corsSafeListedMethodsSet = new Set(corsSafeListedMethods)\n\nconst nullBodyStatus = [101, 204, 205, 304]\n\nconst redirectStatus = [301, 302, 303, 307, 308]\nconst redirectStatusSet = new Set(redirectStatus)\n\n// https://fetch.spec.whatwg.org/#block-bad-port\nconst badPorts = [\n '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',\n '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',\n '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',\n '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',\n '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',\n '10080'\n]\n\nconst badPortsSet = new Set(badPorts)\n\n// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies\nconst referrerPolicy = [\n '',\n 'no-referrer',\n 'no-referrer-when-downgrade',\n 'same-origin',\n 'origin',\n 'strict-origin',\n 'origin-when-cross-origin',\n 'strict-origin-when-cross-origin',\n 'unsafe-url'\n]\nconst referrerPolicySet = new Set(referrerPolicy)\n\nconst requestRedirect = ['follow', 'manual', 'error']\n\nconst safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']\nconst safeMethodsSet = new Set(safeMethods)\n\nconst requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']\n\nconst requestCredentials = ['omit', 'same-origin', 'include']\n\nconst requestCache = [\n 'default',\n 'no-store',\n 'reload',\n 'no-cache',\n 'force-cache',\n 'only-if-cached'\n]\n\n// https://fetch.spec.whatwg.org/#request-body-header-name\nconst requestBodyHeader = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n // See https://github.com/nodejs/undici/issues/2021\n // 'Content-Length' is a forbidden header name, which is typically\n // removed in the Headers implementation. However, undici doesn't\n // filter out headers, so we add it here.\n 'content-length'\n]\n\n// https://fetch.spec.whatwg.org/#enumdef-requestduplex\nconst requestDuplex = [\n 'half'\n]\n\n// http://fetch.spec.whatwg.org/#forbidden-method\nconst forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']\nconst forbiddenMethodsSet = new Set(forbiddenMethods)\n\nconst subresource = [\n 'audio',\n 'audioworklet',\n 'font',\n 'image',\n 'manifest',\n 'paintworklet',\n 'script',\n 'style',\n 'track',\n 'video',\n 'xslt',\n ''\n]\nconst subresourceSet = new Set(subresource)\n\n/** @type {globalThis['DOMException']} */\nconst DOMException = globalThis.DOMException ?? (() => {\n // DOMException was only made a global in Node v17.0.0,\n // but fetch supports >= v16.8.\n try {\n atob('~')\n } catch (err) {\n return Object.getPrototypeOf(err).constructor\n }\n})()\n\nlet channel\n\n/** @type {globalThis['structuredClone']} */\nconst structuredClone =\n globalThis.structuredClone ??\n // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js\n // structuredClone was added in v17.0.0, but fetch supports v16.8\n function structuredClone (value, options = undefined) {\n if (arguments.length === 0) {\n throw new TypeError('missing argument')\n }\n\n if (!channel) {\n channel = new MessageChannel()\n }\n channel.port1.unref()\n channel.port2.unref()\n channel.port1.postMessage(value, options?.transfer)\n return receiveMessageOnPort(channel.port2).message\n }\n\nmodule.exports = {\n DOMException,\n structuredClone,\n subresource,\n forbiddenMethods,\n requestBodyHeader,\n referrerPolicy,\n requestRedirect,\n requestMode,\n requestCredentials,\n requestCache,\n redirectStatus,\n corsSafeListedMethods,\n nullBodyStatus,\n safeMethods,\n badPorts,\n requestDuplex,\n subresourceSet,\n badPortsSet,\n redirectStatusSet,\n corsSafeListedMethodsSet,\n safeMethodsSet,\n forbiddenMethodsSet,\n referrerPolicySet\n}\n","const assert = require('assert')\nconst { atob } = require('buffer')\nconst { isomorphicDecode } = require('./util')\n\nconst encoder = new TextEncoder()\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#http-token-code-point\n */\nconst HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/\nconst HTTP_WHITESPACE_REGEX = /(\\u000A|\\u000D|\\u0009|\\u0020)/ // eslint-disable-line\n/**\n * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point\n */\nconst HTTP_QUOTED_STRING_TOKENS = /[\\u0009|\\u0020-\\u007E|\\u0080-\\u00FF]/ // eslint-disable-line\n\n// https://fetch.spec.whatwg.org/#data-url-processor\n/** @param {URL} dataURL */\nfunction dataURLProcessor (dataURL) {\n // 1. Assert: dataURL’s scheme is \"data\".\n assert(dataURL.protocol === 'data:')\n\n // 2. Let input be the result of running the URL\n // serializer on dataURL with exclude fragment\n // set to true.\n let input = URLSerializer(dataURL, true)\n\n // 3. Remove the leading \"data:\" string from input.\n input = input.slice(5)\n\n // 4. Let position point at the start of input.\n const position = { position: 0 }\n\n // 5. Let mimeType be the result of collecting a\n // sequence of code points that are not equal\n // to U+002C (,), given position.\n let mimeType = collectASequenceOfCodePointsFast(\n ',',\n input,\n position\n )\n\n // 6. Strip leading and trailing ASCII whitespace\n // from mimeType.\n // Undici implementation note: we need to store the\n // length because if the mimetype has spaces removed,\n // the wrong amount will be sliced from the input in\n // step #9\n const mimeTypeLength = mimeType.length\n mimeType = removeASCIIWhitespace(mimeType, true, true)\n\n // 7. If position is past the end of input, then\n // return failure\n if (position.position >= input.length) {\n return 'failure'\n }\n\n // 8. Advance position by 1.\n position.position++\n\n // 9. Let encodedBody be the remainder of input.\n const encodedBody = input.slice(mimeTypeLength + 1)\n\n // 10. Let body be the percent-decoding of encodedBody.\n let body = stringPercentDecode(encodedBody)\n\n // 11. If mimeType ends with U+003B (;), followed by\n // zero or more U+0020 SPACE, followed by an ASCII\n // case-insensitive match for \"base64\", then:\n if (/;(\\u0020){0,}base64$/i.test(mimeType)) {\n // 1. Let stringBody be the isomorphic decode of body.\n const stringBody = isomorphicDecode(body)\n\n // 2. Set body to the forgiving-base64 decode of\n // stringBody.\n body = forgivingBase64(stringBody)\n\n // 3. If body is failure, then return failure.\n if (body === 'failure') {\n return 'failure'\n }\n\n // 4. Remove the last 6 code points from mimeType.\n mimeType = mimeType.slice(0, -6)\n\n // 5. Remove trailing U+0020 SPACE code points from mimeType,\n // if any.\n mimeType = mimeType.replace(/(\\u0020)+$/, '')\n\n // 6. Remove the last U+003B (;) code point from mimeType.\n mimeType = mimeType.slice(0, -1)\n }\n\n // 12. If mimeType starts with U+003B (;), then prepend\n // \"text/plain\" to mimeType.\n if (mimeType.startsWith(';')) {\n mimeType = 'text/plain' + mimeType\n }\n\n // 13. Let mimeTypeRecord be the result of parsing\n // mimeType.\n let mimeTypeRecord = parseMIMEType(mimeType)\n\n // 14. If mimeTypeRecord is failure, then set\n // mimeTypeRecord to text/plain;charset=US-ASCII.\n if (mimeTypeRecord === 'failure') {\n mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')\n }\n\n // 15. Return a new data: URL struct whose MIME\n // type is mimeTypeRecord and body is body.\n // https://fetch.spec.whatwg.org/#data-url-struct\n return { mimeType: mimeTypeRecord, body }\n}\n\n// https://url.spec.whatwg.org/#concept-url-serializer\n/**\n * @param {URL} url\n * @param {boolean} excludeFragment\n */\nfunction URLSerializer (url, excludeFragment = false) {\n if (!excludeFragment) {\n return url.href\n }\n\n const href = url.href\n const hashLength = url.hash.length\n\n return hashLength === 0 ? href : href.substring(0, href.length - hashLength)\n}\n\n// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points\n/**\n * @param {(char: string) => boolean} condition\n * @param {string} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfCodePoints (condition, input, position) {\n // 1. Let result be the empty string.\n let result = ''\n\n // 2. While position doesn’t point past the end of input and the\n // code point at position within input meets the condition condition:\n while (position.position < input.length && condition(input[position.position])) {\n // 1. Append that code point to the end of result.\n result += input[position.position]\n\n // 2. Advance position by 1.\n position.position++\n }\n\n // 3. Return result.\n return result\n}\n\n/**\n * A faster collectASequenceOfCodePoints that only works when comparing a single character.\n * @param {string} char\n * @param {string} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfCodePointsFast (char, input, position) {\n const idx = input.indexOf(char, position.position)\n const start = position.position\n\n if (idx === -1) {\n position.position = input.length\n return input.slice(start)\n }\n\n position.position = idx\n return input.slice(start, position.position)\n}\n\n// https://url.spec.whatwg.org/#string-percent-decode\n/** @param {string} input */\nfunction stringPercentDecode (input) {\n // 1. Let bytes be the UTF-8 encoding of input.\n const bytes = encoder.encode(input)\n\n // 2. Return the percent-decoding of bytes.\n return percentDecode(bytes)\n}\n\n// https://url.spec.whatwg.org/#percent-decode\n/** @param {Uint8Array} input */\nfunction percentDecode (input) {\n // 1. Let output be an empty byte sequence.\n /** @type {number[]} */\n const output = []\n\n // 2. For each byte byte in input:\n for (let i = 0; i < input.length; i++) {\n const byte = input[i]\n\n // 1. If byte is not 0x25 (%), then append byte to output.\n if (byte !== 0x25) {\n output.push(byte)\n\n // 2. Otherwise, if byte is 0x25 (%) and the next two bytes\n // after byte in input are not in the ranges\n // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),\n // and 0x61 (a) to 0x66 (f), all inclusive, append byte\n // to output.\n } else if (\n byte === 0x25 &&\n !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))\n ) {\n output.push(0x25)\n\n // 3. Otherwise:\n } else {\n // 1. Let bytePoint be the two bytes after byte in input,\n // decoded, and then interpreted as hexadecimal number.\n const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])\n const bytePoint = Number.parseInt(nextTwoBytes, 16)\n\n // 2. Append a byte whose value is bytePoint to output.\n output.push(bytePoint)\n\n // 3. Skip the next two bytes in input.\n i += 2\n }\n }\n\n // 3. Return output.\n return Uint8Array.from(output)\n}\n\n// https://mimesniff.spec.whatwg.org/#parse-a-mime-type\n/** @param {string} input */\nfunction parseMIMEType (input) {\n // 1. Remove any leading and trailing HTTP whitespace\n // from input.\n input = removeHTTPWhitespace(input, true, true)\n\n // 2. Let position be a position variable for input,\n // initially pointing at the start of input.\n const position = { position: 0 }\n\n // 3. Let type be the result of collecting a sequence\n // of code points that are not U+002F (/) from\n // input, given position.\n const type = collectASequenceOfCodePointsFast(\n '/',\n input,\n position\n )\n\n // 4. If type is the empty string or does not solely\n // contain HTTP token code points, then return failure.\n // https://mimesniff.spec.whatwg.org/#http-token-code-point\n if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {\n return 'failure'\n }\n\n // 5. If position is past the end of input, then return\n // failure\n if (position.position > input.length) {\n return 'failure'\n }\n\n // 6. Advance position by 1. (This skips past U+002F (/).)\n position.position++\n\n // 7. Let subtype be the result of collecting a sequence of\n // code points that are not U+003B (;) from input, given\n // position.\n let subtype = collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 8. Remove any trailing HTTP whitespace from subtype.\n subtype = removeHTTPWhitespace(subtype, false, true)\n\n // 9. If subtype is the empty string or does not solely\n // contain HTTP token code points, then return failure.\n if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {\n return 'failure'\n }\n\n const typeLowercase = type.toLowerCase()\n const subtypeLowercase = subtype.toLowerCase()\n\n // 10. Let mimeType be a new MIME type record whose type\n // is type, in ASCII lowercase, and subtype is subtype,\n // in ASCII lowercase.\n // https://mimesniff.spec.whatwg.org/#mime-type\n const mimeType = {\n type: typeLowercase,\n subtype: subtypeLowercase,\n /** @type {Map} */\n parameters: new Map(),\n // https://mimesniff.spec.whatwg.org/#mime-type-essence\n essence: `${typeLowercase}/${subtypeLowercase}`\n }\n\n // 11. While position is not past the end of input:\n while (position.position < input.length) {\n // 1. Advance position by 1. (This skips past U+003B (;).)\n position.position++\n\n // 2. Collect a sequence of code points that are HTTP\n // whitespace from input given position.\n collectASequenceOfCodePoints(\n // https://fetch.spec.whatwg.org/#http-whitespace\n char => HTTP_WHITESPACE_REGEX.test(char),\n input,\n position\n )\n\n // 3. Let parameterName be the result of collecting a\n // sequence of code points that are not U+003B (;)\n // or U+003D (=) from input, given position.\n let parameterName = collectASequenceOfCodePoints(\n (char) => char !== ';' && char !== '=',\n input,\n position\n )\n\n // 4. Set parameterName to parameterName, in ASCII\n // lowercase.\n parameterName = parameterName.toLowerCase()\n\n // 5. If position is not past the end of input, then:\n if (position.position < input.length) {\n // 1. If the code point at position within input is\n // U+003B (;), then continue.\n if (input[position.position] === ';') {\n continue\n }\n\n // 2. Advance position by 1. (This skips past U+003D (=).)\n position.position++\n }\n\n // 6. If position is past the end of input, then break.\n if (position.position > input.length) {\n break\n }\n\n // 7. Let parameterValue be null.\n let parameterValue = null\n\n // 8. If the code point at position within input is\n // U+0022 (\"), then:\n if (input[position.position] === '\"') {\n // 1. Set parameterValue to the result of collecting\n // an HTTP quoted string from input, given position\n // and the extract-value flag.\n parameterValue = collectAnHTTPQuotedString(input, position, true)\n\n // 2. Collect a sequence of code points that are not\n // U+003B (;) from input, given position.\n collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 9. Otherwise:\n } else {\n // 1. Set parameterValue to the result of collecting\n // a sequence of code points that are not U+003B (;)\n // from input, given position.\n parameterValue = collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 2. Remove any trailing HTTP whitespace from parameterValue.\n parameterValue = removeHTTPWhitespace(parameterValue, false, true)\n\n // 3. If parameterValue is the empty string, then continue.\n if (parameterValue.length === 0) {\n continue\n }\n }\n\n // 10. If all of the following are true\n // - parameterName is not the empty string\n // - parameterName solely contains HTTP token code points\n // - parameterValue solely contains HTTP quoted-string token code points\n // - mimeType’s parameters[parameterName] does not exist\n // then set mimeType’s parameters[parameterName] to parameterValue.\n if (\n parameterName.length !== 0 &&\n HTTP_TOKEN_CODEPOINTS.test(parameterName) &&\n (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&\n !mimeType.parameters.has(parameterName)\n ) {\n mimeType.parameters.set(parameterName, parameterValue)\n }\n }\n\n // 12. Return mimeType.\n return mimeType\n}\n\n// https://infra.spec.whatwg.org/#forgiving-base64-decode\n/** @param {string} data */\nfunction forgivingBase64 (data) {\n // 1. Remove all ASCII whitespace from data.\n data = data.replace(/[\\u0009\\u000A\\u000C\\u000D\\u0020]/g, '') // eslint-disable-line\n\n // 2. If data’s code point length divides by 4 leaving\n // no remainder, then:\n if (data.length % 4 === 0) {\n // 1. If data ends with one or two U+003D (=) code points,\n // then remove them from data.\n data = data.replace(/=?=$/, '')\n }\n\n // 3. If data’s code point length divides by 4 leaving\n // a remainder of 1, then return failure.\n if (data.length % 4 === 1) {\n return 'failure'\n }\n\n // 4. If data contains a code point that is not one of\n // U+002B (+)\n // U+002F (/)\n // ASCII alphanumeric\n // then return failure.\n if (/[^+/0-9A-Za-z]/.test(data)) {\n return 'failure'\n }\n\n const binary = atob(data)\n const bytes = new Uint8Array(binary.length)\n\n for (let byte = 0; byte < binary.length; byte++) {\n bytes[byte] = binary.charCodeAt(byte)\n }\n\n return bytes\n}\n\n// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string\n// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string\n/**\n * @param {string} input\n * @param {{ position: number }} position\n * @param {boolean?} extractValue\n */\nfunction collectAnHTTPQuotedString (input, position, extractValue) {\n // 1. Let positionStart be position.\n const positionStart = position.position\n\n // 2. Let value be the empty string.\n let value = ''\n\n // 3. Assert: the code point at position within input\n // is U+0022 (\").\n assert(input[position.position] === '\"')\n\n // 4. Advance position by 1.\n position.position++\n\n // 5. While true:\n while (true) {\n // 1. Append the result of collecting a sequence of code points\n // that are not U+0022 (\") or U+005C (\\) from input, given\n // position, to value.\n value += collectASequenceOfCodePoints(\n (char) => char !== '\"' && char !== '\\\\',\n input,\n position\n )\n\n // 2. If position is past the end of input, then break.\n if (position.position >= input.length) {\n break\n }\n\n // 3. Let quoteOrBackslash be the code point at position within\n // input.\n const quoteOrBackslash = input[position.position]\n\n // 4. Advance position by 1.\n position.position++\n\n // 5. If quoteOrBackslash is U+005C (\\), then:\n if (quoteOrBackslash === '\\\\') {\n // 1. If position is past the end of input, then append\n // U+005C (\\) to value and break.\n if (position.position >= input.length) {\n value += '\\\\'\n break\n }\n\n // 2. Append the code point at position within input to value.\n value += input[position.position]\n\n // 3. Advance position by 1.\n position.position++\n\n // 6. Otherwise:\n } else {\n // 1. Assert: quoteOrBackslash is U+0022 (\").\n assert(quoteOrBackslash === '\"')\n\n // 2. Break.\n break\n }\n }\n\n // 6. If the extract-value flag is set, then return value.\n if (extractValue) {\n return value\n }\n\n // 7. Return the code points from positionStart to position,\n // inclusive, within input.\n return input.slice(positionStart, position.position)\n}\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type\n */\nfunction serializeAMimeType (mimeType) {\n assert(mimeType !== 'failure')\n const { parameters, essence } = mimeType\n\n // 1. Let serialization be the concatenation of mimeType’s\n // type, U+002F (/), and mimeType’s subtype.\n let serialization = essence\n\n // 2. For each name → value of mimeType’s parameters:\n for (let [name, value] of parameters.entries()) {\n // 1. Append U+003B (;) to serialization.\n serialization += ';'\n\n // 2. Append name to serialization.\n serialization += name\n\n // 3. Append U+003D (=) to serialization.\n serialization += '='\n\n // 4. If value does not solely contain HTTP token code\n // points or value is the empty string, then:\n if (!HTTP_TOKEN_CODEPOINTS.test(value)) {\n // 1. Precede each occurence of U+0022 (\") or\n // U+005C (\\) in value with U+005C (\\).\n value = value.replace(/(\\\\|\")/g, '\\\\$1')\n\n // 2. Prepend U+0022 (\") to value.\n value = '\"' + value\n\n // 3. Append U+0022 (\") to value.\n value += '\"'\n }\n\n // 5. Append value to serialization.\n serialization += value\n }\n\n // 3. Return serialization.\n return serialization\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-whitespace\n * @param {string} char\n */\nfunction isHTTPWhiteSpace (char) {\n return char === '\\r' || char === '\\n' || char === '\\t' || char === ' '\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-whitespace\n * @param {string} str\n */\nfunction removeHTTPWhitespace (str, leading = true, trailing = true) {\n let lead = 0\n let trail = str.length - 1\n\n if (leading) {\n for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);\n }\n\n if (trailing) {\n for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);\n }\n\n return str.slice(lead, trail + 1)\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#ascii-whitespace\n * @param {string} char\n */\nfunction isASCIIWhitespace (char) {\n return char === '\\r' || char === '\\n' || char === '\\t' || char === '\\f' || char === ' '\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace\n */\nfunction removeASCIIWhitespace (str, leading = true, trailing = true) {\n let lead = 0\n let trail = str.length - 1\n\n if (leading) {\n for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);\n }\n\n if (trailing) {\n for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);\n }\n\n return str.slice(lead, trail + 1)\n}\n\nmodule.exports = {\n dataURLProcessor,\n URLSerializer,\n collectASequenceOfCodePoints,\n collectASequenceOfCodePointsFast,\n stringPercentDecode,\n parseMIMEType,\n collectAnHTTPQuotedString,\n serializeAMimeType\n}\n","'use strict'\n\nconst { Blob, File: NativeFile } = require('buffer')\nconst { types } = require('util')\nconst { kState } = require('./symbols')\nconst { isBlobLike } = require('./util')\nconst { webidl } = require('./webidl')\nconst { parseMIMEType, serializeAMimeType } = require('./dataURL')\nconst { kEnumerableProperty } = require('../core/util')\nconst encoder = new TextEncoder()\n\nclass File extends Blob {\n constructor (fileBits, fileName, options = {}) {\n // The File constructor is invoked with two or three parameters, depending\n // on whether the optional dictionary parameter is used. When the File()\n // constructor is invoked, user agents must run the following steps:\n webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })\n\n fileBits = webidl.converters['sequence'](fileBits)\n fileName = webidl.converters.USVString(fileName)\n options = webidl.converters.FilePropertyBag(options)\n\n // 1. Let bytes be the result of processing blob parts given fileBits and\n // options.\n // Note: Blob handles this for us\n\n // 2. Let n be the fileName argument to the constructor.\n const n = fileName\n\n // 3. Process FilePropertyBag dictionary argument by running the following\n // substeps:\n\n // 1. If the type member is provided and is not the empty string, let t\n // be set to the type dictionary member. If t contains any characters\n // outside the range U+0020 to U+007E, then set t to the empty string\n // and return from these substeps.\n // 2. Convert every character in t to ASCII lowercase.\n let t = options.type\n let d\n\n // eslint-disable-next-line no-labels\n substep: {\n if (t) {\n t = parseMIMEType(t)\n\n if (t === 'failure') {\n t = ''\n // eslint-disable-next-line no-labels\n break substep\n }\n\n t = serializeAMimeType(t).toLowerCase()\n }\n\n // 3. If the lastModified member is provided, let d be set to the\n // lastModified dictionary member. If it is not provided, set d to the\n // current date and time represented as the number of milliseconds since\n // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).\n d = options.lastModified\n }\n\n // 4. Return a new File object F such that:\n // F refers to the bytes byte sequence.\n // F.size is set to the number of total bytes in bytes.\n // F.name is set to n.\n // F.type is set to t.\n // F.lastModified is set to d.\n\n super(processBlobParts(fileBits, options), { type: t })\n this[kState] = {\n name: n,\n lastModified: d,\n type: t\n }\n }\n\n get name () {\n webidl.brandCheck(this, File)\n\n return this[kState].name\n }\n\n get lastModified () {\n webidl.brandCheck(this, File)\n\n return this[kState].lastModified\n }\n\n get type () {\n webidl.brandCheck(this, File)\n\n return this[kState].type\n }\n}\n\nclass FileLike {\n constructor (blobLike, fileName, options = {}) {\n // TODO: argument idl type check\n\n // The File constructor is invoked with two or three parameters, depending\n // on whether the optional dictionary parameter is used. When the File()\n // constructor is invoked, user agents must run the following steps:\n\n // 1. Let bytes be the result of processing blob parts given fileBits and\n // options.\n\n // 2. Let n be the fileName argument to the constructor.\n const n = fileName\n\n // 3. Process FilePropertyBag dictionary argument by running the following\n // substeps:\n\n // 1. If the type member is provided and is not the empty string, let t\n // be set to the type dictionary member. If t contains any characters\n // outside the range U+0020 to U+007E, then set t to the empty string\n // and return from these substeps.\n // TODO\n const t = options.type\n\n // 2. Convert every character in t to ASCII lowercase.\n // TODO\n\n // 3. If the lastModified member is provided, let d be set to the\n // lastModified dictionary member. If it is not provided, set d to the\n // current date and time represented as the number of milliseconds since\n // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).\n const d = options.lastModified ?? Date.now()\n\n // 4. Return a new File object F such that:\n // F refers to the bytes byte sequence.\n // F.size is set to the number of total bytes in bytes.\n // F.name is set to n.\n // F.type is set to t.\n // F.lastModified is set to d.\n\n this[kState] = {\n blobLike,\n name: n,\n type: t,\n lastModified: d\n }\n }\n\n stream (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.stream(...args)\n }\n\n arrayBuffer (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.arrayBuffer(...args)\n }\n\n slice (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.slice(...args)\n }\n\n text (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.text(...args)\n }\n\n get size () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.size\n }\n\n get type () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.type\n }\n\n get name () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].name\n }\n\n get lastModified () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].lastModified\n }\n\n get [Symbol.toStringTag] () {\n return 'File'\n }\n}\n\nObject.defineProperties(File.prototype, {\n [Symbol.toStringTag]: {\n value: 'File',\n configurable: true\n },\n name: kEnumerableProperty,\n lastModified: kEnumerableProperty\n})\n\nwebidl.converters.Blob = webidl.interfaceConverter(Blob)\n\nwebidl.converters.BlobPart = function (V, opts) {\n if (webidl.util.Type(V) === 'Object') {\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (\n ArrayBuffer.isView(V) ||\n types.isAnyArrayBuffer(V)\n ) {\n return webidl.converters.BufferSource(V, opts)\n }\n }\n\n return webidl.converters.USVString(V, opts)\n}\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.BlobPart\n)\n\n// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag\nwebidl.converters.FilePropertyBag = webidl.dictionaryConverter([\n {\n key: 'lastModified',\n converter: webidl.converters['long long'],\n get defaultValue () {\n return Date.now()\n }\n },\n {\n key: 'type',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'endings',\n converter: (value) => {\n value = webidl.converters.DOMString(value)\n value = value.toLowerCase()\n\n if (value !== 'native') {\n value = 'transparent'\n }\n\n return value\n },\n defaultValue: 'transparent'\n }\n])\n\n/**\n * @see https://www.w3.org/TR/FileAPI/#process-blob-parts\n * @param {(NodeJS.TypedArray|Blob|string)[]} parts\n * @param {{ type: string, endings: string }} options\n */\nfunction processBlobParts (parts, options) {\n // 1. Let bytes be an empty sequence of bytes.\n /** @type {NodeJS.TypedArray[]} */\n const bytes = []\n\n // 2. For each element in parts:\n for (const element of parts) {\n // 1. If element is a USVString, run the following substeps:\n if (typeof element === 'string') {\n // 1. Let s be element.\n let s = element\n\n // 2. If the endings member of options is \"native\", set s\n // to the result of converting line endings to native\n // of element.\n if (options.endings === 'native') {\n s = convertLineEndingsNative(s)\n }\n\n // 3. Append the result of UTF-8 encoding s to bytes.\n bytes.push(encoder.encode(s))\n } else if (\n types.isAnyArrayBuffer(element) ||\n types.isTypedArray(element)\n ) {\n // 2. If element is a BufferSource, get a copy of the\n // bytes held by the buffer source, and append those\n // bytes to bytes.\n if (!element.buffer) { // ArrayBuffer\n bytes.push(new Uint8Array(element))\n } else {\n bytes.push(\n new Uint8Array(element.buffer, element.byteOffset, element.byteLength)\n )\n }\n } else if (isBlobLike(element)) {\n // 3. If element is a Blob, append the bytes it represents\n // to bytes.\n bytes.push(element)\n }\n }\n\n // 3. Return bytes.\n return bytes\n}\n\n/**\n * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native\n * @param {string} s\n */\nfunction convertLineEndingsNative (s) {\n // 1. Let native line ending be be the code point U+000A LF.\n let nativeLineEnding = '\\n'\n\n // 2. If the underlying platform’s conventions are to\n // represent newlines as a carriage return and line feed\n // sequence, set native line ending to the code point\n // U+000D CR followed by the code point U+000A LF.\n if (process.platform === 'win32') {\n nativeLineEnding = '\\r\\n'\n }\n\n return s.replace(/\\r?\\n/g, nativeLineEnding)\n}\n\n// If this function is moved to ./util.js, some tools (such as\n// rollup) will warn about circular dependencies. See:\n// https://github.com/nodejs/undici/issues/1629\nfunction isFileLike (object) {\n return (\n (NativeFile && object instanceof NativeFile) ||\n object instanceof File || (\n object &&\n (typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function') &&\n object[Symbol.toStringTag] === 'File'\n )\n )\n}\n\nmodule.exports = { File, FileLike, isFileLike }\n","'use strict'\n\nconst { isBlobLike, toUSVString, makeIterator } = require('./util')\nconst { kState } = require('./symbols')\nconst { File: UndiciFile, FileLike, isFileLike } = require('./file')\nconst { webidl } = require('./webidl')\nconst { Blob, File: NativeFile } = require('buffer')\n\n/** @type {globalThis['File']} */\nconst File = NativeFile ?? UndiciFile\n\n// https://xhr.spec.whatwg.org/#formdata\nclass FormData {\n constructor (form) {\n if (form !== undefined) {\n throw webidl.errors.conversionFailed({\n prefix: 'FormData constructor',\n argument: 'Argument 1',\n types: ['undefined']\n })\n }\n\n this[kState] = []\n }\n\n append (name, value, filename = undefined) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })\n\n if (arguments.length === 3 && !isBlobLike(value)) {\n throw new TypeError(\n \"Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'\"\n )\n }\n\n // 1. Let value be value if given; otherwise blobValue.\n\n name = webidl.converters.USVString(name)\n value = isBlobLike(value)\n ? webidl.converters.Blob(value, { strict: false })\n : webidl.converters.USVString(value)\n filename = arguments.length === 3\n ? webidl.converters.USVString(filename)\n : undefined\n\n // 2. Let entry be the result of creating an entry with\n // name, value, and filename if given.\n const entry = makeEntry(name, value, filename)\n\n // 3. Append entry to this’s entry list.\n this[kState].push(entry)\n }\n\n delete (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })\n\n name = webidl.converters.USVString(name)\n\n // The delete(name) method steps are to remove all entries whose name\n // is name from this’s entry list.\n this[kState] = this[kState].filter(entry => entry.name !== name)\n }\n\n get (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })\n\n name = webidl.converters.USVString(name)\n\n // 1. If there is no entry whose name is name in this’s entry list,\n // then return null.\n const idx = this[kState].findIndex((entry) => entry.name === name)\n if (idx === -1) {\n return null\n }\n\n // 2. Return the value of the first entry whose name is name from\n // this’s entry list.\n return this[kState][idx].value\n }\n\n getAll (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })\n\n name = webidl.converters.USVString(name)\n\n // 1. If there is no entry whose name is name in this’s entry list,\n // then return the empty list.\n // 2. Return the values of all entries whose name is name, in order,\n // from this’s entry list.\n return this[kState]\n .filter((entry) => entry.name === name)\n .map((entry) => entry.value)\n }\n\n has (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })\n\n name = webidl.converters.USVString(name)\n\n // The has(name) method steps are to return true if there is an entry\n // whose name is name in this’s entry list; otherwise false.\n return this[kState].findIndex((entry) => entry.name === name) !== -1\n }\n\n set (name, value, filename = undefined) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })\n\n if (arguments.length === 3 && !isBlobLike(value)) {\n throw new TypeError(\n \"Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'\"\n )\n }\n\n // The set(name, value) and set(name, blobValue, filename) method steps\n // are:\n\n // 1. Let value be value if given; otherwise blobValue.\n\n name = webidl.converters.USVString(name)\n value = isBlobLike(value)\n ? webidl.converters.Blob(value, { strict: false })\n : webidl.converters.USVString(value)\n filename = arguments.length === 3\n ? toUSVString(filename)\n : undefined\n\n // 2. Let entry be the result of creating an entry with name, value, and\n // filename if given.\n const entry = makeEntry(name, value, filename)\n\n // 3. If there are entries in this’s entry list whose name is name, then\n // replace the first such entry with entry and remove the others.\n const idx = this[kState].findIndex((entry) => entry.name === name)\n if (idx !== -1) {\n this[kState] = [\n ...this[kState].slice(0, idx),\n entry,\n ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)\n ]\n } else {\n // 4. Otherwise, append entry to this’s entry list.\n this[kState].push(entry)\n }\n }\n\n entries () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'key+value'\n )\n }\n\n keys () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'key'\n )\n }\n\n values () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'value'\n )\n }\n\n /**\n * @param {(value: string, key: string, self: FormData) => void} callbackFn\n * @param {unknown} thisArg\n */\n forEach (callbackFn, thisArg = globalThis) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })\n\n if (typeof callbackFn !== 'function') {\n throw new TypeError(\n \"Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'.\"\n )\n }\n\n for (const [key, value] of this) {\n callbackFn.apply(thisArg, [value, key, this])\n }\n }\n}\n\nFormData.prototype[Symbol.iterator] = FormData.prototype.entries\n\nObject.defineProperties(FormData.prototype, {\n [Symbol.toStringTag]: {\n value: 'FormData',\n configurable: true\n }\n})\n\n/**\n * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry\n * @param {string} name\n * @param {string|Blob} value\n * @param {?string} filename\n * @returns\n */\nfunction makeEntry (name, value, filename) {\n // 1. Set name to the result of converting name into a scalar value string.\n // \"To convert a string into a scalar value string, replace any surrogates\n // with U+FFFD.\"\n // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end\n name = Buffer.from(name).toString('utf8')\n\n // 2. If value is a string, then set value to the result of converting\n // value into a scalar value string.\n if (typeof value === 'string') {\n value = Buffer.from(value).toString('utf8')\n } else {\n // 3. Otherwise:\n\n // 1. If value is not a File object, then set value to a new File object,\n // representing the same bytes, whose name attribute value is \"blob\"\n if (!isFileLike(value)) {\n value = value instanceof Blob\n ? new File([value], 'blob', { type: value.type })\n : new FileLike(value, 'blob', { type: value.type })\n }\n\n // 2. If filename is given, then set value to a new File object,\n // representing the same bytes, whose name attribute is filename.\n if (filename !== undefined) {\n /** @type {FilePropertyBag} */\n const options = {\n type: value.type,\n lastModified: value.lastModified\n }\n\n value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile\n ? new File([value], filename, options)\n : new FileLike(value, filename, options)\n }\n }\n\n // 4. Return an entry whose name is name and whose value is value.\n return { name, value }\n}\n\nmodule.exports = { FormData }\n","'use strict'\n\n// In case of breaking changes, increase the version\n// number to avoid conflicts.\nconst globalOrigin = Symbol.for('undici.globalOrigin.1')\n\nfunction getGlobalOrigin () {\n return globalThis[globalOrigin]\n}\n\nfunction setGlobalOrigin (newOrigin) {\n if (newOrigin === undefined) {\n Object.defineProperty(globalThis, globalOrigin, {\n value: undefined,\n writable: true,\n enumerable: false,\n configurable: false\n })\n\n return\n }\n\n const parsedURL = new URL(newOrigin)\n\n if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {\n throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)\n }\n\n Object.defineProperty(globalThis, globalOrigin, {\n value: parsedURL,\n writable: true,\n enumerable: false,\n configurable: false\n })\n}\n\nmodule.exports = {\n getGlobalOrigin,\n setGlobalOrigin\n}\n","// https://github.com/Ethan-Arrowood/undici-fetch\n\n'use strict'\n\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst { kGuard } = require('./symbols')\nconst { kEnumerableProperty } = require('../core/util')\nconst {\n makeIterator,\n isValidHeaderName,\n isValidHeaderValue\n} = require('./util')\nconst { webidl } = require('./webidl')\nconst assert = require('assert')\n\nconst kHeadersMap = Symbol('headers map')\nconst kHeadersSortedMap = Symbol('headers map sorted')\n\n/**\n * @param {number} code\n */\nfunction isHTTPWhiteSpaceCharCode (code) {\n return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize\n * @param {string} potentialValue\n */\nfunction headerValueNormalize (potentialValue) {\n // To normalize a byte sequence potentialValue, remove\n // any leading and trailing HTTP whitespace bytes from\n // potentialValue.\n let i = 0; let j = potentialValue.length\n\n while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j\n while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i\n\n return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)\n}\n\nfunction fill (headers, object) {\n // To fill a Headers object headers with a given object object, run these steps:\n\n // 1. If object is a sequence, then for each header in object:\n // Note: webidl conversion to array has already been done.\n if (Array.isArray(object)) {\n for (let i = 0; i < object.length; ++i) {\n const header = object[i]\n // 1. If header does not contain exactly two items, then throw a TypeError.\n if (header.length !== 2) {\n throw webidl.errors.exception({\n header: 'Headers constructor',\n message: `expected name/value pair to be length 2, found ${header.length}.`\n })\n }\n\n // 2. Append (header’s first item, header’s second item) to headers.\n appendHeader(headers, header[0], header[1])\n }\n } else if (typeof object === 'object' && object !== null) {\n // Note: null should throw\n\n // 2. Otherwise, object is a record, then for each key → value in object,\n // append (key, value) to headers\n const keys = Object.keys(object)\n for (let i = 0; i < keys.length; ++i) {\n appendHeader(headers, keys[i], object[keys[i]])\n }\n } else {\n throw webidl.errors.conversionFailed({\n prefix: 'Headers constructor',\n argument: 'Argument 1',\n types: ['sequence>', 'record']\n })\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-headers-append\n */\nfunction appendHeader (headers, name, value) {\n // 1. Normalize value.\n value = headerValueNormalize(value)\n\n // 2. If name is not a header name or value is not a\n // header value, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.append',\n value: name,\n type: 'header name'\n })\n } else if (!isValidHeaderValue(value)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.append',\n value,\n type: 'header value'\n })\n }\n\n // 3. If headers’s guard is \"immutable\", then throw a TypeError.\n // 4. Otherwise, if headers’s guard is \"request\" and name is a\n // forbidden header name, return.\n // Note: undici does not implement forbidden header names\n if (headers[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (headers[kGuard] === 'request-no-cors') {\n // 5. Otherwise, if headers’s guard is \"request-no-cors\":\n // TODO\n }\n\n // 6. Otherwise, if headers’s guard is \"response\" and name is a\n // forbidden response-header name, return.\n\n // 7. Append (name, value) to headers’s header list.\n return headers[kHeadersList].append(name, value)\n\n // 8. If headers’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from headers\n}\n\nclass HeadersList {\n /** @type {[string, string][]|null} */\n cookies = null\n\n constructor (init) {\n if (init instanceof HeadersList) {\n this[kHeadersMap] = new Map(init[kHeadersMap])\n this[kHeadersSortedMap] = init[kHeadersSortedMap]\n this.cookies = init.cookies === null ? null : [...init.cookies]\n } else {\n this[kHeadersMap] = new Map(init)\n this[kHeadersSortedMap] = null\n }\n }\n\n // https://fetch.spec.whatwg.org/#header-list-contains\n contains (name) {\n // A header list list contains a header name name if list\n // contains a header whose name is a byte-case-insensitive\n // match for name.\n name = name.toLowerCase()\n\n return this[kHeadersMap].has(name)\n }\n\n clear () {\n this[kHeadersMap].clear()\n this[kHeadersSortedMap] = null\n this.cookies = null\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-append\n append (name, value) {\n this[kHeadersSortedMap] = null\n\n // 1. If list contains name, then set name to the first such\n // header’s name.\n const lowercaseName = name.toLowerCase()\n const exists = this[kHeadersMap].get(lowercaseName)\n\n // 2. Append (name, value) to list.\n if (exists) {\n const delimiter = lowercaseName === 'cookie' ? '; ' : ', '\n this[kHeadersMap].set(lowercaseName, {\n name: exists.name,\n value: `${exists.value}${delimiter}${value}`\n })\n } else {\n this[kHeadersMap].set(lowercaseName, { name, value })\n }\n\n if (lowercaseName === 'set-cookie') {\n this.cookies ??= []\n this.cookies.push(value)\n }\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-set\n set (name, value) {\n this[kHeadersSortedMap] = null\n const lowercaseName = name.toLowerCase()\n\n if (lowercaseName === 'set-cookie') {\n this.cookies = [value]\n }\n\n // 1. If list contains name, then set the value of\n // the first such header to value and remove the\n // others.\n // 2. Otherwise, append header (name, value) to list.\n this[kHeadersMap].set(lowercaseName, { name, value })\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-delete\n delete (name) {\n this[kHeadersSortedMap] = null\n\n name = name.toLowerCase()\n\n if (name === 'set-cookie') {\n this.cookies = null\n }\n\n this[kHeadersMap].delete(name)\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-get\n get (name) {\n const value = this[kHeadersMap].get(name.toLowerCase())\n\n // 1. If list does not contain name, then return null.\n // 2. Return the values of all headers in list whose name\n // is a byte-case-insensitive match for name,\n // separated from each other by 0x2C 0x20, in order.\n return value === undefined ? null : value.value\n }\n\n * [Symbol.iterator] () {\n // use the lowercased name\n for (const [name, { value }] of this[kHeadersMap]) {\n yield [name, value]\n }\n }\n\n get entries () {\n const headers = {}\n\n if (this[kHeadersMap].size) {\n for (const { name, value } of this[kHeadersMap].values()) {\n headers[name] = value\n }\n }\n\n return headers\n }\n}\n\n// https://fetch.spec.whatwg.org/#headers-class\nclass Headers {\n constructor (init = undefined) {\n if (init === kConstruct) {\n return\n }\n this[kHeadersList] = new HeadersList()\n\n // The new Headers(init) constructor steps are:\n\n // 1. Set this’s guard to \"none\".\n this[kGuard] = 'none'\n\n // 2. If init is given, then fill this with init.\n if (init !== undefined) {\n init = webidl.converters.HeadersInit(init)\n fill(this, init)\n }\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-append\n append (name, value) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })\n\n name = webidl.converters.ByteString(name)\n value = webidl.converters.ByteString(value)\n\n return appendHeader(this, name, value)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-delete\n delete (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.delete',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. If this’s guard is \"immutable\", then throw a TypeError.\n // 3. Otherwise, if this’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 4. Otherwise, if this’s guard is \"request-no-cors\", name\n // is not a no-CORS-safelisted request-header name, and\n // name is not a privileged no-CORS request-header name,\n // return.\n // 5. Otherwise, if this’s guard is \"response\" and name is\n // a forbidden response-header name, return.\n // Note: undici does not implement forbidden header names\n if (this[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (this[kGuard] === 'request-no-cors') {\n // TODO\n }\n\n // 6. If this’s header list does not contain name, then\n // return.\n if (!this[kHeadersList].contains(name)) {\n return\n }\n\n // 7. Delete name from this’s header list.\n // 8. If this’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from this.\n this[kHeadersList].delete(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-get\n get (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.get',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. Return the result of getting name from this’s header\n // list.\n return this[kHeadersList].get(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-has\n has (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.has',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. Return true if this’s header list contains name;\n // otherwise false.\n return this[kHeadersList].contains(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-set\n set (name, value) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })\n\n name = webidl.converters.ByteString(name)\n value = webidl.converters.ByteString(value)\n\n // 1. Normalize value.\n value = headerValueNormalize(value)\n\n // 2. If name is not a header name or value is not a\n // header value, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.set',\n value: name,\n type: 'header name'\n })\n } else if (!isValidHeaderValue(value)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.set',\n value,\n type: 'header value'\n })\n }\n\n // 3. If this’s guard is \"immutable\", then throw a TypeError.\n // 4. Otherwise, if this’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 5. Otherwise, if this’s guard is \"request-no-cors\" and\n // name/value is not a no-CORS-safelisted request-header,\n // return.\n // 6. Otherwise, if this’s guard is \"response\" and name is a\n // forbidden response-header name, return.\n // Note: undici does not implement forbidden header names\n if (this[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (this[kGuard] === 'request-no-cors') {\n // TODO\n }\n\n // 7. Set (name, value) in this’s header list.\n // 8. If this’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from this\n this[kHeadersList].set(name, value)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie\n getSetCookie () {\n webidl.brandCheck(this, Headers)\n\n // 1. If this’s header list does not contain `Set-Cookie`, then return « ».\n // 2. Return the values of all headers in this’s header list whose name is\n // a byte-case-insensitive match for `Set-Cookie`, in order.\n\n const list = this[kHeadersList].cookies\n\n if (list) {\n return [...list]\n }\n\n return []\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n get [kHeadersSortedMap] () {\n if (this[kHeadersList][kHeadersSortedMap]) {\n return this[kHeadersList][kHeadersSortedMap]\n }\n\n // 1. Let headers be an empty list of headers with the key being the name\n // and value the value.\n const headers = []\n\n // 2. Let names be the result of convert header names to a sorted-lowercase\n // set with all the names of the headers in list.\n const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)\n const cookies = this[kHeadersList].cookies\n\n // 3. For each name of names:\n for (let i = 0; i < names.length; ++i) {\n const [name, value] = names[i]\n // 1. If name is `set-cookie`, then:\n if (name === 'set-cookie') {\n // 1. Let values be a list of all values of headers in list whose name\n // is a byte-case-insensitive match for name, in order.\n\n // 2. For each value of values:\n // 1. Append (name, value) to headers.\n for (let j = 0; j < cookies.length; ++j) {\n headers.push([name, cookies[j]])\n }\n } else {\n // 2. Otherwise:\n\n // 1. Let value be the result of getting name from list.\n\n // 2. Assert: value is non-null.\n assert(value !== null)\n\n // 3. Append (name, value) to headers.\n headers.push([name, value])\n }\n }\n\n this[kHeadersList][kHeadersSortedMap] = headers\n\n // 4. Return headers.\n return headers\n }\n\n keys () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'key')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'key'\n )\n }\n\n values () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'value')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'value'\n )\n }\n\n entries () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'key+value')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'key+value'\n )\n }\n\n /**\n * @param {(value: string, key: string, self: Headers) => void} callbackFn\n * @param {unknown} thisArg\n */\n forEach (callbackFn, thisArg = globalThis) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })\n\n if (typeof callbackFn !== 'function') {\n throw new TypeError(\n \"Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'.\"\n )\n }\n\n for (const [key, value] of this) {\n callbackFn.apply(thisArg, [value, key, this])\n }\n }\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n webidl.brandCheck(this, Headers)\n\n return this[kHeadersList]\n }\n}\n\nHeaders.prototype[Symbol.iterator] = Headers.prototype.entries\n\nObject.defineProperties(Headers.prototype, {\n append: kEnumerableProperty,\n delete: kEnumerableProperty,\n get: kEnumerableProperty,\n has: kEnumerableProperty,\n set: kEnumerableProperty,\n getSetCookie: kEnumerableProperty,\n keys: kEnumerableProperty,\n values: kEnumerableProperty,\n entries: kEnumerableProperty,\n forEach: kEnumerableProperty,\n [Symbol.iterator]: { enumerable: false },\n [Symbol.toStringTag]: {\n value: 'Headers',\n configurable: true\n }\n})\n\nwebidl.converters.HeadersInit = function (V) {\n if (webidl.util.Type(V) === 'Object') {\n if (V[Symbol.iterator]) {\n return webidl.converters['sequence>'](V)\n }\n\n return webidl.converters['record'](V)\n }\n\n throw webidl.errors.conversionFailed({\n prefix: 'Headers constructor',\n argument: 'Argument 1',\n types: ['sequence>', 'record']\n })\n}\n\nmodule.exports = {\n fill,\n Headers,\n HeadersList\n}\n","// https://github.com/Ethan-Arrowood/undici-fetch\n\n'use strict'\n\nconst {\n Response,\n makeNetworkError,\n makeAppropriateNetworkError,\n filterResponse,\n makeResponse\n} = require('./response')\nconst { Headers } = require('./headers')\nconst { Request, makeRequest } = require('./request')\nconst zlib = require('zlib')\nconst {\n bytesMatch,\n makePolicyContainer,\n clonePolicyContainer,\n requestBadPort,\n TAOCheck,\n appendRequestOriginHeader,\n responseLocationURL,\n requestCurrentURL,\n setRequestReferrerPolicyOnRedirect,\n tryUpgradeRequestToAPotentiallyTrustworthyURL,\n createOpaqueTimingInfo,\n appendFetchMetadata,\n corsCheck,\n crossOriginResourcePolicyCheck,\n determineRequestsReferrer,\n coarsenedSharedCurrentTime,\n createDeferredPromise,\n isBlobLike,\n sameOrigin,\n isCancelled,\n isAborted,\n isErrorLike,\n fullyReadBody,\n readableStreamClose,\n isomorphicEncode,\n urlIsLocal,\n urlIsHttpHttpsScheme,\n urlHasHttpsScheme\n} = require('./util')\nconst { kState, kHeaders, kGuard, kRealm } = require('./symbols')\nconst assert = require('assert')\nconst { safelyExtractBody } = require('./body')\nconst {\n redirectStatusSet,\n nullBodyStatus,\n safeMethodsSet,\n requestBodyHeader,\n subresourceSet,\n DOMException\n} = require('./constants')\nconst { kHeadersList } = require('../core/symbols')\nconst EE = require('events')\nconst { Readable, pipeline } = require('stream')\nconst { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = require('../core/util')\nconst { dataURLProcessor, serializeAMimeType } = require('./dataURL')\nconst { TransformStream } = require('stream/web')\nconst { getGlobalDispatcher } = require('../global')\nconst { webidl } = require('./webidl')\nconst { STATUS_CODES } = require('http')\nconst GET_OR_HEAD = ['GET', 'HEAD']\n\n/** @type {import('buffer').resolveObjectURL} */\nlet resolveObjectURL\nlet ReadableStream = globalThis.ReadableStream\n\nclass Fetch extends EE {\n constructor (dispatcher) {\n super()\n\n this.dispatcher = dispatcher\n this.connection = null\n this.dump = false\n this.state = 'ongoing'\n // 2 terminated listeners get added per request,\n // but only 1 gets removed. If there are 20 redirects,\n // 21 listeners will be added.\n // See https://github.com/nodejs/undici/issues/1711\n // TODO (fix): Find and fix root cause for leaked listener.\n this.setMaxListeners(21)\n }\n\n terminate (reason) {\n if (this.state !== 'ongoing') {\n return\n }\n\n this.state = 'terminated'\n this.connection?.destroy(reason)\n this.emit('terminated', reason)\n }\n\n // https://fetch.spec.whatwg.org/#fetch-controller-abort\n abort (error) {\n if (this.state !== 'ongoing') {\n return\n }\n\n // 1. Set controller’s state to \"aborted\".\n this.state = 'aborted'\n\n // 2. Let fallbackError be an \"AbortError\" DOMException.\n // 3. Set error to fallbackError if it is not given.\n if (!error) {\n error = new DOMException('The operation was aborted.', 'AbortError')\n }\n\n // 4. Let serializedError be StructuredSerialize(error).\n // If that threw an exception, catch it, and let\n // serializedError be StructuredSerialize(fallbackError).\n\n // 5. Set controller’s serialized abort reason to serializedError.\n this.serializedAbortReason = error\n\n this.connection?.destroy(error)\n this.emit('terminated', error)\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetch-method\nfunction fetch (input, init = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })\n\n // 1. Let p be a new promise.\n const p = createDeferredPromise()\n\n // 2. Let requestObject be the result of invoking the initial value of\n // Request as constructor with input and init as arguments. If this throws\n // an exception, reject p with it and return p.\n let requestObject\n\n try {\n requestObject = new Request(input, init)\n } catch (e) {\n p.reject(e)\n return p.promise\n }\n\n // 3. Let request be requestObject’s request.\n const request = requestObject[kState]\n\n // 4. If requestObject’s signal’s aborted flag is set, then:\n if (requestObject.signal.aborted) {\n // 1. Abort the fetch() call with p, request, null, and\n // requestObject’s signal’s abort reason.\n abortFetch(p, request, null, requestObject.signal.reason)\n\n // 2. Return p.\n return p.promise\n }\n\n // 5. Let globalObject be request’s client’s global object.\n const globalObject = request.client.globalObject\n\n // 6. If globalObject is a ServiceWorkerGlobalScope object, then set\n // request’s service-workers mode to \"none\".\n if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {\n request.serviceWorkers = 'none'\n }\n\n // 7. Let responseObject be null.\n let responseObject = null\n\n // 8. Let relevantRealm be this’s relevant Realm.\n const relevantRealm = null\n\n // 9. Let locallyAborted be false.\n let locallyAborted = false\n\n // 10. Let controller be null.\n let controller = null\n\n // 11. Add the following abort steps to requestObject’s signal:\n addAbortListener(\n requestObject.signal,\n () => {\n // 1. Set locallyAborted to true.\n locallyAborted = true\n\n // 2. Assert: controller is non-null.\n assert(controller != null)\n\n // 3. Abort controller with requestObject’s signal’s abort reason.\n controller.abort(requestObject.signal.reason)\n\n // 4. Abort the fetch() call with p, request, responseObject,\n // and requestObject’s signal’s abort reason.\n abortFetch(p, request, responseObject, requestObject.signal.reason)\n }\n )\n\n // 12. Let handleFetchDone given response response be to finalize and\n // report timing with response, globalObject, and \"fetch\".\n const handleFetchDone = (response) =>\n finalizeAndReportTiming(response, 'fetch')\n\n // 13. Set controller to the result of calling fetch given request,\n // with processResponseEndOfBody set to handleFetchDone, and processResponse\n // given response being these substeps:\n\n const processResponse = (response) => {\n // 1. If locallyAborted is true, terminate these substeps.\n if (locallyAborted) {\n return Promise.resolve()\n }\n\n // 2. If response’s aborted flag is set, then:\n if (response.aborted) {\n // 1. Let deserializedError be the result of deserialize a serialized\n // abort reason given controller’s serialized abort reason and\n // relevantRealm.\n\n // 2. Abort the fetch() call with p, request, responseObject, and\n // deserializedError.\n\n abortFetch(p, request, responseObject, controller.serializedAbortReason)\n return Promise.resolve()\n }\n\n // 3. If response is a network error, then reject p with a TypeError\n // and terminate these substeps.\n if (response.type === 'error') {\n p.reject(\n Object.assign(new TypeError('fetch failed'), { cause: response.error })\n )\n return Promise.resolve()\n }\n\n // 4. Set responseObject to the result of creating a Response object,\n // given response, \"immutable\", and relevantRealm.\n responseObject = new Response()\n responseObject[kState] = response\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kHeadersList] = response.headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 5. Resolve p with responseObject.\n p.resolve(responseObject)\n }\n\n controller = fetching({\n request,\n processResponseEndOfBody: handleFetchDone,\n processResponse,\n dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici\n })\n\n // 14. Return p.\n return p.promise\n}\n\n// https://fetch.spec.whatwg.org/#finalize-and-report-timing\nfunction finalizeAndReportTiming (response, initiatorType = 'other') {\n // 1. If response is an aborted network error, then return.\n if (response.type === 'error' && response.aborted) {\n return\n }\n\n // 2. If response’s URL list is null or empty, then return.\n if (!response.urlList?.length) {\n return\n }\n\n // 3. Let originalURL be response’s URL list[0].\n const originalURL = response.urlList[0]\n\n // 4. Let timingInfo be response’s timing info.\n let timingInfo = response.timingInfo\n\n // 5. Let cacheState be response’s cache state.\n let cacheState = response.cacheState\n\n // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.\n if (!urlIsHttpHttpsScheme(originalURL)) {\n return\n }\n\n // 7. If timingInfo is null, then return.\n if (timingInfo === null) {\n return\n }\n\n // 8. If response’s timing allow passed flag is not set, then:\n if (!response.timingAllowPassed) {\n // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.\n timingInfo = createOpaqueTimingInfo({\n startTime: timingInfo.startTime\n })\n\n // 2. Set cacheState to the empty string.\n cacheState = ''\n }\n\n // 9. Set timingInfo’s end time to the coarsened shared current time\n // given global’s relevant settings object’s cross-origin isolated\n // capability.\n // TODO: given global’s relevant settings object’s cross-origin isolated\n // capability?\n timingInfo.endTime = coarsenedSharedCurrentTime()\n\n // 10. Set response’s timing info to timingInfo.\n response.timingInfo = timingInfo\n\n // 11. Mark resource timing for timingInfo, originalURL, initiatorType,\n // global, and cacheState.\n markResourceTiming(\n timingInfo,\n originalURL,\n initiatorType,\n globalThis,\n cacheState\n )\n}\n\n// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing\nfunction markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {\n if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {\n performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)\n }\n}\n\n// https://fetch.spec.whatwg.org/#abort-fetch\nfunction abortFetch (p, request, responseObject, error) {\n // Note: AbortSignal.reason was added in node v17.2.0\n // which would give us an undefined error to reject with.\n // Remove this once node v16 is no longer supported.\n if (!error) {\n error = new DOMException('The operation was aborted.', 'AbortError')\n }\n\n // 1. Reject promise with error.\n p.reject(error)\n\n // 2. If request’s body is not null and is readable, then cancel request’s\n // body with error.\n if (request.body != null && isReadable(request.body?.stream)) {\n request.body.stream.cancel(error).catch((err) => {\n if (err.code === 'ERR_INVALID_STATE') {\n // Node bug?\n return\n }\n throw err\n })\n }\n\n // 3. If responseObject is null, then return.\n if (responseObject == null) {\n return\n }\n\n // 4. Let response be responseObject’s response.\n const response = responseObject[kState]\n\n // 5. If response’s body is not null and is readable, then error response’s\n // body with error.\n if (response.body != null && isReadable(response.body?.stream)) {\n response.body.stream.cancel(error).catch((err) => {\n if (err.code === 'ERR_INVALID_STATE') {\n // Node bug?\n return\n }\n throw err\n })\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetching\nfunction fetching ({\n request,\n processRequestBodyChunkLength,\n processRequestEndOfBody,\n processResponse,\n processResponseEndOfBody,\n processResponseConsumeBody,\n useParallelQueue = false,\n dispatcher // undici\n}) {\n // 1. Let taskDestination be null.\n let taskDestination = null\n\n // 2. Let crossOriginIsolatedCapability be false.\n let crossOriginIsolatedCapability = false\n\n // 3. If request’s client is non-null, then:\n if (request.client != null) {\n // 1. Set taskDestination to request’s client’s global object.\n taskDestination = request.client.globalObject\n\n // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin\n // isolated capability.\n crossOriginIsolatedCapability =\n request.client.crossOriginIsolatedCapability\n }\n\n // 4. If useParallelQueue is true, then set taskDestination to the result of\n // starting a new parallel queue.\n // TODO\n\n // 5. Let timingInfo be a new fetch timing info whose start time and\n // post-redirect start time are the coarsened shared current time given\n // crossOriginIsolatedCapability.\n const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)\n const timingInfo = createOpaqueTimingInfo({\n startTime: currenTime\n })\n\n // 6. Let fetchParams be a new fetch params whose\n // request is request,\n // timing info is timingInfo,\n // process request body chunk length is processRequestBodyChunkLength,\n // process request end-of-body is processRequestEndOfBody,\n // process response is processResponse,\n // process response consume body is processResponseConsumeBody,\n // process response end-of-body is processResponseEndOfBody,\n // task destination is taskDestination,\n // and cross-origin isolated capability is crossOriginIsolatedCapability.\n const fetchParams = {\n controller: new Fetch(dispatcher),\n request,\n timingInfo,\n processRequestBodyChunkLength,\n processRequestEndOfBody,\n processResponse,\n processResponseConsumeBody,\n processResponseEndOfBody,\n taskDestination,\n crossOriginIsolatedCapability\n }\n\n // 7. If request’s body is a byte sequence, then set request’s body to\n // request’s body as a body.\n // NOTE: Since fetching is only called from fetch, body should already be\n // extracted.\n assert(!request.body || request.body.stream)\n\n // 8. If request’s window is \"client\", then set request’s window to request’s\n // client, if request’s client’s global object is a Window object; otherwise\n // \"no-window\".\n if (request.window === 'client') {\n // TODO: What if request.client is null?\n request.window =\n request.client?.globalObject?.constructor?.name === 'Window'\n ? request.client\n : 'no-window'\n }\n\n // 9. If request’s origin is \"client\", then set request’s origin to request’s\n // client’s origin.\n if (request.origin === 'client') {\n // TODO: What if request.client is null?\n request.origin = request.client?.origin\n }\n\n // 10. If all of the following conditions are true:\n // TODO\n\n // 11. If request’s policy container is \"client\", then:\n if (request.policyContainer === 'client') {\n // 1. If request’s client is non-null, then set request’s policy\n // container to a clone of request’s client’s policy container. [HTML]\n if (request.client != null) {\n request.policyContainer = clonePolicyContainer(\n request.client.policyContainer\n )\n } else {\n // 2. Otherwise, set request’s policy container to a new policy\n // container.\n request.policyContainer = makePolicyContainer()\n }\n }\n\n // 12. If request’s header list does not contain `Accept`, then:\n if (!request.headersList.contains('accept')) {\n // 1. Let value be `*/*`.\n const value = '*/*'\n\n // 2. A user agent should set value to the first matching statement, if\n // any, switching on request’s destination:\n // \"document\"\n // \"frame\"\n // \"iframe\"\n // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`\n // \"image\"\n // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`\n // \"style\"\n // `text/css,*/*;q=0.1`\n // TODO\n\n // 3. Append `Accept`/value to request’s header list.\n request.headersList.append('accept', value)\n }\n\n // 13. If request’s header list does not contain `Accept-Language`, then\n // user agents should append `Accept-Language`/an appropriate value to\n // request’s header list.\n if (!request.headersList.contains('accept-language')) {\n request.headersList.append('accept-language', '*')\n }\n\n // 14. If request’s priority is null, then use request’s initiator and\n // destination appropriately in setting request’s priority to a\n // user-agent-defined object.\n if (request.priority === null) {\n // TODO\n }\n\n // 15. If request is a subresource request, then:\n if (subresourceSet.has(request.destination)) {\n // TODO\n }\n\n // 16. Run main fetch given fetchParams.\n mainFetch(fetchParams)\n .catch(err => {\n fetchParams.controller.terminate(err)\n })\n\n // 17. Return fetchParam's controller\n return fetchParams.controller\n}\n\n// https://fetch.spec.whatwg.org/#concept-main-fetch\nasync function mainFetch (fetchParams, recursive = false) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. If request’s local-URLs-only flag is set and request’s current URL is\n // not local, then set response to a network error.\n if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {\n response = makeNetworkError('local URLs only')\n }\n\n // 4. Run report Content Security Policy violations for request.\n // TODO\n\n // 5. Upgrade request to a potentially trustworthy URL, if appropriate.\n tryUpgradeRequestToAPotentiallyTrustworthyURL(request)\n\n // 6. If should request be blocked due to a bad port, should fetching request\n // be blocked as mixed content, or should request be blocked by Content\n // Security Policy returns blocked, then set response to a network error.\n if (requestBadPort(request) === 'blocked') {\n response = makeNetworkError('bad port')\n }\n // TODO: should fetching request be blocked as mixed content?\n // TODO: should request be blocked by Content Security Policy?\n\n // 7. If request’s referrer policy is the empty string, then set request’s\n // referrer policy to request’s policy container’s referrer policy.\n if (request.referrerPolicy === '') {\n request.referrerPolicy = request.policyContainer.referrerPolicy\n }\n\n // 8. If request’s referrer is not \"no-referrer\", then set request’s\n // referrer to the result of invoking determine request’s referrer.\n if (request.referrer !== 'no-referrer') {\n request.referrer = determineRequestsReferrer(request)\n }\n\n // 9. Set request’s current URL’s scheme to \"https\" if all of the following\n // conditions are true:\n // - request’s current URL’s scheme is \"http\"\n // - request’s current URL’s host is a domain\n // - Matching request’s current URL’s host per Known HSTS Host Domain Name\n // Matching results in either a superdomain match with an asserted\n // includeSubDomains directive or a congruent match (with or without an\n // asserted includeSubDomains directive). [HSTS]\n // TODO\n\n // 10. If recursive is false, then run the remaining steps in parallel.\n // TODO\n\n // 11. If response is null, then set response to the result of running\n // the steps corresponding to the first matching statement:\n if (response === null) {\n response = await (async () => {\n const currentURL = requestCurrentURL(request)\n\n if (\n // - request’s current URL’s origin is same origin with request’s origin,\n // and request’s response tainting is \"basic\"\n (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||\n // request’s current URL’s scheme is \"data\"\n (currentURL.protocol === 'data:') ||\n // - request’s mode is \"navigate\" or \"websocket\"\n (request.mode === 'navigate' || request.mode === 'websocket')\n ) {\n // 1. Set request’s response tainting to \"basic\".\n request.responseTainting = 'basic'\n\n // 2. Return the result of running scheme fetch given fetchParams.\n return await schemeFetch(fetchParams)\n }\n\n // request’s mode is \"same-origin\"\n if (request.mode === 'same-origin') {\n // 1. Return a network error.\n return makeNetworkError('request mode cannot be \"same-origin\"')\n }\n\n // request’s mode is \"no-cors\"\n if (request.mode === 'no-cors') {\n // 1. If request’s redirect mode is not \"follow\", then return a network\n // error.\n if (request.redirect !== 'follow') {\n return makeNetworkError(\n 'redirect mode cannot be \"follow\" for \"no-cors\" request'\n )\n }\n\n // 2. Set request’s response tainting to \"opaque\".\n request.responseTainting = 'opaque'\n\n // 3. Return the result of running scheme fetch given fetchParams.\n return await schemeFetch(fetchParams)\n }\n\n // request’s current URL’s scheme is not an HTTP(S) scheme\n if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {\n // Return a network error.\n return makeNetworkError('URL scheme must be a HTTP(S) scheme')\n }\n\n // - request’s use-CORS-preflight flag is set\n // - request’s unsafe-request flag is set and either request’s method is\n // not a CORS-safelisted method or CORS-unsafe request-header names with\n // request’s header list is not empty\n // 1. Set request’s response tainting to \"cors\".\n // 2. Let corsWithPreflightResponse be the result of running HTTP fetch\n // given fetchParams and true.\n // 3. If corsWithPreflightResponse is a network error, then clear cache\n // entries using request.\n // 4. Return corsWithPreflightResponse.\n // TODO\n\n // Otherwise\n // 1. Set request’s response tainting to \"cors\".\n request.responseTainting = 'cors'\n\n // 2. Return the result of running HTTP fetch given fetchParams.\n return await httpFetch(fetchParams)\n })()\n }\n\n // 12. If recursive is true, then return response.\n if (recursive) {\n return response\n }\n\n // 13. If response is not a network error and response is not a filtered\n // response, then:\n if (response.status !== 0 && !response.internalResponse) {\n // If request’s response tainting is \"cors\", then:\n if (request.responseTainting === 'cors') {\n // 1. Let headerNames be the result of extracting header list values\n // given `Access-Control-Expose-Headers` and response’s header list.\n // TODO\n // 2. If request’s credentials mode is not \"include\" and headerNames\n // contains `*`, then set response’s CORS-exposed header-name list to\n // all unique header names in response’s header list.\n // TODO\n // 3. Otherwise, if headerNames is not null or failure, then set\n // response’s CORS-exposed header-name list to headerNames.\n // TODO\n }\n\n // Set response to the following filtered response with response as its\n // internal response, depending on request’s response tainting:\n if (request.responseTainting === 'basic') {\n response = filterResponse(response, 'basic')\n } else if (request.responseTainting === 'cors') {\n response = filterResponse(response, 'cors')\n } else if (request.responseTainting === 'opaque') {\n response = filterResponse(response, 'opaque')\n } else {\n assert(false)\n }\n }\n\n // 14. Let internalResponse be response, if response is a network error,\n // and response’s internal response otherwise.\n let internalResponse =\n response.status === 0 ? response : response.internalResponse\n\n // 15. If internalResponse’s URL list is empty, then set it to a clone of\n // request’s URL list.\n if (internalResponse.urlList.length === 0) {\n internalResponse.urlList.push(...request.urlList)\n }\n\n // 16. If request’s timing allow failed flag is unset, then set\n // internalResponse’s timing allow passed flag.\n if (!request.timingAllowFailed) {\n response.timingAllowPassed = true\n }\n\n // 17. If response is not a network error and any of the following returns\n // blocked\n // - should internalResponse to request be blocked as mixed content\n // - should internalResponse to request be blocked by Content Security Policy\n // - should internalResponse to request be blocked due to its MIME type\n // - should internalResponse to request be blocked due to nosniff\n // TODO\n\n // 18. If response’s type is \"opaque\", internalResponse’s status is 206,\n // internalResponse’s range-requested flag is set, and request’s header\n // list does not contain `Range`, then set response and internalResponse\n // to a network error.\n if (\n response.type === 'opaque' &&\n internalResponse.status === 206 &&\n internalResponse.rangeRequested &&\n !request.headers.contains('range')\n ) {\n response = internalResponse = makeNetworkError()\n }\n\n // 19. If response is not a network error and either request’s method is\n // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,\n // set internalResponse’s body to null and disregard any enqueuing toward\n // it (if any).\n if (\n response.status !== 0 &&\n (request.method === 'HEAD' ||\n request.method === 'CONNECT' ||\n nullBodyStatus.includes(internalResponse.status))\n ) {\n internalResponse.body = null\n fetchParams.controller.dump = true\n }\n\n // 20. If request’s integrity metadata is not the empty string, then:\n if (request.integrity) {\n // 1. Let processBodyError be this step: run fetch finale given fetchParams\n // and a network error.\n const processBodyError = (reason) =>\n fetchFinale(fetchParams, makeNetworkError(reason))\n\n // 2. If request’s response tainting is \"opaque\", or response’s body is null,\n // then run processBodyError and abort these steps.\n if (request.responseTainting === 'opaque' || response.body == null) {\n processBodyError(response.error)\n return\n }\n\n // 3. Let processBody given bytes be these steps:\n const processBody = (bytes) => {\n // 1. If bytes do not match request’s integrity metadata,\n // then run processBodyError and abort these steps. [SRI]\n if (!bytesMatch(bytes, request.integrity)) {\n processBodyError('integrity mismatch')\n return\n }\n\n // 2. Set response’s body to bytes as a body.\n response.body = safelyExtractBody(bytes)[0]\n\n // 3. Run fetch finale given fetchParams and response.\n fetchFinale(fetchParams, response)\n }\n\n // 4. Fully read response’s body given processBody and processBodyError.\n await fullyReadBody(response.body, processBody, processBodyError)\n } else {\n // 21. Otherwise, run fetch finale given fetchParams and response.\n fetchFinale(fetchParams, response)\n }\n}\n\n// https://fetch.spec.whatwg.org/#concept-scheme-fetch\n// given a fetch params fetchParams\nfunction schemeFetch (fetchParams) {\n // Note: since the connection is destroyed on redirect, which sets fetchParams to a\n // cancelled state, we do not want this condition to trigger *unless* there have been\n // no redirects. See https://github.com/nodejs/undici/issues/1776\n // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {\n return Promise.resolve(makeAppropriateNetworkError(fetchParams))\n }\n\n // 2. Let request be fetchParams’s request.\n const { request } = fetchParams\n\n const { protocol: scheme } = requestCurrentURL(request)\n\n // 3. Switch on request’s current URL’s scheme and run the associated steps:\n switch (scheme) {\n case 'about:': {\n // If request’s current URL’s path is the string \"blank\", then return a new response\n // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,\n // and body is the empty byte sequence as a body.\n\n // Otherwise, return a network error.\n return Promise.resolve(makeNetworkError('about scheme is not supported'))\n }\n case 'blob:': {\n if (!resolveObjectURL) {\n resolveObjectURL = require('buffer').resolveObjectURL\n }\n\n // 1. Let blobURLEntry be request’s current URL’s blob URL entry.\n const blobURLEntry = requestCurrentURL(request)\n\n // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56\n // Buffer.resolveObjectURL does not ignore URL queries.\n if (blobURLEntry.search.length !== 0) {\n return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))\n }\n\n const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())\n\n // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s\n // object is not a Blob object, then return a network error.\n if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {\n return Promise.resolve(makeNetworkError('invalid method'))\n }\n\n // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.\n const bodyWithType = safelyExtractBody(blobURLEntryObject)\n\n // 4. Let body be bodyWithType’s body.\n const body = bodyWithType[0]\n\n // 5. Let length be body’s length, serialized and isomorphic encoded.\n const length = isomorphicEncode(`${body.length}`)\n\n // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.\n const type = bodyWithType[1] ?? ''\n\n // 7. Return a new response whose status message is `OK`, header list is\n // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.\n const response = makeResponse({\n statusText: 'OK',\n headersList: [\n ['content-length', { name: 'Content-Length', value: length }],\n ['content-type', { name: 'Content-Type', value: type }]\n ]\n })\n\n response.body = body\n\n return Promise.resolve(response)\n }\n case 'data:': {\n // 1. Let dataURLStruct be the result of running the\n // data: URL processor on request’s current URL.\n const currentURL = requestCurrentURL(request)\n const dataURLStruct = dataURLProcessor(currentURL)\n\n // 2. If dataURLStruct is failure, then return a\n // network error.\n if (dataURLStruct === 'failure') {\n return Promise.resolve(makeNetworkError('failed to fetch the data URL'))\n }\n\n // 3. Let mimeType be dataURLStruct’s MIME type, serialized.\n const mimeType = serializeAMimeType(dataURLStruct.mimeType)\n\n // 4. Return a response whose status message is `OK`,\n // header list is « (`Content-Type`, mimeType) »,\n // and body is dataURLStruct’s body as a body.\n return Promise.resolve(makeResponse({\n statusText: 'OK',\n headersList: [\n ['content-type', { name: 'Content-Type', value: mimeType }]\n ],\n body: safelyExtractBody(dataURLStruct.body)[0]\n }))\n }\n case 'file:': {\n // For now, unfortunate as it is, file URLs are left as an exercise for the reader.\n // When in doubt, return a network error.\n return Promise.resolve(makeNetworkError('not implemented... yet...'))\n }\n case 'http:':\n case 'https:': {\n // Return the result of running HTTP fetch given fetchParams.\n\n return httpFetch(fetchParams)\n .catch((err) => makeNetworkError(err))\n }\n default: {\n return Promise.resolve(makeNetworkError('unknown scheme'))\n }\n }\n}\n\n// https://fetch.spec.whatwg.org/#finalize-response\nfunction finalizeResponse (fetchParams, response) {\n // 1. Set fetchParams’s request’s done flag.\n fetchParams.request.done = true\n\n // 2, If fetchParams’s process response done is not null, then queue a fetch\n // task to run fetchParams’s process response done given response, with\n // fetchParams’s task destination.\n if (fetchParams.processResponseDone != null) {\n queueMicrotask(() => fetchParams.processResponseDone(response))\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetch-finale\nfunction fetchFinale (fetchParams, response) {\n // 1. If response is a network error, then:\n if (response.type === 'error') {\n // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».\n response.urlList = [fetchParams.request.urlList[0]]\n\n // 2. Set response’s timing info to the result of creating an opaque timing\n // info for fetchParams’s timing info.\n response.timingInfo = createOpaqueTimingInfo({\n startTime: fetchParams.timingInfo.startTime\n })\n }\n\n // 2. Let processResponseEndOfBody be the following steps:\n const processResponseEndOfBody = () => {\n // 1. Set fetchParams’s request’s done flag.\n fetchParams.request.done = true\n\n // If fetchParams’s process response end-of-body is not null,\n // then queue a fetch task to run fetchParams’s process response\n // end-of-body given response with fetchParams’s task destination.\n if (fetchParams.processResponseEndOfBody != null) {\n queueMicrotask(() => fetchParams.processResponseEndOfBody(response))\n }\n }\n\n // 3. If fetchParams’s process response is non-null, then queue a fetch task\n // to run fetchParams’s process response given response, with fetchParams’s\n // task destination.\n if (fetchParams.processResponse != null) {\n queueMicrotask(() => fetchParams.processResponse(response))\n }\n\n // 4. If response’s body is null, then run processResponseEndOfBody.\n if (response.body == null) {\n processResponseEndOfBody()\n } else {\n // 5. Otherwise:\n\n // 1. Let transformStream be a new a TransformStream.\n\n // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,\n // enqueues chunk in transformStream.\n const identityTransformAlgorithm = (chunk, controller) => {\n controller.enqueue(chunk)\n }\n\n // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm\n // and flushAlgorithm set to processResponseEndOfBody.\n const transformStream = new TransformStream({\n start () {},\n transform: identityTransformAlgorithm,\n flush: processResponseEndOfBody\n }, {\n size () {\n return 1\n }\n }, {\n size () {\n return 1\n }\n })\n\n // 4. Set response’s body to the result of piping response’s body through transformStream.\n response.body = { stream: response.body.stream.pipeThrough(transformStream) }\n }\n\n // 6. If fetchParams’s process response consume body is non-null, then:\n if (fetchParams.processResponseConsumeBody != null) {\n // 1. Let processBody given nullOrBytes be this step: run fetchParams’s\n // process response consume body given response and nullOrBytes.\n const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)\n\n // 2. Let processBodyError be this step: run fetchParams’s process\n // response consume body given response and failure.\n const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)\n\n // 3. If response’s body is null, then queue a fetch task to run processBody\n // given null, with fetchParams’s task destination.\n if (response.body == null) {\n queueMicrotask(() => processBody(null))\n } else {\n // 4. Otherwise, fully read response’s body given processBody, processBodyError,\n // and fetchParams’s task destination.\n return fullyReadBody(response.body, processBody, processBodyError)\n }\n return Promise.resolve()\n }\n}\n\n// https://fetch.spec.whatwg.org/#http-fetch\nasync function httpFetch (fetchParams) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. Let actualResponse be null.\n let actualResponse = null\n\n // 4. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 5. If request’s service-workers mode is \"all\", then:\n if (request.serviceWorkers === 'all') {\n // TODO\n }\n\n // 6. If response is null, then:\n if (response === null) {\n // 1. If makeCORSPreflight is true and one of these conditions is true:\n // TODO\n\n // 2. If request’s redirect mode is \"follow\", then set request’s\n // service-workers mode to \"none\".\n if (request.redirect === 'follow') {\n request.serviceWorkers = 'none'\n }\n\n // 3. Set response and actualResponse to the result of running\n // HTTP-network-or-cache fetch given fetchParams.\n actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)\n\n // 4. If request’s response tainting is \"cors\" and a CORS check\n // for request and response returns failure, then return a network error.\n if (\n request.responseTainting === 'cors' &&\n corsCheck(request, response) === 'failure'\n ) {\n return makeNetworkError('cors failure')\n }\n\n // 5. If the TAO check for request and response returns failure, then set\n // request’s timing allow failed flag.\n if (TAOCheck(request, response) === 'failure') {\n request.timingAllowFailed = true\n }\n }\n\n // 7. If either request’s response tainting or response’s type\n // is \"opaque\", and the cross-origin resource policy check with\n // request’s origin, request’s client, request’s destination,\n // and actualResponse returns blocked, then return a network error.\n if (\n (request.responseTainting === 'opaque' || response.type === 'opaque') &&\n crossOriginResourcePolicyCheck(\n request.origin,\n request.client,\n request.destination,\n actualResponse\n ) === 'blocked'\n ) {\n return makeNetworkError('blocked')\n }\n\n // 8. If actualResponse’s status is a redirect status, then:\n if (redirectStatusSet.has(actualResponse.status)) {\n // 1. If actualResponse’s status is not 303, request’s body is not null,\n // and the connection uses HTTP/2, then user agents may, and are even\n // encouraged to, transmit an RST_STREAM frame.\n // See, https://github.com/whatwg/fetch/issues/1288\n if (request.redirect !== 'manual') {\n fetchParams.controller.connection.destroy()\n }\n\n // 2. Switch on request’s redirect mode:\n if (request.redirect === 'error') {\n // Set response to a network error.\n response = makeNetworkError('unexpected redirect')\n } else if (request.redirect === 'manual') {\n // Set response to an opaque-redirect filtered response whose internal\n // response is actualResponse.\n // NOTE(spec): On the web this would return an `opaqueredirect` response,\n // but that doesn't make sense server side.\n // See https://github.com/nodejs/undici/issues/1193.\n response = actualResponse\n } else if (request.redirect === 'follow') {\n // Set response to the result of running HTTP-redirect fetch given\n // fetchParams and response.\n response = await httpRedirectFetch(fetchParams, response)\n } else {\n assert(false)\n }\n }\n\n // 9. Set response’s timing info to timingInfo.\n response.timingInfo = timingInfo\n\n // 10. Return response.\n return response\n}\n\n// https://fetch.spec.whatwg.org/#http-redirect-fetch\nfunction httpRedirectFetch (fetchParams, response) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let actualResponse be response, if response is not a filtered response,\n // and response’s internal response otherwise.\n const actualResponse = response.internalResponse\n ? response.internalResponse\n : response\n\n // 3. Let locationURL be actualResponse’s location URL given request’s current\n // URL’s fragment.\n let locationURL\n\n try {\n locationURL = responseLocationURL(\n actualResponse,\n requestCurrentURL(request).hash\n )\n\n // 4. If locationURL is null, then return response.\n if (locationURL == null) {\n return response\n }\n } catch (err) {\n // 5. If locationURL is failure, then return a network error.\n return Promise.resolve(makeNetworkError(err))\n }\n\n // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network\n // error.\n if (!urlIsHttpHttpsScheme(locationURL)) {\n return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))\n }\n\n // 7. If request’s redirect count is 20, then return a network error.\n if (request.redirectCount === 20) {\n return Promise.resolve(makeNetworkError('redirect count exceeded'))\n }\n\n // 8. Increase request’s redirect count by 1.\n request.redirectCount += 1\n\n // 9. If request’s mode is \"cors\", locationURL includes credentials, and\n // request’s origin is not same origin with locationURL’s origin, then return\n // a network error.\n if (\n request.mode === 'cors' &&\n (locationURL.username || locationURL.password) &&\n !sameOrigin(request, locationURL)\n ) {\n return Promise.resolve(makeNetworkError('cross origin not allowed for request mode \"cors\"'))\n }\n\n // 10. If request’s response tainting is \"cors\" and locationURL includes\n // credentials, then return a network error.\n if (\n request.responseTainting === 'cors' &&\n (locationURL.username || locationURL.password)\n ) {\n return Promise.resolve(makeNetworkError(\n 'URL cannot contain credentials for request mode \"cors\"'\n ))\n }\n\n // 11. If actualResponse’s status is not 303, request’s body is non-null,\n // and request’s body’s source is null, then return a network error.\n if (\n actualResponse.status !== 303 &&\n request.body != null &&\n request.body.source == null\n ) {\n return Promise.resolve(makeNetworkError())\n }\n\n // 12. If one of the following is true\n // - actualResponse’s status is 301 or 302 and request’s method is `POST`\n // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`\n if (\n ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||\n (actualResponse.status === 303 &&\n !GET_OR_HEAD.includes(request.method))\n ) {\n // then:\n // 1. Set request’s method to `GET` and request’s body to null.\n request.method = 'GET'\n request.body = null\n\n // 2. For each headerName of request-body-header name, delete headerName from\n // request’s header list.\n for (const headerName of requestBodyHeader) {\n request.headersList.delete(headerName)\n }\n }\n\n // 13. If request’s current URL’s origin is not same origin with locationURL’s\n // origin, then for each headerName of CORS non-wildcard request-header name,\n // delete headerName from request’s header list.\n if (!sameOrigin(requestCurrentURL(request), locationURL)) {\n // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name\n request.headersList.delete('authorization')\n\n // https://fetch.spec.whatwg.org/#authentication-entries\n request.headersList.delete('proxy-authorization', true)\n\n // \"Cookie\" and \"Host\" are forbidden request-headers, which undici doesn't implement.\n request.headersList.delete('cookie')\n request.headersList.delete('host')\n }\n\n // 14. If request’s body is non-null, then set request’s body to the first return\n // value of safely extracting request’s body’s source.\n if (request.body != null) {\n assert(request.body.source != null)\n request.body = safelyExtractBody(request.body.source)[0]\n }\n\n // 15. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 16. Set timingInfo’s redirect end time and post-redirect start time to the\n // coarsened shared current time given fetchParams’s cross-origin isolated\n // capability.\n timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =\n coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)\n\n // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s\n // redirect start time to timingInfo’s start time.\n if (timingInfo.redirectStartTime === 0) {\n timingInfo.redirectStartTime = timingInfo.startTime\n }\n\n // 18. Append locationURL to request’s URL list.\n request.urlList.push(locationURL)\n\n // 19. Invoke set request’s referrer policy on redirect on request and\n // actualResponse.\n setRequestReferrerPolicyOnRedirect(request, actualResponse)\n\n // 20. Return the result of running main fetch given fetchParams and true.\n return mainFetch(fetchParams, true)\n}\n\n// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch\nasync function httpNetworkOrCacheFetch (\n fetchParams,\n isAuthenticationFetch = false,\n isNewConnectionFetch = false\n) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let httpFetchParams be null.\n let httpFetchParams = null\n\n // 3. Let httpRequest be null.\n let httpRequest = null\n\n // 4. Let response be null.\n let response = null\n\n // 5. Let storedResponse be null.\n // TODO: cache\n\n // 6. Let httpCache be null.\n const httpCache = null\n\n // 7. Let the revalidatingFlag be unset.\n const revalidatingFlag = false\n\n // 8. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. If request’s window is \"no-window\" and request’s redirect mode is\n // \"error\", then set httpFetchParams to fetchParams and httpRequest to\n // request.\n if (request.window === 'no-window' && request.redirect === 'error') {\n httpFetchParams = fetchParams\n httpRequest = request\n } else {\n // Otherwise:\n\n // 1. Set httpRequest to a clone of request.\n httpRequest = makeRequest(request)\n\n // 2. Set httpFetchParams to a copy of fetchParams.\n httpFetchParams = { ...fetchParams }\n\n // 3. Set httpFetchParams’s request to httpRequest.\n httpFetchParams.request = httpRequest\n }\n\n // 3. Let includeCredentials be true if one of\n const includeCredentials =\n request.credentials === 'include' ||\n (request.credentials === 'same-origin' &&\n request.responseTainting === 'basic')\n\n // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s\n // body is non-null; otherwise null.\n const contentLength = httpRequest.body ? httpRequest.body.length : null\n\n // 5. Let contentLengthHeaderValue be null.\n let contentLengthHeaderValue = null\n\n // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or\n // `PUT`, then set contentLengthHeaderValue to `0`.\n if (\n httpRequest.body == null &&\n ['POST', 'PUT'].includes(httpRequest.method)\n ) {\n contentLengthHeaderValue = '0'\n }\n\n // 7. If contentLength is non-null, then set contentLengthHeaderValue to\n // contentLength, serialized and isomorphic encoded.\n if (contentLength != null) {\n contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)\n }\n\n // 8. If contentLengthHeaderValue is non-null, then append\n // `Content-Length`/contentLengthHeaderValue to httpRequest’s header\n // list.\n if (contentLengthHeaderValue != null) {\n httpRequest.headersList.append('content-length', contentLengthHeaderValue)\n }\n\n // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,\n // contentLengthHeaderValue) to httpRequest’s header list.\n\n // 10. If contentLength is non-null and httpRequest’s keepalive is true,\n // then:\n if (contentLength != null && httpRequest.keepalive) {\n // NOTE: keepalive is a noop outside of browser context.\n }\n\n // 11. If httpRequest’s referrer is a URL, then append\n // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,\n // to httpRequest’s header list.\n if (httpRequest.referrer instanceof URL) {\n httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))\n }\n\n // 12. Append a request `Origin` header for httpRequest.\n appendRequestOriginHeader(httpRequest)\n\n // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]\n appendFetchMetadata(httpRequest)\n\n // 14. If httpRequest’s header list does not contain `User-Agent`, then\n // user agents should append `User-Agent`/default `User-Agent` value to\n // httpRequest’s header list.\n if (!httpRequest.headersList.contains('user-agent')) {\n httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')\n }\n\n // 15. If httpRequest’s cache mode is \"default\" and httpRequest’s header\n // list contains `If-Modified-Since`, `If-None-Match`,\n // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set\n // httpRequest’s cache mode to \"no-store\".\n if (\n httpRequest.cache === 'default' &&\n (httpRequest.headersList.contains('if-modified-since') ||\n httpRequest.headersList.contains('if-none-match') ||\n httpRequest.headersList.contains('if-unmodified-since') ||\n httpRequest.headersList.contains('if-match') ||\n httpRequest.headersList.contains('if-range'))\n ) {\n httpRequest.cache = 'no-store'\n }\n\n // 16. If httpRequest’s cache mode is \"no-cache\", httpRequest’s prevent\n // no-cache cache-control header modification flag is unset, and\n // httpRequest’s header list does not contain `Cache-Control`, then append\n // `Cache-Control`/`max-age=0` to httpRequest’s header list.\n if (\n httpRequest.cache === 'no-cache' &&\n !httpRequest.preventNoCacheCacheControlHeaderModification &&\n !httpRequest.headersList.contains('cache-control')\n ) {\n httpRequest.headersList.append('cache-control', 'max-age=0')\n }\n\n // 17. If httpRequest’s cache mode is \"no-store\" or \"reload\", then:\n if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {\n // 1. If httpRequest’s header list does not contain `Pragma`, then append\n // `Pragma`/`no-cache` to httpRequest’s header list.\n if (!httpRequest.headersList.contains('pragma')) {\n httpRequest.headersList.append('pragma', 'no-cache')\n }\n\n // 2. If httpRequest’s header list does not contain `Cache-Control`,\n // then append `Cache-Control`/`no-cache` to httpRequest’s header list.\n if (!httpRequest.headersList.contains('cache-control')) {\n httpRequest.headersList.append('cache-control', 'no-cache')\n }\n }\n\n // 18. If httpRequest’s header list contains `Range`, then append\n // `Accept-Encoding`/`identity` to httpRequest’s header list.\n if (httpRequest.headersList.contains('range')) {\n httpRequest.headersList.append('accept-encoding', 'identity')\n }\n\n // 19. Modify httpRequest’s header list per HTTP. Do not append a given\n // header if httpRequest’s header list contains that header’s name.\n // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129\n if (!httpRequest.headersList.contains('accept-encoding')) {\n if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {\n httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')\n } else {\n httpRequest.headersList.append('accept-encoding', 'gzip, deflate')\n }\n }\n\n httpRequest.headersList.delete('host')\n\n // 20. If includeCredentials is true, then:\n if (includeCredentials) {\n // 1. If the user agent is not configured to block cookies for httpRequest\n // (see section 7 of [COOKIES]), then:\n // TODO: credentials\n // 2. If httpRequest’s header list does not contain `Authorization`, then:\n // TODO: credentials\n }\n\n // 21. If there’s a proxy-authentication entry, use it as appropriate.\n // TODO: proxy-authentication\n\n // 22. Set httpCache to the result of determining the HTTP cache\n // partition, given httpRequest.\n // TODO: cache\n\n // 23. If httpCache is null, then set httpRequest’s cache mode to\n // \"no-store\".\n if (httpCache == null) {\n httpRequest.cache = 'no-store'\n }\n\n // 24. If httpRequest’s cache mode is neither \"no-store\" nor \"reload\",\n // then:\n if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {\n // TODO: cache\n }\n\n // 9. If aborted, then return the appropriate network error for fetchParams.\n // TODO\n\n // 10. If response is null, then:\n if (response == null) {\n // 1. If httpRequest’s cache mode is \"only-if-cached\", then return a\n // network error.\n if (httpRequest.mode === 'only-if-cached') {\n return makeNetworkError('only if cached')\n }\n\n // 2. Let forwardResponse be the result of running HTTP-network fetch\n // given httpFetchParams, includeCredentials, and isNewConnectionFetch.\n const forwardResponse = await httpNetworkFetch(\n httpFetchParams,\n includeCredentials,\n isNewConnectionFetch\n )\n\n // 3. If httpRequest’s method is unsafe and forwardResponse’s status is\n // in the range 200 to 399, inclusive, invalidate appropriate stored\n // responses in httpCache, as per the \"Invalidation\" chapter of HTTP\n // Caching, and set storedResponse to null. [HTTP-CACHING]\n if (\n !safeMethodsSet.has(httpRequest.method) &&\n forwardResponse.status >= 200 &&\n forwardResponse.status <= 399\n ) {\n // TODO: cache\n }\n\n // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,\n // then:\n if (revalidatingFlag && forwardResponse.status === 304) {\n // TODO: cache\n }\n\n // 5. If response is null, then:\n if (response == null) {\n // 1. Set response to forwardResponse.\n response = forwardResponse\n\n // 2. Store httpRequest and forwardResponse in httpCache, as per the\n // \"Storing Responses in Caches\" chapter of HTTP Caching. [HTTP-CACHING]\n // TODO: cache\n }\n }\n\n // 11. Set response’s URL list to a clone of httpRequest’s URL list.\n response.urlList = [...httpRequest.urlList]\n\n // 12. If httpRequest’s header list contains `Range`, then set response’s\n // range-requested flag.\n if (httpRequest.headersList.contains('range')) {\n response.rangeRequested = true\n }\n\n // 13. Set response’s request-includes-credentials to includeCredentials.\n response.requestIncludesCredentials = includeCredentials\n\n // 14. If response’s status is 401, httpRequest’s response tainting is not\n // \"cors\", includeCredentials is true, and request’s window is an environment\n // settings object, then:\n // TODO\n\n // 15. If response’s status is 407, then:\n if (response.status === 407) {\n // 1. If request’s window is \"no-window\", then return a network error.\n if (request.window === 'no-window') {\n return makeNetworkError()\n }\n\n // 2. ???\n\n // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams)) {\n return makeAppropriateNetworkError(fetchParams)\n }\n\n // 4. Prompt the end user as appropriate in request’s window and store\n // the result as a proxy-authentication entry. [HTTP-AUTH]\n // TODO: Invoke some kind of callback?\n\n // 5. Set response to the result of running HTTP-network-or-cache fetch given\n // fetchParams.\n // TODO\n return makeNetworkError('proxy authentication required')\n }\n\n // 16. If all of the following are true\n if (\n // response’s status is 421\n response.status === 421 &&\n // isNewConnectionFetch is false\n !isNewConnectionFetch &&\n // request’s body is null, or request’s body is non-null and request’s body’s source is non-null\n (request.body == null || request.body.source != null)\n ) {\n // then:\n\n // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams)) {\n return makeAppropriateNetworkError(fetchParams)\n }\n\n // 2. Set response to the result of running HTTP-network-or-cache\n // fetch given fetchParams, isAuthenticationFetch, and true.\n\n // TODO (spec): The spec doesn't specify this but we need to cancel\n // the active response before we can start a new one.\n // https://github.com/whatwg/fetch/issues/1293\n fetchParams.controller.connection.destroy()\n\n response = await httpNetworkOrCacheFetch(\n fetchParams,\n isAuthenticationFetch,\n true\n )\n }\n\n // 17. If isAuthenticationFetch is true, then create an authentication entry\n if (isAuthenticationFetch) {\n // TODO\n }\n\n // 18. Return response.\n return response\n}\n\n// https://fetch.spec.whatwg.org/#http-network-fetch\nasync function httpNetworkFetch (\n fetchParams,\n includeCredentials = false,\n forceNewConnection = false\n) {\n assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)\n\n fetchParams.controller.connection = {\n abort: null,\n destroyed: false,\n destroy (err) {\n if (!this.destroyed) {\n this.destroyed = true\n this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))\n }\n }\n }\n\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 4. Let httpCache be the result of determining the HTTP cache partition,\n // given request.\n // TODO: cache\n const httpCache = null\n\n // 5. If httpCache is null, then set request’s cache mode to \"no-store\".\n if (httpCache == null) {\n request.cache = 'no-store'\n }\n\n // 6. Let networkPartitionKey be the result of determining the network\n // partition key given request.\n // TODO\n\n // 7. Let newConnection be \"yes\" if forceNewConnection is true; otherwise\n // \"no\".\n const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars\n\n // 8. Switch on request’s mode:\n if (request.mode === 'websocket') {\n // Let connection be the result of obtaining a WebSocket connection,\n // given request’s current URL.\n // TODO\n } else {\n // Let connection be the result of obtaining a connection, given\n // networkPartitionKey, request’s current URL’s origin,\n // includeCredentials, and forceNewConnection.\n // TODO\n }\n\n // 9. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. If connection is failure, then return a network error.\n\n // 2. Set timingInfo’s final connection timing info to the result of\n // calling clamp and coarsen connection timing info with connection’s\n // timing info, timingInfo’s post-redirect start time, and fetchParams’s\n // cross-origin isolated capability.\n\n // 3. If connection is not an HTTP/2 connection, request’s body is non-null,\n // and request’s body’s source is null, then append (`Transfer-Encoding`,\n // `chunked`) to request’s header list.\n\n // 4. Set timingInfo’s final network-request start time to the coarsened\n // shared current time given fetchParams’s cross-origin isolated\n // capability.\n\n // 5. Set response to the result of making an HTTP request over connection\n // using request with the following caveats:\n\n // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]\n // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]\n\n // - If request’s body is non-null, and request’s body’s source is null,\n // then the user agent may have a buffer of up to 64 kibibytes and store\n // a part of request’s body in that buffer. If the user agent reads from\n // request’s body beyond that buffer’s size and the user agent needs to\n // resend request, then instead return a network error.\n\n // - Set timingInfo’s final network-response start time to the coarsened\n // shared current time given fetchParams’s cross-origin isolated capability,\n // immediately after the user agent’s HTTP parser receives the first byte\n // of the response (e.g., frame header bytes for HTTP/2 or response status\n // line for HTTP/1.x).\n\n // - Wait until all the headers are transmitted.\n\n // - Any responses whose status is in the range 100 to 199, inclusive,\n // and is not 101, are to be ignored, except for the purposes of setting\n // timingInfo’s final network-response start time above.\n\n // - If request’s header list contains `Transfer-Encoding`/`chunked` and\n // response is transferred via HTTP/1.0 or older, then return a network\n // error.\n\n // - If the HTTP request results in a TLS client certificate dialog, then:\n\n // 1. If request’s window is an environment settings object, make the\n // dialog available in request’s window.\n\n // 2. Otherwise, return a network error.\n\n // To transmit request’s body body, run these steps:\n let requestBody = null\n // 1. If body is null and fetchParams’s process request end-of-body is\n // non-null, then queue a fetch task given fetchParams’s process request\n // end-of-body and fetchParams’s task destination.\n if (request.body == null && fetchParams.processRequestEndOfBody) {\n queueMicrotask(() => fetchParams.processRequestEndOfBody())\n } else if (request.body != null) {\n // 2. Otherwise, if body is non-null:\n\n // 1. Let processBodyChunk given bytes be these steps:\n const processBodyChunk = async function * (bytes) {\n // 1. If the ongoing fetch is terminated, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. Run this step in parallel: transmit bytes.\n yield bytes\n\n // 3. If fetchParams’s process request body is non-null, then run\n // fetchParams’s process request body given bytes’s length.\n fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)\n }\n\n // 2. Let processEndOfBody be these steps:\n const processEndOfBody = () => {\n // 1. If fetchParams is canceled, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. If fetchParams’s process request end-of-body is non-null,\n // then run fetchParams’s process request end-of-body.\n if (fetchParams.processRequestEndOfBody) {\n fetchParams.processRequestEndOfBody()\n }\n }\n\n // 3. Let processBodyError given e be these steps:\n const processBodyError = (e) => {\n // 1. If fetchParams is canceled, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. If e is an \"AbortError\" DOMException, then abort fetchParams’s controller.\n if (e.name === 'AbortError') {\n fetchParams.controller.abort()\n } else {\n fetchParams.controller.terminate(e)\n }\n }\n\n // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,\n // processBodyError, and fetchParams’s task destination.\n requestBody = (async function * () {\n try {\n for await (const bytes of request.body.stream) {\n yield * processBodyChunk(bytes)\n }\n processEndOfBody()\n } catch (err) {\n processBodyError(err)\n }\n })()\n }\n\n try {\n // socket is only provided for websockets\n const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })\n\n if (socket) {\n response = makeResponse({ status, statusText, headersList, socket })\n } else {\n const iterator = body[Symbol.asyncIterator]()\n fetchParams.controller.next = () => iterator.next()\n\n response = makeResponse({ status, statusText, headersList })\n }\n } catch (err) {\n // 10. If aborted, then:\n if (err.name === 'AbortError') {\n // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.\n fetchParams.controller.connection.destroy()\n\n // 2. Return the appropriate network error for fetchParams.\n return makeAppropriateNetworkError(fetchParams, err)\n }\n\n return makeNetworkError(err)\n }\n\n // 11. Let pullAlgorithm be an action that resumes the ongoing fetch\n // if it is suspended.\n const pullAlgorithm = () => {\n fetchParams.controller.resume()\n }\n\n // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s\n // controller with reason, given reason.\n const cancelAlgorithm = (reason) => {\n fetchParams.controller.abort(reason)\n }\n\n // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by\n // the user agent.\n // TODO\n\n // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object\n // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.\n // TODO\n\n // 15. Let stream be a new ReadableStream.\n // 16. Set up stream with pullAlgorithm set to pullAlgorithm,\n // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to\n // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n const stream = new ReadableStream(\n {\n async start (controller) {\n fetchParams.controller.controller = controller\n },\n async pull (controller) {\n await pullAlgorithm(controller)\n },\n async cancel (reason) {\n await cancelAlgorithm(reason)\n }\n },\n {\n highWaterMark: 0,\n size () {\n return 1\n }\n }\n )\n\n // 17. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. Set response’s body to a new body whose stream is stream.\n response.body = { stream }\n\n // 2. If response is not a network error and request’s cache mode is\n // not \"no-store\", then update response in httpCache for request.\n // TODO\n\n // 3. If includeCredentials is true and the user agent is not configured\n // to block cookies for request (see section 7 of [COOKIES]), then run the\n // \"set-cookie-string\" parsing algorithm (see section 5.2 of [COOKIES]) on\n // the value of each header whose name is a byte-case-insensitive match for\n // `Set-Cookie` in response’s header list, if any, and request’s current URL.\n // TODO\n\n // 18. If aborted, then:\n // TODO\n\n // 19. Run these steps in parallel:\n\n // 1. Run these steps, but abort when fetchParams is canceled:\n fetchParams.controller.on('terminated', onAborted)\n fetchParams.controller.resume = async () => {\n // 1. While true\n while (true) {\n // 1-3. See onData...\n\n // 4. Set bytes to the result of handling content codings given\n // codings and bytes.\n let bytes\n let isFailure\n try {\n const { done, value } = await fetchParams.controller.next()\n\n if (isAborted(fetchParams)) {\n break\n }\n\n bytes = done ? undefined : value\n } catch (err) {\n if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {\n // zlib doesn't like empty streams.\n bytes = undefined\n } else {\n bytes = err\n\n // err may be propagated from the result of calling readablestream.cancel,\n // which might not be an error. https://github.com/nodejs/undici/issues/2009\n isFailure = true\n }\n }\n\n if (bytes === undefined) {\n // 2. Otherwise, if the bytes transmission for response’s message\n // body is done normally and stream is readable, then close\n // stream, finalize response for fetchParams and response, and\n // abort these in-parallel steps.\n readableStreamClose(fetchParams.controller.controller)\n\n finalizeResponse(fetchParams, response)\n\n return\n }\n\n // 5. Increase timingInfo’s decoded body size by bytes’s length.\n timingInfo.decodedBodySize += bytes?.byteLength ?? 0\n\n // 6. If bytes is failure, then terminate fetchParams’s controller.\n if (isFailure) {\n fetchParams.controller.terminate(bytes)\n return\n }\n\n // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes\n // into stream.\n fetchParams.controller.controller.enqueue(new Uint8Array(bytes))\n\n // 8. If stream is errored, then terminate the ongoing fetch.\n if (isErrored(stream)) {\n fetchParams.controller.terminate()\n return\n }\n\n // 9. If stream doesn’t need more data ask the user agent to suspend\n // the ongoing fetch.\n if (!fetchParams.controller.controller.desiredSize) {\n return\n }\n }\n }\n\n // 2. If aborted, then:\n function onAborted (reason) {\n // 2. If fetchParams is aborted, then:\n if (isAborted(fetchParams)) {\n // 1. Set response’s aborted flag.\n response.aborted = true\n\n // 2. If stream is readable, then error stream with the result of\n // deserialize a serialized abort reason given fetchParams’s\n // controller’s serialized abort reason and an\n // implementation-defined realm.\n if (isReadable(stream)) {\n fetchParams.controller.controller.error(\n fetchParams.controller.serializedAbortReason\n )\n }\n } else {\n // 3. Otherwise, if stream is readable, error stream with a TypeError.\n if (isReadable(stream)) {\n fetchParams.controller.controller.error(new TypeError('terminated', {\n cause: isErrorLike(reason) ? reason : undefined\n }))\n }\n }\n\n // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.\n // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.\n fetchParams.controller.connection.destroy()\n }\n\n // 20. Return response.\n return response\n\n async function dispatch ({ body }) {\n const url = requestCurrentURL(request)\n /** @type {import('../..').Agent} */\n const agent = fetchParams.controller.dispatcher\n\n return new Promise((resolve, reject) => agent.dispatch(\n {\n path: url.pathname + url.search,\n origin: url.origin,\n method: request.method,\n body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,\n headers: request.headersList.entries,\n maxRedirections: 0,\n upgrade: request.mode === 'websocket' ? 'websocket' : undefined\n },\n {\n body: null,\n abort: null,\n\n onConnect (abort) {\n // TODO (fix): Do we need connection here?\n const { connection } = fetchParams.controller\n\n if (connection.destroyed) {\n abort(new DOMException('The operation was aborted.', 'AbortError'))\n } else {\n fetchParams.controller.on('terminated', abort)\n this.abort = connection.abort = abort\n }\n },\n\n onHeaders (status, headersList, resume, statusText) {\n if (status < 200) {\n return\n }\n\n let codings = []\n let location = ''\n\n const headers = new Headers()\n\n // For H2, the headers are a plain JS object\n // We distinguish between them and iterate accordingly\n if (Array.isArray(headersList)) {\n for (let n = 0; n < headersList.length; n += 2) {\n const key = headersList[n + 0].toString('latin1')\n const val = headersList[n + 1].toString('latin1')\n if (key.toLowerCase() === 'content-encoding') {\n // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1\n // \"All content-coding values are case-insensitive...\"\n codings = val.toLowerCase().split(',').map((x) => x.trim())\n } else if (key.toLowerCase() === 'location') {\n location = val\n }\n\n headers[kHeadersList].append(key, val)\n }\n } else {\n const keys = Object.keys(headersList)\n for (const key of keys) {\n const val = headersList[key]\n if (key.toLowerCase() === 'content-encoding') {\n // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1\n // \"All content-coding values are case-insensitive...\"\n codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()\n } else if (key.toLowerCase() === 'location') {\n location = val\n }\n\n headers[kHeadersList].append(key, val)\n }\n }\n\n this.body = new Readable({ read: resume })\n\n const decoders = []\n\n const willFollow = request.redirect === 'follow' &&\n location &&\n redirectStatusSet.has(status)\n\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding\n if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {\n for (const coding of codings) {\n // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2\n if (coding === 'x-gzip' || coding === 'gzip') {\n decoders.push(zlib.createGunzip({\n // Be less strict when decoding compressed responses, since sometimes\n // servers send slightly invalid responses that are still accepted\n // by common browsers.\n // Always using Z_SYNC_FLUSH is what cURL does.\n flush: zlib.constants.Z_SYNC_FLUSH,\n finishFlush: zlib.constants.Z_SYNC_FLUSH\n }))\n } else if (coding === 'deflate') {\n decoders.push(zlib.createInflate())\n } else if (coding === 'br') {\n decoders.push(zlib.createBrotliDecompress())\n } else {\n decoders.length = 0\n break\n }\n }\n }\n\n resolve({\n status,\n statusText,\n headersList: headers[kHeadersList],\n body: decoders.length\n ? pipeline(this.body, ...decoders, () => { })\n : this.body.on('error', () => {})\n })\n\n return true\n },\n\n onData (chunk) {\n if (fetchParams.controller.dump) {\n return\n }\n\n // 1. If one or more bytes have been transmitted from response’s\n // message body, then:\n\n // 1. Let bytes be the transmitted bytes.\n const bytes = chunk\n\n // 2. Let codings be the result of extracting header list values\n // given `Content-Encoding` and response’s header list.\n // See pullAlgorithm.\n\n // 3. Increase timingInfo’s encoded body size by bytes’s length.\n timingInfo.encodedBodySize += bytes.byteLength\n\n // 4. See pullAlgorithm...\n\n return this.body.push(bytes)\n },\n\n onComplete () {\n if (this.abort) {\n fetchParams.controller.off('terminated', this.abort)\n }\n\n fetchParams.controller.ended = true\n\n this.body.push(null)\n },\n\n onError (error) {\n if (this.abort) {\n fetchParams.controller.off('terminated', this.abort)\n }\n\n this.body?.destroy(error)\n\n fetchParams.controller.terminate(error)\n\n reject(error)\n },\n\n onUpgrade (status, headersList, socket) {\n if (status !== 101) {\n return\n }\n\n const headers = new Headers()\n\n for (let n = 0; n < headersList.length; n += 2) {\n const key = headersList[n + 0].toString('latin1')\n const val = headersList[n + 1].toString('latin1')\n\n headers[kHeadersList].append(key, val)\n }\n\n resolve({\n status,\n statusText: STATUS_CODES[status],\n headersList: headers[kHeadersList],\n socket\n })\n\n return true\n }\n }\n ))\n }\n}\n\nmodule.exports = {\n fetch,\n Fetch,\n fetching,\n finalizeAndReportTiming\n}\n","/* globals AbortController */\n\n'use strict'\n\nconst { extractBody, mixinBody, cloneBody } = require('./body')\nconst { Headers, fill: fillHeaders, HeadersList } = require('./headers')\nconst { FinalizationRegistry } = require('../compat/dispatcher-weakref')()\nconst util = require('../core/util')\nconst {\n isValidHTTPToken,\n sameOrigin,\n normalizeMethod,\n makePolicyContainer,\n normalizeMethodRecord\n} = require('./util')\nconst {\n forbiddenMethodsSet,\n corsSafeListedMethodsSet,\n referrerPolicy,\n requestRedirect,\n requestMode,\n requestCredentials,\n requestCache,\n requestDuplex\n} = require('./constants')\nconst { kEnumerableProperty } = util\nconst { kHeaders, kSignal, kState, kGuard, kRealm } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { getGlobalOrigin } = require('./global')\nconst { URLSerializer } = require('./dataURL')\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst assert = require('assert')\nconst { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require('events')\n\nlet TransformStream = globalThis.TransformStream\n\nconst kAbortController = Symbol('abortController')\n\nconst requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {\n signal.removeEventListener('abort', abort)\n})\n\n// https://fetch.spec.whatwg.org/#request-class\nclass Request {\n // https://fetch.spec.whatwg.org/#dom-request\n constructor (input, init = {}) {\n if (input === kConstruct) {\n return\n }\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })\n\n input = webidl.converters.RequestInfo(input)\n init = webidl.converters.RequestInit(init)\n\n // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object\n this[kRealm] = {\n settingsObject: {\n baseUrl: getGlobalOrigin(),\n get origin () {\n return this.baseUrl?.origin\n },\n policyContainer: makePolicyContainer()\n }\n }\n\n // 1. Let request be null.\n let request = null\n\n // 2. Let fallbackMode be null.\n let fallbackMode = null\n\n // 3. Let baseURL be this’s relevant settings object’s API base URL.\n const baseUrl = this[kRealm].settingsObject.baseUrl\n\n // 4. Let signal be null.\n let signal = null\n\n // 5. If input is a string, then:\n if (typeof input === 'string') {\n // 1. Let parsedURL be the result of parsing input with baseURL.\n // 2. If parsedURL is failure, then throw a TypeError.\n let parsedURL\n try {\n parsedURL = new URL(input, baseUrl)\n } catch (err) {\n throw new TypeError('Failed to parse URL from ' + input, { cause: err })\n }\n\n // 3. If parsedURL includes credentials, then throw a TypeError.\n if (parsedURL.username || parsedURL.password) {\n throw new TypeError(\n 'Request cannot be constructed from a URL that includes credentials: ' +\n input\n )\n }\n\n // 4. Set request to a new request whose URL is parsedURL.\n request = makeRequest({ urlList: [parsedURL] })\n\n // 5. Set fallbackMode to \"cors\".\n fallbackMode = 'cors'\n } else {\n // 6. Otherwise:\n\n // 7. Assert: input is a Request object.\n assert(input instanceof Request)\n\n // 8. Set request to input’s request.\n request = input[kState]\n\n // 9. Set signal to input’s signal.\n signal = input[kSignal]\n }\n\n // 7. Let origin be this’s relevant settings object’s origin.\n const origin = this[kRealm].settingsObject.origin\n\n // 8. Let window be \"client\".\n let window = 'client'\n\n // 9. If request’s window is an environment settings object and its origin\n // is same origin with origin, then set window to request’s window.\n if (\n request.window?.constructor?.name === 'EnvironmentSettingsObject' &&\n sameOrigin(request.window, origin)\n ) {\n window = request.window\n }\n\n // 10. If init[\"window\"] exists and is non-null, then throw a TypeError.\n if (init.window != null) {\n throw new TypeError(`'window' option '${window}' must be null`)\n }\n\n // 11. If init[\"window\"] exists, then set window to \"no-window\".\n if ('window' in init) {\n window = 'no-window'\n }\n\n // 12. Set request to a new request with the following properties:\n request = makeRequest({\n // URL request’s URL.\n // undici implementation note: this is set as the first item in request's urlList in makeRequest\n // method request’s method.\n method: request.method,\n // header list A copy of request’s header list.\n // undici implementation note: headersList is cloned in makeRequest\n headersList: request.headersList,\n // unsafe-request flag Set.\n unsafeRequest: request.unsafeRequest,\n // client This’s relevant settings object.\n client: this[kRealm].settingsObject,\n // window window.\n window,\n // priority request’s priority.\n priority: request.priority,\n // origin request’s origin. The propagation of the origin is only significant for navigation requests\n // being handled by a service worker. In this scenario a request can have an origin that is different\n // from the current client.\n origin: request.origin,\n // referrer request’s referrer.\n referrer: request.referrer,\n // referrer policy request’s referrer policy.\n referrerPolicy: request.referrerPolicy,\n // mode request’s mode.\n mode: request.mode,\n // credentials mode request’s credentials mode.\n credentials: request.credentials,\n // cache mode request’s cache mode.\n cache: request.cache,\n // redirect mode request’s redirect mode.\n redirect: request.redirect,\n // integrity metadata request’s integrity metadata.\n integrity: request.integrity,\n // keepalive request’s keepalive.\n keepalive: request.keepalive,\n // reload-navigation flag request’s reload-navigation flag.\n reloadNavigation: request.reloadNavigation,\n // history-navigation flag request’s history-navigation flag.\n historyNavigation: request.historyNavigation,\n // URL list A clone of request’s URL list.\n urlList: [...request.urlList]\n })\n\n const initHasKey = Object.keys(init).length !== 0\n\n // 13. If init is not empty, then:\n if (initHasKey) {\n // 1. If request’s mode is \"navigate\", then set it to \"same-origin\".\n if (request.mode === 'navigate') {\n request.mode = 'same-origin'\n }\n\n // 2. Unset request’s reload-navigation flag.\n request.reloadNavigation = false\n\n // 3. Unset request’s history-navigation flag.\n request.historyNavigation = false\n\n // 4. Set request’s origin to \"client\".\n request.origin = 'client'\n\n // 5. Set request’s referrer to \"client\"\n request.referrer = 'client'\n\n // 6. Set request’s referrer policy to the empty string.\n request.referrerPolicy = ''\n\n // 7. Set request’s URL to request’s current URL.\n request.url = request.urlList[request.urlList.length - 1]\n\n // 8. Set request’s URL list to « request’s URL ».\n request.urlList = [request.url]\n }\n\n // 14. If init[\"referrer\"] exists, then:\n if (init.referrer !== undefined) {\n // 1. Let referrer be init[\"referrer\"].\n const referrer = init.referrer\n\n // 2. If referrer is the empty string, then set request’s referrer to \"no-referrer\".\n if (referrer === '') {\n request.referrer = 'no-referrer'\n } else {\n // 1. Let parsedReferrer be the result of parsing referrer with\n // baseURL.\n // 2. If parsedReferrer is failure, then throw a TypeError.\n let parsedReferrer\n try {\n parsedReferrer = new URL(referrer, baseUrl)\n } catch (err) {\n throw new TypeError(`Referrer \"${referrer}\" is not a valid URL.`, { cause: err })\n }\n\n // 3. If one of the following is true\n // - parsedReferrer’s scheme is \"about\" and path is the string \"client\"\n // - parsedReferrer’s origin is not same origin with origin\n // then set request’s referrer to \"client\".\n if (\n (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||\n (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))\n ) {\n request.referrer = 'client'\n } else {\n // 4. Otherwise, set request’s referrer to parsedReferrer.\n request.referrer = parsedReferrer\n }\n }\n }\n\n // 15. If init[\"referrerPolicy\"] exists, then set request’s referrer policy\n // to it.\n if (init.referrerPolicy !== undefined) {\n request.referrerPolicy = init.referrerPolicy\n }\n\n // 16. Let mode be init[\"mode\"] if it exists, and fallbackMode otherwise.\n let mode\n if (init.mode !== undefined) {\n mode = init.mode\n } else {\n mode = fallbackMode\n }\n\n // 17. If mode is \"navigate\", then throw a TypeError.\n if (mode === 'navigate') {\n throw webidl.errors.exception({\n header: 'Request constructor',\n message: 'invalid request mode navigate.'\n })\n }\n\n // 18. If mode is non-null, set request’s mode to mode.\n if (mode != null) {\n request.mode = mode\n }\n\n // 19. If init[\"credentials\"] exists, then set request’s credentials mode\n // to it.\n if (init.credentials !== undefined) {\n request.credentials = init.credentials\n }\n\n // 18. If init[\"cache\"] exists, then set request’s cache mode to it.\n if (init.cache !== undefined) {\n request.cache = init.cache\n }\n\n // 21. If request’s cache mode is \"only-if-cached\" and request’s mode is\n // not \"same-origin\", then throw a TypeError.\n if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n throw new TypeError(\n \"'only-if-cached' can be set only with 'same-origin' mode\"\n )\n }\n\n // 22. If init[\"redirect\"] exists, then set request’s redirect mode to it.\n if (init.redirect !== undefined) {\n request.redirect = init.redirect\n }\n\n // 23. If init[\"integrity\"] exists, then set request’s integrity metadata to it.\n if (init.integrity != null) {\n request.integrity = String(init.integrity)\n }\n\n // 24. If init[\"keepalive\"] exists, then set request’s keepalive to it.\n if (init.keepalive !== undefined) {\n request.keepalive = Boolean(init.keepalive)\n }\n\n // 25. If init[\"method\"] exists, then:\n if (init.method !== undefined) {\n // 1. Let method be init[\"method\"].\n let method = init.method\n\n // 2. If method is not a method or method is a forbidden method, then\n // throw a TypeError.\n if (!isValidHTTPToken(method)) {\n throw new TypeError(`'${method}' is not a valid HTTP method.`)\n }\n\n if (forbiddenMethodsSet.has(method.toUpperCase())) {\n throw new TypeError(`'${method}' HTTP method is unsupported.`)\n }\n\n // 3. Normalize method.\n method = normalizeMethodRecord[method] ?? normalizeMethod(method)\n\n // 4. Set request’s method to method.\n request.method = method\n }\n\n // 26. If init[\"signal\"] exists, then set signal to it.\n if (init.signal !== undefined) {\n signal = init.signal\n }\n\n // 27. Set this’s request to request.\n this[kState] = request\n\n // 28. Set this’s signal to a new AbortSignal object with this’s relevant\n // Realm.\n // TODO: could this be simplified with AbortSignal.any\n // (https://dom.spec.whatwg.org/#dom-abortsignal-any)\n const ac = new AbortController()\n this[kSignal] = ac.signal\n this[kSignal][kRealm] = this[kRealm]\n\n // 29. If signal is not null, then make this’s signal follow signal.\n if (signal != null) {\n if (\n !signal ||\n typeof signal.aborted !== 'boolean' ||\n typeof signal.addEventListener !== 'function'\n ) {\n throw new TypeError(\n \"Failed to construct 'Request': member signal is not of type AbortSignal.\"\n )\n }\n\n if (signal.aborted) {\n ac.abort(signal.reason)\n } else {\n // Keep a strong ref to ac while request object\n // is alive. This is needed to prevent AbortController\n // from being prematurely garbage collected.\n // See, https://github.com/nodejs/undici/issues/1926.\n this[kAbortController] = ac\n\n const acRef = new WeakRef(ac)\n const abort = function () {\n const ac = acRef.deref()\n if (ac !== undefined) {\n ac.abort(this.reason)\n }\n }\n\n // Third-party AbortControllers may not work with these.\n // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.\n try {\n // If the max amount of listeners is equal to the default, increase it\n // This is only available in node >= v19.9.0\n if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {\n setMaxListeners(100, signal)\n } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {\n setMaxListeners(100, signal)\n }\n } catch {}\n\n util.addAbortListener(signal, abort)\n requestFinalizer.register(ac, { signal, abort })\n }\n }\n\n // 30. Set this’s headers to a new Headers object with this’s relevant\n // Realm, whose header list is request’s header list and guard is\n // \"request\".\n this[kHeaders] = new Headers(kConstruct)\n this[kHeaders][kHeadersList] = request.headersList\n this[kHeaders][kGuard] = 'request'\n this[kHeaders][kRealm] = this[kRealm]\n\n // 31. If this’s request’s mode is \"no-cors\", then:\n if (mode === 'no-cors') {\n // 1. If this’s request’s method is not a CORS-safelisted method,\n // then throw a TypeError.\n if (!corsSafeListedMethodsSet.has(request.method)) {\n throw new TypeError(\n `'${request.method} is unsupported in no-cors mode.`\n )\n }\n\n // 2. Set this’s headers’s guard to \"request-no-cors\".\n this[kHeaders][kGuard] = 'request-no-cors'\n }\n\n // 32. If init is not empty, then:\n if (initHasKey) {\n /** @type {HeadersList} */\n const headersList = this[kHeaders][kHeadersList]\n // 1. Let headers be a copy of this’s headers and its associated header\n // list.\n // 2. If init[\"headers\"] exists, then set headers to init[\"headers\"].\n const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)\n\n // 3. Empty this’s headers’s header list.\n headersList.clear()\n\n // 4. If headers is a Headers object, then for each header in its header\n // list, append header’s name/header’s value to this’s headers.\n if (headers instanceof HeadersList) {\n for (const [key, val] of headers) {\n headersList.append(key, val)\n }\n // Note: Copy the `set-cookie` meta-data.\n headersList.cookies = headers.cookies\n } else {\n // 5. Otherwise, fill this’s headers with headers.\n fillHeaders(this[kHeaders], headers)\n }\n }\n\n // 33. Let inputBody be input’s request’s body if input is a Request\n // object; otherwise null.\n const inputBody = input instanceof Request ? input[kState].body : null\n\n // 34. If either init[\"body\"] exists and is non-null or inputBody is\n // non-null, and request’s method is `GET` or `HEAD`, then throw a\n // TypeError.\n if (\n (init.body != null || inputBody != null) &&\n (request.method === 'GET' || request.method === 'HEAD')\n ) {\n throw new TypeError('Request with GET/HEAD method cannot have body.')\n }\n\n // 35. Let initBody be null.\n let initBody = null\n\n // 36. If init[\"body\"] exists and is non-null, then:\n if (init.body != null) {\n // 1. Let Content-Type be null.\n // 2. Set initBody and Content-Type to the result of extracting\n // init[\"body\"], with keepalive set to request’s keepalive.\n const [extractedBody, contentType] = extractBody(\n init.body,\n request.keepalive\n )\n initBody = extractedBody\n\n // 3, If Content-Type is non-null and this’s headers’s header list does\n // not contain `Content-Type`, then append `Content-Type`/Content-Type to\n // this’s headers.\n if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {\n this[kHeaders].append('content-type', contentType)\n }\n }\n\n // 37. Let inputOrInitBody be initBody if it is non-null; otherwise\n // inputBody.\n const inputOrInitBody = initBody ?? inputBody\n\n // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is\n // null, then:\n if (inputOrInitBody != null && inputOrInitBody.source == null) {\n // 1. If initBody is non-null and init[\"duplex\"] does not exist,\n // then throw a TypeError.\n if (initBody != null && init.duplex == null) {\n throw new TypeError('RequestInit: duplex option is required when sending a body.')\n }\n\n // 2. If this’s request’s mode is neither \"same-origin\" nor \"cors\",\n // then throw a TypeError.\n if (request.mode !== 'same-origin' && request.mode !== 'cors') {\n throw new TypeError(\n 'If request is made from ReadableStream, mode should be \"same-origin\" or \"cors\"'\n )\n }\n\n // 3. Set this’s request’s use-CORS-preflight flag.\n request.useCORSPreflightFlag = true\n }\n\n // 39. Let finalBody be inputOrInitBody.\n let finalBody = inputOrInitBody\n\n // 40. If initBody is null and inputBody is non-null, then:\n if (initBody == null && inputBody != null) {\n // 1. If input is unusable, then throw a TypeError.\n if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {\n throw new TypeError(\n 'Cannot construct a Request with a Request object that has already been used.'\n )\n }\n\n // 2. Set finalBody to the result of creating a proxy for inputBody.\n if (!TransformStream) {\n TransformStream = require('stream/web').TransformStream\n }\n\n // https://streams.spec.whatwg.org/#readablestream-create-a-proxy\n const identityTransform = new TransformStream()\n inputBody.stream.pipeThrough(identityTransform)\n finalBody = {\n source: inputBody.source,\n length: inputBody.length,\n stream: identityTransform.readable\n }\n }\n\n // 41. Set this’s request’s body to finalBody.\n this[kState].body = finalBody\n }\n\n // Returns request’s HTTP method, which is \"GET\" by default.\n get method () {\n webidl.brandCheck(this, Request)\n\n // The method getter steps are to return this’s request’s method.\n return this[kState].method\n }\n\n // Returns the URL of request as a string.\n get url () {\n webidl.brandCheck(this, Request)\n\n // The url getter steps are to return this’s request’s URL, serialized.\n return URLSerializer(this[kState].url)\n }\n\n // Returns a Headers object consisting of the headers associated with request.\n // Note that headers added in the network layer by the user agent will not\n // be accounted for in this object, e.g., the \"Host\" header.\n get headers () {\n webidl.brandCheck(this, Request)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }\n\n // Returns the kind of resource requested by request, e.g., \"document\"\n // or \"script\".\n get destination () {\n webidl.brandCheck(this, Request)\n\n // The destination getter are to return this’s request’s destination.\n return this[kState].destination\n }\n\n // Returns the referrer of request. Its value can be a same-origin URL if\n // explicitly set in init, the empty string to indicate no referrer, and\n // \"about:client\" when defaulting to the global’s default. This is used\n // during fetching to determine the value of the `Referer` header of the\n // request being made.\n get referrer () {\n webidl.brandCheck(this, Request)\n\n // 1. If this’s request’s referrer is \"no-referrer\", then return the\n // empty string.\n if (this[kState].referrer === 'no-referrer') {\n return ''\n }\n\n // 2. If this’s request’s referrer is \"client\", then return\n // \"about:client\".\n if (this[kState].referrer === 'client') {\n return 'about:client'\n }\n\n // Return this’s request’s referrer, serialized.\n return this[kState].referrer.toString()\n }\n\n // Returns the referrer policy associated with request.\n // This is used during fetching to compute the value of the request’s\n // referrer.\n get referrerPolicy () {\n webidl.brandCheck(this, Request)\n\n // The referrerPolicy getter steps are to return this’s request’s referrer policy.\n return this[kState].referrerPolicy\n }\n\n // Returns the mode associated with request, which is a string indicating\n // whether the request will use CORS, or will be restricted to same-origin\n // URLs.\n get mode () {\n webidl.brandCheck(this, Request)\n\n // The mode getter steps are to return this’s request’s mode.\n return this[kState].mode\n }\n\n // Returns the credentials mode associated with request,\n // which is a string indicating whether credentials will be sent with the\n // request always, never, or only when sent to a same-origin URL.\n get credentials () {\n // The credentials getter steps are to return this’s request’s credentials mode.\n return this[kState].credentials\n }\n\n // Returns the cache mode associated with request,\n // which is a string indicating how the request will\n // interact with the browser’s cache when fetching.\n get cache () {\n webidl.brandCheck(this, Request)\n\n // The cache getter steps are to return this’s request’s cache mode.\n return this[kState].cache\n }\n\n // Returns the redirect mode associated with request,\n // which is a string indicating how redirects for the\n // request will be handled during fetching. A request\n // will follow redirects by default.\n get redirect () {\n webidl.brandCheck(this, Request)\n\n // The redirect getter steps are to return this’s request’s redirect mode.\n return this[kState].redirect\n }\n\n // Returns request’s subresource integrity metadata, which is a\n // cryptographic hash of the resource being fetched. Its value\n // consists of multiple hashes separated by whitespace. [SRI]\n get integrity () {\n webidl.brandCheck(this, Request)\n\n // The integrity getter steps are to return this’s request’s integrity\n // metadata.\n return this[kState].integrity\n }\n\n // Returns a boolean indicating whether or not request can outlive the\n // global in which it was created.\n get keepalive () {\n webidl.brandCheck(this, Request)\n\n // The keepalive getter steps are to return this’s request’s keepalive.\n return this[kState].keepalive\n }\n\n // Returns a boolean indicating whether or not request is for a reload\n // navigation.\n get isReloadNavigation () {\n webidl.brandCheck(this, Request)\n\n // The isReloadNavigation getter steps are to return true if this’s\n // request’s reload-navigation flag is set; otherwise false.\n return this[kState].reloadNavigation\n }\n\n // Returns a boolean indicating whether or not request is for a history\n // navigation (a.k.a. back-foward navigation).\n get isHistoryNavigation () {\n webidl.brandCheck(this, Request)\n\n // The isHistoryNavigation getter steps are to return true if this’s request’s\n // history-navigation flag is set; otherwise false.\n return this[kState].historyNavigation\n }\n\n // Returns the signal associated with request, which is an AbortSignal\n // object indicating whether or not request has been aborted, and its\n // abort event handler.\n get signal () {\n webidl.brandCheck(this, Request)\n\n // The signal getter steps are to return this’s signal.\n return this[kSignal]\n }\n\n get body () {\n webidl.brandCheck(this, Request)\n\n return this[kState].body ? this[kState].body.stream : null\n }\n\n get bodyUsed () {\n webidl.brandCheck(this, Request)\n\n return !!this[kState].body && util.isDisturbed(this[kState].body.stream)\n }\n\n get duplex () {\n webidl.brandCheck(this, Request)\n\n return 'half'\n }\n\n // Returns a clone of request.\n clone () {\n webidl.brandCheck(this, Request)\n\n // 1. If this is unusable, then throw a TypeError.\n if (this.bodyUsed || this.body?.locked) {\n throw new TypeError('unusable')\n }\n\n // 2. Let clonedRequest be the result of cloning this’s request.\n const clonedRequest = cloneRequest(this[kState])\n\n // 3. Let clonedRequestObject be the result of creating a Request object,\n // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.\n const clonedRequestObject = new Request(kConstruct)\n clonedRequestObject[kState] = clonedRequest\n clonedRequestObject[kRealm] = this[kRealm]\n clonedRequestObject[kHeaders] = new Headers(kConstruct)\n clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList\n clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]\n clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]\n\n // 4. Make clonedRequestObject’s signal follow this’s signal.\n const ac = new AbortController()\n if (this.signal.aborted) {\n ac.abort(this.signal.reason)\n } else {\n util.addAbortListener(\n this.signal,\n () => {\n ac.abort(this.signal.reason)\n }\n )\n }\n clonedRequestObject[kSignal] = ac.signal\n\n // 4. Return clonedRequestObject.\n return clonedRequestObject\n }\n}\n\nmixinBody(Request)\n\nfunction makeRequest (init) {\n // https://fetch.spec.whatwg.org/#requests\n const request = {\n method: 'GET',\n localURLsOnly: false,\n unsafeRequest: false,\n body: null,\n client: null,\n reservedClient: null,\n replacesClientId: '',\n window: 'client',\n keepalive: false,\n serviceWorkers: 'all',\n initiator: '',\n destination: '',\n priority: null,\n origin: 'client',\n policyContainer: 'client',\n referrer: 'client',\n referrerPolicy: '',\n mode: 'no-cors',\n useCORSPreflightFlag: false,\n credentials: 'same-origin',\n useCredentials: false,\n cache: 'default',\n redirect: 'follow',\n integrity: '',\n cryptoGraphicsNonceMetadata: '',\n parserMetadata: '',\n reloadNavigation: false,\n historyNavigation: false,\n userActivation: false,\n taintedOrigin: false,\n redirectCount: 0,\n responseTainting: 'basic',\n preventNoCacheCacheControlHeaderModification: false,\n done: false,\n timingAllowFailed: false,\n ...init,\n headersList: init.headersList\n ? new HeadersList(init.headersList)\n : new HeadersList()\n }\n request.url = request.urlList[0]\n return request\n}\n\n// https://fetch.spec.whatwg.org/#concept-request-clone\nfunction cloneRequest (request) {\n // To clone a request request, run these steps:\n\n // 1. Let newRequest be a copy of request, except for its body.\n const newRequest = makeRequest({ ...request, body: null })\n\n // 2. If request’s body is non-null, set newRequest’s body to the\n // result of cloning request’s body.\n if (request.body != null) {\n newRequest.body = cloneBody(request.body)\n }\n\n // 3. Return newRequest.\n return newRequest\n}\n\nObject.defineProperties(Request.prototype, {\n method: kEnumerableProperty,\n url: kEnumerableProperty,\n headers: kEnumerableProperty,\n redirect: kEnumerableProperty,\n clone: kEnumerableProperty,\n signal: kEnumerableProperty,\n duplex: kEnumerableProperty,\n destination: kEnumerableProperty,\n body: kEnumerableProperty,\n bodyUsed: kEnumerableProperty,\n isHistoryNavigation: kEnumerableProperty,\n isReloadNavigation: kEnumerableProperty,\n keepalive: kEnumerableProperty,\n integrity: kEnumerableProperty,\n cache: kEnumerableProperty,\n credentials: kEnumerableProperty,\n attribute: kEnumerableProperty,\n referrerPolicy: kEnumerableProperty,\n referrer: kEnumerableProperty,\n mode: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Request',\n configurable: true\n }\n})\n\nwebidl.converters.Request = webidl.interfaceConverter(\n Request\n)\n\n// https://fetch.spec.whatwg.org/#requestinfo\nwebidl.converters.RequestInfo = function (V) {\n if (typeof V === 'string') {\n return webidl.converters.USVString(V)\n }\n\n if (V instanceof Request) {\n return webidl.converters.Request(V)\n }\n\n return webidl.converters.USVString(V)\n}\n\nwebidl.converters.AbortSignal = webidl.interfaceConverter(\n AbortSignal\n)\n\n// https://fetch.spec.whatwg.org/#requestinit\nwebidl.converters.RequestInit = webidl.dictionaryConverter([\n {\n key: 'method',\n converter: webidl.converters.ByteString\n },\n {\n key: 'headers',\n converter: webidl.converters.HeadersInit\n },\n {\n key: 'body',\n converter: webidl.nullableConverter(\n webidl.converters.BodyInit\n )\n },\n {\n key: 'referrer',\n converter: webidl.converters.USVString\n },\n {\n key: 'referrerPolicy',\n converter: webidl.converters.DOMString,\n // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy\n allowedValues: referrerPolicy\n },\n {\n key: 'mode',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#concept-request-mode\n allowedValues: requestMode\n },\n {\n key: 'credentials',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestcredentials\n allowedValues: requestCredentials\n },\n {\n key: 'cache',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestcache\n allowedValues: requestCache\n },\n {\n key: 'redirect',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestredirect\n allowedValues: requestRedirect\n },\n {\n key: 'integrity',\n converter: webidl.converters.DOMString\n },\n {\n key: 'keepalive',\n converter: webidl.converters.boolean\n },\n {\n key: 'signal',\n converter: webidl.nullableConverter(\n (signal) => webidl.converters.AbortSignal(\n signal,\n { strict: false }\n )\n )\n },\n {\n key: 'window',\n converter: webidl.converters.any\n },\n {\n key: 'duplex',\n converter: webidl.converters.DOMString,\n allowedValues: requestDuplex\n }\n])\n\nmodule.exports = { Request, makeRequest }\n","'use strict'\n\nconst { Headers, HeadersList, fill } = require('./headers')\nconst { extractBody, cloneBody, mixinBody } = require('./body')\nconst util = require('../core/util')\nconst { kEnumerableProperty } = util\nconst {\n isValidReasonPhrase,\n isCancelled,\n isAborted,\n isBlobLike,\n serializeJavascriptValueToJSONString,\n isErrorLike,\n isomorphicEncode\n} = require('./util')\nconst {\n redirectStatusSet,\n nullBodyStatus,\n DOMException\n} = require('./constants')\nconst { kState, kHeaders, kGuard, kRealm } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { FormData } = require('./formdata')\nconst { getGlobalOrigin } = require('./global')\nconst { URLSerializer } = require('./dataURL')\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst assert = require('assert')\nconst { types } = require('util')\n\nconst ReadableStream = globalThis.ReadableStream || require('stream/web').ReadableStream\nconst textEncoder = new TextEncoder('utf-8')\n\n// https://fetch.spec.whatwg.org/#response-class\nclass Response {\n // Creates network error Response.\n static error () {\n // TODO\n const relevantRealm = { settingsObject: {} }\n\n // The static error() method steps are to return the result of creating a\n // Response object, given a new network error, \"immutable\", and this’s\n // relevant Realm.\n const responseObject = new Response()\n responseObject[kState] = makeNetworkError()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n return responseObject\n }\n\n // https://fetch.spec.whatwg.org/#dom-response-json\n static json (data, init = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })\n\n if (init !== null) {\n init = webidl.converters.ResponseInit(init)\n }\n\n // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.\n const bytes = textEncoder.encode(\n serializeJavascriptValueToJSONString(data)\n )\n\n // 2. Let body be the result of extracting bytes.\n const body = extractBody(bytes)\n\n // 3. Let responseObject be the result of creating a Response object, given a new response,\n // \"response\", and this’s relevant Realm.\n const relevantRealm = { settingsObject: {} }\n const responseObject = new Response()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kGuard] = 'response'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 4. Perform initialize a response given responseObject, init, and (body, \"application/json\").\n initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })\n\n // 5. Return responseObject.\n return responseObject\n }\n\n // Creates a redirect Response that redirects to url with status status.\n static redirect (url, status = 302) {\n const relevantRealm = { settingsObject: {} }\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })\n\n url = webidl.converters.USVString(url)\n status = webidl.converters['unsigned short'](status)\n\n // 1. Let parsedURL be the result of parsing url with current settings\n // object’s API base URL.\n // 2. If parsedURL is failure, then throw a TypeError.\n // TODO: base-URL?\n let parsedURL\n try {\n parsedURL = new URL(url, getGlobalOrigin())\n } catch (err) {\n throw Object.assign(new TypeError('Failed to parse URL from ' + url), {\n cause: err\n })\n }\n\n // 3. If status is not a redirect status, then throw a RangeError.\n if (!redirectStatusSet.has(status)) {\n throw new RangeError('Invalid status code ' + status)\n }\n\n // 4. Let responseObject be the result of creating a Response object,\n // given a new response, \"immutable\", and this’s relevant Realm.\n const responseObject = new Response()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 5. Set responseObject’s response’s status to status.\n responseObject[kState].status = status\n\n // 6. Let value be parsedURL, serialized and isomorphic encoded.\n const value = isomorphicEncode(URLSerializer(parsedURL))\n\n // 7. Append `Location`/value to responseObject’s response’s header list.\n responseObject[kState].headersList.append('location', value)\n\n // 8. Return responseObject.\n return responseObject\n }\n\n // https://fetch.spec.whatwg.org/#dom-response\n constructor (body = null, init = {}) {\n if (body !== null) {\n body = webidl.converters.BodyInit(body)\n }\n\n init = webidl.converters.ResponseInit(init)\n\n // TODO\n this[kRealm] = { settingsObject: {} }\n\n // 1. Set this’s response to a new response.\n this[kState] = makeResponse({})\n\n // 2. Set this’s headers to a new Headers object with this’s relevant\n // Realm, whose header list is this’s response’s header list and guard\n // is \"response\".\n this[kHeaders] = new Headers(kConstruct)\n this[kHeaders][kGuard] = 'response'\n this[kHeaders][kHeadersList] = this[kState].headersList\n this[kHeaders][kRealm] = this[kRealm]\n\n // 3. Let bodyWithType be null.\n let bodyWithType = null\n\n // 4. If body is non-null, then set bodyWithType to the result of extracting body.\n if (body != null) {\n const [extractedBody, type] = extractBody(body)\n bodyWithType = { body: extractedBody, type }\n }\n\n // 5. Perform initialize a response given this, init, and bodyWithType.\n initializeResponse(this, init, bodyWithType)\n }\n\n // Returns response’s type, e.g., \"cors\".\n get type () {\n webidl.brandCheck(this, Response)\n\n // The type getter steps are to return this’s response’s type.\n return this[kState].type\n }\n\n // Returns response’s URL, if it has one; otherwise the empty string.\n get url () {\n webidl.brandCheck(this, Response)\n\n const urlList = this[kState].urlList\n\n // The url getter steps are to return the empty string if this’s\n // response’s URL is null; otherwise this’s response’s URL,\n // serialized with exclude fragment set to true.\n const url = urlList[urlList.length - 1] ?? null\n\n if (url === null) {\n return ''\n }\n\n return URLSerializer(url, true)\n }\n\n // Returns whether response was obtained through a redirect.\n get redirected () {\n webidl.brandCheck(this, Response)\n\n // The redirected getter steps are to return true if this’s response’s URL\n // list has more than one item; otherwise false.\n return this[kState].urlList.length > 1\n }\n\n // Returns response’s status.\n get status () {\n webidl.brandCheck(this, Response)\n\n // The status getter steps are to return this’s response’s status.\n return this[kState].status\n }\n\n // Returns whether response’s status is an ok status.\n get ok () {\n webidl.brandCheck(this, Response)\n\n // The ok getter steps are to return true if this’s response’s status is an\n // ok status; otherwise false.\n return this[kState].status >= 200 && this[kState].status <= 299\n }\n\n // Returns response’s status message.\n get statusText () {\n webidl.brandCheck(this, Response)\n\n // The statusText getter steps are to return this’s response’s status\n // message.\n return this[kState].statusText\n }\n\n // Returns response’s headers as Headers.\n get headers () {\n webidl.brandCheck(this, Response)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }\n\n get body () {\n webidl.brandCheck(this, Response)\n\n return this[kState].body ? this[kState].body.stream : null\n }\n\n get bodyUsed () {\n webidl.brandCheck(this, Response)\n\n return !!this[kState].body && util.isDisturbed(this[kState].body.stream)\n }\n\n // Returns a clone of response.\n clone () {\n webidl.brandCheck(this, Response)\n\n // 1. If this is unusable, then throw a TypeError.\n if (this.bodyUsed || (this.body && this.body.locked)) {\n throw webidl.errors.exception({\n header: 'Response.clone',\n message: 'Body has already been consumed.'\n })\n }\n\n // 2. Let clonedResponse be the result of cloning this’s response.\n const clonedResponse = cloneResponse(this[kState])\n\n // 3. Return the result of creating a Response object, given\n // clonedResponse, this’s headers’s guard, and this’s relevant Realm.\n const clonedResponseObject = new Response()\n clonedResponseObject[kState] = clonedResponse\n clonedResponseObject[kRealm] = this[kRealm]\n clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList\n clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]\n clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]\n\n return clonedResponseObject\n }\n}\n\nmixinBody(Response)\n\nObject.defineProperties(Response.prototype, {\n type: kEnumerableProperty,\n url: kEnumerableProperty,\n status: kEnumerableProperty,\n ok: kEnumerableProperty,\n redirected: kEnumerableProperty,\n statusText: kEnumerableProperty,\n headers: kEnumerableProperty,\n clone: kEnumerableProperty,\n body: kEnumerableProperty,\n bodyUsed: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Response',\n configurable: true\n }\n})\n\nObject.defineProperties(Response, {\n json: kEnumerableProperty,\n redirect: kEnumerableProperty,\n error: kEnumerableProperty\n})\n\n// https://fetch.spec.whatwg.org/#concept-response-clone\nfunction cloneResponse (response) {\n // To clone a response response, run these steps:\n\n // 1. If response is a filtered response, then return a new identical\n // filtered response whose internal response is a clone of response’s\n // internal response.\n if (response.internalResponse) {\n return filterResponse(\n cloneResponse(response.internalResponse),\n response.type\n )\n }\n\n // 2. Let newResponse be a copy of response, except for its body.\n const newResponse = makeResponse({ ...response, body: null })\n\n // 3. If response’s body is non-null, then set newResponse’s body to the\n // result of cloning response’s body.\n if (response.body != null) {\n newResponse.body = cloneBody(response.body)\n }\n\n // 4. Return newResponse.\n return newResponse\n}\n\nfunction makeResponse (init) {\n return {\n aborted: false,\n rangeRequested: false,\n timingAllowPassed: false,\n requestIncludesCredentials: false,\n type: 'default',\n status: 200,\n timingInfo: null,\n cacheState: '',\n statusText: '',\n ...init,\n headersList: init.headersList\n ? new HeadersList(init.headersList)\n : new HeadersList(),\n urlList: init.urlList ? [...init.urlList] : []\n }\n}\n\nfunction makeNetworkError (reason) {\n const isError = isErrorLike(reason)\n return makeResponse({\n type: 'error',\n status: 0,\n error: isError\n ? reason\n : new Error(reason ? String(reason) : reason),\n aborted: reason && reason.name === 'AbortError'\n })\n}\n\nfunction makeFilteredResponse (response, state) {\n state = {\n internalResponse: response,\n ...state\n }\n\n return new Proxy(response, {\n get (target, p) {\n return p in state ? state[p] : target[p]\n },\n set (target, p, value) {\n assert(!(p in state))\n target[p] = value\n return true\n }\n })\n}\n\n// https://fetch.spec.whatwg.org/#concept-filtered-response\nfunction filterResponse (response, type) {\n // Set response to the following filtered response with response as its\n // internal response, depending on request’s response tainting:\n if (type === 'basic') {\n // A basic filtered response is a filtered response whose type is \"basic\"\n // and header list excludes any headers in internal response’s header list\n // whose name is a forbidden response-header name.\n\n // Note: undici does not implement forbidden response-header names\n return makeFilteredResponse(response, {\n type: 'basic',\n headersList: response.headersList\n })\n } else if (type === 'cors') {\n // A CORS filtered response is a filtered response whose type is \"cors\"\n // and header list excludes any headers in internal response’s header\n // list whose name is not a CORS-safelisted response-header name, given\n // internal response’s CORS-exposed header-name list.\n\n // Note: undici does not implement CORS-safelisted response-header names\n return makeFilteredResponse(response, {\n type: 'cors',\n headersList: response.headersList\n })\n } else if (type === 'opaque') {\n // An opaque filtered response is a filtered response whose type is\n // \"opaque\", URL list is the empty list, status is 0, status message\n // is the empty byte sequence, header list is empty, and body is null.\n\n return makeFilteredResponse(response, {\n type: 'opaque',\n urlList: Object.freeze([]),\n status: 0,\n statusText: '',\n body: null\n })\n } else if (type === 'opaqueredirect') {\n // An opaque-redirect filtered response is a filtered response whose type\n // is \"opaqueredirect\", status is 0, status message is the empty byte\n // sequence, header list is empty, and body is null.\n\n return makeFilteredResponse(response, {\n type: 'opaqueredirect',\n status: 0,\n statusText: '',\n headersList: [],\n body: null\n })\n } else {\n assert(false)\n }\n}\n\n// https://fetch.spec.whatwg.org/#appropriate-network-error\nfunction makeAppropriateNetworkError (fetchParams, err = null) {\n // 1. Assert: fetchParams is canceled.\n assert(isCancelled(fetchParams))\n\n // 2. Return an aborted network error if fetchParams is aborted;\n // otherwise return a network error.\n return isAborted(fetchParams)\n ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))\n : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))\n}\n\n// https://whatpr.org/fetch/1392.html#initialize-a-response\nfunction initializeResponse (response, init, body) {\n // 1. If init[\"status\"] is not in the range 200 to 599, inclusive, then\n // throw a RangeError.\n if (init.status !== null && (init.status < 200 || init.status > 599)) {\n throw new RangeError('init[\"status\"] must be in the range of 200 to 599, inclusive.')\n }\n\n // 2. If init[\"statusText\"] does not match the reason-phrase token production,\n // then throw a TypeError.\n if ('statusText' in init && init.statusText != null) {\n // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:\n // reason-phrase = *( HTAB / SP / VCHAR / obs-text )\n if (!isValidReasonPhrase(String(init.statusText))) {\n throw new TypeError('Invalid statusText')\n }\n }\n\n // 3. Set response’s response’s status to init[\"status\"].\n if ('status' in init && init.status != null) {\n response[kState].status = init.status\n }\n\n // 4. Set response’s response’s status message to init[\"statusText\"].\n if ('statusText' in init && init.statusText != null) {\n response[kState].statusText = init.statusText\n }\n\n // 5. If init[\"headers\"] exists, then fill response’s headers with init[\"headers\"].\n if ('headers' in init && init.headers != null) {\n fill(response[kHeaders], init.headers)\n }\n\n // 6. If body was given, then:\n if (body) {\n // 1. If response's status is a null body status, then throw a TypeError.\n if (nullBodyStatus.includes(response.status)) {\n throw webidl.errors.exception({\n header: 'Response constructor',\n message: 'Invalid response status code ' + response.status\n })\n }\n\n // 2. Set response's body to body's body.\n response[kState].body = body.body\n\n // 3. If body's type is non-null and response's header list does not contain\n // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.\n if (body.type != null && !response[kState].headersList.contains('Content-Type')) {\n response[kState].headersList.append('content-type', body.type)\n }\n }\n}\n\nwebidl.converters.ReadableStream = webidl.interfaceConverter(\n ReadableStream\n)\n\nwebidl.converters.FormData = webidl.interfaceConverter(\n FormData\n)\n\nwebidl.converters.URLSearchParams = webidl.interfaceConverter(\n URLSearchParams\n)\n\n// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit\nwebidl.converters.XMLHttpRequestBodyInit = function (V) {\n if (typeof V === 'string') {\n return webidl.converters.USVString(V)\n }\n\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {\n return webidl.converters.BufferSource(V)\n }\n\n if (util.isFormDataLike(V)) {\n return webidl.converters.FormData(V, { strict: false })\n }\n\n if (V instanceof URLSearchParams) {\n return webidl.converters.URLSearchParams(V)\n }\n\n return webidl.converters.DOMString(V)\n}\n\n// https://fetch.spec.whatwg.org/#bodyinit\nwebidl.converters.BodyInit = function (V) {\n if (V instanceof ReadableStream) {\n return webidl.converters.ReadableStream(V)\n }\n\n // Note: the spec doesn't include async iterables,\n // this is an undici extension.\n if (V?.[Symbol.asyncIterator]) {\n return V\n }\n\n return webidl.converters.XMLHttpRequestBodyInit(V)\n}\n\nwebidl.converters.ResponseInit = webidl.dictionaryConverter([\n {\n key: 'status',\n converter: webidl.converters['unsigned short'],\n defaultValue: 200\n },\n {\n key: 'statusText',\n converter: webidl.converters.ByteString,\n defaultValue: ''\n },\n {\n key: 'headers',\n converter: webidl.converters.HeadersInit\n }\n])\n\nmodule.exports = {\n makeNetworkError,\n makeResponse,\n makeAppropriateNetworkError,\n filterResponse,\n Response,\n cloneResponse\n}\n","'use strict'\n\nmodule.exports = {\n kUrl: Symbol('url'),\n kHeaders: Symbol('headers'),\n kSignal: Symbol('signal'),\n kState: Symbol('state'),\n kGuard: Symbol('guard'),\n kRealm: Symbol('realm')\n}\n","'use strict'\n\nconst { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require('./constants')\nconst { getGlobalOrigin } = require('./global')\nconst { performance } = require('perf_hooks')\nconst { isBlobLike, toUSVString, ReadableStreamFrom } = require('../core/util')\nconst assert = require('assert')\nconst { isUint8Array } = require('util/types')\n\nlet supportedHashes = []\n\n// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable\n/** @type {import('crypto')|undefined} */\nlet crypto\n\ntry {\n crypto = require('crypto')\n const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']\n supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))\n/* c8 ignore next 3 */\n} catch {\n}\n\nfunction responseURL (response) {\n // https://fetch.spec.whatwg.org/#responses\n // A response has an associated URL. It is a pointer to the last URL\n // in response’s URL list and null if response’s URL list is empty.\n const urlList = response.urlList\n const length = urlList.length\n return length === 0 ? null : urlList[length - 1].toString()\n}\n\n// https://fetch.spec.whatwg.org/#concept-response-location-url\nfunction responseLocationURL (response, requestFragment) {\n // 1. If response’s status is not a redirect status, then return null.\n if (!redirectStatusSet.has(response.status)) {\n return null\n }\n\n // 2. Let location be the result of extracting header list values given\n // `Location` and response’s header list.\n let location = response.headersList.get('location')\n\n // 3. If location is a header value, then set location to the result of\n // parsing location with response’s URL.\n if (location !== null && isValidHeaderValue(location)) {\n location = new URL(location, responseURL(response))\n }\n\n // 4. If location is a URL whose fragment is null, then set location’s\n // fragment to requestFragment.\n if (location && !location.hash) {\n location.hash = requestFragment\n }\n\n // 5. Return location.\n return location\n}\n\n/** @returns {URL} */\nfunction requestCurrentURL (request) {\n return request.urlList[request.urlList.length - 1]\n}\n\nfunction requestBadPort (request) {\n // 1. Let url be request’s current URL.\n const url = requestCurrentURL(request)\n\n // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,\n // then return blocked.\n if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {\n return 'blocked'\n }\n\n // 3. Return allowed.\n return 'allowed'\n}\n\nfunction isErrorLike (object) {\n return object instanceof Error || (\n object?.constructor?.name === 'Error' ||\n object?.constructor?.name === 'DOMException'\n )\n}\n\n// Check whether |statusText| is a ByteString and\n// matches the Reason-Phrase token production.\n// RFC 2616: https://tools.ietf.org/html/rfc2616\n// RFC 7230: https://tools.ietf.org/html/rfc7230\n// \"reason-phrase = *( HTAB / SP / VCHAR / obs-text )\"\n// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116\nfunction isValidReasonPhrase (statusText) {\n for (let i = 0; i < statusText.length; ++i) {\n const c = statusText.charCodeAt(i)\n if (\n !(\n (\n c === 0x09 || // HTAB\n (c >= 0x20 && c <= 0x7e) || // SP / VCHAR\n (c >= 0x80 && c <= 0xff)\n ) // obs-text\n )\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * @see https://tools.ietf.org/html/rfc7230#section-3.2.6\n * @param {number} c\n */\nfunction isTokenCharCode (c) {\n switch (c) {\n case 0x22:\n case 0x28:\n case 0x29:\n case 0x2c:\n case 0x2f:\n case 0x3a:\n case 0x3b:\n case 0x3c:\n case 0x3d:\n case 0x3e:\n case 0x3f:\n case 0x40:\n case 0x5b:\n case 0x5c:\n case 0x5d:\n case 0x7b:\n case 0x7d:\n // DQUOTE and \"(),/:;<=>?@[\\]{}\"\n return false\n default:\n // VCHAR %x21-7E\n return c >= 0x21 && c <= 0x7e\n }\n}\n\n/**\n * @param {string} characters\n */\nfunction isValidHTTPToken (characters) {\n if (characters.length === 0) {\n return false\n }\n for (let i = 0; i < characters.length; ++i) {\n if (!isTokenCharCode(characters.charCodeAt(i))) {\n return false\n }\n }\n return true\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-name\n * @param {string} potentialValue\n */\nfunction isValidHeaderName (potentialValue) {\n return isValidHTTPToken(potentialValue)\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-value\n * @param {string} potentialValue\n */\nfunction isValidHeaderValue (potentialValue) {\n // - Has no leading or trailing HTTP tab or space bytes.\n // - Contains no 0x00 (NUL) or HTTP newline bytes.\n if (\n potentialValue.startsWith('\\t') ||\n potentialValue.startsWith(' ') ||\n potentialValue.endsWith('\\t') ||\n potentialValue.endsWith(' ')\n ) {\n return false\n }\n\n if (\n potentialValue.includes('\\0') ||\n potentialValue.includes('\\r') ||\n potentialValue.includes('\\n')\n ) {\n return false\n }\n\n return true\n}\n\n// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect\nfunction setRequestReferrerPolicyOnRedirect (request, actualResponse) {\n // Given a request request and a response actualResponse, this algorithm\n // updates request’s referrer policy according to the Referrer-Policy\n // header (if any) in actualResponse.\n\n // 1. Let policy be the result of executing § 8.1 Parse a referrer policy\n // from a Referrer-Policy header on actualResponse.\n\n // 8.1 Parse a referrer policy from a Referrer-Policy header\n // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.\n const { headersList } = actualResponse\n // 2. Let policy be the empty string.\n // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.\n // 4. Return policy.\n const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')\n\n // Note: As the referrer-policy can contain multiple policies\n // separated by comma, we need to loop through all of them\n // and pick the first valid one.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy\n let policy = ''\n if (policyHeader.length > 0) {\n // The right-most policy takes precedence.\n // The left-most policy is the fallback.\n for (let i = policyHeader.length; i !== 0; i--) {\n const token = policyHeader[i - 1].trim()\n if (referrerPolicyTokens.has(token)) {\n policy = token\n break\n }\n }\n }\n\n // 2. If policy is not the empty string, then set request’s referrer policy to policy.\n if (policy !== '') {\n request.referrerPolicy = policy\n }\n}\n\n// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check\nfunction crossOriginResourcePolicyCheck () {\n // TODO\n return 'allowed'\n}\n\n// https://fetch.spec.whatwg.org/#concept-cors-check\nfunction corsCheck () {\n // TODO\n return 'success'\n}\n\n// https://fetch.spec.whatwg.org/#concept-tao-check\nfunction TAOCheck () {\n // TODO\n return 'success'\n}\n\nfunction appendFetchMetadata (httpRequest) {\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header\n // TODO\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header\n\n // 1. Assert: r’s url is a potentially trustworthy URL.\n // TODO\n\n // 2. Let header be a Structured Header whose value is a token.\n let header = null\n\n // 3. Set header’s value to r’s mode.\n header = httpRequest.mode\n\n // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.\n httpRequest.headersList.set('sec-fetch-mode', header)\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header\n // TODO\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header\n // TODO\n}\n\n// https://fetch.spec.whatwg.org/#append-a-request-origin-header\nfunction appendRequestOriginHeader (request) {\n // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.\n let serializedOrigin = request.origin\n\n // 2. If request’s response tainting is \"cors\" or request’s mode is \"websocket\", then append (`Origin`, serializedOrigin) to request’s header list.\n if (request.responseTainting === 'cors' || request.mode === 'websocket') {\n if (serializedOrigin) {\n request.headersList.append('origin', serializedOrigin)\n }\n\n // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:\n } else if (request.method !== 'GET' && request.method !== 'HEAD') {\n // 1. Switch on request’s referrer policy:\n switch (request.referrerPolicy) {\n case 'no-referrer':\n // Set serializedOrigin to `null`.\n serializedOrigin = null\n break\n case 'no-referrer-when-downgrade':\n case 'strict-origin':\n case 'strict-origin-when-cross-origin':\n // If request’s origin is a tuple origin, its scheme is \"https\", and request’s current URL’s scheme is not \"https\", then set serializedOrigin to `null`.\n if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {\n serializedOrigin = null\n }\n break\n case 'same-origin':\n // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.\n if (!sameOrigin(request, requestCurrentURL(request))) {\n serializedOrigin = null\n }\n break\n default:\n // Do nothing.\n }\n\n if (serializedOrigin) {\n // 2. Append (`Origin`, serializedOrigin) to request’s header list.\n request.headersList.append('origin', serializedOrigin)\n }\n }\n}\n\nfunction coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {\n // TODO\n return performance.now()\n}\n\n// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info\nfunction createOpaqueTimingInfo (timingInfo) {\n return {\n startTime: timingInfo.startTime ?? 0,\n redirectStartTime: 0,\n redirectEndTime: 0,\n postRedirectStartTime: timingInfo.startTime ?? 0,\n finalServiceWorkerStartTime: 0,\n finalNetworkResponseStartTime: 0,\n finalNetworkRequestStartTime: 0,\n endTime: 0,\n encodedBodySize: 0,\n decodedBodySize: 0,\n finalConnectionTimingInfo: null\n }\n}\n\n// https://html.spec.whatwg.org/multipage/origin.html#policy-container\nfunction makePolicyContainer () {\n // Note: the fetch spec doesn't make use of embedder policy or CSP list\n return {\n referrerPolicy: 'strict-origin-when-cross-origin'\n }\n}\n\n// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container\nfunction clonePolicyContainer (policyContainer) {\n return {\n referrerPolicy: policyContainer.referrerPolicy\n }\n}\n\n// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer\nfunction determineRequestsReferrer (request) {\n // 1. Let policy be request's referrer policy.\n const policy = request.referrerPolicy\n\n // Note: policy cannot (shouldn't) be null or an empty string.\n assert(policy)\n\n // 2. Let environment be request’s client.\n\n let referrerSource = null\n\n // 3. Switch on request’s referrer:\n if (request.referrer === 'client') {\n // Note: node isn't a browser and doesn't implement document/iframes,\n // so we bypass this step and replace it with our own.\n\n const globalOrigin = getGlobalOrigin()\n\n if (!globalOrigin || globalOrigin.origin === 'null') {\n return 'no-referrer'\n }\n\n // note: we need to clone it as it's mutated\n referrerSource = new URL(globalOrigin)\n } else if (request.referrer instanceof URL) {\n // Let referrerSource be request’s referrer.\n referrerSource = request.referrer\n }\n\n // 4. Let request’s referrerURL be the result of stripping referrerSource for\n // use as a referrer.\n let referrerURL = stripURLForReferrer(referrerSource)\n\n // 5. Let referrerOrigin be the result of stripping referrerSource for use as\n // a referrer, with the origin-only flag set to true.\n const referrerOrigin = stripURLForReferrer(referrerSource, true)\n\n // 6. If the result of serializing referrerURL is a string whose length is\n // greater than 4096, set referrerURL to referrerOrigin.\n if (referrerURL.toString().length > 4096) {\n referrerURL = referrerOrigin\n }\n\n const areSameOrigin = sameOrigin(request, referrerURL)\n const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&\n !isURLPotentiallyTrustworthy(request.url)\n\n // 8. Execute the switch statements corresponding to the value of policy:\n switch (policy) {\n case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)\n case 'unsafe-url': return referrerURL\n case 'same-origin':\n return areSameOrigin ? referrerOrigin : 'no-referrer'\n case 'origin-when-cross-origin':\n return areSameOrigin ? referrerURL : referrerOrigin\n case 'strict-origin-when-cross-origin': {\n const currentURL = requestCurrentURL(request)\n\n // 1. If the origin of referrerURL and the origin of request’s current\n // URL are the same, then return referrerURL.\n if (sameOrigin(referrerURL, currentURL)) {\n return referrerURL\n }\n\n // 2. If referrerURL is a potentially trustworthy URL and request’s\n // current URL is not a potentially trustworthy URL, then return no\n // referrer.\n if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {\n return 'no-referrer'\n }\n\n // 3. Return referrerOrigin.\n return referrerOrigin\n }\n case 'strict-origin': // eslint-disable-line\n /**\n * 1. If referrerURL is a potentially trustworthy URL and\n * request’s current URL is not a potentially trustworthy URL,\n * then return no referrer.\n * 2. Return referrerOrigin\n */\n case 'no-referrer-when-downgrade': // eslint-disable-line\n /**\n * 1. If referrerURL is a potentially trustworthy URL and\n * request’s current URL is not a potentially trustworthy URL,\n * then return no referrer.\n * 2. Return referrerOrigin\n */\n\n default: // eslint-disable-line\n return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin\n }\n}\n\n/**\n * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url\n * @param {URL} url\n * @param {boolean|undefined} originOnly\n */\nfunction stripURLForReferrer (url, originOnly) {\n // 1. Assert: url is a URL.\n assert(url instanceof URL)\n\n // 2. If url’s scheme is a local scheme, then return no referrer.\n if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {\n return 'no-referrer'\n }\n\n // 3. Set url’s username to the empty string.\n url.username = ''\n\n // 4. Set url’s password to the empty string.\n url.password = ''\n\n // 5. Set url’s fragment to null.\n url.hash = ''\n\n // 6. If the origin-only flag is true, then:\n if (originOnly) {\n // 1. Set url’s path to « the empty string ».\n url.pathname = ''\n\n // 2. Set url’s query to null.\n url.search = ''\n }\n\n // 7. Return url.\n return url\n}\n\nfunction isURLPotentiallyTrustworthy (url) {\n if (!(url instanceof URL)) {\n return false\n }\n\n // If child of about, return true\n if (url.href === 'about:blank' || url.href === 'about:srcdoc') {\n return true\n }\n\n // If scheme is data, return true\n if (url.protocol === 'data:') return true\n\n // If file, return true\n if (url.protocol === 'file:') return true\n\n return isOriginPotentiallyTrustworthy(url.origin)\n\n function isOriginPotentiallyTrustworthy (origin) {\n // If origin is explicitly null, return false\n if (origin == null || origin === 'null') return false\n\n const originAsURL = new URL(origin)\n\n // If secure, return true\n if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {\n return true\n }\n\n // If localhost or variants, return true\n if (/^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^\\[(?:0*:)*?:?0*1\\]$/.test(originAsURL.hostname) ||\n (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||\n (originAsURL.hostname.endsWith('.localhost'))) {\n return true\n }\n\n // If any other, return false\n return false\n }\n}\n\n/**\n * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist\n * @param {Uint8Array} bytes\n * @param {string} metadataList\n */\nfunction bytesMatch (bytes, metadataList) {\n // If node is not built with OpenSSL support, we cannot check\n // a request's integrity, so allow it by default (the spec will\n // allow requests if an invalid hash is given, as precedence).\n /* istanbul ignore if: only if node is built with --without-ssl */\n if (crypto === undefined) {\n return true\n }\n\n // 1. Let parsedMetadata be the result of parsing metadataList.\n const parsedMetadata = parseMetadata(metadataList)\n\n // 2. If parsedMetadata is no metadata, return true.\n if (parsedMetadata === 'no metadata') {\n return true\n }\n\n // 3. If response is not eligible for integrity validation, return false.\n // TODO\n\n // 4. If parsedMetadata is the empty set, return true.\n if (parsedMetadata.length === 0) {\n return true\n }\n\n // 5. Let metadata be the result of getting the strongest\n // metadata from parsedMetadata.\n const strongest = getStrongestMetadata(parsedMetadata)\n const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)\n\n // 6. For each item in metadata:\n for (const item of metadata) {\n // 1. Let algorithm be the alg component of item.\n const algorithm = item.algo\n\n // 2. Let expectedValue be the val component of item.\n const expectedValue = item.hash\n\n // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e\n // \"be liberal with padding\". This is annoying, and it's not even in the spec.\n\n // 3. Let actualValue be the result of applying algorithm to bytes.\n let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')\n\n if (actualValue[actualValue.length - 1] === '=') {\n if (actualValue[actualValue.length - 2] === '=') {\n actualValue = actualValue.slice(0, -2)\n } else {\n actualValue = actualValue.slice(0, -1)\n }\n }\n\n // 4. If actualValue is a case-sensitive match for expectedValue,\n // return true.\n if (compareBase64Mixed(actualValue, expectedValue)) {\n return true\n }\n }\n\n // 7. Return false.\n return false\n}\n\n// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options\n// https://www.w3.org/TR/CSP2/#source-list-syntax\n// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1\nconst parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\\s|$)( +[!-~]*)?)?/i\n\n/**\n * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata\n * @param {string} metadata\n */\nfunction parseMetadata (metadata) {\n // 1. Let result be the empty set.\n /** @type {{ algo: string, hash: string }[]} */\n const result = []\n\n // 2. Let empty be equal to true.\n let empty = true\n\n // 3. For each token returned by splitting metadata on spaces:\n for (const token of metadata.split(' ')) {\n // 1. Set empty to false.\n empty = false\n\n // 2. Parse token as a hash-with-options.\n const parsedToken = parseHashWithOptions.exec(token)\n\n // 3. If token does not parse, continue to the next token.\n if (\n parsedToken === null ||\n parsedToken.groups === undefined ||\n parsedToken.groups.algo === undefined\n ) {\n // Note: Chromium blocks the request at this point, but Firefox\n // gives a warning that an invalid integrity was given. The\n // correct behavior is to ignore these, and subsequently not\n // check the integrity of the resource.\n continue\n }\n\n // 4. Let algorithm be the hash-algo component of token.\n const algorithm = parsedToken.groups.algo.toLowerCase()\n\n // 5. If algorithm is a hash function recognized by the user\n // agent, add the parsed token to result.\n if (supportedHashes.includes(algorithm)) {\n result.push(parsedToken.groups)\n }\n }\n\n // 4. Return no metadata if empty is true, otherwise return result.\n if (empty === true) {\n return 'no metadata'\n }\n\n return result\n}\n\n/**\n * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList\n */\nfunction getStrongestMetadata (metadataList) {\n // Let algorithm be the algo component of the first item in metadataList.\n // Can be sha256\n let algorithm = metadataList[0].algo\n // If the algorithm is sha512, then it is the strongest\n // and we can return immediately\n if (algorithm[3] === '5') {\n return algorithm\n }\n\n for (let i = 1; i < metadataList.length; ++i) {\n const metadata = metadataList[i]\n // If the algorithm is sha512, then it is the strongest\n // and we can break the loop immediately\n if (metadata.algo[3] === '5') {\n algorithm = 'sha512'\n break\n // If the algorithm is sha384, then a potential sha256 or sha384 is ignored\n } else if (algorithm[3] === '3') {\n continue\n // algorithm is sha256, check if algorithm is sha384 and if so, set it as\n // the strongest\n } else if (metadata.algo[3] === '3') {\n algorithm = 'sha384'\n }\n }\n return algorithm\n}\n\nfunction filterMetadataListByAlgorithm (metadataList, algorithm) {\n if (metadataList.length === 1) {\n return metadataList\n }\n\n let pos = 0\n for (let i = 0; i < metadataList.length; ++i) {\n if (metadataList[i].algo === algorithm) {\n metadataList[pos++] = metadataList[i]\n }\n }\n\n metadataList.length = pos\n\n return metadataList\n}\n\n/**\n * Compares two base64 strings, allowing for base64url\n * in the second string.\n *\n* @param {string} actualValue always base64\n * @param {string} expectedValue base64 or base64url\n * @returns {boolean}\n */\nfunction compareBase64Mixed (actualValue, expectedValue) {\n if (actualValue.length !== expectedValue.length) {\n return false\n }\n for (let i = 0; i < actualValue.length; ++i) {\n if (actualValue[i] !== expectedValue[i]) {\n if (\n (actualValue[i] === '+' && expectedValue[i] === '-') ||\n (actualValue[i] === '/' && expectedValue[i] === '_')\n ) {\n continue\n }\n return false\n }\n }\n\n return true\n}\n\n// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request\nfunction tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {\n // TODO\n}\n\n/**\n * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}\n * @param {URL} A\n * @param {URL} B\n */\nfunction sameOrigin (A, B) {\n // 1. If A and B are the same opaque origin, then return true.\n if (A.origin === B.origin && A.origin === 'null') {\n return true\n }\n\n // 2. If A and B are both tuple origins and their schemes,\n // hosts, and port are identical, then return true.\n if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {\n return true\n }\n\n // 3. Return false.\n return false\n}\n\nfunction createDeferredPromise () {\n let res\n let rej\n const promise = new Promise((resolve, reject) => {\n res = resolve\n rej = reject\n })\n\n return { promise, resolve: res, reject: rej }\n}\n\nfunction isAborted (fetchParams) {\n return fetchParams.controller.state === 'aborted'\n}\n\nfunction isCancelled (fetchParams) {\n return fetchParams.controller.state === 'aborted' ||\n fetchParams.controller.state === 'terminated'\n}\n\nconst normalizeMethodRecord = {\n delete: 'DELETE',\n DELETE: 'DELETE',\n get: 'GET',\n GET: 'GET',\n head: 'HEAD',\n HEAD: 'HEAD',\n options: 'OPTIONS',\n OPTIONS: 'OPTIONS',\n post: 'POST',\n POST: 'POST',\n put: 'PUT',\n PUT: 'PUT'\n}\n\n// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.\nObject.setPrototypeOf(normalizeMethodRecord, null)\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-method-normalize\n * @param {string} method\n */\nfunction normalizeMethod (method) {\n return normalizeMethodRecord[method.toLowerCase()] ?? method\n}\n\n// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string\nfunction serializeJavascriptValueToJSONString (value) {\n // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).\n const result = JSON.stringify(value)\n\n // 2. If result is undefined, then throw a TypeError.\n if (result === undefined) {\n throw new TypeError('Value is not JSON serializable')\n }\n\n // 3. Assert: result is a string.\n assert(typeof result === 'string')\n\n // 4. Return result.\n return result\n}\n\n// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object\nconst esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))\n\n/**\n * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object\n * @param {() => unknown[]} iterator\n * @param {string} name name of the instance\n * @param {'key'|'value'|'key+value'} kind\n */\nfunction makeIterator (iterator, name, kind) {\n const object = {\n index: 0,\n kind,\n target: iterator\n }\n\n const i = {\n next () {\n // 1. Let interface be the interface for which the iterator prototype object exists.\n\n // 2. Let thisValue be the this value.\n\n // 3. Let object be ? ToObject(thisValue).\n\n // 4. If object is a platform object, then perform a security\n // check, passing:\n\n // 5. If object is not a default iterator object for interface,\n // then throw a TypeError.\n if (Object.getPrototypeOf(this) !== i) {\n throw new TypeError(\n `'next' called on an object that does not implement interface ${name} Iterator.`\n )\n }\n\n // 6. Let index be object’s index.\n // 7. Let kind be object’s kind.\n // 8. Let values be object’s target's value pairs to iterate over.\n const { index, kind, target } = object\n const values = target()\n\n // 9. Let len be the length of values.\n const len = values.length\n\n // 10. If index is greater than or equal to len, then return\n // CreateIterResultObject(undefined, true).\n if (index >= len) {\n return { value: undefined, done: true }\n }\n\n // 11. Let pair be the entry in values at index index.\n const pair = values[index]\n\n // 12. Set object’s index to index + 1.\n object.index = index + 1\n\n // 13. Return the iterator result for pair and kind.\n return iteratorResult(pair, kind)\n },\n // The class string of an iterator prototype object for a given interface is the\n // result of concatenating the identifier of the interface and the string \" Iterator\".\n [Symbol.toStringTag]: `${name} Iterator`\n }\n\n // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.\n Object.setPrototypeOf(i, esIteratorPrototype)\n // esIteratorPrototype needs to be the prototype of i\n // which is the prototype of an empty object. Yes, it's confusing.\n return Object.setPrototypeOf({}, i)\n}\n\n// https://webidl.spec.whatwg.org/#iterator-result\nfunction iteratorResult (pair, kind) {\n let result\n\n // 1. Let result be a value determined by the value of kind:\n switch (kind) {\n case 'key': {\n // 1. Let idlKey be pair’s key.\n // 2. Let key be the result of converting idlKey to an\n // ECMAScript value.\n // 3. result is key.\n result = pair[0]\n break\n }\n case 'value': {\n // 1. Let idlValue be pair’s value.\n // 2. Let value be the result of converting idlValue to\n // an ECMAScript value.\n // 3. result is value.\n result = pair[1]\n break\n }\n case 'key+value': {\n // 1. Let idlKey be pair’s key.\n // 2. Let idlValue be pair’s value.\n // 3. Let key be the result of converting idlKey to an\n // ECMAScript value.\n // 4. Let value be the result of converting idlValue to\n // an ECMAScript value.\n // 5. Let array be ! ArrayCreate(2).\n // 6. Call ! CreateDataProperty(array, \"0\", key).\n // 7. Call ! CreateDataProperty(array, \"1\", value).\n // 8. result is array.\n result = pair\n break\n }\n }\n\n // 2. Return CreateIterResultObject(result, false).\n return { value: result, done: false }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#body-fully-read\n */\nasync function fullyReadBody (body, processBody, processBodyError) {\n // 1. If taskDestination is null, then set taskDestination to\n // the result of starting a new parallel queue.\n\n // 2. Let successSteps given a byte sequence bytes be to queue a\n // fetch task to run processBody given bytes, with taskDestination.\n const successSteps = processBody\n\n // 3. Let errorSteps be to queue a fetch task to run processBodyError,\n // with taskDestination.\n const errorSteps = processBodyError\n\n // 4. Let reader be the result of getting a reader for body’s stream.\n // If that threw an exception, then run errorSteps with that\n // exception and return.\n let reader\n\n try {\n reader = body.stream.getReader()\n } catch (e) {\n errorSteps(e)\n return\n }\n\n // 5. Read all bytes from reader, given successSteps and errorSteps.\n try {\n const result = await readAllBytes(reader)\n successSteps(result)\n } catch (e) {\n errorSteps(e)\n }\n}\n\n/** @type {ReadableStream} */\nlet ReadableStream = globalThis.ReadableStream\n\nfunction isReadableStreamLike (stream) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n return stream instanceof ReadableStream || (\n stream[Symbol.toStringTag] === 'ReadableStream' &&\n typeof stream.tee === 'function'\n )\n}\n\nconst MAXIMUM_ARGUMENT_LENGTH = 65535\n\n/**\n * @see https://infra.spec.whatwg.org/#isomorphic-decode\n * @param {number[]|Uint8Array} input\n */\nfunction isomorphicDecode (input) {\n // 1. To isomorphic decode a byte sequence input, return a string whose code point\n // length is equal to input’s length and whose code points have the same values\n // as the values of input’s bytes, in the same order.\n\n if (input.length < MAXIMUM_ARGUMENT_LENGTH) {\n return String.fromCharCode(...input)\n }\n\n return input.reduce((previous, current) => previous + String.fromCharCode(current), '')\n}\n\n/**\n * @param {ReadableStreamController} controller\n */\nfunction readableStreamClose (controller) {\n try {\n controller.close()\n } catch (err) {\n // TODO: add comment explaining why this error occurs.\n if (!err.message.includes('Controller is already closed')) {\n throw err\n }\n }\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#isomorphic-encode\n * @param {string} input\n */\nfunction isomorphicEncode (input) {\n // 1. Assert: input contains no code points greater than U+00FF.\n for (let i = 0; i < input.length; i++) {\n assert(input.charCodeAt(i) <= 0xFF)\n }\n\n // 2. Return a byte sequence whose length is equal to input’s code\n // point length and whose bytes have the same values as the\n // values of input’s code points, in the same order\n return input\n}\n\n/**\n * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes\n * @see https://streams.spec.whatwg.org/#read-loop\n * @param {ReadableStreamDefaultReader} reader\n */\nasync function readAllBytes (reader) {\n const bytes = []\n let byteLength = 0\n\n while (true) {\n const { done, value: chunk } = await reader.read()\n\n if (done) {\n // 1. Call successSteps with bytes.\n return Buffer.concat(bytes, byteLength)\n }\n\n // 1. If chunk is not a Uint8Array object, call failureSteps\n // with a TypeError and abort these steps.\n if (!isUint8Array(chunk)) {\n throw new TypeError('Received non-Uint8Array chunk')\n }\n\n // 2. Append the bytes represented by chunk to bytes.\n bytes.push(chunk)\n byteLength += chunk.length\n\n // 3. Read-loop given reader, bytes, successSteps, and failureSteps.\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#is-local\n * @param {URL} url\n */\nfunction urlIsLocal (url) {\n assert('protocol' in url) // ensure it's a url object\n\n const protocol = url.protocol\n\n return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'\n}\n\n/**\n * @param {string|URL} url\n */\nfunction urlHasHttpsScheme (url) {\n if (typeof url === 'string') {\n return url.startsWith('https:')\n }\n\n return url.protocol === 'https:'\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-scheme\n * @param {URL} url\n */\nfunction urlIsHttpHttpsScheme (url) {\n assert('protocol' in url) // ensure it's a url object\n\n const protocol = url.protocol\n\n return protocol === 'http:' || protocol === 'https:'\n}\n\n/**\n * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.\n */\nconst hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))\n\nmodule.exports = {\n isAborted,\n isCancelled,\n createDeferredPromise,\n ReadableStreamFrom,\n toUSVString,\n tryUpgradeRequestToAPotentiallyTrustworthyURL,\n coarsenedSharedCurrentTime,\n determineRequestsReferrer,\n makePolicyContainer,\n clonePolicyContainer,\n appendFetchMetadata,\n appendRequestOriginHeader,\n TAOCheck,\n corsCheck,\n crossOriginResourcePolicyCheck,\n createOpaqueTimingInfo,\n setRequestReferrerPolicyOnRedirect,\n isValidHTTPToken,\n requestBadPort,\n requestCurrentURL,\n responseURL,\n responseLocationURL,\n isBlobLike,\n isURLPotentiallyTrustworthy,\n isValidReasonPhrase,\n sameOrigin,\n normalizeMethod,\n serializeJavascriptValueToJSONString,\n makeIterator,\n isValidHeaderName,\n isValidHeaderValue,\n hasOwn,\n isErrorLike,\n fullyReadBody,\n bytesMatch,\n isReadableStreamLike,\n readableStreamClose,\n isomorphicEncode,\n isomorphicDecode,\n urlIsLocal,\n urlHasHttpsScheme,\n urlIsHttpHttpsScheme,\n readAllBytes,\n normalizeMethodRecord,\n parseMetadata\n}\n","'use strict'\n\nconst { types } = require('util')\nconst { hasOwn, toUSVString } = require('./util')\n\n/** @type {import('../../types/webidl').Webidl} */\nconst webidl = {}\nwebidl.converters = {}\nwebidl.util = {}\nwebidl.errors = {}\n\nwebidl.errors.exception = function (message) {\n return new TypeError(`${message.header}: ${message.message}`)\n}\n\nwebidl.errors.conversionFailed = function (context) {\n const plural = context.types.length === 1 ? '' : ' one of'\n const message =\n `${context.argument} could not be converted to` +\n `${plural}: ${context.types.join(', ')}.`\n\n return webidl.errors.exception({\n header: context.prefix,\n message\n })\n}\n\nwebidl.errors.invalidArgument = function (context) {\n return webidl.errors.exception({\n header: context.prefix,\n message: `\"${context.value}\" is an invalid ${context.type}.`\n })\n}\n\n// https://webidl.spec.whatwg.org/#implements\nwebidl.brandCheck = function (V, I, opts = undefined) {\n if (opts?.strict !== false && !(V instanceof I)) {\n throw new TypeError('Illegal invocation')\n } else {\n return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]\n }\n}\n\nwebidl.argumentLengthCheck = function ({ length }, min, ctx) {\n if (length < min) {\n throw webidl.errors.exception({\n message: `${min} argument${min !== 1 ? 's' : ''} required, ` +\n `but${length ? ' only' : ''} ${length} found.`,\n ...ctx\n })\n }\n}\n\nwebidl.illegalConstructor = function () {\n throw webidl.errors.exception({\n header: 'TypeError',\n message: 'Illegal constructor'\n })\n}\n\n// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values\nwebidl.util.Type = function (V) {\n switch (typeof V) {\n case 'undefined': return 'Undefined'\n case 'boolean': return 'Boolean'\n case 'string': return 'String'\n case 'symbol': return 'Symbol'\n case 'number': return 'Number'\n case 'bigint': return 'BigInt'\n case 'function':\n case 'object': {\n if (V === null) {\n return 'Null'\n }\n\n return 'Object'\n }\n }\n}\n\n// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint\nwebidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {\n let upperBound\n let lowerBound\n\n // 1. If bitLength is 64, then:\n if (bitLength === 64) {\n // 1. Let upperBound be 2^53 − 1.\n upperBound = Math.pow(2, 53) - 1\n\n // 2. If signedness is \"unsigned\", then let lowerBound be 0.\n if (signedness === 'unsigned') {\n lowerBound = 0\n } else {\n // 3. Otherwise let lowerBound be −2^53 + 1.\n lowerBound = Math.pow(-2, 53) + 1\n }\n } else if (signedness === 'unsigned') {\n // 2. Otherwise, if signedness is \"unsigned\", then:\n\n // 1. Let lowerBound be 0.\n lowerBound = 0\n\n // 2. Let upperBound be 2^bitLength − 1.\n upperBound = Math.pow(2, bitLength) - 1\n } else {\n // 3. Otherwise:\n\n // 1. Let lowerBound be -2^bitLength − 1.\n lowerBound = Math.pow(-2, bitLength) - 1\n\n // 2. Let upperBound be 2^bitLength − 1 − 1.\n upperBound = Math.pow(2, bitLength - 1) - 1\n }\n\n // 4. Let x be ? ToNumber(V).\n let x = Number(V)\n\n // 5. If x is −0, then set x to +0.\n if (x === 0) {\n x = 0\n }\n\n // 6. If the conversion is to an IDL type associated\n // with the [EnforceRange] extended attribute, then:\n if (opts.enforceRange === true) {\n // 1. If x is NaN, +∞, or −∞, then throw a TypeError.\n if (\n Number.isNaN(x) ||\n x === Number.POSITIVE_INFINITY ||\n x === Number.NEGATIVE_INFINITY\n ) {\n throw webidl.errors.exception({\n header: 'Integer conversion',\n message: `Could not convert ${V} to an integer.`\n })\n }\n\n // 2. Set x to IntegerPart(x).\n x = webidl.util.IntegerPart(x)\n\n // 3. If x < lowerBound or x > upperBound, then\n // throw a TypeError.\n if (x < lowerBound || x > upperBound) {\n throw webidl.errors.exception({\n header: 'Integer conversion',\n message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`\n })\n }\n\n // 4. Return x.\n return x\n }\n\n // 7. If x is not NaN and the conversion is to an IDL\n // type associated with the [Clamp] extended\n // attribute, then:\n if (!Number.isNaN(x) && opts.clamp === true) {\n // 1. Set x to min(max(x, lowerBound), upperBound).\n x = Math.min(Math.max(x, lowerBound), upperBound)\n\n // 2. Round x to the nearest integer, choosing the\n // even integer if it lies halfway between two,\n // and choosing +0 rather than −0.\n if (Math.floor(x) % 2 === 0) {\n x = Math.floor(x)\n } else {\n x = Math.ceil(x)\n }\n\n // 3. Return x.\n return x\n }\n\n // 8. If x is NaN, +0, +∞, or −∞, then return +0.\n if (\n Number.isNaN(x) ||\n (x === 0 && Object.is(0, x)) ||\n x === Number.POSITIVE_INFINITY ||\n x === Number.NEGATIVE_INFINITY\n ) {\n return 0\n }\n\n // 9. Set x to IntegerPart(x).\n x = webidl.util.IntegerPart(x)\n\n // 10. Set x to x modulo 2^bitLength.\n x = x % Math.pow(2, bitLength)\n\n // 11. If signedness is \"signed\" and x ≥ 2^bitLength − 1,\n // then return x − 2^bitLength.\n if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {\n return x - Math.pow(2, bitLength)\n }\n\n // 12. Otherwise, return x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart\nwebidl.util.IntegerPart = function (n) {\n // 1. Let r be floor(abs(n)).\n const r = Math.floor(Math.abs(n))\n\n // 2. If n < 0, then return -1 × r.\n if (n < 0) {\n return -1 * r\n }\n\n // 3. Otherwise, return r.\n return r\n}\n\n// https://webidl.spec.whatwg.org/#es-sequence\nwebidl.sequenceConverter = function (converter) {\n return (V) => {\n // 1. If Type(V) is not Object, throw a TypeError.\n if (webidl.util.Type(V) !== 'Object') {\n throw webidl.errors.exception({\n header: 'Sequence',\n message: `Value of type ${webidl.util.Type(V)} is not an Object.`\n })\n }\n\n // 2. Let method be ? GetMethod(V, @@iterator).\n /** @type {Generator} */\n const method = V?.[Symbol.iterator]?.()\n const seq = []\n\n // 3. If method is undefined, throw a TypeError.\n if (\n method === undefined ||\n typeof method.next !== 'function'\n ) {\n throw webidl.errors.exception({\n header: 'Sequence',\n message: 'Object is not an iterator.'\n })\n }\n\n // https://webidl.spec.whatwg.org/#create-sequence-from-iterable\n while (true) {\n const { done, value } = method.next()\n\n if (done) {\n break\n }\n\n seq.push(converter(value))\n }\n\n return seq\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-to-record\nwebidl.recordConverter = function (keyConverter, valueConverter) {\n return (O) => {\n // 1. If Type(O) is not Object, throw a TypeError.\n if (webidl.util.Type(O) !== 'Object') {\n throw webidl.errors.exception({\n header: 'Record',\n message: `Value of type ${webidl.util.Type(O)} is not an Object.`\n })\n }\n\n // 2. Let result be a new empty instance of record.\n const result = {}\n\n if (!types.isProxy(O)) {\n // Object.keys only returns enumerable properties\n const keys = Object.keys(O)\n\n for (const key of keys) {\n // 1. Let typedKey be key converted to an IDL value of type K.\n const typedKey = keyConverter(key)\n\n // 2. Let value be ? Get(O, key).\n // 3. Let typedValue be value converted to an IDL value of type V.\n const typedValue = valueConverter(O[key])\n\n // 4. Set result[typedKey] to typedValue.\n result[typedKey] = typedValue\n }\n\n // 5. Return result.\n return result\n }\n\n // 3. Let keys be ? O.[[OwnPropertyKeys]]().\n const keys = Reflect.ownKeys(O)\n\n // 4. For each key of keys.\n for (const key of keys) {\n // 1. Let desc be ? O.[[GetOwnProperty]](key).\n const desc = Reflect.getOwnPropertyDescriptor(O, key)\n\n // 2. If desc is not undefined and desc.[[Enumerable]] is true:\n if (desc?.enumerable) {\n // 1. Let typedKey be key converted to an IDL value of type K.\n const typedKey = keyConverter(key)\n\n // 2. Let value be ? Get(O, key).\n // 3. Let typedValue be value converted to an IDL value of type V.\n const typedValue = valueConverter(O[key])\n\n // 4. Set result[typedKey] to typedValue.\n result[typedKey] = typedValue\n }\n }\n\n // 5. Return result.\n return result\n }\n}\n\nwebidl.interfaceConverter = function (i) {\n return (V, opts = {}) => {\n if (opts.strict !== false && !(V instanceof i)) {\n throw webidl.errors.exception({\n header: i.name,\n message: `Expected ${V} to be an instance of ${i.name}.`\n })\n }\n\n return V\n }\n}\n\nwebidl.dictionaryConverter = function (converters) {\n return (dictionary) => {\n const type = webidl.util.Type(dictionary)\n const dict = {}\n\n if (type === 'Null' || type === 'Undefined') {\n return dict\n } else if (type !== 'Object') {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`\n })\n }\n\n for (const options of converters) {\n const { key, defaultValue, required, converter } = options\n\n if (required === true) {\n if (!hasOwn(dictionary, key)) {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `Missing required key \"${key}\".`\n })\n }\n }\n\n let value = dictionary[key]\n const hasDefault = hasOwn(options, 'defaultValue')\n\n // Only use defaultValue if value is undefined and\n // a defaultValue options was provided.\n if (hasDefault && value !== null) {\n value = value ?? defaultValue\n }\n\n // A key can be optional and have no default value.\n // When this happens, do not perform a conversion,\n // and do not assign the key a value.\n if (required || hasDefault || value !== undefined) {\n value = converter(value)\n\n if (\n options.allowedValues &&\n !options.allowedValues.includes(value)\n ) {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`\n })\n }\n\n dict[key] = value\n }\n }\n\n return dict\n }\n}\n\nwebidl.nullableConverter = function (converter) {\n return (V) => {\n if (V === null) {\n return V\n }\n\n return converter(V)\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-DOMString\nwebidl.converters.DOMString = function (V, opts = {}) {\n // 1. If V is null and the conversion is to an IDL type\n // associated with the [LegacyNullToEmptyString]\n // extended attribute, then return the DOMString value\n // that represents the empty string.\n if (V === null && opts.legacyNullToEmptyString) {\n return ''\n }\n\n // 2. Let x be ? ToString(V).\n if (typeof V === 'symbol') {\n throw new TypeError('Could not convert argument of type symbol to string.')\n }\n\n // 3. Return the IDL DOMString value that represents the\n // same sequence of code units as the one the\n // ECMAScript String value x represents.\n return String(V)\n}\n\n// https://webidl.spec.whatwg.org/#es-ByteString\nwebidl.converters.ByteString = function (V) {\n // 1. Let x be ? ToString(V).\n // Note: DOMString converter perform ? ToString(V)\n const x = webidl.converters.DOMString(V)\n\n // 2. If the value of any element of x is greater than\n // 255, then throw a TypeError.\n for (let index = 0; index < x.length; index++) {\n if (x.charCodeAt(index) > 255) {\n throw new TypeError(\n 'Cannot convert argument to a ByteString because the character at ' +\n `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`\n )\n }\n }\n\n // 3. Return an IDL ByteString value whose length is the\n // length of x, and where the value of each element is\n // the value of the corresponding element of x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-USVString\nwebidl.converters.USVString = toUSVString\n\n// https://webidl.spec.whatwg.org/#es-boolean\nwebidl.converters.boolean = function (V) {\n // 1. Let x be the result of computing ToBoolean(V).\n const x = Boolean(V)\n\n // 2. Return the IDL boolean value that is the one that represents\n // the same truth value as the ECMAScript Boolean value x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-any\nwebidl.converters.any = function (V) {\n return V\n}\n\n// https://webidl.spec.whatwg.org/#es-long-long\nwebidl.converters['long long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 64, \"signed\").\n const x = webidl.util.ConvertToInt(V, 64, 'signed')\n\n // 2. Return the IDL long long value that represents\n // the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-long-long\nwebidl.converters['unsigned long long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 64, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 64, 'unsigned')\n\n // 2. Return the IDL unsigned long long value that\n // represents the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-long\nwebidl.converters['unsigned long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 32, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 32, 'unsigned')\n\n // 2. Return the IDL unsigned long value that\n // represents the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-short\nwebidl.converters['unsigned short'] = function (V, opts) {\n // 1. Let x be ? ConvertToInt(V, 16, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)\n\n // 2. Return the IDL unsigned short value that represents\n // the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#idl-ArrayBuffer\nwebidl.converters.ArrayBuffer = function (V, opts = {}) {\n // 1. If Type(V) is not Object, or V does not have an\n // [[ArrayBufferData]] internal slot, then throw a\n // TypeError.\n // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances\n // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances\n if (\n webidl.util.Type(V) !== 'Object' ||\n !types.isAnyArrayBuffer(V)\n ) {\n throw webidl.errors.conversionFailed({\n prefix: `${V}`,\n argument: `${V}`,\n types: ['ArrayBuffer']\n })\n }\n\n // 2. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V) is true, then throw a\n // TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V) is true, then throw a\n // TypeError.\n // Note: resizable ArrayBuffers are currently a proposal.\n\n // 4. Return the IDL ArrayBuffer value that is a\n // reference to the same object as V.\n return V\n}\n\nwebidl.converters.TypedArray = function (V, T, opts = {}) {\n // 1. Let T be the IDL type V is being converted to.\n\n // 2. If Type(V) is not Object, or V does not have a\n // [[TypedArrayName]] internal slot with a value\n // equal to T’s name, then throw a TypeError.\n if (\n webidl.util.Type(V) !== 'Object' ||\n !types.isTypedArray(V) ||\n V.constructor.name !== T.name\n ) {\n throw webidl.errors.conversionFailed({\n prefix: `${T.name}`,\n argument: `${V}`,\n types: [T.name]\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 4. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n // Note: resizable array buffers are currently a proposal\n\n // 5. Return the IDL value of type T that is a reference\n // to the same object as V.\n return V\n}\n\nwebidl.converters.DataView = function (V, opts = {}) {\n // 1. If Type(V) is not Object, or V does not have a\n // [[DataView]] internal slot, then throw a TypeError.\n if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {\n throw webidl.errors.exception({\n header: 'DataView',\n message: 'Object is not a DataView.'\n })\n }\n\n // 2. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,\n // then throw a TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n // Note: resizable ArrayBuffers are currently a proposal\n\n // 4. Return the IDL DataView value that is a reference\n // to the same object as V.\n return V\n}\n\n// https://webidl.spec.whatwg.org/#BufferSource\nwebidl.converters.BufferSource = function (V, opts = {}) {\n if (types.isAnyArrayBuffer(V)) {\n return webidl.converters.ArrayBuffer(V, opts)\n }\n\n if (types.isTypedArray(V)) {\n return webidl.converters.TypedArray(V, V.constructor)\n }\n\n if (types.isDataView(V)) {\n return webidl.converters.DataView(V, opts)\n }\n\n throw new TypeError(`Could not convert ${V} to a BufferSource.`)\n}\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.ByteString\n)\n\nwebidl.converters['sequence>'] = webidl.sequenceConverter(\n webidl.converters['sequence']\n)\n\nwebidl.converters['record'] = webidl.recordConverter(\n webidl.converters.ByteString,\n webidl.converters.ByteString\n)\n\nmodule.exports = {\n webidl\n}\n","'use strict'\n\n/**\n * @see https://encoding.spec.whatwg.org/#concept-encoding-get\n * @param {string|undefined} label\n */\nfunction getEncoding (label) {\n if (!label) {\n return 'failure'\n }\n\n // 1. Remove any leading and trailing ASCII whitespace from label.\n // 2. If label is an ASCII case-insensitive match for any of the\n // labels listed in the table below, then return the\n // corresponding encoding; otherwise return failure.\n switch (label.trim().toLowerCase()) {\n case 'unicode-1-1-utf-8':\n case 'unicode11utf8':\n case 'unicode20utf8':\n case 'utf-8':\n case 'utf8':\n case 'x-unicode20utf8':\n return 'UTF-8'\n case '866':\n case 'cp866':\n case 'csibm866':\n case 'ibm866':\n return 'IBM866'\n case 'csisolatin2':\n case 'iso-8859-2':\n case 'iso-ir-101':\n case 'iso8859-2':\n case 'iso88592':\n case 'iso_8859-2':\n case 'iso_8859-2:1987':\n case 'l2':\n case 'latin2':\n return 'ISO-8859-2'\n case 'csisolatin3':\n case 'iso-8859-3':\n case 'iso-ir-109':\n case 'iso8859-3':\n case 'iso88593':\n case 'iso_8859-3':\n case 'iso_8859-3:1988':\n case 'l3':\n case 'latin3':\n return 'ISO-8859-3'\n case 'csisolatin4':\n case 'iso-8859-4':\n case 'iso-ir-110':\n case 'iso8859-4':\n case 'iso88594':\n case 'iso_8859-4':\n case 'iso_8859-4:1988':\n case 'l4':\n case 'latin4':\n return 'ISO-8859-4'\n case 'csisolatincyrillic':\n case 'cyrillic':\n case 'iso-8859-5':\n case 'iso-ir-144':\n case 'iso8859-5':\n case 'iso88595':\n case 'iso_8859-5':\n case 'iso_8859-5:1988':\n return 'ISO-8859-5'\n case 'arabic':\n case 'asmo-708':\n case 'csiso88596e':\n case 'csiso88596i':\n case 'csisolatinarabic':\n case 'ecma-114':\n case 'iso-8859-6':\n case 'iso-8859-6-e':\n case 'iso-8859-6-i':\n case 'iso-ir-127':\n case 'iso8859-6':\n case 'iso88596':\n case 'iso_8859-6':\n case 'iso_8859-6:1987':\n return 'ISO-8859-6'\n case 'csisolatingreek':\n case 'ecma-118':\n case 'elot_928':\n case 'greek':\n case 'greek8':\n case 'iso-8859-7':\n case 'iso-ir-126':\n case 'iso8859-7':\n case 'iso88597':\n case 'iso_8859-7':\n case 'iso_8859-7:1987':\n case 'sun_eu_greek':\n return 'ISO-8859-7'\n case 'csiso88598e':\n case 'csisolatinhebrew':\n case 'hebrew':\n case 'iso-8859-8':\n case 'iso-8859-8-e':\n case 'iso-ir-138':\n case 'iso8859-8':\n case 'iso88598':\n case 'iso_8859-8':\n case 'iso_8859-8:1988':\n case 'visual':\n return 'ISO-8859-8'\n case 'csiso88598i':\n case 'iso-8859-8-i':\n case 'logical':\n return 'ISO-8859-8-I'\n case 'csisolatin6':\n case 'iso-8859-10':\n case 'iso-ir-157':\n case 'iso8859-10':\n case 'iso885910':\n case 'l6':\n case 'latin6':\n return 'ISO-8859-10'\n case 'iso-8859-13':\n case 'iso8859-13':\n case 'iso885913':\n return 'ISO-8859-13'\n case 'iso-8859-14':\n case 'iso8859-14':\n case 'iso885914':\n return 'ISO-8859-14'\n case 'csisolatin9':\n case 'iso-8859-15':\n case 'iso8859-15':\n case 'iso885915':\n case 'iso_8859-15':\n case 'l9':\n return 'ISO-8859-15'\n case 'iso-8859-16':\n return 'ISO-8859-16'\n case 'cskoi8r':\n case 'koi':\n case 'koi8':\n case 'koi8-r':\n case 'koi8_r':\n return 'KOI8-R'\n case 'koi8-ru':\n case 'koi8-u':\n return 'KOI8-U'\n case 'csmacintosh':\n case 'mac':\n case 'macintosh':\n case 'x-mac-roman':\n return 'macintosh'\n case 'iso-8859-11':\n case 'iso8859-11':\n case 'iso885911':\n case 'tis-620':\n case 'windows-874':\n return 'windows-874'\n case 'cp1250':\n case 'windows-1250':\n case 'x-cp1250':\n return 'windows-1250'\n case 'cp1251':\n case 'windows-1251':\n case 'x-cp1251':\n return 'windows-1251'\n case 'ansi_x3.4-1968':\n case 'ascii':\n case 'cp1252':\n case 'cp819':\n case 'csisolatin1':\n case 'ibm819':\n case 'iso-8859-1':\n case 'iso-ir-100':\n case 'iso8859-1':\n case 'iso88591':\n case 'iso_8859-1':\n case 'iso_8859-1:1987':\n case 'l1':\n case 'latin1':\n case 'us-ascii':\n case 'windows-1252':\n case 'x-cp1252':\n return 'windows-1252'\n case 'cp1253':\n case 'windows-1253':\n case 'x-cp1253':\n return 'windows-1253'\n case 'cp1254':\n case 'csisolatin5':\n case 'iso-8859-9':\n case 'iso-ir-148':\n case 'iso8859-9':\n case 'iso88599':\n case 'iso_8859-9':\n case 'iso_8859-9:1989':\n case 'l5':\n case 'latin5':\n case 'windows-1254':\n case 'x-cp1254':\n return 'windows-1254'\n case 'cp1255':\n case 'windows-1255':\n case 'x-cp1255':\n return 'windows-1255'\n case 'cp1256':\n case 'windows-1256':\n case 'x-cp1256':\n return 'windows-1256'\n case 'cp1257':\n case 'windows-1257':\n case 'x-cp1257':\n return 'windows-1257'\n case 'cp1258':\n case 'windows-1258':\n case 'x-cp1258':\n return 'windows-1258'\n case 'x-mac-cyrillic':\n case 'x-mac-ukrainian':\n return 'x-mac-cyrillic'\n case 'chinese':\n case 'csgb2312':\n case 'csiso58gb231280':\n case 'gb2312':\n case 'gb_2312':\n case 'gb_2312-80':\n case 'gbk':\n case 'iso-ir-58':\n case 'x-gbk':\n return 'GBK'\n case 'gb18030':\n return 'gb18030'\n case 'big5':\n case 'big5-hkscs':\n case 'cn-big5':\n case 'csbig5':\n case 'x-x-big5':\n return 'Big5'\n case 'cseucpkdfmtjapanese':\n case 'euc-jp':\n case 'x-euc-jp':\n return 'EUC-JP'\n case 'csiso2022jp':\n case 'iso-2022-jp':\n return 'ISO-2022-JP'\n case 'csshiftjis':\n case 'ms932':\n case 'ms_kanji':\n case 'shift-jis':\n case 'shift_jis':\n case 'sjis':\n case 'windows-31j':\n case 'x-sjis':\n return 'Shift_JIS'\n case 'cseuckr':\n case 'csksc56011987':\n case 'euc-kr':\n case 'iso-ir-149':\n case 'korean':\n case 'ks_c_5601-1987':\n case 'ks_c_5601-1989':\n case 'ksc5601':\n case 'ksc_5601':\n case 'windows-949':\n return 'EUC-KR'\n case 'csiso2022kr':\n case 'hz-gb-2312':\n case 'iso-2022-cn':\n case 'iso-2022-cn-ext':\n case 'iso-2022-kr':\n case 'replacement':\n return 'replacement'\n case 'unicodefffe':\n case 'utf-16be':\n return 'UTF-16BE'\n case 'csunicode':\n case 'iso-10646-ucs-2':\n case 'ucs-2':\n case 'unicode':\n case 'unicodefeff':\n case 'utf-16':\n case 'utf-16le':\n return 'UTF-16LE'\n case 'x-user-defined':\n return 'x-user-defined'\n default: return 'failure'\n }\n}\n\nmodule.exports = {\n getEncoding\n}\n","'use strict'\n\nconst {\n staticPropertyDescriptors,\n readOperation,\n fireAProgressEvent\n} = require('./util')\nconst {\n kState,\n kError,\n kResult,\n kEvents,\n kAborted\n} = require('./symbols')\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\n\nclass FileReader extends EventTarget {\n constructor () {\n super()\n\n this[kState] = 'empty'\n this[kResult] = null\n this[kError] = null\n this[kEvents] = {\n loadend: null,\n error: null,\n abort: null,\n load: null,\n progress: null,\n loadstart: null\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer\n * @param {import('buffer').Blob} blob\n */\n readAsArrayBuffer (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsArrayBuffer(blob) method, when invoked,\n // must initiate a read operation for blob with ArrayBuffer.\n readOperation(this, blob, 'ArrayBuffer')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#readAsBinaryString\n * @param {import('buffer').Blob} blob\n */\n readAsBinaryString (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsBinaryString(blob) method, when invoked,\n // must initiate a read operation for blob with BinaryString.\n readOperation(this, blob, 'BinaryString')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#readAsDataText\n * @param {import('buffer').Blob} blob\n * @param {string?} encoding\n */\n readAsText (blob, encoding = undefined) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n if (encoding !== undefined) {\n encoding = webidl.converters.DOMString(encoding)\n }\n\n // The readAsText(blob, encoding) method, when invoked,\n // must initiate a read operation for blob with Text and encoding.\n readOperation(this, blob, 'Text', encoding)\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL\n * @param {import('buffer').Blob} blob\n */\n readAsDataURL (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsDataURL(blob) method, when invoked, must\n // initiate a read operation for blob with DataURL.\n readOperation(this, blob, 'DataURL')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-abort\n */\n abort () {\n // 1. If this's state is \"empty\" or if this's state is\n // \"done\" set this's result to null and terminate\n // this algorithm.\n if (this[kState] === 'empty' || this[kState] === 'done') {\n this[kResult] = null\n return\n }\n\n // 2. If this's state is \"loading\" set this's state to\n // \"done\" and set this's result to null.\n if (this[kState] === 'loading') {\n this[kState] = 'done'\n this[kResult] = null\n }\n\n // 3. If there are any tasks from this on the file reading\n // task source in an affiliated task queue, then remove\n // those tasks from that task queue.\n this[kAborted] = true\n\n // 4. Terminate the algorithm for the read method being processed.\n // TODO\n\n // 5. Fire a progress event called abort at this.\n fireAProgressEvent('abort', this)\n\n // 6. If this's state is not \"loading\", fire a progress\n // event called loadend at this.\n if (this[kState] !== 'loading') {\n fireAProgressEvent('loadend', this)\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate\n */\n get readyState () {\n webidl.brandCheck(this, FileReader)\n\n switch (this[kState]) {\n case 'empty': return this.EMPTY\n case 'loading': return this.LOADING\n case 'done': return this.DONE\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-result\n */\n get result () {\n webidl.brandCheck(this, FileReader)\n\n // The result attribute’s getter, when invoked, must return\n // this's result.\n return this[kResult]\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-error\n */\n get error () {\n webidl.brandCheck(this, FileReader)\n\n // The error attribute’s getter, when invoked, must return\n // this's error.\n return this[kError]\n }\n\n get onloadend () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].loadend\n }\n\n set onloadend (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].loadend) {\n this.removeEventListener('loadend', this[kEvents].loadend)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].loadend = fn\n this.addEventListener('loadend', fn)\n } else {\n this[kEvents].loadend = null\n }\n }\n\n get onerror () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].error\n }\n\n set onerror (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].error) {\n this.removeEventListener('error', this[kEvents].error)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].error = fn\n this.addEventListener('error', fn)\n } else {\n this[kEvents].error = null\n }\n }\n\n get onloadstart () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].loadstart\n }\n\n set onloadstart (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].loadstart) {\n this.removeEventListener('loadstart', this[kEvents].loadstart)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].loadstart = fn\n this.addEventListener('loadstart', fn)\n } else {\n this[kEvents].loadstart = null\n }\n }\n\n get onprogress () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].progress\n }\n\n set onprogress (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].progress) {\n this.removeEventListener('progress', this[kEvents].progress)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].progress = fn\n this.addEventListener('progress', fn)\n } else {\n this[kEvents].progress = null\n }\n }\n\n get onload () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].load\n }\n\n set onload (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].load) {\n this.removeEventListener('load', this[kEvents].load)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].load = fn\n this.addEventListener('load', fn)\n } else {\n this[kEvents].load = null\n }\n }\n\n get onabort () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].abort\n }\n\n set onabort (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].abort) {\n this.removeEventListener('abort', this[kEvents].abort)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].abort = fn\n this.addEventListener('abort', fn)\n } else {\n this[kEvents].abort = null\n }\n }\n}\n\n// https://w3c.github.io/FileAPI/#dom-filereader-empty\nFileReader.EMPTY = FileReader.prototype.EMPTY = 0\n// https://w3c.github.io/FileAPI/#dom-filereader-loading\nFileReader.LOADING = FileReader.prototype.LOADING = 1\n// https://w3c.github.io/FileAPI/#dom-filereader-done\nFileReader.DONE = FileReader.prototype.DONE = 2\n\nObject.defineProperties(FileReader.prototype, {\n EMPTY: staticPropertyDescriptors,\n LOADING: staticPropertyDescriptors,\n DONE: staticPropertyDescriptors,\n readAsArrayBuffer: kEnumerableProperty,\n readAsBinaryString: kEnumerableProperty,\n readAsText: kEnumerableProperty,\n readAsDataURL: kEnumerableProperty,\n abort: kEnumerableProperty,\n readyState: kEnumerableProperty,\n result: kEnumerableProperty,\n error: kEnumerableProperty,\n onloadstart: kEnumerableProperty,\n onprogress: kEnumerableProperty,\n onload: kEnumerableProperty,\n onabort: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onloadend: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'FileReader',\n writable: false,\n enumerable: false,\n configurable: true\n }\n})\n\nObject.defineProperties(FileReader, {\n EMPTY: staticPropertyDescriptors,\n LOADING: staticPropertyDescriptors,\n DONE: staticPropertyDescriptors\n})\n\nmodule.exports = {\n FileReader\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\n\nconst kState = Symbol('ProgressEvent state')\n\n/**\n * @see https://xhr.spec.whatwg.org/#progressevent\n */\nclass ProgressEvent extends Event {\n constructor (type, eventInitDict = {}) {\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})\n\n super(type, eventInitDict)\n\n this[kState] = {\n lengthComputable: eventInitDict.lengthComputable,\n loaded: eventInitDict.loaded,\n total: eventInitDict.total\n }\n }\n\n get lengthComputable () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].lengthComputable\n }\n\n get loaded () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].loaded\n }\n\n get total () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].total\n }\n}\n\nwebidl.converters.ProgressEventInit = webidl.dictionaryConverter([\n {\n key: 'lengthComputable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'loaded',\n converter: webidl.converters['unsigned long long'],\n defaultValue: 0\n },\n {\n key: 'total',\n converter: webidl.converters['unsigned long long'],\n defaultValue: 0\n },\n {\n key: 'bubbles',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'cancelable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'composed',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n])\n\nmodule.exports = {\n ProgressEvent\n}\n","'use strict'\n\nmodule.exports = {\n kState: Symbol('FileReader state'),\n kResult: Symbol('FileReader result'),\n kError: Symbol('FileReader error'),\n kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),\n kEvents: Symbol('FileReader events'),\n kAborted: Symbol('FileReader aborted')\n}\n","'use strict'\n\nconst {\n kState,\n kError,\n kResult,\n kAborted,\n kLastProgressEventFired\n} = require('./symbols')\nconst { ProgressEvent } = require('./progressevent')\nconst { getEncoding } = require('./encoding')\nconst { DOMException } = require('../fetch/constants')\nconst { serializeAMimeType, parseMIMEType } = require('../fetch/dataURL')\nconst { types } = require('util')\nconst { StringDecoder } = require('string_decoder')\nconst { btoa } = require('buffer')\n\n/** @type {PropertyDescriptor} */\nconst staticPropertyDescriptors = {\n enumerable: true,\n writable: false,\n configurable: false\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#readOperation\n * @param {import('./filereader').FileReader} fr\n * @param {import('buffer').Blob} blob\n * @param {string} type\n * @param {string?} encodingName\n */\nfunction readOperation (fr, blob, type, encodingName) {\n // 1. If fr’s state is \"loading\", throw an InvalidStateError\n // DOMException.\n if (fr[kState] === 'loading') {\n throw new DOMException('Invalid state', 'InvalidStateError')\n }\n\n // 2. Set fr’s state to \"loading\".\n fr[kState] = 'loading'\n\n // 3. Set fr’s result to null.\n fr[kResult] = null\n\n // 4. Set fr’s error to null.\n fr[kError] = null\n\n // 5. Let stream be the result of calling get stream on blob.\n /** @type {import('stream/web').ReadableStream} */\n const stream = blob.stream()\n\n // 6. Let reader be the result of getting a reader from stream.\n const reader = stream.getReader()\n\n // 7. Let bytes be an empty byte sequence.\n /** @type {Uint8Array[]} */\n const bytes = []\n\n // 8. Let chunkPromise be the result of reading a chunk from\n // stream with reader.\n let chunkPromise = reader.read()\n\n // 9. Let isFirstChunk be true.\n let isFirstChunk = true\n\n // 10. In parallel, while true:\n // Note: \"In parallel\" just means non-blocking\n // Note 2: readOperation itself cannot be async as double\n // reading the body would then reject the promise, instead\n // of throwing an error.\n ;(async () => {\n while (!fr[kAborted]) {\n // 1. Wait for chunkPromise to be fulfilled or rejected.\n try {\n const { done, value } = await chunkPromise\n\n // 2. If chunkPromise is fulfilled, and isFirstChunk is\n // true, queue a task to fire a progress event called\n // loadstart at fr.\n if (isFirstChunk && !fr[kAborted]) {\n queueMicrotask(() => {\n fireAProgressEvent('loadstart', fr)\n })\n }\n\n // 3. Set isFirstChunk to false.\n isFirstChunk = false\n\n // 4. If chunkPromise is fulfilled with an object whose\n // done property is false and whose value property is\n // a Uint8Array object, run these steps:\n if (!done && types.isUint8Array(value)) {\n // 1. Let bs be the byte sequence represented by the\n // Uint8Array object.\n\n // 2. Append bs to bytes.\n bytes.push(value)\n\n // 3. If roughly 50ms have passed since these steps\n // were last invoked, queue a task to fire a\n // progress event called progress at fr.\n if (\n (\n fr[kLastProgressEventFired] === undefined ||\n Date.now() - fr[kLastProgressEventFired] >= 50\n ) &&\n !fr[kAborted]\n ) {\n fr[kLastProgressEventFired] = Date.now()\n queueMicrotask(() => {\n fireAProgressEvent('progress', fr)\n })\n }\n\n // 4. Set chunkPromise to the result of reading a\n // chunk from stream with reader.\n chunkPromise = reader.read()\n } else if (done) {\n // 5. Otherwise, if chunkPromise is fulfilled with an\n // object whose done property is true, queue a task\n // to run the following steps and abort this algorithm:\n queueMicrotask(() => {\n // 1. Set fr’s state to \"done\".\n fr[kState] = 'done'\n\n // 2. Let result be the result of package data given\n // bytes, type, blob’s type, and encodingName.\n try {\n const result = packageData(bytes, type, blob.type, encodingName)\n\n // 4. Else:\n\n if (fr[kAborted]) {\n return\n }\n\n // 1. Set fr’s result to result.\n fr[kResult] = result\n\n // 2. Fire a progress event called load at the fr.\n fireAProgressEvent('load', fr)\n } catch (error) {\n // 3. If package data threw an exception error:\n\n // 1. Set fr’s error to error.\n fr[kError] = error\n\n // 2. Fire a progress event called error at fr.\n fireAProgressEvent('error', fr)\n }\n\n // 5. If fr’s state is not \"loading\", fire a progress\n // event called loadend at the fr.\n if (fr[kState] !== 'loading') {\n fireAProgressEvent('loadend', fr)\n }\n })\n\n break\n }\n } catch (error) {\n if (fr[kAborted]) {\n return\n }\n\n // 6. Otherwise, if chunkPromise is rejected with an\n // error error, queue a task to run the following\n // steps and abort this algorithm:\n queueMicrotask(() => {\n // 1. Set fr’s state to \"done\".\n fr[kState] = 'done'\n\n // 2. Set fr’s error to error.\n fr[kError] = error\n\n // 3. Fire a progress event called error at fr.\n fireAProgressEvent('error', fr)\n\n // 4. If fr’s state is not \"loading\", fire a progress\n // event called loadend at fr.\n if (fr[kState] !== 'loading') {\n fireAProgressEvent('loadend', fr)\n }\n })\n\n break\n }\n }\n })()\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#fire-a-progress-event\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e The name of the event\n * @param {import('./filereader').FileReader} reader\n */\nfunction fireAProgressEvent (e, reader) {\n // The progress event e does not bubble. e.bubbles must be false\n // The progress event e is NOT cancelable. e.cancelable must be false\n const event = new ProgressEvent(e, {\n bubbles: false,\n cancelable: false\n })\n\n reader.dispatchEvent(event)\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#blob-package-data\n * @param {Uint8Array[]} bytes\n * @param {string} type\n * @param {string?} mimeType\n * @param {string?} encodingName\n */\nfunction packageData (bytes, type, mimeType, encodingName) {\n // 1. A Blob has an associated package data algorithm, given\n // bytes, a type, a optional mimeType, and a optional\n // encodingName, which switches on type and runs the\n // associated steps:\n\n switch (type) {\n case 'DataURL': {\n // 1. Return bytes as a DataURL [RFC2397] subject to\n // the considerations below:\n // * Use mimeType as part of the Data URL if it is\n // available in keeping with the Data URL\n // specification [RFC2397].\n // * If mimeType is not available return a Data URL\n // without a media-type. [RFC2397].\n\n // https://datatracker.ietf.org/doc/html/rfc2397#section-3\n // dataurl := \"data:\" [ mediatype ] [ \";base64\" ] \",\" data\n // mediatype := [ type \"/\" subtype ] *( \";\" parameter )\n // data := *urlchar\n // parameter := attribute \"=\" value\n let dataURL = 'data:'\n\n const parsed = parseMIMEType(mimeType || 'application/octet-stream')\n\n if (parsed !== 'failure') {\n dataURL += serializeAMimeType(parsed)\n }\n\n dataURL += ';base64,'\n\n const decoder = new StringDecoder('latin1')\n\n for (const chunk of bytes) {\n dataURL += btoa(decoder.write(chunk))\n }\n\n dataURL += btoa(decoder.end())\n\n return dataURL\n }\n case 'Text': {\n // 1. Let encoding be failure\n let encoding = 'failure'\n\n // 2. If the encodingName is present, set encoding to the\n // result of getting an encoding from encodingName.\n if (encodingName) {\n encoding = getEncoding(encodingName)\n }\n\n // 3. If encoding is failure, and mimeType is present:\n if (encoding === 'failure' && mimeType) {\n // 1. Let type be the result of parse a MIME type\n // given mimeType.\n const type = parseMIMEType(mimeType)\n\n // 2. If type is not failure, set encoding to the result\n // of getting an encoding from type’s parameters[\"charset\"].\n if (type !== 'failure') {\n encoding = getEncoding(type.parameters.get('charset'))\n }\n }\n\n // 4. If encoding is failure, then set encoding to UTF-8.\n if (encoding === 'failure') {\n encoding = 'UTF-8'\n }\n\n // 5. Decode bytes using fallback encoding encoding, and\n // return the result.\n return decode(bytes, encoding)\n }\n case 'ArrayBuffer': {\n // Return a new ArrayBuffer whose contents are bytes.\n const sequence = combineByteSequences(bytes)\n\n return sequence.buffer\n }\n case 'BinaryString': {\n // Return bytes as a binary string, in which every byte\n // is represented by a code unit of equal value [0..255].\n let binaryString = ''\n\n const decoder = new StringDecoder('latin1')\n\n for (const chunk of bytes) {\n binaryString += decoder.write(chunk)\n }\n\n binaryString += decoder.end()\n\n return binaryString\n }\n }\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#decode\n * @param {Uint8Array[]} ioQueue\n * @param {string} encoding\n */\nfunction decode (ioQueue, encoding) {\n const bytes = combineByteSequences(ioQueue)\n\n // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.\n const BOMEncoding = BOMSniffing(bytes)\n\n let slice = 0\n\n // 2. If BOMEncoding is non-null:\n if (BOMEncoding !== null) {\n // 1. Set encoding to BOMEncoding.\n encoding = BOMEncoding\n\n // 2. Read three bytes from ioQueue, if BOMEncoding is\n // UTF-8; otherwise read two bytes.\n // (Do nothing with those bytes.)\n slice = BOMEncoding === 'UTF-8' ? 3 : 2\n }\n\n // 3. Process a queue with an instance of encoding’s\n // decoder, ioQueue, output, and \"replacement\".\n\n // 4. Return output.\n\n const sliced = bytes.slice(slice)\n return new TextDecoder(encoding).decode(sliced)\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#bom-sniff\n * @param {Uint8Array} ioQueue\n */\nfunction BOMSniffing (ioQueue) {\n // 1. Let BOM be the result of peeking 3 bytes from ioQueue,\n // converted to a byte sequence.\n const [a, b, c] = ioQueue\n\n // 2. For each of the rows in the table below, starting with\n // the first one and going down, if BOM starts with the\n // bytes given in the first column, then return the\n // encoding given in the cell in the second column of that\n // row. Otherwise, return null.\n if (a === 0xEF && b === 0xBB && c === 0xBF) {\n return 'UTF-8'\n } else if (a === 0xFE && b === 0xFF) {\n return 'UTF-16BE'\n } else if (a === 0xFF && b === 0xFE) {\n return 'UTF-16LE'\n }\n\n return null\n}\n\n/**\n * @param {Uint8Array[]} sequences\n */\nfunction combineByteSequences (sequences) {\n const size = sequences.reduce((a, b) => {\n return a + b.byteLength\n }, 0)\n\n let offset = 0\n\n return sequences.reduce((a, b) => {\n a.set(b, offset)\n offset += b.byteLength\n return a\n }, new Uint8Array(size))\n}\n\nmodule.exports = {\n staticPropertyDescriptors,\n readOperation,\n fireAProgressEvent\n}\n","'use strict'\n\n// We include a version number for the Dispatcher API. In case of breaking changes,\n// this version number must be increased to avoid conflicts.\nconst globalDispatcher = Symbol.for('undici.globalDispatcher.1')\nconst { InvalidArgumentError } = require('./core/errors')\nconst Agent = require('./agent')\n\nif (getGlobalDispatcher() === undefined) {\n setGlobalDispatcher(new Agent())\n}\n\nfunction setGlobalDispatcher (agent) {\n if (!agent || typeof agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument agent must implement Agent')\n }\n Object.defineProperty(globalThis, globalDispatcher, {\n value: agent,\n writable: true,\n enumerable: false,\n configurable: false\n })\n}\n\nfunction getGlobalDispatcher () {\n return globalThis[globalDispatcher]\n}\n\nmodule.exports = {\n setGlobalDispatcher,\n getGlobalDispatcher\n}\n","'use strict'\n\nmodule.exports = class DecoratorHandler {\n constructor (handler) {\n this.handler = handler\n }\n\n onConnect (...args) {\n return this.handler.onConnect(...args)\n }\n\n onError (...args) {\n return this.handler.onError(...args)\n }\n\n onUpgrade (...args) {\n return this.handler.onUpgrade(...args)\n }\n\n onHeaders (...args) {\n return this.handler.onHeaders(...args)\n }\n\n onData (...args) {\n return this.handler.onData(...args)\n }\n\n onComplete (...args) {\n return this.handler.onComplete(...args)\n }\n\n onBodySent (...args) {\n return this.handler.onBodySent(...args)\n }\n}\n","'use strict'\n\nconst util = require('../core/util')\nconst { kBodyUsed } = require('../core/symbols')\nconst assert = require('assert')\nconst { InvalidArgumentError } = require('../core/errors')\nconst EE = require('events')\n\nconst redirectableStatusCodes = [300, 301, 302, 303, 307, 308]\n\nconst kBody = Symbol('body')\n\nclass BodyAsyncIterable {\n constructor (body) {\n this[kBody] = body\n this[kBodyUsed] = false\n }\n\n async * [Symbol.asyncIterator] () {\n assert(!this[kBodyUsed], 'disturbed')\n this[kBodyUsed] = true\n yield * this[kBody]\n }\n}\n\nclass RedirectHandler {\n constructor (dispatch, maxRedirections, opts, handler) {\n if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n util.validateHandler(handler, opts.method, opts.upgrade)\n\n this.dispatch = dispatch\n this.location = null\n this.abort = null\n this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy\n this.maxRedirections = maxRedirections\n this.handler = handler\n this.history = []\n\n if (util.isStream(this.opts.body)) {\n // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp\n // so that it can be dispatched again?\n // TODO (fix): Do we need 100-expect support to provide a way to do this properly?\n if (util.bodyLength(this.opts.body) === 0) {\n this.opts.body\n .on('data', function () {\n assert(false)\n })\n }\n\n if (typeof this.opts.body.readableDidRead !== 'boolean') {\n this.opts.body[kBodyUsed] = false\n EE.prototype.on.call(this.opts.body, 'data', function () {\n this[kBodyUsed] = true\n })\n }\n } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {\n // TODO (fix): We can't access ReadableStream internal state\n // to determine whether or not it has been disturbed. This is just\n // a workaround.\n this.opts.body = new BodyAsyncIterable(this.opts.body)\n } else if (\n this.opts.body &&\n typeof this.opts.body !== 'string' &&\n !ArrayBuffer.isView(this.opts.body) &&\n util.isIterable(this.opts.body)\n ) {\n // TODO: Should we allow re-using iterable if !this.opts.idempotent\n // or through some other flag?\n this.opts.body = new BodyAsyncIterable(this.opts.body)\n }\n }\n\n onConnect (abort) {\n this.abort = abort\n this.handler.onConnect(abort, { history: this.history })\n }\n\n onUpgrade (statusCode, headers, socket) {\n this.handler.onUpgrade(statusCode, headers, socket)\n }\n\n onError (error) {\n this.handler.onError(error)\n }\n\n onHeaders (statusCode, headers, resume, statusText) {\n this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)\n ? null\n : parseLocation(statusCode, headers)\n\n if (this.opts.origin) {\n this.history.push(new URL(this.opts.path, this.opts.origin))\n }\n\n if (!this.location) {\n return this.handler.onHeaders(statusCode, headers, resume, statusText)\n }\n\n const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))\n const path = search ? `${pathname}${search}` : pathname\n\n // Remove headers referring to the original URL.\n // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.\n // https://tools.ietf.org/html/rfc7231#section-6.4\n this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)\n this.opts.path = path\n this.opts.origin = origin\n this.opts.maxRedirections = 0\n this.opts.query = null\n\n // https://tools.ietf.org/html/rfc7231#section-6.4.4\n // In case of HTTP 303, always replace method to be either HEAD or GET\n if (statusCode === 303 && this.opts.method !== 'HEAD') {\n this.opts.method = 'GET'\n this.opts.body = null\n }\n }\n\n onData (chunk) {\n if (this.location) {\n /*\n https://tools.ietf.org/html/rfc7231#section-6.4\n\n TLDR: undici always ignores 3xx response bodies.\n\n Redirection is used to serve the requested resource from another URL, so it is assumes that\n no body is generated (and thus can be ignored). Even though generating a body is not prohibited.\n\n For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually\n (which means it's optional and not mandated) contain just an hyperlink to the value of\n the Location response header, so the body can be ignored safely.\n\n For status 300, which is \"Multiple Choices\", the spec mentions both generating a Location\n response header AND a response body with the other possible location to follow.\n Since the spec explicitily chooses not to specify a format for such body and leave it to\n servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.\n */\n } else {\n return this.handler.onData(chunk)\n }\n }\n\n onComplete (trailers) {\n if (this.location) {\n /*\n https://tools.ietf.org/html/rfc7231#section-6.4\n\n TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections\n and neither are useful if present.\n\n See comment on onData method above for more detailed informations.\n */\n\n this.location = null\n this.abort = null\n\n this.dispatch(this.opts, this)\n } else {\n this.handler.onComplete(trailers)\n }\n }\n\n onBodySent (chunk) {\n if (this.handler.onBodySent) {\n this.handler.onBodySent(chunk)\n }\n }\n}\n\nfunction parseLocation (statusCode, headers) {\n if (redirectableStatusCodes.indexOf(statusCode) === -1) {\n return null\n }\n\n for (let i = 0; i < headers.length; i += 2) {\n if (headers[i].toString().toLowerCase() === 'location') {\n return headers[i + 1]\n }\n }\n}\n\n// https://tools.ietf.org/html/rfc7231#section-6.4.4\nfunction shouldRemoveHeader (header, removeContent, unknownOrigin) {\n if (header.length === 4) {\n return util.headerNameToString(header) === 'host'\n }\n if (removeContent && util.headerNameToString(header).startsWith('content-')) {\n return true\n }\n if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {\n const name = util.headerNameToString(header)\n return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'\n }\n return false\n}\n\n// https://tools.ietf.org/html/rfc7231#section-6.4\nfunction cleanRequestHeaders (headers, removeContent, unknownOrigin) {\n const ret = []\n if (Array.isArray(headers)) {\n for (let i = 0; i < headers.length; i += 2) {\n if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {\n ret.push(headers[i], headers[i + 1])\n }\n }\n } else if (headers && typeof headers === 'object') {\n for (const key of Object.keys(headers)) {\n if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {\n ret.push(key, headers[key])\n }\n }\n } else {\n assert(headers == null, 'headers must be an object or an array')\n }\n return ret\n}\n\nmodule.exports = RedirectHandler\n","const assert = require('assert')\n\nconst { kRetryHandlerDefaultRetry } = require('../core/symbols')\nconst { RequestRetryError } = require('../core/errors')\nconst { isDisturbed, parseHeaders, parseRangeHeader } = require('../core/util')\n\nfunction calculateRetryAfterHeader (retryAfter) {\n const current = Date.now()\n const diff = new Date(retryAfter).getTime() - current\n\n return diff\n}\n\nclass RetryHandler {\n constructor (opts, handlers) {\n const { retryOptions, ...dispatchOpts } = opts\n const {\n // Retry scoped\n retry: retryFn,\n maxRetries,\n maxTimeout,\n minTimeout,\n timeoutFactor,\n // Response scoped\n methods,\n errorCodes,\n retryAfter,\n statusCodes\n } = retryOptions ?? {}\n\n this.dispatch = handlers.dispatch\n this.handler = handlers.handler\n this.opts = dispatchOpts\n this.abort = null\n this.aborted = false\n this.retryOpts = {\n retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],\n retryAfter: retryAfter ?? true,\n maxTimeout: maxTimeout ?? 30 * 1000, // 30s,\n timeout: minTimeout ?? 500, // .5s\n timeoutFactor: timeoutFactor ?? 2,\n maxRetries: maxRetries ?? 5,\n // What errors we should retry\n methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],\n // Indicates which errors to retry\n statusCodes: statusCodes ?? [500, 502, 503, 504, 429],\n // List of errors to retry\n errorCodes: errorCodes ?? [\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ENETDOWN',\n 'ENETUNREACH',\n 'EHOSTDOWN',\n 'EHOSTUNREACH',\n 'EPIPE'\n ]\n }\n\n this.retryCount = 0\n this.start = 0\n this.end = null\n this.etag = null\n this.resume = null\n\n // Handle possible onConnect duplication\n this.handler.onConnect(reason => {\n this.aborted = true\n if (this.abort) {\n this.abort(reason)\n } else {\n this.reason = reason\n }\n })\n }\n\n onRequestSent () {\n if (this.handler.onRequestSent) {\n this.handler.onRequestSent()\n }\n }\n\n onUpgrade (statusCode, headers, socket) {\n if (this.handler.onUpgrade) {\n this.handler.onUpgrade(statusCode, headers, socket)\n }\n }\n\n onConnect (abort) {\n if (this.aborted) {\n abort(this.reason)\n } else {\n this.abort = abort\n }\n }\n\n onBodySent (chunk) {\n if (this.handler.onBodySent) return this.handler.onBodySent(chunk)\n }\n\n static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {\n const { statusCode, code, headers } = err\n const { method, retryOptions } = opts\n const {\n maxRetries,\n timeout,\n maxTimeout,\n timeoutFactor,\n statusCodes,\n errorCodes,\n methods\n } = retryOptions\n let { counter, currentTimeout } = state\n\n currentTimeout =\n currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout\n\n // Any code that is not a Undici's originated and allowed to retry\n if (\n code &&\n code !== 'UND_ERR_REQ_RETRY' &&\n code !== 'UND_ERR_SOCKET' &&\n !errorCodes.includes(code)\n ) {\n cb(err)\n return\n }\n\n // If a set of method are provided and the current method is not in the list\n if (Array.isArray(methods) && !methods.includes(method)) {\n cb(err)\n return\n }\n\n // If a set of status code are provided and the current status code is not in the list\n if (\n statusCode != null &&\n Array.isArray(statusCodes) &&\n !statusCodes.includes(statusCode)\n ) {\n cb(err)\n return\n }\n\n // If we reached the max number of retries\n if (counter > maxRetries) {\n cb(err)\n return\n }\n\n let retryAfterHeader = headers != null && headers['retry-after']\n if (retryAfterHeader) {\n retryAfterHeader = Number(retryAfterHeader)\n retryAfterHeader = isNaN(retryAfterHeader)\n ? calculateRetryAfterHeader(retryAfterHeader)\n : retryAfterHeader * 1e3 // Retry-After is in seconds\n }\n\n const retryTimeout =\n retryAfterHeader > 0\n ? Math.min(retryAfterHeader, maxTimeout)\n : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)\n\n state.currentTimeout = retryTimeout\n\n setTimeout(() => cb(null), retryTimeout)\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const headers = parseHeaders(rawHeaders)\n\n this.retryCount += 1\n\n if (statusCode >= 300) {\n this.abort(\n new RequestRetryError('Request failed', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n // Checkpoint for resume from where we left it\n if (this.resume != null) {\n this.resume = null\n\n if (statusCode !== 206) {\n return true\n }\n\n const contentRange = parseRangeHeader(headers['content-range'])\n // If no content range\n if (!contentRange) {\n this.abort(\n new RequestRetryError('Content-Range mismatch', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n // Let's start with a weak etag check\n if (this.etag != null && this.etag !== headers.etag) {\n this.abort(\n new RequestRetryError('ETag mismatch', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n const { start, size, end = size } = contentRange\n\n assert(this.start === start, 'content-range mismatch')\n assert(this.end == null || this.end === end, 'content-range mismatch')\n\n this.resume = resume\n return true\n }\n\n if (this.end == null) {\n if (statusCode === 206) {\n // First time we receive 206\n const range = parseRangeHeader(headers['content-range'])\n\n if (range == null) {\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n const { start, size, end = size } = range\n\n assert(\n start != null && Number.isFinite(start) && this.start !== start,\n 'content-range mismatch'\n )\n assert(Number.isFinite(start))\n assert(\n end != null && Number.isFinite(end) && this.end !== end,\n 'invalid content-length'\n )\n\n this.start = start\n this.end = end\n }\n\n // We make our best to checkpoint the body for further range headers\n if (this.end == null) {\n const contentLength = headers['content-length']\n this.end = contentLength != null ? Number(contentLength) : null\n }\n\n assert(Number.isFinite(this.start))\n assert(\n this.end == null || Number.isFinite(this.end),\n 'invalid content-length'\n )\n\n this.resume = resume\n this.etag = headers.etag != null ? headers.etag : null\n\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n const err = new RequestRetryError('Request failed', statusCode, {\n headers,\n count: this.retryCount\n })\n\n this.abort(err)\n\n return false\n }\n\n onData (chunk) {\n this.start += chunk.length\n\n return this.handler.onData(chunk)\n }\n\n onComplete (rawTrailers) {\n this.retryCount = 0\n return this.handler.onComplete(rawTrailers)\n }\n\n onError (err) {\n if (this.aborted || isDisturbed(this.opts.body)) {\n return this.handler.onError(err)\n }\n\n this.retryOpts.retry(\n err,\n {\n state: { counter: this.retryCount++, currentTimeout: this.retryAfter },\n opts: { retryOptions: this.retryOpts, ...this.opts }\n },\n onRetry.bind(this)\n )\n\n function onRetry (err) {\n if (err != null || this.aborted || isDisturbed(this.opts.body)) {\n return this.handler.onError(err)\n }\n\n if (this.start !== 0) {\n this.opts = {\n ...this.opts,\n headers: {\n ...this.opts.headers,\n range: `bytes=${this.start}-${this.end ?? ''}`\n }\n }\n }\n\n try {\n this.dispatch(this.opts, this)\n } catch (err) {\n this.handler.onError(err)\n }\n }\n }\n}\n\nmodule.exports = RetryHandler\n","'use strict'\n\nconst RedirectHandler = require('../handler/RedirectHandler')\n\nfunction createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {\n return (dispatch) => {\n return function Intercept (opts, handler) {\n const { maxRedirections = defaultMaxRedirections } = opts\n\n if (!maxRedirections) {\n return dispatch(opts, handler)\n }\n\n const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)\n opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.\n return dispatch(opts, redirectHandler)\n }\n }\n}\n\nmodule.exports = createRedirectInterceptor\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;\nconst utils_1 = require(\"./utils\");\n// C headers\nvar ERROR;\n(function (ERROR) {\n ERROR[ERROR[\"OK\"] = 0] = \"OK\";\n ERROR[ERROR[\"INTERNAL\"] = 1] = \"INTERNAL\";\n ERROR[ERROR[\"STRICT\"] = 2] = \"STRICT\";\n ERROR[ERROR[\"LF_EXPECTED\"] = 3] = \"LF_EXPECTED\";\n ERROR[ERROR[\"UNEXPECTED_CONTENT_LENGTH\"] = 4] = \"UNEXPECTED_CONTENT_LENGTH\";\n ERROR[ERROR[\"CLOSED_CONNECTION\"] = 5] = \"CLOSED_CONNECTION\";\n ERROR[ERROR[\"INVALID_METHOD\"] = 6] = \"INVALID_METHOD\";\n ERROR[ERROR[\"INVALID_URL\"] = 7] = \"INVALID_URL\";\n ERROR[ERROR[\"INVALID_CONSTANT\"] = 8] = \"INVALID_CONSTANT\";\n ERROR[ERROR[\"INVALID_VERSION\"] = 9] = \"INVALID_VERSION\";\n ERROR[ERROR[\"INVALID_HEADER_TOKEN\"] = 10] = \"INVALID_HEADER_TOKEN\";\n ERROR[ERROR[\"INVALID_CONTENT_LENGTH\"] = 11] = \"INVALID_CONTENT_LENGTH\";\n ERROR[ERROR[\"INVALID_CHUNK_SIZE\"] = 12] = \"INVALID_CHUNK_SIZE\";\n ERROR[ERROR[\"INVALID_STATUS\"] = 13] = \"INVALID_STATUS\";\n ERROR[ERROR[\"INVALID_EOF_STATE\"] = 14] = \"INVALID_EOF_STATE\";\n ERROR[ERROR[\"INVALID_TRANSFER_ENCODING\"] = 15] = \"INVALID_TRANSFER_ENCODING\";\n ERROR[ERROR[\"CB_MESSAGE_BEGIN\"] = 16] = \"CB_MESSAGE_BEGIN\";\n ERROR[ERROR[\"CB_HEADERS_COMPLETE\"] = 17] = \"CB_HEADERS_COMPLETE\";\n ERROR[ERROR[\"CB_MESSAGE_COMPLETE\"] = 18] = \"CB_MESSAGE_COMPLETE\";\n ERROR[ERROR[\"CB_CHUNK_HEADER\"] = 19] = \"CB_CHUNK_HEADER\";\n ERROR[ERROR[\"CB_CHUNK_COMPLETE\"] = 20] = \"CB_CHUNK_COMPLETE\";\n ERROR[ERROR[\"PAUSED\"] = 21] = \"PAUSED\";\n ERROR[ERROR[\"PAUSED_UPGRADE\"] = 22] = \"PAUSED_UPGRADE\";\n ERROR[ERROR[\"PAUSED_H2_UPGRADE\"] = 23] = \"PAUSED_H2_UPGRADE\";\n ERROR[ERROR[\"USER\"] = 24] = \"USER\";\n})(ERROR = exports.ERROR || (exports.ERROR = {}));\nvar TYPE;\n(function (TYPE) {\n TYPE[TYPE[\"BOTH\"] = 0] = \"BOTH\";\n TYPE[TYPE[\"REQUEST\"] = 1] = \"REQUEST\";\n TYPE[TYPE[\"RESPONSE\"] = 2] = \"RESPONSE\";\n})(TYPE = exports.TYPE || (exports.TYPE = {}));\nvar FLAGS;\n(function (FLAGS) {\n FLAGS[FLAGS[\"CONNECTION_KEEP_ALIVE\"] = 1] = \"CONNECTION_KEEP_ALIVE\";\n FLAGS[FLAGS[\"CONNECTION_CLOSE\"] = 2] = \"CONNECTION_CLOSE\";\n FLAGS[FLAGS[\"CONNECTION_UPGRADE\"] = 4] = \"CONNECTION_UPGRADE\";\n FLAGS[FLAGS[\"CHUNKED\"] = 8] = \"CHUNKED\";\n FLAGS[FLAGS[\"UPGRADE\"] = 16] = \"UPGRADE\";\n FLAGS[FLAGS[\"CONTENT_LENGTH\"] = 32] = \"CONTENT_LENGTH\";\n FLAGS[FLAGS[\"SKIPBODY\"] = 64] = \"SKIPBODY\";\n FLAGS[FLAGS[\"TRAILING\"] = 128] = \"TRAILING\";\n // 1 << 8 is unused\n FLAGS[FLAGS[\"TRANSFER_ENCODING\"] = 512] = \"TRANSFER_ENCODING\";\n})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));\nvar LENIENT_FLAGS;\n(function (LENIENT_FLAGS) {\n LENIENT_FLAGS[LENIENT_FLAGS[\"HEADERS\"] = 1] = \"HEADERS\";\n LENIENT_FLAGS[LENIENT_FLAGS[\"CHUNKED_LENGTH\"] = 2] = \"CHUNKED_LENGTH\";\n LENIENT_FLAGS[LENIENT_FLAGS[\"KEEP_ALIVE\"] = 4] = \"KEEP_ALIVE\";\n})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));\nvar METHODS;\n(function (METHODS) {\n METHODS[METHODS[\"DELETE\"] = 0] = \"DELETE\";\n METHODS[METHODS[\"GET\"] = 1] = \"GET\";\n METHODS[METHODS[\"HEAD\"] = 2] = \"HEAD\";\n METHODS[METHODS[\"POST\"] = 3] = \"POST\";\n METHODS[METHODS[\"PUT\"] = 4] = \"PUT\";\n /* pathological */\n METHODS[METHODS[\"CONNECT\"] = 5] = \"CONNECT\";\n METHODS[METHODS[\"OPTIONS\"] = 6] = \"OPTIONS\";\n METHODS[METHODS[\"TRACE\"] = 7] = \"TRACE\";\n /* WebDAV */\n METHODS[METHODS[\"COPY\"] = 8] = \"COPY\";\n METHODS[METHODS[\"LOCK\"] = 9] = \"LOCK\";\n METHODS[METHODS[\"MKCOL\"] = 10] = \"MKCOL\";\n METHODS[METHODS[\"MOVE\"] = 11] = \"MOVE\";\n METHODS[METHODS[\"PROPFIND\"] = 12] = \"PROPFIND\";\n METHODS[METHODS[\"PROPPATCH\"] = 13] = \"PROPPATCH\";\n METHODS[METHODS[\"SEARCH\"] = 14] = \"SEARCH\";\n METHODS[METHODS[\"UNLOCK\"] = 15] = \"UNLOCK\";\n METHODS[METHODS[\"BIND\"] = 16] = \"BIND\";\n METHODS[METHODS[\"REBIND\"] = 17] = \"REBIND\";\n METHODS[METHODS[\"UNBIND\"] = 18] = \"UNBIND\";\n METHODS[METHODS[\"ACL\"] = 19] = \"ACL\";\n /* subversion */\n METHODS[METHODS[\"REPORT\"] = 20] = \"REPORT\";\n METHODS[METHODS[\"MKACTIVITY\"] = 21] = \"MKACTIVITY\";\n METHODS[METHODS[\"CHECKOUT\"] = 22] = \"CHECKOUT\";\n METHODS[METHODS[\"MERGE\"] = 23] = \"MERGE\";\n /* upnp */\n METHODS[METHODS[\"M-SEARCH\"] = 24] = \"M-SEARCH\";\n METHODS[METHODS[\"NOTIFY\"] = 25] = \"NOTIFY\";\n METHODS[METHODS[\"SUBSCRIBE\"] = 26] = \"SUBSCRIBE\";\n METHODS[METHODS[\"UNSUBSCRIBE\"] = 27] = \"UNSUBSCRIBE\";\n /* RFC-5789 */\n METHODS[METHODS[\"PATCH\"] = 28] = \"PATCH\";\n METHODS[METHODS[\"PURGE\"] = 29] = \"PURGE\";\n /* CalDAV */\n METHODS[METHODS[\"MKCALENDAR\"] = 30] = \"MKCALENDAR\";\n /* RFC-2068, section 19.6.1.2 */\n METHODS[METHODS[\"LINK\"] = 31] = \"LINK\";\n METHODS[METHODS[\"UNLINK\"] = 32] = \"UNLINK\";\n /* icecast */\n METHODS[METHODS[\"SOURCE\"] = 33] = \"SOURCE\";\n /* RFC-7540, section 11.6 */\n METHODS[METHODS[\"PRI\"] = 34] = \"PRI\";\n /* RFC-2326 RTSP */\n METHODS[METHODS[\"DESCRIBE\"] = 35] = \"DESCRIBE\";\n METHODS[METHODS[\"ANNOUNCE\"] = 36] = \"ANNOUNCE\";\n METHODS[METHODS[\"SETUP\"] = 37] = \"SETUP\";\n METHODS[METHODS[\"PLAY\"] = 38] = \"PLAY\";\n METHODS[METHODS[\"PAUSE\"] = 39] = \"PAUSE\";\n METHODS[METHODS[\"TEARDOWN\"] = 40] = \"TEARDOWN\";\n METHODS[METHODS[\"GET_PARAMETER\"] = 41] = \"GET_PARAMETER\";\n METHODS[METHODS[\"SET_PARAMETER\"] = 42] = \"SET_PARAMETER\";\n METHODS[METHODS[\"REDIRECT\"] = 43] = \"REDIRECT\";\n METHODS[METHODS[\"RECORD\"] = 44] = \"RECORD\";\n /* RAOP */\n METHODS[METHODS[\"FLUSH\"] = 45] = \"FLUSH\";\n})(METHODS = exports.METHODS || (exports.METHODS = {}));\nexports.METHODS_HTTP = [\n METHODS.DELETE,\n METHODS.GET,\n METHODS.HEAD,\n METHODS.POST,\n METHODS.PUT,\n METHODS.CONNECT,\n METHODS.OPTIONS,\n METHODS.TRACE,\n METHODS.COPY,\n METHODS.LOCK,\n METHODS.MKCOL,\n METHODS.MOVE,\n METHODS.PROPFIND,\n METHODS.PROPPATCH,\n METHODS.SEARCH,\n METHODS.UNLOCK,\n METHODS.BIND,\n METHODS.REBIND,\n METHODS.UNBIND,\n METHODS.ACL,\n METHODS.REPORT,\n METHODS.MKACTIVITY,\n METHODS.CHECKOUT,\n METHODS.MERGE,\n METHODS['M-SEARCH'],\n METHODS.NOTIFY,\n METHODS.SUBSCRIBE,\n METHODS.UNSUBSCRIBE,\n METHODS.PATCH,\n METHODS.PURGE,\n METHODS.MKCALENDAR,\n METHODS.LINK,\n METHODS.UNLINK,\n METHODS.PRI,\n // TODO(indutny): should we allow it with HTTP?\n METHODS.SOURCE,\n];\nexports.METHODS_ICE = [\n METHODS.SOURCE,\n];\nexports.METHODS_RTSP = [\n METHODS.OPTIONS,\n METHODS.DESCRIBE,\n METHODS.ANNOUNCE,\n METHODS.SETUP,\n METHODS.PLAY,\n METHODS.PAUSE,\n METHODS.TEARDOWN,\n METHODS.GET_PARAMETER,\n METHODS.SET_PARAMETER,\n METHODS.REDIRECT,\n METHODS.RECORD,\n METHODS.FLUSH,\n // For AirPlay\n METHODS.GET,\n METHODS.POST,\n];\nexports.METHOD_MAP = utils_1.enumToMap(METHODS);\nexports.H_METHOD_MAP = {};\nObject.keys(exports.METHOD_MAP).forEach((key) => {\n if (/^H/.test(key)) {\n exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];\n }\n});\nvar FINISH;\n(function (FINISH) {\n FINISH[FINISH[\"SAFE\"] = 0] = \"SAFE\";\n FINISH[FINISH[\"SAFE_WITH_CB\"] = 1] = \"SAFE_WITH_CB\";\n FINISH[FINISH[\"UNSAFE\"] = 2] = \"UNSAFE\";\n})(FINISH = exports.FINISH || (exports.FINISH = {}));\nexports.ALPHA = [];\nfor (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {\n // Upper case\n exports.ALPHA.push(String.fromCharCode(i));\n // Lower case\n exports.ALPHA.push(String.fromCharCode(i + 0x20));\n}\nexports.NUM_MAP = {\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,\n 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n};\nexports.HEX_MAP = {\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,\n 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,\n a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,\n};\nexports.NUM = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n];\nexports.ALPHANUM = exports.ALPHA.concat(exports.NUM);\nexports.MARK = ['-', '_', '.', '!', '~', '*', '\\'', '(', ')'];\nexports.USERINFO_CHARS = exports.ALPHANUM\n .concat(exports.MARK)\n .concat(['%', ';', ':', '&', '=', '+', '$', ',']);\n// TODO(indutny): use RFC\nexports.STRICT_URL_CHAR = [\n '!', '\"', '$', '%', '&', '\\'',\n '(', ')', '*', '+', ',', '-', '.', '/',\n ':', ';', '<', '=', '>',\n '@', '[', '\\\\', ']', '^', '_',\n '`',\n '{', '|', '}', '~',\n].concat(exports.ALPHANUM);\nexports.URL_CHAR = exports.STRICT_URL_CHAR\n .concat(['\\t', '\\f']);\n// All characters with 0x80 bit set to 1\nfor (let i = 0x80; i <= 0xff; i++) {\n exports.URL_CHAR.push(i);\n}\nexports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);\n/* Tokens as defined by rfc 2616. Also lowercases them.\n * token = 1*\n * separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n * | \",\" | \";\" | \":\" | \"\\\" | <\">\n * | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n * | \"{\" | \"}\" | SP | HT\n */\nexports.STRICT_TOKEN = [\n '!', '#', '$', '%', '&', '\\'',\n '*', '+', '-', '.',\n '^', '_', '`',\n '|', '~',\n].concat(exports.ALPHANUM);\nexports.TOKEN = exports.STRICT_TOKEN.concat([' ']);\n/*\n * Verify that a char is a valid visible (printable) US-ASCII\n * character or %x80-FF\n */\nexports.HEADER_CHARS = ['\\t'];\nfor (let i = 32; i <= 255; i++) {\n if (i !== 127) {\n exports.HEADER_CHARS.push(i);\n }\n}\n// ',' = \\x44\nexports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);\nexports.MAJOR = exports.NUM_MAP;\nexports.MINOR = exports.MAJOR;\nvar HEADER_STATE;\n(function (HEADER_STATE) {\n HEADER_STATE[HEADER_STATE[\"GENERAL\"] = 0] = \"GENERAL\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION\"] = 1] = \"CONNECTION\";\n HEADER_STATE[HEADER_STATE[\"CONTENT_LENGTH\"] = 2] = \"CONTENT_LENGTH\";\n HEADER_STATE[HEADER_STATE[\"TRANSFER_ENCODING\"] = 3] = \"TRANSFER_ENCODING\";\n HEADER_STATE[HEADER_STATE[\"UPGRADE\"] = 4] = \"UPGRADE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_KEEP_ALIVE\"] = 5] = \"CONNECTION_KEEP_ALIVE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_CLOSE\"] = 6] = \"CONNECTION_CLOSE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_UPGRADE\"] = 7] = \"CONNECTION_UPGRADE\";\n HEADER_STATE[HEADER_STATE[\"TRANSFER_ENCODING_CHUNKED\"] = 8] = \"TRANSFER_ENCODING_CHUNKED\";\n})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));\nexports.SPECIAL_HEADERS = {\n 'connection': HEADER_STATE.CONNECTION,\n 'content-length': HEADER_STATE.CONTENT_LENGTH,\n 'proxy-connection': HEADER_STATE.CONNECTION,\n 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,\n 'upgrade': HEADER_STATE.UPGRADE,\n};\n//# sourceMappingURL=constants.js.map","module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkBigGLAYwBjQGOAY8BkAGRAZIBkwGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwHLAcoBuAHJAbkByAG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAQDcAQtBACEQDMYBC0EOIRAMxQELQQ0hEAzEAQtBDyEQDMMBC0EQIRAMwgELQRMhEAzBAQtBFCEQDMABC0EVIRAMvwELQRYhEAy+AQtBFyEQDL0BC0EYIRAMvAELQRkhEAy7AQtBGiEQDLoBC0EbIRAMuQELQRwhEAy4AQtBCCEQDLcBC0EdIRAMtgELQSAhEAy1AQtBHyEQDLQBC0EHIRAMswELQSEhEAyyAQtBIiEQDLEBC0EeIRAMsAELQSMhEAyvAQtBEiEQDK4BC0ERIRAMrQELQSQhEAysAQtBJSEQDKsBC0EmIRAMqgELQSchEAypAQtBwwEhEAyoAQtBKSEQDKcBC0ErIRAMpgELQSwhEAylAQtBLSEQDKQBC0EuIRAMowELQS8hEAyiAQtBxAEhEAyhAQtBMCEQDKABC0E0IRAMnwELQQwhEAyeAQtBMSEQDJ0BC0EyIRAMnAELQTMhEAybAQtBOSEQDJoBC0E1IRAMmQELQcUBIRAMmAELQQshEAyXAQtBOiEQDJYBC0E2IRAMlQELQQohEAyUAQtBNyEQDJMBC0E4IRAMkgELQTwhEAyRAQtBOyEQDJABC0E9IRAMjwELQQkhEAyOAQtBKCEQDI0BC0E+IRAMjAELQT8hEAyLAQtBwAAhEAyKAQtBwQAhEAyJAQtBwgAhEAyIAQtBwwAhEAyHAQtBxAAhEAyGAQtBxQAhEAyFAQtBxgAhEAyEAQtBKiEQDIMBC0HHACEQDIIBC0HIACEQDIEBC0HJACEQDIABC0HKACEQDH8LQcsAIRAMfgtBzQAhEAx9C0HMACEQDHwLQc4AIRAMewtBzwAhEAx6C0HQACEQDHkLQdEAIRAMeAtB0gAhEAx3C0HTACEQDHYLQdQAIRAMdQtB1gAhEAx0C0HVACEQDHMLQQYhEAxyC0HXACEQDHELQQUhEAxwC0HYACEQDG8LQQQhEAxuC0HZACEQDG0LQdoAIRAMbAtB2wAhEAxrC0HcACEQDGoLQQMhEAxpC0HdACEQDGgLQd4AIRAMZwtB3wAhEAxmC0HhACEQDGULQeAAIRAMZAtB4gAhEAxjC0HjACEQDGILQQIhEAxhC0HkACEQDGALQeUAIRAMXwtB5gAhEAxeC0HnACEQDF0LQegAIRAMXAtB6QAhEAxbC0HqACEQDFoLQesAIRAMWQtB7AAhEAxYC0HtACEQDFcLQe4AIRAMVgtB7wAhEAxVC0HwACEQDFQLQfEAIRAMUwtB8gAhEAxSC0HzACEQDFELQfQAIRAMUAtB9QAhEAxPC0H2ACEQDE4LQfcAIRAMTQtB+AAhEAxMC0H5ACEQDEsLQfoAIRAMSgtB+wAhEAxJC0H8ACEQDEgLQf0AIRAMRwtB/gAhEAxGC0H/ACEQDEULQYABIRAMRAtBgQEhEAxDC0GCASEQDEILQYMBIRAMQQtBhAEhEAxAC0GFASEQDD8LQYYBIRAMPgtBhwEhEAw9C0GIASEQDDwLQYkBIRAMOwtBigEhEAw6C0GLASEQDDkLQYwBIRAMOAtBjQEhEAw3C0GOASEQDDYLQY8BIRAMNQtBkAEhEAw0C0GRASEQDDMLQZIBIRAMMgtBkwEhEAwxC0GUASEQDDALQZUBIRAMLwtBlgEhEAwuC0GXASEQDC0LQZgBIRAMLAtBmQEhEAwrC0GaASEQDCoLQZsBIRAMKQtBnAEhEAwoC0GdASEQDCcLQZ4BIRAMJgtBnwEhEAwlC0GgASEQDCQLQaEBIRAMIwtBogEhEAwiC0GjASEQDCELQaQBIRAMIAtBpQEhEAwfC0GmASEQDB4LQacBIRAMHQtBqAEhEAwcC0GpASEQDBsLQaoBIRAMGgtBqwEhEAwZC0GsASEQDBgLQa0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAdUB1gHXAdgB2QHaAdsB3AHdAd4B4AHhAeIB4wHkAeUB5gHnAegB6QHqAesB7AHtAe4B7wHwAfEB8gHzAZkCpAKwAv4C/gILIAEiBCACRw3zAUHdASEQDP8DCyABIhAgAkcN3QFBwwEhEAz+AwsgASIBIAJHDZABQfcAIRAM/QMLIAEiASACRw2GAUHvACEQDPwDCyABIgEgAkcNf0HqACEQDPsDCyABIgEgAkcNe0HoACEQDPoDCyABIgEgAkcNeEHmACEQDPkDCyABIgEgAkcNGkEYIRAM+AMLIAEiASACRw0UQRIhEAz3AwsgASIBIAJHDVlBxQAhEAz2AwsgASIBIAJHDUpBPyEQDPUDCyABIgEgAkcNSEE8IRAM9AMLIAEiASACRw1BQTEhEAzzAwsgAC0ALkEBRg3rAwyHAgsgACABIgEgAhDAgICAAEEBRw3mASAAQgA3AyAM5wELIAAgASIBIAIQtICAgAAiEA3nASABIQEM9QILAkAgASIBIAJHDQBBBiEQDPADCyAAIAFBAWoiASACELuAgIAAIhAN6AEgASEBDDELIABCADcDIEESIRAM1QMLIAEiECACRw0rQR0hEAztAwsCQCABIgEgAkYNACABQQFqIQFBECEQDNQDC0EHIRAM7AMLIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN5QFBCCEQDOsDCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEUIRAM0gMLQQkhEAzqAwsgASEBIAApAyBQDeQBIAEhAQzyAgsCQCABIgEgAkcNAEELIRAM6QMLIAAgAUEBaiIBIAIQtoCAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3mASABIQEMDQsgACABIgEgAhC6gICAACIQDecBIAEhAQzwAgsCQCABIgEgAkcNAEEPIRAM5QMLIAEtAAAiEEE7Rg0IIBBBDUcN6AEgAUEBaiEBDO8CCyAAIAEiASACELqAgIAAIhAN6AEgASEBDPICCwNAAkAgAS0AAEHwtYCAAGotAAAiEEEBRg0AIBBBAkcN6wEgACgCBCEQIABBADYCBCAAIBAgAUEBaiIBELmAgIAAIhAN6gEgASEBDPQCCyABQQFqIgEgAkcNAAtBEiEQDOIDCyAAIAEiASACELqAgIAAIhAN6QEgASEBDAoLIAEiASACRw0GQRshEAzgAwsCQCABIgEgAkcNAEEWIRAM4AMLIABBioCAgAA2AgggACABNgIEIAAgASACELiAgIAAIhAN6gEgASEBQSAhEAzGAwsCQCABIgEgAkYNAANAAkAgAS0AAEHwt4CAAGotAAAiEEECRg0AAkAgEEF/ag4E5QHsAQDrAewBCyABQQFqIQFBCCEQDMgDCyABQQFqIgEgAkcNAAtBFSEQDN8DC0EVIRAM3gMLA0ACQCABLQAAQfC5gIAAai0AACIQQQJGDQAgEEF/ag4E3gHsAeAB6wHsAQsgAUEBaiIBIAJHDQALQRghEAzdAwsCQCABIgEgAkYNACAAQYuAgIAANgIIIAAgATYCBCABIQFBByEQDMQDC0EZIRAM3AMLIAFBAWohAQwCCwJAIAEiFCACRw0AQRohEAzbAwsgFCEBAkAgFC0AAEFzag4U3QLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gIA7gILQQAhECAAQQA2AhwgAEGvi4CAADYCECAAQQI2AgwgACAUQQFqNgIUDNoDCwJAIAEtAAAiEEE7Rg0AIBBBDUcN6AEgAUEBaiEBDOUCCyABQQFqIQELQSIhEAy/AwsCQCABIhAgAkcNAEEcIRAM2AMLQgAhESAQIQEgEC0AAEFQag435wHmAQECAwQFBgcIAAAAAAAAAAkKCwwNDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADxAREhMUAAtBHiEQDL0DC0ICIREM5QELQgMhEQzkAQtCBCERDOMBC0IFIREM4gELQgYhEQzhAQtCByERDOABC0IIIREM3wELQgkhEQzeAQtCCiERDN0BC0ILIREM3AELQgwhEQzbAQtCDSERDNoBC0IOIREM2QELQg8hEQzYAQtCCiERDNcBC0ILIREM1gELQgwhEQzVAQtCDSERDNQBC0IOIREM0wELQg8hEQzSAQtCACERAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQLQAAQVBqDjflAeQBAAECAwQFBgfmAeYB5gHmAeYB5gHmAQgJCgsMDeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gEODxAREhPmAQtCAiERDOQBC0IDIREM4wELQgQhEQziAQtCBSERDOEBC0IGIREM4AELQgchEQzfAQtCCCERDN4BC0IJIREM3QELQgohEQzcAQtCCyERDNsBC0IMIREM2gELQg0hEQzZAQtCDiERDNgBC0IPIREM1wELQgohEQzWAQtCCyERDNUBC0IMIREM1AELQg0hEQzTAQtCDiERDNIBC0IPIREM0QELIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN0gFBHyEQDMADCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEkIRAMpwMLQSAhEAy/AwsgACABIhAgAhC+gICAAEF/ag4FtgEAxQIB0QHSAQtBESEQDKQDCyAAQQE6AC8gECEBDLsDCyABIgEgAkcN0gFBJCEQDLsDCyABIg0gAkcNHkHGACEQDLoDCyAAIAEiASACELKAgIAAIhAN1AEgASEBDLUBCyABIhAgAkcNJkHQACEQDLgDCwJAIAEiASACRw0AQSghEAy4AwsgAEEANgIEIABBjICAgAA2AgggACABIAEQsYCAgAAiEA3TASABIQEM2AELAkAgASIQIAJHDQBBKSEQDLcDCyAQLQAAIgFBIEYNFCABQQlHDdMBIBBBAWohAQwVCwJAIAEiASACRg0AIAFBAWohAQwXC0EqIRAMtQMLAkAgASIQIAJHDQBBKyEQDLUDCwJAIBAtAAAiAUEJRg0AIAFBIEcN1QELIAAtACxBCEYN0wEgECEBDJEDCwJAIAEiASACRw0AQSwhEAy0AwsgAS0AAEEKRw3VASABQQFqIQEMyQILIAEiDiACRw3VAUEvIRAMsgMLA0ACQCABLQAAIhBBIEYNAAJAIBBBdmoOBADcAdwBANoBCyABIQEM4AELIAFBAWoiASACRw0AC0ExIRAMsQMLQTIhECABIhQgAkYNsAMgAiAUayAAKAIAIgFqIRUgFCABa0EDaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfC7gIAAai0AAEcNAQJAIAFBA0cNAEEGIQEMlgMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLEDCyAAQQA2AgAgFCEBDNkBC0EzIRAgASIUIAJGDa8DIAIgFGsgACgCACIBaiEVIBQgAWtBCGohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUH0u4CAAGotAABHDQECQCABQQhHDQBBBSEBDJUDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAywAwsgAEEANgIAIBQhAQzYAQtBNCEQIAEiFCACRg2uAyACIBRrIAAoAgAiAWohFSAUIAFrQQVqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw0BAkAgAUEFRw0AQQchAQyUAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMrwMLIABBADYCACAUIQEM1wELAkAgASIBIAJGDQADQAJAIAEtAABBgL6AgABqLQAAIhBBAUYNACAQQQJGDQogASEBDN0BCyABQQFqIgEgAkcNAAtBMCEQDK4DC0EwIRAMrQMLAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AIBBBdmoOBNkB2gHaAdkB2gELIAFBAWoiASACRw0AC0E4IRAMrQMLQTghEAysAwsDQAJAIAEtAAAiEEEgRg0AIBBBCUcNAwsgAUEBaiIBIAJHDQALQTwhEAyrAwsDQAJAIAEtAAAiEEEgRg0AAkACQCAQQXZqDgTaAQEB2gEACyAQQSxGDdsBCyABIQEMBAsgAUEBaiIBIAJHDQALQT8hEAyqAwsgASEBDNsBC0HAACEQIAEiFCACRg2oAyACIBRrIAAoAgAiAWohFiAUIAFrQQZqIRcCQANAIBQtAABBIHIgAUGAwICAAGotAABHDQEgAUEGRg2OAyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAypAwsgAEEANgIAIBQhAQtBNiEQDI4DCwJAIAEiDyACRw0AQcEAIRAMpwMLIABBjICAgAA2AgggACAPNgIEIA8hASAALQAsQX9qDgTNAdUB1wHZAYcDCyABQQFqIQEMzAELAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgciAQIBBBv39qQf8BcUEaSRtB/wFxIhBBCUYNACAQQSBGDQACQAJAAkACQCAQQZ1/ag4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIRAMkQMLIAFBAWohAUEyIRAMkAMLIAFBAWohAUEzIRAMjwMLIAEhAQzQAQsgAUEBaiIBIAJHDQALQTUhEAylAwtBNSEQDKQDCwJAIAEiASACRg0AA0ACQCABLQAAQYC8gIAAai0AAEEBRg0AIAEhAQzTAQsgAUEBaiIBIAJHDQALQT0hEAykAwtBPSEQDKMDCyAAIAEiASACELCAgIAAIhAN1gEgASEBDAELIBBBAWohAQtBPCEQDIcDCwJAIAEiASACRw0AQcIAIRAMoAMLAkADQAJAIAEtAABBd2oOGAAC/gL+AoQD/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4CAP4CCyABQQFqIgEgAkcNAAtBwgAhEAygAwsgAUEBaiEBIAAtAC1BAXFFDb0BIAEhAQtBLCEQDIUDCyABIgEgAkcN0wFBxAAhEAydAwsDQAJAIAEtAABBkMCAgABqLQAAQQFGDQAgASEBDLcCCyABQQFqIgEgAkcNAAtBxQAhEAycAwsgDS0AACIQQSBGDbMBIBBBOkcNgQMgACgCBCEBIABBADYCBCAAIAEgDRCvgICAACIBDdABIA1BAWohAQyzAgtBxwAhECABIg0gAkYNmgMgAiANayAAKAIAIgFqIRYgDSABa0EFaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGQwoCAAGotAABHDYADIAFBBUYN9AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmgMLQcgAIRAgASINIAJGDZkDIAIgDWsgACgCACIBaiEWIA0gAWtBCWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBlsKAgABqLQAARw3/AgJAIAFBCUcNAEECIQEM9QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJkDCwJAIAEiDSACRw0AQckAIRAMmQMLAkACQCANLQAAIgFBIHIgASABQb9/akH/AXFBGkkbQf8BcUGSf2oOBwCAA4ADgAOAA4ADAYADCyANQQFqIQFBPiEQDIADCyANQQFqIQFBPyEQDP8CC0HKACEQIAEiDSACRg2XAyACIA1rIAAoAgAiAWohFiANIAFrQQFqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaDCgIAAai0AAEcN/QIgAUEBRg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyXAwtBywAhECABIg0gAkYNlgMgAiANayAAKAIAIgFqIRYgDSABa0EOaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGiwoCAAGotAABHDfwCIAFBDkYN8AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlgMLQcwAIRAgASINIAJGDZUDIAIgDWsgACgCACIBaiEWIA0gAWtBD2ohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBwMKAgABqLQAARw37AgJAIAFBD0cNAEEDIQEM8QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJUDC0HNACEQIAEiDSACRg2UAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQdDCgIAAai0AAEcN+gICQCABQQVHDQBBBCEBDPACCyABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyUAwsCQCABIg0gAkcNAEHOACEQDJQDCwJAAkACQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZ1/ag4TAP0C/QL9Av0C/QL9Av0C/QL9Av0C/QL9AgH9Av0C/QICA/0CCyANQQFqIQFBwQAhEAz9AgsgDUEBaiEBQcIAIRAM/AILIA1BAWohAUHDACEQDPsCCyANQQFqIQFBxAAhEAz6AgsCQCABIgEgAkYNACAAQY2AgIAANgIIIAAgATYCBCABIQFBxQAhEAz6AgtBzwAhEAySAwsgECEBAkACQCAQLQAAQXZqDgQBqAKoAgCoAgsgEEEBaiEBC0EnIRAM+AILAkAgASIBIAJHDQBB0QAhEAyRAwsCQCABLQAAQSBGDQAgASEBDI0BCyABQQFqIQEgAC0ALUEBcUUNxwEgASEBDIwBCyABIhcgAkcNyAFB0gAhEAyPAwtB0wAhECABIhQgAkYNjgMgAiAUayAAKAIAIgFqIRYgFCABa0EBaiEXA0AgFC0AACABQdbCgIAAai0AAEcNzAEgAUEBRg3HASABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAyOAwsCQCABIgEgAkcNAEHVACEQDI4DCyABLQAAQQpHDcwBIAFBAWohAQzHAQsCQCABIgEgAkcNAEHWACEQDI0DCwJAAkAgAS0AAEF2ag4EAM0BzQEBzQELIAFBAWohAQzHAQsgAUEBaiEBQcoAIRAM8wILIAAgASIBIAIQroCAgAAiEA3LASABIQFBzQAhEAzyAgsgAC0AKUEiRg2FAwymAgsCQCABIgEgAkcNAEHbACEQDIoDC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgAS0AAEFQag4K1AHTAQABAgMEBQYI1QELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMzAELQQkhEEEBIRRBACEXQQAhFgzLAQsCQCABIgEgAkcNAEHdACEQDIkDCyABLQAAQS5HDcwBIAFBAWohAQymAgsgASIBIAJHDcwBQd8AIRAMhwMLAkAgASIBIAJGDQAgAEGOgICAADYCCCAAIAE2AgQgASEBQdAAIRAM7gILQeAAIRAMhgMLQeEAIRAgASIBIAJGDYUDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHiwoCAAGotAABHDc0BIBRBA0YNzAEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhQMLQeIAIRAgASIBIAJGDYQDIAIgAWsgACgCACIUaiEWIAEgFGtBAmohFwNAIAEtAAAgFEHmwoCAAGotAABHDcwBIBRBAkYNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhAMLQeMAIRAgASIBIAJGDYMDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHpwoCAAGotAABHDcsBIBRBA0YNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMgwMLAkAgASIBIAJHDQBB5QAhEAyDAwsgACABQQFqIgEgAhCogICAACIQDc0BIAEhAUHWACEQDOkCCwJAIAEiASACRg0AA0ACQCABLQAAIhBBIEYNAAJAAkACQCAQQbh/ag4LAAHPAc8BzwHPAc8BzwHPAc8BAs8BCyABQQFqIQFB0gAhEAztAgsgAUEBaiEBQdMAIRAM7AILIAFBAWohAUHUACEQDOsCCyABQQFqIgEgAkcNAAtB5AAhEAyCAwtB5AAhEAyBAwsDQAJAIAEtAABB8MKAgABqLQAAIhBBAUYNACAQQX5qDgPPAdAB0QHSAQsgAUEBaiIBIAJHDQALQeYAIRAMgAMLAkAgASIBIAJGDQAgAUEBaiEBDAMLQecAIRAM/wILA0ACQCABLQAAQfDEgIAAai0AACIQQQFGDQACQCAQQX5qDgTSAdMB1AEA1QELIAEhAUHXACEQDOcCCyABQQFqIgEgAkcNAAtB6AAhEAz+AgsCQCABIgEgAkcNAEHpACEQDP4CCwJAIAEtAAAiEEF2ag4augHVAdUBvAHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHKAdUB1QEA0wELIAFBAWohAQtBBiEQDOMCCwNAAkAgAS0AAEHwxoCAAGotAABBAUYNACABIQEMngILIAFBAWoiASACRw0AC0HqACEQDPsCCwJAIAEiASACRg0AIAFBAWohAQwDC0HrACEQDPoCCwJAIAEiASACRw0AQewAIRAM+gILIAFBAWohAQwBCwJAIAEiASACRw0AQe0AIRAM+QILIAFBAWohAQtBBCEQDN4CCwJAIAEiFCACRw0AQe4AIRAM9wILIBQhAQJAAkACQCAULQAAQfDIgIAAai0AAEF/ag4H1AHVAdYBAJwCAQLXAQsgFEEBaiEBDAoLIBRBAWohAQzNAQtBACEQIABBADYCHCAAQZuSgIAANgIQIABBBzYCDCAAIBRBAWo2AhQM9gILAkADQAJAIAEtAABB8MiAgABqLQAAIhBBBEYNAAJAAkAgEEF/ag4H0gHTAdQB2QEABAHZAQsgASEBQdoAIRAM4AILIAFBAWohAUHcACEQDN8CCyABQQFqIgEgAkcNAAtB7wAhEAz2AgsgAUEBaiEBDMsBCwJAIAEiFCACRw0AQfAAIRAM9QILIBQtAABBL0cN1AEgFEEBaiEBDAYLAkAgASIUIAJHDQBB8QAhEAz0AgsCQCAULQAAIgFBL0cNACAUQQFqIQFB3QAhEAzbAgsgAUF2aiIEQRZLDdMBQQEgBHRBiYCAAnFFDdMBDMoCCwJAIAEiASACRg0AIAFBAWohAUHeACEQDNoCC0HyACEQDPICCwJAIAEiFCACRw0AQfQAIRAM8gILIBQhAQJAIBQtAABB8MyAgABqLQAAQX9qDgPJApQCANQBC0HhACEQDNgCCwJAIAEiFCACRg0AA0ACQCAULQAAQfDKgIAAai0AACIBQQNGDQACQCABQX9qDgLLAgDVAQsgFCEBQd8AIRAM2gILIBRBAWoiFCACRw0AC0HzACEQDPECC0HzACEQDPACCwJAIAEiASACRg0AIABBj4CAgAA2AgggACABNgIEIAEhAUHgACEQDNcCC0H1ACEQDO8CCwJAIAEiASACRw0AQfYAIRAM7wILIABBj4CAgAA2AgggACABNgIEIAEhAQtBAyEQDNQCCwNAIAEtAABBIEcNwwIgAUEBaiIBIAJHDQALQfcAIRAM7AILAkAgASIBIAJHDQBB+AAhEAzsAgsgAS0AAEEgRw3OASABQQFqIQEM7wELIAAgASIBIAIQrICAgAAiEA3OASABIQEMjgILAkAgASIEIAJHDQBB+gAhEAzqAgsgBC0AAEHMAEcN0QEgBEEBaiEBQRMhEAzPAQsCQCABIgQgAkcNAEH7ACEQDOkCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRADQCAELQAAIAFB8M6AgABqLQAARw3QASABQQVGDc4BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQfsAIRAM6AILAkAgASIEIAJHDQBB/AAhEAzoAgsCQAJAIAQtAABBvX9qDgwA0QHRAdEB0QHRAdEB0QHRAdEB0QEB0QELIARBAWohAUHmACEQDM8CCyAEQQFqIQFB5wAhEAzOAgsCQCABIgQgAkcNAEH9ACEQDOcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDc8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH9ACEQDOcCCyAAQQA2AgAgEEEBaiEBQRAhEAzMAQsCQCABIgQgAkcNAEH+ACEQDOYCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUH2zoCAAGotAABHDc4BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH+ACEQDOYCCyAAQQA2AgAgEEEBaiEBQRYhEAzLAQsCQCABIgQgAkcNAEH/ACEQDOUCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUH8zoCAAGotAABHDc0BIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH/ACEQDOUCCyAAQQA2AgAgEEEBaiEBQQUhEAzKAQsCQCABIgQgAkcNAEGAASEQDOQCCyAELQAAQdkARw3LASAEQQFqIQFBCCEQDMkBCwJAIAEiBCACRw0AQYEBIRAM4wILAkACQCAELQAAQbJ/ag4DAMwBAcwBCyAEQQFqIQFB6wAhEAzKAgsgBEEBaiEBQewAIRAMyQILAkAgASIEIAJHDQBBggEhEAziAgsCQAJAIAQtAABBuH9qDggAywHLAcsBywHLAcsBAcsBCyAEQQFqIQFB6gAhEAzJAgsgBEEBaiEBQe0AIRAMyAILAkAgASIEIAJHDQBBgwEhEAzhAgsgAiAEayAAKAIAIgFqIRAgBCABa0ECaiEUAkADQCAELQAAIAFBgM+AgABqLQAARw3JASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBA2AgBBgwEhEAzhAgtBACEQIABBADYCACAUQQFqIQEMxgELAkAgASIEIAJHDQBBhAEhEAzgAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBg8+AgABqLQAARw3IASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhAEhEAzgAgsgAEEANgIAIBBBAWohAUEjIRAMxQELAkAgASIEIAJHDQBBhQEhEAzfAgsCQAJAIAQtAABBtH9qDggAyAHIAcgByAHIAcgBAcgBCyAEQQFqIQFB7wAhEAzGAgsgBEEBaiEBQfAAIRAMxQILAkAgASIEIAJHDQBBhgEhEAzeAgsgBC0AAEHFAEcNxQEgBEEBaiEBDIMCCwJAIAEiBCACRw0AQYcBIRAM3QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQYjPgIAAai0AAEcNxQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYcBIRAM3QILIABBADYCACAQQQFqIQFBLSEQDMIBCwJAIAEiBCACRw0AQYgBIRAM3AILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNxAEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYgBIRAM3AILIABBADYCACAQQQFqIQFBKSEQDMEBCwJAIAEiASACRw0AQYkBIRAM2wILQQEhECABLQAAQd8ARw3AASABQQFqIQEMgQILAkAgASIEIAJHDQBBigEhEAzaAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQA0AgBC0AACABQYzPgIAAai0AAEcNwQEgAUEBRg2vAiABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGKASEQDNkCCwJAIAEiBCACRw0AQYsBIRAM2QILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQY7PgIAAai0AAEcNwQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYsBIRAM2QILIABBADYCACAQQQFqIQFBAiEQDL4BCwJAIAEiBCACRw0AQYwBIRAM2AILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNwAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYwBIRAM2AILIABBADYCACAQQQFqIQFBHyEQDL0BCwJAIAEiBCACRw0AQY0BIRAM1wILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNvwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY0BIRAM1wILIABBADYCACAQQQFqIQFBCSEQDLwBCwJAIAEiBCACRw0AQY4BIRAM1gILAkACQCAELQAAQbd/ag4HAL8BvwG/Ab8BvwEBvwELIARBAWohAUH4ACEQDL0CCyAEQQFqIQFB+QAhEAy8AgsCQCABIgQgAkcNAEGPASEQDNUCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGRz4CAAGotAABHDb0BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGPASEQDNUCCyAAQQA2AgAgEEEBaiEBQRghEAy6AQsCQCABIgQgAkcNAEGQASEQDNQCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUGXz4CAAGotAABHDbwBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGQASEQDNQCCyAAQQA2AgAgEEEBaiEBQRchEAy5AQsCQCABIgQgAkcNAEGRASEQDNMCCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUGaz4CAAGotAABHDbsBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGRASEQDNMCCyAAQQA2AgAgEEEBaiEBQRUhEAy4AQsCQCABIgQgAkcNAEGSASEQDNICCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGhz4CAAGotAABHDboBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGSASEQDNICCyAAQQA2AgAgEEEBaiEBQR4hEAy3AQsCQCABIgQgAkcNAEGTASEQDNECCyAELQAAQcwARw24ASAEQQFqIQFBCiEQDLYBCwJAIAQgAkcNAEGUASEQDNACCwJAAkAgBC0AAEG/f2oODwC5AbkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AQG5AQsgBEEBaiEBQf4AIRAMtwILIARBAWohAUH/ACEQDLYCCwJAIAQgAkcNAEGVASEQDM8CCwJAAkAgBC0AAEG/f2oOAwC4AQG4AQsgBEEBaiEBQf0AIRAMtgILIARBAWohBEGAASEQDLUCCwJAIAQgAkcNAEGWASEQDM4CCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUGnz4CAAGotAABHDbYBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGWASEQDM4CCyAAQQA2AgAgEEEBaiEBQQshEAyzAQsCQCAEIAJHDQBBlwEhEAzNAgsCQAJAAkACQCAELQAAQVNqDiMAuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AQG4AbgBuAG4AbgBArgBuAG4AQO4AQsgBEEBaiEBQfsAIRAMtgILIARBAWohAUH8ACEQDLUCCyAEQQFqIQRBgQEhEAy0AgsgBEEBaiEEQYIBIRAMswILAkAgBCACRw0AQZgBIRAMzAILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQanPgIAAai0AAEcNtAEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZgBIRAMzAILIABBADYCACAQQQFqIQFBGSEQDLEBCwJAIAQgAkcNAEGZASEQDMsCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGuz4CAAGotAABHDbMBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGZASEQDMsCCyAAQQA2AgAgEEEBaiEBQQYhEAywAQsCQCAEIAJHDQBBmgEhEAzKAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBtM+AgABqLQAARw2yASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmgEhEAzKAgsgAEEANgIAIBBBAWohAUEcIRAMrwELAkAgBCACRw0AQZsBIRAMyQILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbbPgIAAai0AAEcNsQEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZsBIRAMyQILIABBADYCACAQQQFqIQFBJyEQDK4BCwJAIAQgAkcNAEGcASEQDMgCCwJAAkAgBC0AAEGsf2oOAgABsQELIARBAWohBEGGASEQDK8CCyAEQQFqIQRBhwEhEAyuAgsCQCAEIAJHDQBBnQEhEAzHAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBuM+AgABqLQAARw2vASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBnQEhEAzHAgsgAEEANgIAIBBBAWohAUEmIRAMrAELAkAgBCACRw0AQZ4BIRAMxgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbrPgIAAai0AAEcNrgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ4BIRAMxgILIABBADYCACAQQQFqIQFBAyEQDKsBCwJAIAQgAkcNAEGfASEQDMUCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDa0BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGfASEQDMUCCyAAQQA2AgAgEEEBaiEBQQwhEAyqAQsCQCAEIAJHDQBBoAEhEAzEAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBvM+AgABqLQAARw2sASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBoAEhEAzEAgsgAEEANgIAIBBBAWohAUENIRAMqQELAkAgBCACRw0AQaEBIRAMwwILAkACQCAELQAAQbp/ag4LAKwBrAGsAawBrAGsAawBrAGsAQGsAQsgBEEBaiEEQYsBIRAMqgILIARBAWohBEGMASEQDKkCCwJAIAQgAkcNAEGiASEQDMICCyAELQAAQdAARw2pASAEQQFqIQQM6QELAkAgBCACRw0AQaMBIRAMwQILAkACQCAELQAAQbd/ag4HAaoBqgGqAaoBqgEAqgELIARBAWohBEGOASEQDKgCCyAEQQFqIQFBIiEQDKYBCwJAIAQgAkcNAEGkASEQDMACCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHAz4CAAGotAABHDagBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGkASEQDMACCyAAQQA2AgAgEEEBaiEBQR0hEAylAQsCQCAEIAJHDQBBpQEhEAy/AgsCQAJAIAQtAABBrn9qDgMAqAEBqAELIARBAWohBEGQASEQDKYCCyAEQQFqIQFBBCEQDKQBCwJAIAQgAkcNAEGmASEQDL4CCwJAAkACQAJAAkAgBC0AAEG/f2oOFQCqAaoBqgGqAaoBqgGqAaoBqgGqAQGqAaoBAqoBqgEDqgGqAQSqAQsgBEEBaiEEQYgBIRAMqAILIARBAWohBEGJASEQDKcCCyAEQQFqIQRBigEhEAymAgsgBEEBaiEEQY8BIRAMpQILIARBAWohBEGRASEQDKQCCwJAIAQgAkcNAEGnASEQDL0CCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDaUBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGnASEQDL0CCyAAQQA2AgAgEEEBaiEBQREhEAyiAQsCQCAEIAJHDQBBqAEhEAy8AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBws+AgABqLQAARw2kASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqAEhEAy8AgsgAEEANgIAIBBBAWohAUEsIRAMoQELAkAgBCACRw0AQakBIRAMuwILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQcXPgIAAai0AAEcNowEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQakBIRAMuwILIABBADYCACAQQQFqIQFBKyEQDKABCwJAIAQgAkcNAEGqASEQDLoCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHKz4CAAGotAABHDaIBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGqASEQDLoCCyAAQQA2AgAgEEEBaiEBQRQhEAyfAQsCQCAEIAJHDQBBqwEhEAy5AgsCQAJAAkACQCAELQAAQb5/ag4PAAECpAGkAaQBpAGkAaQBpAGkAaQBpAGkAQOkAQsgBEEBaiEEQZMBIRAMogILIARBAWohBEGUASEQDKECCyAEQQFqIQRBlQEhEAygAgsgBEEBaiEEQZYBIRAMnwILAkAgBCACRw0AQawBIRAMuAILIAQtAABBxQBHDZ8BIARBAWohBAzgAQsCQCAEIAJHDQBBrQEhEAy3AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBzc+AgABqLQAARw2fASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrQEhEAy3AgsgAEEANgIAIBBBAWohAUEOIRAMnAELAkAgBCACRw0AQa4BIRAMtgILIAQtAABB0ABHDZ0BIARBAWohAUElIRAMmwELAkAgBCACRw0AQa8BIRAMtQILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNnQEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQa8BIRAMtQILIABBADYCACAQQQFqIQFBKiEQDJoBCwJAIAQgAkcNAEGwASEQDLQCCwJAAkAgBC0AAEGrf2oOCwCdAZ0BnQGdAZ0BnQGdAZ0BnQEBnQELIARBAWohBEGaASEQDJsCCyAEQQFqIQRBmwEhEAyaAgsCQCAEIAJHDQBBsQEhEAyzAgsCQAJAIAQtAABBv39qDhQAnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBAZwBCyAEQQFqIQRBmQEhEAyaAgsgBEEBaiEEQZwBIRAMmQILAkAgBCACRw0AQbIBIRAMsgILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQdnPgIAAai0AAEcNmgEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbIBIRAMsgILIABBADYCACAQQQFqIQFBISEQDJcBCwJAIAQgAkcNAEGzASEQDLECCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUHdz4CAAGotAABHDZkBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGzASEQDLECCyAAQQA2AgAgEEEBaiEBQRohEAyWAQsCQCAEIAJHDQBBtAEhEAywAgsCQAJAAkAgBC0AAEG7f2oOEQCaAZoBmgGaAZoBmgGaAZoBmgEBmgGaAZoBmgGaAQKaAQsgBEEBaiEEQZ0BIRAMmAILIARBAWohBEGeASEQDJcCCyAEQQFqIQRBnwEhEAyWAgsCQCAEIAJHDQBBtQEhEAyvAgsgAiAEayAAKAIAIgFqIRQgBCABa0EFaiEQAkADQCAELQAAIAFB5M+AgABqLQAARw2XASABQQVGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtQEhEAyvAgsgAEEANgIAIBBBAWohAUEoIRAMlAELAkAgBCACRw0AQbYBIRAMrgILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQerPgIAAai0AAEcNlgEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbYBIRAMrgILIABBADYCACAQQQFqIQFBByEQDJMBCwJAIAQgAkcNAEG3ASEQDK0CCwJAAkAgBC0AAEG7f2oODgCWAZYBlgGWAZYBlgGWAZYBlgGWAZYBlgEBlgELIARBAWohBEGhASEQDJQCCyAEQQFqIQRBogEhEAyTAgsCQCAEIAJHDQBBuAEhEAysAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB7c+AgABqLQAARw2UASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuAEhEAysAgsgAEEANgIAIBBBAWohAUESIRAMkQELAkAgBCACRw0AQbkBIRAMqwILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNkwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbkBIRAMqwILIABBADYCACAQQQFqIQFBICEQDJABCwJAIAQgAkcNAEG6ASEQDKoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHyz4CAAGotAABHDZIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG6ASEQDKoCCyAAQQA2AgAgEEEBaiEBQQ8hEAyPAQsCQCAEIAJHDQBBuwEhEAypAgsCQAJAIAQtAABBt39qDgcAkgGSAZIBkgGSAQGSAQsgBEEBaiEEQaUBIRAMkAILIARBAWohBEGmASEQDI8CCwJAIAQgAkcNAEG8ASEQDKgCCyACIARrIAAoAgAiAWohFCAEIAFrQQdqIRACQANAIAQtAAAgAUH0z4CAAGotAABHDZABIAFBB0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG8ASEQDKgCCyAAQQA2AgAgEEEBaiEBQRshEAyNAQsCQCAEIAJHDQBBvQEhEAynAgsCQAJAAkAgBC0AAEG+f2oOEgCRAZEBkQGRAZEBkQGRAZEBkQEBkQGRAZEBkQGRAZEBApEBCyAEQQFqIQRBpAEhEAyPAgsgBEEBaiEEQacBIRAMjgILIARBAWohBEGoASEQDI0CCwJAIAQgAkcNAEG+ASEQDKYCCyAELQAAQc4ARw2NASAEQQFqIQQMzwELAkAgBCACRw0AQb8BIRAMpQILAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgBC0AAEG/f2oOFQABAgOcAQQFBpwBnAGcAQcICQoLnAEMDQ4PnAELIARBAWohAUHoACEQDJoCCyAEQQFqIQFB6QAhEAyZAgsgBEEBaiEBQe4AIRAMmAILIARBAWohAUHyACEQDJcCCyAEQQFqIQFB8wAhEAyWAgsgBEEBaiEBQfYAIRAMlQILIARBAWohAUH3ACEQDJQCCyAEQQFqIQFB+gAhEAyTAgsgBEEBaiEEQYMBIRAMkgILIARBAWohBEGEASEQDJECCyAEQQFqIQRBhQEhEAyQAgsgBEEBaiEEQZIBIRAMjwILIARBAWohBEGYASEQDI4CCyAEQQFqIQRBoAEhEAyNAgsgBEEBaiEEQaMBIRAMjAILIARBAWohBEGqASEQDIsCCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEGrASEQDIsCC0HAASEQDKMCCyAAIAUgAhCqgICAACIBDYsBIAUhAQxcCwJAIAYgAkYNACAGQQFqIQUMjQELQcIBIRAMoQILA0ACQCAQLQAAQXZqDgSMAQAAjwEACyAQQQFqIhAgAkcNAAtBwwEhEAygAgsCQCAHIAJGDQAgAEGRgICAADYCCCAAIAc2AgQgByEBQQEhEAyHAgtBxAEhEAyfAgsCQCAHIAJHDQBBxQEhEAyfAgsCQAJAIActAABBdmoOBAHOAc4BAM4BCyAHQQFqIQYMjQELIAdBAWohBQyJAQsCQCAHIAJHDQBBxgEhEAyeAgsCQAJAIActAABBdmoOFwGPAY8BAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAQCPAQsgB0EBaiEHC0GwASEQDIQCCwJAIAggAkcNAEHIASEQDJ0CCyAILQAAQSBHDY0BIABBADsBMiAIQQFqIQFBswEhEAyDAgsgASEXAkADQCAXIgcgAkYNASAHLQAAQVBqQf8BcSIQQQpPDcwBAkAgAC8BMiIUQZkzSw0AIAAgFEEKbCIUOwEyIBBB//8DcyAUQf7/A3FJDQAgB0EBaiEXIAAgFCAQaiIQOwEyIBBB//8DcUHoB0kNAQsLQQAhECAAQQA2AhwgAEHBiYCAADYCECAAQQ02AgwgACAHQQFqNgIUDJwCC0HHASEQDJsCCyAAIAggAhCugICAACIQRQ3KASAQQRVHDYwBIABByAE2AhwgACAINgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAyaAgsCQCAJIAJHDQBBzAEhEAyaAgtBACEUQQEhF0EBIRZBACEQAkACQAJAAkACQAJAAkACQAJAIAktAABBUGoOCpYBlQEAAQIDBAUGCJcBC0ECIRAMBgtBAyEQDAULQQQhEAwEC0EFIRAMAwtBBiEQDAILQQchEAwBC0EIIRALQQAhF0EAIRZBACEUDI4BC0EJIRBBASEUQQAhF0EAIRYMjQELAkAgCiACRw0AQc4BIRAMmQILIAotAABBLkcNjgEgCkEBaiEJDMoBCyALIAJHDY4BQdABIRAMlwILAkAgCyACRg0AIABBjoCAgAA2AgggACALNgIEQbcBIRAM/gELQdEBIRAMlgILAkAgBCACRw0AQdIBIRAMlgILIAIgBGsgACgCACIQaiEUIAQgEGtBBGohCwNAIAQtAAAgEEH8z4CAAGotAABHDY4BIBBBBEYN6QEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB0gEhEAyVAgsgACAMIAIQrICAgAAiAQ2NASAMIQEMuAELAkAgBCACRw0AQdQBIRAMlAILIAIgBGsgACgCACIQaiEUIAQgEGtBAWohDANAIAQtAAAgEEGB0ICAAGotAABHDY8BIBBBAUYNjgEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB1AEhEAyTAgsCQCAEIAJHDQBB1gEhEAyTAgsgAiAEayAAKAIAIhBqIRQgBCAQa0ECaiELA0AgBC0AACAQQYPQgIAAai0AAEcNjgEgEEECRg2QASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHWASEQDJICCwJAIAQgAkcNAEHXASEQDJICCwJAAkAgBC0AAEG7f2oOEACPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAY8BCyAEQQFqIQRBuwEhEAz5AQsgBEEBaiEEQbwBIRAM+AELAkAgBCACRw0AQdgBIRAMkQILIAQtAABByABHDYwBIARBAWohBAzEAQsCQCAEIAJGDQAgAEGQgICAADYCCCAAIAQ2AgRBvgEhEAz3AQtB2QEhEAyPAgsCQCAEIAJHDQBB2gEhEAyPAgsgBC0AAEHIAEYNwwEgAEEBOgAoDLkBCyAAQQI6AC8gACAEIAIQpoCAgAAiEA2NAUHCASEQDPQBCyAALQAoQX9qDgK3AbkBuAELA0ACQCAELQAAQXZqDgQAjgGOAQCOAQsgBEEBaiIEIAJHDQALQd0BIRAMiwILIABBADoALyAALQAtQQRxRQ2EAgsgAEEAOgAvIABBAToANCABIQEMjAELIBBBFUYN2gEgAEEANgIcIAAgATYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMiAILAkAgACAQIAIQtICAgAAiBA0AIBAhAQyBAgsCQCAEQRVHDQAgAEEDNgIcIAAgEDYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMiAILIABBADYCHCAAIBA2AhQgAEGnjoCAADYCECAAQRI2AgxBACEQDIcCCyAQQRVGDdYBIABBADYCHCAAIAE2AhQgAEHajYCAADYCECAAQRQ2AgxBACEQDIYCCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNjQEgAEEHNgIcIAAgEDYCFCAAIBQ2AgxBACEQDIUCCyAAIAAvATBBgAFyOwEwIAEhAQtBKiEQDOoBCyAQQRVGDdEBIABBADYCHCAAIAE2AhQgAEGDjICAADYCECAAQRM2AgxBACEQDIICCyAQQRVGDc8BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDIECCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyNAQsgAEEMNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDIACCyAQQRVGDcwBIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDP8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyMAQsgAEENNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDP4BCyAQQRVGDckBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDP0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyLAQsgAEEONgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPwBCyAAQQA2AhwgACABNgIUIABBwJWAgAA2AhAgAEECNgIMQQAhEAz7AQsgEEEVRg3FASAAQQA2AhwgACABNgIUIABBxoyAgAA2AhAgAEEjNgIMQQAhEAz6AQsgAEEQNgIcIAAgATYCFCAAIBA2AgxBACEQDPkBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQzxAQsgAEERNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPgBCyAQQRVGDcEBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPcBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyIAQsgAEETNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPYBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQztAQsgAEEUNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPUBCyAQQRVGDb0BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDPQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyGAQsgAEEWNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPMBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQt4CAgAAiBA0AIAFBAWohAQzpAQsgAEEXNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPIBCyAAQQA2AhwgACABNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzxAQtCASERCyAQQQFqIQECQCAAKQMgIhJC//////////8PVg0AIAAgEkIEhiARhDcDICABIQEMhAELIABBADYCHCAAIAE2AhQgAEGtiYCAADYCECAAQQw2AgxBACEQDO8BCyAAQQA2AhwgACAQNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzuAQsgACgCBCEXIABBADYCBCAQIBGnaiIWIQEgACAXIBAgFiAUGyIQELWAgIAAIhRFDXMgAEEFNgIcIAAgEDYCFCAAIBQ2AgxBACEQDO0BCyAAQQA2AhwgACAQNgIUIABBqpyAgAA2AhAgAEEPNgIMQQAhEAzsAQsgACAQIAIQtICAgAAiAQ0BIBAhAQtBDiEQDNEBCwJAIAFBFUcNACAAQQI2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAzqAQsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAM6QELIAFBAWohEAJAIAAvATAiAUGAAXFFDQACQCAAIBAgAhC7gICAACIBDQAgECEBDHALIAFBFUcNugEgAEEFNgIcIAAgEDYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAM6QELAkAgAUGgBHFBoARHDQAgAC0ALUECcQ0AIABBADYCHCAAIBA2AhQgAEGWk4CAADYCECAAQQQ2AgxBACEQDOkBCyAAIBAgAhC9gICAABogECEBAkACQAJAAkACQCAAIBAgAhCzgICAAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIABBAToALgsgACAALwEwQcAAcjsBMCAQIQELQSYhEAzRAQsgAEEjNgIcIAAgEDYCFCAAQaWWgIAANgIQIABBFTYCDEEAIRAM6QELIABBADYCHCAAIBA2AhQgAEHVi4CAADYCECAAQRE2AgxBACEQDOgBCyAALQAtQQFxRQ0BQcMBIRAMzgELAkAgDSACRg0AA0ACQCANLQAAQSBGDQAgDSEBDMQBCyANQQFqIg0gAkcNAAtBJSEQDOcBC0ElIRAM5gELIAAoAgQhBCAAQQA2AgQgACAEIA0Qr4CAgAAiBEUNrQEgAEEmNgIcIAAgBDYCDCAAIA1BAWo2AhRBACEQDOUBCyAQQRVGDasBIABBADYCHCAAIAE2AhQgAEH9jYCAADYCECAAQR02AgxBACEQDOQBCyAAQSc2AhwgACABNgIUIAAgEDYCDEEAIRAM4wELIBAhAUEBIRQCQAJAAkACQAJAAkACQCAALQAsQX5qDgcGBQUDAQIABQsgACAALwEwQQhyOwEwDAMLQQIhFAwBC0EEIRQLIABBAToALCAAIAAvATAgFHI7ATALIBAhAQtBKyEQDMoBCyAAQQA2AhwgACAQNgIUIABBq5KAgAA2AhAgAEELNgIMQQAhEAziAQsgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDEEAIRAM4QELIABBADoALCAQIQEMvQELIBAhAUEBIRQCQAJAAkACQAJAIAAtACxBe2oOBAMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0EpIRAMxQELIABBADYCHCAAIAE2AhQgAEHwlICAADYCECAAQQM2AgxBACEQDN0BCwJAIA4tAABBDUcNACAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA5BAWohAQx1CyAAQSw2AhwgACABNgIMIAAgDkEBajYCFEEAIRAM3QELIAAtAC1BAXFFDQFBxAEhEAzDAQsCQCAOIAJHDQBBLSEQDNwBCwJAAkADQAJAIA4tAABBdmoOBAIAAAMACyAOQQFqIg4gAkcNAAtBLSEQDN0BCyAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA4hAQx0CyAAQSw2AhwgACAONgIUIAAgATYCDEEAIRAM3AELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHMLIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzbAQsgACgCBCEEIABBADYCBCAAIAQgDhCxgICAACIEDaABIA4hAQzOAQsgEEEsRw0BIAFBAWohEEEBIQECQAJAAkACQAJAIAAtACxBe2oOBAMBAgQACyAQIQEMBAtBAiEBDAELQQQhAQsgAEEBOgAsIAAgAC8BMCABcjsBMCAQIQEMAQsgACAALwEwQQhyOwEwIBAhAQtBOSEQDL8BCyAAQQA6ACwgASEBC0E0IRAMvQELIAAgAC8BMEEgcjsBMCABIQEMAgsgACgCBCEEIABBADYCBAJAIAAgBCABELGAgIAAIgQNACABIQEMxwELIABBNzYCHCAAIAE2AhQgACAENgIMQQAhEAzUAQsgAEEIOgAsIAEhAQtBMCEQDLkBCwJAIAAtAChBAUYNACABIQEMBAsgAC0ALUEIcUUNkwEgASEBDAMLIAAtADBBIHENlAFBxQEhEAy3AQsCQCAPIAJGDQACQANAAkAgDy0AAEFQaiIBQf8BcUEKSQ0AIA8hAUE1IRAMugELIAApAyAiEUKZs+bMmbPmzBlWDQEgACARQgp+IhE3AyAgESABrUL/AYMiEkJ/hVYNASAAIBEgEnw3AyAgD0EBaiIPIAJHDQALQTkhEAzRAQsgACgCBCECIABBADYCBCAAIAIgD0EBaiIEELGAgIAAIgINlQEgBCEBDMMBC0E5IRAMzwELAkAgAC8BMCIBQQhxRQ0AIAAtAChBAUcNACAALQAtQQhxRQ2QAQsgACABQff7A3FBgARyOwEwIA8hAQtBNyEQDLQBCyAAIAAvATBBEHI7ATAMqwELIBBBFUYNiwEgAEEANgIcIAAgATYCFCAAQfCOgIAANgIQIABBHDYCDEEAIRAMywELIABBwwA2AhwgACABNgIMIAAgDUEBajYCFEEAIRAMygELAkAgAS0AAEE6Rw0AIAAoAgQhECAAQQA2AgQCQCAAIBAgARCvgICAACIQDQAgAUEBaiEBDGMLIABBwwA2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMygELIABBADYCHCAAIAE2AhQgAEGxkYCAADYCECAAQQo2AgxBACEQDMkBCyAAQQA2AhwgACABNgIUIABBoJmAgAA2AhAgAEEeNgIMQQAhEAzIAQsgAEEANgIACyAAQYASOwEqIAAgF0EBaiIBIAIQqICAgAAiEA0BIAEhAQtBxwAhEAysAQsgEEEVRw2DASAAQdEANgIcIAAgATYCFCAAQeOXgIAANgIQIABBFTYCDEEAIRAMxAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDF4LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMwwELIABBADYCHCAAIBQ2AhQgAEHBqICAADYCECAAQQc2AgwgAEEANgIAQQAhEAzCAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAzBAQtBACEQIABBADYCHCAAIAE2AhQgAEGAkYCAADYCECAAQQk2AgwMwAELIBBBFUYNfSAAQQA2AhwgACABNgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAy/AQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgAUEBaiEBAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBAJAIAAgECABEK2AgIAAIhANACABIQEMXAsgAEHYADYCHCAAIAE2AhQgACAQNgIMQQAhEAy+AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMrQELIABB2QA2AhwgACABNgIUIAAgBDYCDEEAIRAMvQELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKsBCyAAQdoANgIcIAAgATYCFCAAIAQ2AgxBACEQDLwBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQypAQsgAEHcADYCHCAAIAE2AhQgACAENgIMQQAhEAy7AQsCQCABLQAAQVBqIhBB/wFxQQpPDQAgACAQOgAqIAFBAWohAUHPACEQDKIBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQynAQsgAEHeADYCHCAAIAE2AhQgACAENgIMQQAhEAy6AQsgAEEANgIAIBdBAWohAQJAIAAtAClBI08NACABIQEMWQsgAEEANgIcIAAgATYCFCAAQdOJgIAANgIQIABBCDYCDEEAIRAMuQELIABBADYCAAtBACEQIABBADYCHCAAIAE2AhQgAEGQs4CAADYCECAAQQg2AgwMtwELIABBADYCACAXQQFqIQECQCAALQApQSFHDQAgASEBDFYLIABBADYCHCAAIAE2AhQgAEGbioCAADYCECAAQQg2AgxBACEQDLYBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKSIQQV1qQQtPDQAgASEBDFULAkAgEEEGSw0AQQEgEHRBygBxRQ0AIAEhAQxVC0EAIRAgAEEANgIcIAAgATYCFCAAQfeJgIAANgIQIABBCDYCDAy1AQsgEEEVRg1xIABBADYCHCAAIAE2AhQgAEG5jYCAADYCECAAQRo2AgxBACEQDLQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxUCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLMBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAAgEDoAKSAAKAIEIRAgAEEANgIEIAAgECABEKuAgIAAIhANVCABIQEMPgsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQfGbgIAANgIQIABBBjYCDAyXAQsgAUEVRg1QIABBADYCHCAAIAU2AhQgAEHwjICAADYCECAAQRs2AgxBACEQDJYBCyAAKAIEIQUgAEEANgIEIAAgBSAQEKmAgIAAIgUNASAQQQFqIQULQa0BIRAMewsgAEHBATYCHCAAIAU2AgwgACAQQQFqNgIUQQAhEAyTAQsgACgCBCEGIABBADYCBCAAIAYgEBCpgICAACIGDQEgEEEBaiEGC0GuASEQDHgLIABBwgE2AhwgACAGNgIMIAAgEEEBajYCFEEAIRAMkAELIABBADYCHCAAIAc2AhQgAEGXi4CAADYCECAAQQ02AgxBACEQDI8BCyAAQQA2AhwgACAINgIUIABB45CAgAA2AhAgAEEJNgIMQQAhEAyOAQsgAEEANgIcIAAgCDYCFCAAQZSNgIAANgIQIABBITYCDEEAIRAMjQELQQEhFkEAIRdBACEUQQEhEAsgACAQOgArIAlBAWohCAJAAkAgAC0ALUEQcQ0AAkACQAJAIAAtACoOAwEAAgQLIBZFDQMMAgsgFA0BDAILIBdFDQELIAAoAgQhECAAQQA2AgQgACAQIAgQrYCAgAAiEEUNPSAAQckBNgIcIAAgCDYCFCAAIBA2AgxBACEQDIwBCyAAKAIEIQQgAEEANgIEIAAgBCAIEK2AgIAAIgRFDXYgAEHKATYCHCAAIAg2AhQgACAENgIMQQAhEAyLAQsgACgCBCEEIABBADYCBCAAIAQgCRCtgICAACIERQ10IABBywE2AhwgACAJNgIUIAAgBDYCDEEAIRAMigELIAAoAgQhBCAAQQA2AgQgACAEIAoQrYCAgAAiBEUNciAAQc0BNgIcIAAgCjYCFCAAIAQ2AgxBACEQDIkBCwJAIAstAABBUGoiEEH/AXFBCk8NACAAIBA6ACogC0EBaiEKQbYBIRAMcAsgACgCBCEEIABBADYCBCAAIAQgCxCtgICAACIERQ1wIABBzwE2AhwgACALNgIUIAAgBDYCDEEAIRAMiAELIABBADYCHCAAIAQ2AhQgAEGQs4CAADYCECAAQQg2AgwgAEEANgIAQQAhEAyHAQsgAUEVRg0/IABBADYCHCAAIAw2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDIYBCyAAQYEEOwEoIAAoAgQhECAAQgA3AwAgACAQIAxBAWoiDBCrgICAACIQRQ04IABB0wE2AhwgACAMNgIUIAAgEDYCDEEAIRAMhQELIABBADYCAAtBACEQIABBADYCHCAAIAQ2AhQgAEHYm4CAADYCECAAQQg2AgwMgwELIAAoAgQhECAAQgA3AwAgACAQIAtBAWoiCxCrgICAACIQDQFBxgEhEAxpCyAAQQI6ACgMVQsgAEHVATYCHCAAIAs2AhQgACAQNgIMQQAhEAyAAQsgEEEVRg03IABBADYCHCAAIAQ2AhQgAEGkjICAADYCECAAQRA2AgxBACEQDH8LIAAtADRBAUcNNCAAIAQgAhC8gICAACIQRQ00IBBBFUcNNSAAQdwBNgIcIAAgBDYCFCAAQdWWgIAANgIQIABBFTYCDEEAIRAMfgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQMfQtBACEQDGMLQQIhEAxiC0ENIRAMYQtBDyEQDGALQSUhEAxfC0ETIRAMXgtBFSEQDF0LQRYhEAxcC0EXIRAMWwtBGCEQDFoLQRkhEAxZC0EaIRAMWAtBGyEQDFcLQRwhEAxWC0EdIRAMVQtBHyEQDFQLQSEhEAxTC0EjIRAMUgtBxgAhEAxRC0EuIRAMUAtBLyEQDE8LQTshEAxOC0E9IRAMTQtByAAhEAxMC0HJACEQDEsLQcsAIRAMSgtBzAAhEAxJC0HOACEQDEgLQdEAIRAMRwtB1QAhEAxGC0HYACEQDEULQdkAIRAMRAtB2wAhEAxDC0HkACEQDEILQeUAIRAMQQtB8QAhEAxAC0H0ACEQDD8LQY0BIRAMPgtBlwEhEAw9C0GpASEQDDwLQawBIRAMOwtBwAEhEAw6C0G5ASEQDDkLQa8BIRAMOAtBsQEhEAw3C0GyASEQDDYLQbQBIRAMNQtBtQEhEAw0C0G6ASEQDDMLQb0BIRAMMgtBvwEhEAwxC0HBASEQDDALIABBADYCHCAAIAQ2AhQgAEHpi4CAADYCECAAQR82AgxBACEQDEgLIABB2wE2AhwgACAENgIUIABB+paAgAA2AhAgAEEVNgIMQQAhEAxHCyAAQfgANgIcIAAgDDYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMRgsgAEHRADYCHCAAIAU2AhQgAEGwl4CAADYCECAAQRU2AgxBACEQDEULIABB+QA2AhwgACABNgIUIAAgEDYCDEEAIRAMRAsgAEH4ADYCHCAAIAE2AhQgAEHKmICAADYCECAAQRU2AgxBACEQDEMLIABB5AA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAxCCyAAQdcANgIcIAAgATYCFCAAQcmXgIAANgIQIABBFTYCDEEAIRAMQQsgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMQAsgAEHCADYCHCAAIAE2AhQgAEHjmICAADYCECAAQRU2AgxBACEQDD8LIABBADYCBCAAIA8gDxCxgICAACIERQ0BIABBOjYCHCAAIAQ2AgwgACAPQQFqNgIUQQAhEAw+CyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBEUNACAAQTs2AhwgACAENgIMIAAgAUEBajYCFEEAIRAMPgsgAUEBaiEBDC0LIA9BAWohAQwtCyAAQQA2AhwgACAPNgIUIABB5JKAgAA2AhAgAEEENgIMQQAhEAw7CyAAQTY2AhwgACAENgIUIAAgAjYCDEEAIRAMOgsgAEEuNgIcIAAgDjYCFCAAIAQ2AgxBACEQDDkLIABB0AA2AhwgACABNgIUIABBkZiAgAA2AhAgAEEVNgIMQQAhEAw4CyANQQFqIQEMLAsgAEEVNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMNgsgAEEbNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNQsgAEEPNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNAsgAEELNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMMwsgAEEaNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMgsgAEELNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMQsgAEEKNgIcIAAgATYCFCAAQeSWgIAANgIQIABBFTYCDEEAIRAMMAsgAEEeNgIcIAAgATYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAMLwsgAEEANgIcIAAgEDYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMLgsgAEEENgIcIAAgATYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMLQsgAEEANgIAIAtBAWohCwtBuAEhEAwSCyAAQQA2AgAgEEEBaiEBQfUAIRAMEQsgASEBAkAgAC0AKUEFRw0AQeMAIRAMEQtB4gAhEAwQC0EAIRAgAEEANgIcIABB5JGAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAwoCyAAQQA2AgAgF0EBaiEBQcAAIRAMDgtBASEBCyAAIAE6ACwgAEEANgIAIBdBAWohAQtBKCEQDAsLIAEhAQtBOCEQDAkLAkAgASIPIAJGDQADQAJAIA8tAABBgL6AgABqLQAAIgFBAUYNACABQQJHDQMgD0EBaiEBDAQLIA9BAWoiDyACRw0AC0E+IRAMIgtBPiEQDCELIABBADoALCAPIQEMAQtBCyEQDAYLQTohEAwFCyABQQFqIQFBLSEQDAQLIAAgAToALCAAQQA2AgAgFkEBaiEBQQwhEAwDCyAAQQA2AgAgF0EBaiEBQQohEAwCCyAAQQA2AgALIABBADoALCANIQFBCSEQDAALC0EAIRAgAEEANgIcIAAgCzYCFCAAQc2QgIAANgIQIABBCTYCDAwXC0EAIRAgAEEANgIcIAAgCjYCFCAAQemKgIAANgIQIABBCTYCDAwWC0EAIRAgAEEANgIcIAAgCTYCFCAAQbeQgIAANgIQIABBCTYCDAwVC0EAIRAgAEEANgIcIAAgCDYCFCAAQZyRgIAANgIQIABBCTYCDAwUC0EAIRAgAEEANgIcIAAgATYCFCAAQc2QgIAANgIQIABBCTYCDAwTC0EAIRAgAEEANgIcIAAgATYCFCAAQemKgIAANgIQIABBCTYCDAwSC0EAIRAgAEEANgIcIAAgATYCFCAAQbeQgIAANgIQIABBCTYCDAwRC0EAIRAgAEEANgIcIAAgATYCFCAAQZyRgIAANgIQIABBCTYCDAwQC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwPC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwOC0EAIRAgAEEANgIcIAAgATYCFCAAQcCSgIAANgIQIABBCzYCDAwNC0EAIRAgAEEANgIcIAAgATYCFCAAQZWJgIAANgIQIABBCzYCDAwMC0EAIRAgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDAwLC0EAIRAgAEEANgIcIAAgATYCFCAAQfuPgIAANgIQIABBCjYCDAwKC0EAIRAgAEEANgIcIAAgATYCFCAAQfGZgIAANgIQIABBAjYCDAwJC0EAIRAgAEEANgIcIAAgATYCFCAAQcSUgIAANgIQIABBAjYCDAwIC0EAIRAgAEEANgIcIAAgATYCFCAAQfKVgIAANgIQIABBAjYCDAwHCyAAQQI2AhwgACABNgIUIABBnJqAgAA2AhAgAEEWNgIMQQAhEAwGC0EBIRAMBQtB1AAhECABIgQgAkYNBCADQQhqIAAgBCACQdjCgIAAQQoQxYCAgAAgAygCDCEEIAMoAggOAwEEAgALEMqAgIAAAAsgAEEANgIcIABBtZqAgAA2AhAgAEEXNgIMIAAgBEEBajYCFEEAIRAMAgsgAEEANgIcIAAgBDYCFCAAQcqagIAANgIQIABBCTYCDEEAIRAMAQsCQCABIgQgAkcNAEEiIRAMAQsgAEGJgICAADYCCCAAIAQ2AgRBISEQCyADQRBqJICAgIAAIBALrwEBAn8gASgCACEGAkACQCACIANGDQAgBCAGaiEEIAYgA2ogAmshByACIAZBf3MgBWoiBmohBQNAAkAgAi0AACAELQAARg0AQQIhBAwDCwJAIAYNAEEAIQQgBSECDAMLIAZBf2ohBiAEQQFqIQQgAkEBaiICIANHDQALIAchBiADIQILIABBATYCACABIAY2AgAgACACNgIEDwsgAUEANgIAIAAgBDYCACAAIAI2AgQLCgAgABDHgICAAAvyNgELfyOAgICAAEEQayIBJICAgIAAAkBBACgCoNCAgAANAEEAEMuAgIAAQYDUhIAAayICQdkASQ0AQQAhAwJAQQAoAuDTgIAAIgQNAEEAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEIakFwcUHYqtWqBXMiBDYC4NOAgABBAEEANgL004CAAEEAQQA2AsTTgIAAC0EAIAI2AszTgIAAQQBBgNSEgAA2AsjTgIAAQQBBgNSEgAA2ApjQgIAAQQAgBDYCrNCAgABBAEF/NgKo0ICAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALQYDUhIAAQXhBgNSEgABrQQ9xQQBBgNSEgABBCGpBD3EbIgNqIgRBBGogAkFIaiIFIANrIgNBAXI2AgBBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAQYDUhIAAIAVqQTg2AgQLAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFLDQACQEEAKAKI0ICAACIGQRAgAEETakFwcSAAQQtJGyICQQN2IgR2IgNBA3FFDQACQAJAIANBAXEgBHJBAXMiBUEDdCIEQbDQgIAAaiIDIARBuNCAgABqKAIAIgQoAggiAkcNAEEAIAZBfiAFd3E2AojQgIAADAELIAMgAjYCCCACIAM2AgwLIARBCGohAyAEIAVBA3QiBUEDcjYCBCAEIAVqIgQgBCgCBEEBcjYCBAwMCyACQQAoApDQgIAAIgdNDQECQCADRQ0AAkACQCADIAR0QQIgBHQiA0EAIANrcnEiA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqIgRBA3QiA0Gw0ICAAGoiBSADQbjQgIAAaigCACIDKAIIIgBHDQBBACAGQX4gBHdxIgY2AojQgIAADAELIAUgADYCCCAAIAU2AgwLIAMgAkEDcjYCBCADIARBA3QiBGogBCACayIFNgIAIAMgAmoiACAFQQFyNgIEAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQQCQAJAIAZBASAHQQN2dCIIcQ0AQQAgBiAIcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCAENgIMIAIgBDYCCCAEIAI2AgwgBCAINgIICyADQQhqIQNBACAANgKc0ICAAEEAIAU2ApDQgIAADAwLQQAoAozQgIAAIglFDQEgCUEAIAlrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqQQJ0QbjSgIAAaigCACIAKAIEQXhxIAJrIQQgACEFAkADQAJAIAUoAhAiAw0AIAVBFGooAgAiA0UNAgsgAygCBEF4cSACayIFIAQgBSAESSIFGyEEIAMgACAFGyEAIAMhBQwACwsgACgCGCEKAkAgACgCDCIIIABGDQAgACgCCCIDQQAoApjQgIAASRogCCADNgIIIAMgCDYCDAwLCwJAIABBFGoiBSgCACIDDQAgACgCECIDRQ0DIABBEGohBQsDQCAFIQsgAyIIQRRqIgUoAgAiAw0AIAhBEGohBSAIKAIQIgMNAAsgC0EANgIADAoLQX8hAiAAQb9/Sw0AIABBE2oiA0FwcSECQQAoAozQgIAAIgdFDQBBACELAkAgAkGAAkkNAEEfIQsgAkH///8HSw0AIANBCHYiAyADQYD+P2pBEHZBCHEiA3QiBCAEQYDgH2pBEHZBBHEiBHQiBSAFQYCAD2pBEHZBAnEiBXRBD3YgAyAEciAFcmsiA0EBdCACIANBFWp2QQFxckEcaiELC0EAIAJrIQQCQAJAAkACQCALQQJ0QbjSgIAAaigCACIFDQBBACEDQQAhCAwBC0EAIQMgAkEAQRkgC0EBdmsgC0EfRht0IQBBACEIA0ACQCAFKAIEQXhxIAJrIgYgBE8NACAGIQQgBSEIIAYNAEEAIQQgBSEIIAUhAwwDCyADIAVBFGooAgAiBiAGIAUgAEEddkEEcWpBEGooAgAiBUYbIAMgBhshAyAAQQF0IQAgBQ0ACwsCQCADIAhyDQBBACEIQQIgC3QiA0EAIANrciAHcSIDRQ0DIANBACADa3FBf2oiAyADQQx2QRBxIgN2IgVBBXZBCHEiACADciAFIAB2IgNBAnZBBHEiBXIgAyAFdiIDQQF2QQJxIgVyIAMgBXYiA0EBdkEBcSIFciADIAV2akECdEG40oCAAGooAgAhAwsgA0UNAQsDQCADKAIEQXhxIAJrIgYgBEkhAAJAIAMoAhAiBQ0AIANBFGooAgAhBQsgBiAEIAAbIQQgAyAIIAAbIQggBSEDIAUNAAsLIAhFDQAgBEEAKAKQ0ICAACACa08NACAIKAIYIQsCQCAIKAIMIgAgCEYNACAIKAIIIgNBACgCmNCAgABJGiAAIAM2AgggAyAANgIMDAkLAkAgCEEUaiIFKAIAIgMNACAIKAIQIgNFDQMgCEEQaiEFCwNAIAUhBiADIgBBFGoiBSgCACIDDQAgAEEQaiEFIAAoAhAiAw0ACyAGQQA2AgAMCAsCQEEAKAKQ0ICAACIDIAJJDQBBACgCnNCAgAAhBAJAAkAgAyACayIFQRBJDQAgBCACaiIAIAVBAXI2AgRBACAFNgKQ0ICAAEEAIAA2ApzQgIAAIAQgA2ogBTYCACAEIAJBA3I2AgQMAQsgBCADQQNyNgIEIAQgA2oiAyADKAIEQQFyNgIEQQBBADYCnNCAgABBAEEANgKQ0ICAAAsgBEEIaiEDDAoLAkBBACgClNCAgAAiACACTQ0AQQAoAqDQgIAAIgMgAmoiBCAAIAJrIgVBAXI2AgRBACAFNgKU0ICAAEEAIAQ2AqDQgIAAIAMgAkEDcjYCBCADQQhqIQMMCgsCQAJAQQAoAuDTgIAARQ0AQQAoAujTgIAAIQQMAQtBAEJ/NwLs04CAAEEAQoCAhICAgMAANwLk04CAAEEAIAFBDGpBcHFB2KrVqgVzNgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgABBgIAEIQQLQQAhAwJAIAQgAkHHAGoiB2oiBkEAIARrIgtxIgggAksNAEEAQTA2AvjTgIAADAoLAkBBACgCwNOAgAAiA0UNAAJAQQAoArjTgIAAIgQgCGoiBSAETQ0AIAUgA00NAQtBACEDQQBBMDYC+NOAgAAMCgtBAC0AxNOAgABBBHENBAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQAJAIAMoAgAiBSAESw0AIAUgAygCBGogBEsNAwsgAygCCCIDDQALC0EAEMuAgIAAIgBBf0YNBSAIIQYCQEEAKALk04CAACIDQX9qIgQgAHFFDQAgCCAAayAEIABqQQAgA2txaiEGCyAGIAJNDQUgBkH+////B0sNBQJAQQAoAsDTgIAAIgNFDQBBACgCuNOAgAAiBCAGaiIFIARNDQYgBSADSw0GCyAGEMuAgIAAIgMgAEcNAQwHCyAGIABrIAtxIgZB/v///wdLDQQgBhDLgICAACIAIAMoAgAgAygCBGpGDQMgACEDCwJAIANBf0YNACACQcgAaiAGTQ0AAkAgByAGa0EAKALo04CAACIEakEAIARrcSIEQf7///8HTQ0AIAMhAAwHCwJAIAQQy4CAgABBf0YNACAEIAZqIQYgAyEADAcLQQAgBmsQy4CAgAAaDAQLIAMhACADQX9HDQUMAwtBACEIDAcLQQAhAAwFCyAAQX9HDQILQQBBACgCxNOAgABBBHI2AsTTgIAACyAIQf7///8HSw0BIAgQy4CAgAAhAEEAEMuAgIAAIQMgAEF/Rg0BIANBf0YNASAAIANPDQEgAyAAayIGIAJBOGpNDQELQQBBACgCuNOAgAAgBmoiAzYCuNOAgAACQCADQQAoArzTgIAATQ0AQQAgAzYCvNOAgAALAkACQAJAAkBBACgCoNCAgAAiBEUNAEHI04CAACEDA0AgACADKAIAIgUgAygCBCIIakYNAiADKAIIIgMNAAwDCwsCQAJAQQAoApjQgIAAIgNFDQAgACADTw0BC0EAIAA2ApjQgIAAC0EAIQNBACAGNgLM04CAAEEAIAA2AsjTgIAAQQBBfzYCqNCAgABBAEEAKALg04CAADYCrNCAgABBAEEANgLU04CAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgQgBkFIaiIFIANrIgNBAXI2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAIAAgBWpBODYCBAwCCyADLQAMQQhxDQAgBCAFSQ0AIAQgAE8NACAEQXggBGtBD3FBACAEQQhqQQ9xGyIFaiIAQQAoApTQgIAAIAZqIgsgBWsiBUEBcjYCBCADIAggBmo2AgRBAEEAKALw04CAADYCpNCAgABBACAFNgKU0ICAAEEAIAA2AqDQgIAAIAQgC2pBODYCBAwBCwJAIABBACgCmNCAgAAiCE8NAEEAIAA2ApjQgIAAIAAhCAsgACAGaiEFQcjTgIAAIQMCQAJAAkACQAJAAkACQANAIAMoAgAgBUYNASADKAIIIgMNAAwCCwsgAy0ADEEIcUUNAQtByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiIFIARLDQMLIAMoAgghAwwACwsgAyAANgIAIAMgAygCBCAGajYCBCAAQXggAGtBD3FBACAAQQhqQQ9xG2oiCyACQQNyNgIEIAVBeCAFa0EPcUEAIAVBCGpBD3EbaiIGIAsgAmoiAmshAwJAIAYgBEcNAEEAIAI2AqDQgIAAQQBBACgClNCAgAAgA2oiAzYClNCAgAAgAiADQQFyNgIEDAMLAkAgBkEAKAKc0ICAAEcNAEEAIAI2ApzQgIAAQQBBACgCkNCAgAAgA2oiAzYCkNCAgAAgAiADQQFyNgIEIAIgA2ogAzYCAAwDCwJAIAYoAgQiBEEDcUEBRw0AIARBeHEhBwJAAkAgBEH/AUsNACAGKAIIIgUgBEEDdiIIQQN0QbDQgIAAaiIARhoCQCAGKAIMIgQgBUcNAEEAQQAoAojQgIAAQX4gCHdxNgKI0ICAAAwCCyAEIABGGiAEIAU2AgggBSAENgIMDAELIAYoAhghCQJAAkAgBigCDCIAIAZGDQAgBigCCCIEIAhJGiAAIAQ2AgggBCAANgIMDAELAkAgBkEUaiIEKAIAIgUNACAGQRBqIgQoAgAiBQ0AQQAhAAwBCwNAIAQhCCAFIgBBFGoiBCgCACIFDQAgAEEQaiEEIAAoAhAiBQ0ACyAIQQA2AgALIAlFDQACQAJAIAYgBigCHCIFQQJ0QbjSgIAAaiIEKAIARw0AIAQgADYCACAADQFBAEEAKAKM0ICAAEF+IAV3cTYCjNCAgAAMAgsgCUEQQRQgCSgCECAGRhtqIAA2AgAgAEUNAQsgACAJNgIYAkAgBigCECIERQ0AIAAgBDYCECAEIAA2AhgLIAYoAhQiBEUNACAAQRRqIAQ2AgAgBCAANgIYCyAHIANqIQMgBiAHaiIGKAIEIQQLIAYgBEF+cTYCBCACIANqIAM2AgAgAiADQQFyNgIEAkAgA0H/AUsNACADQXhxQbDQgIAAaiEEAkACQEEAKAKI0ICAACIFQQEgA0EDdnQiA3ENAEEAIAUgA3I2AojQgIAAIAQhAwwBCyAEKAIIIQMLIAMgAjYCDCAEIAI2AgggAiAENgIMIAIgAzYCCAwDC0EfIQQCQCADQf///wdLDQAgA0EIdiIEIARBgP4/akEQdkEIcSIEdCIFIAVBgOAfakEQdkEEcSIFdCIAIABBgIAPakEQdkECcSIAdEEPdiAEIAVyIAByayIEQQF0IAMgBEEVanZBAXFyQRxqIQQLIAIgBDYCHCACQgA3AhAgBEECdEG40oCAAGohBQJAQQAoAozQgIAAIgBBASAEdCIIcQ0AIAUgAjYCAEEAIAAgCHI2AozQgIAAIAIgBTYCGCACIAI2AgggAiACNgIMDAMLIANBAEEZIARBAXZrIARBH0YbdCEEIAUoAgAhAANAIAAiBSgCBEF4cSADRg0CIARBHXYhACAEQQF0IQQgBSAAQQRxakEQaiIIKAIAIgANAAsgCCACNgIAIAIgBTYCGCACIAI2AgwgAiACNgIIDAILIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgsgBkFIaiIIIANrIgNBAXI2AgQgACAIakE4NgIEIAQgBUE3IAVrQQ9xQQAgBUFJakEPcRtqQUFqIgggCCAEQRBqSRsiCEEjNgIEQQBBACgC8NOAgAA2AqTQgIAAQQAgAzYClNCAgABBACALNgKg0ICAACAIQRBqQQApAtDTgIAANwIAIAhBACkCyNOAgAA3AghBACAIQQhqNgLQ04CAAEEAIAY2AszTgIAAQQAgADYCyNOAgABBAEEANgLU04CAACAIQSRqIQMDQCADQQc2AgAgA0EEaiIDIAVJDQALIAggBEYNAyAIIAgoAgRBfnE2AgQgCCAIIARrIgA2AgAgBCAAQQFyNgIEAkAgAEH/AUsNACAAQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgAEEDdnQiAHENAEEAIAUgAHI2AojQgIAAIAMhBQwBCyADKAIIIQULIAUgBDYCDCADIAQ2AgggBCADNgIMIAQgBTYCCAwEC0EfIQMCQCAAQf///wdLDQAgAEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCIIIAhBgIAPakEQdkECcSIIdEEPdiADIAVyIAhyayIDQQF0IAAgA0EVanZBAXFyQRxqIQMLIAQgAzYCHCAEQgA3AhAgA0ECdEG40oCAAGohBQJAQQAoAozQgIAAIghBASADdCIGcQ0AIAUgBDYCAEEAIAggBnI2AozQgIAAIAQgBTYCGCAEIAQ2AgggBCAENgIMDAQLIABBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhCANAIAgiBSgCBEF4cSAARg0DIANBHXYhCCADQQF0IQMgBSAIQQRxakEQaiIGKAIAIggNAAsgBiAENgIAIAQgBTYCGCAEIAQ2AgwgBCAENgIIDAMLIAUoAggiAyACNgIMIAUgAjYCCCACQQA2AhggAiAFNgIMIAIgAzYCCAsgC0EIaiEDDAULIAUoAggiAyAENgIMIAUgBDYCCCAEQQA2AhggBCAFNgIMIAQgAzYCCAtBACgClNCAgAAiAyACTQ0AQQAoAqDQgIAAIgQgAmoiBSADIAJrIgNBAXI2AgRBACADNgKU0ICAAEEAIAU2AqDQgIAAIAQgAkEDcjYCBCAEQQhqIQMMAwtBACEDQQBBMDYC+NOAgAAMAgsCQCALRQ0AAkACQCAIIAgoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAA2AgAgAA0BQQAgB0F+IAV3cSIHNgKM0ICAAAwCCyALQRBBFCALKAIQIAhGG2ogADYCACAARQ0BCyAAIAs2AhgCQCAIKAIQIgNFDQAgACADNgIQIAMgADYCGAsgCEEUaigCACIDRQ0AIABBFGogAzYCACADIAA2AhgLAkACQCAEQQ9LDQAgCCAEIAJqIgNBA3I2AgQgCCADaiIDIAMoAgRBAXI2AgQMAQsgCCACaiIAIARBAXI2AgQgCCACQQNyNgIEIAAgBGogBDYCAAJAIARB/wFLDQAgBEF4cUGw0ICAAGohAwJAAkBBACgCiNCAgAAiBUEBIARBA3Z0IgRxDQBBACAFIARyNgKI0ICAACADIQQMAQsgAygCCCEECyAEIAA2AgwgAyAANgIIIAAgAzYCDCAAIAQ2AggMAQtBHyEDAkAgBEH///8HSw0AIARBCHYiAyADQYD+P2pBEHZBCHEiA3QiBSAFQYDgH2pBEHZBBHEiBXQiAiACQYCAD2pBEHZBAnEiAnRBD3YgAyAFciACcmsiA0EBdCAEIANBFWp2QQFxckEcaiEDCyAAIAM2AhwgAEIANwIQIANBAnRBuNKAgABqIQUCQCAHQQEgA3QiAnENACAFIAA2AgBBACAHIAJyNgKM0ICAACAAIAU2AhggACAANgIIIAAgADYCDAwBCyAEQQBBGSADQQF2ayADQR9GG3QhAyAFKAIAIQICQANAIAIiBSgCBEF4cSAERg0BIANBHXYhAiADQQF0IQMgBSACQQRxakEQaiIGKAIAIgINAAsgBiAANgIAIAAgBTYCGCAAIAA2AgwgACAANgIIDAELIAUoAggiAyAANgIMIAUgADYCCCAAQQA2AhggACAFNgIMIAAgAzYCCAsgCEEIaiEDDAELAkAgCkUNAAJAAkAgACAAKAIcIgVBAnRBuNKAgABqIgMoAgBHDQAgAyAINgIAIAgNAUEAIAlBfiAFd3E2AozQgIAADAILIApBEEEUIAooAhAgAEYbaiAINgIAIAhFDQELIAggCjYCGAJAIAAoAhAiA0UNACAIIAM2AhAgAyAINgIYCyAAQRRqKAIAIgNFDQAgCEEUaiADNgIAIAMgCDYCGAsCQAJAIARBD0sNACAAIAQgAmoiA0EDcjYCBCAAIANqIgMgAygCBEEBcjYCBAwBCyAAIAJqIgUgBEEBcjYCBCAAIAJBA3I2AgQgBSAEaiAENgIAAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQMCQAJAQQEgB0EDdnQiCCAGcQ0AQQAgCCAGcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCADNgIMIAIgAzYCCCADIAI2AgwgAyAINgIIC0EAIAU2ApzQgIAAQQAgBDYCkNCAgAALIABBCGohAwsgAUEQaiSAgICAACADCwoAIAAQyYCAgAAL4g0BB38CQCAARQ0AIABBeGoiASAAQXxqKAIAIgJBeHEiAGohAwJAIAJBAXENACACQQNxRQ0BIAEgASgCACICayIBQQAoApjQgIAAIgRJDQEgAiAAaiEAAkAgAUEAKAKc0ICAAEYNAAJAIAJB/wFLDQAgASgCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgASgCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAwsgAiAGRhogAiAENgIIIAQgAjYCDAwCCyABKAIYIQcCQAJAIAEoAgwiBiABRg0AIAEoAggiAiAESRogBiACNgIIIAIgBjYCDAwBCwJAIAFBFGoiAigCACIEDQAgAUEQaiICKAIAIgQNAEEAIQYMAQsDQCACIQUgBCIGQRRqIgIoAgAiBA0AIAZBEGohAiAGKAIQIgQNAAsgBUEANgIACyAHRQ0BAkACQCABIAEoAhwiBEECdEG40oCAAGoiAigCAEcNACACIAY2AgAgBg0BQQBBACgCjNCAgABBfiAEd3E2AozQgIAADAMLIAdBEEEUIAcoAhAgAUYbaiAGNgIAIAZFDQILIAYgBzYCGAJAIAEoAhAiAkUNACAGIAI2AhAgAiAGNgIYCyABKAIUIgJFDQEgBkEUaiACNgIAIAIgBjYCGAwBCyADKAIEIgJBA3FBA0cNACADIAJBfnE2AgRBACAANgKQ0ICAACABIABqIAA2AgAgASAAQQFyNgIEDwsgASADTw0AIAMoAgQiAkEBcUUNAAJAAkAgAkECcQ0AAkAgA0EAKAKg0ICAAEcNAEEAIAE2AqDQgIAAQQBBACgClNCAgAAgAGoiADYClNCAgAAgASAAQQFyNgIEIAFBACgCnNCAgABHDQNBAEEANgKQ0ICAAEEAQQA2ApzQgIAADwsCQCADQQAoApzQgIAARw0AQQAgATYCnNCAgABBAEEAKAKQ0ICAACAAaiIANgKQ0ICAACABIABBAXI2AgQgASAAaiAANgIADwsgAkF4cSAAaiEAAkACQCACQf8BSw0AIAMoAggiBCACQQN2IgVBA3RBsNCAgABqIgZGGgJAIAMoAgwiAiAERw0AQQBBACgCiNCAgABBfiAFd3E2AojQgIAADAILIAIgBkYaIAIgBDYCCCAEIAI2AgwMAQsgAygCGCEHAkACQCADKAIMIgYgA0YNACADKAIIIgJBACgCmNCAgABJGiAGIAI2AgggAiAGNgIMDAELAkAgA0EUaiICKAIAIgQNACADQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQACQAJAIAMgAygCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAgsgB0EQQRQgBygCECADRhtqIAY2AgAgBkUNAQsgBiAHNgIYAkAgAygCECICRQ0AIAYgAjYCECACIAY2AhgLIAMoAhQiAkUNACAGQRRqIAI2AgAgAiAGNgIYCyABIABqIAA2AgAgASAAQQFyNgIEIAFBACgCnNCAgABHDQFBACAANgKQ0ICAAA8LIAMgAkF+cTYCBCABIABqIAA2AgAgASAAQQFyNgIECwJAIABB/wFLDQAgAEF4cUGw0ICAAGohAgJAAkBBACgCiNCAgAAiBEEBIABBA3Z0IgBxDQBBACAEIAByNgKI0ICAACACIQAMAQsgAigCCCEACyAAIAE2AgwgAiABNgIIIAEgAjYCDCABIAA2AggPC0EfIQICQCAAQf///wdLDQAgAEEIdiICIAJBgP4/akEQdkEIcSICdCIEIARBgOAfakEQdkEEcSIEdCIGIAZBgIAPakEQdkECcSIGdEEPdiACIARyIAZyayICQQF0IAAgAkEVanZBAXFyQRxqIQILIAEgAjYCHCABQgA3AhAgAkECdEG40oCAAGohBAJAAkBBACgCjNCAgAAiBkEBIAJ0IgNxDQAgBCABNgIAQQAgBiADcjYCjNCAgAAgASAENgIYIAEgATYCCCABIAE2AgwMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgBCgCACEGAkADQCAGIgQoAgRBeHEgAEYNASACQR12IQYgAkEBdCECIAQgBkEEcWpBEGoiAygCACIGDQALIAMgATYCACABIAQ2AhggASABNgIMIAEgATYCCAwBCyAEKAIIIgAgATYCDCAEIAE2AgggAUEANgIYIAEgBDYCDCABIAA2AggLQQBBACgCqNCAgABBf2oiAUF/IAEbNgKo0ICAAAsLBAAAAAtOAAJAIAANAD8AQRB0DwsCQCAAQf//A3ENACAAQX9MDQACQCAAQRB2QAAiAEF/Rw0AQQBBMDYC+NOAgABBfw8LIABBEHQPCxDKgICAAAAL8gICA38BfgJAIAJFDQAgACABOgAAIAIgAGoiA0F/aiABOgAAIAJBA0kNACAAIAE6AAIgACABOgABIANBfWogAToAACADQX5qIAE6AAAgAkEHSQ0AIAAgAToAAyADQXxqIAE6AAAgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIFayICQSBJDQAgAa1CgYCAgBB+IQYgAyAFaiEBA0AgASAGNwMYIAEgBjcDECABIAY3AwggASAGNwMAIAFBIGohASACQWBqIgJBH0sNAAsLIAALC45IAQBBgAgLhkgBAAAAAgAAAAMAAAAAAAAAAAAAAAQAAAAFAAAAAAAAAAAAAAAGAAAABwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEludmFsaWQgY2hhciBpbiB1cmwgcXVlcnkAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9ib2R5AENvbnRlbnQtTGVuZ3RoIG92ZXJmbG93AENodW5rIHNpemUgb3ZlcmZsb3cAUmVzcG9uc2Ugb3ZlcmZsb3cASW52YWxpZCBtZXRob2QgZm9yIEhUVFAveC54IHJlcXVlc3QASW52YWxpZCBtZXRob2QgZm9yIFJUU1AveC54IHJlcXVlc3QARXhwZWN0ZWQgU09VUkNFIG1ldGhvZCBmb3IgSUNFL3gueCByZXF1ZXN0AEludmFsaWQgY2hhciBpbiB1cmwgZnJhZ21lbnQgc3RhcnQARXhwZWN0ZWQgZG90AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fc3RhdHVzAEludmFsaWQgcmVzcG9uc2Ugc3RhdHVzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABEdXBsaWNhdGUgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyIGluIHVybCBwYXRoAENvbnRlbnQtTGVuZ3RoIGNhbid0IGJlIHByZXNlbnQgd2l0aCBUcmFuc2Zlci1FbmNvZGluZwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBzaXplAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX3ZhbHVlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgdmFsdWUATWlzc2luZyBleHBlY3RlZCBMRiBhZnRlciBoZWFkZXIgdmFsdWUASW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fbmFtZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIG5hbWUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAXhMAACYTAAAwEAAA8BcAAJ0TAAAVEgAAORcAAPASAAAKEAAAdRIAAK0SAACCEwAATxQAAH8QAACgFQAAIxQAAIkSAACLFAAATRUAANQRAADPFAAAEBgAAMkWAADcFgAAwREAAOAXAAC7FAAAdBQAAHwVAADlFAAACBcAAB8QAABlFQAAoxQAACgVAAACFQAAmRUAACwQAACLGQAATw8AANQOAABqEAAAzhAAAAIXAACJDgAAbhMAABwTAABmFAAAVhcAAMETAADNEwAAbBMAAGgXAABmFwAAXxcAACITAADODwAAaQ4AANgOAABjFgAAyxMAAKoOAAAoFwAAJhcAAMUTAABdFgAA6BEAAGcTAABlEwAA8hYAAHMTAAAdFwAA+RYAAPMRAADPDgAAzhUAAAwSAACzEQAApREAAGEQAAAyFwAAuxMAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIDAgICAgIAAAICAAICAAICAgICAgICAgIABAAAAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAACAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbG9zZWVlcC1hbGl2ZQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AAAAAAAAAAAAAAAAAAAByYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AAAAAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQIAAQMAAAAAAAAAAAAAAAAAAAAAAAAEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAQAAAgAAAAAAAAAAAAAAAAAAAAAAAAMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='\n","module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCrLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AcsBygG4AckBuQHIAboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBANwBC0EAIRAMxgELQQ4hEAzFAQtBDSEQDMQBC0EPIRAMwwELQRAhEAzCAQtBEyEQDMEBC0EUIRAMwAELQRUhEAy/AQtBFiEQDL4BC0EXIRAMvQELQRghEAy8AQtBGSEQDLsBC0EaIRAMugELQRshEAy5AQtBHCEQDLgBC0EIIRAMtwELQR0hEAy2AQtBICEQDLUBC0EfIRAMtAELQQchEAyzAQtBISEQDLIBC0EiIRAMsQELQR4hEAywAQtBIyEQDK8BC0ESIRAMrgELQREhEAytAQtBJCEQDKwBC0ElIRAMqwELQSYhEAyqAQtBJyEQDKkBC0HDASEQDKgBC0EpIRAMpwELQSshEAymAQtBLCEQDKUBC0EtIRAMpAELQS4hEAyjAQtBLyEQDKIBC0HEASEQDKEBC0EwIRAMoAELQTQhEAyfAQtBDCEQDJ4BC0ExIRAMnQELQTIhEAycAQtBMyEQDJsBC0E5IRAMmgELQTUhEAyZAQtBxQEhEAyYAQtBCyEQDJcBC0E6IRAMlgELQTYhEAyVAQtBCiEQDJQBC0E3IRAMkwELQTghEAySAQtBPCEQDJEBC0E7IRAMkAELQT0hEAyPAQtBCSEQDI4BC0EoIRAMjQELQT4hEAyMAQtBPyEQDIsBC0HAACEQDIoBC0HBACEQDIkBC0HCACEQDIgBC0HDACEQDIcBC0HEACEQDIYBC0HFACEQDIUBC0HGACEQDIQBC0EqIRAMgwELQccAIRAMggELQcgAIRAMgQELQckAIRAMgAELQcoAIRAMfwtBywAhEAx+C0HNACEQDH0LQcwAIRAMfAtBzgAhEAx7C0HPACEQDHoLQdAAIRAMeQtB0QAhEAx4C0HSACEQDHcLQdMAIRAMdgtB1AAhEAx1C0HWACEQDHQLQdUAIRAMcwtBBiEQDHILQdcAIRAMcQtBBSEQDHALQdgAIRAMbwtBBCEQDG4LQdkAIRAMbQtB2gAhEAxsC0HbACEQDGsLQdwAIRAMagtBAyEQDGkLQd0AIRAMaAtB3gAhEAxnC0HfACEQDGYLQeEAIRAMZQtB4AAhEAxkC0HiACEQDGMLQeMAIRAMYgtBAiEQDGELQeQAIRAMYAtB5QAhEAxfC0HmACEQDF4LQecAIRAMXQtB6AAhEAxcC0HpACEQDFsLQeoAIRAMWgtB6wAhEAxZC0HsACEQDFgLQe0AIRAMVwtB7gAhEAxWC0HvACEQDFULQfAAIRAMVAtB8QAhEAxTC0HyACEQDFILQfMAIRAMUQtB9AAhEAxQC0H1ACEQDE8LQfYAIRAMTgtB9wAhEAxNC0H4ACEQDEwLQfkAIRAMSwtB+gAhEAxKC0H7ACEQDEkLQfwAIRAMSAtB/QAhEAxHC0H+ACEQDEYLQf8AIRAMRQtBgAEhEAxEC0GBASEQDEMLQYIBIRAMQgtBgwEhEAxBC0GEASEQDEALQYUBIRAMPwtBhgEhEAw+C0GHASEQDD0LQYgBIRAMPAtBiQEhEAw7C0GKASEQDDoLQYsBIRAMOQtBjAEhEAw4C0GNASEQDDcLQY4BIRAMNgtBjwEhEAw1C0GQASEQDDQLQZEBIRAMMwtBkgEhEAwyC0GTASEQDDELQZQBIRAMMAtBlQEhEAwvC0GWASEQDC4LQZcBIRAMLQtBmAEhEAwsC0GZASEQDCsLQZoBIRAMKgtBmwEhEAwpC0GcASEQDCgLQZ0BIRAMJwtBngEhEAwmC0GfASEQDCULQaABIRAMJAtBoQEhEAwjC0GiASEQDCILQaMBIRAMIQtBpAEhEAwgC0GlASEQDB8LQaYBIRAMHgtBpwEhEAwdC0GoASEQDBwLQakBIRAMGwtBqgEhEAwaC0GrASEQDBkLQawBIRAMGAtBrQEhEAwXC0GuASEQDBYLQQEhEAwVC0GvASEQDBQLQbABIRAMEwtBsQEhEAwSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB4fICEjJSg/QEFERUZHSElKS0xNT1BRUlPeA1dZW1xdYGJlZmdoaWprbG1vcHFyc3R1dnd4eXp7fH1+gAGCAYUBhgGHAYkBiwGMAY0BjgGPAZABkQGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwG4AbkBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgHHAcgByQHKAcsBzAHNAc4BzwHQAdEB0gHTAdQB1QHWAdcB2AHZAdoB2wHcAd0B3gHgAeEB4gHjAeQB5QHmAecB6AHpAeoB6wHsAe0B7gHvAfAB8QHyAfMBmQKkArAC/gL+AgsgASIEIAJHDfMBQd0BIRAM/wMLIAEiECACRw3dAUHDASEQDP4DCyABIgEgAkcNkAFB9wAhEAz9AwsgASIBIAJHDYYBQe8AIRAM/AMLIAEiASACRw1/QeoAIRAM+wMLIAEiASACRw17QegAIRAM+gMLIAEiASACRw14QeYAIRAM+QMLIAEiASACRw0aQRghEAz4AwsgASIBIAJHDRRBEiEQDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg0AIABBi4CAgAA2AgggACABNgIEIAEhAUEHIRAMxAMLQRkhEAzcAwsgAUEBaiEBDAILAkAgASIUIAJHDQBBGiEQDNsDCyAUIQECQCAULQAAQXNqDhTdAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAgDuAgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQM2gMLAkAgAS0AACIQQTtGDQAgEEENRw3oASABQQFqIQEM5QILIAFBAWohAQtBIiEQDL8DCwJAIAEiECACRw0AQRwhEAzYAwtCACERIBAhASAQLQAAQVBqDjfnAeYBAQIDBAUGBwgAAAAAAAAACQoLDA0OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPEBESExQAC0EeIRAMvQMLQgIhEQzlAQtCAyERDOQBC0IEIREM4wELQgUhEQziAQtCBiERDOEBC0IHIREM4AELQgghEQzfAQtCCSERDN4BC0IKIREM3QELQgshEQzcAQtCDCERDNsBC0INIREM2gELQg4hEQzZAQtCDyERDNgBC0IKIREM1wELQgshEQzWAQtCDCERDNUBC0INIREM1AELQg4hEQzTAQtCDyERDNIBC0IAIRECQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAtAABBUGoON+UB5AEAAQIDBAUGB+YB5gHmAeYB5gHmAeYBCAkKCwwN5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAQ4PEBESE+YBC0ICIREM5AELQgMhEQzjAQtCBCERDOIBC0IFIREM4QELQgYhEQzgAQtCByERDN8BC0IIIREM3gELQgkhEQzdAQtCCiERDNwBC0ILIREM2wELQgwhEQzaAQtCDSERDNkBC0IOIREM2AELQg8hEQzXAQtCCiERDNYBC0ILIREM1QELQgwhEQzUAQtCDSERDNMBC0IOIREM0gELQg8hEQzRAQsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3SAUEfIRAMwAMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQSQhEAynAwtBICEQDL8DCyAAIAEiECACEL6AgIAAQX9qDgW2AQDFAgHRAdIBC0ERIRAMpAMLIABBAToALyAQIQEMuwMLIAEiASACRw3SAUEkIRAMuwMLIAEiDSACRw0eQcYAIRAMugMLIAAgASIBIAIQsoCAgAAiEA3UASABIQEMtQELIAEiECACRw0mQdAAIRAMuAMLAkAgASIBIAJHDQBBKCEQDLgDCyAAQQA2AgQgAEGMgICAADYCCCAAIAEgARCxgICAACIQDdMBIAEhAQzYAQsCQCABIhAgAkcNAEEpIRAMtwMLIBAtAAAiAUEgRg0UIAFBCUcN0wEgEEEBaiEBDBULAkAgASIBIAJGDQAgAUEBaiEBDBcLQSohEAy1AwsCQCABIhAgAkcNAEErIRAMtQMLAkAgEC0AACIBQQlGDQAgAUEgRw3VAQsgAC0ALEEIRg3TASAQIQEMkQMLAkAgASIBIAJHDQBBLCEQDLQDCyABLQAAQQpHDdUBIAFBAWohAQzJAgsgASIOIAJHDdUBQS8hEAyyAwsDQAJAIAEtAAAiEEEgRg0AAkAgEEF2ag4EANwB3AEA2gELIAEhAQzgAQsgAUEBaiIBIAJHDQALQTEhEAyxAwtBMiEQIAEiFCACRg2wAyACIBRrIAAoAgAiAWohFSAUIAFrQQNqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB8LuAgABqLQAARw0BAkAgAUEDRw0AQQYhAQyWAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMsQMLIABBADYCACAUIQEM2QELQTMhECABIhQgAkYNrwMgAiAUayAAKAIAIgFqIRUgFCABa0EIaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfS7gIAAai0AAEcNAQJAIAFBCEcNAEEFIQEMlQMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLADCyAAQQA2AgAgFCEBDNgBC0E0IRAgASIUIAJGDa4DIAIgFGsgACgCACIBaiEVIBQgAWtBBWohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUHQwoCAAGotAABHDQECQCABQQVHDQBBByEBDJQDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAyvAwsgAEEANgIAIBQhAQzXAQsCQCABIgEgAkYNAANAAkAgAS0AAEGAvoCAAGotAAAiEEEBRg0AIBBBAkYNCiABIQEM3QELIAFBAWoiASACRw0AC0EwIRAMrgMLQTAhEAytAwsCQCABIgEgAkYNAANAAkAgAS0AACIQQSBGDQAgEEF2ag4E2QHaAdoB2QHaAQsgAUEBaiIBIAJHDQALQTghEAytAwtBOCEQDKwDCwNAAkAgAS0AACIQQSBGDQAgEEEJRw0DCyABQQFqIgEgAkcNAAtBPCEQDKsDCwNAAkAgAS0AACIQQSBGDQACQAJAIBBBdmoOBNoBAQHaAQALIBBBLEYN2wELIAEhAQwECyABQQFqIgEgAkcNAAtBPyEQDKoDCyABIQEM2wELQcAAIRAgASIUIAJGDagDIAIgFGsgACgCACIBaiEWIBQgAWtBBmohFwJAA0AgFC0AAEEgciABQYDAgIAAai0AAEcNASABQQZGDY4DIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADKkDCyAAQQA2AgAgFCEBC0E2IRAMjgMLAkAgASIPIAJHDQBBwQAhEAynAwsgAEGMgICAADYCCCAAIA82AgQgDyEBIAAtACxBf2oOBM0B1QHXAdkBhwMLIAFBAWohAQzMAQsCQCABIgEgAkYNAANAAkAgAS0AACIQQSByIBAgEEG/f2pB/wFxQRpJG0H/AXEiEEEJRg0AIBBBIEYNAAJAAkACQAJAIBBBnX9qDhMAAwMDAwMDAwEDAwMDAwMDAwMCAwsgAUEBaiEBQTEhEAyRAwsgAUEBaiEBQTIhEAyQAwsgAUEBaiEBQTMhEAyPAwsgASEBDNABCyABQQFqIgEgAkcNAAtBNSEQDKUDC0E1IRAMpAMLAkAgASIBIAJGDQADQAJAIAEtAABBgLyAgABqLQAAQQFGDQAgASEBDNMBCyABQQFqIgEgAkcNAAtBPSEQDKQDC0E9IRAMowMLIAAgASIBIAIQsICAgAAiEA3WASABIQEMAQsgEEEBaiEBC0E8IRAMhwMLAkAgASIBIAJHDQBBwgAhEAygAwsCQANAAkAgAS0AAEF3ag4YAAL+Av4ChAP+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gIA/gILIAFBAWoiASACRw0AC0HCACEQDKADCyABQQFqIQEgAC0ALUEBcUUNvQEgASEBC0EsIRAMhQMLIAEiASACRw3TAUHEACEQDJ0DCwNAAkAgAS0AAEGQwICAAGotAABBAUYNACABIQEMtwILIAFBAWoiASACRw0AC0HFACEQDJwDCyANLQAAIhBBIEYNswEgEEE6Rw2BAyAAKAIEIQEgAEEANgIEIAAgASANEK+AgIAAIgEN0AEgDUEBaiEBDLMCC0HHACEQIAEiDSACRg2aAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQZDCgIAAai0AAEcNgAMgAUEFRg30AiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyaAwtByAAhECABIg0gAkYNmQMgAiANayAAKAIAIgFqIRYgDSABa0EJaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGWwoCAAGotAABHDf8CAkAgAUEJRw0AQQIhAQz1AgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmQMLAkAgASINIAJHDQBByQAhEAyZAwsCQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZJ/ag4HAIADgAOAA4ADgAMBgAMLIA1BAWohAUE+IRAMgAMLIA1BAWohAUE/IRAM/wILQcoAIRAgASINIAJGDZcDIAIgDWsgACgCACIBaiEWIA0gAWtBAWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBoMKAgABqLQAARw39AiABQQFGDfACIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJcDC0HLACEQIAEiDSACRg2WAyACIA1rIAAoAgAiAWohFiANIAFrQQ5qIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaLCgIAAai0AAEcN/AIgAUEORg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyWAwtBzAAhECABIg0gAkYNlQMgAiANayAAKAIAIgFqIRYgDSABa0EPaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUHAwoCAAGotAABHDfsCAkAgAUEPRw0AQQMhAQzxAgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlQMLQc0AIRAgASINIAJGDZQDIAIgDWsgACgCACIBaiEWIA0gAWtBBWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw36AgJAIAFBBUcNAEEEIQEM8AILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJQDCwJAIAEiDSACRw0AQc4AIRAMlAMLAkACQAJAAkAgDS0AACIBQSByIAEgAUG/f2pB/wFxQRpJG0H/AXFBnX9qDhMA/QL9Av0C/QL9Av0C/QL9Av0C/QL9Av0CAf0C/QL9AgID/QILIA1BAWohAUHBACEQDP0CCyANQQFqIQFBwgAhEAz8AgsgDUEBaiEBQcMAIRAM+wILIA1BAWohAUHEACEQDPoCCwJAIAEiASACRg0AIABBjYCAgAA2AgggACABNgIEIAEhAUHFACEQDPoCC0HPACEQDJIDCyAQIQECQAJAIBAtAABBdmoOBAGoAqgCAKgCCyAQQQFqIQELQSchEAz4AgsCQCABIgEgAkcNAEHRACEQDJEDCwJAIAEtAABBIEYNACABIQEMjQELIAFBAWohASAALQAtQQFxRQ3HASABIQEMjAELIAEiFyACRw3IAUHSACEQDI8DC0HTACEQIAEiFCACRg2OAyACIBRrIAAoAgAiAWohFiAUIAFrQQFqIRcDQCAULQAAIAFB1sKAgABqLQAARw3MASABQQFGDccBIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADI4DCwJAIAEiASACRw0AQdUAIRAMjgMLIAEtAABBCkcNzAEgAUEBaiEBDMcBCwJAIAEiASACRw0AQdYAIRAMjQMLAkACQCABLQAAQXZqDgQAzQHNAQHNAQsgAUEBaiEBDMcBCyABQQFqIQFBygAhEAzzAgsgACABIgEgAhCugICAACIQDcsBIAEhAUHNACEQDPICCyAALQApQSJGDYUDDKYCCwJAIAEiASACRw0AQdsAIRAMigMLQQAhFEEBIRdBASEWQQAhEAJAAkACQAJAAkACQAJAAkACQCABLQAAQVBqDgrUAdMBAAECAwQFBgjVAQtBAiEQDAYLQQMhEAwFC0EEIRAMBAtBBSEQDAMLQQYhEAwCC0EHIRAMAQtBCCEQC0EAIRdBACEWQQAhFAzMAQtBCSEQQQEhFEEAIRdBACEWDMsBCwJAIAEiASACRw0AQd0AIRAMiQMLIAEtAABBLkcNzAEgAUEBaiEBDKYCCyABIgEgAkcNzAFB3wAhEAyHAwsCQCABIgEgAkYNACAAQY6AgIAANgIIIAAgATYCBCABIQFB0AAhEAzuAgtB4AAhEAyGAwtB4QAhECABIgEgAkYNhQMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQeLCgIAAai0AAEcNzQEgFEEDRg3MASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyFAwtB4gAhECABIgEgAkYNhAMgAiABayAAKAIAIhRqIRYgASAUa0ECaiEXA0AgAS0AACAUQebCgIAAai0AAEcNzAEgFEECRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyEAwtB4wAhECABIgEgAkYNgwMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQenCgIAAai0AAEcNywEgFEEDRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyDAwsCQCABIgEgAkcNAEHlACEQDIMDCyAAIAFBAWoiASACEKiAgIAAIhANzQEgASEBQdYAIRAM6QILAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AAkACQAJAIBBBuH9qDgsAAc8BzwHPAc8BzwHPAc8BzwECzwELIAFBAWohAUHSACEQDO0CCyABQQFqIQFB0wAhEAzsAgsgAUEBaiEBQdQAIRAM6wILIAFBAWoiASACRw0AC0HkACEQDIIDC0HkACEQDIEDCwNAAkAgAS0AAEHwwoCAAGotAAAiEEEBRg0AIBBBfmoOA88B0AHRAdIBCyABQQFqIgEgAkcNAAtB5gAhEAyAAwsCQCABIgEgAkYNACABQQFqIQEMAwtB5wAhEAz/AgsDQAJAIAEtAABB8MSAgABqLQAAIhBBAUYNAAJAIBBBfmoOBNIB0wHUAQDVAQsgASEBQdcAIRAM5wILIAFBAWoiASACRw0AC0HoACEQDP4CCwJAIAEiASACRw0AQekAIRAM/gILAkAgAS0AACIQQXZqDhq6AdUB1QG8AdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAcoB1QHVAQDTAQsgAUEBaiEBC0EGIRAM4wILA0ACQCABLQAAQfDGgIAAai0AAEEBRg0AIAEhAQyeAgsgAUEBaiIBIAJHDQALQeoAIRAM+wILAkAgASIBIAJGDQAgAUEBaiEBDAMLQesAIRAM+gILAkAgASIBIAJHDQBB7AAhEAz6AgsgAUEBaiEBDAELAkAgASIBIAJHDQBB7QAhEAz5AgsgAUEBaiEBC0EEIRAM3gILAkAgASIUIAJHDQBB7gAhEAz3AgsgFCEBAkACQAJAIBQtAABB8MiAgABqLQAAQX9qDgfUAdUB1gEAnAIBAtcBCyAUQQFqIQEMCgsgFEEBaiEBDM0BC0EAIRAgAEEANgIcIABBm5KAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAz2AgsCQANAAkAgAS0AAEHwyICAAGotAAAiEEEERg0AAkACQCAQQX9qDgfSAdMB1AHZAQAEAdkBCyABIQFB2gAhEAzgAgsgAUEBaiEBQdwAIRAM3wILIAFBAWoiASACRw0AC0HvACEQDPYCCyABQQFqIQEMywELAkAgASIUIAJHDQBB8AAhEAz1AgsgFC0AAEEvRw3UASAUQQFqIQEMBgsCQCABIhQgAkcNAEHxACEQDPQCCwJAIBQtAAAiAUEvRw0AIBRBAWohAUHdACEQDNsCCyABQXZqIgRBFksN0wFBASAEdEGJgIACcUUN0wEMygILAkAgASIBIAJGDQAgAUEBaiEBQd4AIRAM2gILQfIAIRAM8gILAkAgASIUIAJHDQBB9AAhEAzyAgsgFCEBAkAgFC0AAEHwzICAAGotAABBf2oOA8kClAIA1AELQeEAIRAM2AILAkAgASIUIAJGDQADQAJAIBQtAABB8MqAgABqLQAAIgFBA0YNAAJAIAFBf2oOAssCANUBCyAUIQFB3wAhEAzaAgsgFEEBaiIUIAJHDQALQfMAIRAM8QILQfMAIRAM8AILAkAgASIBIAJGDQAgAEGPgICAADYCCCAAIAE2AgQgASEBQeAAIRAM1wILQfUAIRAM7wILAkAgASIBIAJHDQBB9gAhEAzvAgsgAEGPgICAADYCCCAAIAE2AgQgASEBC0EDIRAM1AILA0AgAS0AAEEgRw3DAiABQQFqIgEgAkcNAAtB9wAhEAzsAgsCQCABIgEgAkcNAEH4ACEQDOwCCyABLQAAQSBHDc4BIAFBAWohAQzvAQsgACABIgEgAhCsgICAACIQDc4BIAEhAQyOAgsCQCABIgQgAkcNAEH6ACEQDOoCCyAELQAAQcwARw3RASAEQQFqIQFBEyEQDM8BCwJAIAEiBCACRw0AQfsAIRAM6QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEANAIAQtAAAgAUHwzoCAAGotAABHDdABIAFBBUYNzgEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBB+wAhEAzoAgsCQCABIgQgAkcNAEH8ACEQDOgCCwJAAkAgBC0AAEG9f2oODADRAdEB0QHRAdEB0QHRAdEB0QHRAQHRAQsgBEEBaiEBQeYAIRAMzwILIARBAWohAUHnACEQDM4CCwJAIAEiBCACRw0AQf0AIRAM5wILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNzwEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf0AIRAM5wILIABBADYCACAQQQFqIQFBECEQDMwBCwJAIAEiBCACRw0AQf4AIRAM5gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQfbOgIAAai0AAEcNzgEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf4AIRAM5gILIABBADYCACAQQQFqIQFBFiEQDMsBCwJAIAEiBCACRw0AQf8AIRAM5QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQfzOgIAAai0AAEcNzQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf8AIRAM5QILIABBADYCACAQQQFqIQFBBSEQDMoBCwJAIAEiBCACRw0AQYABIRAM5AILIAQtAABB2QBHDcsBIARBAWohAUEIIRAMyQELAkAgASIEIAJHDQBBgQEhEAzjAgsCQAJAIAQtAABBsn9qDgMAzAEBzAELIARBAWohAUHrACEQDMoCCyAEQQFqIQFB7AAhEAzJAgsCQCABIgQgAkcNAEGCASEQDOICCwJAAkAgBC0AAEG4f2oOCADLAcsBywHLAcsBywEBywELIARBAWohAUHqACEQDMkCCyAEQQFqIQFB7QAhEAzIAgsCQCABIgQgAkcNAEGDASEQDOECCyACIARrIAAoAgAiAWohECAEIAFrQQJqIRQCQANAIAQtAAAgAUGAz4CAAGotAABHDckBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgEDYCAEGDASEQDOECC0EAIRAgAEEANgIAIBRBAWohAQzGAQsCQCABIgQgAkcNAEGEASEQDOACCyACIARrIAAoAgAiAWohFCAEIAFrQQRqIRACQANAIAQtAAAgAUGDz4CAAGotAABHDcgBIAFBBEYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGEASEQDOACCyAAQQA2AgAgEEEBaiEBQSMhEAzFAQsCQCABIgQgAkcNAEGFASEQDN8CCwJAAkAgBC0AAEG0f2oOCADIAcgByAHIAcgByAEByAELIARBAWohAUHvACEQDMYCCyAEQQFqIQFB8AAhEAzFAgsCQCABIgQgAkcNAEGGASEQDN4CCyAELQAAQcUARw3FASAEQQFqIQEMgwILAkAgASIEIAJHDQBBhwEhEAzdAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBiM+AgABqLQAARw3FASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhwEhEAzdAgsgAEEANgIAIBBBAWohAUEtIRAMwgELAkAgASIEIAJHDQBBiAEhEAzcAgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw3EASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiAEhEAzcAgsgAEEANgIAIBBBAWohAUEpIRAMwQELAkAgASIBIAJHDQBBiQEhEAzbAgtBASEQIAEtAABB3wBHDcABIAFBAWohAQyBAgsCQCABIgQgAkcNAEGKASEQDNoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRADQCAELQAAIAFBjM+AgABqLQAARw3BASABQQFGDa8CIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYoBIRAM2QILAkAgASIEIAJHDQBBiwEhEAzZAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBjs+AgABqLQAARw3BASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiwEhEAzZAgsgAEEANgIAIBBBAWohAUECIRAMvgELAkAgASIEIAJHDQBBjAEhEAzYAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw3AASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjAEhEAzYAgsgAEEANgIAIBBBAWohAUEfIRAMvQELAkAgASIEIAJHDQBBjQEhEAzXAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8s+AgABqLQAARw2/ASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjQEhEAzXAgsgAEEANgIAIBBBAWohAUEJIRAMvAELAkAgASIEIAJHDQBBjgEhEAzWAgsCQAJAIAQtAABBt39qDgcAvwG/Ab8BvwG/AQG/AQsgBEEBaiEBQfgAIRAMvQILIARBAWohAUH5ACEQDLwCCwJAIAEiBCACRw0AQY8BIRAM1QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQZHPgIAAai0AAEcNvQEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY8BIRAM1QILIABBADYCACAQQQFqIQFBGCEQDLoBCwJAIAEiBCACRw0AQZABIRAM1AILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQZfPgIAAai0AAEcNvAEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZABIRAM1AILIABBADYCACAQQQFqIQFBFyEQDLkBCwJAIAEiBCACRw0AQZEBIRAM0wILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQZrPgIAAai0AAEcNuwEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZEBIRAM0wILIABBADYCACAQQQFqIQFBFSEQDLgBCwJAIAEiBCACRw0AQZIBIRAM0gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQaHPgIAAai0AAEcNugEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZIBIRAM0gILIABBADYCACAQQQFqIQFBHiEQDLcBCwJAIAEiBCACRw0AQZMBIRAM0QILIAQtAABBzABHDbgBIARBAWohAUEKIRAMtgELAkAgBCACRw0AQZQBIRAM0AILAkACQCAELQAAQb9/ag4PALkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AbkBAbkBCyAEQQFqIQFB/gAhEAy3AgsgBEEBaiEBQf8AIRAMtgILAkAgBCACRw0AQZUBIRAMzwILAkACQCAELQAAQb9/ag4DALgBAbgBCyAEQQFqIQFB/QAhEAy2AgsgBEEBaiEEQYABIRAMtQILAkAgBCACRw0AQZYBIRAMzgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQafPgIAAai0AAEcNtgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZYBIRAMzgILIABBADYCACAQQQFqIQFBCyEQDLMBCwJAIAQgAkcNAEGXASEQDM0CCwJAAkACQAJAIAQtAABBU2oOIwC4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBAbgBuAG4AbgBuAECuAG4AbgBA7gBCyAEQQFqIQFB+wAhEAy2AgsgBEEBaiEBQfwAIRAMtQILIARBAWohBEGBASEQDLQCCyAEQQFqIQRBggEhEAyzAgsCQCAEIAJHDQBBmAEhEAzMAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBqc+AgABqLQAARw20ASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmAEhEAzMAgsgAEEANgIAIBBBAWohAUEZIRAMsQELAkAgBCACRw0AQZkBIRAMywILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQa7PgIAAai0AAEcNswEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZkBIRAMywILIABBADYCACAQQQFqIQFBBiEQDLABCwJAIAQgAkcNAEGaASEQDMoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG0z4CAAGotAABHDbIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGaASEQDMoCCyAAQQA2AgAgEEEBaiEBQRwhEAyvAQsCQCAEIAJHDQBBmwEhEAzJAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBts+AgABqLQAARw2xASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmwEhEAzJAgsgAEEANgIAIBBBAWohAUEnIRAMrgELAkAgBCACRw0AQZwBIRAMyAILAkACQCAELQAAQax/ag4CAAGxAQsgBEEBaiEEQYYBIRAMrwILIARBAWohBEGHASEQDK4CCwJAIAQgAkcNAEGdASEQDMcCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG4z4CAAGotAABHDa8BIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGdASEQDMcCCyAAQQA2AgAgEEEBaiEBQSYhEAysAQsCQCAEIAJHDQBBngEhEAzGAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBus+AgABqLQAARw2uASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBngEhEAzGAgsgAEEANgIAIBBBAWohAUEDIRAMqwELAkAgBCACRw0AQZ8BIRAMxQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNrQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ8BIRAMxQILIABBADYCACAQQQFqIQFBDCEQDKoBCwJAIAQgAkcNAEGgASEQDMQCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUG8z4CAAGotAABHDawBIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGgASEQDMQCCyAAQQA2AgAgEEEBaiEBQQ0hEAypAQsCQCAEIAJHDQBBoQEhEAzDAgsCQAJAIAQtAABBun9qDgsArAGsAawBrAGsAawBrAGsAawBAawBCyAEQQFqIQRBiwEhEAyqAgsgBEEBaiEEQYwBIRAMqQILAkAgBCACRw0AQaIBIRAMwgILIAQtAABB0ABHDakBIARBAWohBAzpAQsCQCAEIAJHDQBBowEhEAzBAgsCQAJAIAQtAABBt39qDgcBqgGqAaoBqgGqAQCqAQsgBEEBaiEEQY4BIRAMqAILIARBAWohAUEiIRAMpgELAkAgBCACRw0AQaQBIRAMwAILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQcDPgIAAai0AAEcNqAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaQBIRAMwAILIABBADYCACAQQQFqIQFBHSEQDKUBCwJAIAQgAkcNAEGlASEQDL8CCwJAAkAgBC0AAEGuf2oOAwCoAQGoAQsgBEEBaiEEQZABIRAMpgILIARBAWohAUEEIRAMpAELAkAgBCACRw0AQaYBIRAMvgILAkACQAJAAkACQCAELQAAQb9/ag4VAKoBqgGqAaoBqgGqAaoBqgGqAaoBAaoBqgECqgGqAQOqAaoBBKoBCyAEQQFqIQRBiAEhEAyoAgsgBEEBaiEEQYkBIRAMpwILIARBAWohBEGKASEQDKYCCyAEQQFqIQRBjwEhEAylAgsgBEEBaiEEQZEBIRAMpAILAkAgBCACRw0AQacBIRAMvQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNpQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQacBIRAMvQILIABBADYCACAQQQFqIQFBESEQDKIBCwJAIAQgAkcNAEGoASEQDLwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHCz4CAAGotAABHDaQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGoASEQDLwCCyAAQQA2AgAgEEEBaiEBQSwhEAyhAQsCQCAEIAJHDQBBqQEhEAy7AgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBxc+AgABqLQAARw2jASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqQEhEAy7AgsgAEEANgIAIBBBAWohAUErIRAMoAELAkAgBCACRw0AQaoBIRAMugILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQcrPgIAAai0AAEcNogEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaoBIRAMugILIABBADYCACAQQQFqIQFBFCEQDJ8BCwJAIAQgAkcNAEGrASEQDLkCCwJAAkACQAJAIAQtAABBvn9qDg8AAQKkAaQBpAGkAaQBpAGkAaQBpAGkAaQBA6QBCyAEQQFqIQRBkwEhEAyiAgsgBEEBaiEEQZQBIRAMoQILIARBAWohBEGVASEQDKACCyAEQQFqIQRBlgEhEAyfAgsCQCAEIAJHDQBBrAEhEAy4AgsgBC0AAEHFAEcNnwEgBEEBaiEEDOABCwJAIAQgAkcNAEGtASEQDLcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHNz4CAAGotAABHDZ8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGtASEQDLcCCyAAQQA2AgAgEEEBaiEBQQ4hEAycAQsCQCAEIAJHDQBBrgEhEAy2AgsgBC0AAEHQAEcNnQEgBEEBaiEBQSUhEAybAQsCQCAEIAJHDQBBrwEhEAy1AgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw2dASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrwEhEAy1AgsgAEEANgIAIBBBAWohAUEqIRAMmgELAkAgBCACRw0AQbABIRAMtAILAkACQCAELQAAQat/ag4LAJ0BnQGdAZ0BnQGdAZ0BnQGdAQGdAQsgBEEBaiEEQZoBIRAMmwILIARBAWohBEGbASEQDJoCCwJAIAQgAkcNAEGxASEQDLMCCwJAAkAgBC0AAEG/f2oOFACcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAEBnAELIARBAWohBEGZASEQDJoCCyAEQQFqIQRBnAEhEAyZAgsCQCAEIAJHDQBBsgEhEAyyAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFB2c+AgABqLQAARw2aASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBsgEhEAyyAgsgAEEANgIAIBBBAWohAUEhIRAMlwELAkAgBCACRw0AQbMBIRAMsQILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQd3PgIAAai0AAEcNmQEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbMBIRAMsQILIABBADYCACAQQQFqIQFBGiEQDJYBCwJAIAQgAkcNAEG0ASEQDLACCwJAAkACQCAELQAAQbt/ag4RAJoBmgGaAZoBmgGaAZoBmgGaAQGaAZoBmgGaAZoBApoBCyAEQQFqIQRBnQEhEAyYAgsgBEEBaiEEQZ4BIRAMlwILIARBAWohBEGfASEQDJYCCwJAIAQgAkcNAEG1ASEQDK8CCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUHkz4CAAGotAABHDZcBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG1ASEQDK8CCyAAQQA2AgAgEEEBaiEBQSghEAyUAQsCQCAEIAJHDQBBtgEhEAyuAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB6s+AgABqLQAARw2WASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtgEhEAyuAgsgAEEANgIAIBBBAWohAUEHIRAMkwELAkAgBCACRw0AQbcBIRAMrQILAkACQCAELQAAQbt/ag4OAJYBlgGWAZYBlgGWAZYBlgGWAZYBlgGWAQGWAQsgBEEBaiEEQaEBIRAMlAILIARBAWohBEGiASEQDJMCCwJAIAQgAkcNAEG4ASEQDKwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDZQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG4ASEQDKwCCyAAQQA2AgAgEEEBaiEBQRIhEAyRAQsCQCAEIAJHDQBBuQEhEAyrAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw2TASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuQEhEAyrAgsgAEEANgIAIBBBAWohAUEgIRAMkAELAkAgBCACRw0AQboBIRAMqgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNkgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQboBIRAMqgILIABBADYCACAQQQFqIQFBDyEQDI8BCwJAIAQgAkcNAEG7ASEQDKkCCwJAAkAgBC0AAEG3f2oOBwCSAZIBkgGSAZIBAZIBCyAEQQFqIQRBpQEhEAyQAgsgBEEBaiEEQaYBIRAMjwILAkAgBCACRw0AQbwBIRAMqAILIAIgBGsgACgCACIBaiEUIAQgAWtBB2ohEAJAA0AgBC0AACABQfTPgIAAai0AAEcNkAEgAUEHRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbwBIRAMqAILIABBADYCACAQQQFqIQFBGyEQDI0BCwJAIAQgAkcNAEG9ASEQDKcCCwJAAkACQCAELQAAQb5/ag4SAJEBkQGRAZEBkQGRAZEBkQGRAQGRAZEBkQGRAZEBkQECkQELIARBAWohBEGkASEQDI8CCyAEQQFqIQRBpwEhEAyOAgsgBEEBaiEEQagBIRAMjQILAkAgBCACRw0AQb4BIRAMpgILIAQtAABBzgBHDY0BIARBAWohBAzPAQsCQCAEIAJHDQBBvwEhEAylAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAELQAAQb9/ag4VAAECA5wBBAUGnAGcAZwBBwgJCgucAQwNDg+cAQsgBEEBaiEBQegAIRAMmgILIARBAWohAUHpACEQDJkCCyAEQQFqIQFB7gAhEAyYAgsgBEEBaiEBQfIAIRAMlwILIARBAWohAUHzACEQDJYCCyAEQQFqIQFB9gAhEAyVAgsgBEEBaiEBQfcAIRAMlAILIARBAWohAUH6ACEQDJMCCyAEQQFqIQRBgwEhEAySAgsgBEEBaiEEQYQBIRAMkQILIARBAWohBEGFASEQDJACCyAEQQFqIQRBkgEhEAyPAgsgBEEBaiEEQZgBIRAMjgILIARBAWohBEGgASEQDI0CCyAEQQFqIQRBowEhEAyMAgsgBEEBaiEEQaoBIRAMiwILAkAgBCACRg0AIABBkICAgAA2AgggACAENgIEQasBIRAMiwILQcABIRAMowILIAAgBSACEKqAgIAAIgENiwEgBSEBDFwLAkAgBiACRg0AIAZBAWohBQyNAQtBwgEhEAyhAgsDQAJAIBAtAABBdmoOBIwBAACPAQALIBBBAWoiECACRw0AC0HDASEQDKACCwJAIAcgAkYNACAAQZGAgIAANgIIIAAgBzYCBCAHIQFBASEQDIcCC0HEASEQDJ8CCwJAIAcgAkcNAEHFASEQDJ8CCwJAAkAgBy0AAEF2ag4EAc4BzgEAzgELIAdBAWohBgyNAQsgB0EBaiEFDIkBCwJAIAcgAkcNAEHGASEQDJ4CCwJAAkAgBy0AAEF2ag4XAY8BjwEBjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAI8BCyAHQQFqIQcLQbABIRAMhAILAkAgCCACRw0AQcgBIRAMnQILIAgtAABBIEcNjQEgAEEAOwEyIAhBAWohAUGzASEQDIMCCyABIRcCQANAIBciByACRg0BIActAABBUGpB/wFxIhBBCk8NzAECQCAALwEyIhRBmTNLDQAgACAUQQpsIhQ7ATIgEEH//wNzIBRB/v8DcUkNACAHQQFqIRcgACAUIBBqIhA7ATIgEEH//wNxQegHSQ0BCwtBACEQIABBADYCHCAAQcGJgIAANgIQIABBDTYCDCAAIAdBAWo2AhQMnAILQccBIRAMmwILIAAgCCACEK6AgIAAIhBFDcoBIBBBFUcNjAEgAEHIATYCHCAAIAg2AhQgAEHJl4CAADYCECAAQRU2AgxBACEQDJoCCwJAIAkgAkcNAEHMASEQDJoCC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgCS0AAEFQag4KlgGVAQABAgMEBQYIlwELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMjgELQQkhEEEBIRRBACEXQQAhFgyNAQsCQCAKIAJHDQBBzgEhEAyZAgsgCi0AAEEuRw2OASAKQQFqIQkMygELIAsgAkcNjgFB0AEhEAyXAgsCQCALIAJGDQAgAEGOgICAADYCCCAAIAs2AgRBtwEhEAz+AQtB0QEhEAyWAgsCQCAEIAJHDQBB0gEhEAyWAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EEaiELA0AgBC0AACAQQfzPgIAAai0AAEcNjgEgEEEERg3pASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHSASEQDJUCCyAAIAwgAhCsgICAACIBDY0BIAwhAQy4AQsCQCAEIAJHDQBB1AEhEAyUAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EBaiEMA0AgBC0AACAQQYHQgIAAai0AAEcNjwEgEEEBRg2OASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHUASEQDJMCCwJAIAQgAkcNAEHWASEQDJMCCyACIARrIAAoAgAiEGohFCAEIBBrQQJqIQsDQCAELQAAIBBBg9CAgABqLQAARw2OASAQQQJGDZABIBBBAWohECAEQQFqIgQgAkcNAAsgACAUNgIAQdYBIRAMkgILAkAgBCACRw0AQdcBIRAMkgILAkACQCAELQAAQbt/ag4QAI8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwEBjwELIARBAWohBEG7ASEQDPkBCyAEQQFqIQRBvAEhEAz4AQsCQCAEIAJHDQBB2AEhEAyRAgsgBC0AAEHIAEcNjAEgBEEBaiEEDMQBCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEG+ASEQDPcBC0HZASEQDI8CCwJAIAQgAkcNAEHaASEQDI8CCyAELQAAQcgARg3DASAAQQE6ACgMuQELIABBAjoALyAAIAQgAhCmgICAACIQDY0BQcIBIRAM9AELIAAtAChBf2oOArcBuQG4AQsDQAJAIAQtAABBdmoOBACOAY4BAI4BCyAEQQFqIgQgAkcNAAtB3QEhEAyLAgsgAEEAOgAvIAAtAC1BBHFFDYQCCyAAQQA6AC8gAEEBOgA0IAEhAQyMAQsgEEEVRg3aASAAQQA2AhwgACABNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAyIAgsCQCAAIBAgAhC0gICAACIEDQAgECEBDIECCwJAIARBFUcNACAAQQM2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAyIAgsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMhwILIBBBFUYN1gEgAEEANgIcIAAgATYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMhgILIAAoAgQhFyAAQQA2AgQgECARp2oiFiEBIAAgFyAQIBYgFBsiEBC1gICAACIURQ2NASAAQQc2AhwgACAQNgIUIAAgFDYCDEEAIRAMhQILIAAgAC8BMEGAAXI7ATAgASEBC0EqIRAM6gELIBBBFUYN0QEgAEEANgIcIAAgATYCFCAAQYOMgIAANgIQIABBEzYCDEEAIRAMggILIBBBFUYNzwEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAMgQILIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDI0BCyAAQQw2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMgAILIBBBFUYNzAEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM/wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIwBCyAAQQ02AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/gELIBBBFUYNyQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM/QELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIsBCyAAQQ42AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/AELIABBADYCHCAAIAE2AhQgAEHAlYCAADYCECAAQQI2AgxBACEQDPsBCyAQQRVGDcUBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPoBCyAAQRA2AhwgACABNgIUIAAgEDYCDEEAIRAM+QELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDPEBCyAAQRE2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM+AELIBBBFUYNwQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM9wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIgBCyAAQRM2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM9gELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDO0BCyAAQRQ2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM9QELIBBBFUYNvQEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM9AELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIYBCyAAQRY2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM8wELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC3gICAACIEDQAgAUEBaiEBDOkBCyAAQRc2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM8gELIABBADYCHCAAIAE2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDPEBC0IBIRELIBBBAWohAQJAIAApAyAiEkL//////////w9WDQAgACASQgSGIBGENwMgIAEhAQyEAQsgAEEANgIcIAAgATYCFCAAQa2JgIAANgIQIABBDDYCDEEAIRAM7wELIABBADYCHCAAIBA2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDO4BCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNcyAAQQU2AhwgACAQNgIUIAAgFDYCDEEAIRAM7QELIABBADYCHCAAIBA2AhQgAEGqnICAADYCECAAQQ82AgxBACEQDOwBCyAAIBAgAhC0gICAACIBDQEgECEBC0EOIRAM0QELAkAgAUEVRw0AIABBAjYCHCAAIBA2AhQgAEGwmICAADYCECAAQRU2AgxBACEQDOoBCyAAQQA2AhwgACAQNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAzpAQsgAUEBaiEQAkAgAC8BMCIBQYABcUUNAAJAIAAgECACELuAgIAAIgENACAQIQEMcAsgAUEVRw26ASAAQQU2AhwgACAQNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAzpAQsCQCABQaAEcUGgBEcNACAALQAtQQJxDQAgAEEANgIcIAAgEDYCFCAAQZaTgIAANgIQIABBBDYCDEEAIRAM6QELIAAgECACEL2AgIAAGiAQIQECQAJAAkACQAJAIAAgECACELOAgIAADhYCAQAEBAQEBAQEBAQEBAQEBAQEBAQDBAsgAEEBOgAuCyAAIAAvATBBwAByOwEwIBAhAQtBJiEQDNEBCyAAQSM2AhwgACAQNgIUIABBpZaAgAA2AhAgAEEVNgIMQQAhEAzpAQsgAEEANgIcIAAgEDYCFCAAQdWLgIAANgIQIABBETYCDEEAIRAM6AELIAAtAC1BAXFFDQFBwwEhEAzOAQsCQCANIAJGDQADQAJAIA0tAABBIEYNACANIQEMxAELIA1BAWoiDSACRw0AC0ElIRAM5wELQSUhEAzmAQsgACgCBCEEIABBADYCBCAAIAQgDRCvgICAACIERQ2tASAAQSY2AhwgACAENgIMIAAgDUEBajYCFEEAIRAM5QELIBBBFUYNqwEgAEEANgIcIAAgATYCFCAAQf2NgIAANgIQIABBHTYCDEEAIRAM5AELIABBJzYCHCAAIAE2AhQgACAQNgIMQQAhEAzjAQsgECEBQQEhFAJAAkACQAJAAkACQAJAIAAtACxBfmoOBwYFBQMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0ErIRAMygELIABBADYCHCAAIBA2AhQgAEGrkoCAADYCECAAQQs2AgxBACEQDOIBCyAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMQQAhEAzhAQsgAEEAOgAsIBAhAQy9AQsgECEBQQEhFAJAAkACQAJAAkAgAC0ALEF7ag4EAwECAAULIAAgAC8BMEEIcjsBMAwDC0ECIRQMAQtBBCEUCyAAQQE6ACwgACAALwEwIBRyOwEwCyAQIQELQSkhEAzFAQsgAEEANgIcIAAgATYCFCAAQfCUgIAANgIQIABBAzYCDEEAIRAM3QELAkAgDi0AAEENRw0AIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHULIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzdAQsgAC0ALUEBcUUNAUHEASEQDMMBCwJAIA4gAkcNAEEtIRAM3AELAkACQANAAkAgDi0AAEF2ag4EAgAAAwALIA5BAWoiDiACRw0AC0EtIRAM3QELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDiEBDHQLIABBLDYCHCAAIA42AhQgACABNgIMQQAhEAzcAQsgACgCBCEBIABBADYCBAJAIAAgASAOELGAgIAAIgENACAOQQFqIQEMcwsgAEEsNgIcIAAgATYCDCAAIA5BAWo2AhRBACEQDNsBCyAAKAIEIQQgAEEANgIEIAAgBCAOELGAgIAAIgQNoAEgDiEBDM4BCyAQQSxHDQEgAUEBaiEQQQEhAQJAAkACQAJAAkAgAC0ALEF7ag4EAwECBAALIBAhAQwEC0ECIQEMAQtBBCEBCyAAQQE6ACwgACAALwEwIAFyOwEwIBAhAQwBCyAAIAAvATBBCHI7ATAgECEBC0E5IRAMvwELIABBADoALCABIQELQTQhEAy9AQsgACAALwEwQSByOwEwIAEhAQwCCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBA0AIAEhAQzHAQsgAEE3NgIcIAAgATYCFCAAIAQ2AgxBACEQDNQBCyAAQQg6ACwgASEBC0EwIRAMuQELAkAgAC0AKEEBRg0AIAEhAQwECyAALQAtQQhxRQ2TASABIQEMAwsgAC0AMEEgcQ2UAUHFASEQDLcBCwJAIA8gAkYNAAJAA0ACQCAPLQAAQVBqIgFB/wFxQQpJDQAgDyEBQTUhEAy6AQsgACkDICIRQpmz5syZs+bMGVYNASAAIBFCCn4iETcDICARIAGtQv8BgyISQn+FVg0BIAAgESASfDcDICAPQQFqIg8gAkcNAAtBOSEQDNEBCyAAKAIEIQIgAEEANgIEIAAgAiAPQQFqIgQQsYCAgAAiAg2VASAEIQEMwwELQTkhEAzPAQsCQCAALwEwIgFBCHFFDQAgAC0AKEEBRw0AIAAtAC1BCHFFDZABCyAAIAFB9/sDcUGABHI7ATAgDyEBC0E3IRAMtAELIAAgAC8BMEEQcjsBMAyrAQsgEEEVRg2LASAAQQA2AhwgACABNgIUIABB8I6AgAA2AhAgAEEcNgIMQQAhEAzLAQsgAEHDADYCHCAAIAE2AgwgACANQQFqNgIUQQAhEAzKAQsCQCABLQAAQTpHDQAgACgCBCEQIABBADYCBAJAIAAgECABEK+AgIAAIhANACABQQFqIQEMYwsgAEHDADYCHCAAIBA2AgwgACABQQFqNgIUQQAhEAzKAQsgAEEANgIcIAAgATYCFCAAQbGRgIAANgIQIABBCjYCDEEAIRAMyQELIABBADYCHCAAIAE2AhQgAEGgmYCAADYCECAAQR42AgxBACEQDMgBCyAAQQA2AgALIABBgBI7ASogACAXQQFqIgEgAhCogICAACIQDQEgASEBC0HHACEQDKwBCyAQQRVHDYMBIABB0QA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAzEAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAzDAQsgAEEANgIcIAAgFDYCFCAAQcGogIAANgIQIABBBzYCDCAAQQA2AgBBACEQDMIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxdCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDMEBC0EAIRAgAEEANgIcIAAgATYCFCAAQYCRgIAANgIQIABBCTYCDAzAAQsgEEEVRg19IABBADYCHCAAIAE2AhQgAEGUjYCAADYCECAAQSE2AgxBACEQDL8BC0EBIRZBACEXQQAhFEEBIRALIAAgEDoAKyABQQFqIQECQAJAIAAtAC1BEHENAAJAAkACQCAALQAqDgMBAAIECyAWRQ0DDAILIBQNAQwCCyAXRQ0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQrYCAgAAiEA0AIAEhAQxcCyAAQdgANgIcIAAgATYCFCAAIBA2AgxBACEQDL4BCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQytAQsgAEHZADYCHCAAIAE2AhQgACAENgIMQQAhEAy9AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMqwELIABB2gA2AhwgACABNgIUIAAgBDYCDEEAIRAMvAELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKkBCyAAQdwANgIcIAAgATYCFCAAIAQ2AgxBACEQDLsBCwJAIAEtAABBUGoiEEH/AXFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHSADYCHCAAIBQ2AhQgACABNgIMQQAhEAykAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHTADYCHCAAIBQ2AhQgACABNgIMQQAhEAyjAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMQwsgAEHlADYCHCAAIBQ2AhQgACABNgIMQQAhEAyiAQsgAEEANgIcIAAgFDYCFCAAQcOPgIAANgIQIABBBzYCDEEAIRAMoQELIABBADYCHCAAIAE2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKABC0EAIRAgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDAyfAQsgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDEEAIRAMngELIABBADYCHCAAIBQ2AhQgAEH+kYCAADYCECAAQQc2AgxBACEQDJ0BCyAAQQA2AhwgACABNgIUIABBjpuAgAA2AhAgAEEGNgIMQQAhEAycAQsgEEEVRg1XIABBADYCHCAAIAE2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDJsBCyAAQQA2AgAgEEEBaiEBQSQhEAsgACAQOgApIAAoAgQhECAAQQA2AgQgACAQIAEQq4CAgAAiEA1UIAEhAQw+CyAAQQA2AgALQQAhECAAQQA2AhwgACAENgIUIABB8ZuAgAA2AhAgAEEGNgIMDJcBCyABQRVGDVAgAEEANgIcIAAgBTYCFCAAQfCMgIAANgIQIABBGzYCDEEAIRAMlgELIAAoAgQhBSAAQQA2AgQgACAFIBAQqYCAgAAiBQ0BIBBBAWohBQtBrQEhEAx7CyAAQcEBNgIcIAAgBTYCDCAAIBBBAWo2AhRBACEQDJMBCyAAKAIEIQYgAEEANgIEIAAgBiAQEKmAgIAAIgYNASAQQQFqIQYLQa4BIRAMeAsgAEHCATYCHCAAIAY2AgwgACAQQQFqNgIUQQAhEAyQAQsgAEEANgIcIAAgBzYCFCAAQZeLgIAANgIQIABBDTYCDEEAIRAMjwELIABBADYCHCAAIAg2AhQgAEHjkICAADYCECAAQQk2AgxBACEQDI4BCyAAQQA2AhwgACAINgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAyNAQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgCUEBaiEIAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBCAAIBAgCBCtgICAACIQRQ09IABByQE2AhwgACAINgIUIAAgEDYCDEEAIRAMjAELIAAoAgQhBCAAQQA2AgQgACAEIAgQrYCAgAAiBEUNdiAAQcoBNgIcIAAgCDYCFCAAIAQ2AgxBACEQDIsBCyAAKAIEIQQgAEEANgIEIAAgBCAJEK2AgIAAIgRFDXQgAEHLATYCHCAAIAk2AhQgACAENgIMQQAhEAyKAQsgACgCBCEEIABBADYCBCAAIAQgChCtgICAACIERQ1yIABBzQE2AhwgACAKNgIUIAAgBDYCDEEAIRAMiQELAkAgCy0AAEFQaiIQQf8BcUEKTw0AIAAgEDoAKiALQQFqIQpBtgEhEAxwCyAAKAIEIQQgAEEANgIEIAAgBCALEK2AgIAAIgRFDXAgAEHPATYCHCAAIAs2AhQgACAENgIMQQAhEAyIAQsgAEEANgIcIAAgBDYCFCAAQZCzgIAANgIQIABBCDYCDCAAQQA2AgBBACEQDIcBCyABQRVGDT8gAEEANgIcIAAgDDYCFCAAQcyOgIAANgIQIABBIDYCDEEAIRAMhgELIABBgQQ7ASggACgCBCEQIABCADcDACAAIBAgDEEBaiIMEKuAgIAAIhBFDTggAEHTATYCHCAAIAw2AhQgACAQNgIMQQAhEAyFAQsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQdibgIAANgIQIABBCDYCDAyDAQsgACgCBCEQIABCADcDACAAIBAgC0EBaiILEKuAgIAAIhANAUHGASEQDGkLIABBAjoAKAxVCyAAQdUBNgIcIAAgCzYCFCAAIBA2AgxBACEQDIABCyAQQRVGDTcgAEEANgIcIAAgBDYCFCAAQaSMgIAANgIQIABBEDYCDEEAIRAMfwsgAC0ANEEBRw00IAAgBCACELyAgIAAIhBFDTQgEEEVRw01IABB3AE2AhwgACAENgIUIABB1ZaAgAA2AhAgAEEVNgIMQQAhEAx+C0EAIRAgAEEANgIcIABBr4uAgAA2AhAgAEECNgIMIAAgFEEBajYCFAx9C0EAIRAMYwtBAiEQDGILQQ0hEAxhC0EPIRAMYAtBJSEQDF8LQRMhEAxeC0EVIRAMXQtBFiEQDFwLQRchEAxbC0EYIRAMWgtBGSEQDFkLQRohEAxYC0EbIRAMVwtBHCEQDFYLQR0hEAxVC0EfIRAMVAtBISEQDFMLQSMhEAxSC0HGACEQDFELQS4hEAxQC0EvIRAMTwtBOyEQDE4LQT0hEAxNC0HIACEQDEwLQckAIRAMSwtBywAhEAxKC0HMACEQDEkLQc4AIRAMSAtB0QAhEAxHC0HVACEQDEYLQdgAIRAMRQtB2QAhEAxEC0HbACEQDEMLQeQAIRAMQgtB5QAhEAxBC0HxACEQDEALQfQAIRAMPwtBjQEhEAw+C0GXASEQDD0LQakBIRAMPAtBrAEhEAw7C0HAASEQDDoLQbkBIRAMOQtBrwEhEAw4C0GxASEQDDcLQbIBIRAMNgtBtAEhEAw1C0G1ASEQDDQLQboBIRAMMwtBvQEhEAwyC0G/ASEQDDELQcEBIRAMMAsgAEEANgIcIAAgBDYCFCAAQemLgIAANgIQIABBHzYCDEEAIRAMSAsgAEHbATYCHCAAIAQ2AhQgAEH6loCAADYCECAAQRU2AgxBACEQDEcLIABB+AA2AhwgACAMNgIUIABBypiAgAA2AhAgAEEVNgIMQQAhEAxGCyAAQdEANgIcIAAgBTYCFCAAQbCXgIAANgIQIABBFTYCDEEAIRAMRQsgAEH5ADYCHCAAIAE2AhQgACAQNgIMQQAhEAxECyAAQfgANgIcIAAgATYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMQwsgAEHkADYCHCAAIAE2AhQgAEHjl4CAADYCECAAQRU2AgxBACEQDEILIABB1wA2AhwgACABNgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAxBCyAAQQA2AhwgACABNgIUIABBuY2AgAA2AhAgAEEaNgIMQQAhEAxACyAAQcIANgIcIAAgATYCFCAAQeOYgIAANgIQIABBFTYCDEEAIRAMPwsgAEEANgIEIAAgDyAPELGAgIAAIgRFDQEgAEE6NgIcIAAgBDYCDCAAIA9BAWo2AhRBACEQDD4LIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCxgICAACIERQ0AIABBOzYCHCAAIAQ2AgwgACABQQFqNgIUQQAhEAw+CyABQQFqIQEMLQsgD0EBaiEBDC0LIABBADYCHCAAIA82AhQgAEHkkoCAADYCECAAQQQ2AgxBACEQDDsLIABBNjYCHCAAIAQ2AhQgACACNgIMQQAhEAw6CyAAQS42AhwgACAONgIUIAAgBDYCDEEAIRAMOQsgAEHQADYCHCAAIAE2AhQgAEGRmICAADYCECAAQRU2AgxBACEQDDgLIA1BAWohAQwsCyAAQRU2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAw2CyAAQRs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw1CyAAQQ82AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw0CyAAQQs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAwzCyAAQRo2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwyCyAAQQs2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwxCyAAQQo2AhwgACABNgIUIABB5JaAgAA2AhAgAEEVNgIMQQAhEAwwCyAAQR42AhwgACABNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAwvCyAAQQA2AhwgACAQNgIUIABB2o2AgAA2AhAgAEEUNgIMQQAhEAwuCyAAQQQ2AhwgACABNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAwtCyAAQQA2AgAgC0EBaiELC0G4ASEQDBILIABBADYCACAQQQFqIQFB9QAhEAwRCyABIQECQCAALQApQQVHDQBB4wAhEAwRC0HiACEQDBALQQAhECAAQQA2AhwgAEHkkYCAADYCECAAQQc2AgwgACAUQQFqNgIUDCgLIABBADYCACAXQQFqIQFBwAAhEAwOC0EBIQELIAAgAToALCAAQQA2AgAgF0EBaiEBC0EoIRAMCwsgASEBC0E4IRAMCQsCQCABIg8gAkYNAANAAkAgDy0AAEGAvoCAAGotAAAiAUEBRg0AIAFBAkcNAyAPQQFqIQEMBAsgD0EBaiIPIAJHDQALQT4hEAwiC0E+IRAMIQsgAEEAOgAsIA8hAQwBC0ELIRAMBgtBOiEQDAULIAFBAWohAUEtIRAMBAsgACABOgAsIABBADYCACAWQQFqIQFBDCEQDAMLIABBADYCACAXQQFqIQFBCiEQDAILIABBADYCAAsgAEEAOgAsIA0hAUEJIRAMAAsLQQAhECAAQQA2AhwgACALNgIUIABBzZCAgAA2AhAgAEEJNgIMDBcLQQAhECAAQQA2AhwgACAKNgIUIABB6YqAgAA2AhAgAEEJNgIMDBYLQQAhECAAQQA2AhwgACAJNgIUIABBt5CAgAA2AhAgAEEJNgIMDBULQQAhECAAQQA2AhwgACAINgIUIABBnJGAgAA2AhAgAEEJNgIMDBQLQQAhECAAQQA2AhwgACABNgIUIABBzZCAgAA2AhAgAEEJNgIMDBMLQQAhECAAQQA2AhwgACABNgIUIABB6YqAgAA2AhAgAEEJNgIMDBILQQAhECAAQQA2AhwgACABNgIUIABBt5CAgAA2AhAgAEEJNgIMDBELQQAhECAAQQA2AhwgACABNgIUIABBnJGAgAA2AhAgAEEJNgIMDBALQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA8LQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA4LQQAhECAAQQA2AhwgACABNgIUIABBwJKAgAA2AhAgAEELNgIMDA0LQQAhECAAQQA2AhwgACABNgIUIABBlYmAgAA2AhAgAEELNgIMDAwLQQAhECAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMDAsLQQAhECAAQQA2AhwgACABNgIUIABB+4+AgAA2AhAgAEEKNgIMDAoLQQAhECAAQQA2AhwgACABNgIUIABB8ZmAgAA2AhAgAEECNgIMDAkLQQAhECAAQQA2AhwgACABNgIUIABBxJSAgAA2AhAgAEECNgIMDAgLQQAhECAAQQA2AhwgACABNgIUIABB8pWAgAA2AhAgAEECNgIMDAcLIABBAjYCHCAAIAE2AhQgAEGcmoCAADYCECAAQRY2AgxBACEQDAYLQQEhEAwFC0HUACEQIAEiBCACRg0EIANBCGogACAEIAJB2MKAgABBChDFgICAACADKAIMIQQgAygCCA4DAQQCAAsQyoCAgAAACyAAQQA2AhwgAEG1moCAADYCECAAQRc2AgwgACAEQQFqNgIUQQAhEAwCCyAAQQA2AhwgACAENgIUIABBypqAgAA2AhAgAEEJNgIMQQAhEAwBCwJAIAEiBCACRw0AQSIhEAwBCyAAQYmAgIAANgIIIAAgBDYCBEEhIRALIANBEGokgICAgAAgEAuvAQECfyABKAIAIQYCQAJAIAIgA0YNACAEIAZqIQQgBiADaiACayEHIAIgBkF/cyAFaiIGaiEFA0ACQCACLQAAIAQtAABGDQBBAiEEDAMLAkAgBg0AQQAhBCAFIQIMAwsgBkF/aiEGIARBAWohBCACQQFqIgIgA0cNAAsgByEGIAMhAgsgAEEBNgIAIAEgBjYCACAAIAI2AgQPCyABQQA2AgAgACAENgIAIAAgAjYCBAsKACAAEMeAgIAAC/I2AQt/I4CAgIAAQRBrIgEkgICAgAACQEEAKAKg0ICAAA0AQQAQy4CAgABBgNSEgABrIgJB2QBJDQBBACEDAkBBACgC4NOAgAAiBA0AQQBCfzcC7NOAgABBAEKAgISAgIDAADcC5NOAgABBACABQQhqQXBxQdiq1aoFcyIENgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgAALQQAgAjYCzNOAgABBAEGA1ISAADYCyNOAgABBAEGA1ISAADYCmNCAgABBACAENgKs0ICAAEEAQX82AqjQgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAtBgNSEgABBeEGA1ISAAGtBD3FBAEGA1ISAAEEIakEPcRsiA2oiBEEEaiACQUhqIgUgA2siA0EBcjYCAEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgABBgNSEgAAgBWpBODYCBAsCQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHsAUsNAAJAQQAoAojQgIAAIgZBECAAQRNqQXBxIABBC0kbIgJBA3YiBHYiA0EDcUUNAAJAAkAgA0EBcSAEckEBcyIFQQN0IgRBsNCAgABqIgMgBEG40ICAAGooAgAiBCgCCCICRw0AQQAgBkF+IAV3cTYCiNCAgAAMAQsgAyACNgIIIAIgAzYCDAsgBEEIaiEDIAQgBUEDdCIFQQNyNgIEIAQgBWoiBCAEKAIEQQFyNgIEDAwLIAJBACgCkNCAgAAiB00NAQJAIANFDQACQAJAIAMgBHRBAiAEdCIDQQAgA2tycSIDQQAgA2txQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmoiBEEDdCIDQbDQgIAAaiIFIANBuNCAgABqKAIAIgMoAggiAEcNAEEAIAZBfiAEd3EiBjYCiNCAgAAMAQsgBSAANgIIIAAgBTYCDAsgAyACQQNyNgIEIAMgBEEDdCIEaiAEIAJrIgU2AgAgAyACaiIAIAVBAXI2AgQCQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhBAJAAkAgBkEBIAdBA3Z0IghxDQBBACAGIAhyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAQ2AgwgAiAENgIIIAQgAjYCDCAEIAg2AggLIANBCGohA0EAIAA2ApzQgIAAQQAgBTYCkNCAgAAMDAtBACgCjNCAgAAiCUUNASAJQQAgCWtxQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmpBAnRBuNKAgABqKAIAIgAoAgRBeHEgAmshBCAAIQUCQANAAkAgBSgCECIDDQAgBUEUaigCACIDRQ0CCyADKAIEQXhxIAJrIgUgBCAFIARJIgUbIQQgAyAAIAUbIQAgAyEFDAALCyAAKAIYIQoCQCAAKAIMIgggAEYNACAAKAIIIgNBACgCmNCAgABJGiAIIAM2AgggAyAINgIMDAsLAkAgAEEUaiIFKAIAIgMNACAAKAIQIgNFDQMgAEEQaiEFCwNAIAUhCyADIghBFGoiBSgCACIDDQAgCEEQaiEFIAgoAhAiAw0ACyALQQA2AgAMCgtBfyECIABBv39LDQAgAEETaiIDQXBxIQJBACgCjNCAgAAiB0UNAEEAIQsCQCACQYACSQ0AQR8hCyACQf///wdLDQAgA0EIdiIDIANBgP4/akEQdkEIcSIDdCIEIARBgOAfakEQdkEEcSIEdCIFIAVBgIAPakEQdkECcSIFdEEPdiADIARyIAVyayIDQQF0IAIgA0EVanZBAXFyQRxqIQsLQQAgAmshBAJAAkACQAJAIAtBAnRBuNKAgABqKAIAIgUNAEEAIQNBACEIDAELQQAhAyACQQBBGSALQQF2ayALQR9GG3QhAEEAIQgDQAJAIAUoAgRBeHEgAmsiBiAETw0AIAYhBCAFIQggBg0AQQAhBCAFIQggBSEDDAMLIAMgBUEUaigCACIGIAYgBSAAQR12QQRxakEQaigCACIFRhsgAyAGGyEDIABBAXQhACAFDQALCwJAIAMgCHINAEEAIQhBAiALdCIDQQAgA2tyIAdxIgNFDQMgA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBUEFdkEIcSIAIANyIAUgAHYiA0ECdkEEcSIFciADIAV2IgNBAXZBAnEiBXIgAyAFdiIDQQF2QQFxIgVyIAMgBXZqQQJ0QbjSgIAAaigCACEDCyADRQ0BCwNAIAMoAgRBeHEgAmsiBiAESSEAAkAgAygCECIFDQAgA0EUaigCACEFCyAGIAQgABshBCADIAggABshCCAFIQMgBQ0ACwsgCEUNACAEQQAoApDQgIAAIAJrTw0AIAgoAhghCwJAIAgoAgwiACAIRg0AIAgoAggiA0EAKAKY0ICAAEkaIAAgAzYCCCADIAA2AgwMCQsCQCAIQRRqIgUoAgAiAw0AIAgoAhAiA0UNAyAIQRBqIQULA0AgBSEGIAMiAEEUaiIFKAIAIgMNACAAQRBqIQUgACgCECIDDQALIAZBADYCAAwICwJAQQAoApDQgIAAIgMgAkkNAEEAKAKc0ICAACEEAkACQCADIAJrIgVBEEkNACAEIAJqIgAgBUEBcjYCBEEAIAU2ApDQgIAAQQAgADYCnNCAgAAgBCADaiAFNgIAIAQgAkEDcjYCBAwBCyAEIANBA3I2AgQgBCADaiIDIAMoAgRBAXI2AgRBAEEANgKc0ICAAEEAQQA2ApDQgIAACyAEQQhqIQMMCgsCQEEAKAKU0ICAACIAIAJNDQBBACgCoNCAgAAiAyACaiIEIAAgAmsiBUEBcjYCBEEAIAU2ApTQgIAAQQAgBDYCoNCAgAAgAyACQQNyNgIEIANBCGohAwwKCwJAAkBBACgC4NOAgABFDQBBACgC6NOAgAAhBAwBC0EAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEMakFwcUHYqtWqBXM2AuDTgIAAQQBBADYC9NOAgABBAEEANgLE04CAAEGAgAQhBAtBACEDAkAgBCACQccAaiIHaiIGQQAgBGsiC3EiCCACSw0AQQBBMDYC+NOAgAAMCgsCQEEAKALA04CAACIDRQ0AAkBBACgCuNOAgAAiBCAIaiIFIARNDQAgBSADTQ0BC0EAIQNBAEEwNgL404CAAAwKC0EALQDE04CAAEEEcQ0EAkACQAJAQQAoAqDQgIAAIgRFDQBByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiAESw0DCyADKAIIIgMNAAsLQQAQy4CAgAAiAEF/Rg0FIAghBgJAQQAoAuTTgIAAIgNBf2oiBCAAcUUNACAIIABrIAQgAGpBACADa3FqIQYLIAYgAk0NBSAGQf7///8HSw0FAkBBACgCwNOAgAAiA0UNAEEAKAK404CAACIEIAZqIgUgBE0NBiAFIANLDQYLIAYQy4CAgAAiAyAARw0BDAcLIAYgAGsgC3EiBkH+////B0sNBCAGEMuAgIAAIgAgAygCACADKAIEakYNAyAAIQMLAkAgA0F/Rg0AIAJByABqIAZNDQACQCAHIAZrQQAoAujTgIAAIgRqQQAgBGtxIgRB/v///wdNDQAgAyEADAcLAkAgBBDLgICAAEF/Rg0AIAQgBmohBiADIQAMBwtBACAGaxDLgICAABoMBAsgAyEAIANBf0cNBQwDC0EAIQgMBwtBACEADAULIABBf0cNAgtBAEEAKALE04CAAEEEcjYCxNOAgAALIAhB/v///wdLDQEgCBDLgICAACEAQQAQy4CAgAAhAyAAQX9GDQEgA0F/Rg0BIAAgA08NASADIABrIgYgAkE4ak0NAQtBAEEAKAK404CAACAGaiIDNgK404CAAAJAIANBACgCvNOAgABNDQBBACADNgK804CAAAsCQAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQCAAIAMoAgAiBSADKAIEIghqRg0CIAMoAggiAw0ADAMLCwJAAkBBACgCmNCAgAAiA0UNACAAIANPDQELQQAgADYCmNCAgAALQQAhA0EAIAY2AszTgIAAQQAgADYCyNOAgABBAEF/NgKo0ICAAEEAQQAoAuDTgIAANgKs0ICAAEEAQQA2AtTTgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiBCAGQUhqIgUgA2siA0EBcjYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgAAgACAFakE4NgIEDAILIAMtAAxBCHENACAEIAVJDQAgBCAATw0AIARBeCAEa0EPcUEAIARBCGpBD3EbIgVqIgBBACgClNCAgAAgBmoiCyAFayIFQQFyNgIEIAMgCCAGajYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAU2ApTQgIAAQQAgADYCoNCAgAAgBCALakE4NgIEDAELAkAgAEEAKAKY0ICAACIITw0AQQAgADYCmNCAgAAgACEICyAAIAZqIQVByNOAgAAhAwJAAkACQAJAAkACQAJAA0AgAygCACAFRg0BIAMoAggiAw0ADAILCyADLQAMQQhxRQ0BC0HI04CAACEDA0ACQCADKAIAIgUgBEsNACAFIAMoAgRqIgUgBEsNAwsgAygCCCEDDAALCyADIAA2AgAgAyADKAIEIAZqNgIEIABBeCAAa0EPcUEAIABBCGpBD3EbaiILIAJBA3I2AgQgBUF4IAVrQQ9xQQAgBUEIakEPcRtqIgYgCyACaiICayEDAkAgBiAERw0AQQAgAjYCoNCAgABBAEEAKAKU0ICAACADaiIDNgKU0ICAACACIANBAXI2AgQMAwsCQCAGQQAoApzQgIAARw0AQQAgAjYCnNCAgABBAEEAKAKQ0ICAACADaiIDNgKQ0ICAACACIANBAXI2AgQgAiADaiADNgIADAMLAkAgBigCBCIEQQNxQQFHDQAgBEF4cSEHAkACQCAEQf8BSw0AIAYoAggiBSAEQQN2IghBA3RBsNCAgABqIgBGGgJAIAYoAgwiBCAFRw0AQQBBACgCiNCAgABBfiAId3E2AojQgIAADAILIAQgAEYaIAQgBTYCCCAFIAQ2AgwMAQsgBigCGCEJAkACQCAGKAIMIgAgBkYNACAGKAIIIgQgCEkaIAAgBDYCCCAEIAA2AgwMAQsCQCAGQRRqIgQoAgAiBQ0AIAZBEGoiBCgCACIFDQBBACEADAELA0AgBCEIIAUiAEEUaiIEKAIAIgUNACAAQRBqIQQgACgCECIFDQALIAhBADYCAAsgCUUNAAJAAkAgBiAGKAIcIgVBAnRBuNKAgABqIgQoAgBHDQAgBCAANgIAIAANAUEAQQAoAozQgIAAQX4gBXdxNgKM0ICAAAwCCyAJQRBBFCAJKAIQIAZGG2ogADYCACAARQ0BCyAAIAk2AhgCQCAGKAIQIgRFDQAgACAENgIQIAQgADYCGAsgBigCFCIERQ0AIABBFGogBDYCACAEIAA2AhgLIAcgA2ohAyAGIAdqIgYoAgQhBAsgBiAEQX5xNgIEIAIgA2ogAzYCACACIANBAXI2AgQCQCADQf8BSw0AIANBeHFBsNCAgABqIQQCQAJAQQAoAojQgIAAIgVBASADQQN2dCIDcQ0AQQAgBSADcjYCiNCAgAAgBCEDDAELIAQoAgghAwsgAyACNgIMIAQgAjYCCCACIAQ2AgwgAiADNgIIDAMLQR8hBAJAIANB////B0sNACADQQh2IgQgBEGA/j9qQRB2QQhxIgR0IgUgBUGA4B9qQRB2QQRxIgV0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAQgBXIgAHJrIgRBAXQgAyAEQRVqdkEBcXJBHGohBAsgAiAENgIcIAJCADcCECAEQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiAEEBIAR0IghxDQAgBSACNgIAQQAgACAIcjYCjNCAgAAgAiAFNgIYIAIgAjYCCCACIAI2AgwMAwsgA0EAQRkgBEEBdmsgBEEfRht0IQQgBSgCACEAA0AgACIFKAIEQXhxIANGDQIgBEEddiEAIARBAXQhBCAFIABBBHFqQRBqIggoAgAiAA0ACyAIIAI2AgAgAiAFNgIYIAIgAjYCDCACIAI2AggMAgsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiCyAGQUhqIgggA2siA0EBcjYCBCAAIAhqQTg2AgQgBCAFQTcgBWtBD3FBACAFQUlqQQ9xG2pBQWoiCCAIIARBEGpJGyIIQSM2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAs2AqDQgIAAIAhBEGpBACkC0NOAgAA3AgAgCEEAKQLI04CAADcCCEEAIAhBCGo2AtDTgIAAQQAgBjYCzNOAgABBACAANgLI04CAAEEAQQA2AtTTgIAAIAhBJGohAwNAIANBBzYCACADQQRqIgMgBUkNAAsgCCAERg0DIAggCCgCBEF+cTYCBCAIIAggBGsiADYCACAEIABBAXI2AgQCQCAAQf8BSw0AIABBeHFBsNCAgABqIQMCQAJAQQAoAojQgIAAIgVBASAAQQN2dCIAcQ0AQQAgBSAAcjYCiNCAgAAgAyEFDAELIAMoAgghBQsgBSAENgIMIAMgBDYCCCAEIAM2AgwgBCAFNgIIDAQLQR8hAwJAIABB////B0sNACAAQQh2IgMgA0GA/j9qQRB2QQhxIgN0IgUgBUGA4B9qQRB2QQRxIgV0IgggCEGAgA9qQRB2QQJxIgh0QQ92IAMgBXIgCHJrIgNBAXQgACADQRVqdkEBcXJBHGohAwsgBCADNgIcIARCADcCECADQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiCEEBIAN0IgZxDQAgBSAENgIAQQAgCCAGcjYCjNCAgAAgBCAFNgIYIAQgBDYCCCAEIAQ2AgwMBAsgAEEAQRkgA0EBdmsgA0EfRht0IQMgBSgCACEIA0AgCCIFKAIEQXhxIABGDQMgA0EddiEIIANBAXQhAyAFIAhBBHFqQRBqIgYoAgAiCA0ACyAGIAQ2AgAgBCAFNgIYIAQgBDYCDCAEIAQ2AggMAwsgBSgCCCIDIAI2AgwgBSACNgIIIAJBADYCGCACIAU2AgwgAiADNgIICyALQQhqIQMMBQsgBSgCCCIDIAQ2AgwgBSAENgIIIARBADYCGCAEIAU2AgwgBCADNgIIC0EAKAKU0ICAACIDIAJNDQBBACgCoNCAgAAiBCACaiIFIAMgAmsiA0EBcjYCBEEAIAM2ApTQgIAAQQAgBTYCoNCAgAAgBCACQQNyNgIEIARBCGohAwwDC0EAIQNBAEEwNgL404CAAAwCCwJAIAtFDQACQAJAIAggCCgCHCIFQQJ0QbjSgIAAaiIDKAIARw0AIAMgADYCACAADQFBACAHQX4gBXdxIgc2AozQgIAADAILIAtBEEEUIAsoAhAgCEYbaiAANgIAIABFDQELIAAgCzYCGAJAIAgoAhAiA0UNACAAIAM2AhAgAyAANgIYCyAIQRRqKAIAIgNFDQAgAEEUaiADNgIAIAMgADYCGAsCQAJAIARBD0sNACAIIAQgAmoiA0EDcjYCBCAIIANqIgMgAygCBEEBcjYCBAwBCyAIIAJqIgAgBEEBcjYCBCAIIAJBA3I2AgQgACAEaiAENgIAAkAgBEH/AUsNACAEQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgBEEDdnQiBHENAEEAIAUgBHI2AojQgIAAIAMhBAwBCyADKAIIIQQLIAQgADYCDCADIAA2AgggACADNgIMIAAgBDYCCAwBC0EfIQMCQCAEQf///wdLDQAgBEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCICIAJBgIAPakEQdkECcSICdEEPdiADIAVyIAJyayIDQQF0IAQgA0EVanZBAXFyQRxqIQMLIAAgAzYCHCAAQgA3AhAgA0ECdEG40oCAAGohBQJAIAdBASADdCICcQ0AIAUgADYCAEEAIAcgAnI2AozQgIAAIAAgBTYCGCAAIAA2AgggACAANgIMDAELIARBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhAgJAA0AgAiIFKAIEQXhxIARGDQEgA0EddiECIANBAXQhAyAFIAJBBHFqQRBqIgYoAgAiAg0ACyAGIAA2AgAgACAFNgIYIAAgADYCDCAAIAA2AggMAQsgBSgCCCIDIAA2AgwgBSAANgIIIABBADYCGCAAIAU2AgwgACADNgIICyAIQQhqIQMMAQsCQCAKRQ0AAkACQCAAIAAoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAg2AgAgCA0BQQAgCUF+IAV3cTYCjNCAgAAMAgsgCkEQQRQgCigCECAARhtqIAg2AgAgCEUNAQsgCCAKNgIYAkAgACgCECIDRQ0AIAggAzYCECADIAg2AhgLIABBFGooAgAiA0UNACAIQRRqIAM2AgAgAyAINgIYCwJAAkAgBEEPSw0AIAAgBCACaiIDQQNyNgIEIAAgA2oiAyADKAIEQQFyNgIEDAELIAAgAmoiBSAEQQFyNgIEIAAgAkEDcjYCBCAFIARqIAQ2AgACQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhAwJAAkBBASAHQQN2dCIIIAZxDQBBACAIIAZyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAM2AgwgAiADNgIIIAMgAjYCDCADIAg2AggLQQAgBTYCnNCAgABBACAENgKQ0ICAAAsgAEEIaiEDCyABQRBqJICAgIAAIAMLCgAgABDJgICAAAviDQEHfwJAIABFDQAgAEF4aiIBIABBfGooAgAiAkF4cSIAaiEDAkAgAkEBcQ0AIAJBA3FFDQEgASABKAIAIgJrIgFBACgCmNCAgAAiBEkNASACIABqIQACQCABQQAoApzQgIAARg0AAkAgAkH/AUsNACABKAIIIgQgAkEDdiIFQQN0QbDQgIAAaiIGRhoCQCABKAIMIgIgBEcNAEEAQQAoAojQgIAAQX4gBXdxNgKI0ICAAAwDCyACIAZGGiACIAQ2AgggBCACNgIMDAILIAEoAhghBwJAAkAgASgCDCIGIAFGDQAgASgCCCICIARJGiAGIAI2AgggAiAGNgIMDAELAkAgAUEUaiICKAIAIgQNACABQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQECQAJAIAEgASgCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAwsgB0EQQRQgBygCECABRhtqIAY2AgAgBkUNAgsgBiAHNgIYAkAgASgCECICRQ0AIAYgAjYCECACIAY2AhgLIAEoAhQiAkUNASAGQRRqIAI2AgAgAiAGNgIYDAELIAMoAgQiAkEDcUEDRw0AIAMgAkF+cTYCBEEAIAA2ApDQgIAAIAEgAGogADYCACABIABBAXI2AgQPCyABIANPDQAgAygCBCICQQFxRQ0AAkACQCACQQJxDQACQCADQQAoAqDQgIAARw0AQQAgATYCoNCAgABBAEEAKAKU0ICAACAAaiIANgKU0ICAACABIABBAXI2AgQgAUEAKAKc0ICAAEcNA0EAQQA2ApDQgIAAQQBBADYCnNCAgAAPCwJAIANBACgCnNCAgABHDQBBACABNgKc0ICAAEEAQQAoApDQgIAAIABqIgA2ApDQgIAAIAEgAEEBcjYCBCABIABqIAA2AgAPCyACQXhxIABqIQACQAJAIAJB/wFLDQAgAygCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgAygCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAgsgAiAGRhogAiAENgIIIAQgAjYCDAwBCyADKAIYIQcCQAJAIAMoAgwiBiADRg0AIAMoAggiAkEAKAKY0ICAAEkaIAYgAjYCCCACIAY2AgwMAQsCQCADQRRqIgIoAgAiBA0AIANBEGoiAigCACIEDQBBACEGDAELA0AgAiEFIAQiBkEUaiICKAIAIgQNACAGQRBqIQIgBigCECIEDQALIAVBADYCAAsgB0UNAAJAAkAgAyADKAIcIgRBAnRBuNKAgABqIgIoAgBHDQAgAiAGNgIAIAYNAUEAQQAoAozQgIAAQX4gBHdxNgKM0ICAAAwCCyAHQRBBFCAHKAIQIANGG2ogBjYCACAGRQ0BCyAGIAc2AhgCQCADKAIQIgJFDQAgBiACNgIQIAIgBjYCGAsgAygCFCICRQ0AIAZBFGogAjYCACACIAY2AhgLIAEgAGogADYCACABIABBAXI2AgQgAUEAKAKc0ICAAEcNAUEAIAA2ApDQgIAADwsgAyACQX5xNgIEIAEgAGogADYCACABIABBAXI2AgQLAkAgAEH/AUsNACAAQXhxQbDQgIAAaiECAkACQEEAKAKI0ICAACIEQQEgAEEDdnQiAHENAEEAIAQgAHI2AojQgIAAIAIhAAwBCyACKAIIIQALIAAgATYCDCACIAE2AgggASACNgIMIAEgADYCCA8LQR8hAgJAIABB////B0sNACAAQQh2IgIgAkGA/j9qQRB2QQhxIgJ0IgQgBEGA4B9qQRB2QQRxIgR0IgYgBkGAgA9qQRB2QQJxIgZ0QQ92IAIgBHIgBnJrIgJBAXQgACACQRVqdkEBcXJBHGohAgsgASACNgIcIAFCADcCECACQQJ0QbjSgIAAaiEEAkACQEEAKAKM0ICAACIGQQEgAnQiA3ENACAEIAE2AgBBACAGIANyNgKM0ICAACABIAQ2AhggASABNgIIIAEgATYCDAwBCyAAQQBBGSACQQF2ayACQR9GG3QhAiAEKAIAIQYCQANAIAYiBCgCBEF4cSAARg0BIAJBHXYhBiACQQF0IQIgBCAGQQRxakEQaiIDKAIAIgYNAAsgAyABNgIAIAEgBDYCGCABIAE2AgwgASABNgIIDAELIAQoAggiACABNgIMIAQgATYCCCABQQA2AhggASAENgIMIAEgADYCCAtBAEEAKAKo0ICAAEF/aiIBQX8gARs2AqjQgIAACwsEAAAAC04AAkAgAA0APwBBEHQPCwJAIABB//8DcQ0AIABBf0wNAAJAIABBEHZAACIAQX9HDQBBAEEwNgL404CAAEF/DwsgAEEQdA8LEMqAgIAAAAvyAgIDfwF+AkAgAkUNACAAIAE6AAAgAiAAaiIDQX9qIAE6AAAgAkEDSQ0AIAAgAToAAiAAIAE6AAEgA0F9aiABOgAAIANBfmogAToAACACQQdJDQAgACABOgADIANBfGogAToAACACQQlJDQAgAEEAIABrQQNxIgRqIgMgAUH/AXFBgYKECGwiATYCACADIAIgBGtBfHEiBGoiAkF8aiABNgIAIARBCUkNACADIAE2AgggAyABNgIEIAJBeGogATYCACACQXRqIAE2AgAgBEEZSQ0AIAMgATYCGCADIAE2AhQgAyABNgIQIAMgATYCDCACQXBqIAE2AgAgAkFsaiABNgIAIAJBaGogATYCACACQWRqIAE2AgAgBCADQQRxQRhyIgVrIgJBIEkNACABrUKBgICAEH4hBiADIAVqIQEDQCABIAY3AxggASAGNwMQIAEgBjcDCCABIAY3AwAgAUEgaiEBIAJBYGoiAkEfSw0ACwsgAAsLjkgBAEGACAuGSAEAAAACAAAAAwAAAAAAAAAAAAAABAAAAAUAAAAAAAAAAAAAAAYAAAAHAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsb3NlZWVwLWFsaXZlAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgAAAAAAAAAAAAAAAAAAAHJhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KDQpTTQ0KDQpUVFAvQ0UvVFNQLwAAAAAAAAAAAAAAAAECAAEDAAAAAAAAAAAAAAAAAAAAAAAABAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQUBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAABAAACAAAAAAAAAAAAAAAAAAAAAAAAAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.enumToMap = void 0;\nfunction enumToMap(obj) {\n const res = {};\n Object.keys(obj).forEach((key) => {\n const value = obj[key];\n if (typeof value === 'number') {\n res[key] = value;\n }\n });\n return res;\n}\nexports.enumToMap = enumToMap;\n//# sourceMappingURL=utils.js.map","'use strict'\n\nconst { kClients } = require('../core/symbols')\nconst Agent = require('../agent')\nconst {\n kAgent,\n kMockAgentSet,\n kMockAgentGet,\n kDispatches,\n kIsMockActive,\n kNetConnect,\n kGetNetConnect,\n kOptions,\n kFactory\n} = require('./mock-symbols')\nconst MockClient = require('./mock-client')\nconst MockPool = require('./mock-pool')\nconst { matchValue, buildMockOptions } = require('./mock-utils')\nconst { InvalidArgumentError, UndiciError } = require('../core/errors')\nconst Dispatcher = require('../dispatcher')\nconst Pluralizer = require('./pluralizer')\nconst PendingInterceptorsFormatter = require('./pending-interceptors-formatter')\n\nclass FakeWeakRef {\n constructor (value) {\n this.value = value\n }\n\n deref () {\n return this.value\n }\n}\n\nclass MockAgent extends Dispatcher {\n constructor (opts) {\n super(opts)\n\n this[kNetConnect] = true\n this[kIsMockActive] = true\n\n // Instantiate Agent and encapsulate\n if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n const agent = opts && opts.agent ? opts.agent : new Agent(opts)\n this[kAgent] = agent\n\n this[kClients] = agent[kClients]\n this[kOptions] = buildMockOptions(opts)\n }\n\n get (origin) {\n let dispatcher = this[kMockAgentGet](origin)\n\n if (!dispatcher) {\n dispatcher = this[kFactory](origin)\n this[kMockAgentSet](origin, dispatcher)\n }\n return dispatcher\n }\n\n dispatch (opts, handler) {\n // Call MockAgent.get to perform additional setup before dispatching as normal\n this.get(opts.origin)\n return this[kAgent].dispatch(opts, handler)\n }\n\n async close () {\n await this[kAgent].close()\n this[kClients].clear()\n }\n\n deactivate () {\n this[kIsMockActive] = false\n }\n\n activate () {\n this[kIsMockActive] = true\n }\n\n enableNetConnect (matcher) {\n if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {\n if (Array.isArray(this[kNetConnect])) {\n this[kNetConnect].push(matcher)\n } else {\n this[kNetConnect] = [matcher]\n }\n } else if (typeof matcher === 'undefined') {\n this[kNetConnect] = true\n } else {\n throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')\n }\n }\n\n disableNetConnect () {\n this[kNetConnect] = false\n }\n\n // This is required to bypass issues caused by using global symbols - see:\n // https://github.com/nodejs/undici/issues/1447\n get isMockActive () {\n return this[kIsMockActive]\n }\n\n [kMockAgentSet] (origin, dispatcher) {\n this[kClients].set(origin, new FakeWeakRef(dispatcher))\n }\n\n [kFactory] (origin) {\n const mockOptions = Object.assign({ agent: this }, this[kOptions])\n return this[kOptions] && this[kOptions].connections === 1\n ? new MockClient(origin, mockOptions)\n : new MockPool(origin, mockOptions)\n }\n\n [kMockAgentGet] (origin) {\n // First check if we can immediately find it\n const ref = this[kClients].get(origin)\n if (ref) {\n return ref.deref()\n }\n\n // If the origin is not a string create a dummy parent pool and return to user\n if (typeof origin !== 'string') {\n const dispatcher = this[kFactory]('http://localhost:9999')\n this[kMockAgentSet](origin, dispatcher)\n return dispatcher\n }\n\n // If we match, create a pool and assign the same dispatches\n for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {\n const nonExplicitDispatcher = nonExplicitRef.deref()\n if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {\n const dispatcher = this[kFactory](origin)\n this[kMockAgentSet](origin, dispatcher)\n dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]\n return dispatcher\n }\n }\n }\n\n [kGetNetConnect] () {\n return this[kNetConnect]\n }\n\n pendingInterceptors () {\n const mockAgentClients = this[kClients]\n\n return Array.from(mockAgentClients.entries())\n .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))\n .filter(({ pending }) => pending)\n }\n\n assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {\n const pending = this.pendingInterceptors()\n\n if (pending.length === 0) {\n return\n }\n\n const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)\n\n throw new UndiciError(`\n${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:\n\n${pendingInterceptorsFormatter.format(pending)}\n`.trim())\n }\n}\n\nmodule.exports = MockAgent\n","'use strict'\n\nconst { promisify } = require('util')\nconst Client = require('../client')\nconst { buildMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kMockAgent,\n kClose,\n kOriginalClose,\n kOrigin,\n kOriginalDispatch,\n kConnected\n} = require('./mock-symbols')\nconst { MockInterceptor } = require('./mock-interceptor')\nconst Symbols = require('../core/symbols')\nconst { InvalidArgumentError } = require('../core/errors')\n\n/**\n * MockClient provides an API that extends the Client to influence the mockDispatches.\n */\nclass MockClient extends Client {\n constructor (origin, opts) {\n super(origin, opts)\n\n if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n\n this[kMockAgent] = opts.agent\n this[kOrigin] = origin\n this[kDispatches] = []\n this[kConnected] = 1\n this[kOriginalDispatch] = this.dispatch\n this[kOriginalClose] = this.close.bind(this)\n\n this.dispatch = buildMockDispatch.call(this)\n this.close = this[kClose]\n }\n\n get [Symbols.kConnected] () {\n return this[kConnected]\n }\n\n /**\n * Sets up the base interceptor for mocking replies from undici.\n */\n intercept (opts) {\n return new MockInterceptor(opts, this[kDispatches])\n }\n\n async [kClose] () {\n await promisify(this[kOriginalClose])()\n this[kConnected] = 0\n this[kMockAgent][Symbols.kClients].delete(this[kOrigin])\n }\n}\n\nmodule.exports = MockClient\n","'use strict'\n\nconst { UndiciError } = require('../core/errors')\n\nclass MockNotMatchedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, MockNotMatchedError)\n this.name = 'MockNotMatchedError'\n this.message = message || 'The request does not match any registered mock dispatches'\n this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'\n }\n}\n\nmodule.exports = {\n MockNotMatchedError\n}\n","'use strict'\n\nconst { getResponseData, buildKey, addMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kDispatchKey,\n kDefaultHeaders,\n kDefaultTrailers,\n kContentLength,\n kMockDispatch\n} = require('./mock-symbols')\nconst { InvalidArgumentError } = require('../core/errors')\nconst { buildURL } = require('../core/util')\n\n/**\n * Defines the scope API for an interceptor reply\n */\nclass MockScope {\n constructor (mockDispatch) {\n this[kMockDispatch] = mockDispatch\n }\n\n /**\n * Delay a reply by a set amount in ms.\n */\n delay (waitInMs) {\n if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {\n throw new InvalidArgumentError('waitInMs must be a valid integer > 0')\n }\n\n this[kMockDispatch].delay = waitInMs\n return this\n }\n\n /**\n * For a defined reply, never mark as consumed.\n */\n persist () {\n this[kMockDispatch].persist = true\n return this\n }\n\n /**\n * Allow one to define a reply for a set amount of matching requests.\n */\n times (repeatTimes) {\n if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {\n throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')\n }\n\n this[kMockDispatch].times = repeatTimes\n return this\n }\n}\n\n/**\n * Defines an interceptor for a Mock\n */\nclass MockInterceptor {\n constructor (opts, mockDispatches) {\n if (typeof opts !== 'object') {\n throw new InvalidArgumentError('opts must be an object')\n }\n if (typeof opts.path === 'undefined') {\n throw new InvalidArgumentError('opts.path must be defined')\n }\n if (typeof opts.method === 'undefined') {\n opts.method = 'GET'\n }\n // See https://github.com/nodejs/undici/issues/1245\n // As per RFC 3986, clients are not supposed to send URI\n // fragments to servers when they retrieve a document,\n if (typeof opts.path === 'string') {\n if (opts.query) {\n opts.path = buildURL(opts.path, opts.query)\n } else {\n // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811\n const parsedURL = new URL(opts.path, 'data://')\n opts.path = parsedURL.pathname + parsedURL.search\n }\n }\n if (typeof opts.method === 'string') {\n opts.method = opts.method.toUpperCase()\n }\n\n this[kDispatchKey] = buildKey(opts)\n this[kDispatches] = mockDispatches\n this[kDefaultHeaders] = {}\n this[kDefaultTrailers] = {}\n this[kContentLength] = false\n }\n\n createMockScopeDispatchData (statusCode, data, responseOptions = {}) {\n const responseData = getResponseData(data)\n const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}\n const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }\n const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }\n\n return { statusCode, data, headers, trailers }\n }\n\n validateReplyParameters (statusCode, data, responseOptions) {\n if (typeof statusCode === 'undefined') {\n throw new InvalidArgumentError('statusCode must be defined')\n }\n if (typeof data === 'undefined') {\n throw new InvalidArgumentError('data must be defined')\n }\n if (typeof responseOptions !== 'object') {\n throw new InvalidArgumentError('responseOptions must be an object')\n }\n }\n\n /**\n * Mock an undici request with a defined reply.\n */\n reply (replyData) {\n // Values of reply aren't available right now as they\n // can only be available when the reply callback is invoked.\n if (typeof replyData === 'function') {\n // We'll first wrap the provided callback in another function,\n // this function will properly resolve the data from the callback\n // when invoked.\n const wrappedDefaultsCallback = (opts) => {\n // Our reply options callback contains the parameter for statusCode, data and options.\n const resolvedData = replyData(opts)\n\n // Check if it is in the right format\n if (typeof resolvedData !== 'object') {\n throw new InvalidArgumentError('reply options callback must return an object')\n }\n\n const { statusCode, data = '', responseOptions = {} } = resolvedData\n this.validateReplyParameters(statusCode, data, responseOptions)\n // Since the values can be obtained immediately we return them\n // from this higher order function that will be resolved later.\n return {\n ...this.createMockScopeDispatchData(statusCode, data, responseOptions)\n }\n }\n\n // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)\n return new MockScope(newMockDispatch)\n }\n\n // We can have either one or three parameters, if we get here,\n // we should have 1-3 parameters. So we spread the arguments of\n // this function to obtain the parameters, since replyData will always\n // just be the statusCode.\n const [statusCode, data = '', responseOptions = {}] = [...arguments]\n this.validateReplyParameters(statusCode, data, responseOptions)\n\n // Send in-already provided data like usual\n const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)\n return new MockScope(newMockDispatch)\n }\n\n /**\n * Mock an undici request with a defined error.\n */\n replyWithError (error) {\n if (typeof error === 'undefined') {\n throw new InvalidArgumentError('error must be defined')\n }\n\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })\n return new MockScope(newMockDispatch)\n }\n\n /**\n * Set default reply headers on the interceptor for subsequent replies\n */\n defaultReplyHeaders (headers) {\n if (typeof headers === 'undefined') {\n throw new InvalidArgumentError('headers must be defined')\n }\n\n this[kDefaultHeaders] = headers\n return this\n }\n\n /**\n * Set default reply trailers on the interceptor for subsequent replies\n */\n defaultReplyTrailers (trailers) {\n if (typeof trailers === 'undefined') {\n throw new InvalidArgumentError('trailers must be defined')\n }\n\n this[kDefaultTrailers] = trailers\n return this\n }\n\n /**\n * Set reply content length header for replies on the interceptor\n */\n replyContentLength () {\n this[kContentLength] = true\n return this\n }\n}\n\nmodule.exports.MockInterceptor = MockInterceptor\nmodule.exports.MockScope = MockScope\n","'use strict'\n\nconst { promisify } = require('util')\nconst Pool = require('../pool')\nconst { buildMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kMockAgent,\n kClose,\n kOriginalClose,\n kOrigin,\n kOriginalDispatch,\n kConnected\n} = require('./mock-symbols')\nconst { MockInterceptor } = require('./mock-interceptor')\nconst Symbols = require('../core/symbols')\nconst { InvalidArgumentError } = require('../core/errors')\n\n/**\n * MockPool provides an API that extends the Pool to influence the mockDispatches.\n */\nclass MockPool extends Pool {\n constructor (origin, opts) {\n super(origin, opts)\n\n if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n\n this[kMockAgent] = opts.agent\n this[kOrigin] = origin\n this[kDispatches] = []\n this[kConnected] = 1\n this[kOriginalDispatch] = this.dispatch\n this[kOriginalClose] = this.close.bind(this)\n\n this.dispatch = buildMockDispatch.call(this)\n this.close = this[kClose]\n }\n\n get [Symbols.kConnected] () {\n return this[kConnected]\n }\n\n /**\n * Sets up the base interceptor for mocking replies from undici.\n */\n intercept (opts) {\n return new MockInterceptor(opts, this[kDispatches])\n }\n\n async [kClose] () {\n await promisify(this[kOriginalClose])()\n this[kConnected] = 0\n this[kMockAgent][Symbols.kClients].delete(this[kOrigin])\n }\n}\n\nmodule.exports = MockPool\n","'use strict'\n\nmodule.exports = {\n kAgent: Symbol('agent'),\n kOptions: Symbol('options'),\n kFactory: Symbol('factory'),\n kDispatches: Symbol('dispatches'),\n kDispatchKey: Symbol('dispatch key'),\n kDefaultHeaders: Symbol('default headers'),\n kDefaultTrailers: Symbol('default trailers'),\n kContentLength: Symbol('content length'),\n kMockAgent: Symbol('mock agent'),\n kMockAgentSet: Symbol('mock agent set'),\n kMockAgentGet: Symbol('mock agent get'),\n kMockDispatch: Symbol('mock dispatch'),\n kClose: Symbol('close'),\n kOriginalClose: Symbol('original agent close'),\n kOrigin: Symbol('origin'),\n kIsMockActive: Symbol('is mock active'),\n kNetConnect: Symbol('net connect'),\n kGetNetConnect: Symbol('get net connect'),\n kConnected: Symbol('connected')\n}\n","'use strict'\n\nconst { MockNotMatchedError } = require('./mock-errors')\nconst {\n kDispatches,\n kMockAgent,\n kOriginalDispatch,\n kOrigin,\n kGetNetConnect\n} = require('./mock-symbols')\nconst { buildURL, nop } = require('../core/util')\nconst { STATUS_CODES } = require('http')\nconst {\n types: {\n isPromise\n }\n} = require('util')\n\nfunction matchValue (match, value) {\n if (typeof match === 'string') {\n return match === value\n }\n if (match instanceof RegExp) {\n return match.test(value)\n }\n if (typeof match === 'function') {\n return match(value) === true\n }\n return false\n}\n\nfunction lowerCaseEntries (headers) {\n return Object.fromEntries(\n Object.entries(headers).map(([headerName, headerValue]) => {\n return [headerName.toLocaleLowerCase(), headerValue]\n })\n )\n}\n\n/**\n * @param {import('../../index').Headers|string[]|Record} headers\n * @param {string} key\n */\nfunction getHeaderByName (headers, key) {\n if (Array.isArray(headers)) {\n for (let i = 0; i < headers.length; i += 2) {\n if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {\n return headers[i + 1]\n }\n }\n\n return undefined\n } else if (typeof headers.get === 'function') {\n return headers.get(key)\n } else {\n return lowerCaseEntries(headers)[key.toLocaleLowerCase()]\n }\n}\n\n/** @param {string[]} headers */\nfunction buildHeadersFromArray (headers) { // fetch HeadersList\n const clone = headers.slice()\n const entries = []\n for (let index = 0; index < clone.length; index += 2) {\n entries.push([clone[index], clone[index + 1]])\n }\n return Object.fromEntries(entries)\n}\n\nfunction matchHeaders (mockDispatch, headers) {\n if (typeof mockDispatch.headers === 'function') {\n if (Array.isArray(headers)) { // fetch HeadersList\n headers = buildHeadersFromArray(headers)\n }\n return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})\n }\n if (typeof mockDispatch.headers === 'undefined') {\n return true\n }\n if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {\n return false\n }\n\n for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {\n const headerValue = getHeaderByName(headers, matchHeaderName)\n\n if (!matchValue(matchHeaderValue, headerValue)) {\n return false\n }\n }\n return true\n}\n\nfunction safeUrl (path) {\n if (typeof path !== 'string') {\n return path\n }\n\n const pathSegments = path.split('?')\n\n if (pathSegments.length !== 2) {\n return path\n }\n\n const qp = new URLSearchParams(pathSegments.pop())\n qp.sort()\n return [...pathSegments, qp.toString()].join('?')\n}\n\nfunction matchKey (mockDispatch, { path, method, body, headers }) {\n const pathMatch = matchValue(mockDispatch.path, path)\n const methodMatch = matchValue(mockDispatch.method, method)\n const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true\n const headersMatch = matchHeaders(mockDispatch, headers)\n return pathMatch && methodMatch && bodyMatch && headersMatch\n}\n\nfunction getResponseData (data) {\n if (Buffer.isBuffer(data)) {\n return data\n } else if (typeof data === 'object') {\n return JSON.stringify(data)\n } else {\n return data.toString()\n }\n}\n\nfunction getMockDispatch (mockDispatches, key) {\n const basePath = key.query ? buildURL(key.path, key.query) : key.path\n const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath\n\n // Match path\n let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)\n }\n\n // Match method\n matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)\n }\n\n // Match body\n matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)\n }\n\n // Match headers\n matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)\n }\n\n return matchedMockDispatches[0]\n}\n\nfunction addMockDispatch (mockDispatches, key, data) {\n const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }\n const replyData = typeof data === 'function' ? { callback: data } : { ...data }\n const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }\n mockDispatches.push(newMockDispatch)\n return newMockDispatch\n}\n\nfunction deleteMockDispatch (mockDispatches, key) {\n const index = mockDispatches.findIndex(dispatch => {\n if (!dispatch.consumed) {\n return false\n }\n return matchKey(dispatch, key)\n })\n if (index !== -1) {\n mockDispatches.splice(index, 1)\n }\n}\n\nfunction buildKey (opts) {\n const { path, method, body, headers, query } = opts\n return {\n path,\n method,\n body,\n headers,\n query\n }\n}\n\nfunction generateKeyValues (data) {\n return Object.entries(data).reduce((keyValuePairs, [key, value]) => [\n ...keyValuePairs,\n Buffer.from(`${key}`),\n Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)\n ], [])\n}\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status\n * @param {number} statusCode\n */\nfunction getStatusText (statusCode) {\n return STATUS_CODES[statusCode] || 'unknown'\n}\n\nasync function getResponse (body) {\n const buffers = []\n for await (const data of body) {\n buffers.push(data)\n }\n return Buffer.concat(buffers).toString('utf8')\n}\n\n/**\n * Mock dispatch function used to simulate undici dispatches\n */\nfunction mockDispatch (opts, handler) {\n // Get mock dispatch from built key\n const key = buildKey(opts)\n const mockDispatch = getMockDispatch(this[kDispatches], key)\n\n mockDispatch.timesInvoked++\n\n // Here's where we resolve a callback if a callback is present for the dispatch data.\n if (mockDispatch.data.callback) {\n mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }\n }\n\n // Parse mockDispatch data\n const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch\n const { timesInvoked, times } = mockDispatch\n\n // If it's used up and not persistent, mark as consumed\n mockDispatch.consumed = !persist && timesInvoked >= times\n mockDispatch.pending = timesInvoked < times\n\n // If specified, trigger dispatch error\n if (error !== null) {\n deleteMockDispatch(this[kDispatches], key)\n handler.onError(error)\n return true\n }\n\n // Handle the request with a delay if necessary\n if (typeof delay === 'number' && delay > 0) {\n setTimeout(() => {\n handleReply(this[kDispatches])\n }, delay)\n } else {\n handleReply(this[kDispatches])\n }\n\n function handleReply (mockDispatches, _data = data) {\n // fetch's HeadersList is a 1D string array\n const optsHeaders = Array.isArray(opts.headers)\n ? buildHeadersFromArray(opts.headers)\n : opts.headers\n const body = typeof _data === 'function'\n ? _data({ ...opts, headers: optsHeaders })\n : _data\n\n // util.types.isPromise is likely needed for jest.\n if (isPromise(body)) {\n // If handleReply is asynchronous, throwing an error\n // in the callback will reject the promise, rather than\n // synchronously throw the error, which breaks some tests.\n // Rather, we wait for the callback to resolve if it is a\n // promise, and then re-run handleReply with the new body.\n body.then((newData) => handleReply(mockDispatches, newData))\n return\n }\n\n const responseData = getResponseData(body)\n const responseHeaders = generateKeyValues(headers)\n const responseTrailers = generateKeyValues(trailers)\n\n handler.abort = nop\n handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))\n handler.onData(Buffer.from(responseData))\n handler.onComplete(responseTrailers)\n deleteMockDispatch(mockDispatches, key)\n }\n\n function resume () {}\n\n return true\n}\n\nfunction buildMockDispatch () {\n const agent = this[kMockAgent]\n const origin = this[kOrigin]\n const originalDispatch = this[kOriginalDispatch]\n\n return function dispatch (opts, handler) {\n if (agent.isMockActive) {\n try {\n mockDispatch.call(this, opts, handler)\n } catch (error) {\n if (error instanceof MockNotMatchedError) {\n const netConnect = agent[kGetNetConnect]()\n if (netConnect === false) {\n throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)\n }\n if (checkNetConnect(netConnect, origin)) {\n originalDispatch.call(this, opts, handler)\n } else {\n throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)\n }\n } else {\n throw error\n }\n }\n } else {\n originalDispatch.call(this, opts, handler)\n }\n }\n}\n\nfunction checkNetConnect (netConnect, origin) {\n const url = new URL(origin)\n if (netConnect === true) {\n return true\n } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {\n return true\n }\n return false\n}\n\nfunction buildMockOptions (opts) {\n if (opts) {\n const { agent, ...mockOptions } = opts\n return mockOptions\n }\n}\n\nmodule.exports = {\n getResponseData,\n getMockDispatch,\n addMockDispatch,\n deleteMockDispatch,\n buildKey,\n generateKeyValues,\n matchValue,\n getResponse,\n getStatusText,\n mockDispatch,\n buildMockDispatch,\n checkNetConnect,\n buildMockOptions,\n getHeaderByName\n}\n","'use strict'\n\nconst { Transform } = require('stream')\nconst { Console } = require('console')\n\n/**\n * Gets the output of `console.table(…)` as a string.\n */\nmodule.exports = class PendingInterceptorsFormatter {\n constructor ({ disableColors } = {}) {\n this.transform = new Transform({\n transform (chunk, _enc, cb) {\n cb(null, chunk)\n }\n })\n\n this.logger = new Console({\n stdout: this.transform,\n inspectOptions: {\n colors: !disableColors && !process.env.CI\n }\n })\n }\n\n format (pendingInterceptors) {\n const withPrettyHeaders = pendingInterceptors.map(\n ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({\n Method: method,\n Origin: origin,\n Path: path,\n 'Status code': statusCode,\n Persistent: persist ? '✅' : '❌',\n Invocations: timesInvoked,\n Remaining: persist ? Infinity : times - timesInvoked\n }))\n\n this.logger.table(withPrettyHeaders)\n return this.transform.read().toString()\n }\n}\n","'use strict'\n\nconst singulars = {\n pronoun: 'it',\n is: 'is',\n was: 'was',\n this: 'this'\n}\n\nconst plurals = {\n pronoun: 'they',\n is: 'are',\n was: 'were',\n this: 'these'\n}\n\nmodule.exports = class Pluralizer {\n constructor (singular, plural) {\n this.singular = singular\n this.plural = plural\n }\n\n pluralize (count) {\n const one = count === 1\n const keys = one ? singulars : plurals\n const noun = one ? this.singular : this.plural\n return { ...keys, count, noun }\n }\n}\n","/* eslint-disable */\n\n'use strict'\n\n// Extracted from node/lib/internal/fixed_queue.js\n\n// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.\nconst kSize = 2048;\nconst kMask = kSize - 1;\n\n// The FixedQueue is implemented as a singly-linked list of fixed-size\n// circular buffers. It looks something like this:\n//\n// head tail\n// | |\n// v v\n// +-----------+ <-----\\ +-----------+ <------\\ +-----------+\n// | [null] | \\----- | next | \\------- | next |\n// +-----------+ +-----------+ +-----------+\n// | item | <-- bottom | item | <-- bottom | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | bottom --> | item |\n// | item | | item | | item |\n// | ... | | ... | | ... |\n// | item | | item | | item |\n// | item | | item | | item |\n// | [empty] | <-- top | item | | item |\n// | [empty] | | item | | item |\n// | [empty] | | [empty] | <-- top top --> | [empty] |\n// +-----------+ +-----------+ +-----------+\n//\n// Or, if there is only one circular buffer, it looks something\n// like either of these:\n//\n// head tail head tail\n// | | | |\n// v v v v\n// +-----------+ +-----------+\n// | [null] | | [null] |\n// +-----------+ +-----------+\n// | [empty] | | item |\n// | [empty] | | item |\n// | item | <-- bottom top --> | [empty] |\n// | item | | [empty] |\n// | [empty] | <-- top bottom --> | item |\n// | [empty] | | item |\n// +-----------+ +-----------+\n//\n// Adding a value means moving `top` forward by one, removing means\n// moving `bottom` forward by one. After reaching the end, the queue\n// wraps around.\n//\n// When `top === bottom` the current queue is empty and when\n// `top + 1 === bottom` it's full. This wastes a single space of storage\n// but allows much quicker checks.\n\nclass FixedCircularBuffer {\n constructor() {\n this.bottom = 0;\n this.top = 0;\n this.list = new Array(kSize);\n this.next = null;\n }\n\n isEmpty() {\n return this.top === this.bottom;\n }\n\n isFull() {\n return ((this.top + 1) & kMask) === this.bottom;\n }\n\n push(data) {\n this.list[this.top] = data;\n this.top = (this.top + 1) & kMask;\n }\n\n shift() {\n const nextItem = this.list[this.bottom];\n if (nextItem === undefined)\n return null;\n this.list[this.bottom] = undefined;\n this.bottom = (this.bottom + 1) & kMask;\n return nextItem;\n }\n}\n\nmodule.exports = class FixedQueue {\n constructor() {\n this.head = this.tail = new FixedCircularBuffer();\n }\n\n isEmpty() {\n return this.head.isEmpty();\n }\n\n push(data) {\n if (this.head.isFull()) {\n // Head is full: Creates a new queue, sets the old queue's `.next` to it,\n // and sets it as the new main queue.\n this.head = this.head.next = new FixedCircularBuffer();\n }\n this.head.push(data);\n }\n\n shift() {\n const tail = this.tail;\n const next = tail.shift();\n if (tail.isEmpty() && tail.next !== null) {\n // If there is another queue, it forms the new tail.\n this.tail = tail.next;\n }\n return next;\n }\n};\n","'use strict'\n\nconst DispatcherBase = require('./dispatcher-base')\nconst FixedQueue = require('./node/fixed-queue')\nconst { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('./core/symbols')\nconst PoolStats = require('./pool-stats')\n\nconst kClients = Symbol('clients')\nconst kNeedDrain = Symbol('needDrain')\nconst kQueue = Symbol('queue')\nconst kClosedResolve = Symbol('closed resolve')\nconst kOnDrain = Symbol('onDrain')\nconst kOnConnect = Symbol('onConnect')\nconst kOnDisconnect = Symbol('onDisconnect')\nconst kOnConnectionError = Symbol('onConnectionError')\nconst kGetDispatcher = Symbol('get dispatcher')\nconst kAddClient = Symbol('add client')\nconst kRemoveClient = Symbol('remove client')\nconst kStats = Symbol('stats')\n\nclass PoolBase extends DispatcherBase {\n constructor () {\n super()\n\n this[kQueue] = new FixedQueue()\n this[kClients] = []\n this[kQueued] = 0\n\n const pool = this\n\n this[kOnDrain] = function onDrain (origin, targets) {\n const queue = pool[kQueue]\n\n let needDrain = false\n\n while (!needDrain) {\n const item = queue.shift()\n if (!item) {\n break\n }\n pool[kQueued]--\n needDrain = !this.dispatch(item.opts, item.handler)\n }\n\n this[kNeedDrain] = needDrain\n\n if (!this[kNeedDrain] && pool[kNeedDrain]) {\n pool[kNeedDrain] = false\n pool.emit('drain', origin, [pool, ...targets])\n }\n\n if (pool[kClosedResolve] && queue.isEmpty()) {\n Promise\n .all(pool[kClients].map(c => c.close()))\n .then(pool[kClosedResolve])\n }\n }\n\n this[kOnConnect] = (origin, targets) => {\n pool.emit('connect', origin, [pool, ...targets])\n }\n\n this[kOnDisconnect] = (origin, targets, err) => {\n pool.emit('disconnect', origin, [pool, ...targets], err)\n }\n\n this[kOnConnectionError] = (origin, targets, err) => {\n pool.emit('connectionError', origin, [pool, ...targets], err)\n }\n\n this[kStats] = new PoolStats(this)\n }\n\n get [kBusy] () {\n return this[kNeedDrain]\n }\n\n get [kConnected] () {\n return this[kClients].filter(client => client[kConnected]).length\n }\n\n get [kFree] () {\n return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length\n }\n\n get [kPending] () {\n let ret = this[kQueued]\n for (const { [kPending]: pending } of this[kClients]) {\n ret += pending\n }\n return ret\n }\n\n get [kRunning] () {\n let ret = 0\n for (const { [kRunning]: running } of this[kClients]) {\n ret += running\n }\n return ret\n }\n\n get [kSize] () {\n let ret = this[kQueued]\n for (const { [kSize]: size } of this[kClients]) {\n ret += size\n }\n return ret\n }\n\n get stats () {\n return this[kStats]\n }\n\n async [kClose] () {\n if (this[kQueue].isEmpty()) {\n return Promise.all(this[kClients].map(c => c.close()))\n } else {\n return new Promise((resolve) => {\n this[kClosedResolve] = resolve\n })\n }\n }\n\n async [kDestroy] (err) {\n while (true) {\n const item = this[kQueue].shift()\n if (!item) {\n break\n }\n item.handler.onError(err)\n }\n\n return Promise.all(this[kClients].map(c => c.destroy(err)))\n }\n\n [kDispatch] (opts, handler) {\n const dispatcher = this[kGetDispatcher]()\n\n if (!dispatcher) {\n this[kNeedDrain] = true\n this[kQueue].push({ opts, handler })\n this[kQueued]++\n } else if (!dispatcher.dispatch(opts, handler)) {\n dispatcher[kNeedDrain] = true\n this[kNeedDrain] = !this[kGetDispatcher]()\n }\n\n return !this[kNeedDrain]\n }\n\n [kAddClient] (client) {\n client\n .on('drain', this[kOnDrain])\n .on('connect', this[kOnConnect])\n .on('disconnect', this[kOnDisconnect])\n .on('connectionError', this[kOnConnectionError])\n\n this[kClients].push(client)\n\n if (this[kNeedDrain]) {\n process.nextTick(() => {\n if (this[kNeedDrain]) {\n this[kOnDrain](client[kUrl], [this, client])\n }\n })\n }\n\n return this\n }\n\n [kRemoveClient] (client) {\n client.close(() => {\n const idx = this[kClients].indexOf(client)\n if (idx !== -1) {\n this[kClients].splice(idx, 1)\n }\n })\n\n this[kNeedDrain] = this[kClients].some(dispatcher => (\n !dispatcher[kNeedDrain] &&\n dispatcher.closed !== true &&\n dispatcher.destroyed !== true\n ))\n }\n}\n\nmodule.exports = {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kRemoveClient,\n kGetDispatcher\n}\n","const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require('./core/symbols')\nconst kPool = Symbol('pool')\n\nclass PoolStats {\n constructor (pool) {\n this[kPool] = pool\n }\n\n get connected () {\n return this[kPool][kConnected]\n }\n\n get free () {\n return this[kPool][kFree]\n }\n\n get pending () {\n return this[kPool][kPending]\n }\n\n get queued () {\n return this[kPool][kQueued]\n }\n\n get running () {\n return this[kPool][kRunning]\n }\n\n get size () {\n return this[kPool][kSize]\n }\n}\n\nmodule.exports = PoolStats\n","'use strict'\n\nconst {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kGetDispatcher\n} = require('./pool-base')\nconst Client = require('./client')\nconst {\n InvalidArgumentError\n} = require('./core/errors')\nconst util = require('./core/util')\nconst { kUrl, kInterceptors } = require('./core/symbols')\nconst buildConnector = require('./core/connect')\n\nconst kOptions = Symbol('options')\nconst kConnections = Symbol('connections')\nconst kFactory = Symbol('factory')\n\nfunction defaultFactory (origin, opts) {\n return new Client(origin, opts)\n}\n\nclass Pool extends PoolBase {\n constructor (origin, {\n connections,\n factory = defaultFactory,\n connect,\n connectTimeout,\n tls,\n maxCachedSessions,\n socketPath,\n autoSelectFamily,\n autoSelectFamilyAttemptTimeout,\n allowH2,\n ...options\n } = {}) {\n super()\n\n if (connections != null && (!Number.isFinite(connections) || connections < 0)) {\n throw new InvalidArgumentError('invalid connections')\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (typeof connect !== 'function') {\n connect = buildConnector({\n ...tls,\n maxCachedSessions,\n allowH2,\n socketPath,\n timeout: connectTimeout,\n ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),\n ...connect\n })\n }\n\n this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)\n ? options.interceptors.Pool\n : []\n this[kConnections] = connections || null\n this[kUrl] = util.parseOrigin(origin)\n this[kOptions] = { ...util.deepClone(options), connect, allowH2 }\n this[kOptions].interceptors = options.interceptors\n ? { ...options.interceptors }\n : undefined\n this[kFactory] = factory\n }\n\n [kGetDispatcher] () {\n let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])\n\n if (dispatcher) {\n return dispatcher\n }\n\n if (!this[kConnections] || this[kClients].length < this[kConnections]) {\n dispatcher = this[kFactory](this[kUrl], this[kOptions])\n this[kAddClient](dispatcher)\n }\n\n return dispatcher\n }\n}\n\nmodule.exports = Pool\n","'use strict'\n\nconst { kProxy, kClose, kDestroy, kInterceptors } = require('./core/symbols')\nconst { URL } = require('url')\nconst Agent = require('./agent')\nconst Pool = require('./pool')\nconst DispatcherBase = require('./dispatcher-base')\nconst { InvalidArgumentError, RequestAbortedError } = require('./core/errors')\nconst buildConnector = require('./core/connect')\n\nconst kAgent = Symbol('proxy agent')\nconst kClient = Symbol('proxy client')\nconst kProxyHeaders = Symbol('proxy headers')\nconst kRequestTls = Symbol('request tls settings')\nconst kProxyTls = Symbol('proxy tls settings')\nconst kConnectEndpoint = Symbol('connect endpoint function')\n\nfunction defaultProtocolPort (protocol) {\n return protocol === 'https:' ? 443 : 80\n}\n\nfunction buildProxyOptions (opts) {\n if (typeof opts === 'string') {\n opts = { uri: opts }\n }\n\n if (!opts || !opts.uri) {\n throw new InvalidArgumentError('Proxy opts.uri is mandatory')\n }\n\n return {\n uri: opts.uri,\n protocol: opts.protocol || 'https'\n }\n}\n\nfunction defaultFactory (origin, opts) {\n return new Pool(origin, opts)\n}\n\nclass ProxyAgent extends DispatcherBase {\n constructor (opts) {\n super(opts)\n this[kProxy] = buildProxyOptions(opts)\n this[kAgent] = new Agent(opts)\n this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)\n ? opts.interceptors.ProxyAgent\n : []\n\n if (typeof opts === 'string') {\n opts = { uri: opts }\n }\n\n if (!opts || !opts.uri) {\n throw new InvalidArgumentError('Proxy opts.uri is mandatory')\n }\n\n const { clientFactory = defaultFactory } = opts\n\n if (typeof clientFactory !== 'function') {\n throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')\n }\n\n this[kRequestTls] = opts.requestTls\n this[kProxyTls] = opts.proxyTls\n this[kProxyHeaders] = opts.headers || {}\n\n const resolvedUrl = new URL(opts.uri)\n const { origin, port, host, username, password } = resolvedUrl\n\n if (opts.auth && opts.token) {\n throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')\n } else if (opts.auth) {\n /* @deprecated in favour of opts.token */\n this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`\n } else if (opts.token) {\n this[kProxyHeaders]['proxy-authorization'] = opts.token\n } else if (username && password) {\n this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`\n }\n\n const connect = buildConnector({ ...opts.proxyTls })\n this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })\n this[kClient] = clientFactory(resolvedUrl, { connect })\n this[kAgent] = new Agent({\n ...opts,\n connect: async (opts, callback) => {\n let requestedHost = opts.host\n if (!opts.port) {\n requestedHost += `:${defaultProtocolPort(opts.protocol)}`\n }\n try {\n const { socket, statusCode } = await this[kClient].connect({\n origin,\n port,\n path: requestedHost,\n signal: opts.signal,\n headers: {\n ...this[kProxyHeaders],\n host\n }\n })\n if (statusCode !== 200) {\n socket.on('error', () => {}).destroy()\n callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))\n }\n if (opts.protocol !== 'https:') {\n callback(null, socket)\n return\n }\n let servername\n if (this[kRequestTls]) {\n servername = this[kRequestTls].servername\n } else {\n servername = opts.servername\n }\n this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)\n } catch (err) {\n callback(err)\n }\n }\n })\n }\n\n dispatch (opts, handler) {\n const { host } = new URL(opts.origin)\n const headers = buildHeaders(opts.headers)\n throwIfProxyAuthIsSent(headers)\n return this[kAgent].dispatch(\n {\n ...opts,\n headers: {\n ...headers,\n host\n }\n },\n handler\n )\n }\n\n async [kClose] () {\n await this[kAgent].close()\n await this[kClient].close()\n }\n\n async [kDestroy] () {\n await this[kAgent].destroy()\n await this[kClient].destroy()\n }\n}\n\n/**\n * @param {string[] | Record} headers\n * @returns {Record}\n */\nfunction buildHeaders (headers) {\n // When using undici.fetch, the headers list is stored\n // as an array.\n if (Array.isArray(headers)) {\n /** @type {Record} */\n const headersPair = {}\n\n for (let i = 0; i < headers.length; i += 2) {\n headersPair[headers[i]] = headers[i + 1]\n }\n\n return headersPair\n }\n\n return headers\n}\n\n/**\n * @param {Record} headers\n *\n * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers\n * Nevertheless, it was changed and to avoid a security vulnerability by end users\n * this check was created.\n * It should be removed in the next major version for performance reasons\n */\nfunction throwIfProxyAuthIsSent (headers) {\n const existProxyAuth = headers && Object.keys(headers)\n .find((key) => key.toLowerCase() === 'proxy-authorization')\n if (existProxyAuth) {\n throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')\n }\n}\n\nmodule.exports = ProxyAgent\n","'use strict'\n\nlet fastNow = Date.now()\nlet fastNowTimeout\n\nconst fastTimers = []\n\nfunction onTimeout () {\n fastNow = Date.now()\n\n let len = fastTimers.length\n let idx = 0\n while (idx < len) {\n const timer = fastTimers[idx]\n\n if (timer.state === 0) {\n timer.state = fastNow + timer.delay\n } else if (timer.state > 0 && fastNow >= timer.state) {\n timer.state = -1\n timer.callback(timer.opaque)\n }\n\n if (timer.state === -1) {\n timer.state = -2\n if (idx !== len - 1) {\n fastTimers[idx] = fastTimers.pop()\n } else {\n fastTimers.pop()\n }\n len -= 1\n } else {\n idx += 1\n }\n }\n\n if (fastTimers.length > 0) {\n refreshTimeout()\n }\n}\n\nfunction refreshTimeout () {\n if (fastNowTimeout && fastNowTimeout.refresh) {\n fastNowTimeout.refresh()\n } else {\n clearTimeout(fastNowTimeout)\n fastNowTimeout = setTimeout(onTimeout, 1e3)\n if (fastNowTimeout.unref) {\n fastNowTimeout.unref()\n }\n }\n}\n\nclass Timeout {\n constructor (callback, delay, opaque) {\n this.callback = callback\n this.delay = delay\n this.opaque = opaque\n\n // -2 not in timer list\n // -1 in timer list but inactive\n // 0 in timer list waiting for time\n // > 0 in timer list waiting for time to expire\n this.state = -2\n\n this.refresh()\n }\n\n refresh () {\n if (this.state === -2) {\n fastTimers.push(this)\n if (!fastNowTimeout || fastTimers.length === 1) {\n refreshTimeout()\n }\n }\n\n this.state = 0\n }\n\n clear () {\n this.state = -1\n }\n}\n\nmodule.exports = {\n setTimeout (callback, delay, opaque) {\n return delay < 1e3\n ? setTimeout(callback, delay, opaque)\n : new Timeout(callback, delay, opaque)\n },\n clearTimeout (timeout) {\n if (timeout instanceof Timeout) {\n timeout.clear()\n } else {\n clearTimeout(timeout)\n }\n }\n}\n","'use strict'\n\nconst diagnosticsChannel = require('diagnostics_channel')\nconst { uid, states } = require('./constants')\nconst {\n kReadyState,\n kSentClose,\n kByteParser,\n kReceivedClose\n} = require('./symbols')\nconst { fireEvent, failWebsocketConnection } = require('./util')\nconst { CloseEvent } = require('./events')\nconst { makeRequest } = require('../fetch/request')\nconst { fetching } = require('../fetch/index')\nconst { Headers } = require('../fetch/headers')\nconst { getGlobalDispatcher } = require('../global')\nconst { kHeadersList } = require('../core/symbols')\n\nconst channels = {}\nchannels.open = diagnosticsChannel.channel('undici:websocket:open')\nchannels.close = diagnosticsChannel.channel('undici:websocket:close')\nchannels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')\n\n/** @type {import('crypto')} */\nlet crypto\ntry {\n crypto = require('crypto')\n} catch {\n\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#concept-websocket-establish\n * @param {URL} url\n * @param {string|string[]} protocols\n * @param {import('./websocket').WebSocket} ws\n * @param {(response: any) => void} onEstablish\n * @param {Partial} options\n */\nfunction establishWebSocketConnection (url, protocols, ws, onEstablish, options) {\n // 1. Let requestURL be a copy of url, with its scheme set to \"http\", if url’s\n // scheme is \"ws\", and to \"https\" otherwise.\n const requestURL = url\n\n requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'\n\n // 2. Let request be a new request, whose URL is requestURL, client is client,\n // service-workers mode is \"none\", referrer is \"no-referrer\", mode is\n // \"websocket\", credentials mode is \"include\", cache mode is \"no-store\" ,\n // and redirect mode is \"error\".\n const request = makeRequest({\n urlList: [requestURL],\n serviceWorkers: 'none',\n referrer: 'no-referrer',\n mode: 'websocket',\n credentials: 'include',\n cache: 'no-store',\n redirect: 'error'\n })\n\n // Note: undici extension, allow setting custom headers.\n if (options.headers) {\n const headersList = new Headers(options.headers)[kHeadersList]\n\n request.headersList = headersList\n }\n\n // 3. Append (`Upgrade`, `websocket`) to request’s header list.\n // 4. Append (`Connection`, `Upgrade`) to request’s header list.\n // Note: both of these are handled by undici currently.\n // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397\n\n // 5. Let keyValue be a nonce consisting of a randomly selected\n // 16-byte value that has been forgiving-base64-encoded and\n // isomorphic encoded.\n const keyValue = crypto.randomBytes(16).toString('base64')\n\n // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s\n // header list.\n request.headersList.append('sec-websocket-key', keyValue)\n\n // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s\n // header list.\n request.headersList.append('sec-websocket-version', '13')\n\n // 8. For each protocol in protocols, combine\n // (`Sec-WebSocket-Protocol`, protocol) in request’s header\n // list.\n for (const protocol of protocols) {\n request.headersList.append('sec-websocket-protocol', protocol)\n }\n\n // 9. Let permessageDeflate be a user-agent defined\n // \"permessage-deflate\" extension header value.\n // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673\n // TODO: enable once permessage-deflate is supported\n const permessageDeflate = '' // 'permessage-deflate; 15'\n\n // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to\n // request’s header list.\n // request.headersList.append('sec-websocket-extensions', permessageDeflate)\n\n // 11. Fetch request with useParallelQueue set to true, and\n // processResponse given response being these steps:\n const controller = fetching({\n request,\n useParallelQueue: true,\n dispatcher: options.dispatcher ?? getGlobalDispatcher(),\n processResponse (response) {\n // 1. If response is a network error or its status is not 101,\n // fail the WebSocket connection.\n if (response.type === 'error' || response.status !== 101) {\n failWebsocketConnection(ws, 'Received network error or non-101 status code.')\n return\n }\n\n // 2. If protocols is not the empty list and extracting header\n // list values given `Sec-WebSocket-Protocol` and response’s\n // header list results in null, failure, or the empty byte\n // sequence, then fail the WebSocket connection.\n if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {\n failWebsocketConnection(ws, 'Server did not respond with sent protocols.')\n return\n }\n\n // 3. Follow the requirements stated step 2 to step 6, inclusive,\n // of the last set of steps in section 4.1 of The WebSocket\n // Protocol to validate response. This either results in fail\n // the WebSocket connection or the WebSocket connection is\n // established.\n\n // 2. If the response lacks an |Upgrade| header field or the |Upgrade|\n // header field contains a value that is not an ASCII case-\n // insensitive match for the value \"websocket\", the client MUST\n // _Fail the WebSocket Connection_.\n if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {\n failWebsocketConnection(ws, 'Server did not set Upgrade header to \"websocket\".')\n return\n }\n\n // 3. If the response lacks a |Connection| header field or the\n // |Connection| header field doesn't contain a token that is an\n // ASCII case-insensitive match for the value \"Upgrade\", the client\n // MUST _Fail the WebSocket Connection_.\n if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {\n failWebsocketConnection(ws, 'Server did not set Connection header to \"upgrade\".')\n return\n }\n\n // 4. If the response lacks a |Sec-WebSocket-Accept| header field or\n // the |Sec-WebSocket-Accept| contains a value other than the\n // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-\n // Key| (as a string, not base64-decoded) with the string \"258EAFA5-\n // E914-47DA-95CA-C5AB0DC85B11\" but ignoring any leading and\n // trailing whitespace, the client MUST _Fail the WebSocket\n // Connection_.\n const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')\n const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')\n if (secWSAccept !== digest) {\n failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')\n return\n }\n\n // 5. If the response includes a |Sec-WebSocket-Extensions| header\n // field and this header field indicates the use of an extension\n // that was not present in the client's handshake (the server has\n // indicated an extension not requested by the client), the client\n // MUST _Fail the WebSocket Connection_. (The parsing of this\n // header field to determine which extensions are requested is\n // discussed in Section 9.1.)\n const secExtension = response.headersList.get('Sec-WebSocket-Extensions')\n\n if (secExtension !== null && secExtension !== permessageDeflate) {\n failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')\n return\n }\n\n // 6. If the response includes a |Sec-WebSocket-Protocol| header field\n // and this header field indicates the use of a subprotocol that was\n // not present in the client's handshake (the server has indicated a\n // subprotocol not requested by the client), the client MUST _Fail\n // the WebSocket Connection_.\n const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')\n\n if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {\n failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')\n return\n }\n\n response.socket.on('data', onSocketData)\n response.socket.on('close', onSocketClose)\n response.socket.on('error', onSocketError)\n\n if (channels.open.hasSubscribers) {\n channels.open.publish({\n address: response.socket.address(),\n protocol: secProtocol,\n extensions: secExtension\n })\n }\n\n onEstablish(response)\n }\n })\n\n return controller\n}\n\n/**\n * @param {Buffer} chunk\n */\nfunction onSocketData (chunk) {\n if (!this.ws[kByteParser].write(chunk)) {\n this.pause()\n }\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4\n */\nfunction onSocketClose () {\n const { ws } = this\n\n // If the TCP connection was closed after the\n // WebSocket closing handshake was completed, the WebSocket connection\n // is said to have been closed _cleanly_.\n const wasClean = ws[kSentClose] && ws[kReceivedClose]\n\n let code = 1005\n let reason = ''\n\n const result = ws[kByteParser].closingInfo\n\n if (result) {\n code = result.code ?? 1005\n reason = result.reason\n } else if (!ws[kSentClose]) {\n // If _The WebSocket\n // Connection is Closed_ and no Close control frame was received by the\n // endpoint (such as could occur if the underlying transport connection\n // is lost), _The WebSocket Connection Close Code_ is considered to be\n // 1006.\n code = 1006\n }\n\n // 1. Change the ready state to CLOSED (3).\n ws[kReadyState] = states.CLOSED\n\n // 2. If the user agent was required to fail the WebSocket\n // connection, or if the WebSocket connection was closed\n // after being flagged as full, fire an event named error\n // at the WebSocket object.\n // TODO\n\n // 3. Fire an event named close at the WebSocket object,\n // using CloseEvent, with the wasClean attribute\n // initialized to true if the connection closed cleanly\n // and false otherwise, the code attribute initialized to\n // the WebSocket connection close code, and the reason\n // attribute initialized to the result of applying UTF-8\n // decode without BOM to the WebSocket connection close\n // reason.\n fireEvent('close', ws, CloseEvent, {\n wasClean, code, reason\n })\n\n if (channels.close.hasSubscribers) {\n channels.close.publish({\n websocket: ws,\n code,\n reason\n })\n }\n}\n\nfunction onSocketError (error) {\n const { ws } = this\n\n ws[kReadyState] = states.CLOSING\n\n if (channels.socketError.hasSubscribers) {\n channels.socketError.publish(error)\n }\n\n this.destroy()\n}\n\nmodule.exports = {\n establishWebSocketConnection\n}\n","'use strict'\n\n// This is a Globally Unique Identifier unique used\n// to validate that the endpoint accepts websocket\n// connections.\n// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3\nconst uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n\n/** @type {PropertyDescriptor} */\nconst staticPropertyDescriptors = {\n enumerable: true,\n writable: false,\n configurable: false\n}\n\nconst states = {\n CONNECTING: 0,\n OPEN: 1,\n CLOSING: 2,\n CLOSED: 3\n}\n\nconst opcodes = {\n CONTINUATION: 0x0,\n TEXT: 0x1,\n BINARY: 0x2,\n CLOSE: 0x8,\n PING: 0x9,\n PONG: 0xA\n}\n\nconst maxUnsigned16Bit = 2 ** 16 - 1 // 65535\n\nconst parserStates = {\n INFO: 0,\n PAYLOADLENGTH_16: 2,\n PAYLOADLENGTH_64: 3,\n READ_DATA: 4\n}\n\nconst emptyBuffer = Buffer.allocUnsafe(0)\n\nmodule.exports = {\n uid,\n staticPropertyDescriptors,\n states,\n opcodes,\n maxUnsigned16Bit,\n parserStates,\n emptyBuffer\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\nconst { MessagePort } = require('worker_threads')\n\n/**\n * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent\n */\nclass MessageEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.MessageEventInit(eventInitDict)\n\n super(type, eventInitDict)\n\n this.#eventInit = eventInitDict\n }\n\n get data () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.data\n }\n\n get origin () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.origin\n }\n\n get lastEventId () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.lastEventId\n }\n\n get source () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.source\n }\n\n get ports () {\n webidl.brandCheck(this, MessageEvent)\n\n if (!Object.isFrozen(this.#eventInit.ports)) {\n Object.freeze(this.#eventInit.ports)\n }\n\n return this.#eventInit.ports\n }\n\n initMessageEvent (\n type,\n bubbles = false,\n cancelable = false,\n data = null,\n origin = '',\n lastEventId = '',\n source = null,\n ports = []\n ) {\n webidl.brandCheck(this, MessageEvent)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })\n\n return new MessageEvent(type, {\n bubbles, cancelable, data, origin, lastEventId, source, ports\n })\n }\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#the-closeevent-interface\n */\nclass CloseEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.CloseEventInit(eventInitDict)\n\n super(type, eventInitDict)\n\n this.#eventInit = eventInitDict\n }\n\n get wasClean () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.wasClean\n }\n\n get code () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.code\n }\n\n get reason () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.reason\n }\n}\n\n// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface\nclass ErrorEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })\n\n super(type, eventInitDict)\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})\n\n this.#eventInit = eventInitDict\n }\n\n get message () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.message\n }\n\n get filename () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.filename\n }\n\n get lineno () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.lineno\n }\n\n get colno () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.colno\n }\n\n get error () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.error\n }\n}\n\nObject.defineProperties(MessageEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'MessageEvent',\n configurable: true\n },\n data: kEnumerableProperty,\n origin: kEnumerableProperty,\n lastEventId: kEnumerableProperty,\n source: kEnumerableProperty,\n ports: kEnumerableProperty,\n initMessageEvent: kEnumerableProperty\n})\n\nObject.defineProperties(CloseEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'CloseEvent',\n configurable: true\n },\n reason: kEnumerableProperty,\n code: kEnumerableProperty,\n wasClean: kEnumerableProperty\n})\n\nObject.defineProperties(ErrorEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'ErrorEvent',\n configurable: true\n },\n message: kEnumerableProperty,\n filename: kEnumerableProperty,\n lineno: kEnumerableProperty,\n colno: kEnumerableProperty,\n error: kEnumerableProperty\n})\n\nwebidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.MessagePort\n)\n\nconst eventInit = [\n {\n key: 'bubbles',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'cancelable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'composed',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n]\n\nwebidl.converters.MessageEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'data',\n converter: webidl.converters.any,\n defaultValue: null\n },\n {\n key: 'origin',\n converter: webidl.converters.USVString,\n defaultValue: ''\n },\n {\n key: 'lastEventId',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'source',\n // Node doesn't implement WindowProxy or ServiceWorker, so the only\n // valid value for source is a MessagePort.\n converter: webidl.nullableConverter(webidl.converters.MessagePort),\n defaultValue: null\n },\n {\n key: 'ports',\n converter: webidl.converters['sequence'],\n get defaultValue () {\n return []\n }\n }\n])\n\nwebidl.converters.CloseEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'wasClean',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'code',\n converter: webidl.converters['unsigned short'],\n defaultValue: 0\n },\n {\n key: 'reason',\n converter: webidl.converters.USVString,\n defaultValue: ''\n }\n])\n\nwebidl.converters.ErrorEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'message',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'filename',\n converter: webidl.converters.USVString,\n defaultValue: ''\n },\n {\n key: 'lineno',\n converter: webidl.converters['unsigned long'],\n defaultValue: 0\n },\n {\n key: 'colno',\n converter: webidl.converters['unsigned long'],\n defaultValue: 0\n },\n {\n key: 'error',\n converter: webidl.converters.any\n }\n])\n\nmodule.exports = {\n MessageEvent,\n CloseEvent,\n ErrorEvent\n}\n","'use strict'\n\nconst { maxUnsigned16Bit } = require('./constants')\n\n/** @type {import('crypto')} */\nlet crypto\ntry {\n crypto = require('crypto')\n} catch {\n\n}\n\nclass WebsocketFrameSend {\n /**\n * @param {Buffer|undefined} data\n */\n constructor (data) {\n this.frameData = data\n this.maskKey = crypto.randomBytes(4)\n }\n\n createFrame (opcode) {\n const bodyLength = this.frameData?.byteLength ?? 0\n\n /** @type {number} */\n let payloadLength = bodyLength // 0-125\n let offset = 6\n\n if (bodyLength > maxUnsigned16Bit) {\n offset += 8 // payload length is next 8 bytes\n payloadLength = 127\n } else if (bodyLength > 125) {\n offset += 2 // payload length is next 2 bytes\n payloadLength = 126\n }\n\n const buffer = Buffer.allocUnsafe(bodyLength + offset)\n\n // Clear first 2 bytes, everything else is overwritten\n buffer[0] = buffer[1] = 0\n buffer[0] |= 0x80 // FIN\n buffer[0] = (buffer[0] & 0xF0) + opcode // opcode\n\n /*! ws. MIT License. Einar Otto Stangvik */\n buffer[offset - 4] = this.maskKey[0]\n buffer[offset - 3] = this.maskKey[1]\n buffer[offset - 2] = this.maskKey[2]\n buffer[offset - 1] = this.maskKey[3]\n\n buffer[1] = payloadLength\n\n if (payloadLength === 126) {\n buffer.writeUInt16BE(bodyLength, 2)\n } else if (payloadLength === 127) {\n // Clear extended payload length\n buffer[2] = buffer[3] = 0\n buffer.writeUIntBE(bodyLength, 4, 6)\n }\n\n buffer[1] |= 0x80 // MASK\n\n // mask body\n for (let i = 0; i < bodyLength; i++) {\n buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]\n }\n\n return buffer\n }\n}\n\nmodule.exports = {\n WebsocketFrameSend\n}\n","'use strict'\n\nconst { Writable } = require('stream')\nconst diagnosticsChannel = require('diagnostics_channel')\nconst { parserStates, opcodes, states, emptyBuffer } = require('./constants')\nconst { kReadyState, kSentClose, kResponse, kReceivedClose } = require('./symbols')\nconst { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = require('./util')\nconst { WebsocketFrameSend } = require('./frame')\n\n// This code was influenced by ws released under the MIT license.\n// Copyright (c) 2011 Einar Otto Stangvik \n// Copyright (c) 2013 Arnout Kazemier and contributors\n// Copyright (c) 2016 Luigi Pinca and contributors\n\nconst channels = {}\nchannels.ping = diagnosticsChannel.channel('undici:websocket:ping')\nchannels.pong = diagnosticsChannel.channel('undici:websocket:pong')\n\nclass ByteParser extends Writable {\n #buffers = []\n #byteOffset = 0\n\n #state = parserStates.INFO\n\n #info = {}\n #fragments = []\n\n constructor (ws) {\n super()\n\n this.ws = ws\n }\n\n /**\n * @param {Buffer} chunk\n * @param {() => void} callback\n */\n _write (chunk, _, callback) {\n this.#buffers.push(chunk)\n this.#byteOffset += chunk.length\n\n this.run(callback)\n }\n\n /**\n * Runs whenever a new chunk is received.\n * Callback is called whenever there are no more chunks buffering,\n * or not enough bytes are buffered to parse.\n */\n run (callback) {\n while (true) {\n if (this.#state === parserStates.INFO) {\n // If there aren't enough bytes to parse the payload length, etc.\n if (this.#byteOffset < 2) {\n return callback()\n }\n\n const buffer = this.consume(2)\n\n this.#info.fin = (buffer[0] & 0x80) !== 0\n this.#info.opcode = buffer[0] & 0x0F\n\n // If we receive a fragmented message, we use the type of the first\n // frame to parse the full message as binary/text, when it's terminated\n this.#info.originalOpcode ??= this.#info.opcode\n\n this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION\n\n if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {\n // Only text and binary frames can be fragmented\n failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')\n return\n }\n\n const payloadLength = buffer[1] & 0x7F\n\n if (payloadLength <= 125) {\n this.#info.payloadLength = payloadLength\n this.#state = parserStates.READ_DATA\n } else if (payloadLength === 126) {\n this.#state = parserStates.PAYLOADLENGTH_16\n } else if (payloadLength === 127) {\n this.#state = parserStates.PAYLOADLENGTH_64\n }\n\n if (this.#info.fragmented && payloadLength > 125) {\n // A fragmented frame can't be fragmented itself\n failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')\n return\n } else if (\n (this.#info.opcode === opcodes.PING ||\n this.#info.opcode === opcodes.PONG ||\n this.#info.opcode === opcodes.CLOSE) &&\n payloadLength > 125\n ) {\n // Control frames can have a payload length of 125 bytes MAX\n failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')\n return\n } else if (this.#info.opcode === opcodes.CLOSE) {\n if (payloadLength === 1) {\n failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')\n return\n }\n\n const body = this.consume(payloadLength)\n\n this.#info.closeInfo = this.parseCloseBody(false, body)\n\n if (!this.ws[kSentClose]) {\n // If an endpoint receives a Close frame and did not previously send a\n // Close frame, the endpoint MUST send a Close frame in response. (When\n // sending a Close frame in response, the endpoint typically echos the\n // status code it received.)\n const body = Buffer.allocUnsafe(2)\n body.writeUInt16BE(this.#info.closeInfo.code, 0)\n const closeFrame = new WebsocketFrameSend(body)\n\n this.ws[kResponse].socket.write(\n closeFrame.createFrame(opcodes.CLOSE),\n (err) => {\n if (!err) {\n this.ws[kSentClose] = true\n }\n }\n )\n }\n\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n this.ws[kReadyState] = states.CLOSING\n this.ws[kReceivedClose] = true\n\n this.end()\n\n return\n } else if (this.#info.opcode === opcodes.PING) {\n // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in\n // response, unless it already received a Close frame.\n // A Pong frame sent in response to a Ping frame must have identical\n // \"Application data\"\n\n const body = this.consume(payloadLength)\n\n if (!this.ws[kReceivedClose]) {\n const frame = new WebsocketFrameSend(body)\n\n this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))\n\n if (channels.ping.hasSubscribers) {\n channels.ping.publish({\n payload: body\n })\n }\n }\n\n this.#state = parserStates.INFO\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n return\n }\n } else if (this.#info.opcode === opcodes.PONG) {\n // A Pong frame MAY be sent unsolicited. This serves as a\n // unidirectional heartbeat. A response to an unsolicited Pong frame is\n // not expected.\n\n const body = this.consume(payloadLength)\n\n if (channels.pong.hasSubscribers) {\n channels.pong.publish({\n payload: body\n })\n }\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n return\n }\n }\n } else if (this.#state === parserStates.PAYLOADLENGTH_16) {\n if (this.#byteOffset < 2) {\n return callback()\n }\n\n const buffer = this.consume(2)\n\n this.#info.payloadLength = buffer.readUInt16BE(0)\n this.#state = parserStates.READ_DATA\n } else if (this.#state === parserStates.PAYLOADLENGTH_64) {\n if (this.#byteOffset < 8) {\n return callback()\n }\n\n const buffer = this.consume(8)\n const upper = buffer.readUInt32BE(0)\n\n // 2^31 is the maxinimum bytes an arraybuffer can contain\n // on 32-bit systems. Although, on 64-bit systems, this is\n // 2^53-1 bytes.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length\n // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275\n // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e\n if (upper > 2 ** 31 - 1) {\n failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')\n return\n }\n\n const lower = buffer.readUInt32BE(4)\n\n this.#info.payloadLength = (upper << 8) + lower\n this.#state = parserStates.READ_DATA\n } else if (this.#state === parserStates.READ_DATA) {\n if (this.#byteOffset < this.#info.payloadLength) {\n // If there is still more data in this chunk that needs to be read\n return callback()\n } else if (this.#byteOffset >= this.#info.payloadLength) {\n // If the server sent multiple frames in a single chunk\n\n const body = this.consume(this.#info.payloadLength)\n\n this.#fragments.push(body)\n\n // If the frame is unfragmented, or a fragmented frame was terminated,\n // a message was received\n if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {\n const fullMessage = Buffer.concat(this.#fragments)\n\n websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)\n\n this.#info = {}\n this.#fragments.length = 0\n }\n\n this.#state = parserStates.INFO\n }\n }\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n break\n }\n }\n }\n\n /**\n * Take n bytes from the buffered Buffers\n * @param {number} n\n * @returns {Buffer|null}\n */\n consume (n) {\n if (n > this.#byteOffset) {\n return null\n } else if (n === 0) {\n return emptyBuffer\n }\n\n if (this.#buffers[0].length === n) {\n this.#byteOffset -= this.#buffers[0].length\n return this.#buffers.shift()\n }\n\n const buffer = Buffer.allocUnsafe(n)\n let offset = 0\n\n while (offset !== n) {\n const next = this.#buffers[0]\n const { length } = next\n\n if (length + offset === n) {\n buffer.set(this.#buffers.shift(), offset)\n break\n } else if (length + offset > n) {\n buffer.set(next.subarray(0, n - offset), offset)\n this.#buffers[0] = next.subarray(n - offset)\n break\n } else {\n buffer.set(this.#buffers.shift(), offset)\n offset += next.length\n }\n }\n\n this.#byteOffset -= n\n\n return buffer\n }\n\n parseCloseBody (onlyCode, data) {\n // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5\n /** @type {number|undefined} */\n let code\n\n if (data.length >= 2) {\n // _The WebSocket Connection Close Code_ is\n // defined as the status code (Section 7.4) contained in the first Close\n // control frame received by the application\n code = data.readUInt16BE(0)\n }\n\n if (onlyCode) {\n if (!isValidStatusCode(code)) {\n return null\n }\n\n return { code }\n }\n\n // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6\n /** @type {Buffer} */\n let reason = data.subarray(2)\n\n // Remove BOM\n if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {\n reason = reason.subarray(3)\n }\n\n if (code !== undefined && !isValidStatusCode(code)) {\n return null\n }\n\n try {\n // TODO: optimize this\n reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)\n } catch {\n return null\n }\n\n return { code, reason }\n }\n\n get closingInfo () {\n return this.#info.closeInfo\n }\n}\n\nmodule.exports = {\n ByteParser\n}\n","'use strict'\n\nmodule.exports = {\n kWebSocketURL: Symbol('url'),\n kReadyState: Symbol('ready state'),\n kController: Symbol('controller'),\n kResponse: Symbol('response'),\n kBinaryType: Symbol('binary type'),\n kSentClose: Symbol('sent close'),\n kReceivedClose: Symbol('received close'),\n kByteParser: Symbol('byte parser')\n}\n","'use strict'\n\nconst { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols')\nconst { states, opcodes } = require('./constants')\nconst { MessageEvent, ErrorEvent } = require('./events')\n\n/* globals Blob */\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isEstablished (ws) {\n // If the server's response is validated as provided for above, it is\n // said that _The WebSocket Connection is Established_ and that the\n // WebSocket Connection is in the OPEN state.\n return ws[kReadyState] === states.OPEN\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isClosing (ws) {\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n return ws[kReadyState] === states.CLOSING\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isClosed (ws) {\n return ws[kReadyState] === states.CLOSED\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e\n * @param {EventTarget} target\n * @param {EventInit | undefined} eventInitDict\n */\nfunction fireEvent (e, target, eventConstructor = Event, eventInitDict) {\n // 1. If eventConstructor is not given, then let eventConstructor be Event.\n\n // 2. Let event be the result of creating an event given eventConstructor,\n // in the relevant realm of target.\n // 3. Initialize event’s type attribute to e.\n const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap\n\n // 4. Initialize any other IDL attributes of event as described in the\n // invocation of this algorithm.\n\n // 5. Return the result of dispatching event at target, with legacy target\n // override flag set if set.\n target.dispatchEvent(event)\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @param {import('./websocket').WebSocket} ws\n * @param {number} type Opcode\n * @param {Buffer} data application data\n */\nfunction websocketMessageReceived (ws, type, data) {\n // 1. If ready state is not OPEN (1), then return.\n if (ws[kReadyState] !== states.OPEN) {\n return\n }\n\n // 2. Let dataForEvent be determined by switching on type and binary type:\n let dataForEvent\n\n if (type === opcodes.TEXT) {\n // -> type indicates that the data is Text\n // a new DOMString containing data\n try {\n dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)\n } catch {\n failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')\n return\n }\n } else if (type === opcodes.BINARY) {\n if (ws[kBinaryType] === 'blob') {\n // -> type indicates that the data is Binary and binary type is \"blob\"\n // a new Blob object, created in the relevant Realm of the WebSocket\n // object, that represents data as its raw data\n dataForEvent = new Blob([data])\n } else {\n // -> type indicates that the data is Binary and binary type is \"arraybuffer\"\n // a new ArrayBuffer object, created in the relevant Realm of the\n // WebSocket object, whose contents are data\n dataForEvent = new Uint8Array(data).buffer\n }\n }\n\n // 3. Fire an event named message at the WebSocket object, using MessageEvent,\n // with the origin attribute initialized to the serialization of the WebSocket\n // object’s url's origin, and the data attribute initialized to dataForEvent.\n fireEvent('message', ws, MessageEvent, {\n origin: ws[kWebSocketURL].origin,\n data: dataForEvent\n })\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455\n * @see https://datatracker.ietf.org/doc/html/rfc2616\n * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407\n * @param {string} protocol\n */\nfunction isValidSubprotocol (protocol) {\n // If present, this value indicates one\n // or more comma-separated subprotocol the client wishes to speak,\n // ordered by preference. The elements that comprise this value\n // MUST be non-empty strings with characters in the range U+0021 to\n // U+007E not including separator characters as defined in\n // [RFC2616] and MUST all be unique strings.\n if (protocol.length === 0) {\n return false\n }\n\n for (const char of protocol) {\n const code = char.charCodeAt(0)\n\n if (\n code < 0x21 ||\n code > 0x7E ||\n char === '(' ||\n char === ')' ||\n char === '<' ||\n char === '>' ||\n char === '@' ||\n char === ',' ||\n char === ';' ||\n char === ':' ||\n char === '\\\\' ||\n char === '\"' ||\n char === '/' ||\n char === '[' ||\n char === ']' ||\n char === '?' ||\n char === '=' ||\n char === '{' ||\n char === '}' ||\n code === 32 || // SP\n code === 9 // HT\n ) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4\n * @param {number} code\n */\nfunction isValidStatusCode (code) {\n if (code >= 1000 && code < 1015) {\n return (\n code !== 1004 && // reserved\n code !== 1005 && // \"MUST NOT be set as a status code\"\n code !== 1006 // \"MUST NOT be set as a status code\"\n )\n }\n\n return code >= 3000 && code <= 4999\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n * @param {string|undefined} reason\n */\nfunction failWebsocketConnection (ws, reason) {\n const { [kController]: controller, [kResponse]: response } = ws\n\n controller.abort()\n\n if (response?.socket && !response.socket.destroyed) {\n response.socket.destroy()\n }\n\n if (reason) {\n fireEvent('error', ws, ErrorEvent, {\n error: new Error(reason)\n })\n }\n}\n\nmodule.exports = {\n isEstablished,\n isClosing,\n isClosed,\n fireEvent,\n isValidSubprotocol,\n isValidStatusCode,\n failWebsocketConnection,\n websocketMessageReceived\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\nconst { DOMException } = require('../fetch/constants')\nconst { URLSerializer } = require('../fetch/dataURL')\nconst { getGlobalOrigin } = require('../fetch/global')\nconst { staticPropertyDescriptors, states, opcodes, emptyBuffer } = require('./constants')\nconst {\n kWebSocketURL,\n kReadyState,\n kController,\n kBinaryType,\n kResponse,\n kSentClose,\n kByteParser\n} = require('./symbols')\nconst { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = require('./util')\nconst { establishWebSocketConnection } = require('./connection')\nconst { WebsocketFrameSend } = require('./frame')\nconst { ByteParser } = require('./receiver')\nconst { kEnumerableProperty, isBlobLike } = require('../core/util')\nconst { getGlobalDispatcher } = require('../global')\nconst { types } = require('util')\n\nlet experimentalWarned = false\n\n// https://websockets.spec.whatwg.org/#interface-definition\nclass WebSocket extends EventTarget {\n #events = {\n open: null,\n error: null,\n close: null,\n message: null\n }\n\n #bufferedAmount = 0\n #protocol = ''\n #extensions = ''\n\n /**\n * @param {string} url\n * @param {string|string[]} protocols\n */\n constructor (url, protocols = []) {\n super()\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })\n\n if (!experimentalWarned) {\n experimentalWarned = true\n process.emitWarning('WebSockets are experimental, expect them to change at any time.', {\n code: 'UNDICI-WS'\n })\n }\n\n const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)\n\n url = webidl.converters.USVString(url)\n protocols = options.protocols\n\n // 1. Let baseURL be this's relevant settings object's API base URL.\n const baseURL = getGlobalOrigin()\n\n // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.\n let urlRecord\n\n try {\n urlRecord = new URL(url, baseURL)\n } catch (e) {\n // 3. If urlRecord is failure, then throw a \"SyntaxError\" DOMException.\n throw new DOMException(e, 'SyntaxError')\n }\n\n // 4. If urlRecord’s scheme is \"http\", then set urlRecord’s scheme to \"ws\".\n if (urlRecord.protocol === 'http:') {\n urlRecord.protocol = 'ws:'\n } else if (urlRecord.protocol === 'https:') {\n // 5. Otherwise, if urlRecord’s scheme is \"https\", set urlRecord’s scheme to \"wss\".\n urlRecord.protocol = 'wss:'\n }\n\n // 6. If urlRecord’s scheme is not \"ws\" or \"wss\", then throw a \"SyntaxError\" DOMException.\n if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {\n throw new DOMException(\n `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,\n 'SyntaxError'\n )\n }\n\n // 7. If urlRecord’s fragment is non-null, then throw a \"SyntaxError\"\n // DOMException.\n if (urlRecord.hash || urlRecord.href.endsWith('#')) {\n throw new DOMException('Got fragment', 'SyntaxError')\n }\n\n // 8. If protocols is a string, set protocols to a sequence consisting\n // of just that string.\n if (typeof protocols === 'string') {\n protocols = [protocols]\n }\n\n // 9. If any of the values in protocols occur more than once or otherwise\n // fail to match the requirements for elements that comprise the value\n // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket\n // protocol, then throw a \"SyntaxError\" DOMException.\n if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {\n throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')\n }\n\n if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {\n throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')\n }\n\n // 10. Set this's url to urlRecord.\n this[kWebSocketURL] = new URL(urlRecord.href)\n\n // 11. Let client be this's relevant settings object.\n\n // 12. Run this step in parallel:\n\n // 1. Establish a WebSocket connection given urlRecord, protocols,\n // and client.\n this[kController] = establishWebSocketConnection(\n urlRecord,\n protocols,\n this,\n (response) => this.#onConnectionEstablished(response),\n options\n )\n\n // Each WebSocket object has an associated ready state, which is a\n // number representing the state of the connection. Initially it must\n // be CONNECTING (0).\n this[kReadyState] = WebSocket.CONNECTING\n\n // The extensions attribute must initially return the empty string.\n\n // The protocol attribute must initially return the empty string.\n\n // Each WebSocket object has an associated binary type, which is a\n // BinaryType. Initially it must be \"blob\".\n this[kBinaryType] = 'blob'\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#dom-websocket-close\n * @param {number|undefined} code\n * @param {string|undefined} reason\n */\n close (code = undefined, reason = undefined) {\n webidl.brandCheck(this, WebSocket)\n\n if (code !== undefined) {\n code = webidl.converters['unsigned short'](code, { clamp: true })\n }\n\n if (reason !== undefined) {\n reason = webidl.converters.USVString(reason)\n }\n\n // 1. If code is present, but is neither an integer equal to 1000 nor an\n // integer in the range 3000 to 4999, inclusive, throw an\n // \"InvalidAccessError\" DOMException.\n if (code !== undefined) {\n if (code !== 1000 && (code < 3000 || code > 4999)) {\n throw new DOMException('invalid code', 'InvalidAccessError')\n }\n }\n\n let reasonByteLength = 0\n\n // 2. If reason is present, then run these substeps:\n if (reason !== undefined) {\n // 1. Let reasonBytes be the result of encoding reason.\n // 2. If reasonBytes is longer than 123 bytes, then throw a\n // \"SyntaxError\" DOMException.\n reasonByteLength = Buffer.byteLength(reason)\n\n if (reasonByteLength > 123) {\n throw new DOMException(\n `Reason must be less than 123 bytes; received ${reasonByteLength}`,\n 'SyntaxError'\n )\n }\n }\n\n // 3. Run the first matching steps from the following list:\n if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {\n // If this's ready state is CLOSING (2) or CLOSED (3)\n // Do nothing.\n } else if (!isEstablished(this)) {\n // If the WebSocket connection is not yet established\n // Fail the WebSocket connection and set this's ready state\n // to CLOSING (2).\n failWebsocketConnection(this, 'Connection was closed before it was established.')\n this[kReadyState] = WebSocket.CLOSING\n } else if (!isClosing(this)) {\n // If the WebSocket closing handshake has not yet been started\n // Start the WebSocket closing handshake and set this's ready\n // state to CLOSING (2).\n // - If neither code nor reason is present, the WebSocket Close\n // message must not have a body.\n // - If code is present, then the status code to use in the\n // WebSocket Close message must be the integer given by code.\n // - If reason is also present, then reasonBytes must be\n // provided in the Close message after the status code.\n\n const frame = new WebsocketFrameSend()\n\n // If neither code nor reason is present, the WebSocket Close\n // message must not have a body.\n\n // If code is present, then the status code to use in the\n // WebSocket Close message must be the integer given by code.\n if (code !== undefined && reason === undefined) {\n frame.frameData = Buffer.allocUnsafe(2)\n frame.frameData.writeUInt16BE(code, 0)\n } else if (code !== undefined && reason !== undefined) {\n // If reason is also present, then reasonBytes must be\n // provided in the Close message after the status code.\n frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)\n frame.frameData.writeUInt16BE(code, 0)\n // the body MAY contain UTF-8-encoded data with value /reason/\n frame.frameData.write(reason, 2, 'utf-8')\n } else {\n frame.frameData = emptyBuffer\n }\n\n /** @type {import('stream').Duplex} */\n const socket = this[kResponse].socket\n\n socket.write(frame.createFrame(opcodes.CLOSE), (err) => {\n if (!err) {\n this[kSentClose] = true\n }\n })\n\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n this[kReadyState] = states.CLOSING\n } else {\n // Otherwise\n // Set this's ready state to CLOSING (2).\n this[kReadyState] = WebSocket.CLOSING\n }\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#dom-websocket-send\n * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data\n */\n send (data) {\n webidl.brandCheck(this, WebSocket)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })\n\n data = webidl.converters.WebSocketSendData(data)\n\n // 1. If this's ready state is CONNECTING, then throw an\n // \"InvalidStateError\" DOMException.\n if (this[kReadyState] === WebSocket.CONNECTING) {\n throw new DOMException('Sent before connected.', 'InvalidStateError')\n }\n\n // 2. Run the appropriate set of steps from the following list:\n // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1\n // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2\n\n if (!isEstablished(this) || isClosing(this)) {\n return\n }\n\n /** @type {import('stream').Duplex} */\n const socket = this[kResponse].socket\n\n // If data is a string\n if (typeof data === 'string') {\n // If the WebSocket connection is established and the WebSocket\n // closing handshake has not yet started, then the user agent\n // must send a WebSocket Message comprised of the data argument\n // using a text frame opcode; if the data cannot be sent, e.g.\n // because it would need to be buffered but the buffer is full,\n // the user agent must flag the WebSocket as full and then close\n // the WebSocket connection. Any invocation of this method with a\n // string argument that does not throw an exception must increase\n // the bufferedAmount attribute by the number of bytes needed to\n // express the argument as UTF-8.\n\n const value = Buffer.from(data)\n const frame = new WebsocketFrameSend(value)\n const buffer = frame.createFrame(opcodes.TEXT)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n } else if (types.isArrayBuffer(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need\n // to be buffered but the buffer is full, the user agent must flag\n // the WebSocket as full and then close the WebSocket connection.\n // The data to be sent is the data stored in the buffer described\n // by the ArrayBuffer object. Any invocation of this method with an\n // ArrayBuffer argument that does not throw an exception must\n // increase the bufferedAmount attribute by the length of the\n // ArrayBuffer in bytes.\n\n const value = Buffer.from(data)\n const frame = new WebsocketFrameSend(value)\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n } else if (ArrayBuffer.isView(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need to\n // be buffered but the buffer is full, the user agent must flag the\n // WebSocket as full and then close the WebSocket connection. The\n // data to be sent is the data stored in the section of the buffer\n // described by the ArrayBuffer object that data references. Any\n // invocation of this method with this kind of argument that does\n // not throw an exception must increase the bufferedAmount attribute\n // by the length of data’s buffer in bytes.\n\n const ab = Buffer.from(data, data.byteOffset, data.byteLength)\n\n const frame = new WebsocketFrameSend(ab)\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += ab.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= ab.byteLength\n })\n } else if (isBlobLike(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need to\n // be buffered but the buffer is full, the user agent must flag the\n // WebSocket as full and then close the WebSocket connection. The data\n // to be sent is the raw data represented by the Blob object. Any\n // invocation of this method with a Blob argument that does not throw\n // an exception must increase the bufferedAmount attribute by the size\n // of the Blob object’s raw data, in bytes.\n\n const frame = new WebsocketFrameSend()\n\n data.arrayBuffer().then((ab) => {\n const value = Buffer.from(ab)\n frame.frameData = value\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n })\n }\n }\n\n get readyState () {\n webidl.brandCheck(this, WebSocket)\n\n // The readyState getter steps are to return this's ready state.\n return this[kReadyState]\n }\n\n get bufferedAmount () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#bufferedAmount\n }\n\n get url () {\n webidl.brandCheck(this, WebSocket)\n\n // The url getter steps are to return this's url, serialized.\n return URLSerializer(this[kWebSocketURL])\n }\n\n get extensions () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#extensions\n }\n\n get protocol () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#protocol\n }\n\n get onopen () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.open\n }\n\n set onopen (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.open) {\n this.removeEventListener('open', this.#events.open)\n }\n\n if (typeof fn === 'function') {\n this.#events.open = fn\n this.addEventListener('open', fn)\n } else {\n this.#events.open = null\n }\n }\n\n get onerror () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.error\n }\n\n set onerror (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.error) {\n this.removeEventListener('error', this.#events.error)\n }\n\n if (typeof fn === 'function') {\n this.#events.error = fn\n this.addEventListener('error', fn)\n } else {\n this.#events.error = null\n }\n }\n\n get onclose () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.close\n }\n\n set onclose (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.close) {\n this.removeEventListener('close', this.#events.close)\n }\n\n if (typeof fn === 'function') {\n this.#events.close = fn\n this.addEventListener('close', fn)\n } else {\n this.#events.close = null\n }\n }\n\n get onmessage () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.message\n }\n\n set onmessage (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.message) {\n this.removeEventListener('message', this.#events.message)\n }\n\n if (typeof fn === 'function') {\n this.#events.message = fn\n this.addEventListener('message', fn)\n } else {\n this.#events.message = null\n }\n }\n\n get binaryType () {\n webidl.brandCheck(this, WebSocket)\n\n return this[kBinaryType]\n }\n\n set binaryType (type) {\n webidl.brandCheck(this, WebSocket)\n\n if (type !== 'blob' && type !== 'arraybuffer') {\n this[kBinaryType] = 'blob'\n } else {\n this[kBinaryType] = type\n }\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n */\n #onConnectionEstablished (response) {\n // processResponse is called when the \"response’s header list has been received and initialized.\"\n // once this happens, the connection is open\n this[kResponse] = response\n\n const parser = new ByteParser(this)\n parser.on('drain', function onParserDrain () {\n this.ws[kResponse].socket.resume()\n })\n\n response.socket.ws = this\n this[kByteParser] = parser\n\n // 1. Change the ready state to OPEN (1).\n this[kReadyState] = states.OPEN\n\n // 2. Change the extensions attribute’s value to the extensions in use, if\n // it is not the null value.\n // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1\n const extensions = response.headersList.get('sec-websocket-extensions')\n\n if (extensions !== null) {\n this.#extensions = extensions\n }\n\n // 3. Change the protocol attribute’s value to the subprotocol in use, if\n // it is not the null value.\n // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9\n const protocol = response.headersList.get('sec-websocket-protocol')\n\n if (protocol !== null) {\n this.#protocol = protocol\n }\n\n // 4. Fire an event named open at the WebSocket object.\n fireEvent('open', this)\n }\n}\n\n// https://websockets.spec.whatwg.org/#dom-websocket-connecting\nWebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING\n// https://websockets.spec.whatwg.org/#dom-websocket-open\nWebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN\n// https://websockets.spec.whatwg.org/#dom-websocket-closing\nWebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING\n// https://websockets.spec.whatwg.org/#dom-websocket-closed\nWebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED\n\nObject.defineProperties(WebSocket.prototype, {\n CONNECTING: staticPropertyDescriptors,\n OPEN: staticPropertyDescriptors,\n CLOSING: staticPropertyDescriptors,\n CLOSED: staticPropertyDescriptors,\n url: kEnumerableProperty,\n readyState: kEnumerableProperty,\n bufferedAmount: kEnumerableProperty,\n onopen: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onclose: kEnumerableProperty,\n close: kEnumerableProperty,\n onmessage: kEnumerableProperty,\n binaryType: kEnumerableProperty,\n send: kEnumerableProperty,\n extensions: kEnumerableProperty,\n protocol: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'WebSocket',\n writable: false,\n enumerable: false,\n configurable: true\n }\n})\n\nObject.defineProperties(WebSocket, {\n CONNECTING: staticPropertyDescriptors,\n OPEN: staticPropertyDescriptors,\n CLOSING: staticPropertyDescriptors,\n CLOSED: staticPropertyDescriptors\n})\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.DOMString\n)\n\nwebidl.converters['DOMString or sequence'] = function (V) {\n if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {\n return webidl.converters['sequence'](V)\n }\n\n return webidl.converters.DOMString(V)\n}\n\n// This implements the propsal made in https://github.com/whatwg/websockets/issues/42\nwebidl.converters.WebSocketInit = webidl.dictionaryConverter([\n {\n key: 'protocols',\n converter: webidl.converters['DOMString or sequence'],\n get defaultValue () {\n return []\n }\n },\n {\n key: 'dispatcher',\n converter: (V) => V,\n get defaultValue () {\n return getGlobalDispatcher()\n }\n },\n {\n key: 'headers',\n converter: webidl.nullableConverter(webidl.converters.HeadersInit)\n }\n])\n\nwebidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {\n if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {\n return webidl.converters.WebSocketInit(V)\n }\n\n return { protocols: webidl.converters['DOMString or sequence'](V) }\n}\n\nwebidl.converters.WebSocketSendData = function (V) {\n if (webidl.util.Type(V) === 'Object') {\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {\n return webidl.converters.BufferSource(V)\n }\n }\n\n return webidl.converters.USVString(V)\n}\n\nmodule.exports = {\n WebSocket\n}\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;\n }\n\n return \"\";\n}\n\nexports.getUserAgent = getUserAgent;\n//# sourceMappingURL=index.js.map\n","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\n\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\n\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\n\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\n\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\n\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\n\nvar _version = _interopRequireDefault(require(\"./version.js\"));\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction md5(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return _crypto.default.createHash('md5').update(bytes).digest();\n}\n\nvar _default = md5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = '00000000-0000-0000-0000-000000000000';\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nvar _default = parse;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\n\nfunction rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n _crypto.default.randomFillSync(rnds8Pool);\n\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _crypto = _interopRequireDefault(require(\"crypto\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return _crypto.default.createHash('sha1').update(bytes).digest();\n}\n\nvar _default = sha1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nvar _default = stringify;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\nlet _nodeId;\n\nlet _clockseq; // Previous uuid creation time\n\n\nlet _lastMSecs = 0;\nlet _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node || _nodeId;\n let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || (0, _stringify.default)(b);\n}\n\nvar _default = v1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = v3;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = _default;\nexports.URL = exports.DNS = void 0;\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nconst DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexports.DNS = DNS;\nconst URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexports.URL = URL;\n\nfunction _default(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.default)(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction v4(options, buf, offset) {\n options = options || {};\n\n const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.default)(rnds);\n}\n\nvar _default = v4;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = v5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\n\nvar _default = validate;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nvar _default = version;\nexports.default = _default;","// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ApiClient = exports.CredentialFetchingError = exports.JobDetailsFetchingError = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst httpClient = __importStar(require(\"@actions/http-client\"));\nclass JobDetailsFetchingError extends Error {\n}\nexports.JobDetailsFetchingError = JobDetailsFetchingError;\nclass CredentialFetchingError extends Error {\n}\nexports.CredentialFetchingError = CredentialFetchingError;\nclass ApiClient {\n constructor(client, params, jobToken, credentialsToken) {\n this.client = client;\n this.params = params;\n this.credentialsToken = credentialsToken;\n // We use a static unknown SHA when marking a job as complete from the action\n // to remain in parity with the existing runner.\n this.UnknownSha = {\n 'base-commit-sha': 'unknown'\n };\n this.jobToken = jobToken;\n }\n // Getter for jobToken\n getJobToken() {\n return this.jobToken;\n }\n getJobDetails() {\n return __awaiter(this, void 0, void 0, function* () {\n const detailsURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/details`;\n try {\n const res = yield this.getJsonWithRetry(detailsURL, this.jobToken);\n if (res.statusCode !== 200) {\n throw new JobDetailsFetchingError(`fetching job details: unexpected status code: ${res.statusCode}: ${JSON.stringify(res.result)}`);\n }\n if (!res.result) {\n throw new JobDetailsFetchingError(`fetching job details: missing response`);\n }\n return res.result.data.attributes;\n }\n catch (error) {\n if (error instanceof JobDetailsFetchingError) {\n throw error;\n }\n else if (error instanceof httpClient.HttpClientError) {\n throw new JobDetailsFetchingError(`fetching job details: unexpected status code: ${error.statusCode}: ${error.message}`);\n }\n else if (error instanceof Error) {\n throw new JobDetailsFetchingError(`fetching job details: ${error.name}: ${error.message}`);\n }\n throw error;\n }\n });\n }\n getCredentials() {\n return __awaiter(this, void 0, void 0, function* () {\n const credentialsURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/credentials`;\n try {\n const res = yield this.getJsonWithRetry(credentialsURL, this.credentialsToken);\n if (res.statusCode !== 200) {\n throw new CredentialFetchingError(`fetching credentials: unexpected status code: ${res.statusCode}: ${JSON.stringify(res.result)}`);\n }\n if (!res.result) {\n throw new CredentialFetchingError(`fetching credentials: missing response`);\n }\n // Mask any secrets we've just retrieved from Actions logs\n for (const credential of res.result.data.attributes.credentials) {\n if (credential.password) {\n core.setSecret(credential.password);\n }\n if (credential.token) {\n core.setSecret(credential.token);\n }\n }\n return res.result.data.attributes.credentials;\n }\n catch (error) {\n if (error instanceof CredentialFetchingError) {\n throw error;\n }\n else if (error instanceof httpClient.HttpClientError) {\n throw new CredentialFetchingError(`fetching credentials: unexpected status code: ${error.statusCode}: ${error.message}`);\n }\n else if (error instanceof Error) {\n throw new CredentialFetchingError(`fetching credentials: ${error.name}: ${error.message}`);\n }\n throw error;\n }\n });\n }\n reportJobError(error) {\n return __awaiter(this, void 0, void 0, function* () {\n const recordErrorURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/record_update_job_error`;\n const res = yield this.client.postJson(recordErrorURL, { data: error }, {\n ['Authorization']: this.jobToken\n });\n if (res.statusCode !== 204) {\n throw new Error(`Unexpected status code: ${res.statusCode}`);\n }\n });\n }\n markJobAsProcessed() {\n return __awaiter(this, void 0, void 0, function* () {\n const markAsProcessedURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/mark_as_processed`;\n const res = yield this.client.patchJson(markAsProcessedURL, { data: this.UnknownSha }, {\n ['Authorization']: this.jobToken\n });\n if (res.statusCode !== 204) {\n throw new Error(`Unexpected status code: ${res.statusCode}`);\n }\n });\n }\n getJsonWithRetry(url, token) {\n return __awaiter(this, void 0, void 0, function* () {\n let attempt = 1;\n const execute = () => __awaiter(this, void 0, void 0, function* () {\n try {\n return yield this.client.getJson(url, {\n ['Authorization']: token\n });\n }\n catch (error) {\n if (error instanceof httpClient.HttpClientError) {\n if (error.statusCode >= 500 && error.statusCode <= 599) {\n if (attempt >= 3) {\n throw error;\n }\n core.warning(`Retrying failed request with status code: ${error.statusCode}`);\n // exponential backoff\n const delayMs = 1000 * Math.pow(2, attempt);\n yield new Promise(resolve => setTimeout(resolve, delayMs));\n attempt++;\n return execute();\n }\n }\n throw error;\n }\n });\n return execute();\n });\n }\n}\nexports.ApiClient = ApiClient;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ContainerService = exports.ContainerRuntimeError = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst tar_stream_1 = require(\"tar-stream\");\nconst utils_1 = require(\"./utils\");\nclass ContainerRuntimeError extends Error {\n}\nexports.ContainerRuntimeError = ContainerRuntimeError;\nconst RWX_ALL = 0o777;\nexports.ContainerService = {\n storeInput(name, path, container, input) {\n return __awaiter(this, void 0, void 0, function* () {\n const tar = (0, tar_stream_1.pack)();\n tar.entry({ name, mode: RWX_ALL }, JSON.stringify(input));\n tar.finalize();\n yield container.putArchive(tar, { path });\n });\n },\n storeCert(name, path, container, cert) {\n return __awaiter(this, void 0, void 0, function* () {\n const tar = (0, tar_stream_1.pack)();\n tar.entry({ name }, cert);\n tar.finalize();\n yield container.putArchive(tar, { path });\n });\n },\n run(container) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const stream = yield container.attach({\n stream: true,\n stdout: true,\n stderr: true\n });\n container.modem.demuxStream(stream, (0, utils_1.outStream)('updater'), (0, utils_1.errStream)('updater'));\n yield container.start();\n const outcome = yield container.wait();\n if (outcome.StatusCode === 0) {\n return true;\n }\n else {\n core.info(`Failure running container ${container.id}`);\n throw new ContainerRuntimeError('The updater encountered one or more errors.');\n }\n }\n finally {\n yield container.remove({ v: true });\n core.info(`Cleaned up container ${container.id}`);\n }\n });\n }\n};\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.digestName = exports.hasDigest = exports.repositoryName = exports.updaterImages = exports.updaterImageName = exports.PROXY_IMAGE_NAME = void 0;\n// eslint-disable-next-line import/extensions\nconst containers_json_1 = __importDefault(require(\"../docker/containers.json\"));\nexports.PROXY_IMAGE_NAME = containers_json_1.default.proxy;\nfunction updaterImageName(packageManager) {\n return containers_json_1.default[packageManager];\n}\nexports.updaterImageName = updaterImageName;\nconst updaterRegex = /ghcr.io\\/dependabot\\/dependabot-updater-([\\w+])/;\nfunction updaterImages() {\n return Object.values(containers_json_1.default).filter(image => image.match(updaterRegex));\n}\nexports.updaterImages = updaterImages;\nconst imageNamePattern = '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))(:[a-zA-Z0-9._/-]+)?(?@sha256:[a-zA-Z0-9]{64})?$';\nfunction repositoryName(imageName) {\n const match = imageName.match(imageNamePattern);\n if (match === null || match === void 0 ? void 0 : match.groups) {\n return match.groups['repository'];\n }\n else {\n throw Error('invalid image name');\n }\n}\nexports.repositoryName = repositoryName;\nfunction hasDigest(imageName) {\n const match = imageName.match(imageNamePattern);\n if (match === null || match === void 0 ? void 0 : match.groups) {\n if (match === null || match === void 0 ? void 0 : match.groups['digest']) {\n return true;\n }\n return false;\n }\n else {\n throw Error('invalid image name');\n }\n}\nexports.hasDigest = hasDigest;\nfunction digestName(imageName) {\n const match = imageName.match(imageNamePattern);\n if (match === null || match === void 0 ? void 0 : match.groups) {\n return match.groups['repository'] + match.groups['digest'];\n }\n else {\n throw Error('invalid image name');\n }\n}\nexports.digestName = digestName;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ImageService = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst dockerode_1 = __importDefault(require(\"dockerode\"));\nconst endOfStream = (docker, stream) => __awaiter(void 0, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n docker.modem.followProgress(stream, (err) => err ? reject(err) : resolve(undefined));\n });\n});\n/** Fetch the configured updater image, if it isn't already available. */\nexports.ImageService = {\n pull(imageName_1) {\n return __awaiter(this, arguments, void 0, function* (imageName, force = false) {\n /*\n This method fetches images hosts on GitHub infrastructure.\n \n We expose the `fetch_image` utility method to allow us to pull in arbitrary images for unit tests.\n */\n if (!(imageName.startsWith('ghcr.io/') ||\n imageName.startsWith('docker.pkg.github.com/'))) {\n throw new Error('Only images distributed via docker.pkg.github.com or ghcr.io can be fetched');\n }\n const docker = new dockerode_1.default();\n try {\n const image = yield docker.getImage(imageName).inspect();\n if (!force) {\n core.info(`Resolved ${imageName} to existing ${image.RepoDigests}`);\n return;\n } // else fallthrough to pull\n }\n catch (e) {\n if (e instanceof Error && !e.message.includes('no such image')) {\n throw e;\n } // else fallthrough to pull\n }\n const auth = {}; // Images are public so not authentication info is required\n yield this.fetchImage(imageName, auth, docker);\n });\n },\n /* Retrieve the imageName using the auth details provided, if any */\n fetchImage(imageName_1) {\n return __awaiter(this, arguments, void 0, function* (imageName, auth = {}, docker = new dockerode_1.default()) {\n core.info(`Pulling image ${imageName}...`);\n const stream = yield docker.pull(imageName, { authconfig: auth });\n yield endOfStream(docker, stream);\n core.info(`Pulled image ${imageName}`);\n });\n }\n};\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getJobParameters = exports.JobParameters = void 0;\nconst fs_1 = __importDefault(require(\"fs\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst core = __importStar(require(\"@actions/core\"));\nconst DYNAMIC = 'dynamic';\nconst DEPENDABOT_ACTOR = 'dependabot[bot]';\n// JobParameters are the Action inputs required to execute the job\nclass JobParameters {\n constructor(jobId, jobToken, credentialsToken, dependabotApiUrl, dependabotApiDockerUrl, updaterImage, workingDirectory) {\n this.jobId = jobId;\n this.jobToken = jobToken;\n this.credentialsToken = credentialsToken;\n this.dependabotApiUrl = dependabotApiUrl;\n this.dependabotApiDockerUrl = dependabotApiDockerUrl;\n this.updaterImage = updaterImage;\n this.workingDirectory = workingDirectory;\n }\n}\nexports.JobParameters = JobParameters;\nfunction getJobParameters(ctx) {\n checkEnvironmentAndContext(ctx);\n if (ctx.actor !== DEPENDABOT_ACTOR) {\n core.warning(`This workflow can only be triggered by Dependabot. Actor was '${ctx.actor}'.`);\n return null;\n }\n if (process.env.GITHUB_TRIGGERING_ACTOR &&\n process.env.GITHUB_TRIGGERING_ACTOR !== DEPENDABOT_ACTOR) {\n core.warning('Dependabot workflows cannot be re-run. Retrigger this update via Dependabot instead.');\n return null;\n }\n if (ctx.eventName === DYNAMIC) {\n return fromWorkflowInputs(ctx);\n }\n else {\n core.warning(`Dependabot Updater Action does not support '${ctx.eventName}' events.`);\n return null;\n }\n}\nexports.getJobParameters = getJobParameters;\nfunction checkEnvironmentAndContext(ctx) {\n let valid = true;\n if (!ctx.actor) {\n core.error('GITHUB_ACTOR is not defined');\n valid = false;\n }\n if (!ctx.eventName) {\n core.error('GITHUB_EVENT_NAME is not defined');\n valid = false;\n }\n if (!process.env.GITHUB_WORKSPACE) {\n core.error('GITHUB_WORKSPACE is not defined');\n valid = false;\n }\n if (!valid) {\n throw new Error('Required Actions environment variables missing.');\n }\n else {\n return valid;\n }\n}\nfunction fromWorkflowInputs(ctx) {\n const evt = ctx.payload;\n if (!evt.inputs) {\n throw new Error('Event payload has no inputs');\n }\n const dependabotApiDockerUrl = evt.inputs.dependabotApiDockerUrl || evt.inputs.dependabotApiUrl;\n const workingDirectory = absoluteWorkingDirectory(evt.inputs.workingDirectory);\n return new JobParameters(parseInt(evt.inputs.jobId, 10), evt.inputs.jobToken, evt.inputs.credentialsToken, evt.inputs.dependabotApiUrl, dependabotApiDockerUrl, evt.inputs.updaterImage, workingDirectory);\n}\nfunction absoluteWorkingDirectory(workingDirectory) {\n const workspace = process.env.GITHUB_WORKSPACE;\n if (!workingDirectory) {\n throw new Error('The workingDirectory input must not be blank.');\n }\n if (!directoryExistsSync(workspace)) {\n throw new Error('The GITHUB_WORKSPACE directory does not exist.');\n }\n const fullPath = path_1.default.join(workspace, workingDirectory);\n if (!directoryExistsSync(fullPath)) {\n throw new Error(`The workingDirectory '${workingDirectory}' does not exist in GITHUB_WORKSPACE`);\n }\n return fullPath;\n}\nfunction directoryExistsSync(directoryPath) {\n let stats;\n try {\n stats = fs_1.default.statSync(directoryPath);\n return stats.isDirectory();\n }\n catch (error) {\n if (isNodeError(error) && error.code === 'ENOENT') {\n return false;\n }\n else if (error instanceof Error) {\n throw new Error(`Encountered an error when checking whether path '${directoryPath}' exists: ${error.message}`);\n }\n }\n return false;\n}\nfunction isNodeError(error) {\n return error instanceof Error;\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.run = exports.DependabotErrorType = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst github = __importStar(require(\"@actions/github\"));\nconst httpClient = __importStar(require(\"@actions/http-client\"));\nconst api_client_1 = require(\"./api-client\");\nconst inputs_1 = require(\"./inputs\");\nconst image_service_1 = require(\"./image-service\");\nconst docker_tags_1 = require(\"./docker-tags\");\nconst updater_1 = require(\"./updater\");\nvar DependabotErrorType;\n(function (DependabotErrorType) {\n DependabotErrorType[\"Unknown\"] = \"actions_workflow_unknown\";\n DependabotErrorType[\"Image\"] = \"actions_workflow_image\";\n DependabotErrorType[\"UpdateRun\"] = \"actions_workflow_updater\";\n})(DependabotErrorType || (exports.DependabotErrorType = DependabotErrorType = {}));\nlet jobId;\nfunction run(context) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n botSay('starting update');\n // Retrieve JobParameters from the Actions environment\n const params = (0, inputs_1.getJobParameters)(context);\n // The parameters will be null if the Action environment\n // is not a valid Dependabot-triggered dynamic event.\n if (params === null) {\n botSay('finished: nothing to do');\n return; // TODO: This should be setNeutral in future\n }\n // Use environment variables if set and not empty, otherwise use parameters.\n // The param values of job token and credentials token are kept to support backwards compatibility.\n const jobToken = process.env.GITHUB_DEPENDABOT_JOB_TOKEN || params.jobToken;\n const credentialsToken = process.env.GITHUB_DEPENDABOT_CRED_TOKEN || params.credentialsToken;\n // Validate jobToken and credentialsToken\n if (!jobToken) {\n const errorMessage = 'Github Dependabot job token is not set';\n botSay(`finished: ${errorMessage}`);\n core.setFailed(errorMessage);\n return;\n }\n if (!credentialsToken) {\n const errorMessage = 'Github Dependabot credentials token is not set';\n botSay(`finished: ${errorMessage}`);\n core.setFailed(errorMessage);\n return;\n }\n jobId = params.jobId;\n core.setSecret(jobToken);\n core.setSecret(credentialsToken);\n const client = new httpClient.HttpClient('github/dependabot-action');\n const apiClient = new api_client_1.ApiClient(client, params, jobToken, credentialsToken);\n core.info('Fetching job details');\n // If we fail to succeed in fetching the job details, we cannot be sure the job has entered a 'processing' state,\n // so we do not try attempt to report back an exception if this fails and instead rely on the workflow run\n // webhook as it anticipates scenarios where jobs have failed while 'enqueued'.\n const details = yield apiClient.getJobDetails();\n // The dynamic workflow can specify which updater image to use. If it doesn't, fall back to the pinned version.\n const updaterImage = params.updaterImage || (0, docker_tags_1.updaterImageName)(details['package-manager']);\n try {\n const credentials = yield apiClient.getCredentials();\n const updater = new updater_1.Updater(updaterImage, docker_tags_1.PROXY_IMAGE_NAME, apiClient, details, credentials, params.workingDirectory);\n core.startGroup('Pulling updater images');\n try {\n yield image_service_1.ImageService.pull(updaterImage);\n yield image_service_1.ImageService.pull(docker_tags_1.PROXY_IMAGE_NAME);\n }\n catch (error) {\n if (error instanceof Error) {\n yield failJob(apiClient, 'Error fetching updater images', error, DependabotErrorType.Image);\n return;\n }\n }\n core.endGroup();\n try {\n core.info('Starting update process');\n yield updater.runUpdater();\n }\n catch (error) {\n if (error instanceof Error) {\n yield failJob(apiClient, 'Dependabot encountered an error performing the update', error, DependabotErrorType.UpdateRun);\n return;\n }\n }\n botSay('finished');\n }\n catch (error) {\n if (error instanceof api_client_1.CredentialFetchingError) {\n yield failJob(apiClient, 'Dependabot was unable to retrieve job credentials', error, DependabotErrorType.UpdateRun);\n }\n else if (error instanceof Error) {\n yield failJob(apiClient, 'Dependabot was unable to start the update', error);\n }\n return;\n }\n }\n catch (error) {\n if (error instanceof Error) {\n // If we've reached this point, we do not have a viable\n // API client to report back to Dependabot API.\n //\n // We output the raw error in the Action logs and defer\n // to workflow_run monitoring to detect the job failure.\n setFailed('Dependabot encountered an unexpected problem', error);\n botSay('finished: unexpected error');\n }\n }\n });\n}\nexports.run = run;\nfunction failJob(apiClient_1, message_1, error_1) {\n return __awaiter(this, arguments, void 0, function* (apiClient, message, error, errorType = DependabotErrorType.Unknown) {\n yield apiClient.reportJobError({\n 'error-type': errorType,\n 'error-details': {\n 'action-error': error.message\n }\n });\n yield apiClient.markJobAsProcessed();\n setFailed(message, error);\n botSay('finished: error reported to Dependabot');\n });\n}\nfunction botSay(message) {\n core.info(`🤖 ~ ${message} ~`);\n}\nfunction setFailed(message, error) {\n if (jobId) {\n message = [message, error, dependabotJobHelp()].filter(Boolean).join('\\n\\n');\n }\n core.setFailed(message);\n}\nfunction dependabotJobHelp() {\n if (jobId) {\n return `For more information see: ${dependabotJobUrl(jobId)} (write access to the repository is required to view the log)`;\n }\n else {\n return null;\n }\n}\nfunction dependabotJobUrl(id) {\n const url_parts = [\n process.env.GITHUB_SERVER_URL,\n process.env.GITHUB_REPOSITORY,\n 'network/updates',\n id\n ];\n return url_parts.filter(Boolean).join('/');\n}\nrun(github.context);\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProxyBuilder = void 0;\nconst fs_1 = __importDefault(require(\"fs\"));\nconst core = __importStar(require(\"@actions/core\"));\nconst container_service_1 = require(\"./container-service\");\nconst node_forge_1 = require(\"node-forge\");\nconst utils_1 = require(\"./utils\");\nconst KEY_SIZE = 2048;\nconst KEY_EXPIRY_YEARS = 2;\nconst CONFIG_FILE_PATH = '/';\nconst CONFIG_FILE_NAME = 'config.json';\nconst CA_CERT_INPUT_PATH = '/usr/local/share/ca-certificates';\nconst CUSTOM_CA_CERT_NAME = 'custom-ca-cert.crt';\nconst CERT_SUBJECT = [\n {\n name: 'commonName',\n value: 'Dependabot Internal CA'\n },\n {\n name: 'organizationName',\n value: 'GitHub ic.'\n },\n {\n shortName: 'OU',\n value: 'Dependabot'\n },\n {\n name: 'countryName',\n value: 'US'\n },\n {\n shortName: 'ST',\n value: 'California'\n },\n {\n name: 'localityName',\n value: 'San Francisco'\n }\n];\nclass ProxyBuilder {\n constructor(docker, proxyImage, cachedMode) {\n this.docker = docker;\n this.proxyImage = proxyImage;\n this.cachedMode = cachedMode;\n }\n run(jobId, jobToken, dependabotApiUrl, credentials) {\n return __awaiter(this, void 0, void 0, function* () {\n const name = `dependabot-job-${jobId}-proxy`;\n const config = this.buildProxyConfig(credentials);\n const cert = config.ca.cert;\n const externalNetworkName = `dependabot-job-${jobId}-external-network`;\n const externalNetwork = yield this.ensureNetwork(externalNetworkName, false);\n const internalNetworkName = `dependabot-job-${jobId}-internal-network`;\n const internalNetwork = yield this.ensureNetwork(internalNetworkName, true);\n const container = yield this.createContainer(jobId, jobToken, dependabotApiUrl, name, externalNetwork, internalNetwork, internalNetworkName);\n yield container_service_1.ContainerService.storeInput(CONFIG_FILE_NAME, CONFIG_FILE_PATH, container, config);\n const customCAPath = this.customCAPath();\n if (customCAPath) {\n core.info('Detected custom CA certificate, adding to proxy');\n const customCert = fs_1.default.readFileSync(customCAPath, 'utf8').toString();\n yield container_service_1.ContainerService.storeCert(CUSTOM_CA_CERT_NAME, CA_CERT_INPUT_PATH, container, customCert);\n }\n const stream = yield container.attach({\n stream: true,\n stdout: true,\n stderr: true\n });\n container.modem.demuxStream(stream, (0, utils_1.outStream)(' proxy'), (0, utils_1.errStream)(' proxy'));\n const url = () => __awaiter(this, void 0, void 0, function* () {\n const containerInfo = yield container.inspect();\n if (containerInfo.State.Running === true) {\n const ipAddress = containerInfo.NetworkSettings.Networks[`${internalNetworkName}`]\n .IPAddress;\n return `http://${ipAddress}:1080`;\n }\n else {\n throw new Error(\"proxy container isn't running\");\n }\n });\n return {\n container,\n network: internalNetwork,\n networkName: internalNetworkName,\n url,\n cert,\n shutdown: () => __awaiter(this, void 0, void 0, function* () {\n yield container.stop();\n yield container.remove();\n yield Promise.all([externalNetwork.remove(), internalNetwork.remove()]);\n })\n };\n });\n }\n ensureNetwork(name_1) {\n return __awaiter(this, arguments, void 0, function* (name, internal = true) {\n const networks = yield this.docker.listNetworks({\n filters: JSON.stringify({ name: [name] })\n });\n if (networks.length > 0) {\n return this.docker.getNetwork(networks[0].Id);\n }\n else {\n return yield this.docker.createNetwork({ Name: name, Internal: internal });\n }\n });\n }\n buildProxyConfig(credentials) {\n const ca = this.generateCertificateAuthority();\n const config = { all_credentials: credentials, ca };\n return config;\n }\n generateCertificateAuthority() {\n const keys = node_forge_1.pki.rsa.generateKeyPair(KEY_SIZE);\n const cert = node_forge_1.pki.createCertificate();\n cert.publicKey = keys.publicKey;\n cert.serialNumber = '01';\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + KEY_EXPIRY_YEARS);\n cert.setSubject(CERT_SUBJECT);\n cert.setIssuer(CERT_SUBJECT);\n cert.setExtensions([{ name: 'basicConstraints', cA: true }]);\n cert.sign(keys.privateKey);\n const pem = node_forge_1.pki.certificateToPem(cert);\n const key = node_forge_1.pki.privateKeyToPem(keys.privateKey);\n return { cert: pem, key };\n }\n createContainer(jobId, jobToken, dependabotApiUrl, containerName, externalNetwork, internalNetwork, internalNetworkName) {\n return __awaiter(this, void 0, void 0, function* () {\n const container = yield this.docker.createContainer({\n Image: this.proxyImage,\n name: containerName,\n AttachStdout: true,\n AttachStderr: true,\n Env: [\n `http_proxy=${process.env.http_proxy || process.env.HTTP_PROXY || ''}`,\n `https_proxy=${process.env.https_proxy || process.env.HTTPS_PROXY || ''}`,\n `no_proxy=${process.env.no_proxy || process.env.NO_PROXY || ''}`,\n `JOB_ID=${jobId}`,\n `JOB_TOKEN=${jobToken}`,\n `PROXY_CACHE=${this.cachedMode ? 'true' : 'false'}`,\n `DEPENDABOT_API_URL=${dependabotApiUrl}`\n ],\n Entrypoint: [\n 'sh',\n '-c',\n '/usr/sbin/update-ca-certificates && /update-job-proxy'\n ],\n HostConfig: {\n NetworkMode: internalNetworkName\n }\n });\n yield externalNetwork.connect({ Container: container.id });\n core.info(`Created proxy container: ${container.id}`);\n return container;\n });\n }\n customCAPath() {\n if ('CUSTOM_CA_PATH' in process.env) {\n return process.env.CUSTOM_CA_PATH;\n }\n // default to node.js configuration\n return process.env.NODE_EXTRA_CA_CERTS;\n }\n}\nexports.ProxyBuilder = ProxyBuilder;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UpdaterBuilder = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst container_service_1 = require(\"./container-service\");\nconst JOB_OUTPUT_FILENAME = 'output.json';\nconst JOB_OUTPUT_PATH = '/home/dependabot/dependabot-updater/output';\nconst JOB_INPUT_FILENAME = 'job.json';\nconst JOB_INPUT_PATH = `/home/dependabot/dependabot-updater`;\nconst REPO_CONTENTS_PATH = '/home/dependabot/dependabot-updater/repo';\nconst CA_CERT_INPUT_PATH = '/usr/local/share/ca-certificates';\nconst CA_CERT_FILENAME = 'dbot-ca.crt';\nconst UPDATER_MAX_MEMORY = 8 * 1024 * 1024 * 1024; // 8GB in bytes\nclass UpdaterBuilder {\n constructor(docker, jobParams, input, outputHostPath, proxy, updaterImage) {\n this.docker = docker;\n this.jobParams = jobParams;\n this.input = input;\n this.outputHostPath = outputHostPath;\n this.proxy = proxy;\n this.updaterImage = updaterImage;\n }\n run(containerName) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = `/usr/sbin/update-ca-certificates &&\\\n mkdir -p ${JOB_OUTPUT_PATH} &&\\\n $DEPENDABOT_HOME/dependabot-updater/bin/run fetch_files &&\\\n $DEPENDABOT_HOME/dependabot-updater/bin/run update_files`;\n const proxyUrl = yield this.proxy.url();\n const container = yield this.docker.createContainer({\n Image: this.updaterImage,\n name: containerName,\n AttachStdout: true,\n AttachStderr: true,\n Env: [\n `GITHUB_ACTIONS=${process.env.GITHUB_ACTIONS}`,\n `DEPENDABOT_JOB_ID=${this.jobParams.jobId}`,\n `DEPENDABOT_JOB_TOKEN=`,\n `DEPENDABOT_JOB_PATH=${JOB_INPUT_PATH}/${JOB_INPUT_FILENAME}`,\n `DEPENDABOT_OPEN_TIMEOUT_IN_SECONDS=15`,\n `DEPENDABOT_OUTPUT_PATH=${JOB_OUTPUT_PATH}/${JOB_OUTPUT_FILENAME}`,\n `DEPENDABOT_REPO_CONTENTS_PATH=${REPO_CONTENTS_PATH}`,\n `DEPENDABOT_API_URL=${this.jobParams.dependabotApiDockerUrl}`,\n `SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt`,\n `http_proxy=${proxyUrl}`,\n `HTTP_PROXY=${proxyUrl}`,\n `https_proxy=${proxyUrl}`,\n `HTTPS_PROXY=${proxyUrl}`,\n `UPDATER_ONE_CONTAINER=1`,\n `ENABLE_CONNECTIVITY_CHECK=${process.env.DEPENDABOT_ENABLE_CONNECTIVITY_CHECK || '1'}`\n ],\n Cmd: ['sh', '-c', cmd],\n HostConfig: {\n Memory: UPDATER_MAX_MEMORY,\n NetworkMode: this.proxy.networkName\n }\n });\n yield container_service_1.ContainerService.storeCert(CA_CERT_FILENAME, CA_CERT_INPUT_PATH, container, this.proxy.cert);\n yield container_service_1.ContainerService.storeInput(JOB_INPUT_FILENAME, JOB_INPUT_PATH, container, this.input);\n core.info(`Created container: ${container.id}`);\n return container;\n });\n }\n}\nexports.UpdaterBuilder = UpdaterBuilder;\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Updater = void 0;\nconst dockerode_1 = __importDefault(require(\"dockerode\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst fs_1 = __importDefault(require(\"fs\"));\nconst container_service_1 = require(\"./container-service\");\nconst proxy_1 = require(\"./proxy\");\nconst updater_builder_1 = require(\"./updater-builder\");\nclass Updater {\n constructor(updaterImage, proxyImage, apiClient, details, credentials, workingDirectory) {\n this.updaterImage = updaterImage;\n this.proxyImage = proxyImage;\n this.apiClient = apiClient;\n this.details = details;\n this.credentials = credentials;\n this.workingDirectory = workingDirectory;\n this.docker = new dockerode_1.default();\n this.outputHostPath = path_1.default.join(workingDirectory, 'output');\n this.repoHostPath = path_1.default.join(workingDirectory, 'repo');\n }\n /**\n * Execute an update job and report the result to Dependabot API.\n */\n runUpdater() {\n return __awaiter(this, void 0, void 0, function* () {\n var _a;\n // Create required folders in the workingDirectory\n fs_1.default.mkdirSync(this.outputHostPath);\n const cachedMode = ((_a = this.details.experiments) === null || _a === void 0 ? void 0 : _a.hasOwnProperty('proxy-cached')) === true;\n const proxyBuilder = new proxy_1.ProxyBuilder(this.docker, this.proxyImage, cachedMode);\n const proxy = yield proxyBuilder.run(this.apiClient.params.jobId, this.apiClient.getJobToken(), this.apiClient.params.dependabotApiUrl, this.credentials);\n yield proxy.container.start();\n try {\n yield this.runUpdate(proxy);\n return true;\n }\n finally {\n yield this.cleanup(proxy);\n }\n });\n }\n runUpdate(proxy) {\n return __awaiter(this, void 0, void 0, function* () {\n const name = `dependabot-job-${this.apiClient.params.jobId}`;\n const container = yield this.createContainer(proxy, name, {\n job: this.details\n });\n yield container_service_1.ContainerService.run(container);\n });\n }\n createContainer(proxy, containerName, input) {\n return __awaiter(this, void 0, void 0, function* () {\n return new updater_builder_1.UpdaterBuilder(this.docker, this.apiClient.params, input, this.outputHostPath, proxy, this.updaterImage).run(containerName);\n });\n }\n cleanup(proxy) {\n return __awaiter(this, void 0, void 0, function* () {\n yield proxy.shutdown();\n if (fs_1.default.existsSync(this.outputHostPath)) {\n fs_1.default.rmSync(this.outputHostPath, { recursive: true });\n }\n if (fs_1.default.existsSync(this.repoHostPath)) {\n fs_1.default.rmSync(this.repoHostPath, { recursive: true });\n }\n });\n }\n}\nexports.Updater = Updater;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.errStream = exports.outStream = exports.base64DecodeDependencyFile = void 0;\nconst stream_1 = __importDefault(require(\"stream\"));\nconst base64Decode = (str) => Buffer.from(str, 'base64').toString('binary');\nconst base64DecodeDependencyFile = (file) => {\n const fileCopy = JSON.parse(JSON.stringify(file));\n fileCopy.content = base64Decode(fileCopy.content);\n return fileCopy;\n};\nexports.base64DecodeDependencyFile = base64DecodeDependencyFile;\nconst outStream = (prefix) => {\n return new stream_1.default.Writable({\n write(chunk, _, next) {\n process.stderr.write(`${prefix} | ${chunk.toString()}`);\n next();\n }\n });\n};\nexports.outStream = outStream;\nconst errStream = (prefix) => {\n return new stream_1.default.Writable({\n write(chunk, _, next) {\n process.stderr.write(`${prefix} | ${chunk.toString()}`);\n next();\n }\n });\n};\nexports.errStream = errStream;\n","module.exports = __non_webpack_require__(__webpack_require__.ab + \"build/Release/cpufeatures.node\")","module.exports = __non_webpack_require__(__webpack_require__.ab + \"lib/protocol/crypto/build/Release/sshcrypto.node\")","module.exports = require(\"assert\");","module.exports = require(\"async_hooks\");","module.exports = require(\"buffer\");","module.exports = require(\"child_process\");","module.exports = require(\"console\");","module.exports = require(\"constants\");","module.exports = require(\"crypto\");","module.exports = require(\"diagnostics_channel\");","module.exports = require(\"dns\");","module.exports = require(\"events\");","module.exports = require(\"fs\");","module.exports = require(\"http\");","module.exports = require(\"http2\");","module.exports = require(\"https\");","module.exports = require(\"net\");","module.exports = require(\"node:events\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","module.exports = require(\"os\");","module.exports = require(\"path\");","module.exports = require(\"perf_hooks\");","module.exports = require(\"querystring\");","module.exports = require(\"stream\");","module.exports = require(\"stream/web\");","module.exports = require(\"string_decoder\");","module.exports = require(\"tls\");","module.exports = require(\"tty\");","module.exports = require(\"url\");","module.exports = require(\"util\");","module.exports = require(\"util/types\");","module.exports = require(\"worker_threads\");","module.exports = require(\"zlib\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\tvar threw = true;\n\ttry {\n\t\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\t\tthrew = false;\n\t} finally {\n\t\tif(threw) delete __webpack_module_cache__[moduleId];\n\t}\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","\nif (typeof __webpack_require__ !== 'undefined') __webpack_require__.ab = __dirname + \"/\";","","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(399);\n",""],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/dist/main/licenses.txt b/dist/main/licenses.txt index faf304013..9f88e2f08 100644 --- a/dist/main/licenses.txt +++ b/dist/main/licenses.txt @@ -47,6 +47,238 @@ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +@balena/dockerignore +Apache-2.0 + +* Copyright 2020 Balena Ltd. under the Apache 2.0 License included in this file. +* Copyright 2018 Zeit Inc. under the MIT License included in this file. + +-------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +-------------------------------------------------------------------------- + +The MIT License (MIT) + +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. + +-------------------------------------------------------------------------- + + +@fastify/busboy +MIT +Copyright Brian White. All rights reserved. + +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. + @octokit/auth-token MIT The MIT License @@ -219,16 +451,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -@vercel/ncc -MIT -Copyright 2018 ZEIT, Inc. - -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. - asn1 MIT Copyright (c) 2011 Mark Cavage, All rights reserved. @@ -252,27 +474,23 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE -axios -MIT -Copyright (c) 2014-present Matt Zabriskie +b4a +ISC +ISC License -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Copyright (c) 2021 Contributors -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. -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. +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. bcrypt-pbkdf @@ -612,21 +830,22 @@ debug MIT (The MIT License) -Copyright (c) 2014 TJ Holowaychuk +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon -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, +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 +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 +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. @@ -1084,26 +1303,29 @@ 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. -follow-redirects +fast-fifo MIT -Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh +The MIT License (MIT) -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: +Copyright (c) 2019 Mathias Buus -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +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. +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. fs-constants @@ -1164,31 +1386,6 @@ PERFORMANCE OF THIS SOFTWARE. -is-plain-object -MIT -The MIT License (MIT) - -Copyright (c) 2014-2017, Jon Schlinkert. - -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. - - mkdirp-classic MIT The MIT License (MIT) @@ -1239,32 +1436,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -node-fetch -MIT -The MIT License (MIT) - -Copyright (c) 2016 David Frank - -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. - - - node-forge (BSD-3-Clause OR GPL-2.0) You may use the Forge project under the terms of either the BSD License or the @@ -1643,6 +1814,31 @@ 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. +queue-tick +MIT +The MIT License (MIT) + +Copyright (c) 2021 Mathias Buus + +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. + + readable-stream MIT Node.js is licensed for use as follows: @@ -1769,6 +1965,31 @@ 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. +streamx +MIT +The MIT License (MIT) + +Copyright (c) 2019 Mathias Buus + +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. + + string_decoder MIT Node.js is licensed for use as follows: @@ -1882,9 +2103,6 @@ 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. -tr46 -MIT - tunnel MIT The MIT License (MIT) @@ -1938,6 +2156,31 @@ OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to +undici +MIT +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +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. + + universal-user-agent ISC # [ISC License](https://spdx.org/licenses/ISC) @@ -1990,47 +2233,6 @@ The above copyright notice and this permission notice shall be included in all c 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. -webidl-conversions -BSD-2-Clause -# The BSD 2-Clause License - -Copyright (c) 2014, Domenic Denicola -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -whatwg-url -MIT -The MIT License (MIT) - -Copyright (c) 2015–2016 Sebastian Mayr - -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. - - wrappy ISC The ISC License diff --git a/docker/Dockerfile.bundler b/docker/Dockerfile.bundler new file mode 100644 index 000000000..9fa243f68 --- /dev/null +++ b/docker/Dockerfile.bundler @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-bundler:v2.0.20241107222650@sha256:3cf4cafa6016c78e372fb29cac35472ed261c57b084b326747429afee2199c1b diff --git a/docker/Dockerfile.cargo b/docker/Dockerfile.cargo new file mode 100644 index 000000000..879f1c583 --- /dev/null +++ b/docker/Dockerfile.cargo @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-cargo:v2.0.20241107222650@sha256:91f64f9e49c36fc5b683756997060565dff67c5e30a1d5588ade386d2a79c8ec diff --git a/docker/Dockerfile.composer b/docker/Dockerfile.composer new file mode 100644 index 000000000..42589aa68 --- /dev/null +++ b/docker/Dockerfile.composer @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-composer:v2.0.20241107222650@sha256:0fbb307c6e249c08498527b9c3ceb23b761dd9d55bcca2f74cd0ca81a8914740 diff --git a/docker/Dockerfile.devcontainers b/docker/Dockerfile.devcontainers new file mode 100644 index 000000000..d2c11db74 --- /dev/null +++ b/docker/Dockerfile.devcontainers @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-devcontainers:v2.0.20241107222650@sha256:5273198c7c9d2490c6c1147b0e79a7d5351a8fa6f4ad37fdfffe434b7b569c32 diff --git a/docker/Dockerfile.docker b/docker/Dockerfile.docker new file mode 100644 index 000000000..ee2794177 --- /dev/null +++ b/docker/Dockerfile.docker @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-docker:v2.0.20241107222650@sha256:3d44776d7a87cc5fc4c9d61678b03d6efc388901702697e514ed70823b440aba diff --git a/docker/Dockerfile.elm b/docker/Dockerfile.elm new file mode 100644 index 000000000..c312fdcec --- /dev/null +++ b/docker/Dockerfile.elm @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-elm:v2.0.20241107222650@sha256:16e94bdb0144ef7398b66d81388d7eb437dd8f5b514171d13cb858cc171efa05 diff --git a/docker/Dockerfile.github-actions b/docker/Dockerfile.github-actions new file mode 100644 index 000000000..c0a1a960c --- /dev/null +++ b/docker/Dockerfile.github-actions @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-github-actions:v2.0.20241107222650@sha256:c58910178f005aecfbdc41e0610f76ded7a4c5dc333521a33b3d6985c2eb9dc0 diff --git a/docker/Dockerfile.gitsubmodule b/docker/Dockerfile.gitsubmodule new file mode 100644 index 000000000..9c728906e --- /dev/null +++ b/docker/Dockerfile.gitsubmodule @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-gitsubmodule:v2.0.20241107222650@sha256:2a6bc87850734c8e3116c7020d6681b49151e201c43a0b590288e812a0336023 diff --git a/docker/Dockerfile.gomod b/docker/Dockerfile.gomod new file mode 100644 index 000000000..9c7096b65 --- /dev/null +++ b/docker/Dockerfile.gomod @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-gomod:v2.0.20241107222650@sha256:77980075afb1a74eae6f63764f1cb26fcd6e146c90ac91a9ed77db25da55a008 diff --git a/docker/Dockerfile.gradle b/docker/Dockerfile.gradle new file mode 100644 index 000000000..48c4d3923 --- /dev/null +++ b/docker/Dockerfile.gradle @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-gradle:v2.0.20241107222650@sha256:8108e23b0d3a76dacea69f3756c89a3d6d35bcca3c2f975a61c1bfde815d7ee9 diff --git a/docker/Dockerfile.maven b/docker/Dockerfile.maven new file mode 100644 index 000000000..93dfa8c0c --- /dev/null +++ b/docker/Dockerfile.maven @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-maven:v2.0.20241107222650@sha256:eadf9c29977e411420ca3fa9bb89e79f0a49872a87c3cd718721714782144a0b diff --git a/docker/Dockerfile.mix b/docker/Dockerfile.mix new file mode 100644 index 000000000..ddedb70d5 --- /dev/null +++ b/docker/Dockerfile.mix @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-mix:v2.0.20241107222650@sha256:0460f703a613ff38dd2ad61ef7d079070f37cbbb14f57e764c9427a4ee46b831 diff --git a/docker/Dockerfile.npm b/docker/Dockerfile.npm new file mode 100644 index 000000000..0e05da59e --- /dev/null +++ b/docker/Dockerfile.npm @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-npm:v2.0.20241107222650@sha256:f187a18dbf871c71124d59c970e551d76196384e8d266da70a9c8c6417cb88fc diff --git a/docker/Dockerfile.nuget b/docker/Dockerfile.nuget new file mode 100644 index 000000000..44d8a0ea8 --- /dev/null +++ b/docker/Dockerfile.nuget @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-nuget:v2.0.20241107222650@sha256:d2f293e19cd21467c73d0d967febb865184f5059c8b40fa9d73cd05810267b10 diff --git a/docker/Dockerfile.pip b/docker/Dockerfile.pip new file mode 100644 index 000000000..551376bf1 --- /dev/null +++ b/docker/Dockerfile.pip @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-pip:v2.0.20241107222650@sha256:3dc06304cabaa7839388fb7c87b2cfa7d3cddf6c648e810415b025f3498b084c diff --git a/docker/Dockerfile.proxy b/docker/Dockerfile.proxy index eb9200c4e..98d7f1b78 100644 --- a/docker/Dockerfile.proxy +++ b/docker/Dockerfile.proxy @@ -1 +1 @@ -FROM ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy@sha256:4714e9c495d7af0a83347517703cf524e2793f58625e4285e323d5d890a7cfa4 +FROM ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy:v2.0.20241004183849@sha256:5e895b5edfaba72e99d0a19b43f386b18b65fc08a2d43af5aedd6360cda56842 diff --git a/docker/Dockerfile.pub b/docker/Dockerfile.pub new file mode 100644 index 000000000..0b0268bb5 --- /dev/null +++ b/docker/Dockerfile.pub @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-pub:v2.0.20241107222650@sha256:ce2b994ba59765b847251036a7a66f7d32e6a7076ae455f80bb6bf8cad2f16fc diff --git a/docker/Dockerfile.swift b/docker/Dockerfile.swift new file mode 100644 index 000000000..2f2fbf538 --- /dev/null +++ b/docker/Dockerfile.swift @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-swift:v2.0.20241107141918@sha256:4935ce7bd14b783e4838a38e59c6e2eae25e0ca7b0a11cd779d04a064ba8b654 diff --git a/docker/Dockerfile.terraform b/docker/Dockerfile.terraform new file mode 100644 index 000000000..37d4be409 --- /dev/null +++ b/docker/Dockerfile.terraform @@ -0,0 +1 @@ +FROM ghcr.io/dependabot/dependabot-updater-terraform:v2.0.20241107222650@sha256:d28f3845ae8cf4cbf1ae0f8ea0622da31cd1035a0eda18a3229e125fba0d224c diff --git a/docker/Dockerfile.updater b/docker/Dockerfile.updater deleted file mode 100644 index e6993af30..000000000 --- a/docker/Dockerfile.updater +++ /dev/null @@ -1 +0,0 @@ -FROM ghcr.io/dependabot/dependabot-updater@sha256:85108a36530c8ee66027eb798b62aabe0b31d2972a902375ff9baf862777cb38 diff --git a/docker/README.md b/docker/README.md index 3179732ed..1b83cd9d3 100644 --- a/docker/README.md +++ b/docker/README.md @@ -3,7 +3,7 @@ This Action uses two Dependabot containers from the GitHub Container Registry to perform jobs. In order to ensure that any given release of the Action deterministically uses the same, tested containers we -uses these Dockerfiles to check-in the specific SHA for each. +use these Dockerfiles to check-in the specific SHA for each. This allows us to use Dependabot to keep these SHAs up to date as new versions of the container are published. diff --git a/docker/containers.json b/docker/containers.json index 4b2ea847f..6e6ad933b 100644 --- a/docker/containers.json +++ b/docker/containers.json @@ -1,4 +1,21 @@ { - "proxy": "ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy@sha256:4714e9c495d7af0a83347517703cf524e2793f58625e4285e323d5d890a7cfa4", - "updater": "ghcr.io/dependabot/dependabot-updater@sha256:85108a36530c8ee66027eb798b62aabe0b31d2972a902375ff9baf862777cb38" + "proxy": "ghcr.io/github/dependabot-update-job-proxy/dependabot-update-job-proxy:v2.0.20241004183849@sha256:5e895b5edfaba72e99d0a19b43f386b18b65fc08a2d43af5aedd6360cda56842", + "bundler": "ghcr.io/dependabot/dependabot-updater-bundler:v2.0.20241107222650@sha256:3cf4cafa6016c78e372fb29cac35472ed261c57b084b326747429afee2199c1b", + "cargo": "ghcr.io/dependabot/dependabot-updater-cargo:v2.0.20241107222650@sha256:91f64f9e49c36fc5b683756997060565dff67c5e30a1d5588ade386d2a79c8ec", + "composer": "ghcr.io/dependabot/dependabot-updater-composer:v2.0.20241107222650@sha256:0fbb307c6e249c08498527b9c3ceb23b761dd9d55bcca2f74cd0ca81a8914740", + "pub": "ghcr.io/dependabot/dependabot-updater-pub:v2.0.20241107222650@sha256:ce2b994ba59765b847251036a7a66f7d32e6a7076ae455f80bb6bf8cad2f16fc", + "docker": "ghcr.io/dependabot/dependabot-updater-docker:v2.0.20241107222650@sha256:3d44776d7a87cc5fc4c9d61678b03d6efc388901702697e514ed70823b440aba", + "elm": "ghcr.io/dependabot/dependabot-updater-elm:v2.0.20241107222650@sha256:16e94bdb0144ef7398b66d81388d7eb437dd8f5b514171d13cb858cc171efa05", + "github_actions": "ghcr.io/dependabot/dependabot-updater-github-actions:v2.0.20241107222650@sha256:c58910178f005aecfbdc41e0610f76ded7a4c5dc333521a33b3d6985c2eb9dc0", + "submodules": "ghcr.io/dependabot/dependabot-updater-gitsubmodule:v2.0.20241107222650@sha256:2a6bc87850734c8e3116c7020d6681b49151e201c43a0b590288e812a0336023", + "go_modules": "ghcr.io/dependabot/dependabot-updater-gomod:v2.0.20241107222650@sha256:77980075afb1a74eae6f63764f1cb26fcd6e146c90ac91a9ed77db25da55a008", + "gradle": "ghcr.io/dependabot/dependabot-updater-gradle:v2.0.20241107222650@sha256:8108e23b0d3a76dacea69f3756c89a3d6d35bcca3c2f975a61c1bfde815d7ee9", + "maven": "ghcr.io/dependabot/dependabot-updater-maven:v2.0.20241107222650@sha256:eadf9c29977e411420ca3fa9bb89e79f0a49872a87c3cd718721714782144a0b", + "hex": "ghcr.io/dependabot/dependabot-updater-mix:v2.0.20241107222650@sha256:0460f703a613ff38dd2ad61ef7d079070f37cbbb14f57e764c9427a4ee46b831", + "nuget": "ghcr.io/dependabot/dependabot-updater-nuget:v2.0.20241107222650@sha256:d2f293e19cd21467c73d0d967febb865184f5059c8b40fa9d73cd05810267b10", + "npm_and_yarn": "ghcr.io/dependabot/dependabot-updater-npm:v2.0.20241107222650@sha256:f187a18dbf871c71124d59c970e551d76196384e8d266da70a9c8c6417cb88fc", + "pip": "ghcr.io/dependabot/dependabot-updater-pip:v2.0.20241107222650@sha256:3dc06304cabaa7839388fb7c87b2cfa7d3cddf6c648e810415b025f3498b084c", + "swift": "ghcr.io/dependabot/dependabot-updater-swift:v2.0.20241107141918@sha256:4935ce7bd14b783e4838a38e59c6e2eae25e0ca7b0a11cd779d04a064ba8b654", + "terraform": "ghcr.io/dependabot/dependabot-updater-terraform:v2.0.20241107222650@sha256:d28f3845ae8cf4cbf1ae0f8ea0622da31cd1035a0eda18a3229e125fba0d224c", + "devcontainers": "ghcr.io/dependabot/dependabot-updater-devcontainers:v2.0.20241107222650@sha256:5273198c7c9d2490c6c1147b0e79a7d5351a8fa6f4ad37fdfffe434b7b569c32" } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 2d7ced0cf..a74a6de20 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,93 +1,169 @@ { "name": "dependabot-updater-action", - "version": "2.2.5", + "version": "2.20.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "dependabot-updater-action", - "version": "2.2.5", + "version": "2.20.0", "license": "MIT", "dependencies": { - "@actions/core": "^1.9.1", - "@actions/github": "^5.0.0", - "@octokit/webhooks-types": "^6.3.6", - "axios": "^0.23.0", - "ci": "^2.1.1", - "commander": "^9.1.0", - "dockerode": "^3.3.1", - "npm": "^8.18.0", - "tar-stream": "^2.2.0" + "@actions/core": "^1.10.1", + "@actions/github": "^6.0.0", + "@actions/http-client": "^2.2.1", + "@octokit/webhooks-types": "^7.5.1", + "commander": "^12.1.0", + "dockerode": "^4.0.2", + "node-forge": "^1.3.1", + "tar-stream": "^3.1.7" }, "devDependencies": { - "@types/dockerode": "^3.2.6", - "@types/jest": "^27.0.2", - "@types/node": "^18.7.13", - "@types/node-forge": "^1.0.1", - "@types/tar-stream": "^2.2.2", - "@typescript-eslint/parser": "^4.33.0", - "@vercel/ncc": "^0.34.0", - "eslint": "^7.32.0", - "eslint-config-prettier": "^8.3.0", - "eslint-plugin-github": "^4.1.5", - "eslint-plugin-jest": "^25.2.4", - "husky": "^7.0.4", - "jest": "^27.5.1", - "jest-circus": "^27.3.1", - "js-yaml": "^4.1.0", - "json-server": "^0.17.0", - "lint-staged": "^11.1.1", - "node-forge": "^1.2.1", - "prettier": "2.4.1", - "ts-jest": "^27.1.3", - "ts-node": "^10.9.1", - "typescript": "^4.8.4", - "wait-port": "^0.2.9" + "@types/dockerode": "^3.3.28", + "@types/jest": "^29.5.12", + "@types/node": "^20.12.7", + "@types/node-forge": "^1.3.11", + "@types/tar-stream": "^3.1.3", + "@typescript-eslint/parser": "^5.62.0", + "@vercel/ncc": "^0.38.1", + "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", + "eslint-import-resolver-typescript": "^3.6.1", + "eslint-plugin-github": "^4.10.2", + "eslint-plugin-jest": "^27.9.0", + "eslint-plugin-prettier": "^5.1.3", + "husky": "^9.0.11", + "jest": "^29.7.0", + "jest-circus": "^29.5.0", + "json-server": "^0.17.4", + "lint-staged": "^15.2.2", + "prettier": "3.2.5", + "ts-jest": "^29.1.2", + "ts-node": "^10.9.2", + "typescript": "^5.4.5", + "wait-port": "^1.1.0" + } + }, + "node_modules/@aashutoshrathi/word-wrap": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz", + "integrity": "sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==", + "dev": true, + "engines": { + "node": ">=0.10.0" } }, "node_modules/@actions/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.9.1.tgz", - "integrity": "sha512-5ad+U2YGrmmiw6du20AQW5XuWo7UKN2052FjSV7MX+Wfjf8sCqcsZe62NfgHys4QI4/Y+vQvLKYL8jWtA1ZBTA==", + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.1.tgz", + "integrity": "sha512-3lBR9EDAY+iYIpTnTIXmWcNbX3T2kCkAEQGIQx4NVQ0575nk2k3GRZDTPQG+vVtS2izSLmINlxXf0uLtnrTP+g==", "dependencies": { "@actions/http-client": "^2.0.1", "uuid": "^8.3.2" } }, - "node_modules/@actions/core/node_modules/@actions/http-client": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz", - "integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==", - "dependencies": { - "tunnel": "^0.0.6" - } - }, "node_modules/@actions/github": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@actions/github/-/github-5.0.0.tgz", - "integrity": "sha512-QvE9eAAfEsS+yOOk0cylLBIO/d6WyWIOvsxxzdrPFaud39G6BOkUwScXZn1iBzQzHyu9SBkkLSWlohDWdsasAQ==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@actions/github/-/github-6.0.0.tgz", + "integrity": "sha512-alScpSVnYmjNEXboZjarjukQEzgCRmjMv6Xj47fsdnqGS73bjJNDpiiXmp8jr0UZLdUB6d9jW63IcmddUP+l0g==", "dependencies": { - "@actions/http-client": "^1.0.11", - "@octokit/core": "^3.4.0", - "@octokit/plugin-paginate-rest": "^2.13.3", - "@octokit/plugin-rest-endpoint-methods": "^5.1.1" + "@actions/http-client": "^2.2.0", + "@octokit/core": "^5.0.1", + "@octokit/plugin-paginate-rest": "^9.0.0", + "@octokit/plugin-rest-endpoint-methods": "^10.0.0" } }, "node_modules/@actions/http-client": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.11.tgz", - "integrity": "sha512-VRYHGQV1rqnROJqdMvGUbY/Kn8vriQe/F9HR2AlYHzmKuM/p3kjNuXhmdBfcVgsvRWTz5C5XW5xvndZrVBuAYg==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.1.tgz", + "integrity": "sha512-KhC/cZsq7f8I4LfZSJKgCvEwfkE8o1538VoBeoGzokVLLnbFDEAdFD3UhoMklxo2un9NJVBdANOresx7vTHlHw==", "dependencies": { - "tunnel": "0.0.6" + "tunnel": "^0.0.6", + "undici": "^5.25.4" } }, "node_modules/@babel/code-frame": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", - "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", + "version": "7.22.13", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", + "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", + "dev": true, + "dependencies": { + "@babel/highlight": "^7.22.13", + "chalk": "^2.4.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/code-frame/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/code-frame/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "node_modules/@babel/code-frame/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/code-frame/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, "dependencies": { - "@babel/highlight": "^7.10.4" + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" } }, "node_modules/@babel/compat-data": { @@ -126,15 +202,6 @@ "url": "https://opencollective.com/babel" } }, - "node_modules/@babel/core/node_modules/@babel/code-frame": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", - "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, - "dependencies": { - "@babel/highlight": "^7.12.13" - } - }, "node_modules/@babel/core/node_modules/semver": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", @@ -154,23 +221,28 @@ } }, "node_modules/@babel/generator": { - "version": "7.14.3", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.14.3.tgz", - "integrity": "sha512-bn0S6flG/j0xtQdz3hsjJ624h3W0r3llttBMfyHX3YrZ/KtLYr15bjA0FXkgW7FpvrDuTuElXeVjiKlYRpnOFA==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.0.tgz", + "integrity": "sha512-lN85QRR+5IbYrMWM6Y4pE/noaQtg4pNiqeNGX60eqOfo6gtEj6uw/JagelB8vVztSd7R6M5n1+PQkDbHbBRU4g==", "dev": true, "dependencies": { - "@babel/types": "^7.14.2", - "jsesc": "^2.5.1", - "source-map": "^0.5.0" + "@babel/types": "^7.23.0", + "@jridgewell/gen-mapping": "^0.3.2", + "@jridgewell/trace-mapping": "^0.3.17", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" } }, - "node_modules/@babel/generator/node_modules/source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "node_modules/@babel/generator/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", "dev": true, - "engines": { - "node": ">=0.10.0" + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, "node_modules/@babel/helper-compilation-targets": { @@ -197,24 +269,38 @@ "semver": "bin/semver.js" } }, + "node_modules/@babel/helper-environment-visitor": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/helper-function-name": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.14.2.tgz", - "integrity": "sha512-NYZlkZRydxw+YT56IlhIcS8PAhb+FEUiOzuhFTfqDyPmzAhRge6ua0dQYT/Uh0t/EDHq05/i+e5M2d4XvjgarQ==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dev": true, "dependencies": { - "@babel/helper-get-function-arity": "^7.12.13", - "@babel/template": "^7.12.13", - "@babel/types": "^7.14.2" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" + }, + "engines": { + "node": ">=6.9.0" } }, - "node_modules/@babel/helper-get-function-arity": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.13.tgz", - "integrity": "sha512-DjEVzQNz5LICkzN0REdpD5prGoidvbdYk1BVgRUOINaWJP2t6avB27X1guXK1kXNrX0WMfsrm1A/ZBthYuIMQg==", + "node_modules/@babel/helper-hoist-variables": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", + "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", "dev": true, "dependencies": { - "@babel/types": "^7.12.13" + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" } }, "node_modules/@babel/helper-member-expression-to-functions": { @@ -261,10 +347,13 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.13.0", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.13.0.tgz", - "integrity": "sha512-ZPafIPSwzUlAoWT8DKs1W2VyF2gOWthGd5NGFMsBcMMol+ZhK+EQY/e6V96poa6PA/Bh+C9plWN0hXO1uB8AfQ==", - "dev": true + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.19.0.tgz", + "integrity": "sha512-40Ryx7I8mT+0gaNxm8JGTZFUITNqdLAgdg0hXzeVZxVD6nFsdhQvip6v8dqkRHzsz1VFpFAaOCHNn0vKBL7Czw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } }, "node_modules/@babel/helper-replace-supers": { "version": "7.14.4", @@ -288,19 +377,34 @@ } }, "node_modules/@babel/helper-split-export-declaration": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.12.13.tgz", - "integrity": "sha512-tCJDltF83htUtXx5NLcaDqRmknv652ZWCHyoTETf1CXYJdPC7nohZohjUgieXhv0hTJdRf2FjDueFehdNucpzg==", + "version": "7.22.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", + "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", "dev": true, "dependencies": { - "@babel/types": "^7.12.13" + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz", + "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==", + "dev": true, + "engines": { + "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.0.tgz", - "integrity": "sha512-V3ts7zMSu5lfiwWDVWzRDGIN+lnCEUdaXgtVHJgLb1rGaA6jMrtB9EmE7L18foXJIE8Un/A/h6NJfGQp/e1J4A==", - "dev": true + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } }, "node_modules/@babel/helper-validator-option": { "version": "7.12.17", @@ -320,14 +424,17 @@ } }, "node_modules/@babel/highlight": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.0.tgz", - "integrity": "sha512-YSCOwxvTYEIMSGaBQb5kDDsCopDdiUGsqpatp3fOlI4+2HQSkTmEVWnVuySdAC5EWCqSWWTv0ib63RjR7dTBdg==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", + "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", "dev": true, "dependencies": { - "@babel/helper-validator-identifier": "^7.14.0", - "chalk": "^2.0.0", + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" } }, "node_modules/@babel/highlight/node_modules/ansi-styles": { @@ -368,13 +475,13 @@ "node_modules/@babel/highlight/node_modules/color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", "dev": true }, "node_modules/@babel/highlight/node_modules/escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true, "engines": { "node": ">=0.8.0" @@ -383,7 +490,7 @@ "node_modules/@babel/highlight/node_modules/has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", "dev": true, "engines": { "node": ">=4" @@ -402,9 +509,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.17.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.17.3.tgz", - "integrity": "sha512-7yJPvPV+ESz2IUTPbOL+YkIGyCqOyNIzdguKQuJGnH7bg1WTIifuM21YqokFt/THWh1AkCRn9IgoykTRCBVpzA==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.0.tgz", + "integrity": "sha512-vvPKKdMemU85V9WE/l5wZEmImpCtLqbnTvqDS2U1fJ96KrxoW7KrXhNsNCblQlg8Ck4b85yxdTyelsMUgFUXiw==", "dev": true, "bin": { "parser": "bin/babel-parser.js" @@ -473,6 +580,21 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.18.6.tgz", + "integrity": "sha512-6mmljtAedFGTWu2p/8WIORGwy+61PLgOMPOdazc7YoJ9ZCWUyFy3A6CpPkRKLKD1ToAesxX8KGEViAiLo9N+7Q==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, "node_modules/@babel/plugin-syntax-logical-assignment-operators": { "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", @@ -558,60 +680,65 @@ } }, "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.12.13.tgz", - "integrity": "sha512-cHP3u1JiUiG2LFDKbXnwVad81GvfyIOmCD6HIEId6ojrY0Drfy2q1jw7BwN7dE84+kTnBjLkXoL3IEy/3JPu2w==", + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.18.6.tgz", + "integrity": "sha512-mAWAuq4rvOepWCBid55JuRNvpTNf2UGVgoz4JV0fXEKolsVZDzsa4NqCef758WZJj/GDu0gVGItjKFiClTAmZA==", "dev": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.12.13" + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, - "node_modules/@babel/template": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.12.13.tgz", - "integrity": "sha512-/7xxiGA57xMo/P2GVvdEumr8ONhFOhfgq2ihK3h1e6THqzTAkHbkXgB0xI9yeTfIUoH3+oAeHhqm/I43OTbbjA==", + "node_modules/@babel/runtime": { + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.21.0.tgz", + "integrity": "sha512-xwII0//EObnq89Ji5AKYQaRYiW/nZ3llSv29d49IuxPhKbtJoLP+9QUUZ4nVragQVtaVGeZrpB+ZtG/Pdy/POw==", "dev": true, "dependencies": { - "@babel/code-frame": "^7.12.13", - "@babel/parser": "^7.12.13", - "@babel/types": "^7.12.13" + "regenerator-runtime": "^0.13.11" + }, + "engines": { + "node": ">=6.9.0" } }, - "node_modules/@babel/template/node_modules/@babel/code-frame": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", - "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", + "node_modules/@babel/template": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", + "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", "dev": true, "dependencies": { - "@babel/highlight": "^7.12.13" + "@babel/code-frame": "^7.22.13", + "@babel/parser": "^7.22.15", + "@babel/types": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.14.2.tgz", - "integrity": "sha512-TsdRgvBFHMyHOOzcP9S6QU0QQtjxlRpEYOy3mcCO5RgmC305ki42aSAmfZEMSSYBla2oZ9BMqYlncBaKmD/7iA==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.12.13", - "@babel/generator": "^7.14.2", - "@babel/helper-function-name": "^7.14.2", - "@babel/helper-split-export-declaration": "^7.12.13", - "@babel/parser": "^7.14.2", - "@babel/types": "^7.14.2", + "version": "7.23.2", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.2.tgz", + "integrity": "sha512-azpe59SQ48qG6nu2CzcMLbxUudtN+dOM9kDbUqGq3HXUJRlo7i8fvPoxQUzYgLZ4cMVmuZgm8vvBpNeRhd6XSw==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.22.13", + "@babel/generator": "^7.23.0", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/parser": "^7.23.0", + "@babel/types": "^7.23.0", "debug": "^4.1.0", "globals": "^11.1.0" - } - }, - "node_modules/@babel/traverse/node_modules/@babel/code-frame": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", - "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, - "dependencies": { - "@babel/highlight": "^7.12.13" + }, + "engines": { + "node": ">=6.9.0" } }, "node_modules/@babel/traverse/node_modules/globals": { @@ -624,15 +751,24 @@ } }, "node_modules/@babel/types": { - "version": "7.14.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.14.4.tgz", - "integrity": "sha512-lCj4aIs0xUefJFQnwwQv2Bxg7Omd6bgquZ6LGC+gGMh6/s5qDVfjuCMlDmYQ15SLsWHd9n+X3E75lKIhl5Lkiw==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.0.tgz", + "integrity": "sha512-0oIyUfKoI3mSqMvsxBdclDwxXKXAUA8v/apZbc+iSyARYou1o8ZGDxbUYyLFoW2arqS2jDGqJuZvv1d/io1axg==", "dev": true, "dependencies": { - "@babel/helper-validator-identifier": "^7.14.0", + "@babel/helper-string-parser": "^7.22.5", + "@babel/helper-validator-identifier": "^7.22.20", "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" } }, + "node_modules/@balena/dockerignore": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@balena/dockerignore/-/dockerignore-1.0.2.tgz", + "integrity": "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q==" + }, "node_modules/@bcoe/v8-coverage": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", @@ -651,66 +787,116 @@ "node": ">=12" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", + "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^3.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.6.2.tgz", + "integrity": "sha512-pPTNuaAG3QMH+buKyBIGJs3g/S5y0caxw0ygM3YyE6yJFySwiGGSzA+mM3KJ8QQvzeLh3blwgSonkFjgQdxzMw==", + "dev": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, "node_modules/@eslint/eslintrc": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", - "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", + "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", "dev": true, "dependencies": { "ajv": "^6.12.4", - "debug": "^4.1.1", - "espree": "^7.3.0", - "globals": "^13.9.0", - "ignore": "^4.0.6", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", "import-fresh": "^3.2.1", - "js-yaml": "^3.13.1", - "minimatch": "^3.0.4", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, - "node_modules/@eslint/eslintrc/node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "node_modules/@eslint/js": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.0.tgz", + "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", "dev": true, - "dependencies": { - "sprintf-js": "~1.0.2" + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, - "node_modules/@eslint/eslintrc/node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" + "node_modules/@fastify/busboy": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.0.0.tgz", + "integrity": "sha512-JUFJad5lv7jxj926GPgymrWQxxjPYuJNiNjNMzqT+HiuP6Vl3dk5xzG+8sTX96np0ZAluvaMzPsjhHZ5rNuNQQ==", + "engines": { + "node": ">=14" } }, + "node_modules/@github/browserslist-config": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@github/browserslist-config/-/browserslist-config-1.0.0.tgz", + "integrity": "sha512-gIhjdJp/c2beaIWWIlsXdqXVRUz3r2BxBCpfz/F3JXHvSAQ1paMYjLH+maEATtENg+k5eLV7gA+9yPp762ieuw==", + "dev": true + }, "node_modules/@humanwhocodes/config-array": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", - "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "version": "0.11.14", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", + "integrity": "sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==", "dev": true, "dependencies": { - "@humanwhocodes/object-schema": "^1.2.0", - "debug": "^4.1.1", - "minimatch": "^3.0.4" + "@humanwhocodes/object-schema": "^2.0.2", + "debug": "^4.3.1", + "minimatch": "^3.0.5" }, "engines": { "node": ">=10.10.0" } }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, "node_modules/@humanwhocodes/object-schema": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz", - "integrity": "sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.2.tgz", + "integrity": "sha512-6EwiSjwWYP7pTckG6I5eyFANjPhmPjUX9JRLUSfNPC7FX7zK9gyZAfUEaECL6ALTpGX5AjnBq3C9XmVWPitNpw==", "dev": true }, "node_modules/@istanbuljs/load-nyc-config": { @@ -803,24 +989,6 @@ "node": ">=8" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", @@ -840,59 +1008,59 @@ } }, "node_modules/@jest/console": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-27.5.1.tgz", - "integrity": "sha512-kZ/tNpS3NXn0mlXXXPNuDZnb4c0oZ20r4K5eemM2k30ZC3G0T02nXUvyhf5YdbXWHPEJLc9qGLxEZ216MdL+Zg==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", + "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", + "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", - "jest-message-util": "^27.5.1", - "jest-util": "^27.5.1", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", "slash": "^3.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/@jest/core": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-27.5.1.tgz", - "integrity": "sha512-AK6/UTrvQD0Cd24NSqmIA6rKsu0tKIxfiCducZvqxYdmMisOYAsdItspT+fQDQYARPf8XgjAFZi0ogW2agH5nQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", + "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", "dev": true, "dependencies": { - "@jest/console": "^27.5.1", - "@jest/reporters": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/console": "^29.7.0", + "@jest/reporters": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", "@types/node": "*", "ansi-escapes": "^4.2.1", "chalk": "^4.0.0", - "emittery": "^0.8.1", + "ci-info": "^3.2.0", "exit": "^0.1.2", "graceful-fs": "^4.2.9", - "jest-changed-files": "^27.5.1", - "jest-config": "^27.5.1", - "jest-haste-map": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-resolve-dependencies": "^27.5.1", - "jest-runner": "^27.5.1", - "jest-runtime": "^27.5.1", - "jest-snapshot": "^27.5.1", - "jest-util": "^27.5.1", - "jest-validate": "^27.5.1", - "jest-watcher": "^27.5.1", + "jest-changed-files": "^29.7.0", + "jest-config": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-resolve-dependencies": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "jest-watcher": "^29.7.0", "micromatch": "^4.0.4", - "rimraf": "^3.0.0", + "pretty-format": "^29.7.0", "slash": "^3.0.0", "strip-ansi": "^6.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" @@ -904,85 +1072,110 @@ } }, "node_modules/@jest/environment": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-27.5.1.tgz", - "integrity": "sha512-/WQjhPJe3/ghaol/4Bq480JKXV/Rfw8nQdN7f41fM8VDHLcxKXou6QyXAh3EFr9/bVG3x74z1NWDkP87EiY8gA==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", + "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", "dev": true, "dependencies": { - "@jest/fake-timers": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", "@types/node": "*", - "jest-mock": "^27.5.1" + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", + "dev": true, + "dependencies": { + "expect": "^29.7.0", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", + "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", + "dev": true, + "dependencies": { + "jest-get-type": "^29.6.3" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/@jest/fake-timers": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-27.5.1.tgz", - "integrity": "sha512-/aPowoolwa07k7/oM3aASneNeBGCmGQsc3ugN4u6s4C/+s5M64MFo/+djTdiwcbQlRfFElGuDXWzaWj6QgKObQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", + "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", - "@sinonjs/fake-timers": "^8.0.1", + "@jest/types": "^29.6.3", + "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", - "jest-message-util": "^27.5.1", - "jest-mock": "^27.5.1", - "jest-util": "^27.5.1" + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/@jest/globals": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-27.5.1.tgz", - "integrity": "sha512-ZEJNB41OBQQgGzgyInAv0UUfDDj3upmHydjieSxFvTRuZElrx7tXg/uVQ5hYVEwiXs3+aMsAeEc9X7xiSKCm4Q==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", + "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", "dev": true, "dependencies": { - "@jest/environment": "^27.5.1", - "@jest/types": "^27.5.1", - "expect": "^27.5.1" + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/types": "^29.6.3", + "jest-mock": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/@jest/reporters": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-27.5.1.tgz", - "integrity": "sha512-cPXh9hWIlVJMQkVk84aIvXuBB4uQQmFqZiacloFuGiP3ah1sbCxCosidXFDfqG8+6fO1oR2dTJTlsOy4VFmUfw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", + "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", "dev": true, "dependencies": { "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/console": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", "@types/node": "*", "chalk": "^4.0.0", "collect-v8-coverage": "^1.0.0", "exit": "^0.1.2", - "glob": "^7.1.2", + "glob": "^7.1.3", "graceful-fs": "^4.2.9", "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^5.1.0", + "istanbul-lib-instrument": "^6.0.0", "istanbul-lib-report": "^3.0.0", "istanbul-lib-source-maps": "^4.0.0", "istanbul-reports": "^3.1.3", - "jest-haste-map": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-util": "^27.5.1", - "jest-worker": "^27.5.1", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", "slash": "^3.0.0", - "source-map": "^0.6.0", "string-length": "^4.0.1", - "terminal-link": "^2.0.0", - "v8-to-istanbul": "^8.1.0" + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" @@ -993,90 +1186,169 @@ } } }, + "node_modules/@jest/reporters/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jest/reporters/node_modules/istanbul-lib-instrument": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.1.tgz", + "integrity": "sha512-EAMEJBsYuyyztxMxW3g7ugGPkrZsV57v0Hmv3mm1uQsmB+QnZuepg731CRaIgeUVSdmsTngOkSnauNF8p7FIhA==", + "dev": true, + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "dev": true, + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/@jest/source-map": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-27.5.1.tgz", - "integrity": "sha512-y9NIHUYF3PJRlHk98NdC/N1gl88BL08aQQgu4k4ZopQkCw9t9cV8mtl3TV8b/YCB8XaVTFrmUTAJvjsntDireg==", + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", + "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", "dev": true, "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", "callsites": "^3.0.0", - "graceful-fs": "^4.2.9", - "source-map": "^0.6.0" + "graceful-fs": "^4.2.9" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.19", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz", + "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, "node_modules/@jest/test-result": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-27.5.1.tgz", - "integrity": "sha512-EW35l2RYFUcUQxFJz5Cv5MTOxlJIQs4I7gxzi2zVU7PJhOwfYq1MdC5nhSmYjX1gmMmLPvB3sIaC+BkcHRBfag==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", + "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", "dev": true, "dependencies": { - "@jest/console": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/console": "^29.7.0", + "@jest/types": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "collect-v8-coverage": "^1.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/@jest/test-sequencer": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-27.5.1.tgz", - "integrity": "sha512-LCheJF7WB2+9JuCS7VB/EmGIdQuhtqjRNI9A43idHv3E4KltCTsPsLxvdaubFHSYwY/fNjMWjl6vNRhDiN7vpQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", + "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", "dev": true, "dependencies": { - "@jest/test-result": "^27.5.1", + "@jest/test-result": "^29.7.0", "graceful-fs": "^4.2.9", - "jest-haste-map": "^27.5.1", - "jest-runtime": "^27.5.1" + "jest-haste-map": "^29.7.0", + "slash": "^3.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/@jest/transform": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-27.5.1.tgz", - "integrity": "sha512-ipON6WtYgl/1329g5AIJVbUuEh0wZVbdpGwC99Jw4LwuoBNS95MVphU6zOeD9pDkon+LLbFL7lOQRapbB8SCHw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", + "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", "dev": true, "dependencies": { - "@babel/core": "^7.1.0", - "@jest/types": "^27.5.1", + "@babel/core": "^7.11.6", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", - "convert-source-map": "^1.4.0", - "fast-json-stable-stringify": "^2.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", - "jest-haste-map": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-util": "^27.5.1", + "jest-haste-map": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", - "source-map": "^0.6.1", - "write-file-atomic": "^3.0.0" + "write-file-atomic": "^4.0.2" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.18", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz", + "integrity": "sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "3.1.0", + "@jridgewell/sourcemap-codec": "1.4.14" } }, + "node_modules/@jest/transform/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + }, "node_modules/@jest/types": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-27.5.1.tgz", - "integrity": "sha512-Cx46iJ9QpwQTjIdq5VJu2QTMMs3QlEjI0x1QbBP5W1+nMzyc2XmimiRR/CbX9TO0cPTeUlxWMOu8mslYsJ8DEw==", + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", + "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", "dev": true, "dependencies": { + "@jest/schemas": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "@types/istanbul-reports": "^3.0.0", "@types/node": "*", - "@types/yargs": "^16.0.0", + "@types/yargs": "^17.0.8", "chalk": "^4.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", + "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "dev": true, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" } }, "node_modules/@jridgewell/resolve-uri": { @@ -1088,6 +1360,15 @@ "node": ">=6.0.0" } }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.4.14", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", @@ -1127,9 +1408,9 @@ } }, "node_modules/@nodelib/fs.walk": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.7.tgz", - "integrity": "sha512-BTIhocbPBSrRmHxOAJFtR18oLhxTtAFDAvL8hY1S3iU8k+E60W/YFs4jrixGzQjMpF4qPXxIQHcjVD9dz1C2QA==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dev": true, "dependencies": { "@nodelib/fs.scandir": "2.1.5", @@ -1140,157 +1421,188 @@ } }, "node_modules/@octokit/auth-token": { - "version": "2.4.5", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz", - "integrity": "sha512-BpGYsPgJt05M7/L/5FoE1PiAbdxXFZkX/3kDYcsvd1v6UhlnE5e96dTDr0ezX/EFwciQxf3cNV0loipsURU+WA==", - "dependencies": { - "@octokit/types": "^6.0.3" + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-4.0.0.tgz", + "integrity": "sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA==", + "engines": { + "node": ">= 18" } }, "node_modules/@octokit/core": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.4.0.tgz", - "integrity": "sha512-6/vlKPP8NF17cgYXqucdshWqmMZGXkuvtcrWCgU5NOI0Pl2GjlmZyWgBMrU8zJ3v2MJlM6++CiB45VKYmhiWWg==", - "dependencies": { - "@octokit/auth-token": "^2.4.4", - "@octokit/graphql": "^4.5.8", - "@octokit/request": "^5.4.12", - "@octokit/request-error": "^2.0.5", - "@octokit/types": "^6.0.3", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-5.2.0.tgz", + "integrity": "sha512-1LFfa/qnMQvEOAdzlQymH0ulepxbxnCYAKJZfMci/5XJyIHWgEYnDmgnKakbTh7CH2tFQ5O60oYDvns4i9RAIg==", + "dependencies": { + "@octokit/auth-token": "^4.0.0", + "@octokit/graphql": "^7.1.0", + "@octokit/request": "^8.3.1", + "@octokit/request-error": "^5.1.0", + "@octokit/types": "^13.0.0", "before-after-hook": "^2.2.0", "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" } }, "node_modules/@octokit/endpoint": { - "version": "6.0.11", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.11.tgz", - "integrity": "sha512-fUIPpx+pZyoLW4GCs3yMnlj2LfoXTWDUVPTC4V3MUEKZm48W+XYpeWSZCv+vYF1ZABUm2CqnDVf1sFtIYrj7KQ==", + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.5.tgz", + "integrity": "sha512-ekqR4/+PCLkEBF6qgj8WqJfvDq65RH85OAgrtnVp1mSxaXF03u2xW/hUdweGS5654IlC0wkNYC18Z50tSYTAFw==", "dependencies": { - "@octokit/types": "^6.0.3", - "is-plain-object": "^5.0.0", + "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" } }, "node_modules/@octokit/graphql": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.2.tgz", - "integrity": "sha512-WmsIR1OzOr/3IqfG9JIczI8gMJUMzzyx5j0XXQ4YihHtKlQc+u35VpVoOXhlKAlaBntvry1WpAzPl/a+s3n89Q==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-7.1.0.tgz", + "integrity": "sha512-r+oZUH7aMFui1ypZnAvZmn0KSqAUgE1/tUXIWaqUCa1758ts/Jio84GZuzsvUkme98kv0WFY8//n0J1Z+vsIsQ==", "dependencies": { - "@octokit/request": "^5.3.0", - "@octokit/types": "^6.0.3", + "@octokit/request": "^8.3.0", + "@octokit/types": "^13.0.0", "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" } }, "node_modules/@octokit/openapi-types": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.2.3.tgz", - "integrity": "sha512-V1ycxkR19jqbIl3evf2RQiMRBvTNRi+Iy9h20G5OP5dPfEF6GJ1DPlUeiZRxo2HJxRr+UA4i0H1nn4btBDPFrw==" + "version": "22.2.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-22.2.0.tgz", + "integrity": "sha512-QBhVjcUa9W7Wwhm6DBFu6ZZ+1/t/oYxqc2tp81Pi41YNuJinbFRx8B133qVOrAaBbF7D/m0Et6f9/pZt9Rc+tg==" }, "node_modules/@octokit/plugin-paginate-rest": { - "version": "2.13.3", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.13.3.tgz", - "integrity": "sha512-46lptzM9lTeSmIBt/sVP/FLSTPGx6DCzAdSX3PfeJ3mTf4h9sGC26WpaQzMEq/Z44cOcmx8VsOhO+uEgE3cjYg==", + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-9.2.1.tgz", + "integrity": "sha512-wfGhE/TAkXZRLjksFXuDZdmGnJQHvtU/joFQdweXUgzo1XwvBCD4o4+75NtFfjfLK5IwLf9vHTfSiU3sLRYpRw==", "dependencies": { - "@octokit/types": "^6.11.0" + "@octokit/types": "^12.6.0" + }, + "engines": { + "node": ">= 18" }, "peerDependencies": { - "@octokit/core": ">=2" + "@octokit/core": "5" + } + }, + "node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/openapi-types": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", + "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==" + }, + "node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/types": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", + "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", + "dependencies": { + "@octokit/openapi-types": "^20.0.0" } }, "node_modules/@octokit/plugin-rest-endpoint-methods": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.3.1.tgz", - "integrity": "sha512-3B2iguGmkh6bQQaVOtCsS0gixrz8Lg0v4JuXPqBcFqLKuJtxAUf3K88RxMEf/naDOI73spD+goJ/o7Ie7Cvdjg==", + "version": "10.4.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-10.4.1.tgz", + "integrity": "sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg==", "dependencies": { - "@octokit/types": "^6.16.2", - "deprecation": "^2.3.1" + "@octokit/types": "^12.6.0" + }, + "engines": { + "node": ">= 18" }, "peerDependencies": { - "@octokit/core": ">=3" + "@octokit/core": "5" + } + }, + "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/openapi-types": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", + "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==" + }, + "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/types": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", + "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", + "dependencies": { + "@octokit/openapi-types": "^20.0.0" } }, "node_modules/@octokit/request": { - "version": "5.4.15", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.15.tgz", - "integrity": "sha512-6UnZfZzLwNhdLRreOtTkT9n57ZwulCve8q3IT/Z477vThu6snfdkBuhxnChpOKNGxcQ71ow561Qoa6uqLdPtag==", - "dependencies": { - "@octokit/endpoint": "^6.0.1", - "@octokit/request-error": "^2.0.0", - "@octokit/types": "^6.7.1", - "is-plain-object": "^5.0.0", - "node-fetch": "^2.6.1", + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.0.tgz", + "integrity": "sha512-9Bb014e+m2TgBeEJGEbdplMVWwPmL1FPtggHQRkV+WVsMggPtEkLKPlcVYm/o8xKLkpJ7B+6N8WfQMtDLX2Dpw==", + "dependencies": { + "@octokit/endpoint": "^9.0.1", + "@octokit/request-error": "^5.1.0", + "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" } }, "node_modules/@octokit/request-error": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.5.tgz", - "integrity": "sha512-T/2wcCFyM7SkXzNoyVNWjyVlUwBvW3igM3Btr/eKYiPmucXTtkxt2RBsf6gn3LTzaLSLTQtNmvg+dGsOxQrjZg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.0.tgz", + "integrity": "sha512-GETXfE05J0+7H2STzekpKObFe765O5dlAKUTLNGeH+x47z7JjXHfsHKo5z21D/o/IOZTUEI6nyWyR+bZVP/n5Q==", "dependencies": { - "@octokit/types": "^6.0.3", + "@octokit/types": "^13.1.0", "deprecation": "^2.0.0", "once": "^1.4.0" + }, + "engines": { + "node": ">= 18" } }, "node_modules/@octokit/types": { - "version": "6.16.2", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.16.2.tgz", - "integrity": "sha512-wWPSynU4oLy3i4KGyk+J1BLwRKyoeW2TwRHgwbDz17WtVFzSK2GOErGliruIx8c+MaYtHSYTx36DSmLNoNbtgA==", + "version": "13.5.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-13.5.0.tgz", + "integrity": "sha512-HdqWTf5Z3qwDVlzCrP8UJquMwunpDiMPt5er+QjGzL4hqr/vBVY/MauQgS1xWxCDT1oMx1EULyqxncdCY/NVSQ==", "dependencies": { - "@octokit/openapi-types": "^7.2.3" + "@octokit/openapi-types": "^22.2.0" } }, "node_modules/@octokit/webhooks-types": { - "version": "6.3.6", - "resolved": "https://registry.npmjs.org/@octokit/webhooks-types/-/webhooks-types-6.3.6.tgz", - "integrity": "sha512-x6yBtWobk20OhOiJ4VWsH3iJ/30IG+VoDWSgS4Tiyidi2KOiBS3bL+AJrNuq4OyNuWOM/FbHQTp6KEZs1oPD/g==" + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/@octokit/webhooks-types/-/webhooks-types-7.5.1.tgz", + "integrity": "sha512-1dozxWEP8lKGbtEu7HkRbK1F/nIPuJXNfT0gd96y6d3LcHZTtRtlf8xz3nicSJfesADxJyDh+mWBOsdLkqgzYw==" }, - "node_modules/@sindresorhus/is": { - "version": "0.14.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", - "integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==", + "node_modules/@pkgr/core": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.1.0.tgz", + "integrity": "sha512-Zwq5OCzuwJC2jwqmpEQt7Ds1DTi6BWSwoGkbb1n9pO3hzb35BoJELx7c0T23iDkBGkh2e7tvOtjF3tr3OaQHDQ==", "dev": true, "engines": { - "node": ">=6" + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" } }, + "node_modules/@sinclair/typebox": { + "version": "0.27.8", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", + "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "dev": true + }, "node_modules/@sinonjs/commons": { - "version": "1.8.3", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.3.tgz", - "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz", + "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==", "dev": true, "dependencies": { "type-detect": "4.0.8" } }, "node_modules/@sinonjs/fake-timers": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-8.1.0.tgz", - "integrity": "sha512-OAPJUAtgeINhh/TAlUID4QTs53Njm7xzddaVlEs/SXwgtiD1tW22zAB/W1wdqfrpmikgaWQ9Fw6Ws+hsiRm5Vg==", - "dev": true, - "dependencies": { - "@sinonjs/commons": "^1.7.0" - } - }, - "node_modules/@szmarczak/http-timer": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-1.1.2.tgz", - "integrity": "sha512-XIB2XbzHTN6ieIjfIMV9hlVcfPU26s2vafYWQcZHWXHOxiaRZYEDKEwdl129Zyg50+foYV2jCgtrqSA6qNuNSA==", + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", "dev": true, "dependencies": { - "defer-to-connect": "^1.0.1" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/@tootallnate/once": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", - "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", - "dev": true, - "engines": { - "node": ">= 6" + "@sinonjs/commons": "^3.0.0" } }, "node_modules/@tsconfig/node10": { @@ -1318,13 +1630,13 @@ "dev": true }, "node_modules/@types/babel__core": { - "version": "7.1.18", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.18.tgz", - "integrity": "sha512-S7unDjm/C7z2A2R9NzfKCK1I+BAALDtxEmsJBwlB3EzNfb929ykjL++1CK9LO++EIp2fQrC8O+BwjKvz6UeDyQ==", + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.1.tgz", + "integrity": "sha512-aACu/U/omhdk15O4Nfb+fHgH/z3QsfQzpnvRZhYhThms83ZnAOZz7zZAWO7mn2yyNQaA4xTO8GLK3uqFU4bYYw==", "dev": true, "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0", + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" @@ -1350,21 +1662,33 @@ } }, "node_modules/@types/babel__traverse": { - "version": "7.11.1", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.11.1.tgz", - "integrity": "sha512-Vs0hm0vPahPMYi9tDjtP66llufgO3ST16WXaSTtDGEl9cewAl3AibmxWw6TINOqHPT9z0uABKAYjT9jNSg4npw==", + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.1.tgz", + "integrity": "sha512-MitHFXnhtgwsGZWtT68URpOvLN4EREih1u3QtQiN4VdAxWKRVvGCSvw/Qth0M0Qq3pJpnGOu5JaM/ydK7OGbqg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.20.7" + } + }, + "node_modules/@types/docker-modem": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/docker-modem/-/docker-modem-3.0.2.tgz", + "integrity": "sha512-qC7prjoEYR2QEe6SmCVfB1x3rfcQtUr1n4x89+3e0wSTMQ/KYCyf+/RAA9n2tllkkNc6//JMUZePdFRiGIWfaQ==", "dev": true, "dependencies": { - "@babel/types": "^7.3.0" + "@types/node": "*", + "@types/ssh2": "*" } }, "node_modules/@types/dockerode": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/@types/dockerode/-/dockerode-3.2.6.tgz", - "integrity": "sha512-rz50DbrfQGsKOlkLbkknXNyurl2z/yR0CmV/OhzPW3Ef3jbIGoIE+Rd+2UC17gNVrnDl+mpejCI7RqQNe2bEbw==", + "version": "3.3.28", + "resolved": "https://registry.npmjs.org/@types/dockerode/-/dockerode-3.3.28.tgz", + "integrity": "sha512-RjY96chW88t2QvSebCsec+mQYo3/nyOr+/tVcE+0ynlOg2m/i9wPE52DhptzF75QDlhv2uDYVPqKfHKeGTn6Fg==", "dev": true, "dependencies": { - "@types/node": "*" + "@types/docker-modem": "*", + "@types/node": "*", + "@types/ssh2": "*" } }, "node_modules/@types/graceful-fs": { @@ -1401,109 +1725,123 @@ } }, "node_modules/@types/jest": { - "version": "27.0.2", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-27.0.2.tgz", - "integrity": "sha512-4dRxkS/AFX0c5XW6IPMNOydLn2tEhNhJV7DnYK+0bjoJZ+QTmfucBlihX7aoEsh/ocYtkLC73UbnBXBXIxsULA==", + "version": "29.5.12", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.12.tgz", + "integrity": "sha512-eDC8bTvT/QhYdxJAulQikueigY5AsdBRH2yDKW3yveW7svY3+DzN84/2NUgkw10RTiJbWqZrTtoGVdYlvFJdLw==", "dev": true, "dependencies": { - "jest-diff": "^27.0.0", - "pretty-format": "^27.0.0" + "expect": "^29.0.0", + "pretty-format": "^29.0.0" } }, "node_modules/@types/json-schema": { - "version": "7.0.7", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.7.tgz", - "integrity": "sha512-cxWFQVseBm6O9Gbw1IWb8r6OS4OhSt3hPZLkFApLjM8TEXROBuQGLAH2i2gZpcXdLBIrpXuTDhH7Vbm1iXmNGA==", + "version": "7.0.12", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.12.tgz", + "integrity": "sha512-Hr5Jfhc9eYOQNPYO5WLDq/n4jqijdHNlDXjuAQkkt+mWdQR+XJToOHrsD4cPaMXpn6KO7y2+wM8AZEs8VpBLVA==", "dev": true }, "node_modules/@types/json5": { "version": "0.0.29", "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", - "integrity": "sha1-7ihweulOEdK4J7y+UnC86n8+ce4=", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", "dev": true }, "node_modules/@types/node": { - "version": "18.7.13", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.13.tgz", - "integrity": "sha512-46yIhxSe5xEaJZXWdIBP7GU4HDTG8/eo0qd9atdiL+lFpA03y8KS+lkTN834TWJj5767GbWv4n/P6efyTFt1Dw==", - "dev": true + "version": "20.12.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.7.tgz", + "integrity": "sha512-wq0cICSkRLVaf3UGLMGItu/PtdY7oaXaI/RVU+xliKVOtRna3PRY57ZDfztpDL0n11vfymMUnXv8QwYCO7L1wg==", + "dev": true, + "dependencies": { + "undici-types": "~5.26.4" + } }, "node_modules/@types/node-forge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.0.1.tgz", - "integrity": "sha512-96ELNKv9tQJ19afdBUiM5iDw7OYEc53iUc51gAPR2aGaqRsO1DBROjqgZRjZa1tkPj7TnEOR0EnyAX6iryGkzA==", + "version": "1.3.11", + "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.11.tgz", + "integrity": "sha512-FQx220y22OKNTqaByeBGqHWYz4cl94tpcxeFdvBo3wjG6XPBuZ0BNgNZRV5J5TFmmcsJ4IzsLkmGRiQbnYsBEQ==", "dev": true, "dependencies": { "@types/node": "*" } }, - "node_modules/@types/parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==", + "node_modules/@types/semver": { + "version": "7.5.8", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", + "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==", "dev": true }, - "node_modules/@types/prettier": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.2.3.tgz", - "integrity": "sha512-PijRCG/K3s3w1We6ynUKdxEc5AcuuH3NBmMDP8uvKVp6X43UY7NQlTzczakXP3DJR0F4dfNQIGjU2cUeRYs2AA==", + "node_modules/@types/ssh2": { + "version": "1.11.7", + "resolved": "https://registry.npmjs.org/@types/ssh2/-/ssh2-1.11.7.tgz", + "integrity": "sha512-MaVSlZOiekRUHnxL2NAmDkcU3+bTwz+ZRktLygjQCnxhLjDzN+XnsG6JUdoocmfxatMiqFo/6eb48uVqFaxBsg==", + "dev": true, + "dependencies": { + "@types/node": "^18.11.18" + } + }, + "node_modules/@types/ssh2/node_modules/@types/node": { + "version": "18.16.17", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.16.17.tgz", + "integrity": "sha512-QAkjjRA1N7gPJeAP4WLXZtYv6+eMXFNviqktCDt4GLcmCugMr5BcRHfkOjCQzvCsnMp+L79a54zBkbw356xv9Q==", "dev": true }, "node_modules/@types/stack-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.0.tgz", - "integrity": "sha512-RJJrrySY7A8havqpGObOB4W92QXKJo63/jFLLgpvOtsGUqbQZ9Sbgl35KMm1DjC6j7AvmmU2bIno+3IyEaemaw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", "dev": true }, "node_modules/@types/tar-stream": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/@types/tar-stream/-/tar-stream-2.2.2.tgz", - "integrity": "sha512-1AX+Yt3icFuU6kxwmPakaiGrJUwG44MpuiqPg4dSolRFk6jmvs4b3IbUol9wKDLIgU76gevn3EwE8y/DkSJCZQ==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/tar-stream/-/tar-stream-3.1.3.tgz", + "integrity": "sha512-Zbnx4wpkWBMBSu5CytMbrT5ZpMiF55qgM+EpHzR4yIDu7mv52cej8hTkOc6K+LzpkOAbxwn/m7j3iO+/l42YkQ==", "dev": true, "dependencies": { "@types/node": "*" } }, "node_modules/@types/yargs": { - "version": "16.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-16.0.3.tgz", - "integrity": "sha512-YlFfTGS+zqCgXuXNV26rOIeETOkXnGQXP/pjjL9P0gO/EP9jTmc7pUBhx+jVEIxpq41RX33GQ7N3DzOSfZoglQ==", + "version": "17.0.13", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.13.tgz", + "integrity": "sha512-9sWaruZk2JGxIQU+IhI1fhPYRcQ0UuTNuKuCW9bR5fp7qi2Llf7WDzNa17Cy7TKnh3cdxDOiyTu6gaLS0eDatg==", "dev": true, "dependencies": { "@types/yargs-parser": "*" } }, "node_modules/@types/yargs-parser": { - "version": "20.2.0", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-20.2.0.tgz", - "integrity": "sha512-37RSHht+gzzgYeobbG+KWryeAW8J33Nhr69cjTqSYymXVZEN9NbRYWoYlRtDhHKPVT1FyNKwaTPC1NynKZpzRA==", + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", "dev": true }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.26.0.tgz", - "integrity": "sha512-yA7IWp+5Qqf+TLbd8b35ySFOFzUfL7i+4If50EqvjT6w35X8Lv0eBHb6rATeWmucks37w+zV+tWnOXI9JlG6Eg==", + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.39.0.tgz", + "integrity": "sha512-xVfKOkBm5iWMNGKQ2fwX5GVgBuHmZBO1tCRwXmY5oAIsPscfwm2UADDuNB8ZVYCtpQvJK4xpjrK7jEhcJ0zY9A==", "dev": true, - "dependencies": { - "@typescript-eslint/experimental-utils": "4.26.0", - "@typescript-eslint/scope-manager": "4.26.0", - "debug": "^4.3.1", - "functional-red-black-tree": "^1.0.1", - "lodash": "^4.17.21", - "regexpp": "^3.1.0", - "semver": "^7.3.5", + "optional": true, + "peer": true, + "dependencies": { + "@typescript-eslint/scope-manager": "5.39.0", + "@typescript-eslint/type-utils": "5.39.0", + "@typescript-eslint/utils": "5.39.0", + "debug": "^4.3.4", + "ignore": "^5.2.0", + "regexpp": "^3.2.0", + "semver": "^7.3.7", "tsutils": "^3.21.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^4.0.0", - "eslint": "^5.0.0 || ^6.0.0 || ^7.0.0" + "@typescript-eslint/parser": "^5.0.0", + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { "typescript": { @@ -1511,68 +1849,26 @@ } } }, - "node_modules/@typescript-eslint/experimental-utils": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-4.26.0.tgz", - "integrity": "sha512-TH2FO2rdDm7AWfAVRB5RSlbUhWxGVuxPNzGT7W65zVfl8H/WeXTk1e69IrcEVsBslrQSTDKQSaJD89hwKrhdkw==", - "dev": true, - "dependencies": { - "@types/json-schema": "^7.0.7", - "@typescript-eslint/scope-manager": "4.26.0", - "@typescript-eslint/types": "4.26.0", - "@typescript-eslint/typescript-estree": "4.26.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "*" - } - }, - "node_modules/@typescript-eslint/experimental-utils/node_modules/eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "dependencies": { - "eslint-visitor-keys": "^2.0.0" - }, - "engines": { - "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - }, - "peerDependencies": { - "eslint": ">=5" - } - }, "node_modules/@typescript-eslint/parser": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-4.33.0.tgz", - "integrity": "sha512-ZohdsbXadjGBSK0/r+d87X0SBmKzOq4/S5nzK6SBgJspFo9/CUDJ7hjayuze+JK7CZQLDMroqytp7pOcFKTxZA==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", + "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "4.33.0", - "@typescript-eslint/types": "4.33.0", - "@typescript-eslint/typescript-estree": "4.33.0", - "debug": "^4.3.1" + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", + "debug": "^4.3.4" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^5.0.0 || ^6.0.0 || ^7.0.0" + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { "typescript": { @@ -1581,16 +1877,16 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/scope-manager": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.33.0.tgz", - "integrity": "sha512-5IfJHpgTsTZuONKbODctL4kKuQje/bzBRkwHE8UOZ4f89Zeddg+EGZs8PD8NcN4LdM3ygHWYB3ukPAYjvl/qbQ==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", + "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", "dev": true, "dependencies": { - "@typescript-eslint/types": "4.33.0", - "@typescript-eslint/visitor-keys": "4.33.0" + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0" }, "engines": { - "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", @@ -1598,12 +1894,12 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/types": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.33.0.tgz", - "integrity": "sha512-zKp7CjQzLQImXEpLt2BUw1tvOMPfNoTAfb8l51evhYbOEEzdWyQNmHWWGPR6hwKJDAi+1VXSBmnhL9kyVTTOuQ==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", + "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", "dev": true, "engines": { - "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", @@ -1611,21 +1907,21 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/typescript-estree": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.33.0.tgz", - "integrity": "sha512-rkWRY1MPFzjwnEVHsxGemDzqqddw2QbTJlICPD9p9I9LfsO8fdmfQPOX3uKfUaGRDFJbfrtm/sXhVXN4E+bzCA==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", + "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "4.33.0", - "@typescript-eslint/visitor-keys": "4.33.0", - "debug": "^4.3.1", - "globby": "^11.0.3", - "is-glob": "^4.0.1", - "semver": "^7.3.5", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "semver": "^7.3.7", "tsutils": "^3.21.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", @@ -1638,46 +1934,87 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/visitor-keys": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.33.0.tgz", - "integrity": "sha512-uqi/2aSz9g2ftcHWf8uLPJA70rUv6yuMW5Bohw+bwcuzaxQIHaKFZCKGoGXIrc9vkTJ3+0txM73K0Hq3d5wgIg==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", + "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", "dev": true, "dependencies": { - "@typescript-eslint/types": "4.33.0", - "eslint-visitor-keys": "^2.0.0" + "@typescript-eslint/types": "5.62.0", + "eslint-visitor-keys": "^3.3.0" }, "engines": { - "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@typescript-eslint/parser/node_modules/eslint-visitor-keys": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.1.tgz", + "integrity": "sha512-pZnmmLwYzf+kWaM/Qgrvpen51upAktaaiI01nsJD/Yr3lMOdNtq0cxkrrg16w64VtisN6okbs7Q8AfGqj4c9fA==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/@typescript-eslint/scope-manager": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.26.0.tgz", - "integrity": "sha512-G6xB6mMo4xVxwMt5lEsNTz3x4qGDt0NSGmTBNBPJxNsrTXJSm21c6raeYroS2OwQsOyIXqKZv266L/Gln1BWqg==", + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.39.0.tgz", + "integrity": "sha512-/I13vAqmG3dyqMVSZPjsbuNQlYS082Y7OMkwhCfLXYsmlI0ca4nkL7wJ/4gjX70LD4P8Hnw1JywUVVAwepURBw==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "5.39.0", + "@typescript-eslint/visitor-keys": "5.39.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.39.0.tgz", + "integrity": "sha512-KJHJkOothljQWzR3t/GunL0TPKY+fGJtnpl+pX+sJ0YiKTz3q2Zr87SGTmFqsCMFrLt5E0+o+S6eQY0FAXj9uA==", "dev": true, + "optional": true, + "peer": true, "dependencies": { - "@typescript-eslint/types": "4.26.0", - "@typescript-eslint/visitor-keys": "4.26.0" + "@typescript-eslint/typescript-estree": "5.39.0", + "@typescript-eslint/utils": "5.39.0", + "debug": "^4.3.4", + "tsutils": "^3.21.0" }, "engines": { - "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } } }, "node_modules/@typescript-eslint/types": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.26.0.tgz", - "integrity": "sha512-rADNgXl1kS/EKnDr3G+m7fB9yeJNnR9kF7xMiXL6mSIWpr3Wg5MhxyfEXy/IlYthsqwBqHOr22boFbf/u6O88A==", + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.39.0.tgz", + "integrity": "sha512-gQMZrnfEBFXK38hYqt8Lkwt8f4U6yq+2H5VDSgP/qiTzC8Nw8JO3OuSUOQ2qW37S/dlwdkHDntkZM6SQhKyPhw==", "dev": true, "engines": { - "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", @@ -1685,21 +2022,21 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.26.0.tgz", - "integrity": "sha512-GHUgahPcm9GfBuy3TzdsizCcPjKOAauG9xkz9TR8kOdssz2Iz9jRCSQm6+aVFa23d5NcSpo1GdHGSQKe0tlcbg==", + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.39.0.tgz", + "integrity": "sha512-qLFQP0f398sdnogJoLtd43pUgB18Q50QSA+BTE5h3sUxySzbWDpTSdgt4UyxNSozY/oDK2ta6HVAzvGgq8JYnA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "4.26.0", - "@typescript-eslint/visitor-keys": "4.26.0", - "debug": "^4.3.1", - "globby": "^11.0.3", - "is-glob": "^4.0.1", - "semver": "^7.3.5", + "@typescript-eslint/types": "5.39.0", + "@typescript-eslint/visitor-keys": "5.39.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "semver": "^7.3.7", "tsutils": "^3.21.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", @@ -1711,55 +2048,88 @@ } } }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.26.0.tgz", - "integrity": "sha512-cw4j8lH38V1ycGBbF+aFiLUls9Z0Bw8QschP3mkth50BbWzgFS33ISIgBzUMuQ2IdahoEv/rXstr8Zhlz4B1Zg==", + "node_modules/@typescript-eslint/utils": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.39.0.tgz", + "integrity": "sha512-+DnY5jkpOpgj+EBtYPyHRjXampJfC0yUZZzfzLuUWVZvCuKqSdJVC8UhdWipIw7VKNTfwfAPiOWzYkAwuIhiAg==", "dev": true, "dependencies": { - "@typescript-eslint/types": "4.26.0", - "eslint-visitor-keys": "^2.0.0" + "@types/json-schema": "^7.0.9", + "@typescript-eslint/scope-manager": "5.39.0", + "@typescript-eslint/types": "5.39.0", + "@typescript-eslint/typescript-estree": "5.39.0", + "eslint-scope": "^5.1.1", + "eslint-utils": "^3.0.0" }, "engines": { - "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, - "node_modules/@vercel/ncc": { - "version": "0.34.0", - "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.34.0.tgz", - "integrity": "sha512-G9h5ZLBJ/V57Ou9vz5hI8pda/YQX5HQszCs3AmIus3XzsmRn/0Ptic5otD3xVST8QLKk7AMk7AqpsyQGN7MZ9A==", + "node_modules/@typescript-eslint/visitor-keys": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.39.0.tgz", + "integrity": "sha512-yyE3RPwOG+XJBLrhvsxAidUgybJVQ/hG8BhiJo0k8JSAYfk/CshVcxf0HwP4Jt7WZZ6vLmxdo1p6EyN3tzFTkg==", "dev": true, - "bin": { - "ncc": "dist/ncc/cli.js" + "dependencies": { + "@typescript-eslint/types": "5.39.0", + "eslint-visitor-keys": "^3.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/abab": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.5.tgz", - "integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@ungap/structured-clone": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", + "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", "dev": true }, + "node_modules/@vercel/ncc": { + "version": "0.38.1", + "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.38.1.tgz", + "integrity": "sha512-IBBb+iI2NLu4VQn3Vwldyi2QwaXt5+hTyh58ggAMoCGE6DJmPvwL3KPBWcJl1m9LYPChBLE980Jw+CS4Wokqxw==", + "dev": true, + "bin": { + "ncc": "dist/ncc/cli.js" + } + }, "node_modules/accepts": { - "version": "1.3.7", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", - "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", "dev": true, "dependencies": { - "mime-types": "~2.1.24", - "negotiator": "0.6.2" + "mime-types": "~2.1.34", + "negotiator": "0.6.3" }, "engines": { "node": ">= 0.6" } }, "node_modules/acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.9.0.tgz", + "integrity": "sha512-jaVNAFBHNLXspO543WnNNPZFRtavh3skAkITqD0/2aeMkKZTN+254PyhwxFYrk3vQ1xfY+2wbesJMs/JC8/PwQ==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -1768,16 +2138,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-globals": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-6.0.0.tgz", - "integrity": "sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg==", - "dev": true, - "dependencies": { - "acorn": "^7.1.1", - "acorn-walk": "^7.1.1" - } - }, "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", @@ -1787,40 +2147,6 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, - "node_modules/acorn-walk": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", - "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "dev": true, - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/aggregate-error": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", - "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", - "dev": true, - "dependencies": { - "clean-stack": "^2.0.0", - "indent-string": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/ajv": { "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", @@ -1837,24 +2163,6 @@ "url": "https://github.com/sponsors/epoberezkin" } }, - "node_modules/ansi-align": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.1.tgz", - "integrity": "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==", - "dev": true, - "dependencies": { - "string-width": "^4.1.0" - } - }, - "node_modules/ansi-colors": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", - "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -1931,6 +2239,15 @@ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "dependencies": { + "dequal": "^2.0.3" + } + }, "node_modules/array-flatten": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", @@ -1938,16 +2255,16 @@ "dev": true }, "node_modules/array-includes": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.3.tgz", - "integrity": "sha512-gcem1KlBU7c9rB+Rq8/3PPKsK2kjqeEBa3bD5kkQo4nYlOHQCJqIJFqBXDEfwaRuYTT4E+FxA9xez7Gf/e3Q7A==", + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.6.tgz", + "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", "dev": true, "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.0-next.2", - "get-intrinsic": "^1.1.1", - "is-string": "^1.0.5" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "get-intrinsic": "^1.1.3", + "is-string": "^1.0.7" }, "engines": { "node": ">= 0.4" @@ -1966,14 +2283,33 @@ } }, "node_modules/array.prototype.flat": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.4.tgz", - "integrity": "sha512-4470Xi3GAPAjZqFcljX2xzckv1qeKPizoNkiS0+O4IoPR2ZNpcjE0pkhdihlDouK+x6QOast26B4Q/O9DJnwSg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.0.tgz", + "integrity": "sha512-12IUEkHsAhA4DY5s0FPgNXIdc8VRSqD9Zp78a5au9abH/SOBrsp082JOWFNTjkMozh8mqcdiKuaLGhPeYztxSw==", "dev": true, "dependencies": { - "call-bind": "^1.0.0", + "call-bind": "^1.0.2", "define-properties": "^1.1.3", - "es-abstract": "^1.18.0-next.1" + "es-abstract": "^1.19.2", + "es-shim-unscopables": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.1.tgz", + "integrity": "sha512-8UGn9O1FDVvMNB0UlLv4voxRMze7+FpHyF5mSMRjWHUMlpoDViniy05870VlxhfgTnLbpuwTzvD76MTtWxB/mQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "es-shim-unscopables": "^1.0.0" }, "engines": { "node": ">= 0.4" @@ -1990,46 +2326,63 @@ "safer-buffer": "~2.1.0" } }, - "node_modules/astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "node_modules/ast-types-flow": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.7.tgz", + "integrity": "sha512-eBvWn1lvIApYMhzQMsu9ciLfkBY499mFZlNqG+/9WR7PVlroQw0vG30cOQQbaKz3sCEc44TAOu2ykzqXSNnwag==", + "dev": true + }, + "node_modules/available-typed-arrays": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", + "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", "dev": true, "engines": { - "node": ">=8" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", - "dev": true + "node_modules/axe-core": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.6.3.tgz", + "integrity": "sha512-/BQzOX780JhsxDnPpH4ZiyrJAzcd8AfzFPkv+89veFSr1rcMjuq2JDCwypKaPeB6ljHp9KjXhPpjgCvQlWYuqg==", + "dev": true, + "engines": { + "node": ">=4" + } }, - "node_modules/axios": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.23.0.tgz", - "integrity": "sha512-NmvAE4i0YAv5cKq8zlDoPd1VLKAqX5oLuZKs8xkJa4qi6RGn0uhCYFjWtHHC9EM/MwOwYWOs53W+V0aqEXq1sg==", + "node_modules/axobject-query": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-3.1.1.tgz", + "integrity": "sha512-goKlv8DZrK9hUh975fnHzhNIO4jUnFCfv/dszV5VwUGDFjI6vQ2VwoyjYjYNEbBE8AH87TduWP5uyDR1D+Iteg==", + "dev": true, "dependencies": { - "follow-redirects": "^1.14.4" + "deep-equal": "^2.0.5" } }, + "node_modules/b4a": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz", + "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==" + }, "node_modules/babel-jest": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-27.5.1.tgz", - "integrity": "sha512-cdQ5dXjGRd0IBRATiQ4mZGlGlRE8kJpjPOixdNRdT+m3UcNqmYWN6rK6nvtXYfY3D76cb8s/O1Ss8ea24PIwcg==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", + "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", "dev": true, "dependencies": { - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/transform": "^29.7.0", "@types/babel__core": "^7.1.14", "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^27.5.1", + "babel-preset-jest": "^29.6.3", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "slash": "^3.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "peerDependencies": { "@babel/core": "^7.8.0" @@ -2052,18 +2405,18 @@ } }, "node_modules/babel-plugin-jest-hoist": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-27.5.1.tgz", - "integrity": "sha512-50wCwD5EMNW4aRpOwtqzyZHIewTYNxLA4nhB+09d8BIssfNfzBRhkBIHiaPv1Si226TQSvp8gxAJm2iY2qs2hQ==", + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", + "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", "dev": true, "dependencies": { "@babel/template": "^7.3.3", "@babel/types": "^7.3.3", - "@types/babel__core": "^7.0.0", + "@types/babel__core": "^7.1.14", "@types/babel__traverse": "^7.0.6" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/babel-preset-current-node-syntax": { @@ -2090,16 +2443,16 @@ } }, "node_modules/babel-preset-jest": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-27.5.1.tgz", - "integrity": "sha512-Nptf2FzlPCWYuJg41HBqXVT8ym6bXOevuCTbhxlUpjwtysGaIWFvDEjp4y+G7fl13FgOdjs7P/DmErqH7da0Ag==", + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", + "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", "dev": true, "dependencies": { - "babel-plugin-jest-hoist": "^27.5.1", + "babel-plugin-jest-hoist": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "peerDependencies": { "@babel/core": "^7.0.0" @@ -2145,45 +2498,38 @@ "node_modules/bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", - "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", "dependencies": { "tweetnacl": "^0.14.3" } }, "node_modules/before-after-hook": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.1.tgz", - "integrity": "sha512-/6FKxSTWoJdbsLDF8tdIjaRiFXiE6UHsEHE3OPI/cwPURCVi1ukP0gmLn7XWEiFk5TcwQjjY5PWsU+j+tgXgmw==" - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz", + "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==" }, "node_modules/body-parser": { - "version": "1.19.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", - "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", "dev": true, "dependencies": { - "bytes": "3.1.0", - "content-type": "~1.0.4", + "bytes": "3.1.2", + "content-type": "~1.0.5", "debug": "2.6.9", - "depd": "~1.1.2", - "http-errors": "1.7.2", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", "iconv-lite": "0.4.24", - "on-finished": "~2.3.0", - "qs": "6.7.0", - "raw-body": "2.4.0", - "type-is": "~1.6.17" + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" }, "engines": { - "node": ">= 0.8" + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" } }, "node_modules/body-parser/node_modules/debug": { @@ -2201,38 +2547,16 @@ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, - "node_modules/boxen": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/boxen/-/boxen-5.1.2.tgz", - "integrity": "sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==", + "node_modules/body-parser/node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", "dev": true, "dependencies": { - "ansi-align": "^3.0.0", - "camelcase": "^6.2.0", - "chalk": "^4.1.0", - "cli-boxes": "^2.2.1", - "string-width": "^4.2.2", - "type-fest": "^0.20.2", - "widest-line": "^3.1.0", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=10" + "ee-first": "1.1.1" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/boxen/node_modules/camelcase": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz", - "integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==", - "dev": true, "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">= 0.8" } }, "node_modules/brace-expansion": { @@ -2246,44 +2570,43 @@ } }, "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dev": true, "dependencies": { - "fill-range": "^7.0.1" + "fill-range": "^7.1.1" }, "engines": { "node": ">=8" } }, - "node_modules/browser-process-hrtime": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", - "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", - "dev": true - }, "node_modules/browserslist": { - "version": "4.16.6", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.6.tgz", - "integrity": "sha512-Wspk/PqO+4W9qp5iUTJsa1B/QrYn1keNCcEP5OvP7WBwT4KaDly0uONYmC6Xa3Z5IqnUgS0KcgLYu1l74x0ZXQ==", + "version": "4.21.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.4.tgz", + "integrity": "sha512-CBHJJdDmgjl3daYjN5Cp5kbTf1mUhZoS+beLklHIvkOWscs83YAhLlF3Wsh/lciQYAcbBJgTOD44VtG31ZM4Hw==", "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], "dependencies": { - "caniuse-lite": "^1.0.30001219", - "colorette": "^1.2.2", - "electron-to-chromium": "^1.3.723", - "escalade": "^3.1.1", - "node-releases": "^1.1.71" + "caniuse-lite": "^1.0.30001400", + "electron-to-chromium": "^1.4.251", + "node-releases": "^2.0.6", + "update-browserslist-db": "^1.0.9" }, "bin": { "browserslist": "cli.js" }, "engines": { "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" } }, "node_modules/bs-logger": { @@ -2307,84 +2630,28 @@ "node-int64": "^0.4.0" } }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, - "node_modules/bytes": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", - "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==", - "dev": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/cacheable-request": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-6.1.0.tgz", - "integrity": "sha512-Oj3cAGPCqOZX7Rz64Uny2GYAZNliQSqfbePrgAQ1wKAihYmCUnraBtJtKcGR4xz7wF+LoJC+ssFZvv5BgF9Igg==", - "dev": true, - "dependencies": { - "clone-response": "^1.0.2", - "get-stream": "^5.1.0", - "http-cache-semantics": "^4.0.0", - "keyv": "^3.0.0", - "lowercase-keys": "^2.0.0", - "normalize-url": "^4.1.0", - "responselike": "^1.0.2" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cacheable-request/node_modules/get-stream": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", - "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", - "dev": true, - "dependencies": { - "pump": "^3.0.0" - }, + "node_modules/buildcheck": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.6.tgz", + "integrity": "sha512-8f9ZJCUXyT1M35Jx7MkBgmBMo3oHTTBIPLiY9xyL0pl3T5RwcPEY8cUHr5LBNfu/fk6c2T4DJZuVM/8ZZT2D2A==", + "optional": true, "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=10.0.0" } }, - "node_modules/cacheable-request/node_modules/lowercase-keys": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", - "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==", + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", "dev": true, "engines": { - "node": ">=8" + "node": ">= 0.8" } }, "node_modules/call-bind": { @@ -2419,19 +2686,25 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001234", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001234.tgz", - "integrity": "sha512-a3gjUVKkmwLdNysa1xkUAwN2VfJUJyVW47rsi3aCbkRCtbHAfo+rOsCqVw29G6coQ8gzAPb5XBXwiGHwme3isA==", + "version": "1.0.30001418", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001418.tgz", + "integrity": "sha512-oIs7+JL3K9JRQ3jPZjlH6qyYDp+nBTCais7hjh0s+fuBwufc7uZ7hPYMXrDOJhV360KGMTcczMRObk0/iMqZRg==", "dev": true, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - } + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + } + ] }, "node_modules/chalk": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.1.tgz", - "integrity": "sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "dependencies": { "ansi-styles": "^4.1.0", @@ -2458,17 +2731,6 @@ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" }, - "node_modules/ci": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ci/-/ci-2.1.1.tgz", - "integrity": "sha512-StBCU1G9zbhgVBqvslvOpT601zme9YfyZaUSjgXCtfnIynPuDBHX85WwnXv5cnh74bYo8S3xfPpI41yk1jZmRw==", - "bin": { - "ci": "ci.js" - }, - "funding": { - "url": "https://github.com/privatenumber/ci?sponsor=1" - } - }, "node_modules/ci-info": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.2.0.tgz", @@ -2476,98 +2738,110 @@ "dev": true }, "node_modules/cjs-module-lexer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.1.tgz", - "integrity": "sha512-jVamGdJPDeuQilKhvVn1h3knuMOZzr8QDnpk+M9aMlCaMkTDd6fBWPhiDqFvFZ07pL0liqabAiuy8SY4jGHeaw==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz", + "integrity": "sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==", "dev": true }, - "node_modules/clean-stack": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", - "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "node_modules/cli-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", "dev": true, + "dependencies": { + "restore-cursor": "^4.0.0" + }, "engines": { - "node": ">=6" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cli-boxes": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-2.2.1.tgz", - "integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==", + "node_modules/cli-truncate": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz", + "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==", "dev": true, + "dependencies": { + "slice-ansi": "^5.0.0", + "string-width": "^7.0.0" + }, "engines": { - "node": ">=6" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cli-cursor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", - "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "node_modules/cli-truncate/node_modules/ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", "dev": true, - "dependencies": { - "restore-cursor": "^3.1.0" - }, "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, - "node_modules/cli-truncate": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", - "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", + "node_modules/cli-truncate/node_modules/emoji-regex": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.3.0.tgz", + "integrity": "sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==", + "dev": true + }, + "node_modules/cli-truncate/node_modules/string-width": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.1.0.tgz", + "integrity": "sha512-SEIJCWiX7Kg4c129n48aDRwLbFb2LJmXXFrWBG4NGaRtMQ3myKPKbwrD1BKqQn74oCoNMBVrfDEr5M9YxCsrkw==", "dev": true, "dependencies": { - "slice-ansi": "^3.0.0", - "string-width": "^4.2.0" + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" }, "engines": { - "node": ">=8" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cli-truncate/node_modules/slice-ansi": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", - "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", + "node_modules/cli-truncate/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", "dev": true, "dependencies": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" + "ansi-regex": "^6.0.1" }, "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, "node_modules/cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", "dev": true, "dependencies": { "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", + "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" - } - }, - "node_modules/clone-response": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", - "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", - "dev": true, - "dependencies": { - "mimic-response": "^1.0.0" + }, + "engines": { + "node": ">=12" } }, "node_modules/co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", "dev": true, "engines": { "iojs": ">= 1.0.0", @@ -2599,29 +2873,17 @@ "dev": true }, "node_modules/colorette": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.2.2.tgz", - "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==", + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", "dev": true }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/commander": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-9.1.0.tgz", - "integrity": "sha512-i0/MaqBtdbnJ4XQs4Pmyb+oFQl+q0lsAmokVUH92SlSw4fkeAcG3bVon+Qt7hmtF+u3Het6o4VgrcY3qAoEB6w==", + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", "engines": { - "node": "^12.20.0 || >=14" + "node": ">=18" } }, "node_modules/compressible": { @@ -2684,23 +2946,6 @@ "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, - "node_modules/configstore": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/configstore/-/configstore-5.0.1.tgz", - "integrity": "sha512-aMKprgk5YhBNyH25hj8wGt2+D52Sw1DRRIzqBwLp2Ya9mFmY8KPvvtvmna8SxVR9JMZ4kzMD68N22vlaRpkeFA==", - "dev": true, - "dependencies": { - "dot-prop": "^5.2.0", - "graceful-fs": "^4.1.2", - "make-dir": "^3.0.0", - "unique-string": "^2.0.0", - "write-file-atomic": "^3.0.0", - "xdg-basedir": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/connect-pause": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/connect-pause/-/connect-pause-0.1.1.tgz", @@ -2711,21 +2956,41 @@ } }, "node_modules/content-disposition": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", - "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", "dev": true, "dependencies": { - "safe-buffer": "5.1.2" + "safe-buffer": "5.2.1" }, "engines": { "node": ">= 0.6" } }, + "node_modules/content-disposition/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/content-type": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", - "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", "dev": true, "engines": { "node": ">= 0.6" @@ -2741,9 +3006,9 @@ } }, "node_modules/cookie": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", - "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==", + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", "dev": true, "engines": { "node": ">= 0.6" @@ -2768,51 +3033,39 @@ "node": ">= 0.10" } }, - "node_modules/cosmiconfig": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.0.tgz", - "integrity": "sha512-pondGvTuVYDk++upghXJabWzL6Kxu6f26ljFw64Swq9v6sQPUL3EUlVDV56diOjpCayKihL6hVe8exIACU4XcA==", - "dev": true, + "node_modules/cpu-features": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.9.tgz", + "integrity": "sha512-AKjgn2rP2yJyfbepsmLfiYcmtNn/2eUvocUyM/09yB0YDiz39HteK/5/T4Onf0pmdYDMgkBoGvRLvEguzyL7wQ==", + "hasInstallScript": true, + "optional": true, "dependencies": { - "@types/parse-json": "^4.0.0", - "import-fresh": "^3.2.1", - "parse-json": "^5.0.0", - "path-type": "^4.0.0", - "yaml": "^1.10.0" + "buildcheck": "~0.0.6", + "nan": "^2.17.0" }, "engines": { - "node": ">=10" + "node": ">=10.0.0" } }, - "node_modules/cosmiconfig/node_modules/parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "node_modules/create-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", + "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", "dev": true, "dependencies": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - }, - "engines": { - "node": ">=8" + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "prompts": "^2.0.1" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/cpu-features": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.2.tgz", - "integrity": "sha512-/2yieBqvMcRj8McNzkycjW2v3OIUOibBfd2dLEJ0nWts8NobAxwiyw9phVNS6oDL8x8tz9F7uNVFEVpJncQpeA==", - "hasInstallScript": true, - "optional": true, - "dependencies": { - "nan": "^2.14.1" + "bin": { + "create-jest": "bin/create-jest.js" }, "engines": { - "node": ">=8.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/create-require": { @@ -2835,57 +3088,16 @@ "node": ">= 8" } }, - "node_modules/crypto-random-string": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", - "integrity": "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/cssom": { - "version": "0.4.4", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.4.4.tgz", - "integrity": "sha512-p3pvU7r1MyyqbTk+WbNJIgJjG2VmTIaB10rI93LzVPrmDJKkzKYMtxxyAvQXR/NS6otuzveI7+7BBq3SjBS2mw==", - "dev": true - }, - "node_modules/cssstyle": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", - "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", - "dev": true, - "dependencies": { - "cssom": "~0.3.6" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cssstyle/node_modules/cssom": { - "version": "0.3.8", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", - "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", + "node_modules/damerau-levenshtein": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", + "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==", "dev": true }, - "node_modules/data-urls": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-2.0.0.tgz", - "integrity": "sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ==", - "dev": true, - "dependencies": { - "abab": "^2.0.3", - "whatwg-mimetype": "^2.3.0", - "whatwg-url": "^8.0.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/debug": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", - "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dependencies": { "ms": "2.1.2" }, @@ -2898,88 +3110,92 @@ } } }, - "node_modules/decimal.js": { - "version": "10.3.1", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz", - "integrity": "sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ==", - "dev": true + "node_modules/dedent": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.1.tgz", + "integrity": "sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg==", + "dev": true, + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } }, - "node_modules/decompress-response": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", - "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", + "node_modules/deep-equal": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.0.tgz", + "integrity": "sha512-RdpzE0Hv4lhowpIUKKMJfeH6C1pXdtT1/it80ubgWqwI3qpuxUBpC1S4hnHg+zjnuOoDkzUtUCEEkG+XG5l3Mw==", "dev": true, "dependencies": { - "mimic-response": "^1.0.0" + "call-bind": "^1.0.2", + "es-get-iterator": "^1.1.2", + "get-intrinsic": "^1.1.3", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.4.3", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.9" }, - "engines": { - "node": ">=4" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/dedent": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", - "integrity": "sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=", + "node_modules/deep-equal/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", "dev": true }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "dev": true, - "engines": { - "node": ">=4.0.0" - } - }, "node_modules/deep-is": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true }, "node_modules/deepmerge": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", - "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", "dev": true, "engines": { "node": ">=0.10.0" } }, - "node_modules/defer-to-connect": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-1.1.3.tgz", - "integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==", - "dev": true - }, "node_modules/define-properties": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", + "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", "dev": true, "dependencies": { - "object-keys": "^1.0.12" + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" }, "engines": { "node": ">= 0.4" - } - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", - "dev": true, - "engines": { - "node": ">=0.4.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", "dev": true, "engines": { - "node": ">= 0.6" + "node": ">= 0.8" } }, "node_modules/deprecation": { @@ -2987,11 +3203,24 @@ "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, "node_modules/destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", - "dev": true + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "dev": true, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } }, "node_modules/detect-newline": { "version": "3.1.0", @@ -3012,12 +3241,12 @@ } }, "node_modules/diff-sequences": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-27.5.1.tgz", - "integrity": "sha512-k1gCAXAsNgLwEL+Y8Wvl+M6oEFj5bgazfZULpS5CneoPPXRaCCW7dm+q21Ky2VEE5X+VeRDBVg1Pcvvsr4TtNQ==", + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", "dev": true, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/dir-glob": { @@ -3033,25 +3262,26 @@ } }, "node_modules/docker-modem": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/docker-modem/-/docker-modem-3.0.3.tgz", - "integrity": "sha512-Tgkn2a+yiNP9FoZgMa/D9Wk+D2Db///0KOyKSYZRJa8w4+DzKyzQMkczKSdR/adQ0x46BOpeNkoyEOKjPhCzjw==", + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/docker-modem/-/docker-modem-5.0.3.tgz", + "integrity": "sha512-89zhop5YVhcPEt5FpUFGr3cDyceGhq/F9J+ZndQ4KfqNvfbJpPMfgeixFgUj5OjCYAboElqODxY5Z1EBsSa6sg==", "dependencies": { "debug": "^4.1.1", "readable-stream": "^3.5.0", "split-ca": "^1.0.1", - "ssh2": "^1.4.0" + "ssh2": "^1.15.0" }, "engines": { "node": ">= 8.0" } }, "node_modules/dockerode": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/dockerode/-/dockerode-3.3.1.tgz", - "integrity": "sha512-AS2mr8Lp122aa5n6d99HkuTNdRV1wkkhHwBdcnY6V0+28D3DSYwhxAk85/mM9XwD3RMliTxyr63iuvn5ZblFYQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/dockerode/-/dockerode-4.0.2.tgz", + "integrity": "sha512-9wM1BVpVMFr2Pw3eJNXrYYt6DT9k0xMcsSCjtPvyQ+xa1iPg/Mo3T/gUcwI0B2cczqCeCYRPF8yFYDwtFXT0+w==", "dependencies": { - "docker-modem": "^3.0.0", + "@balena/dockerignore": "^1.0.2", + "docker-modem": "^5.0.3", "tar-fs": "~2.0.1" }, "engines": { @@ -3070,54 +3300,6 @@ "node": ">=6.0.0" } }, - "node_modules/domexception": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/domexception/-/domexception-2.0.1.tgz", - "integrity": "sha512-yxJ2mFy/sibVQlu5qHjOkf9J3K6zgmCxgJ94u2EdvDOV09H+32LtRswEcUsmUWN72pVLOEnTSRaIVVzVQgS0dg==", - "dev": true, - "dependencies": { - "webidl-conversions": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/domexception/node_modules/webidl-conversions": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-5.0.0.tgz", - "integrity": "sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/dot-prop": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", - "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", - "dev": true, - "dependencies": { - "is-obj": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/dot-prop/node_modules/is-obj": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", - "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/duplexer3": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", - "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=", - "dev": true - }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -3125,18 +3307,18 @@ "dev": true }, "node_modules/electron-to-chromium": { - "version": "1.3.748", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.748.tgz", - "integrity": "sha512-fmIKfYALVeEybk/L2ucdgt7jN3JsbGtg3K9pmF/MRWgkeADBI1VSAa5IzdG2gZwTxsnsrFtdMpOTSM5mrBRKVQ==", + "version": "1.4.276", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.276.tgz", + "integrity": "sha512-EpuHPqu8YhonqLBXHoU6hDJCD98FCe6KDoet3/gY1qsQ6usjJoHqBH2YIVs8FXaAtHwVL8Uqa/fsYao/vq9VWQ==", "dev": true }, "node_modules/emittery": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.8.1.tgz", - "integrity": "sha512-uDfvUjVrfGJJhymx/kz6prltenw1u7WrCg1oa94zYY8xxVpLLUu045LAT0dhDZdXG58/EpPL/5kA180fQ/qudg==", + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", "dev": true, "engines": { - "node": ">=10" + "node": ">=12" }, "funding": { "url": "https://github.com/sindresorhus/emittery?sponsor=1" @@ -3151,7 +3333,7 @@ "node_modules/encodeurl": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", "dev": true, "engines": { "node": ">= 0.8" @@ -3165,16 +3347,17 @@ "once": "^1.4.0" } }, - "node_modules/enquirer": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", - "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", + "node_modules/enhanced-resolve": { + "version": "5.12.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.12.0.tgz", + "integrity": "sha512-QHTXI/sZQmko1cbDoNAa3mJ5qhWUUNAq3vR0/YiD379fWQrcfuoX1+HW2S0MTt7XmoPLapdaDKUtelUSPic7hQ==", "dev": true, "dependencies": { - "ansi-colors": "^4.1.1" + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" }, "engines": { - "node": ">=8.6" + "node": ">=10.13.0" } }, "node_modules/error-ex": { @@ -3200,27 +3383,35 @@ } }, "node_modules/es-abstract": { - "version": "1.18.3", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.3.tgz", - "integrity": "sha512-nQIr12dxV7SSxE6r6f1l3DtAeEYdsGpps13dR0TwJg1S8gyp4ZPgy3FZcHBgbiQqnoqSTb+oC+kO4UQ0C/J8vw==", + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.20.4.tgz", + "integrity": "sha512-0UtvRN79eMe2L+UNEF1BwRe364sj/DXhQ/k5FmivgoSdpM90b8Jc0mDzKMGo7QS0BVbOP/bTwBKNnDc9rNzaPA==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", - "get-intrinsic": "^1.1.1", + "function.prototype.name": "^1.1.5", + "get-intrinsic": "^1.1.3", + "get-symbol-description": "^1.0.0", "has": "^1.0.3", - "has-symbols": "^1.0.2", - "is-callable": "^1.2.3", - "is-negative-zero": "^2.0.1", - "is-regex": "^1.1.3", - "is-string": "^1.0.6", - "object-inspect": "^1.10.3", + "has-property-descriptors": "^1.0.0", + "has-symbols": "^1.0.3", + "internal-slot": "^1.0.3", + "is-callable": "^1.2.7", + "is-negative-zero": "^2.0.2", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "is-string": "^1.0.7", + "is-weakref": "^1.0.2", + "object-inspect": "^1.12.2", "object-keys": "^1.1.1", - "object.assign": "^4.1.2", - "string.prototype.trimend": "^1.0.4", - "string.prototype.trimstart": "^1.0.4", - "unbox-primitive": "^1.0.1" + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.4.3", + "safe-regex-test": "^1.0.0", + "string.prototype.trimend": "^1.0.5", + "string.prototype.trimstart": "^1.0.5", + "unbox-primitive": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -3229,6 +3420,41 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/es-get-iterator": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.3.tgz", + "integrity": "sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "has-symbols": "^1.0.3", + "is-arguments": "^1.1.1", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.7", + "isarray": "^2.0.5", + "stop-iteration-iterator": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-get-iterator/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true + }, + "node_modules/es-shim-unscopables": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.0.tgz", + "integrity": "sha512-Jm6GPcCdC30eMLbZ2x8z2WuRwAws3zTBBKuusffYVUrNj/GVSUAZ+xKMaUpfNDR5IbyNA5LJbaecoUVbmUcB1w==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + } + }, "node_modules/es-to-primitive": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", @@ -3255,15 +3481,6 @@ "node": ">=6" } }, - "node_modules/escape-goat": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/escape-goat/-/escape-goat-2.1.1.tgz", - "integrity": "sha512-8/uIhbG12Csjy2JEW7D9pHbreaVaS/OpN3ycnyvElTdwM5n6GY6W6e2IPemfvGZeUMqZ9A/3GqIZMgKnBhAw/Q==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", @@ -3282,149 +3499,65 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/escodegen": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.0.0.tgz", - "integrity": "sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw==", - "dev": true, - "dependencies": { - "esprima": "^4.0.1", - "estraverse": "^5.2.0", - "esutils": "^2.0.2", - "optionator": "^0.8.1" - }, - "bin": { - "escodegen": "bin/escodegen.js", - "esgenerate": "bin/esgenerate.js" - }, - "engines": { - "node": ">=6.0" - }, - "optionalDependencies": { - "source-map": "~0.6.1" - } - }, - "node_modules/escodegen/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/escodegen/node_modules/levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", - "dev": true, - "dependencies": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/escodegen/node_modules/optionator": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", - "dev": true, - "dependencies": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.6", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "word-wrap": "~1.2.3" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/escodegen/node_modules/prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/escodegen/node_modules/type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", - "dev": true, - "dependencies": { - "prelude-ls": "~1.1.2" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/eslint": { - "version": "7.32.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", - "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", - "dev": true, - "dependencies": { - "@babel/code-frame": "7.12.11", - "@eslint/eslintrc": "^0.4.3", - "@humanwhocodes/config-array": "^0.5.0", - "ajv": "^6.10.0", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.0.1", - "doctrine": "^3.0.0", - "enquirer": "^2.3.5", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^2.1.0", - "eslint-visitor-keys": "^2.0.0", - "espree": "^7.3.1", - "esquery": "^1.4.0", + "node_modules/eslint": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", + "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.4", + "@eslint/js": "8.57.0", + "@humanwhocodes/config-array": "^0.11.14", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "@ungap/structured-clone": "^1.2.0", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^6.0.1", - "functional-red-black-tree": "^1.0.1", - "glob-parent": "^5.1.2", - "globals": "^13.6.0", - "ignore": "^4.0.6", - "import-fresh": "^3.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "js-yaml": "^3.13.1", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.2", "natural-compare": "^1.4.0", - "optionator": "^0.9.1", - "progress": "^2.0.0", - "regexpp": "^3.1.0", - "semver": "^7.2.1", - "strip-ansi": "^6.0.0", - "strip-json-comments": "^3.1.0", - "table": "^6.0.9", - "text-table": "^0.2.0", - "v8-compile-cache": "^2.0.3" + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" }, "bin": { "eslint": "bin/eslint.js" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "url": "https://opencollective.com/eslint" } }, "node_modules/eslint-config-prettier": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz", - "integrity": "sha512-BgZuLUSeKzvlL/VUjx/Yb787VQ26RU3gGjA3iiFvdsp/2bMfVIWUVP7tjxtjS0e+HP409cPlPvNkQloz8C91ew==", + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", + "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", "dev": true, "bin": { "eslint-config-prettier": "bin/cli.js" @@ -3434,41 +3567,64 @@ } }, "node_modules/eslint-import-resolver-node": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz", - "integrity": "sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA==", + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.6.tgz", + "integrity": "sha512-0En0w03NRVMn9Uiyn8YRPDKvWjxCWkslUEhGNTdGx15RvPJYQ+lbOlqrlNI2vEAs4pDYK4f/HN2TbDmk5TP0iw==", "dev": true, "dependencies": { - "debug": "^2.6.9", - "resolve": "^1.13.1" + "debug": "^3.2.7", + "resolve": "^1.20.0" } }, "node_modules/eslint-import-resolver-node/node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "dependencies": { - "ms": "2.0.0" + "ms": "^2.1.1" } }, - "node_modules/eslint-import-resolver-node/node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true + "node_modules/eslint-import-resolver-typescript": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.6.1.tgz", + "integrity": "sha512-xgdptdoi5W3niYeuQxKmzVDTATvLYqhpwmykwsh7f6HIOStGWEIL9iqZgQDF9u9OEzrRwR8no5q2VT+bjAujTg==", + "dev": true, + "dependencies": { + "debug": "^4.3.4", + "enhanced-resolve": "^5.12.0", + "eslint-module-utils": "^2.7.4", + "fast-glob": "^3.3.1", + "get-tsconfig": "^4.5.0", + "is-core-module": "^2.11.0", + "is-glob": "^4.0.3" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts/projects/eslint-import-resolver-ts" + }, + "peerDependencies": { + "eslint": "*", + "eslint-plugin-import": "*" + } }, "node_modules/eslint-module-utils": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.6.1.tgz", - "integrity": "sha512-ZXI9B8cxAJIH4nfkhTwcRTEAnrVfobYqwjWy/QMCZ8rHkZHFjf9yO4BzpiF9kCSfNlMG54eKigISHpX0+AaT4A==", + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.7.4.tgz", + "integrity": "sha512-j4GT+rqzCoRKHwURX7pddtIPGySnX9Si/cgMI5ztrcqOPtk5dDEeZ34CQVPphnqkJytlc97Vuk05Um2mJ3gEQA==", "dev": true, "dependencies": { - "debug": "^3.2.7", - "pkg-dir": "^2.0.0" + "debug": "^3.2.7" }, "engines": { "node": ">=4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } } }, "node_modules/eslint-module-utils/node_modules/debug": { @@ -3480,6 +3636,18 @@ "ms": "^2.1.1" } }, + "node_modules/eslint-plugin-escompat": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/eslint-plugin-escompat/-/eslint-plugin-escompat-3.3.4.tgz", + "integrity": "sha512-d/k6JwRzGRY6uZ426l6Ut6Eb2S/pi/079Ykj2GdWSzwm6WJHkdm28tECUWfLtpFA5ObApjPw6wR9bgY+uWAhag==", + "dev": true, + "dependencies": { + "browserslist": "^4.21.0" + }, + "peerDependencies": { + "eslint": ">=5.14.1" + } + }, "node_modules/eslint-plugin-eslint-comments": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/eslint-plugin-eslint-comments/-/eslint-plugin-eslint-comments-3.2.0.tgz", @@ -3508,194 +3676,189 @@ "node": ">=0.8.0" } }, - "node_modules/eslint-plugin-eslint-comments/node_modules/ignore": { - "version": "5.1.8", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", - "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", + "node_modules/eslint-plugin-filenames": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-filenames/-/eslint-plugin-filenames-1.3.2.tgz", + "integrity": "sha512-tqxJTiEM5a0JmRCUYQmxw23vtTxrb2+a3Q2mMOPhFxvt7ZQQJmdiuMby9B/vUAuVMghyP7oET+nIf6EO6CBd/w==", "dev": true, - "engines": { - "node": ">= 4" + "dependencies": { + "lodash.camelcase": "4.3.0", + "lodash.kebabcase": "4.1.1", + "lodash.snakecase": "4.1.1", + "lodash.upperfirst": "4.3.1" + }, + "peerDependencies": { + "eslint": "*" } }, "node_modules/eslint-plugin-github": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/eslint-plugin-github/-/eslint-plugin-github-4.1.5.tgz", - "integrity": "sha512-fY+3C8914Efqzmb6ODvL0ZNjv8xxLkwmUasYZ189IY1gL7AxFE9CVED+MZA8B1e+OZtnfTdrQR036t5AYoun0A==", + "version": "4.10.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-github/-/eslint-plugin-github-4.10.2.tgz", + "integrity": "sha512-F1F5aAFgi1Y5hYoTFzGQACBkw5W1hu2Fu5FSTrMlXqrojJnKl1S2pWO/rprlowRQpt+hzHhqSpsfnodJEVd5QA==", "dev": true, "dependencies": { - "@typescript-eslint/eslint-plugin": "^4.20.0", - "@typescript-eslint/parser": "^4.20.0", + "@github/browserslist-config": "^1.0.0", + "@typescript-eslint/eslint-plugin": "^7.0.1", + "@typescript-eslint/parser": "^7.0.1", + "aria-query": "^5.3.0", "eslint-config-prettier": ">=8.0.0", + "eslint-plugin-escompat": "^3.3.3", "eslint-plugin-eslint-comments": "^3.2.0", - "eslint-plugin-import": "^2.22.1", - "eslint-plugin-prettier": "^3.3.1", + "eslint-plugin-filenames": "^1.3.2", + "eslint-plugin-i18n-text": "^1.0.1", + "eslint-plugin-import": "^2.25.2", + "eslint-plugin-jsx-a11y": "^6.7.1", + "eslint-plugin-no-only-tests": "^3.0.0", + "eslint-plugin-prettier": "^5.0.0", "eslint-rule-documentation": ">=1.0.0", - "prettier": "^2.2.1", + "jsx-ast-utils": "^3.3.2", + "prettier": "^3.0.0", "svg-element-attributes": "^1.3.1" }, "bin": { "eslint-ignore-errors": "bin/eslint-ignore-errors.js" }, "peerDependencies": { - "eslint": "^7.23.0" + "eslint": "^8.0.1" } }, - "node_modules/eslint-plugin-import": { - "version": "2.23.4", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.23.4.tgz", - "integrity": "sha512-6/wP8zZRsnQFiR3iaPFgh5ImVRM1WN5NUWfTIRqwOdeiGJlBcSk82o1FEVq8yXmy4lkIzTo7YhHCIxlU/2HyEQ==", + "node_modules/eslint-plugin-github/node_modules/@typescript-eslint/eslint-plugin": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.1.0.tgz", + "integrity": "sha512-j6vT/kCulhG5wBmGtstKeiVr1rdXE4nk+DT1k6trYkwlrvW9eOF5ZbgKnd/YR6PcM4uTEXa0h6Fcvf6X7Dxl0w==", "dev": true, "dependencies": { - "array-includes": "^3.1.3", - "array.prototype.flat": "^1.2.4", - "debug": "^2.6.9", - "doctrine": "^2.1.0", - "eslint-import-resolver-node": "^0.3.4", - "eslint-module-utils": "^2.6.1", - "find-up": "^2.0.0", - "has": "^1.0.3", - "is-core-module": "^2.4.0", - "minimatch": "^3.0.4", - "object.values": "^1.1.3", - "pkg-up": "^2.0.0", - "read-pkg-up": "^3.0.0", - "resolve": "^1.20.0", - "tsconfig-paths": "^3.9.0" + "@eslint-community/regexpp": "^4.5.1", + "@typescript-eslint/scope-manager": "7.1.0", + "@typescript-eslint/type-utils": "7.1.0", + "@typescript-eslint/utils": "7.1.0", + "@typescript-eslint/visitor-keys": "7.1.0", + "debug": "^4.3.4", + "graphemer": "^1.4.0", + "ignore": "^5.2.4", + "natural-compare": "^1.4.0", + "semver": "^7.5.4", + "ts-api-utils": "^1.0.1" }, "engines": { - "node": ">=4" + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0" - } - }, - "node_modules/eslint-plugin-import/node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/eslint-plugin-import/node_modules/doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "dev": true, - "dependencies": { - "esutils": "^2.0.2" + "@typescript-eslint/parser": "^7.0.0", + "eslint": "^8.56.0" }, - "engines": { - "node": ">=0.10.0" + "peerDependenciesMeta": { + "typescript": { + "optional": true + } } }, - "node_modules/eslint-plugin-import/node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "node_modules/eslint-plugin-jest": { - "version": "25.2.4", - "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-25.2.4.tgz", - "integrity": "sha512-HRyinpgmEdkVr7pNPaYPHCoGqEzpgk79X8pg/xCeoAdurbyQjntJQ4pTzHl7BiVEBlam/F1Qsn+Dk0HtJO7Aaw==", + "node_modules/eslint-plugin-github/node_modules/@typescript-eslint/parser": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.1.0.tgz", + "integrity": "sha512-V1EknKUubZ1gWFjiOZhDSNToOjs63/9O0puCgGS8aDOgpZY326fzFu15QAUjwaXzRZjf/qdsdBrckYdv9YxB8w==", "dev": true, "dependencies": { - "@typescript-eslint/experimental-utils": "^5.0.0" + "@typescript-eslint/scope-manager": "7.1.0", + "@typescript-eslint/types": "7.1.0", + "@typescript-eslint/typescript-estree": "7.1.0", + "@typescript-eslint/visitor-keys": "7.1.0", + "debug": "^4.3.4" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/eslint-plugin": "^4.0.0 || ^5.0.0", - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + "eslint": "^8.56.0" }, "peerDependenciesMeta": { - "@typescript-eslint/eslint-plugin": { - "optional": true - }, - "jest": { + "typescript": { "optional": true } } }, - "node_modules/eslint-plugin-jest/node_modules/@types/json-schema": { - "version": "7.0.9", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz", - "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==", - "dev": true - }, - "node_modules/eslint-plugin-jest/node_modules/@typescript-eslint/experimental-utils": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-5.3.1.tgz", - "integrity": "sha512-RgFn5asjZ5daUhbK5Sp0peq0SSMytqcrkNfU4pnDma2D8P3ElZ6JbYjY8IMSFfZAJ0f3x3tnO3vXHweYg0g59w==", + "node_modules/eslint-plugin-github/node_modules/@typescript-eslint/scope-manager": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.1.0.tgz", + "integrity": "sha512-6TmN4OJiohHfoOdGZ3huuLhpiUgOGTpgXNUPJgeZOZR3DnIpdSgtt83RS35OYNNXxM4TScVlpVKC9jyQSETR1A==", "dev": true, "dependencies": { - "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.3.1", - "@typescript-eslint/types": "5.3.1", - "@typescript-eslint/typescript-estree": "5.3.1", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" + "@typescript-eslint/types": "7.1.0", + "@typescript-eslint/visitor-keys": "7.1.0" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "*" } }, - "node_modules/eslint-plugin-jest/node_modules/@typescript-eslint/scope-manager": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.3.1.tgz", - "integrity": "sha512-XksFVBgAq0Y9H40BDbuPOTUIp7dn4u8oOuhcgGq7EoDP50eqcafkMVGrypyVGvDYHzjhdUCUwuwVUK4JhkMAMg==", + "node_modules/eslint-plugin-github/node_modules/@typescript-eslint/type-utils": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.1.0.tgz", + "integrity": "sha512-UZIhv8G+5b5skkcuhgvxYWHjk7FW7/JP5lPASMEUoliAPwIH/rxoUSQPia2cuOj9AmDZmwUl1usKm85t5VUMew==", "dev": true, "dependencies": { - "@typescript-eslint/types": "5.3.1", - "@typescript-eslint/visitor-keys": "5.3.1" + "@typescript-eslint/typescript-estree": "7.1.0", + "@typescript-eslint/utils": "7.1.0", + "debug": "^4.3.4", + "ts-api-utils": "^1.0.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.56.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } } }, - "node_modules/eslint-plugin-jest/node_modules/@typescript-eslint/types": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.3.1.tgz", - "integrity": "sha512-bG7HeBLolxKHtdHG54Uac750eXuQQPpdJfCYuw4ZI3bZ7+GgKClMWM8jExBtp7NSP4m8PmLRM8+lhzkYnSmSxQ==", + "node_modules/eslint-plugin-github/node_modules/@typescript-eslint/types": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.1.0.tgz", + "integrity": "sha512-qTWjWieJ1tRJkxgZYXx6WUYtWlBc48YRxgY2JN1aGeVpkhmnopq+SUC8UEVGNXIvWH7XyuTjwALfG6bFEgCkQA==", "dev": true, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/eslint-plugin-jest/node_modules/@typescript-eslint/typescript-estree": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.3.1.tgz", - "integrity": "sha512-PwFbh/PKDVo/Wct6N3w+E4rLZxUDgsoII/GrWM2A62ETOzJd4M6s0Mu7w4CWsZraTbaC5UQI+dLeyOIFF1PquQ==", + "node_modules/eslint-plugin-github/node_modules/@typescript-eslint/typescript-estree": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.1.0.tgz", + "integrity": "sha512-k7MyrbD6E463CBbSpcOnwa8oXRdHzH1WiVzOipK3L5KSML92ZKgUBrTlehdi7PEIMT8k0bQixHUGXggPAlKnOQ==", "dev": true, "dependencies": { - "@typescript-eslint/types": "5.3.1", - "@typescript-eslint/visitor-keys": "5.3.1", - "debug": "^4.3.2", - "globby": "^11.0.4", + "@typescript-eslint/types": "7.1.0", + "@typescript-eslint/visitor-keys": "7.1.0", + "debug": "^4.3.4", + "globby": "^11.1.0", "is-glob": "^4.0.3", - "semver": "^7.3.5", - "tsutils": "^3.21.0" + "minimatch": "9.0.3", + "semver": "^7.5.4", + "ts-api-utils": "^1.0.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", @@ -3707,133 +3870,251 @@ } } }, - "node_modules/eslint-plugin-jest/node_modules/@typescript-eslint/visitor-keys": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.3.1.tgz", - "integrity": "sha512-3cHUzUuVTuNHx0Gjjt5pEHa87+lzyqOiHXy/Gz+SJOCW1mpw9xQHIIEwnKn+Thph1mgWyZ90nboOcSuZr/jTTQ==", + "node_modules/eslint-plugin-github/node_modules/@typescript-eslint/utils": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.1.0.tgz", + "integrity": "sha512-WUFba6PZC5OCGEmbweGpnNJytJiLG7ZvDBJJoUcX4qZYf1mGZ97mO2Mps6O2efxJcJdRNpqweCistDbZMwIVHw==", "dev": true, "dependencies": { - "@typescript-eslint/types": "5.3.1", - "eslint-visitor-keys": "^3.0.0" + "@eslint-community/eslint-utils": "^4.4.0", + "@types/json-schema": "^7.0.12", + "@types/semver": "^7.5.0", + "@typescript-eslint/scope-manager": "7.1.0", + "@typescript-eslint/types": "7.1.0", + "@typescript-eslint/typescript-estree": "7.1.0", + "semver": "^7.5.4" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/eslint-plugin-jest/node_modules/debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", - "dev": true, - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "peerDependencies": { + "eslint": "^8.56.0" } }, - "node_modules/eslint-plugin-jest/node_modules/eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", + "node_modules/eslint-plugin-github/node_modules/@typescript-eslint/visitor-keys": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.1.0.tgz", + "integrity": "sha512-FhUqNWluiGNzlvnDZiXad4mZRhtghdoKW6e98GoEOYSu5cND+E39rG5KwJMUzeENwm1ztYBRqof8wMLP+wNPIA==", "dev": true, "dependencies": { - "eslint-visitor-keys": "^2.0.0" + "@typescript-eslint/types": "7.1.0", + "eslint-visitor-keys": "^3.4.1" }, "engines": { - "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { - "url": "https://github.com/sponsors/mysticatea" - }, - "peerDependencies": { - "eslint": ">=5" + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/eslint-plugin-jest/node_modules/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", + "node_modules/eslint-plugin-github/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", "dev": true, - "engines": { - "node": ">=10" + "dependencies": { + "balanced-match": "^1.0.0" } }, - "node_modules/eslint-plugin-jest/node_modules/eslint-visitor-keys": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.1.0.tgz", - "integrity": "sha512-yWJFpu4DtjsWKkt5GeNBBuZMlNcYVs6vRCLoCVEJrTjaSB6LC98gFipNK/erM2Heg/E8mIK+hXG/pJMLK+eRZA==", + "node_modules/eslint-plugin-github/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint-plugin-jest/node_modules/globby": { - "version": "11.0.4", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.4.tgz", - "integrity": "sha512-9O4MVG9ioZJ08ffbcyVYyLOJLk5JQ688pJ4eMGLpdWLHq/Wr1D9BlriLQyL0E+jbkuePVZXYFj47QM/v093wHg==", + "node_modules/eslint-plugin-github/node_modules/minimatch": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz", + "integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==", "dev": true, "dependencies": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.1.1", - "ignore": "^5.1.4", - "merge2": "^1.3.0", - "slash": "^3.0.0" + "brace-expansion": "^2.0.1" }, "engines": { - "node": ">=10" + "node": ">=16 || 14 >=14.17" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/eslint-plugin-jest/node_modules/ignore": { - "version": "5.1.9", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.9.tgz", - "integrity": "sha512-2zeMQpbKz5dhZ9IwL0gbxSW5w0NK/MSAMtNuhgIHEPmaU3vPdKPL0UdvUCXs5SS4JAwsBxysK5sFMW8ocFiVjQ==", + "node_modules/eslint-plugin-i18n-text": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-i18n-text/-/eslint-plugin-i18n-text-1.0.1.tgz", + "integrity": "sha512-3G3UetST6rdqhqW9SfcfzNYMpQXS7wNkJvp6dsXnjzGiku6Iu5hl3B0kmk6lIcFPwYjhQIY+tXVRtK9TlGT7RA==", "dev": true, - "engines": { - "node": ">= 4" + "peerDependencies": { + "eslint": ">=5.0.0" } }, - "node_modules/eslint-plugin-jest/node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "node_modules/eslint-plugin-import": { + "version": "2.26.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.26.0.tgz", + "integrity": "sha512-hYfi3FXaM8WPLf4S1cikh/r4IxnO6zrhZbEGz2b660EJRbuxgpDS5gkCuYgGWg2xxh2rBuIr4Pvhve/7c31koA==", "dev": true, "dependencies": { - "is-extglob": "^2.1.1" + "array-includes": "^3.1.4", + "array.prototype.flat": "^1.2.5", + "debug": "^2.6.9", + "doctrine": "^2.1.0", + "eslint-import-resolver-node": "^0.3.6", + "eslint-module-utils": "^2.7.3", + "has": "^1.0.3", + "is-core-module": "^2.8.1", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.values": "^1.1.5", + "resolve": "^1.22.0", + "tsconfig-paths": "^3.14.1" }, "engines": { - "node": ">=0.10.0" + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8" } }, - "node_modules/eslint-plugin-prettier": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.4.0.tgz", - "integrity": "sha512-UDK6rJT6INSfcOo545jiaOwB701uAIt2/dR7WnFQoGCVl1/EMqdANBmwUaqqQ45aXprsTGzSa39LI1PyuRBxxw==", + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "dependencies": { - "prettier-linter-helpers": "^1.0.0" - }, + "ms": "2.0.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, "engines": { - "node": ">=6.0.0" + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true + }, + "node_modules/eslint-plugin-jest": { + "version": "27.9.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.9.0.tgz", + "integrity": "sha512-QIT7FH7fNmd9n4se7FFKHbsLKGQiw885Ds6Y/sxKgCZ6natwCsXdgPOADnYVxN2QrRweF0FZWbJ6S7Rsn7llug==", + "dev": true, + "dependencies": { + "@typescript-eslint/utils": "^5.10.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@typescript-eslint/eslint-plugin": "^5.0.0 || ^6.0.0 || ^7.0.0", + "eslint": "^7.0.0 || ^8.0.0", + "jest": "*" + }, + "peerDependenciesMeta": { + "@typescript-eslint/eslint-plugin": { + "optional": true + }, + "jest": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-jsx-a11y": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.7.1.tgz", + "integrity": "sha512-63Bog4iIethyo8smBklORknVjB0T2dwB8Mr/hIC+fBS0uyHdYYpzM/Ed+YC8VxTjlXHEWFOdmgwcDn1U2L9VCA==", + "dev": true, + "dependencies": { + "@babel/runtime": "^7.20.7", + "aria-query": "^5.1.3", + "array-includes": "^3.1.6", + "array.prototype.flatmap": "^1.3.1", + "ast-types-flow": "^0.0.7", + "axe-core": "^4.6.2", + "axobject-query": "^3.1.1", + "damerau-levenshtein": "^1.0.8", + "emoji-regex": "^9.2.2", + "has": "^1.0.3", + "jsx-ast-utils": "^3.3.3", + "language-tags": "=1.0.5", + "minimatch": "^3.1.2", + "object.entries": "^1.1.6", + "object.fromentries": "^2.0.6", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=4.0" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8" + } + }, + "node_modules/eslint-plugin-jsx-a11y/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true + }, + "node_modules/eslint-plugin-jsx-a11y/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-plugin-no-only-tests": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-no-only-tests/-/eslint-plugin-no-only-tests-3.1.0.tgz", + "integrity": "sha512-Lf4YW/bL6Un1R6A76pRZyE1dl1vr31G/ev8UzIc/geCgFWyrKil8hVjYqWVKGB/UIGmb6Slzs9T0wNezdSVegw==", + "dev": true, + "engines": { + "node": ">=5.0.0" + } + }, + "node_modules/eslint-plugin-prettier": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.1.3.tgz", + "integrity": "sha512-C9GCVAs4Eq7ZC/XFQHITLiHJxQngdtraXaM+LoUFoFp/lHNl2Zn8f3WQbe9HvTBBQ9YnKFB0/2Ajdqwo5D1EAw==", + "dev": true, + "dependencies": { + "prettier-linter-helpers": "^1.0.0", + "synckit": "^0.8.6" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-plugin-prettier" }, "peerDependencies": { - "eslint": ">=5.0.0", - "prettier": ">=1.13.0" + "@types/eslint": ">=8.0.0", + "eslint": ">=8.0.0", + "eslint-config-prettier": "*", + "prettier": ">=3.0.0" }, "peerDependenciesMeta": { + "@types/eslint": { + "optional": true + }, "eslint-config-prettier": { "optional": true } @@ -3862,27 +4143,21 @@ } }, "node_modules/eslint-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", - "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", "dev": true, "dependencies": { - "eslint-visitor-keys": "^1.1.0" + "eslint-visitor-keys": "^2.0.0" }, "engines": { - "node": ">=6" + "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" }, "funding": { "url": "https://github.com/sponsors/mysticatea" - } - }, - "node_modules/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", - "dev": true, - "engines": { - "node": ">=4" + }, + "peerDependencies": { + "eslint": ">=5" } }, "node_modules/eslint-visitor-keys": { @@ -3894,49 +4169,82 @@ "node": ">=10" } }, - "node_modules/eslint/node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "node_modules/eslint/node_modules/eslint-scope": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", + "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", "dev": true, "dependencies": { - "sprintf-js": "~1.0.2" + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint/node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/eslint/node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "is-glob": "^4.0.3" }, - "bin": { - "js-yaml": "bin/js-yaml.js" + "engines": { + "node": ">=10.13.0" } }, "node_modules/espree": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", - "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", "dev": true, "dependencies": { - "acorn": "^7.4.0", - "acorn-jsx": "^5.3.1", - "eslint-visitor-keys": "^1.3.0" + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, "node_modules/espree/node_modules/eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true, "engines": { - "node": ">=4" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, "node_modules/esprima": { @@ -3953,9 +4261,9 @@ } }, "node_modules/esquery": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", - "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", + "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", "dev": true, "dependencies": { "estraverse": "^5.1.0" @@ -3965,9 +4273,9 @@ } }, "node_modules/esquery/node_modules/estraverse": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", - "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true, "engines": { "node": ">=4.0" @@ -4015,12 +4323,18 @@ "node_modules/etag": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", "dev": true, "engines": { "node": ">= 0.6" } }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "dev": true + }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", @@ -4047,60 +4361,62 @@ "node_modules/exit": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", "dev": true, "engines": { "node": ">= 0.8.0" } }, "node_modules/expect": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/expect/-/expect-27.5.1.tgz", - "integrity": "sha512-E1q5hSUG2AmYQwQJ041nvgpkODHQvB+RKlB4IYdru6uJsyFTRyZAP463M+1lINorwbqAmUggi6+WwkD8lCS/Dw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", - "jest-get-type": "^27.5.1", - "jest-matcher-utils": "^27.5.1", - "jest-message-util": "^27.5.1" + "@jest/expect-utils": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/express": { - "version": "4.17.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", - "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", "dev": true, "dependencies": { - "accepts": "~1.3.7", + "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.19.0", - "content-disposition": "0.5.3", + "body-parser": "1.20.2", + "content-disposition": "0.5.4", "content-type": "~1.0.4", - "cookie": "0.4.0", + "cookie": "0.6.0", "cookie-signature": "1.0.6", "debug": "2.6.9", - "depd": "~1.1.2", + "depd": "2.0.0", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", - "finalhandler": "~1.1.2", + "finalhandler": "1.2.0", "fresh": "0.5.2", + "http-errors": "2.0.0", "merge-descriptors": "1.0.1", "methods": "~1.1.2", - "on-finished": "~2.3.0", + "on-finished": "2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.5", - "qs": "6.7.0", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", "range-parser": "~1.2.1", - "safe-buffer": "5.1.2", - "send": "0.17.1", - "serve-static": "1.14.1", - "setprototypeof": "1.1.1", - "statuses": "~1.5.0", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" @@ -4143,6 +4459,38 @@ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, + "node_modules/express/node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/express/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -4150,26 +4498,30 @@ "dev": true }, "node_modules/fast-diff": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", - "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", + "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", "dev": true }, + "node_modules/fast-fifo": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.0.tgz", + "integrity": "sha512-IgfweLvEpwyA4WgiQe9Nx6VV2QkML2NkvZnk1oKnIzXgXdWxuhF7zw4DvLTPZJn6PIUneiAXPF24QmoEqHTjyw==" + }, "node_modules/fast-glob": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.5.tgz", - "integrity": "sha512-2DtFcgT68wiTTiwZ2hNdJfcHNke9XOfnwmBRWXhmeKM8rF0TGwmC/Qto3S7RoZKp5cilZbxzO5iTNTQsJ+EeDg==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", + "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", "dev": true, "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.0", + "glob-parent": "^5.1.2", "merge2": "^1.3.0", - "micromatch": "^4.0.2", - "picomatch": "^2.2.1" + "micromatch": "^4.0.4" }, "engines": { - "node": ">=8" + "node": ">=8.6.0" } }, "node_modules/fast-json-stable-stringify": { @@ -4181,13 +4533,13 @@ "node_modules/fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", "dev": true }, "node_modules/fastq": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.11.0.tgz", - "integrity": "sha512-7Eczs8gIPDrVzT+EksYBcupqMyxSHXXrHOLRRxU2/DicV8789MRBRR8+Hc2uWzUupOs4YS4JzBmBxjjCVBxD/g==", + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.13.0.tgz", + "integrity": "sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==", "dev": true, "dependencies": { "reusify": "^1.0.4" @@ -4215,9 +4567,9 @@ } }, "node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dev": true, "dependencies": { "to-regex-range": "^5.0.1" @@ -4227,17 +4579,17 @@ } }, "node_modules/finalhandler": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", - "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", "dev": true, "dependencies": { "debug": "2.6.9", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", - "on-finished": "~2.3.0", + "on-finished": "2.4.1", "parseurl": "~1.3.3", - "statuses": "~1.5.0", + "statuses": "2.0.1", "unpipe": "~1.0.0" }, "engines": { @@ -4256,19 +4608,35 @@ "node_modules/finalhandler/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true }, + "node_modules/finalhandler/node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, "dependencies": { - "locate-path": "^2.0.0" + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" }, "engines": { - "node": ">=4" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/flat-cache": { @@ -4290,37 +4658,13 @@ "integrity": "sha512-zAoAQiudy+r5SvnSw3KJy5os/oRJYHzrzja/tBDqrZtNhUw8bt6y8OBzMWcjWr+8liV8Eb6yOhw8WZ7VFZ5ZzA==", "dev": true }, - "node_modules/follow-redirects": { - "version": "1.14.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", - "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, - "node_modules/form-data": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", - "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", + "node_modules/for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", "dev": true, "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" + "is-callable": "^1.1.3" } }, "node_modules/forwarded": { @@ -4335,7 +4679,7 @@ "node_modules/fresh": { "version": "0.5.2", "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", "dev": true, "engines": { "node": ">= 0.6" @@ -4372,11 +4716,32 @@ "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, - "node_modules/functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "dev": true + "node_modules/function.prototype.name": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.5.tgz", + "integrity": "sha512-uN7m/BzVKQnCUF/iW8jYea67v++2u7m5UgENbHRtdDVclOUP+FMPlCNdmk0h/ysGyo2tavMJEDqJAkJdRa1vMA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "es-abstract": "^1.19.0", + "functions-have-names": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/gensync": { "version": "1.0.0-beta.2", @@ -4396,26 +4761,32 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-east-asian-width": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.2.0.tgz", + "integrity": "sha512-2nk+7SIVb14QrgXFHcm84tD4bKQz0RxPuMT8Ag5KPOq7J5fEmAg0UbXdTOSHqNuHSU28k55qnceesxXRZGzKWA==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.0.tgz", + "integrity": "sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q==", "dev": true, "dependencies": { "function-bind": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1" + "has-symbols": "^1.0.3" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/get-own-enumerable-property-symbols": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", - "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==", - "dev": true - }, "node_modules/get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", @@ -4437,6 +4808,31 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/get-symbol-description": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz", + "integrity": "sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-tsconfig": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.5.0.tgz", + "integrity": "sha512-MjhiaIWCJ1sAU4pIQ5i5OfOuHHxVo1oYeNsWTON7jxYkod8pHocXeh+SSbmu5OZZZK73B6cbJ2XADzXehLyovQ==", + "dev": true, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, "node_modules/glob": { "version": "7.1.7", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", @@ -4469,25 +4865,10 @@ "node": ">= 6" } }, - "node_modules/global-dirs": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-3.0.0.tgz", - "integrity": "sha512-v8ho2DS5RiCjftj1nD9NmnfaOzTdud7RRnVd9kFNOjqZbISlx5DQ+OrTkywgd0dIt7oFCvKetZSHoHcP3sDdiA==", - "dev": true, - "dependencies": { - "ini": "2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/globals": { - "version": "13.10.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.10.0.tgz", - "integrity": "sha512-piHC3blgLGFjvOuMmWZX60f+na1lXFDhQXBf1UYp2fXPXqvEUbOhNwi6BsQ0bQishwedgnjkwv1d9zKf+MWw3g==", + "version": "13.23.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.23.0.tgz", + "integrity": "sha512-XAmF0RjlrjY23MA51q3HltdlGxUpXPvg0GioKiD9X6HD28iMjo2dKC8Vqwm7lne4GNr78+RHTfliktR6ZH09wA==", "dev": true, "dependencies": { "type-fest": "^0.20.2" @@ -4500,16 +4881,16 @@ } }, "node_modules/globby": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.3.tgz", - "integrity": "sha512-ffdmosjA807y7+lA1NM0jELARVmYul/715xiILEjo3hBLPTcirgQNnXECn5g3mtR8TOLCVbkfua1Hpen25/Xcg==", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", "dev": true, "dependencies": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", - "fast-glob": "^3.1.1", - "ignore": "^5.1.4", - "merge2": "^1.3.0", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", "slash": "^3.0.0" }, "engines": { @@ -4519,47 +4900,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/globby/node_modules/ignore": { - "version": "5.1.8", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", - "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", - "dev": true, - "engines": { - "node": ">= 4" - } - }, - "node_modules/got": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/got/-/got-9.6.0.tgz", - "integrity": "sha512-R7eWptXuGYxwijs0eV+v3o6+XH1IqVK8dJOEecQfTmkncw9AV4dcw/Dhxi8MdlqPthxxpZyizMzyg8RTmEsG+Q==", - "dev": true, - "dependencies": { - "@sindresorhus/is": "^0.14.0", - "@szmarczak/http-timer": "^1.1.2", - "cacheable-request": "^6.0.0", - "decompress-response": "^3.3.0", - "duplexer3": "^0.1.4", - "get-stream": "^4.1.0", - "lowercase-keys": "^1.0.1", - "mimic-response": "^1.0.1", - "p-cancelable": "^1.0.0", - "to-readable-stream": "^1.0.0", - "url-parse-lax": "^3.0.0" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/got/node_modules/get-stream": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", - "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", "dev": true, "dependencies": { - "pump": "^3.0.0" + "get-intrinsic": "^1.1.3" }, - "engines": { - "node": ">=6" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/graceful-fs": { @@ -4568,6 +4918,12 @@ "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", "dev": true }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true + }, "node_modules/has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", @@ -4581,9 +4937,9 @@ } }, "node_modules/has-bigints": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz", - "integrity": "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", "dev": true, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -4598,43 +4954,43 @@ "node": ">=8" } }, - "node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "node_modules/has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", "dev": true, - "engines": { - "node": ">= 0.4" + "dependencies": { + "get-intrinsic": "^1.1.1" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/has-yarn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/has-yarn/-/has-yarn-2.1.0.tgz", - "integrity": "sha512-UqBRqi4ju7T+TqGNdqAO0PaSVGsDGJUBQvk9eUWNGRY1CFGDzYhLWoM7JQEemnlvVcv/YEmc2wNW8BC24EnUsw==", + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", "dev": true, "engines": { - "node": ">=8" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/hosted-git-info": { - "version": "2.8.9", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", - "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", - "dev": true - }, - "node_modules/html-encoding-sniffer": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz", - "integrity": "sha512-D5JbOMBIR/TVZkubHT+OyT2705QvogUW4IBn6nHd756OwieSF9aDYFj4dv6HHEVGYbHaLETa3WggZYWWMyy3ZQ==", + "node_modules/has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", "dev": true, "dependencies": { - "whatwg-encoding": "^1.0.5" + "has-symbols": "^1.0.2" }, "engines": { - "node": ">=10" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/html-escaper": { @@ -4643,59 +4999,20 @@ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, - "node_modules/http-cache-semantics": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz", - "integrity": "sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==", - "dev": true - }, "node_modules/http-errors": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", - "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", - "dev": true, - "dependencies": { - "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/http-errors/node_modules/inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true - }, - "node_modules/http-proxy-agent": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", - "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", - "dev": true, - "dependencies": { - "@tootallnate/once": "1", - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/https-proxy-agent": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", - "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "dev": true, "dependencies": { - "agent-base": "6", - "debug": "4" + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" }, "engines": { - "node": ">= 6" + "node": ">= 0.8" } }, "node_modules/human-signals": { @@ -4708,15 +5025,15 @@ } }, "node_modules/husky": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/husky/-/husky-7.0.4.tgz", - "integrity": "sha512-vbaCKN2QLtP/vD4yvs6iz6hBEo6wkSzs8HpRah1Z6aGmF2KW5PdYuAd7uX5a+OyBZHBhd+TFLqgjUgytQr4RvQ==", + "version": "9.0.11", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.0.11.tgz", + "integrity": "sha512-AB6lFlbwwyIqMdHYhwPe+kjOC3Oc5P3nThEoW/AaO2BX3vJDjWPFxYLxokUZOo6RNX20He3AaT8sESs9NJcmEw==", "dev": true, "bin": { - "husky": "lib/bin.js" + "husky": "bin.mjs" }, "engines": { - "node": ">=12" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/typicode" @@ -4754,9 +5071,9 @@ ] }, "node_modules/ignore": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", "dev": true, "engines": { "node": ">= 4" @@ -4778,15 +5095,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/import-lazy": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", - "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/import-local": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", @@ -4806,88 +5114,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/import-local/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/import-local/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/import-local/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/import-local/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/import-local/node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/import-local/node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/import-local/node_modules/pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "dependencies": { - "find-up": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", @@ -4897,15 +5123,6 @@ "node": ">=0.8.19" } }, - "node_modules/indent-string": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", - "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -4921,13 +5138,18 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, - "node_modules/ini": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ini/-/ini-2.0.0.tgz", - "integrity": "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==", + "node_modules/internal-slot": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.5.tgz", + "integrity": "sha512-Y+R5hJrzs52QCG2laLn4udYVnxsfny9CpOhNhUvk/SSSVyF6T27FzRbF0sroPidSu3X8oEAkOn2K804mjpt6UQ==", "dev": true, + "dependencies": { + "get-intrinsic": "^1.2.0", + "has": "^1.0.3", + "side-channel": "^1.0.4" + }, "engines": { - "node": ">=10" + "node": ">= 0.4" } }, "node_modules/ipaddr.js": { @@ -4939,28 +5161,62 @@ "node": ">= 0.10" } }, + "node_modules/is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.1.tgz", + "integrity": "sha512-ASfLknmY8Xa2XtB4wmbz13Wu202baeA18cJBCeCy0wXUHZF0IPyVEXqKEcd+t2fNSLLL1vC6k7lxZEojNbISXQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-typed-array": "^1.1.10" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", "dev": true }, "node_modules/is-bigint": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.2.tgz", - "integrity": "sha512-0JV5+SOCQkIdzjBK9buARcV804Ddu7A0Qet6sHi3FimE9ne6m4BGQZfRn+NZiXbBk4F4XmHfDZIipLj9pX8dSA==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", "dev": true, + "dependencies": { + "has-bigints": "^1.0.1" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-boolean-object": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.1.tgz", - "integrity": "sha512-bXdQWkECBUIAcCkeH1unwJLIpZYaa5VvuygSyS/c2lf719mTKZDU5UdDRlpd01UjADgmW8RfqaP+mRaVPdr/Ng==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", "dev": true, "dependencies": { - "call-bind": "^1.0.2" + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" @@ -4970,9 +5226,9 @@ } }, "node_modules/is-callable": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", - "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", "dev": true, "engines": { "node": ">= 0.4" @@ -4981,28 +5237,10 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-ci": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", - "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", - "dev": true, - "dependencies": { - "ci-info": "^2.0.0" - }, - "bin": { - "is-ci": "bin.js" - } - }, - "node_modules/is-ci/node_modules/ci-info": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", - "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", - "dev": true - }, "node_modules/is-core-module": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.4.0.tgz", - "integrity": "sha512-6A2fkfq1rfeQZjxrZJGerpLCTHRNEBiSgnu0+obeJpEPZRUooHgsizvzv0ZjJwOz3iWIHdJtVWJ/tmPr3D21/A==", + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", "dev": true, "dependencies": { "has": "^1.0.3" @@ -5012,10 +5250,13 @@ } }, "node_modules/is-date-object": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.4.tgz", - "integrity": "sha512-/b4ZVsG7Z5XVtIxs/h9W8nvfLgSAyKYdtGWQLbqy6jA1icmgjf8WCoTKgeS4wy5tYaPePouzFMANbnj94c2Z+A==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, "engines": { "node": ">= 0.4" }, @@ -5051,9 +5292,9 @@ } }, "node_modules/is-glob": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", - "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "dependencies": { "is-extglob": "^2.1.1" @@ -5062,26 +5303,19 @@ "node": ">=0.10.0" } }, - "node_modules/is-installed-globally": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/is-installed-globally/-/is-installed-globally-0.4.0.tgz", - "integrity": "sha512-iwGqO3J21aaSkC7jWnHP/difazwS7SFeIqxv6wEtLU8Y5KlzFTjyqcSIT0d8s4+dDhKytsk9PJZ2BkS5eZwQRQ==", + "node_modules/is-map": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.2.tgz", + "integrity": "sha512-cOZFQQozTha1f4MxLFzlgKYPTyj26picdZTx82hbc/Xf4K/tZOOXSCkMvU4pKioRXGDLJRn0GM7Upe7kR721yg==", "dev": true, - "dependencies": { - "global-dirs": "^3.0.0", - "is-path-inside": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-negative-zero": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", - "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz", + "integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==", "dev": true, "engines": { "node": ">= 0.4" @@ -5090,18 +5324,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-npm": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-5.0.0.tgz", - "integrity": "sha512-WW/rQLOazUq+ST/bCAVBp/2oMERWLsR7OrKyt052dNDk4DHcDE0/7QSXITlmi+VBcV13DfIbysG3tZJm5RfdBA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -5112,10 +5334,13 @@ } }, "node_modules/is-number-object": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.5.tgz", - "integrity": "sha512-RU0lI/n95pMoUKu9v1BZP5MBcZuNSVJkMkAG2dJqC4z2GlkGUNeH68SuHuBKBD/XFe+LHZ+f9BKkLET60Niedw==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, "engines": { "node": ">= 0.4" }, @@ -5123,15 +5348,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", - "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/is-path-inside": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", @@ -5141,20 +5357,6 @@ "node": ">=8" } }, - "node_modules/is-plain-object": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", - "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-potential-custom-element-name": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", - "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true - }, "node_modules/is-promise": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz", @@ -5162,13 +5364,13 @@ "dev": true }, "node_modules/is-regex": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", - "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", "dev": true, "dependencies": { "call-bind": "^1.0.2", - "has-symbols": "^1.0.2" + "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" @@ -5177,29 +5379,47 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-regexp": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", - "integrity": "sha1-/S2INUXEa6xaYz57mgnof6LLUGk=", + "node_modules/is-set": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.2.tgz", + "integrity": "sha512-+2cnTEZeY5z/iXGbLhPrOAaK/Mau5k5eXq9j14CpRTftq0pAJu2MwVRSZhyZWBzx3o6X795Lz6Bpb6R0GKf37g==", "dev": true, - "engines": { - "node": ">=0.10.0" + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz", + "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", - "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", "dev": true, "engines": { "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-string": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.6.tgz", - "integrity": "sha512-2gdzbKUuqtQ3lYNrUTQYoClPhm7oQu4UdpSZMp1/DGgkHBT8E2Z1l0yMdb6D4zNAxwDiMv8MdulKROJGNl0Q0w==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, "engines": { "node": ">= 0.4" }, @@ -5222,29 +5442,58 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", - "dev": true - }, - "node_modules/is-unicode-supported": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", - "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "node_modules/is-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.10.tgz", + "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", "dev": true, + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + }, "engines": { - "node": ">=10" + "node": ">= 0.4" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-yarn-global": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz", - "integrity": "sha512-VjSeb/lHmkoyd8ryPVIKvOCn4D1koMqY+vqyjjUfc3xyKtP4dYOxM44sZrnqQSzSds3xyOrUTLTC9LVCVgLngw==", - "dev": true + "node_modules/is-weakmap": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.1.tgz", + "integrity": "sha512-NSBR4kH5oVj1Uwvv970ruUkCV7O1mzgVFO4/rev2cLRda9Tm9HrL70ZPut4rOHgY0FNrUu9BCbXA2sdQ+x0chA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", + "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.2.tgz", + "integrity": "sha512-t2yVvttHkQktwnNNmBQ98AhENLdPUTDTE21uPqAQ0ARwQfGeQKRVS0NNurH7bTf7RrvcVn1OOge45CnBeHCSmg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/isarray": { "version": "0.0.1", @@ -5293,17 +5542,17 @@ } }, "node_modules/istanbul-lib-report": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", - "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", "dev": true, "dependencies": { "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^3.0.0", + "make-dir": "^4.0.0", "supports-color": "^7.1.0" }, "engines": { - "node": ">=8" + "node": ">=10" } }, "node_modules/istanbul-lib-source-maps": { @@ -5321,9 +5570,9 @@ } }, "node_modules/istanbul-reports": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.4.tgz", - "integrity": "sha512-r1/DshN4KSE7xWEknZLLLLDn5CJybV3nw01VTkp6D5jzLuELlcbudfj/eSQFvrKsJuTVCGnePO7ho82Nw9zzfw==", + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz", + "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==", "dev": true, "dependencies": { "html-escaper": "^2.0.0", @@ -5334,20 +5583,21 @@ } }, "node_modules/jest": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz", - "integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", + "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", "dev": true, "dependencies": { - "@jest/core": "^27.5.1", + "@jest/core": "^29.7.0", + "@jest/types": "^29.6.3", "import-local": "^3.0.2", - "jest-cli": "^27.5.1" + "jest-cli": "^29.7.0" }, "bin": { "jest": "bin/jest.js" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" @@ -5359,73 +5609,73 @@ } }, "node_modules/jest-changed-files": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-27.5.1.tgz", - "integrity": "sha512-buBLMiByfWGCoMsLLzGUUSpAmIAGnbR2KJoMN10ziLhOLvP4e0SlypHnAel8iqQXTrcbmfEY9sSqae5sgUsTvw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", + "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", "execa": "^5.0.0", - "throat": "^6.0.1" + "jest-util": "^29.7.0", + "p-limit": "^3.1.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-circus": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-27.5.1.tgz", - "integrity": "sha512-D95R7x5UtlMA5iBYsOHFFbMD/GVA4R/Kdq15f7xYWUfWHBto9NYRsOvnSauTgdF+ogCpJ4tyKOXhUifxS65gdw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", + "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", "dev": true, "dependencies": { - "@jest/environment": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "co": "^4.6.0", - "dedent": "^0.7.0", - "expect": "^27.5.1", + "dedent": "^1.0.0", "is-generator-fn": "^2.0.0", - "jest-each": "^27.5.1", - "jest-matcher-utils": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-runtime": "^27.5.1", - "jest-snapshot": "^27.5.1", - "jest-util": "^27.5.1", - "pretty-format": "^27.5.1", + "jest-each": "^29.7.0", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0", + "pretty-format": "^29.7.0", + "pure-rand": "^6.0.0", "slash": "^3.0.0", - "stack-utils": "^2.0.3", - "throat": "^6.0.1" + "stack-utils": "^2.0.3" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-cli": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-27.5.1.tgz", - "integrity": "sha512-Hc6HOOwYq4/74/c62dEE3r5elx8wjYqxY0r0G/nFrLDPMFRu6RA/u8qINOIkvhxG7mMQ5EJsOGfRpI8L6eFUVw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", + "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", "dev": true, "dependencies": { - "@jest/core": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/core": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", "chalk": "^4.0.0", + "create-jest": "^29.7.0", "exit": "^0.1.2", - "graceful-fs": "^4.2.9", "import-local": "^3.0.2", - "jest-config": "^27.5.1", - "jest-util": "^27.5.1", - "jest-validate": "^27.5.1", - "prompts": "^2.0.1", - "yargs": "^16.2.0" + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "yargs": "^17.3.1" }, "bin": { "jest": "bin/jest.js" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" @@ -5437,372 +5687,204 @@ } }, "node_modules/jest-config": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-27.5.1.tgz", - "integrity": "sha512-5sAsjm6tGdsVbW9ahcChPAFCk4IlkQUknH5AvKjuLTSlcO/wCZKyFdn7Rg0EkC+OGgWODEy2hDpWB1PgzH0JNA==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", + "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", "dev": true, "dependencies": { - "@babel/core": "^7.8.0", - "@jest/test-sequencer": "^27.5.1", - "@jest/types": "^27.5.1", - "babel-jest": "^27.5.1", + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-jest": "^29.7.0", "chalk": "^4.0.0", "ci-info": "^3.2.0", "deepmerge": "^4.2.2", - "glob": "^7.1.1", + "glob": "^7.1.3", "graceful-fs": "^4.2.9", - "jest-circus": "^27.5.1", - "jest-environment-jsdom": "^27.5.1", - "jest-environment-node": "^27.5.1", - "jest-get-type": "^27.5.1", - "jest-jasmine2": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-runner": "^27.5.1", - "jest-util": "^27.5.1", - "jest-validate": "^27.5.1", + "jest-circus": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", "micromatch": "^4.0.4", "parse-json": "^5.2.0", - "pretty-format": "^27.5.1", + "pretty-format": "^29.7.0", "slash": "^3.0.0", "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "peerDependencies": { + "@types/node": "*", "ts-node": ">=9.0.0" }, "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, "ts-node": { "optional": true } } }, - "node_modules/jest-config/node_modules/parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/jest-diff": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-27.5.1.tgz", - "integrity": "sha512-m0NvkX55LDt9T4mctTEgnZk3fmEg3NRYutvMPWM/0iPnkFj2wIeF45O1718cMSOFO1vINkqmxqD8vE37uTEbqw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", + "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", "dev": true, "dependencies": { "chalk": "^4.0.0", - "diff-sequences": "^27.5.1", - "jest-get-type": "^27.5.1", - "pretty-format": "^27.5.1" + "diff-sequences": "^29.6.3", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-docblock": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-27.5.1.tgz", - "integrity": "sha512-rl7hlABeTsRYxKiUfpHrQrG4e2obOiTQWfMEH3PxPjOtdsfLQO4ReWSZaQ7DETm4xu07rl4q/h4zcKXyU0/OzQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", + "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", "dev": true, "dependencies": { "detect-newline": "^3.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-each": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-27.5.1.tgz", - "integrity": "sha512-1Ff6p+FbhT/bXQnEouYy00bkNSY7OUpfIcmdl8vZ31A1UUaurOLPA8a8BbJOF2RDUElwJhmeaV7LnagI+5UwNQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", + "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", + "@jest/types": "^29.6.3", "chalk": "^4.0.0", - "jest-get-type": "^27.5.1", - "jest-util": "^27.5.1", - "pretty-format": "^27.5.1" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, - "node_modules/jest-environment-jsdom": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-27.5.1.tgz", - "integrity": "sha512-TFBvkTC1Hnnnrka/fUb56atfDtJ9VMZ94JkjTbggl1PEpwrYtUBKMezB3inLmWqQsXYLcMwNoDQwoBTAvFfsfw==", - "dev": true, - "dependencies": { - "@jest/environment": "^27.5.1", - "@jest/fake-timers": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "jest-mock": "^27.5.1", - "jest-util": "^27.5.1", - "jsdom": "^16.6.0" + "jest-get-type": "^29.6.3", + "jest-util": "^29.7.0", + "pretty-format": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-environment-node": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-27.5.1.tgz", - "integrity": "sha512-Jt4ZUnxdOsTGwSRAfKEnE6BcwsSPNOijjwifq5sDFSA2kesnXTvNqKHYgM0hDq3549Uf/KzdXNYn4wMZJPlFLw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", + "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", "dev": true, "dependencies": { - "@jest/environment": "^27.5.1", - "@jest/fake-timers": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", "@types/node": "*", - "jest-mock": "^27.5.1", - "jest-util": "^27.5.1" + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-get-type": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-27.5.1.tgz", - "integrity": "sha512-2KY95ksYSaK7DMBWQn6dQz3kqAf3BB64y2udeG+hv4KfSOb9qwcYQstTJc1KCbsix+wLZWZYN8t7nwX3GOBLRw==", + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", + "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", "dev": true, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-haste-map": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-27.5.1.tgz", - "integrity": "sha512-7GgkZ4Fw4NFbMSDSpZwXeBiIbx+t/46nJ2QitkOjvwPYyZmqttu2TDSimMHP1EkPOi4xUZAN1doE5Vd25H4Jng==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", + "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", - "@types/graceful-fs": "^4.1.2", + "@jest/types": "^29.6.3", + "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", - "jest-regex-util": "^27.5.1", - "jest-serializer": "^27.5.1", - "jest-util": "^27.5.1", - "jest-worker": "^27.5.1", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", "micromatch": "^4.0.4", - "walker": "^1.0.7" + "walker": "^1.0.8" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, - "node_modules/jest-jasmine2": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-27.5.1.tgz", - "integrity": "sha512-jtq7VVyG8SqAorDpApwiJJImd0V2wv1xzdheGHRGyuT7gZm6gG47QEskOlzsN1PG/6WNaCo5pmwMHDf3AkG2pQ==", - "dev": true, - "dependencies": { - "@jest/environment": "^27.5.1", - "@jest/source-map": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "expect": "^27.5.1", - "is-generator-fn": "^2.0.0", - "jest-each": "^27.5.1", - "jest-matcher-utils": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-runtime": "^27.5.1", - "jest-snapshot": "^27.5.1", - "jest-util": "^27.5.1", - "pretty-format": "^27.5.1", - "throat": "^6.0.1" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, "node_modules/jest-leak-detector": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-27.5.1.tgz", - "integrity": "sha512-POXfWAMvfU6WMUXftV4HolnJfnPOGEu10fscNCA76KBpRRhcMN2c8d3iT2pxQS3HLbA+5X4sOUPzYO2NUyIlHQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", + "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", "dev": true, "dependencies": { - "jest-get-type": "^27.5.1", - "pretty-format": "^27.5.1" + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-matcher-utils": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-27.5.1.tgz", - "integrity": "sha512-z2uTx/T6LBaCoNWNFWwChLBKYxTMcGBRjAt+2SbP929/Fflb9aa5LGma654Rz8z9HLxsrUaYzxE9T/EFIL/PAw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", + "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", "dev": true, "dependencies": { "chalk": "^4.0.0", - "jest-diff": "^27.5.1", - "jest-get-type": "^27.5.1", - "pretty-format": "^27.5.1" + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-message-util": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-27.5.1.tgz", - "integrity": "sha512-rMyFe1+jnyAAf+NHwTclDz0eAaLkVDdKVHHBFWsBWHnnh5YeJMNWWsv7AbFYXfK3oTqvL7VTWkhNLu1jX24D+g==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", + "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", "dev": true, "dependencies": { "@babel/code-frame": "^7.12.13", - "@jest/types": "^27.5.1", + "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", - "pretty-format": "^27.5.1", + "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, - "node_modules/jest-message-util/node_modules/@babel/code-frame": { - "version": "7.15.8", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.15.8.tgz", - "integrity": "sha512-2IAnmn8zbvC/jKYhq5Ki9I+DwjlrtMPUCH/CpHvqI4dNnlwHwsxoIhlc8WcYY5LSYknXQtAlFYuHfqAFCvQ4Wg==", - "dev": true, - "dependencies": { - "@babel/highlight": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/jest-message-util/node_modules/@babel/helper-validator-identifier": { - "version": "7.15.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz", - "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/jest-message-util/node_modules/@babel/highlight": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", - "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", - "dev": true, - "dependencies": { - "@babel/helper-validator-identifier": "^7.14.5", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/jest-message-util/node_modules/@babel/highlight/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/jest-message-util/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/jest-message-util/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/jest-message-util/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true - }, - "node_modules/jest-message-util/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/jest-message-util/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/jest-message-util/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-mock": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-27.5.1.tgz", - "integrity": "sha512-K4jKbY1d4ENhbrG2zuPWaQBvDly+iZ2yAW+T1fATN78hc0sInwn7wZB8XtlNnvHug5RMwV897Xm4LqmPM4e2Og==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", + "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", - "@types/node": "*" + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-util": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-pnp-resolver": { @@ -5823,167 +5905,150 @@ } }, "node_modules/jest-regex-util": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-27.5.1.tgz", - "integrity": "sha512-4bfKq2zie+x16okqDXjXn9ql2B0dScQu+vcwe4TvFVhkVyuWLqpZrZtXxLLWoXYgn0E87I6r6GRYHF7wFZBUvg==", + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", + "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", "dev": true, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-resolve": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-27.5.1.tgz", - "integrity": "sha512-FFDy8/9E6CV83IMbDpcjOhumAQPDyETnU2KZ1O98DwTnz8AOBsW/Xv3GySr1mOZdItLR+zDZ7I/UdTFbgSOVCw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", + "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", - "jest-haste-map": "^27.5.1", + "jest-haste-map": "^29.7.0", "jest-pnp-resolver": "^1.2.2", - "jest-util": "^27.5.1", - "jest-validate": "^27.5.1", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", "resolve": "^1.20.0", - "resolve.exports": "^1.1.0", + "resolve.exports": "^2.0.0", "slash": "^3.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-resolve-dependencies": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-27.5.1.tgz", - "integrity": "sha512-QQOOdY4PE39iawDn5rzbIePNigfe5B9Z91GDD1ae/xNDlu9kaat8QQ5EKnNmVWPV54hUdxCVwwj6YMgR2O7IOg==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", + "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-snapshot": "^27.5.1" + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-runner": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-27.5.1.tgz", - "integrity": "sha512-g4NPsM4mFCOwFKXO4p/H/kWGdJp9V8kURY2lX8Me2drgXqG7rrZAx5kv+5H7wtt/cdFIjhqYx1HrlqWHaOvDaQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", + "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", "dev": true, "dependencies": { - "@jest/console": "^27.5.1", - "@jest/environment": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/console": "^29.7.0", + "@jest/environment": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", - "emittery": "^0.8.1", + "emittery": "^0.13.1", "graceful-fs": "^4.2.9", - "jest-docblock": "^27.5.1", - "jest-environment-jsdom": "^27.5.1", - "jest-environment-node": "^27.5.1", - "jest-haste-map": "^27.5.1", - "jest-leak-detector": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-runtime": "^27.5.1", - "jest-util": "^27.5.1", - "jest-worker": "^27.5.1", - "source-map-support": "^0.5.6", - "throat": "^6.0.1" + "jest-docblock": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-leak-detector": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-resolve": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-util": "^29.7.0", + "jest-watcher": "^29.7.0", + "jest-worker": "^29.7.0", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-runtime": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-27.5.1.tgz", - "integrity": "sha512-o7gxw3Gf+H2IGt8fv0RiyE1+r83FJBRruoA+FXrlHw6xEyBsU8ugA6IPfTdVyA0w8HClpbK+DGJxH59UrNMx8A==", - "dev": true, - "dependencies": { - "@jest/environment": "^27.5.1", - "@jest/fake-timers": "^27.5.1", - "@jest/globals": "^27.5.1", - "@jest/source-map": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", + "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", + "dev": true, + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/globals": "^29.7.0", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", "chalk": "^4.0.0", "cjs-module-lexer": "^1.0.0", "collect-v8-coverage": "^1.0.0", - "execa": "^5.0.0", "glob": "^7.1.3", "graceful-fs": "^4.2.9", - "jest-haste-map": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-mock": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-snapshot": "^27.5.1", - "jest-util": "^27.5.1", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", "slash": "^3.0.0", "strip-bom": "^4.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, - "node_modules/jest-serializer": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-serializer/-/jest-serializer-27.5.1.tgz", - "integrity": "sha512-jZCyo6iIxO1aqUxpuBlwTDMkzOAJS4a3eYz3YzgxxVQFwLeSA7Jfq5cbqCY+JLvTDrWirgusI/0KwxKMgrdf7w==", - "dev": true, - "dependencies": { - "@types/node": "*", - "graceful-fs": "^4.2.9" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-snapshot": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-27.5.1.tgz", - "integrity": "sha512-yYykXI5a0I31xX67mgeLw1DZ0bJB+gpq5IpSuCAoyDi0+BhgU/RIrL+RTzDmkNTchvDFWKP8lp+w/42Z3us5sA==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", + "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", "dev": true, "dependencies": { - "@babel/core": "^7.7.2", + "@babel/core": "^7.11.6", "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/traverse": "^7.7.2", - "@babel/types": "^7.0.0", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/babel__traverse": "^7.0.4", - "@types/prettier": "^2.1.5", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0", "chalk": "^4.0.0", - "expect": "^27.5.1", + "expect": "^29.7.0", "graceful-fs": "^4.2.9", - "jest-diff": "^27.5.1", - "jest-get-type": "^27.5.1", - "jest-haste-map": "^27.5.1", - "jest-matcher-utils": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-util": "^27.5.1", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", "natural-compare": "^1.4.0", - "pretty-format": "^27.5.1", - "semver": "^7.3.2" + "pretty-format": "^29.7.0", + "semver": "^7.5.3" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-util": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-27.5.1.tgz", - "integrity": "sha512-Kv2o/8jNvX1MQ0KGtw480E/w4fBCDOnH6+6DmeKi6LZUIlKA5kwY0YNdlzaWTiVgxqAqik11QyxDOKk543aKXw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", + "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", + "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "ci-info": "^3.2.0", @@ -5991,24 +6056,24 @@ "picomatch": "^2.2.3" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-validate": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-27.5.1.tgz", - "integrity": "sha512-thkNli0LYTmOI1tDB3FI1S1RTp/Bqyd9pTarJwL87OIBFuqEb5Apv5EaApEudYg4g86e3CT6kM0RowkhtEnCBQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", + "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", "dev": true, "dependencies": { - "@jest/types": "^27.5.1", + "@jest/types": "^29.6.3", "camelcase": "^6.2.0", "chalk": "^4.0.0", - "jest-get-type": "^27.5.1", + "jest-get-type": "^29.6.3", "leven": "^3.1.0", - "pretty-format": "^27.5.1" + "pretty-format": "^29.7.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-validate/node_modules/camelcase": { @@ -6024,35 +6089,37 @@ } }, "node_modules/jest-watcher": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-27.5.1.tgz", - "integrity": "sha512-z676SuD6Z8o8qbmEGhoEUFOM1+jfEiL3DXHK/xgEiG2EyNYfFG60jluWcupY6dATjfEsKQuibReS1djInQnoVw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", + "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", "dev": true, "dependencies": { - "@jest/test-result": "^27.5.1", - "@jest/types": "^27.5.1", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", "@types/node": "*", "ansi-escapes": "^4.2.1", "chalk": "^4.0.0", - "jest-util": "^27.5.1", + "emittery": "^0.13.1", + "jest-util": "^29.7.0", "string-length": "^4.0.1" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-worker": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", - "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", + "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", "dev": true, "dependencies": { "@types/node": "*", + "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" }, "engines": { - "node": ">= 10.13.0" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, "node_modules/jest-worker/node_modules/supports-color": { @@ -6094,64 +6161,6 @@ "js-yaml": "bin/js-yaml.js" } }, - "node_modules/jsdom": { - "version": "16.7.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-16.7.0.tgz", - "integrity": "sha512-u9Smc2G1USStM+s/x1ru5Sxrl6mPYCbByG1U/hUmqaVsm4tbNyS7CicOSRyuGQYZhTu0h84qkZZQ/I+dzizSVw==", - "dev": true, - "dependencies": { - "abab": "^2.0.5", - "acorn": "^8.2.4", - "acorn-globals": "^6.0.0", - "cssom": "^0.4.4", - "cssstyle": "^2.3.0", - "data-urls": "^2.0.0", - "decimal.js": "^10.2.1", - "domexception": "^2.0.1", - "escodegen": "^2.0.0", - "form-data": "^3.0.0", - "html-encoding-sniffer": "^2.0.1", - "http-proxy-agent": "^4.0.1", - "https-proxy-agent": "^5.0.0", - "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.0", - "parse5": "6.0.1", - "saxes": "^5.0.1", - "symbol-tree": "^3.2.4", - "tough-cookie": "^4.0.0", - "w3c-hr-time": "^1.0.2", - "w3c-xmlserializer": "^2.0.0", - "webidl-conversions": "^6.1.0", - "whatwg-encoding": "^1.0.5", - "whatwg-mimetype": "^2.3.0", - "whatwg-url": "^8.5.0", - "ws": "^7.4.6", - "xml-name-validator": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "canvas": "^2.5.0" - }, - "peerDependenciesMeta": { - "canvas": { - "optional": true - } - } - }, - "node_modules/jsdom/node_modules/acorn": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz", - "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", - "dev": true, - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", @@ -6164,18 +6173,6 @@ "node": ">=4" } }, - "node_modules/json-buffer": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.0.tgz", - "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=", - "dev": true - }, - "node_modules/json-parse-better-errors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", - "dev": true - }, "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", @@ -6198,9 +6195,9 @@ "dev": true }, "node_modules/json-server": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/json-server/-/json-server-0.17.0.tgz", - "integrity": "sha512-+e/nW0mf666j1yTK+5dRx7hgxq5wJTkc5QhTYa/cBfD6vLlQWHfB4l8XKPgzeO55A8Hqm38g44OtZ5SooXi6MQ==", + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/json-server/-/json-server-0.17.4.tgz", + "integrity": "sha512-bGBb0WtFuAKbgI7JV3A864irWnMZSvBYRJbohaOuatHwKSRFUfqtQlrYMrB6WbalXy/cJabyjlb7JkHli6dYjQ==", "dev": true, "dependencies": { "body-parser": "^1.19.0", @@ -6221,7 +6218,6 @@ "please-upgrade-node": "^3.2.0", "pluralize": "^8.0.0", "server-destroy": "^1.0.1", - "update-notifier": "^5.1.0", "yargs": "^17.0.1" }, "bin": { @@ -6231,40 +6227,6 @@ "node": ">=12" } }, - "node_modules/json-server/node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/json-server/node_modules/yargs": { - "version": "17.2.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.2.1.tgz", - "integrity": "sha512-XfR8du6ua4K6uLGm5S6fA+FIJom/MdJcFNVY8geLlp2v8GYbOXD4EB1tPNZsRn4vBzKGMgb5DRZMeWuFc2GO8Q==", - "dev": true, - "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - }, - "engines": { - "node": ">=12" - } - }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", @@ -6272,13 +6234,10 @@ "dev": true }, "node_modules/json5": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz", - "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", "dev": true, - "dependencies": { - "minimist": "^1.2.5" - }, "bin": { "json5": "lib/cli.js" }, @@ -6286,13 +6245,17 @@ "node": ">=6" } }, - "node_modules/keyv": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", - "integrity": "sha512-9ykJ/46SN/9KPM/sichzQ7OvXyGDYKGTaDlKMGCAlg2UK8KRy4jb0d8sFc+0Tt0YYnThq8X2RZgCg74RPxgcVA==", + "node_modules/jsx-ast-utils": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.3.tgz", + "integrity": "sha512-fYQHZTZ8jSfmWZ0iyzfwiU4WDX4HpHbMCZ3gPlWYiCl3BoeOTsqKBqnTVfH2rYT7eP5c3sVbeSPHnnJOaTrWiw==", "dev": true, "dependencies": { - "json-buffer": "3.0.0" + "array-includes": "^3.1.5", + "object.assign": "^4.1.3" + }, + "engines": { + "node": ">=4.0" } }, "node_modules/kleur": { @@ -6304,16 +6267,19 @@ "node": ">=6" } }, - "node_modules/latest-version": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-5.1.0.tgz", - "integrity": "sha512-weT+r0kTkRQdCdYCNtkMwWXQTMEswKrFBkm4ckQOMVhhqhIMI1UT2hMj+1iigIhgSZm5gTmrRXBNoGUgaTY1xA==", + "node_modules/language-subtag-registry": { + "version": "0.3.22", + "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.22.tgz", + "integrity": "sha512-tN0MCzyWnoz/4nHS6uxdlFWoUZT7ABptwKPQ52Ea7URk6vll88bWBVhodtnlfEuCcKWNGoc+uGbw1cwa9IKh/w==", + "dev": true + }, + "node_modules/language-tags": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.5.tgz", + "integrity": "sha512-qJhlO9cGXi6hBGKoxEG/sKZDAHD5Hnu9Hs4WbOY3pCWXDhw0N8x1NenNzm2EnNLkLkk7J2SdxAkDSbb6ftT+UQ==", "dev": true, "dependencies": { - "package-json": "^6.3.0" - }, - "engines": { - "node": ">=8" + "language-subtag-registry": "~0.3.2" } }, "node_modules/leven": { @@ -6338,317 +6304,625 @@ "node": ">= 0.8.0" } }, + "node_modules/lilconfig": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.0.0.tgz", + "integrity": "sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g==", + "dev": true, + "engines": { + "node": ">=14" + } + }, "node_modules/lines-and-columns": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", - "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, "node_modules/lint-staged": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-11.1.1.tgz", - "integrity": "sha512-eTNGe6i78PSUUH2BZi1gZmGmNfb8IeN4z2OzMYxSZ1qnP1WXKn1E7D+OHwLbRDm/wQINnzIj0bsKJ6lLVSuZiQ==", - "dev": true, - "dependencies": { - "chalk": "^4.1.1", - "cli-truncate": "^2.1.0", - "commander": "^7.2.0", - "cosmiconfig": "^7.0.0", - "debug": "^4.3.1", - "dedent": "^0.7.0", - "enquirer": "^2.3.6", - "execa": "^5.0.0", - "listr2": "^3.8.2", - "log-symbols": "^4.1.0", - "micromatch": "^4.0.4", - "normalize-path": "^3.0.0", - "please-upgrade-node": "^3.2.0", - "string-argv": "0.3.1", - "stringify-object": "^3.3.0" + "version": "15.2.2", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.2.2.tgz", + "integrity": "sha512-TiTt93OPh1OZOsb5B7k96A/ATl2AjIZo+vnzFZ6oHK5FuTk63ByDtxGQpHm+kFETjEWqgkF95M8FRXKR/LEBcw==", + "dev": true, + "dependencies": { + "chalk": "5.3.0", + "commander": "11.1.0", + "debug": "4.3.4", + "execa": "8.0.1", + "lilconfig": "3.0.0", + "listr2": "8.0.1", + "micromatch": "4.0.5", + "pidtree": "0.6.0", + "string-argv": "0.3.2", + "yaml": "2.3.4" }, "bin": { "lint-staged": "bin/lint-staged.js" }, + "engines": { + "node": ">=18.12.0" + }, "funding": { "url": "https://opencollective.com/lint-staged" } }, + "node_modules/lint-staged/node_modules/chalk": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", + "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", + "dev": true, + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, "node_modules/lint-staged/node_modules/commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", "dev": true, "engines": { - "node": ">= 10" + "node": ">=16" } }, - "node_modules/listr2": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/listr2/-/listr2-3.10.0.tgz", - "integrity": "sha512-eP40ZHihu70sSmqFNbNy2NL1YwImmlMmPh9WO5sLmPDleurMHt3n+SwEWNu2kzKScexZnkyFtc1VI0z/TGlmpw==", + "node_modules/lint-staged/node_modules/execa": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", + "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", "dev": true, "dependencies": { - "cli-truncate": "^2.1.0", - "colorette": "^1.2.2", - "log-update": "^4.0.0", - "p-map": "^4.0.0", - "rxjs": "^6.6.7", - "through": "^2.3.8", - "wrap-ansi": "^7.0.0" + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" }, "engines": { - "node": ">=10.0.0" + "node": ">=16.17" }, - "peerDependencies": { - "enquirer": ">= 2.3.0 < 3" + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, - "node_modules/load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", + "node_modules/lint-staged/node_modules/get-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", + "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", "dev": true, - "dependencies": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" - }, "engines": { - "node": ">=4" + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/load-json-file/node_modules/strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "node_modules/lint-staged/node_modules/human-signals": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", + "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", "dev": true, "engines": { - "node": ">=4" + "node": ">=16.17.0" } }, - "node_modules/locate-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "node_modules/lint-staged/node_modules/is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", "dev": true, - "dependencies": { - "p-locate": "^2.0.0", - "path-exists": "^3.0.0" - }, "engines": { - "node": ">=4" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true - }, - "node_modules/lodash-id": { - "version": "0.14.1", - "resolved": "https://registry.npmjs.org/lodash-id/-/lodash-id-0.14.1.tgz", - "integrity": "sha512-ikQPBTiq/d5m6dfKQlFdIXFzvThPi2Be9/AHxktOnDSfSxE1j9ICbBT5Elk1ke7HSTgM38LHTpmJovo9/klnLg==", + "node_modules/lint-staged/node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", "dev": true, "engines": { - "node": ">= 4" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lodash.clonedeep": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", - "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", - "dev": true - }, - "node_modules/lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=", - "dev": true - }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true - }, - "node_modules/lodash.truncate": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", - "dev": true - }, - "node_modules/log-symbols": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", - "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "node_modules/lint-staged/node_modules/npm-run-path": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.1.0.tgz", + "integrity": "sha512-sJOdmRGrY2sjNTRMbSvluQqg+8X7ZK61yvzBEIDhz4f8z1TZFYABsqjjCBd/0PUNE9M6QDgHJXQkGUEm7Q+l9Q==", "dev": true, "dependencies": { - "chalk": "^4.1.0", - "is-unicode-supported": "^0.1.0" + "path-key": "^4.0.0" }, "engines": { - "node": ">=10" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/log-update": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/log-update/-/log-update-4.0.0.tgz", - "integrity": "sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg==", + "node_modules/lint-staged/node_modules/onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", "dev": true, "dependencies": { - "ansi-escapes": "^4.3.0", - "cli-cursor": "^3.1.0", - "slice-ansi": "^4.0.0", - "wrap-ansi": "^6.2.0" + "mimic-fn": "^4.0.0" }, "engines": { - "node": ">=10" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/log-update/node_modules/wrap-ansi": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "node_modules/lint-staged/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lowdb": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/lowdb/-/lowdb-1.0.0.tgz", - "integrity": "sha512-2+x8esE/Wb9SQ1F9IHaYWfsC9FIecLOPrK4g17FGEayjUWH172H6nwicRovGvSE2CPZouc2MCIqCI7h9d+GftQ==", + "node_modules/lint-staged/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", "dev": true, - "dependencies": { - "graceful-fs": "^4.1.3", - "is-promise": "^2.1.0", - "lodash": "4", - "pify": "^3.0.0", - "steno": "^0.4.1" - }, "engines": { - "node": ">=4" + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/lowercase-keys": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", - "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==", + "node_modules/lint-staged/node_modules/strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", "dev": true, "engines": { - "node": ">=0.10.0" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "node_modules/listr2": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-8.0.1.tgz", + "integrity": "sha512-ovJXBXkKGfq+CwmKTjluEqFi3p4h8xvkxGQQAQan22YCgef4KZ1mKGjzfGh6PL6AW5Csw0QiQPNuQyH+6Xk3hA==", "dev": true, "dependencies": { - "yallist": "^4.0.0" + "cli-truncate": "^4.0.0", + "colorette": "^2.0.20", + "eventemitter3": "^5.0.1", + "log-update": "^6.0.0", + "rfdc": "^1.3.0", + "wrap-ansi": "^9.0.0" }, "engines": { - "node": ">=10" + "node": ">=18.0.0" } }, - "node_modules/make-dir": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "node_modules/listr2/node_modules/ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", "dev": true, - "dependencies": { - "semver": "^6.0.0" - }, "engines": { - "node": ">=8" + "node": ">=12" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, - "node_modules/make-dir/node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "node_modules/listr2/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", "dev": true, - "bin": { - "semver": "bin/semver.js" + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "node_modules/listr2/node_modules/emoji-regex": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.3.0.tgz", + "integrity": "sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==", "dev": true }, - "node_modules/makeerror": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.11.tgz", - "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", + "node_modules/listr2/node_modules/string-width": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.1.0.tgz", + "integrity": "sha512-SEIJCWiX7Kg4c129n48aDRwLbFb2LJmXXFrWBG4NGaRtMQ3myKPKbwrD1BKqQn74oCoNMBVrfDEr5M9YxCsrkw==", "dev": true, "dependencies": { - "tmpl": "1.0.x" + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "node_modules/listr2/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", "dev": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, "engines": { - "node": ">= 0.6" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, - "node_modules/merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", - "dev": true - }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "node_modules/listr2/node_modules/wrap-ansi": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.0.tgz", + "integrity": "sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==", "dev": true, + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, "engines": { - "node": ">= 8" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/method-override": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/method-override/-/method-override-3.0.0.tgz", - "integrity": "sha512-IJ2NNN/mSl9w3kzWB92rcdHpz+HjkxhDJWNDBqSlas+zQdP8wBiJzITPg08M/k2uVvMow7Sk41atndNtt/PHSA==", + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, "dependencies": { - "debug": "3.1.0", - "methods": "~1.1.2", - "parseurl": "~1.3.2", - "vary": "~1.1.2" + "p-locate": "^5.0.0" }, "engines": { - "node": ">= 0.10" - } - }, - "node_modules/method-override/node_modules/debug": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true + }, + "node_modules/lodash-id": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/lodash-id/-/lodash-id-0.14.1.tgz", + "integrity": "sha512-ikQPBTiq/d5m6dfKQlFdIXFzvThPi2Be9/AHxktOnDSfSxE1j9ICbBT5Elk1ke7HSTgM38LHTpmJovo9/klnLg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "dev": true + }, + "node_modules/lodash.kebabcase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.kebabcase/-/lodash.kebabcase-4.1.1.tgz", + "integrity": "sha512-N8XRTIMMqqDgSy4VLKPnJ/+hpGZN+PHQiJnSenYqPaVV/NCqEogTnAdZLQiGKhxX+JCs8waWq2t1XHWKOmlY8g==", + "dev": true + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=", + "dev": true + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", + "dev": true + }, + "node_modules/lodash.upperfirst": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/lodash.upperfirst/-/lodash.upperfirst-4.3.1.tgz", + "integrity": "sha512-sReKOYJIJf74dhJONhU4e0/shzi1trVbSWDOhKYE5XV2O+H7Sb2Dihwuc7xWxVl+DgFPyTqIN3zMfT9cq5iWDg==", + "dev": true + }, + "node_modules/log-update": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.0.0.tgz", + "integrity": "sha512-niTvB4gqvtof056rRIrTZvjNYE4rCUzO6X/X+kYjd7WFxXeJ0NwEFnRxX6ehkvv3jTwrXnNdtAak5XYZuIyPFw==", + "dev": true, + "dependencies": { + "ansi-escapes": "^6.2.0", + "cli-cursor": "^4.0.0", + "slice-ansi": "^7.0.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-escapes": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-6.2.0.tgz", + "integrity": "sha512-kzRaCqXnpzWs+3z5ABPQiVke+iq0KXkHo8xiWV4RPTi5Yli0l97BEQuhXV1s7+aSU/fu1kUuxgS4MsQ0fRuygw==", + "dev": true, + "dependencies": { + "type-fest": "^3.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/log-update/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/log-update/node_modules/emoji-regex": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.3.0.tgz", + "integrity": "sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==", + "dev": true + }, + "node_modules/log-update/node_modules/is-fullwidth-code-point": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.0.0.tgz", + "integrity": "sha512-OVa3u9kkBbw7b8Xw5F9P+D/T9X+Z4+JruYVNapTjPYZYUznQ5YfWeFkOj606XYYW8yugTfC8Pj0hYqvi4ryAhA==", + "dev": true, + "dependencies": { + "get-east-asian-width": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/slice-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.0.tgz", + "integrity": "sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg==", + "dev": true, + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/string-width": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.1.0.tgz", + "integrity": "sha512-SEIJCWiX7Kg4c129n48aDRwLbFb2LJmXXFrWBG4NGaRtMQ3myKPKbwrD1BKqQn74oCoNMBVrfDEr5M9YxCsrkw==", + "dev": true, + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/type-fest": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-3.13.1.tgz", + "integrity": "sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g==", + "dev": true, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/wrap-ansi": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.0.tgz", + "integrity": "sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/lowdb": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lowdb/-/lowdb-1.0.0.tgz", + "integrity": "sha512-2+x8esE/Wb9SQ1F9IHaYWfsC9FIecLOPrK4g17FGEayjUWH172H6nwicRovGvSE2CPZouc2MCIqCI7h9d+GftQ==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.1.3", + "is-promise": "^2.1.0", + "lodash": "4", + "pify": "^3.0.0", + "steno": "^0.4.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "node_modules/makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dev": true, + "dependencies": { + "tmpl": "1.0.5" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", + "dev": true + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/method-override": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/method-override/-/method-override-3.0.0.tgz", + "integrity": "sha512-IJ2NNN/mSl9w3kzWB92rcdHpz+HjkxhDJWNDBqSlas+zQdP8wBiJzITPg08M/k2uVvMow7Sk41atndNtt/PHSA==", + "dev": true, + "dependencies": { + "debug": "3.1.0", + "methods": "~1.1.2", + "parseurl": "~1.3.2", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/method-override/node_modules/debug": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", @@ -6673,13 +6947,13 @@ } }, "node_modules/micromatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.4.tgz", - "integrity": "sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", "dev": true, "dependencies": { - "braces": "^3.0.1", - "picomatch": "^2.2.3" + "braces": "^3.0.2", + "picomatch": "^2.3.1" }, "engines": { "node": ">=8.6" @@ -6698,21 +6972,21 @@ } }, "node_modules/mime-db": { - "version": "1.48.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.48.0.tgz", - "integrity": "sha512-FM3QwxV+TnZYQ2aRqhlKBMHxk10lTbMt3bBkMAp54ddrNeVSfcQYOOKuGuy3Ddrm38I04If834fOUSq1yzslJQ==", + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, "engines": { "node": ">= 0.6" } }, "node_modules/mime-types": { - "version": "2.1.31", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.31.tgz", - "integrity": "sha512-XGZnNzm3QvgKxa8dpzyhFTHmpP3l5YNusmne07VUOXxou9CqUqYa/HBy124RqtVh/O2pECas/MOcsDgpilPOPg==", + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "dependencies": { - "mime-db": "1.48.0" + "mime-db": "1.52.0" }, "engines": { "node": ">= 0.6" @@ -6727,19 +7001,10 @@ "node": ">=6" } }, - "node_modules/mimic-response": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", - "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, "dependencies": { "brace-expansion": "^1.1.7" @@ -6784,15 +7049,6 @@ "ms": "2.0.0" } }, - "node_modules/morgan/node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "dev": true, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/morgan/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", @@ -6805,9 +7061,9 @@ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "node_modules/nan": { - "version": "2.15.0", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.15.0.tgz", - "integrity": "sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ==", + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.18.0.tgz", + "integrity": "sha512-W7tfG7vMOGtD30sHoZSSc/JVYiyDPEyQVso/Zz+/uQd0B0L46gtC+pHha5FFMRpil6fm/AoEcRWyOVi4+E/f8w==", "optional": true }, "node_modules/nanoid": { @@ -6829,57 +7085,18 @@ "dev": true }, "node_modules/negotiator": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", - "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==", + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", "dev": true, "engines": { "node": ">= 0.6" } }, - "node_modules/node-fetch": { - "version": "2.6.7", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", - "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/node-fetch/node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=" - }, - "node_modules/node-fetch/node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=" - }, - "node_modules/node-fetch/node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, "node_modules/node-forge": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.0.tgz", - "integrity": "sha512-08ARB91bUi6zNKzVmaj3QO7cr397uiDT2nJ63cHjyNtCTWIgvS47j3eT0WfzUwS9+6Z5YshRaoasFkXCKrIYbA==", - "dev": true, + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz", + "integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==", "engines": { "node": ">= 6.13.0" } @@ -6891,32 +7108,11 @@ "dev": true }, "node_modules/node-releases": { - "version": "1.1.72", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.72.tgz", - "integrity": "sha512-LLUo+PpH3dU6XizX3iVoubUNheF/owjXCZZ5yACDxNnPtgFuludV1ZL3ayK1kVep42Rmm0+R9/Y60NQbZ2bifw==", + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.6.tgz", + "integrity": "sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg==", "dev": true }, - "node_modules/normalize-package-data": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", - "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", - "dev": true, - "dependencies": { - "hosted-git-info": "^2.1.4", - "resolve": "^1.10.0", - "semver": "2 || 3 || 4 || 5", - "validate-npm-package-license": "^3.0.1" - } - }, - "node_modules/normalize-package-data/node_modules/semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true, - "bin": { - "semver": "bin/semver" - } - }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -6926,173 +7122,6 @@ "node": ">=0.10.0" } }, - "node_modules/normalize-url": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-4.5.1.tgz", - "integrity": "sha512-9UZCFRHQdNrfTpGg8+1INIg93B6zE0aXMVFkw1WFwvO4SlZywU6aLg5Of0Ap/PgcbSw4LNxvMWXMeugwMCX0AA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/npm": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/npm/-/npm-8.18.0.tgz", - "integrity": "sha512-G07/yKvNUwhwxYhk8BxcuDPB/4s+y755i6CnH3lf9LQBHP5siUx66WbuNGWEnN3xaBER4+IR3OWApKX7eBO5Dw==", - "bundleDependencies": [ - "@isaacs/string-locale-compare", - "@npmcli/arborist", - "@npmcli/ci-detect", - "@npmcli/config", - "@npmcli/fs", - "@npmcli/map-workspaces", - "@npmcli/package-json", - "@npmcli/run-script", - "abbrev", - "archy", - "cacache", - "chalk", - "chownr", - "cli-columns", - "cli-table3", - "columnify", - "fastest-levenshtein", - "glob", - "graceful-fs", - "hosted-git-info", - "ini", - "init-package-json", - "is-cidr", - "json-parse-even-better-errors", - "libnpmaccess", - "libnpmdiff", - "libnpmexec", - "libnpmfund", - "libnpmhook", - "libnpmorg", - "libnpmpack", - "libnpmpublish", - "libnpmsearch", - "libnpmteam", - "libnpmversion", - "make-fetch-happen", - "minipass", - "minipass-pipeline", - "mkdirp", - "mkdirp-infer-owner", - "ms", - "node-gyp", - "nopt", - "npm-audit-report", - "npm-install-checks", - "npm-package-arg", - "npm-pick-manifest", - "npm-profile", - "npm-registry-fetch", - "npm-user-validate", - "npmlog", - "opener", - "p-map", - "pacote", - "parse-conflict-json", - "proc-log", - "qrcode-terminal", - "read", - "read-package-json", - "read-package-json-fast", - "readdir-scoped-modules", - "rimraf", - "semver", - "ssri", - "tar", - "text-table", - "tiny-relative-date", - "treeverse", - "validate-npm-package-name", - "which", - "write-file-atomic" - ], - "dependencies": { - "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/arborist": "^5.0.4", - "@npmcli/ci-detect": "^2.0.0", - "@npmcli/config": "^4.2.1", - "@npmcli/fs": "^2.1.0", - "@npmcli/map-workspaces": "^2.0.3", - "@npmcli/package-json": "^2.0.0", - "@npmcli/run-script": "^4.2.1", - "abbrev": "~1.1.1", - "archy": "~1.0.0", - "cacache": "^16.1.1", - "chalk": "^4.1.2", - "chownr": "^2.0.0", - "cli-columns": "^4.0.0", - "cli-table3": "^0.6.2", - "columnify": "^1.6.0", - "fastest-levenshtein": "^1.0.12", - "glob": "^8.0.1", - "graceful-fs": "^4.2.10", - "hosted-git-info": "^5.0.0", - "ini": "^3.0.0", - "init-package-json": "^3.0.2", - "is-cidr": "^4.0.2", - "json-parse-even-better-errors": "^2.3.1", - "libnpmaccess": "^6.0.2", - "libnpmdiff": "^4.0.2", - "libnpmexec": "^4.0.2", - "libnpmfund": "^3.0.1", - "libnpmhook": "^8.0.2", - "libnpmorg": "^4.0.2", - "libnpmpack": "^4.0.2", - "libnpmpublish": "^6.0.2", - "libnpmsearch": "^5.0.2", - "libnpmteam": "^4.0.2", - "libnpmversion": "^3.0.1", - "make-fetch-happen": "^10.2.0", - "minipass": "^3.1.6", - "minipass-pipeline": "^1.2.4", - "mkdirp": "^1.0.4", - "mkdirp-infer-owner": "^2.0.0", - "ms": "^2.1.2", - "node-gyp": "^9.1.0", - "nopt": "^6.0.0", - "npm-audit-report": "^3.0.0", - "npm-install-checks": "^5.0.0", - "npm-package-arg": "^9.1.0", - "npm-pick-manifest": "^7.0.1", - "npm-profile": "^6.2.0", - "npm-registry-fetch": "^13.3.1", - "npm-user-validate": "^1.0.1", - "npmlog": "^6.0.2", - "opener": "^1.5.2", - "p-map": "^4.0.0", - "pacote": "^13.6.2", - "parse-conflict-json": "^2.0.2", - "proc-log": "^2.0.1", - "qrcode-terminal": "^0.12.0", - "read": "~1.0.7", - "read-package-json": "^5.0.1", - "read-package-json-fast": "^2.0.3", - "readdir-scoped-modules": "^1.1.0", - "rimraf": "^3.0.2", - "semver": "^7.3.7", - "ssri": "^9.0.1", - "tar": "^6.1.11", - "text-table": "~0.2.0", - "tiny-relative-date": "^1.3.0", - "treeverse": "^2.0.0", - "validate-npm-package-name": "^4.0.0", - "which": "^2.0.2", - "write-file-atomic": "^4.0.1" - }, - "bin": { - "npm": "bin/npm-cli.js", - "npx": "bin/npx-cli.js" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16" - } - }, "node_modules/npm-run-path": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", @@ -7105,2101 +7134,1886 @@ "node": ">=8" } }, - "node_modules/npm/node_modules/@colors/colors": { - "version": "1.5.0", - "inBundle": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.1.90" - } - }, - "node_modules/npm/node_modules/@gar/promisify": { - "version": "1.1.3", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/@isaacs/string-locale-compare": { - "version": "1.1.0", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/@npmcli/arborist": { - "version": "5.6.0", - "inBundle": true, - "license": "ISC", - "dependencies": { - "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/installed-package-contents": "^1.0.7", - "@npmcli/map-workspaces": "^2.0.3", - "@npmcli/metavuln-calculator": "^3.0.1", - "@npmcli/move-file": "^2.0.0", - "@npmcli/name-from-folder": "^1.0.1", - "@npmcli/node-gyp": "^2.0.0", - "@npmcli/package-json": "^2.0.0", - "@npmcli/query": "^1.1.1", - "@npmcli/run-script": "^4.1.3", - "bin-links": "^3.0.0", - "cacache": "^16.0.6", - "common-ancestor-path": "^1.0.1", - "json-parse-even-better-errors": "^2.3.1", - "json-stringify-nice": "^1.1.4", - "minimatch": "^5.1.0", - "mkdirp": "^1.0.4", - "mkdirp-infer-owner": "^2.0.0", - "nopt": "^6.0.0", - "npm-install-checks": "^5.0.0", - "npm-package-arg": "^9.0.0", - "npm-pick-manifest": "^7.0.0", - "npm-registry-fetch": "^13.0.0", - "npmlog": "^6.0.2", - "pacote": "^13.6.1", - "parse-conflict-json": "^2.0.1", - "proc-log": "^2.0.0", - "promise-all-reject-late": "^1.0.0", - "promise-call-limit": "^1.0.1", - "read-package-json-fast": "^2.0.2", - "readdir-scoped-modules": "^1.1.0", - "rimraf": "^3.0.2", - "semver": "^7.3.7", - "ssri": "^9.0.0", - "treeverse": "^2.0.0", - "walk-up-path": "^1.0.0" - }, - "bin": { - "arborist": "bin/index.js" - }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=0.10.0" } }, - "node_modules/npm/node_modules/@npmcli/ci-detect": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC", - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16" + "node_modules/object-inspect": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", + "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/@npmcli/config": { - "version": "4.2.1", - "inBundle": true, - "license": "ISC", + "node_modules/object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "dev": true, "dependencies": { - "@npmcli/map-workspaces": "^2.0.2", - "ini": "^3.0.0", - "mkdirp-infer-owner": "^2.0.0", - "nopt": "^6.0.0", - "proc-log": "^2.0.0", - "read-package-json-fast": "^2.0.3", - "semver": "^7.3.5", - "walk-up-path": "^1.0.0" + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/@npmcli/disparity-colors": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC", - "dependencies": { - "ansi-styles": "^4.3.0" - }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.4" } }, - "node_modules/npm/node_modules/@npmcli/fs": { - "version": "2.1.2", - "inBundle": true, - "license": "ISC", + "node_modules/object.assign": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "dev": true, "dependencies": { - "@gar/promisify": "^1.1.3", - "semver": "^7.3.5" + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/@npmcli/git": { - "version": "3.0.2", - "inBundle": true, - "license": "ISC", + "node_modules/object.entries": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.6.tgz", + "integrity": "sha512-leTPzo4Zvg3pmbQ3rDK69Rl8GQvIqMWubrkxONG9/ojtFE2rD9fjMKfSI5BxW3osRH1m6VdzmqK8oAY9aT4x5w==", + "dev": true, "dependencies": { - "@npmcli/promise-spawn": "^3.0.0", - "lru-cache": "^7.4.4", - "mkdirp": "^1.0.4", - "npm-pick-manifest": "^7.0.0", - "proc-log": "^2.0.0", - "promise-inflight": "^1.0.1", - "promise-retry": "^2.0.1", - "semver": "^7.3.5", - "which": "^2.0.2" + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.4" } }, - "node_modules/npm/node_modules/@npmcli/installed-package-contents": { - "version": "1.0.7", - "inBundle": true, - "license": "ISC", + "node_modules/object.fromentries": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.6.tgz", + "integrity": "sha512-VciD13dswC4j1Xt5394WR4MzmAQmlgN72phd/riNp9vtD7tp4QQWJ0R4wvclXcafgcYK8veHRed2W6XeGBvcfg==", + "dev": true, "dependencies": { - "npm-bundled": "^1.1.1", - "npm-normalize-package-bin": "^1.0.1" - }, - "bin": { - "installed-package-contents": "index.js" + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" }, "engines": { - "node": ">= 10" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/@npmcli/map-workspaces": { - "version": "2.0.4", - "inBundle": true, - "license": "ISC", + "node_modules/object.values": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.6.tgz", + "integrity": "sha512-FVVTkD1vENCsAcwNs9k6jea2uHC/X0+JcjG8YA60FN5CMaJmG95wT9jek/xX9nornqGRrBkKtzuAu2wuHpKqvw==", + "dev": true, "dependencies": { - "@npmcli/name-from-folder": "^1.0.1", - "glob": "^8.0.1", - "minimatch": "^5.0.1", - "read-package-json-fast": "^2.0.3" + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/@npmcli/metavuln-calculator": { - "version": "3.1.1", - "inBundle": true, - "license": "ISC", + "node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dev": true, "dependencies": { - "cacache": "^16.0.0", - "json-parse-even-better-errors": "^2.3.1", - "pacote": "^13.0.3", - "semver": "^7.3.5" + "ee-first": "1.1.1" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.8" } }, - "node_modules/npm/node_modules/@npmcli/move-file": { - "version": "2.0.1", - "inBundle": true, - "license": "MIT", - "dependencies": { - "mkdirp": "^1.0.4", - "rimraf": "^3.0.2" - }, + "node_modules/on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.8" } }, - "node_modules/npm/node_modules/@npmcli/name-from-folder": { - "version": "1.0.1", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/@npmcli/node-gyp": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC", - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dependencies": { + "wrappy": "1" } }, - "node_modules/npm/node_modules/@npmcli/package-json": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, "dependencies": { - "json-parse-even-better-errors": "^2.3.1" + "mimic-fn": "^2.1.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/@npmcli/promise-spawn": { - "version": "3.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/optionator": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.3.tgz", + "integrity": "sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==", + "dev": true, "dependencies": { - "infer-owner": "^1.0.4" + "@aashutoshrathi/word-wrap": "^1.2.3", + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.8.0" } }, - "node_modules/npm/node_modules/@npmcli/query": { - "version": "1.1.1", - "inBundle": true, - "license": "ISC", + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, "dependencies": { - "npm-package-arg": "^9.1.0", - "postcss-selector-parser": "^6.0.10", - "semver": "^7.3.7" + "yocto-queue": "^0.1.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/@npmcli/run-script": { - "version": "4.2.1", - "inBundle": true, - "license": "ISC", + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, "dependencies": { - "@npmcli/node-gyp": "^2.0.0", - "@npmcli/promise-spawn": "^3.0.0", - "node-gyp": "^9.0.0", - "read-package-json-fast": "^2.0.3", - "which": "^2.0.2" + "p-limit": "^3.0.2" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/@tootallnate/once": { - "version": "2.0.0", - "inBundle": true, - "license": "MIT", + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, "engines": { - "node": ">= 10" + "node": ">=6" } }, - "node_modules/npm/node_modules/abbrev": { - "version": "1.1.1", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/agent-base": { - "version": "6.0.2", - "inBundle": true, - "license": "MIT", + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, "dependencies": { - "debug": "4" + "callsites": "^3.0.0" }, "engines": { - "node": ">= 6.0.0" + "node": ">=6" } }, - "node_modules/npm/node_modules/agentkeepalive": { - "version": "4.2.1", - "inBundle": true, - "license": "MIT", + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, "dependencies": { - "debug": "^4.1.0", - "depd": "^1.1.2", - "humanize-ms": "^1.2.1" + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" }, "engines": { - "node": ">= 8.0.0" + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/aggregate-error": { - "version": "3.1.0", - "inBundle": true, - "license": "MIT", - "dependencies": { - "clean-stack": "^2.0.0", - "indent-string": "^4.0.0" - }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, "engines": { - "node": ">=8" + "node": ">= 0.8" } }, - "node_modules/npm/node_modules/ansi-regex": { - "version": "5.0.1", - "inBundle": true, - "license": "MIT", + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, "engines": { "node": ">=8" } }, - "node_modules/npm/node_modules/ansi-styles": { - "version": "4.3.0", - "inBundle": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/npm/node_modules/aproba": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC" + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true }, - "node_modules/npm/node_modules/archy": { - "version": "1.0.0", - "inBundle": true, - "license": "MIT" + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", + "dev": true }, - "node_modules/npm/node_modules/are-we-there-yet": { - "version": "3.0.1", - "inBundle": true, - "license": "ISC", - "dependencies": { - "delegates": "^1.0.0", - "readable-stream": "^3.6.0" - }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/asap": { - "version": "2.0.6", - "inBundle": true, - "license": "MIT" + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true }, - "node_modules/npm/node_modules/balanced-match": { - "version": "1.0.2", - "inBundle": true, - "license": "MIT" + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } }, - "node_modules/npm/node_modules/bin-links": { - "version": "3.0.2", - "inBundle": true, - "license": "ISC", - "dependencies": { - "cmd-shim": "^5.0.0", - "mkdirp-infer-owner": "^2.0.0", - "npm-normalize-package-bin": "^1.0.0", - "read-cmd-shim": "^3.0.0", - "rimraf": "^3.0.0", - "write-file-atomic": "^4.0.0" + "node_modules/pidtree": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.6.0.tgz", + "integrity": "sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==", + "dev": true, + "bin": { + "pidtree": "bin/pidtree.js" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=0.10" } }, - "node_modules/npm/node_modules/binary-extensions": { - "version": "2.2.0", - "inBundle": true, - "license": "MIT", + "node_modules/pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true, "engines": { - "node": ">=8" + "node": ">=4" } }, - "node_modules/npm/node_modules/brace-expansion": { - "version": "2.0.1", - "inBundle": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" + "node_modules/pirates": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", + "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==", + "dev": true, + "engines": { + "node": ">= 6" } }, - "node_modules/npm/node_modules/builtins": { - "version": "5.0.1", - "inBundle": true, - "license": "MIT", + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, "dependencies": { - "semver": "^7.0.0" - } - }, - "node_modules/npm/node_modules/cacache": { - "version": "16.1.2", - "inBundle": true, - "license": "ISC", - "dependencies": { - "@npmcli/fs": "^2.1.0", - "@npmcli/move-file": "^2.0.0", - "chownr": "^2.0.0", - "fs-minipass": "^2.1.0", - "glob": "^8.0.1", - "infer-owner": "^1.0.4", - "lru-cache": "^7.7.1", - "minipass": "^3.1.6", - "minipass-collect": "^1.0.2", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "mkdirp": "^1.0.4", - "p-map": "^4.0.0", - "promise-inflight": "^1.0.1", - "rimraf": "^3.0.2", - "ssri": "^9.0.0", - "tar": "^6.1.11", - "unique-filename": "^1.1.1" + "find-up": "^4.0.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/chalk": { - "version": "4.1.2", - "inBundle": true, - "license": "MIT", + "node_modules/pkg-dir/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/npm/node_modules/chownr": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC", "engines": { - "node": ">=10" + "node": ">=8" } }, - "node_modules/npm/node_modules/cidr-regex": { - "version": "3.1.1", - "inBundle": true, - "license": "BSD-2-Clause", + "node_modules/pkg-dir/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, "dependencies": { - "ip-regex": "^4.1.0" + "p-locate": "^4.1.0" }, "engines": { - "node": ">=10" + "node": ">=8" } }, - "node_modules/npm/node_modules/clean-stack": { - "version": "2.2.0", - "inBundle": true, - "license": "MIT", + "node_modules/pkg-dir/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, "engines": { "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/cli-columns": { - "version": "4.0.0", - "inBundle": true, - "license": "MIT", + "node_modules/pkg-dir/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, "dependencies": { - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1" + "p-limit": "^2.2.0" }, "engines": { - "node": ">= 10" + "node": ">=8" } }, - "node_modules/npm/node_modules/cli-table3": { - "version": "0.6.2", - "inBundle": true, - "license": "MIT", + "node_modules/please-upgrade-node": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", + "integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==", + "dev": true, "dependencies": { - "string-width": "^4.2.0" - }, - "engines": { - "node": "10.* || >= 12.*" - }, - "optionalDependencies": { - "@colors/colors": "1.5.0" + "semver-compare": "^1.0.0" } }, - "node_modules/npm/node_modules/clone": { - "version": "1.0.4", - "inBundle": true, - "license": "MIT", + "node_modules/pluralize": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "dev": true, "engines": { - "node": ">=0.8" + "node": ">=4" } }, - "node_modules/npm/node_modules/cmd-shim": { - "version": "5.0.0", - "inBundle": true, - "license": "ISC", - "dependencies": { - "mkdirp-infer-owner": "^2.0.0" - }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.8.0" } }, - "node_modules/npm/node_modules/color-convert": { - "version": "2.0.1", - "inBundle": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" + "node_modules/prettier": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", + "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" }, "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/npm/node_modules/color-name": { - "version": "1.1.4", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/color-support": { - "version": "1.1.3", - "inBundle": true, - "license": "ISC", - "bin": { - "color-support": "bin.js" + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" } }, - "node_modules/npm/node_modules/columnify": { - "version": "1.6.0", - "inBundle": true, - "license": "MIT", + "node_modules/prettier-linter-helpers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", + "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", + "dev": true, "dependencies": { - "strip-ansi": "^6.0.1", - "wcwidth": "^1.0.0" + "fast-diff": "^1.1.2" }, "engines": { - "node": ">=8.0.0" + "node": ">=6.0.0" } }, - "node_modules/npm/node_modules/common-ancestor-path": { - "version": "1.0.1", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/concat-map": { - "version": "0.0.1", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/console-control-strings": { - "version": "1.1.0", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/cssesc": { - "version": "3.0.0", - "inBundle": true, - "license": "MIT", - "bin": { - "cssesc": "bin/cssesc" + "node_modules/pretty-format": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "dev": true, + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" }, "engines": { - "node": ">=4" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, - "node_modules/npm/node_modules/debug": { - "version": "4.3.4", - "inBundle": true, - "license": "MIT", - "dependencies": { - "ms": "2.1.2" - }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, "engines": { - "node": ">=6.0" + "node": ">=10" }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/npm/node_modules/debug/node_modules/ms": { - "version": "2.1.2", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/debuglog": { - "version": "1.0.1", - "inBundle": true, - "license": "MIT", + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, "engines": { - "node": "*" + "node": ">= 6" } }, - "node_modules/npm/node_modules/defaults": { - "version": "1.0.3", - "inBundle": true, - "license": "MIT", + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dev": true, "dependencies": { - "clone": "^1.0.2" + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" } }, - "node_modules/npm/node_modules/delegates": { - "version": "1.0.0", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/depd": { - "version": "1.1.2", - "inBundle": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/npm/node_modules/dezalgo": { - "version": "1.0.4", - "inBundle": true, - "license": "ISC", - "dependencies": { - "asap": "^2.0.0", - "wrappy": "1" - } - }, - "node_modules/npm/node_modules/diff": { - "version": "5.0.0", - "inBundle": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.3.1" - } - }, - "node_modules/npm/node_modules/emoji-regex": { - "version": "8.0.0", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/encoding": { - "version": "0.1.13", - "inBundle": true, - "license": "MIT", - "optional": true, + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", "dependencies": { - "iconv-lite": "^0.6.2" + "end-of-stream": "^1.1.0", + "once": "^1.3.1" } }, - "node_modules/npm/node_modules/env-paths": { - "version": "2.2.1", - "inBundle": true, - "license": "MIT", + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, "engines": { "node": ">=6" } }, - "node_modules/npm/node_modules/err-code": { - "version": "2.0.3", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/fastest-levenshtein": { - "version": "1.0.12", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/fs-minipass": { - "version": "2.1.0", - "inBundle": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/npm/node_modules/fs.realpath": { - "version": "1.0.0", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/function-bind": { - "version": "1.1.1", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/gauge": { - "version": "4.0.4", - "inBundle": true, - "license": "ISC", - "dependencies": { - "aproba": "^1.0.3 || ^2.0.0", - "color-support": "^1.1.3", - "console-control-strings": "^1.1.0", - "has-unicode": "^2.0.1", - "signal-exit": "^3.0.7", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1", - "wide-align": "^1.1.5" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } + "node_modules/pure-rand": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.0.tgz", + "integrity": "sha512-rLSBxJjP+4DQOgcJAx6RZHT2he2pkhQdSnofG5VWyVl6GRq/K02ISOuOLcsMOrtKDIJb8JN2zm3FFzWNbezdPw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ] }, - "node_modules/npm/node_modules/glob": { - "version": "8.0.3", - "inBundle": true, - "license": "ISC", + "node_modules/qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "dev": true, "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" + "side-channel": "^1.0.4" }, "engines": { - "node": ">=12" + "node": ">=0.6" }, "funding": { - "url": "https://github.com/sponsors/isaacs" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/graceful-fs": { - "version": "4.2.10", - "inBundle": true, - "license": "ISC" + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] }, - "node_modules/npm/node_modules/has": { - "version": "1.0.3", - "inBundle": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.1" - }, - "engines": { - "node": ">= 0.4.0" - } + "node_modules/queue-tick": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz", + "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==" }, - "node_modules/npm/node_modules/has-flag": { - "version": "4.0.0", - "inBundle": true, - "license": "MIT", + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "dev": true, "engines": { - "node": ">=8" + "node": ">= 0.6" } }, - "node_modules/npm/node_modules/has-unicode": { - "version": "2.0.1", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/hosted-git-info": { - "version": "5.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dev": true, "dependencies": { - "lru-cache": "^7.5.1" + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16" + "node": ">= 0.8" } }, - "node_modules/npm/node_modules/http-cache-semantics": { - "version": "4.1.0", - "inBundle": true, - "license": "BSD-2-Clause" + "node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true }, - "node_modules/npm/node_modules/http-proxy-agent": { - "version": "5.0.0", - "inBundle": true, - "license": "MIT", + "node_modules/readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", "dependencies": { - "@tootallnate/once": "2", - "agent-base": "6", - "debug": "4" + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" }, "engines": { "node": ">= 6" } }, - "node_modules/npm/node_modules/https-proxy-agent": { - "version": "5.0.1", - "inBundle": true, - "license": "MIT", + "node_modules/regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "dev": true + }, + "node_modules/regexp.prototype.flags": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz", + "integrity": "sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==", + "dev": true, "dependencies": { - "agent-base": "6", - "debug": "4" + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "functions-have-names": "^1.2.2" }, "engines": { - "node": ">= 6" - } - }, - "node_modules/npm/node_modules/humanize-ms": { - "version": "1.2.1", - "inBundle": true, - "license": "MIT", - "dependencies": { - "ms": "^2.0.0" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/iconv-lite": { - "version": "0.6.3", - "inBundle": true, - "license": "MIT", + "node_modules/regexpp": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", + "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", + "dev": true, "optional": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" + "peer": true, + "engines": { + "node": ">=8" }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "dev": true, "engines": { "node": ">=0.10.0" } }, - "node_modules/npm/node_modules/ignore-walk": { - "version": "5.0.1", - "inBundle": true, - "license": "ISC", + "node_modules/resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, "dependencies": { - "minimatch": "^5.0.1" + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/imurmurhash": { - "version": "0.1.4", - "inBundle": true, - "license": "MIT", + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "dependencies": { + "resolve-from": "^5.0.0" + }, "engines": { - "node": ">=0.8.19" + "node": ">=8" } }, - "node_modules/npm/node_modules/indent-string": { - "version": "4.0.0", - "inBundle": true, - "license": "MIT", + "node_modules/resolve-cwd/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, "engines": { "node": ">=8" } }, - "node_modules/npm/node_modules/infer-owner": { - "version": "1.0.4", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/inflight": { - "version": "1.0.6", - "inBundle": true, - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "engines": { + "node": ">=4" } }, - "node_modules/npm/node_modules/inherits": { - "version": "2.0.4", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/ini": { - "version": "3.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/resolve.exports": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.0.tgz", + "integrity": "sha512-6K/gDlqgQscOlg9fSRpWstA8sYe8rbELsSTNpx+3kTrsVCzvSl0zIvRErM7fdl9ERWDsKnrLnwB+Ne89918XOg==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=10" } }, - "node_modules/npm/node_modules/init-package-json": { - "version": "3.0.2", - "inBundle": true, - "license": "ISC", + "node_modules/restore-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", + "dev": true, "dependencies": { - "npm-package-arg": "^9.0.1", - "promzard": "^0.3.0", - "read": "^1.0.7", - "read-package-json": "^5.0.0", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4", - "validate-npm-package-name": "^4.0.0" + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/ip": { - "version": "2.0.0", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/ip-regex": { - "version": "4.3.0", - "inBundle": true, - "license": "MIT", + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "dev": true, "engines": { - "node": ">=8" + "iojs": ">=1.0.0", + "node": ">=0.10.0" } }, - "node_modules/npm/node_modules/is-cidr": { - "version": "4.0.2", - "inBundle": true, - "license": "BSD-2-Clause", - "dependencies": { - "cidr-regex": "^3.1.1" - }, - "engines": { - "node": ">=10" - } + "node_modules/rfdc": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.1.tgz", + "integrity": "sha512-r5a3l5HzYlIC68TpmYKlxWjmOP6wiPJ1vWv2HeLhNsRZMrCkxeqxiHlQ21oXmQ4F3SiryXBHhAD7JZqvOJjFmg==", + "dev": true }, - "node_modules/npm/node_modules/is-core-module": { - "version": "2.10.0", - "inBundle": true, - "license": "MIT", + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, "dependencies": { - "has": "^1.0.3" + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/npm/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "inBundle": true, - "license": "MIT", - "engines": { - "node": ">=8" + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" } }, - "node_modules/npm/node_modules/is-lambda": { - "version": "1.0.1", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/isexe": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/json-parse-even-better-errors": { - "version": "2.3.1", - "inBundle": true, - "license": "MIT" + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true }, - "node_modules/npm/node_modules/json-stringify-nice": { - "version": "1.1.4", - "inBundle": true, - "license": "ISC", + "node_modules/safe-regex-test": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.0.tgz", + "integrity": "sha512-JBUUzyOgEwXQY1NuPtvcj/qcBDbDmEvWufhlnXZIm75DEHp+afM1r1ujJpJsV/gSM4t59tpDyPi1sd6ZaPFfsA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-regex": "^1.1.4" + }, "funding": { - "url": "https://github.com/sponsors/isaacs" + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/jsonparse": { - "version": "1.3.1", - "engines": [ - "node >= 0.2.0" - ], - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/just-diff": { - "version": "5.1.1", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/just-diff-apply": { - "version": "5.4.1", - "inBundle": true, - "license": "MIT" + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, - "node_modules/npm/node_modules/libnpmaccess": { - "version": "6.0.3", - "inBundle": true, - "license": "ISC", + "node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, "dependencies": { - "aproba": "^2.0.0", - "minipass": "^3.1.1", - "npm-package-arg": "^9.0.1", - "npm-registry-fetch": "^13.0.0" + "lru-cache": "^6.0.0" }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/npm/node_modules/libnpmdiff": { - "version": "4.0.4", - "inBundle": true, - "license": "ISC", - "dependencies": { - "@npmcli/disparity-colors": "^2.0.0", - "@npmcli/installed-package-contents": "^1.0.7", - "binary-extensions": "^2.2.0", - "diff": "^5.0.0", - "minimatch": "^5.0.1", - "npm-package-arg": "^9.0.1", - "pacote": "^13.6.1", - "tar": "^6.1.0" + "bin": { + "semver": "bin/semver.js" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=10" } }, - "node_modules/npm/node_modules/libnpmexec": { - "version": "4.0.11", - "inBundle": true, - "license": "ISC", - "dependencies": { - "@npmcli/arborist": "^5.0.0", - "@npmcli/ci-detect": "^2.0.0", - "@npmcli/fs": "^2.1.1", - "@npmcli/run-script": "^4.2.0", - "chalk": "^4.1.0", - "mkdirp-infer-owner": "^2.0.0", - "npm-package-arg": "^9.0.1", - "npmlog": "^6.0.2", - "pacote": "^13.6.1", - "proc-log": "^2.0.0", - "read": "^1.0.7", - "read-package-json-fast": "^2.0.2", - "semver": "^7.3.7", - "walk-up-path": "^1.0.0" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } + "node_modules/semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w=", + "dev": true }, - "node_modules/npm/node_modules/libnpmfund": { - "version": "3.0.2", - "inBundle": true, - "license": "ISC", + "node_modules/send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dev": true, "dependencies": { - "@npmcli/arborist": "^5.0.0" + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.8.0" } }, - "node_modules/npm/node_modules/libnpmhook": { - "version": "8.0.3", - "inBundle": true, - "license": "ISC", + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, "dependencies": { - "aproba": "^2.0.0", - "npm-registry-fetch": "^13.0.0" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "ms": "2.0.0" } }, - "node_modules/npm/node_modules/libnpmorg": { - "version": "4.0.3", - "inBundle": true, - "license": "ISC", + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/send/node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, "dependencies": { - "aproba": "^2.0.0", - "npm-registry-fetch": "^13.0.0" + "ee-first": "1.1.1" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.8" } }, - "node_modules/npm/node_modules/libnpmpack": { - "version": "4.1.2", - "inBundle": true, - "license": "ISC", + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dev": true, "dependencies": { - "@npmcli/run-script": "^4.1.3", - "npm-package-arg": "^9.0.1", - "pacote": "^13.6.1" + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.8.0" } }, - "node_modules/npm/node_modules/libnpmpublish": { - "version": "6.0.4", - "inBundle": true, - "license": "ISC", + "node_modules/server-destroy": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/server-destroy/-/server-destroy-1.0.1.tgz", + "integrity": "sha1-8Tv5KOQrnD55OD5hzDmYtdFObN0=", + "dev": true + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, "dependencies": { - "normalize-package-data": "^4.0.0", - "npm-package-arg": "^9.0.1", - "npm-registry-fetch": "^13.0.0", - "semver": "^7.3.7", - "ssri": "^9.0.0" + "shebang-regex": "^3.0.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/libnpmsearch": { - "version": "5.0.3", - "inBundle": true, - "license": "ISC", - "dependencies": { - "npm-registry-fetch": "^13.0.0" - }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/libnpmteam": { - "version": "4.0.3", - "inBundle": true, - "license": "ISC", + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dev": true, "dependencies": { - "aproba": "^2.0.0", - "npm-registry-fetch": "^13.0.0" + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/libnpmversion": { - "version": "3.0.6", - "inBundle": true, - "license": "ISC", + "node_modules/slice-ansi": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", + "dev": true, "dependencies": { - "@npmcli/git": "^3.0.0", - "@npmcli/run-script": "^4.1.3", - "json-parse-even-better-errors": "^2.3.1", - "proc-log": "^2.0.0", - "semver": "^7.3.7" + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, - "node_modules/npm/node_modules/lru-cache": { - "version": "7.13.2", - "inBundle": true, - "license": "ISC", + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, "engines": { "node": ">=12" - } - }, - "node_modules/npm/node_modules/make-fetch-happen": { - "version": "10.2.1", - "inBundle": true, - "license": "ISC", - "dependencies": { - "agentkeepalive": "^4.2.1", - "cacache": "^16.1.0", - "http-cache-semantics": "^4.1.0", - "http-proxy-agent": "^5.0.0", - "https-proxy-agent": "^5.0.0", - "is-lambda": "^1.0.1", - "lru-cache": "^7.7.1", - "minipass": "^3.1.6", - "minipass-collect": "^1.0.2", - "minipass-fetch": "^2.0.3", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^0.6.3", - "promise-retry": "^2.0.1", - "socks-proxy-agent": "^7.0.0", - "ssri": "^9.0.0" }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/npm/node_modules/minimatch": { - "version": "5.1.0", - "inBundle": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "dev": true, "engines": { - "node": ">=10" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/minipass": { - "version": "3.3.4", - "inBundle": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, "engines": { - "node": ">=8" + "node": ">=0.10.0" } }, - "node_modules/npm/node_modules/minipass-collect": { - "version": "1.0.2", - "inBundle": true, - "license": "ISC", + "node_modules/source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "dev": true, "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" } }, - "node_modules/npm/node_modules/minipass-fetch": { - "version": "2.1.1", - "inBundle": true, - "license": "MIT", + "node_modules/split-ca": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/split-ca/-/split-ca-1.0.1.tgz", + "integrity": "sha512-Q5thBSxp5t8WPTTJQS59LrGqOZqOsrhDGDVm8azCqIBjSBd7nd9o2PM+mDulQQkh8h//4U6hFZnc/mul8t5pWQ==" + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "node_modules/ssh2": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.15.0.tgz", + "integrity": "sha512-C0PHgX4h6lBxYx7hcXwu3QWdh4tg6tZZsTfXcdvc5caW/EMxaB4H9dWsl7qk+F7LAW762hp8VbXOX7x4xUYvEw==", + "hasInstallScript": true, "dependencies": { - "minipass": "^3.1.6", - "minipass-sized": "^1.0.3", - "minizlib": "^2.1.2" + "asn1": "^0.2.6", + "bcrypt-pbkdf": "^1.0.2" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=10.16.0" }, "optionalDependencies": { - "encoding": "^0.1.13" + "cpu-features": "~0.0.9", + "nan": "^2.18.0" } }, - "node_modules/npm/node_modules/minipass-flush": { - "version": "1.0.5", - "inBundle": true, - "license": "ISC", + "node_modules/stack-utils": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.5.tgz", + "integrity": "sha512-xrQcmYhOsn/1kX+Vraq+7j4oE2j/6BFscZ0etmYg81xuM8Gq0022Pxb8+IqgOFUIaxHs0KaSb7T1+OegiNrNFA==", + "dev": true, "dependencies": { - "minipass": "^3.0.0" + "escape-string-regexp": "^2.0.0" }, "engines": { - "node": ">= 8" - } - }, - "node_modules/npm/node_modules/minipass-json-stream": { - "version": "1.0.1", - "inBundle": true, - "license": "MIT", - "dependencies": { - "jsonparse": "^1.3.1", - "minipass": "^3.0.0" + "node": ">=10" } }, - "node_modules/npm/node_modules/minipass-pipeline": { - "version": "1.2.4", - "inBundle": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, + "node_modules/stack-utils/node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, "engines": { "node": ">=8" } }, - "node_modules/npm/node_modules/minipass-sized": { - "version": "1.0.3", - "inBundle": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "dev": true, "engines": { - "node": ">=8" + "node": ">= 0.8" } }, - "node_modules/npm/node_modules/minizlib": { - "version": "2.1.2", - "inBundle": true, - "license": "MIT", + "node_modules/steno": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/steno/-/steno-0.4.4.tgz", + "integrity": "sha1-BxEFvfwobmYVwEA8J+nXtdy4Vcs=", + "dev": true, "dependencies": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/npm/node_modules/mkdirp": { - "version": "1.0.4", - "inBundle": true, - "license": "MIT", - "bin": { - "mkdirp": "bin/cmd.js" - }, - "engines": { - "node": ">=10" + "graceful-fs": "^4.1.3" } }, - "node_modules/npm/node_modules/mkdirp-infer-owner": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/stop-iteration-iterator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.0.0.tgz", + "integrity": "sha512-iCGQj+0l0HOdZ2AEeBADlsRC+vsnDsZsbdSiH1yNSjcfKM7fdpCMfqAL/dwF5BLiw/XhRft/Wax6zQbhq2BcjQ==", + "dev": true, "dependencies": { - "chownr": "^2.0.0", - "infer-owner": "^1.0.4", - "mkdirp": "^1.0.3" + "internal-slot": "^1.0.4" }, "engines": { - "node": ">=10" - } - }, - "node_modules/npm/node_modules/ms": { - "version": "2.1.3", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/mute-stream": { - "version": "0.0.8", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/negotiator": { - "version": "0.6.3", - "inBundle": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" + "node": ">= 0.4" } }, - "node_modules/npm/node_modules/node-gyp": { - "version": "9.1.0", - "inBundle": true, - "license": "MIT", + "node_modules/streamx": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.0.tgz", + "integrity": "sha512-HcxY6ncGjjklGs1xsP1aR71INYcsXFJet5CU1CHqihQ2J5nOsbd4OjgjHO42w/4QNv9gZb3BueV+Vxok5pLEXg==", "dependencies": { - "env-paths": "^2.2.0", - "glob": "^7.1.4", - "graceful-fs": "^4.2.6", - "make-fetch-happen": "^10.0.3", - "nopt": "^5.0.0", - "npmlog": "^6.0.0", - "rimraf": "^3.0.2", - "semver": "^7.3.5", - "tar": "^6.1.2", - "which": "^2.0.2" - }, - "bin": { - "node-gyp": "bin/node-gyp.js" - }, - "engines": { - "node": "^12.22 || ^14.13 || >=16" + "fast-fifo": "^1.1.0", + "queue-tick": "^1.0.1" } }, - "node_modules/npm/node_modules/node-gyp/node_modules/brace-expansion": { - "version": "1.1.11", - "inBundle": true, - "license": "MIT", + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "safe-buffer": "~5.2.0" } }, - "node_modules/npm/node_modules/node-gyp/node_modules/glob": { - "version": "7.2.3", - "inBundle": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] }, - "node_modules/npm/node_modules/node-gyp/node_modules/minimatch": { - "version": "3.1.2", - "inBundle": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, + "node_modules/string-argv": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", + "dev": true, "engines": { - "node": "*" + "node": ">=0.6.19" } }, - "node_modules/npm/node_modules/node-gyp/node_modules/nopt": { - "version": "5.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "dev": true, "dependencies": { - "abbrev": "1" - }, - "bin": { - "nopt": "bin/nopt.js" + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" }, "engines": { - "node": ">=6" + "node": ">=10" } }, - "node_modules/npm/node_modules/nopt": { - "version": "6.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, "dependencies": { - "abbrev": "^1.0.0" - }, - "bin": { - "nopt": "bin/nopt.js" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/normalize-package-data": { - "version": "4.0.1", - "inBundle": true, - "license": "BSD-2-Clause", + "node_modules/string.prototype.trimend": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.5.tgz", + "integrity": "sha512-I7RGvmjV4pJ7O3kdf+LXFpVfdNOxtCW/2C8f6jNiW4+PQchwxkCDzlk1/7p+Wl4bqFIZeF47qAHXLuHHWKAxog==", + "dev": true, "dependencies": { - "hosted-git-info": "^5.0.0", - "is-core-module": "^2.8.1", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4" + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.19.5" }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/npm-audit-report": { - "version": "3.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/string.prototype.trimstart": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.5.tgz", + "integrity": "sha512-THx16TJCGlsN0o6dl2o6ncWUsdgnLRSA23rRE5pyGBw/mLr3Ej/R2LaqCtgP8VNMGZsvMWnf9ooZPyY2bHvUFg==", + "dev": true, "dependencies": { - "chalk": "^4.0.0" + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.19.5" }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/npm/node_modules/npm-bundled": { - "version": "1.1.2", - "inBundle": true, - "license": "ISC", - "dependencies": { - "npm-normalize-package-bin": "^1.0.1" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/npm-install-checks": { - "version": "5.0.0", - "inBundle": true, - "license": "BSD-2-Clause", + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, "dependencies": { - "semver": "^7.1.1" + "ansi-regex": "^5.0.1" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/npm-normalize-package-bin": { - "version": "1.0.1", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/npm-package-arg": { - "version": "9.1.0", - "inBundle": true, - "license": "ISC", - "dependencies": { - "hosted-git-info": "^5.0.0", - "proc-log": "^2.0.1", - "semver": "^7.3.5", - "validate-npm-package-name": "^4.0.0" - }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/npm-packlist": { - "version": "5.1.1", - "inBundle": true, - "license": "ISC", - "dependencies": { - "glob": "^8.0.1", - "ignore-walk": "^5.0.1", - "npm-bundled": "^1.1.2", - "npm-normalize-package-bin": "^1.0.1" - }, - "bin": { - "npm-packlist": "bin/index.js" - }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=6" } }, - "node_modules/npm/node_modules/npm-pick-manifest": { - "version": "7.0.1", - "inBundle": true, - "license": "ISC", - "dependencies": { - "npm-install-checks": "^5.0.0", - "npm-normalize-package-bin": "^1.0.1", - "npm-package-arg": "^9.0.0", - "semver": "^7.3.5" - }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/npm/node_modules/npm-profile": { - "version": "6.2.1", - "inBundle": true, - "license": "ISC", - "dependencies": { - "npm-registry-fetch": "^13.0.1", - "proc-log": "^2.0.0" + "node": ">=8" }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/npm-registry-fetch": { - "version": "13.3.1", - "inBundle": true, - "license": "ISC", + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, "dependencies": { - "make-fetch-happen": "^10.0.6", - "minipass": "^3.1.6", - "minipass-fetch": "^2.0.3", - "minipass-json-stream": "^1.0.1", - "minizlib": "^2.1.2", - "npm-package-arg": "^9.0.1", - "proc-log": "^2.0.0" + "has-flag": "^4.0.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8" } }, - "node_modules/npm/node_modules/npm-user-validate": { - "version": "1.0.1", - "inBundle": true, - "license": "BSD-2-Clause" - }, - "node_modules/npm/node_modules/npmlog": { - "version": "6.0.2", - "inBundle": true, - "license": "ISC", - "dependencies": { - "are-we-there-yet": "^3.0.0", - "console-control-strings": "^1.1.0", - "gauge": "^4.0.3", - "set-blocking": "^2.0.0" - }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/npm/node_modules/once": { - "version": "1.4.0", - "inBundle": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/opener": { - "version": "1.5.2", - "inBundle": true, - "license": "(WTFPL OR MIT)", - "bin": { - "opener": "bin/opener-bin.js" + "node_modules/svg-element-attributes": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/svg-element-attributes/-/svg-element-attributes-1.3.1.tgz", + "integrity": "sha512-Bh05dSOnJBf3miNMqpsormfNtfidA/GxQVakhtn0T4DECWKeXQRQUceYjJ+OxYiiLdGe4Jo9iFV8wICFapFeIA==", + "dev": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/npm/node_modules/p-map": { - "version": "4.0.0", - "inBundle": true, - "license": "MIT", + "node_modules/synckit": { + "version": "0.8.8", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.8.tgz", + "integrity": "sha512-HwOKAP7Wc5aRGYdKH+dw0PRRpbO841v2DENBtjnR5HFWoiNByAl7vrx3p0G/rCyYXQsrxqtX48TImFtPcIHSpQ==", + "dev": true, "dependencies": { - "aggregate-error": "^3.0.0" + "@pkgr/core": "^0.1.0", + "tslib": "^2.6.2" }, "engines": { - "node": ">=10" + "node": "^14.18.0 || >=16.0.0" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://opencollective.com/unts" } }, - "node_modules/npm/node_modules/pacote": { - "version": "13.6.2", - "inBundle": true, - "license": "ISC", - "dependencies": { - "@npmcli/git": "^3.0.0", - "@npmcli/installed-package-contents": "^1.0.7", - "@npmcli/promise-spawn": "^3.0.0", - "@npmcli/run-script": "^4.1.0", - "cacache": "^16.0.0", - "chownr": "^2.0.0", - "fs-minipass": "^2.1.0", - "infer-owner": "^1.0.4", - "minipass": "^3.1.6", - "mkdirp": "^1.0.4", - "npm-package-arg": "^9.0.0", - "npm-packlist": "^5.1.0", - "npm-pick-manifest": "^7.0.0", - "npm-registry-fetch": "^13.0.1", - "proc-log": "^2.0.0", - "promise-retry": "^2.0.1", - "read-package-json": "^5.0.0", - "read-package-json-fast": "^2.0.3", - "rimraf": "^3.0.2", - "ssri": "^9.0.0", - "tar": "^6.1.11" - }, - "bin": { - "pacote": "lib/bin.js" - }, + "node_modules/synckit/node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==", + "dev": true + }, + "node_modules/tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=6" } }, - "node_modules/npm/node_modules/parse-conflict-json": { - "version": "2.0.2", - "inBundle": true, - "license": "ISC", + "node_modules/tar-fs": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.0.1.tgz", + "integrity": "sha512-6tzWDMeroL87uF/+lin46k+Q+46rAJ0SyPGz7OW7wTgblI273hsBqk2C1j0/xNadNLKDTUL9BukSjB7cwgmlPA==", "dependencies": { - "json-parse-even-better-errors": "^2.3.1", - "just-diff": "^5.0.1", - "just-diff-apply": "^5.2.0" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.0.0" } }, - "node_modules/npm/node_modules/path-is-absolute": { - "version": "1.0.1", - "inBundle": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/npm/node_modules/postcss-selector-parser": { - "version": "6.0.10", - "inBundle": true, - "license": "MIT", + "node_modules/tar-fs/node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", "dependencies": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/npm/node_modules/proc-log": { - "version": "2.0.1", - "inBundle": true, - "license": "ISC", - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/npm/node_modules/promise-all-reject-late": { - "version": "1.0.1", - "inBundle": true, - "license": "ISC", - "funding": { - "url": "https://github.com/sponsors/isaacs" + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" } }, - "node_modules/npm/node_modules/promise-call-limit": { - "version": "1.0.1", - "inBundle": true, - "license": "ISC", - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node_modules/tar-fs/node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" } }, - "node_modules/npm/node_modules/promise-inflight": { - "version": "1.0.1", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/promise-retry": { - "version": "2.0.1", - "inBundle": true, - "license": "MIT", + "node_modules/tar-fs/node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", "dependencies": { - "err-code": "^2.0.2", - "retry": "^0.12.0" + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" }, "engines": { - "node": ">=10" + "node": ">=6" } }, - "node_modules/npm/node_modules/promzard": { - "version": "0.3.0", - "inBundle": true, - "license": "ISC", + "node_modules/tar-stream": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.7.tgz", + "integrity": "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==", "dependencies": { - "read": "1" - } - }, - "node_modules/npm/node_modules/qrcode-terminal": { - "version": "0.12.0", - "inBundle": true, - "bin": { - "qrcode-terminal": "bin/qrcode-terminal.js" + "b4a": "^1.6.4", + "fast-fifo": "^1.2.0", + "streamx": "^2.15.0" } }, - "node_modules/npm/node_modules/read": { - "version": "1.0.7", - "inBundle": true, - "license": "ISC", + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, "dependencies": { - "mute-stream": "~0.0.4" + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" }, "engines": { - "node": ">=0.8" + "node": ">=8" } }, - "node_modules/npm/node_modules/read-cmd-shim": { - "version": "3.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "node_modules/tmpl": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", + "dev": true + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=4" } }, - "node_modules/npm/node_modules/read-package-json": { + "node_modules/to-regex-range": { "version": "5.0.1", - "inBundle": true, - "license": "ISC", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, "dependencies": { - "glob": "^8.0.1", - "json-parse-even-better-errors": "^2.3.1", - "normalize-package-data": "^4.0.0", - "npm-normalize-package-bin": "^1.0.1" + "is-number": "^7.0.0" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=8.0" } }, - "node_modules/npm/node_modules/read-package-json-fast": { - "version": "2.0.3", - "inBundle": true, - "license": "ISC", - "dependencies": { - "json-parse-even-better-errors": "^2.3.0", - "npm-normalize-package-bin": "^1.0.1" - }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, "engines": { - "node": ">=10" + "node": ">=0.6" } }, - "node_modules/npm/node_modules/readable-stream": { - "version": "3.6.0", - "inBundle": true, - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, + "node_modules/ts-api-utils": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.2.1.tgz", + "integrity": "sha512-RIYA36cJn2WiH9Hy77hdF9r7oEwxAtB/TS9/S4Qd90Ap4z5FSiin5zEiTL44OII1Y3IIlEvxwxFUVgrHSZ/UpA==", + "dev": true, "engines": { - "node": ">= 6" + "node": ">=16" + }, + "peerDependencies": { + "typescript": ">=4.2.0" } }, - "node_modules/npm/node_modules/readdir-scoped-modules": { - "version": "1.1.0", - "inBundle": true, - "license": "ISC", + "node_modules/ts-jest": { + "version": "29.1.2", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.2.tgz", + "integrity": "sha512-br6GJoH/WUX4pu7FbZXuWGKGNDuU7b8Uj77g/Sp7puZV6EXzuByl6JrECvm0MzVzSTkSHWTihsXt+5XYER5b+g==", + "dev": true, "dependencies": { - "debuglog": "^1.0.1", - "dezalgo": "^1.0.0", - "graceful-fs": "^4.1.2", - "once": "^1.3.0" - } - }, - "node_modules/npm/node_modules/retry": { - "version": "0.12.0", - "inBundle": true, - "license": "MIT", + "bs-logger": "0.x", + "fast-json-stable-stringify": "2.x", + "jest-util": "^29.0.0", + "json5": "^2.2.3", + "lodash.memoize": "4.x", + "make-error": "1.x", + "semver": "^7.5.3", + "yargs-parser": "^21.0.1" + }, + "bin": { + "ts-jest": "cli.js" + }, "engines": { - "node": ">= 4" + "node": "^16.10.0 || ^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "@babel/core": ">=7.0.0-beta.0 <8", + "@jest/types": "^29.0.0", + "babel-jest": "^29.0.0", + "jest": "^29.0.0", + "typescript": ">=4.3 <6" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "@jest/types": { + "optional": true + }, + "babel-jest": { + "optional": true + }, + "esbuild": { + "optional": true + } } }, - "node_modules/npm/node_modules/rimraf": { - "version": "3.0.2", - "inBundle": true, - "license": "ISC", + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, "dependencies": { - "glob": "^7.1.3" + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" }, "bin": { - "rimraf": "bin.js" + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } } }, - "node_modules/npm/node_modules/rimraf/node_modules/brace-expansion": { - "version": "1.1.11", - "inBundle": true, - "license": "MIT", + "node_modules/ts-node/node_modules/acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/tsconfig-paths": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz", + "integrity": "sha512-fxDhWnFSLt3VuTwtvJt5fpwxBHg5AdKWMsgcPOOIilyjymcYVZoCQF8fvFRezCNfblEXmi+PcM1eYHeOAgXCOQ==", + "dev": true, "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "@types/json5": "^0.0.29", + "json5": "^1.0.1", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" } }, - "node_modules/npm/node_modules/rimraf/node_modules/glob": { - "version": "7.2.3", - "inBundle": true, - "license": "ISC", + "node_modules/tsconfig-paths/node_modules/json5": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "dev": true, "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" + "minimist": "^1.2.0" }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/tsconfig-paths/node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">=4" } }, - "node_modules/npm/node_modules/rimraf/node_modules/minimatch": { - "version": "3.1.2", - "inBundle": true, - "license": "ISC", + "node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, + "node_modules/tsutils": { + "version": "3.21.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", + "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", + "dev": true, "dependencies": { - "brace-expansion": "^1.1.7" + "tslib": "^1.8.1" }, "engines": { - "node": "*" + "node": ">= 6" + }, + "peerDependencies": { + "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" } }, - "node_modules/npm/node_modules/safe-buffer": { - "version": "5.2.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/safer-buffer": { - "version": "2.1.2", - "inBundle": true, - "license": "MIT", - "optional": true - }, - "node_modules/npm/node_modules/semver": { - "version": "7.3.7", - "inBundle": true, - "license": "ISC", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, + "node_modules/tunnel": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", + "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", "engines": { - "node": ">=10" + "node": ">=0.6.11 <=0.7.0 || >=0.7.3" } }, - "node_modules/npm/node_modules/semver/node_modules/lru-cache": { - "version": "6.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, "dependencies": { - "yallist": "^4.0.0" + "prelude-ls": "^1.2.1" }, "engines": { - "node": ">=10" + "node": ">= 0.8.0" } }, - "node_modules/npm/node_modules/set-blocking": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/signal-exit": { - "version": "3.0.7", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/smart-buffer": { - "version": "4.2.0", - "inBundle": true, - "license": "MIT", + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, "engines": { - "node": ">= 6.0.0", - "npm": ">= 3.0.0" + "node": ">=4" } }, - "node_modules/npm/node_modules/socks": { - "version": "2.7.0", - "inBundle": true, - "license": "MIT", - "dependencies": { - "ip": "^2.0.0", - "smart-buffer": "^4.2.0" - }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, "engines": { - "node": ">= 10.13.0", - "npm": ">= 3.0.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/npm/node_modules/socks-proxy-agent": { - "version": "7.0.0", - "inBundle": true, - "license": "MIT", + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dev": true, "dependencies": { - "agent-base": "^6.0.2", - "debug": "^4.3.3", - "socks": "^2.6.2" + "media-typer": "0.3.0", + "mime-types": "~2.1.24" }, "engines": { - "node": ">= 10" - } - }, - "node_modules/npm/node_modules/spdx-correct": { - "version": "3.1.1", - "inBundle": true, - "license": "Apache-2.0", - "dependencies": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" - } - }, - "node_modules/npm/node_modules/spdx-exceptions": { - "version": "2.3.0", - "inBundle": true, - "license": "CC-BY-3.0" - }, - "node_modules/npm/node_modules/spdx-expression-parse": { - "version": "3.0.1", - "inBundle": true, - "license": "MIT", - "dependencies": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" + "node": ">= 0.6" } }, - "node_modules/npm/node_modules/spdx-license-ids": { - "version": "3.0.11", - "inBundle": true, - "license": "CC0-1.0" - }, - "node_modules/npm/node_modules/ssri": { - "version": "9.0.1", - "inBundle": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.1.1" + "node_modules/typescript": { + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=14.17" } }, - "node_modules/npm/node_modules/string_decoder": { - "version": "1.3.0", - "inBundle": true, - "license": "MIT", + "node_modules/unbox-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", + "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", + "dev": true, "dependencies": { - "safe-buffer": "~5.2.0" + "call-bind": "^1.0.2", + "has-bigints": "^1.0.2", + "has-symbols": "^1.0.3", + "which-boxed-primitive": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/string-width": { - "version": "4.2.3", - "inBundle": true, - "license": "MIT", + "node_modules/undici": { + "version": "5.28.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz", + "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" + "@fastify/busboy": "^2.0.0" }, "engines": { - "node": ">=8" + "node": ">=14.0" } }, - "node_modules/npm/node_modules/strip-ansi": { + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "dev": true + }, + "node_modules/universal-user-agent": { "version": "6.0.1", - "inBundle": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", + "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, "engines": { - "node": ">=8" + "node": ">= 0.8" } }, - "node_modules/npm/node_modules/supports-color": { - "version": "7.2.0", - "inBundle": true, - "license": "MIT", + "node_modules/update-browserslist-db": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", + "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], "dependencies": { - "has-flag": "^4.0.0" + "escalade": "^3.1.1", + "picocolors": "^1.0.0" }, - "engines": { - "node": ">=8" + "bin": { + "browserslist-lint": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" } }, - "node_modules/npm/node_modules/tar": { - "version": "6.1.11", - "inBundle": true, - "license": "ISC", + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, "dependencies": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^3.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" - }, - "engines": { - "node": ">= 10" + "punycode": "^2.1.0" } }, - "node_modules/npm/node_modules/text-table": { - "version": "0.2.0", - "inBundle": true, - "license": "MIT" - }, - "node_modules/npm/node_modules/tiny-relative-date": { - "version": "1.3.0", - "inBundle": true, - "license": "MIT" + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" }, - "node_modules/npm/node_modules/treeverse": { - "version": "2.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">= 0.4.0" } }, - "node_modules/npm/node_modules/unique-filename": { - "version": "1.1.1", - "inBundle": true, - "license": "ISC", + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true + }, + "node_modules/v8-to-istanbul": { + "version": "9.1.3", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.3.tgz", + "integrity": "sha512-9lDD+EVI2fjFsMWXc6dy5JJzBsVTcQ2fVkfBvncZ6xJWG9wtBhOldG+mHkSL0+V1K/xgZz0JDO5UT5hFwHUghg==", + "dev": true, "dependencies": { - "unique-slug": "^2.0.0" + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^2.0.0" + }, + "engines": { + "node": ">=10.12.0" } }, - "node_modules/npm/node_modules/unique-slug": { - "version": "2.0.2", - "inBundle": true, - "license": "ISC", + "node_modules/v8-to-istanbul/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", + "dev": true, "dependencies": { - "imurmurhash": "^0.1.4" + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/npm/node_modules/util-deprecate": { - "version": "1.0.2", - "inBundle": true, - "license": "MIT" + "node_modules/v8-to-istanbul/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true }, - "node_modules/npm/node_modules/validate-npm-package-license": { - "version": "3.0.4", - "inBundle": true, - "license": "Apache-2.0", - "dependencies": { - "spdx-correct": "^3.0.0", - "spdx-expression-parse": "^3.0.0" + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "dev": true, + "engines": { + "node": ">= 0.8" } }, - "node_modules/npm/node_modules/validate-npm-package-name": { - "version": "4.0.0", - "inBundle": true, - "license": "ISC", + "node_modules/wait-port": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/wait-port/-/wait-port-1.1.0.tgz", + "integrity": "sha512-3e04qkoN3LxTMLakdqeWth8nih8usyg+sf1Bgdf9wwUkp05iuK1eSY/QpLvscT/+F/gA89+LpUmmgBtesbqI2Q==", + "dev": true, "dependencies": { - "builtins": "^5.0.0" + "chalk": "^4.1.2", + "commander": "^9.3.0", + "debug": "^4.3.4" + }, + "bin": { + "wait-port": "bin/wait-port.js" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": ">=10" } }, - "node_modules/npm/node_modules/walk-up-path": { - "version": "1.0.0", - "inBundle": true, - "license": "ISC" + "node_modules/wait-port/node_modules/commander": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", + "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", + "dev": true, + "engines": { + "node": "^12.20.0 || >=14" + } }, - "node_modules/npm/node_modules/wcwidth": { - "version": "1.0.1", - "inBundle": true, - "license": "MIT", + "node_modules/walker": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", + "dev": true, "dependencies": { - "defaults": "^1.0.3" + "makeerror": "1.0.12" } }, - "node_modules/npm/node_modules/which": { + "node_modules/which": { "version": "2.0.2", - "inBundle": true, - "license": "ISC", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, "dependencies": { "isexe": "^2.0.0" }, @@ -9210,79 +9024,49 @@ "node": ">= 8" } }, - "node_modules/npm/node_modules/wide-align": { - "version": "1.1.5", - "inBundle": true, - "license": "ISC", + "node_modules/which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, "dependencies": { - "string-width": "^1.0.2 || 2 || 3 || 4" + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/wrappy": { - "version": "1.0.2", - "inBundle": true, - "license": "ISC" - }, - "node_modules/npm/node_modules/write-file-atomic": { - "version": "4.0.2", - "inBundle": true, - "license": "ISC", + "node_modules/which-collection": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.1.tgz", + "integrity": "sha512-W8xeTUwaln8i3K/cY1nGXzdnVZlidBcagyNFtBdD5kxnb4TvGKR7FfSIS3mYpwWS1QUCutfKz8IY8RjftB0+1A==", + "dev": true, "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" + "is-map": "^2.0.1", + "is-set": "^2.0.1", + "is-weakmap": "^2.0.1", + "is-weakset": "^2.0.1" }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/npm/node_modules/yallist": { - "version": "4.0.0", - "inBundle": true, - "license": "ISC" - }, - "node_modules/nwsapi": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.0.tgz", - "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", - "dev": true - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", - "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==", - "dev": true, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/object-keys": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", - "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "dev": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/object.assign": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", - "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "node_modules/which-typed-array": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.9.tgz", + "integrity": "sha512-w9c4xkx6mPidwp7180ckYWfMmvxpjlZuIudNtDf4N/tTAUB8VJbX25qZoAsrtGuYNnGw3pa0AXgbGKRB8/EceA==", "dev": true, "dependencies": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "has-symbols": "^1.0.1", - "object-keys": "^1.1.1" + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0", + "is-typed-array": "^1.1.10" }, "engines": { "node": ">= 0.4" @@ -9291,9135 +9075,5408 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/object.values": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.4.tgz", - "integrity": "sha512-TnGo7j4XSnKQoK3MfvkzqKCi0nVe/D9I9IjwTNYdb/fxYHpjrluHVOgw0AF6jrRFGMPHdfuidR09tIDiIvnaSg==", + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.2" + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" }, "engines": { - "node": ">= 0.4" + "node": ">=10" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "node_modules/write-file-atomic": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", "dev": true, "dependencies": { - "ee-first": "1.1.1" + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" }, "engines": { - "node": ">= 0.8" + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" } }, - "node_modules/on-headers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", - "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "dev": true, "engines": { - "node": ">= 0.8" + "node": ">=10" } }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "dependencies": { - "wrappy": "1" - } + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "node_modules/yaml": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.3.4.tgz", + "integrity": "sha512-8aAvwVUSHpfEqTQ4w/KMlf3HcRdt50E5ODIQJBw1fQ5RL34xabzxtUlzTXVqc4rkZsPbvrXKWnABCD7kWSmocA==", "dev": true, - "dependencies": { - "mimic-fn": "^2.1.0" - }, "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">= 14" } }, - "node_modules/optionator": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", - "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", + "node_modules/yargs": { + "version": "17.6.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.6.0.tgz", + "integrity": "sha512-8H/wTDqlSwoSnScvV2N/JHfLWOKuh5MVla9hqLjK3nsfyy6Y4kDSYSvkU5YCUEPOSnRXfIyx3Sq+B/IWudTo4g==", "dev": true, "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.3" + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.0.0" }, "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/p-cancelable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", - "integrity": "sha512-s73XxOZ4zpt1edZYZzvhqFa6uvQc1vwUa0K0BdtIZgQMAJj9IbebH+JkgKZc9h+B05PKHLOTl4ajG1BmNrVZlw==", - "dev": true, - "engines": { - "node": ">=6" + "node": ">=12" } }, - "node_modules/p-limit": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", - "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", "dev": true, - "dependencies": { - "p-try": "^1.0.0" - }, "engines": { - "node": ">=4" + "node": ">=12" } }, - "node_modules/p-locate": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", "dev": true, - "dependencies": { - "p-limit": "^1.1.0" - }, "engines": { - "node": ">=4" + "node": ">=6" } }, - "node_modules/p-map": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", - "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true, - "dependencies": { - "aggregate-error": "^3.0.0" - }, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } + } + }, + "dependencies": { + "@aashutoshrathi/word-wrap": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz", + "integrity": "sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==", + "dev": true }, - "node_modules/p-try": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", - "dev": true, - "engines": { - "node": ">=4" + "@actions/core": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.1.tgz", + "integrity": "sha512-3lBR9EDAY+iYIpTnTIXmWcNbX3T2kCkAEQGIQx4NVQ0575nk2k3GRZDTPQG+vVtS2izSLmINlxXf0uLtnrTP+g==", + "requires": { + "@actions/http-client": "^2.0.1", + "uuid": "^8.3.2" } }, - "node_modules/package-json": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/package-json/-/package-json-6.5.0.tgz", - "integrity": "sha512-k3bdm2n25tkyxcjSKzB5x8kfVxlMdgsbPr0GkZcwHsLpba6cBjqCt1KlcChKEvxHIcTB1FVMuwoijZ26xex5MQ==", - "dev": true, - "dependencies": { - "got": "^9.6.0", - "registry-auth-token": "^4.0.0", - "registry-url": "^5.0.0", - "semver": "^6.2.0" - }, - "engines": { - "node": ">=8" + "@actions/github": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@actions/github/-/github-6.0.0.tgz", + "integrity": "sha512-alScpSVnYmjNEXboZjarjukQEzgCRmjMv6Xj47fsdnqGS73bjJNDpiiXmp8jr0UZLdUB6d9jW63IcmddUP+l0g==", + "requires": { + "@actions/http-client": "^2.2.0", + "@octokit/core": "^5.0.1", + "@octokit/plugin-paginate-rest": "^9.0.0", + "@octokit/plugin-rest-endpoint-methods": "^10.0.0" } }, - "node_modules/package-json/node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true, - "bin": { - "semver": "bin/semver.js" + "@actions/http-client": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.1.tgz", + "integrity": "sha512-KhC/cZsq7f8I4LfZSJKgCvEwfkE8o1538VoBeoGzokVLLnbFDEAdFD3UhoMklxo2un9NJVBdANOresx7vTHlHw==", + "requires": { + "tunnel": "^0.0.6", + "undici": "^5.25.4" } }, - "node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "@babel/code-frame": { + "version": "7.22.13", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", + "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", "dev": true, - "dependencies": { - "callsites": "^3.0.0" + "requires": { + "@babel/highlight": "^7.22.13", + "chalk": "^2.4.2" }, - "engines": { - "node": ">=6" - } - }, - "node_modules/parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", - "dev": true, "dependencies": { - "error-ex": "^1.3.1", - "json-parse-better-errors": "^1.0.1" - }, - "engines": { - "node": ">=4" + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } } }, - "node_modules/parse5": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", - "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", + "@babel/compat-data": { + "version": "7.14.4", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.14.4.tgz", + "integrity": "sha512-i2wXrWQNkH6JplJQGn3Rd2I4Pij8GdHkXwHMxm+zV5YG/Jci+bCNrWZEWC4o+umiDkRrRs4dVzH3X4GP7vyjQQ==", "dev": true }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "@babel/core": { + "version": "7.14.3", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.14.3.tgz", + "integrity": "sha512-jB5AmTKOCSJIZ72sd78ECEhuPiDMKlQdDI/4QRI6lzYATx5SSogS1oQA2AoPecRCknm30gHi2l+QVvNUu3wZAg==", "dev": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true, - "engines": { - "node": ">=4" + "requires": { + "@babel/code-frame": "^7.12.13", + "@babel/generator": "^7.14.3", + "@babel/helper-compilation-targets": "^7.13.16", + "@babel/helper-module-transforms": "^7.14.2", + "@babel/helpers": "^7.14.0", + "@babel/parser": "^7.14.3", + "@babel/template": "^7.12.13", + "@babel/traverse": "^7.14.2", + "@babel/types": "^7.14.2", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.1.2", + "semver": "^6.3.0", + "source-map": "^0.5.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "@babel/generator": { + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.0.tgz", + "integrity": "sha512-lN85QRR+5IbYrMWM6Y4pE/noaQtg4pNiqeNGX60eqOfo6gtEj6uw/JagelB8vVztSd7R6M5n1+PQkDbHbBRU4g==", "dev": true, - "engines": { - "node": ">=0.10.0" + "requires": { + "@babel/types": "^7.23.0", + "@jridgewell/gen-mapping": "^0.3.2", + "@jridgewell/trace-mapping": "^0.3.17", + "jsesc": "^2.5.1" + }, + "dependencies": { + "@jridgewell/trace-mapping": { + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + } } }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "@babel/helper-compilation-targets": { + "version": "7.14.4", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.14.4.tgz", + "integrity": "sha512-JgdzOYZ/qGaKTVkn5qEDV/SXAh8KcyUVkCoSWGN8T3bwrgd6m+/dJa2kVGi6RJYJgEYPBdZ84BZp9dUjNWkBaA==", "dev": true, - "engines": { - "node": ">=8" + "requires": { + "@babel/compat-data": "^7.14.4", + "@babel/helper-validator-option": "^7.12.17", + "browserslist": "^4.16.6", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } } }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true - }, - "node_modules/path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", + "@babel/helper-environment-visitor": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", "dev": true }, - "node_modules/path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "@babel/helper-function-name": { + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dev": true, - "engines": { - "node": ">=8" + "requires": { + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" } }, - "node_modules/picomatch": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", - "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", + "@babel/helper-hoist-variables": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", + "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", "dev": true, - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" + "requires": { + "@babel/types": "^7.22.5" } }, - "node_modules/pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "@babel/helper-member-expression-to-functions": { + "version": "7.13.12", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.13.12.tgz", + "integrity": "sha512-48ql1CLL59aKbU94Y88Xgb2VFy7a95ykGRbJJaaVv+LX5U8wFpLfiGXJJGUozsmA1oEh/o5Bp60Voq7ACyA/Sw==", "dev": true, - "engines": { - "node": ">=4" + "requires": { + "@babel/types": "^7.13.12" } }, - "node_modules/pirates": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", - "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==", + "@babel/helper-module-imports": { + "version": "7.13.12", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.13.12.tgz", + "integrity": "sha512-4cVvR2/1B693IuOvSI20xqqa/+bl7lqAMR59R4iu39R9aOX8/JoYY1sFaNvUMyMBGnHdwvJgUrzNLoUZxXypxA==", "dev": true, - "engines": { - "node": ">= 6" + "requires": { + "@babel/types": "^7.13.12" } }, - "node_modules/pkg-dir": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", - "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", + "@babel/helper-module-transforms": { + "version": "7.14.2", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.14.2.tgz", + "integrity": "sha512-OznJUda/soKXv0XhpvzGWDnml4Qnwp16GN+D/kZIdLsWoHj05kyu8Rm5kXmMef+rVJZ0+4pSGLkeixdqNUATDA==", "dev": true, - "dependencies": { - "find-up": "^2.1.0" - }, - "engines": { - "node": ">=4" + "requires": { + "@babel/helper-module-imports": "^7.13.12", + "@babel/helper-replace-supers": "^7.13.12", + "@babel/helper-simple-access": "^7.13.12", + "@babel/helper-split-export-declaration": "^7.12.13", + "@babel/helper-validator-identifier": "^7.14.0", + "@babel/template": "^7.12.13", + "@babel/traverse": "^7.14.2", + "@babel/types": "^7.14.2" } }, - "node_modules/pkg-up": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-2.0.0.tgz", - "integrity": "sha1-yBmscoBZpGHKscOImivjxJoATX8=", + "@babel/helper-optimise-call-expression": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.12.13.tgz", + "integrity": "sha512-BdWQhoVJkp6nVjB7nkFWcn43dkprYauqtk++Py2eaf/GRDFm5BxRqEIZCiHlZUGAVmtwKcsVL1dC68WmzeFmiA==", "dev": true, - "dependencies": { - "find-up": "^2.1.0" - }, - "engines": { - "node": ">=4" + "requires": { + "@babel/types": "^7.12.13" } }, - "node_modules/please-upgrade-node": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", - "integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==", - "dev": true, - "dependencies": { - "semver-compare": "^1.0.0" - } + "@babel/helper-plugin-utils": { + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.19.0.tgz", + "integrity": "sha512-40Ryx7I8mT+0gaNxm8JGTZFUITNqdLAgdg0hXzeVZxVD6nFsdhQvip6v8dqkRHzsz1VFpFAaOCHNn0vKBL7Czw==", + "dev": true }, - "node_modules/pluralize": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", - "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "@babel/helper-replace-supers": { + "version": "7.14.4", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.14.4.tgz", + "integrity": "sha512-zZ7uHCWlxfEAAOVDYQpEf/uyi1dmeC7fX4nCf2iz9drnCwi1zvwXL3HwWWNXUQEJ1k23yVn3VbddiI9iJEXaTQ==", "dev": true, - "engines": { - "node": ">=4" + "requires": { + "@babel/helper-member-expression-to-functions": "^7.13.12", + "@babel/helper-optimise-call-expression": "^7.12.13", + "@babel/traverse": "^7.14.2", + "@babel/types": "^7.14.4" } }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "@babel/helper-simple-access": { + "version": "7.13.12", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.13.12.tgz", + "integrity": "sha512-7FEjbrx5SL9cWvXioDbnlYTppcZGuCY6ow3/D5vMggb2Ywgu4dMrpTJX0JdQAIcRRUElOIxF3yEooa9gUb9ZbA==", "dev": true, - "engines": { - "node": ">= 0.8.0" + "requires": { + "@babel/types": "^7.13.12" } }, - "node_modules/prepend-http": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-2.0.0.tgz", - "integrity": "sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=", + "@babel/helper-split-export-declaration": { + "version": "7.22.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", + "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", "dev": true, - "engines": { - "node": ">=4" + "requires": { + "@babel/types": "^7.22.5" } }, - "node_modules/prettier": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.4.1.tgz", - "integrity": "sha512-9fbDAXSBcc6Bs1mZrDYb3XKzDLm4EXXL9sC1LqKP5rZkT6KRr/rf9amVUcODVXgguK/isJz0d0hP72WeaKWsvA==", - "dev": true, - "bin": { - "prettier": "bin-prettier.js" - }, - "engines": { - "node": ">=10.13.0" - } + "@babel/helper-string-parser": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz", + "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==", + "dev": true }, - "node_modules/prettier-linter-helpers": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", - "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", - "dev": true, - "dependencies": { - "fast-diff": "^1.1.2" - }, - "engines": { - "node": ">=6.0.0" - } + "@babel/helper-validator-identifier": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "dev": true }, - "node_modules/pretty-format": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", - "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", - "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1", - "ansi-styles": "^5.0.0", - "react-is": "^17.0.1" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } + "@babel/helper-validator-option": { + "version": "7.12.17", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.12.17.tgz", + "integrity": "sha512-TopkMDmLzq8ngChwRlyjR6raKD6gMSae4JdYDB8bByKreQgG0RBTuKe9LRxW3wFtUnjxOPRKBDwEH6Mg5KeDfw==", + "dev": true }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "@babel/helpers": { + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.14.0.tgz", + "integrity": "sha512-+ufuXprtQ1D1iZTO/K9+EBRn+qPWMJjZSw/S0KlFrxCw4tkrzv9grgpDHkY9MeQTjTY8i2sp7Jep8DfU6tN9Mg==", "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" + "requires": { + "@babel/template": "^7.12.13", + "@babel/traverse": "^7.14.0", + "@babel/types": "^7.14.0" } }, - "node_modules/progress": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", - "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "@babel/highlight": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", + "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "dev": true, - "dependencies": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" + "requires": { + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0" }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "dev": true, "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } } }, - "node_modules/psl": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", - "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "@babel/parser": { + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.0.tgz", + "integrity": "sha512-vvPKKdMemU85V9WE/l5wZEmImpCtLqbnTvqDS2U1fJ96KrxoW7KrXhNsNCblQlg8Ck4b85yxdTyelsMUgFUXiw==", "dev": true }, - "node_modules/pump": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", - "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" + "@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" } }, - "node_modules/punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", "dev": true, - "engines": { - "node": ">=6" + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" } }, - "node_modules/pupa": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/pupa/-/pupa-2.1.1.tgz", - "integrity": "sha512-l1jNAspIBSFqbT+y+5FosojNpVpF94nlI+wDUpqP9enwOTfHx9f0gh5nB96vl+6yTpsJsypeNrwfzPrKuHB41A==", + "@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", "dev": true, - "dependencies": { - "escape-goat": "^2.0.0" - }, - "engines": { - "node": ">=8" + "requires": { + "@babel/helper-plugin-utils": "^7.12.13" } }, - "node_modules/qs": { - "version": "6.7.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", - "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==", + "@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", "dev": true, - "engines": { - "node": ">=0.6" + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" } }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "@babel/plugin-syntax-jsx": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.18.6.tgz", + "integrity": "sha512-6mmljtAedFGTWu2p/8WIORGwy+61PLgOMPOdazc7YoJ9ZCWUyFy3A6CpPkRKLKD1ToAesxX8KGEViAiLo9N+7Q==", "dev": true, - "engines": { - "node": ">= 0.6" + "requires": { + "@babel/helper-plugin-utils": "^7.18.6" } }, - "node_modules/raw-body": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", - "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", + "@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", "dev": true, - "dependencies": { - "bytes": "3.1.0", - "http-errors": "1.7.2", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" } }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", "dev": true, - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" } }, - "node_modules/rc/node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "dev": true - }, - "node_modules/rc/node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", "dev": true, - "engines": { - "node": ">=0.10.0" + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" } }, - "node_modules/react-is": { - "version": "17.0.2", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", - "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", - "dev": true + "@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } }, - "node_modules/read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", + "@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", "dev": true, - "dependencies": { - "load-json-file": "^4.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" - }, - "engines": { - "node": ">=4" + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" } }, - "node_modules/read-pkg-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", - "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", + "@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", "dev": true, - "dependencies": { - "find-up": "^2.0.0", - "read-pkg": "^3.0.0" - }, - "engines": { - "node": ">=4" + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" } }, - "node_modules/read-pkg/node_modules/path-type": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", - "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "@babel/plugin-syntax-top-level-await": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.12.13.tgz", + "integrity": "sha512-A81F9pDwyS7yM//KwbCSDqy3Uj4NMIurtplxphWxoYtNPov7cJsDkAFNNyVlIZ3jwGycVsurZ+LtOA8gZ376iQ==", "dev": true, - "dependencies": { - "pify": "^3.0.0" - }, - "engines": { - "node": ">=4" + "requires": { + "@babel/helper-plugin-utils": "^7.12.13" } }, - "node_modules/readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" + "@babel/plugin-syntax-typescript": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.18.6.tgz", + "integrity": "sha512-mAWAuq4rvOepWCBid55JuRNvpTNf2UGVgoz4JV0fXEKolsVZDzsa4NqCef758WZJj/GDu0gVGItjKFiClTAmZA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.18.6" } }, - "node_modules/regexpp": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.1.0.tgz", - "integrity": "sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q==", + "@babel/runtime": { + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.21.0.tgz", + "integrity": "sha512-xwII0//EObnq89Ji5AKYQaRYiW/nZ3llSv29d49IuxPhKbtJoLP+9QUUZ4nVragQVtaVGeZrpB+ZtG/Pdy/POw==", "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" + "requires": { + "regenerator-runtime": "^0.13.11" } }, - "node_modules/registry-auth-token": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-4.2.1.tgz", - "integrity": "sha512-6gkSb4U6aWJB4SF2ZvLb76yCBjcvufXBqvvEx1HbmKPkutswjW1xNVRY0+daljIYRbogN7O0etYSlbiaEQyMyw==", + "@babel/template": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", + "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", "dev": true, - "dependencies": { - "rc": "^1.2.8" - }, - "engines": { - "node": ">=6.0.0" + "requires": { + "@babel/code-frame": "^7.22.13", + "@babel/parser": "^7.22.15", + "@babel/types": "^7.22.15" } }, - "node_modules/registry-url": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-5.1.0.tgz", - "integrity": "sha512-8acYXXTI0AkQv6RAOjE3vOaIXZkT9wo4LOFbBKYQEEnnMNBpKqdUrI6S4NT0KPIo/WVvJ5tE/X5LF/TQUf0ekw==", - "dev": true, - "dependencies": { - "rc": "^1.2.8" + "@babel/traverse": { + "version": "7.23.2", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.2.tgz", + "integrity": "sha512-azpe59SQ48qG6nu2CzcMLbxUudtN+dOM9kDbUqGq3HXUJRlo7i8fvPoxQUzYgLZ4cMVmuZgm8vvBpNeRhd6XSw==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.22.13", + "@babel/generator": "^7.23.0", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/parser": "^7.23.0", + "@babel/types": "^7.23.0", + "debug": "^4.1.0", + "globals": "^11.1.0" }, - "engines": { - "node": ">=8" + "dependencies": { + "globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true + } } }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "@babel/types": { + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.0.tgz", + "integrity": "sha512-0oIyUfKoI3mSqMvsxBdclDwxXKXAUA8v/apZbc+iSyARYou1o8ZGDxbUYyLFoW2arqS2jDGqJuZvv1d/io1axg==", "dev": true, - "engines": { - "node": ">=0.10.0" + "requires": { + "@babel/helper-string-parser": "^7.22.5", + "@babel/helper-validator-identifier": "^7.22.20", + "to-fast-properties": "^2.0.0" } }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "@balena/dockerignore": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@balena/dockerignore/-/dockerignore-1.0.2.tgz", + "integrity": "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q==" + }, + "@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "dev": true + }, + "@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", "dev": true, - "engines": { - "node": ">=0.10.0" + "requires": { + "@jridgewell/trace-mapping": "0.3.9" } }, - "node_modules/resolve": { - "version": "1.20.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", - "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "@eslint-community/eslint-utils": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", + "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", "dev": true, - "dependencies": { - "is-core-module": "^2.2.0", - "path-parse": "^1.0.6" + "requires": { + "eslint-visitor-keys": "^3.3.0" }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "dependencies": { + "eslint-visitor-keys": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "dev": true + } } }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "@eslint-community/regexpp": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.6.2.tgz", + "integrity": "sha512-pPTNuaAG3QMH+buKyBIGJs3g/S5y0caxw0ygM3YyE6yJFySwiGGSzA+mM3KJ8QQvzeLh3blwgSonkFjgQdxzMw==", + "dev": true + }, + "@eslint/eslintrc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", + "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", "dev": true, - "dependencies": { + "requires": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + } + }, + "@eslint/js": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.0.tgz", + "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", + "dev": true + }, + "@fastify/busboy": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.0.0.tgz", + "integrity": "sha512-JUFJad5lv7jxj926GPgymrWQxxjPYuJNiNjNMzqT+HiuP6Vl3dk5xzG+8sTX96np0ZAluvaMzPsjhHZ5rNuNQQ==" + }, + "@github/browserslist-config": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@github/browserslist-config/-/browserslist-config-1.0.0.tgz", + "integrity": "sha512-gIhjdJp/c2beaIWWIlsXdqXVRUz3r2BxBCpfz/F3JXHvSAQ1paMYjLH+maEATtENg+k5eLV7gA+9yPp762ieuw==", + "dev": true + }, + "@humanwhocodes/config-array": { + "version": "0.11.14", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", + "integrity": "sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==", + "dev": true, + "requires": { + "@humanwhocodes/object-schema": "^2.0.2", + "debug": "^4.3.1", + "minimatch": "^3.0.5" + } + }, + "@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true + }, + "@humanwhocodes/object-schema": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.2.tgz", + "integrity": "sha512-6EwiSjwWYP7pTckG6I5eyFANjPhmPjUX9JRLUSfNPC7FX7zK9gyZAfUEaECL6ALTpGX5AjnBq3C9XmVWPitNpw==", + "dev": true + }, + "@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "requires": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", "resolve-from": "^5.0.0" }, - "engines": { - "node": ">=8" + "dependencies": { + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + } } }, - "node_modules/resolve-cwd/node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true + }, + "@jest/console": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", + "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", "dev": true, - "engines": { - "node": ">=8" + "requires": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0" } }, - "node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "@jest/core": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", + "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", "dev": true, - "engines": { - "node": ">=4" + "requires": { + "@jest/console": "^29.7.0", + "@jest/reporters": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.7.0", + "jest-config": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-resolve-dependencies": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "jest-watcher": "^29.7.0", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" } }, - "node_modules/resolve.exports": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-1.1.0.tgz", - "integrity": "sha512-J1l+Zxxp4XK3LUDZ9m60LRJF/mAe4z6a4xyabPHk7pvK5t35dACV32iIjJDFeWZFfZlO29w6SZ67knR0tHzJtQ==", + "@jest/environment": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", + "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", "dev": true, - "engines": { - "node": ">=10" + "requires": { + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0" } }, - "node_modules/responselike": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/responselike/-/responselike-1.0.2.tgz", - "integrity": "sha1-kYcg7ztjHFZCvgaPFa3lpG9Loec=", + "@jest/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", "dev": true, - "dependencies": { - "lowercase-keys": "^1.0.0" + "requires": { + "expect": "^29.7.0", + "jest-snapshot": "^29.7.0" } }, - "node_modules/restore-cursor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", - "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "@jest/expect-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", + "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", "dev": true, - "dependencies": { - "onetime": "^5.1.0", - "signal-exit": "^3.0.2" - }, - "engines": { - "node": ">=8" + "requires": { + "jest-get-type": "^29.6.3" } }, - "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "@jest/fake-timers": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", + "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", "dev": true, - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" + "requires": { + "@jest/types": "^29.6.3", + "@sinonjs/fake-timers": "^10.0.2", + "@types/node": "*", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" } }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "@jest/globals": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", + "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", "dev": true, - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "requires": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/types": "^29.6.3", + "jest-mock": "^29.7.0" } }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "@jest/reporters": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", + "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" + "requires": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "dependencies": { + "@jridgewell/trace-mapping": { + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } }, - { - "type": "consulting", - "url": "https://feross.org/support" + "istanbul-lib-instrument": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.1.tgz", + "integrity": "sha512-EAMEJBsYuyyztxMxW3g7ugGPkrZsV57v0Hmv3mm1uQsmB+QnZuepg731CRaIgeUVSdmsTngOkSnauNF8p7FIhA==", + "dev": true, + "requires": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + } } - ], - "dependencies": { - "queue-microtask": "^1.2.2" } }, - "node_modules/rxjs": { - "version": "6.6.7", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", - "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", "dev": true, - "dependencies": { - "tslib": "^1.9.0" - }, - "engines": { - "npm": ">=2.0.0" + "requires": { + "@sinclair/typebox": "^0.27.8" } }, - "node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "node_modules/saxes": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", - "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", + "@jest/source-map": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", + "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", "dev": true, - "dependencies": { - "xmlchars": "^2.2.0" + "requires": { + "@jridgewell/trace-mapping": "^0.3.18", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" }, - "engines": { - "node": ">=10" - } - }, - "node_modules/semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", - "dev": true, "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" + "@jridgewell/trace-mapping": { + "version": "0.3.19", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz", + "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + } } }, - "node_modules/semver-compare": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", - "integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w=", - "dev": true - }, - "node_modules/semver-diff": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-3.1.1.tgz", - "integrity": "sha512-GX0Ix/CJcHyB8c4ykpHGIAvLyOwOobtM/8d+TQkAd81/bEjgPHrfba41Vpesr7jX/t8Uh+R3EX9eAS5be+jQYg==", + "@jest/test-result": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", + "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", "dev": true, - "dependencies": { - "semver": "^6.3.0" - }, - "engines": { - "node": ">=8" + "requires": { + "@jest/console": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" } }, - "node_modules/semver-diff/node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "@jest/test-sequencer": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", + "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", "dev": true, - "bin": { - "semver": "bin/semver.js" + "requires": { + "@jest/test-result": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "slash": "^3.0.0" } }, - "node_modules/send": { - "version": "0.17.1", - "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", - "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", + "@jest/transform": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", + "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", "dev": true, - "dependencies": { - "debug": "2.6.9", - "depd": "~1.1.2", - "destroy": "~1.0.4", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "~1.7.2", - "mime": "1.6.0", - "ms": "2.1.1", - "on-finished": "~2.3.0", - "range-parser": "~1.2.1", - "statuses": "~1.5.0" + "requires": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.2" }, - "engines": { - "node": ">= 0.8.0" + "dependencies": { + "@jridgewell/trace-mapping": { + "version": "0.3.18", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz", + "integrity": "sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "3.1.0", + "@jridgewell/sourcemap-codec": "1.4.14" + } + }, + "convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + } } }, - "node_modules/send/node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "@jest/types": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", + "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", "dev": true, - "dependencies": { - "ms": "2.0.0" + "requires": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" } }, - "node_modules/send/node_modules/debug/node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - }, - "node_modules/serve-static": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", - "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", + "@jridgewell/gen-mapping": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", + "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", "dev": true, - "dependencies": { - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.17.1" - }, - "engines": { - "node": ">= 0.8.0" + "requires": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" } }, - "node_modules/server-destroy": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/server-destroy/-/server-destroy-1.0.1.tgz", - "integrity": "sha1-8Tv5KOQrnD55OD5hzDmYtdFObN0=", + "@jridgewell/resolve-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", + "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", "dev": true }, - "node_modules/setprototypeof": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", - "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==", + "@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", "dev": true }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "@jridgewell/sourcemap-codec": { + "version": "1.4.14", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", + "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", + "dev": true + }, + "@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", "dev": true, - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" + "requires": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "dev": true, - "engines": { - "node": ">=8" + "requires": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" } }, - "node_modules/signal-exit": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", - "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", - "dev": true - }, - "node_modules/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "dev": true }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dev": true, - "engines": { - "node": ">=8" + "requires": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" } }, - "node_modules/slice-ansi": { + "@octokit/auth-token": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", - "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/slice-ansi?sponsor=1" - } + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-4.0.0.tgz", + "integrity": "sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA==" }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "engines": { - "node": ">=0.10.0" + "@octokit/core": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-5.2.0.tgz", + "integrity": "sha512-1LFfa/qnMQvEOAdzlQymH0ulepxbxnCYAKJZfMci/5XJyIHWgEYnDmgnKakbTh7CH2tFQ5O60oYDvns4i9RAIg==", + "requires": { + "@octokit/auth-token": "^4.0.0", + "@octokit/graphql": "^7.1.0", + "@octokit/request": "^8.3.1", + "@octokit/request-error": "^5.1.0", + "@octokit/types": "^13.0.0", + "before-after-hook": "^2.2.0", + "universal-user-agent": "^6.0.0" } }, - "node_modules/source-map-support": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", - "dev": true, - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" + "@octokit/endpoint": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.5.tgz", + "integrity": "sha512-ekqR4/+PCLkEBF6qgj8WqJfvDq65RH85OAgrtnVp1mSxaXF03u2xW/hUdweGS5654IlC0wkNYC18Z50tSYTAFw==", + "requires": { + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" } }, - "node_modules/spdx-correct": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", - "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", - "dev": true, + "@octokit/graphql": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-7.1.0.tgz", + "integrity": "sha512-r+oZUH7aMFui1ypZnAvZmn0KSqAUgE1/tUXIWaqUCa1758ts/Jio84GZuzsvUkme98kv0WFY8//n0J1Z+vsIsQ==", + "requires": { + "@octokit/request": "^8.3.0", + "@octokit/types": "^13.0.0", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/openapi-types": { + "version": "22.2.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-22.2.0.tgz", + "integrity": "sha512-QBhVjcUa9W7Wwhm6DBFu6ZZ+1/t/oYxqc2tp81Pi41YNuJinbFRx8B133qVOrAaBbF7D/m0Et6f9/pZt9Rc+tg==" + }, + "@octokit/plugin-paginate-rest": { + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-9.2.1.tgz", + "integrity": "sha512-wfGhE/TAkXZRLjksFXuDZdmGnJQHvtU/joFQdweXUgzo1XwvBCD4o4+75NtFfjfLK5IwLf9vHTfSiU3sLRYpRw==", + "requires": { + "@octokit/types": "^12.6.0" + }, "dependencies": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" + "@octokit/openapi-types": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", + "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==" + }, + "@octokit/types": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", + "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", + "requires": { + "@octokit/openapi-types": "^20.0.0" + } + } } }, - "node_modules/spdx-exceptions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", - "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", + "@octokit/plugin-rest-endpoint-methods": { + "version": "10.4.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-10.4.1.tgz", + "integrity": "sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg==", + "requires": { + "@octokit/types": "^12.6.0" + }, + "dependencies": { + "@octokit/openapi-types": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", + "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==" + }, + "@octokit/types": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", + "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", + "requires": { + "@octokit/openapi-types": "^20.0.0" + } + } + } + }, + "@octokit/request": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.0.tgz", + "integrity": "sha512-9Bb014e+m2TgBeEJGEbdplMVWwPmL1FPtggHQRkV+WVsMggPtEkLKPlcVYm/o8xKLkpJ7B+6N8WfQMtDLX2Dpw==", + "requires": { + "@octokit/endpoint": "^9.0.1", + "@octokit/request-error": "^5.1.0", + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/request-error": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.0.tgz", + "integrity": "sha512-GETXfE05J0+7H2STzekpKObFe765O5dlAKUTLNGeH+x47z7JjXHfsHKo5z21D/o/IOZTUEI6nyWyR+bZVP/n5Q==", + "requires": { + "@octokit/types": "^13.1.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + } + }, + "@octokit/types": { + "version": "13.5.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-13.5.0.tgz", + "integrity": "sha512-HdqWTf5Z3qwDVlzCrP8UJquMwunpDiMPt5er+QjGzL4hqr/vBVY/MauQgS1xWxCDT1oMx1EULyqxncdCY/NVSQ==", + "requires": { + "@octokit/openapi-types": "^22.2.0" + } + }, + "@octokit/webhooks-types": { + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/@octokit/webhooks-types/-/webhooks-types-7.5.1.tgz", + "integrity": "sha512-1dozxWEP8lKGbtEu7HkRbK1F/nIPuJXNfT0gd96y6d3LcHZTtRtlf8xz3nicSJfesADxJyDh+mWBOsdLkqgzYw==" + }, + "@pkgr/core": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.1.0.tgz", + "integrity": "sha512-Zwq5OCzuwJC2jwqmpEQt7Ds1DTi6BWSwoGkbb1n9pO3hzb35BoJELx7c0T23iDkBGkh2e7tvOtjF3tr3OaQHDQ==", "dev": true }, - "node_modules/spdx-expression-parse": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", - "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "@sinclair/typebox": { + "version": "0.27.8", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", + "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "dev": true + }, + "@sinonjs/commons": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz", + "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==", "dev": true, - "dependencies": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" + "requires": { + "type-detect": "4.0.8" + } + }, + "@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "dev": true, + "requires": { + "@sinonjs/commons": "^3.0.0" } }, - "node_modules/spdx-license-ids": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.9.tgz", - "integrity": "sha512-Ki212dKK4ogX+xDo4CtOZBVIwhsKBEfsEEcwmJfLQzirgc2jIWdzg40Unxz/HzEUqM1WFzVlQSMF9kZZ2HboLQ==", + "@tsconfig/node10": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.8.tgz", + "integrity": "sha512-6XFfSQmMgq0CFLY1MslA/CPUfhIL919M1rMsa5lP2P097N2Wd1sSX0tx1u4olM16fLNhtHZpRhedZJphNJqmZg==", "dev": true }, - "node_modules/split-ca": { + "@tsconfig/node12": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.9.tgz", + "integrity": "sha512-/yBMcem+fbvhSREH+s14YJi18sp7J9jpuhYByADT2rypfajMZZN4WQ6zBGgBKp53NKmqI36wFYDb3yaMPurITw==", + "dev": true + }, + "@tsconfig/node14": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/split-ca/-/split-ca-1.0.1.tgz", - "integrity": "sha1-bIOv82kvphJW4M0ZfgXp3hV2kaY=" + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.1.tgz", + "integrity": "sha512-509r2+yARFfHHE7T6Puu2jjkoycftovhXRqW328PDXTVGKihlb1P8Z9mMZH04ebyajfRY7dedfGynlrFHJUQCg==", + "dev": true }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "@tsconfig/node16": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.2.tgz", + "integrity": "sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA==", "dev": true }, - "node_modules/ssh2": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.6.0.tgz", - "integrity": "sha512-lxc+uvXqOxyQ99N2M7k5o4pkYDO5GptOTYduWw7hIM41icxvoBcCNHcj+LTKrjkL0vFcAl+qfZekthoSFRJn2Q==", - "hasInstallScript": true, - "dependencies": { - "asn1": "^0.2.4", - "bcrypt-pbkdf": "^1.0.2" - }, - "engines": { - "node": ">=10.16.0" - }, - "optionalDependencies": { - "cpu-features": "0.0.2", - "nan": "^2.15.0" + "@types/babel__core": { + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.1.tgz", + "integrity": "sha512-aACu/U/omhdk15O4Nfb+fHgH/z3QsfQzpnvRZhYhThms83ZnAOZz7zZAWO7mn2yyNQaA4xTO8GLK3uqFU4bYYw==", + "dev": true, + "requires": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" } }, - "node_modules/stack-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.3.tgz", - "integrity": "sha512-gL//fkxfWUsIlFL2Tl42Cl6+HFALEaB1FU76I/Fy+oZjRreP7OPMXFlGbxM7NQsI0ZpUfw76sHnv0WNYuTb7Iw==", + "@types/babel__generator": { + "version": "7.6.4", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", + "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", "dev": true, - "dependencies": { - "escape-string-regexp": "^2.0.0" - }, - "engines": { - "node": ">=10" + "requires": { + "@babel/types": "^7.0.0" } }, - "node_modules/stack-utils/node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "@types/babel__template": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", + "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", "dev": true, - "engines": { - "node": ">=8" + "requires": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" } }, - "node_modules/statuses": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", - "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "@types/babel__traverse": { + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.1.tgz", + "integrity": "sha512-MitHFXnhtgwsGZWtT68URpOvLN4EREih1u3QtQiN4VdAxWKRVvGCSvw/Qth0M0Qq3pJpnGOu5JaM/ydK7OGbqg==", "dev": true, - "engines": { - "node": ">= 0.6" + "requires": { + "@babel/types": "^7.20.7" } }, - "node_modules/steno": { - "version": "0.4.4", - "resolved": "https://registry.npmjs.org/steno/-/steno-0.4.4.tgz", - "integrity": "sha1-BxEFvfwobmYVwEA8J+nXtdy4Vcs=", + "@types/docker-modem": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/docker-modem/-/docker-modem-3.0.2.tgz", + "integrity": "sha512-qC7prjoEYR2QEe6SmCVfB1x3rfcQtUr1n4x89+3e0wSTMQ/KYCyf+/RAA9n2tllkkNc6//JMUZePdFRiGIWfaQ==", "dev": true, - "dependencies": { - "graceful-fs": "^4.1.3" + "requires": { + "@types/node": "*", + "@types/ssh2": "*" } }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "dependencies": { - "safe-buffer": "~5.2.0" + "@types/dockerode": { + "version": "3.3.28", + "resolved": "https://registry.npmjs.org/@types/dockerode/-/dockerode-3.3.28.tgz", + "integrity": "sha512-RjY96chW88t2QvSebCsec+mQYo3/nyOr+/tVcE+0ynlOg2m/i9wPE52DhptzF75QDlhv2uDYVPqKfHKeGTn6Fg==", + "dev": true, + "requires": { + "@types/docker-modem": "*", + "@types/node": "*", + "@types/ssh2": "*" } }, - "node_modules/string_decoder/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/string-argv": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.1.tgz", - "integrity": "sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg==", + "@types/graceful-fs": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.5.tgz", + "integrity": "sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw==", "dev": true, - "engines": { - "node": ">=0.6.19" + "requires": { + "@types/node": "*" } }, - "node_modules/string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "@types/istanbul-lib-coverage": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz", + "integrity": "sha512-sz7iLqvVUg1gIedBOvlkxPlc8/uVzyS5OwGz1cKjXzkl3FpL3al0crU8YGU1WoHkxn0Wxbw5tyi6hvzJKNzFsw==", + "dev": true + }, + "@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", "dev": true, - "dependencies": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" + "requires": { + "@types/istanbul-lib-coverage": "*" } }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "@types/istanbul-reports": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", + "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", "dev": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" + "requires": { + "@types/istanbul-lib-report": "*" } }, - "node_modules/string.prototype.trimend": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", - "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "@types/jest": { + "version": "29.5.12", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.12.tgz", + "integrity": "sha512-eDC8bTvT/QhYdxJAulQikueigY5AsdBRH2yDKW3yveW7svY3+DzN84/2NUgkw10RTiJbWqZrTtoGVdYlvFJdLw==", "dev": true, - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "requires": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" } }, - "node_modules/string.prototype.trimstart": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", - "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "@types/json-schema": { + "version": "7.0.12", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.12.tgz", + "integrity": "sha512-Hr5Jfhc9eYOQNPYO5WLDq/n4jqijdHNlDXjuAQkkt+mWdQR+XJToOHrsD4cPaMXpn6KO7y2+wM8AZEs8VpBLVA==", + "dev": true + }, + "@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "dev": true + }, + "@types/node": { + "version": "20.12.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.7.tgz", + "integrity": "sha512-wq0cICSkRLVaf3UGLMGItu/PtdY7oaXaI/RVU+xliKVOtRna3PRY57ZDfztpDL0n11vfymMUnXv8QwYCO7L1wg==", "dev": true, - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "requires": { + "undici-types": "~5.26.4" } }, - "node_modules/stringify-object": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", - "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", + "@types/node-forge": { + "version": "1.3.11", + "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.11.tgz", + "integrity": "sha512-FQx220y22OKNTqaByeBGqHWYz4cl94tpcxeFdvBo3wjG6XPBuZ0BNgNZRV5J5TFmmcsJ4IzsLkmGRiQbnYsBEQ==", "dev": true, - "dependencies": { - "get-own-enumerable-property-symbols": "^3.0.0", - "is-obj": "^1.0.1", - "is-regexp": "^1.0.0" - }, - "engines": { - "node": ">=4" + "requires": { + "@types/node": "*" } }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" + "@types/semver": { + "version": "7.5.8", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", + "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==", + "dev": true + }, + "@types/ssh2": { + "version": "1.11.7", + "resolved": "https://registry.npmjs.org/@types/ssh2/-/ssh2-1.11.7.tgz", + "integrity": "sha512-MaVSlZOiekRUHnxL2NAmDkcU3+bTwz+ZRktLygjQCnxhLjDzN+XnsG6JUdoocmfxatMiqFo/6eb48uVqFaxBsg==", + "dev": true, + "requires": { + "@types/node": "^18.11.18" }, - "engines": { - "node": ">=8" + "dependencies": { + "@types/node": { + "version": "18.16.17", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.16.17.tgz", + "integrity": "sha512-QAkjjRA1N7gPJeAP4WLXZtYv6+eMXFNviqktCDt4GLcmCugMr5BcRHfkOjCQzvCsnMp+L79a54zBkbw356xv9Q==", + "dev": true + } } }, - "node_modules/strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "@types/stack-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", + "dev": true + }, + "@types/tar-stream": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/tar-stream/-/tar-stream-3.1.3.tgz", + "integrity": "sha512-Zbnx4wpkWBMBSu5CytMbrT5ZpMiF55qgM+EpHzR4yIDu7mv52cej8hTkOc6K+LzpkOAbxwn/m7j3iO+/l42YkQ==", "dev": true, - "engines": { - "node": ">=8" + "requires": { + "@types/node": "*" } }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "@types/yargs": { + "version": "17.0.13", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.13.tgz", + "integrity": "sha512-9sWaruZk2JGxIQU+IhI1fhPYRcQ0UuTNuKuCW9bR5fp7qi2Llf7WDzNa17Cy7TKnh3cdxDOiyTu6gaLS0eDatg==", "dev": true, - "engines": { - "node": ">=6" + "requires": { + "@types/yargs-parser": "*" } }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "@types/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", + "dev": true + }, + "@typescript-eslint/eslint-plugin": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.39.0.tgz", + "integrity": "sha512-xVfKOkBm5iWMNGKQ2fwX5GVgBuHmZBO1tCRwXmY5oAIsPscfwm2UADDuNB8ZVYCtpQvJK4xpjrK7jEhcJ0zY9A==", "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "optional": true, + "peer": true, + "requires": { + "@typescript-eslint/scope-manager": "5.39.0", + "@typescript-eslint/type-utils": "5.39.0", + "@typescript-eslint/utils": "5.39.0", + "debug": "^4.3.4", + "ignore": "^5.2.0", + "regexpp": "^3.2.0", + "semver": "^7.3.7", + "tsutils": "^3.21.0" } }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "@typescript-eslint/parser": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", + "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", "dev": true, - "dependencies": { - "has-flag": "^4.0.0" + "requires": { + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", + "debug": "^4.3.4" }, - "engines": { - "node": ">=8" + "dependencies": { + "@typescript-eslint/scope-manager": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", + "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", + "dev": true, + "requires": { + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0" + } + }, + "@typescript-eslint/types": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", + "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", + "dev": true + }, + "@typescript-eslint/typescript-estree": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", + "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", + "dev": true, + "requires": { + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "semver": "^7.3.7", + "tsutils": "^3.21.0" + } + }, + "@typescript-eslint/visitor-keys": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", + "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", + "dev": true, + "requires": { + "@typescript-eslint/types": "5.62.0", + "eslint-visitor-keys": "^3.3.0" + } + }, + "eslint-visitor-keys": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.1.tgz", + "integrity": "sha512-pZnmmLwYzf+kWaM/Qgrvpen51upAktaaiI01nsJD/Yr3lMOdNtq0cxkrrg16w64VtisN6okbs7Q8AfGqj4c9fA==", + "dev": true + } } }, - "node_modules/supports-hyperlinks": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-2.2.0.tgz", - "integrity": "sha512-6sXEzV5+I5j8Bmq9/vUphGRM/RJNT9SCURJLjwfOg51heRtguGWDzcaBlgAzKhQa0EVNpPEKzQuBwZ8S8WaCeQ==", + "@typescript-eslint/scope-manager": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.39.0.tgz", + "integrity": "sha512-/I13vAqmG3dyqMVSZPjsbuNQlYS082Y7OMkwhCfLXYsmlI0ca4nkL7wJ/4gjX70LD4P8Hnw1JywUVVAwepURBw==", "dev": true, - "dependencies": { - "has-flag": "^4.0.0", - "supports-color": "^7.0.0" - }, - "engines": { - "node": ">=8" + "requires": { + "@typescript-eslint/types": "5.39.0", + "@typescript-eslint/visitor-keys": "5.39.0" } }, - "node_modules/svg-element-attributes": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/svg-element-attributes/-/svg-element-attributes-1.3.1.tgz", - "integrity": "sha512-Bh05dSOnJBf3miNMqpsormfNtfidA/GxQVakhtn0T4DECWKeXQRQUceYjJ+OxYiiLdGe4Jo9iFV8wICFapFeIA==", + "@typescript-eslint/type-utils": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.39.0.tgz", + "integrity": "sha512-KJHJkOothljQWzR3t/GunL0TPKY+fGJtnpl+pX+sJ0YiKTz3q2Zr87SGTmFqsCMFrLt5E0+o+S6eQY0FAXj9uA==", "dev": true, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" + "optional": true, + "peer": true, + "requires": { + "@typescript-eslint/typescript-estree": "5.39.0", + "@typescript-eslint/utils": "5.39.0", + "debug": "^4.3.4", + "tsutils": "^3.21.0" } }, - "node_modules/symbol-tree": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", - "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "@typescript-eslint/types": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.39.0.tgz", + "integrity": "sha512-gQMZrnfEBFXK38hYqt8Lkwt8f4U6yq+2H5VDSgP/qiTzC8Nw8JO3OuSUOQ2qW37S/dlwdkHDntkZM6SQhKyPhw==", "dev": true }, - "node_modules/table": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/table/-/table-6.7.1.tgz", - "integrity": "sha512-ZGum47Yi6KOOFDE8m223td53ath2enHcYLgOCjGr5ngu8bdIARQk6mN/wRMv4yMRcHnCSnHbCEha4sobQx5yWg==", + "@typescript-eslint/typescript-estree": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.39.0.tgz", + "integrity": "sha512-qLFQP0f398sdnogJoLtd43pUgB18Q50QSA+BTE5h3sUxySzbWDpTSdgt4UyxNSozY/oDK2ta6HVAzvGgq8JYnA==", "dev": true, - "dependencies": { - "ajv": "^8.0.1", - "lodash.clonedeep": "^4.5.0", - "lodash.truncate": "^4.4.2", - "slice-ansi": "^4.0.0", - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10.0.0" + "requires": { + "@typescript-eslint/types": "5.39.0", + "@typescript-eslint/visitor-keys": "5.39.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "semver": "^7.3.7", + "tsutils": "^3.21.0" } }, - "node_modules/table/node_modules/ajv": { - "version": "8.5.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.5.0.tgz", - "integrity": "sha512-Y2l399Tt1AguU3BPRP9Fn4eN+Or+StUGWCUpbnFyXSo8NZ9S4uj+AG2pjs5apK+ZMOwYOz1+a+VKvKH7CudXgQ==", + "@typescript-eslint/utils": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.39.0.tgz", + "integrity": "sha512-+DnY5jkpOpgj+EBtYPyHRjXampJfC0yUZZzfzLuUWVZvCuKqSdJVC8UhdWipIw7VKNTfwfAPiOWzYkAwuIhiAg==", "dev": true, - "dependencies": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/table/node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true - }, - "node_modules/tar-fs": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.0.1.tgz", - "integrity": "sha512-6tzWDMeroL87uF/+lin46k+Q+46rAJ0SyPGz7OW7wTgblI273hsBqk2C1j0/xNadNLKDTUL9BukSjB7cwgmlPA==", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.0.0" - } - }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" + "requires": { + "@types/json-schema": "^7.0.9", + "@typescript-eslint/scope-manager": "5.39.0", + "@typescript-eslint/types": "5.39.0", + "@typescript-eslint/typescript-estree": "5.39.0", + "eslint-scope": "^5.1.1", + "eslint-utils": "^3.0.0" } }, - "node_modules/terminal-link": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-2.1.1.tgz", - "integrity": "sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ==", + "@typescript-eslint/visitor-keys": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.39.0.tgz", + "integrity": "sha512-yyE3RPwOG+XJBLrhvsxAidUgybJVQ/hG8BhiJo0k8JSAYfk/CshVcxf0HwP4Jt7WZZ6vLmxdo1p6EyN3tzFTkg==", "dev": true, - "dependencies": { - "ansi-escapes": "^4.2.1", - "supports-hyperlinks": "^2.0.0" - }, - "engines": { - "node": ">=8" + "requires": { + "@typescript-eslint/types": "5.39.0", + "eslint-visitor-keys": "^3.3.0" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, "dependencies": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=8" + "eslint-visitor-keys": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "dev": true + } } }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "@ungap/structured-clone": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", + "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", "dev": true }, - "node_modules/throat": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/throat/-/throat-6.0.1.tgz", - "integrity": "sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w==", + "@vercel/ncc": { + "version": "0.38.1", + "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.38.1.tgz", + "integrity": "sha512-IBBb+iI2NLu4VQn3Vwldyi2QwaXt5+hTyh58ggAMoCGE6DJmPvwL3KPBWcJl1m9LYPChBLE980Jw+CS4Wokqxw==", "dev": true }, - "node_modules/through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", - "dev": true + "accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dev": true, + "requires": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + } }, - "node_modules/tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", + "acorn": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.9.0.tgz", + "integrity": "sha512-jaVNAFBHNLXspO543WnNNPZFRtavh3skAkITqD0/2aeMkKZTN+254PyhwxFYrk3vQ1xfY+2wbesJMs/JC8/PwQ==", "dev": true }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", "dev": true, - "engines": { - "node": ">=4" - } + "requires": {} }, - "node_modules/to-readable-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/to-readable-stream/-/to-readable-stream-1.0.0.tgz", - "integrity": "sha512-Iq25XBt6zD5npPhlLVXGFN3/gyR2/qODcKNNyTMd4vbm39HUaOiAM4PMq0eMVC/Tkxz+Zjdsc55g9yyz+Yq00Q==", + "ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, - "engines": { - "node": ">=6" + "requires": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" } }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", "dev": true, - "dependencies": { - "is-number": "^7.0.0" + "requires": { + "type-fest": "^0.21.3" }, - "engines": { - "node": ">=8.0" + "dependencies": { + "type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true + } } }, - "node_modules/toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", - "dev": true, - "engines": { - "node": ">=0.6" - } + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true }, - "node_modules/tough-cookie": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", - "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, - "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.1.2" - }, - "engines": { - "node": ">=6" + "requires": { + "color-convert": "^2.0.1" } }, - "node_modules/tr46": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz", - "integrity": "sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==", + "anymatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", + "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", "dev": true, - "dependencies": { - "punycode": "^2.1.1" - }, - "engines": { - "node": ">=8" + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" } }, - "node_modules/ts-jest": { - "version": "27.1.3", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-27.1.3.tgz", - "integrity": "sha512-6Nlura7s6uM9BVUAoqLH7JHyMXjz8gluryjpPXxr3IxZdAXnU6FhjvVLHFtfd1vsE1p8zD1OJfskkc0jhTSnkA==", - "dev": true, - "dependencies": { - "bs-logger": "0.x", - "fast-json-stable-stringify": "2.x", - "jest-util": "^27.0.0", - "json5": "2.x", - "lodash.memoize": "4.x", - "make-error": "1.x", - "semver": "7.x", - "yargs-parser": "20.x" - }, - "bin": { - "ts-jest": "cli.js" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - }, - "peerDependencies": { - "@babel/core": ">=7.0.0-beta.0 <8", - "@types/jest": "^27.0.0", - "babel-jest": ">=27.0.0 <28", - "esbuild": "~0.14.0", - "jest": "^27.0.0", - "typescript": ">=3.8 <5.0" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "@types/jest": { - "optional": true - }, - "babel-jest": { - "optional": true - }, - "esbuild": { - "optional": true - } - } + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true }, - "node_modules/ts-node": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", - "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", - "dev": true, - "dependencies": { - "@cspotcode/source-map-support": "^0.8.0", - "@tsconfig/node10": "^1.0.7", - "@tsconfig/node12": "^1.0.7", - "@tsconfig/node14": "^1.0.0", - "@tsconfig/node16": "^1.0.2", - "acorn": "^8.4.1", - "acorn-walk": "^8.1.1", - "arg": "^4.1.0", - "create-require": "^1.1.0", - "diff": "^4.0.1", - "make-error": "^1.1.1", - "v8-compile-cache-lib": "^3.0.1", - "yn": "3.1.1" - }, - "bin": { - "ts-node": "dist/bin.js", - "ts-node-cwd": "dist/bin-cwd.js", - "ts-node-esm": "dist/bin-esm.js", - "ts-node-script": "dist/bin-script.js", - "ts-node-transpile-only": "dist/bin-transpile.js", - "ts-script": "dist/bin-script-deprecated.js" - }, - "peerDependencies": { - "@swc/core": ">=1.2.50", - "@swc/wasm": ">=1.2.50", - "@types/node": "*", - "typescript": ">=2.7" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "@swc/wasm": { - "optional": true - } - } + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true }, - "node_modules/ts-node/node_modules/acorn": { - "version": "8.5.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.5.0.tgz", - "integrity": "sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q==", + "aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", "dev": true, - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" + "requires": { + "dequal": "^2.0.3" } }, - "node_modules/ts-node/node_modules/acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", + "dev": true + }, + "array-includes": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.6.tgz", + "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", "dev": true, - "engines": { - "node": ">=0.4.0" + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "get-intrinsic": "^1.1.3", + "is-string": "^1.0.7" } }, - "node_modules/tsconfig-paths": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz", - "integrity": "sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw==", + "array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true + }, + "array.prototype.flat": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.0.tgz", + "integrity": "sha512-12IUEkHsAhA4DY5s0FPgNXIdc8VRSqD9Zp78a5au9abH/SOBrsp082JOWFNTjkMozh8mqcdiKuaLGhPeYztxSw==", "dev": true, - "dependencies": { - "@types/json5": "^0.0.29", - "json5": "^1.0.1", - "minimist": "^1.2.0", - "strip-bom": "^3.0.0" + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "es-abstract": "^1.19.2", + "es-shim-unscopables": "^1.0.0" } }, - "node_modules/tsconfig-paths/node_modules/json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "array.prototype.flatmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.1.tgz", + "integrity": "sha512-8UGn9O1FDVvMNB0UlLv4voxRMze7+FpHyF5mSMRjWHUMlpoDViniy05870VlxhfgTnLbpuwTzvD76MTtWxB/mQ==", "dev": true, - "dependencies": { - "minimist": "^1.2.0" - }, - "bin": { - "json5": "lib/cli.js" + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "es-shim-unscopables": "^1.0.0" } }, - "node_modules/tsconfig-paths/node_modules/strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true, - "engines": { - "node": ">=4" + "asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "requires": { + "safer-buffer": "~2.1.0" } }, - "node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "ast-types-flow": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.7.tgz", + "integrity": "sha512-eBvWn1lvIApYMhzQMsu9ciLfkBY499mFZlNqG+/9WR7PVlroQw0vG30cOQQbaKz3sCEc44TAOu2ykzqXSNnwag==", "dev": true }, - "node_modules/tsutils": { - "version": "3.21.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", - "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", - "dev": true, - "dependencies": { - "tslib": "^1.8.1" - }, - "engines": { - "node": ">= 6" - }, - "peerDependencies": { - "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" - } - }, - "node_modules/tunnel": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", - "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", - "engines": { - "node": ">=0.6.11 <=0.7.0 || >=0.7.3" - } + "available-typed-arrays": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", + "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", + "dev": true }, - "node_modules/tweetnacl": { - "version": "0.14.5", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + "axe-core": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.6.3.tgz", + "integrity": "sha512-/BQzOX780JhsxDnPpH4ZiyrJAzcd8AfzFPkv+89veFSr1rcMjuq2JDCwypKaPeB6ljHp9KjXhPpjgCvQlWYuqg==", + "dev": true }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "axobject-query": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-3.1.1.tgz", + "integrity": "sha512-goKlv8DZrK9hUh975fnHzhNIO4jUnFCfv/dszV5VwUGDFjI6vQ2VwoyjYjYNEbBE8AH87TduWP5uyDR1D+Iteg==", "dev": true, - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" + "requires": { + "deep-equal": "^2.0.5" } }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "engines": { - "node": ">=4" - } + "b4a": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz", + "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==" }, - "node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "babel-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", + "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "requires": { + "@jest/transform": "^29.7.0", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.6.3", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" } }, - "node_modules/type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", "dev": true, - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" } }, - "node_modules/typedarray-to-buffer": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", - "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "babel-plugin-jest-hoist": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", + "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", "dev": true, - "dependencies": { - "is-typedarray": "^1.0.0" + "requires": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" } }, - "node_modules/typescript": { - "version": "4.8.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.4.tgz", - "integrity": "sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=4.2.0" - } - }, - "node_modules/unbox-primitive": { + "babel-preset-current-node-syntax": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", - "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", + "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", "dev": true, - "dependencies": { - "function-bind": "^1.1.1", - "has-bigints": "^1.0.1", - "has-symbols": "^1.0.2", - "which-boxed-primitive": "^1.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "requires": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.8.3", + "@babel/plugin-syntax-import-meta": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.8.3", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-top-level-await": "^7.8.3" } }, - "node_modules/unique-string": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", - "integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", + "babel-preset-jest": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", + "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", "dev": true, - "dependencies": { - "crypto-random-string": "^2.0.0" - }, - "engines": { - "node": ">=8" + "requires": { + "babel-plugin-jest-hoist": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0" } }, - "node_modules/universal-user-agent": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", - "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true }, - "node_modules/universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" + }, + "basic-auth": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", + "integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==", "dev": true, - "engines": { - "node": ">= 4.0.0" + "requires": { + "safe-buffer": "5.1.2" } }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", - "dev": true, - "engines": { - "node": ">= 0.8" + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "requires": { + "tweetnacl": "^0.14.3" } }, - "node_modules/update-notifier": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-5.1.0.tgz", - "integrity": "sha512-ItnICHbeMh9GqUy31hFPrD1kcuZ3rpxDZbf4KUDavXwS0bW5m7SLbDQpGX3UYr072cbrF5hFUs3r5tUsPwjfHw==", - "dev": true, - "dependencies": { - "boxen": "^5.0.0", - "chalk": "^4.1.0", - "configstore": "^5.0.1", - "has-yarn": "^2.1.0", - "import-lazy": "^2.1.0", - "is-ci": "^2.0.0", - "is-installed-globally": "^0.4.0", - "is-npm": "^5.0.0", - "is-yarn-global": "^0.3.0", - "latest-version": "^5.1.0", - "pupa": "^2.1.1", - "semver": "^7.3.4", - "semver-diff": "^3.1.1", - "xdg-basedir": "^4.0.0" - }, - "engines": { - "node": ">=10" + "before-after-hook": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz", + "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==" + }, + "body-parser": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "dev": true, + "requires": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" }, - "funding": { - "url": "https://github.com/yeoman/update-notifier?sponsor=1" + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + } } }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, - "dependencies": { - "punycode": "^2.1.0" + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" } }, - "node_modules/url-parse-lax": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-3.0.0.tgz", - "integrity": "sha1-FrXK/Afb42dsGxmZF3gj1lA6yww=", + "braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dev": true, - "dependencies": { - "prepend-http": "^2.0.0" - }, - "engines": { - "node": ">=4" + "requires": { + "fill-range": "^7.1.1" } }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + "browserslist": { + "version": "4.21.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.4.tgz", + "integrity": "sha512-CBHJJdDmgjl3daYjN5Cp5kbTf1mUhZoS+beLklHIvkOWscs83YAhLlF3Wsh/lciQYAcbBJgTOD44VtG31ZM4Hw==", + "dev": true, + "requires": { + "caniuse-lite": "^1.0.30001400", + "electron-to-chromium": "^1.4.251", + "node-releases": "^2.0.6", + "update-browserslist-db": "^1.0.9" + } }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", "dev": true, - "engines": { - "node": ">= 0.4.0" + "requires": { + "fast-json-stable-stringify": "2.x" } }, - "node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", - "bin": { - "uuid": "dist/bin/uuid" + "bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "dev": true, + "requires": { + "node-int64": "^0.4.0" } }, - "node_modules/v8-compile-cache": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", - "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", + "buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, - "node_modules/v8-compile-cache-lib": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", - "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "buildcheck": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.6.tgz", + "integrity": "sha512-8f9ZJCUXyT1M35Jx7MkBgmBMo3oHTTBIPLiY9xyL0pl3T5RwcPEY8cUHr5LBNfu/fk6c2T4DJZuVM/8ZZT2D2A==", + "optional": true + }, + "bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", "dev": true }, - "node_modules/v8-to-istanbul": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-8.1.1.tgz", - "integrity": "sha512-FGtKtv3xIpR6BYhvgH8MI/y78oT7d8Au3ww4QIxymrCtZEh5b8gCw2siywE+puhEmuWKDtmfrvF5UlB298ut3w==", + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, - "dependencies": { - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^1.6.0", - "source-map": "^0.7.3" - }, - "engines": { - "node": ">=10.12.0" + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" } }, - "node_modules/v8-to-istanbul/node_modules/source-map": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", - "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", - "dev": true, - "engines": { - "node": ">= 8" - } + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true }, - "node_modules/validate-npm-package-license": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", - "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", - "dev": true, - "dependencies": { - "spdx-correct": "^3.0.0", - "spdx-expression-parse": "^3.0.0" - } + "camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "caniuse-lite": { + "version": "1.0.30001418", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001418.tgz", + "integrity": "sha512-oIs7+JL3K9JRQ3jPZjlH6qyYDp+nBTCais7hjh0s+fuBwufc7uZ7hPYMXrDOJhV360KGMTcczMRObk0/iMqZRg==", + "dev": true + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, - "engines": { - "node": ">= 0.8" + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" } }, - "node_modules/w3c-hr-time": { + "char-regex": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", - "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", - "dev": true, - "dependencies": { - "browser-process-hrtime": "^1.0.0" - } + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "dev": true }, - "node_modules/w3c-xmlserializer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz", - "integrity": "sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA==", + "chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" + }, + "ci-info": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.2.0.tgz", + "integrity": "sha512-dVqRX7fLUm8J6FgHJ418XuIgDLZDkYcDFTeL6TA2gt5WlIZUQrrH6EZrNClwT/H0FateUsZkGIOPRrLbP+PR9A==", + "dev": true + }, + "cjs-module-lexer": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz", + "integrity": "sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==", + "dev": true + }, + "cli-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", "dev": true, - "dependencies": { - "xml-name-validator": "^3.0.0" - }, - "engines": { - "node": ">=10" + "requires": { + "restore-cursor": "^4.0.0" } }, - "node_modules/wait-port": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/wait-port/-/wait-port-0.2.9.tgz", - "integrity": "sha512-hQ/cVKsNqGZ/UbZB/oakOGFqic00YAMM5/PEj3Bt4vKarv2jWIWzDbqlwT94qMs/exAQAsvMOq99sZblV92zxQ==", + "cli-truncate": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz", + "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==", "dev": true, - "dependencies": { - "chalk": "^2.4.2", - "commander": "^3.0.2", - "debug": "^4.1.1" + "requires": { + "slice-ansi": "^5.0.0", + "string-width": "^7.0.0" }, - "bin": { - "wait-port": "bin/wait-port.js" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wait-port/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" + "ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", + "dev": true + }, + "emoji-regex": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.3.0.tgz", + "integrity": "sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==", + "dev": true + }, + "string-width": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.1.0.tgz", + "integrity": "sha512-SEIJCWiX7Kg4c129n48aDRwLbFb2LJmXXFrWBG4NGaRtMQ3myKPKbwrD1BKqQn74oCoNMBVrfDEr5M9YxCsrkw==", + "dev": true, + "requires": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + } + }, + "strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "requires": { + "ansi-regex": "^6.0.1" + } + } } }, - "node_modules/wait-port/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", "dev": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" } }, - "node_modules/wait-port/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "dev": true + }, + "collect-v8-coverage": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", + "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==", + "dev": true + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, - "dependencies": { - "color-name": "1.1.3" + "requires": { + "color-name": "~1.1.4" } }, - "node_modules/wait-port/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, - "node_modules/wait-port/node_modules/commander": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/commander/-/commander-3.0.2.tgz", - "integrity": "sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow==", + "colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", "dev": true }, - "node_modules/wait-port/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true, - "engines": { - "node": ">=0.8.0" - } + "commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==" }, - "node_modules/wait-port/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "compressible": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", + "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", "dev": true, - "engines": { - "node": ">=4" + "requires": { + "mime-db": ">= 1.43.0 < 2" } }, - "node_modules/wait-port/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "compression": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.4.tgz", + "integrity": "sha512-jaSIDzP9pZVS4ZfQ+TzvtiWhdpFhE2RDHz8QJkpX9SIpLq88VueF5jJw6t+6CUQcAoA6t+x89MLrWAqpfDE8iQ==", "dev": true, - "dependencies": { - "has-flag": "^3.0.0" + "requires": { + "accepts": "~1.3.5", + "bytes": "3.0.0", + "compressible": "~2.0.16", + "debug": "2.6.9", + "on-headers": "~1.0.2", + "safe-buffer": "5.1.2", + "vary": "~1.1.2" }, - "engines": { - "node": ">=4" - } - }, - "node_modules/walker": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz", - "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", - "dev": true, "dependencies": { - "makeerror": "1.0.x" + "bytes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", + "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } } }, - "node_modules/webidl-conversions": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", - "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "connect-pause": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/connect-pause/-/connect-pause-0.1.1.tgz", + "integrity": "sha1-smmyu4Ldsaw9tQmcD7WCq6mfs3o=", + "dev": true + }, + "content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", "dev": true, - "engines": { - "node": ">=10.4" + "requires": { + "safe-buffer": "5.2.1" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + } } }, - "node_modules/whatwg-encoding": { + "content-type": { "version": "1.0.5", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", - "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "dev": true + }, + "convert-source-map": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", + "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", "dev": true, - "dependencies": { - "iconv-lite": "0.4.24" + "requires": { + "safe-buffer": "~5.1.1" } }, - "node_modules/whatwg-mimetype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", - "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", + "cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", "dev": true }, - "node_modules/whatwg-url": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-8.7.0.tgz", - "integrity": "sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg==", + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=", + "dev": true + }, + "cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", "dev": true, - "dependencies": { - "lodash": "^4.7.0", - "tr46": "^2.1.0", - "webidl-conversions": "^6.1.0" - }, - "engines": { - "node": ">=10" + "requires": { + "object-assign": "^4", + "vary": "^1" } }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" + "cpu-features": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.9.tgz", + "integrity": "sha512-AKjgn2rP2yJyfbepsmLfiYcmtNn/2eUvocUyM/09yB0YDiz39HteK/5/T4Onf0pmdYDMgkBoGvRLvEguzyL7wQ==", + "optional": true, + "requires": { + "buildcheck": "~0.0.6", + "nan": "^2.17.0" } }, - "node_modules/which-boxed-primitive": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", - "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "create-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", + "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", "dev": true, - "dependencies": { - "is-bigint": "^1.0.1", - "is-boolean-object": "^1.1.0", - "is-number-object": "^1.0.4", - "is-string": "^1.0.5", - "is-symbol": "^1.0.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "requires": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "prompts": "^2.0.1" } }, - "node_modules/widest-line": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz", - "integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==", + "create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, - "dependencies": { - "string-width": "^4.0.0" - }, - "engines": { - "node": ">=8" + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" } }, - "node_modules/word-wrap": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", - "dev": true, - "engines": { - "node": ">=0.10.0" + "damerau-levenshtein": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", + "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==", + "dev": true + }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "requires": { + "ms": "2.1.2" } }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" - }, - "node_modules/write-file-atomic": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", - "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dedent": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.1.tgz", + "integrity": "sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg==", "dev": true, - "dependencies": { - "imurmurhash": "^0.1.4", - "is-typedarray": "^1.0.0", - "signal-exit": "^3.0.2", - "typedarray-to-buffer": "^3.1.5" - } + "requires": {} }, - "node_modules/ws": { - "version": "7.5.7", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.7.tgz", - "integrity": "sha512-KMvVuFzpKBuiIXW3E4u3mySRO2/mCHSyZDJQM5NQ9Q9KHWHWh0NHgfbRMLLrceUK5qAL4ytALJbpRMjixFZh8A==", + "deep-equal": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.0.tgz", + "integrity": "sha512-RdpzE0Hv4lhowpIUKKMJfeH6C1pXdtT1/it80ubgWqwI3qpuxUBpC1S4hnHg+zjnuOoDkzUtUCEEkG+XG5l3Mw==", "dev": true, - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true + "requires": { + "call-bind": "^1.0.2", + "es-get-iterator": "^1.1.2", + "get-intrinsic": "^1.1.3", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.4.3", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.9" + }, + "dependencies": { + "isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true } } }, - "node_modules/xdg-basedir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", - "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", + "deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true + }, + "deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true + }, + "define-properties": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", + "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", "dev": true, - "engines": { - "node": ">=8" + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" } }, - "node_modules/xml-name-validator": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", - "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", "dev": true }, - "node_modules/xmlchars": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "deprecation": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", + "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" + }, + "dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", "dev": true }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, - "engines": { - "node": ">=10" - } + "destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "dev": true }, - "node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", "dev": true }, - "node_modules/yaml": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", - "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true + }, + "diff-sequences": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "dev": true + }, + "dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", "dev": true, - "engines": { - "node": ">= 6" + "requires": { + "path-type": "^4.0.0" } }, - "node_modules/yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", - "dev": true, - "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - }, - "engines": { - "node": ">=10" + "docker-modem": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/docker-modem/-/docker-modem-5.0.3.tgz", + "integrity": "sha512-89zhop5YVhcPEt5FpUFGr3cDyceGhq/F9J+ZndQ4KfqNvfbJpPMfgeixFgUj5OjCYAboElqODxY5Z1EBsSa6sg==", + "requires": { + "debug": "^4.1.1", + "readable-stream": "^3.5.0", + "split-ca": "^1.0.1", + "ssh2": "^1.15.0" } }, - "node_modules/yargs-parser": { - "version": "20.2.7", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.7.tgz", - "integrity": "sha512-FiNkvbeHzB/syOjIUxFDCnhSfzAL8R5vs40MgLFBorXACCOAEaWu0gRZl14vG8MR9AOJIZbmkjhusqBYZ3HTHw==", - "dev": true, - "engines": { - "node": ">=10" + "dockerode": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/dockerode/-/dockerode-4.0.2.tgz", + "integrity": "sha512-9wM1BVpVMFr2Pw3eJNXrYYt6DT9k0xMcsSCjtPvyQ+xa1iPg/Mo3T/gUcwI0B2cczqCeCYRPF8yFYDwtFXT0+w==", + "requires": { + "@balena/dockerignore": "^1.0.2", + "docker-modem": "^5.0.3", + "tar-fs": "~2.0.1" } }, - "node_modules/yn": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", - "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", "dev": true, - "engines": { - "node": ">=6" + "requires": { + "esutils": "^2.0.2" } - } - }, - "dependencies": { - "@actions/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.9.1.tgz", - "integrity": "sha512-5ad+U2YGrmmiw6du20AQW5XuWo7UKN2052FjSV7MX+Wfjf8sCqcsZe62NfgHys4QI4/Y+vQvLKYL8jWtA1ZBTA==", + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "dev": true + }, + "electron-to-chromium": { + "version": "1.4.276", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.276.tgz", + "integrity": "sha512-EpuHPqu8YhonqLBXHoU6hDJCD98FCe6KDoet3/gY1qsQ6usjJoHqBH2YIVs8FXaAtHwVL8Uqa/fsYao/vq9VWQ==", + "dev": true + }, + "emittery": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", + "dev": true + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "dev": true + }, + "end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", "requires": { - "@actions/http-client": "^2.0.1", - "uuid": "^8.3.2" - }, - "dependencies": { - "@actions/http-client": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz", - "integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==", - "requires": { - "tunnel": "^0.0.6" - } - } + "once": "^1.4.0" } }, - "@actions/github": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@actions/github/-/github-5.0.0.tgz", - "integrity": "sha512-QvE9eAAfEsS+yOOk0cylLBIO/d6WyWIOvsxxzdrPFaud39G6BOkUwScXZn1iBzQzHyu9SBkkLSWlohDWdsasAQ==", + "enhanced-resolve": { + "version": "5.12.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.12.0.tgz", + "integrity": "sha512-QHTXI/sZQmko1cbDoNAa3mJ5qhWUUNAq3vR0/YiD379fWQrcfuoX1+HW2S0MTt7XmoPLapdaDKUtelUSPic7hQ==", + "dev": true, "requires": { - "@actions/http-client": "^1.0.11", - "@octokit/core": "^3.4.0", - "@octokit/plugin-paginate-rest": "^2.13.3", - "@octokit/plugin-rest-endpoint-methods": "^5.1.1" + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" } }, - "@actions/http-client": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.11.tgz", - "integrity": "sha512-VRYHGQV1rqnROJqdMvGUbY/Kn8vriQe/F9HR2AlYHzmKuM/p3kjNuXhmdBfcVgsvRWTz5C5XW5xvndZrVBuAYg==", + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, "requires": { - "tunnel": "0.0.6" + "is-arrayish": "^0.2.1" } }, - "@babel/code-frame": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", - "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", + "errorhandler": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/errorhandler/-/errorhandler-1.5.1.tgz", + "integrity": "sha512-rcOwbfvP1WTViVoUjcfZicVzjhjTuhSMntHh6mW3IrEiyE6mJyXvsToJUJGlGlw/2xU9P5whlWNGlIDVeCiT4A==", "dev": true, "requires": { - "@babel/highlight": "^7.10.4" + "accepts": "~1.3.7", + "escape-html": "~1.0.3" } }, - "@babel/compat-data": { - "version": "7.14.4", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.14.4.tgz", - "integrity": "sha512-i2wXrWQNkH6JplJQGn3Rd2I4Pij8GdHkXwHMxm+zV5YG/Jci+bCNrWZEWC4o+umiDkRrRs4dVzH3X4GP7vyjQQ==", - "dev": true + "es-abstract": { + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.20.4.tgz", + "integrity": "sha512-0UtvRN79eMe2L+UNEF1BwRe364sj/DXhQ/k5FmivgoSdpM90b8Jc0mDzKMGo7QS0BVbOP/bTwBKNnDc9rNzaPA==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "function.prototype.name": "^1.1.5", + "get-intrinsic": "^1.1.3", + "get-symbol-description": "^1.0.0", + "has": "^1.0.3", + "has-property-descriptors": "^1.0.0", + "has-symbols": "^1.0.3", + "internal-slot": "^1.0.3", + "is-callable": "^1.2.7", + "is-negative-zero": "^2.0.2", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "is-string": "^1.0.7", + "is-weakref": "^1.0.2", + "object-inspect": "^1.12.2", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.4.3", + "safe-regex-test": "^1.0.0", + "string.prototype.trimend": "^1.0.5", + "string.prototype.trimstart": "^1.0.5", + "unbox-primitive": "^1.0.2" + } }, - "@babel/core": { - "version": "7.14.3", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.14.3.tgz", - "integrity": "sha512-jB5AmTKOCSJIZ72sd78ECEhuPiDMKlQdDI/4QRI6lzYATx5SSogS1oQA2AoPecRCknm30gHi2l+QVvNUu3wZAg==", + "es-get-iterator": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.3.tgz", + "integrity": "sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==", "dev": true, "requires": { - "@babel/code-frame": "^7.12.13", - "@babel/generator": "^7.14.3", - "@babel/helper-compilation-targets": "^7.13.16", - "@babel/helper-module-transforms": "^7.14.2", - "@babel/helpers": "^7.14.0", - "@babel/parser": "^7.14.3", - "@babel/template": "^7.12.13", - "@babel/traverse": "^7.14.2", - "@babel/types": "^7.14.2", - "convert-source-map": "^1.7.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.1.2", - "semver": "^6.3.0", - "source-map": "^0.5.0" - }, - "dependencies": { - "@babel/code-frame": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", - "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, - "requires": { - "@babel/highlight": "^7.12.13" - } - }, - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - }, - "source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "has-symbols": "^1.0.3", + "is-arguments": "^1.1.1", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.7", + "isarray": "^2.0.5", + "stop-iteration-iterator": "^1.0.0" + }, + "dependencies": { + "isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", "dev": true } } }, - "@babel/generator": { - "version": "7.14.3", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.14.3.tgz", - "integrity": "sha512-bn0S6flG/j0xtQdz3hsjJ624h3W0r3llttBMfyHX3YrZ/KtLYr15bjA0FXkgW7FpvrDuTuElXeVjiKlYRpnOFA==", + "es-shim-unscopables": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.0.tgz", + "integrity": "sha512-Jm6GPcCdC30eMLbZ2x8z2WuRwAws3zTBBKuusffYVUrNj/GVSUAZ+xKMaUpfNDR5IbyNA5LJbaecoUVbmUcB1w==", "dev": true, "requires": { - "@babel/types": "^7.14.2", - "jsesc": "^2.5.1", - "source-map": "^0.5.0" - }, - "dependencies": { - "source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true - } + "has": "^1.0.3" } }, - "@babel/helper-compilation-targets": { - "version": "7.14.4", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.14.4.tgz", - "integrity": "sha512-JgdzOYZ/qGaKTVkn5qEDV/SXAh8KcyUVkCoSWGN8T3bwrgd6m+/dJa2kVGi6RJYJgEYPBdZ84BZp9dUjNWkBaA==", + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", "dev": true, "requires": { - "@babel/compat-data": "^7.14.4", - "@babel/helper-validator-option": "^7.12.17", - "browserslist": "^4.16.6", - "semver": "^6.3.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" } }, - "@babel/helper-function-name": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.14.2.tgz", - "integrity": "sha512-NYZlkZRydxw+YT56IlhIcS8PAhb+FEUiOzuhFTfqDyPmzAhRge6ua0dQYT/Uh0t/EDHq05/i+e5M2d4XvjgarQ==", - "dev": true, - "requires": { - "@babel/helper-get-function-arity": "^7.12.13", - "@babel/template": "^7.12.13", - "@babel/types": "^7.14.2" - } + "escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true }, - "@babel/helper-get-function-arity": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.13.tgz", - "integrity": "sha512-DjEVzQNz5LICkzN0REdpD5prGoidvbdYk1BVgRUOINaWJP2t6avB27X1guXK1kXNrX0WMfsrm1A/ZBthYuIMQg==", - "dev": true, - "requires": { - "@babel/types": "^7.12.13" - } + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "dev": true }, - "@babel/helper-member-expression-to-functions": { - "version": "7.13.12", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.13.12.tgz", - "integrity": "sha512-48ql1CLL59aKbU94Y88Xgb2VFy7a95ykGRbJJaaVv+LX5U8wFpLfiGXJJGUozsmA1oEh/o5Bp60Voq7ACyA/Sw==", - "dev": true, - "requires": { - "@babel/types": "^7.13.12" + "escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true + }, + "eslint": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", + "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", + "dev": true, + "requires": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.4", + "@eslint/js": "8.57.0", + "@humanwhocodes/config-array": "^0.11.14", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "@ungap/structured-clone": "^1.2.0", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "dependencies": { + "eslint-scope": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", + "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "dev": true, + "requires": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + } + }, + "eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true + }, + "estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true + }, + "glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "requires": { + "is-glob": "^4.0.3" + } + } } }, - "@babel/helper-module-imports": { - "version": "7.13.12", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.13.12.tgz", - "integrity": "sha512-4cVvR2/1B693IuOvSI20xqqa/+bl7lqAMR59R4iu39R9aOX8/JoYY1sFaNvUMyMBGnHdwvJgUrzNLoUZxXypxA==", + "eslint-config-prettier": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", + "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", "dev": true, - "requires": { - "@babel/types": "^7.13.12" - } + "requires": {} }, - "@babel/helper-module-transforms": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.14.2.tgz", - "integrity": "sha512-OznJUda/soKXv0XhpvzGWDnml4Qnwp16GN+D/kZIdLsWoHj05kyu8Rm5kXmMef+rVJZ0+4pSGLkeixdqNUATDA==", + "eslint-import-resolver-node": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.6.tgz", + "integrity": "sha512-0En0w03NRVMn9Uiyn8YRPDKvWjxCWkslUEhGNTdGx15RvPJYQ+lbOlqrlNI2vEAs4pDYK4f/HN2TbDmk5TP0iw==", "dev": true, "requires": { - "@babel/helper-module-imports": "^7.13.12", - "@babel/helper-replace-supers": "^7.13.12", - "@babel/helper-simple-access": "^7.13.12", - "@babel/helper-split-export-declaration": "^7.12.13", - "@babel/helper-validator-identifier": "^7.14.0", - "@babel/template": "^7.12.13", - "@babel/traverse": "^7.14.2", - "@babel/types": "^7.14.2" + "debug": "^3.2.7", + "resolve": "^1.20.0" + }, + "dependencies": { + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + } } }, - "@babel/helper-optimise-call-expression": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.12.13.tgz", - "integrity": "sha512-BdWQhoVJkp6nVjB7nkFWcn43dkprYauqtk++Py2eaf/GRDFm5BxRqEIZCiHlZUGAVmtwKcsVL1dC68WmzeFmiA==", + "eslint-import-resolver-typescript": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.6.1.tgz", + "integrity": "sha512-xgdptdoi5W3niYeuQxKmzVDTATvLYqhpwmykwsh7f6HIOStGWEIL9iqZgQDF9u9OEzrRwR8no5q2VT+bjAujTg==", "dev": true, "requires": { - "@babel/types": "^7.12.13" + "debug": "^4.3.4", + "enhanced-resolve": "^5.12.0", + "eslint-module-utils": "^2.7.4", + "fast-glob": "^3.3.1", + "get-tsconfig": "^4.5.0", + "is-core-module": "^2.11.0", + "is-glob": "^4.0.3" } }, - "@babel/helper-plugin-utils": { - "version": "7.13.0", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.13.0.tgz", - "integrity": "sha512-ZPafIPSwzUlAoWT8DKs1W2VyF2gOWthGd5NGFMsBcMMol+ZhK+EQY/e6V96poa6PA/Bh+C9plWN0hXO1uB8AfQ==", - "dev": true - }, - "@babel/helper-replace-supers": { - "version": "7.14.4", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.14.4.tgz", - "integrity": "sha512-zZ7uHCWlxfEAAOVDYQpEf/uyi1dmeC7fX4nCf2iz9drnCwi1zvwXL3HwWWNXUQEJ1k23yVn3VbddiI9iJEXaTQ==", + "eslint-module-utils": { + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.7.4.tgz", + "integrity": "sha512-j4GT+rqzCoRKHwURX7pddtIPGySnX9Si/cgMI5ztrcqOPtk5dDEeZ34CQVPphnqkJytlc97Vuk05Um2mJ3gEQA==", "dev": true, "requires": { - "@babel/helper-member-expression-to-functions": "^7.13.12", - "@babel/helper-optimise-call-expression": "^7.12.13", - "@babel/traverse": "^7.14.2", - "@babel/types": "^7.14.4" + "debug": "^3.2.7" + }, + "dependencies": { + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + } } }, - "@babel/helper-simple-access": { - "version": "7.13.12", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.13.12.tgz", - "integrity": "sha512-7FEjbrx5SL9cWvXioDbnlYTppcZGuCY6ow3/D5vMggb2Ywgu4dMrpTJX0JdQAIcRRUElOIxF3yEooa9gUb9ZbA==", + "eslint-plugin-escompat": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/eslint-plugin-escompat/-/eslint-plugin-escompat-3.3.4.tgz", + "integrity": "sha512-d/k6JwRzGRY6uZ426l6Ut6Eb2S/pi/079Ykj2GdWSzwm6WJHkdm28tECUWfLtpFA5ObApjPw6wR9bgY+uWAhag==", "dev": true, "requires": { - "@babel/types": "^7.13.12" + "browserslist": "^4.21.0" } }, - "@babel/helper-split-export-declaration": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.12.13.tgz", - "integrity": "sha512-tCJDltF83htUtXx5NLcaDqRmknv652ZWCHyoTETf1CXYJdPC7nohZohjUgieXhv0hTJdRf2FjDueFehdNucpzg==", + "eslint-plugin-eslint-comments": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-eslint-comments/-/eslint-plugin-eslint-comments-3.2.0.tgz", + "integrity": "sha512-0jkOl0hfojIHHmEHgmNdqv4fmh7300NdpA9FFpF7zaoLvB/QeXOGNLIo86oAveJFrfB1p05kC8hpEMHM8DwWVQ==", "dev": true, "requires": { - "@babel/types": "^7.12.13" + "escape-string-regexp": "^1.0.5", + "ignore": "^5.0.5" + }, + "dependencies": { + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + } } }, - "@babel/helper-validator-identifier": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.0.tgz", - "integrity": "sha512-V3ts7zMSu5lfiwWDVWzRDGIN+lnCEUdaXgtVHJgLb1rGaA6jMrtB9EmE7L18foXJIE8Un/A/h6NJfGQp/e1J4A==", - "dev": true - }, - "@babel/helper-validator-option": { - "version": "7.12.17", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.12.17.tgz", - "integrity": "sha512-TopkMDmLzq8ngChwRlyjR6raKD6gMSae4JdYDB8bByKreQgG0RBTuKe9LRxW3wFtUnjxOPRKBDwEH6Mg5KeDfw==", - "dev": true - }, - "@babel/helpers": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.14.0.tgz", - "integrity": "sha512-+ufuXprtQ1D1iZTO/K9+EBRn+qPWMJjZSw/S0KlFrxCw4tkrzv9grgpDHkY9MeQTjTY8i2sp7Jep8DfU6tN9Mg==", + "eslint-plugin-filenames": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-filenames/-/eslint-plugin-filenames-1.3.2.tgz", + "integrity": "sha512-tqxJTiEM5a0JmRCUYQmxw23vtTxrb2+a3Q2mMOPhFxvt7ZQQJmdiuMby9B/vUAuVMghyP7oET+nIf6EO6CBd/w==", "dev": true, "requires": { - "@babel/template": "^7.12.13", - "@babel/traverse": "^7.14.0", - "@babel/types": "^7.14.0" + "lodash.camelcase": "4.3.0", + "lodash.kebabcase": "4.1.1", + "lodash.snakecase": "4.1.1", + "lodash.upperfirst": "4.3.1" } }, - "@babel/highlight": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.0.tgz", - "integrity": "sha512-YSCOwxvTYEIMSGaBQb5kDDsCopDdiUGsqpatp3fOlI4+2HQSkTmEVWnVuySdAC5EWCqSWWTv0ib63RjR7dTBdg==", + "eslint-plugin-github": { + "version": "4.10.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-github/-/eslint-plugin-github-4.10.2.tgz", + "integrity": "sha512-F1F5aAFgi1Y5hYoTFzGQACBkw5W1hu2Fu5FSTrMlXqrojJnKl1S2pWO/rprlowRQpt+hzHhqSpsfnodJEVd5QA==", "dev": true, "requires": { - "@babel/helper-validator-identifier": "^7.14.0", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" + "@github/browserslist-config": "^1.0.0", + "@typescript-eslint/eslint-plugin": "^7.0.1", + "@typescript-eslint/parser": "^7.0.1", + "aria-query": "^5.3.0", + "eslint-config-prettier": ">=8.0.0", + "eslint-plugin-escompat": "^3.3.3", + "eslint-plugin-eslint-comments": "^3.2.0", + "eslint-plugin-filenames": "^1.3.2", + "eslint-plugin-i18n-text": "^1.0.1", + "eslint-plugin-import": "^2.25.2", + "eslint-plugin-jsx-a11y": "^6.7.1", + "eslint-plugin-no-only-tests": "^3.0.0", + "eslint-plugin-prettier": "^5.0.0", + "eslint-rule-documentation": ">=1.0.0", + "jsx-ast-utils": "^3.3.2", + "prettier": "^3.0.0", + "svg-element-attributes": "^1.3.1" }, "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "@typescript-eslint/eslint-plugin": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.1.0.tgz", + "integrity": "sha512-j6vT/kCulhG5wBmGtstKeiVr1rdXE4nk+DT1k6trYkwlrvW9eOF5ZbgKnd/YR6PcM4uTEXa0h6Fcvf6X7Dxl0w==", "dev": true, "requires": { - "color-convert": "^1.9.0" + "@eslint-community/regexpp": "^4.5.1", + "@typescript-eslint/scope-manager": "7.1.0", + "@typescript-eslint/type-utils": "7.1.0", + "@typescript-eslint/utils": "7.1.0", + "@typescript-eslint/visitor-keys": "7.1.0", + "debug": "^4.3.4", + "graphemer": "^1.4.0", + "ignore": "^5.2.4", + "natural-compare": "^1.4.0", + "semver": "^7.5.4", + "ts-api-utils": "^1.0.1" + } + }, + "@typescript-eslint/parser": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.1.0.tgz", + "integrity": "sha512-V1EknKUubZ1gWFjiOZhDSNToOjs63/9O0puCgGS8aDOgpZY326fzFu15QAUjwaXzRZjf/qdsdBrckYdv9YxB8w==", + "dev": true, + "requires": { + "@typescript-eslint/scope-manager": "7.1.0", + "@typescript-eslint/types": "7.1.0", + "@typescript-eslint/typescript-estree": "7.1.0", + "@typescript-eslint/visitor-keys": "7.1.0", + "debug": "^4.3.4" } }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "@typescript-eslint/scope-manager": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.1.0.tgz", + "integrity": "sha512-6TmN4OJiohHfoOdGZ3huuLhpiUgOGTpgXNUPJgeZOZR3DnIpdSgtt83RS35OYNNXxM4TScVlpVKC9jyQSETR1A==", "dev": true, "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" + "@typescript-eslint/types": "7.1.0", + "@typescript-eslint/visitor-keys": "7.1.0" } }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "@typescript-eslint/type-utils": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.1.0.tgz", + "integrity": "sha512-UZIhv8G+5b5skkcuhgvxYWHjk7FW7/JP5lPASMEUoliAPwIH/rxoUSQPia2cuOj9AmDZmwUl1usKm85t5VUMew==", "dev": true, "requires": { - "color-name": "1.1.3" + "@typescript-eslint/typescript-estree": "7.1.0", + "@typescript-eslint/utils": "7.1.0", + "debug": "^4.3.4", + "ts-api-utils": "^1.0.1" } }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "@typescript-eslint/types": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.1.0.tgz", + "integrity": "sha512-qTWjWieJ1tRJkxgZYXx6WUYtWlBc48YRxgY2JN1aGeVpkhmnopq+SUC8UEVGNXIvWH7XyuTjwALfG6bFEgCkQA==", "dev": true }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true + "@typescript-eslint/typescript-estree": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.1.0.tgz", + "integrity": "sha512-k7MyrbD6E463CBbSpcOnwa8oXRdHzH1WiVzOipK3L5KSML92ZKgUBrTlehdi7PEIMT8k0bQixHUGXggPAlKnOQ==", + "dev": true, + "requires": { + "@typescript-eslint/types": "7.1.0", + "@typescript-eslint/visitor-keys": "7.1.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "minimatch": "9.0.3", + "semver": "^7.5.4", + "ts-api-utils": "^1.0.1" + } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "@typescript-eslint/utils": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.1.0.tgz", + "integrity": "sha512-WUFba6PZC5OCGEmbweGpnNJytJiLG7ZvDBJJoUcX4qZYf1mGZ97mO2Mps6O2efxJcJdRNpqweCistDbZMwIVHw==", + "dev": true, + "requires": { + "@eslint-community/eslint-utils": "^4.4.0", + "@types/json-schema": "^7.0.12", + "@types/semver": "^7.5.0", + "@typescript-eslint/scope-manager": "7.1.0", + "@typescript-eslint/types": "7.1.0", + "@typescript-eslint/typescript-estree": "7.1.0", + "semver": "^7.5.4" + } + }, + "@typescript-eslint/visitor-keys": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.1.0.tgz", + "integrity": "sha512-FhUqNWluiGNzlvnDZiXad4mZRhtghdoKW6e98GoEOYSu5cND+E39rG5KwJMUzeENwm1ztYBRqof8wMLP+wNPIA==", + "dev": true, + "requires": { + "@typescript-eslint/types": "7.1.0", + "eslint-visitor-keys": "^3.4.1" + } + }, + "brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0" + } + }, + "eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "minimatch": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz", + "integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==", "dev": true, "requires": { - "has-flag": "^3.0.0" + "brace-expansion": "^2.0.1" } } } }, - "@babel/parser": { - "version": "7.17.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.17.3.tgz", - "integrity": "sha512-7yJPvPV+ESz2IUTPbOL+YkIGyCqOyNIzdguKQuJGnH7bg1WTIifuM21YqokFt/THWh1AkCRn9IgoykTRCBVpzA==", - "dev": true - }, - "@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "eslint-plugin-i18n-text": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-i18n-text/-/eslint-plugin-i18n-text-1.0.1.tgz", + "integrity": "sha512-3G3UetST6rdqhqW9SfcfzNYMpQXS7wNkJvp6dsXnjzGiku6Iu5hl3B0kmk6lIcFPwYjhQIY+tXVRtK9TlGT7RA==", "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } + "requires": {} }, - "@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "eslint-plugin-import": { + "version": "2.26.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.26.0.tgz", + "integrity": "sha512-hYfi3FXaM8WPLf4S1cikh/r4IxnO6zrhZbEGz2b660EJRbuxgpDS5gkCuYgGWg2xxh2rBuIr4Pvhve/7c31koA==", "dev": true, "requires": { - "@babel/helper-plugin-utils": "^7.12.13" + "array-includes": "^3.1.4", + "array.prototype.flat": "^1.2.5", + "debug": "^2.6.9", + "doctrine": "^2.1.0", + "eslint-import-resolver-node": "^0.3.6", + "eslint-module-utils": "^2.7.3", + "has": "^1.0.3", + "is-core-module": "^2.8.1", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.values": "^1.1.5", + "resolve": "^1.22.0", + "tsconfig-paths": "^3.14.1" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true + } } }, - "@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "eslint-plugin-jest": { + "version": "27.9.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.9.0.tgz", + "integrity": "sha512-QIT7FH7fNmd9n4se7FFKHbsLKGQiw885Ds6Y/sxKgCZ6natwCsXdgPOADnYVxN2QrRweF0FZWbJ6S7Rsn7llug==", "dev": true, "requires": { - "@babel/helper-plugin-utils": "^7.10.4" + "@typescript-eslint/utils": "^5.10.0" } }, - "@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" + "eslint-plugin-jsx-a11y": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.7.1.tgz", + "integrity": "sha512-63Bog4iIethyo8smBklORknVjB0T2dwB8Mr/hIC+fBS0uyHdYYpzM/Ed+YC8VxTjlXHEWFOdmgwcDn1U2L9VCA==", + "dev": true, + "requires": { + "@babel/runtime": "^7.20.7", + "aria-query": "^5.1.3", + "array-includes": "^3.1.6", + "array.prototype.flatmap": "^1.3.1", + "ast-types-flow": "^0.0.7", + "axe-core": "^4.6.2", + "axobject-query": "^3.1.1", + "damerau-levenshtein": "^1.0.8", + "emoji-regex": "^9.2.2", + "has": "^1.0.3", + "jsx-ast-utils": "^3.3.3", + "language-tags": "=1.0.5", + "minimatch": "^3.1.2", + "object.entries": "^1.1.6", + "object.fromentries": "^2.0.6", + "semver": "^6.3.0" + }, + "dependencies": { + "emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } } }, - "@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.10.4" - } + "eslint-plugin-no-only-tests": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-no-only-tests/-/eslint-plugin-no-only-tests-3.1.0.tgz", + "integrity": "sha512-Lf4YW/bL6Un1R6A76pRZyE1dl1vr31G/ev8UzIc/geCgFWyrKil8hVjYqWVKGB/UIGmb6Slzs9T0wNezdSVegw==", + "dev": true }, - "@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "eslint-plugin-prettier": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.1.3.tgz", + "integrity": "sha512-C9GCVAs4Eq7ZC/XFQHITLiHJxQngdtraXaM+LoUFoFp/lHNl2Zn8f3WQbe9HvTBBQ9YnKFB0/2Ajdqwo5D1EAw==", "dev": true, "requires": { - "@babel/helper-plugin-utils": "^7.8.0" + "prettier-linter-helpers": "^1.0.0", + "synckit": "^0.8.6" } }, - "@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.10.4" - } + "eslint-rule-documentation": { + "version": "1.0.23", + "resolved": "https://registry.npmjs.org/eslint-rule-documentation/-/eslint-rule-documentation-1.0.23.tgz", + "integrity": "sha512-pWReu3fkohwyvztx/oQWWgld2iad25TfUdi6wvhhaDPIQjHU/pyvlKgXFw1kX31SQK2Nq9MH+vRDWB0ZLy8fYw==", + "dev": true }, - "@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, "requires": { - "@babel/helper-plugin-utils": "^7.8.0" + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" } }, - "@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "eslint-utils": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", "dev": true, "requires": { - "@babel/helper-plugin-utils": "^7.8.0" + "eslint-visitor-keys": "^2.0.0" } }, - "@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } + "eslint-visitor-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", + "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", + "dev": true }, - "@babel/plugin-syntax-top-level-await": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.12.13.tgz", - "integrity": "sha512-A81F9pDwyS7yM//KwbCSDqy3Uj4NMIurtplxphWxoYtNPov7cJsDkAFNNyVlIZ3jwGycVsurZ+LtOA8gZ376iQ==", + "espree": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", "dev": true, "requires": { - "@babel/helper-plugin-utils": "^7.12.13" + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" + }, + "dependencies": { + "eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true + } } }, - "@babel/plugin-syntax-typescript": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.12.13.tgz", - "integrity": "sha512-cHP3u1JiUiG2LFDKbXnwVad81GvfyIOmCD6HIEId6ojrY0Drfy2q1jw7BwN7dE84+kTnBjLkXoL3IEy/3JPu2w==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.12.13" - } + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true }, - "@babel/template": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.12.13.tgz", - "integrity": "sha512-/7xxiGA57xMo/P2GVvdEumr8ONhFOhfgq2ihK3h1e6THqzTAkHbkXgB0xI9yeTfIUoH3+oAeHhqm/I43OTbbjA==", + "esquery": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", + "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", "dev": true, "requires": { - "@babel/code-frame": "^7.12.13", - "@babel/parser": "^7.12.13", - "@babel/types": "^7.12.13" + "estraverse": "^5.1.0" }, "dependencies": { - "@babel/code-frame": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", - "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, - "requires": { - "@babel/highlight": "^7.12.13" - } + "estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true } } }, - "@babel/traverse": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.14.2.tgz", - "integrity": "sha512-TsdRgvBFHMyHOOzcP9S6QU0QQtjxlRpEYOy3mcCO5RgmC305ki42aSAmfZEMSSYBla2oZ9BMqYlncBaKmD/7iA==", + "esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, "requires": { - "@babel/code-frame": "^7.12.13", - "@babel/generator": "^7.14.2", - "@babel/helper-function-name": "^7.14.2", - "@babel/helper-split-export-declaration": "^7.12.13", - "@babel/parser": "^7.14.2", - "@babel/types": "^7.14.2", - "debug": "^4.1.0", - "globals": "^11.1.0" + "estraverse": "^5.2.0" }, "dependencies": { - "@babel/code-frame": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", - "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, - "requires": { - "@babel/highlight": "^7.12.13" - } - }, - "globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "estraverse": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", "dev": true } } }, - "@babel/types": { - "version": "7.14.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.14.4.tgz", - "integrity": "sha512-lCj4aIs0xUefJFQnwwQv2Bxg7Omd6bgquZ6LGC+gGMh6/s5qDVfjuCMlDmYQ15SLsWHd9n+X3E75lKIhl5Lkiw==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.14.0", - "to-fast-properties": "^2.0.0" - } + "estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true }, - "@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true }, - "@cspotcode/source-map-support": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", - "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", - "dev": true, - "requires": { - "@jridgewell/trace-mapping": "0.3.9" - } + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "dev": true }, - "@eslint/eslintrc": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", - "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", + "eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "dev": true + }, + "execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", "dev": true, "requires": { - "ajv": "^6.12.4", - "debug": "^4.1.1", - "espree": "^7.3.0", - "globals": "^13.9.0", - "ignore": "^4.0.6", - "import-fresh": "^3.2.1", - "js-yaml": "^3.13.1", - "minimatch": "^3.0.4", - "strip-json-comments": "^3.1.1" - }, - "dependencies": { - "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "requires": { - "sprintf-js": "~1.0.2" - } - }, - "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - } + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" } }, - "@humanwhocodes/config-array": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", - "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "dev": true + }, + "expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", "dev": true, "requires": { - "@humanwhocodes/object-schema": "^1.2.0", - "debug": "^4.1.1", - "minimatch": "^3.0.4" + "@jest/expect-utils": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0" } }, - "@humanwhocodes/object-schema": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz", - "integrity": "sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w==", - "dev": true - }, - "@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "express": { + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", "dev": true, "requires": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" }, "dependencies": { - "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "requires": { - "sprintf-js": "~1.0.2" - } - }, - "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "requires": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - } - }, - "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "ms": "2.0.0" } }, - "locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "requires": { - "p-locate": "^4.1.0" - } + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true }, - "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", "dev": true, "requires": { - "p-try": "^2.0.0" + "ee-first": "1.1.1" } }, - "p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + } + } + }, + "express-urlrewrite": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/express-urlrewrite/-/express-urlrewrite-1.4.0.tgz", + "integrity": "sha512-PI5h8JuzoweS26vFizwQl6UTF25CAHSggNv0J25Dn/IKZscJHWZzPrI5z2Y2jgOzIaw2qh8l6+/jUcig23Z2SA==", + "dev": true, + "requires": { + "debug": "*", + "path-to-regexp": "^1.0.3" + }, + "dependencies": { + "path-to-regexp": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.8.0.tgz", + "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==", "dev": true, "requires": { - "p-limit": "^2.2.0" + "isarray": "0.0.1" } - }, - "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true - }, - "path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true - }, - "resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true } } }, - "@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, - "@jest/console": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-27.5.1.tgz", - "integrity": "sha512-kZ/tNpS3NXn0mlXXXPNuDZnb4c0oZ20r4K5eemM2k30ZC3G0T02nXUvyhf5YdbXWHPEJLc9qGLxEZ216MdL+Zg==", + "fast-diff": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", + "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", + "dev": true + }, + "fast-fifo": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.0.tgz", + "integrity": "sha512-IgfweLvEpwyA4WgiQe9Nx6VV2QkML2NkvZnk1oKnIzXgXdWxuhF7zw4DvLTPZJn6PIUneiAXPF24QmoEqHTjyw==" + }, + "fast-glob": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", + "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", "dev": true, "requires": { - "@jest/types": "^27.5.1", - "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^27.5.1", - "jest-util": "^27.5.1", - "slash": "^3.0.0" + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" } }, - "@jest/core": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-27.5.1.tgz", - "integrity": "sha512-AK6/UTrvQD0Cd24NSqmIA6rKsu0tKIxfiCducZvqxYdmMisOYAsdItspT+fQDQYARPf8XgjAFZi0ogW2agH5nQ==", + "fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true + }, + "fastq": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.13.0.tgz", + "integrity": "sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==", "dev": true, "requires": { - "@jest/console": "^27.5.1", - "@jest/reporters": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "emittery": "^0.8.1", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^27.5.1", - "jest-config": "^27.5.1", - "jest-haste-map": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-resolve-dependencies": "^27.5.1", - "jest-runner": "^27.5.1", - "jest-runtime": "^27.5.1", - "jest-snapshot": "^27.5.1", - "jest-util": "^27.5.1", - "jest-validate": "^27.5.1", - "jest-watcher": "^27.5.1", - "micromatch": "^4.0.4", - "rimraf": "^3.0.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" + "reusify": "^1.0.4" } }, - "@jest/environment": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-27.5.1.tgz", - "integrity": "sha512-/WQjhPJe3/ghaol/4Bq480JKXV/Rfw8nQdN7f41fM8VDHLcxKXou6QyXAh3EFr9/bVG3x74z1NWDkP87EiY8gA==", + "fb-watchman": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.1.tgz", + "integrity": "sha512-DkPJKQeY6kKwmuMretBhr7G6Vodr7bFwDYTXIkfG1gjvNpaxBTQV3PbXg6bR1c1UP4jPOX0jHUbbHANL9vRjVg==", "dev": true, "requires": { - "@jest/fake-timers": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "jest-mock": "^27.5.1" + "bser": "2.1.1" } }, - "@jest/fake-timers": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-27.5.1.tgz", - "integrity": "sha512-/aPowoolwa07k7/oM3aASneNeBGCmGQsc3ugN4u6s4C/+s5M64MFo/+djTdiwcbQlRfFElGuDXWzaWj6QgKObQ==", + "file-entry-cache": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", "dev": true, "requires": { - "@jest/types": "^27.5.1", - "@sinonjs/fake-timers": "^8.0.1", - "@types/node": "*", - "jest-message-util": "^27.5.1", - "jest-mock": "^27.5.1", - "jest-util": "^27.5.1" + "flat-cache": "^3.0.4" } }, - "@jest/globals": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-27.5.1.tgz", - "integrity": "sha512-ZEJNB41OBQQgGzgyInAv0UUfDDj3upmHydjieSxFvTRuZElrx7tXg/uVQ5hYVEwiXs3+aMsAeEc9X7xiSKCm4Q==", + "fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dev": true, "requires": { - "@jest/environment": "^27.5.1", - "@jest/types": "^27.5.1", - "expect": "^27.5.1" + "to-regex-range": "^5.0.1" } }, - "@jest/reporters": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-27.5.1.tgz", - "integrity": "sha512-cPXh9hWIlVJMQkVk84aIvXuBB4uQQmFqZiacloFuGiP3ah1sbCxCosidXFDfqG8+6fO1oR2dTJTlsOy4VFmUfw==", + "finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", "dev": true, "requires": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.2", - "graceful-fs": "^4.2.9", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^5.1.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", - "istanbul-reports": "^3.1.3", - "jest-haste-map": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-util": "^27.5.1", - "jest-worker": "^27.5.1", - "slash": "^3.0.0", - "source-map": "^0.6.0", - "string-length": "^4.0.1", - "terminal-link": "^2.0.0", - "v8-to-istanbul": "^8.1.0" + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + } } }, - "@jest/source-map": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-27.5.1.tgz", - "integrity": "sha512-y9NIHUYF3PJRlHk98NdC/N1gl88BL08aQQgu4k4ZopQkCw9t9cV8mtl3TV8b/YCB8XaVTFrmUTAJvjsntDireg==", + "find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, "requires": { - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9", - "source-map": "^0.6.0" + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" } }, - "@jest/test-result": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-27.5.1.tgz", - "integrity": "sha512-EW35l2RYFUcUQxFJz5Cv5MTOxlJIQs4I7gxzi2zVU7PJhOwfYq1MdC5nhSmYjX1gmMmLPvB3sIaC+BkcHRBfag==", + "flat-cache": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", + "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", "dev": true, "requires": { - "@jest/console": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" + "flatted": "^3.1.0", + "rimraf": "^3.0.2" } }, - "@jest/test-sequencer": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-27.5.1.tgz", - "integrity": "sha512-LCheJF7WB2+9JuCS7VB/EmGIdQuhtqjRNI9A43idHv3E4KltCTsPsLxvdaubFHSYwY/fNjMWjl6vNRhDiN7vpQ==", - "dev": true, - "requires": { - "@jest/test-result": "^27.5.1", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^27.5.1", - "jest-runtime": "^27.5.1" - } + "flatted": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.1.1.tgz", + "integrity": "sha512-zAoAQiudy+r5SvnSw3KJy5os/oRJYHzrzja/tBDqrZtNhUw8bt6y8OBzMWcjWr+8liV8Eb6yOhw8WZ7VFZ5ZzA==", + "dev": true }, - "@jest/transform": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-27.5.1.tgz", - "integrity": "sha512-ipON6WtYgl/1329g5AIJVbUuEh0wZVbdpGwC99Jw4LwuoBNS95MVphU6zOeD9pDkon+LLbFL7lOQRapbB8SCHw==", + "for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", "dev": true, "requires": { - "@babel/core": "^7.1.0", - "@jest/types": "^27.5.1", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", - "convert-source-map": "^1.4.0", - "fast-json-stable-stringify": "^2.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-util": "^27.5.1", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", - "slash": "^3.0.0", - "source-map": "^0.6.1", - "write-file-atomic": "^3.0.0" + "is-callable": "^1.1.3" } }, - "@jest/types": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-27.5.1.tgz", - "integrity": "sha512-Cx46iJ9QpwQTjIdq5VJu2QTMMs3QlEjI0x1QbBP5W1+nMzyc2XmimiRR/CbX9TO0cPTeUlxWMOu8mslYsJ8DEw==", - "dev": true, - "requires": { - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^16.0.0", - "chalk": "^4.0.0" - } + "forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true }, - "@jridgewell/resolve-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", - "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", "dev": true }, - "@jridgewell/sourcemap-codec": { - "version": "1.4.14", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", - "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", + "fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true }, - "@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, - "requires": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } + "optional": true }, - "@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "function.prototype.name": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.5.tgz", + "integrity": "sha512-uN7m/BzVKQnCUF/iW8jYea67v++2u7m5UgENbHRtdDVclOUP+FMPlCNdmk0h/ysGyo2tavMJEDqJAkJdRa1vMA==", "dev": true, "requires": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "es-abstract": "^1.19.0", + "functions-have-names": "^1.2.2" } }, - "@nodelib/fs.stat": { + "functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true + }, + "gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true + }, + "get-caller-file": { "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, - "@nodelib/fs.walk": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.7.tgz", - "integrity": "sha512-BTIhocbPBSrRmHxOAJFtR18oLhxTtAFDAvL8hY1S3iU8k+E60W/YFs4jrixGzQjMpF4qPXxIQHcjVD9dz1C2QA==", - "dev": true, - "requires": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - } + "get-east-asian-width": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.2.0.tgz", + "integrity": "sha512-2nk+7SIVb14QrgXFHcm84tD4bKQz0RxPuMT8Ag5KPOq7J5fEmAg0UbXdTOSHqNuHSU28k55qnceesxXRZGzKWA==", + "dev": true }, - "@octokit/auth-token": { - "version": "2.4.5", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz", - "integrity": "sha512-BpGYsPgJt05M7/L/5FoE1PiAbdxXFZkX/3kDYcsvd1v6UhlnE5e96dTDr0ezX/EFwciQxf3cNV0loipsURU+WA==", + "get-intrinsic": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.0.tgz", + "integrity": "sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q==", + "dev": true, "requires": { - "@octokit/types": "^6.0.3" + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" } }, - "@octokit/core": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.4.0.tgz", - "integrity": "sha512-6/vlKPP8NF17cgYXqucdshWqmMZGXkuvtcrWCgU5NOI0Pl2GjlmZyWgBMrU8zJ3v2MJlM6++CiB45VKYmhiWWg==", - "requires": { - "@octokit/auth-token": "^2.4.4", - "@octokit/graphql": "^4.5.8", - "@octokit/request": "^5.4.12", - "@octokit/request-error": "^2.0.5", - "@octokit/types": "^6.0.3", - "before-after-hook": "^2.2.0", - "universal-user-agent": "^6.0.0" - } + "get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true }, - "@octokit/endpoint": { - "version": "6.0.11", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.11.tgz", - "integrity": "sha512-fUIPpx+pZyoLW4GCs3yMnlj2LfoXTWDUVPTC4V3MUEKZm48W+XYpeWSZCv+vYF1ZABUm2CqnDVf1sFtIYrj7KQ==", - "requires": { - "@octokit/types": "^6.0.3", - "is-plain-object": "^5.0.0", - "universal-user-agent": "^6.0.0" - } + "get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true }, - "@octokit/graphql": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.2.tgz", - "integrity": "sha512-WmsIR1OzOr/3IqfG9JIczI8gMJUMzzyx5j0XXQ4YihHtKlQc+u35VpVoOXhlKAlaBntvry1WpAzPl/a+s3n89Q==", + "get-symbol-description": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz", + "integrity": "sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==", + "dev": true, "requires": { - "@octokit/request": "^5.3.0", - "@octokit/types": "^6.0.3", - "universal-user-agent": "^6.0.0" + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" } }, - "@octokit/openapi-types": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.2.3.tgz", - "integrity": "sha512-V1ycxkR19jqbIl3evf2RQiMRBvTNRi+Iy9h20G5OP5dPfEF6GJ1DPlUeiZRxo2HJxRr+UA4i0H1nn4btBDPFrw==" + "get-tsconfig": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.5.0.tgz", + "integrity": "sha512-MjhiaIWCJ1sAU4pIQ5i5OfOuHHxVo1oYeNsWTON7jxYkod8pHocXeh+SSbmu5OZZZK73B6cbJ2XADzXehLyovQ==", + "dev": true }, - "@octokit/plugin-paginate-rest": { - "version": "2.13.3", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.13.3.tgz", - "integrity": "sha512-46lptzM9lTeSmIBt/sVP/FLSTPGx6DCzAdSX3PfeJ3mTf4h9sGC26WpaQzMEq/Z44cOcmx8VsOhO+uEgE3cjYg==", + "glob": { + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", + "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", + "dev": true, "requires": { - "@octokit/types": "^6.11.0" + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" } }, - "@octokit/plugin-rest-endpoint-methods": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.3.1.tgz", - "integrity": "sha512-3B2iguGmkh6bQQaVOtCsS0gixrz8Lg0v4JuXPqBcFqLKuJtxAUf3K88RxMEf/naDOI73spD+goJ/o7Ie7Cvdjg==", + "glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, "requires": { - "@octokit/types": "^6.16.2", - "deprecation": "^2.3.1" + "is-glob": "^4.0.1" } }, - "@octokit/request": { - "version": "5.4.15", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.15.tgz", - "integrity": "sha512-6UnZfZzLwNhdLRreOtTkT9n57ZwulCve8q3IT/Z477vThu6snfdkBuhxnChpOKNGxcQ71ow561Qoa6uqLdPtag==", - "requires": { - "@octokit/endpoint": "^6.0.1", - "@octokit/request-error": "^2.0.0", - "@octokit/types": "^6.7.1", - "is-plain-object": "^5.0.0", - "node-fetch": "^2.6.1", - "universal-user-agent": "^6.0.0" + "globals": { + "version": "13.23.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.23.0.tgz", + "integrity": "sha512-XAmF0RjlrjY23MA51q3HltdlGxUpXPvg0GioKiD9X6HD28iMjo2dKC8Vqwm7lne4GNr78+RHTfliktR6ZH09wA==", + "dev": true, + "requires": { + "type-fest": "^0.20.2" } }, - "@octokit/request-error": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.5.tgz", - "integrity": "sha512-T/2wcCFyM7SkXzNoyVNWjyVlUwBvW3igM3Btr/eKYiPmucXTtkxt2RBsf6gn3LTzaLSLTQtNmvg+dGsOxQrjZg==", + "globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, "requires": { - "@octokit/types": "^6.0.3", - "deprecation": "^2.0.0", - "once": "^1.4.0" + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" } }, - "@octokit/types": { - "version": "6.16.2", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.16.2.tgz", - "integrity": "sha512-wWPSynU4oLy3i4KGyk+J1BLwRKyoeW2TwRHgwbDz17WtVFzSK2GOErGliruIx8c+MaYtHSYTx36DSmLNoNbtgA==", + "gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, "requires": { - "@octokit/openapi-types": "^7.2.3" + "get-intrinsic": "^1.1.3" } }, - "@octokit/webhooks-types": { - "version": "6.3.6", - "resolved": "https://registry.npmjs.org/@octokit/webhooks-types/-/webhooks-types-6.3.6.tgz", - "integrity": "sha512-x6yBtWobk20OhOiJ4VWsH3iJ/30IG+VoDWSgS4Tiyidi2KOiBS3bL+AJrNuq4OyNuWOM/FbHQTp6KEZs1oPD/g==" + "graceful-fs": { + "version": "4.2.9", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", + "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", + "dev": true }, - "@sindresorhus/is": { - "version": "0.14.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", - "integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==", + "graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true }, - "@sinonjs/commons": { - "version": "1.8.3", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.3.tgz", - "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==", + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "dev": true, "requires": { - "type-detect": "4.0.8" + "function-bind": "^1.1.1" } }, - "@sinonjs/fake-timers": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-8.1.0.tgz", - "integrity": "sha512-OAPJUAtgeINhh/TAlUID4QTs53Njm7xzddaVlEs/SXwgtiD1tW22zAB/W1wdqfrpmikgaWQ9Fw6Ws+hsiRm5Vg==", + "has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", "dev": true, "requires": { - "@sinonjs/commons": "^1.7.0" + "get-intrinsic": "^1.1.1" } }, - "@szmarczak/http-timer": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-1.1.2.tgz", - "integrity": "sha512-XIB2XbzHTN6ieIjfIMV9hlVcfPU26s2vafYWQcZHWXHOxiaRZYEDKEwdl129Zyg50+foYV2jCgtrqSA6qNuNSA==", + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + }, + "has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", "dev": true, "requires": { - "defer-to-connect": "^1.0.1" + "has-symbols": "^1.0.2" } }, - "@tootallnate/once": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", - "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", + "html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, - "@tsconfig/node10": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.8.tgz", - "integrity": "sha512-6XFfSQmMgq0CFLY1MslA/CPUfhIL919M1rMsa5lP2P097N2Wd1sSX0tx1u4olM16fLNhtHZpRhedZJphNJqmZg==", - "dev": true + "http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dev": true, + "requires": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + } }, - "@tsconfig/node12": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.9.tgz", - "integrity": "sha512-/yBMcem+fbvhSREH+s14YJi18sp7J9jpuhYByADT2rypfajMZZN4WQ6zBGgBKp53NKmqI36wFYDb3yaMPurITw==", + "human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", "dev": true }, - "@tsconfig/node14": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.1.tgz", - "integrity": "sha512-509r2+yARFfHHE7T6Puu2jjkoycftovhXRqW328PDXTVGKihlb1P8Z9mMZH04ebyajfRY7dedfGynlrFHJUQCg==", + "husky": { + "version": "9.0.11", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.0.11.tgz", + "integrity": "sha512-AB6lFlbwwyIqMdHYhwPe+kjOC3Oc5P3nThEoW/AaO2BX3vJDjWPFxYLxokUZOo6RNX20He3AaT8sESs9NJcmEw==", "dev": true }, - "@tsconfig/node16": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.2.tgz", - "integrity": "sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA==", + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" + }, + "ignore": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", "dev": true }, - "@types/babel__core": { - "version": "7.1.18", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.18.tgz", - "integrity": "sha512-S7unDjm/C7z2A2R9NzfKCK1I+BAALDtxEmsJBwlB3EzNfb929ykjL++1CK9LO++EIp2fQrC8O+BwjKvz6UeDyQ==", + "import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", "dev": true, "requires": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" } }, - "@types/babel__generator": { - "version": "7.6.4", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", - "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", + "import-local": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", + "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", "dev": true, "requires": { - "@babel/types": "^7.0.0" + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" } }, - "@types/babel__template": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", - "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "dev": true, "requires": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" + "once": "^1.3.0", + "wrappy": "1" } }, - "@types/babel__traverse": { - "version": "7.11.1", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.11.1.tgz", - "integrity": "sha512-Vs0hm0vPahPMYi9tDjtP66llufgO3ST16WXaSTtDGEl9cewAl3AibmxWw6TINOqHPT9z0uABKAYjT9jNSg4npw==", + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "internal-slot": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.5.tgz", + "integrity": "sha512-Y+R5hJrzs52QCG2laLn4udYVnxsfny9CpOhNhUvk/SSSVyF6T27FzRbF0sroPidSu3X8oEAkOn2K804mjpt6UQ==", "dev": true, "requires": { - "@babel/types": "^7.3.0" + "get-intrinsic": "^1.2.0", + "has": "^1.0.3", + "side-channel": "^1.0.4" } }, - "@types/dockerode": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/@types/dockerode/-/dockerode-3.2.6.tgz", - "integrity": "sha512-rz50DbrfQGsKOlkLbkknXNyurl2z/yR0CmV/OhzPW3Ef3jbIGoIE+Rd+2UC17gNVrnDl+mpejCI7RqQNe2bEbw==", + "ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true + }, + "is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", "dev": true, "requires": { - "@types/node": "*" + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" } }, - "@types/graceful-fs": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.5.tgz", - "integrity": "sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw==", + "is-array-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.1.tgz", + "integrity": "sha512-ASfLknmY8Xa2XtB4wmbz13Wu202baeA18cJBCeCy0wXUHZF0IPyVEXqKEcd+t2fNSLLL1vC6k7lxZEojNbISXQ==", "dev": true, "requires": { - "@types/node": "*" + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-typed-array": "^1.1.10" } }, - "@types/istanbul-lib-coverage": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz", - "integrity": "sha512-sz7iLqvVUg1gIedBOvlkxPlc8/uVzyS5OwGz1cKjXzkl3FpL3al0crU8YGU1WoHkxn0Wxbw5tyi6hvzJKNzFsw==", + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", "dev": true }, - "@types/istanbul-lib-report": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", - "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "is-bigint": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", "dev": true, "requires": { - "@types/istanbul-lib-coverage": "*" + "has-bigints": "^1.0.1" } }, - "@types/istanbul-reports": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", - "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", + "is-boolean-object": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", "dev": true, "requires": { - "@types/istanbul-lib-report": "*" + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" } }, - "@types/jest": { - "version": "27.0.2", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-27.0.2.tgz", - "integrity": "sha512-4dRxkS/AFX0c5XW6IPMNOydLn2tEhNhJV7DnYK+0bjoJZ+QTmfucBlihX7aoEsh/ocYtkLC73UbnBXBXIxsULA==", + "is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true + }, + "is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, + "is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", "dev": true, "requires": { - "jest-diff": "^27.0.0", - "pretty-format": "^27.0.0" + "has-tostringtag": "^1.0.0" } }, - "@types/json-schema": { - "version": "7.0.7", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.7.tgz", - "integrity": "sha512-cxWFQVseBm6O9Gbw1IWb8r6OS4OhSt3hPZLkFApLjM8TEXROBuQGLAH2i2gZpcXdLBIrpXuTDhH7Vbm1iXmNGA==", + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", "dev": true }, - "@types/json5": { - "version": "0.0.29", - "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", - "integrity": "sha1-7ihweulOEdK4J7y+UnC86n8+ce4=", + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, - "@types/node": { - "version": "18.7.13", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.13.tgz", - "integrity": "sha512-46yIhxSe5xEaJZXWdIBP7GU4HDTG8/eo0qd9atdiL+lFpA03y8KS+lkTN834TWJj5767GbWv4n/P6efyTFt1Dw==", + "is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", "dev": true }, - "@types/node-forge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.0.1.tgz", - "integrity": "sha512-96ELNKv9tQJ19afdBUiM5iDw7OYEc53iUc51gAPR2aGaqRsO1DBROjqgZRjZa1tkPj7TnEOR0EnyAX6iryGkzA==", + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "requires": { - "@types/node": "*" + "is-extglob": "^2.1.1" } }, - "@types/parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==", + "is-map": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.2.tgz", + "integrity": "sha512-cOZFQQozTha1f4MxLFzlgKYPTyj26picdZTx82hbc/Xf4K/tZOOXSCkMvU4pKioRXGDLJRn0GM7Upe7kR721yg==", "dev": true }, - "@types/prettier": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.2.3.tgz", - "integrity": "sha512-PijRCG/K3s3w1We6ynUKdxEc5AcuuH3NBmMDP8uvKVp6X43UY7NQlTzczakXP3DJR0F4dfNQIGjU2cUeRYs2AA==", + "is-negative-zero": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz", + "integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==", "dev": true }, - "@types/stack-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.0.tgz", - "integrity": "sha512-RJJrrySY7A8havqpGObOB4W92QXKJo63/jFLLgpvOtsGUqbQZ9Sbgl35KMm1DjC6j7AvmmU2bIno+3IyEaemaw==", + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true }, - "@types/tar-stream": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/@types/tar-stream/-/tar-stream-2.2.2.tgz", - "integrity": "sha512-1AX+Yt3icFuU6kxwmPakaiGrJUwG44MpuiqPg4dSolRFk6jmvs4b3IbUol9wKDLIgU76gevn3EwE8y/DkSJCZQ==", + "is-number-object": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", "dev": true, "requires": { - "@types/node": "*" + "has-tostringtag": "^1.0.0" } }, - "@types/yargs": { - "version": "16.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-16.0.3.tgz", - "integrity": "sha512-YlFfTGS+zqCgXuXNV26rOIeETOkXnGQXP/pjjL9P0gO/EP9jTmc7pUBhx+jVEIxpq41RX33GQ7N3DzOSfZoglQ==", + "is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true + }, + "is-promise": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz", + "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==", + "dev": true + }, + "is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", "dev": true, "requires": { - "@types/yargs-parser": "*" + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" } }, - "@types/yargs-parser": { - "version": "20.2.0", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-20.2.0.tgz", - "integrity": "sha512-37RSHht+gzzgYeobbG+KWryeAW8J33Nhr69cjTqSYymXVZEN9NbRYWoYlRtDhHKPVT1FyNKwaTPC1NynKZpzRA==", + "is-set": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.2.tgz", + "integrity": "sha512-+2cnTEZeY5z/iXGbLhPrOAaK/Mau5k5eXq9j14CpRTftq0pAJu2MwVRSZhyZWBzx3o6X795Lz6Bpb6R0GKf37g==", "dev": true }, - "@typescript-eslint/eslint-plugin": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.26.0.tgz", - "integrity": "sha512-yA7IWp+5Qqf+TLbd8b35ySFOFzUfL7i+4If50EqvjT6w35X8Lv0eBHb6rATeWmucks37w+zV+tWnOXI9JlG6Eg==", + "is-shared-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz", + "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==", "dev": true, "requires": { - "@typescript-eslint/experimental-utils": "4.26.0", - "@typescript-eslint/scope-manager": "4.26.0", - "debug": "^4.3.1", - "functional-red-black-tree": "^1.0.1", - "lodash": "^4.17.21", - "regexpp": "^3.1.0", - "semver": "^7.3.5", - "tsutils": "^3.21.0" + "call-bind": "^1.0.2" } }, - "@typescript-eslint/experimental-utils": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-4.26.0.tgz", - "integrity": "sha512-TH2FO2rdDm7AWfAVRB5RSlbUhWxGVuxPNzGT7W65zVfl8H/WeXTk1e69IrcEVsBslrQSTDKQSaJD89hwKrhdkw==", + "is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true + }, + "is-string": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", "dev": true, "requires": { - "@types/json-schema": "^7.0.7", - "@typescript-eslint/scope-manager": "4.26.0", - "@typescript-eslint/types": "4.26.0", - "@typescript-eslint/typescript-estree": "4.26.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" - }, - "dependencies": { - "eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^2.0.0" - } - } + "has-tostringtag": "^1.0.0" } }, - "@typescript-eslint/parser": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-4.33.0.tgz", - "integrity": "sha512-ZohdsbXadjGBSK0/r+d87X0SBmKzOq4/S5nzK6SBgJspFo9/CUDJ7hjayuze+JK7CZQLDMroqytp7pOcFKTxZA==", + "is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", "dev": true, "requires": { - "@typescript-eslint/scope-manager": "4.33.0", - "@typescript-eslint/types": "4.33.0", - "@typescript-eslint/typescript-estree": "4.33.0", - "debug": "^4.3.1" - }, - "dependencies": { - "@typescript-eslint/scope-manager": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.33.0.tgz", - "integrity": "sha512-5IfJHpgTsTZuONKbODctL4kKuQje/bzBRkwHE8UOZ4f89Zeddg+EGZs8PD8NcN4LdM3ygHWYB3ukPAYjvl/qbQ==", - "dev": true, - "requires": { - "@typescript-eslint/types": "4.33.0", - "@typescript-eslint/visitor-keys": "4.33.0" - } - }, - "@typescript-eslint/types": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.33.0.tgz", - "integrity": "sha512-zKp7CjQzLQImXEpLt2BUw1tvOMPfNoTAfb8l51evhYbOEEzdWyQNmHWWGPR6hwKJDAi+1VXSBmnhL9kyVTTOuQ==", - "dev": true - }, - "@typescript-eslint/typescript-estree": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.33.0.tgz", - "integrity": "sha512-rkWRY1MPFzjwnEVHsxGemDzqqddw2QbTJlICPD9p9I9LfsO8fdmfQPOX3uKfUaGRDFJbfrtm/sXhVXN4E+bzCA==", - "dev": true, - "requires": { - "@typescript-eslint/types": "4.33.0", - "@typescript-eslint/visitor-keys": "4.33.0", - "debug": "^4.3.1", - "globby": "^11.0.3", - "is-glob": "^4.0.1", - "semver": "^7.3.5", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/visitor-keys": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.33.0.tgz", - "integrity": "sha512-uqi/2aSz9g2ftcHWf8uLPJA70rUv6yuMW5Bohw+bwcuzaxQIHaKFZCKGoGXIrc9vkTJ3+0txM73K0Hq3d5wgIg==", - "dev": true, - "requires": { - "@typescript-eslint/types": "4.33.0", - "eslint-visitor-keys": "^2.0.0" - } - } + "has-symbols": "^1.0.2" } }, - "@typescript-eslint/scope-manager": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.26.0.tgz", - "integrity": "sha512-G6xB6mMo4xVxwMt5lEsNTz3x4qGDt0NSGmTBNBPJxNsrTXJSm21c6raeYroS2OwQsOyIXqKZv266L/Gln1BWqg==", + "is-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.10.tgz", + "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", "dev": true, "requires": { - "@typescript-eslint/types": "4.26.0", - "@typescript-eslint/visitor-keys": "4.26.0" + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" } }, - "@typescript-eslint/types": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.26.0.tgz", - "integrity": "sha512-rADNgXl1kS/EKnDr3G+m7fB9yeJNnR9kF7xMiXL6mSIWpr3Wg5MhxyfEXy/IlYthsqwBqHOr22boFbf/u6O88A==", + "is-weakmap": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.1.tgz", + "integrity": "sha512-NSBR4kH5oVj1Uwvv970ruUkCV7O1mzgVFO4/rev2cLRda9Tm9HrL70ZPut4rOHgY0FNrUu9BCbXA2sdQ+x0chA==", "dev": true }, - "@typescript-eslint/typescript-estree": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.26.0.tgz", - "integrity": "sha512-GHUgahPcm9GfBuy3TzdsizCcPjKOAauG9xkz9TR8kOdssz2Iz9jRCSQm6+aVFa23d5NcSpo1GdHGSQKe0tlcbg==", + "is-weakref": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", + "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", "dev": true, "requires": { - "@typescript-eslint/types": "4.26.0", - "@typescript-eslint/visitor-keys": "4.26.0", - "debug": "^4.3.1", - "globby": "^11.0.3", - "is-glob": "^4.0.1", - "semver": "^7.3.5", - "tsutils": "^3.21.0" + "call-bind": "^1.0.2" } }, - "@typescript-eslint/visitor-keys": { - "version": "4.26.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.26.0.tgz", - "integrity": "sha512-cw4j8lH38V1ycGBbF+aFiLUls9Z0Bw8QschP3mkth50BbWzgFS33ISIgBzUMuQ2IdahoEv/rXstr8Zhlz4B1Zg==", + "is-weakset": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.2.tgz", + "integrity": "sha512-t2yVvttHkQktwnNNmBQ98AhENLdPUTDTE21uPqAQ0ARwQfGeQKRVS0NNurH7bTf7RrvcVn1OOge45CnBeHCSmg==", "dev": true, "requires": { - "@typescript-eslint/types": "4.26.0", - "eslint-visitor-keys": "^2.0.0" + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" } }, - "@vercel/ncc": { - "version": "0.34.0", - "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.34.0.tgz", - "integrity": "sha512-G9h5ZLBJ/V57Ou9vz5hI8pda/YQX5HQszCs3AmIus3XzsmRn/0Ptic5otD3xVST8QLKk7AMk7AqpsyQGN7MZ9A==", + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", "dev": true }, - "abab": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.5.tgz", - "integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, - "accepts": { - "version": "1.3.7", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", - "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", + "istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true + }, + "istanbul-lib-instrument": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.1.0.tgz", + "integrity": "sha512-czwUz525rkOFDJxfKK6mYfIs9zBKILyrZQxjz3ABhjQXhbhFsSbo1HW/BFcsDnfJYJWA6thRR5/TUY2qs5W99Q==", "dev": true, "requires": { - "mime-types": "~2.1.24", - "negotiator": "0.6.2" + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } } }, - "acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", - "dev": true - }, - "acorn-globals": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-6.0.0.tgz", - "integrity": "sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg==", + "istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", "dev": true, "requires": { - "acorn": "^7.1.1", - "acorn-walk": "^7.1.1" + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" } }, - "acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", "dev": true, - "requires": {} - }, - "acorn-walk": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", - "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==", - "dev": true + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + } }, - "agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "istanbul-reports": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz", + "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==", "dev": true, "requires": { - "debug": "4" + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" } }, - "aggregate-error": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", - "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", + "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", "dev": true, "requires": { - "clean-stack": "^2.0.0", - "indent-string": "^4.0.0" + "@jest/core": "^29.7.0", + "@jest/types": "^29.6.3", + "import-local": "^3.0.2", + "jest-cli": "^29.7.0" } }, - "ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "jest-changed-files": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", + "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", "dev": true, "requires": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" + "execa": "^5.0.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0" } }, - "ansi-align": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.1.tgz", - "integrity": "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==", + "jest-circus": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", + "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", "dev": true, "requires": { - "string-width": "^4.1.0" + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^1.0.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.7.0", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0", + "pretty-format": "^29.7.0", + "pure-rand": "^6.0.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" } }, - "ansi-colors": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", - "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", - "dev": true + "jest-cli": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", + "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", + "dev": true, + "requires": { + "@jest/core": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "create-jest": "^29.7.0", + "exit": "^0.1.2", + "import-local": "^3.0.2", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "yargs": "^17.3.1" + } }, - "ansi-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "jest-config": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", + "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", "dev": true, "requires": { - "type-fest": "^0.21.3" - }, - "dependencies": { - "type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true - } + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-jest": "^29.7.0", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" } }, - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true + "jest-diff": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", + "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "diff-sequences": "^29.6.3", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + } }, - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "jest-docblock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", + "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", "dev": true, "requires": { - "color-convert": "^2.0.1" + "detect-newline": "^3.0.0" } }, - "anymatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", - "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", + "jest-each": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", + "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", "dev": true, "requires": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "jest-util": "^29.7.0", + "pretty-format": "^29.7.0" } }, - "arg": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", - "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", - "dev": true + "jest-environment-node": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", + "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", + "dev": true, + "requires": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + } }, - "argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "jest-get-type": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", + "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", "dev": true }, - "array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", - "dev": true + "jest-haste-map": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", + "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", + "dev": true, + "requires": { + "@jest/types": "^29.6.3", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "fsevents": "^2.3.2", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + } }, - "array-includes": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.3.tgz", - "integrity": "sha512-gcem1KlBU7c9rB+Rq8/3PPKsK2kjqeEBa3bD5kkQo4nYlOHQCJqIJFqBXDEfwaRuYTT4E+FxA9xez7Gf/e3Q7A==", + "jest-leak-detector": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", + "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", "dev": true, "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.0-next.2", - "get-intrinsic": "^1.1.1", - "is-string": "^1.0.5" + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" } }, - "array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "dev": true + "jest-matcher-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", + "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + } }, - "array.prototype.flat": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.4.tgz", - "integrity": "sha512-4470Xi3GAPAjZqFcljX2xzckv1qeKPizoNkiS0+O4IoPR2ZNpcjE0pkhdihlDouK+x6QOast26B4Q/O9DJnwSg==", + "jest-message-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", + "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", "dev": true, "requires": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.0-next.1" + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.6.3", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" } }, - "asn1": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", - "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "jest-mock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", + "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", + "dev": true, "requires": { - "safer-buffer": "~2.1.0" + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-util": "^29.7.0" } }, - "astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true + "jest-pnp-resolver": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz", + "integrity": "sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w==", + "dev": true, + "requires": {} }, - "asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "jest-regex-util": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", + "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", "dev": true }, - "axios": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.23.0.tgz", - "integrity": "sha512-NmvAE4i0YAv5cKq8zlDoPd1VLKAqX5oLuZKs8xkJa4qi6RGn0uhCYFjWtHHC9EM/MwOwYWOs53W+V0aqEXq1sg==", - "requires": { - "follow-redirects": "^1.14.4" - } - }, - "babel-jest": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-27.5.1.tgz", - "integrity": "sha512-cdQ5dXjGRd0IBRATiQ4mZGlGlRE8kJpjPOixdNRdT+m3UcNqmYWN6rK6nvtXYfY3D76cb8s/O1Ss8ea24PIwcg==", + "jest-resolve": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", + "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", "dev": true, "requires": { - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^27.5.1", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", "slash": "^3.0.0" } }, - "babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "jest-resolve-dependencies": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", + "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", "dev": true, "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.7.0" } }, - "babel-plugin-jest-hoist": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-27.5.1.tgz", - "integrity": "sha512-50wCwD5EMNW4aRpOwtqzyZHIewTYNxLA4nhB+09d8BIssfNfzBRhkBIHiaPv1Si226TQSvp8gxAJm2iY2qs2hQ==", + "jest-runner": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", + "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", "dev": true, "requires": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.0.0", - "@types/babel__traverse": "^7.0.6" + "@jest/console": "^29.7.0", + "@jest/environment": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-leak-detector": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-resolve": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-util": "^29.7.0", + "jest-watcher": "^29.7.0", + "jest-worker": "^29.7.0", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" } }, - "babel-preset-current-node-syntax": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", - "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", - "dev": true, - "requires": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.8.3", - "@babel/plugin-syntax-import-meta": "^7.8.3", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.8.3", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-top-level-await": "^7.8.3" + "jest-runtime": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", + "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", + "dev": true, + "requires": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/globals": "^29.7.0", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" } }, - "babel-preset-jest": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-27.5.1.tgz", - "integrity": "sha512-Nptf2FzlPCWYuJg41HBqXVT8ym6bXOevuCTbhxlUpjwtysGaIWFvDEjp4y+G7fl13FgOdjs7P/DmErqH7da0Ag==", + "jest-snapshot": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", + "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", "dev": true, "requires": { - "babel-plugin-jest-hoist": "^27.5.1", - "babel-preset-current-node-syntax": "^1.0.0" + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "natural-compare": "^1.4.0", + "pretty-format": "^29.7.0", + "semver": "^7.5.3" } }, - "balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true - }, - "base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" - }, - "basic-auth": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", - "integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==", + "jest-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", + "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", "dev": true, "requires": { - "safe-buffer": "5.1.2" + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" } }, - "bcrypt-pbkdf": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", - "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "jest-validate": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", + "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", + "dev": true, "requires": { - "tweetnacl": "^0.14.3" + "@jest/types": "^29.6.3", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "leven": "^3.1.0", + "pretty-format": "^29.7.0" + }, + "dependencies": { + "camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true + } } }, - "before-after-hook": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.1.tgz", - "integrity": "sha512-/6FKxSTWoJdbsLDF8tdIjaRiFXiE6UHsEHE3OPI/cwPURCVi1ukP0gmLn7XWEiFk5TcwQjjY5PWsU+j+tgXgmw==" - }, - "bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "jest-watcher": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", + "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", + "dev": true, "requires": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.7.0", + "string-length": "^4.0.1" } }, - "body-parser": { - "version": "1.19.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", - "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", + "jest-worker": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", + "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", "dev": true, "requires": { - "bytes": "3.1.0", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "~1.1.2", - "http-errors": "1.7.2", - "iconv-lite": "0.4.24", - "on-finished": "~2.3.0", - "qs": "6.7.0", - "raw-body": "2.4.0", - "type-is": "~1.6.17" + "@types/node": "*", + "jest-util": "^29.7.0", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" }, "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", "dev": true, "requires": { - "ms": "2.0.0" + "has-flag": "^4.0.0" } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true } } }, - "boxen": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/boxen/-/boxen-5.1.2.tgz", - "integrity": "sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==", - "dev": true, - "requires": { - "ansi-align": "^3.0.0", - "camelcase": "^6.2.0", - "chalk": "^4.1.0", - "cli-boxes": "^2.2.1", - "string-width": "^4.2.2", - "type-fest": "^0.20.2", - "widest-line": "^3.1.0", - "wrap-ansi": "^7.0.0" - }, - "dependencies": { - "camelcase": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz", - "integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==", - "dev": true - } - } + "jju": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/jju/-/jju-1.4.0.tgz", + "integrity": "sha1-o6vicYryQaKykE+EpiWXDzia4yo=", + "dev": true }, - "brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "dev": true, "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "argparse": "^2.0.1" } }, - "braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true + }, + "json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "json-parse-helpfulerror": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/json-parse-helpfulerror/-/json-parse-helpfulerror-1.0.3.tgz", + "integrity": "sha1-E/FM4C7tTpgSl7ZOueO5MuLdE9w=", "dev": true, "requires": { - "fill-range": "^7.0.1" + "jju": "^1.1.0" } }, - "browser-process-hrtime": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", - "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true }, - "browserslist": { - "version": "4.16.6", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.6.tgz", - "integrity": "sha512-Wspk/PqO+4W9qp5iUTJsa1B/QrYn1keNCcEP5OvP7WBwT4KaDly0uONYmC6Xa3Z5IqnUgS0KcgLYu1l74x0ZXQ==", + "json-server": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/json-server/-/json-server-0.17.4.tgz", + "integrity": "sha512-bGBb0WtFuAKbgI7JV3A864irWnMZSvBYRJbohaOuatHwKSRFUfqtQlrYMrB6WbalXy/cJabyjlb7JkHli6dYjQ==", "dev": true, "requires": { - "caniuse-lite": "^1.0.30001219", - "colorette": "^1.2.2", - "electron-to-chromium": "^1.3.723", - "escalade": "^3.1.1", - "node-releases": "^1.1.71" + "body-parser": "^1.19.0", + "chalk": "^4.1.2", + "compression": "^1.7.4", + "connect-pause": "^0.1.1", + "cors": "^2.8.5", + "errorhandler": "^1.5.1", + "express": "^4.17.1", + "express-urlrewrite": "^1.4.0", + "json-parse-helpfulerror": "^1.0.3", + "lodash": "^4.17.21", + "lodash-id": "^0.14.1", + "lowdb": "^1.0.0", + "method-override": "^3.0.0", + "morgan": "^1.10.0", + "nanoid": "^3.1.23", + "please-upgrade-node": "^3.2.0", + "pluralize": "^8.0.0", + "server-destroy": "^1.0.1", + "yargs": "^17.0.1" } }, - "bs-logger": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", - "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true + }, + "json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true + }, + "jsx-ast-utils": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.3.tgz", + "integrity": "sha512-fYQHZTZ8jSfmWZ0iyzfwiU4WDX4HpHbMCZ3gPlWYiCl3BoeOTsqKBqnTVfH2rYT7eP5c3sVbeSPHnnJOaTrWiw==", "dev": true, "requires": { - "fast-json-stable-stringify": "2.x" + "array-includes": "^3.1.5", + "object.assign": "^4.1.3" } }, - "bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true + }, + "language-subtag-registry": { + "version": "0.3.22", + "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.22.tgz", + "integrity": "sha512-tN0MCzyWnoz/4nHS6uxdlFWoUZT7ABptwKPQ52Ea7URk6vll88bWBVhodtnlfEuCcKWNGoc+uGbw1cwa9IKh/w==", + "dev": true + }, + "language-tags": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.5.tgz", + "integrity": "sha512-qJhlO9cGXi6hBGKoxEG/sKZDAHD5Hnu9Hs4WbOY3pCWXDhw0N8x1NenNzm2EnNLkLkk7J2SdxAkDSbb6ftT+UQ==", "dev": true, "requires": { - "node-int64": "^0.4.0" + "language-subtag-registry": "~0.3.2" } }, - "buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true + }, + "levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, "requires": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" } }, - "buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "lilconfig": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.0.0.tgz", + "integrity": "sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g==", "dev": true }, - "bytes": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", - "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==", + "lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, - "cacheable-request": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-6.1.0.tgz", - "integrity": "sha512-Oj3cAGPCqOZX7Rz64Uny2GYAZNliQSqfbePrgAQ1wKAihYmCUnraBtJtKcGR4xz7wF+LoJC+ssFZvv5BgF9Igg==", + "lint-staged": { + "version": "15.2.2", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.2.2.tgz", + "integrity": "sha512-TiTt93OPh1OZOsb5B7k96A/ATl2AjIZo+vnzFZ6oHK5FuTk63ByDtxGQpHm+kFETjEWqgkF95M8FRXKR/LEBcw==", "dev": true, "requires": { - "clone-response": "^1.0.2", - "get-stream": "^5.1.0", - "http-cache-semantics": "^4.0.0", - "keyv": "^3.0.0", - "lowercase-keys": "^2.0.0", - "normalize-url": "^4.1.0", - "responselike": "^1.0.2" + "chalk": "5.3.0", + "commander": "11.1.0", + "debug": "4.3.4", + "execa": "8.0.1", + "lilconfig": "3.0.0", + "listr2": "8.0.1", + "micromatch": "4.0.5", + "pidtree": "0.6.0", + "string-argv": "0.3.2", + "yaml": "2.3.4" }, "dependencies": { - "get-stream": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", - "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", - "dev": true, - "requires": { - "pump": "^3.0.0" - } + "chalk": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", + "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", + "dev": true }, - "lowercase-keys": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", - "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==", + "commander": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", + "dev": true + }, + "execa": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", + "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" + } + }, + "get-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", + "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "dev": true + }, + "human-signals": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", + "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", + "dev": true + }, + "is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "dev": true + }, + "mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true + }, + "npm-run-path": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.1.0.tgz", + "integrity": "sha512-sJOdmRGrY2sjNTRMbSvluQqg+8X7ZK61yvzBEIDhz4f8z1TZFYABsqjjCBd/0PUNE9M6QDgHJXQkGUEm7Q+l9Q==", + "dev": true, + "requires": { + "path-key": "^4.0.0" + } + }, + "onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "dev": true, + "requires": { + "mimic-fn": "^4.0.0" + } + }, + "path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true + }, + "signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true + }, + "strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", "dev": true } } }, - "call-bind": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", - "dev": true, - "requires": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" - } - }, - "callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true - }, - "camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true - }, - "caniuse-lite": { - "version": "1.0.30001234", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001234.tgz", - "integrity": "sha512-a3gjUVKkmwLdNysa1xkUAwN2VfJUJyVW47rsi3aCbkRCtbHAfo+rOsCqVw29G6coQ8gzAPb5XBXwiGHwme3isA==", - "dev": true - }, - "chalk": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.1.tgz", - "integrity": "sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg==", - "dev": true, - "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - } - }, - "char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true - }, - "chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" - }, - "ci": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ci/-/ci-2.1.1.tgz", - "integrity": "sha512-StBCU1G9zbhgVBqvslvOpT601zme9YfyZaUSjgXCtfnIynPuDBHX85WwnXv5cnh74bYo8S3xfPpI41yk1jZmRw==" - }, - "ci-info": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.2.0.tgz", - "integrity": "sha512-dVqRX7fLUm8J6FgHJ418XuIgDLZDkYcDFTeL6TA2gt5WlIZUQrrH6EZrNClwT/H0FateUsZkGIOPRrLbP+PR9A==", - "dev": true - }, - "cjs-module-lexer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.1.tgz", - "integrity": "sha512-jVamGdJPDeuQilKhvVn1h3knuMOZzr8QDnpk+M9aMlCaMkTDd6fBWPhiDqFvFZ07pL0liqabAiuy8SY4jGHeaw==", - "dev": true - }, - "clean-stack": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", - "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", - "dev": true - }, - "cli-boxes": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-2.2.1.tgz", - "integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==", - "dev": true - }, - "cli-cursor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", - "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", - "dev": true, - "requires": { - "restore-cursor": "^3.1.0" - } - }, - "cli-truncate": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", - "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", + "listr2": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-8.0.1.tgz", + "integrity": "sha512-ovJXBXkKGfq+CwmKTjluEqFi3p4h8xvkxGQQAQan22YCgef4KZ1mKGjzfGh6PL6AW5Csw0QiQPNuQyH+6Xk3hA==", "dev": true, "requires": { - "slice-ansi": "^3.0.0", - "string-width": "^4.2.0" + "cli-truncate": "^4.0.0", + "colorette": "^2.0.20", + "eventemitter3": "^5.0.1", + "log-update": "^6.0.0", + "rfdc": "^1.3.0", + "wrap-ansi": "^9.0.0" }, "dependencies": { - "slice-ansi": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", - "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", + "ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", + "dev": true + }, + "ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true + }, + "emoji-regex": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.3.0.tgz", + "integrity": "sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==", + "dev": true + }, + "string-width": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.1.0.tgz", + "integrity": "sha512-SEIJCWiX7Kg4c129n48aDRwLbFb2LJmXXFrWBG4NGaRtMQ3myKPKbwrD1BKqQn74oCoNMBVrfDEr5M9YxCsrkw==", + "dev": true, + "requires": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + } + }, + "strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", "dev": true, "requires": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" + "ansi-regex": "^6.0.1" + } + }, + "wrap-ansi": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.0.tgz", + "integrity": "sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==", + "dev": true, + "requires": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" } } } }, - "cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", - "dev": true, - "requires": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" - } - }, - "clone-response": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", - "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", + "locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, "requires": { - "mimic-response": "^1.0.0" + "p-locate": "^5.0.0" } }, - "co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, - "collect-v8-coverage": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", - "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==", + "lodash-id": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/lodash-id/-/lodash-id-0.14.1.tgz", + "integrity": "sha512-ikQPBTiq/d5m6dfKQlFdIXFzvThPi2Be9/AHxktOnDSfSxE1j9ICbBT5Elk1ke7HSTgM38LHTpmJovo9/klnLg==", "dev": true }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "dev": true }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "lodash.kebabcase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.kebabcase/-/lodash.kebabcase-4.1.1.tgz", + "integrity": "sha512-N8XRTIMMqqDgSy4VLKPnJ/+hpGZN+PHQiJnSenYqPaVV/NCqEogTnAdZLQiGKhxX+JCs8waWq2t1XHWKOmlY8g==", "dev": true }, - "colorette": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.2.2.tgz", - "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==", + "lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=", "dev": true }, - "combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "requires": { - "delayed-stream": "~1.0.0" - } + "lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true }, - "commander": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-9.1.0.tgz", - "integrity": "sha512-i0/MaqBtdbnJ4XQs4Pmyb+oFQl+q0lsAmokVUH92SlSw4fkeAcG3bVon+Qt7hmtF+u3Het6o4VgrcY3qAoEB6w==" + "lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", + "dev": true }, - "compressible": { - "version": "2.0.18", - "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", - "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", - "dev": true, - "requires": { - "mime-db": ">= 1.43.0 < 2" - } + "lodash.upperfirst": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/lodash.upperfirst/-/lodash.upperfirst-4.3.1.tgz", + "integrity": "sha512-sReKOYJIJf74dhJONhU4e0/shzi1trVbSWDOhKYE5XV2O+H7Sb2Dihwuc7xWxVl+DgFPyTqIN3zMfT9cq5iWDg==", + "dev": true }, - "compression": { - "version": "1.7.4", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.4.tgz", - "integrity": "sha512-jaSIDzP9pZVS4ZfQ+TzvtiWhdpFhE2RDHz8QJkpX9SIpLq88VueF5jJw6t+6CUQcAoA6t+x89MLrWAqpfDE8iQ==", + "log-update": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.0.0.tgz", + "integrity": "sha512-niTvB4gqvtof056rRIrTZvjNYE4rCUzO6X/X+kYjd7WFxXeJ0NwEFnRxX6ehkvv3jTwrXnNdtAak5XYZuIyPFw==", "dev": true, "requires": { - "accepts": "~1.3.5", - "bytes": "3.0.0", - "compressible": "~2.0.16", - "debug": "2.6.9", - "on-headers": "~1.0.2", - "safe-buffer": "5.1.2", - "vary": "~1.1.2" + "ansi-escapes": "^6.2.0", + "cli-cursor": "^4.0.0", + "slice-ansi": "^7.0.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" }, "dependencies": { - "bytes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", - "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", - "dev": true - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "ansi-escapes": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-6.2.0.tgz", + "integrity": "sha512-kzRaCqXnpzWs+3z5ABPQiVke+iq0KXkHo8xiWV4RPTi5Yli0l97BEQuhXV1s7+aSU/fu1kUuxgS4MsQ0fRuygw==", "dev": true, "requires": { - "ms": "2.0.0" + "type-fest": "^3.0.0" } }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", "dev": true - } - } - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true - }, - "configstore": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/configstore/-/configstore-5.0.1.tgz", - "integrity": "sha512-aMKprgk5YhBNyH25hj8wGt2+D52Sw1DRRIzqBwLp2Ya9mFmY8KPvvtvmna8SxVR9JMZ4kzMD68N22vlaRpkeFA==", - "dev": true, - "requires": { - "dot-prop": "^5.2.0", - "graceful-fs": "^4.1.2", - "make-dir": "^3.0.0", - "unique-string": "^2.0.0", - "write-file-atomic": "^3.0.0", - "xdg-basedir": "^4.0.0" - } - }, - "connect-pause": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/connect-pause/-/connect-pause-0.1.1.tgz", - "integrity": "sha1-smmyu4Ldsaw9tQmcD7WCq6mfs3o=", - "dev": true - }, - "content-disposition": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", - "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", - "dev": true, - "requires": { - "safe-buffer": "5.1.2" - } - }, - "content-type": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", - "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", - "dev": true - }, - "convert-source-map": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", - "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", - "dev": true, - "requires": { - "safe-buffer": "~5.1.1" - } - }, - "cookie": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", - "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==", - "dev": true - }, - "cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=", - "dev": true - }, - "cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "dev": true, - "requires": { - "object-assign": "^4", - "vary": "^1" - } - }, - "cosmiconfig": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.0.tgz", - "integrity": "sha512-pondGvTuVYDk++upghXJabWzL6Kxu6f26ljFw64Swq9v6sQPUL3EUlVDV56diOjpCayKihL6hVe8exIACU4XcA==", - "dev": true, - "requires": { - "@types/parse-json": "^4.0.0", - "import-fresh": "^3.2.1", - "parse-json": "^5.0.0", - "path-type": "^4.0.0", - "yaml": "^1.10.0" - }, - "dependencies": { - "parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - } - } - } - }, - "cpu-features": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.2.tgz", - "integrity": "sha512-/2yieBqvMcRj8McNzkycjW2v3OIUOibBfd2dLEJ0nWts8NobAxwiyw9phVNS6oDL8x8tz9F7uNVFEVpJncQpeA==", - "optional": true, - "requires": { - "nan": "^2.14.1" - } - }, - "create-require": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", - "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", - "dev": true - }, - "cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", - "dev": true, - "requires": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - } - }, - "crypto-random-string": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", - "integrity": "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==", - "dev": true - }, - "cssom": { - "version": "0.4.4", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.4.4.tgz", - "integrity": "sha512-p3pvU7r1MyyqbTk+WbNJIgJjG2VmTIaB10rI93LzVPrmDJKkzKYMtxxyAvQXR/NS6otuzveI7+7BBq3SjBS2mw==", - "dev": true - }, - "cssstyle": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", - "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", - "dev": true, - "requires": { - "cssom": "~0.3.6" - }, - "dependencies": { - "cssom": { - "version": "0.3.8", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", - "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", - "dev": true - } - } - }, - "data-urls": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-2.0.0.tgz", - "integrity": "sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ==", - "dev": true, - "requires": { - "abab": "^2.0.3", - "whatwg-mimetype": "^2.3.0", - "whatwg-url": "^8.0.0" - } - }, - "debug": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", - "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", - "requires": { - "ms": "2.1.2" - } - }, - "decimal.js": { - "version": "10.3.1", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz", - "integrity": "sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ==", - "dev": true - }, - "decompress-response": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", - "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", - "dev": true, - "requires": { - "mimic-response": "^1.0.0" - } - }, - "dedent": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", - "integrity": "sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=", - "dev": true - }, - "deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "dev": true - }, - "deep-is": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", - "dev": true - }, - "deepmerge": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", - "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", - "dev": true - }, - "defer-to-connect": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-1.1.3.tgz", - "integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==", - "dev": true - }, - "define-properties": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", - "dev": true, - "requires": { - "object-keys": "^1.0.12" - } - }, - "delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", - "dev": true - }, - "depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", - "dev": true - }, - "deprecation": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", - "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" - }, - "destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", - "dev": true - }, - "detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "dev": true - }, - "diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", - "dev": true - }, - "diff-sequences": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-27.5.1.tgz", - "integrity": "sha512-k1gCAXAsNgLwEL+Y8Wvl+M6oEFj5bgazfZULpS5CneoPPXRaCCW7dm+q21Ky2VEE5X+VeRDBVg1Pcvvsr4TtNQ==", - "dev": true - }, - "dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "dev": true, - "requires": { - "path-type": "^4.0.0" - } - }, - "docker-modem": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/docker-modem/-/docker-modem-3.0.3.tgz", - "integrity": "sha512-Tgkn2a+yiNP9FoZgMa/D9Wk+D2Db///0KOyKSYZRJa8w4+DzKyzQMkczKSdR/adQ0x46BOpeNkoyEOKjPhCzjw==", - "requires": { - "debug": "^4.1.1", - "readable-stream": "^3.5.0", - "split-ca": "^1.0.1", - "ssh2": "^1.4.0" - } - }, - "dockerode": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/dockerode/-/dockerode-3.3.1.tgz", - "integrity": "sha512-AS2mr8Lp122aa5n6d99HkuTNdRV1wkkhHwBdcnY6V0+28D3DSYwhxAk85/mM9XwD3RMliTxyr63iuvn5ZblFYQ==", - "requires": { - "docker-modem": "^3.0.0", - "tar-fs": "~2.0.1" - } - }, - "doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "requires": { - "esutils": "^2.0.2" - } - }, - "domexception": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/domexception/-/domexception-2.0.1.tgz", - "integrity": "sha512-yxJ2mFy/sibVQlu5qHjOkf9J3K6zgmCxgJ94u2EdvDOV09H+32LtRswEcUsmUWN72pVLOEnTSRaIVVzVQgS0dg==", - "dev": true, - "requires": { - "webidl-conversions": "^5.0.0" - }, - "dependencies": { - "webidl-conversions": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-5.0.0.tgz", - "integrity": "sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA==", - "dev": true - } - } - }, - "dot-prop": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", - "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", - "dev": true, - "requires": { - "is-obj": "^2.0.0" - }, - "dependencies": { - "is-obj": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", - "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", - "dev": true - } - } - }, - "duplexer3": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", - "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=", - "dev": true - }, - "ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", - "dev": true - }, - "electron-to-chromium": { - "version": "1.3.748", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.748.tgz", - "integrity": "sha512-fmIKfYALVeEybk/L2ucdgt7jN3JsbGtg3K9pmF/MRWgkeADBI1VSAa5IzdG2gZwTxsnsrFtdMpOTSM5mrBRKVQ==", - "dev": true - }, - "emittery": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.8.1.tgz", - "integrity": "sha512-uDfvUjVrfGJJhymx/kz6prltenw1u7WrCg1oa94zYY8xxVpLLUu045LAT0dhDZdXG58/EpPL/5kA180fQ/qudg==", - "dev": true - }, - "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", - "dev": true - }, - "end-of-stream": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", - "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", - "requires": { - "once": "^1.4.0" - } - }, - "enquirer": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", - "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", - "dev": true, - "requires": { - "ansi-colors": "^4.1.1" - } - }, - "error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, - "requires": { - "is-arrayish": "^0.2.1" - } - }, - "errorhandler": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/errorhandler/-/errorhandler-1.5.1.tgz", - "integrity": "sha512-rcOwbfvP1WTViVoUjcfZicVzjhjTuhSMntHh6mW3IrEiyE6mJyXvsToJUJGlGlw/2xU9P5whlWNGlIDVeCiT4A==", - "dev": true, - "requires": { - "accepts": "~1.3.7", - "escape-html": "~1.0.3" - } - }, - "es-abstract": { - "version": "1.18.3", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.3.tgz", - "integrity": "sha512-nQIr12dxV7SSxE6r6f1l3DtAeEYdsGpps13dR0TwJg1S8gyp4ZPgy3FZcHBgbiQqnoqSTb+oC+kO4UQ0C/J8vw==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "es-to-primitive": "^1.2.1", - "function-bind": "^1.1.1", - "get-intrinsic": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.2", - "is-callable": "^1.2.3", - "is-negative-zero": "^2.0.1", - "is-regex": "^1.1.3", - "is-string": "^1.0.6", - "object-inspect": "^1.10.3", - "object-keys": "^1.1.1", - "object.assign": "^4.1.2", - "string.prototype.trimend": "^1.0.4", - "string.prototype.trimstart": "^1.0.4", - "unbox-primitive": "^1.0.1" - } - }, - "es-to-primitive": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", - "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", - "dev": true, - "requires": { - "is-callable": "^1.1.4", - "is-date-object": "^1.0.1", - "is-symbol": "^1.0.2" - } - }, - "escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "dev": true - }, - "escape-goat": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/escape-goat/-/escape-goat-2.1.1.tgz", - "integrity": "sha512-8/uIhbG12Csjy2JEW7D9pHbreaVaS/OpN3ycnyvElTdwM5n6GY6W6e2IPemfvGZeUMqZ9A/3GqIZMgKnBhAw/Q==", - "dev": true - }, - "escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", - "dev": true - }, - "escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true - }, - "escodegen": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.0.0.tgz", - "integrity": "sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw==", - "dev": true, - "requires": { - "esprima": "^4.0.1", - "estraverse": "^5.2.0", - "esutils": "^2.0.2", - "optionator": "^0.8.1", - "source-map": "~0.6.1" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - }, - "levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", - "dev": true, - "requires": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" - } - }, - "optionator": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", - "dev": true, - "requires": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.6", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "word-wrap": "~1.2.3" - } - }, - "prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", - "dev": true - }, - "type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", - "dev": true, - "requires": { - "prelude-ls": "~1.1.2" - } - } - } - }, - "eslint": { - "version": "7.32.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", - "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", - "dev": true, - "requires": { - "@babel/code-frame": "7.12.11", - "@eslint/eslintrc": "^0.4.3", - "@humanwhocodes/config-array": "^0.5.0", - "ajv": "^6.10.0", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.0.1", - "doctrine": "^3.0.0", - "enquirer": "^2.3.5", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^2.1.0", - "eslint-visitor-keys": "^2.0.0", - "espree": "^7.3.1", - "esquery": "^1.4.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "functional-red-black-tree": "^1.0.1", - "glob-parent": "^5.1.2", - "globals": "^13.6.0", - "ignore": "^4.0.6", - "import-fresh": "^3.0.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "js-yaml": "^3.13.1", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.0.4", - "natural-compare": "^1.4.0", - "optionator": "^0.9.1", - "progress": "^2.0.0", - "regexpp": "^3.1.0", - "semver": "^7.2.1", - "strip-ansi": "^6.0.0", - "strip-json-comments": "^3.1.0", - "table": "^6.0.9", - "text-table": "^0.2.0", - "v8-compile-cache": "^2.0.3" - }, - "dependencies": { - "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "requires": { - "sprintf-js": "~1.0.2" - } - }, - "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - } - } - }, - "eslint-config-prettier": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz", - "integrity": "sha512-BgZuLUSeKzvlL/VUjx/Yb787VQ26RU3gGjA3iiFvdsp/2bMfVIWUVP7tjxtjS0e+HP409cPlPvNkQloz8C91ew==", - "dev": true, - "requires": {} - }, - "eslint-import-resolver-node": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz", - "integrity": "sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA==", - "dev": true, - "requires": { - "debug": "^2.6.9", - "resolve": "^1.13.1" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "eslint-module-utils": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.6.1.tgz", - "integrity": "sha512-ZXI9B8cxAJIH4nfkhTwcRTEAnrVfobYqwjWy/QMCZ8rHkZHFjf9yO4BzpiF9kCSfNlMG54eKigISHpX0+AaT4A==", - "dev": true, - "requires": { - "debug": "^3.2.7", - "pkg-dir": "^2.0.0" - }, - "dependencies": { - "debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - } - } - }, - "eslint-plugin-eslint-comments": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-eslint-comments/-/eslint-plugin-eslint-comments-3.2.0.tgz", - "integrity": "sha512-0jkOl0hfojIHHmEHgmNdqv4fmh7300NdpA9FFpF7zaoLvB/QeXOGNLIo86oAveJFrfB1p05kC8hpEMHM8DwWVQ==", - "dev": true, - "requires": { - "escape-string-regexp": "^1.0.5", - "ignore": "^5.0.5" - }, - "dependencies": { - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "ignore": { - "version": "5.1.8", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", - "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", - "dev": true - } - } - }, - "eslint-plugin-github": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/eslint-plugin-github/-/eslint-plugin-github-4.1.5.tgz", - "integrity": "sha512-fY+3C8914Efqzmb6ODvL0ZNjv8xxLkwmUasYZ189IY1gL7AxFE9CVED+MZA8B1e+OZtnfTdrQR036t5AYoun0A==", - "dev": true, - "requires": { - "@typescript-eslint/eslint-plugin": "^4.20.0", - "@typescript-eslint/parser": "^4.20.0", - "eslint-config-prettier": ">=8.0.0", - "eslint-plugin-eslint-comments": "^3.2.0", - "eslint-plugin-import": "^2.22.1", - "eslint-plugin-prettier": "^3.3.1", - "eslint-rule-documentation": ">=1.0.0", - "prettier": "^2.2.1", - "svg-element-attributes": "^1.3.1" - } - }, - "eslint-plugin-import": { - "version": "2.23.4", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.23.4.tgz", - "integrity": "sha512-6/wP8zZRsnQFiR3iaPFgh5ImVRM1WN5NUWfTIRqwOdeiGJlBcSk82o1FEVq8yXmy4lkIzTo7YhHCIxlU/2HyEQ==", - "dev": true, - "requires": { - "array-includes": "^3.1.3", - "array.prototype.flat": "^1.2.4", - "debug": "^2.6.9", - "doctrine": "^2.1.0", - "eslint-import-resolver-node": "^0.3.4", - "eslint-module-utils": "^2.6.1", - "find-up": "^2.0.0", - "has": "^1.0.3", - "is-core-module": "^2.4.0", - "minimatch": "^3.0.4", - "object.values": "^1.1.3", - "pkg-up": "^2.0.0", - "read-pkg-up": "^3.0.0", - "resolve": "^1.20.0", - "tsconfig-paths": "^3.9.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "dev": true, - "requires": { - "esutils": "^2.0.2" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "eslint-plugin-jest": { - "version": "25.2.4", - "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-25.2.4.tgz", - "integrity": "sha512-HRyinpgmEdkVr7pNPaYPHCoGqEzpgk79X8pg/xCeoAdurbyQjntJQ4pTzHl7BiVEBlam/F1Qsn+Dk0HtJO7Aaw==", - "dev": true, - "requires": { - "@typescript-eslint/experimental-utils": "^5.0.0" - }, - "dependencies": { - "@types/json-schema": { - "version": "7.0.9", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz", - "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==", - "dev": true - }, - "@typescript-eslint/experimental-utils": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-5.3.1.tgz", - "integrity": "sha512-RgFn5asjZ5daUhbK5Sp0peq0SSMytqcrkNfU4pnDma2D8P3ElZ6JbYjY8IMSFfZAJ0f3x3tnO3vXHweYg0g59w==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.3.1", - "@typescript-eslint/types": "5.3.1", - "@typescript-eslint/typescript-estree": "5.3.1", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" - } - }, - "@typescript-eslint/scope-manager": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.3.1.tgz", - "integrity": "sha512-XksFVBgAq0Y9H40BDbuPOTUIp7dn4u8oOuhcgGq7EoDP50eqcafkMVGrypyVGvDYHzjhdUCUwuwVUK4JhkMAMg==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.3.1", - "@typescript-eslint/visitor-keys": "5.3.1" - } - }, - "@typescript-eslint/types": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.3.1.tgz", - "integrity": "sha512-bG7HeBLolxKHtdHG54Uac750eXuQQPpdJfCYuw4ZI3bZ7+GgKClMWM8jExBtp7NSP4m8PmLRM8+lhzkYnSmSxQ==", - "dev": true - }, - "@typescript-eslint/typescript-estree": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.3.1.tgz", - "integrity": "sha512-PwFbh/PKDVo/Wct6N3w+E4rLZxUDgsoII/GrWM2A62ETOzJd4M6s0Mu7w4CWsZraTbaC5UQI+dLeyOIFF1PquQ==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.3.1", - "@typescript-eslint/visitor-keys": "5.3.1", - "debug": "^4.3.2", - "globby": "^11.0.4", - "is-glob": "^4.0.3", - "semver": "^7.3.5", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/visitor-keys": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.3.1.tgz", - "integrity": "sha512-3cHUzUuVTuNHx0Gjjt5pEHa87+lzyqOiHXy/Gz+SJOCW1mpw9xQHIIEwnKn+Thph1mgWyZ90nboOcSuZr/jTTQ==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.3.1", - "eslint-visitor-keys": "^3.0.0" - } - }, - "debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", - "dev": true, - "requires": { - "ms": "2.1.2" - } - }, - "eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^2.0.0" - }, - "dependencies": { - "eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true - } - } - }, - "eslint-visitor-keys": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.1.0.tgz", - "integrity": "sha512-yWJFpu4DtjsWKkt5GeNBBuZMlNcYVs6vRCLoCVEJrTjaSB6LC98gFipNK/erM2Heg/E8mIK+hXG/pJMLK+eRZA==", - "dev": true - }, - "globby": { - "version": "11.0.4", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.4.tgz", - "integrity": "sha512-9O4MVG9ioZJ08ffbcyVYyLOJLk5JQ688pJ4eMGLpdWLHq/Wr1D9BlriLQyL0E+jbkuePVZXYFj47QM/v093wHg==", - "dev": true, - "requires": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.1.1", - "ignore": "^5.1.4", - "merge2": "^1.3.0", - "slash": "^3.0.0" - } - }, - "ignore": { - "version": "5.1.9", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.9.tgz", - "integrity": "sha512-2zeMQpbKz5dhZ9IwL0gbxSW5w0NK/MSAMtNuhgIHEPmaU3vPdKPL0UdvUCXs5SS4JAwsBxysK5sFMW8ocFiVjQ==", - "dev": true - }, - "is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "requires": { - "is-extglob": "^2.1.1" - } - } - } - }, - "eslint-plugin-prettier": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.4.0.tgz", - "integrity": "sha512-UDK6rJT6INSfcOo545jiaOwB701uAIt2/dR7WnFQoGCVl1/EMqdANBmwUaqqQ45aXprsTGzSa39LI1PyuRBxxw==", - "dev": true, - "requires": { - "prettier-linter-helpers": "^1.0.0" - } - }, - "eslint-rule-documentation": { - "version": "1.0.23", - "resolved": "https://registry.npmjs.org/eslint-rule-documentation/-/eslint-rule-documentation-1.0.23.tgz", - "integrity": "sha512-pWReu3fkohwyvztx/oQWWgld2iad25TfUdi6wvhhaDPIQjHU/pyvlKgXFw1kX31SQK2Nq9MH+vRDWB0ZLy8fYw==", - "dev": true - }, - "eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", - "dev": true, - "requires": { - "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - } - }, - "eslint-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", - "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^1.1.0" - }, - "dependencies": { - "eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", - "dev": true - } - } - }, - "eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true - }, - "espree": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", - "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", - "dev": true, - "requires": { - "acorn": "^7.4.0", - "acorn-jsx": "^5.3.1", - "eslint-visitor-keys": "^1.3.0" - }, - "dependencies": { - "eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", - "dev": true - } - } - }, - "esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true - }, - "esquery": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", - "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", - "dev": true, - "requires": { - "estraverse": "^5.1.0" - }, - "dependencies": { - "estraverse": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", - "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", - "dev": true - } - } - }, - "esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "requires": { - "estraverse": "^5.2.0" - }, - "dependencies": { - "estraverse": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", - "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", - "dev": true - } - } - }, - "estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true - }, - "esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true - }, - "etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", - "dev": true - }, - "execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "requires": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - } - }, - "exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", - "dev": true - }, - "expect": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/expect/-/expect-27.5.1.tgz", - "integrity": "sha512-E1q5hSUG2AmYQwQJ041nvgpkODHQvB+RKlB4IYdru6uJsyFTRyZAP463M+1lINorwbqAmUggi6+WwkD8lCS/Dw==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "jest-get-type": "^27.5.1", - "jest-matcher-utils": "^27.5.1", - "jest-message-util": "^27.5.1" - } - }, - "express": { - "version": "4.17.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", - "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", - "dev": true, - "requires": { - "accepts": "~1.3.7", - "array-flatten": "1.1.1", - "body-parser": "1.19.0", - "content-disposition": "0.5.3", - "content-type": "~1.0.4", - "cookie": "0.4.0", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "~1.1.2", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "~1.1.2", - "fresh": "0.5.2", - "merge-descriptors": "1.0.1", - "methods": "~1.1.2", - "on-finished": "~2.3.0", - "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.5", - "qs": "6.7.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.1.2", - "send": "0.17.1", - "serve-static": "1.14.1", - "setprototypeof": "1.1.1", - "statuses": "~1.5.0", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "express-urlrewrite": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/express-urlrewrite/-/express-urlrewrite-1.4.0.tgz", - "integrity": "sha512-PI5h8JuzoweS26vFizwQl6UTF25CAHSggNv0J25Dn/IKZscJHWZzPrI5z2Y2jgOzIaw2qh8l6+/jUcig23Z2SA==", - "dev": true, - "requires": { - "debug": "*", - "path-to-regexp": "^1.0.3" - }, - "dependencies": { - "path-to-regexp": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.8.0.tgz", - "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==", - "dev": true, - "requires": { - "isarray": "0.0.1" - } - } - } - }, - "fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true - }, - "fast-diff": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", - "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", - "dev": true - }, - "fast-glob": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.5.tgz", - "integrity": "sha512-2DtFcgT68wiTTiwZ2hNdJfcHNke9XOfnwmBRWXhmeKM8rF0TGwmC/Qto3S7RoZKp5cilZbxzO5iTNTQsJ+EeDg==", - "dev": true, - "requires": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.0", - "merge2": "^1.3.0", - "micromatch": "^4.0.2", - "picomatch": "^2.2.1" - } - }, - "fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true - }, - "fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", - "dev": true - }, - "fastq": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.11.0.tgz", - "integrity": "sha512-7Eczs8gIPDrVzT+EksYBcupqMyxSHXXrHOLRRxU2/DicV8789MRBRR8+Hc2uWzUupOs4YS4JzBmBxjjCVBxD/g==", - "dev": true, - "requires": { - "reusify": "^1.0.4" - } - }, - "fb-watchman": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.1.tgz", - "integrity": "sha512-DkPJKQeY6kKwmuMretBhr7G6Vodr7bFwDYTXIkfG1gjvNpaxBTQV3PbXg6bR1c1UP4jPOX0jHUbbHANL9vRjVg==", - "dev": true, - "requires": { - "bser": "2.1.1" - } - }, - "file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", - "dev": true, - "requires": { - "flat-cache": "^3.0.4" - } - }, - "fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "dev": true, - "requires": { - "to-regex-range": "^5.0.1" - } - }, - "finalhandler": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", - "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", - "dev": true, - "requires": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "~2.3.0", - "parseurl": "~1.3.3", - "statuses": "~1.5.0", - "unpipe": "~1.0.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "^2.0.0" - } - }, - "flat-cache": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", - "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", - "dev": true, - "requires": { - "flatted": "^3.1.0", - "rimraf": "^3.0.2" - } - }, - "flatted": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.1.1.tgz", - "integrity": "sha512-zAoAQiudy+r5SvnSw3KJy5os/oRJYHzrzja/tBDqrZtNhUw8bt6y8OBzMWcjWr+8liV8Eb6yOhw8WZ7VFZ5ZzA==", - "dev": true - }, - "follow-redirects": { - "version": "1.14.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", - "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==" - }, - "form-data": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", - "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", - "dev": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - }, - "forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "dev": true - }, - "fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", - "dev": true - }, - "fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true - }, - "fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "optional": true - }, - "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true - }, - "functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "dev": true - }, - "gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true - }, - "get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true - }, - "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - } - }, - "get-own-enumerable-property-symbols": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", - "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==", - "dev": true - }, - "get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true - }, - "get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true - }, - "glob": { - "version": "7.1.7", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", - "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "requires": { - "is-glob": "^4.0.1" - } - }, - "global-dirs": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-3.0.0.tgz", - "integrity": "sha512-v8ho2DS5RiCjftj1nD9NmnfaOzTdud7RRnVd9kFNOjqZbISlx5DQ+OrTkywgd0dIt7oFCvKetZSHoHcP3sDdiA==", - "dev": true, - "requires": { - "ini": "2.0.0" - } - }, - "globals": { - "version": "13.10.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.10.0.tgz", - "integrity": "sha512-piHC3blgLGFjvOuMmWZX60f+na1lXFDhQXBf1UYp2fXPXqvEUbOhNwi6BsQ0bQishwedgnjkwv1d9zKf+MWw3g==", - "dev": true, - "requires": { - "type-fest": "^0.20.2" - } - }, - "globby": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.3.tgz", - "integrity": "sha512-ffdmosjA807y7+lA1NM0jELARVmYul/715xiILEjo3hBLPTcirgQNnXECn5g3mtR8TOLCVbkfua1Hpen25/Xcg==", - "dev": true, - "requires": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.1.1", - "ignore": "^5.1.4", - "merge2": "^1.3.0", - "slash": "^3.0.0" - }, - "dependencies": { - "ignore": { - "version": "5.1.8", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", - "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", - "dev": true - } - } - }, - "got": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/got/-/got-9.6.0.tgz", - "integrity": "sha512-R7eWptXuGYxwijs0eV+v3o6+XH1IqVK8dJOEecQfTmkncw9AV4dcw/Dhxi8MdlqPthxxpZyizMzyg8RTmEsG+Q==", - "dev": true, - "requires": { - "@sindresorhus/is": "^0.14.0", - "@szmarczak/http-timer": "^1.1.2", - "cacheable-request": "^6.0.0", - "decompress-response": "^3.3.0", - "duplexer3": "^0.1.4", - "get-stream": "^4.1.0", - "lowercase-keys": "^1.0.1", - "mimic-response": "^1.0.1", - "p-cancelable": "^1.0.0", - "to-readable-stream": "^1.0.0", - "url-parse-lax": "^3.0.0" - }, - "dependencies": { - "get-stream": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", - "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", - "dev": true, - "requires": { - "pump": "^3.0.0" - } - } - } - }, - "graceful-fs": { - "version": "4.2.9", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", - "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", - "dev": true - }, - "has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "dev": true, - "requires": { - "function-bind": "^1.1.1" - } - }, - "has-bigints": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz", - "integrity": "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==", - "dev": true - }, - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - }, - "has-yarn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/has-yarn/-/has-yarn-2.1.0.tgz", - "integrity": "sha512-UqBRqi4ju7T+TqGNdqAO0PaSVGsDGJUBQvk9eUWNGRY1CFGDzYhLWoM7JQEemnlvVcv/YEmc2wNW8BC24EnUsw==", - "dev": true - }, - "hosted-git-info": { - "version": "2.8.9", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", - "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", - "dev": true - }, - "html-encoding-sniffer": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz", - "integrity": "sha512-D5JbOMBIR/TVZkubHT+OyT2705QvogUW4IBn6nHd756OwieSF9aDYFj4dv6HHEVGYbHaLETa3WggZYWWMyy3ZQ==", - "dev": true, - "requires": { - "whatwg-encoding": "^1.0.5" - } - }, - "html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true - }, - "http-cache-semantics": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz", - "integrity": "sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==", - "dev": true - }, - "http-errors": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", - "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", - "dev": true, - "requires": { - "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" - }, - "dependencies": { - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true - } - } - }, - "http-proxy-agent": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", - "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", - "dev": true, - "requires": { - "@tootallnate/once": "1", - "agent-base": "6", - "debug": "4" - } - }, - "https-proxy-agent": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", - "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", - "dev": true, - "requires": { - "agent-base": "6", - "debug": "4" - } - }, - "human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true - }, - "husky": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/husky/-/husky-7.0.4.tgz", - "integrity": "sha512-vbaCKN2QLtP/vD4yvs6iz6hBEo6wkSzs8HpRah1Z6aGmF2KW5PdYuAd7uX5a+OyBZHBhd+TFLqgjUgytQr4RvQ==", - "dev": true - }, - "iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "dev": true, - "requires": { - "safer-buffer": ">= 2.1.2 < 3" - } - }, - "ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" - }, - "ignore": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", - "dev": true - }, - "import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", - "dev": true, - "requires": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - } - }, - "import-lazy": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", - "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=", - "dev": true - }, - "import-local": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", - "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", - "dev": true, - "requires": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - }, - "dependencies": { - "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "requires": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - } - }, - "locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "requires": { - "p-locate": "^4.1.0" - } - }, - "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "requires": { - "p-limit": "^2.2.0" - } - }, - "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true - }, - "path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true - }, - "pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "requires": { - "find-up": "^4.0.0" - } - } - } - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", - "dev": true - }, - "indent-string": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", - "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", - "dev": true - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "ini": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ini/-/ini-2.0.0.tgz", - "integrity": "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==", - "dev": true - }, - "ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "dev": true - }, - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true - }, - "is-bigint": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.2.tgz", - "integrity": "sha512-0JV5+SOCQkIdzjBK9buARcV804Ddu7A0Qet6sHi3FimE9ne6m4BGQZfRn+NZiXbBk4F4XmHfDZIipLj9pX8dSA==", - "dev": true - }, - "is-boolean-object": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.1.tgz", - "integrity": "sha512-bXdQWkECBUIAcCkeH1unwJLIpZYaa5VvuygSyS/c2lf719mTKZDU5UdDRlpd01UjADgmW8RfqaP+mRaVPdr/Ng==", - "dev": true, - "requires": { - "call-bind": "^1.0.2" - } - }, - "is-callable": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", - "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", - "dev": true - }, - "is-ci": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", - "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", - "dev": true, - "requires": { - "ci-info": "^2.0.0" - }, - "dependencies": { - "ci-info": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", - "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", - "dev": true - } - } - }, - "is-core-module": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.4.0.tgz", - "integrity": "sha512-6A2fkfq1rfeQZjxrZJGerpLCTHRNEBiSgnu0+obeJpEPZRUooHgsizvzv0ZjJwOz3iWIHdJtVWJ/tmPr3D21/A==", - "dev": true, - "requires": { - "has": "^1.0.3" - } - }, - "is-date-object": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.4.tgz", - "integrity": "sha512-/b4ZVsG7Z5XVtIxs/h9W8nvfLgSAyKYdtGWQLbqy6jA1icmgjf8WCoTKgeS4wy5tYaPePouzFMANbnj94c2Z+A==", - "dev": true - }, - "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true - }, - "is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", - "dev": true - }, - "is-glob": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", - "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", - "dev": true, - "requires": { - "is-extglob": "^2.1.1" - } - }, - "is-installed-globally": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/is-installed-globally/-/is-installed-globally-0.4.0.tgz", - "integrity": "sha512-iwGqO3J21aaSkC7jWnHP/difazwS7SFeIqxv6wEtLU8Y5KlzFTjyqcSIT0d8s4+dDhKytsk9PJZ2BkS5eZwQRQ==", - "dev": true, - "requires": { - "global-dirs": "^3.0.0", - "is-path-inside": "^3.0.2" - } - }, - "is-negative-zero": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", - "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", - "dev": true - }, - "is-npm": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-5.0.0.tgz", - "integrity": "sha512-WW/rQLOazUq+ST/bCAVBp/2oMERWLsR7OrKyt052dNDk4DHcDE0/7QSXITlmi+VBcV13DfIbysG3tZJm5RfdBA==", - "dev": true - }, - "is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true - }, - "is-number-object": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.5.tgz", - "integrity": "sha512-RU0lI/n95pMoUKu9v1BZP5MBcZuNSVJkMkAG2dJqC4z2GlkGUNeH68SuHuBKBD/XFe+LHZ+f9BKkLET60Niedw==", - "dev": true - }, - "is-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", - "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", - "dev": true - }, - "is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true - }, - "is-plain-object": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", - "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==" - }, - "is-potential-custom-element-name": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", - "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true - }, - "is-promise": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz", - "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==", - "dev": true - }, - "is-regex": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", - "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "has-symbols": "^1.0.2" - } - }, - "is-regexp": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", - "integrity": "sha1-/S2INUXEa6xaYz57mgnof6LLUGk=", - "dev": true - }, - "is-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", - "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", - "dev": true - }, - "is-string": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.6.tgz", - "integrity": "sha512-2gdzbKUuqtQ3lYNrUTQYoClPhm7oQu4UdpSZMp1/DGgkHBT8E2Z1l0yMdb6D4zNAxwDiMv8MdulKROJGNl0Q0w==", - "dev": true - }, - "is-symbol": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", - "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", - "dev": true, - "requires": { - "has-symbols": "^1.0.2" - } - }, - "is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", - "dev": true - }, - "is-unicode-supported": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", - "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", - "dev": true - }, - "is-yarn-global": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz", - "integrity": "sha512-VjSeb/lHmkoyd8ryPVIKvOCn4D1koMqY+vqyjjUfc3xyKtP4dYOxM44sZrnqQSzSds3xyOrUTLTC9LVCVgLngw==", - "dev": true - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true - }, - "istanbul-lib-coverage": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", - "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", - "dev": true - }, - "istanbul-lib-instrument": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.1.0.tgz", - "integrity": "sha512-czwUz525rkOFDJxfKK6mYfIs9zBKILyrZQxjz3ABhjQXhbhFsSbo1HW/BFcsDnfJYJWA6thRR5/TUY2qs5W99Q==", - "dev": true, - "requires": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, - "istanbul-lib-report": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", - "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", - "dev": true, - "requires": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^3.0.0", - "supports-color": "^7.1.0" - } - }, - "istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "dev": true, - "requires": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - } - }, - "istanbul-reports": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.4.tgz", - "integrity": "sha512-r1/DshN4KSE7xWEknZLLLLDn5CJybV3nw01VTkp6D5jzLuELlcbudfj/eSQFvrKsJuTVCGnePO7ho82Nw9zzfw==", - "dev": true, - "requires": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - } - }, - "jest": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz", - "integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==", - "dev": true, - "requires": { - "@jest/core": "^27.5.1", - "import-local": "^3.0.2", - "jest-cli": "^27.5.1" - } - }, - "jest-changed-files": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-27.5.1.tgz", - "integrity": "sha512-buBLMiByfWGCoMsLLzGUUSpAmIAGnbR2KJoMN10ziLhOLvP4e0SlypHnAel8iqQXTrcbmfEY9sSqae5sgUsTvw==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "execa": "^5.0.0", - "throat": "^6.0.1" - } - }, - "jest-circus": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-27.5.1.tgz", - "integrity": "sha512-D95R7x5UtlMA5iBYsOHFFbMD/GVA4R/Kdq15f7xYWUfWHBto9NYRsOvnSauTgdF+ogCpJ4tyKOXhUifxS65gdw==", - "dev": true, - "requires": { - "@jest/environment": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "dedent": "^0.7.0", - "expect": "^27.5.1", - "is-generator-fn": "^2.0.0", - "jest-each": "^27.5.1", - "jest-matcher-utils": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-runtime": "^27.5.1", - "jest-snapshot": "^27.5.1", - "jest-util": "^27.5.1", - "pretty-format": "^27.5.1", - "slash": "^3.0.0", - "stack-utils": "^2.0.3", - "throat": "^6.0.1" - } - }, - "jest-cli": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-27.5.1.tgz", - "integrity": "sha512-Hc6HOOwYq4/74/c62dEE3r5elx8wjYqxY0r0G/nFrLDPMFRu6RA/u8qINOIkvhxG7mMQ5EJsOGfRpI8L6eFUVw==", - "dev": true, - "requires": { - "@jest/core": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/types": "^27.5.1", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "import-local": "^3.0.2", - "jest-config": "^27.5.1", - "jest-util": "^27.5.1", - "jest-validate": "^27.5.1", - "prompts": "^2.0.1", - "yargs": "^16.2.0" - } - }, - "jest-config": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-27.5.1.tgz", - "integrity": "sha512-5sAsjm6tGdsVbW9ahcChPAFCk4IlkQUknH5AvKjuLTSlcO/wCZKyFdn7Rg0EkC+OGgWODEy2hDpWB1PgzH0JNA==", - "dev": true, - "requires": { - "@babel/core": "^7.8.0", - "@jest/test-sequencer": "^27.5.1", - "@jest/types": "^27.5.1", - "babel-jest": "^27.5.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.1", - "graceful-fs": "^4.2.9", - "jest-circus": "^27.5.1", - "jest-environment-jsdom": "^27.5.1", - "jest-environment-node": "^27.5.1", - "jest-get-type": "^27.5.1", - "jest-jasmine2": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-runner": "^27.5.1", - "jest-util": "^27.5.1", - "jest-validate": "^27.5.1", - "micromatch": "^4.0.4", - "parse-json": "^5.2.0", - "pretty-format": "^27.5.1", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - }, - "dependencies": { - "parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - } - } - } - }, - "jest-diff": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-27.5.1.tgz", - "integrity": "sha512-m0NvkX55LDt9T4mctTEgnZk3fmEg3NRYutvMPWM/0iPnkFj2wIeF45O1718cMSOFO1vINkqmxqD8vE37uTEbqw==", - "dev": true, - "requires": { - "chalk": "^4.0.0", - "diff-sequences": "^27.5.1", - "jest-get-type": "^27.5.1", - "pretty-format": "^27.5.1" - } - }, - "jest-docblock": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-27.5.1.tgz", - "integrity": "sha512-rl7hlABeTsRYxKiUfpHrQrG4e2obOiTQWfMEH3PxPjOtdsfLQO4ReWSZaQ7DETm4xu07rl4q/h4zcKXyU0/OzQ==", - "dev": true, - "requires": { - "detect-newline": "^3.0.0" - } - }, - "jest-each": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-27.5.1.tgz", - "integrity": "sha512-1Ff6p+FbhT/bXQnEouYy00bkNSY7OUpfIcmdl8vZ31A1UUaurOLPA8a8BbJOF2RDUElwJhmeaV7LnagI+5UwNQ==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "chalk": "^4.0.0", - "jest-get-type": "^27.5.1", - "jest-util": "^27.5.1", - "pretty-format": "^27.5.1" - } - }, - "jest-environment-jsdom": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-27.5.1.tgz", - "integrity": "sha512-TFBvkTC1Hnnnrka/fUb56atfDtJ9VMZ94JkjTbggl1PEpwrYtUBKMezB3inLmWqQsXYLcMwNoDQwoBTAvFfsfw==", - "dev": true, - "requires": { - "@jest/environment": "^27.5.1", - "@jest/fake-timers": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "jest-mock": "^27.5.1", - "jest-util": "^27.5.1", - "jsdom": "^16.6.0" - } - }, - "jest-environment-node": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-27.5.1.tgz", - "integrity": "sha512-Jt4ZUnxdOsTGwSRAfKEnE6BcwsSPNOijjwifq5sDFSA2kesnXTvNqKHYgM0hDq3549Uf/KzdXNYn4wMZJPlFLw==", - "dev": true, - "requires": { - "@jest/environment": "^27.5.1", - "@jest/fake-timers": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "jest-mock": "^27.5.1", - "jest-util": "^27.5.1" - } - }, - "jest-get-type": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-27.5.1.tgz", - "integrity": "sha512-2KY95ksYSaK7DMBWQn6dQz3kqAf3BB64y2udeG+hv4KfSOb9qwcYQstTJc1KCbsix+wLZWZYN8t7nwX3GOBLRw==", - "dev": true - }, - "jest-haste-map": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-27.5.1.tgz", - "integrity": "sha512-7GgkZ4Fw4NFbMSDSpZwXeBiIbx+t/46nJ2QitkOjvwPYyZmqttu2TDSimMHP1EkPOi4xUZAN1doE5Vd25H4Jng==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "@types/graceful-fs": "^4.1.2", - "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "fsevents": "^2.3.2", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^27.5.1", - "jest-serializer": "^27.5.1", - "jest-util": "^27.5.1", - "jest-worker": "^27.5.1", - "micromatch": "^4.0.4", - "walker": "^1.0.7" - } - }, - "jest-jasmine2": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-27.5.1.tgz", - "integrity": "sha512-jtq7VVyG8SqAorDpApwiJJImd0V2wv1xzdheGHRGyuT7gZm6gG47QEskOlzsN1PG/6WNaCo5pmwMHDf3AkG2pQ==", - "dev": true, - "requires": { - "@jest/environment": "^27.5.1", - "@jest/source-map": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "expect": "^27.5.1", - "is-generator-fn": "^2.0.0", - "jest-each": "^27.5.1", - "jest-matcher-utils": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-runtime": "^27.5.1", - "jest-snapshot": "^27.5.1", - "jest-util": "^27.5.1", - "pretty-format": "^27.5.1", - "throat": "^6.0.1" - } - }, - "jest-leak-detector": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-27.5.1.tgz", - "integrity": "sha512-POXfWAMvfU6WMUXftV4HolnJfnPOGEu10fscNCA76KBpRRhcMN2c8d3iT2pxQS3HLbA+5X4sOUPzYO2NUyIlHQ==", - "dev": true, - "requires": { - "jest-get-type": "^27.5.1", - "pretty-format": "^27.5.1" - } - }, - "jest-matcher-utils": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-27.5.1.tgz", - "integrity": "sha512-z2uTx/T6LBaCoNWNFWwChLBKYxTMcGBRjAt+2SbP929/Fflb9aa5LGma654Rz8z9HLxsrUaYzxE9T/EFIL/PAw==", - "dev": true, - "requires": { - "chalk": "^4.0.0", - "jest-diff": "^27.5.1", - "jest-get-type": "^27.5.1", - "pretty-format": "^27.5.1" - } - }, - "jest-message-util": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-27.5.1.tgz", - "integrity": "sha512-rMyFe1+jnyAAf+NHwTclDz0eAaLkVDdKVHHBFWsBWHnnh5YeJMNWWsv7AbFYXfK3oTqvL7VTWkhNLu1jX24D+g==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^27.5.1", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^27.5.1", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "dependencies": { - "@babel/code-frame": { - "version": "7.15.8", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.15.8.tgz", - "integrity": "sha512-2IAnmn8zbvC/jKYhq5Ki9I+DwjlrtMPUCH/CpHvqI4dNnlwHwsxoIhlc8WcYY5LSYknXQtAlFYuHfqAFCvQ4Wg==", - "dev": true, - "requires": { - "@babel/highlight": "^7.14.5" - } - }, - "@babel/helper-validator-identifier": { - "version": "7.15.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz", - "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==", - "dev": true - }, - "@babel/highlight": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", - "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.14.5", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" - }, - "dependencies": { - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - } - } - }, - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-mock": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-27.5.1.tgz", - "integrity": "sha512-K4jKbY1d4ENhbrG2zuPWaQBvDly+iZ2yAW+T1fATN78hc0sInwn7wZB8XtlNnvHug5RMwV897Xm4LqmPM4e2Og==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "@types/node": "*" - } - }, - "jest-pnp-resolver": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz", - "integrity": "sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w==", - "dev": true, - "requires": {} - }, - "jest-regex-util": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-27.5.1.tgz", - "integrity": "sha512-4bfKq2zie+x16okqDXjXn9ql2B0dScQu+vcwe4TvFVhkVyuWLqpZrZtXxLLWoXYgn0E87I6r6GRYHF7wFZBUvg==", - "dev": true - }, - "jest-resolve": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-27.5.1.tgz", - "integrity": "sha512-FFDy8/9E6CV83IMbDpcjOhumAQPDyETnU2KZ1O98DwTnz8AOBsW/Xv3GySr1mOZdItLR+zDZ7I/UdTFbgSOVCw==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^27.5.1", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^27.5.1", - "jest-validate": "^27.5.1", - "resolve": "^1.20.0", - "resolve.exports": "^1.1.0", - "slash": "^3.0.0" - } - }, - "jest-resolve-dependencies": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-27.5.1.tgz", - "integrity": "sha512-QQOOdY4PE39iawDn5rzbIePNigfe5B9Z91GDD1ae/xNDlu9kaat8QQ5EKnNmVWPV54hUdxCVwwj6YMgR2O7IOg==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-snapshot": "^27.5.1" - } - }, - "jest-runner": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-27.5.1.tgz", - "integrity": "sha512-g4NPsM4mFCOwFKXO4p/H/kWGdJp9V8kURY2lX8Me2drgXqG7rrZAx5kv+5H7wtt/cdFIjhqYx1HrlqWHaOvDaQ==", - "dev": true, - "requires": { - "@jest/console": "^27.5.1", - "@jest/environment": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "chalk": "^4.0.0", - "emittery": "^0.8.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^27.5.1", - "jest-environment-jsdom": "^27.5.1", - "jest-environment-node": "^27.5.1", - "jest-haste-map": "^27.5.1", - "jest-leak-detector": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-runtime": "^27.5.1", - "jest-util": "^27.5.1", - "jest-worker": "^27.5.1", - "source-map-support": "^0.5.6", - "throat": "^6.0.1" - } - }, - "jest-runtime": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-27.5.1.tgz", - "integrity": "sha512-o7gxw3Gf+H2IGt8fv0RiyE1+r83FJBRruoA+FXrlHw6xEyBsU8ugA6IPfTdVyA0w8HClpbK+DGJxH59UrNMx8A==", - "dev": true, - "requires": { - "@jest/environment": "^27.5.1", - "@jest/fake-timers": "^27.5.1", - "@jest/globals": "^27.5.1", - "@jest/source-map": "^27.5.1", - "@jest/test-result": "^27.5.1", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "execa": "^5.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-mock": "^27.5.1", - "jest-regex-util": "^27.5.1", - "jest-resolve": "^27.5.1", - "jest-snapshot": "^27.5.1", - "jest-util": "^27.5.1", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - } - }, - "jest-serializer": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-serializer/-/jest-serializer-27.5.1.tgz", - "integrity": "sha512-jZCyo6iIxO1aqUxpuBlwTDMkzOAJS4a3eYz3YzgxxVQFwLeSA7Jfq5cbqCY+JLvTDrWirgusI/0KwxKMgrdf7w==", - "dev": true, - "requires": { - "@types/node": "*", - "graceful-fs": "^4.2.9" - } - }, - "jest-snapshot": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-27.5.1.tgz", - "integrity": "sha512-yYykXI5a0I31xX67mgeLw1DZ0bJB+gpq5IpSuCAoyDi0+BhgU/RIrL+RTzDmkNTchvDFWKP8lp+w/42Z3us5sA==", - "dev": true, - "requires": { - "@babel/core": "^7.7.2", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/traverse": "^7.7.2", - "@babel/types": "^7.0.0", - "@jest/transform": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/babel__traverse": "^7.0.4", - "@types/prettier": "^2.1.5", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^27.5.1", - "graceful-fs": "^4.2.9", - "jest-diff": "^27.5.1", - "jest-get-type": "^27.5.1", - "jest-haste-map": "^27.5.1", - "jest-matcher-utils": "^27.5.1", - "jest-message-util": "^27.5.1", - "jest-util": "^27.5.1", - "natural-compare": "^1.4.0", - "pretty-format": "^27.5.1", - "semver": "^7.3.2" - } - }, - "jest-util": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-27.5.1.tgz", - "integrity": "sha512-Kv2o/8jNvX1MQ0KGtw480E/w4fBCDOnH6+6DmeKi6LZUIlKA5kwY0YNdlzaWTiVgxqAqik11QyxDOKk543aKXw==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - } - }, - "jest-validate": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-27.5.1.tgz", - "integrity": "sha512-thkNli0LYTmOI1tDB3FI1S1RTp/Bqyd9pTarJwL87OIBFuqEb5Apv5EaApEudYg4g86e3CT6kM0RowkhtEnCBQ==", - "dev": true, - "requires": { - "@jest/types": "^27.5.1", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^27.5.1", - "leven": "^3.1.0", - "pretty-format": "^27.5.1" - }, - "dependencies": { - "camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true - } - } - }, - "jest-watcher": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-27.5.1.tgz", - "integrity": "sha512-z676SuD6Z8o8qbmEGhoEUFOM1+jfEiL3DXHK/xgEiG2EyNYfFG60jluWcupY6dATjfEsKQuibReS1djInQnoVw==", - "dev": true, - "requires": { - "@jest/test-result": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "jest-util": "^27.5.1", - "string-length": "^4.0.1" - } - }, - "jest-worker": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", - "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", - "dev": true, - "requires": { - "@types/node": "*", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "dependencies": { - "supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - } - } - }, - "jju": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/jju/-/jju-1.4.0.tgz", - "integrity": "sha1-o6vicYryQaKykE+EpiWXDzia4yo=", - "dev": true - }, - "js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true - }, - "js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, - "requires": { - "argparse": "^2.0.1" - } - }, - "jsdom": { - "version": "16.7.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-16.7.0.tgz", - "integrity": "sha512-u9Smc2G1USStM+s/x1ru5Sxrl6mPYCbByG1U/hUmqaVsm4tbNyS7CicOSRyuGQYZhTu0h84qkZZQ/I+dzizSVw==", - "dev": true, - "requires": { - "abab": "^2.0.5", - "acorn": "^8.2.4", - "acorn-globals": "^6.0.0", - "cssom": "^0.4.4", - "cssstyle": "^2.3.0", - "data-urls": "^2.0.0", - "decimal.js": "^10.2.1", - "domexception": "^2.0.1", - "escodegen": "^2.0.0", - "form-data": "^3.0.0", - "html-encoding-sniffer": "^2.0.1", - "http-proxy-agent": "^4.0.1", - "https-proxy-agent": "^5.0.0", - "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.0", - "parse5": "6.0.1", - "saxes": "^5.0.1", - "symbol-tree": "^3.2.4", - "tough-cookie": "^4.0.0", - "w3c-hr-time": "^1.0.2", - "w3c-xmlserializer": "^2.0.0", - "webidl-conversions": "^6.1.0", - "whatwg-encoding": "^1.0.5", - "whatwg-mimetype": "^2.3.0", - "whatwg-url": "^8.5.0", - "ws": "^7.4.6", - "xml-name-validator": "^3.0.0" - }, - "dependencies": { - "acorn": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz", - "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", - "dev": true - } - } - }, - "jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true - }, - "json-buffer": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.0.tgz", - "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=", - "dev": true - }, - "json-parse-better-errors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", - "dev": true - }, - "json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true - }, - "json-parse-helpfulerror": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/json-parse-helpfulerror/-/json-parse-helpfulerror-1.0.3.tgz", - "integrity": "sha1-E/FM4C7tTpgSl7ZOueO5MuLdE9w=", - "dev": true, - "requires": { - "jju": "^1.1.0" - } - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true - }, - "json-server": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/json-server/-/json-server-0.17.0.tgz", - "integrity": "sha512-+e/nW0mf666j1yTK+5dRx7hgxq5wJTkc5QhTYa/cBfD6vLlQWHfB4l8XKPgzeO55A8Hqm38g44OtZ5SooXi6MQ==", - "dev": true, - "requires": { - "body-parser": "^1.19.0", - "chalk": "^4.1.2", - "compression": "^1.7.4", - "connect-pause": "^0.1.1", - "cors": "^2.8.5", - "errorhandler": "^1.5.1", - "express": "^4.17.1", - "express-urlrewrite": "^1.4.0", - "json-parse-helpfulerror": "^1.0.3", - "lodash": "^4.17.21", - "lodash-id": "^0.14.1", - "lowdb": "^1.0.0", - "method-override": "^3.0.0", - "morgan": "^1.10.0", - "nanoid": "^3.1.23", - "please-upgrade-node": "^3.2.0", - "pluralize": "^8.0.0", - "server-destroy": "^1.0.1", - "update-notifier": "^5.1.0", - "yargs": "^17.0.1" - }, - "dependencies": { - "chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - } - }, - "yargs": { - "version": "17.2.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.2.1.tgz", - "integrity": "sha512-XfR8du6ua4K6uLGm5S6fA+FIJom/MdJcFNVY8geLlp2v8GYbOXD4EB1tPNZsRn4vBzKGMgb5DRZMeWuFc2GO8Q==", - "dev": true, - "requires": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - } - } - } - }, - "json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", - "dev": true - }, - "json5": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz", - "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", - "dev": true, - "requires": { - "minimist": "^1.2.5" - } - }, - "keyv": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", - "integrity": "sha512-9ykJ/46SN/9KPM/sichzQ7OvXyGDYKGTaDlKMGCAlg2UK8KRy4jb0d8sFc+0Tt0YYnThq8X2RZgCg74RPxgcVA==", - "dev": true, - "requires": { - "json-buffer": "3.0.0" - } - }, - "kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", - "dev": true - }, - "latest-version": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-5.1.0.tgz", - "integrity": "sha512-weT+r0kTkRQdCdYCNtkMwWXQTMEswKrFBkm4ckQOMVhhqhIMI1UT2hMj+1iigIhgSZm5gTmrRXBNoGUgaTY1xA==", - "dev": true, - "requires": { - "package-json": "^6.3.0" - } - }, - "leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", - "dev": true - }, - "levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "requires": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - } - }, - "lines-and-columns": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", - "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=", - "dev": true - }, - "lint-staged": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-11.1.1.tgz", - "integrity": "sha512-eTNGe6i78PSUUH2BZi1gZmGmNfb8IeN4z2OzMYxSZ1qnP1WXKn1E7D+OHwLbRDm/wQINnzIj0bsKJ6lLVSuZiQ==", - "dev": true, - "requires": { - "chalk": "^4.1.1", - "cli-truncate": "^2.1.0", - "commander": "^7.2.0", - "cosmiconfig": "^7.0.0", - "debug": "^4.3.1", - "dedent": "^0.7.0", - "enquirer": "^2.3.6", - "execa": "^5.0.0", - "listr2": "^3.8.2", - "log-symbols": "^4.1.0", - "micromatch": "^4.0.4", - "normalize-path": "^3.0.0", - "please-upgrade-node": "^3.2.0", - "string-argv": "0.3.1", - "stringify-object": "^3.3.0" - }, - "dependencies": { - "commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", - "dev": true - } - } - }, - "listr2": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/listr2/-/listr2-3.10.0.tgz", - "integrity": "sha512-eP40ZHihu70sSmqFNbNy2NL1YwImmlMmPh9WO5sLmPDleurMHt3n+SwEWNu2kzKScexZnkyFtc1VI0z/TGlmpw==", - "dev": true, - "requires": { - "cli-truncate": "^2.1.0", - "colorette": "^1.2.2", - "log-update": "^4.0.0", - "p-map": "^4.0.0", - "rxjs": "^6.6.7", - "through": "^2.3.8", - "wrap-ansi": "^7.0.0" - } - }, - "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" - }, - "dependencies": { - "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true - } - } - }, - "locate-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", - "dev": true, - "requires": { - "p-locate": "^2.0.0", - "path-exists": "^3.0.0" - } - }, - "lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true - }, - "lodash-id": { - "version": "0.14.1", - "resolved": "https://registry.npmjs.org/lodash-id/-/lodash-id-0.14.1.tgz", - "integrity": "sha512-ikQPBTiq/d5m6dfKQlFdIXFzvThPi2Be9/AHxktOnDSfSxE1j9ICbBT5Elk1ke7HSTgM38LHTpmJovo9/klnLg==", - "dev": true - }, - "lodash.clonedeep": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", - "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", - "dev": true - }, - "lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=", - "dev": true - }, - "lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true - }, - "lodash.truncate": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", - "dev": true - }, - "log-symbols": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", - "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", - "dev": true, - "requires": { - "chalk": "^4.1.0", - "is-unicode-supported": "^0.1.0" - } - }, - "log-update": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/log-update/-/log-update-4.0.0.tgz", - "integrity": "sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg==", - "dev": true, - "requires": { - "ansi-escapes": "^4.3.0", - "cli-cursor": "^3.1.0", - "slice-ansi": "^4.0.0", - "wrap-ansi": "^6.2.0" - }, - "dependencies": { - "wrap-ansi": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", - "dev": true, - "requires": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - } - } - } - }, - "lowdb": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/lowdb/-/lowdb-1.0.0.tgz", - "integrity": "sha512-2+x8esE/Wb9SQ1F9IHaYWfsC9FIecLOPrK4g17FGEayjUWH172H6nwicRovGvSE2CPZouc2MCIqCI7h9d+GftQ==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.3", - "is-promise": "^2.1.0", - "lodash": "4", - "pify": "^3.0.0", - "steno": "^0.4.1" - } - }, - "lowercase-keys": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", - "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==", - "dev": true - }, - "lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "requires": { - "yallist": "^4.0.0" - } - }, - "make-dir": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", - "dev": true, - "requires": { - "semver": "^6.0.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, - "make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true - }, - "makeerror": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.11.tgz", - "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", - "dev": true, - "requires": { - "tmpl": "1.0.x" - } - }, - "media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", - "dev": true - }, - "merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", - "dev": true - }, - "merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true - }, - "merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true - }, - "method-override": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/method-override/-/method-override-3.0.0.tgz", - "integrity": "sha512-IJ2NNN/mSl9w3kzWB92rcdHpz+HjkxhDJWNDBqSlas+zQdP8wBiJzITPg08M/k2uVvMow7Sk41atndNtt/PHSA==", - "dev": true, - "requires": { - "debug": "3.1.0", - "methods": "~1.1.2", - "parseurl": "~1.3.2", - "vary": "~1.1.2" - }, - "dependencies": { - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", - "dev": true - }, - "micromatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.4.tgz", - "integrity": "sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==", - "dev": true, - "requires": { - "braces": "^3.0.1", - "picomatch": "^2.2.3" - } - }, - "mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "dev": true - }, - "mime-db": { - "version": "1.48.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.48.0.tgz", - "integrity": "sha512-FM3QwxV+TnZYQ2aRqhlKBMHxk10lTbMt3bBkMAp54ddrNeVSfcQYOOKuGuy3Ddrm38I04If834fOUSq1yzslJQ==", - "dev": true - }, - "mime-types": { - "version": "2.1.31", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.31.tgz", - "integrity": "sha512-XGZnNzm3QvgKxa8dpzyhFTHmpP3l5YNusmne07VUOXxou9CqUqYa/HBy124RqtVh/O2pECas/MOcsDgpilPOPg==", - "dev": true, - "requires": { - "mime-db": "1.48.0" - } - }, - "mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true - }, - "mimic-response": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", - "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", - "dev": true - }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", - "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", - "dev": true - }, - "mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" - }, - "morgan": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz", - "integrity": "sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==", - "dev": true, - "requires": { - "basic-auth": "~2.0.1", - "debug": "2.6.9", - "depd": "~2.0.0", - "on-finished": "~2.3.0", - "on-headers": "~1.0.2" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "dev": true - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "nan": { - "version": "2.15.0", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.15.0.tgz", - "integrity": "sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ==", - "optional": true - }, - "nanoid": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.2.0.tgz", - "integrity": "sha512-fmsZYa9lpn69Ad5eDn7FMcnnSR+8R34W9qJEijxYhTbfOWzr22n1QxCMzXLK+ODyW2973V3Fux959iQoUxzUIA==", - "dev": true - }, - "natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", - "dev": true - }, - "negotiator": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", - "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==", - "dev": true - }, - "node-fetch": { - "version": "2.6.7", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", - "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", - "requires": { - "whatwg-url": "^5.0.0" - }, - "dependencies": { - "tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=" - }, - "webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=" - }, - "whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=", - "requires": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - } - } - }, - "node-forge": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.0.tgz", - "integrity": "sha512-08ARB91bUi6zNKzVmaj3QO7cr397uiDT2nJ63cHjyNtCTWIgvS47j3eT0WfzUwS9+6Z5YshRaoasFkXCKrIYbA==", - "dev": true - }, - "node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=", - "dev": true - }, - "node-releases": { - "version": "1.1.72", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.72.tgz", - "integrity": "sha512-LLUo+PpH3dU6XizX3iVoubUNheF/owjXCZZ5yACDxNnPtgFuludV1ZL3ayK1kVep42Rmm0+R9/Y60NQbZ2bifw==", - "dev": true - }, - "normalize-package-data": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", - "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", - "dev": true, - "requires": { - "hosted-git-info": "^2.1.4", - "resolve": "^1.10.0", - "semver": "2 || 3 || 4 || 5", - "validate-npm-package-license": "^3.0.1" - }, - "dependencies": { - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true - } - } - }, - "normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true - }, - "normalize-url": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-4.5.1.tgz", - "integrity": "sha512-9UZCFRHQdNrfTpGg8+1INIg93B6zE0aXMVFkw1WFwvO4SlZywU6aLg5Of0Ap/PgcbSw4LNxvMWXMeugwMCX0AA==", - "dev": true - }, - "npm": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/npm/-/npm-8.18.0.tgz", - "integrity": "sha512-G07/yKvNUwhwxYhk8BxcuDPB/4s+y755i6CnH3lf9LQBHP5siUx66WbuNGWEnN3xaBER4+IR3OWApKX7eBO5Dw==", - "requires": { - "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/arborist": "^5.0.4", - "@npmcli/ci-detect": "^2.0.0", - "@npmcli/config": "^4.2.1", - "@npmcli/fs": "^2.1.0", - "@npmcli/map-workspaces": "^2.0.3", - "@npmcli/package-json": "^2.0.0", - "@npmcli/run-script": "^4.2.1", - "abbrev": "~1.1.1", - "archy": "~1.0.0", - "cacache": "^16.1.1", - "chalk": "^4.1.2", - "chownr": "^2.0.0", - "cli-columns": "^4.0.0", - "cli-table3": "^0.6.2", - "columnify": "^1.6.0", - "fastest-levenshtein": "^1.0.12", - "glob": "^8.0.1", - "graceful-fs": "^4.2.10", - "hosted-git-info": "^5.0.0", - "ini": "^3.0.0", - "init-package-json": "^3.0.2", - "is-cidr": "^4.0.2", - "json-parse-even-better-errors": "^2.3.1", - "libnpmaccess": "^6.0.2", - "libnpmdiff": "^4.0.2", - "libnpmexec": "^4.0.2", - "libnpmfund": "^3.0.1", - "libnpmhook": "^8.0.2", - "libnpmorg": "^4.0.2", - "libnpmpack": "^4.0.2", - "libnpmpublish": "^6.0.2", - "libnpmsearch": "^5.0.2", - "libnpmteam": "^4.0.2", - "libnpmversion": "^3.0.1", - "make-fetch-happen": "^10.2.0", - "minipass": "^3.1.6", - "minipass-pipeline": "^1.2.4", - "mkdirp": "^1.0.4", - "mkdirp-infer-owner": "^2.0.0", - "ms": "^2.1.2", - "node-gyp": "^9.1.0", - "nopt": "^6.0.0", - "npm-audit-report": "^3.0.0", - "npm-install-checks": "^5.0.0", - "npm-package-arg": "^9.1.0", - "npm-pick-manifest": "^7.0.1", - "npm-profile": "^6.2.0", - "npm-registry-fetch": "^13.3.1", - "npm-user-validate": "^1.0.1", - "npmlog": "^6.0.2", - "opener": "^1.5.2", - "p-map": "^4.0.0", - "pacote": "^13.6.2", - "parse-conflict-json": "^2.0.2", - "proc-log": "^2.0.1", - "qrcode-terminal": "^0.12.0", - "read": "~1.0.7", - "read-package-json": "^5.0.1", - "read-package-json-fast": "^2.0.3", - "readdir-scoped-modules": "^1.1.0", - "rimraf": "^3.0.2", - "semver": "^7.3.7", - "ssri": "^9.0.1", - "tar": "^6.1.11", - "text-table": "~0.2.0", - "tiny-relative-date": "^1.3.0", - "treeverse": "^2.0.0", - "validate-npm-package-name": "^4.0.0", - "which": "^2.0.2", - "write-file-atomic": "^4.0.1" - }, - "dependencies": { - "@colors/colors": { - "version": "1.5.0", - "bundled": true, - "optional": true - }, - "@gar/promisify": { - "version": "1.1.3", - "bundled": true - }, - "@isaacs/string-locale-compare": { - "version": "1.1.0", - "bundled": true - }, - "@npmcli/arborist": { - "version": "5.6.0", - "bundled": true, - "requires": { - "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/installed-package-contents": "^1.0.7", - "@npmcli/map-workspaces": "^2.0.3", - "@npmcli/metavuln-calculator": "^3.0.1", - "@npmcli/move-file": "^2.0.0", - "@npmcli/name-from-folder": "^1.0.1", - "@npmcli/node-gyp": "^2.0.0", - "@npmcli/package-json": "^2.0.0", - "@npmcli/query": "^1.1.1", - "@npmcli/run-script": "^4.1.3", - "bin-links": "^3.0.0", - "cacache": "^16.0.6", - "common-ancestor-path": "^1.0.1", - "json-parse-even-better-errors": "^2.3.1", - "json-stringify-nice": "^1.1.4", - "minimatch": "^5.1.0", - "mkdirp": "^1.0.4", - "mkdirp-infer-owner": "^2.0.0", - "nopt": "^6.0.0", - "npm-install-checks": "^5.0.0", - "npm-package-arg": "^9.0.0", - "npm-pick-manifest": "^7.0.0", - "npm-registry-fetch": "^13.0.0", - "npmlog": "^6.0.2", - "pacote": "^13.6.1", - "parse-conflict-json": "^2.0.1", - "proc-log": "^2.0.0", - "promise-all-reject-late": "^1.0.0", - "promise-call-limit": "^1.0.1", - "read-package-json-fast": "^2.0.2", - "readdir-scoped-modules": "^1.1.0", - "rimraf": "^3.0.2", - "semver": "^7.3.7", - "ssri": "^9.0.0", - "treeverse": "^2.0.0", - "walk-up-path": "^1.0.0" - } - }, - "@npmcli/ci-detect": { - "version": "2.0.0", - "bundled": true - }, - "@npmcli/config": { - "version": "4.2.1", - "bundled": true, - "requires": { - "@npmcli/map-workspaces": "^2.0.2", - "ini": "^3.0.0", - "mkdirp-infer-owner": "^2.0.0", - "nopt": "^6.0.0", - "proc-log": "^2.0.0", - "read-package-json-fast": "^2.0.3", - "semver": "^7.3.5", - "walk-up-path": "^1.0.0" - } - }, - "@npmcli/disparity-colors": { - "version": "2.0.0", - "bundled": true, - "requires": { - "ansi-styles": "^4.3.0" - } - }, - "@npmcli/fs": { - "version": "2.1.2", - "bundled": true, - "requires": { - "@gar/promisify": "^1.1.3", - "semver": "^7.3.5" - } - }, - "@npmcli/git": { - "version": "3.0.2", - "bundled": true, - "requires": { - "@npmcli/promise-spawn": "^3.0.0", - "lru-cache": "^7.4.4", - "mkdirp": "^1.0.4", - "npm-pick-manifest": "^7.0.0", - "proc-log": "^2.0.0", - "promise-inflight": "^1.0.1", - "promise-retry": "^2.0.1", - "semver": "^7.3.5", - "which": "^2.0.2" - } - }, - "@npmcli/installed-package-contents": { - "version": "1.0.7", - "bundled": true, - "requires": { - "npm-bundled": "^1.1.1", - "npm-normalize-package-bin": "^1.0.1" - } - }, - "@npmcli/map-workspaces": { - "version": "2.0.4", - "bundled": true, - "requires": { - "@npmcli/name-from-folder": "^1.0.1", - "glob": "^8.0.1", - "minimatch": "^5.0.1", - "read-package-json-fast": "^2.0.3" - } - }, - "@npmcli/metavuln-calculator": { - "version": "3.1.1", - "bundled": true, - "requires": { - "cacache": "^16.0.0", - "json-parse-even-better-errors": "^2.3.1", - "pacote": "^13.0.3", - "semver": "^7.3.5" - } - }, - "@npmcli/move-file": { - "version": "2.0.1", - "bundled": true, - "requires": { - "mkdirp": "^1.0.4", - "rimraf": "^3.0.2" - } - }, - "@npmcli/name-from-folder": { - "version": "1.0.1", - "bundled": true - }, - "@npmcli/node-gyp": { - "version": "2.0.0", - "bundled": true - }, - "@npmcli/package-json": { - "version": "2.0.0", - "bundled": true, - "requires": { - "json-parse-even-better-errors": "^2.3.1" - } - }, - "@npmcli/promise-spawn": { - "version": "3.0.0", - "bundled": true, - "requires": { - "infer-owner": "^1.0.4" - } - }, - "@npmcli/query": { - "version": "1.1.1", - "bundled": true, - "requires": { - "npm-package-arg": "^9.1.0", - "postcss-selector-parser": "^6.0.10", - "semver": "^7.3.7" - } - }, - "@npmcli/run-script": { - "version": "4.2.1", - "bundled": true, - "requires": { - "@npmcli/node-gyp": "^2.0.0", - "@npmcli/promise-spawn": "^3.0.0", - "node-gyp": "^9.0.0", - "read-package-json-fast": "^2.0.3", - "which": "^2.0.2" - } - }, - "@tootallnate/once": { - "version": "2.0.0", - "bundled": true - }, - "abbrev": { - "version": "1.1.1", - "bundled": true - }, - "agent-base": { - "version": "6.0.2", - "bundled": true, - "requires": { - "debug": "4" - } - }, - "agentkeepalive": { - "version": "4.2.1", - "bundled": true, - "requires": { - "debug": "^4.1.0", - "depd": "^1.1.2", - "humanize-ms": "^1.2.1" - } - }, - "aggregate-error": { - "version": "3.1.0", - "bundled": true, - "requires": { - "clean-stack": "^2.0.0", - "indent-string": "^4.0.0" - } - }, - "ansi-regex": { - "version": "5.0.1", - "bundled": true - }, - "ansi-styles": { - "version": "4.3.0", - "bundled": true, - "requires": { - "color-convert": "^2.0.1" - } - }, - "aproba": { - "version": "2.0.0", - "bundled": true - }, - "archy": { - "version": "1.0.0", - "bundled": true - }, - "are-we-there-yet": { - "version": "3.0.1", - "bundled": true, - "requires": { - "delegates": "^1.0.0", - "readable-stream": "^3.6.0" - } - }, - "asap": { - "version": "2.0.6", - "bundled": true - }, - "balanced-match": { - "version": "1.0.2", - "bundled": true - }, - "bin-links": { - "version": "3.0.2", - "bundled": true, - "requires": { - "cmd-shim": "^5.0.0", - "mkdirp-infer-owner": "^2.0.0", - "npm-normalize-package-bin": "^1.0.0", - "read-cmd-shim": "^3.0.0", - "rimraf": "^3.0.0", - "write-file-atomic": "^4.0.0" - } - }, - "binary-extensions": { - "version": "2.2.0", - "bundled": true - }, - "brace-expansion": { - "version": "2.0.1", - "bundled": true, - "requires": { - "balanced-match": "^1.0.0" - } - }, - "builtins": { - "version": "5.0.1", - "bundled": true, - "requires": { - "semver": "^7.0.0" - } - }, - "cacache": { - "version": "16.1.2", - "bundled": true, - "requires": { - "@npmcli/fs": "^2.1.0", - "@npmcli/move-file": "^2.0.0", - "chownr": "^2.0.0", - "fs-minipass": "^2.1.0", - "glob": "^8.0.1", - "infer-owner": "^1.0.4", - "lru-cache": "^7.7.1", - "minipass": "^3.1.6", - "minipass-collect": "^1.0.2", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "mkdirp": "^1.0.4", - "p-map": "^4.0.0", - "promise-inflight": "^1.0.1", - "rimraf": "^3.0.2", - "ssri": "^9.0.0", - "tar": "^6.1.11", - "unique-filename": "^1.1.1" - } - }, - "chalk": { - "version": "4.1.2", - "bundled": true, - "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - } - }, - "chownr": { - "version": "2.0.0", - "bundled": true - }, - "cidr-regex": { - "version": "3.1.1", - "bundled": true, - "requires": { - "ip-regex": "^4.1.0" - } - }, - "clean-stack": { - "version": "2.2.0", - "bundled": true - }, - "cli-columns": { - "version": "4.0.0", - "bundled": true, - "requires": { - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1" - } - }, - "cli-table3": { - "version": "0.6.2", - "bundled": true, - "requires": { - "@colors/colors": "1.5.0", - "string-width": "^4.2.0" - } - }, - "clone": { - "version": "1.0.4", - "bundled": true - }, - "cmd-shim": { - "version": "5.0.0", - "bundled": true, - "requires": { - "mkdirp-infer-owner": "^2.0.0" - } - }, - "color-convert": { - "version": "2.0.1", - "bundled": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "bundled": true - }, - "color-support": { - "version": "1.1.3", - "bundled": true - }, - "columnify": { - "version": "1.6.0", - "bundled": true, - "requires": { - "strip-ansi": "^6.0.1", - "wcwidth": "^1.0.0" - } - }, - "common-ancestor-path": { - "version": "1.0.1", - "bundled": true - }, - "concat-map": { - "version": "0.0.1", - "bundled": true - }, - "console-control-strings": { - "version": "1.1.0", - "bundled": true - }, - "cssesc": { - "version": "3.0.0", - "bundled": true - }, - "debug": { - "version": "4.3.4", - "bundled": true, - "requires": { - "ms": "2.1.2" - }, - "dependencies": { - "ms": { - "version": "2.1.2", - "bundled": true - } - } - }, - "debuglog": { - "version": "1.0.1", - "bundled": true - }, - "defaults": { - "version": "1.0.3", - "bundled": true, - "requires": { - "clone": "^1.0.2" - } - }, - "delegates": { - "version": "1.0.0", - "bundled": true - }, - "depd": { - "version": "1.1.2", - "bundled": true - }, - "dezalgo": { - "version": "1.0.4", - "bundled": true, - "requires": { - "asap": "^2.0.0", - "wrappy": "1" - } - }, - "diff": { - "version": "5.0.0", - "bundled": true - }, - "emoji-regex": { - "version": "8.0.0", - "bundled": true - }, - "encoding": { - "version": "0.1.13", - "bundled": true, - "optional": true, - "requires": { - "iconv-lite": "^0.6.2" - } - }, - "env-paths": { - "version": "2.2.1", - "bundled": true - }, - "err-code": { - "version": "2.0.3", - "bundled": true - }, - "fastest-levenshtein": { - "version": "1.0.12", - "bundled": true - }, - "fs-minipass": { - "version": "2.1.0", - "bundled": true, - "requires": { - "minipass": "^3.0.0" - } - }, - "fs.realpath": { - "version": "1.0.0", - "bundled": true - }, - "function-bind": { - "version": "1.1.1", - "bundled": true - }, - "gauge": { - "version": "4.0.4", - "bundled": true, - "requires": { - "aproba": "^1.0.3 || ^2.0.0", - "color-support": "^1.1.3", - "console-control-strings": "^1.1.0", - "has-unicode": "^2.0.1", - "signal-exit": "^3.0.7", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1", - "wide-align": "^1.1.5" - } - }, - "glob": { - "version": "8.0.3", - "bundled": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" - } - }, - "graceful-fs": { - "version": "4.2.10", - "bundled": true - }, - "has": { - "version": "1.0.3", - "bundled": true, - "requires": { - "function-bind": "^1.1.1" - } - }, - "has-flag": { - "version": "4.0.0", - "bundled": true - }, - "has-unicode": { - "version": "2.0.1", - "bundled": true - }, - "hosted-git-info": { - "version": "5.0.0", - "bundled": true, - "requires": { - "lru-cache": "^7.5.1" - } - }, - "http-cache-semantics": { - "version": "4.1.0", - "bundled": true - }, - "http-proxy-agent": { - "version": "5.0.0", - "bundled": true, - "requires": { - "@tootallnate/once": "2", - "agent-base": "6", - "debug": "4" - } - }, - "https-proxy-agent": { - "version": "5.0.1", - "bundled": true, - "requires": { - "agent-base": "6", - "debug": "4" - } - }, - "humanize-ms": { - "version": "1.2.1", - "bundled": true, - "requires": { - "ms": "^2.0.0" - } - }, - "iconv-lite": { - "version": "0.6.3", - "bundled": true, - "optional": true, - "requires": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - } - }, - "ignore-walk": { - "version": "5.0.1", - "bundled": true, - "requires": { - "minimatch": "^5.0.1" - } - }, - "imurmurhash": { - "version": "0.1.4", - "bundled": true - }, - "indent-string": { - "version": "4.0.0", - "bundled": true - }, - "infer-owner": { - "version": "1.0.4", - "bundled": true - }, - "inflight": { - "version": "1.0.6", - "bundled": true, - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.4", - "bundled": true - }, - "ini": { - "version": "3.0.0", - "bundled": true - }, - "init-package-json": { - "version": "3.0.2", - "bundled": true, - "requires": { - "npm-package-arg": "^9.0.1", - "promzard": "^0.3.0", - "read": "^1.0.7", - "read-package-json": "^5.0.0", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4", - "validate-npm-package-name": "^4.0.0" - } - }, - "ip": { - "version": "2.0.0", - "bundled": true - }, - "ip-regex": { - "version": "4.3.0", - "bundled": true - }, - "is-cidr": { - "version": "4.0.2", - "bundled": true, - "requires": { - "cidr-regex": "^3.1.1" - } - }, - "is-core-module": { - "version": "2.10.0", - "bundled": true, - "requires": { - "has": "^1.0.3" - } - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "bundled": true - }, - "is-lambda": { - "version": "1.0.1", - "bundled": true - }, - "isexe": { - "version": "2.0.0", - "bundled": true - }, - "json-parse-even-better-errors": { - "version": "2.3.1", - "bundled": true - }, - "json-stringify-nice": { - "version": "1.1.4", - "bundled": true - }, - "jsonparse": { - "version": "1.3.1", - "bundled": true - }, - "just-diff": { - "version": "5.1.1", - "bundled": true - }, - "just-diff-apply": { - "version": "5.4.1", - "bundled": true - }, - "libnpmaccess": { - "version": "6.0.3", - "bundled": true, - "requires": { - "aproba": "^2.0.0", - "minipass": "^3.1.1", - "npm-package-arg": "^9.0.1", - "npm-registry-fetch": "^13.0.0" - } - }, - "libnpmdiff": { - "version": "4.0.4", - "bundled": true, - "requires": { - "@npmcli/disparity-colors": "^2.0.0", - "@npmcli/installed-package-contents": "^1.0.7", - "binary-extensions": "^2.2.0", - "diff": "^5.0.0", - "minimatch": "^5.0.1", - "npm-package-arg": "^9.0.1", - "pacote": "^13.6.1", - "tar": "^6.1.0" - } - }, - "libnpmexec": { - "version": "4.0.11", - "bundled": true, - "requires": { - "@npmcli/arborist": "^5.0.0", - "@npmcli/ci-detect": "^2.0.0", - "@npmcli/fs": "^2.1.1", - "@npmcli/run-script": "^4.2.0", - "chalk": "^4.1.0", - "mkdirp-infer-owner": "^2.0.0", - "npm-package-arg": "^9.0.1", - "npmlog": "^6.0.2", - "pacote": "^13.6.1", - "proc-log": "^2.0.0", - "read": "^1.0.7", - "read-package-json-fast": "^2.0.2", - "semver": "^7.3.7", - "walk-up-path": "^1.0.0" - } - }, - "libnpmfund": { - "version": "3.0.2", - "bundled": true, - "requires": { - "@npmcli/arborist": "^5.0.0" - } - }, - "libnpmhook": { - "version": "8.0.3", - "bundled": true, - "requires": { - "aproba": "^2.0.0", - "npm-registry-fetch": "^13.0.0" - } - }, - "libnpmorg": { - "version": "4.0.3", - "bundled": true, - "requires": { - "aproba": "^2.0.0", - "npm-registry-fetch": "^13.0.0" - } - }, - "libnpmpack": { - "version": "4.1.2", - "bundled": true, - "requires": { - "@npmcli/run-script": "^4.1.3", - "npm-package-arg": "^9.0.1", - "pacote": "^13.6.1" - } - }, - "libnpmpublish": { - "version": "6.0.4", - "bundled": true, - "requires": { - "normalize-package-data": "^4.0.0", - "npm-package-arg": "^9.0.1", - "npm-registry-fetch": "^13.0.0", - "semver": "^7.3.7", - "ssri": "^9.0.0" - } - }, - "libnpmsearch": { - "version": "5.0.3", - "bundled": true, - "requires": { - "npm-registry-fetch": "^13.0.0" - } - }, - "libnpmteam": { - "version": "4.0.3", - "bundled": true, - "requires": { - "aproba": "^2.0.0", - "npm-registry-fetch": "^13.0.0" - } - }, - "libnpmversion": { - "version": "3.0.6", - "bundled": true, - "requires": { - "@npmcli/git": "^3.0.0", - "@npmcli/run-script": "^4.1.3", - "json-parse-even-better-errors": "^2.3.1", - "proc-log": "^2.0.0", - "semver": "^7.3.7" - } - }, - "lru-cache": { - "version": "7.13.2", - "bundled": true - }, - "make-fetch-happen": { - "version": "10.2.1", - "bundled": true, - "requires": { - "agentkeepalive": "^4.2.1", - "cacache": "^16.1.0", - "http-cache-semantics": "^4.1.0", - "http-proxy-agent": "^5.0.0", - "https-proxy-agent": "^5.0.0", - "is-lambda": "^1.0.1", - "lru-cache": "^7.7.1", - "minipass": "^3.1.6", - "minipass-collect": "^1.0.2", - "minipass-fetch": "^2.0.3", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^0.6.3", - "promise-retry": "^2.0.1", - "socks-proxy-agent": "^7.0.0", - "ssri": "^9.0.0" - } - }, - "minimatch": { - "version": "5.1.0", - "bundled": true, - "requires": { - "brace-expansion": "^2.0.1" - } - }, - "minipass": { - "version": "3.3.4", - "bundled": true, - "requires": { - "yallist": "^4.0.0" - } - }, - "minipass-collect": { - "version": "1.0.2", - "bundled": true, - "requires": { - "minipass": "^3.0.0" - } - }, - "minipass-fetch": { - "version": "2.1.1", - "bundled": true, - "requires": { - "encoding": "^0.1.13", - "minipass": "^3.1.6", - "minipass-sized": "^1.0.3", - "minizlib": "^2.1.2" - } - }, - "minipass-flush": { - "version": "1.0.5", - "bundled": true, - "requires": { - "minipass": "^3.0.0" - } - }, - "minipass-json-stream": { - "version": "1.0.1", - "bundled": true, - "requires": { - "jsonparse": "^1.3.1", - "minipass": "^3.0.0" - } - }, - "minipass-pipeline": { - "version": "1.2.4", - "bundled": true, - "requires": { - "minipass": "^3.0.0" - } - }, - "minipass-sized": { - "version": "1.0.3", - "bundled": true, - "requires": { - "minipass": "^3.0.0" - } - }, - "minizlib": { - "version": "2.1.2", - "bundled": true, - "requires": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" - } - }, - "mkdirp": { - "version": "1.0.4", - "bundled": true - }, - "mkdirp-infer-owner": { - "version": "2.0.0", - "bundled": true, - "requires": { - "chownr": "^2.0.0", - "infer-owner": "^1.0.4", - "mkdirp": "^1.0.3" - } - }, - "ms": { - "version": "2.1.3", - "bundled": true - }, - "mute-stream": { - "version": "0.0.8", - "bundled": true - }, - "negotiator": { - "version": "0.6.3", - "bundled": true - }, - "node-gyp": { - "version": "9.1.0", - "bundled": true, - "requires": { - "env-paths": "^2.2.0", - "glob": "^7.1.4", - "graceful-fs": "^4.2.6", - "make-fetch-happen": "^10.0.3", - "nopt": "^5.0.0", - "npmlog": "^6.0.0", - "rimraf": "^3.0.2", - "semver": "^7.3.5", - "tar": "^6.1.2", - "which": "^2.0.2" - }, - "dependencies": { - "brace-expansion": { - "version": "1.1.11", - "bundled": true, - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "glob": { - "version": "7.2.3", - "bundled": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "minimatch": { - "version": "3.1.2", - "bundled": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "nopt": { - "version": "5.0.0", - "bundled": true, - "requires": { - "abbrev": "1" - } - } - } - }, - "nopt": { - "version": "6.0.0", - "bundled": true, - "requires": { - "abbrev": "^1.0.0" - } - }, - "normalize-package-data": { - "version": "4.0.1", - "bundled": true, - "requires": { - "hosted-git-info": "^5.0.0", - "is-core-module": "^2.8.1", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4" - } - }, - "npm-audit-report": { - "version": "3.0.0", - "bundled": true, - "requires": { - "chalk": "^4.0.0" - } - }, - "npm-bundled": { - "version": "1.1.2", - "bundled": true, - "requires": { - "npm-normalize-package-bin": "^1.0.1" - } - }, - "npm-install-checks": { - "version": "5.0.0", - "bundled": true, - "requires": { - "semver": "^7.1.1" - } - }, - "npm-normalize-package-bin": { - "version": "1.0.1", - "bundled": true - }, - "npm-package-arg": { - "version": "9.1.0", - "bundled": true, - "requires": { - "hosted-git-info": "^5.0.0", - "proc-log": "^2.0.1", - "semver": "^7.3.5", - "validate-npm-package-name": "^4.0.0" - } - }, - "npm-packlist": { - "version": "5.1.1", - "bundled": true, - "requires": { - "glob": "^8.0.1", - "ignore-walk": "^5.0.1", - "npm-bundled": "^1.1.2", - "npm-normalize-package-bin": "^1.0.1" - } - }, - "npm-pick-manifest": { - "version": "7.0.1", - "bundled": true, - "requires": { - "npm-install-checks": "^5.0.0", - "npm-normalize-package-bin": "^1.0.1", - "npm-package-arg": "^9.0.0", - "semver": "^7.3.5" - } }, - "npm-profile": { + "ansi-styles": { "version": "6.2.1", - "bundled": true, - "requires": { - "npm-registry-fetch": "^13.0.1", - "proc-log": "^2.0.0" - } - }, - "npm-registry-fetch": { - "version": "13.3.1", - "bundled": true, - "requires": { - "make-fetch-happen": "^10.0.6", - "minipass": "^3.1.6", - "minipass-fetch": "^2.0.3", - "minipass-json-stream": "^1.0.1", - "minizlib": "^2.1.2", - "npm-package-arg": "^9.0.1", - "proc-log": "^2.0.0" - } - }, - "npm-user-validate": { - "version": "1.0.1", - "bundled": true - }, - "npmlog": { - "version": "6.0.2", - "bundled": true, - "requires": { - "are-we-there-yet": "^3.0.0", - "console-control-strings": "^1.1.0", - "gauge": "^4.0.3", - "set-blocking": "^2.0.0" - } - }, - "once": { - "version": "1.4.0", - "bundled": true, - "requires": { - "wrappy": "1" - } - }, - "opener": { - "version": "1.5.2", - "bundled": true - }, - "p-map": { - "version": "4.0.0", - "bundled": true, - "requires": { - "aggregate-error": "^3.0.0" - } - }, - "pacote": { - "version": "13.6.2", - "bundled": true, - "requires": { - "@npmcli/git": "^3.0.0", - "@npmcli/installed-package-contents": "^1.0.7", - "@npmcli/promise-spawn": "^3.0.0", - "@npmcli/run-script": "^4.1.0", - "cacache": "^16.0.0", - "chownr": "^2.0.0", - "fs-minipass": "^2.1.0", - "infer-owner": "^1.0.4", - "minipass": "^3.1.6", - "mkdirp": "^1.0.4", - "npm-package-arg": "^9.0.0", - "npm-packlist": "^5.1.0", - "npm-pick-manifest": "^7.0.0", - "npm-registry-fetch": "^13.0.1", - "proc-log": "^2.0.0", - "promise-retry": "^2.0.1", - "read-package-json": "^5.0.0", - "read-package-json-fast": "^2.0.3", - "rimraf": "^3.0.2", - "ssri": "^9.0.0", - "tar": "^6.1.11" - } - }, - "parse-conflict-json": { - "version": "2.0.2", - "bundled": true, - "requires": { - "json-parse-even-better-errors": "^2.3.1", - "just-diff": "^5.0.1", - "just-diff-apply": "^5.2.0" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "bundled": true - }, - "postcss-selector-parser": { - "version": "6.0.10", - "bundled": true, - "requires": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - } - }, - "proc-log": { - "version": "2.0.1", - "bundled": true - }, - "promise-all-reject-late": { - "version": "1.0.1", - "bundled": true - }, - "promise-call-limit": { - "version": "1.0.1", - "bundled": true - }, - "promise-inflight": { - "version": "1.0.1", - "bundled": true - }, - "promise-retry": { - "version": "2.0.1", - "bundled": true, - "requires": { - "err-code": "^2.0.2", - "retry": "^0.12.0" - } - }, - "promzard": { - "version": "0.3.0", - "bundled": true, - "requires": { - "read": "1" - } - }, - "qrcode-terminal": { - "version": "0.12.0", - "bundled": true - }, - "read": { - "version": "1.0.7", - "bundled": true, - "requires": { - "mute-stream": "~0.0.4" - } - }, - "read-cmd-shim": { - "version": "3.0.0", - "bundled": true - }, - "read-package-json": { - "version": "5.0.1", - "bundled": true, - "requires": { - "glob": "^8.0.1", - "json-parse-even-better-errors": "^2.3.1", - "normalize-package-data": "^4.0.0", - "npm-normalize-package-bin": "^1.0.1" - } - }, - "read-package-json-fast": { - "version": "2.0.3", - "bundled": true, - "requires": { - "json-parse-even-better-errors": "^2.3.0", - "npm-normalize-package-bin": "^1.0.1" - } - }, - "readable-stream": { - "version": "3.6.0", - "bundled": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, - "readdir-scoped-modules": { - "version": "1.1.0", - "bundled": true, - "requires": { - "debuglog": "^1.0.1", - "dezalgo": "^1.0.0", - "graceful-fs": "^4.1.2", - "once": "^1.3.0" - } - }, - "retry": { - "version": "0.12.0", - "bundled": true - }, - "rimraf": { - "version": "3.0.2", - "bundled": true, - "requires": { - "glob": "^7.1.3" - }, - "dependencies": { - "brace-expansion": { - "version": "1.1.11", - "bundled": true, - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "glob": { - "version": "7.2.3", - "bundled": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "minimatch": { - "version": "3.1.2", - "bundled": true, - "requires": { - "brace-expansion": "^1.1.7" - } - } - } - }, - "safe-buffer": { - "version": "5.2.1", - "bundled": true - }, - "safer-buffer": { - "version": "2.1.2", - "bundled": true, - "optional": true - }, - "semver": { - "version": "7.3.7", - "bundled": true, - "requires": { - "lru-cache": "^6.0.0" - }, - "dependencies": { - "lru-cache": { - "version": "6.0.0", - "bundled": true, - "requires": { - "yallist": "^4.0.0" - } - } - } - }, - "set-blocking": { - "version": "2.0.0", - "bundled": true - }, - "signal-exit": { - "version": "3.0.7", - "bundled": true - }, - "smart-buffer": { - "version": "4.2.0", - "bundled": true - }, - "socks": { - "version": "2.7.0", - "bundled": true, - "requires": { - "ip": "^2.0.0", - "smart-buffer": "^4.2.0" - } - }, - "socks-proxy-agent": { - "version": "7.0.0", - "bundled": true, - "requires": { - "agent-base": "^6.0.2", - "debug": "^4.3.3", - "socks": "^2.6.2" - } - }, - "spdx-correct": { - "version": "3.1.1", - "bundled": true, - "requires": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" - } - }, - "spdx-exceptions": { - "version": "2.3.0", - "bundled": true - }, - "spdx-expression-parse": { - "version": "3.0.1", - "bundled": true, - "requires": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" - } - }, - "spdx-license-ids": { - "version": "3.0.11", - "bundled": true - }, - "ssri": { - "version": "9.0.1", - "bundled": true, - "requires": { - "minipass": "^3.1.1" - } - }, - "string_decoder": { - "version": "1.3.0", - "bundled": true, - "requires": { - "safe-buffer": "~5.2.0" - } - }, - "string-width": { - "version": "4.2.3", - "bundled": true, - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - } - }, - "strip-ansi": { - "version": "6.0.1", - "bundled": true, - "requires": { - "ansi-regex": "^5.0.1" - } - }, - "supports-color": { - "version": "7.2.0", - "bundled": true, - "requires": { - "has-flag": "^4.0.0" - } - }, - "tar": { - "version": "6.1.11", - "bundled": true, - "requires": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^3.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" - } - }, - "text-table": { - "version": "0.2.0", - "bundled": true - }, - "tiny-relative-date": { - "version": "1.3.0", - "bundled": true - }, - "treeverse": { - "version": "2.0.0", - "bundled": true + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true }, - "unique-filename": { - "version": "1.1.1", - "bundled": true, - "requires": { - "unique-slug": "^2.0.0" - } + "emoji-regex": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.3.0.tgz", + "integrity": "sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==", + "dev": true }, - "unique-slug": { - "version": "2.0.2", - "bundled": true, + "is-fullwidth-code-point": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.0.0.tgz", + "integrity": "sha512-OVa3u9kkBbw7b8Xw5F9P+D/T9X+Z4+JruYVNapTjPYZYUznQ5YfWeFkOj606XYYW8yugTfC8Pj0hYqvi4ryAhA==", + "dev": true, "requires": { - "imurmurhash": "^0.1.4" + "get-east-asian-width": "^1.0.0" } }, - "util-deprecate": { - "version": "1.0.2", - "bundled": true - }, - "validate-npm-package-license": { - "version": "3.0.4", - "bundled": true, + "slice-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.0.tgz", + "integrity": "sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg==", + "dev": true, "requires": { - "spdx-correct": "^3.0.0", - "spdx-expression-parse": "^3.0.0" + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" } }, - "validate-npm-package-name": { - "version": "4.0.0", - "bundled": true, + "string-width": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.1.0.tgz", + "integrity": "sha512-SEIJCWiX7Kg4c129n48aDRwLbFb2LJmXXFrWBG4NGaRtMQ3myKPKbwrD1BKqQn74oCoNMBVrfDEr5M9YxCsrkw==", + "dev": true, "requires": { - "builtins": "^5.0.0" + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" } }, - "walk-up-path": { - "version": "1.0.0", - "bundled": true - }, - "wcwidth": { - "version": "1.0.1", - "bundled": true, + "strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, "requires": { - "defaults": "^1.0.3" + "ansi-regex": "^6.0.1" } }, - "which": { - "version": "2.0.2", - "bundled": true, + "type-fest": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-3.13.1.tgz", + "integrity": "sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g==", + "dev": true + }, + "wrap-ansi": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.0.tgz", + "integrity": "sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==", + "dev": true, "requires": { - "isexe": "^2.0.0" + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" } - }, - "wide-align": { - "version": "1.1.5", - "bundled": true, + } + } + }, + "lowdb": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lowdb/-/lowdb-1.0.0.tgz", + "integrity": "sha512-2+x8esE/Wb9SQ1F9IHaYWfsC9FIecLOPrK4g17FGEayjUWH172H6nwicRovGvSE2CPZouc2MCIqCI7h9d+GftQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.3", + "is-promise": "^2.1.0", + "lodash": "4", + "pify": "^3.0.0", + "steno": "^0.4.1" + } + }, + "lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "requires": { + "yallist": "^4.0.0" + } + }, + "make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "requires": { + "semver": "^7.5.3" + } + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dev": true, + "requires": { + "tmpl": "1.0.5" + } + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "dev": true + }, + "merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", + "dev": true + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true + }, + "method-override": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/method-override/-/method-override-3.0.0.tgz", + "integrity": "sha512-IJ2NNN/mSl9w3kzWB92rcdHpz+HjkxhDJWNDBqSlas+zQdP8wBiJzITPg08M/k2uVvMow7Sk41atndNtt/PHSA==", + "dev": true, + "requires": { + "debug": "3.1.0", + "methods": "~1.1.2", + "parseurl": "~1.3.2", + "vary": "~1.1.2" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, "requires": { - "string-width": "^1.0.2 || 2 || 3 || 4" + "ms": "2.0.0" } }, - "wrappy": { - "version": "1.0.2", - "bundled": true - }, - "write-file-atomic": { - "version": "4.0.2", - "bundled": true, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "dev": true + }, + "micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "requires": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + } + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true + }, + "mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true + }, + "mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "requires": { + "mime-db": "1.52.0" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", + "dev": true + }, + "mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" + }, + "morgan": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz", + "integrity": "sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==", + "dev": true, + "requires": { + "basic-auth": "~2.0.1", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-finished": "~2.3.0", + "on-headers": "~1.0.2" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, "requires": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" + "ms": "2.0.0" } }, - "yallist": { - "version": "4.0.0", - "bundled": true + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true } } }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "nan": { + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.18.0.tgz", + "integrity": "sha512-W7tfG7vMOGtD30sHoZSSc/JVYiyDPEyQVso/Zz+/uQd0B0L46gtC+pHha5FFMRpil6fm/AoEcRWyOVi4+E/f8w==", + "optional": true + }, + "nanoid": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.2.0.tgz", + "integrity": "sha512-fmsZYa9lpn69Ad5eDn7FMcnnSR+8R34W9qJEijxYhTbfOWzr22n1QxCMzXLK+ODyW2973V3Fux959iQoUxzUIA==", + "dev": true + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, + "negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "dev": true + }, + "node-forge": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz", + "integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==" + }, + "node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=", + "dev": true + }, + "node-releases": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.6.tgz", + "integrity": "sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg==", + "dev": true + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, "npm-run-path": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", @@ -18429,12 +14486,6 @@ "path-key": "^3.0.0" } }, - "nwsapi": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.0.tgz", - "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", - "dev": true - }, "object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -18442,11 +14493,21 @@ "dev": true }, "object-inspect": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", - "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==", + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", + "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", "dev": true }, + "object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, "object-keys": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", @@ -18454,26 +14515,48 @@ "dev": true }, "object.assign": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", - "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", "dev": true, "requires": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "has-symbols": "^1.0.1", + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", "object-keys": "^1.1.1" } }, + "object.entries": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.6.tgz", + "integrity": "sha512-leTPzo4Zvg3pmbQ3rDK69Rl8GQvIqMWubrkxONG9/ojtFE2rD9fjMKfSI5BxW3osRH1m6VdzmqK8oAY9aT4x5w==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + } + }, + "object.fromentries": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.6.tgz", + "integrity": "sha512-VciD13dswC4j1Xt5394WR4MzmAQmlgN72phd/riNp9vtD7tp4QQWJ0R4wvclXcafgcYK8veHRed2W6XeGBvcfg==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + } + }, "object.values": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.4.tgz", - "integrity": "sha512-TnGo7j4XSnKQoK3MfvkzqKCi0nVe/D9I9IjwTNYdb/fxYHpjrluHVOgw0AF6jrRFGMPHdfuidR09tIDiIvnaSg==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.6.tgz", + "integrity": "sha512-FVVTkD1vENCsAcwNs9k6jea2uHC/X0+JcjG8YA60FN5CMaJmG95wT9jek/xX9nornqGRrBkKtzuAu2wuHpKqvw==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.2" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" } }, "on-finished": { @@ -18509,78 +14592,43 @@ } }, "optionator": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", - "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.3.tgz", + "integrity": "sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==", "dev": true, "requires": { + "@aashutoshrathi/word-wrap": "^1.2.3", "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.3" + "type-check": "^0.4.0" } }, - "p-cancelable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", - "integrity": "sha512-s73XxOZ4zpt1edZYZzvhqFa6uvQc1vwUa0K0BdtIZgQMAJj9IbebH+JkgKZc9h+B05PKHLOTl4ajG1BmNrVZlw==", - "dev": true - }, "p-limit": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", - "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, "requires": { - "p-try": "^1.0.0" + "yocto-queue": "^0.1.0" } }, "p-locate": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", - "dev": true, - "requires": { - "p-limit": "^1.1.0" - } - }, - "p-map": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", - "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "dev": true, "requires": { - "aggregate-error": "^3.0.0" + "p-limit": "^3.0.2" } }, "p-try": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true }, - "package-json": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/package-json/-/package-json-6.5.0.tgz", - "integrity": "sha512-k3bdm2n25tkyxcjSKzB5x8kfVxlMdgsbPr0GkZcwHsLpba6cBjqCt1KlcChKEvxHIcTB1FVMuwoijZ26xex5MQ==", - "dev": true, - "requires": { - "got": "^9.6.0", - "registry-auth-token": "^4.0.0", - "registry-url": "^5.0.0", - "semver": "^6.2.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, "parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -18591,21 +14639,17 @@ } }, "parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", "dev": true, "requires": { + "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", - "json-parse-better-errors": "^1.0.1" + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" } }, - "parse5": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", - "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", - "dev": true - }, "parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -18613,9 +14657,9 @@ "dev": true }, "path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true }, "path-is-absolute": { @@ -18648,10 +14692,22 @@ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", "dev": true }, + "picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, "picomatch": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", - "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true + }, + "pidtree": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.6.0.tgz", + "integrity": "sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==", "dev": true }, "pify": { @@ -18667,21 +14723,51 @@ "dev": true }, "pkg-dir": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", - "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", - "dev": true, - "requires": { - "find-up": "^2.1.0" - } - }, - "pkg-up": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-2.0.0.tgz", - "integrity": "sha1-yBmscoBZpGHKscOImivjxJoATX8=", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, "requires": { - "find-up": "^2.1.0" + "find-up": "^4.0.0" + }, + "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + } } }, "please-upgrade-node": { @@ -18705,16 +14791,10 @@ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true }, - "prepend-http": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-2.0.0.tgz", - "integrity": "sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=", - "dev": true - }, "prettier": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.4.1.tgz", - "integrity": "sha512-9fbDAXSBcc6Bs1mZrDYb3XKzDLm4EXXL9sC1LqKP5rZkT6KRr/rf9amVUcODVXgguK/isJz0d0hP72WeaKWsvA==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", + "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", "dev": true }, "prettier-linter-helpers": { @@ -18727,14 +14807,14 @@ } }, "pretty-format": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", - "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", "dev": true, "requires": { - "ansi-regex": "^5.0.1", + "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", - "react-is": "^17.0.1" + "react-is": "^18.0.0" }, "dependencies": { "ansi-styles": { @@ -18745,12 +14825,6 @@ } } }, - "progress": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", - "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", - "dev": true - }, "prompts": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", @@ -18771,12 +14845,6 @@ "ipaddr.js": "1.9.1" } }, - "psl": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", - "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", - "dev": true - }, "pump": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", @@ -18787,32 +14855,37 @@ } }, "punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", "dev": true }, - "pupa": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/pupa/-/pupa-2.1.1.tgz", - "integrity": "sha512-l1jNAspIBSFqbT+y+5FosojNpVpF94nlI+wDUpqP9enwOTfHx9f0gh5nB96vl+6yTpsJsypeNrwfzPrKuHB41A==", + "pure-rand": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.0.tgz", + "integrity": "sha512-rLSBxJjP+4DQOgcJAx6RZHT2he2pkhQdSnofG5VWyVl6GRq/K02ISOuOLcsMOrtKDIJb8JN2zm3FFzWNbezdPw==", + "dev": true + }, + "qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", "dev": true, "requires": { - "escape-goat": "^2.0.0" + "side-channel": "^1.0.4" } }, - "qs": { - "version": "6.7.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", - "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==", - "dev": true - }, "queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", "dev": true }, + "queue-tick": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz", + "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==" + }, "range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", @@ -18820,81 +14893,23 @@ "dev": true }, "raw-body": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", - "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", "dev": true, "requires": { - "bytes": "3.1.0", - "http-errors": "1.7.2", + "bytes": "3.1.2", + "http-errors": "2.0.0", "iconv-lite": "0.4.24", "unpipe": "1.0.0" } }, - "rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "dev": true, - "requires": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "dependencies": { - "ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "dev": true - }, - "strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", - "dev": true - } - } - }, "react-is": { - "version": "17.0.2", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", - "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", "dev": true }, - "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", - "dev": true, - "requires": { - "load-json-file": "^4.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" - }, - "dependencies": { - "path-type": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", - "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", - "dev": true, - "requires": { - "pify": "^3.0.0" - } - } - } - }, - "read-pkg-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", - "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", - "dev": true, - "requires": { - "find-up": "^2.0.0", - "read-pkg": "^3.0.0" - } - }, "readable-stream": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", @@ -18905,29 +14920,30 @@ "util-deprecate": "^1.0.1" } }, - "regexpp": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.1.0.tgz", - "integrity": "sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q==", + "regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", "dev": true }, - "registry-auth-token": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-4.2.1.tgz", - "integrity": "sha512-6gkSb4U6aWJB4SF2ZvLb76yCBjcvufXBqvvEx1HbmKPkutswjW1xNVRY0+daljIYRbogN7O0etYSlbiaEQyMyw==", + "regexp.prototype.flags": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz", + "integrity": "sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==", "dev": true, "requires": { - "rc": "^1.2.8" + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "functions-have-names": "^1.2.2" } }, - "registry-url": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-5.1.0.tgz", - "integrity": "sha512-8acYXXTI0AkQv6RAOjE3vOaIXZkT9wo4LOFbBKYQEEnnMNBpKqdUrI6S4NT0KPIo/WVvJ5tE/X5LF/TQUf0ekw==", + "regexpp": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", + "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", "dev": true, - "requires": { - "rc": "^1.2.8" - } + "optional": true, + "peer": true }, "require-directory": { "version": "2.1.1", @@ -18935,20 +14951,15 @@ "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, - "require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true - }, "resolve": { - "version": "1.20.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", - "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", "dev": true, "requires": { - "is-core-module": "^2.2.0", - "path-parse": "^1.0.6" + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" } }, "resolve-cwd": { @@ -18975,24 +14986,15 @@ "dev": true }, "resolve.exports": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-1.1.0.tgz", - "integrity": "sha512-J1l+Zxxp4XK3LUDZ9m60LRJF/mAe4z6a4xyabPHk7pvK5t35dACV32iIjJDFeWZFfZlO29w6SZ67knR0tHzJtQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.0.tgz", + "integrity": "sha512-6K/gDlqgQscOlg9fSRpWstA8sYe8rbELsSTNpx+3kTrsVCzvSl0zIvRErM7fdl9ERWDsKnrLnwB+Ne89918XOg==", "dev": true }, - "responselike": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/responselike/-/responselike-1.0.2.tgz", - "integrity": "sha1-kYcg7ztjHFZCvgaPFa3lpG9Loec=", - "dev": true, - "requires": { - "lowercase-keys": "^1.0.0" - } - }, "restore-cursor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", - "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", "dev": true, "requires": { "onetime": "^5.1.0", @@ -19005,6 +15007,12 @@ "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", "dev": true }, + "rfdc": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.1.tgz", + "integrity": "sha512-r5a3l5HzYlIC68TpmYKlxWjmOP6wiPJ1vWv2HeLhNsRZMrCkxeqxiHlQ21oXmQ4F3SiryXBHhAD7JZqvOJjFmg==", + "dev": true + }, "rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", @@ -19023,39 +15031,32 @@ "queue-microtask": "^1.2.2" } }, - "rxjs": { - "version": "6.6.7", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", - "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", - "dev": true, - "requires": { - "tslib": "^1.9.0" - } - }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true }, + "safe-regex-test": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.0.tgz", + "integrity": "sha512-JBUUzyOgEwXQY1NuPtvcj/qcBDbDmEvWufhlnXZIm75DEHp+afM1r1ujJpJsV/gSM4t59tpDyPi1sd6ZaPFfsA==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-regex": "^1.1.4" + } + }, "safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, - "saxes": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", - "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", - "dev": true, - "requires": { - "xmlchars": "^2.2.0" - } - }, "semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, "requires": { "lru-cache": "^6.0.0" @@ -19067,42 +15068,25 @@ "integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w=", "dev": true }, - "semver-diff": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-3.1.1.tgz", - "integrity": "sha512-GX0Ix/CJcHyB8c4ykpHGIAvLyOwOobtM/8d+TQkAd81/bEjgPHrfba41Vpesr7jX/t8Uh+R3EX9eAS5be+jQYg==", - "dev": true, - "requires": { - "semver": "^6.3.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, "send": { - "version": "0.17.1", - "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", - "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", "dev": true, "requires": { "debug": "2.6.9", - "depd": "~1.1.2", - "destroy": "~1.0.4", + "depd": "2.0.0", + "destroy": "1.2.0", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "0.5.2", - "http-errors": "~1.7.2", + "http-errors": "2.0.0", "mime": "1.6.0", - "ms": "2.1.1", - "on-finished": "~2.3.0", + "ms": "2.1.3", + "on-finished": "2.4.1", "range-parser": "~1.2.1", - "statuses": "~1.5.0" + "statuses": "2.0.1" }, "dependencies": { "debug": { @@ -19117,29 +15101,38 @@ "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true } } }, "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } } } }, "serve-static": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", - "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", "dev": true, "requires": { "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "parseurl": "~1.3.3", - "send": "0.17.1" + "send": "0.18.0" } }, "server-destroy": { @@ -19149,9 +15142,9 @@ "dev": true }, "setprototypeof": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", - "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", "dev": true }, "shebang-command": { @@ -19169,10 +15162,21 @@ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true }, + "side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + } + }, "signal-exit": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", - "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, "sisteransi": { @@ -19188,14 +15192,27 @@ "dev": true }, "slice-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", - "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", "dev": true, "requires": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "dev": true + } } }, "source-map": { @@ -19204,52 +15221,20 @@ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true }, - "source-map-support": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", - "dev": true, - "requires": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "spdx-correct": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", - "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", - "dev": true, - "requires": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" - } - }, - "spdx-exceptions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", - "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", - "dev": true - }, - "spdx-expression-parse": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", - "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", "dev": true, "requires": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" } }, - "spdx-license-ids": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.9.tgz", - "integrity": "sha512-Ki212dKK4ogX+xDo4CtOZBVIwhsKBEfsEEcwmJfLQzirgc2jIWdzg40Unxz/HzEUqM1WFzVlQSMF9kZZ2HboLQ==", - "dev": true - }, "split-ca": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/split-ca/-/split-ca-1.0.1.tgz", - "integrity": "sha1-bIOv82kvphJW4M0ZfgXp3hV2kaY=" + "integrity": "sha512-Q5thBSxp5t8WPTTJQS59LrGqOZqOsrhDGDVm8azCqIBjSBd7nd9o2PM+mDulQQkh8h//4U6hFZnc/mul8t5pWQ==" }, "sprintf-js": { "version": "1.0.3", @@ -19258,20 +15243,20 @@ "dev": true }, "ssh2": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.6.0.tgz", - "integrity": "sha512-lxc+uvXqOxyQ99N2M7k5o4pkYDO5GptOTYduWw7hIM41icxvoBcCNHcj+LTKrjkL0vFcAl+qfZekthoSFRJn2Q==", + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.15.0.tgz", + "integrity": "sha512-C0PHgX4h6lBxYx7hcXwu3QWdh4tg6tZZsTfXcdvc5caW/EMxaB4H9dWsl7qk+F7LAW762hp8VbXOX7x4xUYvEw==", "requires": { - "asn1": "^0.2.4", + "asn1": "^0.2.6", "bcrypt-pbkdf": "^1.0.2", - "cpu-features": "0.0.2", - "nan": "^2.15.0" + "cpu-features": "~0.0.9", + "nan": "^2.18.0" } }, "stack-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.3.tgz", - "integrity": "sha512-gL//fkxfWUsIlFL2Tl42Cl6+HFALEaB1FU76I/Fy+oZjRreP7OPMXFlGbxM7NQsI0ZpUfw76sHnv0WNYuTb7Iw==", + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.5.tgz", + "integrity": "sha512-xrQcmYhOsn/1kX+Vraq+7j4oE2j/6BFscZ0etmYg81xuM8Gq0022Pxb8+IqgOFUIaxHs0KaSb7T1+OegiNrNFA==", "dev": true, "requires": { "escape-string-regexp": "^2.0.0" @@ -19286,9 +15271,9 @@ } }, "statuses": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", - "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true }, "steno": { @@ -19300,6 +15285,24 @@ "graceful-fs": "^4.1.3" } }, + "stop-iteration-iterator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.0.0.tgz", + "integrity": "sha512-iCGQj+0l0HOdZ2AEeBADlsRC+vsnDsZsbdSiH1yNSjcfKM7fdpCMfqAL/dwF5BLiw/XhRft/Wax6zQbhq2BcjQ==", + "dev": true, + "requires": { + "internal-slot": "^1.0.4" + } + }, + "streamx": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.0.tgz", + "integrity": "sha512-HcxY6ncGjjklGs1xsP1aR71INYcsXFJet5CU1CHqihQ2J5nOsbd4OjgjHO42w/4QNv9gZb3BueV+Vxok5pLEXg==", + "requires": { + "fast-fifo": "^1.1.0", + "queue-tick": "^1.0.1" + } + }, "string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -19316,9 +15319,9 @@ } }, "string-argv": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.1.tgz", - "integrity": "sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg==", + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", "dev": true }, "string-length": { @@ -19343,34 +15346,25 @@ } }, "string.prototype.trimend": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", - "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.5.tgz", + "integrity": "sha512-I7RGvmjV4pJ7O3kdf+LXFpVfdNOxtCW/2C8f6jNiW4+PQchwxkCDzlk1/7p+Wl4bqFIZeF47qAHXLuHHWKAxog==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3" + "define-properties": "^1.1.4", + "es-abstract": "^1.19.5" } }, "string.prototype.trimstart": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", - "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.5.tgz", + "integrity": "sha512-THx16TJCGlsN0o6dl2o6ncWUsdgnLRSA23rRE5pyGBw/mLr3Ej/R2LaqCtgP8VNMGZsvMWnf9ooZPyY2bHvUFg==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - } - }, - "stringify-object": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", - "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", - "dev": true, - "requires": { - "get-own-enumerable-property-symbols": "^3.0.0", - "is-obj": "^1.0.1", - "is-regexp": "^1.0.0" + "define-properties": "^1.1.4", + "es-abstract": "^1.19.5" } }, "strip-ansi": { @@ -19409,15 +15403,11 @@ "has-flag": "^4.0.0" } }, - "supports-hyperlinks": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-2.2.0.tgz", - "integrity": "sha512-6sXEzV5+I5j8Bmq9/vUphGRM/RJNT9SCURJLjwfOg51heRtguGWDzcaBlgAzKhQa0EVNpPEKzQuBwZ8S8WaCeQ==", - "dev": true, - "requires": { - "has-flag": "^4.0.0", - "supports-color": "^7.0.0" - } + "supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true }, "svg-element-attributes": { "version": "1.3.1", @@ -19425,46 +15415,30 @@ "integrity": "sha512-Bh05dSOnJBf3miNMqpsormfNtfidA/GxQVakhtn0T4DECWKeXQRQUceYjJ+OxYiiLdGe4Jo9iFV8wICFapFeIA==", "dev": true }, - "symbol-tree": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", - "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", - "dev": true - }, - "table": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/table/-/table-6.7.1.tgz", - "integrity": "sha512-ZGum47Yi6KOOFDE8m223td53ath2enHcYLgOCjGr5ngu8bdIARQk6mN/wRMv4yMRcHnCSnHbCEha4sobQx5yWg==", + "synckit": { + "version": "0.8.8", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.8.tgz", + "integrity": "sha512-HwOKAP7Wc5aRGYdKH+dw0PRRpbO841v2DENBtjnR5HFWoiNByAl7vrx3p0G/rCyYXQsrxqtX48TImFtPcIHSpQ==", "dev": true, "requires": { - "ajv": "^8.0.1", - "lodash.clonedeep": "^4.5.0", - "lodash.truncate": "^4.4.2", - "slice-ansi": "^4.0.0", - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0" + "@pkgr/core": "^0.1.0", + "tslib": "^2.6.2" }, "dependencies": { - "ajv": { - "version": "8.5.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.5.0.tgz", - "integrity": "sha512-Y2l399Tt1AguU3BPRP9Fn4eN+Or+StUGWCUpbnFyXSo8NZ9S4uj+AG2pjs5apK+ZMOwYOz1+a+VKvKH7CudXgQ==", - "dev": true, - "requires": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - } - }, - "json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==", "dev": true } } }, + "tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", + "dev": true + }, "tar-fs": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.0.1.tgz", @@ -19474,28 +15448,49 @@ "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.0.0" + }, + "dependencies": { + "bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "requires": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "requires": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "requires": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + } + } } }, "tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "requires": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - } - }, - "terminal-link": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-2.1.1.tgz", - "integrity": "sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ==", - "dev": true, + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.7.tgz", + "integrity": "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==", "requires": { - "ansi-escapes": "^4.2.1", - "supports-hyperlinks": "^2.0.0" + "b4a": "^1.6.4", + "fast-fifo": "^1.2.0", + "streamx": "^2.15.0" } }, "test-exclude": { @@ -19515,18 +15510,6 @@ "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", "dev": true }, - "throat": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/throat/-/throat-6.0.1.tgz", - "integrity": "sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w==", - "dev": true - }, - "through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", - "dev": true - }, "tmpl": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", @@ -19539,12 +15522,6 @@ "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", "dev": true }, - "to-readable-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/to-readable-stream/-/to-readable-stream-1.0.0.tgz", - "integrity": "sha512-Iq25XBt6zD5npPhlLVXGFN3/gyR2/qODcKNNyTMd4vbm39HUaOiAM4PMq0eMVC/Tkxz+Zjdsc55g9yyz+Yq00Q==", - "dev": true - }, "to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -19555,51 +15532,38 @@ } }, "toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", "dev": true }, - "tough-cookie": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", - "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", - "dev": true, - "requires": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.1.2" - } - }, - "tr46": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz", - "integrity": "sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==", + "ts-api-utils": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.2.1.tgz", + "integrity": "sha512-RIYA36cJn2WiH9Hy77hdF9r7oEwxAtB/TS9/S4Qd90Ap4z5FSiin5zEiTL44OII1Y3IIlEvxwxFUVgrHSZ/UpA==", "dev": true, - "requires": { - "punycode": "^2.1.1" - } + "requires": {} }, "ts-jest": { - "version": "27.1.3", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-27.1.3.tgz", - "integrity": "sha512-6Nlura7s6uM9BVUAoqLH7JHyMXjz8gluryjpPXxr3IxZdAXnU6FhjvVLHFtfd1vsE1p8zD1OJfskkc0jhTSnkA==", + "version": "29.1.2", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.2.tgz", + "integrity": "sha512-br6GJoH/WUX4pu7FbZXuWGKGNDuU7b8Uj77g/Sp7puZV6EXzuByl6JrECvm0MzVzSTkSHWTihsXt+5XYER5b+g==", "dev": true, "requires": { "bs-logger": "0.x", "fast-json-stable-stringify": "2.x", - "jest-util": "^27.0.0", - "json5": "2.x", + "jest-util": "^29.0.0", + "json5": "^2.2.3", "lodash.memoize": "4.x", "make-error": "1.x", - "semver": "7.x", - "yargs-parser": "20.x" + "semver": "^7.5.3", + "yargs-parser": "^21.0.1" } }, "ts-node": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", - "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", "dev": true, "requires": { "@cspotcode/source-map-support": "^0.8.0", @@ -19617,12 +15581,6 @@ "yn": "3.1.1" }, "dependencies": { - "acorn": { - "version": "8.5.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.5.0.tgz", - "integrity": "sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q==", - "dev": true - }, "acorn-walk": { "version": "8.2.0", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", @@ -19632,21 +15590,21 @@ } }, "tsconfig-paths": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz", - "integrity": "sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw==", + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz", + "integrity": "sha512-fxDhWnFSLt3VuTwtvJt5fpwxBHg5AdKWMsgcPOOIilyjymcYVZoCQF8fvFRezCNfblEXmi+PcM1eYHeOAgXCOQ==", "dev": true, "requires": { "@types/json5": "^0.0.29", "json5": "^1.0.1", - "minimist": "^1.2.0", + "minimist": "^1.2.6", "strip-bom": "^3.0.0" }, "dependencies": { "json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", "dev": true, "requires": { "minimist": "^1.2.0" @@ -19655,7 +15613,7 @@ "strip-bom": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", "dev": true } } @@ -19683,7 +15641,7 @@ "tweetnacl": { "version": "0.14.5", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==" }, "type-check": { "version": "0.4.0", @@ -19716,79 +15674,57 @@ "mime-types": "~2.1.24" } }, - "typedarray-to-buffer": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", - "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", - "dev": true, - "requires": { - "is-typedarray": "^1.0.0" - } - }, "typescript": { - "version": "4.8.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.4.tgz", - "integrity": "sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==", + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", "dev": true }, "unbox-primitive": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", - "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", + "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", "dev": true, "requires": { - "function-bind": "^1.1.1", - "has-bigints": "^1.0.1", - "has-symbols": "^1.0.2", + "call-bind": "^1.0.2", + "has-bigints": "^1.0.2", + "has-symbols": "^1.0.3", "which-boxed-primitive": "^1.0.2" } }, - "unique-string": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", - "integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", - "dev": true, + "undici": { + "version": "5.28.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz", + "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", "requires": { - "crypto-random-string": "^2.0.0" + "@fastify/busboy": "^2.0.0" } }, - "universal-user-agent": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", - "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" - }, - "universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", "dev": true }, + "universal-user-agent": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", + "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==" + }, "unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", "dev": true }, - "update-notifier": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-5.1.0.tgz", - "integrity": "sha512-ItnICHbeMh9GqUy31hFPrD1kcuZ3rpxDZbf4KUDavXwS0bW5m7SLbDQpGX3UYr072cbrF5hFUs3r5tUsPwjfHw==", - "dev": true, - "requires": { - "boxen": "^5.0.0", - "chalk": "^4.1.0", - "configstore": "^5.0.1", - "has-yarn": "^2.1.0", - "import-lazy": "^2.1.0", - "is-ci": "^2.0.0", - "is-installed-globally": "^0.4.0", - "is-npm": "^5.0.0", - "is-yarn-global": "^0.3.0", - "latest-version": "^5.1.0", - "pupa": "^2.1.1", - "semver": "^7.3.4", - "semver-diff": "^3.1.1", - "xdg-basedir": "^4.0.0" + "update-browserslist-db": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", + "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", + "dev": true, + "requires": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" } }, "uri-js": { @@ -19800,15 +15736,6 @@ "punycode": "^2.1.0" } }, - "url-parse-lax": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-3.0.0.tgz", - "integrity": "sha1-FrXK/Afb42dsGxmZF3gj1lA6yww=", - "dev": true, - "requires": { - "prepend-http": "^2.0.0" - } - }, "util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -19825,12 +15752,6 @@ "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" }, - "v8-compile-cache": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", - "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", - "dev": true - }, "v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", @@ -19838,172 +15759,66 @@ "dev": true }, "v8-to-istanbul": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-8.1.1.tgz", - "integrity": "sha512-FGtKtv3xIpR6BYhvgH8MI/y78oT7d8Au3ww4QIxymrCtZEh5b8gCw2siywE+puhEmuWKDtmfrvF5UlB298ut3w==", + "version": "9.1.3", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.3.tgz", + "integrity": "sha512-9lDD+EVI2fjFsMWXc6dy5JJzBsVTcQ2fVkfBvncZ6xJWG9wtBhOldG+mHkSL0+V1K/xgZz0JDO5UT5hFwHUghg==", "dev": true, "requires": { + "@jridgewell/trace-mapping": "^0.3.12", "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^1.6.0", - "source-map": "^0.7.3" + "convert-source-map": "^2.0.0" }, "dependencies": { - "source-map": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", - "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "@jridgewell/trace-mapping": { + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "dev": true } } }, - "validate-npm-package-license": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", - "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", - "dev": true, - "requires": { - "spdx-correct": "^3.0.0", - "spdx-expression-parse": "^3.0.0" - } - }, "vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", "dev": true }, - "w3c-hr-time": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", - "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", - "dev": true, - "requires": { - "browser-process-hrtime": "^1.0.0" - } - }, - "w3c-xmlserializer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz", - "integrity": "sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA==", - "dev": true, - "requires": { - "xml-name-validator": "^3.0.0" - } - }, "wait-port": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/wait-port/-/wait-port-0.2.9.tgz", - "integrity": "sha512-hQ/cVKsNqGZ/UbZB/oakOGFqic00YAMM5/PEj3Bt4vKarv2jWIWzDbqlwT94qMs/exAQAsvMOq99sZblV92zxQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/wait-port/-/wait-port-1.1.0.tgz", + "integrity": "sha512-3e04qkoN3LxTMLakdqeWth8nih8usyg+sf1Bgdf9wwUkp05iuK1eSY/QpLvscT/+F/gA89+LpUmmgBtesbqI2Q==", "dev": true, "requires": { - "chalk": "^2.4.2", - "commander": "^3.0.2", - "debug": "^4.1.1" + "chalk": "^4.1.2", + "commander": "^9.3.0", + "debug": "^4.3.4" }, "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true - }, "commander": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/commander/-/commander-3.0.2.tgz", - "integrity": "sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow==", + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", + "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } } } }, "walker": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz", - "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", - "dev": true, - "requires": { - "makeerror": "1.0.x" - } - }, - "webidl-conversions": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", - "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", - "dev": true - }, - "whatwg-encoding": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", - "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", - "dev": true, - "requires": { - "iconv-lite": "0.4.24" - } - }, - "whatwg-mimetype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", - "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", - "dev": true - }, - "whatwg-url": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-8.7.0.tgz", - "integrity": "sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", "dev": true, "requires": { - "lodash": "^4.7.0", - "tr46": "^2.1.0", - "webidl-conversions": "^6.1.0" + "makeerror": "1.0.12" } }, "which": { @@ -20028,20 +15843,31 @@ "is-symbol": "^1.0.3" } }, - "widest-line": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz", - "integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==", + "which-collection": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.1.tgz", + "integrity": "sha512-W8xeTUwaln8i3K/cY1nGXzdnVZlidBcagyNFtBdD5kxnb4TvGKR7FfSIS3mYpwWS1QUCutfKz8IY8RjftB0+1A==", "dev": true, "requires": { - "string-width": "^4.0.0" + "is-map": "^2.0.1", + "is-set": "^2.0.1", + "is-weakmap": "^2.0.1", + "is-weakset": "^2.0.1" } }, - "word-wrap": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", - "dev": true + "which-typed-array": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.9.tgz", + "integrity": "sha512-w9c4xkx6mPidwp7180ckYWfMmvxpjlZuIudNtDf4N/tTAUB8VJbX25qZoAsrtGuYNnGw3pa0AXgbGKRB8/EceA==", + "dev": true, + "requires": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0", + "is-typed-array": "^1.1.10" + } }, "wrap-ansi": { "version": "7.0.0", @@ -20060,42 +15886,15 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", - "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", "dev": true, "requires": { "imurmurhash": "^0.1.4", - "is-typedarray": "^1.0.0", - "signal-exit": "^3.0.2", - "typedarray-to-buffer": "^3.1.5" + "signal-exit": "^3.0.7" } }, - "ws": { - "version": "7.5.7", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.7.tgz", - "integrity": "sha512-KMvVuFzpKBuiIXW3E4u3mySRO2/mCHSyZDJQM5NQ9Q9KHWHWh0NHgfbRMLLrceUK5qAL4ytALJbpRMjixFZh8A==", - "dev": true, - "requires": {} - }, - "xdg-basedir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", - "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", - "dev": true - }, - "xml-name-validator": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", - "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", - "dev": true - }, - "xmlchars": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", - "dev": true - }, "y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", @@ -20109,30 +15908,30 @@ "dev": true }, "yaml": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", - "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.3.4.tgz", + "integrity": "sha512-8aAvwVUSHpfEqTQ4w/KMlf3HcRdt50E5ODIQJBw1fQ5RL34xabzxtUlzTXVqc4rkZsPbvrXKWnABCD7kWSmocA==", "dev": true }, "yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "version": "17.6.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.6.0.tgz", + "integrity": "sha512-8H/wTDqlSwoSnScvV2N/JHfLWOKuh5MVla9hqLjK3nsfyy6Y4kDSYSvkU5YCUEPOSnRXfIyx3Sq+B/IWudTo4g==", "dev": true, "requires": { - "cliui": "^7.0.2", + "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", - "string-width": "^4.2.0", + "string-width": "^4.2.3", "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" + "yargs-parser": "^21.0.0" } }, "yargs-parser": { - "version": "20.2.7", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.7.tgz", - "integrity": "sha512-FiNkvbeHzB/syOjIUxFDCnhSfzAL8R5vs40MgLFBorXACCOAEaWu0gRZl14vG8MR9AOJIZbmkjhusqBYZ3HTHw==", + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", "dev": true }, "yn": { @@ -20140,6 +15939,12 @@ "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", "dev": true + }, + "yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true } } } diff --git a/package.json b/package.json index fd4bd00c4..aad610e75 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dependabot-updater-action", - "version": "2.2.5", + "version": "2.20.0", "private": true, "description": "Runs Dependabot workloads via GitHub Actions.", "main": "src/main.ts", @@ -30,40 +30,39 @@ "author": "GitHub", "license": "MIT", "dependencies": { - "@actions/core": "^1.9.1", - "@actions/github": "^5.0.0", - "@octokit/webhooks-types": "^6.3.6", - "axios": "^0.23.0", - "ci": "^2.1.1", - "commander": "^9.1.0", - "dockerode": "^3.3.1", - "npm": "^8.18.0", - "tar-stream": "^2.2.0" + "@actions/core": "^1.10.1", + "@actions/github": "^6.0.0", + "@actions/http-client": "^2.2.1", + "@octokit/webhooks-types": "^7.5.1", + "commander": "^12.1.0", + "dockerode": "^4.0.2", + "node-forge": "^1.3.1", + "tar-stream": "^3.1.7" }, "devDependencies": { - "@types/dockerode": "^3.2.6", - "@types/jest": "^27.0.2", - "@types/node": "^18.7.13", - "@types/node-forge": "^1.0.1", - "@types/tar-stream": "^2.2.2", - "@typescript-eslint/parser": "^4.33.0", - "@vercel/ncc": "^0.34.0", - "eslint": "^7.32.0", - "eslint-config-prettier": "^8.3.0", - "eslint-plugin-github": "^4.1.5", - "eslint-plugin-jest": "^25.2.4", - "husky": "^7.0.4", - "jest": "^27.5.1", - "jest-circus": "^27.3.1", - "js-yaml": "^4.1.0", - "json-server": "^0.17.0", - "lint-staged": "^11.1.1", - "node-forge": "^1.2.1", - "prettier": "2.4.1", - "ts-jest": "^27.1.3", - "ts-node": "^10.9.1", - "typescript": "^4.8.4", - "wait-port": "^0.2.9" + "@types/dockerode": "^3.3.28", + "@types/jest": "^29.5.12", + "@types/node": "^20.12.7", + "@types/node-forge": "^1.3.11", + "@types/tar-stream": "^3.1.3", + "@typescript-eslint/parser": "^5.62.0", + "@vercel/ncc": "^0.38.1", + "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", + "eslint-import-resolver-typescript": "^3.6.1", + "eslint-plugin-github": "^4.10.2", + "eslint-plugin-jest": "^27.9.0", + "eslint-plugin-prettier": "^5.1.3", + "husky": "^9.0.11", + "jest": "^29.7.0", + "jest-circus": "^29.5.0", + "json-server": "^0.17.4", + "lint-staged": "^15.2.2", + "prettier": "3.2.5", + "ts-jest": "^29.1.2", + "ts-node": "^10.9.2", + "typescript": "^5.4.5", + "wait-port": "^1.1.0" }, "lint-staged": { "src/**/*.ts": [ diff --git a/src/api-client.ts b/src/api-client.ts index 62e8692b5..a4e350fa4 100644 --- a/src/api-client.ts +++ b/src/api-client.ts @@ -1,14 +1,16 @@ import * as core from '@actions/core' -import axios, {AxiosInstance} from 'axios' +import * as httpClient from '@actions/http-client' import {JobParameters} from './inputs' +import {TypedResponse} from '@actions/http-client/lib/interfaces' // JobDetails are information about the repository and dependencies to be updated export type JobDetails = { - 'allowed-updates': { + 'allowed-updates': Array<{ 'dependency-type': string - }[] + }> id: string 'package-manager': string + experiments: object } export type JobError = { @@ -26,13 +28,19 @@ export type Credential = { token?: string } +export class JobDetailsFetchingError extends Error {} export class CredentialFetchingError extends Error {} export class ApiClient { + private jobToken: string constructor( - private readonly client: AxiosInstance, - readonly params: JobParameters - ) {} + private readonly client: httpClient.HttpClient, + readonly params: JobParameters, + jobToken: string, + private readonly credentialsToken: string + ) { + this.jobToken = jobToken + } // We use a static unknown SHA when marking a job as complete from the action // to remain in parity with the existing runner. @@ -40,27 +48,68 @@ export class ApiClient { 'base-commit-sha': 'unknown' } + // Getter for jobToken + getJobToken(): string { + return this.jobToken + } + async getJobDetails(): Promise { - const detailsURL = `/update_jobs/${this.params.jobId}/details` - const res: any = await this.client.get(detailsURL, { - headers: {Authorization: this.params.jobToken} - }) - if (res.status !== 200) { - throw new Error(`Unexpected status code: ${res.status}`) - } + const detailsURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/details` + try { + const res = await this.getJsonWithRetry(detailsURL, this.jobToken) + if (res.statusCode !== 200) { + throw new JobDetailsFetchingError( + `fetching job details: unexpected status code: ${ + res.statusCode + }: ${JSON.stringify(res.result)}` + ) + } + if (!res.result) { + throw new JobDetailsFetchingError( + `fetching job details: missing response` + ) + } - return res.data.data.attributes + return res.result.data.attributes + } catch (error: unknown) { + if (error instanceof JobDetailsFetchingError) { + throw error + } else if (error instanceof httpClient.HttpClientError) { + throw new JobDetailsFetchingError( + `fetching job details: unexpected status code: ${error.statusCode}: ${error.message}` + ) + } else if (error instanceof Error) { + throw new JobDetailsFetchingError( + `fetching job details: ${error.name}: ${error.message}` + ) + } + throw error + } } async getCredentials(): Promise { - const credentialsURL = `/update_jobs/${this.params.jobId}/credentials` + const credentialsURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/credentials` try { - const res: any = await this.client.get(credentialsURL, { - headers: {Authorization: this.params.credentialsToken} - }) + const res = await this.getJsonWithRetry( + credentialsURL, + this.credentialsToken + ) + + if (res.statusCode !== 200) { + throw new CredentialFetchingError( + `fetching credentials: unexpected status code: ${ + res.statusCode + }: ${JSON.stringify(res.result)}` + ) + } + if (!res.result) { + throw new CredentialFetchingError( + `fetching credentials: missing response` + ) + } // Mask any secrets we've just retrieved from Actions logs - for (const credential of res.data.data.attributes.credentials) { + for (const credential of res.result.data.attributes.credentials) { if (credential.password) { core.setSecret(credential.password) } @@ -69,46 +118,84 @@ export class ApiClient { } } - return res.data.data.attributes.credentials + return res.result.data.attributes.credentials } catch (error: unknown) { - if (axios.isAxiosError(error)) { - const err = error + if (error instanceof CredentialFetchingError) { + throw error + } else if (error instanceof httpClient.HttpClientError) { throw new CredentialFetchingError( - `fetching credentials: received code ${ - err.response?.status - }: ${JSON.stringify(err.response?.data)}` + `fetching credentials: unexpected status code: ${error.statusCode}: ${error.message}` + ) + } else if (error instanceof Error) { + throw new CredentialFetchingError( + `fetching credentials: ${error.name}: ${error.message}` ) - } else { - throw error } + throw error } } async reportJobError(error: JobError): Promise { - const recordErrorURL = `/update_jobs/${this.params.jobId}/record_update_job_error` - const res = await this.client.post( + const recordErrorURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/record_update_job_error` + const res = await this.client.postJson( recordErrorURL, {data: error}, { - headers: {Authorization: this.params.jobToken} + ['Authorization']: this.jobToken } ) - if (res.status !== 204) { - throw new Error(`Unexpected status code: ${res.status}`) + if (res.statusCode !== 204) { + throw new Error(`Unexpected status code: ${res.statusCode}`) } } async markJobAsProcessed(): Promise { - const markAsProcessedURL = `/update_jobs/${this.params.jobId}/mark_as_processed` - const res = await this.client.patch( + const markAsProcessedURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/mark_as_processed` + const res = await this.client.patchJson( markAsProcessedURL, {data: this.UnknownSha}, { - headers: {Authorization: this.params.jobToken} + ['Authorization']: this.jobToken } ) - if (res.status !== 204) { - throw new Error(`Unexpected status code: ${res.status}`) + if (res.statusCode !== 204) { + throw new Error(`Unexpected status code: ${res.statusCode}`) + } + } + + private async getJsonWithRetry( + url: string, + token: string + ): Promise> { + let attempt = 1 + + const execute = async (): Promise> => { + try { + return await this.client.getJson(url, { + ['Authorization']: token + }) + } catch (error: unknown) { + if (error instanceof httpClient.HttpClientError) { + if (error.statusCode >= 500 && error.statusCode <= 599) { + if (attempt >= 3) { + throw error + } + core.warning( + `Retrying failed request with status code: ${error.statusCode}` + ) + + // exponential backoff + const delayMs = 1000 * 2 ** attempt + await new Promise(resolve => setTimeout(resolve, delayMs)) + + attempt++ + return execute() + } + } + throw error + } } + + return execute() } } diff --git a/src/cleanup.ts b/src/cleanup.ts index ecd8a25c5..85fe54592 100644 --- a/src/cleanup.ts +++ b/src/cleanup.ts @@ -1,8 +1,10 @@ import * as core from '@actions/core' import Docker from 'dockerode' import { - UPDATER_IMAGE_NAME, + updaterImages, PROXY_IMAGE_NAME, + digestName, + hasDigest, repositoryName } from './docker-tags' @@ -12,6 +14,10 @@ import { // // cutoff - a Go duration string to pass to the Docker API's 'until' argument, default '24h' export async function run(cutoff = '24h'): Promise { + if (process.env.DEPENDABOT_DISABLE_CLEANUP === '1') { + return + } + try { const docker = new Docker() const untilFilter = {until: [cutoff]} @@ -19,7 +25,11 @@ export async function run(cutoff = '24h'): Promise { await docker.pruneNetworks({filters: untilFilter}) core.info(`Pruning containers older than ${cutoff}`) await docker.pruneContainers({filters: untilFilter}) - await cleanupOldImageVersions(docker, UPDATER_IMAGE_NAME) + await Promise.all( + updaterImages().map(async image => { + return cleanupOldImageVersions(docker, image) + }) + ) await cleanupOldImageVersions(docker, PROXY_IMAGE_NAME) } catch (error: unknown) { if (error instanceof Error) { @@ -34,9 +44,7 @@ export async function cleanupOldImageVersions( ): Promise { const repo = repositoryName(imageName) const options = { - filters: { - reference: [repo] - } + filters: `{"reference":["${repo}"]}` } core.info(`Cleaning up images for ${repo}`) @@ -44,19 +52,16 @@ export async function cleanupOldImageVersions( docker.listImages(options, async function (err, imageInfoList) { if (imageInfoList && imageInfoList.length > 0) { for (const imageInfo of imageInfoList) { - // The given imageName is expected to be a digest, however to avoid any surprises in future - // we fail over to check for a match on tags as well. + // The given imageName is expected to be a tag + digest, however to avoid any surprises in future + // we fail over to check for a match on just tags as well. // // This means we won't remove any image which matches an imageName of either of these notations: - // - dependabot/image@sha256:$REF (current implementation) + // - dependabot/image:$TAG@sha256:$REF (current implementation) // - dependabot/image:v1 // // Without checking imageInfo.RepoTags for a match, we would actually remove the latter even if // this was the active version. - if ( - imageInfo.RepoDigests?.includes(imageName) || - imageInfo.RepoTags?.includes(imageName) - ) { + if (imageMatches(imageInfo, imageName)) { core.info(`Skipping current image ${imageInfo.Id}`) continue } @@ -74,4 +79,13 @@ export async function cleanupOldImageVersions( }) } +function imageMatches(imageInfo: Docker.ImageInfo, imageName: string): boolean { + if (hasDigest(imageName)) { + return imageInfo.RepoDigests + ? imageInfo.RepoDigests.includes(digestName(imageName)) + : false + } + return imageInfo.RepoTags ? imageInfo.RepoTags.includes(imageName) : false +} + run() diff --git a/src/config-types.ts b/src/config-types.ts index 94b04ebb1..b69795c12 100644 --- a/src/config-types.ts +++ b/src/config-types.ts @@ -30,13 +30,7 @@ export type CertificateAuthority = { key: string } -export type BasicAuthCredentials = { - username: string - password: string -} - export type ProxyConfig = { all_credentials: Credential[] ca: CertificateAuthority - proxy_auth: BasicAuthCredentials } diff --git a/src/container-service.ts b/src/container-service.ts index 1749324c6..99f7e1321 100644 --- a/src/container-service.ts +++ b/src/container-service.ts @@ -6,6 +6,8 @@ import {outStream, errStream} from './utils' export class ContainerRuntimeError extends Error {} +const RWX_ALL = 0o777 + export const ContainerService = { async storeInput( name: string, @@ -14,7 +16,7 @@ export const ContainerService = { input: FileFetcherInput | FileUpdaterInput | ProxyConfig ): Promise { const tar = pack() - tar.entry({name}, JSON.stringify(input)) + tar.entry({name, mode: RWX_ALL}, JSON.stringify(input)) tar.finalize() await container.putArchive(tar, {path}) }, diff --git a/src/docker-tags.ts b/src/docker-tags.ts index 1458b1c54..7aa4ef56c 100644 --- a/src/docker-tags.ts +++ b/src/docker-tags.ts @@ -1,10 +1,24 @@ +// eslint-disable-next-line import/extensions import dockerContainerConfig from '../docker/containers.json' -export const UPDATER_IMAGE_NAME = dockerContainerConfig.updater export const PROXY_IMAGE_NAME = dockerContainerConfig.proxy +export function updaterImageName(packageManager: string): string { + return dockerContainerConfig[ + packageManager as keyof typeof dockerContainerConfig + ] +} + +const updaterRegex = /ghcr.io\/dependabot\/dependabot-updater-([\w+])/ + +export function updaterImages(): string[] { + return Object.values(dockerContainerConfig).filter(image => + image.match(updaterRegex) + ) +} + const imageNamePattern = - '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))((:[a-zA-Z0-9._/-]+)|(@sha256:[a-zA-Z0-9]{64}))?$' + '^(?(([a-zA-Z0-9._-]+([:[0-9]+[^/]))?([a-zA-Z0-9._/-]+)?))(:[a-zA-Z0-9._/-]+)?(?@sha256:[a-zA-Z0-9]{64})?$' export function repositoryName(imageName: string): string { const match = imageName.match(imageNamePattern) @@ -15,3 +29,26 @@ export function repositoryName(imageName: string): string { throw Error('invalid image name') } } + +export function hasDigest(imageName: string): boolean { + const match = imageName.match(imageNamePattern) + + if (match?.groups) { + if (match?.groups['digest']) { + return true + } + return false + } else { + throw Error('invalid image name') + } +} + +export function digestName(imageName: string): string { + const match = imageName.match(imageNamePattern) + + if (match?.groups) { + return match.groups['repository'] + match.groups['digest'] + } else { + throw Error('invalid image name') + } +} diff --git a/src/fetch-images.ts b/src/fetch-images.ts index d04c840bc..b52ae32d9 100644 --- a/src/fetch-images.ts +++ b/src/fetch-images.ts @@ -1,9 +1,15 @@ import {ImageService} from './image-service' -import {UPDATER_IMAGE_NAME, PROXY_IMAGE_NAME} from './docker-tags' +import {updaterImageName, PROXY_IMAGE_NAME} from './docker-tags' -export async function run(): Promise { - await ImageService.pull(UPDATER_IMAGE_NAME) +export async function run(packageManager: string): Promise { + await ImageService.pull(updaterImageName(packageManager)) await ImageService.pull(PROXY_IMAGE_NAME) } -run() +if (process.argv.length < 2) { + // eslint-disable-next-line no-console + console.error('Usage: npm run fetch-images ') + process.exit(1) +} + +run(process.argv[2]) diff --git a/src/image-service.ts b/src/image-service.ts index f0b376e41..7efdf8ff9 100644 --- a/src/image-service.ts +++ b/src/image-service.ts @@ -4,7 +4,7 @@ import {Readable} from 'stream' const endOfStream = async (docker: Docker, stream: Readable): Promise => { return new Promise((resolve, reject) => { - docker.modem.followProgress(stream, (err: Error) => + docker.modem.followProgress(stream, (err: Error | null) => err ? reject(err) : resolve(undefined) ) }) diff --git a/src/inputs.ts b/src/inputs.ts index 77a5bac9d..e38f3f2d6 100644 --- a/src/inputs.ts +++ b/src/inputs.ts @@ -15,6 +15,7 @@ export class JobParameters { readonly credentialsToken: string, readonly dependabotApiUrl: string, readonly dependabotApiDockerUrl: string, + readonly updaterImage: string, readonly workingDirectory: string ) {} } @@ -23,7 +24,19 @@ export function getJobParameters(ctx: Context): JobParameters | null { checkEnvironmentAndContext(ctx) if (ctx.actor !== DEPENDABOT_ACTOR) { - core.warning('This workflow can only be triggered by Dependabot.') + core.warning( + `This workflow can only be triggered by Dependabot. Actor was '${ctx.actor}'.` + ) + return null + } + + if ( + process.env.GITHUB_TRIGGERING_ACTOR && + process.env.GITHUB_TRIGGERING_ACTOR !== DEPENDABOT_ACTOR + ) { + core.warning( + 'Dependabot workflows cannot be re-run. Retrigger this update via Dependabot instead.' + ) return null } @@ -82,6 +95,7 @@ function fromWorkflowInputs(ctx: Context): JobParameters { evt.inputs.credentialsToken as string, evt.inputs.dependabotApiUrl as string, dependabotApiDockerUrl as string, + evt.inputs.updaterImage as string, workingDirectory ) } diff --git a/src/main.ts b/src/main.ts index eb9a5b11a..92e7e580c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,12 +1,12 @@ -import axios from 'axios' import * as core from '@actions/core' import * as github from '@actions/github' +import * as httpClient from '@actions/http-client' import {Context} from '@actions/github/lib/context' import {ApiClient, CredentialFetchingError} from './api-client' import {getJobParameters} from './inputs' import {ImageService} from './image-service' -import {UPDATER_IMAGE_NAME, PROXY_IMAGE_NAME} from './docker-tags' -import {Updater, UpdaterFetchError} from './updater' +import {updaterImageName, PROXY_IMAGE_NAME} from './docker-tags' +import {Updater} from './updater' export enum DependabotErrorType { Unknown = 'actions_workflow_unknown', @@ -30,24 +30,48 @@ export async function run(context: Context): Promise { return // TODO: This should be setNeutral in future } + // Use environment variables if set and not empty, otherwise use parameters. + // The param values of job token and credentials token are kept to support backwards compatibility. + const jobToken = process.env.GITHUB_DEPENDABOT_JOB_TOKEN || params.jobToken + const credentialsToken = + process.env.GITHUB_DEPENDABOT_CRED_TOKEN || params.credentialsToken + + // Validate jobToken and credentialsToken + if (!jobToken) { + const errorMessage = 'Github Dependabot job token is not set' + botSay(`finished: ${errorMessage}`) + core.setFailed(errorMessage) + return + } + if (!credentialsToken) { + const errorMessage = 'Github Dependabot credentials token is not set' + botSay(`finished: ${errorMessage}`) + core.setFailed(errorMessage) + return + } + jobId = params.jobId - core.setSecret(params.jobToken) - core.setSecret(params.credentialsToken) + core.setSecret(jobToken) + core.setSecret(credentialsToken) - const client = axios.create({baseURL: params.dependabotApiUrl}) - const apiClient = new ApiClient(client, params) + const client = new httpClient.HttpClient('github/dependabot-action') + const apiClient = new ApiClient(client, params, jobToken, credentialsToken) core.info('Fetching job details') // If we fail to succeed in fetching the job details, we cannot be sure the job has entered a 'processing' state, - // so we do not try attempt to report back an exception if this fails and instead rely on the the workflow run + // so we do not try attempt to report back an exception if this fails and instead rely on the workflow run // webhook as it anticipates scenarios where jobs have failed while 'enqueued'. const details = await apiClient.getJobDetails() + // The dynamic workflow can specify which updater image to use. If it doesn't, fall back to the pinned version. + const updaterImage = + params.updaterImage || updaterImageName(details['package-manager']) + try { const credentials = await apiClient.getCredentials() const updater = new Updater( - UPDATER_IMAGE_NAME, + updaterImage, PROXY_IMAGE_NAME, apiClient, details, @@ -57,7 +81,7 @@ export async function run(context: Context): Promise { core.startGroup('Pulling updater images') try { - await ImageService.pull(UPDATER_IMAGE_NAME) + await ImageService.pull(updaterImage) await ImageService.pull(PROXY_IMAGE_NAME) } catch (error: unknown) { if (error instanceof Error) { @@ -77,17 +101,7 @@ export async function run(context: Context): Promise { await updater.runUpdater() } catch (error: unknown) { - // If we have encountered a UpdaterFetchError, the Updater will already have - // reported the error and marked the job as processed, so we only need to - // set an exit status. - if (error instanceof UpdaterFetchError) { - setFailed( - 'Dependabot was unable to retrieve the files required to perform the update', - null - ) - botSay('finished: unable to fetch files') - return - } else if (error instanceof Error) { + if (error instanceof Error) { await failJob( apiClient, 'Dependabot encountered an error performing the update', @@ -162,7 +176,7 @@ function dependabotJobHelp(): string | null { if (jobId) { return `For more information see: ${dependabotJobUrl( jobId - )} (write access required)` + )} (write access to the repository is required to view the log)` } else { return null } diff --git a/src/proxy.ts b/src/proxy.ts index c9f8218fc..a36f2c3bd 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -1,12 +1,7 @@ import fs from 'fs' import * as core from '@actions/core' import Docker, {Container, Network} from 'dockerode' -import crypto from 'crypto' -import { - BasicAuthCredentials, - CertificateAuthority, - ProxyConfig -} from './config-types' +import {CertificateAuthority, ProxyConfig} from './config-types' import {ContainerService} from './container-service' import {Credential} from './api-client' import {pki} from 'node-forge' @@ -57,12 +52,18 @@ export type Proxy = { export class ProxyBuilder { constructor( private readonly docker: Docker, - private readonly proxyImage: string + private readonly proxyImage: string, + private readonly cachedMode: boolean ) {} - async run(jobId: number, credentials: Credential[]): Promise { + async run( + jobId: number, + jobToken: string, + dependabotApiUrl: string, + credentials: Credential[] + ): Promise { const name = `dependabot-job-${jobId}-proxy` - const config = this.buildProxyConfig(credentials, jobId) + const config = this.buildProxyConfig(credentials) const cert = config.ca.cert const externalNetworkName = `dependabot-job-${jobId}-external-network` @@ -73,6 +74,8 @@ export class ProxyBuilder { const container = await this.createContainer( jobId, + jobToken, + dependabotApiUrl, name, externalNetwork, internalNetwork, @@ -117,7 +120,7 @@ export class ProxyBuilder { const ipAddress = containerInfo.NetworkSettings.Networks[`${internalNetworkName}`] .IPAddress - return `http://${config.proxy_auth.username}:${config.proxy_auth.password}@${ipAddress}:1080` + return `http://${ipAddress}:1080` } else { throw new Error("proxy container isn't running") } @@ -132,8 +135,7 @@ export class ProxyBuilder { shutdown: async () => { await container.stop() await container.remove() - await externalNetwork.remove() - await internalNetwork.remove() + await Promise.all([externalNetwork.remove(), internalNetwork.remove()]) } } } @@ -149,18 +151,10 @@ export class ProxyBuilder { } } - private buildProxyConfig( - credentials: Credential[], - jobId: number - ): ProxyConfig { + private buildProxyConfig(credentials: Credential[]): ProxyConfig { const ca = this.generateCertificateAuthority() - const password = crypto.randomBytes(20).toString('hex') - const proxy_auth: BasicAuthCredentials = { - username: `${jobId}`, - password - } - const config: ProxyConfig = {all_credentials: credentials, ca, proxy_auth} + const config: ProxyConfig = {all_credentials: credentials, ca} return config } @@ -189,6 +183,8 @@ export class ProxyBuilder { private async createContainer( jobId: number, + jobToken: string, + dependabotApiUrl: string, containerName: string, externalNetwork: Network, internalNetwork: Network, @@ -205,7 +201,10 @@ export class ProxyBuilder { process.env.https_proxy || process.env.HTTPS_PROXY || '' }`, `no_proxy=${process.env.no_proxy || process.env.NO_PROXY || ''}`, - `JOB_ID=${jobId}` + `JOB_ID=${jobId}`, + `JOB_TOKEN=${jobToken}`, + `PROXY_CACHE=${this.cachedMode ? 'true' : 'false'}`, + `DEPENDABOT_API_URL=${dependabotApiUrl}` ], Entrypoint: [ 'sh', diff --git a/src/update-containers.ts b/src/update-containers.ts index 009e6655a..135ce217e 100644 --- a/src/update-containers.ts +++ b/src/update-containers.ts @@ -1,6 +1,6 @@ import fs from 'fs' -export function getImageName(dockerfileName: string): String { +export function getImageName(dockerfileName: string): string { const dockerfile = fs.readFileSync( require.resolve(`../docker/${dockerfileName}`), 'utf8' @@ -21,7 +21,24 @@ export function getImageName(dockerfileName: string): String { const manifest = { proxy: getImageName('Dockerfile.proxy'), - updater: getImageName('Dockerfile.updater') + bundler: getImageName('Dockerfile.bundler'), + cargo: getImageName('Dockerfile.cargo'), + composer: getImageName('Dockerfile.composer'), + pub: getImageName('Dockerfile.pub'), + docker: getImageName('Dockerfile.docker'), + elm: getImageName('Dockerfile.elm'), + github_actions: getImageName('Dockerfile.github-actions'), + submodules: getImageName('Dockerfile.gitsubmodule'), + go_modules: getImageName('Dockerfile.gomod'), + gradle: getImageName('Dockerfile.gradle'), + maven: getImageName('Dockerfile.maven'), + hex: getImageName('Dockerfile.mix'), + nuget: getImageName('Dockerfile.nuget'), + npm_and_yarn: getImageName('Dockerfile.npm'), + pip: getImageName('Dockerfile.pip'), + swift: getImageName('Dockerfile.swift'), + terraform: getImageName('Dockerfile.terraform'), + devcontainers: getImageName('Dockerfile.devcontainers') } fs.writeFile( diff --git a/src/updater-builder.ts b/src/updater-builder.ts index df8950688..1c3d99042 100644 --- a/src/updater-builder.ts +++ b/src/updater-builder.ts @@ -21,16 +21,15 @@ export class UpdaterBuilder { private readonly input: FileFetcherInput | FileUpdaterInput, private readonly outputHostPath: string, private readonly proxy: Proxy, - private readonly repoHostPath: string, private readonly updaterImage: string ) {} - async run(containerName: string, updaterCommand: string): Promise { - const cmd = `(echo > /etc/ca-certificates.conf) &&\ - rm -Rf /usr/share/ca-certificates/ &&\ - /usr/sbin/update-ca-certificates &&\ - $DEPENDABOT_HOME/dependabot-updater/bin/run ${updaterCommand}` + async run(containerName: string): Promise { + const cmd = `/usr/sbin/update-ca-certificates &&\ + mkdir -p ${JOB_OUTPUT_PATH} &&\ + $DEPENDABOT_HOME/dependabot-updater/bin/run fetch_files &&\ + $DEPENDABOT_HOME/dependabot-updater/bin/run update_files` const proxyUrl = await this.proxy.url() const container = await this.docker.createContainer({ @@ -41,7 +40,7 @@ export class UpdaterBuilder { Env: [ `GITHUB_ACTIONS=${process.env.GITHUB_ACTIONS}`, `DEPENDABOT_JOB_ID=${this.jobParams.jobId}`, - `DEPENDABOT_JOB_TOKEN=${this.jobParams.jobToken}`, + `DEPENDABOT_JOB_TOKEN=`, `DEPENDABOT_JOB_PATH=${JOB_INPUT_PATH}/${JOB_INPUT_FILENAME}`, `DEPENDABOT_OPEN_TIMEOUT_IN_SECONDS=15`, `DEPENDABOT_OUTPUT_PATH=${JOB_OUTPUT_PATH}/${JOB_OUTPUT_FILENAME}`, @@ -52,17 +51,15 @@ export class UpdaterBuilder { `HTTP_PROXY=${proxyUrl}`, `https_proxy=${proxyUrl}`, `HTTPS_PROXY=${proxyUrl}`, - `ENABLE_CONNECTIVITY_CHECK=1` + `UPDATER_ONE_CONTAINER=1`, + `ENABLE_CONNECTIVITY_CHECK=${ + process.env.DEPENDABOT_ENABLE_CONNECTIVITY_CHECK || '1' + }` ], - User: 'root', Cmd: ['sh', '-c', cmd], HostConfig: { Memory: UPDATER_MAX_MEMORY, - NetworkMode: this.proxy.networkName, - Binds: [ - `${this.outputHostPath}:${JOB_OUTPUT_PATH}:rw`, - `${this.repoHostPath}:${REPO_CONTENTS_PATH}:rw` - ] + NetworkMode: this.proxy.networkName } }) @@ -80,7 +77,7 @@ export class UpdaterBuilder { this.input ) - core.info(`Created ${updaterCommand} container: ${container.id}`) + core.info(`Created container: ${container.id}`) return container } } diff --git a/src/updater.ts b/src/updater.ts index 35a0dc069..e705c9b3f 100644 --- a/src/updater.ts +++ b/src/updater.ts @@ -1,26 +1,12 @@ -import * as core from '@actions/core' import Docker, {Container} from 'dockerode' import path from 'path' import fs from 'fs' import {JobDetails, ApiClient, Credential} from './api-client' import {ContainerService} from './container-service' -import {base64DecodeDependencyFile} from './utils' -import { - DependencyFile, - FetchedFiles, - FileUpdaterInput, - FileFetcherInput -} from './config-types' +import {FileUpdaterInput, FileFetcherInput} from './config-types' import {ProxyBuilder, Proxy} from './proxy' import {UpdaterBuilder} from './updater-builder' -export class UpdaterFetchError extends Error { - constructor(msg: string) { - super(msg) - Object.setPrototypeOf(this, UpdaterFetchError.prototype) - } -} - export class Updater { docker: Docker outputHostPath: string @@ -45,79 +31,44 @@ export class Updater { async runUpdater(): Promise { // Create required folders in the workingDirectory fs.mkdirSync(this.outputHostPath) - fs.mkdirSync(this.repoHostPath) - const proxy = await new ProxyBuilder(this.docker, this.proxyImage).run( + const cachedMode = + this.details.experiments?.hasOwnProperty('proxy-cached') === true + + const proxyBuilder = new ProxyBuilder( + this.docker, + this.proxyImage, + cachedMode + ) + + const proxy = await proxyBuilder.run( this.apiClient.params.jobId, + this.apiClient.getJobToken(), + this.apiClient.params.dependabotApiUrl, this.credentials ) await proxy.container.start() try { - const files = await this.runFileFetcher(proxy) - await this.runFileUpdater(proxy, files) + await this.runUpdate(proxy) return true } finally { await this.cleanup(proxy) } } - private async runFileFetcher(proxy: Proxy): Promise { - const name = `dependabot-job-${this.apiClient.params.jobId}-file-fetcher` - const container = await this.createContainer(proxy, name, 'fetch_files', { + private async runUpdate(proxy: Proxy): Promise { + const name = `dependabot-job-${this.apiClient.params.jobId}` + const container = await this.createContainer(proxy, name, { job: this.details }) await ContainerService.run(container) - - const outputPath = path.join(this.outputHostPath, 'output.json') - if (!fs.existsSync(outputPath)) { - throw new UpdaterFetchError( - 'No output.json created by the fetcher container' - ) - } - - const fileFetcherSync = fs.readFileSync(outputPath).toString() - const fileFetcherOutput = JSON.parse(fileFetcherSync) - - const fetchedFiles: FetchedFiles = { - base_commit_sha: fileFetcherOutput.base_commit_sha, - base64_dependency_files: fileFetcherOutput.base64_dependency_files, - dependency_files: fileFetcherOutput.base64_dependency_files.map( - (file: DependencyFile) => base64DecodeDependencyFile(file) - ) - } - - return fetchedFiles - } - - private async runFileUpdater( - proxy: Proxy, - files: FetchedFiles - ): Promise { - core.info(`Running update job ${this.apiClient.params.jobId}`) - const name = `dependabot-job-${this.apiClient.params.jobId}-updater` - - const containerInput: FileUpdaterInput = { - base_commit_sha: files.base_commit_sha, - base64_dependency_files: files.base64_dependency_files, - dependency_files: files.dependency_files, - job: this.details - } - const container = await this.createContainer( - proxy, - name, - 'update_files', - containerInput - ) - - await ContainerService.run(container) } private async createContainer( proxy: Proxy, containerName: string, - updaterCommand: string, input: FileFetcherInput | FileUpdaterInput ): Promise { return new UpdaterBuilder( @@ -126,20 +77,19 @@ export class Updater { input, this.outputHostPath, proxy, - this.repoHostPath, this.updaterImage - ).run(containerName, updaterCommand) + ).run(containerName) } private async cleanup(proxy: Proxy): Promise { await proxy.shutdown() if (fs.existsSync(this.outputHostPath)) { - fs.rmdirSync(this.outputHostPath, {recursive: true}) + fs.rmSync(this.outputHostPath, {recursive: true}) } if (fs.existsSync(this.repoHostPath)) { - fs.rmdirSync(this.repoHostPath, {recursive: true}) + fs.rmSync(this.repoHostPath, {recursive: true}) } } }